{"text": "# Newton's method\n\nx0 = 1  # The initial guess\nf(x) = x^2 - 2  # The function whose root we are trying to find\nfprime(x) = 2 * x  # The derivative of the function\ntolerance = 10^(-7)  # 7 digit accuracy is desired\nepsilon = 10^(-14)  # Do not divide by a number smaller than this\nmaxIterations = 20  # Do not allow the iterations to continue indefinitely\nsolutionFound = false  # Have not converged to a solution yet\n\nfor i = 1:maxIterations\n  y = f(x0)\n  yprime = fprime(x0)\n \n  if abs(yprime) < epsilon  # Stop if the denominator is too small\n    break\n  end\n \n  global x1 = x0 - y/yprime  # Do Newton's computation\n \n  if abs(x1 - x0) <= tolerance  # Stop when the result is within the desired tolerance\n    global solutionFound = true\n    break\n  end\n \n  global x0 = x1  # Update x0 to start the process again\nend\n\nif solutionFound\n  println(\"Solution: \", x1)  # x1 is a solution within tolerance and maximum number of iterations\nelse\n  println(\"Did not converge\")  # Newton's method did not converge\nend", "meta": {"hexsha": "a2b757f78f439a22b96e2254067157dc0631f2e9", "size": 1008, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Code/Numerical Analysis & Machine Learning/Newton Method/NewtonMethod.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/Newton Method/NewtonMethod.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/Newton Method/NewtonMethod.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": 30.5454545455, "max_line_length": 97, "alphanum_fraction": 0.6994047619, "num_tokens": 294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341999997376, "lm_q2_score": 0.9407897471835636, "lm_q1q2_score": 0.8999916471649038}}
{"text": "# Regression Metrics\n\n\"\"\"\n    mae(y_pred, y_true)\n\nMean Absolute Error. Calculated as `sum(|y_true .- y_pred|) / length(y_true)` based on provided `y_pred` and `y_true`.\n\"\"\"\nfunction mae(y_pred, y_true)\n    @assert length(y_true) == length(y_pred)\n    return sum(abs.(y_true .- y_pred)) / length(y_true)\nend\n\n\"\"\"\n    mse(y_pred, y_true)\n\nMean Squared Error. Calculated as `sum((y_true .- y_pred).^2) / length(y_true)` based on provided `y_pred` and `y_true`.\n\"\"\"\nfunction mse(y_pred, y_true)\n    @assert length(y_true) == length(y_pred)\n    return sum((y_true .- y_pred).^2) / length(y_true)\nend\n\n\"\"\"\n    male(y_pred, y_true)\n\nMean Absolute Logarithmic Error. Calculated as `sum(|log.(y_true) .- log.(y_pred)|) / length(y_true)` based on provided `y_pred` and `y_true`.\n\"\"\"\nfunction male(y_pred, y_true)\n    @assert length(y_true) == length(y_pred)\n    epsilon = eps(eltype(y_pred)(1.0))\n    return sum(abs.(log.(y_true .+ epsilon) .- log.(y_pred .+ epsilon)))  / length(y_true)\nend\n\n\"\"\"\n    msle(y_pred, y_true)\n\nMean Absolute Logarithmic Error.\nCalculated as `sum((log.(y_true) .- log.(y_pred)).^2) / length(y_true)` based on provided `y_pred` and `y_true`.\n\"\"\"\nfunction msle(y_pred, y_true)\n    @assert length(y_true) == length(y_pred)\n    epsilon = eps(eltype(y_pred)(1.0))\n    return sum((log.(y_true .+ epsilon) .- log.(y_pred .+ epsilon)).^2)  / length(y_true)\nend\n\n\"\"\"\n    r2_score(y_pred, y_true)\n\nCalculates the r2 (Coefficient of Determination) score for the provided `y_pred` and `y_true`.\nBest possible score is 1.0 and it can be negative (because the model can be arbitrarily worse).\nA constant model that always predicts the expected value of y, disregarding the input features, would get a r2_score of `0.0`.\n\"\"\"\nfunction r2_score(y_pred, y_true)\n    @assert length(y_true) == length(y_pred)\n    ss_res = sum((y_true .- y_pred).^2)\n    mean = sum(y_true) / length(y_true)\n    ss_total = sum((y_true .- mean).^2)\n    return 1 - ss_res/(ss_total + eps(eltype(y_pred)))\nend\n\n\"\"\"\n    adjusted_r2_score(y_pred, y_true, n)\n\nModified version of `r2_score` that has been adjusted for the number of predictors in the model. Here the argument `n` is for the number of predictors(or independent variables in X). \n\nSee also: [`r2_score`](@ref)\n\"\"\"\nfunction adjusted_r2_score(y_pred, y_true, n)\t\t# n -> number of predictors(independent variables in X)\n    @assert length(y_true) == length(y_pred)\n    score = r2_score(y_pred, y_true)\n    epsilon = eps(eltype(y_pred)(1.0))\n    return 1 - ((1 - score) * (length(y_true) -1)) / abs(( length(y_true) - n - 1 + epsilon))\nend\n\n", "meta": {"hexsha": "490bc9fab397f95aff7604b964c5a5cfb4f43266", "size": 2575, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Regression.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/Regression.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/Regression.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.3333333333, "max_line_length": 183, "alphanum_fraction": 0.680776699, "num_tokens": 753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.970239908635611, "lm_q2_score": 0.9273633001635967, "lm_q1q2_score": 0.8997648836227468}}
{"text": "using NewtonsMethod\nusing Test\n\nusing LinearAlgebra, Statistics, Compat, ForwardDiff\n\n@testset \"NewtonsMethod.jl\" begin\n\n#This function has no root, it should return nothing  \nf1(x) = x^2+1 \nf1_prime(x) = 2*x \n  \n@test newtonroot(f1, f1_prime,x\u2080 = 0).root == nothing\n@test newtonroot(f1, x\u2080 = 0).root == nothing\n \n \n#Now, I will test some functions which I know the roots  \nf2(x) = (x - 1)^3\nf2_prime(x) = 3*((x-1)^2)\n  \nf3(x) = 4*x+5\nf3_prime(x) = 4\n  \nf4(x) = 5^x - 25  \nf4_prime(x) =  5^x * log(5)\n\n  \n@test newtonroot(f2, f2_prime,x\u2080 = 0).root \u2248 0.9999998643434097\n@test newtonroot(f2, x\u2080 = 0).root \u2248 0.9999998643434097\n\n  \n@test newtonroot(f3, f3_prime,x\u2080 = 0).root \u2248 -1.25\n@test newtonroot(f3, x\u2080 = 0).root \u2248 -1.25\n\n@test newtonroot(f4, f4_prime,x\u2080 = 0).root \u2248 2\n@test newtonroot(f4, x\u2080 = 0).root \u2248 2\n\n #Testing tolerance\n @test !(newtonroot(f2, f2_prime, x\u2080 = 0, tolerance = 1).root \u2248 0.9999998643434097)\n @test !(newtonroot(f2, x\u2080 = 0, tolerance = 1).root \u2248 0.9999998643434097)\n @test newtonroot(f2, f2_prime, x\u2080 = 0, tolerance = 1E-10).root \u2248 1 #with smaller tolerance, I can reach the \"exact\" number\n\n  \n #Testing BigFloat\n @test newtonroot(f2, f2_prime, x\u2080 = BigFloat(0.0), tolerance = 1E-40).root \u2248 1\n @test newtonroot(f2, x\u2080 = BigFloat(0.0), tolerance = 1E-40).root \u2248 1\n  \n #Testing if the maxiter works as intended\n   #Function 2\n   @test newtonroot(f2, f2_prime, x\u2080 = 0, maxiter = 10).root == nothing\n  @test newtonroot(f2, x\u2080 = 0, maxiter = 10).root == nothing\n  # Function 4\n   @test newtonroot(f4, f4_prime, x\u2080 = 0, maxiter = 10).root == nothing\n   @test newtonroot(f4,x\u2080 = 0, maxiter = 10).root == nothing\n   \nend\n", "meta": {"hexsha": "767d0238253e4e61b7b51ca8c1ff3afe0782c52b", "size": 1633, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "GAlbuquerque/NewtonsMethod.jl", "max_stars_repo_head_hexsha": "5397bd839ac70c44f687bb168c774fda4b8e902f", "max_stars_repo_licenses": ["MIT"], "max_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": "GAlbuquerque/NewtonsMethod.jl", "max_issues_repo_head_hexsha": "5397bd839ac70c44f687bb168c774fda4b8e902f", "max_issues_repo_licenses": ["MIT"], "max_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": "GAlbuquerque/NewtonsMethod.jl", "max_forks_repo_head_hexsha": "5397bd839ac70c44f687bb168c774fda4b8e902f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1607142857, "max_line_length": 123, "alphanum_fraction": 0.6638089406, "num_tokens": 662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813501370537, "lm_q2_score": 0.9372107874569682, "lm_q1q2_score": 0.8959560339561237}}
{"text": "using LinearAlgebra \nusing Statistics\nusing StatsBase\n\n\nfunction linear_regression(X, y) \n    Q, R = modified_gram_schmidt(X)\n    f = transpose(Q) * y \n    betas = backsolve(R, f)\n    return betas\nend \n\n\n# Helper Functions \n\nfunction back_substitute(U, y)\n    n, _ = size(U)\n    x = zeros(n)\n    for i in n:1 \n        x[i] = y[i]\n        for j in (i+1): n\n            x[i] = x[i] - U[i, j] * x[j]\n        end \n        x[i] = x[i] / U[i, i]\n    end \n    return x \nend \n\nfunction back_solve(A, b)\n    Q,R = modified_gram_schmidt(A)\n    y = tranpose(Q) * b \n    x = back_substitute(R, y)\n    return x\nend \n\n\nfunction classical_gram_schmidt(A)\n    m, n = size(A)\n    R = zeros(n, n)\n    Q = zeros(m, n)\n    for j in 1:n\n        v_j = A[:, j]\n        for i in 1:(j-1)\n            R[i, j] = dot(Q[:, i], A[:, j])\n            v_j = v_j - R[i, j] * Q[:, i]\n        end \n        R[j, j] = norm(v_j)\n        Q[:, j] = v_j / R[j, j]\n    end\n    return Q, R\nend \n\nfunction modified_gram_schmidt(A)\n    m, n = size(A)\n    R = zeros(Float64, n, n)\n    Q = zeros(Float64, m, n)\n\n    V = zeros(Float64, n, n)\n    for i in 1:n\n        V[:, i] = A[:, i]\n    end\n\n    for i in 1:n\n        R[i, i] = norm(V[:, i])\n        Q[:, i] = V[:, i] / R[i, i]\n        for j in (i+1):n\n            R[i, j] = dot(Q[:, i], V[:, j])\n            V[:, j] = V[:, j] - R[i, j] * Q[:, i]\n        end \n    end \n    return Q, R\nend \n\n\nfunction check_stability(Q)\n    m, n = size(Q)\n    total_dot_error = 0 \n    for i in 1:m\n        for j in 1:n \n            if i != j\n                total_dot_error += abs(dot(Q[:, i], Q[:, j]))\n            end \n        end \n    end \n    return total_dot_error\nend \n\nfunction boostrap_confint(X, y, bootstrap_samples)\n    n, d = size(X)\n    beta_arr = zeros(bootstrap_samples, d)\n\n    for i in 1:bootstrap_samples\n        sample_arr = sample(1:n,n) \n        sampled_X = X[sample_arr, :]\n        sampled_y = y[sample_arr]\n        beta_arr[i, :] = linear_regression(sampled_X, sampled_y)\n    end \n\n    betas = linear_regression(X,y)\n    confidence_intervals = zeros(n, 2)\n\n    for i in 1:n\n        beta_i = beta_arr[i, :]\n        beta_std = std(beta_i)\n        confidence_intervals[i, 1] = betas[i] - 1.96 * beta_std\n        confidence_intervals[i, 2] = betas[i] + 1.96 * beta_std\n\n    end \n    return confidence_intervals\nend \n\n\n# Very Simple Stability Analysis \n\nA = [1 2 3; 4 1 6; 7 8 1]\nQ, R = classical_gram_schmidt(A)\n\nclassical_error = check_stability(Q)\nQ, R = modified_gram_schmidt(A)\nmodified_error = check_stability(Q)\n\nerrror_ratios = classical_error / modified_error\nprintln(\"classical error $classical_error\")\nprintln(\"modified error $modified_error\")\nprintln(\"Error ratios: $errror_ratios\")\n\n", "meta": {"hexsha": "81881e61988fbd9c339287a360b8b667f56ea2c0", "size": 2699, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "multivariate_regression.jl", "max_stars_repo_name": "CornellDataScience/interpret-ml", "max_stars_repo_head_hexsha": "e8cd6d1fb1ccadf820c494c33ce2bedc2fd3bbef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "multivariate_regression.jl", "max_issues_repo_name": "CornellDataScience/interpret-ml", "max_issues_repo_head_hexsha": "e8cd6d1fb1ccadf820c494c33ce2bedc2fd3bbef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "multivariate_regression.jl", "max_forks_repo_name": "CornellDataScience/interpret-ml", "max_forks_repo_head_hexsha": "e8cd6d1fb1ccadf820c494c33ce2bedc2fd3bbef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.2519685039, "max_line_length": 64, "alphanum_fraction": 0.5390885513, "num_tokens": 876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995733060719, "lm_q2_score": 0.9273632981560942, "lm_q1q2_score": 0.895739813988683}}
{"text": "\"\"\"\n    factorial_iterative(n)\n\nFinds factorial of a number using Iterative method\n\n# Example\n```julia\nfactorial_iterative(5)      # returns 120\nfactorial_iterative(-1)     # returns error\n```\n# Reference\n- factorial of a positive integer -- https://en.wikipedia.org/wiki/Factorial\n\nContributed By:- [Ashwani Rathee](https://github.com/ashwani-rathee) and [Rratic](https://github.com/Rratic)\n\"\"\"\nfunction factorial_iterative(n::N) where {N<:Integer}\n    if n < 0\n        throw(\n            error(\n                \"factorial_iterative() only accepts non-negative integral values\",\n            ),\n        )\n    end\n    if n == 0 || n == 1\n        return one(BigInt)\n    end\n    return n * factorial_iterative(n - 1)\nend\n\n\"\"\"\n    factorial_recursive(n)\n\nFinds factorial of anumber using recursive method\n\n# Example\n```julia\nfactorial_recursive(5)      # returns 120\n```\n# Reference\n- factorial of a positive integer -- https://en.wikipedia.org/wiki/Factorial\n\nContributed By:- [Ashwani Rathee](https://github.com/ashwani-rathee) and [Rratic](https://github.com/Rratic)\n\"\"\"\nfunction factorial_recursive(n::N)::BigInt where {N<:Integer}\n    if n < 0\n        throw(\n            error(\n                \"factorial_iterative() only accepts non-negative integral values\",\n            ),\n        )\n    end\n    if n == 0 || n == 1\n        return one(BigInt)\n        # keep same result type\n    else\n        factorial = one(BigInt)\n        for i in 1:n\n            factorial *= i\n        end\n        return factorial\n    end\nend\n", "meta": {"hexsha": "cd5e5e7db6789fc523215b22cb8e1d4b54fd59f4", "size": 1516, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/factorial.jl", "max_stars_repo_name": "AugustoCL/Julia", "max_stars_repo_head_hexsha": "1bf4e4a7829fafc64290d903bcbfdd48eab839e7", "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/math/factorial.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/math/factorial.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.0634920635, "max_line_length": 108, "alphanum_fraction": 0.6160949868, "num_tokens": 401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750360641186, "lm_q2_score": 0.9390248135892422, "lm_q1q2_score": 0.895148913039387}}
{"text": "\"\"\"\n    collatz_sequence(n)\n\nCollatz conjecture: start with any positive integer n. The next term is\nobtained as follows:\n\tIf n term is even, the next term is: n / 2 .\n\tIf n is odd, the next term is: 3 * n + 1.\nThe conjecture states the sequence will always reach 1 for any starting value n.\n\"\"\"\n\nfunction collatz_sequence(n)\n\tsequence = [n]\n\twhile n != 1\n\t\tn = n % 2 == 1 ? 3 * n + 1 : div(n, 2)\n\t\tappend!(sequence, n)\n\tend\n\treturn sequence\nend\n", "meta": {"hexsha": "68758849d63924da23f047269912c34c4381d90b", "size": 446, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/collatz_sequence.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/collatz_sequence.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/collatz_sequence.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": 23.4736842105, "max_line_length": 80, "alphanum_fraction": 0.668161435, "num_tokens": 139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.974434786819155, "lm_q2_score": 0.9184802423517104, "lm_q1q2_score": 0.8949990991535948}}
{"text": "using NewtonsMethod\nusing Test\n\n@testset \"NewtonsMethod.jl\" begin\n    # Write your own tests here.\n\n# return back nothing if non-convergence: wrote in function\n\n# test of non-convergence\n\nf(x)=2+x^2\nf_prime(x)=2*x\nt1=newtonroot(f, f_prime; x_0=0, tolerance=1E-7, maxiter=1000)[1]\nt2=newtonroot1(f; x_0=0, tolerance=1E-7, maxiter=1000)[1]\n@test t1 == nothing\n@test t2 == nothing\n\n\n# root of a known function\nf(x)=x^2-2x+1\nf_prime(x)=2*x-2\nt3=newtonroot(f, f_prime; x_0=0, tolerance=1E-7, maxiter=1000)[1]\n@test t3 \u2248 1.0\n\n# automatic differentiation\nt4=newtonroot2(f; x_0=0, tolerance=1E-7, maxiter=1000)[1]\n@test t4 \u2248 1.0\n\n# finding those roots with a BigFloat\nt5=newtonroot(f, f_prime; x_0=BigFloat(x0), tolerance=1E-7, maxiter=1000)[1]\n@test t5 \u2248 1.0\n\n\n# several of above tests\n\nf(x)=x^2-2x\nf_prime(x)=2*x-2\n\nt3=newtonroot(f, f_prime; x_0=1.5, tolerance=1E-7, maxiter=1000)[1]\n@test t3 \u2248 2.0\nt4=newtonroot2(f; x_0=1.5, tolerance=1E-7, maxiter=1000)[1]\n@test t4 \u2248 2.0\nt5=newtonroot(f, f_prime; x_0=BigFloat(1.5), tolerance=1E-7, maxiter=1000)[1]\n@test t5 \u2248 2.0\n\n\nf(x)=x^2-3x+2\nf_prime(x)=2*x-3\n\nt3=newtonroot(f, f_prime; x_0=0, tolerance=1E-7, maxiter=1000)[1]\n@test t3 \u2248 1.0\nt4=newtonroot2(f; x_0=0, tolerance=1E-7, maxiter=1000)[1]\n@test t4 \u2248 1.0\nt5=newtonroot(f, f_prime; x_0=BigFloat(0), tolerance=1E-7, maxiter=1000)[1]\n@test t5 \u2248 1.0\n\n\n\n# ensure that the maxiter is working\nf(x)=x^2-2x+1\nf_prime(x)=2*x-2\n\nt6=newtonroot(f, f_prime; x_0=0, tolerance=1E-7, maxiter=5)[1]\n@test t6 == nothing\n\n\n# ensure that tol is working\nt7=newtonroot(f, f_prime; x_0=0, tolerance=1E-7, maxiter=1000)[2]\n@test t7 <= 1E-7\n\n\nend\n", "meta": {"hexsha": "280979a8a03e4c103f9e8881da71009faff5cd36", "size": 1615, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "Zining-Liu/NewtonsMethod.jl", "max_stars_repo_head_hexsha": "a8c59326fec4e1e6ca6dbe1a18d4675685a925d6", "max_stars_repo_licenses": ["MIT"], "max_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": "Zining-Liu/NewtonsMethod.jl", "max_issues_repo_head_hexsha": "a8c59326fec4e1e6ca6dbe1a18d4675685a925d6", "max_issues_repo_licenses": ["MIT"], "max_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": "Zining-Liu/NewtonsMethod.jl", "max_forks_repo_head_hexsha": "a8c59326fec4e1e6ca6dbe1a18d4675685a925d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.1232876712, "max_line_length": 77, "alphanum_fraction": 0.6941176471, "num_tokens": 715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959762052772658, "lm_q2_score": 0.9324533032291501, "lm_q1q2_score": 0.8949332964218548}}
{"text": "\"\"\"\n    simpsons_integration(f::Function, a::Real, b::Real, n::Int)\n\nSimpson's rule uses a quadratic polynomial on each subinterval of a partition to approximate the function f(x) and to compute the definite integral. \nThis is an improvement over the trapezoid rule which approximates f(x) by a straight line on each subinterval of a partition.\nFor more details of the method, check the link in the reference.\n\n# Arguments\n- `f`: The function to integrate. (ar the moment only single variable is suported)\n- `a`: Start of the integration limit.\n- `b`: End of the integration limit.\n- `n`: Number of points to sample. (as n increase, error decrease)\n\n# Examples/Test\n```julia\n# aproximate pi with f(x) = 4 / (1 + x^2)\njulia> simpsons_integration(x -> 4 / (1 + x^2), 0, 1, 100_000)\n3.1415926535897936\njulia> simpsons_integration(x -> 4 / (1 + x^2), 0, 1, 100_000) \u2248 pi\ntrue\n```\n\n# References:\n- https://personal.math.ubc.ca/~pwalls/math-python/integration/simpsons-rule/\n\n# Contributed By:- [AugustoCL](https://github.com/AugustoCL)\n\"\"\"\nfunction simpsons_integration(f::Function, a::Real, b::Real, n::Int)\n    # width of the segments\n    \u0394\u2093 = (b - a) / n\n    \n    # rules of the method (check link in references)\n    a\u2081(i) = 2i - 2\n    a\u2082(i) = 2i - 1\n\n    # sum of the heights\n    \u03a3 = sum(1:n/2) do i\n            f(a + a\u2081(i)*\u0394\u2093) + 4f(a + a\u2082(i)*\u0394\u2093) + f(a + 2i*\u0394\u2093)\n        end\n\n    # approximate integral of f\n    return (\u0394\u2093 / 3) * \u03a3\nend\n", "meta": {"hexsha": "f5c06dbce021d3f07a6cb45fee322c1e4ad1e9cd", "size": 1434, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/simpsons_integration.jl", "max_stars_repo_name": "frankschmitt/Julia", "max_stars_repo_head_hexsha": "c94cf524ad5d3221e05a4967fd088145d9c51a33", "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/simpsons_integration.jl", "max_issues_repo_name": "frankschmitt/Julia", "max_issues_repo_head_hexsha": "c94cf524ad5d3221e05a4967fd088145d9c51a33", "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/simpsons_integration.jl", "max_forks_repo_name": "frankschmitt/Julia", "max_forks_repo_head_hexsha": "c94cf524ad5d3221e05a4967fd088145d9c51a33", "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": 32.5909090909, "max_line_length": 149, "alphanum_fraction": 0.6631799163, "num_tokens": 469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9748211568364099, "lm_q2_score": 0.9173026607161, "lm_q1q2_score": 0.8942060408883854}}
{"text": "function calc_nchk(n::Int,k::Int)\n    #=\n    Calculate n choose k\n    =#\n    if n == 0 || k == 0\n\t\treturn 1\n\tend\n\n    #@myassert(n>=k)\n    accum::BigInt = 1\n    for i in 1:k\n        accum = accum * (n-k+i) \u00f7 i\n    end\n    return accum\nend\n\n\nfunction build_nchk_table(N)\n\tbinom_coeff = Array{BigInt,2}(undef,N+1,N+1)\n\tfor i in 0:N\n    \t\tfor j in i:N\n        \t\tbinom_coeff[j+1,i+1] = calc_nchk(j,i)\n    \t\tend\n    \tend\n\treturn binom_coeff\nend\n\n", "meta": {"hexsha": "eaa0403d201a9834de37d3a1f73e1071a57fad6d", "size": 441, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Tools.jl", "max_stars_repo_name": "nmayhall-vt/FermiCG", "max_stars_repo_head_hexsha": "acb3e5a4206b18be52a49eef328a8613e1a8a8cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-11-08T21:34:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T15:25:02.000Z", "max_issues_repo_path": "src/Tools.jl", "max_issues_repo_name": "nmayhall-vt/FermiCG", "max_issues_repo_head_hexsha": "acb3e5a4206b18be52a49eef328a8613e1a8a8cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 59, "max_issues_repo_issues_event_min_datetime": "2021-03-22T18:25:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T01:04:48.000Z", "max_forks_repo_path": "src/Tools.jl", "max_forks_repo_name": "nmayhall-vt/FermiCG", "max_forks_repo_head_hexsha": "acb3e5a4206b18be52a49eef328a8613e1a8a8cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-14T04:22:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T04:22:05.000Z", "avg_line_length": 15.75, "max_line_length": 47, "alphanum_fraction": 0.5532879819, "num_tokens": 161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.971129092218133, "lm_q2_score": 0.9207896807817187, "lm_q1q2_score": 0.894205646821375}}
{"text": "\"\"\"\n    bab_sqrt(S::Real; tolerance = 1e-6, guess = nothing)\n\nThe Babylonian Method of calculating a square root is a simple iterative method to determine square roots. A full description of the algorithm can be found on [Wikipedia](https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)\n\n# Arguments:\n- `S`: The number to calculate the square root for.\n\n# Positional Arguments\n- `tolerance`: How close the square of the square root needs to be from the input value. `abs(S - xn^2) < tolerance`\n- `guess`: The initial value to use for `xn`\n\n# Examples/Tests \n```julia\njulia> bab_sqrt(100)\n10.000000000107445\n\njulia> bab_sqrt(100, guess = 15)\n10.000000000131072\n\njulia> bab_sqrt(\u03c0, guess = 1)\n1.7724538555800293\n\njulia> bab_sqrt(\u03c0, guess = 1, tolerance = 2)\n2.0707963267948966\n```\n\n# Algorithm: \n\n```julia\nwhile tolerance <= abs(xn^2 - S)\n    xn = (1 / 2) * (xn + S / xn)\nend\n```\n\n# References:\n[Methods of computing square roots](https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)\n\n```\n\n# Contributed by:- [Anson Biggs](https://ansonbiggs.com) \n\"\"\"\nfunction bab_sqrt(S::Real; tolerance = 1e-6, guess = nothing)\n\n    # Can only calculate for positive numbers\n    if S < 0\n        throw(DomainError(\"Input must be greater than zero\"))\n    end\n\n    xn = guess\n    if xn === nothing\n        xn = S / 2\n    elseif xn < 0\n        xn = abs(xn)\n    end\n\n    while tolerance <= abs(xn^2 - S)\n        xn = (1 / 2) * (xn + S / xn)\n    end\n    return xn\n\nend\n", "meta": {"hexsha": "a54d35008e7f50ffc4b4661e7be253781f2df4e4", "size": 1507, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/babylonian_sqrt.jl", "max_stars_repo_name": "standardgalactic/Julia-algorithms", "max_stars_repo_head_hexsha": "9afacbb8941f543f2d7383ca6ae3a9c7eb86ba36", "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/babylonian_sqrt.jl", "max_issues_repo_name": "Seanpm2001-languages/Julia-1", "max_issues_repo_head_hexsha": "7ca5e16974418cba937395f1ba006042501f92c0", "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/babylonian_sqrt.jl", "max_forks_repo_name": "Seanpm2001-languages/Julia-1", "max_forks_repo_head_hexsha": "7ca5e16974418cba937395f1ba006042501f92c0", "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.9206349206, "max_line_length": 253, "alphanum_fraction": 0.6741871267, "num_tokens": 458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778048911612, "lm_q2_score": 0.933430805473952, "lm_q1q2_score": 0.8935525924818932}}
{"text": "\"\"\"\n    trapezoid_integration(f::Function, a::Real, b::Real, n::Int)\n\nThe trapezoidal rule works by approximating the region under the graph of the function f(x) as a trapezoid and calculating its area.\n\n# Arguments\n- `f`: the function to integrate. (at the momment only single variable is suported)\n- `a`: Start of the integration limit.\n- `b`: End of the integration limit.\n- `n`: Number of points to sample. (as n increase, error decrease)\n\n# Examples/Test\n```julia\njulia> trapezoid_integration(x -> 4 / (1 + x^2), 0, 1, 100_000)\n3.1415926535731526\njulia> trapezoid_integration(x -> 4 / (1 + x^2), 0, 1, 100_000) \u2248 pi\ntrue\n```\n# References:\n-https://personal.math.ubc.ca/~pwalls/math-python/integration/trapezoid-rule/\n-https://en.wikipedia.org/wiki/Trapezoidal_rule\n\n# Contributed By:- [AugustoCL](https://github.com/AugustoCL)\n\"\"\"\nfunction trapezoid_integration(f::Function, a::Real, b::Real, n::Int)\n    # width of the trapezoids\n    \u0394\u2093 = (b - a) / n\n\n    # sum of the height of the trapezoids\n    \u03a3 = 0.5 * f(a) + sum(f(i) for i in (a+\u0394\u2093):\u0394\u2093:(b-\u0394\u2093)) + 0.5 * f(b)\n\n    # approximate integral of f\n    return \u0394\u2093 * \u03a3\nend\n", "meta": {"hexsha": "044a199bf755ee3608286385fd502d5125b7289b", "size": 1125, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/trapezoid_integration.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/math/trapezoid_integration.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/math/trapezoid_integration.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": 32.1428571429, "max_line_length": 132, "alphanum_fraction": 0.6817777778, "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.97241471777321, "lm_q2_score": 0.9184802384467119, "lm_q1q2_score": 0.8931437018494299}}
{"text": "using Newtonsmethod\nusing Test\nusing LinearAlgebra\n\n# Testing the first function (unit test)\nf(x) = x^2-16.0\nf\u2032(x) = 2.0*x\n@test newtonroot(f,f\u2032;x\u2080=10.0)[1] \u2248 4.0 atol=0.00001\n\nf(x) = log(x)-1.0\nf\u2032(x) = 1/x\n@test newtonroot(f,f\u2032;x\u2080=3.0)[1] \u2248 2.71828182 atol=0.00001\n\nf(x) = exp(x) - 2.5\nf\u2032(x) = exp(x)\n@test newtonroot(f,f\u2032;x\u2080=10.0)[1] \u2248 0.9162907318741551 atol=0.00001\n\n# Testing the second function\nf(x) = x^2-16.0\n@test newtonroot(f;x\u2080=10.0)[1] \u2248 4.0 atol=0.00001\n\nf(x) = log(x)-1.0\n@test newtonroot(f;x\u2080=3.0)[1] \u2248 2.71828182 atol=0.00001\n\nf(x) = exp(x) - 2.5\n@test newtonroot(f;x\u2080=10.0)[1] \u2248 0.9162907318741551 atol=0.00001\n\n# Testing the BigFloat\nf(x) = exp(x) - 2.5\n@test newtonroot(f;x\u2080 = BigFloat(10.0), tolerance = BigFloat(1E-10), maxiter = BigFloat(1000))[1] \u2248 0.9162907318741551 atol=0.00001\n\n# Testing non-convergence\nf(x) = x^2+2.0\nf\u2032(x) = 2.0*x\n@test newtonroot(f,f\u2032;x\u2080=1.0) == nothing\n\n# Testing maxiter\nf(x) = exp(x) - 2.5\na=newtonroot(f;x\u2080=10.0)[1]\nb=newtonroot(f;x\u2080=10.0,maxiter=5)\n@testset \"maxiter\" begin\n    @test a \u2248 0.9162907318741551 atol=0.00001\n    @test b == nothing\nend;\n\n# Testing tolerance level\ng(x) = exp(x) - 2.5\nx\u2081 = newtonroot(g;x\u2080=10.0)[1]\nx\u2082 = newtonroot(g;x\u2080=10.0,tolerance=1E-3)[1]\nx\u2083 = newtonroot(g;x\u2080=10.0,tolerance=1)[1]\n@testset \"tolerance\" begin\n    @test norm(g(x\u2081)) < norm(g(x\u2082))\n    @test norm(g(x\u2081)) < norm(g(x\u2083))\n    @test norm(g(x\u2082)) < norm(g(x\u2083))\nend;\n\n# Give a fail test\n# g(x) = exp(x) - 2.5\n# @test newtonroot(g;x\u2080=1.0)[1] == 1.0\n", "meta": {"hexsha": "7f1c5af6e798853c7f4240e8aab24e801da54b0f", "size": 1485, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "Qirui-UBC/NewtonsMethod.jl", "max_stars_repo_head_hexsha": "ab5ceeb507f6b4864b1e31853ea3c3712523f442", "max_stars_repo_licenses": ["MIT"], "max_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": "Qirui-UBC/NewtonsMethod.jl", "max_issues_repo_head_hexsha": "ab5ceeb507f6b4864b1e31853ea3c3712523f442", "max_issues_repo_licenses": ["MIT"], "max_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": "Qirui-UBC/NewtonsMethod.jl", "max_forks_repo_head_hexsha": "ab5ceeb507f6b4864b1e31853ea3c3712523f442", "max_forks_repo_licenses": ["MIT"], "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": 131, "alphanum_fraction": 0.6363636364, "num_tokens": 699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741308615413, "lm_q2_score": 0.9372107931567176, "lm_q1q2_score": 0.892762756725316}}
{"text": "function ctrap(f::Function, a::Number, b::Number, n::Number)\n  #= Numerical integration of functions using the trapezium rule \n  Keyword Arguments:\n    f -- Anonymous function to integrate\n    a -- Lower limit of integration\n    b -- Upper limit of integration\n    n -- The number of sections to use in the calculation\n  =#\n  if n <= 0\n    error(\"n must be a positive integer\");\n  end\n  h = (b - a) / n;\n  0.5 * h * (f(a) + 2*sum(f([a+h:h:b-h])) + f(b));\nend\n\nfunction richardson(f::Function, a::Number, b::Number, n::Number, n2::Number)\n  #= Numerical integration of functions using Richardson's Method\n  Keyword Arguments:\n    f -- Anonymous function to integrate\n    a -- Lower limit of integration\n    b -- Upper limit of integration\n    n -- Number of intervals to use for 1st estimate\n    n2 -- Number of intervals to use for 2nd estimate.\n  =#\n\n  # Error checks\n  if n <= 0 || n2 <= 0\n    error(\"n and n2 must be positive integers.\");\n  end\n\n  if n == n2\n    error(\"n and n2 can't be equal.\");\n  end\n\n  I1, I2 = ctrap(f, a, b, n), ctrap(f, a, b, n2);\n  h1, h2 = (b - a) / n, (b - a) / n2;\n\n  I2 + ((I1 - I2) / (1 - (h1 / h2)^2));\nend\n\nfunction simpsonInt(f::Function, x1::Number, x2::Number, x3::Number)\n  #= Numerical integration of functions using Simpson's 1/3 Rule\n  \n  Keyword arguments:\n    f -- Function to integrate\n    x1 -- Lower limit of integration\n    x2 -- Midpoint of integral limits\n    x3 -- Upper limit of integration\n\n  Returns:\n    The results of \u222bf between x1 and x3\n  =#\n  (x3 - x1) * (1//6) * (f(x1) + 4*f(x2) + f(x3));\nend\n\nfunction simpsonInt(f::Function, x1::Number, xn::Number, n::Int)\n  #= Numerical integration using Simpson's Rule\n  \n  Will select the best method for integration depending on the number of data \n  points provided. If n is odd, Simpson's Composite 1/3 rule will be used. If\n  n is a multiple of 3, Simpson's composite 3/8 rule will be used.\n\n  Keyword arguments\n    f -- Function to integrate\n    x1 -- Lower limit of integration.\n    xn -- Upper limit of integration.\n    n -- Number of data points to use\n  \n  Returns\n    The results of \u222bf between x1 and xn.\n  =#\n  if n <= 1\n    error(\"Insufficient data points. Try increasing n.\");\n  elseif isodd(n)\n    simpsonOneThirdComposite(f, x1, xn, n);\n  elseif n%3 == 0\n    simpsonThreeEigthComposite(f, x1, xn, n);\n  else\n    error(\"Unusable number of data points. Make sure n is \u2265 1, odd or a multiple of 3.\");\n  end\nend\n\nfunction simpsonOneThirdComposite(f::Function, x1::Number, xn::Number, n::Int)\n  #= Numerical integration using Simpson's 1/3 Rule\n  \n  Keyword arguments:\n    f -- Function to integrate\n    x1 -- Lower limit of integration\n    xn -- Upper limit of integration\n    n -- Number of data points to use. **Must be odd**\n\n  Returns:\n    The results of \u222bf between x1 and xn\n  =#\n  if n%2 == 0\n    error(\"Must use an odd number of data points.\");\n  end \n  h = (xn - x1) / (n - 1);\n  (1//3) * h * (f(x1) + 4*(sum(f([x1+h:2h:xn-h]))) + 2*(sum(f([x1+2h:2h:xn-2h]))) + f(xn));\nend\n\nfunction simpsonThreeEigthComposite(f::Function, x1::Number, xn::Number, n::Int)\n  #= Numerical integration using Simpson's 3/8 rule\n\n  Keyword arguments:\n    f -- Function to integrate\n    x1 -- Lower limit of integration\n    xn -- Upper limit of integration\n    n -- Number of data points to use. **Must be a multiple of 3**.\n  \n  Returns:\n    The result of \u222bf between x1 and xn.\n  =#\n  if n%3 != 0\n    error(\"Must use a multiple of three data points\");\n  end\n  h = (xn - x1) / n;\n  (3//8) * h * (f(x1) + 3*sum(f([x1+h:3h:xn-2h])) + 3*sum(f([x1+2h:3h:xn-h])) + 2*sum(f([x1+3h:3h:xn-3h])) + f(xn));\nend\n", "meta": {"hexsha": "1e6e982ab0efe4429ded81ff70623ddcf7f26d58", "size": 3598, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/Integration/integration.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/Integration/integration.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/Integration/integration.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": 29.9833333333, "max_line_length": 116, "alphanum_fraction": 0.6311839911, "num_tokens": 1174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877700966098, "lm_q2_score": 0.9196425273235999, "lm_q1q2_score": 0.8926857541337557}}
{"text": "using Pkg\nPkg.activate(pwd())\n\n# # Julia package\n# ## Introduction\n\nusing DifferentialEquations\n\nf(u,p,t) = 0.98*u\n\nu0 = 1.0\ntspan = (0.0, 1.0)\n\n#+\n\nprob = ODEProblem(f, u0, tspan)\nsol = solve(prob)\n\n#+\n\nusing Plots\n\nplot(sol; label=\"\")\n\n#+\n\nsol(0.8)\n\n# ### Exercise:\n# \n# When calling the `solve` function, we can specify the interpolation way. Solve the ODE\n# with linear interpolation (`dense=false`) and the Runge-Kutta method of the fourth order \n# (`RK4()`). Plot the results and compare them with the default and original solutions.\n# \n# ---\n# ### Solution:\n\nsol2 = solve(prob, dense=false)\nsol3 = solve(prob, RK4())\n\n#+\n\nts = range(tspan...; length = 100)\n\nplot(ts, t->exp(0.98*t), label=\"True solution\", legend=:topleft);\nplot!(ts, t->sol(t), label=\"Default\");\nplot!(ts, t->sol2(t), label=\"Linear\");\nplot!(ts, t->sol3(t), label=\"Runge-Kutta\")\n\n# ---\n# \n# ## Lorenz system\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\n#+\n\nu0 = [1.0; 0.0; 0.0]\np = [10; 28; 8/3] \ntspan = (0.0, 100.0)\n\n#+\n\nprob = ODEProblem(lorenz, u0, tspan, p)\nsol = solve(prob)\n\n#+\n\nplot(sol)\n\n#+\n\nplt1 = plot(sol, vars=(1,2,3), label=\"\")\n\n#+\n\nplot(sol, vars=(1,2,3), denseplot=false; label=\"\")\n\n#+\n\ntraj = hcat(sol.u...)\nplot(traj[1,:], traj[2,:], traj[3,:]; label=\"\")\n\n# ### Exercise:\n# \n# Use the `nextfloat` function to perturb the first parameter of `p` by the smallest\n# possible value. Then solve the Lorenz system again and compare the results by plotting\n# the two trajectories next to each other.\n# \n# ---\n# ### Solution:\n\np0 = (nextfloat(p[1]), p[2:end]...) \n\n#+\n\nprob0 = ODEProblem(lorenz, u0, tspan, p0)\nsol0 = solve(prob0)\n\n#+\n\nplt0 = plot(sol0, vars=(1,2,3), label=\"\")\nplot(plt1, plt0; layout=(1,2))\n\n# ---\n\nhcat(sol(tspan[2]), sol0(tspan[2]))", "meta": {"hexsha": "4b13c325e5e20b35dcd9bc59ec8b213c7392f1a0", "size": 1847, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lecture_13/02-diffeq-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_13/02-diffeq-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_13/02-diffeq-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": 16.3451327434, "max_line_length": 91, "alphanum_fraction": 0.6015159718, "num_tokens": 666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422241476943, "lm_q2_score": 0.9381240099514927, "lm_q1q2_score": 0.8922893573516165}}
{"text": "\"\"\"\r\n    jacobi(A, B, Xawal)\r\nadalah fungsi yang digunakan untuk mencari solusi SPL `Ax=B` secara iteratif dengan\r\nnilai tebakan awal `Xawal` menggunakan metode jacobi.\r\n\r\n# Example\r\n```jl\r\njulia> A = [4 -1 1\r\n            4 -8 1\r\n           -2 1 5];\r\n\r\njulia> B = [7;-21;15];\r\n\r\njulia> Xa = [1,2,2];\r\n\r\njulia> X,flag,err,M = jacobi(A,B,Xa);\r\n\r\njulia> X\r\n3-element Array{Float64,1}:\r\n 1.9999999884128572\r\n 3.9999999907302857\r\n 3.0000000018539428\r\n\r\njulia> flag\r\n0\r\n\r\njulia> err\r\n3.777053140308286e-8\r\n\r\njulia> M\r\n18\u00d75 Array{Float64,2}:\r\n  0.0  1.0      2.0    2.0     NaN\r\n  1.0  1.75     3.375  3.0       1.85826\r\n  2.0  1.84375  3.875  3.025     0.509327\r\n  3.0  1.9625   3.925  2.9625    0.143205\r\n  \u22ee\r\n 14.0  2.0      4.0    3.0       1.00721e-6\r\n 15.0  2.0      4.0    3.0       2.83194e-7\r\n 16.0  2.0      4.0    3.0       1.37804e-7\r\n 17.0  2.0      4.0    3.0       3.77705e-8\r\n```\r\nreturn solusi `X` dengan `flag` bernilai 0 jika metode jacobi berhasil menemukan\r\nsolusi dan gagal jika tidak 0. Serta, matriks `M` yang berisi catatan proses tiap\r\niterasi `[k, X', error]`\r\n\"\"\"\r\nfunction jacobi(A, B, Xawal)\r\n    delta = 10^-7;\r\n    maxi = 100;\r\n    flag = 1;\r\n    D = Diagonal(diag(A))\r\n    R = A - D;\r\n    X = Xawal[:];\r\n    M = [0 X' NaN];\r\n    for k = 1:maxi\r\n        Xlama = X;\r\n        X = inv(D)*(B - R*Xlama);\r\n        err = norm(X-Xlama);\r\n        M = [M; [k X' err] ];\r\n        if err<delta || norm(B-A*X)<delta\r\n            flag = 0;\r\n            break\r\n        end\r\n    end\r\n    err = M[end,end]\r\n    return X, flag, err, M\r\nend\r\n", "meta": {"hexsha": "3ca4557bd251f4321dc7d1fb9fdd9e8b3c259e0b", "size": 1549, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/jacobi.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/jacobi.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/jacobi.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.1194029851, "max_line_length": 84, "alphanum_fraction": 0.5158166559, "num_tokens": 664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122696813392, "lm_q2_score": 0.9304582516374121, "lm_q1q2_score": 0.8912973756697241}}
{"text": "#= Frobenius Dot product\n   ---------------------\n\n1st method of calculation\n\na) element-wise multiplication between 2 matrices (which have the same size)\n\nb) Sum all elements\n=#\nFrb1(A,B) = reduce(+, (A .* B))\n\n#= 2nd method\n   ----------\na) Vectorise both matrices\nb) Compute vector dot product\n\nVectorising a Matrix\n--------------------\n\nCreate a vector from a matrix\n\ne.g. [a c e; b d f]\n\ngoes to [a b c d e f]' (column-wise concatenation)\n=#\nfunction Frb2(A,B)\n  va = A[:]\n  vb = B[:]\n  \n  return va .* vb\nend\n\n#=\n3rd way of Frobenius (most efficient)\n-------------------------------------\n\ntake the trace of A' * B\n=#\nFrb3(A,B) = tr(A' * B)\n\n#=\nFrobenius Norm\n--------------\n\nFrobenius dot product of matrix with itself\n=#\n\nFnorm(A) = sqrt(Frb3(A,A))\n\n# Implementation in code\n# ----------------------\nusing LinearAlgebra\n\nm = 9; n = 4;\n\nA = randn(m,n);\nB = randn(m,n);\n\nAv = A[:] # reshapes into a (mxn) x 1 column vector\n\nBv = B[:] # same for B\n\n## Ways of calculating Frobenius Dot Product\n\n# 1) Sum of Hadamard multiplication\nFrb1(A,B) = reduce(+, (A .* B))\n\n# 2) Dot product of vectorised matrices\nFrb2(A,B) = A[:] .* B[:]\n\n# 3) Trace of transposed A matrix multiplied by B matrix\nFrb3(A,B) = tr(A' * B)\n\n# Frobenius Norm aka Matrix Norm:\n# 1) square root of trace of (A' * A)\nFnorm1(A) = sqrt(Frb3(A,A))\n\n# 2) another way of doing Frobenius norm in Julia\nFnorm2(A) = norm(A, 2) \n", "meta": {"hexsha": "ffb703f4539e347662066d29685673ccf912f3fa", "size": 1391, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "linear-algebra-code-challenges/Lecture 59 - Frobenius Dot Product.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/Lecture 59 - Frobenius Dot Product.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/Lecture 59 - Frobenius Dot Product.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": 17.3875, "max_line_length": 76, "alphanum_fraction": 0.5866283249, "num_tokens": 441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9840936087546923, "lm_q2_score": 0.9046505254608136, "lm_q1q2_score": 0.8902608002625607}}
{"text": "#' ---\r\n#' title: Integer Programming\r\n#' ---\r\n\r\n#' **Originally Contributed by**: Arpit Bhatia\r\n\r\n#' While we already know how to set a variable as integer or binary in the `@variable` macro, \r\n#' this tutorial covers other JuMP features for integer programming along with some modelling techniques.\r\n\r\nusing JuMP\r\n\r\n#' ## Modelling Logical Conditions\r\n#' Generally, in a mathematical programming problem, all constraints must hold. \r\n#' However, we might want to have conditions where we have some logical conditions between constraints.\r\n#' In such cases, we can use binary variables for modelling logical conditions between constraints.\r\n\r\n#' ### Disjunctive Constraints (OR)\r\n#' Suppose that we are given two constraints $a'x \\geq b$ and $c' x \\geq d$, \r\n#' in which all components of $a$ and $c$ are non-negative. \r\n#' We would like to model a requirement that at least one of the two constraints is satisfied. \r\n#' For this, we defined a binary variable $y$ and impose the constraints:\r\n\r\n#' $$\r\n#' \\begin{align*}\r\n#' a' x \\geq y b \\\\\r\n#' c' x \\geq (1 - y) d \\\\\r\n#' y \\in \\{0,1\\}\r\n#' \\end{align*}\r\n#' $$\r\n\r\na = rand(1:100, 5, 5)\r\nc = rand(1:100, 5, 5)\r\nb = rand(1:100, 5)\r\nd = rand(1:100, 5)\r\n\r\nmodel = Model()\r\n@variable(model, x[1:5])\r\n@variable(model, y, Bin)\r\n@constraint(model, a * x .>= y .* b)\r\n@constraint(model, c * x .>= (1 - y) .* d);\r\n\r\n#' ### Conditional Constraints ($\\implies$)\r\n#' Suppose we want to model that a certain linear inequality must be satisfied when some other event occurs. \r\n#' i.e. for a binary variable $z$, we want to model the implication\r\n\r\n#' $$\r\n#' \\begin{align*}\r\n#' z = 1 \\implies a^Tx\\leq b\r\n#' \\end{align*}\r\n#' $$\r\n\r\n#' If we know in advance an upper bound $a^Tx\\leq b$. Then we can write the above as a linear inequality\r\n\r\n#' $$\r\n#' \\begin{align*}\r\n#' a^Tx\\leq b + M(1-z)\r\n#' \\end{align*}\r\n#' $$\r\n\r\na = rand(1:100, 5, 5)\r\nb = rand(1:100, 5)\r\nm = rand(10000:11000, 5)\r\n\r\nmodel = Model()\r\n@variable(model, x[1:5])\r\n@variable(model, z, Bin)\r\n@constraint(model, a * x .<=  b .+ (m .* (1 - z)));\r\n# If z was a regular Julia variable, we would not have had to use the vectorized dot operator\r\n\r\n#' ### Boolean Operators on Binary Variables\r\n#' The following table is useful when we want to model boolean operators in the form of \r\n#' linear inequalities that can be given to a solver.\r\n\r\n#' | Boolean Expression | Constraint                           | \r\n#' |:----------         |                           ----------:|\r\n#' | $z=x \\lor y$       | $x \\leq z,  y \\leq z,  z \\leq x+y$   |\r\n#' | $z=x \\land y$      | $x \\geq z,  y \\geq z,  z+1 \\geq x+y$ | \r\n#' | $z= \\neg x$        | $z = 1 \u2212 x$                          | \r\n#' | $x \\implies y$     | $x \\leq y$                           | \r\n#' | $x \\iff y$         | $x = y$                              | \r\n\r\n#' ## Modelling Integer Variables\r\n\r\n#' ### Integer Variables using Constraints\r\n#' We can add binary and integer restrictions to the domain of each variable using the `@constraint` macro as well.\r\n\r\nmodel = Model()\r\n\r\n@variable(model, x)\r\n@variable(model, y)\r\n@constraint(model, x in MOI.ZeroOne())\r\n@constraint(model, y in MOI.Integer());\r\n\r\n#' ### Semi-Continuous Variables\r\n#' A semi-continuous variable is a continuous variable \r\n#' between bounds $[l,u]$ that also can assume the value zero. ie.\r\n#' $$\r\n#' x \\in \\{0\\} \\cup \\{l,u\\}\r\n#' $$\r\n\r\nl = 7.45\r\nu = 22.22\r\n@variable(model, a)\r\n@constraint(model, a in MOI.Semicontinuous(l, u))\r\n\r\n#' ### Semi-Integer Variables\r\n#' A semi-integer variable is a variable which asummes integer values\r\n#' between bounds $[l,u]$ and can also assume the value zero. ie.\r\n\r\n#' $$\r\n#' x \\in \\{0\\} \\cup (\\{l,u\\} \\cap \\mathbb{Z})\r\n#' $$\r\n\r\nl = 5\r\nu = 34\r\n@variable(model, b)\r\n@constraint(model, b in MOI.Semiinteger(l, u))\r\n\r\n#' Note that the bounds specified in `MOI.Semiinteger` must be integral otherwise it would throw an error.\r\n\r\n#' ## Special Ordered Sets\r\n\r\n#' ### Special Ordered Sets of type 1 (SOS1)\r\n#' A Special Ordered Set of type 1 is a set of variables, \r\n#' at most one of which can take a non-zero value, all others being at 0. \r\n#' They most frequently apply where a set of variables are actually 0-1 variables: \r\n#' in other words, we have to choose at most one from a set of possibilities.\r\n\r\n@variable(model, u[1:3])\r\n@constraint(model, u in MOI.SOS1([1.0, 2.0, 3.0]))\r\n\r\n#' Note that we have to pass MOI.SOS1 a weight vector which is essentially an ordering on the variables. \r\n#' If the decision variables are related and have a physical ordering, then the weight vector, \r\n#' although not used directly in the constraint, can help the solver make a better decision in the solution process.\r\n\r\n#' ### Special Ordered Sets of type 2 (SOS2)\r\n\r\n#' A Special Ordered Set of type 2 is a set of non-negative variables, \r\n#' of which at most two can be non-zero, and if two are non-zero these must be consecutive in their ordering.\r\n\r\n@variable(model, v[1:3])\r\n@constraint(model, v in MOI.SOS2([3.0, 1.0, 2.0]))\r\n\r\n#' The ordering provided by the weight vector is more important in this case as \r\n#' the variables need to be consecutive according to the ordering.\r\n#' For example, in the above constraint, the possible pairs are:\r\n#' * Consecutive\r\n#'   * (`x[1]` and `x[3]`) as they correspond to 3 and 2 resp. and thus can be non-zero \r\n#'   * (`x[2]` and `x[3]`) as they correspond to 1 and 2 resp. and thus can be non-zero \r\n#' * Non-consecutive\r\n#'   * (`x[1]` and `x[2]`) as they correspond to 3 and 1 resp. and thus cannot be non-zero", "meta": {"hexsha": "b33b258416eea2704a131321eca99fd7474c587f", "size": 5496, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/optimization_concepts/integer_programming.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/optimization_concepts/integer_programming.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/optimization_concepts/integer_programming.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": 36.3973509934, "max_line_length": 117, "alphanum_fraction": 0.624636099, "num_tokens": 1561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620550745211, "lm_q2_score": 0.9273632951448401, "lm_q1q2_score": 0.8900481019488913}}
{"text": "# Fourier Transform and visualization of which\r\n\r\nusing Plots\r\n# idk why I just like to load plot function first\r\n# - weired isn't it\r\ngr()\r\n# rotation factor\r\n\r\nW_rotate(N::Int)=exp(-2*im*\u03c0/N)\r\n\r\nW_rotate.(1:10)\r\nplot(1:100,W_rotate.(1:100))#takes long if runned for the 1st time\r\nplot(W_rotate.(1:100))#\r\n\r\n#Amplitute can be calcd with abs(x::Complex)\r\nabs(1+im)\r\n\r\n\r\n# DFT and visualization\r\n\r\n\r\nfunction dft(x::Array)\r\n    n = length(x)\r\n    r = Array{Any,1}(missing,n)\r\n    #Note how sum is used to aggregate results after broadcasting\r\n    for i in 1:n\r\n        r[i]=sum(x.*exp(1).^(-(i-1)*collect(0:(n-1)).*(2*\u03c0*im/n)))\r\n    end\r\n    return(r)\r\nend\r\n\r\nx=1:.1:2\u03c0\r\ny =sin.(x)\r\nplot(x,y)\r\nplot(1:length(x),dft(y))\r\nplot(1:length(x),abs.(dft(y)))\r\nplot(1:length(x),real.(dft(y)))\r\n# FFT and visualization of FFT\r\n\r\n\r\nfunction idft(x::Array)\r\n    n = length(x)\r\n    r = Array{Any,1}(missing,n)\r\n    #Note how sum is used to aggregate results after broadcasting\r\n    for i in 1:n\r\n        r[i]=sum(x.*exp(1).^(+(i-1)*collect(0:(n-1)).*(2*\u03c0*im/n)))#change - to+\r\n    end\r\n    return(r)\r\nend\r\n\r\n#below inspired by\r\n#https://www.mathworks.com/matlabcentral/answers/3187-fft-recursive-code-problem\r\n\r\n\r\nfunction p2_fft_rec(f)\r\n  n = length(f)\r\n  if (n == 1)\r\n    return(f)\r\n  else\r\n    a= p2_fft_rec(f[1:2:n])\r\n    b= p2_fft_rec(f[2:2:n]).*exp(1).^(-2/n*\u03c0*im.*collect(0:1:(n/2)-1))\r\n    return append!(a+b,a-b)\r\n  end\r\nend\r\n\r\n\r\nfunction p2_fft(x)\r\n  n = length(x)\r\n  N = 2^(ceil(log2(n)))\r\n  x = append!(x,repeat([0],Int64(N - n)))\r\n  return(p2_fft_rec(x)[1:n])\r\nend\r\n\r\n\r\n\r\n#p2_fft(collect(1:4))\r\n#inspired by\r\n#https://in.mathworks.com/help/signal/ug/power-spectral-density-estimates-using-fft.html\r\n\r\nfunction p2_psd_fft(x)\r\n  N = length(x)\r\n  xdft = p2_fft(x)[1:Int(N/2+1)]\r\n  psdx = (1/N/N) * abs.(xdft).^2\r\n  psdx[2:end] = 2*psdx[2:end]\r\n  freq = 0:1:(N/2)\r\n  return(Dict(\"freq\"=>freq,\"psdx\"=>psdx,\"psd_est\"=>10*log10.(psdx)))\r\nend\r\n", "meta": {"hexsha": "abb4842a0f39b473d25fe7833de52da6476a8277", "size": 1935, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Fourier Transform and power spectral.jl", "max_stars_repo_name": "HaoLi111/Julia_Numerical_Recipe", "max_stars_repo_head_hexsha": "d887ee783bfc6e4efc1b4f748c19a21baef5d654", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-06-27T05:52:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-05T04:55:37.000Z", "max_issues_repo_path": "Fourier Transform and power spectral.jl", "max_issues_repo_name": "HaoLi111/Julia_Numerical_Recipe", "max_issues_repo_head_hexsha": "d887ee783bfc6e4efc1b4f748c19a21baef5d654", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Fourier Transform and power spectral.jl", "max_forks_repo_name": "HaoLi111/Julia_Numerical_Recipe", "max_forks_repo_head_hexsha": "d887ee783bfc6e4efc1b4f748c19a21baef5d654", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.9886363636, "max_line_length": 89, "alphanum_fraction": 0.6010335917, "num_tokens": 684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811591688145, "lm_q2_score": 0.9219218412907381, "lm_q1q2_score": 0.8900059758083005}}
{"text": "\n\"\"\"\n\n                newtonroot(f[, f']; x0 = 0.8, tolerance = 1.e-13, maxiter = 1000)\n\n\nThis function computes the local root of a univariate smooth function `f(x)` using the Newton's Method. This method starts with a  `x_0` guess, a function `f(x)` and the first-derivative  `f'(x)`. The algorithm follows: `` x^{n+1} = x^n - f(x^n)/f'(x^n) `` until `` |x^{n+1} - x^n|`` is below the tolerance level.\n \n...\n# Arguments\n- `f(x)::Function`: the function you are trying to solve.\n- `f'(x)::Function`: the first derivative of the function you are trying to solve. If it is not given the program estimate `f'(x)` using ForwardDiff.\n- `x0::Float64`: the initial value for the algorithm. The default value is 0.8.\n- `tolerance::Float64` : the minimum tolerance for the algorithm to converge. The default value is 1.0e-13.\n- `maxiter::Int64`: the maximum number of iterations allowed. The default value is 1000.\n---\n# Examples\n```julia-repl\njulia> f(x)  =  (x - 2)^2\nf (generic function with 1 method)\n\njulia> df(x) = 2(x - 2)\ndf (generic function with 1 method)\n\njulia> newtonroot(f,df)\n(value = 1.9999999999999318, normdiff = 6.816769371198461e-14, iter = 45)\n\njulia> a = newtonroot(f)[1]\n1.9999999999999318\n\njulia> newtonroot(f)[1] \u2248 2\ntrue\n```\n...\n\n\"\"\"\nfunction newtonroot(f, f_prime; x0=0.8, tolerance=1.0E-13, maxiter=1000)\n    # Initial values\n    v_old = x0\n    normdiff = Inf\n    iter = 1\n    \n    # Running the algorithm \n    while (normdiff > tolerance)  && (iter < maxiter)\n        if !(f_prime(v_old) == 0)\n            v_new = v_old - (f(v_old) / f_prime(v_old))\n            normdiff = norm(v_new - v_old)\n            # replace and continue\n            v_old = v_new\n            iter = iter + 1\n        else\n            return(value = nothing, normdiff = nothing, iter = nothing)\n        end\n    end\n    if (iter < maxiter)\n        return(value = v_old, normdiff = normdiff, iter = iter)\n    else\n        return(value = nothing, normdiff = nothing, iter = nothing)\n    end\nend\n\nfunction newtonroot(f; x0=0.8, tolerance=1.0E-13, maxiter=1000)\n    # Initial values\n    v_old = x0\n    normdiff = Inf\n    iter = 1\n    \n    # Taking the derivative\n    D(f) = x -> ForwardDiff.derivative(f, x)\n    f_prime = D(f)\n\n    # Running the algorithm \n\n    while (normdiff > tolerance)  && (iter < maxiter)\n        if !(f_prime(v_old) == 0)\n            v_new = v_old - (f(v_old) / f_prime(v_old))\n            normdiff = norm(v_new - v_old)\n            # replace and continue\n            v_old = v_new\n            iter = iter + 1\n        else\n            return(value = nothing, normdiff = nothing, iter = nothing)\n        end\n    end\n    if (iter < maxiter)\n        return(value = v_old, normdiff = normdiff, iter = iter)\n    else\n        return(value = nothing, normdiff = nothing, iter = nothing)\n    end\nend\n", "meta": {"hexsha": "32b899f329e929c7015fb3651149e9707e8175a0", "size": 2804, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/newtonroot.jl", "max_stars_repo_name": "pvalenzuelac/NewtonsMethod.jl", "max_stars_repo_head_hexsha": "73de7f9c485850875238eb976e6ce1bf7fad12b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/newtonroot.jl", "max_issues_repo_name": "pvalenzuelac/NewtonsMethod.jl", "max_issues_repo_head_hexsha": "73de7f9c485850875238eb976e6ce1bf7fad12b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-21T01:09:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-21T01:09:13.000Z", "max_forks_repo_path": "src/newtonroot.jl", "max_forks_repo_name": "pvalenzuelac/NewtonsMethod.jl", "max_forks_repo_head_hexsha": "73de7f9c485850875238eb976e6ce1bf7fad12b2", "max_forks_repo_licenses": ["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.8131868132, "max_line_length": 313, "alphanum_fraction": 0.6055634807, "num_tokens": 857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.970239909496136, "lm_q2_score": 0.9173026646724284, "lm_q1q2_score": 0.8900036543523413}}
{"text": "# # Poisson Equation\n#\n# $$\n# \\frac{\\partial^2 u}{\\partial x^2} = b  \\qquad x \\in [0,1]\n# $$\n#\n# $$\n# u(0) = u(1) = 0, \\qquad b = \\sin(2\\pi x)\n# $$\n\nusing Plots, SparseArrays\n\n\n\u0394x = 0.05\nx = \u0394x:\u0394x:1-\u0394x ## Solve only interior points: the endpoints are set to zero.\nn = length(x)\nB = sin.(2\u03c0*x) * \u0394x^2\n\nP = spdiagm( -1 =>    ones(Float64,n-1),\n              0 => -2*ones(Float64,n),\n              1 =>    ones(Float64,n-1))\n\nu1 = P \\ B\n\n# ---\n\nplot([0;x;1],[0;u1;0], label=\"computed\")\nscatter!([0;x;1],-sin.(2\u03c0*[0;x;1])/(4\u03c0^2),label=\"exact\")\nsavefig(\"poisson1.png\"); nothing #hide\n\n# ![](poisson1.png)\n\n# ---\n\n# # DiffEqOperators.jl\n\nusing DiffEqOperators\n\n\u0394x = 0.05\nx = \u0394x:\u0394x:1-\u0394x ## Solve only interior points: the endpoints are set to zero.\nn = length(x)\nb = sin.(2\u03c0*x) \n\n## Second order approximation to the second derivative\norder = 2\nderiv = 2\n\n\u0394 = CenteredDifference{Float64}(deriv, order, \u0394x, n)\nbc = Dirichlet0BC(Float64)\n\nu2 = (\u0394 * bc) \\ b\n\n# ---\n\nplot([0;x;1],[0;u2;0], label=\"computed\")\nscatter!([0;x;1],-sin.(2\u03c0*[0;x;1])/(4\u03c0^2),label=\"exact\")\nsavefig(\"poisson2.png\"); nothing #hide\n\n# ![](poisson2.png)\n\n# ---\n", "meta": {"hexsha": "4f3371ea170b5ffa2ab1084ebea078fbed9ac436", "size": 1121, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/03.PoissonEquation.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/03.PoissonEquation.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/03.PoissonEquation.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.0806451613, "max_line_length": 76, "alphanum_fraction": 0.5753791258, "num_tokens": 454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620608291781, "lm_q2_score": 0.9263037236819582, "lm_q1q2_score": 0.8890311707947378}}
{"text": "# Test transforms.jl\nusing Test, LinearAlgebra\n\nprintln(\"testing transforms\")\n\ntol = 1e-10\n\n# rotx, roty, rotz, invrpy\nroll = 0.3\npitch = -1.0\nyaw = 0.8\nT = rotz(yaw)*roty(pitch)*rotx(roll)\n\n(rpy1, rpy2) = invrpy(T)\n\n# Check 1st solution matches roll pitch and yaw\n@test abs(rpy1[1]-yaw) < tol\n@test abs(rpy1[2]-pitch) < tol\n@test abs(rpy1[3]-roll) < tol\n\n# Check 2nd solution produces the same transform\nT2 = rotz(rpy2[1])*roty(rpy2[2])*rotx(rpy2[3])\n@test maximum(abs.(T2-T)) < tol\n\n# inveuler\nphi = 0.5\ntheta = -0.2\npsi = 0.1\nT = rotz(phi) * roty(theta) * rotz(psi)     \n(euler1, euler2) = inveuler(T)\n\n# Check both solutions produce the same transform\nT1 = rotz(euler1[1])*roty(euler1[2])*rotz(euler1[3])\n@test maximum(abs.(T1-T)) < tol\n\nT2 = rotz(euler2[1])*roty(euler2[2])*rotz(euler2[3])\n@test maximum(abs.(T2-T)) < tol\n\n# invht\nv = [1,-2,3]\nT = rotz(yaw)*roty(pitch)*rotx(roll) * trans(v)\n\n@test maximum(abs.(invht(T)*T - I)) < tol\n@test maximum(abs.(trans(v) - trans(v[1],v[2],v[3]))) < tol\n\n# angleaxis, angleaxis2matrix, matrix2angleaxis\n# matrix2quaternion, quaternion2matrix\nT1 = rotz(yaw)*roty(pitch)*rotx(roll)\nax = matrix2angleaxis(T1)\nT2 = angleaxis2matrix(ax)\n@test maximum(abs.(T2-T1)) < tol\n\ntheta = 0.35\naxis = T1[1:3,1]\nax = angleaxis(theta, axis)\nQ = quaternion(theta,axis)\n\nT1 = quaternion2matrix(Q)\nT2 = angleaxis2matrix(ax)\n@test maximum(abs.(T2-T1)) < tol\n\nQ2 = matrix2quaternion(T1)\n@test maximum(abs.(Q-Q2)) < tol\n\n# angleaxisrotate, quaternionrotate\nax = angleaxis(theta, [1,0,0])\nQ = quaternion(theta, [1,0,0])\nv = [3,-2,7,1]\nvnew1 = quaternionrotate(Q,v)\nvnew2 = angleaxisrotate(ax,v)\nvnew3 = rotx(theta)*v\n\n@test maximum(abs.(vnew3-vnew1)) < tol\n@test maximum(abs.(vnew3-vnew2)) < tol\n\n# quaternionconjugate, quaternionproduct, \n# vector2quaternion\n", "meta": {"hexsha": "c904b517a68a1112d14f8a1bdc45ffde6a6952db", "size": 1782, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_transforms.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_transforms.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_transforms.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.8461538462, "max_line_length": 59, "alphanum_fraction": 0.6801346801, "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191348157373, "lm_q2_score": 0.9294404096760998, "lm_q1q2_score": 0.8879122080345561}}
{"text": "function compute_s(n)\n    sn = 0\n    for i = 1:n\n        sn += 1/i\n    end\n    sn\nend\n\ncompute_s(100)\n\nfor x = 1:2:20      # Steps of 2 - only odd values x\n    print(x, \" \")\nend\n\nfor x = 1:0.2:5     # Non-integers are ok\n    print(x, \" \")\nend\n\nfor x = 10:-1:-5    # Use a negative step to count down\n    print(x, \" \")\nend\n\nfor x = 10:2:5      # No repetitions since start > stop and step is positive\n    print(x, \" \")\nend\n\nfunction my_factorial(n)\n    y = 1\n    for i = 2:n\n        y *= i\n    end\n    y\nend\n\nmy_factorial(5)\n\nmy_factorial(20)     # This is OK\n\nmy_factorial(30)     # Too large - overflow\n\nmy_factorial(Int128(30))\n\nfactorial(30)\n\nfunction taylor_cos_bad(x,n)\n    y = 0\n    for k = 0:n\n        y += (-1)^k / factorial(2k) * x^2k\n    end\n    y\nend\n\n# x = 0.25, excellent approximation of degree 4\nprintln(taylor_cos_bad(0.25, 2))  # Taylor approximation\nprintln(cos(0.25))                # true value\n\n# x = 10, very poor approximation of degree 4\nprintln(taylor_cos_bad(10, 2))  # Taylor approximation\nprintln(cos(10))                # true value\n\n# x = 10, try approximation of degree 30\nprintln(taylor_cos_bad(10, 15)) # Taylor approximation\nprintln(cos(10))                # true value\n\nfunction taylor_cos(x,n)\n    term = 1\n    y = 1\n    for k = 1:n\n        term *= -x^2 / ((2k-1) * 2k)\n        y += term\n    end\n    y\nend\n\n# x = 10, try approximation of degree 30\nprintln(taylor_cos(10, 15)) # Taylor approximation\nprintln(cos(10))            # true value\n\n# x = 10, try approximation of degree 100\nprintln(taylor_cos(10, 50)) # Taylor approximation\nprintln(cos(10))            # true value\n\nx = 10\ny = 10\n\nfor i = 1:5\n    z = i        # Local scope, only visible inside for-loop\n    x = z        # Using x from parent scope\n    local y = z  # Local scope, only visible inside for-loop (not using y from parent scope)\nend\n\nprintln(x)    #  = 5, since for loop modifies parent variable x\nprintln(y)    #  = 10, since for loop uses local variable y\nprintln(z)    # Error: z only defined in the local scope of the for-loop\n", "meta": {"hexsha": "05df8d031a87cfd18c2c3b812dcdb05849c1242f", "size": 2040, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "textbook/_build/jupyter_execute/content/Introduction/For_Loops.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/For_Loops.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/For_Loops.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.4736842105, "max_line_length": 92, "alphanum_fraction": 0.5990196078, "num_tokens": 659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741281688026, "lm_q2_score": 0.9314625098218848, "lm_q1q2_score": 0.8872870882155067}}
{"text": "### A Pluto.jl notebook ###\n# v0.16.0\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 9d2617c5-ebf2-46c8-910f-190ba1d160ac\nusing BenchmarkTools\n\n# \u2554\u2550\u2561 89196053-24db-4013-a1e3-3d3b22c4eedc\nusing Combinatorics\n\n# \u2554\u2550\u2561 27547863-22e1-466e-951e-2a5677bb9501\nusing IterTools\n\n# \u2554\u2550\u2561 bade5453-0522-4cbc-8200-78ec160f1192\nusing ConstraintSolver, JuMP\n\n# \u2554\u2550\u2561 568f057a-126d-11ec-23cb-f98bea4a534f\nmd\"# Project Euler 1\n\nIf we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.\n\nFind the sum of all the multiples of 3 or 5 below 1000.\n\n\"\n\n# \u2554\u2550\u2561 daad198c-10c8-4e4c-93c4-d330ab22f3dd\nnaive1(x)=sum([i for i in 1:(x-1) if i%3==0 || i%5==0])\n\n# \u2554\u2550\u2561 2cca4797-d1ee-4c27-8243-736e3e468dd1\nnaive1(1000)\n\n# \u2554\u2550\u2561 6b82e993-2f3d-4d5c-8709-57050c7211de\nsumRange(i,j) = (j-i+1)*(i+j)/2\n\n# \u2554\u2550\u2561 382a2b3a-4059-4cbe-8485-b0ecce99c451\nsumRange(1,10)\n\n# \u2554\u2550\u2561 e59e2718-acc6-4a98-8ec9-61cf0a375f90\nmd\"We can also solve it with the inclusion-exclusion principle\"\n\n# \u2554\u2550\u2561 f7acd079-f79b-4967-a9ee-fc4965e2a06c\ninclusionExclusionPrincipleProb1(n) = begin \n\tk=n-1\n\tsumRange(1,floor(k/3))*3+sumRange(1,floor(k/5))*5-sumRange(1,floor(k/15))*15\nend\n\n# \u2554\u2550\u2561 c118a05d-d1bb-4767-9f3a-0b5cefd69d47\ninclusionExclusionPrincipleProb1(1000)\n\n# \u2554\u2550\u2561 078cb436-e238-4a69-bde6-156624db601b\n@benchmark sum(1:1000000)\n\n# \u2554\u2550\u2561 cea0b9f0-b908-4c33-8a5d-6a3019cfa47a\n@benchmark sumRange(1,1000000)\n\n# \u2554\u2550\u2561 07d10397-f053-45e0-ab2b-6565c18db5a2\n@benchmark inclusionExclusionPrincipleProb1(10000)\n\n# \u2554\u2550\u2561 464e87db-a12f-4e8b-a03a-ae1f943a42d0\n@benchmark naive1(10000)\n\n# \u2554\u2550\u2561 e323b98a-47a7-4182-9892-4d0b1891e295\nmd\" so we can see we have about $(6.380*10^(-6)/(0.021*10^(-9))) speed-up\"\n\n# \u2554\u2550\u2561 82baf161-7a98-4bb5-a928-b2273e4360cb\nmd\"We can also do it for a general problem with the inclusion- exclusion principle as follows:\n\"\n\n# \u2554\u2550\u2561 c7667675-8018-40f5-a1d9-8756f29466e0\nprod([1,2,3])\n\n# \u2554\u2550\u2561 ed4ded6b-925a-46e7-bcab-0cf0dc0fe80a\ninclusionExclusionSumUpTo(n,multiples) = begin\n\tk=n-1\n\tres = 0\n\tfor comb in combinations(multiples)\n\t\tpcomb=prod(comb)\n\t\tres += (-1)^(length(comb)-1)* sumRange(1,floor(k/pcomb))*pcomb\n\tend\n\tres\nend\n\n# \u2554\u2550\u2561 fa4d516c-74ea-44cb-bc18-e2b6cde80515\ninclusionExclusionSumUpTo(1000,[3,5])\n\n# \u2554\u2550\u2561 120de079-e8e5-40b3-9582-c3741cf024cb\n@benchmark inclusionExclusionSumUpTo(100000,[3,5,7,11,13])\n\n# \u2554\u2550\u2561 6ea414f8-d5bb-4432-9afb-6d2b2cfd1d01\nmd\"We can see it's pretty fast...\"\n\n# \u2554\u2550\u2561 6d793a48-b48e-4547-ac87-c23a1b03de9c\nmd\" # Problem 2\nEach new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:\n\n1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...\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\n\"\n\n# \u2554\u2550\u2561 e0470dad-e1ab-4603-85d0-e165f80c2463\nmd\"Copy some fibonacci channel code from [this blog post about lazy sequences](https://www.oxinabox.net/2017/11/18/Lazy-Sequences-in-Julia.html)\"\n\n# \u2554\u2550\u2561 c6a079d7-2773-41ba-81c8-773efaabd010\nfunction fib_ch(buff=1)\n    prev=0\n    cur=1\n    Channel(ctype=Int, csize=buff) do c\n        while(true)\n            put!(c, cur)\n            prev, cur = (cur, prev+cur) # nice little avoiding a temp here\n        end\n    end\nend\n\n# \u2554\u2550\u2561 61d320a0-2f4f-4cf4-b800-20bb77560c17\n\n\n# \u2554\u2550\u2561 2eb91ffc-799d-496e-8b50-6be2d497beaa\nsum([x for x in collect(IterTools.takewhile(x->x<=4_000_000,fib_ch(100))) if x%2==0])\n\n# \u2554\u2550\u2561 5e201d20-3600-4b21-a764-8dd1e89cdf66\nmd\" It's also quite fast!\"\n\n# \u2554\u2550\u2561 6678078e-f30c-4e5e-8de5-f697d6c241fd\neulerProblem2WithLazySeq(limit)=sum([x for x in collect(IterTools.takewhile(x->x<=limit,fib_ch(100))) if x%2==0])\n\n# \u2554\u2550\u2561 c2c72029-ffd2-463c-8548-bbe306178bd1\neulerProblem2WithLazySeq(4_000_000)\n\n# \u2554\u2550\u2561 77f86b91-0ac4-4ba4-a687-0ea49a0ddd10\n@benchmark eulerProblem2WithLazySeq(4_000_000)\n\n# \u2554\u2550\u2561 314415de-ac90-479a-8665-fa9e51323740\n@benchmark eulerProblem2WithLazySeq(1_000_000_000_000)\n\n# \u2554\u2550\u2561 cea3d8d2-70e4-49c7-9698-d4085976e924\nmd\"Let's figure out also how to solve some recurrent equations and do it like that\n\n$a_n=a_{n-1}+a_{n-2}$\n\nThe characteristic equation of the generating function is\n\n$x^2-x-1==0$, with roots\n\n$x_1 = (1+\u221a5)/2, x_2=(1-\u221a5)/2$\n\nThen we can search for a solution of the form $dx_1^n+ex_2^n$,\nsince then\n$a_n-a_{n-1}-a_{n-2} = (dx_1^n+ex_2^n)-(dx_1^{n-1}+ex_2^{n-1})-(...) = dx_1^{n-2}(...=0)-ex_2^{n-2}(...=0)$\nand setting $a_0 = 0, a_1=1$ and solving for \n$d,e$ we get eventually Binet's formula:\n\n$\u03d5 = (\\sqrt(5)+1)/2$\n$a_n = (\u03d5^n-((-\u03d5)^{-n}))/\u221a5$\n\n\"\n\n# \u2554\u2550\u2561 fba39823-d264-4210-80c8-491eb19486d2\nmd\"# Product 3\n\nThe prime factors of 13195 are 5, 7, 13 and 29.\n\nWhat is the largest prime factor of the number 600851475143 ?\n\n\n\"\n\n# \u2554\u2550\u2561 d6a95c3b-30c1-4004-884c-2acdf4a2ef7f\n# let's implement erathostens' sieve\nfunction get_primes(n::Int64)\n\tnumbers = fill(true,n)\n\tnumbers[1] = false\n\t\n\tfor i = 2:isqrt(n)\n\t\tif numbers[i]\n\t\t\tfor j = i:div(n,i)\n\t\t\t\tnumbers[i*j] = false\n\t\t\tend\n\t\tend\n\tend\n\tprimes = findall(numbers)\n\treturn primes\nend\n\n# \u2554\u2550\u2561 080bd517-473a-4c13-9969-a4775a2acc16\n\n\n# \u2554\u2550\u2561 4746f780-750d-4151-bdfb-9687456a36f5\nfunction findFactors(n::Int64)\n all_primes = get_primes(isqrt(600851475143))\n res = []\n for prime in all_primes\n\t\tif mod(n,prime)==0\n\t\t\tpush!(res,prime)\n\t\t\twhile mod(n,prime)==0\n\t\t\t\tn= (n//prime)\n\t\t\tend\n\t\tend\n\tend\n\tres\nend\n\n# \u2554\u2550\u2561 f2279703-313c-4146-8e01-52c5fecf8cfd\nfindFactors(600851475143)\n\n# \u2554\u2550\u2561 69853164-2ca0-4cba-9aef-307f0766b273\nmd\" \n# Problem 4\n\n The largest palindrome made fromt he product of 2 2-digit numbers is 9009=91*99.\nWhat's the largest palindorme made forom the product of two 3-digit numbers... \n\n\n\"\n\n# \u2554\u2550\u2561 3c93ec46-633e-4d97-aa53-6d16b7e85502\nCS = ConstraintSolver\n\n# \u2554\u2550\u2561 1c57967f-f38f-41e2-bc7c-51d1dd681e0b\nfunction CSPalindrome()\n\tmod = Model(CS.Optimizer)\n\t@variable(mod,0<=a[i=1:3]<=9,Int)\n\t@variable(mod,0<=b[i=1:3]<=9,Int)\n\t@variable(mod,0<=res[i=1:6]<=9,Int)\n\t@variable(mod,0<=carry[i=1:5]<=9,Int)\n\t@constraint(mod,three_digits_1,a[1]>=1)\n\t@constraint(mod,three_digits_2,b[1]>=1)\n\t@constraint(mod,first_digit,res[1]==b[1]*a[1])\n\t@objective(mod,Max,1_000_00*res[1]+10_000*res[2]+1000*res[3]+100*res[4]+10*res[5]+res[6])\n\tmod\n\t\nend\n\n# \u2554\u2550\u2561 b5da5b91-de7c-4b69-98f5-737a8a9ced34\nbegin\n\tmd = CSPalindrome()\n\toptimize!(md)\nend\n\n# \u2554\u2550\u2561 e0d8e8d1-8e92-4ea3-9b38-bfb7378fe004\nobjective_value(md)\n\n# \u2554\u2550\u2561 f6b8b94d-0176-4b19-9c81-2959cfff60e7\nisPalindrome(k,l)= begin\n str1= string(k*l)\n  str1==reverse(str1)\nend\n\n# \u2554\u2550\u2561 cc6dbc26-db1f-4534-95b9-7a801139e1d0\nfindPalindrome()=\n\n\tfor i = 999:-1:100\n\tfor j in i:-1:100\n\t\tif isPalindrome(i,j)\n\t\t\treturn i,j\n\tend\n\n\tend\n\tend\n\n# \u2554\u2550\u2561 c5d9bd7f-1a75-482f-a2aa-f653fdce083c\nfindPalindrome()\n\n# \u2554\u2550\u2561 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nBenchmarkTools = \"6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf\"\nCombinatorics = \"861a8166-3701-5b0c-9a16-15d98fcdc6aa\"\nConstraintSolver = \"e0e52ebd-5523-408d-9ca3-7641f1cd1405\"\nIterTools = \"c8e1da08-722c-5040-9ed9-7db0dc04731e\"\nJuMP = \"4076af6c-e467-56ae-b986-b466b2749572\"\n\n[compat]\nBenchmarkTools = \"~1.1.4\"\nCombinatorics = \"~1.0.2\"\nConstraintSolver = \"~0.7.0\"\nIterTools = \"~1.3.0\"\nJuMP = \"~0.21.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\njulia_version = \"1.7.0-beta3.0\"\nmanifest_format = \"2.0\"\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.Arpack]]\ndeps = [\"Arpack_jll\", \"Libdl\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"2ff92b71ba1747c5fdd541f8fc87736d82f40ec9\"\nuuid = \"7d9fca2a-8960-54d3-9f78-7d1dccf2cb97\"\nversion = \"0.4.0\"\n\n[[deps.Arpack_jll]]\ndeps = [\"Libdl\", \"OpenBLAS_jll\", \"Pkg\"]\ngit-tree-sha1 = \"e214a9b9bd1b4e1b4f15b22c0994862b66af7ff7\"\nuuid = \"68821587-b530-5797-8361-c406ea357684\"\nversion = \"3.5.0+3\"\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\", \"Statistics\", \"UUIDs\"]\ngit-tree-sha1 = \"42ac5e523869a84eac9669eaceed9e4aa0e1587b\"\nuuid = \"6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf\"\nversion = \"1.1.4\"\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.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 = \"30ee06de5ff870b45c78f529a6b093b3323256a3\"\nuuid = \"d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4\"\nversion = \"1.3.1\"\n\n[[deps.CodecBzip2]]\ndeps = [\"Bzip2_jll\", \"Libdl\", \"TranscodingStreams\"]\ngit-tree-sha1 = \"2e62a725210ce3c3c2e1a3080190e7ca491f18d7\"\nuuid = \"523fee87-0ab8-5b00-afb7-3ecf72e48cfd\"\nversion = \"0.7.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.Combinatorics]]\ngit-tree-sha1 = \"08c8b6831dc00bfea825826be0bc8336fc369860\"\nuuid = \"861a8166-3701-5b0c-9a16-15d98fcdc6aa\"\nversion = \"1.0.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 = \"6071cb87be6a444ac75fdbf51b8e7273808ce62f\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.35.0\"\n\n[[deps.CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[deps.ConstraintProgrammingExtensions]]\ndeps = [\"LinearAlgebra\", \"MathOptInterface\", \"Test\"]\ngit-tree-sha1 = \"989acd05e57112a5fd1bc8849ebc398a614aa010\"\nuuid = \"b65d079e-ed98-51d9-b0db-edee61a5c5f8\"\nversion = \"0.3.2\"\n\n[[deps.ConstraintSolver]]\ndeps = [\"ConstraintProgrammingExtensions\", \"DataStructures\", \"Formatting\", \"JSON\", \"JuMP\", \"LightGraphs\", \"MathOptInterface\", \"MatrixNetworks\", \"Random\", \"Statistics\", \"StatsBase\", \"StatsFuns\"]\ngit-tree-sha1 = \"47a4c07efa6890e7da286495e22742eb19f3eed9\"\nuuid = \"e0e52ebd-5523-408d-9ca3-7641f1cd1405\"\nversion = \"0.7.0\"\n\n[[deps.DataAPI]]\ngit-tree-sha1 = \"bec2532f8adb82005476c141ec23e921fc20971b\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.8.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.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 = \"3ed8fa7178a10d1cd0f1ca524f249ba6937490c0\"\nuuid = \"b552c78f-8df3-52c6-915a-8e097449b14b\"\nversion = \"1.3.0\"\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.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\", \"NaNMath\", \"Printf\", \"Random\", \"SpecialFunctions\", \"StaticArrays\"]\ngit-tree-sha1 = \"b5e930ac60b613ef3406da6d4f42c35d8dc51419\"\nuuid = \"f6369f11-7733-5829-9624-2563aa707210\"\nversion = \"0.10.19\"\n\n[[deps.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[[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.InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[deps.IrrationalConstants]]\ngit-tree-sha1 = \"f76424439413893a832026ca355fe273e93bce94\"\nuuid = \"92d709cd-6900-40b7-9082-c6be49f344b6\"\nversion = \"0.1.0\"\n\n[[deps.IterTools]]\ngit-tree-sha1 = \"05110a2ab1fc5f932622ffea2a003221f4782c18\"\nuuid = \"c8e1da08-722c-5040-9ed9-7db0dc04731e\"\nversion = \"1.3.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.JSONSchema]]\ndeps = [\"HTTP\", \"JSON\", \"URIs\"]\ngit-tree-sha1 = \"2f49f7f86762a0fbbeef84912265a1ae61c4ef80\"\nuuid = \"7d188eb4-7ad8-530c-ae41-71a32a6d4692\"\nversion = \"0.3.4\"\n\n[[deps.JuMP]]\ndeps = [\"Calculus\", \"DataStructures\", \"ForwardDiff\", \"JSON\", \"LinearAlgebra\", \"MathOptInterface\", \"MutableArithmetics\", \"NaNMath\", \"Printf\", \"Random\", \"SparseArrays\", \"SpecialFunctions\", \"Statistics\"]\ngit-tree-sha1 = \"4358b7cbf2db36596bdbbe3becc6b9d87e4eb8f5\"\nuuid = \"4076af6c-e467-56ae-b986-b466b2749572\"\nversion = \"0.21.10\"\n\n[[deps.KahanSummation]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"1f01068b28d3ad83d4d1212a0ce8d7ecacb33482\"\nuuid = \"8e2b3108-d4c1-50be-a7a2-16352aec75c3\"\nversion = \"0.1.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.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 = \"86197a8ecb06e222d66797b0c2d2f0cc7b69e42b\"\nuuid = \"2ab3a3ac-af41-5b50-aa03-7779005ae688\"\nversion = \"0.3.2\"\n\n[[deps.Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[deps.MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"0fb723cd8c45858c22169b2e42269e53271a6df7\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.7\"\n\n[[deps.Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[deps.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[[deps.MatrixNetworks]]\ndeps = [\"Arpack\", \"DataStructures\", \"DelimitedFiles\", \"IterTools\", \"KahanSummation\", \"LinearAlgebra\", \"Printf\", \"Random\", \"SparseArrays\", \"Statistics\"]\ngit-tree-sha1 = \"f6794d987d426bab570aabb2d03e2f40ca4fc438\"\nuuid = \"4f449596-a032-5618-b826-5a251cb6dc11\"\nversion = \"1.0.2\"\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.Missings]]\ndeps = [\"DataAPI\"]\ngit-tree-sha1 = \"2ca267b08821e86c5ef4376cffed98a46c2cb205\"\nuuid = \"e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28\"\nversion = \"1.0.1\"\n\n[[deps.Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[deps.MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[deps.MutableArithmetics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\", \"Test\"]\ngit-tree-sha1 = \"3927848ccebcc165952dc0d9ac9aa274a87bfe01\"\nuuid = \"d8a4904e-b15c-11e9-3269-09a3773c0cb0\"\nversion = \"0.2.20\"\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.OpenBLAS_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Libdl\"]\nuuid = \"4536629a-c528-5b80-bd46-f80d51c5b363\"\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 = \"438d35d2d95ae2c5e8780b330592b6de8494e779\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.0.3\"\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 = \"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.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.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.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.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\", \"LogExpFunctions\", \"OpenSpecFun_jll\"]\ngit-tree-sha1 = \"a322a9493e49c5f3a10b50df3aedaf1cdb3244b7\"\nuuid = \"276daf66-3868-5448-9aa4-cd146d93841b\"\nversion = \"1.6.1\"\n\n[[deps.StaticArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"3240808c6d463ac46f1c1cd7638375cd22abbccb\"\nuuid = \"90137ffa-7385-5640-81b9-e52037218182\"\nversion = \"1.2.12\"\n\n[[deps.Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[deps.StatsAPI]]\ngit-tree-sha1 = \"1958272568dc176a1d881acb797beb909c785510\"\nuuid = \"82ae8749-77ed-4fe6-ae5f-f523153014b0\"\nversion = \"1.0.0\"\n\n[[deps.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[[deps.StatsFuns]]\ndeps = [\"ChainRulesCore\", \"IrrationalConstants\", \"LogExpFunctions\", \"Reexport\", \"Rmath\", \"SpecialFunctions\"]\ngit-tree-sha1 = \"46d7ccc7104860c38b11966dd1f72ff042f382e4\"\nuuid = \"4c63d2b9-4356-54db-8cca-17b64c39e42c\"\nversion = \"0.9.10\"\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.TranscodingStreams]]\ndeps = [\"Random\", \"Test\"]\ngit-tree-sha1 = \"216b95ea110b5972db65aa90f88d8d89dcb8851c\"\nuuid = \"3bb67fe8-82b1-5028-8e26-92a6c54297fa\"\nversion = \"0.9.6\"\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.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\u2550568f057a-126d-11ec-23cb-f98bea4a534f\n# \u2560\u2550daad198c-10c8-4e4c-93c4-d330ab22f3dd\n# \u2560\u25502cca4797-d1ee-4c27-8243-736e3e468dd1\n# \u2560\u25506b82e993-2f3d-4d5c-8709-57050c7211de\n# \u2560\u2550382a2b3a-4059-4cbe-8485-b0ecce99c451\n# \u2560\u2550e59e2718-acc6-4a98-8ec9-61cf0a375f90\n# \u2560\u2550f7acd079-f79b-4967-a9ee-fc4965e2a06c\n# \u2560\u2550c118a05d-d1bb-4767-9f3a-0b5cefd69d47\n# \u2560\u25509d2617c5-ebf2-46c8-910f-190ba1d160ac\n# \u2560\u2550078cb436-e238-4a69-bde6-156624db601b\n# \u2560\u2550cea0b9f0-b908-4c33-8a5d-6a3019cfa47a\n# \u2560\u255007d10397-f053-45e0-ab2b-6565c18db5a2\n# \u2560\u2550464e87db-a12f-4e8b-a03a-ae1f943a42d0\n# \u2560\u2550e323b98a-47a7-4182-9892-4d0b1891e295\n# \u2560\u255082baf161-7a98-4bb5-a928-b2273e4360cb\n# \u2560\u255089196053-24db-4013-a1e3-3d3b22c4eedc\n# \u2560\u2550c7667675-8018-40f5-a1d9-8756f29466e0\n# \u2560\u2550ed4ded6b-925a-46e7-bcab-0cf0dc0fe80a\n# \u2560\u2550fa4d516c-74ea-44cb-bc18-e2b6cde80515\n# \u2560\u2550120de079-e8e5-40b3-9582-c3741cf024cb\n# \u2560\u25506ea414f8-d5bb-4432-9afb-6d2b2cfd1d01\n# \u2560\u25506d793a48-b48e-4547-ac87-c23a1b03de9c\n# \u2560\u2550e0470dad-e1ab-4603-85d0-e165f80c2463\n# \u2560\u2550c6a079d7-2773-41ba-81c8-773efaabd010\n# \u2560\u255061d320a0-2f4f-4cf4-b800-20bb77560c17\n# \u2560\u255027547863-22e1-466e-951e-2a5677bb9501\n# \u2560\u25502eb91ffc-799d-496e-8b50-6be2d497beaa\n# \u2560\u25505e201d20-3600-4b21-a764-8dd1e89cdf66\n# \u2560\u25506678078e-f30c-4e5e-8de5-f697d6c241fd\n# \u2560\u2550c2c72029-ffd2-463c-8548-bbe306178bd1\n# \u2560\u255077f86b91-0ac4-4ba4-a687-0ea49a0ddd10\n# \u2560\u2550314415de-ac90-479a-8665-fa9e51323740\n# \u2560\u2550cea3d8d2-70e4-49c7-9698-d4085976e924\n# \u2560\u2550fba39823-d264-4210-80c8-491eb19486d2\n# \u2560\u2550d6a95c3b-30c1-4004-884c-2acdf4a2ef7f\n# \u2560\u2550080bd517-473a-4c13-9969-a4775a2acc16\n# \u2560\u25504746f780-750d-4151-bdfb-9687456a36f5\n# \u2560\u2550f2279703-313c-4146-8e01-52c5fecf8cfd\n# \u2560\u255069853164-2ca0-4cba-9aef-307f0766b273\n# \u2560\u2550bade5453-0522-4cbc-8200-78ec160f1192\n# \u2560\u25503c93ec46-633e-4d97-aa53-6d16b7e85502\n# \u2560\u25501c57967f-f38f-41e2-bc7c-51d1dd681e0b\n# \u2560\u2550b5da5b91-de7c-4b69-98f5-737a8a9ced34\n# \u2560\u2550e0d8e8d1-8e92-4ea3-9b38-bfb7378fe004\n# \u2560\u2550f6b8b94d-0176-4b19-9c81-2959cfff60e7\n# \u2560\u2550cc6dbc26-db1f-4534-95b9-7a801139e1d0\n# \u2560\u2550c5d9bd7f-1a75-482f-a2aa-f653fdce083c\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "3375c65d60e742c7c0edf24b7aba54204f308c7c", "size": 24550, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "_notebooks/2021-09-10-project_euler.jl", "max_stars_repo_name": "petrovs12/stats", "max_stars_repo_head_hexsha": "dda50d63d605f0b0ece16eface67554d960b12c6", "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/2021-09-10-project_euler.jl", "max_issues_repo_name": "petrovs12/stats", "max_issues_repo_head_hexsha": "dda50d63d605f0b0ece16eface67554d960b12c6", "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/2021-09-10-project_euler.jl", "max_forks_repo_name": "petrovs12/stats", "max_forks_repo_head_hexsha": "dda50d63d605f0b0ece16eface67554d960b12c6", "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.9025578563, "max_line_length": 280, "alphanum_fraction": 0.7334419552, "num_tokens": 11403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533107374444, "lm_q2_score": 0.95041097648925, "lm_q1q2_score": 0.8862138615886086}}
{"text": "#=Given a posititve number n find all the numbers from 2 to n which \nare prime and print them. Sieve of Eratosthenes is an optimal approach\nto find the prime numbers.We get an array of length n and if the value\nof array at index i is zero the number i is prime.=#\n\n## Function \n\nfunction primeSieve(n)\n    a = zeros(Int64, n + 5)\n    for i = 2:n\n        if (a[i] == 0)\n            for j = (i*i):i:n\n                a[j] = 1\n            end\n        end\n    end\n    for i = 2:n\n        if (a[i] == 0)\n            print(\"$(i) \")\n        end\n    end\nend\n\n##Input\n\nn = readline()\nn = parse(Int64, n)\n\n#Calling the function\n\nprimeSieve(n)\n\n#=\nSample test case:\nInput:\n    n = 20\nOutput:\n    2 3 5 7 11 13 17 19 \n    \nTime complexity: O( N * log(log(N)) )\n=#", "meta": {"hexsha": "87f80c821a7cfdd7d45b44ad5d9d25fc90570e63", "size": 751, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/cp/Sieve_of_Eratosthenes.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/cp/Sieve_of_Eratosthenes.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/cp/Sieve_of_Eratosthenes.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": 18.3170731707, "max_line_length": 70, "alphanum_fraction": 0.5565912117, "num_tokens": 241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731105140616, "lm_q2_score": 0.9196425267730008, "lm_q1q2_score": 0.8853151318095759}}
{"text": "#=\nMatrix Norms\n------------\n\nMany different matrix norms with different numerical values for the same matrix\n\n3 main types of Matrix Norms\n----------------------------\n\n1) Frobenius norm aka Euclidian Norm\n\nSquare all individual matrix elements,\nadd them together\ntake square root\n\n=#\nA = [1 2 3;4 5 6;7 8 9]\n# naive implementation\nfrobnorm1(A) = sqrt(reduce(+, (map(x -> x^2, A))))\n\n## (defn frobnorm [A]\n##   (Math/sqrt (reduce + (map #(* % %) A))))\n\n# more efficient ways using LinearAlgebra package\n\nusing LinearAlgebra\n\nfrobnorm2(A) = sqrt(tr(A' * A))\n\nfrobnorm3(A) = norm(A) # default in Julia\n#=\n\n2) Induced 2-norm - ascertains how much matrix A scales vector x\n\nthe magnitude of vector Ax (A matrix multiplied by vector x results in a vector),\ndivided by the magnitude of vector x\n\n(where x is not a zero vector)\n\n||Ax|| / ||x||\n=#\n\ntwonorm(A,x) = norm(A * x) / norm(x)\n\nnormInd2(A) = sqrt(eigmax(A' * A)) \n\n# if A is a pure rotation matrix, then ||Ax|| would be equal to ||x||\n# so the induced two-norm would be 1\n\n#=\n3) Schatten P-norm\nSum of the singluar values of a matrix\n\nSingluar values is a set of scalar values associated with a matrix.\n\nSingular Value Decomposition determines these values\n\n=#\n\np = 1 # Schatten 1-norm\ns = svdvals(A) # extracts singular values into a vector\nnormSchat = sum(s.^p)^(1/p)\n\np = 2 # same as Frobenius norm\nnormSchat = sum(s.^p)^(1/p)\n\n#= Orthogonal Matrix\n   -----------------\n\nAll the columns have a magnitude of 1, and each column is par-wise orthogonal to every other column\n\nThis can be a purely rotational matrix, so the induced 2-norm is 1\n\nCan be extracted as the Q matrix of the pair from QR Decomposition\n=#\n\nQ, R = qr(randn(5,5))\n\n# induced 2-norm = 1\nind2norm = sqrt(eigmax(Q' * Q))\n", "meta": {"hexsha": "752cb132924e280a58f2f67d7b250aa38d513d90", "size": 1742, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "linear-algebra-code-challenges/Lecture 60 - Matrix Norms.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/Lecture 60 - Matrix Norms.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/Lecture 60 - Matrix Norms.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": 21.5061728395, "max_line_length": 99, "alphanum_fraction": 0.6733639495, "num_tokens": 523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.973240714486111, "lm_q2_score": 0.9086179062123119, "lm_q1q2_score": 0.8843039402369446}}
{"text": "# Entropy.jl\n\n###### generalized entropy #####\n\"\"\"\n    gen_entropy(v, \u03b1)\n\n    Compute the Generalized Entropy Index of a vector `v` at a specified parameter `\u03b1`.\n\n# Examples\n```julia\njulia> using Inequality\njulia> gen_entropy([8, 5, 1, 3, 5, 6, 7, 6, 3], 2)\n0.09039256198347094\n```\n\"\"\"\ngen_entropy(v::AbstractVector{<:Real}, \u03b1::Real)::Float64 = \u03b1 == 1 ? theil(v) : (\u03b1 == 0) ? (mld(v)) : (1/(\u03b1 * (\u03b1 - 1)) * sum(((v./Statistics.mean(v)).^\u03b1 .- 1) * (1/length(v))) )\n\n\n###### weighted generalized entropy #####\n\"\"\"\n    gen_entropy(v, w, \u03b1)\n\nCompute the Generalized Entropy Index of a vector `v`, using weights given by a weight vector `w` \nat a specified parameter `\u03b1`.\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> gen_entropy([8, 5, 1, 3, 5, 6, 7, 6, 3], collect(0.1:0.1:0.9), 2)\n0.0709746654322026\n```\n\"\"\"\nfunction gen_entropy(v::AbstractVector{<:Real},w::AbstractVector{<:Real}, \u03b1::Real)::Float64\n\n    if \u03b1 == 1\n        return theil(v, w)\n    elseif \u03b1 == 0\n        return mld(v, w)\n    end\n\n    checks_weights(v, w)  \n\n    return 1/(\u03b1 * (\u03b1 - 1)) * sum(((v./(sum(v .* w)/sum(w)) ) .^ \u03b1 .-1) .* (w/sum(w)))\n\nend\n\n\nfunction gen_entropy(v::AbstractVector{<:Real},w::AbstractWeights, \u03b1::Real)::Float64\n\n    if \u03b1 == 1\n        return theil(v, w)\n    elseif \u03b1 == 0\n        return mld(v, w)\n    end\n\n    checks_weights(v, w)  \n\n    return 1/(\u03b1 * (\u03b1 - 1)) * sum(((v./(sum(v .* w)/w.sum) ) .^ \u03b1 .-1) .* (w/w.sum))\n\nend\n\n\n\n\"\"\"\n    wgen_entropy(v, w, \u03b1)\n\nCompute the Generalized Entropy Index of `v` with weights `w` at a specified parameter `\u03b1`. See also [`gen_entropy`](gen_entropy)\n\"\"\"\nwgen_entropy(v::AbstractVector{<:Real}, w::AbstractVector{<:Real}, \u03b1::Real)::Float64 = gen_entropy(v,w,\u03b1)\n\nwgen_entropy(v::AbstractVector{<:Real},  w::AbstractWeights, \u03b1::Real)::Float64 = gen_entropy(v,w,\u03b1)\n", "meta": {"hexsha": "1b8e58e24057421db2c221e9679c17cee40c6963", "size": 1892, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Entropy.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/Entropy.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/Entropy.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": 25.5675675676, "max_line_length": 176, "alphanum_fraction": 0.6094080338, "num_tokens": 650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.966410491447634, "lm_q2_score": 0.9149009509324104, "lm_q1q2_score": 0.8841698776164985}}
{"text": "using DifferentialEquations\nusing Plots; gr()\n\nf(u,p,t) = p[1]*u\nu0 = 0.5\n#params = [3.0]\np = [3.0]\ntspan = (0.0,1.0)\nprob = ODEProblem(f,u0,tspan,p)\n\nsol = solve(prob,reltol=1e-7,abstol=1e-7)\n\nplot(sol)\n\nplot(sol,linewidth=5,title=\"Exponential Growth\",\n     xaxis=\"Time\",yaxis=\"Population size\",label=\"Numerical solution\")\n\nplot!(sol.t,t->u0*exp(p[1]t),lw=3,ls=:dash,label=\"True Solution\", legend =:bottomright)\n\n############################################################################\n\nf(u,p,t) = p[1]*u*(1-(u/p[2]))\n#f(u,p,t) = p[1]*u*(1-u)\nu0 = 0.005\n#params = [5.0,1.0]\np = [1.2,1.0]\ntspan = (0.0, 10.0)\n#prob2 = ODEProblem(f, u0, tspan, params)\nprob2 = ODEProblem(f, u0, tspan, p)\n\nsol2 = solve(prob2,reltol=1e-8,abstol=1e-8)\n\nplot(sol2)\n\nplot(sol2,linewidth=5,title=\"Logistic Growth\",\n     xaxis=\"Time\",yaxis=\"Population size\",label=\"Numerical Solution\", legend=:bottomright)\n\nplot!(sol2.t,t->((p[2])*(u0*exp(p[1]t)))/(p[2]+(u0*(exp(p[1]t)-1))),lw=3,ls=:dash,label=\"True Solution\")\n", "meta": {"hexsha": "fed1da1c308f220208aac91300f170e14360a810", "size": 993, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "code/week_three-differential_equations/exponential_logistic_models.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_three-differential_equations/exponential_logistic_models.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_three-differential_equations/exponential_logistic_models.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": 25.4615384615, "max_line_length": 104, "alphanum_fraction": 0.5871097684, "num_tokens": 390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9728307661011976, "lm_q2_score": 0.9086178963141963, "lm_q1q2_score": 0.8839314441645981}}
{"text": "using NewtonsMethod\nusing Test\nusing LinearAlgebra, Statistics, Compat, ForwardDiff\n\n@testset \"NewtonsMethod.jl\" begin\n\n    f(x) = (x-1.0)^3\n    f\u2032(x) = 3.0*(x-1.0)^2\n    x_0 = 0.1\n    @test newtonroot(f, f\u2032, x_0 = x_0).root \u2248 0.9999998168636032\n    @test newtonroot(f, x_0 = x_0).root \u2248 0.9999998168636032\n    @test newtonroot(f, f\u2032, x_0 = BigFloat(x_0), tolerance = 1E-80).root \u2248 BigFloat(1.0)\n    @test newtonroot(f, x_0 = BigFloat(x_0), tolerance = 1E-80).root \u2248 BigFloat(1.0)\n\n    #maxiter\n    @test newtonroot(f, f\u2032, x_0 = x_0, maxiter = 5).root == nothing\n    @test newtonroot(f, x_0 = x_0, maxiter = 5).root == nothing\n    @test newtonroot(f, f\u2032, x_0 = BigFloat(x_0), tolerance = 1E-80, maxiter = 10).root == nothing\n    @test newtonroot(f, x_0 = BigFloat(x_0), tolerance = 1E-80, maxiter = 10).root == nothing\n\n    g(x) = log(x)\n    g\u2032(x) = 1.0/x\n    x_0 = 2.0\n    @test newtonroot(g, g\u2032, x_0 = x_0).root \u2248 1.0\n    @test newtonroot(g, x_0 = x_0).root \u2248 1.0\n    @test newtonroot(g, g\u2032, x_0 = BigFloat(x_0), tolerance = 1E-50).root \u2248 BigFloat(1.0)\n    @test newtonroot(g, x_0 = BigFloat(x_0), tolerance = 1E-50).root \u2248 BigFloat(1.0)\n\n    @test !(newtonroot(g, g\u2032, x_0 = x_0, tolerance = 1E-2).root \u2248 1.0)\n    @test !(newtonroot(g, x_0 = x_0, tolerance = 1E-2).root \u2248 1.0)\n\n    #non-convergence\n\n    h(x) = x^2 + 1.0\n    h\u2032(x) = 2x\n    x_0 = 10.0\n    @test newtonroot(h, h\u2032, x_0 = x_0).root == nothing\n    @test newtonroot(h, x_0 = x_0).root == nothing\n    @test newtonroot(h, h\u2032, x_0 = BigFloat(x_0), tolerance = 1E-100).root == nothing\n    @test newtonroot(h, x_0 = BigFloat(x_0), tolerance = 1E-100).root == nothing\n\nend\n", "meta": {"hexsha": "c3d517ce3e91df3d7c05ea135597c9f5aeb02dad", "size": 1630, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "pedropessoa/NewtonsMethod.jl", "max_stars_repo_head_hexsha": "db5446d3ad9598c8424eb0e67d2b9b3338fc378d", "max_stars_repo_licenses": ["MIT"], "max_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": "pedropessoa/NewtonsMethod.jl", "max_issues_repo_head_hexsha": "db5446d3ad9598c8424eb0e67d2b9b3338fc378d", "max_issues_repo_licenses": ["MIT"], "max_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": "pedropessoa/NewtonsMethod.jl", "max_forks_repo_head_hexsha": "db5446d3ad9598c8424eb0e67d2b9b3338fc378d", "max_forks_repo_licenses": ["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.9069767442, "max_line_length": 97, "alphanum_fraction": 0.6128834356, "num_tokens": 722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620619801094, "lm_q2_score": 0.920789673717312, "lm_q1q2_score": 0.8837389958969195}}
{"text": "\"\"\"\n# Interpolation Search\nUsed for sorted array which is uniformly distributed.\nBinary Search always goes to the middle element to check. On the other hand, interpolation search may go to different locations according to the value of the key being searched. For example, if the value of the key is closer to the last element, interpolation search is likely to start search toward the end side.\nThe idea of formula is to return higher value of pos when element to be searched is closer to arr[hi]. And smaller value when closer to arr[lo]\npos = lo + [ (x-arr[lo])*(hi-lo) / (arr[hi]-arr[Lo]) ]\n- arr[] ==> Array where elements need to be searched\n- x     ==> Element to be searched\n- lo    ==> Starting index in arr[]\n- hi    ==> Ending index in arr[]\n## Derivation =>\nLet's assume that the elements of the array are linearly distributed.\nGeneral equation of line : y = m*x + c.\ny is the value in the array and x is its index.\nNow putting value of lo,hi and x in the equation\n- arr[hi] = m*hi+c ----(1)\n- arr[lo] = m*lo+c ----(2)\n- x = m*pos + c     ----(3)\nm = (arr[hi] - arr[lo] )/ (hi - lo)\nsubtracting eqxn (2) from (3)\n- x - arr[lo] = m * (pos - lo)\n- lo + (x - arr[lo])/m = pos\n- pos = lo + (x - arr[lo]) *(hi - lo)/(arr[hi] - arr[lo])\n## Algorithm:\nRest of the Interpolation algorithm is the same except the above partition logic.\n- Step1: In a loop, calculate the value of \u201cpos\u201d using the probe position formula.\n- Step2: If it is a match, return the index of the item, and exit.\n- Step3: If the item is less than arr[pos], calculate the probe position of the left sub-array. Otherwise calculate the same in the right sub-array.\n- Step4: Repeat until a match is found or the sub-array reduces to zero.\n\n\"\"\"\n\n\"\"\"\n\t interpolation_search(arr::AbstractArray{T,1}, l::T, r::T, x::T) where {T <: Real}\n\nInterpolation Search in 1-D array\nTime Complexity: O(log2(log2 n))\n\"\"\"\nfunction interpolation_search(arr::AbstractArray{T,1}, l::T, r::T, x::T) where {T <: Real}\n\n    if (r >= l && x >= arr[l] && x <= arr[r])\n\n        mid = Int(ceil(l + (((x - arr[l]) * (r - l)) / (arr[r] - arr[l]))))\n\n        if (arr[mid] == x)\n            return mid\n\n        elseif (arr[mid] > x)\n            interpolation_search(arr, l, mid - 1, x)\n\n        else\n            interpolation_search(arr, mid + 1, r, x)\n\n        end\n\n    else\n        return -1\n\n    end\n\nend\n", "meta": {"hexsha": "46aa80a40824cecc8a87771d2d077dc4fa17c191", "size": 2348, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/searches/interpolation_search.jl", "max_stars_repo_name": "gohpeijin/Julia", "max_stars_repo_head_hexsha": "99866f5f6048919c67b28fdcfbffa83f470888f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/searches/interpolation_search.jl", "max_issues_repo_name": "gohpeijin/Julia", "max_issues_repo_head_hexsha": "99866f5f6048919c67b28fdcfbffa83f470888f5", "max_issues_repo_licenses": ["MIT"], "max_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/interpolation_search.jl", "max_forks_repo_name": "gohpeijin/Julia", "max_forks_repo_head_hexsha": "99866f5f6048919c67b28fdcfbffa83f470888f5", "max_forks_repo_licenses": ["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.8709677419, "max_line_length": 313, "alphanum_fraction": 0.6401192504, "num_tokens": 664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812336438724, "lm_q2_score": 0.9124361664296878, "lm_q1q2_score": 0.8835860604684668}}
{"text": "\"\"\"\n    riemann_integration(f::Function, a::Real, b::Real, n::Int, approx::Symbol = :midpoint)\n\na Riemann sum is a certain kind of approximation of an integral by a finite sum.\nThe sum is calculated by partitioning the region into shapes (rectangles, trapezoids, parabolas, or cubics) that together form a region that is similar to the region being measured, then calculating the area for each of these shapes, and finally adding all of these small areas together.\n\nBecause the region filled by the small shapes is usually not exactly the same shape as the region being measured, the Riemann sum will differ from the area being measured. \nThis error can be reduced by dividing up the region more finely, using smaller and smaller shapes. \nAs the shapes get smaller and smaller, the sum approaches the Riemann integral.\n\n# Arguments\n- `f`: the function to integrate. (at the momment only single variable is suported)\n- `a`: Start of the integration limit.\n- `b`: End of the integration limit.\n- `n`: Number of points to sample. (as n increase, error decrease)\n- `approx`: Indicate the method of approximation (midpoint, left or right)\n\n# Examples\n```julia\njulia> riemann_integration(x -> x, 1, 3, 1_000, :midpoint)  # 4.0\njulia> riemann_integration(x -> x, 1, 3, 1_000, :left)      # 3.997997997997998\njulia> riemann_integration(x -> x, 1, 3, 1_000, :right)     # 4.002002002002002\njulia> riemann_integration(x -> 3*x^2, 0, 1, 100000)        # integrate a polynomial\n0.9999999999750021\njulia> riemann_integration(x -> sin(x), 0, pi, 1000)          # integrate the sin function\n2.0000008241146774\n```\n\n# Refereces\n- https://www.khanacademy.org/math/ap-calculus-ab/ab-integration-new/ab-6-2/a/riemann-sums-review\n- https://math.libretexts.org/Courses/Mount_Royal_University/MATH_2200%3A_Calculus_for_Scientists_II/2%3A_Techniques_of_Integration/2.5%3A_Numerical_Integration_-_Midpoint%2C_Trapezoid%2C_Simpson's_rule\n- https://abel.math.harvard.edu/~knill/teaching/math1a_2011/handouts/40-numerical.pdf\n- https://en.wikipedia.org/wiki/Riemann_integral\n\n\nContributed By:- [AugustoCL](https://github.com/AugustoCL)\n\"\"\"\nfunction riemann_integration(f::Function, a::Real, b::Real, n::Int, approx::Symbol = :midpoint)\n    # width of the rectangles\n    \u0394\u2093 = (b - a) / n\n\n    # methods of approximation (:midpoint, :left, :right)\n    if approx == :midpoint\n        sum_range = (a + \u0394\u2093/2):\u0394\u2093:(b - \u0394\u2093/2)\n    elseif approx == :left\n        sum_range = a:\u0394\u2093:(b - \u0394\u2093)\n    elseif approx == :right\n        sum_range = (a + \u0394\u2093):\u0394\u2093:b\n    else\n        throw(ArgumentError(\"The symbol :$approx is not a valid argument. Insert :midpoint, :left or :right\"))\n    end\n\n    # sum of the height of the rectangles\n    \u03a3 = 0.0\n    for i in 2:length(sum_range)\n        a  = sum_range[i-1]\n        b  = sum_range[i]\n        x\u1d62 = a + (b-a)*rand()   # draw a uniform(a,b) for each subinterval [a,b]\n        \u03a3 += f(x\u1d62)\n    end\n\n    # approximate integral of f\n    return \u0394\u2093 * \u03a3\nend\n", "meta": {"hexsha": "9107032022b9a38d2cac759b04426ba9bcd75763", "size": 2947, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/riemann_integration.jl", "max_stars_repo_name": "frankschmitt/Julia", "max_stars_repo_head_hexsha": "c94cf524ad5d3221e05a4967fd088145d9c51a33", "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/riemann_integration.jl", "max_issues_repo_name": "frankschmitt/Julia", "max_issues_repo_head_hexsha": "c94cf524ad5d3221e05a4967fd088145d9c51a33", "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/riemann_integration.jl", "max_forks_repo_name": "frankschmitt/Julia", "max_forks_repo_head_hexsha": "c94cf524ad5d3221e05a4967fd088145d9c51a33", "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": 45.3384615385, "max_line_length": 287, "alphanum_fraction": 0.7064811673, "num_tokens": 910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995772325382, "lm_q2_score": 0.9136765269395709, "lm_q1q2_score": 0.8825197710982253}}
{"text": "\"\"\"Julia program to find the n'th number in the tribonacci series\nTribonacci series is a generalization of the Fibonacci sequence, in which the current term\nis the sum of the previous three \n\"\"\"\n\nfunction find_tribonacci(n)\n    dp = zeros(Int, n + 1)\n    dp[1] = 0\n    dp[2] = 0\n    dp[3] = 1\n\n    for i in 4:n\n        dp[i] = dp[i-1] + dp[i-2] + dp[i-3]\n    end\n\n    return dp[n]\nend\n\n\nprint(\"Enter the value of n?, where you need the n'th number in the tribonacci sequence. \")\nn = readline()\nn = parse(Int, n)\nif (n <= 0)\n    println(\"The given value of n is invalid.\")\n    exit()\nend\nres = find_tribonacci(n)\nprintln(\"The $n'th term in the tribonacci series is $res.\")\n\n\n\"\"\"\nTime Complexity - O(n)\nSpace Complexity - O(n)\n\nSAMPLE INPUT AND OUTPUT\n\nSAMPLE I\nEnter the value of n?, where you need the n'th number in the tribonacci sequence. 12\nThe 12'th term in the tribonacci series is 149.\n\nSAMPLE II\nEnter the value of n?, where you need the n'th number in the tribonacci sequence. 1254\nThe 1254'th term in the tribonacci series is 4020147461713125140.\n\"\"\"\n", "meta": {"hexsha": "19f52343b095cbf046fdd0e1f0c13753df0e26c3", "size": 1061, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/math/tribonacci.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/tribonacci.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/math/tribonacci.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.5777777778, "max_line_length": 91, "alphanum_fraction": 0.6814326107, "num_tokens": 322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.969785412932606, "lm_q2_score": 0.9099070084811307, "lm_q1q2_score": 0.8824145439501456}}
{"text": "# Run this cell to load the graphics packages\n\nusing Plots; gr()\nusing Interact\n\n# ------------------------------------------------------------------------------------------\n# ## Adding a function parameter\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# In the last notebook, we saw an example of adding **parameters** to functions. These are\n# values that control the behavior of a function. Let's look at that in some more detail.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# Let's go back to our original version of the \u03c3 function:\n# ------------------------------------------------------------------------------------------\n\n\u03c3(x) = 1 / (1 + exp(-x))\n\n# ------------------------------------------------------------------------------------------\n# Instead of working with a single function, we can work with a whole class (set) of\n# functions that look similar but differ in the value of a **parameter**. Let's make a new\n# function that uses the previous $\\sigma$ function, but also has a parameter, $w$.\n# Mathematically, we could write\n#\n# $$f_w(x) = f(x; w) = \\sigma(w \\, x).$$\n#\n# (Here, $w$ and $x$ are multiplied in the argument of $\\sigma$; we could write $w \\times x$\n# or $w * x$, or even $w \\cdot x$, but usually the symbols are not written.)\n#\n# Mathematically speaking, we can think of $f_w$ as a different function for each different\n# value of the parameter $w$.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# In Julia, we write this as follows:\n# ------------------------------------------------------------------------------------------\n\nf(x, w) = \u03c3(w * x)\n\n# ------------------------------------------------------------------------------------------\n# Note that Julia just treats parameters as additional *arguments* to the function; the\n# function `f` has two arguments, the value of `x` and the value of `w` that we want to use.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# We can now investigate the effect of $w$ interactively. To do so, we need a way of writing\n# in Julia \"the function of one variable $x$ that we obtain when we fix the value of $w$\".\n# We write this as an \"anonymous function\", as we saw in the notebook on functions:\n#\n#     x -> f(x, w)\n#\n# We can read this as \"the function that maps $x$ to the value of $f(x, w)$, for a value of\n# $w$ that was previously given\".\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# Now we are ready to draw the function. For each plot, we *fix* a value of the parameter\n# $w$ and draw the resulting function as a function of $x$. However, `Interact.jl` then\n# allows us to modify interactively the value of $w$, and plot the new function that comes\n# out:\n# ------------------------------------------------------------------------------------------\n\n@manipulate for w in -2:0.01:2\n    \n    plot(x->f(x, w), -5, 5, ylims=(0,1), label=\"sigmoid\")\n    plot!(x->(x>0), -5,5, label=\"Square Wave\")\nend\n\n# ------------------------------------------------------------------------------------------\n# #### Exercise 1\n#\n# Try writing your own function that takes a parameter. Start by copying and executing\n#\n# ```julia\n# square(x) = x^2\n# ```\n#\n# Then use `square` to declare a new function `square_and_scale` that takes two inputs, `a`\n# and `x` such that\n#\n# $$\\mathrm{square\\_and\\_scale}(x; a) := a \\cdot x^2$$\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# #### Exercise 2\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# Once you have declared `square_and_scale`, uncomment the code below and see how the\n# parameter `a` scales the function `square` :\n# ------------------------------------------------------------------------------------------\n\n# x = -10:10\n# @manipulate for a in 0:0.01:10\n#     plot(x, square.(x), label=\"x^2\")\n#     plot!(x, square_and_scale.(x, a), ls=:dash, label=\"ax^2\")\n# end\n\n# ------------------------------------------------------------------------------------------\n# ## Fitting a function to data\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# As we saw in the previous notebook, what we would like to do is use the fact that we now\n# have a parameter in our function in order to do something useful! Namely, we want to model\n# data with it.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# So suppose that we are given a single data point $(x_0, y_0) = (2, 0.8)$. We can try to\n# \"fit\" the function $f_w$ by adjusting the parameter $w$ until the function passes through\n# the data.\n#\n# **Game**: Move the slider until the graph of the function hits the data point. Which value\n# of $w$ does that correspond to?\n# ------------------------------------------------------------------------------------------\n\nx0, y0 = 2, 0.8\n\n@manipulate for w in -2:0.01:2\n    plot(x->f(x, w), -5, 5, ylims=(0, 1), label=\"f\")\n    scatter!([x0], [y0], label=\"data\")\nend\n\n# ------------------------------------------------------------------------------------------\n# ## Quantifying how far we are from the goal: the *loss function*\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# We can see visually when the graph of the function passes through the data point. But the\n# goal is to be able to automate this process so that the computer can do it unaided.\n#\n# So we will need a more precise way of deciding and quantifying (i.e. measuring with a\n# number) *how far away we are from the goal*; here, the goal means hitting the data point\n# with the function.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# #### Exercise 3\n#\n# Can you think of a way of measuring how far away our function is from the data point?\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# ### Defining the loss function\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# We need to measure how far away the curve is from the data point when we choose a\n# particular value of $w$.\n# One way to do this is by finding the vertical distance $d$ from the curve to the data\n# point.\n#\n# Instead of just taking the distance, it is common to take the *square* of the distance,\n# $d^2$.\n#\n# Since we are taking the vertical distance, we need the distance at the given value of\n# $x_0$ where the data point lies. For a given value of the parameter $w$, the height of the\n# point on the curve with that value of $x_0$ is $f(x_0, w)$.\n#\n# So we take\n# $$d := y_0 - f(x_0, w)$$\n#\n# and\n# $$d^2 = [y_0 - f(x_0, w)]^2.$$\n#\n# This is our measure of distance. It will change when $w$ changes -- in other words, it is\n# itself a *function of $w$*; we will denote this function by $L(w)$, and call it the **loss\n# function**:\n#\n# $$L(w) := [y_0 - f(x_0, w)]^2.$$\n#\n# So the goal is to find the value $w^*$ of $w$ where the loss function is *least*; in other\n# words, we need to *minimize* the loss function!\n#\n# (Another name for a loss function is a *cost function*.)\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# #### Exercise 4\n#\n# (a) Define the loss function `L(w)` in Julia.\n#\n# (b) Draw the data point and the function `x -> f(x, w)`. Also draw a vertical line from\n# the data point to the function `x -> f(x, w)`.\n#\n# (c) Make the plot interactive.\n#\n# (d) Add as the plot title the value of the loss function for the current value of $w$.\n#\n# (e) Use the slider to find the value $w^*$ of $w$ for which the loss function reaches its\n# minimum value. What is $w^*$? What is the value of the loss function there, $L(w^*)$?\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# ## What does the loss function look like?\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# The loss function $L(w)$ tells us how far away the function $f_w$ is from the data when\n# the parameter value is $w$, represented visually as the vertical line in the previous\n# plot. When the data are fixed, this is a function only of the parameter $w$. What does\n# this function look like as a function of $w$? Let's draw it!\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# #### Exercise 5\n#\n# Draw the function $L(w)$ as a function of $w$.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# ### Features of the loss function\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# This graph quantifies how far we are from the data point for a given value of $w$.\n# What features can we see from the graph?\n#\n# Firstly, we see that $L(w)$ is always bigger than $0$, for any value of $w$. This is\n# because we want $L$ to be some kind of measure of *distance*, and distances cannot be\n# negative.\n#\n# Secondly, we see that there is a special value $w^*$ of $w$ where the function $L$ reaches\n# its minimum value. In this particular case, it actually reaches all the way down to $0$!\n# This means that the original function $f$ (the one we manipulated above) passes exactly\n# through the data point $(x_0, y_0)$.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# #### Exercise 6\n#\n# Draw a zoomed-in version of the graph to find the place $w^*$ where the function hits $0$\n# more precisely.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# ### A different way of defining the loss function\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# **Why did we use such a complicated function $L$ with those squares inside?** We could\n# instead just have used the absolute distance, instead of the distance squared, using the\n# *absolute value* function, written mathematically as $| \\cdot |$, and in Julia as `abs`.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# #### Exercise 7\n#\n# Define a new loss function, `L_abs`, using the absolute value, and see what it looks like.\n# ------------------------------------------------------------------------------------------\n", "meta": {"hexsha": "642164a937a3e53cda42484977a539075aaefc81", "size": 12697, "ext": "jl", "lang": "Julia", "max_stars_repo_path": ".nbexports/introductory-tutorials/broader-topics-and-ecosystem/intro-to-ml/06. Tools - Adding a function parameter.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/06. Tools - Adding a function parameter.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/06. Tools - Adding a function parameter.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": 49.9881889764, "max_line_length": 92, "alphanum_fraction": 0.3937150508, "num_tokens": 2288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122756889437, "lm_q2_score": 0.9207896726304802, "lm_q1q2_score": 0.8820357307403407}}
{"text": "# function to determine whether an x, y point is in the unit circle\nfunction in_circle(x_pos::Float64, y_pos::Float64)\n\n    # Setting radius to 1 for unit circle\n    radius = 1\n    return x_pos^2 + y_pos^2 < radius^2\nend\n\n# 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 (in_circle(point_x, point_y))\n            pi_count += 1\n        end\n    end\n\n    # This is using a quarter of the unit sphere in a 1x1 box.\n    # The formula is pi = (box_length^2 / radius^2) * (pi_count / n), but we\n    #     are only using the upper quadrant and the unit circle, so we can use\n    #     4*pi_count/n instead\n    pi_estimate = 4*pi_count/n\n    println(\"The pi estimate is: \", pi_estimate)\n    println(\"Percent error is: \", signif(100 * abs(pi_estimate - pi) / pi, 3), \" %\")\nend\n\nmonte_carlo(10000000)\n", "meta": {"hexsha": "51b9335a880fa6c86b0d0e9aa33dd9493ae8e94d", "size": 933, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "contents/monte_carlo_integration/code/julia/monte_carlo.jl", "max_stars_repo_name": "atocil/algorithm-archive", "max_stars_repo_head_hexsha": "2eb30cb103508c9efb91621564bd3114eb49d3af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-08-30T09:58:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T12:49:47.000Z", "max_issues_repo_path": "contents/monte_carlo_integration/code/julia/monte_carlo.jl", "max_issues_repo_name": "atocil/algorithm-archive", "max_issues_repo_head_hexsha": "2eb30cb103508c9efb91621564bd3114eb49d3af", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-07-12T01:07:26.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-04T19:37:47.000Z", "max_forks_repo_path": "contents/monte_carlo_integration/code/julia/monte_carlo.jl", "max_forks_repo_name": "atocil/algorithm-archive", "max_forks_repo_head_hexsha": "2eb30cb103508c9efb91621564bd3114eb49d3af", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-01-08T16:03:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-23T19:22:17.000Z", "avg_line_length": 29.15625, "max_line_length": 84, "alphanum_fraction": 0.6387995713, "num_tokens": 279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122696813394, "lm_q2_score": 0.9207896748041439, "lm_q1q2_score": 0.8820357272907798}}
{"text": "using Symata, Test\n\nprintln()\n@sym begin\n  xi = [1, 3, 6]\n  yi = [1, 5, 10]\n  L0(x_) := Simplify( Expand( ((x-xi[2])*(x-xi[3]))/((xi[1]-xi[2])*(xi[1]-xi[3])) ) )\n  L1(x_) := Simplify( Expand( ((x-xi[1])*(x-xi[3]))/((xi[2]-xi[1])*(xi[2]-xi[3])) ) )\n  L2(x_) := Simplify( Expand( ((x-xi[1])*(x-xi[2]))/((xi[3]-xi[1])*(xi[3]-xi[2])) ) )\n  Q(x_) := Simplify(yi[1]*L0(x) + yi[2]*L1(x) + yi[3]*L2(x));\n  SetJ(q, ToString(Q(x)))\nend\n\n@sym Print(\"Q(x) = \", Q(x))\nprintln()\n@sym Println(\"Q(4.5) = \", Q(4.5))\n\nprintln()\nq = @sym ToString(Q(x));\nq |> display\nprintln()\n\n@eval f1(x) = $(Meta.parse(q))\n\n@test round(f1(4.5), digits=5) == 7.65\n\n#=\nusing GR\n\nxint = 1:0.1:6 # FloatRange\np = plot(xint, f1.(xint),\"g\", [4.5], [f1(4.5)], \"o\", title=\"Interpolated curve\")\n=#\n", "meta": {"hexsha": "8f629aa1a957ce7708abed0eed9121443225dd53", "size": 756, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/ch04_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/ch04_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/ch04_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": 22.9090909091, "max_line_length": 85, "alphanum_fraction": 0.5066137566, "num_tokens": 358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338035725358, "lm_q2_score": 0.9173026482819238, "lm_q1q2_score": 0.8820175044296782}}
{"text": "\"\"\"\n    partitions_recursive(n)\n\nFinds partitions of an integer using recursion.\n\nA partition of a positive integer n, also called an integer partition,\nis a way of writing n as a sum of positive integers.\n\nThere are 7 partitions of 5:\n5\n4 + 1\n3 + 2\n3 + 1 + 1\n2 + 2 + 1\n2 + 1 + 1 + 1\n1 + 1 + 1 + 1 + 1\n\nPartitions of n is equal to the sum of partitions of n with k parts.\n\n``P \\\\left ( n \\\\right ) = \\\\sum_{k=1}^{n} P_{k} \\\\left ( n \\\\right )``\n\nPartitions of n with k parts is the sum of\npartitions of n-1 with k-1 parts and,\npartitions of n-k with k parts.\n\n``P_{k}\\\\left ( n \\\\right ) = \nP_{k-1}\\\\left ( n - 1 \\\\right ) + P_{k}\\\\left ( n - k \\\\right )``\n\n# Example\n```julia\npartitions_recursive(0)      # returns 1\npartitions_recursive(1)      # returns 1\npartitions_recursive(10)     # returns 42\npartitions_recursive(-1)     # returns DomainError\n```\n# References\n- Partitions of a positive integer -- https://en.wikipedia.org/wiki/Partition_function_(number_theory)\n- Partitions of a positive integer -- https://www.whitman.edu/mathematics/cgt_online/book/section03.03.html\n\n# Contributor\n- [Vaishakh C R](https://github.com/Whiteshark-314)\n\"\"\"\nfunction partitions_recursive(n::N)::BigInt where {N<:Integer}\n    n < 0 && throw(\n        DomainError(\n            \"partitions_recursive() only accepts positive integral values\",\n        ),\n    )\n    if n == 0\n        return one(BigInt)\n    end\n    k = collect(1:n)\n    return sum(partitions_k_parts.(n, k))\nend\n\nfunction partitions_k_parts(n, k)\n    n < 0 ||\n        k < 0 && throw(\n            DomainError(\n                \"partitions_k_parts() only accepts positive integral values\",\n            ),\n        )\n    if (n == 0 && k == 0) || (n > 0 && k == 1) || n == k\n        return one(BigInt)\n    elseif k == 0 || k > n\n        return zero(BigInt)\n    end\n    return partitions_k_parts(n - 1, k - 1) + partitions_k_parts(n - k, k)\nend\n", "meta": {"hexsha": "0551ae7b4d09461b8f4723f4dac3df2a50a1bb8f", "size": 1890, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/partitions.jl", "max_stars_repo_name": "Nikola-Mircic/Julia", "max_stars_repo_head_hexsha": "928972f88c59f87c206ff22e39033e6dd7f799ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-16T05:56:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T05:56:03.000Z", "max_issues_repo_path": "src/math/partitions.jl", "max_issues_repo_name": "Nikola-Mircic/Julia", "max_issues_repo_head_hexsha": "928972f88c59f87c206ff22e39033e6dd7f799ae", "max_issues_repo_licenses": ["MIT"], "max_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/partitions.jl", "max_forks_repo_name": "Nikola-Mircic/Julia", "max_forks_repo_head_hexsha": "928972f88c59f87c206ff22e39033e6dd7f799ae", "max_forks_repo_licenses": ["MIT"], "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": 107, "alphanum_fraction": 0.6185185185, "num_tokens": 575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992923570262, "lm_q2_score": 0.9111797106148062, "lm_q1q2_score": 0.8819301971141508}}
{"text": "using LinearAlgebra\nusing SparseArrays\nusing Plots\nusing ForwardDiff\n\nuexact(x) = log(2+sin(pi*x))\ndudx_exact(x) = ForwardDiff.derivative(uexact,x)\nf(x) = dudx_exact(x)-ForwardDiff.derivative(dudx_exact,x) # du/dx - d^2u/dx^2 = f(x)\n\u03b1 = uexact(-1)\n\u03b2 = uexact(1)\n\n\n\nfunction solve(m,f,\u03b1,\u03b2)\n    x = LinRange(-1,1,m+2) # add 2 endpoints\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    Q = (1/(2*h)) * spdiagm(-1=>-ones(m-1),1=>ones(m-1))\n    b = f.(xint)\n    b[1] += \u03b1/h^2 + \u03b1/(2*h)\n    b[end] += \u03b2/h^2 - \u03b2/(2*h)\n    u = (Q+A)\\b\n    return u,x,xint,h\nend\n\nfunction solve(m,\u03f5,f,\u03b1,\u03b2)\n    x = LinRange(-1,1,m+2) # add 2 endpoints\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    Q = (1/(2*h)) * spdiagm(-1=>-ones(m-1),1=>ones(m-1))\n    # Q = (1/(h)) * spdiagm(0=>-ones(m-1),1=>ones(m-1))\n    b = f.(xint)\n    b[1] += \u03f5*\u03b1/h^2 + \u03b1/(2*h)\n    b[end] += \u03f5*\u03b2/h^2 - \u03b2/(2*h)\n    u = (Q+\u03f5*A)\\b\n    return u,x,xint,h\nend\n\n\u03f5 = .0001\nu,x,xint,h = solve(100,\u03f5,x->1,0,0)\nplot(xint,u,leg=false)\n\n# mvec = 2 .^ (2:9)\n# hvec = zeros(length(mvec))\n# err_inf = zeros(length(mvec))\n# for (i,m) in enumerate(mvec)\n#\n#     \u03f5 = 1.0\n#     u,x,xint,h = solve(m,\u03f5,f,\u03b1,\u03b2)\n#     hvec[i] = h\n#     err_inf[i] = maximum(@. abs(uexact(xint) - u))\n# end\n#\n# plot(hvec,err_inf,marker=:dot,label=\"Max error\")\n# plot!(hvec,hvec,linestyle=:dash,label=\"O(h)\")\n# plot!(hvec,hvec.^2,linestyle=:dash,label=\"O(h^2)\")\n# plot!(xaxis=:log,yaxis=:log,legend=:bottomright)\n", "meta": {"hexsha": "65887474b13b1c6828b09f325ea2442cde035404", "size": 1550, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "hw2/p1.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": "hw2/p1.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": "hw2/p1.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": 25.8333333333, "max_line_length": 84, "alphanum_fraction": 0.544516129, "num_tokens": 696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632275178339, "lm_q2_score": 0.9263037252078029, "lm_q1q2_score": 0.881714453538092}}
{"text": "module Gcd\n\nexport my_gcd\n\n\"\"\"\n   my_gcd(a, b)\n\nCompute the greatest common divisor of a and b\n\n# Arguments\n- `a::Integer`: first argument, not required in real life documentation\n- `b::Integer`: second argument, not required in real life documentation\n\nBoth arguments should be strictly positive, otherwise a `DomaiunErr` exception will be thrown.\n\n# Examples\n\n```julia-repl\njulia> my_gcd(12, 15)\n3\njulia> my_gcd(13, 11)\n1\n```\n\"\"\"\nfunction my_gcd(a::Integer, b::Integer)\n    a < 1 && throw(DomainError(a, \"argument should be strictly positive\"))\n    b < 1 && throw(DomainError(b, \"argument should be strictly positive\"))\n    while a != b\n        if a > b\n            a -= b\n        else\n            b -= a\n        end\n    end\n    return a\nend\n\nend # module\n", "meta": {"hexsha": "6743617e5e48368898a29369d145d32a0d2b43cd", "size": 758, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "source-code/code-organization/Gcd/src/Gcd.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/code-organization/Gcd/src/Gcd.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/code-organization/Gcd/src/Gcd.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": 19.4358974359, "max_line_length": 94, "alphanum_fraction": 0.6464379947, "num_tokens": 214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9496693659780479, "lm_q2_score": 0.9284087985746093, "lm_q1q2_score": 0.8816813951107904}}
{"text": "\"\"\"\nJulia program to implement Eulerian Number\nEulerian number is a number found in combinatorial mathematics. It is the number of permutations of the \nnumbers 1 to n in which exactly m elements are greater than previous element.\n\"\"\"\n\n\nfunction eulerian(n, m)\n    # Build a Dynamic Programming table\n    dp = zeros(Int, n + 1, m + 1)\n\n    # Fill the table in Bottom-Up manner\n    for i in 2:(n+1)\n        for j in 1:(m+1)\n            #Update the table only if i greater than j\n            if(i > j)\n                if(j == 1)\n                    dp[i, j] = 1\n                else\n                    dp[i, j] = (((i - j) * dp[i-1, j-1]) + ((j) * dp[i-1, j]))\n                end\n            end\n        end\n    end\n    return dp[n + 1,m + 1]\nend\n\n\nprint(\"Enter the value of n? \")\nn = readline()\nn = parse(Int64, n)\nprint(\"Enter the value of m? \")\nm = readline()\nm = parse(Int64, m)\nans = eulerian(n, m)\nprint(\"The required eulerian number is \")\nprint(ans)\n\n\n\"\"\"\nTime Complexity - O(n * m)\nSpace Complexity - O(n * m)\n\nSAMPLE INPUT AND OUTPUT\n\nSAMPLE I\nEnter the value of n? 3\nEnter the value of m? 1\nThe required eulerian number is 4\n\nSAMPLE II\nEnter the value of n? 15\nEnter the value of m? 6\nThe required eulerian number is 311387598411\n\"\"\"\n", "meta": {"hexsha": "3df0e1e1d3bf09dc6ff6e1345cde1551f566398e", "size": 1243, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/math/eulerian_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/eulerian_number.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/math/eulerian_number.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": 22.1964285714, "max_line_length": 104, "alphanum_fraction": 0.5880933226, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9805806557900713, "lm_q2_score": 0.8991213806488609, "lm_q1q2_score": 0.8816610330715343}}
{"text": "### A Pluto.jl notebook ###\n# v0.14.5\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 cea30482-e74a-41b0-bdc5-17c2a1c5cf91\nmd\" ## LagrangeInterpolantGenerator.jl\"\n\n# \u2554\u2550\u2561 97e64f8b-18a2-42dd-8872-2acd7983fe09\nmd\" ##### See `https://discourse.julialang.org/t/lagrange-interpolation-function-generator` and the comments on that post. See also the BaricentricInterpolation.jl example (j-05-01b.jl)\"\n\n# \u2554\u2550\u2561 19161060-226e-4469-b13c-ca41a8eace3f\nfunction LagrangeInterpolantGenerator(xvals, yvals)\n\tfunction LagrangeInterpolant(x)\n\t\tnumvalstoevaluate = length(x)\n        numvalstoevaluate == 1 ? output = 0 : output = zeros(numvalstoevaluate)\n        for k = 1:numvalstoevaluate\n            N = length(xvals)\n            LagrangePolynomials = ones(N)\n            for i in 1:N\n\t\t\t\t# Surprisingly, this works even in the i=1 and i=N cases.\n                for j in [1:i-1;i+1:N]     \n                    LagrangePolynomials[i] = LagrangePolynomials[i].*(x[k] -\n\t\t\t\t\t\txvals[j])./(xvals[i]-xvals[j])\n                end\n            end\n            numvalstoevaluate == 1 ? output = sum(LagrangePolynomials.*yvals) : \n\t\t\t\toutput[k] = sum(LagrangePolynomials.*yvals)\n        end\n        return output\n    end\n    return LagrangeInterpolant\nend\n\n# \u2554\u2550\u2561 3ce58d80-543c-42b0-9830-12ffaee6e844\nbegin\n\tx = [1.0, 3.0, 6.0, 5.0]\n\ty = [1.0, 5.0, 10.0, 9.0]\n\txi = [2.0, 4.5]\nend\n\n\n# \u2554\u2550\u2561 e4e3e4de-2dbe-4a0d-9589-fb8456781a73\ninterpolantfunc = LagrangeInterpolantGenerator(x,y);\n\n# \u2554\u2550\u2561 748369b7-3df8-4bed-a125-fa812a92ed1c\ninterpolantfunc.(xi)\n\n# \u2554\u2550\u2561 ccf3b050-7cac-41c4-baf4-c6e535590742\nmd\" ## End of LagrageInterpolantGenerator.jl\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500cea30482-e74a-41b0-bdc5-17c2a1c5cf91\n# \u2560\u255097e64f8b-18a2-42dd-8872-2acd7983fe09\n# \u2560\u255019161060-226e-4469-b13c-ca41a8eace3f\n# \u2560\u25503ce58d80-543c-42b0-9830-12ffaee6e844\n# \u2560\u2550e4e3e4de-2dbe-4a0d-9589-fb8456781a73\n# \u2560\u2550748369b7-3df8-4bed-a125-fa812a92ed1c\n# \u255f\u2500ccf3b050-7cac-41c4-baf4-c6e535590742\n", "meta": {"hexsha": "9b60c3ef3d9a9ca7fc2feba63c9b4dd6d8aeeafe", "size": 1911, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/05/j-05-LagrangeInterpolantGenerator.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/05/j-05-LagrangeInterpolantGenerator.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/05/j-05-LagrangeInterpolantGenerator.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": 31.3278688525, "max_line_length": 186, "alphanum_fraction": 0.673992674, "num_tokens": 812, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9458012717045181, "lm_q2_score": 0.931462509346239, "lm_q1q2_score": 0.8809784258847544}}
{"text": "\"\"\"\r\n    gaussSeidel(A,B,Xawal)\r\nadalah fungsi yang digunakan untuk mencari solusi SPL `Ax=B` secara iteratif dengan\r\nnilai tebakan awal `Xawal` menggunakan metode Gauss-Seidel.\r\n\r\n# Example\r\n```jl\r\njulia> A = [4 -1 1\r\n            4 -8 1\r\n           -2 1 5];\r\n\r\njulia> B = [7;-21;15];\r\n\r\njulia> Xa = [1,2,2];\r\n\r\njulia> X,flag,err,M = gaussSeidel(A,B,Xa);\r\n\r\njulia> X\r\n3-element Array{Float64,1}:\r\n 1.99999999743314\r\n 3.999999998137355\r\n 2.999999999345785\r\n\r\njulia> flag\r\n0\r\n\r\njulia> err\r\n2.1378379298357413e-8\r\n\r\njulia> M\r\n11\u00d75 Array{Float64,2}:\r\n  0.0  1.0      2.0      2.0      NaN\r\n  1.0  1.75     3.75     2.95       2.12779\r\n  2.0  1.95     3.96875  2.98625    0.298606\r\n  3.0  1.99562  3.99609  2.99903    0.0547054\r\n  \u22ee\r\n  7.0  2.0      4.0      3.0        1.21519e-5\r\n  8.0  2.0      4.0      3.0        1.34052e-6\r\n  9.0  2.0      4.0      3.0        1.85294e-7\r\n 10.0  2.0      4.0      3.0        2.13784e-8\r\n```\r\nreturn solusi `X` dengan `flag` bernilai 0 jika metode Gauss-Seidel berhasil menemukan\r\nsolusi dan gagal jika tidak 0. Serta, matriks `M` yang berisi catatan proses tiap\r\niterasi `[k, X', error]`\r\n\"\"\"\r\nfunction gaussSeidel(A,B,Xawal)\r\n    delta = 10^-7;\r\n    maxi = 100;\r\n    flag = 1;\r\n    D = Diagonal(diag(A))\r\n    R = tril(A);\r\n    U = triu(A,1);\r\n    X = Xawal[:];\r\n    M = [0 X' NaN];\r\n    for k = 1:maxi\r\n        Xlama = X;\r\n        X = inv(R)*(B - U*Xlama);\r\n        err = norm(X-Xlama);\r\n        M = [M; [k X' err] ];\r\n        if err<delta\r\n            flag = 0;\r\n            break\r\n        end\r\n    end\r\n    err = M[end,end]\r\n    return X, flag, err, M\r\nend\r\n", "meta": {"hexsha": "43e8643b8f71a1e8caa81000e7791c301de4b442", "size": 1595, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gaussSeidel.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/gaussSeidel.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/gaussSeidel.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.4558823529, "max_line_length": 87, "alphanum_fraction": 0.5153605016, "num_tokens": 671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960361159764527, "lm_q2_score": 0.9173026550642019, "lm_q1q2_score": 0.8809418416725369}}
{"text": "using Random, Distributions, KernelDensity, Plots, LaTeXStrings; pyplot()\nRandom.seed!(1)\n\nfunction pval(mu0,mu,sig,n)\n    sample = rand(Normal(mu,sig),n)\n    xBar   = mean(sample)\n    s      = std(sample)\n    tStat  = (xBar-mu0) / (s/sqrt(n))\n    ccdf(TDist(n-1), tStat)\nend\n\nmu0, mu1A, mu1B  = 20, 22, 24\nsig, n, N = 7, 5, 10^6\n\npValsH0 = [pval(mu0,mu0,sig,n) for _ in 1:N]\npValsH1A = [pval(mu0,mu1A,sig,n) for _ in 1:N]\npValsH1B = [pval(mu0,mu1B,sig,n) for _ in 1:N]\n\nalpha = 0.05\nestPwr(pVals) = sum(pVals .< alpha)/N\n\nprintln(\"Power under H0:  \", estPwr(pValsH0))\nprintln(\"Power under H1A: \", estPwr(pValsH1A))\nprintln(\"Power under H1B (mu's farther apart): \", estPwr(pValsH1B))\n\nstephist(pValsH0, bins=100,\n\tnormed=true, c=:blue, label=\"Under H0\")\nstephist!(pValsH1A, bins=100,\n\tnormed=true, c=:red, label=\"Under H1A\")\nstephist!(pValsH1B, bins=100,\n\tnormed=true, c=:green, label=\"Under H1B\", \n    xlims=(0,1), ylims=(0,6), xlabel = \"p-value\", ylabel = \"Density\")\n\nplot!([alpha,alpha],[0,6], \n\tc=:black, ls=:dash, label=L\"\\alpha\")", "meta": {"hexsha": "cb993993511a8f3d243689033ce55b0eca5c59c9", "size": 1035, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "7_chapter/pValDist.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/pValDist.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/pValDist.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.5714285714, "max_line_length": 73, "alphanum_fraction": 0.6473429952, "num_tokens": 423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338123908151, "lm_q2_score": 0.9161096198879968, "lm_q1q2_score": 0.8808703753788061}}
{"text": "function euclid_mod(a::Int64, b::Int64)\n    a = abs(a)\n    b = abs(b)\n\n    while(b != 0)\n        b,a = a%b,b\n    end\n\n    return a\nend\n\nfunction euclid_sub(a::Int64, b::Int64)\n    a = abs(a)\n    b = abs(b)\n\n    while (a != b)\n        if (a > b)\n            a -= b\n        else\n            b -= a\n        end\n    end\n\n    return a\nend\n\nfunction main()\n    check1 = euclid_mod(64 * 67, 64 * 81);\n    check2 = euclid_sub(128 * 12, 128 * 77);\n\n    println(\"Modulus-based euclidean algorithm result: $(check1)\")\n    println(\"subtraction-based euclidean algorithm result: $(check2)\")\n\nend\n\nmain()\n", "meta": {"hexsha": "744ae218793e87b52b54beb7c0a1af0267545635", "size": 591, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "contents/euclidean_algorithm/code/julia/euclidean.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/euclidean_algorithm/code/julia/euclidean.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/euclidean_algorithm/code/julia/euclidean.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": 15.972972973, "max_line_length": 70, "alphanum_fraction": 0.5262267343, "num_tokens": 191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338068793908, "lm_q2_score": 0.9161096055730491, "lm_q1q2_score": 0.8808703565654311}}
{"text": "\"\"\"\r\n    richardson(f, a; delta = 1e-9)\r\nadalah fungsi yang digunakan untuk mencari nilai turunan `f` pada titik `a`\r\nmenggunakan formula ekstrapolasi Richardson. Secara default, digunakan nilai\r\ntoleransi `delta=1e-9`\r\n\r\n# Examples\r\n```jl\r\njulia> sol,flag,err,D = richardson(sin,pi/3);\r\n\r\njulia> sol\r\n0.49999999999998856\r\n\r\njulia> flag\r\n0\r\n\r\njulia> err\r\n3.323475383787411e-10\r\n\r\njulia> D\r\n5\u00d75 Array{Float64,2}:\r\n 0.420735  0.0       0.0       0.0  0.0\r\n 0.479426  0.498989  0.0       0.0  0.0\r\n 0.494808  0.499935  0.499998  0.0  0.0\r\n 0.498699  0.499996  0.5       0.5  0.0\r\n 0.499675  0.5       0.5       0.5  0.5\r\n\r\njulia> sol,flag,err,D = richardson(sin,pi/3,delta=1e-12);\r\n\r\njulia> sol\r\n0.5000000000000013\r\n\r\njulia> flag\r\n0\r\n\r\njulia> err\r\n1.27675647831893e-14\r\n\r\njulia> D\r\n6\u00d76 Array{Float64,2}:\r\n 0.420735  0.0       0.0       0.0  0.0  0.0\r\n 0.479426  0.498989  0.0       0.0  0.0  0.0\r\n 0.494808  0.499935  0.499998  0.0  0.0  0.0\r\n 0.498699  0.499996  0.5       0.5  0.0  0.0\r\n 0.499675  0.5       0.5       0.5  0.5  0.0\r\n 0.499919  0.5       0.5       0.5  0.5  0.5\r\n```\r\nreturn solusi `sol` dengan `flag` bernilai 0 jika toleransi terpenuhi, `flag`\r\nbernilai 1 jika maksimum iterasi tercapai. Serta, error `err` dan matriks `D`\r\nyang berisi tabel ekstrapolasi Richardson.\r\n\"\"\"\r\nfunction richardson(f, a; delta = 1e-9)\r\n  maxi = 50;\r\n  flag = 1;\r\n  h = 1;\r\n  D = (f(a+h)-f(a-h))/(2*h);\r\n  err = NaN;\r\n  for j=1:maxi\r\n    h = h/2;\r\n    D = [D zeros(size(D,1),1);\r\n\t\t(f(a.+h).-f(a.-h))./(2*h) zeros(1, size(D,1))];\r\n    for k = 1:j\r\n      D[j+1,k+1] = D[j+1,k] + (D[j+1,k]-D[j,k])/(4^k-1);\r\n    end\r\n    err = abs(D[j+1,j+1]-D[j,j]);\r\n    if err<delta\r\n      flag=0;\r\n      break\r\n    end\r\n  end\r\n  sol = D[end,end];\r\n  return sol, flag, err, D\r\nend\r\n", "meta": {"hexsha": "d1fc0301ae95c5b041fe9792b13824509c31d921", "size": 1760, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/richardson.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/richardson.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/richardson.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.7837837838, "max_line_length": 78, "alphanum_fraction": 0.5607954545, "num_tokens": 824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191309994468, "lm_q2_score": 0.9219218396818158, "lm_q1q2_score": 0.8807295707342436}}
{"text": "\"\"\"\n    perfect_number(number)\n\nChecks if a number is a perfect_number number or not\n\n# Details\n\nperfect_number number is a positive integer that is equal to the sum of\nits positive divisors, excluding the number itself.\n\nFor example : 6 is perfect_number number\n\nDivisors of 6 => [1,2,3]\n\nSum of divisors => 1+2+3 = 6\n\n6 == sum(divisors) # which is true\n\n# Example\n\n```julia\nperfect_number(27)     # returns false\nperfect_number(28)     # returns true\nperfect_number(496)    # returns true\nperfect_number(8128)   # returns true\nperfect_number(123)    # returns false\n```\n\nContributed By:- [Ashwani Rathee](https://github.com/ashwani-rathee)\n\"\"\"\nfunction perfect_number(number)\n    divisors = []\n    for i = 1:(number\u00f72+1)\n        if number % i == 0\n            push!(divisors, i)\n        end\n    end\n    return sum(divisors) == number\nend\n", "meta": {"hexsha": "949142b9f6f60f46df9bfe03d70f26c631d207bc", "size": 840, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/perfect_number.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_number.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_number.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": 21.0, "max_line_length": 71, "alphanum_fraction": 0.6773809524, "num_tokens": 237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.950410981229714, "lm_q2_score": 0.9263037308025663, "lm_q1q2_score": 0.8803692377088119}}
{"text": "\"\"\"\nnewton(f,dfdx,x1)\n\nUse Newton's method to find a root of `f` starting from `x1`, where\n`dfdx` is the derivative of `f`. Returns a vector of root estimates.\n\"\"\"\nfunction newton(f,dfdx,x1)\n    # Operating parameters.\n    funtol = 100*eps();  xtol = 100*eps();  maxiter = 40;\n\n    x = [x1]\n    y = f(x1)\n    dx = Inf   # for initial pass below\n    k = 1\n\n    while (abs(dx) > xtol) && (abs(y) > funtol) && (k < maxiter)\n        dydx = dfdx(x[k])\n        dx = -y/dydx            # Newton step\n        push!(x,x[k]+dx)        # append new estimate\n\n        k = k+1\n        y = f(x[k])\n    end\n\n    if k==maxiter\n        @warn \"Maximum number of iterations reached.\"\n    end\n\n    return x\nend\n\n\"\"\"\nsecant(f,x1,x2)\n\nUse the secant method to find a root of `f` starting from `x1` and\n`x2`. Returns a vector of root estimates.\n\"\"\"\nfunction secant(f,x1,x2)\n    # Operating parameters.\n    funtol = 100*eps();  xtol = 100*eps();  maxiter = 40;\n\n    x = [x1,x2]\n    y1 = f(x1); y2 = 100;\n    dx = Inf   # for initial pass below\n    k = 2\n\n    while (abs(dx) > xtol) && (abs(y2) > funtol) && (k < maxiter)\n        y2 = f(x[k])\n        dx = -y2 * (x[k]-x[k-1]) / (y2-y1)   # secant step\n        push!(x,x[k]+dx)        # append new estimate\n\n        k = k+1\n        y1 = y2    # current f-value becomes the old one next time\n    end\n\n    if k==maxiter\n        @warn \"Maximum number of iterations reached.\"\n    end\n\n    return x\nend\n\n\"\"\"\nnewtonsys(f,jac,x1)\n\nUse Newton's method to find a root of a system of equations,\nstarting from `x1`. The functions `f` and `jac should return the\nresidual vector and the Jacobian matrix, respectively. Returns\nhistory of root estimates as a vector of vectors.\n\"\"\"\nfunction newtonsys(f,jac,x1)\n    # Operating parameters.\n    funtol = 1000*eps();  xtol = 1000*eps();  maxiter = 40;\n\n    x = [float(x1)]\n    y,J = f(x1),jac(x1)\n    dx = Inf   # for initial pass below\n    k = 1\n\n    while (norm(dx) > xtol) && (norm(y) > funtol) && (k < maxiter)\n        dx = -(J\\y)             # Newton step\n        push!(x,x[k] + dx)    # append to history\n        k += 1\n        y,J = f(x[k]),jac(x[k])\n    end\n\n    if k==maxiter\n        @warn \"Maximum number of iterations reached.\"\n    end\n\n    return x\nend\n\n\"\"\"\nfdjac(f,x0,y0)\n\nCompute a finite-difference approximation of the Jacobian matrix for\n`f` at `x0`, where `y0`=`f(x0)` is given.\n\"\"\"\nfunction fdjac(f,x0,y0)\n\ndelta = sqrt(eps())   # FD step size\nm,n = length(y0),length(x0)\nif n==1\n    J = (f(x0+delta) - y0) / delta\nelse\n    J = zeros(m,n)\n    In = I(n)\n    for j = 1:n\n        J[:,j] = (f(x0 + delta*In[:,j]) - y0) / delta\n    end\nend\n\nreturn J\nend\n\n\"\"\"\nlevenberg(f,x1,tol)\n\nUse Levenberg's quasi-Newton iteration to find a root of the system\n`f`, starting from `x1`, with `tol` as the stopping tolerance in\nboth step size and residual norm. Returns root estimates as a\nmatrix, one estimate per column.\n\"\"\"\nfunction levenberg(f,x1,tol=1e-12)\n\n# Operating parameters.\nftol = tol;  xtol = tol;  maxiter = 40;\n\nx = zeros(length(x1),maxiter)\nx = [float(x1)]\nfk = f(x1)\nk = 1;  s = Inf;\nAk = fdjac(f,x1,fk)   # start with FD Jacobian\njac_is_new = true\n\nlambda = 10;\nwhile (norm(s) > xtol) && (norm(fk) > ftol) && (k < maxiter)\n    # Compute the proposed step.\n    B = Ak'*Ak + lambda*I\n    z = Ak'*fk\n    s = -(B\\z)\n\n    xnew = x[k] + s\n    fnew = f(xnew)\n\n    # Do we accept the result?\n    if norm(fnew) < norm(fk)    # accept\n        y = fnew - fk\n        push!(x,xnew)\n        fk = fnew\n        k += 1\n\n        lambda = lambda/10   # get closer to Newton\n        # Broyden update of the Jacobian.\n        Ak = Ak + (y-Ak*s)*(s'/(s'*s))\n        jac_is_new = false\n    else                       # don't accept\n        # Get closer to steepest descent.\n        lambda = 4lambda\n        # Re-initialize the Jacobian if it's out of date.\n        if !jac_is_new\n            Ak = fdjac(f,x[k],fk)\n            jac_is_new = true\n        end\n    end\nend\n\nif (norm(fk) > 1e-3)\n    @warn \"Iteration did not find a root.\"\nend\n\nreturn x\nend\n", "meta": {"hexsha": "9c53f3b8d45145d0c8b8ffa9178de723059fdd48", "size": 4002, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chapter04.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": "src/chapter04.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": "src/chapter04.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": 22.8685714286, "max_line_length": 68, "alphanum_fraction": 0.559970015, "num_tokens": 1326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778073288128, "lm_q2_score": 0.9196425311777929, "lm_q1q2_score": 0.880353385772197}}
{"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\nusing LinearAlgebra, Statistics\nusing QuantEcon, Plots\ngr(fmt=:png);\n\n# Exercise 1\n\u03d5_0, \u03d5_1, \u03d5_2 = 1.1, 0.8, -0.8\n\nA = [1.0 0.0 0.0; \u03d5_0 \u03d5_1 \u03d5_2; 0.0 1.0 0.0]\nC = zeros(3,1)\nG = [0 1 0]\n\u03bc_0 =  ones(3)\n\nlss = LSS(A,C,G; mu_0 = \u03bc_0)\n\nx,y = simulate(lss, 50)\nplot(dropdims(y, dims = 1), color = :blue)\nplot!(xlabel=\"time\", ylabel = \"y_t\", legend = :none)\n\n# Exercise 2\n\nusing Random\nRandom.seed!(42) # For deterministic results.\n\n\u03d51, \u03d52, \u03d53, \u03d54 = 0.5, -0.2, 0, 0.5\n\u03c3 = 0.2\n\nA = [\u03d51 \u03d52 \u03d53 \u03d54; 1.0 0.0 0.0 0.0; 0.0 1.0 0.0 0.0; 0.0 0.0 1.0 0.0]\nC = [\u03c3; 0.0; 0.0; 0.0]\nG = [1.0 0.0 0.0 0.0]\n\u03bc_0 =  ones(4)\n\nlss = LSS(A,C,G; mu_0 = \u03bc_0)\n\nx,y = simulate(lss, 200)\nplot(dropdims(y, dims = 1), color = :blue)\nplot!(xlabel=\"time\", ylabel = \"y_t\", legend = :none)\n\n# Exercise 3\n\u03d51, \u03d52, \u03d53, \u03d54 = 0.5, -0.2, 0, 0.5\n\u03c3 = 0.1\n\nA = [\u03d51 \u03d52 \u03d53 \u03d54; 1.0 0.0 0.0 0.0; 0.0 1.0 0.0 0.0; 0.0 0.0 1.0 0.0]\nC = [\u03c3; 0.0; 0.0; 0.0]\nG = [1.0 0.0 0.0 0.0]\n\u03bc_0 = ones(4)\n\nI = 20\nT = 50\n\nar = LSS(A, C, G; mu_0 = \u03bc_0)\n\nensemble_mean = zeros(T)\nys = []\nfor ii in 1:I\n        x,y = simulate(ar, T)\n        y = dropdims(y, dims=1)\n        push!(ys,y)\n        ensemble_mean .+= y\nend\nensemble_mean = ensemble_mean./I\n\nplot(ensemble_mean, label = \"y_t_bar\", linewidth = 2)\nplot!(ys, linewidth = 0.8, alpha = 0.2, label = \"\", color =:blue)\n\nymin, ymax = -0.5, 1.15\nm = moment_sequence(ar)\npop_means = zeros(0)\nfor (i, t) \u2208 enumerate(m)\n    (\u03bc_x, \u03bc_y, \u03a3_x, \u03a3_y) = t\n    push!(pop_means, \u03bc_y[1])\nend\nplot!(pop_means, color = :green, linewidth = 2, label = \"G mu_t\")\nplot!(ylims=(ymin, ymax), xlabel = \"time\", ylabel = \"y_t\", legendfont = font(12))\n", "meta": {"hexsha": "ff987d1868ad27f21108cc370a1d42e1d3392675", "size": 1793, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ToolsandTechniques_LSS.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": "ToolsandTechniques_LSS.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": "ToolsandTechniques_LSS.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": 22.9871794872, "max_line_length": 87, "alphanum_fraction": 0.5939765756, "num_tokens": 869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813451206062, "lm_q2_score": 0.920789678608055, "lm_q1q2_score": 0.8802577555288991}}
{"text": "using JuMP\nusing HiGHS\nusing SCS\nusing LinearAlgebra\n\nusing Graphs\nusing GenericTensorNetworks\nusing Random\n#g = smallgraph(:petersen)\ng = random_diagonal_coupled_graph(10, 10, 0.8)\n\n# MIT course: http://people.csail.mit.edu/moitra/854.html\nfunction maxcut_ilp(g::SimpleGraph; optimizer=HiGHS.Optimizer)\n    ws = ones(Int,ne(g))\n    edgs = collect(edges(g))\n    model = Model(optimizer)\n    @variable model xs[1:nv(g)] Bin\n    @variable model zs[1:ne(g)] Bin\n    @constraint model [i=1:ne(g)] zs[i] <= xs[edgs[i].src] + xs[edgs[i].dst]\n    @constraint model [i=1:ne(g)] zs[i] <= 2 - xs[edgs[i].src] - xs[edgs[i].dst]\n    @objective model Max ws' * zs \n    optimize!(model)\n    return objective_value(model), value.(xs)\nend\n\n# see also: https://jump.dev/JuMP.jl/stable/tutorials/conic/max_cut_sdp/\nfunction maxcut_relaxed_sdp(g::SimpleGraph; optimizer=SCS.Optimizer)\n    L = laplacian_matrix(g)\n    model = Model(optimizer)\n    # Start with X as the identity matrix to avoid numerical issues.\n    @variable model X[i=1:nv(g), j=1:nv(g)] PSD start=(i==j ? 1.0 : 0.0)\n    @constraint model diag(X) .== 1\n    @objective model Max 0.25 * dot(L, X)\n    optimize!(model)\n    @assert termination_status(model) == MOI.OPTIMAL\n    return objective_value(model), value.(X)\nend\n\nfunction goemans_williamson_postprocess(X)\n    num_vertex = size(X, 1)\n    # small positive number to avoid zero\n    V = cholesky(X + 1e-3 * I).U\n    # Generate random vector on unit sphere.\n    r = rand(size(V, 1))\n    r /= LinearAlgebra.norm(r)\n    # Iterate over vertices, and assign each vertex to a side of cut.\n    cut = ones(num_vertex)\n    for i in 1:num_vertex\n        if LinearAlgebra.dot(r, V[:, i]) <= 0\n            cut[i] = -1\n        end\n    end\n    return cut\nend\n\nfunction goemans_williamson(g::SimpleGraph)\n    loss, X = maxcut_relaxed_sdp(g)\n    @info \"Got loss = $(loss)\"\n    return goemans_williamson_postprocess(X)\nend\n\n@time solve(MaxCut(g; optimizer=TreeSA(ntrials=3, \u03b2s=0.1:0.1:30, niters=10, sc_target=25)), SizeMax())\n#function addvar!(model::Model, ::Type{T}, name::String; lower_bound::Union{T,Nothing}=nothing, upper_bound::Union{T,Nothing}=nothing, fixed_value::Union{T,Nothing}=nothing, start) where T\n#end\n#JuMP.add_variable(model, JuMP.build_variable(error, JuMP.VariableInfo(true, 0, false, NaN, false, NaN, false, NaN, false, true)), \"x\")\n#model[:x] = var\"#25###291\"", "meta": {"hexsha": "000dda588a0733f8047f55f528fbbc060c6751e1", "size": 2368, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "project/integer_prog.jl", "max_stars_repo_name": "RydbergBoston/GraphUtilities.jl", "max_stars_repo_head_hexsha": "99235c9481dd19d7eda4732382d13d53d48a8b70", "max_stars_repo_licenses": ["MIT"], "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/integer_prog.jl", "max_issues_repo_name": "RydbergBoston/GraphUtilities.jl", "max_issues_repo_head_hexsha": "99235c9481dd19d7eda4732382d13d53d48a8b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-25T05:52:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T05:52:04.000Z", "max_forks_repo_path": "project/integer_prog.jl", "max_forks_repo_name": "RydbergBoston/GraphUtilities.jl", "max_forks_repo_head_hexsha": "99235c9481dd19d7eda4732382d13d53d48a8b70", "max_forks_repo_licenses": ["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.8787878788, "max_line_length": 188, "alphanum_fraction": 0.6786317568, "num_tokens": 755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305339244013, "lm_q2_score": 0.913676521650809, "lm_q1q2_score": 0.8800811237838986}}
{"text": "using Jacobi, Plots\ngr(size=(700,700))\n\nProjDir = dirname(@__FILE__)\ncd(ProjDir) #do\n  \n  if !isdefined(Main, :lgt)\n    function lgt(Q, nx, lb, ub)\n      z = zglj(Q)\n      x = collect(linspace(lb, ub, nx))\n      y = zeros(nx, Q)\n      for k = 1:Q, i=1:nx\n        y[i,k]=lagrange(k,x[i],z)\n      end\n      (x, y)\n    end\n  end\n  \n  Q = 5\n  nx = 201\n  lb = -1\n  ub = 1\n  (x, y) = lgt(Q, nx, lb, ub)\n  \n  p = plot()\n  for k = 1:Q\n    plot!(x, y[:, k], label=\"Q = $k\")\n  end\n  \n  plot(p)\n  savefig(\"lagrange_n201.png\")\n  gui()\n  \n  Q = 5\n  nx = 3\n  lb = -1\n  ub = 1\n  (x, y) = lgt(Q, nx, lb, ub)\n  x |> display\n  println()\n  y |> display\n  println()\n  \n  p = plot()\n  for k = 1:Q\n    plot!(x, y[:, k], label=\"Q = $k\")\n  end\n  \n  plot(p)\n  savefig(\"lagrange_n3.png\")\n  gui()\n  \n#end", "meta": {"hexsha": "7ea9aca2a5c067070faac20f9abcc209e11b0c62", "size": 777, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ch04/lagrange.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/ch04/lagrange.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/ch04/lagrange.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": 14.6603773585, "max_line_length": 39, "alphanum_fraction": 0.4723294723, "num_tokens": 329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422241476944, "lm_q2_score": 0.9252299539994746, "lm_q1q2_score": 0.8800252762951293}}
{"text": "\"\"\"\n   `ecc_anom_init_guess_danby(mean_anomaly, eccentricity)`\n\nReturns initial guess for the eccentric anomaly for use by itterative solvers of Kepler's equation for bound orbits.\n\nBased on \"The Solution of Kepler's Equations - Part Three\"\nDanby, 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::Real, ecc::Real)\n\t@assert -2\u03c0<= M <= 2\u03c0\n\t@assert 0 <= ecc <= 1.0\n    if  M < zero(M)\n\t\tM += 2\u03c0\n\tend\n    E = (M<\u03c0) ? M + 0.85*ecc : M - 0.85*ecc\nend;\n\n\"\"\"\n   `update_ecc_anom_laguerre(eccentric_anomaly_guess, mean_anomaly, eccentricity)`\n\nUpdate the current guess for solution to Kepler's equation\n\nBased 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::Real, M::Real, ecc::Real)\n  (es, ec) = ecc .* sincos(E)\n  F = (E-es)-M\n  Fp = one(M)-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\"\"\"\n   `calc_ecc_anom( mean_anomaly, eccentricity )`\n   `calc_ecc_anom( param::Vector )``\n\tEstimates eccentric anomaly for given 'mean_anomaly' and 'eccentricity'.\nIf passed a parameter vector, param[1] = mean_anomaly and param[2] = eccentricity.\nOptional parameter `tol` specifies tolerance (default 1e-8)\n\"\"\"\nfunction calc_ecc_anom end\nfunction calc_ecc_anom(mean_anom::Real, ecc::Real; tol::Real = 1.0e-8)\n\t@assert 0 <= ecc <= 1.0\n\t@assert 1e-16 <= tol < 1\n  \tM = rem2pi(mean_anom,RoundNearest)\n    E = ecc_anom_init_guess_danby(M,ecc)\n\tlocal E_old\n    max_its_laguerre = 200\n    for i in 1:max_its_laguerre\n       E_old = E\n       E = update_ecc_anom_laguerre(E_old, M, ecc)\n       if abs(E-E_old) < tol break end\n    end\n    return E\nend\n\nfunction calc_ecc_anom(param::Vector; tol::Real = 1.0e-8)\n\t@assert length(param) == 2\n\tcalc_ecc_anom(param[1], param[2], tol=tol)\nend\n", "meta": {"hexsha": "87cb5956add41ba254fb623b769c5a8fc67f409f", "size": 2018, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kepler_eqn.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/kepler_eqn.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/kepler_eqn.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": 31.53125, "max_line_length": 116, "alphanum_fraction": 0.6873141724, "num_tokens": 722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632288833652, "lm_q2_score": 0.9241418262465169, "lm_q1q2_score": 0.8796566226771794}}
{"text": "#=\nThe area of a circle is defined as \u03c0r^2. Estimate \u03c0 to 3 decimal places using a Monte Carlo method.\n\nHint: The basic equation of a circle is x2 + y2 = r2\n=#\nusing Test\ninclude(\"Solutions/problem14_estimate_pi.jl\")\n\n@test abs(estimate_pi() - pi) <= 0.001\n@test abs(estimate_pi(number_of_decimal = 5) - pi) <= 0.00001\n", "meta": {"hexsha": "41f1516fbc92e99c5f1132a07a92d0b349699436", "size": 319, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Tests/problem14_estimate_pi_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/problem14_estimate_pi_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/problem14_estimate_pi_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": 29.0, "max_line_length": 99, "alphanum_fraction": 0.7210031348, "num_tokens": 99, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9763105280113491, "lm_q2_score": 0.9005297914570319, "lm_q1q2_score": 0.879196716187365}}
{"text": "\"\"\"\n    gauss_jordan(A::AbstractMatrix{T}) where T<:Number\n\nGaussian elimination, also known as row reduction, is an algorithm for solving systems of linear equations. \nIt consists of a sequence of operations performed on the corresponding matrix of coefficients. \nThis method can also be used to compute the rank of a matrix, the determinant of a square matrix, and the inverse of an invertible matrix.\nhttps://en.wikipedia.org/wiki/Gaussian_elimination\n\n# Examples/Tests\n```julia\njulia> M1 = [1 2 3; 4 5 6];\njulia> M2 = [1 2 3; 4 8 12];\n\njulia> @test gauss_jordan(M1) == [1 0 -1; 0 1 2]        # Test Passed\njulia> @test_throws AssertionError gauss_jordan(M2)     # Test Passed - Thrown: AssertionError\n```     \n\n# Contributed By:- [AugustoCL](https://github.com/AugustoCL)\n\"\"\"\nfunction gauss_jordan(A::AbstractMatrix{T}) where {T<:Number}\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    # execute the gauss-jordan elimination\n    for i \u2208 axes(A, 1)\n\n        if A[i, i] == 0.0\n            for n \u2208 (i + 1):m                           # iterate in lines below 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\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# using multiple dispatch to avoid InexactError with Integers\ngauss_jordan(A::AbstractMatrix{T}) where {T<:Integer} = gauss_jordan(convert(Matrix{Float64}, A))\n", "meta": {"hexsha": "82b66ebe51634661f340ea20622ceeacd5dc1221", "size": 2221, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/matrix/gauss_jordan_elim.jl", "max_stars_repo_name": "frankschmitt/Julia", "max_stars_repo_head_hexsha": "c94cf524ad5d3221e05a4967fd088145d9c51a33", "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/matrix/gauss_jordan_elim.jl", "max_issues_repo_name": "frankschmitt/Julia", "max_issues_repo_head_hexsha": "c94cf524ad5d3221e05a4967fd088145d9c51a33", "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/matrix/gauss_jordan_elim.jl", "max_forks_repo_name": "frankschmitt/Julia", "max_forks_repo_head_hexsha": "c94cf524ad5d3221e05a4967fd088145d9c51a33", "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": 38.2931034483, "max_line_length": 138, "alphanum_fraction": 0.5484016209, "num_tokens": 597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422158380862, "lm_q2_score": 0.924141827813457, "lm_q1q2_score": 0.8789903058551506}}
{"text": "\"\"\"\n    tern2cart(a, b, c)\n\nTakes a point in the ternary coordinate system and returns the cartesian co-ordinate of this point.\nThe ternary axes are all between 0 and 1 and the cartesian co-ordinates form an equilateral triangle at (0, 0), (1, 0), (1/2, \u221a3/2)\n\"\"\"\ntern2cart(a, b, c) = (1 / 2 * (2b + c) / (a + b + c), \u221a3 / 2 * (c / (a + b + c)))\ntern2cart(vec) = tern2cart(vec[1], vec[2], vec[3])\n\n\"\"\"\n    cart2tern(x, y)\n\nTakes a point in the cartesian coordinate system and returns the ternary co-ordinate of this point.\n\"\"\"\nfunction cart2tern(x, y)\n    c = (2 * y) / \u221a3\n    b = x - c / 2\n    a = 1 - b - c\n    return (a, b, c)\nend\ncart2tern(array) = cart2tern(array[1], array[2])\n", "meta": {"hexsha": "90fad2dbf93c60a75c719be6752a533e49fa862d", "size": 683, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/user_helpers.jl", "max_stars_repo_name": "jacobusmmsmit/TernaryPlots.jl", "max_stars_repo_head_hexsha": "4a7f710688c2b9ec702bb836a8306e1010a36721", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2021-03-24T00:05:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T11:31:29.000Z", "max_issues_repo_path": "src/user_helpers.jl", "max_issues_repo_name": "jacobusmmsmit/TernaryPlots.jl", "max_issues_repo_head_hexsha": "4a7f710688c2b9ec702bb836a8306e1010a36721", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-03-24T10:47:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-13T20:24:06.000Z", "max_forks_repo_path": "src/user_helpers.jl", "max_forks_repo_name": "jacobusmmsmit/TernaryPlots.jl", "max_forks_repo_head_hexsha": "4a7f710688c2b9ec702bb836a8306e1010a36721", "max_forks_repo_licenses": ["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.0454545455, "max_line_length": 131, "alphanum_fraction": 0.6105417277, "num_tokens": 248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9805806478450307, "lm_q2_score": 0.8962513738264114, "lm_q1q2_score": 0.8788467527787013}}
{"text": "\"Square the sum of the numbers up to the given number\" # These descriptions were the wrong way round in the skeleton\n# I knew GCSE maths would come in handy one day\n# a = 1 + 2 + ... + n\n# b = n + ... + 2 + 1\n# a+b = n(n+1)\n# => sum = n(n+1) \u00f7 2 # even * odd = even\nfunction square_of_sum(n::Integer)\n#   These two lines are just as fast as each other: it turns out that Julia knows GCSE maths too\n#   (see sum(::Abstractrange{<:Real}) in base/range.jl)\n#   (n*(n+1) \u00f7 2) ^ 2\n    sum(Base.OneTo(n))^2\nend\n\n# a = 1^2 + 2^2 + ... + n\n# b = n^2 + (n-1)^2 + ...\n#\n# Telescoping series trick:\n# sum(k^2 - (k-1)^2) = n^2\n# k^2 - (k^2 - 2k +1) = 2k - 1\n# => sum(k^2 - (k-1)^2) = sum(2k - 1) = 2*sum(k) - n = n^2 => sum(k) = (n^2 + n) / 2\n#\n# We want sum([telescoping thing]) \u221d (sum(k^2) + tractable stuff)\n# => try sum(k^3 - (k-1)^3) = n^3\n# = sum(k^3 - (k-1)(k^2 - 2k +1)) = sum(k^3 - (k^3 -3k^2 +3k -1)) = sum(3k^2 - 3k +1) = 3*sum(k^2) - 3*sum(k) + n = n^3\n# => sum(k^2) = 1/3 * (n^3 - n + 3(n(n+1))/2) = 1/3 n^3 + 1/2 n^2 + 1/6 n = n/6 * (2n^2 + 3n + 1) = n/6 * (2n + 1)(n + 1)\n#\n# Slightly faster way of getting this:\n# ```\n# using SymPy\n# @vars(k,n)\n# summation(k^2,(k,(1,n)))\n# ```\n#\n# Can turn it into a function with summation(...).evalf() but it uses Python so it's slow - better off copying it out manually\n\"Sum the squares of the numbers up to the given number\" # These descriptions were the wrong way round in the skeleton\nfunction sum_of_squares(n::Integer)\n    n*(2n+1)*(n+1) \u00f7 6\nend\n\n\"Subtract sum of squares from square of sums\"\nfunction difference(n::Integer)\n    square_of_sum(n) - sum_of_squares(n) \nend\n", "meta": {"hexsha": "5416ac1301d2502e8b9c49a4e62ee15e57589c27", "size": 1617, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "difference-of-squares/difference-of-squares.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": "difference-of-squares/difference-of-squares.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": "difference-of-squares/difference-of-squares.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": 36.75, "max_line_length": 126, "alphanum_fraction": 0.5745207174, "num_tokens": 673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122720843812, "lm_q2_score": 0.9173026612812898, "lm_q1q2_score": 0.8786954764570098}}
{"text": "##################### Question 1 #####################\r\n\r\nfunction bisect_left(A, p, r, v)\r\n    i = p\r\n    if p < r\r\n       q = floor(Int, (p+r)/2)\r\n       if v <= A[q]\r\n           i = bisect_left(A, p, q, v)\r\n       else\r\n           i = bisect_left(A, q+1, r, v)\r\n       end\r\n    end\r\n    return i\r\nend\r\n\r\nfunction bisect_right(A, p, r, v)\r\n    i = p\r\n    if p < r\r\n       q = floor(Int, (p+r)/2)\r\n       if v < A[q]\r\n           i = bisect_right(A, p, q, v)\r\n       else\r\n           i = bisect_right(A, q+1, r, v)\r\n       end\r\n    end\r\n    return i\r\nend\r\n\r\n##################### Question 2 #####################\r\n\r\nfunction bisect(A, p, r, v)\r\n    while (p <= r)\r\n        q = floor(Int, (p+r/2))\r\n        if (v == A[q]) return q\r\n        elseif (v < A[q]) r = q-1\r\n        else p = q+1\r\n        end\r\n    end\r\n    return nothing\r\nend\r\n\r\nfunction qsort!(A, lo, hi) # lo - low, hi - high\r\n    i, j = lo, hi\r\n    while i < hi # iterate from \"low\" to \"high\" in relevant partition\r\n        pivot = A[(lo+hi)>>>1] # logical shift (low+high) bits right to divide them by 2\r\n        while i <= j\r\n            while A[i] < pivot; i = i+1; end # find index less than pivot\r\n            while A[j] > pivot; j = j-1; end # find index bigger than pivot\r\n            if i <= j\r\n                A[i], A[j] = A[j], A[i] # change places of the lesser and bigger element\r\n                i, j = i+1, j-1 # next index towards middle\r\n            end\r\n        end\r\n        if lo < j; qsort!(A,lo,j); end # call qsort on bottom partition\r\n        lo, j = i, hi # start over again with the top partition\r\n    end\r\n    return A\r\nend\r\n\r\nfunction algdat_sort!(A) # quicksort\r\n    p = 1\r\n    r = length(A)\r\n    qsort!(A, p, r)\r\nend\r\n\r\nfunction find_median(A, lower, upper)\r\n    lo = bisect_left(A, 1, length(A)+1, lower) # lower index of interval\r\n    hi = bisect_right(A, 1, length(A)+1, upper) - 1 # upper index of interval (-1 to return the actual last idx containing this value, not to the next)\r\n\r\n    ctr = (lo+hi)/2 # float or integer if size of array is even or odd\r\n    ctrLeft = (floor(Int, ctr))\r\n\r\n    if (ctrLeft == ctr) # if array is odd, ctr index is an integer and its value the median (comparing floats)\r\n        return A[Int(ctr)]\r\n    else # else find median of the values to the left and right of the floating idx value\r\n        return (A[ctrLeft] + A[ctrLeft+1]) / 2\r\n    end\r\nend\r\n", "meta": {"hexsha": "cfa29a3552d1260716c927f84924c0ede96b5ad0", "size": 2377, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "assignment-03/assignment-03.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-03/assignment-03.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-03/assignment-03.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": 30.0886075949, "max_line_length": 152, "alphanum_fraction": 0.5048380311, "num_tokens": 718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632316144274, "lm_q2_score": 0.9230391643039739, "lm_q1q2_score": 0.8786070418410611}}
{"text": "using Random, Distributions\n\nfunction normal_approximation_to_binomial(n, p)\n    mu = n * p\n    sigma = sqrt(n * (1-p) * p)\n    return mu, sigma \nend\n\nfunction normal_cdf(lo, mu=0, sigma=1)\n   return cdf(Normal(mu, sigma), lo) \nend\n\n# function normal_probability_below(lo, mu=0, sigma=1)\n#   return normal_cdf(lo, mu, sigma)\n# end\n\nfunction normal_probability_above(lo, mu=0, sigma=1)\n   return 1 - normal_cdf(lo, mu, sigma)\nend\n\nfunction normal_probability_between(lo, hi, mu=0, sigma=1)\n   return normal_cdf(hi,mu, sigma) - normal_cdf(lo, mu, sigma)\nend\n\nfunction normal_probability_outside(lo, hi, mu=0, sigma=1)\n    return 1 - normal_probability_between(lo, hi, mu, sigma)\nend\n\n@assert normal_cdf(0, 0 ,1)==0.5\n\n\nfunction normal_upper_bound(probability, mu=0, sigma=1)\n   return quantile(Normal(mu, sigma), probability)\nend\n\nfunction normal_lower_bound(probability, mu=0, sigma=1)\n   return quantile(Normal(mu, sigma), 1 - probability)   \nend\n\nfunction normal_two_sided_bounds(probability, mu=0, sigma=1)\n   tail_probability = (1 - probability)/2\n\n   upper_bound = normal_lower_bound(tail_probability, mu, sigma)\n\n   lower_bound = normal_upper_bound(tail_probability, mu, sigma)\n\n   return  lower_bound, upper_bound\nend\n\nmu_0, sigma_0 = normal_approximation_to_binomial(1000, 0.5)\n\n@assert mu_0 == 500 \n@assert 15.8 < sigma_0 < 15.9\n# 95% bounds based on assumption p is 0.5\nlo, hi = normal_two_sided_bounds(0.95, mu_0, sigma_0)\n\n# actual mu and sigma based on p = 0.55\nmu_1, sigma_1 = normal_approximation_to_binomial(1000, 0.55)\n\n# a type 2 error means we fail to reject the null hypothesis\n# which will happen when X is still in our original interval\ntype_2_probability = normal_probability_between(lo, hi, mu_1, sigma_1)\npower = 1 - type_2_probability      # 0.887\n@assert 0.886 < power < 0.888\n\nfunction two_sided_p_value(x, mu = 0, sigma = 1)\n    \"\"\"\n    How likely are we to see a value at least as extreme as x (in either\n    direction) if our values are from a N(mu, sigma)?\n    \"\"\"\n   if (x >= mu)\n        # x is greater than the mean, so the tail is everything greater than x\n        return 2 * normal_probability_above(x, mu, sigma) \n   else\n        # x is less than the mean, so the tail is everything less than x\n        return 2 * normal_probability_below(x, mu, sigma)\n   end\nend\n\n\ntwo_sided_p_value(529.5, mu_0, sigma_0)   # 0.062\n\n# TODO: Add julia code Monte-Carlo simulation\n\n\n\ntwo_sided_p_value(531.5, mu_0, sigma_0)   # 0.0463\n\n# TODO: Two sided tests\n\n\np_hat = 525 / 1000\nmu = p_hat\nsigma = sqrt(p_hat * (1 - p_hat) / 1000)   # 0.0158\n\nnormal_two_sided_bounds(0.95, mu, sigma)        # [0.4940, 0.5560]\n\np_hat = 540 / 1000\nmu = p_hat\nsigma = sqrt(p_hat * (1 - p_hat) / 1000) # 0.0158\nnormal_two_sided_bounds(0.95, mu, sigma) # [0.5091, 0.5709]", "meta": {"hexsha": "864bd9deeaa2d55fe341671c75ef0fa0365d4a80", "size": 2770, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scratch/julia/ch7-hypo.jl", "max_stars_repo_name": "vettukal/data-science-from-scratch.jl", "max_stars_repo_head_hexsha": "5404d308ab9aee1fcbe9d7b4bbeb347ef636b234", "max_stars_repo_licenses": ["MIT"], "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/julia/ch7-hypo.jl", "max_issues_repo_name": "vettukal/data-science-from-scratch.jl", "max_issues_repo_head_hexsha": "5404d308ab9aee1fcbe9d7b4bbeb347ef636b234", "max_issues_repo_licenses": ["MIT"], "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/julia/ch7-hypo.jl", "max_forks_repo_name": "vettukal/data-science-from-scratch.jl", "max_forks_repo_head_hexsha": "5404d308ab9aee1fcbe9d7b4bbeb347ef636b234", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4257425743, "max_line_length": 78, "alphanum_fraction": 0.7050541516, "num_tokens": 896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140216112959, "lm_q2_score": 0.9086179012632543, "lm_q1q2_score": 0.8785553890184685}}
{"text": "\"\"\"\n`hilbert(n)` creates an `n`-by-`n` Hilbert matrix.\n\n## Example\n```\njulia> hilbert(4)\n4\u00d74 Array{Rational{Int64},2}:\n 1//1  1//2  1//3  1//4\n 1//2  1//3  1//4  1//5\n 1//3  1//4  1//5  1//6\n 1//4  1//5  1//6  1//7\n```\n\"\"\"\nfunction hilbert(n::Int)\n    A = zeros(Rational{Int}, n, n)\n    for i = 1:n\n        for j = 1:n\n            A[i, j] = 1 // (i + j - 1)\n        end\n    end\n    return A\nend\n\n", "meta": {"hexsha": "933dee57972c45fdb2fcf164bc202b70e62de062", "size": 396, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "extras/hilbert.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": "extras/hilbert.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": "extras/hilbert.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": 16.5, "max_line_length": 50, "alphanum_fraction": 0.4545454545, "num_tokens": 197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9724147169737825, "lm_q2_score": 0.9032942132122422, "lm_q1q2_score": 0.8783765866848381}}
{"text": "# function to determine whether an x, y point is in the unit circle\nfunction in_circle(x_pos::Float64, y_pos::Float64, radius::Float64)\n    if (x_pos^2 + y_pos^2 < radius^2)\n        return true\n    else\n        return false\n    end\nend\n\n# function to integrate a unit circle to find pi via monte_carlo\nfunction monte_carlo(n::Int64, radius::Float64)\n\n    pi_count = 0\n    for i = 1:n\n        point_x = rand()\n        point_y = rand()\n\n        if (in_circle(point_x, point_y, radius))\n            pi_count += 1\n        end\n    end\n\n    pi_estimate = 4*pi_count/(n*radius^2)\n    println(\"Percent error is: \", signif(100*(pi - pi_estimate)/pi, 3), \" %\")\nend\n\nmonte_carlo(10000000, 0.5)\n", "meta": {"hexsha": "818d60efb116f6b116004c07f813006a3b0b6298", "size": 683, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "chapters/monte_carlo/code/julia/monte_carlo.jl", "max_stars_repo_name": "chrisb2244/algorithm-archive", "max_stars_repo_head_hexsha": "a30a088dc57f73c24724e9adcf45131c34ec2829", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-08-16T17:42:24.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-16T17:42:24.000Z", "max_issues_repo_path": "chapters/monte_carlo/code/julia/monte_carlo.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/monte_carlo/code/julia/monte_carlo.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": 24.3928571429, "max_line_length": 77, "alphanum_fraction": 0.6281112738, "num_tokens": 210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693241982893259, "lm_q2_score": 0.9059898279984214, "lm_q1q2_score": 0.8781978636828541}}
{"text": "export differentiate\n\n#################################################################\n#\n# differentiate()\n#   based on John's differentiate and this code, I think by Miles Lubin:\n#     https://github.com/IainNZ/NLTester/blob/master/julia/nlp.jl#L74\n#\n#################################################################\n\ndifferentiate(ex::SymbolicVariable, wrt::SymbolicVariable) = (ex == wrt) ? 1 : 0\n\ndifferentiate(ex::Number, wrt::SymbolicVariable) = 0\n\nfunction differentiate(ex::Expr,wrt)\n    if ex.head != :call\n        error(\"Unrecognized expression $ex\")\n    end\n    simplify(differentiate(SymbolParameter(ex.args[1]), ex.args[2:end], wrt))\nend\n\ndifferentiate{T}(x::SymbolParameter{T}, args, wrt) = error(\"Derivative of function \" * string(T) * \" not supported\")\n\n# The Power Rule:\nfunction differentiate(::SymbolParameter{:^}, args, wrt)\n    x = args[1]\n    y = args[2]\n    xp = differentiate(x, wrt)\n    yp = differentiate(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 differentiate(::SymbolParameter{:+}, args, wrt)\n    termdiffs = Any[:+]\n    for y in args\n        x = differentiate(y, wrt)\n        if x != 0\n            push!(termdiffs, x)\n        end\n    end\n    if (length(termdiffs) == 1)\n        return 0\n    elseif (length(termdiffs) == 2)\n        return termdiffs[2]\n    else\n        return Expr(:call, termdiffs...)\n    end\nend\n\nfunction differentiate(::SymbolParameter{:-}, args, wrt)\n    termdiffs = Any[:-]\n    # first term is special, can't be dropped\n    term1 = differentiate(args[1], wrt)\n    push!(termdiffs, term1)\n    for y in args[2:end]\n        x = differentiate(y, wrt)\n        if x != 0\n            push!(termdiffs, x)\n        end\n    end\n    if term1 != 0 && length(termdiffs) == 2 && length(args) >= 2\n        # if all of the terms but the first disappeared, we just return the first\n        return term1\n    elseif (term1 == 0 && length(termdiffs) == 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 differentiate(::SymbolParameter{:*}, args, wrt)\n    n = length(args)\n    res_args = Array(Any, n)\n    for i in 1:n\n       new_args = Array(Any, n)\n       for j in 1:n\n           if j == i\n               new_args[j] = differentiate(args[j], wrt)\n           else\n               new_args[j] = args[j]\n           end\n       end\n       res_args[i] = Expr(:call, :*, new_args...)\n    end\n    return Expr(:call, :+, res_args...)\nend\n\n# The Quotient Rule\n# d/dx (f / g) = ((d/dx f) * g - f * (d/dx g)) / g^2\nfunction differentiate(::SymbolParameter{:/}, args, wrt)\n    x = args[1]\n    y = args[2]\n    xp = differentiate(x, wrt)\n    yp = differentiate(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\nsymbolic_derivative_1arg_list = [\n    ( :sqrt,        :(  1 / 2 / sqrt(x)                         ))\n    ( :cbrt,        :(  1 / 3 / cbrt(x)^2                       ))\n    ( :abs2,        :(  1 * 2 * x                               ))\n    ( :inv,         :( -1 * abs2(inv(x))                        ))\n    ( :log,         :(  1 / x                                   ))\n    ( :log10,       :(  1 / x / log(10)                         ))\n    ( :log2,        :(  1 / x / log(2)                          ))\n    ( :log1p,       :(  1 / (x + 1)                             ))\n    ( :exp,         :(  exp(x)                                  ))\n    ( :exp2,        :(  log(2) * exp2(x)                        ))\n    ( :expm1,       :(  exp(x)                                  ))\n    ( :sin,         :(  cos(x)                                  ))\n    ( :cos,         :( -sin(x)                                  ))\n    ( :tan,         :(  (1 + tan(x)^2)                          ))\n    ( :sec,         :(  sec(x) * tan(x)                         ))\n    ( :csc,         :( -csc(x) * cot(x)                         ))\n    ( :cot,         :( -(1 + cot(x)^2)                          ))\n    ( :sind,        :(  pi / 180 * cosd(x)                      ))\n    ( :cosd,        :( -pi / 180 * sind(x)                      ))\n    ( :tand,        :(  pi / 180 * (1 + tand(x)^2)              ))\n    ( :secd,        :(  pi / 180 * secd(x) * tand(x)            ))\n    ( :cscd,        :( -pi / 180 * cscd(x) * cotd(x)            ))\n    ( :cotd,        :( -pi / 180 * (1 + cotd(x)^2)              ))\n    ( :asin,        :(  1 / sqrt(1 - x^2)                       ))\n    ( :acos,        :( -1 / sqrt(1 - x^2)                       ))\n    ( :atan,        :(  1 / (1 + x^2)                           ))\n    ( :asec,        :(  1 / abs(x) / sqrt(x^2 - 1)              ))\n    ( :acsc,        :( -1 / abs(x) / sqrt(x^2 - 1)              ))\n    ( :acot,        :( -1 / (1 + x^2)                           ))\n    ( :asind,       :(  180 / pi / sqrt(1 - x^2)                ))\n    ( :acosd,       :( -180 / pi / sqrt(1 - x^2)                ))\n    ( :atand,       :(  180 / pi / (1 + x^2)                    ))\n    ( :asecd,       :(  180 / pi / abs(x) / sqrt(x^2 - 1)       ))\n    ( :acscd,       :( -180 / pi / abs(x) / sqrt(x^2 - 1)       ))\n    ( :acotd,       :( -180 / pi / (1 + x^2)                    ))\n    ( :sinh,        :(  cosh(x)                                 ))\n    ( :cosh,        :(  sinh(x)                                 ))\n    ( :tanh,        :(  sech(x)^2                               ))\n    ( :sech,        :( -tanh(x) * sech(x)                       ))\n    ( :csch,        :( -coth(x) * csch(x)                       ))\n    ( :coth,        :( -csch(x)^2                               ))\n    ( :asinh,       :(  1 / sqrt(x^2 + 1)                       ))\n    ( :acosh,       :(  1 / sqrt(x^2 - 1)                       ))\n    ( :atanh,       :(  1 / (1 - x^2)                           ))\n    ( :asech,       :( -1 / x / sqrt(1 - x^2)                   ))\n    ( :acsch,       :( -1 / abs(x) / sqrt(1 + x^2)              ))\n    ( :acoth,       :(  1 / (1 - x^2)                           ))\n    ( :deg2rad,     :(  pi / 180                                ))\n    ( :rad2deg,     :(  180 / pi                                ))\n    ( :erf,         :(  2 * exp(-x*x) / sqrt(pi)                ))\n    ( :erfinv,      :(  0.5 * sqrt(pi) * exp(erfinv(x) * erfinv(x))  ))\n    ( :erfc,        :( -2 * exp(-x*x) / sqrt(pi)                ))\n    ( :erfcinv,     :( -0.5 * sqrt(pi) * exp(erfcinv(x) * erfcinv(x))  ))\n    ( :erfi,        :(  2 * exp(x*x) / sqrt(pi)                 ))\n    ( :gamma,       :(  digamma(x) * gamma(x)                   ))\n    ( :lgamma,      :(  digamma(x)                              ))\n    ( :digamma,     :(  trigamma(x)                             ))\n    ( :invdigamma,  :(  inv(trigamma(invdigamma(x)))            ))\n    ( :trigamma,    :(  polygamma(2, x)                         ))\n    ( :airy,        :(  airyprime(x)                            ))  # note: only covers the 1-arg version\n    ( :airyprime,   :(  x * airy(x)                             ))\n    ( :airyai,      :(  airyaiprime(x)                          ))\n    ( :airybi,      :(  airybiprime(x)                          ))\n    ( :airyaiprime, :(  x * airyai(x)                           ))\n    ( :airybiprime, :(  x * airybi(x)                           ))\n    ( :besselj0,    :( -besselj1(x)                             ))\n    ( :besselj1,    :(  (besselj0(x) - besselj(2, x)) / 2       ))\n    ( :bessely0,    :( -bessely1(x)                             ))\n    ( :bessely1,    :(  (bessely0(x) - bessely(2, x)) / 2       ))\n    ( :erfcx,       :(  (2 * x * erfcx(x) - 2 / sqrt(pi))       ))\n    ( :dawson,      :(  (1 - 2x * dawson(x))                    ))\n\n]\n\n\n# This is the public interface for accessing the list of symbolic\n# derivatives. The format is a list of (Symbol,Expr) tuples\n# (:f, deriv_expr), where deriv_expr is a symbolic\n# expression for the first derivative of the function f.\n# The symbol :x is used within deriv_expr for the point at\n# which the derivative should be evaluated.\nsymbolic_derivatives_1arg() = symbolic_derivative_1arg_list\nexport symbolic_derivatives_1arg\n\n\n# deprecated: for backward compatibility with packages that used\n# this unexported interface.\nderivative_rules = Array(@Compat.compat(Tuple{Symbol,Expr}),0)\nfor (s,ex) in symbolic_derivative_1arg_list\n    push!(derivative_rules, (s, :(xp*$ex)))\nend\n\n\nfor (funsym, exp) in symbolic_derivative_1arg_list\n    @eval function differentiate(::SymbolParameter{$(Meta.quot(funsym))}, args, wrt)\n        x = args[1]\n        xp = differentiate(x, wrt)\n        if xp != 0\n            return @sexpr(xp*$exp)\n        else\n            return 0\n        end\n    end\nend\n\nderivative_rules_bessel = [\n    ( :besselj,    :(    (besselj(nu - 1, x) - besselj(nu + 1, x)) / 2   ))\n    ( :besseli,    :(    (besseli(nu - 1, x) + besseli(nu + 1, x)) / 2   ))\n    ( :bessely,    :(    (bessely(nu - 1, x) - bessely(nu + 1, x)) / 2   ))\n    ( :besselk,    :( -1 * (besselk(nu - 1, x) + besselk(nu + 1, x)) / 2   ))\n    ( :hankelh1,   :(    (hankelh1(nu - 1, x) - hankelh1(nu + 1, x)) / 2 ))\n    ( :hankelh2,   :(    (hankelh2(nu - 1, x) - hankelh2(nu + 1, x)) / 2 ))\n]\n\n\n# This is the public interface for accessing the list of symbolic\n# derivatives. The format is a list of (Symbol,Expr) tuples\n# (:f, deriv_expr), where deriv_expr is a symbolic\n# expression for the first derivative of the function f with respect to x.\n# The symbol :nu and :x are used within deriv_expr\n# :nu specifies the first parameter of the bessel\n# function (usually written n or alpha)\n# :x gives the point at which the derivative should be evaluated.\nsymbolic_derivative_bessel_list() = derivative_rules_bessel\nexport symbolic_derivative_bessel_list\n\n# 2-argument bessel functions\nfor (funsym, exp) in derivative_rules_bessel\n    @eval function differentiate(::SymbolParameter{$(Meta.quot(funsym))}, args, wrt)\n        nu = args[1]\n        x = args[2]\n        xp = differentiate(x, wrt)\n        if xp != 0\n            return @sexpr(xp*$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\n## Differentiate for piecewise functions defined using ifelse\nfunction differentiate(::SymbolParameter{:ifelse}, args, wrt)\n    :(ifelse($(args[1]), $(differentiate(args[2],wrt)),$(differentiate(args[3],wrt))))\nend\n\nfunction differentiate(ex::Expr, targets::Vector{Symbol})\n    n = length(targets)\n    exprs = Array(Any, 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)\ndifferentiate(s::Compat.AbstractString, target...) = differentiate(parse(s), target...)\ndifferentiate(s::Compat.AbstractString, target::Compat.AbstractString) = differentiate(parse(s), symbol(target))\ndifferentiate{T <: Compat.AbstractString}(s::Compat.AbstractString, targets::Vector{T}) = differentiate(parse(s), map(symbol, targets))\n", "meta": {"hexsha": "e9b45b81d98a6410530490a34376ddd5747209dc", "size": 11345, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/differentiate.jl", "max_stars_repo_name": "JuliaPackageMirrors/Calculus.jl", "max_stars_repo_head_hexsha": "ae95d7fb9859d87b68c57909157fe509ec2fb7ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/differentiate.jl", "max_issues_repo_name": "JuliaPackageMirrors/Calculus.jl", "max_issues_repo_head_hexsha": "ae95d7fb9859d87b68c57909157fe509ec2fb7ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/differentiate.jl", "max_forks_repo_name": "JuliaPackageMirrors/Calculus.jl", "max_forks_repo_head_hexsha": "ae95d7fb9859d87b68c57909157fe509ec2fb7ce", "max_forks_repo_licenses": ["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.3736654804, "max_line_length": 135, "alphanum_fraction": 0.4397531952, "num_tokens": 3439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693241965169938, "lm_q2_score": 0.9059898153067649, "lm_q1q2_score": 0.8781978497748095}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.18\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 938f32d0-4dc2-11eb-29e1-19b4e28bf3c8\nusing BenchmarkTools, Random, DataFrames, Plots\n\n# \u2554\u2550\u2561 12341f32-4dbf-11eb-1753-6fac96fd666a\nmd\"\"\"\n# Ancient Algorithms\n\nThe concept of algorithm has existed since ancient ages. Babylonian (c. 2500 BC) and Egyptian (c. 1550 BC) used arithmetic algorithms for example division. Greek mathematicians used the sieve of Eratosthenes for finding prime numbers, and the Euclidean algorithm for finding the greatest common divisor of two numbers.\n\n\nThe word algorithm itself was derived from the name of the 9th-century Persian mathematician Mu\u1e25ammad ibn M\u016bs\u0101 al-Khw\u0101rizm\u012b (c. 780\u2013850) , whose name (Khwarazm) was Latinized as Algoritmi.\n\"\"\"\n\n# \u2554\u2550\u2561 10ef1d92-4dc0-11eb-3524-bd5cb089a31b\nmd\"\"\"\n## The Peasant Multiplication\n\nOrigin: Russian and Egyptian\n\nIdea: To multiply two positive integers a and b, \n- we can instead compute (a/2)*(2b) if a is even and \n- ((a \u2212 1)/2) * (2b) + b if a is odd.\n\n**Algorithm Analysis:**\n- a is reduced by at least a factor of 2, at the cost of one halving, one doubling, and possibly one addition.\n- If we assume that halving, doubling, and addition are all constant-time operations, then the total computational complexity of the algorithm is proportional to the number of binary digits of a.\n- Converges to correct answer\n\"\"\"\n\n# \u2554\u2550\u2561 09744cea-4dc0-11eb-11b0-c7c6b42683bc\nhtml\"\"\"\n<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/HJ_PP5rqLg0\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen></iframe>\n\"\"\"\n\n# \u2554\u2550\u2561 aae2f0aa-4dbf-11eb-3f50-39e262cc1845\nfunction peasantprod(a::T, b::T) where T <: Integer\n    c = zero(T)\n    while a > one(T)\n        if isodd(a)\n            c = c + b\n        end\n        a = a >> 1 # divide a by 2\n        b = b << 1 # multiply b by 2\n    end\n    return c + b\nend\n\n# \u2554\u2550\u2561 81d2d826-4dc0-11eb-2efb-9f5ef5161edd\npeasantprod(10, 33)\n\n# \u2554\u2550\u2561 87f00406-4dc0-11eb-29b9-6b5c19d03b53\nmd\"\"\"\n## Babylonian Method for finding square root\n\nStill used by many calculators.\n\nIdea:\n\n$$x \\cdot \\frac{a}{x} = a = \\sqrt{a} \\sqrt{a}$$\n\n- If $x < \\sqrt{a}$, then $\\frac{a}{x} > \\sqrt{a}$\n- If $x > \\sqrt{a}$, then $\\frac{a}{x} < \\sqrt{a}$\n\nTake averge of the two\n\n$X_{n+1} = \\frac{X_n + \\frac{a}{X_n}}{2} = \\frac{X_n^2 + a}{2 X_n}$\n\n\n\"\"\"\n\n# \u2554\u2550\u2561 a78d5570-4dc0-11eb-37a8-adc45a4964ee\nfunction babylonian(a::T, tol::T) where T <: Real\n    x = one(T)  # start x at 1\n    while abs(x^2 - a) > tol  # convergence test\n        x = (x + c / x) / 2\n    end\n    return x\nend\n\n# \u2554\u2550\u2561 c0c78d52-4dc1-11eb-325d-81452aa6d218\n\n\n# \u2554\u2550\u2561 0dd9ea7c-4dc2-11eb-1b99-f7b120c21a70\nmd\"\"\"\n## [Sieve of Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) for finding primes\n\nIteratively mark of all composites of the identified prime.\n\n![Sieve of Eratosthenes](https://upload.wikimedia.org/wikipedia/commons/b/b9/Sieve_of_Eratosthenes_animation.gif)\n\n\"\"\"\n\n# \u2554\u2550\u2561 371f8004-4dc2-11eb-340e-c367fc0d718d\nbegin\n\tfunction es(n::Int)\n\t    isprime = trues(n)  # n-element vector of true-s\n\t    isprime[1] = false  # 1 is not a prime\n\t    for i in 2:isqrt(n)  # loop integers less or equal than sqrt(n)\n\t        if isprime[i]  # conditional evaluation\n\t            for j in i^2:i:n  # sequence with step i\n\t                isprime[j] = false \n\t                end\n\t            end\n\t        end\n\t    return filter(x -> isprime[x], 1:n)# filter using an anonymous function\n\t    end\n\t\n\tprintln(es(100))# print all primes less or equal than 100\n\t@time length(es(10^6))# check function execution time and memory usage\nend\n\n# \u2554\u2550\u2561 5a9e6414-4dc2-11eb-2ed3-8f6abe2b7847\nmd\"\"\"\n## Greatest Common Divisor (GCD)\n\nFor integers a and b (likely to be very large positive integers), GCD(a,b) is the largest integer d that divides both a and b. GCD is very important in number theory such as factorization, prime numbers and hence cryptography.\n\"\"\"\n\n# \u2554\u2550\u2561 61a2ce56-4dc2-11eb-3b58-df1a7f2bf4d6\nbegin\n\t\"\"\"GCD using the definition of GCD\"\"\"\n\tfunction GCDnaive(a,b)\n\t    largest = 0\n\t    for d in 1:min(a,b)   # runtime ~min(a,b)\n\t        if a%d==0 && b%d==0\n\t            largest = d\n\t        end\n\t    end\n\t    return largest\n\tend\n\t\n\t@assert GCDnaive(8,12)==4\n\t@benchmark GCDnaive(3918848,1653264)\nend\n\n# \u2554\u2550\u2561 c3fdeae2-4dc2-11eb-0d57-598c117205c7\nmd\"\"\"\n### Euclidean GCD\n\n**Lemma:**\n> Let $a'$ be the remainder when a is divided by b, then $$gcd(a,b) = gcd(a',b)= gcd(b,a')$$\n\n**Proof**\n- when a is divided by b, $a = b*q + a'$\n- now d divides a and b if and only if it divides $a'$ and $b$\n\nEach step reduces the size of the numbers by about a factor of 2. Takes about log(ab) steps\n\"\"\"\n\n# \u2554\u2550\u2561 e0401ae0-4dc2-11eb-2ba6-9d18e1915fa1\nbegin\n\tfunction GCDEuclid(a,b)\n\t    if b == 0 \n\t        return a\n\t    else\n\t        return GCDEuclid(b,a%b)\n\t    end\n\tend\n\t\n\t# onliner\n\tGCD(a,b) = b==0 ? a : GCD(b , a%b)\n\t\n\t@benchmark GCDEuclid(3918848,1653264)\nend\n\n# \u2554\u2550\u2561 f40e1e6e-4dc2-11eb-2c04-d7020e727f7f\nmd\"\"\"\n## Fibonacci Numbers\n\nDeveloped by to study Rabbit Population after multiple genertions\n\n$$F_n = \\begin{cases} 0, \\qquad n=0, \\\\ 1, \\qquad n=1, \\\\ F_{n+1} + F_{n+2}, \\quad n>1 \\end{cases}$$\n\nThis has a rapid growth. $F_n \\geq 2^{n/2} \\text{ for } n \\geq 6$\n\n\"\"\"\n\n# \u2554\u2550\u2561 02317fca-4dc3-11eb-34c4-a5e009b09775\nbegin\n\t\"\"\"Fibbonaci Implementation directly from definition\"\"\"\n\tfunction fibbo_naive(n::Integer)\n\t    n >= 0 || throw(DomainError(n, \"Domain: n \u2265 0\"))\n\t    if n <= 1\n\t        return n\n\t    else\n\t        return fibbo_naive(n-1) + fibbo_naive(n-2)\n\t    end\n\t    \n\tend\n\t\n\t# Do not try huge numbers here\n\t@assert fibbo_naive(1) == 1\n\t@assert fibbo_naive(7) == 13\t\nend\n\n# \u2554\u2550\u2561 1b865a74-4dc3-11eb-25ac-d56e25e7b4b6\nmd\"\"\"\nIf T(n) is the Lines of Code executed by the function on input n. If you step through the debugger you can calculate the number of lines  for the implementation.\n\n$$T(n) = \\begin{cases} 2, \\qquad n \\leq 1, \\\\ F_{n+1} + F_{n+2} + 3, \\quad n >1 \\end{cases}$$\n$$\\therefore T(n) \\geq F_n$$\n\n$T(100) \\approx 1.77 * 10^{21} \\approx 56000$ years at 1GHz\n\nWhy is this so slow?\n![Fibbonacci call stack](https://idawud.tech/assets/img/support/fibonacci_1.png)\nFor evaluating any number same number has to be evaluated multiple times eg f(3), f(2) has been repeatedly evaluated so many times, this increases exponentially when n is very large.\n\nWhen we calculate manually we don't redo such calculation but rather use only the last two numbers.\n\"\"\"\n\n# \u2554\u2550\u2561 0eea1918-4dc3-11eb-1484-b7f0db8d3a9a\nbegin\n\tfunction fibbo_efficient(n::Integer)\n\t    n >= 0 || throw(DomainError(n, \"Domain: n \u2265 0\"))\n\t    n <= 1 && return n\n\t    \n\t    Fn = zeros(Integer, n + 1)\n\t    Fn[1:2] = [0, 1]  # you can only store two numbers\n\t    \n\t    for i = 3:n+1 \n\t        Fn[i] = Fn[i-1] + Fn[i-2]\n\t    end\n\t    \n\t    return Fn[end]\n\tend\n\t\n\t@assert fibbo_efficient(7) == 13\n\t\n\t@benchmark fibbo_efficient(50)\nend\n\n# \u2554\u2550\u2561 b98372a2-4dc3-11eb-2956-69554b9ff7b8\nmd\"\"\"\n$$T(n) = \\begin{cases} 2, \\qquad n \\leq 1, \\\\ 2n + 3, \\quad n >1 \\end{cases}$$\n\n$T(100) \\approx 202$ Incredibly fast compared to above\n\"\"\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u250012341f32-4dbf-11eb-1753-6fac96fd666a\n# \u2560\u2550938f32d0-4dc2-11eb-29e1-19b4e28bf3c8\n# \u255f\u250010ef1d92-4dc0-11eb-3524-bd5cb089a31b\n# \u255f\u250009744cea-4dc0-11eb-11b0-c7c6b42683bc\n# \u2560\u2550aae2f0aa-4dbf-11eb-3f50-39e262cc1845\n# \u2560\u255081d2d826-4dc0-11eb-2efb-9f5ef5161edd\n# \u255f\u250087f00406-4dc0-11eb-29b9-6b5c19d03b53\n# \u2560\u2550a78d5570-4dc0-11eb-37a8-adc45a4964ee\n# \u2560\u2550c0c78d52-4dc1-11eb-325d-81452aa6d218\n# \u2560\u25500dd9ea7c-4dc2-11eb-1b99-f7b120c21a70\n# \u2560\u2550371f8004-4dc2-11eb-340e-c367fc0d718d\n# \u255f\u25005a9e6414-4dc2-11eb-2ed3-8f6abe2b7847\n# \u2560\u255061a2ce56-4dc2-11eb-3b58-df1a7f2bf4d6\n# \u255f\u2500c3fdeae2-4dc2-11eb-0d57-598c117205c7\n# \u2560\u2550e0401ae0-4dc2-11eb-2ba6-9d18e1915fa1\n# \u255f\u2500f40e1e6e-4dc2-11eb-2c04-d7020e727f7f\n# \u2560\u255002317fca-4dc3-11eb-34c4-a5e009b09775\n# \u255f\u25001b865a74-4dc3-11eb-25ac-d56e25e7b4b6\n# \u2560\u25500eea1918-4dc3-11eb-1484-b7f0db8d3a9a\n# \u255f\u2500b98372a2-4dc3-11eb-2956-69554b9ff7b8\n", "meta": {"hexsha": "f160286f0fbdf98006b3ba52a5c7310e2e5658bc", "size": 7923, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/Intro2DSA/AncientAlgo.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/Intro2DSA/AncientAlgo.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/Intro2DSA/AncientAlgo.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": 29.6741573034, "max_line_length": 318, "alphanum_fraction": 0.6722201186, "num_tokens": 3169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.9399133435142799, "lm_q1q2_score": 0.8773440745339818}}
{"text": "using Pkg\nPkg.activate(pwd())\n\n# # Arithmetic operators\n\n1 + 2\n2*3\n4/3\n\n#+\n\nx = 1;\ny = 3;\n\n(x + 2)/(y - 1) - 4*(x - 2)^2\n\n#+\n\n2(3 + 4) # equivalent to 2*(3 + 4)\n\n# ### Exercise:\n# Determine the value and type of $y$ given by the following expression\n# $$\n# y = \\frac{(x + 2)^2 - 4}{(x - 2)^{p - 2}},\n# $$\n# where $x = 4$ and $p = 5$.\n# \n# ---\n# ### Solution:\n\n\n\n# ---\n# \n# ## Promotion system\n\nx = 1.0 # Float64\ny = 2 # Int64\n\nxp, yp = promote(x, y)\n\ntypeof(xp)\ntypeof(yp)\n\n#+\n\npromote(1, 2f0, true, 4.5, Int32(1))\npromote_type(Float64, Int64, Bool, Int32)\n\n#+\n\nx = 1 # Int64\ny = 2f0 # Float32\nz = x + y\n\ntypeof(z)\n\n# ### Exercise:\n# All of these values represent number ``1``. Determine the smallest type which can\n# represent them.\n\nx = 1\ny = 1f0\nz = true\nw = Int32(1)\n\n# ---\n# ### Solution:\n\n\n\n# ---\n# \n# ## Updating operators\n\nx = 1\nx += 3 # x = x + 3\nx *= 4 # x = x * 4\nx /= 2 # x = x / 2\nx \\= 16 # x = x \\ 16 = 16 / x\n\n# ### Exercise:\n# Compute the value of $y$ given by the following expression\n# $$\n# y = \\frac{(x + 4)^{\\frac{3}{2}}}{(x + 1)^{p - 1}},\n# $$\n# where $x = 5$ and $p = 3$. Then multiply the result by $8$, add $3$, divide by $3$, and\n# subtract $1$. What are all the intermediate results and the final result?\n# \n# ---\n# ### Solution:\n\n\n\n# ---\n# \n# ## Numeric comparison\n\n1 == 1\n1 == 1.0\n\n#+\n\n-1 <= 1\n-1 \u2265 1\n\n#+\n\n3 > 2 > 1\n3 > 2 & 2 > 1\n\n#+\n\n1 < 2 <= 2 < 3 == 3 > 2 >= 1 == 1 < 3 != 5\n\n#+\n\nNaN == NaN\nNaN != NaN\nNaN < NaN\n\n#+\n\nisequal(NaN, NaN)\n!isequal(NaN, NaN)\n\n#+\n\n!true\n!false\n\n# ## Rounding functions\n\nx = 3141.5926\n\nround(x)\nfloor(x)\nceil(x)\n\n#+\n\nround(Int64, x)\nfloor(Int32, x)\nceil(Int16, x)\n\n#+\n\nround(x; digits = 3)\nround(x; sigdigits = 3)\n\n# ### Exercise:\n# Use rounding functions to solve the following tasks:\n# - Round `1252.1518` to the nearest larger integer and convert the resulting value to\n#   `Int64`.\n# - Round `1252.1518` to the nearest smaller integer and convert the resulting value to\n#   `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# ## Numerical Conversions\n\nconvert(Float32, 1.234)\nFloat32(1.234)\n\n#+\n\nconvert(Int64, 1.0)\nInt64(1.0)\n\n#+\n\nconvert(Int64, 1.234)\nInt64(1.234)\n\n# ### Exercise:\n# Use the proper numeric conversion to get the correct result (not approximate) of summing\n# the following two numbers\n# \n# ```julia\n# x = 1//3\n# y = 0.5\n# ```\n# \n# **Hint:** rational numbers can be summed without approximation.\n# \n# ---\n# ### Solution:\n", "meta": {"hexsha": "1fd05cdd4910f6abf6d5b2a192f3626925304fde", "size": 2506, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lecture_01/02-operators.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_01/02-operators.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_01/02-operators.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": 12.8512820513, "max_line_length": 90, "alphanum_fraction": 0.5630486832, "num_tokens": 948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039738, "lm_q2_score": 0.9504109749090952, "lm_q1q2_score": 0.8772665520254163}}
{"text": "# column\nunit_cost_c = [6 4 3 2 1]\n# row\namount_r = [2, 3, 4, 6, 12]\n\n# row * column adds up to a sum\nunit_cost_c * amount_r\n\nusing LinearAlgebra\n# define as row\nunit_cost = [6, 4, 3, 2, 1]\n# diagnol matrix times a vector gives a vector\nDiagonal(unit_cost) * amount_r\n\n#this obviously gives same answer as row 7 since transpose makes it a column\ntranspose(unit_cost) * amount_r\n\n# matrix with different orders in eacch column\namounts =  [6 1 10;\n            4 1 10;\n            3 1 10;\n            2 1 10;\n            1 1 10]\n\n# get the summed cost for each column order\ntranspose(unit_cost) * amounts\n\n# first row calculates sum based on unit costs (as before) \n# second row calculates average number of units (divide by 5 and sum)\noperations =   [6.0 4.0 3.0 2.0 1.0;\n                0.2 0.2 0.2 0.2 0.2]\noperations * amounts\n\n# identity operation\nDiagonal([1,1,1]) * [8,12,3]\n# I does it better\nI*[8,12,3]\nI*[8,12,3,5]\n\n# reverse operation - since this is part of base not sure why Engheim doesnt mention simple operator\nR =  [0 0 1;\n      0 1 0;\n      1 0 0]\n\nR * [8, 12, 3]\nreverse([8, 12, 3])\n# can also reverse a row\nreverse([8 12 3])\n# you can use multiplication on the matrix\n2I*[8, 12, 3]\n# more examples\nz = [1 2 3;\n     4 5 6;\n     7 8 9]\n\nI*z\n2*z\nreverse(z)\n2*reverse(z)\n# be careful with inverse\n#inv(z) # commented out see below\n# this gives you a singular exception. If you take the determinant you see it is ) which explains why\ndet(z)\n# a simple change solves the problem\nzf = [1 2 3;\n      4 5 6;\n      7 8 10]\ndet(zf)\ninv(zf)\n# rounding error for floating point doesnt create perfect identity\nIf = zf * inv(zf)\n# but its close enough\nI \u2248 If  # yields true\n\n# Back to Engheim\nA =   [1  1 -2;\n       1 -1 -1;\n       1  1  3]\n\nB = [3, 0, 12]\n\nX = inv(A)*B\n\nA*X\nB\nA*X \u2248 B  # yields true\n\n# concatenation\nC = [1 3 5]\nD = [7 9 11]\nE = [1, 3, 5]\nF = [7, 9, 11]\nG = [1 3 5; 2 4 6]\nH = [7 9 11; 8 10 12]\n\n# horizontal - dims indiccate which dimention \nhcat(C, D)\ncat(C, D, dims=2)\nhcat(E, F)\ncat(E, F, dims=2)\nhcat(G, H)\ncat(G, H, dims=2)\nhcat(G, 2G, 3G, 4G)\n\n\n# vertical\nvcat(C, D)\ncat(C, D, dims=1)\nvcat(E, F)\ncat(E, F, dims=1)\nvcat(G, H)\ncat(G, H, dims=1)\nvcat(C, D, C, D)\n\n# creating matrices\nzeros(Int8, 3, 4)\nones(Int8, 3, 4)\nrand(Int8, 3, 4)\nzeros(Float64, 3, 4)\nones(Float64, 3, 4)\nrand(Float64, 3, 4)\nfill(12, 3, 4)  #Int64\nfill(12.0, 3, 4) #Float64\nfill(1//2, 3, 4) #Rational{Int64}\nfill(0x4, 3, 4) #Int8\n\n# in the example on page 249 for vector addition this is what you are really seeing:\nu = [4,2]  # from the origin [0,0]\nv = [-1,1] # from the starting point [4,2]\nu + v \n# yields:\n# 2-element Vector{Int64}:\n# 3\n# 3\n# scalar addition needs to be done per element\nu .+ 1\n# yields:\n# 2-element Vector{Int64}:\n# 5\n# 3\n# assignment of vectors\nw = v\nw == v # true\nw[1] = 1 # change w\nw == v # true\nv[2] = 2 # change v\nw == v # true\n# element wise assignment has different result in that w is NOT pointing to unit\n# w .= u is equivalent to w[1] = 4 and w[2] = 2 which obviously has no impact on u\nw .= u\nw == v # true\nw == u # true temporarily\nv == u # true temporarily\n# but\nw[1] = 1 # change w\nw == v # true\nw == u # false\nv == u # false\n# subtraction\nv = [-1, 1]\n# next two give same result. This also shows multiplying vector by scaler works as expected\nu + (-v)\nu - v\n# vector rotation\nx = [3, 4]\nxm = 3*[1, 0] + 4*[0, 1]\nx == xm # true\n# rotate x 90 degrees\nxmr = 3*[0, 1] + 4*[-1, 0]\n# do it as matrix multiplication - NB: Engheim got the matrix wrong \n# [0,1] and [-1, 0] are columns not rows so the matrix looks like A below\nA = [ 0 -1;\n      1 0]\n# a vector is a column not a row\n# multiply each row in the vector x times a column in A and add the two vectors together (as in xmr)\n# 3 is first row times [0, 1] + 4 is second row * [-1,0] giving vector (column) [-4, 3]\nA*x == xmr # true\n\n\n#rotation(degrees)\n#Create a rotation matrix for rotating a 2D vector `deg` degrees.\n\nfunction rotation(deg::Real)\n  rad = deg2rad(deg)\n  cos\u03b8 = cos(rad)\n  sin\u03b8 = sin(rad)\n  \n  [cos\u03b8 -sin\u03b8;\n   sin\u03b8  cos\u03b8] \nend\n\n# create a Matrix for rotating a vector 90 degrees\nM = rotation(90)\n\n# create a saaple [x,y] vector and rotate 90 degrees\nv = [3, 4]\nM*v\nv2 = [3, 3]\nM*v2\nv3 = [3, 0]\nM*v3\nv4 = [0, 3]\nM*v4\n\n# # Dot Product\n# # important you add \"using LinearAlgebra\" before running the following\n# a = [2, 3]\n# b = [3, 1]\n\n# # to get the dot product character type \"a \\cdot[tab] b\" (i.e. thit the tab key)\n# a \u22c5 b\n# transpose(a)*b\n# dot(a, b)\n\n# # Work equations\n# r = [3, 1]\n# # the norm is the sqrt of r \u22c5 r which gives the length of the vector r\n# # u is a unit vector with same direction as r (divide r by its lenght \n# # to get a vector lenght 1 with same direction as r)\n# u = r / norm(r)\n# # in the graph in the book Engheim shifts teh vector from the 0origin\n# F = [2, 3]\n# # the work\n# F \u22c5 u\n# # from this equality \u201c\ud835\udc05 \u22c5 \ud835\udc2e = |\ud835\udc05| cos \u03b8 \" we can calulate the angle \u03b8\n# \u03b8 = acos(F \u22c5 u/norm(F))\n# # check the equality\n# F \u22c5 u == norm(F) * cos(\u03b8)\n# # substitute back the defintion of u\n# F \u22c5 (r/norm(r)) == norm(F) * cos(\u03b8)\n# # multiply norm(r) to both sides of the equation (there are rounding errors)\n# F \u22c5 r \u2248 norm(F) * norm(r) * cos(\u03b8)\n# # Cross product\n# u = [6, 0, 0]\n# v = [3, 4, 0]\n# # \u2a2f is \\times\n# w = u \u2a2f v", "meta": {"hexsha": "5170276484ef468057ba60908e7ef7d421b9610c", "size": 5232, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "linearalgebra.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": "linearalgebra.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": "linearalgebra.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": 22.0759493671, "max_line_length": 101, "alphanum_fraction": 0.619266055, "num_tokens": 2034, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545289551957, "lm_q2_score": 0.925229964823448, "lm_q1q2_score": 0.8772609814724086}}
{"text": "using StatsFuns\nusing Base.Test\nusing Compat\n\n# xlogx & xlogy\n\nprintln(\"\\ttesting xlogx & xlogy ...\")\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# logistic & logit\n\nprintln(\"\\ttesting logistic & logit ...\")\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(logistic(2)) 2.0\n\n# log1psq\n\nprintln(\"\\ttesting log1psq ...\")\n\n@test_approx_eq log1psq(0.0) 0.0\n@test_approx_eq log1psq(1.0) log1p(1.0)\n@test_approx_eq log1psq(2.0) log1p(4.0)\n\n# log1pexp, log1mexp, log2mexp & logexpm1\n\nprintln(\"\\ttesting log1pexp ...\")\n\n@test_approx_eq log1pexp(2.0) log(1.0 + exp(2.0))\n@test_approx_eq log1pexp(-2.0) log(1.0 + exp(-2.0))\n@test_approx_eq log1pexp(10000) 10000.0\n@test_approx_eq log1pexp(-10000) 0.0\n\nprintln(\"\\ttesting log1mexp ...\")\n\n@test_approx_eq log1mexp(-1.0) log1p(- exp(-1.0))\n@test_approx_eq log1mexp(-10.0) log1p(- exp(-10.0))\n\nprintln(\"\\ttesting log2mexp ...\")\n\n@test_approx_eq log2mexp(0.0) 0.0\n@test_approx_eq log2mexp(-1.0) log(2.0 - exp(-1.0))\n\nprintln(\"\\ttesting logexpm1 ...\")\n\n@test_approx_eq logexpm1(2.0) log(exp(2.0) - 1.0)\n@test_approx_eq logexpm1(log1pexp(2.0)) 2.0\n@test_approx_eq logexpm1(log1pexp(-2.0)) -2.0\n\n# log1pmx\n\nprintln(\"\\ttesting log1pmx ...\")\n\n@test_approx_eq log1pmx(0.0) 0.0\n@test_approx_eq log1pmx(1.0) log(2.0) - 1.0\n@test_approx_eq log1pmx(2.0) log(3.0) - 2.0\n\nprintln(\"\\ttesting logmxp1 ...\")\n\n@test_approx_eq logmxp1(1.0) 0.0\n@test_approx_eq logmxp1(2.0) log(2.0) - 1.0\n@test_approx_eq logmxp1(3.0) log(3.0) - 2.0\n\n# logsumexp\n\nprintln(\"\\ttesting logsumexp ...\")\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@test_approx_eq logsumexp([1.0, 2.0, 3.0]) 3.40760596444438\n@test_approx_eq logsumexp([1.0, 2.0, 3.0] .+ 1000.) 1003.40760596444438\n\n# softmax\n\nprintln(\"\\ttesting softmax ...\")\n\nx = [1.0, 2.0, 3.0]\nr = @compat exp.(x) ./ sum(exp.(x))\n@test_approx_eq softmax([1.0, 2.0, 3.0]) r\nsoftmax!(x)\n@test_approx_eq x r\n", "meta": {"hexsha": "429b4576742a4b0b0a78c968277f45944bfe718a", "size": 2087, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/basicfuns.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": "test/basicfuns.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": "test/basicfuns.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": 23.4494382022, "max_line_length": 71, "alphanum_fraction": 0.682798275, "num_tokens": 909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620562254525, "lm_q2_score": 0.9136765222384492, "lm_q1q2_score": 0.8769120577084945}}
{"text": "# Julian program to Find the n'th Catalan number\n# To know more about Catalan Numbers Visit Here : https://en.wikipedia.org/wiki/Catalan_number\n\n\nfunction find_catalan(n)\n    if (n == 0 || n == 1)\n        return 1\n    end\n\n    # DP Table \n    cat = [0 for i in 1:(n + 1)]\n\n    # Initialize the first to values\n    cat[1] = 1\n    cat[2] = 1\n    for i in 3:(n + 1)\n        for j in 1:(i - 1)\n            cat[i] = cat[i] +  (cat[j] * cat[i - j])\n        end\n    end\n    return cat[n + 1]\nend\n\nprint(\"Enter the number: \")\nnum = readline()\nnum = parse(Int, num)\ncatalan_number = find_catalan(abs(num))\nprintln(\"The $num'th catalan number is $catalan_number.\")\n\n\"\"\"\nTime Complexity: O(num^2), where 'num' is the given number\nSpace Complexity: O(num)\n\nSAMPLE INPUT AND OUTPUT\n\nSAMPLE 1\nEnter the number: 12\nThe 12'th catalan number is 208012.\n\nSAMPLE 2\nEnter the number: 2\nThe 2'th catalan number is 2.\n\n\"\"\"\n", "meta": {"hexsha": "ad5b4eedde714dc2ee2972ec91fd83ee8e4a6384", "size": 901, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/math/catalan_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/catalan_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/catalan_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": 20.0222222222, "max_line_length": 94, "alphanum_fraction": 0.6193118757, "num_tokens": 292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992914310606, "lm_q2_score": 0.9059898299021697, "lm_q1q2_score": 0.8769069144060572}}
{"text": "\"\"\"\n    cosine_similarity(u::AbstractVector, v::AbstractVector) -> Float\n\nCompute the cosine similarity of two vectors.\n\n# Examples\n\n```jldoctest\njulia> cosine_similarity([1, 0], [1, 0])\n1.0\n\njulia> round(cosine_similarity([1,1], [1,0]), digits=3)\n0.707\n\njulia> cosine_similarity([1, 0], [0, 1])\n0.0\n\njulia> cosine_similarity([-1, 0], [1, 0])\n-1.0\n\njulia> round(cosine_similarity([1,0,0], [1,1,1]), digits=3)\n0.577\n```\n\n\"\"\"\nfunction cosine_similarity(u::AbstractVector, v::AbstractVector)\n    u \u22c5 v / (norm(u) * norm(v))\nend\n\n\n\"\"\"\n    angle_between(u::AbstractVector, v::AbstractVector) -> Float\n\nCompute the angle between two vectors. The angle is returned in radians.\n\n# Examples\n\n```jldoctest\njulia> angle_between([1, 0], [1, 0])\n0.0\n\njulia> round(angle_between([1,1], [1,0]), digits=3)\n0.785\n\njulia> round(angle_between([1, 0], [0, 1]), digits=3)\n1.571\n\njulia> round(angle_between([-1, 0], [1, 0]), digits=3)\n3.142\n\njulia> round(angle_between([1,0,0], [1,1,1]), digits=3)\n0.955\n```\n\n\"\"\"\nfunction angle_between(u::AbstractVector, v::AbstractVector)\n    acos(cosine_similarity(u, v))\nend\n\n\n\"\"\"\n    distance(point_a::AbstractVector, point_b::AbstractVector) -> Float\n\nCompute the distance between two points.\n\n# Examples\n\n```jldoctest\njulia> distance([0, 0], [0, 0])\n0.0\n\njulia> distance([1, 0], [0, 0])\n1.0\n\njulia> round(distance([1, 1], [2, 2]), digits=3)\n1.414\n\njulia> round(distance([0, 0, 0], [-1, -1, -1]), digits=3)\n1.732\n```\n\n\"\"\"\nfunction distance(point_a::AbstractVector, point_b::AbstractVector)\n    return norm(Vector(point_a, point_b))\nend\n\n\n\"\"\"\n    distance(point_a::AbstractVector, line::AbstractLine) -> Float\n\nCompute the distance from a point to a line.\n\nThis is the distance from the point to its projection on the line.\n\n# Examples\n\n```jldoctest\njulia> distance([0, 0], Line([0, 0], [1, 0]))\n0.0\n\njulia> round(distance([1, 0], Line([0, 0], [1, 1])), digits=3)\n0.707\n\njulia> round(distance([1, 2, 3], Line([-1, 3, 2], [7, 4, 2])), digits=3)\n1.978\n```\n\n\"\"\"\nfunction distance(point::AbstractVector, line::AbstractLine)\n    point_projected = project(point, line)\n    return distance(point, point_projected)\nend\n", "meta": {"hexsha": "d67e38d3203fca9aba62a98b6a321e6d5d20a297", "size": 2127, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/computations/measurement.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/measurement.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/measurement.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": 18.8230088496, "max_line_length": 72, "alphanum_fraction": 0.662435355, "num_tokens": 722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.965899575269305, "lm_q2_score": 0.9073122150949273, "lm_q1q2_score": 0.8763724831968426}}
{"text": "using ApproxFun, Plots\n\n# In this example, we numerically compute with Galerkin orthogonal polynomials.\n# If H is a separable Hilbert space and B contains \u03bd linear functional constraints,\n# then the Galerkin orthogonal polynomials are those orthogonal polynomials with\n# respect to H_B := \\{ u \\in H : Bu = 0 \\}.\n# For example, if H = L^2([-1,1]) and we wish to enforce that u(-1) = u'(-1) =\n# u'(1) = 0, then the 2-normalized orthonormal polynomials may be created by\n# taking the QR factorization of the connection coefficients between the\n# normalized Legendre polynomials \\sqrt{n+1/2}P_n(x) and a degree-graded\n# polynomial basis that satisfies the constraints.\n\nN = 501\n\nNS = NormalizedLegendre()\nB = [Evaluation(NS, -1, 0); Evaluation(NS, -1, 1); Evaluation(NS, 1, 1)]\n\u03bd = size(B, 1)\nQS = QuotientSpace(B)\nA = Conversion(QS, NS)\nQ, R = qr(A[1:N+\u03bd,1:N])\n\np = Vector{Fun}(undef, N)\nfor n = 1:N\n    en = [zeros(n-1);1.0;zeros(N+\u03bd-n)]\n    p[n] = Conversion(NS, Legendre())*Fun(NS, (Q*en)[1:n+\u03bd])\n    pad!(p[n], 3n+50)\nend\n\n# The mass matrix with entries M_{i,j} = \\int_{-1}^1 p_i(x) p_j(x) dx,\n# is numerically the identity, as we expect.\n\nM = [innerproduct(p[i], p[j]) for i = 1:N, j = 1:N]\n@show norm(M-I) \u2264 4*norm(M)*eps()\n@show opnorm(M-I) \u2264 4*sqrt(N)*opnorm(M)*eps()\n\n# Although the polynomials now satisfy deg(p_n) = n+\u03bd instead of deg(p_n) = n,\n# the index appears to determine the number of roots of the Galerkin orthogonal\n# polynomials. In particular, p_n has exactly n roots in (-1,1).\n\npl = plot(p[1]; legend = false)\nfor n in 2:10\n    plot!(p[n])\nend\nplot(pl)\n\n# This need not be the case! If the second constraint is modified to impose\n# u'(0) = 0, then the odd-index polynomials have one more root than their index\n# and the even-index polynomials have one fewer.\n\nB = [Evaluation(NS, -1, 0); Evaluation(NS, 0, 1); Evaluation(NS, 1, 1)]\nQS = QuotientSpace(B)\nA = Conversion(QS, NS)\nQ, R = qr(A[1:N+\u03bd,1:N])\n\nq = Vector{Fun}(undef, N)\nfor n = 1:N\n    en = [zeros(n-1);1.0;zeros(N+\u03bd-n)]\n    q[n] = Conversion(NS, Legendre())*Fun(NS, (Q*en)[1:n+\u03bd])\n    pad!(q[n], 3n+50)\nend\n\npl = plot(q[1]; legend = false)\nfor n in 2:10\n    plot!(q[n])\nend\nplot(pl)\n\n# More information on Galerkin orthogonal polynomials is available in\n#\n#   P. W. Livermore. Galerkin orthogonal polynomials, J. Comp. Phys., 229:2046\u20132060, 2010.\n#\n# The banded QR factorization of the connection coefficients is a linear\n# complexity algorithm to represent the Galerkin orthogonal polynomials in H_B\n# in terms of the polynomial basis for H. This is described in\n#\n#   J. L. Aurentz and R. M. Slevinsky. On symmetrizing the ultraspherical spectral method for self-adjoint problems, arXiv:1903.08538, 2019.\n#\n", "meta": {"hexsha": "2797d803d9a9f697de628dddd0d1b03b8cfca6ff", "size": 2690, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Extras/GalerkinOrthogonalPolynomials.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/GalerkinOrthogonalPolynomials.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/GalerkinOrthogonalPolynomials.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": 34.4871794872, "max_line_length": 140, "alphanum_fraction": 0.6821561338, "num_tokens": 890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191284552528, "lm_q2_score": 0.9173026578901509, "lm_q1q2_score": 0.8763167756653059}}
{"text": "\"\"\"Julia program to check if a number is a Perfect number or not.\n    Perfect Number is a number if it is equal to the sum of its proper divisors excluding the number itself.\"\"\"\n\n\n\"\"\"Iterate from 1 till the square root of the given number.\n    Identify the divisors and take thier sum. And then check\n    If the sum is equal to given number\"\"\"\nfunction perfect_number(num)\n    # variable to store the sum of the proper divisors, initialized to one\n    sum = 1\n    # Index to iterate from 1 till the square root\n    div = 2\n    while((div * div) <= num)\n        # Check if the current 'div' number is a divisor or not.\n        if(num % div == 0)\n            sum = sum + div + num \u00f7 div\n        end\n        div = div + 1\n    end\n    if(sum == num && num != 1)\n        return true\n    else\n        return false\n    end\nend\n\n\nprint(\"Enter the number: \")\nnum = readline()\nnum = parse(Int, num)\nres = perfect_number(num)\nif res\n    println(\"The given number $num is a Perfect Number.\")\nelse\n    println(\"The given number $num is not a Perfect Number.\")\nend\n\n\n\"\"\"\nTime Complexity: O(n^(0.5)), where 'n' is the given number\nSpace Complexity: O(1)\n\nSAMPLE INPUT AND OUTPUT\n\nSAMPLE 1\nEnter the number: 8128\nThe given number 8128 is a Perfect Number.\n\nSAMPLE 2\nEnter the number: 8129\nThe given number 8129 is not a Perfect Number.\n\"\"\"\n", "meta": {"hexsha": "7221e1c3dc8386847e33fe22d40ca013805b52f3", "size": 1324, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/math/perfect_number.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/math/perfect_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/perfect_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": 24.9811320755, "max_line_length": 111, "alphanum_fraction": 0.6563444109, "num_tokens": 353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.966914019704466, "lm_q2_score": 0.9059898216525933, "lm_q1q2_score": 0.8760142602654413}}
{"text": "@testset \"Matrix\" begin\n\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\t    @test lu_decompose(mat) == (L,U)\n    end\n\t\n\t@testset \"Matrix: rotation matrix\" begin\n\t\ttheta = pi/6\n\t\ta = [1;0]\n\t\tb = [0;1]\n\t\t@test rotation_matrix(theta)*a == [cos(theta);sin(theta)]\n\t\t@test rotation_matrix(theta)*b == [-sin(theta);cos(theta)]\n\tend\nend\n", "meta": {"hexsha": "790e336d048ac8ba045a8bff94604a05d409e059", "size": 908, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/matrix.jl", "max_stars_repo_name": "KohRongSoon/Julia", "max_stars_repo_head_hexsha": "e0276ab9224e191452f7932343f8b24ea8625eea", "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": "test/matrix.jl", "max_issues_repo_name": "KohRongSoon/Julia", "max_issues_repo_head_hexsha": "e0276ab9224e191452f7932343f8b24ea8625eea", "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": "test/matrix.jl", "max_forks_repo_name": "KohRongSoon/Julia", "max_forks_repo_head_hexsha": "e0276ab9224e191452f7932343f8b24ea8625eea", "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": 21.619047619, "max_line_length": 76, "alphanum_fraction": 0.4460352423, "num_tokens": 320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811571768048, "lm_q2_score": 0.9073122257466114, "lm_q1q2_score": 0.8759021264119261}}
{"text": "## Exercise 7-4\n## The mathematician Srinivasa Ramanujan found an infinite series that can be used to generate a numerical approximation of 1/\u03c0:\n\n## 1/\u03c0 = 2\u221a2 /9801 \u2211_{k=0}^{\u221e} ((4k)!(1103+26390k))/(k!)^4 * 396^{4k}\n\n## Write a function called estimatepi that uses this formula to compute and return an estimate of \u03c0. It should use a while loop to compute terms of the summation until the last term is smaller than 1e-15 (which is Julia notation for 10^{\u221215}). You can check the result by comparing it to \u03c0.\nprintln(\"Ans: \")\n\nfunction last_part(k::Int)\n    numerator = factorial(4k) * (1103 + 26390 * k)\n    denominator = factorial(k)^4 * 396^(4k)\n\n    return numerator/denominator\nend\n\nfunction estimatepi()\n    k = 0\n    sum = 0.0\n\n    while true\n        last_term = last_part(k)\n        \n        if last_term < 1e-15\n            break\n        end\n        \n        k += 1\n        sum += last_term\n    end\n\n    one_over_pi = ((2 * \u221a2) / 9801) * sum\n\n    return 1 / one_over_pi\nend\n\nprintln(estimatepi())\n\nprintln(\"End.\")\n", "meta": {"hexsha": "232f60ab59ecded21424472354c7f9d648d34f3b", "size": 1022, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chapter7/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": "Chapter7/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": "Chapter7/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": 26.2051282051, "max_line_length": 290, "alphanum_fraction": 0.6340508806, "num_tokens": 311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.98504290989414, "lm_q2_score": 0.8887587824432529, "lm_q1q2_score": 0.8754655372518747}}
{"text": "\"\"\"\n    sum_gp(first_term, ratio, num_terms)\n\nFinds sum of n terms in a geometric progression\n\n# Input parameters\n\n- first_term : first term of the series\n- raio      : common ratio between consecutive terms -> a2/a1 or a3/a2 or a4/a3\n- num_terms  : number of terms in the series till which we count sum\n\n# Example\n\n```julia\nsum_gp(1, 2, 10)    # 1023.0\nsum_gp(1, 10, 5)    # 11111.0\nsum_gp(0, 2, 10)    # 0.0\nsum_gp(1, 0, 10)    # 1.0\nsum_gp(1, 2, 0)     # -0.0\nsum_gp(-1, 2, 10)   # -1023.0\nsum_gp(1, -2, 10)   # -341.0\n```\n\nContributed By:- [Ashwani Rathee](https://github.com/ashwani-rathee)\n\"\"\"\nfunction sum_gp(first_term, ratio, num_terms)\n    # case where ratio is 1\n    if ratio == 1\n        return num_terms * first_term\n    end\n    # ormula for finding sum of n terms of a geometric progression\n    return (first_term / (1 - ratio)) * (1 - ratio^num_terms)\nend\n", "meta": {"hexsha": "8ed5455a8c3ce633840373e3e54670e0b39e0353", "size": 871, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/sum_of_geometric_progression.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/math/sum_of_geometric_progression.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/math/sum_of_geometric_progression.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": 25.6176470588, "max_line_length": 79, "alphanum_fraction": 0.644087256, "num_tokens": 317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9719924810166349, "lm_q2_score": 0.9005297874526778, "lm_q1q2_score": 0.8753081823355112}}
{"text": "using NewtonsMethod\nusing Test\n\n#Test method 1\nf(x)=x^2-4.0\nf\u2032(x)=2x\n@test newtonroot(f,f\u2032,x\u2080=0.2)[1]\u22482.0 atol=0.000001\n\nf(x)=log(x)-20\nf\u2032(x)=1/x\n@test newtonroot(f,f\u2032,x\u2080=0.2)[1]\u22484.851651954097909e8 atol=0.000001\n\nf(x)=3x^2-5x+1\nf\u2032(x)=6x-5\n@test newtonroot(f,f\u2032,x\u2080=0.2)[1]\u22480.23240824122077 atol=0.000001\n\nf(x)=-10x^3-5x^2+20\nf\u2032(x)=-20x^2-10x\n@test newtonroot(f,f\u2032,x\u2080=0.2)[1]\u22481.11338619006481 atol=0.000001\n\n\n#Test method 2\nf(x)=x^2-4.0\n@test newtonroot(f,x\u2080=0.2)[1]\u22482.0 atol=0.000001\n\nf(x)=log(x)-20\n@test newtonroot(f,x\u2080=0.2)[1]\u22484.851651954097909e8 atol=0.000001\n\nf(x)=3x^2-5x+1\n@test newtonroot(f,x\u2080=0.2)[1]\u22480.23240824122077 atol=0.000001\n\nf(x)=-10x^3-5x^2+20\n@test newtonroot(f,x\u2080=0.2)[1]\u22481.11338619006481 atol=0.000001\n\n\n#Test Big Float (Not really sure what to do here. What I did is compare the root with a BigFloat)\nf(x)=3x^2-5x+1\na=BigFloat(0.23240824122077)\n@testset \"BigFloat\" begin\n  @test newtonroot(f,x\u2080=0.2)[1]\u22480.23240824122077 atol=0.000001\n  @test newtonroot(f,x\u2080=0.2)[1]\u2248a atol=0.000001\n end;\n\n#(I also set all parameters to be BigFloat)\nf(x)=3x^2-5x+1\n@test newtonroot(f,x\u2080= BigFloat(0.2),tolerance = BigFloat(1E-7), maxiter = BigFloat(1000))[1]\u22480.23240824122077 atol=0.000001\n\n\n#Test non-convergence (return nothing)\nf(x)=2+x^2\n@test newtonroot(f,x\u2080=0.2)==nothing\n\n\n#Test maxiter (first should return the value, second should return nothing)\nf(x)=log(x)-20\na=newtonroot(f,x\u2080=0.2)[1] #Algorithm needs 17 iterations in this case\nb=newtonroot(f,x\u2080=0.2,maxiter=5)\n@testset \"maxiter\" begin\n  @test a\u22484.851651954097909e8 atol=0.000001 \n  @test b==nothing\n end;\n\n\n#Test tolerance (As tolerance parameter increases, the code is less accurate)\nf(x)=3x^2-5x+1\na=newtonroot(f,x\u2080=1)[1]\nb=newtonroot(f,x\u2080=1, tolerance=0.0005)[1]\nc=newtonroot(f,x\u2080=1, tolerance=0.05)[1]\n@test f(a)<f(b)<f(c)\n", "meta": {"hexsha": "3a6f3b0c592c71384acb7d8d3a766282aad092ed", "size": 1796, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "sejinahn2/NewtonsMethod.jl", "max_stars_repo_head_hexsha": "bdb0cfa9b99c2a571d362546c98cd369430da49a", "max_stars_repo_licenses": ["MIT"], "max_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": "sejinahn2/NewtonsMethod.jl", "max_issues_repo_head_hexsha": "bdb0cfa9b99c2a571d362546c98cd369430da49a", "max_issues_repo_licenses": ["MIT"], "max_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": "sejinahn2/NewtonsMethod.jl", "max_forks_repo_head_hexsha": "bdb0cfa9b99c2a571d362546c98cd369430da49a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6571428571, "max_line_length": 124, "alphanum_fraction": 0.7021158129, "num_tokens": 823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542840900507, "lm_q2_score": 0.9124361598816667, "lm_q1q2_score": 0.8751670517091751}}
{"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\n\nf = x->sin(10x)+cos(3x)\nx0 = 3.4\n#busca do intervalo\na,c = bracket_minimum(f,x0)\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))\nam,bm\n\n\nplot(f,0.,4.,lw=2,draw_arrow=\"true\")\nscatter!([a,c],[f(a),f(c)])\nscatter!([am,bm],[f(am),f(bm)])\n", "meta": {"hexsha": "ba105e30ad7db7320f9465e809b173b0fcc3bfb5", "size": 994, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Golden_Section_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": "Golden_Section_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": "Golden_Section_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": 17.4385964912, "max_line_length": 47, "alphanum_fraction": 0.4336016097, "num_tokens": 420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214491222696, "lm_q2_score": 0.9073122201074847, "lm_q1q2_score": 0.8749406349003933}}
{"text": "function getPolynomial(X, Y)\n    n = length(Y)\n    p = string(\"P = x -> \", Y[1])\n    for i::Int in 2:n\n        P = string(p, \" + \", Y[i])\n        for j in 1:i-1\n            p = string(p, \"*(x-\", X[j], \")\")\n        end\n    end\n    return eval(Meta.parse(p))\nend\n\nfunction getCoefficients(X, Y)\n  \n    n = length(X)\n   \n    for i::Int in 2:n\n        for j::Int in 2:i\n            Y[i, j] = (Y[i, j-1] - Y[i-1, j-1])/(X[i] - X[i-j+1])\n        end\n    end\n\n    F = []\n\n    for i in 1:n\n        push!(F, Y[i, i])\n    end\n\n    return F\nend\n\n\"\"\"\n    divid(X, Y, cff)\n\nComputes interpolating polynomial passing through the points whoose coordinates are provided in `X[]` and `Y[]`\nusing Newton's divided difference method. Returns `::Array{Float64}` if `cff = true` (default), or the interpolating polynomial P if `cff = false`. \n\n    divid(X::Array{Float64}, Y::Array{Float64}, cff::Bool=true)\n\n### OUTPUT:\n  * `F` - coefficiants of the interpolating polynomial of the type `Array{Float64}`,\n  * `P` - interpolating polynomial.\n\"\"\"\nfunction divid(X::Array{Float64}, Y::Array{Float64}, cff::Bool=true)\n    if cff\n        return getCoefficients(X, Y)\n    else\n        return getPolynomial(X, Y)\n    end\nend\n", "meta": {"hexsha": "1961b6df1d90945cf13ccb7ccfd3bec94a0f4120", "size": 1198, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/divided_difference.jl", "max_stars_repo_name": "faruk-becirovic/Julia-Numerical-Alalysis", "max_stars_repo_head_hexsha": "aa5eea30a3862ad06bfe451b5478156bce5f31cd", "max_stars_repo_licenses": ["MIT"], "max_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_difference.jl", "max_issues_repo_name": "faruk-becirovic/Julia-Numerical-Alalysis", "max_issues_repo_head_hexsha": "aa5eea30a3862ad06bfe451b5478156bce5f31cd", "max_issues_repo_licenses": ["MIT"], "max_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_difference.jl", "max_forks_repo_name": "faruk-becirovic/Julia-Numerical-Alalysis", "max_forks_repo_head_hexsha": "aa5eea30a3862ad06bfe451b5478156bce5f31cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4901960784, "max_line_length": 148, "alphanum_fraction": 0.5609348915, "num_tokens": 383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741308615412, "lm_q2_score": 0.9184802350995702, "lm_q1q2_score": 0.8749205116634772}}
{"text": "#HW2 Problem 4\n#Minhao Yan my497, Wentong Chen wc422\n\n#1. Recast the problem as an unconstrained utility maximization problem\n#Plug the budget constraint back to the utility function\n#u(c1) = (\u03ba*c1^((\u03b7-1)/\u03b7)+(1-\u03ba)*((w-p1*c1)/p2)^((\u03b7-1)/\u03b7))^(\u03b7/(\u03b7-1))\n\n#2. Solve this utility maximization problem\nPkg.add(\"Optim\")\nusing Optim\n\nfunction utility_maximizer(\u03ba, \u03b7, p1, p2, w, initial_guess, solver)\n    u(c1)=-((\u03ba*c1^((\u03b7-1)/\u03b7)+(1-\u03ba)*((w-p1*c1)/p2)^((\u03b7-1)/\u03b7)))^(\u03b7/(\u03b7-1))\n    results = optimize(u,initial_guess)\n    c1_min=Optim.minimizer(results)[1]\n    c2_min= (w-p1*c1_min)/p2\n    u_max=-Optim.minimum(results)\n    println(\"c1= $c1_min\")\n    println(\"c2= $c2_min\")\n    println(\"u_max= $u_max\")\n    return [c1_min c2_min u_max]\n    return results\nend\n\n#3.Solve analytically\n\u03ba=.5\n\u03b7=3\nw=50\np1=2\np2=3\ninitial_guess=0.0\nResult_ana = utility_maximizer(\u03ba, \u03b7, p1, p2, w, initial_guess, Newton())\n\n#Solve numerically\nu1(c1)=\u03ba*c1^((\u03b7-1)/\u03b7)+(1-\u03ba)*((w-p1*c1)/p2)^((\u03b7-1)/\u03b7)\nfunction g!(storage, x)\n    storage[1]=-(\u03b7/(\u03b7-1))*u1(x[1])^(1/(\u03b7-1))*(\u03ba*((\u03b7-1)/\u03b7)*x[1]^(-1/\u03b7)+(1-\u03ba)*((\u03b7-1)/\u03b7)*((w-p1*x[1])/p2)^(-1/\u03b7)*(-p1/p2))\n    storage[2] = 0.0\nend\nfunction utility_maximizer_num(\u03ba, \u03b7, p1, p2, w, initial_guess, solver)\n    x=initial_guess\n    u(c1)=0.0*x[2]-((\u03ba*c1^((\u03b7-1)/\u03b7)+(1-\u03ba)*((w-p1*c1)/p2)^((\u03b7-1)/\u03b7)))^(\u03b7/(\u03b7-1))\n    results = optimize(u, g!, initial_guess)\n    c1_min=Optim.minimizer(results)[1]\n    c2_min= (w-p1*c1_min)/p2\n    u_max=-Optim.minimum(results)\n    println(\"c1= $c1_min\")\n    println(\"c2= $c2_min\")\n    println(\"u_max= $u_max\")\n    return [c1_min c2_min u_max]\n    return results\nend\n\n\u03ba=.5\n\u03b7=3\nw=50\np1=2\np2=3\ninitial_guess=0.0\nReturn_num = utility_maximizer_num(\u03ba, \u03b7, p1, p2, w, initial_guess, Newton())\n", "meta": {"hexsha": "4774aa6e29438a065655fcc0ace93690140461aa", "size": 1700, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Problem4.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": "Problem4.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": "Problem4.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.868852459, "max_line_length": 119, "alphanum_fraction": 0.6270588235, "num_tokens": 717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966762263737, "lm_q2_score": 0.92414182206801, "lm_q1q2_score": 0.8747895771313631}}
{"text": "function cosine_similarity(set1::Union{Vector, Array}, set2::Union{Vector, Array})\n\n    @assert length(set1) == length(set2) \"Sets don't have the same length.\"\n\n    num = zero(eltype(set1))\n    for i in 1:length(set1)\n        num += set1[i] * set2[i]\n    end\n    norm_set1 = zero(eltype(set1))\n    norm_set2 = zero(eltype(set2))\n    for i in 1:length(set1)\n        norm_set1 += set1[i]^2\n        norm_set2 += set2[i]^2\n    end\n    norm_set1, norm_set2 = sqrt(norm_set1), sqrt(norm_set2)\n    dem = norm_set1 * norm_set2\n\n    if dem == 0\n        throw(ArgumentError(\"denominador igual a 0\"))\n    end\n    return num/dem\nend\n\nfunction cosine_similarity_2(set1, set2)\n    return dot(set1, set2) / (norm(set1) * norm(set2))\nend\n", "meta": {"hexsha": "52f56cb970a74bd2e75f364bb1eea3ad4944d849", "size": 722, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/CosineSimilarity.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/CosineSimilarity.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/CosineSimilarity.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": 26.7407407407, "max_line_length": 82, "alphanum_fraction": 0.6343490305, "num_tokens": 228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854138058636, "lm_q2_score": 0.9019206837793828, "lm_q1q2_score": 0.8746695235390562}}
{"text": "\n\n\n\n\"Fits a straight line through a set of points, `y = a\u2081 + a\u2082 * x`\"\nlinear_fit(x, y) = hcat(fill!(similar(x),1), x) \\ y\n\n\"Fits a log function through a set of points: `y = a\u2081+ a\u2082*log(x)`\"\nlog_fit(x, y) = linear_fit(log.(x), y)\n\n\"Fits a power law through a set of points: `y = a\u2081*x^a\u2082`\"\nfunction power_fit(x, y)\n    fit = linear_fit(log.(x), log.(y))\n    [exp(fit[1]), fit[2]]\nend\n\n\"Fits an `exp` through a set of points: `y = a\u2081*exp(a\u2082*x)`\"\nfunction exp_fit(x, y)\n    fit = linear_fit(x, log.(y))\n    [exp(fit[1]), fit[2]]\nend\n\n\"\"\"\nFits a polynomial of degree `n` through a set of points.\n\nSimple algorithm, doesn't use orthogonal polynomials or any such thing \nand therefore unconditioned matrices are possible. Use it only for low\ndegree polynomials. \n\nThis function returns a the coefficients of the polynomial.\n\"\"\"\nfunction poly_fit(x, y, n)\n\n    nx = length(x)\n    A = zeros(eltype(x), nx, n+1)\n    A[:,1] .= 1.0\n    for i in 1:n\n        for k in 1:nx\n            A[k,i+1] = A[k,i] * x[k]\n        end\n    end\n    A\\y\nend\n\n\n    \n\n\n\"\"\"\nHigh Level interface for fitting straight lines\n\"\"\"\nstruct LinearFit{T<:Number} <: LeastSquares\n    coefs::Array{T,1}\n    LinearFit{T}(coefs) where {T<:Number} = new(copy(coefs))\nend\nLinearFit(x::AbstractVector{T}, y::AbstractVector{T}) where {T<:Number} = LinearFit{T}(linear_fit(x, y))\n\n\n\"High Level interface for fitting log laws\"\nstruct LogFit{T<:Number} <: LeastSquares\n    coefs::Array{T,1}\n    LogFit{T}(coefs) where {T<:Number} = new(copy(coefs))\nend\nLogFit(x::AbstractVector{T}, y::AbstractVector{T}) where {T<:Number} = LogFit{T}(log_fit(x, y))\n\n\"High Level interface for fitting power laws\"\nstruct PowerFit{T<:Number} <: LeastSquares\n    coefs::Array{T,1}\n    PowerFit{T}(coefs) where {T<:Number} = new(copy(coefs))\nend\nPowerFit(x::AbstractVector{T}, y::AbstractVector{T}) where {T<:Number} = PowerFit{T}(power_fit(x, y))\n\n\"High Level interface for fitting exp laws\"\nstruct ExpFit{T<:Number} <: LeastSquares\n    coefs::Array{T,1}\n    ExpFit{T}(coefs) where {T<:Number} = new(copy(coefs))\nend\nExpFit(x::AbstractVector{T}, y::AbstractVector{T}) where {T<:Number} = ExpFit{T}(exp_fit(x, y))\n\n\n\n\"\"\"\n# Generic interface for curve fitting.\n\nThe same function `curve_fit` can be used to fit the data depending on fit type, \nshich is specified in the first parameter. This function returns an object that\ncan be used to estimate the value of the fitting model using function `apply_fit`.\n\n## A few examples:\n\n * `f = curve_fit(LinearFit, x, y)`\n * `f = curve_fit(Poly, x, y, n)`\n\"\"\"\ncurve_fit(::Type{T}, x, y) where {T<:LeastSquares} = T(x, y)\ncurve_fit(::Type{T}, x, y, args...) where {T<:LeastSquares} = T(x, y, args...)\ncurve_fit(::Type{Poly}, x, y, n=1) = Poly(poly_fit(x, y, n))\n\n\n\n(f::LinearFit)(x) = f.coefs[1] + f.coefs[2] *x\n(f::PowerFit)(x) = f.coefs[1] * x ^ f.coefs[2]\n(f::LogFit)(x) = f.coefs[1] + f.coefs[2] * log(x)\n(f::ExpFit)(x) = f.coefs[1] * exp(f.coefs[2] * x)\n", "meta": {"hexsha": "b862b8943bfa1d579172d466d6e386bad61b364e", "size": 2925, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/linfit.jl", "max_stars_repo_name": "NTimmons/CurveFit.jl", "max_stars_repo_head_hexsha": "ace2c6b008e8ac7e4eaa650ef4754708aeedaed0", "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/linfit.jl", "max_issues_repo_name": "NTimmons/CurveFit.jl", "max_issues_repo_head_hexsha": "ace2c6b008e8ac7e4eaa650ef4754708aeedaed0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/linfit.jl", "max_forks_repo_name": "NTimmons/CurveFit.jl", "max_forks_repo_head_hexsha": "ace2c6b008e8ac7e4eaa650ef4754708aeedaed0", "max_forks_repo_licenses": ["MIT"], "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": 104, "alphanum_fraction": 0.6478632479, "num_tokens": 962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811611608242, "lm_q2_score": 0.9059898121338507, "lm_q1q2_score": 0.8746254968376537}}
{"text": "using NewtonsMethod\nusing Test\n\n#Test method 1\nf(x)=x^2-4.0\nf\u2032(x)=2x\n@test newtonroot(f,f\u2032,x\u2080=0.2)[1]\u22482.0\n\nf(x)=log(x)-20\nf\u2032(x)=1/x\n@test newtonroot(f,f\u2032,x\u2080=0.2)[1]\u22484.851651954097909e8\n\nf(x)=3x^2-5x+1\nf\u2032(x)=6x-5\n@test newtonroot(f,f\u2032,x\u2080=0.2)[1]\u22482.32408120756001784480129727405038536389084291259026547774006206530426035584922e-01\n\nf(x)=-10x^3-5x^2+20\nf\u2032(x)=-20x^2-10x\n@test newtonroot(f,f\u2032,x\u2080=0.2)[1]\u22481.113386205687796447877673190361708447749219094960359587626412934254462034979434\n\n\n#Test method 2\nf(x)=x^2-4.0\n@test newtonroot(f,x\u2080=0.2)[1]\u22482.0\n\nf(x)=log(x)-20\n@test newtonroot(f,x\u2080=0.2)[1]\u22484.851651954097909e8\n\nf(x)=3x^2-5x+1\n@test newtonroot(f,x\u2080=0.2)[1]\u22482.32408120756001784480129727405038536389084291259026547774006206530426035584922e-01\n\nf(x)=-10x^3-5x^2+20\n@test newtonroot(f,x\u2080=0.2)[1]\u22481.113386205687796447877673190361708447749219094960359587626412934254462034979434\n\n\n#Test Big Float (Not really sure what to do here)\n#(I set all parameters to be BigFloat)\nf(x)=3x^2-5x+1\n@test newtonroot(f,x\u2080= BigFloat(0.2),tolerance = BigFloat(1E-100), maxiter = BigFloat(1000))[1]  \u2248  2.32408120756001784480129727405038536389084291259026547774006206530426035584922e-01\n\n#Test non-convergence (return nothing)\nf(x)=2+x^2\n@test newtonroot(f,x\u2080=0.2)==nothing\n\n\n#Test maxiter (first should return the value, second should return nothing)\nf(x)=log(x)-20\na=newtonroot(f,x\u2080=0.2)[1] #Algorithm needs 17 iterations in this case\nb=newtonroot(f,x\u2080=0.2,maxiter=5)\n@testset \"maxiter\" begin\n  @test a\u22484.851651954097909e8\n  @test b==nothing\n end;\n\n\n#Test tolerance (As tolerance parameter increases, the code is less accurate)\nf(x)=3x^2-5x+1\na=newtonroot(f,x\u2080=1)[1]\nb=newtonroot(f,x\u2080=1, tolerance=0.0005)[1]\nc=newtonroot(f,x\u2080=1, tolerance=0.05)[1]\n@test f(a)<f(b)<f(c)\n", "meta": {"hexsha": "63e248adb53659d6d50a20c6acaf90cc7b02d946", "size": 1748, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "gava31/NewtonsMethod", "max_stars_repo_head_hexsha": "99620f6e4833fcd1a9b71def102688715faa1eba", "max_stars_repo_licenses": ["MIT"], "max_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": "gava31/NewtonsMethod", "max_issues_repo_head_hexsha": "99620f6e4833fcd1a9b71def102688715faa1eba", "max_issues_repo_licenses": ["MIT"], "max_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": "gava31/NewtonsMethod", "max_forks_repo_head_hexsha": "99620f6e4833fcd1a9b71def102688715faa1eba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1935483871, "max_line_length": 183, "alphanum_fraction": 0.7465675057, "num_tokens": 773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474207360066, "lm_q2_score": 0.916109622750986, "lm_q1q2_score": 0.8745616884706647}}
{"text": "# # Basic linear algebra in Julia\n# Author: Andreas Noack Jensen (MIT) (http://www.econ.ku.dk/phdstudent/noack/)\n# (with edits from Jane Herriman)\n\n#-\n\n# First let's define a random matrix\n\nA = rand(1:4,3,3)\n\n# Define a vector of ones\n\nx = fill(1.0, (3,)) # = fill(1.0, 3)\n\n# Notice that $A$ has type Array{Int64,2} but $x$ has type Array{Float64,1}. Julia defines the aliases Vector{Type}=Array{Type,1} and Matrix{Type}=Array{Type,2}.\n#\n# Many of the basic operations are the same as in other languages\n# #### Multiplication\n\nb = A*x\n\n# #### Transposition\n# As in other languages `A'` is the conjugate transpose, or adjoint\n\nA'\n\n# and we can get the transpose with\n\ntranspose(A)\n\n# #### Transposed multiplication\n# Julia allows us to write this without *\n\nA'A\n\n# #### Solving linear systems\n# The problem $Ax=b$ for ***square*** $A$ is solved by the \\ function.\n\nA\\b\n\n# `A\\b` gives us the *least squares solution* if we have an overdetermined linear system (a \"tall\" matrix)\n\nAtall = rand(3, 2)\n\n#-\n\nAtall\\b\n\n# and the *minimum norm least squares solution* if we have a rank-deficient least squares problem\n\nv = rand(3)\nrankdef = hcat(v, v)\n\n#-\n\nrankdef\\b\n\n# Julia also gives us the minimum norm solution when we have an underdetermined solution (a \"short\" matrix)\n\nbshort = rand(2)\nAshort = rand(2, 3)\n\n#-\n\nAshort\\bshort\n\n# # The LinearAlgebra library\n#\n# While much of linear algebra is available in Julia by default (as shown above), there's a standard library named `LinearAlgebra` that brings in many more relevant names and functions. In particular, it provides factorizations and some structured matrix types.  As with all packages, you can bring these additional features into your session with a `using LinearAlgebra`.\n\n#-\n\n# ### Exercises\n#\n# #### 10.1\n# Take the inner product (or \"dot\" product) of a vector `v` with itself and assign it to variable `dot_v`.\n\nv = [1,2,3]\n\n#-\n\n@assert dot_v == 14\n\n# #### 10.2\n# Take the outer product of a vector v with itself and assign it to variable `cross_v`\n\n@assert cross_v == [0, 0, 0]\n\n", "meta": {"hexsha": "d3efb7c1f63982e2484cb345f804bc1806f8d930", "size": 2040, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Courses/Introduction to Julia/11.Basic-linear-algebra.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/11.Basic-linear-algebra.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/11.Basic-linear-algebra.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": 22.9213483146, "max_line_length": 372, "alphanum_fraction": 0.6995098039, "num_tokens": 581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750440288019, "lm_q2_score": 0.9173026482819238, "lm_q1q2_score": 0.8744417224286875}}
{"text": "using Distributions\nusing LinearAlgebra\nusing BenchmarkTools\n\n# ------------------------------------------------------------------------------\n\nfunction find_Q(A, l)\n    #=\n    Given an m \u00d7 n matrix A, and an integer l, compute an m \u00d7 l orthonormal\n    matrix Q whose range approximates the range of A.\n    =#\n    m, n = size(A)\n    \u03a9 = rand(Normal(), n, l)\n    Y = A * \u03a9\n    Q, R = qr(Y)\n    return Q\nend\n\n# ------------------------------------------------------------------------------\n\nfunction randomized_SVD(A, k)\n    #=\n    Given an m \u00d7 n matrix A, a target number k of singular vectors, and an\n    exponent q (say q = 1 or q = 2), this procedure computes an approximate\n    rank-2k factorization U\u03a3Vt, where U and V are orthonormal and \u03a3 is\n    nonnegative and diagonal.\n    =#\n    Q = find_Q(A, 2*k)\n    B = Q' * A\n    S, \u03a3, Vt = svd(B)\n    U = Q * S\n    return U, \u03a3, Vt\nend\n\n# ------------------------------------------------------------------------------\n\nm = 2000\nn = 20000\nk = 10\n# Construct low-rank matrix\nA = rand(m, k) * rand(k, n)\nprintln(\"Rank of A: \", rank(A))\nprintln(\"Size of A: \", size(A))\n\nprintln(\"Throwaway test:\")\n@time svd(A)\n@time randomized_SVD(A, k)\nprintln(\"Actual test:\")\n@benchmark svd(A)\n@benchmark randomized_SVD(A, k)\n\nprintln(\"Completed\")\n\n# https://stackoverflow.com/questions/53162206/why-does-my-randomized-svd-implementation-use-so-much-memory", "meta": {"hexsha": "3b9556b0f85844693e506200687986d191a53855", "size": 1384, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/others/randsvd_test.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": "test/others/randsvd_test.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": "test/others/randsvd_test.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": 25.6296296296, "max_line_length": 107, "alphanum_fraction": 0.5310693642, "num_tokens": 378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517083920618, "lm_q2_score": 0.9099070054272775, "lm_q1q2_score": 0.8743766913432474}}
{"text": "@doc raw\"\"\"\n    lentz_thompson(b\u2080, a, b)\n\nLentz\u2013Thompson algorithm for the forward evaluation of continued\nfractions:\n\n```math\nf_n = b_0 + \\frac{a_1}{b_1+}\\frac{a_2}{b_2+}...\\frac{a_{n-1}}{b_{n-1}+}\\frac{a_n}{b_n}\n```\n\nAs described in\n\n- Barnett, A. R. (1996). The Calculation of Spherical Bessel and\n  Coulomb Functions. In (Eds.), Computational Atomic Physics\n  (pp. 181\u2013202). Springer Berlin Heidelberg.\n\n\"\"\"\nfunction lentz_thompson(b\u2080::T, a, b;\n                        max_iter=20000,\n                        \u03f5 = eps(T), tol=100eps(T),\n                        verbosity=0) where T\n    val_or_\u03f5(x) = abs(x) < \u03f5 ? \u03f5 : x\n\n    f = val_or_\u03f5(b\u2080)\n    C = f\n    D = zero(T)\n    \u03b4 = zero(T)\n\n    fmt = if verbosity>1\n        printfmtln(\"{1:>4s} {2:>10s} {3:>10s} {4:>10s} {5:>10s} {6:>10s} {7:>10s} {8:>10s}\",\n                   \"n\", \"a\", \"b\", \"C\", \"D\", \"|\u0394-1|\", \"f\", \"\u03b4f\")\n        FormatExpr(\"{1:>4d} {2:10.3e} {3:10.3e} {4:10.3e} {5:10.3e} {6:10.3e} {7:10.3e} {8:10.3e}\")\n    else\n        nothing\n    end\n\n    s = true\n\n    for n = 1:max_iter\n        a\u2099 = a(n)\n        b\u2099 = b(n)\n        C = val_or_\u03f5(b\u2099 + a\u2099/C)\n        D = inv(val_or_\u03f5(b\u2099 + a\u2099*D))\n        if isreal(D) && D < 0\n            # See section 3.2 of\n            #\n            # - Barnett, A., Feng, D., Steed, J., & Goldfarb, L. (1974). Coulomb\n            #   wave functions for all real $\\eta$ and \u03c1. Computer Physics\n            #   Communications, 8(5),\n            #   377\u2013395. http://dx.doi.org/10.1016/0010-4655(74)90013-7\n            s = !s\n        end\n        \u0394 = C*D\n        fn = f*\u0394\n        \u03b4 = abs(\u0394-1)\n        verbosity>1 && printfmtln(fmt, n, a\u2099, b\u2099, C, D, \u03b4, fn, fn-f)\n        f = fn\n        \u03b4 < tol && return f,n,\u03b4,s,true\n    end\n\n    verbosity > 0 && @warn \"Lentz\u2013Thompson did not converge in $(max_iter) iterations, |\u0394-1| = $(\u03b4)\"\n    f,max_iter,\u03b4,s,false\nend\n", "meta": {"hexsha": "fc78d7c9cd0ea6eacf987daeffdcf1da978d2a76", "size": 1835, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/continued_fractions.jl", "max_stars_repo_name": "jagot/SphericalBesselFunctions.jl", "max_stars_repo_head_hexsha": "c1d1472f2f67166d45c2ebd53f472c3a8ec2f0f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/continued_fractions.jl", "max_issues_repo_name": "jagot/SphericalBesselFunctions.jl", "max_issues_repo_head_hexsha": "c1d1472f2f67166d45c2ebd53f472c3a8ec2f0f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/continued_fractions.jl", "max_forks_repo_name": "jagot/SphericalBesselFunctions.jl", "max_forks_repo_head_hexsha": "c1d1472f2f67166d45c2ebd53f472c3a8ec2f0f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-07T09:42:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T09:42:01.000Z", "avg_line_length": 28.671875, "max_line_length": 100, "alphanum_fraction": 0.4920980926, "num_tokens": 713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475699138559, "lm_q2_score": 0.926303728768107, "lm_q1q2_score": 0.8738263715355372}}
{"text": "\"\"\"Julia program to implement Fibonacci Search algorithm.\nFibonacci Search is a Divide and Conquer strategy based algorithm that works for sorted arrays\nFibonacci Search avoids CPU costly division operation and uses addition and subtraction opertations\nThis algorithm uses Fibonacci series as an underlying principle, where every element of the series is defined by:\n\n    fib(n) = fib(n-1) + fib(n-2), where fib(0) = 0, fib(1) = 1\n\"\"\"\n\nfunction fibonacci_search(arr, n, ele)\n\n    # We start the series from 1, 1 as the Julia language is 1-based indexing\n    fibn2 = 1\n    fibn1 = 1\n    fibn = fibn1 + fibn2\n    while (fibn < n)\n        fibn2 = fibn1\n        fibn1 = fibn\n        fibn = fibn1 + fibn2\n    end\n\n    # To denote the eliminted range from left.\n    offset = 0\n\n    while (fibn > 1)\n        i = min(offset + fibn2, n - 1)\n        \n        \"\"\"Compares the element in i'th index with ele and decide the next fibonacci element. If the element doesn't\n            turns out to be greater than or less than the element at i'th index then we find the required element\"\"\"\n        if (arr[i] < ele) \n            fibn = fibn1;\n            fibn1 = fibn2;\n            fibn2 = fibn - fibn1;\n            offset = i;\n        elseif (arr[i] > ele) \n            fibn = fibn2;\n            fibn1 = fibn1 - fibn2;\n            fibn2 = fibn - fibn1;\n        else\n            return true\n        end\n        if (arr[offset + 1] == ele)\n            return true\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 = fibonacci_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\"\"\"\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": "6a4776d771bb38059734b8fc3af0e3c03a7c6e2e", "size": 2525, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/search/fibonacci_search.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/fibonacci_search.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/fibonacci_search.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": 27.1505376344, "max_line_length": 116, "alphanum_fraction": 0.6348514851, "num_tokens": 711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9748211582993981, "lm_q2_score": 0.8962513648201267, "lm_q1q2_score": 0.8736847935813723}}
{"text": "#=\nCreated on 09/01/2021 15:00:09\nLast update: -\n\n@author: Michiel Stock\nmichielfmstock@gmail.com\n\nImplement the information entropy:\n$$\nH(p) = -\\sum_i p_i \\log p_i\\,,\n$$\n\nTake caution that, by definition,$0 \\log 0$ is evaluated as 0 (i.e., its limit value).\n\nHave an optional flag to specify the bag of log, default is base 2, making the output in bits.\n\nMake a plot of the entropy of a Bernouilli-distributed variable for varying probability of success\n$p$, i.e., the entropy of probability vector $[p, 1-p]$ for $p\\in [0, 1]$.\n=#\n\nusing Plots\n\nentropy(p; base=2) = p .|> (p\u1d62 -> p\u1d62 > 0.0 ? -p\u1d62 * log(p\u1d62) : 0.0) |> sum |> (H -> H / log(base))\n\nentropy([0, 1, 0])  # 0.0\nentropy([0.5, 0.5])  # 1.0\nentropy([0.5, 0.5], base=10)  # 0.30102999566398114\n\nplot(p->entropy((p, 1-p)), 0, 1, xlabel=\"p\", label=\"entropy\")\n", "meta": {"hexsha": "7d8b727aa932e2b02ebe7d0c80c35d1352651073", "size": 813, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/informationentropy.jl", "max_stars_repo_name": "jpgmolina/DS-Julia2925", "max_stars_repo_head_hexsha": "4d96351afb72f4107fa12561a6a460dcd3c617e3", "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/informationentropy.jl", "max_issues_repo_name": "jpgmolina/DS-Julia2925", "max_issues_repo_head_hexsha": "4d96351afb72f4107fa12561a6a460dcd3c617e3", "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/informationentropy.jl", "max_forks_repo_name": "jpgmolina/DS-Julia2925", "max_forks_repo_head_hexsha": "4d96351afb72f4107fa12561a6a460dcd3c617e3", "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.1, "max_line_length": 98, "alphanum_fraction": 0.6469864699, "num_tokens": 311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813551535005, "lm_q2_score": 0.9136765245890102, "lm_q1q2_score": 0.8734577221485426}}
{"text": "using FiniteDiff, LinearAlgebra, SparseArrays, Test, StaticArrays\r\n\r\nfunction f(x)\r\n  xm1 = [0;x[1:end-1]]\r\n  xp1 = [x[2:end];0]\r\n  xm1 - 2x + xp1\r\nend\r\n\r\nfunction second_derivative_stencil(N)\r\n  A = zeros(N,N)\r\n  for i in 1:N, j in 1:N\r\n      (j-i==-1 || j-i==1) && (A[i,j]=1)\r\n      j-i==0 && (A[i,j]=-2)\r\n  end\r\n  A\r\nend\r\n\r\nx = @SVector ones(30)\r\nJ = FiniteDiff.finite_difference_jacobian(f,x, Val{:forward}, eltype(x))\r\n@test J \u2248 second_derivative_stencil(30)\r\n_J = sparse(J)\r\nJ = FiniteDiff.finite_difference_jacobian(f,x, Val{:central}, eltype(x))\r\n@test J \u2248 second_derivative_stencil(30)\r\n\r\nJ = FiniteDiff.finite_difference_jacobian(f,x, Val{:complex}, eltype(x))\r\n@test J \u2248 second_derivative_stencil(30)\r\n\r\n#1x1 SVector test\r\nx = SVector{1}([1.])\r\nf(x) = x\r\nJ = FiniteDiff.finite_difference_jacobian(f, x, Val{:forward}, eltype(x))\r\n@test J \u2248 SMatrix{1,1}([1.])\r\nJ = FiniteDiff.finite_difference_jacobian(f, x, Val{:central}, eltype(x))\r\n@test J \u2248 SMatrix{1,1}([1.])\r\nJ = FiniteDiff.finite_difference_jacobian(f, x, Val{:complex}, eltype(x))\r\n@test J \u2248 SMatrix{1,1}([1.])\r\n", "meta": {"hexsha": "191f85f9fbf48e73e879b1f4b08ed49db2d3bcb4", "size": 1081, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/out_of_place_tests.jl", "max_stars_repo_name": "crstnbr/FiniteDiff.jl", "max_stars_repo_head_hexsha": "d809185b44cb7766f54222dd03e214f46b03f39f", "max_stars_repo_licenses": ["MIT"], "max_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_tests.jl", "max_issues_repo_name": "crstnbr/FiniteDiff.jl", "max_issues_repo_head_hexsha": "d809185b44cb7766f54222dd03e214f46b03f39f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/out_of_place_tests.jl", "max_forks_repo_name": "crstnbr/FiniteDiff.jl", "max_forks_repo_head_hexsha": "d809185b44cb7766f54222dd03e214f46b03f39f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2162162162, "max_line_length": 74, "alphanum_fraction": 0.6493987049, "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778073288128, "lm_q2_score": 0.9124361521430956, "lm_q1q2_score": 0.8734548790510817}}
{"text": "\nfunction chebyshev_points(::Type{T}, s::Integer, ::Val{1}) where {T}\n    shift_nodes(T[ @big sin( \u03c0*(s-2i+1) / (2s) ) for i in s:-1:1 ])\nend\n\nfunction chebyshev_points(::Type{T}, s::Integer, ::Val{2}) where {T}\n    shift_nodes(T[ @big cos( \u03c0 * (i-1) / (s-1) ) for i in s:-1:1 ])\nend\n\n\"\"\"\nGauss-Chebyshev quadrature.\n\"\"\"\nfunction GaussChebyshevQuadrature(::Type{T}, s::Integer) where {T}\n    local tj::BigFloat = 0\n    local th::BigFloat = 0\n\n    c = chebyshev_points(BigFloat, s, Val(1))\n    b = zero(c)\n    for i in eachindex(b)\n        tj = 0\n        th = @big \u03c0 * (2i-1) / (2s)\n        for j in 1:div(s,2)\n            tj += @big cos(2j*th) / (4j^2 - 1)\n        end\n        b[i] = @big (1 - 2tj) / s\n    end\n\n    QuadratureRule(2s, c, b, T)\nend\n\nGaussChebyshevQuadrature(s) = GaussChebyshevQuadrature(Float64, s)\n\n\n\"\"\"\nLobatto-Chebyshev quadrature.\n\"\"\"\nfunction LobattoChebyshevQuadrature(::Type{T}, s::Integer) where {T}\n    if s == 1\n        throw(ErrorException(\"Lobatto-Chebyshev quadrature is not defined for one stage.\"))\n    end\n\n    local tj::BigFloat = 0\n    local th::BigFloat = 0\n\n    c = chebyshev_points(BigFloat, s, Val(2))\n    b = zero(c)\n    for i in eachindex(b)\n        tj = 0\n        th = @big \u03c0 * i / (s+1)\n        for j in 1:div(s+1,2)\n            tj += @big sin((2j-1) * th) / (2j - 1)\n        end\n        b[i] = @big (2tj * sin(th)) / (s+1)\n    end\n\n    QuadratureRule(2s, c, b, T)\nend\n\nLobattoChebyshevQuadrature(s) = LobattoChebyshevQuadrature(Float64, s)\n\n\nChebyshevQuadrature(::Type{T}, s::Integer, ::Val{1}) where {T} = GaussChebyshevQuadrature(T,s)\nChebyshevQuadrature(::Type{T}, s::Integer, ::Val{2}) where {T} = LobattoChebyshevQuadrature(T,s)\n\nChebyshevQuadrature(s, kind) = ChebyshevQuadrature(Float64, s, Val(kind))\n", "meta": {"hexsha": "2e3dace758aaf69488cf6887b999d31d55604dfe", "size": 1753, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/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": "src/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": "src/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": 26.5606060606, "max_line_length": 96, "alphanum_fraction": 0.5938391329, "num_tokens": 671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517083920618, "lm_q2_score": 0.9086179025005187, "lm_q1q2_score": 0.8731379256834852}}
{"text": "using LinearAlgebra\nusing Test\n\n# 1\n# a\nA = [\n   3 -1 -1  0 -1\n  -1  3  0 -1 -1\n  -1  0  3 -1 -1\n   0 -1 -1  3 -1\n  -1 -1 -1 -1  4\n]\n\nA\u1d40A = A' * A\n\n# b\n@test tr(A\u1d40A) == 68\n\n@test rank(A\u1d40A) == 4\n\nvalues, = eigen(A\u1d40A)\n\n@test round(sum(values)) == 68\n\n@test round(reduce(*, values)) == 0\n\n# c\nA\u2081 = [\n   1 -1 0 0 0\n  -1  1 0 0 0\n   0  0 0 0 0\n   0  0 0 0 0\n   0  0 0 0 0\n]\n\nA\u2081\u1d40A\u2081 = A\u2081' * A\u2081\n\n@test A\u2081\u1d40A\u2081 == [\n  2  -2  0  0  0\n -2   2  0  0  0\n  0   0  0  0  0\n  0   0  0  0  0\n  0   0  0  0  0\n]\n\n#d\nb = ones(8, 1)\n\n@test_throws SingularException inv(A)\n", "meta": {"hexsha": "336ac5ebf2e4649f1a08b9044cdc1f44a854e6de", "size": 550, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "3.BoundaryValueProblems/Exam2/Exam2.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": "3.BoundaryValueProblems/Exam2/Exam2.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": "3.BoundaryValueProblems/Exam2/Exam2.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.0, "max_line_length": 37, "alphanum_fraction": 0.4563636364, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104962847373, "lm_q2_score": 0.9032942132122422, "lm_q1q2_score": 0.8729530088815743}}
{"text": "\r\n\r\n\r\nmodule number\r\n\r\n\r\n\r\nfunction gcd(a::T, b::T) where {T <: Integer}\r\n    a, b = (a < b) ? (b, a) : (a, b)\r\n    while b != 0\r\n        c = b\r\n        d = mod(a, b)\r\n        a = c\r\n        b = d\r\n    end\r\n    return a\r\nend\r\n\r\nfunction lcm(a, b)\r\n    (a, b) = (a < b) ? (a, b) : (b, a)\r\n    d = gcd(b, a)\r\n    return div(b, d) * a\r\nend\r\n\r\nfunction sieve_of_eratosthenes(n)\r\n    a = trues(n)\r\n    max_n = ceil(Int, sqrt(Float64(n)))\r\n\r\n    for ii = 2:max_n\r\n        if a[ii]\r\n            jj = ii^2\r\n            while jj <= n\r\n                a[jj] = false\r\n                jj += ii\r\n            end\r\n        end\r\n    end\r\n    a[1] = false # for 1\r\n    pr = findall(a)\r\n    return pr\r\nend\r\n\r\n\r\n\r\nend\r\n\r\n\r\n#=\r\nmodule ntest\r\nusing ..number\r\n\r\na = 30 # 2 * 3 * 5\r\nb = 21 # 3 * 7\r\n\r\nd = number.gcd(a, b) # 3\r\nl = number.lcm(a, b) # 7 * 2 * 5 * 3\r\n\r\n\r\na = 28 # 2*2 * 7\r\nb = 21 # 3 * 7\r\n\r\nd = number.gcd(a, b) # 3\r\nl = number.lcm(a, b) # 2 * 2 * 3 * 7\r\n\r\n\r\npr = number.sieve_of_eratosthenes(1000)\r\n\r\n\r\nend\r\n=#\r\n\r\n", "meta": {"hexsha": "d3863af3ed348e06c28bb80d8c76ba49d15dc8b6", "size": 1006, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "__lib__/math/number_theo/src/number_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/number_theo/src/number_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/number_theo/src/number_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": 13.9722222222, "max_line_length": 46, "alphanum_fraction": 0.4035785288, "num_tokens": 384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.97241471777321, "lm_q2_score": 0.8976953003183444, "lm_q1q2_score": 0.8729321221053998}}
{"text": "using Distributions, Plots, LaTeXStrings, Random; pyplot()\n\nfunction tStat(mu0,mu,sig,n)\n    sample = rand(Normal(mu,sig),n)\n    xBar   = mean(sample)\n    s      = std(sample)\n    (xBar-mu0) / (s/sqrt(n))\nend\n\nfunction powerEstimate(mu0,mu1,sig,n,alpha,N)\n    Random.seed!(0)\n    sampleH1 = [tStat(mu0,mu1,sig,n) for _ in 1:N]\n    critVal  = quantile(TDist(n-1),1-alpha)\n    sum(sampleH1 .> critVal)/N\nend\n\nmu0 = 20\nsig = 5\nalpha = 0.05\nN = 10^4\nrangeMu1 = 16:0.1:30\nnList = [5,10,20,30]\n\npowerCurves = [powerEstimate.(mu0,rangeMu1,sig,n,alpha,N) for n in nList]    \n\nplot(rangeMu1,powerCurves[1],c=:blue, label=\"n = $(nList[1])\")\nplot!(rangeMu1,powerCurves[2],c=:red, label=\"n = $(nList[2])\")\nplot!(rangeMu1,powerCurves[3],c=:green, label=\"n = $(nList[3])\")\nplot!(rangeMu1,powerCurves[4],c=:purple, label=\"n = $(nList[4])\", \n\txlabel= L\"\\mu\", ylabel=\"Power\", \n\txlims=(minimum(rangeMu1) ,maximum(rangeMu1)), ylims=(0,1))", "meta": {"hexsha": "001dcc49b70a07abd352d72980ee24539322a01f", "size": 919, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "7_chapter/powerCurves.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/powerCurves.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/powerCurves.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.6451612903, "max_line_length": 77, "alphanum_fraction": 0.6430903156, "num_tokens": 364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9736446494481298, "lm_q2_score": 0.8962513793687401, "lm_q1q2_score": 0.8726303600828798}}
{"text": "export permanent, veroneselift\n\nusing Combinatorics\n\nfunction permanent(A, perms)\n    n = LinearAlgebra.checksquare(A)\n    sum(\u03c3 -> prod(i -> A[i,\u03c3[i]], 1:n), perms)\nend\n\nfunction \u03bc(combi)\n    prod = 1\n    last = 0\n    cur = 1\n    for i in combi\n        if i == last\n            cur += 1\n        else\n            prod *= factorial(cur)\n            last = i\n            cur = 1\n        end\n    end\n    prod *= factorial(cur)\n    return prod\nend\n\n\"\"\"\n   veroneselift_explicit(A::AbstractMatrix, d::Integer)\n\nComputes the Veronese lift of degree `d` of `A` using the explicit formula\n```math\n(A^{[d]})_{\\\\alpha\\\\beta} = \\\\frac{\\\\text{per}\\\\,A(\\\\alpha, \\\\beta)}{\\\\sqrt{\\\\mu(\\\\alpha)\\\\mu(\\\\beta)}}\n```\ngiven in equation (8) of [PJ08]. Note that this is a lot slower than\n[`veroneselift`](@ref) and is implemented mainly for educational purpose.\n\n* [PJ08] P. Parrilo and A. Jadbabaie.\n*Approximation of the joint spectral radius using sum of squares*.\nLinear Algebra and its Applications, Elsevier, **2008**, 428, 2385-2402\n\"\"\"\nfunction veroneselift_explicit(A::AbstractMatrix, d::Integer)\n    d > 0 || throw(ArgumentError(\"`d` should be a positive integer, got $d\"))\n\n    n = LinearAlgebra.checksquare(A)\n    N = binomial(n+d-1, d)\n\n    Ad = Matrix{Float64}(undef, N, N)\n\n    # Computing permutations is the most expensive part so we precompute it\n    perms = collect(permutations(1:d))\n    for (i,\u03b1) in enumerate(with_replacement_combinations(1:n, d))\n        for (j,\u03b2) in enumerate(with_replacement_combinations(1:n, d))\n            Ad[i, j] = permanent(A[\u03b1, \u03b2], perms) / sqrt(\u03bc(\u03b1) * \u03bc(\u03b2))\n        end\n    end\n\n    return Ad\nend\n\n\nfunction transform_combination(\u03b1, m)\n    \u03b2 = zeros(Int, m)\n    for i in \u03b1\n        \u03b2[i] += 1\n    end\n    return \u03b2\nend\n\n\"\"\"\n   veroneselift(A::AbstractMatrix, d::Integer)\n\nComputes the Veronese lift of degree `d` of `A` using `DynamicPolynomials`.\n\"\"\"\nfunction veroneselift(A::AbstractMatrix, d::Integer)\n    d > 0 || throw(ArgumentError(\"`d` should be a positive integer, got $d\"))\n    m, n = size(A)\n    @polyvar x[1:n]\n    Ax = A * x\n    M = binomial(m + d - 1, d)\n    N = binomial(n + d - 1, d)\n    Ad = Matrix{Float64}(undef, M, N)\n    df = factorial(d)\n    scaling(m) = sqrt(df / prod(factorial, exponents(m)))\n    X = monomials(x, d)\n    # Scaling for the scaled monomial basis\n    col_scaling = Float64[scaling(m) for m in X]\n    if m == n\n        Y = X\n        row_scaling = col_scaling\n    else\n        # Only exponents matter\n        @polyvar y[1:m]\n        Y = monomials(y, d)\n        row_scaling = Float64[scaling(m) for m in Y]\n    end\n    for (i, mono) in enumerate(Y)\n        \u03b1 = exponents(mono)\n        Ax\u03b1 = prod(i -> Ax[i]^\u03b1[i], 1:m)\n        Ad[i, :] = MP.coefficients(Ax\u03b1, X) .* row_scaling[i] ./ col_scaling\n    end\n    return Ad\nend\n", "meta": {"hexsha": "f03720a0936eb8434785a34166c24cc1b9e82609", "size": 2781, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/veronese.jl", "max_stars_repo_name": "blegat/SwitchedSystems.jl", "max_stars_repo_head_hexsha": "88c6c64f7499de1fc8b039cfc2da393778f1e4c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-12-26T18:35:52.000Z", "max_stars_repo_stars_event_max_datetime": "2016-12-26T19:32:52.000Z", "max_issues_repo_path": "src/veronese.jl", "max_issues_repo_name": "blegat/SwitchedSystems.jl", "max_issues_repo_head_hexsha": "88c6c64f7499de1fc8b039cfc2da393778f1e4c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/veronese.jl", "max_forks_repo_name": "blegat/SwitchedSystems.jl", "max_forks_repo_head_hexsha": "88c6c64f7499de1fc8b039cfc2da393778f1e4c4", "max_forks_repo_licenses": ["MIT"], "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": 103, "alphanum_fraction": 0.6030204962, "num_tokens": 866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422186079557, "lm_q2_score": 0.9173026528034426, "lm_q1q2_score": 0.8724852803224297}}
{"text": "module MonteCarlo\n\nexport mcintegral\n\nusing Statistics\n\n\"\"\"\nIntegrate a 1D real function using Monte Carlo integration with importance sampling\n\nDoes uniform sampling by default\n\n# Arguments\n- `func`: the function to be integrated\n- `lo`: lower bound of the integral\n- `up`: upper bound of the integral\n- `samples`: the number of random samples used for integration\n- `impfunc`: The importance sampling function.\n    Constant function `x -> 1` by default (for uniform sampling).\n- `impint`: the integral of the importance function in the integration interval. If equal to\n    zero, this function will calculate the integral itself. `up - lo` by default\n    (for uniform sampling).\n- `distribution`: Applies this transformation function to the random numbers generated\n    in the range [0, 1] to get the random samples used for integration. This must be\n    a distribution that gives a probability density function proportional to impfunc\n    to get the correct results. By default, samples are uniformly generated in the range\n    [lo, up].\n\n# Returns\n\nThe calculated integral and the standard error\n\"\"\"\nfunction mcintegral(func::Function, lo::Real, up::Real; samples::Integer = 10000,\n        impfunc::Function = x -> 1, impint::Real = up - lo,\n        distribution::Function = x -> muladd(x, up - lo, lo))\n    if impint == 0\n        impint = (up - lo) * mean(impfunc.(muladd.(rand(samples), up - lo, lo)))\n    end\n\n    intfunc(x) = func(x) / impfunc(x)\n    samplevalues = intfunc.(distribution.(rand(samples)))\n    avg = mean(samplevalues) \n\n    integral = impint * avg\n    error = impint / \u221asamples * std(samplevalues, mean=avg)\n\n    return integral, error\nend\n\n\"\"\"\nn-dimensional Monte Carlo integration with importance sampling\n\nDoes uniform sampling by default\n\n# Arguments\n- `func`: the function to be integrated\n- `lo`: vector of lower bounds of the integral\n- `up`: vector of upper bounds of the integral\n- `samples`: the number of random samples used for integration\n- `impfunc`: The importance sampling function.\n    Constant function `(x...) -> 1` by default (for uniform sampling).\n- `impint`: the integral of the importance function in the integration interval. If equal to\n    zero, this function will calculate the integral itself. `up - lo` by default\n    (for uniform sampling).\n- `distribution`: Applies this transformation function to the random collection of numbers\n    generated in the range [0, 1] to get the random samples used for integration. This must\n    be a distribution that gives a probability density function proportional to impfunc\n    to get the correct results. By default, samples are uniformly generated in the range\n    [lo, up].\n\nPlease note that `length(lo)` must equal `length(up)` and all functions should also take\nthis many arguments as their input.\n\n# Returns\n\nThe calculated integral and the standard error\n\"\"\"\nfunction mcintegral(func::Function, lo::Vector{<:Real}, up::Vector{<:Real};\n        samples::Integer = 10000,\n        impfunc::Function = (x...) -> 1, impint::Real = reduce(.*, up .- lo),\n        distribution::Function = (x...) -> muladd.(x, up .- lo, lo))\n    ndims = length(up)\n    if impint == 0\n        rndnums = rand(ndims, samples)\n        samplepoints = [muladd.(x, up .- lo, lo) for x in eachcol(rndnums)]\n        impint = (up - lo) * mean(impfunc(x...) for x in samplepoints)\n    end\n\n    rndnums = rand(ndims, samples)\n    samplepoints = [distribution(x...) for x in eachcol(rndnums)]\n\n    intfunc(x...) = func(x...) / impfunc(x...)\n    samplevalues = [intfunc(x...) for x in samplepoints]\n    avg = mean(samplevalues)\n\n    integral = impint * avg\n    error = impint / \u221asamples * std(samplevalues, mean=avg)\n\n    return integral, error\nend\n\nend\n", "meta": {"hexsha": "eefb1098721bd0e6f7d6030326fce613bc0c9e50", "size": 3714, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ps7-integration-metropolis/p1-2-monte-carlo-integration/MonteCarlo.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/p1-2-monte-carlo-integration/MonteCarlo.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/p1-2-monte-carlo-integration/MonteCarlo.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": 36.4117647059, "max_line_length": 92, "alphanum_fraction": 0.696553581, "num_tokens": 913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338079816758, "lm_q2_score": 0.9073122176012061, "lm_q1q2_score": 0.8724113716183864}}
{"text": "\n@doc raw\"\"\"\nThe Gauss nodes are given by the roots of the shifted Legendre polynomial\n$P_s (2x-1)$ with $s$ the number of stages.\n\"\"\"\nfunction get_gauss_nodes(::Type{T}, s) where {T}\n    sort(T.(Polynomials.roots(_shifted_legendre(s,T))))\nend\n\nget_gauss_nodes(s) = get_gauss_nodes(BigFloat, s)\n\n\n@doc raw\"\"\"\nThe Gauss weights are given by the following integrals\n```math\nb_i = \\bigg( \\frac{dP}{dx} (c_i) \\bigg)^{-2} \\int \\limits_0^1 \\bigg( \\frac{P(x)}{x - c_i} \\bigg)^2 dx ,\n```\nwhere $P(x)$ denotes the shifted Legendre polynomial\n$P(x) = P_s (2x-1)$ with $s$ the number of stages.\n\"\"\"\nfunction get_gauss_weights(::Type{T}, s) where {T}\n    c = get_gauss_nodes(T,s)\n    P = _shifted_legendre(s,T)\n    D = Polynomials.derivative(P)\n    \n    inti(i) = begin\n        I = Polynomials.integrate( ( P \u00f7 Polynomial(T[-c[i], 1]) )^2 )\n        I(1) - I(0)\n    end\n    \n    b = [ inti(i) / D(c[i])^2  for i in 1:s ]\nend\n\nget_gauss_weights(s) = get_gauss_weights(BigFloat, s)\n\n\n@doc raw\"\"\"\nThe Gauss coefficients are implicitly given by the so-called simplifying assumption $C(s)$:\n```math\n\\sum \\limits_{j=1}^{s} a_{ij} c_{j}^{k-1} = \\frac{c_i^k}{k}  \\qquad i = 1 , \\, ... , \\, s , \\; k = 1 , \\, ... , \\, s .\n```\n\"\"\"\nfunction get_gauss_coefficients(::Type{T}, s) where {T}\n    solve_simplifying_assumption_c(get_gauss_nodes(T,s))\nend\n\nget_gauss_coefficients(s) = get_gauss_coefficients(BigFloat, s)\n\n\n\"\"\"\nGauss tableau with s stages\n\n```julia\nTableauGauss(::Type{T}, s)\nTableauGauss(s) = TableauGauss(Float64, s)\n```\n\nThe constructor takes the number of stages `s` and optionally the element type `T` of the tableau.\n\nReferences:\n\n    John C. Butcher.\n    Implicit Runge-Kutta processes.\n    Mathematics of Computation, Volume 18, Pages 50-64, 1964.\n    doi: 10.1090/S0025-5718-1964-0159424-9.\n\n    John C. Butcher.\n    Gauss Methods. \n    In: Engquist B. (eds). Encyclopedia of Applied and Computational Mathematics. Springer, Berlin, Heidelberg. 2015.\n    doi: 10.1007/978-3-540-70529-1_115.\n\n\"\"\"\nfunction TableauGauss(::Type{T}, s) where {T}\n    Tableau{T}(Symbol(\"Gauss($s)\"), 2s, get_gauss_coefficients(s), get_gauss_weights(s), get_gauss_nodes(s))\nend\n\nTableauGauss(s) = TableauGauss(Float64, s)\n", "meta": {"hexsha": "40e04bbc0302800326eb4bd1129698f4e77b5bb8", "size": 2193, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/tableaus/gauss.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/tableaus/gauss.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/tableaus/gauss.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": 28.1153846154, "max_line_length": 118, "alphanum_fraction": 0.6625626995, "num_tokens": 738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813451206063, "lm_q2_score": 0.9124361640485893, "lm_q1q2_score": 0.8722719514438566}}
{"text": "using Turing, MCMCChains, Distributions\n\n@model HMM(y) = begin\n    n = length(y)\n    x = zeros(Int64, length(y)) # hidden states\n\n    # Define priors\n    p\u2081 ~ Uniform(0,1) # Transition probability 1\u21921\n    p\u2082 ~ Uniform(0,1) # Transition probability 2\u21921\n\n    # Define transition matrix\n    P = [p\u2081 1-p\u2081; p\u2082 1-p\u2082]\n\n    # Initialize samples\n    x[1] ~ Categorical([0.5,0.5]) # Start Z at either 1 or 2\n    y[1] ~ Normal(x[1],0.1)\n\n    for i=2:n\n        # Get next hidden state\n        x[i] ~ Categorical(P[x[i-1],:])\n        y[i] ~ Normal(x[i], 0.1) # Add noise\n    end\n\n    return (p\u2081, p\u2082)\nend\n\n## Simulate observed data\nusing DataFrames\nusing CSV\np\u2081 = 0.25\np\u2082 = 0.55\nP = [p\u2081 1-p\u2081; p\u2082 1-p\u2082]\ndata_n = 15\nZ_samples = zeros(Int64, data_n)\nZ_samples[1] = rand(Categorical([0.5, 0.5]))\nX_samples = zeros(data_n)\nX_samples[1] = rand(Normal(Z_samples[1], 0.1))\nfor i=2:data_n\n    Z_samples[i] = rand(Categorical(P[Z_samples[i-1],:]))\n    X_samples[i] = rand(Normal(Z_samples[i], 0.1))\nend\n\ndf = DataFrame(Y = X_samples)\nCSV.write(\"pp_ex_2_data.csv\", df)\n##\n\n# Load observed data\ndata = CSV.read(\"pp_ex_2_data.csv\")[:,1]\n\n## Use HMC sampler to obtain posterior samples\nnum_posterior_samples = 1000\n\u03f5 = 0.1 # Leapfrog step size\n\u03c4 = 10   # Number of leapfrog iterations\nhmc = HMC(\u03f5, \u03c4, :p\u2081, :p\u2082)\nparticle_gibbs = Turing.PG(20, :z)\nG = Gibbs(hmc, particle_gibbs)\n# Obtain posterior samples\nchain = sample(HMM(data), G, num_posterior_samples)\n\n# Extract summary of p parameter and plot histogram\nusing LaTeXStrings\nusing StatsPlots\n\nplot(chain[:p\u2081], seriestype = :histogram, bg =  RGB(247/255, 236/255, 226/255), title=L\"p_1\")\nplot(chain[:p\u2082], seriestype = :histogram, bg =  RGB(247/255, 236/255, 226/255), title=L\"p_2\")\n\n\nsavefig(\"../images/pp_ex_2_hist_2.svg\")\n\n# Extract 95% interval\nprintln(quantile(Array(chain[:p\u2081]), [0.025, 0.975]))\nprintln(quantile(Array(chain[:p\u2082]), [0.025, 0.975]))\n", "meta": {"hexsha": "bda477492bf72fb759966c6ae798a80c90cf1c0d", "size": 1878, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "content/bayesian-inference-and-graphical-models/code/pp_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/bayesian-inference-and-graphical-models/code/pp_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/bayesian-inference-and-graphical-models/code/pp_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": 25.7260273973, "max_line_length": 93, "alphanum_fraction": 0.6586794462, "num_tokens": 674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959762055074521, "lm_q2_score": 0.908617893221035, "lm_q1q2_score": 0.8720569764753022}}
{"text": "using LinearAlgebra\n\nA = [1 2; 3 4]\nb = [5,1]\nx = A \\ b         # Solve Ax = b for x\nA*x == b        # Confirm solution is correct\n\nB = [5 7; 1 -3]\nX = A \\ B          # Solve for two RHS vectors\nA*X == B\n\nn = 2000\nT = SymTridiagonal(2ones(n), -ones(n))     # n-by-n symmetric tridiagonal\n\nfor rep = 1:3 @time T \\ randn(n) end       # Very fast since T is a SymTridiagonal\nTfull = Matrix(T)                          # Convert T to a full 2D array\nfor rep = 1:3 @time Tfull \\ randn(n) end   # Now \\ is magnitudes slower\n\nx = 0:0.1:10\nn = length(x)\ny = 3x .- 2 + randn(n)     # Example data: straight line with noise\n\nA = [ones(n) x]            # LHS\nab = A \\ y                 # Least-squares solution\n\nusing PyPlot\nxplot = 0:10;\nyplot = @. ab[1] + ab[2] * xplot\nplot(x,y,\".\")\nplot(xplot, yplot, \"r\");\n", "meta": {"hexsha": "16deff76d87bc0f35de7dd88e59d52e29a6dbe88", "size": 800, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "textbook/_build/jupyter_execute/content/Linear_Algebra/Linear_Systems_And_Regression.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/Linear_Systems_And_Regression.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/Linear_Systems_And_Regression.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.8064516129, "max_line_length": 82, "alphanum_fraction": 0.54375, "num_tokens": 293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811611608242, "lm_q2_score": 0.9032942132122422, "lm_q1q2_score": 0.8720232164206875}}
{"text": "using LinearAlgebra # for the norm and dot function\nusing ForwardDiff # for automatic differentiation\n\n#=\n\n## 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\nBelow you find some pseudo-code and a few template for the functions you could create.\n(You can change name and arguments of the functions in your implementation of course.)\n\nThe pseudo algorithms are:\n\n\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\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\nSource: [https://web.stanford.edu/class/ee364a/lectures/unconstrained.pdf](https://web.stanford.edu/class/ee364a/lectures/unconstrained.pdf)\n\n=#\n\nfunction linesearch(f, \u0394x, x, \u03b1, \u03b2; t_min = 1e-5)\n\t# write your code here\n\n\treturn NaN\nend\n\nfunction gradientdecent(f, x0, \u03b1, \u03b2, \u03b5; max_steps = 1e4)\n\t@assert \u03b2 < 1\n\t@assert \u03b1 < 0.5\n\t# write your code here\n\n\treturn NaN\nend\n\n# test case\n\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", "meta": {"hexsha": "f87d8ff6f44744ffca82a956b78506d75a345924", "size": 1382, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "exercises/atom/gradient_decent.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/gradient_decent.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/gradient_decent.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": 20.9393939394, "max_line_length": 140, "alphanum_fraction": 0.6881331404, "num_tokens": 473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545304202039, "lm_q2_score": 0.91964253282959, "lm_q1q2_score": 0.8719632338694868}}
{"text": "\"\"\"\n\tEstimates the integral of f between a and b by the trapezoidal rule\n\n    trapz(f, a, b, n)\n\n\t Parameters\n\t ----------\n     `f` is the function to integrate\n     `a` lower bound for the interval\n     `b` upper bound for the interval\n     `n` number of partition of [a,b]\n\"\"\"\n\nfunction trapz(f, a, b, n)\n    h = (b - a)/n\n    integral = f(a) + f(b)\n    i = 1\n    while i < n\n        x1 = a + i*h\n        integral += 2*f(x1)\n        i += 1\n    end\n    integral *= h/2\n    return integral\nend\n", "meta": {"hexsha": "43e6926142641adc6e7e87b80fecae3cb095a44d", "size": 494, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Utils.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/Utils.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/Utils.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.0, "max_line_length": 68, "alphanum_fraction": 0.5303643725, "num_tokens": 162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191259110588, "lm_q2_score": 0.9124361557147439, "lm_q1q2_score": 0.871667710727056}}
{"text": "using LinearAlgebra\nsq(x) = x*x\n\n\"Fits a straight line through a set of points, `y = a\u2081 + a\u2082 * x`\"\nfunction linear_fit(x, y)\n\n    \n    sx = sum(x)\n    sy = sum(y)\n\n    m = length(x)\n\n    sx2 = zero(sx)\n    sy2 = zero(sy)\n    sxy = zero(sx*sy)\n\n    for i = 1:m\n        sx2 += x[i]*x[i]\n        sy2 += y[i]*y[i]\n        sxy += x[i]*y[i]\n    end\n\n    a0 = (sx2*sy - sxy*sx) / ( m*sx2 - sx*sx )\n    a1 = (m*sxy - sx*sy) / (m*sx2 - sx*sx)\n\n    return [a0, a1]\nend\n\n\"Fits a log function through a set of points: `y = a\u2081+ a\u2082*log(x)`\"\nlog_fit(x, y) = linear_fit(log.(x), y)\n\n\"Fits a power law through a set of points: `y = a\u2081*x^a\u2082`\"\nfunction power_fit(x, y)\n    fit = linear_fit(log.(x), log.(y))\n    [exp(fit[1]), fit[2]]\nend\n\n\"Fits an `exp` through a set of points: `y = a\u2081*exp(a\u2082*x)`\"\nfunction exp_fit(x, y)\n    fit = linear_fit(x, log.(y))\n    [exp(fit[1]), fit[2]]\nend\n\n\"\"\"\nCreate Vandermonde matrix for simple polynomial fit\n\"\"\"\nfunction vandermondepoly(x, y, n)\n    m = length(x)\n    A = zeros(eltype(y), m, n+1)\n    A[:,1] .= 1.0\n\n    for i = 1:n\n        for k in 1:m\n            A[k, i+1] = A[k, i] * x[k]\n        end\n    end\n    return A\nend\n\n\"\"\"\n    Calculates the coefficients of a linear model using Least Squares\n\nGiven a Vandermonde matrix, this function uses the QR factorization to compute the Least Squares\nfit of a linear model. The code probably could be optimized.\n\n\"\"\"\nfunction fit_linear_model(Av, y)\n    m, n = size(Av)\n    F = qr(Av)\n\n    d = (F.Q * Matrix(I, m, n))' * y\n    R = UpperTriangular(F.R)\n\n    coefs = R\\d\n\n    return coefs\n   \nend\n\n\"\"\"\nFits a polynomial of degree `n` through a set of points.\n\nSimple algorithm, doesn't use orthogonal polynomials or any such thing \nand therefore unconditioned matrices are possible. Use it only for low\ndegree polynomials. \n\nThis function returns a the coefficients of the polynomial.\n\"\"\"\nfunction poly_fit(x, y, n)\n\n    A = vandermondepoly(x, y, n)\n    coefs = fit_linear_model(A, y)\n    return coefs\nend\n\n\n    \n\n\n\"\"\"\nHigh Level interface for fitting straight lines\n\"\"\"\nstruct LinearFit{T<:Number} <: LeastSquares\n    coefs::Array{T,1}\n    LinearFit{T}(coefs) where {T<:Number} = new(copy(coefs))\nend\nLinearFit(x::AbstractVector{T}, y::AbstractVector{T}) where {T<:Number} = LinearFit{T}(linear_fit(x, y))\n\n\n\"High Level interface for fitting log laws\"\nstruct LogFit{T<:Number} <: LeastSquares\n    coefs::Array{T,1}\n    LogFit{T}(coefs) where {T<:Number} = new(copy(coefs))\nend\nLogFit(x::AbstractVector{T}, y::AbstractVector{T}) where {T<:Number} = LogFit{T}(log_fit(x, y))\n\n\"High Level interface for fitting power laws\"\nstruct PowerFit{T<:Number} <: LeastSquares\n    coefs::Array{T,1}\n    PowerFit{T}(coefs) where {T<:Number} = new(copy(coefs))\nend\nPowerFit(x::AbstractVector{T}, y::AbstractVector{T}) where {T<:Number} = PowerFit{T}(power_fit(x, y))\n\n\"High Level interface for fitting exp laws\"\nstruct ExpFit{T<:Number} <: LeastSquares\n    coefs::Array{T,1}\n    ExpFit{T}(coefs) where {T<:Number} = new(copy(coefs))\nend\nExpFit(x::AbstractVector{T}, y::AbstractVector{T}) where {T<:Number} = ExpFit{T}(exp_fit(x, y))\n\n\n\n\"\"\"\n# Generic interface for curve fitting.\n\nThe same function `curve_fit` can be used to fit the data depending on fit type, \nshich is specified in the first parameter. This function returns an object that\ncan be used to estimate the value of the fitting model using function `apply_fit`.\n\n## A few examples:\n\n * `f = curve_fit(LinearFit, x, y)`\n * `f = curve_fit(Poly, x, y, n)`\n\"\"\"\ncurve_fit(::Type{T}, x, y) where {T<:LeastSquares} = T(x, y)\ncurve_fit(::Type{T}, x, y, args...) where {T<:LeastSquares} = T(x, y, args...)\ncurve_fit(::Type{Poly}, x, y, n=1) = Poly(poly_fit(x, y, n))\n\n\n\n(f::LinearFit)(x) = f.coefs[1] + f.coefs[2] *x\n(f::PowerFit)(x) = f.coefs[1] * x ^ f.coefs[2]\n(f::LogFit)(x) = f.coefs[1] + f.coefs[2] * log(x)\n(f::ExpFit)(x) = f.coefs[1] * exp(f.coefs[2] * x)\n", "meta": {"hexsha": "6a450efc7224b6ed7ace1dbd487db36133fb71ae", "size": 3867, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/linfit.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": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/linfit.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/linfit.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.9483870968, "max_line_length": 104, "alphanum_fraction": 0.6312386863, "num_tokens": 1277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960361162033533, "lm_q2_score": 0.9073122144683576, "lm_q1q2_score": 0.87134741261405}}
{"text": "##############   EXAMPLE-1    ##############\n# Non-correlated errors in X and in Y\n\nusing LinearFitXYerrors\nusing Plots; gr()\n\n# INPUT DATA:\n# York, D. [1966] Least-squares fitting of a straight line. Canadian Journal of Physics, 44(5), pp.1079\u20131086\n# Cantrell, C. [2008] Technical Note: Review of methods for linear least-squares fitting of data and application to atmospheric chemistry problems. Atmospheric Chem. & Physics, 8(17), pp.5477\u20135487\n\n# Tables I and II from York [1966]\n\nX = [0.0, 0.9, 1.8, 2.6, 3.3, 4.4, 5.2, 6.1, 6.5, 7.4]\nY = [5.9, 5.4, 4.4, 4.6, 3.5, 3.7, 2.8, 2.8, 2.4, 1.5]\n\n# the weights \u03c9X, \u03c9Y are the inverse of the variances\n\u03c3X = 1 ./ sqrt.([1000., 1000, 500, 800, 200, 80,  60, 20, 1.8, 1])\n\u03c3Y = 1 ./ sqrt.([1., 1.8, 4, 8, 20, 20, 70, 70, 100, 500])\nr = 0*X;\n\n\n# COMPUTE and PLOT:\nstxy = linearfitxy(X,Y; \u03c3X=\u03c3X, \u03c3Y=\u03c3Y, r=r, isplot=true);\n\n\n# If assuming only erros in Y or in X:\nsty = linearfitxy(X,Y; \u03c3X=0, \u03c3Y=\u03c3Y, r=r);\nstx = linearfitxy(X,Y; \u03c3X=\u03c3X, \u03c3Y=0, r=r);\n\ndX = diff([extrema(X)...])[1]/7\nx1, x2 = (-dX, dX) .+ extrema(X)\nxx = [x1; X; x2]\nplot!(xx, sty.a .+ sty.b*xx, color=:lime, lw=0.5, label=\"LinearFitXY (Y errors)\")\nplot!(xx, stx.a .+ stx.b*xx, color=:orange, lw=0.5, label=\"LinearFitXY (X errors)\")\n\n\nsavefig(\"Example1_LinearFitXYerrors.png\")\n########################################\n", "meta": {"hexsha": "f19ec218737e96c508e6f68a7be4a99d727e2f00", "size": 1322, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/example1.jl", "max_stars_repo_name": "rafael-guerra-www/LinearFitXYerrors.jl", "max_stars_repo_head_hexsha": "5109cda43472fb08f61b12ac792ca991a233c6a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-09-12T18:13:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-18T10:11:37.000Z", "max_issues_repo_path": "examples/example1.jl", "max_issues_repo_name": "rafael-guerra-www/LinearFitXYerrors.jl", "max_issues_repo_head_hexsha": "5109cda43472fb08f61b12ac792ca991a233c6a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-09-12T11:21:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-11T19:43:40.000Z", "max_forks_repo_path": "examples/example1.jl", "max_forks_repo_name": "rafael-guerra-www/LinearFitXYerrors.jl", "max_forks_repo_head_hexsha": "5109cda43472fb08f61b12ac792ca991a233c6a3", "max_forks_repo_licenses": ["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.8974358974, "max_line_length": 196, "alphanum_fraction": 0.5983358548, "num_tokens": 561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693688269984, "lm_q2_score": 0.9173026624116692, "lm_q1q2_score": 0.8711342404358151}}
{"text": "\n\"\"\"\nCompute the `n-th` degree Chebyshev polynomial of first and second kind and its derivatives\n\n * `chebyshev(x, n)` Chebyshev polynomial of the first kind\n * `chebyshev2(x, n)` Chebyshev polynomial of the second kind\n * `dchebyshev(x, n)` Derivative of Chebyshev polynomial of the first kind\n * `dchebyshev2(x, n)` Derivative of Chebyshev polynomial of the second kind\n\nThere are also functions that compute the zeros of Chebyshev polynomials:\n\n * `chebyshev_zeros`\n * `chebyshev2_zeros`\n * `chebyshev_zeros!`\n * `chebyshev2_zeros!`\n\n\"\"\"\nfunction chebyshev(x, n)\n    if n==0\n        return one(x)\n    elseif n==1\n        return x\n    end\n\n    T0 = one(x)\n    T1 = x\n\n    for i = 2:n\n        T2 = 2*x*T1 - T0\n        T0 = T1\n        T1 = T2\n    end\n\n    return T1\n\nend\n\n\nfunction chebyshev2(x, n)\n\n    if n==0\n        return one(x)\n    elseif n==1\n        return 2x\n    end\n\n    U0 = one(x)\n    U1 = 2*x\n\n    for i = 2:n\n        U2 = 2*x*U1 - U0\n        U0 = U1\n        U1 = U2\n    end\n\n    return U1\n\n    \nend\n\n\ndchebyshev(x, n) = n * chebyshev2(x, n-1)\n\n\n\nfunction dchebyshev2(x, n)\n\n    if n == 0\n        return zero(x)\n    elseif n==1\n        return 2*one(x)\n    end\n\n    dU0 = zero(x)\n    dU1 = 2\n    U0 = one(x)\n    U1 = 2*x\n\n    for i = 2:n\n        U2 = 2*x*U1 - U0\n        dU2 = 2*U1 + 2*x*dU1 - dU0\n        \n        U0 = U1\n        U1 = U2\n        dU0 = dU1\n        dU1 = dU2\n    end\n\n    return dU1\nend\n\n\n\n\nfunction chebyshev_zeros!(n, x::AbstractArray{T}) where {T<:Number}\n\n    for k in 1:n\n        num::T =  (2*k - 1)*pi\n        \n        x[k] = -cos( num/(2*n) )\n    end\n\n    return x\n\nend\n\nchebyshev_zeros(n, ::Type{T}=Float64) where {T<:Number} = chebyshev_zeros!(n, zeros(T, n))\n\nfunction chebyshev2_zeros!(n, x::AbstractArray{T}) where {T<:Number}\n\n    for k in 1:n\n        num::T = k*pi\n        \n        x[k] = -cos( num/(n+1) )\n    end\n\n    return x\n\nend\nchebyshev2_zeros(n, ::Type{T}=Float64) where {T<:Number} = chebyshev2_zeros!(n, zeros(T, n))\n\n@doc (@doc chebyshev) chebyshev2\n\n@doc (@doc chebyshev) dchebyshev\n@doc (@doc chebyshev) dchebyshev2\n\n@doc (@doc chebyshev) chebyshev_zeros!\n@doc (@doc chebyshev) chebyshev2_zeros!\n@doc (@doc chebyshev) chebyshev_zeros\n@doc (@doc chebyshev) chebyshev2_zeros\n\n", "meta": {"hexsha": "172d7a6b440ae0fe86ca5f0b8525306559a68ecc", "size": 2229, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chebyshev.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/Jacobi.jl-83f21c0b-4282-5fbc-9e3f-f6da3d2e584c", "max_stars_repo_head_hexsha": "342433a86ee29b7a681c2d6e1f863b3ea49dea0f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/chebyshev.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/Jacobi.jl-83f21c0b-4282-5fbc-9e3f-f6da3d2e584c", "max_issues_repo_head_hexsha": "342433a86ee29b7a681c2d6e1f863b3ea49dea0f", "max_issues_repo_licenses": ["MIT"], "max_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": "UnofficialJuliaMirrorSnapshots/Jacobi.jl-83f21c0b-4282-5fbc-9e3f-f6da3d2e584c", "max_forks_repo_head_hexsha": "342433a86ee29b7a681c2d6e1f863b3ea49dea0f", "max_forks_repo_licenses": ["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.8863636364, "max_line_length": 92, "alphanum_fraction": 0.5724540153, "num_tokens": 846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778036723353, "lm_q2_score": 0.9099070029841949, "lm_q1q2_score": 0.8710337773627871}}
{"text": "\"\"\"\n    perfect_cube(number)\n\nCheck if a number is a perfect cube or not.\n\n# Example\n```jula\nperfect_cube(27) # returns true\nperfect_cube(4)  # returns false\n```\n\nContributed By:- [Ashwani Rathee](https://github.com/ashwani-rathee)\n\"\"\"\nfunction perfect_cube(number)\n    val = number^(1/3)\n    return (val * val * val) == number\nend\n", "meta": {"hexsha": "7d9fd51150ea87fbb6f8829a10b5164ea73d9bb4", "size": 332, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/perfect_cube.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_cube.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_cube.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": 18.4444444444, "max_line_length": 68, "alphanum_fraction": 0.6807228916, "num_tokens": 97, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9597620573763841, "lm_q2_score": 0.907312219480915, "lm_q1q2_score": 0.8708038424517364}}
{"text": "x = randn(3)   # Random vector\n\nA = randn(3,3) # Random matrix\n\nusing LinearAlgebra\n\ny = randn(3)\nx - 3y\n\nx_dot_y_1 = dot(x,y)   # Dot product\nx_dot_y_2 = x \u22c5 y      # Same thing\n\nx_cross_y = cross(x,y)\n\na = norm(x)                 # 2-norm of x\nb = sqrt(sum(abs.(x).^2))   # Should be the same\na - b                       # Confirm\n\nB = randn(4,3)\nC = B*A     # OK, since B is 4-by-3 and A is 3-by-3\n\nAA = A*A     # Square of matrix\nA2 = A.*A    # Square of each entry in matrix\nA2 - AA      # These are not the same\n\nA_to_the_power_of_2 = A^2       # Same as A*A\nA_to_the_power_of_3_5 = A^3.5   # A^3.5, much harder to compute!\n\nBT = transpose(B)     # B is 4-by-3, so BT is 3-by-4\nBT2 = B'              # Same thing (since B is real so conjugate does not matter)\n\nA * B'                # Well-defined, since A is 3-by-3 and B' is 3-by-4\n\nx_dot_y_3 = x' * y\n\na = randn(3,1)   # Column vector\nb = randn(1,3)   # Row vector\n\na_dot_b = dot(a,b)\n\nA = randn(3,3)\nprintln(\"det(A) = \", det(A))\nprintln(\"tr(A) = \", tr(A))\nprintln(\"inv(A) = \", inv(A))\n\nA = randn(3,3)\nlambda = eigvals(A)     # Eigenvalues\n\nX = eigvecs(A)          # Eigenvectors\n\nnorm(A*X - X*Diagonal(lambda))     # Confirm A*X = X*LAMBDA\n\nusing PyPlot\nn = 1000\nA = randn(n,n)\nl = eigvals(A)\nplot(real(l), imag(l), \".\")\naxis(\"equal\");\n# Draw circle\nradius = sqrt(n)\nphi = 2\u03c0*(0:100)/100\nplot(radius*cos.(phi), radius*sin.(phi));\n\nnum = rand(-10:10, 3, 3)\nden = rand(1:10, 3, 3)\nrat = num .// den\ndisplay(rat)\ninv(rat)\n", "meta": {"hexsha": "e979e1c7f59596c834046ee08d303211093ed482", "size": 1479, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "textbook/_build/jupyter_execute/content/Linear_Algebra/Matrix_Operations.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/Matrix_Operations.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/Matrix_Operations.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.4347826087, "max_line_length": 81, "alphanum_fraction": 0.5672751859, "num_tokens": 559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799462157138, "lm_q2_score": 0.9032942106088968, "lm_q1q2_score": 0.8705768457176083}}
{"text": "\"\"\"\n    closest_pair_search(array::Array{Int64,1}, target::Int64)\n\nFinding the closet pair of values for a given target in a sorted array. For this reason,\nthe distance between a pair of of values has to be minimazied with respect to the target.\nFor more information see: [https://en.wikipedia.org/wiki/Closest_pair_of_points_problem](https://en.wikipedia.org/wiki/Closest_pair_of_points_problem)\n\n\n# Arguments\n- `array::Array{Int64,1}`: Sorted array of integers\n- `target::Int64`: Target-value to find the position\n\n\n# Examples\n```julia-repl\njulia> import ClassicAlgorithmsCollections\njulia> arr = [10, 22, 28, 29, 30, 40]\njulia> target = 56\njulia> ClassicAlgorithmsCollections.closest_pair_search(arr, target)\n(28, 29)\n```\n\"\"\"\nfunction closest_pair_search(array::Array{Int64,1}, target::Int64)\n\n    # To store indexes of result pair\n    res_left, res_right = 1, 1\n\n    #Initialize left, right array boundaries, and their difference\n    left, right, diff = 1, length(array), 999999\n\n    # While there are elements between left and right array boundaries\n    while right > left\n\n        # Check if the distance between the current pair is closer than the closest\n        # previous pair so far\n        if abs(array[left] + array[right] - target) < diff\n            res_left = left\n            res_right = right\n            # If yes update the distance\n            diff = abs(array[left] + array[right] - target)\n        end\n\n        # If this pair has more sum than the target, shrink the array to a smaller value\n        if array[left] + array[right] > target\n\n            right -= 1\n        # Otherwise, shrink the array to a larger value\n        else\n            left += 1\n        end\n    end\n    return array[res_left], array[res_right]\nend\n", "meta": {"hexsha": "e612d7baf56e36b583d6baf9901e16b2584dce5a", "size": 1745, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SortingAndSearching/ClosetPairSearch.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/ClosetPairSearch.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/ClosetPairSearch.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.3148148148, "max_line_length": 150, "alphanum_fraction": 0.6779369628, "num_tokens": 440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799441350253, "lm_q2_score": 0.90329420279886, "lm_q1q2_score": 0.8705768363109775}}
{"text": "function euler(f::Function, x::Float64, y::Vector{Float64}, steps::Int64, h::Float64)\n  nsteps = steps + 1\n  res = zeros(nsteps, length(y)+1)\n  for i in 1:nsteps\n    res[i,:] = [x; [y[i] for i in 1:length(y)]]\n    k0 = h * f(x, y)\n    y += k0\n    x += h\n  end\n  res\nend\n\nfunction modified_euler(f::Function, x::Float64, y::Vector{Float64}, steps::Int64, h::Float64)\n  nsteps = steps + 1\n  res = zeros(nsteps, length(y)+1)\n  for i in 1:nsteps\n    res[i,:] = [x; [y[i] for i in 1:length(y)]]\n    k0 = h * f(x, y)\n    k1 = h * f(x+h, y+k0)\n    y += (k0+k1)/2.0\n    x += h\n  end\n  res\nend\n\nfunction mid_point_euler(f::Function, x::Float64, y::Vector{Float64}, steps::Int64, h::Float64)\n  nsteps = steps + 1\n  res = zeros(nsteps, length(y)+1)\n  for i in 1:nsteps\n    res[i,:] = [x; [y[i] for i in 1:length(y)]]\n    k0 = h * f(x, y)\n    k1 = h * f(x+h/2.0, y+k0/2.0)\n    y += k1\n    x += h\n  end\n  res\nend\n\nfunction runga_kutta_4(f::Function, x::Float64, y::Vector{Float64}, steps::Int64, h::Float64)\n  nsteps = steps + 1\n  res = zeros(nsteps, length(y)+1)\n  for i in 1:nsteps\n    res[i,:] = [x; [y[i] for i in 1:length(y)]]\n    k0 = h * f(x, y)\n    k1 = h * f(x+h/2.0, y+k0/2.0)\n    k2 = h * f(x+h/2.0, y+k1/2.0)\n    k3 = h * f(x+h/2.0, y+k2)\n    y += (k0+2.0*k1+2.0*k2+k3)/6.0\n    x += h\n  end\n  res\nend\n", "meta": {"hexsha": "3cbbd3f54c19b6adce6f88e8d8782f2b1d30e2b1", "size": 1300, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ch07/ivp.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/ivp.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/ivp.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.5283018868, "max_line_length": 95, "alphanum_fraction": 0.54, "num_tokens": 570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854103128328, "lm_q2_score": 0.8976952873175982, "lm_q1q2_score": 0.8705717925471933}}
{"text": "# R2 attributed\n\nusing Distributions\n\nn = 10000\nx1 = rand(Normal(), n)\nx2 = rand(Normal(), n) .+ .2 * x1\nx3 = 1000*(rand(Normal(), n) .- .2 * x1 .+ .2 * x2)\n\nx2 = rand(Normal(), n)\nx3 = rand(Normal(), n)\n\nu = rand(Normal(), n) .* 2\n\ny = 2 .+ 1.5*x1 .+ 2.7*x2 .- .5* x3 + u\n\nconstant = fill(1,n)\nX = hcat(constant, x1, x2, x3)\n\n\u03b2 = inv(X'X) * X'y\n\ny\u0302 = X*\u03b2\n\ns\u00b2 = ((y-y\u0302)' * (y-y\u0302)) / (n-4)\n\n\nse\u03b2\u2081 = \u221a(s\u00b2 * inv(x1' * x1))\nse\u03b2\u2082 = \u221a(s\u00b2 * inv(x2' * x2))\nse\u03b2\u2083 = \u221a(s\u00b2 * inv(x3' * x3))\n\n\u221a(s\u00b2 .* inv(X'X))\n\nccdf(Chisq(4), s\u00b2)\n\n\nSS(x) = sum((x .- mean(x)).^2)\n\n# Sum of Squares Total\nSST = SS(y)\n\n# Sum of Squares Explained\nSSR = SS(y\u0302)\n\n# Sum of Squares Error\nSSE = SS(y-y\u0302)\n\n# Degrees of freedom model\nDFM = 4-1\n\n# Degrees of freedom total\nDFT = n-4\n\n# Mean of squares of regression\nMSR = SSR/DFM\n\n# Mean of squares of total\nMST = SSR/DFT\n\nF = MSR/MST\n\n\nR2 = SSR/SST\n\ny\u0302\u2081 = x1*\u03b2[2]\ny\u0302\u2082 = x2*\u03b2[3]\ny\u0302\u2083 = x3*\u03b2[4]\n\nSSR1 = SS(y\u0302\u2081)\nSSR2 = SS(y\u0302\u2082)\nSSR3 = SS(y\u0302\u2083)\n\nSSR\nSSRp = SSR1 + SSR2 + SSR3\n\nSSR1p = SSR1/SSRp\nSSR2p = SSR2/SSRp\nSSR3p = SSR3/SSRp\n\n\n##### Normalization Approach\nx1 = x1/var(x1)^.5\nx2 = x2/var(x2)^.5\nx3 = x3/var(x3)^.5\n\nX = hcat(constant, x1, x2, x3)\n\n\u03b2 = inv(X'X) * X'y\n\n# Asserting Independence - generally vioated\n# var(y) = \u03b2[2]^2*var(x1) + \u03b2[3]^2*var(x2) + \u03b2[4]^2*var(x3)\n\n# Since we normalized\ndenom = \u03b2[2]^2 + \u03b2[3]^2 + \u03b2[4]^2\n\n\u03b2[2]^2/denom\n\u03b2[3]^2/denom\n\u03b2[4]^2/denom\n", "meta": {"hexsha": "f67449f43b2d6faf7ce49eef7c5b4fa599a33ca4", "size": 1376, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "simulations/OLSproportionalr2/OLSproportionalr2.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/OLSproportionalr2/OLSproportionalr2.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/OLSproportionalr2/OLSproportionalr2.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": 14.0408163265, "max_line_length": 59, "alphanum_fraction": 0.5566860465, "num_tokens": 684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191297273499, "lm_q2_score": 0.9111797082028671, "lm_q1q2_score": 0.8704674058655836}}
{"text": "\nfunction func(x)\n    return x-cos(x)\nend\n\nfunction bisection(func,xleft,xright,eps)  \n    y_left = func(xleft)\n    y_right = func(xright)\n    num_iter = 0\n    iteration = 100000000\n    if y_left == 0\n        return xleft, num_iter\n    elseif y_right == 0\n        return xright, num_iter\n    elseif y_left*y_right > 0\n        return nothing, nothing\n    else\n        for n in 1:iteration\n            x_mid = (xleft+xright)/2\n            y_mid = func(x_mid)\n            if y_mid == 0\n                num_iter = n\n                return x_mid, num_iter\n            end\n            if y_left*y_mid < 0\n                xright = x_mid\n            else\n                xleft = x_mid\n            end\n            if(abs(xright-xleft) < eps)\n                num_iter = n\n                return x_mid, num_iter\n            end\n        end\n        return nothing, num_iter\n    end\nend\n\n\nfunction main()\n    xleft, xright = 0, 3.14\n    eps = 1e-7\n    solution, num_iter = bisection(func, xleft, xright, eps)\n    if solution != nothing\n        print(\"X=$(solution) $(func(solution)), $(num_iter)\")\n    elseif num_iter == nothing\n        print(\"f(x1)*f(x2) must be less than 0\")\n    else\n        print(\"No Convergence\")\n    end\nend\n\nmain()\n", "meta": {"hexsha": "ef57562d1001e9a5c250b8e313f14cbf370e966b", "size": 1226, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "solveNonLinear/bisection/bisection.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": "solveNonLinear/bisection/bisection.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": "solveNonLinear/bisection/bisection.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.7037037037, "max_line_length": 61, "alphanum_fraction": 0.5228384992, "num_tokens": 345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.952574129515172, "lm_q2_score": 0.9136765298777719, "lm_q1q2_score": 0.8703446251067616}}
{"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\nperfect_square(-9)  # returns False\n```\n\nContributed By:- [Ashwani Rathee](https://github.com/ashwani-rathee) and [Rratic](https://github.com/Rratic)\n\"\"\"\nfunction perfect_square(number::N)where N<:Integer\n    number<0&&return false\n    val=isqrt(number)\n    return val*val == number\nend\n", "meta": {"hexsha": "e0b1fce2b5b2d3e7049838719147e49b4fa9ec6f", "size": 556, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/perfect_square.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/perfect_square.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/perfect_square.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": 24.1739130435, "max_line_length": 108, "alphanum_fraction": 0.7248201439, "num_tokens": 160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9372107931567176, "lm_q2_score": 0.9284087960985615, "lm_q1q2_score": 0.8701147441652062}}
{"text": "include(\"factorial.jl\")\n\n\"\"\"\n    krishnamurthy(number)\n\nCheck if a number is a Krishnamurthy number or not\n\n# Details\n\nIt is also known as Peterson Number. \n\nA Krishnamurthy Number is a number whose sum of the\nfactorial of the digits equals to the original\nnumber itself.\n\nFor example: 145 = 1! + 4! + 5!\n    So, 145 is a Krishnamurthy Number\n\n# Example\n\n```julia\nkrishnamurthy(145) # returns true\nkrishnamurthy(240) # returns false\nkrishnamurthy(1)   # returns true \n```\n\nContributed By:- [Ashwani Rathee](https://github.com/ashwani-rathee)\n\"\"\"\nfunction krishnamurthy(number)\n    if number != trunc(number) || number < 0\n        throw(\n            error(\"krishnamurthy() only accepts non-negative integral values\"),\n        )\n    end\n    total = 0\n    temp = number\n    while temp > 0\n        temp, digit = divrem(temp, 10)\n        total += factorial_iterative(digit)\n    end\n    return total == number\nend\n", "meta": {"hexsha": "dc100d8e38351425d8f20f17fbeb5c6109ce00b3", "size": 908, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/krishnamurthy_number.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/math/krishnamurthy_number.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/math/krishnamurthy_number.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.1162790698, "max_line_length": 79, "alphanum_fraction": 0.6707048458, "num_tokens": 264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750413739076, "lm_q2_score": 0.9124361545241945, "lm_q1q2_score": 0.8698026129551006}}
{"text": "\"\"\"\n    monte_carlo_integration(f::Function, a::Real, b::Real, n::Int)\n\nMonte carlo integration is a very easy and scalable way to do multidimentional integrals.\nHowever, only single variable integrals are considered.\n\n# Arguments\n- `f`: the function to integrate. (at the momment only single variable is suported)\n- `a`: start in the integration limits.\n- `b`: endin the integration limits.\n- `N`: Number of points to sample. For most simple functions, 1000 to 10,000 should be okay.\n\n# Examples\n```julia\njulia> monte_carlo_integration(x -> 3*x^2, 0, 1, 100000) # integrate a polynomial\n1.0000037602209\n\njulia> monte_carlo_integration(x -> sin(x), 0, pi, 1000) # integrate the sin function\n2.0018927826323756\n```\n\n# References\n- https://www.scratchapixel.com/lessons/mathematics-physics-for-computer-graphics/monte-carlo-methods-in-practice/monte-carlo-integration\n- https://kingaa.github.io/sbied/pfilter/monteCarlo.html\n\n# Contributors\n- [AugustoCL](https://github.com/AugustoCL)\n- [Ved Mahajan](https://github.com/Ved-Mahajan)\n\"\"\"\nfunction monte_carlo_integration(f::Function, a::Real, b::Real, n::Int)\n    \u0394\u2093 = ((b - a) / n)\n\n    \u03a3 = 0.0\n    for _ \u2208 1:n\n        # generate uniform(a, b) using uniform(0, 1)\n        X\u1d62 = a + (b-a)*rand()\n        \u03a3 += f(X\u1d62)\n    end\n\n    return \u0394\u2093 * \u03a3\nend\n", "meta": {"hexsha": "a306ebf96d82b8bdd944109964aaa9684aae8111", "size": 1292, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/monte_carlo_integration.jl", "max_stars_repo_name": "frankschmitt/Julia", "max_stars_repo_head_hexsha": "c94cf524ad5d3221e05a4967fd088145d9c51a33", "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/monte_carlo_integration.jl", "max_issues_repo_name": "frankschmitt/Julia", "max_issues_repo_head_hexsha": "c94cf524ad5d3221e05a4967fd088145d9c51a33", "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/monte_carlo_integration.jl", "max_forks_repo_name": "frankschmitt/Julia", "max_forks_repo_head_hexsha": "c94cf524ad5d3221e05a4967fd088145d9c51a33", "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": 30.7619047619, "max_line_length": 137, "alphanum_fraction": 0.7004643963, "num_tokens": 408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620573763839, "lm_q2_score": 0.9059898235563418, "lm_q1q2_score": 0.8695346570185016}}
{"text": "function solve_poisson_cg( LF::LF3dGrid, rho::Array{Float64,1}, NiterMax::Int64;\n                           verbose=false, TOL=5.e-10 )\n    Npoints = LF.Nx * LF.Ny * LF.Nz\n    #\n    phi = zeros( Float64, Npoints ) # XXX or use some starting guess\n    #\n    r = zeros( Float64, Npoints )\n    p = zeros( Float64, Npoints )\n    #\n    nabla2_phi = apply_Laplacian( LF, phi )\n    for ip = 1:Npoints\n        r[ip] = rho[ip] - nabla2_phi[ip]\n        p[ip] = r[ip]\n    end\n\n    rsold = dot( r, r )\n    for iter = 1 : NiterMax\n        #\n        nabla2_phi = apply_Laplacian( LF, p )\n        #\n        alpha = rsold/dot( p, nabla2_phi )\n        #\n        phi = phi + alpha * p\n        r = r - alpha * nabla2_phi\n        #\n        rsnew = dot( r, r )\n        deltars = rsold - rsnew # used ?\n        if verbose\n          @printf(\"%8d %20.10f\\n\", iter, sqrt(rsnew))\n        end\n        #\n        if sqrt(rsnew) < TOL\n          if verbose\n            @printf(\"#Convergence achieved in solve_poison_cg: N, iter: %d %d\\n\", Npoints, iter)\n          end\n          break\n        end\n        #\n        p = r + (rsnew/rsold) * p\n        #\n        rsold = rsnew\n    end\n    #\n    return phi\n    #\nend # of function\n\n\nfunction solve_poisson_cg( Lmat::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    #\n    nabla2_phi = Lmat*phi\n    for ip = 1 : Npoints\n        r[ip] = rho[ip] - nabla2_phi[ip]\n        p[ip] = r[ip]\n    end\n    rsold = dot( r, r )\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        #\n        rsnew = dot( r, r )\n        deltars = rsold - rsnew\n        if verbose\n            @printf(\"%8d %20.10f\\n\", iter, sqrt(rsnew))\n        end\n        #\n        if sqrt(rsnew) < TOL\n            if verbose\n                @printf(\"Convergence achieved in solve_poison_cg: N, iter: %d %d\\n\", Npoints, iter)\n            end\n            break\n        end\n        #\n        p = r + (rsnew/rsold) * p\n        #\n        rsold = rsnew\n    end\n    #\n    return phi\n    #\nend # of function\n", "meta": {"hexsha": "635aa89593edb7cf3bd990c826c492ce8f7e69f5", "size": 2400, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "LF/LF_common/solve_poisson_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/LF_common/solve_poisson_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/LF_common/solve_poisson_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": 25.0, "max_line_length": 99, "alphanum_fraction": 0.4779166667, "num_tokens": 748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620550745211, "lm_q2_score": 0.9059898102301019, "lm_q1q2_score": 0.869534642143018}}
{"text": "using Test\nusing LinearAlgebra\nusing WaveProp\nusing WaveProp.Geometry\nusing WaveProp.Integration\n\n@testset \"Trapezoidal quadrature\" begin\n    q = Trapezoidal{10}()\n    D = domain(q)\n    @test D == ReferenceLine()\n    x,w = q()\n    @test sum(w) \u2248 1\n    # integrate a periodic function. Should be very accurate.\n    @test isapprox(integrate(x->cos(2\u03c0*x),q),0,atol=1e-10)\n    @test integrate(x->sin(2\u03c0*x[1])^2,q) \u2248 0.5\nend\n\n@testset \"TrapezoidalP quadrature\" begin\n    q = TrapezoidalP{10}()\n    D = domain(q)\n    @test D == ReferenceLine()\n    x,w = q()\n    @test sum(w) \u2248 1\n    # integrate a periodic function. Should be very accurate.\n    @test isapprox(integrate(x->cos(2\u03c0*x[1]),q),0,atol=1e-10)\n    @test integrate(x->sin(2\u03c0*x[1])^2,q) \u2248 0.5\nend\n\n@testset \"Fejer quadrature\" begin\n    N = 5\n    q = Fejer{N}()\n    x,w = q()\n    @test sum(w) \u2248 1\n    # integrate all polynomial of degree N-1 exactly\n    for n in 1:(N-1)\n        @test integrate(x->x[1]^n,q) \u2248 1/(n+1)\n    end\nend\n\n@testset \"Gauss-Legendre quadrature\" begin\n    N = 5\n    q = GaussLegendre{N}()\n    x,w = q()\n    @test sum(w) \u2248 1\n    # integrate all polynomial of degree 2N-1 exactly\n    for n in 1:(2*N-1)\n        @test integrate(x->x[1]^n,q) \u2248 1/(n+1)\n    end\nend\n\n@testset \"Gauss quad on triangle\" begin\n    D= ReferenceTriangle\n    for N in (1,3)\n        q = Gauss{D,N}()\n        x,w = q()\n        @test sum(w) \u2248 1/2\n    end\n    # FIXME: check that we integrate all monomials up to `order` on the triangle\nend\n\n@testset \"Gauss quad on tetrahedron\" begin\n    D= ReferenceTetrahedron\n    for N in (1,4)\n        q = Gauss{D,N}()\n        x,w = q()\n        @test sum(w) \u2248 1/6\n    end\n    # FIXME: check that we integrate all monomials up to `order`\nend\n\n@testset \"Tensor product quad on square\" begin\n    D   = ReferenceSquare\n    N,M = 10,12\n    qx  = GaussLegendre{N}()\n    qy  = Fejer{M}()\n    q   = TensorProductQuadrature(qx,qy)\n    a,b = 2*N-1,M-1 # maximum integration order of monomials\n    @test integrate( x -> 1,q) \u2248 1\n    f = x -> x[1]^a*x[2]^b\n    @test integrate(f,q) \u2248 1/(a+1)*1/(b+1)\nend\n\n\n", "meta": {"hexsha": "194ee6262e95f215918e30afea5d98802563b849", "size": 2071, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Integration/quadrule_test.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": "test/Integration/quadrule_test.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": "test/Integration/quadrule_test.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": 24.6547619048, "max_line_length": 80, "alphanum_fraction": 0.5919845485, "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639644850629, "lm_q2_score": 0.8947894555814343, "lm_q1q2_score": 0.8693451908441294}}
{"text": "\"\"\"\n    sum_ap(first_term, diff, num_terms)\n\nFinds sum of a arithmetic progression series\n\n# Input parameters\n\n- first_term : first term of the series\n- diff       : common difference between consecutive terms\n- num_terms  : number of terms in the series till which we count sum\n\n# Example \n\n```julia\nsum_ap(1, 1, 10)    # returns 55.0 \nsum_ap(1, 10, 100)  # returns 49600.0\n```\n\nContributed By:- [Ashwani Rathee](https://github.com/ashwani-rathee)\n\"\"\"\nfunction sum_ap(first_term, diff, num_terms)\n    #formula for sum of the ap series\n    sum = (num_terms / 2) * (2 * first_term + (num_terms - 1) * diff)\n    return sum\nend\n", "meta": {"hexsha": "3f107166b809cc31dee216fa5747eeb2220b226a", "size": 625, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/sum_of_arithmetic_series.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/math/sum_of_arithmetic_series.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/math/sum_of_arithmetic_series.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.0384615385, "max_line_length": 69, "alphanum_fraction": 0.688, "num_tokens": 188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741241296944, "lm_q2_score": 0.9124361688107864, "lm_q1q2_score": 0.8691630843291889}}
{"text": "\"\"\"\n    Pearson Correlation\n\nFind the pearson correlation between two variables.\n\n# Example:\n\njulia> PearsonCorrelation([12,11,16,17,19,21],[11,51,66,72,12,15])\n-0.2092706263573845\n\nContribution by: [Aru Bhardwaj](https://github.com/arubhardwaj)\n\n\n\"\"\"\n\n\n\nfunction PearsonCorrelation(x, y)\n    mean_x = sum(x)/length(x)\n    mean_y = sum(y)/length(y)\n    XY = (x.-mean_x).*(y.-mean_y)\n    XXs = sum((x.-mean_x).*(x.-mean_x))\n    YYs = sum((y.-mean_y).*(y.-mean_y))\n    return(sum(XY)/(sqrt(XXs.*YYs)))\nend\n", "meta": {"hexsha": "4c400e0e9e40906adaa264f9766731bddaa717a0", "size": 504, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/statistics/PearsonCorrelaion.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/statistics/PearsonCorrelaion.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/statistics/PearsonCorrelaion.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.3846153846, "max_line_length": 66, "alphanum_fraction": 0.6448412698, "num_tokens": 176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9811668668053619, "lm_q2_score": 0.8856314813647587, "lm_q1q2_score": 0.8689522657148515}}
{"text": "eval_at(args...) = f -> f(args...)\nfindallin(xs, ys) = map(x -> findfirst(y -> x == y, ys), xs)\n\n\"\"\"\n    catalan_number(n)\n\ncalculate the n-th catalan number\n\"\"\"\ncatalan_number(n) = div(binomial(2n, n), n+1)\n\n\"\"\"\n    number_binary_trees(n)\n\ncalculate the number of binary trees with n leafs\n\"\"\"\nnumber_binary_trees(n) = catalan_number(n - 1)\n\n\"\"\"\n    categorical_sample(tokens, weights)\n\nsample one token according to the given weights\n\"\"\"\nfunction categorical_sample(tokens, weights)\n    T = eltype(weights)\n    x = convert(T, rand()) * sum(weights)\n    cum_weights = zero(T)\n    for (t, w) in zip(tokens, weights)\n        cum_weights += w\n        if cum_weights >= x\n            return t\n        end\n    end\n    error(\"categorical sample failed with length(tokens)=$(length(tokens)), weights=$weights\")\nend\n\ncategorical_sample(d::Dict)   = categorical_sample(keys(d), values(d))\ncategorical_sample(v::Vector) = categorical_sample(1:length(v), v)\n", "meta": {"hexsha": "c90ff634a881a0687eb218f93e9c06bcfecdf4dd", "size": 948, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "dharasim/GeneralizedChartParsing.jl", "max_stars_repo_head_hexsha": "a1998860258c4758b8b22314571f7d5eec40615b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-02-05T17:56:25.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-05T17:56:25.000Z", "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "dharasim/GeneralizedChartParsing.jl", "max_issues_repo_head_hexsha": "a1998860258c4758b8b22314571f7d5eec40615b", "max_issues_repo_licenses": ["MIT"], "max_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": "dharasim/GeneralizedChartParsing.jl", "max_forks_repo_head_hexsha": "a1998860258c4758b8b22314571f7d5eec40615b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9473684211, "max_line_length": 94, "alphanum_fraction": 0.6582278481, "num_tokens": 244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992905050948, "lm_q2_score": 0.8976952866333484, "lm_q1q2_score": 0.8688786310221857}}
{"text": "using Plots\n\n\n\"\"\"\n    runge_kutta(f::Function, x\u2080::Real, y\u2080::Real, x::Real, h::Real=10^(-3))::Array{Float64,1}\nReturn an array with values of function which is solution to the differential equation\ngiven by function f with intial condition\n\"\"\"\nfunction runge_kutta(f::Function, x\u2080::Real, y\u2080::Real, x::Real, h::Real=10^(-3))::Array{Float64,1}\n    n = round(Int64, x / h)\n    array = zeros(n)\n    for i in 1:n\n        k\u2081 = f(x\u2080, y\u2080)\n        k\u2082 = f(x\u2080 + 1/2*h, y\u2080 + 1/2*h*k\u2081)\n        k\u2083 = f(x\u2080 + 1/2*h, y\u2080 + 1/2*h*k\u2082)\n        k\u2084 = f(x\u2080 + h, y\u2080 + h*k\u2083)\n        y\u2080 = y\u2080 + h / 6 * (k\u2081 + 2*k\u2082 + 2*k\u2083 + k\u2084)\n        x\u2080 = x\u2080 + h\n        array[i] = y\u2080\n    end\n    return array\nend\n\n# logistic growth for chosen constants\nf(t, y) = 0.6y*(1 - y / 10)\narray = runge_kutta(f, 0, 1, 20)\n\ud835\udc2b = plot(LinRange(0, 20, length(array)), array)\ndisplay(\ud835\udc2b)\n\n# https://en.smath.com/wiki/GetFile.aspx?File=Examples/RK4SystemEquations.pdf\n# examples below are taken from this url\n\narray  = [(t, y\u2081, y\u2082) -> sin(t) + cos(y\u2081) + sin(y\u2082),\n        (t, y\u2081, y\u2082) -> cos(t) + sin(y\u2082)]\nX = 0\nY = [-1., 1.]\n\n\n\n\"\"\"\n    evaluate(array::Array{Function, 1}, X::Real, Y::Array{Real, 1})::Array{Real, 1}\nReturn an array with values of function f(t, y\u2081, y\u2082) defined in array for given point X\n\"\"\"\nfunction evaluate(array::Array{Function, 1}, X::Real, Y::Array{T, 1})::Array{T, 1} where T <: Real\n    return [i(X, Y[1], Y[2]) for i in array]\nend\n\n\n\"\"\"\n    runge_kutta(F::Array{Function, 1}, x::Real, X::Real, Y::Array{T, 1}, h::Real=1e-3)::Array{T, 2} where T <: Real\nReturn an array with values of functions which are solutions to the system of differential equations defined by the array.\nX and Y are initial conditions, x is the maximum point.\n\"\"\"\nfunction runge_kutta(F::Array{Function, 1}, x::Real, X::Real, Y::Array{T, 1}, h::Real=1e-3)::Array{T, 2} where T <: Real\n    n = round(Int64, x / h)\n    array = zeros((n, 2))\n    for i in 1:n\n        k\u2081 = evaluate(F, X, Y)\n        k\u2082 = evaluate(F, X + 1/2 * h, Y .+ 1/2 * h * k\u2081)\n        k\u2083 = evaluate(F, X + 1/2 * h, Y .+ 1/2 * h * k\u2082)\n        k\u2084 = evaluate(F, X + h, Y .+ h * k\u2083)\n        Y = @. Y + h / 6 * (k\u2081 + 2*k\u2082 + 2*k\u2083 + k\u2084)\n        X = X + h\n        array[i, :] = Y\n    end\n    return array\nend\n\n\na = runge_kutta(array, 20, X, Y)\n\n\ud835\udc5d = plot(LinRange(0, 5, length(a[:, 1])), a[:, 1])\nplot!(LinRange(0, 5, length(a[:, 2])), a[:, 2])\ndisplay(\ud835\udc5d)\n# everything works fine\n\n\n# harmonic oscillator x\u0308 + x = 0\n# can be rewritten as\n# x\u0307 = y, y\u0307 = -x\n# note that y is velocity \u20d7v\n\n\narray2 = [(t, y\u2081, y\u2082) -> y\u2082, (t, y\u2081, y\u2082) -> -y\u2081]\nY2 = [0., 1.]\nb = runge_kutta(array2, 30, 0, Y2)\n\n\ud835\udc5e = plot(LinRange(0, 5, length(b[:, 1])), b[:, 1])\ndisplay(\ud835\udc5e)\n# plot!(LinRange(0, 5, length(b[:, 2])), b[:, 2])\n\ud835\udc64 = plot(b[:, 1], b[:, 2])  # a kind of phase plane plot\ndisplay(\ud835\udc64)\n\n# vector field for harmonic oscillator\nxs = LinRange(0, 5, length(b[1, :]))\n\nxs = xs[1:150:end]\nxs |>println\ny\u2081s = b[:, 1][1:150:end]\ny\u2082s = b[:, 2][1:150:end]\n\nplot(quiver(y\u2081s, y\u2082s, quiver=(0.2 * array2[1].(xs, y\u2081s, y\u2082s), 0.2 * array2[2].(xs, y\u2081s, y\u2082s)), color=:red))\n", "meta": {"hexsha": "1ab43a2a3e10ec7184ea9743f1dfc4d222195152", "size": 3029, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "runge_kutta.jl", "max_stars_repo_name": "Manik2000/diff_equ_proj", "max_stars_repo_head_hexsha": "867cc63e24168e2dabedcddb5718712db60e991c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "runge_kutta.jl", "max_issues_repo_name": "Manik2000/diff_equ_proj", "max_issues_repo_head_hexsha": "867cc63e24168e2dabedcddb5718712db60e991c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "runge_kutta.jl", "max_forks_repo_name": "Manik2000/diff_equ_proj", "max_forks_repo_head_hexsha": "867cc63e24168e2dabedcddb5718712db60e991c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4077669903, "max_line_length": 122, "alphanum_fraction": 0.5668537471, "num_tokens": 1238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545304202039, "lm_q2_score": 0.916109606145647, "lm_q1q2_score": 0.8686134734284638}}
{"text": "function bin_length_long(s::AbstractString)\r\n    binNum = parse(UInt, s)\r\n\r\n    finNum = 0\r\n    seq = 1\r\n\r\n    for i in 1:binNum\r\n        if (i == seq)\r\n            finNum += 1\r\n            seq *= 2\r\n        end\r\n    end\r\n\r\n    return string(finNum)\r\nend\r\n\r\n\"\"\"\r\nThis algorithm features use of the OEIS entry A070939 - \r\nlength of Binary Representation of n. It finds \r\nthe length of any binary number and returns said length.\r\n  \r\n https://oeis.org/A070939\r\n\r\nThis function, as believed, is O(n)\r\n\r\nThe idea follows that the sequence is dependent on \r\na repeating pattern of 2. Short for sequence, seq is the\r\nnumber of digits required before an increase in finNum \r\nor final number as seen here with the first few\r\niterations - i on the left, final number on the right:\r\n\r\n1 : 1 \r\n2 : 2\r\n3 : 2\r\n4 : 3\r\n5 : 3\r\n6 : 3\r\n7 : 3\r\n8 : 4\r\ncont.\r\n\r\nAs you can see, for every version of i, there is an appropriate\r\nmodified number that only repeats for the sequence of the last\r\ndoubled amount.\r\n\r\n#Contributions:\r\nContributed by F35H: https://github.com/F35H\r\n\"\"\"\r\n\r\nfunction bin_length_short(s::AbstractString)\r\n    binNum = parse(UInt, s)\r\n\r\n    finNum = 0\r\n    i = 1\r\n\r\n    while i <= binNum\r\n        i *= 2\r\n        finNum += 1\r\n    end\r\n\r\n    return string(finNum)\r\nend\r\n\r\n\"\"\"\r\nThis algorithm features use of the OEIS entry A070939 - \r\nlength of Binary Representation of n. It finds \r\nthe length of any binary number and returns said length.\r\n  \r\n https://oeis.org/A070939\r\n\r\nThis function, as believed, is O(n)\r\n\r\nThe idea follows that the sequence is dependent on \r\na repeating pattern of 2. The final number being finNum\r\nincreases on every doubling of i.\r\n\r\n1 : 1 \r\n2 : 2\r\n3 : 2\r\n4 : 3\r\n5 : 3\r\n6 : 3\r\n7 : 3\r\n8 : 4\r\ncont.\r\n\r\nAs you can see, for every version of i, there is an appropriate\r\nfinal number that iterates on every doubling of i.\r\n\r\nContributors:\r\n- [F45H](https://github.com/F35H)\r\n\"\"\"\r\n", "meta": {"hexsha": "4f2ae58fd57ed60a9968d9cf0f66f68cb13c9582", "size": 1899, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/strings/binary_length.jl", "max_stars_repo_name": "Nikola-Mircic/Julia", "max_stars_repo_head_hexsha": "928972f88c59f87c206ff22e39033e6dd7f799ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-16T05:56:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T05:56:03.000Z", "max_issues_repo_path": "src/strings/binary_length.jl", "max_issues_repo_name": "Nikola-Mircic/Julia", "max_issues_repo_head_hexsha": "928972f88c59f87c206ff22e39033e6dd7f799ae", "max_issues_repo_licenses": ["MIT"], "max_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/binary_length.jl", "max_forks_repo_name": "Nikola-Mircic/Julia", "max_forks_repo_head_hexsha": "928972f88c59f87c206ff22e39033e6dd7f799ae", "max_forks_repo_licenses": ["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.4193548387, "max_line_length": 64, "alphanum_fraction": 0.6477093207, "num_tokens": 523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951680216529, "lm_q2_score": 0.9294404013696267, "lm_q1q2_score": 0.8684646200038848}}
{"text": "\"\"\"\n    Newton_Raphson(f, fp, x; tol = 1e-14, MITR = 100)\n---\nGiven function `f` and its derivative `fp`, this function finds a root for `f = 0` with\na starter `x`\n\"\"\"\nfunction Newton_Raphson(f, fp, x; tol = 1e-14, MITR = 100)\n    xnew, xold = x, Inf\n    fn, fo = f(xnew), Inf\n\n    ctr = 1\n\n    while (ctr < 100) && (abs(xnew - xold) > tol) && ( abs(fn - fo) > tol )\n\tx = xnew - f(xnew)/fp(xnew) # update step\n\txnew, xold = x, xnew\n        fn, fo = f(xnew), fn\n\tctr = ctr + 1\n    end\n\n    if ctr == MITR\n\terror(\"Did not converge in $MITR steps\")\n    else\n\txnew, ctr\n    end\nend\n\n\"\"\"\n    Newton_Raphson(f, x; tol = 1e-14, MITR = 100, inc = 1e-8)\n---\nGiven function `f`, this function numerically finds a root for `f = 0` with a starter `x` using `secant` method.\n\"\"\"\nfunction Newton_Raphson(f, x; tol = 1e-14, MITR = 100, inc = 1e-8)\n    fp(x1, x2) = (f(x1) - f(x2))/(x1 - x2)\n\n    fn, fo = f(x1), Inf\n\n    ctr = 1\n\n    x2, x1 = x + inc, x\n    while (ctr < 100) && (abs(x2 - x1) > tol) && ( abs(fn - fo) > tol )\n        x2, x1 = x2 - f(x2)/fp(x1, x2), x2\n        fn, fo = f(x2), fn\n\tctr = ctr + 1\n    end\n\n    if ctr == 100\n\terror(\"Did not converge in 100 steps\")\n    else\n\tx2, ctr\n    end\nend\n", "meta": {"hexsha": "7e632be57acf3035b5ca3f2e9dc7c757e1ea665e", "size": 1193, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Newton-Raphson.jl", "max_stars_repo_name": "xijiang/PlayGround.jl", "max_stars_repo_head_hexsha": "b37a22ced95b61fe04381e6ee64a239d827bf4f5", "max_stars_repo_licenses": ["MIT"], "max_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": "xijiang/PlayGround.jl", "max_issues_repo_head_hexsha": "b37a22ced95b61fe04381e6ee64a239d827bf4f5", "max_issues_repo_licenses": ["MIT"], "max_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": "xijiang/PlayGround.jl", "max_forks_repo_head_hexsha": "b37a22ced95b61fe04381e6ee64a239d827bf4f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9423076923, "max_line_length": 112, "alphanum_fraction": 0.538977368, "num_tokens": 480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741268224331, "lm_q2_score": 0.9111797172476384, "lm_q1q2_score": 0.8679662235354806}}
{"text": "using SymPy\nusing Base.Test\n\n\n\n## ODEs\nx, a = Sym(\"x, a\")\nF = SymFunction(\"F\")\nex = diff(F(x), x) - a*F(x)\nex1 = dsolve(ex)\nex2 = rhs(ex1) |> subs(Sym(:C1), 1) |> subs(a, 2)\n@assert ex2 == exp(2x)\n\nt, = @syms t\nX, Y = map(SymFunction, (\"X\", \"Y\"))\neq = [Eq(diff(X(t),t), 12*t*X(t) + 8*Y(t)), Eq(diff(Y(t),t), 21*X(t) + 7*t*Y(t))]\ndsolve(eq)\n\n\n## version 0.4+ allow use of u'(x) in lieu of diff(u(x), x) and `ivpsolve`\nu = SymFunction(\"u\")\na,x, y, y0, y1 = symbols(\"a, x, y, y0, y1\")\n\ndsolve(u'(x) - a*u(x), x, (u, 0, 1))\ndsolve(u'(x) - a*u(x), x, (u, 0, y1))\ndsolve(u'(x) - a*u(x), x, (u, y0, y1))\ndsolve(x*u'(x) + x*u(x) + 1, x, (u, 1, 1))\ndsolve((u'(x))^2 - a*u(x), x, (u, 0, 1))\ndsolve(u''(x) - a * u(x), x, (u, 0, 1), (u', 0, 0))\n\nF, G, K = symbols(\"F, G, K\", cls = symfunction)\neqn = F(x)*u'(y)*y + G(x)*u(y) + K(x)\ndsolve(eqn, y, (u, 1, 0))\n\n## dsolve eqn has two answers, but we want to eliminate based on initial condition\ndsolve(u'(x) - (u(x)-1)*u(x)*(u(x)+1), x, (u, 0, 1//2))\n", "meta": {"hexsha": "47cc3ccf8698ea61429b095382cb3cdb52aef932", "size": 986, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test-ode.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-ode.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-ode.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": 26.6486486486, "max_line_length": 82, "alphanum_fraction": 0.5040567951, "num_tokens": 477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342024724487, "lm_q2_score": 0.9073122219871936, "lm_q1q2_score": 0.8679659038742243}}
{"text": "@doc raw\"\"\"\n    block_matrix_logdet(A, B, C, D)\n\nLog-determinant of a block matrix using the determinant lemma.\n\n```math\n\\det\\left(\n    \\begin{bmatrix}\n        \\mathbf{A} & \\mathbf{B} \\\\\n        \\mathbf{C} & \\mathbf{D}\n    \\end{bmatrix}\n\\right)\n= \\det(A) \\det(D - CA^{-1}B)\n= \\det(D) \\det(A - BD^{-1}C)\n```\n\nHere we assume that `A` and `D` are invertible, and moreover are easy to invert\n(for example, if they are diagonal).\nWe use this to chose one or the other of the two formulas above.\n\"\"\"\nfunction block_matrix_logdet(\n    A::AbstractMatrix, B::AbstractMatrix,\n    C::AbstractMatrix, D::AbstractMatrix\n)\n    @assert size(A, 1) == size(B, 1)\n    @assert size(C, 1) == size(D, 1)\n    @assert size(A, 2) == size(C, 2)\n    @assert size(B, 2) == size(D, 2)\n\n    if length(A) \u2265 length(D)\n        return logdet(A) + logdet(D - C * inv(A) * B)\n    else\n        return logdet(D) + logdet(A - B * inv(D) * C)\n    end\nend\n\n@doc raw\"\"\"\n    block_matrix_invert(A, B, C, D)\n\nInversion of a block matrix, using the formula:\n\n```math\n\\begin{bmatrix}\n    \\mathbf{A} & \\mathbf{B} \\\\\n    \\mathbf{C} & \\mathbf{D}\n\\end{bmatrix}^{-1}\n=\n\\begin{bmatrix}\n    \\left(\\mathbf{A} - \\mathbf{B} \\mathbf{D}^{-1} \\mathbf{C}\\right)^{-1} & \\mathbf{0} \\\\\n    \\mathbf{0} & \\left(\\mathbf{D} - \\mathbf{C} \\mathbf{A}^{-1} \\mathbf{B}\\right)^{-1}\n\\end{bmatrix}\n\\begin{bmatrix}\n    \\mathbf{I} & -\\mathbf{B} \\mathbf{D}^{-1} \\\\\n    -\\mathbf{C} \\mathbf{A}^{-1} & \\mathbf{I}\n\\end{bmatrix}\n```\n\nAssumes that `A` and `D` are square and invertible.\n\"\"\"\nfunction block_matrix_invert(\n    A::AbstractMatrix, B::AbstractMatrix,\n    C::AbstractMatrix, D::AbstractMatrix\n)\n    @assert size(A, 1) == size(A, 2) == size(B, 1) == size(C, 2)\n    @assert size(D, 1) == size(D, 2) == size(B, 2) == size(C, 1)\n\n    CinvA = C * inv(A)\n    BinvD = B * inv(D)\n\n    M = [\n        inv(A - BinvD * C)  zero(B)\n        zero(C)  inv(D - CinvA * B)\n    ]\n\n    N = [\n        I(size(B, 1))  -BinvD\n        -CinvA  I(size(C, 1))\n    ]\n\n    return M * N\nend\n", "meta": {"hexsha": "977da422475c3668dc71bc9084daa89e8a405734", "size": 1988, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/util/linalg.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": "src/util/linalg.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": "src/util/linalg.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": 24.243902439, "max_line_length": 88, "alphanum_fraction": 0.5628772636, "num_tokens": 749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639686018702, "lm_q2_score": 0.8933094152856197, "lm_q1q2_score": 0.8679072407043128}}
{"text": "\"\"\"\neuler(ivp,n)\n\nApply Euler's method to solve the given IVP using `n` time steps.\nReturns a vector of times and a vector of solution values.\n\"\"\"\nfunction euler(ivp,n)\n    # Time discretization.\n    a,b = ivp.tspan\n    h = (b-a)/n\n    t = [ a + i*h for i in 0:n ]\n\n    # Initial condition and output setup.\n    u = fill(float(ivp.u0),n+1)\n\n    # The time stepping iteration.\n    for i in 1:n\n        u[i+1] = u[i] + h*ivp.f(u[i],ivp.p,t[i])\n    end\n    return t,u\nend\n\n\"\"\"\nie2(ivp,n)\n\nApply the Improved Euler method to solve the given IVP using `n`\ntime steps. Returns a vector of times and a vector of solution\nvalues.\n\"\"\"\nfunction ie2(ivp,n)\n    # Time discretization.\n    a,b = ivp.tspan\n    h = (b-a)/n\n    t = [ a + i*h for i in 0:n ]\n\n    # Initialize output.\n    u = fill(float(ivp.u0),n+1)\n\n    # Time stepping.\n    for i in 1:n\n        uhalf = u[i] + h/2*ivp.f(u[i],ivp.p,t[i]);\n        u[i+1] = u[i] + h*ivp.f(uhalf,ivp.p,t[i]+h/2);\n    end\n    return t,u\nend\n\n\"\"\"\nrk4(ivp,n)\n\nApply \"the\" Runge-Kutta 4th order method to solve the given IVP\nusing `n` time steps. Returns a vector of times and a vector of\nsolution values.\n\"\"\"\nfunction rk4(ivp,n)\n    # Time discretization.\n    a,b = ivp.tspan\n    h = (b-a)/n\n    t = [ a + i*h for i in 0:n ]\n\n    # Initialize output.\n    u = fill(float(ivp.u0),n+1)\n\n    # Time stepping.\n    for i in 1:n\n        k1 = h*ivp.f( u[i],      ivp.p, t[i]     )\n        k2 = h*ivp.f( u[i]+k1/2, ivp.p, t[i]+h/2 )\n        k3 = h*ivp.f( u[i]+k2/2, ivp.p, t[i]+h/2 )\n        k4 = h*ivp.f( u[i]+k3,   ivp.p, t[i]+h   )\n        u[i+1] = u[i] + (k1 + 2*(k2 + k3) + k4)/6\n    end\n    return t,u\nend\n\n\"\"\"\nrk23(ivp,tol)\n\nApply an adaptive embedded RK formula pair to solve given IVP with\nestimated error `tol`. Returns a vector of times and a vector of\nsolution values.\n\"\"\"\nfunction rk23(ivp,tol)\n    # Initialize for the first time step.\n    a,b = ivp.tspan\n    t = [a]\n    u = [float(ivp.u0)];   i = 1;\n    h = 0.5*tol^(1/3)\n    s1 = ivp.f(ivp.u0,ivp.p,a)\n\n    # Time stepping.\n    while t[i] < b\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 = ivp.f( u[i]+(h/2)*s1,   ivp.p, t[i]+h/2   )\n        s3 = ivp.f( u[i]+(3*h/4)*s2, ivp.p, t[i]+3*h/4 )\n        unew2 = u[i] + h*(2*s1 + 3*s2 + 4*s3)/9   # 2rd order solution\n        s4 = ivp.f( unew2, ivp.p, t[i]+h )\n        err = h*(-5*s1/72 + s2/12 + s3/9 - s4/8)  # 2nd/3rd 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            push!(t,t[i]+h)\n            push!(u,unew2)\n            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,b-t[i])        # don't step past the end\n    end\n    return t,u\nend\n\n\"\"\"\nab4(ivp,n)\n\nApply the Adams-Bashforth 4th order method to solve the given IVP\nusing `n` time steps.\n\"\"\"\nfunction ab4(ivp,n)\n    # Time discretization.\n    a,b = ivp.tspan\n    h = (b-a)/n\n    t = [ a + i*h for i in 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 = fill(float(ivp.u0),n+1)\n    rkivp = ODEProblem(ivp.f,ivp.u0,(a,a+(k-1)*h),ivp.p)\n    ts,us = rk4(rkivp,k-1)\n    u[1:k] = us[1:k]\n\n    # Compute history of u' values, from newest to oldest.\n    f = [ ivp.f(u[k-i],ivp.p,t[k-i]) for i in 1:k-1  ]\n\n    # Time stepping.\n    for i in k:n\n      f = [ ivp.f(u[i],ivp.p,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 in 1:k)  # advance a step\n    end\n    return t,u\nend\n\n\n\"\"\"\nam2(ivp,n)\n\nApply the Adams-Moulton 2nd order method to solve given IVP using\n`n` time steps.\n\"\"\"\nfunction am2(ivp,n)\n    # Time discretization.\n    a,b = ivp.tspan\n    h = (b-a)/n\n    t = [ a + i*h for i in 0:n ]\n\n     # Initialize output.\n     u = fill(float(ivp.u0),n+1)\n\n    # Time stepping.\n    for i in 1:n\n        # Data that does not depend on the new value.\n        known = u[i] + h/2*ivp.f(u[i],ivp.p,t[i])\n        # Find a root for the new value.\n        F = z -> z .- h/2*ivp.f(z,ivp.p,t[i+1]) .- known\n        unew = levenberg(F,known)\n        u[i+1] = unew[end]\n    end\n    return t,u\nend\n", "meta": {"hexsha": "f8a1b4c6aaf0a5989dff11260cd48244fae01a73", "size": 4538, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chapter06.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": "src/chapter06.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": "src/chapter06.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.0718232044, "max_line_length": 73, "alphanum_fraction": 0.5268840899, "num_tokens": 1651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810451666345, "lm_q2_score": 0.9161096101538326, "lm_q1q2_score": 0.867904879954736}}
{"text": "\"\"\"\n    lcs_length(str_1::String, str_2::String)\n\nThe longest common subsequence (LCS) algorithm is dedicated to solve the problem of finding\nthe longest subsequence common to all sequences in a set of two sequences. For finding these\nsubsequences are brute force approach (permuation) has to be chosen as follow:\n    \n    1. Figure out the number of possible different subsequences of a string with length `m` and `n`.\n    2. Recontracted `for-loops` for defining the outer layer of the storing matrix `C`.\n    3. Checking if `str_1[i] == str_2[j]` and updating the count in  matrix `C`.\n    4.Return the latest element of `C[m,n]`.\n    \nThe **LCS** differs from the [longest common substring problem](https://en.wikipedia.org/wiki/Longest_common_substring_problem) because it is not required to occupy consecutive positions within the original sequences. \nFor more information see: [https://en.wikipedia.org/wiki/Longest_common_subsequence_problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem)\n\n\n# Arguments\n- `str_1::String`: String 1 of length `m`\n- `str_2::String`: String 2 of length `n`\n\n\n# Examples\n```julia-repl\njulia> import ClassicAlgorithmsCollections\njulia> ClassicAlgorithmsCollections.lcs_lenght(\"AGGTAB\",\"GXTXAYB\")\n4\n```\n\"\"\"\nfunction lcs_length(str_1::String, str_2::String)\n    m = length(str_1)\n    n = length(str_2)\n    C = zeros(Int64, (m, n))\n    for i in 1:m\n        C[i, 1] = 1\n    end\n    for j in 1:n\n        C[1, j] = 1\n    end\n    for i in 2:m\n        for j in 2:n\n            if str_1[i] == str_2[j]\n                C[i, j] = C[i-1, j-1] + 1\n            else\n                if C[i, j-1] > C[i-1, j]\n                    C[i, j] = C[i, j-1]\n                else\n                    C[i, j] = C[i-1, j]\n                end\n            end\n        end\n    end\n    return C[m, n]\nend\n", "meta": {"hexsha": "c2f78cde5c696b09803d0c26be0b421ff78bea2f", "size": 1829, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/DynamicProgramming/LongestCommonSubsequence.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/DynamicProgramming/LongestCommonSubsequence.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/DynamicProgramming/LongestCommonSubsequence.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": 33.8703703704, "max_line_length": 218, "alphanum_fraction": 0.6331328595, "num_tokens": 534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122744874229, "lm_q2_score": 0.9059898159413479, "lm_q1q2_score": 0.8678587652508182}}
{"text": "\nusing LinearAlgebra, Statistics;\nfunction Newtonfixedpointmap(f, f_prime, x_0, tolerance, maxiter)\n    # setup the algorithm\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)) # use the passed in map\n        normdiff = norm(x_new - x_old)\n        x_old = x_new\n        iter = iter + 1\n    end\n    return (x_old, normdiff, iter)\nend\n\nmaxiter = 1000\ntolerance = 1.0E-7\nx_0 = 0.0 # initial condition\n\nf(v) = (v-1)^3 \nf_prime(v)= 3*(v-1)^2 \n\nx_star, normdiff, iter = Newtonfixedpointmap(f, f_prime, x_0, tolerance, maxiter)\nprintln(\"Fixed point = $x_star, and |f(x) - x| = $normdiff in $iter iterations\")\n\nf(v)= 27*v^3 - 3*v + 1\nf_prime(v)= 81*v^2 - 3\n\nx_star, normdiff, iter = Newtonfixedpointmap(f, f_prime, x_0, tolerance, maxiter)\nprintln(\"Fixed point = $x_star, and |f(x) - x| = $normdiff in $iter iterations\")\n\nusing ForwardDiff\n\n# operator to get the derivative of this function using AD\nD(f) = v-> ForwardDiff.derivative(f, v)\n\nfunction Newtonfixedpointmap(f, x_0, tolerance, maxiter)\n    # setup the algorithm\n    x_old = x_0\n    normdiff = Inf\n    iter = 1\n    f_prime = D(f)\n    while normdiff > tolerance && iter <= maxiter\n        x_new = x_old - (f(x_old)/ f_prime(x_old)) # use the passed in map\n        normdiff = norm(x_new - x_old)\n        x_old = x_new\n        iter = iter + 1\n    end\n    return (x_old, normdiff, iter)\nend\nmaxiter = 1000\ntolerance = 1.0E-7\nx_0 = 0.0 # initial condition\n\nf(v) = (v-1)^3 \nf_prime(v)= 3*(v-1)^2 \n\nx_star, normdiff, iter = Newtonfixedpointmap(f, f_prime, x_0, tolerance, maxiter)\nprintln(\"Fixed point = $x_star, and |f(x) - x| = $normdiff in $iter iterations\")\n\nf(v)= 27*v^3 - 3*v + 1\nf_prime(v)= 81*v^2 - 3\n\nx_star, normdiff, iter = Newtonfixedpointmap(f, f_prime, x_0, tolerance, maxiter)\nprintln(\"Fixed point = $x_star, and |f(x) - x| = $normdiff in $iter iterations\")\n", "meta": {"hexsha": "083f121ab7ff592e6916ec5b7e4918ed41c40f60", "size": 1917, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Assignment4_Aditi.jl", "max_stars_repo_name": "Aditi095/Assignment4_Aditi", "max_stars_repo_head_hexsha": "530c599a2f7069f547637308e34f16ef8fc3dc45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assignment4_Aditi.jl", "max_issues_repo_name": "Aditi095/Assignment4_Aditi", "max_issues_repo_head_hexsha": "530c599a2f7069f547637308e34f16ef8fc3dc45", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-10-08T19:27:40.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-08T20:34:23.000Z", "max_forks_repo_path": "Assignment4_Aditi.jl", "max_forks_repo_name": "Aditi095/Assignment4_Aditi", "max_forks_repo_head_hexsha": "530c599a2f7069f547637308e34f16ef8fc3dc45", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6119402985, "max_line_length": 81, "alphanum_fraction": 0.6473656755, "num_tokens": 664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572777987970315, "lm_q2_score": 0.9059898210180106, "lm_q1q2_score": 0.8672839415966377}}
{"text": "# Copyright (c) 2022 Code Komali\n# \n# This software is released under the MIT License.\n# https://opensource.org/licenses/MIT\n\n\nusing Test\n \n# Generate prime using the sieve of eratosthenes approach\nfunction generateprime(limit)\n    limit > 0 || throw(ArgumentError(\"limit must be > 0\"))\n    boolArray = fill!(Vector{Bool}(undef,limit), true) #may be simplified\n    boolArray[1] = false\n    for num in 2:limit\n        if boolArray[num] == false\n            continue\n        end\n        # Don't touch the element, just its multiples. Hence starting from num*2.\n        for j in (num*2):num:limit\n            boolArray[j] = false\n        end\n    end\n    return primeindexes(boolArray)\nend\n\n#TODO: need to test which one of the below works faster\nfunction primeindexes(boolArray)\n    filter(x -> x!=-1, #filter all -1\n            #note: the additional comma is required for destructing tuples in anonymous functions\n            map(((i,v),)->v ? i : -1, #if value is true return index otherwise -1\n                enumerate(boolArray))) # enumerate index and value as list of tuples\nend\n\nfunction primeindexes_alt(boolArray)\n    #note: the additional comma is required for destructing tuples in anonymous functions\n    map(((i,_),)->i, # return only the index from the tuples\n        filter(\n            ((_,v),) -> v, # filter all tuples with 'false' val\n            collect(enumerate(boolArray)))) #enumerate to get (index, val) tuples and collect them in a vector\nend\n\n@testset \"sieve of erastosthenes\" begin\n    @test generateprime(20) == [2, 3, 5, 7, 11, 13, 17, 19]\n    @test generateprime(1) == []\n    @test_throws ArgumentError generateprime(0)\nend\n", "meta": {"hexsha": "a14a99e134485d51db3f182fb5f80a0b2916654b", "size": 1653, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "sieve_eratosthenes.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": "sieve_eratosthenes.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": "sieve_eratosthenes.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.170212766, "max_line_length": 110, "alphanum_fraction": 0.6588021779, "num_tokens": 434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176852582231, "lm_q2_score": 0.9184802523931341, "lm_q1q2_score": 0.8672077938634826}}
{"text": "# # Time Series Analysis\n# A time series is a sequence of data points, each associated with a time. In our example, we will work with a time series of daily temperatures in the city of Melbourne, Australia over a period of a few years. Let $x$ be the vector of the time series, and $x_i$ denote the temperature in Melbourne on day $i$. Here is a picture of the time series:\n\nusing Plots, Convex, ECOS, DelimitedFiles\naux(str) = joinpath(@__DIR__, \"aux_files\", str) # path to auxiliary files\n\ntemps = readdlm(aux(\"melbourne_temps.txt\"), ',')\nn = size(temps, 1)\nplot(1:n, temps[1:n], ylabel=\"Temperature (\u00b0C)\", label=\"data\", xlabel = \"Time (days)\", xticks=0:365:n)\n\n\n# We can quickly compute the mean of the time series to be $11.2$. If we were to always guess the mean as the temperature of Melbourne on a given day, the RMS error of our guesswork would be $4.1$. We'll try to lower this RMS error by coming up with better ways to model the temperature than guessing the mean.\n#\n# A simple way to model this time series would be to find a smooth curve that approximates the yearly ups and downs.\n# We can represent this model as a vector $s$ where $s_i$ denotes the temperature on the $i$-th day.\n# To force this trend to repeat yearly, we simply want\n#\n# $$\n#  s_i = s_{i + 365}\n# $$\n#\n# for each applicable $i$.\n#\n# We also want our model to have two more properties:\n#\n# - The first is that the temperature on each day in our model should be relatively close to the actual temperature of that day.\n# - The second is that our model needs to be smooth, so the change in temperature from day to day should be relatively small. The following objective would capture both properties:\n#\n# $$\n#  \\sum_{i = 1}^n (s_i - x_i)^2 + \\lambda \\sum_{i = 2}^n(s_i - s_{i - 1})^2\n# $$\n#\n# where $\\lambda$ is the smoothing parameter. The larger $\\lambda$ is, the smoother our model will be.\n#\n# The following code uses Convex to find and plot the model:\n\nyearly = Variable(n)\neq_constraints = [ yearly[i] == yearly[i - 365] for i in 365 + 1 : n ]\n\nsmoothing = 100\nsmooth_objective = sumsquares(yearly[1 : n - 1] - yearly[2 : n])\nproblem = minimize(sumsquares(temps - yearly) + smoothing * smooth_objective, eq_constraints);\nsolve!(problem, () -> ECOS.Optimizer(maxit=200, verbose=0))\nresiduals = temps - evaluate(yearly)\n\n## Plot smooth fit\nplot(1:n, temps[1:n], label=\"data\")\nplot!(1:n, evaluate(yearly)[1:n], linewidth=2, label=\"smooth fit\",  ylabel=\"Temperature (\u00b0C)\", xticks=0:365:n, xlabel=\"Time (days)\")\n\n# We can also plot the residual temperatures, $r$, defined as $r = x - s$.\n\n## Plot residuals for a few days\nplot(1:100, residuals[1:100], ylabel=\"Residuals\", xlabel=\"Time (days)\")\n\n#-\n\nroot_mean_square_error = sqrt(sum( x -> x^2, residuals) / length(residuals))\n# Our smooth model has a RMS error of $2.7$, a significant improvement from just guessing the mean, but we can do better.\n#\n# We now make the hypothesis that the residual temperature on a given day is some linear combination of the previous $5$ days. Such a model is called autoregressive. We are essentially trying to fit the residuals as a function of other parts of the data itself. We want to find a vector of coefficients $a$ such that\n#\n# $$\n#  \\text{r}(i) \\approx \\sum_{j = 1}^5 a_j \\text{r}(i - j)\n# $$\n#\n# This can be done by simply minimizing the following sum of squares objective\n#\n# $$\n#  \\sum_{i = 6}^n \\left(\\text{r}(i) - \\sum_{j = 1}^5 a_j \\text{r}(i - j)\\right)^2\n# $$\n#\n# The following Convex code solves this problem and plots our autoregressive model against the actual residual temperatures:\n\n## Generate the residuals matrix\nar_len = 5\n\nresiduals_mat = Matrix{Float64}(undef, length(residuals) - ar_len, ar_len)\nfor i = 1:ar_len\n  residuals_mat[:, i] = residuals[ar_len - i + 1 : n - i]\nend\n\n## Solve autoregressive problem\nar_coef = Variable(ar_len)\nproblem = minimize(sumsquares(residuals_mat * ar_coef - residuals[ar_len + 1 : end]))\nsolve!(problem, () -> ECOS.Optimizer(max_iters=200, verbose=0))\n\n## plot autoregressive fit of daily fluctuations for a few days\nar_range = 1:145\nday_range = ar_range .+ ar_len\nplot(day_range, residuals[day_range], label=\"fluctuations from smooth fit\", ylabel=\"Temperature difference (\u00b0C)\")\nplot!(day_range, residuals_mat[ar_range, :] * evaluate(ar_coef), label=\"autoregressive estimate\", xlabel=\"Time (days)\")\n\n\n# Now, we can add our autoregressive model for the residual temperatures to our smooth model to get an better fitting model for the daily temperatures in the city of Melbourne:\n\ntotal_estimate = evaluate(yearly)\ntotal_estimate[ar_len + 1 : end] += residuals_mat * evaluate(ar_coef)\n\n# We can plot the final fit of data across the whole time range:\nplot(1:n, temps, label=\"data\", ylabel=\"Temperature (\u00b0C)\")\nplot!(1:n, total_estimate, label=\"estimate\", xticks=0:365:n, xlabel=\"Time (days)\")\n\n\n# The RMS error of this final model is $\\sim 2.3$:\nroot_mean_square_error = sqrt(sum( x -> x^2, total_estimate - temps) / length(temps))\n", "meta": {"hexsha": "e43ef8c114dd3715c38eb22c6984ac345b83c349", "size": 4957, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/examples_literate/time_series/time_series.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/time_series/time_series.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/time_series/time_series.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": 46.7641509434, "max_line_length": 348, "alphanum_fraction": 0.7179745814, "num_tokens": 1379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.950410972802222, "lm_q2_score": 0.9124361640485893, "lm_q1q2_score": 0.8671893422933475}}
{"text": "# numerial integration trapezoidal method\n\n  function integration(a,b,n::Int64, func::Function)\n    sum = 0.\n    step = (b-a) / n # b and a are, respectivelly, upper and lower limits. n is the number of steps\n    fa = func(a) / 2 \n    fb = func(b) / 2\n    for i in 1:n-1\n      x = i*step + a\n      sum += func(x)\n    end\n    sum = (sum + fb + fa)*step\n  \n    return sum\n  end\n\n\n# Numerical integration\n\n  function width(array)\n    dt = ((maximum(array) - minimum(array))/(length(array)-1))\n    return dt\n  end\n\n# NUMERICAL INTEGRATION - TRAPEZIUM METHOD\n\n\n  function integration(x::Vector, y::Vector) \n    dx = width(x)\n\n# I = (h/2) * (y(1) + 2*y(2) + ... + 2y(n) + y(n+1)\n    I = 0.   \n    n = length(y) - 1\n    for i in 2:n\n      I = I + y[i]\n    end\n    I = (dx/2)*(y[1]+2*I+y[n+1])\n    \n    return I\n\n  end\n\n# Simpson's method\n\n  function integration_simp(x::Vector, y::Vector)\n    dx = width(x)\n    n = length(y) - 1\n    \n    if n % 2 != 0\n      n += 1\n    end\n   \n    I = y[1]\n    for i in 2:n\n      if i % 2 == 0\n        I = I + 4*y[i] \n      elseif i % 2 == 1\n        I = I + 2*y[i]\n      end\n    end\n\n    I = (dx/3) * (I + y[n+1])\n    return I\n  end\n   \n  \n   \n", "meta": {"hexsha": "ac775398c80bc646b2d4880ead81600bd5d584fd", "size": 1170, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/num_integration.jl", "max_stars_repo_name": "viniciuspiccoli/QP232.jl", "max_stars_repo_head_hexsha": "a733c2074c1645c4341393751bd22443c50bd4bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/num_integration.jl", "max_issues_repo_name": "viniciuspiccoli/QP232.jl", "max_issues_repo_head_hexsha": "a733c2074c1645c4341393751bd22443c50bd4bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/num_integration.jl", "max_forks_repo_name": "viniciuspiccoli/QP232.jl", "max_forks_repo_head_hexsha": "a733c2074c1645c4341393751bd22443c50bd4bb", "max_forks_repo_licenses": ["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.2058823529, "max_line_length": 99, "alphanum_fraction": 0.4923076923, "num_tokens": 433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561676667173, "lm_q2_score": 0.8947894625955064, "lm_q1q2_score": 0.8669222895988439}}
{"text": "using LinearAlgebra, Quaternions, ReferenceFrameRotations\n# Check if a given vector is three-dimensional\nfunction check_vector_3(v)\n    if size(v) != (1,3) && size(v) != (3, 1) && size(v) != (3,)\n        println(size(v))\n        println(\"\\nIncorrect vector3. You must introduce an R3 vector.\")\n        return false\n    end\nend\n# Format vector3 to be vertically oriented\nfunction format_vector_3(v)\n    if size(v) == (1,3)\n        v = v'\n    end\n    return v\nend\n\nfunction to_2d(vector3)\n    # Check if the given vector is actually on three dimensions\n    if check_vector_3(vector3) == false return end\n    # If the vector is given horizontal, we transpose it\n    vector3 = format_vector_3(vector3)\n\n    # Defined matrix to convert R3 vector to R2 vector\n    # (we find this matrix on the .pdf attached file)\n    axonometry_matrix = [-0.5*cosd(42)    cosd(7)     0;\n                       -0.5*sind(42)    -sind(7)    1]\n\n    #=axonometry_matrix = [-cosd(30)    cosd(30)     0;\n                        -sind(30)    -sind(30)    1]=#\n\n    # Return the result of the multiplication\n    return axonometry_matrix * vector3\nend\n\nfunction rotate_phi_z(X, phi)\n    # Check if the given vector is actually on three dimensions\n    if check_vector_3(X) == false\n        return\n    end\n    # If the vector is given horizontal, we transpose it\n    X = format_vector_3(X)\n\n    # Define rotation matrix on Z axis\n    R = [ 0 -1 0;\n          1 0 0;\n          0 0 0 ]\n\n    # Apply the Rodrigues formula\n    result = I + sind(phi) * R + (1 - cosd(phi)) * R^2\n\n    # Calculate result using the rotation matrix\n    T = result * X\n    return T\n\nend\n\nfunction rotate_phi(X, phi, axis)\n    # Check if the given vector is actually on three dimensions\n    if check_vector_3(X) == false\n        return\n    end\n    # If the vector is given horizontal, we transpose it\n    X = format_vector_3(X)\n\n    axis = normalize(axis)\n\n    # Define rotation matrix on Z axis\n    R = [ 0      -axis[3]    axis[2];\n         axis[3]    0      -axis[1];\n         -axis[2]  axis[1]      0 ]\n\n    # Apply the Rodrigues formula\n    result = I + sind(phi) * R + (1 - cosd(phi)) * R^2\n\n    # Calculate result using the rotation matrix\n    T = result * X\n    return T\n\nend\n\n# To check if the given vector is of dimension 3\nfunction check_vector_3(v)\n    if size(v) != (1,3) && size(v) != (3, 1) && size(v) != (3,)\n        print(\"Your vector is size \", size(v))\n        println(\"\\nIncorrect vector3. You must introduce an R3 vector.\")\n        return false\n    end\nend\n\n# To check if the given object is a Quaternion\nfunction check_quaternion(q)\n    if typeof(q) == Quaternions.Quaternion{Float64} || typeof(q) == Quaternions.Quaternion{Int64}\n        return true\n    end\n    println(\"You must introduce a valid Quaternion! Using Quaternion()\")\n    return false\nend\n\n# To check if the given matrix is of dimensions 3x3\nfunction check_matrix_3(R)\n    if size(R) != (3,3)\n        print(\"Your matrix is size \", size(R))\n        println(\"\\nIncorrect matrix. You must introduce a 3x3 matrix.\")\n        return false\n    end\nend\n\nfunction check_euler_angleaxis(E)\n    if typeof(E) == EulerAngleAxis{Float64} || typeof(E) == EulerAngleAxis{Int64}\n        return true\n    end\n    println(\"Incorrect EulerAngleAxis. You must introduce an EulerAngleAxis()\")\n    return false\nend\n# Axis/Angle to Quaternion\nfunction axis_angle_to_quat(E)\n\n    if check_euler_angleaxis(E) == false\n        return\n    end\n\n    # We get the axis from our EulerAngleAxis\n    V = Vector{Float64}(E.v)\n    # We get the angle from our EulerAngleAxis\n    phi = E.a\n\n    # Use qrotation function to create a Quaternion with the given axis and angle\n    qR = qrotation(V, phi)\n\n    return qR\n\nend\n\nfunction axis_angle_to_mat(E)\n\n    if check_euler_angleaxis(E) == false\n        return\n    end\n    # We get the axis from our EulerAngleAxis\n    V = normalize(E.v)\n    # We get the angle from our EulerAngleAxis\n    phi = E.a\n\n    # We use Rodrigues Formula to find the Rotation matrix\n    # Define rotation matrix on Z axis\n    R = [ 0     -V[3]   V[2];\n          V[3]   0      -V[1];\n         -V[2]   V[1]      0 ]\n\n    # Apply the Rodrigues formula\n    result = I + sin(phi) * R + (1 - cos(phi)) * R^2\n\n    return result\nend\n\nfunction mat_to_axis_angle(R)\n    if check_matrix_3(R) == false\n        return\n    end\n\n# Find angle\nphi = acos((tr(R) -1) / 2)\n\n# Find axis matrix\nV = (R - R') / (2 * sin(phi))\n\n# Get axis values from the axis matrix into a vector\naxis = [V[3,2]; V[1,3]; V[2,1]]\n\nreturn EulerAngleAxis(phi, axis)\nend\n\nfunction quat_to_axis_angle(q)\n    if check_quaternion(q) == false\n        return\n    end\n\n    # Get the angle\n    angle = 2 * atan(sqrt(q.v1^2 + q.v2^2 + q.v3^2) / q.s)\n\n    # Normalize the Quaternion\n    q = normalize(q)\n\n    # We do the same process as in the\n    s = sin(angle/2)\n\n    # If the s is not zero, we divide. If it is zero, we can't divide.\n    # Therefore, we set axis as the [1 0 0] vector\n    s != 0 ? axis = [q.v1; q.v2; q.v3] / s : axis = [1.0; 0.0; 0.0]\n\n    return EulerAngleAxis(angle, axis)\nend\n\nfunction quat_to_mat(q)\n    if check_quaternion(q) == false\n        return\n    end\n    # We apply the matrix to Quaternion transformation\n    R = [q.s^2 + q.v1^2 - q.v2^2 - q.v3^2    2*q.v1*q.v2 - 2*q.s*q.v3            2*q.v1*q.v3 + 2*q.s*q.v2;\n     2*q.v1*q.v2 + 2*q.s*q.v3                q.s^2 - q.v1^2 + q.v2^2 - q.v3^2    2*q.v2*q.v3 - 2*q.s*q.v1;\n     2*q.v1*q.v3 - 2*q.s*q.v2                2*q.v2*q.v3 + 2*q.s*q.v1            q.s^2 - q.v1^2 - q.v2^2 + q.v3^2]\n\n     return R\n\nend\n\nfunction mat_to_quat(R)\n    if check_matrix_3(R) == false\n        return\n    end\n\n    E = mat_to_axis_angle(R)\n\n    q = axis_angle_to_quat(E)\n\n    return q\nend\n\nfunction rescale_transalte_vector(V, pos, scale)\n    # Get Vector without considering origin\n    # Change Vector position using pos\n    # Position is on world coordinates (always positive)\n\n    #Check vector and position are on the correct format\n    V = format_vector_3(V)\n    pos = format_vector_3(pos)\n\n    # Rescale vector\n    V = V*scale\n\n    # Change vector position\n    V = V+pos\n\n    return V\n\nend\n", "meta": {"hexsha": "08477efc7aab87574ae465e4932c60fd61cf32ff", "size": 6114, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Lab3AffineTransformations_ZhidaChen_AdriaSellares/Exercice_3_Julia/CostumeFunctions.jl", "max_stars_repo_name": "AdriaSeSa/Laboratory3Math", "max_stars_repo_head_hexsha": "2e598e0a2982af3419fe5372a7a42a5f6fd46c29", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lab3AffineTransformations_ZhidaChen_AdriaSellares/Exercice_3_Julia/CostumeFunctions.jl", "max_issues_repo_name": "AdriaSeSa/Laboratory3Math", "max_issues_repo_head_hexsha": "2e598e0a2982af3419fe5372a7a42a5f6fd46c29", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lab3AffineTransformations_ZhidaChen_AdriaSellares/Exercice_3_Julia/CostumeFunctions.jl", "max_forks_repo_name": "AdriaSeSa/Laboratory3Math", "max_forks_repo_head_hexsha": "2e598e0a2982af3419fe5372a7a42a5f6fd46c29", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6890756303, "max_line_length": 114, "alphanum_fraction": 0.6104023553, "num_tokens": 1866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9736446509776294, "lm_q2_score": 0.8902942188450159, "lm_q1q2_score": 0.8668302039747567}}
{"text": "# adapted from https://www.youtube.com/watch?v=vAp6nUMrKYg\r\nstruct Dual <: Number\r\n    x::Float64\r\n    y::Float64\r\nend\r\n\r\nimport Base: +, -, *, /, convert, promote_rule, show\r\n\r\n+(a::Dual, b::Dual) = Dual(a.x+b.x, a.y+b.y)\r\n-(a::Dual, b::Dual) = Dual(a.x-b.x, a.y-b.y)\r\n\r\n*(a::Dual, b::Dual) = Dual(a.x*b.x, a.y*b.x + a.x*b.y)\r\n/(a::Dual, b::Dual) = Dual(a.x/b.x, (a.y*b.x - a.x*b.y)/(b.x^2))\r\n\r\nconvert(::Type{Dual}, x::Real) = Dual(x, zero(x))\r\npromote_rule(::Type{Dual}, ::Type{<:Number}) = Dual\r\nshow(io::IO, d::Dual) = print(io, d.x, \" + \", d.y,\" \u03f5\")\r\n\r\nf(x) = x^2\r\nf(1)\r\nf(1.0)\r\nf(Dual(1,1))\r\n\r\n\"\"\"\r\nCompute the square root of x using the Babylonian algorithm\r\n\"\"\"\r\nfunction babylonian(x; nmax = 10)\r\n    t = (1+x)/2\r\n    for i in 2:nmax\r\n        t = (t + x/t)/2\r\n    end\r\n    return t\r\nend\r\n\r\nbabylonian(\u03c0), \u221a\u03c0\r\nbabylonian(2), \u221a2\r\n\r\n# What happens when we pass a Dual number to babylonian?\r\nx = Dual(2,1)\r\n# We automagically get the derivative!\r\nbabylonian(x)\r\n\u221a2, 0.5/\u221a2", "meta": {"hexsha": "9e8dc243df72f6c092913425f07d17b7750d0865", "size": 978, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "code/dualnumbers.jl", "max_stars_repo_name": "csimal/Julia-Unamur", "max_stars_repo_head_hexsha": "61a1aed8e1bcbed8591508daa8b4b6c1d11384f3", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-15T12:49:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-15T12:49:48.000Z", "max_issues_repo_path": "code/dualnumbers.jl", "max_issues_repo_name": "csimal/Julia-Unamur", "max_issues_repo_head_hexsha": "61a1aed8e1bcbed8591508daa8b4b6c1d11384f3", "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": "code/dualnumbers.jl", "max_forks_repo_name": "csimal/Julia-Unamur", "max_forks_repo_head_hexsha": "61a1aed8e1bcbed8591508daa8b4b6c1d11384f3", "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.2857142857, "max_line_length": 65, "alphanum_fraction": 0.5593047035, "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191348157374, "lm_q2_score": 0.907312213841788, "lm_q1q2_score": 0.8667727191350881}}
{"text": "function nonLinChem(dy,y,p,t)\n dy[1] = -y[1]\n dy[2] = y[1]-(y[2])^2\n dy[3] = (y[2])^2\nend\ny0 = [1.0;0.0;0.0]\ntspan = (0.0,20.0)\nnlc_analytic(u0,p,t) = [exp(-t);\n    (2sqrt(exp(-t))besselk(1,2sqrt(exp(-t)))-2besselk(1,2)/besseli(1,2)*sqrt(exp(-t))besseli(1,2sqrt(exp(-t))))/(2besselk(0,2sqrt(exp(-t)))+(2besselk(1,2)/besseli(1,2))besseli(0,2sqrt(exp(-t))));\n    -exp(-t)+1+(-2sqrt(exp(-t))*besselk(1,2sqrt(exp(-t)))+sqrt(exp(-t))*besseli(1,2sqrt(exp(-t)))*2besselk(1,2)/besseli(1,2))/(2besselk(0,2sqrt(exp(-t)))+2besselk(1,2)/besseli(1,2)*besseli(0,2sqrt(exp(-t))))]\nnonLinChem_f = ODEFunction(nonLinChem,analytic = nlc_analytic)\n\n@doc doc\"\"\"\nNonlinear system of reactions with an analytical solution\n\n```math\n\\frac{dy_1}{dt} = -y_1\n```\n\n```math\n\\frac{dy_2}{dt} = y_1 - y_2^2\n```\n\n```math\n\\frac{dy_3}{dt} = y_2^2\n```\n\nwith initial condition ``y=[1;0;0]`` on a time span of ``t \\in (0,20)``\n\nFrom\n\nLiu, L. C., Tian, B., Xue, Y. S., Wang, M., & Liu, W. J. (2012). Analytic solution \nfor a nonlinear chemistry system of ordinary differential equations. Nonlinear \nDynamics, 68(1-2), 17-21.\n\nThe analytical solution is implemented, allowing easy testing of ODE solvers.\n\"\"\"\nprob_ode_nonlinchem = ODEProblem(nonLinChem,y0,tspan)\n", "meta": {"hexsha": "62fff1c474dcb253cb500b7d75cb2f4330ea6493", "size": 1223, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ode/nonlinchem.jl", "max_stars_repo_name": "hellmrf/DiffEqProblemLibrary.jl", "max_stars_repo_head_hexsha": "ed6c668ec9cf82ee1769fb7efdaf8bf9755ec81a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2020-05-12T17:21:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T06:28:06.000Z", "max_issues_repo_path": "src/ode/nonlinchem.jl", "max_issues_repo_name": "hellmrf/DiffEqProblemLibrary.jl", "max_issues_repo_head_hexsha": "ed6c668ec9cf82ee1769fb7efdaf8bf9755ec81a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 42, "max_issues_repo_issues_event_min_datetime": "2017-05-17T03:36:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-16T02:01:05.000Z", "max_forks_repo_path": "src/ode/nonlinchem.jl", "max_forks_repo_name": "hellmrf/DiffEqProblemLibrary.jl", "max_forks_repo_head_hexsha": "ed6c668ec9cf82ee1769fb7efdaf8bf9755ec81a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21, "max_forks_repo_forks_event_min_datetime": "2016-11-04T12:18:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-23T13:04:07.000Z", "avg_line_length": 31.358974359, "max_line_length": 208, "alphanum_fraction": 0.6443172527, "num_tokens": 532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248157222395, "lm_q2_score": 0.9230391563648734, "lm_q1q2_score": 0.8667566737099367}}
{"text": "using LinearAlgebra\r\nusing Symbolics\r\n\r\n# Problem One\r\n\r\nA = Matrix{Int8}([0 5 0; 8 3 7; 9 -2 9])\r\nB = Matrix{Int8}([4 6 -2; 7 2 3; 1 3 -4])\r\nC = Vector{Int8}([-1, 2, 5])\r\n\r\nprintln(\"Result of A*B: \")\r\ndisplay(A*B)\r\nprintln(\"\")\r\n\r\nprintln(\"Result of A*C: \")\r\ndisplay(A*C)\r\nprintln(\"\")\r\n\r\nprintln(\"Identity Matrix of Matrix A: \")\r\nidentityA = Matrix{Int8}(I,3,3)\r\ndisplay(identityA)\r\nprintln(\"\")\r\n\r\nprintln(\"Result of I*A: \")\r\ndisplay(identityA*A)\r\nprintln(\"\")\r\n\r\nprintln(\"Result of A*I: \")\r\ndisplay(A*identityA)\r\nprintln(\"\")\r\n\r\nprintln(\"Matrix A\")\r\ndisplay(A)\r\nprintln(\"\")\r\n\r\n#Problem Two\r\n\r\nA = Matrix{Int8}([5  7  2  0  3  5;\r\n     3  8 -3 -5  0  8;\r\n     1  4  0  7 15  9;\r\n     0 10  5 12  3 -1;\r\n     2 -5  9  2 18 -10])\r\n\r\nB = Matrix{Int8}([ 2 10  0;\r\n      8  7  5;\r\n     -5  2 -4;\r\n      4  8 13;\r\n      3 12  0;\r\n      1  5  7])\r\n\r\nprintln(\"Result C = A*B: \")\r\ndisplay(A*B)\r\nprintln(\"\")\r\n\r\nprintln(\"Transpose of Matrix A: \")\r\ndisplay(transpose(A))\r\nprintln(\"\")\r\n\r\n# Problem Three\r\n\r\nA = Matrix{Int8}([1 5 0; 8 3 7; 6 -2 9])\r\n\r\nprintln(\"Determinant of Matrix A: \")\r\ndisplay(det(A))\r\nprintln(\"\")\r\n\r\nprintln(\"Determinant of the Transpose of Matrix A: \")\r\ndisplay(det(transpose(A)))\r\nprintln(\"\")\r\n\r\nprintln(\"Inverse of Matrix A: \")\r\ndisplay(inv(A))\r\nprintln(\"\")\r\n\r\n# Problem Four\r\n@variables k1\r\nA = [0 0 0 0;\r\n     0 k1 0 -k1;\r\n     0 0 0 0;\r\n     0 -k1 0 k1;]\r\nprintln(\"Local Matrix A: \")\r\ndisplay(A)\r\nprintln(\"\")\r\n\r\nG = [0 0 0 0 0 0 0 0 0 0;\r\n     0 0 0 0 0 0 0 0 0 0;\r\n     0 0 0 0 0 0 0 0 0 0;\r\n     0 0 0 k1 0 0 0 -k1 0 0;\r\n     0 0 0 0 0 0 0 0 0 0;\r\n     0 0 0 0 0 0 0 0 0 0;\r\n     0 0 0 0 0 0 0 0 0 0;\r\n     0 0 0 -k1 0 0 0 k1 0 0;\r\n     0 0 0 0 0 0 0 0 0 0;\r\n     0 0 0 0 0 0 0 0 0 0;]\r\nprintln(\"Mapped global matrix, G: \")\r\ndisplay(G)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "4fa2af7899b1494c51f4df89ba917d6e9f00ae3e", "size": 1769, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "trejo_nicholas_IC1.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_IC1.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_IC1.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": 16.8476190476, "max_line_length": 54, "alphanum_fraction": 0.5195025438, "num_tokens": 769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741241296944, "lm_q2_score": 0.9099069987088003, "lm_q1q2_score": 0.8667538623345145}}
{"text": "#############################################################\nfunction mylogpdf_Cov(x, \u03bc, \u03a3)\n#############################################################\n\n    @assert(length(x) == length(\u03bc) == size(\u03a3,1) == size(\u03a3,2))\n\n    d = length(\u03bc)\n\n    L = chol(Hermitian(\u03a3))'\n\n    TERM1 = -0.5 * 2.0*sum(log.(diag(L))) # consult eq. A.18 in RW\n    TERM2 = -0.5 * d * log(2\u03c0)\n    TERM3 = -0.5 * sum(( (L\\(x-\u03bc)).^2 ))\n\n    return TERM1 + TERM2 + TERM3\n\nend\n\n#############################################################\nfunction mylogpdf_scalCov(x, \u03bc, \u03c32)\n#############################################################\n\n    @assert(length(x) == length(\u03bc))\n\n    d = length(\u03bc)\n\n    TERM1 = -0.5 * d * log(\u03c32)\n    TERM2 = -0.5 * d * log(2\u03c0)\n    TERM3 = -0.5 * sum((x-\u03bc).^2)/\u03c32\n\n    return TERM1 + TERM2 + TERM3\n\nend\n", "meta": {"hexsha": "a5c3bf21b2af2b63149d018e00f6fe6dc6b38802", "size": 800, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/OLD/mylogpdf.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/mylogpdf.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/mylogpdf.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.5294117647, "max_line_length": 66, "alphanum_fraction": 0.3575, "num_tokens": 245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399069145609, "lm_q2_score": 0.8933094152856196, "lm_q1q2_score": 0.8667244439326204}}
{"text": "### A Pluto.jl notebook ###\n# v0.16.0\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 863debb0-fc11-11ea-09e6-dfb25ad73b07\nusing JuMP\n\n# \u2554\u2550\u2561 894add90-fc11-11ea-16ed-0120c97d8aec\nusing GLPK\n\n# \u2554\u2550\u2561 6f96aa50-fc11-11ea-22c9-01e5e73d8ab0\nmd\"# Applications of Linear Programming\"\n\n# \u2554\u2550\u2561 8c3d90b0-fc11-11ea-2873-934ec496d1ee\nmd\"\"\"## Economy\n\nA manufacturer produces  four different  products  $X_1$, $X_2$, $X_3$ and $X_4$. There are three inputs to this production process:\n\n- labor in man weeks,  \n- kilograms of raw material A, and \n- boxes  of raw  material  B.\n\nEach product has different input requirements. In determining each  week's production schedule, the manufacturer cannot use more than the available amounts of  manpower and the two raw  materials:\n\n|Inputs|$X_1$|$X_2$|$X_3$|$X_4$|Availabilities|\n|------|-----|-----|-----|-----|--------------|\n|Person-weeks|1|2|1|2|20|\n|Kilograms of material A|6|5|3|2|100|\n|Boxes of material B|3|4|9|12|75|\n|Production level|$x_1$|$x_2$|$x_3$|$x_4$| |\n\nThese constraints can be written in mathematical form\n\n```math\n\\begin{aligned}\nx_1+2x_2+x_3+2x_4\\le&20\\\\\n6x_1+5x_2+3x_3+2x_4\\le&100\\\\\n3x_1+4x_2+9x_3+12x_4\\le&75\n\\end{aligned}\n```\n\nBecause negative production levels are not meaningful, we must impose the following nonnegativity constraints on the production levels:\n\n```math\nx_i\\ge0,\\qquad i=1,2,3,4\n```\n\nNow suppose that one unit of product $X_1$ sells for \u20ac6 and $X_2$, $X_3$ and $X_4$ sell for \u20ac4, \u20ac7 and \u20ac5, respectively. Then, the total revenue for any production decision $\\left(x_1,x_2,x_3,x_4\\right)$ is\n\n```math\nf\\left(x_1,x_2,x_3,x_4\\right)=6x_1+4x_2+7x_3+5x_4\n```\n\nThe problem is then to maximize $f$ subject to the given constraints.\"\"\"\n\n# \u2554\u2550\u2561 acba3730-fc11-11ea-2d31-27432ab5e777\nlet\n\tmodel = Model(GLPK.Optimizer)\n\t@variable(model, 0 <= x1)\n\t@variable(model, 0 <= x2)\n\t@variable(model, 0 <= x3)\n\t@variable(model, 0 <= x4)\n\t@objective(model, Max, 6*x1 + 4*x2 + 7*x3 + 5*x4)\n\t@constraint(model, con1,   x1 + 2*x2 +   x3 +  2*x4 <= 20)\n\t@constraint(model, con2, 6*x1 + 5*x2 + 3*x3 +  2*x4 <= 100)\n\t@constraint(model, con3, 3*x1 + 4*x2 + 9*x3 + 12*x4 <= 75)\n\toptimize!(model)\n\ttermination_status(model), primal_status(model), value(x1), value(x2), value(x3), value(x4), objective_value(model)\nend\n\n# \u2554\u2550\u2561 06330800-fc12-11ea-011c-e762078d0d88\nmd\"\"\"## Manufacturing\n\nA manufacturer produces two different products $X_1$ and $X_2$ using three machines $M_1$, $M_2$, and $M_3$. Each machine can be used only for a limited amount of time. Production times of each product on each machine are given by \n\n|Machine|Production time $X_1$|Production time $X_2$|Available time|\n|-------|---------------------|---------------------|--------------|\n|$M_1$  |1                    |1                    |8             |\n|$M_2$  |1                    |3                    |18            |\n|$M_3$  |2                    |1                    |14            |\n|Total  |4                    |5                    |              |\n\nThe objective is to maximize the combined time of utilization of all three machines.\n\nEvery production decision must satisfy the constraints on the available time. These restrictions can be written down using data from the table.\n\n```math\n\\begin{aligned}\nx_1+x_2&\\le8\\,,\\\\\nx_1+3x_2&\\le18\\,,\\\\\n2x_1+x_2&\\le14\\,,\n\\end{aligned}\n```\n\nwhere $x_1$ and $x_2$ denote the production levels. The combined production time of all three machines is\n\n```math\nf\\left(x_1,x_2\\right)=4x_1+5x_2\\,.\n```\"\"\"\n\n# \u2554\u2550\u2561 51553150-fc12-11ea-2020-7b418f5eb559\nlet\n\tmodel = Model(GLPK.Optimizer)\n\t@variable(model, 0 <= x1)\n\t@variable(model, 0 <= x2)\n\t@objective(model, Max, 4*x1 + 5*x2)\n\t@constraint(model, con1,   x1 +   x2 <= 8)\n\t@constraint(model, con2,   x1 + 3*x2 <= 18)\n\t@constraint(model, con3, 2*x1 +   x2 <= 14)\n\toptimize!(model)\n\ttermination_status(model), primal_status(model), value(x1), value(x2), objective_value(model)\nend\n\n# \u2554\u2550\u2561 7616fb90-fc12-11ea-1b4b-f7ad83c91fe9\nmd\"\"\"## Transportation\n\nA manufacturing company has plants in cities A, B, and C. The company produces and distributes its product to dealers in various cities. On a particular day, the company has 30 units of its product in A, 40 in B, and 30 in C. The company plans to ship 20 units to D, 20 to E, 25 to F, and 35 to G, following orders received from dealers. The transportation costs per unit of each product between the cities are given by\n\n|From|To D|To E|To F|To G|Supply|\n|----|----|----|----|----|------|\n|A   |7   |10  |14  |8   |30    |\n|B   |7   |11  |12  |6   |40    |\n|C   |5   |8   |15  |9   |30    |\n|Demand|20|20  |25  |35  |100   |\n\nIn the table, the quantities supplied and demanded appear at the right and along the bottom of the table. The quantities to be transported from the plants to different destinations are represented by the decision variables.\n\nThis problem can be stated in the form:\n\n```math\n\\min 7x_{AD}+10x_{AE}+14x_{AF}+8x_{AG}+7x_{BD}+11x_{BE}+12x_{BF}+6x_{BG}+5x_{CD}+8x_{CE}+15x_{CF}+9x_{CG}\n```\n\nsubject to\n\n```math\n\\begin{aligned}\nx_{AD}+x_{AE}+x_{AF}+x_{AG}&=30\\\\\nx_{BD}+x_{BE}+x_{BF}+x_{BG}&=40\\\\\nx_{CD}+x_{CE}+x_{CF}+x_{CG}&=30\\\\\nx_{AD}+x_{BD}+x_{CD}&=20\\\\\nx_{AE}+x_{BE}+x_{CE}&=20\\\\\nx_{AF}+x_{BF}+x_{CF}&=25\\\\\nx_{AG}+x_{BG}+x_{CG}&=35\n\\end{aligned}\n```\n\nIn this problem, one of the constraint equations is redundant because it can be derived from the rest of the constraint equations. The mathematical formulation of the transportation problem is then in a linear programming form with twelve (3x4) decision variables and six (3 + 4 - 1) linearly independent constraint equations. Obviously, we also require nonnegativity of the decision variables, since a negative shipment is impossible and does not have any valid interpretation.\"\"\"\n\n# \u2554\u2550\u2561 d6798340-fc12-11ea-0b8d-71931d797511\nlet\n\tmodel = Model(GLPK.Optimizer)\n\t@variable(model, 0 <= x[1:3,1:4])\n\t@objective(model, Min, 7x[1,1]+10x[1,2]+14x[1,3]+8x[1,4]+7x[2,1]+11x[2,2]+12x[2,3]+6x[2,4]+5x[3,1]+8x[3,2]+15x[3,3]+9x[3,4])\n\t@constraint(model, con1, sum(x[1,j] for j in 1:4) == 30)\n\t@constraint(model, con2, sum(x[2,j] for j in 1:4) == 40)\n\t@constraint(model, con3, sum(x[3,j] for j in 1:4) == 30)\n\t@constraint(model, con4, sum(x[i,1] for i in 1:3) == 20)\n\t@constraint(model, con5, sum(x[i,2] for i in 1:3) == 20)\n\t@constraint(model, con6, sum(x[i,3] for i in 1:3) == 25)\n\t@constraint(model, con7, sum(x[i,4] for i in 1:3) == 35)\n\toptimize!(model)\n\ttermination_status(model), primal_status(model), value.(x), objective_value(model)\nend\n\n# \u2554\u2550\u2561 6d012070-fc13-11ea-1f08-b3754cf9c6bd\nmd\"\"\"This problem is an _integer linear programming_ problem, i.e. the solution components must be integers.\n\nWe can use the simplex method to find a solution to an ILP problem if the $m\\times n$ matrix $A$ is unimodular, i.e. if all its nonzero $m$th order minors are $\\pm 1$.\"\"\"\n\n# \u2554\u2550\u2561 7a077a30-fc13-11ea-193e-6b30f852c9e7\nmd\"\"\"## Electricity\n\nAn electric circuit is designed to use a 30 V source to charge 10 V, 6 V, and 20 V batteries connected in parallel. Physical constraints limit the currents $I_1$, $I_2$, $I_3$, $I_4$, and $I_5$ to a maximum of 4 A, 3 A, 3 A, 2 A, and 2 A, respectively. In addition, the batteries must not be discharged, that is, the currents $I_1$, $I_2$, $I_3$, $I_4$, and $I_5$ must not be negative. We wish to find the values of the currents $I_1$, $I_2$, $I_3$, $I_4$, and $I_5$ such that the total power transferred to the batteries is maximized.\n\nThe total power transferred to the batteries is the sum of the powers transferred to each battery, and is given by $10I_2 + 6I_4 + 20I_5$ W. From the circuit, we observe that the currents satisfy the constraints $I_1 = I_2 + I_3$, and $I_3 = I_4 + I_5$. Therefore, the problem can be posed as the following linear program:\n\n```math\n\\max 10I_2+6I_4+20I_5\n```\n\nsubject to\n\n```math\n\\begin{aligned}\nI_1 &= I_2 + I_3\\\\\nI_3 &= I_4 + I_5\\\\\nI_1 &\\le 4\\\\\nI_2 &\\le 3\\\\\nI_3 &\\le 3\\\\\nI_4 &\\le 2\\\\\nI_5 &\\le 2\n\\end{aligned}\n```\n\n\"\"\"\n\n# \u2554\u2550\u2561 98561d20-fc13-11ea-0278-cf26118a2c51\nlet\n\tmodel = Model(GLPK.Optimizer)\n\t@variable(model, 0 <= I[1:5])\n\t@objective(model, Max, 10*I[2]+6*I[4]+20I[5])\n\t@constraint(model, con1, I[1] == I[2] + I[3])\n\t@constraint(model, con2, I[3] == I[4] + I[5])\n\t@constraint(model, con3, I[1] <= 4)\n\t@constraint(model, con4, I[2] <= 3)\n\t@constraint(model, con5, I[3] <= 3)\n\t@constraint(model, con6, I[4] <= 2)\n\t@constraint(model, con7, I[5] <= 2)\n\toptimize!(model)\n\ttermination_status(model), primal_status(model), value.(I), objective_value(model)\nend\n\n# \u2554\u2550\u2561 478fe6e0-fc14-11ea-10d4-4d9e0de6ea00\nmd\"\"\"## Telecom\n\nConsider a wireless communication system. There are $n$ \"mobile\" users. For each $i$ in $1,\\dots, n$; user $i$ transmits a signal to the base station with power $P_i$ and an attenuation factor of $h_i$ (i.e., the actual received signal power at the basestation from user $i$ is $h_iP_i$). When the basestation is receiving from user $i$, the total received power from all other users is considered \"interference\" (i.e., the interference for user $i$ is $\\sum_{i\\ne j}h_jP_j$). For the communication with user $i$ to be reliable, the signal-to-interference ratio must exceed a threshold $\\gamma_i$, where the \"signal\" is the received power for user $i$.\n\nWe are interested in minimizing the total power transmitted by all the users subject to having reliable communications for all users. We can formulate the problem as a linear programming problem of the form\n\n```math\n\\min \\sum_iP_i\n```\n\nsubject to\n\n```math\n\\forall i \\in 1,\\dots,n\\,:\\,\\begin{cases}\n\\frac{h_iP_i}{\\sum_{i\\ne j}h_jP_j}\\ge\\gamma_i\\\\\nP_i\\ge0\n\\end{cases}\n```\"\"\"\n\n# \u2554\u2550\u2561 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nGLPK = \"60bf3e95-4087-53dc-ae20-288a0d20c6a6\"\nJuMP = \"4076af6c-e467-56ae-b986-b466b2749572\"\n\n[compat]\nGLPK = \"~0.14.14\"\nJuMP = \"~0.21.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[[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[[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[[ChainRulesCore]]\ndeps = [\"Compat\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"4ce9393e871aca86cc457d9f66976c3da6902ea7\"\nuuid = \"d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4\"\nversion = \"1.4.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[[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[[DataStructures]]\ndeps = [\"Compat\", \"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"7d9d316f04214f7efdbb6398d545446e246eff02\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.18.10\"\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[[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[[GLPK]]\ndeps = [\"BinaryProvider\", \"CEnum\", \"GLPK_jll\", \"Libdl\", \"MathOptInterface\"]\ngit-tree-sha1 = \"833dbc8fbb0554e31186df509d67fc2f78f1bb09\"\nuuid = \"60bf3e95-4087-53dc-ae20-288a0d20c6a6\"\nversion = \"0.14.14\"\n\n[[GLPK_jll]]\ndeps = [\"Artifacts\", \"GMP_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"01de09b070d4b8e3e1250c6542e16ed5cad45321\"\nuuid = \"e8aa6df9-e6ca-548a-97ff-1f85fc5b8b98\"\nversion = \"5.0.0+0\"\n\n[[GMP_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"781609d7-10c4-51f6-84f2-b8444358ff6d\"\n\n[[HTTP]]\ndeps = [\"Base64\", \"Dates\", \"IniFile\", \"MbedTLS\", \"Sockets\"]\ngit-tree-sha1 = \"c7ec02c4c6a039a98a15f955462cd7aea5df4508\"\nuuid = \"cd3eb016-35fb-5094-929b-558a96fad6f3\"\nversion = \"0.8.19\"\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[[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[[JSONSchema]]\ndeps = [\"HTTP\", \"JSON\", \"ZipFile\"]\ngit-tree-sha1 = \"b84ab8139afde82c7c65ba2b792fe12e01dd7307\"\nuuid = \"7d188eb4-7ad8-530c-ae41-71a32a6d4692\"\nversion = \"0.3.3\"\n\n[[JuMP]]\ndeps = [\"Calculus\", \"DataStructures\", \"ForwardDiff\", \"JSON\", \"LinearAlgebra\", \"MathOptInterface\", \"MutableArithmetics\", \"NaNMath\", \"Printf\", \"Random\", \"SparseArrays\", \"SpecialFunctions\", \"Statistics\"]\ngit-tree-sha1 = \"4358b7cbf2db36596bdbbe3becc6b9d87e4eb8f5\"\nuuid = \"4076af6c-e467-56ae-b986-b466b2749572\"\nversion = \"0.21.10\"\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[[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[[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[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[MutableArithmetics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\", \"Test\"]\ngit-tree-sha1 = \"3927848ccebcc165952dc0d9ac9aa274a87bfe01\"\nuuid = \"d8a4904e-b15c-11e9-3269-09a3773c0cb0\"\nversion = \"0.2.20\"\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 = \"438d35d2d95ae2c5e8780b330592b6de8494e779\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.0.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[[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[[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[[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[[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[[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[[ZipFile]]\ndeps = [\"Libdl\", \"Printf\", \"Zlib_jll\"]\ngit-tree-sha1 = \"3593e69e469d2111389a9bd06bac1f3d730ac6de\"\nuuid = \"a5390f91-8eb1-5f08-bee0-b1d1ffed6cea\"\nversion = \"0.9.4\"\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\u25006f96aa50-fc11-11ea-22c9-01e5e73d8ab0\n# \u2560\u2550863debb0-fc11-11ea-09e6-dfb25ad73b07\n# \u2560\u2550894add90-fc11-11ea-16ed-0120c97d8aec\n# \u255f\u25008c3d90b0-fc11-11ea-2873-934ec496d1ee\n# \u2560\u2550acba3730-fc11-11ea-2d31-27432ab5e777\n# \u255f\u250006330800-fc12-11ea-011c-e762078d0d88\n# \u2560\u255051553150-fc12-11ea-2020-7b418f5eb559\n# \u255f\u25007616fb90-fc12-11ea-1b4b-f7ad83c91fe9\n# \u2560\u2550d6798340-fc12-11ea-0b8d-71931d797511\n# \u255f\u25006d012070-fc13-11ea-1f08-b3754cf9c6bd\n# \u255f\u25007a077a30-fc13-11ea-193e-6b30f852c9e7\n# \u2560\u255098561d20-fc13-11ea-0278-cf26118a2c51\n# \u255f\u2500478fe6e0-fc14-11ea-10d4-4d9e0de6ea00\n# \u255f\u250000000000-0000-0000-0000-000000000001\n# \u255f\u250000000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "9c58cd94176852b175ce0b7c0db3bc8d33f2272d", "size": 21673, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Lectures/Lecture07.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/Lecture07.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/Lecture07.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": 33.6537267081, "max_line_length": 652, "alphanum_fraction": 0.7054399483, "num_tokens": 9037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341962906709, "lm_q2_score": 0.9059898121338507, "lm_q1q2_score": 0.8667008357782021}}
{"text": "module MaxCut\n\nusing LinearAlgebra\nusing Convex\nusing SCS\n\n\"The Goemans-Williamson algorithm for the MAXCUT problem.\"\n\nfunction maxcut(W::Matrix{<:Real}; iter::Int=100, tol::Real=0)\n\t\"Partition a graph into two disjoint sets such that the sum of the edge weights\n\twhich cross the partition is as large as possible (known to be NP-hard).\"\n\n\t\"A cut of a graph can be produced by assigning either 1 or -1 to each vertex. The Goemans-Williamson \n\talgorithm relaxes this binary condition to allow for vector assignments drawn from the (n-1)-sphere\n\t(choosing an n-1 dimensional space will ensure seperability). This relaxation can then be written as \n\ta semidefinite program. Once the optimal vector assignments are found, origin centered hyperplanes are generated and \n\ttheir corresponding cuts evaluated. After 'iter' trials, or when the desired tolerance is reached,\n\tthe hyperplane with the highest corresponding binary cut is used to partition the vertices.\"\n\t\n\t\"W:\t\tAdjacency matrix.\"\n\t\"tol:\tMaximum acceptable distance between a cut and the MAXCUT upper bound.\"\n\t\"iter:\tMaximum number of hyperplane iterations before a cut is chosen.\"\n\n\tLinearAlgebra.checksquare(W)\n\tissymmetric(W)\t\t\t\t\t|| throw(ArgumentError(\"Adjacency matrix must be symmetric.\"))\n\tall(W .>= 0)\t\t\t\t\t|| throw(ArgumentError(\"Adjacency matrix must be nonnegative.\"))\n\tall(iszero.(diag(W)))\t\t\t|| throw(ArgumentError(\"Diagonal of adjacency matrix must be zero (no self loops).\"))\n\t(tol >= 0)\t\t\t\t\t\t|| throw(ArgumentError(\"The tolerance must be nonnegative.\"))\n\t(iter > 0)\t\t\t\t\t\t|| throw(ArgumentError(\"The number of iterations must be a positive integer.\"))\n\n\t\"This is the standard SDP Relaxation of the MAXCUT problem, a reference can be found at,\n\thttp://www.sfu.ca/~mdevos/notes/semidef/GW.pdf\"\n\tk = size(W, 1)\n\tS = Semidefinite(k)\n\t\n\texpr = dot(W, S)\n\tconstr = [S[i,i] == 1.0 for i in 1:k]\n\tproblem = minimize(expr, constr...)\n\tsolve!(problem, SCS.Optimizer(verbose=false))\n\n\t## ensure symmetric positive-definite\n\tA = 0.5 * (S.value + S.value')\n\tA += (max(0, -eigmin(A)) + 1e-14) * Matrix(I, size(A, 1), size(A, 1))\n\n\tX = Matrix(cholesky(A))\n\n\t## a non-trivial upper bound on MAXCUT\n\tupperbound = (sum(W) - dot(W, S.value)) / 4\n\n\t## random origin-centered hyperplanes, generated to produce partitions of the graph\n\tmax_cut = -1\n\tmax_partition = nothing\n\n\tfor i in 1:iter\n\t\tgweval = X' * randn(k)\n\t\tpartition = (findall(gweval .>= 0), findall(gweval .< 0))\n\t\tcut = sum(W[partition...])\n\n\t\tif cut > max_cut\n\t\t\tmax_partition = partition\n\t\t\tmax_cut = cut\n\t\tend\n\n\t\t(upperbound - max_cut < tol) && break\n\t\t(i == iter) && println(\"Max iterations reached.\")\n\tend\n\treturn max_cut, max_partition\nend\n\nexport maxcut\n\nend\n", "meta": {"hexsha": "942940f1ec376b5e89913f6e92f8b8fd500c2ec2", "size": 2678, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MaxCut.jl", "max_stars_repo_name": "ericproffitt/maxcut.jl", "max_stars_repo_head_hexsha": "ccd1ad59b346c510310ab8e7e46f71e670bb0520", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MaxCut.jl", "max_issues_repo_name": "ericproffitt/maxcut.jl", "max_issues_repo_head_hexsha": "ccd1ad59b346c510310ab8e7e46f71e670bb0520", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MaxCut.jl", "max_forks_repo_name": "ericproffitt/maxcut.jl", "max_forks_repo_head_hexsha": "ccd1ad59b346c510310ab8e7e46f71e670bb0520", "max_forks_repo_licenses": ["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.6849315068, "max_line_length": 118, "alphanum_fraction": 0.716206124, "num_tokens": 753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811641488383, "lm_q2_score": 0.8976952859490985, "lm_q1q2_score": 0.866618120200465}}
{"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 = 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# ======================================================\nfunction dlyap_test()\n\t\n\t# example from \n\t# Barraud, A.Y., \"A numerical algorithm to solve A'XA - X = Q\",\n\t# IEEE Trans. Auto. Contr., AC-22, pp. 883-885, 1977. \n\n\tA = [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\n\tq = [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\n\tQ = (q + q') - diagm(diag(q))\n\n\tx = [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\n\tX = (x + x') - diagm(diag(x))\n\t\n\tA = A'\n\tQ = -Q\n\n\tX1 = dlyap(A,Q)\n\n\treturn X,X1\n\nend\n", "meta": {"hexsha": "612953e97b9d3bdf36d78dd4d4e1f9a14e68b56b", "size": 1227, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/auxfun/dlyap.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/auxfun/dlyap.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/auxfun/dlyap.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": 19.7903225806, "max_line_length": 64, "alphanum_fraction": 0.4849225754, "num_tokens": 707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811641488385, "lm_q2_score": 0.8976952845805988, "lm_q1q2_score": 0.8666181188793413}}
{"text": "# Unit 00 -  Brief Review of Vectors, Planes, and Optimization\n\nusing LinearAlgebra, Distributions\n\n## Homework 0\n\n### 4. Points and Vectors\n\nx = [0.4, 0.3]\ny = [-0.15, 0.2]\n\nnx = norm(x)\nny = norm(y)\n\nsqrt(0.4^2+0.3^2)\nsqrt((-0.15)^2+0.2^2)\n\ndotxy = dot(x,y)\n0.4*-0.15+0.3*0.2\n\n\u03b1 = acos(0)\n\n3.14/2\n\nusing LinearAlgebra\na = [4,1]\nb = [2,3]\nnormC = dot(a,b)/norm(b)\nc = (dot(a,b)/norm(b)^2) * b\n\n### 7. Univariate Gaussians\n\n#### Probability\n\n# Direct approach\nX = Normal(1,sqrt(2))\nP = cdf(X,2) - cdf(X,0.5)\n\n# Using Standard Normals\nZ = Normal(0,1)\nZlBound = (0.5-1)/sqrt(2)\nZuBound = (2-1)/sqrt(2)\nP = cdf(Z,ZuBound) - cdf(Z,ZlBound)\n\n### 8. (Optional Ungraded Warmup) 1D Optimization via Calculus\n\nusing SymPy,Plots\n\nx = symbols(\"x\")\n\nf = (1/3)* x^3 - x^2 - 3*x + 10\ndf = diff(f,x)\ncritPoints = solve(df,x)\ndf2 = diff(df,x)\n\ndf2_x1 = subs(df2, x => critPoints[1])\ndf2_x2 = subs(df2, x => critPoints[2])\n\nf_x1 = subs(f, x => critPoints[1])\nf_x2 = subs(f, x => critPoints[2])\nf_m4 = subs(f, x => -4)\nf_4 = subs(f, x => 4)\n# or, more simply...\nf(critPoints[1])\nf(critPoints[2])\nf(-4)\nf(4)\n\nplot(f,-4,4)\nplot(-exp(-x))\nplot(x^0.7)\n\n### 9. Gradients and Optimization\n\nsurface((x,y) -> x^2+y^2)\n\nusing Plots\nx=-10:0.1:10\ny=-10:0.1:10\nf2(x,y) = x^2+y^2\nplot(x,y,f2,st=:surface,camera=(45,45))\n\n### 10. Matrices and Vectors\n\nA = [1 2 3; 4 5 6; 1 2 1]\nB = [2 1 0; 1 4 4; 5 6 4]\n\nrank(A)\nrank(B)\n\n### 12. Linear Independence, Subspaces and Dimension\n\nA = [1 3; 2 6]\n\nB = [1 2; 2 1]\n\nC = [1 1 0; 0 1 1; 0 0 1]\n\nD = [2 -1 -1; -1 2 -1; -1 -1 2]\n\nrank(A)\n\nrank(B)\n\nrank(C)\n\nrank(D)\n\n### 13. Determinant\n\nA = [1 2 3; 4 5 6; 1 2 1]\n\ndet(A)\n\ndet(A')\n", "meta": {"hexsha": "d59844100512cc07aa28eea3bbda7a986c84b6e6", "size": 1636, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Unit 00 - Course Overview, Homework 0, Project 0/Unit 00 - Course Overview, Homework 0, Project 0.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 00 - Course Overview, Homework 0, Project 0/Unit 00 - Course Overview, Homework 0, Project 0.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 00 - Course Overview, Homework 0, Project 0/Unit 00 - Course Overview, Homework 0, Project 0.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": 14.1034482759, "max_line_length": 62, "alphanum_fraction": 0.5776283619, "num_tokens": 755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075722839015, "lm_q2_score": 0.9005297834483234, "lm_q1q2_score": 0.8664065237228139}}
{"text": "# If we list all the natural numbers below 10 that are multiples of 3 or 5, we\n# get 3, 5, 6 and 9. The sum of these multiples is 23.\n#\n# Find the sum of all the multiples of 3 or 5 below 1000.\n\nusing ProjectEulerSolutions\n\n# Brute force approach, loop through checking for multiples.\nfunction p001solution_loop(n::Integer=9)::Integer\n    total_sum = 0\n    @simd for i in 1:n\n        if i % 3 == 0 || i % 5 == 0\n            total_sum += i\n        end\n    end\n    return total_sum\nend\n\n# Faster approach, sum of real numbers in a sequence is n*(n+1)/2, just scale\n# and remove double counts.\nfunction p001solution_closedform(n::Integer=9)::Integer\n    n3  = div(n, 3)\n    n5  = div(n, 5)\n    n15 = div(n, 15)\n    return  3 * div(n3 * (n3 + 1), 2) +\n            5 * div(n5 * (n5 + 1), 2) -\n           15 * div(n15 * (n15 + 1), 2)\nend\n\np001 = Problems.Problem(Dict(\"Closed form\" => p001solution_closedform,\n                             \"Loop\" => p001solution_loop))\n\nProblems.benchmark(p001, 999)", "meta": {"hexsha": "fea0a527e35e7306741380c76cc20a71a2cffa89", "size": 993, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/001.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/001.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/001.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.0909090909, "max_line_length": 78, "alphanum_fraction": 0.6112789527, "num_tokens": 326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551566309688, "lm_q2_score": 0.8976953003183444, "lm_q1q2_score": 0.8661459395955408}}
{"text": "\"\"\"\n    triangle_area(v1, v2, v3)\n\nArea of a triangle defined by the vertices `v1`, `v2` and `v3`.\n\"\"\"\nfunction triangle_area(v1, v2, v3)\n    u1 = v2 - v1\n    u2 = v3 - v1\n\n    return abs(u1[1]*u2[2] - u1[2]*u2[1])/2\n\nend\n\n\"\"\"\n    isinsideconvex(p, vertices; tol=sqrt(eps()))\n\nDetermines if a point `p` is inside a convex region defined by the vertices in the array `vertices`.\n\"\"\"\nfunction isinsideconvex(p, vertices; tol=sqrt(eps()))\n    n = length(vertices)\n\n    center = [0.0, 0.0]\n    for i=1:n\n        center += vertices[i]\n    end\n    center = center/n\n\n    convex_area = 0.0\n    for i=1:n\n        convex_area += triangle_area(center, vertices[i], vertices[mod1(i+1,n)])\n    end\n\n    test_area = 0.0\n    for i=1:n\n        test_area += triangle_area(p, vertices[i], vertices[mod1(i+1,n)])\n    end\n\n    return isapprox(test_area, convex_area, rtol = tol)\nend\n", "meta": {"hexsha": "1e8649ebe2151cf9a539c44b388316277125532b", "size": 864, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/presets/geom2D_utils.jl", "max_stars_repo_name": "BacAmorim/TBHamiltonians.jl", "max_stars_repo_head_hexsha": "291776e87c0c7b49d53f764b66ed6df930ec18ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/presets/geom2D_utils.jl", "max_issues_repo_name": "BacAmorim/TBHamiltonians.jl", "max_issues_repo_head_hexsha": "291776e87c0c7b49d53f764b66ed6df930ec18ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/presets/geom2D_utils.jl", "max_forks_repo_name": "BacAmorim/TBHamiltonians.jl", "max_forks_repo_head_hexsha": "291776e87c0c7b49d53f764b66ed6df930ec18ff", "max_forks_repo_licenses": ["MIT"], "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": 100, "alphanum_fraction": 0.6111111111, "num_tokens": 286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305360354471, "lm_q2_score": 0.8991213840277783, "lm_q1q2_score": 0.86606117269801}}
{"text": "using Plots,DifferentialEquations,LaTeXStrings\r\n\r\n##\r\nV(x,y) = (1/2)*(x^2 + y^2 + 2*x^2*y - (2/3)*y^3)\r\nx1 = y1 = range(-1,stop = 1, length = 1000)\r\n\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\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_together.png\")\r\n\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\nplot()\r\ne = 0.0833\r\nfor y in -0.2:0.1:0.4\r\n    for ydot in -0.1:0.1:0.2\r\n        # y = 0.02\r\n        # ydot = -0.08\r\n        xdot = sqrt(2*e - ydot^2 - y^2 + (2//3)*y^3)\r\n        initial = [0.0,y,xdot,ydot]\r\n        tspan = (0,500.)\r\n        prob = ODEProblem(H\u00e9non_Heiles, initial, tspan)\r\n        sol = solve(prob, saveat = 0.001,Rodas5());\r\n        Y = [i[2] for i in sol.u if (abs(i[1]) < 9.e-4)];\r\n        Ydot = [i[4] for i in sol.u if (abs(i[1]) < 9.e-4)];\r\n        scatter!(Y,Ydot,xlabel = \"y\",ylabel = \"y\u0307\",label = false,title = \"Poincare section: E = $(e)\", titlefont=10,markersize = 2,markercolor = :black)\r\n    end\r\nend\r\nplot!()\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\ne = 0.125\r\ny = 0.02\r\nydot = -0.08\r\nxdot = sqrt(2*e - ydot^2 - y^2 + (2//3)*y^3)\r\ninitial = [0.0,y,xdot,ydot]\r\ntspan = (0,500.)\r\nprob = ODEProblem(H\u00e9non_Heiles, initial, tspan)\r\nsol = solve(prob, saveat = 0.001);\r\nplot(sol,vars = (1,2,4))\r\n\r\n##", "meta": {"hexsha": "6e6d02e6bcd8615a5cccc04e82b6427a362a3110", "size": 1658, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "HH.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.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.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": 25.5076923077, "max_line_length": 153, "alphanum_fraction": 0.4969843185, "num_tokens": 742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572777987970316, "lm_q2_score": 0.9046505273888291, "lm_q1q2_score": 0.8660018655393521}}
{"text": "function golden_method(f::Function, a::AbstractVector, b::AbstractVector;\n                       tol=eps()*10, maxit=1000)\n    \u03b11 = (3 - sqrt(5)) / 2\n    \u03b12 = 1 - \u03b11\n    d = b - a\n    x1 = a + \u03b11*d\n    x2 = a + \u03b12*d\n    s = ones(a)\n    f1 = f(x1)\n    f2 = f(x2)\n\n    d = \u03b11*\u03b12*d\n    it = 0\n\n    while any(d .> tol) && it < maxit\n        it += 1\n        i = f2 .> f1\n        x1[i] = x2[i]\n        f1[i] = f2[i]\n        d *= \u03b12\n        x2 = x1 + s.*(i- map(!, i)).*d\n        s = sign.(x2 .- x1)\n        f2 = f(x2)\n    end\n\n    it >= maxit && warn(\"`golden_method`: maximum iterations exceeded\")\n\n    i = f2 .> f1\n    x1[i] = x2[i]\n    f1[i] = f2[i]\n\n    x1, f1\nend\n\n# function golden_method(f::Function, a::AbstractVector, b::AbstractVector;\n#                        tol=eps()*10, maxit=1000)\n#     out_x = similar(a)\n#     out_f = similar(a)\n#     N = length(a)\n#     @inbounds for i=1:N\n#         out_x[i], out_f[i] = golden_method(f, a[i], b[i]; tol=tol, maxit=maxit)\n#     end\n#     out_x, out_f\n# end\n\n\"\"\"\nApplies Golden-section search to search for the _maximum_ of a function in\nthe interval (a, b)\n\nhttps://en.wikipedia.org/wiki/Golden-section_search\n\"\"\"\nfunction golden_method(f::Function, a::Real, b::Real; tol::Float64=10*eps(),\n                       maxit::Int=1000)\n    \u03b11 = (3 - sqrt(5)) / 2\n    \u03b12 = 1 - \u03b11\n    d = b - a\n    x1 = a + \u03b11*d\n    x2 = a + \u03b12*d\n    s = 1.0\n    f1 = f(x1)::Float64\n    f2 = f(x2)::Float64\n\n    d = \u03b11*\u03b12*d\n\n    it = 0\n\n    while d > tol && it < maxit\n        it += 1\n\n        d *= \u03b12\n\n        if f2 > f1\n            x1 = x2\n            f1 = f2\n            x2 = x1 + s*d\n        else\n            x2 = x1 - s*d\n        end\n\n        s = sign(x2 - x1)\n\n        f2 = f(x2)::Float64\n    end\n\n    it >= maxit && warn(\"`golden_method`: maximum iterations exceeded\")\n\n    if f2 > f1\n        x1 = x2\n        f1 = f2\n    end\n\n    x1, f1::Float64\nend\n", "meta": {"hexsha": "2977ed607836fc22fbe4bbc242ea0486b6fa3252", "size": 1881, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/optimization.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/optimization.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/optimization.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": 20.0106382979, "max_line_length": 81, "alphanum_fraction": 0.4625199362, "num_tokens": 699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377272885903, "lm_q2_score": 0.9032942021480235, "lm_q1q2_score": 0.8658415715999269}}
{"text": "#Generate 2D data from 4 spherical (\u03c3=0.25) gaussian clusters centered at [-1,1], [1,-1], [-1,1] and [1,1]\n\"\"\"\n    generate_4_clusters(npts_per_cluster; \u03c3=0.25)\n    generate_4_clusters(::DataType, npts_per_cluster; \u03c3=0.25)\n\nGenerate 2D data from 4 spherical gaussian clusters, with standard deviation `\u03c3`, centered at [-1,1], [1,-1], [-1,1] and [1,1]. `DataType` can be `Float32` or `Float64`, default is `Float64`.\n\"\"\"\nfunction generate_4_clusters(T::DataType, npts_per_cluster; \u03c3 = 0.25)\n    c = convert(Matrix{T},[1 1 -1 -1; 1 -1 1 -1])\n    data = Matrix{T}(undef,2,4*npts_per_cluster)\n    for i \u2208 axes(c,2)\n        rpts = randn(T,(2,npts_per_cluster))\n        sindx = (i-1)*npts_per_cluster+1\n        eindx = i*npts_per_cluster\n        data[:,sindx:eindx] = \u03c3*rpts .+ c[:,i]\n    end\n    return data\nend\n\ngenerate_4_clusters(npts_per_cluster; \u03c3 = 0.25) = generate_4_clusters(Float64, npts_per_cluster; \u03c3)\n\n\n#Generate 2D data arranged in a circle (default radius, r =0.5) around centres at [-1,1], [1,-1], [-1,1] and [1,1]\n\"\"\"\n    generate_4_circle_clusters(npts_per_cluster = 8; r = 0.5)\n    generate_4_circle_clusters(::DataType, npts_per_cluster = 8; r = 0.5)\n\nGenerate 2D data arranged in a circle (default radius, r =0.5) around centres at [-1,1], [1,-1], [-1,1] and [1,1]. `DataType` can be `Float32` or `Float64`, default is `Float64`.\n\"\"\"\nfunction generate_4_circle_clusters(T::DataType, npts_per_cluster::Int = 8; r = 0.5)\n    c = convert(Matrix{T},[1 1 -1 -1; 1 -1 1 -1])\n    data = Matrix{T}(undef,2,4*npts_per_cluster)\n    for i \u2208 axes(c,2)\n        sindx = (i-1)*npts_per_cluster+1\n        eindx = i*npts_per_cluster\n        pts = generate_circle_cluster(T, npts_per_cluster)\n        data[:,sindx:eindx] = r*pts .+ c[:,i]\n    end\n    return data\nend\n\ngenerate_4_circle_clusters(npts_per_cluster::Int = 8; r = 0.5) = generate_4_circle_clusters(Float64, npts_per_cluster; r)\n\n\n#Generate 2D data arranged in a circle of radius one around [0,0]\n\"\"\"\n    generate_circle_cluster(npts = 8)\n    generate_circle_cluster(::DataType, npts = 8)\n\nGenerate 2D data arranged in a circle of radius one around [0,0]. `DataType` can be `Float32` or `Float64`, default is `Float64`.\n\"\"\"\nfunction generate_circle_cluster(T::DataType, npts::Int = 8)\n    \u0394\u03b8 = 2\u03c0/npts\n    \u03b8 = 0:\u0394\u03b8:2\u03c0-\u0394\u03b8\n    x = Matrix{T}(undef,2,npts)\n    for i \u2208 eachindex(\u03b8)\n        x[1,i] = cos(\u03b8[i])\n        x[2,i] = sin(\u03b8[i])\n    end\n    return x\nend\n\ngenerate_circle_cluster(npts::Int = 8) = generate_circle_cluster(Float64, npts)", "meta": {"hexsha": "54a755a565abe6e53b20f6d3de8c2c4c60b5d5cb", "size": 2495, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/toy_data.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/toy_data.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/toy_data.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": 39.6031746032, "max_line_length": 191, "alphanum_fraction": 0.6609218437, "num_tokens": 845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377237352755, "lm_q2_score": 0.90329420279886, "lm_q1q2_score": 0.8658415690140895}}
{"text": "\nA = [ 1. 2 3; 4 5 6; 7 8 9 ]\n\nB = [12 -51 4; 6 167 -68; -4 24 -41]\n\nfunction check_DV(A, D, V)\n    I = eye(size(A)[1])\n    for i = 1:size(A)[1]\n        check = (A - D[i] * I) * V[:,i]\n        println(\"For the \", i, \"th eigen value and vector, (A - lambda I)^k * v = \", check, \"\\n\\twhich has a L2 norm = \", norm(check))\n        assert(norm(check) <= 1e-14)\n    end\nend\n\nD_A, V_A = eig(A)\n\ncheck_DV(A, D_A, V_A)\n\nD_B, V_B = eig(B)\n\ncheck_DV(B, D_B, V_B)\n\n\"Power iteration method on A, to find eigenpair with largest eigen value.\"\nfunction poweriteration(A, maxiter=20, userandomstart=true)\n    n = size(A)[1]\n    if userandomstart\n        X = randn((n, 1))\n    else\n        X = ones((n, 1))\n    end\n    for i = 1:maxiter\n        next_X = A * X\n        X = next_X / norm(next_X)\n    end\n    # lambda = (X^* \u22c5 A \u22c5 X) / (X^* \u22c5 X)\n    lambda = (transpose(conj(X)) * (A * X)) / (transpose(conj(X)) * X)\n    lambda, X\nend\n\npoweriteration(A)\n\nD_A, V_A = eig(A)\n\n(D_A[1], -1 * V_A[:,1])\n\npoweriteration\n\nprintln(poweriteration(A, 1))\nprintln(poweriteration(A, 2))\nprintln(poweriteration(A, 5))\nprintln(poweriteration(A, 10))\n\n\"Inner product of two vectors v, w. Can be vertical (n,1) or horizontal (1,n) vectors.\"\nfunction inner(v, w)\n    assert(size(v) == size(w))\n    nm = size(v)\n    if length(nm) == 1\n        return transpose(conj(v)) * w\n    elseif nm[1] == 1\n        return conj(v) * transpose(w)\n    end\nend\n\ninner([1 1 1], [2 3 4])\n\ninner([1; 1; 1], [2; 3; 4])\n\n\"projection(a, e): projection operator of vector a onto base vector e. Uses inner(e, a) and inner(e, e).\"\nfunction projection(a, e)\n    return (inner(e, a) / inner(e, e)) * e \nend\n\n\"gramschmidt(A): Gram-Schmidt orthogonalization operator, returns us, es (unormalized matrix, base matrix).\"\nfunction gramschmidt(A, verbose=false)\n    assert(size(A)[1] == size(A)[2])\n    n = size(A)[1]\n    if verbose\n        println(\"n = \", n)\n    end\n    us = zeros((n, n))\n    es = zeros((n, n))\n    for i = 1:n\n        if verbose\n            println(\"i = \", i)\n        end\n        us[:,i] = A[:,i] \n        for j = 1:i-1\n            if verbose\n                println(\"\\tj = \", j)\n                println(\"\\tus[:,i] = \", us[:,i])\n            end\n            us[:,i] -= projection(A[:,i], us[:,j]) \n        end\n        if verbose\n            println(\"us[:,i] = \", us[:,i])\n        end\n        es[:,i] = us[:,i] / norm(us[:,i])\n        if verbose\n            println(\"es[:,i] = \", es[:,i])\n        end\n    end\n    return us, es\nend\n\nA\n\nus, es = gramschmidt(A)\n\nus\n\nes\n\ninner(es[:,1], A[:,1]) * es[:,1]\n\ninner(es[:,1], A[:,2]) * es[:,1] + inner(es[:,2], A[:,2]) * es[:,2]\n\nrank(A)\n\ninner(es[:,1], A[:,3]) * es[:,1] + inner(es[:,2], A[:,3]) * es[:,2] + inner(es[:,3], A[:,3]) * es[:,3]\n\n[ norm(es[:,i]) for i = 1:size(es)[1] ]\n\n(es' * es)[1:2,1:2]\n\nus, es = gramschmidt(B)\n\n[ norm(es[:,i]) for i = 1:size(es)[1] ]\n\nes * es'\n\nV = [3 2; 1 2]\n\nus, es = gramschmidt(V)\n\nes' * es\n\n\"QR decomposition, returns (Q, R): Q is orthogonal and R is upper-triangular, such that A = Q R.\"\nfunction QR(A)\n    assert(size(A)[1] == size(A)[2])\n    n = size(A)[1]\n    us, es = gramschmidt(A)\n    Q = copy(es)\n    R = zeros((n, n))\n    for i = 1:n\n        for j = i:n\n            R[i,j] = inner(es[:,i], A[:,j])\n        end\n    end\n    return Q, R\nend\n\nQ, R = QR(A)\n\nA\n\nQ\n\nR\n\nQ * R\n\nQ2, R2 = QR(B)\n\nB\n\nQ2\n\nR2\n\nQ2 * R2\n\nB == Q2 * R2\n\nassert(norm(B - (Q2 * R2)) <= 1e-13)\n\n\"Apply the QR method for maxiter steps. Should return a triangular matrix similar to A (same eigenvalues).\"\nfunction QR_method(A, maxiter=50)\n    Ak = A\n    for k = 1:maxiter\n        Qk, Rk = QR(Ak)\n        Ak = Rk * Qk\n    end\n    return Ak\nend\n\nAk = QR_method(A)\n\n\"Truncate to zero values under the diagonal (have to be smaller than tolerance)\"\nfunction truncate_to_zero_below_diag(A, tolerance=1e-12)\n    assert(size(A)[1] == size(A)[2])\n    n = size(A)[1]\n    for j = 1:n\n        for i = j+1:n\n            assert(norm(A[i,j]) <= tolerance)\n            A[i,j] = 0\n        end\n    end\n    return A\nend\n\ntruncate_to_zero_below_diag(Ak)\n\nAk = QR_method(B)\n\ntruncate_to_zero_below_diag(Ak)\n\n\"Extract the diagonal from the QR method.\"\nfunction QR_eigenvalues(A, maxiter=50)\n    return diag(QR_method(A, maxiter))\nend\n\nQR_eigenvalues(A)\n\neigvals(A)\n\nQR_eigenvalues(B)\n\neigvals(B)\n\n\"Inverse iteration method to find the eigen vector corresponding to a given eigen value.\"\nfunction inverseIteration(A, val, maxiter=20, userandomstart=true)\n    mu_I = val * eye(A)\n    inv_A_minus_muI = inv(A - mu_I)\n    n = size(A)[1]\n    if userandomstart\n        X = randn((n, 1))\n    else\n        X = ones((n, 1))\n    end\n    for i = 1:maxiter\n        next_X = inv_A_minus_muI * X\n        X = next_X / norm(next_X)\n    end\n    X\nend\n\n\"Approximation of D, V: D contains the eigen values (vector) and V the eigen vectors (column based).\"\nfunction QR_eigen(A, maxiter=20, userandomstart=true)\n    n = size(A)[1]\n    D = QR_eigenvalues(A, maxiter)\n    V = zeros((n,n))\n    for i = 1:n\n        V[:,i] = inverseIteration(A, D[i], maxiter, userandomstart)\n    end\n    return D, V\nend\n\nD2, V2 = QR_eigen(B)\n\nD2s, V2s = eig(B)\n", "meta": {"hexsha": "990b0bc6984ea1f9276bd0658b82779c6378e175", "size": 5095, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Algorithms_to_compute_eigen_values_and_eigen_vectors_in_Julia.jl", "max_stars_repo_name": "IEWbgfnYDwHRoRRSKtkdyMDUzgdwuBYgDKtDJWd/narnt", "max_stars_repo_head_hexsha": "0eda13a7b8663e218b4fe2e06a974b99db9ff166", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 102, "max_stars_repo_stars_event_min_datetime": "2016-06-25T09:30:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T21:02:49.000Z", "max_issues_repo_path": "Algorithms_to_compute_eigen_values_and_eigen_vectors_in_Julia.jl", "max_issues_repo_name": "operade/notebooks", "max_issues_repo_head_hexsha": "56f97e33e81b5e86905961b09184a41b7616fa90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34, "max_issues_repo_issues_event_min_datetime": "2016-06-26T12:21:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-06T09:19:49.000Z", "max_forks_repo_path": "Algorithms_to_compute_eigen_values_and_eigen_vectors_in_Julia.jl", "max_forks_repo_name": "operade/notebooks", "max_forks_repo_head_hexsha": "56f97e33e81b5e86905961b09184a41b7616fa90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 44, "max_forks_repo_forks_event_min_datetime": "2017-05-13T23:54:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-17T15:34:24.000Z", "avg_line_length": 20.2988047809, "max_line_length": 134, "alphanum_fraction": 0.5477919529, "num_tokens": 1754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172601537141, "lm_q2_score": 0.9124361688107864, "lm_q1q2_score": 0.8658264293730832}}
{"text": "using NumericalMethodsforEngineers\n\na = [1. 2. -2.; 2. 5. -4.; -2. -4. 5.]\n\nprintln(\"\\n|a[1, 1]| = $(det(a[1, 1]))\\n\")\nprintln(\"|a[1:2, 1:2]| = $(det(a[1:2, 1:2])))\\n\")\nprintln(\"|a| = $(det(a))\")\nprintln(\"\\nchol(a):\")\nchol(a) |> display\n\na = [16. 4. 8.; 4. 5. -4.; 8. -4. 22.]\n\nprintln(\"\\n|a[1, 1]| = $(det(a[1, 1]))\\n\")\nprintln(\"|a[1:2, 1:2]| = $(det(a[1:2, 1:2])))\\n\")\nprintln(\"|a| = $(det(a))\")\n\nprintln(\"\\nchol(a) - upper:\")\nupper = chol(a)\nupper |> display\n\nprintln(\"\\nchol(a) - lower:\")\nlower = chol(a)'\nlower |> display\n\nprintln(\"\\nlower * upper:\")\nlower * upper |> display\n\n@test a == lower * upper", "meta": {"hexsha": "554a7f62956a1dc53ef97f8be031f7c3d302ffca", "size": 606, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ch02/ex_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/ex_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/ex_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": 21.6428571429, "max_line_length": 49, "alphanum_fraction": 0.5148514851, "num_tokens": 266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214480969029, "lm_q2_score": 0.8976952880018481, "lm_q1q2_score": 0.8656668200757084}}
{"text": "module RandomTestMatrices\n\nexport randsym, randantisym, randposdef, randstable, randnormal, randorth, randunitary\n\n#=\n\nRandom test matrices. These are for testing and debugging purposes, for random matrix ensembles with known limiting distributions, see the package RandomMatrices.jl . \n\n=#\n\n\n\"\"\"\nrandsym(d)\n             \n\tGaussian random symmetric matrix of dimension ``d``.\n\"\"\"\t\nfunction randsym(d)\n    y = randn(d, d) \n\ttriu(y) + triu(y,1)' \nend\n\n\n\"\"\"\nrandantisym(d)\n\n    Anti symmetric matrix\n\"\"\"\nfunction randantisym(d)\n\ty = randn(d, d) \n\ttriu(y,1) - triu(y,1)' \nend\n\n\n\"\"\"\nrandposdef(d, n = d)\n             \n\tRandom positive definite matrix of dimension ``d`` from the Laguerre ensemble ``n``. \n\"\"\"\nfunction randposdef(d,n = d)\n\tx = randn(d, n) \n\tx'* x/n\nend\n\n\"\"\"\nrandstable(d)\n             \n\tRandom stable matrix (matrix with eigenvalues with negative real part) with dimension ``d``.\n\"\"\"\nfunction randstable(d)\n\t# positive definite matrix\n\tx = randn(d, d) \n\ta = x'*x/d \n\t\n\t# antisymmetric matrix\n\tb = randantisym(d)\n\t\n\t# return stable matrix\n\tb - a\nend\n\n\"\"\"\nrandunitary(d)\n             \n\tRandom unitary matrix of dimension ``d``.\n\"\"\"\t\nrandunitary(d) = expm(im* randposdef(d))\n\n\"\"\"\nrandorth(d)\n             \n\tOrthogonal matrix drawn according to the Haar measure on the group of orthogonal matrices.\n\"\"\"\t\nrandorth(d) = qr(randn(d,d))[1]\n\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\n\n\"\"\"\nrandnormal(d) \n             \n\tRandom normal matrix of dimension ``d``.\n\"\"\"\t\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, -beta) * Q\n\t\nend\n\nend # module\n", "meta": {"hexsha": "843315037005ecdd027d1bb3b401784c01616850", "size": 2270, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/RandomTestMatrices.jl", "max_stars_repo_name": "mschauer/RandomTestMatrices.jl", "max_stars_repo_head_hexsha": "ec57ed1f0c7a4fdc1fd208208c9c1efa66ca9c41", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/RandomTestMatrices.jl", "max_issues_repo_name": "mschauer/RandomTestMatrices.jl", "max_issues_repo_head_hexsha": "ec57ed1f0c7a4fdc1fd208208c9c1efa66ca9c41", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/RandomTestMatrices.jl", "max_forks_repo_name": "mschauer/RandomTestMatrices.jl", "max_forks_repo_head_hexsha": "ec57ed1f0c7a4fdc1fd208208c9c1efa66ca9c41", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:19:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:19:11.000Z", "avg_line_length": 18.3064516129, "max_line_length": 167, "alphanum_fraction": 0.5916299559, "num_tokens": 740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214460461697, "lm_q2_score": 0.8976952880018481, "lm_q1q2_score": 0.8656668182347749}}
{"text": "# # Factorizations and other fun\n# Based on work by Andreas Noack\n#\n# ## Outline\n#  - Factorizations\n#  - Special matrix structures\n#  - Generic linear algebra\n\n#-\n\n# Before we get started, let's set up a linear system and use `LinearAlgebra` to bring in the factorizations and special matrix structures.\n\nusing LinearAlgebra\nA = rand(3, 3)\nx = fill(1, (3,))\nb = A * x\n\n# ## Factorizations\n#\n# #### LU factorizations\n# In Julia we can perform an LU factorization\n# ```julia\n# PA = LU\n# ```\n# where `P` is a permutation matrix, `L` is lower triangular unit diagonal and `U` is upper triangular, using `lufact`.\n#\n# Julia allows computing the LU factorization and defines a composite factorization type for storing it.\n\nAlu = lu(A)\n\n#-\n\ntypeof(Alu)\n\n# The different parts of the factorization can be extracted by accessing their special properties\n\nAlu.P\n\n#-\n\nAlu.L\n\n#-\n\nAlu.U\n\n# Julia can dispatch methods on factorization objects.\n#\n# For example, we can solve the linear system using either the original matrix or the factorization object.\n\nA\\b\n\n#-\n\nAlu\\b\n\n# Similarly, we can calculate the determinant of `A` using either `A` or the factorization object\n\ndet(A) \u2248 det(Alu)\n\n# #### QR factorizations\n#\n# In Julia we can perform a QR factorization\n# ```\n# A=QR\n# ```\n#\n# where `Q` is unitary/orthogonal and `R` is upper triangular, using `qrfact`.\n\nAqr = qr(A)\n\n# Similarly to the LU factorization, the matrices `Q` and `R` can be extracted from the QR factorization object via\n\nAqr.Q\n\n#-\n\nAqr.R\n\n# #### Eigendecompositions\n\n#-\n\n# The results from eigendecompositions, singular value decompositions, Hessenberg factorizations, and Schur decompositions are all stored in `Factorization` types.\n#\n# The eigendecomposition can be computed\n\nAsym = A + A'\nAsymEig = eigen(Asym)\n\n# The values and the vectors can be extracted from the Eigen type by special indexing\n\nAsymEig.values\n\n#-\n\nAsymEig.vectors\n\n# Once again, when the factorization is stored in a type, we can dispatch on it and write specialized methods that exploit the properties of the factorization, e.g. that $A^{-1}=(V\\Lambda V^{-1})^{-1}=V\\Lambda^{-1}V^{-1}$.\n\ninv(AsymEig)*Asym\n\n# ## Special matrix structures\n# Matrix structure is very important in linear algebra. To see *how* important it is, let's work with a larger linear system\n\nn = 1000\nA = randn(n,n);\n\n# Julia can often infer special matrix structure\n\nAsym = A + A'\nissymmetric(Asym)\n\n# but sometimes floating point error might get in the way.\n\nAsym_noisy = copy(Asym)\nAsym_noisy[1,2] += 5eps()\n\n#-\n\nissymmetric(Asym_noisy)\n\n# Luckily we can declare structure explicitly with, for example, `Diagonal`, `Triangular`, `Symmetric`, `Hermitian`, `Tridiagonal` and `SymTridiagonal`.\n\nAsym_explicit = Symmetric(Asym_noisy);\n\n# Let's compare how long it takes Julia to compute the eigenvalues of `Asym`, `Asym_noisy`, and `Asym_explicit`\n\n@time eigvals(Asym);\n\n#-\n\n@time eigvals(Asym_noisy);\n\n#-\n\n@time eigvals(Asym_explicit);\n\n# In this example, using `Symmetric()` on `Asym_noisy` made our calculations about `5x` more efficient :)\n\n#-\n\n# #### A big problem\n# Using the `Tridiagonal` and `SymTridiagonal` types to store tridiagonal matrices makes it possible to work with potentially very large tridiagonal problems. The following problem would not be possible to solve on a laptop if the matrix had to be stored as a (dense) `Matrix` type.\n\nn = 1_000_000;\nA = SymTridiagonal(randn(n), randn(n-1));\n@time eigmax(A)\n\n# ## Generic linear algebra\n# The usual way of adding support for numerical linear algebra is by wrapping BLAS and LAPACK subroutines. For matrices with elements of `Float32`, `Float64`, `Complex{Float32}` or `Complex{Float64}` this is also what Julia does.\n#\n# However, Julia also supports generic linear algebra, allowing you to, for example, work with matrices and vectors of rational numbers.\n\n#-\n\n# #### Rational numbers\n# Julia has rational numbers built in. To construct a rational number, use double forward slashes:\n\n1//2\n\n# #### Example: Rational linear system of equations\n# The following example shows how linear system of equations with rational elements can be solved without promoting to floating point element types. Overflow can easily become a problem when working with rational numbers so we use `BigInt`s.\n\nArational = Matrix{Rational{BigInt}}(rand(1:10, 3, 3))/10\n\n#-\n\nx = fill(1, 3)\nb = Arational*x\n\n#-\n\nArational\\b\n\n#-\n\nlu(Arational)\n\n# ### Exercises\n#\n# #### 11.1\n# What are the eigenvalues of matrix A?\n#\n# ```\n# A =\n# [\n#  140   97   74  168  131\n#   97  106   89  131   36\n#   74   89  152  144   71\n#  168  131  144   54  142\n#  131   36   71  142   36\n# ]\n# ```\n# and assign it a variable `A_eigv`\n\nusing LinearAlgebra\n\n#-\n\n@assert A_eigv ==  [-128.49322764802145, -55.887784553056875, 42.7521672793189, 87.16111477514521, 542.4677301466143]\n\n# #### 11.2\n# Create a `Diagonal` matrix from the eigenvalues of `A`.\n\n@assert A_diag ==  [-128.493    0.0      0.0      0.0       0.0;\n    0.0    -55.8878   0.0      0.0       0.0;\n    0.0      0.0     42.7522   0.0       0.0;\n    0.0      0.0      0.0     87.1611    0.0;\n    0.0 0.0      0.0      0.0     542.468]\n## #### 11.3\n## Create a `LowerTriangular` matrix from `A` and store it in `A_lowertri`\n@assert A_lowertri ==  [140    0    0    0   0;\n  97  106    0    0   0;\n  74   89  152    0   0;\n 168  131  144   54   0;\n 131   36   71  142  36]\n\n", "meta": {"hexsha": "3deb2b2b6f4604f2cd6d055f55c785d46a13c577", "size": 5359, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Courses/Introduction to Julia/12.Factorizations-and-other-fun.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/12.Factorizations-and-other-fun.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/12.Factorizations-and-other-fun.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": 24.4703196347, "max_line_length": 282, "alphanum_fraction": 0.6909871245, "num_tokens": 1639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620556499868, "lm_q2_score": 0.9019206699387733, "lm_q1q2_score": 0.8656292362136504}}
{"text": "# Mld.jl\n\n\n###### mld #####\n\"\"\"\n    mld(v)\n\nCompute the Mean log deviation of a vector `v`.\n\n# Examples\n```julia\njulia> using Inequality\njulia> mld([8, 5, 1, 3, 5, 6, 7, 6, 3])\n0.1397460530936332\n```\n\"\"\"\nmld(v::AbstractVector{<:Real})::Float64 = log(Statistics.mean(v[v .!= 0])) - Statistics.mean(log.(v[v .!= 0]))\n\n\n###### weighted mld #####\n\"\"\"\n    mld(v, w)\n\nCompute the weighted Mean log deviation of a vector `v` 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> mld([8, 5, 1, 3, 5, 6, 7, 6, 3], collect(0.1:0.1:0.9))\n0.10375545537468206\n```\n\"\"\"\nfunction mld(v::AbstractVector{<:Real}, w::AbstractVector{<:Real})::Float64\n    checks_weights(v, w)\n    w = w[v .!= 0]\n    v = v[v .!= 0]\n\n    return -sum(w .* log.(v/mean(v, weights(w))) ) / sum(w)\nend\n\n\nfunction mld(v::AbstractVector{<:Real}, w::AbstractWeights)::Float64\n    checks_weights(v, w)\n    w = w[v .!= 0]\n    v = v[v .!= 0]\n\n    return -sum(w .* log.(v/mean(v, weights(w))))/ sum(w)\nend\n\n\n\"\"\"\n    wmld(v, w)\n\nCompute the Mean log deviationof `v` with weights `w`. See also [`mld`](@mld)\n\"\"\"\nwmld(v::AbstractVector{<:Real}, w::AbstractVector{<:Real}) = mld(v, w)\n\nwmld(v::AbstractVector{<:Real}, w::AbstractWeights) = mld(v, w)", "meta": {"hexsha": "6b78b5028bca0e1fc5cd0a3ccaa52cfc98be4a90", "size": 1340, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Mld.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/Mld.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/Mld.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": 22.3333333333, "max_line_length": 110, "alphanum_fraction": 0.6082089552, "num_tokens": 481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191297273498, "lm_q2_score": 0.9059898210180105, "lm_q1q2_score": 0.8655094073567632}}
{"text": "struct ODEProblem{F,T<:Tuple{Number,Number},U<:AbstractVector,P<:AbstractVector}\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::ODEProblem, u, t)\n    f, \u03b8, dt  = prob.f, prob.\u03b8, solver.dt\n    (u + dt*f(u,\u03b8), t+dt)\nend\n\n\nfunction solve(prob::ODEProblem, 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\n\n# Define & Solve ODE\n\nfunction lotkavolterra(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\n\u03b8 = [0.1,0.2,0.3,0.2]\nu0 = [1.0,1.0]\ntspan = (0.,100.)\nprob = ODEProblem(lotkavolterra,tspan,u0,\u03b8)\n\n", "meta": {"hexsha": "44617a12896699d62e2276b1d8429e2aec500b4a", "size": 831, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/lecture_12/lab-ode.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_12/lab-ode.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_12/lab-ode.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": 16.62, "max_line_length": 80, "alphanum_fraction": 0.5631768953, "num_tokens": 345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561712637256, "lm_q2_score": 0.893309411735131, "lm_q1q2_score": 0.8654883364075501}}
{"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\nchua(u0 = [0.7, 0.0, 0.0]; a = 15.6, b = 25.58, m0 = -8/7, m1 = -5/7)\n```\n```math\n\\\\begin{aligned}\n\\\\dot{x} &= \\\\alpha (y - h(x))\\\\\\\\\n\\\\dot{y} &= x - y+z \\\\\\\\\n\\\\dot{z} &= \\\\beta y\n\\\\end{aligned}\n```\nwhere h(x) is defined by\n```math\nh(x) = m_1 x + \\\\frac 1 2 (m_0 - m_1)(|x + 1| - |x - 1|)\n```\nThis is a 3D continuous system that exhibits chaos.\n\nChua designed an electronic circuit with the expressed goal of exhibiting\nchaotic motion, and this system is obtained by rescaling the circuit units\nto simplify the form of the equation. [1]\n\nThe parameters are a, b, m0 and m1. Setting a = 15.6, m0 = -8/7 and m1 = -5/7,\nand varying the parameter b from b = 25 to b = 51, one observes a classic\nperiod-doubling bifurcation route to chaos. [2]\n\nThe parameter container has the parameters in the same order as stated in this\nfunction's documentation string.\n\n[1] : Chua, Leon O. \"The genesis of Chua's circuit\", 1992.\n\n[2] : [Leon O. Chua (2007) \"Chua circuit\", Scholarpedia, 2(10):1488.](http://www.scholarpedia.org/article/Chua_circuit)\n\n\"\"\"\nfunction chua(u0 = [0.7, 0.0, 0.0]; a = 15.6, b = 25.58, m0 = -8/7, m1 = -5/7)\n    return CDS(chua_rule, u0, [a, b, m0, m1], chua_jacob)\nend\nfunction chua_rule(u, p, t)\n    @inbounds begin\n    a, b, m0, m1 = p\n    du1 = a * (u[2] - u[1] - chua_element(u[1], m0, m1))\n    du2 = u[1] - u[2] + u[3]\n    du3 = -b * u[2]\n    return SVector{3}(du1, du2, du3)\n    end\nend\nfunction chua_jacob(u, p, t)\n    a, b, m0, m1 = p\n    return @SMatrix[-a*(1 + chua_element_derivative(u[1], m0, m1)) a 0;\n                    1 -1 1;\n                    0 -b 0]\nend\n# Helper functions for Chua's circuit.\nfunction chua_element(x, m0, m1)\n    return m1 * x + 0.5 * (m0 - m1) * (abs(x + 1.0) - abs(x - 1.0))\nend\nfunction chua_element_derivative(x, m0, m1)\n    return m1 + 0.5 * (m0 - m1) * (-1 < x < 1 ? 2 : 0)\nend\n\n\n\n\"\"\"\n```julia\nroessler(u0=[1, -2, 0.1]; 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=[1, -2, 0.1]; a = 0.2, b = 0.2, c = 5.7)\n    return CDS(roessler_rule, u0, [a, b, c], roessler_jacob)\nend\nfunction roessler_rule(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}(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, 0.5];\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, 0.5]; G=10.0, L1 = 1.0, L2 = 1.0, M1 = 1.0, M2 = 1.0)\n    return CDS(doublependulum_rule, u0, [G, L1, L2, M1, M2])\nend\n@inbounds function doublependulum_rule(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] is a conservative dynamical system and 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.\nThe function `Systems.henonheiles_ics(E, n)` generates a grid of\n`n\u00d7n` initial conditions, all having the same energy `E`.\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    i = one(eltype(u0))\n    o = zero(eltype(u0))\n    J = zeros(eltype(u0), 4, 4)\n    return CDS(hhrule!, u0, nothing, hhjacob!, J)\nend\nfunction hhrule!(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_hhenergy(x,y,px,py) = 0.5(px^2 + py^2) + _hhpotential(x,y)\n_hhpotential(x, y) = 0.5(x^2 + y^2) + (x^2*y - (y^3)/3)\nfunction henonheiles_ics(E, n=10)\n    ys = range(-0.4, stop = 1.0, length = n)\n    pys = range(-0.5, stop = 0.5, length = n)\n    ics = Vector{Vector{Float64}}()\n    for y in ys\n        V = _hhpotential(0.0, y)\n        V \u2265 E && continue\n        for py in pys\n            Ky = 0.5*(py^2)\n            Ky + V \u2265 E && continue\n            px = sqrt(2(E - V - Ky))\n            ic = [0.0, y, px, py]\n            push!(ics, [0.0, y, px, py])\n        end\n    end\n    return ics\nend\n\n\n\"\"\"\n    qbh([u0]; A=1.0, B=0.55, D=0.4)\n\nA conservative dynamical system with rule\n```math\n\\\\begin{aligned}\n\\\\dot{q}_0 &= A p_0 \\\\\\\\\n\\\\dot{q}_2 &= A p_2 \\\\\\\\\n\\\\dot{p}_0 &= -A q_0 -3 \\\\frac{B}{\\\\sqrt{2}} (q_2^2 - q_1^2) - D q_1 (q_1^2 + q_2^2) \\\\\\\\\n\\\\dot{p}_2 &= -q_2 (A + 3\\\\sqrt{2} B q_1 + D (q_1^2 + q_2^2)) (x^2 - y^2)\n\\\\end{aligned}\n```\n\nThis dynamical rule corresponds to a Hamiltonian used in nuclear\nphysics to study the quadrupole vibrations of the nuclear surface [1,2].\n\n```math\nH(p_0, p_2, q_0, q_2) = \\\\frac{A}{2}\\\\left(p_0^2+p_2^2\\\\right)+\\\\frac{A}{2}\\\\left(q_0^2+q_2^2\\\\right)\n\t\t\t +\\\\frac{B}{\\\\sqrt{2}}q_0\\\\left(3q_2^2-q_0^2\\\\right) +\\\\frac{D}{4}\\\\left(q_0^2+q_2^2\\\\right)^2\n```\n\nThe Hamiltonian has a similar structure with the Henon-Heiles one, but it has an added fourth order term\nand presents a nontrivial dependence of chaoticity with the increase of energy [3].\nThe default initial condition is chaotic.\n\n[1]: Eisenberg, J.M., & Greiner, W., Nuclear theory 2 rev ed. Netherlands: North-Holland pp 80 (1975)\n\n[2]: Baran V. and Raduta A. A., International Journal of Modern Physics E, **7**, pp 527--551 (1998)\n\n[3]: Micluta-Campeanu S., Raportaru M.C., Nicolin A.I., Baran V., Rom. Rep. Phys. **70**, pp 105 (2018)\n\"\"\"\nfunction qbh(u0=[0., -2.5830294658973876, 1.3873470962626937, -4.743416490252585];  A=1., B=0.55, D=0.4)\n    return CDS(qrule, u0, [A, B, D])\nend\nfunction qrule(z, p, t)\n    @inbounds begin\n        A, B, D = p\n        p\u2080, p\u2082 = z[1], z[2]\n        q\u2080, q\u2082 = z[3], z[4]\n\n        return SVector{4}(\n            -A * q\u2080 - 3 * B / \u221a2 * (q\u2082^2 - q\u2080^2) - D * q\u2080 * (q\u2080^2 + q\u2082^2),\n            -q\u2082 * (A + 3 * \u221a2 * B * q\u2080 + D * (q\u2080^2 + q\u2082^2)),\n            A * p\u2080,\n            A * p\u2082\n        )\n    end\nend\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 = range(0; length = N, step = 0.1); 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 = [0.1, 0.25]; \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 = [0.1, 0.25]; \u03c9 = 2.2, f = 27.0, d = 0.2, \u03b2 = 1)\n    J = zeros(eltype(u0), 2, 2)\n    J[1,2] = 1\n    return CDS(duffing_rule, u0, [\u03c9, f, d, \u03b2], duffing_jacob, J)\nend\n@inbounds function duffing_rule(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(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_rule(::Type{Val{:jac}}, J, u, p, t) = (shi::Shinriki)(t, u, J)\n    return CDS(shinriki_rule, u0, [R1])\nend\nshinriki_voltage(V) = 2.295e-5*(exp(3.0038*V) - exp(-3.0038*V))\nfunction shinriki_rule(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 = [3, 0.5, 1.5]; \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 = [3, 0.5, 1.5]; \u03bc = 0.119, \u03bd = 0.1, \u0393 = 0.9)\n    return CDS(gissinger_rule, u0, [\u03bc, \u03bd, \u0393], gissinger_jacob)\nend\nfunction gissinger_rule(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\nfunction gissinger_jacob(u, p, t)\n    \u03bc, \u03bd, \u0393 = p\n    return @SMatrix [\u03bc -u[3] -u[2];\n                     u[3] -\u03bd u[1];\n                     u[2] u[1] -1]\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{z} &= 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_rule, u0, [\u03bc, \u03b1], rikitake_jacob)\nend\nfunction rikitake_rule(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\nfunction rikitake_jacob(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 @SMatrix [-\u03bc  z  y;\n                     z-\u03b1 -\u03bc x;\n                     -y  -x 0]\nend\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{z} &= 1 - y^2\n\\\\end{aligned}\n```\nThree dimensional conservative continuous system, discovered in 1984 during\ninvestigations in thermodynamical chemistry by Nos\u00e9 and Hoover, then\nrediscovered by Sprott during an exhaustive search as an extremely simple\nchaotic system. [1]\n\nSee Chapter 4 of \"Elegant Chaos\" by J. C. Sprott. [2]\n\n[1] : Hoover, W. G. (1995). Remark on \u2018\u2018Some simple chaotic flows\u2019\u2019. *Physical Review E*, *51*(1), 759.\n\n[2] : Sprott, J. C. (2010). *Elegant chaos: algebraically simple chaotic flows*. World Scientific.\n\"\"\"\nnosehoover(u0 = [0, 0.1, 0]) = CDS(nosehoover_rule, u0, nothing, nosehoover_jacob)\nfunction nosehoover_rule(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\nfunction nosehoover_jacob(u, p, t)\n    x,y,z = u\n    return @SMatrix [0 1 0;\n                     -1 z y;\n                     0 2y 0]\nend\n\n\"\"\"\n    antidots([u]; B = 1.0, d0 = 0.3, c = 0.2)\nAn antidot \"superlattice\" is a Hamiltonian system that corresponds to a\nsmoothened periodic Sinai billiard with disk diameter `d0` and smooth\nfactor `c` [1].\n\nThis version is the two dimensional\nclassical form of the system, with quadratic dynamical rule and\na perpendicular magnetic field. Notice that the dynamical rule\nis with respect to the velocity instead of momentum, i.e.:\n```math\n\\\\begin{aligned}\n\\\\dot{x} &= v_x \\\\\\\\\n\\\\dot{y} &= v_y \\\\\\\\\n\\\\dot{v_x} &= B*v_y - U_x \\\\\\\\\n\\\\dot{v_y} &= -B*v_x - U_X \\\\\\\\\n\\\\end{aligned}\n```\nwith ``U`` the potential energy:\n```math\nU = \\\\left(\\\\tfrac{1}{c^4}\\\\right) \\\\left[\\\\tfrac{d_0}{2} + c - r_a\\\\right]^4\n```\nif ``r_a = \\\\sqrt{(x \\\\mod 1)^2 + (y \\\\mod 1)^2} < \\\\frac{d_0}{2} + c`` and 0\notherwise. I.e. the potential is periodic with period 1 in both ``x, y`` and\nnormalized such that for energy value of 1 it is a circle of diameter ``d0``.\nThe magnetic field is also normalized such that for value `B=1` the cyclotron\ndiameter is 1.\n\n[1] : G. Datseris *et al*, [New Journal of Physics 2019](https://iopscience.iop.org/article/10.1088/1367-2630/ab19cc/meta)\n\"\"\"\nfunction antidots(u0 = [0.5, 0.5, 0.25, 0.25];\n    d0 = 0.5, c = 0.2, B = 1.0)\n    return CDS(antidot_rule, u0, [B, d0, c], antidot_jacob)\nend\n\nfunction antidot_rule(u, p, t)\n    B, d0, c = p\n    x, y, vx, vy = u\n    # Calculate quadrant of (x,y):\n    U = Uy = Ux = 0.0\n    xtilde = x - round(x);  ytilde = y - round(y)\n    \u03c1 = sqrt(xtilde^2 + ytilde^2)\n    # Calculate derivatives and potential:\n    if \u03c1 < 0.5*d0 + c\n        sharedfactor = -(4*(c + d0/2 - \u03c1)^(3))/(c^4*\u03c1)\n        Ux = sharedfactor*xtilde # derivatives\n        Uy = sharedfactor*ytilde\n    end\n    Br = 2*\u221a(2)*B # magnetic field with prefactor\n    return SVector{4}(vx, vy, Br*vy - Ux, -vx*Br - Uy)\nend\nfunction antidot_jacob(u, p, t)\n    B, d0, c = p\n    x, y, vx, vy = u\n    xtilde = x - round(x);  ytilde = y - round(y)\n    \u03c1 = sqrt(xtilde^2 + ytilde^2)\n    # Calculate derivatives and potential:\n    if \u03c1 < 0.5*d0 + c\n        Uxx, Uyy, Uxy = antidot_secondderv(xtilde, ytilde, p)\n    else\n        Uxx, Uyy, Uxy = 0.0, 0.0, 0.0\n    end\n    Br = 2*\u221a(2)*B # magnetic field with prefactor\n    return SMatrix{4, 4}(0.0, 0, -Uxx, -Uxy, 0, 0, -Uxy, -Uyy,\n                         1, 0, 0, -Br,        0, 1, Br, 0)\nend\n\nfunction antidot_potential(x::Real, y::Real, p)\n    B, d0, c = p\n    \u03b4 = 4\n    # Calculate quadrant of (x,y):\n    xtilde = x - round(x);  ytilde = y - round(y)\n    \u03c1 = sqrt(xtilde^2 + ytilde^2)\n    # Check distance:\n    pot = \u03c1 > 0.5*d0 + c ? 0.0 : (1/(c^\u03b4))*(0.5*d0 + c - \u03c1)^\u03b4\nend\n\nfunction antidot_secondderv(x, y, p)\n    B, d0, c = p\n    r = sqrt(x^2 + y^2)\n    Uxx = _Uxx(x, y, c, d0, r)\n    Uyy = _Uxx(y, x, c, d0, r)\n    Uxy =  (2c + d0 - 2r)^2 * (2c + d0 + 4r)*x*y / (2c^4*r^3)\n    return Uxx, Uyy, Uxy\nend\n\nfunction _Uxx(x, y, c, d0, r)\n    Uxx =  (2c + d0 - 2r)^2 * (-2c*y^2 - d0*y^2 + 2*r*(3x^2 + y^2)) /\n    (2 * (c^4) * r^3)\nend\n\n\"\"\"\n```julia\nueda(u0 = [3.0, 0]; k = 0.1, B = 12.0)\n```\n```math\n\\\\ddot{x} + k \\\\dot{x} + x^3 = B\\\\cos{t}\n```\nNonautonomous Duffing-like forced oscillation system, discovered by Ueda in\n1961. It is one of the first chaotic systems to be discovered.\n\nThe stroboscopic plot in the (x, \u0307x) plane with period 2\u03c0 creates a \"broken-egg\nattractor\" for k = 0.1 and B = 12. Figure 5 of [1] is reproduced by\n\n```julia\nusing Plots\nds = Systems.ueda()\na = trajectory(ds, 2\u03c0*5e3, dt = 2\u03c0)\nscatter(a[:, 1], a[:, 2], markersize = 0.5, title=\"Ueda attractor\")\n```\n\nFor more forced oscillation systems, see Chapter 2 of \"Elegant Chaos\" by\nJ. C. Sprott. [2]\n\n[1] : [Ruelle, David, \u2018Strange Attractors\u2019, The Mathematical Intelligencer, 2.3 (1980), 126\u201337](https://doi.org/10/dkfd3n)\n\n[2] : Sprott, J. C. (2010). *Elegant chaos: algebraically simple chaotic flows*. World Scientific.\n\"\"\"\nfunction ueda(u0 = [3.0, 0]; k = 0.1, B = 12.0)\n    return CDS(ueda_rule, u0, [k, B], ueda_jacob)\nend\nfunction ueda_rule(u, p, t)\n    x,y = u\n    k, B = p\n    xdot = y\n    ydot = B*cos(t) - k*y - x^3\n    return SVector{2}(xdot, ydot)\nend\nfunction ueda_jacob(u, p, t)\n    x,y = u\n    k, B = p\n    return @SMatrix [0      1;\n                     -3*x^2 -k]\nend\n\n\nstruct MagneticPendulum\n    magnets::Vector{SVector{2, Float64}}\nend\nmutable struct MagneticPendulumParams\n    \u03b3s::Vector{Float64}\n    d::Float64\n    \u03b1::Float64\n    \u03c9::Float64\nend\n\nfunction (m::MagneticPendulum)(u, p, t)\n    x, y, vx, vy = u\n    \u03b3s::Vector{Float64}, d::Float64, \u03b1::Float64, \u03c9::Float64 = p.\u03b3s, p.d, p.\u03b1, p.\u03c9\n    dx, dy = vx, vy\n    dvx, dvy = @. -\u03c9^2*(x, y) - \u03b1*(vx, vy)\n    for (i, ma) in enumerate(m.magnets)\n        \u03b4x, \u03b4y = (x - ma[1]), (y - ma[2])\n        D = sqrt(\u03b4x^2 + \u03b4y^2 + d^2)\n        dvx -= \u03b3s[i]*(x - ma[1])/D^3\n        dvy -= \u03b3s[i]*(y - ma[2])/D^3\n    end\n    return SVector(dx, dy, dvx, dvy)\nend\n\n\"\"\"\n    magnetic_pendulum(u=[0.7,0.7,0,0]; d=0.3, \u03b1=0.2, \u03c9=0.5, N=3, \u03b3s=fill(1.0,N))\n\nCreate a pangetic pendulum with `N` magnetics, equally distributed along the unit circle,\nwith dynamical rule\n```math\n\\\\begin{aligned}\n\\\\ddot{x} &= -\\\\omega ^2x - \\\\alpha \\\\dot{x} - \\\\sum_{i=1}^N \\\\frac{\\\\gamma_i (x - x_i)}{D_i^3} \\\\\\\\\n\\\\ddot{y} &= -\\\\omega ^2y - \\\\alpha \\\\dot{y} - \\\\sum_{i=1}^N \\\\frac{\\\\gamma_i (y - y_i)}{D_i^3} \\\\\\\\\nD_i &= \\\\sqrt{(x-x_i)^2  + (y-y_i)^2 + d^2}\n\\\\end{aligned}\n```\nwhere \u03b1 is friction, \u03c9 is eigenfrequency, d is distance of pendulum from the magnet's plane\nand \u03b3 is the magnetic strength.\n\"\"\"\nfunction magnetic_pendulum(u = [sincos(0.12553*2\u03c0)..., 0, 0];\n    \u03b3 = 1.0, d = 0.3, \u03b1 = 0.2, \u03c9 = 0.5, N = 3, \u03b3s = fill(\u03b3, N))\n    m = MagneticPendulum([SVector(cos(2\u03c0*i/N), sin(2\u03c0*i/N)) for i in 1:N])\n    p = MagneticPendulumParams(\u03b3s, d, \u03b1, \u03c9)\n    ds = ContinuousDynamicalSystem(m, u, p)\nend\n\n\"\"\"\n    fitzhugh_nagumo(u = 0.5ones(2); a=3.0, b=0.2, \u03b5=0.01, I=0.0)\nFamous excitable system which emulates the firing of a neuron, with rule\n```math\n\\\\begin{aligned}\n\\\\dot{v} &= av(v-b)(1-v) - w + I \\\\\\\\\n\\\\ddot{w} &= \\\\varepsilon(v - w)\n\\\\end{aligned}\n```\n\nMore details in the [Scholarpedia](http://www.scholarpedia.org/article/FitzHugh-Nagumo_model) entry.\n\"\"\"\nfunction fitzhugh_nagumo(u = 0.5ones(2); a=3.0, b=0.2, \u03b5=0.01, I=0.0)\n    ds = ContinuousDynamicalSystem(fitzhugh_nagumo_rule, u, [a, b, \u03b5, I])\nend\nfunction fitzhugh_nagumo_rule(x, p, t)\n    u, w = x\n    a, b, \u03b5, I = p\n    return SVector(a*u*(u-b)*(1. - u) - w + I, \u03b5*(u - w))\nend\n\n\"\"\"\n    more_chaos_example(u = rand(3))\nA three dimensional chaotic system introduced in [^Sprott2020] with rule\n```math\n\\\\begin{aligned}\n\\\\dot{x} &= y \\\\\\\\\n\\\\dot{y} &= -x - sign(z)y \\\\\\\\\n\\\\dot{z} &= y^2 - \\\\exp(-x^2)\n\\\\end{aligned}\n```\nIt is noteworthy because its strange attractor is multifractal with fractal dimension \u2248 3.\n\n[^Sprott2020]: Sprott, J.C. 'Do We Need More Chaos Examples?', Chaos Theory and Applications 2(2),1-3, 2020\n\"\"\"\nmore_chaos_example(u = [0.0246, 0.79752, 0.3535866]) =\nContinuousDynamicalSystem(more_chaos_rule, u, nothing)\nfunction more_chaos_rule(u, p, t)\n    x, y, z = u\n    dx = y\n    dy = -x - sign(z)*y\n    dz = y^2 - exp(-x^2)\n    return SVector(dx, dy, dz)\nend\n\n\"\"\"\n    thomas_cyclical(u0 = [1.0, 0, 0]; b = 0.2)\n```math\n\\\\begin{aligned}\n\\\\dot{x} &= \\\\sin(y) - bx\\\\\\\\\n\\\\dot{y} &= \\\\sin(z) - by\\\\\\\\\n\\\\dot{z} &= \\\\sin(x) - bz\n\\\\end{aligned}\n```\nThomas' cyclically symmetric attractor is a 3D strange attractor originally proposed\nby Ren\u00e9 Thomas[^Thomas1999]. It has a simple form which is cyclically symmetric in the\nx,y, and z variables and can be viewed as the trajectory of a frictionally dampened\nparticle moving in a 3D lattice of forces.\nFor more see the [Wikipedia page](https://en.wikipedia.org/wiki/Thomas%27_cyclically_symmetric_attractor).\n\nReduces to the labyrinth system for `b=0`, see\nSee discussion in Section 4.4.3 of \"Elegant Chaos\" by J. C. Sprott.\n\n[^Thomas1999]: Thomas, R. (1999). *International Journal of Bifurcation and Chaos*, *9*(10), 1889-1905.\n\"\"\"\nthomas_cyclical(u0 = [1.0, 0, 0]; b = 0.2) = CDS(thomas_rule, u0, [b], thomas_jacob)\nlabyrinth(u0 = [1.0, 0, 0]) = CDS(thomas_rule, u0, [0.0], thomas_jacob)\n\nfunction thomas_rule(u, p, t)\n    x,y,z = u\n    b = p[1]\n    xdot = sin(y) - b*x\n    ydot = sin(z) - b*y\n    zdot = sin(x) - b*z\n    return SVector{3}(xdot, ydot, zdot)\nend\nfunction thomas_jacob(u, p, t)\n    x,y,z = u\n    b = p[1]\n    return @SMatrix [b cos(y) 0;\n                     0 b cos(z);\n                     cos(x) 0 b]\nend\n\n\"\"\"\n    stommel_thermohaline(u = [0.3, 0.2]; \u03b71 = 3.0, \u03b72 = 1, \u03b73 = 0.3)\nStommel's box model for Atlantic thermohaline circulation\n```math\n\\\\begin{aligned}\n \\\\dot{T} &= \\\\eta_1 - T - |T-S|\\\\cdot T \\\\\\\\\n \\\\dot{S} &= \\\\eta_2 - \\\\eta_3S - |T-S|\\\\cdot S\n\\\\end{aligned}\n```\nHere ``T, S`` are variables standing for dimensionless temperature and salinity\ndifferences between the boxes (polar and equitorial ocean basins) and ``\\\\eta_i``\nare parameters.\n\n[^Stommel1961]: Stommel, Thermohaline convection with two stable regimes offlow. Tellus, 13(2)\n\"\"\"\nfunction stommel_thermohaline(u = [0.3, 0.2]; \u03b71 = 3.0, \u03b72 = 1, \u03b73 = 0.3)\n    ds = ContinuousDynamicalSystem(stommel_thermohaline_rule, u, [\u03b71, \u03b72, \u03b73],\n    stommel_thermohaline_jacob)\nend\nfunction stommel_thermohaline_rule(x, p, t)\n    T, S = x\n    \u03b71, \u03b72, \u03b73 = p\n    q = abs(T-S)\n    return SVector(\u03b71 - T -q*T, \u03b72 - \u03b73*S - q*S)\nend\nfunction stommel_thermohaline_jacob(x, p, t)\n    T, S = x\n    \u03b71, \u03b72, \u03b73 = p\n    q = abs(T-S)\n    if T \u2265 S\n        return @SMatrix [(-1 - 2T + S)  (T);\n                         (-S)  (-\u03b73 - T + 2S)]\n    else\n        return @SMatrix [(-1 + 2T - S)  (-T);\n                         (+S)  (-\u03b73 + T - 2S)]\n    end\nend\n", "meta": {"hexsha": "c2691d9c717f109a7fb93dedeef7499ab19c2e94", "size": 25444, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/predefined/continuous_famous_systems.jl", "max_stars_repo_name": "navidcy/DynamicalSystemsBase.jl", "max_stars_repo_head_hexsha": "5e1cebad4dbcb1d9cdb39647fbd0bff5910b268d", "max_stars_repo_licenses": ["MIT"], "max_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/continuous_famous_systems.jl", "max_issues_repo_name": "navidcy/DynamicalSystemsBase.jl", "max_issues_repo_head_hexsha": "5e1cebad4dbcb1d9cdb39647fbd0bff5910b268d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/predefined/continuous_famous_systems.jl", "max_forks_repo_name": "navidcy/DynamicalSystemsBase.jl", "max_forks_repo_head_hexsha": "5e1cebad4dbcb1d9cdb39647fbd0bff5910b268d", "max_forks_repo_licenses": ["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.6185318893, "max_line_length": 122, "alphanum_fraction": 0.5776214432, "num_tokens": 10260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122684798184, "lm_q2_score": 0.9032942119105695, "lm_q1q2_score": 0.8652766076359434}}
{"text": "using Images, LinearAlgebra, Plots\n\nfunction low_rank_approx(x::SVD{T}, k) where T <: Real\n    #take a low rank (k) approx of the SVD of a matrix\n    #via outer products\n    return x.U[:, 1:k] * Diagonal(x.S[1:k]) * x.V[:, 1:k]'\nend\n\nimage_path = joinpath(dirname(@__DIR__), \"data/20210501_171236.jpg\")\n\nimg_big = load(image_path)\nimg = Images.imresize(img_big, ratio = 1/4)\n\nchannels = channelview(img)\nsvd_r = svd(channels[1,:,:])\nsvd_g = svd(channels[2,:,:])\nsvd_b = svd(channels[3,:,:])\n\np1 = plot(svd_r.S, c = :red, label = \"red singular values\")\nplot!(p1, svd_g.S, c = :green, label = \"green singular values\")\nplot!(p1, svd_b.S, c = :blue, label = \"blue singular values\")\n\n#recall trace norm identity\n\n# ||A||f  = \u221asum(\u03c3(A)^2)\n\n#Frobenius norm => Pretend matrix is big vector and take l2 norm\n# hints that truncated svd might contain a good representation on matrix\n\n#in case you don't trust me...\nnorm(channels[1,:,:]) \u2248 norm(svd_r.S)\nnorm(channels[2,:,:]) \u2248 norm(svd_g.S)\nnorm(channels[3,:,:]) \u2248 norm(svd_b.S)\n\napprox_error = [norm(low_rank_approx(svd_r, i) - channels[1,:,:]) for i = 1 :10: length(svd_r.S)]\n\np2 = plot(approx_error./norm(channels[1,:,:]))\n\n#what does it look like though...\n\nreconstructed_images = []\n\nfor k = 1:10:60\n    r_low = low_rank_approx(svd_r, k)\n    g_low = low_rank_approx(svd_g, k)\n    b_low = low_rank_approx(svd_b, k)\n    push!(reconstructed_images, colorview(RGB, r_low, g_low, b_low))\nend\n\noutput_plot = [plot(ri) for ri in reconstructed_images]\n\nplot(output_plot...)\n\n#So we can get a linear reduction in size by keeping the components of the \n#outer product U[:, 1:k], S[1:k], V[:, 1:k] and reconstructing via matrix \n#multiplication\n\n#So...\n\n@show sizeof(img_big)/1e6\n\n#So to get approx 1% reconstruction error in Frobenius norm we need about half the singular values\n\npercent_reduction_01 = findfirst(approx_error./norm(channels[1,:,:]) .< 0.01)/length(approx_error)\n\n@show percent_reduction_01\n\n#so the final \"saved\" image would be\n\n@show (sizeof(img_big)/1e6) * percent_reduction_01\n\n#not bad, but look at what jpeg gets...", "meta": {"hexsha": "20658d49afc703a2c55b53f88dada8c11ad73ee2", "size": 2071, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/fun_with_linear_algebra.jl", "max_stars_repo_name": "PaulBellette/Pauls_Silly_Test_Repo", "max_stars_repo_head_hexsha": "742d568a3fddade611365bda4a061bbf5e2e51b1", "max_stars_repo_licenses": ["MIT"], "max_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_with_linear_algebra.jl", "max_issues_repo_name": "PaulBellette/Pauls_Silly_Test_Repo", "max_issues_repo_head_hexsha": "742d568a3fddade611365bda4a061bbf5e2e51b1", "max_issues_repo_licenses": ["MIT"], "max_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_with_linear_algebra.jl", "max_forks_repo_name": "PaulBellette/Pauls_Silly_Test_Repo", "max_forks_repo_head_hexsha": "742d568a3fddade611365bda4a061bbf5e2e51b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7638888889, "max_line_length": 98, "alphanum_fraction": 0.6919362627, "num_tokens": 646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399043329856, "lm_q2_score": 0.8918110382493034, "lm_q1q2_score": 0.8652706564341047}}
{"text": "function linear_kernel(x1::Vector, x2::Vector)\n  return dot(x1, x2)::Float64\nend\n\nfunction polynomial_kernel(x1::Vector, x2::Vector, d::Integer=2)\n  return ((1 + dot(x1, x2)) ^ d)::Float64\nend\n\n# function gaussian_kernel(x1::Vector, x2::Vector, sigma::Real=1.0)\n#   # k = exp(-1/(2*sigma^2)  ||x1 - x2||^2 )\n#   return exp( -norm(x1 - x2)^2 / (2*sigma^2) )::Float64\n# end\n\nfunction gaussian_kernel(x1::Vector, x2::Vector, gamma::Real=1.0)\n  # k = exp(-gamma  ||x1 - x2||^2 )\n  return exp( -gamma * norm(x1 - x2)^2 )::Float64\nend\n", "meta": {"hexsha": "7f922554050551341a753f04e14deced1c175a70", "size": 529, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "kernel.jl", "max_stars_repo_name": "Koprvhdix/adversarial-multiclass", "max_stars_repo_head_hexsha": "5760e58332caffd8ac381d042be0f967ad3e4904", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 29, "max_stars_repo_stars_event_min_datetime": "2016-12-03T20:08:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-16T20:59:14.000Z", "max_issues_repo_path": "kernel.jl", "max_issues_repo_name": "Koprvhdix/adversarial-multiclass", "max_issues_repo_head_hexsha": "5760e58332caffd8ac381d042be0f967ad3e4904", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kernel.jl", "max_forks_repo_name": "Koprvhdix/adversarial-multiclass", "max_forks_repo_head_hexsha": "5760e58332caffd8ac381d042be0f967ad3e4904", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2016-12-04T18:26:05.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-11T02:08:15.000Z", "avg_line_length": 29.3888888889, "max_line_length": 67, "alphanum_fraction": 0.6313799622, "num_tokens": 205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.969785415552379, "lm_q2_score": 0.891811053345418, "lm_q1q2_score": 0.864865352962791}}
{"text": "\r\n\r\n\r\nmodule poly\r\nusing LinearAlgebra\r\n\r\n# Base.+ OK\r\n# Base.- OK\r\n# Base.* OK\r\n# degree OK\r\n# pow to a positive integer OK\r\n# eval OK\r\n# derivative OK\r\n# integrate OK\r\n# roots OK\r\n# create polynomial from roots OK\r\n\r\n\r\nstruct Polynomial{N, T}\r\n    coeff::NTuple{N, T}\r\n\r\n    function Polynomial{N, T}(coeff::NTuple{N, T}) where {N, T}\r\n        return new(coeff)\r\n    end\r\nend\r\n\r\nfunction Polynomial(coeff::AbstractArray{T}) where {T}\r\n    N = length(coeff)\r\n    t = tuple(coeff...)\r\n    return Polynomial{N, T}(t)\r\nend\r\n\r\nfunction Polynomial(coeff::Tuple)\r\n    t = promote(coeff...)\r\n    N = length(coeff)\r\n    T = eltype(t)\r\n    return Polynomial{N,T}(t)\r\n    # return Polynomial(t)\r\nend\r\n\r\nfunction Polynomial(coeff::T) where {T <: Number}\r\n    return Polynomial((coeff,))\r\nend\r\n\r\nfunction Base.eltype(p::Polynomial)\r\n    return eltype(p.coeff)\r\nend\r\n\r\nfunction degree(p::Polynomial)\r\n    return length(p.coeff)-1\r\nend\r\n\r\nfunction vector(p::Polynomial)\r\n    N = degree(p)+1\r\n    v = Vector{eltype(p)}(undef, N)\r\n    for ii = 1:N\r\n        v[ii] = p.coeff[ii]\r\n    end\r\n    return v\r\nend\r\n\r\nfunction Base.:+(p1::Polynomial, p2::Polynomial)\r\n    N1 = degree(p1)+1\r\n    N2 = degree(p2)+1\r\n    N3 = max(N1, N2)\r\n    T1 = eltype(p1)\r\n    T2 = eltype(p2)\r\n    T3 = promote_type(T1, T2)\r\n    \r\n    coeff = zeros(T3, N3)\r\n    for ii = 1:N1\r\n        coeff[ii] += p1.coeff[ii]\r\n    end\r\n    for ii = 1:N2\r\n        coeff[ii] += p2.coeff[ii]\r\n    end\r\n    \r\n    p3 = Polynomial(coeff)\r\n    return p3\r\nend\r\n\r\nfunction Base.:-(p1::Polynomial, p2::Polynomial)\r\n    N1 = degree(p1)+1\r\n    N2 = degree(p2)+1\r\n    N3 = max(N1, N2)\r\n    T1 = eltype(p1)\r\n    T2 = eltype(p2)\r\n    T3 = promote_type(T1, T2)\r\n    \r\n    coeff = zeros(T3, N3)\r\n    for ii = 1:N1\r\n        coeff[ii] += p1.coeff[ii]\r\n    end\r\n    for ii = 1:N2\r\n        coeff[ii] -= p2.coeff[ii]\r\n    end\r\n    \r\n    p3 = Polynomial(coeff)\r\n    return p3\r\nend\r\n\r\nfunction Base.:*(p1::Polynomial, p2::Polynomial)\r\n\r\n    d1 = degree(p1)\r\n    d2 = degree(p2)\r\n    N1 = d1 + 1\r\n    N2 = d2 + 1\r\n    T1 = eltype(p1)\r\n    T2 = eltype(p2)\r\n    T = promote_type(T1, T2)\r\n    N = d1 + d2 + 1\r\n    v = Vector{T}(undef, N)\r\n    \r\n    if N1 <= N2\r\n        v1 = p1.coeff\r\n        v2 = p2.coeff\r\n    else\r\n        v1 = p2.coeff\r\n        v2 = p1.coeff\r\n        N1, N2 = N2, N1\r\n    end\r\n     \r\n\r\n    for ii = 1:d1\r\n        sum = 0.0\r\n        for jj = 1:ii\r\n            sum += v1[ii - jj + 1] * v2[jj]\r\n        end\r\n        v[ii] = sum\r\n    end\r\n\r\n    for ii = N1:-1:2\r\n        sum = 0.0\r\n        for jj = ii:N1\r\n            sum += v1[jj] * v2[ii - jj + N2]\r\n        end\r\n        v[ii - N1 + N] = sum\r\n    end\r\n\r\n    for ii = N1:N2\r\n        sum = 0.0\r\n        for jj = 1:N1\r\n            sum += v1[N1 - jj + 1] * v2[jj + ii - N1]\r\n        end\r\n        v[ii] = sum\r\n    end\r\n\r\n    q = Polynomial(v)\r\n    return q\r\nend\r\n\r\nfunction Base.:^(p::Polynomial, n::Int)\r\n    if n < 0\r\n        error(\"This is not a polynomial any more\")\r\n    end\r\n    if n == 0\r\n        q = Polynomial(1.0)\r\n        return q\r\n    end\r\n\r\n    q = p\r\n    for ii = 1:(n-1)\r\n        q = q * p\r\n    end\r\n    return q\r\nend\r\n\r\nfunction integrate(p::Polynomial, C = 0.0)\r\n    # int x^m = x^(m+1) / (m+1)\r\n\r\n    v = [C, vector(p)...]\r\n\r\n    for ii = 2:length(v)\r\n        v[ii] /= ii - 1\r\n    end\r\n\r\n    q = Polynomial(v)\r\n    return q\r\nend\r\n\r\nfunction derivative(p::Polynomial)\r\n    # der x^m = m * x^(m-1)\r\n\r\n    v = vector(p)\r\n    v = v[2:end]\r\n    \r\n    for ii = eachindex(v)\r\n        v[ii] *= ii\r\n    end\r\n\r\n    q = Polynomial(v)\r\n    return q\r\nend\r\n\r\nfunction highest_nonzero_degree(p::Polynomial; abs_tol = 0.0, rel_tol = eps(1.0))\r\n    d = degree(p)\r\n    max_degree = 0\r\n    for ii = (d+1):-1:1\r\n        if !isapprox(p.coeff[ii], zero(eltype(p)), atol = abs_tol, rtol = rel_tol)\r\n            max_degree = ii - 1\r\n            break\r\n        end\r\n    end\r\n\r\n    return max_degree\r\nend\r\n\r\nfunction companion_matrix(p::Polynomial)\r\n    hd = highest_nonzero_degree(p)\r\n    m = zeros(hd, hd)\r\n    for ii = 1:(hd-1)\r\n        m[ii+1, ii] = 1.0\r\n    end\r\n    for ii = 1:hd\r\n        m[1, ii] = - p.coeff[hd + 1 - ii] / p.coeff[hd+1]\r\n    end\r\n\r\n    return m\r\nend\r\n\r\nfunction roots(p::Polynomial)\r\n    m = companion_matrix(p)\r\n    F = eigen(m)\r\n    z = F.values\r\n    return z\r\nend\r\n\r\nfunction poly_from_roots(roots::AbstractArray; make_real::Bool = true)\r\n    t = tuple(roots...)\r\n    return poly_from_roots(t; make_real = make_real)\r\nend\r\n\r\nfunction poly_from_roots(roots::Tuple; make_real::Bool = true)\r\n    L = length(roots)\r\n    q = Polynomial(1.0)\r\n    for ii = 1:L\r\n        p = Polynomial( (-roots[ii], one(eltype(roots[1]))) )\r\n        # q = q * p\r\n        q = p * q\r\n    end\r\n    if make_real\r\n        q_real_or_imag = Polynomial( map(real, q.coeff) )\r\n    else\r\n        q_real_or_imag = q\r\n    end\r\n    return q_real_or_imag\r\nend\r\n\r\n\r\nfunction poly_eval(p::Polynomial, x)\r\n    return poly_eval(x, p.coeff)\r\nend\r\n\r\nfunction (p::Polynomial)(x)\r\n    return poly_eval(p, x)\r\nend\r\n\r\nfunction poly_eval(x, a0, a1, a2, a3)\r\n    return ((a3 .* x .+ a2) .* x + a1) .* x .+ a0\r\nend\r\n\r\nfunction poly_eval(x, a0, a1, a2)\r\n    return (a2 .* x .+ a1) .* x + a0\r\nend\r\n\r\nfunction poly_eval(x, a0, a1)\r\n    return a1 .* x .+ a0\r\nend\r\n\r\n\r\nfunction poly_eval(x::AbstractArray, p)\r\n    # p array polynomial coeffiecents\r\n    # p[1] + p[2] * x + p[3] * x^2 + ...\r\n    y = zeros( length(x) )\r\n    np = length(p)\r\n    if np == 0\r\n        return y\r\n    end\r\n    if np == 1\r\n        # return y .* p[1]\r\n        return p[1] .* ones(np)\r\n    end\r\n\r\n    y .= p[np] \r\n    for ii = np:-1:2\r\n        y = y .* x .+ p[ii-1]\r\n    end\r\n\r\n    return y\r\nend\r\n\r\n\r\nfunction poly_eval(x::T, p) where {T <: Number}\r\n    y = zero(T)\r\n    np = length(p)\r\n    if np == 0\r\n        return y\r\n    end\r\n    if np == 1\r\n        return p[1]\r\n    end\r\n\r\n    y = p[np] \r\n    for ii = np:-1:2\r\n        y = y * x + p[ii-1]\r\n    end\r\n\r\n    return y\r\nend\r\n\r\n\r\nend\r\n\r\n\r\n\r\nmodule ptest\r\nusing ..poly\r\n\r\n# coeff = (1.0, 2.0, 3.0)\r\n# # t_coeff = tuple(map(Float64, v_coeff)...)\r\n\r\n# p_v = poly.Polynomial(v_coeff)\r\n# p_t = poly.Polynomial(t_coeff)\r\n\r\n\r\ncoeff = (1.0, 2.0, 3.0, 5.0)\r\np = poly.Polynomial(coeff)\r\nint_p = poly.integrate(p)\r\nder_p = poly.derivative(p)\r\n\r\ncoeff1 = (3.0, 2.0, 4.0)\r\np1 = poly.Polynomial(coeff1)\r\n\r\ncoeff2 = (5.0, 6.0, 3.0, 7.0)\r\np2 = poly.Polynomial(coeff2)\r\n\r\n# q = p1 * p2\r\n\r\n# p1_sq = p1^2\r\n# p2_sq = p2^2\r\n\r\n# z = poly.roots(p1)\r\n# q = poly.poly_from_roots(z)\r\n\r\nz = [-3.0, 1.0, 5.0, 2.0 - im, 2.0 + im]\r\nq = poly.poly_from_roots(z)\r\nz_c = poly.roots(q)\r\n\r\nend\r\n\r\n\r\n\r\n", "meta": {"hexsha": "4bbcf55f9ad559dd0c26dadc8e5db513a962a2f3", "size": 6532, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "__lib__/math/common/poly/src/poly_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/poly/src/poly_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/poly/src/poly_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": 18.5042492918, "max_line_length": 83, "alphanum_fraction": 0.5050520514, "num_tokens": 2220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104933824753, "lm_q2_score": 0.8947894541786198, "lm_q1q2_score": 0.8647339178861957}}
{"text": "#===============================================================================\n\nLet r be the remainder when (a\u22121)^n + (a+1)^n is divided by a^2.\n\nFor example, if a = 7 and n = 3, then r = 42: 6^3 + 8^3 = 728 \u2261 42 mod 49. And\nas n varies, so too will r, but for a = 7 it turns out that r_max = 42.\n\nFor 3 \u2264 a \u2264 1000, find \u2211 r_max.\n\n--------------------------------------------------------------------------------\n\nLet r(a,n) := ((a\u22121)^n + (a+1)^n) % a^2\nIt comes: r(a, n) = 0 for a=1 (because of the modulo 1)\n                  = 2 for n even\n                  = 2an % a^2 = a(2n % a) for n odd\n\n          max_n(2n % a) = a-1 if a is odd\n                        = a-2 if a is even\n\nThis max_n(r(a, n)) = 0 for a = 1\n                    = 2 for a = 2\n                    = a(a-1) for 3 <= a and a odd\n                    = a(a-2) for 3 <= a and a even\n\n===============================================================================#\n\nrmax(a) = isodd(a) ? a*(a-1) : a*(a-2) # It is assumed that a>=3\n\nfunction compute(limit)\n    result = 0\n    for a in 3:limit\n        result += rmax(a)\n    end\n    result;\nend\n\nprintln(\"Euler 120: $(compute(1000))\")\n", "meta": {"hexsha": "0b7e023d6fbf76c5d7d8d2d6c6e0d4222972160e", "size": 1151, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "0120.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": "0120.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": "0120.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": 30.2894736842, "max_line_length": 80, "alphanum_fraction": 0.3735881842, "num_tokens": 361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9728307661011976, "lm_q2_score": 0.888758786126321, "lm_q1q2_score": 0.8646118907864392}}
{"text": "# ------------------------------------------------------------------------------------------\n# # ModInt: a simple modular integer type\n# ------------------------------------------------------------------------------------------\n\nstruct ModInt{n} <: Integer\n    k::Int\n\n    # Constructor definition...\n    # note the left side looks like the call it defines\n    ModInt{n}(k::Int) where {n} = new(mod(k,n))\nend\n\na = ModInt{13}(1238279873492834)\n\nb = ModInt{13}(9872349827349827)\n\na + b\n\n# ------------------------------------------------------------------------------------------\n# To extend standard functions we need to import them.\n# ------------------------------------------------------------------------------------------\n\nimport Base: +\n\n+(a::ModInt{n}, b::ModInt{n}) where {n} = ModInt{n}(a.k + b.k)\n\na + b\n\nimport Base: *, -\n\n*(a::ModInt{n}, b::ModInt{n}) where{n} = ModInt{n}(a.k * b.k)\n-(a::ModInt{n}, b::ModInt{n}) where {n} = ModInt{n}(a.k - b.k)\n-(a::ModInt{n}) where {n} = ModInt{n}(-a.k)\n\na * b\n\na - b\n\n-b\n\nBase.show(io::IO, a::ModInt{n}) where {n} =\n    get(io, :compact, false) ? show(io, a.k) : print(io, \"$(a.k) mod $n\")\n\na\n\nb\n\na + 1\n\nBase.promote_rule(::Type{ModInt{n}}, ::Type{Int}) where {n} = ModInt{n}\n\nBase.convert(::Type{ModInt{n}}, x::Int) where {n} = ModInt{n}(x)\n\na + 1\n\n1 + a\n\nA = map(ModInt{13}, rand(1:100, 5, 5))\n\nA^100000000\n\n2A^100 .- 1\n\n# ------------------------------------------------------------------------------------------\n# ### Summary\n#\n# Here is all the code that defines the `ModInt` type:\n# ```jl\n# struct ModInt{n} <: Integer\n#     k::Int\n#\n#     # Constructor definition...\n#     # note the left side looks like the call it defines\n#     ModInt{n}(k::Int) where {n} = new(mod(k,n))\n# end\n#\n# import Base: +, *, -\n#\n# +(a::ModInt{n}, b::ModInt{n}) where {n} = ModInt{n}(a.k + b.k)\n# *(a::ModInt{n}, b::ModInt{n}) where{n} = ModInt{n}(a.k * b.k)\n# -(a::ModInt{n}, b::ModInt{n}) where {n} = ModInt{n}(a.k - b.k)\n# -(a::ModInt{n}) where {n} = ModInt{n}(-a.k)\n#\n# Base.show(io::IO, a::ModInt{n}) where {n} =\n#     get(io, :compact, false) ? show(io, a.k) : print(io, \"$(a.k) mod $n\")\n#\n# Base.promote_rule(::Type{ModInt{n}}, ::Type{Int}) where {n} = ModInt{n}\n# Base.convert(::Type{ModInt{n}}, x::Int) where {n} = ModInt{n}(x)\n# ```\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# ### Exercise\n#\n# Add two methods that allows operations between modular integers with different modulus\n# using the rule that they should combine in the modulus that is the `lcm` (least common\n# multiple) of the moduli of the arguments.\n#\n# **Hint:** try something, see what fails, define something to make that work.\n# ------------------------------------------------------------------------------------------\n\nx = ModInt{12}(9)\n\ny = ModInt{15}(13)\n\n# two method definitions here...\n\n@assert x + y == ModInt{60}(22)\n@assert x * y == ModInt{60}(57)\n", "meta": {"hexsha": "38f811ac0c7ecec5a57e9e88354c18a667146388", "size": 3015, "ext": "jl", "lang": "Julia", "max_stars_repo_path": ".nbexports/introductory-tutorials/intro-to-julia/long-version/140 ModInt.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/intro-to-julia/long-version/140 ModInt.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/intro-to-julia/long-version/140 ModInt.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": 27.4090909091, "max_line_length": 92, "alphanum_fraction": 0.4484245439, "num_tokens": 826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.942506726044381, "lm_q2_score": 0.9173026578901509, "lm_q1q2_score": 0.864563924879855}}
{"text": "module Utils\n\nfunction is_prime(n::Int)\n    if n == 2\n        return true\n    else\n        for i = 2:Int(ceil(sqrt(n)))\n            if n%i==0\n                return false\n            end\n        end\n        return true\n    end\nend\n\nfunction next_prime(n::Int)\n    i = n+1\n    while !is_prime(i)\n        i += 1\n    end\n    return i\nend\n\n# Prime number iterator.\nstruct Primes end\nBase.start(::Primes) = 2\nBase.next(P::Primes, state) = (state, next_prime(state))\nBase.done(P::Primes, state) = false\n\n\nfunction factorize(n::Int)\n    # Factorizes n = p1^(e1) * p2^(e2) * ... * pk^(ek)\n    # into array of tuples [(p1,e1),(p2,e2),...,(pk,ek)]\n    # We'll do this by iteratively dividing n by ever\n    # larger primes (and powers thereof) until n becomes 1, \n    # at which point we'll know factorization is complete.\n    factors = []\n\n    for prime in Primes()\n        if n % prime == 0 # We've found a factor\n            # Find the power to which the prime\n            # factor is raised by progressively dividing\n            # n by the factor until it no longer divides\n            # evenly.\n            power = 0\n            while n % prime == 0\n                n /= prime\n                power += 1\n            end\n            push!(factors, (prime, power))\n        end\n        if n == 1\n            break # We've fully factored n\n        end\n    end\n    return factors\nend\n\nend", "meta": {"hexsha": "b576b361b1240ab10ff5c82c95b57ead93116ba8", "size": 1377, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "PriceHardman/ProjectEuler.jl", "max_stars_repo_head_hexsha": "84c9bcc129d62a49874ed0e4b5b4c9ffa6535ab1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-01-27T01:58:17.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-27T01:58:17.000Z", "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "PriceHardman/ProjectEuler.jl", "max_issues_repo_head_hexsha": "84c9bcc129d62a49874ed0e4b5b4c9ffa6535ab1", "max_issues_repo_licenses": ["MIT"], "max_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": "PriceHardman/ProjectEuler.jl", "max_forks_repo_head_hexsha": "84c9bcc129d62a49874ed0e4b5b4c9ffa6535ab1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3389830508, "max_line_length": 60, "alphanum_fraction": 0.5301379811, "num_tokens": 380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338079816756, "lm_q2_score": 0.8991213759183765, "lm_q1q2_score": 0.8645356004245203}}
{"text": "\"\"\"\nSigmoid Activation function\n\"\"\"\nfunction sigmoid(Z::Array{BigFloat})\n    A = max.(min.(1 ./ (1 .+ exp.(.-Z)), 1-eps(1.0)), eps(1.0))\n    return (A = A, Z = Z)\nend # function\n\n\"\"\"\nReLU Activation function\n\"\"\"\nfunction relu(Z)\n    A = max.(0, Z)\n    return (A = A, Z = Z)\nend # function\n\n\"\"\"\nSoftmax Activation function\n\"\"\"\nfunction softmax(Z::Array{BigFloat})\n    A = max.(exp.(Z) ./ ( sum(exp.(Z))), eps(1.0))\n    return (A = A, Z = Z)\nend # function\n\n\"\"\"\nTanh Activation function\n\"\"\"\nfunction tanhact(Z::Array{BigFloat})\n    A = min.(max.(tanh.(Z), -1.0+eps(1.0)), 1.0-eps(1.0))\n    return (A = A, Z = Z)\nend # function\n\n\"\"\"\nSwish Activation function\n\"\"\"\nfunction swish(Z::Array{BigFloat})\n    #Z\u2081 = sigmoid(Z).A\n    #A = [Z[i] * Z\u2081[i] for i in 1:length(Z)]\n    A = Z .* sigmoid(Z).A\n    return (A = A, Z = Z)\nend # function\n\n\"\"\"\nGELU Activation function\n\"\"\"\nfunction gelu(Z)\n    A = 0.5 * Z * (1 + tanh( sqrt(pi / 2) * (Z + 0.044715 * Z^3) ))\n    return (A = A, Z = Z)\nend # function", "meta": {"hexsha": "e5394d4eb8e7b492c2256088d8059d57d10703b3", "size": 989, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "case_names/activation_functions.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/activation_functions.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/activation_functions.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": 20.1836734694, "max_line_length": 67, "alphanum_fraction": 0.5551061678, "num_tokens": 355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995752693051, "lm_q2_score": 0.8947894703109853, "lm_q1q2_score": 0.8642767693288272}}
{"text": "#= Given a number n, print its prime factorization. We could do it \nnormal way which will be having time complexity of O (sqrt(N)) \nbut we will be using Sieve to lessen the time complexity\nWe will make a sieve to get all the prime numbers and then get the \nprime factorization of the number using that.=#\n\n## Function\n\nfunction PrimeFactor(n)\n    a = zeros(Int64, n)\n    for i = 2:n\n        a[i] = i\n    end\n    for i = 2:n\n        if (a[i] == i)\n            for j = (i*i):i:n\n                if (a[j] == j)\n                    a[j] = i\n                end\n            end\n        end\n    end\n    while (n != 1)\n        println(a[n])\n        n = div(n, a[n])\n    end\nend\n\n## Input\n\nn = readline()\nn = parse(Int64, n)\n\n#Calling the function\n\nPrimeFactor(n)\n\n#=\nSample Test case\nInput:\n    n = 495\nOutput:\n    3 3 5 11\n\nTime Complexity: O( log N )\n=#", "meta": {"hexsha": "7f1db0a86f75494e7be0ebced6c56a45db4d906d", "size": 848, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/cp/Prime_factorization.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/cp/Prime_factorization.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/cp/Prime_factorization.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": 18.4347826087, "max_line_length": 67, "alphanum_fraction": 0.545990566, "num_tokens": 248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214511730026, "lm_q2_score": 0.8962513675912912, "lm_q1q2_score": 0.8642744194114221}}
{"text": "# Exercise 1\n\nfunction factorial2(n)\n    k=1\n    for i \u2208 1:n\n        k = k * i\n    end\n    return k\nend\n\nfactorial2(3)\n\n\n# Exercise 2\n\nfunction binomial_rv(n,p)\n    count = 0\n    U = rand(n)\n    for i \u2208 1:n\n        if U[i] < p\n            count += 1\n        end\n    end\n    return count\nend\n\nn=60\np=0.7\n\nbinomial_rv(n,p)\n\n\n# Exercise 3\n\nn = 10000\ncount = 0\n\nfor i \u2208 1:n\n    x, y = rand(2)\n    r = ((x-0.5)^2 + (y-0.5)^2)^(0.5) # distance from center of circle\n    if r < 0.5 # radius\n        count+=1\n    end\nend\n\npi_estimate = (count/n)/0.5^2\n\nprintln(\"Estimated pi = $pi_estimate\")\n\n# Exercise 4\n\nfunction flipcoin(n)\n    payoff = 0\n    count = 0\n    x = rand(n)\n    for i \u2208 eachindex(x)\n        if x[i] <= 0.5\n            count += 1\n        else\n            count = 0\n        end\n        print(count)\n        if count >= 3\n            payoff = 1\n        end\n    end\n    return (count,payoff)\nend\n\n# parameters\nn = 10\nflipcoin(n)\n\n# Exercise 5\n\n# parameters\nn = 200\n\u03b1 = 0.9\n\nx = zeros(n)\n\nfor i \u2208 1:n\n    x[i+1] = \u03b1 * x[i] + randn()\nend\nplot(x)\n\n\n# Exercise 6\n\n\u03b1s = [0.0, 0.8, 0.98]\nn = 200\np = plot() # naming a plot to add to\n\nfor \u03b1 in \u03b1s\n    x = zeros(n + 1)\n    x[1] = 0.0\n    for t in 1:n\n        x[t+1] = \u03b1 * x[t] + randn()\n    end\n    plot!(p, x, label = \"alpha = $\u03b1\") # add to plot p\nend\np # display plot\n\n\n# Exercise 7\nfunction firstpassage(threshold; tmax=100, \u03b1 = 1.0, \u03c3 =0.2)\n    x = zeros(tmax)\n    x[1] = 1.0\n    x[tmax] = 0.0\n    for i in 2:tmax\n        x[i] = \u03b1 * x[i-1] + \u03c3 * randn()\n        if x[i] < threshold # checks threshold\n            return i # leaves function, returning draw number\n        end\n    end\n    return tmax # if here, reached maxdraws\nend\n\n# parameters\ntmax = 200\n\u03c3 = 0.2\n\u03b1s = [0.8, 1.0, 1.2]\nthreshold = 0.0\n\n# sample using firstpassage\nnsamp = 100\naverages = zeros(0)\n\nfor \u03b1 \u2208 \u03b1s\n    draws = zeros(nsamp)\n    for i \u2208 1:100\n        draws[i] = firstpassage(threshold, tmax=tmax, \u03b1 = \u03b1, \u03c3 = \u03c3)\n    end\n    average = mean(draws)\n    push!(averages,average)\n#    histogram!(h, draws, labels = \"alpha = $\u03b1\", bins= 20) # add to histogram h\nend\naverages\n# h\n\n# Exercise 8a\n\nfunction f_prime(f; x0 = 2)\n\n    # intialise loop\n    crit = 1\n    iter = 1\n    del = 0.1\n    normdiff = Inf\n\n    fd_initial = (f(x0+del)-f(x0))/del\n    fd_old = fd_initial\n\n    while crit > 1.0E-8 && iter < 1000\n\n        del = del/2 # shrink change\n        fd_new = (f(x0+del)-f(x0))/del #calculate derivative\n\n        crit =  norm(fd_new - fd_old) #how large is the change in derivative?\n\n        # continuation\n        iter = iter + 1\n        fd_old = fd_new\n    end\n    return fd_old\nend\n\n# test with polynomial function\nf(x) = (x-1)^3\nx0 = 2\n\nderivative = f_prime(f,x0=2)\n\n# Newton Raphson algorithm\n\nfunction NewtonRaphson(f, f_prime; x0 = 2, tolerance =1.0E-8 , maxiter = 1000)\n\n    #initialise loop\n    iter = 1\n    normdiff = Inf\n\n    x_old = x0 # starting point\n    f_old = f(x0)\n\n    while normdiff > tolerance && iter < maxiter\n\n        fd = f_prime(f, x0 = x_old) # get derivative\n\n        step = f(x_old)/fd # compute step\n\n        x_new = x_old - step # compute expression to iterate over\n\n        normdiff = norm(x_new - x_old)# do we converge?\n\n        # continuation\n        iter = iter+1\n        x_old = x_new\n    end\n    return (root = x_old, normdiff = normdiff, iter = iter )\nend\n\n# peform Newton Raphson algorithm\nf(x) = (x-1)^3\nx0 = 2\n\nsol = NewtonRaphson(f,f_prime, x0 = x0, tolerance =1.0E-8 , maxiter = 1000 )\n\nprintln(\"root = $(sol.root), and |f(x) - x| = $(sol.normdiff) in $(sol.iter) iterations\")\n", "meta": {"hexsha": "88ba612372a9c4b4e48bf68f39910b9938a75fa1", "size": 3537, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "GettingStarted_IntroExamples.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_IntroExamples.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_IntroExamples.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": 16.9234449761, "max_line_length": 89, "alphanum_fraction": 0.5538592027, "num_tokens": 1281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632234212403, "lm_q2_score": 0.9073122251200418, "lm_q1q2_score": 0.863637139252261}}
{"text": "function falseposition(f::Function, xl::Number, xu::Number, ea::Number, maxIter::Int64)\n  # Estimate roots of functions using the false position method\n  xr = NaN; # Initial estimate of the root\n  fxu = f(xu);\n  fxl = f(xl);\n\n  for i = 1:maxIter \n    xrold = xr;\n    xr = xu - fxu*(xl-xu) / (fxl-fxu);\n    fxr = f(xr);\n    relativeError = abs((xr - xrold) / xr) * 100;\n\n    if fxr * fxl == 0\n      break;\n    elseif fxr * fxl > 0\n      xl = xr;\n      fxl = fxr;\n    else\n      xu = xr;\n      fxu = fxr;\n    end\n\n    if relativeError < ea\n      break;\n    end\n  end\n  return xr;\nend\n", "meta": {"hexsha": "1f19ace49e5d7bf682340ce32b88494bef75b7b1", "size": 582, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/Root Estimation/falseposition.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/falseposition.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/falseposition.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": 20.0689655172, "max_line_length": 87, "alphanum_fraction": 0.5515463918, "num_tokens": 205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9559813551535004, "lm_q2_score": 0.903294214513915, "lm_q1q2_score": 0.8635324272933291}}
{"text": "using Random, Distributions, NLsolve\nRandom.seed!(0)\n\na, b, c = 3, 5, 4\ndist = TriangularDist(a,b,c)\nn = 2000\nsamples = rand(dist,n)\n\nm_k(k,data) = 1/n*sum(data.^k)\nmHats = [m_k(i,samples) for i in 1:3]\n\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\nnlOutput = nlsolve(equations, [ 0.1; 0.1; 0.1])\nsol = sort(nlOutput.zero)\naHat, bHat, cHat = sol[1], sol[3], sol[2]\nprintln(\"Found estimates for (a,b,c) = \", (aHat, bHat, cHat) , \"\\n\" )\nprintln(nlOutput)", "meta": {"hexsha": "195ad5b8a5bb254340b47690e9df4c4667fd198b", "size": 743, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "5_chapter/parametersNumerical.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/parametersNumerical.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/parametersNumerical.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.72, "max_line_length": 72, "alphanum_fraction": 0.5181695828, "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9728307716151472, "lm_q2_score": 0.8872045877523147, "lm_q1q2_score": 0.8630999236835829}}
{"text": "\"\"\"\n    mean(nums)\n\nFind mean of a vector of numbers\n\n# Example\n\n```julia\nmean([3, 6, 9, 12, 15, 18, 21])      # returns 12.0\nmean([5, 10, 15, 20, 25, 30, 35])    # returns 20.0\nmean([1, 2, 3, 4, 5, 6, 7, 8])       # returns 4.5\n```\n\nContributed By:- [Ashwani Rathee](https://github.com/ashwani-rathee)\n\"\"\"\nfunction mean(nums)\n    return sum(nums) / length(nums)\nend\n", "meta": {"hexsha": "4961b0dded4032b9ec33fef5f129feb0cae5805c", "size": 367, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/average_mean.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/average_mean.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/average_mean.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": 19.3157894737, "max_line_length": 68, "alphanum_fraction": 0.583106267, "num_tokens": 154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9407897509188345, "lm_q2_score": 0.9173026607161, "lm_q1q2_score": 0.8629889416922839}}
{"text": "# This file is a part of SimilaritySearch.jl\n\nexport L1Distance, L2Distance, SqL2Distance, LInftyDistance, LpDistance\nimport Distances: evaluate\n\n\"\"\"\n    L1Distance()\n\nThe manhattan distance or ``L_1`` is defined as\n\n```math\nL_1(u, v) = \\\\sum_i{|u_i - v_i|}\n```\n\"\"\"\nstruct L1Distance <: PreMetric end\n\n\"\"\"\n    L2Distance()\n\nThe euclidean distance or ``L_2`` is defined as\n\n```math\nL_2(u, v) = \\\\sqrt{\\\\sum_i{(u_i - v_i)^2}}\n```\n\"\"\"\nstruct L2Distance <: PreMetric end\n\n\"\"\"\n    SqL2Distance()\n\nThe squared euclidean distance is defined as\n\n```math\nL_2(u, v) = \\\\sum_i{(u_i - v_i)^2}\n```\n\nIt avoids the computation of the square root and should be used\nwhenever you are able do it.\n\"\"\"\nstruct SqL2Distance <: PreMetric end\n\n\"\"\"\n    LInftyDistance()\n\nThe Chebyshev or ``L_{\\\\infty}`` distance is defined as\n\n```math\nL_{\\\\infty}(u, v) = \\\\max_i{\\\\left| u_i - v_i \\\\right|}\n```\n\n\"\"\"\nstruct LInftyDistance <: PreMetric end\n\n\"\"\"\n    LpDistance(p)\n    LpDistance(p, pinv)\n\nThe general Minkowski distance ``L_p`` distance is defined as\n\n```math\nL_p(u, v) = \\\\left|\\\\sum_i{(u_i - v_i)^p}\\\\right|^{1/p}\n```\n\nWhere ``p_{inv} = 1/p``. Note that you can specify unrelated `p` and `pinv` if you need an specific behaviour.\n\"\"\"\nstruct LpDistance <: PreMetric\n    p::Float32\n    pinv::Float32\nend\n\nLpDistance(p::Real) = LpDistance(p, 1/p)\n\n\n\"\"\"\n    evaluate(::L1Distance, a, b)\n\nComputes the Manhattan's distance between `a` and `b`\n\"\"\"\nfunction evaluate(::L1Distance, a, b)\n    d = zero(eltype(a))\n\n    @fastmath @inbounds @simd for i in eachindex(a)\n\t    m = a[i] - b[i]\n        d += ifelse(m > 0, m, -m)\n    end\n\n    d\nend\n\n\"\"\"\n    evaluate(::L2Distance, a, b)\n    \nComputes the Euclidean's distance betweem `a` and `b`\n\"\"\"\nfunction evaluate(::L2Distance, a, b)\n    d = zero(eltype(a))\n\n    @fastmath @inbounds @simd for i in eachindex(a)\n        d += (a[i] - b[i])^2 #m * m\n    end\n\n    sqrt(d)\nend\n\n\"\"\"\n    evaluate(::SqL2Distance, a, b)\n\nComputes the squared Euclidean's distance between `a` and `b`\n\"\"\"\nfunction evaluate(::SqL2Distance, a, b)\n    d = zero(eltype(a))\n\n    @fastmath @inbounds @simd for i in eachindex(a)\n        d += (a[i] - b[i])^2\n    end\n\n    d\nend\n\n\n\"\"\"\n    evaluate(::LInftyDistance, a, b)\n\nComputes the maximum distance or Chebyshev's distance\n\"\"\"\nfunction evaluate(::LInftyDistance, a, b)\n    d = zero(eltype(a))\n\n    @inbounds @simd for i in eachindex(a)\n        m = abs(a[i] - b[i])\n        d = max(d, m)\n    end\n\n    d\nend\n\n\"\"\"\n    evaluate(lp::LpDistance, a, b)\n\nComputes generic Minkowski's distance\n\"\"\"\nfunction evaluate(lp::LpDistance, a, b)\n    d = zero(eltype(a))\n\n    @inbounds @simd for i in eachindex(a)\n        m = abs(a[i] - b[i])\n        d += m ^ lp.p\n    end\n\n    d ^ lp.pinv\nend\n", "meta": {"hexsha": "9f811e4ea448dcd9d38d21e62917d4123872e1cc", "size": 2708, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distances/vectors.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/vectors.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/vectors.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": 17.8157894737, "max_line_length": 110, "alphanum_fraction": 0.6122599705, "num_tokens": 882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.964321452198369, "lm_q2_score": 0.8947894710123925, "lm_q1q2_score": 0.8628646820984807}}
{"text": "using Plots\n\"\"\"\n    newton(f, df)\n    newton(f, df, x0)\n    newton(f, df, x0, tol)\n\nFind roots of the noninear function `f` using Netwon's method.\n\n# Argument\n- `f::Function`: the nonlinear function.\n- `df::function`: the derivative of the nonlinear function.\n- `x0::Float64`: initial guess.\n- 'tol::Float64': error tolerance.\n\n# Example\n```julia-repl\njulia> newton(x->cos(x)-x, x->-sin(x)-1)\n```\n\"\"\"\nfunction newton(f::Function, df::Function, x0::Float64=1.0, tol::Float64=1e-7)\n    err = 1.0\n    it = 0\n    xp = x0\n    while err > tol\n        xc = x0 - f(xp)/df(xp)\n        err = abs(xc-xp)\n        xp = xc\n        it += 1\n    end\n    return xp, it\nend\n\n\"\"\"\n    secant(f)\n    secant(f, x0, x1)\n    secant(f, x0, x1, tol)\n\nFind roots of the noninear function `f` using secant method.\n\n# Argument\n- `f::Function`: the nonlinear function.\n- `x0::Float64`: the first initial guess.\n- `x1::Float64`: the second initial guess.\n- `tol::Float64`: error tolerance.\n\n# Example\n```julia-repl\njulia> secant(x->cos(x)-x)\n```\n\"\"\"\nfunction secant(f::Function, x0=1, x1 = 2, tol=1e-14)\n    err = 1.0\n    it = 0\n    xp1 = x1\n    xp2 = x0\n    while err > tol\n        xc = xp1 - f(xp1)*(xp1-xp2)/(f(xp1)-f(xp2))\n        err = abs(xp1-xc)\n        xp2 = xp1\n        xp1 = xc\n        it += 1\n    end\n    return xp1, it\nend\n\n\"\"\"\n    bisect(f, a, b)\n    bisect(f, a, b, tol)\n    bisect(f, a, b, tol, maxit)\n\nFind roots of the noninear function `f` using bisection.\n\n# Argument\n- `f::Function`: the nonlinear function.\n- `a::Float64`: the lower bound of the interval.\n- `b::Float64`: the upper bound of the interval.\n- `tol::Float64`: error tolerance.\n- `maxit::Int64`: maximum number of iteration.\n\n# Example\n```julia-repl\njulia> bisection(x->cos(x)-x, 0, pi)\n```\n\"\"\"\nfunction bisect(f::Function, a::Number, b::Number, tol=1e-7, maxit=100)\n    if b < a\n        error(\"the input of interval is not correct\")\n    end\n    if f(a)*f(b) > 0\n        error(\"You must give an input with difference sign\")\n    end\n    it = 0\n    while (b-a)>tol && it < maxit\n        c = (a+b)/2\n        if f(c) == 0 \n            return c\n        elseif f(a)*f(c) < 0\n            b = c\n        else\n            a = c\n        end\n        it += 1\n    end\n    return (a+b)/2, it\nend\n\n\"\"\"\n    fixedpoint(g, x0)\n    fixedpoint(g, x0, tol)\n    fixedpoint(g, x0, tol, maxit)\n\nFind roots of the noninear function `x=g(x)` using fixed point iteration.\n\n# Argument\n- `g::Function`: the fixed point function.\n- `x0::Float64`: the initial guess.\n- `tol::Float64`: error tolerance.\n- `maxit::Int64`: maximum number of iteration.\n\n# Example\n```julia-repl\njulia> fixedpoint(x->cos(x)-x, 0, pi)\n```\n\"\"\"\nfunction fixedpoint(g::Function, x0, tol=1e-15, maxIt=50)\n    it = 0\n    x1 = x0 + 1\n    while abs(x1-x0)>tol && it < maxIt\n        x1 = x0\n        x0 = g(x0)\n        it += 1\n    end\n    return x0, it\nend\n\n\"\"\"\n    cobweb(g, a, b, x0, N)\n\nGenerate the cobweb plot associated with the orbits x_n+1=g(x_n).\n\n# Argument\n- `g::Function`: the fixed point function.\n- `a::Float64`: the lower bound of the interval.\n- `b::Float64`: the upper bound of the interval.\n- `x0::Float64`: the initial guess.\n- `N::Int64`: the number of iteration.\n\n# Example\n```julia-repl\njulia> cobweb(x->cos(x), 0, pi, 1, 30)\n```\n\"\"\"\nfunction cobweb(g::Function,a,b,x0,N)\n    #generate N linearly space values on (a,b)\n    x = collect(range(a, b, length=N+1))\n    y = g.(x);\n    plot(x,y,linecolor=:black, legend = false)\n    plot!(x,x,linecolor=:black, legend = false)\n    x[1] = x0\n    #@gif for i in 1:N\n    anim = @animate  for i in 1:N\n        x[i+1] = g(x[i])\n        plot!([x[i]; x[i]], [x[i], x[i+1]], linecolor=:red,legend = false)\n        plot!([x[i]; x[i+1]], [x[i+1], x[i+1]], linecolor=:red,legend = false)\n    end\n    return anim\nend\n\n\"\"\"\n    viznewton(f, df, a, b, x0, N)\n\nVisualize the Newton's method for the nonlinear equation f(x)=0.\n\n# Argument\n- `f::Function`: the nonlinear function.\n- `df::function`: the derivative of the nonlinear function.\n- `a::Float64`: the lower bound of the interval.\n- `b::Float64`: the upper bound of the interval.\n- `x0::Float64`: the initial guess.\n- `N::Int64`: the number of iteration.\n\n# Example\n```julia-repl\njulia> cobweb(x->cos(x), 0, pi, 1, 30)\n```\n\"\"\"\nfunction viznewton(f::Function, df::Function, a,b,x0,N)\n    #generate N linearly space values on (a,b)\n    x = collect(range(a, b, length=N+1))\n    y = f.(x);\n    plot(x,y,linecolor=:black, legend = false)\n    plot!(x,zeros(N+1),linecolor=:black, legend = false)\n    x[1] = x0\n    #@gif for i in 1:N\n    anim = @animate  for i in 1:N\n        x[i+1] = x[i] - f(x[i])/df(x[i])\n        plot!([x[i]; x[i]], [0, f(x[i])], linecolor=:red,legend = false)\n        plot!([x[i]; x[i+1]], [f(x[i]), 0], linecolor=:red,legend = false)\n    end\n    return anim\nend\n\n\n\"\"\"\n    brent(f, a, b, tol, maxit)\n\nFind roots of the noninear function `f` using Brent algorithm\n\n# Argument\n- `f::Function`: the nonlinear function.\n- `a::Float64`: the lower bound of the interval.\n- `b::Float64`: the upper bound of the interval.\n- `tol::Float64`: error tolerance.\n- `maxit::Int64`: maximum number of iteration.\n\n# Example\n```julia-repl\njulia> brent(x->cos(x)-x, 0, pi)\n```\n\"\"\"\nfunction brent(f::Function, a::Float64, b::Float64, tol::Float64=1e-13)\n    if f(a)*f(b) >= 0.0\n        error(\"Error: the root is not bracket\")\n    end\n    if abs(f(a)) < abs(f(b))\n        a, b = b, a\n    end\n    c = a\n    d = c\n    mflag = 1\n    while abs(f(b)) > tol || abs(b-a) > tol\n        if ~isapprox(f(a), f(c)) && ~isapprox(f(b), f(c))\n            # inverse quadratic interpolation\n            s = a*f(b)*f(c)/(f(a)-f(b))/(f(a)-f(c)) -\n                b*f(a)*f(c)/(f(b)-f(a))/(f(b)-f(c)) -\n                c*f(a)*f(b)/(f(c)-f(a))/(f(c)-f(b))\n        else\n            # secan method\n            s = b - f(b)*(b-a)/(f(b)-f(a))\n        end\n        if (s > max((3a+b)/4, b) || s < min((3a+b)/4, b)) ||\n            ( mflag == 1 && abs(s-b) >= abs(b-c)/2.0) ||\n            ( mflag == 0 && abs(s-b) >= abs(c-d)/2.0) ||\n            ( mflag == 1 && abs(b-c) < tol) ||\n            ( mflag == 0 && abs(c-d) < tol) \n            s = (a+b)/2\n            mflag = 1\n        else\n            mflag = 0\n        end\n        d = c\n        c = b\n        if f(a)*f(s) < 0 \n            b = s\n        else \n            a = s\n        end\n        if abs(f(a)) < abs(f(b))\n            a, b = b, a\n        end\n    end\n    return b\nend", "meta": {"hexsha": "3d6f1a90e6704cf0a636df1f99b7d7eb2c1c7cd2", "size": 6385, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/rootfinding.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/rootfinding.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/rootfinding.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": 24.2775665399, "max_line_length": 78, "alphanum_fraction": 0.5407987471, "num_tokens": 2213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995742876885, "lm_q2_score": 0.8933094152856196, "lm_q1q2_score": 0.8628471839315639}}
{"text": "using DifferentialEquations\n\nf(u,t) = 0.98*u\nu0 = 1.0\ntspan = (0.0,5.0)\nprob = ODEProblem(f,u0,tspan)\nsol = solve(prob)\n\nusing Plots; gr()\nplot(sol)\n\n\n\nplot(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!\")\n\nplot!(sol.t,t->0.5*exp(1.01t),lw=3,ls=:dash,label=\"True Solution!\")\n\n\n###############\n# Solving system of Equaitons\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.0/3.0) * u[3]\nend\n\nu0 = [1.0;0.0;0.0]\ntspan = (0.0,1.0)\n\nprob = ODEProblem(lorenz,u0,tspan)\nsol = solve(prob)\nplot(sol , vars=[1,2,3])\n# animate(sol,lw=3,every=4)\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)\ngr()\nsol = solve(prob,vars=[1,2,3])\n\nusing StaticArrays\n\n#######################\nusing DiffEqOperators\n\norder = 2\nderiv = 2\n\n\u0394x =  0.1\nN = 9\nA = DerivativeOperator{Float64}(order,deriv,\u0394x,N,:Dirichlet0,:Dirichlet0)\n\nfull(DerivativeOperator{Float64}(order,deriv,\u0394x,N,:Dirichlet0,:Dirichlet0))\n", "meta": {"hexsha": "1e070cf813e9a8b29793654e4523a6fd810dc20b", "size": 1191, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Missing around and learning DifferentialEquations.jl/Juliacon_2017_code.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/Juliacon_2017_code.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/Juliacon_2017_code.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": 19.5245901639, "max_line_length": 75, "alphanum_fraction": 0.5927791772, "num_tokens": 525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314624993576758, "lm_q2_score": 0.9263037241905732, "lm_q1q2_score": 0.8628171820988745}}
{"text": "module ActivationFunctions\n\nexport sigmoid, relu, softmax\n\n\"\"\"\n    sigmoid(x)\n\nComputes the sigmoid activation of scalar `x`, returning a scalar.\n\"\"\"\nsigmoid(x::Number)::Number = (1.0 + exp(-x))^(-1)\n\n\"\"\"\n    sigmoid(x)\n\nComputes the sigmoid activation of vector `x`, returning a vector.\n\"\"\"\nsigmoid(x::AbstractVector{<:Number})::AbstractVector{<:Number} = sigmoid.(x)\n\n\"\"\"\n    relu(x)\n\nComputes the rectified linear unit activation of scalar `x`, returning a scalar.\n\"\"\"\nrelu(x::Number)::Number = max(0.0, x)\n\n\"\"\"\n    relu(x)\n\nComputes the rectified linear unit activation of vector `x`, returning a vector.\n\"\"\"\nrelu(x::AbstractVector{<:Number})::AbstractVector{<:Number} = max.(0.0, x)\n\n\"\"\"\n    softmax(x)\n\nComputes the softmax activation of vector `x`, returning a vector.\n\nUnlike some other activation functions, softmax does not treat vector elements\nindependently.\n\"\"\"\nsoftmax(x::AbstractVector{<:Number})::AbstractVector{<:Number} =\n    exp.(x .- maximum(x)) .* sum(exp.(x .- maximum(x)))^(-1)\n\nend # module\n", "meta": {"hexsha": "634847e6aca30ae7a1f063ecabd75ce32af9825c", "size": 1015, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/neural_networks/activation_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/neural_networks/activation_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/neural_networks/activation_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": 22.5555555556, "max_line_length": 80, "alphanum_fraction": 0.6837438424, "num_tokens": 264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517050371972, "lm_q2_score": 0.8976953003183443, "lm_q1q2_score": 0.8626418294447917}}
{"text": "# Starting in the top left corner of a 2\u00d72 grid, and only being able to move to\n# the right and down, there are exactly 6 routes to the bottom right corner.\n#\n# How many such routes are there through a 20\u00d720 grid?\n\nusing ProjectEulerSolutions\n\n# Memoization type solution to store intermediate results.\nfunction p015solution(n::Integer=2)::Integer\n    counts = zeros(Integer, n+1, n+1)\n    counts[1, :] .= 1  # There's only one way down.\n    counts[:, 1] .= 1  # There's only one way to the right.\n\n    # Count for a cell is the sum of the counts above and to the left.\n    for i = 2:n+1\n        for j = 2:n+1\n            @inbounds counts[i, j] = counts[i-1, j] + counts[i, j-1]\n        end\n    end\n\n    return counts[end, end]\nend\n\np015 = Problems.Problem(p015solution)\n\nProblems.benchmark(p015, 20)", "meta": {"hexsha": "9814625b6a91186a9aded8933a6b983b8d94e836", "size": 800, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/015.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/015.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/015.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.7692307692, "max_line_length": 79, "alphanum_fraction": 0.665, "num_tokens": 236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9669140216112959, "lm_q2_score": 0.891811041124754, "lm_q1q2_score": 0.8623046002912926}}
{"text": "#using TensorToolbox, LinearAlgebra\n\n#Define tensor as multidimensional arrays and calculate its norm:\n\nX=rand(4,3,2)\nnorm(X)\n\n#Create identity and diagonal tensor:\n\nId=neye(2,2,2)\nD=diagt([1,2,3,4])\n\n#For two tensors of same size calculate their inner product:\n\nX=rand(3,3,3,3);Y=rand(3,3,3,3);\ninnerprod(X,Y)\n\n#Matricization of a tensor:\n\nX=rand(4,3,2);mode=1;\nA=tenmat(X,mode)\nB=tenmat(X,row=[2,1],col=3) #by row modes [2,1] and column mode 3\n\n#Fold matrix back to tensor:\n\nX=matten(A,mode,[4,3,2])\nX=matten(B,[2,1],[3],[4,3,2]) # by row modes [2,1] and column mode 3\n\n#n-mode product of a tensor and a matrix or an array of matrices:\n\nX=rand(5,4,3);\nA=[rand(2,5),rand(2,4),rand(2,3)];\nttm(X,A[1],1)  #X times A[1] by mode 1\nttm(X,[A[1],A[2]],[1,2]) #X times A[1] by mode 1 and times A[2] by mode 2; same as ttm(X,A,-3)\nttm(X,A) #X times matrices from A by each mode\n\n#n-mode (vector) product of a tensor and a vector or an array of vectors:\n\nX=rand(5,4,3);\nV=[rand(5),rand(4),rand(3)];\nttv(X,V[1],1)  #X times V[1] by mode 1\nttv(X,[V[1],V[2]],[1,2]) #X times V[1] by mode 1 and times V[2] by mode 2; same as ttm(X,V,-3)\nttv(X,V) #X times vectors from V by each mode\n\n#Outer product of two tensors:\n\n X=rand(5,4,3,2);Y=rand(2,3,4);\n ttt(X,Y)\n\n#Kronecker product of two tensors (straightforward generalization of Kronecker product of matrices):\n\nX=rand(5,4,3);Y=rand(2,2,2);\ntkron(X,Y)\n\n#The n-rank and the mutlilinear rank of a tensor:\n\nX=rand(5,4,3);\nmode=2;\nnrank(X,mode)\nmrank(X)\n\n#The HOSVD:\n\nX=rand(5,4,3);\nhosvd(X) #same as T1=hosvd(X,eps_abs=1e-8)\nhosvd(X,eps_abs=1e-6) #discard singular values lower than 1e-5\nhosvd(X,eps_rel=1e-3) #discard singular values lower than 1e-3*sigma_{max}\nhosvd(X,reqrank=[2,2,2])\n\n#The CP decomposition:\n\nX=rand(5,4,3);\nR=3; #number of components\ncp_als(X,R)  #same as cp_als(X,R,init=\"rand\",dimorder=1:ndims(X))\ncp_als(X,R,init=[rand(5,3),rand(4,3),rand(3,3)]) #initialize factor matrices\ncp_als(X,R,init=\"nvecs\",dimorder=[2,1,3])\n\n##Tensors in Tucker format\n\n#Define tensor in Tucker format by its core tensor and factor matrices:\n\nF=rand(5,4,3);\nA=[rand(6,5),rand(6,4),rand(6,3)];\nttensor(F,A)\n\n#Get Tucker format of a tensor by using HOSVD:\n\nX=rand(8,9,7);\nhosvd(X)\nhosvd(X,reqrank=[3,3,3]) #HOSVD with predefined multilinear rank\n\n#Create random tensor in Tucker format of size 5x4x3 and mulilinear rank (2,2,2):\n\nX=randttensor([5,4,3],[2,2,2])\n\n#Basic functions:\n\nsize(X)\ncoresize(X)\nndims(X)\nnorm(X)\nfull(X)  #Creates full tensor out of Tucker format\nreorth(X) #Orthogonalize factor matrices\npermutedims(X,[2,1,3])\n\n#n-mode matricization of a tensor in Tucker format:\n\nmode=1;\ntenmat(X,mode)\n\n#Basic operations:\n\nX=randttensor([5,4,3],[2,2,2]);Y=randttensor([5,4,3],[3,2,1]);\ninnerprod(X,Y)\nX+Y\nX-Y\nX==Y #same as isequal(X,Y)\n3*X #same as mtimes(3,X)\n\n#n-mode product of a tensor in Tucker format and a matrix or an array of matrices:\n\nX=randttensor([5,4,3],[2,2,2]);\nA=[rand(2,5),rand(2,4),rand(2,3)];\nttm(X,A[1],1)  #X times A[1] by mode 1\nttm(X,[A[1],A[2]],[1,2]) #X times A[1] by mode 1 and times A[2] by mode 2; same as ttm(X,A,-3)\nttm(X,A) #X times matrices from A by each mode\n\n#n-mode (vector) product of a tensor in Tucker format and a vector or an array of vectors:\n\nX=randttensor([5,4,3],[2,2,2]);\nV=[rand(5),rand(4),rand(3)];\nttv(X,V[1],1)  #X times V[1] by mode 1\nttv(X,[V[1],V[2]],[1,2]) #X times V[1] by mode 1 and times V[2] by mode 2; same as ttm(X,V,-3)\nttv(X,V) #X times vectors from V by each mode\n\n#The n-rank and the mutlilinear rank of a tensor in Tucker format:\n\nX=randttensor([9,8,7],[5,4,3]);\nmode=2;\nnrank(X,mode)\nmrank(X)\n\n#HOSVD of a tensor in Tucker format:\n\nX=randttensor([6,7,5],[4,4,4]);\nhosvd(X)  #same as hosvd(X,eps_abs=1e-8)\nhosvd(X,eps_abs=1e-6) #discard singular values lower than 1e-5\nhosvd(X,eps_rel=1e-3) #discard singular values lower than 1e-3*sigma_{max}\nhosvd(X,reqrank=[3,3,3]) #HOSVD with predefined multilinear rank\n\n#The CP decomposition:\n\nX=randttensor([6,7,5],[4,4,4]);\nR=3; #number of components\ncp_als(X,R)  #same as cp_als(X,R,init=\"rand\",dimorder=1:ndims(X))\ncp_als(X,R,init=[rand(6,3),rand(7,3),rand(5,3)]) #initialize factor matrices\ncp_als(X,R,init=\"nvecs\",dimorder=[2,1,3])\n\n##Tensors in Kruskal format\n\n#Define tensor in Kruskal format by its factor matrices (and vector of weights):\n\nlambda=rand(3)\nA=[rand(5,3),rand(4,3),rand(3,3)];\nktensor(A)\nktensor(lambda,A)\n\n#Create random tensor in Kruskal format of size 5x4x3 and with 2 components:\n\nX=randktensor([5,4,3],2)\n\n#Basic functions:\n\nsize(X)\nndims(X)\nnorm(X)\nfull(X)  #Creates full tensor out of Kruskal format\npermutedims(X,[2,1,3])\nncomponents(X) #Number of components\n\n#n-mode matricization of a tensor in Kruskal format:\n\nmode=1;\ntenmat(X,mode)\n\n#Basic operations:\n\nX=randktensor([5,4,3],2);Y=randktensor([5,4,3],3);\ninnerprod(X,Y)\nX+Y\nX-Y\nX==Y #same as isequal(X,Y)\n3*X #same as mtimes(3,X)\n\n#n-mode product of a tensor in Kruskal format and a matrix or an array of matrices:\n\nX=randktensor([5,4,3],2);\nA=[rand(2,5),rand(2,4),rand(2,3)];\nttm(X,A[1],1)  #X times A[1] by mode 1\nttm(X,[A[1],A[2]],[1,2]) #X times A[1] by mode 1 and times A[2] by mode 2; same as ttm(X,A,-3)\nttm(X,A) #X times matrices from A by each mode\n\n#n-mode (vector) product of a tensor in Kruskal format and a vector or an array of vectors:\n\nX=randktensor([5,4,3],2);\nV=[rand(5),rand(4),rand(3)];\nttv(X,V[1],1)  #X times V[1] by mode 1\nttv(X,[V[1],V[2]],[1,2]) #X times V[1] by mode 1 and times V[2] by mode 2; same as ttm(X,V,-3)\nttv(X,V) #X times vectors from V by each mode\n\n#Arrange the rank-1 components of a tensor in Kruskal format:\n\nX=randktensor([6,5,4,3],3);\narrange(X)\narrange!(X)\n\n#Fix sign ambiguity of a tensor in Kruskal format:\n\nX=randktensor([6,5,4,3,4],3);\nfixsigns(X)\nfixsigns!(X)\n\n#Distribute weights a tensor in Kruskal format to a specific mode:\n\nX=randktensor([3,3,3],3);\nmode=2;\nredistribute(X,mode)\nredistribute!(X,mode)\n\n#The CP decomposition:\n\nX=randktensor([6,7,5],4);\nR=3; #number of components\ncp_als(X,R)  #same as cp_als(X,R,init=\"rand\",dimorder=1:ndims(X))\ncp_als(X,R,init=[rand(6,3),rand(7,3),rand(5,3)]) #initialize factor matrices\ncp_als(X,R,init=\"nvecs\",dimorder=[2,1,3]);\n\n##Tensors in Hierarchical Tucker format\n\n#Define tensor in Hierarchical Tucker format by dimensional tree T, its transfer tensors and factor matrices:\n\nT=dimtree(3)\nB=[rand(2,3,1),rand(4,3,2)]\nA=[rand(5,4),rand(4,3),rand(3,3)]\nhtensor(T,B,A)\n\n#Get Tucker format of a tensor by using htrunc:\n\nX=rand(8,9,7);\nhtrunc(X)\nhtrunc(X,maxrank=3) #hrunc with defined maximal rank\n\n#Create random tensor in Hierarchical Tucker format of size 5x4x3:\n\nX=randhtensor([5,4,3])\n\n#Basic functions:\n\nsize(X)\nndims(X)\nnorm(X)\nfull(X)  #Creates full tensor out of Hierarchial Tucker format\nreorth(X) #Orthogonalize factor matrices\n\n#Basic operations:\n\nX=randhtensor([5,4,3]);Y=randhtensor([5,4,3]);\ninnerprod(X,Y)\nX+Y\nX-Y\nX==Y #same as isequal(X,Y)\n3*X #same as mtimes(3,X)\n\n#n-mode product of a tensor in Hierarchical Tucker format and a matrix or an array of matrices:\n\nX=randhtensor([5,4,3]);\nA=[rand(2,5),rand(2,4),rand(2,3)];\nttm(X,A[1],1)  #X times A[1] by mode 1\nttm(X,[A[1],A[2]],[1,2]) #X times A[1] by mode 1 and times A[2] by mode 2; same as ttm(X,A,-3)\nttm(X,A) #X times matrices from A by each mode\n\n#n-mode (vector) product of a tensor in Hierarchical Tucker format and a vector or an array of vectors:\n\nX=randhtensor([5,4,3]);\nV=[rand(5),rand(4),rand(3)];\nttv(X,V[1],1)  #X times V[1] by mode 1\nttv(X,[V[1],V[2]],[1,2]) #X times V[1] by mode 1 and times V[2] by mode 2; same as ttm(X,V,-3)\nttv(X,V) #X times vectors from V by each mode\n\n#The h-rank of a tensor in Hierarchical Tucker format:\n\nX=htrunc(rand(9,8,7),maxrank=2)\nhrank(X)\n\n##Tensors in Tensor Train format\n\n#Define tensor in TT format by its core tensors:\n\nG=CoreCell(undef,3)\nG[1]=rand(1,4,3)\nG[2]=rand(3,6,4)\nG[3]=rand(4,3,1)\nX=TTtensor(G)\n\n#Get TT format of a tensor by using TTsvd:\n\nX=rand(5,4,3,2)\nTTsvd(X)\nTTsvd(X,reqrank=[2,2,2])\n\n#Create random TT tensor of size 5x4x3 and TT-rank (2,2):\n\nX=randTTtensor([5,4,3],[2,2])\n\n#Basic functions::\n\nsize(X)\nTTrank(X)\nndims(X)\nnorm(X)\nfull(X)  #Creates full tensor out of Tucker format\nreorth(X)\n\n#Basic operations:\n\nX=randTTtensor([5,4,3],[2,2])\nY=randTTtensor([5,4,3],[3,3])\n\ninnerprod(X,Y)\nX+Y\nX-Y\n3*X\n\n#TTsvd of a TT tensor:\n\nX=randTTtensor([7,6,5],[5,4])\nTTsvd(X,reqrank=[3,3])\n\n\nprintln()\n", "meta": {"hexsha": "d47b9e33930cba39b55dbeb1a22e3c6d9f420e33", "size": 8350, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/doctest.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/doctest.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/doctest.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": 24.4868035191, "max_line_length": 109, "alphanum_fraction": 0.6823952096, "num_tokens": 3225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947117065458, "lm_q2_score": 0.912436159286392, "lm_q1q2_score": 0.8622473452954719}}
{"text": "# # Exercise: compressing an image using the SVD\n\nusing Pkg\nPkg.add(\"Images\")\nPkg.add(\"ImageMagick\")\n\nusing Images, LinearAlgebra\n\nbanana = load(\"Courses/Introduction to Julia/images/banana.jpg\")\n\n# Images work just like arrays, but display specially\n\nsize(banana)\n\nbanana[60,50]\n\ngb = Gray.(banana)\n\nchannelview(gb)\n\n# The SVD factorizes a matrix A such that\n#     A == U * S * transpose(V)\n# where U and V are unitary, and S is diagonal.\n#\n# You can think of this as a sum of outer products (column of U times row\n# of V), where each one is scaled by a value in diag(S).\n# Each outer product is a full matrix (image).\n# So, the ones scaled by larger singular values are more important,\n# and we can throw away ones scaled by smaller values.\n\n# Here's what it looks like keeping 30, 10, 5, and 3 values:\n\nload(\"Courses/Introduction to Julia/images/banana_30svals.png\")\n\nload(\"Courses/Introduction to Julia/images/banana_10svals.png\")\n\nload(\"Courses/Introduction to Julia/images/banana_5svals.png\")\n\nload(\"Courses/Introduction to Julia/images/banana_3svals.png\")\n\n# ## Problem statement\n#\n# Write a function `compress_image`. Its arguments should be an image and the\n# factor by which you want to compress the image. A compressed grayscale image\n# should display when compress_image is called.\n# For example,\n#     `compress_image(\"images/104_100.jpg\", 33)`\n# will return a compressed image of a grayscale banana built using 3 singular\n# values. (This image has 100 singular values, so use fld(100, 33) to determine\n# how many singular values to keep. fld performs \"floor\" division.)\n#\n# Hints:\n# - Perform the SVD on the `channelview` of the image.\n# - Read the documentation for `svd`.\n\n# Remember: you can index arrays with `:` and ranges `a:b`:\n\nA = [ i+j for i = 1:10, j = 1:10 ]\n\nA[2:4, :]\nA[1:2, 1:2]\nA[:, 4:5]\n", "meta": {"hexsha": "8c8ca5a73c5a7d93cb693ff6781d3842316da6f9", "size": 1818, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Courses/Introduction to Julia/05. Image compression exercise.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/05. Image compression exercise.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/05. Image compression exercise.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": 28.8571428571, "max_line_length": 79, "alphanum_fraction": 0.7255225523, "num_tokens": 502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172659321806, "lm_q2_score": 0.9086178994073576, "lm_q1q2_score": 0.8622032128826709}}
{"text": "using LinearAlgebra\n\"\"\"\n    lu!(A)\nCompute LU factorization of the matrix `A`.\n\n# Example\n```julia-repl\njulia> lu!([1 2; 3 4])\n```\n\"\"\"\nfunction lu!(A::AbstractMatrix)\n    n,n = size(A)\n    p = collect(1:n)\n    for k in 1:n-1\n        m = argmax(abs.(A[k:n,k]))\n        m = m + k - 1\n        if A[m,k] != 0\n            if m != k\n                p[k], p[m] = p[m], p[k]\n                for j in 1:n\n                    A[k,j], A[m,j] = A[m,j], A[k,j]\n                end\n            end\n            for i in k+1:n\n                A[i,k] /= A[k,k]\n                for j in k+1:n\n                    A[i,j] -= A[i,k]*A[k,j]\n                end\n            end\n        end\n    end\n    L = tril(A,-1) + Matrix{Float64}(I, n, n)\n    U = triu(A)\n    return L, U, p\nend\n\n\"\"\"\n    chol!(A)\nCompute cholesky factorization of the spd matrix `A`.\n\n# Argument\n- `A:AbstractMatrix`: symmetric positive definite matrix\n\n# Example\n```julia-repl\njulia> chol([1 2; 2 5])\n```\n\"\"\"\nfunction chol(A::AbstractMatrix)\n    n,n = size(A)\n    L = similar(A)\n    @inbounds begin\n         for i in 1:n\n             tmp = 0\n             for k in 1:i-1\n                tmp += L[i,k].^2\n            end\n            L[i,i] = sqrt(A[i,i] - tmp)\n            for j in i+1:n\n                L[j,i] = A[i,j] / L[i,i]\n                for k in 1:i-1\n                    L[j,i] -=  L[i,k].*L[j,k] / L[i,i]\n                end\n            end\n        end \n    end\n    return L\nend\n\n\"\"\"\n    gepp!(A,b)\nSolve the linear system ``Ax=b`` using Gaussian elimination with partial pivot\n\n# Example\n```julia-repl\njulia> A = rand(3,3)\njulia> b = rand(3)\njulia> x = gepp!(A, b)\n```\n\"\"\"\nfunction gepp!(A::AbstractMatrix, b::AbstractVector)\n    n,n = size(A)\n    for k in 1:n-1\n        # pivot\n        m = argmax(abs.(A[k:n,k]))\n        m = m + k - 1\n        if A[m,k] != 0\n            if m != k\n                b[k], b[m] = b[m], b[k]\n                for j in 1:n\n                    A[k,j], A[m,j] = A[m,j], A[k,j]\n                end\n            end\n            for i in k+1:n\n                A[i,k] /= A[k,k]\n                b[i] -= A[i,k]*b[k]\n                for j in k+1:n\n                    A[i,j] -= A[i,k]*A[k,j]\n                end\n            end\n        end\n    end\n    # back substituion\n    x = zeros(n)\n    for k in n:-1:1\n        for j = n:-1:k+1\n            b[k] -= A[k,j]*x[j]\n        end\n        x[k] = b[k] / A[k,k]\n    end\n    return x\nend\n\n\"\"\"\n    jacobi(A, b, x0)\n    jacobi(A, b, x0, tol)\n\nSolve the linear system using Jacobi method.\n\n# Example\n```julia-repl\njulia> A = rand(3,3)\njulia> b = rand(3)\njulia> x0 = rand(3)\njulia> x = jacobi(A, b, x0)\n```\n\"\"\"\nfunction jacobi(A::AbstractMatrix, b::AbstractVector, x::AbstractVector, tol::Float64=1e-10)\n    xc = similar(b)\n    n, = size(b)\n    err = 1.0\n    it = 0\n    while err > tol\n        @inbounds for i in 1:n\n            xc[i] = b[i]\n            @inbounds for k in 1:n\n                if k != i\n                    xc[i] -= A[i,k]*x[k]\n                end\n            end\n            xc[i] /= A[i,i]\n        end\n        err = norm(x-xc)\n        x = copy(xc)\n        it += 1\n    end\n    return xc, it\nend\n\n\"\"\"\n    gaussseidel(A, b, x0)\n    gaussseidel(A, b, x0, tol)\n\nSolve the linear system using Gauss-Seidel method.\n\n# Example\n```julia-repl\njulia> A = rand(3,3)\njulia> b = rand(3)\njulia> x0 = rand(3)\njulia> x = gaussseidel(A, b, x0)\n```\n\"\"\"\nfunction gaussseidel(A::AbstractMatrix, b::AbstractVector, x::AbstractVector, tol::Float64=1e-10)\n    n, = size(b)\n    err = 1.0\n    it = 0\n    xc = copy(x)\n    while err > tol\n        @inbounds for i in 1:n\n            xc[i] = b[i]\n            @inbounds for k in 1:n\n                if k != i\n                    xc[i] -= A[i,k]*xc[k]\n                end\n            end\n            xc[i] /= A[i,i]\n        end\n        err = norm(x-xc)\n        x = copy(xc)\n        it += 1\n    end\n    return xc, it\nend", "meta": {"hexsha": "0ba237e8956986a8d79e809b9b9b32797994df45", "size": 3869, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/linearsystem.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/linearsystem.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/linearsystem.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": 21.027173913, "max_line_length": 97, "alphanum_fraction": 0.4218144223, "num_tokens": 1291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172659321806, "lm_q2_score": 0.9086178975514609, "lm_q1q2_score": 0.8622032111215785}}
{"text": "using Distributions, Random\nRandom.seed!(1234)\n\n# Sample from conditional X|Y=y\n# Inputs:\n# - y: The current value of y (Y_k)\n# - \u03bc: The mean vector of the joint density\n# - \u03a3: The covariance matrix of X,Y\n# Outputs:\n# X_{k+1} where X_{k+1} \u223c f(X|Y=y)\nfunction condition_on_Y(y, \u03bc, \u03a3)\n    \u03bcX = \u03bc[1]\n    \u03bcY = \u03bc[2]\n    \u03c3X2, \u03c3XY, _, \u03c3Y2 = \u03a3\n\n    conditional_mean = \u03bcX + \u03c3XY/\u03c3Y2*(y-\u03bcY)\n    conditional_variance = (1-\u03c3XY^2/(\u03c3X2*\u03c3Y2))*\u03c3X2\n\n    distribution = Normal(conditional_mean, conditional_variance)\n\n    return rand(distribution)\nend\n\n# Sample from conditional Y|X=y\n# Inputs:\n# - x: The current value of x (X_{k+1})\n# - \u03bc: The mean vector of the joint density\n# - \u03a3: The covariance matrix of X,Y\n# Outputs:\n# Y_{k+1} where Y_{k+1} \u223c f(y|X=x)\nfunction condition_on_X(x, \u03bc, \u03a3)\n    \u03bcX = \u03bc[1]\n    \u03bcY = \u03bc[2]\n    \u03c3X2, \u03c3XY, _, \u03c3Y2 = \u03a3\n\n    conditional_mean = \u03bcY + \u03c3XY/\u03c3X2*(x-\u03bcX)\n    conditional_variance = (1-\u03c3XY^2/(\u03c3X2*\u03c3Y2))*\u03c3Y2\n\n    distribution = Normal(conditional_mean, conditional_variance)\n\n    return rand(distribution)\nend\n\n# Gibbs sampler to obtain samples from (X,Y) ~ N(\u03bc,\u03a3)\n# Inputs:\n# - \u03bc: The joint density mean vector\n# - \u03a3: The covaraince matrix of X and Y\n# - n: The number of samples to return\n# Outputs:\n# An (n x 2) matrix where each row represent a sample\nfunction bivariate_gibbs(\u03bc, \u03a3, n)\n    # Store samples here\n    S = zeros(n,2)\n\n    # Initialize S_0 to means\n    S[1,:] = \u03bc\n\n    for i=2:n\n        X_k1 = condition_on_Y(S[i-1,2], \u03bc, \u03a3) # Get X_{k+1}\n        Y_k1 = condition_on_X(X_k1, \u03bc, \u03a3) # Get Y_{k+1}\n        S[i,:] = [X_k1, Y_k1]\n    end\n\n    return S\nend\n\n# Define joint density parameters\n\u03bcX = -1\n\u03bcY = 1\n\u03c3X = \u221a2\n\u03c3Y = \u221a3\n\u03c3XY = 2\n\u03bc = [\u03bcX, \u03bcY]\n\u03a3 = [\u03c3X^2 \u03c3XY; \u03c3XY \u03c3Y^2]\n\n# Get samples\nsamples = bivariate_gibbs(\u03bc, \u03a3, 10000)\n\n\n# Create 2d histogram\nusing Seaborn, Pandas\npygui(true)\ndf = DataFrame(Dict(:X=>samples[:,1], :Y=>samples[:,2]))\njointplot(x = \"X\", y = \"Y\", data = df, s = 1, alpha = 0.18)\n", "meta": {"hexsha": "82afc5f84af9cc4958d83539fa0edcc3ed181ffd", "size": 1925, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "content/stochastic-approximations/code/gibbs_sampler_bivariate_normal.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/gibbs_sampler_bivariate_normal.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/gibbs_sampler_bivariate_normal.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": 22.6470588235, "max_line_length": 65, "alphanum_fraction": 0.6275324675, "num_tokens": 731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9732407175907054, "lm_q2_score": 0.8856314692902446, "lm_q1q2_score": 0.8619326066929485}}
{"text": "module Gallery\nimport LinearAlgebra\nusing ..NLEVP\n\n\"\"\"\n    D,x=cheb(N)\n\nCompute differentiation matrix `D` on Chebyshev grid `x`. See Lloyd N.\nTrefethen. Spectral methods in MATLAB. Society for Industrial and Applied\nMathematics, Philadelphia, PA, USA, 2000.\n\"\"\"\nfunction cheb(N)\n    # Compute D = differentiation matrix, x = Chebyshev grid.\n    # See Lloyd N. Trefethen. Spectral Methods in MATLAB. Society for Industrial\n    # and Applied Mathematics, Philadelphia, PA, USA, 2000.\n    if N == 0\n        D=0\n        x=1\n        return D,x\n    end\n\n    x = cos.(pi/N*(0:N))\n    c = [2.; ones(N-1); 2. ].*((-1.).^(0:N))\n    X = repeat(x,1,N+1)\n    dX= X-X'\n    I=Array{Float64}(LinearAlgebra.I,N+1,N+1)\n    D =(c*(1. ./c'))./(dX+I) # off-diagonal entries\n    for i = 1:size(D)[1]\n        D[i,i]-=sum(D[i,:])\n    end\n    #D=D -np.diag(np.array(np.sum(D,1))[:,0]) #diagonal entries\n    return D,x\nend\n\n\"\"\"\n    L,y=orr_sommerfeld(N=64, Re=5772, w=0.26943)\n\nReturn a linear operator family `L` representing the Orr-Sommerfeld equation.\nA Chebyshev collocation method is used to discretize the problem. The grid\npoints are returned as `y`. The number of grid points is `N`.\n\n#Note\nThe OrrSommerfeld equation reads:\n[(d\u00b2/dy\u00b2-\u03bb\u00b2)\u00b2-Re((\u03bbU-\u03c9)(d\u00b2/dy\u00b2-\u03bb\u00b2)-\u03bbU'')] v = 0\n\nwhere y is the spatial coordinate, \u03bb the wavenumber (set as the eigenvalue by\ndefault), Re the Reynolds number, \u03c9 the oscillation frequency, U the mean flow\nvelocity profile and v the velocity fluctuation amplitude in the y-direction\n(the mode shape).\n\n#Remarks on implementation\nThis is a Julia port of (our python port of) the Orr-Sommerfeld example from the\nMatlab toolbox \"NLEVP: A Collection of Nonlinear Eigenvalue Problems\"\nby  T. Betcke, N. J. Higham, V. Mehrmann, C. Schr\u00f6der, and F. Tisseur.\n\nThe original toolbox is available at :\nhttp://www.maths.manchester.ac.uk/our-research/research-groups/numerical-analysis-and-scientific-computing/numerical-analysis/software/nlevp/\n\nSee  [1] or [2] for further refrence.\n\n#References\n[1] T. Betcke, N. J. Higham, V. Mehrmann, C. Schr\u00f6der, and F. Tisseur, NLEVP:\nA Collection of Nonlinear Eigenvalue Problems, MIMS EPrint 2011.116, December\n2011.\n\n[2] T. Betcke, N. J. Higham, V. Mehrmann, C. Schr\u00f6der, and F. Tisseur, NLEVP:\nA Collection of Nonlinear Eigenvalue Problems. Users' Guide, MIMS EPrint\n2010.117, December 2011.\n\"\"\"\nfunction orr_sommerfeld(N=64, Re=5772, \u03c9 =0.26943)\n    # Define the Orr-Sommerfeld operator for spatial stability analysis.\n    # N: number of Cheb points, R: Reynolds number, w: angular frequency\n    N=N+1\n    # 2nd- and 4th-order differentiation matrices:\n    D,y=cheb(N); D2 =D^2;  D2 = D2[2:N,2:N]\n    S= LinearAlgebra.diagm(0=>[0; 1.0./(1. .-y[2:N].^2.); 0])\n    D4=(LinearAlgebra.diagm(0=>1. .-y.^2.)*D^4-8*LinearAlgebra.diagm(0=>y)*D^3-12*D^2)*S\n    D4 = D4[2:N,2:N]\n\n    I=Array{ComplexF64}(LinearAlgebra.I,N-1,N-1)\n    # type conversion\n    D2=D2.+0.0im\n    D4=D4.+0.0im\n    U=LinearAlgebra.diagm(0=>-y[2:N].^2.0.+1)\n    # Build Orr-Sommerfeld operator\n    L= LinearOperatorFamily([\"\u03bb\",\"\u03c9\",\"Re\",\"a\"],complex([1.,\u03c9,Re,Inf]))\n    push!(L,Term(I,(pow_a(4),),((:\u03bb,),),\"\u03bb^4\",\"I\"))\n    push!(L,Term(1.0im*U,(pow_a(3),pow1,),((:\u03bb,),(:Re,),),\"i\u03bb^3Re\",\"i*U\"))\n    push!(L,Term(-2*D2,(pow2,),((:\u03bb,),),\"\u03bb^2\",\"-2D2\"))\n    push!(L,Term(-1.0im*I,(pow2,pow1,pow1,),((:\u03bb,),(:\u03c9,),(:Re,),),\"\u03bb^2*\u03c9*Re\",\"-i*I\"))\n    push!(L,Term(-1.0im*(U*D2+2.0*I),(pow1,pow1,),((:\u03bb,),(:Re,),),\"\u03bb*Re\",\"(U*D2+2*I)\"))\n    push!(L,Term(1.0im*D2,(pow1,pow1),((:\u03c9,),(:Re,),),\"\u03c9*Re\",\"i*D2\"))\n    push!(L,Term(D4,(),(),\"\",\"D4\"))\n    push!(L,Term(-I,(pow1,),((:a,),),\"-a\",\"__aux__\"))\n    return L,y\nend\n\n\"\"\"\n    L,x,y=biharmonic(N=12;scaleX=2,scaleY=1+sqrt(5))\n\nDiscretize the biharmonic equation.\n\n# Arguments\n-`N::Int`: Number of collocation points\n-`scaleX::Float=2` length of the x-axis\n-`scaleY::Float=1+sqrt(5)` length of the y-axis\n\n# Returns\n-`L::LinearOperatorFamily`: discretization of the biharmonic operator\n- `x:Array`: x-axis\n- `y:Array`: y-axis\n\n# Notes\nThe biharmonic equation models the oscillations of a membrane. It is an an eigenvalue problem that reads:\n(\u2207\u2074+\u03b5cos(2\u03c0x)cos(\u03c0y))**v**=\u03bb**v** in \u03a9\nwith boundary conditions\n**v**=\u2207\u00b2**v**=0\n\n\nThe term \u03b5cos(2\u03c0x)cos(\u03c0y) is included to model some inhomogeneous material properties.\nThe equation is discretized using Chebyshev collocation.\n\nSee also: [`cheb`](@ref)\n\"\"\"\n\nfunction biharmonic(N=12;scaleX=2,scaleY=1+sqrt(5))\n#N,scaleX,scaleY=12,2,1+sqrt(5)\n    N=N+1\n    D, xx = cheb(N)\n    x = xx/scaleX\n    y = xx/scaleY\n\n    #The Chebychev matrices are space dependent scale the accordingly\n    Dx = D*scaleX\n    Dy = D*scaleY\n\n    D2x=Dx*Dx\n    D2y=Dy*Dy\n    Dx = Dx[2:N,2:N]\n    Dy = Dy[2:N,2:N]\n    D2x= D2x[2:N,2:N]\n    D2y= D2y[2:N,2:N]\n    #Apply BC\n    I = Array{ComplexF64}(LinearAlgebra.I,N-1,N-1)\n    L = kron(I,D2x) +kron(D2y,I)\n    X=kron(ones(N-1),x[2:N])\n    Y=kron(y[2:N],ones(N-1))\n    P=LinearAlgebra.diagm(0=>cos.(\u03c0*2*X).*cos.(\u03c0*Y))\n    D4= L*L\n    I = Array{ComplexF64}(LinearAlgebra.I,(N-1)^2,(N-1)^2)\n    L= LinearOperatorFamily([\"\u03bb\",\"\u03b5\",\"a\"],complex([0,0.,Inf]))\n    push!(L,Term(D4,(),(),\"\",\"D4\"))\n    push!(L,Term(P,(pow1,),((:\u03b5,),),\"\u03b5\",\"P\"))\n    push!(L,Term(-I,(pow1,),((:\u03bb,),),\"-\u03bb\",\"I\"))\n    push!(L,Term(-I,(pow1,),((:a,),),\"-a\",\"__aux__\"))\n    return L,x,y\nend\n\n\n## 1DRijkeModel\nusing SparseArrays\n\"\"\"\n    L,grid=rijke_tube(resolution=128; l=1, c_max=2,mid=0)\n\nDiscretize a 1-dimensional Rijke tube. The model is based on the thermoacoustic equations.\nThis eigenvalue problem reads:\n\u2207c\u00b2(x)\u2207p+\u03c9\u00b2p-n exp(-i\u03c9\u03c4) \u2207p(x_ref)=0 for x in ]0,l[\nwith boundariy conditions\n\u2207p(0)=p(l)=0\n\"\"\"\nfunction rijke_tube(resolution=127; l=1, c_max=2,mid=0)\n  n=1.0\n  tau=2\n  #l=1\n  c_min=1\n  #c_max=2\n  outlet=resolution\n  outlet_c=c_max\n  grid=range(0,stop=l,length=resolution)\n  e2p=[(i, i+1) for i =1:resolution-1]\n  number_of_elements=resolution-1\n  if mid==0\n    mid=div(resolution,2)+1# this is the element containing the flame\n    #it is not the center if resolotion is odd but then the refernce is in the center\n  end\n  ref=mid-1 #the reference element is the one in the middle\n  flame=(mid)\n  #compute element volume\n  e2v=diff(grid)\n  V=e2v[mid]\n  e2c=[i < mid ? c_min : c_max for i = 1:resolution]\n\n  #assemble mass matrix\n  m_unit=[2 1;1 2]*1/6\n  #preallocation\n  ii=Array{Int64}(undef,(resolution-1,2^2))\n  jj=Array{Int64}(undef,(resolution-1,2^2))\n  mm=Array{ComplexF64}(undef,(resolution-1,2^2))\n  for (idx,el) in enumerate(e2p)\n    mm[idx,:] = m_unit[:]*e2v[idx]\n    ii[idx,:] = [el[1] el[2] el[1] el[2]]\n    jj[idx,:] = [el[1] el[1] el[2] el[2]]\n  end\n  # finally assemble global (sparse) mass matrix\n  M =sparse(ii[:],jj[:],mm[:])\n\n  # assemble stiffness matrix\n  k_unit = -[1. -1.; -1. 1.]\n  #preallocation\n  ii=Array{Int64}(undef,(resolution-1,2^2))\n  jj=Array{Int64}(undef,(resolution-1,2^2))\n  kk=Array{ComplexF64}(undef,(resolution-1,2^2))\n  for (idx,el) in enumerate(e2p)\n    kk[idx,:]=k_unit[:]/e2v[idx]*e2c[idx]^2\n    ii[idx,:] = [el[1] el[2] el[1] el[2]]\n    jj[idx,:] = [el[1] el[1] el[2] el[2]]\n  end\n  # finally assemble global (sparse) stiffness matrix\n  K = sparse(ii[:],jj[:],kk[:])\n\n\n  #assemble boundary mass matrix\n  bb=[-outlet_c*1im]\n  ii=[outlet]\n  jj=[outlet]\n  B = sparse(ii,jj,bb)\n  #assemble flame matrix\n  #preallocation\n  ii=Array{Int64}(undef,(length(flame),2*2))\n  jj=Array{Int64}(undef,(length(flame),2*2))\n  qq=Array{ComplexF64}(undef,(length(flame),2*2))\n\n  grad_p_ref=[-1 1]\n  grad_p_ref=grad_p_ref/e2v[ref]*1\n  #println(\"##!!!!!Here!!!!!##'\")\n  #println(\"flame:\",flame)\n  #println(\"ref:\",ref)\n  for (idx,el) in enumerate(flame)\n    jj[idx,:]=[e2p[ref][1] e2p[ref][2] e2p[ref][1] e2p[ref][2]]\n    ii[idx,:]=[e2p[el][1] e2p[el][1] e2p[el][2] e2p[el][2]]\n    run=1\n    for i=1:2\n      for j =1:2\n        qq[idx,run]= grad_p_ref[1,j]*e2v[el]/2\n        run+=1\n      end\n    end\n  end\n  #finally assemble flame matrix\n  Q= sparse(ii[:],jj[:],-qq[:],resolution,resolution)\n  Q=Q/V\n  L=LinearOperatorFamily([\"\u03c9\",\"n\",\"\u03c4\",\"Y\",\"\u03bb\"],complex([0.,n,tau,1E15,Inf]))\n  push!(L,Term(M,(pow2,),((:\u03c9,),),\"\u03c9^2\",\"M\"))\n  push!(L,Term(K,(),(),\"\",\"K\"))\n  push!(L,Term(B,(pow1,pow1,),((:\u03c9,),(:Y,),),\"\u03c9*Y\",\"C\"))\n  push!(L,Term(Q,(pow1,exp_delay,),((:n,),(:\u03c9,:\u03c4,)),\"n*exp(-i \u03c9 \u03c4)\",\"Q\"))\n  push!(L,Term(-M,(pow1,),((:\u03bb,),),\"-\u03bb\",\"__aux__\"))\n  #push!(L,Term(-SparseArrays.I,(pow1,),((:\u03bb,),),\"-\u03bb\",\"__aux__\"))\n return L,grid\nend\n\nend\n", "meta": {"hexsha": "ea4cd87a0f9c31203f588f3a72824aa3a3644640", "size": 8324, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NLEVP/gallery.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": "src/NLEVP/gallery.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": "src/NLEVP/gallery.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": 31.6501901141, "max_line_length": 141, "alphanum_fraction": 0.6239788563, "num_tokens": 3211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104982195785, "lm_q2_score": 0.8918110526265554, "lm_q1q2_score": 0.861855563686556}}
{"text": "using Test\nusing Plots\n\ninclude(\"../../../lib/DifferencesMatrix.jl\")\nusing .DifferencesMatrix: backwardDiff, forwardDiff, centeredDiff\n\ninclude(\"../../../lib/SpecialVectors.jl\")\nusing .SpecialVectors: squares\n\ninclude(\"../../../lib/KTBC.jl\")\nusing .KTBC: CreateKTBC\n\n# 8\ndim = 5\nforwardDiff(dim) - backwardDiff(dim)\n\nbackwardDiff(dim) * forwardDiff(dim)\n\nbackwardDiff(dim) * centeredDiff(dim)\n\n# 10\nforwardDiff(dim) * backwardDiff(dim)\n\nfunction getH(n::Int)\n    return 1 / (n + 1)\nend\n\nfunction getAnalogRange()\n    return 0:10^(-2):1\nend\n\n# 13\nfunction discretSolution(n::Int)\n    h = getH(n)\n    T = backwardDiff(n) * (-forwardDiff(n))\n    u = h^2 * (T \\ ones(n))\n    return u\nend\n\nn = 7\nanalogSolution(x) = (1 / 2) * (1 - x^2)\nsteps = 0:1 / (n + 1):1\n\nu\u209c = analogSolution.([steps...])[2:(n + 1)]\nplot(u\u209c)\n\nu\u2087 = discretSolution(n)\nplot!(u\u2087)\n\ne = u\u209c - u\u2087\nplot(e)\n\n# 14\nfunction cosAgainstDiscretCos(n::Int)\n    x = getAnalogRange()\n\n    h = getH(n)\n    x\u1d62 = 0:h:1\n    \u03c9 = 4 * \u03c0\n\n    u = cos.(\u03c9 * x)\n    u\u1d62 = cos.(\u03c9 * h * (1:n + 2))\n\n    lineWidth = 2\n    plot(x, u, label=\"analog cos\", lw=lineWidth, title=\"Cos/DiscretCos Oscilations with N=$n\")\n    plot!(x\u1d62, u\u1d62, label=\"discret cos\", lw=lineWidth)\nend\n\ncosAgainstDiscretCos(3)\ncosAgainstDiscretCos(20)\ncosAgainstDiscretCos(150)\ncosAgainstDiscretCos(350)\n\n# 16\nfunction analogAndDiscretSolutions(n::Int)\n    \u03c9 = 4 * \u03c0\n    h = getH(n)\n\n    range\u2090 = getAnalogRange()\n\n    analogSolution(x) = ((\u03c9)^-2) * cos(\u03c9 * x) - ((\u03c9)^-2)\n    u = analogSolution.(range\u2090)\n  \n    range\u1d62 = h * (1:n)\n    K\u2099, T\u2099, B\u2099, C\u2099 = CreateKTBC(n)\n    u\u1d62 = h^2 * (K\u2099 \\ cos.(\u03c9 * range\u1d62))\n\n    plot(range\u2090, u, label=\"analog\", title=\"Analog+Discret solutions with N=$n\")\n    plot!(range\u1d62, u\u1d62, label=\"discret\")\nend\n\nanalogAndDiscretSolutions(4)\nanalogAndDiscretSolutions(8)\nanalogAndDiscretSolutions(16)\nanalogAndDiscretSolutions(32)\n\n# 18\nfunction analogAndDiscretSolutions2(n::Int)\n    h = getH(n)\n\n    range\u2090 = getAnalogRange()\n\n    analogSolution(x) = (x / 6) * (x^2 - 1)\n    u = analogSolution.(range\u2090)\n  \n    range\u1d62 = h * (1:n)\n    K\u2099 = CreateKTBC(n)[1]\n    u\u1d62 = h^2 * (-K\u2099 \\ range\u1d62)\n\n    plot(range\u2090, u, label=\"analog\", title=\"Analog+Discret solutions with N=$n\")\n    plot!(range\u1d62, u\u1d62, label=\"discret\")\nend\n\nanalogAndDiscretSolutions2(4)\nanalogAndDiscretSolutions2(8)\nanalogAndDiscretSolutions2(32)\nanalogAndDiscretSolutions2(64)\n\n# 19\nfunction analogAndDiscretSolutions3(n::Int)\n    h = getH(n)\n\n    range\u2090 = getAnalogRange()\n\n    c\u2090 = 1 / (\u212f - 1)\n    analogSolution(x) = c\u2090 - c\u2090 * \u212f^x + x\n    u = analogSolution.(range\u2090)\n\n    f = ones(n)\n    \u25ec\u208a = forwardDiff(n)\n    \u25ec\u208b = backwardDiff(n)\n    \u25ec\u2080 = (\u25ec\u208a + \u25ec\u208b) / (2 * h)\n    K\u2099 = CreateKTBC(n)[1]\n    K = K\u2099 / (h^2)\n\n    range\u1d62 = h * (1:n)\n    u\u1d62 = round.((K + \u25ec\u2080) \\ f, digits=4)\n    u\u208a = round.((K + \u25ec\u208a / h) \\ f, digits=4)\n\n    plot(range\u2090, u, label=\"analog\", title=\"Analog+Discret solutions with N=$n\")\n    plot!(range\u1d62, u\u1d62, label=\"discret centered\")\n    plot!(range\u1d62, u\u208a, label=\"discret uncentered\")\nend\n\nanalogAndDiscretSolutions3(4)\nanalogAndDiscretSolutions3(8)\nanalogAndDiscretSolutions3(16)\nanalogAndDiscretSolutions3(32)\nanalogAndDiscretSolutions3(64)\n", "meta": {"hexsha": "57846f65b4c9ff0c40a9a67b293c6cf6179b0b33", "size": 3131, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "1.AppliedLInearAlgebra/2.DifferentialEqnsAndDifferenceEqns/ProblemSet/Solutions.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/ProblemSet/Solutions.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/ProblemSet/Solutions.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": 20.8733333333, "max_line_length": 94, "alphanum_fraction": 0.6343021399, "num_tokens": 1221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012762876286, "lm_q2_score": 0.9111797160416689, "lm_q1q2_score": 0.8617949383596094}}
{"text": "using Printf\n\nfunction newton(f, df, p0, n_max, rel_tol; verbose = true)\n    \n    converged = false;\n    p = p0;\n    p_old = p0;\n\n    for i in 1:n_max\n\n        p = p_old - f(p_old)/df(p_old);\n        \n        if verbose\n            @printf(\" %d: p = %.15g, f(p) = %g\\n\", i, p, f(p));\n        end\n\n        \n        if (i>1)\n            if abs(p-p_old)/abs(p)< rel_tol\n                converged = true;\n                break\n            end\n        end\n\n        p_old = p;\n\n    end\n    \n    if !converged\n        @printf(\"ERROR: Did not converge after %d iterations\\n\", n_max);\n    end\n\n    return p\n    \nend\n\nfunction bisection(f, a, b, n_max, rel_tol; verbose = true)\n    \n    converged = false;\n    p_old = 0;\n    p = 0;\n    for i in 1:n_max\n\n        p = 0.5 * (a+b)\n        \n        if verbose\n            @printf(\" %d: a = %g, b = %g, p = %g, f(p) = %g\\n\", i, a, b, p, f(p));\n        end\n\n        if ( f(a) * f(p)<=0)\n            b = p;\n        else\n            a = p\n        end\n        \n        if (i>1)\n            if abs(p-p_old)/abs(p)< rel_tol\n                converged = true;\n                break\n            end\n        end\n\n        if(abs(f(p))==0)\n            converged = true;\n            break\n        end\n        p_old = p;\n\n    end\n    \n    if !converged\n        @printf(\"ERROR: Did not converge after %d iterations\\n\", n_max);\n    end\n\n    return p\n    \nend\n\nfunction secant(f, p0, p1, n_max, rel_tol; verbose = true)\n    \n    converged = false;\n    \n    p = p0;\n    for i in 1:n_max\n\n        p = p1 - f(p1) * (p1-p0)/(f(p1)-f(p0));\n        \n        if verbose\n            @printf(\" %d: p = %.12g, f(p) = %g\\n\", i, p, f(p));\n        end\n\n        \n        if (i>1)\n            if abs(p-p1)/abs(p1)< rel_tol\n                converged = true;\n                break\n            end\n        end\n        p0 = p1;\n        p1 = p;\n\n    end\n    \n    if !converged\n        @printf(\"ERROR: Did not converge after %d iterations\\n\", n_max);\n    end\n\n    return p\n    \nend", "meta": {"hexsha": "2c8fe72aedc215c64681542c290d00aefa8bead1", "size": 1978, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/Julia Functionality/rootfinding.jl", "max_stars_repo_name": "liamfdoherty/Math_300_2021", "max_stars_repo_head_hexsha": "815487d4fe6549026fcd4c3efea152c723457129", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-20T02:43:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T19:09:21.000Z", "max_issues_repo_path": "notebooks/Julia Functionality/rootfinding.jl", "max_issues_repo_name": "liamfdoherty/Math_300_2021", "max_issues_repo_head_hexsha": "815487d4fe6549026fcd4c3efea152c723457129", "max_issues_repo_licenses": ["MIT"], "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/Julia Functionality/rootfinding.jl", "max_forks_repo_name": "liamfdoherty/Math_300_2021", "max_forks_repo_head_hexsha": "815487d4fe6549026fcd4c3efea152c723457129", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-09-22T15:34:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-03T11:11:55.000Z", "avg_line_length": 17.9818181818, "max_line_length": 82, "alphanum_fraction": 0.4095045501, "num_tokens": 601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012717045181, "lm_q2_score": 0.911179716041669, "lm_q1q2_score": 0.8617949341835722}}
{"text": "# # Fidelity in quantum information theory\n# This example is inspired from a lecture of John Watrous in the [course on Theory of Quantum Information](https://cs.uwaterloo.ca/~watrous/CS766/LectureNotes/08.pdf).\n#\n# The Fidelity between two Hermitian semidefinite matrices P and Q is defined as:\n#\n# $$\n# F(P, Q) = \\|P^{1/2}Q^{1/2}\\|_{\\text{tr}} = \\max_U \\mathrm{tr}(P^{1/2}U Q^{1/2})\n# $$\n#\n# where the trace norm $\\|\\cdot\\|_{\\text{tr}}$ is the sum of the singular values, and the maximization goes over the set of all unitary matrices U. This quantity can be expressed as the optimal value of the following complex-valued SDP:\n#\n# $$\n# \\begin{array}{ll}\n#   \\mbox{maximize} &  \\frac{1}{2}\\text{tr}(Z+Z^\\dagger) \\\\\n#   \\mbox{subject to} &\\\\\n#   & \\left[\\begin{array}{cc}P&Z\\\\{Z}^{\\dagger}&Q\\end{array}\\right] \\succeq 0\\\\\n#   & Z \\in \\mathbf {C}^{n \\times n}\\\\\n# \\end{array}\n# $$\n#\n\nusing Convex, SCS, LinearAlgebra\nif VERSION < v\"1.2.0-DEV.0\"\n     LinearAlgebra.diagm(v::AbstractVector) = diagm(0 => v)\nend\n\nn = 20\nP = randn(n,n) + im*randn(n,n)\nP = P*P'\nQ = randn(n,n) + im*randn(n,n)\nQ = Q*Q'\nZ = ComplexVariable(n,n)\nobjective = 0.5*real(tr(Z+Z'))\nconstraint = [P Z;Z' Q] \u2ab0 0\nproblem = maximize(objective,constraint)\nsolve!(problem, SCSSolver(verbose=0))\ncomputed_fidelity = evaluate(objective)\n\n#-\n\n## Verify that computer fidelity is equal to actual fidelity\nP1,P2 = eigen(P)\nsqP = P2 * diagm([p1^0.5 for p1 in P1]) * P2'\nQ1,Q2 = eigen(Q)\nsqQ = Q2 * diagm([q1^0.5 for q1 in Q1]) * Q2'\n\n#-\n\nactual_fidelity = sum(svdvals(sqP * sqQ))\n\n# We can see that the actual fidelity value is very close the computed fidelity value.\n", "meta": {"hexsha": "96d1bbb76acd5f5f69f00371f1f30b564ed3f74e", "size": 1625, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/examples_literate/optimization_with_complex_variables/Fidelity in Quantum Information Theory.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/optimization_with_complex_variables/Fidelity in Quantum Information Theory.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/optimization_with_complex_variables/Fidelity in Quantum Information Theory.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": 31.25, "max_line_length": 236, "alphanum_fraction": 0.6615384615, "num_tokens": 582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9748211561049158, "lm_q2_score": 0.8840392939666335, "lm_q1q2_score": 0.8617802065867272}}
{"text": "module CalculoNumerico\n\n@doc raw\"\n\tnewton_raphson\n\nEsta fun\u00e7\u00e3o implementa uma b\u00e1sica vers\u00e3o do m\u00e9todo de Newton-Raphson. Essencialmente, esta implementa\u00e7\u00e3o depende de um ponto inicial ``x_0``, uma fun\u00e7\u00e3o $f$ e sua derivada $f'$. Estabelecida uma precis\u00e3o $\u03b5$, o m\u00e9todo de Newton-Raphson gera uma sequ\u00eancia iterativa \n\t$$x_{k+1} = x_{k} -frac{f(x_k)}{f'(x_k)},$$\nque, sob certas condi\u00e7\u00f5es converge para solu\u00e7\u00e3o do problema. \n\tEsta fun\u00e7\u00e3o retorna a raiz, o valor da fun\u00e7\u00e3o na raiz e o n\u00famero de itera\u00e7\u00f5es necess\u00e1rias. \n\n# Exemplo\n\ncolocar exemplo\n\"\nfunction newton_raphson(x0,f,df,\u03b5=10.0^(-4))\n\tx = x0 - f(x0)/df(x0)\n\tk = 1\n\twhile abs(x-x0)>=\u03b5 && abs(f(x))>\u03b5\n\t\tx0 = x\n\t\tx = x0 - f(x0)/df(x0)\n\t\tk += 1\n\tend\n\treturn x,f(x),k\nend\n\nend # module\n", "meta": {"hexsha": "8127c262d1a9332aaf34e779bf718006ebe2137f", "size": 739, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/CalculoNumerico.jl", "max_stars_repo_name": "evcastelani/CalculoNumerico.jl", "max_stars_repo_head_hexsha": "a77c7d2c36d7a191c88f754a5cb4e612f567a88c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/CalculoNumerico.jl", "max_issues_repo_name": "evcastelani/CalculoNumerico.jl", "max_issues_repo_head_hexsha": "a77c7d2c36d7a191c88f754a5cb4e612f567a88c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CalculoNumerico.jl", "max_forks_repo_name": "evcastelani/CalculoNumerico.jl", "max_forks_repo_head_hexsha": "a77c7d2c36d7a191c88f754a5cb4e612f567a88c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3703703704, "max_line_length": 265, "alphanum_fraction": 0.6955345061, "num_tokens": 264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.953966096291997, "lm_q2_score": 0.903294209307224, "lm_q1q2_score": 0.8617120506559786}}
{"text": "# julia1_4.2.jl Vector and Matrix Operations\n#\n# Most of the math functions work equally well on Vectors\n# and matrices.\n# The same goes for operations but some need a preceding\n# dot (.) to be corresponding element by element ops\n# Those include .* .+ .- .% ./ .\\ and .^ or any op with otherwise\n#  different normal vector/matrix behavior. .+ and .- were enforced\n#  recently for clarity of intent.\n#  library functions that are operating on element-wise also require a dot\n# The following types have a variety of elementary\n# operations and functions with optimized methods:\n# Type\t            Description\n# Diagonal\t        Diagonal matrix\n# Hermitian\t        Hermitian matrix - Square, self conjugate\n# UpperTriangular\tUpper right triangular matrix\n# LowerTriangular\tLower left triangular matrix\n# Tridiagonal\t    Tridiagonal matrix\n# SymTridiagonal\tSymmetric tridiagonal matrix\n# Bidiagonal\t    (true)Upper/(false)Lower bidiagonal matrix\n\n# In addition, The LAPACK library is available.\n# and a large variety of matrix factorizations\n\n# Examples:\nusing LinearAlgebra\nA = [2.5 2 -4; 3 -1 -6; -10 2.3 4.4]\nprintln(eigvals(A))\nprintln(eigvecs(A))\n# 3 ways to get an inverse\nAinv=inv(A)\nA^-1\nA\\I  # I is the identity/uniform-scaling operator\n# checking out the inverse\nA*Ainv\n\nAm1=A^2 .+ exp.(A) .- 1\n\nB = [2.5 2 -4; 2 -1 -3; -4 -3 4.4]\nsB=Symmetric(B)  # less computation\n# solve for x in sB*x=v linear system of equations\nv=[1.0,2,3]\nx=sB\\v\nprintln(x)  # Linear Solutions\n#\n###\n#\n# more than 12 different factorizations are available\n# Single Valued Decomposition SVD\n#\n(U,S,V)=svd(B)  # such that U*diagm(S)*V'\nprintln(U)      # Matrix\nprintln(V)      # Matrix\nprintln(S)      # Vector diagonal of matrix\nprintln(U*Diagonal(S)*V') # V' transpose of matrix V\n#\n# LU decomposition L=lower triangular part,\n# U=upper triangular part, p= permutation vector\n(L,U,p)=lu(B)\nprintln(L)  # lower triangle\nprintln(U)  # upper triangle\nprintln(p)  # permutation vector for rows\nprintln((L*U)[p,:]) # rearrange rows by p\n\n# Make a random Matrix\nR=rand(3,3) .+ Diagonal([1.0, 1, 1])  # random matrix R + unit diag. matrix\nRi=inv(R)            # now invert it\n\n# Sparce matrices - type=SparseMatrixCSC Compressed Sparce Cols\n#        colVec       rowVec       Data\nusing SparseArrays\n#          row index    col index    values\nS=sparse([1, 2, 3, 3],[1, 3, 1, 2],[3, 3, 2, 0])\nS=dropzeros(S)\nR=S*I\nR*rand(3,3)\n", "meta": {"hexsha": "29063db2fcb900280f89ceafe71307cd5bbe54e9", "size": 2400, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Section4/Julia1_4.2.jl", "max_stars_repo_name": "PacktPublishing/Learning-Julia-1.0", "max_stars_repo_head_hexsha": "103b679bafe3646f1dd2dba5e626df879db9b647", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-08-14T03:22:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T13:10:30.000Z", "max_issues_repo_path": "Section4/Julia1_4.2.jl", "max_issues_repo_name": "PacktPublishing/Learning-Julia-1.0", "max_issues_repo_head_hexsha": "103b679bafe3646f1dd2dba5e626df879db9b647", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Section4/Julia1_4.2.jl", "max_forks_repo_name": "PacktPublishing/Learning-Julia-1.0", "max_forks_repo_head_hexsha": "103b679bafe3646f1dd2dba5e626df879db9b647", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-04-19T08:06:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-08T15:00:12.000Z", "avg_line_length": 31.1688311688, "max_line_length": 75, "alphanum_fraction": 0.6916666667, "num_tokens": 735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660976007596, "lm_q2_score": 0.9032942008463507, "lm_q1q2_score": 0.8617120437667899}}
{"text": "#script for solving a 2D BVP of the form\n# -a0(x)*\\Delta u(x,y)+a1(x)*u(x,y)=f(x,y) for (x,y) \u2208 \u03a9:= (0,1)^2\n# Here a0(x,y)=1, a1(x,y)=0, f(x,y)=-8*\u03c0^2*sin(2*\u03c0*x)*sin(2*\u03c0*y)\n# with Dirichlet boundary conditions u(x,y)=0 for (x,y) \u2208 \u2202\u03a9\ninclude(\"../src/Solver2D.jl\")\ninclude(\"../src/SplinePlotting.jl\")\n\na0(x,y) = 1\na1(x,y) = 0\nf(x,y) = 8*\u03c0^2*sin(2*\u03c0*x)*sin(2*\u03c0*y)\nexact_sol(x,y) = sin(2*\u03c0*x)*sin(2*\u03c0*y)\nderiv_exact_sol(x,y) = [2*\u03c0*cos(2*\u03c0*x)*sin(2*\u03c0*y), 2*\u03c0*sin(2*\u03c0*x)*cos(2*\u03c0*y)]\n\n#Define the boundary conditions\nu_bound(x,y) = 0\nbound_left = Boundary2D(\"Dirichlet\", \"Left\", u_bound)\nbound_right = Boundary2D(\"Dirichlet\", \"Right\", u_bound)\nbound_down = Boundary2D(\"Dirichlet\", \"Down\", u_bound)\nbound_up = Boundary2D(\"Dirichlet\", \"Up\", u_bound)\nbound_all = [bound_left, bound_right, bound_down, bound_up]\n\n#Define the domain geometry\ncornerLowerLeft = [0., 0.]\nlengthx = 1.\nlengthy = 1.\nuPtRight = 1.\ndegP = [3, 3]\nnumSubdiv = 80\nnrb = nrbsquare(cornerLowerLeft, lengthx, lengthy, degP, numSubdiv)\n#Plots.surface(reuse = false)\n#plt = nrbctrlplot(nrb)\n#plt = nrbkntplot(nrb)\n#display(plt)\nIEN, elemVertex = makeIEN(nrb.knots, numSubdiv^2, degP)\nIGAmesh = genMesh(nrb)\n#plotBasisParam(IGAmesh)\n\ngauss_rule = [genGaussLegendre(degP[1]+1), genGaussLegendre(degP[2]+1)]\nstiff = assemble_stiff2D(IGAmesh, a0, gauss_rule)\nrhs = assemble_rhs2D(IGAmesh, f, gauss_rule)\nbcdof_all, elem_all = classifyBoundary2D(IGAmesh)\nlhs, rhs = applyBCnurbs(IGAmesh, bound_all, stiff, rhs, bcdof_all, elem_all, gauss_rule)\n@time sol0 = lhs\\rhs\nplotSol(IGAmesh, sol0, \"Poisson2DSquare\")\nplotSolError(IGAmesh, sol0, exact_sol, \"Poisson2DSquareError\")\nrelL2Err, relH1Err = compErrorNorm(IGAmesh, sol0, exact_sol, deriv_exact_sol, a0, gauss_rule)\nprintln(\"Relative L2-norm error is $relL2Err\")\nprintln(\"Relative energy-norm error is $relH1Err\")\nprint(\"Done!\")\n", "meta": {"hexsha": "f61ac7d19594c02e62a736c5e6040228c9df5db0", "size": 1831, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Poisson2DSquare.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/Poisson2DSquare.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/Poisson2DSquare.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": 36.62, "max_line_length": 93, "alphanum_fraction": 0.7094483889, "num_tokens": 722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768541530197, "lm_q2_score": 0.9124361688107863, "lm_q1q2_score": 0.8615011114832017}}
{"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\nPT = 100\nPA = 150\nlifeT = 5\nlifeA = 5\nAT = 50\nAA = 62\nFT = 20\nFA = 30\n\n# Find\n# (a.) Construct a break even graph showing the present worth of each\n#      alternative as a function of interest rates between 6 percent and 20\n#      percent.\ni = collect(0.06:0.01:0.2)\nNPWT = -PT .+ AT * seriesPresentAmountFactor.(i, lifeT) .+ FT * presentWorthFactor.(i, lifeT)\nNPWA = -PA .+ AA * seriesPresentAmountFactor.(i, lifeA) .+ FA * presentWorthFactor.(i, lifeA)\n\nplot(i, NPWT, label=\"Model T\", xlabel=\"Interest Sensitivity (6%-20%)\",\n\tylabel=\"Present Worth (\\$1000)\",\n\ttitle=\"Sensitivity of Net Present Worth of Models T and A to Interest Rate\",\n\tpalette=cgrad(uwEngColorScheme))\nplot!(i, NPWA, label=\"Model A\")\n\n# (b.) Which is the preferred choice at 8 percent interest?\ni8 = findall(x->x == 0.08, i)\n@assert length(i8) == 1\ni8 = i8[1]\nNPWT_i8 = NPWT[i8]\nNPWA_i8 = NPWA[i8]\n\nif NPWT_i8 > NPWA_i8\n\tprintln(\"Model T is preferred because its NPW at i=8% is greater than that of Model A\")\nelse\n\tprintln(\"Model A is preferred because its NPW at i=8% is greater than that of Model T\")\nend\n\n# (c.) Which is the preferred choice at 16 percent interest?\ni16 = findall(x->x == 0.16, i)\n@assert length(i16) == 1\ni16 = i16[1]\nNPWT_i16 = NPWT[i16]\nNPWA_i16 = NPWA[i16]\n\nif NPWT_i16 > NPWA_i16\n\tprintln(\"Model T is preferred because its NPW at i=16% is greater than that of Model A\")\nelse\n\tprintln(\"Model A is preferred because its NPW at i=16% is greater than that of Model T\")\nend\n\n# (d.) What is the break-even interest rate?\nNPWT_func(interest) = -PT .+ AT * seriesPresentAmountFactor.(interest, lifeT) .+ FT * presentWorthFactor.(interest, lifeT)\nNPWA_func(interest) = -PA .+ AA * seriesPresentAmountFactor.(interest, lifeA) .+ FA * presentWorthFactor.(interest, lifeA)\nf(interest) = NPWT_func(interest) - NPWA_func(interest)\niBreakEven = find_zero(f, 0.11)\n\nprintln(\"The break even interest rate is roughly \", iBreakEven)\n", "meta": {"hexsha": "79f126b3d9383aafb3b47283959c8fdfb6d052f1", "size": 2120, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problems/ps8/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/ps8/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/ps8/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": 33.6507936508, "max_line_length": 144, "alphanum_fraction": 0.7075471698, "num_tokens": 694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122684798184, "lm_q2_score": 0.8991213874066956, "lm_q1q2_score": 0.8612794078494693}}
{"text": "## Exercise 6-5\n## The Ackermann function, A(m,n), is defined:\n\n##           \u23a7 n + 1  if m = 0\n## A(m, n) = \u23a8 A(m-1, 1) if m>0 &n = 0\n##           \u23a9 A(m-1, A(m, n-1)) if m>0 and n>0.  \n\n## See https://en.wikipedia.org/wiki/Ackermann_function. Write a function named ack that evaluates the Ackermann function. Use your function to evaluate ack(3, 4), which should be 125. What happens for larger values of m and n?\nprintln(\"Ans: \")\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    elseif m > 0 && n > 0\n        return ack(m - 1, ack(m, n -1 ))\n    end \nend\n\nprintln(ack(3, 4))\n\nprintln(\"End.\")\n", "meta": {"hexsha": "c038ef3e34c9f6b6b8bd54e0aa34372b36278662", "size": 658, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chapter6/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": "Chapter6/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": "Chapter6/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": 27.4166666667, "max_line_length": 227, "alphanum_fraction": 0.5577507599, "num_tokens": 236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9706877700966098, "lm_q2_score": 0.8872045907347108, "lm_q1q2_score": 0.8611986457997517}}
{"text": "using Test\nusing Plots\n\ninclude(\"../../lib/KTBC.jl\")\nusing .KTBC: CreateKTBC\n\nusing LinearAlgebra: I, SymTridiagonal, lu, cholesky, det, eigen, Diagonal, diag, diagm, PosDefException\n\n# 1\nK\u2084 = CreateKTBC(4)[1]\n\nL\u2090 = [\n  1 0 0 0\n  -1 / 2 1 0 0\n  0 -2 / 3 1 0\n  0 0 -3 / 4 1\n]\n\nU\u2090 = [\n  2 -1 0 0\n  0 3 / 2 -1 0\n  0 0 4 / 3 -1\n  0 0 0 5 / 4\n]\n\nL, U = lu(K\u2084)\n\n@test K\u2084 == L * U\n@test K\u2084 == L * Diagonal(U) * L'\n@test det(K\u2084) == 5\n\n# 3\nK\u2085 = CreateKTBC(4)[1]\n\n@test round.(det(K\u2085) * inv(K\u2085)) == [\n 4.0  3.0  2.0  1.0\n 3.0  6.0  4.0  2.0\n 2.0  4.0  6.0  3.0\n 1.0  2.0  3.0  4.0\n]\n\nL, U = lu(K\u2085)\ninvL = inv(L)\n\n@test K\u2085 == L * Diagonal(U) * L'\n\nfunction checkInvL(i::Int, j::Int)\n    return round(invL[i, j], digits=2) == round(j / i, digits=2)\nend\n\n@test checkInvL(3, 1)\n@test checkInvL(3, 2)\n@test checkInvL(4, 2)\n@test round(invL[4, 2], digits=1) == 1 / 2\n\n# 4\nd = (2:5) ./ (1:4)\n\nL = I(4) - diagm(-1 => (1:3) ./ (2:4))\n\nL * Diagonal(d) * L'\n\n# 9\nK\u2083, T\u2083, B\u2083, C\u2083 = CreateKTBC(3)\n\nA = cholesky(convert(Array{Float64}, K\u2083))\n@test round.(A.L * A.U) == K\u2083\n\nA = cholesky(convert(Array{Float64}, T\u2083))\n@test round.(A.L * A.U) == T\u2083\n\n@test_throws PosDefException cholesky(convert(Array{Float64}, B\u2083))\n\nB\u2091 = B\u2083 + eps() * I(3)\nA = cholesky(convert(Array{Float64}, B\u2091))\n@test round.(A.L * A.U) == round.(B\u2091)\n\n# 10\neye\u2084 = ones(4, 4)\neigen(eye\u2084)\n\n@test det(eye\u2084) == 0.0\n\nL = [\n  1\n  1\n  1\n  1\n]\n\n@test L * L' == eye\u2084\n\n# 11\nK = ones(4, 4) + I(4) / 100\nL, U = lu(K)\neigen(K)\ninv(K)\n\n# 12 \n# https://rosettacode.org/wiki/Pascal_matrix_generation#Julia\nfunction pascal(n::Int)\n    return [binomial(j + i, i) for i in 0:n, j in 0:n]\nend\n\n# https://en.wikipedia.org/wiki/Pascal_matrix\nfunction pascalL(n::Int)\n    return exp(diagm(-1 => 1:(n - 1)))\nend\n\nK = pascal(4)\nL, U = lu(K)\n\n@test det(K) == abs(reduce(*, diag(U)))\n\nL = pascalL(5)\n\n@test K == round.(L * L')\n\n# 13\nFib = [\n  1 1\n  1 0\n]\n\nv = [\n  1\n  0\n]\n\n@test Fib^6 * v == [\n  13\n  8\n]\n\n# 14\nL = [\n  1 0 0\n  3 1 0\n  0 2 1\n]\n\nU = [\n  2 8 0\n  0 3 5\n  0 0 7\n]\n\nf = [\n  0\n  3\n  6\n]\n\nc = L \\ f\nx = U \\ c\n\n@test x == round.(L * U \\ f)\n", "meta": {"hexsha": "947d9f2d5f33a898d1f52f5794e7ced1e24bf8ad", "size": 2061, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "1.AppliedLInearAlgebra/3.SolvingALinearSystem/Solutions.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/3.SolvingALinearSystem/Solutions.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/3.SolvingALinearSystem/Solutions.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": 13.0443037975, "max_line_length": 104, "alphanum_fraction": 0.5361475012, "num_tokens": 1041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075771731111, "lm_q2_score": 0.8947894583870631, "lm_q1q2_score": 0.8608837178888177}}
{"text": "## In this notebook, we'll look at least absolute deviation 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_ls = A\\b # solve the least squares problem\n\n## Solve the Least Absolute Deviation version\nusing Convex, SCS\nxvar = Variable(2)\nproblem = minimize(sum(abs(A * xvar - b)))\nsolve!(problem, SCSSolver(max_iters=20000))\nab_lad = xvar.value\n##\nusing Printf\nscatter(Xf[:,1],Xf[:,2],color=2,size=(300,300), label=\"\")\nplot!(x, x*ab_ls[1] .+ ab_ls[2], label=\"\",color=5)\nplot!(x, x*ab_lad[1] .+ ab_lad[2], label=\"\",color=6)\ntitle!(@sprintf(\"LS: height \u2248 %.2f weight + %.2f\\nLAD:  height \u2248 %.2f weight + %.2f    \",\nab_ls[1],ab_ls[2],ab_lad[1],ab_lad[2]), titlefontsize=12)\nxlabel!(\"Weight (kg)\")\nylabel!(\"Height (cm)\")\nsavefig(\"weight-height-fit-lad.pdf\")\n## Except, we actually filtered the data.\n# to remove an outlier\nscatter(X[:,1],X[:,2],color=2,size=(300,300), label=\"\",xlabel=\"weight (kg)\", ylabel=\"height (cm)\")\nsavefig(\"weight-height-outliers.pdf\")\n##\nx = X[:,1]\nA = [x ones(length(x))]\nb = X[:,2]\nab_ls = A\\b # solve the least squares problem\nxvar = Variable(2)\nproblem = minimize(sum(abs(A * xvar - b)))\nsolve!(problem, SCSSolver(max_iters=20000))\nab_lad = xvar.value\nscatter(X[:,1],X[:,2],color=2,size=(300,300), label=\"\")\nplot!(x, x*ab_ls[1] .+ ab_ls[2], label=\"\",color=5)\nplot!(x, x*ab_lad[1] .+ ab_lad[2], label=\"\",color=6)\ntitle!(@sprintf(\"LS: height \u2248 %.2f weight + %.2f\\nLAD:  height \u2248 %.2f weight + %.2f    \",\nab_ls[1],ab_ls[2],ab_lad[1],ab_lad[2]), titlefontsize=12)\nxlabel!(\"Weight (kg)\")\nylabel!(\"Height (cm)\")\nsavefig(\"weight-height-outliers-fit-lad.pdf\")\n", "meta": {"hexsha": "3d7b28c650c6352e2161e99535efa4dee8053615", "size": 1997, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "6-unit-5-demos/least-absolute-deviation.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/least-absolute-deviation.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/least-absolute-deviation.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": 33.2833333333, "max_line_length": 98, "alphanum_fraction": 0.6549824737, "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012732322215, "lm_q2_score": 0.9099070139780661, "lm_q1q2_score": 0.8605912123433836}}
{"text": "#############################\n##  These numerical experiments, included for the sake of completion,\n##  showcase some numerical solutions to LINEAR Volterra integral equations\n#############################\n\nusing ApproxFun, MultivariateOrthogonalPolynomials, BandedMatrices, BlockBandedMatrices, SpecialFunctions, Plots\nusing SparseVolterraExamples\n\n#####################################################\n## Solving Equation 18 in https://doi.org/10.1137/19M1267441\n## This is a linear Volterra integral equation of FIRST kind.\n#####################################################\n####\n## Set up g(x) and kernel K(x,y)\ng1(x)= exp(-x)/4+1/4*exp(x)*(-1+2*x)\nK(x,y) = exp(y-x)\n####\n## For linear problems the solver is wrapped into convenient functions. N is polynomial order of approximation.\nN = 20\nu = triVolterraEQ1FullKernelSolver(g1,K,N,true)\n####\n## Plot the computed and analytic solution\nplot(u,grid=false,ylabel=\"u(x)\",xlabel=\"x\",label=\"sparse method\")\nplot!(x->x*exp(x),0,1,grid=false,ylabel=\"u(x)\",xlabel=\"x\",label=\"analytic\")\n####\n## Plot error\nplot(triVolterraEQ1FullKernelSolver(g1,K,N,true)-Fun(x->x*exp(x),Jacobi(0,1,0..1)),ylabel=\"error\",xlabel=\"x\",grid=false,label=false)\n\n#####################################################\n## The following is a simple linear second kind Volterra integral equation, not appearing in either paper.\n## It uses the monomial coefficient vector input kernel implementation and limits of integration to 1-x instead and has analytically known solution sin(-2*pi*x).\n#####################################################\n####\n## Set up g(x) and kernel K(x,y)\ng2 = Fun(x->(x-1)/(2*pi)*cos(-2*pi*x)+(4*pi^2+1)/(4*pi^2)*sin(2*pi*(1-x)), Jacobi(0,1,0..1))\nK2 = [0.,1.,0.,0.] # this is equivalent to K(x,y)=y\n####\n## Compute and plot solutions\nN = 20\nu = triVolterraEQ2Solver(g2,K2,N,false) # note the false indicating that we are not flipping the integration bounds, i.e. we are integrating from 0 to 1-x\nplot(u,grid=false,ylabel=\"u(x)\",xlabel=\"x\",label=\"sparse method\")\nplot!(x->sin(-2*pi*x),0,1,grid=false,ylabel=\"u(x)\",xlabel=\"x\",label=\"analytic\")\n####\n## Plot errors\nplot(triVolterraEQ2Solver(g2,K2,N,false)-Fun(x->sin(-2*pi*x),Jacobi(0,1,0..1)),grid=false,ylabel=\"error\",xlabel=\"x\",label=false)\n####\n## The above is equivalent to the following much simpler input, which uses the full kernel input as a function\nu2 = triVolterraEQ2FullKernelSolver(g2,(x,y)->y,N,false)\n####\n## Verify the two input methods give the same answer\nplot(x->abs(u2(x)-u(x)),0,1,grid=false,ylabel=\"difference\",xlabel=\"x\",label=false)\n", "meta": {"hexsha": "dfab21e7dba0c7c8fea3ad3b393ad3dd2c79fcf1", "size": 2555, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Example 0 - Some linear Volterra integral equation examples.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/Example 0 - Some linear Volterra integral equation examples.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/Example 0 - Some linear Volterra integral equation examples.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": 49.1346153846, "max_line_length": 161, "alphanum_fraction": 0.6399217221, "num_tokens": 693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377261041521, "lm_q2_score": 0.8976952996340946, "lm_q1q2_score": 0.8604748112456505}}
{"text": "using SparseArrays, DiffEqOperators, LinearAlgebra, Random,\n      Test, BandedMatrices, FillArrays\n\nimport DiffEqOperators: BoundaryPaddedVector\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# 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\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 -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\n\n# The following test-sets test for the correctness of the convolutions against\n# AbstractVector and BoundaryPaddedArray in one dimension.\n\n@testset \"L.boundary_point_count is zero\" begin\n    N = 20\n    L = CenteredDifference(2, 2, 1.0, N)\n    cl = rand()\n    cr = rand()\n    u = rand(N)\n    Qu = BoundaryPaddedVector(cl, cr, u)\n    arrayQu = [cl;u;cr]\n\n    # Check that BoundaryPaddedVector is constructed correctly\n    @test Qu == arrayQu\n\n    # Test for correctness of DerivativeOperator*AbstractVector\n    @test second_derivative_stencil(N)*arrayQu \u2248 L*arrayQu\n\n    # Test for correctness of DerivativeOperator*BoundaryPaddedVector\n    @test second_derivative_stencil(N)*arrayQu \u2248 L*Qu\nend\n\n@testset \"Fourth Derivative and Approximation Order Test\" begin\n    N = 20\n    L = CenteredDifference(4, 4, 1.0, N)\n    cl = rand()\n    cr = rand()\n    u = rand(N)\n    Qu = BoundaryPaddedVector(cl, cr, u)\n    arrayQu = [cl;u;cr]\n\n    # Check that BoundaryPaddedVector is constructed correctly\n    @test Qu == arrayQu\n\n    # Test for correctness of DerivativeOperator*AbstractVector\n    @test fourth_deriv_approx_stencil(N)*arrayQu \u2248 L*arrayQu\n\n    # Test for correctness of DerivativeOperator*BoundaryPaddedVector\n    @test fourth_deriv_approx_stencil(N)*arrayQu \u2248 L*Qu\nend\n", "meta": {"hexsha": "8ad1c651bd7563db0125981e87534b5d503650f7", "size": 2411, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/DerivativeOperators/convolutions.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/convolutions.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/convolutions.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": 29.4024390244, "max_line_length": 79, "alphanum_fraction": 0.6457901286, "num_tokens": 889, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741254760638, "lm_q2_score": 0.9032942132122422, "lm_q1q2_score": 0.8604546951982408}}
{"text": "begin \n  import Pkg; Pkg.activate(\".\")\n  Pkg.add(\"DifferentialEquations\")\n  Pkg.add(\"Optim\")\nend\n\nusing DifferentialEquations, Plots\n\n\n\nfunction f(du,u,p,t)\n  du[1] = u[2]\n  du[2] = -p\nend\n\nu\u2080 = [50.0,0.0]\ntspan = (0.0,15.0)\np = 9.8\n\nprob = ODEProblem(f,u\u2080,tspan, p)\nsol = solve(prob,Tsit5())\nplot(sol, label = [\"Displacement\" \"Velocity\"],\n  xlabel=\"Time (s)\", \n  ylabel=\"Displacement (m) | Velocity (m/s)\")\n\n\n# But where is the ground?\nfunction condition(u,t,integrator) # Event when event_f(u,t) == 0\n  u[1]\nend\n\nfunction affect!(integrator)\n  integrator.u[2] = -integrator.u[2]\nend\n\ncb = ContinuousCallback(condition,affect!, save_positions=(false, false))\n\nsol = solve(prob,Tsit5(), callback=cb)\nplot(sol, label = [\"Displacement\" \"Velocity\"], \n  xlabel=\"Time (s)\", \n  ylabel=\"Displacement (m) | Velocity (m/s)\")\n\n\n### Air resistance\nfunction f\u2082(du,u,p,t)\n  g, Cd = p\n  du[1] = u[2]\n  du[2] = -(g+u[2]^2*Cd*sign(u[2])) \nend\n\np = (9.81, 15e-2)\n\nprob = ODEProblem(f\u2082, u\u2080,tspan, p)\nsol = solve(prob, Tsit5(), callback=cb)\n\nplot(sol, label = [\"Displacement\" \"Velocity\"], \n  xlabel=\"Time (s)\", \n  ylabel=\"Displacement (m) | Velocity (m/s)\")\n\n\n### Optim.jl\nusing Optim\n\nfunction compute_ODE(p; times=1:0.5:15)\n  prob = ODEProblem(f\u2082, u\u2080,tspan, p)\n  sol = solve(prob, Tsit5(), saveat=times, callback = cb)\n  return sol.t , hcat(sol.u...)[1,:]\nend\n\ntime, exp_disp = compute_ODE((9.81, 5e-2)) \nexp_disp .+= 0.75randn(length(exp_disp)) # add noise\n\nscatter(time, exp_disp, label=\"Experiment\", xlabel=\"Time(s)\", ylabel=\"Displacement (m)\")\n\nfunction objective(Cd) \n  _, sim_disp = compute_ODE((9.81, Cd[1]))\n  return sum((sim_disp.- exp_disp).^2)\nend\n\nres = optimize(objective, [5e-3], Newton(), Optim.Options(store_trace=true, extended_trace=true))\nCd = res.minimizer[1]\n\nplot!(compute_ODE((9.81, Cd); times=0:0.1:15), label=\"Simulated\")\n\n### Visual\nfor iteration in res.trace[1:10]\n  Cd = iteration.metadata[\"x\"][1]\n  pl = scatter(time, exp_disp, label=\"Experiment\", xlabel=\"Time(s)\", ylabel=\"Displacement (m)\")\n  plot!(pl, compute_ODE((9.81, Cd); times=0:0.1:15), label=\"Simulated (Cd: $Cd\")\n  display(pl)\n  sleep(1.0)\nend\n\n\n", "meta": {"hexsha": "54b8d24eaed3ab4d87424a5d9a7e88424a658dee", "size": 2119, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/intermezzo-diffeq-optim.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": "scripts/intermezzo-diffeq-optim.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": "scripts/intermezzo-diffeq-optim.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": 22.3052631579, "max_line_length": 97, "alphanum_fraction": 0.6503067485, "num_tokens": 734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741281688025, "lm_q2_score": 0.9032942014971871, "lm_q1q2_score": 0.8604546864711176}}
{"text": "x = rand(1:100, 5)\nprintln(\"Sum of \", x, \" = \", sum(x))\n\nA = rand(-100:100, 3, 5)\n\nsum(A, dims=1)\n\nsum(A, dims=2)\n\nsum(A, dims=1)[:]\n\nx = rand(1:100, 5)\ndisplay(x)\nprod(x)                         # Product of all elements\n\ndisplay(A)\ndisplay(maximum(A, dims=1))     # Largest element in each column\ndisplay(minimum(A, dims=1))     # Smallest element in each column\n\nx = 1:5\ndisplay(cumsum(x))                   # Cumulative sum, that is, entry n is the sum of x_1,...,x_n\ndisplay(cumprod(x))                  # Cumulative product\n\nA = reshape(1:6, 2, 3)\n\ncumsum(A, dims=1)                    # Cumulative sum along dimension 1 (that is, column-wise)\n\ncumprod(A, dims=2)                   # Cumulative product along dimension 2\n\nfunction taylor_cos(x,n)\n    factors = [ -x^2 / ((2k-1) * 2k) for k = 1:n ]\n    y = 1 + sum(cumprod(factors))\nend\n\nprintln(taylor_cos(10, 50)) # Taylor approximation\nprintln(cos(10))            # true value\n\nxx = -10:0.01:10\nyy = cos.(xx)\nyy_taylor = [ taylor_cos(x,n) for x in xx, n in 0:5 ]\n\nusing PyPlot\nplot(xx, yy, linewidth=2, color=\"k\")\nplot(xx, yy_taylor)\ngrid(true)\naxis([-10,10,-1.2,1.2]);\n\nx = 1:2:1000                 # Odd numbers\nprintln(503 in x)            # True, 503 is in the list\nprintln(1000 \u2208 x)            # False, 1000 is not in the list\n\nprintln(all(x .< 500))\nprintln(all(x .> 0))\n\nprintln(any(x .== 503))\nprintln(any(x .== 1000))\n\nidx = findfirst(x .== 503)    # Index in x with the value 503\n\nind = findall(@. x % 97 == 0)\nprintln(\"Indices in x with numbers that are multiples of 97: \", ind)\n\ncount(@. x % 97 == 0)\n", "meta": {"hexsha": "e77debe4148d9b9ba690fd5806ae31cfd79757a9", "size": 1571, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "textbook/_build/jupyter_execute/content/Vectorization/Array_Functions.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/Vectorization/Array_Functions.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/Vectorization/Array_Functions.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": 24.546875, "max_line_length": 97, "alphanum_fraction": 0.5779758116, "num_tokens": 527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951643678381, "lm_q2_score": 0.9207896764343916, "lm_q1q2_score": 0.8603814210601217}}
{"text": "# Load X and y variable\r\nusing JLD\r\ndata = load(\"logisticData.jld\")\r\n(X,y) = (data[\"X\"],data[\"y\"])\r\n\r\n# Add bias variable, initialize w, set regularization and optimization parameters\r\n(n,d) = size(X)\r\nX = [ones(n,1) X]\r\nd += 1\r\nw = zeros(d,1)\r\nlambda = 1\r\nmaxPasses = 500\r\nprogTol = 1e-4\r\nverbose = true\r\n\r\n## Run and time coordinate descent to minimize L2-regularization logistic loss\r\n\r\n# Start timer\r\ntic()\r\n\r\n# Compute Lipschitz constant of 'f'\r\n(eigenvalues,~) = eig(X'*X)\r\nL = .25*maximum(eigenvalues) + lambda;\r\n\r\n# Start running coordinate descent\r\nw_old = copy(w);\r\nfor k in 1:maxPasses*d\r\n\r\n    # Choose variable to update 'j'\r\n    j = rand(1:d)\r\n\r\n    # Compute partial derivative 'g_j'\r\n    yXw = y.*(X*w);\r\n    sigmoid = 1./(1+exp.(-yXw));\r\n    g = -X'*(y.*(1-sigmoid)) + lambda*w;\r\n    g_j = g[j];\r\n\r\n    # Update variable\r\n    w[j] -= (1/L)*g_j;\r\n\r\n    # Check for lack of progress after each \"pass\"\r\n    if mod(k,d) == 0\r\n        yXw = y.*(X*w)\r\n        f = sum(log.(1 + exp.(-y.*(X*w)))) + (lambda/2)norm(w)^2\r\n        delta = norm(w-w_old,Inf);\r\n        if verbose\r\n            @printf(\"Passes = %d, function = %.4e, change = %.4f\\n\",k/d,f,delta);\r\n        end\r\n        if delta < progTol\r\n            @printf(\"Parameters changed by less than progTol on pass\\n\");\r\n            break;\r\n        end\r\n        w_old = copy(w);\r\n    end\r\n\r\nend\r\n\r\n# End timer\r\ntoc()\r\n", "meta": {"hexsha": "2b4ca54c493f0515308b321e1ca5e722c1916f40", "size": 1381, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "a2/example_CD.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": "a2/example_CD.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": "a2/example_CD.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.0166666667, "max_line_length": 82, "alphanum_fraction": 0.5510499638, "num_tokens": 428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338035725359, "lm_q2_score": 0.8947894527758053, "lm_q1q2_score": 0.8603703059241081}}
{"text": "A = rand(-4:4,5,3)\nB = rand(-4:4,3,4)\n\nC = A*B\n\nC[2,3]\n\nm = 5; n = 3; p = 4;\nC = zeros(m,p);\nfor i = 1:m\n    for j = 1:p\n        for k = 1:n\n            C[i,j] += A[i,k]*B[k,j]\n        end\n    end\nend\n\nC\n\nm = 5; n = 3; p = 4;\nC = zeros(m,p);\nfor i = 1:m\n    for j = 1:p\n        C[i,j] = sum( A[i,k]*B[k,j] for k = 1:n );\n    end\nend\nC\n\nm = 5; n = 3; p = 4;\nC = [ sum( A[i,k]*B[k,j] for k = 1:n ) for i=1:m, j=1:p ]\n\n\n# C is a matrix of inner products\ni=2; j=3;\nusing LinearAlgebra\ndot(A[i,:],B[:,j])\nC = [ dot(A[i,:],B[:,j]) for i=1:m, j=1:p ]\n\n# C columnwise is a linear combination of columns\nC[:,j]\nsum( B[k,j]*A[:,k] for k=1:n  )\nhcat( [ sum( B[k,j]*A[:,k] for k=1:n  ) for j=1:p ]... )\nq = [ sum( B[k,j]*A[:,k] for k=1:n  ) for j=1:p ];\nhcat(q[1],q[2],q[3],q[4])\n\nlength(C)\n\nlength(q)\n\n# C is a sum of outer products\nsum( A[:,k]*B[k,:]' for k=1:n)\n\nB[1,:]'\n\n(B[1,:]')'\n", "meta": {"hexsha": "9b6be9990650615ca672a0f5d2db4c222288f505", "size": 874, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "daily/daily-08-28.jl", "max_stars_repo_name": "tobydriscoll/udmath612", "max_stars_repo_head_hexsha": "3d5d86d2e153ee93e0de7b0f720ce2af354303e6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-09-25T14:12:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-01T06:11:06.000Z", "max_issues_repo_path": "daily/daily-08-28.jl", "max_issues_repo_name": "tobydriscoll/udmath612", "max_issues_repo_head_hexsha": "3d5d86d2e153ee93e0de7b0f720ce2af354303e6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "daily/daily-08-28.jl", "max_forks_repo_name": "tobydriscoll/udmath612", "max_forks_repo_head_hexsha": "3d5d86d2e153ee93e0de7b0f720ce2af354303e6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-11-01T06:11:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-03T03:47:34.000Z", "avg_line_length": 15.6071428571, "max_line_length": 57, "alphanum_fraction": 0.4508009153, "num_tokens": 416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768541530198, "lm_q2_score": 0.9111796997610798, "lm_q1q2_score": 0.8603147824885095}}
{"text": "\r\nstruct LineSearchOptions\r\n    sufficient_decrease::Float64\r\n    curvature::Float64\r\n    max_iter::Int\r\nend\r\n\r\nfunction LineSearchOptions(; sufficient_decrease = 1e-4, curvature = 0.1, max_iter = 100)\r\n    LineSearchOptions(sufficient_decrease, curvature, max_iter)\r\nend\r\n\r\n\r\nfunction line_search(\r\n    fcn,\r\n    x0,\r\n    step_direction,\r\n    f0 = fcn(x0),\r\n    search_options::LineSearchOptions = LineSearchOptions())\r\n# suff_decrease = 1e-4, curvature = 0.1, max_iter = 100)\r\n\r\n    # rename for ease of refactoring\r\n    suff_decrease = search_options.sufficient_decrease\r\n    curvature     = search_options.curvature\r\n    max_iter      = search_options.max_iter\r\n\r\n    # strong wolfe condition\r\n    step_size_prev = zero(eltype(x0))\r\n    step_size      = one(eltype(x0))\r\n    step_size_lo   = step_size_prev\r\n    step_size_hi   = step_size_prev\r\n    f_prev         = NaN\r\n    dphi0          = numder.directional_diff_fw(fcn, x0, step_direction)\r\n\r\n    # bracket phase\r\n    for iter = 1:max_iter\r\n\r\n        f1 = fcn(x0 + step_direction * step_size)\r\n        if f1 > f0 + suff_decrease * step_size * dphi0 || (iter > 1 && f1 >= f_prev)\r\n            step_size_lo, step_size_hi = step_size_prev, step_size\r\n            break\r\n        end\r\n\r\n        dphi = numder.directional_diff_fw(fcn, x0 + step_direction * step_size, step_direction)\r\n        if abs(dphi) <= abs(dphi0) * curvature\r\n            return step_size\r\n        elseif dphi >= 0\r\n            step_size_lo, step_size_hi = step_size, step_size_prev\r\n            break\r\n        end\r\n\r\n        f_prev = f1\r\n        step_size_prev, step_size = step_size, step_size * 2\r\n    end\r\n\r\n    # zoom phase\r\n    f_lo = fcn(x0 + step_size_lo * step_direction)\r\n    for iter = 1:max_iter\r\n        step_size = 0.5 * (step_size_lo + step_size_hi)\r\n        f1 = fcn(x0 + step_size * step_direction)\r\n        if f1 > f0 + suff_decrease * step_size * dphi0 || f1 >= f_lo\r\n            step_size_hi = step_size\r\n        else\r\n            dphi = numder.directional_diff_fw(fcn, x0 + step_direction * step_size, step_direction)\r\n            if abs(dphi) <= abs(dphi0) * curvature\r\n                return step_size\r\n            elseif dphi * (step_size_hi - step_size_lo) >= 0\r\n                step_size_hi = step_size_lo\r\n            end\r\n            step_size_lo = step_size\r\n        end\r\n\r\n    end\r\n\r\n    return step_size\r\nend\r\n\r\n\r\n\r\n#=\r\nfunction armijo_backtracking(fcn, x0, direction, f0 = fcn(x0), alpha_0 = 1, step_factor = 0.5, max_iteration = 20, beta = 1e-4)\r\n    # sufficient decrease condition shall be satisfied\r\n    phi_0 = f0\r\n    dphi_dalpha_0 = NumDiff.directional_diff_fw(fcn, x0, direction)\r\n\r\n    alpha = alpha_0\r\n    for iter = 1:max_iteration\r\n        phi_alpha = fcn( x0 + direction .* alpha)\r\n        if phi_alpha <= phi_0 + beta * alpha * phi_alpha\r\n            break\r\n        end\r\n        alpha = alpha * step_factor\r\n    end\r\nend\r\n=#\r\n\r\n", "meta": {"hexsha": "1bcc45f161867dc665ea8a13ac6801bdc97124a9", "size": 2899, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "__lib__/math/opti/src/line_search.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/line_search.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/line_search.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": 30.1979166667, "max_line_length": 128, "alphanum_fraction": 0.6095205243, "num_tokens": 787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545274901876, "lm_q2_score": 0.9073122238669025, "lm_q1q2_score": 0.8602721929065942}}
{"text": "## Exercise 7-2\n## Copy the loop from Square Roots and encapsulate it in a function called mysqrt that takes a as a parameter, chooses a reasonable value of x, and returns an estimate of the square root of a.\n\nfunction mysqrt(a, x)\n    a = float(a)\n    while true\n        y = (x + a/x) / 2\n        if y == x\n            break\n        end\n        x = y\n    end\n    return x\nend\n\n## To test it, write a function named testsquareroot that prints a table like this:\n# see ex 7-2 in book\nprintln(\"Ans: \")\n\nfunction rightjustify(string::String, chr)\n    if chr - length(string) > 0 \n        return ' ' ^ (chr - length(string)) * string\n    end \n    return string\nend \n\nfunction testsquareroot()\n    println(\"a   mysqrt             sqrt               diff\")\n    println(\"-   ------             ----               ----\")\n    for i in 1:10\n        i = float(i)\n        root = sqrt(i)\n        root_my = mysqrt(i, i/2)\n        println(\n            string(i) * \" \" * \n            rightjustify(string(root_my), 18) * \n            \" \" * \n            rightjustify(string(root), 18) * \" \" * string(abs(root_my - root)))\n    end\nend\n\ntestsquareroot()\n\nprintln(\"End.\")\n", "meta": {"hexsha": "6cf047f304469401f40daf8b6e3581fda81a2b22", "size": 1151, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chapter7/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": "Chapter7/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": "Chapter7/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": 25.5777777778, "max_line_length": 192, "alphanum_fraction": 0.5369244136, "num_tokens": 307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299632771662, "lm_q2_score": 0.9294404091874837, "lm_q1q2_score": 0.8599461156608499}}
{"text": "# hann.jl\n# Hann window function\n\n\n\"\"\"\n    hann(x::AbstractFloat)\nHann window function (often called \"Hanning\" window function).\nThis version is `0.5 * (1 + cospi(2x))` and used in `[-0.5,+0.5]`.\nhttps://en.wikipedia.org/wiki/Hann_function\n\"\"\"\nhann(x::AbstractFloat) = 0.5 * (1 + cospi(2x))\n\n\n\"\"\"\n    hann(n::Int)\nReturn vector of `n \u2265 2` samples of Hann window function\nequally spaced over `[-0.5,+0.5]`.\nThe first and last samples are zero for `n \u2265 2`.\n\nCaution.\nMatlab has both `hann` and `hanning` functions for which\n`[0; hanning(n); 0] == hann(n+2)`.\n\n`DSP.hanning(n)` == Matlab.hann(n)`\nwhereas\n`Sound.hann(n) == Matlab.hanning(n)`.\n\"\"\"\nhann(n::Int) = hann.(LinRange(-0.5, 0.5, n+2))[2:end-1]\n", "meta": {"hexsha": "4f4d9361fcd111f427ef79b825299e393e7e7cc6", "size": 700, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/hann.jl", "max_stars_repo_name": "JeffFessler/Sound.jl", "max_stars_repo_head_hexsha": "dd9177669e81b74bf5c3e85fb23ac41bd45af4c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-11-27T13:53:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-09T19:55:57.000Z", "max_issues_repo_path": "src/hann.jl", "max_issues_repo_name": "JeffFessler/Sound.jl", "max_issues_repo_head_hexsha": "dd9177669e81b74bf5c3e85fb23ac41bd45af4c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2021-11-27T13:44:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T19:26:46.000Z", "max_forks_repo_path": "src/hann.jl", "max_forks_repo_name": "JeffFessler/Sound.jl", "max_forks_repo_head_hexsha": "dd9177669e81b74bf5c3e85fb23ac41bd45af4c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-02T12:33:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T12:33:00.000Z", "avg_line_length": 24.1379310345, "max_line_length": 66, "alphanum_fraction": 0.6414285714, "num_tokens": 245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9658995772325382, "lm_q2_score": 0.8902942304882371, "lm_q1q2_score": 0.8599348208411561}}
{"text": "using Random, Distributions, KernelDensity, Plots, LaTeXStrings; pyplot()\nRandom.seed!(1)\n\nfunction tStat(mu0,mu,sig,n)\n    sample = rand(Normal(mu,sig),n)\n    xBar   = mean(sample)\n    s      = std(sample)\n    (xBar-mu0)/(s/sqrt(n))\nend\n\nmu0, mu1A, mu1B = 20, 22, 24\nsig, n = 7, 5\nN = 10^6\nalpha = 0.05\n\ndataH0  = [tStat(mu0,mu0,sig,n) for _ in 1:N]\ndataH1A = [tStat(mu0,mu1A,sig,n) for _ in 1:N]\ndataH1B = [tStat(mu0,mu1B,sig,n) for _ in 1:N]\ndataH1C = [tStat(mu0,mu1B,sig,2*n) for _ in 1:N]\ndataH1D = [tStat(mu0,mu1B,sig/2,2*n) for _ in 1:N]\n\ntCrit = quantile(TDist(n-1),1-alpha)\nestPwr(sample) = sum(sample .> tCrit)/N\n\nprintln(\"Rejection boundary: \", tCrit)\nprintln(\"Power under H0:  \", estPwr(dataH0))\nprintln(\"Power under H1A: \", estPwr(dataH1A))\nprintln(\"Power under H1B (mu's farther apart): \", estPwr(dataH1B))\nprintln(\"Power under H1C (double sample size): \", estPwr(dataH1C))\nprintln(\"Power under H1D (like H1C but std/2): \", estPwr(dataH1D))\n\nkH0  = kde(dataH0)\nkH1A = kde(dataH1A)\nkH1D = kde(dataH1D)\nxGrid = -10:0.1:15\n\nplot(xGrid,pdf(kH0,xGrid),\n\tc=:blue, label=\"Distribution under H0\")\nplot!(xGrid,pdf(kH1A,xGrid),\n\tc=:red, label=\"Distribution under H1A\")\nplot!(xGrid,pdf(kH1D,xGrid),\n\tc=:green, label=\"Distribution under H1D\")\nplot!([tCrit,tCrit],[0,0.4], \n\tc=:black, ls=:dash, label=\"Critical value boundary\", \n\txlims=(-5,10), ylims=(0,0.4), xlabel=L\"\\Delta = \\mu - \\mu_0\")", "meta": {"hexsha": "946d212f889220bb4281f47a425a54f5123745bd", "size": 1392, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "7_chapter/power.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/power.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/power.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.9333333333, "max_line_length": 73, "alphanum_fraction": 0.6659482759, "num_tokens": 569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995713428385, "lm_q2_score": 0.8902942319436397, "lm_q1q2_score": 0.8599348170033633}}
{"text": "using SpecialFunctions, Distributions, Roots, Plots, LaTeXStrings; pyplot()\n\neq(alpha, xb, xbl) = log(alpha) - digamma(alpha) - log(xb) + xbl\n\nactualAlpha, actualLambda = 2, 3\ngammaDist = Gamma(actualAlpha,1/actualLambda)\n\nfunction mle(sample)\n    alpha  = find_zero( (a)->eq(a,mean(sample),mean(log.(sample))), 1)\n    lambda = alpha/mean(sample)\n    return [alpha,lambda]\nend\n\nN = 10^4\n\nmles10   = [mle(rand(gammaDist,10)) for _ in 1:N]\nmles100  = [mle(rand(gammaDist,100)) for _ in 1:N]\nmles1000 = [mle(rand(gammaDist,1000)) for _ in 1:N]\n\nscatter(first.(mles10), last.(mles10), \n\tc=:blue, ms=1, msw=0, label=\"n = 10\")\nscatter!(first.(mles100), last.(mles100), \n\tc=:red, ms=1, msw=0, label=\"n = 100\")\nscatter!(first.(mles1000), last.(mles1000), \n\tc=:green, ms=1, msw=0, label=\"n = 1000\", \n\txlims=(0,6), ylims=(0,8), xlabel=L\"\\alpha\", ylabel=L\"\\lambda\")", "meta": {"hexsha": "20e03ab8a43de6e7b84bd2d570ad77415d98d1d4", "size": 854, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "5_chapter/mleGamma.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/mleGamma.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/mleGamma.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.8461538462, "max_line_length": 75, "alphanum_fraction": 0.6592505855, "num_tokens": 320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517083920617, "lm_q2_score": 0.8947894668039496, "lm_q1q2_score": 0.8598494667764773}}
{"text": "export dde_stability\n\n\"\"\"\n    dde_stability(A, B, \u03c4; N=10)\n\nCalculate (a finite number of) the characteristic roots of the linear delay differential\nequation\n\n```math\nx'(t) = Ax(t) + Bx(t-\u03c4)\n```\n\nwhere `A` and `B` can be (square) matrices. `N` controls the order of the Chebyshev\npolynomial approximation to the infinitesimal generator; higher values of `N` result in a\nmore accurate approximation. A property of the algorithm used is that characteristic roots\nclosest to the origin are approximated best.\n\n## Reference\n\nPseudospectral Differencing Methods for Characteristic Roots of Delay Differential\nEquations; D. Breda, S. Maset, and R. Vermiglio, SIAM Journal on Scientific Computing 2005\n27:2, 482-495\n\"\"\"\nfunction dde_stability(A, B, \u03c4; N=10)\n    @assert size(A) == size(B)\n    @assert size(A, 1) == size(A, 2)\n    T = eltype(A) == Int ? Float64 : eltype(A)\n    n = size(A, 1)\n    (x, D) = cheb_diff(T, N)\n    M = kron(-D, Matrix(I / convert(T, \u03c4), n, n))\n    M[1:n, 1:n] .= A\n    M[1:n, (n + 1):(end - n)] .= 0\n    M[1:n, (end - n + 1):end] .= B\n    return eigen(M)\nend\n\n# Tests\n# 1. x'(t) = 2x(t) - exp(1)*x(t - 1) has a double root at \u03bb = 1\n# 2. x'(t) = -x(t - \u03c4) goes unstable at \u03c4=\u03c0/2\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", "meta": {"hexsha": "2a5540f58deb05483d1b0b66cfde51a3e88fe5bf", "size": 1613, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/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": "src/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": "src/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": 31.6274509804, "max_line_length": 90, "alphanum_fraction": 0.5840049597, "num_tokens": 624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.950410982634296, "lm_q2_score": 0.9046505299595162, "lm_q1q2_score": 0.8597897991194605}}
{"text": "using Test, SpikeSynchrony\n\n####### ANALYTICAL TEST ########\ny1 = [1]\ny2 = [2]\nta = [0, 0, 1, 1, 2, 2, 3, 3]\n# I calculated S by hand for these trains:\nSa = [0, 0, 5//9, 3//8, 3//8, 5//9, 0, 0]\n\nt, S = SPIKE_distance_profile(y1, y2; tf = 3)\n@test t == ta\n@test S \u2248 Sa    atol = 1e-15\n\nD_S_a = sum( 1//2 * (Sa[2:end] .+ Sa[1:end-1]) .* (ta[2:end] .- ta[1:end-1]))//(ta[end] - ta[1])\nD_S = SpikeSynchrony.trapezoid_integral(t, S)/(t[end] - t[1])\n@test D_S \u2248 D_S_a    atol = 1e-15\n\n####### Second Analytic test ########\ny1 = [2.0, 5.0, 8.0]\ny2 = [1, 5, 9]\nt, S  = SPIKE_distance_profile(y1, y2; t0 = 0, tf = 10)\n\nanalytic_t = [0, 1, 2, 5, 8, 9, 10]\nanalytic_S = [0, 0, 0.555555555555555580,  0.222222222222222210,\n11/36, 25/98, 0, 0, 25/98, 11/36, 0.222222222222222210,  0.555555555555555580, 0, 0]\n\n@test S \u2248 analytic_S  atol = 1e-15\n\n####### TEST WITH ARBITRARY REAL DATA ########\nt0 = 0; tf = 500\ny1 = cumsum(rand(10:10:tf, 100))\ny2 = cumsum(rand(10:10:tf, 100))\nt, S  = SPIKE_distance_profile(y1, y2)\nt, S2 = SPIKE_distance_profile(y2, y1)\nt, S0 = SPIKE_distance_profile(y1, y1)\n# tr, Sr = SPIKE_distance_profile(abs.(reverse(y1) .- y1[end]), abs.(reverse(y1) .- y1[end]),\n\n# Fundamental tests from the definition of S and D_S\n@test issorted(t)\n@test (0 .\u2264 S) == trues(length(S))\n@test S == S2\n@test S0 == zeros(length(S0))\n\nD_S = SpikeSynchrony.trapezoid_integral(t, S)/(t[end]-t[1]) # == SPIKE_distance(y1, y2)\n@test 0 \u2264 D_S \u2264 1\n", "meta": {"hexsha": "4839ebba60a3cb552dee17b8f510f51cbab96713", "size": 1432, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/SPIKEdistance_tests.jl", "max_stars_repo_name": "JuliaNeuroscience/SpikeSynchrony.jl", "max_stars_repo_head_hexsha": "c88e97c6581c33d15f198711eacc8e859bdd8db7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-10-30T01:27:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T12:36:47.000Z", "max_issues_repo_path": "test/SPIKEdistance_tests.jl", "max_issues_repo_name": "JuliaNeuroscience/SpikeSynchrony.jl", "max_issues_repo_head_hexsha": "c88e97c6581c33d15f198711eacc8e859bdd8db7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2022-01-07T13:34:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-10T02:38:45.000Z", "max_forks_repo_path": "test/SPIKEdistance_tests.jl", "max_forks_repo_name": "russelljjarvis/SpikeSynchrony.jl", "max_forks_repo_head_hexsha": "2d000b8db1c78bcaa16e4173e456a2fcf321a36e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-09-05T13:19:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-23T01:06:34.000Z", "avg_line_length": 31.1304347826, "max_line_length": 96, "alphanum_fraction": 0.6033519553, "num_tokens": 635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475762847495, "lm_q2_score": 0.9111797027760038, "lm_q1q2_score": 0.8595591641736017}}
{"text": "\nusing LinearAlgebra\nusing Statistics: mean, median\n\n#TODO\n# R2-Score, Variance-Score, Deviance related functions\n\nexport max_error, mean_absolute_error, mean_squared_error, mean_squared_log_error, median_absolute_error, mean_absolute_percentage_error\n\n\"\"\"\n```max_error(y_true, y_pred)```\nReturn the maximum residual error.\n\n## Arguments\n- `y_true` : Ground truths\n- `y_pred` : Predictions\n\n\"\"\"\nmax_error(y_true, y_pred) = maximum(abs.(convert_1d(y_true) .- convert_1d(y_pred)))\n\n\"\"\"\n```mean_absolute_error(y_true, y_pred; keywords)```\nReturn the mean absolute error.\n\n## Arguments\n- `y_true` : Ground truths\n- `y_pred` : Predictions\n\n## Keywords\n- `weights` : Sample weights\n\n\"\"\"\nfunction mean_absolute_error(y_true, y_pred; weights = nothing)\n    _validate_distance_input(y_true, y_pred, weights)\n    result = abs.(y_true .- y_pred)\n    result = weights == nothing ? mean(result) : mean(result .* weights)\n    return result\nend\n\n\"\"\"\n```mean_squared_error(y_true, y_pred; keywords)```\nReturn the mean squared error.\n\n## Arguments\n- `y_true` : Ground truths\n- `y_pred` : Predictions\n\n## Keywords\n- `weights` : Sample weights\n- `squared = false` : Denotes whether or not to execute the last squaring operation\n\"\"\"\nfunction mean_squared_error(y_true, y_pred; weights = nothing, squared = false)\n    _validate_distance_input(y_true, y_pred, weights)\n    result = (y_true .- y_pred) .^ 2\n    result = !squared ? sqrt.(result) : result\n    return weights == nothing ? mean(result) : mean(result .* weights)\nend\n\n\"\"\"\n```mean_squared_log_error(y_true, y_pred; keywords)```\nReturn the mean squared log error.\n\n## Arguments\n- `y_true` : Ground truths\n- `y_pred` : Predictions\n\n## Keywords\n- `weights` : Sample weights\n\n\"\"\"\nmean_squared_log_error(y_true, y_pred; weights = nothing) = mean_squared_error(log.(1 .+ y_true), log.(1 .+ y_pred); weights = weights)\n\n\"\"\"\n```median_absolute_error(y_true, y_pred; keywords)```\nReturn the median absolute error.\n\n## Arguments\n- `y_true` : Ground truths\n- `y_pred` : Predictions\n\n## Keywords\n- `weights` : Sample weights\n\n\"\"\"\nfunction median_absolute_error(y_true, y_pred; weights = nothing)\n    _validate_distance_input(y_true, y_pred, weights)\n    result = median(abs.(y_pred .- y_true) ; dims = 1)\n    return weights == nothing ? mean(result) : mean(result .* weights)\nend\n\n\"\"\"\n```mean_absolute_percentage_error(y_true, y_pred; keywords)```\nReturn the median absolute percentage error.\n\n## Arguments\n- `y_true` : Ground truths\n- `y_pred` : Predictions\n\n## Keywords\n- `weights` : Sample weights\n\n\"\"\"\nfunction mean_absolute_percentage_error(y_true, y_pred; weights = nothing)\n    _validate_distance_input(y_true, y_pred, weights)\n    result = abs.(y_true .- y_pred) ./ max.(abs.(y_true),eps())\n    return weights == nothing ? mean(result) : mean(result .* weights)\nend\n", "meta": {"hexsha": "6f1af0b49c8f721ea1b3c0486167e4d6f253c085", "size": 2800, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/regression/metrics.jl", "max_stars_repo_name": "KnetML/KnetMetrics.jl", "max_stars_repo_head_hexsha": "ad6aec57a9323de86b9851f1be23668f368b4a86", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-08-25T08:56:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T21:48:37.000Z", "max_issues_repo_path": "src/regression/metrics.jl", "max_issues_repo_name": "emirhan422/KnetMetrics", "max_issues_repo_head_hexsha": "ad6aec57a9323de86b9851f1be23668f368b4a86", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-12-31T10:02:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-01T20:09:53.000Z", "max_forks_repo_path": "src/regression/metrics.jl", "max_forks_repo_name": "emirhan422/KnetMetrics.jl", "max_forks_repo_head_hexsha": "ad6aec57a9323de86b9851f1be23668f368b4a86", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-22T18:53:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-22T18:53:48.000Z", "avg_line_length": 25.9259259259, "max_line_length": 136, "alphanum_fraction": 0.7175, "num_tokens": 728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813538993888, "lm_q2_score": 0.8991213813246445, "lm_q1q2_score": 0.8595432754386222}}
{"text": "# Inverse and soln of matrix\r\n# Gaussian\r\n# generally JL handles eqns and invs\r\n\r\n\r\n# we use Finverse to denote function to find inverse\r\n# \ud83d\ude48\r\n\r\nfunction Finverse_Gaussian(x)\r\n    n = Int(sqrt(length(x)))\r\n    x = reshape(x,n,n)\r\n    I = zeros(n,n)\r\n    for i in 1:n\r\n        I[i,i] =1\r\n    end\r\n    for i in 1:(n-1)\r\n        for j in (i+1):n\r\n            m = x[j,i]/x[i,i]\r\n            x[j,i:end] = x[j,i:end].-x[i,i:end].*m\r\n            I[j,:] = I[j,:].-I[i,:].*m\r\n        end\r\n    end\r\n    for i in n:-1:2\r\n        for j in (i-1):-1:1\r\n            m = x[j,i]/x[i,i]\r\n            x[j,i]=0\r\n            I[j,:] =I[j,:] .- I[i,:].*m\r\n        end\r\n    end\r\n    for i in 1:n\r\n        I[i,:] = I[i,:]./x[i,i]\r\n    end\r\n    return I\r\nend\r\n\r\nfunction Fsolve_Gaussian(x,b)\r\n    n=length(b)\r\n    x = reshape(x,n,n)\r\n    for i in 1:(n-1)\r\n        for j in (i+1):n\r\n            m = x[j,i]/x[i,i]\r\n            x[j,i:end] = x[j,i:end].-x[i,i:end].*m\r\n            b[j] = b[j]-b[i]*m\r\n        end\r\n    end\r\n    return b\r\nend\r\n\r\nFsolve_Gaussian([1 2 3; 4 5 6;7 8 9],[1;2;3])\r\n[1 2 3; 4 5 6;7 8 9]*[1 ,-2, 0]\r\n\r\n\r\n\r\n\r\n#Finverse_Gaussian([1 2;6 7])\r\n\r\n#[1 2;6 7]*Finverse_Gaussian([1 2;6 7])\r\n\r\n\r\n# safer version of Gaussian solve -judge and shift terms with 0\r\n\r\n\r\n#function Fsolve_Gaussian_safely(x,b)\r\n#    n=length(b)\r\n#    for j in 1:(n-1)\r\n#    end\r\n#end\r\n\r\nx = [1 2 3;4 5 6;7 8 9]\r\n\r\nfunction LU(x)\r\n    n=Int(sqrt(length(x)))\r\n    for j in 1:(n-1)\r\n        for i in (j+1):n\r\n            m = x[i,j] / x[j,j]\r\n            x[i,(j+1):n] = x[i,(j+1):n].-m.*x[j,(j+1):n]\r\n            x[i,j] = m\r\n        end\r\n    end\r\n    return x\r\nend\r\nLU(x)\r\n", "meta": {"hexsha": "f63b2afe6bdee20acac11c3aaba90fbf47fb0f6a", "size": 1629, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Inverse.jl", "max_stars_repo_name": "HaoLi111/Julia_Numerical_Recipe", "max_stars_repo_head_hexsha": "d887ee783bfc6e4efc1b4f748c19a21baef5d654", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-06-27T05:52:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-05T04:55:37.000Z", "max_issues_repo_path": "Inverse.jl", "max_issues_repo_name": "HaoLi111/Julia_Numerical_Recipe", "max_issues_repo_head_hexsha": "d887ee783bfc6e4efc1b4f748c19a21baef5d654", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Inverse.jl", "max_forks_repo_name": "HaoLi111/Julia_Numerical_Recipe", "max_forks_repo_head_hexsha": "d887ee783bfc6e4efc1b4f748c19a21baef5d654", "max_forks_repo_licenses": ["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.6265060241, "max_line_length": 64, "alphanum_fraction": 0.4327808471, "num_tokens": 630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305318133553, "lm_q2_score": 0.8918110511888303, "lm_q1q2_score": 0.8590196331136444}}
{"text": "function bicgstab(a::Matrix{Float64}, b::Vector{Float64}, x0::Vector{Float64};\n  tol=1.0e-10, limit=1000, trace=false)\n  \n  n = size(a, 1)\n  x = copy(x0)\n  local converged\n  \n  r = b - a * x\n  r0_hat = copy(r)\n  rho0 = w = \u03b1 = 1.0\n  v = zeros(n)\n  p = zeros(n)\n  rho1 = dot(r0_hat, r)\n  trace && println(\"\\nFirst few iterations:\")\n  iters = 0\n  while true\n    iters += 1\n    converged = norm(r) < tol * norm(b)\n    (converged || (iters == limit)) && break\n    \u03b2 = (rho1 / rho0) * (\u03b1 / w)\n    p = r + \u03b2 * (p - w * v)\n    v = a * p\n    \u03b1 = rho1 / dot(r0_hat, v)\n    s = r - \u03b1 * v\n    t = a * s\n    w = dot(t, s) / dot(t, t)\n    rho0 = rho1\n    rho1 = -w * dot(r0_hat, t)\n    x += \u03b1 * p + w * s\n    r = s - w * t\n    if trace && iters <= 5\n      println(\"After $iters iterations: x = $x\")\n    end\n  end\n  iters, converged, x\nend\n", "meta": {"hexsha": "9196916a8d643e70e74863bbd251a2d9878a6368", "size": 826, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nmlib/bicgstab.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/bicgstab.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/bicgstab.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.3243243243, "max_line_length": 78, "alphanum_fraction": 0.5012106538, "num_tokens": 334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551535992067, "lm_q2_score": 0.8902942348544447, "lm_q1q2_score": 0.8590049807189735}}
{"text": "#=\n  Original Author: Anastasia Yendiki\n\n  Copyright \u00a9 2022 The General Hospital Corporation (Boston, MA) \"MGH\"\n \n  Terms and conditions for use, reproduction, distribution and contribution\n  are found in the 'FreeSurfer Software License Agreement' contained\n  in the file 'LICENSE' found in the FreeSurfer distribution, and here:\n \n  https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense\n \n  Reporting: freesurfer@nmr.mgh.harvard.edu\n=#\n\nexport cart2pol, pol2cart, cart2sph, sph2cart\n\n\n\"\"\"\n    cart2pol(x, y)\n\n    Transform Cartesian coordinates (`x`, `y`) to polar coordinates (`\u03c6`, `\u03c1`),\n    where `\u03c6` is in radians.\n\"\"\"\nfunction cart2pol(x, y)\n\n  \u03c6 = atan.(y, x)\n  \u03c1 = hypot.(x, y)\n\n  return \u03c6, \u03c1\nend\n\n\n\"\"\"\n    pol2cart(\u03c6, \u03c1)\n\n    Transform polar coordinates (`\u03c6`, `\u03c1`) to Cartesian coordinates (`x`, `y`),\n    where `\u03c6` is in radians.\n\"\"\"\nfunction pol2cart(\u03c6, \u03c1)\n\n  x = \u03c1 .* cos.(\u03c6)\n  y = \u03c1 .* sin.(\u03c6)\n\n  return x, y\nend\n\n\n\"\"\"\n    cart2sph(x, y, z)\n\n    Transform Cartesian coordinates (`x`, `y`, `z`) to spherical coordinates\n    (`\u03c6`, `\u03b8`, `\u03c1`), where `\u03c6` and `\u03b8` are in radians.\n\"\"\"\nfunction cart2sph(x, y, z)\n\n  hypotxy = hypot.(x, y)\n  \u03c1 = hypot.(hypotxy, z)\n  \u03b8 = atan.(z, hypotxy)\n  \u03c6 = atan.(y, x)\n\n  return \u03c6, \u03b8, \u03c1\nend\n\n\n\"\"\"\n    sph2cart(\u03c6, \u03b8, \u03c1)\n\n    Transform spherical coordinates (`\u03c6`, `\u03b8`, `\u03c1`) to Cartesian coordinates\n    (`x`, `y`, `z`).\n\n    `\u03c6` and `\u03b8` must be in radians.\n\"\"\"\nfunction sph2cart(\u03c6, \u03b8, \u03c1)\n\n  z = \u03c1 .* sin.(\u03b8)\n  \u03c1cos\u03b8 = \u03c1 .* cos.(\u03b8)\n  x = \u03c1cos\u03b8 .* cos.(\u03c6)\n  y = \u03c1cos\u03b8 .* sin.(\u03c6)\n\n  return x, y, z\nend\n\n\n\"\"\"\n    ang2rot(\u03c6, \u03b8)\n\n    Convert polar `\u03c6` and azimuthal `\u03b8` angles to a rotation matrix.\n\n    `\u03c6` and `\u03b8` must be in radians.\n\"\"\"\nfunction ang2rot(\u03c6, \u03b8)\n\n  # Rotate by \u03c6 around the z-axis\n  Rz = [cos(\u03c6)  -sin(\u03c6)  0\n        sin(\u03c6)   cos(\u03c6)  0\n        0         0      1]\n\n  # Rotate by \u03b8 around the y-axis\n  Ry = [cos(\u03b8)   0   sin(\u03b8)\n        0        1   0\n       -sin(\u03b8)   0   cos(\u03b8)]\n\n  R =  Rz * Ry\n\n  return R\nend\n\n\n", "meta": {"hexsha": "bbd555f9e51f42b9bb7f6ee175e524709ab8b3b3", "size": 1977, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/util.jl", "max_stars_repo_name": "freesurfer/jupysurf", "max_stars_repo_head_hexsha": "6c28345c895b0aacd5de1166fe8f04f6c26c68bf", "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/util.jl", "max_issues_repo_name": "freesurfer/jupysurf", "max_issues_repo_head_hexsha": "6c28345c895b0aacd5de1166fe8f04f6c26c68bf", "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/util.jl", "max_forks_repo_name": "freesurfer/jupysurf", "max_forks_repo_head_hexsha": "6c28345c895b0aacd5de1166fe8f04f6c26c68bf", "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.1376146789, "max_line_length": 79, "alphanum_fraction": 0.5842185129, "num_tokens": 709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551505674444, "lm_q2_score": 0.8902942348544447, "lm_q1q2_score": 0.859004978019813}}
{"text": "function subbac!(u::Matrix{Float64}, b::Vector{Float64})\n# Back-substitution on an Upper Triangle\n  n = size(u, 1)\n  for i in n:-1:1\n    total = b[i]\n    if i < n\n      for j in i+1:n\n        total -= u[i, j] * b[j]\n      end\n    end\n    b[i] = total / u[i, i]\n  end\nend\n\nfunction subbac(u::Matrix{Float64}, b::Vector{Float64})\n# Back-substitution on an Upper Triangle\n  bt = deepcopy(b)\n  n = size(u, 1)\n  for i in n:-1:1\n    total = bt[i]\n    if i < n\n      for j in i+1:n\n        total -= u[i, j] * bt[j]\n      end\n    end\n    bt[i] = total / u[i, i]\n  end\n  bt\nend\n\nexport\n  subbac!,\n  subbac\n", "meta": {"hexsha": "0de9f5215a70ae2625d87966b0a1e54ace63e66c", "size": 597, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nmlib/subbac.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/subbac.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/subbac.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": 17.5588235294, "max_line_length": 56, "alphanum_fraction": 0.5360134003, "num_tokens": 222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.956634203708804, "lm_q2_score": 0.8976952845805988, "lm_q1q2_score": 0.8587660137379093}}
{"text": "using FiniteDiff, LinearAlgebra, SparseArrays, Test, StaticArrays\r\n\r\nfunction f(x)\r\n  xm1 = [0;x[1:end-1]]\r\n  xp1 = [x[2:end];0]\r\n  xm1 - 2x + xp1\r\nend\r\n\r\nfunction second_derivative_stencil(N)\r\n  A = zeros(N,N)\r\n  for i in 1:N, j in 1:N\r\n      (j-i==-1 || j-i==1) && (A[i,j]=1)\r\n      j-i==0 && (A[i,j]=-2)\r\n  end\r\n  A\r\nend\r\n\r\nx = @SVector ones(30)\r\nJ = FiniteDiff.finite_difference_jacobian(f, x, Val{:forward}, eltype(x))\r\n@test J \u2248 second_derivative_stencil(30)\r\n\r\nJ = FiniteDiff.finite_difference_jacobian(f, x, Val{:central}, eltype(x))\r\n@test J \u2248 second_derivative_stencil(30)\r\n\r\nJ = FiniteDiff.finite_difference_jacobian(f, x, Val{:complex}, eltype(x))\r\n@test J \u2248 second_derivative_stencil(30)\r\n\r\nspJ = sparse(second_derivative_stencil(30))\r\nJ = FiniteDiff.finite_difference_jacobian(f, x, Val{:forward}, eltype(x), jac_prototype=spJ)\r\n@test J \u2248 second_derivative_stencil(30)\r\n@test typeof(J) == typeof(spJ)\r\nJ = FiniteDiff.finite_difference_jacobian(f, x, Val{:forward}, eltype(x),\r\n    colorvec=SVector{30}(repeat(1:3, 10)), sparsity=spJ, jac_prototype=spJ)\r\n@test J \u2248 second_derivative_stencil(30)\r\n@test typeof(J) == typeof(spJ)\r\n\r\nf(x) = x\r\n@testset \"1x1 test of $x\" for\r\n  (x, y) in ((SVector{1}([1.]), SMatrix{1,1}), ([1.0], Matrix)),\r\n    difftype in (:forward, :central, :complex)\r\n\r\n  J = FiniteDiff.finite_difference_jacobian(f, x, Val{difftype}, eltype(x))\r\n  @test J[1, 1] \u2248 1.0\r\n  @test J isa y\r\nend\r\n\r\nx = SVector{1}([1.])\r\nf(x) = vcat(x, x)\r\nJ = FiniteDiff.finite_difference_jacobian(f, x, Val{:forward}, eltype(x))\r\n@test J \u2248 fill(1.0, 2, 1)\r\n@test J isa SMatrix{2,1}\r\nJ = FiniteDiff.finite_difference_jacobian(f, x, Val{:central}, eltype(x))\r\n@test J \u2248 fill(1.0, 2, 1)\r\n@test J isa SMatrix{2,1}\r\nJ = FiniteDiff.finite_difference_jacobian(f, x, Val{:complex}, eltype(x))\r\n@test J \u2248 fill(1.0, 2, 1)\r\n@test J isa SMatrix{2,1}\r\n", "meta": {"hexsha": "d3dca1be6f37a13993952a4da343d6fc50a11da6", "size": 1849, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/out_of_place_tests.jl", "max_stars_repo_name": "andrewning/FiniteDiff.jl", "max_stars_repo_head_hexsha": "bdbd980f61afde53046a30902d5a106f4dadb6da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 131, "max_stars_repo_stars_event_min_datetime": "2020-01-04T19:08:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T07:19:47.000Z", "max_issues_repo_path": "test/out_of_place_tests.jl", "max_issues_repo_name": "andrewning/FiniteDiff.jl", "max_issues_repo_head_hexsha": "bdbd980f61afde53046a30902d5a106f4dadb6da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 80, "max_issues_repo_issues_event_min_datetime": "2017-01-12T03:49:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-01T02:37:03.000Z", "max_forks_repo_path": "test/out_of_place_tests.jl", "max_forks_repo_name": "andrewning/FiniteDiff.jl", "max_forks_repo_head_hexsha": "bdbd980f61afde53046a30902d5a106f4dadb6da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2017-01-12T20:28:06.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-12T10:07:23.000Z", "avg_line_length": 31.8793103448, "max_line_length": 93, "alphanum_fraction": 0.6560302866, "num_tokens": 636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947148047777, "lm_q2_score": 0.9086179012632543, "lm_q1q2_score": 0.8586391144707847}}
{"text": "\"\"\"\n    pearson_correlation(x, y)\n\nFind the pearson correlation between two variables.\n\n# Example:\n\njulia> PearsonCorrelation([12,11,16,17,19,21],[11,51,66,72,12,15])\n-0.2092706263573845\n\nContribution by: [Aru Bhardwaj](https://github.com/arubhardwaj)\n\n\n\"\"\"\n\nfunction pearson_correlation(x, y)\n    mean_x = sum(x) / length(x)\n    mean_y = sum(y) / length(y)\n    XY = (x .- mean_x) .* (y .- mean_y)\n    XXs = sum((x .- mean_x) .* (x .- mean_x))\n    YYs = sum((y .- mean_y) .* (y .- mean_y))\n    return(sum(XY) / (sqrt(XXs .* YYs)))\nend\n", "meta": {"hexsha": "519cc554d92470f7587173a154a5c070a21f1223", "size": 535, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/statistics/pearson_correlation.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/pearson_correlation.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/pearson_correlation.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.2916666667, "max_line_length": 66, "alphanum_fraction": 0.614953271, "num_tokens": 193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9783846628255124, "lm_q2_score": 0.8774767954920548, "lm_q1q2_score": 0.8585098386947051}}
{"text": "# Monte-Carlo Applications\r\n\r\n# Type 1\r\n# path like integration\r\n# \u222b\u2080\u00b9 e\r\n# todo\r\n\r\n\r\n# Type 2\r\n# Volume-like integration\r\n\r\n\r\n# E.g. evaluate \u03c0\r\n\r\n# 1. generate n points within a unit \u25a1\r\n#    enclosed by xlim<-[0 1]\r\n#    and         ylim<-[0 1]\r\n\r\nn = 1000\r\nx = rand(n)\r\ny = rand(n)\r\n\r\n# 2. Judge # of pts in the unit \u25f7\r\ns = 0\r\nfor i in 1:n# I hate for loop , there's a simpler version below\r\n    if (x[i]^2 + y[i]^2)<=1\r\n        global s+=1\r\n    end\r\nend\r\ns\r\n\r\n# Area of \u25a7 / Area of \u25cd  = 4/\u03c0\r\n\u03c0_est = 4s/n\r\n\u03c0_est\r\n\r\n\r\n# Vectorize? replace 2 with\r\n#even faster?\r\n@time size(zeros(n)[x.^2+y.^2 .<=1])\r\n#0.000070 seconds (27 allocations: 42.813 KiB)\r\n#Compared with\r\n\r\ns=0\r\n@time for i in 1:n\r\n    if (x[i]^2 + y[i]^2)<=1\r\n        global s+=1\r\n    end\r\nend\r\n#0.000220 seconds (7.75 k allocations: 136.734 KiB)\r\n\r\n\u03c0_est = 4s/n\r\n\u03c0_est\r\n\r\n\r\nplot(x,y;seriestype=\"scatter\")\r\nplot!(0:.01:1,sqrt.(1 .-(0:.01:1).^2))\r\n", "meta": {"hexsha": "2fb8430276b1ec5430047f45506da41079c0e1d4", "size": 910, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Monte-Carlo.jl", "max_stars_repo_name": "HaoLi111/Julia_Numerical_Recipe", "max_stars_repo_head_hexsha": "d887ee783bfc6e4efc1b4f748c19a21baef5d654", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-06-27T05:52:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-05T04:55:37.000Z", "max_issues_repo_path": "Monte-Carlo.jl", "max_issues_repo_name": "HaoLi111/Julia_Numerical_Recipe", "max_issues_repo_head_hexsha": "d887ee783bfc6e4efc1b4f748c19a21baef5d654", "max_issues_repo_licenses": ["MIT"], "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": "HaoLi111/Julia_Numerical_Recipe", "max_forks_repo_head_hexsha": "d887ee783bfc6e4efc1b4f748c19a21baef5d654", "max_forks_repo_licenses": ["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.9649122807, "max_line_length": 64, "alphanum_fraction": 0.5538461538, "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109812297141, "lm_q2_score": 0.9032942034496964, "lm_q1q2_score": 0.8585007302397389}}
{"text": "# determine the moment of the stoichiometric matrix coefficient\r\n# necessary to deal with (independent) stochastic variables\r\n# NOTE: only geometric distribution is supported\r\n# the parameter passed is supposed to be the MEAN value\r\n#function expected_coeff(x::Union{Int, Sym{ModelingToolkit.Parameter{Real}}}, pwr)\r\nfunction expected_coeff(x::Union{Int, Symbolic}, pwr)\r\n    if typeof(x) == Int64\r\n        x^pwr\r\n    else\r\n        geometric_raw_moment(x, pwr)\r\n    end\r\nend\r\n\r\nfunction eulerian_number(n, k)\r\n    suma = 0\r\n    for j in 0:k+1\r\n        suma += (-1)^j * binomial(n+1, j) * (k-j+1)^n\r\n    end\r\n    return suma\r\nend\r\n\r\n#function geometric_raw_moment_arbitrary_order(m::Sym{ModelingToolkit.Parameter{Real}}, n::Int)\r\nfunction geometric_raw_moment_arbitrary_order(m::Symbolic, n::Int)\r\n    # computes the symbolic expression of \u27e8X\u207f\u27e9 where X is a stochastic variable\r\n    # following a geometric distribution with mean burst size m\r\n    # the distribution has the form P(x) = (1-p)\u02e3p, and m is given by m = (1-p)/p\r\n    #@syms p\r\n    suma = 0.0\r\n    for i in 0:n\r\n        #suma += eulerian_number(n, i) * (1-p)^(n-i)\r\n        suma += eulerian_number(n, i) * m^(n-i) * (1+m)^(i-n)\r\n        suma = simplify(suma)\r\n    end\r\n    #return p^(-n) * suma\r\n    simplify((1+m)^n * suma)\r\nend\r\n\r\n#function geometric_raw_moment(m::Sym{ModelingToolkit.Parameter{Real}}, n::Int)\r\nfunction geometric_raw_moment(m::Symbolic, n::Int)\r\n    # provide the symbolic expression of \u27e8X\u207f\u27e9 where X is a stochastic variable\r\n    # following a geometric distribution with mean burst size m\r\n    # the distribution has the form P(x) = (1-p)\u02e3p, and m is given by m = (1-p)/p\r\n    # Although geometric_raw_moment_arbitrary_order() can obtain the moment up to\r\n    # arbitrary order, it is unable to format it in a nice and readable way\r\n    # (not straightforward to use SymbolicUtils.jl to perform a binomial expansion\r\n    # and hence tidy up the expression). For this reason, we provide the clean\r\n    # symbolic expressions up to order 5 just to make the moment equations easier to check\r\n    if n == 0\r\n        1\r\n    elseif n==1\r\n        m\r\n    elseif n==2\r\n        2*m^2+m\r\n    elseif n==3\r\n        m*(6*m^2 + 6*m + 1)\r\n    elseif n==4\r\n        m*(2*m + 1)*(12*m^2+12*m+1)\r\n    elseif n==5\r\n        m*(120*m^4 + 240*m^3 + 150*m^2 + 30*m + 1)\r\n    elseif n>5\r\n        geometric_raw_moment_arbitrary_order(m, n)\r\n    else\r\n        error(\"negative argument values\")\r\n    end\r\nend\r\n", "meta": {"hexsha": "2cc42b038ed3beda1e53fe711a87b1fd2256cd4d", "size": 2464, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/stochastic_stoichiometry.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": "src/stochastic_stoichiometry.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": "src/stochastic_stoichiometry.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.3333333333, "max_line_length": 96, "alphanum_fraction": 0.6424512987, "num_tokens": 715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102571131692, "lm_q2_score": 0.8872045996818986, "lm_q1q2_score": 0.8582908298902518}}
{"text": "# Richardson function\r\nfunction numdiff(f,x::Number,h::Float64)\r\n    D0 = (f(x+h)-f(x-h))/(2*h);\r\n    D1 = ( f(x+(h/2)) - f(x-(h/2)) )/(h);\r\n    TV = D1 + (D1-D0)/3\r\n    return TV\r\nend\r\n\r\n# Richardson function\r\nfunction numdiff(f,x::Number,h::Int64)\r\n    D0 = (f(x+h)-f(x-h))/(2*h);\r\n    D1 = ( f(x+(h/2)) - f(x-(h/2)) )/(h);\r\n    TV = D1 + (D1-D0)/3\r\n    return TV\r\nend\r\n\r\n# Richardson discrete of type 1 (We get an exact value in x vector in which we want to differentiate)\r\nfunction numdiff(x::Array{Float64,1}, y::Array{Float64,1}, val) #We get a x array, a y array and a val in x for which we want to get its derivative\r\n    h = abs(x[2] - x[1]);\r\n    ind = findall(p->p==val, x)[1]\r\n    D0 = (y[ind+2]-y[ind-2])/(4*h);\r\n    D1 = (y[ind+1]-y[ind-1])/(2*h);\r\n    TV = D1 + (D1-D0)/3\r\n    return TV\r\nend\r\n\r\n# Richardson getting the whole bunch i.e. CDD of O(h^4) residues\r\n\r\n#=\r\nfunction numdiff(x::Array{Float64,1}, y::Array{Float64,1}) #We get a x array, a y array and a val in x for which we want to get its derivative\r\n    h = abs(x[2] - x[1]);\r\n    \r\n    return TV\r\nend\r\n=#\r\n\r\n# Forward func of linear order\r\nfunction fdiff(f,x,h)\r\n    d = (f(x+h)-f(x))/h;\r\n    return d\r\nend\r\n\r\n# Forward discrete of type 1 (We get an exact value in x vector in which we want to differentiate)\r\nfunction fdiff(x::Array{Float64,1}, y::Array{Float64,1},val)\r\n    h = abs( x[2] - x[1] );\r\n    ind = findall(p->p==val, x)[1]\r\n    d = (y[ind+1] - y[ind])/h\r\n    return d\r\nend\r\n\r\n# Forward discrete, with the whole bunch (MATLAB-like, with the whole vector)\r\nfunction fdiff(x::Array{Float64,1}, y::Array{Float64,1})\r\n    h = abs( x[2] - x[1] );\r\n    d = (y[2:end] - y[1:end-1])/h\r\n    return d\r\nend\r\n\r\n# Backwards func\r\nfunction bdiff(f,x,h)\r\n    d = (f(x)-f(x-h))/h;\r\n    return d\r\nend\r\n\r\n# Backwards discrete of type 1 (We get an exact value in x vector in which we want to differentiate)\r\nfunction bdiff(x::Array{Float64,1}, y::Array{Float64,1},val)\r\n    h = abs( x[2] - x[1] );\r\n    ind = findall(p->p==val, x)[1]\r\n    d = (y[ind] - y[ind-1])/h\r\n    return d\r\nend\r\n\r\n# Backwards discrete, with the whole bunch (MATLAB-like, with the whole vector)\r\nfunction bdiff(x::Array{Float64,1}, y::Array{Float64,1})\r\n    h = abs( x[2] - x[1] );\r\n    d = (y[2:end] - y[1:end-1])/h\r\n    return d\r\nend\r\n\r\n\r\n", "meta": {"hexsha": "56de7643cf1bfb8ee875526cbc445417bd60a503", "size": 2283, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/numdiff.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/numdiff.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/numdiff.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": 28.5375, "max_line_length": 148, "alphanum_fraction": 0.5742444152, "num_tokens": 814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542875927779, "lm_q2_score": 0.8947894682067639, "lm_q1q2_score": 0.8582411549233792}}
{"text": "using ModelingToolkit, OrdinaryDiffEq, Test, LinearAlgebra\r\n\r\n@parameters t \u03c3 \u03c1 \u03b2\r\n@variables x(t) y(t) z(t) k(t)\r\nD = Differential(t)\r\n\r\neqs = [D(D(x)) ~ \u03c3*(y-x),\r\n       D(y) ~ x*(\u03c1-z)-y,\r\n       D(z) ~ x*y - \u03b2*z]\r\n\r\nsys\u2032 = ODESystem(eqs)\r\nsys = ode_order_lowering(sys\u2032)\r\n\r\neqs2 = [0 ~ x*y - k,\r\n        D(D(x)) ~ \u03c3*(y-x),\r\n        D(y) ~ x*(\u03c1-z)-y,\r\n        D(z) ~ x*y - \u03b2*z]\r\nsys2 = ODESystem(eqs2, t, [x, y, z, k], parameters(sys\u2032))\r\nsys2 = ode_order_lowering(sys2)\r\n# test equation/varible ordering\r\nModelingToolkit.calculate_massmatrix(sys2) == Diagonal([1, 1, 1, 1, 0])\r\n\r\nu0 = [D(x) => 2.0,\r\n      x => 1.0,\r\n      y => 0.0,\r\n      z => 0.0]\r\n\r\np  = [\u03c3 => 28.0,\r\n      \u03c1 => 10.0,\r\n      \u03b2 => 8/3]\r\n\r\ntspan = (0.0,100.0)\r\nprob = ODEProblem(sys,u0,tspan,p,jac=true)\r\nprobexpr = ODEProblemExpr(sys,u0,tspan,p,jac=true)\r\nsol = solve(prob,Tsit5())\r\nsolexpr = solve(eval(prob),Tsit5())\r\n@test all(x->x==0,Array(sol - solexpr))\r\n#using Plots; plot(sol,vars=(:x,:y))\r\n\r\n@parameters t \u03c3 \u03c1 \u03b2\r\n@variables x(t) y(t) z(t)\r\nD = Differential(t)\r\n\r\neqs = [D(x) ~ \u03c3*(y-x),\r\n       D(y) ~ x*(\u03c1-z)-y,\r\n       D(z) ~ x*y - \u03b2*z]\r\n\r\nlorenz1 = ODESystem(eqs,name=:lorenz1)\r\nlorenz2 = ODESystem(eqs,name=:lorenz2)\r\n\r\n@variables \u03b1(t)\r\n@parameters \u03b3\r\nconnections = [0 ~ lorenz1.x + lorenz2.y + \u03b1*\u03b3]\r\nconnected = ODESystem(connections,t,[\u03b1],[\u03b3],systems=[lorenz1,lorenz2])\r\n\r\nu0 = [lorenz1.x => 1.0,\r\n      lorenz1.y => 0.0,\r\n      lorenz1.z => 0.0,\r\n      lorenz2.x => 0.0,\r\n      lorenz2.y => 1.0,\r\n      lorenz2.z => 0.0,\r\n      \u03b1 => 2.0]\r\n\r\np  = [lorenz1.\u03c3 => 10.0,\r\n      lorenz1.\u03c1 => 28.0,\r\n      lorenz1.\u03b2 => 8/3,\r\n      lorenz2.\u03c3 => 10.0,\r\n      lorenz2.\u03c1 => 28.0,\r\n      lorenz2.\u03b2 => 8/3,\r\n      \u03b3 => 2.0]\r\n\r\ntspan = (0.0,100.0)\r\nprob = ODEProblem(connected,u0,tspan,p)\r\nsol = solve(prob,Rodas5())\r\n@test maximum(sol[2,:] + sol[6,:] + 2sol[1,:]) < 1e-12\r\n#using Plots; plot(sol,vars=(:\u03b1,Symbol(lorenz1.x),Symbol(lorenz2.y)))\r\n", "meta": {"hexsha": "f1d9105834bd3115069280183cfc9d59b8a11c1c", "size": 1916, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/lowering_solving.jl", "max_stars_repo_name": "JKRT/ModelingToolkit.jl", "max_stars_repo_head_hexsha": "fc34034daa87f8f8fc683ede7a88e8f360f3d41f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-18T08:15:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-18T08:15:30.000Z", "max_issues_repo_path": "test/lowering_solving.jl", "max_issues_repo_name": "JKRT/ModelingToolkit.jl", "max_issues_repo_head_hexsha": "fc34034daa87f8f8fc683ede7a88e8f360f3d41f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/lowering_solving.jl", "max_forks_repo_name": "JKRT/ModelingToolkit.jl", "max_forks_repo_head_hexsha": "fc34034daa87f8f8fc683ede7a88e8f360f3d41f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8831168831, "max_line_length": 72, "alphanum_fraction": 0.5328810021, "num_tokens": 778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012732322216, "lm_q2_score": 0.9073122119620788, "lm_q1q2_score": 0.8581370452928775}}
{"text": "\nusing LinearAlgebra\nusing Statistics\n\nx = [ 2, -1, 2];\n\n# norm of x is written in Julia as norm(x)\nnorm(x)\n\nsqrt(x'*x)\n\nsqrt(sum(x.^2))\n\nx = randn(10); y = randn(10)\n\nlhs = norm(x+y)\n\nrhs = norm(x) + norm(y)\n\n# rms value of a vector is rms(x) = norm(x)/sqrt(length(x))\nrms(x) = norm(x) / sqrt(length(x))\n\nt = 0:0.01:1; # list of times\n\nx = cos.(8*t) - 2*sin.(11*t)\n\nrms(x)\n\nusing Plots\n\nplot(t,x)\n\nplot!(t, avg(x)*ones(length(x)))\n\nplot!(t, (avg(x)+rms(x))*ones(length(x)), color = :green)\n\nplot!(t, (avg(x)-rms(x))*ones(length(x)), color = :green)\n\nplot!(legend = false)\n\n# Define Chebyshev bound function\n# The Chebyshev inequality states that the number of entries of an \n# n-vector x that have absolute value at least a is no more than \n# \u2225x\u22252/a2 = nrms(x)2/a2. If this number is, say, 12.15, \n# we can conclude that no more that 12 entries have absolute value \n# at least a, since the number of entries is an integer.\n\ncheb_bound(x,a) = floor(norm(x)^2/a);\na = 1.5;\ncheb_bound(x,a)\n# Number of entries of x with |x_i| >= a\nsum(abs.(x) .>= a)\n\n\n", "meta": {"hexsha": "fd997aef35e61070b8622242b684b3da6c1f6ad7", "size": 1050, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "3_Norm_and_Distance/1-Norm-Dist.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": "3_Norm_and_Distance/1-Norm-Dist.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": "3_Norm_and_Distance/1-Norm-Dist.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.0909090909, "max_line_length": 67, "alphanum_fraction": 0.6371428571, "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799441350253, "lm_q2_score": 0.8902942261220292, "lm_q1q2_score": 0.858047719515625}}
{"text": "# Algorithm 5.3\n# Runge Kutta Fehlberg\n\nfunction rkf(f, a, b, \u03b1, max_step, min_step, tolerance)\n\tflag = 1\n\tresult = Tuple{Float64, Float64, Float64}[]\n\tt = a\n\tk = Array{Float64}(undef, 6)\n\th = max_step\n\t\u03c9 = \u03b1\n\tpush!(result, (t, \u03c9, h))\n\twhile flag == 1\n\t\tk[1] = h*f(t, \u03c9)\n\t\tk[2] = h*f(t + (1/4)*h, \u03c9 + (1/4)*k[1])\n\t\tk[3] = h*f(t + (3/8)*h, \u03c9 + (3/32)*k[1] + (9/32)*k[2])\n\t\tk[4] = h*f(t + (12/13)*h, \u03c9 + (1932/2197)*k[1] - (7200/2197)*k[2] + (7296/2197)*k[3])\n\t\tk[5] = h*f(t + h, \u03c9 + (439/216)*k[1] - 8*k[2] + (3680/513)*k[3] - (845/4104)*k[4])\n\t\tk[6] = h*f(t + (1/2)*h, \u03c9 - (8/27)*k[1] + 2*k[2] - (3544/2565)*k[3] + (1859/4104)*k[4] - (11/40)*k[5])\n\t\tR = (1/h)*abs((1/360)*k[1] - (128/4275)*k[3] - (2197/75240)*k[4] + (1/50)*k[5] + (2/55)k[6])\n\t\tif R <= tolerance\n\t\t\tt = t + h\n\t\t\t\u03c9 = \u03c9 + (25/216)*k[1] + (1408/25655)*k[3] + (21977/4104)*k[4] - (1/5)*k[5]\n\t\t\tpush!(result, (t, \u03c9, h))\n\t\tend\n\t\t\u03b4 = 0.84 * (tolerance/R)^(1/4)\n\t\tif \u03b4 <= 0.1\n\t\t\th = 0.1*h\n\t\telseif \u03b4 >= 4\n\t\t\th = 4h\n\t\telse\n\t\t\th = \u03b4*h\n\t\tend\n\t\tif h > max_step\n\t\t\th = max_step\n\t\tend\n\t\tif t >= b\n\t\t\tflag = 0\n\t\telseif (t + h) > b\n\t\t\th = b - t\n\t\telseif h < min_step\n\t\t\tflag = 0\n\t\tend\n\tend\n\treturn result\nend\n\nf(t, y) = y - t^2 + 1\nprintln(rkf(f, 0, 2, 0.5, 0.25, 0, 10^(-5)))\n", "meta": {"hexsha": "0a8a45a266c785208217000da64c5422c1c43371", "size": 1228, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "chapter5/runge-kutta-fehlberg.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/runge-kutta-fehlberg.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/runge-kutta-fehlberg.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": 25.0612244898, "max_line_length": 104, "alphanum_fraction": 0.4780130293, "num_tokens": 674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075744568837, "lm_q2_score": 0.891811041124754, "lm_q1q2_score": 0.8580181576504051}}
{"text": "module NewtonMethod2\n\nusing LinearAlgebra, Statistics, ForwardDiff\n\nfunction newtonroot(f, f_prime; x0, tol=1E-7, maxiter=1000)\n    # setup the algorithm\n    x_old = x0\n    normdiff = Inf\n    iter = 0\n    while normdiff > tol && iter <= maxiter\n        x_new = x_old-f(x_old)/f_prime(x_old) # use the passed in map\n        normdiff = norm(x_new - x_old)\n        x_old = x_new\n        iter = iter + 1\n    end\n    if iter <= maxiter\n        return (x_old, normdiff, iter)\n    else\n        return (nothing, normdiff, iter) # hope it is correct!\n    end\nend\n\nexport newtonroot\n\n\n#########\n\n\nfunction newtonroot2(f; x0, tol=1E-7, maxiter=1000)\n    D(f) = x -> ForwardDiff.derivative(f, x)\n    f_prime = D(f)\n    # setup the algorithm\n    x_old = x0\n    normdiff = Inf\n    iter = 0\n    while normdiff > tol && iter <= maxiter\n        x_new = x_old-f(x_old)/f_prime(x_old) # use the passed in map\n        normdiff = norm(x_new - x_old)\n        x_old = x_new\n        iter = iter + 1\n    end\n    if iter <= maxiter\n        return (x_old, normdiff, iter)\n    else\n        return (nothing, normdiff, iter)\n    end\nend\n\nexport(newtonroot2)\n\nend\n", "meta": {"hexsha": "4fd019703bc68dcbb39d201e0469976e370fb374", "size": 1133, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NewtonMethod2.jl", "max_stars_repo_name": "mayupei/NewtonMethod2.jl", "max_stars_repo_head_hexsha": "38f1636499048e7fcbd49916bb78f263c1755b76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NewtonMethod2.jl", "max_issues_repo_name": "mayupei/NewtonMethod2.jl", "max_issues_repo_head_hexsha": "38f1636499048e7fcbd49916bb78f263c1755b76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-23T00:14:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-23T00:14:56.000Z", "max_forks_repo_path": "src/NewtonMethod2.jl", "max_forks_repo_name": "mayupei/NewtonMethod2.jl", "max_forks_repo_head_hexsha": "38f1636499048e7fcbd49916bb78f263c1755b76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.7884615385, "max_line_length": 69, "alphanum_fraction": 0.6019417476, "num_tokens": 355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.935346511643776, "lm_q2_score": 0.9173026584553408, "lm_q1q2_score": 0.8579958417077651}}
{"text": "### A Pluto.jl notebook ###\n# v0.17.4\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 d16725a0-6cd3-11ec-0998-fd4af26f10dd\nbegin\n\tusing Pkg; Pkg.activate(@__DIR__); Pkg.instantiate()\n\tPkg.precompile()\n\n\tusing PlutoUI\n\tusing Plots\n\tusing Statistics\n\tusing StatsBase\n\tusing PyCall\n\tusing DataFrames\n\tusing GLM\n\tusing Tables\n\tusing XLSX\n\tusing DataStructures\n\tusing MLBase\n\tusing RDatasets\n\tusing LsqFit\nend;\n\n# \u2554\u2550\u2561 91471950-703f-4927-8bce-f4478f4a53ba\nPlutoUI.TableOfContents(aside=true, indent=true, depth=3)\n\n# \u2554\u2550\u2561 a53d44c5-75c4-4508-aa19-33e838c9e0bb\nmd\"\"\"\n# \ud83d\udcc8 Regression\n\nRegression Analysis is a set of statistical processes for estimating the relationships between a _dependent variable_ (often called the _outcome_ or _response_ variable) and one or more _independent variables_ (often called _predictors_, _covariates_, _explanatory variables_ or _features_). The most common form of regression analysis is linear regression, in which one finds the line (or a more complex linear combination) that most closely fits the data according to a specific mathematical criterion.\n\n[YouTube Link](https://www.youtube.com/watch?v=5TCbIK_cpZE)\n\"\"\"\n\n# \u2554\u2550\u2561 e9458f99-4ec0-4167-b771-3090dfec6320\nmd\"\"\"\n## Simple linear regression\n\"\"\"\n\n# \u2554\u2550\u2561 784c5b0e-59dc-4b2d-bf40-112261ac8e85\nmd\"\"\"\n### Building from scratch\n\nFirstly, let's generate some random data and then plot it...\n\"\"\"\n\n# \u2554\u2550\u2561 65e22edc-ef5c-412f-82f4-1c84da209d6d\nbegin\n\t# x values\n\txvals = repeat(1:0.5:10, inner=2)\n\t# y values (with some noise)\n\tyvals = 3 .+ xvals .+ 2 .* rand(length(xvals)) .-1\n\n\t# plotting\n\tscatter(xvals, yvals, color=:black, leg=false,\n\t\t\txlabel=\"X values\", ylabel=\"Y values\")\nend\n\n# \u2554\u2550\u2561 db2c3459-2127-4b46-8e73-546850767dc0\nmd\"\"\"\nAssuming an ordinary least squares regression, the slope `a` of the fitted line is equal to the correlation between `y` and `x` corrected by the ratio of standard deviations of these variables. The intercept `b` of the fitted line is such that the line passes through the center of mass (`x`, `y`) of the data points.\n\nThus, we can easily build the `find_best_fit` function, which returns `a` and `b` coefficients.\n\"\"\"\n\n# \u2554\u2550\u2561 3bb8c382-f97d-48dc-8cbe-99bf77de0784\nfunction find_best_fit(x, y)\n\tX\u0305, Y\u0305 = mean(x), mean(y)\n\tS\u02e3, S\u02b8 = std(x), std(y)\n\n\ta = cor(x,y) * (S\u02e3/S\u02b8)\n\tb = Y\u0305 - a*X\u0305\n\n\treturn a, b\nend\n\n# \u2554\u2550\u2561 75059ff4-6b9d-4e01-9aed-33ea8b0e9a71\nmd\"\"\"\nWe can now use the function above to calculate `a` and `b` and then compute the estimated values `y\u0302vals`...\n\"\"\"\n\n# \u2554\u2550\u2561 e83331a1-8655-4de0-a36f-b74b5e43674b\nbegin\n\ta, b = find_best_fit(xvals, yvals)\n\ty\u0302vals\u2081 = a .* xvals .+ b\nend\n\n# \u2554\u2550\u2561 d81e448b-b4e4-4d6f-8ca7-42c41569977d\nmd\"\"\"\n### numpy\n\nWe can also import the `numpy` python package to perform a simple linear regression. We are able to use any `numpy` function by adding the prefix `np`, just like in Python.\n\"\"\"\n\n# \u2554\u2550\u2561 a047abfb-178c-40ac-8f8c-c3a8a73c1849\n# importing numpy\nnp = pyimport(\"numpy\");\n\n# \u2554\u2550\u2561 208af138-5131-4034-885b-c41f6ccf36f5\n# numpy model\nnp_model = np.polyfit(xvals, yvals, 1)\n\n# \u2554\u2550\u2561 39884fc4-c41c-46e5-a92a-44d766243715\n# estimated y\u0302 values\ny\u0302vals\u2082 = np_model[1] .* collect(xvals) .+ np_model[2]\n\n# \u2554\u2550\u2561 13719feb-60ae-433b-bf1e-df6ac045215d\nmd\"\"\"\n### GLM\n\nFinally, we can use the [GLM.jl](https://github.com/JuliaStats/GLM.jl) package to perform simple linear regression using the `lm` function.\n\"\"\"\n\n# \u2554\u2550\u2561 10c072d4-b793-458c-b947-d5dc3aae5e25\n# converting data into a DataFrame\ndata = DataFrame(X=xvals, Y=yvals);\n\n# \u2554\u2550\u2561 68a0574f-5b17-48ae-b8c4-a03c7e385561\n# GLM model\nglm_model = lm(@formula(Y ~ X), data)\n\n# \u2554\u2550\u2561 ecb1cb29-2b57-4197-9327-e762fc876281\n# estimated y\u0302 values\ny\u0302vals\u2083 = predict(glm_model)\n\n# \u2554\u2550\u2561 056b28f3-8da4-4a94-a33c-72b30c8aa0aa\nmd\"\"\"\n### Comparing methods\n\nNow we can plot all the three models. We can see below that both `numpy` and `GLM` models are exactly the same. The model that we build from scratch is slightly different.\n\"\"\"\n\n# \u2554\u2550\u2561 9a5dcad1-9365-423c-b27a-a6c206850848\nbegin\n\t# plotting data\n\tscatter(xvals, yvals, color=:black, label=\"Data\",\n\t\t\txlabel=\"X values\", ylabel=\"Y values\", legend=:topleft)\n\n\t# plotting \"from scratch\" fitted line\n\tplot!(xvals, y\u0302vals\u2081, color=:red, label=\"From Scratch\")\n\n\t# plotting numpy model\n\tplot!(xvals, y\u0302vals\u2082, color=:green, label=\"Numpy\")\n\n\t# plotting GLM model\n\tplot!(xvals, y\u0302vals\u2083, color=:blue, label=\"GLM\")\nend\n\n# \u2554\u2550\u2561 a89ec73a-5e35-49ad-8829-dc2ecc7e8aac\nmd\"\"\"\n## Load real data\n\nNow let's get some real data. We will use housing information from zillow, check out the file `zillow_data_download_april2020.xlsx` for a quick look of what the data looks like. Our goal will be to build a linear regression model between the number of houses listed vs the number of houses sold in a few states. Fitting these models can serve as a key real estate indicator.\n\"\"\"\n\n# \u2554\u2550\u2561 aa78c706-8860-46f1-9982-ea10bdc4fccb\n# loading data\nS = XLSX.readxlsx(\"data/zillow_data_download_april2020.xlsx\")\n\n# \u2554\u2550\u2561 618ab9ee-ee9c-4dbb-b48f-ebeeb15549c6\nmd\"\"\"\n**Note:** there are three different sheets in our data.\n\n## Data wrangling\n\nLet's create a `DataFrame` from the `Sale_counts_city` sheet...\n\"\"\"\n\n# \u2554\u2550\u2561 b530e842-bfa4-4c41-9cc9-4aa629e12f99\n# selecting sheet\nsale_counts = S[\"Sale_counts_city\"][:]\n\n# \u2554\u2550\u2561 041e87c7-deee-46c1-85be-ea47df16217c\n# converting Matrix into DataFrame\ndf_sale_counts = DataFrame(sale_counts[2:end,:], Symbol.(sale_counts[1,:]))\n\n# \u2554\u2550\u2561 19a44596-2367-4964-b21e-7d84ba147915\nmd\"\"\"\nNow, we can do the same with the `MonthlyListings_City` sheet...\n\"\"\"\n\n# \u2554\u2550\u2561 ab8cf8d2-9ac6-4361-b168-243f781e7dfa\nbegin\n\t# selecting sheet\n\tmonth_list = S[\"MonthlyListings_City\"][:]\n\t# converting Matrix into DataFrame\n\tdf_month_list = DataFrame(month_list[2:end,:], Symbol.(month_list[1,:]))\nend\n\n# \u2554\u2550\u2561 215483a1-6059-437d-a4b6-ca3cd897f13b\nmd\"\"\"\nWe may filter just the data from February 2020...\n\"\"\"\n\n# \u2554\u2550\u2561 b075d090-91aa-4d1f-bb9f-a93dd65413e7\nbegin\n\t# monthly listing data (Feb 2020)\n\tmonthlist_2020_2 = df_month_list[!,[1,2,3,4,5,end]]\n\trename!(monthlist_2020_2, Symbol(\"2020-02\") => :listing)\nend\n\n# \u2554\u2550\u2561 1b8f7b0d-a843-4af7-90b7-4a64d74edab0\nbegin\n\t# sale counts data (Feb 2020)\n\tsalecounts_2020_2 = df_sale_counts[!,[1,end]]\n\trename!(salecounts_2020_2, Symbol(\"2020-02\") => :sales)\nend\n\n# \u2554\u2550\u2561 39456bea-24dc-482b-9d8b-33a9f2ed715a\nmd\"\"\"\nNext, we can (outer) join our two DataFrames and, then, remove missing values...\n\"\"\"\n\n# \u2554\u2550\u2561 f195db71-f2a4-4f5c-bfa4-2d9ec1f23a32\nbegin\n\tfeb2020data = outerjoin(monthlist_2020_2, salecounts_2020_2, on=:RegionID)\n\tdropmissing!(feb2020data)\nend\n\n# \u2554\u2550\u2561 2da58c4e-8db4-4d80-aa29-f3ec10952f73\nmd\"\"\"\nLet's define variables for all the three columns we are interested in...\n\"\"\"\n\n# \u2554\u2550\u2561 93179d9a-5bf4-488b-b710-28a5f56b2e26\nbegin\n\tsales = feb2020data[!,:sales]\n\tcounts = feb2020data[!,:listing]\n\tstates = feb2020data[!,:StateName]\nend;\n\n# \u2554\u2550\u2561 560a134f-1175-4d56-83af-1ad6bbe1a99f\nmd\"\"\"\nNow, we can select just the top 10 states (most cited states). We will use the `counter` function from the [DataStructures.jl](https://github.com/JuliaCollections/DataStructures.jl) package.\n\"\"\"\n\n# \u2554\u2550\u2561 0c4a00f6-69f2-4fc3-a7f8-ca6e38404ac9\n# counter object (Accumulator)\nC = counter(states)\n\n# \u2554\u2550\u2561 a02a9fdf-46bc-4ea1-bb29-b1731a66c057\n# converting into a Dictionary\nCdict = C.map\n\n# \u2554\u2550\u2561 63b596be-9392-4efb-8d31-7f1d6e9c7254\nbegin\n\t# getting counts as an Array\n\tcountvals = values(Cdict) |> collect\n\t\n\t# getting state names as an Array\n\tstate_labels = keys(Cdict) |> collect\nend;\n\n# \u2554\u2550\u2561 feced955-2e69-44ae-bc2a-82d4f2136b38\n# getting indexes from 10 top states\ntopstateindexes = sortperm(countvals, rev=true)[1:10]\n\n# \u2554\u2550\u2561 831484f5-6cdc-4641-8adf-117a33c518c2\nmd\"\"\"\n**Note:** the built-in `sortperm` function returns a permutation vector `I` that puts `v[I]` in sorted order. The order is specified using the same keywords as `sort!`.\n\"\"\"\n\n# \u2554\u2550\u2561 b94019d8-a7d8-4781-819b-28eeac823812\n# getting top 10 states names\ntopstates = state_labels[topstateindexes]\n\n# \u2554\u2550\u2561 4735fc87-68cb-4617-aa7c-6139ba7b7c0a\nmd\"\"\"\n## Linear regression models\n\nFirstly, we will plot the model for each state using the formula `Y ~ X`.\n\"\"\"\n\n# \u2554\u2550\u2561 ec7ae9e6-b191-4578-8a47-9d2245280316\nbegin\n\t# creating a blank Array of Plot\n\tall_plots\u2081 = Array{Plots.Plot,1}(undef,10)\n\n\tfor (i,s) in enumerate(topstates)\n\t\t# finding indexes of all occurences of a given state\n\t\tids = findall(feb2020data[!,:StateName] .== s)\n\t\t# getting data for a given state\n\t\tdata = DataFrame(X=Float64.(counts[ids]), Y=Float64.(sales[ids]))\n\t\t# training the model\n\t\tols = GLM.lm(@formula(Y ~ X), data)\n\n\t\t# plotting data by each state\n\t\tall_plots\u2081[i] = scatter(data.X, data.Y, markersize=2,\n\t\t\t\t\t\t\t\txlims=(0,500), ylims=(0,500),\n\t\t\t\t\t\t\t\tcolor=i, aspect_ratio=:equal,\n\t\t\t\t\t\t\t\tlegend=false, title=s)\n\n\t\t# plotting model by each state\n\t\tplot!(data.X, predict(ols), color=:black)\n\tend\n\n\t# display plots\n\tplot(all_plots\u2081..., layout=(2,5), size=(850,300))\nend\n\n# \u2554\u2550\u2561 216dc17e-54c1-4520-890d-8663165b10dd\nmd\"\"\"\nWe can do the same thing, but now we will plot all the elements within the same figure.\n\n**Note:** when we use the `Y ~ X + 0` formula, it forces the intercept to be zero.\n\"\"\"\n\n# \u2554\u2550\u2561 dddfb8fb-7047-4417-8dd2-569a93277f0c\nbegin\n\tplot()\n\t\n\tfor (i,s) in enumerate(topstates)\n\t    ids = findall(feb2020data[!,:StateName] .== s)\n\t    data = DataFrame(X=Float64.(counts[ids]), Y=Float64.(sales[ids]))\n\t    ols = GLM.lm(@formula(Y ~ 0 + X), data)\n\t\t\n\t    scatter!(counts[ids], sales[ids], markersize=2, xlim=(0,500),\n\t\t\t\t ylim=(0,500), color=i, aspect_ratio=:equal,\n\t        \t legend=false, marker=(3,3,stroke(0)), alpha=0.2)\n\t\t\n\t    if s \u2208 [\"NC\",\"CA\",\"FL\"]\n\t        annotate!([(500-20,10+coef(ols)[1]*500, text(s,10))])\n\t    end\n\n\t    plot!(counts[ids], predict(ols), color=i, linewidth=2)\n\tend\n\n\txlabel!(\"Listings\")\n\tylabel!(\"Sales\")\nend\n\n# \u2554\u2550\u2561 5116c117-75e4-4989-b06f-2883bba48330\nmd\"\"\"\n## Logistic regression\n\nSo far, we have shown several ways to solve the linear regression problem in Julia. Here, we will first start with a motivating example of when you would want to use logistic regression. Let's assume that our predictor vector is binary (`0` or `1`), let's fit a linear regression model.\n\"\"\"\n\n# \u2554\u2550\u2561 3a86069b-3f24-4eec-a7ae-f77189a4fd77\n# generating random data\n\ud835\udcae = DataFrame(X=collect(1:7), Y=[1,0,1,1,1,1,1])\n\n# \u2554\u2550\u2561 453385dd-8bda-42b8-9b4a-6a4963b21346\n# linear regression model\nlin_reg = lm(@formula(Y ~ X), \ud835\udcae)\n\n# \u2554\u2550\u2561 bd31693d-dee9-4534-b4d4-3904997e8020\nbegin\n\t# plotting data\n\tscatter(\ud835\udcae.X, \ud835\udcae.Y, legend=false, xlabel=\"X\", ylabel=\"Y\")\n\t#plotting model\n\tplot!(1:7, predict(lin_reg))\nend\n\n# \u2554\u2550\u2561 0fb142cd-ac45-42e8-b5d1-24c6142392bb\nmd\"\"\"\nWhat this plot quickly shows is that linear regression may end up predicting values outside the `[0,1]` interval. For an example like this, we will use logistic regression. Interestingly, a generalized linear model (https://en.wikipedia.org/wiki/Generalized_linear_model) unifies concepts like linear regression and logistic regression, and the [GLM.jl](https://github.com/JuliaStats/GLM.jl) package allows you to apply either of these regressions easily by specifying the `distribution family` and the `link` function.\n\nTo apply logistic regression via the `GLM.jl` package, you can readily use the `Binomial` family and the `LogitLink` link function.\n\n### Load data\n\nFirstly, let's load some data from the [RDatasets.jl](https://github.com/JuliaStats/RDatasets.jl) package...\n\"\"\"\n\n# \u2554\u2550\u2561 3caa5331-2507-4299-b2e4-50e8a5cbbe46\ncats = dataset(\"MASS\", \"cats\")\n\n# \u2554\u2550\u2561 22c201af-9437-4dde-8653-508ebf514008\nmd\"\"\"\n### Data wrangling\n\nWe will map the sex of each cat to a binary `0/1` value.\n\"\"\"\n\n# \u2554\u2550\u2561 16367b7a-65ea-4fa0-abad-a1cc25c60ee6\n# getting the map\nsex_map = labelmap(cats.Sex)\n\n# \u2554\u2550\u2561 1d7ef9db-dd15-4ed4-841a-b4baf02302a1\n# encoding Sex column\nsex_enconde = labelencode(sex_map, cats.Sex)\n\n# \u2554\u2550\u2561 f42bdc3a-943b-4157-853d-860af52e059c\n# plotting data by Sex\nscatter(cats.BWt, cats.HWt, color=sex_enconde, legend=false)\n\n# \u2554\u2550\u2561 310f2282-d6dd-405d-8399-e75fdc75c27c\nmd\"\"\"\nFemales (blue) seem to be more present in the lower left corner and Males (orange) seem to be present in the top right corner.\n\nWe will use the `HWt` variable as the only feature and the `encoded_sex` as the target. Let's convert labels from `1/2` into `0/1`...\n\"\"\"\n\n# \u2554\u2550\u2561 cc911a53-9139-4c90-b02b-15f30e6772f0\ncats_df = DataFrame(X=cats[!,:HWt], Y=sex_enconde .- 1)\n\n# \u2554\u2550\u2561 79bbe213-c15a-4ecb-aef7-107846234f1d\nmd\"\"\"\n### Modeling data\n\nLet's run a logistic regression model on this data.\n\"\"\"\n\n# \u2554\u2550\u2561 11b1f5d1-7ae2-43dd-bd35-5b0ba6fde6f4\n# logistic model\nprobit = glm(@formula(Y ~ X), cats_df, Binomial(), LogitLink())\n\n# \u2554\u2550\u2561 e3e9d570-af57-4065-84ec-b61400fa449d\nbegin\n\t# plotting ground truth data\n\tscatter(cats_df.X, cats_df.Y, label=\"Ground Truth\", color=6)\n\t\n\t# plotting predictions\n\tscatter!(cats_df.X, predict(probit), label=\"Predictions\", color=7,\n\t\t\t xlabel=\"Heart Rate\", ylabel=\"Pr(Sex=M)\")\nend\n\n# \u2554\u2550\u2561 dfc76a4c-4e2b-4588-92e1-2209507fd670\nmd\"\"\"\n**Note:** as you can see, contrary to the linear regression case, the predicted values do not go beyond `1`.\n\"\"\"\n\n# \u2554\u2550\u2561 31308555-dfc9-4e28-9108-8a83d65b7770\nmd\"\"\"\n## Non-linear regression\n\nFinally, sometimes you may have a set of points and the goal is to fit a non-linear function (maybe a quadratic function, a cubic function, an exponential function...). The way we would solve such a problem is by minimizing the least square error between the fitted function and the observations we have. We will use the package [LsqFit.jl](https://github.com/JuliaNLSolvers/LsqFit.jl) for this task.\n\n**Note:** this problem is usually modeled as a numerical optimizaiton problem.\n\"\"\"\n\n# \u2554\u2550\u2561 4a7d2c25-04b1-4ccb-85cd-7276902a9679\nmd\"\"\"\n### Generate data\n\nWe will first set up our data and plot it...\n\"\"\"\n\n# \u2554\u2550\u2561 7203ba1b-ce21-4c53-9dce-358df13df21e\nbegin\n\tx = 0:0.05:10\n\ty = 1 * exp.(-x * 2) + 2 * sin.(0.8 * \u03c0 * x) + 0.15 * randn(length(x));\n\tscatter(x, y, legend=false)\nend\n\n# \u2554\u2550\u2561 775e6fbe-8c10-4f94-b53e-618e4dd551fc\nmd\"\"\"\n### Modeling data\n\nThen, we set up the model with `model(x,p)`. The vector `p` is what to be estimated given a set of values `x`.\n\"\"\"\n\n# \u2554\u2550\u2561 5d75ebce-1181-4490-ae10-8bcc08456fdf\nbegin\n\t@. model(v, p) = p[1] * exp(-v * p[2]) + p[3] * sin(0.8 * \u03c0 *v)\n\tp0 = [0.5, 0.5, 0.5]\n\tmyfit = curve_fit(model, x, y, p0)\nend\n\n# \u2554\u2550\u2561 a94163fe-e1ac-483a-bc2d-5d7795cfe188\nmd\"\"\"\n\u26a0\ufe0f A note about `curve_fit`: this function can take multiple other inputs, for instance the Jacobian of what you are trying to fit. We don't dive into these details here, but be sure to check out the LsqFit.jl package to see what other things you can can pass to create a better fit.\n\nAlso note that julia has multiple packages that allow you to create Jacobians so you don't have to write them yourself. Two such packages are [FiniteDifferences.jl](https://github.com/JuliaDiff/FiniteDifferences.jl) or [ForwardDiff.jl](https://github.com/JuliaDiff/ForwardDiff.jl).\n\n\u21aa\ufe0f Back to our example. Let's define the paramenter variable and then calculate the predictions `y\u0302`...\n\"\"\"\n\n# \u2554\u2550\u2561 6a965e6d-4724-47c8-a3bb-bfec7d6706c9\nbegin\n\tp = myfit.param\n\ty\u0302 = p[1] * exp.(-x * p[2]) + p[3] * sin.(0.8 * \u03c0 * x)\nend\n\n# \u2554\u2550\u2561 c7d07a47-3f3f-482e-9c06-78877b91e380\nmd\"\"\"\nWe are ready now to plot the curve we have generated...\n\"\"\"\n\n# \u2554\u2550\u2561 6ca3290d-5980-4749-b309-fd84d73b7bb5\nbegin\n\tscatter(x, y, legend=false, xlabel=\"X\", ylabel=\"Y\")\n\tplot!(x, y\u0302)\nend\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500d16725a0-6cd3-11ec-0998-fd4af26f10dd\n# \u255f\u250091471950-703f-4927-8bce-f4478f4a53ba\n# \u255f\u2500a53d44c5-75c4-4508-aa19-33e838c9e0bb\n# \u255f\u2500e9458f99-4ec0-4167-b771-3090dfec6320\n# \u255f\u2500784c5b0e-59dc-4b2d-bf40-112261ac8e85\n# \u2560\u255065e22edc-ef5c-412f-82f4-1c84da209d6d\n# \u255f\u2500db2c3459-2127-4b46-8e73-546850767dc0\n# \u2560\u25503bb8c382-f97d-48dc-8cbe-99bf77de0784\n# \u255f\u250075059ff4-6b9d-4e01-9aed-33ea8b0e9a71\n# \u2560\u2550e83331a1-8655-4de0-a36f-b74b5e43674b\n# \u255f\u2500d81e448b-b4e4-4d6f-8ca7-42c41569977d\n# \u2560\u2550a047abfb-178c-40ac-8f8c-c3a8a73c1849\n# \u2560\u2550208af138-5131-4034-885b-c41f6ccf36f5\n# \u2560\u255039884fc4-c41c-46e5-a92a-44d766243715\n# \u255f\u250013719feb-60ae-433b-bf1e-df6ac045215d\n# \u2560\u255010c072d4-b793-458c-b947-d5dc3aae5e25\n# \u2560\u255068a0574f-5b17-48ae-b8c4-a03c7e385561\n# \u2560\u2550ecb1cb29-2b57-4197-9327-e762fc876281\n# \u255f\u2500056b28f3-8da4-4a94-a33c-72b30c8aa0aa\n# \u255f\u25009a5dcad1-9365-423c-b27a-a6c206850848\n# \u255f\u2500a89ec73a-5e35-49ad-8829-dc2ecc7e8aac\n# \u2560\u2550aa78c706-8860-46f1-9982-ea10bdc4fccb\n# \u255f\u2500618ab9ee-ee9c-4dbb-b48f-ebeeb15549c6\n# \u2560\u2550b530e842-bfa4-4c41-9cc9-4aa629e12f99\n# \u2560\u2550041e87c7-deee-46c1-85be-ea47df16217c\n# \u255f\u250019a44596-2367-4964-b21e-7d84ba147915\n# \u2560\u2550ab8cf8d2-9ac6-4361-b168-243f781e7dfa\n# \u255f\u2500215483a1-6059-437d-a4b6-ca3cd897f13b\n# \u2560\u2550b075d090-91aa-4d1f-bb9f-a93dd65413e7\n# \u2560\u25501b8f7b0d-a843-4af7-90b7-4a64d74edab0\n# \u255f\u250039456bea-24dc-482b-9d8b-33a9f2ed715a\n# \u2560\u2550f195db71-f2a4-4f5c-bfa4-2d9ec1f23a32\n# \u255f\u25002da58c4e-8db4-4d80-aa29-f3ec10952f73\n# \u2560\u255093179d9a-5bf4-488b-b710-28a5f56b2e26\n# \u255f\u2500560a134f-1175-4d56-83af-1ad6bbe1a99f\n# \u2560\u25500c4a00f6-69f2-4fc3-a7f8-ca6e38404ac9\n# \u2560\u2550a02a9fdf-46bc-4ea1-bb29-b1731a66c057\n# \u2560\u255063b596be-9392-4efb-8d31-7f1d6e9c7254\n# \u2560\u2550feced955-2e69-44ae-bc2a-82d4f2136b38\n# \u255f\u2500831484f5-6cdc-4641-8adf-117a33c518c2\n# \u2560\u2550b94019d8-a7d8-4781-819b-28eeac823812\n# \u255f\u25004735fc87-68cb-4617-aa7c-6139ba7b7c0a\n# \u2560\u2550ec7ae9e6-b191-4578-8a47-9d2245280316\n# \u255f\u2500216dc17e-54c1-4520-890d-8663165b10dd\n# \u2560\u2550dddfb8fb-7047-4417-8dd2-569a93277f0c\n# \u255f\u25005116c117-75e4-4989-b06f-2883bba48330\n# \u2560\u25503a86069b-3f24-4eec-a7ae-f77189a4fd77\n# \u2560\u2550453385dd-8bda-42b8-9b4a-6a4963b21346\n# \u2560\u2550bd31693d-dee9-4534-b4d4-3904997e8020\n# \u255f\u25000fb142cd-ac45-42e8-b5d1-24c6142392bb\n# \u2560\u25503caa5331-2507-4299-b2e4-50e8a5cbbe46\n# \u255f\u250022c201af-9437-4dde-8653-508ebf514008\n# \u2560\u255016367b7a-65ea-4fa0-abad-a1cc25c60ee6\n# \u2560\u25501d7ef9db-dd15-4ed4-841a-b4baf02302a1\n# \u2560\u2550f42bdc3a-943b-4157-853d-860af52e059c\n# \u255f\u2500310f2282-d6dd-405d-8399-e75fdc75c27c\n# \u2560\u2550cc911a53-9139-4c90-b02b-15f30e6772f0\n# \u255f\u250079bbe213-c15a-4ecb-aef7-107846234f1d\n# \u2560\u255011b1f5d1-7ae2-43dd-bd35-5b0ba6fde6f4\n# \u2560\u2550e3e9d570-af57-4065-84ec-b61400fa449d\n# \u255f\u2500dfc76a4c-4e2b-4588-92e1-2209507fd670\n# \u255f\u250031308555-dfc9-4e28-9108-8a83d65b7770\n# \u255f\u25004a7d2c25-04b1-4ccb-85cd-7276902a9679\n# \u2560\u25507203ba1b-ce21-4c53-9dce-358df13df21e\n# \u255f\u2500775e6fbe-8c10-4f94-b53e-618e4dd551fc\n# \u2560\u25505d75ebce-1181-4490-ae10-8bcc08456fdf\n# \u255f\u2500a94163fe-e1ac-483a-bc2d-5d7795cfe188\n# \u2560\u25506a965e6d-4724-47c8-a3bb-bfec7d6706c9\n# \u255f\u2500c7d07a47-3f3f-482e-9c06-78877b91e380\n# \u2560\u25506ca3290d-5980-4749-b309-fd84d73b7bb5\n", "meta": {"hexsha": "f845105a9916e3424a57acc51c105281321d3591", "size": 18091, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "07_Regression.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": "07_Regression.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": "07_Regression.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.1903914591, "max_line_length": 519, "alphanum_fraction": 0.7256646952, "num_tokens": 7545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465098415279, "lm_q2_score": 0.9173026595857203, "lm_q1q2_score": 0.8579958411118547}}
{"text": "# Classical Multidimensional Scaling\n\n## convert Gram matrix to Distance matrix\n\n\"\"\"\n    gram2dmat!(D, G)\n\nConvert a Gram matrix `G` to a distance matrix, and write the results to `D`.\n\"\"\"\nfunction gram2dmat!(D::AbstractMatrix{DT}, G::AbstractMatrix) where {DT<:Real}\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\n\"\"\"\n    gram2dmat(G)\n\nConvert a Gram matrix `G` to a distance matrix.\n\"\"\"\ngram2dmat(G::AbstractMatrix{T}) where {T<:Real} = gram2dmat!(similar(G, T), G)\n\n## convert Distance matrix to Gram matrix\n\n\"\"\"\n    dmat2gram!(G, D)\n\nConvert a distance matrix `D` to a Gram matrix, and write the results to `G`.\n\"\"\"\nfunction dmat2gram!(G::AbstractMatrix{GT}, D::AbstractMatrix) where GT\n    # argument checking\n    n = LinearAlgebra.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\nmomenttype(T) = typeof((zero(T) * zero(T) + zero(T) * zero(T))/ 2)\n\n\"\"\"\n    dmat2gram(D)\n\nConvert a distance matrix `D` to a Gram matrix.\n\"\"\"\ndmat2gram(D::AbstractMatrix{T}) where {T<:Real} = dmat2gram!(similar(D, momenttype(T)), D)\n\n## Classical MDS\n\n\"\"\"\n*Classical Multidimensional Scaling* (MDS), also known as Principal Coordinates Analysis (PCoA),\nis a specific technique in this family that accomplishes the embedding in two steps:\n\n1. Convert the distance matrix to a Gram matrix. This conversion is based on\nthe following relations between a distance matrix ``D`` and a Gram matrix ``G``:\n\n```math\n\\\\mathrm{sqr}(\\\\mathbf{D}) = \\\\mathbf{g} \\\\mathbf{1}^T + \\\\mathbf{1} \\\\mathbf{g}^T - 2 \\\\mathbf{G}\n```\n\nHere, ``\\\\mathrm{sqr}(\\\\mathbf{D})`` indicates the element-wise square of ``\\\\mathbf{D}``,\nand ``\\\\mathbf{g}`` is the diagonal elements of ``\\\\mathbf{G}``. This relation is\nitself based on the following decomposition of squared Euclidean distance:\n\n```math\n\\\\| \\\\mathbf{x} - \\\\mathbf{y} \\\\|^2 = \\\\| \\\\mathbf{x} \\\\|^2 + \\\\| \\\\mathbf{y} \\\\|^2 - 2 \\\\mathbf{x}^T \\\\mathbf{y}\n```\n\n2. Perform eigenvalue decomposition of the Gram matrix to derive the coordinates.\n\n*Note:*  The Gramian derived from ``D`` may have non-positive or degenerate\neigenvalues.  The subspace of non-positive eigenvalues is projected out\nof the MDS solution so that the strain function is minimized in a\nleast-squares sense.  If the smallest remaining eigenvalue that is used\nfor the MDS is degenerate, then the solution is not unique, as any\nlinear combination of degenerate eigenvectors will also yield a MDS\nsolution with the same strain value.\n\"\"\"\nstruct MDS{T<:Real} <: NonlinearDimensionalityReduction\n    d::Real                  # original dimension\n    X::AbstractMatrix{T}     # fitted data, X (d x n)\n    \u03bb::AbstractVector{T}     # eigenvalues in feature space, (k x 1)\n    U::AbstractMatrix{T}     # eigenvectors in feature space, U (n x k)\nend\n\n## properties\n\"\"\"\n    size(M)\n\nReturns tuple where the first value is the MDS model `M` input dimension,\n*i.e* the dimension of the observation space, and the second value is the output\ndimension, *i.e* the dimension of the embedding.\n\"\"\"\nsize(M::MDS) = (M.d, size(M.U,2))\n\n\"\"\"\n    projection(M)\n\nGet the MDS model `M` eigenvectors matrix (of size ``(n, p)``) of the embedding space.\nThe eigenvectors are arranged in descending order of the corresponding eigenvalues.\n\"\"\"\nprojection(M::MDS) = M.U\n\n\"\"\"\n    eigvecs(M::MDS)\n\nGet the MDS model `M` eigenvectors matrix. \n\"\"\"\neigvecs(M::MDS) = projection(M)\n\n\"\"\"\n    eigvals(M::MDS)\n\nGet the eigenvalues of the MDS model `M`.\n\"\"\"\neigvals(M::MDS) = M.\u03bb\n\n\"\"\"\n    loadings(M::MDS)\n\nGet the loading of the MDS model `M`.\n\"\"\"\nloadings(M::MDS) = sqrt.(M.\u03bb)' .* M.U\n\n## use\n\n\"\"\"\n    predict(M, x::AbstractVector)\n\nCalculate the out-of-sample transformation of the observation `x` for the MDS model `M`.\nHere, `x` is a vector of length `d`.\n\"\"\"\nfunction predict(M::MDS, x::AbstractVector{T}; distances=false) where {T<:Real}\n    d = if isnan(M.d) # model has only distance matrix\n        @assert distances \"Cannot transform points if model was fitted with a distance matrix. Use point distances.\"\n        size(x, 1) != size(M.X, 1) && throw(\n            DimensionMismatch(\"Point distances should be calculated to all original points\"))\n        x\n    else\n        if distances\n            size(x, 1) != size(M.X, 2) && throw(\n                DimensionMismatch(\"Point distances should be calculated to all original points.\"))\n            x\n        else\n            size(x, 1) != size(M.X, 1) && throw(\n                DimensionMismatch(\"Points and original data must have same dimensionality.\"))\n            pairwise((x,y)->norm(x-y), M.X, x)\n        end\n    end\n\n    # get distance matrix\n    D = isnan(M.d) ? M.X : pairwise((x,y)->norm(x-y), eachcol(M.X), symmetric=true)\n    d = d.^2\n\n    # b = 0.5*(ones(n,n)*d./n - d + D*ones(n,1)./n - ones(n,n)*D*ones(n,1)./n^2)\n    mD = mean(D.^2, dims=2)\n    b = (d  .- mean(d, dims=1) .- mD .+ mean(mD)) ./ -2\n\n    # sqrt(\u03bb)\u207b\u00b9U'b\n    \u03bb = vcat(M.\u03bb, zeros(T, size(M)[2] - length(M.\u03bb)))\n    return M.U' * b ./ sqrt.(\u03bb)\nend\n\n\"\"\"\n    predict(M)\n\nReturns a coordinate matrix of size ``(p, n)`` for the MDS model `M`, where each column\nis the coordinates for an observation in the embedding space.\n\"\"\"\nfunction predict(M::MDS{T}) where {T<:Real}\n    d, p = size(M)\n    # if there are non-positive missing eigval then pad with zeros\n    \u03bb = vcat(M.\u03bb, zeros(T, p - length(M.\u03bb)))\n    return diagm(0=>sqrt.(\u03bb)) * M.U'\nend\n\n## show\n\nfunction show(io::IO, M::MDS)\n    d, p = size(M)\n    print(io, \"Classical MDS(indim = $d, outdim = $p)\")\nend\n\n## interface functions\n\n\"\"\"\n    fit(MDS, X; kwargs...)\n\nCompute an embedding of `X` points by classical multidimensional scaling (MDS).\nThere are two calling options, specified via the required keyword argument `distances`:\n\n    mds = fit(MDS, X; distances=false, maxoutdim=size(X,1)-1)\n\nwhere `X` is the data matrix. Distances between pairs of columns of `X` are computed using the Euclidean norm.\nThis is equivalent to performing PCA on `X`.\n\n    mds = fit(MDS, D; distances=true, maxoutdim=size(D,1)-1)\n\nwhere `D` is a symmetric matrix `D` of distances between points.\n\"\"\"\nfunction fit(::Type{MDS}, X::AbstractMatrix{T};\n             maxoutdim::Int = size(X,1)-1,\n             distances::Bool) where T<:Real\n\n    # get distance matrix and space dimension\n    D, d = if !distances\n        pairwise((x,y)->norm(x-y), eachcol(X), symmetric=true), size(X,1)\n    else\n        X, NaN\n    end\n    G = dmat2gram(D)\n\n    n = size(D, 1)\n    m = min(maxoutdim, n) #Actual number of eigenpairs wanted\n\n    E = eigen!(Hermitian(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    mineig, maxeig = extrema(E.values)\n    if mineig < 0 && abs(mineig) > abs(maxeig)\n        #do flip\n        ord = sortperm(E.values)\n        \u03bb = -E.values[ord[1:m]]\n    else\n        ord = sortperm(E.values; rev=true)\n        \u03bb = E.values[ord[1:m]]\n    end\n\n    for i in 1:m\n        if \u03bb[i] <= 0\n            #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            @warn(\"Gramian has only $(i-1) positive eigenvalue(s)\")\n            m = i-1\n            ord = ord[1:m]\n            \u03bb = \u03bb[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]] .- \u03bb[m]) .< n*eps())\n        nevals = sum(abs.(E.values .- \u03bb[m]) .< n*eps())\n        if nevalsmore > 1\n            @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\n    #Add trailing zero coordinates if dimension of embedding space (p) exceeds\n    #number of eigenpairs used (m)\n    if m < maxoutdim\n        U = [U zeros(T, n, maxoutdim-m)]\n    end\n\n    return MDS(d, X, \u03bb, U)\nend\n\n\n\"\"\"\n    stress(M)\n\nGet the stress of the MDS mode `M`.\n\"\"\"\nfunction stress(M::MDS)\n    # calculate distances if original data was stored\n    DX = isnan(M.d) ? M.X : pairwise((x,y)->norm(x-y), eachcol(M.X), symmetric=true)\n    DY = pairwise((x,y)->norm(x-y), eachcol(predict(M)), symmetric=true)\n    n = size(DX,1)\n    return sqrt(2*sum((DX - DY).^2)/sum(DX.^2));\nend\n\n", "meta": {"hexsha": "6d6f21f3049e0ed708e6a0dc15c20f6f9ea39483", "size": 9265, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/cmds.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/cmds.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/cmds.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.9838187702, "max_line_length": 125, "alphanum_fraction": 0.6151106314, "num_tokens": 2760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778000158575, "lm_q2_score": 0.8962513745192024, "lm_q1q2_score": 0.8579615440609305}}
{"text": "\nexport minkowski_distance, euclidian_distance, manhattan_distance, chebyshev_distance, braycurtis_distance, canberra_distance, cityblock_distance, mahalanobis_distance,\ncorrelation, cosine_distance, cosine_similarity\n\nusing LinearAlgebra\nusing Statistics: mean\n\n#TODO\n# scikitlearn-like kernels ?\n\n# Distance methods\n\n\"\"\"\n```minkowski_distance(u,v; keywords)```\n```minkowski_distance(x::Tuple; keywords)```\n\nReturn the Minkowski distance between the given points both of which are given with vector-like structures.\n\n## Arguments\n- `u` : first point\n- `v` : second point\n- `x::Tuple` : tuple as follows: (u,v)\n\n## Keywords\n- `p::Int = 2` : p value\n- `w::Int` : weights that must be of the same length with u,v\n- `rooted = false` : denotes whether or not to execute the final rooting operation\n\"\"\"\nfunction minkowski_distance(u,v; p = 2, w = nothing, rooted = false)\n    _validate_distance_input(u, v, w; p = p, p_is_used = true)\n    val = abs.(u .- v)\n    val = w != nothing ? val .* w : val\n    if p == 1\n        val = sum(val)\n    elseif p == Inf\n        val = maximum(val)\n    else\n        val = sum(val .^ p)\n    end\n    return rooted ? val .^ (1 / p) : val\nend\n\nminkowski_distance(x::Tuple; p = 2, w = nothing) = minkowski_distance(x...; p = p, w = w)\n\n\"\"\"\n```euclidian_distance(u,v; keywords)```\n```euclidian_distance(x::Tuple; keywords)```\n\nReturn the Euclidian distance between the given points both of which are given with vector-like structures.\n\n## Arguments\n- `u` : first point\n- `v` : second point\n- `x::Tuple` : tuple as follows: (u,v)\n\n## Keywords\n- `w::Int` : weights that must be of the same length with u,v\n- `squared = false` : denotes whether or not to execute the final squaring operation\n\"\"\"\neuclidian_distance(u,v; w = nothing, squared = false) = minkowski_distance(u,v; w = w, p = 2, rooted = squared)\neuclidian_distance(x::Tuple;w = nothing, squared = false) = euclidian_distance(x...; w = w, rooted = squared)\n\n\"\"\"\n```manhattan_distance(u,v; keywords)```\n```manhattan_distance(x::Tuple; keywords)```\n\nReturn the Manhattan distance between the given points both of which are given with vector-like structures.\n\n## Arguments\n- `u` : first point\n- `v` : second point\n- `x::Tuple` : tuple as follows: (u,v)\n\n## Keywords\n- `w::Int` : weights that must be of the same length with u,v\n\"\"\"\nmanhattan_distance(u,v; w = nothing) = minkowski_distance(u,v; w = w, p = 1)\nmanhattan_distance(x::Tuple;w = nothing) = manhattan_distance(x...; w = w)\n\n\"\"\"\n```chebyshev_distance(u,v; keywords)```\n```chebyshev_distance(x::Tuple; keywords)```\n\nReturn the Chebyshev distance between the given points both of which are given with vector-like structures.\n\n## Arguments\n- `u` : first point\n- `v` : second point\n- `x::Tuple` : tuple as follows: (u,v)\n\n## Keywords\n- `w::Int` : weights that must be of the same length with u,v\n\"\"\"\nchebyshev_distance(u,v; w = nothing) = minkowski_distance(u,v; w = w, p = Inf, rooted=false)\nchebyshev_distance(x::Tuple;w = nothing) = chebyshev_distance(x...; w = w)\n\n\"\"\"\n```braycurtis_distance(u,v; keywords)```\n```braycurtis_distance(x::Tuple; keywords)```\n\nReturn the Braycurtis distance between the given points both of which are given with vector-like structures.\n\n## Arguments\n- `u` : first point\n- `v` : second point\n- `x::Tuple` : tuple as follows: (u,v)\n\n## Keywords\n- `w::Int` : weights that must be of the same length with u,v\n\"\"\"\nfunction braycurtis_distance(u,v; w = nothing)\n    _validate_distance_input(u, v, w)\n    difference = abs.(u .- v)\n    summation = abs.(u .+ v)\n    if w != nothing\n        difference = w .* difference\n        summation = w .* summation\n    end\n    sum(difference) / sum(summation)\nend\n\nbraycurtis_distance(x::Tuple; w = nothing) = braycurtis_distance(x...; w = w)\n\n\"\"\"\n```canberra_distance(u,v; keywords)```\n```canberra_distance(x::Tuple; keywords)```\n\nReturn the Canberra distance between the given points both of which are given with vector-like structures.\n\n## Arguments\n- `u` : first point\n- `v` : second point\n- `x::Tuple` : tuple as follows: (u,v)\n\n## Keywords\n- `w::Int` : weights that must be of the same length with u,v\n\"\"\"\nfunction canberra_distance(u,v; w = nothing)\n    _validate_distance_input(u, v, w)\n    difference = abs.(u .- v)\n    result = difference / (abs.(u) .+ abs.(v))\n    if w != nothing\n        result = result .* w\n    end\n    return  sum(result[result .!== Inf])\nend\ncanberra_distance(x::Tuple; w = nothing) = canberra_distance(x...; w = w)\n\n\"\"\"\n```cityblock_distance(u,v; keywords)```\n```cityblock_distance(x::Tuple; keywords)```\n\nReturn the Cityblock distance between the given points both of which are given with vector-like structures.\n\n## Arguments\n- `u` : first point\n- `v` : second point\n- `x::Tuple` : tuple as follows: (u,v)\n\n## Keywords\n- `w::Int` : weights that must be of the same length with u,v\n\"\"\"\nfunction cityblock_distance(u,v; w = nothing)\n    _validate_distance_input(u,v,w)\n    result = abs.(u .- v)\n    if w != nothing\n        result = result .* w\n    end\n    return sum(result)\nend\ncityblock_distance(x; w = nothing) = cityblock_distance(x...; w = w)\n\n\"\"\"\n```mahalanobis_distance(u,v; keywords)```\n```mahalanobis_distance(x::Tuple; keywords)```\n\nReturn the Cityblock distance between the given points both of which are given with vector-like structures.\n\n## Arguments\n- `u` : first point\n- `v` : second point\n- `x::Tuple` : tuple as follows: (u,v)\n- `Vinv::Matrix` : The inverse of the covariance matrix.\n\n\"\"\"\nfunction mahalanobis_distance(u,v, Vinv)\n    _validate_distance_input(u,v,nothing)\n    delta = u .- v\n    return sqrt.(dot(dot(delta, convert_1d(Vinv)), delta))\nend\n\nmahalanobis_distance(x::Tuple, Vinv) = mahalanobis_distance(x..., Vinv)\n\n##\n\n\"\"\"\n```correlation(u,v; keywords)```\n```correlation(x::Tuple; keywords)```\n\nReturn the Cityblock distance between the given points both of which are given with vector-like structures.\n\n## Arguments\n- `u` : first point\n- `v` : second point\n- `x::Tuple` : tuple as follows: (u,v)\n\n## Keywords\n- `w::Int` : weights that must be of the same length with u,v\n- `centered=true` : If true, u and v will be centered.\n\"\"\"\nfunction correlation(u,v; w = nothing, centered = true)\n    _validate_distance_input(u,v,w)\n    w = w != nothing ? w : ones(length(u))\n    _u = convert_1d(u)\n    _v = convert_1d(v)\n    if centered\n        umu = mean(_u .* w)\n        vmu = mean(_v .* w)\n        _u = _u .- umu\n        _v = _v .- vmu\n    end\n    uv = mean(_u .* _v .* w)\n    uu = mean( (_u .^ 2) .* w )\n    vv = mean( (_v .^ 2) .* w  )\n    return abs(1 - uv / sqrt(uu*vv))\nend\n\ncosine_distance(u,v;w=nothing) = correlation(u,v; w = w)\ncosine_similarity(u,v; w = nothing) = -cosine_distance(u,v; w = w) + 1\n", "meta": {"hexsha": "8c6e7ce45381f9173dc699dd700cb7c7f8119b3a", "size": 6663, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/pairwise/metrics.jl", "max_stars_repo_name": "KnetML/KnetMetrics.jl", "max_stars_repo_head_hexsha": "ad6aec57a9323de86b9851f1be23668f368b4a86", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-08-25T08:56:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T21:48:37.000Z", "max_issues_repo_path": "src/pairwise/metrics.jl", "max_issues_repo_name": "emirhan422/KnetMetrics", "max_issues_repo_head_hexsha": "ad6aec57a9323de86b9851f1be23668f368b4a86", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-12-31T10:02:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-01T20:09:53.000Z", "max_forks_repo_path": "src/pairwise/metrics.jl", "max_forks_repo_name": "emirhan422/KnetMetrics.jl", "max_forks_repo_head_hexsha": "ad6aec57a9323de86b9851f1be23668f368b4a86", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-22T18:53:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-22T18:53:48.000Z", "avg_line_length": 28.9695652174, "max_line_length": 168, "alphanum_fraction": 0.6632147681, "num_tokens": 1952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9719924785827003, "lm_q2_score": 0.8824278618165526, "lm_q1q2_score": 0.8577132445775035}}
{"text": "\"\"\"\nA 2D Rotation matrix is a mtrix that rotates a vector in a 2D real space by an angle theta.\nFor more info: https://en.wikipedia.org/wiki/Rotation_matrix\n\nThis function takes the angle `theta` in radians as input and returns a 2D Matrix which will rotate the the vector by angle `theta`.\n\"\"\"\nfunction rotation_matrix(\u03b8)\n\trot_mat = Matrix{Float64}(undef,2,2)\n\trot_mat[1,1]  = cos(\u03b8)\n\trot_mat[1,2] = -sin(\u03b8)\n\trot_mat[2,1] = sin(\u03b8)\n\trot_mat[2,2] = cos(\u03b8)\n\n\treturn rot_mat\nend\n", "meta": {"hexsha": "69400184d3d4a700a4cdbaa92bb267f64c65a9de", "size": 476, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/matrix/rotation-matrix.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/matrix/rotation-matrix.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/matrix/rotation-matrix.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": 29.75, "max_line_length": 132, "alphanum_fraction": 0.7205882353, "num_tokens": 154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9773707999669627, "lm_q2_score": 0.8774767970940975, "lm_q1q2_score": 0.8576201991283063}}
{"text": "#=\nPlease see\nhttps://computationalmindset.com/en/neural-networks/ordinary-differential-equation-solvers.html#ode2\nfor details\n=#\n\n#=Original problem\nx\u2032\u2032 + x\u2032 + 2x = 0\nx(0)=1\nx\u2032(0)=0\n=#\n\n#=Esplicit form of equation\nx\u2032\u2032 = -x\u2032 - 2x\n=#\n\n#=Analytical solution\nx(t) = e^(-t/2) (cos(\u221a7 t / 2) + sin(\u221a7 t / 2) / \u221a7)\n=#\n\nusing DifferentialEquations\nusing Plots\n\nfunction ode_fn(dx,x,p,t)\n    -dx -2.0 * x\nend\n\nan_sol(t) = exp(-t/2.0) *\n            (cos(sqrt(7.0) * t / 2.0) + sin(sqrt(7.0) * t / 2.0)/sqrt(7.0))\n\nt_begin=0.0\nt_end=12.0\ntspan = (t_begin,t_end)\nx_init=1.0\ndxdt_init=0.0\n\nprob = SecondOrderODEProblem(ode_fn, dxdt_init, x_init, tspan)\nnum_sol = solve(prob, Tsit5(), reltol=1e-8, abstol=1e-8)\nx_num_sol = [u[2] for u in num_sol.u]\n\nplot(num_sol.t, an_sol.(num_sol.t),\n    linewidth=2, ls=:dash,\n    title=\"ODE 2nd order IVP solved by D.E. package\",\n    xaxis=\"t\", yaxis=\"x\",\n    label=\"analytical\",\n    legend=true)\nplot!(num_sol.t, x_num_sol,\n    linewidth=1,\n    label=\"numerical\")\n", "meta": {"hexsha": "9565cef64b002be84c88b2ca9313fb1e2f46a10e", "size": 989, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ODEs/solver-demos/julia/DifferentialEquations/ode_2nd_ord_ivp_01.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/solver-demos/julia/DifferentialEquations/ode_2nd_ord_ivp_01.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/solver-demos/julia/DifferentialEquations/ode_2nd_ord_ivp_01.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": 19.78, "max_line_length": 100, "alphanum_fraction": 0.6349848332, "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259924, "lm_q2_score": 0.912436159286392, "lm_q1q2_score": 0.8576109269772355}}
{"text": "## The birthday paradox in theory and in practice.\n\n## Let's simulate the classic birthday paradox.\n# In this simulation, we will draw birthdays at random for a group\n# of N people, and see if there are any two birthdays that\n# are the same.\n\n\"\"\"\nN is the number of people\n\nThis function returns true if two people had the same birthday.\n\"\"\"\nfunction simple_birthday_simulation(N::Int)\n    birthdays = rand(1:365, N)\n    # so each birthday is an integer from 1 to 365.\n    # we need to check if all of the birthdays are unique\n    return !allunique(birthdays) # ! reverses true -> false, false -> true\nend\n\nsimple_birthday_simulation(20)\n\n## Let's look at what happens as we vary the number of people.\nntrials = 100\nprob_dup_birthday = zeros(0) # this is an empty array\nfor people=5:40\n    numdup = 0\n    for t=1:ntrials\n        numdup += simple_birthday_simulation(people)\n    end\n    push!(prob_dup_birthday, numdup/ntrials)\nend\n# make a quick people - by - prob table\ndisplay([5:40 prob_dup_birthday])\n# but also make a plot\nusing Plots\nplot(5:40, prob_dup_birthday)\nxlabel!(\"People\")\nylabel!(\"Prob. of shared birthday\")\n\n## Some ideas to improve\n# IDEA -- add confidence intervals\n# IDEA -- add \"exact\" curve based on prob.\n\n## Let's use real data.\nusing DelimitedFiles\nbirthdays = readdlm(\"1-julia-intro/birthday.txt\")\nplot(birthdays[:,2])\n\n## First step, let's simulate a random birthday from data.\nusing StatsBase\nbday_weights = fweights(Int.(birthdays[:,2]))\nsample(bday_weights)\n\n## Let's do the same demo\nsample_bdays = [sample(fweights([2,4,3,1])) for i=1:1000]\nsum(sample_bdays .== 4)\n\n## Let's implement the sampling ourselves too...\n\"\"\"\nN is the number of people\ndata is an array of length number of days with the number of people\nthat were born on that day.\n\nInternally, what this does is convert data to a cum. prob. distribution\nand then we use a random [0,1] sample to find where in the CDF we fall.\n\nThe idea of how this works is:\ngive probs [0.2 0.4 0.3 0.1] (i.e. we have 4 birthdays)\nthen we are going to make an array\n[0.2, 0.6, 0.9, 1.0]\nand then we are going to guess a random [0,1] variable\nand see which bin it falls into.\nif the rv. is less than 0.2, we will call it birthday 1\nif the rv. is less between 0.2, 0.6, we will call it birthday 2\nif the rv. is less between 0.6, 0.9, we will call it birthday 3\nif the rv. is less between 0.9, 1, we will call it birthday 4\nbut this will work for even larger lists too.\n\"\"\"\nfunction sample_birthdays(N::Int, data)\n    probs = data/sum(data)\n    cumdist = cumsum(probs)\n    bdays = zeros(Int, N)\n    for i=1:N\n        rv = rand()\n        for j=1:length(cumdist)\n            if rv <= cumdist[j]\n                bdays[i] = j\n                break # need to stop when we find the birthday\n            end\n        end\n    end\n    return bdays\nend\nbdays = sample_birthdays(1000, [2,4,3,1])\n# Let's check their frequency\nsum(bdays .== 3) # count the number of \"2\" birthdays in our test\n## IDEA - use binary search to find the right birthday faster.\n\n## Let's simulate the data-based shared birthday probability\nfunction data_birthday_simulation(N::Int, data)\n    birthdays = sample_birthdays(N, data)\n    # so each birthday is an integer from 1 to 365.\n    # we need to check if all of the birthdays are unique\n    return !allunique(birthdays) # ! reverses true -> false, false -> true\nend\n\ndata_birthday_simulation(20, Int.(birthdays[:,2]))\n\nntrials = 100\nprob_dup_birthday = zeros(0) # this is an empty array\nfor people=5:40\n    numdup = 0\n    for t=1:ntrials\n        numdup += data_birthday_simulation(people, Int.(birthdays[:,2]))\n    end\n    push!(prob_dup_birthday, numdup/ntrials)\nend\n# make a quick people - by - prob table\ndisplay([5:40 prob_dup_birthday])\n# but also make a plot\nusing Plots\nplot(5:40, prob_dup_birthday)\nxlabel!(\"People\")\nylabel!(\"Prob. of shared birthday based on data\")\n\n## TODO Do a test to show that this curve is higher than the uniform\n# case.\n\n\n## Use Julia's sampler\nfunction data_birthday_simulation_julia(N::Int, data)\n    w = fweights(data)\n    birthdays = [sample(w) for i=1:N]\n    # so each birthday is an integer from 1 to 365.\n    # we need to check if all of the birthdays are unique\n    return !allunique(birthdays) # ! reverses true -> false, false -> true\nend\nntrials = 100\nprob_dup_birthday = zeros(0) # this is an empty array\nfor people=5:40\n    numdup = 0\n    for t=1:ntrials\n        numdup += data_birthday_simulation_julia(people, Int.(birthdays[:,2]))\n    end\n    push!(prob_dup_birthday, numdup/ntrials)\nend\n# make a quick people - by - prob table\ndisplay([5:40 prob_dup_birthday])\n# but also make a plot\nusing Plots\nplot(5:40, prob_dup_birthday)\nxlabel!(\"People\")\nylabel!(\"Prob. of shared birthday based on data\")\n", "meta": {"hexsha": "bc74ed0b6da9ec44677995d9099274a1cee67310", "size": 4733, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "1-julia-intro/birthday-paradox.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/birthday-paradox.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/birthday-paradox.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.7337662338, "max_line_length": 78, "alphanum_fraction": 0.7008240017, "num_tokens": 1363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067147399245, "lm_q2_score": 0.9099069980980297, "lm_q1q2_score": 0.8575934554962407}}
{"text": "\"\"\"\n    lis_length(str_1::String, str_2::String)\n\nThe longest increasing subsequence (LIS) algorithm is dedicated to finding the longest\nincreasing subsequence for a given array.  This subsequence does not have to be contiguous\nor unique. \n    \n    1. Figure out the number of possible different subsequences of a string with length `m` and `n`.\n    2. Recontracted `for-loops` for defining the outer layer of the storing matrix `C`.\n    3. Checking if `str_1[i] == str_2[j]` and updating the count in  matrix `C`.\n    4.Return the latest element of `C[m,n]`.\n    \nFor more information see: [https://en.wikipedia.org/wiki/Longest_increasing_subsequence](https://en.wikipedia.org/wiki/Longest_increasing_subsequence)\n\n\n# Arguments\n- `array::Array{Int64,1}`: array of integers unsortetd or sorted\n\n\n# Examples\n```julia-repl\njulia> import ClassicAlgorithmsCollections\njulia> arr = [10, 22, 9, 33, 21, 50, 41, 60] \njulia> ClassicAlgorithmsCollections.lis_length(arr)\n4\n```\n\"\"\"\nfunction lis_length(array::Array{Int64,1})\n    n = length(array)\n    list = fill(1, n)\n    for i in 2:n\n        for j in 1:i\n            if array[i] > array[j] && list[i] < list[j] + 1\n                list[i] = list[j] + 1\n            end\n        end\n    end\n\n    result = 0\n    for i in 1:n\n        if list[i] > result\n            result = list[i]\n        end\n    end\n    return result\nend\n", "meta": {"hexsha": "4b9c786aee6c1a8ce2f9fe67240daeed633f8000", "size": 1364, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/DynamicProgramming/LongestIncreasingSubsequence.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/DynamicProgramming/LongestIncreasingSubsequence.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/DynamicProgramming/LongestIncreasingSubsequence.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.0212765957, "max_line_length": 150, "alphanum_fraction": 0.6539589443, "num_tokens": 399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191322715435, "lm_q2_score": 0.8976952989498449, "lm_q1q2_score": 0.8575854940370097}}
{"text": "\"\"\"\nSieve of Eratosthenes is an algorithm for finding all the primes upto a limit `n`.\n\nReference:\n-https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\n\"\"\"\nfunction eratosthenes(n)\n    primes = fill(true,n)\n    primes[1] = false\n    for p = 2:n\n        primes[p] || continue\n        for i = 2:div(n,p)\n            primes[p*i] = false\n        end\n    end\n    findall(primes)\nend\n", "meta": {"hexsha": "91a09c74ee1fbcfb3118bee8ef9f9e99930ae7ef", "size": 378, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/sieve_of_eratosthenes.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/sieve_of_eratosthenes.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/sieve_of_eratosthenes.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": 21.0, "max_line_length": 82, "alphanum_fraction": 0.6137566138, "num_tokens": 113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9736446448596304, "lm_q2_score": 0.880797068590724, "lm_q1q2_score": 0.8575833490414191}}
{"text": "## Before we got started\n# I added the Images package via\n# typing \"]\" then \"add Images\"\n# alternatively, we could use\n# using Pkg; Pkg.add(\"Images\")\n\n## Let's try and make Wikipedia's Julia set figure.\nusing Images\nusing Plots\n\n## It says the seed coordinates are:\nseeds = (-0.512511498387847167, 0.521295573094847167)\n\n## Let's work with the Julia set.\n# What we need to do is to check if, when starting\n# from the complex number z=0, and iterating the map\n# f(z) = z^2 + c\n# for a large number of times (say 256)\n# if the value of abs(f(z)) ever goes above 2,\n# then we stop when that happens and return the value.\nc = 0.25\n# if we start at z = 0, then we test if z=0 is in the set.\nz = 0.0+0.0im # this is how to make an imaginary number\nf(z) = z^2 + c\n@show f(z)\n@show f(f(z))\n@show f(f(f(z)))\n\n##\nzi = z\nfor i=1:10\n    global zi\n    zi = f(zi)\n    @show zi\nend\n##\n\"\"\"\n`julia_check` is a subroutine useful for working with\nthe Julia set. We are going take as input two values:\nz0 and c. The goal is to test whether or not the value\nz0 seems to be in the Julia set for\n    f(z) = z^2 + c\nby starting from z0 = the input z0 and iterating\nz1 = f(z0)\nz2 = f(z1)\n...\nand so on.\nNow, if at any point, we find abs(z) >= 2, then we know\nthat the point is NOT in the Julia set. In which case,\nwe return the iteration number where we detect this.\nWe run this for maxiter steps.\n\"\"\"\nfunction julia_check(z0, c; maxiter::Int=256)\n    z = z0\n    for i=1:maxiter\n        z = z^2 + c\n        if abs(z) >= 2\n            return i\n        end\n    end\n    return maxiter\nend\njulia_check(-1, 0.25)\n\n## Let's look at starting positions z0 that range\n## from [-1.75 to 1.75] in the real component\n## and [-1.75 to 1.75] in the complex component\nnpts = 10\nZ = zeros(npoints,npoints) # this will represent our Images\nreal_values = range(start=-1.75,stop=1.75,length=npts)\ncomplex_values = range(start=-1.75,stop=1.75,length=npts)\nfor i=1:npts\n    for j=1:npts\n        z0 = real_values[i] + complex_values[j]*1.0im\n        Z[j,i] = julia_check(z0, 0.25)\n    end\nend\nheatmap(Z)\n\n## The fix!\nnpts = 10\nZ = zeros(npts,npts) # this will represent our Images\nreal_values = range(-1.75,stop=1.75,length=npts)\ncomplex_values = range(-1.75,stop=1.75,length=npts)\nfor i=1:npts\n    for j=1:npts\n        z0 = real_values[i] + complex_values[j]*1.0im\n        Z[j,i] = julia_check(z0, 0.25)\n    end\nend\nheatmap(Z)\n\n## Let's turn this into a function!\nfunction julia_set(real_values, complex_values)\n    Z = zeros(length(complex_values), length(real_values))\n    for i=1:length(real_values)\n        for j=1:length(complex_values)\n            z0 = real_values[i] + complex_values[j]*1.0im\n            Z[j,i] = julia_check(z0, 0.25)\n        end\n    end\n    return Z\nend\nnpts = 500\nreal_values = range(-1.75,stop=1.75,length=npts)\ncomplex_values = range(-1.75,stop=1.75,length=npts)\nheatmap(julia_set(real_values, complex_values))\n##\nfunction julia_set(real_values, complex_values; c=0.25)\n    Z = zeros(length(complex_values), length(real_values))\n    for i=1:length(real_values)\n        for j=1:length(complex_values)\n            z0 = real_values[i] + complex_values[j]*1.0im\n            Z[j,i] = julia_check(z0, c)\n        end\n    end\n    return Z\nend\nnpts = 500\nreal_values = range(-1.75,stop=1.75,length=npts)\ncomplex_values = range(-1.75,stop=1.75,length=npts)\nheatmap(julia_set(real_values, complex_values; c = seeds[1] + seeds[2]*1.0im))\n## Let's increase the resolution.\nnpts = 1000\nreal_values = range(-1.75,stop=1.75,length=npts)\ncomplex_values = range(-1.75,stop=1.75,length=npts)\nZ = julia_set(real_values, complex_values; c = seeds[1] + seeds[2]*1.0im)\n## And then try and make our plot.\nheatmap(log10.(Z))\n## TODO or IDEA - Play around the with the colors to see if you find something you like better\n## Show this like an image.\nimage = Gray.(Z/maximum(Z))\nimage\n\n## to save this picture, we can use\nusing FileIO\nusing ImageMagick\nsave(\"juliaset.png\", Gray.(Z/maximum(Z)))\n", "meta": {"hexsha": "5233a95993507abd7bfbbbb411d532f6ae7d9e93", "size": 3951, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "1-julia-intro/julia-set.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/julia-set.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/julia-set.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.4244604317, "max_line_length": 94, "alphanum_fraction": 0.6714755758, "num_tokens": 1267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947101574299, "lm_q2_score": 0.9073122201074847, "lm_q1q2_score": 0.8574052484627667}}
{"text": "##########################################################\n#FEniCS tutorial demo program: Poisson equation with Dirichlet conditions.\n#Test 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_D = 1 + x^2 + 2y^2\n#    f = -6\n###########################################################\n\nmodule ft01\n\nusing FenicsPy\n\n# Create mesh and define function space\nmesh = UnitSquareMesh(8, 8)\nV = FunctionSpace(mesh, \"P\", 1)\n\n# Define boundary condition\nu_D = Expression(\"1 + x[0]*x[0] + 2*x[1]*x[1]\", degree=2)\n\nbc = DirichletBC(V, u_D, \"on_boundary\")\n\n# Define variational problem\nu = TrialFunction(V)\nv = TestFunction(V)\nf = Constant(-6.0)\na = dot(grad(u), grad(v))*dx\nL = f*v*dx\n\n# Compute solution\nu = FeFunction(V)\nsolve(a == L, u, bc)\n\n# Save solution to file in VTK format\nvtkfile = File(\"poisson/solution.pvd\")\nvtkfile << u\n\n# Compute error in L2 norm\nerror_L2 = errornorm(u_D, u, \"L2\")\n\n# Compute maximum error at vertices\nvertex_values_u_D = u_D.compute_vertex_values(mesh)\nvertex_values_u = u.compute_vertex_values(mesh)\nerror_max = max(abs.(vertex_values_u_D - vertex_values_u)...)\n\n# Print errors\nprintln(\"error_L2  =\", error_L2)\nprintln(\"error_max =\", error_max)\n\n# Plot solution and mesh\n#plot(u)\n#plot(mesh)\n\nend # module ft01\n", "meta": {"hexsha": "2df80d316110fab9c2f7ef5218f42ea0aa24509c", "size": 1334, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ft01_poisson.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/ft01_poisson.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/ft01_poisson.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": 24.2545454545, "max_line_length": 75, "alphanum_fraction": 0.6349325337, "num_tokens": 381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.966410491447634, "lm_q2_score": 0.8872045892435128, "lm_q1q2_score": 0.8574038231054194}}
{"text": "using FractalTools\nusing Plots\n\nfunction example_attractor_of_ifs(N_iter)\n    # An example of one dimensional ifs\n    A1 = reshape([1/2],1,1)\n    b1 = [0]\n    A2 = reshape([1/2],1,1)\n    b2 = [1/2]\n\n    w1 = Transformation(A1,b1)\n    w2 = Transformation(A2,b2)\n\n    w = [w1, w2]\n    ifs = IFS(w)\n    initset = [[0.1]]\n    atr = attractor(ifs, initset; alg=RandAlg(), numiter=N_iter,allocated=true) \n    attrset = vcat(atr.set...)\n    t = ones(length(attrset))\n    return atr, attrset, t\nend\n\natr, attrset, t = example_attractor_of_ifs(10)\np1 = scatter(t, attrset, title=\"Attractor of the IFS\", label=\"Attractor Points\", markersize = 4)\n\natr, attrset, t = example_attractor_of_ifs(100)\np2 = scatter(t, attrset, title=\"Attractor of the IFS\", label=\"Attractor Points\", markersize = 4)\n\natr, attrset, t = example_attractor_of_ifs(10000)\np3 = scatter(t, attrset, title=\"Attractor of the IFS\", label=\"Attractor Points\", markersize = 4)\n\n\nplot(p1, p2, p3, layout=(1,3))\nxlabel!(\"x\")\nylabel!(\"z\")\nxlims!((0.9,1.1))\n# savefig(\"myplot.png\")\n\n\n# An example of atr with Channel\natr = attractor(ifs1, initset; alg=RandAlg(), numiter=100, allocated=false) \ncollect(atr.set)\ntake!(atr.generator)\n# An example of atr with randalg_sequential_generator\n# generator = randalg_sequential_generator(ifs1.ws, ifs1.probs)\n# take!(generator)\n\n\n# An example of two dimensional ifs\nA = [1/2 0;0 1/2]\nb1 = [0; 0] \nb2 = [0; 1/2] \nb3 = [1/2; 1/2] \nb4 = [1/2; 0] \n\nw1 = Transformation(A,b1)\nw2 = Transformation(A,b2)\nw3 = Transformation(A,b3)\nw4 = Transformation(A,b4)\n\nw = [w1, w2, w3, w4]\nifs2 = IFS(w)\nifs2.ws\nifs2.probs\n\n\n# An example of different probabilities\n\np = [0.2, 0.4, 0.1, 0.3]\n\nifs3 = IFS(w,p)\nifs3.ws\nifs3.probs\n\n", "meta": {"hexsha": "619c3a4bdf1e81b07c7074b6b45cb009f2cc9537", "size": 1699, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/stash/ifs/ifs_constraction.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/ifs/ifs_constraction.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/ifs/ifs_constraction.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": 22.6533333333, "max_line_length": 96, "alphanum_fraction": 0.6668628605, "num_tokens": 613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341999997378, "lm_q2_score": 0.8962513655129177, "lm_q1q2_score": 0.8573847080461227}}
{"text": "@testset \"l2inner\" begin\n    ndim = 10\n    a = rand(Float,ndim)\n    b = rand(Float,ndim)\n    ca = rand(Complex{Float},ndim)\n    cb = rand(Complex{Float},ndim)\n    @test a\u22c5b \u2248 VectorDataUtils.l2inner(a,b)\n    @test a\u22c5cb \u2248 VectorDataUtils.l2inner(a,cb)\n    @test ca\u22c5b \u2248 VectorDataUtils.l2inner(ca,b)\n    @test ca\u22c5cb \u2248 VectorDataUtils.l2inner(ca,cb)\n    @test a\u22c5a \u2248 VectorDataUtils.l2inner(a)\n    @test a\u22c5a \u2248 VectorDataUtils.sql2norm(a)\n    @test sqrt(a\u22c5a) \u2248 VectorDataUtils.l2norm(a)\nend\n\n@testset \"l2dist\" begin\n    ndim = 10\n    a = rand(Float,ndim)\n    b = rand(Float,ndim)\n    @test (a-b)\u22c5(a-b) \u2248 VectorDataUtils.sql2dist(a,b)\n    @test sqrt(sum(abs2,a-b)) \u2248 VectorDataUtils.l2dist(a,b)\nend\n\n@testset \"lpnorms\" begin\n    ndim = 10\n    a = rand(Float,ndim)\n    @test sum(abs.(a)) \u2248 VectorDataUtils.l1norm(a)\nend\n\n@testset \"lpdist\" begin\n    ndim = 10\n    a = rand(Float,ndim)\n    b = rand(Float,ndim)\n    @test sum(abs.(a-b)) \u2248 VectorDataUtils.l1dist(a,b)\nend", "meta": {"hexsha": "f118bcf0d48442d5b624c2eadf45d06b7dc4a8a4", "size": 960, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Lp_tests.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": "test/Lp_tests.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": "test/Lp_tests.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": 27.4285714286, "max_line_length": 59, "alphanum_fraction": 0.6375, "num_tokens": 375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620596782467, "lm_q2_score": 0.8933094167058151, "lm_q1q2_score": 0.8573644857075462}}
{"text": "# Root finder functions for 1d func\r\n# Newton's Method, Linear Approximation\r\n# Note that you can also find root by applying optimizer on an Error function\r\n# \u03f5(x,...)\r\n\r\n\r\n\r\n\r\n# Newton's Method\r\n# f1 is \u03b4f\u2571\u03b4x\r\nfunction solve_Newton(f,f1,par;nlim = 1e4,\u03f5=1e-3)\r\n    for i in 1:nlim\r\n        par1 = par - f(par)/f1(par)\r\n        if \u03f5>abs(par1 -par)\r\n            return(par1)\r\n        end\r\n        par=par1\r\n    end\r\n    println(\"Warning! unconverged after\" * string(nlim) *\"Iterations.\")\r\n    return(par1)\r\nend\r\n\r\n\r\n# Linear Approximation\r\nfunction solve_Linear_Approx(f,par1,par2;nlim = 1e4,\u03f5=1e-3)\r\n    #must follow :x1 * x2<0\r\n    #             par1<par2\r\n    for i in 1:nlim\r\n        x1 = f(par1)\r\n        x2 = f(par2)\r\n        global par3 = par1+(par2 - par1)*abs(x1/(x1-x2))\r\n        if abs(par3-par1)<\u03f5\r\n            if abs(par3 - par2)<\u03f5\r\n                return par3\r\n            end\r\n        else\r\n            if (par3*par1)>0\r\n                par1=par3\r\n            else (par3*par2)>0\r\n                par2=par3\r\n            end\r\n        end\r\n    end\r\n    println(\"Warning! unconverged after\"*string(nlim)*\"iterations.\")\r\n    return par3\r\nend\r\n\r\n\r\n#----------------------------------------------------------------\r\nusing Plots\r\nx = 1:.1:4\r\ny = sin.(x)\r\nplot(x,y)\r\nplot!(x,zeros(length(x)))\r\n\r\nf(x) = sin(x)\r\nf1(x) = cos(x)\r\n\r\n\r\nsolve_Newton(f,f1,3)\r\n\r\nsolve_Linear_Approx(f,3,4)\r\n#----------------------------------------------------------------\r\n", "meta": {"hexsha": "a3e600120396e677900ed6940868fcbeab99cde5", "size": 1455, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Root Solving.jl", "max_stars_repo_name": "HaoLi111/Julia_Numerical_Recipe", "max_stars_repo_head_hexsha": "d887ee783bfc6e4efc1b4f748c19a21baef5d654", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-06-27T05:52:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-05T04:55:37.000Z", "max_issues_repo_path": "Root Solving.jl", "max_issues_repo_name": "HaoLi111/Julia_Numerical_Recipe", "max_issues_repo_head_hexsha": "d887ee783bfc6e4efc1b4f748c19a21baef5d654", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Root Solving.jl", "max_forks_repo_name": "HaoLi111/Julia_Numerical_Recipe", "max_forks_repo_head_hexsha": "d887ee783bfc6e4efc1b4f748c19a21baef5d654", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.734375, "max_line_length": 78, "alphanum_fraction": 0.483161512, "num_tokens": 436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620608291783, "lm_q2_score": 0.8933094074745443, "lm_q1q2_score": 0.8573644778758608}}
{"text": "\"\"\"\n    ceil_val(x)\n\nFinds the ceiling of x as an Integer\n\n# Example\n```julia\nceil_val(1.3)   # 2.0\nceil_val(2.0)   # returns 2.0\nceil_val(-1.5)  #returns -1.0\n````\n\n# Reference\n- https://en.wikipedia.org/wiki/Floor_and_ceiling_functions\n\nContributed By:- [Ashwani Rathee](https://github.com/ashwani-rathee)\n\"\"\"\nfunction ceil_val(x)\n    return x -trunc(x) <= 0 ? trunc(x) : trunc(x)+1\nend\n\n\"\"\"\n    floor_val(x)\n\nFinds the floor of x as an Integer\n\n# Example\n```julia\nfloor_val(1.3)  # 1\nfloor_val(2.0)  # returns 2.0\nfloor_val(-1.7) # returns -2.0\n````\n\n# Reference\n- https://en.wikipedia.org/wiki/Floor_and_ceiling_functions\n\nContributed By:- [Ashwani Rathee](https://github.com/ashwani-rathee)\n\"\"\"\nfunction floor_val(x)\n    return x -trunc(x) >= 0 ? trunc(x) : trunc(x)-1\nend\n", "meta": {"hexsha": "b16294bb8445855189a8c81bf88a3562e07e25d7", "size": 778, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/ceil_floor.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/ceil_floor.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/ceil_floor.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": 18.5238095238, "max_line_length": 68, "alphanum_fraction": 0.6683804627, "num_tokens": 275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.9184802501617068, "lm_q1q2_score": 0.8573377682247914}}
{"text": "# Number of iterations Euclidean Algorithm needs for gcd(a, b)\nfunction gcd_iters(a, b)\n    iters = 0\n    while b != 0\n        iters += 1\n        a, b = b, a % b\n    end\n    return iters\nend\n\n# Number of bits needed to represent some non-negative n\nfunction num_bits(n)\n    ct = 1\n    n >>= 1\n    while n != 0\n        n >>= 1\n        ct += 1\n    end\n    return ct\nend\n\n# Test num_bits\nnum_bits_tests = [(0, 1), (1, 1), (2, 2), (3, 2), (4, 3), (5, 3), (6, 3), (7, 3), (8, 4)]\nfor (num, ans) in num_bits_tests\n    @assert num_bits(num) == ans\nend\n\nsmall_numbers = collect(0:2^12-1)\nfibs = [0, 1] # Fibonacci numbers\nfor i in 1:90\n    push!(fibs, fibs[length(fibs) - 1] + fibs[length(fibs)])\nend\ntwo_powers = [2 ^ x for x in 1 : 60] \nmersenne_numbers = [x - 1 for x in two_powers]\n\noperands_of_interest = Set(vcat(small_numbers, fibs, two_powers, mersenne_numbers))\n\n# Verify that for all operands of interest, num iters is <= 1 + num_bits(y) \u00f7 log2_of_\u03c6 (note floor divison)\nlog2_of_\u03c6 = log2(MathConstants.golden)\nfor x in operands_of_interest, y in operands_of_interest\n# for x in 0:2^16-1, y in 0:2^16-1\n    iters = gcd_iters(x, y)\n    if 1 + num_bits(y) \u00f7 log2_of_\u03c6 < iters\n        println(\"gcd($(x), $(y)) takes $(iters) iters (max bits: $(max_bits), ratio: $(iters / max_bits))\")\n    end\n    @assert iters <= 1 + num_bits(y) \u00f7 log2_of_\u03c6 \nend\nprintln(\"Done\")\n\n#==\nOperands where (# of iterations)/(max_bits) = 1.5 (none have a higher ratio, up through 14 bits)\nNote that all are sequential fibonacci #s\ngcd(2, 3) takes 3 iters (max bits: 2)\ngcd(8, 13) takes 6 iters (max bits: 4)\ngcd(34, 55) takes 9 iters (max bits: 6)\ngcd(144, 233) takes 12 iters (max bits: 8)\ngcd(610, 987) takes 15 iters (max bits: 10)\n\n\nhttps://stackoverflow.com/questions/9060816/running-time-of-euclids-gcd-algorithm\ny = second arg\nb = # of bits in second arg\nbound is:\n1 + log(\u03c6, y)\n1 + log(\u03c6, 2^b - 1)\n1 + log(2, 2^b - 1)/log(2, \u03c6)\n1 + b/log(2, \u03c6)\n\nexperimentally verified for all numbers representable in 16 bits\n\n==#", "meta": {"hexsha": "dac3b7154605d57db2676ae6e8a4d37569a12c3e", "size": 1996, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/gcd_iters_bound.jl", "max_stars_repo_name": "rtjoa/Dice.jl", "max_stars_repo_head_hexsha": "839b906edbe6a1b51c723211533b3145700406b6", "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/gcd_iters_bound.jl", "max_issues_repo_name": "rtjoa/Dice.jl", "max_issues_repo_head_hexsha": "839b906edbe6a1b51c723211533b3145700406b6", "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/gcd_iters_bound.jl", "max_forks_repo_name": "rtjoa/Dice.jl", "max_forks_repo_head_hexsha": "839b906edbe6a1b51c723211533b3145700406b6", "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.1126760563, "max_line_length": 108, "alphanum_fraction": 0.6387775551, "num_tokens": 740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430812881347, "lm_q2_score": 0.9184802412359966, "lm_q1q2_score": 0.857337758192372}}
{"text": "\r\nstruct BracketingInterval\r\n    x_lo\r\n    x_mid\r\n    x_hi\r\n    f_lo\r\n    f_mid\r\n    f_hi\r\n    iter\r\n    success::Bool\r\nend\r\n\r\nfunction Base.show(io::IO, bracket::BracketingInterval)\r\n    if bracket.success\r\n        print(\"Successful seach\")\r\n    else\r\n        print(\"Failed seach\")\r\n    end\r\n    print(\" with $(bracket.iter)-iterations\\n\")\r\n    println(\"\\tx\\tf(x)\")\r\n    println( \"lo:\\t$(bracket.x_lo)\\t$(bracket.f_lo)\" )\r\n    println( \"mid:\\t$(bracket.x_mid)\\t$(bracket.f_mid)\" )\r\n    println( \"hi:\\t$(bracket.x_hi)\\t$(bracket.f_hi)\" )\r\nend\r\n\r\n\r\n\r\nfunction bracket_min(\r\n    fcn,\r\n    x_lo,\r\n    x_hi; \r\n    step = abs(x_hi-x_lo) * 1e-2, \r\n    step_factor = 1.61,\r\n    max_iter = 1000)\r\n\r\n    f_x_lo = fcn(x_lo)\r\n    f_x_hi = fcn(x_hi)\r\n    \r\n    if f_x_lo < f_x_hi\r\n        # swap the orders\r\n        x_lo, x_hi = x_hi, x_lo\r\n        f_x_lo, f_x_hi = f_x_hi, f_x_lo\r\n        step = -step\r\n    end\r\n\r\n    iter = 1\r\n    while iter <= max_iter\r\n        x_next = x_hi + step\r\n        f_next = fcn(x_next)\r\n        if f_next > f_x_hi\r\n            # bracketed interval found\r\n            return BracketingInterval(x_lo, x_hi, x_next, f_x_lo, f_x_hi, f_next, iter, true)\r\n        end\r\n        \r\n        x_lo, x_hi = x_hi, x_next\r\n        f_x_lo, f_x_hi = f_x_hi, f_next\r\n\r\n\r\n        step *= step_factor\r\n        iter += 1\r\n    end\r\n    println(\"Failed to find a bracketing interval in the prescribed number of iterations\")\r\n    return BracketingInterval(x_lo, x_hi, x_next, f_x_lo, f_x_hi, f_next, iter, false)\r\n\r\nend\r\n\r\n\r\nstruct GoldenSectionSearchStatistics\r\n    x_sol\r\n    y_sol\r\n    iter\r\nend\r\n\r\nfunction golden_section_search(fcn, x_lo, x_hi; max_iter = 100, x_tol = 1e-10)\r\n\r\n    rho = 0.5 * (sqrt(5)-1)\r\n    if x_lo > x_hi\r\n        # swap\r\n        x_lo, x_hi = x_hi, x_lo\r\n    end\r\n    a = x_lo\r\n    b = x_hi\r\n    \r\n    c_fcn(lo, hi) = rho * lo + (1 - rho) * hi\r\n    d_fcn(lo, hi) = (1 - rho) * lo + rho * hi\r\n\r\n\r\n    y_a = fcn(a)\r\n    y_b = fcn(b)\r\n\r\n    c = c_fcn(a, b)\r\n    d = d_fcn(a, b)\r\n\r\n    y_c = fcn(c)\r\n    y_d = fcn(d)\r\n\r\n    x_sol = NaN\r\n    y_sol = NaN\r\n    iter = 0\r\n    for outer iter = 1:max_iter\r\n\r\n        if y_c < y_d\r\n            # choose (a, c, d)\r\n            a, d, b = a, c, d\r\n            y_a, y_d, y_b = y_a, y_c, y_d\r\n            c = c_fcn(a, b)\r\n            y_c = fcn(c)\r\n        else\r\n            # choose (c, d, b)\r\n            a, c, b = c, d, b\r\n            y_a, y_c, y_b = y_c, y_d, y_b\r\n            d = d_fcn(a, b)\r\n            y_d = fcn(d)\r\n        end\r\n\r\n        if abs(b - a) <= x_tol\r\n            (x_sol, y_sol) = (y_c < y_d) ? (c, y_c) : (d, y_d) \r\n            break\r\n        end\r\n\r\n    end\r\n    if iter == max_iter\r\n        (x_sol, y_sol) = (y_c < y_d) ? (c, y_c) : (d, y_d) \r\n    end\r\n\r\n    return GoldenSectionSearchStatistics(x_sol, y_sol, iter)\r\n\r\nend", "meta": {"hexsha": "b66a20616c5073377833546ba4cb5dad43dcd772", "size": 2797, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "__lib__/math/opti/src/opti_1d.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_1d.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_1d.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.8515625, "max_line_length": 94, "alphanum_fraction": 0.500178763, "num_tokens": 927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109742068041, "lm_q2_score": 0.90192067652954, "lm_q1q2_score": 0.8571953088376999}}
{"text": "# p12.jl - accuracy of Chebyshev spectral differentiation\n#         (compare p7.jl)\n\n# Compute derivatives for various values of N:\nNmax = 50; allN = 6:2:Nmax; E = zeros(4,Nmax);\nfor N = 1:Nmax\n    (D,x) = cheb(N);\n    v = @. abs(x)^3; vprime = @. 3*x*abs(x);   # 3rd deriv in BV\n    E[1,N] = norm(D*v-vprime,Inf);\n    v = @. exp(-x^(-2)); vprime = @. 2*v/x^3;  # C-infinity\n    E[2,N] = norm(D*v-vprime,Inf);\n    v = @. 1/(1+x^2); vprime = @. -2*x*v^2;    # analytic in [-1,1]\n    E[3,N] = norm(D*v-vprime,Inf);\n    v = x.^10; vprime = 10*x.^9;               # polynomial\n    E[4,N] = norm(D*v-vprime,Inf);\nend\n\n# Plot results:\ntitles = [L\"|x|^3\",L\"\\exp(-x^2)\",L\"1/(1+x^2)\",L\"x^{10}\"];  clf();\nfor iplot = 1:4\n    subplot(2,2,iplot);\n    semilogy(1:Nmax,E[iplot,:],\".-\",markersize=6);\n    axis([0,Nmax,1e-16,1e3]); grid(true);\n    xticks(0:10:Nmax); yticks(10.0.^(-15:5:0));\n    title(titles[iplot]);\n    iplot > 2 ? xlabel(\"N\") : nothing;\n    iplot%2 > 0? ylabel(\"error\") : nothing;\nend\n", "meta": {"hexsha": "2f1db14d85e10581a79ae03cae66c954b5535467", "size": 989, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/scripts/p12.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/p12.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/p12.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.1034482759, "max_line_length": 67, "alphanum_fraction": 0.5308392315, "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172630429475, "lm_q2_score": 0.9032942067038784, "lm_q1q2_score": 0.8571514663479948}}
{"text": "#' ## Run this cell to load the graphics packages\r\n#+ results=\"hidden\"\r\nusing Plots\r\n#gr()\r\n#plotly()\r\npyplot()\r\n#+\r\n\r\n#' ## Adding a function parameter\r\n#' In the last notebook, we saw an example of adding **parameters** to\r\n#' functions. These are values that control the behavior of a function.\r\n#' Let's look at that in some more detail.\r\n#' Let's go back to our original version of the \u03c3 function:\r\n#+ results=\"hidden\"\r\nsigma(x) = 1/(1+exp(-x))\r\n#+\r\n#' Instead of working with a single function, we can work with a whole class\r\n#' (set) of functions that look similar but differ in the value of a\r\n#' **parameter**. Let's make a new function that uses the previous $\\sigma$\r\n#' function, but also has a parameter, $w$. Mathematically, we could write\r\n\r\n#' $$f_w(x) = f(x; w) = \\sigma(w \\, x).$$\r\n\r\n#' (Here, $w$ and $x$ are multiplied in the argument of $\\sigma$; we could\r\n#' write $w \\times x$ or $w * x$, or even $w \\cdot x$, but usually the symbols\r\n#' are not written.)\r\n\r\n#' Mathematically speaking, we can think of $f_w$ as a different function for\r\n#' each different value of the parameter $w$.\r\n\r\n#' In Julia, we write this as follows:\r\n#+ results=\"hidden\"\r\nf(x, w) = sigma(w * x)\r\n#+\r\n#' Note that Julia just treats parameters as additional *arguments* to the\r\n#' function; the function `f` has two arguments, the value of `x` and the\r\n#' value of `w` that we want to use.\r\n\r\n#' We can now investigate the effect of $w$ interactively. To do so, we need\r\n#' a way of writing in Julia \"the function of one variable $x$ that we obtain\r\n#' when we fix the value of $w$\". We write this as an \"anonymous function\", as\r\n#' we saw in the notebook on functions:\r\n#'\r\n#'     x -> f(x, w)\r\n#'\r\n#' We can read this as \"the function that maps $x$ to the value of $f(x, w)$,\r\n#' for a value of $w$ that was previously given\".\r\n\r\n#' Now we are ready to draw the function. For each plot, we *fix* a value of\r\n#' the parameter $w$ and draw the resulting function as a function of $x$.\r\n#' We can interactively modify the value of $w$, and plot the new function that\r\n#' comes out:\r\n#' ## Try manipulating `w` between -2 and 2\r\nw = -1\r\nplot(x->f(x, w), -5, 5, ylims=(0,1), label=\"sigmoid\")\r\nplot!(x->(x>0), -5,5, label=\"Square Wave\")\r\n\r\n#' #### Exercise 1\r\n#'\r\n#' Try writing your own function that takes a parameter. Start by copying and\r\n#' executing\r\n#'\r\nsquare(x) = x^2\r\n#'\r\n#' Then use `square` to declare a new function `square_and_scale` that takes\r\n#' two inputs, `a` and `x` such that\r\n#'\r\n#' $$\\mathrm{square\\_and\\_scale}(x; a) := a \\cdot x^2$$\r\n\r\n#' ####\r\nfunction square_and_scale(x, a) \r\n    return a*x^2\r\nend\r\n\r\n#' We can write some tests as follows, using the approximate equality operator,\r\n# `\u2248`, written as `\\approx<TAB>`:\r\nsquare_and_scale(1, 1) \u2248 1\r\nsquare_and_scale(1, 2) \u2248 2\r\nsquare_and_scale(2, 1) \u2248 4\r\nsquare_and_scale(2, 2) \u2248 8\r\n\r\n# #### Exercise 2\r\n\r\n#' Once you have declared `square_and_scale`, uncomment the code below and see\r\n#' how the parameter `a` scales the function `square` :\r\n\r\nx = -10:10\r\na = 5.0 # Try manipulating a here\r\n\r\nplot(x, square.(x), label=\"x^2\")\r\nplot!(x, square_and_scale.(x, a), ls=:dash, label=\"ax^2\")\r\n\r\n#' ## Fitting a function to data\r\n#' As we saw in the previous notebook, what we would like to do is use the\r\n#' fact that we now have a parameter in our function in order to do something\r\n#' useful! Namely, we want to model data with it.\r\n\r\n#' So suppose that we are given a single data point $(x_0, y_0) = (2, 0.8)$.\r\n#' We can try to \"fit\" the function $f_w$ by adjusting the parameter $w$ until\r\n#' the function passes through the data.\r\n#'\r\n#' **Game**: Change `w` until the graph of the function hits the data point.\r\n#' Which value of $w$ does that correspond to?\r\nx0, y0 = 2, 0.8\r\n\r\n#' f(x, w) = sigma(w * x)\r\nw = 0.7 # try mainipulatoing `w` between -2 and 2\r\nplot(x->f(x, w), -5, 5, ylims=(0, 1), label=\"f\")\r\nscatter!([x0], [y0], label=\"data\")\r\n#' ## Quantifying how far we are from the goal: the *loss function*\r\n#' We can see visually when the graph of the function passes through the data\r\n#' point. But the goal is to be able to automate this process so that the\r\n#' computer can do it unaided.\r\n#'\r\n#' So we will need a more precise way of deciding and quantifying\r\n#' (i.e. measuring with a number) *how far away we are from the goal*;\r\n#' here, the goal means hitting the data point with the function.\r\n\r\n#' #### Exercise 3\r\n#' Can you think of a way of measuring how far away our function is from\r\n#' the data point?\r\n\r\n#' ### Defining the loss function\r\n#' We need to measure how far away the curve is from the data point when we\r\n#' choose a particular value of $w$.\r\n#' One way to do this is by finding the vertical distance $d$ from the curve\r\n#' to the data point.\r\n#'\r\n#' Instead of just taking the distance, it is common to take the *square* of\r\n#' the distance, $d^2$.\r\n#'\r\n#' Since we are taking the vertical distance, we need the distance at the given\r\n#' value of $x_0$ where the data point lies. For a given value of the parameter\r\n#' $w$, the height of the point on the curve with that value of $x_0$ is\r\n#' $f(x_0, w)$.\r\n#'\r\n#' So we take\r\n#'\r\n#' $$d := y_0 - f(x_0, w)$$\r\n#'\r\n#' and\r\n#'\r\n#' $$d^2 = [y_0 - f(x_0, w)]^2.$$\r\n#'\r\n#' This is our measure of distance. It will change when $w$ changes -- in other\r\n#' words, it is itself a *function of $w$*; we will denote this function by\r\n#' $L(w)$, and call it the **loss function**:\r\n#'\r\n#' $$L(w) := [y_0 - f(x_0, w)]^2.$$\r\n#'\r\n#' So the goal is to find the value $w^*$ of $w$ where the loss function is *least*; in other words, we need to *minimize* the loss function!\r\n#'\r\n#' (Another name for a loss function is a *cost function*.)\r\n\r\n#' #### Exercise 4\r\n#'\r\n#' (a) Define the loss function `L(w)` in Julia.\r\n#+ results=\"hidden\"\r\nx0, y0 = 2, 0.8\r\nL(w) = (y0 - f(x0,w))^2\r\n#+\r\n\r\n#' (b) Draw the data point and the function `x -> f(x, w)`.\r\n#' Also draw a vertical line from the data point to the function `x -> f(x, w)`.\r\nw = 0.5\r\npl = plot(x->f(x,w), -5, 5, ylims=(0,1), label=\"f_w\", lw=3)\r\nscatter!(pl, [x0], [y0], label=\"data\")\r\nplot!([x0, x0], [y0, f(x0, w)], label=\"loss\", legend=(0.2,0.9))\r\n#' (c) Make the plot interactive.\r\n#'\r\n#' (d) Add as the plot title the value of the loss function for the current value\r\n#' of $w$.\r\ntitle!(\"L(w) = $(round(L(w); sigdigits = 5))\")\r\n#'\r\n#' (e) Use the slider to find the value $w^*$ of $w$ for which the loss function\r\n#' reaches its minimum value. What is $w^*$? What is the value of the loss\r\n#' function there, $L(w^*)$?\r\nw = 0.7\r\npl = plot(x->f(x,w), -5, 5, ylims=(0,1), label=\"f_w\", lw=3)\r\nscatter!(pl, [x0], [y0], label=\"data\")\r\nplot!([x0, x0], [y0, f(x0, w)], label=\"loss\", legend=(0.1,0.9))\r\ntitle!(\"L(w) = $(round(L(w); sigdigits = 5))\")\r\n\r\n#' ## What does the loss function look like?\r\n#' The loss function $L(w)$ tells us how far away the function $f_w$ is from\r\n#' the data when the parameter value is $w$, represented visually as the\r\n#' vertical line in the previous plot. When the data are fixed, this is a\r\n#' function only of the parameter $w$. What does this function look like as\r\n#' a function of $w$? Let's draw it!\r\n\r\n#' #### Exercise 5\r\n#' Draw the function $L(w)$ as a function of $w$.\r\n\r\n#' #### Solution\r\npl = plot(L, -2, 2, xlabel=\"w\", ylabel=\"L(w)\", ylims=(0, 0.7), label=\"L\", legend=(0.8,0.9))\r\n#' This graph quantifies how far we are from the data point for a given value\r\n#' of $w$.\r\n#' What features can we see from the graph?\r\n#'\r\n#' Firstly, we see that $L(w)$ is always bigger than $0$, for any value of $w$.\r\n#' This is because we want $L$ to be some kind of measure of *distance*, and\r\n#' distances cannot be negative.\r\n#'\r\n#' Secondly, we see that there is a special value $w^*$ of $w$ where the\r\n#' function $L$ reaches its minimum value. In this particular case, it actually\r\n#' reaches all the way down to $0$!\r\n#' This means that the original function $f$ (the one we manipulated above)\r\n#' passes exactly through the data point $(x_0, y_0)$.\r\n\r\n#' #### Exercise 6\r\n#' Draw a zoomed-in version of the graph to find the place $w^*$ where the\r\n#' function hits $0$ more precisely.\r\npl = plot(L, 0.5, 1, xlabel=\"w\", ylabel=\"L(w)\", ylims=(0, 0.01), label=\"L\", legend=(0.8,0.9))\r\n\r\n#' ### A different way of defining the loss function\r\n#' **Why did we use such a complicated function $L$ with those squares inside?**\r\n#' We could instead just have used the absolute distance, instead of the\r\n#' distance squared, using the *absolute value* function, written mathematically\r\n#' as $| \\cdot |$, and in Julia as `abs`.\r\n\r\n#' #### Exercise 7\r\n#'\r\n#' Define a new loss function, `L_abs`, using the absolute value, and see what\r\n#' it looks like.\r\n\r\n#' #### Solution\r\nL_abs(w) = abs(y0 - f(x0,w))\r\n\r\npl = plot(L_abs, 0.5, 1, xlabel=\"w\", ylabel=\"L_abs(w)\", ylims=(0, 0.01), label=\"L\", legend=(0.8,0.9))\r\n\r\n#' Now we see why it was previously generally preferred to use squares: using\r\n#' the absolute value gives a cost function that is *not smooth*. This makes it\r\n#' difficult to use methods from calculus to find the minimum. Nonetheless,\r\n#' using non-smooth functions is very common in machine learning nowadays.", "meta": {"hexsha": "99a6d84041df76af02896e6a84e80df3358fe5cb", "size": 9134, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "JuliaAcademy/FundMachLearn/ch0500quiz.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/ch0500quiz.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/ch0500quiz.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.0341880342, "max_line_length": 142, "alphanum_fraction": 0.6439675936, "num_tokens": 2738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750427013547, "lm_q2_score": 0.899121379297294, "lm_q1q2_score": 0.8571099712433288}}
{"text": "\"\"\"\r\n    conGrad(A,B,Xawal)\r\nadalah fungsi yang digunakan untuk mencari solusi SPL `Ax=B` secara iteratif dengan\r\nnilai tebakan awal `Xawal` menggunakan metode conjugate gradient.\r\n\r\n# Example\r\n```jl\r\njulia> A = [2  3  3\r\n        3  5  4\r\n        3  4  6];\r\n\r\njulia> B = [3,4,6];\r\n\r\njulia> X,flag,err,M = conGrad(A,B,[0 0 0.9]);\r\n\r\njulia> X\r\n3-element Array{Float64,1}:\r\n  2.380760976839332e-6\r\n -1.220333023839802e-6\r\n  0.9999996142293243\r\n\r\njulia> flag\r\n0\r\n\r\njulia> err\r\n8.019009497939746e-8\r\n\r\njulia> M\r\n229\u00d75 Array{Float64,2}:\r\n   0.0  0.0          0.0          0.9       NaN\r\n   1.0  0.0266764    0.0355685    0.953353    0.0694497\r\n   2.0  0.0154769    0.000266424  0.975767    0.0432903\r\n   3.0  0.0193622    0.00858077   0.976843    0.00924021\r\n   \u22ee\r\n 225.0  5.10651e-6  -1.83459e-6   0.999999    1.32762e-6\r\n 226.0  2.29335e-6  -1.29137e-6   1.0         3.08384e-6\r\n 227.0  2.4522e-6   -1.23209e-6   1.0         1.73709e-7\r\n 228.0  2.38076e-6  -1.22033e-6   1.0         8.01901e-8\r\n```\r\nreturn solusi `X` dengan `flag` bernilai 0 jika metode conjugate gradient\r\nberhasil menemukan solusi dan gagal jika tidak 0.\r\nSerta, matriks `M` yang berisi catatan proses tiap iterasi `[k, X', error]`\r\n\"\"\"\r\nfunction conGrad(A,B,Xawal)\r\n    if ~(isposdef(A) && issymmetric(A))\r\n        error(\"matriks A harus simetrik definit positif\")\r\n    end\r\n    delta = 10^-7;\r\n    maxi = 1000;\r\n    flag = 1;\r\n    X = Xawal[:];\r\n    r = B-A*X\r\n    d = r\r\n    M = [0 X' NaN];\r\n    for k = 1:maxi\r\n        Xlama = X\r\n        rlama = r\r\n        dlama = d\r\n        X = Xlama + ((rlama'rlama)/(dlama'A*dlama))*dlama\r\n        r = rlama - ((rlama'rlama)/(dlama'A*dlama))*A*dlama\r\n        d = r - ((r'r)/(rlama'rlama))*dlama\r\n        err = norm(X-Xlama)\r\n        M = [M; [k X' err] ];\r\n        if err<delta\r\n            flag = 0;\r\n            break\r\n        end\r\n    end\r\n    err = M[end,end]\r\n    return X, flag, err, M\r\nend\r\n", "meta": {"hexsha": "fa8f5a0097524f6e0d9e5d36bccbbffe1dd2afdb", "size": 1904, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/conGrad.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/conGrad.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/conGrad.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": 26.4444444444, "max_line_length": 84, "alphanum_fraction": 0.5467436975, "num_tokens": 802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731147976794, "lm_q2_score": 0.8902942188450159, "lm_q1q2_score": 0.8570623087418983}}
{"text": "function solve_euler(timestep::Float64, n::Int64)\n    euler_result = Vector{Float64}(undef, n)\n\n    # Setting the initial condition\n    euler_result[1] = 1;\n    for i = 2:length(euler_result)\n        euler_result[i] = euler_result[i-1] - 3.0*euler_result[i-1]*timestep\n    end\n    return euler_result\nend\n\nfunction check_result(euler_result::Vector{Float64}, threshold::Float64,\n                      timestep::Float64)\n    is_approx = true\n\n    for i = 1:length(euler_result)\n        time = (i - 1)*timestep\n        solution = exp(-3*time);\n        if (abs(euler_result[i] - solution) > threshold)\n            println(euler_result[i], solution)\n            is_approx = false\n        end\n    end\n\n    return is_approx\nend\n\nfunction main()\n    timestep = 0.01\n    n = 100\n    threshold = 0.01\n\n    euler_result = solve_euler(timestep,n)\n    is_approx = check_result(euler_result, threshold, timestep)\n\n    println(is_approx)\nend\n\nmain()\n", "meta": {"hexsha": "49ddcacafe1b846eca655616a124fab3c2470b35", "size": 936, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "contents/forward_euler_method/code/julia/euler.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/forward_euler_method/code/julia/euler.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/forward_euler_method/code/julia/euler.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": 23.4, "max_line_length": 76, "alphanum_fraction": 0.6367521368, "num_tokens": 255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810511092412, "lm_q2_score": 0.9046505267461572, "lm_q1q2_score": 0.8570487669153032}}
{"text": "using SymPy\n\n# National Income Model\n\neq1 =  SymFunction(\"eq1\")\neq2 =  SymFunction(\"eq2\")\n\nY, C, b, I\u2080, G\u2080, a = symbols(\"Y C b I\u2080 G\u2080, a\")\n\neq1 = Eq(Y - C, I\u2080 + G\u2080)\neq2 = Eq(-b*Y + C, a)\n\ndisplay(eq1)\ndisplay(eq2)\n\nrow1 = [1 -1 I\u2080 + G\u2080]\nrow2 = [-b 1 a]\n\nsystem  = sympy.Matrix((row1, row2))\n\ndisplay(system)\n\nsolution = linsolve(system, (Y, C))\ndisplay(solution)\n\n\n\n# Demand and Supply Model\n\neq1 = SymFunction(\"eq1\")\neq2 = SymFunction(\"eq2\")\neq3 = SymFunction(\"eq3\")\u00a0\n\nQ\u1d48, Q\u02e2, a, b, P, f, Y, c, d, g, P\u1d62 = symbols(\"Q\u1d48 Q\u02e2 a b P f Y c d g P\u1d62\")\n\neq1 = Eq(Q\u1d48 + b*P, a + f*Y)\neq2 = Eq(Q\u02e2 + d*s, c - g*P\u1d62)\neq3 = Eq(Q\u1d48 - Q\u02e2)\n\nrow1 = [1 0 b a+f*Y]\nrow2 = [0 1 -d c-g*P\u1d62]\nrow3 = [1 -1 0 0]\n\n\nsystem = sympy.Matrix(((1, 0, b, a+f*Y), (0, 1, -d, c-g*P\u1d62), (1, -1, 0, 0)))\n\nsolution = linsolve(system, (Q\u1d48, Q\u02e2, P))\n\ndisplay(solution)\n\nsympy.init_printing(use_latex = \"mathjax\")\n", "meta": {"hexsha": "dd80641d7a30cd2af54524a7aada0e3f9549fa39", "size": 865, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Notebooks/lecture4.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.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.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": 16.6346153846, "max_line_length": 76, "alphanum_fraction": 0.5768786127, "num_tokens": 407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517106286379, "lm_q2_score": 0.8918110360927155, "lm_q1q2_score": 0.856987340690793}}
{"text": "## Exercise 5-7\n## https://benlauwens.github.io/ThinkJulia.jl/latest/images/fig52.svg\n## Figure 8. A Koch curve\n\n## The Koch curve is a fractal that looks something like A Koch curve. To draw a Koch curve with length x, all you have to do is\n\n## 1. Draw a Koch curve with length x/3.\n## 2. Turn left 60 degrees.\n## 3. Draw a Koch curve with length x/3.\n## 4. Turn right 120 degrees.\n## 5. Draw a Koch curve with length x/3.\n## 6. Turn left 60 degrees.\n## 7. Draw a Koch curve with length x/3.\n\n## The exception is if x is less than 3: in that case, you can just draw a straight line with length x.\n\nusing ThinkJulia\n\n## 1. Write a function called koch that takes a turtle and a length as parameters, and that uses the turtle to draw a Koch curve with the given length.\nprintln(\"Ans 1: \")\n\nfunction koch(turtle::Turtle, length)\n    if length < 3\n        forward(turtle, length)\n        return\n    end \n\n    koch(turtle, length/3)\n    turn(turtle, 60)\n    koch(turtle, length/3)\n    turn(turtle, -120)\n    koch(turtle, length/3)\n    turn(turtle, 60)\n    koch(turtle, length/3)\nend\n\nturtle = Turtle()\n# @svg begin\n#     koch(turtle, 100)\n# end\n\n## 2. Write a function called snowflake that draws three Koch curves to make the outline of a snowflake.\nprintln(\"Ans 2: \")\n\nfunction snowflake(turtle, length)\n    koch(turtle, length)\n    turn(turtle, -60)\n    koch(turtle, length)\n    turn(turtle, -60)\n    koch(turtle, length)\n    turn(turtle, -60)\n    koch(turtle, length)\n    turn(turtle, -60)\n    koch(turtle, length)\n    turn(turtle, -60)\n    koch(turtle, length)\n    turn(turtle, -60)\nend\n\n# @svg begin\n#     snowflake(turtle, 100)\n# end\n\n## 3. The Koch curve can be generalized in several ways. See https://en.wikipedia.org/wiki/Koch_snowflake for examples and implement your favorite.\nprintln(\"Ans 3: \")\n\nfunction koch_square(turtle::Turtle, length)\n    if length < 3\n        forward(turtle, length)\n        return\n    end\n\n    koch_square(turtle, length/3)\n    turn(turtle, 90)    \n    koch_square(turtle, length/3)\n    turn(turtle, -90)    \n    koch_square(turtle, length/3)\n    turn(turtle, -90)    \n    koch_square(turtle, length/3)\n    turn(turtle, 90)    \n    koch_square(turtle, length/3)\n    turn(turtle, 90)    \nend\n\n@svg begin\n    koch_square(turtle, 60)\nend\n\nprintln(\"End.\")\n", "meta": {"hexsha": "3213984b81b10d79b7343c94ebd653cf0b21b98d", "size": 2287, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chapter5/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": "Chapter5/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": "Chapter5/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": 25.4111111111, "max_line_length": 151, "alphanum_fraction": 0.6646261478, "num_tokens": 699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9353465134460243, "lm_q2_score": 0.9161096050004511, "lm_q1q2_score": 0.8568799249715865}}
{"text": "#=\nThe sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:\n\n1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...\n\nLet us list the factors of the first seven triangle numbers:\n\n 1: 1\n 3: 1,3\n 6: 1,2,3,6\n10: 1,2,5,10\n15: 1,3,5,15\n21: 1,3,7,21\n28: 1,2,4,7,14,28\nWe can see that 28 is the first triangle number to have over five divisors.\n\nWhat is the value of the first triangle number to have over five hundred divisors?\n=#\n\nfunction num_divisors(n)\n  count,i = 2,2 # accounts for 'n' and '1'\n  while (i^2 <= n)\n    if n%i==0\n      count += 2\n    end\n    i += 1\n  end\n  count\nend\n\nfunction triangle_number(n)\n  return convert(Int64,(1/2)*n*(n+1))\nend\n\nfunction calc()\n  i = 2\n  while num_divisors(triangle_number(i)) < 500\n    i += 1\n  end\n  triangle_number(i)\nend\n@time println(calc())\n", "meta": {"hexsha": "1f0e21600f033105eb93818edc849378431af382", "size": 892, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p12.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/p12.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/p12.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.7441860465, "max_line_length": 174, "alphanum_fraction": 0.6479820628, "num_tokens": 338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9728307708274402, "lm_q2_score": 0.880797085800514, "lm_q1q2_score": 0.856866507921877}}
{"text": "#=\nThe area of a circle is defined as \u03c0r^2. Estimate \u03c0 to 3 decimal places using a Monte Carlo method.\n\nHint: The basic equation of a circle is x2 + y2 = r2\n=#\nfunction estimate_pi(;number_of_decimal::Int64 = 3)\n    in = 0\n    out = 0\n    pi_estimated = 0.0\n    n_points = 0\n    while round(pi_estimated; digits = number_of_decimal) != round(pi; digits = number_of_decimal)\n        x, y = rand(2)\n        if (x^2 + y^2) <= 1\n            in = in + 1\n        end\n        n_points = n_points + 1\n        pi_estimated = in/n_points * 4\n    end\n    return pi_estimated\nend\n", "meta": {"hexsha": "9030bbd6c408512399df9aa02d473d06e364f10d", "size": 568, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/problem14_estimate_pi.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/problem14_estimate_pi.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/problem14_estimate_pi.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": 27.0476190476, "max_line_length": 99, "alphanum_fraction": 0.610915493, "num_tokens": 182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9728307700397332, "lm_q2_score": 0.8807970779778824, "lm_q1q2_score": 0.8568664996179702}}
{"text": "# This script solves a Fredholm equation of the first type\n\nprintln('\\n', \" \"^4, \"> Loading the packages...\")\n\nusing LinearAlgebra # Norm\nusing Optim # Optimization\nusing Plots # Plotting\nusing Printf # Formatted printing\nusing QuadGK # Gauss\u2013Kronrod integration\n\n# Use the GR backend for plots\ngr()\n\n# Change the default font for plots\ndefault(fontfamily=\"Computer Modern\", dpi=300, legend=:outerright)\n\nprintln(\" \"^4, \"> Computing the solution (Test)...\")\n\n# Define the kernel (Test)\nK(x, s) = exp(s * x)\n\n# Define the right part of the equation (Test)\nu(x) = (exp(x + 1) - 1) / (x + 1)\n\n# Set the integration intervals\na = 0\nb = 1\nc = 0\nd = 1\n\n# Set the number of nodes\nn = 100\n\n# Calculate the step\nh = (b - a) / n\n\n# Calculate the nodes for the s argument\ns = [ a + 0.5 * h + (i - 1) * h for i in 1:n ]\n\n# Set the initial value of the regularization parameter\n\u03b1 = 0.001\n\n# Prepare a range of nodes for the residual calculation\nxr = range(c, d; length=1000)\n\n# Compute the residual of the solution with the specified number of nodes and the regularization parameter\nfunction calculate(n::Int, \u03b1::Float64)::Tuple{Vector{Float64},Float64}\n    # Calculate the step\n    h = (b - a) / n\n\n    # Calculate the nodes for the s argument\n    s = [ a + 0.5 * h + (i - 1) * h for i in 1:n ]\n\n    # Calculate the nodes for the t argument\n    t = copy(s)\n\n    # Compute the g vector\n    g = [ quadgk(x -> K(x, s[i]) * u(x), c, d; rtol=1e-8)[1] for i in 1:n ]\n\n    # Prepare a matrix for the computation\n    B\u03b1 = Matrix{Float64}(undef, n, n)\n\n    # Compute the B\u03b1 matrix\n    for i in 1:n, j in 1:n\n        B\u03b1[i, j] = quadgk(x -> K(x, s[i]) * K(x, t[j]), c, d; rtol=1e-8)[1] * h + (i == j ? \u03b1 : 0)\n    end\n\n    # Compute the solution\n    z = Symmetric(B\u03b1) \\ g\n\n    # Calculate the residual\n    r = norm([ sum(K.(x, s) .* z .* h) for x in xr ] .- u.(xr))\n    \n    return z, r\nend\n\n# Compute the residual of the solution with the specified regularization parameter (optimization only)\nfunction residual(\u03b8::Vector{Float64})::Float64\n    return calculate(100, \u03b8[1])[2]\nend\n\n# Optimize over the regularization parameter\nres = Optim.optimize(\n    residual,\n    [\u03b1,],\n    LBFGS(),\n    Optim.Options(\n        show_trace=false,\n        extended_trace=true,\n        store_trace=true,\n    );\n    inplace=false,\n)\n\n# Save the trace and the results\nopen(\"test_optimization.trace\", \"w\") do io\n    println(io, res.trace)\n    println(\n        io,\n        \" * Parameters:\\n\",\n        \" \"^4, \"\u03b1 = $(res.minimum)\\n\",\n    )\n    show(io, res)\nend\n\n# Print the residual\nprintln(\n    '\\n',\n    \" \"^6, \"Regularization parameter: \", res.minimizer[1], '\\n',\n    \" \"^6, \"Residual: \", res.minimum, '\\n',\n)\n\nprintln(\" \"^4, \"> Plotting the solution (Test)...\")\n\n# Recalculate the solution\nz = calculate(n, res.minimizer[1])\n\n# Plot the solution\np = plot(s, z; label=\"\u041f\u0440\u0438\u0431\u043b\u0438\u0436\u0435\u043d\u043d\u043e\u0435 \u0440\u0435\u0448\u0435\u043d\u0438\u0435\", xlabel=\"s\", ylabel=\"z(s)\");\n\n# Add the solution to the plot\nplot!(p, x -> exp(x), a, b; label=\"\u0422\u043e\u0447\u043d\u043e\u0435 \u0440\u0435\u0448\u0435\u043d\u0438\u0435\");\n\n# Save the figure\nsavefig(p, \"$(@__DIR__)/../plots/test.pdf\")\n\nprintln('\\n', \" \"^6, \"* The figure `test.pdf` is saved. *\", '\\n')\n\nprintln(\" \"^4, \"> Plotting the residuals against the number of nodes (Test)...\")\n\n# Define the `n`s to plot against\nns = [ i for i in 10:300 ]\n\n# Calculate the residuals for these `n`s\nrs = @. getindex(calculate(ns, res.minimizer[1]), 2)\n\n# Make a plot of the residual against `n`\np = plot(ns, rs; label=\"\", xlabel=\"n\", ylabel=\"r\");\n\n# Save the figure\nsavefig(p, \"$(@__DIR__)/../plots/test_residual.pdf\")\n\nprintln('\\n', \" \"^6, \"* The figure `test_residual.pdf` is saved. *\", '\\n')\n\nprintln(\" \"^4, \"> Computing the solution (Assignment)...\")\n\n# Define the kernel\nK(x, s) = 1 / (1 + x + s)\n\n# Define the right part of the equation\nu(x) = 1 / sqrt(2 - x) * (log((2 + x) / (1 + x)) +\n       2 * log((sqrt(3) + sqrt(2 - x)) / (2 + sqrt(2 - x))))\n\n# Compute the g vector\ng = [ quadgk(x -> K(x, s[i]) * u(x), c, d; rtol=1e-8)[1] for i in 1:n ]\n\n# Optimize over the regularization parameter\nres = Optim.optimize(\n    residual,\n    [\u03b1,],\n    LBFGS(),\n    Optim.Options(\n        show_trace=false,\n        extended_trace=true,\n        store_trace=true,\n    );\n    inplace=false,\n)\n\n# Save the trace and the results\nopen(\"assignment_optimization.trace\", \"w\") do io\n    println(io, res.trace)\n    println(\n        io,\n        \" * Parameters:\\n\",\n        \" \"^4, \"\u03b1 = $(res.minimum)\\n\",\n    )\n    show(io, res)\nend\n\n# Print the residual\nprintln(\n    '\\n',\n    \" \"^6, \"Regularization parameter: \", res.minimizer[1], '\\n',\n    \" \"^6, \"Residual: \", res.minimum, '\\n',\n)\n\nprintln(\" \"^4, \"> Plotting the solution (Assignment)...\")\n\n# Recalculate the solution\nz = calculate(n, res.minimizer[1])\n\n# Plot the solution\np = plot(s, z; label=\"\", xlabel=\"s\", ylabel=\"z(s)\");\n\n# Save the figure\nsavefig(p, \"$(@__DIR__)/../plots/assignment.pdf\")\n\nprintln('\\n', \" \"^6, \"* The figure `assignment.pdf` is saved. *\", '\\n')\n\nprintln(\" \"^4, \"> Plotting the residuals against the number of nodes (Assignment)...\")\n\n# Define the `n`s to plot against\nns = [ i for i in 10:300 ]\n\n# Calculate the residuals for these `n`s\nrs = @. getindex(calculate(ns, res.minimizer[1]), 2)\n\n# Make a plot of the residual against `n`\np = plot(ns, rs; label=\"\", xlabel=\"n\", ylabel=\"r\");\n\n# Save the figure\nsavefig(p, \"$(@__DIR__)/../plots/assignment_residual.pdf\")\n\nprintln('\\n', \" \"^6, \"* The figure `assignment_residual.pdf` is saved. *\", '\\n')\n\nprintln(\" \"^4, \"> Calculating the solutions for tables (Assignment)...\")\n\n# Define the header\nheader = \"\u03b1 = 1e-4\" * \" \"^7 * \"1e-5\" * \" \"^11 * \"1e-6\" * \" \"^11 * \"1e-7\" *\n         \" \"^11 * \"1e-8\" * \" \"^11 * \"1e-9\" * \" \"^11 * \"1e-10\" * \" \"^10 * \"1e-11\" *\n         \" \"^10 * \"1e-12\" * \" \"^10 * \"1e-13\" * \" \"^10 * \"1e-14\" * \" \"^10 * \"1e-15\"\n\n# Calculate the solutions for different numbers of nodes and regularization parameters\nfor n in [100, 200, 300]\n    step = Int(n * 0.05)\n    data = Matrix{Float64}(undef, 20, 12)\n    format = Printf.Format(\"%.8e \"^11 * \"%.8e\\n\")\n    open(\"$(@__DIR__)/../tables/$(n).dat\", \"w\") do io\n        println(io, header)\n        for (i, \u03b1) in enumerate([1e-4, 1e-5, 1e-6, 1e-7, 1e-8, 1e-9, 1e-10, 1e-11, 1e-12, 1e-13, 1e-14, 1e-15])\n            sol, _ = calculate(n, \u03b1)\n            data[:, i] = sol[1:step:end]\n        end\n        for i in 1:20\n            Printf.format(io, format, data[i, :]...)\n        end\n    end\nend\n\nprintln('\\n', \" \"^6, \"* Tables `100.dat`, `200.dat`, and `300.dat` are saved. *\", '\\n')\n", "meta": {"hexsha": "8330af7b6ff1fff1b1d7e9adff67b7c4f9a8137b", "size": 6420, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "A1/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": "A1/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": "A1/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": 26.5289256198, "max_line_length": 111, "alphanum_fraction": 0.5886292835, "num_tokens": 2072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154287592778, "lm_q2_score": 0.8933094131553265, "lm_q1q2_score": 0.8568215537749198}}
{"text": "# This file is a part of AstroLib.jl. License is MIT \"Expat\".\n# Copyright (C) 2016 Mos\u00e8 Giordano.\n\n_trueanom{T<:AbstractFloat}(E::T, e::T) =\n    if e < 0\n        # We don't need to check e > 1, because a DomainError is raised anyway.\n        error(\"eccentricity must be in the range [0, 1]\")\n    else\n        2.0*atan(sqrt((1.0 + e)/(1.0 - e))*tan(E/2.0))\n    end\n\n\"\"\"\n    trueanom(E, e) -> true anomaly\n\n### Purpose ###\n\nCalculate true anomaly for a particle in elliptic orbit with eccentric anomaly\n\\$E\\$ and eccentricity \\$e\\$.\n\n### Explanation ###\n\nIn the two-body problem, once that the [Kepler's\nequation](https://en.wikipedia.org/wiki/Kepler%27s_equation) is solved and\n\\$E(t)\\$ is determined, the polar coordinates \\$(r(t), \\\\theta(t))\\$ of the body\nat time \\$t\\$ in the elliptic orbit are given by\n\n\\$\\$ \\\\theta(t) = 2\\\\arctan \\\\left(\\\\sqrt{\\\\frac{1 + e}{1 - e}} \\\\tan\\\\frac{E(t)}{2} \\\\right)\\$\\$\n\\$\\$ r(t) = \\\\frac{a(1 - e^{2})}{1 + e\\\\cos(\\\\theta(t) - \\\\theta_{0})}\\$\\$\n\nin which \\$a\\$ is the semi-major axis of the orbit, and \\$\\\\theta_0\\$ the value\nof angular coordinate at time \\$t = t_{0}\\$.\n\n### Arguments ###\n\n* `E`: eccentric anomaly.  This can be either a scalar or an array\n* `e`: eccentricity, in the elliptic motion regime (\\$0 \\\\leq e \\\\leq 1\\$)\n\n### Output ###\n\nThe true anomaly.  If an array of eccentric anomalies is provided in input, an\narray of the same length as `E` is returned.\n\n### Example ###\n\nPlot the true anomaly as a function of mean anomaly for eccentricity \\$e = 0\\$,\n\\$0.5\\$, \\$0.9\\$.  Use [PyPlot.jl](https://github.com/stevengj/PyPlot.jl) for\nplotting.\n\n``` julia\nusing PyPlot\nM=linspace(0, 2pi, 1001)[1:end-1];\nfor ecc in (0, 0.5, 0.9)\n    E = kepler_solver(M, ecc);\n    plot(M, cirrange(trueanom(E, ecc), 2pi))\nend\n```\n\n### Notes ###\n\nThe eccentric anomaly can be calculated with `kepler_solver` function.\n\"\"\"\ntrueanom(E::Real, e::Real) = _trueanom(promote(float(E), float(e))...)\n\nfunction trueanom{R1<:Real,R2<:Real}(E::AbstractArray{R1}, e::R2)\n    type\u03bd = promote_type(float(R1), float(R2))\n    \u03bd = similar(E, type\u03bd)\n    for i in eachindex(E)\n        \u03bd[i] = trueanom(E[i], e)\n    end\n    return \u03bd\nend\n", "meta": {"hexsha": "1f128e8ec2e387f604e14657fd501c9e50bdc2e6", "size": 2150, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/trueanom.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/trueanom.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/trueanom.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": 29.8611111111, "max_line_length": 97, "alphanum_fraction": 0.6269767442, "num_tokens": 719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541610257063, "lm_q2_score": 0.9099070066488187, "lm_q1q2_score": 0.8568177189573052}}
{"text": "# Imports\nusing Random, Statistics, Plots, Printf\nRandom.seed!(430);\n\n# Part (a)\nN = 10000;\nX\u2099 = randn(2, 1);\n\u03bc\u2093 = [0.5; 0.3];\nC\u2093 = [1 0.6; 0.6 sqrt(2)];\n\n# 2-dimensional Gaussian vector\nX = C\u2093 * X\u2099 + \u03bc\u2093;\nprintln(\"Answer of part (a)\")\nprintln(\"2-dimensional Gaussian vector:\")\nprintln(X)\n\n# Part (b)\n# Generate 10000 vector with related parameters\nfunction generate(matrix, \u03bc\u2093, n)\n    samples = zeros(N, 2)\n    for i in 1:n\n        X = randn(2, 1);\n        X = sqrt(matrix) * X + \u03bc\u2093;\n        samples[i, :] = X;\n    end\n    return samples\nend\n\n# Plot generated samples\nsamples = generate(C\u2093, \u03bc\u2093, N)\nX\u2081, X\u2082 = samples[:, 1], samples[:, 2];\ndisplay(plot(X\u2081, X\u2082, seriestype = :scatter, title = \"Scatter Plot\"))\n\n# Part (c)\n#\u2211 = zeros(2,2)\n\u2211 = []\nfor i in 1:N\n    #\u2211 += samples[i, :]*samples[i, :]'\n    push!(\u2211, samples[i, :]*samples[i, :]')\nend\n#S\u2093 = \u2211/N\nS\u2093 = sum(\u2211) / N;\nprintln(\"\\nAnswer of part (c) for $N samples: \")\nprintln(S\u2093)\n\n\n# When we increase \"N\", convergence will be [1.25 0.75; 0.75 1.504] matrix\nprintln(\"Convergence limit matrix:\")\nconvergence = C\u2093 + \u03bc\u2093*\u03bc\u2093'\n\n\n\n\n", "meta": {"hexsha": "d86fd0933f213fd19163cf81df9931645bd50696", "size": 1072, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Homeworks/Homework2/eacikgoz17_q6.jl", "max_stars_repo_name": "ecacikgoz97/ELEC430_Detection_and_Estimation_Theory", "max_stars_repo_head_hexsha": "049b5acb8b5c240432be8263cd1594331f286a35", "max_stars_repo_licenses": ["MIT"], "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/Homework2/eacikgoz17_q6.jl", "max_issues_repo_name": "ecacikgoz97/ELEC430_Detection_and_Estimation_Theory", "max_issues_repo_head_hexsha": "049b5acb8b5c240432be8263cd1594331f286a35", "max_issues_repo_licenses": ["MIT"], "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/Homework2/eacikgoz17_q6.jl", "max_forks_repo_name": "ecacikgoz97/ELEC430_Detection_and_Estimation_Theory", "max_forks_repo_head_hexsha": "049b5acb8b5c240432be8263cd1594331f286a35", "max_forks_repo_licenses": ["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.8518518519, "max_line_length": 74, "alphanum_fraction": 0.5970149254, "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541561135442, "lm_q2_score": 0.909906997487259, "lm_q1q2_score": 0.8568177058606736}}
{"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 OrdinaryDiffEq\nusing Plots, Plots.PlotMeasures\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[1]*u\ndotrf(u,p,t) = [-p[2]*u[1]*u[2], p[3]*u[1]*u[2]]\ndotf(u,p,t) = -p[4]*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\nrabbitfox_system = oapply(rabbitfox_pattern, [rabbit_growth, rabbitfox_predation, fox_decline])\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.\n\n\u03b1, \u03b2, \u03b3, \u03b4 = 0.3, 0.015, 0.015, 0.7\nparams = [\u03b1, \u03b2, \u03b3, \u03b4]\n\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, lw=2, title = \"Lotka-Volterra Predator-Prey Model\", bottom_margin=10mm, left_margin=10mm, label=[\"rabbits\" \"foxes\"])\nxlabel!(\"Time\")\nylabel!(\"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    rabbit_hawk_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(x, p, t) = [-p[5]*x[1]*x[2], p[6]*x[1]*x[2]]\ndoth(x, p, t)  = -p[7]*x\n\nrabbithawk_predation = ContinuousResourceSharer{Float64}(2, dotrh)\nhawk_decline         = ContinuousResourceSharer{Float64}(1, doth)\n\n## Compose\nland_system = oapply(rabbitfoxhawk_pattern, \n                        [rabbit_growth, rabbitfox_predation, fox_decline, \n                         rabbithawk_predation, hawk_decline])\n\n## Solve and plot\n\u03b2\u2032, \u03b3\u2032, \u03b4\u2032 = .01, .01, .5\nparams = vcat(params, [\u03b2\u2032, \u03b3\u2032, \u03b4\u2032])\n\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, lw=2, title = \"Land Ecosystem\", bottom_margin=10mm, left_margin=10mm, label=[\"rabbits\" \"foxes\" \"hawks\"])\nxlabel!(\"Time\")\nylabel!(\"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[1]*f[1] - p[2]*x[1]*f[1]]\ndotFISH(F, x, p, t) = [p[3]*x[1]*F[1] - p[4]*F[1] - p[5]*x[2]*F[1]]\ndotsharks(s, x, p, t) = [p[6]*s[1]*x[1]-p[7]*s[1]]\n\nfish   = ContinuousMachine{Float64}(1,1,1, dotfish,   f->f)\nFISH   = ContinuousMachine{Float64}(2,1,1, dotFISH,   F->F)\nsharks = ContinuousMachine{Float64}(1,1,1, dotsharks, s->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([], [])\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\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])\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\n\u03b1, \u03b2, \u03b3, \u03b4, \u03b2\u2032, \u03b3\u2032, \u03b4\u2032 = 0.35, 0.015, 0.015, 0.7, 0.017, 0.017, 0.35\nparams = [\u03b1, \u03b2, \u03b3, \u03b4, \u03b2\u2032, \u03b3\u2032, \u03b4\u2032]\n\nu0 = [100.0, 10, 2.0]\ntspan = (0.0, 100.0)\n\nprob = ODEProblem(ocean_system, u0, tspan, params)\nsol = solve(prob, FRK65(0))\n\nplot(sol, lw=2, title = \"Ocean Ecosystem\", bottom_margin=10mm, left_margin=10mm, label=[\"little fish\" \"big fish\" \"sharks\"])\nxlabel!(\"Time\")\nylabel!(\"Population size\")\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\n# There will be 16 parameters in to the total ecosystem.\n# - parameters 1-7 will determine the land ecosystem\n# - parameters 8 and 9 will determine the hawk/little fish predation. Parameter 8 gives the rate of hawk growth and parameter 8 gives the rate of little fish decline.\n# - parameter 10-16 will determine the ocean ecosystem.\n\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[10:16]))\n\ndothf(u,p,t) = [p[8]*u[1]*u[2], -p[9]*u[1]*u[2]]\nfishhawk_predation = ContinuousResourceSharer{Float64}(2, dothf)\n\n## Define the composition pattern\neco_pattern = @relation () where (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\necosystem=oapply(eco_pattern, [land_system, fishhawk_predation, ocean_system_rs])\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\nparams = [0.3, 0.015, 0.015, 0.7, .01, .01, .5, \n          0.001, 0.003, \n          0.35, 0.015, 0.015, 0.7, 0.017, 0.017, 0.35]\n\nprob = ODEProblem(ecosystem, u0, tspan, params)\nsol = solve(prob, Tsit5())\nplot(sol, lw=2, bottom_margin=10mm, left_margin=10mm, label = [\"rabbits\" \"foxes\" \"hawks\" \"little fish\" \"big fish\" \"sharks\"])\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, lw=2, bottom_margin=10mm, left_margin=10mm, label = [\"rabbits\" \"foxes\" \"hawks\" \"little fish\" \"big fish\" \"sharks\"])\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 = [0.3, 0.015, 0.015, 0.7, .01, .01, .5, \n          0, 0, \n          0.35, 0.015, 0.015, 0.7, 0.017, 0.017, 0.35]\nprob = ODEProblem(ecosystem, u0, tspan, params)\nsol = solve(prob, Tsit5())\nplot(sol, lw=2, bottom_margin=10mm, left_margin=10mm, label = [\"rabbits\" \"foxes\" \"hawks\" \"little fish\" \"big fish\" \"sharks\"])\n\n\n\n\n", "meta": {"hexsha": "25b6c9211e718336ab6794b66f21898599f5dd9c", "size": 11995, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Ecosystem.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/Ecosystem.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/Ecosystem.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": 47.4110671937, "max_line_length": 644, "alphanum_fraction": 0.7203834931, "num_tokens": 3591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768525822309, "lm_q2_score": 0.9073122163480667, "lm_q1q2_score": 0.8566631927409258}}
{"text": "##############   EXAMPLE-3     ##############\n# Correlated errors in X and Y\n\nusing LinearFitXYerrors\nusing Plots; gr()\n\n\n# INPUT DATA:\n# Mahon, K. [1996] The New \u201cYork\u201d Regression: Application of an Improved Statistical Method to Geochemistry. International Geology Review, 38(4), pp.293\u2013303\n\n#  Table 3\n#      X        Y\nM = [0.037   0.0080\n     0.035   0.0084\n     0.032   0.0100\n     0.040   0.0085\n     0.013   0.0270\n     0.038   0.0071\n     0.042   0.0043\n     0.030   0.0160]\n\nX = M[:,1]\nY = M[:,2]\n\u03c3X = 0.03*X     # standard deviation of errors in X\n\u03c3Y = 0.10*Y     # standard deviation of errors in Y\nr1 = 0  # correlation coefficient between errors\nr2 = 0.7071\n\n# COMPUTE and PLOT:\n\n# st = linearfitxy(X, Y; isplot=true, ratio=:auto);  # if assuming no errors\n# stxy1 = linearfitxy(X, Y; \u03c3X=\u03c3X, \u03c3Y=\u03c3Y, r=r1, isplot=true, ratio=:auto);\n\nstxy2 = linearfitxy(X, Y; \u03c3X=\u03c3X, \u03c3Y=\u03c3Y, r=r2, isplot=true, ratio=:auto);\n\n\n\nsavefig(\"Example3_LinearFitXYerrors.png\")\n########################################\n", "meta": {"hexsha": "ab0f95f911720e76a2acd9c1a6c0d240f4b0d7f0", "size": 1006, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/example3.jl", "max_stars_repo_name": "rafael-guerra-www/LinearFitXYerrors.jl", "max_stars_repo_head_hexsha": "5109cda43472fb08f61b12ac792ca991a233c6a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-09-12T18:13:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-18T10:11:37.000Z", "max_issues_repo_path": "examples/example3.jl", "max_issues_repo_name": "rafael-guerra-www/LinearFitXYerrors.jl", "max_issues_repo_head_hexsha": "5109cda43472fb08f61b12ac792ca991a233c6a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-09-12T11:21:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-11T19:43:40.000Z", "max_forks_repo_path": "examples/example3.jl", "max_forks_repo_name": "rafael-guerra-www/LinearFitXYerrors.jl", "max_forks_repo_head_hexsha": "5109cda43472fb08f61b12ac792ca991a233c6a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.15, "max_line_length": 156, "alphanum_fraction": 0.5894632207, "num_tokens": 371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741214369554, "lm_q2_score": 0.8991213867309121, "lm_q1q2_score": 0.8564797650303756}}
{"text": "using LinearAlgebra\nusing SparseArrays\nusing Plots\n\n\"This routine solves the periodic advection 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\na = 1 # advection speed\n\u0394t = .9*\u0394x / a # timestep\nT = 2.0 # final time\n\n# initial condition and forcing\nu0(x) = exp(-25*x^2)\nu = u0.(x)\nf(uL,uR) = uL\n\n# indexing for periodic boundaries\nindex_left = [m+1; 1:m+1]\nindex_right = [1:m+1; 1]\nfv_flux = zeros(m+2) # storage at interfaces\n\nNsteps = ceil(Int,T/\u0394t)\n\u0394t = T / Nsteps\ninterval = 10\nplot()\nunorm = zeros(Nsteps)\n@gif for k = 1:Nsteps\n    for i = 1:m+2 # loop over cell interfaces\n        left = index_left[i]\n        right = index_left[i]\n        fv_flux[i] = f(u[left],u[right])\n    end\n    for i = 1:m+1\n        u[i] = u[i] - a*\u0394t/\u0394x * (fv_flux[i+1]-fv_flux[i])\n    end\n\n    if k % interval==0\n        plot(x,u,linewidth=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": "5f93b06f9e2dd274b6dcdd6e4829f3f75d45c634", "size": 1174, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "weeks11_to_12/fv_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": "weeks11_to_12/fv_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": "weeks11_to_12/fv_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": 23.9591836735, "max_line_length": 92, "alphanum_fraction": 0.6277683135, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133464597458, "lm_q2_score": 0.9111797027760039, "lm_q1q2_score": 0.8564299636623903}}
{"text": "\"\"\"\n    SEq1\n\nSolutions of Equations in One Variable\nhere are functions to find root:\n1. Bisection\n2. Fixed-Point Iteration\n3. Newton Method\n4. The Secant Method\n5. The False Position Method\n6.  M\u00fcller\u2019s Method\n\"\"\"\nmodule SEq1\nusing ForwardDiff\n\n\"\"\"\n    Bisection(f::Function, a::Real, b::Real; TOL::Float64=0.0000001, N::Int=40, output_seq::Bool=false)\n\nUse Bisection To find a solution to.\n\n``f(x) = 0``\n\nYou should use the function, and a interval ``[a, b]``, tolerance TOL, maximum number of iterations N.\n\nThen you will get approximate solution ``p`` or can't find in maximum N and return -1.\n\nyou can set output_seq=true to output sequence.\n\"\"\"\n@inline function Bisection(f::Function, a::Real, b::Real; TOL::Float64=0.0000001, N::Int=40, output_seq::Bool=false)\n    i = 1\n    fa = f(a)\n    seq = []\n    if f(a)*f(b) > 0\n        return -1\n    else\n        while i <= N\n            p = a + (b - a)/2\n            fp = f(p)\n            push!(seq, [p, f(p)])\n            if fp == 0 || (b - a)/2 < TOL\n                if output_seq\n                    return seq\n                else\n                    return p\n                end\n                break\n            end\n            i += 1\n            if fa*fp > 0\n                a = p\n                fa = fp\n            else\n                b = p\n            end\n        end\n        return -1\n    end\nend\n\n\"\"\"\n    fixed_point(f::Function, p\u2080::Real; TOL::Float64=0.0000001, N::Int=30, output_seq::Bool=false)\n\nUse fixed point Iteration to find root.\n\nThe number p is a **fixed point** for a given function g if ``g(p) = p``.\n\ninput a function, initial p\u2080, optional Args: tolerancs TOL, maximum number of iterations N, output_seq.\n\nOutput a root p or sequence.\n\"\"\"\n@inline function fixed_point(f::Function, p\u2080::Real; TOL::Float64=0.0000001, N::Int=30, output_seq::Bool=false)\n    i = 1\n    seq = []\n    while i <= N\n        p = f(p\u2080)\n        push!(seq, p\u2080)\n        if abs(p - p\u2080) < TOL\n            if output_seq\n                return seq\n            else\n                return p\n            end\n            break\n        end\n        i += 1\n        p\u2080 = p\n    end\n    return -1\nend\n\n\"\"\"\n    Newton(f::Function, p\u2080::Real; TOL::Float64=0.0000001, N::Int=20, output_seq=false)\n\nUse Newton method to find root.\n\nyou should use a function and initial p\u2080, then you can set Args or use default.\n\n\"\"\"\n@inline function Newton(f::Function, p\u2080::Real; TOL::Float64=0.0000001, N::Int=20, output_seq::Bool=false)\n    i = 1\n    seq = []\n    f1(x) = ForwardDiff.derivative(x -> f(x), x)\n    while i <= N\n        push!(seq, p\u2080)\n        p = p\u2080 - f(p\u2080)/f1(p\u2080)\n        if abs(p - p\u2080) < TOL\n            if output_seq\n                return seq\n            else\n                return p\n            end\n            break\n        end\n        p\u2080 = p\n        i += 1\n    end\n    return -1\nend\n\n\"\"\"\n    Secant(f::Function, p\u2080::Real, )\n\nUse the Secant Method to find root\nA function and p\u2080, p\u2081(p\u2080<p\u2081), then you can set Args or use default.\n\"\"\"\n@inline function Secant(f::Function, p\u2080::Real, p\u2081::Real; TOL::Float64=0.0000001, N::Int=30, output_seq::Bool=false)\n    i = 2\n    seq = []\n    a\u2080 = f(p\u2080)\n    a\u2081 = f(p\u2081)\n    push!(seq, p\u2080)\n    push!(seq, p\u2081)\n    while i <= N\n        p = p\u2081 - a\u2081*(p\u2081 - p\u2080)/(a\u2081 - a\u2080)\n        push!(seq, p)\n        if abs(p - p\u2081) < TOL\n            if output_seq\n                return seq\n            else\n                return p\n            end\n            break\n        end\n        i += 1\n        p\u2080 = p\u2081\n        a\u2080 = a\u2081\n        p\u2081 = p\n        a\u2081 = f(p)\n    end\nend\n\n\"\"\"\n    FalsePos(f::Function, p\u2080::Real, p\u2081::Real; TOL::Float64=0.00000001, N::Int=40, output_seq::Bool=false)\n\nUse the false position method to find root.\na function and interval ``[a, b]``, then you can set Args or use default.\n\"\"\"\n@inline function FalsePos(f::Function, p\u2080::Real, p\u2081::Real; TOL::Float64=0.00000001, N::Int=40, output_seq::Bool=false)\n    i = 2\n    seq = []\n    q\u2080 = f(p\u2080)\n    q\u2081 = f(p\u2081)\n    push!(seq, p\u2080)\n    push!(seq, p\u2081)\n    while i <= N\n        p = p\u2081 - q\u2081*(p\u2081 - p\u2080)/(q\u2081 - q\u2080)\n        push!(seq, p)\n        if abs(p - p\u2081) < TOL\n            if output_seq\n                return seq\n            else\n                return p\n            end\n            break\n        end\n        i += 1\n        q = f(p)\n        if q*q\u2081 < 0\n            p\u2080 = p\u2081\n            q\u2080 = q\u2081\n        end\n        p\u2081 = p\n        q\u2081 = q\n    end\n    return -1\nend\n\n\"\"\"\n    ModifiedNewton(f::Function, p\u2080::Real; TOL::Float64=0.00000001, N::Int=20, output_seq::Bool=false)\n\nNewton and ModifiedNewton, Both methods are rapidly convergent to the actual zero.\n\"\"\"\n@inline function ModifiedNewton(f::Function, p\u2080::Real; TOL::Float64=0.00000001, N::Int=20, output_seq::Bool=false)\n    i = 1\n    seq = []\n    push!(seq, p\u2080)\n    f1(x) = ForwardDiff.derivative(x -> f(x), x)\n    f11(x) = ForwardDiff.derivative(x -> f1(x), x)\n    while i <= N\n        p = p\u2080 - f(p\u2080)*f1(p\u2080)/((f1(p\u2080))^2 - f(p\u2080)*f11(p\u2080))\n        push!(seq, p)\n        if abs(p - p\u2080) < TOL\n            if output_seq\n                return seq\n            else\n                return p\n            end\n            break\n        end\n        i += 1\n        p\u2080 = p\n    end\n    return -1\nend\n\n\n\"\"\"\n    Muller(f::Function, p\u2080::Real, p\u2081::Real, p\u2082::Real; TOL::Float64=0.00000001, N::Int=20, output_seq::Bool=false)\n\"\"\"\n@inline function Muller(f::Function, p\u2080::Real, p\u2081::Real, p\u2082::Real; TOL::Float64=0.00000001, N::Int=20, output_seq::Bool=false)\n    h\u2081 = p\u2081 - p\u2080\n    h\u2082 = p\u2082 - p\u2081\n    \u03b4\u2081 = (f(p\u2081) - f(p\u2080))/h\u2081\n    \u03b4\u2082 = (f(p\u2082) - f(p\u2081))/h\u2082\n    d = (\u03b4\u2082 - \u03b4\u2081)/(h\u2081 + h\u2082)\n    i = 3\n    seq = []\n    while i <= N\n        b = \u03b4\u2082 + h\u2082*d\n        D = sqrt(complex(b^2 - 4*f(p\u2082)*d))\n        if abs(b - D) < abs(b + D)\n            E = b + D\n        else\n            E = b - D\n        end\n        h = -2 * f(p\u2082)/E\n        p = p\u2082 + h\n        push!(seq, p)\n        if abs(h) < TOL\n            if output_seq\n                return seq\n            else\n                return p\n            end\n            break\n        end\n        p\u2080 = p\u2081\n        p\u2081 = p\u2082\n        p\u2082 = p\n        h\u2081 = p\u2081 - p\u2080\n        h\u2082 = p\u2082 - p\u2081\n        \u03b4\u2081 = (f(p\u2081) - f(p\u2080))/h\u2081\n        \u03b4\u2082 = (f(p\u2082) - f(p\u2081))/h\u2082\n        d = (\u03b4\u2082 - \u03b4\u2081)/(h\u2081 + h\u2082)\n        i += 1\n    end\n    return -1\nend\n\nend\n", "meta": {"hexsha": "867959d482528106e2cf69f6498ffd4d727a9303", "size": 6185, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SEq1.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/SEq1.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/SEq1.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.6973180077, "max_line_length": 126, "alphanum_fraction": 0.489894907, "num_tokens": 2027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.953966096291997, "lm_q2_score": 0.8976952832120991, "lm_q1q2_score": 0.8563708649855849}}
{"text": "using Test\nimport LinearAlgebra: dot\nusing RationalSimplex\n\n@testset \"RationalSimplex\" begin\n\n@testset \"Test standard form\" begin\n      # Test case 1\n      # min -10x - 12y - 12z\n      # st     x +  2y +  2z <= 20\n      #       2x +   y +  2z <= 20\n      #       2x +  2y +   z <= 20\n      #       x, y, z >= 0\n      @testset \"Test case 1 (optimal)\" begin\n            c = [-10//1, -12//1, -12//1, 0//1, 0//1, 0//1]\n            A = [  1//1    2//1    2//1  1//1  0//1  0//1;\n                   2//1    1//1    2//1  0//1  1//1  0//1;\n                   2//1    2//1    1//1  0//1  0//1  1//1]\n            b = [20//1, 20//1, 20//1]\n            status, x = simplex(c, A, b)\n            @test status == :Optimal\n            @test x[1] == 4//1\n            @test x[2] == 4//1\n            @test x[3] == 4//1\n      end\n\n      # Test case 2\n      # min -90x - y\n      # st    2x + y <= 40\n      #      20x + y <= 100\n      #       2x     <= 3\n      #        x,  y >= 0\n      @testset \"Test case 2 (optimal)\" begin\n            c = [-90//1, -1//1, 0//1, 0//1, 0//1]\n            A = [  2//1   1//1  1//1  0//1  0//1;\n                  20//1   1//1  0//1  1//1  0//1;\n                   2//1   0//1  0//1  0//1  1//1]\n            b = [ 40//1, 100//1, 3//1]\n            status, x = simplex(c, A, b)\n            @test status == :Optimal\n            @test x[1] == 3//2\n            @test x[2] == 37//1\n            @test x[3] == 0//1\n            @test x[4] == 33//1\n            @test x[5] == 0//1\n      end\n\n      # Test case 3\n      # min x\n      # st  x >= 3\n      #     x <= 2\n      @testset \"Test case 3 (infeasible)\" begin\n            c = [1//1, 0//1, 0//1]\n            A = [1//1 -1//1  0//1;\n                 1//1  0//1  1//1]\n            b = [3//1, 2//1]\n            status, x = simplex(c, A, b)\n            @test status == :Infeasible\n      end\n\n      # Test case 4\n      # min -x\n      # st  x >= 2\n      @testset \"Test Case 4 (unbounded)\" begin\n            c = [-1//1, 0//1]\n            A = [ 1//1 -1//1;]\n            b = [ 2//1]\n            status, x = simplex(c, A, b)\n            @test status == :Unbounded\n      end\n\n      # Check simplex detects nonneg rhs\n      @testset \"Check for nonnegative RHS\" begin\n            c = [-1//1, 0//1]\n            A = [ 1//1 -1//1;]\n            b = [-2//1]\n            @test_throws AssertionError simplex(c, A, b)\n      end\nend\n\n@testset \"Test general form\" begin\n      # Test case 1\n      # max  10x + 12y + 12z\n      # st     x +  2y +  2z <= 20\n      #       2x +   y +  2z <= 20\n      #       2x +  2y +   z <= 20\n      #       x, y, z >= 0\n      @testset \"Test case 1 (optimal)\" begin\n            c = [ 10//1,  12//1,  12//1]\n            A = [  1//1    2//1    2//1;\n                   2//1    1//1    2//1;\n                   2//1    2//1    1//1]\n            b = [20//1, 20//1, 20//1]\n            status, x = simplex(c, :Max, A, b, ['<','<','<'])\n            @test status == :Optimal\n            @test x[1] == 4//1\n            @test x[2] == 4//1\n            @test x[3] == 4//1\n      end\n\n      # Test case 2\n      # max  90x + y\n      # st    2x + y <= 40\n      #      20x + y <= 100\n      #       2x     <= 3\n      #        x,  y >= 0\n      @testset \"Test case 2 (optimal)\" begin\n            c = [ 90//1,  1//1]\n            A = [  2//1   1//1;\n                  20//1   1//1;\n                   2//1   0//1]\n            b = [ 40//1, 100//1, 3//1]\n            status, x = simplex(c, :Max, A, b, ['<','<','<'])\n            @test status == :Optimal\n            @test x[1] == 3//2\n            @test x[2] == 37//1\n      end\n\n      # Test case 3\n      # min x\n      # st  x >= 3\n      #     x <= 2\n      @testset \"Test case 3 (infeasible)\" begin\n            c = [1//1, 0//1]\n            A = [1//1 0//1;\n                 1//1 0//1]\n            b = [3//1, 2//1]\n            status, x = simplex(c, :Min, A, b, ['>','<'])\n            @test status == :Infeasible\n      end\n\n      # Test case 4\n      # min x\n      # st   x >=  3\n      #     -x >= -2\n      @testset \"Test case 4 (infeasible)\" begin\n            c = [1//1, 0//1]\n            A = [ 1//1 0//1;\n                 -1//1 0//1]\n            b = [3//1, -2//1]\n            status, x = simplex(c, :Min, A, b, ['>','>'])\n            @test status == :Infeasible\n      end\nend\n\n@testset \"Kantorovich distances\" begin\n      # Problem description from \n      # http://stla.github.io/stlapblog/posts/KantorovichWithJulia.html\n      c = [0//1, 1//1, 1//1, 1//1, 0//1, 1//1, 1//1, 1//1, 0//1]\n      b = [1//7, 2//7, 4//7, 1//4, 1//4, 1//2]\n      M = [1//1 1//1 1//1 0//1 0//1 0//1 0//1 0//1 0//1;\n           0//1 0//1 0//1 1//1 1//1 1//1 0//1 0//1 0//1;\n           0//1 0//1 0//1 0//1 0//1 0//1 1//1 1//1 1//1;\n           1//1 0//1 0//1 1//1 0//1 0//1 1//1 0//1 0//1;\n           0//1 1//1 0//1 0//1 1//1 0//1 0//1 1//1 0//1;\n           0//1 0//1 1//1 0//1 0//1 1//1 0//1 0//1 1//1]\n\n      status, x = simplex(c, :Min, M, b, ['=','=','=','=','=','='])\n      @test dot(c,x) == 3//28\nend\n\nend  # RationalSimplex testset.", "meta": {"hexsha": "103ec40636dbd7cd8afd9a72ce1fca4b1dcdec8a", "size": 4990, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "bemot/RationalSimplex.jl", "max_stars_repo_head_hexsha": "63e079d7880e18b7a70f4265f651e8f08f63701e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2016-01-18T11:10:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T23:29:21.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "bemot/RationalSimplex.jl", "max_issues_repo_head_hexsha": "63e079d7880e18b7a70f4265f651e8f08f63701e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-03-08T13:08:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-11T09:05:16.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "bemot/RationalSimplex.jl", "max_forks_repo_head_hexsha": "63e079d7880e18b7a70f4265f651e8f08f63701e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2016-01-18T11:10:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-01T20:52:30.000Z", "avg_line_length": 30.8024691358, "max_line_length": 71, "alphanum_fraction": 0.3458917836, "num_tokens": 2090, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.966914020657881, "lm_q2_score": 0.8856314783461303, "lm_q1q2_score": 0.8563294935488399}}
{"text": "using Pkg\nPkg.activate(pwd())\n\n# # Logistic regression\n# ## Loading and preparing data\n\n\nusing StatsPlots\nusing RDatasets\n\niris = dataset(\"datasets\", \"iris\")\n\n# ### Exercise:\n# Create the `iris_reduced` dataframe in the following way:\n# - Label \"setosa\" will be deleted.\n# - Label \"versicolor\" will be the negative class.\n# - Label \"virginica\" will be the positive class.\n# - Add the `intercept` column with ones as entries.\n# For the features, consider only petal length and petal width.\n# \n# **Hint**: Use the `Query` package or do it manually via the `!insertcols` function.\n# \n# ---\n# ### Solution:\n\n\n\n# ---\n\nX = Matrix(iris_reduced[:, 1:3])\ny = iris_reduced.label\n\n\n# ### Exercise:\n# Since X has two features (columns), it is simple to visualize. Use scatter plot to show\n# the data. Use different colours for different classes. Try to produce a nice graph by\n# including names of classes and axis labels (petal length and petal width).\n# \n# ---\n# ### Solution:\n\n\n\n# ---\n# \n# ## Training the classifier\n# ### Exercise:\n# Write a function log_reg which takes as an input the dataset, the labels and the initial \n# point. It should use Newton's method to find the optimal weights ``w``. Print the results \n# when started from zero.\n# \n# It would be possible to use the code optim(f, g, x, s::Step) from the previous lecture\n# and define only the step function s for the Newton's method. However, sometimes it may be \n# better to write simple functions separately instead of using more complex machinery.\n# \n# ---\n# ### Solution:\n\n\n\n# ---\n# \n# ## Analyzing the solution\n\nusing LinearAlgebra\n\nsepar(x::Real, 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#+\n\ny_hat = \u03c3.(X*w)\ngrad = X'*(y_hat.-y) / size(X,1)\nnorm(grad)\n\n\n# ### Exercise:\n# Compute how many samples were correctly and incorrectly classified.\n# \n# ---\n# ### Solution:\n", "meta": {"hexsha": "201824b3e9a030bffeb91a13aa209d94422b3913", "size": 2186, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lecture_09/02-logistic.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/02-logistic.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/02-logistic.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.5360824742, "max_line_length": 92, "alphanum_fraction": 0.6724611162, "num_tokens": 604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430805473952, "lm_q2_score": 0.9173026494123034, "lm_q1q2_score": 0.8562385509043166}}
{"text": "# Helpful packages for working with images and factorizations\n# using Pkg; Pkg.add(\"Images\")\n# using Pkg; Pkg.add(\"ImageMagick\") # And this allows us to load JPEG-encoded images\nusing Images, LinearAlgebra, Interact\n\n# ------------------------------------------------------------------------------------------\n# ### Using a SVD to compress an image\n#\n# In this exercise, we'll use a singular value decomposition (SVD) to compress an image --\n# so that we can store an image without keeping around \"unnecessary\" information.\n#\n# To start, let's define a singular value decomposition. In a SVD, we take a matrix $A$ and\n# factorize it so that\n#\n# $$A = USV^T$$\n#\n# where matrices $U$ and $V$ are unitary and hold our singular vectors. Matrix $S$ is\n# diagonal and stores our singular values in decreasing order from top/left to bottom/right.\n#\n# In Julia, our images are stored as arrays, so we can think of `yellowbanana` as a matrix\n# ------------------------------------------------------------------------------------------\n\nfile = download(\"https://uploads6.wikiart.org/images/salvador-dali/the-persistence-of-memory-1931.jpg!Large.jpg\")\n\nimg = load(file)\n\nsize(img)\n\nimg[24,24] # Each element in the array is a color\n\ndump(img[24,24])\n\n# ------------------------------------------------------------------------------------------\n# We can extract each \"channel\" of red, green, and blue and view each independently:\n# ------------------------------------------------------------------------------------------\n\nchannels = Float64.(channelview(img))\nGray.(channels[1, :, :])\n\n# ------------------------------------------------------------------------------------------\n# That means we can take the SVD of this image. So, we can store this picture of a banana as\n# sets of singular vectors and singular values.\n#\n# **The reason this is important** is that we'll find that we do **not** need to keep track\n# of *all* the singular vectors and *all* the singular values to store an image that still\n# looks like a banana! This means we can choose to keep only the important information,\n# throw away the rest, and thereby \"compress\" the image.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# If we don't throw away any data, we get back what we started with:\n# ------------------------------------------------------------------------------------------\n\nU, S, V = svd(channels[1,:,:])\nGray.(U * Diagonal(S) * V')\n\n# ------------------------------------------------------------------------------------------\n# But of course we're not doing any compression here \u2014 the sizes of U, S, and V are bigger\n# than our original matrix! This is like the opposite of compression.  The key is that the\n# values are stored in decreasing order so we can start throwing things away.\n# ------------------------------------------------------------------------------------------\n\nsum(length.((U, S, V)))\n\nlength(img)\n\nGray.(U[:, 1:25] * Diagonal(S[1:25]) * V[:, 1:25]')\n\nsum(length.((U[:, 1:25], S[1:25], V[:, 1:25])))/length(img)\n\n# ------------------------------------------------------------------------------------------\n# Of course this is just one channel of the image. Let's put it all back together and see\n# how we can compress the different channels to find an acceptable compression level.\n# ------------------------------------------------------------------------------------------\n\nfunction rank_approx(M, k)\n    U, S, V = svd(M)\n    \n    M = U[:, 1:k] * Diagonal(S[1:k]) * V[:, 1:k]'\n    \n    M = min.(max.(M, 0.0), 1.)\nend\n\nn = 100\n@manipulate for k1 in 1:n, k2 in 1:n, k3 in 1:n\n    colorview(  RGB, \n                rank_approx(channels[1,:,:], k1),\n                rank_approx(channels[2,:,:], k2),\n                rank_approx(channels[3,:,:], k3)\n    )\nend\n\n# ------------------------------------------------------------------------------------------\n# **So how can we use a SVD to determine what information in an image is really important?**\n#\n# The singular values tell us!\n#\n# If we have matrices $U$, $S$, and $V$ from our image, we can rebuild that image with the\n# matrix product $USV^T$.\n#\n# Taking this matrix product is the same as adding together the outer products of each\n# corresponding pair of vectors from $U$ and $V$, scaled by a singular value ($\\sigma$) from\n# $S$. In other words, for a (100 x 100) pixel image,\n#\n# $$A_{image} = USV^T = \\sum_{i = 1}^{100} \\sigma_i \\mathbf{u_i}\\mathbf{v_i'} $$\n#\n# Every outer product $u_i * v_i'$ creates a (100 x 100) matrix. Here we're summing together\n# one hundred (100 x 100) matrices in order to create the original matrix $A_{image}$. The\n# matrices at the beginning of the series -- those that are scaled by **large** singular\n# values -- will be **much** more important in recreating the original matrix $A_{image}$.\n#\n# This means we can approximate $A_{image}$ as\n#\n# $$A_{image} \\approx \\sum_{i = 1}^{n} \\sigma_i \\mathbf{u_i}\\mathbf{v_i'}$$\n#\n# where $n < 100$.\n#\n#\n# #### Exercise\n#\n# Write a function called `compress_image`. Its input arguments should be an image and the\n# factor by which you want to compress the image. A compressed grayscale image should\n# display when `compress_image` is called.\n#\n# For example,\n#\n# ```julia\n# compress_image(\"images/104_100.jpg\", 33)\n# ```\n#\n# will return a compressed image of a grayscale banana built using 3 singular values. (This\n# image has 100 singular values, so use `fld(100, 33)` to determine how many singular values\n# to keep. `fld` performs \"floor\" division.)\n#\n# *Hints*:\n#\n# * Perform the SVD on the `channelview` of a grayscale image.\n# * In an empty input cell, execute `?svd` to find a function that wil perform an SVD for\n# you.\n# ------------------------------------------------------------------------------------------\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "fd9e744b9ebc1c720427313d41f4b07b2f8b7365", "size": 5894, "ext": "jl", "lang": "Julia", "max_stars_repo_path": ".nbexports/introductory-tutorials/intro-to-julia/long-version/050 Compressing an Image.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/intro-to-julia/long-version/050 Compressing an Image.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/intro-to-julia/long-version/050 Compressing an Image.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": 39.5570469799, "max_line_length": 113, "alphanum_fraction": 0.5359687818, "num_tokens": 1347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191297273498, "lm_q2_score": 0.8962513620489619, "lm_q1q2_score": 0.8562060712095662}}
{"text": "#function to calculate volume\nfunction sphere_vol(r)\n\n    return 4/3*pi*r^3\nend\n\nquadratic(a, sqr_term, b) = (-b + sqr_term) / 2a\n\n#quadratic funtion calculation\n\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)\n\n    r1, r2\nend\n\nvol = sphere_vol(3)\n\n@printf \"volume = %0.3f\\n\" vol \n#prints volume = 113.097\n\nquad1, quad2 = quadratic2(2.0, -2.0, -12.0)\nprintln(\"result 1: \", quad1)\n#> result 1: 3.0\nprintln(\"result 2: \", quad2)\n#> result 2: -2.0", "meta": {"hexsha": "79a0b51f0643e8803513881090925e12a8e2ea97", "size": 553, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Desktop/first_function.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": "Desktop/first_function.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": "Desktop/first_function.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": 19.0689655172, "max_line_length": 55, "alphanum_fraction": 0.6473779385, "num_tokens": 212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399060540358, "lm_q2_score": 0.8824278680004706, "lm_q1q2_score": 0.8561667317482397}}
{"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\n\nfunction nextPrime!(l)\n\tx = l[end]+2\n\twhile !isPrime(x)\n\t\tx += 2\n\tend\n\tpush!(l, x)\nend\n\nl = [2,3,5,7,11,13]\nwhile length(l) < 10001\n\tnextPrime!(l)\nend\nprintln(length(l))\nprintln(l[end])\n", "meta": {"hexsha": "310432b9cdb59825c2037acf889b2275ab43e63a", "size": 297, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "algo/su.7.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.7.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.7.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.5, "max_line_length": 36, "alphanum_fraction": 0.6296296296, "num_tokens": 112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9449947070591977, "lm_q2_score": 0.9059898248255075, "lm_q1q2_score": 0.8561555891095943}}
{"text": "# Julia program to find the sum of divisors of a number.\n\nfunction sum_of_divisors(num)\n    i = 1\n    sum = 0\n    while (i <= sqrt(num))\n        if num % i == 0 && i == sqrt(num)\n            sum = sum + i\n        elseif num % i == 0\n            sum = sum + i\n            sum = sum + (num \u00f7 i)\n        end\n        i = i + 1\n    end\n    return sum\nend\n\n\nprint(\"Enter the number: \")\nnum = readline()\nnum = parse(Int, num)\nsum = sum_of_divisors(num)\nprint(\"The Sum of the Divisors of the given number is $sum.\")\n\n\"\"\"\nTime Complexity - O(n^(0.5)), where 'n' given is the number\nSpace Complexity - O(1)\n\nSAMPLE INPUT AND OUTPUT\n\nSAMPLE I\n\nEnter the number: 256\nThe Sum of the Divisors of the given number is 511.\n\nSAMPLE II\n\nEnter the number: 5687\nThe Sum of the Divisors of the given number is 6384.\n\"\"\"\n", "meta": {"hexsha": "9f86d05ec846bb72046114799fca08105d99f259", "size": 799, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/math/sum_of_divisors.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/sum_of_divisors.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/sum_of_divisors.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.487804878, "max_line_length": 61, "alphanum_fraction": 0.5969962453, "num_tokens": 234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.96323053709097, "lm_q2_score": 0.8887587993853654, "lm_q1q2_score": 0.8560796156762911}}
{"text": "# Formulas used for Chapter 2 exercises\nyearly_compounded_interest(i, r, y) = (i * (1 + (r / 100)))^y\n\nfind_effective_rate(i, n) = (1 + i / n)^n - 1\n\n\"internal rate of return\"\nfunction irr(func1, func2, init, stop)\n    sol = Float64[]\n    \u03bb\u2096 = func1(init)\n    \u03bb\u2096\u208a\u2081 = \u03bb\u2096 - func1(\u03bb\u2096) / func2(\u03bb\u2096)\n    push!(sol, float(\u03bb\u2096))\n    if stop == 0\n        return [\u03bb\u2096]\n    end\n    push!(sol, float(\u03bb\u2096\u208a\u2081))\n    if stop == 1\n        return [\u03bb\u2096, \u03bb\u2096\u208a\u2081]\n    end\n    for k in range(2; stop=stop)\n        \u03bb\u2096 = \u03bb\u2096\u208a\u2081\n        \u03bb\u2096\u208a\u2081 = \u03bb\u2096 - func1(\u03bb\u2096) / func2(\u03bb\u2096)\n        push!(sol, float(\u03bb\u2096\u208a\u2081))\n    end\n    return sol\nend\n\n\"net present value\"\nnpv(inv, val, rate, year) = -inv + val / (1 + rate)^year\n\n\"annual equivalent rate\"\naer(r, n) = (1 + r / n)^n - 1\n\n\"continuously compounded interest\"\ncci(r) = exp(r) - 1\n\n\"present value\"\nfunction pv(p, r, n)\n    interest = 0.0\n    for i in range(0, n - 1; step=1)\n        interest += (1 + r)^-i\n    end\n    return p * interest\nend\n\n# From Lecture Notes\n\n\"present value\"\nfunction present_value(s, r)\n    return mapreduce((k, x) -> x / (1 + r)^k, +, 0:(length(s) - 1), s)\nend\n", "meta": {"hexsha": "6b10b20bf47eac99a7840694e26600896593df13", "size": 1090, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/interest.jl", "max_stars_repo_name": "jvaverka/Invest.jl", "max_stars_repo_head_hexsha": "5a1f0a5d03b84cf96dfc09772c9ad5feb8ce8c68", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/interest.jl", "max_issues_repo_name": "jvaverka/Invest.jl", "max_issues_repo_head_hexsha": "5a1f0a5d03b84cf96dfc09772c9ad5feb8ce8c68", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/interest.jl", "max_forks_repo_name": "jvaverka/Invest.jl", "max_forks_repo_head_hexsha": "5a1f0a5d03b84cf96dfc09772c9ad5feb8ce8c68", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.3725490196, "max_line_length": 70, "alphanum_fraction": 0.5614678899, "num_tokens": 436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551546097942, "lm_q2_score": 0.8872045862611166, "lm_q1q2_score": 0.8560239182474882}}
{"text": "\n\"\"\"If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.\nFind the sum of all the multiples of 3 or 5 below 1000.\"\"\"\n\nfunction sum_multiples_3_5(n::Int)\n    multiples3or5 = union(3:3:n-1 , 5:5:n-1)\n    return sum(multiples3or5)\nend\n\n@assert sum_multiples_3_5(10) ==23\n\n@show sum_multiples_3_5(1000)\n\n# Oneliner and faster\n@show sum([i for i in 1:999 if i%3==0 || i%5 ==0]);\n\n", "meta": {"hexsha": "ab617648ece9e0a9fbf25abdcbf3403b5479f001", "size": 451, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/P1_Multiples_3_or_5.jl", "max_stars_repo_name": "rojesh-shikhrakar/ProjectEuler.jl", "max_stars_repo_head_hexsha": "ee16f625e11d4076e4bff1b02d71913468fb3555", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/P1_Multiples_3_or_5.jl", "max_issues_repo_name": "rojesh-shikhrakar/ProjectEuler.jl", "max_issues_repo_head_hexsha": "ee16f625e11d4076e4bff1b02d71913468fb3555", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/P1_Multiples_3_or_5.jl", "max_forks_repo_name": "rojesh-shikhrakar/ProjectEuler.jl", "max_forks_repo_head_hexsha": "ee16f625e11d4076e4bff1b02d71913468fb3555", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5294117647, "max_line_length": 132, "alphanum_fraction": 0.6917960089, "num_tokens": 168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.934395157060208, "lm_q2_score": 0.9161096112990285, "lm_q1q2_score": 0.8560083841341218}}
{"text": "function getGrid(minongrid, maxongrid, GridPoints, method)\r\n\r\n#NB: This code borrows some code from Chris Carroll of John's Hopkins University\r\n#His website is here http://www.econ2.jhu.edu/people/ccarroll/ and his\r\n#notes on solving dynamic models are very good - they can be found\r\n#here: http://www.econ2.jhu.edu/people/ccarroll/SolvingMicroDSOPs.pdf\r\n\r\n\r\n#% ------------------------------------------------------------------------ \r\n# Explanation\r\n\r\n# We need to a grid from a to b. A basic approach could involve spacing out\r\n# the point equally. The following line of code would achieve this:\r\n#     grid= linspace(a, b, GridPoints);\r\n\r\n# If we want to space them out so that the growth rate of the distance\r\n# between spaces is equal we achieve this by spacing out the logs of grid \r\n# equally. We could achieve this by the following line of code:\r\n#     grid= exp(linspace(log(a), log(b), GridPoints));\r\n\r\n# This is problematic if a<=0. The approach taken here is to get a grid\r\n# from log(1) to log(b - a + 1), exponentiate and then subrtact 1\r\n# so that we have a grid from 0 to b-a. If we have add a to each point we\r\n# get the desired result - a log-spaced grid from a to b\r\n\r\n\r\n\r\nspan = maxongrid - minongrid;     # b - a                  \r\n\r\n\r\n\r\nif method==\"equalsteps\"\r\n    grid= linspace(min, span, GridPoints);\r\nelseif method== \"logsteps\"\r\n  loggrid = linspace(log(1), log(1+span), GridPoints);\r\n  grid = exp(loggrid)-1;\r\nelseif method==\"3logsteps\"\r\n  loggrid = linspace(log(1+log(1+log(1))), log(1+log(1+log(1+span))), GridPoints);\r\n  grid = exp(exp(exp(loggrid)-1)-1)-1;   \r\nelseif method==\"5logsteps\"\r\n  loggrid = linspace(log(1+log(1+log(1+log(1+log(1))))), log(1+log(1+log(1+log(1+log(1+span))))), GridPoints);\r\n  grid = exp(exp(exp(exp(exp(loggrid)-1)-1)-1)-1)-1;   \r\nelseif method==\"10logsteps\"\r\n  loggrid = linspace(log(1+log(1+log(1+log(1+log(1+log(1+log(1+log(1+log(1+log(1)))))))))), log(1+log(1+log(1+log(1+log(1+log(1+log(1+log(1+log(1+log(1+span)))))))))), GridPoints);\r\n  grid = exp(exp(exp(exp(exp(exp(exp(exp(exp(exp(loggrid)-1)-1)-1)-1)-1)-1)-1)-1)-1)-1;   \r\nelse\r\n    error(\"Error in getgrid. You have entered an invalid method for choosing the distance between grid points. Method must be one of equalsteps, logsteps, 3logsteps, 5logsteps or 10logsteps.\");\r\nend\r\n\r\n\r\ngrid = grid + minongrid*ones(Float64,GridPoints,1);\r\n\r\nreturn grid;\r\n\r\nend\r\n\r\n", "meta": {"hexsha": "f78be554c67f0444d10223f7dcd4fb063718b43f", "size": 2382, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "LifecycleCostaDias/v5_julia/code_gridsInputs/getGrid.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_gridsInputs/getGrid.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_gridsInputs/getGrid.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.7894736842, "max_line_length": 194, "alphanum_fraction": 0.6540722082, "num_tokens": 713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341987633821, "lm_q2_score": 0.8947894661025424, "lm_q1q2_score": 0.85598620396692}}
{"text": "import LinearAlgebra\nimport SparseArrays\n#using Images\nimport Images\nimport MAT\n\nLA = LinearAlgebra\nSA = SparseArrays\nImg = Images\n\n# Matrix\ndim = 4\nA = rand(dim,dim)\nAT = A'\nA2 = A*AT\n\n@show A[11] == A[1,2]\nb = rand(dim)\n# Solve for x where Ax = b\nx = A\\b\n@show LA.norm(A*x - b)\n\n@show typeof(A)\n@show typeof(b)\n@show typeof(rand(1,dim))\n@show typeof(AT)\n\n#A = [1 2;3 4]\nsizeof(A) # => byte count\nsizeof(AT)\nB = copy(AT)\nsizeof(B)\n\n# \\(x, y) => x^(-1) * y\n#x = \\(A,b) # => A^(-1)*b\n@show \\(3,6) # => 1/3 * 6\n@show 3\\6    # => 1/3 * 6\n\n1//3 + 1//2\n\n#A = sparse([1,2,4], [1,1,1], [1.0,1.0,1.0], 4, 2)\n#F = qr(A)\n\nluA = LA.lu(A)\n# LU = PA\nLA.norm(luA.L*luA.U - luA.P*A)\n\n# QR = A\nqrA = LA.qr(A)\nQ = qrA.Q\nR = qrA.R\nLA.norm(Q*R - A)\n\n# Skip Cholesky factorization\n\n# Skip Sparse Linear Algebra\n\n# Images as matrices\nX1 = Images.load(\"data/khiam-small.jpg\")\n# Gray scale\nXgray = Images.Gray.(X1)\n# Extract RGB values\nR = map(i -> X1[i].r, 1:length(X1))    # => Vector\nR2 = Float64.(reshape(R, size(X1)...)) # (80089,) => (283,283)\nG = map(i -> X1[i].g, 1:length(X1))\nG2 = Float64.(reshape(G, size(X1)...)) # (80089,) => (283,283)\nB = map(i -> X1[i].b, 1:length(X1))\nB2 = Float64.(reshape(B, size(X1)...))\n\nZ = zeros(size(G2)...)\nImages.RGB.(Z,G2,Z)\n\nXgrayvalues = Float64.(Xgray)\n# SVD: A = U*Sigma*V'\nusv =LA.svd(Xgrayvalues)\n# usv.U, S, V, Vt\nU = usv.U\nS = usv.S\nV = usv.V\nVt = usv.Vt\n\nLA.norm(U*LA.diagm(S)*Vt - Xgrayvalues)\n\n# Use the top 4 singular vectors/values to form a new image\ni = 1\nu1 = usv.U[:,i]\nv1 = usv.V[:,i]\nimg1 = usv.S[i]*u1*v1'\n\ni = 2\nu1 = usv.U[:,i]\nv1 = usv.V[:,i]\nimg1 += usv.S[i]*u1*v1'\n\ni = 3\nu1 = usv.U[:,i]\nv1 = usv.V[:,i]\nimg1 += usv.S[i]*u1*v1'\n\ni = 4\nu1 = usv.U[:,i]\nv1 = usv.V[:,i]\nimg1 += usv.S[i]*u1*v1'\n\nImages.Gray.(img1)\n\ni = 1:100\nu1 = usv.U[:,i]\ns1 = SA.spdiagm(0=>usv.S[i])\nv1 = usv.V[:,i]\nimg1 = u1 * s1 * v1'\nImg.Gray.(img1)\n# Close but not the same\nLA.norm(Xgrayvalues - img1)\n\n# Face recognition\nM = MAT.matread(\"data/face_recog_qr.mat\")\n# V2 contains 490 faces\n# each column is a face and need to reshape into 192,168\nV2 = M[\"V2\"]\nq = reshape(V2[:,200], 192, 168)\nImg.Gray.(q)\nb = q[:]\n\nA = V2[:,2:end]\nx = A\\b\nImg.Gray.(reshape(A*x, 192,168))\nLA.norm(A*x - b)\n\n# Skip\n", "meta": {"hexsha": "318496f69b207260c0fdd3af13d5f08a036d074c", "size": 2211, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "JuliaAcademy/DataScience/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": "JuliaAcademy/DataScience/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": "JuliaAcademy/DataScience/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": 16.8778625954, "max_line_length": 62, "alphanum_fraction": 0.579375848, "num_tokens": 944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.97364464791863, "lm_q2_score": 0.8791467706759584, "lm_q1q2_score": 0.855976548003594}}
{"text": "begin\n# Jump Search\n\n# Julia code to jump search x in arr[].\n# If x is present then return its location,\n# otherwise return -1\nimport Base:length,show,AbstractArray\narr = [ 0, 1, 1, 2, 3, 5, 8, 13, 21, \n    34, 55, 89, 144, 233, 377, 610 ] \nx = 610\nn = length(arr) \nfunction jumpsearch(arr::AbstractArray{},n,x)\n    \n    # Finding block size to be jumped \n    step = sqrt(n) \n      \n    # Finding the block where element is \n    # present (if it is present) \n    prev = 1\n    while arr[round(Int,floor(min(step, n)))] < x\n        prev = step \n        step += sqrt(n) \n        if prev >= n\n            return -1\n\t\tend\n\tend\n    # Doing a linear search for x in  \n    # block beginning with prev. \n    while arr[round(Int,floor(prev))] < x\n        prev += 1\n          \n        # If we reached next block or end  \n        # of array, element is not present. \n        if prev == min(step, n)\n            return -1\n\t\tend\n\tend\n    # If element is found \n    if arr[round(Int,floor(prev))] == x\n        return prev \n\tend  \n    return -1\nend\nglobal result=-1\n\nresult=jumpsearch(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": "4b1bcdb0566ca0afd80fed2750038bbf617ebc09", "size": 1293, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Searching_Algorithms/Jump_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/Jump_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/Jump_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": 23.5090909091, "max_line_length": 73, "alphanum_fraction": 0.5854601701, "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218434359675, "lm_q2_score": 0.9284087946129328, "lm_q1q2_score": 0.8559203473917195}}
{"text": "using DifferentialEquations\nusing Plots\nusing CPUTime\n\nfunction main()\n     a = 3.0  # \u30d1\u30e9\u30e1\u30fc\u30bf\n\n     \"\"\"\n     \u5fae\u5206\u65b9\u7a0b\u5f0f\n     \"\"\"\n     dy(y, t, a) = a * y\n     y0 = 1.0  # \u521d\u671f\u5024\u3092\u8a2d\u5b9a\n     tspan = (0.0, 1.0)  # \u89e3\u304f\u7bc4\u56f2\u3092\u8a2d\u5b9a\n\n     prob = ODEProblem(dy , y0 , tspan)\n     sol = solve(prob)  # \u30bd\u30eb\u30d0\u3067\u89e3\u304f\n\n     # plot\n     plot(\n          sol,\n          linewidth=5,\n          xaxis=\"x\",\n          yaxis=\"y(x)\",\n          label=\"solution\"\n     )\n\n     # savefig(\"solution_of_example_2.png\")  #  \u4fdd\u5b58\nend\n\n\n\"\"\"\n\u30aa\u30a4\u30e9\u30fc\u6cd5\n\n\u30fb\u53c2\u8003\u306b\u3057\u307e\u3057\u305f -> [url](https://twitter.com/genkuroki/status/1301832571131633665/photo/1)  \n\"\"\"\nfunction jisaku_solve_euler(dx, x\u2080, t_span, \u0394t)\n     t = range(t_span..., step = \u0394t)  # \u6642\u9593\u8ef8\n     x = Vector{typeof(x\u2080)}(undef, length(t))  # \u89e3\u3092\u683c\u7d0d\u3059\u308b1\u6b21\u5143\u914d\u5217\n\n     x[1] = x\u2080  # \u521d\u671f\u5024\n     for i in 1:length(x)-1\n          x[i+1] = x[i] + dx(t[i], x[i])\u0394t\n     end\n\n     t, x\nend\n\n\"\"\"\u30eb\u30f3\u30b2\u30af\u30c3\u30bf\u6cd5\uff084\u6b21\uff09\"\"\"\nfunction jisaku_solve_RungeKutta(dx, x\u2080, t_span, \u0394t)\n     t = range(t_span..., step = \u0394t)  # \u6642\u9593\u8ef8\n     x = Vector{typeof(x\u2080)}(undef, length(t))  # \u89e3\u3092\u683c\u7d0d\u3059\u308b1\u6b21\u5143\u914d\u5217\n\n     x[1] = x\u2080  # \u521d\u671f\u5024\n     for i in 1:length(x)-1\n          k\u2081 = dx(t[i], x[i])\n          k\u2082 = dx(t[i]+\u0394t/2, x[i]+k\u2081*\u0394t/2)\n          k\u2083 = dx(t[i]+\u0394t/2, x[i]+k\u2082*\u0394t/2)\n          k\u2084 = dx(t[i]+\u0394t, x[i]+k\u2083*\u0394t)\n          x[i+1] = x[i] + (k\u2081 + 2k\u2082 + 2k\u2083 +k\u2084)\u0394t/6\n     end\n\n     t, x\nend\n\n\nfunction main()\n     a = 3.0  # \u30d1\u30e9\u30e1\u30fc\u30bf\n     dx(t, x) = a * x  # \u5fae\u5206\u65b9\u7a0b\u5f0f\n\n     x\u2080 = 1.0\n     t_span = (0.0, 5.0)\n     \u0394t = 0.01\n     t, x = jisaku_solve_RungeKutta(dx, x\u2080, t_span, \u0394t)\n     plot(t, x, label=\"RungeKutta\")\n\n     t, x = jisaku_solve_euler(dx, x\u2080, t_span, \u0394t)\n     plot!(t, x, label=\"euler\")\n\n     x = exp.(a*t)\n     plot!(t, x, label=\"exact sol exp(at)\")\nend", "meta": {"hexsha": "e2163a6f8b7d5526565bddc87c225d960f09c835", "size": 1679, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example_jl/example_2.jl", "max_stars_repo_name": "YoshimitsuMatsutaIe/ans_2021", "max_stars_repo_head_hexsha": "a04cd9b9541583aaa8a6dc5ece323ae1cf706c3b", "max_stars_repo_licenses": ["MIT"], "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/example_2.jl", "max_issues_repo_name": "YoshimitsuMatsutaIe/ans_2021", "max_issues_repo_head_hexsha": "a04cd9b9541583aaa8a6dc5ece323ae1cf706c3b", "max_issues_repo_licenses": ["MIT"], "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/example_2.jl", "max_forks_repo_name": "YoshimitsuMatsutaIe/ans_2021", "max_forks_repo_head_hexsha": "a04cd9b9541583aaa8a6dc5ece323ae1cf706c3b", "max_forks_repo_licenses": ["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.7283950617, "max_line_length": 85, "alphanum_fraction": 0.5014889815, "num_tokens": 766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172587090974, "lm_q2_score": 0.90192067455231, "lm_q1q2_score": 0.8558480940692379}}
{"text": "\"\"\"Julia program to implement Subset Sum problem.\nGiven a set, we have to find if there exist a subset with the given sum.\nThe given problem can be solved using Dynamic Programming.\n\"\"\"\n\nfunction subset_sum(set, n, S)\n\n    # Initialize the entire 2D matrix with 0 as value, signifying false.\n    dp = zeros(Int, n + 1, S + 1)\n\n    # When the sum is zero, the answer is always true, by forming an empty subset.\n    for i in 1:n + 1\n        dp[i,1] = 1\n    end\n\n    # When the given set is empty and the required sum is not zero, then such a subset cannot e formed.\n    for i in 1:S + 1\n        dp[1,i] = 0\n    end\n\n    \"\"\"Tabulating the dp array in Bottom-Up manner. In such a way that each cell of the dp[i, j]\n       array contains whether a subset of sum j can be formed with elements in the given set till i\"\"\"\n    for i in 2:n + 1\n        for j in 2:S + 1\n            if j < (set[i - 1] + 1)\n                dp[i,j] = dp[(i - 1),j]\n            else\n                if (dp[(i - 1),j] == 1)\n                    dp[i, j] = 1\n                elseif (dp[(i - 1),(j - set[i - 1])] == 1)\n                    dp[i, j] = 1\n                else\n                    dp[i, j] = 0\n                end\n            end\n        end\n    end\n    return dp[n + 1,S + 1]\nend\n\n\nprint(\"What is the size of the set? \")\nn = readline()\nn = parse(Int, n)\narr = Int[]\nif (n > 0)\n    print(\"Enter the numbers: \")\n    arr = [parse(Int, num) for num in split(readline())]\nelse\n    print(\"The set is Empty!!!\")\n    exit()\nend\nprint(\"Enter the sum? \")\nS = readline()\nS = parse(Int, S)\nres = subset_sum(arr, n, S)\nif (res == 1)\n    print(\"A subset with the given sum is present in the array.\")\nelse\n    print(\"A subset with the given sum is not present in the array.\")\nend\n\n\n\"\"\"\nTime Complexity - O(n * S), where 'n' is the size of the array and 'S is the Sum\nSpace Complexity - O(n * S)\n\nSAMPLE INPUT AND OUTPUT\n\nSAMPLE I\n\nWhat is the size of the set? 3\nEnter the numbers: 3 2 1\nEnter the sum? 55\nA subset with the given sum is not present in the array.\n\nSAMPLE II\n\nWhat is the size of the set? 4\nEnter the numbers: 10 20 30 40\nEnter the sum? 60\nA subset with the given sum is present in the array.\n\"\"\"\n", "meta": {"hexsha": "1356ecf300a13578899b5de0447bcc4c4d3dd646", "size": 2175, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/dp/subset_sum.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/subset_sum.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/subset_sum.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": 25.8928571429, "max_line_length": 103, "alphanum_fraction": 0.5783908046, "num_tokens": 649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012762876287, "lm_q2_score": 0.9046505299595162, "lm_q1q2_score": 0.8556196258299901}}
{"text": "export Linear\n\n\"\"\"\n**Linear function**\n\n    Linear(c)\n\nReturns the function\n```math\nf(x) = \\\\langle c, x \\\\rangle.\n```\n\"\"\"\nstruct Linear{R <: Real, A <: AbstractArray{R}} <: ProximableFunction\n    c::A\nend\n\nis_separable(f::Linear) = true\nis_convex(f::Linear) = true\nis_smooth(f::Linear) = true\n\nfunction (f::Linear{R})(x::AbstractArray{R}) where R\n    return dot(f.c, x)\nend\n\nfunction prox!(y::AbstractArray{R}, f::Linear{R}, x::AbstractArray{R}, gamma::Union{R, AbstractArray{R}}=1.0) where R\n    y .= x .- gamma.*(f.c)\n    fy = dot(f.c, y)\n    return fy\nend\n\nfunction gradient!(y::AbstractArray{R}, f::Linear{R}, x::AbstractArray{R}) where R\n    y .= f.c\n    return dot(f.c, x)\nend\n\nfun_name(f::Linear) = \"Linear function\"\nfun_expr(f::Linear) = \"x \u21a6 c'x\"\n\nfunction prox_naive(f::Linear, x, gamma)\n    y = x - gamma.*(f.c)\n    fy = dot(f.c, y)\n    return y, fy\nend\n", "meta": {"hexsha": "30128279a15e4a9706ac940b1550ab0fc183ec3c", "size": 866, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/linear.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/linear.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/linear.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": 19.6818181818, "max_line_length": 117, "alphanum_fraction": 0.6200923788, "num_tokens": 294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012640659995, "lm_q2_score": 0.9046505408849362, "lm_q1q2_score": 0.8556196251069629}}
{"text": "# Algorithm 2.5\n# False Position method for finding roots\n# Same as the secant method, but it checks\n# if the roots are bracketed between successive\n# iterations.\n\nfunction false_approx(f, p0, p1, tolerance, maxIter)\n\tfor i \u2208 2:maxIter\n\t\tq0 = f(p0)\n\t\tq1 = f(p1)\n\t\tp = p1 - q1*(p1 - p0)/(q1 - q0)\n\t\tif abs(p - p1) < tolerance\n\t\t\treturn p\n\t\tend\n\t\tq = f(p)\n\t\tif q \u22c5 q1 < 0\n\t\t\tp0 = p1\n\t\t\tq0 = q1\n\t\tend\n\t\tp1 = p\n\t\tq1 = q\n\tend\n\tthrow(ArgumentError(\"Method failed\"))\nend\n\nprintln(false_approx(x->(cos(x) - x), 0.5, \u03c0/4, 0.1, 100))\n", "meta": {"hexsha": "3f237cf1898bfb79e904006c39aa20cfb8d321bb", "size": 524, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "chapter2/falsepositionroot.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/falsepositionroot.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/falsepositionroot.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.4074074074, "max_line_length": 58, "alphanum_fraction": 0.6202290076, "num_tokens": 207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9609517072737737, "lm_q2_score": 0.8902942224835226, "lm_q1q2_score": 0.8555297530715179}}
{"text": "\"\"\"\n    median(nums)\n\nFinds median of a vector of numbers\n\n## Example\n\n```julia\nmedian([2,1,3,4])                   # returns 2.5\nmedian([2, 70, 6, 50, 20, 8, 4])    # returns 8\nmedian([0])                         # returns 0\n```\n\nContributed By:- [Ashwani Rathee](https://github.com/ashwani-rathee) and [Rratic](https://github.com/Rratic)\n\"\"\"\nfunction median(nums::Vector{T}) where {T<:Number}\n    sorted = sort(nums)\n    len = length(sorted)\n    mid_index = div(len, 2)\n    return if len % 2 == 0\n        (sorted[mid_index+1] + sorted[mid_index]) / 2\n    else\n        sorted[mid_index+1]\n    end\nend\n", "meta": {"hexsha": "d40c95ed43292e3bba79cb627ff9791377008cd3", "size": 602, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/average_median.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/math/average_median.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/math/average_median.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": 23.1538461538, "max_line_length": 108, "alphanum_fraction": 0.5714285714, "num_tokens": 196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768588653856, "lm_q2_score": 0.9059898108646848, "lm_q1q2_score": 0.8554146137862628}}
{"text": "\"\"\"\nrw_test(p; method = \"VR\", m = 1)\n\nTEST OF RANDOM WALK\n\nRandom walk with uncorrelated increments (RW3) is the weakest form version of the random walk.\nThe other versions are random walk with iid increments (RW1) and random walk with independent increments (RW2).\n\n\nBox and Pierce (1970) test of RW(3): the autocorrelation of increments at all leads and lags should be zero under random walk.\nBy summing the squared autocorrelation, the Box-Pierce Q-statistics is designed to detect departures from zero autocorrelations in either directions and at all lags\n\nLjung and Box (1978) test of RW(3): the Ljung-Box Q-statistics provides the finite-sample correction which yields a better fit to the chi-squared distribution for small sample size.\n\nVariance ratio test of RW(1): the variance of random walk increments must be a linear function of the time interval under random walk. The variance ratios statistics tests such property.\n\nINPUT\n`p': a T x 1 vector of asset prices\n`method': method used to test random walk hypthesis with uncorrelated increments:\n        - BP: the Box and Pierce (1970) statistics\n        - LB: the Ljung and Box (1978) statistics\n        - VR: variance ratio test\n`m': number of autocorrelation lags used for test\n\nOUTPUT\n`test_statistics': test statistics of the random walk test\n`pvalue': p-value of the test statistics\n\n\"\"\"\n\nfunction rw_test(p, method = \"VR\", m = 1)\n    r = diff(log.(p), dims = 1)\n    T = length(r); # length of the time series\n\n    if method == \"BP\" # Box and Pierce (1970) test of RW(3)\n        Qm = 0.0;\n        for k = 1:m\n            rho_k = autocor(r, [k]; demean = false);\n            Qm = Qm .+ rho_k.^2;\n        end\n        test_statistics = T * Qm;\n        pvalue = 1.0 .- cdf.(Chisq(m), test_statistics);\n    elseif method == \"LB\" # Ljung and Box (1978) test of RW(3)\n        Qm = 0.0;\n        for k = 1:m\n            rho_k = autocor(r, [k]; demean = false);\n            Qm = Qm .+ rho_k.^2;\n        end\n        test_statistics = T * (T + 2) / (T - m) * Qm;\n        pvalue = 1.0 .- cdf.(Chisq(m), test_statistics);\n    elseif method == \"VR\" # Variance ratio test of RW(1)\n        VR = 1.0;\n        for k = 1:m-1\n            rho_k = autocor(r, [k]; demean = false);\n            VR = VR .+ 2 .* (1 .- k / m) .* rho_k;\n        end\n        test_statistics = sqrt(T * m) * (VR .- 1.0) ./ sqrt(2.0 .* (m - 1));\n        pvalue = 1.0 .- cdf.(Normal(0.0, 1.0), test_statistics);\n    end\n\n    return (test_statistics, pvalue)\nend\n", "meta": {"hexsha": "3938e6fbfc3bcbdf35f1889626626b849642c9a6", "size": 2479, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/rw_test.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/rw_test.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/rw_test.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": 39.3492063492, "max_line_length": 186, "alphanum_fraction": 0.6325131101, "num_tokens": 725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542852576265, "lm_q2_score": 0.8918110346549902, "lm_q1q2_score": 0.8553843755293715}}
{"text": "\"\"\"\nJulia program to check if a number is a Strong number or not.\nStrong Number is a number whose sum of the factorial of digits\nis equal to the number itself.\n\"\"\"\n\n# Helper function to return the factorial of a number\nfunction factorial(num)\n    if ( num == 1 || num == 0 )\n        return 1\n    end\n    return num * factorial( num - 1)\nend\n\n\"\"\" Extract each digit of the given number and calculate the sum of the\n    factorial of each digit present in the given number\"\"\"\nfunction strong_number(num)\n    temp = num\n    sum = 0\n    while(temp > 0)\n        rem = temp % 10\n        sum = sum + factorial(rem)\n        temp = temp \u00f7 10\n    end\n    return sum\nend\n\n\n\nprint(\"Enter the number: \")\nnum = readline()\nnum = parse(Int, num)\nsum = strong_number(num)\nif sum == num\n    println(\"The given number $num is a Strong Number.\")\nelse\n    println(\"The given number $num is not a Strong Number.\")\nend\n\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: 3124\nThe given number 3124 is not a Strong Number.\n\nSAMPLE 2\nEnter the number: 145\nThe given number 145 is a Strong Number.\n\"\"\"\n", "meta": {"hexsha": "6faa90ceae454e3008fd21fd50fb96a46896e0a3", "size": 1165, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/math/strong_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/strong_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/strong_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": 21.1818181818, "max_line_length": 71, "alphanum_fraction": 0.6703862661, "num_tokens": 306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102571131693, "lm_q2_score": 0.8840392924390587, "lm_q1q2_score": 0.855228679196614}}
{"text": "### A Pluto.jl notebook ###\n# v0.16.0\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 cc106912-0b14-4981-a67b-580dda8a56ed\nbegin\n\tusing Pkg\n\tcd(joinpath(dirname(@__FILE__),\"..\"))\n    Pkg.activate(pwd())\n    using Distributions, LinearAlgebra, Plots, InteractiveUtils\nend\n\n# \u2554\u2550\u2561 235e2200-fce9-11ea-0696-d36cddaa843e\nmd\"\"\"\n# Phase transition in networks\n## Generalities - Networks\n\nA network is a set of objects (called nodes or vertices) that are connected together. The connections between the nodes are called edges or links. In mathematics, networks are often referred to as [graphs](https://en.wikipedia.org/wiki/Graph_(discrete_mathematics)). \n\nIn the following, we will only consider undirected networks i.e. if node $i$ is connected to node $j$, then node $j$ is automatically connected to node $i$ (as is the case with Facebook friendships). For unweighted networks of $N$ nodes, the network structure can be represented by an $N \\times N$ adjacency matrix $A$:\n\n```math\na_{i,j} = \\left\\{\n                \\begin{array}{ll}\n                  1 & \\text{if there is an edge from node $i$ to node $j$}\\\\\n                  0 & \\text{otherwise}\\\\\n                \\end{array}\n                \\right.\n```\nThe degree of a node $i$ is the number of connections it has. In terms of the adjacency matrix\n$A$, the degree of node $i$ is the sum of the i$^{\\text{th}}$ row of $A$:\n$$k_i = \\sum_{j=1}^{N}a_{i,j}$$\n\nThe average node degree $\\langle k \\rangle$ is then given by: $$\\langle k \\rangle = \\sum_{i=1}^{N}k_{i}$$\n\n\n## Erd\u00f6s-R\u00e9nyi random graph model\nOne of the simplest graph models is the Erd\u00f6s-R\u00e9nyi random graph model, denoted by $\\mathcal{G}(N,p)$ with $N$ being the amount of nodes and $p$ being the probability that a link exists between two nodes. Self-loops are excluded. The value of $p$ is typically small (this is to avoid that the average degree $\\langle k \\rangle$ depends on $N$, cf. specialised literature for more details). When studying random graph model models, a major aim is to predict the average behaviour of certain network metrics and, if possible, their variance.\n\n\n\nThe Erd\u00f6s-R\u00e9nyi random graph  exhibits a phase transition. Let us consider the size (i.e., number of nodes) of the largest connected component in the network as a function of the mean degree \u27e8k\u27e9. When \u27e8k\u27e9 = 0, the network is trivially composed of N disconnected nodes. In the other extreme of \u27e8k\u27e9 = N \u2212 1, each node pair is adjacent such that the network is trivially connected. Between the two extremes, the network does not change smoothly in terms of the largest component size. Instead, a giant component, i.e., a component whose size is the largest and proportional to N, suddenly appears as \u27e8k\u27e9 increases, marking a phase transition. The goal of this application is to determine this value by simulation.\n\n## Problem solution\nWe split the problem in a series of subproblems:\n* generating a random graph\n* determine the average degree\n* identifying the size of the largest connected component\n* visualising the result\n* determine the critical value\n\n\"\"\"\n\n# \u2554\u2550\u2561 976bb1e0-07c9-11eb-2a4f-fb7aac69f8ec\nbegin\n\tfunction gengraph(N::Int, p::Float64)\n\t\td = Bernoulli(p) # define the distribution\n\t\tA = rand(d, N, N)\n\t\t# set main diagonal to 0\n\t\tA[diagind(A)] = zeros(Int,N)\n\t\treturn LinearAlgebra.Symmetric(A)\n\tend\n\t\n\tfunction avgdegree(A)\n\t\treturn mean(sum(A, dims=1))\n\tend\n\t\n\t\"\"\"\n\t\tneighbors(A, i)\n\t\n\tD\u00e9termine les voisins du noeud i dans le graph repr\u00e9sent\u00e9 par A\n\t\"\"\"\n\tfunction neighbors(A, i)\n\t\tfindall(x -> isequal(x, 1), @view A[i,:])\n\tend\n\t\n\tfunction components(A)\n\t\tN = size(A,1) # network size\n\t\tvisited = Dict(i => false for i in 1:N)\n\t\tcomps = []\n\t\tfor n in 1:N\n\t\t\tif !visited[n]\n\t\t\t\tpush!(comps,dig(A, n, visited))\n\t\t\t\tend\n\t\tend\n\n\t\treturn maximum(length,comps) / N\n\tend\n\t\n\tfunction dig(A, n, visited, comp=[])\n\t\tvisited[n] = true\n\t\tpush!(comp, n)\n\t\tfor neigbor in neighbors(A, n)\n\t\t\tif !visited[neigbor]\n\t\t\t\tdig(A, neigbor, visited, comp)\n\t\t\tend\n\t\tend\n\t\treturn comp\n\tend\n\t\n\tfunction sim(N::Int, p::Float64)\n\t\tA = gengraph(N,p)\n\t\treturn components(A), avgdegree(A)\n\tend\nend\n\n# \u2554\u2550\u2561 42f5cca6-07d1-11eb-3169-cd3650c42081\nN = 1000\n\n# \u2554\u2550\u2561 a060dc62-07cb-11eb-2aaa-7190bde5dc36\n# simulation part (range of probabilities, 10 simulations for each probability)\nlet N = N\n\tP = range(5e-5, 3e-3, length=20)\n\trat_comp = Array{Float64, 1}()\n\tk_moy = Array{Float64, 1}()\n\tfor p in P\n\t\tfor _ in 1:10\n\t\t\tres = sim(N,p)\n\t\t\tpush!(rat_comp, res[1])\n\t\t\tpush!(k_moy, res[2])\n\t\tend\n\tend\n\tscatter(k_moy, rat_comp, ylims=(0,1), label=\"\", xlabel=\"<k>\", ylabel=\"N_largest_comp / N\")\nend\n\n# \u2554\u2550\u2561 1f0d3e38-402b-4d82-a041-c623c5d531b3\nmd\"\"\"\n# Test from previous years\n* ants foraging (cf. \"./Exercises/data/test2019.pdf\")\n* housing evolution (cf. \"./Exercises/data/test2020.pdf\")\n\n\"\"\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u2560\u2550cc106912-0b14-4981-a67b-580dda8a56ed\n# \u255f\u2500235e2200-fce9-11ea-0696-d36cddaa843e\n# \u2560\u2550976bb1e0-07c9-11eb-2a4f-fb7aac69f8ec\n# \u2560\u255042f5cca6-07d1-11eb-3169-cd3650c42081\n# \u2560\u2550a060dc62-07cb-11eb-2aaa-7190bde5dc36\n# \u255f\u25001f0d3e38-402b-4d82-a041-c623c5d531b3\n", "meta": {"hexsha": "28d36c9d6f583af83a1a40abc0d5dfeb20810cb1", "size": 5017, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Exercises/PS03 - Phase transitions.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/PS03 - Phase transitions.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/PS03 - Phase transitions.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": 35.0839160839, "max_line_length": 710, "alphanum_fraction": 0.7008172214, "num_tokens": 1601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9496693645535723, "lm_q2_score": 0.9005297941266013, "lm_q1q2_score": 0.8552055573497688}}
{"text": "# # Poisson Equation\n#\n# We want to solve the [poisson equation](https://en.wikipedia.org/wiki/Poisson_equation) on the unit interval. It is given by\n# `\u0394u = f` with boundary conditions `u(0) = a` and `u(1) = b`\n# First of all let us choose some values for the parameters and remark, that there is an exact solution:\nf = 1.0\na = -1.0\nb = 2.0\n\nu_analytic(x) = f/2*x^2 + (b-a-f/2) * x + a\n\n# We would like to recompute this solution numerically\nusing DiffEqOperators\n\nnknots = 10\nh = 1.0/(nknots+1)\nord_deriv = 2\nord_approx = 2\n\n\u0394 = CenteredDifference(ord_deriv, ord_approx, h, nknots)\nbc = DirichletBC(a, b)\n\n# Before solving the equation, lets take a look at \u0394 and bc:\n# display(Array(\u0394))\n# display(bc*zeros(nknots))\n# We see that `\u0394` is a (lazy) matrix with the laplace stencil extended over the boundaries.\n# And `bc` acts by padding the values just outside the boundaries.\n\nu = (\u0394*bc) \\ fill(f, nknots)\nknots = range(h, step=h, length=nknots)\n\n# Since we used a second order approximation and the analytic solution itself was a second order\n# polynomial, we expect that they are equal up to rounding errors:\nusing Test\n@test u \u2248 u_analytic.(knots)\n", "meta": {"hexsha": "c711e7693c2a7992fa9944321ee3e9bb4cd73f29", "size": 1151, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/poisson.jl", "max_stars_repo_name": "FuZhiyu/DiffEqOperators.jl", "max_stars_repo_head_hexsha": "a55b696ec6f4fe8b0307a2dcfec06665a382a7d2", "max_stars_repo_licenses": ["MIT"], "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/poisson.jl", "max_issues_repo_name": "FuZhiyu/DiffEqOperators.jl", "max_issues_repo_head_hexsha": "a55b696ec6f4fe8b0307a2dcfec06665a382a7d2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/poisson.jl", "max_forks_repo_name": "FuZhiyu/DiffEqOperators.jl", "max_forks_repo_head_hexsha": "a55b696ec6f4fe8b0307a2dcfec06665a382a7d2", "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.9722222222, "max_line_length": 126, "alphanum_fraction": 0.7158992181, "num_tokens": 365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422269175634, "lm_q2_score": 0.8991213718636754, "lm_q1q2_score": 0.8551923039035908}}
{"text": "using NewtonsMethod\nusing Test\n\n@testset \"NewtonsMethod.jl\" begin\n\n    # Define some functions to be tested\n\n    # a. root = 1.0\n    f(x) = (x - 1)^3\n    df(x) = 3*(x - 1)^2\n\n    # b. root = 0.6\n    g(x) = (5*x - 3)^2\n    dg(x) = 10*(5*x - 3)\n\n    # c. no root (root = nothing)\n    h(x) = 2 + x^2\n    dh(x) = 2*x\n\n    # 1. Test function f(x)\n    @test NewtonsMethod.newtonroot(f, df)[1] \u2248 1.0\n    @test NewtonsMethod.newtonroot(f)[1] \u2248 1.0\n\n    # 2. Test function g(x)\n    @test NewtonsMethod.newtonroot(g, dg)[1] \u2248 0.6\n    @test NewtonsMethod.newtonroot(g)[1] \u2248 0.6\n\n    # 3. Test using BigFloat precision instead of Float\n    @test BigFloat(NewtonsMethod.newtonroot(f, df)[1]) \u2248 1.0\n    @test BigFloat(NewtonsMethod.newtonroot(f)[1]) \u2248 1.0\n\n    x0 = BigFloat(0.3)\n    @test NewtonsMethod.newtonroot(f, df; iv = x0)[1] \u2248 1.0\n    @test NewtonsMethod.newtonroot(f; iv = x0)[1] \u2248 1.0\n\n    # 4. Test non-convergence of h(x)\n    @test NewtonsMethod.newtonroot(h, dh)[1] === nothing\n    @test NewtonsMethod.newtonroot(h)[1] === nothing\n\n    # 5. Test maxiter\n    # From PS1, root of f(x) found in \u2248 20 iterations\n    @test NewtonsMethod.newtonroot(f, df; maxiter = 1)[1] === nothing\n    @test NewtonsMethod.newtonroot(f; maxiter = 1)[1] === nothing\n    @test NewtonsMethod.newtonroot(f, df; maxiter = 200)[1] \u2248 1.0\n    @test NewtonsMethod.newtonroot(f; maxiter = 200)[1] \u2248 1.0\n\n    # 6. Test tolerance\n    @test !(NewtonsMethod.newtonroot(f, df; tol = 0.1)[1] \u2248 1.0)\n    @test !(NewtonsMethod.newtonroot(f; tol = 0.1)[1] \u2248 1.0)\n\n    # 7. Test initial value\n    @test NewtonsMethod.newtonroot(f, df; iv = 0.5)[1] \u2248 1.0\n    @test NewtonsMethod.newtonroot(f; iv = 0.5)[1] \u2248 1.0\n\n    # 8. Break a test\n    # @test NewtonsMethod.newtonroot(f, df)[1] \u2248 0.2\n    # @test NewtonsMethod.newtonroot(f)[1] \u2248 0.2\n\n\nend\n", "meta": {"hexsha": "976371d70812111ff446853f5065f98524c99568", "size": 1801, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "loforteg/NewtonsMethod", "max_stars_repo_head_hexsha": "64d2988fb53c3124f088df1e68bb567a728499c8", "max_stars_repo_licenses": ["MIT"], "max_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": "loforteg/NewtonsMethod", "max_issues_repo_head_hexsha": "64d2988fb53c3124f088df1e68bb567a728499c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-10-20T00:47:34.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-22T00:48:08.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "loforteg/NewtonsMethod.jl", "max_forks_repo_head_hexsha": "64d2988fb53c3124f088df1e68bb567a728499c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5245901639, "max_line_length": 69, "alphanum_fraction": 0.6029983343, "num_tokens": 726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107878954106, "lm_q2_score": 0.9124361527383703, "lm_q1q2_score": 0.8551450056121852}}
{"text": "# ------------------------------------------------------------------------------------------\n# # Entropies & Dimensions\n#\n#\n# Topics:\n# * Entropies from **DynamicalSystems.jl**\n# * Generalized Dimension\n# * Automated dimension estimation!\n# * Other related concepts\n# * Docstrings\n#\n# ---\n#\n# # Generalized Entropy\n#\n# * In the study of dynamical systems there are many quantities that identify as \"entropy\".\n# * These quantities are not the more commonly known [thermodynamic\n# ones](https://en.wikipedia.org/wiki/Entropy), used in Statistical Physics.\n# * Rather, they are more like the entropies of [information\n# theory](https://en.wikipedia.org/wiki/Entropy_(information_theory), which represent\n# information contained within a dataset.\n# * In general, the more \"uncertain\" or \"random\" the dataset is, the larger its entropy will\n# be. On the other hand, the lower the entropy, the more \"predictable\" the dataset becomes.\n#\n#\n# Let $p$ be an array of probabilities (such that it sums to 1). Then the generalized\n# entropy is defined as\n#\n# $$\n# R_\\alpha(p) = \\frac{1}{1-\\alpha}\\log\\left(\\sum_i p[i]^\\alpha\\right)\n# $$\n#\n# and is also called [R\u00e9nyi entropy](https://en.wikipedia.org/wiki/R%C3%A9nyi_entropy).\n# Other entropies, like e.g. the [Shannon\n# entropy](https://en.wikipedia.org/wiki/Entropy_(information_theory) are generalized by it,\n# since for $\\alpha = 1$, the R\u00e9nyi entropy becomes the Shannon entropy,\n#\n# $$\n# R_1(p) = -\\left(\\sum_i p[i] \\log (p[i]) \\right)\n# $$\n#\n# The R\u00e9nyi entropy can be computed for a specific dataset, given $p$. But how does one get\n# $p$?\n# 1. $p$ represents the probability that a point of a dataset falls into a specific \"bin\".\n# 2. It is nothing more than the (normalized) histogram of the dataset!\n# ------------------------------------------------------------------------------------------\n\nusing DynamicalSystems\n\n# ------------------------------------------------------------------------------------------\n# Let's generate a dataset so that we can practice calculating entropies.\n# ------------------------------------------------------------------------------------------\n\nN = 100000\nrandomdata = Dataset(rand(N,3))\n\n# ------------------------------------------------------------------------------------------\n# ---\n#\n# ```julia\n# genentropy(\u03b1, \u03b5, dataset::AbstractDataset; base = e)\n# ```\n# * This function calculates the generalized entropy of order `\u03b1`.\n# * It first calculates the probability array $p$.\n# * The \"histogram\" is created by partitioning the `dataset` into boxes of size `\u03b5`.\n# \n# ------------------------------------------------------------------------------------------\n\ngenentropy(2, 0.1, randomdata)\n\ngenentropy(2, 0.01, randomdata)\n\ngenentropy(2, 0.001, randomdata)\n\ngenentropy(2, 0.0001, randomdata)\n\n# ------------------------------------------------------------------------------------------\n# Note that the output of `genentropy` changed with changing $\\varepsilon$ until we hit\n# $\\varepsilon = 0.001$.\n#\n# At this point the value for the entropy has already saturated. There's no use in\n# partitioning the dataset in smaller boxes.\n#\n# ---\n#\n# Now let's calculate the entropy of a coin toss!\n#\n# First, let's create an array, `y`, that stores the results of coin tosses as `0`s or `1`s\n# for `1000000` tosses.\n# ------------------------------------------------------------------------------------------\n\ny = Float64.(rand(Bool, 1000000))\n\nsh = genentropy(1, 0.1, y) # Renyi entropy with \u03b1 = 1 is the Shannon entropy\n\n# ------------------------------------------------------------------------------------------\n# The above number should be log(2) [by\n# definition](https://en.wikipedia.org/wiki/Shannon_(unit)\n# ------------------------------------------------------------------------------------------\n\nisapprox(sh, log(2), rtol = 1e-4)\n\n# ------------------------------------------------------------------------------------------\n# `genentropy` is conveniently used with `trajectory` outputs.\n#\n# Here we create a trajectory for a towel map,\n# ------------------------------------------------------------------------------------------\n\ntowel = Systems.towel()\ntr = trajectory(towel, N-1);\nsummary(tr)\n\n# ------------------------------------------------------------------------------------------\n# and calculate its entropy:\n# ------------------------------------------------------------------------------------------\n\ngenentropy(1, 0.01, tr) # The result is with log base-e !\n\n# ------------------------------------------------------------------------------------------\n# Let's also compare the entropy of the above dataset (a trajectory of the towel map) with\n# that of a random dataset:\n# ------------------------------------------------------------------------------------------\n\ngenentropy(1, 0.01, randomdata)\n\n# ------------------------------------------------------------------------------------------\n# * As expected, the entropy of the random dataset is higher.\n#\n# ---\n#\n# How much time does the computation take?\n# ------------------------------------------------------------------------------------------\n\nusing BenchmarkTools\n@btime genentropy(1, 0.01, $tr);\n\n# ------------------------------------------------------------------------------------------\n# ## Specialized histogram\n# * Partitioning the dataset (i.e. generating a \"histogram\") is in general a costly\n# operation that depends exponentially on the number of dimensions.\n# * In this specific application however, we can tremendously reduce the memory allocation\n# and time spent!\n#\n# Let's get the array of probabilities $p$ for size \u03b5 where `tr` is the trajectory of the\n# towel map\n# ------------------------------------------------------------------------------------------\n\n\u03b5 = 0.01\np = non0hist(\u03b5, tr)\n\n# ------------------------------------------------------------------------------------------\n# Here's a sanity check, showing our probabilities should sum to roughly `1`.\n# ------------------------------------------------------------------------------------------\n\nsum(p)\n\n# ------------------------------------------------------------------------------------------\n# How long does generating the histogram take?\n# ------------------------------------------------------------------------------------------\n\n@btime non0hist($\u03b5, $tr);\n\n# ------------------------------------------------------------------------------------------\n# How long does this take if we create 9-dimensional data and compare again?\n# ------------------------------------------------------------------------------------------\n\nnine = Dataset(rand(N, 9))\n@btime non0hist($\u03b5, $nine);\n\n# ------------------------------------------------------------------------------------------\n# * We went from dimension 3 to dimension 9 but the time roughly only tripled\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# # Attractor Dimension\n# 1. There are numerous methods that one can use to calculate a so-called \"dimension\" of a\n# dataset, like for example the [Fractal\n# dimension](https://en.wikipedia.org/wiki/Fractal_dimension).\n#\n# 2. Most of the time these dimensions indicate some kind of scaling behavior.\n#\n# 3. For example, the scaling of `genentropy` with decreasing `\u03b5` gives the so-called\n# \"generalized dimension\".\n#\n#\n# $ E \\approx -D\\log(\\varepsilon)$ with $E$ the entropy and $D$ the \"dimension\".\n#\n# ---\n# I want to know dimension of attractor of the Towel Map!\n#\n# \n# ------------------------------------------------------------------------------------------\n\ntowel = Systems.towel()\ntowel_tr = trajectory(towel, 1000000);\nsummary(towel_tr)\n\n# ------------------------------------------------------------------------------------------\n# Note that more points = more precision = more computations = more time!\n#\n# Now I want to compute `genentropy` for different \u03b5.\n#\n# Which \u03b5 should we use...?\n#\n# Let's do a \"random\" logspace based guess...\n# ------------------------------------------------------------------------------------------\n\n\u03b5\u03c2 = logspace(-4, 1, 12)\n\nEs = zeros(\u03b5\u03c2)\nfor (i, \u03b5) \u2208 enumerate(\u03b5\u03c2)\n    Es[i] = genentropy(1, \u03b5, towel_tr)\nend\nEs\n\n# ------------------------------------------------------------------------------------------\n# **Shorter version:**\n# ------------------------------------------------------------------------------------------\n\nEs = genentropy.(1, \u03b5\u03c2, towel_tr)\n\n# ------------------------------------------------------------------------------------------\n# Alright. Remember that it should be that $E \\approx -D\\log(\\varepsilon)$\n#  with $E$ the entropy and $D$ the \"dimension\".\n#\n# Let's plot and see:\n# ------------------------------------------------------------------------------------------\n\nusing PyPlot; figure(figsize = (6,4))\nx = -log.(\u03b5\u03c2)\nplot(x, Es); xlabel(\"-log(\u03b5)\"); ylabel(\"Entropy\");\nplot([x[4], x[4]], [0, 15], color = \"C1\", alpha = 0.5)\nplot([x[end-3], x[end-3]], [0, 15], color = \"C1\", alpha = 0.5);\n\n# ------------------------------------------------------------------------------------------\n# What typically happens is that there is some region where this scaling behavior holds, but\n# then it stops holding due to the finite amount of data points.\n#\n# Above, the expected scaling behavior holds between the orange vertical lines.\n#\n# Let's choose the curve points that do fall in the linear regime of the above plot,\n# ------------------------------------------------------------------------------------------\n\nx, y = -log.(\u03b5\u03c2)[4:end-2], Es[4:end-2]\n\n# ------------------------------------------------------------------------------------------\n# and find the slope of the curve there, to calculate the dimension, D.\n# ------------------------------------------------------------------------------------------\n\noffset, slope = linreg(x, y)\nD = slope\n\n# ------------------------------------------------------------------------------------------\n# This is actually a correct result, the information dimension of the attractor of the towel\n# map is around 2.\n#\n# ---\n#\n# * Are the values of `\u03b5\u03c2` we used good?\n# * For a general dataset, how can we determine them?\n#\n# the function `estimate_boxsizes(dataset; kwargs...)` can help with that!\n# ------------------------------------------------------------------------------------------\n\n\u03b5\u03c2 = estimate_boxsizes(towel_tr)\n\n# ------------------------------------------------------------------------------------------\n# Let's plot $E$ vs. $-\\log \\epsilon$ again\n# ------------------------------------------------------------------------------------------\n\nEs = genentropy.(1, \u03b5\u03c2, towel_tr)\nfigure(figsize = (6,4))\nplot(-log.(\u03b5\u03c2), Es); xlabel(\"-log(\u03b5)\"); ylabel(\"E\");\n\n# ------------------------------------------------------------------------------------------\n# ---\n# # Automated Dimension Estimation\n#\n# Given some arbitrary plot like the one above, is there any algorithm to deduce a scaling\n# region???\n#\n# The function `linear_regions(x, y; kwargs...)` decomposes the function `y(x)` into regions\n# where  the function is linear.\n#\n# It returns the indices of `x` that correspond to linear regions and the approximated\n# tangents at each region!\n# ------------------------------------------------------------------------------------------\n\nx = -log.(\u03b5\u03c2)\nlrs, slopes = linear_regions(x, Es)\n\nfor i in 1:length(slopes)\n    println(\"linear region $(i) starts from index $(lrs[i]) and ends at index $(lrs[i+1])\")\n    println(\"with corresponding slope $(slopes[i])\")\n    println()\nend\n\n# ------------------------------------------------------------------------------------------\n# The linear region which is biggest is \"probably correct one\".\n# Here the last linear region is the largest; thus the slope is\n# ------------------------------------------------------------------------------------------\n\nslopes[end]\n\n# ------------------------------------------------------------------------------------------\n# This `linear_regions` function seems very shady... Is there any \"easy\" way to visualize\n# what it does? *Say no more!*\n#\n# In this next example, we'll use `ChaosTools`, which belows to `DynamicalSystems`.\n# ------------------------------------------------------------------------------------------\n\nusing PyPlot, ChaosTools\n\n# ------------------------------------------------------------------------------------------\n# `ChaosTools` provides a function, `plot_linear_regions` !\n# ------------------------------------------------------------------------------------------\n\nfigure(figsize=(6,4))\nplot_linear_regions(x, Es)\nxlabel(\"-log(\u03b5)\"); ylabel(\"E\");\n\n# ------------------------------------------------------------------------------------------\n# Adjust the tolerance of `linear_regions` using keyword argument `tol`\n# ------------------------------------------------------------------------------------------\n\nfigure(figsize=(6,4))\nplot_linear_regions(x, Es; tol = 0.8)\nxlabel(\"-log(\u03b5)\"); ylabel(\"E\");\n\n# ------------------------------------------------------------------------------------------\n# Notice how the color schemes allow us to visualize that adjusting the tolerance reduces\n# our number of linear regimes!\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# ## `generalized_dim` function\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# Let's summarize what we just did to estimate the dimension of an attractor.\n#\n# 1. We decided on some partition sizes `\u03b5\u03c2` to use (the function `estimate_boxsizes` can\n# give an estimate for that).\n# 2. For each `\u03b5` in `\u03b5\u03c2` we calculated the entropy via `genentropy`. We stored these\n# entropies in an array `Es`.\n# 3. We tried to find a \"linear scaling region\" of the curve `Es` vs. `-log.(\u03b5\u03c2)`.\n# 4. The slope of this \"linear scaling region\" is the dimension we estimated.\n#\n# Wouldn't it be **cool** if all of this process could happen with one function call?\n#\n# This is *exactly* what the following function does:\n# ```julia\n# generalized_dim(\u03b1, dataset, \u03b5\u03c2 = estimate_boxsizes(tr))\n# ```\n# which computes the `\u03b1`-order generalized dimension.\n# ------------------------------------------------------------------------------------------\n\ngeneralized_dim(2.0, tr)\n\ngeneralized_dim(1.0, tr)\n\n# ------------------------------------------------------------------------------------------\n# The first input to `generalized_dim` is our value for $\\alpha$!\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# Similarly, let's calculate the dimension of the Henon map that we have seen in previous\n# tutorials,\n# ------------------------------------------------------------------------------------------\n\nhen = Systems.henon()\ntr = trajectory(hen, 200000)\ngeneralized_dim(0, tr)\n\n# ------------------------------------------------------------------------------------------\n# and of the Lorenz system:\n# ------------------------------------------------------------------------------------------\n\nlor = Systems.lorenz()\ntr_lor = trajectory(lor, 1000.0; dt = 0.05);\n\ngeneralized_dim(2.0, tr_lor)\n\n# ------------------------------------------------------------------------------------------\n# The correlation dimension of the Lorenz attractor (for default parameters) is reported\n# *somewhere* around `2.0` (Grassberger and Procaccia, 1983).\n#\n# ## `generalized_dim` is but a crude estimate!\n#\n# **It is important to understand that `generalized_dim` is only a crude estimate! You must\n# check and double-check and triple-check if you want more accuracy!**\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# # Other related concepts\n# ## Kaplan-Yorke dimension\n# The Kaplan-Yorke dimension is defined as simply the (interpolated) number where the sum of\n# Lyapunov exponents crosses zero.\n#\n# This simple interpolation is done by the function `kaplanyorke_dim(ls)`.\n# ------------------------------------------------------------------------------------------\n\nlor = Systems.lorenz()\n\nls = lyapunovs(lor, 4000.0; Ttr = 100.0)\n\nkaplanyorke_dim(ls)\n\n# ------------------------------------------------------------------------------------------\n# ## Permutation Entropy\n#\n# Another entropy-like quantity that you can compute with **DynamicalSystems.jl** is the\n# [permutation entropy](https://juliadynamics.github.io/DynamicalSystems.jl/latest/chaos/ent\n# ropies/#permutation-entropy).\n#\n# This is done with the function `permentropy(s, order; ...)`. The permutation entropy is\n# different because it requires a *timeseries* `s` as the input.\n# ------------------------------------------------------------------------------------------\n\n# create timeseries:\ns = (ds = Systems.towel(); trajectory(towel, 10000)[:, 1])\n# order `o` permutation entropy:\no = 6\npermentropy(s, o)\n\n# ------------------------------------------------------------------------------------------\n# # Docstrings\n# ------------------------------------------------------------------------------------------\n\n?genentropy\n\n?generalized_dim\n\n?non0hist\n\n?estimate_boxsizes\n\n?linear_regions\n\n?kaplanyorke_dim\n\n?permentropy\n", "meta": {"hexsha": "66fd2ddbd85ccacea267fe7ca5646f13b2c08d54", "size": 17566, "ext": "jl", "lang": "Julia", "max_stars_repo_path": ".nbexports/introductory-tutorials/broader-topics-and-ecosystem/introduction-to-dynamicalsystems.jl/4. Entropies & Dimensions.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/4. Entropies & Dimensions.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/4. Entropies & Dimensions.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": 39.6523702032, "max_line_length": 92, "alphanum_fraction": 0.4329955596, "num_tokens": 3243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966686936262, "lm_q2_score": 0.9032942145139149, "lm_q1q2_score": 0.8550552943090977}}
{"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.09\"\n\n# \u2554\u2550\u2561 fa68607e-22e5-11eb-0558-c9a4d9f77426\nbegin\n\tactualAlpha, actualLambda = 2,3\n\tgammaDist = Gamma(actualAlpha,1/actualLambda)\n\tn = 10^2\n\tsample = rand(gammaDist, n)\nend\n\n# \u2554\u2550\u2561 68b12c46-3a9c-11eb-03b3-bf9862c5371c\nbegin\n\talphaGrid = 1:0.02:3\n\tlambdaGrid = 2:0.02:5\nend\n\n# \u2554\u2550\u2561 68b16da0-3a9c-11eb-21e2-53c689f1599c\nlikelihood = [prod([pdf.(Gamma(a,1/l),v) for v in sample])\n                        for l in lambdaGrid, a in alphaGrid]\n\n# \u2554\u2550\u2561 68b1f8ce-3a9c-11eb-2ad9-a5af4bd66c0e\nsurface(alphaGrid, lambdaGrid, likelihood, lw=0.1, \n\tc=cgrad([:blue, :red]), legend=:none, camera = (135,20),\n\txlabel=L\"\\alpha\", ylabel=L\"\\lambda\", zlabel=\"Likelihood\")\n\n# \u2554\u2550\u2561 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing5.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\u2550fa68607e-22e5-11eb-0558-c9a4d9f77426\n# \u2560\u255068b12c46-3a9c-11eb-03b3-bf9862c5371c\n# \u2560\u255068b16da0-3a9c-11eb-21e2-53c689f1599c\n# \u2560\u255068b1f8ce-3a9c-11eb-2ad9-a5af4bd66c0e\n# \u255f\u2500475ff888-22e6-11eb-2354-09f8f40a8e12\n", "meta": {"hexsha": "df66905fc58acf578e83fd2066f8f7fc39cca810", "size": 1444, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/05/listing5.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/05/listing5.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/05/listing5.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": 26.2545454545, "max_line_length": 60, "alphanum_fraction": 0.7209141274, "num_tokens": 744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9465966732132748, "lm_q2_score": 0.9032942099580603, "lm_q1q2_score": 0.8550552940791133}}
{"text": "include(\"ceil_floor.jl\")\n\n\"\"\"\n    median(nums)\n\nFinds median of a vector of numbers\n\n# Example\n\n```julia\nmedian([2,1,3,4])                   # returns 2.5\nmedian([2, 70, 6, 50, 20, 8, 4])    # returns 8\nmedian([0])                         # returns 0\n```\n\nContributed By:- [Ashwani Rathee](https://github.com/ashwani-rathee)\n\"\"\"\nfunction median(nums)\n    sorted = sort(nums)\n    len = length(sorted)\n    mid_index = Int(floor_val(len / 2))\n    return len % 2 == 0 ? (sorted[mid_index+1] + sorted[mid_index]) / 2 : sorted[mid_index+1]\nend\n", "meta": {"hexsha": "4a50ed966e78bafdf1dc19c545a7d15c7d141eb5", "size": 538, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/average_median.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_median.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_median.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": 22.4166666667, "max_line_length": 93, "alphanum_fraction": 0.5855018587, "num_tokens": 172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9465966732132747, "lm_q2_score": 0.9032942054022056, "lm_q1q2_score": 0.8550552897665562}}
{"text": "using DiffEqBiological\nusing DifferentialEquations\nusing Plots\nusing Colors\n\nlogistic_model = @reaction_network logistic begin\n  r, cell + nutrient --> 2cell\nend r\n\nr = 1.5\ncell0 = 1.0\nnutrient0 = 2000.0\n\ntspan = (0.0,0.008)\np =  (r)\nu0 = [cell0, nutrient0]\n\noprob = ODEProblem(logistic_model, u0, tspan, p)\nosol = solve(oprob, reltol=1e-8,abstol=1e-8)\nKbio = nutrient0+cell0\nn = [((Kbio)*(cell0*exp(r*t)))/((Kbio)+(cell0*(exp(r*t)-1))) for t in osol.t]\n#plot(osol)\nplot(osol.t, [osol.u[i][1] for i in 1:length(osol.t)], labels=\"Cells\", color= \"blue\", lw=2.0)\nplot!(osol.t, [osol.u[i][2] for i in 1:length(osol.t)], labels=\"Nutrients\", color=\"red\", lw=2.0)\n\n\n# https://nextjournal.com/sosiris-de/diffeqbiological\n# What is the final value of cell(t)?  How does it relate to K?\n# Can you overlay the analytical solution?\n\nprob = DiscreteProblem(u0, tspan ,p)\njump_prob = JumpProblem(prob,Direct(),logistic_model)\nsol = solve(jump_prob,FunctionMap())\n#plot(sol)\nplot(sol.t, [sol.u[i][1] for i in 1:length(sol.t)], labels=\"\", color=\"blue\", lw=2)\nplot!(sol.t, [sol.u[i][2] for i in 1:length(sol.t)], labels=\"\", color=\"red\", lw=2)\n# Can you plot the stochastic solution (sol) on top of the deterministic solution (osol)?\n\nplot(osol)\nplot!(sol)\n\n#or\n\np1=plot(osol)\np2=plot(sol)\n\nplot(p1,p2, xaxis=\"Time\", yaxis=\"Population Size\")\n\n# Can you see how step-like the results are?\n# What happens if you increase nutrient0 to 2000.0?\n# Do the stochastic results still look very different to the deterministic ones?\n# If you run line 27 above several times, saving the results in a list comprehension,\n# then drawing them all on the same plot, will they be the same?\n\nnsins=100\nprob = DiscreteProblem(u0, tspan ,p)\njump_prob = JumpProblem(prob,Direct(),logistic_model)\nsolutions =[solve(jump_prob,FunctionMap()) for i in 1:nsins]\nplot(solutions[1].t, [solutions[1].u[i][1] for i in 1:length(solutions[1].t)], labels=\"Cells\", color= \"blue\", xaxis=\"Time\", yaxis=\"Population Size\", title=\"Discrete Stochastic Populations Dynamics\", lw=0.3)\nplot!(solutions[1].t,[solutions[1].u[i][2] for i in 1:length(solutions[1].t)], labels=\"Nutrients\", color=\"red\", lw=0.3)\nfor j in 2:nsins\n    p=plot!(solutions[j].t, [solutions[j].u[i][1] for i in 1:length(solutions[j].t)], labels=\"\", color= \"blue\", lw=0.3)\n    q=plot!(solutions[j].t,[solutions[j].u[i][2] for i in 1:length(solutions[j].t)], labels=\"\", color=\"red\", lw=0.3)\n    display(p)\n    display(q)\nend\noprob = ODEProblem(logistic_model, u0, tspan, p)\nosol = solve(oprob, reltol=1e-8,abstol=1e-8)\nKbio = nutrient0+cell0\nn = [((Kbio)*(cell0*exp(r*t)))/((Kbio)+(cell0*(exp(r*t)-1))) for t in osol.t]\nplot!(osol.t, [osol.u[i][1] for i in 1:length(osol.t)], labels=\"Deterministic Continuous Solution\", color=\"black\", lw=2)\nplot!(osol.t, [osol.u[i][2] for i in 1:length(osol.t)], labels=\"\", color=\"black\", legend=:right, lw=2)\n\n# Can you simulate from the discrete stochastic exponential model?\n\n############################################################################################################\n\nusing DiffEqBiological\nusing DifferentialEquations\nusing Plots\nusing Colors\n\nexponential_model = @reaction_network exponential begin\n  r, cell  --> 2cell\nend r\n\nr = 5.0\ncell0 = 10.0\n\ntspan = (0.0,1.0)\np = (r)\nu0 = [cell0]\n\noprobe = ODEProblem(exponential_model, u0, tspan, p)\nosole = solve(oprobe)\nplot(osole, labels=\"Deterministic Solution\", lw=2)\n\nprobe = DiscreteProblem(u0, tspan ,p)\njump_prob = JumpProblem(probe,Direct(),exponential_model)\nsole = solve(jump_prob,FunctionMap())\n#plot(sole)\nplot!(sole, title=\"Deterministic and Stochastic Exponential Model\", xaxis=\"Time\", yaxis=\"Popuplation Size\", legend=:left, lw=2, labels=\"Stochastic Solution\")\n\nnsims=100\nprobe = DiscreteProblem(u0, tspan ,p)\njump_prob = JumpProblem(probe,Direct(),exponential_model)\nsolutions =[solve(jump_prob,FunctionMap()) for i in 1:nsims]\nplot(solutions[1].t, [solutions[1].u[i][1] for i in 1:length(solutions[1].t)], labels=\"Cells\", color=\"blue\", lw=0.2)\nfor j in 2:nsims\n    p=plot!(solutions[j].t, [solutions[j].u[i][1] for i in 1:length(solutions[j].t)], labels=\"\", color=\"blue\", legend=:left, title=\"Exponential Model w/ Stochastic and Deterministic Solutions\", lw=0.2)\n    display(p)\nend\noprobe = ODEProblem(exponential_model, u0, tspan, p)\nosole = solve(oprobe)\nplot!(osole, labels=\"Deterministic Solution\", xaxis=\"Time\", yaxis=\"Population Size\",color=\"black\", lw=2)\n\n######################################################################################################################\n\n\n\n# Can you simulate from the discrete stochastic Lotka-Volterra model?\n\nlv_model = @reaction_network lv begin\n  k1, prey --> 2prey\n  k2, prey + predator --> 2predator\n  k3, predator --> null\n # k4, prey --> null\nend k1 k2 k3 #k4\n\nk1 = 1.0\nk2 = 0.1\nk3 = 0.1\n#k4 = 0.001\n\nprey0 = 40.0\npredator0 = 100.0\nnull0 = 0.0\ntspan = (0.0,200.0)\np =  (k1,k2,k3)\nu0 = [prey0, predator0]\n\noproblv = ODEProblem(lv_model, u0, tspan, p)\nosollv = solve(oproblv, reltol=1e-5,abstol=1e-5)\n#plot(osollv)\nplot(osollv.t, [osollv.u[i][1] for i in 1:length(osollv.t)], labels=\"D-Prey\", color= \"blue\", lw=2)\nplot!(osollv.t, [osollv.u[i][2] for i in 1:length(osollv.t)], labels=\"D-Predators\", color=\"orange\", lw=2)\n\nprob = DiscreteProblem(u0, tspan ,p)\njump_prob = JumpProblem(prob,Direct(),lv_model)\nsollv = solve(jump_prob,FunctionMap())\n#plot(sollv)\nplot!(sollv.t, [sollv.u[i][1] for i in 1:length(sollv.t)], labels=\"S-Prey\", color= \"green\", lw=2.0)\nplot!(sollv.t, [sollv.u[i][2] for i in 1:length(sollv.t)], labels=\"S-Predators\", color=\"red\", lw=2.0, title=\"Lotka-Volterra Deterministic and Stochastic Models\", xaxis=\"Time\", yaxis=\"Population Size\")\n\n# at larger pops the stochastic solution looks very similar to the deterministic solution but it doesnt have the advantage of being continuous\n\n# Can you simulate from the discrete stochastic birth-death model?\n\n############################################################################################################################\n\nbd_model = @reaction_network bd begin\n  lambda, cell  --> 2cell\n  mu, cell  --> null\nend lambda mu\n\nlambda = 2.0\n#lambda = 0.8\nmu= 1.5\n#mu= 0.5\ncell0 = 100.0\nnull0 = 0.0\n\ntspan = (0.0,5.0)\np =  (lambda, mu)\nu0 = [cell0, null0]\n\noprobbd = ODEProblem(bd_model, u0, tspan, p)\nosolbd = solve(oprobbd, reltol=1e-8,abstol=1e-8)\n#plot(osolbd)\nplot(osolbd.t, [osolbd.u[i][1] for i in 1:length(osolbd.t)], labels=\"\", color= \"blue\", ls=:dash)\nplot!(osolbd.t, [osolbd.u[i][2] for i in 1:length(osolbd.t)], labels=\"\", color=\"red\", ls=:dash)\n\n\nprobbd = DiscreteProblem(u0, tspan ,p)\njump_prob = JumpProblem(probbd,Direct(),bd_model)\nsolbd = solve(jump_prob,FunctionMap())\n#plot(solbd)\nplot!(solbd.t, [solbd.u[i][1] for i in 1:length(solbd.t)], labels=\"Cells\", color= \"blue\")\nplot!(solbd.t, [solbd.u[i][2] for i in 1:length(solbd.t)], labels=\"Dead Cells\", color=\"red\", legend=:left, title=\"Birth-Death Model w/ Deterministic and Stochastic Solutions\", xaxis=\"Time\", yaxis=\"Popuplation Size\")\n\n\nnsins=100\nprobbd = DiscreteProblem(u0, tspan ,p)\njump_prob = JumpProblem(probbd,Direct(),bd_model)\nsolutions =[solve(jump_prob,FunctionMap()) for i in 1:nsins]\nplot(solutions[1].t, [solutions[1].u[i][1] for i in 1:length(solutions[1].t)], labels=\"Cells\", color= \"blue\", xaxis=\"Time\", yaxis=\"Population Size\", title=\"Discrete Stochastic Populations Dynamics\", lw=0.3)\nplot!(solutions[1].t,[solutions[1].u[i][2] for i in 1:length(solutions[1].t)], labels=\"Dead Cells\", color=\"red\", lw=0.2)\nfor j in 2:nsins\n    p=plot!(solutions[j].t, [solutions[j].u[i][1] for i in 1:length(solutions[j].t)], labels=\"\", color= \"blue\", lw=0.2)\n    q=plot!(solutions[j].t,[solutions[j].u[i][2] for i in 1:length(solutions[j].t)], labels=\"\", color=\"red\", lw=0.2)\n    display(p)\n    display(q)\nend\noprobbd = ODEProblem(bd_model, u0, tspan, p)\nosolbd = solve(oprobbd, reltol=1e-10,abstol=1e-10)\nplot!(osolbd.t, [osolbd.u[i][1] for i in 1:length(osolbd.t)], labels=\"Deterministic Solution\", color=\"black\", lw=3)\nplot!(osolbd.t, [osolbd.u[i][2] for i in 1:length(osolbd.t)], labels=\"\", color=\"black\", legend=:left, lw=3, title=\"Birth-Death Model Showing Stochastic Behavior\")\n\n\n################################################################################################################################\n\n# What is the difference between the birth-death model and the exponential model?\n\nusing DiffEqBiological\nusing DifferentialEquations\nusing Plots\nusing Colors\n#using ParameterizedFunctions\n\nmtdna_model = @reaction_network mtdna begin\n  b, wildtype --> 2wildtype\n  d, wildtype  --> null\n  bmut, mut --> 2mut\n  dmut, mut --> null\n  m, wildtype --> wildtype + mut\n  # can we have wildtype --> 2mut\nend b d bmut dmut m\n\n# parameter values\n\nb = 0.001875*365\nd = 0.001875*365\nbmut = 0.001875*365\ndmut = 0.001875*365\nm = (1e-5)*365\n\n# initial conditions\n\nwildtype0 = 100.0\nmut0 = 0.0\nnull0 = 0.0\ndummy0 = 1.0\ntspan= (0.0, 100.0)\np = (b,d,bmut,dmut,m)\nu0 = [wildtype0, mut0, null0]\n\nsim_to_tot = function(res, totmax, b_small, b_big, replicative_advantage)\n  u0 = res.u[end]\n  tot_mtDNA0 = u0[1] + u0[3]\n  pnew = collect(p)\n  if tot_mtDNA0 >= totmax\n    pnew[1] = b_small\n    pnew[3] = b_small * replicative_advantage\n  else\n    pnew[1] = b_big\n    pnew[3] = b_big * replicative_advantage\n  end\n  pnewer = (pnew...,)\n  oprobmtdna = ODEProblem(mtdna_model, u0, tspan, pnewer)#, callback=cset)\n  osolmtdna = solve(oprobmtdna)\n  totmtDNA = [osolmtdna.u[i][1] + osolmtdna.u[i][3] for i in 1:length(osolmtdna.t)];\n  triggered = [t>=totmax for t in totmtDNA];\n  lastres = findfirst(triggered)-1;\n  times = [t for t in osolmtdna.t[1:lastres]]\n  species = [u for u in osolmtdna.u[1:lastres]]\n  res = (t = times, u = species)\n  return(res)\nend\n\nres = (t = [0.0], u = [u0])\ncurrent_time = res.t[1]\nallres = []\nwhile current_time <= tspan[2]\n  global current_time, allres, b\n  resnew = sim_to_tot(res, 105.0, 0.0, b, 1.0)\n  ttotal = [t + current_time for t in resnew.t]\n  current_time = ttotal[end]\n  updatedres = (t=ttotal, u=resnew.u)\n  push!(allres,updatedres)\nend\n\ntimes = collect(Iterators.flatten([res.t for res in allres]))\nspecies = collect(Iterators.flatten([res.u for res in allres]))\nosolmtdna = (t=times,u=species)\n\nplot(osolmtdna.t, [osolmtdna.u[i][1] for i in 1:length(osolmtdna.t)], labels=\"Wildtype\", color= \"blue\")\nplot!(osolmtdna.t, [osolmtdna.u[i][3] for i in 1:length(osolmtdna.t)], labels=\"Mutant\", color=\"red\")\nplot!(osolmtdna.t, [osolmtdna.u[i][1]+osolmtdna.u[i][3] for i in 1:length(osolmtdna.t)], labels=\"Total\", color=\"black\")\n\nusing DiffEqBiological\nusing DifferentialEquations\nusing Plots\nusing Colors\n\nmtdna_model = @reaction_network mtdna begin\n  b, wildtype --> 2wildtype\n  d, wildtype  --> null\n  bmut, mut --> 2mut\n  dmut, mut --> null\n  m, wildtype --> wildtype + mut\n  # can we have wildtype --> 2mut\nend b d bmut dmut m\n\n# parameter values\n\nb = 0.001875*365\nd = 0.001875*365\nbmut = 0.001875*365\ndmut = 0.001875*365\nm = (1e-5)*365\n\n# initial conditions\n\nwildtype0 = 100.0\nmut0 = 10.0\nnull0 = 0.0\ndummy0 = 1.0\ntspan= (0.0, 100.0)\np = (b,d,bmut,dmut,m)\nu0 = [wildtype0, mut0, null0]\n\nsim_to_tot2 = function(res, totmax, b_small, b_big, replicative_advantage)\n  u0 = res.u[end]\n  tot_mtDNA0 = u0[1] + u0[3]\n  pnew = collect(p)\n  if tot_mtDNA0 >= totmax\n    pnew[1] = b_small\n    pnew[3] = b_small * replicative_advantage\n  else\n    pnew[1] = b_big\n    pnew[3] = b_big * replicative_advantage\n  end\n  pnewer = (pnew...,)\n  probmtdna = DiscreteProblem(u0, tspan ,pnewer)\n  jump_prob = JumpProblem(probmtdna,Direct(),mtdna_model)\n  solmtdna = solve(jump_prob,FunctionMap())\n  totmtDNA = [solmtdna.u[i][1] + solmtdna.u[i][3] for i in 1:length(solmtdna.t)];\n  triggered = [t>=totmax for t in totmtDNA];\n  lastres = findfirst(triggered)-1;\n  times = [t for t in solmtdna.t[1:lastres]]\n  species = [u for u in solmtdna.u[1:lastres]]\n  res = (t = times, u = species)\n  return(res)\nend\n\nres = (t = [0.0], u = [u0])\ncurrent_time = res.t[1]\nallres = []\nwhile current_time <= tspan[2]\n  global current_time, allres, b\n  resnew = sim_to_tot2(res, 105.0, 0.0, b, 1.0)\n  ttotal = [t + current_time for t in resnew.t]\n  current_time = ttotal[end]\n  updatedres = (t=ttotal, u=resnew.u)\n  push!(allres,updatedres)\nend\n\ntimes = collect(Iterators.flatten([res.t for res in allres]))\nspecies = collect(Iterators.flatten([res.u for res in allres]))\nsolmtdna = (t=times,u=species)\n\nplot(solmtdna.t, [solmtdna.u[i][1] for i in 1:length(solmtdna.t)], labels=\"Wildtype\", color= \"blue\")\nplot!(solmtdna.t, [solmtdna.u[i][3] for i in 1:length(solmtdna.t)], labels=\"Mutant\", color=\"red\")\nplot!(solmtdna.t, [solmtdna.u[i][1] + solmtdna.u[i][3] for i in 1:length(solmtdna.t)], labels=\"Total\", color=\"black\", legend=:outerright, title=\"mtDNA Population Dynamics Within a Cell\", xaxis=\"Time (Years)\", yaxis=\"Population Size\")\n\n\nnsins=10\nprobmtdna = DiscreteProblem(u0, tspan ,p)\njump_prob = JumpProblem(probmtdna,Direct(),mtdna_model)\nsolutions =[solve(jump_prob,FunctionMap()) for i in 1:nsins]\nplot(solutions[1].t, [solutions[1].u[i][1] for i in 1:length(solutions[1].t)], labels=\"Wildtype\", color= \"blue\", xaxis=\"Time\", yaxis=\"Population Size\", title=\"mtDNA Populations Dynamics\", lw=0.3)\nplot!(solutions[1].t,[solutions[1].u[i][2] for i in 1:length(solutions[2].t)], labels=\"Mutant\", color=\"red\", lw=0.3)\nfor j in 2:nsins\n    p=plot!(solutions[j].t, [solutions[j].u[i][1] for i in 1:length(solutions[j].t)], labels=\"\", color= \"blue\", lw=0.3)\n    q=plot!(solutions[j].t,[solutions[j].u[i][3] for i in 1:length(solutions[j].t)], labels=\"\", color=\"red\", lw=0.3)\n    display(p)\n    display(q)\nend\noprobmtdna = ODEProblem(mtdna_model, u0, tspan, p)\nosolmtdna = solve(oprobmtdna)\nplot!(osolmtdna.t, [osolmtdna.u[i][1] for i in 1:length(osolmtdna.t)], labels=\"Deterministic Continuous Solution\", color=\"black\", lw=2)\nplot!(osolmtdna.t, [osolmtdna.u[i][3] for i in 1:length(osolmtdna.t)], labels=\"\", color=\"black\", legend=:right, lw=2)\n\n\n# What happens if a cells is born with no mutations?\n\n# What happens if a cell inherits a lot of mutations?  70%?\n\n# What happens in both of the scenarios above if bmut > b?\n", "meta": {"hexsha": "9f3339577b9d6bb08738dd00d025285cbfa416de", "size": 14024, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "code/learning_material/discretestochlogistic.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/learning_material/discretestochlogistic.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/learning_material/discretestochlogistic.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": 35.958974359, "max_line_length": 233, "alphanum_fraction": 0.6650741586, "num_tokens": 4886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191297273498, "lm_q2_score": 0.8947894534772125, "lm_q1q2_score": 0.8548094819850616}}
{"text": "\"\"\"\n    combination(n, r)\n        \nreturns the number of ways picking r unordered outcomes from\nn possibilities, without repetition\n\n# Arguments:\n- `n`: Positive integers of items to choose from\n- 'r': Positive integers of items to choose\n\nContributed By:- [Mayur Dahibhate](https://github.com/mayurdahibhate)\n\"\"\"\n\nfunction combination(n, r)\n\n    function factorial(n)        \n        fact = 1\n        \n        if n == 0 || n == 1\n            return fact\n        end\n         \n        for i = 1:n\n            fact = fact * i\n        end \n        \n        return fact\n    end\n    \n    comb = factorial(n) / (factorial(r) * factorial(n - r))\n\n    return convert(Int64, comb)\nend\n", "meta": {"hexsha": "842b54ce8ada7488445cdd3062bd486c82e5c14d", "size": 677, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/combination.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/combination.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/combination.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": 19.9117647059, "max_line_length": 69, "alphanum_fraction": 0.5627769572, "num_tokens": 167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9740426375276383, "lm_q2_score": 0.8774767762675405, "lm_q1q2_score": 0.8546997935248846}}
{"text": "\"\"\"\nJulia program to find the Delannoy number for a given rectangular grid.\nA Delannoy number describes the number of paths from the southwest corner \n(0, 0) of a rectangular grid to the northeast corner (m, n) using only single steps north, northeast, or east.\nDelannoy number is named after the French mathematican Henri Delannoy.\n\"\"\"\n\nfunction delannoy_number(r, c)\n\n    # Initialize the dp array with '0' as value.\n    dp = zeros(Int, c + 1, r + 1)\n\n    for i in 1:c\n        dp[1,i] = 1\n    end\n    for i in 2:c+1\n        dp[i,1] = 1\n    end\n    # From Each point calculate the number of paths, to the north-east point, that can be reached by \n    # traversing through the immediate right or immediate top or immediate top-right point.\n    for i in 2:c+1\n        for j in 2:r+1\n            dp[i,j] = dp[i-1,j] + dp[i-1,j-1] + dp[i,j-1]\n        end\n    end\n    return dp[c+1,r+1]\nend    \n        \n\nprint(\"Enter the co-ordinates of the north-east corner.\\nEnter the row co-ordinate: \")\nx = readline()\nx = parse(Int, x)\nprint(\"Enter the column co-ordinate: \")\ny = readline()\ny = parse(Int, y)\nres = delannoy_number(x, y)\nprint(\"The Delannoy number of the given grid is $res.\")\n\n\n\"\"\"\nTime Complexity - O(x * y), where `x`, `y` is the given co-ordinates.\nSpace Complexity - O(1)\n\nSAMPLE INPUT AND OUTPUT\n\nSAMPLE I\n\nEnter the co-ordinates of the north-east corner.\nEnter the row co-ordinate: 5\nEnter the column co-ordinate: 6\nThe Delannoy number of the given grid is 3653.\n\"\"\"\n", "meta": {"hexsha": "92b5460c1947613dbc501d970f018445124dffa3", "size": 1475, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/math/delannoy_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/delannoy_number.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/math/delannoy_number.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": 27.8301886792, "max_line_length": 110, "alphanum_fraction": 0.6637288136, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338112885303, "lm_q2_score": 0.8887588008585925, "lm_q1q2_score": 0.8545716371057864}}
{"text": "@doc raw\"\"\"\n    triag_rng(a, b, m, shape=1; seed=nothing)\n\nGenerate a `shape` element array of random variables from a Triangular(`a`, `b`, `m`) distribution. Optionally you can set a specific seed.\n\n# Notes\n\nThe Triangular distribution is given by:\n\n```math\nf(x, a, b, m) = \\begin{cases}\n\\frac{2(x-a)}{(m-a)(b-a)}  & \\text{if  } a < x \u2264 m, \\\\\n\\frac{2(b-x)}{(b-m)(b-a)}  & \\text{if  } m < x \u2264 c, \\\\\n0 & \\text{otherwise}\n\\end{cases}\n```\n\n# Examples\n\n```julia-repl\njulia> triag_rng()\n1-element Vector{Float64}:\n 0.3559088458688944\n\njulia> triag_rng(0,7,2,5)\n5-element Vector{Float64}:\n 1.3758072115332673\n 6.049452463477447\n 6.042781317411027\n 2.914959243260448\n 4.454707036522528\n```\n\n# References\n\nW. Stein and M. Keblis. A new method to simulate the triangular distribution. Mathematical and Computer Modelling, Volume 49, Issues 5\u20136, 2009.\n\"\"\"\nfunction triag_rng(a=0,b=1,m=.5,shape=1)\n    u = get_std_uniform(shape)\n    v = get_std_uniform(shape)\n    t_min = min.(u,v)\n    t_max = max.(u,v)\n    c = (m-a)/(b-a)\n    t = ((1-c) .* t_min) .+ (c .* t_max)\n    X = a .+ (b-a) .*t\n    return X\nend", "meta": {"hexsha": "ec47a5026a6e7a12165982a61ba5bf13a24bdb3d", "size": 1093, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/triangular.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/triangular.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/triangular.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": 23.2553191489, "max_line_length": 143, "alphanum_fraction": 0.637694419, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.956634203708804, "lm_q2_score": 0.8933094152856197, "lm_q1q2_score": 0.8545703411573361}}
{"text": "using Random, Distributions, LinearAlgebra\nusing Plots; pyplot()\n\n\nfunction sum_of_squares(v)\n    \"\"\"Computes the sum of squared elements in v\"\"\"\n    return dot(v, v)\nend\n\n\nfunction difference_quotient(f, x, h)\n    return (f(x + h) - f(x)) / h\nend\n\nfunction square(x)   \n    return x * x\nend\n\nfunction derivative(x)\n    return 2 * x\nend\n\n@assert 4 <= difference_quotient(square, 2, .001) <=4.01\n\nfunction squared_distance(v, w)\n    \"\"\"Computes (v_1 - w_1) ** 2 + ... + (v_n - w_n) ** 2\"\"\"\n    return sum_of_squares((v - w))\nend\n\nfunction distance(v, w)\n    \"\"\"Computes the distance between v and w\"\"\"\n    return sqrt(squared_distance(v, w))\nend\n\nfunction partial_difference_quotient(f, v, i, h)\n        \"\"\"Returns the i-th partial difference quotient of f at v\"\"\"\n        # w = [v_j + (h if j == i else 0) for j, v_j in enumerate(v)]\n        w = copy(v) \n        for j in 1:length(v)\n            v_j = v[j]   \n            if(j==i) \n                w[j] = v_j + h\n            else\n                w[j] = v_j \n            end\n        end\n\n        return (f(w) - f(v)) / h\nend\n\n\nfunction add(v, w)\n    \"\"\"Adds corresponding elements\"\"\"\n    @assert length(v) == length(w)\n    return v+w \nend\n\n\n\nfunction scalar_multiply(c, v)\n    \"\"\"Multiplies every element by c\"\"\"\n    return [c * v_i for v_i in v]\nend\n\nfunction gradient_step(v, gradient, step_size)\n    \"\"\"Moves `step_size` in the `gradient` direction from `v`\"\"\"\n    @assert length(v) == length(gradient)\n    step = scalar_multiply(step_size, gradient)\n    return add(v, step)\nend\n\nfunction sum_of_squares_gradient(v)\n    return [2 * v_i for v_i in v]\nend\n\n\nfunction custom_fun(v)\n    sign = -1\n    if(v[2] > 4)\n        sign = 1\n    end\n    return v[1]*v[1] + sign * v[2]*v[2] + 16\nend\n\nfunction estimate_gradient(f, v, h = 0.0001)\n    return [partial_difference_quotient(f, v, i, h) for i in 1:length(v)]\nend\n# let v = [rand(-10: 10) for i in 0:2]\nlet v = [2.0, 2.0]\n    for epoch in 1:1000\n        # grad = sum_of_squares_gradient(v)    # compute the gradient at v\n        grad = estimate_gradient( custom_fun,v)\n        v = gradient_step(v, grad, -0.001)    # take a negative gradient step\n    end\n\n    # @assert distance(v, [0, 0]) < 0.001    # v should be close to 0\n    @assert custom_fun(v) < .1\nend\n\n\n\nxs = -10: 11\nactuals = [derivative(x) for x in xs]\nestimates = [difference_quotient(square, x, 0.001) for x in xs]\n\n# plot to show they're basically the same\nplot(title = \"Actual Derivatives vs. Estimates\")\nplot!(xs, actuals, label=\"Actual\", seriestype = :scatter, color = \"red\", markersize = 7)       # red  x\nplot!(xs, estimates, label=\"Estimate\", seriestype = :scatter, color = \"blue\", markershape= :x)   # blue +\n# plot(legend=loc=9)\n# plot.show()\n\n\n\nresult = estimate_gradient(sum_of_squares,[2.0 2.0])\nprintln(result) #should be equal to [4.0 4.0]\n\nfunction error(v)\n    x, y, slope, intercept = v\n    predicted = slope * x + intercept\n    error = (predicted - y)^2\n    return error\nend\n\nprintln(error([2, 1 , 3, 5]))\n\nex_vector = [2.0, 1.0 , 2.0, 5.0]\nprintln(partial_difference_quotient(error,ex_vector,3,.001))\n  \nfunction linear_gradient(x, y, theta)\n    vector = [x,y, theta...] \n    error_diff_estimate = [partial_difference_quotient(error,vector,i,.001)\n                        for i in 3:4]\n                        \nend \nerror_diff_estimate = linear_gradient(2.0,1.0, [2.0, 5.0])\nprintln(error_diff_estimate)\n\ninputs = [(x, 20 * x + 5) for x in -50: 49]\n\nfunction vector_mean(vectors)\n    \"\"\"Computes the element-wise average\"\"\"\n    n = length(vectors)\n    return scalar_multiply(1/n, sum(vectors))\nend\n\nud = Uniform(-1,1)\nlet theta = [rand(ud), rand(ud)]\n\nlearning_rate = 0.001\nfor epoch in 1:3000\n    grad = vector_mean([linear_gradient(x,y, theta) for (x,y) in inputs])\n\n    theta = gradient_step(theta, grad, -learning_rate)\n    println(epoch, theta)\nend\n\nslope, intercept = theta\n@assert 19.9 < theta[1] < 20.1\n@assert 4.9 < intercept < 5.1\nend\n\n#finished\n", "meta": {"hexsha": "353c9871a6d8d56ae25fbca0d1d6d3e33db1933d", "size": 3935, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scratch/julia/ch8_grad_desc.jl", "max_stars_repo_name": "vettukal/data-science-from-scratch.jl", "max_stars_repo_head_hexsha": "5404d308ab9aee1fcbe9d7b4bbeb347ef636b234", "max_stars_repo_licenses": ["MIT"], "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/julia/ch8_grad_desc.jl", "max_issues_repo_name": "vettukal/data-science-from-scratch.jl", "max_issues_repo_head_hexsha": "5404d308ab9aee1fcbe9d7b4bbeb347ef636b234", "max_issues_repo_licenses": ["MIT"], "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/julia/ch8_grad_desc.jl", "max_forks_repo_name": "vettukal/data-science-from-scratch.jl", "max_forks_repo_head_hexsha": "5404d308ab9aee1fcbe9d7b4bbeb347ef636b234", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.993902439, "max_line_length": 105, "alphanum_fraction": 0.6172808132, "num_tokens": 1235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109742068042, "lm_q2_score": 0.8991213853793453, "lm_q1q2_score": 0.8545348318085549}}
{"text": "exp(\u03c0) - \u03c0\n\n# Solve x^2 + 5x + 6 = 0 using the quadratic formula (real arithmetics)\n\n# Coefficients a,b,c in ax^2 + bx + c = 0\na = 1\nb = 5\nc = 6\n\n# The quadratic formula\nd = sqrt(b^2 - 4*a*c)\nr1 = (-b - d) / 2a\nr2 = (-b + d) / 2a\nprintln(\"The roots are \", r1, \" and \", r2)\n\nfunction myfunc(x,y)\n    x + y\nend\n\nmyfunc(1,2)\n\nmyfunc2(x,y) = x + 2y\nmyfunc2(3,5)\n\nmyfunc3 = (x,y) -> x + 3y\nmyfunc3(3,5)\n\n# Same thing without giving the function a name:\n((x,y) -> x + 3y)(3,5)\n\nfunction mynewfunc(x,y)\n    out1 = x + y\n    out2 = out1 * (2x + y)\n    out1, out2\nend\n\ny1, y2 = mynewfunc(2,1)\n\nfunction real_roots_of_quadratic(a,b,c)\n    # Compute the real roots of the quadratic ax^2 + bx + c = 0\n    d = sqrt(b^2 - 4*a*c)\n    r1 = (-b - d) / 2a\n    r2 = (-b + d) / 2a\n    r1, r2\nend\n\nreal_roots_of_quadratic(1, 5, 6)\n\nreal_roots_of_quadratic(-1, 5, 6)\n", "meta": {"hexsha": "909f49efd4cba4cf2265164ee7cbd4dfcbf8d204", "size": 845, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "textbook/_build/jupyter_execute/content/Introduction/Functions.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/Functions.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/Functions.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": 16.9, "max_line_length": 71, "alphanum_fraction": 0.5727810651, "num_tokens": 375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9719924818279466, "lm_q2_score": 0.8791467770088162, "lm_q1q2_score": 0.8545240576758396}}
{"text": "\"\"\"\n    beta_rng(\u03b1, \u03b2, shape=1; seed=nothing)\n\nGenerate a `shape` element array of random variables from a Beta(`\u03b1`, `\u03b2`) distribution. Optionally you can set a specific seed.\n\n# Notes\n\nThe Beta distribution is given:\n\n``f(x,\u03b1,\u03b2) = \\\\frac{x^{\u03b1-1 (1-x)^{\u03b2-1}}}{\u0392(\u03b1,\u03b2)} \\\\quad x \\\\in [0,1]``\n\nwhere ``\u0392(\u03b1,\u03b2) = \\\\frac{\u0393(\u03b1)\u0393(\u03b2)}{\u0393(\u03b1+\u03b2)}``\n\n# Examples\n\n```julia-repl\njulia> beta_rng(1,2)\n1-element Vector{Float64}:\n 0.44456674672905633\n\njulia> beta_rng(1, 2, (2,2))\n2\u00d72 Matrix{Float64}:\n 0.0792132  0.595657\n 0.737615   0.649721\n\n```\n\n# References\n\nD.P. Kroese, T. Taimre, Z.I. Botev. Handbook of Monte Carlo Methods. \n  Wiley Series in Probability and Statistics, John Wiley & Sons, New York, 2011.\n\nLaw, A. Simulation modeling and analysis, 5th Ed. McGraw Hill Education, Tuscon, 2013.\n\"\"\"\nfunction beta_rng(\u03b1::Real, \u03b2::Real, shape::Union{Int, Tuple{Vararg{Int}}}=1; seed::Union{Int, Nothing}=nothing)\n    seed_setter(seed)\n    Y\u2081 = gamma_rng(\u03b1, 1, shape, seed=seed)\n    Y\u2082 = gamma_rng(\u03b2, 1, shape, seed=seed)\n    X = Y\u2081 ./ (Y\u2081 .+ Y\u2082)\n    return X\nend\n", "meta": {"hexsha": "eb5aa21205511f1dfc5849910429ea4163b1fe2f", "size": 1049, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/beta.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/beta.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/beta.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": 24.9761904762, "max_line_length": 128, "alphanum_fraction": 0.6530028599, "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620550745211, "lm_q2_score": 0.8902942326713409, "lm_q1q2_score": 0.8544706223696399}}
{"text": "#= Finding the Greatest Common Divisor of 2 numbers using the Euclidean\nFormula to lessen the time complexity.\n=#\n\n## Function\n\nfunction GCD(a, b)\n    if (a == 0)\n        return b\n    end\n    if (b == 0)\n        return a\n    end\n    if (a < b)\n        a, b = b, a\n    end\n    ans = a % b\n    while (ans != 0)\n        a = b\n        b = ans\n        ans = a % b\n    end\n    return b\nend\n\n## Input\n\na = readline()\na = parse(Int64, a)\nb = readline()\nb = parse(Int64, b)\n\n## Calling the function\n\nGCD(a, b)\n\n#=\nSample Test case:\nInput: \n    a = 1001  b = 2352\nOutput:\n    7\nTime complexity: O( log (min(a,b)) )\n=#\n", "meta": {"hexsha": "b4105cd92f6a5bdf937353f6ba22610e0e4a4e8a", "size": 608, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/cp/GCD.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/cp/GCD.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/cp/GCD.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": 13.5111111111, "max_line_length": 71, "alphanum_fraction": 0.5213815789, "num_tokens": 205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620550745211, "lm_q2_score": 0.8902942181173146, "lm_q1q2_score": 0.8544706084012378}}
{"text": "# # Huber regression\n\n# This example can be found here: <https://web.stanford.edu/~boyd/papers/pdf/cvx_applications.pdf>.\n# Here we set `big_example = false` to only generate a small example which takes less time to run.\nbig_example = false\nif big_example\n    n = 300\n    number_tests = 50\nelse\n    n = 100\n    number_tests = 20\nend\n\n# Generate data for Huber regression.\nusing Random\nRandom.seed!(1);\nnumber_samples = round(Int,1.5*n);\nbeta_true = 5*randn(n);\nX = randn(n, number_samples);\nY = zeros(number_samples);\nv = randn(number_samples);\n\n#-\n\n## Generate data for different values of p.\n## Solve the resulting problems.\nusing Convex, SCS, Distributions\nlsq_data = zeros(number_tests);\nhuber_data = zeros(number_tests);\nprescient_data = zeros(number_tests);\np_vals = range(0, stop=0.15, length=number_tests);\nfor i=1:length(p_vals)\n    p = p_vals[i];\n    ## Generate the sign changes.\n    factor = 2 * rand(Binomial(1, 1-p), number_samples) .- 1;\n    Y = factor .* X' * beta_true + v;\n    \n    ## Form and solve a standard regression problem.\n    beta = Variable(n);\n    fit = norm(beta - beta_true) / norm(beta_true);\n    cost = norm(X' * beta - Y);\n    prob = minimize(cost);\n    solve!(prob, SCS.Optimizer(verbose=0));\n    lsq_data[i] = evaluate(fit);\n    \n    ## Form and solve a prescient regression problem,\n    ## i.e., where the sign changes are known.\n    cost = norm(factor .* (X'*beta) - Y);\n    solve!(minimize(cost), SCS.Optimizer(verbose=0))\n    prescient_data[i] = evaluate(fit);\n    \n    ## Form and solve the Huber regression problem.\n    cost = sum(huber(X' * beta - Y, 1));\n    solve!(minimize(cost), SCS.Optimizer(verbose=0))\n    huber_data[i] = evaluate(fit);\nend\n\n#-\nusing Plots\n\nplot(p_vals, huber_data, label=\"Huber\", xlabel=\"p\", ylabel=\"Fit\" )\nplot!(p_vals, lsq_data, label=\"Least squares\")\nplot!(p_vals, prescient_data, label=\"Prescient\")\n#-\n\n## Plot the relative reconstruction error for Huber and prescient regression,\n## zooming in on smaller values of p.\nindices = findall(p_vals .<= 0.08);\nplot(p_vals[indices], huber_data[indices], label=\"Huber\")\nplot!(p_vals[indices], prescient_data[indices], label=\"Prescient\")\n", "meta": {"hexsha": "b2f0c1e0f4ea005d12f7659b909839cfefaef85c", "size": 2152, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/examples_literate/general_examples/huber_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/huber_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/huber_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": 30.3098591549, "max_line_length": 99, "alphanum_fraction": 0.6830855019, "num_tokens": 608, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680098, "lm_q2_score": 0.9173026561945815, "lm_q1q2_score": 0.8544330317874193}}
{"text": "#=\n\t\t\t\t\t\t\tEven Fibonacci numbers\n\n\tEach  new term in the Fibonacci sequence is generated by adding the previous\n\ttwo terms. By starting with 1 and 2, the first 10 terms will be:\n\n\t\t\t\t\t1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...\n\n\tBy  considering  the  terms  in  the  Fibonacci sequence whose values do not\n\texceed four million, find the sum of the even-valued terms.\n\n\t\t\t\t\t\t\t\tAnswer: 4613732\n=#\n\nfunction fibonacci(limit::Int)\n    array = [1, 2]\n    flag = true\n    i = 2\n\n    while flag\n        new_value = array[i]+array[i-1]\n\n        if new_value < limit\n            push!(array, new_value)\n            i += 1\n        else\n            flag = false\n        end\n    end\n\n    return array\nend\n\nprintln(sum(filter(iseven, fibonacci(4_000_000))))\n", "meta": {"hexsha": "10d8a1df866612bc6ccef5f31c6ea51726fb3056", "size": 741, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/julia/1-25/problem_2.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_2.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_2.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": 21.1714285714, "max_line_length": 77, "alphanum_fraction": 0.6032388664, "num_tokens": 221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474233166328, "lm_q2_score": 0.8947894583870633, "lm_q1q2_score": 0.8542084508600953}}
{"text": "#=\n(a, ya) (b, yb) (c, yc)\n====\nq(x) = p1 + p2*x + p3 * x^2\n====\nya = p1 + p2*a + p3 * a^2\nyb = p1 + p2*b + p3 * b^2\nyc = p1 + p2*c + p3 * c^2\n=====\nlagrange\u2019s interpolating polynomial:\nq(x) = ya * ((x-b)(x-c))/((a-b)(a-c)) +\n       yb * ((x-a)(x-c))/((b-a)(b-c)) +\n       yc * ((x-a)(x-b))/((c-a)(c-b))\n=====\nq'(x) = 1/2 * (ya(b^2-c^2)+yb(c^2-a^2)+yc(a^2-b^2))/(ya(b-c) + yb(c-a) + yc(a-b))\n=#\n\nfunction quadratic_fit_search(f, a, b, c, n)\n    ya, yb, yc = f(x), f(x), 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", "meta": {"hexsha": "15bc736ae5e0cfe34239075fe3036553813a2273", "size": 968, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "bracketing/3.5-quadratic_fit_search.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": "bracketing/3.5-quadratic_fit_search.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": "bracketing/3.5-quadratic_fit_search.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": 24.2, "max_line_length": 81, "alphanum_fraction": 0.3450413223, "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731105140615, "lm_q2_score": 0.8872045952083047, "lm_q1q2_score": 0.8540880073315475}}
{"text": "using LinearAlgebra\nusing SparseArrays\nusing Plots\nusing ForwardDiff\n\n\"This routine runs a convergence test for the heat equation using either Backwards\nEuler or Crank-Nicolson in time and finite differences in space. The exact solution\nis generated using the method of manufactured solutions.\"\n\nuexact(x,t) = log(2+sin(pi*x))*exp(-t)*t\ndudx_exact(x,t) = ForwardDiff.derivative(x->uexact(x,t),x)\n# du/dt - d^2u/dx^2 = f\nf(x,t) = ForwardDiff.derivative(t->uexact(x,t),t) -\n         ForwardDiff.derivative(x->dudx_exact(x,t),x)\nu0(x) = uexact(x,0)\n\u03b1(t) = uexact(-1,t)\n\u03b2(t) = uexact(1,t)\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\nfunction solve_backward_Euler(m, f, \u03b1, \u03b2, u0, T, dt)\n\n    A,x,xint,h,F = build_FD(m,f,\u03b1,\u03b2)\n\n    u = u0.(xint)\n    Nsteps = ceil(Int,T/dt)\n    dt = T/Nsteps\n    for i = 1:Nsteps\n        t = i*dt\n        u .= (I + dt*A)\\(u .+ dt*F(t))\n    end\n    return u,x,xint,h\nend\n\nfunction solve_Crank_Nicolson(m, f, \u03b1, \u03b2, u0, T, dt)\n\n    A,x,xint,h,F = build_FD(m,f,\u03b1,\u03b2)\n\n    u = u0.(xint)\n    Nsteps = ceil(Int,T/dt)\n    dt = T/Nsteps\n    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    end\n    return u,x,xint,h\nend\n\nmvec = 2 .^ (2:8)\nhvec = zeros(length(mvec))\nhvec = Float64[]\nerr1 = Float64[]\nerr2 = Float64[]\nfor (i,m) in enumerate(mvec)\n\n    T = 1.0\n    dt = 5/m # proportional to h\n\n    u,x,xint,h = solve_backward_Euler(m,f,\u03b1,\u03b2,u0,T,dt)\n    push!(err1,maximum(@. abs(uexact(xint,T) - u)))\n\n    u,x,xint,h = solve_Crank_Nicolson(m,f,\u03b1,\u03b2,u0,T,dt)\n    push!(err2,maximum(@. abs(uexact(xint,T) - u)))\n\n    push!(hvec,h)\nend\nplot(hvec,err1,marker=:dot,label=\"Max error (backwards Euler)\")\nplot!(hvec,err2,marker=:dot,label=\"Max error (Crank-Nicolson)\")\nplot!(hvec,hvec,linestyle=:dash,label=\"O(h)\")\nplot!(hvec,hvec.^2,linestyle=:dash,label=\"O(h^2)\")\nplot!(xaxis=:log,yaxis=:log,legend=:bottomright)\n", "meta": {"hexsha": "db0751b20d6cf6639169347f31b41baf26c91914", "size": 2198, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "week3/fd_heat_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": "week3/fd_heat_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": "week3/fd_heat_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": 25.2643678161, "max_line_length": 83, "alphanum_fraction": 0.5959963603, "num_tokens": 830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731137267749, "lm_q2_score": 0.8872045884979137, "lm_q1q2_score": 0.8540880037219686}}
{"text": "# Input data for generation of the cellular complex shown in figure of Data 2.1.2\n\nV = [\n    0.0 1.5 3.0 1.0 1.5 2.0 1.0 1.5 2.0 0.0 1.5 3.0;\n    0.0 0.0 0.0 1.0 1.0 1.0 2.0 2.0 2.0 3.0 3.0 3.0\n];\nEV = [\n    [1,  2], [2,  3], [ 4,  5], [ 5,  6],\n    [7,  8], [8,  9], [10, 11], [11, 12],\n    [1, 10], [4,  7], [ 6,  9], [ 3, 12],\n    [2,  5], [8, 11]\n];\nFV = [\n    [1, 2, 4, 5, 7, 8, 10, 11],\n    [2, 3, 5, 6, 8, 9, 11, 12],\n    [4, 5, 6, 7, 8, 9]\n];\n\n# The function K returns the Julia SparseArrays matrix providing\n#  the characteristic matrix K\ud835\udc5f given as input an array CV\n#  specifying each \ud835\udc5f-cell as array of vertex indices.\n\nfunction K( CV )\n    I = vcat( [ [k for h in CV[k]] for k=1:length(CV) ]...)\n    J = vcat( CV...)\n    X = Int8[1 for k=1:length(I)]\n    return SparseArrays.sparse(I, J, X)\nend\n\n# Generation of the sparse binary matrices\n\ncopEV = K(EV);\ncopFV = K(FV);\n\nMatrix(copEV)\nMatrix(copFV)\n\nif todisplay\n    VV = [[k] for k in 1:size(V,2)];\n    GL.VIEW( GL.numbering(1.0)( (V, [VV, EV]),GL.COLORS[1],0.1 ) );\nend;\n\n# Boundary matrix generation\n# we construct the sparse matrix [\ud835\udf152] from the product of characteristic matrices EV and the transposed FV\n\nMatrix( copEV * copFV' )\n\ncopEF = (copEV * copFV') .\u00f7 2;\n\nMatrix(copEF)\n\nb1 = (copEF * sparse([1 1 1])') .% 2\nb2 = (copEF * sparse([1 1 0])') .% 2\n\nf1 = SparseArrays.findnz(b1)[1]\nf2 = SparseArrays.findnz(b2)[1]\n\ne1 = EV[f1]\ne2 = EV[f2]\n\nif todisplay\n    GL.VIEW( GL.numbering(1.0)( (V, [VV, e1]),GL.COLORS[1],0.1 ) );\n    GL.VIEW( GL.numbering(1.0)( (V, [VV, e2]),GL.COLORS[1],0.1 ) );\nend;\n", "meta": {"hexsha": "b386b3a6fc63ea9d73abb139de6c284ff5612931", "size": 1565, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "CAGD.jl/paper/examples/cellular_complex.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/cellular_complex.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/cellular_complex.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": 24.0769230769, "max_line_length": 106, "alphanum_fraction": 0.5616613419, "num_tokens": 715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133515091156, "lm_q2_score": 0.9086179043564152, "lm_q1q2_score": 0.8540220997248272}}
{"text": "#=\nIn this example we'll compare the optimization of a relatively simple problem: Logistic Regression.\n\nConsider a binary classification dataset\n  $\\Omega = \\{(x_i, y_i) \\subset \\mathbb{R}^p\\times\\{0,1\\}:\\ i = 1, \\dots, n\\}$.\n\nThe logistic regression problem defines a model\n$h_{\\beta}(x) = \\sigma(\\hat{x}^T \\beta) = \\sigma(\\beta_0 + x^T\\beta_{1:p})$,\nwhere\n$\\hat{x} = \\begin{bmatrix} 1 \\\\ x \\end{bmatrix}$.\nThe value of $\\beta$ is found by finding the maximum of the log-likelihood function\n  \n$$\\ell(\\beta) = \\frac{1}{n} \\sum_{i=1}^n y_i \\ln \\big(h_{\\beta}(x_i)\\big) + (1 - y_i) \\ln\\big(1 - h_{\\beta}(x_i)\\big).$$\n\nWe'll input the gradient of this function manually. It is given by\n\n$$\\nabla \\ell(\\beta) = \\frac{1}{n} \\sum_{i=1}^n \\big(y_i - h_{\\beta}(x_i)\\big) \\hat{x}_i = \\frac{1}{n} \\begin{bmatrix} e^T \\\\ X^T \\end{bmatrix} (y - h_{\\beta}(X)), $$\n\nwhere $e$ is the vector with all components equal to 1.\n\nDownload [data.csv](https://github.com/abelsiqueira/julia-tutorial-at-nlesc/raw/main/assets/data.csv) to follow the example.\n\nIn Python, we can define the function $-\\ell(\\beta)$ to minimize, and its derivatives, as follows:\n\n```python\nimport numpy as np\nimport pandas as pd\nfrom scipy.optimize import minimize\n\ndf = pd.read_csv('data.csv')\nX = df.iloc[:,0:-1].values\ny = df.iloc[:,-1].values\nn, p = X.shape\n\ndef sigmoid(t):\n    return 1 / (1 + np.exp(-t))\n\ndef myfun(beta):\n    hbeta = sigmoid(beta[0] + X.dot(beta[1:]))\n    return -np.sum(\n        y * np.log(hbeta + 1e-8) + (1 - y) * np.log(1 - hbeta + 1e-8)\n    ) / n\n\ndef myjac(beta):\n    hbeta = sigmoid(beta[0] + X.dot(beta[1:]))\n    dif = hbeta - y\n    return np.concatenate((np.array([np.sum(dif)]), X.T.dot(dif))) / n\n\nbeta0 = np.zeros(p + 1)\nres = minimize(myfun, beta0, jac=myjac, method='l-bfgs-b', tol=1e-4)\nbeta = res.x\nhbeta = sigmoid(beta[0] + X.dot(beta[1:]))\nypred = np.round(hbeta)\naccuracy = sum(y == ypred) / n\nprint('accuracy = ', accuracy)\n```\nIf you're using Jupyter, I also ask you to run\n```\n%%timeit\nres = minimize(myfun, beta0, jac=myjac, method='l-bfgs-b', tol=1e-4)\n```\nSo that we can compare the time\n\nHere's a similar Julia version\n=#\nusing CSV, DataFrames, Optim, LinearAlgebra\n\npath = joinpath(\"assets\", \"data.csv\")\ndf = DataFrame(CSV.File(path))\nX = Matrix(df[:,1:end-1])\ny = df[:,end]\nn, p = size(X)\n\nsigmoid(t) = 1 / (1 + exp(-t))\n\nfunction myfun(\u03b2, X, y)\n  @views h\u03b2 = sigmoid.(\u03b2[1] .+ X * \u03b2[2:end])\n  out = sum(\n    y\u1d62 * log(y\u0302\u1d62 + 1e-8) + (1 - y\u1d62) * log(1 - y\u0302\u1d62 + 1e-8)\n    for (y\u1d62, y\u0302\u1d62) in zip(y, h\u03b2)\n  )\n  return -out / length(y)\nend\n\nfunction myjac(out, \u03b2, X, y)\n  n = length(y)\n  @views \u03b4 = (sigmoid.(\u03b2[1] .+ X * \u03b2[2:end]) - y) / n\n  out[1] = sum(\u03b4)\n  out[2:end] .= X' * \u03b4\n  return out\nend\n\noutput = optimize(\n  \u03b2 -> myfun(\u03b2, X, y),\n  (out, \u03b2) -> myjac(out, \u03b2, X, y),\n  zeros(p + 1),\n  LBFGS(),\n  Optim.Options(\n    g_tol = 1e-4,\n  ),\n)\n\n\u03b2 = Optim.minimizer(output)\nh\u03b2 = sigmoid.(\u03b2[1] .+ X * \u03b2[2:end])\ny\u0302 = round.(h\u03b2)\naccuracy = sum(y .== y\u0302) / n\n\n#=\nThe beginning of the codes is similar: read the file, create `X` and `y`.\n\nWe then define the functions. Some main differences:\n- Instead of writing the objective vectorized, I use a loop over the indices.\n- To avoid creating a vector for `\u03b2[2:end]`, I use `@views` at the beginning of the line. The macro automatically transforms `\u03b2[2:end]` into `view(\u03b2, 2:end)`.\n- The Julia `myjac` function receives an additional argument for the memory that it should reuse (`gx`) for the output.\n\nNow, the specific part. In Python, we use SciPy's optimize, and in Julia we're using Optim.jl.\nThe arguments are similar, although Optim's arguments are positional.\n\nWe can benchmark Optim's code to compare against SciPy's optimize:\n=#\nusing BenchmarkTools\n\n\u03b2\u2080 = zeros(p + 1)\n@benchmark optimize(\n  \u03b2 -> myfun(\u03b2, X, y),\n  (out, \u03b2) -> myjac(out, \u03b2, X, y),\n  \u03b2\u2080,\n  LBFGS(),\n  Optim.Options(\n    g_tol = 1e-4,\n  ),\n)\n#=\nIn Julia, we don't have a single optimization library.\nIn fact, I'm co-creator of the [JuliaSmoothOptimizers](https://juliasmoothoptimizers.github.io) organization, which \"competes\" against Optim.\nWe focus on tools for Nonlinear Optimization developers, instead of focusing on users, so our basic interface is a lot more raw.\nOn the other hand, we claim that our methods are faster, but notice my bias.\n\nNLPModels alone doesn't have a simple user interface, so we create a struct `MyLogisticRegression` to hold the problem and to indicate the objective and gradient.\nThe struct fields are not obvious and you have to follow the docs of NLPModels to learn how to do it.\nBut you can check the speed gain.\n=#\n\nusing JSOSolvers, Logging, NLPModels\n\nstruct MyLogisticRegression <: AbstractNLPModel{Float64, Vector{Float64}}\n  meta :: NLPModelMeta{Float64, Vector{Float64}}\n  counters :: Counters\n  X\n  y\n\n  function MyLogisticRegression(X, y)\n    meta = NLPModelMeta(p+1, x0=zeros(p+1))\n    return new(meta, Counters(), X, y)\n  end\nend\n\nNLPModels.obj(nlp :: MyLogisticRegression, x) = myfun(x, nlp.X, nlp.y)\nNLPModels.grad!(nlp :: MyLogisticRegression, x, gx) = myjac(gx, x, nlp.X, nlp.y)\n\nnlp = MyLogisticRegression(X, y)\noutput = lbfgs(nlp, atol=1e-4, rtol=1e-4)\nprintln(output)\n\n@benchmark with_logger(NullLogger()) do\n  lbfgs(nlp, atol=1e-4, rtol=1e-4)\nend\n\n# TODO: Check progress of ManualNLPModels (check after 18-Oct)\n\n#=\nOne noteworthy aspect of this comparison is that Python uses the L-BFGS-B Fortran algorithm, which is a reference implementation of a classic method.\nThe Julia versions are pure Julia.\n=#", "meta": {"hexsha": "1cbd7206bf340272bd43d35d447cc4319a556b7e", "size": 5469, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "_literate/optimization.jl", "max_stars_repo_name": "chunggnuhc/julia-tutorial-at-nlesc", "max_stars_repo_head_hexsha": "af27c6085a2b251815e8d4224af65b6a88e36629", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-20T23:00:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-20T23:00:22.000Z", "max_issues_repo_path": "_literate/optimization.jl", "max_issues_repo_name": "chunggnuhc/julia-tutorial-at-nlesc", "max_issues_repo_head_hexsha": "af27c6085a2b251815e8d4224af65b6a88e36629", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-10-31T08:45:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-31T09:20:39.000Z", "max_forks_repo_path": "_literate/optimization.jl", "max_forks_repo_name": "chunggnuhc/julia-tutorial-at-nlesc", "max_forks_repo_head_hexsha": "af27c6085a2b251815e8d4224af65b6a88e36629", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-05T08:55:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-05T08:55:04.000Z", "avg_line_length": 31.4310344828, "max_line_length": 166, "alphanum_fraction": 0.6686780033, "num_tokens": 1816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308165850443, "lm_q2_score": 0.914900963114118, "lm_q1q2_score": 0.8539967530940547}}
{"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\n# Is the dot product commutative?\n# A*B' == B*A' ?\n=#\n\nusing LinearAlgebra\n\n# generate two 100-element random row vectors, transposed from default column layout.\na = randn(100)'\nb = randn(100)'\n\n# display vectors (in truncated form)\nprintln(\"Vector a with 100 elements:\")\ndisplay(a)\nprintln(\"\\n\")\n\nprintln(\"Vector b of the same size:\")\ndisplay(b)\nprintln(\"\\n\")\n\n# calculate dot products\ndp1 = dot(a, b) # a * b' also works\ndp2 = dot(b, a) # b * a'\n\n# display them\nprintln(\"Dot product of a and b is $(dp1)\")\nprintln(\"Dot product of b and a is $(dp2)\\n\")\n\n# are they equal?\nif dp1 == dp2\n  println(\"The dot product of the 100-element vector is commutative.\\n\")\nelse\n  println(\"Dot product is not commutative.\\n\")\nend\n\n# generate 1 row, 2 column array with random integers from -10:10\nc = rand(-10:10, 1, 2)\n\nd = rand(-10:10, 1, 2)\n\nprintln(\"Array c = $c\")\nprintln(\"Array d = $d\\n\")\n\ndp3 = c * d'\ndp4 = d * c'\n\nprintln(\"Dot product of c and d is $(dp3)\")\nprintln(\"Dot product of d and c is $(dp4)\")\n\nif dp3 == dp4\n  println(\"Thus, the dot product of the 2-element vector is commutative.\")\nelse\n  println(\"Dot product is not commutative\")\nend\n", "meta": {"hexsha": "9b5156235b5607385a285b3a09b895449e6cdbce", "size": 1290, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "linear-algebra-code-challenges/02DotProductCommutative.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/02DotProductCommutative.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/02DotProductCommutative.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.2413793103, "max_line_length": 85, "alphanum_fraction": 0.6821705426, "num_tokens": 392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.955981348882942, "lm_q2_score": 0.8933093996634686, "lm_q1q2_score": 0.8539871248600938}}
{"text": "using LinearAlgebra\r\nusing Dates\r\nusing Plots\r\n\r\ninclude(\"qr_factorization.jl\")\r\ninclude(\"truncated_svd.jl\")\r\n\r\n\"\"\"\r\nverifies <num_tests> times that ||Q*R - A||_2 <= min_error\r\n\"\"\"\r\nfunction test_qr_A(num_tests, min_error= 1e-13)\r\n    errors = 0\r\n\r\n    for i = 1:num_tests\r\n\r\n        #generating random matrix\r\n        rows = rand(10:100)\r\n        columns = rand(10:rows)\r\n        r = rand(10:columns)\r\n        #using SVD to obtain a rank r matrix\r\n        A = approx_matrix_svd(rand(rows,columns),r)\r\n\r\n        #calculating QR factorization\r\n        QR, v, u = allocate_matrices(A)\r\n        Q = rand(rows, columns)\r\n        qr_factorization!(A,QR,v,u)\r\n        get_Q!(QR,Q)\r\n        R = triu(QR)[1:columns,:]\r\n\r\n        #checking ||QR - A||\r\n        if (norm(Q*R - A) > min_error)\r\n            errors += 1\r\n        end   \r\n\r\n    end\r\n    return errors\r\nend\r\n\r\n\"\"\"\r\nverifies <num_tests> times that ||R - R_j||_2 <= min_error where R is the R \r\ncomputed by our QR factorization while R_j is the R computed by the \r\nJULIA's implementation\r\n\"\"\"\r\nfunction test_qr_R(num_tests, min_error = 1e-10)\r\n    errors = 0\r\n\r\n    for i = 1:num_tests\r\n\r\n        #generating random matrix\r\n        rows = rand(10:100)\r\n        columns = rand(10:rows)\r\n        r = rand(10:columns)\r\n        A = approx_matrix_svd(rand(rows,columns),r)\r\n\r\n        #calculating QR factorization\r\n        QR, v, u = allocate_matrices(A)\r\n        qr_factorization!(A,QR,v,u)\r\n        Q_j,R_j = qr(A)\r\n        R = triu(QR)[1:columns,:]\r\n\r\n        #checking ||R - R_j||\r\n        if (norm(R - R_j) > min_error)\r\n            errors += 1\r\n        end   \r\n\r\n    end\r\n    return errors\r\nend\r\n\r\n\"\"\"\r\nverifies Q_t_times_A() function\r\n\"\"\"\r\nfunction test_qr_multiplication(num_tests, min_error = 1e-10)\r\n    errors = 0\r\n\r\n    for i = 1:num_tests\r\n        #generating random matrix\r\n        rows = rand(10:100)\r\n        columns = rand(10:rows)\r\n        r = rand(10:columns)\r\n        A = approx_matrix_svd(rand(rows,columns),r)\r\n\r\n        #calculating QR factorization\r\n        QR, v, u = allocate_matrices(A)\r\n        qr_factorization!(A,QR,v,u)\r\n        Q_j,R_j = qr(A)\r\n        W = zeros(rows,columns)\r\n        Q_t_times_A!(QR,A,W)\r\n        W_j = Q_j'*A   \r\n\r\n        #checking ||W - W_j||\r\n        if (norm(W - W_j) > min_error)\r\n            errors += 1\r\n        end   \r\n\r\n    end\r\n    return errors\r\nend\r\n\r\nfunction qr_test(A)\r\n    QR, v, u = allocate_matrices(A)\r\n    qr_factorization!(A,QR,v,u)\r\nend\r\n\r\n\"\"\"\r\nDraws a plot that compares the time (in seconds) required by our implementation and the one built-in in Julia. \r\n\r\nThe algorithm generates Int((max_dimension - min_dimension) / step) + 1 random matrices of increasing dimension.\r\n\r\nAt step k, the matrix shape will be (min dimension+((k - 1) * step) x min dimension+((k - 1) * step)). The algorithm terminates when\r\nthe matrix shapes reach max dimension.\r\n\r\n\"\"\"\r\nfunction test_time_qr(min_dimension, max_dimension; step = 15)\r\n    plotly()\r\n    dim = Int((max_dimension - min_dimension) / step) + 1\r\n    x = zeros(dim)\r\n    y = zeros(dim,2)\r\n    for i = 0:dim-1\r\n        x[i+1] = i * step + min_dimension\r\n        A = rand(Int(x[i+1]),Int(x[i+1]))\r\n        y[i+1,1] = @elapsed qr_test(A)\r\n        y[i+1,2] = @elapsed qr(A)\r\n    end\r\n    plot(x, y, label = [\"Our QR\" \"Julia's QR\"], lw = 3)\r\nend", "meta": {"hexsha": "294af6790500859379e3ef46143ece09e29001df", "size": 3305, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test_qr.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": "test_qr.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": "test_qr.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.2301587302, "max_line_length": 133, "alphanum_fraction": 0.5697428139, "num_tokens": 941, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628703, "lm_q2_score": 0.9219218284193597, "lm_q1q2_score": 0.8539796324554982}}
{"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\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# ---\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\nusing LinearAlgebra\n\nw = (X'*X) \\ (X'*y)\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# ---\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\nf_pred(x::Real, w) = w[1]*x + w[2]\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", "meta": {"hexsha": "cee9096c699d12174f1d9b51c161079738423f2b", "size": 1789, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lecture_09/01-linear-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_09/01-linear-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_09/01-linear-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": 19.6593406593, "max_line_length": 161, "alphanum_fraction": 0.6327557295, "num_tokens": 551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067228145365, "lm_q2_score": 0.9059898127684335, "lm_q1q2_score": 0.8539014893357317}}
{"text": "\nfunction bisection(fun, a, b; threshold = 1e-10, maxiter = 100)\n    root = (a+b)/2\n    iter = 0\n    while (abs(fun(root)) > threshold) && (iter < maxiter)\n        if fun(a)*fun(root) < 0\n            b = root\n        else\n            a = root\n        end\n        root = (a+b)/2\n        iter += 1\n    end\n    if iter == maxiter\n        println(\"Maximal number of iterations reached in bisection method.\")\n    end\n    root\nend\n\n\n\n####################\n# Newton iterations\n#####################\n\n\"The abstract NonlinearSystem type represents a system of non-linear equations in n variables.\"\nabstract type NonlinearSystem\nend\n\n# Default numeric type is Float64\n# eltype(::Type{S}) where {S <: NonlinearSystem} = Float64\n\nfunction residual(sys::NonlinearSystem, x)\n    result = Array{eltype(sys)}(length(sys))\n    residual!(result, sys, x)\nend\n\nfunction jacobian(sys::NonlinearSystem, x)\n    J = Array{eltype(sys)}(size(sys))\n    jacobian!(J, sys, x)\nend\n\n\n\n\"\"\"\nApply Newton iterations with the given starting values to find the roots of the given\nsystem of equations. A convergence threshold and maximum number of iterations are optional.\n\nThe maximal step size in each iteration can be limited using `maxstep`.\n\nDamped Newton iterations can be achieved by supplying damping parameter 0 < alpha < 1.\n\"\"\"\nfunction newton(sys::NonlinearSystem, x0; threshold = 1e-6, alpha = 1, maxiter = 100, maxstep = 1e5, verbose = false)\n    n = length(x0)\n    S = Array{eltype(sys)}(undef, n)\n    J = Array{eltype(sys)}(undef, n, n)\n\n    residual!(S, sys, x0)\n    jacobian!(J, sys, x0)\n    c = cond(J)\n    threshold = max(threshold, eps(eltype(x0))*c)\n    u = J \\ S\n    if norm(alpha*u) > maxstep\n        u = u * maxstep/norm(u)\n    end\n    x1 = x0 - alpha*u\n\n    iter = 1\n    while norm(x1-x0) > threshold && iter < maxiter\n        iter += 1\n        x0 = x1\n        residual!(S, sys, x0)\n        jacobian!(J, sys, x0)\n        u = J \\ S\n        if norm(alpha*u) > maxstep\n            u = u * maxstep/norm(u)\n        end\n        x1 = x0 - alpha*u\n    end\n    if verbose\n        if iter == maxiter\n            println(\"Newton: maximum number of iterations, no convergence\")\n        else\n            println(\"Newton: Converged to solution in \", iter, \" iterations.\")\n        end\n    end\n    x1,iter,norm(x1-x0)\nend\n\n\n\"Invoke Newton but restart with smaller maximal step size if an error is thrown.\"\nfunction newton_with_restart(args...; maxstep = 1e5, maxiter = 100, verbose = false, options...)\n    local nx,iter,normx\n    nb_decreased = 0\n    try\n    nx,iter,normx = newton(args...; maxstep = maxstep, options...)\n    catch e\n        print(\"Error thrown by newton: \")\n        println(e)\n        iter = maxiter\n    end\n    while iter == maxiter\n        verbose && println(\"Decreasing step size.\")\n        maxstep /= 2\n        try\n            nx,iter,normx = newton(args...; maxstep = maxstep, verbose=verbose, options...)\n        catch e\n            print(\"Error thrown by newton: \")\n            println(e)\n            iter = maxiter\n        end\n        nb_decreased += 1\n        if nb_decreased > 20\n            error(\"Too many step decreases in newton_with_restart. Aborting.\")\n        end\n    end\n    nx,iter,normx\nend\n", "meta": {"hexsha": "e3873cad97623dbabacc3d02ac6e42fb427ce0f5", "size": 3201, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/rootfinding.jl", "max_stars_repo_name": "daanhb/GeneralizedGauss.jl", "max_stars_repo_head_hexsha": "ac3228d7813f98a0b804cf6e48c86d193344a741", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/rootfinding.jl", "max_issues_repo_name": "daanhb/GeneralizedGauss.jl", "max_issues_repo_head_hexsha": "ac3228d7813f98a0b804cf6e48c86d193344a741", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rootfinding.jl", "max_forks_repo_name": "daanhb/GeneralizedGauss.jl", "max_forks_repo_head_hexsha": "ac3228d7813f98a0b804cf6e48c86d193344a741", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8991596639, "max_line_length": 117, "alphanum_fraction": 0.5929397063, "num_tokens": 902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966717067252, "lm_q2_score": 0.9019206785067698, "lm_q1q2_score": 0.8537551124179796}}
{"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\tn = mat |> size |> first\n\tL = zeros(n, n)\n\tU = zeros(n, n)\n\n\tfor i in 1:n\n\t\tfor j in i:n\n\t\t\ts = 0\n\t\t\tfor k in 1:i\n\t\t\t\ts += L[i,k] * U[k,j]\n\t\t\tend\n\t\t\tU[i,j] = mat[i,j] - s\n\t\tend\n\n\t\tfor k in i:n\n\t\t\tif i == k\n\t\t\t\tL[i,i] = 1\n    \t\t\telse\n\t\t\t\ts = 0\n\t\t\t\tfor j in 1:i\n\t\t\t\t\ts += L[k,j] * U[j,i]\n\t\t\t\tend\n\t\t\t\tL[k,i] = (mat[k,i] - s) / U[i,i]\n\t\t\tend\n\t\tend\n\tend\n\n\treturn L, U\nend\n", "meta": {"hexsha": "3e919d6aa65c21859b37bf3e579454f8a5c161bf", "size": 536, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/matrix/lu_decompose.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/matrix/lu_decompose.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/matrix/lu_decompose.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": 15.7647058824, "max_line_length": 110, "alphanum_fraction": 0.5074626866, "num_tokens": 211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9674102571131692, "lm_q2_score": 0.8824278618165526, "lm_q1q2_score": 0.8536697646837753}}
{"text": "function errorCheck(a1,a2,p)\r\n    if length(a1)!= length(a2)\r\n        println(\"The arrays have different length\")\r\n        return -1\r\n        end\r\n        if p<1\r\n            println(\"the value attributed to 'p' must be at least 1\")\r\n            return -1\r\n        end\r\n    return 0\r\nend\r\n\r\nfunction euclidianDistance(a1,a2)\r\n        if errorCheck(a1,a2,1) !=-1\r\n                return sqrt((sum((a1-a2).^2)))\r\n        end\r\nend\r\n\r\n\r\nfunction manhattanDistance(a1,a2)\r\n        if errorCheck(a1,a2,1) !=-1\r\n                return sum(abs.((a1-a2)))\r\n        end\r\nend\r\n\r\n\r\nfunction cosineDistance(a1,a2)\r\n        if errorCheck(a1,a2,1) !=-1\r\n                return 1 - sum(a1.*a2)/(sqrt(sum(a1.^2))*sqrt(sum(a2.^2)))\r\n        end\r\nend\r\n\r\n\r\nfunction minkowskiDistance(a1,a2,p)\r\n        if errorCheck(a1,a2,p) !=-1\r\n                return (sum(abs.(a1-a2).^p))^1/p\r\n        end\r\nend\r\n\r\nfunction jaccardSimilarity(a1,a2)\r\n        if errorCheck(a1,a2,1) !=-1\r\n                return length(intersect(a1,a2))/length(union(a1,a2))\r\n        end\r\nend\r\n\r\nfunction jaccardDistance(a1,a2)\r\n        if errorCheck(a1,a2,1) !=-1\r\n                return 1 - jaccardSimilarity(a1,a2)\r\n        end\r\nend\r\n", "meta": {"hexsha": "bf938b75b8098749122cbb6757266a06cae5218c", "size": 1184, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Functions.jl", "max_stars_repo_name": "nicolasmagalhaes/DistanceAndSimilarity", "max_stars_repo_head_hexsha": "a3e85a17e7b1c218f1ece291fd49cc2f341405d2", "max_stars_repo_licenses": ["MIT"], "max_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": "nicolasmagalhaes/DistanceAndSimilarity", "max_issues_repo_head_hexsha": "a3e85a17e7b1c218f1ece291fd49cc2f341405d2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-07-02T22:34:57.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-02T22:34:57.000Z", "max_forks_repo_path": "src/Functions.jl", "max_forks_repo_name": "nicolasmagalhaes/DistanceAndSimilarity", "max_forks_repo_head_hexsha": "a3e85a17e7b1c218f1ece291fd49cc2f341405d2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2156862745, "max_line_length": 75, "alphanum_fraction": 0.5244932432, "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102571131693, "lm_q2_score": 0.8824278587245935, "lm_q1q2_score": 0.8536697616925825}}
{"text": "\"\"\"\n    newton(f, fprime, x0, e, n)\n\nCompute the root of the given function using Newton's method.\nUses the point at which tangent line intersects x-axis to find the next approximate of the root of function 'f', \nas such it requires initial approximation `x0` and `fprime`, the derivative of function `f`.\nNewton's method has very fast convergence provided a sufficiantly accurate initial approximation is chosen.\n\n    newton(f::Function, fprime::Function, x0::Float64, e::Float64, n::Integer)\n\n### OUTPUT:\n  * `p` - approximation of the root of the function `f` (Float64) or,\n  * `-1` - if `n` the maximum number of iterations was exceeded.\n\"\"\"\nfunction newton(f::Function, fprime::Function, x0::Float64, e::Float64, n::Integer)\n\n    Afx = []\n    \n    for i in 1:n\n\n        yprime = fprime(x0)\n        \n        if abs(yprime) < e\n            warn(\"First derivative is zero\")\n            return x0\n        end\n        \n        y = f(x0)\n        x1 = x0 - y / yprime\n        push!(Afx, f(x1))\n        \n        if abs(x1 - x0) < e\n            return x1\n        end\n        \n        x0 = x1\n    end\n\n    return -1\nend\n", "meta": {"hexsha": "63dd4208d920268dfcc3f17aa9ff21286477cb93", "size": 1115, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/newtons_method.jl", "max_stars_repo_name": "faruk-becirovic/Julia-Numerical-Alalysis", "max_stars_repo_head_hexsha": "aa5eea30a3862ad06bfe451b5478156bce5f31cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/newtons_method.jl", "max_issues_repo_name": "faruk-becirovic/Julia-Numerical-Alalysis", "max_issues_repo_head_hexsha": "aa5eea30a3862ad06bfe451b5478156bce5f31cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/newtons_method.jl", "max_forks_repo_name": "faruk-becirovic/Julia-Numerical-Alalysis", "max_forks_repo_head_hexsha": "aa5eea30a3862ad06bfe451b5478156bce5f31cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1951219512, "max_line_length": 113, "alphanum_fraction": 0.597309417, "num_tokens": 306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539661028358093, "lm_q2_score": 0.8947894654011352, "lm_q1q2_score": 0.8535988191672582}}
{"text": "using NewtonsMethod\nusing Test\n\n@testset \"NewtonsMethod.jl\" begin\n\n# several @test for the root of a known function, given the f and analytical f' derivatives\nf(x) = x - 10\nf\u2032(x)= 1\n@test newtonroot(f,f\u2032;x\u2080 = 0.0) == 10.0\n\nf(x) = x-cos(x)\nf\u2032(x)= 1+sin(x)\n@test newtonroot(f,f\u2032;x\u2080 = 0.0) == 0.7390851332151607\n\nf(x) = (x+5)^3\nf\u2032(x)= 3*(x+5)^2\n@test newtonroot(f,f\u2032;x\u2080 = 0.0) == -4.999999866018182\n\n# tests of those roots using the automatic differentiation version of the function\nf(x) = (x-1)^3\n@test newtonroot(f;x\u2080=0.0) == 0.9999998643434097\n\nf(x) = (x+1)^2\n@test newtonroot(f;x\u2080=0.0) == -0.9999999403953552\n\nf(x) = x^3 + x^2 + x - 1\n@test newtonroot(f;x\u2080=0.0) == 0.5436890126920766\n\n\n# test of finding those roots with a BigFloat and not just a Float64\nf(x) = x - BigFloat(sqrt(5))\n@test newtonroot(f;x\u2080 = 0.0) == BigFloat(sqrt(5))\n\nf(x) =x-BigFloat(pi)\n@test newtonroot(f;x\u2080 = 0.0) == BigFloat(pi)\n\n# test of non-convergence for a function without a root (e.g. f(x)=2+x^2)\nf(x) = x^2 + 2\n@test newtonroot(f;x\u2080 = 1.0) == nothing\n\n# test to ensure that the maxiter is working (e.g. what happens if you call maxiter = 5)\nf(x) = (x-1)^3\nf\u2032(x)= 3*(x-1)^2\n@test newtonroot(f,f\u2032;x\u2080 = 0.0,maxiter = 5) == nothing\n\nf(x) = (x-6)^6\n@test newtonroot(f;x\u2080 = 0.0, maxiter = 10) == nothing\n\n# test to ensure that tol is working\nf(x) = (x-1)^3\nf\u2032(x)= 3*(x-1)^2\n@test newtonroot(f,f\u2032;x\u2080 = 0.0,tol = 1E-20) == 0.9999999999999999\n\nf(x) = (x-6)^6\n@test newtonroot(f;x\u2080 = 0.0,tol = 1E-3) == 5.995101279575065\n\nend\n", "meta": {"hexsha": "1a6e898b052824ad9dcecd6109e7a3278d5f12ac", "size": 1497, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "zhaoshengEE/NewtonsMethod.jl", "max_stars_repo_head_hexsha": "da94d13331e42412bbe6bc613b025a90dbc3d37a", "max_stars_repo_licenses": ["MIT"], "max_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": "zhaoshengEE/NewtonsMethod.jl", "max_issues_repo_head_hexsha": "da94d13331e42412bbe6bc613b025a90dbc3d37a", "max_issues_repo_licenses": ["MIT"], "max_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": "zhaoshengEE/NewtonsMethod.jl", "max_forks_repo_head_hexsha": "da94d13331e42412bbe6bc613b025a90dbc3d37a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8103448276, "max_line_length": 91, "alphanum_fraction": 0.6399465598, "num_tokens": 647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660976007596, "lm_q2_score": 0.8947894562828415, "lm_q1q2_score": 0.8535988057844477}}
{"text": "# Theil.jl\n\n###### theil #####\n\"\"\"\n    theil(v)\n\n    Compute the Theil Index of a vector `v`.\n\n# Examples\n```julia\njulia> using Inequality\njulia> theil([8, 5, 1, 3, 5, 6, 7, 6, 3])\n0.10494562214323544\n```\n\"\"\"\ntheil(v::AbstractVector{<:Real})::Float64 = sum(v .* log.(v/Statistics.mean(v))) / sum(v)\n\n\n###### weighted theil #####\n\"\"\"\n    theil(v, w)\n\nCompute the Theil Index of a vector `v`, 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> theil([8, 5, 1, 3, 5, 6, 7, 6, 3], collect(0.1:0.1:0.9))\n0.08120013911680612\n```\n\"\"\"\nfunction theil(v::AbstractVector{<:Real}, w::AbstractVector{<:Real})::Float64\n    \n    checks_weights(v, w)\n\n    w = w[v .!= 0]\n    v = v[v .!= 0]\n\n    w = w/sum(w)\n    v = v / sum(v .* w) \n    return sum(v .* w .* log.(v))\nend\n\n\nfunction theil(v::AbstractVector{<:Real}, w::AbstractWeights)::Float64\n    \n    checks_weights(v, w)\n\n    w = w[v .!= 0]\n    v = v[v .!= 0]\n\n    w = w/w.sum\n    v = v / sum(v .* w) \n    return sum(v .* w .* log.(v))\nend\n\n\n\"\"\"\n    wtheil(v, w)\n\nCompute the Theil Index of `v` with weights `w`. See also [`theil`](@theil)\n\"\"\"\nwtheil(v::AbstractVector{<:Real}, w::AbstractVector{<:Real})::Float64 = theil(v,w) \n\nwtheil(v::AbstractVector{<:Real}, w::AbstractWeights)::Float64 = theil(v,w) \n", "meta": {"hexsha": "05c770bc404ef76ba3bfbed6a3ebd4d74bae6a7b", "size": 1391, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Theil.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/Theil.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/Theil.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": 20.4558823529, "max_line_length": 101, "alphanum_fraction": 0.5887850467, "num_tokens": 498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660949832346, "lm_q2_score": 0.8947894562828415, "lm_q1q2_score": 0.853598803442314}}
{"text": "\"\"\"\nnewton(f,dfdx,x\u2081)\n\nUse Newton's method to find a root of `f` starting from `x\u2081`, where\n`dfdx` is the derivative of `f`. Returns a vector of root estimates.\n\"\"\"\nfunction newton(f,dfdx,x\u2081)\n    # Operating parameters.\n    funtol = 100*eps();  xtol = 100*eps();  maxiter = 40;\n\n    x = [x\u2081]\n    y = f(x\u2081)\n    dx = Inf   # for initial pass below\n    k = 1\n\n    while (abs(dx) > xtol) && (abs(y) > funtol) && (k < maxiter)\n        dydx = dfdx(x[k])\n        dx = -y/dydx            # Newton step\n        push!(x,x[k]+dx)        # append new estimate\n\n        k += 1\n        y = f(x[k])\n    end\n\n    if k==maxiter\n        @warn \"Maximum number of iterations reached.\"\n    end\n\n    return x\nend\n\n\"\"\"\nsecant(f,x\u2081,x\u2082)\n\nUse the secant method to find a root of `f` starting from `x\u2081` and\n`x\u2082`. Returns a vector of root estimates.\n\"\"\"\nfunction secant(f,x\u2081,x\u2082)\n    # Operating parameters.\n    funtol = 100*eps();  xtol = 100*eps();  maxiter = 40;\n\n    x = [x\u2081,x\u2082]\n    y\u2081 = f(x\u2081); y\u2082 = 100;\n    dx = Inf   # for initial pass below\n    k = 2\n\n    while (abs(dx) > xtol) && (abs(y\u2082) > funtol) && (k < maxiter)\n        y\u2082 = f(x[k])\n        dx = -y\u2082 * (x[k]-x[k-1]) / (y\u2082-y\u2081)   # secant step\n        push!(x,x[k]+dx)        # append new estimate\n\n        k += 1\n        y\u2081 = y\u2082    # current f-value becomes the old one next time\n    end\n\n    if k==maxiter\n        @warn \"Maximum number of iterations reached.\"\n    end\n\n    return x\nend\n\n\"\"\"\nnewtonsys(f,jac,x\u2081)\n\nUse Newton's method to find a root of a system of equations,\nstarting from `x\u2081`. The functions `f` and `jac should return the\nresidual vector and the Jacobian matrix, respectively. Returns\nhistory of root estimates as a vector of vectors.\n\"\"\"\nfunction newtonsys(f,jac,x\u2081)\n    # Operating parameters.\n    funtol = 1000*eps();  xtol = 1000*eps();  maxiter = 40;\n\n    x = [float(x\u2081)]\n    y,J = f(x\u2081),jac(x\u2081)\n    dx = Inf   # for initial pass below\n    k = 1\n\n    while (norm(dx) > xtol) && (norm(y) > funtol) && (k < maxiter)\n        dx = -(J\\y)             # Newton step\n        push!(x,x[k] + dx)    # append to history\n        k += 1\n        y,J = f(x[k]),jac(x[k])\n    end\n\n    if k==maxiter\n        @warn \"Maximum number of iterations reached.\"\n    end\n\n    return x\nend\n\n\"\"\"\nfdjac(f,x0,y0)\n\nCompute a finite-difference approximation of the Jacobian matrix for\n`f` at `x0`, where `y0`=`f(x0)` is given.\n\"\"\"\nfunction fdjac(f,x0,y0)\n\n\u03b4 = sqrt(eps())   # FD step size\nm,n = length(y0),length(x0)\nif n==1\n    J = (f(x0+\u03b4) - y0) / \u03b4\nelse\n    J = zeros(m,n)\n    I\u2099 = I(n)\n    for j = 1:n\n        J[:,j] = (f(x0 + \u03b4*I\u2099[:,j]) - y0) / \u03b4\n    end\nend\n\nreturn J\nend\n\n\"\"\"\nlevenberg(f,x\u2081,tol)\n\nUse Levenberg's quasi-Newton iteration to find a root of the system\n`f`, starting from `x\u2081`, with `tol` as the stopping tolerance in\nboth step size and residual norm. Returns root estimates as a\nmatrix, one estimate per column.\n\"\"\"\nfunction levenberg(f,x\u2081,tol=1e-12)\n\n# Operating parameters.\nftol = tol;  xtol = tol;  maxiter = 40;\n\nx = zeros(length(x\u2081),maxiter)\nx = [float(x\u2081)]\nf\u2096 = f(x\u2081)\nk = 1;  s = Inf;\nA\u2096 = fdjac(f,x\u2081,f\u2096)   # start with FD Jacobian\njac_is_new = true\n\n\u03bb = 10;\nwhile (norm(s) > xtol) && (norm(f\u2096) > ftol) && (k < maxiter)\n    # Compute the proposed step.\n    B = A\u2096'*A\u2096 + \u03bb*I\n    z = A\u2096'*f\u2096\n    s = -(B\\z)\n\n    xnew = x[k] + s\n    fnew = f(xnew)\n\n    # Do we accept the result?\n    if norm(fnew) < norm(f\u2096)    # accept\n        y = fnew - f\u2096\n        push!(x,xnew)\n        f\u2096 = fnew\n        k += 1\n\n        \u03bb = \u03bb/10   # get closer to Newton\n        # Broyden update of the Jacobian.\n        A\u2096 = A\u2096 + (y-A\u2096*s)*(s'/(s'*s))\n        jac_is_new = false\n    else                       # don't accept\n        # Get closer to steepest descent.\n        \u03bb = 4\u03bb\n        # Re-initialize the Jacobian if it's out of date.\n        if !jac_is_new\n            A\u2096 = fdjac(f,x[k],f\u2096)\n            jac_is_new = true\n        end\n    end\nend\n\nif (norm(f\u2096) > 1e-3)\n    @warn \"Iteration did not find a root.\"\nend\n\nreturn x\nend\n", "meta": {"hexsha": "b24779200c1de35478ac63997ba4006e17842088", "size": 3950, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chapter04.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/chapter04.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/chapter04.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": 22.5714285714, "max_line_length": 68, "alphanum_fraction": 0.5541772152, "num_tokens": 1356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897459384733, "lm_q2_score": 0.9073122119620788, "lm_q1q2_score": 0.8535900253786783}}
{"text": "#\n###\n# Lagrange polynomial matrices\n###\n\n\"\"\"\n    Compute the Lagrange interpolation matrix from xi to xo.\n    lagrange_poly_interp_mat(x\u2092,x\u1d62)\n\"\"\"\nfunction lagrange_interp_mat(xo,xi)\n\n    no = length(xo)\n    ni = length(xi)\n\n    a = ones(1,ni)\n    for i=1:ni\n        for j=1:(i-1)  a[i]=a[i]*(xi[i]-xi[j]); end\n        for j=(i+1):ni a[i]=a[i]*(xi[i]-xi[j]); end\n    end\n    a = 1 ./ a # Barycentric weights\n\n    J = zeros(no,ni)\n    s = ones(1,ni)\n    t = ones(1,ni)\n    for i=1:no\n        x = xo[i]\n        for j=2:ni\n            s[j]      = s[j-1]    * (x-xi[j-1]   )\n            t[ni+1-j] = t[ni+2-j] * (x-xi[ni+2-j])\n        end\n        J[i,:] = a .* s .* t\n    end\n\n    return J\nend\n\n\"\"\"\n Compute derivative matrix for lagrange\n interpolants on points [x]\n\"\"\"\nfunction lagrange_deriv_mat(x)\n    \n    n = length(x)\n\n    a = ones(1,n)\n    for i=1:n\n        for j=1:(i-1) a[i]=a[i]*(x[i]-x[j]) end\n        for j=(i+1):n a[i]=a[i]*(x[i]-x[j]) end\n    end\n    a = 1 ./ a # Barycentric weights\n\n    # diagonal elements\n    D = x .- x'\n    for i=1:n D[i,i] = 1. end\n    D = 1 ./ D\n    for i=1:n\n        D[i,i] = 0.\n        D[i,i] = sum(D[i,:])\n    end\n\n    # off-diagonal elements\n    for j=1:n for i=1:n\n        if(i!=j) D[i,j] = a[j] / (a[i]*(x[i]-x[j])) end\n    end end\n\n    return D\nend\n\n", "meta": {"hexsha": "20377939891d6810d5221bc3758389fbb380ddcf", "size": 1291, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Spectral/LagrangeMatrices.jl", "max_stars_repo_name": "vpuri3/SpectralElements.jl", "max_stars_repo_head_hexsha": "276bdd7fdfc67796fef64a20e0411044da70928b", "max_stars_repo_licenses": ["MIT"], "max_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/LagrangeMatrices.jl", "max_issues_repo_name": "vpuri3/SpectralElements.jl", "max_issues_repo_head_hexsha": "276bdd7fdfc67796fef64a20e0411044da70928b", "max_issues_repo_licenses": ["MIT"], "max_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/LagrangeMatrices.jl", "max_forks_repo_name": "vpuri3/SpectralElements.jl", "max_forks_repo_head_hexsha": "276bdd7fdfc67796fef64a20e0411044da70928b", "max_forks_repo_licenses": ["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.7101449275, "max_line_length": 60, "alphanum_fraction": 0.4709527498, "num_tokens": 494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075701109193, "lm_q2_score": 0.8872045847699186, "lm_q1q2_score": 0.8535862472442535}}
{"text": "################################################################################\n\n\"\"\"\n    euclDist(arr::Array{T, 1}, h::Array{T, 1}) where {T <: Number}\n\n# Description\nEuclidean distance.\n\n# Examples\n```\njulia> euclDist(collect(1:10), fill(5, 10))\n9.219544457292887\n```\n\nSee also: [`bhattDist`](@ref), [`amplitude`](@ref)\n\"\"\"\nfunction euclDist(arr::Array{T,1}, h::Array{T,1}) where {T <: Number}\n  return (arr .- h) .^ 2 |> sum |> sqrt\nend\n\n\"\"\"\n    bhattDist(arr::Array{T, 1}, h::Array{T, 1}) where {T <: Number}\n\n# Description\nBhattacharyya distance.\n\n# Examples\n```\njulia> bhattDist(collect(1:10), fill(5, 10))\n-3.936532135073928\n```\n\nSee also: [`euclDist`](@ref), [`amplitude`](@ref)\n\"\"\"\nfunction bhattDist(arr::Array{T,1}, h::Array{T,1}) where {T <: Number}\n  return -log((arr .* h .|> sqrt |> sum) + 1)\nend\n\n\"\"\"\n    amplitude(arr::Array{T, 1}) where {T <: Number}\n\n# Description\nAmplitude.\n\n# Examples\n```\njulia> amplitude(collect(1:10))\n19.621416870348583\n```\n\nSee also: [`euclDist`](@ref), [`bhattDist`](@ref)\n\"\"\"\nfunction amplitude(arr::Array{T,1}) where {T <: Number}\n  return arr .^ 2 |> sum |> sqrt\nend\n\n################################################################################\n", "meta": {"hexsha": "d84767534a3f647e43ae86e88acd3e83bf4f2e83", "size": 1196, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distance.jl", "max_stars_repo_name": "DanielRivasMD/HiddenMarkovModelReaders.jl", "max_stars_repo_head_hexsha": "9962bd16f18b6e8cd54a8701faf2c90d71ffc639", "max_stars_repo_licenses": ["MIT"], "max_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": "DanielRivasMD/HiddenMarkovModelReaders.jl", "max_issues_repo_head_hexsha": "9962bd16f18b6e8cd54a8701faf2c90d71ffc639", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-28T11:43:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T11:43:33.000Z", "max_forks_repo_path": "src/distance.jl", "max_forks_repo_name": "DanielRivasMD/HiddenMarkovModelReaders.jl", "max_forks_repo_head_hexsha": "9962bd16f18b6e8cd54a8701faf2c90d71ffc639", "max_forks_repo_licenses": ["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.6206896552, "max_line_length": 80, "alphanum_fraction": 0.5301003344, "num_tokens": 369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611620335328, "lm_q2_score": 0.8887587993853655, "lm_q1q2_score": 0.8535294333452571}}
{"text": "export eye\n\n\"\"\"\n`eye(T,n)` returns an `n`-by-`n` identity matrix whose entries\nare numbers of type `T` (`Float64` by default).\n\"\"\"\nfunction eye(T,n)\n    A = zeros(T,n,n)\n    for j=1:n\n        A[j,j] = 1\n    end\n    return A\nend\n\neye(n) = eye(Float64,n)\n", "meta": {"hexsha": "54396f945ff53261f6584a095291f27cc74bfc79", "size": 253, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/my_eye.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SimpleTools.jl-4696fa5f-36f0-5b18-99a6-fef83351280f", "max_stars_repo_head_hexsha": "daa8c7af9616567691f63d596b1de74e763178bf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/my_eye.jl", "max_issues_repo_name": "UnofficialJuliaMirror/SimpleTools.jl-4696fa5f-36f0-5b18-99a6-fef83351280f", "max_issues_repo_head_hexsha": "daa8c7af9616567691f63d596b1de74e763178bf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/my_eye.jl", "max_forks_repo_name": "UnofficialJuliaMirror/SimpleTools.jl-4696fa5f-36f0-5b18-99a6-fef83351280f", "max_forks_repo_head_hexsha": "daa8c7af9616567691f63d596b1de74e763178bf", "max_forks_repo_licenses": ["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.8125, "max_line_length": 62, "alphanum_fraction": 0.5770750988, "num_tokens": 87, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.930458253565792, "lm_q2_score": 0.917302657890151, "lm_q1q2_score": 0.8535118290517291}}
{"text": "# Continuation of ex 7.13, Least Squares WRM\n\nusing NumericalMethodsforEngineers\nusing Test\n\n@sym begin\n  ClearAll(xi, yi, N1, Y, Ydotdot, C11, ytilde1, ytilde2)\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 = (27/2)*(a-b)\n  \u03a81(x_) := x^3 - x^2\n  # C2 = -(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  Ydotdot(x_) = D(Y(x), x, 2)\n  R(x_) := Ydotdot(x) - 3*x - 4*Y(x)\n  Rdota(x_) = D(R(x), a)\n  Rdotb(x_) = D(R(x), b)\n  sol = Solve([Integrate(R(x)*Rdota(x), [x, 0, 1]), Integrate(R(x)*Rdotb(x), [x, 0, 1])], [a, b])\n  SetJ(r, ToString(Simplify(R(x))))\n  SetJ(a, ToString(sol[1][1][2]))\n  SetJ(b, ToString(sol[1][2][2]))\n  ytilde1 = Simplify(Y(x) ./ (a => sol[1][1][2]))\n  ytilde2 = Simplify(ytilde1 ./ (b => sol[1][2][2]))\n  SetJ(y, ToString(Simplify(Expand(ytilde2))));\nend\n\nprintln(\"\\n\\nExample 7.17b: y'' = 3x + 4y, y(0)=0, y(1)=1\")\nprintln(\"by 2-point least squares Weighted Residual Method\")\n@sym Println(\"\\nY(x) = $(Simplify(Expand(Y(x))))\\n\")\n@sym Println(\"R(x) = $(R(x))\\n\")\n@eval a = $(Meta.parse(a))\n@eval b = $(Meta.parse(b))\nprintln(\"(a,b) = $((a, b))\\n\")\nprintln(\"C1 = $((27/2*(a-b)))\\n\")\nprintln(\"C2 = $(-(9/2*(2a-b)))\\n\")\n@eval rf_2pt_leastsquares(x, a, b) = $(Meta.parse(r))\n@eval ytilde_2pt_leastsquares(x) = $(Meta.parse(y))\nprintln()\n\nrf_2pt_leastsquares_1(x) = rf_2pt_leastsquares(x, a, b)\nprintln()\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\"\n@test y == \"(1/9693)*x*(2420 - 3311x + 10584*x^2)\"\n#@test (quadgk(rf_2pt_leastsquares_1, 0, 1))[1] < 5*eps()\n\n", "meta": {"hexsha": "42e113ab69ec91eb214a1cb265e6b4bc5bb296b2", "size": 1742, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ch07/WRM/Ex.7.17b.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.17b.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.17b.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": 31.6727272727, "max_line_length": 106, "alphanum_fraction": 0.5476463835, "num_tokens": 821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191297273498, "lm_q2_score": 0.8933094039240553, "lm_q1q2_score": 0.8533955623339862}}
{"text": "#!/usr/bin/env julia\n\n\"\"\"\n# Problem 1: Multiples of 3 and 5\n\nIf we list all the natural numbers below 10 that are multiples of 3 or 5, we\nget 3, 5, 6 and 9. The sum of these multiples is 23.\n\nFind the sum of all the multiples of `m` or `n` below `limit`.\n\"\"\"\nmodule Problem001\n\ninclude(\"Sequences.jl\")\n\n\"\"\"\n    solve(; m::Integer = 3, n::Integer = 5, limit::Integer = 1000)\n\nReturns the solution for [`Problem001`](@ref) with the given parameters.\n\n## Preconditions\n- `m > 0`\n- `n > 0`\n- `limit > 0`\n\"\"\"\nfunction solve(; m::Integer = 3, n::Integer = 5, limit::Integer = 1000)\n    m_sum = sum_divisible_by(m, limit)\n    n_sum = sum_divisible_by(n, limit)\n    lcm_sum = sum_divisible_by(lcm(m, n), limit)\n    return m_sum + n_sum - lcm_sum\nend\n\n\"\"\"\n    sum_divisible_by(n::Integer, limit::Integer)\n\nReturns the sum of natural numbers below `limit` that are divisible by `n`.\n\n## Preconditions\n- `n > 0`\n- `limit > 0`\n\n## Examples\n```jldoctest\njulia> sum_divisible_by(3, 10)\n18\n\njulia> sum_divisible_by(5, 10)\n5\n\njulia> sum_divisible_by(5, 5)\n0\n```\n\"\"\"\nfunction sum_divisible_by(n::Integer, limit::Integer)\n    return Sequences.arithmetic_series(n, (limit - 1) \u00f7 n, n)\nend\n\nend\n", "meta": {"hexsha": "d8b91a593c5a92465db3078b24f0e20181f732a8", "size": 1175, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "jl/src/Problem001.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/Problem001.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/Problem001.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": 20.2586206897, "max_line_length": 76, "alphanum_fraction": 0.6689361702, "num_tokens": 385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191297273498, "lm_q2_score": 0.8933094003735664, "lm_q1q2_score": 0.8533955589421361}}
{"text": "#Function that group the mainly statistics moments that include nan values\n\nfunction nanmean(vector::Vector)\nN=length(vector);\ns=0.0;                                        #--sample mean sum\nm=0.0;                                        #--counter for the sample size\n  for i=1:N\n     if isnan(vector[i])==0;                  #--make sure to sum numeric values\n        m=m+1;\n        s=s+vector[i];\n     end\n  end\nmu=s/m;\nmu\nend\n\n\n#In nanvar.jl\n#https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Higher-order_statistics\nfunction nanvar(vector::Array)\nN=length(vector);  \nm=0.0;             #---Initialize counter for samples\nmu=0.0;            #---Initialize mean\nM2=0.0;            #---Intitialize sum(x_i-mu)^2\n\n for i=1:N\n      if isnan(vector[i])==0;                  #--make sure to sum numeric values\n         m=m+1;\n         delta=vector[i]-mu;\n         mu=mu+delta/m;\n         M2=M2+delta*(vector[i]-mu);\n      end\n end\n if m<2;\n    return NaN\n else\n    return M2/m\n end   \nend\n\n\n#In nanskew.jl\n#https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Higher-order_statistics\nfunction nanskew(vector::Array)\nN=length(vector);  \nm=0.0;             #---Initialize counter for samples\nmu=0.0;            #---Initialize mean\nM2=0.0;            #---Intitialize sum(x_i-mu)^2\nM3=0.0;            #---Intitialize sum(x_i-mu)^2\nM4=0.0;            #---Intitialize sum(x_i-mu)^2\n\n for i=1:N\n      if isnan(vector[i])==0;                  #--make sure to sum numeric values\n         n1=m;\n         m=m+1;\n         delta=vector[i]-mu;\n         delta_m=delta/m;\n         delta_m2=delta_m*delta_m;\n         term1=delta*delta_m*n1;\n         mu=mu+delta_m;\n         M3=M3+term1*delta_m*(m-2)-3*delta_m*M2\n         M2=M2+term1;\n      end\n end\nskewness=sqrt(m)*M3/M2^(3/2); \nreturn skewness\nend\n\n\n#In nankurt.jl\n#https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Higher-order_statistics\nfunction nankurt(vector::Array)\nN=length(vector);  \nm=0.0;             #---Initialize counter for samples\nmu=0.0;            #---Initialize mean\nM2=0.0;            #---Intitialize sum(x_i-mu)^2\nM3=0.0;            #---Intitialize sum(x_i-mu)^2\nM4=0.0;            #---Intitialize sum(x_i-mu)^2\n\n for i=1:N\n      if isnan(vector[i])==0;                  #--make sure to sum numeric values\n         n1=m;\n         m=m+1;\n         delta=vector[i]-mu;\n         delta_m=delta/m;\n         delta_m2=delta_m*delta_m;\n         term1=delta*delta_m*n1;\n         mu=mu+delta_m;\n         M4=M4+term1*delta_m2*(m*m-3*m+3)+6*delta_m2*M2-4*delta_m*M3\n         M3=M3+term1*delta_m*(m-2)-3*delta_m*M2\n         M2=M2+term1;\n      end\n end\n#kurtosis=(m*M4)/(M2*M2)-3;      #--normalized\nkurtosis=(m*M4)/(M2*M2); \nreturn kurtosis\nend\n\n\n\n", "meta": {"hexsha": "8bd5fb6dceed66153d451ba1a0dd86ece6dbe774", "size": 2733, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nan_statsjc.jl", "max_stars_repo_name": "jccuevasb/julia_packages", "max_stars_repo_head_hexsha": "9b3054d0c61069e7287e17c577a5ac4ec22ea5a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/nan_statsjc.jl", "max_issues_repo_name": "jccuevasb/julia_packages", "max_issues_repo_head_hexsha": "9b3054d0c61069e7287e17c577a5ac4ec22ea5a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/nan_statsjc.jl", "max_forks_repo_name": "jccuevasb/julia_packages", "max_forks_repo_head_hexsha": "9b3054d0c61069e7287e17c577a5ac4ec22ea5a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0594059406, "max_line_length": 90, "alphanum_fraction": 0.5620197585, "num_tokens": 874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377237352755, "lm_q2_score": 0.89029422102812, "lm_q1q2_score": 0.8533805960789643}}
{"text": "using Test\n\nimport LinearAlgebra.diagm\nimport LinearAlgebra.triu\nimport LinearAlgebra.I\nimport LinearAlgebra.det\n\ninclude(\"../../../lib/KTBC.jl\")\nimport .KTBC.CreateKTBC\n\nfunction createU(dim=3)\n    return I(dim) - diagm(1 => ones(dim - 1))\nend\n\nfunction createS(dim=3)\n    return triu(ones(dim, dim))\nend\n\n# 3\nU\u2085 = createU(5)\nS\u2085 = createS(5)\n\nU\u2085 * S\u2085\n\n@test S\u2085 == inv(U\u2085)\n\n# 4\nS\u2084 = triu(ones(4, 4))\n\nS\u2084 * S\u2084'\n\n# 5\nKTBC\u2082 = CreateKTBC()\nK\u2082 = convert(Array{Int}, KTBC\u2082[1])\n\ndet(K\u2082)\ninv(K\u2082)\n\n@test inv(K\u2082) * det(K\u2082) == [\n  2.0 1.0\n  1.0 2.0\n]\n\nKTBC\u2083 = CreateKTBC(3)\nK\u2083 = convert(Array{Int}, KTBC\u2083[1])\n\ndet(K\u2083)\ninv(K\u2083)\n\n@test round.(Int, inv(K\u2083) * det(K\u2083)) == [\n  3 2 1\n  2 4 2\n  1 2 3\n]\n\n# 6\nfunction klcounter(n=4)\n    j = 1\n    result = zeros(n, n)\n    while j <= n\n        i = j\n        while i <= n\n            result[i, j] = (n - i + 1) * j\n            i += 1\n        end\n        j += 1\n    end\n    return result\nend\n\n@test klcounter() == [\n  4.0  0.0  0.0  0.0\n  3.0  6.0  0.0  0.0\n  2.0  4.0  6.0  0.0\n  1.0  2.0  3.0  4.0\n]\n\n# 7\nKTBC\u2083 = CreateKTBC(3)\n\nT\u2083 = convert(Array{Int}, KTBC\u2083[2])\nK\u2083 - T\u2083\n\nu = [\n  1\n  0\n  0\n]\nv\u1d40 = transpose(u)\n\n@test u * v\u1d40 == K\u2083 - T\u2083\n\ninvT\u2083 = inv(T\u2083)\ninvK\u2083 = inv(K\u2083)\n\n@test round.(Int, 4(invT\u2083 - invK\u2083)) == [\n 9  6  3\n 6  4  2\n 3  2  1\n]\n\nu = [\n  3\n  2\n  1\n]\nv\u1d40 = transpose(u)\n\n@test 1 / 4 * u * v\u1d40 == round.(invT\u2083 - invK\u2083; digits=2)\n", "meta": {"hexsha": "b7e91324fe168bfa1c4e7775d9747462971bf07b", "size": 1364, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "1.AppliedLInearAlgebra/1.FourSpecialMatrices/ProblemSet/3-7.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/3-7.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/3-7.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": 12.4, "max_line_length": 55, "alphanum_fraction": 0.534457478, "num_tokens": 680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172615983309, "lm_q2_score": 0.8991213705121082, "lm_q1q2_score": 0.853191788750888}}
{"text": "# This file investigates MSE with respect to free variables \n\nusing FractalTools \nusing GeometryBasics\nusing Makie \n\n# Construct interpolation data \nf = FractalTools.ackley\n\u03b1 = 10\nngon = [BigFloat.([-1., -1.]), BigFloat.([1., -1]), BigFloat.([0., 1.])] * \u03b1\nnpts = 100\npts = getdata(f, ngon, npts)\n\n# Construct test data \ntpts = getdata(ngon, npts)\nntpts = length(tpts)\n\n# Compute errors \nfvals = map(pt -> f(pt...), tpts) \nfreevars = 0.001 : 0.001 : 0.05\nmse = map(freevars) do freevar \n    interp = interpolate(pts, Interp2D(freevar))\n    ivals = map(pt -> interp(pt...), tpts)\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 Interpolation MSE\") \nstem!(ax, freevars, mse, color=:black)\nsave(joinpath(@__DIR__, \"interp2d_mse.png\"), fig)\ndisplay(fig)\n\n# using FractalTools \n# using GeometryBasics\n# using Makie \n\n# # Construct interpolation data \n# f(x, y) = -20*exp(-0.2 * \u221a(0.5*(x^2+y^2))) -\n#             exp(0.5*(cos(2\u03c0*x)+cos(2\u03c0*y))) + \n#             MathConstants.e + 20 \n\n# # f(x, y) = x^2 + y^2 + 1\n\n# # f(x, y) = sin(x) * cos(y)\n# ngon = Triangle(\n#     Point(BigFloat(-5.), BigFloat(-5.)), \n#     Point(BigFloat(5), BigFloat(-5.)), \n#     Point(BigFloat(0), BigFloat(5.)))\n\n# # ngon = [BigFloat.([-5,5]),\n# #         BigFloat.([-5,-5]),\n# #         BigFloat.([5,-5]),\n# #         BigFloat.([5,5])\n# # ]\n# npts = 100\n# pts = getdata(f, ngon, npts)\n\n# # Construct test data \n# tpts = getdata(ngon, npts)\n# ntpts = length(tpts)\n\n# # Compute errors \n# fvals = map(pt -> f(pt...), tpts) \n# freevars = 0.001 : 0.001 : 0.05\n# mse = map(freevars) do freevar \n#     interp = interpolate(pts, Interp2D(freevar))\n#     ivals = map(pt -> interp(pt...), tpts)\n#     sum((fvals - ivals).^2) / ntpts\n# end \n\n# # Plot mse \n# fig = Figure() \n# ax = fig[1, 1] = Axis(fig, xlabel=\"Free Variable\", ylabel=\"MSE\", title=\"2D Interpolation MSE\") \n# stem!(ax, freevars, mse, color=:black)\n# save(joinpath(@__DIR__, \"interp2d_mse.png\"), fig)\n# display(fig)\n", "meta": {"hexsha": "f1bd9fdcbd9bc4a9e22b02cc98ae6477896d2d3e", "size": 2037, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "experiment_2/interpolation_mse_vs_freevars/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_freevars/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_freevars/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": 26.1153846154, "max_line_length": 97, "alphanum_fraction": 0.5925380461, "num_tokens": 737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172572644806, "lm_q2_score": 0.8991213732152424, "lm_q1q2_score": 0.8531917874192813}}
{"text": "include(\"misc.jl\")\r\n\r\nfunction findMin(funObj,w;maxIter=100,epsilon=1e-2,derivativeCheck=false,verbose=true)\r\n\t# funObj: function that returns (objective,gradient)\r\n\t# w: initial guess\r\n\t# maxIter: maximum number of iterations\r\n\t# epsilon: stop if the gradient gets below this\r\n\t# derivativeCheck: whether to check against numerical gradient\r\n\r\n\t# Evalluate the intial objective and gradient\r\n\t(f,g) = funObj(w)\r\n\r\n\t# Optionally check if gradient matches finite-differencing\r\n\tif derivativeCheck\r\n\t\tg2 = numGrad(funObj,w)\r\n\r\n\t\tif maximum(abs.(g-g2)) > 1e-4\r\n\t\t\t@show([g g2])\r\n\t\t\t@printf(\"User and numerical derivatives differ\\n\")\r\n\t\t\tsleep(1)\r\n\t\telse\r\n\t\t\t@printf(\"User and numerical derivatives agree\\n\")\r\n\t\tend\r\n\tend\r\n\r\n\t# Initial step size and sufficient decrease parameter\r\n\tgamma = 1e-4\r\n\talpha = 1\r\n\tfor i in 1:maxIter\r\n\r\n\t\t# Try out the current step-size\r\n\t\twNew = w - alpha*g\r\n\t\t(fNew,gNew) = funObj(wNew)\r\n\r\n\t\t# Decrease the step-size if we increased the function\r\n\t\tgg = dot(g,g)\r\n\t\twhile fNew > f - gamma*alpha*gg\r\n\r\n\t\t\tif verbose\r\n\t\t\t\t@printf(\"Backtracking\\n\")\r\n\t\t\tend\r\n\r\n\t\t\t# Fit a degree-2 polynomial to set step-size\r\n\t\t\talpha = alpha^2*gg/(2(fNew - f + alpha*gg))\r\n\r\n\t\t\t# Try out the smaller step-size\r\n\t\t\twNew = w - alpha*g\r\n\t\t\t(fNew,gNew) = funObj(wNew)\r\n\t\tend\r\n\r\n\t\t# Guess the step-size for the next iteration\r\n\t\ty = gNew - g\r\n\t\talpha *= -dot(y,g)/dot(y,y)\r\n\r\n\t\t# Sanity check on the step-size\r\n\t\tif (!isfinitereal(alpha)) | (alpha < 1e-10) | (alpha > 1e10)\r\n\t\t\talpha = 1\r\n\t\tend\r\n\r\n\t\t# Accept the new parameters/function/gradient\r\n\t\tw = wNew\r\n\t\tf = fNew\r\n\t\tg = gNew\r\n\r\n\t\t# Print out some diagnostics\r\n\t\tgradNorm = norm(g,Inf)\r\n\t\tif verbose\r\n\t\t\t@printf(\"%6d %15.5e %15.5e %15.5e\\n\",i,alpha,f,gradNorm)\r\n\t\tend\r\n\r\n\t\t# We want to stop if the gradient is really small\r\n\t\tif gradNorm < epsilon\r\n\t\t\tif verbose\r\n\t\t\t\t@printf(\"Problem solved up to optimality tolerance\\n\")\r\n\t\t\tend\r\n\t\t\treturn w\r\n\t\tend\r\n\tend\r\n\tif verbose\r\n\t\t@printf(\"Reached maximum number of iterations\\n\")\r\n\tend\r\n\treturn w\r\nend\r\n\r\n\r\n\r\nfunction findMinL1(funObj,w,lambda;maxIter=100,epsilon=1e-2)\r\n\t# funObj: function that returns (objective,gradient)\r\n\t# w: initial guess\r\n\t# lambda: value of L1-regularization parmaeter\r\n\t# maxIter: maximum number of iterations\r\n\t# epsilon: stop if the gradient gets below this\r\n\r\n\t# Evalluate the intial objective and gradient\r\n\t(f,g) = funObj(w)\r\n\r\n\t# Initial step size and sufficient decrease parameter\r\n\tgamma = 1e-4\r\n\talpha = 1\r\n\tfor i in 1:maxIter\r\n\r\n\t\t# Gradient step on smoooth part\r\n\t\twNew = w - alpha*g\r\n\t\t# Proximal step on non-smooth part\r\n\t\twNew = sign.(wNew).*max.(abs.(wNew) - lambda*alpha,0)\r\n\t\t(fNew,gNew) = funObj(wNew)\r\n\r\n\t\t# Decrease the step-size if we increased the function\r\n\t\tgtd = dot(g,wNew-w)\r\n\t\twhile fNew + lambda*norm(wNew,1) > f + lambda*norm(w,1) - gamma*alpha*gtd\r\n\t\t\t@printf(\"Backtracking\\n\")\r\n\t\t\talpha /= 2\r\n\r\n\t\t\t# Try out the smaller step-size\r\n\t\t\twNew = w - alpha*g\r\n\t\t\twNew = sign.(wNew).*max.(abs.(wNew) - lambda*alpha,0)\r\n\t\t\t(fNew,gNew) = funObj(wNew)\r\n\t\tend\r\n\r\n\t\t# Guess the step-size for the next iteration\r\n\t\ty = gNew - g\r\n\t\talpha *= -dot(y,g)/dot(y,y)\r\n\r\n\t\t# Sanity check on the step-size\r\n\t\tif (!isfinitereal(alpha)) | (alpha < 1e-10) | (alpha > 1e10)\r\n\t\t\talpha = 1\r\n\t\tend\r\n\r\n\t\t# Accept the new parameters/function/gradient\r\n\t\tw = wNew\r\n\t\tf = fNew\r\n\t\tg = gNew\r\n\r\n\t\t# Print out some diagnostics\r\n\t\toptCond = norm(w-sign.(w-g).*max.(abs.(w-g)-lambda,0),Inf)\r\n\t\t@printf(\"%6d %15.5e %15.5e %15.5e\\n\",i,alpha,f+lambda*norm(w,1),optCond)\r\n\r\n\t\t# We want to stop if the gradient is really small\r\n\t\tif optCond < epsilon\r\n\t\t\t@printf(\"Problem solved up to optimality tolerance\\n\")\r\n\t\t\treturn w\r\n\t\tend\r\n\tend\r\n\t@printf(\"Reached maximum number of iterations\\n\")\r\n\treturn w\r\nend\r\n", "meta": {"hexsha": "cbba0764047b197517d62e00dfae34ca8ca522c5", "size": 3720, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "a2/findMin.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": "a2/findMin.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": "a2/findMin.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": 25.306122449, "max_line_length": 87, "alphanum_fraction": 0.6502688172, "num_tokens": 1182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109728022221, "lm_q2_score": 0.8976952859490985, "lm_q1q2_score": 0.8531794499988516}}
{"text": "import Pkg; Pkg.add(Pkg.PackageSpec(url=\"https://github.com/JuliaComputing/JuliaAcademyData.jl\"))\nusing JuliaAcademyData; activate(\"Foundations of machine learning\")\n\n## Run this cell to load the graphics packages\nusing Plots; gr()\n\n# ## Adding a function parameter\n\n#-\n\n# In the last notebook, we saw an example of adding **parameters** to functions. These are values that control the behavior of a function. Let's look at that in some more detail.\n\n#-\n\n# Let's go back to our original version of the \u03c3 function:\n\n\u03c3(x) = 1 / (1 + exp(-x))\n\n# Instead of working with a single function, we can work with a whole class (set) of functions that look similar but differ in the value of a **parameter**. Let's make a new function that uses the previous $\\sigma$ function, but also has a parameter, $w$. Mathematically, we could write\n#\n# $$f_w(x) = f(x; w) = \\sigma(w \\, x).$$\n#\n# (Here, $w$ and $x$ are multiplied in the argument of $\\sigma$; we could write $w \\times x$ or $w * x$, or even $w \\cdot x$, but usually the symbols are not written.)\n#\n# Mathematically speaking, we can think of $f_w$ as a different function for each different value of the parameter $w$.\n\n#-\n\n# In Julia, we write this as follows:\n\nf(x, w) = \u03c3(w * x)\n\n# Note that Julia just treats parameters as additional *arguments* to the function; the function `f` has two arguments, the value of `x` and the value of `w` that we want to use.\n\n#-\n\n# We can now investigate the effect of $w$ interactively. To do so, we need a way of writing in Julia \"the function of one variable $x$ that we obtain when we fix the value of $w$\". We write this as an \"anonymous function\", as we saw in the notebook on functions:\n#\n#     x -> f(x, w)\n#\n# We can read this as \"the function that maps $x$ to the value of $f(x, w)$, for a value of $w$ that was previously given\".\n\n#-\n\n# Now we are ready to draw the function. For each plot, we *fix* a value of the parameter $w$ and draw the resulting function as a function of $x$. We can interactively modify the value of $w$, and plot the new function that comes out:\n\n## Try manipulating `w` between -2 and 2\nw = 0.0\nplot(x->f(x, w), -5, 5, ylims=(0,1), label=\"sigmoid\")\nplot!(x->(x>0), -5,5, label=\"Square Wave\")\n\n# #### Exercise 1\n#\n# Try writing your own function that takes a parameter. Start by copying and executing\n#\n# ```julia\n# square(x) = x^2\n# ```\n#\n# Then use `square` to declare a new function `square_and_scale` that takes two inputs, `a` and `x` such that\n#\n# $$\\mathrm{square\\_and\\_scale}(x; a) := a \\cdot x^2$$\n\n#-\n\n# #### Solution\n#\n# You should have declared the following function:\n#\n# ```julia\n# square_and_scale(x, a) = a * x^2\n# ```\n#\n# We can write some tests as follows, using the approximate equality operator, `\u2248`, written as `\\approx<TAB>`:\n#\n# ```julia\n# square_and_scale(1, 1) \u2248 1\n# square_and_scale(1, 2) \u2248 2\n# square_and_scale(2, 1) \u2248 4\n# square_and_scale(2, 2) \u2248 8\n# ```\n\n#-\n\n# #### Exercise 2\n\n#-\n\n# Once you have declared `square_and_scale`, uncomment the code below and see how the parameter `a` scales the function `square` :\n\n## x = -10:10\n## a = 5.0 # Try manipulating a here\n## plot(x, square.(x), label=\"x^2\")\n## plot!(x, square_and_scale.(x, a), ls=:dash, label=\"ax^2\")\n\n# ## Fitting a function to data\n\n#-\n\n# As we saw in the previous notebook, what we would like to do is use the fact that we now have a parameter in our function in order to do something useful! Namely, we want to model data with it.\n\n#-\n\n# So suppose that we are given a single data point $(x_0, y_0) = (2, 0.8)$. We can try to \"fit\" the function $f_w$ by adjusting the parameter $w$ until the function passes through the data.\n#\n# **Game**: Change `w` until the graph of the function hits the data point. Which value of $w$ does that correspond to?\n\nx0, y0 = 2, 0.8\n\nw = 0.0 # try mainipulatoing `w` between -2 and 2\nplot(x->f(x, w), -5, 5, ylims=(0, 1), label=\"f\")\nscatter!([x0], [y0], label=\"data\")\n\n# ## Quantifying how far we are from the goal: the *loss function*\n\n#-\n\n# We can see visually when the graph of the function passes through the data point. But the goal is to be able to automate this process so that the computer can do it unaided.\n#\n# So we will need a more precise way of deciding and quantifying (i.e. measuring with a number) *how far away we are from the goal*; here, the goal means hitting the data point with the function.\n\n#-\n\n# #### Exercise 3\n#\n# Can you think of a way of measuring how far away our function is from the data point?\n\n#-\n\n# ### Defining the loss function\n\n#-\n\n# We need to measure how far away the curve is from the data point when we choose a particular value of $w$.\n# One way to do this is by finding the vertical distance $d$ from the curve to the data point.\n#\n# Instead of just taking the distance, it is common to take the *square* of the distance, $d^2$.\n#\n# Since we are taking the vertical distance, we need the distance at the given value of $x_0$ where the data point lies. For a given value of the parameter $w$, the height of the point on the curve with that value of $x_0$ is $f(x_0, w)$.\n#\n# So we take\n# $$d := y_0 - f(x_0, w)$$\n#\n# and\n# $$d^2 = [y_0 - f(x_0, w)]^2.$$\n#\n# This is our measure of distance. It will change when $w$ changes -- in other words, it is itself a *function of $w$*; we will denote this function by $L(w)$, and call it the **loss function**:\n#\n# $$L(w) := [y_0 - f(x_0, w)]^2.$$\n#\n# So the goal is to find the value $w^*$ of $w$ where the loss function is *least*; in other words, we need to *minimize* the loss function!\n#\n# (Another name for a loss function is a *cost function*.)\n\n#-\n\n# #### Exercise 4\n#\n# (a) Define the loss function `L(w)` in Julia.\n#\n# (b) Draw the data point and the function `x -> f(x, w)`. Also draw a vertical line from the data point to the function `x -> f(x, w)`.\n#\n# (c) Make the plot interactive.\n#\n# (d) Add as the plot title the value of the loss function for the current value of $w$.\n#\n# (e) Use the slider to find the value $w^*$ of $w$ for which the loss function reaches its minimum value. What is $w^*$? What is the value of the loss function there, $L(w^*)$?\n\n#-\n\n# #### Solution\n\n#-\n\n# (a) We have data\n\nx0, y0 = 2, 0.8\n\n# We define the loss function as follows:\n\nL(w) = (y0 - f(x0, w))^2\n\n# (b-d): The visualization can be written as follows\n\nw = 0.0 # try manipulating w here between -2 and 2\n\nplot(x->f(x, w), -5, 5, ylims=(0, 1), label=\"f_w\", lw=3)  # function\n\nscatter!([x0], [y0], label=\"data\")\nplot!([x0, x0], [y0, f(x0, w)], label=\"loss\")  # vertical line\n\ntitle!(\"L(w) = $(round(L(w); sigdigits = 5))\")\n\n\n# ## What does the loss function look like?\n\n#-\n\n# The loss function $L(w)$ tells us how far away the function $f_w$ is from the data when the parameter value is $w$, represented visually as the vertical line in the previous plot. When the data are fixed, this is a function only of the parameter $w$. What does this function look like as a function of $w$? Let's draw it!\n\n#-\n\n# #### Exercise 5\n#\n# Draw the function $L(w)$ as a function of $w$.\n\n#-\n\n# #### Solution\n\nplot(L, -3, 3, xlabel=\"w\", ylabel=\"L(w)\", ylims=(0, 0.7), label=\"L\")\n\n# ### Features of the loss function\n\n#-\n\n# This graph quantifies how far we are from the data point for a given value of $w$.\n# What features can we see from the graph?\n#\n# Firstly, we see that $L(w)$ is always bigger than $0$, for any value of $w$. This is because we want $L$ to be some kind of measure of *distance*, and distances cannot be negative.\n#\n# Secondly, we see that there is a special value $w^*$ of $w$ where the function $L$ reaches its minimum value. In this particular case, it actually reaches all the way down to $0$!\n# This means that the original function $f$ (the one we manipulated above) passes exactly through the data point $(x_0, y_0)$.\n\n#-\n\n# #### Exercise 6\n#\n# Draw a zoomed-in version of the graph to find the place $w^*$ where the function hits $0$ more precisely.\n\n#-\n\n# ### A different way of defining the loss function\n\n#-\n\n# **Why did we use such a complicated function $L$ with those squares inside?** We could instead just have used the absolute distance, instead of the distance squared, using the *absolute value* function, written mathematically as $| \\cdot |$, and in Julia as `abs`.\n\n#-\n\n# #### Exercise 7\n#\n# Define a new loss function, `L_abs`, using the absolute value, and see what it looks like.\n\n#-\n\n# #### Solution\n\nL_abs(w) = abs(y0 - f(x0, w))\n\nplot(L_abs, -3, 3, xlabel=\"w\", ylabel=\"L_abs(w)\", ylims=(0, 0.7), label=\"L_abs\")\n\n# Now we see why it was previously generally preferred to use squares: using the absolute value gives a cost function that is *not smooth*. This makes it difficult to use methods from calculus to find the minimum. Nonetheless, using non-smooth functions is very common in machine learning nowadays.\n\n", "meta": {"hexsha": "6e56fda5116dbe3ab66ab38a41657d2f81f794eb", "size": 8772, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Courses/Foundations of machine learning/0500.Building-models-quiz.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/0500.Building-models-quiz.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/0500.Building-models-quiz.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": 34.4, "max_line_length": 323, "alphanum_fraction": 0.6785225718, "num_tokens": 2571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541610257062, "lm_q2_score": 0.9059898140375993, "lm_q1q2_score": 0.8531290782354111}}
{"text": "# --- Imports\n\nimport Distributions\nusing Distributions: MvNormal, Uniform, ContinuousUnivariateDistribution, cdf, pdf\nusing HypothesisTests\nusing LinearAlgebra\nusing Plots\nusing Random\n\n# --- Generate sample of vectors drawn from a uniform distribution on a unit circle\n\nn = 2\nnum_samples_2d = 50000\n\ndist = Uniform(-\u03c0, \u03c0)\nnum_vectors = num_samples_2d\ntheta = rand(dist, num_vectors)\nvectors = transpose(hcat(cos.(theta), sin.(theta)));\n\n# --- Plot histogram of angles\n\nthetas = map(i -> atan(vectors[:, i][2], vectors[:, i][1]), 1:num_vectors)\n\nnum_hist_bins = 25\nhist_bins = range(-\u03c0, \u03c0; length=num_hist_bins)\nhist = histogram(thetas; bins=hist_bins, normalize=true)\nplt = plot(hist)\n\npdf_2d = 0.5 / \u03c0\nprintln(\"pdf(\u03b8): $(pdf_2d)\")\n\n# Display plot\ndisplay(plt)\n\n# --- Perform test for uniformity on the circle\n\n# Analytical formula for distribution over angle from x-axis\nstruct ThetaDistribution2D <: ContinuousUnivariateDistribution end\nDistributions.pdf(dist::ThetaDistribution2D, x::Real) = 0.5 / \u03c0\nDistributions.cdf(dist::ThetaDistribution2D, x::Real) = 0.5 * (x + \u03c0) / \u03c0\n\ntheta_dist = ThetaDistribution2D()\n\n# Perform Anderson-Darling Test\ntest_results = OneSampleADTest(thetas, theta_dist)\nprintln(test_results)\n\ntest_results = ExactOneSampleKSTest(thetas, theta_dist)\nprintln(test_results)\n\ntest_results = ApproximateOneSampleKSTest(thetas, theta_dist)\nprintln(test_results)\n\n# --- Generate sample of vectors drawn from a uniform distribution on a unit circle\n\nn = 2\nnum_samples_2d = 50000\n\n# Generate vectors\ndist = MvNormal(zeros(n), ones(n))\nnum_vectors = num_samples_2d\nvectors = rand(dist, num_vectors)\nfor i = 1:num_vectors\n    vectors[:, i] /= norm(vectors[:, i])\nend\n\n# --- Plot histogram of angles\n\nthetas = map(i -> atan(norm(vectors[:, i][2]), vectors[:, i][1]), 1:num_vectors)\n\nnum_hist_bins = 25\nhist_bins = range(0, \u03c0; length=num_hist_bins)\nhist = histogram(thetas; bins=hist_bins, normalize=true)\nplt = plot(hist)\n\npdf_2d = 1 / \u03c0\nprintln(\"pdf(\u03b8): $(pdf_2d)\")\n\n# Display plot\ndisplay(plt)\n\n# --- Perform test for uniformity on the circle\n\n# Analytical formula for distribution over angle from x-axis\nstruct ThetaDistribution2D <: ContinuousUnivariateDistribution end\nDistributions.pdf(dist::ThetaDistribution2D, x::Real) = 1 / \u03c0\nDistributions.cdf(dist::ThetaDistribution2D, x::Real) = x / \u03c0\n\ntheta_dist = ThetaDistribution2D()\n\n# Perform Anderson-Darling Test\ntest_results = OneSampleADTest(thetas, theta_dist)\nprintln(test_results)\n\ntest_results = ExactOneSampleKSTest(thetas, theta_dist)\nprintln(test_results)\n\ntest_results = ApproximateOneSampleKSTest(thetas, theta_dist)\nprintln(test_results)\n\n# --- Generate sample of vectors drawn from a uniform distribution on a unit sphere\n\nn = 3\nnum_samples_3d = 50000\n\n# Generate vectors\ndist = MvNormal(zeros(n), ones(n))\nnum_vectors = num_samples_3d\nvectors = rand(dist, num_vectors)\nfor i = 1:num_vectors\n    vectors[:, i] /= norm(vectors[:, i])\nend\n\n# --- Plot histogram of angles\n\nthetas = map(i -> atan(norm(vectors[:, i][2:end]), vectors[:, i][1]), 1:num_vectors)\n\nnum_hist_bins = 50\nhist_bins = range(0, \u03c0; length=num_hist_bins)\nhist = histogram(thetas; bins=hist_bins, normalize=true)\nplt = plot(hist)\n\npdf_3d(x) = 0.5 * sin(x)\nplt = plot!(pdf_3d, 0, \u03c0)\n\n# Display plot\ndisplay(plt)\n\n# --- Perform test for uniformity on the sphere\n\n# Analytical formula for distribution over angle from x-axis\nstruct ThetaDistribution3D <: ContinuousUnivariateDistribution end\nDistributions.cdf(dist::ThetaDistribution3D, x::Real) = 0.5 * (1 - cos(x))\n\ntheta_dist = ThetaDistribution3D()\n\n# Perform Anderson-Darling Test\ntest_results = OneSampleADTest(thetas, theta_dist)\nprintln(test_results)\n\ntest_results = ExactOneSampleKSTest(thetas, theta_dist)\nprintln(test_results)\n\ntest_results = ApproximateOneSampleKSTest(thetas, theta_dist)\nprintln(test_results)\n\n# --- Generate sample of vectors drawn from a uniform distribution on a unit sphere\n\nn = 20\nnum_samples = 50000\n\n# Generate vectors\ndist = MvNormal(zeros(n), ones(n))\nnum_vectors = num_samples\nvectors = rand(dist, num_vectors)\nfor i = 1:num_vectors\n    vectors[:, i] /= norm(vectors[:, i])\nend\n\n# --- Plot histogram of angles\n\nthetas = map(i -> atan(norm(vectors[:, i][2:end]), vectors[:, i][1]), 1:num_vectors)\n\nnum_hist_bins = 50\nhist_bins = range(0, \u03c0; length=num_hist_bins)\nhist = histogram(thetas; bins=hist_bins, normalize=true)\nplt = plot(hist)\n\npdf_nd(x) = (2^(n-2) / \u03c0 / binomial(n-2, (n-2) \u00f7 2)) * sin(x)^(n-2)\nplt = plot!(pdf_nd, 0, \u03c0)\n\n# Display plot\ndisplay(plt)\n\n# --- Perform test for uniformity on the hypersphere\n\n# Analytical formula for distribution over angle from x-axis\nstruct ThetaDistributionND <: ContinuousUnivariateDistribution end\n\nfunction Distributions.cdf(dist::ThetaDistributionND, x::Real)\n    k = n-2\n    sgn = (-1)^(k\u00f72)\n    value = 0\n    for j = 0:(k\u00f72 - 1)\n        value += (-1)^j * binomial(k, j) * sin((k - 2*j) * x) / (k - 2*j)\n    end\n    value *= 2\n    value += sgn * binomial(k, k\u00f72) * x  # contribution from i = k\u00f72 term\n    value *= sgn / \u03c0 / binomial(k, k\u00f72)\n\n    return value\nend\n\ntheta_dist = ThetaDistributionND()\n\n# Perform Anderson-Darling Test\ntest_results = OneSampleADTest(thetas, theta_dist)\nprintln(test_results)\n\ntest_results = ExactOneSampleKSTest(thetas, theta_dist)\nprintln(test_results)\n\ntest_results = ApproximateOneSampleKSTest(thetas, theta_dist)\nprintln(test_results)\n\n# --- Generate sample of vectors drawn from a uniform distribution on a unit sphere\n\nn = 45\nnum_samples = 50000\n\n# Generate vectors\ndist = MvNormal(zeros(n), ones(n))\nnum_vectors = num_samples\nvectors = rand(dist, num_vectors)\nfor i = 1:num_vectors\n    vectors[:, i] /= norm(vectors[:, i])\nend\n\n# --- Plot histogram of angles\n\nthetas = map(i -> atan(norm(vectors[:, i][2:end]), vectors[:, i][1]), 1:num_vectors)\n\nnum_hist_bins = 50\nhist_bins = range(0, \u03c0; length=num_hist_bins)\nhist = histogram(thetas; bins=hist_bins, normalize=true)\nplt = plot(hist)\n\npdf_nd(x) = (2^(n-2) / \u03c0 / binomial(n-2, (n-2) \u00f7 2)) * sin(x)^(n-2)\nplt = plot!(pdf_nd, 0, \u03c0)\n\n# Display plot\ndisplay(plt)\n\n# --- Perform test for uniformity on the hypersphere\n\n# Analytical formula for distribution over angle from x-axis\nstruct ThetaDistributionND <: ContinuousUnivariateDistribution end\n\nfunction Distributions.cdf(dist::ThetaDistributionND, x::Real)\n    k = n-2\n    value = 0\n    norm_ = 0\n    for j = 0:(k-1)\u00f72\n        coef = (-1)^j * binomial(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    return value\nend\n\ntheta_dist = ThetaDistributionND()\n\n# Perform Anderson-Darling Test\ntest_results = OneSampleADTest(thetas, theta_dist)\nprintln(test_results)\n\ntest_results = ExactOneSampleKSTest(thetas, theta_dist)\nprintln(test_results)\n\ntest_results = ApproximateOneSampleKSTest(thetas, theta_dist)\nprintln(test_results)\n", "meta": {"hexsha": "8bb525ed25a4c2f89a5fb7ade03d6c5b11c3b6a8", "size": 6820, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/2022-02-17-Tests_for_Uniformity_of_Distributions_on_Unit_Hyperspheres.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-17-Tests_for_Uniformity_of_Distributions_on_Unit_Hyperspheres.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-17-Tests_for_Uniformity_of_Distributions_on_Unit_Hyperspheres.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.8333333333, "max_line_length": 84, "alphanum_fraction": 0.7236070381, "num_tokens": 1954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012747599251, "lm_q2_score": 0.9019206705978501, "lm_q1q2_score": 0.8530377199837732}}
{"text": "using Statistics, StatsBase, LinearAlgebra, DataFrames, CSV\ndf = CSV.read(\"../data/3featureData.csv\",header=false)\nn, p = size(df)\nprintln(\"Number of features: \", p)\nprintln(\"Number of observations: \", n)\nX = convert(Array{Float64,2},df)\nprintln(\"Dimensions of data matrix: \", size(X))\n\nxbarA = (1/n)*X'*ones(n)\nxbarB = [mean(X[:,i]) for i in 1:p]\nxbarC = sum(X,dims=1)/n\nprintln(\"\\nAlternative calculations of (sample) mean vector: \")\n@show(xbarA), @show(xbarB), @show(xbarC)\n\nY = (I-ones(n,n)/n)*X\nprintln(\"Y is the de-meaned data: \", mean(Y,dims=1))\n\ncovA = (X .- xbarA')'*(X .- xbarA')/(n-1)\ncovB = Y'*Y/(n-1)\ncovC = [cov(X[:,i], X[:,j]) for i in 1:p, j in 1:p]\ncovD = [cor(X[:,i], X[:,j])*std(X[:,i])*std(X[:,j]) for i in 1:p, j in 1:p]\ncovE = cov(X)\nprintln(\"\\nAlternative calculations of (sample) covariance matrix: \")\n@show(covA), @show(covB), @show(covC), @show(covD), @show(covE)\n\nZmatA = [(X[i,j] - mean(X[:,j]))/std(X[:,j]) for i in 1:n, j in 1:p ]\nZmatB = hcat([zscore(X[:,j]) for j in 1:p]...)\nprintln(\"\\nAlternate computation of Z-scores yields same matrix: \", \n\tmaximum(norm(ZmatA-ZmatB)))\nZ = ZmatA\n\ncorA = covA ./ [std(X[:,i])*std(X[:,j]) for i in 1:p, j in 1:p]\ncorB = covA ./ (std(X,dims = 1)'*std(X,dims = 1))\ncorC = [cor(X[:,i],X[:,j]) for i in 1:p, j in 1:p]\ncorD = Z'*Z/(n-1)\ncorE = cov(Z)\ncorF = cor(X)\nprintln(\"\\nAlternative calculations of (sample) correlation matrix: \")\n@show(corA), @show(corB), @show(corC), @show(corD), @show(corE), @show(corF);\n", "meta": {"hexsha": "3877d29483c1f0f77a86b57e094aad77716b7e88", "size": 1477, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "4_chapter/sampleCovarianceMatrix.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/sampleCovarianceMatrix.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/sampleCovarianceMatrix.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.925, "max_line_length": 77, "alphanum_fraction": 0.6140825999, "num_tokens": 559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620619801095, "lm_q2_score": 0.888758786126321, "lm_q1q2_score": 0.8529969651755369}}
{"text": "function parabolicinterp(f::Function, xl::Number, xm::Number, xu::Number, ea::Number, maxIter::Int64)\n  # 1D optimisation using parabolic interpolation\n  \n  xo = NaN; # Current estimate of the optimum\n  fxm = f(xm);\n  fxu = f(xu);\n  fxl = f(xl);\n\n  for i = 1:maxIter\n    xoold = xo; # xoxo\n\n    # Solution for xo using simultaneous equations\n    fracNumerator = ((xm - xl)^2 * (fxm-fxu)) - ((xm - xu)^2 * (fxm - fxl));\n    fracDenominator = ((xm - xl) * (fxm - fxu)) - ((xm - xu) * (fxm - fxl));\n    xo = xm - 0.5 * (fracNumerator / fracDenominator);\n\n    if xo < xm\n      # The optimum is to the left of xm so make the upper estimate xm and make\n      # the middle estimate xo.\n      xu = xm;\n      fxu = fxm;\n      xm = xo;\n      fxm = f(xm);\n    elseif xo > xm\n      # The optimum is to the right of xm so make the lower estimate xm and\n      # the middle estimate xo.\n      xl = xm;\n      fxl = fxm;\n      xm = xo;\n      fxm = f(xm);\n    else\n      break;\n    end\n\n    # Relative error checks\n    if abs((xo - xoold) / xo) * 100 < ea\n      break;\n    end\n  end\n  return xo;\nend\n", "meta": {"hexsha": "31e5d79509e0d29ee64bfa6cdc82d1e516751c9e", "size": 1082, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/One-Dimensional Optimisation/parabolicinterp.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/One-Dimensional Optimisation/parabolicinterp.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/One-Dimensional Optimisation/parabolicinterp.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": 25.7619047619, "max_line_length": 101, "alphanum_fraction": 0.561922366, "num_tokens": 353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551515780318, "lm_q2_score": 0.8840392802184581, "lm_q1q2_score": 0.8529698537161146}}
{"text": "module YaLinearAlgebra\n\nimport Base: +, -, *\n\nexport +, -, *, \u03bc, dot, sum_of_square, norm,\n  distance, shape, get_row, get_column, get_col, make_matrix\n\n## Vector Portion\n\nfunction +(v\u2081::Vector{T}, v\u2082::Vector{T})::Vector{T} where T <: Number\n  \"\"\"\n  Vector Additon is component-wise\n  \"\"\"\n  @assert length(v\u2081) == length(v\u2082)\n  v\u2081 .+ v\u2082\nend\n\nfunction +(vc::Vector{Vector{T}})::Vector{T} where T <: Number\n  \"\"\"\n  Sum all corresponding components of a collection of vector to return\n  one vector\n  \"\"\"\n  @assert length(vc) > 0 \"expect the collection to have at leat one vector element\"\n  n = length(vc[1])\n  @assert all(v -> length(v) == n, vc) \"Expect all vectors to be of he same length\"\n  v = zeros(T, n)\n  for v\u2080 \u2208 vc\n    v .+= v\u2080\n  end\n  v\nend\n\nfunction -(v\u2081::Vector{T}, v\u2082::Vector{T})::Vector{T} where T <: Number\n  \"\"\"\n  Vector Additon is component-wise\n  \"\"\"\n  @assert length(v\u2081) == length(v\u2082)\n  v\u2081 .- v\u2082\nend\n\n*(x::T, v::Vector{T}) where T <: Number = v .* x\n*(v::Vector{T}, x::T) where T <: Number = v .* x\n\nfunction \u03bc(vc::Vector{Vector{T}})::Vector{AbstractFloat} where T <: Number\n  \"\"\"Element-wise mean\"\"\"\n  @assert length(vc) > 0\n  n = length(vc[1])\n\n  @assert all(v -> length(v) == n, vc)\n  reduce(+, vc) / length(vc)\nend\n\nfunction dot(v\u2081::Vector{T}, v\u2082::Vector{T})::T where T <: Number\n  @assert length(v\u2081) == length(v\u2082)\n  sum(v\u2081 .* v\u2082)\nend\n\nfunction sum_of_square(v::Vector{T})::T where T <: Number\n  \"\"\"\n  return v\u1d62 * v\u1d62 \u2200 i \u2208 1:length(v)\n  \"\"\"\n  dot(v, v)\nend\n\nfunction norm(v::Vector{T})::AbstractFloat where T <: Number\n  \u221a sum(v .* v)\nend\n\nfunction distance(v\u2081::Vector{T}, v\u2082::Vector{T})::AbstractFloat where T <: Number\n  \"\"\"\n  (Euclidean) distance(v\u2081, v\u2082) \u2261 \u221a(\u03a3 (v\u2081\u1d62 - v\u2082\u1d62)\u00b2)\n  \"\"\"\n  @assert length(v\u2081) == length(v\u2082)\n  \u221a sum((v\u2081 .- v\u2082).^2)  # == norm(v\u2081 .- v\u2082)\nend\n\n## Matrix Portion\n\nfunction shape(m::Matrix{T})::Tuple{Integer, Integer} where T <: Number\n  size(m)\nend\n\nfunction get_row(m::Matrix{T}, r::Integer)::Vector{T}  where T <: Number\n  @assert 1 \u2264 r \u2264 size(m)[1]\n  view(m, r, :)  ## no copy!\nend\n\nfunction get_column(m::Matrix{T}, c::Integer)::Vector{T}  where T <: Number\n  @assert 1 \u2264 c \u2264 size(m)[2]\n  view(m, :, c)  ## no copy!\nend\n\nget_col(m::Matrix{T}, c::Integer) where T <: Number = get_column(m, c)\n\nfunction make_matrix(nrows::Integer, ncols::Integer, fn::Function;\n    DT::DataType=Float64)::Matrix\n  @assert 1 \u2264 nrows && 1 \u2264 ncols\n\n  m = zeros(DT, (nrows, ncols))\n  for c \u2208 1:ncols, r \u2208 1:nrows\n    m[r, c] = fn(r, c)\n  end\n  m\nend\n\nend  ## YaLinearAlgebra\n", "meta": {"hexsha": "1f1779badfbc21dd2c79586ec4911687c448efaa", "size": 2499, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Data Science From Scratch/src/YaLinearAlgebra.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/YaLinearAlgebra.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/YaLinearAlgebra.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": 23.3551401869, "max_line_length": 83, "alphanum_fraction": 0.6130452181, "num_tokens": 855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.971992476960077, "lm_q2_score": 0.8774767922879693, "lm_q1q2_score": 0.8529008408109662}}
{"text": "using LinearAlgebra\nusing SparseArrays\nusing Plots\nusing ForwardDiff\n\n\"This code performs a convergence test for two finite difference methods applied to\nLaplace's equation with mixed Dirichlet-Neumann boundary conditions.\"\n\n# method of manufactured solutions: define the exact solution, then figure out\n# what f,\u03b1,\u03b2 should be to make it the solution to your PDE\nuexact(x) = log(2+sin(pi*x))\ndudx_exact(x) = ForwardDiff.derivative(uexact,x)\nf(x) = -ForwardDiff.derivative(dudx_exact,x) # -d^2u/dx^2 = f\n\n\u03b1 = uexact(-1)\n\u03b2 = dudx_exact(1)\n\n# The O(h) accurate method\nfunction solve1(m,f,\u03b1,\u03b2)\n    x = LinRange(-1,1,m+2) # add 2 endpoints\n    xint = x[2:end]\n    h = x[2]-x[1]\n    A = (1/h^2) * spdiagm(0=>2*ones(m+1),-1=>-ones(m),1=>-ones(m))\n    A[end,end] = 1/h^2\n    b = f.(xint)\n    b[1] += \u03b1/h^2\n\n    b[end] += \u03b2/h # approach 1 - O(h) accuracy only\n\n    u = A\\b\n    return u,x,xint,h\nend\n\n# The O(h^2) accurate method\nfunction solve2(m,f,\u03b1,\u03b2)\n    x = LinRange(-1,1,m+2) # add 2 endpoints\n    xint = x[2:end] # leave x_{m+1} in the list of points!\n    h = x[2]-x[1]\n    A = (1/h^2) * spdiagm(0=>2*ones(m+1),-1=>-ones(m),1=>-ones(m))\n    A[end,end] = 1/h^2\n    b = f.(xint)\n    b[1] += \u03b1/h^2\n\n    b[end] = .5*f(x[end]) + \u03b2/h\n\n    u = A\\b\n    return u,x,xint,h\nend\n\n# # this code plots the solution\n# m = 40\n# u1,x,xint1,h = solve1(m,f,\u03b1,\u03b2)\n# u2,x,xint2,h = solve2(m,f,\u03b1,\u03b2)\n# plot(xint1,u1,mark=:dot,markersize=2,label=\"O(h) solution\")\n# plot!(xint2,u2,mark=:dot,markersize=2,label=\"O(h^2) solution\")\n# plot!(x,uexact.(x),label=\"Exact solution\")\n# plot!(leg=:bottomright)\n\nmvec = 2 .^ (2:9)\nhvec = zeros(length(mvec))\nerr1 = zeros(length(mvec))\nerr2 = zeros(length(mvec))\nfor (i,m) in enumerate(mvec)\n    u1,x,xint,h = solve1(m,f,\u03b1,\u03b2)\n    u2,x,xint,h = solve2(m,f,\u03b1,\u03b2)\n    hvec[i] = h\n    err1[i] = maximum(@. abs(uexact(xint) - u1))\n    err2[i] = maximum(@. abs(uexact(xint) - u2))\nend\nplot(hvec,err1,marker=:dot,label=\"Max error for method 1\")\nplot!(hvec,err2,marker=:dot,label=\"Max error for method 2\")\nplot!(hvec,hvec.^2,linestyle=:dash,label=\"O(h^2)\")\nplot!(xaxis=:log,yaxis=:log,legend=:bottomright)\n", "meta": {"hexsha": "0385426d83c15e8988a0c89a1b3c2bf5505f4eca", "size": 2105, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "week2/fd_laplace_mixedBCs_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": "week2/fd_laplace_mixedBCs_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": "week2/fd_laplace_mixedBCs_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": 28.4459459459, "max_line_length": 83, "alphanum_fraction": 0.6280285036, "num_tokens": 804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176857294597, "lm_q2_score": 0.9032942106088968, "lm_q1q2_score": 0.8528694889851121}}
{"text": "using LinearAlgebra\r\n\r\n# k_local(Elastic Modulus,thickness,height,length,number of nodes,row/column one, row/column two)\r\n\r\n#creates local stiffness matrix and maps to global\r\nfunction k_local(k,l,n,rc_1,rc_2)\r\n    k_global = zeros(n,n)\r\n    k_global[rc_1,rc_1] = k\r\n    k_global[rc_1,rc_2] = -k\r\n    k_global[rc_2,rc_1] = -k\r\n    k_global[rc_2,rc_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 = 25\r\nk2 = 35\r\nk3 = 45\r\nk4 = 30\r\n# combining all globally mapped matrices\r\nkG = k_local(k1,l,5,1,2)+\r\n     k_local(k2,l,5,2,3)+\r\n     k_local(k3,l,5,3,4)+\r\n     k_local(k4,l,5,3,5)\r\nkG[4,:] = Float64[0 0 0 1 0] #adjustment for Reaction from fixed end\r\nkG[5,:] = Float64[0 0 0 0 1] #adjustment for Reaction from fixed end\r\nkG[:,4] = transpose(Float64[0 0 0 1 0]) #adjustment for Reaction from fixed end\r\nkG[:,5] = transpose(Float64[0 0 0 0 1]) #adjustment for Reaction from fixed end\r\n\r\n# Force Vector\r\nf = Float64[75 0 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\n      \u03f5(u[5],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\n      \u03c3(E,\u03f5M[4])]\r\nprintln(\"Element Stress vector (psi):\")\r\ndisplay(\u03c3M)\r\n\r\n#Reaction Forces vector\r\nFapp(k,x2,x) = k*(x2-x)\r\nFappM = [Fapp(k12,u[2],u[1])\r\n         Fapp(k12,u[3],u[2])\r\n         Fapp(k3,u[4],u[3])\r\n         Fapp(k4,u[5],u[3])]\r\nprintln(\"Reaction Forces vector (lbs):\")\r\ndisplay(FappM)\r\n\r\n", "meta": {"hexsha": "2c9e37b893346fe8540512bf6463ee7f5d8f6d6b", "size": 1711, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "trejo_nicholas_HW2_p3.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_p3.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_p3.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": 23.7638888889, "max_line_length": 98, "alphanum_fraction": 0.6054938632, "num_tokens": 671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122744874229, "lm_q2_score": 0.8902942333990421, "lm_q1q2_score": 0.852823774078313}}
{"text": "\"\"\"\n    univariate(k::Int64, l::Int64, low::N, high::N)::Vector{N} where {N<:AbstractFloat}\n\nCompute the Bernstein coefficients of a univariate monomial.\n\n### Input\n\n- `k`    -- degree of the given monomial\n- `l`    -- degree of the Bernstein polynomial\n- `low`  -- the lower bound of the interval where the Bernstein coefficients are computed\n- `high` -- the upper bound of the interval the Bernstein coefficients are computed\n\n### Output\n\nA vector with floating point entries containing the Bernstein coefficients.\n\"\"\"\nfunction univariate(k::Int64, l::Int64, low::N, high::N)::Vector{N} where {N<:AbstractFloat}\n    m = l - k\n    b = zeros(N, l+1)\n    @inbounds @fastmath for i in 0:l\n        if k < l\n            for j in max(0, i-m):min(k, i)\n                aux =  binomial(m, i-j) * binomial(k, j) / binomial(k+m, i)\n                b[i+1] += aux * low^(k-j) * high^j\n            end\n        else\n            b[i+1] = low^(k-i) * high^i\n        end\n    end\n    return b\nend\n\n\"\"\"\n    univariate(k::Int64, l::Int64, low::Rational, high::Rational)::Vector{Rational}\n\nCompute *exactly* the Bernstein coefficients of a univariate monomial.\n\n### Input\n\n- `k`    -- degree of the given monomial\n- `l`    -- degree of the Bernstein polynomial\n- `low`  -- the lower bound of the interval where the Bernstein coefficients are computed\n- `high` -- the upper bound of the interval the Bernstein coefficients are computed\n\n### Output\n\nA vector with rational entries containing the Bernstein coefficients.\n\"\"\"\nfunction univariate(k::Int64, l::Int64, low::Rational, high::Rational)::Vector{Rational}\n    m = l - k\n    b = zeros(Rational, l+1)\n    @inbounds for i in 0:l\n        if k < l\n            for j in max(0, i-m):min(k, i)\n                aux =  binomial(m, i-j) * binomial(k, j) // binomial(k+m, i)\n                b[i+1] += aux * low^(k-j) * high^j\n            end\n        else\n            b[i+1] = low^(k-i) * high^i\n        end\n    end\n    return b\nend\n\n\"\"\"\n    multivariate(k::Vector{Int64}, l::Vector{Int64},\n                          low::Vector{N}, high::Vector{N})::ImplicitForm{N} where {N<:Number}\n\nCompute the Bernstein coefficients of a multivariate monomial.\n\n### Input\n\n- `k`    -- vector of degrees for each monomial\n- `l`    -- vector of degrees of the Bernstein polynomial for each monomial\n- `low`  -- the lower bounds of the interval where the Bernstein coefficients are computed\n- `high` -- the upper bounds of the interval the Bernstein coefficients are computed\n\n### Output\n\nA Bernstein implicit form holding the Bernstein coefficients.\n\n### Examples\n\n```julia\njulia> m = multivariate([3,2],[3,2],[1.0,2],[2,4.0]);\njulia> m.array\n2-element Array{Array{Float64,1},1}:\n [1.0, 2.0, 4.0, 8.0]\n [4.0, 8.0, 16.0]\n```\n\"\"\"\nfunction multivariate(k::Vector{Int64}, l::Vector{Int64},\n                      low::Vector{N}, high::Vector{N})::ImplicitForm{N} where {N<:Number}\n    n = length(low)\n    ncoeffs = 1\n    B = Vector{Vector{N}}(n)\n    @inbounds for i in 1:n\n        @views B[i] = univariate(k[i], l[i], low[i], high[i])\n        ncoeffs = ncoeffs * length(B[i])\n    end\n    return ImplicitForm(B, n, ncoeffs)\nend\n", "meta": {"hexsha": "c34283fe62aeb7871eb7b4cf3ecd2c69468494d5", "size": 3130, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/monomials.jl", "max_stars_repo_name": "roccaa/BernsteinExpansions.jl", "max_stars_repo_head_hexsha": "5adfbdf330669054c1f5e086eb57f7a3251d3916", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/monomials.jl", "max_issues_repo_name": "roccaa/BernsteinExpansions.jl", "max_issues_repo_head_hexsha": "5adfbdf330669054c1f5e086eb57f7a3251d3916", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/monomials.jl", "max_forks_repo_name": "roccaa/BernsteinExpansions.jl", "max_forks_repo_head_hexsha": "5adfbdf330669054c1f5e086eb57f7a3251d3916", "max_forks_repo_licenses": ["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.3883495146, "max_line_length": 93, "alphanum_fraction": 0.6111821086, "num_tokens": 933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.957912273285902, "lm_q2_score": 0.8902942246666266, "lm_q1q2_score": 0.8528237646437178}}
{"text": "using ForwardDiff, Roots, Plots, LinearAlgebra, Optim\n\nfunction strong_backtracking(f, \u2207, x, d; \u03b1=1, \u03b2=0.1, \u03c3=0.4)\n    y0, g0, y_prev, \u03b1_prev = f(x), \u2207(x)\u22c5d, NaN, 0\n    \u03b1lo, \u03b1hi = NaN, NaN\n    # bracket phase\n    while true\n        y = f(x + \u03b1*d)\n        if y > y0 + \u03b2*\u03b1*g0 || (!isnan(y_prev) && y \u2265 y_prev)\n            \u03b1lo, \u03b1hi = \u03b1_prev, \u03b1\n            break\n        end\n        g = \u2207(x + \u03b1*d)\u22c5d\n        if abs(g) \u2264 -\u03c3*g0\n            return \u03b1\n        elseif g \u2265 0\n            \u03b1lo, \u03b1hi = \u03b1, \u03b1_prev\n            break\n        end\n        y_prev, \u03b1_prev, \u03b1 = y, \u03b1, 2\u03b1\n    end\n    \n    # zoom phase\n    ylo = f(x + \u03b1lo*d)\n    while true\n        \u03b1 = (\u03b1lo + \u03b1hi)/2\n        y = f(x + \u03b1*d)\n        if y > y0 + \u03b2*\u03b1*g0 || y \u2265 ylo\n            \u03b1hi = \u03b1\n        else\n            g = \u2207(x + \u03b1*d)\u22c5d\n            if abs(g) \u2264 -\u03c3*g0\n                return \u03b1\n            elseif g*(\u03b1hi - \u03b1lo) \u2265 0\n                \u03b1hi = \u03b1lo\n            end\n            \u03b1lo = \u03b1\n        end\n    end\nend\n\n\n\n\nf(x) = ((x[1]-1.0)^2) + (0.1*(x[2]-4)^2) + sin(5*pi*x[1])+sin(5*pi*x[2]) \ngrad_f(x) = ForwardDiff.gradient(f,x)\n\n# Ponto inicial\nxk = [-1.0,1.0]\n\n#direcao de busca\ndk = -grad_f(xk)/norm(grad_f(xk))\n\nbeta = 0.1\nalpha_f = 1.0\n\nphi(alpha) = f(xk+alpha*dk)\nd_phi(alpha) = grad_f(xk+alpha*dk)'dk\n\nl_alpha(alpha) = phi(0)+alpha*beta*d_phi(0)\nsigma = 0.4\n\nwolf = []\n\nfor alpha = 0:0.01:alpha_f\n    if (phi(alpha) <= l_alpha(alpha)) && (abs(grad_f(xk+alpha*dk)'dk) <= -sigma*grad_f(xk)'dk)\n        push!(wolf,alpha)\n    end\nend\n\n\nwolfbt = strong_backtracking(f,grad_f,xk,dk)\n\nplot(phi,0,alpha_f,lw=2,lab=\"phi\")\nplot!(l_alpha,0,alpha_f,lw=2,lab=\"L_phi\",c=:black)\nscatter!(wolf,phi.(wolf),lab=\"StrongWolfe\",ms=3,c=:red)\nscatter!([wolfbt],[phi(wolfbt)],lab=\"StrongWolf - BT\",c=:yellow)\nplot!(legend=:outerbottomright)\nplot!(title=\"beta = 0.1 e sigma = 0.4\",xlabel = \"alpha\", ylabel = \"phi(alpha), l_alpha(alpha\")", "meta": {"hexsha": "756002540329095c82a59ea253d6c894c04d8a0f", "size": 1864, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "strong_wolf.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": "strong_wolf.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": "strong_wolf.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": 23.5949367089, "max_line_length": 94, "alphanum_fraction": 0.5112660944, "num_tokens": 721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122672782974, "lm_q2_score": 0.8902942246666267, "lm_q1q2_score": 0.8528237592951822}}
{"text": "using SpecialMatrices\nusing LinearAlgebra\nusing SparseArrays\n\n\"\"\"Ankara.jl contain the functions to develop the description of the\ndiscrete and finite harmonic oscillator in terms of the Harper equations.\"\"\"\n\n# \u03941(j) gives the circulant matrix of size d_{j} \u00d7 d_{j} where d_{j} = 2j + 1\nfunction \u03941(j)\n\t\u03941 = zeros(Float64, 2j + 1)\n\t\u03941[1] = -2\n\t\u03941[2] = 1\n\t\u03941[end] = 1\n\t\u03941 = SpecialMatrices.Circulant(\u03941)\nend\n\n# \u03942(j) gives the diagonal matrix of size d_{j} \u00d7 d_{j} whose diagonal entries\n# are oscillating terms\nfunction \u03942(j)\n\t\u03942 = zeros(Float64, 2j + 1)\n\tfor i in -j:j\n\t\t\u03942[i + 1 + j] = -4 * (sin(pi * i / (2j)))^2\n\tend\n\treturn \u03942 = LinearAlgebra.diagm(\u03942)\nend\n\n# If necessary, compose the Hamiltonian (Harper's equation) H from who the\n# eigenvectors and eigenvalues are obtained\nH(j) = -(1/2.0)*(\u03941(j) + \u03942(j))\n\n# Eigenvectors of H\nh(j) = LinearAlgebra.eigvecs(H(j));\n\n# Eigenvalues of H. Altough, this eigvenvalues are not strictly used because\n# of the symmetry importation below\nk(j) = LinearAlgebra.eigvals(H(j));\n\n# Lineal monotonic increasing values who serves as the (new) eigenvalues\n# in the symmetry importation to construct the evolution operator\n\u03b7(j) = [l for l in 0:(2j + 1)];\n\n# Kernel of the evolution\nker(j, t) = exp.(-1im * pi * t * \u03b7(j)/2.0)\n", "meta": {"hexsha": "fbe97b47860d2ab65d21dc3344629bda1142f439", "size": 1263, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Ankara.jl", "max_stars_repo_name": "rurz/Waveguides_FrFT", "max_stars_repo_head_hexsha": "531dd8b1ddfface099212489fe68e91da3eff622", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Ankara.jl", "max_issues_repo_name": "rurz/Waveguides_FrFT", "max_issues_repo_head_hexsha": "531dd8b1ddfface099212489fe68e91da3eff622", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-18T13:54:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-20T01:46:15.000Z", "max_forks_repo_path": "src/Ankara.jl", "max_forks_repo_name": "rurz/Waveguides_FrFT", "max_forks_repo_head_hexsha": "531dd8b1ddfface099212489fe68e91da3eff622", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7045454545, "max_line_length": 78, "alphanum_fraction": 0.6967537609, "num_tokens": 440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.966410497252158, "lm_q2_score": 0.8824278649085117, "lm_q1q2_score": 0.8527875517153949}}
{"text": "#' ## Run this cell to load the graphics packages\nusing Plots\ngr()\n\n#' ## Run this cell to use a couple of definitions from the previous\n#' Tools notebook\n\nsigma(x) = 1 / (1 + exp(-x))\nf(x, w) = sigma(w * x)\n\n#' ## Multiple function parameters\n#'\n#' In notebook 6, we saw how we could adjust a parameter to make a curve fit\n#' a single data point. What if there is more data to fit?\n#'\n#' We'll see that as we acquire more data to fit, it can sometimes be useful\n#' to add complexity to our model via additional parameters.\n\n#' ## Multiple function parameters\n#'\n#' In notebook 6, we saw how we could adjust a parameter to make a curve fit\n#' a single data point. What if there is more data to fit?\n#'\n#' We'll see that as we acquire more data to fit, it can sometimes be useful\n#' to add complexity to our model via additional parameters.\n\n#' ## Adding more data\n#' Suppose there are now two data points to fit, the previous $(x_0, y_0)$\n#' used in notebook 6 and also $(x_1, y_1) = (-3, 0.3)$.\n\n#' #### Exercise 1\n#\n# Make an interactive plot of the function $f_w$ together with the two data\n# points. Can you make the graph of $f_w$ pass through *both* data points\n# at the *same* time?\n\nx0, y0 = 2, 0.8\nx1, y1 = -3, 0.3\nw = 0.4\nplot(x->f(x, w), -5, 5, ylims=(0, 1), label=\"f\")\nscatter!([x0,x1], [y0,y1], label=\"data\")\n\n#' You should have found that it's actually *impossible* to fit both data points\n#' at the same time! The best we could do is to *minimise* how far away the\n#' function is from the data. To do so, we need to somehow balance the distance\n#' from each of the two data points.\n\n#' #### Exercise 2\n#'\n#' Play with the slider to find the value $w^*$ of $w$ that you think has the \"least error\" in an intuitive sense.\n\nw=0.45\nplot(x->f(x, w), -5, 5, ylim=(0,1))\nscatter!([x0, x1], [y0, y1])\n\n#' ## Defining a loss function\n#' How can we *quantify* some kind of overall measure of the distance from *all* of the data? Well, we just need to define a new loss function! One way to do so would be to sum up the loss functions for each data point, i.e. the sum of the squared vertical distances from the graph to each data point:\n#'\n#' $$L(w) = [y_0 - f_w(x_0)]^2 + [y_1 - f_w(x_1)]^2.$$\n#'\n#' Since the two pieces that we are adding have the same mathematical \"shape\" or structure, we can abbreviate this by writing it as a sum:\n#'\n#' $$L(w) = \\sum_{i=0}^1 [y_i - f_w(x_i)]^2.$$\n\n#' So now we want to find the value $w^*$ of $w$ that minimizes this new\n#' function $L$!\n\n#' #### Exercise 3\n#'\n#' Make a visualization to show the function $f_w$ and to visualize the\n#' distance from each of the data points.\nxs = [2, -3]\nys = [0.8, 0.3]\n\nL(w) = sum( (ys .- f.(xs, w)) .^ 2 )\n\nbegin\n    w = 0.3 # Try manipulating w between -2 and 2\n\n    plot(x->f(x, w), -5, 5, ylims=(0, 1), lw = 3, label=\"f_w\")\n\n    scatter!(xs, ys, label=\"data\")\n\n    for i in 1:2\n        plot!([xs[i], xs[i]], [ys[i], f(xs[i], w)], c=:green)\n    end\n\n\n    title!(\"L(w) =  $(round(L(w); sigdigits = 5))\")\nend\n\n\n#' #### Exercise 4\n#'\n#' After playing with this for a while, it is intuitively obvious that we\n# cannot make the function pass through both data points for any value of\n# $w$. In other words, our loss function, `L(w)`, is never zero.\n#'\n#' What is the minimum value of `L(w)` that you can find by altering `w`?\n#' What is the corresponding value of `w`?\nw = 0.42\nplot(x->f(x, w), -5, 5, ylims=(0, 1), lw = 3, label=\"f_w\", legend=(0.8,0.1))\n\nscatter!(xs, ys, label=\"data\")\n\nfor i in 1:2\n    plot!([xs[i], xs[i]], [ys[i], f(xs[i], w)], c=:green)\nend\n\n\ntitle!(\"L($w) =  $(round(L(w); sigdigits = 5))\")\n\n#' ### Sums in Julia\n#' To generate the above plot we used the `sum` function.\n#' `sum` can add together all the elements of a collection or range,\n#' or it can add together the outputs of applying a function to all the\n#' elements of a collection or range.\n#'\n#' Look up the docs for `sum` via\n#'\n#' ```julia\n#' ?sum\n#' ```\n#' if you need more information.\n\n#' #### Exercise 6\n#'\n#' What is the sum of the absolute values of all integers between -3 and 3? Use `sum` and the `abs` function.\n\n#' #### Solution\n\nsum(abs, -3:3)\n\n#' ## What does the loss function $L$ look like?\n#' In our last attempt to minimize `L(w)` by varying `w`, we saw that `L(w)`\n#' always seemed to be greater than 0.  Is that true? Let's plot it to find out!\n\n#' #### Exercise 7\n#'\n#' Plot the new loss function $L(w)$ as a function of $w$.\n#' #### Solution\nplot(L, -2, 2, xlabel=\"w\", ylabel=\"L(w)\", ylims=(0, 1.2))\n\n#' ### Features of the loss function\n#' The first thing to notice is that $L$ is always positive.\n#' Since it is the sum of squares, and squares cannot be negative,\n#' the sum cannot be negative either!\n#'\n#' However, we also see that although $L$ dips close to $0$ for a single,\n#' special value $w^* \\simeq 0.4$, it never actually *reaches* 0!\n#' Again we could zoom in on that region of the graph to estimate it more\n#' precisely.\n\n#' We might start suspecting that there should be a better way of using the\n#' computer to minimize $L$ to find the location $w^*$ of the minimum,\n#' rather than still doing everything by eye. Indeed there is, as we will\n#' see in the next two notebooks!\n\n#' ## Adding more parameters to the model\n\n#' If we add more parameters to a function, we may be able to improve how it\n#' fits to data. For example, we could define a new function $g$ with another\n#' parameter, a shift or **bias**:\n#'\n#' $$g(x; w, b) := \\sigma(w \\, x + b).$$\n#+ results=\"hidden\"\ng(x, w, b) = sigma(w*x + b)\n#+\n\nxs = [2, -3]\nys = [0.8, 0.3]\n\nL2D(w, b) = sum( (ys .- g.(xs, w, b)) .^ 2)\nw = 0.45 # Try manipulating w between -2 and 2\nb = 0.5 # Try manipulating b between -2 and 2\nplot(x -> g(x, w, b), -5, 5, ylims=(0, 1), lw=3)\n\nscatter!(xs, ys)\n\nfor i in 1:2\n    plot!([xs[i], xs[i]], [ys[i], g(xs[i], w, b)])\nend\n\ntitle!(\"L2D(w, b) = $(L2D(w, b))\")\n\n#' You should be able to convince yourself that we can now make the curve pass\n#' through both points simultaneously.\n\n#' #### Exercise 9\n#'\n#' For what values of `w` and `b` does the line pass through both points?\n\nw = 0.45\nb = 0.48\nplot(x -> g(x, w, b), -5, 5, ylims=(0, 1), lw=3)\n\nscatter!(xs, ys)\n\nfor i in 1:2\n    plot!([xs[i], xs[i]], [ys[i], g(xs[i], w, b)])\nend\n\n\ntitle!(\"L2D(w, b) = $(L2D(w, b))\")\n#' ## Fitting both data points: a loss function\n#' Following the procedure that we used when we had a single parameter,\n#' we can think of the fitting procedure once again as minimizing a suitable\n#' *loss function*. The expression for the loss function is almost the same,\n#' except that now $f$ has two parameters $w$ and $b$, so the loss function\n#' $L_2$ is itself a function of $w$ *and* $b$:\n#'\n#' $$L_2(w, b) = \\sum_i [y_i - f(x_i; w, b)]^2.$$\n#'\n#' So we want to minimize this loss function over *both* of the parameters\n#' $w$ and $b$! Let's plot it.\n\n#' #### Exercise 10\n#'\n#' Define the function `L2` in Julia.\n\n\n#' #### Solution\n\nL2(w, b) = sum( (ys .- g.(xs, w, b)) .^ 2 )\n\n#' To plot the loss as a function of *two* variables (the weights *and* the bias),\n#' we will make use of the `surface` function.  To get a nice interactive\n# 3D plot, we will use the PlotlyJS \"backend\" (plotting engine):\n\ngr()  # load the backend\n\n#-\n\nws = -2:0.05:2\nbs = -2:0.05:2\n\ncontour(ws, bs, L2, levels=0.001:0.025:1.25, xlabel=\"value of w\", ylabel=\"value of b\")\n\n#' We can see that indeed there is a unique point $(w^*, b^*)$ where the\n#' function $L_2$ attains its minimum. You can try different ranges for the\n#' $x$, $y$ and $z$ coordinates to get a better view.\n\n#' ## More data\n\n#' If we add more data, however, we will again not be able to fit all of the\n#' data; we will only be able to attain a \"best fit\".\n#'\n#' Let's create `xs` and `ys` with some more data:\n\nxs = [2, -3, -1, 1]\nys = [0.8, 0.3, 0.4, 0.4]\n\n#' #### Exercise 11\n#'\n#' a) Make an interactive visualization of the function $f$ and the data. Try\n#' to find the values of $w$ and $b$ that give the best fit.\n#'\n#' b) Define the loss function and plot it.\n#' \n#' ```julia\n#' sigma(x) = 1 / (1 + exp(-x))\n#' f(x, w) = sigma(w * x)\n#' g(x, w, b) = sigma(w*x + b)\n#' ```\nL2(w, b) = sum( (ys .- g.(xs, w, b)) .^ 2 )\n\nw = 0.4 # Try manipulating w between -2 and 2\nb = -0.1 # Try manipulating b between -2 and 2\nplot(x->g(x, w, b), -5, 5, ylims=(-0.2, 1))\n\nscatter!(xs, ys)\n\nfor i in 1:length(xs)\n    plot!([xs[i], xs[i]], [ys[i], g(xs[i], w, b)])\nend\n\ntitle!(\"L2(w, b) = $(round(L2(w, b); sigdigits = 5))\")\n\n#' Let's define the loss function that we're using above so that we can plot\n#' it as a function of the parameters `w` and `b`.\n#' #### Exercise 12\n#'\n#' We've seen the loss function, $$L_{2D}(w, b) = \\sum_i[\\mathrm{ys}_i - g(\\mathrm{xs}_i, w, b)]^2,$$ written in Julia as\n#\n# ```julia\n# L2(w, b) = sum( (ys .- g.(xs, w, b)) .^ 2 )\n# ```\n#\n# a few times now. To ensure you understand what this function is doing, implement your own loss function using the commented code below. Do this without using `sum`, `abs2`, or broadcasting dot syntax (for example, `.-`). Hint: you'll want to use a `for` loop to do this.\n\nfunction myL2(w, b)\n    loss = 0.0\n    for (x, y) in zip(xs, ys)\n        loss += (y - g(x, w, b))^2\n    end\n    return loss\nend\n\n#' Now that you've defined `L2`, we can plot it using either `surface` or\n#' `contour` to see how the loss changes as `w` and `b` change!\n\n#' ## plotlyjs() # Use Plotly for 3d surface plots (if possible)\n\nws = -2:0.05:2\nbs = -2:0.05:2\n\n#' ## surface(ws, bs, L2, alpha=0.8, zlims=(0,3))  # alpha gives transparency\ncontour(ws, bs, L2, levels=0.055:0.05:1.5, xlabel=\"value of w\", ylabel=\"value of b\")", "meta": {"hexsha": "70ad6ca8f7c94e69db011dc0e7d5b056ea999aa4", "size": 9561, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "JuliaAcademy/FundMachLearn/ch0700quiz.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/ch0700quiz.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/ch0700quiz.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": 31.0422077922, "max_line_length": 301, "alphanum_fraction": 0.6283861521, "num_tokens": 3169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067244294588, "lm_q2_score": 0.904650530602188, "lm_q1q2_score": 0.8526392083512402}}
{"text": "\"\"\"\n    curve_length(f::Function,a::Real,b::Real;rtol=1e-13) -> Float64\n\nCalculates the length of the curve given by `f`, where `f` is function of one parameter, on interval <`a`, `b`> of said parameter.\n\n# Arguments\n- `f::Function`: function of the curve to be measured,\n- `a::Real`: left-bound of the interval to be integrated on,\n- `b::Real`: right-bound of the interval to be integrated on,\n- `rtol::Real`: default `rtol = 1e-13`, relative tolerance,\n\n# Keywords\n\n# Returns\n- `Float64`: length of the curve defined by the `f` on the interval <`a`, `b`>. \n\n# Throws\n\"\"\"\nfunction curve_length(f::Function,a::Real,b::Real;rtol=1e-13)\n    df = x -> ForwardDiff.derivative(f,x)\n    dr = x -> sqrt(1+df(x)^2)\n    l,_ = quadgk(dr,a,b;rtol=rtol)\n    return l\nend\n\n\"\"\"\n    curve_fraction(f::Function,a::Real,b::Real,r::Real) -> Float64\n\nRetunrs the position of the fraction of the length from the interval <`a`, `b`>, where the length of the curve is given by one parameter function `f`.\n\n# Arguments\n- `f::Function`: function of the curve,\n- `a::Real`: left-bound of the interval to be integrated on,\n- `b::Real`: right-bound of the interval to be integrated on,\n- `r::Real`: fraction of the length of the curve given by `f` from the left,\n- `rtol:Real`: default `rtol = 1e-13`, relative tolerance,\n\n# Keywords\n\n# Returns\n- `Float64`: position of the fraction of the length from the interval <`a`, `b`>. \n\n# Throws\n\"\"\"\nfunction curve_fraction(f::Function,a::Real,b::Real,r::Real;rtol=1e-13)\n    df = x -> ForwardDiff.derivative(f,x)\n    dr = x -> sqrt(1.0 + df(x)^2)\n\n    l,_ = quadgk(dr,a,b;rtol=rtol)\n    lf = l*r\n\n    xo = (a+b)/2\n    xn = 0.0\n    eps_n = 1.0\n    while eps_n > xo*rtol\n        l,_ = quadgk(dr,a,xo;rtol=rtol)\n        xn = xo - (l - lf)/dr(xo)\n        eps_n = abs(xo-xn)\n        xo = xn\n    end\n\n    return xo\nend\n", "meta": {"hexsha": "8bd16c5ecea8d59af87f08532689f7d72efb12fe", "size": 1829, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/curve.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": "src/curve.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": "src/curve.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.578125, "max_line_length": 150, "alphanum_fraction": 0.6364133406, "num_tokens": 587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517072737737, "lm_q2_score": 0.8872046011730964, "lm_q1q2_score": 0.8525607761984344}}
{"text": "###############################################################################\n#\n# Quadratic function solver\n#\n###############################################################################\n\"\"\"\n\n    lower_quadratic(a::FT, b::FT, c::FT) where {FT<:AbstractFloat}\n\nReturn the lower quadratic solution or NaN, given\n- `a` Parameter in `a*x^2 + b*x + c = 0`\n- `b` Parameter in `a*x^2 + b*x + c = 0`\n- `c` Parameter in `a*x^2 + b*x + c = 0`\n\n---\nExample\n```julia\nlow_x = lower_quadratic(1.0, 2.0, 0.0);\nlow_x = lower_quadratic(-1.0, 2.0, 0.0);\nlow_x = lower_quadratic(1.0, 2.0, 2.0);\n```\n\"\"\"\nfunction lower_quadratic(a::FT, b::FT, c::FT) where {FT<:AbstractFloat}\n    discr = b^2 - 4*a*c;\n\n    if (discr >= 0) && (a > 0)\n        return (-b - sqrt(discr)) / (2 * a)\n    elseif (discr >= 0) && (a < 0)\n        return (-b + sqrt(discr)) / (2 * a)\n    else\n        return FT(NaN)\n    end\nend\n\n\n\n\n\"\"\"\n\n    upper_quadratic(a::FT, b::FT, c::FT) where {FT<:AbstractFloat}\n\nReturn the upper quadratic solution or NaN, given\n- `a` Parameter in `a*x^2 + b*x + c = 0`\n- `b` Parameter in `a*x^2 + b*x + c = 0`\n- `c` Parameter in `a*x^2 + b*x + c = 0`\n\n---\nExample\n```julia\nup_x = upper_quadratic(1.0, 2.0, 0.0);\nup_x = upper_quadratic(-1.0, 2.0, 0.0);\nup_x = upper_quadratic(1.0, 2.0, 2.0);\n```\n\"\"\"\nfunction upper_quadratic(a::FT, b::FT, c::FT) where {FT<:AbstractFloat}\n    discr = b^2 - 4*a*c;\n\n    if (discr >= 0) && (a > 0)\n        return (-b + sqrt(discr)) / (2 * a)\n    elseif (discr >= 0) && (a < 0)\n        return (-b - sqrt(discr)) / (2 * a)\n    else\n        return FT(NaN)\n    end\nend\n", "meta": {"hexsha": "f8d51ac1a9e2c8e5daabadc6b23ef68bea0e2a25", "size": 1579, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/quadratic.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/quadratic.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/quadratic.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": 23.9242424242, "max_line_length": 79, "alphanum_fraction": 0.4876504117, "num_tokens": 576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639694252316, "lm_q2_score": 0.8774767858797979, "lm_q1q2_score": 0.8525248291678705}}
{"text": "using Optim, HTTP, GLM, LinearAlgebra, Random, Statistics, DataFrames, CSV, FreqTables\r\nusing Pkg\r\nPkg.add(\"Distributions\")\r\nusing Pkg\r\nPkg.add(\"ForwardDiff\")\r\n\r\n    #Question1\r\n    using DataFrames\r\nusing CSV\r\nusing HTTP\r\nurl = \"https://raw.githubusercontent.com/OU-PhD-Econometrics/fall-2021/master/ProblemSets/PS4-mixture/nlsw88t.csv\"\r\ndf = CSV.read(HTTP.get(url).body, DataFrame)\r\nX = [df.age df.white df.collgrad]\r\nZ = hcat(df.elnwage1, df.elnwage2, df.elnwage3, df.elnwage4,\r\ndf.elnwage5, df.elnwage6, df.elnwage7, df.elnwage8)\r\ny = df.occ_code\r\n#Using Q1 from Pset3 \r\nfunction mlogit_with_Z(theta, X, Z, y)\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    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] = exp.(X*bigAlpha[:,j] .+ (Z[:,j] .- Z[:,J])*gamma)\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\nstartvals = [2*rand(7*size(X,2)).-1; .1]\r\ntd = TwiceDifferentiable(theta -> mlogit_with_Z(theta, X, Z, y), startvals; autodiff = :forward)\r\n# run the optimizer\r\ntheta_hat_optim_ad = optimize(td, startvals, LBFGS(), Optim.Options(g_tol = 1e-5, iterations=100_000, show_trace=true, show_every=50))\r\ntheta_hat_mle_ad = theta_hat_optim_ad.minimizer\r\n# evaluate the Hessian at the estimates\r\nH  = Optim.hessian!(td, theta_hat_mle_ad)\r\ntheta_hat_mle_ad_se = sqrt.(diag(inv(H)))\r\nprintln([theta_hat_mle_ad theta_hat_mle_ad_se]\r\n#Question 2\r\n#Interpretation of gamma#\r\n#Question 3\r\nn.\r\nusing Distributions\r\ninclude(\"lgwt.jl\") # make sure the function gets read in\r\n# define distribution\r\nd = Normal(0,1) # mean=0, standard deviation=1\r\ne.\r\n# get quadrature nodes and weights for 7 grid points\r\nnodes, weights = lgwt(7,-4,4)\r\n# now compute the integral over the density and verify it's 1\r\nsum(weights.*pdf.(d,nodes))\r\n# now compute the expectation and verify it's 0\r\nsum(weights.*nodes.*pdf.(d,nodes))\r\n#computing integrals using the above\r\nd = Normal(0,2)\r\nnodes, weights = lgwt(7,-5,5)\r\nsum(weights.*(nodes.).*pdf.(d,nodes))\r\n\r\nd = Normal(0,2)\r\nnodes, weights = lgwt(10,-5,5)\r\nsum(weights.*(nodes.).*pdf.(d,nodes))\r\n\r\n#Question4\r\n", "meta": {"hexsha": "494d3f32d4b135b2bbf61e5e831e7f18d6837202", "size": 2420, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ProblemSets/PS4-mixture/pset4aleeze.jl", "max_stars_repo_name": "Aleezemalik25/fall-2021", "max_stars_repo_head_hexsha": "8b91c4956ebd06dd22fcb198a01f478276a3cc23", "max_stars_repo_licenses": ["MIT"], "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/pset4aleeze.jl", "max_issues_repo_name": "Aleezemalik25/fall-2021", "max_issues_repo_head_hexsha": "8b91c4956ebd06dd22fcb198a01f478276a3cc23", "max_issues_repo_licenses": ["MIT"], "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/pset4aleeze.jl", "max_forks_repo_name": "Aleezemalik25/fall-2021", "max_forks_repo_head_hexsha": "8b91c4956ebd06dd22fcb198a01f478276a3cc23", "max_forks_repo_licenses": ["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.6329113924, "max_line_length": 135, "alphanum_fraction": 0.6549586777, "num_tokens": 782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693702514737, "lm_q2_score": 0.8976953023710936, "lm_q1q2_score": 0.8525137324804627}}
{"text": "### A Pluto.jl notebook ###\n# v0.16.0\n\nusing Markdown\nusing InteractiveUtils\n\n# \u2554\u2550\u2561 10349518-03ca-11eb-09b2-69c80c4662ac\nbegin\n\tusing Pkg\n\tcd(joinpath(dirname(@__FILE__),\"..\"))\n    Pkg.activate(pwd())\n\tusing JuMP, Tulip, GLPK, LinearAlgebra\n\tusing Distributions, Plots, StatsPlots, LaTeXStrings, Measures\nend\n\n# \u2554\u2550\u2561 f7f3a256-03c6-11eb-2c1e-83cc62bf55e6\nmd\"\"\"\n# Linear programming\nWe will be using [JuMP](https://jump.dev/JuMP.jl/stable/) as a general framework, combined with [Tulip](https://github.com/ds4dm/Tulip.jl) or [GLPK](https://github.com/jump-dev/GLPK.jl) as a solver.\n\"\"\"\n\n# \u2554\u2550\u2561 7910d53e-03ca-11eb-1536-7fc4c236e10a\nmd\"\"\"\n## Application - Employee planning\nWe manage a crew of call center employees and want to optimise our shifts in order to reduce the total payroll cost. Employees have to work for five consecutive days and are then given two days off. The current policy is simple: each day gets the same amount of employees (currently we have 5 persons per shift, which leads to 25 persons on any given day).\n\nWe have some historical data that gives us the minimum amount of calls we can expect: Mon: 22, Tue: 17, Wed:13, Thu:14, Fri: 15, Sat: 18, Sun: 24\n\nEmployees are payed \u20ac 96 per day of work. This lead to the current payroll cost of 25x7x96 = \u20ac 16.800. You need to optimize employee planning to reduce the payroll cost.\n\n\n| Schedule | Days worked | Attibuted Pers | Mon | Tue | Wed | Thu | Fri | Sat |\u00a0Sun |\n|----------|-------------|----------------|-----|-----|-----|-----|-----|-----|-----|\n| A | Mon-Fri | 5 | W | W | W | W | W | O | O |\n| B | Tue-Sat | 5 | O | W | W | W | W | W | O |\n| C | Wed-Sun | 5 | O | O | W | W | W | W | W |\n| D | Thu-Mon | 5 | W | O | O | W | W | W | W |\n| E | Fri-Tue | 5 | W | W | O | O | W | W | W |\n| F | Sat-Wed | 5 | W | W | W | O | O | W | W |\n| G | Sun-Thu | 5 | W | W | W | W | O | O | W |\n| Totals: | - | 35 | 5 | 5 | 5 | 5 | 5 | 5 | 5 |\n| Required: | - | - | 22 | 17 | 13 | 14 | 15 | 18 | 24 |\n\n### Mathematical formulation\nWe need do formaly define our decision variables, constraints and objective function.\n* decision variables: the amount of persons attributed to each schedule ( ``Y = [y_1,y_2,\\dots,y_7]^{\\intercal} ``)\n* objective function: the payroll cost\n  \n  Suppose the matrix ``A`` is the matrix indicating the workload for each schedule (in practice ``W=1`` and ``O=0``):\n```math\nA = \\begin{bmatrix}  \nW & W & W & W & W & O & O \\\\\nO & W & W & W & W & W & O \\\\\nO & O & W & W & W & W & W \\\\\nW & O & O & W & W & W & W \\\\\nW & W & O & O & W & W & W \\\\\nW & W & W & O & O & W & W \\\\\nW & W & W & W & O & O & W \t\\\\\n\\end{bmatrix}\n```\n\n  Now $$Y*A'$$ gives us a vector indicating the amount of employees working on a given day. Suppose we also use the vector $$c$$ to indicate the salary for a given day (in this case $$c = [96,96,96,\\dots,96]$$). \n\nWe are now able to write our objective function:\n```math\n\\min Z = c^\\intercal A^\\intercal Y\n```\n\n* constraints (1): each day we need at least enough employees to cover all incoming calls. Suppose we use the vector $$b$$ to indicate the amount of incoming calls for a given day. We are able to write the constraints in a compact way:\n\n```math\n\\text{subject to } A^\\intercal Y  \\ge b \n```\n\n* constraints (2): we also want to avoid a negative amount of attributed employees on any given day, since this would lead to a negative payroll cost:\n```math\n\\text{and }Y \\ge 0\n```\n\n* $\\forall Y : Y \\in \\mathbb{N}$\n### Implementation\n\"\"\"\n\n# \u2554\u2550\u2561 572d14c4-03cb-11eb-2b68-234b3d7e9e8e\nbegin\n\t# basic data\n\tA = ones(Bool,7,7) - diagm(-1=>ones(Bool,6), -2=> ones(Bool,5), 5=>ones(Bool,2), 6=>ones(Bool,1))\n\tY = [5,5,5,5,5,5,5]\n\tB = [22,17,13,14,15,18,24]\n\tC = [96,96,96,96,96,96,96];\n\tA\nend\n\n# \u2554\u2550\u2561 4ba4687e-087f-11eb-1cb0-2581818cbd93\n# A' * Y .> B\nC' * A' * Y\n\n# \u2554\u2550\u2561 79351ee4-087f-11eb-147d-d389de200857\nlet\n\tmodel = Model(GLPK.Optimizer)\n\t@variable(model, Y[1:7] >= 0, Int)\n\t@constraint(model, A' * Y .>= B)\n\t@objective(model, Min, C' * A' * Y)\n\toptimize!(model)\n\ttermination_status(model)\n\tobjective_value(model)\n\t#A' * value.(Y) .> B\n\tsum(value.(Y))\nend\n\n# \u2554\u2550\u2561 3bafd152-6724-4847-a79d-f2340e2ab5e4\n\n\n# \u2554\u2550\u2561 4bc4c2aa-04b4-11eb-2b6e-452d4ecc258a\nmd\"\"\"\n### Adding uncertainty\nUp to now, we have had constant numbers the minimum number of employees needed per day. In reality these quantities are uncertain. The actual number of calls will fluctuate each day. For simplicity's sake will we use a [lognormal distribution](https://en.wikipedia.org/wiki/Log-normal_distribution#Occurrence_and_applications) for the amount of calls (using their initial value as mean and a standard deviation of two). Working this way, we avoid having negative calls.\n\"\"\"\n\n# \u2554\u2550\u2561 6e48e306-04b4-11eb-2561-0151a5e0a908\nB\n\n# \u2554\u2550\u2561 7a54f9b4-04b4-11eb-3a7c-8d90eb026392\nbegin\n\t# generating the distributions\n\tB_u = Distributions.LogNormal.(B,2) # array with distributions\n\n\t# quick sample to illustrate amount of calls being randomized\n\tlog.(rand.(B_u))\nend\n\n# \u2554\u2550\u2561 9d3ceafe-0880-11eb-36f0-0f8530d6b285\nbegin\n\tcost = Float64[]\n\tfor _ in 1:10000\n\t\tlet cout=cost\n\t\t\tmodel = Model(GLPK.Optimizer)\n\t\t\t@variable(model, Y[1:7] >= 0, Int)\n\t\t\t@constraint(model, A' * Y .>= log.(rand.(B_u)))\n\t\t\t@objective(model, Min, C' * A' * Y)\n\t\t\toptimize!(model)\n\t\t\tpush!(cout, objective_value(model))\n\t\tend\n\tend\n\tcost\nend\n\n# \u2554\u2550\u2561 14a32a20-0881-11eb-1a20-715b99417266\nStatsPlots.histogram(cost, yscale=:log10)\n\n# \u2554\u2550\u2561 259bbbc6-04b5-11eb-1ad4-c567e45ba4b6\nmd\"\"\"\n### Small variant: adding a commission\nSuppose each worker receives extra pay for the amount of calls that have been treated. We can easily include this in our model\n\"\"\"\n\n# \u2554\u2550\u2561 83130656-0881-11eb-2c87-a3ae5f81f04b\nbegin\n\tcost_c = Float64[]\n\tcommission = 20\n\tfor _ in 1:1000\n\t\tlet cout=cost_c\n\t\t\tmodel = Model(GLPK.Optimizer)\n\t\t\tappels = log.(rand.(B_u))\n\t\t\t@variable(model, Y[1:7] >= 0, Int)\n\t\t\t@constraint(model, A' * Y .>= appels)\n\t\t\t@objective(model, Min, C' * A' * Y + sum(appels) * commission)\n\t\t\toptimize!(model)\n\t\t\tpush!(cout, objective_value(model))\n\t\tend\n\tend\n\tStatsPlots.histogram(cost_c)\nend\n\n# \u2554\u2550\u2561 e1e41ea6-04b5-11eb-174e-1d43f601a07c\nmd\"\"\"\n#### Playing it safe\nThe above has given us some information on what the distributions of the payroll cost may be, however in reality, you would want to make sure that the clients calling to center are taken care off. To realise this, one might say that for any given day, you want to make sure that 90% of all calls can be treated by the specific capacity.\n\"\"\"\n\n# \u2554\u2550\u2561 62b516be-0882-11eb-094b-d183f8d00ab8\nlog.(quantile.(B_u, 0.90))\n\n# \u2554\u2550\u2561 6274be66-0882-11eb-11be-05163cda6633\n let\n\tmodel = Model(GLPK.Optimizer)\n\t@variable(model, Y[1:7] >= 0, Int)\n\t@constraint(model, A' * Y .>= log.(quantile.(B_u, 0.99)))\n\t@objective(model, Min, C' * A' * Y)\n\toptimize!(model)\n\ttermination_status(model)\n\tobjective_value(model)\nend\n\n# \u2554\u2550\u2561 1f177098-04b6-11eb-2508-6bd8d7e1e996\nmd\"\"\"\n### Additional questions\n* The example we have treated so far has very traditional working patterns for the employees. How woud you deal with modern working patterns (e.g. 4/5 or parttime working)?\n* We took a look at the stochastic nature of the amount of calls, however, the personnel might not show up for various reasons. How would you describe the possible influence? Hint: make a discrete event model of this setting, using the optimal design and controlling for employees showing up or not.\n\"\"\"\n\n# \u2554\u2550\u2561 Cell order:\n# \u255f\u2500f7f3a256-03c6-11eb-2c1e-83cc62bf55e6\n# \u2560\u255010349518-03ca-11eb-09b2-69c80c4662ac\n# \u255f\u25007910d53e-03ca-11eb-1536-7fc4c236e10a\n# \u2560\u2550572d14c4-03cb-11eb-2b68-234b3d7e9e8e\n# \u2560\u25504ba4687e-087f-11eb-1cb0-2581818cbd93\n# \u2560\u255079351ee4-087f-11eb-147d-d389de200857\n# \u2560\u25503bafd152-6724-4847-a79d-f2340e2ab5e4\n# \u255f\u25004bc4c2aa-04b4-11eb-2b6e-452d4ecc258a\n# \u2560\u25506e48e306-04b4-11eb-2561-0151a5e0a908\n# \u2560\u25507a54f9b4-04b4-11eb-3a7c-8d90eb026392\n# \u2560\u25509d3ceafe-0880-11eb-36f0-0f8530d6b285\n# \u2560\u255014a32a20-0881-11eb-1a20-715b99417266\n# \u255f\u2500259bbbc6-04b5-11eb-1ad4-c567e45ba4b6\n# \u2560\u255083130656-0881-11eb-2c87-a3ae5f81f04b\n# \u255f\u2500e1e41ea6-04b5-11eb-174e-1d43f601a07c\n# \u2560\u255062b516be-0882-11eb-094b-d183f8d00ab8\n# \u2560\u25506274be66-0882-11eb-11be-05163cda6633\n# \u255f\u25001f177098-04b6-11eb-2508-6bd8d7e1e996\n", "meta": {"hexsha": "48a424f4b15665d2aea6a4f79c212dc7a2dbc661", "size": 8089, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Exercises/PS05 - Linear programming I.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/PS05 - Linear programming I.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/PS05 - Linear programming I.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": 36.6018099548, "max_line_length": 469, "alphanum_fraction": 0.6789467178, "num_tokens": 3059, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9481545377452442, "lm_q2_score": 0.8991213820004279, "lm_q1q2_score": 0.8525060183274809}}
{"text": "module Bisect\n\nexport idx_of_closest\n#export bin_search, idx_of_closest\n\nfunction midpoint(a, b)\n    if a > b\n        error(\"... b must be greater or equal than a; a == $a, b == $b\")\n    elseif a == b\n        a\n    else\n        div(a + b , 2)\n    end\nend\n\n#................ 1) Search bin\nfunction search_bin(edges::Vector{Float64}, val::Float64, imin::Int, imax::Int)\n    # find the BIN - characterized by the pair of edges\n    # If\n    imid = midpoint(imin, imax)\n    if imin == imax\n        if val >= edges[imid]\n            imid + 1\n        else\n            imid\n        end\n    else\n        if val >= edges[imid]\n            search_bin(edges, val, imid + 1, imax)\n        else\n            search_bin(edges, val, imin, max(imid - 1, imin))\n        end\n    end\nend\n\nfunction search_bin(edges::Vector{Float64}, val::Float64)\n    search_bin(edges, val, 1, length(edges))\nend\n\nfunction test_search_bin()\n    println( search_bin([0.1, 0.2, 0.3], 0.05)) # 1\n    println( search_bin([0.1, 0.2, 0.3], 0.10)) # 2\n    println( search_bin([0.1, 0.2, 0.3], 0.15)) # 2\n    println( search_bin([0.1, 0.2, 0.3], 0.19)) # 2\n    println( search_bin([0.1, 0.2, 0.3], 0.29)) # 3\n    println( search_bin([0.1, 0.2, 0.3], 0.31)) # 4\nend\n# test_search_bin()\n#................ End 1) Search bin\n#............... 2) Index of the closest element\nfunction idx_of_closest(edges::Vector{Float64}, val::Float64, imin::Int, imax::Int)\n    # Find index of the closest edge to the value\n    bin  = search_bin(edges, val)\n    n = length(edges)\n    if bin == 1\n        edges[bin]\n    elseif bin == n + 1\n        edges[n]\n    else\n        left_dist  = abs(val - edges[bin-1])\n        right_dist = abs(val - edges[bin]  )\n        left_dist >= right_dist ? bin : bin - 1\n    end\nend\n\nfunction idx_of_closest(edges::Vector{Float64}, val::Float64)\n    idx_of_closest(edges, val, 1, length(edges))\nend\n\nfunction test_bin_search_closest_idx()\n    println( idx_of_closest([0.1, 0.2, 0.5], 0.15))\n    println( idx_of_closest([0.1, 0.2, 0.5], 0.16))\nend\n#test_bin_search_closest_idx()\n#............... End 2) Index of the closest element\nend\n", "meta": {"hexsha": "bec3ceb4dd2512401f55182b10d47a3554275537", "size": 2101, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "data/archive/bin_search.jl", "max_stars_repo_name": "av-maslov/Recurrency", "max_stars_repo_head_hexsha": "620a34badc66247e348a47b76828ed5a562246c4", "max_stars_repo_licenses": ["MIT"], "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/archive/bin_search.jl", "max_issues_repo_name": "av-maslov/Recurrency", "max_issues_repo_head_hexsha": "620a34badc66247e348a47b76828ed5a562246c4", "max_issues_repo_licenses": ["MIT"], "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/archive/bin_search.jl", "max_forks_repo_name": "av-maslov/Recurrency", "max_forks_repo_head_hexsha": "620a34badc66247e348a47b76828ed5a562246c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2857142857, "max_line_length": 83, "alphanum_fraction": 0.5792479772, "num_tokens": 720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966717067253, "lm_q2_score": 0.9005297947939936, "lm_q1q2_score": 0.8524385065247347}}
{"text": "# ## Line plot 2d\n\n#md # ![FILE_NAME.png](images/FILE_NAME.png)\n\nx = 0:0.1:2pi\ny1 = cos.(x)\ny2 = sin.(x)\n\nplot(x, y1, c=\"blue\", linewidth=3)\nplot!(x, y2, c=\"red\", line=:dash)\ntitle!(\"Trigonometric functions\")\nxlabel!(\"angle\")\nylabel!(\"sin(x) and cos(x)\")\n\n## axis limit\nplot!(xlims=(0,2pi), ylims=(-2, 2))\n\n#-\n## same plot\nx = 0:0.1:2pi\ny1 = cos.(x)\ny2 = sin.(x)\n\nplot(x, y1,\n    c=\"blue\",\n    linewidth=3,\n    title=\"Trigonometric functions\",\n    xlabel=\"angle\",\n    ylabel=\"sin(x) and cos(x)\")\nplot!(x, y2, c=\"red\", line=:dash)\n\nplot!(xlims=(0,2pi), ylims=(-2, 2))\n", "meta": {"hexsha": "60eb297368c710ba235b1f153ce920086cfd6802", "size": 567, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "site_generator/line_plot_2d_1.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_plot_2d_1.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_plot_2d_1.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": 17.1818181818, "max_line_length": 44, "alphanum_fraction": 0.5802469136, "num_tokens": 223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582574225517, "lm_q2_score": 0.9161096107264306, "lm_q1q2_score": 0.8524017520045668}}
{"text": "\"\"\"\nhatfun(x,t,k)\n\nEvaluate a piecewise linear \"hat\" function at `x`, where `t` is a\nvector of n+1 interpolation nodes and `k` is an integer in 0:n\ngiving the index of the node where the hat function equals one.\n\"\"\"\n\nfunction hatfun(x,t,k)\n    n = length(t)-1\n    # Return correct node given mathematical index k, including\n    # fictitious choices.   \n    function node(k)\n        if k < 0\n            2t[1]-t[2]\n        elseif k > n \n            2t[n+1]-t[n] \n        else\n            t[k+1]\n        end\n    end\n\n    H1 = (x-node(k-1))/(node(k)-node(k-1))   # upward slope\n    H2 = (node(k+1)-x)/(node(k+1)-node(k))   # downward slope\n\n    H = min(H1,H2)\n    return max(0,H)\nend\n\n\"\"\"\nplinterp(t,y)\n\nCreate a piecewise linear interpolating function for data values in\n`y` given at nodes in `t`.\n\"\"\"\nfunction plinterp(t,y)\nn = length(t)-1\nreturn x -> sum( y[k+1]*hatfun(x,t,k) for k in 0:n )\nend\n\n\"\"\"\nspinterp(t,y)\n\nCreate a cubic not-a-knot spline interpolating function for data\nvalues in `y` given at nodes in `t`.\n\"\"\"\nfunction spinterp(t,y)\n\n    n = length(t)-1\n    h = diff(t)         # differences of all adjacent pairs\n\n    # Preliminary definitions.\n    Z = zeros(n,n);\n    In = I(n);  E = In[1:n-1,:];\n    J = diagm(0=>ones(n),1=>-ones(n-1))\n    H = diagm(0=>h)\n\n    # Left endpoint interpolation:\n    AL = [ In Z Z Z ]\n    vL = y[1:n]\n\n    # Right endpoint interpolation:\n    AR = [ In H H^2 H^3 ];\n    vR = y[2:n+1]\n\n    # Continuity of first derivative:\n    A1 = E*[ Z J 2*H 3*H^2 ]\n    v1 = zeros(n-1)\n\n    # Continuity of second derivative:\n    A2 = E*[ Z Z J 3*H ]\n    v2 = zeros(n-1)\n\n    # Not-a-knot conditions:\n    nakL = [ zeros(1,3*n) [1 -1 zeros(1,n-2)] ]\n    nakR = [ zeros(1,3*n) [zeros(1,n-2) 1 -1] ]\n\n    # Assemble and solve the full system.\n    A = [ AL; AR; A1; A2; nakL; nakR ]\n    v = [ vL; vR; v1; v2; 0; 0 ]\n    z = A\\v\n\n    # Break the coefficients into separate vectors.\n    rows = 1:n\n    a = z[rows]\n    b = z[n.+rows];  c = z[2*n.+rows];  d = z[3*n.+rows]\n    S = [ Polynomial([a[k],b[k],c[k],d[k]]) for k = 1:n ]\n    # This function evaluates the spline when called with a value\n    # for x.\n    function evaluate(x)\n        k = findfirst(@. x<t)   # one greater than interval x belongs to\n        k==1 && return NaN\n        if isnothing(k)\n            return x==t[end] ? y[end] : NaN\n        end\n        return S[k-1](x-t[k-1])\n    end\n    return evaluate\nend\n\n\"\"\"\nfdweights(t,m)\n\nReturn weights for the `m`th derivative of a function at zero using\nvalues at the nodes in vector `t`.\n\"\"\"\nfunction fdweights(t,m)\n    # This is a compact implementation, not an efficient one.\n\n    function weight(t,m,r,k)\n        # Recursion for one weight. Input: t   nodes (vector) m\n        # order of derivative sought r   number of nodes to use from\n        # t (<= length(t)) k   index of node whose weight is found\n\n        if (m<0) || (m>r)        # undefined coeffs must be zero\n            c = 0\n        elseif (m==0) && (r==0)  # base case of one-point interpolation\n            c = 1\n        else                     # generic recursion\n            if k<r\n                c = (t[r+1]*weight(t,m,r-1,k) -\n                    m*weight(t,m-1,r-1,k))/(t[r+1]-t[k+1])\n            else\n                numer = r > 1 ? prod(t[r]-x for x in t[1:r-1]) : 1.0\n                denom = r > 0 ? prod(t[r+1]-x for x in t[1:r]) : 1.0\n                \u03b2 = numer/denom\n                c = \u03b2*(m*weight(t,m-1,r-1,r-1) - t[r]*weight(t,m,r-1,r-1))\n            end\n        end\n        return c\n    end\n\n    r = length(t)-1\n    w = zeros(size(t))\n    return [ weight(t,m,r,k) for k=0:r ]\nend\n\n\"\"\"\ntrapezoid(f,a,b,n)\n\nApply the trapezoid integration formula for integrand `f` over\ninterval [`a`,`b`], broken up into `n` equal pieces. Returns\nestimate, vector of nodes, and vector of integrand values at the\nnodes.\n\"\"\"\nfunction trapezoid(f,a,b,n)\n    h = (b-a)/n\n    t = LinRange(a,b,n+1)\n    y = f.(t)\n    T = h * ( sum(y[2:n]) + 0.5*(y[1] + y[n+1]) )\n\n    return T,t,y\nend\n\n\"\"\"\nintadapt(f,a,b,tol)\n\nDo adaptive integration to estimate the integral of `f` over\n[`a`,`b`] to desired error tolerance `tol`. Returns estimate and a\nvector of evaluation nodes used.\n\"\"\"\nfunction intadapt(f,a,b,tol)\n    # Use error estimation and recursive bisection.\n    function do_integral(a,fa,b,fb,m,fm,tol)\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        else\n            # Error is too large--bisect and recurse.\n            QL,tL = do_integral(a,fa,m,fm,xl,fl,tol)\n            QR,tR = do_integral(m,fm,b,fb,xr,fr,tol)\n            Q = QL + QR\n            t = [tL;tR[2:end]]   # merge the nodes w/o duplicate\n        end\n        return Q,t\n    end\n\n    m = (b+a)/2\n    Q,t = do_integral(a,f(a),b,f(b),m,f(m),tol)\n    return Q,t\nend\n", "meta": {"hexsha": "30dffaaea14326541d8c9a88be9696d6e006fcc7", "size": 5291, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chapter05.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": "src/chapter05.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": "src/chapter05.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": 26.9948979592, "max_line_length": 74, "alphanum_fraction": 0.5276885277, "num_tokens": 1758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947055100817, "lm_q2_score": 0.9019206798249232, "lm_q1q2_score": 0.852310267224606}}
{"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\n    n = size(L,1)\n    x = zeros(n)\n    for 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]\n    end\n\n    return 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\n    n = size(U,1)\n    x = zeros(n)\n    for 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]\n    end\n\n    return x\nend\n\n\"\"\"\n    lufact(A)\n\nCompute the LU factorization of square matrix `A`, returning the factors.\n\"\"\"\nfunction lufact(A)\n\n    n = size(A,1)\n    L = Matrix(Diagonal(ones(n)))    # puts ones on diagonal\n    U = copy(A)\n\n    # Gaussian elimination\n    for 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\n    end\n\n    return L,triu(U)\nend\n", "meta": {"hexsha": "b8b006414d3856458f451d814783dab65d53ca48", "size": 1057, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/functions/chapter02.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/chapter02.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/chapter02.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": 18.224137931, "max_line_length": 76, "alphanum_fraction": 0.5108798486, "num_tokens": 368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539661002182847, "lm_q2_score": 0.8933093954028817, "lm_q1q2_score": 0.8521868802208407}}
{"text": "using LinearAlgebra \n\nfunction classical_gram_schmidt(A)\n    m, n = size(A)\n    R = zeros(n, n)\n    Q = zeros(m, n)\n    for j in 1:n\n        v_j = A[:, j]\n        for i in 1:(j-1)\n            R[i, j] = dot(Q[:, i], A[:, j])\n            v_j = v_j - R[i, j] * Q[:, i]\n        end \n        R[j, j] = norm(v_j)\n        Q[:, j] = v_j / R[j, j]\n    end\n    return Q, R\nend \n\nfunction modified_gram_schmidt(A)\n    m, n = size(A)\n    R = zeros(Float64, n, n)\n    Q = zeros(Float64, m, n)\n\n    V = zeros(Float64, n, n)\n    for i in 1:n\n        V[:, i] = A[:, i]\n    end\n\n    for i in 1:n\n        R[i, i] = norm(V[:, i])\n        Q[:, i] = V[:, i] / R[i, i]\n        for j in (i+1):n\n            R[i, j] = dot(Q[:, i], V[:, j])\n            V[:, j] = V[:, j] - R[i, j] * Q[:, i]\n        end \n    end \n    return Q, R\nend \n\n\nfunction check_stability(Q)\n    m, n = size(Q)\n    total_dot_error = 0 \n    for i in 1:m\n        for j in 1:n \n            if i != j\n                total_dot_error += abs(dot(Q[:, i], Q[:, j]))\n            end \n        end \n    end \n    return total_dot_error\nend \n\n\n", "meta": {"hexsha": "66a05463aaa62274343f41eb074b7470ab040762", "size": 1079, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "qr.jl", "max_stars_repo_name": "CornellDataScience/interpret-ml", "max_stars_repo_head_hexsha": "e8cd6d1fb1ccadf820c494c33ce2bedc2fd3bbef", "max_stars_repo_licenses": ["MIT"], "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.jl", "max_issues_repo_name": "CornellDataScience/interpret-ml", "max_issues_repo_head_hexsha": "e8cd6d1fb1ccadf820c494c33ce2bedc2fd3bbef", "max_issues_repo_licenses": ["MIT"], "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.jl", "max_forks_repo_name": "CornellDataScience/interpret-ml", "max_forks_repo_head_hexsha": "e8cd6d1fb1ccadf820c494c33ce2bedc2fd3bbef", "max_forks_repo_licenses": ["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.6181818182, "max_line_length": 61, "alphanum_fraction": 0.4087117702, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.969324199175492, "lm_q2_score": 0.8791467785920306, "lm_q1q2_score": 0.8521782471164336}}
{"text": "\"\"\"\nEstimate if the number is prime\n\"\"\"\nfunction check_composite(a::BigInt, d::BigInt, n::BigInt, s::BigInt) \n    x = exp!(a, d, n)\n\n    if (x == 1 || x == (n - 1))\n        return (false)\n    end\n\n    for _ in 1:s\n        x = (x * x) % n\n        if (x == (n - 1))\n            return (false)\n        end\n    end\n    true\nend\n\ncheck_composite(a::T, d::T, n::T, s::T) where {T <: Integer} =\ncheck_composite(big(a), big(d), big(n), big(s))\n\n\"\"\"Miller Rabin primality test\nReturn False if n is composite, True(probably prime) otherwise.\n\nn: Number to be tested for primality\nk: number of iterations to run the test\n\"\"\"\nfunction miller_rabin(n::BigInt, k::BigInt = big(10)) \n    if (n == 2)\n        return (true)\n    end\n    if (n == 1 || n % 2 == 0)\n        return (false)\n    end \n\n    s::BigInt = 0\n    d = n - 1\n\n    while d % 2 == 0\n        s += 1\n        d /= 2\n    end\n\n    @assert floor(BigInt, 2 ^ s * d) == n - 1\n\n    for _ in 1:k\n        a = rand(2:n - 1)\n        d = floor(BigInt, d)\n        if (check_composite(a, d, n, s))\n            return (false)\n        end\n    end\n    true\nend\n\nmiller_rabin(n::T, k::T = 10) where {T <: Integer} = \nmiller_rabin(big(n), big(k))\n\n\"\"\"\nSolovay Strassen Primality Test\nReturns False is n is composite, True(probably prime) otherwise\n\nn: Number to be tested for primality\nk: number of iterations to run the test\n\"\"\"\nfunction solovay_strassen(n::BigInt, k::BigInt = big(10)) \n    if (n == 2)\n        return (true)\n    end\n    if (n == 1 || n & 1 == 0)\n        return (false)\n    end\n\n    for _ in 1:k\n        a = rand(2:n-1)\n        x = (jacobi!(a, n) + n) % n\n        if (x == 0 || exp!(a, floor(BigInt, (n - 1) / 2), n) != x)\n            return (false)\n        end\n    end\n    true\nend\n\nsolovay_strassen(n::T, k::T = 10) where {T <: Integer} = \nsolovay_strassen(big(n), big(k))\n\n\"\"\"\nFermat's Primality test\nReturns True(probably prime) if n is prime, Flase if n is composite\n\nn: Number to be tested for primality\nk: number of iterations of the Fermat's Primality Test\n\"\"\"\nfunction fermat_test(n::BigInt, k::BigInt = big(10)) \n    if (n == 2)\n        return (true)\n    end\n    if (n & 1 == 0)\n        return (false)\n    end\n\n    for _ in 1:k\n        a = rand(2:n-1)\n        if (exp!(a, n - 1, n) != 1)\n            return (false)\n        end\n    end\n    true\nend\n\nfermat_test(n::T, k::T = 10) where {T <: Integer} = \nfermat_test(big(n), big(k))\n", "meta": {"hexsha": "7f630f810c238acbc212d65eddf5beeacbfcabb3", "size": 2386, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/primality.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/primality.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/primality.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": 20.9298245614, "max_line_length": 69, "alphanum_fraction": 0.5331098072, "num_tokens": 817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102561735719, "lm_q2_score": 0.8807970670261976, "lm_q1q2_score": 0.8520921162487446}}
{"text": "export SoftMax\n\n\"\"\"\n`SoftMax([domainType=Float64::Type,] dim_in::Tuple)`\n\nCreates the softmax non-linear operator with input dimensions `dim_in`.\n```math\n\\\\sigma(\\\\mathbf{x}) = \\\\frac{e^{\\\\mathbf{x} }}{ \\\\sum e^{\\\\mathbf{x} } }\n```\n\n\"\"\"\nstruct SoftMax{T,N} <: NonLinearOperator\n\tdim::NTuple{N,Int}\n\tbuf::Array{T,N}\nend\n\nfunction SoftMax(DomainType::Type, DomainDim::NTuple{N,Int}) where {N} \n\tSoftMax{DomainType,N}(DomainDim,zeros(DomainType,DomainDim))\nend\n\nSoftMax(DomainDim::NTuple{N,Int}) where {N} = SoftMax(Float64,DomainDim)\n\nfunction mul!(y::AbstractArray{T,N}, L::SoftMax{T,N}, x::AbstractArray{T,N}) where {T,N}\n\ty .= exp.(x.-maximum(x))\n\ty ./= sum(y)\nend\n\nfunction mul!(y::AbstractArray, \n              J::AdjointOperator{Jacobian{A,TT}}, \n              b::AbstractArray) where {T, N, A<: SoftMax{T,N}, TT <: AbstractArray{T,N} }\n    L = J.A\n\tfill!(y,zero(T))\n\tL.A.buf .= exp.(L.x.-maximum(L.x))\n\tL.A.buf ./= sum(L.A.buf)\n\tfor i in eachindex(y)\n\t\ty[i] = -L.A.buf[i]*dot(L.A.buf,b) \n\t\ty[i] += L.A.buf[i]*b[i]\n\tend\n\treturn y\nend\n\nfun_name(L::SoftMax) = \"\u03c3\"\n\nsize(L::SoftMax) = (L.dim, L.dim)\n\ndomainType(L::SoftMax{T,N}) where {T,N} = T\ncodomainType(L::SoftMax{T,N}) where {T,N} = T\n", "meta": {"hexsha": "f26408d399c70b6fe495a70f1c023b53ce8123a5", "size": 1192, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nonlinearoperators/SoftMax.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/SoftMax.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/SoftMax.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.8333333333, "max_line_length": 89, "alphanum_fraction": 0.6275167785, "num_tokens": 414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611643025387, "lm_q2_score": 0.8872045817875224, "lm_q1q2_score": 0.8520368251400119}}
{"text": "@doc doc\"\"\"\nApproximation de la solution du probl\u00e8me ``\\min_{x \\in \\mathbb{R}^{n}} f(x)`` en utilisant l'algorithme de Newton\n\n# Syntaxe\n```julia\nxk,f_min,flag,nb_iters = Algorithme_de_Newton(f,gradf,hessf,x0,option)\n```\n\n# Entr\u00e9es :\n   * **f**       : (Function) la fonction \u00e0 minimiser\n   * **gradf**   : (Function) le gradient de la fonction f\n   * **hessf**   : (Function) la Hessienne de la fonction f\n   * **x0**      : (Array{Float,1}) premi\u00e8re approximation de la solution cherch\u00e9e\n   * **options** : (Array{Float,1})\n       * **max_iter**      : le nombre maximal d'iterations\n       * **Tol_abs**       : la tol\u00e9rence absolue\n       * **Tol_rel**       : la tol\u00e9rence relative\n\n# Sorties:\n   * **xmin**    : (Array{Float,1}) une approximation de la solution du probl\u00e8me  : ``\\min_{x \\in \\mathbb{R}^{n}} f(x)``\n   * **f_min**   : (Float) ``f(x_{min})``\n   * **flag**     : (Integer) indique le crit\u00e8re sur lequel le programme \u00e0 arr\u00eater\n      * **0**    : Convergence\n      * **1**    : stagnation du xk\n      * **2**    : stagnation du f\n      * **3**    : nombre maximal d'it\u00e9ration d\u00e9pass\u00e9\n   * **nb_iters** : (Integer) le nombre d'it\u00e9rations faites par le programme\n\n# Exemple d'appel\n```@example\nusing Optinum\nf(x)=100*(x[2]-x[1]^2)^2+(1-x[1])^2\ngradf(x)=[-400*x[1]*(x[2]-x[1]^2)-2*(1-x[1]) ; 200*(x[2]-x[1]^2)]\nhessf(x)=[-400*(x[2]-3*x[1]^2)+2  -400*x[1];-400*x[1]  200]\nx0 = [1; 0]\noptions = []\nxmin,f_min,flag,nb_iters = Algorithme_De_Newton(f,gradf,hessf,x0,options)\n```\n\"\"\"\nfunction Algorithme_De_Newton(f::Function,gradf::Function,hessf::Function,x0,options)\n\n    \"# Si options == [] on prends les param\u00e8tres par d\u00e9faut\"\n    if options == []\n        max_iter = 100\n        Tol_abs = sqrt(eps())\n        Tol_rel = 1e-15\n    else\n        max_iter = options[1]\n        Tol_abs = options[2]\n        Tol_rel = options[3]\n    end\n    \n    n = length(x0)\n    xmin = x0\n    f_min = 0\n    flag = 0\n    nb_iters = 0\n    xk = x0\n    xk_1 = x0\n    \n    while (norm(gradf(xk)) > max(Tol_rel * norm(gradf(x0)), Tol_abs))\n        nb_iters += 1\n        xk_1 = xk\n        dk = -hessf(xk) \\ gradf(xk)\n        xk = xk + dk\n        \n        if norm(gradf(xk_1)) <= max(Tol_abs, Tol_rel * norm(gradf(x0)))\n            flag = 0\n            break\n        \n        elseif norm(dk) <= max(Tol_abs, Tol_rel * norm(xk))\n            flag = 1\n            break\n        \n        elseif abs(f(xk_1) - f(xk)) <= max(Tol_abs, Tol_rel * abs(f(xk)))\n            flag = 2\n            break\n        elseif nb_iters == max_iter\n            flag = 3\n            break\n        end\n    end\n    \n    xmin = xk\n    f_min = f(xmin)\n    \n    return xmin,f_min,flag,nb_iters\nend\n", "meta": {"hexsha": "78f52dfd169d1ec4f27f6d0e9e2cf8c82993938a", "size": 2652, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "2A/S7/Optimisation/TP-Projet/src/Algorithme_De_Newton.jl", "max_stars_repo_name": "MOUDDENEHamza/ENSEEIHT", "max_stars_repo_head_hexsha": "a90b1dee0c8d18a9578153a357278d99405bb534", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-05-02T12:32:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T20:20:35.000Z", "max_issues_repo_path": "2A/S7/Optimisation/TP-Projet/src/Algorithme_De_Newton.jl", "max_issues_repo_name": "MOUDDENEHamza/ENSEEIHT", "max_issues_repo_head_hexsha": "a90b1dee0c8d18a9578153a357278d99405bb534", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-01-14T20:03:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-30T01:10:00.000Z", "max_forks_repo_path": "2A/S7/Optimisation/TP-Projet/src/Algorithme_De_Newton.jl", "max_forks_repo_name": "MOUDDENEHamza/ENSEEIHT", "max_forks_repo_head_hexsha": "a90b1dee0c8d18a9578153a357278d99405bb534", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2020-11-11T21:28:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-19T13:54:22.000Z", "avg_line_length": 29.797752809, "max_line_length": 120, "alphanum_fraction": 0.5433634992, "num_tokens": 911, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611563610179, "lm_q2_score": 0.8872045817875224, "lm_q1q2_score": 0.8520368180942582}}
{"text": "function Example_4_3(; T = 200, seed = 1)\n\n    # Set random number generator\n\n    rg = MersenneTwister(seed)\n\n\n    # state x is four dimensional, comprises car position and velocities\n\n    \u0394t  = 1 / 10\n    \u03c3\u2081  = \u03c3\u2082  = 1 / 2\n    q\u1d9c\u2081 = q\u1d9c\u2082 = 1\n\n\n    # Matrices in the dynamic model are:\n\n    A = [1  0  \u0394t  0;\n         0  1   0  \u0394t;\n         0  0   1  0;\n         0  0   0  1]\n\n    Q = [(q\u1d9c\u2081*\u0394t^3)/3         0        (q\u1d9c\u2081*\u0394t^2)/2       0        ;\n              0         (q\u1d9c\u2082*\u0394t^3)/3         0        (q\u1d9c\u2081*\u0394t^2)/2 ;\n         (q\u1d9c\u2081*\u0394t^2)/2         0            q\u1d9c\u2081*\u0394t         0        ;\n              0         (q\u1d9c\u2082*\u0394t^2)/2         0          q\u1d9c\u2082*\u0394t     ]\n\n    # Measurement matrices\n\n    H = [1 0 0 0;\n         0 1 0 0]\n\n    R = [\u03c3\u2081^2  0;\n         0    \u03c3\u2082^2]\n\n    # initialise\n\n    m\u2080, P\u2080 = zeros(4), 0.1*Matrix(I, 4, 4)\n\n    x\u2080 = rand(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\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_3(seed = 1)\n\n    # Simulate data\n\n    yclean, y, x, A, H, Q, R, m\u2080, P\u2080 = Example_4_3(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)\n\n    subplot(211); cla()\n\n    plot(truepositions[1,:], truepositions[2,:], \"o\", label = \"true positions\")\n\n    plot(filtpositions[1,:], filtpositions[2,:], \".\", label = \"filter positions\", alpha=0.5)\n\n    legend()\n\n    subplot(212); cla()\n\n    plot(truepositions[1,:], truepositions[2,:], \"o\", label = \"true positions\")\n\n    plot(smoopositions[1,:], smoopositions[2,:], \".\", label = \"smooth positions\", alpha=0.5)\n\n    legend()\n\n    nothing\n\nend\n", "meta": {"hexsha": "25982225ff03a86150c69cc5528486cdf53a3dc3", "size": 2359, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Example_4_3.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_3.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_3.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.9915254237, "max_line_length": 98, "alphanum_fraction": 0.5036032217, "num_tokens": 943, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799462157138, "lm_q2_score": 0.8840392741081575, "lm_q1q2_score": 0.8520193240525388}}
{"text": "function Primes(N::Int64)\n\n\tisprime = ones(Bool,N)\n\t\n\tfor i = 2:int64(sqrt(N))\n\t\tif isprime[i]\n\t\t\tfor j in (i*i):i:N\n\t\t\t\tisprime[j] = false\n\t\t\tend\n\t\tend\n\tend\n\treturn filter(x -> isprime[x], 2:N)\nend\n\nfunction TrialDivision(N::Int64)\n\t\n\tprimeFactors = [1]\n\t\n\ttestPrimes = Primes(N);\n\tNc = N;\n\tidx = 1;\n\twhile (prod(primeFactors)!=N) && (idx < length(testPrimes))\n\t\tif mod(Nc, testPrimes[idx])==0\n\t\t\tprintln(testPrimes[idx])\n\t\t\tprimeFactors=[primeFactors,testPrimes[idx]]\n\t\t\tNc = Nc/testPrimes[idx]\n\t\tend\n\t\tidx = idx+1\n\tend\n\t\n\treturn primeFactors[2:end]\nend\n\nfunction LargestPrimeFactor(N::Int64)\n\t\n\tfirst20 = Primes(1000)\n\tlargest = 1\n\tfor p in first20\n\t\tif mod(N, p) == 0\n\t\t\tlargest = p\n\t\t\tN = fld(N,p)\n\t\tend\n\tend\n\tif N == 1\n\t\treturn largest\n\tend\n\ttrials = flipud(Primes(N+1))\n\tfor p in trials\n\t\tif (mod(N,p) == 0)&&(p > largest)\n\t\t\tprintln(p)\n\t\t\tlargest = p\n\t\t\tbreak\n\t\tend\n\tend\n\tif largest == 1\n\t\treturn N\n\telse\n\t\treturn largest\n\tend\nend\n\t\nfunction Euler3(N::Int64)\n\t\n\tbig = LargestPrimeFactor(N)\n\tprintln(\"The largest prime factor of \",N,\" is \",big,\".\")\n\t\nend\n\n@time Euler3(600851475143)\t\n#Euler3(100)\n\t", "meta": {"hexsha": "efa83122c72112b46130c900f0f027f79c5532e9", "size": 1105, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/OldFiles/problem_3.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_3.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_3.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": 15.5633802817, "max_line_length": 60, "alphanum_fraction": 0.6352941176, "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799451753696, "lm_q2_score": 0.8840392741081575, "lm_q1q2_score": 0.8520193231328336}}
{"text": "\"\"\"\r\n    bisection(f,a,b)\r\n\r\nadalah fungsi yang mencari nilai akar persamaan dari fungsi `f(x)` pada interval\r\ndi antara `a` dan `b`.\r\n\r\n# Examples\r\n```jldoctest\r\njulia> f(x) = x*sin(x)-1;\r\n\r\njulia> c, flag, M = bisection(f,0,2);\r\n\r\njulia> c\r\n1.1141571998596191\r\n\r\njulia> flag\r\n0\r\n\r\njulia> M\r\n22\u00d75 Array{Float64,2}:\r\n  0.0  0.0      1.0      2.0      -0.158529\r\n  1.0  1.0      1.5      2.0       0.496242\r\n  2.0  1.0      1.25     1.5       0.186231\r\n  3.0  1.0      1.125    1.25      0.015051\r\n  \u22ee\r\n 18.0  1.11415  1.11415  1.11416  -3.22926e-6\r\n 19.0  1.11415  1.11416  1.11416  -5.80313e-7\r\n 20.0  1.11416  1.11416  1.11416   7.44159e-7\r\n 21.0  1.11416  1.11416  1.11416   8.19227e-8\r\n```\r\nreturn solusi `c` 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, a, c, b, f(c)]`\r\n\r\n\"\"\"\r\nfunction bisection(f,a,b)\r\n    delta = 10^-7; maxi = 100; flag = 1;\r\n    M = Array{Float64}(undef, 0, 5);\r\n    fa = f(a); fb = f(b);\r\n    if fa*fb>0\r\n        c = \"error: f(a) dan f(b) harus berbeda tanda\";\r\n        flag = 2;\r\n        return;\r\n    end\r\n    k = 1\r\n    while k<=maxi\r\n        c  = (b+a)/2;\r\n        fc = f(c);\r\n        M = [M; [k-1 a c b fc] ];\r\n        if fc == 0\r\n            a = c;\r\n            b = c;\r\n        elseif fa*fc>0\r\n            a = c;\r\n            fa = fc;\r\n        else\r\n            b = c;\r\n            fb = fc;\r\n        end\r\n        if b-a < delta || abs(fc) < delta\r\n            flag = 0;\r\n            break;\r\n        end\r\n        k+=1\r\n    end\r\n    return c,flag, M\r\nend\r\n", "meta": {"hexsha": "7e4811c21b74851f553c39778f61dd1df4ad2461", "size": 1604, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/bisection.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/bisection.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/bisection.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.5882352941, "max_line_length": 84, "alphanum_fraction": 0.4750623441, "num_tokens": 667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037262250327, "lm_q2_score": 0.9196425284247979, "lm_q1q2_score": 0.8518683008749007}}
{"text": "using LinearAlgebra\nusing SparseArrays\nusing Plots\nusing ForwardDiff\n\n\"This code applies the method of manufactured solutions to the 2D Laplace's equation\nwith nonzero Dirichlet BCs using a finite difference method.\"\n\nm = 100 # number of points\n\nuexact(x,y) = log(2+sin(pi*x)*sin(pi*y))\ndudx_exact(x,y) = ForwardDiff.derivative(x->uexact(x,y),x)\ndudy_exact(x,y) = ForwardDiff.derivative(y->uexact(x,y),y)\ndu2dx2_exact(x,y) = ForwardDiff.derivative(x->dudx_exact(x,y),x)\ndu2dy2_exact(x,y) = ForwardDiff.derivative(y->dudy_exact(x,y),y)\nf(x,y) = -(du2dx2_exact(x,y) + du2dy2_exact(x,y))\n\nu_left(y)   = uexact(-1,y)\nu_right(y)  = uexact(1,y)\nu_bottom(x) = uexact(x,-1)\nu_top(x)    = uexact(x,1)\nuBC = (u_left,u_right,u_bottom,u_top)\n\nfunction solve(m,f,uBC)\n    u_left,u_right,u_bottom,u_top = uBC\n    x = LinRange(-1,1,m+2)\n    y = LinRange(-1,1,m+2)\n    xint = x[2:end-1]\n    yint = y[2:end-1]\n    h = x[2]-x[1]\n\n    id(i,j,m) = i + (j-1)*m # return global index from i,j\n\n    function FD_matrix_2D(h,m)\n        A = spzeros(m*m,m*m)\n        for i = 1:m, j = 1:m # loop thru x,y indices\n            A[id(i,j,m),id(i,j,m)] = 4/h^2\n            if i > 1 # avoids leftmost line of nodes\n                A[id(i,j,m),id(i-1,j,m)] = -1/h^2 # x-derivative\n            end\n            if i < m # avoids rightmost line of nodes\n                A[id(i,j,m),id(i+1,j,m)] = -1/h^2\n            end\n            if j > 1\n                A[id(i,j,m),id(i,j-1,m)] = -1/h^2 # y-derivative\n            end\n            if j < m\n                A[id(i,j,m),id(i,j+1,m)] = -1/h^2\n            end\n        end\n        return A\n    end\n\n    A = FD_matrix_2D(h,m)\n\n    b = vec(f.(xint,yint'))\n\n    # impose non-zero Dirichlet BCs\n    for i = 1:m, j = 1:m\n        if i==1\n            b[id(i,j,m)] += u_left(yint[j])/h^2\n        end\n        if i==m\n            b[id(i,j,m)] += u_right(yint[j])/h^2\n        end\n        if j==1\n            b[id(i,j,m)] += u_bottom(xint[i])/h^2\n        end\n        if j==m\n            b[id(i,j,m)] += u_top(xint[i])/h^2\n        end\n    end\n\n    # solve Au = f(xi,yj)\n    u = A\\b\n    return u,h,xint,yint\nend\n\nerrvec = []\nhvec = []\nfor m in [4 8 16 32 64 128]\n    u,h,xint,yint = solve(m,f,uBC)\n    err = maximum(abs.(u .- vec(uexact.(xint,yint'))))\n    append!(errvec,err)\n    append!(hvec,h)\nend\nplot(hvec,errvec,mark=:dot,xaxis=:log,yaxis=:log)\nplot!(hvec,hvec.^2,ls=:dash,xaxis=:log,yaxis=:log)\n# contourf(xint,yint,))\n", "meta": {"hexsha": "9e98d069db4650c6bf63bd7479670fd27f5670e0", "size": 2422, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "week5/fd_laplace_2D_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": "week5/fd_laplace_2D_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": "week5/fd_laplace_2D_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": 26.9111111111, "max_line_length": 84, "alphanum_fraction": 0.5400495458, "num_tokens": 868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109798251322, "lm_q2_score": 0.8962513634345443, "lm_q1q2_score": 0.8518071364914359}}
{"text": "#=\n\n\n\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\n\nFind the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product?\n\n\n=#\n\nstr =\"\"\"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\"\"\"\nlong_string = replace(str, \"\\n\" => \"\")\nlen_adjacent = 13\n\nfunction largest_adjacent_product(string, len_adjacent)\n    num_digits = length(string)\n    largest_product = 0\n    largest_piece = 0\n    for offset in 0:num_digits-len_adjacent\n        number_piece = string[1+offset:len_adjacent+offset]\n        #println(number_piece)\n        product = prod(digits(parse(Int, number_piece)))\n        if product > largest_product\n            largest_product = product\n            largest_piece = number_piece\n        end\n\n    end\n    return largest_product, largest_piece\nend\n\nprintln()\nprint(largest_adjacent_product(long_string, len_adjacent))\n", "meta": {"hexsha": "204a54286d673ade9cccea818eac5659e6458c93", "size": 3087, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "euler_8.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_8.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_8.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": 41.16, "max_line_length": 125, "alphanum_fraction": 0.8509880143, "num_tokens": 967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768588653856, "lm_q2_score": 0.9019206666433899, "lm_q1q2_score": 0.8515726219771305}}
{"text": "function sinh(x::DoubleFloat{T}) where {T<:IEEEFloat}\n    x < 0 && return -sinh(-x)\n    iszero(x) && return zero(x)\n    !isfinite(x) && return nan(typeof(x))\n\n    y = exp(x) - exp(-x)\n    z = DoubleFloat{T}(y.hi*0.5, y.lo*0.5)\n    return z\nend\n\nfunction cosh(x::DoubleFloat{T}) where {T<:IEEEFloat}\n    x < 0 && return cosh(-x)\n    iszero(x) && return one(x)\n    !isfinite(x) && return nan(typeof(x))\n\n    y = exp(x) + exp(-x)\n    z = DoubleFloat{T}(y.hi*0.5, y.lo*0.5)\n    return z\nend\n\nfunction tanh(x::DoubleFloat{T}) where {T<:IEEEFloat}\n    return sinh(x) / cosh(x)\nend\n#=\nfunction tanh(x::DoubleFloat{T}) where {T<:IEEEFloat}\n    x < 0 && return -tanh(-x)\n    iszero(x) && return zero(x)\n    !isfinite(x) && return nan(typeof(x))\n    epos = exp(x)\n    eneg = exp(-x)\n    z = (epos - eneg) / (epos + eneg)\n    return z\nend\n=#\n\ncsch(x::DoubleFloat{T}) where {T<:IEEEFloat} =\n    inv(sinh(x))\n\nsech(x::DoubleFloat{T}) where {T<:IEEEFloat} =\n    inv(cosh(x))\n\ncoth(x::DoubleFloat{T}) where {T<:IEEEFloat} =\n    inv(tanh(x))\n", "meta": {"hexsha": "c1cb44d973f29a2ee589b24e94f429ebb6a0c8b7", "size": 1026, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/elementary/hyptrig.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/hyptrig.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/hyptrig.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": 23.3181818182, "max_line_length": 53, "alphanum_fraction": 0.5779727096, "num_tokens": 373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551535992068, "lm_q2_score": 0.8824278618165526, "lm_q1q2_score": 0.8514150701532296}}
{"text": "using Plots\r\n\r\n##------------------------------------------------------------------------------\r\n\r\n# Ch 7.1 Principles of Regression\r\n# Julia code to fit data points using a straight line\r\nN = 50\r\nx = rand(N)\r\na = 2.5                         # true parameter\r\nb = 1.3                         # true parameter\r\ny = a*x .+ b + 0.2*rand(N)      # Synthesize training data\r\n\r\nX = [x ones(N)]                 # construct the X matrix\r\n\u03b8 = X\\y                         # solve y = X*\u03b8\r\n\r\nt    = range(0,stop=1,length=200)\r\nyhat = \u03b8[1]*t .+ \u03b8[2]                  # fitted values at t\r\n\r\np1 = scatter(x,y,makershape=:circle,label=\"data\",legend=:topleft)\r\nplot!(t,yhat,linecolor=:red,linewidth=4,label=\"best fit\")\r\ndisplay(p1)\r\n##------------------------------------------------------------------------------\r\n\r\n# Julia code to fit data using a quadratic equation\r\nN = 50\r\nx = rand(N)\r\na = -2.5\r\nb = 1.3\r\nc = 1.2\r\nX = x.^[0 1 2]                #same as [ones(N) x x.^2]\r\ny = X*[c,b,a] + rand(N)\r\n\r\n\u03b8    = X\\y\r\nt    = range(0,stop=1,length=200)\r\nyhat = (t.^[0 1 2])*\u03b8               #same as (t.^collect(0:2)')*\u03b8\r\n\r\np2 = scatter(x,y,makershape=:circle,label=\"data\",legend=:bottomleft)\r\nplot!(t,yhat,linecolor=:red,linewidth=4,label=\"fitted curve\")\r\ndisplay(p2)\r\n##------------------------------------------------------------------------------\r\n\r\n# Julia code to fit data using Legendre polynomials\r\n\r\nusing LegendrePolynomials\r\n\r\nN = 50\r\nx = rand(N)*2 .- 1\r\na = [-0.001, 0.01, 0.55, 1.5, 1.2]\r\nX = hcat([Pl.(x,p) for p=0:4]...)   # same as [Pl.(x,0) Pl.(x,1) Pl.(x,2) Pl.(x,3) Pl.(x,4)]\r\ny = X*a + 0.5*randn(N)\r\n\u03b8 = X\\y\r\n\r\nt    = range(-1,stop=1,length=200)\r\nyhat = hcat([Pl.(t,p) for p=0:4]...)*\u03b8\r\n\r\np3 = scatter(x,y,makershape=:circle,label=\"data\",legend=:bottomleft)\r\nplot!(t,yhat,linecolor=:red,linewidth=4,label=\"fitted curve\")\r\ndisplay(p3)\r\n##------------------------------------------------------------------------------\r\n\r\n# Julia code for auto-regressive model\r\nusing ToeplitzMatrices\r\n\r\nN = 500\r\ny = cumsum(0.2*randn(N)) + 0.05*randn(N)        # generate data\r\n\r\nL = 100                                         # use previous 100 samples\r\nc = [0; y[1:400-1]]\r\nr = zeros(L)\r\nX = Matrix(Toeplitz(c,r))                       # Toeplitz matrix, converted\r\n\u03b8 = X\\y[1:400]                                  # solve y = X*\u03b8\r\nyhat = X*\u03b8                                      # prediction\r\n\r\np4 = scatter(y[1:400],makershape=:circle,label=\"data\",legend=:bottomleft)\r\nplot!(yhat[1:400],linecolor=:red,linewidth=4,label=\"fitted curve\")\r\ndisplay(p4)\r\n##------------------------------------------------------------------------------\r\n\r\n# Julia code to demonstrate robust regression\r\n\r\nusing LinearAlgebra, LegendrePolynomials, Convex, SCS\r\nimport MathOptInterface\r\nconst MOI = MathOptInterface\r\n\r\n#----------------------------------------------------------\r\n\"\"\"\r\n    linprog_Convex(c,A,sense,b)\r\n\r\nA wrapper for doing linear programming with Convex.jl/SCS.jl.\r\nIt solves, for instance, `c'x` st. `A*x<=b`\r\n\"\"\"\r\nfunction linprog_Convex(c,A,sense,b)\r\n    n  = length(c)\r\n    x  = Variable(n)\r\n    #c1 = sense(A*x,b)             #restriction, for Ax <= b, use sense = (<=)\r\n    c1 = A*x <= b\r\n    prob = minimize(dot(c,x),c1)\r\n    solve!(prob,()->SCS.Optimizer(verbose = false))\r\n    x_i = prob.status == MOI.OPTIMAL ? vec(evaluate(x)) : NaN\r\n    return x_i\r\nend\r\n#----------------------------------------------------------\r\n\r\nN = 50\r\nx = range(-1,stop=1,length=N)\r\na = [-0.001, 0.01, 0.55, 1.5, 1.2]\r\ny = hcat([Pl.(x,p) for p=0:4]...)*a  + 0.05*randn(N)        # generate data\r\nidx     = [10, 16, 23, 37, 45]\r\ny[idx] .= 5\r\n\r\nX = x.^[0 1 2 3 4]\r\nA = [X -I; -X -I]\r\nb = [y; -y]\r\nc = [zeros(5);ones(N)]\r\n\r\n\u03b8 = linprog_Convex(c,A,(<=),b)\r\n\r\nt    = range(-1,stop=1,length=200)\r\nyhat = (t.^[0 1 2 3 4])*\u03b8[1:5]\r\n\r\np5 = scatter(x,y,makershape=:circle,label=\"data\",legend=:bottomleft)\r\nplot!(t,yhat,linecolor=:red,linewidth=4,label=\"fitted curve\")\r\ndisplay(p5)\r\n##------------------------------------------------------------------------------\r\n\r\n# Ch 7.2 Overfitting\r\n# Julia: An overfitting example\r\n\r\nusing LegendrePolynomials\r\n\r\nN = 20\r\nx = sort(rand(N)*2 .- 1)\r\na = [-0.001, 0.01, 0.55, 1.5, 1.2]\r\ny = hcat([Pl.(x,p) for p=0:4]...)*a + 0.1*randn(N)\r\n\r\nP = 20\r\nX = hcat([Pl.(x,p) for p=0:P]...)\r\n\r\n\u03b2 = X\\y\r\n\r\nt    = range(-1,stop=1,length=50)\r\nXhat = hcat([Pl.(t,p) for p=0:P]...)\r\nyhat = Xhat*\u03b2\r\n\r\np6 = scatter(x,y,makershape=:circle,label=\"data\",legend=:bottomleft,ylims = (-3,3))\r\nplot!(t,yhat,linecolor=:blue,linewidth=4,label=\"fitted curve\")\r\ndisplay(p6)\r\n##------------------------------------------------------------------------------\r\n\r\nusing Statistics\r\n\r\nNset = round.( Int,exp10.(range(1,stop=3,length=20)) )  #10,13,16,21,...\r\n\r\nE_train = zeros(length(Nset))\r\nE_test  = zeros(length(Nset))\r\na = [1.3, 2.5]\r\nfor j = 1:length(Nset)\r\n    local N,x,E_train_temp,E_test_temp,X\r\n    N = Nset[j]\r\n    x = range(-1,stop=1,length=N)\r\n    E_train_temp = zeros(1000)\r\n    E_test_temp  = zeros(1000)\r\n    X = [ones(N) x]\r\n    for i = 1:1000\r\n        local y,y1,\u03b8,yhat\r\n        y  = a[1] .+ a[2]*x + randn(N)\r\n        y1 = a[1] .+ a[2]*x + randn(N)\r\n        \u03b8 = X\\y\r\n        yhat = \u03b8[1] .+ \u03b8[2]*x\r\n        E_train_temp[i] = mean(abs2,yhat-y)\r\n        E_test_temp[i]  = mean(abs2,yhat-y1)\r\n    end\r\n    E_train[j] = mean(E_train_temp)\r\n    E_test[j]  = mean(E_test_temp)\r\nend\r\n\r\np7 = scatter(Nset,E_train,xscale=:log10,markershape=:x,markercolor=:black,label=\"Training Error\")\r\nscatter!(Nset,E_test,xscale=:log10,markershape=:circle,markercolor=:red,label=\"Testing Error\")\r\nplot!(Nset,1.0 .- 2.0./Nset,xscale=:log10,linestyle=:solid,color=:black,label=\"\")\r\nplot!(Nset,1.0 .+ 2.0./Nset,xscale=:log10,linestyle=:solid,color=:red,label=\"\")\r\ndisplay(p7)\r\n##------------------------------------------------------------------------------\r\n\r\n# Ch 7.3 Bias and Variance\r\n# Julia code to visualize the average predictor\r\n\r\nN = 20\r\na = [5.7, 3.7, -3.6, -2.3, 0.05]\r\nx = range(-1,stop=1,length=N)\r\nX = x.^[0 1 2 3 4]\r\n\r\nt    = range(-1,stop=1,length=50)\r\ntMat = t.^[0 1 2 3 4]\r\n\r\nyhat = zeros(50,100)                      #50x100 instead of 100x50\r\nfor i = 1:100\r\n    local y,\u03b8\r\n    y = X*a + 0.5*randn(N)\r\n    \u03b8 = X\\y\r\n    yhat[:,i] = tMat*\u03b8\r\nend\r\n\r\np8 = plot(t,yhat,linecolor=:gray,label=\"\")\r\nplot!(t,mean(yhat,dims=2),linecolor=:red,linewidth=4,label=\"\")\r\ndisplay(p8)\r\n##------------------------------------------------------------------------------\r\n\r\n# Ch 7.4 Regularization\r\n#  Julia code to demonstrate a ridge regression example\r\n\r\n#----------------------------------------------------------\r\n\"\"\"\r\n    RidgeRegression(Y,X,\u03bb,\u03b2\u2080=0)\r\n\r\nCalculate ridge regression estimate with targetr vector \u03b2\u2080.\r\n\"\"\"\r\nfunction RidgeRegression(Y,X,\u03bb,\u03b2\u2080=0)\r\n    K = size(X,2)\r\n    isa(\u03b2\u2080,Number) && (\u03b2\u2080=fill(\u03b2\u2080,K))\r\n    b = (X'X+\u03bb*I)\\(X'Y+\u03bb*\u03b2\u2080)      #same as inv(X'X+\u03bb*I)*(X'Y+\u03bb*\u03b2\u2080)\r\n    return b\r\nend\r\n#----------------------------------------------------------\r\n\r\nN = 20                                 # Generate data\r\nx = range(-1,stop=1,length=N)\r\na = [0.5, -2, -3, 4, 6]\r\ny = x.^[0 1 2 3 4]*a + 0.25*randn(N)\r\n\r\n\u03bb = 0.1                                # Ridge regression\r\nd = 20\r\nX = x.^collect(0:d-1)'\r\nA = [X; sqrt(\u03bb)I]\r\nb = [y; zeros(d)]\r\n\u03b8 = A\\b\r\n\u03b8_alt = RidgeRegression(y,X,\u03bb)         # alternative ridge regression\r\ndisplay([\u03b8 \u03b8_alt])\r\n\r\nt    = range(-1,stop=1,length=500)\r\nXhat = t.^collect(0:d-1)'\r\nyhat = Xhat*\u03b8\r\n\r\np9 = scatter(x,y,makershape=:circle,label=\"data\",legend=:bottomleft)\r\nplot!(t,yhat,linecolor=:blue,linewidth=4,label=\"fitted curve\")\r\ndisplay(p9)\r\n##------------------------------------------------------------------------------\r\n\r\n\r\n#----------------------------------------------------------\r\n\"\"\"\r\n    LassoEN(Y,X,\u03bb,\u03b4,\u03b2\u2080)\r\n\r\nDo Lasso (set \u03bb>0,\u03b4=0), ridge (set \u03bb=0,\u03b4>0) or elastic net regression (set \u03bb>0,\u03b4>0).\r\nSetting \u03b2\u2080 allows us to specify the target level.\r\n\r\n\"\"\"\r\nfunction LassoEN(Y,X,\u03bb,\u03b4=0.0,\u03b2\u2080=0)\r\n\r\n    K = size(X,2)\r\n    isa(\u03b2\u2080,Number) && (\u03b2\u2080=fill(\u03b2\u2080,K))\r\n\r\n    #b_ls = X\\Y                    #LS estimate of weights, no restrictions\r\n\r\n    Q  = X'X\r\n    c  = X'Y                      #c'b = Y'X*b\r\n\r\n    b  = Variable(K)              #define variables to optimize over\r\n    L1 = quadform(b,Q)            #b'Q*b\r\n    L2 = dot(c,b)                 #c'b\r\n    L3 = norm(b-\u03b2\u2080,1)             #sum(|b-\u03b2\u2080|)\r\n    L4 = sumsquares(b-\u03b2\u2080)         #sum((b-\u03b2\u2080)^2)\r\n\r\n    Sol = minimize(L1-2*L2+\u03bb*L3+\u03b4*L4)      #u'u + \u03bb*sum(|b|) + \u03b4*sum(b^2), where u = Y-Xb\r\n    solve!(Sol,()->SCS.Optimizer(verbose = false))\r\n    b_i = vec(evaluate(b))\r\n\r\n    return b_i\r\n\r\nend\r\n#----------------------------------------------------------\r\n\r\nusing LinearAlgebra, DelimitedFiles, Convex, SCS\r\nimport MathOptInterface\r\nconst MOI = MathOptInterface\r\n\r\ndata  = readdlm(\"dataset/ch7_data_crime.txt\")\r\ny     = data[:,1]        # the observed crime rate\r\nX     = data[:,3:end]    # feature vectors\r\n(N,d) = size(X)\r\n\r\n(y,X) = (y.-mean(y),X.-mean(X,dims=1))           # de-meaning all variables\r\n\r\n\u03bbset = exp10.(range(-2,stop=4,length=50))        # adjusted range of \u03bb values since X/100 is used\r\n(\u03b8_store,\u03b8_store2,\u03b8_store3) = [zeros(50,d) for _=1:3]   # 50 x d instead of d x 50\r\nfor i = 1:length(\u03bbset)\r\n    \u03b8_store[i,:]  = LassoEN(y/100,X/100,\u03bbset[i])    # LASSO, /100 improves the numerical stability\r\n    \u03b8_store2[i,:] = LassoEN(y/100,X/100,0,\u03bbset[i])  # ridge regression\r\n    #\u03b8_store3[i,:] = RidgeRegression(y/100,X/100,\u03bbset[i])   # alternative ridge regression\r\nend\r\n#display(\u03b8_store2-\u03b8_store3)                                 # compare solutions\r\n\r\np10 = plot(\u03bbset,\u03b8_store,xscale=:log10,title=\"LASSO\",xlabel=\"\u03bb\",ylabel=\"feature attribute\",\r\n           label = [\"funding\" \"% high\" \"% no high\" \"% college\" \"% graduate\"],\r\n            linecolor = [:blue :red :yellow3 :magenta :green],ylims=(-5,15))\r\ndisplay(p10)\r\n\r\np10b = plot(\u03bbset,\u03b8_store2,xscale=:log10,title=\"ridge regression\",xlabel=\"\u03bb\",ylabel=\"feature attribute\",\r\n           label = [\"funding\" \"% high\" \"% no high\" \"% college\" \"% graduate\"],\r\n            linecolor = [:blue :red :yellow3 :magenta :green],ylims=(-5,15))\r\ndisplay(p10b)\r\n##------------------------------------------------------------------------------\r\n\r\n# Julia code to demonstrate overfitting and LASSO\r\n\r\nusing LinearAlgebra, LegendrePolynomials, Convex, SCS\r\nimport MathOptInterface\r\nconst MOI = MathOptInterface\r\n\r\nN = 20                                          # Generate data\r\nx = range(-1,stop=1,length=N)\r\na = [1, 0.5, 0.5, 1.5, 1]\r\ny = hcat([Pl.(x,p) for p=0:4]...)*a + 0.25*randn(N)\r\n\r\nd = 20                                          # Solve LASSO using Convex.jl\r\nX = hcat([Pl.(x,p) for p=0:d-1]...)\r\n\u03bb = 2\r\n\u03b8 = LassoEN(y,X,\u03bb)\r\n\r\nt    = range(-1,stop=1,length=200)\r\nXhat = hcat([Pl.(t,p) for p=0:d-1]...)\r\nyhat = Xhat*\u03b8\r\n\r\np11 = scatter(x,y,makershape=:circle,label=\"data\",legend=:bottomleft)\r\nplot!(t,yhat,linecolor=:blue,linewidth=4,label=\"fitted curve\")\r\ndisplay(p11)\r\n#------------------------------------------------------------------------------\r\n", "meta": {"hexsha": "1d71e9729e7fb8b73d62ee769b39cd8639f270be", "size": 10944, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Ch07.jl", "max_stars_repo_name": "PaulSoderlind/IntProbDS.jl", "max_stars_repo_head_hexsha": "c32fb9f1c0b36f65dbf7742504978b0b9bf830d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-10-13T00:51:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T06:28:31.000Z", "max_issues_repo_path": "Ch07.jl", "max_issues_repo_name": "PaulSoderlind/IntProbDS.jl", "max_issues_repo_head_hexsha": "c32fb9f1c0b36f65dbf7742504978b0b9bf830d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-10-14T11:58:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-19T11:08:17.000Z", "max_forks_repo_path": "Ch07.jl", "max_forks_repo_name": "PaulSoderlind/IntProbDS.jl", "max_forks_repo_head_hexsha": "c32fb9f1c0b36f65dbf7742504978b0b9bf830d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2021-10-14T16:00:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-22T22:36:10.000Z", "avg_line_length": 32.4747774481, "max_line_length": 104, "alphanum_fraction": 0.4954312865, "num_tokens": 3489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474194456935, "lm_q2_score": 0.8918110353738529, "lm_q1q2_score": 0.8513651035528408}}
{"text": "\"\"\"\n\tfourier_matrix(n::Int; normalized=true)\n\nReturns a ``n``-by-``n`` Fourier matrix with optional normalization (`true` by default).\n\"\"\"\nfunction fourier_matrix(n::Int; normalized = true)\n\n    U = Array{ComplexF64}(undef, n, n)\n\n    for i in 1:n\n        for j in 1:n\n            U[i,j] = exp((2im * pi / n)* (i-1) * (j-1))\n        end\n    end\n\n    if normalized\n        return 1/sqrt(n) * U\n    else\n        return U\n    end\nend\n\n\"\"\"\n\thadamard_matrix(n::Int; normalized=true)\n\nReturns a ``n``-by-``n`` Hadamard matrix with optional normalization (`true` by default).\n\"\"\"\nfunction hadamard_matrix(n::Int, normalized = true )\n\n\tH = Array{ComplexF64}(undef, n, n)\n\n\tfor i in 1:n\n\t\tfor j in 1:n\n\t\t\tbi = map(x->parse(Int,x), split(bitstring(Int8(i-1)),\"\"))\n\t\t\tbj = map(x->parse(Int,x), split(bitstring(UInt8(j-1)),\"\"))\n\t\t\tH[i,j] = (-1)^(sum(bi.&bj))\n\t\tend\n\tend\n\n\tif normalized\n\t\treturn 1/sqrt(n) * H\n\telse\n\t\treturn H\n\tend\n\nend\n\n\"\"\"\n\tsylvester_matrix(p::Int; normalized=true)\n\nReturns a ``2^p``-by-``2^p`` Sylvester matrix with optional normalization\n(`true` by default) following [https://arxiv.org/abs/1502.06372](https://arxiv.org/abs/1502.06372).\n\"\"\"\nfunction sylvester_matrix(p; normalized = true)\n\n    \"\"\"returns the sylvester matrix of size 2^p\"\"\"\n\n    function sylvester_element(i,j,p)\n\n        \"\"\"returns the element A(i,j) for the sylvester matrix of size 2^p\"\"\"\n        # following https://arxiv.org/abs/1502.06372\n        if p == 0\n            return 1\n        else\n            i_b = digits(i-1, base = 2, pad = p+1)\n            j_b = digits(j-1, base = 2, pad = p+1)\n            return (-1)^(sum(i_b .* j_b))\n        end\n    end\n\n    A = Array{ComplexF64}(undef, 2^p, 2^p)\n    for i in 1:2^p\n        for j in 1:2^p\n            A[i,j] = sylvester_element(i,j,p)\n        end\n    end\n\n    normalized == true ? 1/sqrt(2^p) * A : A\n\nend\n\n\"\"\"\n\trand_haar(n::Int)\n\nReturns a ``n``-by-``n`` Haar distributed unitary matrix following [https://case.edu/artsci/math/esmeckes/Meckes_SAMSI_Lecture2.pdf](https://case.edu/artsci/math/esmeckes/Meckes_SAMSI_Lecture2.pdf).\n\"\"\"\nfunction rand_haar(n::Int)\n\n    \"\"\"generates a Haar distributed unitary matrix of size n*n\"\"\"\n    # follows https://case.edu/artsci/math/esmeckes/Meckes_SAMSI_Lecture2.pdf\n\n    qr(randn(ComplexF64, n,n)).Q\nend\n\nfunction matrix_test(n::Int)\n\n    \"\"\"matrix of 1,2,3... for testing your code\"\"\"\n\n    U = Array{Int64}(undef, n, n)\n\n    for i in 1:n\n        for j in 1:n\n            U[i,j] = (i-1) * n + j\n        end\n    end\n\n    U\n\nend\n\nfunction antihermitian_test_matrix(n::Int)\n\n    h = randn(ComplexF64, n, n)\n\n    for i = 1:n\n        h[i,i] = 1im*imag(h[i,i])\n    end\n\n    for i = 1:n\n        for j = i+1:n\n            h[j,i] = -conj(h[i,j])\n        end\n    end\n\n    h\n\nend\n\nfunction hermitian_test_matrix(n::Int)\n\n    h = randn(ComplexF64, n,n)\n\n    for i = 1:n\n        h[i,i] = real(h[i,i])\n    end\n\n    for i = 1:n\n        for j = i+1:n\n            h[j,i] = conj(h[i,j])\n        end\n    end\n\n    h\n\nend\n\nfunction permutation_matrix_special_partition_fourier(n::Int)\n\n    \"\"\"P * [1,1,1,1,1,0,0,0,0,0] = [1, 0, 1, 0, 1, 0, 1, 0, 1, 0]\"\"\"\n\n    P = zeros(Int, n,n)\n\n    for i in 1:2:n\n        P[i, Int((i+1)/2)] = 1\n    end\n\n    for i in 2:2:n\n        P[i, Int(n/2 + i/2)] = 1\n    end\n\n    P\n\nend\n\n\"\"\"\n\trand_gram_matrix_from_orthonormal_basis(n::Int, r::Int)\n\nReturns a ``n``-by-``n`` random Gram matrix that generates orthonormal basis of `r` vectors.\n\"\"\"\nfunction rand_gram_matrix_from_orthonormal_basis(n,r)\n\n\t\"\"\"generates a random gram matrix with the property that the\n\tgenerating vector basis of r vectors is orthonormal (as is\n\tstrangely the case in Drury's work)\"\"\"\n\n\tfunction normalized_random_vector(n)\n\t\tv = rand(ComplexF64, n)\n\t\t1/norm(v) .* v\n\tend\n\n\tif r >= n\n\t\tthrow(ArgumentError(\"need rank < dim to have a non trivial result\"))\n\tend\n\n\tgenerating_vectors = 0.\n\t#while det(generating_vectors) \u2248 0. #check it's a basis\n\t    generating_vectors = hcat([normalized_random_vector(n) for i = 1:r]...)\n\t#### TODO caveat : we don't check for linear independance so there is a chance it doesn't work though highly unlikely\n\t#end\n\n\tgenerating_vectors = modified_gram_schmidt(generating_vectors)\n\n\tis_orthonormal(generating_vectors)\n\n\tgenerating_vectors * generating_vectors'\n\nend\n\n\nfunction modified_gram_schmidt(input_vectors)\n\n\t\"\"\"does the modified gram schmidt (numerically stable) on the columns of the matrix input_vectors\"\"\"\n\n\tfunction projector(a, u)\n\t\t\"\"\"projector of a on u\"\"\"\n\t\tdot(u,a)/dot(u,u) .* u\n\tend\n\n\tfinal_vectors = copy(input_vectors)\n\n\tfor i in 1:size(input_vectors)[2]\n\n\t\tif i == 1\n\t\t\t#normalize first vector\n\t\t\tfinal_vectors[:,1] /= norm(final_vectors[:, 1])\n\t\telse\n\t\t\tfor j in 1:i-1\n\t\t\t\tfinal_vectors[:, i] -= projector(final_vectors[:, i], final_vectors[:, j])\n\t\t\tend\n\t\t\tfinal_vectors[:, i] /= norm(final_vectors[:, i])\n\n\t\tend\n\n\tend\n\n\tis_orthonormal(final_vectors)\n\n\tfinal_vectors\n\nend\n\n\"\"\"\n\trand_gram_matrix(n::Int)\n\nReturns a full rank ``n``-by-``n`` random Gram matrix.\n\"\"\"\nfunction rand_gram_matrix(n::Int)\n\n\t\"\"\"random gram matrix with full rank \"\"\"\n\n\tfunction normalized_random_vector(n)\n\t\tv = rand(ComplexF64, n)\n\t\t1/norm(v) .* v\n\tend\n\n\tgenerating_vectors = 0.\n\twhile det(generating_vectors) \u2248 0. #check it's a basis\n\t    generating_vectors = hcat([normalized_random_vector(n) for i = 1:n]...)\n\n\tend\n\n\tgenerating_vectors' * generating_vectors\n\nend\n\n\"\"\"\n\trand_gram_matrix_rank(n::Int, r::Int)\n\nReturns a ``n``-by-``n`` random Gram matrix of maximum rank and great likelihood `r`.\n\"\"\"\nfunction rand_gram_matrix_rank(n, r)\n\n\t\"\"\"random gram matrix with rank at most r, and with great likelihood r\n\t\"\"\"\n\n\tfunction normalized_random_vector(r)\n\t\tv = rand(ComplexF64, r)\n\t\t1/norm(v) .* v\n\tend\n\n\tgenerating_vectors = 0.\n\tgenerating_vectors = hcat([normalized_random_vector(r) for i = 1:n]...)\n\n\tgenerating_vectors' * generating_vectors\n\n\nend\n\n\"\"\"\n\trand_gram_matrix_real(n::Int)\n\nReturns a real ``n``-by-``n`` random Gram matrix of full rank.\n\"\"\"\nfunction rand_gram_matrix_real(n)\n\n\t\"\"\"random gram matrix with full rank and real el\"\"\"\n\n\tfunction normalized_random_vector(n)\n\t\tv = rand(Float64, n)\n\t\t1/norm(v) .* v\n\tend\n\n\tgenerating_vectors = 0.\n\twhile det(generating_vectors) \u2248 0. #check it's a basis\n\t    generating_vectors = hcat([normalized_random_vector(n) for i = 1:n]...)\n\n\tend\n\n\tgenerating_vectors' * generating_vectors\n\nend\n\n\"\"\"\n\trand_gram_matrix_positive(n::Int)\n\nReturns a positive elements ``n``-by-``n`` random Gram matrix of full rank.\n\"\"\"\nfunction rand_gram_matrix_positive(n::Int)\n\n\t\"\"\"random gram matrix with full rank and positive el\"\"\"\n\n\tfunction normalized_random_vector(n)\n\t\tv = abs.(rand(Float64, n))\n\t\t1/norm(v) .* v\n\tend\n\n\tgenerating_vectors = 0.\n\twhile det(generating_vectors) \u2248 0. #check it's a basis\n\t    generating_vectors = hcat([normalized_random_vector(n) for i = 1:n]...)\n\n\tend\n\n\tgenerating_vectors' * generating_vectors\n\nend\n\n# functions to clear matrices for better readability of a matrix by a human\n\nfunction set_small_values_to_zero(x, eps)\n\tabs(x) < eps ? 0.0 : x\nend\n\nfunction set_small_imag_real_to_zero(x, eps = 1e-7)\n\tif abs(real(x)) < eps\n\t\tx = 0.0 + 1im * imag(x)\n\tend\n\tif abs(imag(x)) < eps\n\t\tx = real(x) + 0.0im\n\tend\n\tx\nend\n\nfunction make_matrix_more_readable(M)\n\tset_small_imag_real_to_zero.(M)\nend\n\nfunction display_matrix_more_readable(M)\n\tpretty_table(make_matrix_more_readable(M))\nend\n\n####### sub matrices ########\n\nfunction remove_row_col(A, rows_to_remove, cols_to_remove)\n\n\t\"\"\"hands back the matrix A without the rows labelled in rows_to_remove, columns in cols_to_remove\n\n\tex :\n\trows_to_remove = [1]\n\tcols_to_remove = [2]\n\n\tto have A(1,2) in the notations of Minc\"\"\"\n\n\tn = size(A)[1]\n\tm = size(A)[2]\n\n\trange_rows = collect(1:n)\n\trange_col = collect(1:m)\n\n\tsetdiff!(range_rows, rows_to_remove)\n\tsetdiff!(range_col, cols_to_remove)\n\n\tA[range_rows, range_col]\n\nend\n\n### permanent related quantities ###\n\nfunction sub_permanent_matrix(A)\n\n\tn = size(A)[1]\n\n\tsub_permanents = similar(A)\n\n\n\tfor i in 1 : n\n\t\tfor j in 1 : n\n\n\t\t\tsub_permanents[i,j] = ryser(remove_row_col(A, [i], [j]))\n\n\t\tend\n\tend\n\n\tsub_permanents\n\nend\n\nfunction gram_from_n_r_vectors(M)\n\n\t# generate a random matrix of n r-vectors M\n\t# normalize it to have a gram matrix\n\n\tn = size(M)[1]\n\n\tfor i in  1 : n\n\t\tM[:,i] ./= norm(M[:,i])\n\tend\n\n\tM' * M # our rank r n*n gram matrix\n\nend\n\n\"\"\"\n\tgram_matrix_one_param(n::Int, x::Real)\n\nReturns a ``n``-by-``n`` Gram matrix parametrized by the real ``0 \u2264 x \u2266 1``.\n\"\"\"\nfunction gram_matrix_one_param(n::Int, x::Real)\n\n\t@argcheck x>=0 && x<= 1\n\n\tS = 1.0 * Matrix(I, n, n)\n\tfor i in 1:n\n\t\tfor j in 1:n\n\t\t\ti!=j ? S[i,j] = x : continue\n\t\tend\n\tend\n\n\tS\n\nend\n\nfunction column_normalize(M)\n   for col in 1:size(M,2) #column normalize\n\t   M[:, col] = M[:, col]./norm(M[:, col])\n   end\n   M\nend\n\n\"\"\"\n\tperturbed_gram_matrix(M, epsilon)\n\nReturns a Gram matrix generated by the columns of `M` which are perturbed by\na Gaussian quantity of variance epsilon once normalized.\n\"\"\"\nfunction perturbed_gram_matrix(M, epsilon)\n\n    \"\"\"M defines the set of vectors generating the gram matrix\n    each column is a generating vector for the gram matrix\n    we perturb them by some random gaussian amount with set variance epsilon once normalized \"\"\"\n\n    M = column_normalize(M)\n\n    d = Normal(0.0, epsilon)\n\n    perturbation_vector = rand(d,size(M))\n\n    M += perturbation_vector\n\n    M = column_normalize(M)\n\n    M' * M\n\nend\n\n\"\"\"\n\tperturbed_unitary(U, epsilon)\n\nReturns a unitary matrix whose columns are generating vector perturbed by a\nrandom Gaussian quantity with variance epsilon once normalized.\n\"\"\"\nfunction perturbed_unitary(U, epsilon)\n\n    \"\"\"U a unitary matrix each column is a generating vector\n    we perturb them by some random gaussian amount with set variance epsilon once normalized \"\"\"\n\n    d = Normal(0.0, epsilon)\n\n    perturbation_vector = rand(d,size(U))\n\n    U += perturbation_vector\n\n    U = modified_gram_schmidt(U)\n\n    U\n\nend\n", "meta": {"hexsha": "0522ee069250d322307089279f5ccd6090cc0845", "size": 9878, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/special_matrices.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/special_matrices.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/special_matrices.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": 20.2833675565, "max_line_length": 198, "alphanum_fraction": 0.6558007694, "num_tokens": 2988, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.942506716354847, "lm_q2_score": 0.9032942041005328, "lm_q1q2_score": 0.8513608542091582}}
{"text": "\"\"\"\n# Counting Sort \nOVERVIEW:\nCounting Sort is a sorting algorithm that sort elements within a specific range.\nThe sorting technique is to count the existing element and stored its occurrence time in a new list, then only print it out.\n\nSTEPS: \nAssume the input as --> x=[-3, 1, -5, 0, -3]\n  minimum = -5\n- STEP 1: Create a list size within the range, in this case is -5 --> 1 which have range of 7 (-5, -4, -3, -2, -1, 0, 1), so list with size 7 and assign all to 0 is created\n- STEP 2: Count the occurances of element in the list \n          First number = -3 it is the third number in the range, so count[3]+=1\n          Final view:\n          index : ( 1,  2,  3,  4,  5, 6, 7)\n          range : (-5, -4, -3, -2, -1, 0, 1)\n          count : [ 1,  0,  2,  0,  0, 1, 1] <-- the list will store this occurences\n- STEP 3: Make the count list accumulate the occurances \n          The final count is (1, 1, 3, 3, 3, 4, 5)\n- STEP 4: Assign the elements in x into correct possition by creating a new list (will call 'output' in this sample)\n          the 1st element in 'x' is -3, it is third in range, so it will call the index of 3 in 'count', which is 3 and assign the -3 in to 3rd position in 'output', \n          then the third element in range will deduct by 1, so the next repeated element will get the correct position, new 'count' --> [1, 1, 2, 3, 3, 4, 5]\n\n          the 2nd element in 'x' is  1, it is last  in range, so it will call the index of 7 in 'count', which is 5 and assign the  1 in to 5th position in 'output', \n          new 'count' --> [1, 1, 2, 3, 3, 4, 4]\n          ......\n          ......\n          *If you want the order of original array to have the same order as the output array use can change this to decremental for loop\n- STEP 5: Assign the 'ouput' list back to 'x'\n\nFINAL RESULT -->  [-5, -3, -3, 0, 1]                                                                                    \n\"\"\"\nfunction counting_sort!(\n    arr::Vector{T},\n    l::Int = 1,\n    r::Int = length(arr),\n) where {T}\n    if l >= r\n        return nothing\n    end\n    max = maximum(arr)\n    min = minimum(arr)\n    range = max - min + 1\n    count = Vector{T}(undef, range)\n    output = Vector{T}(undef, r)\n\n    for i in 1:range\n        count[i] = 0\n    end\n\n    # Store count of the item that appear in the 'arr' (STEP 2)\n    for i in 1:r\n        count[arr[i]-min+1] += 1\n    end\n\n    # Calculate cumulative frequency in 'count' (STEP 3)\n    for i in 2:length(count)\n        count[i] += count[i-1]\n    end\n\n    # Build the 'output' by assigning the item into correct position (STEP 4)\n    for i in 1:r\n        index = arr[i] - min + 1\n        output[count[index]] = arr[i]\n        count[index] -= 1\n    end\n\n    # Copy the 'output' to 'arr', so that 'arr' contain sorted item (STEP 5)\n    for i in 1:r\n        arr[i] = output[i]\n    end\nend\n", "meta": {"hexsha": "0a00e4f00f2f151ae0e87327636e44f2bfc513f2", "size": 2841, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/sorts/counting_sort.jl", "max_stars_repo_name": "AugustoCL/Julia", "max_stars_repo_head_hexsha": "1bf4e4a7829fafc64290d903bcbfdd48eab839e7", "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/sorts/counting_sort.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/sorts/counting_sort.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": 39.4583333333, "max_line_length": 172, "alphanum_fraction": 0.5765575502, "num_tokens": 897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582612793112, "lm_q2_score": 0.9149009555730612, "lm_q1q2_score": 0.8512771523652908}}
{"text": "#############################################################################\n#############################################################################\n#\n# This file contains defines unit tests for integer operations\n#                                                                               \n#############################################################################\n#############################################################################\n\n\n\"\"\"\nTests Euclidean GCD algorithm for integers.\n\"\"\"\nfunction test_euclid_ints(;N::Int = 10^4)\n    Random.seed!(0)\n    for _ in 1:N\n        n1 = rand(1:10^6)\n        n2 = rand(1:10^6)\n        g = euclid_alg(n1,n2)\n        @assert mod(n1,g) == 0 &&  mod(n2,g) == 0\n    end\n    println(\"test_euclid_ints - PASSED\")\nend\n\n\"\"\"\nTests the extended Euclidean GCD algorithm for integers.\n\"\"\"\nfunction test_ext_euclid_ints(;N::Int = 10^4)\n    Random.seed!(0)\n    for _ in 1:N\n        n1 = rand(1:10^6)\n        n2 = rand(1:10^6)\n        g, s, t = ext_euclid_alg(n1,n2)\n        @assert g == s*n1 + t*n2\n        @assert mod(n1,g) == 0 &&  mod(n2,g) == 0\n    end\n    println(\"test_ext_euclid_ints - PASSED\")\nend\n\n\"\"\"\nTests the computation of inverse mod for integers.\n\"\"\"\nfunction test_inverse_mod_ints(;prime::Int=101,N::Int=10^4)\n    Random.seed!(0)\n    for _ in 1:N\n        n = rand(1:10^6)\n        if mod(n, prime) == 0\n            continue\n        end\n        im = int_inverse_mod(n,prime) \n        @assert mod((n*im), prime) == 1\n    end\n    println(\"test_inverse_mod_ints - PASSED\")\nend", "meta": {"hexsha": "e3173095e99537ecb1a367655422eacb5f083fb2", "size": 1538, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/integers_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/integers_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/integers_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": 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": 29.0188679245, "max_line_length": 80, "alphanum_fraction": 0.4323797139, "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966747198242, "lm_q2_score": 0.899121375242593, "lm_q1q2_score": 0.8511053039741537}}
{"text": "\"\"\"\n    perfect_cube(number)\n\nCheck if a number is a perfect cube or not.\n\n# Example\n```jula\nperfect_cube(27) # returns true\nperfect_cube(4)  # returns false\n```\n\nContributed By:- [Ashwani Rathee](https://github.com/ashwani-rathee) and [Rratic](https://github.com/Rratic)\n\"\"\"\nfunction perfect_cube(number::N)where N<:Integer\n    val = trunc(cbrt(number))\n    return (val * val * val) == number\nend\n", "meta": {"hexsha": "ab9ee763b9dffd7fc937b2dfdc46bfa85b3ccbb1", "size": 398, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/perfect_cube.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/perfect_cube.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/perfect_cube.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.1111111111, "max_line_length": 108, "alphanum_fraction": 0.6934673367, "num_tokens": 119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9559813488829418, "lm_q2_score": 0.8902942217558213, "lm_q1q2_score": 0.851104671016819}}
{"text": "\"\"\"\n    opnorm(A::IntervalMatrix, p::Real=Inf)\n\nThe matrix norm of an interval matrix.\n\n### Input\n\n- `A` -- interval matrix\n- `p` -- (optional, default: `Inf`) the class of `p`-norm\n\n### Notes\n\nThe matrix ``p``-norm of an interval matrix ``A`` is defined as\n\n```math\n    \u2016A\u2016_p := \u2016\\\\max(|\\\\text{inf}(A)|, |\\\\text{sup}(A)|)\u2016_p\n```\n\nwhere ``\\\\max`` and ``|\u00b7|`` are taken elementwise.\n\"\"\"\nfunction LinearAlgebra.opnorm(A::IntervalMatrix, p::Real=Inf)\n    if p == Inf\n        return _opnorm_inf(A)\n    elseif p == 1\n        return _opnorm_1(A)\n    else\n        error(\"the interval matrix norm for this value of p=$p is not implemented\")\n    end\nend\n\n# The operator norm in the infinity norm corresponds to the\n# maximum absolute value row-sum.\nfunction _opnorm_inf(A::IntervalMatrix{T}) where {T}\n    m, n = size(A)\n    res = zero(T)\n    @inbounds @simd for i in 1:m\n        acc = zero(T)\n        for j in 1:n\n            x = A[i, j]\n            acc += max(abs(inf(x)), abs(sup(x)))\n        end\n        if acc > res\n            res = acc\n        end\n    end\n    return res\nend\n\n# The operator norm in the 1-norm corresponds to the\n# maximum absolute value column-sum.\nfunction _opnorm_1(A::IntervalMatrix{T}) where {T}\n    m, n = size(A)\n    res = zero(T)\n    @inbounds @simd for j in 1:n\n        acc = zero(T)\n        for i in 1:m\n            x = A[i, j]\n            acc += max(abs(inf(x)), abs(sup(x)))\n        end\n        if acc > res\n            res = acc\n        end\n    end\n    return res\nend\n\n\"\"\"\n    diam_norm(A::IntervalMatrix, p=Inf)\n\nReturn the diameter norm of the interval matrix.\n\n### Input\n\n- `A` -- interval matrix\n- `p` -- (optional, default: `Inf`) the `p`-norm used; valid options are:\n         `1`, `2`, `Inf`\n\n### Output\n\nThe operator norm, in the `p`-norm, of the scalar matrix obtained\nby taking the element-wise `diam` function, where `diam(x) := sup(x) - inf(x)`\nfor an interval `x`.\n\n### Notes\n\nThis function gives a measure of the *width* of the interval matrix.\n\"\"\"\nfunction diam_norm(A::IntervalMatrix, p=Inf)\n    return opnorm(diam.(A), p)\nend\n", "meta": {"hexsha": "c89dc4a32191eabb34f6bf821c4acc3196e059f7", "size": 2070, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/operations/norm.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/norm.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/norm.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.7472527473, "max_line_length": 83, "alphanum_fraction": 0.5835748792, "num_tokens": 621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422241476943, "lm_q2_score": 0.8947894597898776, "lm_q1q2_score": 0.851072036928458}}
{"text": "function  is_prime(n::Int64)\r\n\tif(n<=1)  return false\r\n\tend\r\n\tif(n==2)  return true\r\n\tend\r\n     if( n%2==0)  return false\r\n     end\r\n\ti::Int64=3\r\n\twhile(i*i<=n)\r\n\t\tif( n%i==0)  return false\r\n\t\tend\r\n\t\ti+=2\r\n\tend\r\n\r\n\treturn true;\r\n\r\nend\r\n\"\"\"\r\n# test \r\nfor i=1:100\r\n\tif( prime(i))\r\n\t\tprint(i,\"  \")\r\n\tend\r\nend\r\n\"\"\"\r\n\r\nfunction prime(N::Int64,a::Array{Int64,1})\r\n\t  b=fill(true,N);\r\n\t  b[1]=false;\r\n\t  for i=2:N\r\n\t  \tfor j=i*i:i:N \r\n\t  \t\tif(b[i])\r\n\t  \t\t\tb[j]=false\r\n\t  \t\tend\r\n\t  \tend\r\n\t  end\r\n\r\n\t  for i=1:N\r\n\t  \tif (b[i]) \r\n\t  \t\tpush!(a,i)\r\n\t  \tend\r\n\t  end\r\nend\r\n\r\n\"\"\"\r\n# test\r\na=Int64[]\r\nprime(100,a)\r\n\r\nprint(a)\r\n\r\n\"\"\"\r\n\r\n\r\nfunction prime_table(n::Int)\r\n\tb=fill(true,N);\r\n\tb[1]=false;\r\n\tfor i=2:N\r\n\t for j=i*i:i:N \r\n\t \tif(b[i])\r\n\t \t\tb[j]=false\r\n\t  \tend\r\n\t  end\r\n\tend\r\n\treturn b\r\nend\r\n\r\n", "meta": {"hexsha": "443d3f77e3fd49cb8faf87c867e8e4b29ec2ce97", "size": 784, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/prime.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/prime.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/prime.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.5294117647, "max_line_length": 43, "alphanum_fraction": 0.4795918367, "num_tokens": 283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517072737737, "lm_q2_score": 0.8856314723088733, "lm_q1q2_score": 0.8510490753305976}}
{"text": "# # Convex hull of a set of points\n\n# ## Convex hull in a plane\n\n# This examples shows how to find the convex hull in the context of a plane.\n# First we have to create an object representing the vertices. We have multiple ways of doing this\n\nusing Polyhedra\n\nv = convexhull([0, 0], [0, 1], [1, 0], [0.1, 0.1]) # list of points\nv = vrep([[0, 0], [0, 1], [1, 0], [0.1, 0.1]]) # vector of points\n# number of points \u00d7 dimension matrix\nx = [0,0,1,0.1]\ny = [0,1,0,0.1]\nv = vrep([x y])\n\n# Then we can compute the hull of these points using the planar_hull function\n\nPolyhedra.planar_hull(v)\n\n# ## Convex hull in higher dimension\n\n# In higher dimension, we can do it with a linear programming solver implementing the [MathOptInterface](https://github.com/jump-dev/MathOptInterface.jl), e.g.,\n\nimport GLPK\n\nremovevredundancy(v, GLPK.Optimizer)\n\n# We can also use any Polyhedral library implementing the interface of this package. If we don't specify any library, it falls back to a default one implementing on this package which will use the `planar_hull` if the dimension is 2 (so it's equivalent to the first approach shown above):\n\np = polyhedron(v)\nremovevredundancy!(p)\np\n\n# We can also specify a library. For instance, to use `CDDLib`, write `using CDDLib` and then `p = polyhedron(v, CDDLib.Library())`.\n", "meta": {"hexsha": "c672827662d2e44120f7bb78c63b44d0e1f2b8ec", "size": 1302, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Convex hull of a set of points.jl", "max_stars_repo_name": "blegat/Polyhedra", "max_stars_repo_head_hexsha": "07567d48fa60e6acc0d0ed1af012eb82c82ff78c", "max_stars_repo_licenses": ["MIT"], "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 of a set of points.jl", "max_issues_repo_name": "blegat/Polyhedra", "max_issues_repo_head_hexsha": "07567d48fa60e6acc0d0ed1af012eb82c82ff78c", "max_issues_repo_licenses": ["MIT"], "max_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 of a set of points.jl", "max_forks_repo_name": "blegat/Polyhedra", "max_forks_repo_head_hexsha": "07567d48fa60e6acc0d0ed1af012eb82c82ff78c", "max_forks_repo_licenses": ["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.1666666667, "max_line_length": 288, "alphanum_fraction": 0.7188940092, "num_tokens": 392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947148047778, "lm_q2_score": 0.9005297927918167, "lm_q1q2_score": 0.8509958947125085}}
{"text": "# Huber loss function\n\nusing LinearAlgebra\n\nexport HuberLoss\n\n\"\"\"\n**Huber loss**\n\n    HuberLoss(\u03c1=1.0, \u03bc=1.0)\n\nReturns the function\n```math\nf(x) = \\\\begin{cases}\n    \\\\tfrac{\u03bc}{2}\\\\|x\\\\|^2 & \\\\text{if}\\\\ \\\\|x\\\\| \u2a7d \u03c1 \\\\\\\\\n    \u03c1\u03bc(\\\\|x\\\\| - \\\\tfrac{\u03c1}{2}) & \\\\text{otherwise},\n\\\\end{cases}\n```\nwhere `\u03c1` and `\u03bc` are positive parameters.\n\"\"\"\nstruct HuberLoss{R <: Real} <: ProximableFunction\n    rho::R\n    mu::R\n    function HuberLoss{R}(rho::R, mu::R) where {R <: Real}\n        if rho <= 0.0 || mu <= 0.0\n            error(\"parameters rho and mu must be positive\")\n        else\n            new(rho, mu)\n        end\n    end\nend\n\nis_convex(f::HuberLoss) = true\nis_smooth(f::HuberLoss) = true\n\nHuberLoss(rho::R=1.0, mu::R=1.0) where {R <: Real} = HuberLoss{R}(rho, mu)\n\nfunction (f::HuberLoss)(x::AbstractArray{T}) where T <: Union{Real, Complex}\n    normx = norm(x)\n    if normx <= f.rho\n        return (f.mu/2)*normx^2\n    else\n        return f.rho*f.mu*(normx-f.rho/2)\n    end\nend\n\nfunction gradient!(y::AbstractArray{T}, f::HuberLoss, x::AbstractArray{T}) where T <: Union{Real, Complex}\n    normx = norm(x)\n    if normx <= f.rho\n        y .= f.mu .* x\n        v = (f.mu/2)*normx^2\n    else\n        y .= (f.mu*f.rho)/normx .* x\n        v = f.rho*f.mu*(normx-f.rho/2)\n    end\n    return v\nend\n\nfunction prox!(y::AbstractArray{T}, f::HuberLoss, x::AbstractArray{T}, gamma::Real=1.0) where T <: Union{Real, Complex}\n    normx = norm(x)\n    mugam = f.mu*gamma\n    scal = (1-min(mugam/(1+mugam), mugam*f.rho/(normx)))\n    for k in eachindex(y)\n        y[k] = scal*x[k]\n    end\n    normy = scal*normx\n    if normy <= f.rho\n        return (f.mu/2)*normy^2\n    else\n        return f.rho*f.mu*(normy-f.rho/2)\n    end\nend\n\nfun_name(f::HuberLoss) = \"Huber loss\"\nfun_dom(f::HuberLoss) = \"AbstractArray{Real}, AbstractArray{Complex}\"\nfun_expr(f::HuberLoss) = \"x \u21a6 (\u03bc/2)||x||\u00b2 if ||x||\u2a7d\u03c1, \u03bc\u03c1(||x||-\u03c1/2) otherwise\"\nfun_params(f::HuberLoss) = string(\"\u03c1 = $(f.rho), \u03bc = $(f.mu)\")\n\nfunction prox_naive(f::HuberLoss, x::AbstractArray{T}, gamma::Real=1.0) where T <: Union{Real, Complex}\n    y = (1-min(f.mu*gamma/(1+f.mu*gamma), f.mu*gamma*f.rho/(norm(x))))*x\n    if norm(y) <= f.rho\n        return y, (f.mu/2)*norm(y)^2\n    else\n        return y, f.rho*f.mu*(norm(y)-f.rho/2)\n    end\nend\n", "meta": {"hexsha": "b75dfc2d7fe5116dc7c36b021cbffea0e160f08d", "size": 2269, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/huberLoss.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/huberLoss.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/huberLoss.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.0804597701, "max_line_length": 119, "alphanum_fraction": 0.5698545615, "num_tokens": 843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154287592778, "lm_q2_score": 0.8872045877523147, "lm_q1q2_score": 0.8509660843146157}}
{"text": "# This subroutine discretize an AR(1) process with Tauchen (86)\n# \u03bb' = (1 - \u03c1)\u03bc_\u03bb + \u03c1\u03bb + \u03f5, where \u03f5 ~ N(0, (\u03c3_\u03f5)^2)\n# Inputs:\n# Outputs:\n\nusing Distributions\n\nfunction Tauchen(\u03bc_\u03bb, \u03c1, \u03c3_\u03f5, n; m = 3)\n    \u03c3_\u03bb = \u03c3_\u03f5/(1-\u03c1^2)^(1/2);\n\n    \u03bb_min = \u03bc_\u03bb - m*\u03c3_\u03bb;\n    \u03bb_max = \u03bc_\u03bb + m*\u03c3_\u03bb;\n    \u03bb_vals = range(\u03bb_min, \u03bb_max, length = n); # can also use LinRange(\u03bb_min, \u03bb_max, n)\n\n    w = \u03bb_vals[2] - \u03bb_vals[1];\n\n    d = Normal();\n    P = zeros(n,n);\n\n    for i in 1:n\n        for j = 1:n\n            if j == 1\n                P[i,j] = cdf(d, (\u03bb_vals[1] + w/2 - (1-\u03c1)*\u03bc_\u03bb - \u03c1*\u03bb_vals[i])/\u03c3_\u03f5);\n            elseif j == n\n                P[i,j] = 1 - cdf(d, (\u03bb_vals[n] - w/2 - (1-\u03c1)*\u03bc_\u03bb - \u03c1*\u03bb_vals[i])/\u03c3_\u03f5);\n            else\n                P[i,j] = cdf(d, (\u03bb_vals[j] + w/2 - (1-\u03c1)*\u03bc_\u03bb - \u03c1*\u03bb_vals[i])/\u03c3_\u03f5) - cdf(d, (\u03bb_vals[j] - w/2 - (1-\u03c1)*\u03bc_\u03bb - \u03c1*\u03bb_vals[i])/\u03c3_\u03f5);\n            end\n\n        end\n    end\n    return \u03bb_vals, P\nend\n\n", "meta": {"hexsha": "f367154c678b5880dfa017678fbe05fd50bbd4a1", "size": 911, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Ellen/HW1/Tauchen.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/Tauchen.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/Tauchen.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.0285714286, "max_line_length": 139, "alphanum_fraction": 0.4709110867, "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854146791214, "lm_q2_score": 0.8774767986961403, "lm_q1q2_score": 0.8509642010948443}}
{"text": "# # Logistic Regression\n# The presented example is adapted from the [Machine Learning - course by Andrew Ng](https://www.coursera.org/learn/machine-learning).\n#\n# In this example we use logistic regression to estimate the parameters $\\theta_i$ of a logistic model in a classification problem. We will first  transform the logistic regression problem into an exponential cone optimisation problem. We will then solve the optimisation problem with COSMO  and determine the model parameters and the decision boundary.\n# ## Visualizing the data\n# Before we start, let's load and take a look at the example data from `examples/chip_data.txt`:\n\n#-\nusing LinearAlgebra, SparseArrays, COSMO, JuMP\nusing Plots\n\n## load example data\nf = open(joinpath(@__DIR__, \"chip_data.txt\"))\nlines = readlines(f)\nclose(f)\nn_data = length(lines)\nn_half = div(n_data, 2)\nx1 = zeros(n_data)\nx2 = zeros(n_data)\ny = zeros(Float64, n_data)\nfor (i, l) in enumerate(lines)\n    s = split(l, \",\")\n    x1[i] = parse(Float64, s[1])\n    x2[i] = parse(Float64, s[2])\n    y[i] = parse(Float64, s[3])\nend\n\n\n## visualize data\nplot(x1[1:n_half-1], x2[1:n_half-1], color = :blue, st=:scatter, markershape = :cross, aspect_ratio=:equal, label = \"Accepted\", xlabel = \"x1 - Microchip Test Score 1\", ylabel = \"x2 - Microchip Test Score 2\")\nplot!(x1[n_half:end], x2[n_half:end], color = :red, st=:scatter, markershape = :circle, label = \"Rejected\")\n\n\n# The plot shows two test scores of $n$ microchip samples from a fabrication plant and whether the chip passed the quality check. Based on this data we would like to build a logistic model that takes into account the test scores and helps us predict the likelihood of a chip being accepted.\n#\n# ## Defining the logistic model\n# The logistic regression hypothesis is given by\n#\n# $$\n# h_\\theta(x) = g(\\theta^\\top x)\n# $$\n# where $g$ is the sigmoid function:\n# $$\n# g(\\theta^\\top x) = \\frac{1}{1+\\exp(-\\theta^\\top x)}.\n# $$\n#\n# The vector $x$ represents the independent variables and $\\theta$ represents the model parameters. For our samples we set the dependent variable $y =1$ if the chip was accepted and $y = 0$ otherwise.\n#\n# The function $h_\\theta(x)$ can be interpreted as the probability of the outcome being true rather than false. We want to find the parameters $\\theta$ that maximize the log-likelihood over all (independently Bernoulli distributed) observations\n#\n# $$\n# J(\\theta) = \\sum_{i, y_i = 1} \\log h_\\theta(x_i) + \\sum_{i, y_i = 0} \\log (1-h_\\theta(x_i)).\n# $$\n# Consequently, we want to solve the following optimization problem:\n# $$\n# \\text{minimize} \\quad -J(\\theta) + \\mu \\|\\theta \\|_2,\n# $$\n#\n# where we added a regularization term with parameter $\\mu$ to prevent overfitting.\n\n# ## Feature mapping\n# As our dataset only has two independent variables (the test scores) our model $y = \\theta_0 + \\theta_1 x_1 + \\theta_2 x_2$ will have the form of a straight line. Looking at the plot one can see that a line will not perform well in separating the samples. Therefore, we will create more features based on each data point by mapping the original features ($x_1$, $x_2$) into all polynomial terms of $x_1$ and $x_2$ up to the 6th power:\n#\n# $$\n# \\text{map\\_feature}(x_1,x_2) = [1, x_1, x_2, x_1^2, x_1x_2, x_2^2, x_1^3, \\dots, x_1x_2^5, x_2^6 ]\n# $$\n#\n# This will create 28 features for each sample.\n\n#-\n\nfunction map_feature(x1, x2)\n  deg = 6\n  x_new = ones(length(x1))\n  for i = 1:deg, j = 0:i\n      x_new = hcat(x_new, x1.^(i-j) .* x2.^j)\n  end\n  return x_new\nend\n\nX = map_feature(x1, x2);\nsize(X)\n\n# ## Transformation into a conic optimisation problem\n# We can rewrite above likelihood maximisation problem as a conic optimisation problem with exponential-cone-, second-order-cone-, equality-, and inequality constraints:\n#\n# $$\n# \\begin{array}{ll}\n# \\text{minimize}  &\\sum_i^n \\epsilon_i + \\mu v\\\\\n# \\text{subject to}  & \\|\\theta \\|_2 \\leq v\\\\\n# &  \\log(1 + \\exp(-\\theta^\\top x_i)) \\leq \\epsilon_i  \\quad \\text{if } y_i = 1, \\\\\n# & \\log(1 + \\exp(\\theta^\\top x_i)) \\leq \\epsilon_i  \\quad\\text{   otherwise.}\n# \\end{array}\n# $$\n#\n# Implementing the constraint $\\log(1 + \\exp(z)) \\leq \\epsilon$ for each of the $n$ samples requires two exponential cone constraints, one inequality constraint and two equality constraints. To see this, take the exponential on both sides and then divide by $\\exp(\\epsilon)$ to get:\n#\n# $$\n# \\exp(-\\epsilon) + \\exp(z - \\epsilon) \\leq 1.\n# $$\n#\n# This constraint is equivalent to:\n# $$\n# \\begin{array}{ll}\n# (z - \\epsilon, s_1, t_1) &\\in K_{\\text{exp}}, \\\\\n# (-\\epsilon, s_2, t_2) &\\in K_{\\text{exp}}, \\\\\n# t_1 + t_2 &\\leq 1,\\\\\n# s_1 = s_2 &= 1,\n# \\end{array}\n# $$\n#\n# where we defined the exponential cone as:\n# $$\n# K_{\\text{exp}} = \\{(r, s, t) \\mid s >0, s \\exp(r/s) \\leq t \\} \\cup \\{ r \\leq 0, s = 0, t \\geq 0 \\}.\n# $$\n#\n# Based on this transformation our optimisation problem will have $5n + n_\\theta + 1$ variables, 1 SOCP constraint, $2n$ exponential cone\n# constraints, $n$ inequality constraints and $2n$ equality constraints.\n# Let's model the problem with JuMP and COSMO:\n\n#-\n\nn_theta = size(X, 2)\nn = n_data\n\u03bc  = 1.\n\nm = JuMP.Model(COSMO.Optimizer)\n@variable(m, v)\n@variable(m, \u03b8[1:n_theta])\n@variable(m, e[1:n])\n@variable(m, t1[1:n])\n@variable(m, t2[1:n])\n@variable(m, s1[1:n])\n@variable(m, s2[1:n])\n\n@objective(m, Min, \u03bc * v + sum(e))\n@constraint(m, [v; \u03b8] in MOI.SecondOrderCone(n_theta + 1))\n\n## create the constraints for each sample points\nfor i = 1:n\n  yi = y[i]\n  x = X[i, :]\n  yi == 1. ? (a = -1) : (a = 1)\n  @constraint(m, [a * dot(\u03b8, x) - e[i]; s1[i]; t1[i] ] in MOI.ExponentialCone())\n  @constraint(m, [-e[i]; s2[i]; t2[i]] in MOI.ExponentialCone())\n  @constraint(m, t1[i] + t2[i] <= 1)\n  @constraint(m, s1[i] == 1)\n  @constraint(m, s2[i] == 1)\nend\nJuMP.optimize!(m)\n#-\ntheta = value.(\u03b8)\n\n# Once we have solved the optimisation problem and obtained the parameter vector $\\theta$, we can plot the decision boundary. This can be done by evaluating our model over a grid of points $(u,v)$ and then plotting the contour line where the function $g$ returns a probability of $p=0.5$.\n\n#-\n## First we evaluate our model over a grid of points z = \u03b8' x\nu = collect(range(-1., stop = 1.5, length = 50))\nv = collect(range(-1., stop = 1.5, length = 50))\nz = zeros(length(u), length(v));\nfor i = 1:length(u), j = 1:length(v)\n    z[i, j] = dot(map_feature(u[i], v[j]), theta);\nend\n\n# To add the decision boundary we have to plot the line indicating $50\\%$ probability of acceptance, i.e. $g(\\theta^\\top x) = g(z)  = 0.5$ which we get at $z=0$.\n\n#-\nplot(x1[1:n_half-1], x2[1:n_half-1], color = :blue, st = :scatter, markershape = :cross, aspect_ratio=:equal, label = \"Accepted\", xlabel = \"x1 - Microchip Test Score 1\", ylabel = \"x2 - Microchip Test Score 2\")\nplot!(x1[n_half:end], x2[n_half:end], color = :red, st = :scatter, markershape = :circle, label = \"Rejected\")\ncontour!(u, v, z', levels = [0.], c = :black, linewidth = 2)\n\n# ## Solving the optimisation problem directly with COSMO\n# We can solve the problem directly in COSMO by using its modeling interface. The problem will have $nn = 5 n + n_\\theta + 1$ variables. Let us define the cost function  $\\frac{1}{2}x^\\top P x + q^\\top x$:\n\n#-\nnn = 5 * n + n_theta +  1\nP = spzeros(nn, nn)\nq = zeros(nn)\nq[1] = \u03bc\nfor i = 1:n\n  q[1 + n_theta + (i - 1) * 5 + 1] = 1.\nend\n# Next we define a function that creates the `COSMO.Constraints` for a given sample:\n\n#-\n## the order of the variables\n## v, thetas, [e1 t11 t12 s11 s12] [e2 t21 t22 s21 s22] ...\n## for each sample create two exponential cone constraints,\n## 1 nonnegatives constraint, 2 zeroset constraints\nfunction add_log_regression_constraints!(constraint_list, x, y, n, sample_num)\n  num_thetas = length(x)\n  ## 1st exponential cone constraint (zi - ei, s1, t1) in Kexp\n  c_start = 1 + num_thetas + (sample_num - 1) * 5 + 1\n  A = spzeros(3, n)\n  A[1, c_start] = -1.\n  y == 1. ? (a = -1) : (a = 1)\n  for k = 1:num_thetas\n    A[1, 2 + k - 1] = a * x[k]\n  end\n  A[2, c_start + 3] = 1.\n  A[3, c_start + 1] = 1.\n  b = zeros(3)\n  push!(constraint_list, COSMO.Constraint(A, b, COSMO.ExponentialCone))\n\n  ## 2nd exponential cone constraint (-e, s2, t2)\n  A = spzeros(3, n)\n  A[1, c_start] = -1.\n  A[2, c_start + 4] = 1.\n  A[3, c_start + 2] = 1.\n  b = zeros(3)\n  push!(constraint_list, COSMO.Constraint(A, b, COSMO.ExponentialCone))\n\n  ## Nonnegatives constraint t1 + t2 <= 1\n  A = spzeros(1, n)\n  A[1, c_start + 1] = -1.\n  A[1, c_start + 2] = -1.\n  b = [1.]\n  push!(constraint_list, COSMO.Constraint(A, b, COSMO.Nonnegatives))\n\n  ## ZeroSet constraint s1 == 1, s2 == 1\n  A = spzeros(2, n)\n  A[1, c_start + 3] = 1.\n  A[2, c_start + 4] = 1.\n  b = -1 * ones(2)\n  push!(constraint_list, COSMO.Constraint(A, b, COSMO.ZeroSet))\nend\nnothing\n\n# Now we can use this function to loop over the sample points and add the constraints to our constraint list:\n\n#-\nconstraint_list = Array{COSMO.Constraint{Float64}}(undef, 0)\nfor i = 1:n\n  add_log_regression_constraints!(constraint_list, X[i, :], y[i], nn, i )\nend\n\n# It remains to add a second order cone constraint for the regularisation term:\n# $\\|\\theta \\|_2 \\leq v$\n\n#-\npush!(constraint_list, COSMO.Constraint(Matrix(1.0I, n_theta + 1, n_theta + 1), zeros(n_theta + 1), COSMO.SecondOrderCone, nn, 1:n_theta+1));\n\n# We can now create, assemble, and solve our `COSMO.Model`:\n\n#-\nmodel = COSMO.Model()\nassemble!(model, P, q, constraint_list, settings = COSMO.Settings(verbose=true))\nres = COSMO.optimize!(model);\n\n# Let us double check that we get the same $\\theta$ as in the previous section:\n\n#-\nusing Test\ntheta_cosmo = res.x[2:2+n_theta-1]\n@test norm(theta_cosmo - theta) < 1e-10\n", "meta": {"hexsha": "dff3175af8f57bf1d216c7f6bbe897d0b53887df", "size": 9591, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/logistic_regression.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/logistic_regression.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/logistic_regression.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": 37.46484375, "max_line_length": 435, "alphanum_fraction": 0.666249609, "num_tokens": 3182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214511730025, "lm_q2_score": 0.8824278680004706, "lm_q1q2_score": 0.8509441222257125}}
{"text": "using lolPackage\nusing Test\n\n\n    \n    #TEST 1 WITH DERIVATIVES\n    f(x)=x^2\n    fprime(x)=2*x\n    @test Newtonsroot1(f,fprime,xiv=0.1)[1]\u22480.0 atol=0.00001\n    \n    f(x)=x^2-16\n    fprime(x)=2*x\n    @test Newtonsroot1(f,fprime,xiv=3.1)[1]\u22484.0 atol=0.00001\n    \n    f(x)=(x-2)^2\n    fprime(x)=2*(x-2)\n    @test Newtonsroot1(f,fprime,xiv=1.0)[1]\u22482.0 atol=0.00001\n    \n    #TEST 2 WITHOUT DERIVATIVES\n    f(x)=x^2\n    \n    @test Newtonsroot1(f,xiv=1.0)[1]\u22480.0 atol=0.00001\n    \n    f(x)=x^2-16\n    @test Newtonsroot1(f,xiv=1.0)[1]\u22484.0 atol=0.00001\n    \n    f(x)=(x-2)^2\n    @test Newtonsroot1(f,xiv=1.0)[1]\u22482.0 atol=0.00001\n    \n    #TEST 3 BIGFLOAT\n    f(x)=(x-2)^2\n    a=BigFloat(2.0)\n    @testset \"BigFloat\" begin\n        @test    Newtonsroot1(f,xiv=1.0)[1]\u22482.0 atol=0.00001\n        @test    Newtonsroot1(f,xiv=1.0)[1]\u2248a atol=0.00001\n    end\n    \n    \n    #TEST 4 tolerance (Accuracy dependent on tolerance)\n    f(x)=4x^3-16x+10\n    a=Newtonsroot1(f,xiv=1)[1]\n    b=Newtonsroot1(f,xiv=1, tol=0.0001)[1]\n    c=Newtonsroot1(f,xiv=1, tol=0.01)[1]\n    @test f(a)<f(b)<f(c)\n\n    #TEST 5 Non-Convergence\n    #Test non-convergence (return nothing)\n    f(x)=2+x^2\n    @test Newtonsroot1(f,xiv=0.2)==nothing\n    \n    #TEST 6 Maxiter\n    f(x)=log(x)-20\n    a=Newtonsroot1(f,xiv=0.2)[1] #Algorithm needs 17 iterations in this case\n    b=Newtonsroot1(f,xiv=0.2,maxiter=5)\n    @testset \"maxiter\" begin\n    @test a\u22484.851651954097909e8 atol=0.000001 \n    @test b==nothing\n    end;\n    \n    \n    \n    \n    \n\n", "meta": {"hexsha": "f73b80024cd7d4ea135105c3bba9a1f6640b5291", "size": 1492, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "anubhavpcjha/lolPackage", "max_stars_repo_head_hexsha": "5a1649076dba63c3dcef0bf9a7dadec1a6be755a", "max_stars_repo_licenses": ["MIT"], "max_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": "anubhavpcjha/lolPackage", "max_issues_repo_head_hexsha": "5a1649076dba63c3dcef0bf9a7dadec1a6be755a", "max_issues_repo_licenses": ["MIT"], "max_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": "anubhavpcjha/lolPackage", "max_forks_repo_head_hexsha": "5a1649076dba63c3dcef0bf9a7dadec1a6be755a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9538461538, "max_line_length": 76, "alphanum_fraction": 0.5777479893, "num_tokens": 640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475683211324, "lm_q2_score": 0.9019206673024666, "lm_q1q2_score": 0.8508246683183549}}
{"text": "\"\"\"\n    horner(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    n = length(c)\n    y = c[n]\n    for k in n-1:-1:1\n        y = x*y + c[k]\n    end\n    return y\nend\n", "meta": {"hexsha": "05910dcaa87a1ccc4dd45afbc5e729de81a0fb1a", "size": 264, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chapter01.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/chapter01.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/chapter01.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": 17.6, "max_line_length": 63, "alphanum_fraction": 0.5795454545, "num_tokens": 83, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9539660949832346, "lm_q2_score": 0.8918110396870287, "lm_q1q2_score": 0.8507574949931732}}
{"text": "# The 5-digit number, 16807=7^5, is also a fifth power. Similarly, the 9-digit\n# number, 134217728=8^9, is a ninth power.\n#\n# How many n-digit positive integers exist which are also an nth power?\n\nusing ProjectEulerSolutions\n\n# Brute for approach, cycling through nth powers on single digits until we see\n# that no more signal digits have the right number of digits (using the built-in\n# ndigits function).\nfunction p063solution_bruteforce(max_n::Integer=10)::Integer\n\n    digs = BigInt.(1:9)\n    count = 0\n    for n = 1:max_n\n        c = sum(ndigits.(digs .^ n) .== n)\n        if c == 0\n           break\n        end\n        count += c\n    end\n    return count\nend\n\n# Recognize that a single digit number k will have n digits as long as \n# 10^(n-1) <= k^n < 10^n.  We know k^n < 10^n when k is 1:9.  Solve for k\n# 10^((n-1) / n) <= k and cycle through n values to see the number of values for\n# n where the relation holds.  Vectorize and try with k = 1:9 to solve the\n# problem in a single line.\nfunction p063solution_explicit_powers(max_n::Integer=10)::Integer\n    return Integer(sum(9 .- floor.(10 .^((0:(max_n-1))./(1:max_n)))) + 1)\nend\n\n# Alternatively, solve directly for n: 10^(n-1) = k^n, (n-1) log(10) = n log(k),\n# n = log(10) / (log(10) - log(k)), where we pass values for k = 1:9.\nfunction p063solution_explicit_logs(max_n::Integer=10)::Integer\n    return Integer(sum(floor.(log.(10)./(log.(10).-log.(1:9)))))\nend\n\np063 = Problems.Problem(Dict(\"Brute-force\" => p063solution_bruteforce,\n                             \"Explicit powers\" => p063solution_explicit_powers,\n                             \"Explicit logs\" => p063solution_explicit_logs))\n\nProblems.benchmark(p063, 30)\n", "meta": {"hexsha": "b4a3b2f4a92431df8f022ed23bd3e1ece4213407", "size": 1684, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/063.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/063.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/063.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.4222222222, "max_line_length": 80, "alphanum_fraction": 0.6526128266, "num_tokens": 515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248225478307, "lm_q2_score": 0.9059898299021698, "lm_q1q2_score": 0.8507469392540243}}
{"text": "# L2 norm (times a constant)\n\nexport NormL2\n\n\"\"\"\n**``L_2`` norm**\n\n    NormL2(\u03bb=1.0)\n\nWith a nonnegative scalar parameter \u03bb, returns the function\n```math\nf(x) = \u03bb\\\\cdot\\\\sqrt{x_1^2 + \u2026 + x_n^2}.\n```\n\"\"\"\nstruct NormL2{R <: Real} <: ProximableFunction\n    lambda::R\n    function NormL2{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\nis_convex(f::NormL2) = true\n\nNormL2(lambda::R=1.0) where {R <: Real} = NormL2{R}(lambda)\n\nfunction (f::NormL2)(x::AbstractArray)\n    return f.lambda*norm(x)\nend\n\nfunction prox!(y::AbstractArray{T}, f::NormL2, x::AbstractArray{T}, gamma::Real=1.0) where T <: RealOrComplex\n    normx = norm(x)\n    scale = max(0, 1-f.lambda*gamma/normx)\n    for i in eachindex(x)\n        y[i] = scale*x[i]\n    end\n    return f.lambda*scale*normx\nend\n\nfunction gradient!(y::AbstractArray{T}, f::NormL2, x::AbstractArray{T}) where T <: Union{Real, Complex}\n    fx = norm(x) # Value of f, without lambda\n    if fx == 0\n        y .= 0\n    else\n        y .= (f.lambda/fx).*x\n    end\n    return f.lambda*fx\nend\n\nfun_name(f::NormL2) = \"Euclidean norm\"\nfun_dom(f::NormL2) = \"AbstractArray{Real}, AbstractArray{Complex}\"\nfun_expr(f::NormL2) = \"x \u21a6 \u03bb||x||_2\"\nfun_params(f::NormL2) = \"\u03bb = $(f.lambda)\"\n\nfunction prox_naive(f::NormL2, x::AbstractArray{T}, gamma::Real=1.0) where T <: RealOrComplex\n    normx = norm(x)\n    scale = max(0, 1-f.lambda*gamma/normx)\n    y = scale*x\n    return y, f.lambda*scale*normx\nend\n", "meta": {"hexsha": "cd2486d016b45a6963bfc69a486a1b9c6f6a2eb8", "size": 1538, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/normL2.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/normL2.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/normL2.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.03125, "max_line_length": 109, "alphanum_fraction": 0.6157347204, "num_tokens": 524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.941654159388319, "lm_q2_score": 0.9032942106088967, "lm_q1q2_score": 0.8505907505712558}}
{"text": "\nusing Random\nusing LinearAlgebra\nusing PyPlot\nusing Seaborn\n#PyPlot.svg(true)\n\nfunction iterate_CG(xk, rk, pk, A)\n    \"\"\"\n    Basic iteration of the conjugate gradient algorithm\n    Parameters:\n    xk: current iterate\n    rk: current residual\n    pk: current direction\n    A: matrix of interest\n    \"\"\"\n    \n    # form products\n    rkk = rk' * rk\n    Apk = A * pk \n    \n    # construct step size\n    \u03b1k = rkk / (pk' * Apk)\n\n    # take a step in current conjugate direction\n    xk_new = xk + \u03b1k * pk\n\n    # construct new residual\n    rk_new = rk + \u03b1k * Apk\n\n    # construct new linear combination\n    betak_new = (rk_new' * rk_new) / rkk\n\n    # generate new conjugate vector\n    pk_new = -rk_new + betak_new * pk\n\n    return xk_new, rk_new, pk_new\n\nend\n\nfunction run_conjugate_gradient(x0, A, b; max_iter = 2000)\n    \"\"\"\n    Conjugate gradient algorithm\n\n    Parameters:\n    x0: initial point\n    A: matrix of interest\n    b: vector in linear system (Ax = b)\n    max_iter: max number of iterations to run CG\n    \"\"\"\n\n    # initial iteration\n    xk = x0\n    rk = A * xk - b\n    pk = -rk\n    \n    err = sum(abs.(rk))\n    errors = [err]\n    D = pk\n\n    #while sum(abs.(rk)) > 10e-6\n    for i in 1:max_iter\n        xk, rk, pk = iterate_CG(xk, rk, pk, A)\n        \n        D = hcat(D,pk)\n        \n        err = sum(abs.(rk))\n        push!(errors, err)\n        \n        # print iteration\n        i % 500 == 0 && println(\"Iteration $i: error: $err\")\n\n        # break if we reach desired error \n        if err < 10e-6\n            println(\"Terminated in $i iterations\")\n            break\n        end\n    end\n    \n    return xk, errors, D\nend\n\nRandom.seed!(123)\nb = rand(5)\n\nA = zeros(5,5)\nA[1,1]=10; A[2,2]=10.1; A[3,3]=10.2; A[4,4]=2; A[5,5] = 1\n\nx = A \\ b\n\nx0 = [0.3,0.1,0.1,0.1,0.1]\nxsol, errors, D = run_conjugate_gradient(x0, A, b);\nxsol\n\nSeaborn.semilogy(0:length(errors)-1, errors)\nxlabel(\"iteration\"); ylabel(\"total absolute error\")\n\n# confirm these are 0\n@assert D[:,1]' * A * D[:,2] < 10e-6\n@assert D[:,1]' * A * D[:,3] < 10e-6\n@assert D[:,1]' * A * D[:,4] < 10e-6\n\n# confirm these aren't 0\n@assert D[:,1]' * A * D[:,1] < 10e-6\n\n# Construct a random symmetric positive definite matrix\nRandom.seed!(111)\nA = rand(5,5); A = 0.5*(A+A'); A = A + 5*I;\n\neigvals(A) \n\nx2 = A \\ b\n\nx0 = [0.,0.,0.,0.,0.]\nxsol, errors, D = run_conjugate_gradient(x0, A, b);\nxsol\n\nSeaborn.semilogy(0:length(errors)-1, errors)\nxlabel(\"iteration\"); ylabel(\"total absolute error\")\n\nN = 1000\nRandom.seed!(123)\nb = rand(N)\nA = rand(N,N); A = 0.5*(A+A'); A = A + 50*I;\nprintln(\"The condition number is: \", cond(A))\n\n# distribution of the eigenvalues\nplt[:hist](eigvals(A), bins=500); xlim(0,100)\n\nx0 = zeros(N)\nxsol, errors, D = run_conjugate_gradient(x0, A, b);\nxsol;\n\nSeaborn.semilogy(0:length(errors)-1, errors)\nxlabel(\"iteration\"); ylabel(\"total absolute error\")\n\nD[:,1]' * A * D[:,2]\n\nD[:,1]' * A * D[:,10]\n\nD[:,1]' * A * D[:,33]\n\nRandom.seed!(123)\n\n# Generate random s.p.d. matrix\nA = rand(N,N); A = 0.5*(A+A'); A = A + 13*I;\nprintln(\"The condition number is: \", cond(A))\n\n# distribution of the eigenvalues\nplt[:hist](eigvals(A), bins=500); xlim(0,100)\n\nx0 = zeros(N)\nxsol, errors, D = run_conjugate_gradient(x0, A, b; max_iter=5000);\n\nSeaborn.semilogy(0:length(errors)-1, errors)\nxlabel(\"iteration\"); ylabel(\"total absolute error\")\n\nD[:,1]' * A * D[:,2]\n\nD[:,1]' * A * D[:,7]\n\nD[:,1]' * A * D[:,75]\n", "meta": {"hexsha": "b6f0cd9c16dc3acde532b404c266cf0907fa780b", "size": 3372, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "conjugate_gradient.jl", "max_stars_repo_name": "dicai/stats_notebook", "max_stars_repo_head_hexsha": "08ec0f99fc953010c4e2af1aa6fbab836b0a6f10", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-12-03T03:20:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-21T07:21:13.000Z", "max_issues_repo_path": "conjugate_gradient.jl", "max_issues_repo_name": "dicai/stats_notebook", "max_issues_repo_head_hexsha": "08ec0f99fc953010c4e2af1aa6fbab836b0a6f10", "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": "conjugate_gradient.jl", "max_forks_repo_name": "dicai/stats_notebook", "max_forks_repo_head_hexsha": "08ec0f99fc953010c4e2af1aa6fbab836b0a6f10", "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.6871165644, "max_line_length": 66, "alphanum_fraction": 0.5851126928, "num_tokens": 1164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430812881347, "lm_q2_score": 0.9111797130267453, "lm_q1q2_score": 0.8505232202115474}}
{"text": "using DataFrames\nusing DataArrays\nusing DifferentialEquations\nusing ParameterizedFunctions\nusing Gadfly\n\n# definition of differential equations\ng = @ode_def_nohes LotkaVolterra begin\n         dx = A*x - B*x*y\n         dy = -C*y + D*x*y\nend A=>1.0 B =>1.0 C =>1.0 D =>1.0\n\n# solving differential equations\nfunction lotka_volterra(a, b, c, d, t0, t1, x0, y0)\n  u0 = [x0;y0]\n  tspan = (t0,t1)\n  h = LotkaVolterra(A=a,B=b,C=c,D=d)\n  prob = ODEProblem(h,u0,tspan)\n  sol = solve(prob, RK4(), dt=0.01)\n  return sol\nend\n\n# extracting results and saving into array\nfunction into_array(sol, expNum)\n  results = Array{Any,1}[]\n  mintime = first(sol.t)\n  maxtime = last(sol.t)\n  i = mintime\n  push!(results, [\"t\", \"x\", \"y\", \"experiment\"])\n  while i < maxtime\n    push!(results, [i, sol(i)[1], sol(i)[2], \"exp$expNum\"])\n    i += 0.1\n  end\n  return results\nend\n\n# saving results (array) into csv file\nfunction into_file(filename, results)\n  open(filename,\"w\")\n  writecsv(filename, results)\nend\n\nfunction experiments()\n  s1 = lotka_volterra(1.5,1.0,3.0,1.0,0.0,5.0,8.0,4.0)\n  s2 = lotka_volterra(1.5,1.0,3.0,1.0,0.0,5.0,16.0,2.0)\n  s3 = lotka_volterra(1.5,1.0,3.0,1.0,0.0,5.0,12.0,4.0)\n  s4 = lotka_volterra(1.5,1.0,3.0,1.0,0.0,5.0,2.0,10.0)\n  into_file(\"res1.csv\",into_array(s1,1))\n  into_file(\"res2.csv\",into_array(s2,2))\n  into_file(\"res3.csv\",into_array(s3,3))\n  into_file(\"res4.csv\",into_array(s4,4))\n  return [s1,s2,s3,s4]\nend\n\n# read in csv files into DataFrame\nfunction read_in(res...)\n  df = vcat([readtable(res[i]) for i in 1:length(res)])\nend\n\n# print out min, max and mean value for each experiment\nfunction min_max_mean(data)\n  experiments = sort(unique(data[:experiment]))\n  i = 1\n  for exp in experiments\n    println(\"Experiment $i\\n\")\n    exp_data = data[data[:experiment] .== exp, :]\n    println(\"Prey population\\n\")\n    println(\"Minimum: $(minimum(exp_data[:x]))\")\n    println(\"Maximum: $(maximum(exp_data[:x]))\")\n    println(\"Mean:    $(mean(exp_data[:x]))\")\n    println(\"\\nPredator population\\n\")\n    println(\"Minimum: $(minimum(exp_data[:y]))\")\n    println(\"Maximum: $(maximum(exp_data[:y]))\")\n    println(\"Mean:    $(mean(exp_data[:y]))\")\n    println(\"\\n\")\n    i += 1\n  end\nend\n\n# adding new column\nfunction diff_column(data)\n  new_data = data\n  new_data[:diff] = new_data[:y] - new_data[:x]\n  return new_data\nend\n\n# plotting functions\nfunction plot_prey_population(sol)\n  df=DataFrame(t=sol.t, prey=map(x->x[1],sol.u))\n  plot(df,  x=\"t\", y=\"prey\") #prey population\nend\n\nfunction plot_predator_population(sol)\n  df2=DataFrame(t=sol.t, predator=map(y->y[2],sol.u))\n  plot(df2,  x=\"t\", y=\"predator\") #predator population\nend\n\nfunction plot_prey_predator(data)\n  dataframe = DataFrame()\n  exp1_data = data[data[:experiment] .== \"exp1\", :]\n  exp2_data = data[data[:experiment] .== \"exp2\", :]\n  exp3_data = data[data[:experiment] .== \"exp3\", :]\n  exp4_data = data[data[:experiment] .== \"exp4\", :]\n  dataframe[:x1] = exp1_data[:x]\n  dataframe[:y1] = exp1_data[:y]\n  dataframe[:x2] = exp2_data[:x]\n  dataframe[:y2] = exp2_data[:y]\n  dataframe[:x3] = exp3_data[:x]\n  dataframe[:y3] = exp3_data[:y]\n  dataframe[:x4] = exp4_data[:x]\n  dataframe[:y4] = exp4_data[:y]\n\n  plot(dataframe, layer(x=\"x1\", y=\"y1\", Geom.point, Theme(default_color= colorant\"blue\")),\n                  layer(x=\"x2\", y=\"y2\", Geom.point, Theme(default_color= colorant\"red\")),\n                  layer(x=\"x3\", y=\"y3\", Geom.point, Theme(default_color= colorant\"green\")),\n                  layer(x=\"x4\", y=\"y4\", Geom.point, Theme(default_color= colorant\"yellow\")),\n                  Guide.XLabel(\"Prey population\"),\n                  Guide.YLabel(\"Predator population\"),\n                  Guide.Title(\"Lotka - Volterra\"))\nend\n\nsolutions = experiments()\n\nsolutions_data = read_in(\"res1.csv\", \"res2.csv\", \"res3.csv\", \"res4.csv\")\n\nmin_max_mean(solutions_data)\n\ndiff_column(solutions_data)\n\nplot_prey_population(solutions[1])\n\nplot_predator_population(solutions[1])\n\nplot_prey_predator(solutions_data)", "meta": {"hexsha": "f876ca5b3de43207d960705632597d3c12f0351b", "size": 3962, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lab-4/lvEquations.jl", "max_stars_repo_name": "wchmielarz/NobodyDoesItLikeJuliet", "max_stars_repo_head_hexsha": "797a0e1b5d3ac291ac25f726f69752cc20dff245", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lab-4/lvEquations.jl", "max_issues_repo_name": "wchmielarz/NobodyDoesItLikeJuliet", "max_issues_repo_head_hexsha": "797a0e1b5d3ac291ac25f726f69752cc20dff245", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lab-4/lvEquations.jl", "max_forks_repo_name": "wchmielarz/NobodyDoesItLikeJuliet", "max_forks_repo_head_hexsha": "797a0e1b5d3ac291ac25f726f69752cc20dff245", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5671641791, "max_line_length": 92, "alphanum_fraction": 0.6519434629, "num_tokens": 1314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191284552529, "lm_q2_score": 0.8902942224835226, "lm_q1q2_score": 0.8505151006917059}}
{"text": "export cgs, cgs!, mgs, mgs!\n\n\"\"\"\nKrylovMethods.cgs = KrylovMethods.cgs!(copy(V))\n\t\n\tClassical Gram Schmidt orthogonalization.\n\n\"\"\"\ncgs(V) = cgs!(copy(V))\n\n\n\"\"\"\nfunction KrylovMethods.cgs!\n\t\nInplace Classical Gram Schmidt orthogonalization.\n\nReference: page 254 in Golub and Van Loan, Matrix Computation, 4th edition.\n\nInput:\n\n\tV::Array  - m by n matrix of full rank m<=n\n\t\nOutput:\n\n\tV::Array  - m-by-m unitary matrix\n\tR::Array  - m-by-n upper triangular matrix\n\n\"\"\"\nfunction cgs!{T}(V::Array{T})\n\n\tm,n    = size(V)\n\tR      = zeros(T,n,n)\n\tR[1,1] = norm(V[:,1])\n\tV[:,1] ./= R[1,1]\n\tfor k=2:n\n\t    R[1:k-1,k] = V[:,1:k-1]'*V[:,k]\n\t    V[:,k]     = V[:,k]-V[:,1:k-1]*R[1:k-1,k]\n\t    R[k,k]     = norm(V[:,k])\n\t    V[:,k]   ./= R[k,k]\n\tend\n\treturn V,R\nend\n\n\n\"\"\"\nKrylovMethods.mgs = KrylovMethods.mgs!(copy(V))\n\t\n\tModified Gram Schmidt orthogonalization.\n\n\"\"\"\nmgs(V) = mgs!(copy(V))\n\n\"\"\"\nfunction KrylovMethods.mgs!\n\t\nInplace Modified Gram Schmidt orthogonalization.\n\nReference: page 255 in Golub and Van Loan, Matrix Computation, 4th edition.\n\nInput:\n\n\tV::Array  - m by n matrix of full rank m<=n\n\t\nOutput:\n\n\tV::Array  - m-by-m unitary matrix\n\tR::Array  - m-by-n upper triangular matrix\n\n\"\"\"\nfunction mgs!{T}(V::Array{T})\n\tm,n    = size(V)\n\tR      = zeros(T,n,n)\n\tfor k=1:n\n\t\tR[k,k]    = norm(V[:,k])\n\t\tV[:,k]    ./= R[k,k]\n\t\tfor j=k+1:n\n\t\t\tR[k,j] = dot(V[:,k],V[:,j])\n\t\t\tV[:,j] -= R[k,j]*V[:,k]\n\t\tend\n\tend\n\treturn V,R\nend", "meta": {"hexsha": "cc22ca1be6eb2bd90b8c1ec2034fd095ab6a4967", "size": 1418, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gs.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/gs.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/gs.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": 17.2926829268, "max_line_length": 75, "alphanum_fraction": 0.5874471086, "num_tokens": 498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799420543365, "lm_q2_score": 0.8824278633625322, "lm_q1q2_score": 0.8504662750186732}}
{"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\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])\n\nnewAlpha, newBeta = alpha + sum(data), beta + length(data)\nclosedFormBayesEstimate = mean(Gamma(newAlpha, 1/newBeta))\n\nprintln(\"Computational Bayes Estimate: \", bayesEstimate)\nprintln(\"Closed form Bayes Estimate: \", closedFormBayesEstimate)\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\")\n", "meta": {"hexsha": "a987ad9e6b89903f9ac87eb6efde17e1a1fed61d", "size": 912, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "5_chapter/bayesUnivariateConjugate.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/bayesUnivariateConjugate.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/bayesUnivariateConjugate.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.4482758621, "max_line_length": 67, "alphanum_fraction": 0.7028508772, "num_tokens": 318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799472560581, "lm_q2_score": 0.8824278540866548, "lm_q1q2_score": 0.8504662706689127}}
{"text": "module problem110\n\ndescription = \"\"\"\nDiophantine reciprocals II\n\nIn the following equation x, y, and n are positive integers.\n1/x + 1/y = 1/n\n\nIt can be verified that when n = 1260 there are 113 distinct solutions and this is the least value of n for which the total number of distinct solutions exceeds one hundred.\nWhat is the least value of n for which the number of distinct solutions exceeds four million?\n\"\"\"\n\n# From the forums in problem 108, I found that the number of solutions to N = ((number of divisors of N^2) + 1)/2\n# Number of divisors can be efficiently calculated by taking the product of (power+1) for the powers of the prime factors of n\n\nfunction nextprime(n)\n  m = n+1\n  while !isprime(m)\n    m += 1\n  end\n  return m\nend\n\n# solution_count(N) = (sigma0(N^2) + 1) / 2\n# N has be factored into product of primes already\n# Sigma0(N^2) is inlined by doubling the power of each prime\nfunction solution_count(d :: Dict)\n  return div(prod([2*v + 1 for v in values(d)]) + 1, 2)\nend\n\n# Seach for the least N solving 1/x + 1/y = 1/N with at least the given number of solutions\n# Iteratively search using numbers of the form 2^p2 * 3^p3 * 5^p5 ..., where p2 >= p3 >= p5 etc..\n# Stop searching once increasing the power on the 2 term doesn't reduce the minimum solution\nfunction least_n_with_num_solutions(numSolutions :: Integer)\n  leastN = -1\n  p2 = 1\n  while true\n    n = solution_search(numSolutions, [2 => p2]) \n    if leastN < 0 || n < leastN\n      leastN = n\n    elseif n > leastN \n      break\n    end\n    p2 += 1\n  end\n  return leastN\nend\n\n# Workhorse function, searches for value with > numSolutions\n# value is kept in factorized form in the Dict d, but is returned as BigInt\nfunction solution_search(numSolutions :: Integer, d :: Dict)\n\n  # base case: D already has enough solutions, so return the value as a BigInt\n  if solution_count(d) >= numSolutions\n    return prod([BigInt(prime)^power for (prime, power) in d])\n  end\n\n  # Recusive case: Find the next prime to add to d, and check with all powers up to the power of the current max prime in d.\n  leastN = -1\n  maxPrime = maximum(keys(d))\n  p = nextprime(maxPrime)\n  for exponent = 1 : d[maxPrime]\n    d[p] = exponent \n    n = solution_search(numSolutions, d)\n    if leastN < 0 || (n > 0 && n < leastN)\n      leastN = n\n    end     \n  end\n\n  # Cleanup the Dict on the way out\n  delete!(d, p)\n  return leastN\nend\n\nusing Base.Test\n\n@test solution_count(factor(1260)) == 113\n@test least_n_with_num_solutions(113) == 1260\n@test least_n_with_num_solutions(1000) == 180180 #from problem 108\n\nend", "meta": {"hexsha": "4ee8b9884a8464b77984156fbb48ab01823be1a9", "size": 2562, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/problem110.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/problem110.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/problem110.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.6296296296, "max_line_length": 173, "alphanum_fraction": 0.6990632319, "num_tokens": 747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029486, "lm_q2_score": 0.9073122201074847, "lm_q1q2_score": 0.8503428038565021}}
{"text": "\"Square the sum of the first `n` positive integers\"\nfunction square_of_sum(n)\n    (n * (n + 1) \u00f7 2)^2\nend\n\n\"Sum the squares of the first `n` positive integers\"\nfunction sum_of_squares(n)\n    n * (n + 1) * (2 * n + 1) \u00f7 6\nend\n\n\"Subtract the sum of squares from square of the sum of the first `n` positive ints\"\nfunction difference(n)\n    square_of_sum(n) - sum_of_squares(n)\nend\n", "meta": {"hexsha": "efa7c5284c7a3e0623232a5fc0fc98fd5ecac004", "size": 378, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/difference-of-squares/difference-of-squares.jl", "max_stars_repo_name": "vladflore/exercism", "max_stars_repo_head_hexsha": "268ec683fdca16f7051340cfcac5326fb59d027d", "max_stars_repo_licenses": ["MIT"], "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/difference-of-squares/difference-of-squares.jl", "max_issues_repo_name": "vladflore/exercism", "max_issues_repo_head_hexsha": "268ec683fdca16f7051340cfcac5326fb59d027d", "max_issues_repo_licenses": ["MIT"], "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/difference-of-squares/difference-of-squares.jl", "max_forks_repo_name": "vladflore/exercism", "max_forks_repo_head_hexsha": "268ec683fdca16f7051340cfcac5326fb59d027d", "max_forks_repo_licenses": ["MIT"], "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": 83, "alphanum_fraction": 0.6798941799, "num_tokens": 123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9728307661011976, "lm_q2_score": 0.8740772466456689, "lm_q1q2_score": 0.8503292374859315}}
{"text": "using NewtonsMethod\nusing Test\nusing LinearAlgebra\n\n@testset \"NewtonTests\" begin\n\n# Testing first function\n\ng(x)=(x-1)^2\ng\u2032(x)=2*(x-1)\n@test newtonroot(g,g\u2032;x\u2080=2) \u2248 1.0 atol=1E-4\n@test newtonroot(g;x\u2080=2)  \u2248 1.0 atol=1E-4\n\n#Testing second function\n\nh(x)=exp(x)-1\nh\u2032(x)=exp(x)\n@test newtonroot(h,h\u2032;x\u2080=3) \u2248 0.0 atol=1E-4\n@test newtonroot(h;x\u2080=3) \u2248 0.0  atol=1E-4\n\n#Testing function without convergence\n\nj(x)=x^2+2\nj\u2032(x)=2*x\n\n@test newtonroot(j,j\u2032;x\u2080=1) == nothing\n@test newtonroot(j;x\u2080=1) == nothing\n\n#Testing maxiter\n\n@test newtonroot(h,h\u2032;x\u2080=3,maxiter=5) == nothing\n\n#Testing tolerance\n#From above\n@test newtonroot(h,h\u2032;x\u2080=3,tol=1E10) == 3\n\n#From below\nroot1=newtonroot(g,g\u2032;x\u2080=3,tol=1E-6)\nroot2=newtonroot(g,g\u2032;x\u2080=3)\n@test norm(root1-1)>norm(root2-1)\n\n#Testing BigFloat\n\n@test newtonroot(h,h\u2032;x\u2080=BigFloat(3),tol=BigFloat(1E-7),maxiter=BigFloat(1000)) \u2248 0.0 atol=1E-4\n\nl(x)=log(x)\n\n@test_broken newtonroot(l;x\u2080=3) \u2248 1.0 atol=1E-4\n\nend\n", "meta": {"hexsha": "14378acbb0841535a45bdf20c336f0615da0008c", "size": 935, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "Amphibianoid/NewtonsMethod.jl", "max_stars_repo_head_hexsha": "a0e5f059b24446c46f7251ecc610ffa0911d917f", "max_stars_repo_licenses": ["MIT"], "max_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": "Amphibianoid/NewtonsMethod.jl", "max_issues_repo_head_hexsha": "a0e5f059b24446c46f7251ecc610ffa0911d917f", "max_issues_repo_licenses": ["MIT"], "max_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": "Amphibianoid/NewtonsMethod.jl", "max_forks_repo_head_hexsha": "a0e5f059b24446c46f7251ecc610ffa0911d917f", "max_forks_repo_licenses": ["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": 95, "alphanum_fraction": 0.6855614973, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632288833653, "lm_q2_score": 0.8933094152856197, "lm_q1q2_score": 0.850308384425681}}
{"text": "acknowledge help from Tommy Hofmann\n\n\n****************************\nlinearcode.jl\n****************************\ninclude(\"linearcode.jl\");\n\n# To create a linear code, need to make generator matrix. We start by creating a field for this.\nF, _ = FiniteField(2, 1, \"\u03b1\");\n# one may either create a matrix space and then embedd the matrix into it as in\nM = MatrixSpace(F, 4, 7);\nG = M([1 0 0 0 0 1 1;\n       0 1 0 0 1 0 1;\n       0 0 1 0 1 1 0;\n       0 0 0 1 1 1 1]);\n# or use either of the two shorthand notations\nG2 = matrix(F, [1 0 0 0 0 1 1;\n       0 1 0 0 1 0 1;\n       0 0 1 0 1 1 0;\n       0 0 0 1 1 1 1]);\nG3 = matrix(F, 4, 7, [1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1]);\nG == G2\nG == G3\n\n# This is the generator matrix for the [7, 4, 3] binary Hamming code in standard form\nC = LinearCode(G)\n# We can get the basic information\nlength(C)\ndimension(C)\ncardinality(C)\nrate(C)\n# since we gave it a full rank matrix, the rank should equal the dimension\nrank(G) == dimension(C)\n# no minimum distance calculations were performed so the object so far does not know\n# this value and the current state of the variable is set to 'missing'\n# functions which rely on this value will report an error in this case\nminimumdistance(C)\nrelativedistance(C)\ngenus(C)\n# since we know the minimum distance of this code is 3, we can go ahead and set that\n# no checking is done to verify the user's input\n# since setting the minimum distance is a desirable thing to be able to do, all code\n# objects are mutable (and hence live on the heap)\nsetminimumdistance!(C, 3)\nminimumdistance(C)\nrelativedistance(C)\ngenus(C)\nisMDS(C)\nnumbercorrectableerrors(C)\n# can check the generator and parity check matrices and check their defining properties\nGC = generatormatrix(C)\nG == GC\nH = paritycheckmatrix(C)\niszero(G * H')\niszero(H * G')\n# if G is full rank, the matrix is stored directly as the generator matrix of C as written\n# and H is computed as the right kernel of G\n# the standard form of G and H may be retrieved by passing true into the optional parameter\nGstand = generatormatrix(C, true)\nHstand = paritycheckmatrix(C, true)\n# G in the example was already in standard form, so we can check the computations\nGstand == GC\nHstand == H\n# finally, we may compute the dual\n# in order to save computational time, this command merely flipps the roles of G and H\n# in the LinearCode constructor, and no new computation is done\ndual(C)\n\n# a vector v is in the code C if it has zero syndrome\nr = generatormatrix(C)[1, :]\niszero(syndrome(r, C))\n# a code C1 is a subset of C2 if every row of the generator matrix of C1 is in C2\nC \u2286 C\nC \u2286 dual(C)\nissubcode(C, dual(C))\n# two codes C1 and C2 are equivalent if C1 \u2286 C2 and C2 \u2286 C1\nisequivalent(C, dual(C))\n# a code is self dual if it is equivalent to its dual\nisselfdual(C)\n# code is self orthogonal if it is a subcode of its dual\nisselforthogonal(C)\n\n# finally, one may encode a length k vector by C using\nencode(C.G[:, 1], C)\n# here the vector to be encoded is an element of MatrixSpace(Nemo.GF(2), 4, 1)\n# allowing for proper matrix multiplication between it and the generator matrix\n# one may also pass in a Vector{Int64} of the proper length and the appropriate\n# matrix space will automatically be created. this may be slow if this is done\n# repeatedly as this object will be built from scratch each time. the same is\n# true for syndrome(). either a (1, C.k) or a (C.k, 1) dimensional vector may\n# be used as the code will automatically apply the transpose if necessary\n# it will not however accept objects of type adjoint such as v'\ngeneratormatrix(C)[:, 1]\nv = [1, 0, 0, 0];\nencode(v, C)\nv2 = [1; 0; 0; 0];\nencode(v2, C)\ngeneratormatrix(C)[1, :]\nv = [1, 0, 0, 0, 0, 1, 1];\nsyndrome(v, C)\nv = [1; 0; 0; 0; 0; 1; 1];\nsyndrome(v, C)\n# might want to remove these transpose examples and remove from code since these have same size\n\n# need examples, not full rank\n# passing in H\n# passing in G and H directly\n\n# we can preform several standard methods of building new codes from old ones\n# direct sum\nD = C \u2295 C;\ngeneratormatrix(D)\nD = directsum(C, C);\ngeneratormatrix(D)\n# direct product\nD = C \u2297 C;\ngeneratormatrix(D)\nD = directproduct(C, C);\ngeneratormatrix(D)\nD = tensorproduct(C, C);\ngeneratormatrix(D)\n# the most common form of extending a code is to add parity check column to right of generator matrix\nD = extend(C);\nlength(D)\ngeneratormatrix(D)\nF3, _ = FiniteField(3, 1, \"\u03b1\");\n# M2 = MatrixSpace(Nemo.GF(3), 2, 4); #- ex page 15\nG2 = matrix(F3, [1 0 1 1; 0 1 1 -1]);\nC2 = LinearCode(G2);\ngeneratormatrix(extend(C2))\nparitycheckmatrix(extend(C2))\noriginalgeneratormatrix(C2) == G2\n# in cases such as this it is often useful to keep track of the original generator matrix which\n# was used to generate the code. can also do this for the parity check matrix. in cases where this\n# does not make sense, the normal generator or parity check matrix is returned\noriginalgeneratormatrix(D)\noriginalgeneratormatrix(D) == generatormatrix(D)[:, 1:end-1]\nparitycheckmatrix(D)\noriginalparitycheckmatrix(D)\n# puncturing deletes columns from a generator matrix\nC2 = puncture(D, [length(D)]);\nisequivalent(C, C2)\ngeneratormatrix(C) == generatormatrix(C2)\noriginalgeneratormatrix(C2) == generatormatrix(C)\n# to expurgate a code is to delete rows from generator matrix and then remove any potentially resulting zero columns\nD = expurgate(C, [dimension(C)]);\nlength(D)\ndimension(D)\ngeneratormatrix(D)\noriginalgeneratormatrix(D) == generatormatrix(C)\n# to augment is to add rows to the generator matrix\n# in this example we are going to first add the all 1's vector to the code, which is common\n# we note that the all 1's vector is actually already in the code so the code\n# shouldn't change\n# M = MatrixSpace(Nemo.GF(2), 1, 7);\nv = matrix(F, [1 for i in 1:7]')\nv \u2208 C\nD = augment(C, v);\ngeneratormatrix(D) == generatormatrix(C)\nv = matrix(F, [1 0 1 0 1 1 1])\nv \u2208 C\nD = augment(C, v);\ngeneratormatrix(D)\noriginalgeneratormatrix(D) == generatormatrix(C)\n# to shorten is to expurgate then puncture\nD = shorten(C, [length(C)]);\ngeneratormatrix(D)\noriginalgeneratormatrix(D) == generatormatrix(C)\n# M2 = MatrixSpace(Nemo.GF(2), 3, 6);\nG2 = matrix(F, [1 0 0 1 1 1; 0 1 0 1 1 1; 0 0 1 1 1 1]);\nC2 = LinearCode(G2);\ngeneratormatrix(shorten(C2, [5, 6]))\n# the most common form of lengthening a code it to augment the all 1's vector and then extend\nD = lengthen(C);\ngeneratormatrix(D)\noriginalgeneratormatrix(D) == generatormatrix(C)\n# the (u | u + v)- or Plotkin construction\n# M2 = MatrixSpace(Nemo.GF(2), 3, 4);\n# M3 = MatrixSpace(Nemo.GF(2), 1, 4);\nG2 = matrix(F, [1 0 1 0; 0 1 0 1; 0 0 1 1]);\nG3 = matrix(F, [1 1 1 1]);\nC2 = LinearCode(G2);\nC3 = LinearCode(G3);\ngeneratormatrix(uuplusv(C2, C3)) #- ex p. 19\n\nSingletonBound\n\n\n****************************\ncyclotomic.jl\n****************************\ninclude(\"cyclotomic.jl\")\n\n# ord_n(q)\nq = 2;\nn = 15;\nb = 3;\n\u03b4 = 4;\nord(n, q)\n# at the moment this comes back sorted so one can easily record a coset representative\ncoset = cyclotomiccoset(3, q, n, false)\ncyclotomiccoset(3, q, n, true)\nallcyclotomiccosets(q, n, true)\ndualqcosets(q, n, [coset])\ncomplementqcosets(q, n, [coset])\n# pairings\nqcosetpairings(q, n)\n# find all in a range\nqcosettable(10, 13, q)\n\n\n****************************\ncycliccode.jl\n****************************\ninclude(\"cycliccode.jl\")\nq = 2;\nn = 15;\nb = 3;\n\u03b4 = 4;\ncosets = definingset([i for i = b:(b + \u03b4 - 2)], q, n, false)\nC = CyclicCode(q, n, cosets)\nbasefield(C)\nsplittingfield(C)\npolynomialring(C)\nprimitiveroot(C)\noffset(C)\ndesigndistance(C)\nqcosets(C)\nqcosetsreps(C)\ndefiningset(C)\ngeneratorpolynomial(C)\nparitycheckpolynomial(C)\nidempotent(C)\n# CyclicCode is a subtype of LinearCode so the functions of the previous section also apply here\noriginalgeneratormatrix(C)\nG = matrix(F, [1 0 0 0 0 1 1;\n       0 1 0 0 1 0 1;\n       0 0 1 0 1 1 0;\n       0 0 0 1 1 1 1]);\nD = LinearCode(G);\nCD = directsum(C, D);\ngeneratormatrix(CD)\n# the generator matrix of a cyclic code is kept in cyclic form but the standard form is of course always available\ngeneratormatrix(C)\ngeneratormatrix(C, true)\n# note how the previous code auto detected that it was a BCH code and returned an object of type BCHCode\ncomplement(C)\n# the above is equivalent to\nB = BCHCode(q, n, \u03b4, b)\nC == B\n# the optional offset parameter is set to 0 by default\nBCHCode(q, n, \u03b4)\n# for cyclic codes, we can\nC \u2229 B == C\nB = BCHCode(q, n, \u03b4 - 1, b + 4)\nD = C \u2229 B # check later that this is == repetition code\nC + B\n\n# Reed Solomon codes are BCH codes with n = q^m - 1\n# this forces the cyclotomic cosets to each have size one\nq = 16;\nn = 15;\nb = 3;\n\u03b4 = 4;\nallcyclotomiccosets(q, n, true)\n# as with BCH codes, it will auto detect whether or not the code is Reed Solomon and call the appropriate constructor\ncosets = definingset([i for i = b:(b + \u03b4 - 2)], q, n, false);\nCyclicCode(q, n, cosets)\nBCHCode(q, n, \u03b4, b)\n\n############## this doesn't work\nReedSolomonCode(q, \u03b4, b)\n\ncome up with better examples from the book but basis functionality is working so far and interaction with LinearCode is good\nfix C \u2229 complement(C) example where defining set is an extreme (Vector{Any} so probably empty)\n2nd form of CyclicCode constructor\n\n\n****************************\nReedMuller.jl\n****************************\ninclude(\"ReedMuller.jl\")\n\n# so far only binary implemented\n# fields are created via F, _ = FiniteField(2, 1, \"\u03b1\") by default\n# codes are created using the recursive form of the generator matrix\nq = 2;\nReedMullergeneratormatrix(q, 0, 3)\nReedMullergeneratormatrix(q, 2, 2)\nReedMullerCode(q, 1, 2)\nC = ReedMullerCode(q, 1, 3)\nReedMullerCode(q, 2, 3)\nisselfdual(C)\n", "meta": {"hexsha": "95aacbc78069555ab59502a572fb5815660e01f8", "size": 9624, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testcases.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": "test/testcases.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": "test/testcases.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": 32.6237288136, "max_line_length": 124, "alphanum_fraction": 0.6936824605, "num_tokens": 3133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632329799586, "lm_q2_score": 0.8933094081846421, "lm_q1q2_score": 0.8503083813260469}}
{"text": "# Example driver for the geometric multigrid program, GMG.jl, to solve a Poisson equation on a 2D grid using \r\n#  second order finite difference method.\r\n#  Dirichlet Boundary conditions\r\n\r\n\r\ninclude(\"GMG.jl\")\r\nusing .GMG: V_cycle!\r\nusing Formatting: printfmt\r\n\r\n# Define the problem being solved. It is on a 1x1 square domain with \r\n# homogeneous dirichlet boundary conditions\r\nfunction U_exact(x,y)\r\n  return (x^3-x)*(y^3-y)\r\nend\r\n\r\nfunction source(x,y)\r\n  return 6*x*y*(x^2 + y^2 -2)\r\nend\r\n\r\nmax_cycles = 10              # max number of V cycles to execute\r\nnlevels    = 10              # number of grid levels. 1 means no multigrid, 2 means one coarse grid. etc \r\nnx         = 1*2^(nlevels-1) # Nx and Ny are given as function of grid levels\r\nny         = 1*2^(nlevels-1) #\r\n\r\nconst u_ex = zeros(Float64,(nx+2,ny+2))\r\nconst u = zeros(Float64,(nx+2,ny+2))\r\nconst f = zeros(Float64,(nx+2,ny+2))\r\nconst res = zeros(Float64,(nx+2,ny+2))\r\nconst error = zeros(Float64,(nx,ny))\r\n\r\n#calcualte the RHS and exact solution\r\nDX=1.0/nx\r\nDY=1.0/ny\r\nxc=range(0.5*DX,1-0.5*DX,length=nx)\r\nyc=range(0.5*DY,1-0.5*DY,length=ny)\r\n\r\n#set the exact solution and the source term corresponding to it\r\nfor i= 1:nx, j=1:ny;\r\n  u_ex[i+1,j+1] = U_exact(xc[i],yc[j])\r\n  f[i+1,j+1]    = source(xc[i],yc[j])\r\nend\r\n\r\nprintln(\"-------------------------New Run------------------------------\")\r\nprintln(\"           Poisson equation on $(nx)X$(ny) grid\")\r\n\r\nfor it=1:max_cycles\r\n\r\n  u[:,:],res[:,:]=V_cycle!(nx,ny,nlevels,u,f,1)\r\n\r\n  error[:,:]=u_ex[2:nx+1,2:ny+1]-u[2:nx+1,2:ny+1]\r\n\r\n  printfmt( \"|V cycle: {:2d}| res. norm: {:16.9e}| error norm: {:16.9e}|\\n\", it,findmax(abs.(res))[1],findmax(abs.(error))[1] )\r\nend\r\n", "meta": {"hexsha": "7565dda9b02b6fbb6616c6c52e545704fe034c87", "size": 1686, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example_2d.jl", "max_stars_repo_name": "AbhilashReddyM/Multigrid-in-Julia", "max_stars_repo_head_hexsha": "c88751eb47b1190103c5c4ba4a16eb3c9a410701", "max_stars_repo_licenses": ["MIT"], "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_2d.jl", "max_issues_repo_name": "AbhilashReddyM/Multigrid-in-Julia", "max_issues_repo_head_hexsha": "c88751eb47b1190103c5c4ba4a16eb3c9a410701", "max_issues_repo_licenses": ["MIT"], "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_2d.jl", "max_forks_repo_name": "AbhilashReddyM/Multigrid-in-Julia", "max_forks_repo_head_hexsha": "c88751eb47b1190103c5c4ba4a16eb3c9a410701", "max_forks_repo_licenses": ["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.2222222222, "max_line_length": 128, "alphanum_fraction": 0.6103202847, "num_tokens": 570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632247867715, "lm_q2_score": 0.8933093968230773, "lm_q1q2_score": 0.8503083631923402}}
{"text": "## integration.jl\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, 1000, 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 -> (lr -> begin l,r = lr; f(r) * (r-l) end)\n    elseif method == \"left\"\n        meth = f -> (lr -> begin l,r = lr; f(l) * (r-l) end)\n    elseif method == \"trapezoid\"\n        meth = f -> (lr -> begin l,r = lr; (1/2) * (f(l) + f(r)) * (r-l) end)\n    elseif method == \"simpsons\"\n        meth = f -> (lr -> begin l,r=lr; (1/6) * (f(l) + 4*(f((l+r)/2)) + f(r)) * (r-l) end)\n    end\n\n    xs = a .+ (0:n) * (b-a)/n\n\n    sum(meth(f), zip(xs[1:end-1], xs[2:end]))\nend\n\n#######\n## simplified multivariable integrals\n\n# limits of integration\nendpoints(ys,x) = ((f,x) -> isa(f, Function) ? f(x...) : f).(ys, Ref(x))\n# avoid specialization in quadgk\nstruct FWrapper\n    f\nend\n(F::FWrapper)(x) = F.f(x)\n\n\"\"\"\nfubini(f, dy, dx)\nfubini(f, dz, dy, dx)\n\nComputes numeric integral of `f` over region specified by `dz`, `dy`, `dx`. These are a tuple of values of numbers or univariate functions depending on the value of the term on the right (`dy` can depend on `dx`s value).\n\n\n*Much* slower than `hcubature` from the `HCubature` package, as it refines flat areas too many times, allocates too much, etc. But does allow a more flexible specification of the region to integrate over, as `hcubature` requires box-like regions.\n\n```\nf(x,y,z) = x * y^2 * z^3\nfubini(f, (0,1), (0,2), (0,3))  # int_0^3 int_0^2 int_0^1 f(x,y,z) dz dy dx\ng(v) = f(v...)\nhcubature(g, (0,0,0), (3,2,1))  # same. Not order switched\n\n# triangular like region\nfubini(f, (0, y->y), (0, x->x), (0,3))\n```\n\"\"\"\nfubini(f, dx)     = quadgk(FWrapper(f), dx...)[1]\nfubini(f, ys, xs) = fubini(x -> fubini(y -> f(x,y), endpoints(ys, x)), xs)\nfubini(f, zs, ys, xs) = fubini(x ->\n    fubini(y ->\n        fubini(z -> f(x,y,z),\n            endpoints(zs, (x,y))),\n        endpoints(ys,x)),\n    xs)\n", "meta": {"hexsha": "8b09c857206ce68ad0589fae790cffb0def7c14a", "size": 2268, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/integration.jl", "max_stars_repo_name": "BryceStevenWilley/CalculusWithJulia.jl", "max_stars_repo_head_hexsha": "801773a3651b2e8f03a8e6eb2f427ab1527e3844", "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/integration.jl", "max_issues_repo_name": "BryceStevenWilley/CalculusWithJulia.jl", "max_issues_repo_head_hexsha": "801773a3651b2e8f03a8e6eb2f427ab1527e3844", "max_issues_repo_licenses": ["MIT"], "max_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": "BryceStevenWilley/CalculusWithJulia.jl", "max_forks_repo_head_hexsha": "801773a3651b2e8f03a8e6eb2f427ab1527e3844", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-17T02:26:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-17T02:26:35.000Z", "avg_line_length": 31.9436619718, "max_line_length": 246, "alphanum_fraction": 0.5850970018, "num_tokens": 820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811611608241, "lm_q2_score": 0.880797071719777, "lm_q1q2_score": 0.8503048998438919}}
{"text": "# Exercise 1\n#various rules for differentiation\n\n\nstruct DualNumber{T} <: Real\n    val::T\n    \u03f5::T\nend\nimport Base: +, *, -, ^, /, exp\n+(x::DualNumber, y::DualNumber) = DualNumber(x.val + y.val, x.\u03f5 + y.\u03f5)  # dual addition\n+(x::DualNumber, a::Number) = DualNumber(x.val + a, x.\u03f5)  # i.e. scalar addition, not dual\n+(a::Number, x::DualNumber) = DualNumber(x.val + a, x.\u03f5)  # i.e. scalar addition, not dual\n-(x::DualNumber, y::DualNumber) = DualNumber(x.val - y.val, x.\u03f5 - y.\u03f5)  # dual subtraction\n-(x::DualNumber, a::Number) = DualNumber(x.val - a, x.\u03f5)  # i.e. scalar subtraction, not dual\n-(a::Number, x::DualNumber) = DualNumber(x.val - a, x.\u03f5)  # i.e. scalar subtraction, not dual\n/(x::DualNumber, y::DualNumber) = DualNumber(x.val/y.val, (y.val*x.\u03f5 - x.val*y.\u03f5)/y.val^2) #dual quotient rule\n*(x::DualNumber, y::DualNumber) = DualNumber(x.val*y.val, x.val*y.\u03f5 + y.val*x.\u03f5 ) #dual product rule\n*(x::DualNumber, a::Number) = DualNumber(a*x.val, a*x.\u03f5 ) #scalar multiplicaiton\n^(a::Number, x::DualNumber) = DualNumber(x.val^a, a*x.val^(a-1)*x.\u03f5)\n\n\n\nf(x) = x^2.0\n\nx = DualNumber(1.0, 1.0)  # x -> 2.0 + 1.0\\epsilon\ny = DualNumber(3.0, 1.0)  # i.e. y = 3.0, no derivative\n\n\n# seeded calculates both the function and the d/dx gradient!\nf(x)\n", "meta": {"hexsha": "7a9a8b05d0a7739397af2636cdfe6a6ae7caf8a3", "size": 1238, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Packages_SolversOptimisers.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_SolversOptimisers.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_SolversOptimisers.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": 39.935483871, "max_line_length": 110, "alphanum_fraction": 0.6357027464, "num_tokens": 481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133447766224, "lm_q2_score": 0.9046505318875316, "lm_q1q2_score": 0.8502931072803603}}
{"text": "using NumericalMethodsforEngineers\n\na = [16. 4. 8.; 4. 5. -4.; 8. -4. 22.]\nb = [4., 2., 5.]\n\nf = cholesky(a)\nf |> display\n\ny = f.L \\ b\nc = f.U \\ y\nprintln(\"Solution Vector: \\n $c\")\n\n@test c == a \\ b\n\na = [16. 4. 8.; 4. 5. -4.; 8. -4. 22.]\nb = [4., 2., 5.]\n\na[2, 2] += 1.0e20\nb[2] = a[2, 2] * 5.0\n\nF = cholesky(a)\nupper = Matrix(sparse(F.U))\nupper |> display\n\nlower = F.L\nlower |> display\n\ny = lower \\ b\nc = upper \\ y\nprintln(\"Solution Vector: \\n $c\")\n\n@test \u2248(c, a \\ b, atol=1e-5)", "meta": {"hexsha": "db747ca8cf9ac64591338529f4fd6537016eda33", "size": 480, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ch02/j-02-07.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/j-02-07.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/j-02-07.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": 15.0, "max_line_length": 38, "alphanum_fraction": 0.5145833333, "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341975270265, "lm_q2_score": 0.8887587890727754, "lm_q1q2_score": 0.8502170509797263}}
{"text": "\"\"\"   \nReturns the Finite Impulse Response of a Raised Cosine (RC) filter.\tThe filter is defined by its span (evaluated in number of symbol N), its Roll-Off factor and its oversampling factor. The span corresponds to the number of symbol affected by filter before and after the center point.\\n\nOutput is a Vector{Float64} array of size L= 2KN+1 \\n\nSRRC definition is based on [1]\t \\n\n[1]\t 3GPP TS 25.104 V6.8.0 (2004-12). http://www.3gpp.org/ftp/Specs/archive/25_series/25.104/25104-680.zip \\n\n Syntax \\n\n\t\th\t= raisedCosine(N,beta,ovS)\nInput parameters \\n\n- N\t  : Symbol span (Int16)\n- beta  : Roll-off factor (Float64)\n- ovS\t  : Oversampling rate (Int16)\n\"\"\"\nfunction raisedCosine(N,beta,ovS)\n\t# --- Final size of filter\n\tnbTaps\t= 2 * N * ovS + 1;\n\t# --- Init output\n\th\t\t\t= zeros(Float64,nbTaps);\n\tcounter\t\t= 0;\n\t# --- Iterative SRRC definition\n\tfor k = -N*ovS : 1 : N*ovS\n\t\tcounter\t\t = counter + 1;\n\t\tif k == 0\n\t\t\t## First singular point at t=0\n\t\t\th[counter]  = 1;#(1-beta) + 3*beta/pi;\n\t\telseif abs(k) == ovS / (2*beta);\n\t\t\t## Second possible singular point\n\t\t\th[counter]  = pi/4*sin(pi/(2beta))/(pi/(2beta));\n\t\telse\n\t\t\t## Classic SRRC formulation (see [1])\n\t\t\th[counter]\t= sin(pi*k/ovS)/(pi*k/ovS) * cos(pi*beta*k/ovS)/(1- 4beta^2*(k/ovS)^2);\n\t\tend\n\tend\n\treturn h\nend\n\n\n\"\"\"\nReturns the Finite Impulse Response of a Square Root Raised Cosine (SRRC) filter. \\n\nThe filter is defined by its span (evaluated in number of symbol N), its Roll-Off factor and its oversampling factor. The span corresponds to the number of symbol affected by filter before and after the center point.\\n\nOutput is a Vector{Float64} array of size L= 2KN+1\\n\nSRRC definition is based on [1]\\n\n[1]\t 3GPP TS 25.104 V6.8.0 (2004-12). http://www.3gpp.org/ftp/ Specs/archive/25_series/25.104/25104-680.zip\\n\nSyntax\\n\nh\t= sqrtRaisedCosine(N,beta,ovS) \\n\nInput parameters \\n\n- N\t  : Symbol span (Int16)\n- beta  : Roll-off factor (Float64)\n- ovS\t  : Oversampling rate (Int16)\n\"\"\"\nfunction sqrtRaisedCosine(N,beta,ovS)\n\t# --- Final size of filter\n\tnbTaps\t= 2 * N * ovS + 1;\n\t# --- Init output\n\th\t\t\t= zeros(Float64,nbTaps);\n\tcounter\t\t= 0;\n\t# --- Iterative SRRC definition\n\tfor k = -N*ovS : 1 : N*ovS\n\t\tcounter\t\t = counter + 1;\n\t\tif k == 0\n\t\t\t## First singular point at t=0\n\t\t\th[counter]  = (1-beta) + 4*beta/pi;\n\t\telseif abs(k) == ovS / (4*beta);\n\t\t\t## Second possible singular point\n\t\t\th[counter]  = beta/sqrt(2)*( (1+2/pi)sin(pi/(4beta))+(1-2/pi)cos(pi/(4beta)));\n\t\telse\n\t\t\t## Classic SRRC formulation (see [1])\n\t\t\th[counter]  = ( sin(pi*k/ovS*(1-beta)) + 4beta*k/ovS*cos(pi*k/ovS*(1+beta))) / (pi*k/ovS*(1- (4beta*k/ovS)^2) );\n\t\tend\n\tend\n    # --- Max @ h[0]\n    h   = h ./ maximum(h)\n\treturn h\nend\n", "meta": {"hexsha": "76474b47c3e711e33085267ae799c70acd4f60dc", "size": 2668, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/raisedCosine.jl", "max_stars_repo_name": "JuliaTelecom/DigitalComm.jl", "max_stars_repo_head_hexsha": "13c854b9c4a8864787075e06e0e3ef5a1d30beae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-03-24T16:21:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T21:33:36.000Z", "max_issues_repo_path": "src/raisedCosine.jl", "max_issues_repo_name": "JuliaTelecom/DigitalComm.jl", "max_issues_repo_head_hexsha": "13c854b9c4a8864787075e06e0e3ef5a1d30beae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-11-10T22:27:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-24T09:12:27.000Z", "max_forks_repo_path": "src/raisedCosine.jl", "max_forks_repo_name": "JuliaTelecom/DigitalComm.jl", "max_forks_repo_head_hexsha": "13c854b9c4a8864787075e06e0e3ef5a1d30beae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-13T03:59:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-13T03:59:29.000Z", "avg_line_length": 36.0540540541, "max_line_length": 286, "alphanum_fraction": 0.6525487256, "num_tokens": 960, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750387190131, "lm_q2_score": 0.8918110368115781, "lm_q1q2_score": 0.8501412006466004}}
{"text": "using Printf\nusing LinearAlgebra\nusing DelimitedFiles\nusing Quaternions\n\n#EXERCISE MADE BY ERIK MART\u00cdN GARZ\u00d3N & DAVID BOCES OBIS\n#-------------------------------------------------------------------- EXERCISE 2.2\n\nV3 = [0; 0; 1] #vector of R3 we want to project in R2\n\nfunction to_2d(V3)\n    #we calculate de matrix (see the first exercise)\n\n    a = 0.5*cosd(42)\n    b = 0.5*sind(42)\n    c = cosd(7)\n    d = sind(7)\n    e = 0\n    f = 1\n\n    M = [-a c e;\n        -b -d f]\n     #matrix found in the first exercise\n\n    V2 = M*V3 #operation to transform V3 of R3 in V2 in R2\n\n    # println(\"The vector \", V3, \" representated in R2 is: \", V2)\n    # println()\n\n    return V2\nend\n\n#-------------------------------------------------------------------- EXERCISE 2.3\nfunction rotate_phi_z(phi, z, V)\n\n    global z_norm\n    global z_module\n\n    z_module = sqrt(z[1]*z[1]+z[2]*z[2]+z[3]*z[3])\n\n    z_norm = z/z_module\n\n    Z = [0.0 -z_norm[3] z_norm[2];\n         z_norm[3] 0.0 -z_norm[1];\n        -z_norm[2] z_norm[1] 0.0]\n\n    #formula de Rodriges to find \"R\", the rotation matrix\n    R = I + sind(phi)*Z + (1-cosd(phi))*(Z^2)\n    #just above, we multiply pi/180 to the angle (in degrees) to obtain the angle in radians\n    #so julia can do the operation we want\n\n    #next, we will check if R is a rotation matrix: R*R'=I and det(R)=1\n    #For this comprobation, we needed to round R*R' and det(R). That's because much times\n    #the result was 0.999999 and not 1\n    if(phi==0)\n        return V\n    end\n    if (z != [0.0;0.0;0.0])\n        if (round.(R*R') == I && round(det(R)) == 1)\n            #we find the rotated matrix:\n            U = R*V\n            # print(\"V rotated is = \", U)\n            # println()\n            return U\n        else\n\n            print(\"R = \", R, \"\\nis NOT a rotation matrix\\n\")\n            println(\"R*R'= \", round.(R*R'))\n            println(\"det(R)= \", round(det(R)))\n\n        end\n    else\n\n            return [0.0 0.0 0.0; 0.0 0.0 0.0;0.0 0.0 0.0]\n    end\nend\n\n#-------------------------------------------------------------------- EXERCISE 3.1\nglobal axis_norm\n\nfunction axis_angle_to_mat(axis, angle)\n    #first, we normalize the axis\n    modul = sqrt(axis[1]*axis[1] + axis[2]*axis[2] + axis[3]*axis[3])\n\n    global axis_norm\n\n    round(modul)\n\n    if (modul == 0)\n        return [1.0 0.0 0.0; 0.0 1.0 0.0; 0.0 0.0 1.0]\n    else\n        axis_norm = axis/modul\n\n        Z = [0 -axis_norm[3] axis_norm[2];\n             axis_norm[3] 0 -axis_norm[1];\n            -axis_norm[2] axis_norm[1] 0]\n\n        #formula Rodrigues\n        R = I + sind(angle)*Z + (1-cosd(angle))*(Z^2)\n        #just above, we multiply pi/180 to the angle (in degrees) to obtain the angle in radians\n        #so julia can do the operation we want\n\n        #next, we will check if R is a rotation matrix: R*R'=I and det(R)=1\n        #For this comprobation, we needed to round R*R' and det(R). That's because much times\n        #the result was 0.999999 and not 1\n        if (round.(R*R')== I && round(det(R))==1)\n            #we return the rotation matrix\n            return R\n        else\n            print(\"R = \", R, \"\\nis NOT a rotation matrix\\n\")\n            println(\"R*R'= \", round.(R*R'))\n            println(\"det(R)= \", round(det(R)))\n        end\n    end\nend\n\nfunction mat_to_axis_angle(mat)\n    #first, we find the angle:\n    angle = acosd((tr(mat)-1)/2)\n\n    #then, we find the axis:\n    V = (mat-mat')/(2*sind(angle))\n    v = [V[3,2]; V[1,3]; V[2,1]]\n\n    #we return the angle in degrees\n    return angle, v\nend\n\nfunction axis_angle_to_quat(axis, angle)\n    global q2\n    #first, we normalize the axis\n    modul = sqrt(axis[1]*axis[1] + axis[2]*axis[2] + axis[3]*axis[3])\n\n# if (modul==0)\n#         print(\"\\n QUATERNION MODULE IS 0\")\n#         return 0\n#     else\n        global axis_norm = axis/modul\n\n        q2 = quat(cosd(angle/2), sind(angle/2)*axis_norm[1], sind(angle/2)*axis_norm[2], sind(angle/2)*axis_norm[3])\n\n        return q2\n    # end\nend\n\nfunction quat_to_axis_angle(q3)\n\n    norm = sqrt(q3.s*q3.s + q3.v1*q3.v1 + q3.v2*q3.v2 + q3.v3*q3.v3)\n\n\n    global axis_norm = [0.0;0.0;0.0]\n\n    if(norm == 0)\n        angle3 = 0\n\n        axis_norm[1] = 0\n        axis_norm[2] = 0\n        axis_norm[3] = 0\n\n    else\n        angle3 = 2*acosd(q3.s/norm)\n    end\n    if (angle3==0)\n        # println(\"Angle of the quaternion = 0  Returning 0 axis\")\n        return angle3, axis_norm\n    else\n        axis_norm[1] = (q3.v1/norm)/sind(angle3/2)\n        axis_norm[2] = (q3.v2/norm)/sind(angle3/2)\n        axis_norm[3] = (q3.v3/norm)/sind(angle3/2)\n    end\n    return angle3, axis_norm\nend\n\nfunction quat_to_mat(q)\n    global matQuat = [((q.s)^2 + (q.v1)^2 - (q.v2)^2 - (q.v3)^2) (2*(q.v1)*(q.v2) - 2*(q.s)*(q.v3)) (2*(q.v1)*(q.v3) + 2*(q.s)*(q.v2));\n            (2*(q.v1)*(q.v2) + 2*(q.s)*(q.v3)) ((q.s)^2 - (q.v1)^2 + (q.v2)^2 - (q.v3)^2) (2*(q.v2)*(q.v3) - 2*(q.s)*(q.v1));\n            (2*(q.v1)*(q.v3) - 2*(q.s)*(q.v2)) (2*(q.v2)*(q.v3) + 2*(q.s)*(q.v1)) ((q.s)^2 - (q.v1)^2 - (q.v2)^2 + (q.v3)^2)]\n\n    return matQuat\nend\n\nfunction mat_to_quat(mat)\n    #first, we find the angle:\n    angle2 = acosd((tr(mat)-1)/2)\n\n    if (angle2 != 0)\n        #then, we find the axis:\n        V = (mat-mat')/(2*sind(angle2))\n        v = [V[3,2]; V[1,3]; V[2,1]]\n\n        q3 = quat(cosd(angle2/2), sind(angle2/2)*v[1], sind(angle2/2)*v[2], sind(angle2/2)*v[3])\n\n        return q3\n    else\n        return \"THIS ROTATION MATRIX [IDENTITY MATRIX] HAS NO AXIS. ITS ROTATION ANGLE IS 0 + 360*K [BEING K AN ENTER]. FOR THE RESULT THIS MATRIX HAS NO QUATERNION FORM.\"\n    end\nend\n\n#-------------------------------------------------------------------- EXERCISE 4.3\nfunction scale_and_translation(v3d, scale, point)\n\n# println(\"V3D \", v3d)\n\n    v3d = v3d*scale\n\n    # println(\"V3D SCALED \", v3d)\n\n    #movement = [0.0;0.0]\n    v3dResult = [0.0;0.0;0.0]\n\n    # movement[1] = point[1] - v2d[1]\n    # movement[2] = point[2] - v2d[2]\n\n    v3dResult[1] = v3d[1] + point[1]\n    v3dResult[2] = v3d[2] + point[2]\n    v3dResult[3] = v3d[3] + point[3]\n\n    return v3dResult\n\nend\n", "meta": {"hexsha": "5fb9adb644eacd218ca31722cd62dd35ec419cb6", "size": 6043, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "proj2.jl", "max_stars_repo_name": "VoZeS/proyecto_rotaciones-mathII", "max_stars_repo_head_hexsha": "c25af16fa005910a91773d1c22a27eb04765ea5e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "proj2.jl", "max_issues_repo_name": "VoZeS/proyecto_rotaciones-mathII", "max_issues_repo_head_hexsha": "c25af16fa005910a91773d1c22a27eb04765ea5e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "proj2.jl", "max_forks_repo_name": "VoZeS/proyecto_rotaciones-mathII", "max_forks_repo_head_hexsha": "c25af16fa005910a91773d1c22a27eb04765ea5e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3438914027, "max_line_length": 171, "alphanum_fraction": 0.5247393679, "num_tokens": 2146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067195846918, "lm_q2_score": 0.9019206752113866, "lm_q1q2_score": 0.8500662969190943}}
