{"text": "module EngEconomics\n\nusing Dates\n\nexport simpleInterest, findFractionalPeriod\n\n# Simple Interest (F = P(1 + i x n))\n# F = Future amount\n# P = Principal amount\n# i = simple interest rate\n# n = period of time\nfunction simpleInterest(P::Number, i::Number, n::Number)::Number\n\tF = P * (1 + i * n)\nend\n\n# Find Fraction Period (360 days a year, 12 months, 60 days)\nfunction findFractionalPeriod(date1::Date, date2::Date)::Number\n\tmonthDays = 30 * (Dates.month(date2) - Dates.month(date1))\n\td = Dates.day(date2) - Dates.day(date1) + 1\n\treturn (monthDays + d) / 360\nend\n\n\nexport learningCurveModel, learningCurveModelCoeff, learningCurvePercentage\nfunction learningCurveModel(T_init, N, b)\n\treturn T_init * N^b\nend\n\nfunction learningCurveModelCoeff(T1, N1, T2, N2)\n\tb = log(T1 / T2) / log(N1 / N2)\nend\n\nfunction learningCurvePercentage(b)\n\treturn exp(b * log(2))\nend\n\n\nexport compoundAmountFactor, presentWorthFactor\n# Compound Amount Factor: (F/P, i, N)\n# - gives future amount, F, that is equivalent to a present amount, P, when the\n# interest rate is i, and the number of periods is N\n# - How much money will be in the bank after 15 years if we invest 100 dollars\n# now at 8% interest compounded semi-annually\nfunction compoundAmountFactor(i, N)\n\t(1 + i)^N\nend\n\n# Present Worth Factor: (P/F, i, N)\n# - gives the present amount, P, that is equivalent to the future amount, F,\n# when the interest rate is i, and the number of periods is N\n# - How much should be invested now so that in 4 years we will have 1360.5\n# dollars in the bank if the interest rate is 8%\nfunction presentWorthFactor(i, N)\n\t1 / ((1 + i)^N)\nend\n\nexport sinkingFundFactor, uniformSeriesCompoundAmoundFactor\n# Sinking Fund Factor: (A/F, i, N)\n# - gives the size of A of a repeated receipt or disbursement that is equivalent\n# to a future amount F if the interest rate is i and the number of periods is\n# N\n# - If you want to accumulate 50,000 in 5 years, how much should we invest\n# yearly if the interest rate is 10%? F * (A/F,10%, 5)\nfunction sinkingFundFactor(i, N)\n\ti / ((1 + i)^N - 1)\nend\n\n# Uniform Series Compound Amount Factor: (F/A, i, N)\n# - gives the future value F that is equivalent to a series of equal size\n# receipts or disbursements of A when the interest rate is i and the number of\n# periods is N\n# - If you deposit $200 yearly for 45 years if the interest rate is 12% how much\n# will be in your savings account? 200 (A/F, 12%, 45)\nfunction uniformSeriesCompoundAmoundFactor(i, N)\n\t((1+i)^N - 1) / i\nend\n\nexport capitalRecoveryFactor, seriesPresentAmountFactor\n# Capital Recovery Factor: (A/P, i, N)\n# - gives the value of A of the equal periodic payments or receipts that are\n# equivalent to the present amount P when the interest is i and the number of\n# period is N\n# - how much should I pay per month to be equal to just paying $100 dollars now\n# for the thing?\nfunction capitalRecoveryFactor(i, N)\n\t(i * (1 + i)^N) / ((i+1)^N - 1)\nend\n\n# Series Present Worth Factor: (P/A,i,N)\n# - gives the present amount, P, that is equivalent to an annuity with\n# disbursements or receipts in the amount of A, where the interest rate is i\n# and the number of periods is N\n# - how much should I pay now to get out of paying $200 a month for 40 years if\n# the interest is 2%\nfunction seriesPresentAmountFactor(i, N)\n\t((1 + i)^N - 1) / (i * (1 + i)^N)\nend\n\nexport singlePaymentPresentWorthArithmetic, sinkingFundPaymentArithmetic\n# Single Payment Present Worth for Arithmetic Gradient Series:\n# - gives the present worth of paying a gradient cost for N periods at an\n# interest rate of i\n# - (P/G, i, N)\nfunction singlePaymentPresentWorthArithmetic(i, N)\n\t((1+i)^N - i * N - 1) / (i^2 * (1+i)^N)\nend\n\n# Sinking Fund Payment for Arithmetic Gradient Series\n# - (A/G, i, N)\nfunction sinkingFundPaymentArithmetic(i, N)\n\t(1 / i - N / ((1+i)^N - 1))\nend\n\nexport presentWorthConversionFactorGeometric\n# Conversion Factor for Geometric Gradient Series (P/A, g, i, N)\n# - gives the present worth P that is equivalent to a geometric gradient series\n# where the base receipt or disbursement is A, the growth rate is g, and the\n# interest rate is i, and the number of periods is N\nfunction presentWorthConversionFactorGeometric(g, i, N)\n\ti0 = (1 + i) / (1 + g) - 1\n\t(((1 + i0)^N - 1) / (i0 * (1+i0)^N)) * 1 / (1 + g)\nend\n\nexport paybackPeriod\nfunction paybackPeriod(firstCost, annualSavings)\n\treturn firstCost / annualSavings\nend\n\nend\n", "meta": {"hexsha": "c1518130f51e072447e2ccfd79a80a9e9500c99d", "size": 4432, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/EngEconomics.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": "src/EngEconomics.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": "src/EngEconomics.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": 34.0923076923, "max_line_length": 80, "alphanum_fraction": 0.7150270758, "num_tokens": 1309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551525886194, "lm_q2_score": 0.880797068590724, "lm_q1q2_score": 0.8498415900147117}} {"text": "# ------------------------------------------------------------------------------------------\n# # Factorizaciones y otras diversiones\n# Autor: Andreas Noack Jensen (MIT) (http://www.econ.ku.dk/phdstudent/noack/)\n# (con edición de Jane Herriman=\n#\n# ## Sinopsis\n# - Factorizaciones\n# - Estructuras de matrices especiales\n# - Álgebra lineal genérica\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# Empezamos con un sistema lineal de la forma\n#\n# `Ax = b`\n# ------------------------------------------------------------------------------------------\n\nA = randn(3,3)\n\nx = fill(1.0, (3))\nb = A*x\n\n# ------------------------------------------------------------------------------------------\n# ### Factorización\n# La función `\\` esconde cómo regularmente se resuelve el problema.\n#\n# Dependiendo de las dimensiones de `A`, distintos métodos son elegidos para resolver el\n# problema.\n#\n# ```\n# Ax = b\n# ```\n#\n# Un paso intermedio en la solución es el cálculo de la factorización de la matriz `A`.\n#\n# Básicamente, una factorización de `A` es una manera de expresar `A` como el producto de\n# matrices triangulares, unitarias, y de permutación.\n#\n# Julia guarda estas factorizaciones usando un tipo abstracto llamado `Factorization` y\n# varios subtipos.\n#\n# Un objeto `Factorization` entonces debería ser pensado como una represenatación de la\n# matriz `A`.\n#\n# #### LU\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# Cuando `A` es cuadrada, el sistema linear es resuelto factorizando `A` vía\n#\n# ```\n# PA=LU\n# ```\n#\n# donde `P` es una matriz de permutación, `L` es un triangular inferior unitaria y `U` es\n# triangular superior.\n#\n# Julia permita calcular la facorización LU y define un tipo de factorización compuesta para\n# guardarlo.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# Podemos hacer una factorización LU sobre `A` vía `lu(A)` ó `lufact(A)`.\n#\n# La función `lu` regresa matrices `l` y `u` y un vector de permutación `p`.\n# ------------------------------------------------------------------------------------------\n\nl,u,p = lu(A)\n\n# ------------------------------------------------------------------------------------------\n# El pivoteo está prendido por default, o sea que no podemos assumir que A == LU.\n# Vamos a comprobar esto viendo la norma de `LU - A`:\n# ------------------------------------------------------------------------------------------\n\nnorm(l*u - A)\n\n# ------------------------------------------------------------------------------------------\n# Esto nos muestra que queremos tomar en cuenta el pivoteo!\n#\n# Podemos pensar en `A[p,:]` como la sintaxis para `PA`, o como el producto de una matriz de\n# permutación con `A`\n# ------------------------------------------------------------------------------------------\n\nnorm(l*u - A[p,:])\n\n# ------------------------------------------------------------------------------------------\n# Por otro lado, podemos apagar el pivoteo usando `Val{false}` en Julia 0.6 ó `Val(false)`\n# en versiones más modernas.\n# ------------------------------------------------------------------------------------------\n\nl,u,p = lu(A, Val{false})\n\n# ------------------------------------------------------------------------------------------\n# Cuando apagamos el pivoteo, `LU = A`\n# ------------------------------------------------------------------------------------------\n\nnorm(l*u - A)\n\n# ------------------------------------------------------------------------------------------\n# Una segunda manera de hacer la factorización es con `lufact`.\n# ------------------------------------------------------------------------------------------\n\nAlu = lufact(A)\n\n# ------------------------------------------------------------------------------------------\n# Distintas partes de la factorización las puedes accesar con índices especiales\n# ------------------------------------------------------------------------------------------\n\nAlu[:P]\n\nAlu[:L]\n\nAlu[:U]\n\n# ------------------------------------------------------------------------------------------\n# Podemos calcular la solución de $Ax=b$ del objecto de factorización\n# ------------------------------------------------------------------------------------------\n\n# PA = LU\n# A = P'LU\n# P'LUx = b\n# LUx = Pb\n# Ux = L\\Pb\n# x = U\\L\\Pb\nAlu[:U]\\(Alu[:L]\\(Alu[:P]b))\n\n# ------------------------------------------------------------------------------------------\n# *Más importantemente,* podemos despachar sobre el tipo de `LU` y simplemente resolver el\n# problema por medio de\n# ------------------------------------------------------------------------------------------\n\nAlu\\b\n\n# ------------------------------------------------------------------------------------------\n# Esto puede ser útil si el mismo lado izquierdo es usado para lados derechos.\n#\n# La factorización también se puede usar para calcular el determinante pues\n#\n# $\\det(A)=\\det(PLU)=\\det(P)\\det(U)=\\pm \\prod u_{ii}$\n#\n# porque $U$ es triangular y el signo está definido por $\\det(P)$.\n# ------------------------------------------------------------------------------------------\n\ndet(A)\n\ndet(Alu)\n\n# ------------------------------------------------------------------------------------------\n# #### QR\n# Cuando `A` es alta,\n# ------------------------------------------------------------------------------------------\n\nAtall = randn(3, 2)\n\n# ------------------------------------------------------------------------------------------\n# Julia calcula la solución de mínimos cuadrados $\\hat{x}$ que minimiza $\\|Ax-b\\|_2$.\n#\n# Esto se puede hacer factorizando\n#\n# ```\n# A=QR\n# ```\n#\n# donde $Q$ es unitaria/ortogonal y\n#\n# $R=\\left(\\begin{smallmatrix}R_0\\\\0\\end{smallmatrix}\\right)$ y $R_0$ es triangular\n# superior.\n#\n# con la factorización QR la norma mínima se puede expresar como\n#\n# \\begin{equation*}\n# \\|Ax-b\\|=\\|QRx-b\\|=\\|Q(Rx-Q'b)\\|=\\|Rx-Q'b\\|=\\left\\|\\begin{pmatrix}R_0x-Q_0'b\\\\Q_1'b\\end{pm\n# atrix}\\right\\|=\\|R_0x-Q_0'b\\|+\\|Q_1'b\\|\n# \\end{equation*}\n#\n# Y entonces el problema se puede reducir a resolver el problema cuadrado $R_0x=Q_0'b$ para\n# $x$.\n#\n# Podemos factorizar QR sobre `Atall` vía\n# ------------------------------------------------------------------------------------------\n\nAqr = qrfact(Atall)\n\n# ------------------------------------------------------------------------------------------\n# Otra característica de la factorización QR es que los tipos `Q` para guardar las matrices\n# unitarias $Q$. Se pueden extraer de tipos `QR` con los índices\n# ------------------------------------------------------------------------------------------\n\nAqr[:Q]\n\n# ------------------------------------------------------------------------------------------\n# Similarmente, la matriz superior triangular $R$ se puede extraer con el índice\n# ------------------------------------------------------------------------------------------\n\nAqr[:R]\n\n# ------------------------------------------------------------------------------------------\n# En este caso se guarda R como una matriz 2x2 en vez de 3x2 porque el último renglón de R\n# está lleno de 0's.

\n#\n#\n# Aunque la matriz `Aqr[:Q]` se imprime como $3\\times 3$ en el objeto de factorización, en\n# la práctica puede representar la versión delgada también. Así\n# ------------------------------------------------------------------------------------------\n\nAqr[:Q]*ones(2)\n\n# ------------------------------------------------------------------------------------------\n# funciona y representa a $3 x 2$ matrix por un vector de 2-elementos.\n#\n# Similarmente,\n# ------------------------------------------------------------------------------------------\n\nAqr[:Q]*ones(3)\n\n# ------------------------------------------------------------------------------------------\n# funciona representando la matriz $3x3$ y un vector de 3 elementos.\n#\n# Sin embargo, esto no significa que podemos multiplicar a `Q` por vectores de longitued\n# arbitraria.\n# ------------------------------------------------------------------------------------------\n\nAqr[:Q]*ones(4)\n\n# ------------------------------------------------------------------------------------------\n# La matriz tiene representación interna compacta, entonces indexar sólo hace sentido si uno\n# sabe cómo la factorización guarda datos.\n# ------------------------------------------------------------------------------------------\n\nAqr[:Q][1]\n\n# ------------------------------------------------------------------------------------------\n# El objeto QRCompactWY `\\` tiene un método para QR y entonces el problema de los mínimos\n# cuadrados es resuelto con\n# ------------------------------------------------------------------------------------------\n\nAqr\\b\n\n# ------------------------------------------------------------------------------------------\n# Y si en vez escribimos\n# ------------------------------------------------------------------------------------------\n\nAtall\\b\n\n# ------------------------------------------------------------------------------------------\n# En vez de factorizar con QR a `Atall` primero, Julia va a defaultear factorizar *con*\n# pivoteo.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# Este default a pivotear la factorización QR le permite a Julia resolver problemas\n# deficientes de rango.\n#\n# Podemos explícitamente escoger pivotear durante la factorización QR (de una matriz\n# singular, por ejemplo) con `Val{true}`.\n# ------------------------------------------------------------------------------------------\n\nv = randn(3)\n# Tomar el producto exterio de un vector consigo mismo nos da una matriz singular\nsingmatriz = v * v'\n\nAqrp = qrfact(singmatriz,Val{true})\n\n# ------------------------------------------------------------------------------------------\n# Notamos que el tipo que resulta del objecto de Factorization es distinto que antes.\n#\n# `\\` también tiene un método de `QRPivoted` y el problema con rango deficiente es entonces\n# calculado como\n# ------------------------------------------------------------------------------------------\n\nAqrp\\b\n\n# ------------------------------------------------------------------------------------------\n# #### Eigendescompisición y los SVDs (Valores de descomposición Singular)\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# Los resultados de eigendescomposición y de la descomposición singular de valores se\n# guardan en los tipos`Factorization`. Esto también incluye la factorización de Hessenberg y\n# de Schur\n#\n# La eigendescomposición puede ser calculada como\n# ------------------------------------------------------------------------------------------\n\nAsym = A + A'\nAsymEig = eigfact(Asym)\n\n# ------------------------------------------------------------------------------------------\n# Los valores y vectores se pueden recoger del tipo Eigen con un índice especial\n# ------------------------------------------------------------------------------------------\n\nAsymEig[:values]\n\nAsymEig[:vectors]\n\n# ------------------------------------------------------------------------------------------\n# Una vez más, como la descomposición se guarda en un tipo, podemos despatchar sobre esos\n# tipos y explotar un método especializado para cada factorización, e.g. que\n# $A^{-1}=(V\\Lambda V^{-1})^{-1}=V\\Lambda^{-1}V^{-1}$.\n# ------------------------------------------------------------------------------------------\n\ninv(AsymEig)*Asym\n\n# ------------------------------------------------------------------------------------------\n# Julia también tiene una función `eig` que regresa una tupla con los valores y vectores\n# ------------------------------------------------------------------------------------------\n\neig(Asym)\n\n# ------------------------------------------------------------------------------------------\n# No recomendamos esta versión.\n#\n# La función `svdfact` calcula la descomposición singular de valores\n# ------------------------------------------------------------------------------------------\n\nAsvd = svdfact(A[:,1:2])\n\n# ------------------------------------------------------------------------------------------\n# y de nuevo `\\` tiene un método para el tipo que permite los mínimos cuadrados por SVD\n# ------------------------------------------------------------------------------------------\n\nAsvd\\b\n\n# ------------------------------------------------------------------------------------------\n# Existen funciones especiales para proporcionar los valores sólamente: `eigvals` and\n# `svdvals`.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# ### Estructuras especiales de matrices\n#\n# La estructura de matrices es muy importante en el álgebra linear. Ésta estructura se le\n# puede hacer explícita a Julia por medio de los tipos compuestos. Ejemplos: `Diagonal`,\n# `Triangular`, `Symmetric`, `Hermitian`, `Tridiagonal` y `SymTridiagonal`. Se han escrito\n# métodos especializados para cada tipo de matriz especial para aprovechar su estructura.\n# Siguen algunos ejemplos:\n# ------------------------------------------------------------------------------------------\n\nA\n\n# ------------------------------------------------------------------------------------------\n# Creando una matriz Diagonal\n# ------------------------------------------------------------------------------------------\n\nDiagonal(diag(A))\n\nDiagonal(A)\n\n# ------------------------------------------------------------------------------------------\n# Creando una matriz triangular inferior\n# ------------------------------------------------------------------------------------------\n\nLowerTriangular(tril(A))\n\nLowerTriangular(A)\n\n# ------------------------------------------------------------------------------------------\n# Creando una matriz simétrica\n# ------------------------------------------------------------------------------------------\n\nSymmetric(Asym)\n\nSymTridiagonal(diag(Asym),diag(Asym,1))\n\n# ------------------------------------------------------------------------------------------\n# Cuando se sabe que una matriz es e.g. triangular o simétrica Julia puede que resuelva el\n# problema más rápido convirtiendo a una matriz especial.\n#\n# Para algunos procedimientos, Julia checa si el input de matriz es triangular o simétrica y\n# lo convierte a tal estructura si lo detecta.\n#\n# Debería notarse que `Symmetric`, `Hermitian` y `Triangular` no copian la matriz original.\n#\n# #### Eigenproblema simétrico\n# La capacidad de Julia para poder detectar si una matriz es simétrica/Hermitian puede\n# influenciar muchísimo sobre qué tan rápido se puede resolver un problema de eigenvalor.\n# ------------------------------------------------------------------------------------------\n\nn = 1000;\nA = randn(n,n);\n\n# ------------------------------------------------------------------------------------------\n# Usamos `A` para genera una matriz simétrica `Asym`\n# ------------------------------------------------------------------------------------------\n\nAsym = A + A';\n\n# ------------------------------------------------------------------------------------------\n# Ahora creemos una matriz Asym para simular una matriz simétrica con errores de punto\n# flotante\n# ------------------------------------------------------------------------------------------\n\nAsym_noisy = copy(Asym); Asym_noisy[1,2] += 5eps();\n\n# ------------------------------------------------------------------------------------------\n# ¿Puede Julia determinar que ambas `Asym` y `Asym_noisy` son matrices simétricas?\n# ------------------------------------------------------------------------------------------\n\nprintln(\"Is Asym symmetric? \", issymmetric(Asym))\nprintln(\"Is Asym_noisy symmetric? \", issymmetric(Asym_noisy))\n\n# ------------------------------------------------------------------------------------------\n# Ahora veamos como el ruido de `Asym_noisy` impacta el tiempo en llevar a cabo una\n# eigendescomposición\n# ------------------------------------------------------------------------------------------\n\n@time eigvals(Asym);\n\n@time eigvals(Asym_noisy);\n\n# ------------------------------------------------------------------------------------------\n# Por suerte, le podeemos proveer información explícita sobre la estructura de la matriz a\n# Julia\n# En este ejemplo, usamos la palabra clave `Symmetric`\n# ------------------------------------------------------------------------------------------\n\n@time eigvals(Symmetric(Asym_noisy));\n\n# ------------------------------------------------------------------------------------------\n# Y así nuestros cálculos son mucho más eficientes :)\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# ### Un gran problema\n# Usar matrices tridiagonales permite trabajar con problemas potencialmente muy grandes. El\n# siguiente problema no seria posible resolverlo en una laptop si la matriz se tuviera que\n# guardar como tipo `Matrix`.\n# ------------------------------------------------------------------------------------------\n\nn = 1_000_000;\nA = SymTridiagonal(randn(n), randn(n-1));\n@time eigmax(A)\n\n# ------------------------------------------------------------------------------------------\n# ### Álgebra lineal numérica\n# La manera usual de agregar soporte para álgebra lineal numérica es haciendo un wrapper\n# para subrutinas de BLAS y LAPACK. Para matrices con elementos `Float32`, `Float64`,\n# `Complex{Float32}` ó `Complex{Float64}` esto es lo que hace Julia. Desde hace rato, Julia\n# ha tnido soport para la multiplicación genérica de tipos. Así, cuando uno multiplica\n# matrices de enteros, obtiene una matriz de enteros.\n# ------------------------------------------------------------------------------------------\n\nrand(1:10,3,3)*rand(1:10,3,3)\n\n# ------------------------------------------------------------------------------------------\n# Recientemente, más métodos de álgebra lineal se han añadido a Julia y ahora soporta\n# factorizaciones generales de tipo `LU` y `QR`. Métodos generales para eigenvalores y SVD\n# han sido escritos más recientemente en paquetería externa.\n#\n# En general, la factorización `LU` puede ser calculada cuando los elementos de la matriz se\n# cierraon sobre los operadores `+`, `-`, `*` y `\\`. Por supuesto, la matriz también deben\n# tener rango completo. El método general de factorización `LU` en Julia aplica pivoteo y\n# por lo tanto debe poder soportar `<` y `abs`. Por lo tanto es posible resolver sistemas de\n# ecuaciones de e.g. números racionales como en los ejemplos que siguen.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# Para usar números racionales, usamos un doble //:\n# ------------------------------------------------------------------------------------------\n\n1//2\n\n# ------------------------------------------------------------------------------------------\n# #### Ejemplo 1: Sistemas racionales lineales de ecuaciones\n# Julia cuenta con números racionales ya instalados. El siguiente ejemplo consta de un\n# sistema lineal de ecuaciones resulto sin promover a tipos de punto flotanto. Puede haber\n# un error de overflow fácilmente al trabajar con racionales, así que usamos `BigInt`s.\n# ------------------------------------------------------------------------------------------\n\nAr = convert(Matrix{Rational{BigInt}}, rand(1:10,3,3))/10\n\nx = fill(1, (3))\nb = Ar*x\n\nAr\\b\n\nlufact(Ar)\n\n# ------------------------------------------------------------------------------------------\n# #### Ejemplo 2: Matriz racional de eigenestructura\n#\n# El siguiente ejemplo muestra como la artimética de matriz racional puede ser usada para\n# calcular una matriz dados los eigenvalores y eigenvectores racionales. Yo he encontrado\n# ésto útil para mostrar ejemplos de sistemas dinámicos lineales.\n# ------------------------------------------------------------------------------------------\n\nλ1,λ2,λ3 = 1//1,1//2,1//4\nv1,v2,v3 = [1,0,0],[1,1,0],[1,1,1]\nV,Λ = [v1 v2 v3], Diagonal([λ1,λ2,λ3])\nA = V*Λ/V\n\n# ------------------------------------------------------------------------------------------\n# ### Exercises\n#\n# 11.1 ¿Cuáles son los eigenvalores de la Matriz 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# ------------------------------------------------------------------------------------------\n\n\n\n# ------------------------------------------------------------------------------------------\n# 11.2 Crea una matriz diagonal de los eigenvalores de A\n# ------------------------------------------------------------------------------------------\n\n\n\n# ------------------------------------------------------------------------------------------\n# 11.3 Realiza un factorización de Hessenberg sobre la matriz A. Verifica que `A = QHQ'`.\n# ------------------------------------------------------------------------------------------\n\n\n", "meta": {"hexsha": "e272508c5f048d627eee0565c557c30b6b8f78f3", "size": 21726, "ext": "jl", "lang": "Julia", "max_stars_repo_path": ".nbexports/introductory-tutorials/intro-to-julia-ES/11.Factorizaciones y otras diversiones.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-ES/11.Factorizaciones y otras diversiones.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-ES/11.Factorizaciones y otras diversiones.jl", "max_forks_repo_name": "grenkoca/JuliaTutorials", "max_forks_repo_head_hexsha": "3968e0430db77856112521522e10f7da0d7610a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 394, "max_forks_repo_forks_event_min_datetime": "2020-07-14T23:22:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T20:12:57.000Z", "avg_line_length": 41.6206896552, "max_line_length": 92, "alphanum_fraction": 0.382629108, "num_tokens": 3938, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897475985937, "lm_q2_score": 0.9032942041005328, "lm_q1q2_score": 0.8498099262830129}} {"text": "\"\"\"\r\nComparison of means: plot posterior densities and compute odds against difference of 0.\r\n\r\nReturns:\r\n diff_mean, draws_m1, draws_m2, qs, tst ## out-of-date: plt,diff_mean,qs,tst\r\n\r\n plt = plot of densities\r\n diff_mean = MC sample from posterior of difference in means\r\n qs = HPD quantile intervals from diff_mean\r\n tst = posterior odds against zero difference and area in tail to one side of zero.\r\n\r\nEnter either:\r\n compare_mean(x,y)\r\n x, y are two samples to compare_means\r\n\r\n compare_means(m1, m2, s1, s2, n1, n2)\r\n m1, m2, are sample means, s1, s2, are sample SDs, n1, n2 are sample number of obs.\r\n\r\nOptional arguments:\r\n M = MC sample size (larger for improvement numerical accuracy)\r\n lbl = [\"mu 1 label\" \"mu 1 label\"], use lbl = [\"\" \"\"] to eliminate labels\r\n lgd = :topright (choose legend position, :topleft to move to top left of figure, etc.)\r\n\"\"\"\r\nfunction compare_means(m1, m2, s1, s2, n1, n2; M = 1000000, lbl=[\"mu 1\" \"mu 2\"],lgd = :topright)\r\n draws_m1 = m1 .+ (s1/sqrt(n1)).*rand(TDist(n1-1),M)\r\n draws_m2 = m2 .+ (s2/sqrt(n2)).*rand(TDist(n2-1),M)\r\n diff_mean = draws_m1 - draws_m2\r\n plot(draws_m1,st=:histogram,normalize=true,bins=100)\r\n l = @layout([a b])\r\n plt1 = plot(draws_m1,st=:density,fill=(0,0.4,:red),alpha=0.4,label=lbl[1],legend=lgd,title=\"Posteriors for means\")\r\n plot!(draws_m2,st=:density,fill=(0,0.4,:blue),alpha=0.4,label=lbl[2])\r\n plt2 = plot(diff_mean,st=:density,fill=(0,0.4,:green),alpha=0.4,label=\"\",title=\"Posterior difference\")\r\n vline!([0.0],color=:black,label=\"\")\r\n plt3 = plot(plt1, plt2, layout=l)\r\n qs = quantile(diff_mean,[0.005 0.025 0.05 0.5 0.95 0.975 0.995])\r\n @show(qs)\r\n tst = [mcodds(diff_mean) bayespval(diff_mean)]\r\n @show(tst)\r\n return diff_mean, draws_m1, draws_m2, qs, tst, plt3\r\nend\r\n\r\n# function overload for using two samples directly\r\nfunction compare_means(x,y; M = 1000000, lbl=[\"mu 1\" \"mu 2\"],lgd = :topright)\r\n m1 = mean(x); m2 = mean(y)\r\n s1 = std(x); s2 = std(y)\r\n n1 = length(x); n2 = length(y)\r\n draws_m1 = m1 .+ (s1/sqrt(n1)).*rand(TDist(n1-1),M)\r\n draws_m2 = m2 .+ (s2/sqrt(n2)).*rand(TDist(n2-1),M)\r\n diff_mean = draws_m1 - draws_m2\r\n plot(draws_m1,st=:histogram,normalize=true,bins=100)\r\n l = @layout([a b])\r\n plt1 = plot(draws_m1,st=:density,fill=(0,0.4,:red),alpha=0.4,label=lbl[1],legend=lgd,title=\"Posteriors for means\")\r\n plot!(draws_m2,st=:density,fill=(0,0.4,:blue),alpha=0.4,label=lbl[2])\r\n plt2 = plot(diff_mean,st=:density,fill=(0,0.4,:green),alpha=0.4,label=\"\",title=\"Posterior difference\")\r\n vline!([0.0],color=:black,label=\"\")\r\n plt3 = plot(plt1, plt2, layout=l)\r\n qs = quantile(diff_mean,[0.005 0.025 0.05 0.5 0.95 0.975 0.995])\r\n @show(qs)\r\n tst = [mcodds(diff_mean) bayespval(diff_mean)]\r\n @show(tst)\r\n return diff_mean, draws_m1, draws_m2, qs, tst, plt3\r\nend\r\n\r\n\"\"\"\r\n 2x2 contigency table (categorical data) comparison of proportions\r\n \"\"\"\r\nfunction compare_proportions(s1, s2, n1, n2; a =1, b = 1,M = 1000000, lbl=[\"mu 1\" \"mu 2\"],lgd = :topright)\r\n draws_m1 = rand(Beta((s1+a),(n1-s1+b)),M)\r\n draws_m2 = rand(Beta((s2+a),(n2-s2+b)),M)\r\n diff_mean = draws_m1 - draws_m2\r\n plot(draws_m1,st=:histogram,normalize=true,bins=100)\r\n l = @layout([a b])\r\n plt1 = plot(draws_m1,st=:density,fill=(0,0.4,:red),alpha=0.4,label=lbl[1],legend=lgd,title=\"Posteriors for proportions\",ylab=\"Density\",xlab=\"Proportion\")\r\n plot!(draws_m2,st=:density,fill=(0,0.4,:blue),alpha=0.4,label=lbl[2])\r\n plt2 = plot(diff_mean,st=:density,fill=(0,0.4,:green),alpha=0.4,label=\"\",title=\"Posterior difference\",xlab=\"Difference in proportion\")\r\n vline!([0.0],color=:black,label=\"\",linewidth=2)\r\n plt3 = plot(plt1, plt2, layout=l)\r\n qs = quantile(diff_mean,[0.005 0.025 0.05 0.5 0.95 0.975 0.995])\r\n @show(qs)\r\n tst = [mcodds(diff_mean) bayespval(diff_mean)]\r\n @show(tst)\r\n return diff_mean, draws_m1, draws_m2, qs, tst, plt3\r\nend\r\n\r\nfunction compare_proportions(x, y; a =1, b = 1,M = 1000000, lbl=[\"mu 1\" \"mu 2\"],lgd = :topright)\r\n n1 = length(x); s1 = sum(x)\r\n n2 = length(y); s2 = sum(y)\r\n draws_m1 = rand(Beta((s1+a),(n1-s1+b)),M)\r\n draws_m2 = rand(Beta((s2+a),(n2-s2+b)),M)\r\n diff_mean = draws_m1 - draws_m2\r\n plot(draws_m1,st=:histogram,normalize=true,bins=100)\r\n l = @layout([a b])\r\n plt1 = plot(draws_m1,st=:density,fill=(0,0.4,:blue),alpha=0.4,label=lbl[1],legend=lgd,title=\"Posteriors for proportions\")\r\n plot!(draws_m2,st=:density,fill=(0,0.4,:red),alpha=0.4,label=lbl[2])\r\n plt2 = plot(diff_mean,st=:density,fill=(0,0.4,:green),alpha=0.4,label=\"\",title=\"Posterior difference\")\r\n vline!([0.0],color=:black,label=\"\")\r\n plt3 = plot(plt1, plt2, layout=l)\r\n qs = quantile(diff_mean,[0.005 0.025 0.05 0.5 0.95 0.975 0.995])\r\n @show(qs)\r\n tst = [mcodds(diff_mean) bayespval(diff_mean)]\r\n @show(tst)\r\n return diff_mean, draws_m1, draws_m2, qs, tst, plt3\r\nend\r\n\r\n\"\"\"\r\nFunction to draw from Beta(s+a, n-s+b) posterior\r\n\r\n Default prior is uniform: a = b = 1\r\n\"\"\"\r\nfunction beta_posterior(s,n; a=1, b=1, M=100000)\r\n theta_draws = rand(Beta((s+a),(n-s+b)),M)\r\n return theta_draws\r\nend\r\n\r\n\"\"\"\r\nFunction to update Beta(s+a, n-s+b) posterior given two samples\r\n\r\n Default prior is uniform: a = b = 1 for each sample distribution\r\n\"\"\"\r\nfunction beta_update(s1,n1,s2,n2; a1=1,b1=1,a2=1,b2=1,M=100000)\r\n theta_draws = rand(Beta((s1+s2+a1+a2),(n1+n2-s1-s2+b1+b2)),M)\r\n return theta_draws\r\nend\r\n\r\n\"\"\"\r\nequiv_test = Equivalence test from MC sample of difference in ATE\r\n\r\n mc_sample = posterior simulation sample of difference in treatments\r\n\r\n interval = 1/2 tolerance interval = distance from 0.0 to one side of interval\r\n\r\n see TADS_equiv.jl for example of use.\r\n\"\"\"\r\nfunction equiv_test(mc_sample,interval;h0=0.0)\r\n p1 = p2 = p3 = p4 = p5 = 0.0\r\n for th1 in mc_sample\r\n if th1 < (h0-3*interval)\r\n p1 += 1\r\n elseif th1 < (h0-interval)\r\n p2 += 1\r\n elseif th1 < (h0+interval)\r\n p3 += 1\r\n elseif th1 < (h0+3*interval)\r\n p4 += 1\r\n else\r\n p5 += 1\r\n end\r\n end\r\n ps = [p1; p2; p3; p4; p5]\r\n normps = ps./sum(p1 + p2 + p3 + p4 + p5)\r\n x = [-4*interval; -2*interval; 0.0; 2*interval; 4*interval]\r\n# plt = plot(mc_sample,st=:density,label=\"\",ylab=\"\",alpha=0.4,fill=(0,0.4,:green),ylim=(0.0,0.4))\r\n# plot!(twinx(),x,normps, st=:bar, color=:grey,alpha=0.4,bar_width=2*interval,label=\"\",ylim=(0.0,1.0),ylab=\"Probability\",title = \"Equivalence interval probabilities\") #,axis=:right\r\n plt = plot(mc_sample,st=:density,label=\"\",ylab=\"\",alpha=0.2,fill=(0,0.2,:blue)) #,ylim=(0.0,0.4))\r\n plot!(twinx(),x,normps, st=:bar, color=:green,alpha=0.4,bar_width=2*interval,label=\"\",ylim=(0.0,1.0),ylab=\"\",title = \"Equivalence interval probabilities\") #,axis=:right\r\n oddsf35 = normps[3]/normps[5]\r\n oddsf34 = normps[3]/normps[4]\r\n oddsf32 = normps[3]/normps[2]\r\n oddsf31 = normps[3]/normps[1]\r\n eqodds = [oddsf31 oddsf32 oddsf34 oddsf35]\r\n# @show(eqodds)\r\n# @show(normps)\r\n return eqodds, normps, plt, x\r\nend\r\n\r\n\"\"\"\r\nEquivalance test with 7 intervals (equiv_test has 5)\r\n\"\"\"\r\nfunction equiv_test7(mc_sample,interval;h0=0.0)\r\n p1 = p2 = p3 = p4 = p5 = p6 = p7 = 0.0\r\n for th1 in mc_sample\r\n if th1 < (h0-5*interval)\r\n p1 += 1\r\n elseif th1 < (h0-3*interval)\r\n p2 += 1\r\n elseif th1 < (h0-interval)\r\n p3 += 1\r\n elseif th1 < (h0+interval)\r\n p4 += 1\r\n elseif th1 < (h0+3*interval)\r\n p5 += 1\r\n elseif th1 < (h0+5*interval)\r\n p6 += 1\r\n else\r\n p7 += 1\r\n end\r\n end\r\n ps = [p1; p2; p3; p4; p5; p6; p7]\r\n normps = ps./sum(p1 + p2 + p3 + p4 + p5 + p6 + p7)\r\n x = [-6*interval; -4*interval; -2*interval; 0.0; 2*interval; 4*interval; 6*interval;]\r\n # plt = plot(mc_sample,st=:density,label=\"\",ylab=\"\",alpha=0.4,fill=(0,0.4,:green),ylim=(0.0,0.4))\r\n # plot!(twinx(),x,normps, st=:bar, color=:grey,alpha=0.4,bar_width=2*interval,label=\"\",ylim=(0.0,1.0),ylab=\"Probability\",title = \"Equivalence interval probabilities\") #,axis=:right\r\n plt = plot(mc_sample,st=:density,label=\"\",ylab=\"\",alpha=0.2,fill=(0,0.2,:blue)) #,ylim=(0.0,0.4))\r\n plot!(twinx(),x,normps, st=:bar, color=:green,alpha=0.4,bar_width=2*interval,label=\"\",ylim=(0.0,1.0),ylab=\"\",title = \"Equivalence interval probabilities\") #,axis=:right\r\n oddsf47 = normps[4]/normps[7]\r\n oddsf46 = normps[4]/normps[6]\r\n oddsf45 = normps[4]/normps[5]\r\n oddsf43 = normps[4]/normps[3]\r\n oddsf42 = normps[4]/normps[2]\r\n oddsf41 = normps[4]/normps[1]\r\n eqodds = [oddsf41 oddsf42 oddsf43 oddsf45 oddsf46 oddsf47]\r\n # @show(eqodds)\r\n # @show(normps)\r\n return eqodds, normps, plt, x\r\nend\r\n", "meta": {"hexsha": "b91898ad8b94aecc80ddf9f526093f090fd38eed", "size": 8852, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/compare_means.jl", "max_stars_repo_name": "tszanalytics/BayesTesting.jl", "max_stars_repo_head_hexsha": "d44f1b752be0932afa51860b2eee83681e41f59d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2018-08-10T07:29:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-24T22:09:46.000Z", "max_issues_repo_path": "src/compare_means.jl", "max_issues_repo_name": "tszanalytics/BayesTesting.jl", "max_issues_repo_head_hexsha": "d44f1b752be0932afa51860b2eee83681e41f59d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2018-09-10T06:26:40.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-13T09:57:50.000Z", "max_forks_repo_path": "src/compare_means.jl", "max_forks_repo_name": "tszanalytics/BayesTesting.jl", "max_forks_repo_head_hexsha": "d44f1b752be0932afa51860b2eee83681e41f59d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-07-31T02:03:43.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-15T08:11:03.000Z", "avg_line_length": 42.9708737864, "max_line_length": 186, "alphanum_fraction": 0.61398554, "num_tokens": 3206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812290812827, "lm_q2_score": 0.8774767906859264, "lm_q1q2_score": 0.8497320530547369}} {"text": "#\n# Univariate Calculus\n#\n\nmacro test_simplified_isequal(lhs, rhs)\n quote\n @test isequal(simplify($(esc(lhs))), $(esc(rhs)))\n end\nend\n\n@test isequal(differentiate(:(2), :x), 0)\n@test isequal(differentiate(:(x), :x), 1)\n@test_simplified_isequal differentiate(:(x + x), :x) 2\n@test_simplified_isequal differentiate(:(x - x), :x) 0\n@test_simplified_isequal differentiate(:(2 * x), :x) 2\n@test_simplified_isequal differentiate(:(2 / x), :x) :(-2 / x^2)\n@test_simplified_isequal differentiate(:(x / 2), :x) 0.5\n@test_simplified_isequal differentiate(:(sin(x) / x), :x) :((cos(x) * x - sin(x)) / x^2)\n@test_simplified_isequal differentiate(:(x * 2), :x) 2\n@test_simplified_isequal differentiate(:(a * x), :x) :a\n@test_simplified_isequal differentiate(:(x * a), :x) :a\n@test_simplified_isequal differentiate(:(x ^ 2), :x) :(2 * x)\n@test_simplified_isequal differentiate(:(a * x ^ 2), :x) :(a * (2 * x))\n@test_simplified_isequal differentiate(:(2 ^ x), :x) :(*(0.6931471805599453, ^(2, x)))\n@test_simplified_isequal differentiate(:(sin(x)), :x) :(cos(x))\n@test_simplified_isequal differentiate(:(cos(x)), :x) :(-sin(x))\n@test_simplified_isequal differentiate(:(tan(x)), :x) :(1 + tan(x)^2)\n@test_simplified_isequal differentiate(:(exp(x)), :x) :(exp(x))\n@test_simplified_isequal differentiate(:(log(x)), :x) :(1 / x)\n@test_simplified_isequal differentiate(:(sin(x) + sin(x)), :x) :(cos(x) + cos(x))\n@test_simplified_isequal differentiate(:(sin(x) - cos(x)), :x) :(cos(x) + sin(x))\n@test_simplified_isequal differentiate(:(x * sin(x)), :x) :(sin(x) + x * cos(x))\n@test_simplified_isequal differentiate(:(x / sin(x)), :x) :((sin(x) - x * cos(x)) / (sin(x)^2))\n@test_simplified_isequal differentiate(:(sin(sin(x))), :x) :(*(cos(x),cos(sin(x))))\n@test_simplified_isequal differentiate(:(sin(cos(x) + sin(x))), :x) :(*(+(-sin(x),cos(x)),cos(+(cos(x),sin(x)))))\n@test_simplified_isequal differentiate(:(exp(-x)), :x) :(-exp(-x))\n@test_simplified_isequal differentiate(:(log(x^2)), :x) :((2x) * (1 / x^2))\n@test_simplified_isequal differentiate(:(abs2(x)), :x) :(2x)\n@test_simplified_isequal differentiate(:(inv(x)), :x) :(-abs2(inv(x)))\n@test_simplified_isequal differentiate(:(x^n), :x) :(*(n, ^(x, -(n, 1))))\n@test_simplified_isequal differentiate(:(n^x), :x) :(*(^(n, x), log(n)))\n@test_simplified_isequal differentiate(:(n^n), :x) 0\n\n#\n# Multivariate Calculus\n#\n\n@test isequal(simplify.(differentiate(:(sin(x) + sin(y)), [:x, :y])), [:(cos(x)), :(cos(y))])\n@test isequal(simplify.(differentiate(:(x^2), [:x, :y])), Any[:(2*x), 0])\n\n# TODO: Get the generalized power rule right.\n# @test isequal(differentiate(:(sin(x)^2), :x), :(2 * sin(x) * cos(x)))\n\n#\n# Strings instead of symbols\n#\n\n# @test isequal(differentiate(\"sin(x) + cos(x)^2\"), :(+(cos(x),*(2,cos(x)))))\n@test_simplified_isequal differentiate(\"x + exp(-x) + sin(exp(x))\", :x) :(+(1,-exp(-x),*(exp(x),cos(exp(x)))))\n\n# TODO: Make these work\n# differentiate(:(sin(x)), :x)(0.0)\n# differentiate(:(sin(x)), :x)(1.0)\n# differentiate(:(sin(x)), :x)(pi)\n\n#\n# SymbolicVariable use\n#\n\nx = BasicVariable(:x)\ny = BasicVariable(:y)\n\n@test isequal(@sexpr(x + y), :($x + $y))\n@test_simplified_isequal differentiate(@sexpr(3 * x), x) 3\n@test_simplified_isequal differentiate(:(sin(sin(x))), :x) :(*(cos(x),cos(sin(x))))\n@test_simplified_isequal differentiate(@sexpr(sin(sin(x))), x) :(*(cos($x),cos(sin($x))))\n\nfunction testfun(x)\n z = BasicVariable(:z)\n simplify(differentiate(@sexpr(3*x + x^2*z), z))\nend\n\n@test isequal(testfun(x), :(^($(x),2)))\n@test isequal(testfun(3), 9)\n@test isequal(testfun(@sexpr(x+y)), :(^(+($x,$y),2)))\n\n#\n# Simplify tests\n#\n\n@test isequal(simplify(:(x-0)), :x)\n@test isequal(simplify(:(0-x)), :(-x))\n\n@test isequal(simplify(:(x+y)), :(+(x,y)))\n@test isequal(simplify(:(x+3)), :(+(3,x)))\n@test isequal(simplify(:(x+3+4)), :(+(7,x)))\n@test isequal(simplify(:(2+y+x+3)), :(+(5,y,x)))\n\n@test isequal(simplify(:(x*y)), :(*(x,y)))\n@test isequal(simplify(:(x*3)), :(*(3,x)))\n@test isequal(simplify(:(x*3*4)), :(*(12,x)))\n@test isequal(simplify(:(2*y*x*3)), :(*(6,y,x)))\n\n@test isequal(simplify(:(sin((1*(sin(0/0)))))), NaN)\n\n#\n# Tests with ifelse\n#\n@test_simplified_isequal differentiate(:(ifelse(x < 1, exp(x^2), 1/x)), :x) :(ifelse(x < 1,2x * exp(x^2), -1/x^2))\n@test_simplified_isequal differentiate(:(ifelse(x <= 0, 0, ifelse(x > 1, 1, x))), :x) :(ifelse(x <= 0, 0, ifelse(x > 1, 0, 1)))\n", "meta": {"hexsha": "a40c3ac1ed2603b1f64783c439cd9624a330f2c2", "size": 4367, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/symbolic.jl", "max_stars_repo_name": "UnofficialJuliaMirror/Calculus.jl-49dc2e85-a5d0-5ad3-a950-438e2897f1b9", "max_stars_repo_head_hexsha": "ffeaee8ab516c4dd598be246e2ec8745f1dd70ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 157, "max_stars_repo_stars_event_min_datetime": "2018-05-02T19:42:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T03:11:23.000Z", "max_issues_repo_path": "test/symbolic.jl", "max_issues_repo_name": "UnofficialJuliaMirror/Calculus.jl-49dc2e85-a5d0-5ad3-a950-438e2897f1b9", "max_issues_repo_head_hexsha": "ffeaee8ab516c4dd598be246e2ec8745f1dd70ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 24, "max_issues_repo_issues_event_min_datetime": "2018-05-07T12:42:49.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-24T15:29:05.000Z", "max_forks_repo_path": "test/symbolic.jl", "max_forks_repo_name": "UnofficialJuliaMirror/Calculus.jl-49dc2e85-a5d0-5ad3-a950-438e2897f1b9", "max_forks_repo_head_hexsha": "ffeaee8ab516c4dd598be246e2ec8745f1dd70ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 29, "max_forks_repo_forks_event_min_datetime": "2018-08-07T15:20:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T19:27:10.000Z", "avg_line_length": 39.3423423423, "max_line_length": 127, "alphanum_fraction": 0.6267460499, "num_tokens": 1527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422213778251, "lm_q2_score": 0.8933094167058151, "lm_q1q2_score": 0.8496643029832982}} {"text": "#=\nProblem 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:\n1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...\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\nlast = 1\ncurrent = 1\ntemp = 0\nsum = 0\n\nwhile current <= 4000000\n temp = current + last\n last = current\n current = temp\n if(current % 2 == 0)\n sum += current\n end\nend\n\nprintln(\"The sum is: $(sum)\")\n", "meta": {"hexsha": "7c6ab489eff96db02bfe672e1994c8a27befa749", "size": 533, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problem-2.jl", "max_stars_repo_name": "mebrunet/project-euler", "max_stars_repo_head_hexsha": "95140634b82c568af468e6c065a3be823b4935c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problem-2.jl", "max_issues_repo_name": "mebrunet/project-euler", "max_issues_repo_head_hexsha": "95140634b82c568af468e6c065a3be823b4935c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problem-2.jl", "max_forks_repo_name": "mebrunet/project-euler", "max_forks_repo_head_hexsha": "95140634b82c568af468e6c065a3be823b4935c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1739130435, "max_line_length": 140, "alphanum_fraction": 0.6810506567, "num_tokens": 171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741308615412, "lm_q2_score": 0.8918110382493034, "lm_q1q2_score": 0.8495161246530588}} {"text": "# rng\r\n\r\n#random number generators\r\n#Computers are not capable of generating true random numbers\r\n#but can generate sequences with statistical randomness\r\n\r\n\r\n# 1 Julia's implemented solution\r\nrand(100)\r\n\r\n# LCP psuedo solutions\r\n\r\nfunction rng_Park_Miller1998(n;x1=3)\r\n x=zeros(n)\r\n x[1] = x1\r\n u = zeros(n)\r\n for i in 2:n\r\n x[i] =mod(16807*x[i-1],2147483647)#7^5 \\ 2^31-1 31th mason prime\r\n end\r\n u = x./2147483647\r\n return u\r\nend\r\n# implemented in Matlab 4 1990\r\n\r\nrng_Park_Miller1998(100;x1=3)\r\n\r\nfunction rng_randu(n;x1=3)\r\n x = zeros(n)\r\n x[1]=x1\r\n for i in 2:n\r\n x[i] = mod(65539*x[i-1],2147483648)\r\n end\r\n u = x./2147483648\r\n return u\r\nend\r\n\r\nrng_randu(100)\r\n\r\n\r\n# iterative psudo solutions\r\n\r\nfunction rng_LMap(n;x1=.4)\r\n x = zeros(n)\r\n x[1] = x1\r\n for i in 2:n\r\n x[i]=1-2*x[i-1]^2\r\n end\r\n return((x./2) .+.5)\r\nend\r\n\r\nrng_LMap(100)\r\n\r\n# self - avoiding solutio\r\n\r\nfunction rng_Halton(n;x1 = 3)\r\n b = zeros(Int(ceil(log(n)/log(x1))))\r\n u = zeros(n)\r\n for j in 1:n\r\n i = 1\r\n b[1] = b[1]+1\r\n while b[i]>(x1-1+eps())\r\n b[i]=0\r\n i=i+1\r\n b[i]=b[i]+1\r\n end\r\n\r\n u[j]=0\r\n for k=1:length(b)\r\n u[j] = u[j]+b[k]*Float64(x1)^(-k);\r\n end\r\n end\r\n return u\r\nend\r\n\r\nrng_Halton(100)\r\n", "meta": {"hexsha": "86ddef1e13ef8ff19bc72bf8ce82991f518d4ac3", "size": 1358, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "RNG.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": "RNG.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": "RNG.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": 17.8684210526, "max_line_length": 73, "alphanum_fraction": 0.527982327, "num_tokens": 477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741308615412, "lm_q2_score": 0.8918110368115783, "lm_q1q2_score": 0.8495161232835191}} {"text": "#=\n# 1. Basic potential flow problem\n\nThis part introduces how to solve the basic potential flow problem in this package. We consider here a staggered, Cartesian grid with uniform cell size and of infinite extent. The basic (unbounded) potential flow problem is expressed as\n\n$\\mathsf{Ls} = -\\mathsf{w},$\n\nwhere $\\mathsf{L}$ is the discrete 5-point Laplacian operator, $\\mathsf{s}$ is the discrete streamfunction, and $\\mathsf{w}$ is the discrete vorticity. Following the vortex-in-cell approach, the discrete vorticity is obtained by regularizing the vorticity from the $N_v$ vortex elements onto the cell vertices,\n\n$\\mathsf{w}_{i, j}=\\sum_{q=1}^{N_{v}} \\frac{1}{\\Delta x} \\Gamma_{v, q} d\\left(\\frac{\\mathsf{x}_{i}-X_{q}}{\\Delta x}\\right) d\\left(\\frac{\\mathsf{y}_{j}-Y_{q}}{\\Delta x}\\right)$\n\nwhere $d$ is the $M_{4}'$ interpolation kernel, and $(X_{q},Y_{q})$ and $\\Gamma_{v,q}$ are the position and strength of the $q$th vortex element.\n=#\n\n\n#=\n## Flow around a point vortex\nNow we will solve this discrete potential flow problem using `GridPotentialFlow.jl` to obtain the streamfunction field and velocity field around a single point vortex.\n=#\n\n# The first step in creating *any* `GridPotentialFlow` model is to create a `PhysicalGrid` to discretize the domain.\nusing GridPotentialFlow\nΔx = 0.01\nLx = 2.0\nxlim = (-Lx/2,Lx/2)\nylim = (-Lx/2,Lx/2)\ng = PhysicalGrid(xlim,ylim,Δx);\n\n# The second step is to create our point vortex using `Vortex`.\nv = Vortex(0.0,0.0,1.0);\n\n# Now we can create a `VortexModel` using the grid and an array containing the point vortex.\nmodel = VortexModel(g,vortices=[v]);\n\n# The discrete streamfunction `s` is then obtained using `streamfunction`.\ns = streamfunction(model);\nusing Plots\nplot(s,g,xlabel=\"x\",ylabel=\"y\")\n\n# The function `streamfunction` returns a `Nodes` array. If we want to perform differential calculus operations this data, we can use the methods of the `CartesianGrids` package. For example, we can easily obtain the velocity field from the streamfunction field using the `curl` operation.\nq = curl(s);\nplot(q,g,xlabel=\"x\",ylabel=\"y\")\n\n#=\n## Accuracy of the discretized Poisson equation\nTo verify that the discretization technique of the Poisson equation is second-order accurate, we perform a mesh refinement analysis for a flow consisting of point vortices of random strenght that are randomly positioned on the lower-left quadrant of a square domain.\n=#\n\n# The error is calculated by comparing the numerically calculated streamfunction field with the exact solution for the streamfunction field. We therefore need a function to calculate the exact streamfunction.\nfunction ψ_vortex!(ψ::Nodes{Dual,nx,ny},vortex::Vortex,g::PhysicalGrid) where {nx,ny}\n x,y = coordinates(ψ,g)\n for i in 2:nx-1, j in 2:ny-1\n r = sqrt((x[i]-vortex.x)^2+(y[j]-vortex.y)^2)\n ψ[i,j] = ψ_vortex(r,vortex.Γ)\n end\nend\n\nfunction ψ_vortex(r::Real,Γ::Real)\n return -Γ/(2π)*log(r)\nend\n\n# We create four vortices with random strenghts, randomly positioned in the lower-left quadrant of the domain.\nnv = 4;\nvl = Vortex.(-Lx/4 .+ 0.4*Lx*(rand(nv).-0.5),-Lx/4 .+ 0.4*Lx*(rand(nv).-0.5),0.5*rand(nv).+0.5);\n\n# Next, we create a series of grids, with each grid doubling the number of grid points of the previous grid in each direction.\ngrids = [PhysicalGrid(xlim,ylim,Lx/(nx-2)) for nx in [2^p for p in 5:9]];\n\n# The error is calculated as $\\epsilon = \\Vert \\psi(\\mathsf{x},\\mathsf{y})/\\Delta x - \\mathsf{s} \\Vert_2 / \\Vert \\mathsf{s} \\Vert_2$, for which we use the `norm` function.\nusing LinearAlgebra: norm\n\n# We now loop over the grids and calculate the error.\nerrors = []\ngridspacings = []\nfor g in grids\n ## LGF\n local model = VortexModel(g,vortices=vl)\n s_lgf = streamfunction(model);\n\n ## Exact solution\n s_exact = Nodes(Dual,size(g))\n s_temp = Nodes(Dual,size(g))\n for v in vl\n ψ_vortex!(s_temp,v,g)\n s_exact += s_temp\n end\n\n ## Bring to same reference level. A constant value can be added/subtracted to any potential flow solution\n s_lgf .-= s_lgf[g.I0[1],2];\n s_exact .-= s_exact[g.I0[1],2];\n\n error = s_lgf-s_exact\n idx = g.I0[1] + 1 : g.N[1] - 1 # Only look at top right corner\n push!(errors,norm(error[idx,idx])/norm(s_lgf[idx,idx]))\n push!(gridspacings,g.Δx)\nend\n\n# And finally, we create a log-log plot of the error versus the grid spacing.\nfirstorder=(errors[end]/gridspacings[end].*gridspacings).^1\nsecondorder=(sqrt(errors[end])/gridspacings[end].*gridspacings).^2\np=plot(gridspacings,errors,xaxis=:log,yaxis=:log,marker=:circle,lab=\"error\",xlabel=\"dx\",legend=:bottomright,title=\"Error\")\nplot!(gridspacings,firstorder,lab=\"1st order\",linestyle=:dot,linecolor=:black)\nplot!(gridspacings,secondorder,lab=\"2nd order\",linestyle=:dash,linecolor=:black)\n\n#=\n## Corotating point vortices\nNow we will try advancing a vortex model in time. The simplest unsteady vortex model consists of two point vortices. When both point vortices have the same strength, they will rotate around each other on a trajectory that is easy to describe analytically. In this example, we will compare the analytical and simulated trajectories during one revolution.\n=#\n\n# We create two vortices at a distance $d$ from each other and give them a strength $\\Gamma$\nd = Lx/2\nΓ = 1\nv1 = Vortex(d/2,0.0,Γ);\nv2 = Vortex(-d/2,0.0,Γ);\n\n# We can analytically determine the time $T$ it takes for these vortices to complete one revolution around their centroid.\nVθ = Γ/(2*π*d); # Analytical tangential velocity\nT = π*d/Vθ # Analytical period\n\n# Let's now create a vortex model with the two point vortices.\nmodel = VortexModel(g,vortices=[v1,v2]);\n\n# If we update the positions of the point vortices repeatedly to simulate the model advancing in time from $t=0$ to $t=T$, we can check if they end up again at their original positions.\ntspan = (0.0,T);\n\n# To step in time, we can simply update the position of the $q$th vortex as $X^{n+1}_q = X^{n}_q + Δt Ẋ^{n}_q$ (forward Euler) in a for-loop. Alternatively, we can make use of the `OrdinaryDiffEq.jl` package and use, for example, their fourth-order Runge-Kutta time stepping scheme.\n\nimport OrdinaryDiffEq\n\n#= To construct the `ODEProblem` from this package, we will have to provide a right-hand side function that computes the velocities $Ẋ$ of the vortices, which is the local flow velocity at their positions. These velocities are obtained using `vortexvelocities`, which regularizes the vorticity to the grid, solves the potential flow system, and interpolates the velocities from the grid to the vortex locations as\n\n$\\left(U_{q}, V_{q}\\right)=\\sum_{i, j} \\mathsf{v}_{i j} d\\left(\\frac{\\mathsf{x}_{i}-X_{q}}{\\Delta x}\\right)\\left(\\frac{\\mathsf{y}_{j}-Y_{q}}{\\Delta x}\\right),$\n\nwhere $v$ is the velocity field on the nodes.\n=#\n\nfunction rhs(X,model,t)\n setvortexpositions!(model,X)\n Ẋ = vortexvelocities!(model)\n return Ẋ\nend\n\n# We finally create the problem and solve it with a fourth-order Runge-Kutta time stepping scheme.\nX = getvortexpositions(model)\nprob = OrdinaryDiffEq.ODEProblem(rhs,X,tspan,model);\nsol = OrdinaryDiffEq.solve(prob,dt=0.1,OrdinaryDiffEq.RK4(),dense=false,adaptive=false);\n\n# When we plot the x- and y-position versus time of the first vortex, we see it completed one revolution.\nplot(sol.t,map(s->s.u[1],sol.u),xlabel='t',label=\"x₁\")\nplot!(sol.t,map(s->s.v[1],sol.u),label=\"y₁\")\n\n#jl @testset \"Corotating point vortices\" begin\n#jl @test isapprox(sol.u[end].u[1], 0.5; atol = 1e-2)\n#jl @test isapprox(sol.u[end].u[2], -0.5; atol = 1e-2)\n#jl @test isapprox(sol.u[end].v[1], 0.0; atol = 1e-2)\n#jl @test isapprox(sol.u[end].v[2], 0.0; atol = 1e-2)\n#jl end\n\n#=\n## Corotating vortex patches\nA more complex example is the evolution of two circular regions of spatially uniform vorticity that have an equal radius $r_0$ and circulation $\\Gamma$, and whose centers are separated by a distance $d_0$. If $r_0/d_0$ is small enough, these two vortex patches can be regarded as two point vortices with the same circulation and separation. We therefore assume the period of this system is approximately the same as the the period for the point vortices case.\n=#\n\n#md # ```@setup 1.-Basic-potential-flow-problem\n#md # xlim = (-2,2);\n#md # ylim = (-2,2);\n#md # Δx = 0.05;\n#md # g = PhysicalGrid(xlim,ylim,Δx);\n#md # ```\n#!md xlim = (-2,2);\n#!md ylim = (-2,2);\n#!md Δx = 0.05;\n#!md g = PhysicalGrid(xlim,ylim,Δx);\n\n# We discretize the vortex patches with point vortices arranged on concentric rings using the following function.\n\nfunction vortexpatch!(vort,xc,yc,Γ,radius,nring)\n Δr = radius/(nring-1/2)\n dΓ = Γ/(1+8*nring*(nring-1)/2)\n push!(vort,Vortex(xc,yc,dΓ))\n for ir in 1:nring-1\n nθ = 8*ir\n for j = 0:nθ-1\n push!(vort,Vortex(xc + ir*Δr*cos(2π*j/nθ),yc + ir*Δr*sin(2π*j/nθ),dΓ))\n end\n end\n return vort\nend\n\nvortexpatch(xc,yc,Γ,radius,nring) = vortexpatch!(Vortex[],xc,yc,Γ,radius,nring)\n\n# We will simulate two cases with different values for $r_0/d_0$, the ratio of the vortex patch radius to the distance between them.\nd0 = d\nanims = []\nfor r0 in [0.2*d0, 0.4*d0]\n vortices = vcat(vortexpatch(0.0,0.0+d0/2,Γ,r0,10),vortexpatch(0.0,0.0-d0/2,Γ,r0,10));\n vortexcolors = vcat(fill(:blue,length(vortices)÷2),fill(:red,length(vortices)÷2));\n local model = VortexModel(g,vortices=vortices);\n local X = getvortexpositions(model)\n local prob = OrdinaryDiffEq.ODEProblem(rhs,X,tspan,model);\n local sol = OrdinaryDiffEq.solve(prob,dt=0.1,OrdinaryDiffEq.RK4(),dense=false,adaptive=false);\n anim = @animate for i=1:length(sol.t)-1\n plot(xlims=xlim,ylims=ylim,ratio=:equal,legend=:none,title=\"r0/d0 = $(r0/d0)\")\n scatter!(sol.u[i].u,sol.u[i].v,markerstrokewidth=0,markersize=3,color=vortexcolors)\n end\n push!(anims,anim)\nend\n\ngif(anims[1])\n\n# If the ratio $r_0/d_0$ is big enough, the two vortex patches merge with eachother, a result that has been widely reported in literature [^1].\n\ngif(anims[2])\n\n# [^1]: Eldredge J. D. (2019) \"Mathematical Modeling of Unsteady Inviscid Flows, Interdisciplinary Applied Mathematics\" *Springer*, vol. 50.\n", "meta": {"hexsha": "775c083006fa1092fd6035916c644ec16254fa29", "size": 10108, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/literate/1.-Basic-potential-flow-problem.jl", "max_stars_repo_name": "JuliaIBPM/GridPotentialFlow.jl", "max_stars_repo_head_hexsha": "b24127d036ed54a588a11ebedb35544acb8dea53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-02-25T02:10:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-09T22:51:52.000Z", "max_issues_repo_path": "test/literate/1.-Basic-potential-flow-problem.jl", "max_issues_repo_name": "JuliaIBPM/GridPotentialFlow.jl", "max_issues_repo_head_hexsha": "b24127d036ed54a588a11ebedb35544acb8dea53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-04-01T20:39:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-15T17:46:44.000Z", "max_forks_repo_path": "test/literate/1.-Basic-potential-flow-problem.jl", "max_forks_repo_name": "JuliaIBPM/GridPotentialFlow.jl", "max_forks_repo_head_hexsha": "b24127d036ed54a588a11ebedb35544acb8dea53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.7962962963, "max_line_length": 459, "alphanum_fraction": 0.7120102889, "num_tokens": 3132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9525741281688026, "lm_q2_score": 0.8918110339361276, "lm_q1q2_score": 0.8495161181430252}} {"text": "## Basic understanding of logit regression. \n\nusing DataFrames\nusing CSV\nusing GLM\nusing FreqTables\n\nobs = CSV.File(\"./logit_regression/logit_regression_data.csv\", header=true) |> DataFrame\n\n## summary of methods.\n## want to model variable p in range (0, 1). This is really hard to do. \n## probability is linked with odds ratio = prob of success / prob of failure\n## taking the log of this is the log odds ratio. \n## how do we transform p ∈ (0, 1) to odds ∈ (0, ∞)\n## then take the log of odds to map to (-∞, ∞)\n## This transformation is called logit transformation. The other common choice is the probit transformation,\n\n## so regression of p is \n## log(p/(1-p)) = linear predictors\n\n## now lets see what this means in the sample data. \n# for the purpose of illustration.\n# The data set has 200 observations and the outcome variable used will be hon, indicating if a student is in\n# an honors class or not. So our p = prob(hon=1). \n\n# Model 1, no predictors\nols = glm(@formula(hon ~ 1), obs, Binomial(), LogitLink())\ncoef(ols) # so the intercept here is the log odds -1.12\n# taking the exponential gives us the odds ratio. I.e. what are the odds of getting into a honors class\nexp.(coef(ols))\nexp.(coef(ols)) ./ (1 .+ exp.(coef(ols))) # we can get p back as well\n\n# we can verify all of this by looking at a frequnecy table\n# lets look at the FreqTables\n#freqtable(obs, :hon)\n\n# Model 2, a single predictor: female\nols = glm(@formula(hon ~ female), obs, Binomial(), LogitLink())\ncoef(ols) ## gets the log odds\nexp.(coef(ols)) ## gets the odds ratio \n## and can even calculate the prob given whether person is male or female\n\n# here theintercept of -1.471 is the log odds for males since male is the reference group (female = 0). \n# so this means the odds ratio is 0.23 \n\n# Using the frequency for males, we can confirm this: log(.23) = -1.47.\n\n# Model 3, using math\nols = glm(@formula(hon ~ math), obs, Binomial(), LogitLink())\ncoef(ols) ## gets the log odds\nexp.(coef(ols)) ## gets the odds ratio \n## and can even calculate the prob given math score. \n\n# Model 3, using combination\nols = glm(@formula(hon ~ math + female + read), obs, Binomial(), LogitLink())\ncoef(ols) ## gets the log odds\nexp.(coef(ols)) ## gets the odds ratio \n## and can even calculate the prob given a different combination of predictors\n\n# This fitted model says that, holding math and reading at a fixed value, the odds of getting into an\n# honors class for females (female = 1)over the odds of getting into an honors class for males (female = 0)\n# is exp(.979948) = 2.66\n\n# Model 4, interaction term\nols = glm(@formula(hon ~ math + female + female*math), obs, Binomial(), LogitLink())\ncoef(ols) ## gets the log odds\nexp.(coef(ols)) ## gets the odds ratio \n", "meta": {"hexsha": "29fe48d1b797dd0614e56a17fdd86cb47e0ebaba", "size": 2744, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "regression_models/logit_regression.jl", "max_stars_repo_name": "affans/notebooks", "max_stars_repo_head_hexsha": "daf102cde8b99b8c48ef2434176b44ace2719d9d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "regression_models/logit_regression.jl", "max_issues_repo_name": "affans/notebooks", "max_issues_repo_head_hexsha": "daf102cde8b99b8c48ef2434176b44ace2719d9d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "regression_models/logit_regression.jl", "max_forks_repo_name": "affans/notebooks", "max_forks_repo_head_hexsha": "daf102cde8b99b8c48ef2434176b44ace2719d9d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.3529411765, "max_line_length": 108, "alphanum_fraction": 0.7044460641, "num_tokens": 757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854138058637, "lm_q2_score": 0.8757869819218865, "lm_q1q2_score": 0.8493254406689053}} {"text": "\nfunction trapezoidal_rule(n::Int, a = -1.0, b = 1.0, ::Type{T} = typeof((b-a)/n)) where {T}\n grid = EquispacedGrid(n, a, b)\n weights = step(grid) * ones(T, n)\n weights[1] /= 2\n weights[end] /= 2\n grid, weights\nend\n\nfunction rectangular_rule(n::Int, a = 0.0, b = 1.0, ::Type{T} = typeof((b-a)/n)) where {T}\n grid = PeriodicEquispacedGrid(n, a, b)\n weight = step(grid)\n grid, Fill(weight,length(grid))\nend\n\n# The implementation of the first and second Fejer rule and of Clenshaw-Curtis\n# quadrature is based on the exposition in:\n# J. Waldvogel, Fast construction of the Fejer and Clenshaw-Curtis quadrature\n# rules, BIT 43(1):1-18, 2003.\nfunction fejer_vector1!(v)\n n = length(v)\n T = eltype(v)\n v[1] = T(2)\n for k in 1:(n-1)>>1\n r = T(2)/(1-4k^2)*exp(im*k*T(pi)/n)\n v[k+1] = r\n v[n-k+1] = conj(r)\n end\n if iseven(n)\n v[n>>1+1] = 0\n end\n v\nend\n\nfunction fejer_first_rule(n::Int, ::Type{T} = Float64) where {T}\n v = zeros(Complex{T}, n)\n fejer_vector1!(v)\n ChebyshevNodes{T}(n), real(ifft(v))\nend\n\nfunction fejer_vector2!(v)\n n = length(v)\n T = eltype(v)\n v[1] = T(2)\n for k in 1:(n-1)>>1\n r = T(2)/(1-4k^2)\n v[k+1] = r\n v[n-k+1] = r\n end\n if iseven(n)\n k = n>>1-1\n v[k+1] = T(2)/(1-4k^2)\n v[n>>1+1] = T(n-3)/(2*(n>>1)-1) - 1\n end\n v\nend\n\n# TODO: verify, is this correct?\nfunction fejer_second_rule(n::Int, ::Type{T} = Float64) where {T}\n v = zeros(T, n)\n weights = zeros(T, n+1)\n fejer_vector2!(v)\n weights[1:n] = real(ifft(v))\n weights[n+1] = weights[1]\n ChebyshevExtremae{T}(n+1), weights\nend\n\nfunction cc_vector_g!(g)\n n = length(g)\n T = eltype(g)\n w0cc = one(T) / (n^2-1+mod(n,2))\n for k in 1:n\n g[k] = -w0cc\n end\n if iseven(n)\n g[n>>1+1] = w0cc * ((2-mod(n,2))*n-1)\n end\n g\nend\n\nfunction clenshaw_curtis(n, ::Type{T} = Float64) where {T}\n v = zeros(T, n)\n g = zeros(T, n)\n weights = zeros(T, n+1)\n fejer_vector2!(v)\n cc_vector_g!(g)\n weights[1:n] = real(ifft(v+g))\n weights[n+1] = weights[1]\n ChebyshevExtremae{T}(n+1), weights\nend\n\n\nfunction rescale_cc_quad(x, w, a, b)\n y = (reverse(x).+1)/2 * (b-a) .+ a\n v = w .* (b-a)/2\n y,v\nend\n\nfunction rescale_fejer_quad(x, w, a, b)\n y = (x.+1)/2 * (b-a) .+ a\n v = w .* (b-a)/2\n y,v\nend\n\nfunction graded_rule(sigma, a, b, M, n, T = Float64, ndiff = 2)\n xg = zeros(T, 0)\n wg = zeros(T, 0)\n q1 = one(T)\n for m = M-1:-1:1\n x,w = BasisFunctions.fejer_first_rule(n, T)\n q0 = sigma*q1\n xs,ws = rescale_fejer_quad(x, w, q0, q1)\n xg = [xg; xs]\n wg = [wg; ws]\n q1 = q0\n n -= ndiff\n end\n x,w = BasisFunctions.fejer_first_rule(n, T)\n xs,ws = rescale_fejer_quad(x, w, 0, q1)\n xg = [xg; xs]\n wg = [wg; ws]\n a .+ xg*(b-a), wg * (b-a)\nend\n", "meta": {"hexsha": "6006266e50258b9a203a2a0b1c144f6cbe15b53e", "size": 2899, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/sampling/quadrature.jl", "max_stars_repo_name": "JuliaApproximation/BasisFunctions.jl", "max_stars_repo_head_hexsha": "9f2ab9cae1394cbaede565db1036fbf0fbd1da9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-06-21T03:12:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T03:03:32.000Z", "max_issues_repo_path": "src/sampling/quadrature.jl", "max_issues_repo_name": "JuliaApproximation/BasisFunctions.jl", "max_issues_repo_head_hexsha": "9f2ab9cae1394cbaede565db1036fbf0fbd1da9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28, "max_issues_repo_issues_event_min_datetime": "2020-01-07T17:23:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T17:50:16.000Z", "max_forks_repo_path": "src/sampling/quadrature.jl", "max_forks_repo_name": "JuliaApproximation/BasisFunctions.jl", "max_forks_repo_head_hexsha": "9f2ab9cae1394cbaede565db1036fbf0fbd1da9c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:51:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T12:00:34.000Z", "avg_line_length": 23.3790322581, "max_line_length": 91, "alphanum_fraction": 0.5329423939, "num_tokens": 1159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539661002182845, "lm_q2_score": 0.8902942159342104, "lm_q1q2_score": 0.8493105012216541}} {"text": "# ---\n# title: 258. Add Digits\n# id: problem258\n# author: zhwang\n# date: 2022-03-03\n# difficulty: Easy\n# categories: Math\n# link: \n# hidden: true\n# ---\n# \n# Given a non-negative integer `num`, repeatedly add all its digits until the\n# result has only one digit.\n# \n# **Example:**\n# \n# \n# \n# Input: 38\n# Output: 2 \n# Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2. \n# Since 2 has only one digit, return it.\n# \n# \n# **Follow up:** \n# Could you do it without any loop/recursion in O(1) runtime?\n# \n# \n## @lc code=start\nusing LeetCode\n\nfunction add_digits(num::Int)::Int\n num <= 9 && return num\n return iszero(num % 9) ? 9 : num % 9\nend\n## @lc code=end\n", "meta": {"hexsha": "e59974d737a5cfa8f262f88e65911fc4a8a8186b", "size": 761, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/258.add-digits.jl", "max_stars_repo_name": "RexWzh/LeetCode.jl", "max_stars_repo_head_hexsha": "d86109b9d5a15491304ff9d2ee66e506f60d2146", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/problems/258.add-digits.jl", "max_issues_repo_name": "RexWzh/LeetCode.jl", "max_issues_repo_head_hexsha": "d86109b9d5a15491304ff9d2ee66e506f60d2146", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/problems/258.add-digits.jl", "max_forks_repo_name": "RexWzh/LeetCode.jl", "max_forks_repo_head_hexsha": "d86109b9d5a15491304ff9d2ee66e506f60d2146", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.5675675676, "max_line_length": 77, "alphanum_fraction": 0.5978975033, "num_tokens": 247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778048911613, "lm_q2_score": 0.8872045996818986, "lm_q1q2_score": 0.8493012716728294}} {"text": "using Plots\n\n# number of points to randomly generate in the square [(0,0), (0,1), (1,1), (1,0)]\nN = 100_000\n\n\"function checks weather a given point is in the circle of radius equal to 1\"\nis_in( (x,y) ) = if x^2 + y^2 < 1\n 1\nelse\n 0\nend\n\nall_points = [ (rand(), rand()) for _ in 1:N]\npoints_in = [ p for p in all_points if is_in(p) == 1]\npoints_out = [ p for p in all_points if is_in(p) == 0]\n\nmyPI = 4 * length(points_in) / N\n\nplot( [(0,0), (0,1), (1,1), (1,0), (0,0)],\n xlims = (0,1), ylims = (0,1),\n aspect_ratio=:equal, \n leg=nothing)\nplot!( [(cos(x), sin(x)) for x in 0:0.01:2*pi]) \nscatter!(points_in)\nscatter!(points_out)\n\nprint(\"PI = $(myPI)\")", "meta": {"hexsha": "a8cea94a7203cb5fa9e50b7ae0afa69f96aae410", "size": 665, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "monte-carlo-pi.jl", "max_stars_repo_name": "appblue/monte-carlo-pi-calculation", "max_stars_repo_head_hexsha": "3e59d7ed03f8b674fe5558b63bc5e2ced12134df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "monte-carlo-pi.jl", "max_issues_repo_name": "appblue/monte-carlo-pi-calculation", "max_issues_repo_head_hexsha": "3e59d7ed03f8b674fe5558b63bc5e2ced12134df", "max_issues_repo_licenses": ["MIT"], "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-pi.jl", "max_forks_repo_name": "appblue/monte-carlo-pi-calculation", "max_forks_repo_head_hexsha": "3e59d7ed03f8b674fe5558b63bc5e2ced12134df", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6296296296, "max_line_length": 82, "alphanum_fraction": 0.5939849624, "num_tokens": 256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995723244553, "lm_q2_score": 0.8791467643431002, "lm_q1q2_score": 0.8491674836894293}} {"text": " include(\"num_integration.jl\")\n\n func(x) = x^2 * sin(2*x) + exp(-sin(3*x)) # function that will be integrated from 0 to 5\n \n # evaluating a numerical integration using monte_carlo\n function mc_int(n::Int64,func::Function)\n \n # main variables\n sum = 0.\n crude_mc = 0.\n \n # monte-carlo evaluation\n for i in 1:n\n x = rand() # sorting numbers between 0 and 1\n fx = func(x)\n crude_mc += fx \n sum += fx*fx\n end\n \n crude_mc = crude_mc / n\n sum = sum / n\n variance = sum -(crude_mc*crude_mc)\n \n return crude_mc, variance\n\n end\n \n\n\n # calculation\n n = 1000000\n a = 0 \n b = 1\n\n It = integration(a,b,n,func)\n Imc = mc_int(n,func)\n\n println(\"Trapezoidal integration with $n steps = \",It)\n println(\"Monte-carlo integration with $n steps = \",Imc)\n\n\n", "meta": {"hexsha": "653135d531195e38133af575ce78b278745a8543", "size": 817, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/monte_carlo.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/monte_carlo.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/monte_carlo.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": 19.4523809524, "max_line_length": 90, "alphanum_fraction": 0.5948592411, "num_tokens": 261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172688214137, "lm_q2_score": 0.8947894597898776, "lm_q1q2_score": 0.8490811703539988}} {"text": "# Descriptive Statistics\n\n\n#############################\n#\n# Location\n#\n#############################\n\n# Geometric mean\n\"\"\"\n geomean(a)\n\nReturn the geometric mean of a collection.\n\"\"\"\ngeomean(a) = exp(mean(log, a))\n\n# Harmonic mean\n\"\"\"\n harmmean(a)\n\nReturn the harmonic mean of a collection.\n\"\"\"\nharmmean(a) = inv(mean(inv, a))\n\n# Generalized mean\n\"\"\"\n genmean(a, p)\n\nReturn the generalized/power mean with exponent `p` of a real-valued array,\ni.e. ``\\\\left( \\\\frac{1}{n} \\\\sum_{i=1}^n a_i^p \\\\right)^{\\\\frac{1}{p}}``, where `n = length(a)`.\nIt is taken to be the geometric mean when `p == 0`.\n\"\"\"\nfunction genmean(a, p::Real)\n if p == 0\n return geomean(a)\n end\n\n # At least one of `x` or `p` must not be an int to avoid domain errors when `p` is a negative int.\n # We choose `x` in order to exploit exponentiation by squaring when `p` is an int.\n r = mean(a) do x\n float(x)^p\n end\n return r^inv(p)\nend\n\n# compute mode, given the range of integer values\n\"\"\"\n mode(a, [r])\n mode(a::AbstractArray, wv::AbstractWeights)\n\nReturn the mode (most common number) of an array, optionally\nover a specified range `r` or weighted via a vector `wv`.\nIf several modes exist, the first one (in order of appearance) is returned.\n\"\"\"\nfunction mode(a::AbstractArray{T}, r::UnitRange{T}) where T<:Integer\n isempty(a) && throw(ArgumentError(\"mode is not defined for empty collections\"))\n len = length(a)\n r0 = r[1]\n r1 = r[end]\n cnts = zeros(Int, length(r))\n mc = 0 # maximum count\n mv = r0 # a value corresponding to maximum count\n for i = 1:len\n @inbounds x = a[i]\n if r0 <= x <= r1\n @inbounds c = (cnts[x - r0 + 1] += 1)\n if c > mc\n mc = c\n mv = x\n end\n end\n end\n return mv\nend\n\n\"\"\"\n modes(a, [r])::Vector\n mode(a::AbstractArray, wv::AbstractWeights)::Vector\n\nReturn all modes (most common numbers) of an array, optionally over a\nspecified range `r` or weighted via vector `wv`.\n\"\"\"\nfunction modes(a::AbstractArray{T}, r::UnitRange{T}) where T<:Integer\n r0 = r[1]\n r1 = r[end]\n n = length(r)\n cnts = zeros(Int, n)\n # find the maximum count\n mc = 0\n for i = 1:length(a)\n @inbounds x = a[i]\n if r0 <= x <= r1\n @inbounds c = (cnts[x - r0 + 1] += 1)\n if c > mc\n mc = c\n end\n end\n end\n # find all values corresponding to maximum count\n ms = T[]\n for i = 1:n\n @inbounds if cnts[i] == mc\n push!(ms, r[i])\n end\n end\n return ms\nend\n\n# compute mode over arbitrary iterable\nfunction mode(a)\n isempty(a) && throw(ArgumentError(\"mode is not defined for empty collections\"))\n cnts = Dict{eltype(a),Int}()\n # first element\n mc = 1\n mv, st = iterate(a)\n cnts[mv] = 1\n # find the mode along with table construction\n y = iterate(a, st)\n while y !== nothing\n x, st = y\n if haskey(cnts, x)\n c = (cnts[x] += 1)\n if c > mc\n mc = c\n mv = x\n end\n else\n cnts[x] = 1\n # in this case: c = 1, and thus c > mc won't happen\n end\n y = iterate(a, st)\n end\n return mv\nend\n\nfunction modes(a)\n isempty(a) && throw(ArgumentError(\"mode is not defined for empty collections\"))\n cnts = Dict{eltype(a),Int}()\n # first element\n mc = 1\n x, st = iterate(a)\n cnts[x] = 1\n # find the mode along with table construction\n y = iterate(a, st)\n while y !== nothing\n x, st = y\n if haskey(cnts, x)\n c = (cnts[x] += 1)\n if c > mc\n mc = c\n end\n else\n cnts[x] = 1\n # in this case: c = 1, and thus c > mc won't happen\n end\n y = iterate(a, st)\n end\n # find values corresponding to maximum counts\n return [x for (x, c) in cnts if c == mc]\nend\n\n# Weighted mode of arbitrary vectors of values\nfunction mode(a::AbstractVector, wv::AbstractWeights{T}) where T <: Real\n isempty(a) && throw(ArgumentError(\"mode is not defined for empty collections\"))\n length(a) == length(wv) ||\n throw(ArgumentError(\"data and weight vectors must be the same size, got $(length(a)) and $(length(wv))\"))\n\n # Iterate through the data\n mv = first(a)\n mw = first(wv)\n weights = Dict{eltype(a), T}()\n for (x, w) in zip(a, wv)\n _w = get!(weights, x, zero(T)) + w\n if _w > mw\n mv = x\n mw = _w\n end\n weights[x] = _w\n end\n\n return mv\nend\n\nfunction modes(a::AbstractVector, wv::AbstractWeights{T}) where T <: Real\n isempty(a) && throw(ArgumentError(\"mode is not defined for empty collections\"))\n length(a) == length(wv) ||\n throw(ArgumentError(\"data and weight vectors must be the same size, got $(length(a)) and $(length(wv))\"))\n\n # Iterate through the data\n mw = first(wv)\n weights = Dict{eltype(a), T}()\n for (x, w) in zip(a, wv)\n _w = get!(weights, x, zero(T)) + w\n if _w > mw\n mw = _w\n end\n weights[x] = _w\n end\n\n # find values corresponding to maximum counts\n return [x for (x, w) in weights if w == mw]\nend\n\n#############################\n#\n# quantile and friends\n#\n#############################\n\n\"\"\"\n percentile(x, p)\n\nReturn the `p`th percentile of a collection `x`, i.e. `quantile(x, p / 100)`.\n\"\"\"\npercentile(x, p) = quantile(x, p * 0.01)\n\n\"\"\"\n nquantile(x, n::Integer)\n\nReturn the n-quantiles of collection `x`, i.e. the values which\npartition `v` into `n` subsets of nearly equal size.\n\nEquivalent to `quantile(x, [0:n]/n)`. For example, `nquantiles(x, 5)`\nreturns a vector of quantiles, respectively at `[0.0, 0.2, 0.4, 0.6, 0.8, 1.0]`.\n\"\"\"\nnquantile(x, n::Integer) = quantile(x, (0:n)/n)\n\n\"\"\"\n quantilerank(itr, value; method=:inc)\n\nCompute the quantile position in the [0, 1] interval of `value` relative to collection `itr`.\n\nDifferent definitions can be chosen via the `method` keyword argument.\nLet `count_less` be the number of elements of `itr` that are less than `value`, \n`count_equal` the number of elements of `itr` that are equal to `value`, `n` the length of `itr`, \n`greatest_smaller` the highest value below `value` and `smallest_greater` the lowest value above `value`. \nThen `method` supports the following definitions:\n\n- `:inc` (default): Return a value in the range 0 to 1 inclusive. \nReturn `count_less / (n - 1)` if `value ∈ itr`, otherwise apply interpolation based on \ndefinition 7 of quantile in Hyndman and Fan (1996)\n(equivalent to Excel `PERCENTRANK` and `PERCENTRANK.INC`).\nThis definition corresponds to the lower semi-continuous inverse of\n[`quantile`](@ref) with its default parameters.\n\n- `:exc`: Return a value in the range 0 to 1 exclusive.\nReturn `(count_less + 1) / (n + 1)` if `value ∈ itr` otherwise apply interpolation \nbased on definition 6 of quantile in Hyndman and Fan (1996)\n(equivalent to Excel `PERCENTRANK.EXC`).\n\n- `:compete`: Return `count_less / (n - 1)` if `value ∈ itr`, otherwise \nreturn `(count_less - 1) / (n - 1)`, without interpolation\n(equivalent to MariaDB `PERCENT_RANK`, dplyr `percent_rank`).\n\n- `:tied`: Return `(count_less + count_equal/2) / n`, without interpolation.\nBased on the definition in Roscoe, J. T. (1975)\n(equivalent to `\"mean\"` kind of SciPy `percentileofscore`).\n\n- `:strict`: Return `count_less / n`, without interpolation\n(equivalent to `\"strict\"` kind of SciPy `percentileofscore`).\n\n- `:weak`: Return `(count_less + count_equal) / n`, without interpolation\n(equivalent to `\"weak\"` kind of SciPy `percentileofscore`).\n\n!!! note\n An `ArgumentError` is thrown if `itr` contains `NaN` or `missing` values\n or if `itr` contains fewer than two elements.\n\n# References\nRoscoe, J. T. (1975). [Fundamental Research Statistics for the Behavioral Sciences]\n(http://www.bryanburnham.net/wp-content/uploads/2014/07/Fundamental-Statistics-for-the-Behavioral-Sciences-v2.0.pdf#page=57)\",\n2nd ed., New York : Holt, Rinehart and Winston.\n\nHyndman, R.J and Fan, Y. (1996) \"[Sample Quantiles in Statistical Packages]\n(https://www.amherst.edu/media/view/129116/original/Sample+Quantiles.pdf)\",\n*The American Statistician*, Vol. 50, No. 4, pp. 361-365.\n\n# Examples\n```julia\njulia> using StatsBase\n\njulia> v1 = [1, 1, 1, 2, 3, 4, 8, 11, 12, 13];\n\njulia> v2 = [1, 2, 3, 5, 6, missing, 8];\n\njulia> v3 = [1, 2, 3, 4, 4, 5, 6, 7, 8, 9];\n\njulia> quantilerank(v1, 2)\n0.3333333333333333\n\njulia> quantilerank(v1, 2, method=:exc), quantilerank(v1, 2, method=:tied)\n(0.36363636363636365, 0.35)\n\n# use `skipmissing` for vectors with missing entries.\njulia> quantilerank(skipmissing(v2), 4)\n0.5\n\n# use broadcasting with `Ref` to compute quantile rank for multiple values\njulia> quantilerank.(Ref(v3), [4, 8])\n2-element Vector{Float64}:\n 0.3333333333333333\n 0.8888888888888888\n```\n\"\"\"\nfunction quantilerank(itr, value; method::Symbol=:inc)\n ((value isa Number && isnan(value)) || ismissing(value)) &&\n throw(ArgumentError(\"`value` cannot be NaN or missing\"))\n any(x -> ismissing(x) || (x isa Number && isnan(x)), itr) &&\n throw(ArgumentError(\"`itr` cannot contain missing or NaN entries\"))\n\n count_less = count_equal = n = 0\n greatest_smaller = smallest_greater = value\n for x in itr\n if x == value\n count_equal += 1\n elseif x < value\n count_less += 1\n if greatest_smaller == value || greatest_smaller < x\n greatest_smaller = x\n end\n else\n if smallest_greater == value || smallest_greater > x\n smallest_greater = x\n end\n end\n n += 1\n end\n\n n == 0 && throw(ArgumentError(\"`itr` is empty. Pass a collection with at least two elements\"))\n n == 1 && throw(ArgumentError(\"`itr` has only 1 value. Pass a collection with at least two elements\"))\n\n if method == :inc\n if greatest_smaller == value\n return 0.0\n elseif count_equal > 0\n return count_less / (n - 1)\n elseif smallest_greater == value\n return 1.0\n else\n lower = (count_less - 1) / (n - 1)\n upper = count_less / (n - 1)\n ratio = (value - greatest_smaller) / (smallest_greater - greatest_smaller)\n return lower + ratio * (upper - lower)\n end\n elseif method == :exc\n if count_less == 0 && count_equal == 0\n return 0.0\n elseif count_less == 0\n return 1.0 / (n + 1)\n elseif count_equal > 0\n return (count_less + 1) / (n + 1)\n elseif smallest_greater == value\n return 1.0\n else\n lower = count_less / (n + 1)\n upper = (count_less + 1) / (n + 1)\n ratio = (value - greatest_smaller) / (smallest_greater - greatest_smaller)\n return lower + ratio * (upper - lower)\n end\n elseif method == :compete\n if value > maximum(itr)\n return 1.0\n elseif value ≤ minimum(itr) \n return 0.0\n else\n value ∈ itr && (count_less += 1)\n return (count_less - 1) / (n - 1)\n end \n elseif method == :tied\n return (count_less + count_equal/2) / n\n elseif method == :strict\n return count_less / n\n elseif method == :weak\n return (count_less + count_equal) / n\n else\n throw(ArgumentError(\"method=:$method is not valid. Pass :inc, :exc, :compete, :tied, :strict or :weak.\"))\n end\nend\n\n\"\"\"\n percentilerank(itr, value; method=:inc)\n\nReturn the `q`th percentile of `value` in collection `itr`, i.e. [`quantilerank(itr, value)`](@ref) * 100.\n\nSee the [`quantilerank`](@ref) docstring for more details.\n\"\"\"\npercentilerank(itr, value; method::Symbol=:inc) = quantilerank(itr, value, method=method) * 100\n\n#############################\n#\n# Dispersion\n#\n#############################\n\n# span, i.e. the range minimum(x):maximum(x)\n\"\"\"\n span(x)\n\nReturn the span of a collection, i.e. the range `minimum(x):maximum(x)`.\nThe minimum and maximum of `x` are computed in one pass using `extrema`.\n\"\"\"\nspan(x) = ((a, b) = extrema(x); a:b)\n\n# Variation coefficient: std / mean\n\"\"\"\n variation(x, m=mean(x))\n\nReturn the coefficient of variation of collection `x`, optionally specifying\na precomputed mean `m`. The coefficient of variation is the ratio of the\nstandard deviation to the mean.\n\"\"\"\nvariation(x, m) = stdm(x, m) / m\nvariation(x) = ((m, s) = mean_and_std(x); s/m)\n\n# Standard error of the mean: std / sqrt(len)\n# Code taken from var in the Statistics stdlib module\n\n# faster computation of real(conj(x)*y)\nrealXcY(x::Real, y::Real) = x*y\nrealXcY(x::Complex, y::Complex) = real(x)*real(y) + imag(x)*imag(y)\n\n\"\"\"\n sem(x; mean=nothing)\n sem(x::AbstractArray[, weights::AbstractWeights]; mean=nothing)\n\nReturn the standard error of the mean for a collection `x`.\nA pre-computed `mean` may be provided.\n\nWhen not using weights, this is the (sample) standard deviation\ndivided by the sample size. If weights are used, the \nvariance of the sample mean is calculated as follows:\n\n* `AnalyticWeights`: Not implemented.\n* `FrequencyWeights`: ``\\\\frac{\\\\sum_{i=1}^n w_i (x_i - \\\\bar{x_i})^2}{(\\\\sum w_i) (\\\\sum w_i - 1)}``\n* `ProbabilityWeights`: ``\\\\frac{n}{n-1} \\\\frac{\\\\sum_{i=1}^n w_i^2 (x_i - \\\\bar{x_i})^2}{\\\\left( \\\\sum w_i \\\\right)^2}``\n\nThe standard error is then the square root of the above quantities.\n\n# References\n\nCarl-Erik Särndal, Bengt Swensson, Jan Wretman (1992). Model Assisted Survey Sampling.\nNew York: Springer. pp. 51-53.\n\"\"\"\nfunction sem(x; mean=nothing)\n if isempty(x)\n # Return the NaN of the type that we would get for a nonempty x\n T = eltype(x)\n _mean = mean === nothing ? zero(T) / 1 : mean\n z = abs2(zero(T) - _mean)\n return oftype((z + z) / 2, NaN)\n elseif mean === nothing\n n = 0\n y = iterate(x)\n value, state = y\n # Use Welford algorithm as seen in (among other places)\n # Knuth's TAOCP, Vol 2, page 232, 3rd edition.\n _mean = value / 1\n sse = real(zero(_mean))\n while y !== nothing\n value, state = y\n y = iterate(x, state)\n n += 1\n new_mean = _mean + (value - _mean) / n\n sse += realXcY(value - _mean, value - new_mean)\n _mean = new_mean\n end\n else\n n = 1\n y = iterate(x)\n value, state = y\n sse = abs2(value - mean)\n while (y = iterate(x, state)) !== nothing\n value, state = y\n n += 1\n sse += abs2(value - mean)\n end\n end\n variance = sse / (n - 1)\n return sqrt(variance / n)\nend\n\nfunction sem(x::AbstractArray; mean=nothing) \n if isempty(x)\n # Return the NaN of the type that we would get for a nonempty x\n T = eltype(x)\n _mean = mean === nothing ? zero(T) / 1 : mean\n z = abs2(zero(T) - _mean)\n return oftype((z + z) / 2, NaN)\n end\n return sqrt(var(x; mean=mean, corrected=true) / length(x))\nend\n\nfunction sem(x::AbstractArray, weights::UnitWeights; mean=nothing)\n if length(x) ≠ length(weights)\n throw(DimensionMismatch(\"array and weights do not have the same length\"))\n end\n return sem(x; mean=mean)\nend\n\n\n# Weighted methods for the above\nsem(x::AbstractArray, weights::FrequencyWeights; mean=nothing) =\n sqrt(var(x, weights; mean=mean, corrected=true) / sum(weights))\n\nfunction sem(x::AbstractArray, weights::ProbabilityWeights; mean=nothing)\n if isempty(x)\n # Return the NaN of the type that we would get for a nonempty x\n return var(x, weights; mean=mean, corrected=true) / 0\n else\n _mean = mean === nothing ? Statistics.mean(x, weights) : mean\n # sum of squared errors = sse\n sse = sum(Broadcast.instantiate(Broadcast.broadcasted(x, weights) do x_i, w\n return abs2(w * (x_i - _mean))\n end))\n n = count(!iszero, weights)\n return sqrt(sse * n / (n - 1)) / sum(weights)\n end\nend\n\n# Median absolute deviation\n@irrational mad_constant 1.4826022185056018 BigFloat(\"1.482602218505601860547076529360423431326703202590312896536266275245674447622701\")\n\n\"\"\"\n mad(x; center=median(x), normalize=true)\n\nCompute the median absolute deviation (MAD) of collection `x` around `center`\n(by default, around the median).\n\nIf `normalize` is set to `true`, the MAD is multiplied by\n`1 / quantile(Normal(), 3/4) ≈ 1.4826`, in order to obtain a consistent estimator\nof the standard deviation under the assumption that the data is normally distributed.\n\"\"\"\nfunction mad(x; center=nothing, normalize::Union{Bool, Nothing}=nothing, constant=nothing)\n isempty(x) && throw(ArgumentError(\"mad is not defined for empty arrays\"))\n T = eltype(x)\n # Knowing the eltype allows allocating a single array able to hold both original values\n # and differences from the center, instead of two arrays\n S = isconcretetype(T) ? promote_type(T, typeof(middle(zero(T)))) : T\n x2 = x isa AbstractArray ? copyto!(similar(x, S), x) : collect(S, x)\n c = center === nothing ? median!(x2) : center\n if isconcretetype(T)\n x2 .= abs.(x2 .- c)\n else\n x2 = abs.(x2 .- c)\n end\n m = median!(x2)\n if normalize isa Nothing\n Base.depwarn(\"the `normalize` keyword argument will be false by default in future releases: set it explicitly to silence this deprecation\", :mad)\n normalize = true\n end\n if !isa(constant, Nothing)\n Base.depwarn(\"keyword argument `constant` is deprecated, use `normalize` instead or apply the multiplication directly\", :mad)\n m * constant\n elseif normalize\n m * mad_constant\n else\n m\n end\nend\n\n\"\"\"\n StatsBase.mad!(x; center=median!(x), normalize=true)\n\nCompute the median absolute deviation (MAD) of array `x` around `center`\n(by default, around the median), overwriting `x` in the process.\n`x` must be able to hold values of generated by calling `middle` on its elements\n(for example an integer vector is not appropriate since `middle` can produce\nnon-integer values).\n\nIf `normalize` is set to `true`, the MAD is multiplied by\n`1 / quantile(Normal(), 3/4) ≈ 1.4826`, in order to obtain a consistent estimator\nof the standard deviation under the assumption that the data is normally distributed.\n\"\"\"\nfunction mad!(x::AbstractArray;\n center=median!(x),\n normalize::Union{Bool,Nothing}=true,\n constant=nothing)\n isempty(x) && throw(ArgumentError(\"mad is not defined for empty arrays\"))\n x .= abs.(x .- center)\n m = median!(x)\n if normalize isa Nothing\n Base.depwarn(\"the `normalize` keyword argument will be false by default in future releases: set it explicitly to silence this deprecation\", :mad)\n normalize = true\n end\n if !isa(constant, Nothing)\n Base.depwarn(\"keyword argument `constant` is deprecated, use `normalize` instead or apply the multiplication directly\", :mad)\n m * constant\n elseif normalize\n m * mad_constant\n else\n m\n end\nend\n\n# Interquartile range\n\"\"\"\n iqr(x)\n\nCompute the interquartile range (IQR) of collection `x`, i.e. the 75th percentile\nminus the 25th percentile.\n\"\"\"\niqr(x) = (q = quantile(x, [.25, .75]); q[2] - q[1])\n\n# Generalized variance\n\"\"\"\n genvar(X)\n\nCompute the generalized sample variance of `X`. If `X` is a vector, one-column matrix,\nor other iterable, this is equivalent to the sample variance.\nOtherwise if `X` is a matrix, this is equivalent to the determinant of the covariance\nmatrix of `X`.\n\n!!! note\n The generalized sample variance will be 0 if the columns of the matrix of deviations\n are linearly dependent.\n\"\"\"\ngenvar(X::AbstractMatrix) = size(X, 2) == 1 ? var(vec(X)) : det(cov(X))\ngenvar(itr) = var(itr)\n\n# Total variation\n\"\"\"\n totalvar(X)\n\nCompute the total sample variance of `X`. If `X` is a vector, one-column matrix,\nor other iterable, this is equivalent to the sample variance.\nOtherwise if `X` is a matrix, this is equivalent to the sum of the diagonal elements\nof the covariance matrix of `X`.\n\"\"\"\ntotalvar(X::AbstractMatrix) = sum(var(X, dims=1))\ntotalvar(itr) = var(itr)\n\n#############################\n#\n# Z-scores\n#\n#############################\n\nfunction _zscore!(Z::AbstractArray, X::AbstractArray, μ::Real, σ::Real)\n # Z and X are assumed to have the same size\n iσ = inv(σ)\n if μ == zero(μ)\n for i = 1 : length(X)\n @inbounds Z[i] = X[i] * iσ\n end\n else\n for i = 1 : length(X)\n @inbounds Z[i] = (X[i] - μ) * iσ\n end\n end\n return Z\nend\n\n@generated function _zscore!(Z::AbstractArray{S,N}, X::AbstractArray{T,N},\n μ::AbstractArray, σ::AbstractArray) where {S,T,N}\n quote\n # Z and X are assumed to have the same size\n # μ and σ are assumed to have the same size, that is compatible with size(X)\n siz1 = size(X, 1)\n @nextract $N ud d->size(μ, d)\n if size(μ, 1) == 1 && siz1 > 1\n @nloops $N i d->(d>1 ? (1:size(X,d)) : (1:1)) d->(j_d = ud_d ==1 ? 1 : i_d) begin\n v = (@nref $N μ j)\n c = inv(@nref $N σ j)\n for i_1 = 1:siz1\n (@nref $N Z i) = ((@nref $N X i) - v) * c\n end\n end\n else\n @nloops $N i X d->(j_d = ud_d ==1 ? 1 : i_d) begin\n (@nref $N Z i) = ((@nref $N X i) - (@nref $N μ j)) / (@nref $N σ j)\n end\n end\n return Z\n end\nend\n\nfunction _zscore_chksize(X::AbstractArray, μ::AbstractArray, σ::AbstractArray)\n size(μ) == size(σ) || throw(DimensionMismatch(\"μ and σ should have the same size.\"))\n for i=1:ndims(X)\n dμ_i = size(μ,i)\n (dμ_i == 1 || dμ_i == size(X,i)) || throw(DimensionMismatch(\"X and μ have incompatible sizes.\"))\n end\nend\n\n\n\"\"\"\n zscore!([Z], X, μ, σ)\n\nCompute the z-scores of an array `X` with mean `μ` and standard deviation `σ`.\nz-scores are the signed number of standard deviations above the mean that an\nobservation lies, i.e. ``(x - μ) / σ``.\n\nIf a destination array `Z` is provided, the scores are stored\nin `Z` and it must have the same shape as `X`. Otherwise `X` is overwritten.\n\"\"\"\nfunction zscore!(Z::AbstractArray{ZT}, X::AbstractArray{T}, μ::Real, σ::Real) where {ZT<:AbstractFloat,T<:Real}\n size(Z) == size(X) || throw(DimensionMismatch(\"Z and X must have the same size.\"))\n _zscore!(Z, X, μ, σ)\nend\n\nfunction zscore!(Z::AbstractArray{<:AbstractFloat}, X::AbstractArray{<:Real},\n μ::AbstractArray{<:Real}, σ::AbstractArray{<:Real})\n size(Z) == size(X) || throw(DimensionMismatch(\"Z and X must have the same size.\"))\n _zscore_chksize(X, μ, σ)\n _zscore!(Z, X, μ, σ)\nend\n\nzscore!(X::AbstractArray{<:AbstractFloat}, μ::Real, σ::Real) = _zscore!(X, X, μ, σ)\n\nzscore!(X::AbstractArray{<:AbstractFloat}, μ::AbstractArray{<:Real}, σ::AbstractArray{<:Real}) =\n (_zscore_chksize(X, μ, σ); _zscore!(X, X, μ, σ))\n\n\n\"\"\"\n zscore(X, [μ, σ])\n\nCompute the z-scores of `X`, optionally specifying a precomputed mean `μ` and\nstandard deviation `σ`. z-scores are the signed number of standard deviations\nabove the mean that an observation lies, i.e. ``(x - μ) / σ``.\n\n`μ` and `σ` should be both scalars or both arrays. The computation is broadcasting.\nIn particular, when `μ` and `σ` are arrays, they should have the same size, and\n`size(μ, i) == 1 || size(μ, i) == size(X, i)` for each dimension.\n\"\"\"\nfunction zscore(X::AbstractArray{T}, μ::Real, σ::Real) where T<:Real\n ZT = typeof((zero(T) - zero(μ)) / one(σ))\n _zscore!(Array{ZT}(undef, size(X)), X, μ, σ)\nend\n\nfunction zscore(X::AbstractArray{T}, μ::AbstractArray{U}, σ::AbstractArray{S}) where {T<:Real,U<:Real,S<:Real}\n _zscore_chksize(X, μ, σ)\n ZT = typeof((zero(T) - zero(U)) / one(S))\n _zscore!(Array{ZT}(undef, size(X)), X, μ, σ)\nend\n\nzscore(X::AbstractArray{<:Real}) = ((μ, σ) = mean_and_std(X); zscore(X, μ, σ))\nzscore(X::AbstractArray{<:Real}, dim::Int) = ((μ, σ) = mean_and_std(X, dim); zscore(X, μ, σ))\n\n\n\n#############################\n#\n# entropy and friends\n#\n#############################\n\n\"\"\"\n entropy(p, [b])\n\nCompute the entropy of a collection of probabilities `p`,\noptionally specifying a real number `b` such that the entropy is scaled by `1/log(b)`.\nElements with probability 0 or 1 add 0 to the entropy.\n\"\"\"\nfunction entropy(p)\n if isempty(p)\n throw(ArgumentError(\"empty collections are not supported since they do not \" *\n \"represent proper probability distributions\"))\n end\n return -sum(xlogx, p)\nend\n\nentropy(p, b::Real) = entropy(p) / log(b)\n\n\"\"\"\n renyientropy(p, α)\n\nCompute the Rényi (generalized) entropy of order `α` of an array `p`.\n\"\"\"\nfunction renyientropy(p::AbstractArray{T}, α::Real) where T<:Real\n α < 0 && throw(ArgumentError(\"Order of Rényi entropy not legal, $(α) < 0.\"))\n\n s = zero(T)\n z = zero(T)\n scale = sum(p)\n\n if α ≈ 0\n for i = 1:length(p)\n @inbounds pi = p[i]\n if pi > z\n s += 1\n end\n end\n s = log(s / scale)\n elseif α ≈ 1\n for i = 1:length(p)\n @inbounds pi = p[i]\n if pi > z\n s -= pi * log(pi)\n end\n end\n s = s / scale\n elseif (isinf(α))\n s = -log(maximum(p))\n else # a normal Rényi entropy\n for i = 1:length(p)\n @inbounds pi = p[i]\n if pi > z\n s += pi ^ α\n end\n end\n s = log(s / scale) / (1 - α)\n end\n return s\nend\n\n\"\"\"\n crossentropy(p, q, [b])\n\nCompute the cross entropy between `p` and `q`, optionally specifying a real\nnumber `b` such that the result is scaled by `1/log(b)`.\n\"\"\"\nfunction crossentropy(p::AbstractArray{<:Real}, q::AbstractArray{<:Real})\n length(p) == length(q) || throw(DimensionMismatch(\"Inconsistent array length.\"))\n\n # handle empty collections\n if isempty(p)\n Base.depwarn(\n \"support for empty collections will be removed since they do not \" *\n \"represent proper probability distributions\",\n :crossentropy,\n )\n # return zero for empty arrays\n return xlogy(zero(eltype(p)), zero(eltype(q)))\n end\n\n # use pairwise summation (https://github.com/JuliaLang/julia/pull/31020)\n broadcasted = Broadcast.broadcasted(xlogy, vec(p), vec(q))\n return - sum(Broadcast.instantiate(broadcasted))\nend\n\ncrossentropy(p::AbstractArray{<:Real}, q::AbstractArray{<:Real}, b::Real) =\n crossentropy(p,q) / log(b)\n\n\n\"\"\"\n kldivergence(p, q, [b])\n\nCompute the Kullback-Leibler divergence from `q` to `p`,\nalso called the relative entropy of `p` with respect to `q`,\nthat is the sum `pᵢ * log(pᵢ / qᵢ)`. Optionally a real number `b`\ncan be specified such that the divergence is scaled by `1/log(b)`.\n\"\"\"\nfunction kldivergence(p::AbstractArray{<:Real}, q::AbstractArray{<:Real})\n length(p) == length(q) || throw(DimensionMismatch(\"Inconsistent array length.\"))\n\n # handle empty collections\n if isempty(p)\n Base.depwarn(\n \"support for empty collections will be removed since they do not \"*\n \"represent proper probability distributions\",\n :kldivergence,\n )\n # return zero for empty arrays\n pzero = zero(eltype(p))\n qzero = zero(eltype(q))\n return xlogy(pzero, zero(pzero / qzero))\n end\n\n # use pairwise summation (https://github.com/JuliaLang/julia/pull/31020)\n broadcasted = Broadcast.broadcasted(vec(p), vec(q)) do pi, qi\n # handle pi = qi = 0, otherwise `NaN` is returned\n piqi = iszero(pi) && iszero(qi) ? zero(pi / qi) : pi / qi\n return xlogy(pi, piqi)\n end\n return sum(Broadcast.instantiate(broadcasted))\nend\n\nkldivergence(p::AbstractArray{<:Real}, q::AbstractArray{<:Real}, b::Real) =\n kldivergence(p,q) / log(b)\n\n#############################\n#\n# summary\n#\n#############################\n\nstruct SummaryStats{T<:Union{AbstractFloat,Missing}}\n mean::T\n min::T\n q25::T\n median::T\n q75::T\n max::T\n nobs::Int\n nmiss::Int\nend\n\n\n\"\"\"\n summarystats(a)\n\nCompute summary statistics for a real-valued array `a`. Returns a\n`SummaryStats` object containing the mean, minimum, 25th percentile,\nmedian, 75th percentile, and maxmimum.\n\"\"\"\nfunction summarystats(a::AbstractArray{T}) where T<:Union{Real,Missing}\n # `mean` doesn't fail on empty input but rather returns `NaN`, so we can use the\n # return type to populate the `SummaryStats` structure.\n s = T >: Missing ? collect(skipmissing(a)) : a\n m = mean(s)\n R = typeof(m)\n n = length(a)\n ns = length(s)\n qs = if ns == 0\n R[NaN, NaN, NaN, NaN, NaN]\n elseif T >: Missing\n quantile!(s, [0.00, 0.25, 0.50, 0.75, 1.00])\n else\n quantile(s, [0.00, 0.25, 0.50, 0.75, 1.00])\n end\n SummaryStats{R}(m, qs..., n, n - ns)\nend\n\nfunction Base.show(io::IO, ss::SummaryStats)\n println(io, \"Summary Stats:\")\n @printf(io, \"Length: %i\\n\", ss.nobs)\n ss.nobs > 0 || return\n @printf(io, \"Missing Count: %i\\n\", ss.nmiss)\n @printf(io, \"Mean: %.6f\\n\", ss.mean)\n @printf(io, \"Minimum: %.6f\\n\", ss.min)\n @printf(io, \"1st Quartile: %.6f\\n\", ss.q25)\n @printf(io, \"Median: %.6f\\n\", ss.median)\n @printf(io, \"3rd Quartile: %.6f\\n\", ss.q75)\n @printf(io, \"Maximum: %.6f\\n\", ss.max)\nend\n\n\n\"\"\"\n describe(a)\n\nPretty-print the summary statistics provided by [`summarystats`](@ref):\nthe mean, minimum, 25th percentile, median, 75th percentile, and\nmaximum.\n\"\"\"\nDataAPI.describe(x) = describe(stdout, x)\nfunction DataAPI.describe(io::IO, a::AbstractArray{T}) where T<:Union{Real,Missing}\n show(io, summarystats(a))\n println(io, \"Type: $(string(eltype(a)))\")\nend\nfunction DataAPI.describe(io::IO, a::AbstractArray)\n println(io, \"Summary Stats:\")\n println(io, \"Length: $(length(a))\")\n println(io, \"Type: $(string(eltype(a)))\")\n println(io, \"Number Unique: $(length(unique(a)))\")\n return\nend\n", "meta": {"hexsha": "993c8da6b86755de1c6d0534c29dd2dc5e16fd18", "size": 30180, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/scalarstats.jl", "max_stars_repo_name": "ParadaCarleton/StatsBase.jl", "max_stars_repo_head_hexsha": "fddff35899aa57d9921a214fdd2264fae14af6ad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/scalarstats.jl", "max_issues_repo_name": "ParadaCarleton/StatsBase.jl", "max_issues_repo_head_hexsha": "fddff35899aa57d9921a214fdd2264fae14af6ad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/scalarstats.jl", "max_forks_repo_name": "ParadaCarleton/StatsBase.jl", "max_forks_repo_head_hexsha": "fddff35899aa57d9921a214fdd2264fae14af6ad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.835443038, "max_line_length": 153, "alphanum_fraction": 0.6036447979, "num_tokens": 8770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172630429475, "lm_q2_score": 0.8947894625955064, "lm_q1q2_score": 0.8490811678457978}} {"text": "# Basic Linear algebra\n# https://www.juliabox.com/notebook/notebooks/tutorials/intro-to-julia/11.%20Basic%20linear%20algebra.ipynb\n\nA = [1 2 3;\n 4 5 6;\n 7 8 9]\n\n@show A\n@show A' # conjuate transpose\n@show transpose(A)\n\nx = fill(1.0, (3,))\n\n@show typeof(A), typeof(x)\n\n@show A * x\n@show A' * A\n@show A'A #allows us to write this wiout `*`\n\n# Solving linear systems\n# The problem `Ax=b` for square A is solved by `\\` function\n\nA = [1 3 2;\n 3 2 4;\n 1 9 3]\n\nb = A*x\n@show A\\b # expected the value of `x`\n\n", "meta": {"hexsha": "ee26783f4df17682cb8d5b5aeb9a366f9ecbc864", "size": 517, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "officialTutorial/linear_algebra.jl", "max_stars_repo_name": "terasakisatoshi/juliaExer", "max_stars_repo_head_hexsha": "e3c2195f39de858915a3dcd47684eccbb7ecb552", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-02T01:24:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-04T12:03:25.000Z", "max_issues_repo_path": "officialTutorial/linear_algebra.jl", "max_issues_repo_name": "terasakisatoshi/juliaExer", "max_issues_repo_head_hexsha": "e3c2195f39de858915a3dcd47684eccbb7ecb552", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "officialTutorial/linear_algebra.jl", "max_forks_repo_name": "terasakisatoshi/juliaExer", "max_forks_repo_head_hexsha": "e3c2195f39de858915a3dcd47684eccbb7ecb552", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.2333333333, "max_line_length": 107, "alphanum_fraction": 0.6266924565, "num_tokens": 190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9553191309994467, "lm_q2_score": 0.8887587883361618, "lm_q1q2_score": 0.8490482733414233}} {"text": "\"\"\"\n iscoprime(a,b)\n\nCheck if the pair of polynomials `a` and `b` is coprime, that is, it has no common factors.\n\n# Examples\n\n```julia\njulia> a = Polynomial([1,2,3],:s);\njulia> b = Polynomial([1,2],:s);\njulia> iscoprime(a,b)\ntrue\n\njulia> a = Polynomial([1,2,3],:s);\njulia> b = a*Polynomial([1,2],:s);\njulia> iscoprime(a,b)\nfalse\n```\n\"\"\"\nfunction iscoprime(a::Polynomial,b::Polynomial)\n da = degree(a)\n db = degree(b)\n dx = db-1\n S = sylvestermatrix(a,b)\n return rank(S)==(da+db)\nend\n\n\"\"\"\n isschurstable(a)\n\nCheck if the polynomial `a` is Schur stable, that is, it has all its roots inside the unit disk.\n\n# Examples\n\n```julia\njulia> a = fromroots([-1/2,0, 2/3,-1/3im, 1/3im]);\njulia> isschurstable(a)\ntrue\n\njulia> a = fromroots([2,0, 2/3,-3im, 3im]);\njulia> !isschurstable(a)\nfalse\n```\n\"\"\"\nfunction isschurstable(a::Polynomial)\n r = roots(a)\n all(abs.(r) .<= 1)\nend\n\n\"\"\"\n ishurwitzstable(a::Polynomial)\n\nCheck if the `a` is Schur stable, that is, it has all its roots inside the left complex half-plane.\n\n# Examples\n\n```julia\njulia> a = fromroots([-1, -2, -3+4im, -3-4im]);\njulia> ishurwitzstable(a)\ntrue\n\njulia> a = fromroots([-1, -2, 3+4im, 3-4im]);\njulia> !ishurwitzstable(a)\nfalse\n```\n\"\"\"\nfunction ishurwitzstable(a::Polynomial)\n r = roots(a)\n return all(real(r) .<= 0)\nend\n\n\"\"\"\n isconjsymmetric(a::Polynomial)\n\nCheck if the scalar univariate polynomial `a` is conjugate symmetric, that is, if `a=ã`.\n\nFor a scalar univariate polynomial `a` with real coefficients, check if `a(s)=a(-s)`. If the coefficients are complex, the condition then extends to `a(s)=ā(-s)`, where `ā` is obtained from `a` by complex-conjugating the coefficients. A necessary and sufficient condition for conjugate symmetry is that the coefficients with odd powers of the variable are zero and the coefficients with even powers are real.\n\n# Examples\n```julia\njulia> a = Polynomial([1,0,2,0,3],:s)\nPolynomial(1 + 2*s^2 + 3*s^4)\n\njulia> isconjsymmetric(a)\ntrue\n```\n\"\"\"\nfunction isconjsymmetric(a::Polynomial)\n return isequal(a,cconj(a))\nend\n\n\"\"\"\n isconjsymmetric(a::LaurentPolynomial)\n\nCheck if the scalar univariate Laurent polynomial `a` is conjugate symmetric, that is, if `a=ã`.\n\nFor a scalar univariate Laurent polynomial `a` with real coefficients, check if `a(z)=a(1/z)`. If the coefficients are complex, the condition then extends to `a(z)=ā(1/z)`, where `ā` is obtained from `a` by complex-conjugating the coefficients. A necessary and sufficient condition is that the coefficients are real and their order in the coefficient vector can be flipped with no impact.\n\n# Examples\n```julia\njulia> a = LaurentPolynomial([3,2,1,2,3],-2:2,:z)\nLaurentPolynomial(3*z⁻² + 2*z⁻¹ + 1 + 2*z + 3*z²)\n\njulia> isconjsymmetric(a)\ntrue\n```\n\"\"\"\nfunction isconjsymmetric(a::LaurentPolynomial)\n return isequal(a,dconj(a))\nend\n", "meta": {"hexsha": "d4d35966caec4dc95ba9d56e8f0bd1dd2ee6f1d5", "size": 2842, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/analysis.jl", "max_stars_repo_name": "hurak/PolynomialEquations.jl", "max_stars_repo_head_hexsha": "e04d78a110a6c221ce34a1257a74b4ba9e71f255", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-04-27T20:38:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-30T08:59:25.000Z", "max_issues_repo_path": "src/analysis.jl", "max_issues_repo_name": "hurak/PolynomialEquations.jl", "max_issues_repo_head_hexsha": "e04d78a110a6c221ce34a1257a74b4ba9e71f255", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/analysis.jl", "max_forks_repo_name": "hurak/PolynomialEquations.jl", "max_forks_repo_head_hexsha": "e04d78a110a6c221ce34a1257a74b4ba9e71f255", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-27T20:38:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-27T20:38:33.000Z", "avg_line_length": 25.6036036036, "max_line_length": 410, "alphanum_fraction": 0.6861365236, "num_tokens": 939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109798251322, "lm_q2_score": 0.8933094046341532, "lm_q1q2_score": 0.8490110665453511}} {"text": "@doc raw\"\"\"\n ExponentiatedKernel([α=1])\n\nThe exponentiated kernel is a Mercer kernel given by:\n\n```\n κ(x,y) = exp(α⋅xᵀy) α > 0\n```\nwhere `α` is a positive scaling parameter.\n\n# Examples\n\n```jldoctest; setup = :(using MLKernels)\njulia> ExponentiatedKernel()\nExponentiatedKernel{Float64}(1.0)\n\njulia> ExponentiatedKernel(2)\nExponentiatedKernel{Float64}(2.0)\n\njulia> ExponentiatedKernel(2.0f0)\nExponentiatedKernel{Float32}(2.0)\n```\n\"\"\"\nstruct ExponentiatedKernel{T<:AbstractFloat} <: MercerKernel{T}\n α::T\n function ExponentiatedKernel{T}(α::Real=T(1)) where {T<:AbstractFloat}\n @check_args(ExponentiatedKernel, α, α > zero(T), \"α > 0\")\n return new{T}(α)\n end\nend\nExponentiatedKernel(α::T=1.0) where {T<:Real} = ExponentiatedKernel{promote_float(T)}(α)\n\n@inline basefunction(::ExponentiatedKernel) = ScalarProduct()\n\n@inline kappa(κ::ExponentiatedKernel{T}, xᵀy::T) where {T} = exp(κ.α*xᵀy)\n\nfunction convert(\n ::Type{K},\n κ::ExponentiatedKernel\n ) where {K>:ExponentiatedKernel{T}} where T\n return ExponentiatedKernel{T}(κ.α)\nend", "meta": {"hexsha": "5b454978d6f8463f41416192ad5ca9c4a9980eb1", "size": 1078, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernelfunctions/mercer/exponentiated.jl", "max_stars_repo_name": "trthatcher/Kernels.jl", "max_stars_repo_head_hexsha": "c95971efc89b76f05e39cbdf5213507fe4351d63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 85, "max_stars_repo_stars_event_min_datetime": "2015-04-21T16:40:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-24T00:25:21.000Z", "max_issues_repo_path": "src/kernelfunctions/mercer/exponentiated.jl", "max_issues_repo_name": "trthatcher/Kernels.jl", "max_issues_repo_head_hexsha": "c95971efc89b76f05e39cbdf5213507fe4351d63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 81, "max_issues_repo_issues_event_min_datetime": "2015-04-22T16:33:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-03T14:32:44.000Z", "max_forks_repo_path": "src/kernelfunctions/mercer/exponentiated.jl", "max_forks_repo_name": "trthatcher/Kernels.jl", "max_forks_repo_head_hexsha": "c95971efc89b76f05e39cbdf5213507fe4351d63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 43, "max_forks_repo_forks_event_min_datetime": "2015-04-22T15:59:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-21T19:02:01.000Z", "avg_line_length": 25.6666666667, "max_line_length": 88, "alphanum_fraction": 0.6920222635, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109713976399, "lm_q2_score": 0.8933094096048377, "lm_q1q2_score": 0.849011063741186}} {"text": "#=\nImplement integer exponentiation. That is, implement the pow(x, y) function, where x and y are integers and returns x^y.\n\nDo this faster than the naive method of repeated multiplication.\n\nFor example, pow(2, 10) should return 1024.\n=#\n\nfunction pow(x::Int, y::Int)\n if y == 0\n return 1\n elseif y % 2 == 0\n return pow(x, Int(y/2)) * pow(x, Int(y/2))\n else\n return x * pow(x,Int((y-1)/2)) * pow(x,Int((y-1)/2))\n end\nend\n", "meta": {"hexsha": "0f9cb1029cdd22c67d407937d23abf2b7b014fd7", "size": 454, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/problem61_intexponentiation.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/problem61_intexponentiation.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/problem61_intexponentiation.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": 25.2222222222, "max_line_length": 120, "alphanum_fraction": 0.6167400881, "num_tokens": 146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109728022221, "lm_q2_score": 0.8933093961129794, "lm_q1q2_score": 0.8490110521731024}} {"text": "@doc raw\"\"\"\n gausslobatto(n::Integer) -> Tuple{Vector{Float64},Vector{Float64}}\n\nReturn nodes and weights of [Gauss-Lobatto quadrature](https://mathworld.wolfram.com/LobattoQuadrature.html).\n\n```math\n\\int_{-1}^{1} f(x) dx \\approx \\sum_{i=1}^{n} w_i f(x_i)\n```\n\n# Examples\n```jldoctest\njulia> x, w = gausslobatto(4);\n\njulia> f(x) = x^4;\n\njulia> I = dot(w, f.(x));\n\njulia> I ≈ 2/5\ntrue\n```\n\nNote that the both ends of nodes are fixed at -1 and 1.\n\n```jldoctest\njulia> x, w = gausslobatto(4);\n\njulia> x[1], x[end]\n(-1.0, 1.0)\n```\n\"\"\"\nfunction gausslobatto(n::Integer)\n # Gauss-Legendre-Lobatto Quadrature Nodes and Weights\n if n ≤ 1\n throw(DomainError(n, \"Lobatto undefined for n ≤ 1.\"))\n elseif n == 2\n return [-1.0, 1.0], [1.0, 1.0]\n elseif n == 3\n return [-1.0, 0.0, 1.0], [1.0 / 3, 4.0 / 3, 1.0 / 3]\n else\n # Compute via GaussJacobi:\n x, w = gaussjacobi(n - 2, 1.0, 1.0)\n @inbounds for i in 1:length(x)\n w[i] = w[i] / (1 - x[i]^2)\n end\n pushfirst!(x, -1.0)\n push!(x, 1.0)\n pushfirst!(w, 2 / (n * (n - 1)))\n push!(w, 2 / (n * (n - 1)))\n return x, w\n end\nend\n", "meta": {"hexsha": "81cd525358ff7bcfed59ceee0b3b95a1773550c6", "size": 1174, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gausslobatto.jl", "max_stars_repo_name": "Datseris/FastGaussQuadrature.jl", "max_stars_repo_head_hexsha": "dd1f2fed53c4024bb6bde9f8d5a237ac47985b51", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 145, "max_stars_repo_stars_event_min_datetime": "2019-04-12T02:58:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T23:02:17.000Z", "max_issues_repo_path": "src/gausslobatto.jl", "max_issues_repo_name": "Datseris/FastGaussQuadrature.jl", "max_issues_repo_head_hexsha": "dd1f2fed53c4024bb6bde9f8d5a237ac47985b51", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 45, "max_issues_repo_issues_event_min_datetime": "2019-04-08T23:32:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T21:02:07.000Z", "max_forks_repo_path": "src/gausslobatto.jl", "max_forks_repo_name": "Datseris/FastGaussQuadrature.jl", "max_forks_repo_head_hexsha": "dd1f2fed53c4024bb6bde9f8d5a237ac47985b51", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2019-04-11T03:26:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-29T10:24:13.000Z", "avg_line_length": 22.5769230769, "max_line_length": 109, "alphanum_fraction": 0.5408858603, "num_tokens": 469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693241956308277, "lm_q2_score": 0.875787001374006, "lm_q1q2_score": 0.848921530650793}} {"text": "# p5.jl - repetition of p4.jl via FFT\n# For complex v, delete \"real\" commands.\n\n# Differentiation of a hat function:\nN = 24; h = 2*pi/N; x = h*(1:N);\nv = @. max(0,1-abs(x-pi)/2); v_hat = fft(v);\nw_hat = 1im*[0:N/2-1;0;-N/2+1:-1] .* v_hat;\nw = real(ifft(w_hat)); clf();\nsubplot(2,2,1); plot(x,v,\".-\",markersize=6);\naxis([0,2pi,-.5,1.5]); grid(true); title(\"function\");\nsubplot(2,2,2), plot(x,D*v,\".-\",markersize=6);\naxis([0,2pi,-1,1]); grid(true); title(\"spectral derivative\");\n\n# Differentiation of exp(sin(x)):\nv = @. exp(sin(x)); vprime = @. cos(x)*v;\nv_hat = fft(v);\nw_hat = 1im*[0:N/2-1;0;-N/2+1:-1] .* v_hat;\nw = real(ifft(w_hat));\nsubplot(2,2,3), plot(x,v,\".-\",markersize=6);\naxis([0,2pi,0,3]), grid(true);\nsubplot(2,2,4), plot(x,D*v,\".-\",markersize=6);\naxis([0,2pi,-2,2]), grid(true);\nerror = signif(norm(D*v-vprime,Inf),4);\ntext(2.2,1.4,\"max error = $error\",fontsize=8);\n", "meta": {"hexsha": "de984d73028d9f6a6ebe28c1a5aed75b9e455d73", "size": 887, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/scripts/p5.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/p5.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/p5.jl", "max_forks_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_forks_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.48, "max_line_length": 61, "alphanum_fraction": 0.587373168, "num_tokens": 364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799420543366, "lm_q2_score": 0.880797071719777, "lm_q1q2_score": 0.848894550743716}} {"text": "# This file is a part of AstroLib.jl. License is MIT \"Expat\".\n# Copyright (C) 2016 Mosè Giordano.\n\nfunction planck_freq(frequency::T, temperature::T) where {T<:AbstractFloat}\n c1 = 1.47449944028424e-50 # = 2*h/c*c\n c2 = 4.79924466221135e-11 # = h/k\n return c1*frequency^3/expm1(c2*frequency/temperature)\nend\n\n\"\"\"\n planck_freq(frequency, temperature) -> black_body_flux\n\n### Purpose ###\n\nCalculate the flux of a black body per unit frequency.\n\n### Explanation ###\n\nReturn the spectral radiance of a black body per unit frequency using [Planck's\nlaw](https://en.wikipedia.org/wiki/Planck%27s_law)\n\n`` B_\\\\nu(\\\\nu, T) = \\\\frac{2h\\\\nu ^3}{c^2} \\\\frac{1}{e^\\\\frac{h\\\\nu}{k_\\\\mathrm{B}T} - 1} ``\n\n### Arguments ###\n\n* `frequency`: frequency at which the flux is to be calculated, in Hertz.\n* `temperature`: the equilibrium temperature of the black body, in Kelvin.\n\n### Output ###\n\nThe spectral radiance of the black body, in units of W/(sr·m²·Hz).\n\n### Example ###\n\nPlot the spectrum of a black body in \\$[10^{12}, 10^{15.4}]\\$ Hz at \\$8000\\$ K.\nUse [PyPlot.jl](https://github.com/JuliaPlots/Plots.jl/) for plotting.\n\n```julia\nusing PyPlot\nfrequency = exp10.(range(12, stop=15.4, length=1000));\ntemperature = ones(frequency)*8000;\nflux = planck_freq.(frequency, temperature);\nplot(frequency, flux)\n```\n\n### Notes ###\n\n`planck_wave` calculates the flux of a black body per unit wavelength.\n\"\"\"\nplanck_freq(f::Real, t::Real) = planck_freq(promote(float(f), float(t))...)\n", "meta": {"hexsha": "f12e54e1889649d1dbc10143afaeb78f26a9f07e", "size": 1478, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/planck_freq.jl", "max_stars_repo_name": "UnofficialJuliaMirror/AstroLib.jl-c7932e45-9af1-51e7-9da9-f004cd3a462b", "max_stars_repo_head_hexsha": "fb2ef587a2ac68a1c864bf251e8d9c3601ec4719", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 62, "max_stars_repo_stars_event_min_datetime": "2016-09-11T14:59:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T20:45:36.000Z", "max_issues_repo_path": "src/planck_freq.jl", "max_issues_repo_name": "UnofficialJuliaMirror/AstroLib.jl-c7932e45-9af1-51e7-9da9-f004cd3a462b", "max_issues_repo_head_hexsha": "fb2ef587a2ac68a1c864bf251e8d9c3601ec4719", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 64, "max_issues_repo_issues_event_min_datetime": "2017-01-19T21:03:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T12:27:46.000Z", "max_forks_repo_path": "src/planck_freq.jl", "max_forks_repo_name": "UnofficialJuliaMirror/AstroLib.jl-c7932e45-9af1-51e7-9da9-f004cd3a462b", "max_forks_repo_head_hexsha": "fb2ef587a2ac68a1c864bf251e8d9c3601ec4719", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2016-07-12T02:11:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T11:55:21.000Z", "avg_line_length": 28.9803921569, "max_line_length": 93, "alphanum_fraction": 0.6826792963, "num_tokens": 465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632343454895, "lm_q2_score": 0.8918110404058913, "lm_q1q2_score": 0.8488821413457677}} {"text": "function acqr_em_s(y,start::acqr;\r\n\tae = true, ce = true, qe = true, re = true,\r\n\tmax_iter = 100,tol = 1e-09,txo = false)\r\n\t#\r\n\t# estimate a, c, Q, R, m1, P1 using the STATIONARY EM algorithm for model\r\n\t#\r\n\t# x_{t+1} = a*x_{t} + w_{t}\r\n\t# y_{t} = c*x_{t} + v_{t}\r\n\t#\r\n\t# cov(w_{t},v_{t}) = [q 0;0 r]\r\n\t# x1 -> N(m1,P1)\r\n\t#\r\n\t# javier.cara@upm.es, 2020-05\r\n\t#\r\n\r\n\t#\r\n\tnt = length(y)\r\n\r\n\t# initial values\r\n\ta = start.a\r\n\tc = start.c\r\n\tq = start.q\r\n\tr = start.r\r\n\tm1 = start.m1\r\n\tP1 = start.P1\r\n\r\n\t# log-likelihood values\r\n\tloglikv = zeros(max_iter)\r\n\r\n\t# Syy does not depend on the iterations\r\n\tSyy = sum(y.^2)\r\n\r\n\ttol1 = 1.0\r\n\titer = 1\r\n\twhile (iter <= max_iter) && (tol1 > tol)\r\n\t\ttime1 = time()\r\n\r\n\t\t# E-step\r\n\t\t# ---------------------------------------------------------------------------------\r\n\t\t# Kalmanfilter\r\n\t\t(xtt,Ptt,xtt1,Ptt1,et,St,Kt,loglik) = acqr_kfilter_s(y,a,c,q,r,m1)\r\n\t\t(xtN,PtN,Pt1tN) = acqr_ksmoother_s(a,xtt,Ptt,xtt1,Ptt1)\r\n\r\n\t\tloglikv[iter] = loglik\r\n\t\tif iter > 1\r\n\t\t\ttol1 = abs( (loglikv[iter] - loglikv[iter-1])/loglikv[iter-1] )\r\n\t\tend\r\n\r\n\t\t# Sxx, Sx1x, Syx, Sx1x1\r\n\t\tSxx = nt*PtN + sum(xtN[1:nt].^2)\r\n\t\tSx1x = nt*Pt1tN + sum(xtN[2:nt+1].*xtN[1:nt])\r\n\t\tSyx = sum(y.*xtN[1:nt])\r\n\t\tSx1x1 = Sxx - xtN[1]^2 + xtN[nt+1]^2\r\n\r\n\t\t# M-step\r\n\t\t# -------------------------------------------------------------------------------------\r\n\t\t# Matrices m1 y P1\r\n\t\tm1 = xtN[1]\r\n\t\tP1 = PtN\r\n\r\n\t\t# parameter a\r\n\t\tif ae\r\n\t\t\ta = Sx1x/Sxx\r\n\t\tend\r\n\r\n\t\t# parameter q\r\n\t\tif qe\r\n\t\t\tq = Sx1x1 - 2*a*Sx1x + a^2*Sxx\r\n\t\t\tq = 1/nt*q\r\n\t\tend\r\n\r\n\t\t# parameter c\r\n\t\tif ce\r\n\t\t\tc = Syx/Sxx\r\n\t\tend\r\n\r\n\t\t# parameter r\r\n\t\tif re\r\n\t\t\tr = Syy - 2*c*Syx + c^2*Sxx\r\n\t\t\tr = 1/nt*r\r\n\t\tend\r\n\r\n\t\tetime = time() - time1\r\n\t\tif txo\r\n\t\t\tprintln( \"Iter \" * @sprintf(\"%3d\",iter) * \", @time = \" * @sprintf(\"%.2E\",etime) * \", logLik = \" * @sprintf(\"%.6E\",loglik) * \", tol = \", @sprintf(\"%.2E\",tol1) )\r\n\t\tend\r\n\r\n\t\titer += 1\r\n\r\n\tend\r\n\r\n\tloglikv = loglikv[1:(iter-1)]\r\n\r\n\t# Akaike Information Criterion\r\n\tP = 4\r\n\taic = -2*loglikv[end] + 2*P\r\n\r\n\t# output\r\n\tfit = acqr(a,c,q,r,m1,P1)\r\n\tsalida = acqrEM(y,start,fit,loglikv,aic,true)\r\n\treturn salida\r\n\r\nend\r\n", "meta": {"hexsha": "60c2c5f82bef89a6ce37e57d239afab81457f37e", "size": 2129, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/acqr/acqr_em_s.jl", "max_stars_repo_name": "javiercara/StateSpaceModelsEM.jl", "max_stars_repo_head_hexsha": "989d538b01274885e4579df130f9b38bbb99cc7d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/acqr/acqr_em_s.jl", "max_issues_repo_name": "javiercara/StateSpaceModelsEM.jl", "max_issues_repo_head_hexsha": "989d538b01274885e4579df130f9b38bbb99cc7d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/acqr/acqr_em_s.jl", "max_forks_repo_name": "javiercara/StateSpaceModelsEM.jl", "max_forks_repo_head_hexsha": "989d538b01274885e4579df130f9b38bbb99cc7d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.4711538462, "max_line_length": 169, "alphanum_fraction": 0.4917801785, "num_tokens": 889, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102552339746, "lm_q2_score": 0.8774767986961403, "lm_q1q2_score": 0.848880053788524}} {"text": "\"\"\"\nComputes Jacobi polynomial and derivatives of Jacobi polynomials.\n\nThis function computes the jacobi polynomial of degree `n` with weights\n`a` and `b` at point x (\\$P_n^{a,b}(x)\\$). There are several variants of the function\nwith default values:\n\n * `jacobi(x, n)` (`a` and `b` are both zero)\n * `jacobi(x, n, a)` (`b` is zero)\n * `jacobi(x, n, a, b) where `x` is an array\n * `jacobi!(x, n, a, b, y)` modifying array version of the function\n\nThe derivative of Jacobi polynomials (\\$\\\\frac{dP_n^{a,b}(x)}{dx}\\$)are computed with functions that add a `d` in front of its name:\n\n * `djacobi`\n * `djacobi!`\n\n### Examples\n```julia\nusing Jacobi\n\nx = 0.3\na = 0.2\nb = 0.1\nm = 5\ny = jacobi(x, m, a, b)\nx1 = linspace(-1,1,21)\ny1 = jacobi(x1, m, a, b)\njacobi!(x1, m, a, b, y1)\n\ndy = djacobi(x, m, a, b)\ndy1 = djacobi(x1, m, a, b)\ndjacobi!(x1, m, a, b, dy1)\n\n```\n\n\"\"\"\nfunction jacobi(x, n, a, b)\n ox = one(x)\n zx = zero(x)\n if n==0\n return ox\n elseif n==1\n return ox/2 * (a - b + (a + b + 2)*x)\n end\n\n p0 = ox\n p1 = ox/2 * (a - b + (a + b + 2)*x)\n p2 = zx;\n\n for i = 1:(n-1)\n\ta1 = 2*(i+1)*(i+a+b+1)*(2*i+a+b);\n\ta2 = (2*i+a+b+1)*(a*a-b*b);\n\ta3 = (2*i+a+b)*(2*i+a+b+1)*(2*i+a+b+2);\n\ta4 = 2*(i+a)*(i+b)*(2*i+a+b+2);\n\tp2 = ox/a1*( (a2 + a3*x)*p1 - a4*p0);\n\n p0 = p1\n p1 = p2\n end\n\n return p2\nend\njacobi(x, n) = jacobi(x, n, zero(x), zero(x))\njacobi(x, n, a) = jacobi(x, n, a, zero(x))\n\ndjacobi(x, n, a, b) = one(x)/2 * (a + b + n + 1) * jacobi(x, n-1, a+1, b+1)\n\ndjacobi(x, n) = djacobi(x, n, zero(x), zero(x))\ndjacobi(x, n, a) = djacobi(x, n, a, zero(x))\n\n\neps1(::Type{T}) where {T<:AbstractFloat} = eps(T)\neps1(::Type{Complex{T}}) where {T<:AbstractFloat} = eps(T)\n\n\"\"\"\nCompute the zeros of Jacobi polynomials\n\nThis function computes the zeros of Jacobi polynomials:\n\n * \\$P_m^{a,b}(x) = 0 \\$\n\nThe `jacobi_zeros!` is the modifying version and the memory where the zeros\nwill be stored are preallocated. The non-modifying version, `jacobi_zeros`\nallocates a the memory and calls the modifying version. The function `legendre_zeros`\ncompute the zeros of Legendre polynomials (`a = b = 0`)\n\n### Examples\n```\nusing Jacobi\nz = jacobi_zeros(7, 0.3, 0.2)\n```\n\"\"\"\nfunction jacobi_zeros!(m, alpha, beta, x::AbstractArray{T}) where {T<:Number}\n\n o = one(T)\n z = zero(T)\n\n a = convert(T,alpha)\n b = convert(T,beta)\n\n MAXITER = 500\n EPS::T = 100 * eps1(T)\n local i; local k; local iter=0\n\n for k = 1:m\n # Initial guess.\n r = -cos( (2k-o)/(2*m) * pi)\n if (k > 1)\n r = (r + x[k-1]) / 2\n end\n iter = 0\n while(true)\n s = z\n for i = 1:(k-1)\n s += o/(r - x[i])\n end\n\n poly = jacobi(r, m, a, b)\n delta = -poly / (djacobi(r, m, a, b) - poly*s)\n\n r += delta\n iter += 1\n\n if iter > MAXITER\n throw(\"Program did not converge\")\n end\n\n if abs(delta) < abs(EPS)\n break\n end\n end\n x[k] = r\n end\n\n return x\n\nend\n\n\n\nfunction jacobi_zeros(m, a, b, ::Type{T}=Float64) where {T<:Number}\n jacobi_zeros!(m, a, b, zeros(T,m))\nend\n\njacobi_zeros(m) = jacobi_zeros(m, 0.0, 0.0)\njacobi_zeros(m, a) = jacobi_zeros(m, a, zero(a))\n\n@doc (@doc jacobi) djacobi\n@doc (@doc jacobi) djacobi!\n@doc (@doc jacobi) jacobi!\n@doc (@doc jacobi_zeros!) jacobi_zeros\n", "meta": {"hexsha": "1a72bb34877805994e6c74e82eb1f580d6df9df7", "size": 3428, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/jac_poly.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/jac_poly.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/jac_poly.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": 22.4052287582, "max_line_length": 132, "alphanum_fraction": 0.5402567095, "num_tokens": 1269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897475985937, "lm_q2_score": 0.9019206791658465, "lm_q1q2_score": 0.8485177281063889}} {"text": "\"\"\"\nMonte carlo integration is a very easy and scalable way to do multidimentional integrals.\nHowever, only single variable integrals are considered.\n\n\nThis function takes three outputs:\n\t- `f`: the function to integrate. (at the momment only single variable is suported)\n\t- `N`: Number of points to sample. For most simple functions, 1000 to 10,000 should be okay.\n\t- `span`: a tuple (start, end) for the integration limits\n\nExamples:\n```julia\njulia> monte_carlo_integration(x->3*x^2,100000,(0,1)) # integrate a polynomial\n1.0000037602209\n\njulia> monte_carlo_integration(x->sin(x),1000,(0,pi)) # integrate the sin function\n2.0018927826323756\n\n```\n\tRefereces:\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\nContributed By-: [Ved Mahajan](https://github.com/Ved-Mahajan)\n\"\"\"\nfunction monte_carlo_integration(f,N,span)\n\tx_start,x_end = span\n\trand_array = rand(x_start:0.0001:x_end,N)\n\treturn sum(f.(rand_array))*(x_end - x_start)/float(N)\nend\n", "meta": {"hexsha": "c372d7bfcbda36beec74e3526dbbc8f7cb86f38a", "size": 1088, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/monte_carlo_integration.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": "src/math/monte_carlo_integration.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": "src/math/monte_carlo_integration.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": 35.0967741935, "max_line_length": 136, "alphanum_fraction": 0.765625, "num_tokens": 315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620562254525, "lm_q2_score": 0.8840392786908831, "lm_q1q2_score": 0.8484673559004278}} {"text": "using Plots, LaTeXStrings, ProgressBars\ncd(dirname(@__FILE__))\nfunction LogisticMap(x₀::Vector{Float64} , r::Float64, n::Real)\n x = x₀\n for i in 1:n\n x = 4 .* r .* x .* (1 .- x)\n end\n return x\nend\n\n####Part A####\nr_s=collect(range(0.0, 1.0, step=10^(-4)))\nx₀_s = rand(100)\nx_s=zeros(length(r_s), length(x₀_s))\n\nfor (i,r) in enumerate(r_s)\n x_s[i,:]=LogisticMap(x₀_s, r, 10^4 )\nend\n\nscatter(r_s, x_s, legend=false, ms=0.5, color=:black, dpi=400, xlabel=L\"r\", ylabel=L\"x\", title=L\"Logistic\\ Map\\ :\\ x_n_+_1\\ =\\ 4rx_n(1-x_n)\")\nsavefig(\"../../computational_physics/PSet9/Figs/Bifurcation.pdf\")\n\n####Part B####\n####Zoomed Plot####\nr_zoom= collect(range(0.70, 1.0, step=10^(-4)))\nx₀_zoom = rand(range(0.70, 1.0, length=100), 100)\nx_zoom=zeros(length(r_zoom), length(x₀_zoom))\nfor (i,r) in enumerate(r_zoom)\n x_zoom[i,:]=LogisticMap(x₀_zoom, r, 10^4 )\nend\nscatter(r_zoom, x_zoom, legend=false, ms=0.5, color=:black, dpi=400, xlabel=L\"r\", ylabel=L\"x\", \n title=L\"Logistic\\ Map\\ :\\ x_n_+_1\\ =\\ 4rx_n(1-x_n),\\ 0.7length(unique(round.(x[i, :], digits=9))) == 4, 1:1401)\ndₙ₋₁_index = findfirst(i->length(unique(round.(x[i, :], digits=9))) == 8, 1:1401)\ndₙ_index = findfirst(i->length(unique(round.(x[i, :], digits=9))) == 16, 1:1401)\nδ=(rb[dₙ₋₁_index]-rb[dₙ₋₂_index])/(rb[dₙ_index]-rb[dₙ₋₁_index])\n# σ ∼ 5.0999\n#### α ####\ndₙ₊₁_index = findfirst(i->length(unique(round.(x[i, :], digits=9))) == 32, 1:1401)\nrₙ₋₂_index = findfirst(i-> 1/2 ∈ unique(ceil.(x[i, :], digits=3)), dₙ₋₂_index:dₙ₋₁_index) + dₙ₋₂_index\nrₙ₋₁_index = findfirst(i-> 1/2 ∈ unique(ceil.(x[i, :], digits=3)),dₙ₋₁_index:dₙ_index) + dₙ₋₁_index\nrₙ_index = findfirst(i-> 1/2 ∈ unique(ceil.(x[i, :], digits=3)), dₙ_index:dₙ₊₁_index) + dₙ_index\nxsₙ₋₂ = sort(unique(round.(x[rₙ₋₂_index, :], digits=3)))\nxsₙ₋₁ = sort(unique(round.(x[rₙ₋₁_index, :], digits=3)))\nxsₙ = sort(unique(round.(x[rₙ_index, :], digits=3)))\nα = (xsₙ₋₁[2] - xsₙ₋₁[1] - (xsₙ₋₂[4]- xsₙ₋₂[3] ))/( xsₙ[2] - xsₙ[1] - (xsₙ₋₁[2] - xsₙ₋₁[1]))\n\n", "meta": {"hexsha": "bcf30bf33ffe0e8fbc65441402110bf0dcaa3cc6", "size": 2348, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "PSet9/Bifurcation.jl", "max_stars_repo_name": "narges8k/computational_physics", "max_stars_repo_head_hexsha": "a24229aa7b31648735aab120cd667dffd788df1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PSet9/Bifurcation.jl", "max_issues_repo_name": "narges8k/computational_physics", "max_issues_repo_head_hexsha": "a24229aa7b31648735aab120cd667dffd788df1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PSet9/Bifurcation.jl", "max_forks_repo_name": "narges8k/computational_physics", "max_forks_repo_head_hexsha": "a24229aa7b31648735aab120cd667dffd788df1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-13T09:55:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T09:55:00.000Z", "avg_line_length": 39.1333333333, "max_line_length": 141, "alphanum_fraction": 0.6247870528, "num_tokens": 998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545392102522, "lm_q2_score": 0.8947894724152068, "lm_q1q2_score": 0.8483986999080251}} {"text": "\n\"\"\"\n fivePointStencil(f,x,n::Integer,h)\n\nEvaluates function f and its derivatives up to order n ∈ [0,4] at x:\n``f(x),f'(x),...,f^{(n)}(x)``\nThe result is an array of length n+1.\nDerivatives are numerically computed using the 5-point stencil method\nwith h≠0 being the grid spacing:\n[https://en.wikipedia.org/wiki/Five-point_stencil](https://en.wikipedia.org/wiki/Five-point_stencil)\n\n\"\"\"\nfunction fivePointStencil(f,x,n::Integer,h)\n if ((n<0) || (n>4))\n error(\"In fivePointStencil: Invalid order $n\")\n end\n if (h==0.0)\n error(\"In fivePointStencil: Invalid grid spacing $h\")\n end\n fm2 = f(x-2h)\n fm1 = f(x-h)\n fn0 = f(x)\n fp1 = f(x+h)\n fp2 = f(x+2h)\n\n res = Vector{typeof(fn0)}(undef,n+1)\n\n res[1] = fn0\n\n (n==0) && return res\n\n res[2] = (-fp2+8fp1-8fm1+fm2)/(12*h)\n\n (n==1) && return res\n\n h2 = h * h\n res[3] = (-fp2+16fp1-30fn0+16fm1-fm2)/(12*h2)\n\n (n==2) && return res\n\n h3 = h2 * h\n res[4] = (fp2-2fp1+2fm1-fm2)/(2*h3)\n\n (n==3) && return res\n\n h4 = h3 * h\n res[5] = (fp2-4fp1+6fn0-4fm1+fm2)/h4\n\n return res\nend\n", "meta": {"hexsha": "1b3b526de8d31316b5bf6218182399960b8bae49", "size": 1100, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/fivePointStencil.jl", "max_stars_repo_name": "UnofficialJuliaMirror/CALCEPH.jl-1537fe66-4725-5aba-80f4-3a74792cecc1", "max_stars_repo_head_hexsha": "f8b74fd4e801b0f28aeae903fb54aa5aab16cb34", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-02-05T07:41:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-04T17:31:31.000Z", "max_issues_repo_path": "src/fivePointStencil.jl", "max_issues_repo_name": "UnofficialJuliaMirror/CALCEPH.jl-1537fe66-4725-5aba-80f4-3a74792cecc1", "max_issues_repo_head_hexsha": "f8b74fd4e801b0f28aeae903fb54aa5aab16cb34", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-05-28T06:41:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-04T10:15:17.000Z", "max_forks_repo_path": "src/fivePointStencil.jl", "max_forks_repo_name": "UnofficialJuliaMirror/CALCEPH.jl-1537fe66-4725-5aba-80f4-3a74792cecc1", "max_forks_repo_head_hexsha": "f8b74fd4e801b0f28aeae903fb54aa5aab16cb34", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-02-06T10:47:45.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-24T12:57:05.000Z", "avg_line_length": 21.568627451, "max_line_length": 100, "alphanum_fraction": 0.5772727273, "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122708828602, "lm_q2_score": 0.8856314632529871, "lm_q1q2_score": 0.8483572461299793}} {"text": "\"\"\"\n NCalculus\n\nNumerical Differentiation and Integration Module.\n\"\"\"\nmodule NCalculus\n\nconst GaussianRoots = [0.5773502692,-0.5773502692,\n 0.7745966692,0.0,-0.7745966692,\n 0.8611363116,0.3399810436,-0.3399810436,-0.8611363116,\n 0.9061798459,0.5384693101,0.0,-0.5384693101,-0.9061798459]\nconst GaussianCoef = [1.0,1.0,\n 0.5555555556,0.8888888889,0.5555555556,\n 0.3478548451,0.6521451549,0.6521451549,0.3478548451,\n 0.2369268850,0.4786286705,0.5688888889,0.4786286705,0.2369268850]\n\n\n\"\"\"\n ThreePoint(f::Function, x₀::Real, h::Real; method::String=\"Endpoint\")\n\ninput a function `f`, x₀ and h.Args is method (default: \"Endpoint\", if you set method is't \"Endpoint\", it will\nreturn MidPoint ans.)\n\"\"\"\n@inline function ThreePoint(f::Function, x₀::Real, h::Real; method::String=\"Endpoint\")\n if method == \"Endpoint\"\n return 1/h*(-3/2*f(x₀) + 2*f(x₀+h)- 1/2*f(x₀+2*h))\n else\n return 1/(2*h) * (f(x₀+h) - f(x₀- h))\n end\nend\n\n\"\"\"\n FivePoint(f::Function, x₀::Real, h::Real; method::String=\"Endpoint\")\n\ninput a function `f`, x₀ and h.Args is method (default: \"Endpoint\", if you set method is't \"Endpoint\", it will\nreturn MidPoint ans.)\n\"\"\"\n@inline function FivePoint(f::Function, x₀::Real, h::Real; method::String=\"Endpoint\")\n if method == \"Endpoint\"\n return 1/(12*h)*(-25*f(x₀)+48f(x₀ +h)-36f(x₀+2h)+16f(x₀+3h)-3f(x₀+4h))\n else\n return 1/(12*h) * (f(x₀ - 2h) - 8f(x₀ -h)+8f(x₀+h)-f(x₀ + 2h))\n end\nend\n\n\"\"\"\n Trapezoidal(f::function, a::Real, b::Real)\n\ninput a function `f`, and ``x in [a, b]`` calculate ∫f(x)dx.\n\"\"\"\n@inline function Trapezoidal(f::Function, a::Real, b::Real)\n return (b-a)/2 * (f(a) + f(b))\nend\n\n\"\"\"\n Simpson(f::Function, a::Real, b::Real)\n\ninput a function `f`, and ``x in [a, b]`` calculate ∫f(x)dx.\n\"\"\"\n@inline function Simpson(f::Function, a::Real, b::Real)\n return (b-a)/6 * (f(a) + 4*f(a+(b-a)/2) + f(b))\nend\n\n\n\"\"\"\n Newton_Cotes(f::Function, a::Real, b::Real; n::Int=0, method::String=\"Midpoint\")\n\ninput a function `f`, and ``x in [a, b]``` calculate ``int_a^b f(x)dx``. args ``n∈[1,4]``\n\"\"\"\n@inline function Newton_cotes(f::Function, a::Real, b::Real; n::Int=0, method::String=\"Midpoint\")\n if method == \"Open\"\n o1 = (b-a)/2 * (f(a) + f(b))\n o2 = (b-a)/6 * (f(a) + 4*f(a+(b-a)/2) + f(b))\n o3 = 3*(b-a)/24 * (f(a) + 3*f(a+(b-a)/3) + 3*f(a+2*(b-a)/3) + f(b))\n o4 = 2*(b-a)/180 * (7*f(a) + 32*f(a+(b-a)/4) + 12*f(a+(b-a)/2) + 32*f(a + 3*(b-a)/4) + 7*f(b))\n o = [o1, o2, o3, o4]\n if 0=l)\n\t\tmid = Int(ceil(l+(r-l)/2));\n\t\tprintln(mid)\n\t\tif(arr[mid] == x)\n\t\t\treturn \"Element present at index $mid\"\n\t\telseif(arr[mid] > x)\n\t\t\tbinary_search(arr, l, mid-1, x)\n\t\telse\n\t\t\tbinary_search(arr, mid+1, r, x)\n\t\tend\n\telse \n\t\treturn \"Element not present in array\"\n\tend\nend\n\n\"\"\"\n\t exponential_search(arr::AbstractArray{T,1}, x::T) where {T <: Real}\n\t\nExponential Search in 1-D array\nTime Complexity: O(Log n)\n\"\"\"\nfunction exponential_search(arr::AbstractArray{T,1}, x::T) where {T <: Real}\n\tn = size(arr)[1]\n\tif(arr[1] == x)\n\t\treturn \"Elemenet present at index 1\"\n\tend\n\t\n\ti = 1\n\twhile( i using LinearAlgebra\njulia> A = randn(5,5); A = A*A'; U = randn(5,3); C = Diagonal(rand(3)); V = randn(3,5);\njulia> A⁻¹ = A\\\\I # assume inverse is available\njulia> B1 = inv(A + U*C*V) # regular way of computing inverse\njulia> B2 = woodbury_A_plus_UCV(; A⁻¹=A⁻¹, U=U, C⁻¹=C\\\\I, V=V)\njulia> maximum(abs.(B1.-B2))<1e-10 # verify that they are numerically equal, should return true\n```\n\"\"\"\nwoodbury_A_plus_UCV(; A⁻¹=A⁻¹, U=U, C⁻¹=C⁻¹, V=V) = A⁻¹ - A⁻¹*U*((C⁻¹ + V*A⁻¹*U)\\V)*A⁻¹\n\n\n#-----------------------------------------------------------\n# Make matrix symmetric by adding its transpose\n#-----------------------------------------------------------\n\nfunction makematrixsymmetric!(A)\n I,J = size(A)\n for i in 1:I\n for j in i+1:J\n @inbounds tmp = (A[i,j]+A[j,i])/2\n @inbounds A[i,j] = A[j,i] = tmp\n end\n end\n nothing\nend\n\nfunction makematrixsymmetric(A)\n (A+A')/2\nend\n\n\n\n#-----------------------------------------------------------\n# Add a small constant, i.e. jitter to the diagonal\n#-----------------------------------------------------------\n\n\nfunction addjitter!(A, JITTER = 1e-8)\n\n I, J = size(A)\n\n if I !== J\n error(\"Matrix passed to addjitter! must be square\")\n end\n\n for i in 1:I\n @inbounds A[i,i] += JITTER\n end\n\n nothing\nend\n\n\n\naddjitter(A, JITTER = 1e-8) = A + JITTER*I\n\n\n\n#-----------------------------------------------------------\n# Find closest positive definite matrix\n#-----------------------------------------------------------\n\n\"\"\"\n nearestposdef(A; minimumeigenvalue = 1e-6)\n\nNearest positive definite matrix in Frobenious norm.\nAlso called the projection of the matrix onto the cone of positive definite matrices.\nSee: https://nhigham.com/2021/01/26/what-is-the-nearest-positive-semidefinite-matrix/\n```\n\"\"\"\nfunction nearestposdef(A; minimumeigenvalue = 1e-6)\n\n local Evalues, Evector = eigen(A)\n\n local newA = Evector * Diagonal(max.(Evalues, minimumeigenvalue)) * Evector'\n\n makematrixsymmetric!(newA)\n\n newA\n\nend\n", "meta": {"hexsha": "781793a199aed54fdf43157fa83efd7d080bbc24", "size": 2457, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/matricesutil.jl", "max_stars_repo_name": "ngiann/MiscUtil.jl", "max_stars_repo_head_hexsha": "62bb259ae41ffa2f2eaf4c55142523238995919e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/matricesutil.jl", "max_issues_repo_name": "ngiann/MiscUtil.jl", "max_issues_repo_head_hexsha": "62bb259ae41ffa2f2eaf4c55142523238995919e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-22T10:56:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T10:56:15.000Z", "max_forks_repo_path": "src/matricesutil.jl", "max_forks_repo_name": "ngiann/MiscUtil.jl", "max_forks_repo_head_hexsha": "62bb259ae41ffa2f2eaf4c55142523238995919e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.59375, "max_line_length": 98, "alphanum_fraction": 0.5172975173, "num_tokens": 718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813501370537, "lm_q2_score": 0.8872045907347108, "lm_q1q2_score": 0.8481510424983609}} {"text": "module InverseQuadraticInterpolation \r\nexport invquadinterp\r\n\r\nfunction invquadinterp(f::Function, x0::Number, x1::Number, x2::Number,\r\n args::Tuple=(); xtol::AbstractFloat=1e-5,\r\n ytol=2eps(Float64), maxiter::Integer=50)\r\n y0 = f(x0, args...)\r\n y1 = f(x1, args...)\r\n y2 = f(x2, args...)\r\n for _ in 1:maxiter\r\n x = x0*y1*y2/((y0-y1)*(y0-y2)) +\r\n x1*y0*y2/((y1-y0)*(y1-y2)) +\r\n x2*y0*y1/((y2-y0)*(y2-y1))\r\n # x-tolerance\r\n if min(abs(x-x0), abs(x-x1), abs(x-x2)) < xtol \r\n return x\r\n end\r\n y = f(x, args...)\r\n # y-tolerance.\r\n if abs(y) < ytol\r\n return x\r\n end\r\n x0 = x1\r\n y0 = y1\r\n x1 = x2\r\n y1 = y2\r\n x2 = x\r\n y2 = y\r\n end\r\n error(\"Max iteration exceeded\")\r\nend \r\n\r\nend", "meta": {"hexsha": "f88afd6a2efeaddd7d6f21270756125b1326ac93", "size": 872, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/InverseQuadraticInterpolation.jl", "max_stars_repo_name": "RohitRathore1/NumericalTechniques.jl", "max_stars_repo_head_hexsha": "66eacc0d31c555c42f9712b9187633e2ba0b514c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/InverseQuadraticInterpolation.jl", "max_issues_repo_name": "RohitRathore1/NumericalTechniques.jl", "max_issues_repo_head_hexsha": "66eacc0d31c555c42f9712b9187633e2ba0b514c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/InverseQuadraticInterpolation.jl", "max_forks_repo_name": "RohitRathore1/NumericalTechniques.jl", "max_forks_repo_head_hexsha": "66eacc0d31c555c42f9712b9187633e2ba0b514c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4242424242, "max_line_length": 72, "alphanum_fraction": 0.4495412844, "num_tokens": 291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517095103499, "lm_q2_score": 0.8824278772763472, "lm_q1q2_score": 0.847970577188295}} {"text": "using Pkg\nPkg.add(\"QuadGK\")\n\nusing QuadGK\n\n\nfunc1(x) = exp(-x^2)\nres, err = quadgk(func1, -Inf, Inf)\n\nabs(res - sqrt(π)) / sqrt(π)\n\n\nres, err = quadgk(func1, -Inf, Inf, rtol = 1e-15)\n\nabs(res - sqrt(π)) / sqrt(π)\n\nres, err = quadgk(func1, -Inf, Inf, order = 12)\n\nabs(res - sqrt(π)) / sqrt(π)\n\nsqrt(π)\n\n#%%\n\nres, err = quadgk(func1, BigFloat(-Inf), BigFloat(Inf), rtol = 1e-15, order=12)\nabs(res - sqrt(BigFloat(π))) / sqrt(BigFloat(π))\n#%%\nfunc2(x, y, z) = x + y^3 + sin(z)\n\nx = 5\nz = 3\narg(y) = func2(x, y, z)\n\nquadgk(arg, 1, 3)\n\nquadgk(y -> func2(x, y, z), 1, 3)\n\nres, err = let x=5; z=3\n arg(y) = func2(x, y, z)\n\n quadgk(arg, 1, 3)\nend\n\n#%%\nfunc3(x, y) = x^2 * exp(y)\n\nfunction test_int(x, ymin, ymax)\n arg(y) = func3(x, y)\n return quadgk(arg, ymin, ymax)[1]\nend\n\ntest_int(3, 1, 5)\n", "meta": {"hexsha": "174a3acac22602e7e7348a2db770f903e845c21a", "size": 797, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lesson-numerical-integration/numerical-integration.jl", "max_stars_repo_name": "JeffreySarnoff/techytok-examples", "max_stars_repo_head_hexsha": "5c34c9fc0660da1a69f9e3959465ed80659c30cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-10-28T11:21:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-14T09:06:49.000Z", "max_issues_repo_path": "lesson-numerical-integration/numerical-integration.jl", "max_issues_repo_name": "JeffreySarnoff/techytok-examples", "max_issues_repo_head_hexsha": "5c34c9fc0660da1a69f9e3959465ed80659c30cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lesson-numerical-integration/numerical-integration.jl", "max_forks_repo_name": "JeffreySarnoff/techytok-examples", "max_forks_repo_head_hexsha": "5c34c9fc0660da1a69f9e3959465ed80659c30cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2020-01-20T23:53:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-10T20:51:24.000Z", "avg_line_length": 15.0377358491, "max_line_length": 79, "alphanum_fraction": 0.5646173149, "num_tokens": 354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731126558705, "lm_q2_score": 0.880797085800514, "lm_q1q2_score": 0.8479196722058007}} {"text": "using LinearAlgebra\n\nfunction cheb4c(N)\n\n # The function x,D4 = cheb4c(N) computes the fourth derivative\n # matrix D4 on Chebyshev interior points, incorporating the\n # clamped boundary conditions.\n # It is adapted from the function with the same name in dmsuite\n # developed for Matlab by JAC Weideman and SC Reddy.\n #\n # Adapted by M. Beneitez at KTH Mechanics.\n # beneitez@mech.kth.se\n #\n # Input:\n # N-2: Order of the differentiation matrix.\n #\n # Output:\n # yF: Interior Chebyshev points\n # D4: Size [N-2,N-2] Fourth derivative matrix\n #\n\n eye = Matrix{Float64}(I, N-2, N-2);\n\n n1 = Int(floor(N/2-1)); n2 = Int(ceil(N/2-1)); # Indices used for flipping trick.\n\n k = collect(1:N-2); # Compute theta vector.\n th = k.*pi./(N-1)\n\n x = sin.(pi.*collect(N-3:-2:3-N)./(2*(N-1))); # Compute Chebyshev points.\n\n s = [sin.(th[1:n1]);reverse(sin.(th[1:n2]), dims = 1)]\n\n alpha = s.^4;\n beta1 = -4*s.^2 .*x./alpha;\n beta2 = 4*(3*x.^2 .-1)./alpha;\n beta3 = 24*x./alpha;\n beta4 = 24 ./alpha;\n B = [beta1'; beta2'; beta3'; beta4'];\n\n T = repeat(th/2,1,N-2);\n DX = 2*sin.(T'+T).*sin.(T'-T); # Trigonometric identity. \n DX = [DX[1:n1,:]; -reverse(reverse(DX[1:n2,:], dims = 2), dims=1)]; # Flipping trick. \n DX[eye.==true] = ones(N-2,1); # Put 1's on the main diagonal of DX.\n\n ss = s.^2 .*(-1.0).^k;\n S = repeat(ss, 1, N-2);\n C = S./S';\n\n Z = 1 ./DX;\n Z[eye.==true] = zeros(N-2,1);\n\n X = Z';\n X = X[X .!= 0.0];\n X = reshape(X,N-3,N-2);\n\n Y = ones(N-3,N-2);\n D = Matrix{Float64}(I, N-2, N-2);\n DM = zeros(N-2,N-2,4);\n\n for ell = 1:4\n Y = cumsum([B[ell,:]'; ell.*Y[1:N-3,:].*X], dims = 1);\n D = ell.*Z.*(C.*repeat(diag(D), 1, N-2)-D);\n D[eye.==true] = Y[N-2,:];\n DM[:,:,ell] = D;\n end\n\n D4 = DM[:,:,4];\n\n return x,D4\n \n \nend\n", "meta": {"hexsha": "d211620c1a76ec63566fe36a51815fa127b9efd1", "size": 1956, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/hydro_cheb/cheb4c.jl", "max_stars_repo_name": "harrymd/NonlinearEigenproblems.jl", "max_stars_repo_head_hexsha": "ffb050eb040dc22cb9c3c00c38da117b45ca7937", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 63, "max_stars_repo_stars_event_min_datetime": "2018-06-07T09:54:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T06:57:07.000Z", "max_issues_repo_path": "docs/src/hydro_cheb/cheb4c.jl", "max_issues_repo_name": "harrymd/NonlinearEigenproblems.jl", "max_issues_repo_head_hexsha": "ffb050eb040dc22cb9c3c00c38da117b45ca7937", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 180, "max_issues_repo_issues_event_min_datetime": "2018-06-06T11:25:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T21:49:00.000Z", "max_forks_repo_path": "docs/src/hydro_cheb/cheb4c.jl", "max_forks_repo_name": "harrymd/NonlinearEigenproblems.jl", "max_forks_repo_head_hexsha": "ffb050eb040dc22cb9c3c00c38da117b45ca7937", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2018-06-05T15:30:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T08:39:25.000Z", "avg_line_length": 26.7945205479, "max_line_length": 92, "alphanum_fraction": 0.5056237219, "num_tokens": 725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731126558705, "lm_q2_score": 0.8807970748488297, "lm_q1q2_score": 0.8479196616629087}} {"text": "\"\"\"\n\n`MTH229`: helper functions for using `Julia` with MTH229\n\nThis module does two things:\n\n* Install other useful packages with one command (`Roots`, `ForwardDiff`, `QuadGK`, `SpecialFunctions`, ...) and re-exports their methods.\n\n* Add a number of helper functions.\n\nThe helper functions include:\n\n- `secant(f, a, b)`: return a function giving the secant line between ``(a,f(a))`` and ``(b,f(b))``.\n\n- `tangent(f, c)`: return a function giving the tangent line to ``f(x)`` at the point ``(c,f(c))``.\n\n- `bisection(f, a, b)`: A simple implementation of the bisection\n method. The interval ``[a,b]`` should be a bracketing interval. This\n function makes an illustrative graphic. For real use of the bisection method, the `fzero(f,\n a, b)` function, from the `Roots` package, should be used.\n\n- `'`: As in `f'`. Overloads `adjoint` allowing the derivative of a function to be found as with math notation: `f'`. The notation can be used for higher-order derivatives too: `f''`, `f'''`, ... This uses automatic differentiation from the `ForwardDiff` package.\n\n- `plotif(f, g, a, b)`: Plot the function `f` over the interval `[a,b]` and color differently where ``g(x) > 0`` over ``[a,b]``. By passing in `f` for `g` shows where `f` is positive on `[a,b]`; passing in `f'` shows where `f` is increasing on `[a,b]`; and passing in `f''` shows where `f` is concave up on `[a,b]`.\n\n- `sign_chart(f, a, b)`: shows a *signchart* of `f` by numerically identifying the zero crossings or infinities of `f` over `[a,b]` (assuming `f(a)` and `f(b)` are non zero, then checking the sign between these values. Calling `sign_chart(f', a, b)` is useful for the first-derivative test and `sign_chart(f'', a, b)` for the second-derivative test.\n\n- `fisheye(f)` returns the composition `atan ∘ f ∘ tan`, which can be useful to find zeros of a function over the entire range of real numbers.\n\n- `riemann(f, a, b, n; method=\"right\")` An implementation of Riemann sums. The method can be \"right\" or \"left\" for Riemann sums, or \"trapezoid\" or \"simpsons\" for related approximations.\n\n\nThis package provides some plotting routines for `Plots`, `SimplePlots`, and `Makie`. For the latter two, some \"recipes\" for plotting functions and symbolic directions; and for all some convenience methods.\n\"\"\"\nmodule MTH229\n\n\n# msg = \"\"\"\n# Loading the `MTH229` package.\n\n# * Run the command `?MTH229` for a short description.\n\n\n# \"\"\"\n\n# @info msg\n\n\nif isdefined(Base, :Experimental) && isdefined(Base.Experimental, Symbol(\"@optlevel\"))\n @eval Base.Experimental.@optlevel 1\nend\n\nusing Reexport\n@reexport using Roots\n@reexport using SpecialFunctions\n@reexport using SymPy\n@reexport using QuadGK\n@reexport using LinearAlgebra\n@reexport using ForwardDiff\nusing PlotUtils\n\nusing Requires\n\nfunction __init__()\n @require SimplePlots=\"307c2aad-90be-4152-b348-f51955fac6ce\" include(\"simpleplots.jl\")\n @require Plots=\"91a5bcdd-55d7-5caf-9e0b-520d859cae80\" include(\"plots.jl\")\n @require AbstractPlotting=\"537997a7-5e4e-5d89-9595-2241ea00577e\" include(\"makie.jl\")\n end\n\n\n## start it up\n\n\n\"\"\"\n mth229(dirnm)\nEntry point to install projects and start notebook\n\"\"\"\nfunction mth229(dirnm=homedir())\n eval(:(using IJulia))\n eval(:(import ZipFile))\n\n if !isfile(joinpath(dirnm, \"01-calculator.ipynb\"))\n @warn \"installing projects in $dirnm\"\n zf = \"https://www.github.com/mth229/229-projects/archive/master.zip\"\n zarchive = ZipFile.Reader(download(zf))\n !isdir(dirnm) && mkdir(dirnm)\n cd(dirnm)\n\n @show zarchive.files\n for f in zarchive.files\n nm = basename(f.name)\n occursin(\"ipynb\", nm) || continue\n @info \"installing $nm\"\n open(nm, \"w\") do io\n write(io, read(f, String))\n end\n end\n end\n\n Base.invokelatest(IJulia.notebook)\nend\nexport mth229\n\n\n###\nexport tangent, secant, D, grad, sign_chart, fisheye, rangeclamp\nexport lim\nexport bisection, newton\nexport riemann, fubini\nexport uvec, xs_ys, unzip, parametric_grid\nexport e\n\n@info \"This package defines `e = exp(1)`\"\n\"e is not Base.MathConstants.ℯ, rather `exp(1)` so that it plays nicely with ForwardDiff\"\ne = exp(1)\n\n\"\"\"\n rangeclamp(f, hi=20, lo=-hi)\n\nReplace large values of `f` with `NaN`; useful for plotting with vertical asymptotes.\n\"\"\"\nrangeclamp(f, hi=20, lo=-hi; replacement=NaN) = x -> lo < f(x) < hi ? f(x) : replacement\n\n\n# give a warning\n@info \"This package overloads the `'` operation for derivatives. This may cause issues with linear algebra usage\"\n\n \" f'(x) will find the derivative of `f` using Automatic Differentation from the `ForwardDiff` package \"\nBase.adjoint(f::Function) = x -> ForwardDiff.derivative(f, float(x))\nfunction D(f, n::Int=1)\n n < 0 && throw(ArgumentError(\"n must be non-negative\"))\n n == 0 && return f\n n == 1 && return x -> ForwardDiff.derivative(f, float(x))\n D(D(f), n-1)\nend\ngrad(f) = (x, xs...) -> ForwardDiff.gradient(f, vcat(x, xs...))\n# could aslo wrap as function ForwardDiff.jacobian, ForwardDiff.hessian\n\n\n\"\"\"\n sign_chart(f, a, b; atol=1e-4)\n\nCreate a sign chart for `f` over `(a,b)`. Returns a tuple with an identified zero or vertical asymptote and the corresponding sign change. The tolerance is used to disambiguate numerically found values.\n\n# Example\n\n```\njulia> sign_chart(x -> x/(x-1)^2, -5, 5)\n2-element Vector{NamedTuple{(:∞0, :sign_change), Tuple{Float64, String}}}:\n (∞0 = 0.0, sign_change = \"- → +\")\n (∞0 = 1.0000000000000002, sign_change = \"+ → +\")\n```\n\n\"\"\"\nfunction sign_chart(f, a, b; atol=1e-6)\n pm(x) = x < 0 ? \"-\" : x > 0 ? \"+\" : \"0\"\n summarize(f,cp,d) = (DNE_0_∞=cp, sign_change=pm(f(cp-d)) * \" → \" * pm(f(cp+d)))\n\n if Roots._is_f_approx_0(f(a),a, eps(), eps()) ||\n Roots._is_f_approx_0(f(b), b, eps(), eps())\n return \"Sorry, the endpoints must not be zeros for the function\"\n end\n\n zs = find_zeros(f, a, b)\n pts = vcat(a, zs, b)\n for (u,v) ∈ zip(pts[1:end-1], pts[2:end])\n zs′ = find_zeros(x -> 1/f(x), u, v)\n for z′ ∈ zs′\n flag = false\n for z ∈ zs\n if isapprox(z′, z, atol=atol)\n flag = true\n break\n end\n end\n !flag && push!(zs, z′)\n end\n end\n\n\n if isempty(zs)\n\tfc = f(a + (b-a)/2)\n\treturn \"No sign change, always \" * (fc > 0 ? \"positive\" : iszero(fc) ? \"zero\" : \"negative\")\n end\n\n sort!(zs)\n m,M = extrema(zs)\n d = min((m-a)/2, (b-M)/2)\n if length(zs) > 1\n d′ = minimum(diff(zs))/2\n d = min(d, d′ )\n end\n summarize.(f, zs, d)\nend\n\n\n\n\"\"\"\nReturns a function describing the tangent line to the graph of f at x=c.\n\nExample. Where does the tangent line intersect the y axis?\n```\nf(x) = sin(x)\ntl(x) = tangent(f, pi/4)(x) # or tl = tangent(f, pi/3) to use a non-generic function\ntl(0)\n```\n\nUses the automatic derivative of `f` to find the slope of the tangent line at `x=c`.\n\n\"\"\"\ntangent(f,c) = x -> f(c) + f'(c) * (x-c)\n\n\"\"\"\nReturns a function describing the secant line to the graph of f at x=a and x=b.\n\nExample. Where does the secant line intersect the y axis?\n```\nf(x) = sin(x)\na, b = pi/4, pi/3\nsl(x) = secant(f, a, b)(x) # or sl = sl(f, a, b) to use a non-generic function\nsl(0)\n```\n\n\n\"\"\"\nsecant(f, a, b) = x -> f(a) + (f(b) - f(a)) / (b-a) * (x - a)\n\n\n\"\"\"\n\n`lim(f, c, n, dir=\"+\")`: means to generate numeric table of values of `f` as `h` gets close to `c`.\n\nExample:\n```\nf(x) = sin(x) / x\nlim(f, 0)\n```\n\"\"\"\nfunction lim(f::Function, c::Real; n::Int=6, dir=\"+\")\n\t hs = [(1/10)^i for i in 1:n] # close to 0\n\t if dir == \"+\"\n\t xs = c .+ hs\n\t else\n\t xs = c .- hs\n\t end\n\t ys = map(f, xs)\n\t [xs ys]\nend\n\n\n\"\"\"\n\nSimple implementation of the bisection method.\n\nExample:\n\n```julia\nbisection(sin, 3, 4)\nf(x) = x^5 - x^4 - x^3 - x^2 - x - 1\na = bisection(f, 1, 2)\nf(a)\n```\n\nThe display shows a simple graphic illustrating the method's division for the first few steps.\n\nAn easier-to-understand alternative to `Roots.find_zero(f, (a,b), Bisection())`.\n\n\n\"\"\"\nfunction bisection(f::Function, a, b)\n a,b = sort([a,b])\n\n if f(a) * f(b) > 0\n error(\"[a,b] is not a bracket. A bracket means f(a) and f(b) have different signs!\")\n end\n\n M = a + (b-a) / 2\n\n\n i, j = 0, 64\n ss = fill(\"#\", 65)\n ss[i+1]=\"a\"; ss[j+1]=\"b\"\n println(\"\")\n println(join(ss))\n flag = true\n\n while a < M < b\n if flag && j-i == 1\n ss = fill(\" \", 65)\n ss[j:(j+1)] .= \"⋮\"\n println(join(ss))\n println(\"\")\n flag = false\n end\n\n\n if f(M) == 0.0\n println(\"... exact answer found ...\")\n\t break\n end\n ## update step\n\tif f(a) * f(M) < 0\n\t a, b = a, M\n\n if flag\n j = div(i + j, 2)\n end\n\n\n\telse\n\t a, b = M, b\n\n if flag\n i = div(i + j, 2)\n end\n\n\tend\n\n if flag\n ss = fill(\".\", 65)\n ss[i+1]=\"a\"; ss[j+1]=\"b\"; ss[(i+2):j] .= \"#\"\n println(join(ss))\n end\n\n M = a + (b-a) / 2\n end\n M\nend\n\n\n\nnewton(f, fp, x0; kwargs...) = Roots.find_zero((f,fp), x0, Roots.Newton(); kwargs...)\nnewton(f, x0; kwargs...) = newton(f, f', x0; kwargs...)\n\n\"\"\"\n fisheye(f)\n\nTransform `f` defined on `(-∞, ∞)` to a new function whose domain is in `(-π/2, π/2)` and range is within `(-π/2, π/2)`. Useful for finding all zeros over the real line. For example\n\n```\nf(x) = 1 + 100x^2 - x^3\nfzeros(f, -100, 100) # empty just misses the zero found with:\nfzeros(fisheye(f), -pi/2, pi/2) .|> tan # finds 100.19469143521222, not perfect but easy to get\n```\n\nBy Gunter Fuchs.\n\"\"\"\nfisheye(f) = atan ∘ f ∘ tan\n\n\n##\n## --------------------------------------------------\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,l,r) -> f(r) * (r-l)\n elseif method == \"left\"\n meth= (f,l,r) -> f(l) * (r-l)\n elseif method == \"trapezoid\"\n meth = (f,l,r) -> (1/2) * (f(l) + f(r)) * (r-l)\n elseif method == \"simpsons\"\n meth = (f,l,r) -> (1/6) * (f(l) + 4*(f((l+r)/2)) + f(r)) * (r-l)\n end\n\n xs = a .+ (0:n) * (b-a)/n\n as = [meth(f, l, r) for (l,r) in zip(xs[1:end-1], xs[2:end])]\n sum(as)\nend\n\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\n##################################################\n\nuvec(x) = x / norm(x)\n\n\"\"\"\n `unzip(vs)`\n `unzip(v1, v2, ...)`\n `unzip(r::Function, a, b)`\n `unzip(r::Function, a, b, n)`\n\nTake a vector of points described by vectors (as returned by, say\n`r(t)=[sin(t),cos(t)], r.([1,2,3])`, and return a tuple of collected x\nvalues, y values, and optionally z values.\n\nIf the argument is specified as a comma separated collection of vectors, then these are combined and passed along.\n\nIf the argument is a function and two end point, then the points are chosen by `PlotUtils.adaptedgrid`.\n\nIf the argument is a function, two endpoints and a number of points, then `n` points are chosen evenly spaced over `[a,b]`.\n\nThis is useful for plotting when the data is more conveniently\nrepresented in terms of vectors, but the plotting interface requires the x and y values collected.\n\nExamples:\n```\nusing SimplePlots\nr(t) = [sin(t), cos(t)]\nrp(t) = [cos(t), -sin(t)]\nplot(unzip(r, 0, 2pi)...) # calls plot(xs, ys)\n\nt0, t1 = pi/6, pi/4\n\np, v = r(t0), rp(t0)\nplot!(unzip(p, p+v)...) # connect p to p+v with line\n\np, v = r(t1), rp(t1)\nquiver!(unzip([p])..., quiver=unzip([v]))\n```\n\nBased on `unzip` from the `Plots` package.\n\"\"\"\nunzip(vs) = Tuple([vs[j][i] for j in eachindex(vs)] for i in eachindex(vs[1]))\nunzip(v,vs...) = unzip([v, vs...])\nunzip(r::Function, a, b, n) = unzip(r.(range(a, stop=b, length=n)))\n# return (xs, f.(xs)) or (f₁(xs), f₂(xs), ...)\nfunction unzip(f::Function, a, b)\n n = length(f(a))\n if n == 1\n return PlotUtils.adapted_grid(f, (a,b))\n else\n xsys = [PlotUtils.adapted_grid(x->f(x)[i], (a,b)) for i ∈ 1:n]\n xs = sort(vcat([xsys[i][1] for i ∈ 1:n]...))\n return unzip(f.(xs))\n end\nend\n\n# unzip(a) = map(x -> getfield.(a, x), fieldnames(eltype(a)))\n\n# alternate, should deprecate\nxs_ys(vs) = (A=hcat(vs...); Tuple([A[i,:] for i in eachindex(vs[1])]))\nxs_ys(v,vs...) = xs_ys([v, vs...])\nxs_ys(r::Function, a, b, n=100) = xs_ys(r.(range(a, stop=b, length=n)))\n\n\"\"\"\n parametric_grid(us, vs, r)\n\nCreate matrices for `xs`, `ys`, `zs` from `r(u,v) = [x(u,v), y(u,v), z(u,v)]`\n\nUsed to plot parametrically defined surfaces.\n\"\"\"\nfunction parametric_grid(us, vs, r)\n unzip(r.(us, vs'))\nend\n\n\n# for plotif. This identifies a vector of colors\nfunction identify_colors(g, xs, colors=(:red, :blue, :black))\n F = (a,b) -> begin\n ga,gb=g(a),g(b)\n ga * gb < 0 && return nothing\n ga >= 0 && return true\n return false\n end\n find_colors(F, xs, colors)\nend\n\n# F(a,b) returns true, false, or nothing\nfunction find_colors(F, xs, colors=(:red, :blue, :black))\n n = length(xs)\n cols = repeat([colors[1]], n)\n for i in 1:n-1\n a,b = xs[i], xs[i+1]\n val = F(a,b)\n if val == nothing\n cols[i] = colors[3]\n elseif val\n cols[i] = colors[1]\n else\n cols[i] = colors[2]\n end\n end\n cols[end] = cols[end-1]\n cols\nend\n\n\nend\n", "meta": {"hexsha": "2e6d6fc1263de874af7205b948bf5c562f577439", "size": 14866, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MTH229.jl", "max_stars_repo_name": "mth229/MTH229.jl", "max_stars_repo_head_hexsha": "8adc1ed95a202d50f4646a621bb55fc5b0fc6627", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2016-08-21T11:23:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-21T02:50:18.000Z", "max_issues_repo_path": "src/MTH229.jl", "max_issues_repo_name": "mth229/MTH229.jl", "max_issues_repo_head_hexsha": "8adc1ed95a202d50f4646a621bb55fc5b0fc6627", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-08-20T06:38:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-31T22:15:24.000Z", "max_forks_repo_path": "src/MTH229.jl", "max_forks_repo_name": "mth229/MTH229.jl", "max_forks_repo_head_hexsha": "8adc1ed95a202d50f4646a621bb55fc5b0fc6627", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-06-26T22:51:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T18:15:24.000Z", "avg_line_length": 28.0490566038, "max_line_length": 349, "alphanum_fraction": 0.5939728239, "num_tokens": 4819, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.919642526773001, "lm_q2_score": 0.9219218434359676, "lm_q1q2_score": 0.8478385335846762}} {"text": "include(\"distribution.jl\")\ninclude(\"const.jl\")\n\nexport entropy\n\nfunction entropy_ML(data::Vector{Int64}, base::Number)\n p = fe1p(data)\n return -sum([ p[x] > 0 ? (p[x] * log(base, p[x])) : 0 for x=1:size(p)[1]])\nend\n\n# implemented from [1] (see below)\nfunction entropy_MLBC(data::Vector{Int64}, base::Number)\n p = fe1p(data)\n n = float(size(data)[1])\n S = float(size(p)[1])\n H = -sum([ p[x] > ϵ ? (p[x] * log(base, p[x])) : 0 for x=1:size(p)[1]])\n return H + (S-1) / (2.0 * n)\nend\n\n# implemented from [1] (see below)\nfunction entropy_HT(data::Vector{Int64}, base::Number)\n p = fe1p(data)\n n = size(data)[1]\n return -sum([ p[x] > ϵ ? ((p[x] * log(base, p[x])) / (1.0 - ((1.0 - p[x])^n))) : 0 for x=1:size(p)[1]])\nend\n\n# implemented from [1] (see below)\nfunction entropy_CS(data::Vector{Int64}, base::Number)\n m = maximum(v)\n n = size(v)[1]\n c = counts(v, 1:m)\n c = c ./ n\n # just to get rid of the numerical inaccuracies and make sure its a probability distribution\n s = sum(c)\n p = c ./ s\n C = 1.0 - float(sum(filter(x == 1, c))) / float(n)\n p = p .* C\n return -sum([ p[x] > ϵ ? ((p[x] * log(base, p[x])) / (1.0 - ((1.0 - p[x])^l))) : 0 for x=1:size(p)[1]])\nend\n\nfunction entropy(data::Vector{Int64}; base=2, mode=\"ML\")\n modes = [\"ML\", \"Maximum Likelihood\", \n \"MLBC\", \"Maximum Likelihood with Bias Correction\",\n \"Horovitz-Thompson\", \"HT\",\n \"ChaoShen\", \"Chao-Shen\", \"CS\"]\n umodes = map(x->uppercase(x), modes)\n known_mode = uppercase(mode) in umodes\n pmodes = map(x->\", $x\",modes)\n pmodes = foldl(*, pmodes[1][3:end], pmodes[2:end])\n @assert known_mode \"Mode may be any of the following: [$pmodes].\"\n\n if uppercase(mode) in umodes[1:2]\n return entropy_ML(data, base) \n elseif uppercase(mode) in umodes[3:4]\n return entropy_MLBC(data, base)\n elseif uppercase(mode) in umodes[5:6]\n return entropy_HT(data, base)\n elseif uppercase(mode) in umodes[7:9]\n return entropy_CS(data, base)\n end\n return nothing\nend\n\n\n# [1] A. Chao and T.-J. Shen. Nonparametric estimation of shannon’s index of diversity when there are unseen species in sample. Environmental and Ecological Statistics, 10(4):429–443, 2003.\n\n", "meta": {"hexsha": "b1108d1d4fb49a1945e040b069e8383a3cbebbed", "size": 2176, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/entropy.jl", "max_stars_repo_name": "JuliaPackageMirrors/Shannon.jl", "max_stars_repo_head_hexsha": "91cf6088a009979ddbc63586d891abca6b508901", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/entropy.jl", "max_issues_repo_name": "JuliaPackageMirrors/Shannon.jl", "max_issues_repo_head_hexsha": "91cf6088a009979ddbc63586d891abca6b508901", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/entropy.jl", "max_forks_repo_name": "JuliaPackageMirrors/Shannon.jl", "max_forks_repo_head_hexsha": "91cf6088a009979ddbc63586d891abca6b508901", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4776119403, "max_line_length": 189, "alphanum_fraction": 0.6158088235, "num_tokens": 745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572777975782055, "lm_q2_score": 0.8856314738181875, "lm_q1q2_score": 0.8477953467226147}} {"text": "# ------------------------------------------------------------------------------\n# Geometric objects\n# -------------------------------------------------------------------------------\n\n\"\"\"\n squaredist(A, B)\n\nCompute the square of the euclidean distance between `A` and `B`.\n\n# Examples\n```jldoctest\njulia> squaredist(Point(0, 0), Point(2,2))\n8\n```\n\"\"\"\nfunction squaredist(A, B)\n d = (A.x-B.x)^2+(A.y-B.y)^2\n simplify(Sym(d))\nend\n\n\"\"\"\n distance(A, B)\n\nCompute the euclidean distance between `A` and `B`, which is the \"ordinary\" straight-line distance\nbetween two points.\n\n# Examples\n```jldoctest\njulia> distance(Point(0, 0), Point(3,4))\n5\n```\n\"\"\"\nfunction distance(A, B)\n SymPy.sqrt(squaredist(A, B))\nend\n\n\n\"\"\"\n midpoint(A, B)\n\nFind the midpoint between `A` and `B`.\n\n# Examples\n\n```jldoctest\njulia> midpoint(Point(0, 0), Point(2,4))\nPoint(1, 2)\n```\n\"\"\"\nfunction midpoint(A, B)\n x1 = (A.x + B.x)/2\n y1 = (A.y + B.y)/2\n Point(x1, y1)\nend\n\n\n\"\"\"\n concurrent(edgelist::Vector{Edge})\n\nFind the point where all edges (lines) in `edgelist` intersect if such point exists. Return nothing otherwise.\n\n# Examples\n\n```jldoctest\njulia> concurrent([Edge(Point(0,1), Point(1,1)), Edge(Point(0,1), Point(1,0))])\nPoint(0, 1)\n```\n\"\"\"\nfunction concurrent(edgelist::Vector{Edge})\n enum = length(edgelist)\n if enum == 1\n throw(ArgumentError(\"At least two edges are needed. $enum is given.\"))\n end\n\n @vars x y\n\n eqs = Sym[]\n for e in edgelist\n # This should be 0\n eq = (x-e.src.x)*(y-e.dst.y) - (x-e.dst.x)*(y-e.src.y)\n push!(eqs, eq)\n end\n\n sol = solve(eqs, [x,y])\n\n if length(sol) == 0\n return nothing\n else\n return Point(simplify(sol[x]), simplify(sol[y]))\n end\nend\n\n\"\"\"\n concurrent(e1::Edge, e2::Edge)\n\nFind the point the edges `e1` and `e2` intersect if such point exists. Return nothing otherwise.\n\n# Examples\n\n```jldoctest\njulia> concurrent(Edge(Point(0,1), Point(1,1)), Edge(Point(0,1), Point(1,0)))\nPoint(0, 1)\n```\n\"\"\"\nfunction concurrent(e1::Edge, e2::Edge)\n return concurrent([e1, e2])\nend\n", "meta": {"hexsha": "76e83fb1b5b242a057574cc7e6570e55d69d12b5", "size": 2089, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distance.jl", "max_stars_repo_name": "newptcai/PlaneGeometry.jl", "max_stars_repo_head_hexsha": "fe2644fdf824a364daa1ce362bf5557d40775226", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-05-12T04:22:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T23:20:31.000Z", "max_issues_repo_path": "src/distance.jl", "max_issues_repo_name": "newptcai/PlaneGeometry.jl", "max_issues_repo_head_hexsha": "fe2644fdf824a364daa1ce362bf5557d40775226", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/distance.jl", "max_forks_repo_name": "newptcai/PlaneGeometry.jl", "max_forks_repo_head_hexsha": "fe2644fdf824a364daa1ce362bf5557d40775226", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.3425925926, "max_line_length": 110, "alphanum_fraction": 0.5677357587, "num_tokens": 634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172615983308, "lm_q2_score": 0.8933094081846422, "lm_q1q2_score": 0.8476767173745962}} {"text": "module Generate\n\n# using PyCall\n\n# const map = pyimport(\"mpl_toolkits.basemap\")\n# const Globe = map.Basemap()\n\n\"\"\"\n sphere(N; R=1)\n\nGenerate a spherical point cloud of `N` points with extent of radius `R`.\n\"\"\"\nfunction sphere(N; R=1)\n θ = π .* rand(Float64, N)\n ϕ = 2π .* rand(Float64, N)\n\n return R.*hcat(sin.(θ).*cos.(ϕ), sin.(θ).*sin.(ϕ), cos.(θ))', hcat(θ, ϕ)'\nend\n\nfunction spherical_distance(x; R=1)\n n̂ = x / R\n D = zeros(size(x,2),size(x,2))\n\n norm² = sum(n̂[i,:].^2 for i ∈ 1:size(x,1))\n cosΔψ = sum(n̂[i,:]' .* n̂[i,:] for i ∈ 1:size(x,1))\n sinΔψ = [norm(cross(n̂[:,i], n̂[:,i])) for i ∈ 1:size(x,2), j ∈ 1:size(x,2)]\n\n return R*atan.(sinΔψ, cosΔψ)\nend\n\n\n#=\n\"\"\"\n globe(N)\n\nGenerate a spherical point cloud of `N` points where all points are guaranteed to be sampled from land-masses from Earth.\nUses mpl.basemap Python library.\n\"\"\"\nfunction globe(N)\n Θ = Array{Float64}(undef, N)\n Φ = Array{Float64}(undef, N)\n for n in 1:N\n @label sample\n θ = π*rand(1)[1]\n ϕ = 2π*rand(1)[1]\n\n x, y = Globe(180*(ϕ.-π)/π, 180*(π/2 .- θ)/π)\n\n !Globe.is_land(x,y) && @goto sample\n\n Θ[n] = θ\n Φ[n] = ϕ\n end\n\n return hcat(sin.(Θ).*cos.(Φ), sin.(Θ).*sin.(Φ), cos.(Θ))', hcat(Θ, Φ)'\nend\n=#\n\n\"\"\"\n swissroll(N; z₀=10, R=1/20)\n\nGenerate a point cloud of `N` distributed on a swiss roll manifold with unit radius and length ``\\frac{z₀}{R}``.\n\"\"\"\nfunction swissroll(N; z₀=10, R=1/20)\n z = (z₀/R)*rand(Float64, N)\n ϕ = 1.5π .+ 3π .* rand(Float64, N)\n\n return hcat(ϕ .* cos.(ϕ), ϕ .* sin.(ϕ), z)' .* R, hcat(ϕ, z)'\nend\n\n\"\"\"\n torus(N; R=2, r=1)\n\nGenerate a point cloud of `N` distributed on a torus, sized inner `r` and outer radius `R` respectively.\n\"\"\"\nfunction torus(N; R=2, r=1)\n θ = 2π .* rand(Float64, N)\n ϕ = 2π .* rand(Float64, N)\n\n return hcat((R .+ r*cos.(θ)) .* cos.(ϕ), (R .+ r*cos.(θ)).* sin.(ϕ), r*sin.(θ))', hcat(ϕ, θ)'\nend\n\nend\n", "meta": {"hexsha": "8360f863adbe2ee0a9f4de3f8eb3c2fbc28cb119", "size": 1944, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/generate.jl", "max_stars_repo_name": "nnoll/seqspace", "max_stars_repo_head_hexsha": "ec2165fbe80af1280ef7c69071f472d13977d5d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/generate.jl", "max_issues_repo_name": "nnoll/seqspace", "max_issues_repo_head_hexsha": "ec2165fbe80af1280ef7c69071f472d13977d5d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/generate.jl", "max_forks_repo_name": "nnoll/seqspace", "max_forks_repo_head_hexsha": "ec2165fbe80af1280ef7c69071f472d13977d5d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1428571429, "max_line_length": 121, "alphanum_fraction": 0.5524691358, "num_tokens": 774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995713428387, "lm_q2_score": 0.8774767970940975, "lm_q1q2_score": 0.8475544621764758}} {"text": "export DirectedPath, DirectedCycle, DirectedComplete\nexport RandomDigraph, RandomTournament, TorusDigraph\n\n\"\"\"\n`DirectedPath(n)` creates a directed cycles with vertices `1:n`.\n\"\"\"\nfunction DirectedPath(n::Int)\n if n < 1\n error(\"n must be positive\")\n end\n G = IntDigraph(n)\n for u=1:(n-1)\n add!(G,u,u+1)\n end\n return G\nend\n\n\"\"\"\n`DirectedCycle(n)` creates a directed cycles with vertices `1:n`.\n\"\"\"\nfunction DirectedCycle(n::Int)\n G = DirectedPath(n)\n add!(G,n,1)\n return G\nend\n\n# Create a complete digraph (all possible edges)\n\"\"\"\n`DirectedComplete(n)` creates a directed complete graph with\nall possible edges (including a loop at each vertex). Use\n`DirectedComplete(n,false)` to supress the creation of loops.\n\"\"\"\nfunction DirectedComplete(n::Int, with_loops::Bool=true)\n G = IntDigraph(n)\n if !with_loops\n forbid_loops!(G)\n end\n for u=1:n\n for v=1:n\n add!(G,u,v)\n end\n end\n return G\nend\n\n# Create a random digraph (Erdos-Renyi style)\n\"\"\"\n`RandomDigraph(n,p)` creates an Erdos-Renyi style random directed\ngraph with vertices `1:n` and edge probability `p` (equal to 0.5 by\ndefault). The possible edges `(u,v)` and `(v,u)` are independent. No\nloops are created. To also create loops (each with probability `p`)\nuse `RandomDigraph(n,p,true)`.\n\"\"\"\nfunction RandomDigraph(n::Int, p::Real=0.5, with_loops=false)\n G = IntDigraph(n)\n if !with_loops\n forbid_loops!(G)\n end\n for u=1:n\n for v=1:n\n if rand() < p\n add!(G,u,v)\n end\n end\n end\n return G\nend\n\n# Create a random tournament (no loops!)\n\n\"\"\"\n`RandomTournament(n)` creates a random tournament with vertex set\n`1:n`. This is equivalent to randomly assigning a direction to every\nedge of a simple complete graph.\n\"\"\"\nfunction RandomTournament(n::Int)\n G = IntDigraph()\n for u=1:n-1\n for v=u+1:n\n if rand() < 0.5\n add!(G,u,v)\n else\n add!(G,v,u)\n end\n end\n end\n return G\nend\n\n\n\n\"\"\"\n`all_tuples(alphabet, n)` creates an iterator that produces all\nlength-`n` tuples of distinct elements in `alphabet`.\n\"\"\"\nfunction all_tuples(alphabet, n::Int)\n elts = collect(distinct(alphabet))\n src = [ elts for _=1:n ]\n its = Base.Iterators.product(src...)\n return its\nend\n\n\nexport ShiftDigraph\n\n\"\"\"\n`ShiftDigraph(alphabet,n)` creates a `SimpleDigraph` whose vertices\nare all length-`n` tuples of the elements in `alphabet` (which can be\nan array such as `[0,1]` or a string such as `\"abc\"`). An edge from\n`u` to `v` corresponds to an element dropped from the first position\nin `u` and another element added to the end yielding `v`. For example,\nin `ShiftDigraph([0,1],5)` there are two edges leaving vertex\n`(0,1,0,1,1)`; one goes to `(1,0,1,1,0)` and the other to\n`(1,0,1,1,1)`.\n\"\"\"\nfunction ShiftDigraph(alphabet=[0,1], n::Int=3)\n elts = collect(distinct(alphabet))\n vertex_iter = all_tuples(alphabet, n)\n vlist = collect(vertex_iter)\n T = typeof(vlist[1])\n G = SimpleDigraph{T}()\n for v in vlist\n add!(G,v)\n end\n\n # create edges here\n\n for v in vlist\n head = collect(IterTools.drop(v,1))\n for c in elts\n w = tuple([head;c]...)\n add!(G,v,w)\n end\n end\n\n return G\n\nend\n\n\"\"\"\nfunction for creating a Torus Graph\n\"\"\"\nfunction TorusDigraph(n::Int=4, m::Int=3)\n\n G = SimpleDigraph();\n\n #create vertices\n vlist = Tuple{Int,Int}[]\n for i = 1:m\n for j = 1:n\n push!(vlist,(i,j))\n end\n end\n\n #create edges\n for v in vlist\n if v[1] + 1 <= m\n w = (v[1]+1,v[2])\n add!(G,v,w)\n end\n if v[2] + 1 <= n\n w = (v[1],v[2]+1)\n add!(G,v,w)\n end\n if v[1] == m\n w = (1,v[2])\n add!(G,v,w)\n end\n if v[2] == n\n w = (v[1],1)\n add!(G,v,w)\n end\n end\n\n return G\nend\n", "meta": {"hexsha": "1d2008f77dac64dda637914c87efccf48997f565", "size": 3903, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/d_simple_constructors.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SimpleGraphs.jl-55797a34-41de-5266-9ec1-32ac4eb504d3", "max_stars_repo_head_hexsha": "a22fbfc7f37c5b4debf209a11f5b059a688d8676", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/d_simple_constructors.jl", "max_issues_repo_name": "UnofficialJuliaMirror/SimpleGraphs.jl-55797a34-41de-5266-9ec1-32ac4eb504d3", "max_issues_repo_head_hexsha": "a22fbfc7f37c5b4debf209a11f5b059a688d8676", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/d_simple_constructors.jl", "max_forks_repo_name": "UnofficialJuliaMirror/SimpleGraphs.jl-55797a34-41de-5266-9ec1-32ac4eb504d3", "max_forks_repo_head_hexsha": "a22fbfc7f37c5b4debf209a11f5b059a688d8676", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0508474576, "max_line_length": 70, "alphanum_fraction": 0.6013323085, "num_tokens": 1196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465134460243, "lm_q2_score": 0.9059898248255074, "lm_q1q2_score": 0.8474144238681126}} {"text": "#=\n# Example: Plotting velocity profiles\nIn this notebook, we will discuss a useful way to visualize a flow in fluid\nmechanics: the **velocity profile**.\n=#\n#-\n\n# ### Set up the module\nusing ThermofluidQuantities\n#-\nusing Plots\n\n#=\nTo start, let's consider one of the most basic types of flow: the linear shear flow,\noften called **Couette flow**. This type of flow is generated, for example, between\ntwo parallel walls when one wall is moving and the other is stationary. In the figure\nbelow, the top wall is moving with velocity $U$, the lower wall is stationary:\n\n\"velocity\n\nBecause of the **no-slip condition**, the fluid next to each wall moves with it. The\nfluid next to the upper wall moves at velocity $U$, the fluid next to the lower wall\nis at rest.\n\nThe velocity profile depicts $u(y)$, the horizontal component of velocity as a\nfunction of vertical position, $y$. This increases linearly from the lower to the\nupper wall. In fact, the function is just\n\n$$u(y) = Uy/H$$\n\nThe arrows indicate the direction that the fluid is moving, and the lengths of\nthe arrows indicate the relative speed at that $y$ position.\n=#\n#-\n#=\n### Plotting velocity profiles\nThe arrows are helpful, but you can also plot a velocity profile without them.\nFor example, consider the following velocity:\n\n$$u(y) = \\frac{4U_c}{H^2} y (H - y)$$\n\nThe coefficient $U_c$ is a speed, and $H$ is the gap height.\n=#\n#=\nLet's define a function that evaluates this velocity. Here, `y`, `Uc`, and `H`\nare to be given as arguments to the function.\n=#\nu(y,Uc,H) = 4*Uc/H^2*y*(H-y)\n\n#=\nSuppose the gap height $H$ is 1 cm and the speed $U_c$ is 1 m/s. We will evaluate\nthis velocity at a range of locations between 0 and $H$:\n=#\nH = 1u\"cm\" # 1 cm = 0.01 m\nUc = 1u\"m/s\"\ny = range(0u\"cm\",H,length=101) # 101 points to evaluate at, just to make it look smooth.\n\n#=\nNow we evaluate the velocity function at the range of $y$ locations. (Remember that\nthe `.` vectorizes the evaluation of a function.)\n=#\nv = Velocity.(u.(y,Uc,H))\n\n#=\nNotice that $u$ is 0 at the beginning and end of the range. Let's plot it. But\nlet's plot it as a velocity profile, which means we make $u$ the 'x' axis and $y$\nthe 'y' axis.\n=#\n\nplot(v,y,xlim=(0u\"m/s\",2Uc),ylim=(0u\"cm\",H),\n legend=false,xlabel=\"u(y)\",ylabel=\"y\")\n#=\nThe top and bottom of this plot suggest that these are stationary walls where the\nflow is at rest. In fact, this is the velocity profile associated with pressure-driven\nflow through the gap.\n=#\n", "meta": {"hexsha": "7813e3c1e2ce0882a5b8c1b8b07746f760330e71", "size": 2597, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/literate/1-VelocityProfiles.jl", "max_stars_repo_name": "UCLAMAEThreads/ThermofluidQuantities", "max_stars_repo_head_hexsha": "8d2c2ed6e692ef18e899c96a477b87a6cbd24ec3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-31T23:54:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T21:08:40.000Z", "max_issues_repo_path": "test/literate/1-VelocityProfiles.jl", "max_issues_repo_name": "UCLAMAEThreads/ThermofluidQuantities", "max_issues_repo_head_hexsha": "8d2c2ed6e692ef18e899c96a477b87a6cbd24ec3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-04-01T21:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-12T01:23:08.000Z", "max_forks_repo_path": "test/literate/1-VelocityProfiles.jl", "max_forks_repo_name": "UCLAMAEThreads/ThermofluidQuantities", "max_forks_repo_head_hexsha": "8d2c2ed6e692ef18e899c96a477b87a6cbd24ec3", "max_forks_repo_licenses": ["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.7272727273, "max_line_length": 144, "alphanum_fraction": 0.7181363111, "num_tokens": 739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542184, "lm_q2_score": 0.9136765287024915, "lm_q1q2_score": 0.8473100786468016}} {"text": "using Turing, MCMCChains, Distributions, StatsPlots, CSV\n\n@model die_model(observations) = begin\n # Set prior distribution for p (probability of rolling 1)\n p ~ Uniform(0,1)#Beta(5,1)\n\n # Probability of rolling one of 2 - 6\n q = (1-p)/5\n\n # Define how samples are obtained\n for i=1:length(observations)\n observations[i] ~ Categorical([p, q, q, q, q, q])\n end\n\n return p\nend\n\n# Define the true probabilities\ntrue_p = 0.25\ntrue_q = (1-true_p)/5\n\n## Simulate observed data\nusing DataFrames\nusing CSV\ndata = rand(Categorical([true_p, true_q, true_q, true_q, true_q, true_q]), 100)\ndf = DataFrame(X = data)\nCSV.write(\"pp_ex_1_data.csv\", df)\n\n# Load observed data\ndata = CSV.read(\"pp_ex_1_data.csv\")[:,1]\n\n# Use HMC sampler to obtain posterior samples\nnum_posterior_samples = 1000\nϵ = 0.05 # Leapfrog step size\nτ = 10 # Number of leapfrog iterations\n\n# Obtain posterior samples\nchain = sample(die_model(data), HMC(ϵ, τ, :p), num_posterior_samples, progress=false)\n\n# Extract summary of p parameter and plot histogram\np_summary = chain[:p]\nplot(p_summary, seriestype = :histogram, bg = RGB(247/255, 236/255, 226/255))\n\n\nsavefig(\"../images/pp_ex_1_hist.svg\")\n\n# Extract 95% interval\nprintln(quantile(Array(p_summary), [0.025, 0.975]))\n", "meta": {"hexsha": "3561208cd9f1df746514db5c3a0bb31b4919df73", "size": 1261, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "content/bayesian-inference-and-graphical-models/code/pp_ex_1.jl", "max_stars_repo_name": "seanrattana/courses", "max_stars_repo_head_hexsha": "9453abc38af26ea49cb00fe1744066fc0de237b3", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2019-08-21T07:33:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-24T15:46:58.000Z", "max_issues_repo_path": "content/bayesian-inference-and-graphical-models/code/pp_ex_1.jl", "max_issues_repo_name": "seanrattana/courses", "max_issues_repo_head_hexsha": "9453abc38af26ea49cb00fe1744066fc0de237b3", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-08-23T06:04:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-26T12:47:12.000Z", "max_forks_repo_path": "content/bayesian-inference-and-graphical-models/code/pp_ex_1.jl", "max_forks_repo_name": "seanrattana/courses", "max_forks_repo_head_hexsha": "9453abc38af26ea49cb00fe1744066fc0de237b3", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-08-18T21:23:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-02T19:14:33.000Z", "avg_line_length": 25.7346938776, "max_line_length": 85, "alphanum_fraction": 0.7042030135, "num_tokens": 389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799482964023, "lm_q2_score": 0.8791467564270271, "lm_q1q2_score": 0.84730401545419}} {"text": "#Tutorial 2\n#=\nDaniel\n=#\n# ## is a break on the code\n\n# control+c to stop the process\nmy_integer=5\nmy_float=5.\nmy_range=1:7\nmy_vector=[1, 3, 5]\nmy_string=\"hello\"\nmy_character='o'\nmy_boolean=true\n\ntypeof(my_integer)\ntypeof(my_float)\n\ntypeof(\n my_character\n)\n\n# use \\ to write simbols like alpha\nα=5;\n#show the command\n@show α + my_integer\nprint(\"α = $α \\n\", \"My integer is: $(my_integer)\")\n\n#println automatically saparated linea\n\n#column vector\nA = [1, 3, 5]\n#row vector\nA = [1 2 3]\n\nones(3)\nzeros(5)\nC=[1 3; 5 \"test\"]\nC=[1 3; 5 9]\n\nA = 1:9\n# number with a distance o 0.5\nB= 1:0.5:9\n# secon element of break\nB[3]\n\ntypeof(C)\neltype(C)\nsize(C)\nlength(C)\nndims(C)\n\n#indexing\nC[end]\nC[1,2]\n@show C\n@show C[2,:] #show select row*\n\nusing LinearAlgebra\n\nC*I\nC^2\nC.^2 #by element operation\n\nsin.([1 2 3])\n\ninv(C)\ninv(C)*C # too costly\nC\\C # this notation is better\n\n# to installa a package type ], add pkg name\n\nusing Random\nrand(1)\nrand(3)\nrandn(3)\n\nRandom.seed!(1234) #name of the seed\nrand(1)\nrand(1)\n\nRandom.seed!(1234)\nrand(1)\n\n#if/else statement\na=3\nif a==3\n print(\"a is 3\")\nend\n\na=true\nif a\n print(\"a is true\")\nend\n\na ? print(\"a is true\") : nothing\n\nif a \n print(\"a is true\")\nelse \n print(\"a is no true\")\nend\n\nb=true\n\nif a | b \n print(\"a or b is true (or both)\")\nend\n\nif a & b # double & makes faster the process, just evaluate the firs statement. \n print(\"a and b are true\")\nend\n\n#for loops\nvals = [\"a\" \"b\" \"c\"]\n\nfor val in vals\n println(val)\nend\n\n#global\na = 3\nfor val in vals\n a = a + 1\n return a \nend\n\n\nfor i in eachindex(vals)\n println(vals[i])\nend\n\n# index and value \nfor (index, value) in enumerate(vals)\n println(\"Element $index of vals is $value\")\nend\n\n# Functions\nfunction cobbdouglas(l, k, α, β = 1 - α; A=1)\n y=A*l^α*k^β\n return y\nend\n\ncobbdouglas(1, 3, 0.5)\n\n@show output = cobbdouglas(1, 3, 0.5)\n\ncobbdouglas.([1 2], 3, 0.5)\n\ncobbdouglas(l, k, α) = A*l^α*k^(1-α)\ncobbdouglas(1, 3, 0.5)\n\n", "meta": {"hexsha": "1c36c59f55b21bd85cf2692e8d52b004320b43be", "size": 1943, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "demo.jl", "max_stars_repo_name": "DanielGuzmanGiron/Julia_macro", "max_stars_repo_head_hexsha": "ff013189629b515c672b03bb2f0a5cca7403a177", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "demo.jl", "max_issues_repo_name": "DanielGuzmanGiron/Julia_macro", "max_issues_repo_head_hexsha": "ff013189629b515c672b03bb2f0a5cca7403a177", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "demo.jl", "max_forks_repo_name": "DanielGuzmanGiron/Julia_macro", "max_forks_repo_head_hexsha": "ff013189629b515c672b03bb2f0a5cca7403a177", "max_forks_repo_licenses": ["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.6993464052, "max_line_length": 81, "alphanum_fraction": 0.6356150283, "num_tokens": 732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837706, "lm_q2_score": 0.9324533130837862, "lm_q1q2_score": 0.8472437637074727}} {"text": "\"Square the sum of the first `n` positive integers\"\nfunction square_of_sum(n)\n sum(1:n)^2\nend\n\n\"Sum the squares of the first `n` positive integers\"\nfunction sum_of_squares(n)\n sum((1:n).^2)\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": "406d554fe88af2c332e1372b35df378cdd66ce8e", "size": 353, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "difference-of-squares/difference-of-squares.jl", "max_stars_repo_name": "koladilip/julia-exercism", "max_stars_repo_head_hexsha": "1e67c319ae866a26365da8380659724c5cd472fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "difference-of-squares/difference-of-squares.jl", "max_issues_repo_name": "koladilip/julia-exercism", "max_issues_repo_head_hexsha": "1e67c319ae866a26365da8380659724c5cd472fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "difference-of-squares/difference-of-squares.jl", "max_forks_repo_name": "koladilip/julia-exercism", "max_forks_repo_head_hexsha": "1e67c319ae866a26365da8380659724c5cd472fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5333333333, "max_line_length": 83, "alphanum_fraction": 0.7280453258, "num_tokens": 99, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342037088041, "lm_q2_score": 0.8856314662716159, "lm_q1q2_score": 0.8472253525162079}} {"text": "\"\"\"\n LinearKernel(; c = 0.0)\n\nThe linear kernel is a Mercer kernel given by\n```\n κ(x,y) = xᵀy + c\n```\nWhere `c` is a real number\n\"\"\"\nstruct LinearKernel{Tc<:Real} <: SimpleKernel\n c::Vector{Tc}\n function LinearKernel(;c::T=0.0) where {T}\n new{T}([c])\n end\nend\n\nkappa(κ::LinearKernel, xᵀy::Real) = xᵀy + first(κ.c)\n\nmetric(::LinearKernel) = DotProduct()\n\nBase.show(io::IO, κ::LinearKernel) = print(io, \"Linear Kernel (c = \", first(κ.c), \")\")\n\n\"\"\"\n PolynomialKernel(; d = 2.0, c = 0.0)\n\nThe polynomial kernel is a Mercer kernel given by\n```\n κ(x,y) = (xᵀy + c)^d\n```\nWhere `c` is a real number, and `d` is a shape parameter bigger than 1. For `d = 1` see [`LinearKernel`](@ref)\n\"\"\"\nstruct PolynomialKernel{Td<:Real, Tc<:Real} <: SimpleKernel\n d::Vector{Td}\n c::Vector{Tc}\n function PolynomialKernel(; d::Td=2.0, c::Tc=0.0) where {Td<:Real, Tc<:Real}\n @check_args(PolynomialKernel, d, d >= one(Td), \"d >= 1\")\n return new{Td, Tc}([d], [c])\n end\nend\n\nkappa(κ::PolynomialKernel, xᵀy::Real) = (xᵀy + first(κ.c))^(first(κ.d))\n\nmetric(::PolynomialKernel) = DotProduct()\n\nBase.show(io::IO, κ::PolynomialKernel) = print(io, \"Polynomial Kernel (c = \", first(κ.c), \", d = \", first(κ.d), \")\")\n", "meta": {"hexsha": "09e02ba31dfbaede9ebb3165afd57d2baa12a35b", "size": 1233, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/basekernels/polynomial.jl", "max_stars_repo_name": "tirthasheshpatel/KernelFunctions.jl", "max_stars_repo_head_hexsha": "86d430c8e275a8b41b0a4a68aeb31e488a075b83", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/basekernels/polynomial.jl", "max_issues_repo_name": "tirthasheshpatel/KernelFunctions.jl", "max_issues_repo_head_hexsha": "86d430c8e275a8b41b0a4a68aeb31e488a075b83", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/basekernels/polynomial.jl", "max_forks_repo_name": "tirthasheshpatel/KernelFunctions.jl", "max_forks_repo_head_hexsha": "86d430c8e275a8b41b0a4a68aeb31e488a075b83", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8043478261, "max_line_length": 116, "alphanum_fraction": 0.600973236, "num_tokens": 449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338079816756, "lm_q2_score": 0.8807970685907242, "lm_q1q2_score": 0.8469161594211362}} {"text": "\"\"\"\r\n romberg(f, a, b; maxi = 10, delta = 10^-9)\r\nberisi program untuk mencari integral numerik dari fungsi `f(x)` pada\r\ninterval `[a,b]`. Program ini secara default berisi 3 masukan, yaitu fungsi `f(x)`, dan titik\r\nujung interval `[a,b]`. Secara default memiliki nilai maksimum iterasi `maxi=10` dan\r\ntoleransi error sebesar `delta = 1e-9`\r\n# Examples\r\n```jl\r\njulia> f(x) = (x^2+x+1)*cos(x)\r\nf (generic function with 1 method)\r\n\r\njulia> sol, flag, err, R = romberg(f, 0, pi/2);\r\n\r\njulia> sol\r\n2.0381974270672245\r\n\r\njulia> flag\r\n0\r\n\r\njulia> err\r\n1.213065203842234e-10\r\n\r\njulia> R\r\n6×6 Array{Float64,2}:\r\n 0.785398 0.0 0.0 0.0 0.0 0.0\r\n 1.72681 2.04062 0.0 0.0 0.0 0.0\r\n 1.96053 2.03844 2.0383 0.0 0.0 0.0\r\n 2.01879 2.03821 2.0382 2.0382 0.0 0.0\r\n 2.03335 2.0382 2.0382 2.0382 2.0382 0.0\r\n 2.03698 2.0382 2.0382 2.0382 2.0382 2.0382\r\n\r\n julia> sol, flag, err, R = romberg(f, 0, pi/2, maxi=20, delta=1e-14);\r\n\r\n julia> sol\r\n 2.038197427067236\r\n\r\n julia> flag\r\n 0\r\n\r\n julia> err\r\n 0.0\r\n\r\n julia> R\r\n 8×8 Array{Float64,2}:\r\n 0.785398 0.0 0.0 0.0 0.0 0.0 0.0 0.0\r\n 1.72681 2.04062 0.0 0.0 0.0 0.0 0.0 0.0\r\n 1.96053 2.03844 2.0383 0.0 0.0 0.0 0.0 0.0\r\n 2.01879 2.03821 2.0382 2.0382 0.0 0.0 0.0 0.0\r\n 2.03335 2.0382 2.0382 2.0382 2.0382 0.0 0.0 0.0\r\n 2.03698 2.0382 2.0382 2.0382 2.0382 2.0382 0.0 0.0\r\n 2.03789 2.0382 2.0382 2.0382 2.0382 2.0382 2.0382 0.0\r\n 2.03812 2.0382 2.0382 2.0382 2.0382 2.0382 2.0382 2.0382\r\n```\r\nreturn nilai solusi integral numerik `sol`, status solusi\r\n`flag`, hampiran galat `err`, dan matriks `R` yaitu matriks iterasi Romberg.\r\n\"\"\"\r\nfunction romberg(f, a, b; maxi = 10, delta = 10^-9)\r\n flag = 1;\r\n M = 1;\r\n h = b-a;\r\n err = 1;\r\n R = h/2*(f(a)+f(b));\r\n for J = 1:maxi\r\n # Rekursif Trapesium\r\n h = h/2;\r\n M = 2*M;\r\n s = 0;\r\n for p = 1:M/2\r\n x = a+h*(2*p-1);\r\n s = s+f(x);\r\n end\r\n R = [R zeros(size(R,1),1) ; R[J,1]/2 + h*s zeros(1,size(R,1))]\r\n # Aturan Romberg\r\n for K=1:J\r\n R[J+1,K+1]=R[J+1,K]+(R[J+1,K]-R[J,K])/(4^K-1);\r\n end\r\n err = abs.(R[J,J]-R[J+1,J+1]);\r\n if err Cauchy([1,2,3],[3,4,5])\n3x3 Cauchy{Int64}:\n 0.25 0.2 0.166667\n 0.2 0.166667 0.142857\n 0.166667 0.142857 0.125\n\njulia> Cauchy([1,2,3])\n3x3 Cauchy{Int64}:\n 0.5 0.333333 0.25\n 0.333333 0.25 0.2\n 0.25 0.2 0.166667\n\njulia> Cauchy(pi)\n3x3 Cauchy{Float64}:\n 0.5 0.333333 0.25\n 0.333333 0.25 0.2\n 0.25 0.2 0.166667\n```\n\"\"\"\nstruct Cauchy{T} <: AbstractMatrix{T}\n x::Vector{T} #\n y::Vector{T} #\nend # immutable\n\nfunction Cauchy(k::Number)\n Cauchy(collect(1:k),collect(1:k))\nend\n\nfunction Cauchy(x::Vector)\n Cauchy(x,x)\nend\n\n# Define its size\n\nsize(A::Cauchy, dim::Integer) = dim==1 ? length(A.x) : dim==2 ? length(A.y) : throw(ArgumentError(\"Invalid dimension $dim\"))\nsize(A::Cauchy)= length(A.x), length(A.y)\n\n# Index into a Cauchy\nfunction getindex(A::Cauchy,i::Integer,j::Integer)\n return 1.0/(A.x[i]+A.y[j])\nend # getindex\n\n# Dense version of Cauchy\nMatrix(A::Cauchy) = [A[i,j] for i=1:size(A,1), j=1:size(A,2)]\n", "meta": {"hexsha": "c4069d6ee157fe203bc9b80bf70318661112d926", "size": 1208, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/cauchy.jl", "max_stars_repo_name": "JuliaMath/SpecialMatrices.jl", "max_stars_repo_head_hexsha": "05cb35883d25495aec69d6fb8bc7d40460ddcdb8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2018-09-13T10:26:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T23:21:37.000Z", "max_issues_repo_path": "src/cauchy.jl", "max_issues_repo_name": "JuliaMath/SpecialMatrices.jl", "max_issues_repo_head_hexsha": "05cb35883d25495aec69d6fb8bc7d40460ddcdb8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 36, "max_issues_repo_issues_event_min_datetime": "2017-08-17T17:39:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-31T18:27:05.000Z", "max_forks_repo_path": "src/cauchy.jl", "max_forks_repo_name": "JuliaMath/SpecialMatrices.jl", "max_forks_repo_head_hexsha": "05cb35883d25495aec69d6fb8bc7d40460ddcdb8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2017-08-17T16:49:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-21T10:22:09.000Z", "avg_line_length": 21.9636363636, "max_line_length": 124, "alphanum_fraction": 0.6067880795, "num_tokens": 513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403979493139, "lm_q2_score": 0.9111797082028671, "lm_q1q2_score": 0.8468872305954125}} {"text": "# # SVM with L^1 regularization\n## Generate data for SVM classifier with L1 regularization.\nusing Random\nRandom.seed!(3);\nn = 20;\nm = 1000;\nTEST = m;\nDENSITY = 0.2;\nbeta_true = randn(n,1);\nidxs = randperm(n)[1:round(Int, (1-DENSITY)*n)];\nbeta_true[idxs] .= 0\noffset = 0;\nsigma = 45;\nX = 5 * randn(m, n);\nY = sign.(X * beta_true .+ offset .+ sigma * randn(m,1));\nX_test = 5 * randn(TEST, n);\n\n#-\n\n## Form SVM with L1 regularization problem.\nusing Convex, SCS, ECOS\n\nbeta = Variable(n);\nv = Variable();\nloss = sum(pos(1 - Y .* (X*beta - v)));\nreg = norm(beta, 1);\n\n## Compute a trade-off curve and record train and test error.\nTRIALS = 100\ntrain_error = zeros(TRIALS);\ntest_error = zeros(TRIALS);\nlambda_vals = exp10.(range(-2, stop=0, length=TRIALS);)\nbeta_vals = zeros(length(beta), TRIALS);\nfor i = 1:TRIALS\n lambda = lambda_vals[i];\n problem = minimize(loss/m + lambda*reg);\n solve!(problem, ECOS.Optimizer(verbose=0));\n ## solve!(problem, SCS.Optimizer(verbose=0,linear_solver=SCS.Direct, eps=1e-3))\n train_error[i] = sum(float(sign.(X*beta_true .+ offset) .!= sign.(evaluate(X*beta - v))))/m;\n test_error[i] = sum(float(sign.(X_test*beta_true .+ offset) .!= sign.(evaluate(X_test*beta - v))))/TEST;\n beta_vals[:, i] = evaluate(beta);\nend\n\n#-\n\n# Plot the train and test error over the trade-off curve.\nusing Plots\nplot(lambda_vals, train_error, label=\"Train error\");\nplot!(lambda_vals, test_error, label=\"Test error\");\nplot!(xscale=:log, yscale=:log, ylabel=\"errors\", xlabel=\"lambda\")\n\n#-\n\n# Plot the regularization path for beta.\n\nplot()\nfor i = 1:n\n plot!(lambda_vals, vec(beta_vals[i,:]), label=\"beta$i\")\nend\nplot!(xscale=:log, ylabel=\"betas\", xlabel=\"lambda\")\n", "meta": {"hexsha": "b64e8ffdcf07c4ce0c1d25ee4ad3490071a0f5bf", "size": 1692, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/examples_literate/general_examples/svm_l1regularization.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/svm_l1regularization.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/svm_l1regularization.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": 27.737704918, "max_line_length": 108, "alphanum_fraction": 0.6654846336, "num_tokens": 531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475699138558, "lm_q2_score": 0.8976952927915968, "lm_q1q2_score": 0.8468386729780601}} {"text": "# Basic control flow\n#\n# # Fibonnacci numbers\n#\n# The Fibonnacci sequence is: 1, 1, 2, 3, 5, 8, 13..., where each subsequent\n# number is the sum of the prior two numbers. Create a function that computes\n# the N-th Fibonnacci number.\n# Options:\n# * Iterative: use a for loop and keep track of prior two values to add them\n# What happens if you ask for the 95th number? The 96th? 97th?\n# * Recursive: work backwards and add the prior two numbers together\n# How long does it take to get the 40th number? The 41st? 42nd?\n# * Matrix magic\n\n\n\n# # Monte-carlo pi\n#\n# Create a function that estimates pi by repeatedly throwing a dart at a square\n# board. It's easy to test if the particular dart landed inside the circle —\n# just ask if x^2 + y^2 < 1! Then comparing the number inside vs. the total\n# gives you the ratio of the circle's area to the square's area.\n\nusing Images\nload(download(\"http://corysimon.github.io/images/julia/myplot.png\"))\n\n# Plot the error as the number of iterations increases\n\n# # Packages\n#\n# Add the Primes package. What does it do? How do you compute the 100th prime?\n# A very large prime number?\n#\n#\n", "meta": {"hexsha": "1b1bcc387a68a96985c9bbce0bca0c0eb796259c", "size": 1163, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Courses/Introduction to Julia/Day One Exercises.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/Day One Exercises.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/Day One Exercises.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": 33.2285714286, "max_line_length": 82, "alphanum_fraction": 0.7024935512, "num_tokens": 317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140225647107, "lm_q2_score": 0.8757869867849166, "lm_q1q2_score": 0.8468107183020309}} {"text": "\"\"\"\n area(poly)\n\nCalculate the signed area via the shoelace formula. If the points are ordered\ncounterclockwise, the result will be positive. If the points are ordered clockwise,\nthe result will be negative.\n\"\"\"\nfunction area(poly::T) where T\n a = zero(eltype(eltype(T)))\n @inbounds for i in 1:length(poly)-1\n p1 = poly[i]\n p2 = poly[i+1]\n a += p1[1]*p2[2]-p2[1]*p1[2]\n end\n return a/2\nend\n\nfunction centroid(poly::T) where T\n ZT = zero(eltype(eltype(T)))\n a = ZT\n c = zero(eltype(poly))\n\n @inbounds for i in 1:length(poly)-1\n p = poly[i]\n n = poly[i+1]\n k = p[1]*n[2]-n[1]*p[2]\n a += k\n c = c .+ (p.+n).*k\n end\n a /= 2\n return c./(6*a)\nend\n", "meta": {"hexsha": "772daa148065ab4b9374126654dabf45b773199e", "size": 733, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/area.jl", "max_stars_repo_name": "JuliaGeometry/PolygonOps.jl", "max_stars_repo_head_hexsha": "5e53280721ff04b507e7d76dd13bf7a37449b413", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2020-03-29T02:04:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-15T08:43:43.000Z", "max_issues_repo_path": "src/area.jl", "max_issues_repo_name": "JuliaGeometry/PolygonOps.jl", "max_issues_repo_head_hexsha": "5e53280721ff04b507e7d76dd13bf7a37449b413", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-03-29T16:23:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-04T04:08:33.000Z", "max_forks_repo_path": "src/area.jl", "max_forks_repo_name": "JuliaGeometry/PolygonOps.jl", "max_forks_repo_head_hexsha": "5e53280721ff04b507e7d76dd13bf7a37449b413", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-01-22T22:26:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T19:59:51.000Z", "avg_line_length": 22.2121212121, "max_line_length": 83, "alphanum_fraction": 0.5579809004, "num_tokens": 247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9648551495568569, "lm_q2_score": 0.8774767954920548, "lm_q1q2_score": 0.8466380047471581}} {"text": "\"\"\"\r\n make_twospirals(; n_samples::Int = 2000,\r\n start_degrees::Int = 90,\r\n total_degrees::Int = 570,\r\n noise::Float64 = 0.2\r\nGenerate two spirals dataset. Return a Nx3 matrix, where each line contains the X,Y coordinates and the class of an instance.\r\n# Arguments\r\n- `n_samples::Int = 2000`: The total number of points generated.\r\n- `start_degrees::Int = 90`: Determines how far from the origin the spirals start.\r\n- `total_degrees::Int = 570`: Controls the lenght of the spirals.\r\n- `noise::Float64 = 0.2`: Determines the noise in the dataset.\r\nReference: [link](https://la.mathworks.com/matlabcentral/fileexchange/41459-6-functions-for-generating-artificial-datasets)\r\n\"\"\"\r\nfunction make_twospirals(; n_samples::Int = 2000,\r\n start_degrees::Int = 90,\r\n total_degrees::Int = 570,\r\n noise::Float64 = 0.2)\r\n start_degrees = deg2rad(start_degrees);\r\n\r\n N1 = floor(Int, n_samples / 2);\r\n N2 = n_samples - N1;\r\n\r\n n = start_degrees .+ sqrt.(rand(N1,1)) .* deg2rad(total_degrees);\r\n d1 = [-cos.(n).*n + rand(N1,1).*noise sin.(n).*n+rand(N1,1).*noise];\r\n\r\n n = start_degrees .+ sqrt.(rand(N2,1)) .* deg2rad(total_degrees);\r\n d2 = [cos.(n).*n+rand(N2,1)*noise -sin.(n).*n+rand(N2,1)*noise];\r\n\r\n features = [d1; d2]\r\n labels = [zeros(Int, N1); ones(Int, N2)]\r\n\r\n return convert(features, labels);\r\nend\r\n\r\n\"\"\"\r\n make_halfkernel(; n_samples::Int = 1000,\r\n minx::Int = -20,\r\n r1::Int = 20,\r\n r2::Int = 35,\r\n noise::Float64 = 4.0,\r\n ratio::Float64 = 0.6)\r\nGenerates two half ellipses, one inside the other\r\n# Arguments\r\n- `n_samples::Int = 1000`: The total number of points generated\r\n- `r1::Int = 20`:\r\n- `r2::Int = 35`:\r\n- `minx::Int = -20`:\r\n- `noise::Float64 = 0.2`: Determines the noise in the dataset.\r\n- `ratio::Float64 = 0.6)`:\r\nReference: [link](https://la.mathworks.com/matlabcentral/fileexchange/41459-6-functions-for-generating-artificial-datasets)\r\n\"\"\"\r\nfunction make_halfkernel(; n_samples::Int = 1000,\r\n minx::Int = -20,\r\n r1::Int = 20,\r\n r2::Int = 35,\r\n noise::Float64 = 4.0,\r\n ratio::Float64 = 0.6)\r\n\r\n N = floor(Int, n_samples / 2)\r\n\r\n phi1 = rand(N, 1) * pi\r\n inner = [minx .+ r1 .* sin.(phi1) .- .5 .* noise .+ noise .* rand(N, 1) r1 .* ratio .* cos.(phi1) .- .5 .* noise .+ noise .* rand(N,1)]\r\n l1 = ones(Int, N)\r\n\r\n phi2 = rand(N,1) * pi\r\n outer = [minx .+ r2 .* sin.(phi2) .- .5 .* noise .+ noise .* rand(N,1) r2 .* ratio .* cos.(phi2) .- .5 .* noise .+ noise .* rand(N,1)]\r\n l2 = zeros(Int, N)\r\n\r\n\r\n features = [inner; outer]\r\n labels = [l1; l2]\r\n\r\n return convert(features, labels)\r\nend\r\n\r\n\"\"\"\r\n make_outlier(;n_samples::Int = 600,\r\n r::Int = 20,\r\n dist::Int = 30,\r\n outliers::Float64 = 0.04,\r\n noise::Float64 = 5.0)\r\nGenerates outlier dataset.\r\n# Arguments\r\n- `n_samples::600 = 1000`: The total number of points generated.\r\n- `r::Int = 20`: Radius of lateral blobs.\r\n- `dist::Int = 30`: Determine the distance between the labels.\r\n- `noise::Float64 = 5.0`: Determines the noise in the dataset.\r\nReference: [link](https://la.mathworks.com/matlabcentral/fileexchange/41459-6-functions-for-generating-artificial-datasets)\r\n\"\"\"\r\nfunction make_outlier(;n_samples::Int = 600,\r\n r::Int = 20,\r\n dist::Int = 30,\r\n outliers::Float64 = 0.04,\r\n noise::Float64 = 5.0)\r\n\r\n n1 = round(Int, (n_samples * (0.5 - outliers)) )\r\n n2 = n1\r\n n3 = round(Int, n_samples * outliers)\r\n n4 = n_samples - n1 - n2 - n3\r\n\r\n phi1 = rand(n1, 1) * pi\r\n r1 = sqrt.(rand(n1, 1)) * r\r\n p1 = [ -dist .+ (r1 .* sin.(phi1)) r1 .* cos.(phi1)]\r\n l1 = zeros(Int, n1)\r\n\r\n phi2 = rand(n2, 1) * pi\r\n r2 = sqrt.(rand(n2, 1)) * r\r\n p2 = [ dist .- r2.*sin.(phi2) r2.*cos.(phi2)]\r\n l2 = 3 * ones(Int, n2)\r\n\r\n p3 = [ rand(n3, 1) * noise dist .+ rand(n3, 1) * noise ]\r\n l3 = 2 * ones(Int, n3)\r\n\r\n p4 = [ rand(n4, 1) * noise -dist .+ rand(n4, 1) * noise ]\r\n l4 = ones(Int, n4)\r\n\r\n features = [p1; p2; p3; p4]\r\n labels = [l1; l2; l3; l4]\r\n\r\n return convert(features, labels)\r\nend\r\n", "meta": {"hexsha": "f2012686c747fe0ddc9f3c3aa39680a816b5e401", "size": 4648, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/matlab.jl", "max_stars_repo_name": "Axel-Jacobsen/SyntheticDatasets.jl", "max_stars_repo_head_hexsha": "e3ff1c51e505e5118de975d50dd438a46eeb3591", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2020-09-06T11:59:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-24T15:08:52.000Z", "max_issues_repo_path": "src/matlab.jl", "max_issues_repo_name": "Axel-Jacobsen/SyntheticDatasets.jl", "max_issues_repo_head_hexsha": "e3ff1c51e505e5118de975d50dd438a46eeb3591", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 40, "max_issues_repo_issues_event_min_datetime": "2020-08-19T13:57:59.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-14T04:48:12.000Z", "max_forks_repo_path": "src/matlab.jl", "max_forks_repo_name": "Axel-Jacobsen/SyntheticDatasets.jl", "max_forks_repo_head_hexsha": "e3ff1c51e505e5118de975d50dd438a46eeb3591", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-12T05:48:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-12T05:48:29.000Z", "avg_line_length": 38.0983606557, "max_line_length": 140, "alphanum_fraction": 0.5135542169, "num_tokens": 1389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551556203816, "lm_q2_score": 0.8774767810736693, "lm_q1q2_score": 0.8466379961561067}} {"text": "begin\n# Interpolation Search\n\n# Julia code to interpolation search x in arr[].\n# If x is present then return its location,\n# otherwise return -1\nimport Base:length,show,AbstractArray\narr = [10, 12, 13, 16, 18, 19, 20, 21,22, 23, 24, 33, 35, 42, 47] \nx = 18\nn = length(arr)\nfunction interpolationsearch(arr::AbstractArray{},n,x)\n# Find indexs of two corners \n lo = 1\n hi = n\n \n # Since array is sorted, an element present \n # in array must be in range defined by corner \n while lo <= hi && x >= arr[lo] && x <= arr[hi]\n if lo == hi\n if arr[lo] == x \n return lo; \n\t\t\tend\n return -1; \n\t\tend \n # Probing the position with keeping \n # uniform distribution in mind. \n pos = lo + round(Int,(float(hi - lo)) / ( arr[hi] - arr[lo])) * ( x - arr[lo])\n \n # Condition of target found \n if arr[pos] == x\n return pos \n\t\tend\n # If x is larger, x is in upper part \n if arr[pos] < x\n lo = pos + 1; \n # If x is smaller, x is in lower part \n else\n hi = pos - 1; \n\t\tend\n\tend\n return -1\nend\nglobal result=-1\n\nresult=interpolationsearch(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": "0a465acb34b7b42ca68dd951f9dde81b40c9eafb", "size": 1397, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Searching_Algorithms/Interpolation_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/Interpolation_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/Interpolation_Search.jl", "max_forks_repo_name": "Learning-Julia/Algorithms", "max_forks_repo_head_hexsha": "cb8ba88e155c65c58f124bed9870e97a76c85be8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8703703704, "max_line_length": 87, "alphanum_fraction": 0.5726556908, "num_tokens": 417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582477806521, "lm_q2_score": 0.909907012756525, "lm_q1q2_score": 0.8466304847327637}} {"text": "using DataFrames, GLM, Statistics, LinearAlgebra, CSV\ndata = CSV.read(\"../data/L1L2data.csv\")\nxVals, yVals = data[:,1], data[:,2]\nn = length(xVals)\nA = [ones(n) xVals]\n\n# Approach A\nxBar, yBar = mean(xVals),mean(yVals)\nsXX, sXY = ones(n)'*(xVals.-xBar).^2 , dot(xVals.-xBar,yVals.-yBar)\nb1A = sXY/sXX\nb0A = yBar - b1A*xBar\n\n# Approach B\nb1B = cor(xVals,yVals)*(std(yVals)/std(xVals))\nb0B = yBar - b1B*xBar\n\n# Approach C\nb0C, b1C = A'A \\ A'yVals\n\n# Approach D\nAdag = inv(A'*A)*A'\nb0D, b1D = Adag*yVals\n\n# Approach E\nb0E, b1E = pinv(A)*yVals\n\n# Approach F\nb0F, b1F = A\\yVals\n\n# Approach G\nF = qr(A)\nQ, R = F.Q, F.R\nb0G, b1G = (inv(R)*Q')*yVals\n\n# Approach H\nF = svd(A)\nV, Sp, Us = F.V, Diagonal(1 ./ F.S), F.U'\nb0H, b1H = (V*Sp*Us)*yVals\n\n# Approach I\neta, eps = 0.002, 10^-6.\nb, bPrev = [0,0], [1,1]\nwhile norm(bPrev-b) >= eps\n global bPrev = b\n global b = b - eta*2*A'*(A*b - yVals)\nend\nb0I, b1I = b[1], b[2]\n\n# Approach J\nmodelJ = lm(@formula(Y ~ X), data)\nb0J, b1J = coef(modelJ)\n\n# Approach K\nmodelK = glm(@formula(Y ~ X), data, Normal())\nb0K, b1K = coef(modelK)\nprintln(round.([b0A,b0B,b0C,b0D,b0E,b0F,b0G,b0H,b0I,b0J,b0K],digits=3))\nprintln(round.([b1A,b1B,b1C,b1D,b1E,b1F,b1G,b1H,b1I,b1J,b1K],digits=3))", "meta": {"hexsha": "af675558086543ac63f931427d0014f0a4142940", "size": 1215, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "8_chapter/leastSqMethods.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "8_chapter/leastSqMethods.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "8_chapter/leastSqMethods.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 21.3157894737, "max_line_length": 71, "alphanum_fraction": 0.6205761317, "num_tokens": 556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.974434788304004, "lm_q2_score": 0.8688267745399465, "lm_q1q2_score": 0.8466150341216834}} {"text": "\"\"\"\n laguerre(x, p::Integer)\n\nEvaluate the Laguerre polynomial of degree `p` at `x` using the three term recursion.\n\"\"\"\nfunction laguerre(x, p::Integer)\n T = typeof( 1-x )\n p₀ = one(T)\n p₁ = 1-x\n\n if p <= 0\n return p₀\n elseif p == 1\n return p₁\n end\n\n for n in 2:p\n p₀, p₁ = p₁, ( (2n-1-x)*p₁ - (n-1)*p₀ ) / n\n end\n\n p₁\nend\n\n\"\"\"\n laguerre(x, p::Integer, α)\n\nEvaluate the generalised Laguerre polynomial with parameter `α` of degree `p`\nat `x` using the three term recursion.\n\"\"\"\nfunction laguerre(x, p::Integer, α)\n T = typeof( α+1-x )\n p₀ = one(T)\n p₁ = α+1-x\n\n if p <= 0\n return p₀\n elseif p == 1\n return p₁\n end\n\n for n in 2:p\n p₀, p₁ = p₁, ( (α+2n-1-x)*p₁ - (α+n-1)*p₀ ) / n\n end\n\n p₁\nend\n", "meta": {"hexsha": "869528736c12df0c9b88fc377acccbd739a62822", "size": 794, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/laguerre.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/PolynomialBases.jl-c74db56a-226d-5e98-8bb0-a6049094aeea", "max_stars_repo_head_hexsha": "7a1ac70cbdae378323a4dd611c8dc1386222c71f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-09-11T18:12:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T21:08:56.000Z", "max_issues_repo_path": "src/laguerre.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/PolynomialBases.jl-c74db56a-226d-5e98-8bb0-a6049094aeea", "max_issues_repo_head_hexsha": "7a1ac70cbdae378323a4dd611c8dc1386222c71f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2018-02-15T06:32:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-11T15:59:07.000Z", "max_forks_repo_path": "src/laguerre.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/PolynomialBases.jl-c74db56a-226d-5e98-8bb0-a6049094aeea", "max_forks_repo_head_hexsha": "7a1ac70cbdae378323a4dd611c8dc1386222c71f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-02-26T18:34:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:01:42.000Z", "avg_line_length": 16.8936170213, "max_line_length": 85, "alphanum_fraction": 0.5226700252, "num_tokens": 302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107931567176, "lm_q2_score": 0.9032942054022056, "lm_q1q2_score": 0.8465770786988681}} {"text": "\"\"\"\nVerlet integration is an integration method used to integrate newtons - law of motion. It is frequently used to find trajectories in molecular dynamics simulation.\nThe function takes `four` inputs viz,\n- `f` : the differential equation\n- `x0` : the initial condition. This is a Vector with the first element as initial value for position (x_0) and the second initial condition for velocity (v_0) \n- `tspan`: is the time span for integration. It is a tuple (initial time, final time)\nThis functionr returns a tuple (x,t):\n- `x` is the solution\n- `t` is the array containing the time points\nReference:\n- https://www.algorithm-archive.org/contents/verlet_integration/verlet_integration.html\nContributed by: [Ved Mahajan](https://github.com/Ved-Mahajan)\n\"\"\"\nfunction verlet_integration(f, x0, tspan, Δt = 1.0e-3)\n s, e = tspan\n N = Int(floor((e - s) / Δt))\n x = Vector{Float64}(undef, N)\n t = collect(s:Δt:(e-Δt))\n x[1] = x0[1]\n x[2] = x0[1] + x0[2] * Δt + 0.5 * f(x0[1]) * (Δt)^2\n\n for i in 2:(N-1)\n x[i+1] = 2 * x[i] - x[i-1] + f(x[i]) * (Δt)^2\n end\n return x, t\nend\n", "meta": {"hexsha": "324028fa62ec67ede988b7f19f03a5943cef5e0f", "size": 1103, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/verlet.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": "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/verlet.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/verlet.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": 40.8518518519, "max_line_length": 163, "alphanum_fraction": 0.6681776972, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960951711746926, "lm_q2_score": 0.8807970873650401, "lm_q1q2_score": 0.8464034688051421}} {"text": "module Newtonsmethod\n\nusing ForwardDiff, LinearAlgebra\n\nfunction newtonroot(f, f′; x₀, tolerance = 1E-7, maxiter = 1000)\n # setup the algorithm\n x_old = x₀\n normdiff = Inf\n iter = 1\n while normdiff > tolerance && iter <= maxiter\n x_new = x_old - f(x_old)/f′(x_old)\n normdiff = norm(x_new - x_old)\n x_old = x_new\n iter = iter + 1\n end\n if iter < maxiter\n return (value = x_old, normdiff = normdiff, iter = iter)\n else\n return nothing\n end\nend\n\nD(f) = x -> ForwardDiff.derivative(f, x)\n\nnewtonroot(f; x₀, tolerance = 1E-7, maxiter = 1000) = newtonroot(f, D(f); x₀ = x₀, tolerance=tolerance, maxiter=maxiter)\n\nexport newtonroot\n\nend # module\n", "meta": {"hexsha": "eb5c7a6cf9356c7c5cb412dd9f8f16f3ca5f5379", "size": 708, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Newtonsmethod.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": "src/Newtonsmethod.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": "src/Newtonsmethod.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": 23.6, "max_line_length": 120, "alphanum_fraction": 0.6271186441, "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542817548989, "lm_q2_score": 0.8824278695464501, "lm_q1q2_score": 0.8463844694153311}} {"text": "\n# transition band is cosine. This allows satisfies the power complementary condition.\n# cos( (yp-y)/(yp-ys) * π/2 ) for a falling edge. yp is pass band, ys is stop band.\nfunction cosinetransitionlowpassfunction(y::T, yp::T, ys::T)::T where T\n abs_y = abs(y)\n\n if abs_y <= yp\n return one(T)\n elseif yp < abs_y <= ys\n #return cos( (yp-y)/(ys-yp)*π/2 )\n return cos( (yp-abs_y)/(ys-yp)*π/2 )\n end\n\n return zero(T)\nend\n\nfunction cosinetransitionhighpassfunction(x::T, xp::T, xs::T)::T where T\n abs_x = abs(x)\n\n if abs_x <= xs\n return zero(T)\n elseif xs < abs_x <= xp\n #return cos( (xp-x)/(xp-xs)*π/2 )\n return cos( (xp-abs_x)/(xp-xs)*π/2 )\n end\n\n return one(T)\nend\n\n\n# rs is rising edge's stopband.\n# rp is rising edge's passband.\n# fp is falling edge's passband.\n# fs is falling edge's stopband.\nfunction cosinetransitionbandpassfunction(y::T, rs, rp, fp, fs)::T where T\n abs_y = abs(y)\n\n # rising edge.\n if abs_y <= rs\n return zero(T)\n elseif rs < abs_y <= rp\n #return cos( (rp-y)/(rp-rs)*π/2 )\n return cos( (rp-abs_y)/(rp-rs)*π/2 )\n end\n\n # falling edge.\n if rp <= abs_y <= fp\n return one(T)\n elseif fp < abs_y <= fs\n #return cos( (fp-y)/(fs-fp)*π/2 )\n return cos( (fp-abs_y)/(fs-fp)*π/2 )\n end\n\n return zero(T)\nend\n", "meta": {"hexsha": "ead81b83db2b3abb343739db3bcb1591cb0b3497", "size": 1359, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/filter_helpers.jl", "max_stars_repo_name": "RoyCCWang/FIRRemez", "max_stars_repo_head_hexsha": "41a3ad4e8bd851d51a62c7fcd35ac3abf6fdd84c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/filter_helpers.jl", "max_issues_repo_name": "RoyCCWang/FIRRemez", "max_issues_repo_head_hexsha": "41a3ad4e8bd851d51a62c7fcd35ac3abf6fdd84c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/filter_helpers.jl", "max_forks_repo_name": "RoyCCWang/FIRRemez", "max_forks_repo_head_hexsha": "41a3ad4e8bd851d51a62c7fcd35ac3abf6fdd84c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.2678571429, "max_line_length": 85, "alphanum_fraction": 0.5761589404, "num_tokens": 441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542875927779, "lm_q2_score": 0.8824278602705731, "lm_q1q2_score": 0.8463844656698408}} {"text": "#############################\n# Example of Horner's Method and \n# finding roots of polynomials\n# Created for the YouTube channel\n# https://www.youtube.com/OscarVeliz\n# @author Oscar Veliz\n#############################\n\n# Long Evaluation\nfunction longway(a, x)\n\tresult = 0\n\tfor i in 1:length(a)\n\t\tresult += a[i] * x^(i-1)\n\tend\n\treturn result\nend\n\n# Iterative Horner Evaluation\nfunction horner(a, x)\n\tresult = a[end]\n\tfor i in length(a)-1:-1:1\n\t\tresult = a[i] + x * result\n\tend\n\treturn result\nend\n\n# Recursive Horner Evaluation\nfunction rHorner(a, x, i)\n\tif i == length(a)\n\t\treturn a[i]\n\telse\n\t\treturn a[i] + x * rHorner(a,x,i+1)\n\tend\nend\n\n# Synthetic Division\n# Given array of coefficients and value x return quotient\nfunction quotient(a, x)\n\tq = zeros(length(a))\n\tq[end] = a[end]\n\tfor i in length(a)-1:-1:1\n\t\tq[i] = x * q[i+1]+a[i]\n\tend\n\treturn view(q, 2:length(q))#ignore remainder\nend\n\n# Differentiate using Power Rule\nfunction ddx(a)\n\td = zeros(length(a)-1)\n\tfor i in 1:length(d)\n\t\td[i] = a[i+1]*i\n\tend\n\treturn d\nend\n\n# Find derivative at a point using Horner\nfunction hornerDeriv(a, x)\n\tq = quotient(a, x)\n\treturn horner(q,x)\nend\n\n# Newton's Method strictly on Polynomials using Horner\nfunction newtonHorner(a, x)\n\ti = 0\n\tpx = horner(a,x)\n\t# Power Rule\n\t#q = ddx(a)\n\t#qx = horner(q,x)\n\t# Ruffini's Rule\n\tqx = hornerDeriv(a,x)\n\twhile abs(px) > 0.0000001 && i < 1000\n\t\tif qx == 0 # avoid divide by zero\n\t\t\treturn NaN\n\t\tend\n\t\tx = x - px / qx\n\t\tpx = horner(a,x)\n\t\t#qx = horner(q,x) # Power Rule\n\t\tqx = hornerDeriv(a,x) # Ruffini's Rule\n\t\ti = i + 1\n\tend\n\tif i == 1000 # hit the iteration cap (divierging or stuck in loop)\n\t\treturn NaN\n\tend\n\tr = round(x) # check if rounding will give you a better answer\n\tif(abs(horner(a,r)) < abs(horner(a,x)))\n\t\tx = r\n\tend\n\treturn x\nend\n\n# Assumes that there are no imaginary roots\nfunction findRoots(a)\n\troots = zeros(length(a)-1)\n\tfor r in 1:length(roots)\n\t\tprintPoly(a)\n\t\troot = newtonHorner(a,0) # initial guess of zero\n\t\tprintln(\"r\",r,\" = \",root)\n\t\troots[r] = root\n\t\ta = quotient(a,root) # deflation\n\tend\n\treturn roots\nend\n\n# Print in polynomial form instead of array of coefficients\nfunction printPoly(a)\n\tfor i in length(a):-1:1\n\t\t# remove \".0\" at end\n\t\tai = string(a[i])\n\t\tif length(ai) >= 2 && ai[end] == '0' && ai[end-1] == '.'\n\t\t\tai = ai[1:end-2]\n\t\tend\n\t\tif i == 1 # no x term \n\t\t\tprintln(ai)\n\t\telseif i == 2 # no exponent\n\t\t\tprint(ai,\"x + \")\n\t\telse\n\t\t\tprint(ai,\"x^\",(i-1),\" + \")\n\t\tend\n\tend\nend\n\np = [-2310, 727, 382, -72, -8, 1]\nprintln(sort(findRoots(p)))\n", "meta": {"hexsha": "7e53b51f9e1b54797e983ae8253bfb0c9fd52c59", "size": 2503, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/rootfinding/Horner.jl", "max_stars_repo_name": "deboradeben/numerical-veliz", "max_stars_repo_head_hexsha": "afd208d5198315642aab3e0dab20bf27b20ed61c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 73, "max_stars_repo_stars_event_min_datetime": "2018-09-26T22:41:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T15:50:14.000Z", "max_issues_repo_path": "src/rootfinding/Horner.jl", "max_issues_repo_name": "KulakovaEA/numerical-veliz", "max_issues_repo_head_hexsha": "d2f3f80c4179ddc2793a19d334526ae84d6d7480", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-11-18T20:37:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-22T08:59:13.000Z", "max_forks_repo_path": "src/rootfinding/Horner.jl", "max_forks_repo_name": "KulakovaEA/numerical-veliz", "max_forks_repo_head_hexsha": "d2f3f80c4179ddc2793a19d334526ae84d6d7480", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16, "max_forks_repo_forks_event_min_datetime": "2018-11-14T17:19:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T21:50:34.000Z", "avg_line_length": 20.185483871, "max_line_length": 67, "alphanum_fraction": 0.6272473032, "num_tokens": 847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104904802132, "lm_q2_score": 0.8757869948899666, "lm_q1q2_score": 0.8463697392878046}} {"text": "# # Portfolio Optimisation\n#\n# We consider a single-period Markowitz portfolio optimisation example.\n# Assume that we have a portfolio with $n$ assets at the beginning of time period $t$. Given some forecasts on risks and expected returns we try to find the optimal trade vector that rebalances the portfolio to achieve a good balance between expected risk (variance) $x^\\top \\Sigma x$ and returns $\\mu^\\top x$. In it's most simple form we want to solve:\n# $$\n# \\begin{array}{ll} \\text{maximize} & \\mu^\\top x - \\gamma (x^\\top \\Sigma x)\\\\\n# \\text{subject to} & 1^\\top x = d + 1^\\top x^0 \\\\\n# & x \\geq 0,\n# \\end{array}\n# $$\n# with variable $x \\in \\mathbf{R}^n$, $\\mu$ forecasted (expected) returns, $\\gamma > 0 $ risk aversion parameter. $x^0_i$ represents the initial investment in asset $i$ and $d$ represents the cash reserve. Consequently, the equality constraint tells us that the sum of the new allocation vector $x$ has to equal the initial allocation plus the cash reserve. Furthermore, the covariance matrix of our risk model is given by $\\Sigma \\in \\mathbf{S}_+^n$. Here we assume a factor risk model, i.e. we can write $\\Sigma$ as $\\Sigma = D + F F^\\top$ where $D$ is diagonal and the factor matrix $F$ has a lower rank $k < n$. This approach allows us to reduce the number of nonzeros in the problem. Furthermore, note that we don't consider shortselling in this example. Let's generate some problem data:\n#-\nusing LinearAlgebra, SparseArrays, Random, COSMO, JuMP, Test\n\n## generate the data\nrng = Random.MersenneTwister(1)\nk = 5; # number of factors\nn = k * 10; # number of assets\nD = spdiagm(0 => rand(rng, n) .* sqrt(k))\nF = sprandn(rng, n, k, 0.5); # factor loading matrix\nμ = (3 .+ 9. * rand(rng, n)) / 100. # expected returns between 3% - 12%\nγ = 1.0; # risk aversion parameter\nd = 1 # we are starting from all cash\nx0 = zeros(n);\n\n# We can now write the problem as a QP:\n# $$\n# \\begin{array}{ll} \\text{minimize} & x^\\top D x + y^\\top y - \\gamma^{-1} \\mu^\\top x \\\\\n# \\text{subject to} & y = F^\\top x \\\\\n# & 1^\\top x = d + 1^\\top x^0 \\\\\n# & x \\geq 0.\n# \\end{array}\n# $$\n# Before considering other effects, let's create the model in JuMP and solve it using COSMO:\n#-\n\nmodel = JuMP.Model(with_optimizer(COSMO.Optimizer));\n@variable(model, x[1:n]);\n@variable(model, y[1:k]);\n@objective(model, Min, x' * D * x + y' * y - 1/γ * μ' * x);\n@constraint(model, y .== F' * x);\n@constraint(model, sum(x) == d + sum(x0));\n@constraint(model, x .>= 0);\nJuMP.optimize!(model)\n\n# After solving the problem, we can calculate the expected return and risk $\\sigma= \\sqrt{x^{* \\top} \\Sigma x^*}$:\nx_opt = JuMP.value.(x);\ny_opt = JuMP.value.(y);\nexpected_return_basic = dot(μ, x_opt)\n\n#-\nexpected_risk_basic = sqrt(dot(y_opt, y_opt))\n\n# ## Using standard deviation in the model\n# It is pointed out in \\[1\\] that above problem formulation can lead to numerical problems, e.g. if $\\Sigma$ is not strictly positive semidefinite. Another option is to formulate the risk constraint in terms of the standard deviation $\\|M^\\top x \\|$ where $M M^\\top = D + F F^\\top$ and bound it using a second-order cone constraint:\n# $$\n# \\begin{array}{ll} \\text{minimize} & - \\mu^\\top x \\\\\n# \\text{subject to} & \\|M^\\top x\\| \\leq \\gamma \\\\\n# & 1^\\top x = d + 1^\\top x^0 \\\\\n# & x \\geq 0.\n# \\end{array}\n# $$\n\nMt = [D.^0.5; F']\nmodel = JuMP.Model(with_optimizer(COSMO.Optimizer));\n@variable(model, x[1:n]);\n@objective(model, Min, - μ' * x);\n@constraint(model, [γ; Mt * x] in SecondOrderCone()); # ||M'x|| <= γ\n@constraint(model, sum(x) == d + sum(x0));\n@constraint(model, x .>= 0);\nJuMP.optimize!(model)\n\n# Note that the result is different from the example above because $\\gamma$ scales the problem in a different way. Here it can be seen as an upper bound on the standard deviation of the portfolio.\nx_opt = JuMP.value.(x);\nexpected_return = dot(μ, x_opt)\n# Let us verify that the bound holds:\n@test norm(Mt * x_opt) <= γ\n\n\n# ## Pareto-optimal front\n# The above portfolio optimisation approach yields the optimal expected return for a given level of risk. The result is obviously impacted by the risk aversion $\\gamma$ parameter. To visualise the trade-off and present the investor with an efficient Pareto optimal portfolio for their risk appetite we can compute the optimal portfolio for many choices of $\\gamma$ and plot the corresponding risk-return trade-off curve.\n\ngammas = [ 0.001, 0.01, 0.1, 0.5, 1., 3., 10, 100, 1000]\nrisks = zeros(length(gammas))\nreturns = zeros(length(gammas))\nmodel = JuMP.Model(with_optimizer(COSMO.Optimizer, verbose = false));\n@variable(model, x[1:n]);\n@variable(model, y[1:k]);\n@objective(model, Min, x' * D * x + y' * y - 1/γ * μ' * x);\n@constraint(model, y .== F' * x);\n@constraint(model, sum(x) == d + sum(x0));\n@constraint(model, x .>= 0);\n\n## solve the same problem for different values of γ\nfor (k, gamma) in enumerate(gammas)\n coeff = - 1/gamma * μ\n JuMP.set_objective_coefficient.(model, x, coeff)\n JuMP.optimize!(model)\n x_opt = JuMP.value.(x);\n y_opt = JuMP.value.(y);\n returns[k] = dot(μ, x_opt)\n risks[k] = sqrt(dot(y_opt, y_opt))\nend\n# We can now plot the risk-return trade-off curve:\nusing Plots\nPlots.plot(risks, returns, xlabel = \"Standard deviation (risk)\", ylabel = \"Expected return\", title = \"Risk-return trade-off for efficient portfolios\", legend = false)\n\n# ## Transaction costs\n# In the model above we assume that trading the assets is free and does not impact the market. However, this is clearly not the case in reality. To make the example more realistic consider the following cost $c_j$ associated with the trade $δ_j = x_j - x_j^0$:\n# $$\n# c_j(\\delta_j) = a_j |\\delta_j| + b_j |\\delta_j|^{3/2},\n# $$\n# where the first term models the bid-ask spread and broker fees for asset $j$. The second term models the impact on the market that our trade has. This is obviously only a factor if the volume of our trade is significant. The constant $b_j$ is a function of the total volume traded in the considered time periode and the price volatility of the asset and has to be estimated by the trader. To make this example simple we consider the same coefficients $a$ and $b$ for every asset. The $|\\delta_j|^{3/2}$ term can be easily modeled using a power cone constraint $\\mathcal{K}_{pow} = \\{(x, y, z) \\mid x^\\alpha y^{(1-\\alpha)} \\geq |z|, x \\geq 0, y \\geq 0, 0 \\leq \\alpha \\leq 1 \\}$. In fact this can be used to model any market impact function with exponent greater than 1.\n# We can write the total transaction cost $a^\\top s + b^\\top t$ where $s_j$ bounds the absolute value of $\\delta_j$ and $t_{j}$ is used to bound the term $|x_j - x_j^0|^{3/2} \\leq t_{j}$ using a power cone formulation: $(t_{j}, 1, x_j - x_j^0) \\in \\mathcal{K}_{pow}(2/3)$.\n\n#-\na = 1e-3\nb = 1e-1\nγ = 1.0;\nmodel = JuMP.Model(with_optimizer(COSMO.Optimizer, eps_abs = 1e-5, eps_rel = 1e-5));\n@variable(model, x[1:n]);\n@variable(model, y[1:k]);\n@variable(model, t[1:n]);\n@variable(model, s[1:n]);\n@objective(model, Min, x' * D * x + y' * y - 1/γ * μ' * x);\n@constraint(model, y .== F' * x);\n@constraint(model, x .>= 0);\n\n## transaction costs\n@constraint(model, sum(x) + a * sum(s) + b * sum(t) == d + sum(x0) );\n@constraint(model, [i = 1:n], x[i] - x0[i] <= s[i]); # model the absolute value with slack variable s\n@constraint(model, [i = 1:n], x0[i] - x[i] <= s[i]);\n@constraint(model, [i = 1:n], [t[i], 1, x[i] - x0[i]] in MOI.PowerCone(2/3));\nJuMP.optimize!(model)\n# Let's look at the expected return and the total transaction cost:\n\nx_opt = JuMP.value.(x);\ny_opt = JuMP.value.(y);\ns_opt = JuMP.value.(s);\nt_opt = JuMP.value.(t);\nexpected_return = dot(μ, x_opt)\n#-\nexpected_risk = dot(y_opt, y_opt)\n#-\ntransaction_cost = a * sum(s_opt) + b * sum( t_opt)\n\n\n# ## References\n# [1] [Mosek Case Studies](https://docs.mosek.com/9.2/pythonfusion/case-studies-portfolio.html)\n", "meta": {"hexsha": "923b99125965e0dbc54e8ada89b62a96e7769b74", "size": 7908, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/portfolio_optimisation.jl", "max_stars_repo_name": "msarfati/COSMO.jl", "max_stars_repo_head_hexsha": "c12d46c485ddccba286d3447d60d1cb399402119", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/portfolio_optimisation.jl", "max_issues_repo_name": "msarfati/COSMO.jl", "max_issues_repo_head_hexsha": "c12d46c485ddccba286d3447d60d1cb399402119", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/portfolio_optimisation.jl", "max_forks_repo_name": "msarfati/COSMO.jl", "max_forks_repo_head_hexsha": "c12d46c485ddccba286d3447d60d1cb399402119", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.72, "max_line_length": 793, "alphanum_fraction": 0.6679312089, "num_tokens": 2434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037323284109, "lm_q2_score": 0.9136765145991261, "lm_q1q2_score": 0.8463419656139843}} {"text": "using Symbolics, ModelingToolkit, Plots, DifferentialEquations\nusing BenchmarkTools\n\n# define variables\n@variables x y\n\n# expressions are exactly as you would think\nx^2+y^2\n\n# common derivative operations\nSymbolics.derivative(x^2 + y^2, x)\nSymbolics.gradient(x^2 + y^2, [x, y])\nSymbolics.jacobian([x^2 + y^2; y^2], [x, y])\n\n# other operations # i.e. replace x with y^2\nsubstitute(sin(x)^2 + 2 + cos(x)^2, Dict(x=>y^2))\n\n# substitute numerical value\nsubstitute(sin(x)^2 + 2 + cos(x)^2, Dict(x=>1.0))\n\n# simplify expression to 3 (the analytic value)\nsimplify(sin(x)^2 + 2 + cos(x)^2)\n\n# direct simplification is performed\n2x-x # x\n\nex = x^2 + y^2 + sin(x)\n\nex + ex\nex / ex\nex^2/ex\n\n\n# compare terms\nisequal(ex^2/ex, ex)\n\n# what if we have stochasticity?\nfoo(x, y) = x * rand() + y\n@register foo(x,y) # this tells symbolic not trace further into function\nSymbolics.derivative(foo(hypot(x, y), y), x)\n# this leaves stops the derivative at foo(x,y) and returns result with differential using the chain rule\n# since we don't know how to take (d foo/ dx)\n\n\n# figure out the type that x is representing\nSymbolicUtils.symtype(Symbolics.value(x))\n\n\n# tell symbolics that z is a complex number\n@variables z::Complex\n\n# automatically perform correct algebra\nz^2\n\nreal(z^2)\n\nz'z # i.e. z_conj * z\n\n\n# xs is a symbolic vector of length 10\n@variables xs[1:10]\n\nxs[1]\n\nsum(xs) # lazy representation of sum operation\n\n# eagerly evaluate summation\nsum(collect(xs))\n\n\n\n# Rosenbrock function\nrosenbrock(xs) = sum(1:length(xs)-1) do i\n 100*(xs[i+1] - xs[i]^2)^2 + (1-xs[i])^2\nend\n\nN = 100\nxs = ones(N) # location of minimum\n\nrosenbrock(xs)\n\n# check that it is a minimum via small perturbations to check concavity\nrosenbrock(xs + 1e-6*rand(N))\nrosenbrock(xs + 1e-2*rand(N))\n\n\n# passing symbolic variables to julia functions produces symbolic functions\n@variables xs[1:N]\nrosenbrock(xs)\n\nxs = collect(xs) # expand into eager represenation\nrxs = rosenbrock(xs)\n# compute gradient of rosenbrock\ngrad = Symbolics.gradient(rxs, xs)\nhess = Symbolics.jacobian(grad, xs)\n# or\nhess = Symbolics.hessian(rxs, xs) # Hessian is zeroes.\nhess_sparse = Symbolics.sparsehessian(rxs, xs) # we could also do sparse jacobian.\n\n# check that it worked\nsize(hess_sparse)\nhess_sparse[1,1]\n\n# to get just the sparsity pattern we can do this:\nhes_sparsity = Symbolics.hessian_sparsity(rxs, xs)\nhes_sparsity[1,1]\n\n# plot the sparsity matrix\nspy(hes_sparsity)\n\n\n@benchmark Symbolics.hessian($rxs, $xs)\n@benchmark Symbolics.sparsehessian($rxs, $xs)\n\n\nfoop, fip = build_function(grad, xs, expression=false) # out of place, in place\n\n\naa = rand(N)\nout = similar(aa) # create output vector\nfip(out, aa) # apply in place function of gradients to aa\nout\n\n\nfoop(aa) ≈ out\n\n\nusing ForwardDiff\n\n# evaluate the Jacobian via forward-mode AD to check\nForwardDiff.gradient(rosenbrock, aa) ≈ out\n\n\n\n", "meta": {"hexsha": "671439ccf0115fdb65eeb29a770273af53c35409", "size": 2843, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "SimulatingBigModelsInJuliaWithModelingToolkit/tutorial.jl", "max_stars_repo_name": "john-waczak/JuliaCon2021", "max_stars_repo_head_hexsha": "48979656e94af4e5707094fc836ed76971593eac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SimulatingBigModelsInJuliaWithModelingToolkit/tutorial.jl", "max_issues_repo_name": "john-waczak/JuliaCon2021", "max_issues_repo_head_hexsha": "48979656e94af4e5707094fc836ed76971593eac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SimulatingBigModelsInJuliaWithModelingToolkit/tutorial.jl", "max_forks_repo_name": "john-waczak/JuliaCon2021", "max_forks_repo_head_hexsha": "48979656e94af4e5707094fc836ed76971593eac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0592592593, "max_line_length": 104, "alphanum_fraction": 0.7172001407, "num_tokens": 875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810451666345, "lm_q2_score": 0.8933093946927837, "lm_q1q2_score": 0.846304388001223}} {"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 variable diffusivity κ(x).\"\n\n# variable diffusivity\nκ(x) = 1 + .5*sin(pi*x) # assumed κ(x) >= κ_min > 0\n# κ(x) = Float64(1 + (x>0))\n\n# method of manufactured solutions: define the exact solution, then figure out\n# what f,α,β 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(x->κ(x)*dudx_exact(x),x) # -d/dx (κ(x)*du/dx) = f\nα = uexact(-1)\nβ = uexact(1)\n\nfunction solve(m,κ,f,α,β)\n x = LinRange(-1,1,m+2) # points x_0, x_1, ... x_m, x_m+1\n xint = x[2:end-1]\n h = x[2]-x[1]\n\n xmid = @. x[1:end-1] + h/2 # x_0 + h/2, x_1 + h/2, ..., x_m + h/2\n # (re-indexing using fractional indices) x_1/2, x_3/2, ..., x_i+1/2, ..., x_m+1/2\n k = κ.(xmid)\n\n # κ_{i-1/2}+κ_{i+1/2} κ_{i+1/2} κ_{i+1/2}\n A = (1/h^2) * spdiagm(0=>k[1:end-1]+k[2:end],-1=>-k[2:end-1],1=>-k[2:end-1])\n b = f.(xint)\n b[1] += k[1]*α/h^2\n b[end] += k[end]*β/h^2\n\n u = A\\b\n return u,x,xint,h\nend\n\nm = 40\nu,x,xint,h = solve(m,κ,f,α,β)\nplot(xint,u,mark=:dot,markersize=2,label=\"FD solution\")\nplot!(x,uexact.(x),label=\"Exact solution\")\nplot!(leg=:bottomright)\n\n# mvec = 2 .^ (2:9)\n# hvec = zeros(length(mvec))\n# err = zeros(length(mvec))\n# for (i,m) in enumerate(mvec)\n# u,x,xint,h = solve(m,κ,f,α,β)\n# hvec[i] = h\n# err[i] = maximum(@. abs(uexact(xint) - u))\n# end\n# plot(hvec,err,marker=:dot,label=\"Max error\")\n# plot!(hvec,hvec.^2,linestyle=:dash,label=\"O(h^2)\")\n# plot!(xaxis=:log,yaxis=:log,legend=:bottomright)\n", "meta": {"hexsha": "609087f9886888d27200caeb789353b07e28abba", "size": 1736, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "week2/fd_laplace_variable_coeffs_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_variable_coeffs_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_variable_coeffs_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": 30.4561403509, "max_line_length": 85, "alphanum_fraction": 0.5944700461, "num_tokens": 697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012747599251, "lm_q2_score": 0.894789464699728, "lm_q1q2_score": 0.8462930163547537}} {"text": "\"\"\"\r\n rekons(A,B,Xawal)\r\nadalah fungsi yang digunakan untuk mencari solusi SPL `Ax=B` secara iteratif dengan\r\nnilai tebakan awal `Xawal` menggunakan metode rekonstruksi aljabar.\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 = rekons(A,B,Xa);\r\n\r\njulia> X\r\n3-element Array{Float64,1}:\r\n 1.9999987931831584\r\n 3.9999993707528194\r\n 2.9999996431226994\r\n\r\njulia> flag\r\n0\r\n\r\njulia> err\r\n7.477270454885512e-8\r\n\r\njulia> M\r\n18×5 Array{Float64,2}:\r\n 0.0 1.0 2.0 2.0 NaN\r\n 1.0 0.677229 3.45151 2.58059 0.658544\r\n 2.0 1.51207 3.75397 2.85403 0.0644652\r\n 3.0 1.79762 3.89498 2.94005 0.0145717\r\n ⋮\r\n 14.0 1.99998 3.99999 3.0 9.83924e-7\r\n 15.0 1.99999 4.0 3.0 4.16762e-7\r\n 16.0 2.0 4.0 3.0 1.76529e-7\r\n 17.0 2.0 4.0 3.0 7.47727e-8\r\n```\r\nreturn solusi `X` dengan `flag` bernilai 0 jika metode rekonstruksi aljabar\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 rekons(A,B,Xawal)\r\n delta = 10^-7;\r\n maxi = 100;\r\n flag = 1;\r\n X = Xawal[:];\r\n Xlama = X;\r\n M = [0 X' NaN];\r\n for k = 1:maxi\r\n for i = 1:length(B)\r\n Xlama = X;\r\n X = Xlama + A[i,:]*(B[i]-A[i,:]'Xlama)/(A[i,:]'A[i,:])\r\n end\r\n err = norm(X-Xlama)\r\n M = [M; [k X' err] ];\r\n if err 0\n Q[:, j] /= norm\n R[j, j] = norm\n else\n continue\n end\n\n column = Q[:, j]\n for j_inner in (j + 1):size(Q, 2)\n R[j, j_inner] = Q[:, j_inner] ⋅ column\n Q[:, j_inner] -= R[j, j_inner] * column\n end\n end\n \n Q, R\nend;\n\n# --- Test qr_mgs()\n\nn = 10\nA = randn(n, n)\nQ, R = qr_mgs(A)\n\nprintln(\"Relative error Q * R: \", opnorm(A - Q * R)/opnorm(A))\nprintln(\"Absolute error Q * R: \", opnorm(A - Q * R))\nprintln(\"opnorm(Q' * Q): \", opnorm(transpose(Q) * Q))\n\ndet_A = det(A)\ndet_Q = det(Q)\ndet_R = det(R)\nprintln(\"det(A): \", det_A)\nprintln(\"det(Q): \", det_Q)\nprintln(\"det(R): \", det_R)\nprintln(\"Relative error det(Q * R):\", (det_A - det_Q*det_R) / det_A)\nprintln(\"Absolute error det(Q * R):\", det_A - det_Q*det_R)\n\n# Initialize data vectors\nmgs_orthogonality_errors = zeros(num_samples)\nhouseholder_orthogonality_errors = zeros(num_samples)\n\nmgs_det_errors = zeros(num_samples)\nhouseholder_det_errors = zeros(num_samples)\n\n# Collect data\nfor i in 1:num_samples\n # Generate random matrix\n A = randn(n, n)\n det_A = det(A)\n\n # Compute QR factorization using modified Gram-Schmidt algorithm\n Q_mgs, R_mgs = qr_mgs(A)\n\n mgs_orthogonality_errors[i] = opnorm(transpose(Q_mgs) * Q_mgs - LinearAlgebra.I)\n\n det_R = det(R_mgs)\n mgs_det_errors[i] = abs((abs(det_A) - abs(det_R)) / det_A)\n \n # Compute QR factorization using Householder triangularization\n F_householder= qr(A)\n Q_householder = F_householder.Q\n R_householder = F_householder.R\n \n householder_orthogonality_errors[i] =\n opnorm(transpose(Q_householder) * Q_householder - LinearAlgebra.I)\n\n det_R = det(R_householder)\n householder_det_errors[i] = abs((abs(det_A) - abs(det_R)) / det_A)\nend\n\n# --- Orthogonality Error\n\nprintln(\"mean(mgs_orthogonality_errors): \", mean(mgs_orthogonality_errors))\nprintln(\"std(mgs_orthogonality_errors): \", std(mgs_orthogonality_errors))\n\nprintln(\"mean(householder_orthogonality_errors): \", mean(householder_orthogonality_errors))\nprintln(\"std(householder_orthogonality_errors): \", std(householder_orthogonality_errors))\n\n# --- Determinant Error\n\nprintln(\"mean(mgs_det_errors): \", mean(mgs_det_errors))\nprintln(\"std(mgs_det_errors): \", std(mgs_det_errors))\n\nprintln(\"mean(householder_det_errors): \", mean(householder_det_errors))\nprintln(\"std(householder_det_errors): \", std(householder_det_errors))\n\n# --- Special cases that demonstrate large loss of orthogonality with MGS\n\nA = [0.700000 0.70711; 0.70001 0.70711]\ndet_A = det(A)\n\n# MGS\nQ_mgs, R_mgs = qr_mgs(A)\nprintln(\"MGS orthogonality error: \", opnorm(transpose(Q_mgs) * Q_mgs - LinearAlgebra.I))\nprintln(\"MGS determinant error: \", abs((abs(det_A) - abs(det(R_mgs))) / det_A))\n\n# Householder triangularization\nF_householder = qr(A)\nQ_householder = F_householder.Q\nR_householder = F_householder.R\nprintln(\"Householder triangularization orthogonality error: \",\n opnorm(transpose(Q_householder) * Q_householder - LinearAlgebra.I))\nprintln(\"Householder triangularization determinant error: \",\n abs((abs(det_A) - abs(det(R_householder))) / det_A))\n", "meta": {"hexsha": "9cf74fb4fde64dc7fe59e332d311a11d97a8ed99", "size": 3544, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/2020-09-30-KTC-orthogonalization_algorithms.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/2020-09-30-KTC-orthogonalization_algorithms.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/2020-09-30-KTC-orthogonalization_algorithms.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": 27.905511811, "max_line_length": 91, "alphanum_fraction": 0.6805869074, "num_tokens": 1048, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172630429475, "lm_q2_score": 0.891811054783143, "lm_q1q2_score": 0.8462549052562642}} {"text": "\"\"\"\n[Ceva's theorem](https://en.wikipedia.org/wiki/Ceva%27s_theorem) is a theorem about triangles in\nplane geometry. Given a triangle `ABC`, let the lines `AO`, `BO` and `CO` be drawn from the vertices\nto a common point `O` (not on one of the sides of `ABC`), to meet opposite sides at `D`, `E` and `F`\nrespectively. (The segments `AD`, `BE`, and `CF` are known as\n[cevians](https://en.wikipedia.org/wiki/Cevian).) Then, using signed lengths of segments,\n```math\nBD \\\\times CE \\\\times AF = DC \\\\times EA \\\\times FB.\n```\n\"\"\"\nmodule Ceva\n\nusing Plots\nusing SymPy\nusing PlaneGeometry\nusing PlaneGeometry.GeoPlots\n\nexport \n ceva_proof, ceva_draw, ceva_rand, ceva, ceva_check\n\n\"\"\"\n ceva_draw(📐️, O)\n\nVerify Ceva's Theorem for the triangle `📐️`.\n\"\"\"\nfunction ceva_draw(tri, O)\n\n plist, elist = ceva(tri, O)\n A, B, C, D, E, F = plist\n push!(plist, O)\n\n plt = plot(tri, fill=(0, :green), aspect_ratio=:equal, fillalpha= 0.2, leg=false)\n\n plt = scatter!(shape(plist), \n leg=false, \n aspect_ratio=:equal, \n color=:red,\n series_annotations = text.(['A':'F'..., 'O'], :bottom))\n\n AD, BE, CF = [Edge(epair...) for epair in zip([A, B, C], [D, E, F])]\n\n for e in [AD, BE, CF]\n plot!(e, color=:orange, leg=false)\n end\n\n plt, ceva_check(elist...)\nend\n\n\"\"\"\n ceva_rand()\n\nVerify Ceva's Theorem for a random triangle.\n\"\"\"\nfunction ceva_rand()\n pts = rand(0:1//10:1,6);\n A, B, C = [Point(pts[i], pts[i+3]) for i in 1:3]\n\n # Choose O within ABC so the picture looks nicer\n ptx = [pt.x for pt in [A, B, C]]\n pty = [pt.y for pt in [A, B, C]]\n xmin, xmax = N.([f(ptx...) for f in [min, max]])\n ymin, ymax = N.([f(pty...) for f in [min, max]])\n\n tri = Triangle(A, B, C)\n AB, BC, CA = edges(tri)\n\n # Use rejections sampling until the point is in ABC\n while true\n x = rand(xmin:1//100:xmax)\n y = rand(ymin:1//100:ymax)\n O = Point(x, y)\n\n plist, elist = ceva(tri, O)\n\n # We are unlucky\n if plist == nothing\n continue\n end\n\n BD, DC, CE, EA, AF, FB = elist\n\n if BD > BC || DC > BC || CE > CA || EA > CA || AF > AB || FB > AB\n # This mean O is not in ABC\n continue\n end\n\n return ceva_draw(Triangle(A, B, C), O)\n end\nend\n\n\"\"\"\n ceva_proof()\n\nProve Ceva's Theorem.\n\"\"\"\nfunction ceva_proof()\n @vars by cx positive=true\n @vars cy ox oy\n\n A = Point(0, 0); B = Point(0, by); C = Point(cx, cy); O = Point(ox, oy)\n tri = Triangle(A, B, C)\n\n plist, elist = ceva(tri, O)\n ceva_check(elist...)\nend\n\n\n\"\"\"\n ceva(Triangle(A, B, C), O)\n\nReturns `([A, B, C, D, E, F], [BD, DC, CE, EA, AF, FB])`. \n\"\"\"\nfunction ceva(tri, O)\n A, B, C = vertices(tri)\n AB, BC, CA = edges(tri)\n AO, BO, CO = [Edge(pt, O) for pt in vertices(tri)]\n D, E, F = [concurrent(epair...) for epair in zip([BC, CA, AB], [AO, BO, CO])]\n\n # This mean no such points can be found. (This is possible)\n if D == nothing || E == nothing || F == nothing\n return nothing, nothing\n end\n\n elist = [Edge(pts...) for pts in zip([B, D, C, E, A, F], [D, C, E, A, F, B])]\n ([A, B, C, D, E, F], elist)\nend\n\n\"\"\"\n ceva_check(BD, DC, CE, EA, AF, FB)\n\nCheck if the line segments satisfies Ceva's theorem.\n\"\"\"\nfunction ceva_check(BD, DC, CE, EA, AF, FB) \n eq = Eq((BD*CE*AF)^2, (DC*EA*FB)^2)\n N(simplify(eq))\nend\n\nend\n", "meta": {"hexsha": "e371d4acbd19cc5e061211d6ec4da0fcccfddb78", "size": 3417, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/theorem/Ceva.jl", "max_stars_repo_name": "newptcai/PlaneGeometry.jl", "max_stars_repo_head_hexsha": "fe2644fdf824a364daa1ce362bf5557d40775226", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-05-12T04:22:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T23:20:31.000Z", "max_issues_repo_path": "src/theorem/Ceva.jl", "max_issues_repo_name": "newptcai/PlaneGeometry.jl", "max_issues_repo_head_hexsha": "fe2644fdf824a364daa1ce362bf5557d40775226", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/theorem/Ceva.jl", "max_forks_repo_name": "newptcai/PlaneGeometry.jl", "max_forks_repo_head_hexsha": "fe2644fdf824a364daa1ce362bf5557d40775226", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5827338129, "max_line_length": 100, "alphanum_fraction": 0.559262511, "num_tokens": 1153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172630429475, "lm_q2_score": 0.8918110540642805, "lm_q1q2_score": 0.8462549045741232}} {"text": "### A Pluto.jl notebook ###\n# v0.14.8\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n quote\n local el = $(esc(element))\n global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n el\n end\nend\n\n# ╔═╡ e6db292c-d2be-11eb-1c25-05ed50a9256c\nusing FourierTools, TestImages, ImageShow, Plots, Colors, FFTW, Noise, PlutoUI\n\n# ╔═╡ 4958079f-da85-4357-94df-b122cf01c958\nFFTW.set_num_threads(12)\n\n# ╔═╡ 2a47b7a9-7767-44a7-8dda-480ba1b41f57\nmd\"$\\mathcal{F}[U](\\mathbf k) = \\frac{1}{\\sqrt{2\\pi}} \\int_{-\\infty}^{\\infty} U(\\mathbf r) \\cdot \\exp[-i (\\mathbf x \\cdot \\mathbf k)] \\, \\mathrm d \\mathbf x$\n\n$\\mathcal{F}^{-1}[\\tilde U](\\mathbf x) = \\frac{1}{\\sqrt{2\\pi}} \\int_{-\\infty}^{\\infty} U(\\mathbf r) \\cdot \\exp[i (\\mathbf x \\cdot \\mathbf k)] \\, \\mathrm d \\mathbf k$\n\";\n\n# ╔═╡ b71a5e39-0805-4e3f-aa83-c3972f6c54af\nbegin\n\timg = Float32.(testimage(\"fabio_gray\"));\n\timg_1D = img[:, 200]\nend;\n\n# ╔═╡ c39440fc-17e6-440c-9e10-7b2c9a7e9331\nmd\"### FourierTools.jl | Working with the Frequency Space\n\n* **Felix Wechsler**: Leibniz Institute of Photonic Technology in Jena, Germany\n* **Rainer Heintzmann**: Leibniz Institute of Photonic Technology in Jena, Germany\n\"\n\n# ╔═╡ 6e445cd5-6e51-4a8f-ad5c-2636b3da68f4\nmd\"## FourierTools.jl\n\n* A package built on FFTW.jl\n* Provides several helper functions\n* implements algorithms (like interpolation) based on FFTs\n\"\n\n# ╔═╡ e28dc936-04da-48cb-b324-73632d008290\nmd\"\n### Definition of Fourier Transform\n\nComplex valued sum \n\n$\\mathcal F[x_k] = X_k = \\sum_{n=0}^{N-1} x_n \\cdot \\exp\\left[-\\frac{i 2 \\pi}{N} k n\\right] =$\n\n$=\\sum_{n=0}^{N-1} x_n \\cdot \\left[ \\cos\\left(\\frac{2 \\pi}{N} k n\\right) - i \\cdot \\sin\\left(\\frac{2 \\pi}{N} k n\\right)\\right]$\n\nInverse transform\n\n$\\mathcal F^{-1}[X_k] = x_k = \\frac{1}{N} \\sum_{k=0}^{N-1} X_k \\cdot \\exp\\left[\\frac{i 2 \\pi}{N} k n\\right]$\n\n\n* it decomposes a signal into harmonic basis functions\n* the signal is represented in the _Fourier_ or _Frequency_ space\n\n### Fast Fourier Transform - FFT\n* naive sum calculation takes $\\mathcal O(N^2)$ operations for a 1D dataset with $N$ points \n* FFT algorithms evaluates this with $\\mathcal O(N \\cdot \\log(N))$ operations\n* In Julia available _FFTW.jl_ \n\"\n\n# ╔═╡ e8f1e951-26dd-4c0e-83f9-4a2c60b0ebed\nmd\" ## FFT of an dataset with FFTW.jl\"\n\n# ╔═╡ 3adab086-0c77-40e5-990a-6b89b183cc4d\nbegin\n\tx = range(0, 50, length=999)\n\tf(x) = (0.1 * sin(17.3 + x) + 0.5 * cos(1.2*x) + 0.3 * sin(5*x)^2 + 0.05 * sin(13.1*x) + sin(27.2 * x)) * exp(-x/20)\n\tdata = add_gauss(f.(x), 0.1)\nend;\n\n# ╔═╡ 850869e6-32da-48cf-b2a0-081cc9f8e524\nplot(x, data, title=\"function to transform\")\n\n# ╔═╡ d6f9bd7a-ddcb-40b5-8509-f4dac3f8bd5d\nbegin\n\tplot(real(fft(data)), title=\"FFT of the function\", xlabel=\"frequency\", label=\"real part\")\n\tplot!(imag(fft(data)), label=\"imaginary part\")\nend\n\n# ╔═╡ b4b57f32-e405-4463-b0fa-625e9d54df34\nmd\"\n* Data: $[x_1, x_2, ..., x_N]$\n* FFT of Data: $[f_0, f_1, ..., f_{N/2}, f_{-N/2}, f_{-N/2+1}, ...,f_{-1}]$\n* (for real data negative and positive frequencies are the complex conjugate)\n\"\n\n# ╔═╡ f0746bc6-f50a-49f1-96d2-0379498a0168\nbegin\n\tplot(fftshift(fftfreq(size(data, 1))), real(ffts(data)), xlabel=\"frequency\", label=\"real part\", title=\"FFT of the dataset but shifted\")\n\tplot!(fftshift(fftfreq(size(data, 1))), imag(ffts(data)), label=\"imaginary part\")\nend\n\n# ╔═╡ 979d641e-83ad-4484-bc28-912947711936\nfftshift(fft(data)) == ffts(data)\n\n# ╔═╡ 0ba41c40-21a3-4e26-99fe-cacd76d47a67\ntypeof(ffts(data))\n\n# ╔═╡ cc160200-5911-4c80-b651-a54e1608f186\nbegin\n\tN_low = 64\n\tx_min = 0.0\n\tx_max = 8*2π\n\t\n\txs_low = range(x_min, x_max, length=N_low+1)[1:N_low]\n\txs_high = range(x_min, x_max, length=5000)[1:end-1]\n\tf2(x) = sin(0.5*x) + cos(x) + cos(2 * x) + sin(0.25*x)\n\tarr_low = f2.(xs_low)\n\tarr_high = f2.(xs_high)\nend;\n\n# ╔═╡ 7acf4c37-397d-4c1f-8735-022888390cbe\nmd\"## Different FFT methods\n* `fft` interpretes the data as top-left centered\n\n\"\n\n# ╔═╡ b15df267-6606-4583-8ce9-3dddf1ecf3f9\nfft([1.0,0,0,0,0])\n\n# ╔═╡ 76bb0c74-1a52-47ff-adf2-862cfea15da5\nfft([0,0, 1.0 ,0,0]) # single delta peak\n\n# ╔═╡ ec839c01-a62f-46eb-8e25-15d04a07a79f\nft([0,0, 1.0 ,0,0]) \n\n# which is equivalent to fftshift(fft(ifftshift([0,0, 1.0 ,0,0])))\n\n# ╔═╡ c7f0e20e-7c80-4a47-abdf-800f26ca999a\nffts([0,0, 1.0 ,0,0])\n\n# which is equivalent to fftshift(fft([0,0, 1.0 ,0,0]))\n\n# ╔═╡ a725ae98-e2cc-439c-9cc1-692972ac98e7\nmd\"## Calculate sinc interpolation\n\n* Fourier coefficients represent coefficients of Fourier series\n* Inverse transform is essentially a re-evaluation of a Fourier Series\n* Evaluating this series at more samples points results in an interpolated signal\n\"\n\n# ╔═╡ d5717c9c-2c16-47da-8533-a28acf189e55\nbegin\n\tN = 1000\n\txs_interp = range(x_min, x_max, length=N+1)[1:N]\n\tarr_interp = resample(arr_low, N)\nend;\n\n# ╔═╡ 3d8f11a3-4ebf-4d36-a227-b2cafa13e1d6\nbegin\n\tscatter(xs_low, arr_low, legend=:bottomleft, markersize=2, label=\"Low sampling\")\n\tplot!(xs_interp, arr_interp, label=\"FFT based sinc interpolation\", linestyle=:dash)\n\tplot!(xs_high, arr_high, linestyle=:dashdotdot, label=\"High sampling\")\nend\n\n# ╔═╡ 551f179b-46ad-425f-9dd6-d8f6469a09cf\n[Gray.(img) Gray.(resample(img, (256, 712)))]\n\n# ╔═╡ a5977c5c-dbcd-402d-b7a3-56614968ccb7\nbegin\n\tN_ds = 32\n\txs_ds = range(x_min, x_max, length=N_ds+1)[1:N_ds]\n\tarr_ds = real(resample(arr_high, (N_ds,)))\nend;\n\n# ╔═╡ 7f3be670-cfe3-4e60-b38f-ebacb4eaf8d3\nmd\"## Fourier Shift Theorem\n\n$\\mathcal{F}[U(x+ Δx)](\\mathbf k) = \\mathcal{F}[U(x)](\\mathbf k) \\exp(i k \\Delta x)$\n\n$\\Longrightarrow$\n$U(x+ Δx) = \\mathcal{F}^{-1}\\bigg[\\mathcal{F}[U(x)](\\mathbf k) \\exp(i k \\Delta x)\\bigg](x)$\n\n* which allows for efficient sub-pixel shifting\n\"\n\n# ╔═╡ 1ab61f99-799f-4c34-b0d1-205c01c20dbc\n@bind offset Slider(-10:0.01:10, show_value=true)\n\n# ╔═╡ 55667950-4542-4505-9d21-e44ea8b6074d\nbegin\n\tf3(x) = cos(4π * x / 30)\n\tx1 = 1:30\n\tx2 = x1 .+ 3\n\ty1 = f3.(x1)\n\ty2 = f3.(x2)\n\ty3 = shift(y2, tuple(offset))\nend;\n\n# ╔═╡ 8fc68dfc-0fb7-4a5a-bef1-ae0b33ddf4f6\nshift(y2, (offset,))\n\n# ╔═╡ cfb02910-fb2d-4de0-bc81-8ecea50e5cb5\nbegin\n\tplot(y1, label=\"Original signal\")\n\tplot!(y2, label=\"Shifted signal\")\n\tplot!(y3, label=\"Fourier shifted with $offset\")\nend\n\n# ╔═╡ 105344de-8617-47fd-aeed-84102f19eaeb\nmd\"## Based on Shifting $\\Longrightarrow$ Rotation\n\n\"\n\n# ╔═╡ 344f9221-4213-4540-bb40-8a2de2d9b48c\nbegin\n\tz = zeros(Float32, round.(Ref(Int), 1.5 .* size(img)))\n\tFourierTools.center_set!(z, img)\nend;\n\n# ╔═╡ 27a7bcae-e50f-4225-bd7f-45934ec55be3\n@bind ϕ Slider(-180:1:180, show_value=true)\n\n# ╔═╡ ac331005-48ca-4be8-b0a8-85f6f740f09a\nFourierTools.rotate(z, ϕ);\n\n# ╔═╡ bf2c54f1-8110-4e25-b89c-7276cf55f42a\nGray.(FourierTools.rotate(z, ϕ))\n\n# ╔═╡ a5ea8226-ff14-432c-974e-68e1a79155cf\nGray.(FourierTools.rotate(img, ϕ))\n\n# ╔═╡ e1600b0a-b8ef-49b8-8ed0-f9c4ae0c436b\n\n\n# ╔═╡ 7ff8de2d-85fd-402a-88eb-16427e1e0b47\nmd\"## Convolution\nEfficient FFT convolutions for both real and complex functions are included as well\n\"\n\n# ╔═╡ 03effebd-e918-4847-b13a-7d41d4f159e7\nmd\"Blurring strength\"\n\n# ╔═╡ e9862df6-8d1a-4c5e-88ab-1da28c2652af\n@bind pow Slider(1:0.01:6, show_value=true)\n\n# ╔═╡ bf631ded-b54c-4768-9a8d-825ab7612695\nbegin\n\tx3 = fftpos(1, size(img, 1))\n\tkernel = exp.(.- 10.0 .^pow .* (x3 .^2 .+ x3'.^2))\n\tkernel ./= sum(kernel)\nend;\n\n# ╔═╡ f4870819-9db6-4bdc-8c8d-141c8fa67461\nimg_blurry = conv_psf(img, kernel);\n\n# ╔═╡ 9d22e799-fe80-47ef-a326-1f5f1ccc07f8\n[Gray.(img) Gray.(img_blurry)]\n\n# ╔═╡ c530d7ea-60bd-4458-b3ca-80b509fb4f33\nmd\"# Conclusion\n\n* FourierTools.jl provides convenient wrappers to the FFTW library\n* offers efficient algorithms like sinc interpolation based on FFTs\n* deals with the intricacies of the correct handling of even/odd sized arrays in Fourier space\n\"\n\n# ╔═╡ Cell order:\n# ╠═e6db292c-d2be-11eb-1c25-05ed50a9256c\n# ╠═4958079f-da85-4357-94df-b122cf01c958\n# ╟─2a47b7a9-7767-44a7-8dda-480ba1b41f57\n# ╟─b71a5e39-0805-4e3f-aa83-c3972f6c54af\n# ╟─c39440fc-17e6-440c-9e10-7b2c9a7e9331\n# ╟─6e445cd5-6e51-4a8f-ad5c-2636b3da68f4\n# ╟─e28dc936-04da-48cb-b324-73632d008290\n# ╟─e8f1e951-26dd-4c0e-83f9-4a2c60b0ebed\n# ╟─3adab086-0c77-40e5-990a-6b89b183cc4d\n# ╟─850869e6-32da-48cf-b2a0-081cc9f8e524\n# ╟─d6f9bd7a-ddcb-40b5-8509-f4dac3f8bd5d\n# ╟─b4b57f32-e405-4463-b0fa-625e9d54df34\n# ╟─f0746bc6-f50a-49f1-96d2-0379498a0168\n# ╠═979d641e-83ad-4484-bc28-912947711936\n# ╠═0ba41c40-21a3-4e26-99fe-cacd76d47a67\n# ╟─cc160200-5911-4c80-b651-a54e1608f186\n# ╟─7acf4c37-397d-4c1f-8735-022888390cbe\n# ╠═b15df267-6606-4583-8ce9-3dddf1ecf3f9\n# ╠═76bb0c74-1a52-47ff-adf2-862cfea15da5\n# ╠═ec839c01-a62f-46eb-8e25-15d04a07a79f\n# ╠═c7f0e20e-7c80-4a47-abdf-800f26ca999a\n# ╟─a725ae98-e2cc-439c-9cc1-692972ac98e7\n# ╟─d5717c9c-2c16-47da-8533-a28acf189e55\n# ╟─3d8f11a3-4ebf-4d36-a227-b2cafa13e1d6\n# ╠═551f179b-46ad-425f-9dd6-d8f6469a09cf\n# ╟─a5977c5c-dbcd-402d-b7a3-56614968ccb7\n# ╟─7f3be670-cfe3-4e60-b38f-ebacb4eaf8d3\n# ╟─1ab61f99-799f-4c34-b0d1-205c01c20dbc\n# ╠═8fc68dfc-0fb7-4a5a-bef1-ae0b33ddf4f6\n# ╟─55667950-4542-4505-9d21-e44ea8b6074d\n# ╟─cfb02910-fb2d-4de0-bc81-8ecea50e5cb5\n# ╟─105344de-8617-47fd-aeed-84102f19eaeb\n# ╟─344f9221-4213-4540-bb40-8a2de2d9b48c\n# ╟─27a7bcae-e50f-4225-bd7f-45934ec55be3\n# ╠═ac331005-48ca-4be8-b0a8-85f6f740f09a\n# ╟─bf2c54f1-8110-4e25-b89c-7276cf55f42a\n# ╟─a5ea8226-ff14-432c-974e-68e1a79155cf\n# ╠═e1600b0a-b8ef-49b8-8ed0-f9c4ae0c436b\n# ╟─7ff8de2d-85fd-402a-88eb-16427e1e0b47\n# ╟─03effebd-e918-4847-b13a-7d41d4f159e7\n# ╟─e9862df6-8d1a-4c5e-88ab-1da28c2652af\n# ╠═f4870819-9db6-4bdc-8c8d-141c8fa67461\n# ╠═9d22e799-fe80-47ef-a326-1f5f1ccc07f8\n# ╟─bf631ded-b54c-4768-9a8d-825ab7612695\n# ╟─c530d7ea-60bd-4458-b3ca-80b509fb4f33\n", "meta": {"hexsha": "8ca76863eff0f521b26effe5cb838b42d26d00ed", "size": 9692, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/JuliaCon_2021.jl", "max_stars_repo_name": "bionanoimaging/FourierTools.jl", "max_stars_repo_head_hexsha": "c8a37c8f38b0b9897fac2be1bf3c1e109f844964", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2021-03-30T23:15:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T14:20:15.000Z", "max_issues_repo_path": "examples/JuliaCon_2021.jl", "max_issues_repo_name": "bionanoimaging/FourierTools.jl", "max_issues_repo_head_hexsha": "c8a37c8f38b0b9897fac2be1bf3c1e109f844964", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2021-03-28T13:01:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-22T09:43:02.000Z", "max_forks_repo_path": "examples/JuliaCon_2021.jl", "max_forks_repo_name": "bionanoimaging/FourierTools.jl", "max_forks_repo_head_hexsha": "c8a37c8f38b0b9897fac2be1bf3c1e109f844964", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6708860759, "max_line_length": 195, "alphanum_fraction": 0.7070780025, "num_tokens": 4633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465134460244, "lm_q2_score": 0.9046505363862339, "lm_q1q2_score": 0.8461617250959397}} {"text": "#=\nP36 (**) Determine the prime factors of a given positive integer (2).\nConstruct a list containing the prime factors and their multiplicity.\nExample:\n* (prime-factors-mult 315)\n((3 2) (5 1) (7 1))\nHint: The problem is similar to problem P13.\n=#\n\nSMALLEST_PRIME = 2\n\n# From P35\nfunction next_prime(n)\n # Brute-force incremental check\n isprime(n) ? n : next_prime(n + 1)\nend\n\n# From P35\nfunction _prime_factors(n, x, pf)\n if isprime(n)\n vcat(pf, n)\n else\n if mod(n, x) == 0\n _prime_factors(div(n, x), SMALLEST_PRIME, vcat(pf, x))\n else\n _prime_factors(n, next_prime(x + 1), pf)\n end\n end\nend\n\n# From P35\nfunction prime_factors(n)\n # Starting with the smallest prime, 2\n isprime(n) ? n : _prime_factors(n, SMALLEST_PRIME, [])\nend\n\nfunction _prime_factors_multi(pf, n, count, counters)\n if isempty(pf)\n vcat(counters, Vector{}[[n, count]])\n else\n if pf[1] == n\n _prime_factors_multi(pf[2:end], n, count + 1, counters)\n else\n new_counters = vcat(counters, Vector{}[[n, count]])\n _prime_factors_multi(pf[2:end], pf[1], 1, new_counters)\n end\n end\nend\n\nfunction prime_factors_multi(n)\n pf = prime_factors(n)\n _prime_factors_multi(pf[2:end], pf[1], 1, Vector{}[])\nend\n\n@assert prime_factors_multi(315) == Vector{}[[3, 2], [5, 1], [7, 1]]\n\nprintln(\"Tests passed: JL-36.jl\")\n", "meta": {"hexsha": "c5277b285495df942fd293446064cd227c90f82f", "size": 1413, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "JL-36.jl", "max_stars_repo_name": "microamp/jl-99", "max_stars_repo_head_hexsha": "5d49a7e1617394e6cbc06f1a94fe6230b3025d73", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "JL-36.jl", "max_issues_repo_name": "microamp/jl-99", "max_issues_repo_head_hexsha": "5d49a7e1617394e6cbc06f1a94fe6230b3025d73", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "JL-36.jl", "max_forks_repo_name": "microamp/jl-99", "max_forks_repo_head_hexsha": "5d49a7e1617394e6cbc06f1a94fe6230b3025d73", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3620689655, "max_line_length": 69, "alphanum_fraction": 0.6220806794, "num_tokens": 429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.9046505280315008, "lm_q1q2_score": 0.8461617189117738}} {"text": "\"\"\"Julia program to implement Binary Search algorithm.\nBinary Search is a Divide and Conquer strategy based algorithm, where the entire array is divided into two halfs and the\nrequired element is searched for in one of these sections as per the conditions. It is done on sorted arrays.\n\"\"\"\n\nfunction binary_search(arr, n, ele)\n low = 1\n high = n\n while high >= low\n mid = low + (high - low) ÷ 2\n # If the mid element is the required element, return that index\n if(arr[mid] == ele)\n return mid\n # ele is greater than mid element then ele would be present in first half of the array\n elseif (arr[mid] > ele)\n high = mid - 1\n #Else if ele is smaller than mid element then ele would be present in last half of the array\n else\n low = mid + 1\n end\n end\n # If the element is not found return 0\n return 0\nend\n\n\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 = binary_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": "f8bebd56a098e68e4e682fb4c2df7764efbf34d3", "size": 1942, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/search/binary_search.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/search/binary_search.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/search/binary_search.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": 27.3521126761, "max_line_length": 120, "alphanum_fraction": 0.6658084449, "num_tokens": 515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533144915913, "lm_q2_score": 0.9073122144683576, "lm_q1q2_score": 0.8460262816597256}} {"text": "#****************************************************************#\r\n# VeysiADN 4 Apr 2021\r\n# Advanced Robotics Homework 3 Codes\r\n#****************************************************************#\r\nusing LinearAlgebra\r\n#****************************************************************#\r\n# Returns 3 x 3 rotation matrix representing\r\n# rotation about unit vector w by angle theta.\r\n# theta should be in radian\r\nfunction Rodrigues(w,theta)\r\n if( length(w) != 3)\r\n println(\"!Warning! : W matrix should have 3 elements.\")\r\n return\r\n end\r\n if(size(w)==(1,3))\r\n w=w';\r\n end\r\n w_hat = [0 -w[3] w[2];\r\n w[3] 0 -w[1];\r\n -w[2] w[1] 0];\r\n rotation_matrix = cos(theta)*Matrix(1I,3,3) + sin(theta)*w_hat+(1-cos(theta))*w*w';\r\n return rotation_matrix;\r\nend\r\n#****************************************************************#\r\n# Builds rigid transformation matrix T from given\r\n#rotation matrix R and translation t\r\nfunction RpToTrans(R,t)\r\n if( size(R)!=(3,3) )\r\n println(\"!Warning! : Rotation matrix should be 3x3.\")\r\n return\r\n end\r\n if( length(t) != 3 )\r\n println(\"!Warning! : Translation matrix should have 3 elements.\")\r\n return\r\n end\r\n if(size(t)==(1,3))\r\n t=t';\r\n end\r\n R_B_T = hcat(R,t) ;\r\n R_B_T = vcat(R_B_T,[0 0 0 1]) ;\r\n return R_B_T\r\nend\r\n#****************************************************************#\r\n#Extracts rotation matrix R and translation t from given /\r\n# rigid transformation matrix T\r\nfunction TransToRp(T)\r\n if( size(T)!=(4,4) )\r\n println(\"!Warning! : Transformation matrix should be 4x4.\")\r\n return\r\n end\r\n R = T[1:3,1:3]\r\n t = T[1:3,4]\r\n return R,t;\r\nend\r\n#****************************************************************#\r\n# Inverts rigid transformation matrix T\r\nfunction TransInv(T)\r\n if( size(T)!=(4,4) )\r\n println(\"!Warning! : W matrix should be 4x4.\")\r\n return\r\n end\r\n if( det(T)==0 )\r\n println(\"!Warning! : Inverse doesn't exist (Determinant is equal to zero).\")\r\n return\r\n end\r\n R,t = TransToRp(T);\r\n r_inv =hcat(R',-(R'*t))\r\n r_inv = vcat(r_inv,[0 0 0 1]);\r\n return r_inv;\r\nend\r\n#****************************************************************#\r\n", "meta": {"hexsha": "e4e4d77f90e6d48b4bbdc1cfa7fd736f8d66c213", "size": 2303, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "HW3_VeysiADIN.jl", "max_stars_repo_name": "veysiadn/AdvancedRoboticsJulia", "max_stars_repo_head_hexsha": "0484999de1908b73fd19c7c78f5c8471a62610ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HW3_VeysiADIN.jl", "max_issues_repo_name": "veysiadn/AdvancedRoboticsJulia", "max_issues_repo_head_hexsha": "0484999de1908b73fd19c7c78f5c8471a62610ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW3_VeysiADIN.jl", "max_forks_repo_name": "veysiadn/AdvancedRoboticsJulia", "max_forks_repo_head_hexsha": "0484999de1908b73fd19c7c78f5c8471a62610ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9861111111, "max_line_length": 88, "alphanum_fraction": 0.4476769431, "num_tokens": 571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951863227517834, "lm_q2_score": 0.8887587993853654, "lm_q1q2_score": 0.8459768192678291}} {"text": "module NewtonsMethod\n\nusing LinearAlgebra, Statistics, Compat, ForwardDiff\n\nfunction newtonroot(f, f_prime; x_0, tolerance = 1E-7, maxiter = 1000)\n x_old = x_0\n error = Inf\n iter = 1\n while error > tolerance && iter <= maxiter\n if f_prime(x_old) ≈ 0.0\n return (root = nothing, error = nothing, iter = nothing)\n end\n x_new = x_old - f(x_old)/f_prime(x_old)\n error = norm(x_new - x_old)\n x_old = x_new\n iter = iter + 1\n end\n if iter == maxiter+1\n return (root = nothing, error = nothing, iter = nothing)\n else\n return (root = x_old, error = error, iter = iter)\n end\nend\n\n# Applying auto-differentiation\nD(f) = x -> ForwardDiff.derivative(f, x)\n\nnewtonroot(f; x_0, tolerance = 1E-7, maxiter = 1000) = newtonroot(f, D(f), x_0 = x_0, tolerance = tolerance, maxiter = maxiter)\n\n# Export function\nexport newtonroot\n\nend\n", "meta": {"hexsha": "d4120aedd6a5cd9f06b24afddb4bd50f312747d1", "size": 904, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NewtonsMethod.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": "src/NewtonsMethod.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": "src/NewtonsMethod.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": 26.5882352941, "max_line_length": 127, "alphanum_fraction": 0.6261061947, "num_tokens": 283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632261523028, "lm_q2_score": 0.8887587905460026, "lm_q1q2_score": 0.8459768096403367}} {"text": "#' # Minimizing functions - how a computer learns\n\n#' In the previous notebooks, we've seen that by changing **parameters** in a\n#' function, we could find a \"best fit\" of that function to some data. We use\n#' a **loss function** to quantify the \"goodness\" of a set of parameters and\n#' we look for those parameters that **optimize**, in fact **minimize**,\n#' the loss function. If we teach a machine how to minimize the loss function\n#' on its own, we say that machine is able to **learn** how to model our data.\n#'\n#' In the last notebook, we threw around terms like **derivative**,\n#' **gradient**, and **gradient descent** to give you a rough sense of how we\n#' minimize a function on a computer. In this notebook, we will step through\n#' these concepts more carefully, with the aim of being able to implement them\n#' using Julia.\n\n#' ## Minimizing a 1D function using calculus\n#' Let's draw the 1D loss function $L_1$ from a previous notebook again:\n\nusing Plots\n#gr()\n#pyplot()\nplotly()\n\nsigma(x) = 1 / (1 + exp(-x))\nf(x,w) = sigma(w * x)\n\nx1 = 2\ny1 = 0.8\n\nL1(w) = (y1 - f(x1, w))^2\n\nplot(L1, -2, 1.5, xlabel=\"w\", ylabel=\"L1(w)\", legend=false)\n\n#' By eye, we can see that the minimum is around $w=0.6$. But how can we get\n#' the computer to work this out on its own?\n\n#' In the previous notebook, we thought of this function plot as a hill,\n#' viewed from the side. We could find the minimum by making the hill sticky,\n#' and letting a ball roll down it. The ball will find and settle in the\n#' minimum of the function. Now let's see how to teach a computer to do this.\n\n#' We need to find the downhill direction along the hill, which is related to\n#' its *slope* (how steep it is). Calculus provides us with tools to calculate\n#' that slope!\n\n#' Namely, the slope of a curve $L_1(w)$ at $w$ is given by its **derivative**\n#' $L_1'(w)$; geometrically, this is the slope of the **tangent line** to the\n#' curve at that point, i.e. the straight line which touches the curve at that\n#' point.\n\n#' Calculus provides us with some rules to calculate an analytical formula for\n#' the derivative, and we will see later how to apply these rules, albeit\n#' indirectly, for machine learning.\n#' To gain understanding, however, we will see here how to get the computer\n#' to help us out by calculating the derivatives **numerically** instead!\n\n#' ## Approximating derivatives\n\n#' Let's recall that the derivative $L_1'(w)$ of a function is defined as\n#'\n#' $$L_1'(w) \\simeq \\frac{L_1(w+h) - L_1(w)}{h},$$\n#'\n#' for a small step size $h$. (Strictly speaking, we must take the limit\n#' when $h$ tends to $0$ to obtain the exact value of the derivative.)\n\n#' #### Exercise 1\n#'\n#' Write a function to calculate the derivative of a function at a given\n#' point. Note that in Julia, we can easily pass functions as arguments\n#' to other functions!\n#' The function should take the function, the point $w$ at which to calculate\n#' the derivative, and the value of $h$, which should have a default value\n#' of 0.001.\n#'\n#' *Note*: A function input argument can have a *default value* if we set\n#' the input argument equal to that default value when we define the function.\n#' For example,\n#'\n#' ```julia\n#' f(x, a = 3) = a * x^2\n#' ```\n#'\n#' The function `f` will square the input we give it and multiply by `a`.\n#' However, if we choose to call `f(x)` *without* passing it an `a` input,\n#' it will assume `a` is `3` and return `3*x^2`.\n\n#' #### Solution\n#'\n#' We could define the `derivative` function as\nfunction derivative(f, w, h=0.001)\n Ans = f(w + h) - f(w)\n Ans /= h\n return Ans\nend\n\n#' **Tests**\n@assert isapprox(derivative(x -> x^2, 0.2), 0.4, atol=0.01)\n@assert isapprox(derivative(x -> x^2, 0.2, 0.5), 0.9, atol=0.5)\n@assert isapprox(derivative(x -> x^3, 0.2), 0.12, atol=0.01)\n\n\n#' #### Exercise 2\n#'\n#' Write an interactive visualization of the tangent line to the graph of\n#' $L_1$, so that we can visualize the tangent at any point on $L_1$.\n#' Include the current value of the derivative in the title.\n#'\n#' *Hint*: Recall that the straight line through the point $(x_0, y_0)$ with\n#' slope $m$ is given by\n#'\n#' $$\\frac{y - y_0}{x - x_0} = m,$$\n#'\n#' so\n#'\n#' $$y = y_0 + m*(x - x_0).$$\n\nwmin = -2\nwmax = 1\nw = 0.5\npl = plot(L1, wmin, wmax, label=\"L_1\")\n\nx0 = w\ny0 = L1(w)\nscatter!(pl, [x0], [y0], label=\"\")\n\nm = derivative(L1, w)\n\nplot!(pl, x -> y0 + m * (x - x0), ls=:dash, label=\"tangent line\")\n\nylims!(pl, -0.1, 0.6)\nxlims!(pl, wmin, wmax)\n\n#' #### Exercise 3\n#'\n#' What is the value of the derivative (slope of the tangent line) at a\n#' minimum? Can this happen anywhere else?\n\n#' #### Solution\n#' The derivative is `0` at a minimum. This happens at any minimum, maximum or\n#' \"point of inflection\" of a smooth function.\n\n#' #### Exercise 4\n#'\n#' When the derivative $L_1'(w)$ is positive, that means that $L_1$ increases\n#' from left to right at point $w$.\n#'\n#' If the derivative $L_1'(w)$ is positive (> 0), in which direction should\n#' we move $w$ to *decrease* $L_1$?\n\n#' #### Solution\n#'\n#' We should move $w$ left, i.e. decrease it.\n\n#' #### Exercise 5\n#'\n#' If the derivative $L_1'(w)$ is negative (< 0), in which direction should we\n#' move $w$ to *decrease* $L_1$?\n\n#' We can use this information to tell the computer which way to take a step.\n# This constitutes the numerical algorithm called **gradient descent**;\n#' it is called this since we are descending (moving downwards) along the\n#' graph of the function by using information about its gradient (slope).\n\n#' #### Exercise 6\n#'\n#' Implement gradient descent by following this prescription for an\n#' **iterative (repetitive) algorithm**:\n#'\n#' 1. Start at an initial guess $w_0$ for $w$.\n#'\n#' 2. At each step, calculate the derivative, $L_1'(w_n)$ at the current value\n#' of $w_n$ using the function that you created above.\n#'\n#' 3. Modify the value of $w$ by a small multiple (for example, $\\eta=0.01$)\n#' of the value of the derivative you just created, via\n#' $w_{n+1} = w_n - \\eta L_1'(w_n)$.\n#'\n#' For this problem, start with $w_0 = -2.0$. Repeat steps 2 and 3 a total\n#' of `2000` times.\n#'\n#' Package this code into a function called `gradient_descent` that takes two\n#' inputs, a function and a range for values of $w$, and returns the final\n#' value of $w$ and $L_1(w)$.\n#'\n#' Using `L1` and `-2:0.01:1.5` as your inputs to `gradient_descent`,\n#' for what value of $w$ is $L_1$ at a minimum?\n\n#' #### Solution\nfunction gradient_descent(f) # wrange not used?\n w = -2.0\n for i in 1:2000\n fprime = derivative(f, w)\n step = 0.01 * fprime\n w = w - step\n end\n\n return w, f(w)\nend\n\n(w, fw) = gradient_descent(L1)\n\n#' #### Exercise 7\n#'\n#' Modify your code for gradient descent to return the result once it has\n#' found an answer within some *tolerance*, rather than taking a set number\n#' of steps. The new prescription for this algorithm is:\n#'\n#' 1. Start at an initial guess $w_0$ for $w$.\n#'\n#' 2. At each step, calculate the derivative, $L_1'(w_n)$ at the current value\n#' of $w_n$, using the function that you created above.\n#'\n#' 3. Modify the value of $w$ by a small multiple (for example, $\\eta=0.01$)\n#' of the value of the derivative you just created, via\n#' $w_{n+1} = w_n - \\eta L_1'(w_n)$.\n#'\n#' 4. Check how different $w_{n+1}$ is from $w_n$. If you're satisfied that\n#' $L_1(w_{n+1})$ is minimized, return $w_{n+1}$ and $L_1(w_{n+1})$.\n#' Otherwise, go to step (2) and continue.\n#'\n#' Edit `gradient_descent` so that it takes three inputs: a function, a range\n#' for values of $w$, and a tolerance that tells you how close $w_{n+1}$ must\n#' be to $w_n$ before you can stop iterating.\n#'\n#' Using `L1`, `-2:0.01:1.5`, and `.000001` as your inputs to\n#' `gradient_descent`, for what value of $w$ is $L_1$ at a minimum?\n\n#' #### Solution\n#'\n#'\n#' Your code should look something like this\n#'\n#' $L_1$ is at a minimum when `gradient_descent(L1, -2:0.01:1.5, .000001)[1]`,\n#' or $w$, is around `0.69216`.\n\nfunction gradient_descent(f, tol)\n w = -2.0\n ccount = 0\n \n while ccount < 2000000 # do no more than 2000 times\n fprime = derivative(f, w)\n step = 0.01 * fprime\n w = w - step\n if abs(step) < tol\n return w, f(w)\n end\n\n ccount += 1\n end\nend\n\n(w, fw) = gradient_descent(L1, 0.000001)\n@assert 0.69215 < w < 0.69217\n\n\n\n#' After you've completed this step, you will have found a good approximation\n#' to the value $w^*$ where $L_1$ reaches its minimum, and the minimum\n#' value $L_1(w^*)$, which in this case is (almost) $0$.\n\n#' #### Exercise 8\n#'\n#' Alter the function `gradient_descent` so that it stores the results\n#' `(w, L1(w))` at each step of the algorithm as an array and returns\n#' this array. How many steps does the algorithm take for input parameters\n#' `(L1, -2:0.01:1.5, .000001)` before terminating? You should count your\n#' starting $w_0$ as your first step.\n\n\"\"\"\n gradient_descent(f, wrange, tol)\n\nUse gradient descent method to find the minimum of a function.\n\n# Examples\n\n# Arguments\n- `f`: Find the minimum of the function `f`.\n- `wrange`: User proivded initial guess range.\n- `tol`: Tolerance of consequtive step size. Returns when the difference of\n consequtive steps is less than `tol`.\n\"\"\"\nfunction gradient_descent(f, wrange; tol=0.000001, w_init=undef)\n # find initial guess from wrange\n if w_init == undef\n w_vec = Vector{Float64}(undef, 0)\n fw_vec = Vector{Float64}(undef, 0)\n \n for w = wrange\n fw = f(w)\n push!(w_vec, w)\n push!(fw_vec, fw)\n end\n\n min_ind = argmin(fw_vec)\n w_init = w_vec[min_ind]\n fw_init = fw_vec[min_ind]\n println(\"Initial guess: $w_init, $fw_init\")\n # return (w_inti, fw_init)\n end\n\n # gradient descent\n w = w_init\n w_vec = Vector{Float64}(undef, 0)\n fw_vec = Vector{Float64}(undef, 0)\n ccount = 0\n fw = f(w)\n push!(w_vec, w)\n push!(fw_vec, fw)\n while ccount < 1000000\n fprime = derivative(f, w)\n step = 0.01 * fprime\n\n w = w - step\n fw = f(w)\n push!(w_vec, w)\n push!(fw_vec, fw)\n if abs(step) < tol\n println(\"iteration = $ccount\")\n return w_vec, fw_vec\n end\n\n ccount += 1\n end\n\n error(\"Exceeded maximum iterations\")\nend\n(w, fw) = gradient_descent(L1, -2:0.1:1.5; tol=0.000001)\nprintln(\"Iteration count: $(length(w))\")\n\n#' #### Exercise 9\n#'\n#' Overlay the steps taken in the last exercise with a plot of\n#' $L_1(w)$ vs. $w$.\n#'\n#' Where does our algorithm take the largest steps?\n#' (Where does the ball move fastest down the hill?)\n#'\n#' A) Between w = -2:-1
\n#' B) Between w = -1:0
\n#' C) Between w = 0:.6\n#'\n#' *Hint*: It may be easier to see what's going on if you only plot,\n#' for example, every 15th step.\n\n# Initial guess = 0.7 so the plot range needs to be smaller to see\n(w, fw) = gradient_descent(L1, -2:0.1:1.5; tol=0.000001)\npl = plot(L1, 0.692, 0.70, xlabel=\"w\", ylabel=\"L1(w)\", legend=false)\nws = reverse(w[end:-50:1]) # Make sure end point is included\nfws = reverse(fw[end:-50:1]) \nscatter!(pl, ws,fws)\n\n# Initial guess = -2.0\n(w, fw) = gradient_descent(L1, -2:0.1:1.5; tol=0.000001, w_init=-2)\npl = plot(L1, -2, 1.5, xlabel=\"w\", ylabel=\"L1(w)\", legend=false)\nws = reverse(w[end:-50:1]) # Make sure end point is included\nfws = reverse(fw[end:-50:1]) \nscatter!(pl, ws,fws)\n\n#' ## Functions of 2 variables and their derivatives\n#' So far, we have been looking at the minimizing a loss function\n#' $L_1(w)$ that depends on a single parameter, $w$. Now let's turn to\n#' the cost function $L_2(w, b)$ from a previous notebook, that is a\n#' function of *two* parameters, $w$ and $b$, and try to minimize it.\n#'\n#' As we've seen, we get a **surface**, instead of a curve,\n#' when we graph $L_2$ as a function of both of its parameters.\n\n#' **Exercise 10**\n#'\n#' Draw a surface plot of $L_2$, given by\n#'\n#' $$L_{2}(w, b) = \\sum_i(y_i - g(x_i, w, b))^2$$\n#'\n#' using the `surface` function from `Plots.jl`. For this plot, use the\n#' values of `xs` and `ys` from notebook 5:\n#'\n#' We can get a nice interactive 3D plot by using the Plotly backend\n#' of `Plots.jl` by executing the command\n#'\n#' plotly()\n# if !(@isdefined WEAVE_ARGS)\n# plotly()\n# end\n\nxs = [2, -3, -1, 1]\nys = [0.8, 0.3, 0.4, 0.4]\n\nsigma(x) = 1/(1 + exp(-x))\ng(x,w,b) = sigma(w*x) + b\n\nL2(w,b) = sum(abs2, ys .- g.(xs,w,b))\n\npl = plot()\nsurface!(pl, -2:0.02:2, -2:0.02:2, L2, alpha=0.6, xlabel=\"w\",\n ylabel=\"b\", zlabel=\"L2(w,b)\",\n size=(600,600))\n#'\n\n#+ echo=false\nif !@isdefined WEAVE_ARGS # exe when not from Weave\n gui(pl)\nend\n\n#' ### Finding the minimum\n#' We can just about see, by rotating the graph, that $L_2$ has a single\n#' minimum. We want to find the values of $w$ and $b$ where this\n#' minimum value is reached.\n\n#' Following what we did for the function $L_1$ above, we expect that\n#' we will need to calculate derivatives of $L_2$. Since the function is\n#' more complicated, though, the derivatives are too!\n#'\n#' It turns out that the right concept is that of the\n#' [**gradient**](https://en.wikipedia.org/wiki/Gradient) of\n#' $L_2$, denoted $\\nabla L_2(w, b)$. This is a **vector** consisting\n#' of $2$ numbers if there are $2$ parameters \n#'[or, in general, $n$ numbers if there are $n$ parameters].\n#'\n#' The numbers that form the gradient $\\nabla L_2(w, b)$ are called the\n#' **partial derivatives** of $L_2$ with respect to $w$ and $b$, written as\n#'\n#' $$\\frac{\\partial L_2}{\\partial w} \\quad \\text{and} \\quad \\frac{\\partial L_2}{\\partial b}.$$\n#'\n#' Although this notation might look complicated, all it means is that we\n#' calculate derivatives just like we did before, except that we fix the value\n#' of the other variable.\n#' For example, to calculate $\\frac{\\partial L_2}{\\partial w}$,\n#' the partial derivative of $L_2$ with respect to $w$, we fix the value of\n#' $b$ and think of the resulting function as a function of the single\n#' variable $w$; then we use the formula for derivatives of functions of a\n#' single variable.\n#'\n#' [Note that $\\frac{\\partial L_2}{\\partial w}$ is itself a function of $w$ and $b$; we could write $\\frac{\\partial L_2}{\\partial w}(w, b)$.]\n\n#' #### Exercise 11\n#'\n#' Write functions that will allow you to calculate the partial derivatives of\n#' a function $f$ of two variables.\n#'\n#' In particular, declare functions called `partial_w` and `partial_b`.\n#' Each should take four inputs - a function $f$ of two variables, the first\n#' input argument to $f$, the second input argument to $f$, and a step size\n#' `h` with default value `0.001`. `partial_w` should return the partial\n#' derivative of $f$ with respect to its first input argument and `partial_b`\n#' should return the partial derivative of $f$ with respect to its second\n#' input argument.\n\n#' #### Solution\n#'\n#' The partial derivatives are\npartial_w(f, w, b, h=0.001) = (f(w+h,b) - f(w,b))/h\npartial_b(f, w, b, h=0.001) = (f(w,b+h) - f(w,b))/h\n\n#' **Test**\npartial_x = partial_w\npartial_y = partial_b\nfn(x,y) = 3*x*y\n#' Test default step\n@assert isapprox(partial_x(fn, 0.3, 0.3), 0.9; atol=1.e-6)\n@assert isapprox(partial_y(fn, 0.3, 0.3), 0.9; atol=1.e-6)\n#' Test custom step\nfn(x,y) = 3 * x^2 * y^3\n@assert isapprox(partial_x(fn, 2.3, 10.2, 1), 17828.2944; atol=1.e-2)\n@assert isapprox(partial_y(fn, 2.3, 10.2, 1), 5454.84; atol=1.e-2)\n\n\n#' #### Exercise 12\n#'\n#' Use `partial_b` from the last exercise to find the partial derivative of\n#' $L_2$ with respect to $w$ at b = 0.3,\n#' $\\frac{\\partial L_2}{\\partial w}|_{b = 0.3}$ for `w = -2:0.01:1`\n\nwrange = -2:0.01:1\npartialw = partial_w.(L2, wrange, 0.3)\n\n#' #### Exercise 13\n#'\n#' Plot the cross section of the surface of $L_2(w, b)$ at $b = 0.3$.\n#' Make this plot interactive to show that the function `partial_w` gives\n#' the slope of the tangent to this cross section for any point `w` in\n#' the range `-2:0.01:1`.\n#'\n#' For what value of $w$ in this range is the slope of the cross section\n#' closest to -1?\n\nL2_b(w) = L2(w, 0.3) # b = 0.3\n\nw = 0.0 # Change me\npl = plot(L2_b, wrange) #plot(wrange, L2_b)\nscatter!([w], [L2_b(w)])\n\nslope = partial_w(L2, w, 0.3)\nwrange_value = slope .* wrange .- slope*w .+ L2.(w,0.3)\nplot!(pl, wrange, wrange_value)\nylims!(0.3, 2.0)\ntitle!(\"Slope = $slope @ $(w)\")\n#'\n#' ## **Optional**: Functions with $n$ inputs\n#' If a function $f$ takes $n$ input arguments, we can write them as\n#' $p_1, \\ldots, p_n$, where $p_i$ means the \"$i$th parameter\".\n#' In Julia, we can wrap them up into a single **vector**. Now we can\n#' calculate the partial derivative $\\frac{\\partial L_2}{\\partial p_i}$ with\n#' respect to the $i$th variable.\n\n#' #### Exercise 14\n#'\n#' For the next exercise, you will need to use the splat command, `...`. You can use this command to \"open up\" a collection and pass all the elements of that collection as inputs to a function.\n#'\n#' For example, say you have an array, `numbers`,\n#'\n#' ```julia\n#' numbers = [4, 3, 2]\n#' ```\n#'\n#' and you want to use `numbers` to create a $4\\times3\\times3$ randomly populated array via `rand`. `rand(numbers)` will not do what you want. You could index into `numbers` to grab the values you want and pass them to `rand`, as in\n#'\n#' ```julia\n#' rand(numbers[1], numbers[2], numbers[3])\n#' ```\n#'\n#' or you could use a splat:\n#'\n#' ```julia\n#' rand(numbers...)\n#' ```\n#'\n#' Use `...` to pass the contents of `inputs`\n#'\n#' ```julia\n#' inputs = [30, 12, \"cats\"]\n#' ```\n#'\n#' to the function `dreams`\n#'\n#' ```julia\n#' dreams(i, j, perfect_mammal) = \"I wish I had $(i + j) $perfect_mammal.\"\n#' ```\n\ninputs = [30, 12, \"cats\"]\ndreams(i, j, perfect_mammal) = \"I wish I had $(i + j) $perfect_mammal.\"\ndreams(inputs...)\n\n# **Tests**\n\n@assert dreams(inputs...) == \"I wish I had 42 cats.\"\n\n#' #### Exercise 15:\n#'\n#' Write a function, `partial`, to calculate the $i$th partial derivative of a\n#' function. This function should have four inputs\n#'\n#' * a function, $f$, for which you want to compute the partial derivative\n#' * an array, *p*, specifying the values of all input arguments to $f$ at\n#' the point where you want $\\frac{\\partial f}{\\partial p_i}$ computed\n#' * the index, $i$, of the variable with respect to which you want to calculate the partial derivative of $f$\n#' * a step size with default value 0.001\n#'\n#' Hint: you will need to `copy` and modify `p` within `partial`.\n\nfunction partial(fn, p, i, h=0.001)\n p = copy(p)\n a = fn(p...)\n p[i] += 1*h\n b = fn(p...)\n Ans = (b - a)/(1*h)\n\n return Ans\nend\n\nfn1(x,y,z) = x^2 * y * z\nfn1(xyz) = fn1(xyz...)\n#' $\\frac{\\partial fn_1}{\\partial x}$\nfn1px(x,y,z) = 2*x*y*z\nfn1py(x,y,z) = x^2*1*z\nfn1pz(x,y,z) = x^2*y*1\n\n\n\nx = 1.0\ny = 2.0\nz = 1.0\nxyz = [x, y, z]\n\nactual = partial(fn1, xyz, 1, 1.e-6)\nexpected = fn1px(xyz...)\n@assert isapprox(actual, expected; atol=1.e-4)\n\n\nusing FiniteDifferences\n# what the? Why do I have to use 2nd order central difference for\n# first derivate?\nactual = central_fdm(2,1)(x->fn1(x,y,z), 1.0) \n@assert isapprox(actual, expected; atol=1.e-6)\nactual = forward_fdm(2,1)(x->fn1(x,y,z), 1.0)\n@assert isapprox(actual, expected; atol=1.e-6)\n\nusing FiniteDiff\n# This is right\nactual = FiniteDiff.finite_difference_derivative(x->fn1(x,y,z), 1.0)\n@assert isapprox(actual, expected; atol=1.e-6)\n\n# GradientFiniteDiff.finite_difference_gradient(fn1, xyz)\n(gx,gy,gz) = FiniteDiff.finite_difference_gradient(fn1, xyz)\n\nw = 1.1\nx = 2.2\ny = 3.3\nz = 4.4\nfn2(w,x,y,z) = w * x^2 * y^3 * z^4\nfn2pw(w,x,y,z) = x^2 * y^3 * z^4\nfn2px = w * 2 * x * y^3 * z^4\nfn2py = w * x^2 * 3 * y^2 * z^4\nfn2pz = w * x^2 * y^3 * 4 * z^3\n\n# Test partial()\nexpected = fn2pw(w,x,y,z)\n\nactual = partial(fn2, [w,x,y,z], 1, 1.e-6)\n@assert isapprox(actual, expected; rtol=1.e-6)\n\nactual = FiniteDiff.finite_difference_derivative(\n w->fn2(w,x,y,z), w)\n@assert isapprox(actual, expected; rtol=1.e-9)\n\n#' ## Gradient descent in 2 dimensions\n#' It turns out that the gradient vector of the function $L_2(w, b)$ gives the\n#' direction in the plane $(w, b)$ in which the function $L_2$\n#' **increases fastest**.\n#'\n#' In other words, if you start at the position $(w_0, b_0)$ and take a small\n#' step of length $\\eta$ to new values $(w', b')$, the value of the function\n#' will change to a new value $L_2(w', b')$. How do we get to the minimum of\n#' $L_2(w, b)$ as fast as possible? We want to step in the direction where\n#' $L_2$ decreases fastest!\n#'\n#' In multivariable calculus courses, it is shown that $L_2$ will *increase*\n#' fastest if you take a step **in the direction of the gradient\n#' $\\nabla L_2(w, b)$**! To decrease $L_2$ the fastest, we should take a step\n#' in the *opposite* direction, $-\\nabla L_2(w, b)$.\n#'\n#' Let's now generalize the gradient descent algorithm that we wrote previously\n#' to work our 2-dimensional function.\n\n#' #### Exercise 16\n#'\n#' Extend your 1D implementation of `gradient_descent` so that it will minimize the function $L_2$.\n#'\n#' Requirements:\n#'\n#' * Your new method for `gradient_descent` will take four input arguments: the function $f$ for which you seek the minimum, the range of values for $f$'s first input argument that you will consider, the range of values for $f$'s second input argument that you will consider, and a tolerance that will specify the maximum allowable step size, $\\sum_i \\eta \\frac{\\partial f}{\\partial p_i}$\n#'\n#' * Use $\\eta = .01$. For example, for a function $f(w, b)$, update $w$ such that $w_{n+1} = w_n - 0.01 * \\frac{\\partial f}{\\partial w_n}$\n#'\n#' * Seed `gradient_descent` with the starting coordinates [-2.0, -2.0], i.e. $w_0 = -2.0$ and $b_0 = -2.0$.\n#'\n#' * Return all steps (their coordinates) taken during gradient descent and the values of the loss function at these coordinates.\n#'\n#' Once you have done this, execute\n#'\n#' ```julia\n#' gradient_descent(L2, -2:0.02:2, -2:0.02:2, .001)\n#' ```\n#'\n#' How many steps were taken by gradient descent?\n#'\n#' Hint: Do not count your starting coordinates `[-2.0, -2.0]` as a step.\n\nfunction gradient_descent(fn, wrange, brange; tol=0.001, eta=0.01)\n w = wrange[1]\n b = brange[1]\n\n w_steps = []\n b_steps = []\n f_steps = []\n\n while true\n (gfw,gfb) = FiniteDiff.finite_difference_gradient(fn, [w,b])\n w = w - eta * gfw\n b = b - eta * gfb\n f = fn(w,b)\n\n push!(w_steps, w)\n push!(b_steps, b)\n push!(f_steps, f)\n\n if abs(eta*gfw + eta*gfb) < tol\n return (w_steps,b_steps,f_steps)\n end\n \n end\n\n #return (w_steps, b_steps, f_steps)\nend\n\nxs = [2, -3, -1, 1]\nys = [0.8, 0.3, 0.4, 0.4]\n\nsigma(x) = 1/(1 + exp(-x))\ng(x,w,b) = sigma(w*x) + b\n\nL2(w,b) = sum(abs2, ys .- g.(xs,w,b))\nL2(xb) = L2(xb...)\nwrange = -2.0:0.02:2.0\nbrange = -2.0:0.02:2.0\n(w,b,fv) = gradient_descent(L2, wrange, brange)\n\n#' #### Exercise 17\n#'\n#' Use the `surface` and `scatter!` commands to illustrate the path taken by\n#' `gradient_descent` from [-2.0, -2.0] to wherever the algorithm terminates.\n#'\n#' Where do the scattered points representing the steps of gradient descent\n#' appear the most dense?\n#'\n#' A) Near the starting point at [-2.0, -2.0]
\n#' B) Near the point [-1.8, 0] where $C_2$ appears nearly flat
\n#' C) Near the minimum of $C_2$\n\n#' #### Solution\n#'\n#' B) The following code will plot the function `C2` with an overlay of the\n#' steps taken in gradient descent\n#'\n#' You can change the frequency with which steps are plotted by changing the\n#' iterator in the `for` loop from `1:length(values)` to\n#' `1:n:length(values)` for varying values of `n`. This will allow you to\n#' see more clearly where steps are densely or sparsely packed.\n\nfig = surface(-2:0.02:2, -2:0.02:2, L2, alpha=0.6, xlabel = \"w\",\n ylabel = \"b\", zlabel = \"C2(w, b)\", size=(800,800))\nfor i in 1:10:length(fv)\n scatter!(fig, [w[i]], [b[i]], [fv[i]], markersize=1)\nend \nfig", "meta": {"hexsha": "f3f4911112028faac4a666b09d4f41f3afd28a85", "size": 23807, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "JuliaAcademy/FundMachLearn/ch0900quiz.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/ch0900quiz.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/ch0900quiz.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": 32.4346049046, "max_line_length": 388, "alphanum_fraction": 0.6441802831, "num_tokens": 7700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850004144266, "lm_q2_score": 0.9032942047513692, "lm_q1q2_score": 0.8457408148699849}} {"text": "### A Pluto.jl notebook ###\n# v0.15.1\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 4cb24885-2f27-400e-a20d-b8152f4c59d3\nusing LinearAlgebra\n\n# ╔═╡ 5e4375cd-a2a4-4027-88a0-a7ae49fbde1c\n# we write a function that returns a root of func in the\n# interval [low, high] with relative error tol, assuming such a root exists\nfunction binarySearch(func, low, high, tol)\n\n\t# we repeat until the tolorance condition is met\n\twhile abs(high - low)/2 > tol * abs(high + low)/2\n\n\t\t# we define mid as the midpoint of the interval [low, high]\n\t\tmid = (low + high)/2\n\n\t\t# we check if the value of func at high and mid have the same sign\n\t\tif func(high) * func(mid) > 0\n\n\t\t\t# and reassign [low, high] accordingly\n\t\t high = mid\n\t\telse\n\t\t low = mid\n\t\tend\n\tend\n\n\t# we return the avarage of low and high as the approximate root\n\treturn (low + high)/2;\nend\n\n# ╔═╡ 4533a6ef-85b5-44e2-a381-f60182886903\n# we write an improved version of binarySearch that evaluates func fewer times\n# and checks if there is definitely a root in the initial interval\nfunction binarySearchV2(func, low, high, tol)\n\n # we now also store the values of func at low and high\n f_low = func(low)\n f_high = func(high)\n\n # we check if the initial interval definitely contains a root\n if f_low * f_high > 0\n error(\"func(low) and func(high) must have different sign\")\n end\n \n # the while loop is similar to before\n while abs(high - low)/2 > tol * abs(low + high)/2\n mid = (low + high)/2\n\n # we only have one evaluation of func per loop\n f_mid = func(mid)\n \n if f_high * f_mid > 0\n high = mid\n f_high = f_mid\n # in this case f_low stays the same\n else\n low = mid\n f_low = f_mid\n # in this case f_high stays the same\n end\n end\n \n return (low + high)/2\nend\n\n# ╔═╡ 977bcb22-8089-49f3-931f-be39cbcd950c\nf(x) = exp(x)-4x;\n\n# ╔═╡ 25a35c4d-76aa-406b-b6ba-6cbd960c08b9\nzeta = 1e-7;\n\n# ╔═╡ d6406dcf-fda4-4fc3-ba27-8f33ac760c80\nmd\"Both implementations find the same approxiamte root in the interval $(0,1)$.\"\n\n# ╔═╡ 067c0a97-da55-46b9-9476-396b7d60968f\nbinarySearch(f, 0, 1, zeta)\n\n# ╔═╡ 8a15ea59-e2fc-4534-84dd-52b3c11abeac\nbinarySearchV2(f, 0, 1, zeta)\n\n# ╔═╡ 031bddca-90a9-43cd-b5d4-e6ccb41f501e\nmd\"Let's test the case where there is no root in the initial interval. Note that binarySearch does not test whether there is a root it gives a bad answer: it is an **unreliable** function.\"\n\n# ╔═╡ e53a4200-0d48-4d0a-9b60-ac447eff62d4\nbinarySearch(f, 1, 2, zeta)\n\n# ╔═╡ 57435047-508b-419a-a1b2-8e5cfa4cbfaf\nmd\"BinarySearchV2 on the other hand includes the initial check.\"\n\n# ╔═╡ a9fd5fbd-8c6e-45b5-9821-ba64175ec3e0\nbinarySearchV2(f, 1, 2, zeta)\n\n# ╔═╡ aaf5575d-fb60-43b7-858c-46babc9401b1\nmd\"Let's try it for a more complicated function that involves large matrices. We construct a $n\\times n$ matrix with random numbers.\"\n\n# ╔═╡ ebe48c7f-bae4-4262-b792-0581a0757e0d\nn = 4000;\n\n# ╔═╡ 5827d97a-5cf3-4578-90ba-11d07afb84d6\nA = rand(n,n);\n\n# ╔═╡ ba659a53-9947-4e2d-b615-c3dcd71b3c18\nmd\"Make a symmetric matrix (for real matrices, M' is the transpose of M).\"\n\n# ╔═╡ f997e7f0-26d2-4f90-939b-4776a29d5f66\nB = A + A';\n\n# ╔═╡ 25142ed0-b0d2-440a-874b-e49fb7fd198c\ng(x) = eigmax(exp.(x*B))-2n;\n\n# ╔═╡ 8dfb5f2b-95ef-4701-b90e-2727aa2b2a32\nmd\"\"\"\nThis function computes a matrix with elements\n$A_{ij} = exp(x B_{ij} )$, computes the largest eigenvalue $\\lambda$ of $A$ and returns $\\lambda - 2n$.\n\"\"\"\n\n# ╔═╡ f0fdc7d6-9aa3-4a6c-b2e0-f45706d4ae30\ng(0), g(1)\n\n# ╔═╡ fe08f690-93a7-46bb-a110-2cb917d12991\nmd\"\"\"\nSince $g$ is continuous and $sign(g(0)) \\neq sign(g(1))$, it must have a root in the interval $(0,1)$. \n\"\"\"\n\n# ╔═╡ 0ff24d6c-9032-4743-9400-f90a70b0bc11\nbinarySearchV2(g, 0, 1, zeta)\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nLinearAlgebra = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\n[[Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[LinearAlgebra]]\ndeps = [\"Libdl\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╠═5e4375cd-a2a4-4027-88a0-a7ae49fbde1c\n# ╠═4533a6ef-85b5-44e2-a381-f60182886903\n# ╠═977bcb22-8089-49f3-931f-be39cbcd950c\n# ╠═25a35c4d-76aa-406b-b6ba-6cbd960c08b9\n# ╟─d6406dcf-fda4-4fc3-ba27-8f33ac760c80\n# ╠═067c0a97-da55-46b9-9476-396b7d60968f\n# ╠═8a15ea59-e2fc-4534-84dd-52b3c11abeac\n# ╟─031bddca-90a9-43cd-b5d4-e6ccb41f501e\n# ╠═e53a4200-0d48-4d0a-9b60-ac447eff62d4\n# ╟─57435047-508b-419a-a1b2-8e5cfa4cbfaf\n# ╠═a9fd5fbd-8c6e-45b5-9821-ba64175ec3e0\n# ╟─aaf5575d-fb60-43b7-858c-46babc9401b1\n# ╠═ebe48c7f-bae4-4262-b792-0581a0757e0d\n# ╠═5827d97a-5cf3-4578-90ba-11d07afb84d6\n# ╟─ba659a53-9947-4e2d-b615-c3dcd71b3c18\n# ╠═f997e7f0-26d2-4f90-939b-4776a29d5f66\n# ╠═4cb24885-2f27-400e-a20d-b8152f4c59d3\n# ╠═25142ed0-b0d2-440a-874b-e49fb7fd198c\n# ╟─8dfb5f2b-95ef-4701-b90e-2727aa2b2a32\n# ╠═f0fdc7d6-9aa3-4a6c-b2e0-f45706d4ae30\n# ╟─fe08f690-93a7-46bb-a110-2cb917d12991\n# ╠═0ff24d6c-9032-4743-9400-f90a70b0bc11\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "13f5833c72c3abf841bbdd38fbede6be8d8021f2", "size": 5133, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "1a/Root Finding/binaryTest.jl", "max_stars_repo_name": "sje30/catam-julia", "max_stars_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-07-13T12:55:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:40:23.000Z", "max_issues_repo_path": "1a/Root Finding/binaryTest.jl", "max_issues_repo_name": "sje30/catam-julia", "max_issues_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2021-07-11T21:35:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-25T12:10:58.000Z", "max_forks_repo_path": "1a/Root Finding/binaryTest.jl", "max_forks_repo_name": "sje30/catam-julia", "max_forks_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-13T21:00:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-13T21:00:47.000Z", "avg_line_length": 29.3314285714, "max_line_length": 189, "alphanum_fraction": 0.7108903176, "num_tokens": 2335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070133672955, "lm_q2_score": 0.9294404008810105, "lm_q1q2_score": 0.8457043392685422}} {"text": "# Examples presented in class - Lecture 1\n# Example 4 - Classification\n\nusing JuMP, Ipopt\n\n# Generating random multivariate data.\ndata11 = rand(Normal(8, 4), 100)\ndata12 = rand(Normal(12, 2), 100)\ndata1 = [data11 data12]\n\ndata01 = rand(Normal(2, 6), 100)\ndata02 = rand(Normal(5, 2), 100)\ndata0 = [data01 data02]\n\nscatter(data1[:,1], data1[:,2], label=\"Pos. obs.\")\nscatter!(data0[:,1], data0[:,2], label=\"Neg. obs.\")\n\nfunction classify(data1, data0, δ)\n m = Model(IpoptOptimizer())\n\n\n @variable(m, u[1:100] >= 0)\n @variable(m, v[1:100] >= 0)\n @variable(m, a[1:2])\n @variable(m, b)\n\n @constraint(m, error1[i=1:100], sum(a[j]*data1[i,j] for j = 1:2) - b - u[i] <= -1)\n @constraint(m, error0[i=1:100], sum(a[j]*data0[i,j] for j = 1:2) - b + v[i] >= 1)\n\n# This parameter trades off accuracy and robustness for the classifier\n @objective(m, Min, sum(u[i] for i=1:100) + sum(v[i] for i=1:100)\n + δ*(sum(a[j]^2 for j=1:2)))\n\n solve(m);\n\n return getvalue(a), getvalue(b), getvalue(u), getvalue(v)\nend\n\na, b, u1, v1 = classify(data1, data0, 0.01);\n\n# Calculating the points on plane defined by a and b\nx1 = linspace(-10,20,100);\nx2 = (b - a[1]*x1)/ a[2];\n# boundaries of the slab\nx2u = (b + 1 - a[1]*x1)/ a[2];\nx2d = (b - 1 - a[1]*x1)/ a[2];\nplot!(x1, [x2u x2 x2d],\n xlabel = \"x_1\",\n ylabel = \"x_2\",\n label= [ \"\", \"Classifier\", \"\"] ,\n color=[:green :green :green],\n linestyle=[ :dot :solid :dot],\n )\n\n# another classifier, with δ=50\na, b, u2, v2 = classify(data1, data0, 100);\nx2 = (b - a[1]*x1)/ a[2];\nx2u = (b + 1 - a[1]*x1)/ a[2];\nx2d = (b - 1 - a[1]*x1)/ a[2];\nplot!(x1, [x2u x2 x2d],\n xlabel = \"x_1\",\n ylabel = \"x_2\",\n legend = false,\n color=[:purple :purple :purple],\n linestyle=[:dot :solid :dot],\n )\n", "meta": {"hexsha": "5a49622ffb163acd8d2bc86cb32c050568168670", "size": 1771, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/lectures/Lecture_1/Other/L1_Ex4-Classification.jl", "max_stars_repo_name": "gamma-opt/CourseParser.jl", "max_stars_repo_head_hexsha": "be59cf09c2c8b34373a6cd0f972f46528c4233dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/lectures/Lecture_1/Other/L1_Ex4-Classification.jl", "max_issues_repo_name": "gamma-opt/CourseParser.jl", "max_issues_repo_head_hexsha": "be59cf09c2c8b34373a6cd0f972f46528c4233dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/lectures/Lecture_1/Other/L1_Ex4-Classification.jl", "max_forks_repo_name": "gamma-opt/CourseParser.jl", "max_forks_repo_head_hexsha": "be59cf09c2c8b34373a6cd0f972f46528c4233dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4328358209, "max_line_length": 86, "alphanum_fraction": 0.5748164879, "num_tokens": 695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.956634196290671, "lm_q2_score": 0.8840392848011834, "lm_q1q2_score": 0.8457022107051597}} {"text": "\"\"\"\n LogUniform(a,b)\n\nA positive random variable `X` is log-uniformly with parameters `a` and `b` if the logarithm of `X` is `Uniform(log(a), log(b))`.\nThe *log uniform* distribution is also known as *reciprocal distribution*.\n```julia\nLogUniform(1,10)\n```\nExternal links\n\n* [Log uniform distribution on Wikipedia](https://en.wikipedia.org/wiki/Reciprocal_distribution)\n\"\"\"\nstruct LogUniform{T<:Real} <: ContinuousUnivariateDistribution\n a::T\n b::T\n LogUniform{T}(a::T, b::T) where {T <: Real} = new{T}(a, b)\nend\n\nfunction LogUniform(a::T, b::T; check_args::Bool=true) where {T <: Real}\n check_args && @check_args(LogUniform, 0 < a < b)\n LogUniform{T}(a, b)\nend\n\nLogUniform(a::Real, b::Real; check_args::Bool=true) = LogUniform(promote(a, b)...; check_args=check_args)\n\nconvert(::Type{LogUniform{T}}, d::LogUniform) where {T<:Real} = LogUniform(T(d.a), T(d.b); check_args=false)\nBase.minimum(d::LogUniform) = d.a\nBase.maximum(d::LogUniform) = d.b\n\n#### Parameters\nparams(d::LogUniform) = (d.a, d.b)\npartype(::LogUniform{T}) where {T<:Real} = T\n\n#### Statistics\n\nfunction mean(d::LogUniform)\n a, b = params(d)\n (b - a) / log(b/a)\nend\nfunction var(d::LogUniform)\n a, b = params(d)\n log_ba = log(b/a)\n (b^2 - a^2) / (2*log_ba) - ((b-a)/ log_ba)^2\nend\nmode(d::LogUniform) = d.a\nmodes(d::LogUniform) = partype(d)[]\n\nfunction entropy(d::LogUniform)\n a,b = params(d)\n log(a * b) / 2 + log(log(b / a))\nend\n#### Evaluation\nfunction pdf(d::LogUniform, x::Real)\n x1, a, b = promote(x, params(d)...) # ensure e.g. pdf(LogUniform(1,2), 1f0)::Float32\n res = inv(x1 * log(b / a))\n return insupport(d, x1) ? res : zero(res)\nend\nfunction cdf(d::LogUniform, x::Real)\n x1, a, b = promote(x, params(d)...) # ensure e.g. cdf(LogUniform(1,2), 1f0)::Float32\n x1 = clamp(x1, a, b)\n return log(x1 / a) / log(b / a)\nend\nlogpdf(d::LogUniform, x::Real) = log(pdf(d,x))\n\nfunction quantile(d::LogUniform, p::Real)\n p1,a,b = promote(p, params(d)...) # ensure e.g. quantile(LogUniform(1,2), 1f0)::Float32\n exp(p1 * log(b/a)) * a\nend\n\nfunction kldivergence(p::LogUniform, q::LogUniform)\n ap, bp, aq, bq = promote(params(p)..., params(q)...)\n finite = aq <= ap < bp <= bq\n res = log(log(bq / aq) / log(bp / ap))\n return finite ? res : oftype(res, Inf)\nend\n", "meta": {"hexsha": "da4ef3209fd66949f32f6deee120a536f47a80e8", "size": 2300, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/continuous/loguniform.jl", "max_stars_repo_name": "pdeffebach/Distributions.jl", "max_stars_repo_head_hexsha": "8aea3cc82ee2f8ffe1e8cd754e7fcd99369c7a1c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/univariate/continuous/loguniform.jl", "max_issues_repo_name": "pdeffebach/Distributions.jl", "max_issues_repo_head_hexsha": "8aea3cc82ee2f8ffe1e8cd754e7fcd99369c7a1c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/continuous/loguniform.jl", "max_forks_repo_name": "pdeffebach/Distributions.jl", "max_forks_repo_head_hexsha": "8aea3cc82ee2f8ffe1e8cd754e7fcd99369c7a1c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2631578947, "max_line_length": 129, "alphanum_fraction": 0.6273913043, "num_tokens": 780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430805473952, "lm_q2_score": 0.9059898114992677, "lm_q1q2_score": 0.8456787994989554}} {"text": "using Plots\nusing Random\nusing Pkg; Pkg.add(\"LaTeXStrings\")\nusing LaTeXStrings\n\n# Set seed\nRandom.seed!(123)\n\n# Generate MC points\nn = 2000\npoints_x = rand(n)\npoints_y = rand(n)\n\n# Label points in circle\nlabels = [x^2 + y^2 <= 1 for (x,y) in zip(points_x, points_y)]\n\n# Estaimte of pi\nπ_estimate = 4*sum(labels)/n\n\n# Create plot of MC points\nplot(points_x, points_y, seriestype = :scatter,\n group = .!labels,\n title = L\"\\textrm{Monte Carlo } \\pi \\textrm{ estimation}\",\n legend = false,\n bg = RGB(247/255, 236/255, 226/255))\n\n# Add semi-circle quadrant plot\ncircle_x = 0:0.01:1\ncircle_y = sqrt.(1 .- circle_x.^2)\nplot!(circle_x, circle_y, seriestype= :line, legend = false, lc = :yellow)\n\n# Generate plots comparing π estimate across multiple n\nn_values = [5000, 10000, 100000, 1e6, 2e6]\nπ_estimates_error = zeros(5)\n\nfor i in 1:5\n n_value = Int64(n_values[i])\n points_x = rand(n_value)\n points_y = rand(n_value)\n estimate = 4*sum([x^2 + y^2 <= 1 for (x,y) in zip(points_x, points_y)])/\n n_value\n π_estimates_error[i] = 100*abs(π - estimate)/π\nend\n\nprintln(π_estimates_error)\n\n# savefig(\"../images/pi-monte-carlo.svg\")\n\n# Plot area under circle curve\nplot(circle_x, circle_y, legend = false,\n fillrange = [zeros(length(circle_x)), circle_y],\n alpha = .5,\n lc = :yellow)\n", "meta": {"hexsha": "98e474f6ec8aa60fbfc56719354b09a047a6d07c", "size": 1316, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "content/stochastic-approximations/code/pi_mc_plot.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/pi_mc_plot.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/pi_mc_plot.jl", "max_forks_repo_name": "seanrattana/courses", "max_forks_repo_head_hexsha": "9453abc38af26ea49cb00fe1744066fc0de237b3", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-08-18T21:23:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-02T19:14:33.000Z", "avg_line_length": 24.3703703704, "max_line_length": 76, "alphanum_fraction": 0.6717325228, "num_tokens": 432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966732132748, "lm_q2_score": 0.8933094152856196, "lm_q1q2_score": 0.8456037206594632}} {"text": "using NumericalMethodsforEngineers\nusing Test\n\n@sym begin\n ClearAll(xi, yi, Y, Ydot, Ydotdot, ytilde1, ytilde2, R)\n xi = [0, 1//3, 2//3, 1]\n yi = [0, a, b, 1]\n Y(x_) := LagrangePolynomial(xi, yi)\n #\n # Can be re-formulated as Y(x) = F(x) + C1(a) * Ψ1(x) + C2(a) * Ψ2(x)\n #\n # F(x_) := (1/2)*(9x^3 - 9x^2 + 2x)\n # C1(a_) := (27/2)*(a-b)\n # Ψ1(x_) := x^3 - x^2\n # C2(a_) := -(9/2)*(2a-b)\n # Ψ2(x_) := x^2 - x\n #\n # Y(x_) := F(x) + C1(a)*Ψ1(x) + C2(a)*Ψ2(x)\n #\n R(x_) = Simplify(D(Y(x), x, 2) - 3*x - 4*Y(x))\n sol = Solve([R(xi[2]), R(xi[3])], [a, b])\n ytilde(x_) = Y(x) ./ Flatten(sol)\n SetJ(r, ToString(Simplify(R(x))))\n SetJ(s, \"[$(sol[1][1][2]), $(sol[1][2][2])]\")\n SetJ(t, ToString(Simplify(ytilde(x))))\nend\n\nprintln(\"\\n\\nExample 7.15b: y'' = 3x + 4y, y(0)=0, y(1)=1\")\nprintln(\"by 2-point collocation Weighted Residual Method\")\n@sym Println(\"\\nY(x): \", Y(x), \"\\n\")\n@sym Println(\"R(x) = \", R(x), \"\\n\")\nprintln(\"(a, b) = $(s)\\n\")\n@sym Println(\"ytilde_2pt_collocation(x) = \", Simplify(ytilde(x)), \"\\n\")\nprintln()\n\n@eval rf_2pt_collocation_2(x, a, b) = $(Meta.parse(r))\n@eval ytilde_2pt_collocation(x) = $(Meta.parse(t))\n@eval (a, b) = $(Meta.parse(s))\n\n@test t == \"(1/806)*x*(239 - 252x + 819*x^2)\"\n@test rf_2pt_collocation_2(1//3, a, b) <= eps()\n@test rf_2pt_collocation_2(2//3, a, b) <= eps()\n", "meta": {"hexsha": "c5b6e95a314819fba6f1fdd31e9cc6e59184457c", "size": 1315, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ch07/WRM/Ex.7.15b.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.15b.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.15b.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": 30.5813953488, "max_line_length": 71, "alphanum_fraction": 0.5376425856, "num_tokens": 601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947132556619, "lm_q2_score": 0.8947894618940992, "lm_q1q2_score": 0.8455713109668023}} {"text": "# # Portfolio Optimization\n#\n# In this problem, we will find the portfolio allocation that minimizes risk while achieving a given expected return $R_\\text{target}$.\n#\n# Suppose that we know the mean returns $\\mu \\in \\mathbf{R}^n$ and the covariance $\\Sigma \\in \\mathbf{R}^{n \\times n}$ of the $n$ assets. We would like to find a portfolio allocation $w \\in \\mathbf{R}^n$, $\\sum_i w_i = 1$, minimizing the *risk* of the portfolio, which we measure as the variance $w^T \\Sigma w$ of the portfolio. The requirement that the portfolio allocation achieve the target expected return can be expressed as $w^T \\mu >= R_\\text{target}$. We suppose further that our portfolio allocation must comply with some lower and upper bounds on the allocation, $w_\\text{lower} \\leq w \\leq w_\\text{upper}$.\n#\n# This problem can be written as\n#\n# $$\n# \\begin{array}{ll}\n# \\text{minimize} & w^T \\Sigma w \\\\\n# \\text{subject to} & w^T \\mu >= R_\\text{target} \\\\\n# & \\sum_i w_i = 1 \\\\\n# & w_\\text{lower} \\leq w \\leq w_\\text{upper}\n# \\end{array}\n# $$\n#\n# where $w \\in \\mathbf{R}^n$ is our optimization variable.\n\nusing Convex, SCS\n\n## generate problem data\nμ = [11.5; 9.5; 6]/100 #expected returns\nΣ = [166 34 58; #covariance matrix\n 34 64 4;\n 58 4 100]/100^2\n\nn = length(μ) #number of assets \n\nR_target = 0.1\nw_lower = 0\nw_upper = 0.5;\n\n# If you want to try the optimization with more assets, uncomment and run the next cell. It creates a vector or average returns and a variance-covariance matrix that have scales similar to the numbers above.\n\n#=\nusing Random\nRandom.seed!(123)\n\nn = 15 #number of assets, CHANGE IT?\n\nμ = (6 .+ (11.5-6)*rand(n))/100 #mean\nA = randn(n,n)\nΣ = (A * A' + diagm(0=>rand(n)))/500; #covariance matrix\n=#\n\n#-\n\nw = Variable(n)\nret = dot(w,μ)\nrisk = quadform(w,Σ)\n\np = minimize( risk, \n ret >= R_target, \n sum(w) == 1, \n w_lower <= w, \n w <= w_upper )\n\nsolve!(p, SCS.Optimizer()) #use SCS.Optimizer(verbose = false) to suppress printing\n\n#-\n\n# Optimal portfolio weights:\nw.value\n\n#-\n\nsum(w.value)\n", "meta": {"hexsha": "ca15785a37d9512829205667101c2a88c5064791", "size": 2224, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/examples_literate/portfolio_optimization/portfolio_optimization.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/portfolio_optimization/portfolio_optimization.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/portfolio_optimization/portfolio_optimization.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": 32.231884058, "max_line_length": 617, "alphanum_fraction": 0.6092625899, "num_tokens": 668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.949669363129097, "lm_q2_score": 0.8902942363098473, "lm_q1q2_score": 0.8454851603938784}} {"text": "# # [Implicit Nonlinear Dynamics : Autoregulation](@id autoregulation)\n#\n# The following is another example on how to use the [`ImplicitOptimizer`](@ref) describing a biological autoregulation process using\n# two coupled implicit equations. \n\nusing DataDrivenDiffEq\nusing ModelingToolkit\nusing OrdinaryDiffEq\nusing LinearAlgebra\n#md using Plots\n#md gr()\n\n@parameters begin\n t\n α = 1.0\n β = 1.3\n γ = 2.0\n δ = 0.5\nend\n\n@variables begin\n x[1:2](t) = [20.0; 12.0]\nend\n\nx = collect(x)\nD = Differential(t)\n\neqs = [\n D(x[1]) ~ α/(1+x[2])-β*x[1];\n D(x[2]) ~ γ/(1+x[1])-δ*x[2];\n]\n\nsys = ODESystem(eqs, t, x, [α, β, γ, δ], name = :Autoregulation)\n\nx0 = [x[1] => 20.0; x[2] => 12.0] \n\ntspan = (0.0, 5.0) \n\nde_problem = ODEProblem(sys, x0, tspan) \nde_solution = solve(de_problem, Tsit5(), saveat = 0.005);\n#md plot(de_solution)\n\n# As always, we start by defining a [DataDrivenProblem](@ref problem) and a sufficient basis for sparse regression.\n\ndd_prob = ContinuousDataDrivenProblem(de_solution)\n\neqs = [\n polynomial_basis(x, 4); D.(x); x .* D(x[1]); x .* D(x[2])\n ]\n \nbasis = Basis(eqs, x, independent_variable = t, implicits = D.(x))\n\n#md plot(dd_prob)\n\n# Next to varying over different sparsity penalties, we want also to batch our data using the [DataSampler](@ref).\n# We define a train-test split of 80-20 for our data and batch the resulting training data into 10 minibatches, allowing \n# shuffled and repeated values. Our goal is to find the model with the minimal error.\n\nsampler = DataSampler(\n Split(ratio = 0.8), Batcher(n = 10, shuffle = true, repeated = true, batchsize_min = 30)\n)\n\nres = solve(dd_prob, basis, ImplicitOptimizer(STLSQ(1e-1:1e-1:9e-1)), by = :min, sampler = sampler, digits = 1)\nprint(res) #hide\nprint(result(res)) #hide\n\n# We have recovered the correct equations of motion! \n# Another visual check using the problem and the result yields \n\nsystem = result(res)\n@named ode = ODESystem(equations(system), t, x, parameters(system));\node_prob = ODEProblem(ode, x0, tspan, parameter_map(res));\n\nprediction = solve(ode_prob, Tsit5(), saveat = 0.2);\n#md plot(de_solution, label = [\"Groundtruth\" nothing]) \n#md scatter!(prediction, label = [\"Prediction\" nothing]) \n\n\n#md # ## [Copy-Pasteable Code](@id autoregulation_copy_paste)\n#md #\n#md # ```julia\n#md # @__CODE__\n#md # ```\n\nfor r_ in [res] #src\n @test all(l2error(r_) .< 0.5) #src\n @test all(aic(r_) .> 1e3) #src\n @test all(determination(r_) .>= 0.9) #src\nend #src\n\n\n", "meta": {"hexsha": "8ac771d487cdc9bdd2169bc7150266aa5da01983", "size": 2476, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/examples/6_autoregulation.jl", "max_stars_repo_name": "JuliaDiffEq/DataDrivenDiffEq.jl", "max_stars_repo_head_hexsha": "27f5537d2d04719b80f5785531b2b02e27a8208f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2019-11-22T17:20:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-07T17:10:27.000Z", "max_issues_repo_path": "docs/examples/6_autoregulation.jl", "max_issues_repo_name": "JuliaDiffEq/DataDrivenDiffEq.jl", "max_issues_repo_head_hexsha": "27f5537d2d04719b80f5785531b2b02e27a8208f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 53, "max_issues_repo_issues_event_min_datetime": "2019-11-22T17:20:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-22T15:11:55.000Z", "max_forks_repo_path": "docs/examples/6_autoregulation.jl", "max_forks_repo_name": "AlCap23/DataDrivenDiffEq", "max_forks_repo_head_hexsha": "3be031060d5a3cad08473506be60108e572ac0fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-11-22T18:36:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:36:14.000Z", "avg_line_length": 26.9130434783, "max_line_length": 133, "alphanum_fraction": 0.6744749596, "num_tokens": 803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475810629193, "lm_q2_score": 0.8962513800615312, "lm_q1q2_score": 0.8454765714053485}} {"text": "module RandomNumbers\n# Note:\n# Unless mentioned otherwise, the single variable continuous functions return\n# Float64 and the multiple variable continuous functions return Array{Float64, 1}.\n# Similarly, the single variable discrete functions return Int64 and the multiple\n# variable discrete functions return Array{Int64, 1}.\nexport rn_unif, rn_exp, rn_standard_cauchy, rn_standard_normal, rn_normal,\n\t rn_chi_sq, rn_bernoulli, rn_binom, rn_geo, rn_gamma, rn_beta\n\n# Generate a single uniform random variable between a and b.\nfunction rn_unif(a, b)\n\treturn a + rand() * (b - a)\nend\n\n# Generate n random uniform variables between a and b.\nfunction rn_unif(a, b, n::Int64)\n\treturn [rn_unif(a,b) for x in 1:n]\nend\n\n# Generate a single exponential random variable with rate parameter theta.\nfunction rn_exp(theta)\n\t# Don't allow negative theta values.\n\tif theta <= 0.0\n\t\tthrow(ArgumentError(\"Theta cannot be less than zero.\"))\n\tend\n\n\treturn -log(rn_unif(0, 1)) / theta\nend\n\n# Generate n exponential random variables with rate parameter theta.\nfunction rn_exp(theta, n::Int64)\n\treturn [rn_exp(theta) for x in 1:n]\nend\n\n# Generate a single standard Cauchy random variable.\nfunction rn_standard_cauchy()\n\treturn tan(pi * (rn_unif(0, 1) - .5))\nend\n\n# Generate n standard Cauchy random variables.\nfunction rn_standard_cauchy(n::Int64)\n\treturn [rn_standard_cauchy() for x in 1:n]\nend\n\n# Generate a single standard normal random variable.\nfunction rn_standard_normal()\n\tu1 = rand()\n\tu2 = rand()\n\n\treturn sqrt(-2 * log(u1)) * cos(2 * pi * u2)\nend\n\n# Generate n standard normal random variables.\nfunction rn_standard_normal(n::Int64)\n\treturn [rn_standard_normal() for x in 1:n]\nend\n\n# Generate a single normal random variable with mean mu and\n# standard deviation sigma.\nfunction rn_normal(mu, sigma)\n\t# Don't allow negative sigma.\n\tif sigma <= 0.0\n\t\tthrow(ArgumentError(\"Standard deviation cannot be negative.\"))\n\tend\n\n\treturn (sigma * rn_standard_normal()) + mu\nend\n\n# Generate n normal random variables with mean mu and standard deviation sigma.\nfunction rn_normal(mu, sigma, n::Int64)\n\treturn [rn_normal(mu, sigma) for x in 1:n]\nend\n\n# Generate a single chi-square random normal variable with k degrees of freedom.\n# Is specifying Integer in argument necessary?\nfunction rn_chi_sq(k::Integer)\n\t# Only accept positive natural numbers as input.\n\tif k < 1\n\t\tthrow(ArgumentError(\"Degrees of freedom must be at least 1.\"))\n\tend\n\n\t# Generate k squared random normal variables.\n\tnormals = rn_standard_normal(k).^2\n\n\t# Return the sum of the squared random normal variables.\n\treturn sum(normals)\nend\n\n# Generate n chi-square random normal variables with k degrees of freedom.\nfunction rn_chi_sq(k::Integer, n::Int64)\n\treturn [rn_chi_sq(k) for x in 1:n]\nend\n\n# Generate a single Bernoulli random variable with success probability\n# p as an Int64.\nfunction rn_bernoulli(p)\n\t# Only allow success probabilities in between 0 and 1.\n\tif !(0 < p < 1)\n\t\tthrow(ArgumentError(\"Success probability must be between 0 and 1.\"))\n\tend\n\n\t# Generate a single uniform random variable.\n\tunif = rn_unif(0, 1)\n\n\t# Return whether the random variable is below p.\n\treturn unif < p ? 1 : 0\nend\n\n# Generate n Bernoulli random variables with success probability p as\n# an Array{Int64, 1}.\nfunction rn_bernoulli(p, n::Int64)\n\treturn [rn_bernoulli(p) for x in 1:n]\nend\n\n# Generate a single binomial random variable with success probability p.\n# Returns Int64.\nfunction rn_binom(trials::Int64, p)\n\t# Only allow success probabilities in between 0 and 1.\n\tif !(0 < p < 1)\n\t\tthrow(ArgumentError(\"Success probability must be between 0 and 1.\"))\n\tend\n\n\t# Only allow positive numbers of trials.\n\tif trials < 1\n\t\tthrow(ArgumentError(\"Number of trials must be at least 1.\"))\n\tend\n\n\t# Generate Bernoulli random variable for each trial.\n\tberns = rn_bernoulli(p, trials)\n\n\t# Return the sum of successful trials.\n\treturn sum(berns)\nend\n\n# Generate n binomial random variables with success probability p as an\n# Array{Int64, 1}.\nfunction rn_binom(trials, p, n::Int64)\n\treturn [rn_binom(trials, p) for x in 1:n]\nend\n\n# Generate a single geometric random variable with success probability p.\nfunction rn_geo(p)\n\t# Only allow success probabilities in between 0 and 1.\n\tif !(0 < p < 1)\n\t\tthrow(ArgumentError(\"Success probability must be between 0 and 1.\"))\n\tend\n\n\tlambda = -log(1 - p)\n\n\texp = rn_exp(lambda)\n\n\treturn ifloor(exp) + 1\nend\n\n# Generate n geometric random variables with success probability p.\nfunction rn_geo(p, n::Int64)\n\treturn [rn_geo(p) for x in 1:n]\nend\n\n# Generate a single gamma random variable with shape parameter alpha and rate\n# parameter beta. This function implements Marsaglia and Tsang's method for \n# generating gamma random variables.\nfunction rn_gamma(alpha, beta)\n\tif alpha <= 0 || beta <= 0\n\t\tthrow(ArgumentError(\"Alpha and beta must be greater than zero.\"))\n\tend\n\n\tif (alpha >= 1)\n\t\t# Set two constants used in the algorithm.\n\t\td = alpha - (1.0 / 3.0)\n\t\tc = 1.0 / sqrt(9.0 * d)\n\n\t\t# We need to loop until we generate appropriate random numbers\n\t\twhile true\n\t\t\t# Generate Z~N(0,1).\n\t\t\tz = rn_standard_normal()\n\n\t\t\t# We need a z that will never result in a negative v.\n\t\t\tif z > -1.0 / c\n\t\t\t\tv = (1.0 + c * z)^3\n\n\t\t\t\t# Generate U~U(0,1).\n\t\t\t\tu = rn_unif(0, 1)\n\n\t\t\t\t# Compute the upper bound for log(u).\n\t\t\t\tu_bound = (.5 * z^2) + d - (d * v) + (d * log(v))\n\n\t\t\t\t# If this condition holds we've found a suitable result.\n\t\t\t\tif log(u) < u_bound\n\t\t\t\t\treturn (d * v) / beta\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\telse\n\t\t# When 0 < alpha < 1 we can return a transformed answer.\n\t\tx = rn_gamma(alpha + 1, beta)\n\t\tu = rn_unif(0, 1)\n\t\treturn x * u ^ (1 / alpha)\n\tend\nend\n\n# Generate n gamma random variables with shape parameter alpha and rate\n# parameter beta.\nfunction rn_gamma(alpha, beta, n::Int64)\n\treturn [rn_gamma(alpha, beta) for x in 1:n]\nend\n\n# Generate a beta random variable with shape parameters alpha and beta.\n# Note that this does not use the rejection method.\nfunction rn_beta(alpha, beta)\n\tif alpha <= 0 || beta <= 0\n\t\tthrow(ArgumentError(\"Alpha and beta must be greater than zero.\"))\n\tend\n\n\t# Generate two independent gamma variables\n\tx = rn_gamma(alpha, 1)\n\ty = rn_gamma(beta, 1)\n\n\treturn x / (x + y)\nend\n\nfunction rn_beta(alpha, beta, n::Int64)\n\treturn [rn_beta(alpha, beta) for x in 1:n]\nend\n\nend", "meta": {"hexsha": "2bdb1fcda507e4d43dfa372d2796f82b9defdf75", "size": 6262, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "RandomNumbers.jl", "max_stars_repo_name": "andrewjlm/StatComputing", "max_stars_repo_head_hexsha": "b18167f6ecd3e1689316a3f6077e50bde7dfaa03", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RandomNumbers.jl", "max_issues_repo_name": "andrewjlm/StatComputing", "max_issues_repo_head_hexsha": "b18167f6ecd3e1689316a3f6077e50bde7dfaa03", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RandomNumbers.jl", "max_forks_repo_name": "andrewjlm/StatComputing", "max_forks_repo_head_hexsha": "b18167f6ecd3e1689316a3f6077e50bde7dfaa03", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7079646018, "max_line_length": 82, "alphanum_fraction": 0.7226125838, "num_tokens": 1734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422241476943, "lm_q2_score": 0.8887587875995482, "lm_q1q2_score": 0.8453360099682425}} {"text": "# # Consumption Savings Problem\n# In this case study, a household endowed with ``B_0`` dollars of wealth\n# must decide how much to consume and save \n# to maximize its utility over its finite lifecycle. \n\n# ## Formulation\n\n# The corresponding dynamic optimization problem is expressed:\n# ```math\n# \\begin{aligned}\n# \t&V(B_0,0) = &&\\underset{c(t), B(t)}{\\text{max}} \\int_{t = 0}^{t=T} e^{-\\rho t} u(c(t)) dt \\\\\n# \t&\\text{s.t.} \\\\\n# \t&&& \\frac{dB}{dt} = r \\times B(t) - c(t), && t \\in [0,T] \\\\\n# &&& B(0) = B_0 \\\\\n# &&& B(T) = 0\n# \\end{aligned}\n# ```\n# where \n# the household lives during time ``t \\in [0,T]``,\n# the state variable ``B(t)`` is the household's stock of wealth at time ``t``,\n# the choice variable ``c(t)`` is the household's consumption at time ``t``,\n# ``r`` is the interest rate,\n# ``B_0`` is the household's wealth endowment (initial condition),\n# ``B(T) = 0`` is the terminal condition,\n# and ``T`` is the time\n# horizon.\n\n# ## Model Definition\n\n# Let's implement this in `InfiniteOpt` and first import the packages we need:\nusing InfiniteOpt, Ipopt\n\n# We set the preference and constraint parameters:\nρ = 0.025 # discount rate \nk = 100.0 # utility bliss point \nT = 10.0 # life horizon \nr = 0.05 # interest rate\nB0 = 100.0 # endowment\nu(c; k=k) = -(c - k)^2 # utility function \ndiscount(t; ρ=ρ) = exp(-ρ*t) # discount function \nBC(B, c; r=r) = r*B - c # budget constraint \n\n# We set the hyperparameters:\nopt = Ipopt.Optimizer # desired solver\nns = 1_000; # number of points in the time grid\n\n# We initialize the infinite model and choose the Ipopt solver:\nm = InfiniteModel(opt)\n\n# Let's specify our infinite parameter which is time ``t \\in [0, T]``:\n@infinite_parameter(m, t in [0, T], num_supports = ns)\n\n# Now let's specify the variables:\n@variable(m, B, Infinite(t)) ## state variables \n@variable(m, c, Infinite(t)) ## control variables \n\n# Specify the objective:\n@objective(m, Max, integral(u(c), t, weight_func = discount)) \n\n# Set the initial/terminal conditions:\n@constraint(m, B == B0, DomainRestrictions(t => 0)) \n@constraint(m, B == 0, DomainRestrictions(t => T)) \n\n# Set the budget constraint:\n@constraint(m, c1, deriv(B, t) == BC(B, c; r=r))\n\n# ## Problem Solution\n\n# Optimize the model:\noptimize!(m)\ntermination_status(m)\n\n# Extract the results:\nc_opt = value(c)\nB_opt = value(B)\nts = supports(t)\nopt_obj = objective_value(m) # V(B0, 0)\n\n# Plot the results:\nusing Plots\nix = 2:(length(ts)-1) # index for plotting \nplot(ts[ix], B_opt[ix], lab = \"B: wealth balance\")\nplot!(ts[ix], c_opt[ix], lab = \"c: consumption\")\n\n# That's it, now we have our optimal trajectory!\n\n# This very simple problem has a closed form solution: \nλ1 = exp((r)T)\nλ2 = exp(-(r-ρ)T)\nden = (λ1-λ2)r\nΩ1 = (k + (r*B0-k)λ2)/den \nΩ2 = (k + (r*B0-k)λ1)/den \nc0 = r*B0 + (r)Ω1 + (r-ρ)Ω2\nBB(t; k=k,r=r,ρ=ρ,Ω1=Ω1,Ω2=Ω2) = (k/r) - Ω1*exp((r)t) + Ω2*exp(-(r-ρ)t)\ncc(t; k=k,r=r,ρ=ρ,c0=c0) = k + (c0-k)*exp(-(r-ρ)t)\n\n# Compare the solution given by `InfiniteOpt` with the closed form:\nplot(legend=:topright);\nplot!(ts[ix], c_opt[ix], color = 1, lab = \"c: consumption, InfiniteOpt\");\nplot!(ts[ix], cc, color = 1, linestyle=:dash, lab = \"c: consumption, closed form\");\nplot!(ts[ix], B_opt[ix], color = 4, lab = \"B: wealth balance, InfiniteOpt\");\nplot!(ts[ix], BB, color = 4, linestyle=:dash, lab = \"B: wealth balance, closed form\")\n\n# Not bad!\n\n\n\n# ### Maintenance Tests\n# These are here to ensure this example stays up to date. \nusing Test\n@test termination_status(m) == MOI.LOCALLY_SOLVED\n@test has_values(m)\n@test B_opt isa Vector{<:Real}\n@test c_opt isa Vector{<:Real}\n", "meta": {"hexsha": "3e8c657cb43797c57a6a4eb913ecfb2a0b12af1a", "size": 3691, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/examples/Optimal Control/consumption_savings.jl", "max_stars_repo_name": "azev77/InfiniteOpt.jl", "max_stars_repo_head_hexsha": "db734856e6d89fd105f7bdb4fb5b8e16a72bd7fd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/src/examples/Optimal Control/consumption_savings.jl", "max_issues_repo_name": "azev77/InfiniteOpt.jl", "max_issues_repo_head_hexsha": "db734856e6d89fd105f7bdb4fb5b8e16a72bd7fd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/src/examples/Optimal Control/consumption_savings.jl", "max_forks_repo_name": "azev77/InfiniteOpt.jl", "max_forks_repo_head_hexsha": "db734856e6d89fd105f7bdb4fb5b8e16a72bd7fd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0956521739, "max_line_length": 95, "alphanum_fraction": 0.627743159, "num_tokens": 1186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037282594921, "lm_q2_score": 0.9124361664296878, "lm_q1q2_score": 0.8451930227626183}} {"text": "\"\"\"\n# chebyshevfun\n普通递归给出第一类切比雪夫函数的表达式\n```math\nT_n(x)=2xT_{n-1}(x)-T_{n-2}(x)\n```\n\"\"\"\nfunction chebyshevT(n::Int64,x)\n if n<0\n error(\"chebyshev(n,x), n>=0 is violated\")\n elseif n==0\n return 1\n elseif n==1\n return x\n elseif n==2\n return 2*x^2-1\n elseif n==3\n return 4*x^3-3*x\n elseif n==4\n return 8*x^4-8*x^2+1\n elseif n==5\n return 16*x^5-20*x^3+5*x\n elseif n==6\n return 16*x^5-20*x^3+5*x\n else\n return 2*x*chebyshevT(n-1,x)-chebyshevT(n-2,x)\n end\nend\n\n\"\"\"\n# chebyshevfun\n普通递归给出第一类切比雪夫函数的表达式\n```math\nU_n(x)=2xU_{n-1}(x)-U_{n-2}(x)\n```\n\"\"\"\nfunction chebyshevU(n::Int64,x)\n if n<0\n error(\"chebyshev(n,x), n>=0 is violated\")\n elseif n==0\n return 1\n elseif n==1\n return 2*x\n elseif n==2\n return -1 + 4*x^2\n elseif n==3\n return -4*x + 8*x^3\n elseif n==4\n return 1 - 12*x^2 + 16*x^4\n elseif n==5\n return 6*x - 32*x^3 + 32*x^5\n elseif n==6\n return -1 + 24*x^2 - 80*x^4 + 64*x^6\n else\n return 2*x*chebyshevU(n-1,x)-chebyshevU(n-2,x)\n end\nend\n\n# \"\"\"\n# # chebyshevexpand\n# 切比雪夫展开函数\n# 输入一个函数,返回在指定点处切比雪夫展开后的版本\n# \"\"\"\n\"\"\"\n为切比雪夫T而写的宏\n\"\"\"\nmacro chebyT(n,x)\n return esc(:(2*$x*chebyshevT($n-1,$x)-chebyshevT($n-2,$x)))\nend\n\n\"\"\"\n# chebyshevTmeta\n为切比雪夫展开的多项式\n用元编程进行操作\n\"\"\"\nfunction chebyshevTmeta(n::Int64,x)\n if n==0\n return 1\n elseif n==1\n return x\n elseif n>=2\n return @chebyT(n,x)\n end\nend\n\n# \"\"\"\n# 为切比雪夫U而写的宏\n# \"\"\"\n# macro chebyU(n,x)\n# return esc(:(2*x*chebyshevT($n-1,$x)-chebyshevT($n-2,$x)))\n# end\n\n# \"\"\"\n# # chebyshevTmeta\n# 为切比雪夫展开的多项式\n# 用元编程进行操作\n# \"\"\"\n# function chebyshevUmeta(n::Int64,x)\n# if n==0\n# return 1\n# elseif n==1\n# return 2*x\n# elseif n>=2\n# return @chebyU(n,x)\n# end\n# end", "meta": {"hexsha": "3ec5d252a62103055526c4e264c2e3fac1919e63", "size": 1843, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chebyshev.jl", "max_stars_repo_name": "sesameman/ChebyshevFun.jl", "max_stars_repo_head_hexsha": "638c6b7d05b1e43b3a076c7631371968df95cd1f", "max_stars_repo_licenses": ["MIT"], "max_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": "sesameman/ChebyshevFun.jl", "max_issues_repo_head_hexsha": "638c6b7d05b1e43b3a076c7631371968df95cd1f", "max_issues_repo_licenses": ["MIT"], "max_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": "sesameman/ChebyshevFun.jl", "max_forks_repo_head_hexsha": "638c6b7d05b1e43b3a076c7631371968df95cd1f", "max_forks_repo_licenses": ["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.3867924528, "max_line_length": 64, "alphanum_fraction": 0.5355398806, "num_tokens": 872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140225647108, "lm_q2_score": 0.8740772450055545, "lm_q1q2_score": 0.845157545000601}} {"text": "\"\"\"\n euler_totient(n::Int64)\n\nCompute the positive integers up to a given integer n that are relatively prime to n; also\nknown as Euler's totient. For more information see: [https://en.wikipedia.org/wiki/Euler%27s_totient_function](https://en.wikipedia.org/wiki/Euler%27s_totient_function)\n\n\n# Arguments\n- `n::Int64`: Number of elements\n\n\n# Examples\n```julia-repl\njulia> import ClassicAlgorithmsCollections\njulia> ClassicAlgorithmsCollections.euler_totient(20)\n[1, 1, 2, 2, 4, 2, 6, 4, 6, 4, 10, 4, 12, 6, 8, 8, 16, 6, 18, 8]\n```\n\"\"\"\nfunction euler_totient(n::Int64)\n\n result = collect(Int64, 1:n)\n\n for i in 1:n\n m = i\n p = 2\n while m >= p^2\n if (m % p == 0)\n while (m % p == 0)\n m = convert(Int64, m / p)\n end\n result[i] -= convert(Int64, result[i] / p)\n end\n p += 1\n end\n if m > 1\n result[i] -= convert(Int64, result[i] / m)\n end\n end\n return result\nend\n", "meta": {"hexsha": "9e97b2bee6121134e4169dd048980e7a4169a90b", "size": 1022, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NumberTheory/EulerTotient.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/NumberTheory/EulerTotient.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/NumberTheory/EulerTotient.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": 24.9268292683, "max_line_length": 168, "alphanum_fraction": 0.560665362, "num_tokens": 323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.966914017797636, "lm_q2_score": 0.8740772236840656, "lm_q1q2_score": 0.8451575202177628}} {"text": "using Revise\nusing DynamicalSystems\nusing Basins\nusing Plots\nusing BenchmarkTools\n\n\n# FRACTAL BASIN BOUNDARIES\n# Steven W. MCDONALD, Celso GREBOGY Edward OTT and James A. YORKE\n# Physica D 17 1985\nfunction chaotic_map(dz,z, p, n)\n\n xn = z[1]; yn = z[2]\n λ₁=p[1];λ₂=p[2];\n dz[1]=mod(λ₁*xn,1)\n dz[2]=λ₂*yn+cos(2*π*xn)\n return\nend\n\n# dummy function to keep the initializator happy\nfunction chaotic_map_J(J,z0, p, n)\n return\nend\nds = DiscreteDynamicalSystem(chaotic_map,[1., 0.], [1.1, 1.] , chaotic_map_J)\ninteg = integrator(ds)\n\n# This map has two escapes to ±∞\nfunction escape_function(y)\n if y > 10000\n return 1\n elseif y < -10000\n return 2\n end\n return 0\nend\n\nfunction get_color(integ,x,y)\n reinit!(integ,[x,y])\n while escape_function(integ.u[2]) == 0\n step!(integ)\n integ.t > 2000 && break\n end\n return escape_function(integ.u[2]);\nend\n\n\nxg=range(0.,1.,length=600)\nyg=range(-2.,2.,length=600)\ninteg.p[1] = 3\ninteg.p[2] = 1.5\nbasin_t = zeros(length(xg),length(yg))\n\n# Compute escape basin\nfor (k,x) in enumerate(xg), (n,y) in enumerate(yg)\n basin_t[k,n]=get_color(integ,x,y);\nend\n\n@show bd = box_counting_dim(xg, yg, basin_t)\n\n\n# Estimation using the method of the paper.\n# The results do not match exactly. But the paper talks about\n# approximate results\nN=[]\neps_r = 10 .^range(-8,-1,length=10)\n\nfor eps in eps_r\n @show eps\n N2=0\n N1=0\n\n for k in 1:8192*20\n\n k1 = rand(1:length(xg))\n k2 = rand(1:length(yg))\n\n c1 = get_color(integ, xg[k1],yg[k2])\n c2 = get_color(integ, xg[k1]+eps,yg[k2])\n c3 = get_color(integ, xg[k1]-eps, yg[k2])\n\n if length(unique([c1,Int(c2),Int(c3)]))>1\n N1 += 1\n end\n N2 += 1\n end\n @show N1/N2\n push!(N,N1/N2)\nend\n\nusing LsqFit\n# get exponent\n@. model(x, p) = p[1]*x+p[2]\nfit = curve_fit(model, vec(log10.(eps_r)), vec(log10.(N)), [2., 2.])\nD = coef(fit)\n@show 2-D[1]\n\nplot(xg,yg,basin_t',seriestype=:heatmap)\n", "meta": {"hexsha": "94c1cc4049c49058d9b6ec18a30d28532616ddf7", "size": 1999, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/examples/tst_map_mcdonald.jl", "max_stars_repo_name": "awage/Basins.jl", "max_stars_repo_head_hexsha": "765a232b0568a257a845ee95a14c0cf2776046a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-04-27T14:46:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T08:39:36.000Z", "max_issues_repo_path": "src/examples/tst_map_mcdonald.jl", "max_issues_repo_name": "awage/Basins.jl", "max_issues_repo_head_hexsha": "765a232b0568a257a845ee95a14c0cf2776046a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-12T15:47:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-14T13:47:35.000Z", "max_forks_repo_path": "src/examples/tst_map_mcdonald.jl", "max_forks_repo_name": "awage/Basins.jl", "max_forks_repo_head_hexsha": "765a232b0568a257a845ee95a14c0cf2776046a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.3979591837, "max_line_length": 77, "alphanum_fraction": 0.6193096548, "num_tokens": 741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167045, "lm_q2_score": 0.9111797015700341, "lm_q1q2_score": 0.8449946036575945}} {"text": "```\r\nReg(args...) -->Plot\r\n\r\nEstimate Linear, Exponential and Power regression type\r\n``Linear\\quad \\Rightarrow y=mx+b\\\\ Exponential\\quad \\Rightarrow y=b{ e }^{ mx }\\\\ Power\\quad \\Rightarrow y=b{ x }^{ m }``\r\n\r\nThe next table show the list of variables allowed:\r\n\r\n|PropertyName|Args|Default|Input|Description\r\n|---|---|---|---|---|\r\n|x|Mandatory|--|Array{Number,1}| x Data|\r\n|y|Mandatory|--|Array{Number,1}| y Data|\r\n|TypeReg|Optional|TypeReg=\"Linear\"|TypeReg= \"linear\" or \"Exponential\" or \"Power\"|Type of regression|\r\n|pr|Optional|pr=false|pr=Bool|Print the results of regression|\r\n```\r\nfunction Reg(x,y; TypeReg=\"Linear\", pr=false)\r\n\r\n if TypeReg==\"Linear\"\r\n m=(mean(x)*mean(y)-mean(x.*y))/(mean(x)^2-mean(x.^2))\r\n b=mean(y)-m*mean(x)\r\n SELine=sum(map((X,Y)->((X*m+b)-Y)^2,x,y))\r\n SEYmean=sum(map(Y->(Y-mean(y))^2,y))\r\n R2=1-(SELine/SEYmean)\r\n\r\n pr ? println(\" **Linear Regression \\n form y = mx+b \\n m=$m \\n b=$b \\n r2=$R2\") : :none\r\n return m,b,R2\r\n elseif TypeReg==\"Exponential\"\r\n m=(mean(x)*mean(log.(y))-mean(x.*log.(y) ) )/(mean(x)^2-mean(x.^2))\r\n Logb=mean(log.(y))-m*mean(x)\r\n b=exp(Logb)\r\n SELine=sum(map((X,Y)->((X*m+Logb)-Y)^2,x,log.(y)))\r\n SEYmean=sum(map(Y->(Y-mean(log.(y)))^2,log.(y)))\r\n R2=1-(SELine/SEYmean)\r\n\r\n pr ? println(\" **Exponential Regression \\n form y = b*exp(mx) \\n m=$m \\n b=$b \\n r2=$R2\") : :none\r\n return m, b,R2\r\n elseif TypeReg==\"Power\"\r\n m=(mean(log.(x))*mean(log.(y))-mean(log.(x).*log.(y) ) )/(mean(log.(x))^2-mean(log.(x).^2))\r\n Logb=mean(log.(y))-m*mean(log.(x))\r\n b=exp(Logb)\r\n SELine=sum(map((X,Y)->((X*m+Logb)-Y)^2,log.(x),log.(y)))\r\n SEYmean=sum(map(Y->(Y-mean(log.(y)))^2,log.(y)))\r\n R2=1-(SELine/SEYmean)\r\n\r\n pr ? println(\" **Power Regression \\n form y = b x^(m) \\n m=$m \\n b=$b \\n r2=$R2\") : :none\r\n return m, b,R2\r\n end\r\n\r\nend\r\n", "meta": {"hexsha": "e4a210f2c4cf9394fc625668adbc8fb823d07a59", "size": 1951, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Reg.jl", "max_stars_repo_name": "scuervo91/WellLogs.jl", "max_stars_repo_head_hexsha": "bc691fdd0500414b4f78172f905ca81930364f8c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-05-23T12:19:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T21:34:04.000Z", "max_issues_repo_path": "src/Reg.jl", "max_issues_repo_name": "scuervo91/WellLogs.jl", "max_issues_repo_head_hexsha": "bc691fdd0500414b4f78172f905ca81930364f8c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-06-21T23:04:55.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-25T15:37:20.000Z", "max_forks_repo_path": "src/Reg.jl", "max_forks_repo_name": "scuervo91/WellLogs.jl", "max_forks_repo_head_hexsha": "bc691fdd0500414b4f78172f905ca81930364f8c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-06-21T22:50:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T18:28:16.000Z", "avg_line_length": 39.02, "max_line_length": 122, "alphanum_fraction": 0.5422860072, "num_tokens": 672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660949832346, "lm_q2_score": 0.8856314647623016, "lm_q1q2_score": 0.844862390033575}} {"text": "### A Pluto.jl notebook ###\n# v0.18.4\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n quote\n local iv = try Base.loaded_modules[Base.PkgId(Base.UUID(\"6e696c72-6542-2067-7265-42206c756150\"), \"AbstractPlutoDingetjes\")].Bonds.initial_value catch; b -> missing; end\n local el = $(esc(element))\n global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el)\n el\n end\nend\n\n# ╔═╡ cf07621a-9a65-11ec-1fc0-51fbadbb086f\nusing Pkg; Pkg.activate()\n\n# ╔═╡ 345a90f7-f8ac-43b2-b5bd-0282d9447556\nbegin\n\tusing DifferentialEquations\n\tusing ModelingToolkit\n\tusing DynamicalSystems\n\tusing ForwardDiff\n\tusing LinearAlgebra\n\tusing Graphs\n\tusing Plots\n\tusing PlutoUI\n\tusing LaTeXStrings\nend\n\n# ╔═╡ eaf9dda2-d898-4771-9f86-ca4be174712c\nmd\"\"\"\n# Dynamical Systems in Julia\nIn this tutorial, we'll looking at specifying, simulating and analyzing dynamical systems in Julia. This is one area where Julia especially shines, thanks in no small part to the `DifferentialEquations` package, which pretty much provides the largest and fastest suite of ODE solvers on the market today.\n\"\"\"\n\n# ╔═╡ eb6aed5a-0f95-4a76-8a99-b8719984bbe5\nmd\"## Defining systems symbolically\"\n\n# ╔═╡ 0e28ede5-0af6-49a7-b95d-7094e320eee4\nmd\"\"\"\nWe'll start by using ModelingToolkit to define the famous Lorenz system. The process starts by a symbolic description of the problem.\n\"\"\"\n\n# ╔═╡ 6ccfc87f-40e7-4ee4-baae-ee41b81efe67\nbegin\n\t@parameters t σ ρ β\n\t@variables x(t) y(t) z(t)\n\tD = Differential(t)\n\n\teqs = [\n\t\tD(x) ~ σ*(y-x),\n \tD(y) ~ x*(ρ-z)-y,\n \tD(z) ~ x*y - β*z\n\t]\n\n\t@named lorenz = ODESystem(eqs)\nend\n\n# ╔═╡ 3e4ec586-482f-4c1b-a8e7-4ae88e48fa38\nmd\"\"\"\nSo far, the `lorenz` is purely symbolic, which has the added benefit of being able to render the equations in LaTeX as above! The next step before simulating it is defining values for our initial condition and parameters.\n\"\"\"\n\n# ╔═╡ ce0b65b5-e57a-4def-acb6-892c49f182d9\nbegin\n\tu0 = [\n\t\tx => 0.0,\n \ty => 0.5,\n \tz => 0.5\n\t]\n\n\tp = [\n\t\tρ => 28.0,\n \tσ => 10.0,\n \tβ => 8/3\n\t]\nend\n\n# ╔═╡ 1a7e8273-8069-42a8-ab7b-62f5fe1ade67\nmd\"\"\"\nSimulating our system is a two step process. After defining our timespan of integration, we first create an `ODEProblem`, we describes an ODE + initial conditions and parameters, and then pass it to the `solve` function to compute the solution of our problem. The second argument to solve is the solver we want to use (`Tsit5` is a 4-5 order Runge-Kutta scheme which is generally a good default choice for non-stiff problems)\n\"\"\"\n\n# ╔═╡ 1d77a2be-773c-4edd-9d68-1ed84fb5dadf\nbegin\n\ttspan = (0.0,100.0)\n\tprob = ODEProblem(lorenz,u0,tspan,p,jac=true)\n\tsol = solve(prob,Tsit5())\nend\n\n# ╔═╡ 7c712f73-3931-4cf4-82d8-9d9e2263df14\nplot(sol, vars=(x,y,z))\n\n# ╔═╡ 432fa70e-9225-4e76-aec3-c27d31887fb9\nmd\"\"\"\nNB. There are also packages for modeling specific classes of dynamical systems, such as `Catalyst` for chemical reaction networks, or `PowerDynamics` for power grids.\n\"\"\"\n\n# ╔═╡ 60063cc3-e71f-461b-be0a-491b1b566718\nmd\"## Defining Systems by hand\"\n\n# ╔═╡ ea2eeac2-5514-4fe8-8921-6235cdb0d1ad\nmd\"\"\"\nWhile defining systems symbolically is cool, this can be tedious for large systems, and sometimes you just want full control over how your ODE function is defined. To that end, we will now define another famous system, the Brusselator by hand and then build a network reaction diffusion system with it.\n\nThe Brusselator equations are as follows,\n```math\n\\begin{align*}\n\\dot{x} &= a + x^2y -bx -x \\\\\n\\dot{y} &= bx - x^2y\n\\end{align*}\n```\n\"\"\"\n\n# ╔═╡ 2bf13604-71c6-474f-90de-5b270c5c0708\nmd\"\"\"\nWe can construct ODEProblems by providing a function that computes the derivative, just like we do in Matlab. The functions we can use come in two flavours. The first type just takes as input the state `u`, parameters stored in `p` and time `t` (for non autonomous systems), and returns the new state.\n\"\"\"\n\n# ╔═╡ 743b31cd-6b2a-472c-8a70-a3955a2c26b6\nfunction brusselator(u, p, t)\n\ta, b = p\n\t[\n\t\ta + u[1]^2 * u[2] - b*u[1] - u[1],\n\t\tb*u[1] - u[1]^2 * u[2]\n\t]\nend\n\n# ╔═╡ 03bd6ff6-107f-4b04-9cb8-fe5c28570e58\nmd\"\"\"\nHowever, it is always recommended to use the second form, which also takes as input a preallocated array for the output and modifies it. Doing this is more efficient in terms of memory allocation, which is actually an important source of slowdowns.\n\"\"\"\n\n# ╔═╡ 08fc4616-d2af-471b-adc0-195bb566334f\nfunction brusselator!(du, u, p, t)\n\ta, b = p\n\tdu[1] = a + u[1]^2 * u[2] - b*u[1] - u[1]\n\tdu[2] = b*u[1] - u[1]^2 * u[2]\nend\n\n# ╔═╡ d0c1e91e-d1df-4a12-a0e2-8513eeee7ba6\nbegin\n\tu0_b = [1.0, 1.0]\n\tp_b = [1.0, 3.0]\nend\n\n# ╔═╡ 8623c9b7-5724-4678-9b53-4312389a276d\nbegin\n\tprob_b = ODEProblem(brusselator!, u0_b, (0.0, 50.0), p_b)\n\tsol_b = solve(prob_b, Tsit5())\nend\n\n# ╔═╡ da0220ea-99aa-4a0d-8826-f0e461fd503e\nplot(sol_b)\n\n# ╔═╡ 60d1ea9b-b935-4e88-9e92-07497f06aeaa\nmd\"\"\"\nNow that we have our brusselator function, let's use it on a network to make a reaction diffusion system. Such a system is of the form\n\n```math\n\\dot{u_i} = f(u_i) + D \\sum_{j=1}^N A_{ij}(u_j - u_i),\n```\nwhere ``u_i\\in\\mathbb{R}^m`` is the state of node ``i``, subject to local dynamics ``f:\\mathbb{R}^m\\rightarrow \\mathbb{R}^m``, ``A\\in\\mathbb{R}^{N\\times N}`` is the adjacency matrix of the graph (i.e. ``A_{ij}=1`` iff there is a link between nodes ``i`` and ``j``), and ``D`` is a diagonal matrix of diffusion coefficients.\n\nWe can rewrite this system in vector form (glossing over some details) as\n\n```math\n\\dot{\\mathbf{u}} = F(\\mathbf{u}) + \\mathbf{D} L \\mathbf{u},\n```\nwhere ``L`` is the *Laplacian matrix* of the graph.\n\nReaction-Diffusion systems can take more general forms, but we'll stick to this one for today.\n\"\"\"\n\n# ╔═╡ efbb46be-c442-4ab3-85a0-b10cbc3a2a9e\nmd\"\"\"\nNow, we need to create a function for our reaction-diffusion system.\n\"\"\"\n\n# ╔═╡ 8b2ec98a-b37f-4bd0-9fc8-9f3dcf9550c9\nfunction brusselator_rd(u, p, t)\n\ta, b, L, D = p\n\tdu = similar(u) # creates an array of same shape and element type as u\n\tfor i in 1:size(du, 1)\n\t\tdu[i,:] .= brusselator(u[i,:], [a, b], t)\n\tend\n\tdu[:,1] .-= D[1] .* (L*u[:,1])\n\tdu[:,2] .-= D[2] .* (L*u[:,2])\n\treturn du\nend\n\n# ╔═╡ 25c22a1f-6ae4-4b72-8e4c-de844e2699d1\nfunction brusselator_rd!(du, u, p, t)\n\t# NB. the commented out parts should be equivalent to what is used, but for some reason it is not\n\ta, b, L, D = p\n\tdu .= 0.0\n\tfor i in 1:size(du, 1)\n\t\t#brusselator!(du[i,:], u[i,:], [a, b], t)\n\t\tdu[i,:] .+= brusselator(u[i,:], [a, b], t)\n\tend\n\t#mul!(du[:,1], L, u[:,1], -D[1], 0.0) # du[:,1] .+= D[1]*L*u[:,1]\n\t#mul!(du[:,2], L, u[:,2], -D[2], 0.0)\n\tdu[:,1] .-= D[1] .* (L*u[:,1])\n\tdu[:,2] .-= D[2] .* (L*u[:,2])\nend\n\n# ╔═╡ 582b74c7-aaf6-4a8e-901f-489199ccc0d6\nmd\"\"\"\nNow, we need a network to run our system on. To do this, we can use the `Graphs` package.\n\"\"\"\n\n# ╔═╡ 3e575a45-50d6-4297-84e5-6699e36d00dd\ng = erdos_renyi(10, 0.4)\n\n# ╔═╡ ed1de34a-a42e-474d-ba36-411163a343f8\nmd\"\"\"\nWe can use the function `laplacian_matrix` to get the Laplacian matrix of the graph. The nice thing about this function is that it returns a sparse matrix, which uses optimized methods for matrix multiplications.\n\"\"\"\n\n# ╔═╡ 947c169c-a900-4728-ad29-5200b52f9599\nlaplacian_matrix(g)\n\n# ╔═╡ 04bbc594-17c9-4b41-a599-d41e2e541c9f\nbegin\n\tu_rd_0 = 5*rand(nv(g), 2)\nend\n\n# ╔═╡ 29a0f8c8-5529-496c-99f1-b436d15f2517\nmd\"\"\"\nHere's a nice feature of Pluto. It provides allows interactively modifying variables with html elements (sliders, buttons, ...) via the `PlutoUI` package.\n\nLet's use it to make sliders for the parameters of our system.\n\"\"\"\n\n# ╔═╡ f346a0b3-4d1d-49ad-94ec-cc42ee75a05b\nmd\"\"\"\na: $(@bind a Slider(0.0:0.01:5.0, default=1.0, show_value=true))\n\nb: $(@bind b Slider(0.0:0.01:5.0, default=3.0, show_value=true))\n\nD₁: $(@bind D_1 Slider(0.0:0.01:10.0, default=1.0, show_value=true))\n\nD₂ $(@bind D_2 Slider(0.0:0.01:10.0, default=1.0, show_value=true))\n\"\"\"\n\n# ╔═╡ 8a1c55e5-1008-44ee-b853-c53c2dbf3bb2\np_rd = [a, b, laplacian_matrix(g), [D_1, D_2]];\n\n# ╔═╡ 2ee789c5-ae38-4e85-95e1-920a580df058\nbegin\n\tprob_rd = ODEProblem(brusselator_rd!, u_rd_0, (0.0, 50.0), p_rd)\n\tsol_rd = solve(prob_rd, Tsit5())\n\tnothing\nend\n\n# ╔═╡ 9d1f3408-e0f5-4093-bb6b-862485e99476\nbegin\n\tlocal p1 = plot(sol_rd, vars=(0,1:nv(g)), label=\"\", ylabel=L\"x_i\")\n\tlocal p2 = plot(sol_rd, vars=(0,(nv(g)+1:2nv(g))), label=\"\", ylabel=L\"y_i\")\n\tplot(p1, p2)\nend\n\n# ╔═╡ a4d4a26f-ff25-4bf0-b8ab-2db56131ee3e\nmd\"\"\"\n### Exercise\nImplement your favourite dynamical system and play around with it's parameters.\n\"\"\"\n\n# ╔═╡ 91f1ce37-0d68-4ed2-9359-dbcfd06f6cdd\nmd\"\"\"\n## Intermezzo: using `DynamicalSystems` to study chaotic Systems\n\nBefore moving to the last part of this tutorial, let us make a detour to look at the `DynamicalSystems` package, which provides a library of famous dynamical systems, as well as generic tools for ananlyzing them, particularly chaotic systems. \n\"\"\"\n\n# ╔═╡ 4328e814-82a8-4e7d-8b8a-44a9d5ba17c5\nds = Systems.logistic()\n\n# ╔═╡ 7b11ac9b-a470-4059-bbad-ba6bc443c68b\nmd\"\"\"\nHere we load the well known logistic map from the library of dynamical systems, and generate its orbit diagram for varying values of the `r` parameter. The magic function is `orbitdiagram`, which should work for pretty much any discrete map.\n\"\"\"\n\n# ╔═╡ a5629c28-53bf-4b19-a49f-ab26df1d1b46\nbegin\n\ti = 1\n\tpvalues = 1:0.005:4\n ics = [rand() for m in 1:10]\n n = 2000\n Ttr = 2000\n p_index = 1\n\t\n output = orbitdiagram(ds, i, p_index, pvalues; n = n, Ttr = Ttr)\nend\n\n# ╔═╡ 74adb98a-1ad5-4181-a3be-ec5fe2565a35\nbegin\n\tlocal L = length(pvalues)\n\tlocal x = Vector{Float64}(undef, n*L)\n\tlocal y = copy(x)\n\tfor j in 1:L\n \tx[(1 + (j-1)*n):j*n] .= pvalues[j]\n \t\ty[(1 + (j-1)*n):j*n] .= output[j]\n\tend\n\tscatter(x,y,\n\t\txlabel=\"r\",\n\t\tylabel=\"x\",\n\t\tlabel=\"\",\n\t\tmarkersize=0.8,\n\t\tcolor=:black,\n\t\tmarkeralpha=0.05,\n\t\tmarkerstrokealpha=0.0\n\t)\nend\n\n# ╔═╡ c38e202f-a2d2-4449-8308-df22774b7af1\nmd\"\"\"\nNB. While `DynamicalSystems` provides a bunch of cool tools, a lot of them seem to inexplicably break when used outside of the examples. For example, try changing the above code to use values of `r` above 4.\n\"\"\"\n\n# ╔═╡ d5ab9847-ace4-4a5b-8c81-d2eb8b56c896\nmd\"\"\"\n## Analyzing the stability of our system\n\nReaction-Diffusion systems like the one we just saw are interesting because of their asymptotic behaviour. Because the laplacian always has a zero eigenvalue associated to an eigenvector whose entries are all the same, a reaction-diffusion system always admits a homogeneous solution where the nodes are all synchronised.\nBy tuning the diffusion coefficients, it's possible to (de)synchronize the states of the nodes.\n\nThe standard tool for analysing this phenomenon is the Master Stability Function [Pecora-Caroll. 1998].\n\nThe main idea consists in expressing the system in the basis of eigenvectors of the laplacian matrix. By considering a small perturbation around the synchronized solution, and expressing its linearized equations in the eigenbasis of ``L``, one can obtain a set of decoupled equations involving the laplacian eigenvalues and the jacobian of the local dynamics.\n\nSkipping over the details, we can check that the synchronized solution is linearly stable by checking that the following ODE is stable for every eigenvalue ``\\lambda`` of the laplacian matrix\n\n```math\n\\dot{\\xi} = [\\mathcal{J}f(u_*) - \\lambda D] \\xi\n```\nwhere ``\\mathcal{J}f`` denotes the jacobian of ``f``.\n\nThis can be done, for example, by computing the Lyapunov exponent of this equation, thereby yielding a function ``MSF(\\lambda)`` called the *Master Stability Function* of the system.\n\"\"\"\n\n# ╔═╡ 575e3106-704e-4bea-8155-7ee6e6c9da5d\nmd\"First, let's compute the eigenvalues of the laplacian matrix. We don't actually need to compute the eigenvectors.\"\n\n# ╔═╡ bff34b78-f7ad-452e-9b95-a498f3e377f5\nλ = laplacian_spectrum(g)\n\n# ╔═╡ bba5eaa1-16f2-401d-8cf3-f05e9761583d\nmd\"\"\"\nNext, let's start by writing a function that takes the local dynamics as input, and generates a function for the MSF ODE.\n\nNotice the use, of `ForwardDiff.jacobian` to automagically compute the Jacobian matrix using Automatic Differentiation (this is different from Finite Differences or Symbolic methods)\n\"\"\"\n\n# ╔═╡ ddbb84d1-945a-4184-850b-31ee3540e960\nfunction msf_ode_fun(f)\n\tfunction msf_ode!(du, u, p, t)\n\t\tp_f, D, λ = p\n\t\tdu[:,1] .= f(u[:,1], p_f, t)\n\t\tJ = ForwardDiff.jacobian(x -> f(x,p_f,t), u[:,1])\n\t\tdu[:,2] .= J*u[:,2] - λ*D*u[:,2]\n\tend\n\treturn msf_ode!\nend\n\n# ╔═╡ f0215a78-146d-4009-ae73-8a2f35072db9\nmd\"\"\"\nNow, we can move on to computing the MSF proper. To do this, we solve the MSF ODE, then estimating the Lyapunov exponent from the time series.\n\nNB. Recall that the Lyapunov exponent for a dynamical sytem is defined by\n```math\n\\lambda = \\lim_{t\\rightarrow \\infty} \\lim_{\\xi_0 \\rightarrow 0} \\frac{1}{t} \\ln \\frac{\\|\\xi(t)\\|}{\\|\\xi_0\\|},\n```\nwhere ``\\xi(0) = \\xi_0`` is a small perturbation applied to the orbit of interest (here, the periodic solution).\n\"\"\"\n\n# ╔═╡ 84d86795-e2c4-4c2c-888b-ae999bcda2dd\nfunction master_stability_function(f, u_0, p_f, D, t; δ=0.1, k=50, Δt=0.1)\n\tmsf_ode! = msf_ode_fun(f)\n\tn = length(u_0)\n\tu_msf_0 = hcat(u_0, δ*randn(n))\n\tfunction msf(λ; u_msf_0=u_msf_0, p_f=p_f, D=D, t=t, Δt=Δt)\n\t\tp_msf = [p_f, D, λ]\n\t\tprob = ODEProblem(msf_ode!, u_msf_0, (0.0,t), p_msf)\n\t\tsol = solve(prob, Tsit5(), saveat=0.0:Δt:t, abstol=1e-10, reltol=1e-10)\n\t\tξ_0 = norm(sol.u[1][:,2])\n\t\tl = length(sol.u)\n\t\tξ_t = norm([sol.u[k][:,2] for k in l-k:l])\n\t\treturn log(ξ_t/ξ_0)/sol.t[end]\n\tend\n\treturn msf\nend\n\n# ╔═╡ 8c592351-4da7-4bed-a99c-595156c1ed8b\nbegin\n\tu0_msf = sol_b.u[end]\n\tp_f = [1.0, 3.0]\n\tD_msf = Diagonal([0.2,5.0])\nend\n\n# ╔═╡ e3411cdb-acf7-40da-9f5e-6852c1370797\nmsf = master_stability_function(brusselator, u0_msf, p_f, D_msf, 200.0)\n\n# ╔═╡ 5fbfe4aa-f2e5-4845-92e7-9de00063059f\nmsf(0.0)\n\n# ╔═╡ ffecadd1-95b5-412f-86e4-e4dee733cab1\nmd\"\"\"\nNote that this implementation is not super fast, as it takes about a minute to run the next cell. There's lots of room for improvements though, and in the mean time, we still have a generic funcion for computing the MSF.\n\"\"\"\n\n# ╔═╡ bad93338-72e3-46fc-888f-e507c62cefc6\nbegin\n\tlocal λs = 0.0:0.01:7.0\n\tplot(λs, msf.(λs), \n\t\tlabel=\"\",\n\t\txlabel=\"-Re λ\"\n\t)\n\t#plot!(λs, msf_ds.(λs), label=\"ds\")\n\tplot!([0.0,7.0],[0.0,0.0], linestyle=:dash, label=\"\", color=:black)\n\tscatter!(λ, msf.(λ), label=\"\")\nend\n\n# ╔═╡ 63c14c9e-808e-464b-b5cc-25921aa34f56\nmd\"\"\"\nBelow, we examine the trajectory of the MSF equations for λ = 0. Note that this is quite ill-behaved (notice the log scale), so it's no wonder this is tricky to get right.\n\"\"\"\n\n# ╔═╡ 8f8a9dec-4de2-4fc7-9d87-a3638ec47ee3\nbegin\n\tf! = msf_ode_fun(brusselator)\n\tu0_ = hcat(u0_msf, 0.1*randn(2))\n\tp_msf = [p_f, D_msf, 0.0]\n\tprob_msf = ODEProblem(f!, u0_, (0.0,100.0), p_msf)\n\tsol_msf = solve(prob_msf, Rodas5(), abstol=1e-10, reltol=1e-10)\nend\n\n# ╔═╡ e85b9b6d-736d-446a-acb1-b6ed0ccdd907\nbegin\n\tlocal foo = (t,u,v) -> (t,norm([u;v]))\n\tplot(sol_msf, vars=(foo,0,3,4), \n\t\tyscale=:log10, \n\t\tlabel=\"\", \n\t\tylabel=L\"\\ln \\|\\xi\\|\"\n\t)\nend\n\n# ╔═╡ Cell order:\n# ╟─eaf9dda2-d898-4771-9f86-ca4be174712c\n# ╠═cf07621a-9a65-11ec-1fc0-51fbadbb086f\n# ╠═345a90f7-f8ac-43b2-b5bd-0282d9447556\n# ╟─eb6aed5a-0f95-4a76-8a99-b8719984bbe5\n# ╟─0e28ede5-0af6-49a7-b95d-7094e320eee4\n# ╠═6ccfc87f-40e7-4ee4-baae-ee41b81efe67\n# ╟─3e4ec586-482f-4c1b-a8e7-4ae88e48fa38\n# ╠═ce0b65b5-e57a-4def-acb6-892c49f182d9\n# ╟─1a7e8273-8069-42a8-ab7b-62f5fe1ade67\n# ╠═1d77a2be-773c-4edd-9d68-1ed84fb5dadf\n# ╠═7c712f73-3931-4cf4-82d8-9d9e2263df14\n# ╟─432fa70e-9225-4e76-aec3-c27d31887fb9\n# ╟─60063cc3-e71f-461b-be0a-491b1b566718\n# ╟─ea2eeac2-5514-4fe8-8921-6235cdb0d1ad\n# ╟─2bf13604-71c6-474f-90de-5b270c5c0708\n# ╠═743b31cd-6b2a-472c-8a70-a3955a2c26b6\n# ╟─03bd6ff6-107f-4b04-9cb8-fe5c28570e58\n# ╠═08fc4616-d2af-471b-adc0-195bb566334f\n# ╠═d0c1e91e-d1df-4a12-a0e2-8513eeee7ba6\n# ╠═8623c9b7-5724-4678-9b53-4312389a276d\n# ╠═da0220ea-99aa-4a0d-8826-f0e461fd503e\n# ╟─60d1ea9b-b935-4e88-9e92-07497f06aeaa\n# ╟─efbb46be-c442-4ab3-85a0-b10cbc3a2a9e\n# ╠═8b2ec98a-b37f-4bd0-9fc8-9f3dcf9550c9\n# ╠═25c22a1f-6ae4-4b72-8e4c-de844e2699d1\n# ╟─582b74c7-aaf6-4a8e-901f-489199ccc0d6\n# ╠═3e575a45-50d6-4297-84e5-6699e36d00dd\n# ╟─ed1de34a-a42e-474d-ba36-411163a343f8\n# ╠═947c169c-a900-4728-ad29-5200b52f9599\n# ╠═04bbc594-17c9-4b41-a599-d41e2e541c9f\n# ╟─29a0f8c8-5529-496c-99f1-b436d15f2517\n# ╟─f346a0b3-4d1d-49ad-94ec-cc42ee75a05b\n# ╠═8a1c55e5-1008-44ee-b853-c53c2dbf3bb2\n# ╠═2ee789c5-ae38-4e85-95e1-920a580df058\n# ╠═9d1f3408-e0f5-4093-bb6b-862485e99476\n# ╟─a4d4a26f-ff25-4bf0-b8ab-2db56131ee3e\n# ╟─91f1ce37-0d68-4ed2-9359-dbcfd06f6cdd\n# ╠═4328e814-82a8-4e7d-8b8a-44a9d5ba17c5\n# ╟─7b11ac9b-a470-4059-bbad-ba6bc443c68b\n# ╠═a5629c28-53bf-4b19-a49f-ab26df1d1b46\n# ╠═74adb98a-1ad5-4181-a3be-ec5fe2565a35\n# ╟─c38e202f-a2d2-4449-8308-df22774b7af1\n# ╟─d5ab9847-ace4-4a5b-8c81-d2eb8b56c896\n# ╟─575e3106-704e-4bea-8155-7ee6e6c9da5d\n# ╠═bff34b78-f7ad-452e-9b95-a498f3e377f5\n# ╟─bba5eaa1-16f2-401d-8cf3-f05e9761583d\n# ╠═ddbb84d1-945a-4184-850b-31ee3540e960\n# ╟─f0215a78-146d-4009-ae73-8a2f35072db9\n# ╠═84d86795-e2c4-4c2c-888b-ae999bcda2dd\n# ╠═8c592351-4da7-4bed-a99c-595156c1ed8b\n# ╠═e3411cdb-acf7-40da-9f5e-6852c1370797\n# ╠═5fbfe4aa-f2e5-4845-92e7-9de00063059f\n# ╟─ffecadd1-95b5-412f-86e4-e4dee733cab1\n# ╠═bad93338-72e3-46fc-888f-e507c62cefc6\n# ╟─63c14c9e-808e-464b-b5cc-25921aa34f56\n# ╠═8f8a9dec-4de2-4fc7-9d87-a3638ec47ee3\n# ╠═e85b9b6d-736d-446a-acb1-b6ed0ccdd907\n", "meta": {"hexsha": "b31533b1790e50dcaf7adb3fc1498860712b5b42", "size": 17529, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebook.jl", "max_stars_repo_name": "csimal/Julia-for-Dynamical-Systems", "max_stars_repo_head_hexsha": "6fe31fdfc023c607037a173bacdb6f46b4536ccc", "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": "notebook.jl", "max_issues_repo_name": "csimal/Julia-for-Dynamical-Systems", "max_issues_repo_head_hexsha": "6fe31fdfc023c607037a173bacdb6f46b4536ccc", "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": "notebook.jl", "max_forks_repo_name": "csimal/Julia-for-Dynamical-Systems", "max_forks_repo_head_hexsha": "6fe31fdfc023c607037a173bacdb6f46b4536ccc", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4381139489, "max_line_length": 425, "alphanum_fraction": 0.7072850705, "num_tokens": 7426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172630429475, "lm_q2_score": 0.8902942261220292, "lm_q1q2_score": 0.844815560354655}} {"text": "module Donquicote\n\nusing PrettyTables, Statistics, StatsBase, ForwardDiff\n\nD(f) = x -> ForwardDiff.derivative(f,float(x))\n\nfunction newton(f, ∂f, x0; xatol = 1e-7)\n\n diff = 1\n while diff >= xatol\n x1 = x0 - f(x0) / ∂f(x0);\n diff = abs(x1 - x0);\n x0 = x1;\n end\n return x0\nend\n\nfunction haley(f, ∂f, ∂2f, x0; xatol = 1e-7)\n diff = 1\n while diff >= xatol\n x1 = x0 - (2*f(x0)*∂f(x0)) / (2*∂f(x0)^2 - f(x0)*∂2f(x0));\n diff = abs(x1 - x0);\n x0 = x1;\n end\n return x0\n\nend\n\nfunction schroeder(f, ∂f, ∂2f, x0; xatol = 1e-7)\n diff = 1\n while diff >= xatol\n x1 = x0 - f(x0) / ∂f(x0) - (∂2f(x0)*f(x0)^2)/(2*∂f(x0)^3);\n diff = abs(x1 - x0);\n x0 = x1;\n end\n return x0\n\nend\n\nfunction weightedmean(x, w)\n wxsum = wsum = 0\n for (x,w) in zip(x,w)\n wx = w*x\n if !ismissing(wx) | isfinite(wx)\n wxsum += wx\n wsum += w\n end\n end\n return wxsum / wsum\nend\n\nfunction weightedstd(x, w)\n μ = weightedmean(x, w)\n wxsum = wsum = 0\n for (x,w) in zip(x,w)\n wx = w*(x - μ)^2\n if !ismissing(wx) | isfinite(wx)\n wxsum += wx\n wsum += w\n end\n end\n σ = sqrt((1/wsum)*wxsum)\n return σ\nend\n\nfunction gini(x::Vector{Float64})\n n = length(x)\n sarray = sort(x)\n return 2*(sum(collect(1:n).*sarray))/(n*sum(sarray))-1\nend\n\nlogm(x) = x > 0.0 ? log(x) : missing\n\nlvar(x) = var(logm.(x))\n\nnanmean(x) = mean(filter(!isnan,x))\n\nformat(x) = round(x, digits = 3)\n\nfunction savehtml(filename, data)\n open(\"$filename.html\", \"w\") do f\n pretty_table(f, data, backend = :html)\n end\nend\n\nexport newton, haley, schroeder\nexport gini, nanmean, weightedmean, weightedstd, format, logm, lvar\nexport ones, zeros\nexport savehtml\n\nend", "meta": {"hexsha": "85844cf5869d44d39f64cb39d0bedcab4288a7c1", "size": 1809, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Donquicote.jl", "max_stars_repo_name": "Donquicote/donquicote.jl", "max_stars_repo_head_hexsha": "6b1d7b18f8676a80341288fd43d6805ecfcd0678", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Donquicote.jl", "max_issues_repo_name": "Donquicote/donquicote.jl", "max_issues_repo_head_hexsha": "6b1d7b18f8676a80341288fd43d6805ecfcd0678", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Donquicote.jl", "max_forks_repo_name": "Donquicote/donquicote.jl", "max_forks_repo_head_hexsha": "6b1d7b18f8676a80341288fd43d6805ecfcd0678", "max_forks_repo_licenses": ["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.8791208791, "max_line_length": 67, "alphanum_fraction": 0.535655058, "num_tokens": 683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240142763573, "lm_q2_score": 0.9005297807787537, "lm_q1q2_score": 0.8448086129195724}} {"text": "using NumericalMethodsforEngineers\n\n#=\n@sym begin\n LagrangePolynomial(xi_, yi_) := Module([N, sum, num, den],\n begin\n N = Length(xi)\n sum = 0\n For( i=1, i <= N, Increment(i),\n begin\n num = 1\n den = 1\n For( j=1, j <= N, Increment(j),\n begin\n If(j != i, num *= (x-xi[j]))\n If(j != i, den *= (xi[i]-xi[j]))\n end\n )\n sum += yi[i] * num/den\n end\n ),\n Return(Simplify(sum))\n end\n )\nend\n=#\n\nprintln(\"\\n\\n--------1------------\\n\")\n\n@sym begin\n ClearAll(xi, yi, Y, R, sol, ytilde)\n xi = [0, 1//2, 1]\n yi = [0, a, 1]\n Y(x_) := LagrangePolynomial(xi, yi)\n Println(Y(x))\nend\n\nprintln(\"\\n---------2-----------\\n\")\n\n@sym begin\n ClearAll(xi, yi, Y1, R, sol, ytilde)\n Y1(x_) := x^3 -3x^2 +6x - 9\n R(x_) = Simplify(D(Y1(x), x, 2))\n Println(R(x))\nend\n\nprintln(\"\\n----------3----------\\n\")\n\n@sym begin\n ClearAll(xi, yi, Y, R, sol, ytilde)\n xi = [0, 1//2, 1]\n yi = [0, a, 1]\n Y(x_) := LagrangePolynomial(xi, yi)\n R(x_) = Simplify(D(Y(x), x, 2) - 3*x - 4*Y(x))\n R(x_) = Simplify(R(x) ./ (a => -C1/4))\n Println(R(x))\n SetJ(r, ToString(Simplify(R(x))))\nend\n\nprintln(\"\\n----------4----------\\n\")\n\nprintln(r)\n\nprintln(\"\\n----------5----------\\n\")\n\nprintln(\"\\n\\nExample 7.14: y'' = 3x + 4y, y(0)=0, y(1)=1\")\nprintln(\"Residual for Weighted Residual Method using 2 point Lagragian Polynomial\")\n@sym Println(\"\\nY(x): \", Expand(Y(x)), \"\\n\")\nprintln(\"( Example 7.14 gives: ytilde = 1/2*x^3*(27a-27b+9)-x^2*(45a-36b+9)+x*(18a-9b+2) )\")\n@sym Println(\"\\nR(x) = \", R(x), \"\\n\")\n", "meta": {"hexsha": "1c0d40c13e3d755f5376d5fd6d14dda554aa540f", "size": 1599, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/wrm_with_using_nmfe.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/wrm_with_using_nmfe.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/wrm_with_using_nmfe.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.5211267606, "max_line_length": 92, "alphanum_fraction": 0.4752970607, "num_tokens": 608, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533069832973, "lm_q2_score": 0.9059898153067649, "lm_q1q2_score": 0.8447931993759797}} {"text": "### A Pluto.jl notebook ###\n# v0.12.10\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# ╔═╡ e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, Distributions, StatsPlots, Plots, Measures\n\tRandom.seed!(0)\n end\n\n# ╔═╡ ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing4.21\"\n\n# ╔═╡ fa68607e-22e5-11eb-0558-c9a4d9f77426\nbegin\n\tb1, b2 = 0.5 , 2\n\tdist1, dist2, = Beta(b1,b1), Beta(b2,b2)\n\n\tn = 2000\n\tdata1 = rand(dist1,n)\n\tdata2 = rand(dist2,n)\nend\n\n# ╔═╡ 65067674-250d-11eb-12ab-f7aeb1fb1a16\nbegin\n\tstephist(data1, bins=15, label = \"beta($b1,$b1)\", c = :red, normed = true)\n\tp1 = stephist!(data2, bins=15, label = \"beta($b2,$b2)\",\n\t\t\tc = :blue, xlabel=\"x\", ylabel=\"Density\",normed = true)\n\n\tp2 = qqplot(data1, data2, c=:black, ms=1, msw =0,\n\t\t\txlabel=\"Quantiles for beta($b1,$b1) sample\",\n\t\t\tylabel=\"Quantiles for beta($b2,$b2) sample\",\n\t\t\tlegend=false)\n\n\tplot(p1, p2, size=(800,400), margin = 5mm)\nend\n\n# ╔═╡ 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing4.21\"\n\n# ╔═╡ Cell order:\n# ╟─ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# ╠═e077ab16-22e5-11eb-15ed-5f0654bf7328\n# ╠═e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# ╠═fa68607e-22e5-11eb-0558-c9a4d9f77426\n# ╠═65067674-250d-11eb-12ab-f7aeb1fb1a16\n# ╟─475ff888-22e6-11eb-2354-09f8f40a8e12\n", "meta": {"hexsha": "07cda7ee7cd111f73af1ac6b697fd8db201fc777", "size": 1348, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/04/listing4.21.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/04/listing4.21.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/04/listing4.21.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 24.962962963, "max_line_length": 75, "alphanum_fraction": 0.6958456973, "num_tokens": 668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.942506716354847, "lm_q2_score": 0.8962513745192026, "lm_q1q2_score": 0.8447229400266117}} {"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#-\n\n## Run this cell to use a couple of definitions from the previous Tools notebook\n\nσ(x) = 1 / (1 + exp(-x))\nf(x, w) = σ(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 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 to add complexity to our model via additional parameters.\n\n#-\n\n# ## Adding more data\n\n#-\n\n# Suppose there are now two data points to fit, the previous $(x_0, y_0)$ used in notebook 6 and also $(x_1, y_1) = (-3, 0.3)$.\n\n#-\n\n# #### Exercise 1\n#\n# Make an interactive plot of the function $f_w$ together with the two data points. Can you make the graph of $f_w$ pass through *both* data points at the *same* time?\n\nx0, y0 = 2, 0.8\nx1, y1 = -3, 0.3\n\nw = 5.0 # try manipulating w between 0 and 10\nplot(x->f(x, w), -5, 5, ylim=(0,1))\nscatter!([x0, x1], [y0, y1])\n\n# You should have found that it's actually *impossible* to fit both data points at the same time! The best we could do is to *minimise* how far away the function is from the data. To do so, we need to somehow balance the distance from each of the two data points.\n\n#-\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\n#-\n\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#-\n\n# So now we want to find the value $w^*$ of $w$ that minimizes this new function $L$!\n\n#-\n\n# #### Exercise 3\n#\n# Make a visualization to show the function $f_w$ and to visualize the distance from each of the data points.\n\n#-\n\n# #### Solution\n\nxs = [2, -3]\nys = [0.8, 0.3]\n\nL(w) = sum( (ys .- f.(xs, w)) .^ 2 )\n\nw = 0.0 # 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))\")\n\nend\n\n# #### Exercise 4\n#\n# After playing with this for a while, it is intuitively obvious that we cannot make the function pass through both data points for any value of $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`? What is the corresponding value of `w`?\n\nw = 0.42\nplot(x->f(x, w), -5, 5, ylims=(0, 1), lw = 3, label=\"f_w\")\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\n#-\n\n# To generate the above plot we used the `sum` function. `sum` can add together all the elements of a collection or range, or it can add together the outputs of applying a function to all the 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#-\n\n# #### Exercise 5\n#\n# Use `sum` to add together all integers in the range 1 to 16, inclusive. What is the result?\n\n#-\n\n# #### Solution\n\nsum(1:16)\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#-\n\n# #### Solution\n\nsum(abs, -3:3)\n\n# ## What does the loss function $L$ look like?\n\n#-\n\n# In our last attempt to minimize `L(w)` by varying `w`, we saw that `L(w)` always seemed to be greater than 0. Is that true? Let's plot it to find out!\n\n#-\n\n# #### Exercise 7\n#\n# Plot the new loss function $L(w)$ as a function of $w$.\n\n#-\n\n# #### Solution\n\nplot(L, -2, 2, xlabel=\"w\", ylabel=\"L(w)\", ylims=(0, 1.2))\n\n# ### Features of the loss function\n\n#-\n\n# The first thing to notice is that $L$ is always positive. Since it is the sum of squares, and squares cannot be negative, the sum cannot be negative either!\n#\n# However, we also see that although $L$ dips close to $0$ for a single, special value $w^* \\simeq 0.4$, it never actually *reaches* 0! Again we could zoom in on that region of the graph to estimate it more precisely.\n\n#-\n\n# We might start suspecting that there should be a better way of using the computer to minimize $L$ to find the location $w^*$ of the minimum, rather than still doing everything by eye. Indeed there is, as we will see in the next two notebooks!\n\n#-\n\n# ## Adding more parameters to the model\n\n#-\n\n# If we add more parameters to a function, we may be able to improve how it fits to data. For example, we could define a new function $g$ with another parameter, a shift or **bias**:\n#\n# $$g(x; w, b) := \\sigma(w \\, x + b).$$\n\ng(x, w, b) = σ(w*x + b)\n\n# #### Exercise 8\n#\n# Make an interactive visualization that allows you to change $w$ and $b$. Play with the sliders to try and fit *both* data points at once!\n\n#-\n\n# #### Solution\n\nxs = [2, -3]\nys = [0.8, 0.3]\n\nL2D(w, b) = sum( (ys .- g.(xs, w, b)) .^ 2)\n\nw = 0.0 # Try manipulating w between -2 and 2\nb = 0.0 # 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\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 through both points simultaneously.\n\n#-\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\n# ## Fitting both data points: a loss function\n\n#-\n\n# Following the procedure that we used when we had a single parameter, we can think of the fitting procedure once again as minimizing a suitable *loss function*. The expression for the loss function is almost the same, except that now $f$ has two parameters $w$ and $b$, so the loss function $L_2$ is itself a function of $w$ *and* $b$:\n\n#-\n\n# $$L_2(w, b) = \\sum_i [y_i - f(x_i; w, b)]^2.$$\n\n#-\n\n# So we want to minimize this loss function over *both* of the parameters $w$ and $b$! Let's plot it.\n\n#-\n\n# #### Exercise 10\n#\n# Define the function `L2` in Julia.\n\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), we will make use of the `surface` function. To get a nice interactive 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 function $L_2$ attains its minimum. You can try different ranges for the $x$, $y$ and $z$ coordinates to get a better view.\n\n#-\n\n# ## More data\n\n#-\n\n# If we add more data, however, we will again not be able to fit all of the 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 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#-\n\n# #### Solution\n\ngr()\n\n#-\n\nL2(w, b) = sum( (ys .- g.(xs, w, b)) .^ 2)\n\nw = 0.0 # Try manipulating w between -2 and 2\nb = 0.0 # 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\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 it as a function of the parameters `w` and `b`.\n\n#-\n\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 `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\")\n\n", "meta": {"hexsha": "0f314110d166d3d5693b3d3ef8a76976ba8b4807", "size": 9533, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Courses/Foundations of machine learning/0700.Model-complexity-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/0700.Model-complexity-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/0700.Model-complexity-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": 26.9293785311, "max_line_length": 336, "alphanum_fraction": 0.6375747404, "num_tokens": 3131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391727723469, "lm_q2_score": 0.9149009549929797, "lm_q1q2_score": 0.8444894206653503}} {"text": "#Partitions\n\nexport\n integer_partitions,\n ncpartitions,\n partitions,\n prevprod\n #nextprod,\n\n\n#integer partitions\n\nstruct IntegerPartitions\n n::Int\nend\n\nBase.length(p::IntegerPartitions) = npartitions(p.n)\n\nfunction Base.iterate(p::IntegerPartitions, xs = Int[])\n length(xs) == p.n && return\n xs = nextpartition(p.n,xs)\n (xs, xs)\nend\n\n\"\"\"\n partitions(n)\n\nGenerate all integer arrays that sum to `n`. Because the number of partitions can be very\nlarge, this function returns an iterator object. Use `collect(partitions(n))` to get an\narray of all partitions. The number of partitions to generate can be efficiently computed\nusing `length(partitions(n))`.\n\"\"\"\npartitions(n::Integer) = IntegerPartitions(n)\n\n\n\nfunction nextpartition(n, as)\n isempty(as) && return Int[n]\n\n xs = similar(as, 0)\n sizehint!(xs, length(as) + 1)\n\n for i = 1:length(as)-1\n if as[i+1] == 1\n x = as[i]-1\n push!(xs, x)\n n -= x\n while n > x\n push!(xs, x)\n n -= x\n end\n push!(xs, n)\n\n return xs\n end\n push!(xs, as[i])\n n -= as[i]\n end\n push!(xs, as[end]-1)\n push!(xs, 1)\n\n xs\nend\n\nlet _npartitions = Dict{Int,Int}()\n global npartitions\n function npartitions(n::Int)\n if n < 0\n 0\n elseif n < 2\n 1\n elseif (np = get(_npartitions, n, 0)) > 0\n np\n else\n np = 0\n sgn = 1\n for k = 1:n\n np += sgn * (npartitions(n - (k*(3k-1)) >> 1) + npartitions(n - (k*(3k+1)) >> 1))\n sgn = -sgn\n end\n _npartitions[n] = np\n end\n end\nend\n\n# Algorithm H from TAoCP 7.2.1.4\n# Partition n into m parts\n# in colex order (lexicographic by reflected sequence)\n\nstruct FixedPartitions\n n::Int\n m::Int\nend\n\nBase.length(f::FixedPartitions) = npartitions(f.n,f.m)\n\n\"\"\"\n partitions(n, m)\n\nGenerate all arrays of `m` integers that sum to `n`. Because the number of partitions can\nbe very large, this function returns an iterator object. Use `collect(partitions(n, m))` to\nget an array of all partitions. The number of partitions to generate can be efficiently\ncomputed using `length(partitions(n, m))`.\n\"\"\"\npartitions(n::Integer, m::Integer) =\n n >= 1 && m >= 1 ?\n FixedPartitions(n, m) :\n throw(DomainError((n, m), \"n and m must be positive\"))\n\nfunction Base.iterate(f::FixedPartitions, s::Vector{Int} = Int[])\n f.m <= f.n || return\n if !isempty(s)\n (f.m == 1 || s[1]-1 <= s[end]) && return\n end\n\n xs = nextfixedpartition(f.n,f.m,s)\n (xs, xs)\nend\n\nfunction nextfixedpartition(n, m, bs)\n as = copy(bs)\n if isempty(as)\n # First iteration\n as = [n-m+1; ones(Int, m-1)]\n elseif as[2] < as[1]-1\n # Most common iteration\n as[1] -= 1\n as[2] += 1\n else\n # Iterate\n j = 0\n s = as[1]+as[2]-1\n for jj = 3:m # TODO: use `for outer j = ...` on 0.7\n j = jj\n as[jj] < as[1]-1 && break\n s += as[jj]\n end\n x = as[j] += 1\n for k = j-1:-1:2\n as[k] = x\n s -= x\n end\n as[1] = s\n end\n\n return as\nend\n\nlet _nipartitions = Dict{Tuple{Int,Int},Int}()\n global npartitions\n function npartitions(n::Int, m::Int)\n if n < m || m == 0\n 0\n elseif n == m\n 1\n elseif (np = get(_nipartitions, (n,m), 0)) > 0\n np\n else\n _nipartitions[(n, m)] = npartitions(n-1, m-1) + npartitions(n-m, m)\n end\n end\nend\n\n# Algorithm H from TAoCP 7.2.1.5\n# Set partitions\n\nstruct SetPartitions{T<:AbstractVector}\n s::T\nend\n\nBase.length(p::SetPartitions) = nsetpartitions(length(p.s))\n\n\"\"\"\n partitions(s::AbstractVector)\n\nGenerate all set partitions of the elements of an array `s`, represented as arrays of\narrays. Because the number of partitions can be very large, this function returns an\niterator object. Use `collect(partitions(s))` to get an array of all partitions. The\nnumber of partitions to generate can be efficiently computed using\n`length(partitions(s))`.\n\"\"\"\npartitions(s::AbstractVector) = SetPartitions(s)\n\nfunction Base.iterate(p::SetPartitions)\n n = length(p.s)\n iterate(p, (zeros(Int32, n), ones(Int32, n-1), n, 1))\nend\nfunction Base.iterate(p::SetPartitions, s)\n s[1][1] > 0 && return\n nextsetpartition(p.s, s...)\nend\n\nfunction nextsetpartition(s::AbstractVector, a, b, n, m)\n function makeparts(s, a, m)\n temp = [similar(s, 0) for k = 0:m]\n for i = 1:n\n push!(temp[a[i]+1], s[i])\n end\n filter!(!isempty, temp)\n end\n\n isempty(s) && return ([s], ([1], Int[], n, 1))\n\n part = makeparts(s,a,m)\n\n if a[end] != m\n a[end] += 1\n else\n j = 0\n for jj = n-1:-1:1\n j = jj\n a[jj] == b[jj] || break\n end\n a[j] += 1\n m = b[j] + (a[j] == b[j])\n for k = j+1:n-1\n a[k] = 0\n b[k] = m\n end\n a[end] = 0\n end\n\n return (part, (a,b,n,m))\nend\n\nlet _nsetpartitions = Dict{Int,Int}()\n global nsetpartitions\n function nsetpartitions(n::Int)\n if n < 0\n 0\n elseif n < 2\n 1\n elseif (wn = get(_nsetpartitions, n, 0)) > 0\n wn\n else\n wn = 0\n for k = 0:n-1\n wn += binomial(n-1,k)*nsetpartitions(n-1-k)\n end\n _nsetpartitions[n] = wn\n end\n end\nend\n\nstruct FixedSetPartitions{T<:AbstractVector}\n s::T\n m::Int\nend\n\nBase.length(p::FixedSetPartitions) = nfixedsetpartitions(length(p.s),p.m)\n\n\"\"\"\n partitions(s::AbstractVector, m::Int)\n\nGenerate all set partitions of the elements of an array `s` into exactly `m` subsets,\nrepresented as arrays of arrays. Because the number of partitions can be very large,\nthis function returns an iterator object. Use `collect(partitions(s, m))` to get\nan array of all partitions. The number of partitions into `m` subsets is equal to the\nStirling number of the second kind, and can be efficiently computed using\n`length(partitions(s, m))`.\n\"\"\"\npartitions(s::AbstractVector, m::Int) =\n length(s) >= 1 && m >= 1 ?\n FixedSetPartitions(s, m) :\n throw(DomainError((length(s), m), \"length(s) and m must be positive\"))\n\nfunction Base.iterate(p::FixedSetPartitions)\n n = length(p.s)\n m = p.m\n state = m <= n ? (vcat(ones(Int, n-m),1:m), vcat(1,n-m+2:n), n) : (Int[], Int[], n)\n # state consists of:\n # vector a of length n describing to which partition every element of s belongs\n # vector b of length n describing the first index b[i] that belongs to partition i\n # integer n\n\n iterate(p, state)\nend\n\nfunction Base.iterate(p::FixedSetPartitions, s)\n (isempty(s[1]) || s[1][1] > 1) && return\n nextfixedsetpartition(p.s,p.m, s...)\nend\n\nfunction nextfixedsetpartition(s::AbstractVector, m, a, b, n)\n function makeparts(s, a)\n part = [similar(s, 0) for k = 1:m]\n for i = 1:n\n push!(part[a[i]], s[i])\n end\n return part\n end\n\n part = makeparts(s,a)\n\n if m == 1\n a[1] = 2\n return (part, (a, b, n))\n end\n\n if a[end] != m\n a[end] += 1\n else\n j = k = 0\n for jj = n-1:-1:1\n j = jj\n if a[j] < m && b[a[j]+1] < j\n break\n end\n end\n if j > 1\n a[j] += 1\n for p = j+1:n\n if b[a[p]] != p\n a[p] = 1\n end\n end\n else\n for kk = m:-1:2\n k = kk\n if b[k-1] < b[k] - 1\n break\n end\n end\n b[k] -= 1\n b[k+1:m] = n-m+k+1:n\n a[1:n] .= 1\n a[b] = 1:m\n end\n end\n\n return (part, (a,b,n))\nend\n\nfunction nfixedsetpartitions(n::Int, m::Int)\n numpart = 0\n for k = 0:m\n numpart += (-1)^(m-k) * binomial(m, k) * (k^n)\n end\n numpart = div(numpart, factorial(m))\n return numpart\nend\n\n# TODO: Base.DSP is no longer a thing in Julia 0.7\n#This function is still defined in Base because it is being used by Base.DSP\n#\"\"\"\n#Next integer not less than `n` that can be written as $\\prod k_i^{p_i}$ for integers $p_1$, $p_2$, etc.\n#\n#For a list of integers i1, i2, i3, find the smallest\n# i1^n1 * i2^n2 * i3^n3 >= x\n#for integer n1, n2, n3\n#\"\"\"\n#function nextprod(a::Vector{Int}, x)\n# if x > typemax(Int)\n# throw(ArgumentError(\"unsafe for x > typemax(Int), got $x\"))\n# end\n# k = length(a)\n# v = ones(Int, k) # current value of each counter\n# mx = [nextpow(ai,x) for ai in a] # maximum value of each counter\n# v[1] = mx[1] # start at first case that is >= x\n# p::widen(Int) = mx[1] # initial value of product in this case\n# best = p\n# icarry = 1\n#\n# while v[end] < mx[end]\n# if p >= x\n# best = p < best ? p : best # keep the best found yet\n# carrytest = true\n# while carrytest\n# p = div(p, v[icarry])\n# v[icarry] = 1\n# icarry += 1\n# p *= a[icarry]\n# v[icarry] *= a[icarry]\n# carrytest = v[icarry] > mx[icarry] && icarry < k\n# end\n# if p < x\n# icarry = 1\n# end\n# else\n# while p < x\n# p *= a[1]\n# v[1] *= a[1]\n# end\n# end\n# end\n# best = mx[end] < best ? mx[end] : best\n# return Int(best) # could overflow, but best to have predictable return type\n#end\n\n\"\"\"\n prevprod(a::Vector{Int}, x)\n\nPrevious integer not greater than `x` that can be written as ``\\\\prod k_i^{p_i}`` for\nintegers ``p_1``, ``p_2``, etc.\n\nFor integers ``i_1``, ``i_2``, ``i_3``, this is equivalent to finding the largest ``x``\nsuch that\n```math\ni_1^n_1 i_2^n_2 i_3^n_3 \\\\leq x\n```\nfor integers ``n_1``, ``n_2``, ``n_3``.\n\"\"\"\nfunction prevprod(a::Vector{Int}, x)\n if x > typemax(Int)\n throw(ArgumentError(\"unsafe for x > typemax(Int), got $x\"))\n end\n k = length(a)\n v = ones(Int, k) # current value of each counter\n mx = [nextpow(ai,x) for ai in a] # allow each counter to exceed p (sentinel)\n first = Int(prevpow(a[1], x)) # start at best case in first factor\n v[1] = first\n p::widen(Int) = first\n best = p\n icarry = 1\n\n while v[end] < mx[end]\n while p <= x\n best = p > best ? p : best\n p *= a[1]\n v[1] *= a[1]\n end\n if p > x\n carrytest = true\n while carrytest\n p = div(p, v[icarry])\n v[icarry] = 1\n icarry += 1\n p *= a[icarry]\n v[icarry] *= a[icarry]\n carrytest = v[icarry] > mx[icarry] && icarry < k\n end\n if p <= x\n icarry = 1\n end\n end\n end\n best = x >= p > best ? p : best\n return Int(best)\nend\n\n\n\"\"\"\n integer_partitions(n)\n\nList the partitions of the integer `n`.\n\n!!! note\n The order of the resulting array is consistent with that produced by the computational\n discrete algebra software GAP.\n\"\"\"\nfunction integer_partitions(n::Integer)\n if n < 0\n throw(DomainError(n, \"n must be nonnegative\"))\n elseif n == 0\n return Vector{Int}[]\n elseif n == 1\n return Vector{Int}[[1]]\n end\n\n list = Vector{Int}[]\n\n for p in integer_partitions(n-1)\n push!(list, [p; 1])\n if length(p) == 1 || p[end] < p[end-1]\n push!(list, [p[1:end-1]; p[end]+1])\n end\n end\n\n list\nend\n\n\n\n#Noncrossing partitions\n\nif VERSION >= v\"0.7.0-DEV.3251\"\n const _cmp = cmp\nelse\n const _cmp = lexcmp\nend\n\n#Produces noncrossing partitions of length n\nfunction ncpartitions(n::Int)\n partitions = Vector{Vector{Int}}[]\n _ncpart!(1,n,n,Vector{Int}[], partitions)\n partitions\nend\n\nfunction _ncpart!(a::Int, b::Int, nn::Int, x::Vector, partitions::Vector)\n n = b - a + 1\n for k = 1:n, root in CoolLexCombinations(n, k)\n root .+= a - 1\n #Abort if construction is out of lex order\n !isempty(x) && _cmp(x[end], root) == 1 && return\n\n #Save if we've filled all the holes\n sofar = Vector{Int}[x..., root]\n ssofaru = sort!(union(sofar...))\n if length(ssofaru) == nn && ssofaru == collect(1:nn)\n push!(partitions, sofar)\n return\n end\n\n #otherwise patch all remaining holes\n blob = [ssofaru; nn + 1]\n for l = 1:length(blob)-1\n ap, bp = blob[l] + 1, blob[l+1] - 1\n ap <= bp && _ncpart!(ap, bp, nn, sofar, partitions)\n end\n end\nend\n", "meta": {"hexsha": "f84ead100623257f2c38621e47ffd4f0a92f9c1b", "size": 12908, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/partitions.jl", "max_stars_repo_name": "mschauer/Combinatorics.jl", "max_stars_repo_head_hexsha": "0e0edc6b204f3cbd726074a9d3f8d4288b3ab16b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/partitions.jl", "max_issues_repo_name": "mschauer/Combinatorics.jl", "max_issues_repo_head_hexsha": "0e0edc6b204f3cbd726074a9d3f8d4288b3ab16b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/partitions.jl", "max_forks_repo_name": "mschauer/Combinatorics.jl", "max_forks_repo_head_hexsha": "0e0edc6b204f3cbd726074a9d3f8d4288b3ab16b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2109375, "max_line_length": 104, "alphanum_fraction": 0.5257979548, "num_tokens": 3970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391664210672, "lm_q2_score": 0.9149009544128984, "lm_q1q2_score": 0.8444894143191206}} {"text": "x = -11:11\ny = sin.(x)\nx = x[y .> 0] # Only keep values of x where y=sin x is positive\n\n# Example: Consider the matrix\nA = rand(-10:10, 3, 10)\n\n# Compute a boolean array with `true` if the column sums are >=0\npick = sum(A, dims=1) .≥ 0\n\n# Create a new vector with only the columns of A given by the `pick` variable\n# Note that since `pick` is a 2D vector (row vector), we use [:] before indexing\nB = A[:, pick[:]]\n", "meta": {"hexsha": "862ab79dbab8ba75871fdff082a2d45086f3ac6a", "size": 423, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "textbook/_build/jupyter_execute/content/Vectorization/Logical_Indexing.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/Logical_Indexing.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/Logical_Indexing.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": 30.2142857143, "max_line_length": 80, "alphanum_fraction": 0.6359338061, "num_tokens": 140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572635, "lm_q2_score": 0.9136765163620469, "lm_q1q2_score": 0.8443666825204759}} {"text": "# This file illustrates the calculation of power spectral density and \n# total average power of a sinusoidal signal. \n\nusing FFTW \nusing Plots \n\n# Construct the signal\nf = 20\nfs = 100 \nl = 2^10\nts = 1 / fs \nt = (0 : l -1) * ts \nx = cos.(2π * f * t)\n\n# Compute fft\nxf = fft(x) * ts \nff = 0 : fs / (l - 1) : fs \n\n# Compute power \npsd = abs.(xf).^2 / (l - 1) / ts \nΔf = fs / (l - 1) \nPf = sum(psd) * Δf # Average power calculated in time \nPt = sum(abs.(x).^2) / (l - 1) # Average power calculated in frequency\n@show Pf, Pt\n\n# Plots \nplt = plot(layout=1)\nplot!(ff, psd, subplot=1)\nxlabel!(\"Frequency [Hz]\") \nylabel!(\"Ψ(f)\")\ntitle!(\"Power Spectal Density\")\ndisplay(plt)", "meta": {"hexsha": "86ab6237eefae9be3fd991a2cde2e0e708189e83", "size": 678, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/dsp/sinusoidal.jl", "max_stars_repo_name": "zekeriyasari/DigitalCommunications.jl", "max_stars_repo_head_hexsha": "7ac2e6afe42aa996d94d211c1ea590ac3c0beb15", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-03T20:02:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-13T06:43:38.000Z", "max_issues_repo_path": "example/dsp/sinusoidal.jl", "max_issues_repo_name": "zekeriyasari/DigitalCommunications.jl", "max_issues_repo_head_hexsha": "7ac2e6afe42aa996d94d211c1ea590ac3c0beb15", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2020-11-26T21:56:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-03T19:54:59.000Z", "max_forks_repo_path": "example/dsp/sinusoidal.jl", "max_forks_repo_name": "zekeriyasari/DigitalCommunications.jl", "max_forks_repo_head_hexsha": "7ac2e6afe42aa996d94d211c1ea590ac3c0beb15", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-20T12:53:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T12:53:43.000Z", "avg_line_length": 21.1875, "max_line_length": 71, "alphanum_fraction": 0.598820059, "num_tokens": 239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.967899289579129, "lm_q2_score": 0.8723473663814338, "lm_q1q2_score": 0.8443443961868139}} {"text": "\"Square the sum of the first `n` positive integers\"\nfunction square_of_sum(n)\n tmp=0\n for i in 1:n\n tmp+=i\n end\n return tmp^2\nend\n\n\"Sum the squares of the first `n` positive integers\"\nfunction sum_of_squares(n)\n tmp=0\n for i in 1:n\n tmp+=i^2\n end\n return tmp\nend\n\n\"Subtract the sum of squares from square of the sum of the first `n` positive ints\"\nfunction difference(n)\n return abs(sum_of_squares(n) - square_of_sum(n))\nend\n", "meta": {"hexsha": "5735899c9df90a9ee3e2957b185ebc2204eafb09", "size": 466, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "difference-of-squares/difference-of-squares.jl", "max_stars_repo_name": "stepinski/julia-in", "max_stars_repo_head_hexsha": "08c82e2de236ead3b1eb356d60a04c61e275d4fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-01T11:27:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T11:27:13.000Z", "max_issues_repo_path": "difference-of-squares/difference-of-squares.jl", "max_issues_repo_name": "stepinski/julia-init", "max_issues_repo_head_hexsha": "e70b08c72c4db3677483480e72a9f79827a41fff", "max_issues_repo_licenses": ["MIT"], "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": "stepinski/julia-init", "max_forks_repo_head_hexsha": "e70b08c72c4db3677483480e72a9f79827a41fff", "max_forks_repo_licenses": ["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.2608695652, "max_line_length": 83, "alphanum_fraction": 0.669527897, "num_tokens": 139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966671870766, "lm_q2_score": 0.8918110454379296, "lm_q1q2_score": 0.8441853633721667}} {"text": "function absolute_error(y_true::Vector, y_pred::Vector)\n check_args(y_true, y_pred)\n return(abs(y_true .- y_pred))\nend\n\nfunction percent_error(y_true::Vector, y_pred::Vector)\n check_args(y_true, y_pred)\n return((y_true .- y_pred) ./ y_true)\nend\n\nfunction log_error(y_true::Vector, y_pred::Vector)\n check_args(y_true, y_pred)\n return(log(y_true - y_pred))\nend\n\nfunction squared_error(y_true::Vector, y_pred::Vector)\n check_args(y_true, y_pred)\n return((y_true - y_pred) .^ 2)\nend\n\nfunction squared_log_error(y_true::Vector, y_pred::Vector)\n check_args(y_true, y_pred)\n return(log_error(y_true, y_pred) .^ 2)\nend\n\nfunction absolute_percent_error(y_true::Vector, y_pred::Vector)\n check_args(y_true, y_pred)\n return(abs(percent_error(y_true, y_pred)))\nend\n\nfunction mean_error(y_true::Vector, y_pred::Vector)\n check_args(y_true, y_pred)\n return(mean(y_true - y_pred))\nend\n\nfunction mean_absolute_error(y_true::Vector, y_pred::Vector)\n check_args(y_true, y_pred)\n return(mean(absolute_error(y_true, y_pred)))\nend\n\nfunction median_absolute_error(y_true::Vector, y_pred::Vector)\n check_args(y_true, y_pred)\n return(median(absolute_error(y_true, y_pred)))\nend\n\nfunction mean_percent_error(y_true::Vector, y_pred::Vector)\n check_args(y_true, y_pred)\n return(mean(percent_error(y_true, y_pred)))\nend\n\nfunction median_percent_error(y_true::Vector, y_pred::Vector)\n check_args(y_true, y_pred)\n return(median(percent_error(y_true, y_pred)))\nend\n\nfunction mean_squared_error(y_true::Vector, y_pred::Vector)\n check_args(y_true, y_pred)\n return(mean(squared_error(y_true, y_pred)))\nend\n\nfunction median_squared_error(y_true::Vector, y_pred::Vector)\n check_args(y_true, y_pred)\n return(median(squared_error(y_true, y_pred)))\nend\n\nfunction sum_squared_error(y_true::Vector, y_pred::Vector)\n check_args(y_true, y_pred)\n return(sum(squared_error(y_true, y_pred)))\nend\n\nfunction mean_squared_log_error(y_true::Vector, y_pred::Vector)\n check_args(y_true, y_pred)\n return(mean(squared_log_error(y_true, y_pred)))\nend\n\nfunction mean_absolute_percent_error(y_true::Vector, y_pred::Vector)\n check_args(y_true, y_pred)\n return(mean(absolute_percent_error(y_true, y_pred)))\nend\n\nfunction median_absolute_percent_error(y_true::Vector, y_pred::Vector)\n check_args(y_true, y_pred)\n return(median(absolute_percent_error(y_true, y_pred)))\nend\n\nfunction symmetric_mean_absolute_percent_error(y_true::Vector, y_pred::Vector)\n check_args(y_true, y_pred)\n return(mean(abs(y_pred - y_true) / ((abs(y_true) + abs(y_pred)) / 2)))\nend\n\nfunction symmetric_median_absolute_percent_error(y_true::Vector, y_pred::Vector)\n check_args(y_true, y_pred)\n return(median(abs(y_pred - y_true) / ((abs(y_true) + abs(y_pred)) / 2)))\nend\n\nfunction mean_absolute_scaled_error(y_true::Vector, y_pred::Vector)\n check_args(y_true, y_pred)\n n = max(length(y_true), length(y_pred))\n numerator = sum(abs(y_true - y_pred))\n denominator = (n / (n - 1)) * sum(abs(y_true[2:n] - y_pred[1:(n-1)]))\n return(numerator / denominator)\nend\n\nfunction total_variance_score(y_true::Vector, y_pred::Vector)\n check_args(y_true, y_pred)\n return(sum((y_true - mean(y_true)) .^ 2))\nend\n\nfunction explained_variance_score(y_true::Vector, y_pred::Vector)\n check_args(y_true, y_pred)\n return(sum((y_pred - mean(y_true)) .^ 2))\nend\n\nfunction unexplained_variance_score(y_true::Vector, y_pred::Vector)\n check_args(y_true, y_pred)\n return(sum((y_true - y_pred) .^ 2))\nend\n\nfunction r2_score(y_true::Vector, y_pred::Vector)\n check_args(y_true, y_pred)\n return(explained_variance_score(y_true, y_pred) / total_variance_score(y_true, y_pred))\nend\n", "meta": {"hexsha": "e5bf0b98b739cf8af0ee83b74afc1442fa966723", "size": 3710, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/regression.jl", "max_stars_repo_name": "JuliaPackageMirrors/MachineLearningMetrics.jl", "max_stars_repo_head_hexsha": "6ca8b9c26bab6ef5e08ea9e2278b1eb74e69aae7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2016-04-06T13:02:18.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-11T09:35:51.000Z", "max_issues_repo_path": "src/regression.jl", "max_issues_repo_name": "JuliaPackageMirrors/MachineLearningMetrics.jl", "max_issues_repo_head_hexsha": "6ca8b9c26bab6ef5e08ea9e2278b1eb74e69aae7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2016-03-24T18:23:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T08:26:32.000Z", "max_forks_repo_path": "src/regression.jl", "max_forks_repo_name": "JuliaPackageMirrors/MachineLearningMetrics.jl", "max_forks_repo_head_hexsha": "6ca8b9c26bab6ef5e08ea9e2278b1eb74e69aae7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-07-12T02:14:56.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-26T18:19:25.000Z", "avg_line_length": 30.162601626, "max_line_length": 91, "alphanum_fraction": 0.7447439353, "num_tokens": 994, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341987633821, "lm_q2_score": 0.8824278741843883, "lm_q1q2_score": 0.8441606823868568}} {"text": "# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10\n# without any remainder.\n# What is the smallest positive number that is evenly\n# divisible by all of the numbers from 1 to 20?\n\n# (1,2) (1,3) Means 1 * 2 * 1 * 3\n# (2,2) means 2 * 2\ninclude(\"./primes.jl\")\nusing Primes\n\n\nfunction pop(arr, value)\n inx = findfirst(x -> x == value, arr)\n if inx != 0\n deleteat!(arr, inx)\n return value\n end\n return 0\nend\n\n\nfunction merge(factor_set_1, factor_set_2)\n results = []\n for factor in factor_set_1\n pop(factor_set_2, factor)\n push!(results, factor)\n end\n\n for factor in factor_set_2\n push!(results, factor)\n end\n return results\nend\n\n\n@assert Primes.prime_factors(2) == [2]\n@assert Primes.prime_factors(4) == [2,2]\n@assert Primes.prime_factors(8) == [2,2,2]\n@assert Primes.prime_factors(21) == [3,7]\n\n@assert merge([2,2], [2,2,3]) == [2,2,3]\n@assert merge([2,7], [2,2,3]) == [2,7,2,3]\n@assert merge([7], [2,3,3]) == [7,2,3,3]\n\nfunction min_common_factor(nb)\n factors = map(x -> Primes.prime_factors(x), 2:nb)\n min_factors = reduce(merge, [], factors)\n return prod(min_factors)\nend\n\n@assert min_common_factor(10) == 2520\nprintln(min_common_factor(20))\n", "meta": {"hexsha": "655bce9731ddec31b2ca0083ddecb304e326d95d", "size": 1250, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "5.jl", "max_stars_repo_name": "ddugue/project-euler", "max_stars_repo_head_hexsha": "ab373d896ac5051bb53a706cccfdfa3987ca9272", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "5.jl", "max_issues_repo_name": "ddugue/project-euler", "max_issues_repo_head_hexsha": "ab373d896ac5051bb53a706cccfdfa3987ca9272", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "5.jl", "max_forks_repo_name": "ddugue/project-euler", "max_forks_repo_head_hexsha": "ab373d896ac5051bb53a706cccfdfa3987ca9272", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5849056604, "max_line_length": 85, "alphanum_fraction": 0.6424, "num_tokens": 420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342049451596, "lm_q2_score": 0.8824278618165526, "lm_q1q2_score": 0.844160676010335}} {"text": "# ------------------------------------------------------------------------------------------\n# ## How can we calculate $\\pi$?\n#\n# Given a square of length $2r$, the square's area is\n#\n# $$A_{square} = (2r)^2 = 4r^2$$\n#\n# whereas the area of a circle with radius $r$ is\n# $$A_{circle} = \\pi r^2$$\n#\n# \"Drawing\"\n#\n# Therefore the ratio of the area of the circle to that of the square above is\n#\n# $$\\frac{A_{circle}}{A_{square}} = \\frac{\\pi r^2}{4r^2} = \\frac{\\pi}{4}$$\n#\n# and we can define $\\pi$ as\n#\n# $$\\pi = 4\\frac{A_{circle}}{A_{square}}$$\n#\n# This suggests a way to calculate $\\pi$: if we have a square and the largest circle that\n# fits inside that square, we can determine the ratio of areas of a circle and a square. We\n# can calculate this ratio using a monte carlo simulation. We select random points inside a\n# square, and we keep track of how often those points also fall inside the circle that fits\n# perfectly inside that square.\n#\n# Given a large enough sampling points, $\\frac{A_{circle}}{A_{square}}$ will be equal to the\n# fraction of randomly chosen points inside the square that also fall inside the circle.\n# Then we can figure out $\\pi$!\n#\n# #### Pseudo-code\n#\n# Given the above, our algorithm for determining $\\pi$ looks like this:\n#\n# 1. For each of $N$ iterations,\n# 1. Select a random point inside a square of area $4r^2$ as Cartesian, $(x, y)$,\n# coordinates.\n# 1. Determine if the point also falls inside the circle embedded within this square of\n# area $\\pi r^2$.\n# 1. Keep track of whether or not this point fell inside the circle. At the end of $N$\n# iterations, you want to know $M$ -- the number of the $N$ random points that fell inside\n# the circle!\n# 1. Calculate $\\pi$ as $4\\frac{M}{N}$\n#\n# #### Exercise\n#\n# Write a function that calculates $\\pi$ using Julia.\n#\n# The algorithm above should work for any value of $r$ that you choose to use. Make sure you\n# make $N$ big enough that the value of $\\pi$ is correct to at least a couple numbers after\n# the decimal point!\n#\n# *Hint*:\n#\n# This will probably be easier if you center your circle and square at the coordinate (0, 0)\n# and use a radius of 1. For example, to choose random coordinates within your square at\n# position (x, y), you may want to choose x and y so that they are each a value between -1\n# and +1. Then any point within a distance of 1 from (0, 0) will fall inside the circle!\n#\n# \"Drawing\"\n#\n#\n# #### Solution\n#\n# In what follows are two functions, `calculate_pi` and `calculate_pi_2`. They use the same\n# algorithm to determine `pi` with a couple minor differences in execution. Each of these\n# functions is then called to show that as the number of samples, `N`, increases, our value\n# for `pi` becomes more precise.\n# ------------------------------------------------------------------------------------------\n\n\"\"\"\ncalculate_pi(N = 1000)\n\nReturn the value of pi, calculated using a Monte Carlo simulation with N samples. N defaults to 1000.\nThe radius of the circle, r, defaults to 1.\n\"\"\"\nfunction calculate_pi(N = 1000)\n how_often_in_circle = 0\n for i in 1:N\n # Generate a random point (x, y) inside the square centered at (0, 0) \n # that has corners at (-1, 1), (-1, 1), (1, -1), and (1, 1)\n x, y = rand([-1, 1])*rand(), rand([-1, 1])*rand()\n # Check if the distance to (x, y) from (0, 0) is less than the radius of 1\n if sqrt(x^2 + y^2) < 1\n how_often_in_circle += 1\n end\n end\n return 4 * how_often_in_circle / N\nend\n\ncalculate_pi.([10, 100, 1000, 10000, 100_000, 1_000_000_000])\n\n\"\"\"\ncalculate_pi_2(N = 1000)\n\nReturn the value of pi, calculated using a Monte Carlo simulation with N samples. N defaults to 1000.\nThe radius of the circle, r, defaults to 1.\n\"\"\"\nfunction calculate_pi_2(N = 1000)\n how_often_in_circle = 0\n for i in 1:N\n # Generate a random point (x, y) inside the square centered at (0, 0) \n # that has corners at (-1, 1), (-1, 1), (1, -1), and (1, 1)\n x = 1-2*rand()\n y = 1-2*rand()\n # Check if the distance to (x, y) from (0, 0) is less than the radius of 1\n if x^2 + y^2 < 1\n how_often_in_circle += 1\n end\n end\n return 4 * how_often_in_circle / N\nend\n\ncalculate_pi.([10, 100, 1000, 10000, 100_000, 1_000_000_000])\n", "meta": {"hexsha": "8801da2b4ca801c0f820c3fd006c00f433337cd2", "size": 4408, "ext": "jl", "lang": "Julia", "max_stars_repo_path": ".nbexports/introductory-tutorials/intro-to-julia/calculate_pi_solution.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/calculate_pi_solution.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/calculate_pi_solution.jl", "max_forks_repo_name": "grenkoca/JuliaTutorials", "max_forks_repo_head_hexsha": "3968e0430db77856112521522e10f7da0d7610a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 394, "max_forks_repo_forks_event_min_datetime": "2020-07-14T23:22:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T20:12:57.000Z", "avg_line_length": 38.3304347826, "max_line_length": 101, "alphanum_fraction": 0.6349818512, "num_tokens": 1301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.94815453335022, "lm_q2_score": 0.8902942283051332, "lm_q1q2_score": 0.8441365085830478}} {"text": "@doc raw\"\"\"\n RationalQuadraticKernel([α=1 [,β=1]])\n\nThe rational-quadratic kernel is given by:\n\n```math\n\\kappa(\\mathbf{x},\\mathbf{y}) \n= \\left(1 +\\alpha ||\\mathbf{x},\\mathbf{y}||^2\\right)^{-\\beta} \n\\qquad \\alpha > 0, \\; \\beta > 0\n```\n\nwhere ``\\alpha`` is a scaling parameter and ``\\beta`` is a shape parameter. This kernel can \nbe seen as an infinite sum of Gaussian kernels. If one sets ``\\alpha = \\alpha_0 / \\beta``, \nthen taking the limit ``\\beta \\rightarrow \\infty`` results in the Gaussian kernel with \nscaling parameter ``\\alpha_0``.\n\"\"\"\nstruct RationalQuadraticKernel{T<:AbstractFloat} <: MercerKernel{T}\n alpha::HyperParameter{T}\n beta::HyperParameter{T}\n RationalQuadraticKernel{T}(α::Real, β::Real) where {T<:AbstractFloat} = new{T}(\n HyperParameter(convert(T,α), interval(OpenBound(zero(T)), nothing)),\n HyperParameter(convert(T,β), interval(OpenBound(zero(T)), nothing))\n )\nend\nfunction RationalQuadraticKernel(α::T1 = 1.0, β::T2 = one(T1)) where {T1<:Real,T2<:Real}\n RationalQuadraticKernel{floattype(T1,T2)}(α, β)\nend\n\n@inline rationalquadratickernel(z::T, α::T, β::T) where {T<:AbstractFloat} = (1 + α*z)^(-β)\n\n@inline basefunction(::RationalQuadraticKernel) = SquaredEuclidean()\n@inline function kappa(κ::RationalQuadraticKernel{T}, z::T) where {T}\n rationalquadratickernel(z, getvalue(κ.alpha), getvalue(κ.beta))\nend", "meta": {"hexsha": "47690d6760e07065c1aec3b76f2f446d704d4ad3", "size": 1368, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernelfunctions/mercer/rationalquadratic.jl", "max_stars_repo_name": "holtri/MLKernels.jl", "max_stars_repo_head_hexsha": "d7b84b1bd7b9d9ca4cb7c413d0e34b04c09a331c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernelfunctions/mercer/rationalquadratic.jl", "max_issues_repo_name": "holtri/MLKernels.jl", "max_issues_repo_head_hexsha": "d7b84b1bd7b9d9ca4cb7c413d0e34b04c09a331c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernelfunctions/mercer/rationalquadratic.jl", "max_forks_repo_name": "holtri/MLKernels.jl", "max_forks_repo_head_hexsha": "d7b84b1bd7b9d9ca4cb7c413d0e34b04c09a331c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.2352941176, "max_line_length": 92, "alphanum_fraction": 0.6885964912, "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545392102522, "lm_q2_score": 0.8902942159342104, "lm_q1q2_score": 0.844136502070654}} {"text": "function rectfunc(x::T, x_c::T)::T where T\n if abs(x) <= x_c\n return one(T)\n end\n\n return zero(T)\nend\n\n\nfunction raisedcosinefunction(x::T, β, 𝑇)::T where T\n return raisedcosinefunction(x,convert(T,β),convert(T,𝑇))\nend\n\n\"\"\"\n raisedcosinefunc(x::T, β::T, 𝑇::T)::T\nLet low := (1-β)/(2𝑇),\n |x| := abs(x),\n high := (1+β)/(2𝑇).\n\nReturns 1 if |x| ≤ low,\nReturns 0.5*(1+cos(π*𝑇/β *(|x|-low))) if low ≤ |x| ≤ high.\nReturns 0 otherwise.\n\"\"\"\nfunction raisedcosinefunction(x::T, β::T, 𝑇::T)::T where T\n two = one(T) + one(T)\n low = (one(T)-β)/(two*𝑇)\n high = (one(T)+β)/(two*𝑇)\n\n if abs(x) <= low\n return one(T)\n elseif low < abs(x) <= high\n return one(T)/two*( one(T) + cos(π*𝑇/β *(abs(x)-low)) )\n end\n\n return zero(T)\nend\n\n\n# transition band is cosine. This allows satisfies the power complementary condition.\n# cos( (yp-y)/(yp-ys) * π/2 ) for a falling edge. yp is pass band, ys is stop band.\nfunction cosinetransitionlowpassfunction(y::T, yp::T, ys::T)::T where T\n abs_y = abs(y)\n\n if abs_y <= yp\n return one(T)\n elseif yp < abs_y <= ys\n #return cos( (yp-y)/(ys-yp)*π/2 )\n return cos( (yp-abs_y)/(ys-yp)*π/2 )\n end\n\n return zero(T)\nend\n\nfunction cosinetransitionhighpassfunction(x::T, xp::T, xs::T)::T where T\n abs_x = abs(x)\n\n if abs_x <= xs\n return zero(T)\n elseif xs < abs_x <= xp\n #return cos( (xp-x)/(xp-xs)*π/2 )\n return cos( (xp-abs_x)/(xp-xs)*π/2 )\n end\n\n return one(T)\nend\n\n\n# rs is rising edge's stopband.\n# rp is rising edge's passband.\n# fp is falling edge's passband.\n# fs is falling edge's stopband.\nfunction cosinetransitionbandpassfunction(y::T, rs, rp, fp, fs)::T where T\n abs_y = abs(y)\n\n # rising edge.\n if abs_y <= rs\n return zero(T)\n elseif rs < abs_y <= rp\n #return cos( (rp-y)/(rp-rs)*π/2 )\n return cos( (rp-abs_y)/(rp-rs)*π/2 )\n end\n\n # falling edge.\n if rp <= abs_y <= fp\n return one(T)\n elseif fp < abs_y <= fs\n #return cos( (fp-y)/(fs-fp)*π/2 )\n return cos( (fp-abs_y)/(fs-fp)*π/2 )\n end\n\n return zero(T)\nend\n", "meta": {"hexsha": "8f7304ff0b40beaa193a9f537f9180b04ce2a9d1", "size": 2136, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/misc/template_signals.jl", "max_stars_repo_name": "RoyCCWang/FIRRemez", "max_stars_repo_head_hexsha": "41a3ad4e8bd851d51a62c7fcd35ac3abf6fdd84c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/misc/template_signals.jl", "max_issues_repo_name": "RoyCCWang/FIRRemez", "max_issues_repo_head_hexsha": "41a3ad4e8bd851d51a62c7fcd35ac3abf6fdd84c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/misc/template_signals.jl", "max_forks_repo_name": "RoyCCWang/FIRRemez", "max_forks_repo_head_hexsha": "41a3ad4e8bd851d51a62c7fcd35ac3abf6fdd84c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9677419355, "max_line_length": 85, "alphanum_fraction": 0.5627340824, "num_tokens": 748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475778774728, "lm_q2_score": 0.8947894632969136, "lm_q1q2_score": 0.8440974729114272}} {"text": "\r\n# =========================================================================== #\r\n# pdf functions\r\n# =========================================================================== #\r\n\r\nfunction pdf(d::UniformDistribution, x)\r\n h = 1 / (d.b - d.a)\r\n if d.a <= x <= d.b\r\n y = h\r\n else\r\n y = 0.0\r\n end\r\n return y\r\nend\r\n\r\nfunction pdf(d::NormalDistribution, x)\r\n y = 1 ./ (sqrt(2*pi) .* d.sigma) .* exp.( -0.5 .* (x .- d.mu).^2 ./ d.sigma.^2 )\r\n return y\r\nend\r\n\r\nfunction pdf(d::CauchyDistribution, x)\r\n return 1 ./ ( (pi * d.c) .* (1 .+ ((x .- d.mu) ./ d.c).^2 ) )\r\nend\r\n\r\n\r\nfunction pdf(d::MultiNormalDistribution, x)\r\n n_dim = length(d.mu)\r\n det_sigma = prod( diag(d.L) )\r\n dx = x .- d.mu\r\n arg = -0.5 .* dot(dx, d.inv_sigma * dx )\r\n nom = exp.(arg)\r\n den = sqrt( (2*pi)^n_dim * det_sigma )\r\n return nom ./ den\r\nend", "meta": {"hexsha": "6a3f27767ac3e0dd68e191299b5ce401a0c42498", "size": 912, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "__lib__/math/common/distributions/src/pdf.jl", "max_stars_repo_name": "HomoModelicus/julia", "max_stars_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "__lib__/math/common/distributions/src/pdf.jl", "max_issues_repo_name": "HomoModelicus/julia", "max_issues_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "__lib__/math/common/distributions/src/pdf.jl", "max_forks_repo_name": "HomoModelicus/julia", "max_forks_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8235294118, "max_line_length": 85, "alphanum_fraction": 0.3837719298, "num_tokens": 258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693242000616578, "lm_q2_score": 0.870597270087091, "lm_q1q2_score": 0.8438910024030325}} {"text": "\"\"\"\n mandelbrot( c )\n\nComputes the number of evaluations of the following equation before the resulting complex number `z` beginning with `z=c`.\n- Input: `c::Number`\n- Output: `itrMax::??`\n\n### Questions\n- What do you think is the output type of this function?\n- Which of the part of the code determines the type?\n\nSometimes forcing the type of output can be an advantage.\n\"\"\"\nfunction mandelbrot( c )\n z = c\n itrMax = 80\n for n in 1:itrMax\n if abs(z) > 2\n return n-1\n end\n z = z^2 + c\n end\n return itrMax\nend\n\n", "meta": {"hexsha": "b82463f35e09ab8fe346768184ffbb1f2433b5eb", "size": 561, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "01-HPC/Mandelbrot.jl", "max_stars_repo_name": "jybantang/phys215-202122-1", "max_stars_repo_head_hexsha": "187d0d36b9a8b2e48024242a5fca4d38accfc805", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "01-HPC/Mandelbrot.jl", "max_issues_repo_name": "jybantang/phys215-202122-1", "max_issues_repo_head_hexsha": "187d0d36b9a8b2e48024242a5fca4d38accfc805", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "01-HPC/Mandelbrot.jl", "max_forks_repo_name": "jybantang/phys215-202122-1", "max_forks_repo_head_hexsha": "187d0d36b9a8b2e48024242a5fca4d38accfc805", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5769230769, "max_line_length": 122, "alphanum_fraction": 0.632798574, "num_tokens": 157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.951142225532629, "lm_q2_score": 0.8872045832787205, "lm_q1q2_score": 0.8438577418424709}} {"text": "using NumericalMethodsforEngineers, Test\n\na = [10. 1. -5.; -20. 3. 20.; 5. 3. 5.]\nb = [1., 2., 6.]\nn = size(A, 1)\nx = 0.0\n\n# Convert to upper triang;e\nfunction to_upper(a::Matrix, b::Vector)\n at = deepcopy(a)\n bt = deepcopy(b) \n r, c = size(at)\n\n for k in 1:r-1\n if abs(at[k, k]) > 1.0e-6\n for i in k+1:r\n x = at[i, k] / at[k, k]\n at[i, k] = 0.0\n for j in k+1:r\n at[i, j] -= at[k, j] * x\n end\n bt[i] -= bt[k] * x\n end\n else\n md\"Zero pivot found in row $k\"\n end\n end\n (at, bt)\nend\n\nfunction direct_solve(a::Matrix, b::Vector)\n at = deepcopy(a)\n bt = deepcopy(b)\n r, c = size(at)\n\n for i in r:-1:1\n x = bt[i]\n if i < r\n for j in i+1:r\n x -= at[i, j] * bt[j]\n end\n end\n bt[i] = x / at[i, i]\n end\n bt\nend\n\nprintln(\"Modified lhs matrix and rhs\")\nat, bt = to_upper(a, b)\nat |> display\nprintln()\nbt |> display\nprintln()\n\nprintln(\"Solution vector:\")\nc_nmfe = direct_solve(at, bt)\nc_nmfe |> display\nprintln()\n\nc = a \\ [1., 2., 6.]\nc |> display\n\nprintln()\n@test ≈(c, c_nmfe, atol=1e-10)\n@test round.(a * c; digits=14) == b\n", "meta": {"hexsha": "fb6bae9feb75f3c1c94731c6892ee4cb60012410", "size": 1097, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ch02/f-02-01.jl", "max_stars_repo_name": "PtFEM/NumericalMethodsforEngineers.jl", "max_stars_repo_head_hexsha": "e4a997a14adbb86b7efe1586962df39eb9285ebb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-07-23T18:12:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-25T03:32:45.000Z", "max_issues_repo_path": "examples/ch02/f-02-01.jl", "max_issues_repo_name": "PtFEM/NumericalMethodsforEngineers.jl", "max_issues_repo_head_hexsha": "e4a997a14adbb86b7efe1586962df39eb9285ebb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2018-07-23T21:46:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-27T23:14:46.000Z", "max_forks_repo_path": "examples/ch02/f-02-01.jl", "max_forks_repo_name": "PtFEM/NumericalMethodsforEngineers.jl", "max_forks_repo_head_hexsha": "e4a997a14adbb86b7efe1586962df39eb9285ebb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-10-27T14:13:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T18:54:06.000Z", "avg_line_length": 16.6212121212, "max_line_length": 43, "alphanum_fraction": 0.5278030994, "num_tokens": 442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422199928905, "lm_q2_score": 0.8872045862611166, "lm_q1q2_score": 0.8438577397642724}} {"text": "\"\"\"\n ChirpSignal\nChirp Swept-frequency sine generator.\n\"\"\"\nmodule ChirpSignal\n\nexport chirp\n\n\n\"\"\"\n chirp(T, fs, fl, fh; method=\"linear\", phase=0.0) -> Array{Float64,1}\n\nChirp Swept-frequency sine generator.\n# Arguments\n- `T` : signal's length in second\n- `fs` : sampling rate\n- `fl` : lower frequency at the ending time step, fl <= fs\n- `fh ` : higher frequency at the ending time step, fh <= fs\n- `phase` : phase of the chirp sigal, like sin(wt + phase)\n- `method`: available methods are 'linear','quadratic','exponential' and 'logarithmic'; the default is 'linear'\n\"\"\"\nfunction chirp(T, fs, fl, fh; method=\"linear\", phase=0.0)\n method == \"linear\" && return chirpLinear(T, fs, fl, fh; phase=phase)\n method == \"quadratic\" && return chirpQuadratic(T, fs, fl, fh; phase=phase)\n method == \"logarithmic\" && return chirpLogarithmic(T, fs, fl, fh; phase=phase)\n method == \"exponential\" && return chirpExponential(T, fs, fl, fh; phase=phase)\nend\n\n\nfunction chirpLinear(T, fs, fl, fh; phase=0.0)\n Δt = 1.0/fs;\n fl = min(fs/2,max(0,fl));\n fh = min(fs/2,max(0,fh));\n k = (fh - fl)/T/2;\n t = 0:Δt:T-Δt;\n y = @. sin(6.2831853*(k*t + fl)*t + phase);\nend\n\n\nfunction chirpQuadratic(T, fs, fl, fh; phase=0.0)\n # f(t) = k * t^2 + fl, k = (fh-fl)/T^2\n # F(t) = k/3 * t^3 + fl*t\n Δt = 1.0/fs;\n fl = min(fs/2,max(0,fl));\n fh = min(fs/2,max(0,fh));\n t = 0:Δt:T-Δt;\n y = @. sin(6.2831853*( (fh-fl)/(3*T^2) * t^3 + fl * t) + phase)\nend\n\n\nfunction chirpLogarithmic(T, fs, fl, fh; phase=0.0)\n # f(t) = k*log(t+1) + fl, k = (fh-fl)/log(T+1)\n # F(t) = k*(t+1)*log(t+1) + (fl-k)*t\n (fl <= fh) || error(\"fl <= fh not met\")\n Δt = 1.0/fs;\n fl = min(fs/2,max(0,fl));\n fh = min(fs/2,max(0,fh));\n t = 0:Δt:T-Δt;\n k = (fh-fl)/log(T+1);\n y = @. sin(6.2831853*( k*(t+1)*log(t+1) + (fl-k)*t ) + phase);\nend\n\n\nfunction chirpExponential(T, fs, fl, fh; phase=0.0)\n # f(t) = exp(k * t) + (fl-1), k = 1/T*log(fh-fl+1)\n # F(t) = 1/k * exp(k * t) + (fl-1)*t\n (fl <= fh) || error(\"fl <= fh not met\")\n Δt = 1.0/fs;\n fl = min(fs/2,max(0,fl));\n fh = min(fs/2,max(0,fh));\n t = 0:Δt:T-Δt;\n k = 1/T*log(fh-fl+1);\n y = @. sin(6.2831853*( (1/k) * exp(k*t) + (fl-1)*t ) + phase);\nend\n\n\n\"\"\"\n chirp(T, fs, f::Function; phase=0.0) -> Array{Float64,1}\n\nFunction customizable chirp swept-frequency sine generator.\n# Arguments\n- `T` : signal's length in second\n- `fs` : sampling rate\n- `f` : function that defines how the frequency changes vs time\n- `phase` : phase of the chirp sigal, like sin(wt + phase)\n\"\"\"\nfunction chirp(T, fs, f::Function; phase=0.0)\n Δt = 1.0/fs;\n τ = 0:Δt:T-Δt;\n ϕ = zeros(length(τ),1);\n x = zeros(length(τ),1);\n ϕ[1] = f(0)*Δt;\n x[1] = sin(6.2831853*ϕ[1] + phase);\n for t = 2:length(τ)\n ϕ[t] = ϕ[t-1] + f(τ[t-1])*Δt;\n x[t] = sin(6.2831853*ϕ[t] + phase);\n end\n return x\nend\n\nend # module\n", "meta": {"hexsha": "7e07c1ce3f04537a3ac0a228a70eafafb8a97f96", "size": 2945, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ChirpSignal.jl", "max_stars_repo_name": "sonosole/ChirpSignal", "max_stars_repo_head_hexsha": "18752dfddf43bd45e6e27c3a615bca7342a7ba5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-08-13T16:27:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T17:40:01.000Z", "max_issues_repo_path": "src/ChirpSignal.jl", "max_issues_repo_name": "sonosole/ChirpSignal", "max_issues_repo_head_hexsha": "18752dfddf43bd45e6e27c3a615bca7342a7ba5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ChirpSignal.jl", "max_forks_repo_name": "sonosole/ChirpSignal", "max_forks_repo_head_hexsha": "18752dfddf43bd45e6e27c3a615bca7342a7ba5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-08T17:40:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T17:40:05.000Z", "avg_line_length": 28.8725490196, "max_line_length": 111, "alphanum_fraction": 0.5487266553, "num_tokens": 1195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632956467157, "lm_q2_score": 0.9099070035949656, "lm_q1q2_score": 0.8438143575858553}} {"text": "# ------------------------------------------------------------------------------------------\n# Often used in machine learning, a \"one hot\" vector is a vector of all zeros, except for a\n# single `1` entry.\n# Representing it as a standard vector is memory-inefficient, so it cries out for a special\n# implementation.\n# ------------------------------------------------------------------------------------------\n\nstruct OneHotVector <: AbstractVector{Int}\n idx::Int\n len::Int\nend\n\nBase.size(v::OneHotVector) = (v.len,)\n\nBase.getindex(v::OneHotVector, i::Integer) = Int(i == v.idx)\n\nOneHotVector(3, 10)\n\nA = rand(5,5)\n\nA * OneHotVector(3, 5)\n\nVector(OneHotVector(3,5))\n\n# ------------------------------------------------------------------------------------------\n# ## Exercise\n#\n# Generalize it to any element type.\n# ------------------------------------------------------------------------------------------\n\n\n", "meta": {"hexsha": "5819b200ab9d6d69e11b4773dd4ba0eae9ef5d4c", "size": 912, "ext": "jl", "lang": "Julia", "max_stars_repo_path": ".nbexports/introductory-tutorials/intro-to-julia/long-version/130 OneHot Vector.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/130 OneHot Vector.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/130 OneHot Vector.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": 28.5, "max_line_length": 92, "alphanum_fraction": 0.4122807018, "num_tokens": 178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133531922388, "lm_q2_score": 0.8976952996340946, "lm_q1q2_score": 0.8437557992239934}} {"text": "using Base.MathConstants\n\nfunction getHarmonicNumber(n::Integer)::Float64\n H = 0\n for i = 1:n\n H = H + (1 / i)\n end\n return H\nend\n\nfunction getHarmonicNumberWithOrder(n::Integer, order::Integer)::Float64\n H = 0\n for i = 1:n\n H = H + (1 / i^order)\n end\n return H\nend\n\neulermascheroni = convert(Float64, γ)", "meta": {"hexsha": "76bfd4daf87d6835ab93278cc4ca991eef51c79b", "size": 342, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/harmonic.jl", "max_stars_repo_name": "EllianCarlos/number-theory-but-in-julia", "max_stars_repo_head_hexsha": "74368fee8002bc53031b8ef6026e72f806efe84d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/harmonic.jl", "max_issues_repo_name": "EllianCarlos/number-theory-but-in-julia", "max_issues_repo_head_hexsha": "74368fee8002bc53031b8ef6026e72f806efe84d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/harmonic.jl", "max_forks_repo_name": "EllianCarlos/number-theory-but-in-julia", "max_forks_repo_head_hexsha": "74368fee8002bc53031b8ef6026e72f806efe84d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.0, "max_line_length": 72, "alphanum_fraction": 0.6081871345, "num_tokens": 116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338101862455, "lm_q2_score": 0.8774767746654976, "lm_q1q2_score": 0.8437235864940534}} {"text": "using DrWatson\n@quickactivate \"StatReth\"\n\n# %%\nusing Plots\nusing Distributions\n\n# %%\nlen = 100\np = range(0, 1, length = len)\n\n# %%\nprior = ones(len)\nprior ./= sum(prior)\n\nlikelihood(w, l) = @. pdf(Binomial(w + l, p), w)\n\nfunction posterior(prior, likelih)\n post = prior .* likelih\n return post ./ sum(post)\nend\n\nposterior_a = posterior(prior, likelihood(3, 0)) # www\nposterior_b = posterior(prior, likelihood(3, 1)) # wwwl\nposterior_c = posterior(prior, likelihood(5, 2)) # lwwlwww\n\n# %%\nplot(xlabel = \"p\", ylabel = \"probability\", dpi = 200, legend = :topleft)\nplot!(p, posterior_a, label = \"a\")\nplot!(p, posterior_b, label = \"b\")\nplot!(p, posterior_c, label = \"c\")\n\n\n# %%\nprior = ones(len)\nprior[p .< 0.5] .= 0.0\nprior ./= sum(prior)\n\nposterior_a = posterior(prior, likelihood(3, 0)) # www\nposterior_b = posterior(prior, likelihood(3, 1)) # wwwl\nposterior_c = posterior(prior, likelihood(5, 2)) # lwwlwww\n\n# %%\nplot(xlabel = \"p\", ylabel = \"probability\", dpi = 200, legend = :topleft)\nplot!(p, posterior_a, label = \"a\")\nplot!(p, posterior_b, label = \"b\")\nplot!(p, posterior_c, label = \"c\")\n", "meta": {"hexsha": "aa496fbb722a3d8c4dfff065e8a13698d1bc3cf5", "size": 1102, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "exercises/ch02/2M1.jl", "max_stars_repo_name": "karajan9/statisticalrethinking", "max_stars_repo_head_hexsha": "e7516c468ca182c4b1c9cae0cfd0bb1feef7ed3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2020-06-03T14:18:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T16:52:26.000Z", "max_issues_repo_path": "exercises/ch02/2M1.jl", "max_issues_repo_name": "karajan9/statisticalrethinking", "max_issues_repo_head_hexsha": "e7516c468ca182c4b1c9cae0cfd0bb1feef7ed3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-06-13T05:56:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-12T14:05:57.000Z", "max_forks_repo_path": "exercises/ch02/2M1.jl", "max_forks_repo_name": "karajan9/statisticalrethinking", "max_forks_repo_head_hexsha": "e7516c468ca182c4b1c9cae0cfd0bb1feef7ed3c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-01T13:00:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-03T23:40:53.000Z", "avg_line_length": 22.9583333333, "max_line_length": 72, "alphanum_fraction": 0.6470054446, "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305360354471, "lm_q2_score": 0.875787001374006, "lm_q1q2_score": 0.8435847827863606}} {"text": "# ------------------------------------------------------------------\n# Licensed under the MIT License. See LICENSE in the project root.\n# ------------------------------------------------------------------\n\n\"\"\"\n signarea(p₁, p₂, p₃)\n\nCompute signed area of triangle formed\nby points `p₁`, `p₂` and `p₃`.\n\"\"\"\nfunction signarea(p₁::Point{2}, p₂::Point{2}, p₃::Point{2})\n a = coordinates(p₁)\n b = coordinates(p₂)\n c = coordinates(p₃)\n ((b[1]-a[1])*(c[2]-a[2]) - (b[2]-a[2])*(c[1]-a[1])) / 2\nend\n\n\"\"\"\n signarea(triangle)\n\nCompute the signed area of `triangle`.\n\"\"\"\nfunction signarea(t::Triangle{2})\n vs = vertices(t)\n signarea(vs[1], vs[2], vs[3])\nend\n\n\"\"\"\n sideof(point, segment)\n\nDetermines on which side of the oriented `segment`\nthe `point` lies. Possible results are `:LEFT`,\n`:RIGHT` or `:ON` the segment.\n\"\"\"\nfunction sideof(p::Point{2,T}, s::Segment{2,T}) where {T}\n a, b = vertices(s)\n area = signarea(p, a, b)\n ifelse(area > atol(T), :LEFT, ifelse(area < -atol(T), :RIGHT, :ON))\nend\n\n\"\"\"\n sideof(point, chain)\n\nDetermines on which side of the closed `chain` the\n`point` lies. Possible results are `:INSIDE` or\n`:OUTSIDE` the chain.\n\"\"\"\nfunction sideof(p::Point{2,T}, c::Chain{2,T}) where {T}\n w = windingnumber(p, c)\n ifelse(isapprox(w, zero(T), atol=atol(T)), :OUTSIDE, :INSIDE)\nend\n", "meta": {"hexsha": "e3532de295e17b06e8eaf414fa79e0dc79d96f59", "size": 1312, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "hyrodium/Meshes.jl", "max_stars_repo_head_hexsha": "02fb99be21c6d1f567e0886afe4997e75166f7e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-10T17:32:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-10T17:32:33.000Z", "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "hyrodium/Meshes.jl", "max_issues_repo_head_hexsha": "02fb99be21c6d1f567e0886afe4997e75166f7e0", "max_issues_repo_licenses": ["MIT"], "max_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": "hyrodium/Meshes.jl", "max_forks_repo_head_hexsha": "02fb99be21c6d1f567e0886afe4997e75166f7e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2307692308, "max_line_length": 69, "alphanum_fraction": 0.5670731707, "num_tokens": 409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305297023093, "lm_q2_score": 0.8757869997529962, "lm_q1q2_score": 0.8435847756784748}} {"text": "# Julia program to Find the Sum of Digits of a Number \n\n# Extracting Each digits\nfunction sum_of_digits(num)\n sum = 0\n while(num != 0)\n sum = sum + (num % 10)\n num = num ÷ 10\n end\n return sum\nend\n\nprint(\"Enter the number: \")\nnum = readline()\nnum = parse(Int, num)\nsum = sum_of_digits(abs(num))\nprintln(\"The sum of digits of the given number is $sum.\")\n\n\"\"\"\nTime Complexity: O(log(num)), where 'num' is the length of the given number\nSpace Complexity: O(1)\n\nSAMPLE INPUT AND OUTPUT\n\nSAMPLE 1\nEnter the number: -12\nThe sum of digits of the given number is 3.\n\nSAMPLE 2\nEnter the number: 43258\nThe sum of digits of the given number is 22.\n\n\"\"\"\n", "meta": {"hexsha": "984988d655390fa220e9abe9c79a7a841ea5bea9", "size": 667, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/math/sum_of_digits.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/sum_of_digits.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/sum_of_digits.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": 19.6176470588, "max_line_length": 75, "alphanum_fraction": 0.6731634183, "num_tokens": 188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533126145178, "lm_q2_score": 0.9046505325302034, "lm_q1q2_score": 0.8435443858162758}} {"text": "using Plots\r\nusing PrettyTables\r\n\r\ninclude(\"rfiod.jl\")\r\nusing Main.RFIOD\r\n\r\nio = stdout\r\n# Uncomment below to save to file instead\r\n# io = open(\"output.txt\", \"w\")\r\n\r\nF₁(x) = 2x - 3sin(x) + 5\r\nF₁′(x) = 2 - 3cos(x)\r\nF₁root = -2.8832368725582835\r\n\r\nF₂(x) = x^3 - 8.5x^2 + 20x - 8\r\nF₂′(x) = 3x^2 - 17x + 20\r\nF₂root = 4\r\n\r\n# -- Question 1 -- #\r\n\r\nq1plot = plot(F₁, -5:0.1:5, framestyle=:origin, legend = false, title = \"F₁(x) = 2x - 3sin(x) + 5 has a single real root in [-5,5]\")\r\n# F₁′(x) > 0 outside of this interval with F₁(-5) < 0, F₁(5) > 0, so no roots outside\r\n\r\n# -- Binary Search Programming Task -- #\r\nprintln(io, \"-- Binary Search Programming Task --\")\r\n\r\n# Initial interval [-5, 5]\r\nBSresult1 = binarysearch(F₁, -5, 5)\r\n# Initial interval [-5, 5], but with inputs swapped\r\nBSresult2 = binarysearch(F₁, 5, -5)\r\n# Initial interval [-2.88323688, -2.88323687]\r\nBSresult3 = binarysearch(F₁, -2.88323688, -2.88323687)\r\n# Initial interval [-100, 100]\r\nBSresult4 = binarysearch(F₁, -100, 100)\r\n\r\nprintln(io, \"Binary search with initial interval [a,b]\")\r\n# Table created for display\r\ntabledata = hcat(\r\n [-5, 5, -2.88323688, -100],\r\n [5, -5, -2.88323687, 100],\r\n Plots.unzip([BSresult1, BSresult2, BSresult3, BSresult4])...\r\n)\r\npretty_table(io, tabledata, header = [\"a\", \"b\", \"root\", \"iterations\"])\r\n\r\n# Initial interval [-1, 1], which does not contain a root\r\nBSresult5 = try binarysearch(F₁, -1, 1) catch ErrorException \"Error, root not found\" end\r\nprintln(io, \"Binary search with the invalid initial interval [-1, 1] gives:\")\r\nshow(io, BSresult5)\r\n\r\n# -- Question 3 -- #\r\nprintln(io, \"\\n\\n-- Question 3 --\")\r\n\r\nf(k) = x -> x - F₁(x)/(2+k)\r\n\r\n\"\"\"\r\n q3FPI(k, x₀, Nₘₐₓ, [ε])\r\n\r\nRun the fixed point iteration algorithm used in Question 3, with parameter `k` and starting value `x₀`.\r\n\r\nTerminate if consecutive iterations differ by less than `ε`, or after `Nₘₐₓ` iterations.\r\n\r\nOutputs a table to the REPL with the results, and returns a staircase/cobweb diagram.\r\n\r\n# Examples\r\n\r\n```julia-repl\r\njulia> q3FPI(3,-2,10)\r\nFixed point iteration with k = 3, Nₘₐₓ = 10\r\n┌─────┬──────────┬────────────┬───────────┐\r\n│ n │ xₙ │ ϵₙ │ ϵₙ/ϵₙ₋₁ │\r\n├─────┼──────────┼────────────┼───────────┤\r\n│ 0.0 │ -2.0 │ 0.883237 │ 0.0 │\r\n│ 1.0 │ -2.74558 │ 0.137658 │ 0.155857 │\r\n│ 2.0 │ -2.87879 │ 0.00444334 │ 0.032278 │\r\n│ 3.0 │ -2.88315 │ 9.00029e-5 │ 0.0202557 │\r\n│ 4.0 │ -2.88324 │ 1.79286e-6 │ 0.0199201 │\r\n│ 5.0 │ -2.88324 │ 3.57019e-8 │ 0.0199133 │\r\n└─────┴──────────┴────────────┴───────────┘\r\n```\r\n\r\n\"\"\"\r\nfunction q3FPI(k, x₀, Nₘₐₓ, ε = 1e-5)\r\n\r\n result = fixedpointiteration(f(k), x₀, Nₘₐₓ, ε)\r\n n = length(result) - 1\r\n\r\n errors = result .- F₁root\r\n errorratios = [0, (errors[2:(n+1)] ./ errors[1:n])...]\r\n tabledata = hcat(\r\n collect(0:n),\r\n result,\r\n errors,\r\n errorratios\r\n )\r\n println(io, \"Fixed point iteration with k = $k, Nₘₐₓ = $Nₘₐₓ\")\r\n pretty_table(io, tabledata, header = [\"n\", \"xₙ\", \"ϵₙ\", \"ϵₙ/ϵₙ₋₁\"])\r\n\r\n FPIplot = staircasediagram(f(k), result)\r\n plot!(FPIplot, title = \"k = $k\")\r\n return FPIplot\r\n\r\nend\r\n\r\n# k = 0, ε = 10⁻⁵, x₀ = -2, Nₘₐₓ = 10\r\nq3plot1 = q3FPI(0, -2, 10)\r\n\r\n# k = 4 gives monotonic convergence as f(8)'(x*) > 0\r\nq3plot2 = q3FPI(4, -2, 20)\r\n\r\n# k = 2 gives oscillatory convergence as f(1)'(x*) < 0\r\nq3plot3 = q3FPI(2, -2, 20)\r\n\r\n# k = 16, Nₘₐₓ = 50\r\nq3FPI(16, -2, 50)\r\n\r\n# -- Question 4 -- #\r\nprintln(io, \"\\n-- Question 4 --\")\r\n\r\ng(x) = x - F₂(x)/20\r\n\r\nq4result = fixedpointiteration(g, 5, 1000, 1e-5)\r\n# n and xₙ take the final values given below\r\nn = length(q4result) - 1\r\nxₙ = q4result[end]\r\nprintln(io, \"Fixed point iteration to find the double root of\r\nF₂(x) = x³ - 8.5x² + 20x - 8 results in n = $n iterations\r\nwith estimated root xₙ = $xₙ\")\r\n\r\n# -- Question 5 -- #\r\nprintln(io, \"\\n-- Question 5 --\")\r\n\r\n\"\"\"\r\n q5NR(f, x₀, Nₘₐₓ, root, order)\r\n\r\nRun the Newton-Raphson algorithm used in Question 5 on the function `f(x) = x - F(x)/F'(x)` starting at `x₀`\r\n\r\nTerminate the fixed point iteration after at most Nₘₐₓ iterations.\r\n\r\nOutputs a table with errors to `root` and error ratios of order `order`, and returns the vector of iterations.\r\n\r\n# Examples\r\n\r\n```julia-repl\r\njulia> q5NR(x -> x - sin(x)/cos(x), 3, 10, π, 2)\r\n┌─────┬─────────┬──────────────┬──────────────┐\r\n│ n │ xₙ │ ϵₙ │ ϵₙ/ϵₙ₋₁² │\r\n├─────┼─────────┼──────────────┼──────────────┤\r\n│ 0.0 │ 3.0 │ -0.141593 │ 0.0 │\r\n│ 1.0 │ 3.14255 │ 0.000953889 │ 0.0475791 │\r\n│ 2.0 │ 3.14159 │ -2.89316e-10 │ -0.000317963 │\r\n│ 3.0 │ 3.14159 │ 0.0 │ 0.0 │\r\n│ 4.0 │ 3.14159 │ 0.0 │ NaN │\r\n└─────┴─────────┴──────────────┴──────────────┘\r\n5-element Vector{Float64}:\r\n 3.0\r\n 3.142546543074278\r\n 3.141592653300477\r\n 3.141592653589793\r\n 3.141592653589793\r\n```\r\n\"\"\"\r\nfunction q5NR(f, x₀, Nₘₐₓ, root, order)\r\n result = fixedpointiteration(f, x₀, Nₘₐₓ)\r\n n = length(result) - 1\r\n errors = result .- root\r\n errorratios = [0, (errors[2:(n+1)] ./ errors[1:n].^order)...]\r\n tabledata = hcat(\r\n collect(0:n),\r\n result,\r\n errors,\r\n errorratios\r\n )\r\n pretty_table(io, tabledata, header = [\"n\", \"xₙ\", \"ϵₙ\", \"ϵₙ/ϵₙ₋₁\" * (order == 2 ? \"²\" : \"\")])\r\n return result\r\nend\r\n\r\n\"\"\"\r\n q5NRgraph(F, result, nlines)\r\nCreate a graph from the first `nvalues` iterations of `result`, coming from the Newton-Raphson algorithm on `F`.\r\n\r\n# Examples\r\n\r\n```julia-repl\r\njulia> q5NRgraph(sin, q5NR(x -> x - sin(x)/cos(x), 3, 10, π, 2), 4)\r\n``` \r\n\"\"\"\r\nfunction q5NRgraph(F, result, nlines)\r\n NRplot = scatter((result[1],F(result[1])), markercolor = :black, framestyle = :origin,\r\n title = \"Newton-Raphson with x₀ = $(result[1])\", legend = false)\r\n for n = 1:nlines\r\n plot!(NRplot, [result[n],result[n+1],result[n+1]],\r\n [F(result[n]), 0, F(result[n+1])], linecolor = :black)\r\n end\r\n plot!(NRplot, F, linecolor = :orange)\r\n return NRplot\r\nend\r\n\r\nf₁(x) = x - F₁(x)/F₁′(x)\r\nf₂(x) = x - F₂(x)/F₂′(x)\r\n\r\n# x₀ = 0 for F₁ gives divergence\r\nprintln(io, \"Newton-Raphson method for \\nF₁(x) = 2x - 3sin(x) + 5 with x₀ = 0\")\r\nq5result1 = q5NR(f₁, 0, 10, F₁root, 2)\r\nq5plot1 = q5NRgraph(F₁, q5result1, 4)\r\n\r\n# x₀ = -2 for F₁ gives convergence\r\nprintln(io, \"Newton-Raphson method for \\nF₁(x) = 2x - 3sin(x) + 5 with x₀ = -2\")\r\nq5result2 = q5NR(f₁, -2, 10, F₁root, 2)\r\nq5plot2 = q5NRgraph(F₁, q5result2, 2)\r\n\r\n# x₀ = 5 for F₂ gives convergence\r\nprintln(io, \"Newton-Raphson method for \\nF₂(x) = x³ - 8.5x² + 20x - 8 with x₀ = 5\")\r\nq5result3 = q5NR(f₂, 5, 50, F₂root, 1)\r\nq5plot3 = q5NRgraph(F₂, q5result3, 10)\r\n\r\n# Saves images automatically, uncomment to use\r\n#=\r\n\r\n# File extension e.g. \".png\", \".pdf\"\r\next = \".pdf\"\r\n\r\n# Makes a new directory for the images (or ignores the error if one exists already)\r\ntry\r\n mkdir(\"images\")\r\ncatch IOError\r\n nothing\r\nend\r\n\r\n# Saves the figures created above\r\ntry\r\n savefig(q1plot,\"images\\\\q1-singleroot$ext\")\r\n savefig(q3plot1,\"images\\\\q3-k0-graph$ext\")\r\n savefig(q3plot2,\"images\\\\q3-k4-graph$ext\")\r\n savefig(q3plot3,\"images\\\\q3-k2-graph$ext\")\r\n savefig(q5plot1,\"images\\\\q5-f1divergence-graph$ext\")\r\n savefig(q5plot2,\"images\\\\q5-f1convergence-graph$ext\")\r\n savefig(q5plot3,\"images\\\\q5-f2convergence-graph$ext\")\r\ncatch IOError\r\n println(\"Failed to save images\")\r\nend\r\n\r\n=#\r\n\r\nio == stdout || close(io)\r\nnothing", "meta": {"hexsha": "e72b5d16c1b9d7f32368fddb4e2f6c66a2abb10f", "size": 7375, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "introductoryproject/rfiod-run.jl", "max_stars_repo_name": "sje30/catam-julia", "max_stars_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-07-13T12:55:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:40:23.000Z", "max_issues_repo_path": "introductoryproject/rfiod-run.jl", "max_issues_repo_name": "sje30/catam-julia", "max_issues_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2021-07-11T21:35:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-25T12:10:58.000Z", "max_forks_repo_path": "introductoryproject/rfiod-run.jl", "max_forks_repo_name": "sje30/catam-julia", "max_forks_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-13T21:00:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-13T21:00:47.000Z", "avg_line_length": 30.1020408163, "max_line_length": 133, "alphanum_fraction": 0.5732881356, "num_tokens": 2875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436482, "lm_q2_score": 0.9161096175976053, "lm_q1q2_score": 0.8435442738856762}} {"text": "#md # ---\n\nusing DifferentialEquations, Plots\n\ng = 9.79 # Gravitational constants\nL = 1.00 # Length of the pendulum\n\n#Initial Conditions\nu₀ = [0, π / 60] # Initial speed and initial angle\ntspan = (0.0, 6.3) # time domain\n\n#Define the problem\nfunction simplependulum(du, u, p, t)\n θ = u[1]\n dθ = u[2]\n du[1] = dθ\n du[2] = -(g/L)*θ\nend\n\n#Pass to solvers\nprob = ODEProblem(simplependulum, u₀, tspan)\nsol = solve(prob, Tsit5(), reltol = 1e-6)\n#md nothing # hide\n\n#md # ---\n\n# Analytic solution\nu = u₀[2] .* cos.(sqrt(g / L) .* sol.t)\n\nplot(sol.t, getindex.(sol.u, 2), label = \"Numerical\")\nplot!(sol.t, u, label = \"Analytic\")\n#md savefig(\"pendulum1.svg\"); nothing # hide \n\n#md # ![](pendulum1.svg)\n\n#md # ---\n\n# [Numbers with Uncertainties](http://tutorials.juliadiffeq.org/html/type_handling/02-uncertainties.html)\n\nusing Measurements\n\ng = 9.79 ± 0.02; # Gravitational constants\nL = 1.00 ± 0.01; # Length of the pendulum\n\n#Initial Conditions\nu₀ = [0 ± 0, π / 60 ± 0.01] # Initial speed and initial angle\n\n#Define the problem\nfunction simplependulum(du, u, p, t)\n θ = u[1]\n dθ = u[2]\n du[1] = dθ\n du[2] = -(g/L)*θ\nend\n\n#Pass to solvers\nprob = ODEProblem(simplependulum, u₀, tspan)\nsol = solve(prob, Tsit5(), reltol = 1e-6);\nnothing # hide\n\n#md # ---\n\n# Analytic solution\nu = u₀[2] .* cos.(sqrt(g / L) .* sol.t)\n\nplot(sol.t, getindex.(sol.u, 2), label = \"Numerical\")\nplot!(sol.t, u, label = \"Analytic\")\n#md savefig(\"pendulum2.svg\"); nothing # hide \n\n#md # ![](pendulum2.svg)\n\n", "meta": {"hexsha": "ec81fb6c0d9089d7aa58b4e6e8f0aac5b078443c", "size": 1494, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/01.Measurements.jl", "max_stars_repo_name": "pnavaro/DiffEq", "max_stars_repo_head_hexsha": "42214888a98165b43caaa3bada1e0c8429821896", "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": "src/01.Measurements.jl", "max_issues_repo_name": "pnavaro/DiffEq", "max_issues_repo_head_hexsha": "42214888a98165b43caaa3bada1e0c8429821896", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/01.Measurements.jl", "max_forks_repo_name": "pnavaro/DiffEq", "max_forks_repo_head_hexsha": "42214888a98165b43caaa3bada1e0c8429821896", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.75, "max_line_length": 105, "alphanum_fraction": 0.6305220884, "num_tokens": 555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240160063031, "lm_q2_score": 0.8991213691605412, "lm_q1q2_score": 0.8434873497139728}} {"text": "using Statistics\n\n\"\"\"\n linear_regression(X::Matrix, Y::Matrix, alpha::Float64, iterations::Int64)\n\n Linear Regression Algorithm using Gradient Descent \n to find the best fit line for the data.\n \n Arguments :\n - X : Training data set of shape [m x n]\n - Y : Labels corresponding to the training data set of shape [m x 1]\n - alpha : Learning rate\n - iterations : Number of iterations to train\n Returns :\n - W : Weight vector \n - b : Bias\n - J_history : Cost Function History\n\n \n\n gradient_descent(W::Matrix, b, X::Matrix, Y::Matrix, alpha::Float64, num_iters::Int64)\n \n Performs gradient descent to learn W and b\n\n Arguments\n - `W`: matrix of weights\n - `b`: bias vector\n - `X`: matrix of features\n - `Y`: vector of labels\n - `alpha`: learning rate ( generally ranges from 0.01 to 0.00001 )\n - `num_iters`: number of iterations to run gradient descent\n\n Returns:\n - `W`: matrix of weights\n - `b`: bias vector\n - `J_history`: vector of cost values after each iteration\n\n\n \n # Contributors:- [Navaneeth Sharma](https://github.com/Navaneeth-Sharma) \n\"\"\"\n\nfunction gradient_descent(\n W::Matrix,\n b,\n X::Matrix,\n Y::Matrix,\n alpha::Float64,\n num_iters::Int64,\n)\n m = length(Y)\n J_history = []\n for i in 1:num_iters\n W = W - alpha .* (1 / m) * (X * (X'W .+ b - Y'))\n b = b - alpha .* (1 / m) * sum((X'W .+ b - Y'))\n push!(J_history, 1 / 2m * sum((X'W .+ b - Y') .^ 2))\n end\n return W, b, J_history\nend\n\nfunction linear_regression(\n X::Matrix,\n Y::Matrix,\n alpha::Float64,\n num_iters::Int64,\n)\n W = zeros(1, size(X, 1))\n b = 0\n W, b, J_history = gradient_descent(W, b, X, Y, alpha, num_iters)\n return W, b, J_history\nend\n\n# Function to predict the output of a given data vector\npredict(X::Matrix, W::Matrix, b::Float64) = X'W .+ b;\n\n# Example usage\nX = [1, 3, 2, 5, 7, 8, 8, 9, 10, 12]\nY = [2, 4, 3, 6, 8, 9, 9, 10, 11, 13]\n\nX = reshape(X, 1, length(X));\nY = reshape(Y, 1, length(Y));\n\nW, b, J_history = linear_regression(X, Y, 0.01, 1000);\n\noutput = predict(X, W, b)\nprintln(\"The predicted is: $output\")\n", "meta": {"hexsha": "9fe9018b22663f969585755ab22341d47c3bb60c", "size": 2226, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/machine_learning/linear_regression.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/machine_learning/linear_regression.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/machine_learning/linear_regression.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.5862068966, "max_line_length": 90, "alphanum_fraction": 0.5795148248, "num_tokens": 693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9728307716151472, "lm_q2_score": 0.8670357494949105, "lm_q1q2_score": 0.8434790571990513}} {"text": "\"A module to plot Ulam spirals\"\nmodule UlamSpiral\n\nimport PyPlot\nusing Primes\nimport Base: position\n \nexport position, text_spiral, point_spiral, plot_quadratic\n \n\"\"\" \n position(n[, start_n=1])\n\nCompute (x,y) location in the lattice spiral of the integer n, assuming the spiral\nstarts at the integer start_n (which takes default value 1).\n\n# Arguments\n- `n::Integer`: the integer to find the position of, N.B. n >= start_n\n- `start_n::Integer=1`: the starting integer of the spiral\n\n# Examples\n```jldoctest\njulia> UlamSpiral.position(23, 1)\n(0, -2)\n```\n\"\"\"\nfunction position( n::Integer, start_n::Integer=1 )\n if n text_spiral()\nPyPlot.Figure(PyObject )\n\njulia> text_spiral( 100; fontsize=16)\nPyPlot.Figure(PyObject )\n\njulia> text_spiral(fig_n=2, color_comp=\"white\", color_prime=\"black\", width=20, fontsize=10)\nPyPlot.Figure(PyObject )\n\n```\n\"\"\"\nfunction text_spiral(start_n::Integer=1;\n fontsize=20, color_prime=\"red\", color_comp=\"blue\", width=10, fig_n=1, clear=\"on\")\n c_x = Int(floor(width/2)) # centre of spiral\n c_y = Int(floor(width/2))\n stop_n = start_n + width^2 - 1;\n\n f = figure(fig_n)\n if clear==\"on\"\n clf()\n end\n hold(true)\n for n=start_n : stop_n\n (d_x, d_y) = UlamSpiral.position(n, start_n)\n if isprime(n)\n PyPlot.text(c_x + d_x, c_y + d_y, @sprintf(\"%d\", n), fontsize=fontsize, color=color_prime)\n else\n PyPlot.text(c_x + d_x, c_y + d_y, @sprintf(\"%d\", n), fontsize=fontsize, color=color_comp)\n end\n end\n PyPlot.xlim(0, width+1)\n PyPlot.ylim(0, width+1)\n return f\nend\n\n\n\"\"\"\n point_spiral( [start_n] )\n\nPlot points at numbers in an Ulam spiral starting from start_n.\n\n# Arguments\n- `start_n::Integer=1`: the starting integer of the spiral\n\n# Keyword Arguments\n- `marker=\"o\": the marker to use\n- `markersize=7`: the size of the markers being plotted\n- `color=\"red\"`: the color to use (this routine only plots prime numbers)\n- `width=10`: the width of the square used (which determines how many numbers to plot)\n- `fig_n=1`: the figure on which to plot everything\n- `clear=\"on\"`: whether to clear the previous figure \n\n# Examples\n```jldoctest\njulia> point_spiral()\nPyPlot.Figure(PyObject )\n\njulia> point_spiral( 1000; markersize=10)\nPyPlot.Figure(PyObject )\n\njulia> point_spiral(fig_n=2, markersize=1, color=\"black\", width=200)\nPyPlot.Figure(PyObject )\n\njulia> text_spiral(fig_n=2, color_comp=\"white\", color_prime=\"black\", width=20, fontsize=10)\njulia> point_spiral(fig_n=2, markersize=3, marker=\"s\", color=\"green\", width=20, clear=\"off\")\nPyPlot.Figure(PyObject )\n\n```\n\"\"\"\nfunction point_spiral(start_n::Integer=1;\n marker=\"o\", markersize=7, color=\"red\", width=100, fig_n=1, clear=\"on\")\n c_x = Int(floor(width/2)) # centre of spiral\n c_y = Int(floor(width/2))\n stop_n = start_n + width^2 - 1;\n\n f = figure(fig_n)\n if clear==\"on\"\n clf()\n end\n hold(true)\n for n=primes(start_n, stop_n)\n (d_x, d_y) = UlamSpiral.position(n, start_n)\n PyPlot.plot(c_x + d_x, c_y + d_y; marker=marker, markersize=markersize, color=color)\n end\n PyPlot.xlim(0, width+1)\n PyPlot.ylim(0, width+1)\n return f\nend\n\n\n\n\"\"\"\n plot_quadratic(a, b, c)\n\nHighlight points on the quadratic ax^2 + bx + c. Presumes you have already \nrun point_spiral with the same width parameter.\n\n# Arguments\n- `a::Integer = 4`: quadratic coefficient\n- `b::Integer = -2`: linear coefficient\n- `c::Integer = 41`: constant coefficient\n\n# Keyword Arguments\n- `start_n=1` the starting integer of the spiral\n- `marker=\"o\": the marker to use\n- `markersize=7`: the size of the markers being plotted\n- `color_prime=\"blue\"`: the color to use for prime numbers\n- `color_comp=\"white\"`: the color to use for compositive numbers\n- `width=10`: the width of the square used (should be the same as previous plot)\n- `fig_n=1`: the figure on which to plot everything (should be the same as previous plot)\n\n# Examples\n```jldoctest\njulia> point_spiral(fig_n=2, markersize=1, color=\"black\", width=200);\njulia> plot_quadratic(; fig_n=2, width=200);\njulia> plot_quadratic(4, 2, 41; fig_n=2, width=200, color_prime=\"green\");\n```\n\"\"\"\nfunction plot_quadratic(a::Integer=4, b::Integer=-2, c::Integer=41;\n start_n=1, width=10, fig_n=1,\n marker=\"o\", markersize=7, color_prime=\"red\", color_comp=\"white\")\n c_x = Int(floor(width/2)) # centre of spiral\n c_y = Int(floor(width/2))\n stop_n = start_n + width^2 - 1;\n rad = 0\n x = start_n - 1\n while rad <= width/2\n x = nextprime(x+1)\n n = a*x^2 + b*x + c\n if n>0\n (d_x, d_y) = UlamSpiral.position(n, start_n);\n rad = max( abs(d_x), abs(d_y) )\n plot(c_x + d_x, c_y + d_y, marker=marker, color=color_prime, markersize=markersize)\n end\n end\n # at present not plotting composite numbers at all\nend\n\nend # module\n", "meta": {"hexsha": "6e98f18cc7fb8f061e7fd51d84e8e4e8ae4c1d0a", "size": 6765, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/UlamSpiral.jl", "max_stars_repo_name": "mroughan/UlamSpiral.jl", "max_stars_repo_head_hexsha": "bc493e19c8875826e92e7117c2fd5e49cdf94ba3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/UlamSpiral.jl", "max_issues_repo_name": "mroughan/UlamSpiral.jl", "max_issues_repo_head_hexsha": "bc493e19c8875826e92e7117c2fd5e49cdf94ba3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/UlamSpiral.jl", "max_forks_repo_name": "mroughan/UlamSpiral.jl", "max_forks_repo_head_hexsha": "bc493e19c8875826e92e7117c2fd5e49cdf94ba3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6121495327, "max_line_length": 102, "alphanum_fraction": 0.6415373245, "num_tokens": 2066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810407096791, "lm_q2_score": 0.8902942319436397, "lm_q1q2_score": 0.8434478759965898}} {"text": "module ProjectEuler\n\ninclude(\"utils.jl\")\nusing .Utils\n\n\nfunction problem001()\n #=\n Problem 1:\n If we list all the natural numbers below 10 that are multiples of 3 or 5, \n we get 3, 5, 6 and 9. The sum of these multiples is 23.\n Find the sum of all the multiples of 3 or 5 below 1000.\n =#\n return sum(i for i in 1:999 if i%3==0 || i%5==0) # => 234168\nend\n\nfunction problem002()\n #=\n Problem 2:\n Each new term in the Fibonacci sequence is generated by \n adding the previous two terms. By starting with 1 and 2, \n the first 10 terms will be:\n 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...\n By considering the terms in the Fibonacci sequence whose \n values do not exceed four million, find the sum of the \n even-valued terms.\n =#\n sum = 0\n f1,f2 = 1,1\n while f1 <= 4_000_000\n f1, f2 = f1+f2, f1\n if f1 % 2 == 0\n sum += f1\n end\n end\n return sum\nend\n\nfunction problem003()\n #=\n Problem 3:\n The prime factors of 13195 are 5, 7, 13 and 29.\n What is the largest prime factor of the number 600851475143 ?\n =#\n factors = Utils.factorize(600851475143)\n return maximum(i -> i[1],factors) # largest factor\nend\n\nfunction problem004()\n #=\n Problem 4:\n A palindromic number reads the same both ways. The \n largest palindrome made from the product of two 2-digit \n numbers is 9009 = 91 × 99.\n\n Find the largest palindrome made from the product of two \n 3-digit numbers.\n =#\n palindrome_products = (i*j for i=100:999, j=100:999 if string(i*j)==reverse(string(i*j)))\n return maximum(palindrome_products)\nend\n\nfunction problem005()\n #=\n Problem 5:\n 2520 is the smallest number that can be divided by each of \n the numbers from 1 to 10 without any remainder.\n\n What is the smallest positive number that is evenly \n divisible by all of the numbers from 1 to 20?\n =#\n\n # The desired number will be the product of the factors of\n # each number from 1 to 20, excluding duplicates. For example,\n # 16 = 2^4, so that also covers 2,4,and 8\n return (2^4 * # 2,4,8,16\n 3^2 * # 3, 9\n 5 *\n 7 *\n 11 *\n 13 *\n 17 *\n 19\n )\nend\n\nfunction problem006()\n #=\n Problem 6:\n The sum of the squares of the first ten natural numbers is,\n 1^2 + 2^2 + ... + 10^2 = 385\n The square of the sum of the first ten natural numbers is,\n (1 + 2 + ... + 10)^2 = 55^2 = 3025\n Hence the difference between the sum of the squares of the \n first ten natural numbers and the square of the sum is \n 3025 − 385 = 2640.\n Find the difference between the sum of the squares of the first \n one hundred natural numbers and the square of the sum.\n =#\n return sum(1:100)^2 - sum(i^2 for i=1:100)\nend\n\nfunction problem007()\n #=\n Problem 7:\n By listing the first six prime numbers: \n 2, 3, 5, 7, 11, and 13, \n we can see that the 6th prime is 13.\n What is the 10,001'st prime number?\n =#\n for (i,p) in enumerate(Utils.Primes())\n if i == 10001\n return p\n end\n end\nend\n\nfunction problem008()\n #=\n Problem 8\n The four adjacent digits in the 1000-digit number that \n have the greatest product are 9 × 9 × 8 × 9 = 5832.\n\n 73167176531330624919225119674426574742355349194934\n 96983520312774506326239578318016984801869478851843\n 85861560789112949495459501737958331952853208805511\n 12540698747158523863050715693290963295227443043557\n 66896648950445244523161731856403098711121722383113\n 62229893423380308135336276614282806444486645238749\n 30358907296290491560440772390713810515859307960866\n 70172427121883998797908792274921901699720888093776\n 65727333001053367881220235421809751254540594752243\n 52584907711670556013604839586446706324415722155397\n 53697817977846174064955149290862569321978468622482\n 83972241375657056057490261407972968652414535100474\n 82166370484403199890008895243450658541227588666881\n 16427171479924442928230863465674813919123162824586\n 17866458359124566529476545682848912883142607690042\n 24219022671055626321111109370544217506941658960408\n 07198403850962455444362981230987879927244284909188\n 84580156166097919133875499200524063689912560717606\n 05886116467109405077541002256983155200055935729725\n 71636269561882670428252483600823257530420752963450\n\n Find the thirteen adjacent digits in the 1000-digit number \n that have the greatest product. What is the value \n of this product?\n =#\n\n number_str = \"\"\"\n 73167176531330624919225119674426574742355349194934\n 96983520312774506326239578318016984801869478851843\n 85861560789112949495459501737958331952853208805511\n 12540698747158523863050715693290963295227443043557\n 66896648950445244523161731856403098711121722383113\n 62229893423380308135336276614282806444486645238749\n 30358907296290491560440772390713810515859307960866\n 70172427121883998797908792274921901699720888093776\n 65727333001053367881220235421809751254540594752243\n 52584907711670556013604839586446706324415722155397\n 53697817977846174064955149290862569321978468622482\n 83972241375657056057490261407972968652414535100474\n 82166370484403199890008895243450658541227588666881\n 16427171479924442928230863465674813919123162824586\n 17866458359124566529476545682848912883142607690042\n 24219022671055626321111109370544217506941658960408\n 07198403850962455444362981230987879927244284909188\n 84580156166097919133875499200524063689912560717606\n 05886116467109405077541002256983155200055935729725\n 71636269561882670428252483600823257530420752963450\n \"\"\"\n number = reshape(readdlm(IOBuffer(strip(replace(number_str,\"\",\" \"))),Int)',1,:) # 1x1000 array\n products = (prod(number[i:(i+12)]) for i in 1:(length(number)-12)) # get product of every rolling 13-digit subarray\n return maximum(products)\nend\n\nfunction problem009()\n #=\n Problem 9:\n A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,\n a^2 + b^2 = c^2\n For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.\n\n There exists exactly one Pythagorean triplet for which a + b + c = 1000.\n Find the product abc.\n =#\nend\n\nend # module\n", "meta": {"hexsha": "386636b2de7728a70cd7a71281f4d09f7d88ae77", "size": 6479, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ProjectEuler.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/ProjectEuler.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/ProjectEuler.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": 34.1, "max_line_length": 119, "alphanum_fraction": 0.6942429387, "num_tokens": 2043, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9748211582993981, "lm_q2_score": 0.8652240930029117, "lm_q1q2_score": 0.8434387525296445}} {"text": "# # [Function approximation](@id function-approximation-example)\n#\n# The objective of this example is to approximate a known function ``f`` by a\n# spline.\n#\n# ## Exact function\n#\n# We consider the function ``f(x) = e^{-x} \\cos(8πx)`` in the interval\n# ``x ∈ [0, 1]``.\n\nusing CairoMakie\nCairoMakie.activate!(type = \"svg\")\n\nx_interval = 0..1\nf(x) = exp(-x) * cospi(8x)\n\nfig = Figure(resolution = (800, 600))\nax = Axis(fig[1, 1]; xlabel = \"x\")\nlines!(ax, x_interval, f)\nfig\n\n# ## Approximation space\n\n# To approximate this function using a spline, we first need to define a\n# B-spline basis ``\\{ b_i \\}_{i = 1}^N`` describing a spline space.\n# The approximating spline can then be written as\n#\n# ```math\n# g(x) = ∑_{i = 1}^N c_i b_i(x),\n# ```\n#\n# where the ``c_i`` are the B-spline coefficients describing the spline.\n# The objective is thus to find the coefficients ``c_i`` that result in the best\n# possible approximation of the function ``f``.\n#\n# Here we use splines of order ``k = 4`` (polynomial degree ``d = 3``, i.e.\n# cubic splines).\n# For simplicity, we choose the B-spline knots to be uniformly distributed.\n\nusing BSplineKit\n\nξs = range(x_interval; length = 15)\nB = BSplineBasis(BSplineOrder(4), ξs)\n\n# We plot below the knots and the basis functions describing the spline space.\n# Note that knots are represented by grey crosses.\n\nfunction plot_knots!(ax, ts; ybase = 0, knot_offset = 0.03, kws...)\n ys = zero(ts) .+ ybase\n ## Add offset to distinguish knots with multiplicity > 1\n if knot_offset !== nothing\n for i in eachindex(ts)[(begin + 1):end]\n if ts[i] == ts[i - 1]\n ys[i] = ys[i - 1] + knot_offset\n end\n end\n end\n scatter!(ax, ts, ys; marker = :x, color = :gray, markersize = 16, kws...)\n ax\nend\n\nfunction plot_basis!(ax, B; eval_args = (), kws...)\n cmap = cgrad(:tab20)\n N = length(B)\n ts = knots(B)\n hlines!(ax, 0; color = :gray)\n for (n, bi) in enumerate(B)\n color = cmap[(n - 1) / (N - 1)]\n i, j = extrema(support(bi))\n lines!(ax, ts[i]..ts[j], x -> bi(x, eval_args...); color, linewidth = 2.5)\n end\n plot_knots!(ax, ts; kws...)\n ax\nend\n\nfig = Figure(resolution = (800, 600))\nax = Axis(fig[1, 1]; xlabel = \"x\", ylabel = \"bᵢ(x)\")\nplot_basis!(ax, B; knot_offset = 0.05)\nfig\n\n# ## Approximating the function\n#\n# Three different methods are implemented in BSplineKit to approximate\n# functions.\n# In increasing order of accuracy and complexity, these are:\n#\n# ### 1. [`VariationDiminishing`](@ref)\n#\n# Implements Schoenberg's variation diminishing approximation.\n# This simply consists on estimating the spline coefficients as ``c_i =\n# f(x_i)``, where the ``x_i`` are the Greville sites.\n# These are obtained by window-averaging the B-spline knots ``t_j``:\n#\n# ```math\n# x_i = \\frac{1}{k - 1} ∑_{j = 1}^{k - 1} t_{i + j}.\n# ```\n#\n# This approximation is expected to preserve the shape of the function.\n# However, as shown below, it is usually very inaccurate as an actual\n# approximation, and should only be used when a qualitative estimation of ``f``\n# is sufficient.\n\nS_vd = approximate(f, B, VariationDiminishing())\n\n# ### 2. [`ApproxByInterpolation`](@ref)\n#\n# Approximates the original function by interpolating on a discrete set of\n# interpolation points.\n# In other words, the resulting spline exactly matches ``f`` at those points.\n#\n# By default, the interpolation points are chosen as the Greville sites\n# associated to the B-spline basis (using [`collocation_points`](@ref); see also\n# [`Collocation.AvgKnots`](@ref)).\n# For more control, the interpolation points may also be directly set via the\n# [`ApproxByInterpolation`](@ref) constructor.\n#\n# In the below example, we pass the B-spline basis to the\n# `ApproxByInterpolation` constructor, which automatically determines the\n# collocation points as explained above.\n\nS_interp = approximate(f, B, ApproxByInterpolation(B)) # or simply approximate(f, B)\n\n# ### 3. [`MinimiseL2Error`](@ref)\n#\n# Approximates the function by minimising the ``L^2`` distance between ``f`` and\n# its spline approximation ``g``.\n#\n# In other words, it minimises\n# ```math\n# \\mathcal{L}[g] = {\\left\\lVert f - g \\right\\rVert}^2 = \\left< f - g, f - g \\right>,\n# ```\n# where\n# ```math\n# \\left< u, v \\right> = ∫_a^b u(x) \\, v(x) \\, \\mathrm{d}x\n# ```\n# is the inner product between two functions, and ``a`` and ``b`` are the\n# boundaries of the prescribed B-spline basis.\n#\n# One can show that the optimal coefficients ``c_i`` minimising the ``L^2`` error\n# are the solution to the linear system ``\\bm{M} \\bm{c} = \\bm{φ}``,\n# where ``M_{ij} = \\left< b_i, b_j \\right>`` and ``φ_i = \\left< b_i, f \\right>``.\n# These two terms are respectively computed by [`galerkin_matrix`](@ref) and\n# [`galerkin_projection`](@ref).\n#\n# Indeed, this can be shown by taking the differential\n# ```math\n# δ\\mathcal{L}[g] = \\mathcal{L}[g + δg] - \\mathcal{L}[g]\n# = 2 \\left< δg, g - f \\right>,\n# ```\n# where ``δg`` is a small perturbation of the spline ``g``.\n# The optimal spline ``g^*``, minimising the ``L^2`` distance, is such that\n# ``δ\\mathcal{L}[g^*] = 0``.\n#\n# Noting that ``g = c_i b_i`` (where summing is implicitly performed over\n# repeated indices), the perturbation is given by ``δg = δc_i b_i``, as the\n# B-spline basis is assumed fixed.\n# The optimal spline then satisfies\n# ```math\n# \\left< b_i, g^* - f \\right> δc_i\n# = \\left[ \\left< b_i, b_j \\right> c_j^* - \\left< b_i, f \\right> \\right] δc_i\n# = \\left[ M_{ij} c_j^* - φ_i \\right] δc_i\n# = 0\n# ```\n# for all perturbations ``δ\\bm{c}``, leading to the linear system stated above.\n#\n# As detailed in [`galerkin_projection`](@ref), integrals are computed via\n# Gauss--Legendre quadratures, in a way that ensures that the result is exact\n# when ``f`` is a polynomial of degree up to ``k - 1`` (or more generally, a\n# spline belonging to the space spanned by the chosen B-spline basis).\n\nS_minL2 = approximate(f, B, MinimiseL2Error())\n\n# ## Method comparison\n#\n# Below, the approximations using the three methods are compared to the actual\n# function ``f``.\n\nfig = Figure(resolution = (1000, 750))\ncolours = theme(fig.scene).palette.color[]\nstyle_vd = (color = colours[3], label = \"Variation diminishing\")\nstyle_interp = (color = colours[2], label = \"Interpolation\")\nstyle_minL2 = (color = colours[1], label = \"L² minimisation\")\nlet ax = Axis(fig[1:2, 1]; xlabel = \"x\", ylabel = \"Approximation\")\n plot_knots!(ax, knots(B); knot_offset = nothing)\n lines!(ax, x_interval, f; color = :black, linewidth = 2, label = \"Original\")\n lines!(ax, x_interval, x -> S_vd(x); style_vd...)\n lines!(ax, x_interval, x -> S_interp(x); style_interp...)\n lines!(ax, x_interval, x -> S_minL2(x); style_minL2...)\n axislegend(ax)\nend\nlet ax = Axis(fig[1, 2]; ylabel = \"Difference with original\")\n plot_knots!(ax, knots(B); knot_offset = nothing)\n lines!(ax, x_interval, x -> S_interp(x) - f(x); style_interp...)\n lines!(ax, x_interval, x -> S_minL2(x) - f(x); style_minL2...)\n hidexdecorations!(ax; grid = false)\n axislegend(ax; position = :rt, orientation = :horizontal)\nend\nlet ax = Axis(fig[2, 2]; xlabel = \"x\", ylabel = \"Squared difference\", yscale = log10)\n ylims!(1e-8, 1e-2)\n plot_knots!(ax, knots(B); knot_offset = nothing, ybase = 1e-6)\n lines!(ax, x_interval, x -> abs2(S_interp(x) - f(x)); style_interp...)\n lines!(ax, x_interval, x -> abs2(S_minL2(x) - f(x)); style_minL2...)\nend\nfig\n\n# As seen above, the **variation diminishing approximation**, while capturing the\n# shape of the original function, doesn't really provide an accurate\n# approximation of it.\n#\n# The other two methods are much more accurate.\n# On the right half of the figure, a detailed comparison of the two is provided,\n# by plotting the difference between each approximation and the actual ``f``\n# function.\n#\n# The **interpolation method** works pretty well, matching exactly the actual\n# function at the interpolation points.\n# Note that, in this example, most interpolation points match the spline knots.\n# This is because we're using splines of even degree (``k = 4``) and because\n# knots are uniformly spaced.\n#\n# Nevertheless, when looking at the global error, the **``L^2`` minimisation\n# method** works best, as expected.\n# In particular, as seen above, it reduces the maximum approximation error (i.e.\n# the ``L^∞`` distance, ``{\\left\\lVert f - g \\right\\rVert}_∞ = \\max |f(x) -\n# g(x)|``) compared to the interpolation approach.\n", "meta": {"hexsha": "4ce9ab60b581a494153231b1cb722787ee42a373", "size": 8451, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/approximation.jl", "max_stars_repo_name": "jipolanco/BasisSplines", "max_stars_repo_head_hexsha": "16c689d6464adc9f467b451fe17df3221df67c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2020-11-03T21:11:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T19:09:34.000Z", "max_issues_repo_path": "examples/approximation.jl", "max_issues_repo_name": "jipolanco/BasisSplines", "max_issues_repo_head_hexsha": "16c689d6464adc9f467b451fe17df3221df67c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 21, "max_issues_repo_issues_event_min_datetime": "2020-06-29T07:46:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T16:25:06.000Z", "max_forks_repo_path": "examples/approximation.jl", "max_forks_repo_name": "jipolanco/BasisSplines", "max_forks_repo_head_hexsha": "16c689d6464adc9f467b451fe17df3221df67c8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3938053097, "max_line_length": 85, "alphanum_fraction": 0.6659566915, "num_tokens": 2544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765163620469, "lm_q2_score": 0.9230391605990604, "lm_q1q2_score": 0.8433592047218975}} {"text": "struct Point\n x::Float64\n y::Float64\nend\n\nfunction ccw(a::Point, b::Point, c::Point)\n return ((b.x - a.x)*(c.y - a.y) - (b.y - a.y)*(c.x - a.x))\nend\n\nfunction graham_scan!(points::Vector{Point})\n N = length(points)\n\n # Place the lowest point at the start of the array\n sort!(points, by = item -> item.y)\n\n # Sort all other points according to angle with that point\n other_points = sort(points[2:end], by = item -> atan(item.y - points[1].y,\n item.x - points[1].x))\n\n # Place points sorted by angle back into points vector\n for i in 1:length(other_points)\n points[i+1] = other_points[i]\n end\n\n # M will be the point on the hull\n M = 2\n for i = 1:N\n while (ccw(points[M-1], points[M], points[i]) <= 0)\n if (M > 2)\n M -= 1\n # All points are collinear\n elseif (i == N)\n break\n else\n i += 1\n end\n end\n\n # ccw point found, updating hull and swapping points\n M += 1\n points[i], points[M] = points[M], points[i]\n end\n\n return points[1:M]\nend\n\nfunction main()\n # This hull is just a simple test so we know what the output should be\n points = [\n Point(-5.,2), Point(5,7), Point(-6,-12), Point(-14,-14), Point(9,9),\n Point(-1,-1), Point(-10,11), Point(-6,15), Point(-6,-8), Point(15,-9),\n Point(7,-7), Point(-2,-9), Point(6,-5), Point(0,14), Point(2,8)\n ]\n hull = graham_scan!(points)\n println(hull)\nend\n\nmain()\n\n", "meta": {"hexsha": "75bfc68f12013d1424ed9741d2cc1b1860fc4b10", "size": 1584, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "contents/graham_scan/code/julia/graham.jl", "max_stars_repo_name": "arguiot/algorithm-archive", "max_stars_repo_head_hexsha": "c53c7627529b50e598884f32fdf78f3765291920", "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/graham_scan/code/julia/graham.jl", "max_issues_repo_name": "Aarif1430/algorithm-archive", "max_issues_repo_head_hexsha": "1bb82d96c5edc03922918dda0c818bbbcd08417f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-10-03T20:52:20.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-03T20:52:20.000Z", "max_forks_repo_path": "contents/graham_scan/code/julia/graham.jl", "max_forks_repo_name": "Aarif1430/algorithm-archive", "max_forks_repo_head_hexsha": "1bb82d96c5edc03922918dda0c818bbbcd08417f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-17T09:17:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-17T09:17:56.000Z", "avg_line_length": 26.4, "max_line_length": 79, "alphanum_fraction": 0.5214646465, "num_tokens": 463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172601537141, "lm_q2_score": 0.8887588038050466, "lm_q1q2_score": 0.8433585690441772}} {"text": "## Exercise 4-6\n## Write a function called circle that takes a turtle, t, and radius, r, as parameters and that draws an approximate circle by calling polygon with an appropriate length and number of sides. Test your function with a range of values of r.\n\n## TIP\n## Figure out the circumference of the circle and make sure that len * n == circumference.\nusing ThinkJulia\n\nprintln(\"Ans: \")\n\nfunction polygon(turtle::Turtle, nsides::Int, len::Int = 100)\n angle = (360 / nsides)\n\n for i in 1:nsides\n forward(turtle, len)\n turn(turtle, -angle)\n end\nend\n\nfunction circle(turtle::Turtle, radius::Int)\n circumference = 2 * π * radius\n n = Int(trunc(circumference ÷ 3) + 3) \n len = Int(trunc(circumference / n))\n @show n, len\n polygon(turtle, n, len)\nend\n\n@svg begin\n turtle = Turtle()\n circle(turtle, 100)\nend\n\nprintln(\"End.\")\n", "meta": {"hexsha": "e770a62be0b84d182098515e4f687141b72827aa", "size": 864, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chapter4/ex6.jl", "max_stars_repo_name": "yashppawar/ThinkJuliaExercises.jl", "max_stars_repo_head_hexsha": "72145b969dc51ebcac413a10004175ebc63cd5c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-13T14:11:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T14:11:30.000Z", "max_issues_repo_path": "Chapter4/ex6.jl", "max_issues_repo_name": "yashppawar/ThinkJuliaExercises.jl", "max_issues_repo_head_hexsha": "72145b969dc51ebcac413a10004175ebc63cd5c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter4/ex6.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.1818181818, "max_line_length": 238, "alphanum_fraction": 0.6759259259, "num_tokens": 243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9648551566309689, "lm_q2_score": 0.8740772253241803, "lm_q1q2_score": 0.8433579181477247}} {"text": "\"\"\"\n entropy(decisionMat)\n\nApply Entropy method for a given matrix and criteria types.\n\n# Arguments:\n - `decisionMat::DataFrame`: n × m matrix of objective values for n alternatives and m criteria \n\n# Description \nentropy() applies the Entropy method to calculate objective weights which are obtained through multi-step calculations of the decision matrix constructed from the actual information about the evaluation criteria of the alternatives.\n\n# Output \n- `::EntropyResult`: EntropyResult object that holds multiple outputs including weighting and best index.\n\n# Examples\n```julia-repl\n\njulia> df = DataFrame(\n C1 = [2, 4, 3, 5, 4, 3],\n C2 = [1, 1, 2, 1, 2, 2],\n C3 = [4, 5, 6, 5, 5, 6],\n C4 = [7, 6, 6, 7, 6, 6],\n C5 = [6, 7, 5, 6, 7, 6],\n C6 = [6, 7, 6, 7, 7, 6],\n C7 = [7, 6, 8, 7, 6, 6],\n C8 = [3000, 3500, 4000, 3000, 3000, 3500]\n )\n6×8 DataFrame\n Row │ C1 C2 C3 C4 C5 C6 C7 C8 \n │ Int64 Int64 Int64 Int64 Int64 Int64 Int64 Int64 \n─────┼────────────────────────────────────────────────────────\n 1 │ 2 1 4 7 6 6 7 3000\n 2 │ 4 1 5 6 7 7 6 3500\n 3 │ 3 2 6 6 5 6 8 4000\n 4 │ 5 1 5 7 6 7 7 3000\n 5 │ 4 2 5 6 7 7 6 3000\n 6 │ 3 2 6 6 6 6 6 3500\n\njulia> result = entropy(df);\n\njulia> result.w\n8-element Array{Float64,1}:\n 0.29967360959745126\n 0.441367338923551\n 0.07009088719659533\n 0.021238237112072383\n 0.0490229289460051\n 0.023080378850660263\n 0.0477633096868323\n 0.0477633096868323\n\njulia> result.bestIndex\n2\n```\n# References\n\nShannon, C. E. (1948). A Mathematical Theory of Communication. Bell System Technical Journal, 27(3), 379–423. doi:10.1002/j.1538-7305.1948.tb01338.x\nUlutaş, A . (2019). Entropi ve MABAC Yöntemleri ile Personel Seçimi. OPUS Uluslararası Toplum Araştırmaları Dergisi, 13 (19), 1552-1573. DOI: 10.26466/opus.580456.\n\n\"\"\"\nfunction entropy(decisionMat::DataFrame):EntropyResult\n \n row, col = size(decisionMat)\n normalizeDM = zeros(Float64, row, col)\n\n for i in 1:col\n normalizeDM[:, i] = decisionMat[:,i] ./ sum(decisionMat[:, i])\n end\n\n logMat = zeros(Float64, row, col)\n for i in 1:row\n for j in 1:col\n logMat[i,j] = normalizeDM[i, j] .* log(normalizeDM[i, j])\n end \n end\n\n e = zeros(Float64, col)\n\n for i in 1:col\n e[i] = 1 - sum(logMat[:,i]) ./ -log(row)\n end\n\n w = zeros(Float64, col)\n \n for i in 1:col\n w[i] = e[i] ./ sum(e)\n end\n \n rankings = sortperm(w)\n \n bestIndex = rankings |> last\n \n result = EntropyResult(\n decisionMat,\n w,\n rankings,\n bestIndex\n )\n\n return result\nend\n", "meta": {"hexsha": "0a8100ce79a307ed3f615c0b889b962335b74d01", "size": 2924, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/entropy.jl", "max_stars_repo_name": "drvinceknight/JMcDM", "max_stars_repo_head_hexsha": "89bec7ead2a7553f9e58fc75f37b5b89a30582fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/entropy.jl", "max_issues_repo_name": "drvinceknight/JMcDM", "max_issues_repo_head_hexsha": "89bec7ead2a7553f9e58fc75f37b5b89a30582fa", "max_issues_repo_licenses": ["MIT"], "max_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": "drvinceknight/JMcDM", "max_forks_repo_head_hexsha": "89bec7ead2a7553f9e58fc75f37b5b89a30582fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6666666667, "max_line_length": 232, "alphanum_fraction": 0.5448016416, "num_tokens": 1040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660949832346, "lm_q2_score": 0.8840392848011834, "lm_q1q2_score": 0.8433435043335565}} {"text": "\"\"\"\nFamily of nonlinear transformation parametrized by λ that defaults to Box Cox\n\"\"\"\nstruct nonlinearTransform{T1<:Function, T2<:Function, T3<:Function, T4<:Function, T5<:Function, T6<:Function, T7<:Function}\n f::T1\n df::T2\n d2f::T3 \n df_hyp::T4 \n d2f_hyp::T5 \n d_mixed::T6 \n inv::T7 \nend\n\n\n@doc raw\"\"\"\n BoxCox(λ::Real)\n\nThe Box-Cox power transformation function with parameter λ.\n\n```math\ng_\\lambda(x) = \\begin{cases} \n \\frac{x^\\lambda - 1}{\\lambda} & \\lambda \\neq 0\\\\ \n \\ln(x) & \\lambda = 0\n\\end{cases}\n```\n\nExternal links\n* [Power Transform on Wikipedia](https://en.wikipedia.org/wiki/Power_transform)\n\n...\n# Arguments\n* `x::float64`: evaluation point\n* `lambda::float=1.0`: lambda hyperparameter\n\n\"\"\"\nfunction boxCox(x, lambda=1)\n lambda == 0 ? Base.log.(x) : (float(x).^lambda.-1)./lambda\nend\n\n\"\"\"\nDerivative of Box-Cox power transformation w.r.t x\n\"\"\"\nfunction boxCoxPrime(x, lambda=1)\n lambda==0 ? float(x).^(-1) : float(x).^(lambda .-1)\nend\n\n\"\"\"\nSecond derivative of Box-Cox power transformation w.r.t x\n\"\"\"\nfunction boxCoxPrime2(x, lambda=1)\n lambda==0 ? -float(x).^(-2) : (lambda-1)*float(x).^(lambda-2)\nend\n\n\"\"\"\nDerivative of Box-Cox power transformation w.r.t lambda\n\"\"\"\nfunction boxCoxPrime_lambda(x, lambda=1)\n lambda==0 ? 0 : (lambda * float(x).^lambda .* log.(x) .- float(x).^lambda .+ 1)/lambda^2\nend\n\n\"\"\"\nSecond derivative of Box-Cox power transformation w.r.t lambda\n\"\"\"\nfunction boxCoxPrime_lambda2(x, lambda=1)\n lambda==0 ? 0 : float(x).^lambda .* (Base.log.(x)^2)/lambda - \n (2*x.^lambda .* Base.log.(x))/lambda^2 + 2*(float(x).^lambda-1)/lambda^3\nend\n\n\"\"\"\nMixed derivative of Box-Cox power transformation w.r.t lambda and x\n\"\"\"\nfunction boxCoxMixed_lambda_z(x, lambda=1)\n lambda==0 ? 0 : float(x).^(lambda-1) .* Base.log.(x) \nend\n\n\"\"\"\nInverse Box Cox power transformation\n\"\"\"\nfunction invBoxCox(y, lambda=1)\n lambda==0 ? Base.exp.(y) : Base.exp.(Base.log.(lambda.*y.+1)./lambda)\nend\n\n#define BoxCox Object\nboxCoxObj = nonlinearTransform(boxCox, boxCoxPrime, boxCoxPrime2, boxCoxPrime_lambda, boxCoxPrime_lambda2, boxCoxMixed_lambda_z, invBoxCox)\n\n@doc raw\"\"\"\n TODO Unimplimented\n\"\"\"\nstruct YeoJohnson{T} <: Function end\n\n@doc raw\"\"\"\n TODO Unimplimented\n\"\"\"\nstruct ArandaOrdaz{T} end\n", "meta": {"hexsha": "0fee3bc49c826a976f32155ecc8c6e1dc19e4954", "size": 2267, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "individual_implementations/btg julia/transforms.jl", "max_stars_repo_name": "dbindel/btg", "max_stars_repo_head_hexsha": "83616be1d1c4d80f385fa95cef38753f39a3a4c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-09-18T04:52:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-03T18:58:55.000Z", "max_issues_repo_path": "individual_implementations/btg julia/transforms.jl", "max_issues_repo_name": "dbindel/btg", "max_issues_repo_head_hexsha": "83616be1d1c4d80f385fa95cef38753f39a3a4c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "individual_implementations/btg julia/transforms.jl", "max_forks_repo_name": "dbindel/btg", "max_forks_repo_head_hexsha": "83616be1d1c4d80f385fa95cef38753f39a3a4c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-06T06:07:50.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-06T06:07:50.000Z", "avg_line_length": 23.8631578947, "max_line_length": 139, "alphanum_fraction": 0.6682840759, "num_tokens": 729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154281754899, "lm_q2_score": 0.8791467754256017, "lm_q1q2_score": 0.8432373939404785}} {"text": "\"\"\"\nPDE_Tools\n\nThis file has the operators I need for the PDE example. They\nlive in a separate file to make the CI easier for me to organize.\n\"\"\"\n# Famous sparse matrices\n\"\"\"\nDx2d(n)\n\nreturns x partial on n x n grid.\nUnit square, homogeneous Dirichlet BC\n\"\"\"\nfunction Dx2d(n)\n h = 1 / (n + 1)\n ssdiag = ones(n^2 - 1) / (2 * h)\n for iz = n:n:n^2-1\n ssdiag[iz] = 0.0\n end\n updiag = Pair(1, ssdiag)\n lowdiag = Pair(-1, -ssdiag)\n Dx = spdiagm(lowdiag, updiag)\n return Dx\nend\n\n\"\"\"\nDy2d(n)\n\nreturns y partial on n x n grid.\nUnit square, homogeneous Dirichlet BC\n\"\"\"\nfunction Dy2d(n)\n h = 1 / (n + 1)\n ssdiag = ones(n^2 - n) / (2 * h)\n updiag = Pair(n, ssdiag)\n lowdiag = Pair(-n, -ssdiag)\n Dy = spdiagm(lowdiag, updiag)\n return Dy\nend\n\n\"\"\"\nLap2d(n)\n\nreturns the negative Laplacian in two space dimensions\non n x n grid.\n\nUnit square, homogeneous Dirichlet BC\n\"\"\"\nfunction Lap2d(n)\n # hm2=1/h^2\n hm2 = (n + 1.0)^2\n maindiag = fill(4 * hm2, (n^2,))\n sxdiag = fill(-hm2, (n^2 - 1,))\n sydiag = fill(-hm2, (n^2 - n,))\n for iz = n:n:n^2-1\n sxdiag[iz] = 0.0\n end\n D2 = spdiagm(-n => sydiag, -1 => sxdiag, 0 => maindiag, 1 => sxdiag, n => sydiag)\n return D2\nend\n\n\n\"\"\"\nu=fish2d(f, fdata)\n\nFast Poisson solver in two space dimensions.\nSame as the Matlab code.\nUnit squre + homogeneous Dirichlet BCs.\n\nGrid is nx by nx\n\nYou give me f as a two-dimensional vector f(x,y).\nI return the solution u.\n\"\"\"\nfunction fish2d(f, fdata)\n u = fdata.utmp\n v = fdata.uhat\n T = fdata.T\n ST = fdata.ST\n (nx, ny) = size(f)\n nx == ny || error(\"need a square grid in fish2d\")\n u .= f\n u = ST * u\n u = u'\n u1 = reshape(u, (nx * nx,))\n v1 = reshape(v, (nx * nx,))\n v1 .= u1\n ldiv!(u1, T, v1)\n u = u'\n u .= ST * u\n u ./= (2 * nx + 2)\n return u\nend\n\n\"\"\"\nfishinit(n)\n\nRun FFTW.plan_r2r to set up the solver. Do not mess\nwith this function.\n\"\"\"\nfunction fishinit(n)\n #\n # Get the sine transform from FFTW. This is faster/better/cleaner\n # than what I did in the Matlab codes.\n #\n zstore = zeros(n, n)\n ST = FFTW.plan_r2r!(zstore, FFTW.RODFT00, 1)\n uhat = zeros(n, n)\n fishu = zeros(n, n)\n TD = newT(n)\n T = lu!(TD)\n fdata = (ST = ST, uhat = uhat, utmp = zstore, T = T, fishu = fishu)\n return fdata\nend\n\n\"\"\"\nT = newT(n)\n\nBuilds the n^2 x n^2 sparse tridiagonal matrix for\nthe 2D fast Poisson solver.\n\"\"\"\nfunction newT(n)\n N = n * n\n h = 1 / (n + 1)\n x = h:h:1-h\n h2 = 1 / (h * h)\n LE = 2 * (2 .- cos.(pi * x)) * h2\n fn = ones(N - 1) * h2\n gn = ones(N - 1) * h2\n dx = zeros(N)\n for k = 1:n-1\n fn[k*n] = 0.0\n gn[k*n] = 0.0\n dx[(k-1)*n+1:n*k] = LE[k] * ones(n)\n end\n dx[(n-1)*n+1:n*n] = LE[n] * ones(n)\n T = Tridiagonal(-fn, dx, -gn)\n return T\nend\n\n\"\"\"\nUse fish2d and reshape for preconditioning.\n\"\"\"\nfunction Pfish2d(v, fdata)\n n2 = length(v)\n n = Int(sqrt(n2))\n (n * n == n2) || error(\"input to Pfish2d not a square array\")\n v2 = reshape(v, (n, n))\n u = fish2d(v2, fdata)\n u = reshape(u, (n2,))\n return u\nend\n\n\"\"\"\nPvec2d(v, u, pdata)\n\nReturns inverse Laplacian * v\n\nu is a dummy argument to make nsoli happy\n\nPreconditioner for nsoli\n\"\"\"\nfunction Pvec2d(v, u, pdata)\n fdata = pdata.fdata\n p = Pfish2d(v, fdata)\n return p\nend\n", "meta": {"hexsha": "83865e3e82cfdff920c356ac4a39694448f3a5ef", "size": 3340, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/TestProblems/Systems/PDE_Tools.jl", "max_stars_repo_name": "aliddell/SIAMFANLEquations.jl", "max_stars_repo_head_hexsha": "4a9bad23d726993764c5790d56b9d68cb27dffe0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/TestProblems/Systems/PDE_Tools.jl", "max_issues_repo_name": "aliddell/SIAMFANLEquations.jl", "max_issues_repo_head_hexsha": "4a9bad23d726993764c5790d56b9d68cb27dffe0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/TestProblems/Systems/PDE_Tools.jl", "max_forks_repo_name": "aliddell/SIAMFANLEquations.jl", "max_forks_repo_head_hexsha": "4a9bad23d726993764c5790d56b9d68cb27dffe0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.880952381, "max_line_length": 85, "alphanum_fraction": 0.5652694611, "num_tokens": 1246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542887603537, "lm_q2_score": 0.8791467675095294, "lm_q1q2_score": 0.8432373925065667}} {"text": "# Huber loss function\n\nusing LinearAlgebra\n\nexport HuberLoss\n\n\"\"\"\n**Huber loss**\n\n HuberLoss(ρ=1, μ=1)\n\nReturns the function\n```math\nf(x) = \\\\begin{cases}\n \\\\tfrac{μ}{2}\\\\|x\\\\|^2 & \\\\text{if}\\\\ \\\\|x\\\\| ⩽ ρ \\\\\\\\\n ρμ(\\\\|x\\\\| - \\\\tfrac{ρ}{2}) & \\\\text{otherwise},\n\\\\end{cases}\n```\nwhere `ρ` and `μ` are positive parameters.\n\"\"\"\nstruct HuberLoss{R <: Real, S <: Real} <: ProximableFunction\n rho::R\n mu::S\n function HuberLoss{R, S}(rho::R, mu::S) where {R <: Real, S <: Real}\n if rho <= 0 || mu <= 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, mu::S=1) where {R <: Real, S <: Real} = HuberLoss{R, S}(rho, mu)\n\nfunction (f::HuberLoss)(x::AbstractArray{T}) where {R <: Real, T <: Union{R, Complex{R}}}\n normx = norm(x)\n if normx <= f.rho\n return f.mu / R(2) * normx^2\n else\n return f.rho * f.mu * (normx - f.rho / R(2))\n end\nend\n\nfunction gradient!(y::AbstractArray{T}, f::HuberLoss, x::AbstractArray{T}) where {R <: Real, T <: Union{R, Complex{R}}}\n normx = norm(x)\n if normx <= f.rho\n y .= f.mu .* x\n v = f.mu / R(2) * normx^2\n else\n y .= (f.mu * f.rho) / normx .* x\n v = f.rho * f.mu * (normx - f.rho / R(2))\n end\n return v\nend\n\nfunction prox!(y::AbstractArray{T}, f::HuberLoss, x::AbstractArray{T}, gamma::R=R(1)) where {R <: Real, T <: Union{R, Complex{R}}}\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 / R(2) * normy^2\n else\n return f.rho * f.mu * (normy - f.rho / R(2))\n end\nend\n\nfun_name(f::HuberLoss) = \"Huber loss\"\nfun_dom(f::HuberLoss) = \"AbstractArray{Real}, AbstractArray{Complex}\"\nfun_expr(f::HuberLoss) = \"x ↦ (μ/2)||x||² if ||x||⩽ρ, μρ(||x||-ρ/2) otherwise\"\nfun_params(f::HuberLoss) = string(\"ρ = $(f.rho), μ = $(f.mu)\")\n\nfunction prox_naive(f::HuberLoss, x::AbstractArray{T}, gamma::R=R(1)) where {R <: Real, T <: Union{R, Complex{R}}}\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 / R(2) * norm(y)^2\n else\n return y, f.rho * f.mu * (norm(y) - f.rho / R(2))\n end\nend\n", "meta": {"hexsha": "201b20acd5d8ec21679cc2f09bfcfb2c91026b86", "size": 2436, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/huberLoss.jl", "max_stars_repo_name": "JuliaTagBot/ProximalOperators.jl-1", "max_stars_repo_head_hexsha": "adaa0d22ca6be799cbfd59323c2d20d63b8938cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 95, "max_stars_repo_stars_event_min_datetime": "2016-10-29T12:34:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-18T00:11:52.000Z", "max_issues_repo_path": "src/functions/huberLoss.jl", "max_issues_repo_name": "JuliaTagBot/ProximalOperators.jl-1", "max_issues_repo_head_hexsha": "adaa0d22ca6be799cbfd59323c2d20d63b8938cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 107, "max_issues_repo_issues_event_min_datetime": "2016-10-26T16:08:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-21T20:38:48.000Z", "max_forks_repo_path": "src/functions/huberLoss.jl", "max_forks_repo_name": "JuliaTagBot/ProximalOperators.jl-1", "max_forks_repo_head_hexsha": "adaa0d22ca6be799cbfd59323c2d20d63b8938cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31, "max_forks_repo_forks_event_min_datetime": "2016-10-26T15:33:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-24T10:40:24.000Z", "avg_line_length": 28.0, "max_line_length": 130, "alphanum_fraction": 0.5410509031, "num_tokens": 914, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517061554854, "lm_q2_score": 0.8774767874818408, "lm_q1q2_score": 0.8432128160425092}} {"text": "\n\"\"\"\n RMSE(obs,sim)\n\n Returns the Root Mean Squared Error between observations `obs` and simulations `sim`.\n\n The closer to 0 the better.\n\"\"\"\nfunction RMSE(obs, sim)\n return sqrt(sum((obs .- sim).^2) / length(obs))\nend\n\n\"\"\"\n NRMSE(obs,sim)\n\n Returns the Normalized Root Mean Squared Error between observations `obs` and simulations `sim`.\n Normalization is performed using division by observations range (max-min).\n\n Output: Float/Particles\n\"\"\"\nfunction NRMSE(obs, sim)\n return sqrt(sum((obs .- sim).^2) / length(obs)) / (findmax(obs)[1] - findmin(obs)[1])\nend\n\n\"\"\"\n EF(obs,sim)\n\n Returns the Efficiency Factor between observations `obs` and simulations `sim` using NSE (Nash-Sutcliffe efficiency) model.\n More information can be found at https://en.wikipedia.org/wiki/Nash%E2%80%93Sutcliffe_model_efficiency_coefficient.\n\n The closer to 1 the better.\n\"\"\"\nfunction EF(obs, sim)\n SSres = sum((obs - sim).^2)\n SStot = sum((obs .- mean(obs)).^2)\n return 1 - SSres / SStot\nend\n\n\"\"\"\n dr(obs,sim)\n\n Returns the Willmott’s refined index of agreement dᵣ.\n Willmot et al. 2011. A refined index of model performance. https://rmets.onlinelibrary.wiley.com/doi/10.1002/joc.2419\n\n The closer to 1 the better.\n\n\"\"\"\nfunction dr(obs, sim)\n a = sum(abs.(obs .- sim))\n b = 2 * sum(abs.(obs .- mean(obs)))\n return 0 + (1 - a / b) * (a <= b) + (b / a - 1) * (a > b)\nend\n", "meta": {"hexsha": "a9da71782922b6093998df5b42928c92a59e76db", "size": 1419, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/evaluation/statistics.jl", "max_stars_repo_name": "ARCHIMED-platform/PlantBiophysics.jl", "max_stars_repo_head_hexsha": "007ff8fb36092f555ecae67cf02ce3146a16cf88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-03-04T08:34:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T00:03:44.000Z", "max_issues_repo_path": "src/evaluation/statistics.jl", "max_issues_repo_name": "ARCHIMED-platform/PlantBiophysics.jl", "max_issues_repo_head_hexsha": "007ff8fb36092f555ecae67cf02ce3146a16cf88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-03T21:03:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T10:24:58.000Z", "max_forks_repo_path": "src/evaluation/statistics.jl", "max_forks_repo_name": "VEZY/PlantBiophysics.jl", "max_forks_repo_head_hexsha": "415861b5346d2f8b19b24d0fe65c2d7bdabed6bd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-03-04T10:06:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-15T19:54:52.000Z", "avg_line_length": 26.7735849057, "max_line_length": 127, "alphanum_fraction": 0.652572234, "num_tokens": 418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517050371973, "lm_q2_score": 0.8774767842777551, "lm_q1q2_score": 0.8432128119822657}} {"text": "#!/usr/bin/env julia\n\n# Project 1: Vanilla options in a Black-Scholes World\n#\n# Page 437+, Joshi's Mathematical Finance\n\n\n# Best to run this with JULIA_NUM_THREADS=$(nproc) and julia 1.3\n\n# Notation: if f is a function of x, fv is one realisation of that function\n\nimport ThreadsX\nusing SpecialFunctions: erf\n\nexport C, P, B, present_value, rand_price, mc_pricer, binary, mc_pricer_pathdep\n\nN(x) = 0.5 * (1 + erf(x/sqrt(2)))\n\nd_1(S,t,T,K,r,σ) = (log(S/K) + (r + (σ^2)/2)*(T-t)) / (σ*√(T-t))\nd_2(S,t,T,K,r,σ) = (log(S/K) + (r - (σ^2)/2)*(T-t)) / (σ*√(T-t))\n\n\n# Price of a call option (i.e. the holder has the right to buy stock at maturity)\n# S = current stock (underlying) price\n# t = current time (time since option created)\n# T = time of maturity\n# K = the price at which the stock may be bought at maturity\n# r = the continuously compounded risk-free rate\n# σ = volatility of the underlying (standard deviation per root unit of time)\n# TODO: d = dividend rate\nfunction C(S,t; T=1, K=100, r=0.02, σ=0.5)\n d_1v = d_1(S,t,T,K,r,σ)\n d_2v = d_2(S,t,T,K,r,σ)\n N(d_1v)*S - N(d_2v)*present_value(K,r,t,T)\nend\n\n# Price of a put option (i.e. holder may sell at maturity)\nfunction P(S,t; T=1, K=100, r=0.02, σ=0.5)\n present_value(K,r,t,T) - S + C(S,t, T=T, K=K, r=r, σ=σ)\nend\n\n# Price of a binary option:\n# Payoff of 1 if S(T) > E, 0 otherwise\n# \n# Source: http://www.iam.fmph.uniba.sk/institute/stehlikova/fd14en/lectures/05_black_scholes_1.pdf\n#\n# Can construct a less than binary thusly:\n# less_than_binary = present_value(1) - greater_than_binary\n# (cf. put call parity)\nfunction binary(S,t; T=1, E=100, r=0.02, σ=0.5)\n present_value(1,r,t,T) * N(d_2(S,t,T,E,r,σ))\nend\n\n##############################\n# #\n# Validation via Monte Carlo #\n# #\n##############################\n\n# Brownian motion\nB(T;B0=100,r=0.02,d=0.00,σ=0.5) = B0*exp((r-d)*T-0.5*σ^2*T+σ*√T*randn())\n\n# Sketch of pricer: Brownian motion generates a final stock price; payoff of option is calculated and then discounted. Price of option is average of these.\n\npresent_value(v,r,t,T) = v*exp(-r*(T-t))\n\nfunction rand_price(payoff;S_0=100,t=0,T=1,K=S_0,r=0.02,σ=0.05)\n S = B(T-t;B0=S_0,r=r,d=0,σ=σ)\n present_value(payoff(S),r,t,T)\nend\n\n# Strictly we should use a thread-safe RNG here\nfunction mc_pricer(\n payoff;S_0=100,t=0,T=1,K=S_0,r=0.02,σ=0.05, trials=100_000_000\n)\n linear, squared = ThreadsX.mapreduce(\n x->begin\n p = rand_price(payoff;S_0=S_0,t=t,T=T,K=K,r=r,σ=σ)\n (p,p^2) # Second term is to keep track of standard error\n end,\n (a,b)->a.+b,\n Base.OneTo(trials),\n init=(0.0, 0.0)\n )\n\n mean = linear/trials\n\n (mean = mean, sem = sqrt(squared/trials - mean^2)/sqrt(trials))\nend\n\nfunction mc_pricer_pathdep(\n payoff;S_0=100,t=[0],T=1,K=S_0,r=0.02,σ=0.05, trials=100_000_000\n)\n linear, squared = ThreadsX.mapreduce(\n x->begin\n p = B.(T.-t;B0=S_0,r=r,d=0,σ=σ)\n price = present_value(payoff(p),r,t[1],T) # Payoff must operate on time series\n (price,price^2) \n end,\n (a,b)->a.+b,\n Base.OneTo(trials),\n init=(0.0, 0.0)\n )\n\n mean = linear/trials\n\n (mean = mean, sem = sqrt(squared/trials - mean^2)/sqrt(trials))\nend\n", "meta": {"hexsha": "c2771544816cb6bb458e09e920626e5459453a3b", "size": 3299, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/p1_black_scholes_vanilla/black_scholes_vanilla.jl", "max_stars_repo_name": "bovine3dom/JustJoshing.jl", "max_stars_repo_head_hexsha": "0da2d140fe44692954a6c03d181fdc2c5a45a24e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/p1_black_scholes_vanilla/black_scholes_vanilla.jl", "max_issues_repo_name": "bovine3dom/JustJoshing.jl", "max_issues_repo_head_hexsha": "0da2d140fe44692954a6c03d181fdc2c5a45a24e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-03-07T23:11:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-09T15:35:08.000Z", "max_forks_repo_path": "src/p1_black_scholes_vanilla/black_scholes_vanilla.jl", "max_forks_repo_name": "bovine3dom/JustJoshing.jl", "max_forks_repo_head_hexsha": "0da2d140fe44692954a6c03d181fdc2c5a45a24e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2660550459, "max_line_length": 155, "alphanum_fraction": 0.6083661716, "num_tokens": 1176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897475985937, "lm_q2_score": 0.8962513814471134, "lm_q1q2_score": 0.8431841109365207}} {"text": "\"\"\"\n diffper(n,xspan)\n\nConstruct 2nd-order differentiation matrices for functions with\nperiodic end conditions, using `n` unique nodes in the interval\n`xspan`. Returns a vector of nodes and the matrices for the first\nand second derivatives.\n\"\"\"\nfunction diffper(n,xspan)\n a,b = xspan\n h = (b-a)/n\n x = @. a + h*(0:n-1) # nodes, omitting the repeated data\n\n # Construct Dx by diagonals, then correct the corners.\n dp = fill(0.5/h,n-1) # superdiagonal\n dm = fill(-0.5/h,n-1) # subdiagonal\n Dx = diagm(-1=>dm,1=>dp)\n Dx[1,n] = -1/(2*h)\n Dx[n,1] = 1/(2*h)\n\n # Construct Dxx by diagonals, then correct the corners.\n d0 = fill(-2/h^2,n) # main diagonal\n dp = ones(n-1)/h^2 # superdiagonal and subdiagonal\n Dxx = diagm(-1=>dp,0=>d0,1=>dp)\n Dxx[1,n] = 1/(h^2)\n Dxx[n,1] = 1/(h^2)\n\n return x,Dx,Dxx\nend\n\n\"\"\"\n parabolic(ϕ,xspan,m,g₁,g₂,tspan,init)\n\nSolve a parabolic PDE by the method of lines. The PDE is \n∂u/∂t = `ϕ`(t,x,u,∂u/∂x,∂^2u/∂x^2), `xspan` gives the space \ndomain, m gives the degree of a Chebyshev spectral discretization, \n`g₁` and `g₂` are functions of (u,∂u/∂x) at the domain ends that \nshould be made zero, `tspan` is the time domain, and `init` is a \nfunction of x that gives the initial condition. Returns a vector\n`x` and a function of t that gives the semidiscrete solution at `x`. \n\"\"\"\nfunction parabolic(ϕ,xspan,m,g₁,g₂,tspan,init)\n x,Dₓ,Dₓₓ = diffcheb(m,xspan)\n int = 2:m # indexes of interior nodes\n\n function extend(v)\n function objective(ubc)\n u₀,uₘ = ubc\n uₓ = Dₓ*[u₀;v;uₘ]\n return [g₁(u₀,uₓ[1]),g₂(uₘ,uₓ[end])]\n end\n ubc = levenberg(objective,[0,0])[end]\n return [ubc[1];v;ubc[2]]\n end\n\n function ode!(f,v,p,t)\n u = extend(v)\n uₓ,uₓₓ = Dₓ*u,Dₓₓ*u\n @. f = ϕ(t,x[int],u[int],uₓ[int],uₓₓ[int])\n end\n\n ivp = ODEProblem(ode!,init.(x[int]),float.(tspan))\n u = solve(ivp)\n\n return x,t->extend(u(t))\nend", "meta": {"hexsha": "67ec3c0188358c0d8fee6474d7ef1eff5d4e94ac", "size": 2011, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chapter11.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/chapter11.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/chapter11.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": 30.4696969697, "max_line_length": 69, "alphanum_fraction": 0.5972153158, "num_tokens": 739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897442783526, "lm_q2_score": 0.8962513724408291, "lm_q1q2_score": 0.8431840994877301}} {"text": "#Simulate a determinantally-thinned Poisson point process on a rectangle\n#Author: H. Paul Keeler, 2019.\n\n#Note: Need the .+ for adding a scalar to an array\n#Also need . for sqrt, exp, cos, sin etc and assigning scalars to arrays\n#Index and Boolean arrrays need to be vectors eg v=zeros(n), NOT v=zeros(n,1)\n\n#clearconsole(); #for clearing Julia REPL console\n\nusing Distributions #for random simulations\nusing LinearAlgebra;\nusing PyPlot #uses Python for plotting\nPyPlot.close(\"all\"); # close all PyPlot figures\n\n#set random seed for reproducibility\n#Random.seed!(1234)\n\n###START -- Parameters -- ###START\n#Poisson point process parameters\nlambda=50; #intensity (ie mean density) of the Poisson process\n\n#choose kernel\nchoiceKernel=1; #1 for Gaussian (ie squared exponetial );2 for Cauchy\nsigma=1;# parameter for Gaussian and Cauchy kernel\nalpha=1;# parameter for Cauchy kernel\n\n#Simulation window parameters\nxMin=0;xMax=1;yMin=0;yMax=1;\nxDelta=xMax-xMin;yDelta=yMax-yMin; #rectangle dimensions\nareaTotal=xDelta*yDelta; #area of rectangle\n###END -- Parameters -- ###END\n\n### START -- Simulate a Poisson point process on a rectangle ###START\n#Simulate Poisson point process\nnumbPoints=rand(Poisson(areaTotal*lambda)); #Poisson number of points\nxx=xDelta*(rand(numbPoints)).+xMin;#x coordinates of Poisson points\nyy=xDelta*(rand(numbPoints)).+yMin;#y coordinates of Poisson points\n### END -- Simulate a Poisson point process on a rectangle --END ###\n\n#numbPoints=5; xx=-2:1:2; yy=3:7 #TEMP\n\n### START -- CREATE L matrix -- START ###\n#all squared distances of x/y difference pairs\nxxDiff=kron(xx,ones(1,numbPoints))-kron(ones(numbPoints,1),transpose(xx));\nyyDiff=kron(yy,ones(1,numbPoints))-kron(ones(numbPoints,1),transpose(yy));\nrrDiffSquared=(xxDiff.^2+yyDiff.^2);\nif choiceKernel==1\n ##Gaussian/squared exponential kernel\n L=lambda*exp.(-(rrDiffSquared)/sigma^2);\nelseif choiceKernel==2\n ##Cauchy kernel\n L=lambda./(1+rrDiffSquared/sigma^2).^(alpha+1/2);\nelse\n println(\"choiceKernel has to be equal to 1 or 2.\");\nend\n\n### END-- CREATE L matrix -- ### END\nL=Symmetric(L); #convert to Symmetric marix\n\n#START - Sampling/simulating DPP - START\n# #Retrieve eigenvalues and eigenvectors\neigenVectL=eigvecs(L); #eigen decomposition -- vectors\neigenValL=(eigvals(L)); #eigen decomposition -- values\neigenVectK = (eigenVectL);\neigenValK = eigenValL./(1 .+eigenValL); #eigenvalues of K\n\n#Bernoulli trials (ie coin flips) to determine number of points\nbooleEigen = (rand(length(eigenValK)) .<= eigenValK);\n\n#number of points in the DPP realization\nnumbPointsDPP=sum(booleEigen);\n#retrieve eigenvectors corresponding to successful Bernoulli trials\nglobal spaceV = eigenVectK[:,booleEigen]; #subspace V\nindexDPP = zeros(Int8,numbPointsDPP); #index for final DPP configuration\n\nglobal numbPointsRemain=numbPointsDPP;\n#Loop through for all points\nfor ii=1:numbPointsDPP\n #Compute probabilities for each point i\n global Prob_i=vec(sum(spaceV.^2,dims=2)); #sum across rows\n Prob_i=Prob_i./sum(Prob_i); #normalize\n\n #Choose a point (from 1 to numbPoints) using (prob mass function) Prob_i\n uRand=rand(1);\n indexCurrent= findall(x -> x> uRand[1], cumsum(Prob_i))[1];\n indexDPP[ii]=indexCurrent; #update index\n\n if ii x>0, abs.(spaceV[indexCurrent,:]))[1];\n columnVj=spaceV[:,jj]; #j-th column of V\n booleKeep_j=(jj).!=(1:numbPointsRemain);\n global spaceV=spaceV[:,booleKeep_j]; #remove column\n #probably a better way for removing columns\n\n #Update matrix V by removing Vj component from the space\n spaceV=spaceV-kron(columnVj, transpose(spaceV[indexCurrent,:]./columnVj[indexCurrent]));\n\n #Orthonormalize\n decompQR=qr(spaceV);\n spaceV=Matrix(decompQR.Q);\n #need Matrix function for properly sized matrix\n end\n\n global numbPointsRemain= numbPointsRemain-1; #update\nend\nindexDPP=sort(indexDPP);\n\n#Plotting\n#Plot Poisson point process\nPyPlot.scatter(xx,yy, edgecolor=\"k\", facecolor=\"none\");\nPyPlot.xlabel(\"x\"); plt.ylabel(\"y\");\n#random color vector\nvectorColor=rand(3);\n#Plot determinantally-thinned Poisson point process\nPyPlot.scatter(xx[indexDPP],yy[indexDPP],edgecolor=\"none\",facecolor=vectorColor);\n\nprintln(\"Program has ended.\");\n", "meta": {"hexsha": "838e508d0634893f429a6dfa983b64024f181530", "size": 4304, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "DemoDetPoisson.jl", "max_stars_repo_name": "hpaulkeeler/DetPoisson_Julia", "max_stars_repo_head_hexsha": "9d5273e1f5dcf0869b01edd6e0486b900838a971", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DemoDetPoisson.jl", "max_issues_repo_name": "hpaulkeeler/DetPoisson_Julia", "max_issues_repo_head_hexsha": "9d5273e1f5dcf0869b01edd6e0486b900838a971", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DemoDetPoisson.jl", "max_forks_repo_name": "hpaulkeeler/DetPoisson_Julia", "max_forks_repo_head_hexsha": "9d5273e1f5dcf0869b01edd6e0486b900838a971", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1680672269, "max_line_length": 96, "alphanum_fraction": 0.7328066914, "num_tokens": 1248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9724147193720648, "lm_q2_score": 0.8670357494949105, "lm_q1q2_score": 0.8431183250306412}} {"text": "function transition(time::Int64, system::Array{Int64,2}, parameters::Dict{String,Any})::Array{Float64,2}\n \n # initialize -\n T = zeros(2,2)\n A = system[time,1]\n B = system[time,2]\n \n # get parameters -\n K1 = parameters[\"K1\"]\n n1 = parameters[\"n1\"]\n K2 = parameters[\"K2\"]\n n2 = parameters[\"n2\"]\n\n # compute -\n p1 = A^n1/(K1^n1+A^n1)\n p2 = B^n2/(K2^n2+B^n2)\n \n # package -\n T[1,1] = 1 - p1\n T[1,2] = p1\n T[2,1] = p2\n T[2,2] = 1 - p2\n \n # return -\n return T\nend\n\nfunction machine(time::Int64, state::Int64, system::Array{Int64,2}, parameters::Dict{String,Any})::Int64\n \n # compute the probabilities -\n T = transition(time, system, parameters)\n \n # generate a random number -\n r = rand() # uniform from 0 -> 1\n \n # what are my choice?\n choices = 1.0 .- T[state,:]\n \n # what is the index of the max?\n idx_max = argmax(choices)\n p = choices[idx_max]\n \n if (r >= p)\n return argmax(choices)\n else\n return argmin(choices)\n end\nend", "meta": {"hexsha": "fc5bd5ef5876049e9a2cf8ac4de595ccc35d7a73", "size": 1061, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "prelim_2/Library.jl", "max_stars_repo_name": "varnerlab/CHEME-5440-7770-Cornell-Spring-2022", "max_stars_repo_head_hexsha": "f580d12cb9d08657b6e7488280e5bf8391bb8530", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-02-07T23:40:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T19:06:26.000Z", "max_issues_repo_path": "prelim_2/Library.jl", "max_issues_repo_name": "varnerlab/CHEME-5440-7770-Cornell-Spring-2022", "max_issues_repo_head_hexsha": "f580d12cb9d08657b6e7488280e5bf8391bb8530", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "prelim_2/Library.jl", "max_forks_repo_name": "varnerlab/CHEME-5440-7770-Cornell-Spring-2022", "max_forks_repo_head_hexsha": "f580d12cb9d08657b6e7488280e5bf8391bb8530", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2022-02-03T15:15:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T22:46:36.000Z", "avg_line_length": 22.1041666667, "max_line_length": 104, "alphanum_fraction": 0.5447690858, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812327313546, "lm_q2_score": 0.8705972566572504, "lm_q1q2_score": 0.8430700446142836}} {"text": "\"\"\"\r\n LUtanpaP(A)\r\nadalah fungsi yang digunakan untuk memfaktorisasi matriks `A` sembarang menjadi\r\ndua matriks, yaitu matriks segitiga atas `U` dan bawah `L` sedemikian sehingga `LU=A`\r\n\r\n# Examples\r\n```jl\r\njulia> A = [ 2 5 4 2 3\r\n 4 1 0.4 6 5\r\n 0.9 4 8 7 10\r\n 5 7 0.5 2 7\r\n 2 6 8 9 4];\r\n\r\njulia> L,U = LUtanpaP(A);\r\n\r\njulia> L\r\n5×5 Array{Float64,2}:\r\n 1.0 0.0 0.0 0.0 0.0\r\n 2.0 1.0 0.0 0.0 0.0\r\n 0.45 -0.194444 1.0 0.0 0.0\r\n 2.5 0.611111 -1.02824 1.0 0.0\r\n 1.0 -0.111111 0.668235 1.17806 1.0\r\n\r\njulia> U\r\n5×5 Array{Float64,2}:\r\n 2.0 5.0 4.0 2.0 3.0\r\n 0.0 -9.0 -7.6 2.0 -1.0\r\n 0.0 0.0 4.72222 6.48889 8.45556\r\n 0.0 0.0 0.0 2.44988 8.80541\r\n 0.0 0.0 0.0 0.0 -15.1347\r\n```\r\nreturn matriks `L` dan `U`.\r\n\"\"\"\r\nfunction LUtanpaP(A);\r\n # Definisikan matriks L sebagai pencatat pengali.\r\n n,n = size(A);\r\n L = zeros(n,n);\r\n # Lakukan operasi baris dasar terhadap matriks\r\n Aug = copy(A);\r\n for p = 1:n-1\r\n # Jika pivot bernilai nol, maka gagal.\r\n if Aug[p,p]==0\r\n error(\"Pivot bernilai nol\");\r\n end\r\n # Lakukan eliminasi lalu simpan pengali pada matriks L.\r\n for i = p+1:n\r\n k = Aug[i,p]/Aug[p,p];\r\n Aug[i,1:n] = Aug[i,1:n] - k*Aug[p,1:n];\r\n L[i,p] = k;\r\n end\r\n end\r\n U = Aug;\r\n L = L .+ I(n);\r\n return L, U\r\nend\r\n", "meta": {"hexsha": "0baf7854d82fc5dc35ce9e957c83460fb6fb8a73", "size": 1507, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/LUtanpaP.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/LUtanpaP.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/LUtanpaP.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.9107142857, "max_line_length": 86, "alphanum_fraction": 0.4744525547, "num_tokens": 668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104953173166, "lm_q2_score": 0.872347366381434, "lm_q1q2_score": 0.8430456504334383}} {"text": "# compute primes up to max using the Sieve algorithm\n# https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\n# https://docs.julialang.org/en/v1/\n\n\nimport Dates\n\nfunction print_usage()\n println(string(\"julia \", PROGRAM_FILE, \" max_prime\")) \nend\n\nfunction make_array(max)\n return collect(1:2:max)\nend\n\nfunction remove_multiples(numbers, prime_index, max)\n\n prime::Int64 = numbers[prime_index]\n array_length::Int64 = length(numbers)\n\n # println(\"called remove_multiple(\", prime_index, \") = \", prime, \", length: \", array_length)\n\n # the for loop will start at one multiple past the current prime\n # it will walk the list of numbers by multiples of prime\n # this logic removes the need for any if statements inside the loop\n @inbounds for current_index::Int64 in prime_index+prime : prime : array_length\n numbers[current_index] = 0\n end\nend\n\nfunction compute_primes(max::Int64)\n start_time = Dates.now()\n\n numbers = make_array(max)\n\n # println(numbers)\n # println(\"Length: \", length(numbers))\n\n println(\"Computing primes from 0 to \", max)\n\n half_length::Int64 = Int64(length(numbers)/2)\n\n @inbounds for i = 2:half_length\n if numbers[i] > 0\n remove_multiples(numbers, i, max)\n end\n end\n\n\n primes = filter(x -> x>0, numbers)\n\n mid_time = Dates.now()\n\n # println(\"Primes: \", primes)\n\n finish_time = Dates.now()\n\n println(\"Start: \", start_time, \", Mid: \", mid_time, \", Finish: \", finish_time)\n println(\"Compute time: \", (mid_time - start_time))\n println(\"Found: \", length(primes), \" prime numbers under: \", max)\nend\n\nfunction main()\n if length(ARGS) < 1\n print_usage()\n else\n compute_primes(parse(Int64, ARGS[1]))\n end\n\nend\n\nmain()\n", "meta": {"hexsha": "15fbe3c9c4d8723c2d3a330b65cdd7bdbd83c247", "size": 1671, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "prime_numbers.jl", "max_stars_repo_name": "pizzapanther/stuff", "max_stars_repo_head_hexsha": "45fda48a647dba018c4d8f28955f377a5ff18fb9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "prime_numbers.jl", "max_issues_repo_name": "pizzapanther/stuff", "max_issues_repo_head_hexsha": "45fda48a647dba018c4d8f28955f377a5ff18fb9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "prime_numbers.jl", "max_forks_repo_name": "pizzapanther/stuff", "max_forks_repo_head_hexsha": "45fda48a647dba018c4d8f28955f377a5ff18fb9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8904109589, "max_line_length": 94, "alphanum_fraction": 0.6947935368, "num_tokens": 451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350351, "lm_q2_score": 0.8976952845805989, "lm_q1q2_score": 0.8429581522416707}} {"text": "import StaticArrays: SVector, @SVector\r\n\r\nfunction distsq(A::SVector{2, T}, B::SVector{2, T}) where T <: Real\r\n return (A[1]-B[1])^2 + (A[2]-B[2])^2\r\nend\r\n\r\nfunction grid_idxs(point:: SVector{2, T}, cellsize::T) where T <: Real \r\n \"\"\" Returns cell indices, (i,j)=(row, col) for `point` \"\"\"\r\n return ceil(Int, point[2] / cellsize) + 1, ceil(Int, point[1] / cellsize) + 1\r\nend\r\n\r\nfunction ispoint_inrectangle(point::SVector{2, T}, rlims::Tuple{T, T}) where T <: Real\r\n \"\"\" \r\n Check whether a point is within the rectangle \r\n [0, rlims[1]] x [0, rlims[2]];\r\n here rlims =(width, height)\r\n \"\"\"\r\n return (0 <= point[1] <= rlims[1]) && (0 <= point[2] <= rlims[2])\r\nend \r\n\r\nfunction unif_sampling_annulus(center::SVector{2, T}, inner_rad::T, outer_rad::T; \r\n k=30) where T <: Real\r\n \"\"\" \r\n Samples uniformly k points from the annulus of center, `center`, \r\n and radii, inner_radius, outer_radius\r\n \"\"\"\r\n rad = sqrt.(inner_rad^2 .+ (outer_rad^2 - inner_rad^2)*rand(k)) \r\n angle = 2*pi * rand(k) \r\n x, y = center[1] .+ rad .* cos.(angle), center[2] .+ rad .*sin.(angle) \r\n return [@SVector([xi, yi]) for (xi, yi) in zip(x,y)]\r\nend\r\n\r\nfunction Poisson_disk_sampling(;width =1.0, height=1.0, radius=0.05, k=30)\r\n \"\"\" \r\n Bridson Algorithm to generate Poisson disk samples \r\n within a 2D rectangle, [0, width] x [0, height]\r\n Ref: R Bridson, Fast Poisson disk sampling in arbitrary dimensions,\r\n in SIGGRAPH '07: ACM SIGGRAPH 2007 sketches\r\n https://www.cs.ubc.ca/~rbridson/docs/bridson-siggraph07-poissondisk.pdf\r\n \"\"\"\r\n function is_accepted(point:: SVector{2, T}) where T <: Real\r\n \"\"\" Check whether the point, `point` can be added to the active_list\"\"\"\r\n\r\n i, j = grid_idxs(point, cellsize)\r\n m, n = maximum([i-2, 1]), maximum([j-2, 1])\r\n p, q = minimum([i+2, grid_rows]), minimum([j+2, grid_cols])\r\n for k in n:q\r\n for l in m:p\r\n gpoint = grid[(k-1) * grows + l]\r\n if ismissing(gpoint)\r\n continue\r\n end\r\n if distsq(point, gpoint) <= r2\r\n return false\r\n end\r\n end\r\n end \r\n return true\r\n end\r\n \r\n cellsize = radius/sqrt(2)\r\n grid_cols = ceil(Int, width / cellsize) + 1\r\n grid_rows = ceil(Int, height / cellsize) + 1\r\n \r\n grid = Vector{Any}(missing, grid_rows*grid_cols)\r\n r2 = radius*radius\r\n active_list = SVector{2, Float64}[]\r\n \r\n #generate a random point within the rectangle of interest\r\n # and insert it into the active_list and grid\r\n point = @SVector([width*rand(1)[1], height*rand(1)[1]])\r\n push!(active_list, point)\r\n i, j = grid_idxs(point, cellsize)\r\n grid[(j-1)*grid_rows+i] = point\r\n \r\n while length(active_list) > 0\r\n i = rand(1:length(active_list), 1)[1]\r\n pt = active_list[i] \r\n active_list = active_list[1:end .!= i] #removes the point in pos i\r\n rpoints = unif_sampling_annulus(pt, radius, 2*radius; k=k)\r\n for rp in rpoints\r\n if !ispoint_inrectangle(rp, (width, height)) || !is_accepted(rp)\r\n continue\r\n end \r\n push!(active_list, rp) \r\n i, j = grid_idxs(rp, cellsize)\r\n grid[(j-1)*grid_rows+i] = rp\r\n end\r\n end\r\n return filter(x->!ismissing(x), grid);\r\nend \r\n", "meta": {"hexsha": "5d2684f81522d7be5c54fbc666438cd0475b6b59", "size": 3463, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/poisson_disk.jl", "max_stars_repo_name": "empet/PoissonDisk", "max_stars_repo_head_hexsha": "6efa3f4ccd5451ab18ffce8fc93c0ca3a2c1d7cb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/poisson_disk.jl", "max_issues_repo_name": "empet/PoissonDisk", "max_issues_repo_head_hexsha": "6efa3f4ccd5451ab18ffce8fc93c0ca3a2c1d7cb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/poisson_disk.jl", "max_forks_repo_name": "empet/PoissonDisk", "max_forks_repo_head_hexsha": "6efa3f4ccd5451ab18ffce8fc93c0ca3a2c1d7cb", "max_forks_repo_licenses": ["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.6413043478, "max_line_length": 87, "alphanum_fraction": 0.5558764077, "num_tokens": 1032, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214511730026, "lm_q2_score": 0.8740772269642949, "lm_q1q2_score": 0.8428914199434828}} {"text": "#!/usr/bin/env julia\n#\n# Jerzy Wroczyński (nr. indeksu 250075)\n# Obliczenia Naukowe, Laboratorium\n# Lista 2, Zadanie 3.\n#\n\n# imports\nusing LinearAlgebra\ninclude(\"hilb.jl\")\ninclude(\"matcond.jl\")\nusing Printf\n\n# solve Ax = b using two methods\n# in this particular case x is just a column of ones, but we’re trying\n# to recalculate it to see how bad is the given matrix in terms of its\n# condition number `cond(A)`\nfunction solve(A)\n # prepare\n x = ones(size(A)[1])\n b = A * x\n # calc using two methods\n gauss = A \\ b\n inverted = inv(A) * b\n\n return gauss, inverted\nend\n\n# this function calculates the relative error between the original\n# and the recalculated value\nfunction calc_relative_error(x, x̃)\n return (norm(x - x̃)/norm(x))\nend\n\n# scientific notation formatting function\nfunction scn(n)\n return @sprintf(\"%.0e\", n)\n # return string(n)\nend\n\n# generates and print out the results\nfunction printout(A, n, c, latex_table=false)\n\n gauss, inverted = solve(A)\n\n if !latex_table\n print(\n \"n = \", n, \"\\n\",\n (c != 0 ? string(\"c = \", scn(c), \"\\n\") : \"\"),\n \" cond(A) = \", cond(A), \"\\n\",\n \" rank(A) = \", rank(A), \"\\n\",\n \" relative error (gauss) = \", calc_relative_error(ones(n), gauss), \"\\n\",\n \" relative error (inverted) = \", calc_relative_error(ones(n), inverted), \"\\n\\n\"\n )\n else\n println(\n n, \" & \",\n (c != 0 ? string(scn(c), \" & \") : \"\"),\n cond(A), \" & \",\n rank(A), \" & \",\n calc_relative_error(ones(n), gauss), \" & \",\n calc_relative_error(ones(n), inverted), \"\\\\\\\\\"\n )\n end\nend\n\n# 1. Hilbert’s matrix Hₙ for n > 1\nfor n in 2:24\n\n A = hilb(n)\n printout(A, n, 0, false)\n\nend\n\n# 2. Random matrix Rₙ for n = 5,10,20 and c = 1, 10, 10³, 10⁷, 10^12, 10^16\nfor n in [5,10,20]\n\n for c in [1, 10, 10^3, 10^7, 10^12, 10^16]\n\n A = matcond(n, Float64(c))\n printout(A, n, c, false)\n\n end\n\nend\n", "meta": {"hexsha": "fa07dcf0ef9eb2f3a45e4142f20a8157a213aa1d", "size": 2050, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "5th-semester/on/lab/lista-2/ex-3.jl", "max_stars_repo_name": "jerry-sky/academic-notebook", "max_stars_repo_head_hexsha": "be2d350289441b99168ea40412891bc65b9cb431", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-12-28T21:53:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T19:24:47.000Z", "max_issues_repo_path": "5th-semester/on/lab/lista-2/ex-3.jl", "max_issues_repo_name": "jerry-sky/academic-notebook", "max_issues_repo_head_hexsha": "be2d350289441b99168ea40412891bc65b9cb431", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2022-02-13T18:07:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-13T18:16:07.000Z", "max_forks_repo_path": "5th-semester/on/lab/lista-2/ex-3.jl", "max_forks_repo_name": "jerry-sky/academic-notebook", "max_forks_repo_head_hexsha": "be2d350289441b99168ea40412891bc65b9cb431", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-12-28T16:05:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T16:20:00.000Z", "avg_line_length": 23.8372093023, "max_line_length": 92, "alphanum_fraction": 0.5487804878, "num_tokens": 636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947117065459, "lm_q2_score": 0.8918110382493035, "lm_q1q2_score": 0.842756714987116}} {"text": "\"\"\"\n basis(elem::Line,N,r)\n\nComputes the generalized Vandermonde matrix V of degree N (along with the\nderivative matrix Vr) at points r.\n\"\"\"\nfunction basis(elem::Line, N, r)\n V1D, Vr1D = ntuple(x->zeros(length(r), N+1),2)\n for j = 1:N+1\n V1D[:,j] .= jacobiP(r[:], 0, 0, j-1)\n Vr1D[:,j] .= grad_jacobiP(r[:], 0, 0, j-1)\n end\n return V1D, Vr1D\nend\n\n\"\"\"\n nodes(elem::Line,N)\n\nComputes interpolation nodes of degree N.\n\"\"\"\nnodes(elem::Line, N) = first(gauss_lobatto_quad(0, 0, N))\n\n\"\"\"\n equi_nodes(elem::Line,N)\n\nComputes equally spaced nodes of degree N.\n\"\"\"\nequi_nodes(elem::Line, N) = collect(LinRange(-1, 1, N+1))\n\n\"\"\"\n quad_nodes(elem::Line,N)\n\nComputes (N+1)-point Gauss quadrature rule (exact for degree 2N+1 polynomials)\n\n\"\"\"\nquad_nodes(elem::Line, N) = gauss_quad(0, 0, N)\n", "meta": {"hexsha": "c99dd4a64363c3535143abc82cb6b7b194122074", "size": 816, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/line_element.jl", "max_stars_repo_name": "stevengj/NodesAndModes.jl", "max_stars_repo_head_hexsha": "2c13546a26b23e58164f72aab2e8555b002e79e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2020-08-28T06:59:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T16:38:39.000Z", "max_issues_repo_path": "src/line_element.jl", "max_issues_repo_name": "stevengj/NodesAndModes.jl", "max_issues_repo_head_hexsha": "2c13546a26b23e58164f72aab2e8555b002e79e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-12-01T07:26:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-23T18:04:39.000Z", "max_forks_repo_path": "src/line_element.jl", "max_forks_repo_name": "stevengj/NodesAndModes.jl", "max_forks_repo_head_hexsha": "2c13546a26b23e58164f72aab2e8555b002e79e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-23T16:50:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-23T16:50:40.000Z", "avg_line_length": 22.0540540541, "max_line_length": 78, "alphanum_fraction": 0.6286764706, "num_tokens": 285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750413739075, "lm_q2_score": 0.8840392771633079, "lm_q1q2_score": 0.8427325785140116}} {"text": "\"\"\"\n Polynomials functions for spline interpolation: basis functions for b-splines\n and bernstein polynomials for bezier curves.\n\n Most polynomials have two implementations: one in which the polynomial is \n computed over the entier parameter range, the other for evaluating the \n polynomial at a single parameter value.\n\"\"\"\nmodule Polynomials\n\n # ---------------------------------------------------------------------------- #\n # B-Spline BASIS FUNCTIONS #\n # ---------------------------------------------------------------------------- #\n \"\"\"\n N_0(τ, k; i=0)\n\n Zero-th order basis function for b-splines for the i-th knot.\n for t∈[k[i], k[i+1]] = 1\n else: 0\n\n The additional \"+1\" index in the code is because in the bspline maths \n the knots are indexed starting from 0.\n \"\"\"\n function N_0(τ; k::AbstractArray, i::Int=0)\n if i+2 < length(k)\n return k[i+1] .<= τ .< k[i+2]\n else\n return k[i+1] .<= τ .<= k[i+2]\n end\n end\n\n \"\"\"\n ω(τ, j)\n\n Function used within N_D to compute the factors for the linear interpolation\n of the two lover level basis functions\n \"\"\"\n function ω(τ, j, d, k)\n Δ = k[j+d]-k[j]\n @. Δ!=0 ? (τ - k[j])/Δ : zero(τ)\n end\n\n \"\"\"\n N_D(τ, k; i=0, d=0)\n\n D-th order basis function for b-splines for the i-th knot. \n Built recursively on lower order basis functions.\n See: https://www.geometrictools.com/Documentation/BSplineCurveLeastSquaresFit.pdf\n and: https://pages.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/B-spline/bspline-basis.html\n\n The \"j=i+1\" index in the code is because in the bspline maths \n the knots are indexed starting from 0.\n \"\"\"\n function N_D(τ; k::AbstractArray, i::Int=0, d::Int=0)\n ω(τ, i+1, d, k) .* N_basis(τ; k=k, i=i, d=d-1) .+ (1 .- ω(τ, i+1+1, d, k)) .* N_basis(τ; k=k, i=i+1, d=d-1)\n end\n\n \"\"\"\n N(τ, k; i=0, d=0)\n\n B-spline basis function for the i-th knot and d-th order.\n Calls either N_0 or N_D depending on the value of d.\n \"\"\"\n N_basis(τ; k::AbstractArray, i::Int=0, d::Int=0) = (d == 0) ? N_0(τ; k, i=i) : N_D(τ; k, i=i, d=d)\n\n\n # ---------------------------------------------------------------------------- #\n # BERNSTEIN POLYNOMIALS #\n # ---------------------------------------------------------------------------- #\n \"\"\"\n bernstein(t::Float64; i::Int, n::Int)\n\n Evaluate the bernstein polynomial at parameter value `t` given the index `i` and the number\n of polynomials `n`.\n \"\"\"\n bernstein(τ; i::Int, n::Int) = @. binomial(n, i) * τ^i * (1 - τ)^(n-i) \n\n\nend", "meta": {"hexsha": "799f34cccf5d909ea46c768abdd600530817e7dd", "size": 2763, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Splines/src/Polynomials.jl", "max_stars_repo_name": "FedeClaudi/Splines", "max_stars_repo_head_hexsha": "a475aa4e423b4efe71363a5833a1709a7d59b6ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-02T16:55:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T16:55:13.000Z", "max_issues_repo_path": "Splines/src/Polynomials.jl", "max_issues_repo_name": "FedeClaudi/Splines", "max_issues_repo_head_hexsha": "a475aa4e423b4efe71363a5833a1709a7d59b6ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Splines/src/Polynomials.jl", "max_forks_repo_name": "FedeClaudi/Splines", "max_forks_repo_head_hexsha": "a475aa4e423b4efe71363a5833a1709a7d59b6ba", "max_forks_repo_licenses": ["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.9746835443, "max_line_length": 115, "alphanum_fraction": 0.4969236337, "num_tokens": 776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475715065793, "lm_q2_score": 0.8933093975331751, "lm_q1q2_score": 0.8427012507669261}} {"text": "module Gong\n\nusing Statistics, Dates\n\n#export gc_distance, rad2deg, deg2rad, histc, meshgrid, nan, findNaNmin, findNaNmax\n\nfunction gc_distance(lat1deg::Float64,lon1deg::Float64,lat2deg::Float64,lon2deg::Float64)\n # This code implements Vincenty 1975: https://www.ngs.noaa.gov/PUBS_LIB/inverse.pdf\n # In the future, need to implement: Karney 2013 https://arxiv.org/abs/1109.4448\n\n a = 6378.1370; # Earth semi major axis in km\n b = 6356.7523142; # Earth semi-minor axis in km\n R1 = 1/3 * (2*a + b);\n\n f = (a - b) / a; # flattening parameter for an elipsoid\n #f = 1/298.257223563; # defined by WGS84\n\n lat1 = deg2rad(lat1deg);\n lon1 = deg2rad(lon1deg);\n lat2 = deg2rad(lat2deg);\n lon2 = deg2rad(lon2deg);\n\n beta1 = atan((1-f)*tan(lat1)); # reduced latitude 1\n beta2 = atan((1-f)*tan(lat2)); # reduced latitude 2\n P = (beta1 + beta2)/2;\n Q = (beta2 - beta1)/2;\n\n lambda = abs(lon1 - lon2);\n sigma = atan(sqrt((cos(beta2)*sin(lambda))^2 + (cos(beta1)*sin(beta2) - sin(beta1)*cos(beta2)*cos(lambda))^2) / (sin(beta1)*sin(beta2) + cos(beta1)*cos(beta2)*cos(lambda)));\n\n alpha = asin(cos(beta1) * cos(beta2) * sin(lambda)/sin(sigma));\n sigmam = acos(cos(sigma) - 2*sin(beta1)*sin(beta2) / cos(alpha)^2)/2;\n\n\n X = (sigma - sin(sigma)) * (sin(P)^2 * cos(Q)^2) / (cos(sigma/2)^2)\n Y = (sigma + sin(sigma)) * (cos(P)^2 * sin(Q)^2) / (sin(sigma/2)^2)\n\n dist = a*(sigma - f/2 * (X+Y));\n return dist\nend\n\nfunction rad2deg(rad)\n return rad * 180.0/pi;\nend\n\nfunction deg2rad(deg)\n return deg * pi/180.0;\nend\n\n# define a histogram index function similar to matlab histc\nfunction histc(x, xnodes)\n bin = Array{Number}(undef,length(x));\n for i = 1:length(x)\n a = findlast(x[i] .>= xnodes);\n if !isnothing(a)\n bin[i] = a;\n end\n end\n return bin;\nend\n\n# emulate the behavior of Matlab's meshgrid\nfunction meshgrid(xgrid::Array{<:AbstractFloat,1},ygrid::Array{<:AbstractFloat,1})\n nx = length(xgrid);\n ny = length(ygrid);\n minx = minimum(xgrid);\n maxx = maximum(xgrid);\n miny = minimum(ygrid);\n maxy = maximum(ygrid);\n dx = (maxx .- minx) ./ (nx-1);\n dy = (maxy .- miny) ./ (ny-1);\n i = [i for j in miny:dy:maxy, i in minx:dx:maxx];\n j = [j for j in miny:dy:maxy, i in minx:dx:maxx];\n return (i,j)\nend\n\nfunction meshgrid(xgrid::Array{<:Integer,1},ygrid::Array{<:Integer,1})\n minx = minimum(xgrid);\n maxx = maximum(xgrid);\n miny = minimum(ygrid);\n maxy = maximum(ygrid);\n i = [i for j in miny:maxy, i in minx:maxx];\n j = [j for j in miny:maxy, i in minx:maxx];\n return (i,j)\nend\n\nfunction meshgrid(xgrid::UnitRange{<:Integer},ygrid::UnitRange{<:Integer})\n #minx = minimum(xgrid);\n #maxx = maximum(xgrid);\n #miny = minimum(ygrid);\n #maxy = maximum(ygrid);\n i = [i for j in ygrid[1]:ygrid[end], i in xgrid[1]:xgrid[end]];\n j = [j for j in ygrid[1]:ygrid[end], i in xgrid[1]:xgrid[end]];\n return (i,j)\nend\n\n# emulate the behavior of Matlab's nan function\nfunction nan(m::Unsigned,n::Unsigned)\n nanarray=Array{Float64,2}(undef,m,n);\n nanarray .= NaN;\nend\n\n# adopted from https://github.com/mlubin/NaNMath.jl/issues/31\nfunction findNaNmax(x::Array{<:AbstractFloat,1})\n\tresult = convert(eltype(x), NaN)\n indmax = 0\n @inbounds @simd for i in eachindex(x)\n \tv = x[i]\n if !isnan(v)\n if (isnan(result) || v > result)\n result = v\n indmax = i\n end\n end\n end\n return (result,indmax) # note the order of result and ind may be different that what's proposed by floswald as of 2019-12-03\nend\n\n# adopted from https://github.com/mlubin/NaNMath.jl/issues/31\nfunction findNaNmin(x::Array{<:AbstractFloat,1})\n\tresult = convert(eltype(x), NaN)\n indmin = 0\n @inbounds @simd for i in eachindex(x)\n \tv = x[i]\n if !isnan(v)\n if (isnan(result) || v < result)\n result = v\n indmin = i\n end\n end\n end\n return (result,indmin) # note the order of result and ind may be different that what's proposed by floswald as of 2019-12-03\nend\n\nfunction dg_pol2cart(magnitude::AbstractFloat, compassdir::AbstractFloat)\n theta = mod.(360.0 .- compassdir .+ 90.0, 360) .* pi/180.0;\n u = magnitude .* cos.(theta);\n v = magnitude .* sin.(theta);\n return u + v*im\nend\n\n# this does not work, left in for reference. can you 'repeat' function with splat or Tuple() to reproduce Matlab's repmat behavior\n#function repmat(x, shape)\n# xsize = size(x);\n# xout = reshape(repeat(x, outer=prod(shape)),[collect(size(x));collect(shape)]...);\n# return xout;\n#end\n\n# linearly scale between xmin and xmax using the range provided by xscl\nfunction minmaxscaler(x, xscl; zeromin::Bool=false)\n if zeromin == false\n xmin = minimum(skipmissing(x));\n else\n xmin = 0.0;\n end\n\n xmax = maximum(skipmissing(x));\n if xmin != xmax\n x_std = (x .- xmin) ./ (xmax - xmin);\n x_scl = x_std .* (maximum(xscl) - minimum(xscl)) .+ minimum(xscl);\n else\n x_scl = x;\n end\n return x_scl, xmin, xmax;\nend\n\n# linearly scale between xmin and xmax using the range provided in xscl\nfunction minmaxscaler(x, xscl, xminmax)\n xmin = minimum(skipmissing(xminmax));\n xmax = maximum(skipmissing(xminmax));\n if minimum(skipmissing(x)) != maximum(skipmissing(x))\n x_std = (x .- xmin) ./ (xmax - xmin);\n x_scl = x_std .* (maximum(xscl) - minimum(xscl)) .+ minimum(xscl);\n else\n x_scl = x;\n end\n return x_scl, xmin, xmax;\nend\n\n# find standard deviation of a variable, then scale to +/- n std. dev.\nfunction varscaler(varin,nstd=2.0)\n varstd = std(skipmissing(varin));\n varmean = mean(skipmissing(varin));\n varscl = (varin .- varmean) ./ (nstd * varstd);\n return varscl, varmean, varstd, nstd;\nend\n\n# manually scale the input variable using specified mean and standard deviation\nfunction varscaler_manual(varin, varmean, varstd, nstd=2.0)\n return (varin .- varmean) ./ (nstd * varstd);\nend\n\n# use specified mean and standard deviation to 'unscale' the input variable\nfunction varunscaler(varscl, varmean, varstd, nstd)\n return varscl .* (nstd * varstd) .+ varmean;\nend\n\n# this function returns the indices for stock within a specified time period\nfunction findtind(tt,trange)\n return findall(minimum(trange) .<= tt .<= maximum(trange));\nend\n\nend\n", "meta": {"hexsha": "44aa2f273f260a634f8771a74fd68ed28c582088", "size": 6422, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Gong.jl", "max_stars_repo_name": "truedichotomy/ocean_julia", "max_stars_repo_head_hexsha": "a5af89ddb719e20d5f1d324304833c87e5b93b37", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-18T18:14:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-18T18:14:33.000Z", "max_issues_repo_path": "Gong.jl", "max_issues_repo_name": "truedichotomy/ocean_julia", "max_issues_repo_head_hexsha": "a5af89ddb719e20d5f1d324304833c87e5b93b37", "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": "Gong.jl", "max_forks_repo_name": "truedichotomy/ocean_julia", "max_forks_repo_head_hexsha": "a5af89ddb719e20d5f1d324304833c87e5b93b37", "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.4803921569, "max_line_length": 177, "alphanum_fraction": 0.6292432264, "num_tokens": 2025, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377249197139, "lm_q2_score": 0.8791467801752451, "lm_q1q2_score": 0.8426953545396713}} {"text": "using LinearAlgebra\nfunction powermethod(A;maxiter=100000, tol=1e-6)\n x = normalize!(randn(size(A,1)))\n y = A*x\n λ = x'*y\n for i=1:maxiter\n if norm(y - λ*x)/(abs(λ)+1) <= tol\n break\n end\n x = normalize!(y)\n y = A*x\n λ = x'*y\n end\n if norm(y - λ*x)/(abs(λ)+1) >= tol\n @warn(\"powermethod did not converge, relative residual is \",\n norm(y - λ*x)/(abs(lam)+1))\n end\n return x, λ\nend\n##\nusing Random\nRandom.seed!(2)\nA = randn(3,3)\nv, lam = powermethod(A)\n##\nLams, V = eigen(A)\n##\n@show lam\n@show Lams[1]\n##\nfunction powermethod_explain(A,V;maxiter=9)\n x = normalize!(randn(size(A,1)))\n y = A*x\n for i=1:9\n x = normalize!(y)\n y = A*x\n println(i, \", \", V'*x)\n end\nend\nusing Random\nRandom.seed!(2)\nA = randn(3,3)\nA = A+A' # make it symmetric\nLams, V = eigen(A)\npowermethod_explain(A,V)\n## example on population growth matrix\nG = [1.0215 0.0127; 0.0627 1.0667 ]\nv, lam = powermethod(G)\n@show g = v / sum(v), lam\n", "meta": {"hexsha": "e4ce8735866e7fe5a179daebfe32cab06cfb5ed9", "size": 953, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "4-unit-3-demos/power-method.jl", "max_stars_repo_name": "dgleich/cs590-ncds", "max_stars_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-04-07T15:19:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T04:43:33.000Z", "max_issues_repo_path": "4-unit-3-demos/power-method.jl", "max_issues_repo_name": "dgleich/cs590-ncds", "max_issues_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4-unit-3-demos/power-method.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": 19.06, "max_line_length": 64, "alphanum_fraction": 0.59181532, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611574955211, "lm_q2_score": 0.8774768002981829, "lm_q1q2_score": 0.8426946356098292}} {"text": "#=\nProblem 4\n2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.\nWhat is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?\n=#\n\nimport Primes.factor\n\nfunction mergeLargest(a::Dict{Int64, Int64}, b::Dict{Int64, Int64})\n for k = keys(b)\n b_k = b[k]\n a_v = get!(a, k, b_k) # Get value or store\n if (a_v < b_k)\n a[k] = b_k\n end\n end\nend\n\np = Dict{Int64, Int64}()\nfor i = 1:20\n f = factor(i)\n mergeLargest(p, f)\nend\n\n@show p\n\nsmallest = 1\nfor k = keys(p)\n smallest *= k ^ p[k]\n println(\"key $(k), val $(p[k])\")\nend\n\n# check\nfor i = 1:20\n if ( smallest % i > 0)\n println(\"Ooops - not divisible by $(i)\")\n end\nend\n\nprintln(\"The smallest divisible number is: $(smallest)\")\n", "meta": {"hexsha": "ff35c1a6a4f949d5abd02e501f0ab96ffe15e19b", "size": 787, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problem-5.jl", "max_stars_repo_name": "mebrunet/project-euler", "max_stars_repo_head_hexsha": "95140634b82c568af468e6c065a3be823b4935c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problem-5.jl", "max_issues_repo_name": "mebrunet/project-euler", "max_issues_repo_head_hexsha": "95140634b82c568af468e6c065a3be823b4935c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problem-5.jl", "max_forks_repo_name": "mebrunet/project-euler", "max_forks_repo_head_hexsha": "95140634b82c568af468e6c065a3be823b4935c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.1951219512, "max_line_length": 106, "alphanum_fraction": 0.6365946633, "num_tokens": 264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107878954105, "lm_q2_score": 0.8991213820004279, "lm_q1q2_score": 0.8426662588382313}} {"text": "### A Pluto.jl notebook ###\n# v0.15.1\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 463264a9-0f9b-43ee-930f-74730e158372\n# we write a function that caculates the product of two matrices A and B\nfunction mult(A,B)\n\n\t# we find the sizes of A and B\n\taRows, aCols = size(A)\n\tbRows, bCols = size(B)\n\n\t# we check if the matrix sizes are consistent with multiplication\n\tif aCols != bRows\n\t\terror(\"matrix sizes don't agree\")\n\tend\n\n\t# we initialize C to a zero matrix of the appropriate size\n\tC = zeros(aRows, bCols)\n\n\t# we loop over all pairs of rows and columns\n\tfor i = 1:aRows\n\t\tfor j = 1:bCols\n\t\t\t# and for each pair we store their dot pruduct in C\n\t\t\tfor k = 1:aCols\n\t\t\t\tC[i,j] += A[i,k] * B[k,j];\n\t\t\tend\n\t\tend\n\tend\n\n\t# we return C as the answer\n\treturn C\nend\n\n# ╔═╡ c089bff8-8b2b-420e-95d4-f40026afb897\nmd\"Simple test\"\n\n# ╔═╡ 5d274440-f3b4-4b98-953c-340ca2fb8b8e\nA = [1 2; 3 4];\n\n# ╔═╡ a8dc36db-ffc4-4068-af75-890dd3a98819\nB = [2 1; 1 3];\n\n# ╔═╡ ab386751-af17-41f9-b032-3735fd3492f4\nmult(A, B)\n\n# ╔═╡ 1073d7c1-cd7f-41eb-9531-b7a63c2d6286\nmd\"Check with MATLAB built-in multiplication\"\n\n# ╔═╡ eb028ed8-2ff5-4c97-8b98-156f45402c7c\nA*B\n\n# ╔═╡ 507e8447-6446-44b3-a230-940254bedb6b\nmd\"Two $100\\times 100$ matrices of random numbers\"\n\n# ╔═╡ 413585fe-dbe5-4351-88b0-57cb415c31e5\ntime100 = @elapsed mult(rand(100,100), rand(100,100))\n\n# ╔═╡ f014193b-04d6-430f-83c1-2bee5864ea99\nmd\"Two $200\\times 200$ matrices of random numbers\"\n\n# ╔═╡ 0faabc1c-a618-4351-9876-9fce4ceab769\ntime200 = @elapsed mult(rand(200,200), rand(200,200))\n\n# ╔═╡ 31917d5e-28cf-4caf-80a4-50e630094901\nmd\"Two $1000\\times 1000$ matrices of random numbers\"\n\n# ╔═╡ 7c242e1a-c41c-4e1b-b24b-7343417fbfdd\ntime1000 = @elapsed mult(rand(1000,1000), rand(1000,1000))\n\n# ╔═╡ 695be13b-3dd7-4943-a339-17872c1d128e\nmd\"\"\"\nNow compute the ratio of the times taken for the two different sizes\nand compare with the theroetical complexity $O(n^3)$, where $n$ is the size of the matrices. Note the prediction does not match exactly because it is valid only as $n$ tends to infinity, but it is a reasonable guide.\n\"\"\"\n\n# ╔═╡ 99bdb4c4-4af0-410b-a3f8-3e3e8e13d80f\nratio = time1000/time200\n\n# ╔═╡ 25ae1cca-d886-46ca-9e57-7abd83c7ed86\npredictedRatio = (1000/200)^3\n\n# ╔═╡ 23559250-2979-40e1-87b1-f48b7eeee335\nmd\"\"\"\nThe last part shows that MATLAB is rather efficient at dealing with matrices...\n\"\"\"\n\n# ╔═╡ 426e472d-c146-41de-bf1f-bbe635a4f8cd\ntime = @elapsed rand(1000,1000)*rand(1000,1000)\n\n# ╔═╡ Cell order:\n# ╠═463264a9-0f9b-43ee-930f-74730e158372\n# ╟─c089bff8-8b2b-420e-95d4-f40026afb897\n# ╠═5d274440-f3b4-4b98-953c-340ca2fb8b8e\n# ╠═a8dc36db-ffc4-4068-af75-890dd3a98819\n# ╠═ab386751-af17-41f9-b032-3735fd3492f4\n# ╟─1073d7c1-cd7f-41eb-9531-b7a63c2d6286\n# ╠═eb028ed8-2ff5-4c97-8b98-156f45402c7c\n# ╟─507e8447-6446-44b3-a230-940254bedb6b\n# ╠═413585fe-dbe5-4351-88b0-57cb415c31e5\n# ╟─f014193b-04d6-430f-83c1-2bee5864ea99\n# ╠═0faabc1c-a618-4351-9876-9fce4ceab769\n# ╟─31917d5e-28cf-4caf-80a4-50e630094901\n# ╠═7c242e1a-c41c-4e1b-b24b-7343417fbfdd\n# ╟─695be13b-3dd7-4943-a339-17872c1d128e\n# ╠═99bdb4c4-4af0-410b-a3f8-3e3e8e13d80f\n# ╠═25ae1cca-d886-46ca-9e57-7abd83c7ed86\n# ╟─23559250-2979-40e1-87b1-f48b7eeee335\n# ╠═426e472d-c146-41de-bf1f-bbe635a4f8cd\n", "meta": {"hexsha": "3127269d623c55ea2e32f149a0b7a7e7ddf78f84", "size": 3182, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "1a/Matrix Multiplication/mult_test.jl", "max_stars_repo_name": "sje30/catam-julia", "max_stars_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-07-13T12:55:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:40:23.000Z", "max_issues_repo_path": "1a/Matrix Multiplication/mult_test.jl", "max_issues_repo_name": "sje30/catam-julia", "max_issues_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2021-07-11T21:35:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-25T12:10:58.000Z", "max_forks_repo_path": "1a/Matrix Multiplication/mult_test.jl", "max_forks_repo_name": "sje30/catam-julia", "max_forks_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-13T21:00:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-13T21:00:47.000Z", "avg_line_length": 28.4107142857, "max_line_length": 216, "alphanum_fraction": 0.7284726587, "num_tokens": 1523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9314625031628428, "lm_q2_score": 0.9046505312448598, "lm_q1q2_score": 0.8426480483209328}} {"text": "# # Exact Optimization with Rational Arithmetic\n\n# This example can be found in section 4.3 [in the paper](https://arxiv.org/pdf/2104.06675.pdf).\n# The package allows for exact optimization with rational arithmetic. For this, it suffices to set up the LMO\n# to be rational and choose an appropriate step-size rule as detailed below. For the LMOs included in the\n# package, this simply means initializing the radius with a rational-compatible element type, e.g., `1`, rather\n# than a floating-point number, e.g., `1.0`. Given that numerators and denominators can become quite large in\n# rational arithmetic, it is strongly advised to base the used rationals on extended-precision integer types such\n# as `BigInt`, i.e., we use `Rational{BigInt}`.\n\n# The second requirement ensuring that the computation runs in rational arithmetic is\n# a rational-compatible step-size rule. The most basic step-size rule compatible with rational optimization is\n# the agnostic step-size rule with ``\\gamma_t = 2/(2 + t)``. With this step-size rule, the gradient does not even need to\n# be rational as long as the atom computed by the LMO is of a rational type. Assuming these requirements are\n# met, all iterates and the computed solution will then be rational.\n\nusing FrankWolfe\nusing LinearAlgebra\n\nn = 100\nk = n\n\nx = fill(big(1)//100, n)\n\nf(x) = dot(x, x)\nfunction grad!(storage, x)\n @. storage = 2 * x\nend\n\n# pick feasible region\n# radius needs to be integer or rational\nlmo = FrankWolfe.ProbabilitySimplexOracle{Rational{BigInt}}(1)\n\n# compute some initial vertex\nx0 = FrankWolfe.compute_extreme_point(lmo, zeros(n));\n\nx, v, primal, dual_gap, trajectory = FrankWolfe.frank_wolfe(\n f,\n grad!,\n lmo,\n x0,\n max_iteration=k,\n line_search=FrankWolfe.Agnostic(),\n print_iter=k / 10,\n verbose=true,\n emphasis=FrankWolfe.blas,\n);\n\nprintln(\"\\nOutput type of solution: \", eltype(x))\n\n# Another possible step-size rule is `rationalshortstep` which computes the step size by minimizing the\n# smoothness inequality as ``\\gamma_t=\\frac{\\langle \\nabla f(x_t),x_t-v_t\\rangle}{2L||x_t-v_t||^2}``. However, as this step size depends on an upper bound on the\n# Lipschitz constant ``L`` as well as the inner product with the gradient ``\\nabla f(x_t)``, both have to be of a rational type.\n\n@time x, v, primal, dual_gap, trajectory = FrankWolfe.frank_wolfe(\n f,\n grad!,\n lmo,\n x0,\n max_iteration=k,\n line_search=FrankWolfe.RationalShortstep(),\n L=2,\n print_iter=k / 10,\n verbose=true,\n emphasis=FrankWolfe.blas,\n);\n\n# Note: at the last step, we exactly close the gap, finding the solution 1//n * ones(n)\n", "meta": {"hexsha": "3d0bd154fffac2ea395de6876ae6bde6e8eca3c6", "size": 2630, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/docs_4_rational_opt.jl", "max_stars_repo_name": "gdalle/FrankWolfe.jl-2", "max_stars_repo_head_hexsha": "c3b3903c4808e24aa9e0f655aa2f8de0f2c1571c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 48, "max_stars_repo_stars_event_min_datetime": "2021-03-27T15:50:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T15:11:21.000Z", "max_issues_repo_path": "examples/docs_4_rational_opt.jl", "max_issues_repo_name": "gdalle/FrankWolfe.jl-2", "max_issues_repo_head_hexsha": "c3b3903c4808e24aa9e0f655aa2f8de0f2c1571c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 132, "max_issues_repo_issues_event_min_datetime": "2021-03-29T18:49:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T01:33:22.000Z", "max_forks_repo_path": "docs/src/examples/4_rational_opt.jl", "max_forks_repo_name": "dviladrich95/FrankWolfe.jl", "max_forks_repo_head_hexsha": "bcb441e52918bd1103f13296082cd7a8bc22607b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2021-06-02T13:38:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T10:04:42.000Z", "avg_line_length": 38.115942029, "max_line_length": 161, "alphanum_fraction": 0.7288973384, "num_tokens": 714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167045, "lm_q2_score": 0.9086178994073576, "lm_q1q2_score": 0.8426188823817913}} {"text": "import Pkg\nPkg.activate(\"RbfInterpolationTools\")\nusing RbfInterpolationTools\nusing Plots\n\n# Lets generate some observed points\nX = hcat(rand(30) .* 6.28)\n# We will try to interpolate the sin function\ny = vec(map(x -> sin(x), X))\n\n# Lets create our interpolation environment\ninter = RbfInterpolationTools.Interpolator(X = X, y = (y))\n# Lets regenerate our interpolation domain\nX_new = hcat(0:6.28/(999):6.28)\n\n# And we simply get our answer:\ny_new = RbfInterpolationTools.interpolateMesh(inter, X_new)\n\n# Lets plot the results\nplot()\nPlots.scatter!(X, y, label = \"Shown points\")\nPlots.plot!(X_new, y_new, label = \"Interpolation\")\n\n# The derivative shall be the cosine function. Lets verify it:\n\n∂y = vec(map(x -> RbfInterpolationTools.gradientPoint(inter, [x])[1], X_new))\nPlots.plot!(X_new, ∂y, label = \"Interpolated Derivative\")\n\n# We can actually compare it with the real values\nPlots.plot!(X_new, vec(map(x -> cos(x), X_new)), label = \"Real Derivative\")", "meta": {"hexsha": "270983e210d0eeb541610b7eff4d55d41ab17769", "size": 956, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/usagePoint.jl", "max_stars_repo_name": "munozariasjm/RbfInterpolationTools.jl", "max_stars_repo_head_hexsha": "f9889bf24e774761a973db25c9a9540970e5cfbc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-03T19:26:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T19:26:24.000Z", "max_issues_repo_path": "examples/usagePoint.jl", "max_issues_repo_name": "munozariasjm/RbfInterpolationTools.jl", "max_issues_repo_head_hexsha": "f9889bf24e774761a973db25c9a9540970e5cfbc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-01-03T01:08:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-16T22:40:06.000Z", "max_forks_repo_path": "examples/usagePoint.jl", "max_forks_repo_name": "munozariasjm/RbfInterpolationTools.jl", "max_forks_repo_head_hexsha": "f9889bf24e774761a973db25c9a9540970e5cfbc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8666666667, "max_line_length": 77, "alphanum_fraction": 0.7322175732, "num_tokens": 271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341975270265, "lm_q2_score": 0.8807970842359877, "lm_q1q2_score": 0.8426006118622389}} {"text": "using Printf\nusing LinearAlgebra\nusing DelimitedFiles\nusing Quaternions\n\n#EXERCISE MADE BY ERIK MARTÍN GARZÓN & DAVID BOCES OBIS\n#-------------------------------------------------------------------- EXERCISE 3.1\nangle_input = 90 #degrees\naxis_input = [0;1;2] #axis z\nglobal axis_norm\n\n\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 = 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\nend\n\nmat = axis_angle_to_mat(axis_input, angle_input)\n\nprintln(\"The rotation matrix composed of AXIS = \", axis,\n \" normalized as \", axis_norm, \" and ANGLE = \", angle,\n \" degrees is R = \", mat)\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\nprintln()\nprintln(\"The rotation matrix R = \", mat,\n\" has the following ANGLE (in degrees) and unit AXIS: \\n\", mat_to_axis_angle(mat))\n\nq = quat(1,0,0,0)\n\nglobal q2\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 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\nend\n\nprintln()\nprintln(\"The Quaternion composed of AXIS = \", axis,\n \" normalized as \", axis_norm, \" and ANGLE = \", angle,\n \" degrees is q = \", axis_angle_to_quat(axis_norm, angle_input))\n\nfunction quat_to_axis_angle(q3)\n angle3 = 2*acosd(q3.s);\n axis_norm[1] = q3.v1/sind(angle3/2)\n axis_norm[2] = q3.v2/sind(angle3/2)\n axis_norm[3] = q3.v3/sind(angle3/2)\n\n return angle, axis_norm\nend\n\nprintln()\nprintln(\"The Quaternion q = \", q2,\n\" has the following ANGLE (in degrees) and unit AXIS: \\n\", quat_to_axis_angle(q2))\n\nglobal matQuat\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\nprintln()\nprintln(\"The Quaternion q = \", q, \" as a rotation matrix R = \", quat_to_mat(q))\n\nquat_to_mat(q)\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\n\nend\n\nprintln()\nprintln(\"The rotation matrix R = \", matQuat,\n\" has the following Quaternion q: \\n\", mat_to_quat(matQuat))\n", "meta": {"hexsha": "6ade5a24c56516bf8fa26273d44228dadcf7b9c3", "size": 3936, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "quat.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": "quat.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": "quat.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": 29.3731343284, "max_line_length": 171, "alphanum_fraction": 0.6028963415, "num_tokens": 1341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693674025231, "lm_q2_score": 0.8872045966995027, "lm_q1q2_score": 0.8425510281042273}} {"text": "### A Pluto.jl notebook ###\n# v0.12.10\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# ╔═╡ e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, Distributions, StatsPlots\n\tRandom.seed!(0)\nend\n\n# ╔═╡ ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing4.15\"\n\n# ╔═╡ fa68607e-22e5-11eb-0558-c9a4d9f77426\nbegin\n\tmu1, sigma1 = 10, 5\n\tmu2, sigma2 = 40, 12\n\tdist1, dist2 = Normal(mu1,sigma1), Normal(mu2,sigma2)\n\tp = 0.3\n\tmixRv() = (rand() <= p) ? rand(dist1) : rand(dist2)\n\n\tn = 2000\n\tdata = [mixRv() for _ in 1:n]\nend\n\n# ╔═╡ cd520f9c-2509-11eb-36ce-8340182a95eb\nbegin\n\tdensity(data, c=:blue, label=\"Density via StatsPlots\", \n\t\t\txlims=(-20,80), ylims=(0,0.035))\n\tstephist!(data, bins=50, c=:black, norm=true, \n\t\tlabel=\"Histogram\", xlabel=\"x\", ylabel = \"Density\")\nend\n\n# ╔═╡ 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing4.15\"\n\n# ╔═╡ Cell order:\n# ╟─ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# ╠═e077ab16-22e5-11eb-15ed-5f0654bf7328\n# ╠═e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# ╠═fa68607e-22e5-11eb-0558-c9a4d9f77426\n# ╠═cd520f9c-2509-11eb-36ce-8340182a95eb\n# ╟─475ff888-22e6-11eb-2354-09f8f40a8e12\n", "meta": {"hexsha": "c17d7b116557fb3e6efb47b86408c8a4adccd692", "size": 1208, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/04/listing4.15.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/04/listing4.15.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/04/listing4.15.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 24.16, "max_line_length": 56, "alphanum_fraction": 0.7061258278, "num_tokens": 612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.9173026528034426, "lm_q1q2_score": 0.8425243643919436}} {"text": "using Revise\n\nincludet(\"src/Spring.jl\")\nIArray = InternalArray\n\n\n# 3. Validating the solution --------------------------------------------------------------\n\nconst step = 1e-3\nconst nit = Int(40/step) # round to avoid small rounding errors\n\n# We define a problem with no friction\nprob = SpringProblem(p0 = 0.8, v0 = 0, m = 1, k = 1.5)\n\nx = eulermethod(prob, step, nit)\n\ntimeline = [prob.t0 + i*step for i in 0:length(x)-1]\nplot(timeline, IArray(x, 1), label = \"euler method\")\n\n# And also define the solution we would have obtained by analytic methods\n# Reference: https://en.wikipedia.org/wiki/Simple_harmonic_motion\nω0 = sqrt(prob.k/prob.m)\ng(t) = prob.p0*cos(ω0*t) + prob.v0/ω0*sin(ω0*t)\n\ny = g.(timeline)\nplot!(timeline, y, label = \"analytic solution\")\n\n# (The comparison in my computer is very close)\n# (Which means that for the second step we could have taken a smaller L very likely)\n# Let's check the norm of the difference:\n\nerr = maximum(norm.(y-IArray(x, 1)))\n\n\n# 4. Choosing the step to obtain a final error in the order of 1e-2 ----------------------\n\n# Reference: https://en.wikipedia.org/wiki/Euler_method#Local_truncation_error\n# The global truncation error is bounded by $\\frac{hM}{2L}(ℯ^{L(t-t_0)}-1)$ where\n# M is an upper bound for the second derivative of the solution (in the interval) and\n# L is the lipschitz constant of f.\n\n# This will be explained later, but L < k+b and M can be taken to be maximum of the\n# second derivative for the approximated solution.\n\n# <-- Copied from the definitions\nn = 1\nfunction f(t, x)\n p = x[1:n]\n v = x[n+1:2*n]\n return [v; (-prob.k*p -prob.b*v + [prob.A*sin(prob.ω*t)])/prob.m]\nend\n\nM = maximum((norm ∘ f).(timeline, x))\nL = prob.k+prob.b\nerr_ct = M/L*(ℯ^(L*40)-1) # error constant\ntarget_step = 10e-2/err_ct\n\n# After checking that with 1e-3 the error is approximately $0.02$\n# for the solution without friction.\n# It seems natural to admit that an appropiate step to obtain\n# an error less than 1e-2 is approximately 5e-4.\n# This can be verified using this same script but\n# with a smaller error for the method without friction.\n\n# After doing it, I saw that it was not enough and\n# the error was still slightly larger than 1e-2.\n# With the step equal to 1e-4, the error for the problem without friction is $0.0023$.\n# Hence, we can assume that it won't be much larger for the problem with friction.\n\nsavefig(\"media/spring_validation.png\")\n\n", "meta": {"hexsha": "0a60e689f002805a974b2ecdf8c98caf4e65cb61", "size": 2411, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/spring_validation.jl", "max_stars_repo_name": "useredsa/numeric-differential-equations", "max_stars_repo_head_hexsha": "7647a20120ce0a05ee5223b0ce81ad63d8aee115", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/spring_validation.jl", "max_issues_repo_name": "useredsa/numeric-differential-equations", "max_issues_repo_head_hexsha": "7647a20120ce0a05ee5223b0ce81ad63d8aee115", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/spring_validation.jl", "max_forks_repo_name": "useredsa/numeric-differential-equations", "max_forks_repo_head_hexsha": "7647a20120ce0a05ee5223b0ce81ad63d8aee115", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4861111111, "max_line_length": 91, "alphanum_fraction": 0.6856076317, "num_tokens": 705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896780646392, "lm_q2_score": 0.9149009561531425, "lm_q1q2_score": 0.8424313568772827}} {"text": "\"\"\"\n binary_search(array::Array{Int64,1}, target::Int64)\n\nThe binary search algorithm (BSA) finds a target value's position within a sorted array by\nusing a half-interval cut per each cycle. Thus, the BSA compares the target value to the\nvalue of the array's middle element. In the case of inequality, the half array-piece in\nwhich the target cannot be will be erased. Next, the search continues on the remaining\nhalf array-piece and starts taking the middle element to compare it to the target value.\nThis procedure has to be continued until the target value is found. The search may have to\nbe stopped with a remaining empty half array-piece; consequently, the target is not in the\narray. For more information see: [https://en.wikipedia.org/wiki/Binary_search_algorithm](https://en.wikipedia.org/wiki/Binary_search_algorithm)\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,11, 12, 14, 16, 18, 19, 20, 21, 22, 23, 24, 33, 35, 42, 47]\njulia> target = 12\njulia> ClassicAlgorithmsCollections.binary_search(arr, target)\n3\n```\n\"\"\"\nfunction binary_search(array::Array{Int64,1}, target::Int64)\n left = 1\n right = length(array)\n\n while left <= right\n # Generating the middle element position\n mid = fld((left + right), 2)\n # If element is larger than mid, then it can only be present in right subarray\n if array[mid] < target\n left = mid + 1\n # If element is smaller than mid, then it can only be present in left subarray\n elseif array[mid] > target\n right = mid - 1\n # If element is present at the middle itself\n else\n return mid\n end\n end\n return nothing\nend\n", "meta": {"hexsha": "25064d426abe75551c94a3319682ee07181c0a0e", "size": 1836, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SortingAndSearching/BinarySearch.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/BinarySearch.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/BinarySearch.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": 38.25, "max_line_length": 143, "alphanum_fraction": 0.7004357298, "num_tokens": 471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383028, "lm_q2_score": 0.9149009480320036, "lm_q1q2_score": 0.8424313513881087}} {"text": "module NewtonsMethod\n\nusing ForwardDiff, LinearAlgebra\n\n\nD(g) = x -> ForwardDiff.derivative(g, x)\n\n\n\nfunction newtonroot(f,fprime, x_0=0.8, tolerance=1.0E-7, maxiter=1000)\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)/fprime(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\nnewtonroot(f,x_0=0.8, tolerance=1.0E-7, maxiter=1000)=newtonroot(f,D(f), x_0, tolerance, maxiter)\n\nexport newtonroot\n\n\nend # module\n", "meta": {"hexsha": "f95d45a24fe3c2e156a9a6e27ee99360a5538ca9", "size": 630, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NewtonsMethod.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": "src/NewtonsMethod.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": "src/NewtonsMethod.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": 21.0, "max_line_length": 97, "alphanum_fraction": 0.6555555556, "num_tokens": 212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474155747541, "lm_q2_score": 0.8824278710924296, "lm_q1q2_score": 0.8424074865695201}} {"text": "# by Lazaro Alonso\n# port from the original code used in:\n# L Alonso, et. al. https://doi.org/10.1093/comnet/cnx053\n\n# using CairoMakie # HIDE\nusing LinearAlgebra, Random, CairoMakie\nCairoMakie.activate!()\nfunction RRGAdjacencyM(;lengthBase = 1, radius = 0.1, nodes = 500, rseed = 123)\n Random.seed!(rseed)\n xy = rand(nodes, 2)\n x = lengthBase .* xy[:,1]\n y = xy[:,2] ./ lengthBase\n matrixAdjDiag = Diagonal(√2 * randn(nodes))\n matrixAdj = zeros(nodes, nodes)\n for point in 1:nodes-1\n distance = sqrt.((x[point + 1:end] .- x[point]).^2 .+ (y[point + 1:end] .- y[point]).^2)\n dindx = findall(distance .<= radius) .+ point\n if length(dindx) > 0\n rnd = randn(length(dindx))\n matrixAdj[point, dindx] = rnd\n matrixAdj[dindx, point] = rnd\n end\n end\n return (matrixAdj .+ matrixAdjDiag, x, y)\nend\nadjacencyM, x, y = RRGAdjacencyM()\n\nfunction getGraphEdges(adjMatrix, x, y)\n xyos = []\n weights = [] \n for i in 1:length(x), j in i+1:length(x)\n if adjMatrix[i,j] != 0.0\n push!(xyos, [x[i], y[i]])\n push!(xyos, [x[j], y[j]])\n push!(weights, adjMatrix[i,j])\n push!(weights, adjMatrix[i,j])\n end\n end\n return (Point2f0.(xyos), Float32.(weights))\nend\n\nfunction plotGraph(adjacencyM, x, y)\n cmap = (:Spectral_11, 0.75)\n adjmin = minimum(adjacencyM)\n adjmax = maximum(adjacencyM)\n diagValues = diag(adjacencyM)\n segm, weights = getGraphEdges(adjacencyM, x, y)\n \n fig, ax, pltobj = linesegments(segm, color = weights, colormap = cmap, \n linewidth = abs.(weights)/2, colorrange = (adjmin, adjmax), \n figure = (;resolution = (500,400)), axis = (;aspect = DataAspect()))\n scatter!(ax, x, y, color = diagValues, markersize = 3*abs.(diagValues),\n colorrange = (adjmin, adjmax), colormap = cmap)\n limits!(ax, -0.02,1.02,-0.02,1.02)\n Colorbar(fig[1,2], pltobj, label = \"weights\")\n fig\nend\n#plotGraph(adjacencyM, x, y)\nrrgraph = with_theme(theme_black()) do\n plotGraph(adjacencyM, x, y)\nend\nsave(joinpath(@__DIR__, \"output\", \"RRGraph.png\"), rrgraph, px_per_unit = 2.0) # HIDE\nusing Pkg # HIDE\nPkg.status([\"CairoMakie\", \"LinearAlgebra\", \"Random\"]) # HIDE", "meta": {"hexsha": "c172c7ef202d178aaeeb1c7cac52569a23a0a316", "size": 2246, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "_assets/scripts/RRGraph.jl", "max_stars_repo_name": "MisterBiggs/BeautifulMakie", "max_stars_repo_head_hexsha": "5e43819d1f2af8b80bf45895bc117cd55197d972", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 249, "max_stars_repo_stars_event_min_datetime": "2021-06-07T13:10:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T04:55:41.000Z", "max_issues_repo_path": "_assets/scripts/RRGraph.jl", "max_issues_repo_name": "MisterBiggs/BeautifulMakie", "max_issues_repo_head_hexsha": "5e43819d1f2af8b80bf45895bc117cd55197d972", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2021-06-09T06:03:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-19T16:17:43.000Z", "max_forks_repo_path": "_assets/scripts/RRGraph.jl", "max_forks_repo_name": "MisterBiggs/BeautifulMakie", "max_forks_repo_head_hexsha": "5e43819d1f2af8b80bf45895bc117cd55197d972", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16, "max_forks_repo_forks_event_min_datetime": "2021-06-09T05:21:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T09:16:08.000Z", "avg_line_length": 35.09375, "max_line_length": 96, "alphanum_fraction": 0.6081923419, "num_tokens": 740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939913343093499, "lm_q2_score": 0.8962513738264114, "lm_q1q2_score": 0.8423986250253237}} {"text": "# Fgt.jl\n\n\n\n###### Foster–Greer–Thorbecke indices #####\n\"\"\"\n fgt(v, α, z)\n\nCompute the Foster–Greer–Thorbecke Index of a vector `v` at a specified `α`\nand a given poverty threshold `z`.\n\n# Examples\n```julia\njulia> using Inequality\njulia> fgt([8, 5, 1, 3, 5, 6, 7, 6, 3], 2, 4)\n0.0763888888888889\n```\n\"\"\"\nfunction fgt(v::AbstractVector{<:Real}, α::Real, z::Real)::Float64\n \n if α == 0\n return headcount(v, z)\n elseif α == 1\n return poverty_gap(v, z)\n else \n return sum( ((1 .- (v[v .< z]/z)).^α) )/ length(v)\n end \nend \n\n\n###### Weighted Foster–Greer–Thorbecke indices #####\n\"\"\"\n fgt(v, w, α, z)\n\nCompute the Foster–Greer–Thorbecke Index of a vector `v` at a specified `α` and \na given poverty threshold `z`, 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> fgt([8, 5, 1, 3, 5, 6, 7, 6, 3], collect(0.1:0.1:0.9), 2, 4)\n0.05555555555555555\n```\n\"\"\"\nfunction fgt(v::AbstractVector{<:Real}, w::AbstractVector{<:Real}, α::Real, z::Real)::Float64\n \n if α == 0\n return headcount(v, w, z)\n elseif α == 1\n return poverty_gap(v, w, z)\n else \n checks_weights(v, w)\n\n return sum(((1 .- (v[v .< z] /z)).^α) .* w[v .< z])/ sum(w)\n end\nend\n\n\nfunction fgt(v::AbstractVector{<:Real}, w::AbstractWeights, α::Real, z::Real)::Float64\n \n if α == 0\n return headcount(v, w, z)\n elseif α == 1\n return poverty_gap(v, w, z)\n else \n checks_weights(v, w)\n\n return sum(((1 .- (v[v .< z] /z)).^α) .* w[v .< z] )/ w.sum\n end\nend\n\n\n\"\"\"\nwfgt(v, w)\n\nCompute the Foster–Greer–Thorbecke Index of `v` with weights `w`. See also [`fgt`](@fgt)\n\"\"\"\nwfgt(v::AbstractVector{<:Real}, w::AbstractVector{<:Real}, α::Real, z::Real)::Float64 = fgt(v, w, α, z)\n\nwfgt(v::AbstractVector{<:Real}, w::AbstractWeights, α::Real, z::Real)::Float64 = fgt(v, w, α, z)", "meta": {"hexsha": "eaba2001b0b0b7a29498ec2dfee6c9c9c2db00a8", "size": 1987, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Fgt.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/Fgt.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/Fgt.jl", "max_forks_repo_name": "JosepER/Inequality.jl", "max_forks_repo_head_hexsha": "fd1bb964856dc37eb2648f3825123de9d8181578", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.2317073171, "max_line_length": 103, "alphanum_fraction": 0.5858077504, "num_tokens": 715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422199928904, "lm_q2_score": 0.8856314813647587, "lm_q1q2_score": 0.8423614932808687}} {"text": "\n# ------------------------------------------------------------------------------------------\n# # Julia 中的线性代数\n# > Based on work by Andreas Noack Jensen (MIT) (http://www.econ.ku.dk/phdstudent/noack/)\n# > with edits from Jane Herriman\n#\n# ## 目录\n# - [基础线性代数操作](#基础线性代数操作)\n# - [乘法](#乘法)\n# - [转置](#转置)\n# - [转置的乘法](#转置的乘法)\n# - [解线性方程组](#解线性方程组)\n# - [特殊的矩阵结构](#特殊的矩阵结构)\n# - [大规模问题](#大规模问题)\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# ## 基础线性代数操作\n# 定义一个随机矩阵\n# ------------------------------------------------------------------------------------------\n\nA = rand(1:4,3,3)\n\n# ------------------------------------------------------------------------------------------\n# 定义一个元素全为 1 的向量\n# ------------------------------------------------------------------------------------------\n\nx = fill(1.0, (3))\n\n# ------------------------------------------------------------------------------------------\n# 注意 $A$ 的类型为 `Array{Int64,2}`,而 $x$ 的类型为 `Array{Float64,1}`。\n#\n# Julia 定义 `Array{Type,1}` 的别名为向量 `Vector{Type}`,`Array{Type,2}` 的别名为矩阵 `Matrix{Type}` 。\n#\n# 许多线性代数的基础操作和其他语言一样\n#\n# ### 乘法\n# ------------------------------------------------------------------------------------------\n\nb = A*x\n\n# ------------------------------------------------------------------------------------------\n# ### 转置\n# 就像在其他语言中 `A'` 表示对 `A` 进行共轭转置\n# ------------------------------------------------------------------------------------------\n\nA'\n\n# ------------------------------------------------------------------------------------------\n# 我们还可以通过 `transpose` 函数获得转置矩阵\n# ------------------------------------------------------------------------------------------\n\ntranspose(A)\n\n# ------------------------------------------------------------------------------------------\n# ### 转置的乘法\n# Julia 中某些情况下可以省略 `*` 号\n# ------------------------------------------------------------------------------------------\n\nA'A\n\n# ------------------------------------------------------------------------------------------\n# ### 解线性方程组\n# 用方阵 $A$ 表示的线性方程组 $Ax=b$ 可以用左除运算符(函数)`\\` 求解\n# ------------------------------------------------------------------------------------------\n\nA\\b\n\n# ------------------------------------------------------------------------------------------\n# ## 特殊的矩阵结构\n#\n# 矩阵结构在线性代数中非常重要。\n# 接触一下大一些的线型系统就可以看到矩阵结构有*多*重要了。\n#\n# 用线性代数标准包 `LinearAlgebra` 可以获得结构化的矩阵(structured matrices):\n# ------------------------------------------------------------------------------------------\n\nusing LinearAlgebra\n\nn = 1000\nA = randn(n,n);\n\n# ------------------------------------------------------------------------------------------\n# Julia 可以推断特殊矩阵结构,比如判断对称矩阵\n# ------------------------------------------------------------------------------------------\n\nAsym = A + A'\nissymmetric(Asym)\n\n# ------------------------------------------------------------------------------------------\n# 但有时候浮点错误会比较麻烦\n# ------------------------------------------------------------------------------------------\n\nAsym_noisy = copy(Asym)\nAsym_noisy[1,2] += 5eps()\n\nissymmetric(Asym_noisy)\n\n# ------------------------------------------------------------------------------------------\n# 幸运的是我们可以通过如 `Diagonal`,`Triangular`,`Symmetric`,`Hermitian`,`Tridiagonal`\n# 和 `SymTridiagonal` 这样的函数来明确地创建矩阵\n# ------------------------------------------------------------------------------------------\n\nAsym_explicit = Symmetric(Asym_noisy);\n\n# ------------------------------------------------------------------------------------------\n# 我们来看看 Julia 计算 `Asym`,`Asym_noisy` 和 `Asym_explicit` 的特征值各要花多少时间\n# ------------------------------------------------------------------------------------------\n\n@time eigvals(Asym);\n\n@time eigvals(Asym_noisy);\n\n@time eigvals(Asym_explicit);\n\n# ------------------------------------------------------------------------------------------\n#\n# 本例中,使用 `Symmetric()` 处理 `Asym_noisy` 后让计算效率提高了约5倍\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# ### 大规模问题\n# 使用 `Tridiagonal` 和 `SymTridiagonal` 类型储存三对角矩阵(tridiagonal matrices)\n# 让处理大规模的三对角矩阵问题变为可能。\n#\n# 以下问题如果使用稠密的 `Matrix` 类型储存,在个人计算机上是无法进行求解的。\n# ------------------------------------------------------------------------------------------\n\nn = 1_000_000;\nA = SymTridiagonal(randn(n), randn(n-1));\n@time eigmax(A)\n", "meta": {"hexsha": "bba369e9880fd27a5276961637f99da2b62037e3", "size": 4495, "ext": "jl", "lang": "Julia", "max_stars_repo_path": ".nbexports/zh-cn/intro-to-julia-ZH/简短版/02.Julia中的线性代数.jl", "max_stars_repo_name": "NahsiN/JuliaTutorials", "max_stars_repo_head_hexsha": "6d61077a0f6565e19305cddab0adde79d232e147", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 535, "max_stars_repo_stars_event_min_datetime": "2020-07-15T14:56:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T12:50:32.000Z", "max_issues_repo_path": ".nbexports/zh-cn/intro-to-julia-ZH/简短版/02.Julia中的线性代数.jl", "max_issues_repo_name": "NahsiN/JuliaTutorials", "max_issues_repo_head_hexsha": "6d61077a0f6565e19305cddab0adde79d232e147", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 42, "max_issues_repo_issues_event_min_datetime": "2018-02-25T22:53:47.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-14T02:15:50.000Z", "max_forks_repo_path": ".nbexports/zh-cn/intro-to-julia-ZH/简短版/02.Julia中的线性代数.jl", "max_forks_repo_name": "NahsiN/JuliaTutorials", "max_forks_repo_head_hexsha": "6d61077a0f6565e19305cddab0adde79d232e147", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 394, "max_forks_repo_forks_event_min_datetime": "2020-07-14T23:22:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T20:12:57.000Z", "avg_line_length": 34.053030303, "max_line_length": 92, "alphanum_fraction": 0.2491657397, "num_tokens": 1131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422179154884, "lm_q2_score": 0.8856314783461302, "lm_q1q2_score": 0.8423614885699111}} {"text": "import Base: angle\n\n_dot2(v::Vector, w::Vector) = v[1] * w[1] + v[2] * w[2]\n\n_no_intersect_error = \"The two clines do not intersect; no angle can be calculated.\"\n\nfunction angle(L::Line, M::Line)::Float64\n\n if slope(L) == slope(M)\n return 0\n end\n\n v = collect(reim(L.a - L.b))\n w = collect(reim(M.a - M.b))\n\n top = _dot2(v, w)\n bot = sqrt(_dot2(v, v) * _dot2(w, w))\n θ = abs(acos(top / bot))\n\n if θ > π / 2\n θ = π - θ\n end\n return θ\n\nend\n\n\"\"\"\n angle(C::Cline, D::Cline)\nReturn the angle between two clines. If `C` and `D` are equal, or are parallel lines, return 0.\nOtherwise, if `C` and `D` do not intersect, an error is thrown.\n\"\"\"\nfunction angle(C::Cline, D::Cline)\n if C == D\n return 0\n end\n\n X = C ∩ D\n\n if length(X) == 0\n error(_no_intersect_error)\n end\n\n z = first(X)\n F = LFT(0, 1, 1, -z)\n\n CC = F(C)\n DD = F(D)\n if !(isa(CC, Line) && isa(DD, Line))\n error(\"This can't happen, but it did.\")\n end\n return angle(CC, DD)\nend\n", "meta": {"hexsha": "57f737373615814c947667b3c1d507b959d11902", "size": 1034, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/angle.jl", "max_stars_repo_name": "scheinerman/Clines.jl", "max_stars_repo_head_hexsha": "8d32bef6d6cd3485bf418a4c1969a8bb0c566d3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/angle.jl", "max_issues_repo_name": "scheinerman/Clines.jl", "max_issues_repo_head_hexsha": "8d32bef6d6cd3485bf418a4c1969a8bb0c566d3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/angle.jl", "max_forks_repo_name": "scheinerman/Clines.jl", "max_forks_repo_head_hexsha": "8d32bef6d6cd3485bf418a4c1969a8bb0c566d3b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.5094339623, "max_line_length": 95, "alphanum_fraction": 0.5444874275, "num_tokens": 365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422227627598, "lm_q2_score": 0.8856314632529871, "lm_q1q2_score": 0.8423614785070817}} {"text": "#=\nP27 (**) Group the elements of a set into disjoint subsets.\na) In how many ways can a group of 9 people work in 3 disjoint subgroups of 2, 3 and 4 persons? Write a function that generates all the possibilities and returns them in a list.\n\nExample:\n* (group3 '(aldo beat carla david evi flip gary hugo ida))\n( ( (ALDO BEAT) (CARLA DAVID EVI) (FLIP GARY HUGO IDA) )\n... )\n\nb) Generalize the above predicate in a way that we can specify a list of group sizes and the predicate will return a list of groups.\n\nExample:\n* (group '(aldo beat carla david evi flip gary hugo ida) '(2 2 5))\n( ( (ALDO BEAT) (CARLA DAVID) (EVI FLIP GARY HUGO IDA) )\n... )\n\nNote that we do not want permutations of the group members; i.e. ((ALDO BEAT) ...) is the same solution as ((BEAT ALDO) ...). However, we make a difference between ((ALDO BEAT) (CARLA DAVID) ...) and ((CARLA DAVID) (ALDO BEAT) ...).\n\nYou may find more about this combinatorial problem in a good book on discrete mathematics under the term \"multinomial coefficients\".\n=#\n", "meta": {"hexsha": "0d8e4601c4203f8e6c2c8779abb89ced43271bc3", "size": 1018, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "JL-27.jl", "max_stars_repo_name": "microamp/jl-99", "max_stars_repo_head_hexsha": "5d49a7e1617394e6cbc06f1a94fe6230b3025d73", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "JL-27.jl", "max_issues_repo_name": "microamp/jl-99", "max_issues_repo_head_hexsha": "5d49a7e1617394e6cbc06f1a94fe6230b3025d73", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "JL-27.jl", "max_forks_repo_name": "microamp/jl-99", "max_forks_repo_head_hexsha": "5d49a7e1617394e6cbc06f1a94fe6230b3025d73", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.4761904762, "max_line_length": 232, "alphanum_fraction": 0.7111984283, "num_tokens": 299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284088025362857, "lm_q2_score": 0.9073122276263202, "lm_q1q2_score": 0.8423566587770818}} {"text": "# example using julia 1.0.3\n# -- run using julia fit.jl or include(\"fit.jl\") in repl\n#\n# like rust, functions in julia can either use an explicit return statement or\n# in the absence of one, will evaluate to the last expression in the function\n\n# include if plotting\n# using Gadfly\n\n# -- functions\n\"\"\"find_coeffs: given arrays x, y of length n for a 2D function y = f(x),\n return coefficients for a fitted polynomial of order n\"\"\"\nfunction find_coeffs(x::AbstractArray, y::AbstractArray)\n # first thought to use @assert,\n # but after reading https://github.com/JuliaLang/julia/issues/30610\n # found that check() || error(...) preferred over @assert exceptions\n length(x) == length(y) || error(\"Uneven arrays in find_coeffs\")\n\n # we isolate for the coefficient vector a = [a0, a1, a2, ...] in the\n # expression y = B a .\n # The n by n matrix B has rows of [x0 ^ 0, x0 ^ 1, x0 ^ 2, ...]\n\n # populate a matrix of these rows using matrix comprehension\n B = [x_i ^ n for x_i in x, n in 0:length(x) - 1]\n\n # find the coeffecient vector and return it\n inv(B) * y\nend\n\n# type constraint here is used to only allow vectors passed in\n# -- where T allows T to range over all concrete types\n\"\"\"Interpolate using the polynomial coefficient values 'coeffs' and the given\nargument 'arg'\"\"\"\nfunction coeff_interpolate(coeffs::AbstractArray{T,1}, arg) where T\n sum([coeffs[i] * arg ^ (i-1) for i in eachindex(coeffs)])\nend\n\n# -- examples --\n\n# ex 1 -> pass in three x and three y values for a parabolic fit\nparabola_coeffs = find_coeffs([1,2,3], [1,4,9])\nprintln(\"The coefficients for points along x^2 are:\")\nprintln(parabola_coeffs)\nprintln()\n\n# ex 2 -> pass uneven arrays for length check\n# bad_coeffs = find_coeffs([1], [])\n\n# ex 3 -> check the default scalar type in the array\nprintln(\"Default vector type:\")\nprintln(typeof(find_coeffs([1], [1])));\nprintln()\n\n# ex 4 -> force the return vector to be of Float16's\nf16_coeffs = find_coeffs(Vector{Float16}([1, 3, 5]), [2, 3, 9])\nprintln(\"Array type coerced to:\")\nprintln(typeof(f16_coeffs), \"\\n\")\n\n# ex 5 -> interpolation\nprintln(\"The interpolated value at x = 4 for a model of the unit parabola:\")\nprintln(coeff_interpolate(parabola_coeffs, 4), \"\\n\")\n\n# # ex 6 -> plotting\n# println(\"Plotting the quadratic fit from zero to ten as output.svg\")\n# x = 1:10\n# y = [coeff_interpolate(parabola_coeffs, xi) for xi in x]\n#\n# # write output file\n# # -- took ~4GiB memory and roughly 30 seconds to plot (output was only 9.6 kB)\n#\n# # @time draw(SVG(\"output.svg\", 6inch, 3inch), plot(x=x, y=y, Geom.point, Geom.line))\n\n", "meta": {"hexsha": "95fcda552f90b9edb51cc5898899457864a84ca3", "size": 2596, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "curve-fit/fit.jl", "max_stars_repo_name": "mxxo/numerics", "max_stars_repo_head_hexsha": "1ebc8aee369fdc0938bfdf4567afd4fb79011191", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "curve-fit/fit.jl", "max_issues_repo_name": "mxxo/numerics", "max_issues_repo_head_hexsha": "1ebc8aee369fdc0938bfdf4567afd4fb79011191", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "curve-fit/fit.jl", "max_forks_repo_name": "mxxo/numerics", "max_forks_repo_head_hexsha": "1ebc8aee369fdc0938bfdf4567afd4fb79011191", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5616438356, "max_line_length": 86, "alphanum_fraction": 0.68605547, "num_tokens": 741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937711, "lm_q2_score": 0.9073122113355091, "lm_q1q2_score": 0.8423566382608333}} {"text": "\"\"\"\nThe [centroid of a triangle](https://en.wikipedia.org/wiki/Centroid#Of_a_triangle) is the point of\nintersection of its medians (the lines joining each vertex with the midpoint of the opposite side).\nThe [Centroids Exists Theorem](https://sites.math.rutgers.edu/~zeilberg/PG/CentroidExists.html)\nstates that the three medians indeed intersect at single point.\n\"\"\"\nmodule Centroid\n\nusing Plots\nusing SymPy\nusing PlaneGeometry\nusing PlaneGeometry.GeoPlots\n\nexport \n centroid_proof, centroid_draw, centroid_rand, centroid\n\n\"\"\"\n centroid_draw(📐️::Triangle)\n\nVerify Centroid Exists Theorem for the triangle `📐️`.\n\"\"\"\nfunction centroid_draw(tri::Triangle)\n trishape=shape(tri)\n\n cpt, medians = centroid(tri)\n\n if cpt == nothing\n return (nothing, false)\n end\n\n plt = plot(tri, fill=(0, :green), aspect_ratio=:equal, fillalpha= 0.2, leg=false)\n\n for e in medians\n plot!(e, leg=false, color=:orange)\n end\n\n plt = scatter!(shape([vertices(tri)..., cpt]), \n leg=false, \n aspect_ratio=:equal, \n color=[:red, :red, :red, :green], \n series_annotations = text.([\"A\", \"B\", \"C\", \"cpt\"], :bottom))\n\n plt, true\nend\n\n\"\"\"\n centroid_draw(A, B, C)\n\nVerify Centroid Exists theorem.\n\"\"\"\nfunction centroid_draw(A, B, C)\n tri = Triangle(A, B, C)\n\n centroid_draw(tri)\nend\n\n\"\"\"\n centroid_draw(xA, yA, xB, yB, xC, yC)\n\nVerify Centroid Exists theorem.\n\"\"\"\nfunction centroid_draw(xA, yA, xB, yB, xC, yC)\n A = Point(xA, yA); \n B = Point(xB, yB); \n C = Point(xC, yC);\n\n centroid_draw(A, B, C)\nend\n\n\"\"\"\n centroid_rand()\n\nVerify Centroid Exists Theorem for a random triangle.\n\"\"\"\nfunction centroid_rand()\n pts = rand(0:1//10:1,6);\n plt, hold = centroid_draw(pts...)\nend\n\n\"\"\"\n centroid_proof()\n\nProve Centroid Exists Theorem.\n\"\"\"\nfunction centroid_proof()\n @vars by cx positive=true;\n @vars cy;\n\n A = Point(0, 0); B = Point(0, by); C = Point(cx, cy);\n tri = Triangle(A, B, C)\n\n cpt, medians = centroid(tri)\n cpt != nothing\nend\n\n\n\"\"\"\n centroid(📐️)\n\nFind the centroid and the three medians of `📐️`.\n\"\"\"\nfunction centroid(tri)\n medians = map(i->median(circshift(vertices(tri), i)...), 0:2)\n cpt = concurrent(medians)\n cpt, medians \nend\n\nend\n", "meta": {"hexsha": "134759d477d00a55fee1b37625274c5c98965d11", "size": 2261, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/theorem/Centroid.jl", "max_stars_repo_name": "newptcai/PlaneGeometry.jl", "max_stars_repo_head_hexsha": "fe2644fdf824a364daa1ce362bf5557d40775226", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-05-12T04:22:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T23:20:31.000Z", "max_issues_repo_path": "src/theorem/Centroid.jl", "max_issues_repo_name": "newptcai/PlaneGeometry.jl", "max_issues_repo_head_hexsha": "fe2644fdf824a364daa1ce362bf5557d40775226", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/theorem/Centroid.jl", "max_forks_repo_name": "newptcai/PlaneGeometry.jl", "max_forks_repo_head_hexsha": "fe2644fdf824a364daa1ce362bf5557d40775226", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.7431192661, "max_line_length": 99, "alphanum_fraction": 0.6417514374, "num_tokens": 657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362488, "lm_q2_score": 0.8976953010025941, "lm_q1q2_score": 0.8421495224795047}} {"text": "export LogitLogLoss, value, deriv, deriv2\r\n\r\n# set up loss functions\r\n# The Flux implemnetation\r\n# logloss = logitbinarycrossentropy\r\n\r\n# alternate definition\r\n# softmax(w) = 1/(1 + exp(-w))\r\n# logloss(w, y) = -(y*log(softmax(w)) + (1-y)*log(1-softmax(w)))\r\n\r\n\r\n#x,y = rand(1000), rand([0.0, 1.10], 1000)\r\n#Flux.logitbinarycrossentropy.(x,y) ≈ logloss.(x, y)\r\n\r\n# function logitcrossentropy(logŷ::AbstractVecOrMat, y::AbstractVecOrMat; weight = 1)\r\n# return -sum(y .* logsoftmax(logŷ) .* weight) * 1 // size(y, 2)\r\n# end\r\n\r\nimport LossFunctions: SupervisedLoss, deriv, value, deriv2\r\nstruct LogitLogLoss <: SupervisedLoss end\r\n\r\nbinarysoftmax(w) = 1/(1 + exp(-w))\r\n\r\nvalue(::LogitLogLoss, y::Number, w::Number) = -(y*log(binarysoftmax(w)) + (1-y)*log(1-binarysoftmax(w)))\r\n\r\n# https://www.wolframalpha.com/input/?i=f%28w%29+%3D+-%28y*log%281%2F%281+%2B+exp%28-w%29%29%29+%2B+%281-y%29*log%281-1%2F%281+%2B+exp%28-w%29%29%29%29%2C+df%2Fdw\r\nderiv(::LogitLogLoss, y::Number, w::Number) = -binarysoftmax(-w) - y + 1\r\n\r\n# https://www.wolframalpha.com/input/?i=f%28w%29+%3D+-%28e%5Ew+%28-1+%2B+y%29+%2B+y%29%2F%281+%2B+e%5Ew%29%2C+df%2Fdw\r\nderiv2(::LogitLogLoss, y::Number, w::Number) = exp(w)*(binarysoftmax(-w)^2)\r\n\r\ng(loss::SupervisedLoss, y, warmstart) = begin\r\n\tderiv(loss, y, warmstart)\r\nend\r\n\r\nh(loss::SupervisedLoss, y, warmstart) = begin\r\n\tderiv2(loss, y, warmstart)\r\nend\r\n\r\n\r\n# begin: Zygote.jl\r\n# g(loss::Function, y, warmstart) = begin\r\n# \tgres = gradient(x->loss(x, y), warmstart)\r\n# \tgres[1]\r\n# end\r\n\r\n# h(loss::Function, y, warmstart) = begin\r\n# hres = hessian(x->loss(x[1], y), [warmstart])\r\n# hres[1]\r\n# end\r\n# end: Zygote.jl\r\n\r\n# begin: ForwardDiff.jl\r\n# g(loss::Function, y, warmstart) = begin\r\n# gres = ForwardDiff.gradient(x->loss(x[1], y), [warmstart])\r\n# gres[1]\r\n# end\r\n\r\n# h(loss::Function, y, warmstart) = begin\r\n# hres = ForwardDiff.hessian(x->loss(x[1], y), [warmstart])\r\n# hres[1]\r\n# end\r\n# end: ForwardDiff.jl\r\n", "meta": {"hexsha": "e1428ca276a999e6c73f109c5dd8779211e53745", "size": 1964, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/g_h.jl", "max_stars_repo_name": "altre/JLBoost.jl", "max_stars_repo_head_hexsha": "4a6096aa394d8440c3a5dd52954099c1e44c8e2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 64, "max_stars_repo_stars_event_min_datetime": "2019-11-13T05:14:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T11:24:14.000Z", "max_issues_repo_path": "src/g_h.jl", "max_issues_repo_name": "altre/JLBoost.jl", "max_issues_repo_head_hexsha": "4a6096aa394d8440c3a5dd52954099c1e44c8e2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25, "max_issues_repo_issues_event_min_datetime": "2019-11-12T16:06:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-26T03:25:05.000Z", "max_forks_repo_path": "src/g_h.jl", "max_forks_repo_name": "altre/JLBoost.jl", "max_forks_repo_head_hexsha": "4a6096aa394d8440c3a5dd52954099c1e44c8e2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2020-01-16T15:33:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T20:19:08.000Z", "avg_line_length": 30.6875, "max_line_length": 163, "alphanum_fraction": 0.6354378819, "num_tokens": 743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240142763573, "lm_q2_score": 0.8976952968970955, "lm_q1q2_score": 0.8421495155221096}} {"text": "#=\n持橋,大羽 著 「ガウス過程と機械学習」(機械学習プロフェッショナルシリーズ)\n多変量ガウス分布のサンプリングのJuliaによる実装\n=#\n\nusing LinearAlgebra\nusing Plots\nusing LaTeXStrings\n\nμ1 = μ2 = 0.0\n\n𝛍 = [\n μ1\n μ2\n]\n\nσ11 = σ22 = 1.0\nσ12 = σ21 = -0.7\n\nΣ = [\n σ11 σ12\n σ21 σ22\n]\n\nfunction 𝒩(𝐱...; 𝛍 = 𝛍, Σ = Σ)\n Λ = inv(Σ)\n D = length(𝛍)\n return √(det(Λ)) * exp(-0.5 * (𝐱 .- 𝛍)' * Λ * (𝐱 .- 𝛍)) / √(2π)^D\nend\n\n\nx1min, x1max = -4.0, 4.0\nx2min, x2max = -4.0, 4.0\nx1 = range(x1min, x1max, length = 50)\nx2 = range(x2min, x2max, length = 50)\nz = 𝒩.(x1', x2)\ncontour(x1, x2, z)\nplot!(\n xlabel = L\"x_1\",\n ylabel = L\"x_2\",\n aspect_ratio = 1,\n xlims = [-4.0, 4.0],\n ylims = [-4.0, 4.0],\n)\nstrΣ=\"\\\\sigma_{11}=$σ11, \\\\sigma_{12}=$σ12, \\\\sigma_{21}=$σ21, \\\\sigma_{22}=$σ22\"\nstr𝛍=\"\\\\mu = [$μ1, $μ2]\"\ntitle!(latexstring(\"\\\\mathcal{N}(x \\\\mid \\\\mu, \\\\Sigma),\\\\ $str𝛍 , \\\\atop $strΣ\"))\n\n\n# Box–Muller transform を用いた方法\nL = cholesky(Σ).L\ncL = size(L, 2)\n\nboxmuller(r1, r2) = √(-2 * log(r1)) * sin(2π * r2)\nunivariate(n...) = boxmuller.(rand(n...), rand(n...))\n\nfunction multivariate(n)\n x = univariate(cL, n) # cL 次元ベクトルを n 個生成する\n return L * x # cL 次元ベクトル を変換して 𝒩(0, Σ) に従うサンプルを生成\nend\n\nxy = multivariate(100)\nscatter!(xy[1, :], xy[2, :],color=:blue, label=\"boxmuller\")\n\n# Distributions.jl でサンプルを作成\nd = MvNormal(𝛍, Σ)\nxy = rand(d,100)\nscatter!(xy[1,:], xy[2,:],color=:red, label=\"mvnormal\")\n", "meta": {"hexsha": "eaf44aff4426e6da39313c8ec8a2f1975a34f45f", "size": 1353, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "plotExer/mutivariateGaussian/multivariate.jl", "max_stars_repo_name": "terasakisatoshi/juliaExer", "max_stars_repo_head_hexsha": "e3c2195f39de858915a3dcd47684eccbb7ecb552", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-02T01:24:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-04T12:03:25.000Z", "max_issues_repo_path": "plotExer/mutivariateGaussian/multivariate.jl", "max_issues_repo_name": "terasakisatoshi/juliaExer", "max_issues_repo_head_hexsha": "e3c2195f39de858915a3dcd47684eccbb7ecb552", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "plotExer/mutivariateGaussian/multivariate.jl", "max_forks_repo_name": "terasakisatoshi/juliaExer", "max_forks_repo_head_hexsha": "e3c2195f39de858915a3dcd47684eccbb7ecb552", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.6086956522, "max_line_length": 82, "alphanum_fraction": 0.5683665928, "num_tokens": 742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012686491107, "lm_q2_score": 0.8902942377652497, "lm_q1q2_score": 0.8420414195493663}} {"text": "f(x) = sin(x)\n\nfunction simpsons_rule(a, b, n)\n h = (b - a) / (2*n)\n res = 0.0\n\n for i in 0:2*n\n if (i==0 || i==2*n)\n res += f(a + i*h)\n elseif (i % 2 == 1)\n res += 4 * f(a + i*h)\n else\n res += 2 * f(a + i*h)\n end\n end\n\n res * h / 3\nend\n\nprintln(\"Analytical=\", 2)\nprintln(\"Numerical=\", simpsons_rule(0, pi, 100))", "meta": {"hexsha": "c410b317230461b02bc25c099f98a15b4f30b17b", "size": 388, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "calculus/simpsons_rule.jl", "max_stars_repo_name": "nocotan/numerical_calculus.jl", "max_stars_repo_head_hexsha": "76b46b22d04e2e7e82cf44788c4f48ce25d59847", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-01-07T06:26:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-24T06:21:01.000Z", "max_issues_repo_path": "calculus/simpsons_rule.jl", "max_issues_repo_name": "nocotan/numerical_calculus.jl", "max_issues_repo_head_hexsha": "76b46b22d04e2e7e82cf44788c4f48ce25d59847", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-01-10T08:22:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-08T13:31:00.000Z", "max_forks_repo_path": "calculus/simpsons_rule.jl", "max_forks_repo_name": "nocotan/numerical_calculus.jl", "max_forks_repo_head_hexsha": "76b46b22d04e2e7e82cf44788c4f48ce25d59847", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-01-10T05:59:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T13:22:34.000Z", "avg_line_length": 18.4761904762, "max_line_length": 48, "alphanum_fraction": 0.4097938144, "num_tokens": 147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172688214138, "lm_q2_score": 0.8872045862611166, "lm_q1q2_score": 0.8418837528807313}} {"text": "module problem115\n\ndescription = \"\"\"\nCounting block combinations II\n\nA row measuring n units in length has red blocks with a minimum length of m units placed on it, such that any two red blocks (which are allowed to be different lengths) are separated by at least one black square.\nLet the fill-count function, F(m, n), represent the number of ways that a row can be filled.\nFor example, F(3, 29) = 673135 and F(3, 30) = 1089155.\nThat is, for m = 3, it can be seen that n = 30 is the smallest value for which the fill-count function first exceeds one million.\nIn the same way, for m = 10, it can be verified that F(10, 56) = 880711 and F(10, 57) = 1148904, so n = 57 is the least value for which the fill-count function first exceeds one million.\n\nFor m = 50, find the least value of n for which the fill-count function first exceeds one million.\n\"\"\"\n\nfunction F(m::Integer, n :: Integer, memo = zeros(Int, n))\n # trivial cases\n if n < 1 return 1 end\n\n # Count the total with each block size, and block position, \n # recursively counting the ways to fill the remaining space at the end of the row. \n if memo[n] == 0\n total = 1\n for blocksize = m:n, blockpos = 1:(n-blocksize+1)\n total += F(m, n - blockpos - blocksize, memo)\n end\n memo[n] = total\n end\n return memo[n]\nend\n\n\n\nusing Base.Test\n\n@test F(3, 29) == 673135\n@test F(3, 30) == 1089155 \n@test F(10, 56) == 880711 \n@test F(10, 57) == 1148904\n@test F(50, 167) == 978181\n@test F(50, 168) == 1053389 # <- answer\n\nend", "meta": {"hexsha": "5bec42e8380ebd980661e34cf0d29a8dc2205215", "size": 1494, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/problem115.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/problem115.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/problem115.jl", "max_forks_repo_name": "mbuhot/mbuhot-euler-solutions", "max_forks_repo_head_hexsha": "30066543cfd2d84976beb0605839750b64f4b8ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5714285714, "max_line_length": 212, "alphanum_fraction": 0.688085676, "num_tokens": 454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660976007597, "lm_q2_score": 0.8824278680004707, "lm_q1q2_score": 0.8418062696505673}} {"text": "module RootFinding\n\nexport bisect_root, secant_root\n\nfunction bisect_root(f, a, b; rtol=1e-8, atol=1e-8)\n fa = f(a)\n fb = f(b)\n\n @assert fa*fb < zero(fa)\n\n while abs(a-b) > atol + rtol*(abs(a) + abs(b))/2\n m = (a + b)/2\n fm = f(m)\n\n if fa*fm < zero(fa)\n fb = fm\n b = m\n else\n fa = fm\n a = m\n end\n end\n\n return (a+b)/2\nend\n\nfunction secant_root(f, a, b; rtol=1e-8, atol=1e-8)\n fa = f(a)\n fb = f(b)\n\n @assert fa*fb < zero(fa)\n\n # Secant guesses and function values:\n sg0 = a\n sg1 = b\n sf0 = fa\n sf1 = fb\n\n while abs(sg1-sg0) > atol + rtol*(abs(sg0) + abs(sg1))/2\n sg = sg0 - sf0*(sg1-sg0)/(sf1-sf0)\n\n if sg < a || sg > b\n m = (a+b)/2\n fm = f(m)\n\n if fm*fa > zero(fa)\n a = m\n fa = fm\n else\n b = m\n fb = fm\n end\n\n sg0 = a\n sg1 = b\n sf0 = fa\n sf1 = fb\n else\n sg0 = sg1\n sf0 = sf1\n sg1 = sg\n sf1 = f(sg)\n end\n end\n\n return sg1\nend\n\n\n\nend # module\n", "meta": {"hexsha": "c058dbc73d329b48edd7db788ec323bdf46437a2", "size": 1202, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/RootFinding.jl", "max_stars_repo_name": "Farr-PHY-604/RootFinding.jl", "max_stars_repo_head_hexsha": "29e76be4756a7e3e861953138b56f1268fab40c3", "max_stars_repo_licenses": ["MIT"], "max_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": "Farr-PHY-604/RootFinding.jl", "max_issues_repo_head_hexsha": "29e76be4756a7e3e861953138b56f1268fab40c3", "max_issues_repo_licenses": ["MIT"], "max_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": "Farr-PHY-604/RootFinding.jl", "max_forks_repo_head_hexsha": "29e76be4756a7e3e861953138b56f1268fab40c3", "max_forks_repo_licenses": ["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.6944444444, "max_line_length": 60, "alphanum_fraction": 0.3893510815, "num_tokens": 411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660962919971, "lm_q2_score": 0.8824278633625322, "lm_q1q2_score": 0.8418062640712427}} {"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(θ)\n rot_mat = Matrix{Float64}(undef, 2, 2)\n rot_mat[1, 1] = cos(θ)\n rot_mat[1, 2] = -sin(θ)\n rot_mat[2, 1] = sin(θ)\n rot_mat[2, 2] = cos(θ)\n\n return rot_mat\nend\n", "meta": {"hexsha": "eb6acb784f5b23b2bc37b1e83cc7041a22f6a40d", "size": 499, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/matrix/rotation-matrix.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/matrix/rotation-matrix.jl", "max_issues_repo_name": "AugustoCL/Julia", "max_issues_repo_head_hexsha": "1bf4e4a7829fafc64290d903bcbfdd48eab839e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/matrix/rotation-matrix.jl", "max_forks_repo_name": "AugustoCL/Julia", "max_forks_repo_head_hexsha": "1bf4e4a7829fafc64290d903bcbfdd48eab839e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1875, "max_line_length": 132, "alphanum_fraction": 0.6873747495, "num_tokens": 160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9728307676766119, "lm_q2_score": 0.865224084314688, "lm_q1q2_score": 0.8417166101561515}} {"text": "using LinearAlgebra\r\n\r\n# integrate sinh^(n)(ax) from 0 to r\r\nfunction integrate_sinh(n; r=1.0, a=1.0)\r\n if n==0\r\n return r\r\n elseif n==1\r\n return (cosh(a*r)-1)/a\r\n else\r\n return (sinh(a*r)^(n-1))*cosh(a*r)/(a*n) - (n-1)/n * integrate_sinh(n-2,r=r, a=a)\r\n end \r\nend \r\n \r\n\r\nfunction hyp_radial_density(r, d; curvature=-1.0, radius=1.0)\r\n# k = 1/(curvature^2)\r\n k = 1.0\r\n hyp_r = (sinh(r/k))^(d-1)/integrate_sinh(d-1,r=radius, a=radius/k)\r\n return hyp_r\r\nend \r\n\r\n\r\nfunction euc_radial_density(r, d; radius=1.0)\r\n return d*(r^(d-1))/radius^d\r\nend\r\n\r\n# rejection sampling n=numofpts points from density dens, where the argument lies between 0 and maxval\r\n\r\nfunction rejection_sampling(dens::Function, maxval,numofpts=1)\r\n max_val = dens(maxval)\r\n iter = 1\r\n rands = Array{Float64,1}(undef, numofpts)\r\n while iter <= numofpts\r\n x = rand()*maxval\r\n val = dens(x)\r\n u = rand() \r\n if u*max_val < val\r\n rands[iter] = x\r\n iter+=1\r\n end\r\n end\r\n return rands \r\nend\r\n\r\n\r\nfunction sample_hyp_rad(d, numofpts=1; curvature=-1.0, radius=1.0)\r\n rands = rejection_sampling(x->hyp_radial_density(x,d,curvature=curvature, radius=radius), radius,numofpts)\r\n \r\n # ...radius within the Poincare ball\r\n euc_rands = map(x->tanh(x/2.0),rands)\r\n return euc_rands\r\nend\r\n\r\nfunction sample_euc_rad(d, numofpts=1; radius=1.0)\r\n rands = rejection_sampling(x->euc_radial_density(x,d,radius=radius), radius, numofpts)\r\n return rands\r\nend\r\n\r\nfunction sample_sph(d, numofpts=1; curvature=1.0)\r\n rands = []\r\n i=0\r\n while i<=numofpts\r\n vec = randn(d+1)\r\n if vec[d+1]>0 \r\n push!(rands, normalize(vec))\r\n i+=1\r\n end\r\n end\r\n return rands\r\nend\r\n\r\nfunction sample_sphere(d, numofpts=1)\r\n vecs = randn(d, numofpts)\r\n rands = []\r\n for i=1:numofpts\r\n push!(rands, normalize(vecs[:,i]))\r\n end\r\n return rands\r\nend\r\n\r\nfunction sample_hyp(d, numofpts=1; radius=1.0, curvature=-1)\r\n sphere_pts = sample_sphere(d,numofpts)\r\n radii = sample_hyp_rad(d, numofpts, radius=radius, curvature=curvature)\r\n ball_pts = [radii[i]*sphere_pts[i] for i=1:numofpts]\r\n return ball_pts \r\nend\r\n\r\nfunction sample_euc(d, numofpts=1; radius=1.0)\r\n sphere_pts = sample_sphere(d,numofpts)\r\n radii = sample_euc_rad(d, numofpts, radius=radius)\r\n ball_pts = [radii[i]*sphere_pts[i] for i=1:numofpts]\r\n return ball_pts \r\nend\r\n\r\n\r\nfunction sample_ball(d, numofpts=1; radius=1.0, curvature=0.0)\r\n sphere_pts = sample_sphere(d,numofpts)\r\n if curvature < 0\r\n radii = sample_hyp_rad(d, numofpts, radius=radius, curvature=curvature)\r\n ball_pts = [radii[i]*sphere_pts[i] for i=1:numofpts]\r\n elseif curvature == 0.0\r\n radii = sample_euc_rad(d, numofpts, radius=radius)\r\n ball_pts = [radii[i]*sphere_pts[i] for i=1:numofpts]\r\n elseif curvature > 0\r\n ball_pts = sample_sph(d, numofpts, curvature=curvature) \r\n end\r\nend\r\n\r\nfunction hyp_distance(pts; curvature=-1.0)\r\n distances = zeros(length(pts), length(pts))\r\n for i=1:length(pts)\r\n for j=1:i-1\r\n nx = 1-(norm(pts[i]))^2\r\n ny = 1-(norm(pts[j]))^2\r\n delta = 2 * norm(pts[i]-pts[j])^2/(nx*ny)\r\n distances[i,j] = acosh(1+delta)\r\n distances[j,i] = distances[i,j]\r\n end\r\n end\r\n return distances\r\nend\r\n\r\nfunction euc_distance(pts)\r\n distances = zeros(length(pts), length(pts))\r\n for i=1:length(pts)\r\n for j=1:i-1\r\n distances[i,j] = norm(pts[i]-pts[j])\r\n distances[j,i] = distances[i,j]\r\n end\r\n end\r\n return distances\r\nend\r\n\r\nfunction sph_distance(pts; curvature=1.0)\r\n distances = zeros(length(pts), length(pts))\r\n for i=1:length(pts)\r\n for j=1:i-1\r\n distances[i,j] = acos(dot(pts[i],pts[j]))\r\n distances[j,i] = distances[i,j]\r\n end\r\n end\r\n return distances\r\nend\r\n\r\nfunction distance_matrix(pts; curvature=0.0)\r\n if curvature < 0\r\n return hyp_distance(pts, curvature=curvature)\r\n elseif curvature == 0\r\n return euc_distance(pts)\r\n elseif curvature > 0\r\n return sph_distance(pts, curvature=curvature)\r\n end\r\nend\r\n\r\nfunction to_density(matr)\r\n dens_matr = zeros(size(matr,1), size(matr,2))\r\n n = size(matr)[1]\r\n all_entries = sort(setdiff(unique(matr), 0.0))\r\n total = binomial(n,2)\r\n for i=1:n\r\n for j=i+1:n\r\n dens_matr[i,j] = (findfirst(x->x==matr[i,j], all_entries))/total\r\n dens_matr[j,i] = dens_matr[i,j]\r\n end\r\n end\r\n return dens_matr \r\nend\r\n\r\nfunction to_density!(matr)\r\n matr = to_density(matr)\r\n return matr \r\nend\r\n \r\n", "meta": {"hexsha": "4c9125952b0387f8963c593251f7471a04a66bda", "size": 4819, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/archive/GeometricSampling.jl", "max_stars_repo_name": "edd26/TopologyPreprocessing.jl", "max_stars_repo_head_hexsha": "273497114e8adf84244d3b24b0155b3ae813b84d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-08T02:01:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-08T02:01:57.000Z", "max_issues_repo_path": "src/archive/GeometricSampling.jl", "max_issues_repo_name": "edd26/TopologyPreprocessing", "max_issues_repo_head_hexsha": "12948c0ff3885f8fc2fa6b98d46b8d1c599715fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-11-30T16:38:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T15:10:02.000Z", "max_forks_repo_path": "src/archive/GeometricSampling.jl", "max_forks_repo_name": "edd26/TopologyPreprocessing", "max_forks_repo_head_hexsha": "12948c0ff3885f8fc2fa6b98d46b8d1c599715fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6954022989, "max_line_length": 111, "alphanum_fraction": 0.5893338867, "num_tokens": 1449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9728307653134903, "lm_q2_score": 0.8652240860523327, "lm_q1q2_score": 0.8417166098019561}} {"text": "function sieve_of_atkin(limit)\n primes = Int64[]\n\n sieve = falses(limit)\n\n square_root_of_limit = round(Int64, sqrt(limit))\n\n for x in 1:square_root_of_limit\n for y in 1:square_root_of_limit\n n = (4 * x * x) + (y * y)\n\n if n <= limit && (n % 12 == 1 || n % 12 == 5)\n sieve[n] = !sieve[n]\n end\n\n n = (3 * x * x) + (y * y)\n\n if n <= limit && n % 12 == 7\n sieve[n] = !sieve[n]\n end\n\n n = (3 * x * x) - (y * y)\n\n if x > y && n <= limit && n % 12 == 11\n sieve[n] = !sieve[n]\n end\n end\n end\n\n sieve[2] = true\n\n sieve[3] = true\n\n push!(primes, 2)\n\n push!(primes, 3)\n\n n = 5\n\n while n <= square_root_of_limit\n if sieve[n]\n i = n * n\n\n while i < limit\n sieve[i] = false\n\n i += n * n\n end\n\n push!(primes, n)\n end\n\n n += 2\n end\n\n while n < limit\n if sieve[n]\n push!(primes, n)\n end\n\n n += 2\n end\n\n primes\nend\n\nn = 10001\n\nlimit = round(Int64, (n * log(n)) + (n * (log(log(n)))))\n\nprintln(sieve_of_atkin(limit)[n])\n", "meta": {"hexsha": "c33ecb2d2ceb67832130c7ac7c39dda9b9d489e7", "size": 1232, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/007/007.jl", "max_stars_repo_name": "seaneshbaugh/rosetta-euler", "max_stars_repo_head_hexsha": "14f24dfc347e7d9a4c9c0f090acf2811aa65f453", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 36, "max_stars_repo_stars_event_min_datetime": "2015-01-24T08:11:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-21T00:32:00.000Z", "max_issues_repo_path": "julia/007/007.jl", "max_issues_repo_name": "seaneshbaugh/rosetta-euler", "max_issues_repo_head_hexsha": "14f24dfc347e7d9a4c9c0f090acf2811aa65f453", "max_issues_repo_licenses": ["MIT"], "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/007/007.jl", "max_forks_repo_name": "seaneshbaugh/rosetta-euler", "max_forks_repo_head_hexsha": "14f24dfc347e7d9a4c9c0f090acf2811aa65f453", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2015-01-24T08:17:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T16:10:56.000Z", "avg_line_length": 17.1111111111, "max_line_length": 57, "alphanum_fraction": 0.4017857143, "num_tokens": 384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542852576265, "lm_q2_score": 0.8774767746654976, "lm_q1q2_score": 0.8416356086344526}} {"text": "@doc raw\"\"\"\r\n```\r\nalbedo,illumination_direction,slant,tilt = estimate_img_properties(img::AbstractArray)\r\n```\r\nAttempts to calculate the illumination properties of an image for use in SFS\r\nalgorithms.\r\n# Output\r\nReturns albedo (ρ), illumination vector (I), slant (σ) and tilt (τ) of the image as Float,\r\nArray{Float} of size 3, Float and Float respectively.\r\n# Details\r\nThe illumination properties can be estimated using the first and second\r\nmoments and the gradients of the image (``E_x, E_y``) brightness as per the following:\r\n\r\n```math\r\n\\begin{gathered}\r\n\\mu_1=\\dfrac{\\pi}{4}\\rho\\cos\\sigma\\\\\\\\\\mu_2=\\dfrac{1}{6}\\rho^2(1+3\\cos^2\\sigma)\\\\\r\n\\\\\\rho=\\dfrac{\\sqrt{6\\pi\\mu_2-48\\mu_1^2}}{\\pi}\\\\\\\\\\cos\\sigma=\\dfrac{4\\mu_1}{\\sqrt\r\n{6\\pi\\mu_2-48\\mu_1^2}}\\\\\\\\\\tan\\tau=\\dfrac{\\text{average}(E_y)}{\\text{average}\r\n(E_x)}\\\\\\\\I=[\\cos\\tau\\sin\\sigma,\\sin\\tau\\sin\\sigma,\\cos\\sigma]\r\n\\end{gathered}\r\n```\r\nNote: Properties are an estimate and may not be correct under all conditions.\r\n# Arguments\r\nThe function arguments are described in more detail below.\r\n## `img`\r\nAn `AbstractArray` storing the grayscale value of each pixel within\r\nthe range [0,1].\r\n# Example\r\nCompute properties of synthetic image generated using `generate_surface`.\r\n```julia\r\nusing Images, ShapeFromShading\r\n\r\n#generate synthetic image\r\nimg = generate_surface(SynthSphere(), 1, [0.2,0,0.9], radius = 5)\r\n\r\n#estimate the properties\r\nalbedo, illumination_direction, slant, tilt = estimate_img_properties(img)\r\n```\r\n# Reference\r\n1. T. Ping-Sing and M. Shah, \"Shape from shading using linear approximation\", Image and Vision Computing, vol. 12, no. 8, pp. 487-498, 1994. [doi:10.1016/0262-8856(94)90002-7](https://doi.org/10.1016/0262-8856(94)90002-7)\r\n\"\"\"\r\nfunction estimate_img_properties(img::AbstractArray)\r\n E = Array{Float64}(img)\r\n #calculate spatial gradient of img\r\n Ey, Ex = imgradients(E, KernelFactors.sobel, \"replicate\")\r\n #normalize gradient\r\n nEx = similar(E)\r\n nEy = similar(E)\r\n Exy = sqrt.((Ex.^2) .+ (Ey.^2))\r\n nEx = Ex ./ (Exy .+ eps())\r\n nEy = Ey ./ (Exy .+ eps())\r\n\r\n #calculate means\r\n μ₁ = mean(E)\r\n μ₂ = mean(E.^2)\r\n\r\n #calculate desired values\r\n g = sqrt((6.0 * (π^2) * μ₂) - (48.0 * (μ₁^2)))\r\n ρ = g / π\r\n t = (4 * μ₁) / g\r\n if t > 1.0\r\n t = 1.0\r\n elseif t < -1.0\r\n t = -1.0\r\n end\r\n σ = acos(t)\r\n τ = atan(mean(nEy) / mean(nEx))\r\n if τ < 0\r\n τ = τ + π;\r\n end\r\n I = [cos(τ) * sin(σ), sin(τ) * sin(σ), cos(σ)]\r\n return ρ, I, σ, τ\r\nend\r\n", "meta": {"hexsha": "601b32856142fde979744be47d21aa9200e41dba", "size": 2513, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/estimatealbedo.jl", "max_stars_repo_name": "betttris13/ShapeFromShading.jl", "max_stars_repo_head_hexsha": "c486ad60d1675a65aacfe61dc1ef4d308bd534e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/estimatealbedo.jl", "max_issues_repo_name": "betttris13/ShapeFromShading.jl", "max_issues_repo_head_hexsha": "c486ad60d1675a65aacfe61dc1ef4d308bd534e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/estimatealbedo.jl", "max_forks_repo_name": "betttris13/ShapeFromShading.jl", "max_forks_repo_head_hexsha": "c486ad60d1675a65aacfe61dc1ef4d308bd534e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9594594595, "max_line_length": 222, "alphanum_fraction": 0.6382809391, "num_tokens": 831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9706877692486438, "lm_q2_score": 0.8670357512127872, "lm_q1q2_score": 0.8416209992035625}} {"text": "\"\"\"\n KL(p::Beta, q::Beta)\n\nSee [KL Beta](https://en.wikipedia.org/wiki/Beta_distribution#Quantities_of_information_(entropy))\n\"\"\"\nfunction KL(p::Beta, q::Beta)\n αp, βp = params(p)\n αq, βq = params(q)\n return logbeta(αq, βq) - logbeta(αp, βp) + (αp - αq) * digamma(αp) +\n (βp - βq) * digamma(βp) + (αq - αp + βq - βp) * digamma(αp + βp)\nend\n\n\"\"\"\n KL(p::Exponential, q::Exponential)\n\nSee [KL Exponential](https://en.wikipedia.org/wiki/Exponential_distribution#Kullback%E2%80%93Leibler_divergence)\n\"\"\"\nfunction KL(p::Exponential, q::Exponential)\n λp = scale(p)\n λq = scale(q)\n return log(λp) - log(λq) + λq / λp - 1\nend\n\n\"\"\"\n KL(p::Gamma, q::Gamma)\n\nSee [KL Gamma](https://en.wikipedia.org/wiki/Gamma_distribution#Kullback%E2%80%93Leibler_divergence)\n\"\"\"\nfunction KL(p::Gamma, q::Gamma)\n # We use the parametrization with the rate β\n αp, αq = shape.((p, q))\n βp, βq = rate.((p, q))\n return (αp - αq) * digamma(αp) - loggamma(αp) + loggamma(αq) +\n αq * (log(βp) - log(βq)) + αp * (βq - βp) / βp\nend\n\n\"\"\"\n KL(p::InverseGamma, q::InverseGamma)\n\nSee [KL Inverse-Gamma](https://en.wikipedia.org/wiki/Inverse-gamma_distribution#Properties)\n\"\"\"\nfunction KL(p::InverseGamma, q::InverseGamma)\n # We can reuse the implementation of Gamma\n return KL(Gamma(shape(p), rate(p)), Gamma(shape(q), rate(q)))\nend\n\n\"\"\"\n KL(p::Normal, q::Normal)\n\nSee [KL Gaussian](https://en.wikipedia.org/wiki/Normal_distribution#Other_properties)\n\"\"\"\nfunction KL(p::Normal, q::Normal)\n μp, σp = params(p)\n μq, σq = params(q)\n return 0.5 * (abs2(σp / σq) + abs2((μp - μq) / σq) - 1 + 2 * (log(σq) - log(σp)))\nend\n\n\"\"\"\n KL(p::Poisson, q::Poisson)\n\nSee [KL Poisson](https://en.wikipedia.org/wiki/Poisson_distribution#Other_properties)\n\"\"\"\nfunction KL(p::Poisson, q::Poisson)\n λp, λq = rate.((p, q))\n return λq - λp + λp * (log(λp) - log(λq))\nend\n\n\n\n", "meta": {"hexsha": "d44344a6022a2ea3972b98589ec536d00d557994", "size": 1892, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate.jl", "max_stars_repo_name": "st--/KLDivergences.jl", "max_stars_repo_head_hexsha": "e705a2a456b342fb6090b6dab824cce7bac1e706", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-11-03T00:50:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-12T03:06:46.000Z", "max_issues_repo_path": "src/univariate.jl", "max_issues_repo_name": "st--/KLDivergences.jl", "max_issues_repo_head_hexsha": "e705a2a456b342fb6090b6dab824cce7bac1e706", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-11-02T18:57:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-04T10:19:29.000Z", "max_forks_repo_path": "src/univariate.jl", "max_forks_repo_name": "st--/KLDivergences.jl", "max_forks_repo_head_hexsha": "e705a2a456b342fb6090b6dab824cce7bac1e706", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-14T11:52:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-14T11:52:00.000Z", "avg_line_length": 27.0285714286, "max_line_length": 112, "alphanum_fraction": 0.6257928118, "num_tokens": 677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517050371973, "lm_q2_score": 0.8757869786798663, "lm_q1q2_score": 0.8415889904117931}} {"text": "using Plots, ApproxFun\n# The Blasius boundary layer problem (https://en.wikipedia.org/wiki/Blasius_boundary_layer)\n# describes the boundary layer on a semi-infinite plane with a head-on steady fluid flow.\n# When properly non-dimensionalized, it presents itself as a relatively simple nonlinear BVP.\n# The Falkner-Skan problem generalizes the Blasius boundary layer by considering a wedge at an\n# angle to the steady flow.\n# In both cases, no-slip conditions are in place at the wall and the boundary layer\n# grows linearly (u'(∞)→1) in the far-field.\n# There are more variants which include different nonlinearities which arise in magneto-\n# hydrodynamics, for example.\n\n# We begin with Blasius:\n# solves 2u''' + uu'' = 0 , u(0.) = u'(0.) = 0, u'[∞] = 1\nx=Fun(identity,0..4π)\nd=domain(x)\nB=[ldirichlet(d),lneumann(d),rneumann(d)]\nD=Derivative(d)\nκ = 0.33205733621519630 # This is diff(u,2)(0.), due to Boyd.\nu0 = (1//2) * κ * x^2 # First-order approximation\nu = 0.5x^2 # Other initial solutions may fail to converge\n\nf = (u)->(2.0*D^3*u + u*D^2*u)\ndf = (u)->(2.0*D^3 + u*D^2 + D^2*u)\n\nplot([u,u0]) # Initial estimate and first-order approximation\n\nfor k=1:10\n global u -= [B; df(u)]\\[u(0.);u'(0.);u'(rightendpoint(d))-1.;f(u)]\nend\nnorm(f(u)) # should be zero\nabs(u''(0.)-κ) # should also be zero\nplot([u,u0]) # Solution and First-order approximation\n# Now for Falkner-Skan:\n# solves 2u''' + uu'' - β(1 - (u')^2) = 0 , u(0.) = u'(0.) = 0, u'[∞] = 1\nm = 0.11 # m ∈ [-0.0905, 2]\nβ = 2m/(1+m)\nF = (u)->(2.0*D^3*u + u*D^2*u - β*(1.0 - (D*u)*(D*u)))\ndF = (u)->(2.0*D^3 + u*D^2 + D^2*u + 2β*D*u*D)\nv=u\nnorm(F(v)) # should be non-zero, as we've perturbed the Blasius equation\n\nfor k=1:10\n global v -= [B; dF(v)]\\[v(0.);v'(0.);v'(rightendpoint(d))-1.;F(v)]\nend\nnorm(F(v)) # should be zero\n\nplot([u,v]) # Blasius and Falkner-Skan solutions\n", "meta": {"hexsha": "343a42a68b66023ca78d1664819db768f9a9cc4e", "size": 1951, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ODEs/Blasius and Falkner-Skan.jl", "max_stars_repo_name": "putianyi889/ApproxFunExamples", "max_stars_repo_head_hexsha": "b519a2b2a197607561028fea53a327493bfb344e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2018-06-01T04:19:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T10:15:11.000Z", "max_issues_repo_path": "ODEs/Blasius and Falkner-Skan.jl", "max_issues_repo_name": "putianyi889/ApproxFunExamples", "max_issues_repo_head_hexsha": "b519a2b2a197607561028fea53a327493bfb344e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2018-03-27T09:32:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-30T08:52:42.000Z", "max_forks_repo_path": "ODEs/Blasius and Falkner-Skan.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": 40.6458333333, "max_line_length": 94, "alphanum_fraction": 0.6073808303, "num_tokens": 689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778048911612, "lm_q2_score": 0.879146761176671, "lm_q1q2_score": 0.8415876817163775}} {"text": "function gaussian_elimination!(A::Array{Float64,2})\n\n rows = size(A,1)\n cols = size(A,2)\n\n # Row index\n row = 1\n\n # Main loop going through all columns\n for col = 1:(cols-1)\n\n # Step 1: finding the maximum element for each column\n max_index = argmax(abs.(A[row:end,col])) + row-1\n\n # Check to make sure matrix is good!\n if (A[max_index, col] == 0)\n println(\"matrix is singular!\")\n continue\n end\n\n # Step 2: swap row with highest value for that column to the top\n temp_vector = A[max_index, :]\n A[max_index, :] = A[row, :]\n A[row, :] = temp_vector\n\n # Loop for all remaining rows\n for i = (row+1):rows\n\n # Step 3: finding fraction\n fraction = A[i,col]/A[row,col]\n\n # loop through all columns for that row\n for j = (col+1):cols\n\n # Step 4: re-evaluate each element\n A[i,j] -= A[row,j]*fraction\n\n end\n\n # Step 5: Set lower elements to 0\n A[i,col] = 0\n end\n row += 1\n end\nend\n\nfunction back_substitution(A::Array{Float64,2})\n\n rows = size(A,1)\n cols = size(A,2)\n\n # Creating the solution Vector\n soln = zeros(rows)\n\n for i = rows:-1:1\n sum = 0.0\n for j = rows:-1:i\n sum += soln[j]*A[i,j]\n end\n soln[i] = (A[i, cols] - sum) / A[i, i]\n end\n\n return soln\nend\n\n\nfunction gauss_jordan_elimination!(A::Array{Float64,2})\n\n rows = size(A,1)\n cols = size(A,2)\n\n\n # After this, we know what row to start on (r-1)\n # to go back through the matrix\n row = 1\n for col = 1:cols-1\n if (A[row, col] != 0)\n\n # divide row by pivot and leaving pivot as 1\n for i = cols:-1:col\n A[row,i] /= A[row,col]\n end\n\n # subtract value from above row and set values above pivot to 0\n for i = 1:row-1\n for j = cols:-1:col\n A[i,j] -= A[i,col]*A[row,j]\n end\n end\n row += 1\n end\n end\nend\n\nfunction main()\n A = [2. 3 4 6;\n 1 2 3 4;\n 3 -4 0 10]\n\n gaussian_elimination!(A)\n println(A)\n\n gauss_jordan_elimination!(A)\n println(A)\n\n soln = back_substitution(A)\n println(soln)\n\nend\n\nmain()\n", "meta": {"hexsha": "ef0fba731f631e84179a3ea0acb221dc1a466bf5", "size": 2359, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "contents/gaussian_elimination/code/julia/gaussian_elimination.jl", "max_stars_repo_name": "simbot64/algorithm-archive", "max_stars_repo_head_hexsha": "95a28111e90f15e21e55a924275a51895cb4086d", "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/gaussian_elimination/code/julia/gaussian_elimination.jl", "max_issues_repo_name": "Aarif1430/algorithm-archive", "max_issues_repo_head_hexsha": "1bb82d96c5edc03922918dda0c818bbbcd08417f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "contents/gaussian_elimination/code/julia/gaussian_elimination.jl", "max_forks_repo_name": "Aarif1430/algorithm-archive", "max_forks_repo_head_hexsha": "1bb82d96c5edc03922918dda0c818bbbcd08417f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-17T09:17:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-17T09:17:56.000Z", "avg_line_length": 21.0625, "max_line_length": 75, "alphanum_fraction": 0.5010597711, "num_tokens": 686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951863227517834, "lm_q2_score": 0.8840392893839085, "lm_q1q2_score": 0.8414844912455396}} {"text": "using PyPlot, SparseArrays, LinearAlgebra # Packages used\n\nrows = [1,3,4,2,1,3,1,4,1,5]\ncols = [1,1,1,2,3,3,4,4,5,5]\nvals = [5,-2,-4,5,-3,-1,-2,-10,7,9]\n\nA = sparse(rows, cols, vals, 5, 5)\n\nArray(A)\n\nspy(A, marker=\".\", markersize=24); ## Note - 0-based row and columns\n\nB = A - 4.3A # Will automatically convert datatype of values to Float64\nB[:,4] .= -1.1 # OK since B now has Float64 values (otherwise use Float64.(A) to convert)\nC = A * A' # Matrix multiplication (note: typically increases nnz)\nMatrix([B C]) # Concatenation, again automatic conversion (of C)\n\n\"\"\"\nIncremental matrix construction using the sparse-format\nNot recommended: Insertion into existing matrix very slow\n\"\"\"\nfunction incremental_test_1(N)\n A = spzeros(N,N)\n for k = 1:10N\n i,j = rand(1:N, 2)\n A[i,j] = rand()\n end\n return A\nend\n\nincremental_test_1(10); # Force compile before timing\nfor N in [100,1000,10000]\n @time incremental_test_1(N);\nend\n\n\"\"\"\nIncremental matrix construction using COO and a single call to sparse\nFast approach, avoids incremental insertion into existing array\n\"\"\"\nfunction incremental_test_2(N)\n rows = Int64[]\n cols = Int64[]\n vals = Float64[]\n for i = 1:10N\n push!(rows, rand(1:N))\n push!(cols, rand(1:N))\n push!(vals, rand())\n end\n return sparse(rows, cols, vals, N, N)\nend\n\nincremental_test_2(10); # Force compile before timing\nfor N in [100,1000,10000,100000,1000000]\n @time incremental_test_2(N);\nend\n", "meta": {"hexsha": "15690e3cf693703b46f023e7c1a79b9195e46888", "size": 1492, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "textbook/_build/jupyter_execute/content/Sparse_Matrices/Sparse_Matrices_In_Julia.jl", "max_stars_repo_name": "NoseKnowsAll/NoseKnowsAll.github.io", "max_stars_repo_head_hexsha": "b2cff3e33cc2087770fb4aecb38b7925ad8d6e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "textbook/_build/jupyter_execute/content/Sparse_Matrices/Sparse_Matrices_In_Julia.jl", "max_issues_repo_name": "NoseKnowsAll/NoseKnowsAll.github.io", "max_issues_repo_head_hexsha": "b2cff3e33cc2087770fb4aecb38b7925ad8d6e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "textbook/_build/jupyter_execute/content/Sparse_Matrices/Sparse_Matrices_In_Julia.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": 26.6428571429, "max_line_length": 90, "alphanum_fraction": 0.6595174263, "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.9005297927918167, "lm_q1q2_score": 0.8414506821086601}} {"text": "### A Pluto.jl notebook ###\n# v0.16.0\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ bf54eece-fc02-11ea-3dbc-b37a5644eab1\nusing Plots\n\n# ╔═╡ cd9cc940-fc02-11ea-2a40-19bc6f79a6d3\nusing LaTeXStrings\n\n# ╔═╡ dad114fe-fbfb-11ea-32dd-a302838af30f\nmd\"# Linear Programming: Introduction\"\n\n# ╔═╡ fdab0c70-fbfb-11ea-116d-9f1b613f9d0d\nmd\"\"\"## Definition\n\nFormally, a linear program is an optimization problem of the form:\n\n```math\n\\begin{aligned}\n\\min \\vec{c}^\\mathsf{T}\\vec x&\\\\\n\\textrm{ subject to }&\\begin{cases}\n\\mathbf{A}\\vec x=\\vec b\\\\\n\\vec x\\ge\\vec 0\n\\end{cases}\n\\end{aligned}\n```\n\nwhere $\\vec c\\in\\mathbb R^n$, $\\vec b\\in\\mathbb R^m$ and $\\mathbf A \\in \\mathbb R^{m\\times n}$. The vector inequality $\\vec x\\ge\\vec 0$ means that each component of $\\vec x$ is nonnegative. Several variations of this problem are possible; eg. instead of minimizing, we can maximize, or the constraints may be in the form of inequalities, such as $\\mathbf A\\vec x\\ge \\vec b$ or $\\mathbf A\\vec x\\le\\vec b$. We shall see later, these variations can all be rewritten into the standard form.\"\"\"\n\n# ╔═╡ 0d88a212-fbfc-11ea-37ae-c5e0c6a894e8\nmd\"\"\"## Example\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 €6 and $X_2$, $X_3$ and $X_4$ sell for €4, €7 and €5, 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# ╔═╡ 67071830-fbfc-11ea-3925-798d3d288500\nmd\"\"\"## Vector Notation\n\nUsing vector notation with\n\n```math\n\\vec x = \\begin{pmatrix}\nx_1\\\\x_2\\\\x_3\\\\x_4\n\\end{pmatrix}\n```\n\nthe problem can be written in the compact form\n\n```math\n\\max \n\\begin{pmatrix}6&4&7&5\\end{pmatrix}\n\\begin{pmatrix}\nx_1\\\\x_2\\\\x_3\\\\x_4\n\\end{pmatrix}\\\\\n\\textrm{ subject to }\n\\begin{cases}\n\\begin{pmatrix}\n1&2&1&2\\\\\n6&5&3&2\\\\\n3&4&9&12\n\\end{pmatrix}\n\\begin{pmatrix}\nx_1\\\\x_2\\\\x_3\\\\x_4\n\\end{pmatrix}\\le\n\\begin{pmatrix}\n20\\\\100\\\\75\n\\end{pmatrix}\\\\\n\\begin{pmatrix}\nx_1\\\\x_2\\\\x_3\\\\x_4\n\\end{pmatrix}\\ge\n\\begin{pmatrix}\n0\\\\0\\\\0\\\\0\n\\end{pmatrix}\n\\end{cases}\n```\n \"\"\"\n\n# ╔═╡ 3bb281f0-fc02-11ea-34f0-fd00648c27bb\nmd\"\"\"## Two-dimensional Linear Program\n\nMany fundamental concepts of linear programming are easily illustrated in two-dimensional space.\n\nConsider the following linear program:\n\n```math\n\\begin{aligned}\n\\max&\n\\begin{pmatrix}\n1&5\n\\end{pmatrix}\n\\begin{pmatrix}\nx_1\\\\\nx_2\n\\end{pmatrix}&\\\\\n\\textrm{ subject to }\n&\\begin{cases}\n\\begin{pmatrix}\n5&6\\\\\n3&2\n\\end{pmatrix}\n\\begin{pmatrix}\nx_1\\\\\nx_2\n\\end{pmatrix}\\le\n\\begin{pmatrix}\n30\\\\\n12\n\\end{pmatrix}\\\\\n\\begin{pmatrix}\nx_1\\\\\nx_2\n\\end{pmatrix}\\ge\n\\begin{pmatrix}\n0\\\\\n0\n\\end{pmatrix}\n\\end{cases}\n\\end{aligned}\n```\n\"\"\"\n\n# ╔═╡ e5488250-fc02-11ea-0bc1-4365461fb202\nlet\n\tx = -2:6\n\tplot(x, (30 .- 5 .* x) ./ 6, linestyle=:dash, label=L\"5x_1+6x_2=30\")\n\tplot!(x, (12 .- 3 .* x) ./ 2, linestyle=:dash, label=L\"3x_1+2x_2=12\")\n\tplot!([0,4,1.5,0,0],[0,0,3.75,5,0], linewidth=2, label=\"constraints\")\n\tplot!(x, -x ./ 5, label=L\"f\\left(x_1,x_2\\right)=x_1+5x_2=0\")\n\tplot!(x, (25 .- x) ./ 5, label=L\"f\\left(x_1,x_2\\right)=x_1+5x_2=25\")\nend\n\n# ╔═╡ 08de4fb0-fc03-11ea-08fb-616f792f7c7f\nmd\"\"\"## Slack Variables\n\nTheorems and solution techniques are usually stated for problems in standard form. other forms of linear programs can be converted as the standard form. If a linear program is in the form\n\n```math\n\\begin{aligned}\n\\min &\\vec{c}^\\mathsf{T}\\vec x\\\\\n\\textrm{ subject to }& \\begin{cases}\n\\mathbf{A}\\vec x\\ge \\vec b\\\\\n\\vec x\\ge\\vec 0\n\\end{cases}\n\\end{aligned}\n```\n\nthen by introducing _surplus variables_, we can convert the orginal problem into the standard form\n\n```math\n\\begin{aligned}\n\\min& \\vec{c}^\\mathsf{T}\\vec x\\\\\n\\textrm{ subject to }& \\begin{cases}\n\\mathbf{A}\\vec x-\\mathbf I\\vec y = \\vec b\\\\\n\\vec x\\ge\\vec 0\\\\\n\\vec y\\ge\\vec 0\n\\end{cases}\n\\end{aligned}\n```\n\nwhere $\\mathbf I$ is the $m\\times m$ identity matrix.\n\nIf, on the other hand, the constraints have the form\n\n```math\n\\begin{cases}\n\\mathbf{A}\\vec x\\le b\\\\\n\\vec x\\ge\\vec 0\n\\end{cases}\n```\n\nthen we introduce the _slack variables_ to convert the constraints into the form\n\n```math\n\\begin{cases}\n\\mathbf{A}\\vec x+\\mathbf I\\vec y = \\vec b\\\\\n\\vec x\\ge\\vec 0\\\\\n\\vec y\\ge\\vec 0\n\\end{cases}\n```\n\nConsider the following optimization problem\n\n```math\n\\begin{aligned}\n\\max& x_2-x_1\\\\\n\\textrm{ subject to }&\n\\begin{cases}\n3x_1=x_2-5\\\\\n\\left|x_2\\right|\\le2\\\\\nx_1\\le0\n\\end{cases}\n\\end{aligned}\n```\n\nTo convert the problem into a standard form, we perform the following steps:\n\n1. Change the objective function to:\n\n```math\n\\min x_1 - x_2\n```\n\n2. Substitute $x_1=-x_1^\\prime$.\n\n3. Write $\\left|x_2\\right|\\le2$ as $x_2\\le 2$ and $-x_2\\le 2$.\n\n4. Introduce slack variables $y_1$ and $y_2$, and convert the inequalities above to\n\n```math\n\\begin{cases}\n\\hphantom{-}x_2 + y_1 =2\\\\\n-x_2+y_2 =2\n\\end{cases}\n```\n\n5. Write $x_2=u-v$ with $u,v\\ge0$.\n\nHence, we obtain\n\n```math\n\\begin{aligned}\n\\min& -x_1^\\prime-u+v\\\\\n\\textrm{ subject to }&\n\\begin{cases}\n3x_1^\\prime+u-v=5\\\\\nu-v+y_1=2\\\\\nv-u+y_2=2\\\\\nx_1^\\prime,u,v,y_1,y_2\\ge0\n\\end{cases}\n\\end{aligned}\n```\n\"\"\"\n\n# ╔═╡ cfd86bf0-fc03-11ea-22ef-b99d3e3fbfce\nmd\"\"\"## Fundamental Theorem of Linear Programming\n\nWe consider the system of equalities\n\n```math\n\\mathbf{A}\\vec x=\\vec b\n```\n\nwhere $\\mathrm{rank}\\,\\mathbf A=m$.\n\nLet $\\mathbf B$ a square matrix whose columns are $m$ linearly independent columns of $\\mathbf A$. If necessary, we reorder the columns of $\\mathbf A$ so that the columns in $\\mathbf B$ appear first: $\\mathbf A$ has the form $\\left(\\mathbf B |\\mathbf N\\right)$.\n\nThe matrix is nonsingular, and thus we can solve the equation\n\n```math\n\\mathbf B\\vec x_\\mathbf B = \\vec b\n```\n\nThe solution is $\\vec x_\\mathbf B = \\mathbf B^{-1}\\vec b$.\n\nLet $\\vec x$ be the vector whose first $m$ components are equal to $\\vec x_\\mathbf B$ and the remaining components are equal to zero. Then $\\vec x$ is a solution to $\\mathbf A\\vec x=\\vec b$. We call $\\vec x$ a _basic solution_. Its components refering to the the components of $\\vec x_\\mathbf B$ are called _basic variables_.\n\n- If some of the basic variables are zero, then the basic solution is _degenerate_.\n- A vector $\\vec x$ satisfying $\\mathbf A\\vec x=\\vec b$, $\\vec x \\ge \\vec 0$, is said to be a _feasible solution_.\n- A feasible solution that is also basic is called a _basic feasible solution_.\n\nThe fundamental theorem of linear programming states that when solving a linear programming problem, we need only consider basic feasible solutions. This is because the optimal value (if it exists) is always achieved at a basic solution.\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nLaTeXStrings = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nPlots = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\n\n[compat]\nLaTeXStrings = \"~1.2.1\"\nPlots = \"~1.22.1\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\n[[Adapt]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"84918055d15b3114ede17ac6a7182f68870c16f7\"\nuuid = \"79e6a3ab-5dfb-504d-930d-738a2a938a0e\"\nversion = \"3.3.1\"\n\n[[ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[Bzip2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"19a35467a82e236ff51bc17a3a44b69ef35185a2\"\nuuid = \"6e34b625-4abd-537c-b88f-471c36dfa7a0\"\nversion = \"1.0.8+0\"\n\n[[Cairo_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"JLLWrappers\", \"LZO_jll\", \"Libdl\", \"Pixman_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"f2202b55d816427cd385a9a4f3ffb226bee80f99\"\nuuid = \"83423d85-b0ee-5818-9007-b63ccbeb887a\"\nversion = \"1.16.1+0\"\n\n[[ColorSchemes]]\ndeps = [\"ColorTypes\", \"Colors\", \"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"9995eb3977fbf67b86d0a0a0508e83017ded03f2\"\nuuid = \"35d6a980-a343-548e-a6ea-1d62b119f2f4\"\nversion = \"3.14.0\"\n\n[[ColorTypes]]\ndeps = [\"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"024fe24d83e4a5bf5fc80501a314ce0d1aa35597\"\nuuid = \"3da002f7-5984-5a60-b8a6-cbb66c0b333f\"\nversion = \"0.11.0\"\n\n[[Colors]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"Reexport\"]\ngit-tree-sha1 = \"417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40\"\nuuid = \"5ae59095-9a9b-59fe-a467-6f913c188581\"\nversion = \"0.12.8\"\n\n[[Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"4866e381721b30fac8dda4c8cb1d9db45c8d2994\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.37.0\"\n\n[[CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[Contour]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"9f02045d934dc030edad45944ea80dbd1f0ebea7\"\nuuid = \"d38c429a-6771-53c6-b99e-75d170b6e991\"\nversion = \"0.5.7\"\n\n[[DataAPI]]\ngit-tree-sha1 = \"bec2532f8adb82005476c141ec23e921fc20971b\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.8.0\"\n\n[[DataStructures]]\ndeps = [\"Compat\", \"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"7d9d316f04214f7efdbb6398d545446e246eff02\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.18.10\"\n\n[[DataValueInterfaces]]\ngit-tree-sha1 = \"bfc1187b79289637fa0ef6d4436ebdfe6905cbd6\"\nuuid = \"e2d170a0-9d28-54be-80f0-106bbe20a464\"\nversion = \"1.0.0\"\n\n[[Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[EarCut_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"3f3a2501fa7236e9b911e0f7a588c657e822bb6d\"\nuuid = \"5ae413db-bbd1-5e63-b57d-d24a61df00f5\"\nversion = \"2.2.3+0\"\n\n[[Expat_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b3bfd02e98aedfa5cf885665493c5598c350cd2f\"\nuuid = \"2e619515-83b5-522b-bb60-26c02a35a201\"\nversion = \"2.2.10+0\"\n\n[[FFMPEG]]\ndeps = [\"FFMPEG_jll\"]\ngit-tree-sha1 = \"b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8\"\nuuid = \"c87230d0-a227-11e9-1b43-d7ebe4e7570a\"\nversion = \"0.4.1\"\n\n[[FFMPEG_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"JLLWrappers\", \"LAME_jll\", \"Libdl\", \"Ogg_jll\", \"OpenSSL_jll\", \"Opus_jll\", \"Pkg\", \"Zlib_jll\", \"libass_jll\", \"libfdk_aac_jll\", \"libvorbis_jll\", \"x264_jll\", \"x265_jll\"]\ngit-tree-sha1 = \"d8a578692e3077ac998b50c0217dfd67f21d1e5f\"\nuuid = \"b22a6f82-2f65-5046-a5b2-351ab43fb4e5\"\nversion = \"4.4.0+0\"\n\n[[FixedPointNumbers]]\ndeps = [\"Statistics\"]\ngit-tree-sha1 = \"335bfdceacc84c5cdf16aadc768aa5ddfc5383cc\"\nuuid = \"53c48c17-4a7d-5ca2-90c5-79b7896eea93\"\nversion = \"0.8.4\"\n\n[[Fontconfig_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Expat_jll\", \"FreeType2_jll\", \"JLLWrappers\", \"Libdl\", \"Libuuid_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"21efd19106a55620a188615da6d3d06cd7f6ee03\"\nuuid = \"a3f928ae-7b40-5064-980b-68af3947d34b\"\nversion = \"2.13.93+0\"\n\n[[Formatting]]\ndeps = [\"Printf\"]\ngit-tree-sha1 = \"8339d61043228fdd3eb658d86c926cb282ae72a8\"\nuuid = \"59287772-0a20-5a39-b81b-1366585eb4c0\"\nversion = \"0.4.2\"\n\n[[FreeType2_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"87eb71354d8ec1a96d4a7636bd57a7347dde3ef9\"\nuuid = \"d7e528f0-a631-5988-bf34-fe36492bcfd7\"\nversion = \"2.10.4+0\"\n\n[[FriBidi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"aa31987c2ba8704e23c6c8ba8a4f769d5d7e4f91\"\nuuid = \"559328eb-81f9-559d-9380-de523a88c83c\"\nversion = \"1.0.10+0\"\n\n[[GLFW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"Pkg\", \"Xorg_libXcursor_jll\", \"Xorg_libXi_jll\", \"Xorg_libXinerama_jll\", \"Xorg_libXrandr_jll\"]\ngit-tree-sha1 = \"dba1e8614e98949abfa60480b13653813d8f0157\"\nuuid = \"0656b61e-2033-5cc2-a64a-77c0f6c09b89\"\nversion = \"3.3.5+0\"\n\n[[GR]]\ndeps = [\"Base64\", \"DelimitedFiles\", \"GR_jll\", \"HTTP\", \"JSON\", \"Libdl\", \"LinearAlgebra\", \"Pkg\", \"Printf\", \"Random\", \"Serialization\", \"Sockets\", \"Test\", \"UUIDs\"]\ngit-tree-sha1 = \"c2178cfbc0a5a552e16d097fae508f2024de61a3\"\nuuid = \"28b8d3ca-fb5f-59d9-8090-bfdbd6d07a71\"\nversion = \"0.59.0\"\n\n[[GR_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Cairo_jll\", \"FFMPEG_jll\", \"Fontconfig_jll\", \"GLFW_jll\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Libtiff_jll\", \"Pixman_jll\", \"Pkg\", \"Qt5Base_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"ef49a187604f865f4708c90e3f431890724e9012\"\nuuid = \"d2c73de3-f751-5644-a686-071e5b155ba9\"\nversion = \"0.59.0+0\"\n\n[[GeometryBasics]]\ndeps = [\"EarCut_jll\", \"IterTools\", \"LinearAlgebra\", \"StaticArrays\", \"StructArrays\", \"Tables\"]\ngit-tree-sha1 = \"58bcdf5ebc057b085e58d95c138725628dd7453c\"\nuuid = \"5c1252a2-5f33-56bf-86c9-59e7332b4326\"\nversion = \"0.4.1\"\n\n[[Gettext_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"9b02998aba7bf074d14de89f9d37ca24a1a0b046\"\nuuid = \"78b55507-aeef-58d4-861c-77aaff3498b1\"\nversion = \"0.21.0+0\"\n\n[[Glib_jll]]\ndeps = [\"Artifacts\", \"Gettext_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Libiconv_jll\", \"Libmount_jll\", \"PCRE_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"7bf67e9a481712b3dbe9cb3dac852dc4b1162e02\"\nuuid = \"7746bdde-850d-59dc-9ae8-88ece973131d\"\nversion = \"2.68.3+0\"\n\n[[Graphite2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"344bf40dcab1073aca04aa0df4fb092f920e4011\"\nuuid = \"3b182d85-2403-5c21-9c21-1e1f0cc25472\"\nversion = \"1.3.14+0\"\n\n[[Grisu]]\ngit-tree-sha1 = \"53bb909d1151e57e2484c3d1b53e19552b887fb2\"\nuuid = \"42e2da0e-8278-4e71-bc24-59509adca0fe\"\nversion = \"1.0.2\"\n\n[[HTTP]]\ndeps = [\"Base64\", \"Dates\", \"IniFile\", \"Logging\", \"MbedTLS\", \"NetworkOptions\", \"Sockets\", \"URIs\"]\ngit-tree-sha1 = \"60ed5f1643927479f845b0135bb369b031b541fa\"\nuuid = \"cd3eb016-35fb-5094-929b-558a96fad6f3\"\nversion = \"0.9.14\"\n\n[[HarfBuzz_jll]]\ndeps = [\"Artifacts\", \"Cairo_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"Graphite2_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\"]\ngit-tree-sha1 = \"8a954fed8ac097d5be04921d595f741115c1b2ad\"\nuuid = \"2e76f6c2-a576-52d4-95c1-20adfe4de566\"\nversion = \"2.8.1+0\"\n\n[[IniFile]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"098e4d2c533924c921f9f9847274f2ad89e018b8\"\nuuid = \"83e8ac13-25f8-5344-8a64-a9f2b223428f\"\nversion = \"0.5.0\"\n\n[[InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[IterTools]]\ngit-tree-sha1 = \"05110a2ab1fc5f932622ffea2a003221f4782c18\"\nuuid = \"c8e1da08-722c-5040-9ed9-7db0dc04731e\"\nversion = \"1.3.0\"\n\n[[IteratorInterfaceExtensions]]\ngit-tree-sha1 = \"a3f24677c21f5bbe9d2a714f95dcd58337fb2856\"\nuuid = \"82899510-4779-5014-852e-03e436cf321d\"\nversion = \"1.0.0\"\n\n[[JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"642a199af8b68253517b80bd3bfd17eb4e84df6e\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.3.0\"\n\n[[JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"8076680b162ada2a031f707ac7b4953e30667a37\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.2\"\n\n[[JpegTurbo_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d735490ac75c5cb9f1b00d8b5509c11984dc6943\"\nuuid = \"aacddb02-875f-59d6-b918-886e6ef4fbf8\"\nversion = \"2.1.0+0\"\n\n[[LAME_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"f6250b16881adf048549549fba48b1161acdac8c\"\nuuid = \"c1c5ebd0-6772-5130-a774-d5fcae4a789d\"\nversion = \"3.100.1+0\"\n\n[[LZO_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e5b909bcf985c5e2605737d2ce278ed791b89be6\"\nuuid = \"dd4b983a-f0e5-5f8d-a1b7-129d4a5fb1ac\"\nversion = \"2.10.1+0\"\n\n[[LaTeXStrings]]\ngit-tree-sha1 = \"c7f1c695e06c01b95a67f0cd1d34994f3e7db104\"\nuuid = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nversion = \"1.2.1\"\n\n[[Latexify]]\ndeps = [\"Formatting\", \"InteractiveUtils\", \"LaTeXStrings\", \"MacroTools\", \"Markdown\", \"Printf\", \"Requires\"]\ngit-tree-sha1 = \"a4b12a1bd2ebade87891ab7e36fdbce582301a92\"\nuuid = \"23fbe1c1-3f47-55db-b15f-69d7ec21a316\"\nversion = \"0.15.6\"\n\n[[LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[Libffi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"761a393aeccd6aa92ec3515e428c26bf99575b3b\"\nuuid = \"e9f186c6-92d2-5b65-8a66-fee21dc1b490\"\nversion = \"3.2.2+0\"\n\n[[Libgcrypt_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgpg_error_jll\", \"Pkg\"]\ngit-tree-sha1 = \"64613c82a59c120435c067c2b809fc61cf5166ae\"\nuuid = \"d4300ac3-e22c-5743-9152-c294e39db1e4\"\nversion = \"1.8.7+0\"\n\n[[Libglvnd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"7739f837d6447403596a75d19ed01fd08d6f56bf\"\nuuid = \"7e76a0d4-f3c7-5321-8279-8d96eeed0f29\"\nversion = \"1.3.0+3\"\n\n[[Libgpg_error_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c333716e46366857753e273ce6a69ee0945a6db9\"\nuuid = \"7add5ba3-2f88-524e-9cd5-f83b8a55f7b8\"\nversion = \"1.42.0+0\"\n\n[[Libiconv_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"42b62845d70a619f063a7da093d995ec8e15e778\"\nuuid = \"94ce4f54-9a6c-5748-9c1c-f9c7231a4531\"\nversion = \"1.16.1+1\"\n\n[[Libmount_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"9c30530bf0effd46e15e0fdcf2b8636e78cbbd73\"\nuuid = \"4b2f31a3-9ecc-558c-b454-b3730dcb73e9\"\nversion = \"2.35.0+0\"\n\n[[Libtiff_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Pkg\", \"Zlib_jll\", \"Zstd_jll\"]\ngit-tree-sha1 = \"340e257aada13f95f98ee352d316c3bed37c8ab9\"\nuuid = \"89763e89-9b03-5906-acba-b20f662cd828\"\nversion = \"4.3.0+0\"\n\n[[Libuuid_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7f3efec06033682db852f8b3bc3c1d2b0a0ab066\"\nuuid = \"38a345b3-de98-5d2b-a5d3-14cd9215e700\"\nversion = \"2.36.0+0\"\n\n[[LinearAlgebra]]\ndeps = [\"Libdl\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"5a5bc6bf062f0f95e62d0fe0a2d99699fed82dd9\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.8\"\n\n[[Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[MbedTLS]]\ndeps = [\"Dates\", \"MbedTLS_jll\", \"Random\", \"Sockets\"]\ngit-tree-sha1 = \"1c38e51c3d08ef2278062ebceade0e46cefc96fe\"\nuuid = \"739be429-bea8-5141-9913-cc70e7f3736d\"\nversion = \"1.0.3\"\n\n[[MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[Measures]]\ngit-tree-sha1 = \"e498ddeee6f9fdb4551ce855a46f54dbd900245f\"\nuuid = \"442fdcdd-2543-5da2-b0f3-8c86c306513e\"\nversion = \"0.3.1\"\n\n[[Missings]]\ndeps = [\"DataAPI\"]\ngit-tree-sha1 = \"bf210ce90b6c9eed32d25dbcae1ebc565df2687f\"\nuuid = \"e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28\"\nversion = \"1.0.2\"\n\n[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[NaNMath]]\ngit-tree-sha1 = \"bfe47e760d60b82b66b61d2d44128b62e3a369fb\"\nuuid = \"77ba4419-2d1f-58cd-9bb1-8ffee604a2e3\"\nversion = \"0.3.5\"\n\n[[NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[Ogg_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7937eda4681660b4d6aeeecc2f7e1c81c8ee4e2f\"\nuuid = \"e7412a2a-1a6e-54c0-be00-318e2571c051\"\nversion = \"1.3.5+0\"\n\n[[OpenSSL_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"15003dcb7d8db3c6c857fda14891a539a8f2705a\"\nuuid = \"458c3c95-2e84-50aa-8efc-19380b2a3a95\"\nversion = \"1.1.10+0\"\n\n[[Opus_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"51a08fb14ec28da2ec7a927c4337e4332c2a4720\"\nuuid = \"91d4177d-7536-5919-b921-800302f37372\"\nversion = \"1.3.2+0\"\n\n[[OrderedCollections]]\ngit-tree-sha1 = \"85f8e6578bf1f9ee0d11e7bb1b1456435479d47c\"\nuuid = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nversion = \"1.4.1\"\n\n[[PCRE_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b2a7af664e098055a7529ad1a900ded962bca488\"\nuuid = \"2f80f16e-611a-54ab-bc61-aa92de5b98fc\"\nversion = \"8.44.0+0\"\n\n[[Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"438d35d2d95ae2c5e8780b330592b6de8494e779\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.0.3\"\n\n[[Pixman_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b4f5d02549a10e20780a24fce72bea96b6329e29\"\nuuid = \"30392449-352a-5448-841d-b1acce4e97dc\"\nversion = \"0.40.1+0\"\n\n[[Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[PlotThemes]]\ndeps = [\"PlotUtils\", \"Requires\", \"Statistics\"]\ngit-tree-sha1 = \"a3a964ce9dc7898193536002a6dd892b1b5a6f1d\"\nuuid = \"ccf2f8ad-2431-5c83-bf29-c5338b663b6a\"\nversion = \"2.0.1\"\n\n[[PlotUtils]]\ndeps = [\"ColorSchemes\", \"Colors\", \"Dates\", \"Printf\", \"Random\", \"Reexport\", \"Statistics\"]\ngit-tree-sha1 = \"2537ed3c0ed5e03896927187f5f2ee6a4ab342db\"\nuuid = \"995b91a9-d308-5afd-9ec6-746e21dbc043\"\nversion = \"1.0.14\"\n\n[[Plots]]\ndeps = [\"Base64\", \"Contour\", \"Dates\", \"Downloads\", \"FFMPEG\", \"FixedPointNumbers\", \"GR\", \"GeometryBasics\", \"JSON\", \"Latexify\", \"LinearAlgebra\", \"Measures\", \"NaNMath\", \"PlotThemes\", \"PlotUtils\", \"Printf\", \"REPL\", \"Random\", \"RecipesBase\", \"RecipesPipeline\", \"Reexport\", \"Requires\", \"Scratch\", \"Showoff\", \"SparseArrays\", \"Statistics\", \"StatsBase\", \"UUIDs\"]\ngit-tree-sha1 = \"4c2637482176b1c2fb99af4d83cb2ff0328fc33c\"\nuuid = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nversion = \"1.22.1\"\n\n[[Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"00cfd92944ca9c760982747e9a1d0d5d86ab1e5a\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.2\"\n\n[[Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[Qt5Base_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Fontconfig_jll\", \"Glib_jll\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"OpenSSL_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libxcb_jll\", \"Xorg_xcb_util_image_jll\", \"Xorg_xcb_util_keysyms_jll\", \"Xorg_xcb_util_renderutil_jll\", \"Xorg_xcb_util_wm_jll\", \"Zlib_jll\", \"xkbcommon_jll\"]\ngit-tree-sha1 = \"ad368663a5e20dbb8d6dc2fddeefe4dae0781ae8\"\nuuid = \"ea2cea3b-5b76-57ae-a6ef-0a8af62496e1\"\nversion = \"5.15.3+0\"\n\n[[REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[RecipesBase]]\ngit-tree-sha1 = \"44a75aa7a527910ee3d1751d1f0e4148698add9e\"\nuuid = \"3cdcf5f2-1ef4-517c-9805-6587b60abb01\"\nversion = \"1.1.2\"\n\n[[RecipesPipeline]]\ndeps = [\"Dates\", \"NaNMath\", \"PlotUtils\", \"RecipesBase\"]\ngit-tree-sha1 = \"7ad0dfa8d03b7bcf8c597f59f5292801730c55b8\"\nuuid = \"01d81517-befc-4cb6-b9ec-a95719d0359c\"\nversion = \"0.4.1\"\n\n[[Reexport]]\ngit-tree-sha1 = \"45e428421666073eab6f2da5c9d310d99bb12f9b\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.2.2\"\n\n[[Requires]]\ndeps = [\"UUIDs\"]\ngit-tree-sha1 = \"4036a3bd08ac7e968e27c203d45f5fff15020621\"\nuuid = \"ae029012-a4dd-5104-9daa-d747884805df\"\nversion = \"1.1.3\"\n\n[[SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[Scratch]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"0b4b7f1393cff97c33891da2a0bf69c6ed241fda\"\nuuid = \"6c6a2e73-6563-6170-7368-637461726353\"\nversion = \"1.1.0\"\n\n[[Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[Showoff]]\ndeps = [\"Dates\", \"Grisu\"]\ngit-tree-sha1 = \"91eddf657aca81df9ae6ceb20b959ae5653ad1de\"\nuuid = \"992d4aef-0814-514b-bc4d-f2e9a6c4116f\"\nversion = \"1.0.3\"\n\n[[Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[SortingAlgorithms]]\ndeps = [\"DataStructures\"]\ngit-tree-sha1 = \"b3363d7460f7d098ca0912c69b082f75625d7508\"\nuuid = \"a2af1166-a08f-5f64-846c-94a0d3cef48c\"\nversion = \"1.0.1\"\n\n[[SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[StaticArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"3240808c6d463ac46f1c1cd7638375cd22abbccb\"\nuuid = \"90137ffa-7385-5640-81b9-e52037218182\"\nversion = \"1.2.12\"\n\n[[Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[StatsAPI]]\ngit-tree-sha1 = \"1958272568dc176a1d881acb797beb909c785510\"\nuuid = \"82ae8749-77ed-4fe6-ae5f-f523153014b0\"\nversion = \"1.0.0\"\n\n[[StatsBase]]\ndeps = [\"DataAPI\", \"DataStructures\", \"LinearAlgebra\", \"Missings\", \"Printf\", \"Random\", \"SortingAlgorithms\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"8cbbc098554648c84f79a463c9ff0fd277144b6c\"\nuuid = \"2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91\"\nversion = \"0.33.10\"\n\n[[StructArrays]]\ndeps = [\"Adapt\", \"DataAPI\", \"StaticArrays\", \"Tables\"]\ngit-tree-sha1 = \"2ce41e0d042c60ecd131e9fb7154a3bfadbf50d3\"\nuuid = \"09ab397b-f2b6-538f-b94a-2f83cf4a842a\"\nversion = \"0.6.3\"\n\n[[TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[TableTraits]]\ndeps = [\"IteratorInterfaceExtensions\"]\ngit-tree-sha1 = \"c06b2f539df1c6efa794486abfb6ed2022561a39\"\nuuid = \"3783bdb8-4a98-5b6b-af9a-565f29a5fe9c\"\nversion = \"1.0.1\"\n\n[[Tables]]\ndeps = [\"DataAPI\", \"DataValueInterfaces\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"TableTraits\", \"Test\"]\ngit-tree-sha1 = \"1162ce4a6c4b7e31e0e6b14486a6986951c73be9\"\nuuid = \"bd369af6-aec1-5ad0-b16a-f7cc5008161c\"\nversion = \"1.5.2\"\n\n[[Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[URIs]]\ngit-tree-sha1 = \"97bbe755a53fe859669cd907f2d96aee8d2c1355\"\nuuid = \"5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4\"\nversion = \"1.3.0\"\n\n[[UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[Wayland_jll]]\ndeps = [\"Artifacts\", \"Expat_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"3e61f0b86f90dacb0bc0e73a0c5a83f6a8636e23\"\nuuid = \"a2964d1f-97da-50d4-b82a-358c7fce9d89\"\nversion = \"1.19.0+0\"\n\n[[Wayland_protocols_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\"]\ngit-tree-sha1 = \"2839f1c1296940218e35df0bbb220f2a79686670\"\nuuid = \"2381bf8a-dfd0-557d-9999-79630e7b1b91\"\nversion = \"1.18.0+4\"\n\n[[XML2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"1acf5bdf07aa0907e0a37d3718bb88d4b687b74a\"\nuuid = \"02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a\"\nversion = \"2.9.12+0\"\n\n[[XSLT_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgcrypt_jll\", \"Libgpg_error_jll\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\", \"Zlib_jll\"]\ngit-tree-sha1 = \"91844873c4085240b95e795f692c4cec4d805f8a\"\nuuid = \"aed1982a-8fda-507f-9586-7b0439959a61\"\nversion = \"1.1.34+0\"\n\n[[Xorg_libX11_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\", \"Xorg_xtrans_jll\"]\ngit-tree-sha1 = \"5be649d550f3f4b95308bf0183b82e2582876527\"\nuuid = \"4f6342f7-b3d2-589e-9d20-edeb45f2b2bc\"\nversion = \"1.6.9+4\"\n\n[[Xorg_libXau_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4e490d5c960c314f33885790ed410ff3a94ce67e\"\nuuid = \"0c0b7dd1-d40b-584c-a123-a41640f87eec\"\nversion = \"1.0.9+4\"\n\n[[Xorg_libXcursor_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXfixes_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"12e0eb3bc634fa2080c1c37fccf56f7c22989afd\"\nuuid = \"935fb764-8cf2-53bf-bb30-45bb1f8bf724\"\nversion = \"1.2.0+4\"\n\n[[Xorg_libXdmcp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fe47bd2247248125c428978740e18a681372dd4\"\nuuid = \"a3789734-cfe1-5b06-b2d0-1dd0d9d62d05\"\nversion = \"1.1.3+4\"\n\n[[Xorg_libXext_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"b7c0aa8c376b31e4852b360222848637f481f8c3\"\nuuid = \"1082639a-0dae-5f34-9b06-72781eeb8cb3\"\nversion = \"1.3.4+4\"\n\n[[Xorg_libXfixes_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"0e0dc7431e7a0587559f9294aeec269471c991a4\"\nuuid = \"d091e8ba-531a-589c-9de9-94069b037ed8\"\nversion = \"5.0.3+4\"\n\n[[Xorg_libXi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXfixes_jll\"]\ngit-tree-sha1 = \"89b52bc2160aadc84d707093930ef0bffa641246\"\nuuid = \"a51aa0fd-4e3c-5386-b890-e753decda492\"\nversion = \"1.7.10+4\"\n\n[[Xorg_libXinerama_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"26be8b1c342929259317d8b9f7b53bf2bb73b123\"\nuuid = \"d1454406-59df-5ea1-beac-c340f2130bc3\"\nversion = \"1.1.4+4\"\n\n[[Xorg_libXrandr_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"34cea83cb726fb58f325887bf0612c6b3fb17631\"\nuuid = \"ec84b674-ba8e-5d96-8ba1-2a689ba10484\"\nversion = \"1.5.2+4\"\n\n[[Xorg_libXrender_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"19560f30fd49f4d4efbe7002a1037f8c43d43b96\"\nuuid = \"ea2f1a96-1ddc-540d-b46f-429655e07cfa\"\nversion = \"0.9.10+4\"\n\n[[Xorg_libpthread_stubs_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"6783737e45d3c59a4a4c4091f5f88cdcf0908cbb\"\nuuid = \"14d82f49-176c-5ed1-bb49-ad3f5cbd8c74\"\nversion = \"0.1.0+3\"\n\n[[Xorg_libxcb_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"XSLT_jll\", \"Xorg_libXau_jll\", \"Xorg_libXdmcp_jll\", \"Xorg_libpthread_stubs_jll\"]\ngit-tree-sha1 = \"daf17f441228e7a3833846cd048892861cff16d6\"\nuuid = \"c7cfdc94-dc32-55de-ac96-5a1b8d977c5b\"\nversion = \"1.13.0+3\"\n\n[[Xorg_libxkbfile_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"926af861744212db0eb001d9e40b5d16292080b2\"\nuuid = \"cc61e674-0454-545c-8b26-ed2c68acab7a\"\nversion = \"1.1.0+4\"\n\n[[Xorg_xcb_util_image_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"0fab0a40349ba1cba2c1da699243396ff8e94b97\"\nuuid = \"12413925-8142-5f55-bb0e-6d7ca50bb09b\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\"]\ngit-tree-sha1 = \"e7fd7b2881fa2eaa72717420894d3938177862d1\"\nuuid = \"2def613f-5ad1-5310-b15b-b15d46f528f5\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_keysyms_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"d1151e2c45a544f32441a567d1690e701ec89b00\"\nuuid = \"975044d2-76e6-5fbe-bf08-97ce7c6574c7\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_renderutil_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"dfd7a8f38d4613b6a575253b3174dd991ca6183e\"\nuuid = \"0d47668e-0667-5a69-a72c-f761630bfb7e\"\nversion = \"0.3.9+1\"\n\n[[Xorg_xcb_util_wm_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"e78d10aab01a4a154142c5006ed44fd9e8e31b67\"\nuuid = \"c22f9ab0-d5fe-5066-847c-f4bb1cd4e361\"\nversion = \"0.4.1+1\"\n\n[[Xorg_xkbcomp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxkbfile_jll\"]\ngit-tree-sha1 = \"4bcbf660f6c2e714f87e960a171b119d06ee163b\"\nuuid = \"35661453-b289-5fab-8a00-3d9160c6a3a4\"\nversion = \"1.4.2+4\"\n\n[[Xorg_xkeyboard_config_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xkbcomp_jll\"]\ngit-tree-sha1 = \"5c8424f8a67c3f2209646d4425f3d415fee5931d\"\nuuid = \"33bec58e-1273-512f-9401-5d533626f822\"\nversion = \"2.27.0+4\"\n\n[[Xorg_xtrans_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"79c31e7844f6ecf779705fbc12146eb190b7d845\"\nuuid = \"c5fb5394-a638-5e4d-96e5-b29de1b5cf10\"\nversion = \"1.4.0+3\"\n\n[[Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[Zstd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"cc4bf3fdde8b7e3e9fa0351bdeedba1cf3b7f6e6\"\nuuid = \"3161d3a3-bdf6-5164-811a-617609db77b4\"\nversion = \"1.5.0+0\"\n\n[[libass_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"HarfBuzz_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"5982a94fcba20f02f42ace44b9894ee2b140fe47\"\nuuid = \"0ac62f75-1d6f-5e53-bd7c-93b484bb37c0\"\nversion = \"0.15.1+0\"\n\n[[libfdk_aac_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"daacc84a041563f965be61859a36e17c4e4fcd55\"\nuuid = \"f638f0a6-7fb0-5443-88ba-1cc74229b280\"\nversion = \"2.0.2+0\"\n\n[[libpng_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"94d180a6d2b5e55e447e2d27a29ed04fe79eb30c\"\nuuid = \"b53b4c65-9356-5827-b1ea-8c7a1a84506f\"\nversion = \"1.6.38+0\"\n\n[[libvorbis_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Ogg_jll\", \"Pkg\"]\ngit-tree-sha1 = \"c45f4e40e7aafe9d086379e5578947ec8b95a8fb\"\nuuid = \"f27f6e37-5d2b-51aa-960f-b287f2bc3b7a\"\nversion = \"1.3.7+0\"\n\n[[nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\n[[x264_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fea590b89e6ec504593146bf8b988b2c00922b2\"\nuuid = \"1270edf5-f2f9-52d2-97e9-ab00b5d0237a\"\nversion = \"2021.5.5+0\"\n\n[[x265_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"ee567a171cce03570d77ad3a43e90218e38937a9\"\nuuid = \"dfaa095f-4041-5dcd-9319-2fabd8486b76\"\nversion = \"3.5.0+0\"\n\n[[xkbcommon_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\", \"Wayland_protocols_jll\", \"Xorg_libxcb_jll\", \"Xorg_xkeyboard_config_jll\"]\ngit-tree-sha1 = \"ece2350174195bb31de1a63bea3a41ae1aa593b6\"\nuuid = \"d8fb68d0-12a3-5cfd-a85a-d49703b185fd\"\nversion = \"0.9.1+5\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─dad114fe-fbfb-11ea-32dd-a302838af30f\n# ╟─fdab0c70-fbfb-11ea-116d-9f1b613f9d0d\n# ╟─0d88a212-fbfc-11ea-37ae-c5e0c6a894e8\n# ╟─67071830-fbfc-11ea-3925-798d3d288500\n# ╟─3bb281f0-fc02-11ea-34f0-fd00648c27bb\n# ╠═bf54eece-fc02-11ea-3dbc-b37a5644eab1\n# ╠═cd9cc940-fc02-11ea-2a40-19bc6f79a6d3\n# ╠═e5488250-fc02-11ea-0bc1-4365461fb202\n# ╟─08de4fb0-fc03-11ea-08fb-616f792f7c7f\n# ╟─cfd86bf0-fc03-11ea-22ef-b99d3e3fbfce\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "c3a3aabceb90b095505c1008f81c5e9b29956957", "size": 35676, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Lectures/Lecture05.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/Lecture05.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/Lecture05.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": 31.4603174603, "max_line_length": 489, "alphanum_fraction": 0.7258941585, "num_tokens": 16093, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9553191322715436, "lm_q2_score": 0.8807970873650401, "lm_q1q2_score": 0.8414423092088732}} {"text": "using DifferentialEquations, Plots\n\n#Solving the simple pendulum with a traditional ODE method\n#==========================================================#\nfunction pendulum(du, u, params, t)\n#reference: http://www.pgccphy.net/ref/advmech.pdf page 6\n\n g = params[1] #gravitational acceleration\n m = params[2] #mass\n l = params[3] #length\n\n θ = u[1]\n ℒ = u[2]\n\n d_θ = ℒ/(m*l^2)\n d_ℒ = -m*g*l*sin(θ)\n\n du .= [d_θ, d_ℒ]\n return nothing\nend\n\ng = 9.81\nm = 2.\nl = 1.\nparams = [g,m,l]\nu0 = [1.0,1.0]\n\nprob = ODEProblem(pendulum, u0, (0., 100.), params)\nsol1 = solve(prob, AutoVern7(Rodas5()), dt = .05)\n\n#==========================================================#\n\n\n\n#Solving the simple pendulum with the DiffEqPhysics.jl HamiltonianProblem()\n#==========================================================#\nfunction H(θ, ℒ, params)\n g = params[1] #gravitational acceleration\n m = params[2] #mass\n l = params[3] #length\n\n return ℒ^2/(2*m*l^2) + m*g*l*(1-cos(θ))\nend\n\ng = 9.81\nm = 2.\nl = 1.\nparams = [g,m,l]\nθ₀ = 1.\nℒ₀ = 1.\n\nprob = HamiltonianProblem(H, θ₀, ℒ₀, (0., 100.), p=params)\nsol2 = solve(prob, SofSpa10(), dt = .05);\n#==========================================================#\n\n\n#Plotting\n#==========================================================#\nplot(sol1, vars=1, tspan=(0,20), label=\"ODE Method\")\nplot!(sol2.t, sol2[1,:], xlim=(0,20), label=\"Hamiltonian Method\")\n#They produce the same solution!\n", "meta": {"hexsha": "fb51d9bbfc4804fb46464c7e5f9ca2f3c846e699", "size": 1440, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/pendulum.jl", "max_stars_repo_name": "Eggiverse/DiffEqPhysics.jl", "max_stars_repo_head_hexsha": "f7c80669d74e27bb50006ebccb31a51ec0559587", "max_stars_repo_licenses": ["MIT"], "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/pendulum.jl", "max_issues_repo_name": "Eggiverse/DiffEqPhysics.jl", "max_issues_repo_head_hexsha": "f7c80669d74e27bb50006ebccb31a51ec0559587", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/pendulum.jl", "max_forks_repo_name": "Eggiverse/DiffEqPhysics.jl", "max_forks_repo_head_hexsha": "f7c80669d74e27bb50006ebccb31a51ec0559587", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2258064516, "max_line_length": 75, "alphanum_fraction": 0.4902777778, "num_tokens": 464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191271831559, "lm_q2_score": 0.8807970858005139, "lm_q1q2_score": 0.8414423032324142}} {"text": "using JuMP\n\nusing DataStructures\nusing Parameters\nusing Printf\nusing SparseArrays, LinearAlgebra\n\nimport Xpress\n\nroot_path = dirname(@__DIR__)\npush!(LOAD_PATH, root_path);\ncd(root_path)\ninclude(joinpath(root_path, \"src\", \"PTDF.jl\"));\n\n\n## programme d'optimisation pour calculer theta\nfunction compute_theta(B,P)\n nb_buses = length(P);\n model = Model(Xpress.Optimizer);\n set_optimizer_attribute(model, \"OUTPUTLOG\", 0);\n\n @variable(model, theta[1:nb_buses]);\n @objective(model,Min,0);\n\n for i in range(1,nb_buses)\n @constraint(model,sum(B[i,j] * theta[j] for j in range(1,nb_buses)) == P[i]);\n end\n\n # print(model);\n\n optimize!(model);\n\n return [value(theta[i]) for i in range(1,nb_buses)];\nend;\n\n\n\nfunction compute_ptdf_by_optim(network::PTDF.Network,ref_bus_num::Int, EPS_DIAG::Float64)\n nb_buses = length(network.buses);\n nb_branches = length(network.branches);\n\n # calcul de B\n B=PTDF.get_B(network,EPS_DIAG,false);\n\n # calcul de la colonne de la PTDF pour chaque noeud\n PTDF_matrix = zeros(nb_branches,nb_buses);\n # println(network.buses)\n for bus in network.buses\n bus_num = bus[1]\n # println(\"$bus, id is $bus_num\")\n #définition de la distribution des injections\n P = zeros(nb_buses);\n if bus_num != ref_bus_num\n P[bus_num]=1;\n P[ref_bus_num]+=-1;\n end\n\n #calcul de theta tel que B*theta = P\n theta = compute_theta(B,P);\n\n #calcul de la PTDF\n for branch in collect(network.branches)\n branch_num = branch[1];\n x_inv = PTDF.get_b(branch[2]);\n\n ior = branch[2].from;\n iex = branch[2].to;\n \n PTDF_matrix[branch_num,bus_num] = x_inv*(theta[ior]-theta[iex]);\n end\n end\n return PTDF_matrix;\nend;\n\nfunction compare_ptdfs(network::PTDF.Network,ref_bus_num::Int, EPS_DIAG::Float64)\n\n ptdf_optim = compute_ptdf_by_optim(network,ref_bus_num, EPS_DIAG);\n ptdf_with_inv = PTDF.compute_ptdf(network,ref_bus_num, EPS_DIAG);\n\n return ptdf_optim-ptdf_with_inv;\nend;\n\n\n##### Example\nEPS_DIAG = 0e-6;\nref_bus_num = 1;\ndata_path_sparse = joinpath(@__DIR__, \"..\", \"data_matpower\", \"case1354pegase\");\ndata_path = data_path_sparse;\n\nnetwork = PTDF.read_network(data_path);\n\n# ptdf_optim = compute_ptdf_by_optim(network,ref_bus_num);\nptdf_difference = norm(compare_ptdfs(network, ref_bus_num, EPS_DIAG));\nprintln(\"error_max = $ptdf_difference\");", "meta": {"hexsha": "03da5fc351fe7cb2b319fa601500b0e591737703", "size": 2466, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test-ptdf/test_ptdf.jl", "max_stars_repo_name": "klorel/pscopf", "max_stars_repo_head_hexsha": "3dd4af44143272a78ca5ba81b04ff0909a1f0947", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test-ptdf/test_ptdf.jl", "max_issues_repo_name": "klorel/pscopf", "max_issues_repo_head_hexsha": "3dd4af44143272a78ca5ba81b04ff0909a1f0947", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 28, "max_issues_repo_issues_event_min_datetime": "2022-03-08T17:01:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T13:09:41.000Z", "max_forks_repo_path": "test-ptdf/test_ptdf.jl", "max_forks_repo_name": "klorel/pscopf", "max_forks_repo_head_hexsha": "3dd4af44143272a78ca5ba81b04ff0909a1f0947", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-20T14:28:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-20T14:28:07.000Z", "avg_line_length": 26.2340425532, "max_line_length": 89, "alphanum_fraction": 0.6686942417, "num_tokens": 685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191322715436, "lm_q2_score": 0.8807970748488297, "lm_q1q2_score": 0.8414422972518979}} {"text": "module NewtonsMethod\n\nusing LinearAlgebra, Statistics, Compat, ForwardDiff\n\nfunction newtonroot(f, f′, x₀; tol=1E-7, maxiter=1000)\n x_old = x₀\n normdiff = Inf\n iter = 1\n while normdiff > tol && iter <= maxiter\n x_new = x_old - f(x_old)/f′(x_old)\n normdiff = norm(x_new - x_old)\n x_old = x_new\n iter += 1\n end\n normdiff > tol ? (nothing, normdiff, iter) : (x_old, normdiff, iter)\nend\n\nfunction newtonroot(f, x₀; tol=1E-7, maxiter=1000)\n Diff(f) = x -> ForwardDiff.derivative(f, x)\n f′ = Diff(f)\n newtonroot(f, f′, x₀, tol=tol, maxiter=maxiter)\nend\n\nexport newtonroot\n\nend\n", "meta": {"hexsha": "9d0610c75e40158d3ceb1484ccb9998d18b86dd1", "size": 626, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NewtonsMethod.jl", "max_stars_repo_name": "maxnorton/NewtonsMethod.jl", "max_stars_repo_head_hexsha": "cbed0238734c6ce1bb13f2426e9720b67f297b12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NewtonsMethod.jl", "max_issues_repo_name": "maxnorton/NewtonsMethod.jl", "max_issues_repo_head_hexsha": "cbed0238734c6ce1bb13f2426e9720b67f297b12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NewtonsMethod.jl", "max_forks_repo_name": "maxnorton/NewtonsMethod.jl", "max_forks_repo_head_hexsha": "cbed0238734c6ce1bb13f2426e9720b67f297b12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1851851852, "max_line_length": 72, "alphanum_fraction": 0.6293929712, "num_tokens": 218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.966410494349896, "lm_q2_score": 0.8705972684083609, "lm_q1q2_score": 0.8413543365421932}} {"text": "using ModelingToolkit\nusing Plots\nusing DifferentialEquations\nusing LinearAlgebra\n\n@parameters t σ ρ β # add metadata to variables, i.e. this is a parameter!\n@variables x(t) y(t) z(t) # time-dependent variables\nD = Differential(t)\n\nD(x) # dx/dt\n\neqs = [ D(D(x)) ~ σ * (y-x),\n D(y) ~ x*(ρ-z) - y,\n D(z) ~ x*y - β*z]\n\n# generate an ode system from the equationsj\nsys = ODESystem(eqs)\n\n# what are the equations?\nequations(sys)\n\n\n# but ODE solver want's things in first order form...\n# So just lower the order!\nsys = ode_order_lowering(sys)\nequations(sys)\n# now we have 4 - first order ODEs\n\n# define the initial conditions\nu0 = [D(x) => 2.0,\n x => 1.0,\n y => 0.0,\n z => 0.0]\n\n# define parameter values\np = [σ => 28.0,\n ρ => 10.0,\n β => 8/3]\n\n\n# build the ODE problem, i.e. translate from Symbolic to Numeric\ntspan = (0.0, 100.0)\n\nprob = ODEProblem(sys, u0, tspan, p, jac=true, sparse=true) # build analytic jacobian function and use sparse arrays\n\nsol = solve(prob, Tsit5())\n\n\nstates(sys) # what is the ordering of the solution vector\n\n\n# HYPE: we can use variables to index solution object!!!!!\nsol[x] # get time series for x\nsol[D(x)]\n\n# what if you want to interpolate\nsol(50.0, idxs=y) # i.e. what is y(t) for t=50.0\n\nplot(sol, vars=(x, y))\n\n\n\n# ----- Lorenz equations --------------\n\neqs = [D(x) ~ σ*(y-x),\n D(y) ~ x*(ρ-z) - y,\n D(z) ~ x*y - β*z]\n\n\n# same symbolic equations\n@named lorenz1 = ODESystem(eqs)\n@named lorenz2 = ODESystem(eqs)\n\n# define a mixture between the two\n\n@variables a(t)\n@parameters γ\n\n# define the connection by an algebraic equation\nconnections = [0 ~ lorenz1.x + lorenz2.y + a*γ]\n\n\n# indep var, array of state variables, array of parameters and the systems of odes these relate\nconnected = ODESystem(connections, t, [a], [γ], systems=[lorenz1, lorenz2])\nequations(connected)\n\n\n# define initial conditions, parameters, timespan\nu0 = [lorenz1.x => 1.0, lorenz1.y => 0.0, lorenz1.z => 0.0, lorenz2.x => 0.0, lorenz2.y => 1.0, lorenz2.z => 0.0, a=> 2.0]\np = [lorenz1.σ => 10.0, lorenz1.ρ => 28.0, lorenz1.β => 8/2, lorenz2.σ => 10.0, lorenz2.ρ => 28.0, lorenz2.β => 8/3, γ => 2.0]\ntspan = (0.0, 100.0)\n\nprob = ODEProblem(connected, u0, tspan, p)\n\nsol = solve(prob)\n\nplot(sol, vars=(a, lorenz1.x, lorenz2.z))\n\n\n\n# --------------- Using MTK without using MTK ------------------------\n# naive version that allocates array instead of using inplace f(du, u, p, t)\nfunction rober(u, p, t)\n y₁, y₂, y₃ = u\n k₁, k₂, k₃ = p\n [-k₁*y₁+k₃*y₂*y₃, k₁*y₁-k₂*y₂^2-k₃*y₂*y₃, k₂*y₂^2]\nend\n\n\nprob = ODEProblem(rober, [1.0, 0.0, 0.0], (0.0, 1e5), (0.04, 3e7, 1e4))\n# turn it into an internal MTK problem defined symbolically\nsys = modelingtoolkitize(prob)\nequations(sys)\n\n\n# redefine the problem to use the symbolic jacobian\nprob_jac = ODEProblem(sys, [1.0, 0.0, 0.0], (0.0, 1e5), (0.04, 3e7, 1e4), jac=true)\n\n\nusing BenchmarkTools\n\n@btime sol = solve(prob)\n@btime sol = solve(prob_jac)\n\n\n\n\n#----------- problems with Algebraic Constraints-------------------\nfunction pendulum!(du, u, p, t)\n x, dx, y, dy, T = u\n g, L = p\n du[1] = dx\n du[2] = T*x\n du[3] = dy\n du[4] = T*y -g\n du[5] = x^2 + y^2 - L^2 # the length\n return nothing\nend\n\n# Mu' = f\npendulum_fun! = ODEFunction(pendulum!, mass_matrix=Diagonal([1,1,1,1,0]))\nu0 = [1.0, 0, 0, 0, 0]\np = [9.8, 1]\ntspan = (0, 10.0)\n\npendulum_prob = ODEProblem(pendulum_fun!, u0, tspan, p)\n\n# this doesn't work for technical reasons about DAE's. We need to refactor it into a nicer form\nsol = solve(pendulum_prob, Rodas4(), abstol=1e-8, reltol=1e-8)\n\n# convert to symbolic representation\ntraced_sys = modelingtoolkitize(pendulum_prob)\nequations(traced_sys)\n# lower dae index and simplify\npendulum_sys = structural_simplify(dae_index_lowering(traced_sys)) # this is just being explicit, we could have just done structural simplify\nequations(pendulum_sys)\n\nprob = ODAEProblem(pendulum_sys, Pair[], tspan)\nsol = solve(prob, Tsit5(), abstol=1e-8, reltol=1e-8)\nplot(sol, vars=states(traced_sys))\n", "meta": {"hexsha": "9db15942f761d017beae12f7eb3a413bee79f806", "size": 4021, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "SimulatingBigModelsInJuliaWithModelingToolkit/tutorial_rackauckas.jl", "max_stars_repo_name": "john-waczak/JuliaCon2021", "max_stars_repo_head_hexsha": "48979656e94af4e5707094fc836ed76971593eac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SimulatingBigModelsInJuliaWithModelingToolkit/tutorial_rackauckas.jl", "max_issues_repo_name": "john-waczak/JuliaCon2021", "max_issues_repo_head_hexsha": "48979656e94af4e5707094fc836ed76971593eac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SimulatingBigModelsInJuliaWithModelingToolkit/tutorial_rackauckas.jl", "max_forks_repo_name": "john-waczak/JuliaCon2021", "max_forks_repo_head_hexsha": "48979656e94af4e5707094fc836ed76971593eac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9751552795, "max_line_length": 141, "alphanum_fraction": 0.6418801293, "num_tokens": 1460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107949104866, "lm_q2_score": 0.8976952852648487, "lm_q1q2_score": 0.8413297118904649}} {"text": "## Let's see how finite difference approximations work.\n\nusing Printf\nmyfun = x -> sin(x)\nmyderiv = x -> cos(x) # so we can get error\nfinitediff(f,x,h) = (f(x+h) - f(x))/h\nx = pi/6\ntruederiv = myderiv(x)\nfor h = 10.0.^-(1:16)\n fdderiv = finitediff(myfun,x,h)\n @printf(\"h=%.1e approx=%.8e err=%.8e\\n\",\n h, fdderiv, abs(fdderiv-truederiv))\nend\n\n## Now try a multidim version\nfunction finitediff_i(f,x,h,i)\n fx = f(x)\n xi = x[i] # make a copy\n x[i] += h\n fxh = f(x) # eval f(x+h)\n x[i] = xi # restore\n return (fxh-fx)/h\nend\nfinitediffgrad(f,x,h) = map( i -> finitediff_i(f,x,h,i), 1:length(x) )\n## validate our work on gradient of quadratics\nusing LinearAlgebra\nQ = [1 0.5;0.5 1]\ns = [-1,-1.5]\nquadratic2(A,b) = x -> x'*A*x + x'*b\nmyfun = quadratic2(Q,s)\nmyderiv = x -> 2*Q*x + s\nx = [3.5;-1.5]\ntruederiv = myderiv(x)\nfor h = 10.0.^-(1:16)\n fdderiv = finitediffgrad(myfun,x,h)\n @printf(\"h=%.1e err=%.8e\\n\",\n h, norm(fdderiv-truederiv))\nend\n", "meta": {"hexsha": "ec22c3923e970cf76c90bdb6d7ef8c72363be56c", "size": 954, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "6-unit-5-demos/finite-difference.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/finite-difference.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/finite-difference.jl", "max_forks_repo_name": "dgleich/cs590-ncds", "max_forks_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-07-13T03:13:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-17T01:37:03.000Z", "avg_line_length": 24.4615384615, "max_line_length": 70, "alphanum_fraction": 0.607966457, "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966702001758, "lm_q2_score": 0.8887587875995482, "lm_q1q2_score": 0.8412961089528777}} {"text": "p = [ randn(2) for i = 1:10 ] # 10 random points - note array-of-array\n\n# Plot the points as dots\n# The functions first and last simply collects the corresponding indices\nusing PyPlot\nplot(first.(p), last.(p), \".\")\naxis(\"equal\"); grid(true);\n\nfunction clockwise_oriented(p1, p2, p3)\n # Return true if the line-segment between points p1,p2 is clockwise\n # oriented to the line-segment between points p1,p3\n cross = (p3[2] - p1[2]) * (p2[1] - p1[1]) - (p3[1] - p1[1]) * (p2[2] - p1[2])\n return cross > 0\nend\n\n# Tests\nprintln(clockwise_oriented([0,0], [1,1], [2,3]))\nprintln(clockwise_oriented([0,0], [1,1], [3,2]))\n\nfunction convex_hull(p)\n # Find the nodes on the convex hull of the point array p using\n # the Jarvis march (gift wrapping) algorithm\n\n _, pointOnHull = findmin(first.(p)) # Start at left-most point\n hull = [pointOnHull] # Output: Vector of node indices on the convex hull\n \n while length(hull) ≤ 1 || hull[1] != hull[end] # Loop until closed polygon\n nextPoint = hull[end] % length(p) + 1 # First candidate, any point except current\n for j = 1:length(p) # Consider all other points\n if clockwise_oriented(p[hull[end]], p[nextPoint], p[j]) # If \"more to the left\", switch\n nextPoint = j\n end\n end\n push!(hull, nextPoint) # Update current point\n end\n return hull\nend\n\n# Example: 100 random points, compute and draw the convex hull\np = [ randn(2) for i = 1:100 ]\nhull = convex_hull(p)\nplot(first.(p), last.(p), \".\")\nplot(first.(p[hull]), last.(p[hull]))\naxis(\"equal\"); grid(true);\n\nusing LinearAlgebra\nfunction linesegment_intersect(p1, p2, q1, q2, δ)\n A = [p2-p1 q1-q2]\n b = q1-p1\n if rank(A) == 2\n st = A \\ b\n if all(-δ .≤ st .≤ 1 + δ)\n pintersect = p1 + st[1] * (p2 - p1)\n return true, pintersect\n else\n return false, nothing\n end\n else\n # Warning: parallel lines, should check if they actually overlap\n return false, nothing\n end\nend\n\n# Example: n random lines, find and plot all intersections\nn = 10\nlines = [ [rand(2), rand(2)] for i = 1:n ]\n\n# Plot all lines\nfor line in lines\n plot([line[1][1], line[2][1]], [line[1][2], line[2][2]])\nend\n\n# Find all intersections - note that we only consider j>i to avoid checking\n# the same 2 line-segments twice\nfor i = 1:n\n for j = i+1:n\n isect, pq = linesegment_intersect(lines[i][1], lines[i][2], lines[j][1], lines[j][2], 0)\n if isect\n plot(pq[1], pq[2], \"o\")\n end\n end\nend\n\naxis(\"equal\"); grid(true);\n\nfunction tplot(p, t)\n # Plot triangular mesh with nodes `p` and triangles `t`\n tris = convert(Array{Int64}, hcat(t...)')\n tripcolor(first.(p), last.(p), tris .- 1, 0*tris[:,1],\n cmap=\"Set3\", edgecolors=\"k\", linewidth=1)\n axis(\"equal\")\n return\nend\n\np = [[0,0], [1,0], [0,1], [1,2], [2,1]]\nt = [[1,2,5], [1,5,3], [3,5,4]]\ntplot(p,t)\n\nusing Triangle\n\nfunction delaunay(p)\n # Delaunay triangulation `t` of array of nodes `p`\n vertex_map = Array{Int64,1}(1:size(p,1))\n t = Triangle.basic_triangulation(convert(Array{Float64}, hcat(p...)'), vertex_map)\nend\n\nt = delaunay(p)\ntplot(p,t)\n\np = [ randn(2) for i = 1:50 ]\nt = delaunay(p)\ntplot(p,t)\n\n\n", "meta": {"hexsha": "1523d1613ef7571e884fb7bed450243803eb8191", "size": 3271, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "textbook/_build/jupyter_execute/content/Computational_Geometry/Computational_Geometry.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/Computational_Geometry/Computational_Geometry.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/Computational_Geometry/Computational_Geometry.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": 28.4434782609, "max_line_length": 99, "alphanum_fraction": 0.602568022, "num_tokens": 1067, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475715065793, "lm_q2_score": 0.891811041124754, "lm_q1q2_score": 0.8412877798877908}} {"text": "# Part of submodule Utils of BetaML\n# Function of a single argument (including scalars and vectors), like activation functions but also gini, entropy,...)\n\n\n# ------------------------------------------------------------------------------\n# Various neural network activation functions as well their derivatives\n\n#identity(x) = x already in Julia base\ndidentity(x) = one(x)\n\"\"\" relu(x) \\n\\n Rectified Linear Unit \\n\\n https://www.cs.toronto.edu/~hinton/absps/reluICML.pdf\"\"\"\nrelu(x) = max(zero(x), x)\n\"\"\" drelu(x) \\n\\n Rectified Linear Unit \\n\\n https://www.cs.toronto.edu/~hinton/absps/reluICML.pdf\"\"\"\ndrelu(x) = x <= zero(x) ? zero(x) : one(x)\n\"\"\"elu(x; α=1) with α > 0 \\n\\n https://arxiv.org/pdf/1511.07289.pdf\"\"\"\nelu(x; α=one(x)) = x > zero(x) ? x : α *(exp(x) - one(x))\n\"\"\"delu(x; α=1) with α > 0 \\n\\n https://arxiv.org/pdf/1511.07289.pdf\"\"\"\ndelu(x; α=one(x)) = x > zero(x) ? one(x) : elu(x, α=α) + α\n\"\"\"celu(x; α=1) \\n\\n https://arxiv.org/pdf/1704.07483.pdf\"\"\"\ncelu(x; α=one(x)) = max(zero(x),x)+ min(zero(x), α *(exp(x / α) - one(x) ))\n#celu(x; α=one(x)) = if x >= zero(x) x/α else exp(x/α)-one(x) end\n\"\"\"dcelu(x; α=1) \\n\\n https://arxiv.org/pdf/1704.07483.pdf\"\"\"\ndcelu(x; α=one(x)) = x >= zero(x) ? one(x) : exp(x/α)\n\"\"\"plu(x;α=0.1,c=1) \\n\\n Piecewise Linear Unit \\n\\n https://arxiv.org/pdf/1809.09534.pdf\"\"\"\nplu(x;α=0.1,c=one(x)) = max(α*(x+c)-c,min(α*(x-c)+c,x)) # convert(eltype(x), α)\n\"\"\"dplu(x;α=0.1,c=1) \\n\\n Piecewise Linear Unit derivative \\n\\n https://arxiv.org/pdf/1809.09534.pdf\"\"\"\ndplu(x;α=0.1,c=one(x)) = ( ( x >= (α*(x+c)-c) && x <= (α*(x+c)+c) ) ? one(x) : α ) # convert(eltype(x), α)\n\n\n\"\"\"\n pool1d(x,poolSize=2;f=mean)\n\nApply funtion `f` to a rolling poolSize contiguous (in 1d) neurons.\n\nApplicable to `VectorFunctionLayer`, e.g. `layer2 = VectorFunctionLayer(nₗ,f=(x->pool1d(x,4,f=mean))`\n**Attention**: to apply this funciton as activation function in a neural network you will need Julia version >= 1.6, otherwise you may experience a segmentation fault (see [this bug report](https://github.com/FluxML/Zygote.jl/issues/943))\n\"\"\"\npool1d(x,poolSize=3;f=mean) = [f(x[i:i+poolSize-1]) for i in 1:length(x)-poolSize+1] # we may try to use CartesianIndices/LinearIndices for a n-dimensional generalisation\n\n\n#tanh(x) already in Julia base\n\"\"\"dtanh(x)\"\"\"\ndtanh(x) = sech(x)^2 # = 1-tanh(x)^2\n\"\"\"sigmoid(x)\"\"\"\nsigmoid(x) = one(x)/(one(x)+exp(-x))\n\"\"\"dsigmoid(x)\"\"\"\ndsigmoid(x) = exp(-x)*sigmoid(x)^2\n\"\"\"softmax (x; β=1) \\n\\n The input x is a vector. Return a PMF\"\"\"\nsoftmax(x; β=one.(x)) = exp.((β .* x) .- lse(β .* x)) # efficient implementation of softmax(x) = exp.(x) ./ sum(exp.(x))\nsoftmax(x, β) = softmax(x, β=β)\n\"\"\" dsoftmax(x; β=1) \\n\\n Derivative of the softmax function \\n\\n https://eli.thegreenplace.net/2016/the-softmax-function-and-its-derivative/\"\"\"\nfunction dsoftmax(x; β=one(x[1]))\n x = makeColVector(x)\n d = length(x)\n out = zeros(d,d)\n y = softmax(x,β=β)\n for i in 1:d\n smi = y[i]\n for j in 1:d\n if j == i\n out[i,j] = β*(smi-smi^2)\n else\n out[i,j] = - β*y[j]*smi\n end\n end\n end\n return out\nend\n\n\"\"\"softplus(x) \\n\\n https://en.wikipedia.org/wiki/Rectifier_(neural_networks)#Softplus\"\"\"\nsoftplus(x) = log(one(x) + exp(x))\n\"\"\"dsoftplus(x) \\n\\n https://en.wikipedia.org/wiki/Rectifier_(neural_networks)#Softplus\"\"\"\ndsoftplus(x) = 1/(1+exp(-x))\n\"\"\" mish(x) \\n\\n https://arxiv.org/pdf/1908.08681v1.pdf\"\"\"\nmish(x) = x*tanh(softplus(x))\n\"\"\" dmish(x) \\n\\n https://arxiv.org/pdf/1908.08681v1.pdf\"\"\"\ndmish(x) = x*(1 - tanh(log(exp(x) + 1))^2)*exp(x)/(exp(x) + 1) + tanh(log(exp(x) + 1))\n\n\n\"\"\"\n autoJacobian(f,x;nY)\n\nEvaluate the Jacobian using AD in the form of a (nY,nX) matrix of first derivatives\n\n# Parameters:\n- `f`: The function to compute the Jacobian\n- `x`: The input to the function where the jacobian has to be computed\n- `nY`: The number of outputs of the function `f` [def: `length(f(x))`]\n\n# Return values:\n- An `Array{Float64,2}` of the locally evaluated Jacobian\n\n# Notes:\n- The `nY` parameter is optional. If provided it avoids having to compute `f(x)`\n\"\"\"\nfunction autoJacobian(f,x;nY=length(f(x)))\n x = convert(Array{Float64,1},x)\n #j = Array{Float64, 2}(undef, size(x,1), nY)\n #for i in 1:nY\n # j[:, i] .= gradient(x -> f(x)[i], x)[1]\n #end\n #return j'\n j = Array{Float64, 2}(undef, nY, size(x,1))\n for i in 1:nY\n j[i,:] = gradient(x -> f(x)[i], x)[1]'\n end\n return j\nend\n\n\n# ------------------------------------------------------------------------------\n# Partition tasks..\n\n\"\"\"\n gini(x)\n\nCalculate the Gini Impurity for a list of items (or rows).\n\nSee: https://en.wikipedia.org/wiki/Decision_tree_learning#Information_gain\n\"\"\"\nfunction gini(x)\n\n counts = classCounts(x)\n N = size(x,1)\n impurity = 1.0\n for c in counts\n probₖ = c / N\n impurity -= probₖ^2\n end\n return impurity\n #=\n counts = classCountsWithLabels(x)\n N = size(x,1)\n impurity = 1.0\n for k in keys(counts)\n probₖ = counts[k] / N\n impurity -= probₖ^2\n end\n return impurity\n =#\nend\n\n\"\"\"\n entropy(x)\n\nCalculate the entropy for a list of items (or rows).\n\nSee: https://en.wikipedia.org/wiki/Decision_tree_learning#Gini_impurity\n\"\"\"\nfunction entropy(x)\n counts = classCounts(x)\n N = size(x,1)\n entr = 0.0\n for c in counts\n probₖ = c / N\n entr -= probₖ * log2(probₖ)\n end\n return entr\nend\n\n\"\"\"variance(x) - population variance\"\"\"\nvariance(x) = var(x,corrected=false)\n\n# ------------------------------------------------------------------------------\n# ------------------------------------------------------------------------------\n\n\"\"\"bic(lL,k,n) - Bayesian information criterion (lower is better)\"\"\"\nbic(lL,k,n) = k*log(n)-2*lL\n\"\"\"aic(lL,k) - Akaike information criterion (lower is better)\"\"\"\naic(lL,k) = 2*k-2*lL\n\n# ------------------------------------------------------------------------------\n# Various kernel functions (e.g. for Perceptron)\n\"\"\"Radial Kernel (aka _RBF kernel_) parametrised with γ=1/2. For other gammas γᵢ use\n`K = (x,y) -> radialKernel(x,y,γ=γᵢ)` as kernel function in the supporting algorithms\"\"\"\nradialKernel(x,y;γ=1/2) = exp(-γ*norm(x-y)^2)\n\"\"\"Polynomial kernel parametrised with `c=0` and `d=2` (i.e. a quadratic kernel).\nFor other `cᵢ` and `dᵢ` use `K = (x,y) -> polynomialKernel(x,y,c=cᵢ,d=dᵢ)` as\nkernel function in the supporting algorithms\"\"\"\npolynomialKernel(x,y;c=0,d=2) = (dot(x,y)+c)^d\n", "meta": {"hexsha": "d58bb3ba2c9fbec3cd94bd0a81bb23c0a9f6f28d", "size": 6603, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Utils/Transformers.jl", "max_stars_repo_name": "sylvaticus/bmlt.jl", "max_stars_repo_head_hexsha": "767f69779913dd8a12412be0259e6718c9b61e6f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-05-19T17:13:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-06T20:49:27.000Z", "max_issues_repo_path": "src/Utils/Transformers.jl", "max_issues_repo_name": "sylvaticus/bmlt.jl", "max_issues_repo_head_hexsha": "767f69779913dd8a12412be0259e6718c9b61e6f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-06-03T12:08:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-03T12:09:04.000Z", "max_forks_repo_path": "src/Utils/Transformers.jl", "max_forks_repo_name": "sylvaticus/bmlt.jl", "max_forks_repo_head_hexsha": "767f69779913dd8a12412be0259e6718c9b61e6f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-05-20T11:37:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-22T14:07:32.000Z", "avg_line_length": 36.6833333333, "max_line_length": 238, "alphanum_fraction": 0.5720127215, "num_tokens": 2157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399034724604, "lm_q2_score": 0.8670357460591569, "lm_q1q2_score": 0.8412326785636091}} {"text": "using GLM, Distributions, DataFrames\n\ndata1 = parse.(Float64, readlines(\"../data/machine1.csv\"))\ndata2 = parse.(Float64, readlines(\"../data/machine2.csv\"))\ndata3 = parse.(Float64, readlines(\"../data/machine3.csv\"))\n\nfunction manualANOVA(allData)\n nArray = length.(allData)\n d = length(nArray)\n\n xBarTotal = mean(vcat(allData...))\n xBarArray = mean.(allData)\n\n ssBetween = sum( [nArray[i]*(xBarArray[i] - xBarTotal)^2 for i in 1:d] )\n ssWithin = sum([sum([(ob - xBarArray[i])^2 for ob in allData[i]])\n\t\t\t\tfor i in 1:d])\n dfBetween = d-1\n dfError = sum(nArray)-d\n\n msBetween = ssBetween/dfBetween\n msError = ssWithin/dfError\n fStat = msBetween/msError\n pval = ccdf(FDist(dfBetween,dfError),fStat)\n return (fStat,pval)\nend\n\nfunction glmANOVA(allData)\n nArray = length.(allData)\n d = length(nArray)\n\n treatment = vcat([fill(k,nArray[k]) for k in 1:d]...)\n response = vcat(allData...)\n dataFrame = DataFrame(Response=response, Treatment=categorical(treatment))\n modelH0 = lm(@formula(Response ~ 1), dataFrame)\n modelH1a = lm(@formula(Response ~ 1 + Treatment), dataFrame)\n res = ftest(modelH1a.model, modelH0.model)\n (res.fstat[1],res.pval[1])\nend\n\nprintln(\"Manual ANOVA: \", manualANOVA([data1, data2, data3]))\nprintln(\"GLM ANOVA: \", glmANOVA([data1, data2, data3]))", "meta": {"hexsha": "2b485497a191cecfe6ac0dae347208daa4e4c4b1", "size": 1328, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "7_chapter/anovaFTest.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/anovaFTest.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/anovaFTest.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.3902439024, "max_line_length": 78, "alphanum_fraction": 0.6671686747, "num_tokens": 418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214532237354, "lm_q2_score": 0.8723473779969194, "lm_q1q2_score": 0.8412232912659046}} {"text": "#----------------------------#\n# see page 57 in Sarkka book #\n#----------------------------#\n\nfunction filteringrecursion(y; A = A, H = H, Q = Q, R = R, m₀ = m₀, P₀ = P₀)\n\n N = length(y)\n\n # Store here state distribution\n\n μstate, Σstate = Array{Vector{Float64}}(undef, N), Array{Matrix{Float64}}(undef, N)\n\n # Start recursion with prior mean and prior covariance\n\n mₖ₋₁, Pₖ₋₁ = m₀, P₀\n\n for k in 1:N\n\n # prediction step\n\n mₖ⁻ = A * mₖ₋₁\n\n Pₖ⁻ = A * Pₖ₋₁ * A' + Q # (4.20)\n\n # update step\n\n 𝐯ₖ = y[k] - H * mₖ⁻\n\n Sₖ = H * Pₖ⁻ * H' + R\n\n Kₖ = (Pₖ⁻ * H') / Sₖ\n\n mₖ = mₖ⁻ + Kₖ * 𝐯ₖ\n\n Pₖ = Pₖ⁻ - Kₖ * Sₖ * (Kₖ)' # (4.21)\n\n # store mean and covariance of Gaussian distribution N(xₖ|mₖ, Pₖ)\n\n Pₖ = (Pₖ+(Pₖ)') / 2\n\n μstate[k], Σstate[k] = mₖ, Pₖ\n\n # next state\n\n mₖ₋₁, Pₖ₋₁ = mₖ, Pₖ\n\n end\n\n return μstate, Σstate\n\nend\n\n\nfunction testfiltering() # Works ✅\n\n yclean, y, x, A, H, Q, R, m₀, P₀ = simulatedata()\n\n μ, Σ = filteringrecursion(y; A = A, H = H, Q = Q, R = R, m₀ = m₀, P₀ = P₀)\n\n figure()\n\n subplot(211)\n plot([yᵢ[1] for yᵢ in yclean], label = \"simulated 1 clean\")\n plot([yᵢ[1] for yᵢ in y], label = \"simulated 1\")\n plot([(H*m)[1] for m in μ], label = \"mean 1\")\n legend()\n \n subplot(212)\n plot([yᵢ[2] for yᵢ in y], label = \"simulated 2\")\n plot([(H*m)[2] for m in μ], label = \"mean 2\")\n\n legend()\n\nend\n", "meta": {"hexsha": "1f025600799ae46a30db73dcbc4ccd4defdf82ca", "size": 1477, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/filteringrecursion.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/filteringrecursion.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/filteringrecursion.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.6933333333, "max_line_length": 87, "alphanum_fraction": 0.4759647935, "num_tokens": 618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214532237354, "lm_q2_score": 0.8723473663814338, "lm_q1q2_score": 0.8412232800648426}} {"text": "# Julia code to compute the correlation coefficient\nusing Distributions\nusing Plots\n\nx = rand(MvNormal([0, 0], [3 1; 1 1]), 1000)\n# x = rand(MvNormal([0, 0], [3 0; 0 3]), 1000)\n# x = rand(MvNormal([0, 0], [3 2.9; 2.9 3]), 1000)\nscatter(x[1, :], x[2, :])\n\nσ₁ = std(x[1, :])\nσ₂ = std(x[2, :])\nμ₁ = mean(x[1, :])\nμ₂ = mean(x[2, :])\nExy = mean(x[1, :] .* x[2, :])\nρ = (Exy - μ₁ * μ₂) / (σ₁ * σ₂)\n\n####################################################################\n\n# Julia code to compute a mean vector.\nusing Statistics\n\nX = randn(100, 2)\nmean(X, dims=1)\n\n####################################################################\n\n# Julia code to compute covariance matrix.\nusing Statistics\n\nX = randn(100, 2)\ncov(X)\n\n####################################################################\n\n# Julia code: Overlay random numbers with the Gaussian contour.\nusing Distributions\nusing Plots\n\np = MvNormal([0, 0], [0.25 0.3; 0.3 1])\n\nX = rand(p, 1000)\nx₁ = -2.5:0.01:2.5\nx₂ = -3.5:0.01:3.5\n\nf(x₁, x₂) = pdf(p, [x₁, x₂])\n\nscatter(X[1, :], X[2, :], legend=false)\ncontour!(x₁, x₂, f, linewidth=2)\n\n####################################################################\n\n# Julia code: Gaussian(0,1) --> Gaussian(mu,sigma)\nusing Distributions\n\nx = rand(MvNormal([0, 0], [1 0; 0 1]), 1000)\nΣ = [3 -0.5; -0.5 1]\nμ = [1, -2]\ny = Σ^(1/2) * x .+ μ\n\n####################################################################\n\n# Julia code: Gaussian(mu,sigma) --> Gaussian(0,1)\nusing Distributions\n\ny = rand(MvNormal([1, -2], [3 -0.5; -0.5 1]), 100)\nμ = mean(y, dims=2)\nΣ = cov(y')\nx = Σ^(-1/2) * (y .- μ)\n\n####################################################################\n\n# Julia code to perform the principal component analysis\nusing LinearAlgebra\nusing Distributions\n\nx = rand(MvNormal([0, 0], [2 -1.9; -1.9 2]), 1000)\nΣ = cov(x')\nS, U = eigen(Σ)\nU[:, 1]\nU[:, 2]\n", "meta": {"hexsha": "c7d22a5aa652c683c1dad4df27570f2c074807bb", "size": 1836, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Ch05.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": "Ch05.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": "Ch05.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": 22.6666666667, "max_line_length": 68, "alphanum_fraction": 0.4520697168, "num_tokens": 636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545348152283, "lm_q2_score": 0.8872045892435128, "lm_q1q2_score": 0.8412070546001185}} {"text": "_primes = [2, 3]\n\nfunction is_prime(n, known_primes)\n for prime in known_primes\n if n == prime || prime > n\n return true\n end\n if n % prime == 0\n return false\n end\n end\n return true\nend\n\n\n\nfunction next_prime(n)\n inx = findfirst(x -> x > n, _primes)\n if inx == 0\n # Compute prime\n x = n + 1\n while !is_prime(x, _primes)\n x+=1\n end\n push!(_primes, x)\n return x\n end\n return _primes[inx]\nend\n\nfunction find_highest_prime_factor(n)\n\n current_prime = 2\n while (n % current_prime) != 0\n current_prime = next_prime(current_prime)\n end\n\n if is_prime(n, _primes)\n return n\n end\n return find_highest_prime_factor(n / current_prime)\nend\n@assert is_prime(2, _primes) == true\n@assert is_prime(6, _primes) == false\n@assert next_prime(2) == 3\n@assert next_prime(3) == 5\n@assert find_highest_prime_factor(6) == 3\n@assert find_highest_prime_factor(11) == 11\n@assert find_highest_prime_factor(15) == 5\n@assert find_highest_prime_factor(21) == 7\n@assert find_highest_prime_factor(26) == 13\nprintln(find_highest_prime_factor(13195))\n@assert find_highest_prime_factor(13195) == 29\nprintln(find_highest_prime_factor(600851475143))\n", "meta": {"hexsha": "2cbece96100ec61a082dff56267c43aaf011ef94", "size": 1266, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "3.jl", "max_stars_repo_name": "ddugue/project-euler", "max_stars_repo_head_hexsha": "ab373d896ac5051bb53a706cccfdfa3987ca9272", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "3.jl", "max_issues_repo_name": "ddugue/project-euler", "max_issues_repo_head_hexsha": "ab373d896ac5051bb53a706cccfdfa3987ca9272", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3.jl", "max_forks_repo_name": "ddugue/project-euler", "max_forks_repo_head_hexsha": "ab373d896ac5051bb53a706cccfdfa3987ca9272", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0181818182, "max_line_length": 55, "alphanum_fraction": 0.6453396524, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.953275045356249, "lm_q2_score": 0.8824278741843884, "lm_q1q2_score": 0.8411964717867412}} {"text": "using Distributions, LinearAlgebra\n\nfunction rowenhorst(mean, uncond_sd, rho, num_states)\n \"\"\"\n Rowenhort's method to approximate AR(1) process with Markov chain (ln y_t = mu + rho y_{t-1} + e_t)\n Note: this function also normalizes effective labour to one.\n \n #### Fields\n \n - 'mean': unconditional mean of income process\n - 'uncond_sd': unconditional standard deviation\n - 'rho': autocorrelation coefficient\n - 'num_states': number of states we want discretized\n \n #### Returns\n \n - 'transition_matrix': num_states x num_states array where\n transition_matrx[i,j] is prob. of going from i to j\n - 'ygrid': vector of income state space of length num_states\n \n \"\"\"\n \n # construct grids\n step_r = uncond_sd*sqrt(num_states-1)\n ygrid = -1:2/(num_states-1):1\n ygrid = mean .+ step_r*ygrid\n \n # initialize transition probabilities \n p = (rho+1)/2\n q = p\n \n transition_matrix = [p 1-p; 1-q q]\n \n # rowenhort's method\n for i = 2:num_states-1\n a1 = [transition_matrix zeros(i, 1); zeros(1, i+1)] \n a2 = [zeros(i,1) transition_matrix; zeros(1, i+1)]\n a3 = [zeros(1, i+1); transition_matrix zeros(i,1)]\n a4 = [zeros(1, i+1); zeros(i,1) transition_matrix]\n \n transition_matrix = p*a1 + (1-p)*a2 + (1-q)*a3 + q*a4\n transition_matrix[2:i, :] = transition_matrix[2:i, :]/2\n end\n \n for i = 1:num_states\n transition_matrix[i,:] = transition_matrix[i,:]/sum(transition_matrix[i,:])\n end\n \n # get stationary distribution to normalize effective labour to L=1\n pi = eigvecs(transition_matrix')[:,num_states]\n \n # normalize pi\n pi = pi./sum(pi)\n \n # exponentiate\n ygrid = exp.(ygrid)\n \n # normalize effective labour\n ygrid = ygrid/sum(pi.*ygrid)\n \n return transition_matrix, ygrid\nend\n\n\nfunction tauchen(mean, sd, rho, num_states; q=3)\n\n \"\"\"\n Tauchen's method to approximate AR(1) process with Markov Chain\n \n ##### Fields\n \n - 'num_states': Number of points in markov process\n - 'sd' : Standard deviation of innovation\n - 'rho' : Autocorrelation coefficient\n - 'mean': Unconditional mean\n - 'q' : The number of standard deviations to each side of the process\n \n ##### Returns\n \n - 'transition_matrix': num_states x num_states array where\n transition_matrx[i,j] is prob. of going from i to j\n - 'ygrid': vector of income state space of length num_states\n \n \"\"\"\n \n\n uncond_sd = sd/sqrt(1-rho^2)\n y = range(-q*uncond_sd, stop = q*uncond_sd, length = num_states)\n d = y[2]-y[1]\n\n Pi = zeros(num_states,num_states)\n\n for row = 1:num_states\n # end points\n Pi[row,1] = cdf(Normal(),(y[1] - rho*y[row] + d/2)/sd)\n Pi[row,num_states] = 1 - cdf(Normal(), (y[num_states] - rho*y[row] - d/2)/sd)\n\n # middle columns\n for col = 2:num_states-1\n Pi[row, col] = (cdf(Normal(),(y[col] - rho*y[row] + d/2) / sd) -\n cdf(Normal(),(y[col] - rho*y[row] - d/2) / sd))\n end\n end\n\n yy = y .+ mean # center process around its mean\n\n Pi = Pi./sum(Pi, dims = 2) # renormalize\n\n return Pi, yy\nend \n", "meta": {"hexsha": "245e4834350be00c5b65617b9e9882f792d0665d", "size": 3253, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "rowenhorst_tauchen.jl", "max_stars_repo_name": "yangycpku/RA_HetAgents", "max_stars_repo_head_hexsha": "a550286c8ea508c4a06d509a036998e7f6c731eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-09-09T21:33:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T22:47:10.000Z", "max_issues_repo_path": "rowenhorst_tauchen.jl", "max_issues_repo_name": "yangycpku/RA_HetAgents", "max_issues_repo_head_hexsha": "a550286c8ea508c4a06d509a036998e7f6c731eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rowenhorst_tauchen.jl", "max_forks_repo_name": "yangycpku/RA_HetAgents", "max_forks_repo_head_hexsha": "a550286c8ea508c4a06d509a036998e7f6c731eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-09-08T19:12:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-27T07:46:02.000Z", "avg_line_length": 29.3063063063, "max_line_length": 103, "alphanum_fraction": 0.5939133108, "num_tokens": 940, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750440288019, "lm_q2_score": 0.88242786954645, "lm_q1q2_score": 0.841196466194134}} {"text": "\"\"\"\n`cmean(x)`\n\nCompute circular mean of an array.\n\n**Arguments**\n- `x`: Array of angles in radians.\n\n**Returns**\n- `m`: Circular mean of `x`.\n\"\"\"\nfunction cmean(x)\n S = mean(sin.(x))\n C = mean(cos.(x))\n m = atan(S, C)\n return m\nend\n\n\n\"\"\"\n`cstd(x)`\n\nCompute circular standard deviation of an array.\n\n**Arguments**\n- `x`: Array of angles in radians.\n\n**Returns**\n- `sd`: Circular standard deviation of `x`.\n\"\"\"\nfunction cstd(x)\n S = mean(sin.(x))\n C = mean(cos.(x))\n R = sqrt(S^2 + C^2)\n x = -2*log(R)\n if x < 0\n @warn \"Negative value $x set to 0!\"\n x = 0\n end\n sd = sqrt(x)\n return sd\nend\n", "meta": {"hexsha": "324490e1b75952d0de868e03df27107b3c8a9efa", "size": 639, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MiscFunctions/circular_statistics.jl", "max_stars_repo_name": "vkumpost/stoosc", "max_stars_repo_head_hexsha": "2a1fd4dc3adf9e6066877aa4134530f9d79a16cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MiscFunctions/circular_statistics.jl", "max_issues_repo_name": "vkumpost/stoosc", "max_issues_repo_head_hexsha": "2a1fd4dc3adf9e6066877aa4134530f9d79a16cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MiscFunctions/circular_statistics.jl", "max_forks_repo_name": "vkumpost/stoosc", "max_forks_repo_head_hexsha": "2a1fd4dc3adf9e6066877aa4134530f9d79a16cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.8604651163, "max_line_length": 48, "alphanum_fraction": 0.5477308294, "num_tokens": 201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750427013549, "lm_q2_score": 0.8824278695464501, "lm_q1q2_score": 0.8411964650227579}} {"text": "using Distributions\r\nusing Statistics\r\nusing CSV\r\nusing StringEncodings\r\nusing Printf\r\n\r\n#MathKurtosis - kurtosis (from Distributions)\r\n#MathSkewness - skewness (from Distributions)\r\n#Normal Distribution = \r\n# MathCumulativeDistributionNormal - cdf (nd,x)\r\n\r\n\r\n\"\"\" \r\n returns a series of returns given a serie of prices\r\n\"\"\" \r\nfunction calcReturnsFromPrice(prices::Array{Float64}) \r\n ret=1;\r\n s=size(prices)[1]\r\n rreturns=Array{Float64,1}()\r\n for i=1:(s-1) \r\n push!(rreturns,prices[i+1]/prices[i]-1)\r\n end\r\n return rreturns;\r\nend\r\n\r\n\r\n\"\"\" \r\n returns a series of prices given a serie of returns\r\n\"\"\" \r\nfunction calcPricesFromReturns(rreturns::Array{Float64}) \r\n ret=1;\r\n s=size(rreturns)[1]\r\n equities=Array{Float64,1}()\r\n push!(equities,1000000)\r\n for i=1:s \r\n push!(equities,(rreturns[i]+1)*equities[i])\r\n end\r\n return equities;\r\nend\r\n\r\n\"\"\" \r\nreturns the Total return of a series of returns given of the n first returns\r\n\r\n\"\"\" \r\nfunction calcTotalReturn(returns::Array{Float64}) \r\n ret=1;\r\n s=size(returns)[1]\r\n for i=1:s \r\n ret*=(1+returns[i])\r\n end\r\n return ret-1;\r\nend\r\n\r\n\"\"\" \r\nreturns the arithmetic average return of the series of returns given of the n first returns\r\n\r\n\"\"\" \r\nfunction calcAvgReturn(returns::Array{Float64}) \r\n sum=Float64(0)\r\n s=size(returns)[1]\r\n for i=1:s \r\n sum+=returns[i]\r\n end\r\n return sum/s;\r\nend\r\n\r\nfunction calcAnnualReturn(returns::Array{Float64}, numberOfDays) \r\n gReturn=calcTotalReturn(returns);\r\n return (1+gReturn)^(252.0/numberOfDays)-1;\r\nend\r\n\r\n\r\n\r\nfunction calcAnnualSR(returns::Array{Float64}, riskfree, numberOfDays) \r\n return sqrt(252)*calcSR(returns,riskfree)\r\nend\r\n\r\n\"\"\" \r\n returns the sample standard deviation\r\n\"\"\" \r\nfunction calcDesvPad(x::Array{Float64}) \r\n avg=calcAvgReturn(x);\r\n n=size(x)[1];\r\n s=0;\r\n for i=1:n\r\n s+= (x[i]-avg)^2;\r\n end\r\n s=s/n;\r\n return sqrt(s);\r\nend\r\n\r\n\r\nfunction calcSR(returns::Array{Float64}, riskfree) \r\n avg=calcAvgReturn(returns);\r\n sigma=calcDesvPad(returns);\r\n\r\n if(sigma!=0)\r\n return (avg-riskfree)/sigma;\r\n end\r\n return -1;\r\nend\r\n\r\n\r\n\"\"\" \r\n returns Prob that SR is greater than Threshold\r\n\"\"\" \r\nfunction ProbSRgreaterThreshold(returns::Array{Float64},threshold) \r\n n=size(returns)[1];\r\n sre=calcSR(returns,0);\r\n return Z( (sre-threshold)*sqrt(n-1)/\r\n sqrt(1 - skewness(returns)*sre + (kurtosis(returns)-1)*sre*sre/4) \r\n );\r\nend\r\n\r\n\r\n\"\"\" \r\n returns the mininum Track Record(minTRL) lenght (in years) to have returns above threshold wiht level of conficence (alpha)\r\n\"\"\" \r\nfunction minTRL(returns::Array{Float64}, threshold, alpha) \r\n sre=calcSR(returns,0);\r\n minT= 1.0+ ( 1.0 -skewness(returns)*sre\r\n + (kurtosis(returns)-1)*sre*sre/4.0)*\r\n (Z(alpha)/(sre-threshold))^2.0 ;\r\n return minT/252 \r\nend\r\n\r\nfunction Z( x) \r\n nd=Normal(0,1)\r\n return cdf(nd,x)\r\nend\r\n\r\n\r\n\r\n\"\"\"\r\n Print Strategy performance STSE report. It is calculated from a equity time series (equities parameter) observed in a given number of days (numberOfDays parameters). \r\n Equity series should be an array of float64, from oldest to newest equity value marked to market.\r\n You should provide at least 30 data points and the number of days can not be smaller than the number of points.\r\n You may define a desired threshold. The results for zero threshold is always presentes. The default value for threshold is 0.1.\r\n You may also define a risk free return rate for Sharpe ratio calculation.\r\n\"\"\"\r\n\r\nfunction analyzeEquitySeries(equities::Array{Float64},numberOfDays,threshold=0.1,risk_free_rate=0.0)\r\n n=size(equities)[1]\r\n if n<30 || numberOfDays>n\r\n println(\"ERROR!!\")\r\n println(\" You should provide at least 30 data points and the number of days can not be bigger than the number of points\")\r\n println(\" \",n,\" points where provided!!\")\r\n return\r\n end\r\n\r\n rreturns=calcReturnsFromPrice(equities);\r\n rreturns=convert(Array{Float64},rreturns);\r\n rreturns=convert(Array{Float64},rreturns);\r\n\r\n @printf(\"calcTotalReturn() (%%)=%.2f\\n\", calcTotalReturn(rreturns)*100);\r\n @printf(\"calcAnnualReturn (%%)=%.2f\\n\",calcAnnualReturn(rreturns,numberOfDays)*100)\r\n @printf(\"calcDevPad=%.2f\\n\",calcDesvPad(rreturns))\r\n @printf(\"calcSR=%.2f\\n\",calcSR(rreturns,risk_free_rate))\r\n @printf(\"calcAnnualSR=%.2f\\n\",calcAnnualSR(rreturns,risk_free_rate,numberOfDays ))\r\n @printf(\"ProbSRgreaterThreshold(0)=%.3f\\n\",ProbSRgreaterThreshold(rreturns,0))\r\n @printf(\"minTRL(0)=%.1f\\n\",minTRL(rreturns,0,0.95))\r\n @printf(\"ProbSRgreaterThreshold(%.2f)=%.3f\\n\",threshold,ProbSRgreaterThreshold(rreturns,0.05))\r\n @printf(\"minTRL(%.2f)=%.1f\\n\",threshold,minTRL(rreturns,0.05,0.95))\r\n\r\nend\r\n\r\n\"\"\"\r\nPrint Strategy performance STSE report.\r\n\r\nParameters:\r\nfileName \r\nnumberOfDays \r\ndelim='\\t' \r\n\r\nGiven a equity file with the following format (UTF16 codification): \r\n\r\n\t\t\t\r\n2019.10.01 00:00\t100000.00\t100000.00\t0.0000\r\n2019.10.03 17:59\t99962.79\t100009.43\t0.0022\r\n\r\nThis kind of files are generated by Metatrader5\r\n\r\nNote: The deposit load value shows the percent of account funds used to open positions. Load calculation formula:\r\n\r\nLoad = Margin / Equity * 100%\r\nhttps://www.mql5.com/en/articles/2704#load\r\n\r\n\"\"\"\r\nfunction processEquityFileUtf16(fileName,numberOfDays,delim='\\t')\r\n s=read(fileName,String,enc\"UTF-16\");\r\n print(\"delim=\",delim)\r\n path = tempname();\r\n f = open(path, enc\"UTF-8\", \"w\");\r\n write(f, s);\r\n close(f); # Essential to complete encoding\r\n\r\n cv=CSV.read(path;delim=delim,types=Dict(1=>String,2=>String),normalizenames=true,dateformat=\"yyyy.mm.dd hh:ss\")\r\n \r\n equities=convert(Array{Float64},cv[!,3])\r\n \r\n analyzeEquitySeries(equities,numberOfDays)\r\n return cv;\r\n end\r\n \r\n\r\n\r\n\"\"\"\r\nPrint Strategy performance STSE report.\r\nParameters:fileName,numberOfDays,delim[opcional]\\n\r\n\r\nfileName - \r\nnumberOfDays - \r\ndelim=',' \r\n\r\nO arquivo apontado em fileName deve estar no formato abaixo:\r\n\r\n,\t\t\t\r\n2019.10.01 00:00,\t100000.00,\t100000.00,\t0.0000\r\n2019.10.03 17:59,\t99962.79,\t100009.43,\t0.0022\r\n\r\ne CODIFICAÇÃO UTF-8 (arquivos gravados pelo Metatrader5 geralmente são UTF16 enquanto gravado pelo python em geral são UTF-8)\r\n\r\nObservacao: The deposit load value shows the percent of account funds used to open positions. Load calculation formula:\r\n\r\nLoad = Margin / Equity * 100%\r\nhttps://www.mql5.com/en/articles/2704#load\r\n\r\n\"\"\"\r\nfunction processEquityFileUtf8(fileName,numberOfDays,delim=',')\r\n \"\"\" s=read(fileName,String,enc\"UTF-16\");\r\n print(\"delim=\",delim)\r\n path = tempname();\r\n f = open(path, enc\"UTF-8\", \"w\");\r\n write(f, s);\r\n close(f); # Essential to complete encoding\r\n \"\"\"\r\n cv=CSV.read(fileName;delim=delim,types=Dict(1=>String,2=>String),normalizenames=true,dateformat=\"yyyy.mm.dd hh:ss\")\r\n\r\n # print(head(cv))\r\n equities=convert(Array{Float64},cv[!,3])\r\n\r\n analyzeEquitySeries(equities,numberOfDays)\r\n return cv;\r\nend\r\n\r\n\r\n\r\n\"\"\"\r\nPrint Strategy performance STSE report.\r\nParameters:fileName,numberOfDays,delim[opcional]\\n\r\n\r\nfileName - \r\nnumberOfDays - \r\ndelim=',' \r\n\r\nThe file must be in csv format with the following columns ( UTF-8 codification):\r\n\trow_number,date,balance,equity,load,orders\r\n\r\n These file may created by analyze_TestReport.py, using as raw data the XLS file Report created by StrategyTester in MetatTrader5 platform (StrategyTester | tab Backtest | Report (Open XML (MS office Excel)))\r\n\r\nNote: The deposit load value shows the percent of account funds used to open positions. Load calculation formula:\r\n\r\nLoad = Margin / Equity * 100%\r\nhttps://www.mql5.com/en/articles/2704#load\r\n\r\n\"\"\"\r\nfunction processEquityFilePy(fileName,numberOfDays,delim=',')\r\n \"\"\" s=read(fileName,String,enc\"UTF-16\");\r\n print(\"delim=\",delim)\r\n path = tempname();\r\n f = open(path, enc\"UTF-8\", \"w\");\r\n write(f, s);\r\n close(f); # Essential to complete encoding\r\n \"\"\"\r\n cv=CSV.read(fileName;delim=delim,types=Dict(1=>String,2=>String),normalizenames=true,dateformat=\"yyyy.mm.dd hh:ss\");\r\n\r\n # print(head(cv))\r\n equities=convert(Array{Float64},cv[!,4])\r\n\r\n analyzeEquitySeries(equities,numberOfDays);\r\n return cv;\r\nend\r\n\r\n\r\n\r\n\"\"\"\r\nAnalisa desempenho de trader usando arquivo com formato abaixo.\r\nParameters:fileName,numberOfDays,delim[opcional]\\n\r\n\r\nfileName - \r\nnumberOfDays - \r\ndelim=',' \r\n\r\nThe file must be in csv format with the following columns ( UTF-8 codification):\r\n\trow_number,date,balance,equity,load,orders\r\n\r\nO arquivo apontado em fileName deve estar no formato abaixo:\r\n\r\n \"counter\",\"date-hour\",\"tickReturn\",\"asset Return\",\"currentBalance\"\r\n\"\"\"\r\nfunction processFileRF(fileName, numberOfDays,delim=',')\r\n\r\n cv=CSV.read(fileName;delim=delim,types=Dict(1=>String,2=>String),normalizenames=true,dateformat=\"yyyy-mm-dd hh:mm:ss\")\r\n\r\n rreturns=convert(Array{Float64},cv[!,3])\r\n rreturns=rreturns.-1 # em formato RF o arquivo usa 1.0 para retorno zero!!!\r\n equities=calcPricesFromReturns(rreturns)\r\n println(\" ---equities--- \")\r\n print(equities)\r\n println(\" ---equities end--- \")\r\n #equities=convert(Array{Float64},cv[!,3])\r\n analyzeEquitySeries(equities,numberOfDays)\r\nend\r\n\r\n\r\n\r\n\r\n\r\n\r\n\"\"\"\r\nAnalisa desempenho de trader\r\nParâmetros:fileName,numberOfDays,delim[opcional]\\n\r\n\r\nfileName - string com nome do arquivo\r\nnumberOfDays - numero de dias de operação equivalente ao periodo observado\r\ndelim=';' - caracter delimitador, por default ;\r\n\r\nO arquivo apontado em fileName deve estar no formato abaixo:\r\n\r\n \"counter\",\"date-hour\",\"tickReturn\",\"asset Return\",\"currentBalance\"\r\n\"\"\"\r\nfunction processFile(fileName,numberOfDays,delim=';')\r\nprocessFile(fileName,\"\",numberOfDays,delim);\r\nend\r\n\r\nfunction processFile(fileName,fileName2, numberOfDays,delim)\r\n\r\n\r\n # FileWrite(fileHandle,cont,datahora,StringFormat(\"%.8f\", tickReturn),StringFormat(\"%.8f\", assetReturn),StringFormat(\"%.8f\",currentBalance));\r\n\r\n s=read(fileName,String,enc\"UTF-16\");\r\n #e=encode(s,\"UTF-8\");\r\n #d=decode(e,\"UTF-8\");\r\n\r\n path = tempname();\r\n f = open(path, enc\"UTF-8\", \"w\");\r\n write(f, s);\r\n\r\n close(f); # Essential to complete encoding\r\n\r\nif fileName2!=\"\"\r\n s2=read(fileName,String,enc\"UTF-16\");\r\n \r\n f = open(path, enc\"UTF-8\", \"w\");\r\n write(f, s2);\r\n \r\n close(f); # Essential to complete encoding\r\nend\r\n\r\n\r\n cv=CSV.read(path;delim=delim,types=Dict(1=>String,2=>String),normalizenames=true,dateformat=\"yyyy.mm.dd hh:ss\")\r\n\r\n rreturns=convert(Array{Float64},cv[!,3])\r\n equities=calcPricesFromReturns(rreturns)\r\n #equities=convert(Array{Float64},cv[!,3])\r\n analyzeEquitySeries(equities,numberOfDays)\r\nend\r\n\r\n", "meta": {"hexsha": "db8ba40083f576d1ddd3cca19a9b2fd94b09f6ac", "size": 10678, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "STSE.jl", "max_stars_repo_name": "paulo-al-castro/stse", "max_stars_repo_head_hexsha": "70bdf5b0d0250d233d986a0712729e1e9486da91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "STSE.jl", "max_issues_repo_name": "paulo-al-castro/stse", "max_issues_repo_head_hexsha": "70bdf5b0d0250d233d986a0712729e1e9486da91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "STSE.jl", "max_forks_repo_name": "paulo-al-castro/stse", "max_forks_repo_head_hexsha": "70bdf5b0d0250d233d986a0712729e1e9486da91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9376693767, "max_line_length": 209, "alphanum_fraction": 0.6851470313, "num_tokens": 3000, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611654370414, "lm_q2_score": 0.8757869803008765, "lm_q1q2_score": 0.841071805076337}} {"text": "\"\"\"\n zero_one_pack!(capacity::N, weights::V, values::V, dp::V) where {N <: Number,V <: AbstractVector}\nThis does 0-1 (each item can be chosen only once) knapsack :\npack capacity = capacity\nweight of each item = weights\nvalue of each item = values\ndp array is what the function works on\nIt returns the ans (dp[capacity])\n```\njulia> dp=zeros(Int,30)\njulia> zero_one_pack!(20,[1,3,11],[2,5,30],dp)\n37\n```\n\"\"\"\nfunction dp_zero_one_pack!(capacity::N, weights::V, values::V, dp::V\n) where {N <: Number,V <: AbstractVector}\n for i in 1:length(weights)\n j = capacity\n while j > weights[i] # reversed loop\n dp[j] = max(dp[j], dp[j - weights[i]] + values[i])\n j -= 1\n end\n dp[weights[i]] = max(dp[weights[i]], values[i]) # dp[j]=max(dp[j],dp[0]+values[i])\n end\n return dp[capacity]\nend\n\n\"\"\"\nThis does complete/infinite (each item can be chosen infinite times) knapsack :\npack capacity = capacity\nweight of each item = weights\nvalue of each item = values\ndp array is what the function works on\nIt returns the ans (dp[capacity])\n```\njulia> dp=zeros(Int,30)\njulia> complete_pack!(20,[1,2,9],[1,3,20],dp)\n43\n```\n\"\"\"\nfunction dp_complete_pack!(capacity::N, weights::V, values::V, dp::V\n) where {N <: Number,V <: AbstractVector}\n for i in 1:length(weights)\n dp[weights[i]] = max(dp[weights[i]], values[i]) # dp[j]=max(dp[j],dp[0]+values[i])\n for j in weights[i] + 1:capacity\n dp[j] = max(dp[j], dp[j - weights[i]] + values[i])\n end\n end\n return dp[capacity]\nend\n", "meta": {"hexsha": "e4bd134a52ac6a4f33c06d8cee809a2dd7b40017", "size": 1549, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/knapsack/dynamic_programming.jl", "max_stars_repo_name": "Kai161998/Julia", "max_stars_repo_head_hexsha": "65e8fbb8371f9db51ddb8092c6f9864660eb93cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/knapsack/dynamic_programming.jl", "max_issues_repo_name": "Kai161998/Julia", "max_issues_repo_head_hexsha": "65e8fbb8371f9db51ddb8092c6f9864660eb93cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/knapsack/dynamic_programming.jl", "max_forks_repo_name": "Kai161998/Julia", "max_forks_repo_head_hexsha": "65e8fbb8371f9db51ddb8092c6f9864660eb93cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-26T11:15:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-26T11:15:24.000Z", "avg_line_length": 30.3725490196, "max_line_length": 101, "alphanum_fraction": 0.6268560362, "num_tokens": 467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9719924818279465, "lm_q2_score": 0.8652240860523328, "lm_q1q2_score": 0.8409913067393238}} {"text": "using Distributions, HypothesisTests\n\np = [0.08, 0.12, 0.2, 0.2, 0.15, 0.25]\nO = [3, 2, 9, 11, 8, 27]\nM = length(O)\nn = sum(O)\nE = n*p\n\ntestStatistic = sum((O-E).^2 ./E)\npVal = ccdf(Chisq(M-1), testStatistic)\n\nprintln(\"Manually calculated test statistic: \", testStatistic)\nprintln(\"Manually calculated p-value: \", pVal,\"\\n\")\n\nprintln(ChisqTest(O,p))", "meta": {"hexsha": "c5f82298b896d64024680930f26d90fd3a41efee", "size": 349, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "7_chapter/chiSqTest.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/chiSqTest.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/chiSqTest.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 23.2666666667, "max_line_length": 62, "alphanum_fraction": 0.6532951289, "num_tokens": 139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075701109193, "lm_q2_score": 0.874077222043951, "lm_q1q2_score": 0.8409563121900081}} {"text": "\"\"\"\n pythagorean_triplets(n)\n\nFind all positive integer triplets `(a, b, c)` s.t. `a + b + c = n` and `a < b < c` and `a^2 + b^2 == c^2`.\n\"\"\"\n# cmcaine's answer, with thanks to akshu3398.\nfunction pythagorean_triplets(n)\n triplets = NTuple{3, Int}[]\n # Lower bound because the smallest triple is 3, 4, 5.\n # Upper bound implied by a < b < c && a + b + c == n.\n for a in 3:cld(n, 3) - 1\n # Derived by eliminating c from these simultaneous\n # equations and solving for b:\n # a^2 + b^2 = c^2\n # a + b + c = n\n b = (n^2 - 2n * a) / (2 * (n - a))\n if a < b && isinteger(b)\n c = n - a - b\n # Proof that b < c:\n # Let b = c. Then a^2 + b^2 = c^2 ≡ a^2 = 0 but we know that a ≠ 0.\n # Let b > c. a^2 + b^2 = c^2 ≡ a^2 = c^2 - b^2.\n # If b > c, a^2 < 0, but that is impossible for real numbers.\n push!(triplets, (a, b, c))\n end\n end\n return sort!(triplets)\nend\n", "meta": {"hexsha": "30a85fe5b302f1df9597b8b3b273fbd8a616bc9f", "size": 998, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "exercises/pythagorean-triplet/example.jl", "max_stars_repo_name": "tomerarnon/julia-1", "max_stars_repo_head_hexsha": "6313e702d82f4fee10efdf29e943df50857cd7b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 42, "max_stars_repo_stars_event_min_datetime": "2017-06-27T01:08:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:34:10.000Z", "max_issues_repo_path": "exercises/pythagorean-triplet/example.jl", "max_issues_repo_name": "tomerarnon/julia-1", "max_issues_repo_head_hexsha": "6313e702d82f4fee10efdf29e943df50857cd7b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 269, "max_issues_repo_issues_event_min_datetime": "2017-06-19T13:56:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T22:15:18.000Z", "max_forks_repo_path": "exercises/pythagorean-triplet/example.jl", "max_forks_repo_name": "tomerarnon/julia-1", "max_forks_repo_head_hexsha": "6313e702d82f4fee10efdf29e943df50857cd7b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 69, "max_forks_repo_forks_event_min_datetime": "2017-06-20T18:47:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T22:15:52.000Z", "avg_line_length": 35.6428571429, "max_line_length": 107, "alphanum_fraction": 0.4809619238, "num_tokens": 361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992951349231, "lm_q2_score": 0.8688267626522814, "lm_q1q2_score": 0.8409368111655003}} {"text": "function dare(A,B,Q,R,S=0)\n\t# \n\t# solves discrete-time algebraic Riccati equation\n\t# X = A'XA - (A'XB+S)(R+B'XB)^{-1}(B'XA+S') + Q\n\t#\n\t# R^{-1} is not computed\n\t#\n\t# javier.cara@upm.es, 2016-02 \n\t# \n\t\n\t# Dimensions\n\tn,m = size(B)\n\t\n\tif S== 0\n\t\tS = zeros(n,m)\n\tend\n\n\tL = [A zeros(n,n) B;Q -eye(n) S;S' zeros(m,n) R]\n\tM = [eye(n) zeros(n,n) zeros(n,m); zeros(n,n) -A' zeros(n,m);zeros(m,n) -B' zeros(m,m)]\n\n\t# Compute the eigenvalue decomposition\n\t(d,v) = eig(L,M)\n\t\n\t# Sort the eigenvalues\n\tew = abs(d)\n\tpos = sortperm(ew)\n\n\t# Compute X\n\tv1 = v[1:n,pos[1:n]]\n\tv2 = v[n+1:2*n,pos[1:n]]\n\tX = real(v2/v1)\n\t\n\treturn X\n\nend\n\n######\nfunction dare_test()\n #=\n BibText\n @TECHREPORT{Benner95acollection,\n author = {Peter Benner and Alan J. Laub and Volker Mehrmann},\n title = {A Collection of Benchmark Examples for the Numerical Solution of\n Algebraic Riccati Equations II: Discrete-Time Case},\n institution = {FAK. F. MATHEMATIK, TU CHEMNITZ--ZWICKAU},\n year = {1995}\n }\n \n nov-2016\n =#\n\n\t# ------------------------------------------------------------------\n\t# ejm1 collection of benchmark examples\n\tA1 = [4 3;-4.5 -3.5]\n\tB1 = [1 -1]'\n\tR1 = 1\n\tQ1 = [9 6;6 4]\n\tX1 = (1+sqrt(5))/2*[9 6;6 4]\n\n\tX11 = dare(A1,B1,Q1,R1)\n \n\t# --------------------------------------------------------------------\n\t# ejm computed with mathematica\n\tAm = [1 -1 1;0 1 1;0 0 1]\n\tBm = [1 0;1 0;0 1]\n\tRm = [10 0;0 0.1]\n\tQm = [10 0 0;0 1 0;0 0 0.1]\n\tXm = [42.2835 -68.5247 -3.94783;-68.5247 154.043 16.0017;-3.94783 16.0017 8.33197]\n \n\tXmm = dare(Am,Bm,Qm,Rm)\n \n\t#####\n \n\treturn X1,X11,Xm,Xmm\n \nend\n", "meta": {"hexsha": "37abc1dd697e596046ba74a620bf5eecb0fb0528", "size": 1610, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/auxfun/dare.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/dare.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/dare.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": 20.9090909091, "max_line_length": 88, "alphanum_fraction": 0.5236024845, "num_tokens": 634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951142225532629, "lm_q2_score": 0.8840392863287585, "lm_q1q2_score": 0.8408470942570123}} {"text": "using LinearAlgebra\nusing SparseArrays\nusing Plots\nusing ForwardDiff\n\n\"This routine solves Poisson's equation using piecewise linear finite element methods.\nThe matrix is assembled locally, and boundary nodes are not removed.\"\n\nm = 100 # number of elements\n\nα = 1.0\nβ = 0.0\nf(x) = x + 0*2*sin(2*pi*x)\nκ(x) = 1.0 + x\n\n# define spatial grid\nx = LinRange(-1,1,m+2) # x_0, x_1, ..., x_m, x_{m+1} = x_0\nxint = x[1:end-1]\nh = x[2]-x[1]\n\n# x = x + randn(size(x))/(2*m)\n# x = @. x + (1+x)*(1-x)/3\n\n# construct local FEM matrix\nmap_point(x,a,b) = a + (b-a) * (1+x)/2 # maps x ∈ [-1,1] to interval [a,b]\nA = spzeros(m+2,m+2)\nb = zeros(m+2)\nA_local = [1 -1;-1 1]\n\nfunction ϕ(r)\n ϕ1 = @. (1-r)/2\n ϕ2 = @. (1+r)/2\n return [ϕ1 ϕ2]\nend\nfunction dϕ(r)\n dϕ1 = @. -.5 + 0*r\n dϕ2 = @. .5 + 0*r\n return [dϕ1 dϕ2]\nend\n\nr = 0.0\nw = 2.0\n\n# r = [-1; 1] / sqrt(3)\n# w = ones(2)\nfor e = 1:m+1\n h_e = x[e+1] - x[e]\n ids = e:e+1\n\n # use 1-point quadrature to approximate integrals\n x_e = map_point(0, x[e], x[e+1])\n\n # accumulate local contributions\n A[ids,ids] += A_local * κ(x_e) / h_e\n b[ids] += h_e * w * f(x_e) * [.5;.5]\n\n # # use 2-point Gauss quadrature to approximate integrals\n # x_e = map_point.(r, x[e], x[e+1])\n #\n # # build and accumulate local contributions\n # A_local = dϕ(r)'*diagm(w_e.*κ.(x_e))*dϕ(r)\n # A[ids,ids] += A_local / h_e\n # b[ids] += h_e * (ϕ(r)' * (w.*f.(x_e)))\nend\n\n# modify for boundary conditions\nfunction impose_Dirichlet_BC!(A,b,i,val)\n b .-= A[:,i]*val\n b[i] = val\n A[i,:] .= 0\n A[:,i] .= 0\n A[i,i] = 1.0\nend\nfunction impose_Neumann_BC!(A,b,i,val)\n b[i] += val\nend\n\nimpose_Dirichlet_BC!(A,b,1,α)\nimpose_Dirichlet_BC!(A,b,m+2,β)\n# impose_Neumann_BC!(A,b,m+2,β)\n\nu = A\\b\nplot(x,u,legend=false,mark=:dot,ms=2)\n", "meta": {"hexsha": "e5e42772c2853c4634c61c85f0515356befd41d4", "size": 1792, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "week7/fem_laplace_1D_local.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": "week7/fem_laplace_1D_local.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": "week7/fem_laplace_1D_local.jl", "max_forks_repo_name": "jlchan/caam452_s21", "max_forks_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.3333333333, "max_line_length": 86, "alphanum_fraction": 0.5703125, "num_tokens": 754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240073565739, "lm_q2_score": 0.8962513738264114, "lm_q1q2_score": 0.8407949304128678}} {"text": "# # Trade-off curves\nusing Random\nRandom.seed!(1)\nm = 25;\nn = 10;\nA = randn(m, n);\nb = randn(m, 1);\n\n#-\n\nusing Convex, SCS, LinearAlgebra\n\n\ngammas = exp10.(range(-4, stop=2, length=100));\n\nx_values = zeros(n, length(gammas));\nx = Variable(n);\nfor i=1:length(gammas)\n cost = sumsquares(A*x - b) + gammas[i]*norm(x,1);\n problem = minimize(cost, [norm(x, Inf) <= 1]);\n solve!(problem, SCS.Optimizer(verbose=0));\n x_values[:,i] = evaluate(x);\nend\n\n#-\n\n# Plot the regularization path.\n\nusing Plots\nplot(title = \"Entries of x vs lambda\", xaxis=:log, xlabel=\"lambda\", ylabel=\"x\" )\nfor i = 1:n\n plot!(gammas, x_values[i,:], label=\"x$i\")\nend\nplot!()\n", "meta": {"hexsha": "24f26317654af9671ec421ed538980e0ce06d89c", "size": 656, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/examples_literate/general_examples/trade_off_curves.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/trade_off_curves.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/trade_off_curves.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": 18.7428571429, "max_line_length": 80, "alphanum_fraction": 0.6219512195, "num_tokens": 223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799451753696, "lm_q2_score": 0.8723473630627235, "lm_q1q2_score": 0.8407508937464699}} {"text": "\"\"\"\n\teuler_characteristic(V::Lar.Points, copEV::Lar.ChainOp,\tcopFE::Lar.ChainOp)\n\nReturn the Euler Characteristic number of a 2D- or 3D-model.\n`V` is given by rows.\n\"\"\"\nfunction euler_characteristic(\n\t\tV::Lar.Points, # by rows\n\t\tcopEV::Lar.ChainOp,\n\t\tcopFE::Lar.ChainOp)\n\n\t# χ = size(V,1) - size(copEV,1) + size(copFE,1)\n\t# return χ\n\treturn euler_characteristic_general(V, copEV, copFE)\nend\n\n\"\"\"\n\teuler_characteristic_general(V::Lar.Points, cc::Lar.ChainOp...)\n\nReturn the Euler Characteristic number of a n-dimensional model.\n`V` is given by rows.\n\"\"\"\nfunction euler_characteristic_general(V::Lar.Points, cc::Lar.ChainOp...)\n\tχ = size(V,1)\n\tfor k in 1:length(cc)\n\t\tχ = χ + (-1)^k * size(cc[k],1)\n\tend\n\treturn χ\nend\n", "meta": {"hexsha": "432f64de0c565cbcc51a51a62d41535e98497e86", "size": 716, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/topological_invariants.jl", "max_stars_repo_name": "petruz93/LinearAlgebraicRepresentation.jl", "max_stars_repo_head_hexsha": "d3facd81e331cdc2f8e37fc1e6641b01fa40c0ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/topological_invariants.jl", "max_issues_repo_name": "petruz93/LinearAlgebraicRepresentation.jl", "max_issues_repo_head_hexsha": "d3facd81e331cdc2f8e37fc1e6641b01fa40c0ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/topological_invariants.jl", "max_forks_repo_name": "petruz93/LinearAlgebraicRepresentation.jl", "max_forks_repo_head_hexsha": "d3facd81e331cdc2f8e37fc1e6641b01fa40c0ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8666666667, "max_line_length": 76, "alphanum_fraction": 0.6997206704, "num_tokens": 238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176863577751, "lm_q2_score": 0.8902942377652497, "lm_q1q2_score": 0.840595221074538}} {"text": "# In the 5 by 5 matrix below, the minimal path sum from the top left to the\n# bottom right, by only moving to the right and down, is indicated in bold red\n# and is equal to 2427.\n#\n# 131 673 234 103 18\n# 201 96 342 965 150\n# 630 803 746 422 111\n# 537 699 497 121 956\n# 805 732 524 37 331\n#\n# Find the minimal path sum from the top left to the bottom right by only moving\n# right and down in matrix.txt (right click and \"Save Link/Target As...\"), a 31K\n# text file containing an 80 by 80 matrix.\n\nusing ProjectEulerSolutions\n\n\n# Simple dynamic programming solution to fill in a matrix starting with the\n# corner and then picking the min path to each consecutive cell.\nfunction p081solution(path::String=\"\")::Integer\n\n if !isfile(path)\n if path != \"\"\n println(\"Cannot find path: '\", path, \"'\")\n end\n return -1\n end\n\n # Read in matrix from file\n matrix = reduce(hcat, [parse.(Int32, split(line, ',')) for line in eachline(path)])\n n, m = size(matrix)\n\n best_path = zeros(Integer, size(matrix))\n best_path[1,1] = matrix[1,1]\n\n # Initialize the edges since they only have a single path. Make use of the\n # built-in cumulative sum function\n best_path[:,1] = cumsum(matrix[:,1])\n best_path[1,:] = cumsum(matrix[1,:])\n\n # Very simple dynamic programming solution for the rest\n for i = 2:n\n for j = 2:m\n best_path[i,j] = min(best_path[i-1,j], best_path[i,j-1]) + matrix[i,j]\n end\n end\n\n return best_path[end,end]\nend\n\np081 = Problems.Problem(p081solution)\n\ninput_path = \"data/p081_matrix.txt\"\n\nProblems.benchmark(p081, input_path)\n", "meta": {"hexsha": "78c624e78f017e17ea65418b49a31665f587ec6b", "size": 1627, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/081.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/081.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/081.jl", "max_forks_repo_name": "gnujosh/julia-euler-project", "max_forks_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0535714286, "max_line_length": 87, "alphanum_fraction": 0.6644130301, "num_tokens": 468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9458012701768144, "lm_q2_score": 0.8887587868629346, "lm_q1q2_score": 0.8405891894957682}} {"text": "\"\"\"Julia program to check if a number is automorphic or not.\nAn Automorphic Number is such a number whose square ends in the same digits as the number itself.\"\"\"\n\n\nfunction check_automophic(num)\n temp = num * num\n\n while(num > 0)\n # Extract the last digits of the given number and its square.\n lastNum = num % 10\n lastSquare = temp % 10\n\n # Check if they are equal\n if(lastNum != lastSquare)\n return \"The given number $n is not an Automorphic Number.\"\n end\n\n num = num ÷ 10\n temp = temp ÷ 10\n end\n\n return \"The given number $n is an Automorphic Number.\"\nend\n\nprint(\"Enter the number: \")\nn = readline()\nn = parse(Int, n)\nres = check_automophic(abs(n))\nprint(res)\n\n\n\"\"\"\nTime Complexity: O(log(n)), where 'n' is the given number\nSpace Complexity: O(1)\n\nSAMPLE INPUT AND OUTPUT\n\nSAMPLE 1\n\nEnter the number: 24\nThe given number 24 is not an Automorphic Number.\n\nSAMPLE 2\n\nEnter the number: 25\nThe given number 25 is an Automorphic Number.\n\"\"\"\n\n", "meta": {"hexsha": "f9142b7a825938b6f009292f1fb4a30703c45e5b", "size": 1019, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/math/automorphic_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/automorphic_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/automorphic_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": 20.7959183673, "max_line_length": 101, "alphanum_fraction": 0.6565260059, "num_tokens": 268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308128813471, "lm_q2_score": 0.9005297807787537, "lm_q1q2_score": 0.8405822452961733}} {"text": "module IterativeMethod\n\nusing LinearAlgebra\n\nexport\n is_diagonally_dominant,\n jacobi_method,\n gauss_seidel_method, gauss_seidel_method!\n\n#===== Jacobi method =====#\n\n#=\n\nA x = b\nA = D + R\nD x = -R x + b\n x = -D^{-1} R x + D^{-1} b\n⟹\nx = B x + z, where B = -D^{-1} R, z = D^{-1}\n\n\nx_{i + 1} = B x_i + z\n = B (x^* + e_i) + z\n = x^* + B e_i\n⟹\ne_{i + 1} = B e_i\n\n=#\n\nfunction is_diagonally_dominant(A::AbstractMatrix{T})::Bool where T<:AbstractFloat\n A = abs.(A)\n d2 = diag(A) * 2\n all(sum(A, dims=1)' .<= d2) && all(sum(A, dims=2) .<= d2)\nend\n\nconst MAX_ITERATIONS = 1000\n\nfunction jacobi_method(\n A::Matrix{T},\n b::Vector{T},\n x0::Vector{T} = zero(b),\n)::Vector{T} where T<:AbstractFloat\n (nr, nc) = size(A)\n @assert nr == nc \"Jacobi: A is not square.\"\n if !is_diagonally_dominant(A)\n println(\"Jacobi: A is not diagonally dominant\")\n end\n\n D = Diagonal(A)\n invD = inv(D)\n negR = D - A\n x = x0\n for _ in 1:MAX_ITERATIONS\n x = invD * (negR * x0 + b)\n if x ≈ x0\n return x\n end\n x0 = x\n end\n x\nend\n\n#===== Gauss–Seidel method =====#\n\n#=\n\nIn Jacobi method,\n\n x_i^{(k + 1)} = -1/a_ii * ((L + U)_{i, :} * x^{(k)}) + b_i / a_ii\n\nwhere $U$ ($L$) is the strictly upper (lower) triangular and $R = L + U$. If in the iteration we\nuse the elements of $x^{(k+1)}$ that have already been computed to compute the unknown ones of\n$x^{(k+1)}$,\n\n x_i^{(k + 1)} = -1/a_ii * ((L_*)_{i, :} * x^{(k + 1)} + U_{i, :} * x^{(k)}) + b_i / a_ii\n\nwhere $L_* = D + L$ is a lower triangular matrix. Or more compcatly,\n\n A x = b\n (L_* + U) x = b\n L_* x = b - U x\n\n ⟹\n\n L_* x^{(k + 1)} = b - U x^{(k)}\n x^{(k + 1)} = L_*^{-1} (b - U x^{(k)})\n\n=#\n\nfunction gauss_seidel_method(A::Matrix{T}, b::Vector{T})::Vector{T} where T<:AbstractFloat\n x0 = zero(b)\n gauss_seidel_method!(A, b, x0)\nend\n\n# The initial guess `x0` will be updated in-place.\nfunction gauss_seidel_method!(\n A::Matrix{T},\n b::Vector{T},\n x0::Vector{T},\n)::Vector{T} where T<:AbstractFloat\n (nr, nc) = size(A)\n @assert nr == nc \"Gauss–Seidel: A is not square.\"\n n = nr\n if !is_diagonally_dominant(A)\n println(\"Gauss–Seidel: A is not diagonally dominant\")\n end\n\n x = x0\n for _ in 1:MAX_ITERATIONS\n updated = false\n for r in 1:n\n old = x[r]\n x[r] = (b[r] - ((@view A[r, :])' * x - A[r, r] * x[r])) / A[r, r]\n if !(x[r] ≈ old)\n updated = true\n end\n end\n if !updated\n return x\n end\n end\n x\nend\n\nend # module\n", "meta": {"hexsha": "6593e4bdcefc7b4d735794491e66102b26127212", "size": 2635, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "IterativeMethod/src/IterativeMethod.jl", "max_stars_repo_name": "gyk/TrivialSolutions", "max_stars_repo_head_hexsha": "dc461ebfca5756ac261576785c227d77d578cb33", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-07T13:20:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T05:51:37.000Z", "max_issues_repo_path": "IterativeMethod/src/IterativeMethod.jl", "max_issues_repo_name": "gyk/TrivialSolutions", "max_issues_repo_head_hexsha": "dc461ebfca5756ac261576785c227d77d578cb33", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IterativeMethod/src/IterativeMethod.jl", "max_forks_repo_name": "gyk/TrivialSolutions", "max_forks_repo_head_hexsha": "dc461ebfca5756ac261576785c227d77d578cb33", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.9126984127, "max_line_length": 96, "alphanum_fraction": 0.5138519924, "num_tokens": 975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741308615412, "lm_q2_score": 0.8824278602705731, "lm_q1q2_score": 0.8405779520452507}} {"text": "# Algorithm 6.2\n# Gaussian Elimination with partial pivoting\n\nfunction swap_rows(mat, row1, row2)\n\tfor i in 1:size(mat)[2]\n\t\tp1 = mat[row1, i]\n\t\tp2 = mat[row2, i]\n\t\ttmp = p1\n\t\tmat[row1, i] = p2\n\t\tmat[row2, i] = tmp\n\tend\n\treturn mat\nend\n\nfunction solve_gauss(mat)\n\tn, m = size(mat)\n\tfor k in 1:n\n\t\tmax_row = 1\n\t\tmax_val = 0\n\t\tfor i in 1:n\n\t\t\tif mat[i, k] > max_val\n\t\t\t\tmax_row = i\n\t\t\t\tmax_val = mat[i, k]\n\t\t\tend\n\t\tend\n\t\tif max_val == 0\n\t\t\tprintln(\"No unique solution\")\n\t\t\treturn\n\t\tend\n\n\t\tif max_row != 1\n\t\t\tmat = swap_rows(mat, k, max_row)\n\t\tend\n\n\t\tfor i in (k + 1):n\n\t\t\tm = mat[i, k]/mat[k, k]\n\t\t\tfor j in k:(n + 1)\n\t\t\t\tmat[i, j] -= m*mat[k, j]\n\t\t\tend\n\t\tend\n\tend\n\tprintln(mat)\n\tx = zeros(1, n)\n\tx[n] = mat[n, n + 1]/mat[n ,n]\n\tfor i in (n - 1):-1:1\n\t\tsum = 0\n\t\tfor j in (i + 1):n\n\t\t\tsum = mat[i, j]*x[j]\n\t\tend\n\t\tx[i] = (mat[i, n + 1] - sum)*mat[i, i]\n\tend\n\treturn x\nend\n\nA = [[1.0 1.0 2]; [2.0 -2.0 3.0];]\nprintln(A)\nA = solve_gauss(A)\nprintln(A)\n", "meta": {"hexsha": "a46baffa17a799648e0d20c367edfb1c21ce1759", "size": 947, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "chapter6/gaussian-elim-partial.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": "chapter6/gaussian-elim-partial.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": "chapter6/gaussian-elim-partial.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": 16.0508474576, "max_line_length": 44, "alphanum_fraction": 0.5491024287, "num_tokens": 409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122756889437, "lm_q2_score": 0.8774768002981829, "lm_q1q2_score": 0.8405457986378851}} {"text": "export linear, quadratic, quaddiff, cubic,\n neville, vandermonde, vandermonde!, cubichermite,\n LinearInterpolator, CubicInterpolator,\n BilinearInterpolator, BicubicInterpolator\n\n\n\"\"\"\n linear(x, xₚ, yₚ)\n\nPerform simple linear interpolation of the points defined by coordinates `xₚ` and values `yₚ`, at the coordinate `x`. `xₚ` and `yₚ` must both contain two points.\n\"\"\"\nfunction linear(x, xₚ, yₚ)\n @inbounds x₁, x₂ = xₚ[1], xₚ[2]\n @inbounds y₁, y₂ = yₚ[1], yₚ[2]\n return y₁ + (x - x₁)*(y₂ - y₁)/(x₂ - x₁)\nend\n\n\"\"\"\n quadratic(x, xₚ, yₚ)\n\nPerform quadratic polynomial interpolation of the points defined by coordinates `xₚ` and values `yₚ`, at the coordinate `x`, using Neville's algorithm. `xₚ` and `yₚ` must both contain three points.\n\"\"\"\nfunction quadratic(x, xₚ, yₚ)\n @assert length(xₚ) == length(yₚ) == 3 \"need 3 points for quadratic interpolation\"\n #short names\n @inbounds x₁, x₂, x₃ = xₚ[1], xₚ[2], xₚ[3]\n @inbounds y₁, y₂, y₃ = yₚ[1], yₚ[2], yₚ[3]\n #first stage\n p₁₂ = ((x - x₂)*y₁ + (x₁ - x)*y₂)/(x₁ - x₂)\n p₂₃ = ((x - x₃)*y₂ + (x₂ - x)*y₃)/(x₂ - x₃)\n #final stage\n ((x - x₃)*p₁₂ + (x₁ - x)*p₂₃)/(x₁ - x₃)\nend\n\n\"\"\"\n cubic(x, xₚ, yₚ)\n\nPerform cubic polynomial interpolation of the points defined by coordinates `xₚ` and values `yₚ`, at the coordinate `x`, using Neville's algorithm. `xₚ` and `yₚ` must both contain four points.\n\"\"\" \nfunction cubic(x, xₚ, yₚ)\n @assert length(xₚ) == length(yₚ) == 4 \"need 4 points for cubic interpolation\"\n #short names\n @inbounds x₁, x₂, x₃, x₄ = xₚ[1], xₚ[2], xₚ[3], xₚ[4]\n @inbounds y₁, y₂, y₃, y₄ = yₚ[1], yₚ[2], yₚ[3], yₚ[4]\n #first stage\n p₁₂ = ((x - x₂)*y₁ + (x₁ - x)*y₂)/(x₁ - x₂)\n p₂₃ = ((x - x₃)*y₂ + (x₂ - x)*y₃)/(x₂ - x₃)\n p₃₄ = ((x - x₄)*y₃ + (x₃ - x)*y₄)/(x₃ - x₄)\n #second stage\n p₁₂₃ = ((x - x₃)*p₁₂ + (x₁ - x)*p₂₃)/(x₁ - x₃)\n p₂₃₄ = ((x - x₄)*p₂₃ + (x₂ - x)*p₃₄)/(x₂ - x₄)\n #final stage\n ((x - x₄)*p₁₂₃ + (x₁ - x)*p₂₃₄)/(x₁ - x₄)\nend\n\n\"\"\"\n neville(x, xₚ, yₚ)\n\nPerform polynomial interpolation of the points defined by coordinates `xₚ` and values `yₚ`, at the coordinate `x`, using Neville's algorithm with as many points as are provided. `xₚ` and `yₚ` must have the same length. With only 3 or 4 points the [`quadratic`](@ref) and [`cubic`](@ref) functions will be considerably faster.\n\"\"\"\nfunction neville(x, xₚ, yₚ)\n @assert length(xₚ) == length(yₚ) \"can't Neville with vectors of different lengths\"\n n = length(xₚ)\n P = zeros(n, n)\n P[:,1] = yₚ\n for i ∈ 2:n, j ∈ i:n\n @inbounds P[j,i] = ((x - xₚ[j-i+1])*P[j,i-1] - (x - xₚ[j])*P[j-1,i-1])/(xₚ[j] - xₚ[j-i+1])\n end\n return P[n,n]\nend\n\n\"\"\"\n vandermonde(x, y)\n\nGenerate the coefficients of an arbitrary order polynomial passing through the ponts defined by coordinates `x` and value `y`. For n points, n coefficients ``[c_0, c_1, ..., c_{n-1}]`` are returned forming the polynomial ``c_0 + c_1x + ... + c_{n-1}x^{n-1}``\n\n!!! warning\n\n Solving for the the coefficients of a high-order polynomial is a notoriously ill-conditioned problem. It is not recommended for orders greater than 5 or 6, although it depends on the application. If you must interpolate with a high-order polynomial, it's better to use the [`neville`](@ref) function instead of computing coefficients.\n\"\"\"\nfunction vandermonde(x, y)\n @assert length(x) == length(y) \"length of x must equal length of y\"\n c = zeros(length(x))\n vandermonde!(c, x, y)\n return c\nend\n\nfunction vandermonde!(c, x, y)\n @assert length(c) == length(x) == length(y) \"vandermonde! requires length(c) == length(x) == length(y)\"\n n = length(x)\n s = similar(c)\n c[:] .= zero(eltype(c))\n s[n] = -x[1]\n @inbounds for i = 2:n\n for j = n-i+1:n-1\n s[j] -= x[i]*s[j+1]\n end\n s[n] -= x[i]\n end\n @inbounds for j = 1:n\n ϕ = n\n for k = n:-1:2\n ϕ = (k-1)*s[k] + x[j]*ϕ\n end\n f = y[j]/ϕ\n b = 1.0\n for k = n:-1:1\n c[k] += b*f\n b = s[k] + x[j]*b\n end\n end\nend\n\n\"\"\"\n cubichermite(x, x₁, x₂, y₁, y₂, y₁′, y₂′)\n\nInterpolate a cubic polynomial between two points, given its values and first derivatives at the points.\n\"\"\"\nfunction cubichermite(x, x₁, x₂, y₁, y₂, y₁′, y₂′)\n Δx = (x₂ - x₁)\n ξ = (x - x₁)/Δx\n u = Δx*y₁′\n v = Δx*y₂′\n ξ^3*(2*y₁ + u - 2*y₂ + v) + ξ^2*(-3*y₁ - 2*u + 3*y₂ - v) + ξ*u + y₁\nend\n\n#-------------------------------------------------------------------------------\n# simple piecewise linear interpolator\n\nstruct LinearInterpolator{T,B} <: OneDimensionalInterpolator\n r::InterpolatorRange{T}\n boundaries::B\n i::RefValue{Int64} #previous cell index\nend\n\n\"\"\"\n LinearInterpolator(x, y, boundaries=StrictBoundaries())\n\nConstruct a `LinearInterpolator` for the points defined by coordinates `x` and values `y`\n\"\"\"\nfunction LinearInterpolator(x, y, boundaries::AbstractBoundaries=StrictBoundaries())\n LinearInterpolator(InterpolatorRange(x, y), boundaries, Ref(1))\nend\n\n\"\"\"\n LinearInterpolator(f, xa, xb, n, boundaries=StrictBoundaries())\n\nConstruct a `LinearInterpolator` for the function `f` using `n` evenly spaced function evaluations in the range [`xa`,`xb`]\n\"\"\"\nfunction LinearInterpolator(f, xa, xb, n::Int, boundaries::AbstractBoundaries=StrictBoundaries())\n linstruct(LinearInterpolator, f, xa, xb, n, boundaries)\nend\n\nfunction (ϕ::LinearInterpolator)(x)\n #enforce boundaries\n ϕ.boundaries(x, ϕ.r.xa, ϕ.r.xb)\n #find the interpolation cell\n i = findcell(x, ϕ)\n #short names\n @inbounds x₁, x₂ = ϕ.r.x[i], ϕ.r.x[i+1]\n @inbounds y₁, y₂ = ϕ.r.y[i], ϕ.r.y[i+1]\n #interpolate\n (x - x₁)*(y₂ - y₁)/(x₂ - x₁) + y₁\nend\n\nBase.getindex(ϕ::LinearInterpolator, i) = ϕ.r.y[i]\nBase.firstindex(::LinearInterpolator) = 1\nBase.lastindex(ϕ::LinearInterpolator) = ϕ.r.n\nfunction Base.setindex!(ϕ::LinearInterpolator, v, i)\n ϕ.r.y[i] = v\nend\nfunction Base.copy(ϕ::LinearInterpolator)\n LinearInterpolator(ϕ.r, ϕ.boundaries, Ref(1))\nend\n\n#-------------------------------------------------------------------------------\n# piecewise cubic interpolator without continuous derivatives (not splines)\n\nstruct CubicInterpolator{T,B} <: OneDimensionalInterpolator\n r::InterpolatorRange{T}\n boundaries::B\n i::RefValue{Int64} #previous cell index\nend\n\n\"\"\"\n CubicInterpolator(x, y, boundaries=StrictBoundaries())\n\nConstruct a `CubicInterpolator` for the points defined by coordinates `x` and values `y`\n\"\"\"\nfunction CubicInterpolator(x, y, boundaries::AbstractBoundaries=StrictBoundaries())\n @assert length(x) > 3 \"can't do cubic interpolation with < 4 points\"\n CubicInterpolator(InterpolatorRange(x, y), boundaries, Ref(1))\nend\n\n\"\"\"\n CubicInterpolator(f, xa, xb, n, boundaries=StrictBoundaries())\n\nConstruct a `CubicInterpolator` for the function `f` using `n` evenly spaced function evaluations in the range [`xa`,`xb`]\n\"\"\"\nfunction CubicInterpolator(f, xa, xb, n::Int, boundaries::AbstractBoundaries=StrictBoundaries())\n linstruct(CubicInterpolator, f, xa, xb, n, boundaries)\nend\n\nfunction (ϕ::CubicInterpolator)(x)\n #enforce boundaries if desired\n ϕ.boundaries(x, ϕ.r.xa, ϕ.r.xb)\n #find the interpolation point\n i = findcell(x, ϕ)\n #determine which points to neville\n if i == 1\n I = 1:4\n elseif i == ϕ.r.n - 1\n I = ϕ.r.n-3:ϕ.r.n\n else\n I = i-1:i+2\n end\n #interpolate\n @inbounds cubic(x, view(ϕ.r.x,I), view(ϕ.r.y,I))\nend\n\nBase.getindex(ϕ::CubicInterpolator, i) = ϕ.r.y[i]\nBase.firstindex(::CubicInterpolator) = 1\nBase.lastindex(ϕ::CubicInterpolator) = ϕ.r.n\nfunction Base.setindex!(ϕ::CubicInterpolator, v, i)\n ϕ.r.y[i] = v\nend\nfunction Base.copy(ϕ::CubicInterpolator)\n CubicInterpolator(ϕ.r, ϕ.boundaries, Ref(1))\nend\n\n#-------------------------------------------------------------------------------\n# bilinear interpolator\n\nstruct BilinearInterpolator{T,B} <: TwoDimensionalInterpolator\n G::InterpolatorGrid{T}\n boundaries::B\n i::RefValue{Int64} #previous cell index\n j::RefValue{Int64} #previous cell index\nend\n\n\"\"\"\n BilinearInterpolator(x, y, Z, boundaries=StrictBoundaries())\n\nConstruct a `BilinearInterpolator` for the grid of points points defined by coordinates `x`,`y` and values `Z`.\n\"\"\"\nfunction BilinearInterpolator(x, y, Z, boundaries::AbstractBoundaries=StrictBoundaries())\n BilinearInterpolator(InterpolatorGrid(x, y, Z), boundaries, Ref(1), Ref(1))\nend\n\n\"\"\"\n BilinearInterpolator(f, xa, xb, nx, ya, yb, ny, boundaries=StrictBoundaries())\n\nConstruct a `BilinearInterpolator` for the function `f` using a grid of `nx` points evenly spaced on the first axis in [`xa`,`xb`] and `ny` points evenly spaced on the second axis in [`ya`,`yb`].\n\"\"\"\nfunction BilinearInterpolator(f,\n xa, xb, nx::Int,\n ya, yb, ny::Int,\n boundaries::AbstractBoundaries=StrictBoundaries())\n linstruct(BilinearInterpolator, f, xa, xb, nx, ya, yb, ny, boundaries)\nend\n\nfunction (Φ::BilinearInterpolator)(x, y)\n #enforce boundaries if desired\n Φ.boundaries(x, Φ.G.xa, Φ.G.xb, y, Φ.G.ya, Φ.G.yb)\n #find the proper grid box to interpolate inside\n i, j = findcell(x, y, Φ)\n #clear names\n @inbounds x₁, x₂ = Φ.G.x[i], Φ.G.x[i+1]\n @inbounds y₁, y₂ = Φ.G.y[j], Φ.G.y[j+1]\n @inbounds Z₁₁, Z₂₁ = Φ.G.Z[i,j], Φ.G.Z[i+1,j]\n @inbounds Z₂₂, Z₁₂ = Φ.G.Z[i+1,j+1], Φ.G.Z[i,j+1]\n #reused differences\n xx₁ = x - x₁\n x₂x₁ = x₂ - x₁\n #interpolate along axis 1 first\n t = xx₁*(Z₂₁ - Z₁₁)/x₂x₁ + Z₁₁\n u = xx₁*(Z₂₂ - Z₁₂)/x₂x₁ + Z₁₂\n #then finish by interpolating between the interpolated values along axis 2\n (y - y₁)*(u - t)/(y₂ - y₁) + t\nend\n\nBase.getindex(Φ::BilinearInterpolator, i, j) = Φ.G.Z[i,j]\nfunction Base.setindex!(Φ::BilinearInterpolator, v, i, j)\n Φ.G.Z[i,j] = v\nend\nfunction Base.copy(Φ::BilinearInterpolator)\n BilinearInterpolator(Φ.G, Φ.boundaries, Ref(1), Ref(1))\nend\n\n#-------------------------------------------------------------------------------\n# bicubic interpolator\n\nstruct BicubicInterpolator{T,B} <: TwoDimensionalInterpolator\n G::InterpolatorGrid{T}\n boundaries::B\n i::RefValue{Int64} #previous cell index\n j::RefValue{Int64} #previous cell index\nend\n\n\"\"\"\n BicubicInterpolator(x, y, Z, boundaries=StrictBoundaries())\n\nConstruct a `BicubicInterpolator` for the grid of points points defined by coordinates `x`,`y` and values `Z`.\n\"\"\"\nfunction BicubicInterpolator(x, y, Z, boundaries::AbstractBoundaries=StrictBoundaries())\n #insist on at least 4 points in each dimension\n @assert (length(x) > 3) & (length(y) > 3) \"bicubic interpolation requires at least 4 points in each dimension\"\n BicubicInterpolator(InterpolatorGrid(x, y, Z), boundaries, Ref(1), Ref(1))\nend\n\n\"\"\"\n BicubicInterpolator(f, xa, xb, nx, ya, yb, ny, boundaries=StrictBoundaries())\n\nConstruct a `BicubicInterpolator` for the function `f` using a grid of `nx` points evenly spaced on the first axis in [`xa`,`xb`] and `ny` points evenly spaced on the second axis in [`ya`,`yb`].\n\"\"\"\nfunction BicubicInterpolator(f,\n xa, xb, nx::Int,\n ya, yb, ny::Int,\n boundaries::AbstractBoundaries=StrictBoundaries())\n linstruct(BicubicInterpolator, f, xa, xb, nx, ya, yb, ny, boundaries)\nend\n\nfunction (Φ::BicubicInterpolator)(x, y)\n #enforce boundaries if desired\n Φ.boundaries(x, Φ.G.xa, Φ.G.xb, y, Φ.G.ya, Φ.G.yb)\n #find the proper grid box to interpolate inside\n i, j = findcell(x, y, Φ)\n #get indices of points along axis 1 to use for interpolation\n if i == 1\n I = 1:4\n elseif i == Φ.G.nx - 1\n I = Φ.G.nx-3:Φ.G.nx\n else\n I = i-1:i+2\n end\n #get indices along axis 2 where initial 4 interpolations occur\n if j == 1\n J = 1:4\n elseif j == Φ.G.ny - 1\n J = Φ.G.ny-3:Φ.G.ny\n else\n J = j-1:j+2\n end\n #view the proper chunks of the arrays\n xᵣ = view(Φ.G.x, I)\n yᵣ = view(Φ.G.y, J)\n #perform initial 4 interpolations\n zₓ = (\n cubic(x, xᵣ, @view Φ.G.Z[I,J[1]]),\n cubic(x, xᵣ, @view Φ.G.Z[I,J[2]]),\n cubic(x, xᵣ, @view Φ.G.Z[I,J[3]]),\n cubic(x, xᵣ, @view Φ.G.Z[I,J[4]])\n )\n #final interpolation\n cubic(y, yᵣ, zₓ)\nend\n\nBase.getindex(Φ::BicubicInterpolator, i, j) = Φ.G.Z[i,j]\nfunction Base.setindex!(Φ::BicubicInterpolator, v, i, j)\n Φ.G.Z[i,j] = v\nend\nfunction Base.copy(Φ::BicubicInterpolator)\n BicubicInterpolator(Φ.G, Φ.boundaries, Ref(1), Ref(1))\nend", "meta": {"hexsha": "25be5e1cdb19dae99d3531cd4ada54adbda21351", "size": 12575, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/polynomial.jl", "max_stars_repo_name": "wordsworthgroup/BasicInterpolators.jl", "max_stars_repo_head_hexsha": "1a43e6e657377ee9de53c721cf58141363036e78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-03-03T14:12:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-05T02:27:30.000Z", "max_issues_repo_path": "src/polynomial.jl", "max_issues_repo_name": "markmbaum/BasicInterpolators.jl", "max_issues_repo_head_hexsha": "6986d0418913b39207ccc7825a7f00822e434ef4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-07-16T15:16:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-12T15:05:48.000Z", "max_forks_repo_path": "src/polynomial.jl", "max_forks_repo_name": "wordsworthgroup/BasicInterpolators.jl", "max_forks_repo_head_hexsha": "1a43e6e657377ee9de53c721cf58141363036e78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5467032967, "max_line_length": 338, "alphanum_fraction": 0.6178926441, "num_tokens": 4226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122756889437, "lm_q2_score": 0.8774767826757122, "lm_q1q2_score": 0.840545781757104}} {"text": "# # [PDE Discovery : Heat equations](@id heat_equation)\n#\n# Similar to the discovery of ODE and DAE systems, sparse regression can be used to discover the underlying \n# equations for partial differential equations as well as proposed by [PDEFind](https://www.science.org/doi/10.1126/sciadv.1602614). The following example shows how this \n# can be achieved with DataDrivenDiffEq.jl, using the heat equation with Dirichlet boundary conditions\n# with the analytical soultion $u(x,t) = sin(2\\pi x) exp^{-(2\\pi t)^2t}$.\n# We start by defining the system and generate some data.\n\nusing DataDrivenDiffEq\nusing LinearAlgebra\nusing ModelingToolkit\nusing OrdinaryDiffEq\nusing DiffEqOperators\n#md using Plots\n\nu_analytic(x, t) = sin(2*π*x) * exp(-t*(2*π)^2)\nnknots = 100 \nh = 1.0/(nknots+1) \nknots = range(h, step=h, length=nknots) \nord_deriv = 2 \nord_approx = 2 \n\nconst bc = Dirichlet0BC(Float64) \nconst Δ = CenteredDifference(ord_deriv, ord_approx, h, nknots) \n\nt0 = 0.0 \nt1 = 1.0 \nu0 = u_analytic.(knots, t0)\n\nstep(u,p,t) = Δ*bc*u \nprob = ODEProblem(step, u0, (t0, t1)) \nalg = KenCarp4() \nde_solution = solve(prob, alg);\n\n#md plot(de_solution, legend = nothing)\n\n# Using DiffEqOperators.jl, we can define the difference operators up to order $n =4$ and vectorize the result. \n\n∂U = reduce(vcat, map(1:4) do n \n δ = CenteredDifference(n, ord_approx, h, nknots)\n reshape(\n δ*bc*Array(de_solution), 1, prod(size(de_solution))\n )\n end)\n\n# Next we collect the discretized data samples, their time derivatives and define a DataDrivenProblem\n\nU = reshape(Array(de_solution), 1, prod(size(de_solution)))\n∂ₜU = reshape(Array(de_solution(de_solution.t, Val{1})), 1, prod(size(de_solution)))\n\nproblem = DataDrivenProblem(\n U, DX = ∂ₜU, U = ∂U\n)\n\n# We choose to model the spatial derivatives $\\frac{d^n u}{dx^n}$ as exegenous signals (controls), which are directly substituted into the \n# Basis defined in the following \n\n@parameters t x\n@variables u(x, t)\n∂u = map(1:4) do n \n d = Differential(x)^n\n d(u)\nend\n\nbasis = Basis([monomial_basis([u], 5);∂u], [u], independent_variable = t, controls = ∂u);\nprintln(basis) #hide\n\n# Afterwards, we define a sampler for the available data which performs a 80-20 train-test split and partions the training \n# data into 10 batches and solve the sparse regression using STLSQ.\n\nsampler = DataSampler(Split(ratio = 0.8), Batcher(n = 10))\nsolution = solve(problem, basis, STLSQ(1e-2:1e-2:5e-1), sampler = sampler, by = :best)\n\n# As we can see, the heat equation is recovered correclty\nresult(solution)\nprintln(result(solution)) #hide\n\n#md # ## [Copy-Pasteable Code](@id cartpole_copy_paste)\n#md #\n#md # ```julia\n#md # @__CODE__\n#md # ```\n\n## Test #src\nfor r_ in [solution] #src\n @test all(l2error(r_) .< 0.5) #src\n @test all(aic(r_) .> 1e3) #src\n @test all(determination(r_) .>= 0.9) #src\nend #src\n\n\n", "meta": {"hexsha": "bd96ffad8178d814a517f1a3000a1374cdd65fda", "size": 2857, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/examples/9_heatequation.jl", "max_stars_repo_name": "JuliaDiffEq/DataDrivenDiffEq.jl", "max_stars_repo_head_hexsha": "27f5537d2d04719b80f5785531b2b02e27a8208f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2019-11-22T17:20:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-07T17:10:27.000Z", "max_issues_repo_path": "docs/examples/9_heatequation.jl", "max_issues_repo_name": "JuliaDiffEq/DataDrivenDiffEq.jl", "max_issues_repo_head_hexsha": "27f5537d2d04719b80f5785531b2b02e27a8208f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 53, "max_issues_repo_issues_event_min_datetime": "2019-11-22T17:20:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-22T15:11:55.000Z", "max_forks_repo_path": "docs/examples/9_heatequation.jl", "max_forks_repo_name": "AlCap23/DataDrivenDiffEq", "max_forks_repo_head_hexsha": "3be031060d5a3cad08473506be60108e572ac0fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-11-22T18:36:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:36:14.000Z", "avg_line_length": 31.0543478261, "max_line_length": 170, "alphanum_fraction": 0.7031851593, "num_tokens": 907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067195846919, "lm_q2_score": 0.8918110519076928, "lm_q1q2_score": 0.8405379090228929}} {"text": "#!/usr/bin/env julia\n\n\"\"\"\n# Problem 6: Sum square differences\n\nThe sum of the squares of the first ten natural numbers is,\n\n 1² + 2² + ... + 10² = 385\n\nThe square of the sum of the first ten natural numbers is,\n\n (1 + 2 + ... + 10)² = 55² = 3025\n\nHence the difference between the sum of the squares of the first ten natural\nnumbers and the square of the sum is 3025 − 385 = 2640.\n\nFind the difference between the sum of the squares of the first `n` natural\nnumbers and the square of the sum.\n\"\"\"\nmodule Problem006\n\ninclude(\"Sequences.jl\")\n\n\"\"\"\n solve(; n::Integer = 100)\n\nReturns the solution for [`Problem006`](@ref) with the given parameters.\n\"\"\"\nfunction solve(; n::Integer = 100)\n return Sequences.triangular(n)^2 - Sequences.sum_of_squares(n)\nend\n\nend\n", "meta": {"hexsha": "64672850eda43b242aa3208c6b6e0d845dc48d19", "size": 769, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "jl/src/Problem006.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/Problem006.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/Problem006.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": 22.6176470588, "max_line_length": 76, "alphanum_fraction": 0.6944083225, "num_tokens": 216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811581728097, "lm_q2_score": 0.8705972566572503, "lm_q1q2_score": 0.8404581879338471}} {"text": "# # Phase recovery using MaxCut\n#\n# In this example, we relax the phase retrieval problem similar to the classical\n# [MaxCut](http://www-math.mit.edu/~goemans/PAPERS/maxcut-jacm.pdf) semidefinite\n# program and recover the phase of the signal given the magnitude of the linear\n# measurements.\n#\n# Phase recovery has wide applications such as in X-ray and crystallography\n# imaging, diffraction imaging or microscopy and audio signal processing. In all\n# these applications, the detectors cannot measure the phase of the incoming wave\n# and only record its amplitude i.e complex measurements of a signal\n# $x \\in \\mathbb{C}^p$ are obtained from a linear injective operator $A$, **but we\n# can only measure the magnitude vector $Ax$, not the phase of $Ax$**.\n#\n# Recovering the phase of $Ax$ from $|Ax|$ is a **nonconvex optimization problem**. Using results from [this paper](https://arxiv.org/abs/1206.0102), the problem can be relaxed to a (complex) semidefinite program (complex SDP).\n#\n# The original reprsentation of the problem is as follows:\n#\n# $$\n# \\begin{array}{ll}\n# \\text{find} & x \\in \\mathbb{C}^p \\\\\n# \\text{subject to} & |Ax| = b\n# \\end{array}\n# $$\n#\n# where $A \\in \\mathbb{C}^{n \\times p}$ and $b \\in \\mathbb{R}^n$.\n\n# In this example, **the problem is to find the phase of $Ax$ given the value $|Ax|$**.\n# Given a linear operator $A$ and a vector $b= |Ax|$ of measured amplitudes,\n# in the noiseless case, we can write $Ax = \\text{diag}(b)u$ where\n# $u \\in \\mathbb{C}^n$ is a phase vector, satisfying\n# $|\\mathbb{u}_i| = 1$ for $i = 1,\\ldots, n$.\n#\n# We relax this problem as Complex Semidefinite Programming.\n#\n# ### Relaxed Problem similar to [MaxCut](http://www-math.mit.edu/~goemans/PAPERS/maxcut-jacm.pdf)\n#\n# Define the positive semidefinite hermitian matrix\n# $M = \\text{diag}(b) (I - A A^*) \\text{diag}(b)$. The problem is:\n#\n# $$\n# \\begin{array}{ll}\n# \\text{minimize} & \\langle U, M \\rangle \\\\\n# \\text{subject to} & \\text{diag}(U) = 1\\\\\n# & U \\succeq 0\n# \\end{array}\n# $$\n#\n# Here the variable $U$ must be hermitian ($U \\in \\mathbb{H}_n $),\n# and we have a solution to the phase recovery problem if $U = u u^*$\n# has rank one. Otherwise, the leading singular vector of $U$ can be used\n# to approximate the solution.\n\nusing Convex, SCS, LinearAlgebra\n\nn = 20\np = 2\nA = rand(n, p) + im * randn(n, p)\nx = rand(p) + im * randn(p)\nb = abs.(A * x) + rand(n)\n\nM = diagm(b) * (I(n) - A * A') * diagm(b)\nU = ComplexVariable(n, n)\nobjective = inner_product(U, M)\nc1 = diag(U) == 1\nc2 = U in :SDP\np = minimize(objective, c1, c2)\nsolve!(p, SCS.Optimizer; silent_solver = true)\nevaluate(U)\n\n#-\n\n# Verify if the rank of $U$ is 1:\nB, C = eigen(evaluate(U));\nlength([e for e in B if (abs(real(e)) > 1e-4)])\n\n#-\n\n# Decompose $U = uu^*$ where $u$ is the phase of $Ax$\nu = C[:, 1];\nfor i in 1:n\n u[i] = u[i] / abs(u[i])\nend\nu\n", "meta": {"hexsha": "888cb9f374506ab3dd57758dcd3ebb1661652ec4", "size": 2852, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/examples_literate/optimization_with_complex_variables/phase_recovery_using_MaxCut.jl", "max_stars_repo_name": "baggepinnen/Convex.jl", "max_stars_repo_head_hexsha": "4f52b6fd4c446cda55e77201037ae22043da2c67", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 327, "max_stars_repo_stars_event_min_datetime": "2015-01-22T01:00:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-12T16:42:11.000Z", "max_issues_repo_path": "docs/examples_literate/optimization_with_complex_variables/phase_recovery_using_MaxCut.jl", "max_issues_repo_name": "baggepinnen/Convex.jl", "max_issues_repo_head_hexsha": "4f52b6fd4c446cda55e77201037ae22043da2c67", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 275, "max_issues_repo_issues_event_min_datetime": "2015-01-12T19:27:32.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-05T19:05:45.000Z", "max_forks_repo_path": "docs/examples_literate/optimization_with_complex_variables/phase_recovery_using_MaxCut.jl", "max_forks_repo_name": "baggepinnen/Convex.jl", "max_forks_repo_head_hexsha": "4f52b6fd4c446cda55e77201037ae22043da2c67", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 121, "max_forks_repo_forks_event_min_datetime": "2015-01-23T21:13:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-25T13:58:39.000Z", "avg_line_length": 33.5529411765, "max_line_length": 227, "alphanum_fraction": 0.659887798, "num_tokens": 952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813476288299, "lm_q2_score": 0.8791467580102418, "lm_q1q2_score": 0.8404479024861478}} {"text": "\nusing Symbolics, SymbolicUtils\n\nfunction solve_newton(f, x, x₀; abstol=1e-8, maxiter=50)\n xₙ = Float64(x₀)\n fₙ₊₁ = x - f / Symbolics.derivative(f, x)\n\n for i = 1:maxiter\n xₙ₊₁ = substitute(fₙ₊₁, Dict(x => xₙ))\n if abs(xₙ₊₁ - xₙ) < abstol\n return xₙ₊₁\n else\n xₙ = xₙ₊₁\n end\n end\n return xₙ₊₁\nend\n\n\nn = 2\n@variables ϵ a[1:n]\n\n\nx = 1 + a[1]*ϵ + a[2]*ϵ^2\n\n\n eq = x^5 + ϵ*x - 1\n\n\nexpand(eq)\n\n\nfunction collect_powers(eq, x, ns; max_power=100)\n eq = substitute(expand(eq), Dict(x^j => 0 for j=last(ns)+1:max_power))\n\n eqs = []\n for i in ns\n powers = Dict(x^j => (i==j ? 1 : 0) for j=1:last(ns))\n push!(eqs, substitute(eq, powers))\n end\n eqs\nend\n\n\neqs = collect_powers(eq, ϵ, 1:2)\n\n\nsubstitute(expand(eq), Dict(\n ϵ => 0,\n ϵ^2 => 1,\n ϵ^3 => 0,\n ϵ^4 => 0,\n ϵ^5 => 0,\n ϵ^6 => 0,\n ϵ^7 => 0,\n ϵ^8 => 0)\n)\n\n\nfunction solve_coef(eqs, ps)\n vals = Dict()\n\n for i = 1:length(ps)\n eq = substitute(eqs[i], vals)\n vals[ps[i]] = Symbolics.solve_for(eq ~ 0, ps[i])\n end\n vals\nend\n\n\nsolve_coef(eqs, a)\n\n\nX = 𝜀 -> 1 + a[1]*𝜀 + a[2]*𝜀^2\n\n\ndef_taylor(x, ps) = sum([a*x^i for (i,a) in enumerate(ps)])\ndef_taylor(x, ps, p₀) = p₀ + def_taylor(x, ps)\n\n\nn = 3\n@variables ϵ M a[1:n]\nx = def_taylor(ϵ, a, M)\n\n\nexpand_sin(x, n) = sum([(isodd(k) ? -1 : 1)*(-x)^(2k-1)/factorial(2k-1) for k=1:n])\n\n\nexpand_sin(0.1, 10) ≈ sin(0.1)\n\n\neq = x - ϵ * expand_sin(x, n) - M\n\n\neqs = collect_powers(eq, ϵ, 1:n)\n\n\nvals = solve_coef(eqs, a)\n\n\nx′ = substitute(x, vals)\nX = (𝜀, 𝑀) -> substitute(x′, Dict(ϵ => 𝜀, M => 𝑀))\nX(0.01671, π/2)\n\n", "meta": {"hexsha": "050972046d7e369d9bde1d8c637049e9780fb4ed", "size": 1618, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/perturbation/01-perturbation_algebraic.jl", "max_stars_repo_name": "siravan/SciMLTutorials.jl", "max_stars_repo_head_hexsha": "34f4044f96facf351eb32c991b73325a32d17a94", "max_stars_repo_licenses": ["MIT"], "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/perturbation/01-perturbation_algebraic.jl", "max_issues_repo_name": "siravan/SciMLTutorials.jl", "max_issues_repo_head_hexsha": "34f4044f96facf351eb32c991b73325a32d17a94", "max_issues_repo_licenses": ["MIT"], "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/perturbation/01-perturbation_algebraic.jl", "max_forks_repo_name": "siravan/SciMLTutorials.jl", "max_forks_repo_head_hexsha": "34f4044f96facf351eb32c991b73325a32d17a94", "max_forks_repo_licenses": ["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.4095238095, "max_line_length": 83, "alphanum_fraction": 0.5259579728, "num_tokens": 714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.940789754239075, "lm_q2_score": 0.8933094010836643, "lm_q1q2_score": 0.8404163319049558}} {"text": "### A Pluto.jl notebook ###\n# v0.14.2\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 02d67371-b1e3-4ac9-b4d1-cdca1c85bd18\nusing Distributions, Statistics\n\n# ╔═╡ 7c8394db-271e-4d0b-a3db-b3e3a659ec0a\nusing Gaston; set(showable=\"svg\")\n\n# ╔═╡ bf7ce886-e6ac-45e7-a0f5-98e36c8974c7\nusing LightGraphs, GraphPlot\n\n# ╔═╡ 7a514f20-e7cc-43da-96f6-cc4f7244166b\nusing PlutoUI\n\n# ╔═╡ c7a5ab0b-aba0-4b54-abe9-702b0bad4a8e\nusing SimpleWeightedGraphs\n\n# ╔═╡ ea0dc819-e860-4863-b9ea-81d12d92c4ab\nmd\"[Reference Chapter](https://www.deeplearningbook.org/contents/prob.html)\"\n\n# ╔═╡ e84a31da-8ce7-11eb-1b6a-0f1431d8c96e\nmd\"# Probability\"\n\n# ╔═╡ 48727d46-8cf8-11eb-25a0-73c248dab2da\nmd\"\nThe probability of an event A, given B\n\n$ P(A|B) = \\frac{P(A \\cap B)}{P(B)}$\n\nThe probability of B, given A\n\n$ P(B|A) = \\frac{P(B \\cap A)}{P(A)}$\n\nWe can rewrite the above $ 2 $ as --\n\n$ \\frac{P(A|B)}{P(B|A)} = \\frac{P(A)}{P(B)} $ \n\"\n\n# ╔═╡ af0e8170-9163-11eb-2e48-4dcc7c853090\nmd\"**What does $P(A \\cap B)$ mean?**\"\n\n# ╔═╡ dde86ab8-9163-11eb-173a-0d0fe5d297ad\nmd\"Probability of event A _and_ event B occurring.\"\n\n# ╔═╡ 51cf0da0-8cf8-11eb-13d1-53bb6bd3892a\nmd\"\n#### Question --\n\nIn 5 coin tosses, whats the chance that we get exactly 3 heads, given that we've atleast one head?\n\"\n\n# ╔═╡ 5c51aa26-8cf8-11eb-0add-a1b7f41216f6\nmd\"\nSo... in how many ways can I rearrange 2 squares, in a collection of 3 objects, consisting of 2 squares and a circle?\n\n⭘ ◻ ◻, ◻ ◻ ⭘, ◻ ⭘ ◻\n\n3 ways, without repetition\n\nWell... what about with repetition?\n\n6 ways(if you consider the two squares to be 2 different objects)\n\nSo how do we generalize this?\n\n$ ^{n}P_{r} = \\frac{n!}{(n-r)!}$\n\nwhere $ ^{n}P_{r} $ represents the permutation where we've to rearrange r objects, in a collection of n objects, and repetition is allowed.\n\n$ ^{n}C_{r} = \\frac{n!}{r!(n-r)!}$\n\nwhere `` ^{n}C_{r} `` represents the permutation where we've to rearrange r objects, in a collection of n objects, and repetition is _not_ allowed.\n\n\"\n\n# ╔═╡ 72edf972-8cf8-11eb-2441-75b6edc68854\nmd\"For the above question... We've $ 2^5 $ or $ 32 $ possibilities after we toss the coin 5 times, or $ 32 $ possible combination of heads and tails! Since one of the possibilities is TTTTT, and we already know from the information we have, that we've at least one head, TTTTT is not possible, so we've a total of $31$ possibilities.\n\nOut of these $31$ possibilities, we've to find the ones with exactly three heads. Going with the above formula, we have $^{5}C_{3}$ possibilities of getting exactly three heads in five tosses, which is equal to \n\"\n\n# ╔═╡ c26eb560-9167-11eb-02d3-8b4212f378e6\nbinomial(5,3)\n\n# ╔═╡ 6d6ead0a-9170-11eb-049b-2dfaf08ba40e\nmd\"So the probability of getting exactly 3 heads is $10/31$\"\n\n# ╔═╡ 5e59cfb6-9170-11eb-0215-2390218aac63\nmd\"The below code finds all possible results we can obtain, after flipping a coin 5 times, and stores it in variable `a`. It then removes the possibility that the result is TTTTT, as per given in the question, from `a`.\"\n\n# ╔═╡ 6fd98eb6-916b-11eb-19a4-5368d9cc2b31\nbegin a = [prod.(collect(Iterators.product(['H', 'T'], ['H', 'T'], ['H', 'T'], ['H', 'T'], ['H', 'T'])))[i] for i in 1:2^5]\n\tdeleteat!(a,findall(a .== \"TTTTT\"))\nend\n\n# ╔═╡ 980bb77e-9170-11eb-3d61-19044344aa37\nmd\"The below code finds the number of results where we get heads exactly 3 times, and stores the outcomes in the variable `b`\"\n\n# ╔═╡ 0c0ac120-916b-11eb-1029-cb8615bca99c\nb = a[[(count(\"H\", a[i]) == 3) for i in 1:length(a)]]\n\n# ╔═╡ 4ef0b236-9172-11eb-0813-e12589886a31\nmd\"Counting the number of elements in `a` and `b`\"\n\n# ╔═╡ 47f31ab4-9172-11eb-1bc4-f916418a47db\nlength(b), length(a)\n\n# ╔═╡ eced0ac6-9171-11eb-0f2a-cd5fa1bd818d\nmd\"We get our answer equal to $ $(length(b)) / $(length(a)) $\"\n\n# ╔═╡ 3f168c24-9173-11eb-1cf8-7338a422ff69\nmd\"## Random Variable\"\n\n# ╔═╡ f6b2bf60-9173-11eb-145d-2f1f47b7eb30\nmd\"\"\"\n!!! question \"Consider this example\"\n\tI've a blue bag, and a red bag.\n\n\tThe blue bag has 3 green balls and 5 yellow balls, and the red bag has 6 green balls and 4 yellow balls.\n\n\tWhat is the probability that when I choose a random bag and draw a ball, its a green ball?\n\"\"\"\n\n# ╔═╡ 79557c7c-9173-11eb-3c53-4fa9ad783e8a\nmd\"\"\"\nIn the above example, the color of the bag and the color of balls are _random variables_. Let's call the color of bag, B, and the color of balls, A.\n\nWe've to find out $P(A=🟢)$.\n\nThe probability that I choose a blue bag is, denoted by $P(B=$\"blue\"$)$, and the probability that I choose the red bag is denoted by $P(B=$\"red\"$)$.\n\nMind that the random variable _color of bag_ can have two outcomes. It can either be blue or yellow with equally likely chances with the total probability bound to be $1$. Which means, $P(B=$\"blue\"$)$ $= P(B=$\"red\"$)$ and $P(B=$\"blue\"$) + P(B=$\"red\"$) = 1$.\nWhich means $P(B=$\"blue\"$) = P(B=$\"red\"$) = 0.5$.\n\nTry thinking of it this way, when an unbiased coin is tossed. Very similar to the above case, you've two expected outcomes, C = \"Heads\" or C = \"Tails\", where C is a random variable denoting the side when the coin is tossed. Here too, $P(C = $\"Heads\" $) = P(C = $\"Tails\" $) = 0.5$.\n\n\"\"\"\n\n# ╔═╡ 35cfa732-9238-11eb-3f47-0d921b5d6eeb\nmd\"## Types of random variables and Joint Probability\"\n\n# ╔═╡ b4374be0-9173-11eb-09d2-cbab6657cdaf\nmd\"\"\"\nReturning to our previous example,\n\n$ P(A=🟢) = P(B= $ \"red\"$, A=🟢) + P(B=$\"blue\"$, A=🟢)$\n\nProbability that the ball we chose is a green ball = (Probability that we chose the red bag, and a green ball) + (Probability that we chose the blue bag, and a green ball)\n\n$ P(A=🟢) = \\frac{1}{2} \\times \\frac{3}{8} + \\frac{1}{2} \\times \\frac{6}{10}$ \n\n$ P(A=🟢) = \\frac{39}{80}$ or $ $(39/80) $\n\n\"\"\"\n\n# ╔═╡ 70e11290-923b-11eb-2365-f58a04d0f844\nmd\"\"\"\nThe probability of two or more events occuring at the same time, is called **Joint Probability**\n\nYou see it in the above example and you see it in the below question.\n\"\"\"\n\n# ╔═╡ 758a1460-8cf8-11eb-0ab7-7dfcfac203f9\nmd\"\"\"\n!!! question \"An example\"\n\tIn a particular hospital during Flu season, it was observed that 10% of the patients had Cold. Among the patients with cold, 80% had Flu and among the rest, only 5% had flu. Given that a particular patient had Flu, what is the probability that he had Cold?\n\"\"\"\n\n# ╔═╡ 806857e8-8cf8-11eb-3756-bff672168730\nmd\"\"\"\nProbability that a patient had cold = $ 0.1 $\n\nProbability that a patient had cold, and had flu = $ 0.1 × 0.8 $ = $ 0.08 $\n\nProbability that a patient didn't have cold, and had flu = $ 0.9 × 0.05 $ = $ $(round((0.9*0.05); digits=3)) $\n\nProbability that a patient has cold, given that he had flu = $\\frac{Probability\\;that\\;a\\;patient\\;has\\;cold\\;and\\;flu}{Probability\\;that\\;a\\;patient\\;has\\;flu} = \\frac{0.08}{0.08+0.045}$ = $ \\frac{16}{25} $\n\"\"\"\n\n# ╔═╡ 7bc55826-92de-11eb-258b-31d565464c56\nmd\"\"\"\n!!! question \"Question\"\n\tA man arrives at a bus stop at a random time (that is, with no regard for the scheduled service) to catch the next bus. Buses run every $30$ minutes without fail, hence the next bus will come any time during the next $30$ minutes with evenly distributed probability (a uniform distribution). Find the probability that a bus will come within the next $10$ minutes.\n\"\"\"\n\n# ╔═╡ a2128026-92de-11eb-102f-d924f0ceee27\nmd\"\"\"\nIn the above question, the bus can arrive any time within the next 30minutes. It has equal chances of coming at the $0.1$min or $0.01$min or $25.005$min. Every value we choose for the arrival of the bus has equal proability. For example, the probability of the bus arriving at $1$min is the same as the bus arriving at $29.909$min. Since there're infinite possibilities, for a particular given time, the probability always approaches $0$. Here, if we assume the random variable to be _the time at which the bus arrives_, its number of possible outcomes can't be counted. Such random variables are called **continous random variables**. Similarly, the random variables we encountered before this had countable number of outcomes, and were called **discrete random variables**. $𝑝(x)$ is also called the **probability density function**, and $P(x)$ is also known as the **probability mass function**. \n\nWhen it comes to **continous random variables**, we try finding the probability of the outcome falling in a particular interval, rather than a particular value as in the case of **discrete random variables**.\n\"\"\"\n\n# ╔═╡ 749c569c-92e0-11eb-14c5-8301f513cdad\nmd\"\"\"\nIn this question, since all outputs are equally likely, if we divide the time interval in three parts, the outcome would have equal chances of falling in any of the three intervals. That means, the time at which the bus arrives can be within $0$ to $10$ minutes, $10$ to $20$ minutes, or $20$ to $30$ minutes, with equally likely chances. And since the total probability is always one, following the notation from the book, \n\n$𝑝(069.75) = p(x<69.75) = 0.5$\n\"\"\"\n\n# ╔═╡ 291d53fc-93ec-4926-80ab-a276b025ef82\nmd\"\"\"\n## Likelihood\n\"\"\"\n\n# ╔═╡ fd6e90a0-36f9-4055-a69b-5809cd05b837\n\n\n# ╔═╡ 3d141deb-bf7c-4ef3-88db-1b7e31ba6033\nmd\"\"\"\n#### Try Yourself\n1. Try making the Dirac Delta function in Julia.\n2. Explore [this](https://stats.libretexts.org/Bookshelves/Introductory_Statistics/Book%3A_Introductory_Statistics_(Shafer_and_Zhang)/05%3A_Continuous_Random_Variables/5.01%3A_Continuous_Random_Variables) website, look at solved and unsolved questions, try solving them in julia.\n3. Check out the [Exponential Distribution](https://juliastats.org/Distributions.jl/latest/univariate/#Distributions.Exponential) and [Laplace Distribution](https://juliastats.org/Distributions.jl/latest/univariate/#Distributions.Laplace) from Distributions.jl\n4. Explore [Gaston](https://mbaz.github.io/Gaston.jl/stable/) more, as it'll be used throughout the tutorial. Try getting familiar with it.\n\"\"\"\n\n# ╔═╡ d4bf1c39-6281-4ddf-b87e-bf4e3cefea3e\nmd\"# Information Theory\"\n\n# ╔═╡ 747b4b5b-98e7-4171-bfb0-b5acc792eda3\nmd\"\"\"\nThe self-information of an event $X=x$ denoted by 𝐼, is given by\n\"\"\"\n\n# ╔═╡ 75b07946-f493-49f0-928c-afee87fb22ad\nI(x) = -log(x)\n\n# ╔═╡ 4cf8dd4f-af3b-421f-ab11-e3036d60cc29\nmd\"where x denotes the probability of a random variable's outcome being $x$.\"\n\n# ╔═╡ 2454387d-df18-4932-ad48-691e5583a21e\nmd\"with the Shanon Entropy given by\"\n\n# ╔═╡ 50920106-7a39-4563-a1c0-cdd5d43ebb37\nH(x) = mean(I(x))\n\n# ╔═╡ e8140a83-904a-46b6-a8e8-8a7151b85c43\nmd\"Its mostly theoritical stuff. In this section, I'd like to introduce the reader to Graphs\"\n\n# ╔═╡ 76dc38a7-d06e-41c4-8da5-b15e3ebe54de\nmd\"\"\"\n## Graphs\n_In mathematics, and more specifically in graph theory, a graph is a structure amounting to a set of objects in which some pairs of the objects are in some sense \"related\". The objects correspond to mathematical abstractions called **vertices** (also called **nodes** or **points**) and each of the related pairs of vertices is called an **edge** (also called link or line). Typically, a graph is depicted in diagrammatic form as a set of dots or circles for the vertices, joined by lines or curves for the edges._\n\n_The edges may be **directed** or **undirected**. For example, if the vertices represent people at a party, and there is an edge between two people if they shake hands, then this graph is undirected because any person A can shake hands with a person B only if B also shakes hands with A. In contrast, if any edge from a person A to a person B corresponds to A owes money to B, then this graph is **directed**, because owing money is not necessarily reciprocated. The former type of graph is called an **undirected** graph while the latter type of graph is called a **directed** graph._\n\n$ \\,\\,\\,\\,\\,\\,\\,\\,\\, $ --[Wikipedia](https://en.wikipedia.org/wiki/Graph_(discrete_mathematics))\n\"\"\"\n\n# ╔═╡ 79f9cf36-1f2c-456f-a71c-d0bac25a5aad\nmd\"For an example, lets take a look ath the below graph.\"\n\n# ╔═╡ 87f96fa0-c27e-45a6-8452-f67f952b737d\nResource(\"https://upload.wikimedia.org/wikipedia/commons/thumb/b/bf/Undirected.svg/220px-Undirected.svg.png\")\n\n# ╔═╡ 1d009804-1858-4109-a75b-16ae5523bfa2\nmd\"The three blue circles are **nodes**. While the lines connecting them are **edges**\"\n\n# ╔═╡ cdf1583c-6964-4064-9434-8be1d4c397d9\nmd\"Its an **undirected graph**, since the edges have no orientation.\"\n\n# ╔═╡ 68d60332-1aa2-4668-bfbe-fefa588fe582\nmd\"Lets try making one in LightGraphs\"\n\n# ╔═╡ b7c3798f-5fbb-4a87-8299-28e4c4c28fec\nlet\n\tg = SimpleGraph(3) #Makes an undirected graph\n\tadd_edge!(g, 1, 2); #Adding an edge from 1 to 2\n\tadd_edge!(g, 2, 3);\n\tadd_edge!(g, 1, 3);\n\tgplot(g)\nend\n\n# ╔═╡ cf8483c1-d805-4e99-b2f4-7dce289fa587\nq = [[1,1,1], [1,1,1]]\n\n# ╔═╡ e07b27ab-b1c5-41c6-b932-641bcd893324\nappend!(q[1], 1)\n\n# ╔═╡ 236e38f8-acea-4d03-a34d-d502e6e8e32d\nmd\"\"\"\nA direct graph is one where the edges have an orientation. From the above example, assume A owes money to B and B owes money to C.\n\"\"\"\n\n# ╔═╡ a686295f-6cf1-4da4-be0e-b1935892fc44\nlet\n\tg = SimpleDiGraph(3) #Makes an undirected graph\n\tadd_edge!(g, 1, 2); #Adding an edge from 1 to 2\n\tadd_edge!(g, 2, 3);\n\tgplot(g, nodelabel=[\"A\", \"B\", \"C\"]) \nend\n\n# ╔═╡ 26506fba-3d46-49e5-822b-725741003e17\nmd\"\nA **Weighted Graph** is a graph where weights are assigned to each edge.\nAssume, in the above example, A owes `` \\$54 `` to B and B owes `` \\$89 `` to C. \n\"\n\n# ╔═╡ df7e83b8-eb8b-411c-be35-07d5770fe9b1\nlet\n\tsources = [1,2]\n\tdestinations = [2,3]\n\tweights = [54, 89]\n\tnodelabel=[\"A\", \"B\", \"C\"]\n\tg = SimpleWeightedDiGraph(sources, destinations, weights) #Makes an undirected graph\n\tgplot(g, nodelabel=[\"A\", \"B\", \"C\"], edgelabel=[\"5𝟦\", \"𝟾𝟫\"])\nend\n\n# ╔═╡ 0119dc9f-8ccf-4776-a7e9-5f61b063d509\nmd\"\n### Try yourself\n\"\n\n# ╔═╡ 0db8895b-cb4d-4a3d-9bae-1fd0f460fafe\nmd\"\"\"\n1. Look for different types of graphs on the [wikipedia page](https://en.wikipedia.org/wiki/Graph_(discrete_mathematics)). Try making and visualizing them using [LightGraphs](https://github.com/JuliaGraphs/LightGraphs.jl)+[GraphPlot](https://github.com/JuliaGraphs/GraphPlot.jl).\n2. Try visualizing both the structured probablistic models examples.\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─ea0dc819-e860-4863-b9ea-81d12d92c4ab\n# ╟─e84a31da-8ce7-11eb-1b6a-0f1431d8c96e\n# ╟─48727d46-8cf8-11eb-25a0-73c248dab2da\n# ╟─af0e8170-9163-11eb-2e48-4dcc7c853090\n# ╟─dde86ab8-9163-11eb-173a-0d0fe5d297ad\n# ╟─51cf0da0-8cf8-11eb-13d1-53bb6bd3892a\n# ╟─5c51aa26-8cf8-11eb-0add-a1b7f41216f6\n# ╟─72edf972-8cf8-11eb-2441-75b6edc68854\n# ╠═c26eb560-9167-11eb-02d3-8b4212f378e6\n# ╟─6d6ead0a-9170-11eb-049b-2dfaf08ba40e\n# ╟─5e59cfb6-9170-11eb-0215-2390218aac63\n# ╠═6fd98eb6-916b-11eb-19a4-5368d9cc2b31\n# ╟─980bb77e-9170-11eb-3d61-19044344aa37\n# ╠═0c0ac120-916b-11eb-1029-cb8615bca99c\n# ╟─4ef0b236-9172-11eb-0813-e12589886a31\n# ╠═47f31ab4-9172-11eb-1bc4-f916418a47db\n# ╟─eced0ac6-9171-11eb-0f2a-cd5fa1bd818d\n# ╟─3f168c24-9173-11eb-1cf8-7338a422ff69\n# ╟─f6b2bf60-9173-11eb-145d-2f1f47b7eb30\n# ╟─79557c7c-9173-11eb-3c53-4fa9ad783e8a\n# ╟─35cfa732-9238-11eb-3f47-0d921b5d6eeb\n# ╟─b4374be0-9173-11eb-09d2-cbab6657cdaf\n# ╟─70e11290-923b-11eb-2365-f58a04d0f844\n# ╟─758a1460-8cf8-11eb-0ab7-7dfcfac203f9\n# ╟─806857e8-8cf8-11eb-3756-bff672168730\n# ╟─7bc55826-92de-11eb-258b-31d565464c56\n# ╟─a2128026-92de-11eb-102f-d924f0ceee27\n# ╟─749c569c-92e0-11eb-14c5-8301f513cdad\n# ╟─e0c4991e-92e1-11eb-1cc3-31c0fae42abf\n# ╠═1c95027c-930e-11eb-2a05-8322da402360\n# ╠═a6073126-930c-11eb-2785-79a71976e4d5\n# ╠═f9c89c3c-930c-11eb-278d-9bf0ee036c67\n# ╟─16b2a794-9311-11eb-3604-f1efc56fe690\n# ╠═332020be-9311-11eb-16c5-03374a5c7112\n# ╠═420afebe-9311-11eb-1cd2-2b0ddbb58716\n# ╠═5e578c2c-9311-11eb-22a0-2f57b00d7958\n# ╟─55eee81a-f8cc-4503-adce-3153342baf00\n# ╟─6f8a52ba-f673-47e0-890a-83a7b2e338d9\n# ╟─48bffce6-6ba1-44b8-bd70-ff11b708a23d\n# ╟─b5b45043-cbea-4848-862c-5b39bf6fd2bb\n# ╟─a75111b9-063a-4158-a78f-7f1107db028c\n# ╟─1683d427-5433-4d85-b65e-4b86cc61af14\n# ╟─3a2c5692-ee39-4f26-b094-a6094dd88b68\n# ╠═02d67371-b1e3-4ac9-b4d1-cdca1c85bd18\n# ╟─f5af9c66-ee47-4384-a68a-60711f966557\n# ╠═203d14b2-d7b6-4ac4-b1f8-421a2e80c51a\n# ╠═e18cdf58-13a9-4f98-ab97-6c5cdcc3ee7c\n# ╟─a0dfaf17-1cbf-45e1-be14-8302f68b2b6a\n# ╠═052c45aa-1735-4cba-b911-28c81d7e2850\n# ╠═f2a98e2b-328c-4a8d-bfeb-e5dd7cbb3014\n# ╟─6f8963c0-8c36-43ab-9a6d-e814aaba2d81\n# ╠═4ee83e69-db95-4724-b963-de7dd2445b02\n# ╟─1de8aded-81e9-4f87-baa2-c571f31cb31b\n# ╟─d038c84a-af8b-4da7-974d-0c023e40fcfb\n# ╠═d5b23092-a9fe-44c3-ae9d-bd7186cbdf07\n# ╠═f7f637b6-2f6e-47dc-b1ca-baf1669f6681\n# ╟─7cff52e3-5063-47a6-8d0e-03c333ee401b\n# ╠═0235d738-c7e4-48b0-b7fd-9b6d31a2bbbc\n# ╠═0b67edef-d59a-44ed-9226-3c857e78b0e7\n# ╠═d3faf6d4-6584-476f-bb62-d34ccb701bc4\n# ╟─ce6a1226-923c-11eb-074b-6d708b9773ff\n# ╠═7c8394db-271e-4d0b-a3db-b3e3a659ec0a\n# ╠═6489f711-b127-4283-8171-9478d4c48a0c\n# ╠═fc4769e0-f6c1-473c-b675-13ec737a5572\n# ╠═5a8346f0-ea6f-43e6-916b-041ee5220367\n# ╠═e1be7ec4-6121-401b-b338-37cd34591586\n# ╟─251004a8-fb13-4e92-8c08-27286351753f\n# ╟─291d53fc-93ec-4926-80ab-a276b025ef82\n# ╠═fd6e90a0-36f9-4055-a69b-5809cd05b837\n# ╟─3d141deb-bf7c-4ef3-88db-1b7e31ba6033\n# ╟─d4bf1c39-6281-4ddf-b87e-bf4e3cefea3e\n# ╟─747b4b5b-98e7-4171-bfb0-b5acc792eda3\n# ╠═75b07946-f493-49f0-928c-afee87fb22ad\n# ╟─4cf8dd4f-af3b-421f-ab11-e3036d60cc29\n# ╟─2454387d-df18-4932-ad48-691e5583a21e\n# ╠═50920106-7a39-4563-a1c0-cdd5d43ebb37\n# ╟─e8140a83-904a-46b6-a8e8-8a7151b85c43\n# ╠═bf7ce886-e6ac-45e7-a0f5-98e36c8974c7\n# ╟─76dc38a7-d06e-41c4-8da5-b15e3ebe54de\n# ╠═7a514f20-e7cc-43da-96f6-cc4f7244166b\n# ╟─79f9cf36-1f2c-456f-a71c-d0bac25a5aad\n# ╠═87f96fa0-c27e-45a6-8452-f67f952b737d\n# ╟─1d009804-1858-4109-a75b-16ae5523bfa2\n# ╟─cdf1583c-6964-4064-9434-8be1d4c397d9\n# ╟─68d60332-1aa2-4668-bfbe-fefa588fe582\n# ╠═b7c3798f-5fbb-4a87-8299-28e4c4c28fec\n# ╠═cf8483c1-d805-4e99-b2f4-7dce289fa587\n# ╠═e07b27ab-b1c5-41c6-b932-641bcd893324\n# ╟─236e38f8-acea-4d03-a34d-d502e6e8e32d\n# ╠═a686295f-6cf1-4da4-be0e-b1935892fc44\n# ╟─26506fba-3d46-49e5-822b-725741003e17\n# ╠═c7a5ab0b-aba0-4b54-abe9-702b0bad4a8e\n# ╠═df7e83b8-eb8b-411c-be35-07d5770fe9b1\n# ╟─0119dc9f-8ccf-4776-a7e9-5f61b063d509\n# ╟─0db8895b-cb4d-4a3d-9bae-1fd0f460fafe\n", "meta": {"hexsha": "651710dee0e8867b5615d27ba32d870fd565b61c", "size": 24340, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "PlutoNotebooks/Probability and Information Theory.jl", "max_stars_repo_name": "VarLad/MLTutorials", "max_stars_repo_head_hexsha": "e90de1f631b7a8e3b8febf86b6a7505c6e094d90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PlutoNotebooks/Probability and Information Theory.jl", "max_issues_repo_name": "VarLad/MLTutorials", "max_issues_repo_head_hexsha": "e90de1f631b7a8e3b8febf86b6a7505c6e094d90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PlutoNotebooks/Probability and Information Theory.jl", "max_forks_repo_name": "VarLad/MLTutorials", "max_forks_repo_head_hexsha": "e90de1f631b7a8e3b8febf86b6a7505c6e094d90", "max_forks_repo_licenses": ["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.298013245, "max_line_length": 899, "alphanum_fraction": 0.7238290879, "num_tokens": 10269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464795, "lm_q2_score": 0.9161096135894201, "lm_q1q2_score": 0.8403497870887248}} {"text": "export Eulerian\n\"\"\"\n`Eulerian(n,k)` returns the number of permutations of `{1,2,...,n}`\nwith `k` ascents.\n\"\"\"\nfunction Eulerian(n::Integer, k::Integer)::BigInt\n @assert (n>=0 && k>=0) \"$n,$k must both be nonnegative\"\n\n if n==0\n return big(0)\n end\n\n if k>n || k==0\n return big(0)\n end\n\n if n < 2\n return big(1)\n end\n\n if k==n # includes the case n=k=0\n return big(1)\n end\n\n if k==1\n return big(1)\n end\n\n if _has(Eulerian,(n,k))\n return _get(Eulerian,(n,k))\n end\n\n val = (n-k+1)*Eulerian(n-1,k-1) + k*Eulerian(n-1,k)\n _save(Eulerian,(n,k),val)\n return val\nend\n\n\n_make(Eulerian,Tuple{Integer,Integer})\n", "meta": {"hexsha": "256cd8d28b15ceb266a96c30fadedda0c981d17b", "size": 694, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/eulerian.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/BigCombinatorics.jl-7b33fef7-ef1d-5d54-bb67-cf96d4c8a166", "max_stars_repo_head_hexsha": "ff20dad53db78a62c1e0f9e0c1fa0530bc854d65", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/eulerian.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/BigCombinatorics.jl-7b33fef7-ef1d-5d54-bb67-cf96d4c8a166", "max_issues_repo_head_hexsha": "ff20dad53db78a62c1e0f9e0c1fa0530bc854d65", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/eulerian.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/BigCombinatorics.jl-7b33fef7-ef1d-5d54-bb67-cf96d4c8a166", "max_forks_repo_head_hexsha": "ff20dad53db78a62c1e0f9e0c1fa0530bc854d65", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.35, "max_line_length": 67, "alphanum_fraction": 0.5446685879, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.96323053709097, "lm_q2_score": 0.8723473796562744, "lm_q1q2_score": 0.8402716350362135}} {"text": "#unit step function\r\nfunction u(t::Float64)::Float64 #unit step function\r\n return ifelse( t < 0, zero(t), one(t) )\r\nend\r\n\r\n#unnormalized Gaussian function\r\nfunction 𝒩ᵤ(x::Float64; μ::Float64, σ::Float64)::Float64\r\n return exp(-0.5 * ((x - μ) / σ)^2)\r\nend\r\n\r\n#normalized Gaussian function\r\nfunction 𝒩(x::Float64; μ::Float64, σ::Float64)::Float64\r\n return 1 / (σ * sqrt(2 * π)) * exp(-0.5 * ((x - μ) / σ)^2)\r\nend\r\n\r\n#Dirac delta (Gaussian approximation) amplitude normalized\r\nfunction δn(t::Float64,σ::Float64=1.0e-11)::Float64\r\n return 𝒩ᵤ(t, μ=0.0, σ=σ)\r\nend\r\n\r\n#Dirac delta (Gaussian approximation) unit area\r\nfunction δ(t::Float64,σ::Float64=1.0e-10)::Float64\r\n return 𝒩(t, μ=0.0, σ=σ)\r\nend\r\n", "meta": {"hexsha": "66128cfb69f06212af24d1cbee1aab38b6479d83", "size": 706, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/AuxiliaryFunctions/utilitiesFunctions.jl", "max_stars_repo_name": "mantodas/LTVmodel.jl", "max_stars_repo_head_hexsha": "635d19b9f729c1f8020f6fb9b40d0084fe5c0686", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/AuxiliaryFunctions/utilitiesFunctions.jl", "max_issues_repo_name": "mantodas/LTVmodel.jl", "max_issues_repo_head_hexsha": "635d19b9f729c1f8020f6fb9b40d0084fe5c0686", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/AuxiliaryFunctions/utilitiesFunctions.jl", "max_forks_repo_name": "mantodas/LTVmodel.jl", "max_forks_repo_head_hexsha": "635d19b9f729c1f8020f6fb9b40d0084fe5c0686", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.24, "max_line_length": 63, "alphanum_fraction": 0.6487252125, "num_tokens": 259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660976007596, "lm_q2_score": 0.8807970873650401, "lm_q1q2_score": 0.8402505602117426}} {"text": "\n\"\"\"\n abs_val(num)\n\nProgram to find the absolute value of a number\n\n# Example\n```julia\nabs_val(-100) # returns 100\nabs_val(0) # returns 0\nabs(123.1) # returns 123.1\n-1000 == abs_val(-1000) #returns false\n1000 == abs_val(1000) #returns true\n```\n\nContributed By:- [Ashwani Rathee](https://github.com/ashwani-rathee) and [Rratic](https://github.com/Rratic)\n\"\"\"\nfunction abs_val(num::N)where N<:Real\n return num < 0 ? -num : num\nend\n\n\n\"\"\"\n abs_max(x)\n\nProgram to find the max absolute value in a vector\n\n# Example\n```julia\nabs_max([1,3,4]) # returns 4\nabs_max([-3,1,2]) # returns -3\nabs_max([-7,-3,6]) #returns -7\n```\n\nContributed By:- [Ashwani Rathee](https://github.com/ashwani-rathee) and [Rratic](https://github.com/Rratic)\n\"\"\"\nfunction abs_max(x::Vector{N})where N<:Real\n _max=x[1]\n for i in x\n if abs(i)>abs(_max) _max=i end\n end\n return _max\nend\n\n\"\"\"\n abs_min(num)\n\nProgram to find the min absolute value in a vector\n\n# Example\n```julia\nabs_min([1,3,4]) # returns 1\nabs_min([-3,1,2]) # returns 1\nabs_min([-7,-3,6]) #returns -3\n```\n\nContributed By:- [Ashwani Rathee](https://github.com/ashwani-rathee) and [Rratic](https://github.com/Rratic)\n\"\"\"\nfunction abs_min(x::Vector{N})where N<:Real\n _min=x[1]\n for i in x\n if abs(i) 0)\n model = Model(optimizer)\n @variable(model, y[1:n] >= 0)\n @constraint(model, sum(y) == 1)\n @objective(model, Min, sum((y .- x) .^ 2))\n optimize!(model)\n return value.(y)\nend;\n\nconditions(x, y) = simplex_projection(y - 0.1 * 2(y - x)) - y;\n\nimplicit = ImplicitFunction(forward, conditions);\n\n# ## Testing\n\n# Let us study the behavior of our implicit function.\n\nx = rand(5)\n\n# We can see that the forward pass computes the projection correctly, at least up to numerical precision.\n\nhcat(simplex_projection(x), implicit(x))\n\n# And the same goes for the Jacobian.\n\ncat(Zygote.jacobian(simplex_projection, x)[1], Zygote.jacobian(implicit, x)[1]; dims=3)\n\n# The following tests are not included in the docs. #src\n\n@test implicit(x) ≈ simplex_projection(x) atol = 1e-5 #src\n\n@testset verbose = true \"ChainRules\" begin #src\n test_rrule(simplex_projection, x; check_inferred=false) #src\n test_rrule(implicit, x; atol=1e-2, check_inferred=false) #src\nend #src\n", "meta": {"hexsha": "53291502fcc0473c9a3b1f9278a5a8b6ef8304cd", "size": 2630, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/2_constrained_optimization.jl", "max_stars_repo_name": "gdalle/ImplicitDifferentiation.jl", "max_stars_repo_head_hexsha": "19f68d94c754e2bb2ef370e31b0b6aa2ac1a00f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2022-03-29T14:06:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:10:49.000Z", "max_issues_repo_path": "test/2_constrained_optimization.jl", "max_issues_repo_name": "gdalle/ImplicitDifferentiation.jl", "max_issues_repo_head_hexsha": "19f68d94c754e2bb2ef370e31b0b6aa2ac1a00f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2022-03-30T10:29:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T07:23:57.000Z", "max_forks_repo_path": "test/2_constrained_optimization.jl", "max_forks_repo_name": "gdalle/ImplicitDifferentiation.jl", "max_forks_repo_head_hexsha": "19f68d94c754e2bb2ef370e31b0b6aa2ac1a00f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0666666667, "max_line_length": 173, "alphanum_fraction": 0.7209125475, "num_tokens": 726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109742068042, "lm_q2_score": 0.8840392725805822, "lm_q1q2_score": 0.8402006262903857}} {"text": "\"\"\"\nJulia program to implement Maximum Sum Decreasing Subsequence\nIn this problem, given an array we have to find the maximum sum an decreasing subsequence of that array can make.\nThis problem is a slight modification to the Longest Decreasing subsequence problem.\nThe problem can be solved using Dynamic Programming\n\"\"\"\n\n\nfunction maximum_sum_decreasing_subsequence(arr, n)\n max_sum = 0\n dp = Int[]\n\n # Initialize the dp array with the array values, as the maximum sum \n # at each point is atleast as the value at that point \n for i in 1:n\n push!(dp, arr[i])\n end\n\n for i in 1:n\n for j in 1:(i-1)\n if(arr[i] < arr[j] && dp[i] < dp[j] + arr[i])\n dp[i] = dp[j] + arr[i]\n end\n end\n end\n\n # Now Find the maximum element in the dp array \n max_sum = findmax(dp)[1]\n return max_sum\n\nend\n\n\nprint(\"What is the length of the array? \")\nn = readline()\nn = parse(Int, n)\nif (n <= 0)\n println(\"No numbers present in the array!!!\")\n exit()\nend\narr = Int[]\nprint(\"Enter the numbers: \")\narr = [parse(Int, num) for num in split(readline())]\nres = maximum_sum_decreasing_subsequence(arr, n)\nprint(\"The maximum sum of an decreasing subsequence of the given array is $res\")\n\n\n\"\"\"\nTime Complexity: O(num ^ 2), where 'num' is the size of the given array\nSpace Complexity: O(num)\n\nSAMPLE INPUT AND OUTPUT\n\nSAMPLE 1\n\nWhat is the length of the array? 10\nEnter the numbers: 23 14 5 84 24 222 321 43 123 432\nThe maximum sum of an decreasing subsequence of the given array is 444\n\nSAMPLE 2\n\nWhat is the length of the array? 5\nEnter the numbers: 5 4 3 2 1\nThe maximum sum of an decreasing subsequence of the given array is 15\n\"\"\"\n", "meta": {"hexsha": "37a5526d15d03cb298a0ea85853cd27ec0af55c2", "size": 1702, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/dp/maximum_sum_decreasing_subsequence.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/dp/maximum_sum_decreasing_subsequence.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/dp/maximum_sum_decreasing_subsequence.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": 25.7878787879, "max_line_length": 113, "alphanum_fraction": 0.6745005875, "num_tokens": 467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.8991213745668094, "lm_q1q2_score": 0.8401346629323789}} {"text": "using DifferentialEquations\nusing Plots\n\n\nsir_ode = @ode_def SIRModel begin\n dS = -β*S*I\n dI = β*S*I-γ*I\n dR = γ*I\n end β γ\n\nparms = [0.1,0.05]\ninit = [0.99,0.01,0.0]\ntspan = (0.0,200.0)\n\nsir_prob = ODEProblem(sir_ode,init,tspan,parms)\n\nsir_sol = solve(sir_prob,saveat = 0.1);\n\n# Plot\nplot(sir_sol,xlabel=\"Time\",ylabel=\"Number\")\n\nfunction sir_ode2(du,u,p,t)\n S,I,R = u\n b,g = p\n du[1] = -b*S*I\n du[2] = b*S*I-g*I\n du[3] = g*I\nend\n\nparms = [0.1,0.05]\ninit = [0.99,0.01,0.0]\ntspan = (0.0,200.0)\nsir_prob2 = ODEProblem(sir_ode2,init,tspan,parms)\nsir_sol = solve(sir_prob2,saveat = 0.1)\n", "meta": {"hexsha": "bf6061b9a6cc5637cf9cb14714e1a404f956fd2a", "size": 610, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "models/simple_deterministic_models/sir/sir.jl", "max_stars_repo_name": "epimodels/epicookbook", "max_stars_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/simple_deterministic_models/sir/sir.jl", "max_issues_repo_name": "epimodels/epicookbook", "max_issues_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/simple_deterministic_models/sir/sir.jl", "max_forks_repo_name": "epimodels/epicookbook", "max_forks_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-10T12:46:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-10T12:46:31.000Z", "avg_line_length": 17.4285714286, "max_line_length": 49, "alphanum_fraction": 0.6131147541, "num_tokens": 277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.966914018751051, "lm_q2_score": 0.8688267762381844, "lm_q1q2_score": 0.840080789810983}} {"text": "### A Pluto.jl notebook ###\n# v0.14.7\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 2fdecb39-bff4-4f3c-b3f5-35438541a29d\n# import necessary libraries\nusing Random\n\n# ╔═╡ 29802e3a-8dfe-41c7-a25e-2f0961949854\nusing Statistics\n\n# ╔═╡ cba2ccb0-c5a2-11eb-11be-41eb0278cb72\nmd\"\"\"\n### Logistic Regression\n\n[Reference 1](https://towardsdatascience.com/introduction-to-logistic-regression-66248243c148)\\\n[Reference 2](https://towardsdatascience.com/building-a-logistic-regression-in-python-301d27367c24)\\\n[ML Glossary](https://ml-cheatsheet.readthedocs.io/en/latest/logistic_regression.html) \n\n#### Sigmoid Function\n\n$$f(x)=\\frac{1}{1+e^{-(x)}}$$\n\nwhich maps predicted values to probabilities\n\n#### Hypothesis Representation\n\n$$Z=\\beta_0+\\beta_1X$$\n\n$$h\\Theta(x)=\\text{sigmoid}(Z)=\\frac{1}{1+e^{-(\\beta_0+\\beta_1X)}}$$\n\n#### Cost Function\n\n$$\\text{Cost}(h_\\theta(x),y)=\n \\begin{cases}\n -\\log(h_\\theta(x)) & \\quad \\text{if } y = 1\\\\\n -\\log(1-h_\\theta(x)) & \\quad \\text{if } y = 0\n \\end{cases}$$\n\nwhich is also\n\n$$J(\\theta)=-\\frac{1}{m}\\sum \\Big[ y^{(i)}\\log(h\\theta(x^{(i)})) + (1-y^{(i)})\\log(1-h\\theta(x^{(i)})) \\Big]$$\n\nwhich should be minimized\n\n#### Gradient Descent\n\n$$\\theta_j := \\theta_j - \\alpha\\frac{\\partial}{\\partial\\theta_j}J(\\theta)$$\n\nIn this case:\n\n$$\\theta_j := \\theta_j - \\alpha\\sum^m_{i=1}(h_\\theta(x^{(i)})-y^{(i)})x_j^{(i)}$$\n\"\"\"\n\n# ╔═╡ 3761501d-f02e-41cb-9003-74cb68283d74\nbegin\nX_data = rand(Float32, (100, 5))\nY_data = rand(0:1, 100)\nsize(X_data), size(Y_data)\nend\n\n# ╔═╡ ad8d7761-f843-46f4-a7c6-4a5442d1e17a\nfunction sigmoid(Z::Number)::Float32\n k = 1 + MathConstants.e ^ (-Float32(Z))\n return 1 / k\nend\n\n# ╔═╡ d457cb21-4e23-4527-a2e4-9654579f714a\ntypeof(X_data)\n\n# ╔═╡ fcf0ea6c-72c4-40b9-bca9-d1ad40b67dd2\nfunction scale(X::Array)::Array\n @assert ndims(X) == 2\n u = mean(X, dims=1) # compute mean\n s = std(X, dims=1) # compute standard deviation\n res = (X .- u) ./ s\n return res\nend\n\n# ╔═╡ c7a7f2af-fa56-4bbf-afa1-a64b1af5b78d\nX_data_scaled = scale(X_data);\n\n# ╔═╡ 1a17435a-484c-4ea8-809b-1d3b0a548288\nmean(X_data_scaled, dims=1)\n\n# ╔═╡ 5a87d92e-643f-4032-a6fb-226ce7cab2af\nstd(X_data_scaled, dims=1)\n\n# ╔═╡ 0890963a-806a-456a-89cf-ad68b11b41c3\n# update sigmoid function\nfunction sigmoid(Z::Array)::Array\n denom = 1 .+ (MathConstants.e .^ (-Z))\n return 1 ./ denom\nend\n\n# ╔═╡ bf7c00f8-1a1b-4010-b2a9-c02f33351bd5\n# test sigmoid function\nsigmoid(1234)\n\n# ╔═╡ 4c1f5e23-a985-4f8f-81f5-6b780412a4ad\nsigmoid(0)\n\n# ╔═╡ 7fa3c5e2-8431-49d7-94c2-d3885a6a79f6\nsigmoid(0.123)\n\n# ╔═╡ ed47d544-9ccd-47ff-bf2a-01a9b2b365b0\n# test it\nsigmoid(X_data_scaled)\n\n# ╔═╡ 8eaa7843-aa2b-4af3-9e32-629629d0fc36\nbegin\nbeta = randn(size(X_data)[2]+1)\nsize(beta)\nend\n\n# ╔═╡ e4d93713-c75d-4cbf-a31c-a9194f25280d\nfunction cost(X::Array, y::Array, beta::Array)::AbstractFloat\n @assert ndims(X) == 2\n @assert ndims(y) == 1\n @assert ndims(beta) == 1\n @assert size(X) == (size(y)[1], size(beta)[1]-1)\n m = size(X)[1]\n X_extended = hcat(X, ones(size(X)[1]))\n X_combined = X_extended * reshape(beta, (size(beta)[1], 1))\n prob = sigmoid(X_combined)\n y_prep = reshape(y, (size(y)[1], 1))\n vec = y_prep .* (log.(prob)) .+ (1 .- y_prep) .* (log.(1 .- prob))\n cost = -1 / float(m) * sum(vec)\n return cost\nend\n\n# ╔═╡ 4ae75dea-6fc1-4d10-8c63-176a01193caf\n# try it\ncost(X_data_scaled, Y_data, beta)\n\n# ╔═╡ 83a969a4-2704-421e-ba02-70875e5b22fc\n# prediction function\nfunction predict_proba(X::Array, beta::Array)::Array\n @assert ndims(X) == 2\n @assert ndims(beta) == 1\n @assert size(X)[2] == size(beta)[1]-1\n X_extended = hcat(X, ones(size(X)[1]))\n X_combined = X_extended * reshape(beta, (size(beta)[1], 1))\n prob = sigmoid(X_combined)\n prob = [(prob...)...] # flatten to 1d array\n return prob\nend\n\n# ╔═╡ a04e19f3-8c20-47b4-b30a-ccc0696bf54b\npredict_proba(X_data_scaled, beta)\n\n# ╔═╡ 7d94d627-941c-41fb-8fce-cc0da6972f74\nfunction predict(X::Array, beta::Array)::Array\n @assert ndims(X) == 2\n @assert ndims(beta) == 1\n @assert size(X)[2] == size(beta)[1]-1\n X_extended = hcat(X, ones(size(X)[1]))\n X_combined = X_extended * reshape(beta, (size(beta)[1], 1))\n prob = sigmoid(X_combined)\n prob = [(prob...)...] # flatten to 1d array\n prob = map(m -> m >= 0.5 ? 1 : 0, prob)\n return prob\nend\n\n# ╔═╡ 6418946f-eff9-43fd-8654-415fc41579b5\npredict(X_data_scaled, beta)\n\n# ╔═╡ 4c6ee096-98f5-48b8-9977-f2485365759c\n# inplace learning function (Gradient Descent)\nfunction learn!(X::Array, y::Array, beta::Array, alpha::AbstractFloat)\n @assert ndims(X) == 2\n @assert ndims(y) == 1\n @assert ndims(beta) == 1\n @assert size(X) == (size(y)[1], size(beta)[1]-1)\n predictions = predict_proba(X, beta)\n offset = predictions .- y\n offset = reshape(offset, (size(offset)[1], 1))\n X_extended = hcat(X, ones(size(X)[1]))\n gradients = X_extended' * offset\n gradients = gradients ./ size(X)[1]\n gradients = gradients .* alpha\n beta .= beta .- [(gradients...)...]\n return nothing\nend\n\n# ╔═╡ addad88e-317d-4086-a5e4-a9682f80f54a\nbeta\n\n# ╔═╡ 2c3b2fed-e9aa-44b5-a12d-40281ae487d9\nlearn!(X_data_scaled, Y_data, beta, 0.01)\n\n# ╔═╡ 63ab48c3-8c92-4935-a4ce-36a7049e5c86\nbeta\n\n# ╔═╡ c0f88234-87ec-41ca-8a90-df7d89997090\n# define the logistic regression function\nfunction train(X::Array, y::Array; learning_rate::AbstractFloat=0.01, max_iter::Integer=10, return_all::Bool=false)::Array\n @assert ndims(X) == 2\n @assert ndims(y) == 1\n @assert size(X)[1] == size(y)[1]\n @assert max_iter >= 0\n beta = Random.randn(size(X)[2]+1)\n res = nothing\n if return_all\n res = reshape(beta, (1, size(beta)[1]))\n else\n res = beta\n end\n for i = 1:max_iter\n if return_all\n beta = learn(X, y, beta, learning_rate)\n res = cat(res, reshape(beta, (1, size(beta)[1])), dims=1)\n else\n learn!(X, y, beta, learning_rate)\n res .= beta\n end\n end\n return res\nend\n\n# ╔═╡ addd77a3-6d60-4387-8bad-65c55fc0171e\n# accuracy function\nfunction accuracy(y_pred::Array, y_real::Array)::AbstractFloat\n @assert ndims(y_pred) == ndims(y_real) == 1\n @assert size(y_pred) == size(y_real)\n sum = 0\n for (m, n) in zip(y_pred, y_real)\n if m == n\n sum += 1\n end\n end\n return sum / size(y_pred)[1]\nend\n\n# ╔═╡ eb2362a6-8d78-4f38-8b53-a1b9a1f54820\naccuracy(predict(X_data_scaled, beta), Y_data)\n\n# ╔═╡ acfefff5-53c3-421c-84c8-441007cbba2e\naccuracy(predict(X_data_scaled, train(X_data_scaled, Y_data, max_iter=100, learning_rate=0.5)), Y_data)\n\n# ╔═╡ 8d99210c-eabe-4fe7-a529-4e83be5e6cf8\nmd\"\"\"\nSince it is linear model, we should not expect it to have a high accuracy on a completely randomly generated dataset\\\nBut we can see the improvements\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─cba2ccb0-c5a2-11eb-11be-41eb0278cb72\n# ╠═2fdecb39-bff4-4f3c-b3f5-35438541a29d\n# ╠═3761501d-f02e-41cb-9003-74cb68283d74\n# ╠═ad8d7761-f843-46f4-a7c6-4a5442d1e17a\n# ╠═bf7c00f8-1a1b-4010-b2a9-c02f33351bd5\n# ╠═4c1f5e23-a985-4f8f-81f5-6b780412a4ad\n# ╠═7fa3c5e2-8431-49d7-94c2-d3885a6a79f6\n# ╠═d457cb21-4e23-4527-a2e4-9654579f714a\n# ╠═29802e3a-8dfe-41c7-a25e-2f0961949854\n# ╠═fcf0ea6c-72c4-40b9-bca9-d1ad40b67dd2\n# ╠═c7a7f2af-fa56-4bbf-afa1-a64b1af5b78d\n# ╠═1a17435a-484c-4ea8-809b-1d3b0a548288\n# ╠═5a87d92e-643f-4032-a6fb-226ce7cab2af\n# ╠═0890963a-806a-456a-89cf-ad68b11b41c3\n# ╠═ed47d544-9ccd-47ff-bf2a-01a9b2b365b0\n# ╠═8eaa7843-aa2b-4af3-9e32-629629d0fc36\n# ╠═e4d93713-c75d-4cbf-a31c-a9194f25280d\n# ╠═4ae75dea-6fc1-4d10-8c63-176a01193caf\n# ╠═83a969a4-2704-421e-ba02-70875e5b22fc\n# ╠═a04e19f3-8c20-47b4-b30a-ccc0696bf54b\n# ╠═7d94d627-941c-41fb-8fce-cc0da6972f74\n# ╠═6418946f-eff9-43fd-8654-415fc41579b5\n# ╠═4c6ee096-98f5-48b8-9977-f2485365759c\n# ╠═addad88e-317d-4086-a5e4-a9682f80f54a\n# ╠═2c3b2fed-e9aa-44b5-a12d-40281ae487d9\n# ╠═63ab48c3-8c92-4935-a4ce-36a7049e5c86\n# ╠═c0f88234-87ec-41ca-8a90-df7d89997090\n# ╠═addd77a3-6d60-4387-8bad-65c55fc0171e\n# ╠═eb2362a6-8d78-4f38-8b53-a1b9a1f54820\n# ╠═acfefff5-53c3-421c-84c8-441007cbba2e\n# ╟─8d99210c-eabe-4fe7-a529-4e83be5e6cf8\n", "meta": {"hexsha": "4361b1f498200161f60bba8af74387779e299301", "size": 8045, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Logistic_Regression/notebook.jl", "max_stars_repo_name": "teamclouday/JuliaLearn", "max_stars_repo_head_hexsha": "841b4b305bd485c789616585c6d10960e6db1ee5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Logistic_Regression/notebook.jl", "max_issues_repo_name": "teamclouday/JuliaLearn", "max_issues_repo_head_hexsha": "841b4b305bd485c789616585c6d10960e6db1ee5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Logistic_Regression/notebook.jl", "max_forks_repo_name": "teamclouday/JuliaLearn", "max_forks_repo_head_hexsha": "841b4b305bd485c789616585c6d10960e6db1ee5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6298932384, "max_line_length": 122, "alphanum_fraction": 0.66923555, "num_tokens": 3554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542852576265, "lm_q2_score": 0.8757870029950159, "lm_q1q2_score": 0.8400148568956032}} {"text": "\"\"\"\n\n fibonacci(iterations, [num1, num2])\n\nBuilds a series of fibonacci numbers `n` iterations in a vector\n \n Args: iterations: length of fibonacci sequence to be calculated\n \n Optional: num1 and num2 default to 0 and 1 respectively, the starting numbers of the sequence.\n \n# Examples\n```julia-repl\n\n# one argument - starting values are 0 and 1\njulia> fibonacci(10)\n12-element Array{Int64,1}:\n 0\n 1\n 1\n 2\n 3\n 5\n 8\n 13\n 21\n 34\n 55\n 89\n\n# two arguments - starting values are 4 and 1\njulia> fibonacci(10, 4)\n12-element Array{BigInt,1}:\n 4\n 1\n 5\n 6\n 11\n 17\n 28\n 45\n 73\n 118\n 191\n 309\n\n# Three arguments - starting values are 3 and -1\njulia> fibonacci(10, 3, -1)\n12-element Array{Int64,1}:\n 3\n -1\n 2\n 1\n 3\n 4\n 7\n 11\n 18\n 29\n 47\n 76\n ```\n \"\"\"\nfunction fibonacci(iterations, num1=0, num2=1)\n arr = (BigInt)[num1, num2]\n for i in 1:iterations\n push!(arr, +(arr[end], arr[end - 1]))\n end\n return arr\nend\n", "meta": {"hexsha": "dc29fb1ea4dc996af300fa2833244f96770668ee", "size": 963, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "FibonacciVector.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": "FibonacciVector.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": "FibonacciVector.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": 13.7571428571, "max_line_length": 98, "alphanum_fraction": 0.6251298027, "num_tokens": 366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107878954106, "lm_q2_score": 0.8962513634345444, "lm_q1q2_score": 0.8399764464768253}} {"text": "using FastGaussQuadrature\n\n\"\"\"\n lagrange_1d(points, i, x)\n\nEvaluate the Lagrange interpolation polynomial defined over nodal `points` with index `i`\nat point `x`.\n\"\"\"\nfunction lagrange_1d(points, i, x)\n l = 1.0\n x_i = points[i]\n for x_j in points\n if x_j != x_i\n l *= (x - x_j) / (x_i - x_j)\n end\n end\n return l\nend\n\n\"\"\"\n lagrange_diff(points, i, x)\n\nEvaluate the derivative of the Lagrange interpolation polynomial defined over nodal `points`\nwith index `i` at point `x`.\n\"\"\"\nfunction lagrange_diff(points, i, x)\n dl = 0.0\n x_i = points[i]\n for x_j in points\n if x_j != x_i\n p = 1.0\n for x_m in points\n if (x_m != x_i) & (x_m != x_j)\n p *= (x - x_m) / (x_i - x_m)\n end\n end\n dl += 1.0/(x_i - x_j) * p\n end\n end\n return dl\nend\n\n\"\"\"\n get_quadpoints(n)\n\nCompute quadrature points and weights for Gaussian quadrature\nof order `n`.\nThe points (and thus the corresponding weights) are normalized to the range\n``[0.0, 1.0]``.\n\nReturn a tuple of `points, weights`.\n\"\"\"\nfunction get_quadpoints(n)\n x, w = gausslegendre(n)\n # They are scaled in [-1.0, 1.0]\n # and we need [0.0, 1.0]\n (x .+ 1)./2, w ./ 2\nend\n\n\"\"\"\n Basis\n\nA standard 1-dimensional basis of `order::Integer`\nwith `quadpoints::Array{Float64,1}` and\ncorresponding `quadweights::Array{Float64,1}`\nIs the basis (pun intended) for tensor-product\nbases.\n\n Basis(order::Integer, dimensions)\n\nInitialize a basis of `order::Integer` and\ndimensions `dimensions`.\n\"\"\"\nstruct Basis\n quadpoints::Array{Float64,1}\n quadweights::Array{Float64,1}\n order::Int64\n dimensions::Int64\n\n function Basis(order, dimensions)\n quadpoints, quadweights = get_quadpoints(order)\n new(quadpoints, quadweights, order, dimensions)\n end\nend\n\n\n\"\"\"\n Base.length(basis::Basis)\n\nReturn number of points for `basis` in n-dimensions.\n\"\"\"\n#Base.length(basis::Basis) = length(basis.quadpoints)*basis.dimensions\n#Base.length(basis::Basis) = length(basis.quadpoints) ^ basis.dimensions\nBase.length(basis::Basis) = basis.order ^ basis.dimensions\n\n\"\"\"\n Base.size(basis::Basis)\n\nReturn number of points for `basis` for each dimensions as tuple.\n\"\"\"\nfunction Base.size(basis::Basis)\n ntuple(basis.dimensions) do x\n length(basis.quadpoints)\n end\nend\n\n\"\"\"\n Base.size(basis::Basis, dim)\n\nReturn number of points for `basis` for dimensions `dim`.\n\nfunction Base.size(basis::Basis, dim::Integer)\n length(basis.quadpoints)\nend\n\"\"\"\n\nfunction Base.size(basis::Basis, dim::Integer)\n if dim > basis.dimensions\n println(\"Error: Given Dimension exceeds the Dimension of the problem = \",basis.dimensions)\n else\n length(basis.quadpoints)\n end\nend\n\n\"\"\"\n evaluate_basis(basis::Basis, coeffs, x)\n\nEvaluate the `basis` with coefficients\n`coeffs` at point `x`.\n\n# So the input is coeffs , X point, I need to give basis\n#multiplication of the basis is used , indicate tensor product\n\"\"\"\nfunction evaluate_basis(basis::Basis, coeffs, x)\n #coeffs[1] #code given for order 1\n\n #To collect result\n basisvalue=0\n\n # To make linear indexes\n # collect(): makes a array of tuples of indexes, same like meshgrid in matlab\n # vec(): converts matrix into vector\n linearindex = vec(collect(Iterators.product(1:basis.order, 1:basis.order)))\n \n for i in 1:length(basis)\n basisvalue = basisvalue + ( coeffs[i] * ( lagrange_1d(basis.quadpoints, linearindex[i][1], x[1]) * lagrange_1d(basis.quadpoints, linearindex[i][2], x[2]) ) )\n end\n\n return basisvalue\nend\n\n\"\"\"\n project_to_reference_basis(fun, basis::Basis, ndofs)\n\nProject the result of the function `fun` to coefficients\nof the basis built of a tensor-product of `basis`.\nThe function `fun(x,y)` takes in the ``x, y``-coordinates\nand returns a vector with size `ndofs`.\nThe corresponding coefficients are returned.\n\n#The reshape() is an inbuilt function in julia which is used\nto return an array with the same data as the specified array,\nbut with different specified dimension sizes.\n\n# It returns the matrix of shape[length(basis),ndof]\n\n\"\"\"\nfunction project_to_reference_basis(fun, basis::Basis, ndofs)\n #reshape(fun(0.5, 0.5), (1,ndofs)) #made for constant polynomial of order 1\n \n # make a matrix of shape [length(basis),ndof]\n coeffarray = zeros( ( length(basis) , ndofs ) )\n\n # To make linear indexes\n # collect(): makes a array of tuples of indexes, same like meshgrid in matlab\n # vec(): converts matrix into vector\n\n linearindex = vec(collect(Iterators.product(1:basis.order, 1:basis.order)))\n\n for i in 1:length(basis)\n coeffarray[i,:] = fun( basis.quadpoints[linearindex[i][1]] , basis.quadpoints[linearindex[i][2]] ) # coefficients are nothing but values of function at that point\n end\n\n return coeffarray # No need to reshaping ,as matrix is made fully and filled it\nend\n\n\n\"\"\"\n massmatrix(basis, dimensions)\n\nReturn the mass-matrix for a `dimensions`-dimensional\ntensor-product basis built up from the 1d-basis `basis`.\n\"\"\"\nfunction massmatrix(basis, dimensions)\n #ones(1,1)\n mass_matrix = Matrix(1.0I, basis.order^2, basis.order^2)\n ij = 1\n for j = 1:basis.order\n for i = 1:basis.order #not generalising to dimensions>2\n mass_matrix[ij,ij] = basis.quadweights[i] * basis.quadweights[j] #eq 4.12 and 4.19\n ij += 1\n end\n end\n mass_matrix\n\nend\n\n\"\"\"\n derivativematrix(basis)\n\nReturns the 2-dimensional derivative matrix for `basis`.\nMultiplying this with flux-coefficients of shape\n`(dimensions * basissize_2d, ndofs)` returns the\ncoefficients of the corresponding derivative.\n\"\"\"\nfunction derivativematrix(basis)\n #zeros(1, basis.dimensions * 1)\n\n # Finding Derivative matrix Try3\n # Finding Dx only, Derivative of the basis function in the direction of x\n Dx = zeros(basis.order^2, basis.order^2)\n Dy = zeros(basis.order^2, basis.order^2)\n linearindex = vec(collect(Iterators.product(1:basis.order, 1:basis.order)))\n\n for j in 1:basis.order^2\n for p in 1:basis.order^2\n Dx[j,p] = lagrange_diff(basis.quadpoints,linearindex[j][1],basis.quadpoints[linearindex[p][1]]) * lagrange_1d(basis.quadpoints, linearindex[j][2], basis.quadpoints[linearindex[p][2]])\n end\n end\n\n for j in 1:basis.order^2\n for p in 1:basis.order^2\n Dy[j,p] = lagrange_diff(basis.quadpoints,linearindex[j][2],basis.quadpoints[linearindex[p][2]]) * lagrange_1d(basis.quadpoints, linearindex[j][1], basis.quadpoints[linearindex[p][1]])\n end\n end\n hcat(Dx,Dy)\nend\n\n\n\"\"\"\n get_face_quadpoints(basis::Basis, face)\n\nReturn the quadrature points at the face `face` for basis `basis`.\n\"\"\"\nfunction get_face_quadpoints(basis::Basis, face) # Is there a more efficient/ general way to do this?\n #ones(1.0, 1.0)\n\n face_quadpoints = zeros(basis.order,2)\n if face == left\n face_quadpoints[:,1] .= 0\n face_quadpoints[:,2] = basis.quadpoints\n elseif face == top\n face_quadpoints[:,1] = basis.quadpoints\n face_quadpoints[:,2] .= 1\n elseif face == right\n face_quadpoints[:,1] .= 1\n face_quadpoints[:,2] = basis.quadpoints\n elseif face == bottom\n face_quadpoints[:,1] = basis.quadpoints\n face_quadpoints[:,2] .= 0\n end\n face_quadpoints\nend\n\nfunction face_projection_matrix(basis, face)\n #ones(1,1)\n face_quadpoints = get_face_quadpoints(basis,face)\n\n # Matrix of required size\n P_ij = zeros( basis.order , (basis.order)^2 )\n\n # Linear indexing\n linearindex = vec(collect(Iterators.product(1:basis.order, 1:basis.order)))\n\n for j = 1:(basis.order)^2\n for i = 1:basis.order\n P_ij[i,j] = lagrange_1d( basis.quadpoints, linearindex[j][1] , face_quadpoints[i,1] ) * lagrange_1d( basis.quadpoints, linearindex[j][2], face_quadpoints[i,2] )\n end\n end\n return P_ij\nend\n\n\n\"\"\"\n evaluate_m_to_n_vandermonde_basis(basis)\n\nReturn the Vandermonde matrix that converts between the 2D-modal\n(normalized) Legendre-basis and the 2D-nodal tensor-product basis built\nwith `basis`.\n\"\"\"\nfunction evaluate_m_to_n_vandermonde_basis(basis)\n Array{Float64}(I, length(basis), length(basis))\nend\n", "meta": {"hexsha": "0485b83fd592a0cf2f3499659937cf3544f550af", "size": 8363, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/basis.jl", "max_stars_repo_name": "ashishdarekar/Modern-Wave-Propagation-Discontinuous-Galerkin-Julia", "max_stars_repo_head_hexsha": "b0fa6cda2fc2bdf3ad422abcba7f29a6c168db64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/basis.jl", "max_issues_repo_name": "ashishdarekar/Modern-Wave-Propagation-Discontinuous-Galerkin-Julia", "max_issues_repo_head_hexsha": "b0fa6cda2fc2bdf3ad422abcba7f29a6c168db64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/basis.jl", "max_forks_repo_name": "ashishdarekar/Modern-Wave-Propagation-Discontinuous-Galerkin-Julia", "max_forks_repo_head_hexsha": "b0fa6cda2fc2bdf3ad422abcba7f29a6c168db64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4455782313, "max_line_length": 195, "alphanum_fraction": 0.6661485113, "num_tokens": 2367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951863227517834, "lm_q2_score": 0.8824278587245936, "lm_q1q2_score": 0.839950629657243}} {"text": "using LinearAlgebra\nimport LinearAlgebra:checksquare\n\n\"\"\"\n function sweep_op_internal!(A::AbstractMatrix{Float64}, k::Int64)\n\n Implement the naive sweep operator described by Goodnight, J. (1979). \"A Tutorial on the SWEEP Operator.\" The American Statistician.\n\"\"\"\nfunction sweep_op_internal!(A::AbstractMatrix{Float64}, k::Int64)\n p = checksquare(A)\n if k >= p \n throw(ArgumentError(\"Incorrect k value\"))\n end\n \n @inbounds D = A[k,k] # step 1 D = Aₖₖ\n \n if D == zero(eltype(A))\n throw(ArgumentError(\"sweep_op_internal!: the element $k,$k of the matrix is zero. Is the Design Matrix symmetric positive definite?\"))\n end\n \n @inbounds for i in 1:p\n A[k,i] = A[k,i] / D # step 2 divide row k by D\n end\n \n @inbounds for i in 1:(k - 1) # step 3: for every other row i != k \n B = A[i,k] # let B = Aᵢₖ\n for j in 1:p\n A[i,j] = A[i,j] - B * A[k, j] # Subtract B * row k from row i\n end\n A[i,k] = - B / D # set Aᵢₖ = -B/D \n end\n\n @inbounds for i in k + 1:p # step 3: for every other row i != k \n B = A[i,k] # let B = Aᵢₖ\n for j in 1:p\n A[i,j] = A[i,j] - B * A[k, j] # Subtract B * row k from row i\n end\n A[i,k] = - B / D # set Aᵢₖ = -B/D \n end\n \n @inbounds A[k,k] = 1 / D # step 4 Set Aₖₖ = 1/D\n \n return A\nend\n\nfunction sweep_op!(A::AbstractMatrix{Float64}, k::Int64)\n sweep_op_internal!(A, k)\nend\n\nfunction sweep_op!(A::AbstractMatrix{Float64}, ks::AbstractVector{Int64})\n for k in ks\n sweep_op_internal!(A, k)\n end\n return A\nend\n\n\"\"\"\n function sweep_op_full!(A::AbstractMatrix{Float64})\n\n (internal) Get SSE, error sum of squares, for the full model.\n\"\"\"\nfunction sweep_op_full!(A::AbstractMatrix{Float64})\n n , p = size(A)\n\n for k in 1:p-1\n sweep_op_internal!(A, k)\n end\n return A[p,p]\nend\n\n\"\"\"\n function sweep_op_fullT1SS!(A::AbstractMatrix{Float64})\n\n (internal) Get SSE, error sum of squares for the full model.\n Also give Type I SS for all independent variables.\n\"\"\"\nfunction sweep_op_fullT1SS!(A::AbstractMatrix{Float64})\n n , p = size(A)\n TypeISS = Vector{Float64}(undef, p-1)\n\n for k in 1:p-1\n preSSE = A[p,p]\n sweep_op_internal!(A, k)\n TypeISS[k] = preSSE - A[p,p]\n end\n return A[p,p], TypeISS\nend\n\n\"\"\"\n function sweep_op_fullT1SS!(A::AbstractMatrix{Float64})\n\n (internal) Get SSE, error sum of squares for all (p-1) models.\n Also give Type I SS for all independent variables.\n\"\"\"\nfunction sweep_op_allT1SS!(A::AbstractMatrix{Float64})\n n , p = size(A)\n TypeISS = Vector{Float64}(undef, p-1)\n SSEs = Vector{Float64}(undef, p-1)\n\n for k in 1:p-1\n preSSE = A[p,p]\n sweep_op_internal!(A, k)\n SSEs[k] = A[p, p]\n TypeISS[k] = preSSE - A[p,p]\n end\n return SSEs, TypeISS\nend\n\n\"\"\"\n function get_TypeIISS(extended_inverse::AbstractMatrix{Float64})\n\n (internal) Get Type II SS for all independent variables given an extended inverse (sweep operator already applied)\n\"\"\"\nfunction get_TypeIISS(extended_inverse::AbstractMatrix{Float64})\n n, p = size(extended_inverse)\n TypeIISS = Vector{Float64}(undef, p-1)\n\n for k in 1:p-1\n TypeIISS[k] = extended_inverse[k, end]^2 / extended_inverse[k, k]\n end\n\n return TypeIISS\nend", "meta": {"hexsha": "b217f01b647a4496571d56e018b5ff22b87f2e88", "size": 3360, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/sweep_operator.jl", "max_stars_repo_name": "st--/LinearRegressionKit.jl", "max_stars_repo_head_hexsha": "4d812bd0032227991f579f4d042f6c37937a7035", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2021-09-02T11:08:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-12T19:24:52.000Z", "max_issues_repo_path": "src/sweep_operator.jl", "max_issues_repo_name": "st--/LinearRegressionKit.jl", "max_issues_repo_head_hexsha": "4d812bd0032227991f579f4d042f6c37937a7035", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-09-02T21:00:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-11T10:14:54.000Z", "max_forks_repo_path": "src/sweep_operator.jl", "max_forks_repo_name": "st--/LinearRegressionKit.jl", "max_forks_repo_head_hexsha": "4d812bd0032227991f579f4d042f6c37937a7035", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-26T22:14:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-26T22:14:10.000Z", "avg_line_length": 27.3170731707, "max_line_length": 142, "alphanum_fraction": 0.6098214286, "num_tokens": 1062, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947086083138, "lm_q2_score": 0.8887587964389112, "lm_q1q2_score": 0.8398723598638645}} {"text": "# # An equation of second order in one dimmension\n#\n# Consider the following problem. Given \\\\(f \\in C([0, 1])\\\\), find a function \\\\(u\\\\) satisfying\n# -u'' + u = f in (0, 1)\n# u(0) = u(1) = 0\n\n\nusing SymFEL\nusing SymPy\nusing LinearAlgebra\nusing SparseArrays\n\nusing PyPlot\nclose(\"all\")\n\n# discretization parameters\nN = 101; # number of nodes\ndx = 1 / (N - 1); # discretization step\nnodes = range(0, stop=1, length=N);\nbound_nodes = [1, N];\n\n# exact solution\nu_exact = nodes .* sin.(pi * nodes);\n# right hand \nf = (1 + pi^2) * nodes .* sin.(pi * nodes) - 2 * pi * cos.(pi * nodes);\n\n# elementary matrices\nelem_K = SymFEL.get_lagrange_em(1, 1, 1);\nelem_M = SymFEL.get_lagrange_em(1, 0, 0);\nelem_K_dx = convert(Matrix{Float64}, elem_K.subs(h, dx));\nelem_M_dx = convert(Matrix{Float64}, elem_M.subs(h, dx));\n\nK = SymFEL.assemble_1d_FE_matrix(elem_K_dx, N, intNodes1=0, intNodes2=0, dof1=1, dof2=1);\nM = SymFEL.assemble_1d_FE_matrix(elem_M_dx, N, intNodes1=0, intNodes2=0, dof1=1, dof2=1);\n\nF = M * f;\n\n# boundary conditions\ntgv = 1e100\nA = K + M\nA[bound_nodes, bound_nodes] += tgv*sparse(Matrix{Float64}(I, 2, 2));\n\nF[bound_nodes] = zeros(2);\n\nu = A \\ F;\n\nplot(nodes, u_exact);\nplot(nodes, u);\nlegend([\"Exact solution\", \"Approximate solution\"]);\n\n\nerr = u - u_exact;\nprintln(\"L2 error = \", sqrt(err' * (M * err)))\nprintln(\"H1 error = \", sqrt(err' * (K * err)))\n\n\n# error convergence\nNV = 10 * 2 .^ (0:10)\nEL2 = zeros(11)\nEH1 = zeros(11)\ni = 1\nfor N = NV\n global i\n local dx = 1 / (N - 1); # discretization step\n local nodes = range(0, stop=1, length=N);\n local bound_nodes = [1, N];\n\n # exact solution\n local u_exact = nodes .* sin.(pi * nodes);\n # right hand \n local f = (1 + pi^2) * nodes .* sin.(pi * nodes) - 2 * pi * cos.(pi * nodes);\n\n local elem_K_dx = convert(Matrix{Float64}, elem_K.subs(h, dx));\n local elem_M_dx = convert(Matrix{Float64}, elem_M.subs(h, dx));\n\n local K = SymFEL.assemble_1d_FE_matrix(elem_K_dx, N, intNodes1=0, intNodes2=0, dof1=1, dof2=1);\n local M = SymFEL.assemble_1d_FE_matrix(elem_M_dx, N, intNodes1=0, intNodes2=0, dof1=1, dof2=1);\n\n local F = M * f;\n\n # boundary conditions\n local tgv = 1e100\n local A = K + M\n A[bound_nodes, bound_nodes] += tgv*sparse(Matrix{Float64}(I, 2, 2));\n\n F[bound_nodes] = zeros(2);\n\n local u = A \\ F;\n\n local err = u - u_exact;\n\n EL2[i] = sqrt(err' * M * err)\n EH1[i] = sqrt(err' * K * err)\n\n i += 1\nend\n\nfigure()\nloglog(1 ./ NV, EL2, \"d\")\nloglog(1 ./ NV, EH1)\nloglog(1 ./ NV, (1 ./ NV).^2)\nxlabel(L\"$\\Delta x$\")\nlegend([\"L2 Error\", \"H1 Error\", L\"$\\Delta x^2$\"])\nshow()\n", "meta": {"hexsha": "f2177366243d08accf505d0eea20d5c484ba1f52", "size": 2597, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ex1-lagrange.jl", "max_stars_repo_name": "ncindea/SymFE.jl", "max_stars_repo_head_hexsha": "886e7fe844d0833bda4ab721414111f8fe353915", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-12T22:24:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-16T12:06:02.000Z", "max_issues_repo_path": "examples/ex1-lagrange.jl", "max_issues_repo_name": "ncindea/SymFEL.jl", "max_issues_repo_head_hexsha": "886e7fe844d0833bda4ab721414111f8fe353915", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/ex1-lagrange.jl", "max_forks_repo_name": "ncindea/SymFEL.jl", "max_forks_repo_head_hexsha": "886e7fe844d0833bda4ab721414111f8fe353915", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7333333333, "max_line_length": 99, "alphanum_fraction": 0.619561032, "num_tokens": 946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475778774729, "lm_q2_score": 0.8902942261220292, "lm_q1q2_score": 0.8398569018105154}} {"text": "# Improved Newton's Method\r\n\r\n# Safe version - disclosed version\r\n\r\n\r\n#par1 - lower bound\r\n#par2 - upper bound\r\nfunction solve_Newton_safely(f,f1,par,par1,par2;nlim = 1e4,ϵ=1e-3)\r\n for i in 1:nlim\r\n par3 = par - f(par)/f1(par)\r\n if ϵ>abs(par3 -par)\r\n return(par3)\r\n elseif par3<=par1\r\n par3 = (par+par1)/2\r\n elseif par3>=par2\r\n par3 = (par+par2)/2\r\n end\r\n\r\n par=par3\r\n end\r\n println(\"Warning! unconverged after\" * string(nlim) *\"Iterations.\")\r\n return(par3)\r\nend\r\n\r\n#where f1 is a constant (avoid finding gradient)\r\nfunction solve_constGrad(f,f1,par;nlim = 1e4,ϵ=1e-3)\r\n for i in 1:nlim\r\n par3 = par - f(par)/f1\r\n if ϵ>abs(par3 -par)\r\n return(par3)\r\n end\r\n par=par3\r\n end\r\n println(\"Warning! unconverged after\" * string(nlim) *\"Iterations.\")\r\n return(par3)\r\nend\r\n\r\n\r\n# by cotangent value\r\n# where\r\n# par1 and par2 are 2 starting points( to give 1st gradient value)\r\nfunction solve_cotangent(f,par1,par2;nlim = 1e4,ϵ=1e-3)\r\n for i in 1:nlim\r\n par3 = par2 - f(par2)*(par2 - par1)/(f(par2) - f(par1))\r\n if ϵ>abs(par3 -par2)\r\n return(par3)\r\n end\r\n par1 = par2;par2 = par3\r\n end\r\n println(\"Warning! unconverged after\" * string(nlim) *\"Iterations.\")\r\n return(par3)\r\nend\r\n\r\nusing Plots\r\n\r\nx = 0:.1:4\r\ny=sin.(x)\r\nplot(x,y)\r\nplot!([0,4],[0,0])\r\nsolve_cotangent(sin,3,4)\r\n", "meta": {"hexsha": "e9d308d657dc3d73275153430962df9f73640400", "size": 1451, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Improved Newton Solver.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": "Improved Newton Solver.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": "Improved Newton Solver.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": 23.7868852459, "max_line_length": 72, "alphanum_fraction": 0.5692625775, "num_tokens": 484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475715065793, "lm_q2_score": 0.8902942268497306, "lm_q1q2_score": 0.839856896825021}} {"text": "################################\n# BIBLIOTECA JULIA CalcNumCTEC #\n################################\n\nusing LinearAlgebra\nusing Printf\nusing Base\n\nfunction Derivada_MDFCentrada(f::Function, x₀::Number, i::Int; h::Number=10^-4, n::Int=9)\n x = x₀-((n-1)/2)*h:h:x₀+((n-1)/2)*h\n \n A = zeros(n,n)\n for i in range(1,stop=n)\n for j in range(1,stop=n)\n A[i,j] = x[i]^(n-j)\n end\n end\n\n coefs = A \\ f.(x)\n\n function dif_f_interp(x_in)\n res = 0\n for k in 1:n-i\n res += coefs[k] * ((factorial(n-k))/(factorial(n-k-i))) * x_in^(n-k-i)\n end\n return res\n end\n\n return dif_f_interp(x₀)\nend\n\n# Cálculo de zeros de funções ------------------------------------------------------------------------------\n\nfunction Zeros_Bissecao(f::Function, a::Number, b::Number; \n tol::Number=10^-12, klim::Number=10^6)\n if f(a) * f(b) < 0\n k = 0\n x = (a + b) / 2\n \n while abs(f(x)) > tol\n if k == klim\n @assert false \"ERRO: O método não convergiu para $klim iterações...\"\n else\n k += 1\n end\n \n x = (a + b) / 2\n if f(x) * f(a) < 0 \n b = x\n else\n a = x \n end\n end\n\n return x\n else\n @assert false \"\\n\\nERRO NA FUNÇÃO ZeroBissecao:\\nOs valores da função nos extremos do intervalo dado\\nprecisam ter valores de sinais opostos entre si\\npara que a convergência do método seja garantida...\"\n end\nend\n\nfunction Zeros_Cordas(f::Function, a::Number, b::Number; \n tol::Float64=10^-12, klim::Int64=10^6)\n if f(a) * f(b) < 0\n k = 0\n x = (a * f(b) - b * f(a)) / (f(b) - f(a))\n \n while abs(f(x)) > tol\n if k == klim\n @assert false \"ERRO: O método não convergiu para $klim iterações...\"\n else\n k += 1\n end\n \n x = (a + b) / 2\n if f(x) * f(a) < 0\n b = x \n else\n a = x \n end\n end\n\n return x\n else\n @assert false \"ERRO NA FUNÇÃO ZeroCordas:\\nOs valores da função nos extremos do intervalo dado\",\n \"\\nprecisam ter valores de sinais opostos entre si\",\n \"\\npara que a convergência do método seja garantida...\"\n end\nend\n\nfunction Zeros_NR(f::Function, x::Number; \n tol::Float64=10^-12, klim::Int64=10^6)\n k = 0\n while abs(f(x)) > tol\n if k == klim\n @assert false \"ERRO NA FUNÇÃO ZeroNR:\\nO método não convergiu para $klim iterações...\"\n else\n k += 1\n end\n \n if abs(Derivada_MDFCentrada(f, x, 1, n=5)) < tol\n @assert false \"ERRO NA FUNÇÃO ZeroNR:\\nO ponto x=$x possui derivada nula...\"\n end\n x = x - (f(x) / Derivada_MDFCentrada(f, x, 1, n=5))\n end\n\n return x\nend\n\n# Resolução de sistemas de equações lineares --------------------------------------------------------------\n\nfunction SEL_EliminGauss(A::Matrix, b::Vector; tol::Float64=10^-12)\n (m,n) = size(A)\n \n if m==n && m == length(b)\n if abs(det(A)) < tol\n @assert false \"ERRO na função EliminGauss:\\nA matriz é singular...\"\n else\n function test(M)\n aux = 0\n for j in range(1, stop = n)\n for i in range(1, stop = n)\n if i > j \n aux += abs(M[i,j])\n end\n end\n end\n return aux\n end\n\n AG = copy(A)\n bG = copy(b)\n \n for j in 1:n\n i = j\n while A[j,j] == 0\n i+=1\n\n aux_A = AG[j,:]\n AG[j,:] = AG[i,:]\n AG[i,:] = aux_A\n\n aux_b = b[j]\n bG[j] = bG[i]\n bG[i] = aux_b\n if (i,j) == (m,n)\n @assert false \"ERRO na função EliminGauss:\\nA matriz é singular...\"\n end\n end\n end\n \n i = 1\n j = 1\n k = 0\n while test(AG) > tol\n k += 1\n if i == n\n j += 1\n i = j\n end\n i += 1\n \n bG[i] -= bG[j] * (AG[i,j] / AG[j,j])\n AG[i,:] -= AG[j,:] * (AG[i,j] / AG[j,j])\n end\n \n x = zeros(n)\n for k in n:-1:1\n x[k] = (bG[k] - dot(AG[k,:], x)) / AG[k,k]\n end\n \n return x\n end\n else\n @assert false \"ERRO NA FUNÇÃO ElimGauss:\\nInconsistência nas dimensões da matriz e do vetor...\"\n end\nend\n\nfunction SEL_CritConverg(A::Matrix, modo::Char) \n (m,n) = size(A)\n\n if m == n\n if uppercase(modo) == 'L'\n beta=zeros(n)\n for i in range(1, stop = n)\n for j in range(1, stop = n)\n beta[i] += abs(A[i,j]) \n end\n beta[i] /= abs(A[i,i])\n end\n return max(beta...)\n elseif uppercase(modo) == 'C'\n beta=zeros(n)\n for j in range(1, stop = n)\n for i in range(1, stop = n)\n beta[j] += abs(A[i,j]) \n end\n beta[j] /= abs(A[j,j])\n end\n return max(beta...)\n elseif uppercase(modo) == 'S'\n beta = ones(n)\n for i in range(1, stop = n)\n for j in range(1, stop = n)\n beta[i] += abs(A[i,j]) * beta[j]\n end\n beta[i] -= 1\n beta[i] /= abs(A[i,i])\n end\n return max(beta...)\n end\n else\n @assert false \"\\n\\nERRO NA FUNÇÃO CritConverg:\\nA matriz dada não é quadrada...\"\n end\nend\n\nfunction SEL_GaussJacobi(A::Matrix, b::Vector; x_in::Vector=zeros(length(b)), \n tol::Float64=1e-12, klim::Int=10^6)\n # Rseolve o sistema linear A*x=b através de iterações pelo Método da Gauss-Jacobi.\n # Tolerância padrão: 10^(-12)\n # Métrica de erro: eₐ = ||x_out - x_in|| / ||x_out||\n # Retorno da (x_out, err)\n\n (m,n) = size(A)\n\n if m==n && m == length(b)\n if abs(det(A)) < tol\n @assert false \"ERRO na função GaussJacobi:\\nA matriz é singular...\"\n else\n for j in 1:n\n i = j\n while A[j,j] == 0\n i+=1\n\n aux_A = A[j,:]\n A[j,:] = A[i,:]\n A[i,:] = aux_A\n\n aux_b = b[j]\n b[j] = b[i]\n b[i] = aux_b\n if (i,j) == (m,n)\n @assert false \"ERRO na função EliminGauss:\\nA matriz é singular...\"\n end\n end\n end\n\n function err(x1, x2)\n return norm(x2 - x1) / norm(x2)\n end\n \n k = 1\n x_out = zeros(n)\n for i in range(1, stop = n)\n x_out[i] = (b[i] - dot(A[i,1:i-1], x_in[1:i-1]) - dot(A[i,i+1:n], x_in[i+1:n])) / A[i,i]\n end\n \n while err(x_in, x_out) > tol\n if k == klim\n @assert false \"ERRO NA FUNÇÃO GaussJacobi:\\nO método não convergiu para $klim iterações\\ne tolerância de $tol...\"\n else\n k += 1\n end\n \n x_in = copy(x_out)\n \n for i in range(1, stop = n)\n x_out[i] = (b[i] - dot(A[i,1:i-1], x_in[1:i-1]) - dot(A[i,i+1:n], x_in[i+1:n])) / A[i,i]\n end\n end\n \n return x_out\n end\n else\n @assert false \"ERRO NA FUNÇÃO GaussJacobi:\\nInconsistência nas dimensões da matriz e do vetor...\"\n end\nend\n\nfunction SEL_GaussSeidel(A::Matrix, b::Vector; x_in::Vector=zeros(length(b)), \n tol::Float64=1e-12, klim::Int=10^6)\n # Rseolve o sistema linear A*x=b através de iterações pelo Método da Gauss-Seidel.\n # Tolerância padrão: 10^(-12)\n # Métrica de erro: eₐ = ||x_out - x_in|| / ||x_out||\n # Retorno da (x_out, err)\n\n (m,n) = size(A)\n\n if m==n && m == length(b)\n if abs(det(A)) < tol\n @assert false \"\\n\\nERRO na função GaussJacobi:\\nA matriz é singular...\\n\\n\"\n else\n for j in 1:n\n i = j\n while A[j,j] == 0\n i+=1\n\n aux_A = A[j,:]\n A[j,:] = A[i,:]\n A[i,:] = aux_A\n\n aux_b = b[j]\n b[j] = b[i]\n b[i] = aux_b\n if (i,j) == (m,n)\n @assert false \"ERRO na função GaussSeidel:\\nA matriz é singular...\"\n end\n end\n end\n\n function err(x1, x2)\n return norm(x2 - x1) / norm(x2)\n end\n \n k = 1\n x_out = zeros(n)\n for i in range(1, stop = n)\n x_out[i] = (b[i] - dot(A[i,1:i-1], x_out[1:i-1]) - dot(A[i,i+1:end], x_in[i+1:end])) / A[i,i]\n end\n \n while err(x_in, x_out) > tol\n if k == klim\n @assert false \"ERRO NA FUNÇÃO GaussSeidel:\\nO método não convergiu para $klim iterações\\ne tolerância de $tol...\"\n else\n k += 1\n end\n \n x_in = copy(x_out)\n \n for i in range(1, stop = n)\n x_out[i] = (b[i] - dot(A[i,1:i-1], x_out[1:i-1]) - dot(A[i,i+1:end], x_in[i+1:end])) / A[i,i]\n end\n end\n \n return x_out\n end\n else\n printstyled(\"ERRO NA FUNÇÃO GaussJacobi:\\nInconsistência nas dimensões da matriz e do vetor...\\n\\n\", color=:bold)\n end\nend\n\n# Resolução de sistemas de equações não lineares ---------------------------------------------------------\n\nfunction SENL_NRSecante(F::Function, x_in::Vector;\n tol::Float64=1e-6, klim::Int64=10^3)\n # Rseolve o sistema não linear F(x)=0 através de iterações pelo Método de Newton-Raphson Secante.\n # Ou seja, a Jacobiana é calculada de maneira aproximada em função da tolerância.\n # Tolerância padrão: 10^(-12)\n\n function J_aprox(x, δ=tol)\n n = length(x)\n Jap = zeros(n,n)\n \n for j in range(1, stop = n)\n δx = zeros(n)\n δx[j] = δ * x[j]\n for i in range(1, stop = n)\n Jap[i,j] = (F(x + δx)[i] - F(x)[i]) / δx[j]\n end\n end\n \n return Jap\n end\n\n if length(F(x_in)) == length(x_in)\n err(x_in, x_out) = norm(x_out - x_in) / norm(x_out)\n\n k = 1\n x_out = x_in - J_aprox(x_in) \\ F(x_in)\n \n while err(x_in, x_out) > tol\n if k==klim\n @assert false \"\\n\\nERRO na função NR_Secante:\\nO método não convergiu para $klim iterações\\ne tolerância de $tol...\\n\\n\"\n else\n k+=1\n end\n \n x_in = copy(x_out)\n x_out = x_in - J_aprox(x_in) \\ F(x_in)\n end\n \n return x_out\n else\n printstyled(\"\\n\\nERRO na função NR_Secante:\\nOs vetores possuem dimensões diferentes...\\n\\n\", color=:bold)\n return nothing\n end\nend\n\n# Interpolação e ajuste ------------------------------------------------------------------------------\n\nfunction Interpolacao_Polinomial(x::Vector, y::Vector)\n # Calcula e retorna o polinômio interpolador para os dados de entrada via polinômios de Lagrange.\n # O grau do polinômio é determinado pelas dimensões dos vetores x e y.\n\n n = Int(length(x))\n\n if n==length(y)\n function f_interpoladora(x_in)\n res = 0\n for i in range(1, stop=n)\n aux = 1\n for j in range(1, stop=n)\n if i != j\n aux *= (x_in - x[j])/(x[i] - x[j])\n end\n end\n res += y[i] * aux\n end \n return res\n end \n\n return f_interpoladora\n else\n @assert false \"ERRO NA FUNÇÃO Interpolacao_Polinomial:\\nOs vetores de entrada possuem dimensões diferentes...\"\n end\nend\n\nfunction Interpolacao_Polinomial(f::Function, x::Vector)\n # Calcula e retorna o polinômio interpolador para os dados de entrada via polinômios de Lagrange.\n # O grau do polinômio é determinado pela dimensão do vetor x.\n\n n = Int(length(x))\n\n function f_interpoladora(x_in)\n res = 0\n for i in range(1, stop=n)\n aux = 1\n for j in range(1, stop=n)\n if i != j\n aux *= (x_in - x[j])/(x[i] - x[j])\n end\n end\n res += f(x[i]) * aux\n end \n return res\n end\n \n return f_interpoladora\nend\n\nfunction Interpolacao_Bilinear(x::Vector, y::Vector, z::Vector)\n if length(x) == length(y) == length(z) == 4\n M = [ones(n) x y x.*y]\n b = M \\ z\n g(x,y) = dot(b,[1 x y x*y])\n return g\n else\n @assert false \"\\n\\nERRO NA FUNÇÃO Interpolacao_Bilinear:\\nOs vetores de entrada precisam ter dimensões de 4 elementos...\"\n end\nend\n\nfunction Ajuste_MinimosQuadrados(x::Vector, y::Vector; grau::Int64=1)\n # Calcula e retorna o polinômio ajustado para os dados de entrada via Método dos Mínimos Quadrados.\n # O grau padrão do polinômio é 1.\n # Retorno da função: (polinomio, r²)\n if length(x) != length(y)\n @assert false \"ERRO NA FUNÇÃO MinimosQuadrados:\\nOs vetores de entrada possuem dimensões diferentes...\"\n else\n A = zeros(grau+1, grau+1)\n for i in 0:grau\n for j in 0:grau\n A[i+1,j+1] = sum(x.^(i+j))\n end\n end\n \n b = zeros(grau+1)\n for i in 0:grau\n b[i+1] = sum(y.*(x.^i))\n end \n \n coefs = A \\ b\n end\n\n function f_ap(x_in)\n xᵏ = []\n for i in 0:grau\n push!(xᵏ, x_in^i)\n end\n return dot(coefs, xᵏ)\n end\n\n Sr = sum((y - f_ap.(x)).^2)\n ym = sum(y)/length(y)\n St = sum((y .- ym).^2)\n r² = 1 - (Sr/St)\n \n return f_ap, r²\nend\n\n# Integração Numérica ------------------------------------------------------------------\n\n# OBS: COMPLETAR O ERRO COM A DIFERENCIAÇÃO NUMÉRICA\n\nfunction Integral_Trapezio(f::Function, x::Tuple; tol::Float64 = 1e-12)\n if length(x) == 2\n a = x[1]\n b = x[2]\n c = (a+b)/2\n\n T(a,b) = (b-a) * (f(a) + f(b)) / 2\n\n if T(a,b) - T(a,c) - T(c,b) < tol\n return T(a,b)\n else\n return Integral_Trapezio(f, (a,c), tol=tol) + Integral_Trapezio(f, (c,b),tol=tol)\n end\n else\n @assert false \"ERRO NA FUNÇÃO Intergral_Trapezio:\\nO intervalo precisa ter apenas 2 valores...\"\n end\nend\n\nfunction Integral_Trapezio(x::Vector, y::Vector)\n n = length(x)\n\n if n == length(y)\n I = 0\n for i in 1:n-1\n I += ((x[i+1]-x[i])/2)*(y[i] + y[i+1])\n end\n\n #err = abs(-(b-a)^4 * (IntegSimpson(dif_f4, a, b, n=10^3))[1] / (180*n^4))\n\n return I#, err\n else\n @assert false \"ERRO NA FUNÇÃO Integral_Trapezio:\\nOs vetores possuem dimensões diferentes...\"\n end\nend\n\nfunction IntegralDupla_Trapezio(f::Function, x::Tuple, y::Tuple; tol::Float64=1e-12)\n if length(x) == length(y) == 2\n x₀, x₁ = x\n y₀, y₁ = y\n xₘ = (x₀ + x₁) / 2\n yₘ = (y₀ + y₁) / 2\n\n function T(x,y)\n return Integral_Trapezio([y...], [Integral_Trapezio([x...], f.([x...], [y[1],y[1]])),Integral_Trapezio([x...], f.([x...], [y[2],y[2]]))])\n end\n\n if T(x,y) - T((x₀,xₘ),y) - T((xₘ,x₁),y) < tol\n if T(x,y) - T(x,(y₀,yₘ)) - T(x,(yₘ,y₁)) < tol\n println(\"teste1\")\n return T(x,y)\n else\n println(\"teste2\")\n return IntegralDupla_Trapezio(f, x, (y₀,yₘ), tol=tol) + IntegralDupla_Trapezio(f, x, (yₘ,y₁), tol=tol)\n end\n elseif T(x,y) - T(x,(y₀,yₘ)) - T(x,(yₘ,y₁)) < tol\n println(\"teste3\")\n return IntegralDupla_Trapezio(f, (x₀,xₘ), y, tol=tol) + IntegralDupla_Trapezio(f, (xₘ,x₁), y, tol=tol)\n else\n println(\"teste4\")\n return IntegralDupla_Trapezio(f, (x₀,xₘ), (y₀,yₘ), tol=tol) + IntegralDupla_Trapezio(f, (xₘ,x₁), (y₀,yₘ), tol=tol) + IntegralDupla_Trapezio(f, (x₀,xₘ), y, tol=tol) + IntegralDupla_Trapezio(f, (xₘ,x₁), y, tol=tol)\n end\n else\n @assert false \"ERRO NA FUNÇÃO IntegralDupla_Trapezio:\\nOs intervalos precisam ter apenas 2 valores...\"\n end\nend\n\nfunction Integral_Simpson(f::Function, x::Tuple; tol::Float64 = 1e-12)\n if length(x) == 2\n a = x[1]\n b = x[2]\n c = (a+b)/2\n \n S(a,b) = (b-a) * (f(a) + 4*f((a+b)/2) + f(b)) / 6\n\n if S(a,b) - S(a,c) - S(c,b) < tol\n return S(a,b)\n else\n return Integral_Simpson(f, (a,c), tol=tol) + Integral_Simpson(f, (c,b), tol=tol)\n end\n else\n @assert false \"ERRO NA FUNÇÃO Integral_Simpson:\\nO intervalo precisa ter apenas 2 valores...\"\n end\nend\n\nfunction Integral_Simpson(x::Vector, y::Vector)\n n = length(x)\n\n if n == length(y)\n if n%2==1\n I = 0\n for i in 1:2:n-2\n I += ((x[i+2]-x[i])/6)*(y[i] + 4*y[i+1] + y[i+2])\n end\n\n return I\n else\n @assert false \"ERRO NA FUNÇÃO Integral_Simpson:\\nO número de elementos dos vetores deve ser ímpar...\"\n end\n else\n @assert false \"ERRO NA FUNÇÃO IntegSimpson:\\nOs vetores possuem dimensões diferentes...\"\n end\nend\n\n# function IntegralDupla_Simpson(f::Function, x1::Number, x2::Number, \n# y1::Number, y2::Number; nx::Number=(b-a)*10^3, ny::Number=(d-c)*10^3)\n\n# hx = (x2-x1)/2nx\n# hy = (y2-y1)/2ny\n\n# M = zeros(2nx+1, 2ny+1)\n# for (j,y) in enumerate(y1:hy:y2)\n# for (i,x) in enumerate(x1:hx:x2)\n# M[i,j] = f(x,y)\n# end\n# end\n\n# V = zeros(2ny+1)\n# for k in 1:2ny+1\n# V[k] += Integral_Simpson(Vector(x1:hx:x2), M[:,k]) \n# end\n\n# return Integral_Simpson(Vector(y1:hy:y2), V) \n# end\n\n# function IntegralDupla_Simpson(f::Function, x₀::Number, x₁::Number, y₀::Number, y₁::Number; tol::Float64=1e-12)\n# S(a,b) = (b-a) * (f(a) + 4*f((a+b)/2) + f(b)) / 6\n\n# xₘ = (x₀ + x₁) / 2\n# yₘ = (y₀ + y₁) / 2\n\n# if \n\n# else\n \n# end\n# end\n\nfunction IntegralTripla_Simpson(f::Function, x1::Number, x2::Number, y1::Number, y2::Number, \n z1::Number, z2::Number; nx::Number=(x2-x1)*100, ny::Number=(y2-y1)*100, nz::Number=(z2-z1)*100)\n\n hx = (x2-x1)/2nx\n hy = (y2-y1)/2ny\n hz = (z2-z1)/2nz \n\n I = []\n\n M = Matrix{Number}(undef, 2ny+1, 2nz+1)\n for (k,z) in enumerate(z1:hz:z2)\n for (j,y) in enumerate(y1:hy:y2)\n for (i,x) in enumerate(x1:hx:x2)\n M[i,j] = f(x,y,z)\n end\n end\n # println(M)\n V = zeros(2nx+1)\n for k in 1:2nx+1\n V[k] = Integral_Simpson(Vector(x1:hx:x2), M[:,k]) \n end\n # println(V)\n push!(I, Integral_Simpson(Vector(y1:hy:y2), V))\n end\n res = Integral_Simpson(Vector(z1:hz:z2), I)\n return res\n\n # M = Matrix{Number}(undef, 2nx+1, 2ny+1)\n # for (j,y) in enumerate(y1:hy:y2)\n # for (i,x) in enumerate(x1:hx:x2)\n # M[i,j] = Integral_Simpson(Vector(x1:hx:x2), S[i,j,:]) \n # end\n # end\n\n # V = zeros(2ny+1)\n # for k in 1:2ny+1\n # V[k] = Integral_Simpson(Vector(x1:hx:x2), M[:,k]) \n # end\n\n # return Integral_Simpson(Vector(y1:hy:y2), V)\nend\n\nfunction IntegralTripla_Trapezio(f::Function, x1::Number, x2::Number, y1::Number, y2::Number, \n z1::Number, z2::Number; nx::Int=10^3, ny::Int=10^3, nz::Int=10^3)\n\n hx = (x2-x1)/nx\n hy = (y2-y1)/ny\n hz = (z2-z1)/nz \n\n I = []\n\n M = Matrix{Number}(undef, ny+1, nz+1)\n for (k,z) in enumerate(z1:hz:z2)\n for (j,y) in enumerate(y1:hy:y2)\n for (i,x) in enumerate(x1:hx:x2)\n M[i,j] = f(x,y,z)\n end\n end\n # println(M)\n V = zeros(nx+1)\n for k in 1:nx+1\n V[k] = Integral_Trapezio(Vector(x1:hx:x2), M[:,k]) \n end\n # println(V)\n push!(I, Integral_Trapezio(Vector(y1:hy:y2), V))\n end\n return Integral_Trapezio(Vector(z1:hz:z2), I)\n\n # M = Matrix{Number}(undef, 2nx+1, 2ny+1)\n # for (j,y) in enumerate(y1:hy:y2)\n # for (i,x) in enumerate(x1:hx:x2)\n # M[i,j] = Integral_Simpson(Vector(x1:hx:x2), S[i,j,:]) \n # end\n # end\n\n # V = zeros(2ny+1)\n # for k in 1:2ny+1\n # V[k] = Integral_Simpson(Vector(x1:hx:x2), M[:,k]) \n # end\n\n # return Integral_Simpson(Vector(y1:hy:y2), V)\nend\n\n# Geometria -----------------------------------------------------------------------------------\n\nstruct Vertex2d\n x::Number\n y::Number\n\n function Vertex2d(x::Number, y::Number)\n \n end\n\n function Base.print(v::Vertex2d)\n print(\"(\", v.x, \", \", v.y, \")\")\n end\n function Base.println(v::Vertex2d)\n println(\"(\", v.x, \", \", v.y, \")\")\n end\nend\n\n\n\nstruct Vertex3d\n x::Number\n y::Number\n z::Number\n\n function Vertex3d(v::Vertex2d,z::Number)\n return Vertex3d(v.x, v.y, z)\n end\n\n function Base.print(v::Vertex3d)\n print(\"(\", v.x, \", \", v.y, \", \", v.z, \")\")\n end\n function Base.println(v::Vertex3d)\n println(\"(\", v.x, \", \", v.y, \", \", v.z, \")\")\n end\nend\n\n\"CalcNumCTEC incluída com sucesso!\"\n\n", "meta": {"hexsha": "652480e082755381001169ba8026e33508ad6e76", "size": 21905, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "code/CalcNumCTEC.jl", "max_stars_repo_name": "Lucashcr/CalcNumCTEC", "max_stars_repo_head_hexsha": "57eae73b5931ea2edc99c50ebda163a0f704527d", "max_stars_repo_licenses": ["MIT"], "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/CalcNumCTEC.jl", "max_issues_repo_name": "Lucashcr/CalcNumCTEC", "max_issues_repo_head_hexsha": "57eae73b5931ea2edc99c50ebda163a0f704527d", "max_issues_repo_licenses": ["MIT"], "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/CalcNumCTEC.jl", "max_forks_repo_name": "Lucashcr/CalcNumCTEC", "max_forks_repo_head_hexsha": "57eae73b5931ea2edc99c50ebda163a0f704527d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1677762983, "max_line_length": 224, "alphanum_fraction": 0.4620862817, "num_tokens": 6830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.962673111584966, "lm_q2_score": 0.8723473879530492, "lm_q1q2_score": 0.8397853743437794}} {"text": "#=\nPlease see\nhttps://computationalmindset.com/en/neural-networks/ordinary-differential-equation-solvers.html#sys1\nfor details\n=#\n\n#=Original problem\nx′ + x − y = 0\ny′ − 4x + y = 0\nx(0)=2\ny(0)=0\n=#\n\n#=Esplicit form of equations\nx′ = y - x\ny′ = 4x - y\n=#\n\n#=Analytical solution\nx(t) = e^t + e^−3t\ny(t) = 2e^t − 2e^−3t\n=#\n\nusing DifferentialEquations\nusing Plots\n\nfunction ode_fn(du,u,p,t)\n x, y = u\n du[1] = y - x\n du[2] = 4.0 * x - y\nend\n\nan_sol_x(t) = exp(t) + exp(-3.0 * t)\nan_sol_y(t) = 2.0 * exp(t) - 2.0 * exp(-3.0 * t)\n\nt_begin=0.0\nt_end=5.0\ntspan = (t_begin,t_end)\nx_init=2.0\ny_init=0.0\n\nprob = ODEProblem(ode_fn, [x_init, y_init], tspan)\nnum_sol = solve(prob, Tsit5(), reltol=1e-8, abstol=1e-8)\nx_num_sol = [u[1] for u in num_sol.u]\ny_num_sol = [u[2] for u in num_sol.u]\n\nplot(num_sol.t, an_sol_x.(num_sol.t),\n linewidth=2, ls=:dash,\n title=\"System of 2 ODEs 1st order IVP solved by D.E. package\",\n xaxis=\"t\",\n label=\"analytical x\",\n legend=true)\nplot!(num_sol.t, an_sol_y.(num_sol.t),\n linewidth=2, ls=:dash,\n label=\"analytical y\",\n legend=true)\nplot!(num_sol.t, x_num_sol,\n linewidth=1,\n label=\"numerical x\")\nplot!(num_sol.t, y_num_sol,\n linewidth=1,\n label=\"numerical y\")\n", "meta": {"hexsha": "588ec730ab9d1cb7a564cc85e3617dcac4981df1", "size": 1228, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ODEs/solver-demos/julia/DifferentialEquations/sys_1st_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/sys_1st_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/sys_1st_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.4920634921, "max_line_length": 100, "alphanum_fraction": 0.6302931596, "num_tokens": 491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133548753619, "lm_q2_score": 0.8933094081846422, "lm_q1q2_score": 0.8396334427885511}} {"text": "# This file is a part of AstroLib.jl. License is MIT \"Expat\".\n# Copyright (C) 2016 Mosè Giordano.\n\nfunction _sphdist(long1::T, lat1::T, long2::T, lat2::T,\n degrees::Bool) where {T<:AbstractFloat}\n # Convert both points to rectangular coordinates.\n rxy, z1 = polrec(1, lat1, degrees=degrees)\n x1, y1 = polrec(rxy, long1, degrees=degrees)\n rxy, z2 = polrec(1, lat2, degrees=degrees)\n x2, y2 = polrec(rxy, long2, degrees=degrees)\n # Compute vector dot product for both points.\n cs = x1*x2 + y1*y2 + z1*z2\n # Compute the vector cross product for both points.\n xc = y1*z2 - z1*y2\n yc = z1*x2 - x1*z2\n zc = x1*y2 - y1*x2\n sn = norm((xc, yc, zc))\n # Convert to polar coordinates.\n radius, angle = recpol(cs, sn)\n return degrees ? rad2deg(angle) : angle\nend\n\n\"\"\"\n sphdist(long1, lat1, long2, lat2[, degrees=true]) -> angular_distance\n\n### Purpose ###\n\nAngular distance between points on a sphere.\n\n### Arguments ###\n\n* `long1`: longitude of point 1\n* `lat1`: latitude of point 1\n* `long2`: longitude of point 2\n* `lat2`: latitude of point 2\n* `degrees` (optional boolean keyword): if `true`, all angles, including the\n output distance, are assumed to be in degrees, otherwise they are all in\n radians. It defaults to `false`.\n\n### Output ###\n\nAngular distance on a sphere between points 1 and 2, as an `AbstractFloat`. It\nis expressed in radians unless `degrees` keyword is set to `true`.\n\n### Example ###\n\n```jldoctest\njulia> using AstroLib\n\njulia> sphdist(120, -43, 175, +22)\n1.5904422616007134\n```\n\n### Notes ###\n\n* `gcirc` function is similar to `sphdist`, but may be more suitable for\n astronomical applications.\n\nCode of this function is based on IDL Astronomy User's Library.\n\"\"\"\nsphdist(long1::Real, lat1::Real,\n long2::Real, lat2::Real; degrees::Bool=false) =\n _sphdist(promote(float(long1), float(lat1),\n float(long2), float(lat2))... , degrees)\n", "meta": {"hexsha": "8814d3758a6d9e238336515fda0e809b5b1e87b3", "size": 1973, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/sphdist.jl", "max_stars_repo_name": "UnofficialJuliaMirror/AstroLib.jl-c7932e45-9af1-51e7-9da9-f004cd3a462b", "max_stars_repo_head_hexsha": "fb2ef587a2ac68a1c864bf251e8d9c3601ec4719", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 62, "max_stars_repo_stars_event_min_datetime": "2016-09-11T14:59:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T20:45:36.000Z", "max_issues_repo_path": "src/sphdist.jl", "max_issues_repo_name": "UnofficialJuliaMirror/AstroLib.jl-c7932e45-9af1-51e7-9da9-f004cd3a462b", "max_issues_repo_head_hexsha": "fb2ef587a2ac68a1c864bf251e8d9c3601ec4719", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 64, "max_issues_repo_issues_event_min_datetime": "2017-01-19T21:03:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T12:27:46.000Z", "max_forks_repo_path": "src/sphdist.jl", "max_forks_repo_name": "UnofficialJuliaMirror/AstroLib.jl-c7932e45-9af1-51e7-9da9-f004cd3a462b", "max_forks_repo_head_hexsha": "fb2ef587a2ac68a1c864bf251e8d9c3601ec4719", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2016-07-12T02:11:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T11:55:21.000Z", "avg_line_length": 30.3538461538, "max_line_length": 79, "alphanum_fraction": 0.6507856057, "num_tokens": 603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939913343093499, "lm_q2_score": 0.8933094159957174, "lm_q1q2_score": 0.839633439605436}} {"text": "\"\"\"\nFunctions for area of various geometric shapes\n\nContributed By:- [Ashwani Rathee](https://github.com/ashwani-rathee)\n\"\"\"\n\n\"\"\"\n surfarea_cube(side)\n\nFinds surface area of a cube\n\n# Example\n\n```julia\nsurfarea_cube(1) # returns 6\nsurfarea_cube(3) # returns 54\nsurfarea_cube(-1) # returns DomainError\n```\n\"\"\"\nfunction surfarea_cube(side)\n if side < 0 \n throw(DomainError(side, \"surfarea_cube() only works for non-negative values\"))\n end\n return 6(side^2)\nend\n\n\"\"\"\n surfarea_sphere(side)\n\nFinds surface area of a sphere\n\n# Example\n\n```julia\nsurfarea_sphere(5) # returns 314.1592653589793\nsurfarea_sphere(1) # returns 12.566370614359172\nsurfarea_sphere(-1) # returns DomainError\n```\n\"\"\"\nfunction surfarea_sphere(radius)\n if radius < 0 \n throw(DomainError(radius, \"surfarea_sphere() only works for non-negative values\"))\n end\n return 4pi*(radius^2)\nend\n\n\"\"\"\n area_rectangle(length, width)\n\nFinds area of the rectangle\n\n# Example\n\n```julia\narea_rectangle(10,20) # returns 200\narea_rectangle(-1,-2) # returns DomainError\narea_rectangle(1,-2) # returns DomainError\narea_rectangle(-1,2) # returns DomainError\n```\n\"\"\"\nfunction area_rectangle(length, width)\n if length < 0 || width < 0\n throw(DomainError(\"area_rectangle() only works for non-negative values\"))\n end\n return length * width\nend\n\n\"\"\"\n area_square(side)\n\nFinds area of the area_square\n\n# Example\n\n```julia\narea_square(10) # returns 100\narea_square(-1) # returns DomainError\n```\n\"\"\"\nfunction area_square(side)\n if side < 0\n throw(DomainError(\"area_square() only works for non-negative values\"))\n end\n return side^2\nend\n\n\"\"\"\n area_triangle(base, height)\n\nFinds area of the right angled triangle with base height\n\n# Example\n\n```julia\narea_triangle(10,10) # returns 50.0\narea_triangle(-1,-2) # returns DomainError\narea_triangle(1,-2) # returns DomainError\narea_triangle(-1,2) # returns DomainError\n```\n\"\"\"\nfunction area_triangle(base, height)\n if base < 0 || height < 0\n throw(DomainError(\"area_triangle() only accepts non-negative values\"))\n end\n return (base * height) / 2\nend\n\n\"\"\"\n area_heron_triangle(side1, side2, side3)\n\nFinds area of a triangle using heron's formula\n\n# Example\n\n```julia\narea_heron_triangle(5,12,13) # returns 30.0\narea_heron_triangle(-1,-2,1) # returns DomainError\narea_heron_triangle(1,-2,1) # returns DomainError\narea_heron_triangle(-1,2,1) # returns DomainError\n```\n\"\"\"\nfunction area_heron_triangle(side1, side2, side3)\n if side1 < 0 || side2 < 0 || side3 < 0\n throw(DomainError(\"area_triangle_three_sides() only accepts non-negative values\"))\n elseif side1 + side2 < side3 || side1 + side3 < side2 || side2 + side3 < side1\n throw(DomainError(\"Given three sides do not form a triangle\"))\n end\n semi_perimeter = (side1 + side2 + side3) / 2\n area = sqrt(\n semi_perimeter\n * (semi_perimeter - side1)\n * (semi_perimeter - side2)\n * (semi_perimeter - side3)\n )\n return area\nend\n\n\"\"\"\n area_parallelogram(base, height)\n\nFinds area of the parallelogram\n\n# Example\n\n```julia\narea_parallelogram(10,20) # returns 200\narea_parallelogram(-1,-2) # returns DomainError\narea_parallelogram(1,-2) # returns DomainError\narea_parallelogram(-1,2) # returns DomainError\n```\n\"\"\"\nfunction area_parallelogram(base, height)\n\n if base < 0 || height < 0\n throw(DomainError(\"area_parallelogram() only accepts non-negative values\"))\n end\n return base * height\nend\n\n\"\"\"\narea_trapezium(base1,base2,height)\n\nFinds area of the trapizium\n\n# Example\n\n```julia\narea_trapezium(10, 20, 30) # returns 450.0\narea_trapezium(-1, -2, -3) # returns DomainError\narea_trapezium(-1, 2, 3) # returns DomainError\narea_trapezium(1, -2, 3) # returns DomainError\narea_trapezium(1, 2, -3) # returns DomainError\narea_trapezium(-1, -2, 3) # returns DomainError\narea_trapezium(1, -2, -3) # returns DomainError\narea_trapezium(-1, 2, -3) # returns DomainError\n```\n\"\"\"\nfunction area_trapezium(base1,base2,height)\n if base1 < 0 || base2 < 0 || height < 0\n throw(DomainError(\"area_trapezium() only accepts non-negative values\"))\n end\n return 1 / 2 * (base1 + base2) * height\nend\n\n\"\"\"\n area_circle(radius)\n\nFinds area of the circle\n\n# Example\n\n```julia\narea_circle(20) # returns 1256.6370614359173\narea_circle(-1) # returns DomainError\n```\n\"\"\"\nfunction area_circle(radius)\n if radius < 0\n throw(DomainError(\"area_circle() only accepts non-negative values\"))\n end\n return pi * radius ^ 2\nend\n\n\"\"\"\n area_ellipse(radius_x, radius_y)\n\nFinds area of the ellipse\n\n# Example\n\n```julia\narea_ellipse(10, 10) # returns 314.1592653589793\narea_ellipse(10, 20) # returns 628.3185307179587\narea_ellipse(1, -2) # returns DomainError\narea_ellipse(-1, 2) # returns DomainError\narea_ellipse(-1, -2) # returns DomainError\n```\n\"\"\"\nfunction area_ellipse(radius_x, radius_y)\n if radius_x < 0 || radius_y < 0\n throw(DomainError(\"area_ellipse() only accepts non-negative values\"))\n end\n return pi * radius_x * radius_y\nend\n\n\"\"\"\n area_rhombus(diagonal_1, diagonal_2)\n\nFinds area of the rhombus\n\n# Example\n\n```julia\narea_rhombus(10, 20) # returns 100.0\narea_rhombus(-1,-2) # returns DomainError\narea_rhombus(1,-2) # returns DomainError\narea_rhombus(-1,2) # returns DomainError\n```\n\"\"\"\nfunction area_rhombus(diagonal_1, diagonal_2)\n if diagonal_1 < 0 || diagonal_2 < 0\n throw(DomainError(\"area_rhombus() only accepts non-negative values\"))\n end\n return 1 / 2 * diagonal_1 * diagonal_2\nend", "meta": {"hexsha": "4b59320c6359b876db5e24afd2a7ff65ca5a6100", "size": 5560, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/area.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/area.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/area.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.693877551, "max_line_length": 90, "alphanum_fraction": 0.6949640288, "num_tokens": 1699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.964321448096903, "lm_q2_score": 0.8705972784807408, "lm_q1q2_score": 0.8395356282937707}} {"text": "module GeneralTridiagonal\n\nexport factorize!, solve!\n\n\"\"\"\n factorize!(β, α, γ, δ, p)\n\nComputes the LU factorization with partial pivoting for an `n×n` tridiagonal \nmatrix `A` with subdiagonal `β`, main diagonal `α` and superdiagonal `γ`. Thus,\nthe vector `α` has length `n`, whereas `β` and `γ` each have length `n-1`.\nFor example, if `n=5` then the matrix is given by\n\n α_1 γ_1\n β_1 α_2 γ_2\n A = β_2 α_3 γ_3\n β_3 α_4 γ_4\n β_4 α_5\n\nThe vector `δ` must have length `n-2` to hold the second superdiagonal of \nthe upper triangular factor, arising from the fill-in caused by pivoting.\nThe boolean vector `p` has length `n-1` and records the sequence of pivot\nchoices: `p[j]` is `true` if rows `j` and `j+1` were swapped at the `j`th \nstep.\n\nThe factorization is computed in place, so `β` is overwritten with the\nnonzero subdiagonal entries of `L`, and `α`, `γ` and `δ` hold the nonzero\nentries of `U`.\n\"\"\"\nfunction factorize!(β::Vector{T}, α::Vector{T}, γ::Vector{T}, δ::Vector{T}, \n p::Vector{Bool}) where T <: Number\n n = length(α)\n if ! ( length(β) == n-1 == length(γ) && length(δ) == n-2 )\n throw(BoundsError(\"Array sizes to not match\"))\n end\n for j = 1:n-2\n δ[j] = zero(T)\n if abs(α[j]) < abs(β[j])\n p[j] = true\n α[j], β[j] = β[j], α[j]\n γ[j], α[j+1] = α[j+1], γ[j]\n δ[j], γ[j+1] = γ[j+1], δ[j]\n else\n p[j] = false\n end\n β[j] = β[j] / α[j]\n α[j+1] -= β[j] * γ[j]\n if p[j]\n γ[j+1] = -β[j] * δ[j]\n end\n end\n if abs(α[n-1]) < abs(β[n-1])\n p[n-1] = true\n α[n-1], β[n-1] = β[n-1], α[n-1]\n γ[n-1], α[n] = α[n], γ[n-1]\n else\n p[n-1] = false\n end\n β[n-1] = β[n-1] / α[n-1]\n α[n] -= β[n-1] * γ[n-1]\nend\n\n\"\"\"\n solve!(b, β, α, γ, δ, p)\n\nSolves the tridiagonal linear system `Ax = b` using the LU factorization \ncomputed by `factorize`.\n\"\"\"\nfunction solve!(b::Vector{T}, β::Vector{T}, α::Vector{T}, γ::Vector{T}, \n δ::Vector{T}, p::Vector{Bool}) where T <: Number\n n = length(α)\n if ! ( length(β) == n-1 == length(γ) && length(δ) == n-2 )\n throw(BoundsError(\"Array sizes to not match\"))\n end\n for j = 1:n-1\n if p[j]\n b[j], b[j+1] = b[j+1], b[j]\n end\n b[j+1] -= β[j] * b[j]\n end\n b[n] /= α[n]\n b[n-1] = ( b[n-1] - γ[n-1] * b[n] ) / α[n-1]\n for j = n-2:-1:1\n b[j] = ( b[j] - γ[j] * b[j+1] - δ[j] * b[j+2] ) / α[j]\n end\nend\n\nend # module\n", "meta": {"hexsha": "2150262171a572e940190c4d965b43dfd84e4d5b", "size": 2606, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/appendixA/GeneralTridiagonal.jl", "max_stars_repo_name": "billmclean/ComputationalMathsNotes", "max_stars_repo_head_hexsha": "9d521fdf7ec407cca287997885d81c3150973415", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-30T21:30:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T21:30:20.000Z", "max_issues_repo_path": "src/appendixA/GeneralTridiagonal.jl", "max_issues_repo_name": "billmclean/ComputationalMathsNotes", "max_issues_repo_head_hexsha": "9d521fdf7ec407cca287997885d81c3150973415", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/appendixA/GeneralTridiagonal.jl", "max_forks_repo_name": "billmclean/ComputationalMathsNotes", "max_forks_repo_head_hexsha": "9d521fdf7ec407cca287997885d81c3150973415", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6136363636, "max_line_length": 80, "alphanum_fraction": 0.4980813507, "num_tokens": 949, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474194456935, "lm_q2_score": 0.8791467770088162, "lm_q1q2_score": 0.8392752019854649}} {"text": "# function to calculate the volume of a sphere\nfunction sphere_vol(r)\n # julia allows Unicode names (in UTF-8 encoding)\n # so either \"pi\" or the symbol π can be used\n return 4 / 3 * pi * r^3\nend\n\n# functions can also be defined more succinctly\nquadratic(a, sqr_term, b) = (-b + sqr_term) / 2a\n\n# calculates x for 0 = a*x^2+b*x+c, arguments types can be defined in function definitions\nfunction quadratic2(a::Float64, b::Float64, c::Float64)\n # unlike other languages 2a is equivalent to 2*a\n # a^2 is used instead of a**2 or pow(a,2)\n sqr_term = sqrt(b^2 - 4a * c)\n r1 = quadratic(a, sqr_term, b)\n r2 = quadratic(a, -sqr_term, b)\n # multiple values can be returned from a function using tuples\n # if the return keyword is omitted, the last term is returned\n r1, r2\nend\n\nunit_volume = sphere_vol(1)\n", "meta": {"hexsha": "f504546c9c7ce5e4c8824d5f6d9b29764b75929e", "size": 831, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test.jl", "max_stars_repo_name": "Sushant-Padha/julia-in-python", "max_stars_repo_head_hexsha": "b8c3aca9077d5005fbdaf8af0e4ad50b83c61988", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-18T06:36:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-18T06:36:43.000Z", "max_issues_repo_path": "test.jl", "max_issues_repo_name": "Sushant-Padha/julia-in-python", "max_issues_repo_head_hexsha": "b8c3aca9077d5005fbdaf8af0e4ad50b83c61988", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test.jl", "max_forks_repo_name": "Sushant-Padha/julia-in-python", "max_forks_repo_head_hexsha": "b8c3aca9077d5005fbdaf8af0e4ad50b83c61988", "max_forks_repo_licenses": ["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.625, "max_line_length": 90, "alphanum_fraction": 0.6847172082, "num_tokens": 252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474220263197, "lm_q2_score": 0.8791467738423873, "lm_q1q2_score": 0.8392752012313909}} {"text": "\"Square the sum of the first `n` positive integers\"\nfunction square_of_sum(n)\n return sum(1:n) * sum(1:n)\nend\n\n\"Sum the squares of the first `n` positive integers\"\nfunction sum_of_squares(n)\n return sum(map(x -> x * x, 1:n))\nend\n\n\"Subtract the sum of squares from square of the sum of the first `n` positive ints\"\nfunction difference(n)\n return square_of_sum(n) - sum_of_squares(n)\nend\n", "meta": {"hexsha": "86613f1d6bb70a64d080b36f7699dad215cef8bb", "size": 389, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/difference-of-squares/difference-of-squares.jl", "max_stars_repo_name": "res0nat0r/exercism", "max_stars_repo_head_hexsha": "b3f7df7cefee52cecb932af7ca80280060bfdaf4", "max_stars_repo_licenses": ["MIT"], "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": "res0nat0r/exercism", "max_issues_repo_head_hexsha": "b3f7df7cefee52cecb932af7ca80280060bfdaf4", "max_issues_repo_licenses": ["MIT"], "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": "res0nat0r/exercism", "max_forks_repo_head_hexsha": "b3f7df7cefee52cecb932af7ca80280060bfdaf4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9333333333, "max_line_length": 83, "alphanum_fraction": 0.7300771208, "num_tokens": 111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9546474181553805, "lm_q2_score": 0.8791467675095294, "lm_q1q2_score": 0.8392751917826207}} {"text": "#!/usr/bin/env julia\n\nexport pe8\n\nmodule PE8\n\nconst data=parse.(Int,collect(\n \"73167176531330624919225119674426574742355349194934\"*\n \"96983520312774506326239578318016984801869478851843\"*\n \"85861560789112949495459501737958331952853208805511\"*\n \"12540698747158523863050715693290963295227443043557\"*\n \"66896648950445244523161731856403098711121722383113\"*\n \"62229893423380308135336276614282806444486645238749\"*\n \"30358907296290491560440772390713810515859307960866\"*\n \"70172427121883998797908792274921901699720888093776\"*\n \"65727333001053367881220235421809751254540594752243\"*\n \"52584907711670556013604839586446706324415722155397\"*\n \"53697817977846174064955149290862569321978468622482\"*\n \"83972241375657056057490261407972968652414535100474\"*\n \"82166370484403199890008895243450658541227588666881\"*\n \"16427171479924442928230863465674813919123162824586\"*\n \"17866458359124566529476545682848912883142607690042\"*\n \"24219022671055626321111109370544217506941658960408\"*\n \"07198403850962455444362981230987879927244284909188\"*\n \"84580156166097919133875499200524063689912560717606\"*\n \"05886116467109405077541002256983155200055935729725\"*\n \"71636269561882670428252483600823257530420752963450\"\n));\n\nend\n\npe8(data::Vector{<:Integer}=PE8.data,n::Integer=13)=maximum(prod(data[i:i+n-1]) for i in 1:(length(data)-(n-1)))\n\nif !haskey(ENV,\"PROJECT_EULER_WITHOUT_RESULT\")\n pe8()|>print\nend\n", "meta": {"hexsha": "fdc26f2461d66fd8ac12ab4ba9e4cc4b4a45bee3", "size": 1428, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "8. Largest product in a series/8.jl", "max_stars_repo_name": "miRoox/ProjectEuler", "max_stars_repo_head_hexsha": "020e8efddbf0dde33f2b2561e7b636fa199be75c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-11-13T16:11:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T23:20:05.000Z", "max_issues_repo_path": "8. Largest product in a series/8.jl", "max_issues_repo_name": "miRoox/ProjectEuler", "max_issues_repo_head_hexsha": "020e8efddbf0dde33f2b2561e7b636fa199be75c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-12-27T15:12:05.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-27T15:12:05.000Z", "max_forks_repo_path": "8. Largest product in a series/8.jl", "max_forks_repo_name": "miRoox/ProjectEuler", "max_forks_repo_head_hexsha": "020e8efddbf0dde33f2b2561e7b636fa199be75c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.5945945946, "max_line_length": 112, "alphanum_fraction": 0.8291316527, "num_tokens": 511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474155747541, "lm_q2_score": 0.8791467675095294, "lm_q1q2_score": 0.8392751895138714}} {"text": "\"\"\"\r\n newtonRaphson(f,df,p0)\r\n\r\nadalah fungsi untuk menyelesaikan `f(x)=0` menggunakan metode newton. Metode ini\r\nmemerlukan turunan dari fungsi `f(x)` yaitu `df` dan nilai tebakan awal `p0`.\r\n\r\n# Examples\r\n```jl\r\njulia> f(x) = x^3-3*x+2;\r\n\r\njulia> df(x) = 3*x^2-3;\r\n\r\njulia> pk,flag,M = newtonRaphson(f,df,-2.4);\r\n\r\njulia> pk\r\n-2.0\r\n\r\njulia> flag\r\n0\r\n\r\njulia> M\r\n6×3 Array{Float64,2}:\r\n 0.0 -2.4 NaN\r\n 1.0 -2.07619 0.32381\r\n 2.0 -2.0036 0.0725945\r\n 3.0 -2.00001 0.00358742\r\n 4.0 -2.0 8.58992e-6\r\n 5.0 -2.0 4.91913e-11\r\n```\r\nreturn solusi `p0` dengan `flag` bernilai 0 jika metode bisection berhasil menemukan\r\nsolusi dan gagal jika tidak 0. Serta, matriks `M` yang berisi catatan proses tiap\r\niterasi `[k, pk, error]`\r\n\"\"\"\r\nfunction newtonRaphson(f,df,p0)\r\n # Definisikan nilai toleransi, maksimum iterasi dan tebakan awal\r\n delta = 10^-7;\r\n maxi = 100;\r\n pk = p0\r\n M = [0 pk NaN];\r\n # Mulai langkah iterasi\r\n flag = 1;\r\n for k = 2:maxi\r\n # Rumus metode Newton-Raphson\r\n pk1 = pk\r\n pk = pk1 - f(pk1)/df(pk1);\r\n # Hitung nilai galat mutlak dan relatif\r\n err = abs(pk-pk1);\r\n rel = 2*err/(abs(pk)+eps());\r\n M = [M; [k-1 pk err]]\r\n # Kriteria penghentian iterasi jika galat memenuhi toleransi.\r\n if err zero(x) ? x * log(x) : zero(x)\nxlogx(x::Real) = xlogx(float(x))\n\nxlogy{T<:FloatingPoint}(x::T, y::T) = x > zero(T) ? x * log(y) : zero(x)\nxlogy{T<:Real}(x::T, y::T) = xlogy(float(x), float(y))\nxlogy(x::Real, y::Real) = xlogy(promote(x, y)...)\n\nlogistic(x::FloatingPoint) = one(x) / (one(x) + exp(-x))\nlogistic(x::Real) = logistic(float(x))\n\nlogit(x::FloatingPoint) = log(x / (one(x) - x))\nlogit(x::Real) = logit(float(x))\n\nsoftplus(x::FloatingPoint) = x <= 0 ? log1p(exp(x)) : x + log1p(exp(-x))\nsoftplus(x::Real) = softplus(float(x))\n\ninvsoftplus(x::FloatingPoint) = log(exp(x) - one(x))\ninvsoftplus(x::Real) = invsoftplus(float(x))\n\n@vectorize_1arg Real xlogx\n@vectorize_2arg Real xlogy\n@vectorize_1arg Real logistic\n@vectorize_1arg Real logit\n@vectorize_1arg Real softplus\n@vectorize_1arg Real invsoftplus\n\n## logsumexp\n\nlogsumexp{T<:FloatingPoint}(x::T, y::T) = x > y ? x + log1p(exp(y - x)) : y + log1p(exp(x - y))\nlogsumexp{T<:Real}(x::T, y::T) = logsumexp(float(x), float(y))\nlogsumexp(x::Real, y::Real) = logsumexp(promote(x, y)...)\n\nfunction logsumexp{T<:Real}(x::AbstractArray{T})\n isempty(x) && return -Inf\n u = maximum(x)\n s = 0.\n for i = 1:length(x)\n \t@inbounds s += exp(x[i] - u)\n end\n log(s) + u\nend\n\n## softmax\n\nfunction softmax!{T<:Real}(r::AbstractArray, x::AbstractArray{T})\n\tn = length(x)\n\tlength(r) == n || throw(DimensionMismatch(\"Inconsistent array lengths.\"))\n\tu = maximum(x)\n\ts = 0.\n\tfor i = 1:n\n\t\t@inbounds s += (r[i] = exp(x[i] - u))\n\tend\n\tfor i = 1:n\n\t\tr[i] /= s\n\tend\n\tr\nend\n\nsoftmax!{T<:FloatingPoint}(x::AbstractArray{T}) = softmax!(x, x)\nsoftmax{T<:Real}(x::AbstractArray{T}) = softmax!(Array(Float64, size(x)), x)\n\n", "meta": {"hexsha": "31350f22e75fbf9b9eb5f531ee128ec255a3d704", "size": 1755, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mathfuns.jl", "max_stars_repo_name": "wildart/StatsBase.jl", "max_stars_repo_head_hexsha": "3885542a93d2de71a1102da030c798cd51749481", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mathfuns.jl", "max_issues_repo_name": "wildart/StatsBase.jl", "max_issues_repo_head_hexsha": "3885542a93d2de71a1102da030c798cd51749481", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mathfuns.jl", "max_forks_repo_name": "wildart/StatsBase.jl", "max_forks_repo_head_hexsha": "3885542a93d2de71a1102da030c798cd51749481", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5909090909, "max_line_length": 95, "alphanum_fraction": 0.6301994302, "num_tokens": 635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.945801271704518, "lm_q2_score": 0.8872046026642944, "lm_q1q2_score": 0.8391192414619912}} {"text": "using EngEconomics, Roots, Plots, ColorSchemes\nplotly()\n\n# Given\n# - Finedetail = A, Simplicity = B\nstrA = \"Finedetail\"\nstrB = \"Simplicity\"\nlifeA = 7\nlifeB = 10\nPA = 200000 # Initial Cost of A - [$]\nPB = 350000 # Initial Cost of B - [$]\nMA = 10000 # Maintenance Cost of A - [$/yr]\nUMA = 0.05 # Maintenance Cost of A - [$/units]\nMB = 20000 # Maintenance Cost of B - [$/yr]\nUMB = 0.01 # Maintenance Cost of B - [$/units]\nLA = 1.25 # Labor Cost of A - [$/unit]\nLB = 0.50 # Labor Cost of B - [$/unit]\nOA = 6500 # \"Other\" Costs of A - [$/yr]\nUOA = 0.95 # \"Other\" Costs of A - [$/unit]\nOB = 15500 # \"Other\" Costs of B - [$/yr]\nUOB = 0.55 # \"Other\" Costs of B - [$/unit]\nFA = 5000 # Salvage Value of A - [$]\nFB = 20000 # Salvage Value of B - [$]\nMARR = 0.15\n\n# Find\n# (a.) Who is the preferred supplier if sales are 30,000 units per year? Use an\n# annual worth comparison.\nunitRate = 30000 # [units/yr]\nEUAWA = -PA * capitalRecoveryFactor(MARR, lifeA) + -MA + -UMA * unitRate + -LA * unitRate + -OA + -UOA * unitRate + FA * sinkingFundFactor(MARR, lifeA)\nEUAWB = -PB * capitalRecoveryFactor(MARR, lifeB) + -MB + -UMB * unitRate + -LB * unitRate + -OB + -UOB * unitRate + FB * sinkingFundFactor(MARR, lifeB)\n\nif EUAWA > EUAWB\n\tprintln(strA, \" is the preferred supplier if unit sales are \", unitRate, \" because its EUAW exceeds that of \", strB)\nelse\n\tprintln(strB, \" is the preferred supplier if unit sales are \", unitRate, \" because its EUAW exceeds that of \", strA)\nend\n\n# (b.) Who is the preferred supplier if sales are 200,000 units per year. Use\n# annual worth comparison\nunitRate = 200000 # [units/yr]\nEUAWA = -PA * capitalRecoveryFactor(MARR, lifeA) + -MA + -UMA * unitRate + -LA * unitRate + -OA + -UOA * unitRate + FA * sinkingFundFactor(MARR, lifeA)\nEUAWB = -PB * capitalRecoveryFactor(MARR, lifeB) + -MB + -UMB * unitRate + -LB * unitRate + -OB + -UOB * unitRate + FB * sinkingFundFactor(MARR, lifeB)\n\nif EUAWA > EUAWB\n\tprintln(strA, \" is the preferred supplier if unit sales are \", unitRate, \" because its EUAW exceeds that of \", strB)\nelse\n\tprintln(strB, \" is the preferred supplier if unit sales are \", unitRate, \" because its EUAW exceeds that of \", strA)\nend\n\n# (c.) How sensitive is the choice of supplier to sales level? Experiment with\n# sales levels between 30,000 and 200,000 units per year. At what sales\n# level will the costs of the two melters be equal?\nunitRateVector = collect(30000:1000:200000)\nEUAWA = -PA * capitalRecoveryFactor(MARR, lifeA) .+ -MA .+ -UMA * unitRateVector .+ -LA * unitRateVector .+ -OA .+ -UOA * unitRateVector .+ FA * sinkingFundFactor(MARR, lifeA)\nEUAWB = -PB * capitalRecoveryFactor(MARR, lifeB) .+ -MB .+ -UMB * unitRateVector .+ -LB * unitRateVector .+ -OB .+ -UOB * unitRateVector .+ FB * sinkingFundFactor(MARR, lifeB)\n\nplot(unitRateVector, EUAWA, xlabel=\"Units\", ylabel=\"Annual Worth (\\$)\", label=strA,\n\ttitle=\"Sensitivity of Alternatives to Unit Sales\", legend=:outerbottomright)\nplot!(unitRateVector, EUAWB, label=strB)\n\nEUAWA_func(u) = -PA * capitalRecoveryFactor(MARR, lifeA) .+ -MA .+ -UMA * u .+ -LA * u .+ -OA .+ -UOA * u .+ FA * sinkingFundFactor(MARR, lifeA)\nEUAWB_func(u) = -PB * capitalRecoveryFactor(MARR, lifeB) .+ -MB .+ -UMB * u .+ -LB * u .+ -OB .+ -UOB * u .+ FB * sinkingFundFactor(MARR, lifeB)\nf(u) = EUAWA_func(u) - EUAWB_func(u)\nunitBreakEven = find_zero(f, 34000)\n\nprintln(\"The annual worths of both alternatives are sensitive to the unit sales rate.\")\nprintln(\"The breakeven unit sales rate is: \", unitBreakEven)\nprintln(\"From the plot, we understand that if sales are below the breakeven unit sales rate, then Finedetail is preferred. However, if the unit sales rate exceeds the breakeven unit sales rate, then simplicity is preferred\")\n", "meta": {"hexsha": "70c4aa6b86f646e3b50193e392f149f02d0c93b8", "size": 3729, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problems/ps8/p4.jl", "max_stars_repo_name": "zborffs/EngineeringEconomics.jl", "max_stars_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problems/ps8/p4.jl", "max_issues_repo_name": "zborffs/EngineeringEconomics.jl", "max_issues_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problems/ps8/p4.jl", "max_forks_repo_name": "zborffs/EngineeringEconomics.jl", "max_forks_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.2714285714, "max_line_length": 224, "alphanum_fraction": 0.681952266, "num_tokens": 1218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012732322215, "lm_q2_score": 0.8872045966995028, "lm_q1q2_score": 0.8391192371758693}} {"text": "function linsolve_cg( LF::LF3dGrid, b::Array{Float64,1};\n x0 = nothing,\n NiterMax = 1000, TOL=5.e-10,\n convmsg=true, showprogress=false )\n #\n Npoints = size(b)[1]\n if x0 == nothing\n x = zeros(Float64, Npoints)\n else\n x = copy(x0)\n end\n #\n r = zeros( Float64, Npoints )\n p = zeros( Float64, Npoints )\n #\n L_x = apply_Laplacian( LF, x )\n for ip = 1 : Npoints\n r[ip] = b[ip] - L_x[ip]\n p[ip] = r[ip]\n end\n\n rsold = dot( r, r )\n for iter = 1 : NiterMax\n #\n L_x = apply_Laplacian( LF, p )\n #\n α = rsold/dot( p, L_x )\n #\n x[:] = x[:] + α * p[:] # FIXME use x[:] to force x to be copied, not referenced\n r[:] = r[:] - α * L_x[:]\n #\n rsnew = dot( r, r )\n # deltars = rsold - rsnew\n if showprogress\n @printf(\"%8d %20.10f\\n\", iter, sqrt(rsnew))\n end\n #\n if sqrt(rsnew) < TOL\n if convmsg\n @printf(\"#Convergence achieved in linsolve_cg: %8d iterations.\\n\", iter)\n end\n break\n end\n #\n p = r + (rsnew/rsold) * p\n #\n rsold = rsnew\n end\n #\n return x\n #\nend\n", "meta": {"hexsha": "c5df466cdca5f92b986d83282ac00fe738ff49e3", "size": 1119, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "LF/v_0.4.5/LF_common/linsolve_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/v_0.4.5/LF_common/linsolve_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/v_0.4.5/LF_common/linsolve_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": 21.1132075472, "max_line_length": 84, "alphanum_fraction": 0.4977658624, "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897475985936, "lm_q2_score": 0.8918110346549902, "lm_q1q2_score": 0.8390066781987089}} {"text": "export soundspeed, halfwavelength, wavenumber\nexport flutelength, toneholelength, closedholecorrection\n\n\"\"\"\n 𝑐 = soundspeed(ϑ=25.0)\n\nCalculate the speed of sound in air of temperature ϑ in m/s\n\"\"\"\nfunction soundspeed(ϑ=25.0)\n 𝛾 = 1.400 # heat capacity ratio of air\n 𝑅 = 8.31446261815324 # molar gas constant (J/mol/K)\n 𝑀 = 0.028965369 # mean molar mass of air (kg/mol)\n 𝑐 = √(𝛾*𝑅/𝑀 *273.15)*√(1.0 + ϑ/273.15)\n return 𝑐\nend\n\n\"\"\"\n 𝜔 = angularfreq(𝑓=440.0)\n\ncalculate angular frequency of 𝑓 in rad/s\n\"\"\"\nfunction angularfreq(𝑓=440.0)\n 𝜔 = 2π*𝑓\n return 𝜔\nend\n\n\"\"\"\n 𝑘 = wavenumber(𝑓=440.0; 𝜗=25.0)\n\ncalculate wavenumber of given frequency 𝑓 in air of temperature 𝜗 in m⁻¹\n\"\"\"\nfunction wavenumber(𝑓=440.0; ϑ=25.0)\n 𝑐 = soundspeed(ϑ)\n 𝜔 = angularfreq(𝑓)\n 𝑘 = 𝜔/𝑐\n return 𝑘\nend\n\n\"\"\"\n 𝜆 = halfwavelength(𝑓=440.0; ϑ=25.0)\n\ncalculate half-wavelength of given frequency 𝑓 in air of temperature ϑ\n\"\"\"\nfunction halfwavelength(𝑓=440.0; ϑ=25.0)\n 𝑐 = soundspeed(ϑ)\n 𝜆 = 𝑐/2𝑓\n return 1000𝜆 # (to mm)\nend\n\n\"\"\"\n ℓₜ = flutelength(𝑓=440.0; ϑ=25.0, ⌀=19.0, ℎ=3.5, 𝛥ℓₑ=57.0, 𝛥ℓᵥ=0.0)\n\nCalculate flute length from embouchure-hole to open-end\n for fundamental frequency 𝑓, temperature ϑ, open-end bore diameter ⌀,\n wall thickness ℎ, embouchure correction 𝛥ℓₑ and closed-hole correction 𝛥ℓᵥ\n\"\"\"\nfunction flutelength(𝑓=440.0; ϑ=25.0, ⌀=19.0, ℎ=3.5, 𝛥ℓₑ=57.0, 𝛥ℓᵥ=0.0)\n 𝜆 = halfwavelength(𝑓; ϑ=ϑ)\n ⌀₊ = ⌀ + 2ℎ\n ϖ = ⌀/⌀₊\n 𝜍 = 0.6133⌀/2\n 𝜚 = 0.8216⌀/2\n 𝛥ℓₜ = 𝜚 + ϖ * (𝜍-𝜚) + 0.057ϖ * (1-ϖ ^5)\n ℓₜ = 𝜆 - 𝛥ℓₑ - 𝛥ℓᵥ - 𝛥ℓₜ\n return ℓₜ\nend\n\n\"\"\"\n ℓₕ = toneholelength(𝑓=440.0, 𝑓ₜ=415.305, 𝑑=9.0; ϑ=25.0, ⌀=19.0, ℎ=3.5, 𝛥ℓₑ=57.0, 𝛥ℓᵥ=0.0)\n\nCalculate distance from embouchure hole center to tone hole center\n for open frequency 𝑓, closed frequency 𝑓ₜ, tone-hole diameter 𝑑,\n temperature ϑ, tone-hole bore diameter ⌀, tone-hole height ℎ,\n embouchure correction 𝛥ℓₑ and closed-hole correction 𝛥ℓᵥ\n\"\"\"\nfunction toneholelength(𝑓=440.0, 𝑓ₜ=415.305, 𝑑=9.0; ϑ=25.0, ⌀=19.0, ℎ=3.5, 𝛥ℓₑ=57.0, 𝛥ℓᵥ=0.0)\n 𝜆 = halfwavelength(𝑓; ϑ=ϑ)\n 𝑔 = 𝑓/𝑓ₜ - 1\n 𝜙 = (ℎ+𝑑) * (⌀/𝑑)^2 - 0.45⌀\n 𝑧 = 𝑔/2 * √(1 + 4𝜙/(𝑔*𝜆)) - 𝑔/2\n 𝛥ℓₕ = 𝑧 * 𝜆\n ℓₕ = 𝜆 - 𝛥ℓₑ - 𝛥ℓᵥ - 𝛥ℓₕ\n return ℓₕ\nend\n\n\"\"\"\n 𝛥𝜆ₕ = closedholecorrection(𝑓=440.0, 𝑓ₜ=415.305, 𝑑=9.0; ϑ=25.0, ⌀=19.0, ℎ=3.5, 𝛥ℓₑ=57.0, 𝛥ℓᵥ=0.0)\n\nCalculate correction due to closed hole\n for open frequency 𝑓, closed frequency 𝑓ₜ, tone-hole diameter 𝑑,\n temperature ϑ, tone-hole bore diameter ⌀, tone-hole height ℎ,\n embouchure correction 𝛥ℓₑ and closed-hole correction 𝛥ℓᵥ\n\"\"\"\nfunction closedholecorrection(𝑓=440.0, 𝑓ₜ=415.305, 𝑑=9.0; ϑ=25.0, ⌀=19.0, ℎ=3.5, 𝛥ℓₑ=57.0, 𝛥ℓᵥ=0.0)\n 𝑘 = wavenumber(𝑓; ϑ=ϑ)\n 𝜆ₜ= halfwavelength(𝑓ₜ; ϑ=ϑ)\n ℓₕ = toneholelength(𝑓, 𝑓ₜ, 𝑑; ϑ=ϑ, ⌀=⌀, ℎ=ℎ, 𝛥ℓₑ=𝛥ℓₑ, 𝛥ℓᵥ=𝛥ℓᵥ)\n 𝜙 = 𝑑^2*ℎ / ⌀^2\n ϵ = 2/π * atan(2𝑑/13ℎ)\n 𝛿ₕ = 𝜆ₜ - 𝛥ℓₑ - ℓₕ\n 𝛥𝜆ₕ = (sin(𝑘*𝛿ₕ)^2 - ϵ*cos(𝑘*𝛿ₕ)^2) * 𝜙\n return 𝛥𝜆ₕ\nend\n", "meta": {"hexsha": "5970823b0fe24b878e7e78f7a32b6bf624eaff4a", "size": 2848, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lib/formulae.jl", "max_stars_repo_name": "isaacwhanson/scad-flute", "max_stars_repo_head_hexsha": "3046cc6f536308192bd79828b4d4538d6eca46f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2020-03-31T05:00:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-22T16:19:21.000Z", "max_issues_repo_path": "src/lib/formulae.jl", "max_issues_repo_name": "isaacwhanson/scad-flute", "max_issues_repo_head_hexsha": "3046cc6f536308192bd79828b4d4538d6eca46f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lib/formulae.jl", "max_forks_repo_name": "isaacwhanson/scad-flute", "max_forks_repo_head_hexsha": "3046cc6f536308192bd79828b4d4538d6eca46f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-03-31T10:20:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-23T15:05:36.000Z", "avg_line_length": 27.3846153846, "max_line_length": 99, "alphanum_fraction": 0.6393960674, "num_tokens": 1687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959762057376384, "lm_q2_score": 0.87407724336544, "lm_q1q2_score": 0.838906173398293}} {"text": "function identical_matrix(n::Integer)\n ret = zeros(n, n)\n for itr1 in 1 : n\n ret[itr1, itr1] = 1\n end\n return ret\nend\n\nfunction inner_product(mat::Matrix, a::Integer, b::Integer)\n # if $a$ or $b$ are out of bound, return $0$\n if a > size(mat, 2) || b > size(mat, 2)\n return 0\n end\n # initialize the result\n ret = 0\n # calculate the inner (dot) product of column $a$ and $b$\n for itr1 in 1 : size(mat, 1)\n ret += mat[itr1, a] * mat[itr1, b]\n end\n return ret\nend\n\nfunction column_elimination!(mat::Matrix, a::Integer, b::Integer, k::Number, row::Integer = 1)\n for itr1 in row : size(mat, 1)\n mat[itr1, b] += mat[itr1, a] * k\n end\n return mat\nend\n\nfunction mgs(mat::Matrix)\n # make a copy of the matrix as $Q$\n Q = float(copy(mat))\n # it's assumed that the matrix has $m$ rows and $n$ columns\n m, n = size(mat)\n # make a identical matrix as $R$\n R = identical_matrix(n)\n for itr1 in 1 : n\n # calculate the norm of the column vector\n norm = sqrt(inner_product(Q, itr1, itr1))\n # if the column is $0$, just skip it\n norm == 0 && continue\n # normalize the column vector\n for itr2 in 1 : m\n Q[itr2, itr1] /= norm\n end\n # multiply the $itr1$th row with the norm\n for itr2 in itr1 : n\n R[itr1, itr2] *= norm\n end\n # substract the projections of the current vector\n # from the remaining vectors\n for itr2 in (itr1 + 1) : n\n scaler = inner_product(Q, itr1, itr2)\n column_elimination!(Q, itr1, itr2, -scaler)\n # add the corresponding vectors to some rows\n for itr3 in itr2 : n\n R[itr1, itr3] += R[itr2, itr3] * scaler\n end\n end\n end\n return Q, R\nend", "meta": {"hexsha": "48ac26a66effdc62c02a61acdcde334bb133187f", "size": 1830, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "linear-algebra/mgs.jl", "max_stars_repo_name": "Shimushushushu/Etude-Rhapsody", "max_stars_repo_head_hexsha": "cdca63ca92a44f0f31e716cf4acd3e0de17c9181", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linear-algebra/mgs.jl", "max_issues_repo_name": "Shimushushushu/Etude-Rhapsody", "max_issues_repo_head_hexsha": "cdca63ca92a44f0f31e716cf4acd3e0de17c9181", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear-algebra/mgs.jl", "max_forks_repo_name": "Shimushushushu/Etude-Rhapsody", "max_forks_repo_head_hexsha": "cdca63ca92a44f0f31e716cf4acd3e0de17c9181", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5161290323, "max_line_length": 94, "alphanum_fraction": 0.5590163934, "num_tokens": 564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620562254525, "lm_q2_score": 0.8740772269642949, "lm_q1q2_score": 0.8389061566510932}} {"text": "\"\"\"\nksintegrate: integrate kuramoto-sivashinsky equation (Julia)\n u_t = -u*u_x - u_xx - u_xxxx, domain x in [0,Lx], periodic BCs \n\n inputs\n u = initial condition (vector of u(x) values on uniform gridpoints))\n Lx = domain length\n dt = time step\n Nt = number of integration timesteps\n nsave = save every nsave-th time step\n\n outputs\n\n u = final state, vector of u(x, Nt*dt) at uniform x gridpoints\n\nThis implementation has two improvements over ksintegrateNaive.jl. It uses \n (1) in-place FFTs\n (2) loop fusion: Julia can translate arithmetic vector expressions in dot syntax \n to single for loop over the components, which should be much faster than\n constructing a temporary vector for each operation in the vector expression. \n\"\"\" \nfunction ksintegrateInplace(u, Lx, dt, Nt)\n u = (1+0im)*u # force u to be complex\n Nx = length(u) # number of gridpoints\n kx = vcat(0:Nx/2-1, 0:0, -Nx/2+1:-1)# integer wave #s, exp(2*pi*i*kx*x/L)\n alpha = 2*pi*kx/Lx # real wavenumbers, exp(i*alpha*x)\n D = 1im*alpha # spectral D = d/dx operator \n L = alpha.^2 - alpha.^4 # spectral L = -D^2 - D^4 operator\n G = -0.5*D # spectral -1/2 D operator, to eval -u u_x = 1/2 d/dx u^2\n\n # convenience variables\n dt2 = dt/2\n dt32 = 3*dt/2\n A_inv = (ones(Nx) - dt2*L).^(-1)\n B = ones(Nx) + dt2*L\n\n # compute FFTW plans\n FFT! = plan_fft!(u, flags=FFTW.ESTIMATE)\n IFFT! = plan_ifft!(u, flags=FFTW.ESTIMATE)\n\n # compute nonlinear term Nn == -u u_x and Nuprev (Nu at prev timestep)\n Nn = G.*fft(u.^2) # Nn == -1/2 d/dx (u^2) = -u u_x\n Nn1 = copy(Nn) # use Nn1 = Nn at first time step\n FFT!*u\n\n # timestepping loop\n for n = 0:Nt\n\n Nn1 .= Nn # shift nonlinear term in time\n Nn .= u # put u into N in prep for comp of nonlineat\n \n IFFT!*Nn # transform Nn to gridpt values, in place\n Nn .= Nn.*Nn # collocation calculation of u^2\n FFT!*Nn # transform Nn back to spectral coeffs, in place\n\n Nn .= G.*Nn\n\n # loop fusion! Julia translates the folling line of code to a single for loop. \n u .= A_inv .*(B .* u .+ dt32.*Nn .- dt2.*Nn1) \n end\n\n IFFT!*u\n real(u)\nend\n", "meta": {"hexsha": "268650cd784a67f01cd40f423a6afc5391158929", "size": 2388, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "codes/ksintegrateInplace.jl", "max_stars_repo_name": "raphbacher/julia-intro", "max_stars_repo_head_hexsha": "ecf7d683b46a75fa2214edf55e9873ee57de3834", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33, "max_stars_repo_stars_event_min_datetime": "2017-07-21T17:56:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-10T07:56:55.000Z", "max_issues_repo_path": "codes/ksintegrateInplace.jl", "max_issues_repo_name": "raphbacher/julia-intro", "max_issues_repo_head_hexsha": "ecf7d683b46a75fa2214edf55e9873ee57de3834", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2017-07-24T03:40:18.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-11T01:34:23.000Z", "max_forks_repo_path": "codes/ksintegrateInplace.jl", "max_forks_repo_name": "raphbacher/julia-intro", "max_forks_repo_head_hexsha": "ecf7d683b46a75fa2214edf55e9873ee57de3834", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2017-07-24T00:46:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-02T14:33:02.000Z", "avg_line_length": 36.7384615385, "max_line_length": 97, "alphanum_fraction": 0.5707705193, "num_tokens": 754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172644875641, "lm_q2_score": 0.8840392893839085, "lm_q1q2_score": 0.8388801441817085}} {"text": "using LinearAlgebra \nusing Plots \nusing IterativeSolvers\n\nfunction func(y,t,ϵ)\n return -(1/ϵ)*(y-sin(t)); \nend\n\nfunction actual_solution(t,ϵ)\n return (sin(t) - ϵ*cos(t))/(1+ϵ^2) + (1 + ϵ/(1+ϵ^2))*exp(-t/ϵ); \nend\n\nfunction compute_solution(t,ϵ)\n n = length(t);\n y = zeros(n);\n for i in 1:n\n y[i] = actual_solution(t[i],ϵ); \n end\n return y\nend\n\nfunction explicit_euler(t,y0,ϵ)\n n = length(t);\n y = zeros(n);\n y[1] = y0;\n dt = t[2]-t[1];\n for i in 2:n\n y[i] = y[i-1] + dt*func(y[i-1],t[i-1],ϵ); \n end\n return y;\nend\n\nfunction sor_implicit_euler(t,y0,ϵ) \n n = length(t);\n y = zeros(n);\n y[1] = y0;\n dt = t[2]-t[1];\n res = 100;\n τ = 1e-6;\n iter = 1e6; \n κ2 = (dt/ϵ); \n κ1 = 1/(1 + κ2);\n κ3 = 1/κ1;\n it = 0;\n while (itτ)\n for i in 2:n \n y[i] = κ1*(y[i-1] + κ2*sin(t[i])); \n end\n for i in 2:n \n res+= κ2*sin(t[i]) + y[i-1] - κ3*y[i];\n end\n res = sqrt(abs(res/n^2));\n it += 1;\n end\n return y;\nend \n\nfunction sor_trapezoidal_method(t,y0,ϵ)\n n = length(t);\n y = zeros(n);\n y[1] = y0;\n dt = t[2]-t[1];\n res = 100;\n τ = 1e-6;\n iter = 1e6; \n κ1 = (dt/(2*ϵ)); \n κ2 = 1 - κ1;\n κ3 = 1 + κ1;\n κ4 = 1/κ3;\n it = 0;\n while (itτ)\n for i in 2:n \n y[i] = κ4*(κ1*(sin(t[i]) + sin(t[i-1])) + κ2*y[i-1]);\n end \n for i in 2:n \n res += κ1*(sin(t[i]) + sin(t[i-1])) + κ2*y[i-1] - κ3*y[i];\n end\n res = sqrt(abs(res/n^2));\n it += 1;\n end\n return y;\nend\n\nfunction norm(y1,y2) \n n = length(y1);\n norm = 0;\n for i = 1:n \n norm += abs(y1[i]-y2[i]);\n end\n norm = sqrt(norm/n*n);\n println(\"The norm is \",norm)\nend\n\nx0 = 0;\nxl = pi; \nN = 99;\ny0 = 1;\nx = LinRange(x0,xl,N)\n\nϵ = 1;\ny_a = compute_solution(x,ϵ);\ny = sor_trapezoidal_method(x,y0,ϵ);\nplot(x,y)\np1 = plot!(x,y_a,title=\"Symplectic ϵ=1\")\nnorm(y,y_a);\n\nϵ = 0.1;\ny_a = compute_solution(x,ϵ);\ny = sor_trapezoidal_method(x,y0,ϵ);\nplot(x,y)\np2 = plot!(x,y_a,title=\"Symplectic ϵ=0.1\")\nnorm(y,y_a);\n\nϵ = 0.01;\ny_a = compute_solution(x,ϵ);\ny = sor_trapezoidal_method(x,y0,ϵ);\nplot(x,y)\np3 = plot!(x,y_a,title=\"Symplectic ϵ=0.01\")\nnorm(y,y_a);\n\nϵ = 0.001;\ny_a = compute_solution(x,ϵ);\ny = sor_trapezoidal_method(x,y0,ϵ);\nplot(x,y)\np4 = plot!(x,y_a,title=\"Symplectic ϵ=0.001\")\nnorm(y,y_a);\n\nplot(p1,p2,p3,p4,layout=(2,2),legend=false)\n\nx0 = 0;\nxl = pi; \nN = 99;\ny0 = 1;\nx = LinRange(x0,xl,N)\n\nϵ = 1;\ny_a = compute_solution(x,ϵ);\ny = explicit_euler(x,y0,ϵ);\nplot(x,y)\np1 = plot!(x,y_a,title=\"Explcit Euler ϵ=1\")\nnorm(y,y_a);\n\nϵ = .1;\ny_a = compute_solution(x,ϵ);\ny = explicit_euler(x,y0,ϵ);\nplot(x,y)\np2 = plot!(x,y_a,title=\"Explcit Euler ϵ=0.1\")\nnorm(y,y_a);\n\nϵ = .01;\ny_a = compute_solution(x,ϵ);\ny = explicit_euler(x,y0,ϵ);\nplot(x,y)\np3 = plot!(x,y_a,title=\"Explcit Euler ϵ=0.01\")\nnorm(y,y_a);\n\nϵ = .001;\ny_a = compute_solution(x,ϵ);\ny = explicit_euler(x,y0,ϵ);\nplot(x,y)\np4 = plot!(x,y_a,title=\"Explcit Euler ϵ=0.001\")\nnorm(y,y_a);\n\nplot(p1,p2,p3,p4,layout=(2,2),legend=false)\n\nx0 = 0;\nxl = pi; \nN = 99;\ny0 = 1;\nx = LinRange(x0,xl,N);\n\nϵ = 1;\ny_a = compute_solution(x,ϵ);\ny = sor_implicit_euler(x,y0,ϵ);\nplot(x,y)\np1 = plot!(x,y_a,title=\"Implicit Euler ϵ=1\")\nnorm(y,y_a);\n\nϵ = 0.1;\ny_a = compute_solution(x,ϵ);\ny = sor_implicit_euler(x,y0,ϵ);\nplot(x,y)\np2 = plot!(x,y_a,title=\"Implicit Euler ϵ=0.1\")\nnorm(y,y_a);\n\nϵ = 0.01;\ny_a = compute_solution(x,ϵ);\ny = sor_implicit_euler(x,y0,ϵ);\nplot(x,y)\np3 = plot!(x,y_a,title=\"Implicit Euler ϵ=0.01\")\nnorm(y,y_a);\n\nϵ = 0.001;\ny_a = compute_solution(x,ϵ);\ny = sor_implicit_euler(x,y0,ϵ);\nplot(x,y)\np4 = plot!(x,y_a,title=\"Implicit Euler ϵ=0.001\")\nnorm(y,y_a);\n\nplot(p1,p2,p3,p4,layout=(2,2),legend=false)\n\n\n", "meta": {"hexsha": "62581c9459e4fbf8ed9646b6867c0b850de27d06", "size": 3784, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Numerical_Programming/Stiff_Equations/Stiff Differential Equations.jl.jl", "max_stars_repo_name": "dynamic-queries/PDEs", "max_stars_repo_head_hexsha": "2be01c4b4a67a56ab2c5730acc6c9ffb2904b502", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Numerical_Programming/Stiff_Equations/Stiff Differential Equations.jl.jl", "max_issues_repo_name": "dynamic-queries/PDEs", "max_issues_repo_head_hexsha": "2be01c4b4a67a56ab2c5730acc6c9ffb2904b502", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Numerical_Programming/Stiff_Equations/Stiff Differential Equations.jl.jl", "max_forks_repo_name": "dynamic-queries/PDEs", "max_forks_repo_head_hexsha": "2be01c4b4a67a56ab2c5730acc6c9ffb2904b502", "max_forks_repo_licenses": ["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.6403940887, "max_line_length": 70, "alphanum_fraction": 0.547832981, "num_tokens": 1601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813501370537, "lm_q2_score": 0.877476800298183, "lm_q1q2_score": 0.8388514562629987}} {"text": "@doc \"\"\"\n Fourth-Order Runge-Kutta Method\n Supported by:\n -PhD Kelvyn B. Sánchez kelvyn.baruc@gmail.com\n \"\"\" ->\n\nfunction rk4(f, tspan, y0; h = 1)\ntint = floor((tspan[end] - tspan[1])/h) + 1\n t = range(tspan[1],tspan[end],length=Int(tint))\n\n#t = linspace(tspan[1], tspan[end],tint)\ny = zeros(Int(tint), length(y0))\ny[1,:] = y0\n\n try\n error = f(t[1],y0)\n\n for i=1:1:(length(t) - 1)\n ymid = zeros(1,Int(length(y0)))\n k1 = zeros(1,Int(length(y0)))\n k2 = zeros(1,Int(length(y0)))\n k3 = zeros(1,Int(length(y0)))\n k4 = zeros(1,Int(length(y0)))\n\n for j=1:length(y0)\n k1[1,j] = f(t[i],y[i,:])[j]\n ymid[1,j] = y[i,j] + k1[1,j]*(h/2)\n end\n\n for j=1:length(y0)\n k2[1,j] = f(t[i] + (1/2)*h,ymid)[j]\n ymid[1,j] = y[i,j] + k2[1,j]*(h/2)\n end\n\n for j=1:length(y0)\n k3[1,j] = f(t[i] + (1/2)*h,ymid)[j]\n ymid[1,j] = y[i,j] + k3[1,j]*h\n end\n\n for j=1:length(y0)\n k4[1,j] = f(t[i] + h,ymid)[j]\n end\n\n for j=1:length(y0)\n y[i+1,j] = y[i,j] + (1/6)*(k1[1,j] + 2*(k2[1,j] + k3[1,j]) + k4[1,j])*h\n end\n end\n\n return t, y\n catch\n throw(ErrorException(\"The number of initial values does not match the number of equations\"))\n end\n\n end\n", "meta": {"hexsha": "875f16b6b859832424f3d3fe4967d0a1f86b5127", "size": 1637, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/rk4.jl", "max_stars_repo_name": "Kelvyn88/ODEs.jl", "max_stars_repo_head_hexsha": "15c096f9f4cc6cf3e2f01a9917d3e3c737fe2c1a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/rk4.jl", "max_issues_repo_name": "Kelvyn88/ODEs.jl", "max_issues_repo_head_hexsha": "15c096f9f4cc6cf3e2f01a9917d3e3c737fe2c1a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rk4.jl", "max_forks_repo_name": "Kelvyn88/ODEs.jl", "max_forks_repo_head_hexsha": "15c096f9f4cc6cf3e2f01a9917d3e3c737fe2c1a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7636363636, "max_line_length": 103, "alphanum_fraction": 0.3866829566, "num_tokens": 524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248140158417, "lm_q2_score": 0.8933094152856196, "lm_q1q2_score": 0.8388397075471792}} {"text": "# multivariate gamma function\n# Chikuse, 2003 Eq. 1.5.7\nmvgamma(m, a) = π^(m * (m - 1)//4) * prod(i -> gamma(a - (i - 1)//2), 1:m)\n\n# tr(A'B)\ntr_At_B(A, B) = sum((Ai, Bi) -> dot(Ai, Bi), zip(eachcol(A), eachcol(B)))\n\n# hypergeometric functions with matrix arguments\npFq((), (), x) = exp(tr(x)) # ₀F₀\n# TODO: Implement ₀F₁\n# see P Koev, A Edelman. The efficient evaluation of the hypergeometric function of a\n# matrix argument. Math. Comp. 75 (2006), 833-846\n# pFq(a::NTuple{p}, b::NTuple{q}, x)\n", "meta": {"hexsha": "e15c5ad76bbc09961f37f7148682e1e881a9d499", "size": 495, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/specialfunctions.jl", "max_stars_repo_name": "TigerZhao007/ManifoldMeasures.jl", "max_stars_repo_head_hexsha": "797f0bbe70bd553987fb4375b332ac0e907cc14e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-05T10:07:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T10:07:03.000Z", "max_issues_repo_path": "src/specialfunctions.jl", "max_issues_repo_name": "TigerZhao007/ManifoldMeasures.jl", "max_issues_repo_head_hexsha": "797f0bbe70bd553987fb4375b332ac0e907cc14e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/specialfunctions.jl", "max_forks_repo_name": "TigerZhao007/ManifoldMeasures.jl", "max_forks_repo_head_hexsha": "797f0bbe70bd553987fb4375b332ac0e907cc14e", "max_forks_repo_licenses": ["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.3571428571, "max_line_length": 85, "alphanum_fraction": 0.6262626263, "num_tokens": 196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9736446471538803, "lm_q2_score": 0.8615382094310357, "lm_q1q2_score": 0.8388320659310665}} {"text": "#=\n\n From https://math.stackexchange.com/questions/513250/conditional-probability-question-with-cards-where-the-other-side-color-is-to-be\n \"\"\"\n A box contains three cards. One card is red on both sides, one card is green on both sides, \n and one card is red on one side and green on the other. One card is selected from the \n box at random, and the color on one side is observed. If this side is green, what is \n the probability that the other side of the card is also green?\n\n ... the answer to this question is 2/3.\n \"\"\"\n\n Give that the color of card is green, then the probability \n of the different cards are:\n\n Distributions of variable selected_card\n all_green => 67030 (0.670300)\n red_green => 32970 (0.329700)\n\n I.e. the probability that it's the all green card is 2/3.\n\n Cf ~/webppl/card_problem.wppl\n\n=#\n\nusing Turing, StatsPlots, DataFrames\ninclude(\"jl_utils.jl\")\n\n@model function card_problem()\n red = 1\n green = 2\n \n all_red = 1\n all_green = 2\n red_green = 3\n \n # What card did we select?\n selected_card ~ Categorical(simplex([1/3,1/3,1/3])) # [all_red,all_green,red_green]\n \n # What is the color of the card (one side) that we see?\n card ~ \n selected_card == all_red ? Dirac(red) :\n selected_card == all_green ? Dirac(green) :\n # [red,green]\n selected_card == red_green ? Categorical([1/2,1/2]) : Dirac(0)\n\n # Alternative:\n # if selected_card == all_red\n # card ~ Dirac(red)\n # elseif selected_card == all_green\n # card ~ Dirac(green)\n # else\n # card ~ Categorical([1/2,1/2])\n # end\n \n \n # The color of the card we see is green\n true ~ Dirac(card == green)\n\nend\n\nmodel = card_problem()\n\nnum_chains = 4\n\n# chns = sample(model, Prior(), 10_000)\nchns = sample(model, MH(), 100_000)\n# chns = sample(model, PG(15), 10_000)\n# chns = sample(model, SMC(10_000), 10_000)\n# chns = sample(model, IS(), 10_000)\n\n# chns = sample(model, NUTS(), 10_000)\n# chns = sample(model, HMC(0.1,10), 10_000)\n\ndisplay(chns)\n# display(plot(chns))\n\nshow_var_dist_pct(chns, :selected_card,[\"all_red\",\"all_green\",\"red_green\"])\n", "meta": {"hexsha": "ad70b9087998765e52e6b69be41eb701c3c8266f", "size": 2170, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/card_problem.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/turing/card_problem.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/turing/card_problem.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 27.4683544304, "max_line_length": 135, "alphanum_fraction": 0.6470046083, "num_tokens": 656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731764, "lm_q2_score": 0.9005297947939936, "lm_q1q2_score": 0.8388097436848667}} {"text": "# Descriptive Statistics\n\n\n#############################\n#\n# Location\n#\n#############################\n\n# Geometric mean\n\"\"\"\n geomean(a)\n\nReturn the geometric mean of a real-valued array.\n\"\"\"\nfunction geomean(a::RealArray)\n s = 0.0\n n = length(a)\n for i = 1 : n\n @inbounds s += log(a[i])\n end\n return exp(s / n)\nend\n\n# Harmonic mean\n\"\"\"\n harmmean(a)\n\nReturn the harmonic mean of a real-valued array.\n\"\"\"\nfunction harmmean(a::RealArray)\n s = 0.0\n n = length(a)\n for i in 1 : n\n @inbounds s += inv(a[i])\n end\n return n / s\nend\n\n# Generalized mean\n\"\"\"\n genmean(a, p)\n\nReturn the generalized/power mean with exponent `p` of a real-valued array,\ni.e. ``\\left( \\frac{1}{n} \\sum_{i=1}^n a_i^p \\right)^{\\frac{1}{p}}``, where `n = length(a)`.\nIt is taken to be the geometric mean when `p == 0`.\n\"\"\"\nfunction genmean(a::RealArray, p::Real)\n if p == 0\n return geomean(a)\n end\n s = 0.0\n n = length(a)\n for x in a\n #= At least one of `x` or `p` must not be an int to avoid domain errors when `p` is a negative int.\n We choose `x` in order to exploit exponentiation by squaring when `p` is an int. =#\n @inbounds s += convert(Float64, x)^p\n end\n return (s/n)^(1/p)\nend\n\n# Trimmed mean\n\"\"\"\n trimmean(x, p)\n\nCompute the trimmed mean of `x`, i.e. the mean after removing a\nproportion `p` of its highest- and lowest-valued elements.\n\"\"\"\nfunction trimmean(x::RealArray, p::Real)\n n = length(x)\n n > 0 || error(\"x can not be empty.\")\n 0 <= p < 1 || error(\"p must be non-negative and less than 1.\")\n rn = min(round(Int, n * p), n-1)\n\n sx = sort(x)\n nl = rn >> 1\n nh = (rn - nl)\n s = 0.0\n for i = (1+nl) : (n-nh)\n @inbounds s += sx[i]\n end\n return s / (n - rn)\nend\n\n# compute mode, given the range of integer values\n\"\"\"\n mode(a, [r])\n\nReturn the first mode (most common number) of an array, optionally\nover a specified range `r`.\n\"\"\"\nfunction mode{T<:Integer}(a::AbstractArray{T}, r::UnitRange{T})\n isempty(a) && error(\"mode: input array cannot be empty.\")\n len = length(a)\n r0 = r[1]\n r1 = r[end]\n cnts = zeros(Int, length(r))\n mc = 0 # maximum count\n mv = r0 # a value corresponding to maximum count\n for i = 1:len\n @inbounds x = a[i]\n if r0 <= x <= r1\n @inbounds c = (cnts[x - r0 + 1] += 1)\n if c > mc\n mc = c\n mv = x\n end\n end\n end\n return mv\nend\n\n\"\"\"\n modes(a, [r])::Vector\n\nReturn all modes (most common numbers) of an array, optionally over a\nspecified range `r`.\n\"\"\"\nfunction modes{T<:Integer}(a::AbstractArray{T}, r::UnitRange{T})\n r0 = r[1]\n r1 = r[end]\n n = length(r)\n cnts = zeros(Int, n)\n # find the maximum count\n mc = 0\n for i = 1:length(a)\n @inbounds x = a[i]\n if r0 <= x <= r1\n @inbounds c = (cnts[x - r0 + 1] += 1)\n if c > mc\n mc = c\n end\n end\n end\n # find all values corresponding to maximum count\n ms = T[]\n for i = 1:n\n @inbounds if cnts[i] == mc\n push!(ms, r[i])\n end\n end\n return ms\nend\n\n# compute mode over arbitrary array\nfunction mode{T}(a::AbstractArray{T})\n isempty(a) && error(\"mode: input array cannot be empty.\")\n cnts = Dict{T,Int}()\n # first element\n mc = 1\n mv = a[1]\n cnts[mv] = 1\n # find the mode along with table construction\n for i = 2 : length(a)\n @inbounds x = a[i]\n if haskey(cnts, x)\n c = (cnts[x] += 1)\n if c > mc\n mc = c\n mv = x\n end\n else\n cnts[x] = 1\n # in this case: c = 1, and thus c > mc won't happen\n end\n end\n return mv\nend\n\nfunction modes{T}(a::AbstractArray{T})\n isempty(a) && error(\"modes: input array cannot be empty.\")\n cnts = Dict{T,Int}()\n # first element\n mc = 1\n cnts[a[1]] = 1\n # find the mode along with table construction\n for i = 2 : length(a)\n @inbounds x = a[i]\n if haskey(cnts, x)\n c = (cnts[x] += 1)\n if c > mc\n mc = c\n end\n else\n cnts[x] = 1\n # in this case: c = 1, and thus c > mc won't happen\n end\n end\n # find values corresponding to maximum counts\n ms = T[]\n for (x, c) in cnts\n if c == mc\n push!(ms, x)\n end\n end\n return ms\nend\n\n\n#############################\n#\n# quantile and friends\n#\n#############################\n\n\"\"\"\n percentile(v, p)\n\nReturn the `p`th percentile of a real-valued array `v`.\n\"\"\"\npercentile{T<:Real}(v::AbstractArray{T}, p) = quantile(v, p * 0.01)\n\nquantile{T<:Real}(v::AbstractArray{T}) = quantile(v, [.0, .25, .5, .75, 1.0])\n\n\"\"\"\n nquantile(v, n)\n\nReturn the n-quantiles of a real-valued array, i.e. the values which\npartition `v` into `n` subsets of nearly equal size.\n\"\"\"\nnquantile{T<:Real}(v::AbstractArray{T}, n::Integer) = quantile(v, (0:n)/n)\n\n\n#############################\n#\n# Dispersion\n#\n#############################\n\n# span, i.e. the range minimum(x):maximum(x)\n\"\"\"\n span(x)\n\nReturn the span of an integer array, i.e. the range `minimum(x):maximum(x)`.\n\"\"\"\nspan{T<:Integer}(x::AbstractArray{T}) = ((a, b) = extrema(x); a:b)\n\n# Variation coefficient: std / mean\n\"\"\"\n variation(x, m=mean(x))\n\nReturn the coefficient of variation of an array `x`, optionally specifying\na precomputed mean `m`. The coefficient of variation is the ratio of the\nstandard deviation to the mean.\n\"\"\"\nvariation{T<:Real}(x::AbstractArray{T}, m::Real) = stdm(x, m) / m\nvariation{T<:Real}(x::AbstractArray{T}) = variation(x, mean(x))\n\n# Standard error of the mean: std(a) / sqrt(len)\n\"\"\"\n sem(a)\n\nReturn the standard error of the mean of `a`, i.e. `sqrt(var(a) / length(a))`.\n\"\"\"\nsem{T<:Real}(a::AbstractArray{T}) = sqrt(var(a) / length(a))\n\n# Median absolute deviation\n\"\"\"\n mad(v)\n\nCompute the median absolute deviation of `v`.\n\"\"\"\nfunction mad{T<:Real}(v::AbstractArray{T})\n isempty(v) && throw(ArgumentError(\"mad is not defined for empty arrays\"))\n\n S = promote_type(T, typeof(middle(first(v))))\n\n mad!(LinAlg.copy_oftype(v, S))\nend\n\n\n\"\"\"\n StatsBase.mad!(v, center=median!(v); constant=k)\n\nCompute the maximum absolute deviation (MAD) of `v` about a precomputed center\n`center`, overwriting `v` in the process. Using the MAD as a consistent estimator\nof the standard deviation requires a scaling factor that depends on the underlying\ndistribution. For normally distributed data, `k` is chosen as\n`1 / quantile(Normal(), 3/4) ≈ 1.4826`, which is used as the default here.\n\"\"\"\nfunction mad!{T<:Real}(v::AbstractArray{T}, center::Real=median!(v);\n constant::Real = 1 / (-sqrt(2 * one(T)) * erfcinv(3 * one(T) / 2)))\n for i in 1:length(v)\n @inbounds v[i] = abs(v[i]-center)\n end\n constant * median!(v)\nend\n\n# Interquartile range\n\"\"\"\n iqr(v)\n\nCompute the interquartile range (IQR) of an array, i.e. the 75th percentile\nminus the 25th percentile.\n\"\"\"\niqr{T<:Real}(v::AbstractArray{T}) = (q = quantile(v, [.25, .75]); q[2] - q[1])\n\n\n#############################\n#\n# Z-scores\n#\n#############################\n\nfunction _zscore!(Z::AbstractArray, X::AbstractArray, μ::Real, σ::Real)\n # Z and X are assumed to have the same size\n iσ = inv(σ)\n if μ == zero(μ)\n for i = 1 : length(X)\n @inbounds Z[i] = X[i] * iσ\n end\n else\n for i = 1 : length(X)\n @inbounds Z[i] = (X[i] - μ) * iσ\n end\n end\n return Z\nend\n\n@ngenerate N typeof(Z) function _zscore!{S,T,N}(Z::AbstractArray{S,N}, X::AbstractArray{T,N}, μ::AbstractArray, σ::AbstractArray)\n # Z and X are assumed to have the same size\n # μ and σ are assumed to have the same size, that is compatible with size(X)\n siz1 = size(X, 1)\n @nextract N ud d->size(μ, d)\n if size(μ, 1) == 1 && siz1 > 1\n @nloops N i d->(d>1 ? (1:size(X,d)) : (1:1)) d->(j_d = ud_d ==1 ? 1 : i_d) begin\n v = (@nref N μ j)\n c = inv(@nref N σ j)\n for i_1 = 1:siz1\n (@nref N Z i) = ((@nref N X i) - v) * c\n end\n end\n else\n @nloops N i X d->(j_d = ud_d ==1 ? 1 : i_d) begin\n (@nref N Z i) = ((@nref N X i) - (@nref N μ j)) / (@nref N σ j)\n end\n end\n return Z\nend\n\nfunction _zscore_chksize(X::AbstractArray, μ::AbstractArray, σ::AbstractArray)\n size(μ) == size(σ) || throw(DimensionMismatch(\"μ and σ should have the same size.\"))\n for i=1:ndims(X)\n dμ_i = size(μ,i)\n (dμ_i == 1 || dμ_i == size(X,i)) || throw(DimensionMismatch(\"X and μ have incompatible sizes.\"))\n end\nend\n\n\n\"\"\"\n zscore!([Z], X, μ, σ)\n\nCompute the z-scores of an array `X` with mean `μ` and standard deviation `σ`.\nz-scores are the signed number of standard deviations above the mean that an\nobservation lies. If a destination array `Z` is provided, the scores are stored\nin `Z`, otherwise `X` is overwritten.\n\"\"\"\nfunction zscore!{ZT<:AbstractFloat,T<:Real}(Z::AbstractArray{ZT}, X::AbstractArray{T}, μ::Real, σ::Real)\n size(Z) == size(X) || throw(DimensionMismatch(\"Z and X must have the same size.\"))\n _zscore!(Z, X, μ, σ)\nend\n\nfunction zscore!{ZT<:AbstractFloat,T<:Real,U<:Real,S<:Real}(Z::AbstractArray{ZT}, X::AbstractArray{T},\n μ::AbstractArray{U}, σ::AbstractArray{S})\n size(Z) == size(X) || throw(DimensionMismatch(\"Z and X must have the same size.\"))\n _zscore_chksize(X, μ, σ)\n _zscore!(Z, X, μ, σ)\nend\n\nzscore!{T<:AbstractFloat}(X::AbstractArray{T}, μ::Real, σ::Real) = _zscore!(X, X, μ, σ)\n\nzscore!{T<:AbstractFloat,U<:Real,S<:Real}(X::AbstractArray{T}, μ::AbstractArray{U}, σ::AbstractArray{S}) =\n (_zscore_chksize(X, μ, σ); _zscore!(X, X, μ, σ))\n\n\n\"\"\"\n zscore(X, [μ, σ])\n\nCompute the z-scores of `X`, optionally specifying a precomputed mean `μ` and\nstandard deviation `σ`. z-scores are the signed number of standard deviations\nabove the mean that an observation lies. The mean and standard deviation can be\nreal numbers or arrays of real numbers.\n\"\"\"\nfunction zscore{T<:Real}(X::AbstractArray{T}, μ::Real, σ::Real)\n ZT = typeof((zero(T) - zero(μ)) / one(σ))\n _zscore!(Array(ZT, size(X)), X, μ, σ)\nend\n\nfunction zscore{T<:Real,U<:Real,S<:Real}(X::AbstractArray{T}, μ::AbstractArray{U}, σ::AbstractArray{S})\n _zscore_chksize(X, μ, σ)\n ZT = typeof((zero(T) - zero(U)) / one(S))\n _zscore!(Array(ZT, size(X)), X, μ, σ)\nend\n\nzscore{T<:Real}(X::AbstractArray{T}) = ((μ, σ) = mean_and_std(X); zscore(X, μ, σ))\nzscore{T<:Real}(X::AbstractArray{T}, dim::Int) = ((μ, σ) = mean_and_std(X, dim); zscore(X, μ, σ))\n\n\n\n#############################\n#\n# entropy and friends\n#\n#############################\n\n\"\"\"\n entropy(p, [b])\n\nCompute the entropy of an array `p`, optionally specifying a real number\n`b` such that the entropy is scaled by `1/log(b)`.\n\"\"\"\nfunction entropy{T<:Real}(p::AbstractArray{T})\n s = zero(T)\n z = zero(T)\n for i = 1:length(p)\n @inbounds pi = p[i]\n if pi > z\n s += pi * log(pi)\n end\n end\n return -s\nend\n\nfunction entropy{T<:Real}(p::AbstractArray{T}, b::Real)\n return entropy(p) / log(b)\nend\n\n\"\"\"\n renyientropy(p, α)\n\nCompute the Rényi (generalized) entropy of order `α` of an array `p`.\n\"\"\"\nfunction renyientropy{T<:Real, U<:Real}(p::AbstractArray{T}, α::U)\n α < 0 && throw(ArgumentError(\"Order of Rényi entropy not legal, $(α) < 0.\"))\n\n s = zero(T)\n z = zero(T)\n scale = sum(p)\n\n if α ≈ 0\n for i = 1:length(p)\n @inbounds pi = p[i]\n if pi > z\n s += 1\n end\n end\n s = log(s / scale)\n elseif α ≈ 1\n for i = 1:length(p)\n @inbounds pi = p[i]\n if pi > z\n s -= pi * log(pi)\n end\n end\n s = s / scale\n elseif (isinf(α))\n s = -log(maximum(p))\n else # a normal Rényi entropy\n for i = 1:length(p)\n @inbounds pi = p[i]\n if pi > z\n s += pi ^ α\n end\n end\n s = log(s / scale) / (1 - α)\n end\n return s\nend\n\n\"\"\"\n crossentropy(p, q, [b])\n\nCompute the cross entropy between `p` and `q`, optionally specifying a real\nnumber `b` such that the result is scaled by `1/log(b)`.\n\"\"\"\nfunction crossentropy{T<:Real}(p::AbstractArray{T}, q::AbstractArray{T})\n length(p) == length(q) || throw(DimensionMismatch(\"Inconsistent array length.\"))\n s = 0.\n z = zero(T)\n for i = 1:length(p)\n @inbounds pi = p[i]\n @inbounds qi = q[i]\n if pi > z\n s += pi * log(qi)\n end\n end\n return -s\nend\n\nfunction crossentropy{T<:Real}(p::AbstractArray{T}, q::AbstractArray{T}, b::Real)\n return crossentropy(p,q) / log(b)\nend\n\n\n\"\"\"\n kldivergence(p, q, [b])\n\nCompute the Kullback-Leibler divergence of `q` from `p`, optionally specifying\na real number `b` such that the divergence is scaled by `1/log(b)`.\n\"\"\"\nfunction kldivergence{T<:Real}(p::AbstractArray{T}, q::AbstractArray{T})\n length(p) == length(q) || throw(DimensionMismatch(\"Inconsistent array length.\"))\n s = 0.\n z = zero(T)\n for i = 1:length(p)\n @inbounds pi = p[i]\n @inbounds qi = q[i]\n if pi > z\n s += pi * log(pi / qi)\n end\n end\n return s\nend\n\nfunction kldivergence{T<:Real}(p::AbstractArray{T}, q::AbstractArray{T}, b::Real)\n return kldivergence(p,q) / log(b)\nend\n\n#############################\n#\n# summary\n#\n#############################\n\nimmutable SummaryStats{T<:AbstractFloat}\n mean::T\n min::T\n q25::T\n median::T\n q75::T\n max::T\nend\n\n\n\"\"\"\n summarystats(a)\n\nCompute summary statistics for a real-valued array `a`. Returns a\n`SummaryStats` object containing the mean, minimum, 25th percentile,\nmedian, 75th percentile, and maxmimum.\n\"\"\"\nfunction summarystats{T<:Real}(a::AbstractArray{T})\n m = mean(a)\n qs = quantile(a, [0.00, 0.25, 0.50, 0.75, 1.00])\n R = typeof(convert(AbstractFloat, zero(T)))\n SummaryStats{R}(\n convert(R, m),\n convert(R, qs[1]),\n convert(R, qs[2]),\n convert(R, qs[3]),\n convert(R, qs[4]),\n convert(R, qs[5]))\nend\n\nfunction Base.show(io::IO, ss::SummaryStats)\n println(io, \"Summary Stats:\")\n @printf(io, \"Mean: %.6f\\n\", ss.mean)\n @printf(io, \"Minimum: %.6f\\n\", ss.min)\n @printf(io, \"1st Quartile: %.6f\\n\", ss.q25)\n @printf(io, \"Median: %.6f\\n\", ss.median)\n @printf(io, \"3rd Quartile: %.6f\\n\", ss.q75)\n @printf(io, \"Maximum: %.6f\\n\", ss.max)\nend\n\n\n\"\"\"\n describe(a)\n\nPretty-print the summary statistics provided by `summarystats`:\nthe mean, minimum, 25th percentile, median, 75th percentile, and\nmaximum.\n\"\"\"\ndescribe{T<:Real}(a::AbstractArray{T}) = show(summarystats(a))\n", "meta": {"hexsha": "d6dda9f4cb3a0983618139bafa9102140f8dc999", "size": 14905, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/scalarstats.jl", "max_stars_repo_name": "JuliaPackageMirrors/StatsBase.jl", "max_stars_repo_head_hexsha": "99ee7c3d3638dfa18a104c89b9de00baa663abc2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/scalarstats.jl", "max_issues_repo_name": "JuliaPackageMirrors/StatsBase.jl", "max_issues_repo_head_hexsha": "99ee7c3d3638dfa18a104c89b9de00baa663abc2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/scalarstats.jl", "max_forks_repo_name": "JuliaPackageMirrors/StatsBase.jl", "max_forks_repo_head_hexsha": "99ee7c3d3638dfa18a104c89b9de00baa663abc2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9668989547, "max_line_length": 129, "alphanum_fraction": 0.5565917477, "num_tokens": 4619, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625050654264, "lm_q2_score": 0.9005297881200701, "lm_q1q2_score": 0.8388097323283582}} {"text": "using Distributions, Plots, LaTeXStrings; pyplot()\n\nfunction statPair(dist,n)\n sample = rand(dist,n)\n [mean(sample),var(sample)]\nend\n\nstdUni = Uniform(-sqrt(3),sqrt(3))\nn, N = 3, 10^5\n\ndataUni = [statPair(stdUni,n) for _ in 1:N]\ndataUniInd = [[mean(rand(stdUni,n)),var(rand(stdUni,n))] for _ in 1:N]\ndataNorm = [statPair(Normal(),n) for _ in 1:N]\ndataNormInd = [[mean(rand(Normal(),n)),var(rand(Normal(),n))] for _ in 1:N]\n\np1 = scatter(first.(dataUni), last.(dataUni), \n\tc=:blue, ms=1, msw=0, label=\"Same group\")\np1 = scatter!(first.(dataUniInd), last.(dataUniInd), \n\tc=:red, ms=0.8, msw=0, label=\"Separate group\", \n\txlabel=L\"\\overline{X}\", ylabel=L\"S^2\")\n\np2 = scatter(first.(dataNorm), last.(dataNorm), \n\tc=:blue, ms=1, msw=0, label=\"Same group\")\np2 = scatter!(first.(dataNormInd), last.(dataNormInd),\n\tc=:red, ms=0.8, msw=0, label=\"Separate group\", \n\txlabel=L\"\\overline{X}\", ylabel=L\"$S^2$\")\n\nplot(p1, p2, ylims=(0,5), size=(800, 400))", "meta": {"hexsha": "ab5c6275e43997fd8c6e9942b4e3186a89b3f1c3", "size": 953, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "5_chapter/meanVarIndependence.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/meanVarIndependence.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/meanVarIndependence.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 34.0357142857, "max_line_length": 75, "alphanum_fraction": 0.6453305352, "num_tokens": 346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811651448431, "lm_q2_score": 0.868826784729373, "lm_q1q2_score": 0.8387490137510899}} {"text": "# prime fields =========================================================================== #\n\"\"\"\n is_prime(n)\n\nReturn `true` if `n` is a prime number.\n\"\"\"\nBase.@pure function is_prime(n::Int)\n if iseven(n) || n < 2\n return n == 2\n else\n p = 3\n q = n ÷ p\n while p ≤ q\n iszero(n % p) && return false\n p += 2\n q = n ÷ p\n end\n return true\n end\nend\n# The following causes an error if you try to use anything other than Int as a modulus.\nis_prime(::Any) = false\n\n\"\"\"\n mod_prime(i, ::Val{M})\n\nLike `mod`, but with prime `M`.\n\"\"\"\nfunction mod_prime(i, ::Val{M}) where {M}\n is_prime(M) || throw(DomainError(M, \"modulus must be a prime number\"))\n i = i % M\n return i + ifelse(signbit(i), M, 0)\nend\nmod_prime(i, ::Val{2}) = i & 1\n\n\"\"\"\n Mod{M} <: Integer\n\n`Mod{M}` is the default field used by Ripserer. It is a representation of a finite field\n``\\\\mathbb{Z}_M``, integers modulo small, prime `M`. Supports field arithmetic and can be\nconverted to integer with `Int`.\n\nIts values are not comparable on purpose.\n\n# Example\n\n```jldoctest\njulia> Mod{3}(5)\n2 mod 3\n\njulia> Mod{3}(5) + 1\n0 mod 3\n\n```\n\"\"\"\nstruct Mod{M} <: Integer\n value::Int\n\n # Check mod allows construction when you know you don't need to mod the number.\n function Mod{M}(value::Integer, check_mod=true) where {M}\n if check_mod\n return new{M}(mod_prime(value, Val(M)))\n else\n return new{M}(value)\n end\n end\nend\nMod{M}(i::Mod{M}) where {M} = i\n\nBase.Int(i::Mod) = i.value\n\nBase.show(io::IO, i::Mod{M}) where {M} = print(io, Int(i), \" mod \", M)\n\nfor op in (:+, :-, :*)\n @eval (Base.$op)(i::Mod{M}, j::Mod{M}) where {M} = Mod{M}($op(Int(i), Int(j)))\nend\n\nBase.:/(i::Mod{M}, j::Mod{M}) where {M} = i * inv(j)\nBase.:-(i::Mod{M}) where {M} = Mod{M}(M - Int(i), false)\nBase.zero(::Type{Mod{M}}) where {M} = Mod{M}(0, false)\nBase.one(::Type{Mod{M}}) where {M} = Mod{M}(1, false)\nBase.sign(i::M) where {M<:Mod} = ifelse(iszero(i), zero(M), one(M))\n\nBase.promote_rule(::Type{Mod{M}}, ::Type{<:Integer}) where {M} = Mod{M}\n\nBase.inv(i::Mod{M}) where {M} = Mod{M}(invmod(Int(i), M), false)\n", "meta": {"hexsha": "95eefafa1a9caee88016a6dce3c00ad93c5f58d3", "size": 2190, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/base/primefield.jl", "max_stars_repo_name": "davidhien/Ripserer.jl", "max_stars_repo_head_hexsha": "95391396bea1b2b922967f7da21de05d6b3b67bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30, "max_stars_repo_stars_event_min_datetime": "2020-06-03T11:58:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T21:37:46.000Z", "max_issues_repo_path": "src/base/primefield.jl", "max_issues_repo_name": "davidhien/Ripserer.jl", "max_issues_repo_head_hexsha": "95391396bea1b2b922967f7da21de05d6b3b67bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 149, "max_issues_repo_issues_event_min_datetime": "2020-04-09T07:53:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-05T10:20:46.000Z", "max_forks_repo_path": "src/base/primefield.jl", "max_forks_repo_name": "davidhien/Ripserer.jl", "max_forks_repo_head_hexsha": "95391396bea1b2b922967f7da21de05d6b3b67bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-08-06T22:56:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T14:55:51.000Z", "avg_line_length": 25.1724137931, "max_line_length": 92, "alphanum_fraction": 0.5497716895, "num_tokens": 719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811611608242, "lm_q2_score": 0.8688267728417087, "lm_q1q2_score": 0.8387489988135404}} {"text": "using CSV, Distributions, HypothesisTests\n\ndata1 = CSV.read(\"../data/machine1.csv\", header=false)[:,1]\ndata2 = CSV.read(\"../data/machine2.csv\", header=false)[:,1]\nxBar1, s1, n1 = mean(data1), std(data1), length(data1)\nxBar2, s2, n2 = mean(data2), std(data2), length(data2)\ndelta0 = 0\n\nv = ( s1^2/n1 + s2^2/n2 )^2 / ( (s1^2/n1)^2/(n1-1) + (s2^2/n2)^2/(n2-1) )\ntestStatistic = ( xBar1-xBar2 - delta0 ) / sqrt( s1^2/n1 + s2^2/n2 )\npVal = 2*ccdf(TDist(v), abs(testStatistic))\n\nprintln(\"Manually calculated degrees of freedom, v: \", v)\nprintln(\"Manually calculated test statistic: \", testStatistic)\nprintln(\"Manually calculated p-value: \", pVal, \"\\n\")\nprintln(UnequalVarianceTTest(data1, data2, delta0))\n", "meta": {"hexsha": "b6bfc1e35c4c6f92427a550779552af15d8dbfb1", "size": 701, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "7_chapter/infMeanDiffVarAssumedUnequal.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/infMeanDiffVarAssumedUnequal.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/infMeanDiffVarAssumedUnequal.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": 41.2352941176, "max_line_length": 74, "alphanum_fraction": 0.6733238231, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693241956308277, "lm_q2_score": 0.8652240756264639, "lm_q1q2_score": 0.8386826311470486}} {"text": "import Pkg; Pkg.add(Pkg.PackageSpec(url=\"https://github.com/JuliaComputing/JuliaAcademyData.jl\"))\nusing JuliaAcademyData; activate(\"Foundations of machine learning\")\n\n# # Modeling data 2\n\n#-\n\n# ## Building a model\n#\n# Recall that in notebook 3, we saw that we could use a mathematical function to classify an image as an apple or a banana, based on the average amount of green in an image:\n#\n# \"Drawing\"\n#\n#\n# \"Drawing\"\n\n#-\n\n# A common function for performing this kind of **classification** is the sigmoid that we saw in the last notebook, and that we will now extend by adding two **parameters**, $w$ and $b$:\n#\n# $$\\sigma(x; w, b) := \\frac{1}{1 + \\exp(-wx + b)}$$\n#\n# $$ x = \\mathrm{data} $$\n#\n# \\begin{align}\n# \\sigma(x;w,b) &\\approx 0 \\implies \\mathrm{apple} \\\\\n# \\sigma(x;w,b) &\\approx 1 \\implies \\mathrm{banana}\n# \\end{align}\n\n#-\n\n# In our mathematical notation above, the `;` in the function differentiates between the **data** and the **parameters**. `x` is the data and is determined from the image. The parameters, `w` and `b`, are numbers which we choose to make our function match the results it should be modeling.\n#\n# Note that in the code below, we don't distinguish between data and parameters - both are just inputs to our function, σ!\n\nusing Images, Statistics\n\napple = load(datapath(\"data/10_100.jpg\"))\nbanana = load(datapath(\"data/104_100.jpg\"))\n\napple_green_amount = mean(Float64.(green.(apple)))\nbanana_green_amount = mean(Float64.(green.(banana)))\n\nprintln(\"Average green for apple = $apple_green_amount\")\nprintln(\"Average green for banana = $banana_green_amount\")\n\n#-\n\nσ(x, w, b) = 1 / (1 + exp(-w * x + b))\n\n# What we want is that when we give σ as input the average green for the apple, roughly `x = 0.3385`, it should return as output something close to 0, meaning \"apple\". And when we give σ the input `x = 0.8808`, it should output something close to 1, meaning \"banana\".\n#\n# By changing the parameters of the function, we can change the shape of the function, and hence make it represent, or **fit**, the data better!\n\n#-\n\n# ## Data fitting by varying parameters\n\n#-\n\n# We can understand how our choice of `w` and `b` affects our model by seeing how our values for `w` and `b` change the plot of the $\\sigma$ function.\n\nusing Plots; gr() # GR works better for interactive manipulations\n\n# Run the code in the next cell. You should see two \"sliders\" appear, one for `w` and one for `b`.\n#\n# **Game**:\n# Change w and b around until the blue curve, labeled \"model\", which is the graph of the `\\sigma` function, passes through *both* of the data points at the same time.\n\nw = 10.0 # try manipulating w between -10 and 30\nb = 10.0 # try manipulating b between 0 and 20\n\nplot(x -> σ(x, w, b), xlim=(-0,1), ylim=(-0.1,1.1), label=\"model\", legend=:topleft, lw=3)\n\nscatter!([apple_green_amount], [0.0], label=\"apple\", ms=5) # marker size = 5\nscatter!([banana_green_amount], [1.0], label=\"banana\", ms=5)\n\n# Notice that the two parameters do two very different things. The **weight**, `w`, determines *how fast* the transition between 0 and 1 occurs. It encodes how trustworthy we think our data actually is, and in what range we should be putting points between 0 and 1 and thus calling them \"unsure\". The **bias**, `b`, encodes *where* on the $x$-axis the switch should take place. It can be seen as shifting the function left-right. We'll come to understand these *parameters* more in notebook 6.\n#\n# Here are some parameter choices that work well:\n\nw = 25.58; b = 15.6\n\nplot(x -> σ(x, w, b), xlim=(0,1), ylim=(-0.1,1.1), label=\"model\", legend=:topleft, lw=3)\n\nscatter!([apple_green_amount], [0.0], label=\"apple\")\nscatter!([banana_green_amount],[1.0], label=\"banana\")\n\n# (Note that in this problem there are many combinations of `w` and `b` that fit the data well.)\n\n#-\n\n# Once we have a model, we have a computational representation for how to choose between \"apple\" and \"banana\". So let's pull in some new images and see what our model says about them!\n\napple2 = load(datapath(\"data/107_100.jpg\"))\n\n#-\n\ngreen_amount = mean(Float64.(green.(apple2)))\n@show green_amount\n\nscatter!([green_amount], [0.0], label=\"new apple\")\n\n# Our model successfully says that our new image is an apple! Pat yourself on the back: you've actually just trained your first neural network!\n\n#-\n\n# #### Exercise 1\n#\n# Load the image of a banana in `data/8_100.jpg` as `mybanana`. Edit the code below to calculate the amount of green in `mybanana` and to overlay data for this image with the existing model and data points.\n\n#-\n\n# #### Solution\n\n#-\n\n# To get the desired overlay, the code we need is\n\nmybanana = load(datapath(\"data/8_100.jpg\"))\nmybanana_green_amount = mean(Float64.(green.(banana)))\nscatter!([mybanana_green_amount], [1.0], label=\"my banana\")\n\n# ## Closing remarks: bigger models, more data, more accuracy\n#\n# That last apple should start making you think: not all apples are red; some are yellow. \"Redness\" is one attribute of being an apple, but isn't the whole thing. What we need to do is incorporate more ideas into our model by allowing more inputs. However, more inputs would mean more parameters to play with. Also, we would like to have the computer start \"learning\" on its own, instead of modifying the parameters ourselves until we think it \"looks right\". How do we take the next step?\n#\n# The first thing to think about is, if you wanted to incorporate more data into the model, how would you change the sigmoid function? Play around with some ideas. But also, start thinking about how you chose parameters. What process did you do to finally end up at good parameters? These two problems (working with models with more data and automatically choosing parameters) are the last remaining step to understanding deep learning.\n\n", "meta": {"hexsha": "f10ba6504aa4d3823a14d24ed23647b0352392ca", "size": 6122, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Courses/Foundations of machine learning/0500.Building-models.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.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.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": 47.0923076923, "max_line_length": 494, "alphanum_fraction": 0.7252531852, "num_tokens": 1632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660962919971, "lm_q2_score": 0.8791467564270272, "lm_q1q2_score": 0.8386761992964624}} {"text": "# Linear Regression\n\nusing CSV\nusing Statistics\nusing Missings\nusing Plots\nusing StatsBase\nusing HypothesisTests\n\n# Read data\ndataset = CSV.read(\"C:/Users/Andrew.Bannerman/Desktop/Machine Learning/Machine-Learning/Machine-Learning/linear_regression/Salary_Data.csv\", header=true, types=[Float64, Float64])\ndataset[:index] = collect(1:1:size(dataset,1)) # index the data\ndataset = dataset[sample(axes(dataset, 1), size(dataset,1); replace = false, ordered = false), :] # Random shuffle the dataframe\n\n# Feature Scaling\ndataset[:Salary] = standardization(Float64.(dataset[:Salary]))\ndataset[:YearsExperience] = standardization(Float64.(dataset[:YearsExperience]))\n\n# Split data to train and test sets\nsplit_ratio = 2/3\nlen = size(dataset,1)\nsplit_no = Int64.(round(split_ratio * len))\ntrain_set = dataset[1:split_no,:]\ntest_set = dataset[split_no+1:len,:]\n\n# Visualize the data\ngr() # We will continue onward using the GR backend\nplot(train_set[:YearsExperience],train_set[:Salary],seriestype=:scatter,title=\"My Scatter Plot (Training Data)\")\n\n# Find the regression formula\nx = Float64.(train_set[:YearsExperience])\ny = Float64.(train_set[:Salary])\n\n# Regression coefficients (y = b0 .+ (b1 .* x))\nb1 = cov(x,y) / var(x) # b (slope)\nb0 = mean(y) - b1 * mean(x) # a (intercept)\n\n# Apply the regression formula to the training data\ny_hat_train = fill(0.0,size(train_set,1)) # initialize array\ny_hat_train = b0 .+ (b1 .* x)\nplot!(train_set[:YearsExperience],y_hat_train, smooth=true)\nplot_annotation = \"y = \",round(b0,digits=2),\" + (\",round(b1,digits=2),\" * x)\"\nannotate!(-.5, 1.0, text(plot_annotation, :red, :left, 10))\ntraining_set_residuals = y .- y_hat_train\nr_2 = cor(x,y) ^2\nn = size(train_set,1)\nstandard_error = sqrt((sum(y_hat_train .- y)^2) / (n-2))\n\n# Using the same regression coefficients found on training data - plot the regression line on unseen test data\nx = Float64.(test_set[:YearsExperience])\ny = Float64.(test_set[:Salary])\ny_hat_test = fill(0.0,size(test_set,1))\ny_hat_test = b0 .+ (b1 .* x)\nplot(test_set[:YearsExperience],test_set[:Salary],seriestype=:scatter,title=\"My Scatter Plot (Test Data)\")\nplot!(test_set[:YearsExperience],y_hat_test, smooth=true)\nplot_annotation = \"y = \",round(b0,digits=2),\" + (\",round(b1,digits=2),\" * x)\"\nannotate!(-.5, 1.0, text(plot_annotation, :red, :left, 10))\ntest_set_residuals = y .- y_hat_test\nr_2 = cor(x,y) ^2\nn = size(test_set,1)\nstandard_error = sqrt((sum(y_hat_test .- y)^2) / (n-2))\n\n\"\"\"\n```\nlin_reg_ols(x_train::Array{T},y_train::Array{T},x_test::Array{T},y_test::Array{T})\n```\nTrain the regression model on training data - derive coefficients b0 and b1\nApply training coefficients on test set data:: y_hat_test = b0 .+ (b1 .* x_test)\n\"\"\"\nfunction lin_reg_ols(x_train::Array{T},y_train::Array{T},x_test::Array{T},y_test::Array{T})::Array{T} where {T<:Real}\n let y_hat_train = size(x_train,1), y_hat_test = size(x_test,1)\n b1 = cov(x_train,y_train) / var(x_train) # b (slope)\n b0 = mean(y_train) - b1 * mean(x_train) # a (intercept)\n coefficients = b1,b0\n y_hat_train = b0 .+ (b1 .* x_train)\n # Test set\n y_hat_test = b0 .+ (b1 .* x_test)\n return y_hat_test\nend\nend\n\n# Test function\nx_train = Float64.(train_set[:YearsExperience])\ny_train= Float64.(train_set[:Salary])\nx_test = Float64.(test_set[:YearsExperience])\ny_test= Float64.(test_set[:Salary])\n\ntest_predictions = lin_reg_ols(x_train,y_train,x_test,y_test)\ntest_set_residuals = y_test .- test_predictions\nr_2 = cor(x_test,y_test) ^2\n\n# How to calculate the p-value\n# https://www.wikihow.com/Calculate-P-Value\n", "meta": {"hexsha": "4bbb885dee2c65234d5bf2820778037bb85f18d8", "size": 3552, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "linear_regression/linear_regression.jl", "max_stars_repo_name": "JuliaTagBot/Machine-Learning", "max_stars_repo_head_hexsha": "a4fc7e1b4222a77d2182953a1edaf44f2c8ab35d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linear_regression/linear_regression.jl", "max_issues_repo_name": "JuliaTagBot/Machine-Learning", "max_issues_repo_head_hexsha": "a4fc7e1b4222a77d2182953a1edaf44f2c8ab35d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear_regression/linear_regression.jl", "max_forks_repo_name": "JuliaTagBot/Machine-Learning", "max_forks_repo_head_hexsha": "a4fc7e1b4222a77d2182953a1edaf44f2c8ab35d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T10:43:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T10:43:29.000Z", "avg_line_length": 37.7872340426, "max_line_length": 179, "alphanum_fraction": 0.7179054054, "num_tokens": 1067, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109812297141, "lm_q2_score": 0.8824278664544911, "lm_q1q2_score": 0.8386691344214561}} {"text": "using LinearAlgebra\r\n\r\n#Givens from Problem Statement\r\n#Elastic Modulus(psi),Area(in^2),length(in),Force(lb)\r\nE = 1.9*10^6\r\nA = 8\r\nl = 3*12\r\nl2 = 3*sqrt(2)*12\r\nF = 500\r\n\r\n# Torsional Stiffness Function\r\nk(A,E,l) = (A*E)/l\r\n\r\n# k_local(Elastic Modulus,Area,length,theta,number of nodes,\r\n# row/column one,row/column two, ==1 left fixed/ ==2 right fixed)\r\nfunction k_local(E,A,l,theta,i,n1,n2,fixed=0)\r\n #k_local = zeros(4,4)\r\n p1 = (n1*2)-1\r\n p2 = n1*2\r\n p3 = (n2*2)-1\r\n p4 = n2*2\r\n \r\n k_global = zeros(2*i,2*i)\r\n kin = k(A,E,l)\r\n s = (sind(theta))^2\r\n\tc = (cosd(theta))^2\r\n\tsc = sind(theta)*cosd(theta)\r\n\tk_quad = [c sc;\r\n sc s]\r\n k_global[p1:p2,p1:p2] = k*k_quad\r\n k_global[p1:p2,p3:p4] = -k*k_quad\r\n k_global[p3:p4,p1:p2] = -k*k_quad\r\n k_global[p3:p4,p3:p4] = k*k_quad\r\n # Need to remove rows and columns; check: push!, pop! \r\n if fixed == 1\r\n adj = zeros(1,i)\r\n #adj[n1] = 1\r\n k_global[p1,:] = adj \r\n k_global[:,p1] = adj \r\n k_global[p2,:] = adj \r\n k_global[:,p2] = adj \r\n elseif fixed == 2\r\n adj = zeros(1,i)\r\n #adj[n2] = 1 \r\n k_global[p3,:] = adj \r\n k_global[:,p3] = adj \r\n k_global[p4,:] = adj \r\n k_global[:,p4] = adj \r\n end\r\n return k_global\r\nend\r\n\r\n# Unadjusted Global \r\nk_1 = k_local(E,A,l,0,5,1,2,1)\r\nk_2 = k_local(E,A,l,135,5,2,3)\r\nk_3 = k_local(E,A,l,0,5,3,4,1)\r\nk_4 = k_local(E,A,l,90,5,2,4)\r\nk_5 = k_local(E,A,l,45,5,2,5)\r\nk_6 = k_local(E,A,l,0,5,4,5)\r\nkG = k_1+k_2+k_3+k_4+k_5+k_6\r\n\r\n#Adjusted Global \r\nkG_adj = kG\r\n\r\n# Load Vector\r\np = Float64[0 0 0 -F 0 -F]\r\nP = transpose(p)\r\n\r\n# Angular Displacement Vector\r\nu = kG_adj\\P\r\nprintln(\"Displacement Vector (in)\")\r\ndisplay(u)\r\n\r\n# Moment Reaction Vector\r\nP_abs = kG*u_adj\r\nprintln(\"Load Reaction Vector (lb):\")\r\ndisplay(P_abs)\r\n", "meta": {"hexsha": "0819a410a14f4a771ce789855a448b041edfb9a3", "size": 1785, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "trejo_nicholas_IC4.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_IC4.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_IC4.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": 22.8846153846, "max_line_length": 66, "alphanum_fraction": 0.5770308123, "num_tokens": 709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9732407168145568, "lm_q2_score": 0.8615381987656672, "lm_q1q2_score": 0.8384840541298201}} {"text": "function count_histogram(nbr_outcomes, sequence)\n count = zeros(nbr_outcomes)\n for x in sequence\n count[x] += 1\n end\n count\nend\n\nusing PyPlot\n\nfunction simulate_die(ntrials)\n outcomes = collect(1:6) # Simulate a fair die\n x = rand(outcomes, ntrials);\n bar(outcomes, count_histogram(6, x) / ntrials)\n xlabel(\"Die outcome\")\n ylabel(\"Probability\")\nend\n\nsimulate_die(1000);\n\nfunction simulate_sum_of_n_dice(ntrials, ndice)\n outcomes = collect(1:6) # Simulate fair dice\n x = zeros(Int64, ntrials)\n for i = 1:ndice\n x .+= rand(outcomes, ntrials)\n end\n outcomesn = collect(1:6ndice)\n bar(outcomesn, count_histogram(6ndice, x) / ntrials)\n xlabel(\"Sum of n dice outcome\")\n ylabel(\"Probability\")\nend\n\nsimulate_sum_of_n_dice(1000, 2); # Two dice\n\nsimulate_sum_of_n_dice(10000, 50);\n\nx = randn(10000)\nnbins = 50\n\nplt.hist(x, nbins)\nxlabel(\"Random variable x\")\nylabel(\"Count\");\n", "meta": {"hexsha": "3b0bb6a7e60f22adc15075e69c4c82559c8de709", "size": 941, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "textbook/_build/jupyter_execute/content/Random_Numbers/Histograms.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/Random_Numbers/Histograms.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/Random_Numbers/Histograms.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.8837209302, "max_line_length": 56, "alphanum_fraction": 0.6737513284, "num_tokens": 289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475746920261, "lm_q2_score": 0.8887588008585925, "lm_q1q2_score": 0.8384084592761466}} {"text": "using LinearAlgebra\nusing Plots\n\n\nfunction newtons_method(∇f, H, x, ϵ, k_max)\n k, Δ = 1, Inf\n while abs(Δ) > ϵ && k ≤ k_max\n Δ = ∇f(x)/abs(H(x))\n x -= Δ\n k += 1\n end\n return x\nend\n\nf = x->sin(10x)+cos(3x)\ndf(x) = 10*cos(10*x)-3*sin(3*x)\nddf(x) = -100*sin(10x)-9*cos(3x)\n\n#converge para o ponto de minimo\ninitial_point = 5.1 #ponto inicial\nconvergence = 1e-8 #convergencia\nmaximum_iterations = 10 #numero maximo de iteracoes\nxs = newtons_method(df,ddf,initial_point,convergence,maximum_iterations)\nxs,f(xs),ddf(xs),df(xs)\n\n\n#converge para o ponto de maximo\n#initial_point = 4.45 #ponto inicial\n#convergence = 1e-8 #convergencia\n#maximum_iterations = 10 #numero maximo de iteracoes\n#xs = newtons_method(df,ddf,initial_point,convergence,maximum_iterations)\n#xs,f(xs),ddf(xs),df(xs)\n\nplot(f,0.,8.,lw=2,draw_arrow=\"true\")\n#scatter!([a,c],[f(a),f(c)])\nscatter!([initial_point],[f(initial_point)])\nscatter!([xs],[f(xs)])", "meta": {"hexsha": "15398b0e1ab737fb1f9d203bac0f19b5b449ae4e", "size": 970, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Newtons_Method.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": "Newtons_Method.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": "Newtons_Method.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": 26.2162162162, "max_line_length": 73, "alphanum_fraction": 0.6567010309, "num_tokens": 348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542864252022, "lm_q2_score": 0.8740772384450967, "lm_q1q2_score": 0.838374929921318}} {"text": "using RDatasets, DataFrames, GLM, Plots, Measures; pyplot()\n\ndf = dataset(\"datasets\", \"anscombe\")\n\nmodel1 = lm(@formula(Y1 ~ X1), df)\nmodel2 = lm(@formula(Y2 ~ X2), df)\nmodel3 = lm(@formula(Y3 ~ X3), df)\nmodel4 = lm(@formula(Y4 ~ X4), df)\n\nprintln(\"Model 1. Coefficients: \", coef(model1),\"\\t R squared: \",r2(model1))\nprintln(\"Model 2. Coefficients: \", coef(model2),\"\\t R squared: \",r2(model2))\nprintln(\"Model 3. Coefficients: \", coef(model3),\"\\t R squared: \",r2(model3))\nprintln(\"Model 4. Coefficients: \", coef(model4),\"\\t R squared: \",r2(model4))\n\nyHat(model, X) = coef(model)' * [ 1 , X ]\nxlims = [0, 20]\n\np1 = scatter(df.X1, df.Y1, c=:blue, msw=0, ms=8)\np1 = plot!(xlims, [yHat(model1, x) for x in xlims], c=:red, xlims=(xlims))\n\np2 = scatter(df.X2, df.Y2, c=:blue, msw=0, ms=8)\np2 = plot!(xlims, [yHat(model2, x) for x in xlims], c=:red, xlims=(xlims))\n\np3 = scatter(df.X3, df.Y3, c=:blue, msw=0, ms=8)\np3 = plot!(xlims, [yHat(model3, x) for x in xlims], c=:red, xlims=(xlims))\n\np4 = scatter(df.X4, df.Y4, c=:blue, msw=0, ms=8)\np4 = plot!(xlims, [yHat(model4, x) for x in xlims], c=:red, msw=0, xlims=(xlims))\n\nplot(p1, p2, p3, p4, layout = (2,2), xlims=(0,20), ylims=(0,14), \n\tlegend=:none, xlabel = \"x\", ylabel = \"y\",\n \tsize=(1200, 800), margin = 10mm)", "meta": {"hexsha": "ebf1d8d36bade35a2683bbc26c373cf7a56af31f", "size": 1261, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "8_chapter/anscombeQuartet.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "8_chapter/anscombeQuartet.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "8_chapter/anscombeQuartet.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": 39.40625, "max_line_length": 81, "alphanum_fraction": 0.6193497224, "num_tokens": 511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966686936262, "lm_q2_score": 0.8856314753275017, "lm_q1q2_score": 0.8383358042352346}} {"text": "using Plots\n\n#Useful functions\n\nfunction hat(i, N, x)\n @assert 0 <= i < N\n h = 1 / (N-1) #Domain then goes from 0 to 1\n xim1 = h * (i-1)\n xi = h * i\n xip1 = h * (i+1)\n if x <= xim1\n return 0.\n elseif x <= xi\n return (x - xim1) / h\n elseif x <= xip1\n return -(x - xip1) / h\n else\n return 0.\n end\nend\n\nfunction sample(f, N)\n h = 1 / (N-1)\n return coeffs = Float64[f(h*i) for i in 0:N-1]\nend\n\nfunction evaluate(coeffs, x)\n N = length(coeffs)\n sum(coeffs[i+1] * hat(i, N, x) for i in 0:N-1)\nend\n\nfunction deriv(f)\n N = length(f)\n h = 1 / (N-1)\n deriv_coeffs = similar(f)\n for i in 1:N\n if i == 1\n deriv_coeffs[i] = (f[2] - f[1]) / h\n elseif i == N\n deriv_coeffs[i] = (f[N] - f[N-1]) / h\n else\n deriv_coeffs[i] = (f[i+1] - f[i-1]) / (2*h)\n end\n end\n return deriv_coeffs\nend\n\nfunction deriv2(f)\n N = length(f)\n h = 1 / (N-1)\n deriv2_coeffs = similar(f)\n for i in 1:N\n if i == 1\n deriv2_coeffs[i] = (f[3] - 2*f[2] + f[1]) / h^2\n elseif i == N\n deriv2_coeffs[i] = (f[N] - 2*f[N-1] + f[N-2]) / h^2\n else\n deriv2_coeffs[i] = (f[i+1] - 2*f[i] + f[i-1]) / h^2\n end\n end\n return deriv2_coeffs\nend\n\nfunction rk2step(f, y0, h)\n k0 = f(y0)\n y1 = y0 + (h/2)*k0\n k1 = f(y1)\n y2 = y0 + h*k1\n y2\nend\n\nfunction rk2integrate(f, y0, h, n)\n res = [y0]\n for i in 1:n\n y1 = rk2step(f, y0, h)\n push!(res, y1)\n y0 = y1\n end\n res\nend\n\n#Solving now the wave equation in a box.\n#My state vector will be an array where the first index\n#indicates position and the second index indicates time step\n\nL=100\nT=100\n\n#Create the array\n\nu = zeros(L,T)\n\n#Boundary Conditions\n\nfor n=1:T\n u[1,n]=0.\n u[L,n]=0.\nend\n\n#Initial Conditions\n\nf(x)=sin(2*pi*x)\n\n#Discretization Parameter.\n#It has a big effect on stability\n\ns = 1\n\n#Finite difference scheme\n\nfi=sample(f,L)\nu[:,1]=fi\n\nfor j=2:L-1\n u[j,2]=u[j,1]-1/2*s*(u[j+1,1]-2*u[j,1]+u[j-1,1])\nend\n\nfor n=2:T-1\n for j=2:L-1\n u[j,n+1]=s*(u[j+1,n]+u[j-1,n]) + 2*(1.0-s)*u[j,n]-u[j,n-1]\n end\nend\n\n#Plot the solution\n\ng(x,j)=evaluate(u[:,j],x)\n\nu5(x)=g(x,5)\nu10(x)=g(x,10)\nu25(x)=g(x,25)\nu27(x)=g(x,27)\nu30(x)=g(x,30)\nu50(x)=g(x,50)\n\nlabels = [\"t=5\" \"t=10\" \"t=25\" \"t=27\" \"t=30\" \"t=50\"]\n\nplot([u5,u10,u25,u27,u30,u50],0,1,xlabel=\"x\",ylabel=\"y\",plot_title=`Hello`,label=labels)\n\n#Energy of the solution (Conserved)- Using to check for stability\n\nud=similar(u)\nudt=similar(u)\n\nfor n=1:T\n ud[:,n]=deriv(u[:,n])\nend\n\nfor i=1:L\n udt[i,:]=deriv(u[i,:])\nend\n\nh(x,j)=evaluate(ud[:,j],x)\nk(x,j)=evaluate(udt[:,j],x)\n\nE=[]\nind=[]\n\nfor j=1:T\n\n p(x)=(h(x,j)^2+k(x,j)^2)\n\n Energy=rk2integrate(p,0.001,0.001,9000)[9000]\n\n push!(E,Energy)\n\n push!(ind,j)\n\nend\n\nplot(ind,E,ylabel=\"Energy\",xlabel=\"Time step\",label=\"Energy\")\n\n## Check for convergence\n\nE=[]\nind=[]\n\nfor i=1:10\n\n T=10*i\n\n L=10*i\n\n u = zeros(L,T)\n\n for n=1:T\n u[1,n]=0.\n u[L,n]=0.\n end\n\n fi=sample(f,L)\n u[:,1]=fi\n\n for j=2:L-1\n u[j,2]=u[j,1]-1/2*s*(u[j+1,1]-2*u[j,1]+u[j-1,1])\n end\n\n for n=2:T-1\n for j=2:L-1\n u[j,n+1]=s*(u[j+1,n]+u[j-1,n]) + 2*(1.0-s)*u[j,n]-u[j,n-1]\n end\n end\n\n ud=similar(u)\n udt=similar(u)\n\n for n=1:T\n ud[:,n]=deriv(u[:,n])\n end\n\n for i=1:L\n udt[i,:]=deriv(u[i,:])\n end\n\n #Let's take a particular j, that is, a particular time step\n\n j=10\n\n g(x,j)=evaluate(u[:,j],x)\n h(x,j)=evaluate(ud[:,j],x)\n k(x,j)=evaluate(udt[:,j],x)\n\n p(x)=(h(x,j)^2+k(x,j)^2)\n\n Energy=rk2integrate(p,0.001,0.001,9000)[9000]\n\n push!(E,Energy)\n\n push!(ind,L)\n\nend\n\nplot(ind,ylabel=\"Energy\",xlabel=\"Resolution\",label=\"Energy\")\n", "meta": {"hexsha": "2c3dd84459e8b9330cf578624e5a5eb67d2e9794", "size": 3810, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "wave.jl", "max_stars_repo_name": "JuliMaristany/WaveEquationBox", "max_stars_repo_head_hexsha": "c4df74ace6aa62e8e525c7577f2431f07730eba6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "wave.jl", "max_issues_repo_name": "JuliMaristany/WaveEquationBox", "max_issues_repo_head_hexsha": "c4df74ace6aa62e8e525c7577f2431f07730eba6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-03-02T20:25:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-02T20:50:26.000Z", "max_forks_repo_path": "wave.jl", "max_forks_repo_name": "JuliMaristany/WaveEquationBox", "max_forks_repo_head_hexsha": "c4df74ace6aa62e8e525c7577f2431f07730eba6", "max_forks_repo_licenses": ["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.3519313305, "max_line_length": 88, "alphanum_fraction": 0.5141732283, "num_tokens": 1545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966686936261, "lm_q2_score": 0.8856314723088732, "lm_q1q2_score": 0.8383358013778107}} {"text": "# # Example\n# Lets try to find a sparse representation for a matrix, so that the Frobeniusnorm of the difference \n# is as small as possible. \n# Lets consider a symmetric matrix $M$:\nusing SubspacePreservingSparsification\nusing SparseArrays\nusing LinearAlgebra\nM = [17.05 16.98 0.3 6.99 7; 16.98 0.2 7.1 6.9 0; 0.3 7.1 -12 0.01 17; 6.99 6.9 0.01 -11.97 0; 7 0 17 0 -0.1]\n\n# First we calculate a sparsity pattern:\nM_id = sparsity_pattern(M, 0.6, 2)\n# For every column and every row of the Matrix the function solves the optimization problem\n# ```math\n# max_{Z}\\, ||x - x\\circ Z(x)||_{0}\\,\\, s.t. \\\\\n# ```\n# ```math\n# \\begin{align*}\n# (Z(x))_{i} &= 0 \\, \\text{or}\\, 1 \\\\\n# ||Z(x)||_{0} &\\ge N \\\\\n# ||x - x\\circ Z(x)||_{p} \t\\,&\\le\\, (1-q)||x||_{p},\n# \\end{align*}\n# ```\n# where $Z$ is the sparsity pattern for the column or row. $N$ is a maximum number for non zero entries, \n# $q$ is a factor that controls how sparse the the row or column should be. All the individual row and column\n# patter are overlayed, if either row or column or both return a one for an entry the entry is one.\n# This ensures that the pattern will preserve different Subspaces of the Matrix. \n\n# Than we can take the sparsity pattern and modify it to a binning pattern:\nbin_sparse_matrix!(M, M_id, 200)\n# The function looks at the maximum and minimum values of the matrix and then finds a partition \n# of the negative and positive area according to the specified maximum number of bins.\n# For each entry of the matrix it is checked to which bin it belongs to. The binning controls the \n# number of unknowns and so the computation cost to solve the optimization problem. It also typically \n# improves the conditioning of the optimization problem.\n\n# With the binning pattern we can find the Matrix so that the norm of the difference \n# is as small as possible and so that the binning constrains are fullfilled:\nbinned_minimization(M_id, zeros(5, 5), Matrix{Float64}(I, 5, 5), M)\n\n# The function solves the optimization problem\n# ```math\n# min ||M - X||_{F} \\,\\, s.t.\n# ```\n# ```math\n# X\\, \\text{has the specified sparsity pattern}\\, B(M) = M_{id}\n# ```\n# Of course our example optimization problem is not too interesting, because without the binning\n# only some entries are set to zero, while the others remain the same. However, \n# more sophisticated optimization problems can be used here.\n\n# We can also use the sparsify function on $M$:\nsparsify(M, 0.6, 2, 200)\n# This function calculates the sparsity and binning pattern like we did and uses as optimization problem\n\n# ```math\n# \\min\\limits_{X} \\frac{1}{2} \\sum\\limits_{i=1}^r \\frac{1}{\\sigma_i^2} ||\\left( X - M\\right) v_i||_2^2 \n# + \\frac{1}{2} \\sum\\limits_{i=1}^r \\frac{1}{\\sigma_i^2} ||\\left( X^* - M^*\\right) u_i||_2^2,\n# ```\n\n# where $r$ is the rank, $\\sigma_i$ are the $r$ biggest singular values, $v_i$ the corresponding right singular vectors and $u_i$ \n# the corresponding left singular vectors of $M$. $M^*$ denotes the conjugate transpose of $M$. The function compares the action of \n# the unknown matrix $X$ with the action of $M$ on the singular vectors of $M$ and penalizes the differences in near null-space with \n# larger weights. It can be formulatet in the form\n\n# ```math\n# X M^+(M^+)^* + (M^+)^*M^+X = MM^+(M^+)^* (M^+)^*M^+M,\n# ```\n\n# where $M^+$ is the pseudo inverse of $M$.\n# We can also set `impose_null_spaces` true:\nsparsify(M, 0.6, 2, 200, true)\n# Then after the described optimization problem was solved the function also solves an additional optimization problem that\n# ensures that the left and right null-spaces are preserved exactly. Because our matrix has full rank this makes no difference in our case.\n# \n", "meta": {"hexsha": "d3cf82a5db08b5d223bd4db495373bbab388361e", "size": 3668, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/literate/example.jl", "max_stars_repo_name": "Matt1h/SSA.jl", "max_stars_repo_head_hexsha": "c7cc678e287f14c2d24561442bdd7439b6f9502c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-03-29T09:47:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T12:02:56.000Z", "max_issues_repo_path": "docs/literate/example.jl", "max_issues_repo_name": "Matt1h/SSA.jl", "max_issues_repo_head_hexsha": "c7cc678e287f14c2d24561442bdd7439b6f9502c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-03-25T15:21:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T17:20:56.000Z", "max_forks_repo_path": "docs/literate/example.jl", "max_forks_repo_name": "Matt1h/SSA.jl", "max_forks_repo_head_hexsha": "c7cc678e287f14c2d24561442bdd7439b6f9502c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.9066666667, "max_line_length": 139, "alphanum_fraction": 0.7020174482, "num_tokens": 1116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960951703918909, "lm_q2_score": 0.8723473647220786, "lm_q1q2_score": 0.8382836865388514}} {"text": "import RowEchelon\n\n#=\nHomework 2\nSection 1.4\nProblem 11\n=#\n\n# Create the first Matrix\nA = [1 3 -4 ; \n\t 1 5 2 ; \n\t -3 -7 6]\n\n# Create the second matrix\nB = [-2 ; 4 ; 12]\n\n# Create an augmented matrix\nAugment = [1 3 -4 -2 ;\n\t\t 1 5 2 4 ;\n\t\t -3 -7 6 12]\n\n# Solve the matrix\nAugment_rref = RowEchelon.rref(Augment)\n\n# Print the results\nprintln()\nprintln(\"Original Matrix, A:\")\nprintln(A)\nprintln(\"Original Matrix, B\")\nprintln(B)\nprintln(\"Augmented Matrix:\")\nprintln(Augment)\nprintln(\"Row Reduced Echelon Matrix:\")\nprintln(Augment_rref)\nprintln(\"Solution as a vector:\")\nprintln(Augment_rref[:,4])\nprintln()\n\n", "meta": {"hexsha": "7fe42f04d6de941fe06375cf05ff52c9cfe0a326", "size": 606, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "HW2_S1.4_P11.jl", "max_stars_repo_name": "tleecsm/J4LA", "max_stars_repo_head_hexsha": "0ff51fa1771e9b5fc0b8a684a65cb36cebb8eefb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HW2_S1.4_P11.jl", "max_issues_repo_name": "tleecsm/J4LA", "max_issues_repo_head_hexsha": "0ff51fa1771e9b5fc0b8a684a65cb36cebb8eefb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW2_S1.4_P11.jl", "max_forks_repo_name": "tleecsm/J4LA", "max_forks_repo_head_hexsha": "0ff51fa1771e9b5fc0b8a684a65cb36cebb8eefb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.5384615385, "max_line_length": 39, "alphanum_fraction": 0.6716171617, "num_tokens": 205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9553191271831558, "lm_q2_score": 0.8774767906859265, "lm_q1q2_score": 0.838270361801556}} {"text": "\n\"\"\"\n SqExponential(lnℓ::AbstractFloat) <: RadialKernel{SqEuclidean}\n\nThe squared exponential kernel (aka the Gaussian kernel) with length scale \n``\\\\exp(2 \\\\ln\\\\ell) = \\\\ell^2 > 0``. \n\n```math\nk_{\\\\ell}(x, y) = k_{\\\\ell}(\\\\lVert x - y\\\\rVert_2^2) = \n\\\\exp\\\\bigg\\\\lbrace -\\\\frac{\\\\lVert x - y\\\\rVert_2^2}{2\\\\ell^2}\\\\bigg\\\\rbrace\n```\n\nExternal links\n* [RBF Kernel on Wikipedia](https://en.wikipedia.org/wiki/Radial_basis_function_kernel)\n\n\"\"\"\nmutable struct SqExponential{F<:AbstractFloat} <: RadialKernel{SqEuclidean}\n dist::SqEuclidean\n lnℓ::F\n twoℓ²::F\n function SqExponential(dist::SqEuclidean, lnℓ::AbstractFloat)\n new{typeof(lnℓ)}(dist, lnℓ, exp(2 * lnℓ + float(logtwo)))\n end\nend\n\nSqExponential(lnℓ::AbstractFloat) = SqExponential(SqEuclidean(), lnℓ)\n\n@inline (k::SqExponential)(τ::AbstractFloat) = exp(-τ / k.twoℓ²)\n\nGaussian = SqExponential\n\nnumparams(::SqExponential) = (1,)\nparamtypes(::SqExponential{F}) where F = (F,)\nparams(k::SqExponential) = (lnℓ = k.lnℓ,)\nfunction setparams!(k::SqExponential{F}, lnℓ::F) where F\n k.lnℓ = lnℓ\n k.twoℓ² = exp(2 * lnℓ + float(logtwo))\nend\n", "meta": {"hexsha": "2d107871859cda47ad9a7aa89eae7c932b2dbb4a", "size": 1117, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels/radial/SqExponential.jl", "max_stars_repo_name": "cameton/SKI.jl", "max_stars_repo_head_hexsha": "23b181da99b00b7f1a345ec1004c126624c508ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernels/radial/SqExponential.jl", "max_issues_repo_name": "cameton/SKI.jl", "max_issues_repo_head_hexsha": "23b181da99b00b7f1a345ec1004c126624c508ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernels/radial/SqExponential.jl", "max_forks_repo_name": "cameton/SKI.jl", "max_forks_repo_head_hexsha": "23b181da99b00b7f1a345ec1004c126624c508ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.641025641, "max_line_length": 87, "alphanum_fraction": 0.6723366159, "num_tokens": 400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133464597458, "lm_q2_score": 0.8918110382493035, "lm_q1q2_score": 0.8382250973706432}} {"text": "# Exercise 1\n\nusing LinearAlgebra, Statistics\n\nfunction lyapunov(A,Σ; tolerance = 1.0E-8, maxiter = 500, S0 = Σ*Σ')\n\n #initialise loop\n normdiff = Inf\n iter = 1\n S_old = S0\n Q = Σ * Σ'\n\n while normdiff > tolerance && iter ≤ maxiter\n\n S_new = A * S_old * A' + Q\n\n #continue looping\n normdiff = norm(S_old - S_new)\n S_old = S_new\n iter = iter +1\n end\n return (S_old,iter)\nend\n\n# test function\nA = [0.8 -0.2; -0.1 0.7]\nΣ = [0.5 0.4; 0.4 0.6]\n\n@show maximum(abs, eigvals(A))\n\nour_solution, iter = lyapunov(A, Σ)\n\n###############\n# Exercise 2\n###############\nusing Plots\n\nΘ = [0.8, 0.9, 0.98] #parameters\nγ = 1\nσ = 1\nT = 150 #horizon\np = plot() #naming plot to add\ny0 = 1\nτ = 5 # moving average - interval\n\nfor θ in Θ\n y = zeros(T+1)\n y[1] = y0\n for i ∈ 1:T\n y[i+1] = γ + θ * y[i] + σ * randn()\n end\n plot!(p, y, label = \"θ = $θ\")\n\n # moving average\n x = zeros(T+1)\n for i ∈ τ:(T+1)\n x[i]= sum(y[(i-τ+1):i])/τ\n end\n\n plot!(p, x, label = \"rolling mean θ = $θ\" )\nend\np\n\n# simulate \"nsamp\" times\n\nfunction sim_randomwalk_drift(Θ,γ,σ,T)\n\n y_sim = zeros(nsamp,length(Θ))\n for j in 1:nsamp\n\n y = zeros(T+1,length(Θ))\n y[1,:] = ones(eltype(Θ), length(Θ))\n\n for i in 1:T\n y[i+1,:] = γ .+ Θ .*y[i,:] + σ.*randn(3)\n end\n\n y_sim[j,:] = y[T+1,:]\n end\n return y_sim\nend\n\ny_sim = sim_randomwalk_drift(Θ,γ,σ,T)\n\n# find mean and variance of ensemble averages\n\n@show (mean_θ1, mean_θ2, mean_θ3) = (mean(y_sim[:,1]),mean(y_sim[:,2]),mean(y_sim[:,3]))\n@show (var_θ1, var_θ2, var_θ3) = (var(y_sim[:,1]),var(y_sim[:,2]),var(y_sim[:,3]))\n\n# plot histogram of T+1 values\n\nh=histogram()\nfor (i,θ) in enumerate(Θ)\n histogram!(h, y_sim[:,i],α =0.5, label = \"θ = $θ\",bins =20)\nend\nh\n\n##############\n# Exercise 3\n##############\n\n\n# simulate observations\n\nN = 50 # number of observations\n\nx_1, x_2 = (randn(N), randn(N))\n\na, b, c, d, σ = (0.1, 0.2, 0.5, 1.0, 0.1) #parameters\n\n# simulate data\n\nfunction simdata(a, b, c, d, σ, N; M = 20)\n y = zeros(N,M)\n for i in 1:N\n y[i,:] = a * x_1[i] + b * x_1[i]^2 + c * x_2[i] + d .+ σ.*randn(M)\n end\n return y\nend\n\nY = simdata(a, b, c, d, σ, N)\n\n# perform OLS\n\nX = [x_1 x_1.^2 x_2 ones(N)]\nβ = zeros(M,size(X)[2])\n\nfor m in 1:M\n β[m,:] = inv(X'*X)*X'*Y[:,m]\nend\nβ\n\n\n# plot histograms\nΘ = [\"a=0.1\" \"b=0.2\" \"c=0.5\" \"d=1.0\"]\nh = histogram()\n\nfor (i,θ) in enumerate(Θ)\n histogram!(h, β[:,i],α = 0.8, label = θ, bins = 10)\nend\nh\n\n############################\n# Exercise 4 - use NL solve\n############################\n\nusing NLsolve\n\n\nA = [0.8 -0.2; -0.1 0.7]\nΣ = [0.5 0.4; 0.4 0.6]\nQ = Σ * Σ'\nS0 = Σ * Σ'\n\nf(S) = A * S * A' + Q\n\nf(S0)\nsol = fixedpoint(f,S0)\nsol\n", "meta": {"hexsha": "53f647a3d8df638eea544a4366f1c0f3adab56ef", "size": 2755, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "GettingStarted_ArraysTuplesRanges.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_ArraysTuplesRanges.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_ArraysTuplesRanges.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": 17.21875, "max_line_length": 88, "alphanum_fraction": 0.5085299456, "num_tokens": 1149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545348152282, "lm_q2_score": 0.8840392710530071, "lm_q1q2_score": 0.8382058438036573}} {"text": "# Simple Quadratic Regression\n# Originally written by Keegan Go for lsqpy\n# Translated into LinearLeastSquares.jl by Karanveer Mohan and David Zeng\n\nusing LinearLeastSquares\nusing Gadfly\n# Set the random seed to get consistent data\nsrand(1)\n\n# Number of examples to use\nn = 100\n\n# Specify the true value of the variable\ntrue_coeffs = [2; -2; 0.5]\n\n# Generate data\nx_data = rand(n, 1) * 5\nx_data_expanded = hcat([x_data .^ i for i in 1 : 3]...)\ny_data = x_data_expanded * true_coeffs + 0.5 * rand(n, 1)\n\nquadratic_coeff = Variable()\nslope = Variable()\noffset = Variable()\nquadratic = offset + x_data * slope + quadratic_coeff * x_data .^ 2\nresiduals = quadratic - y_data\nfit_error = sum_squares(residuals)\noptval = minimize!(fit_error)\n\n# Create some evenly spaced points for plotting, again replicate powers\nt = reshape([0 : 0.1 : 5], length([0 : 0.1 : 5]), 1)\nt_squared = t .^ 2\n\n# Plot our regressed function\np = plot(\n layer(x=x_data, y=y_data, Geom.point),\n layer(x=t, y=evaluate(offset) + t * evaluate(slope) + t_squared * evaluate(quadratic_coeff), Geom.line),\n Theme(panel_fill=color(\"white\"))\n)\n# draw(PNG(\"quadratic_regression.png\", 16cm, 12cm), p)\n", "meta": {"hexsha": "ef743554ee714757df38617c723e565547cc3ee6", "size": 1161, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/regression/quadratic_regression.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/LinearLeastSquares.jl-a8002f64-6652-5b53-92ba-d4864fedfa0a", "max_stars_repo_head_hexsha": "f50c74231e7204bb63a9f49ea606ba28dddd3fa5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2015-06-25T15:56:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T16:36:46.000Z", "max_issues_repo_path": "examples/regression/quadratic_regression.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/LinearLeastSquares.jl-a8002f64-6652-5b53-92ba-d4864fedfa0a", "max_issues_repo_head_hexsha": "f50c74231e7204bb63a9f49ea606ba28dddd3fa5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2016-07-12T03:00:37.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-06T12:25:56.000Z", "max_forks_repo_path": "examples/regression/quadratic_regression.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/LinearLeastSquares.jl-a8002f64-6652-5b53-92ba-d4864fedfa0a", "max_forks_repo_head_hexsha": "f50c74231e7204bb63a9f49ea606ba28dddd3fa5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2015-02-14T02:30:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T18:11:37.000Z", "avg_line_length": 29.025, "max_line_length": 106, "alphanum_fraction": 0.7166236003, "num_tokens": 358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545304202039, "lm_q2_score": 0.8840392725805823, "lm_q1q2_score": 0.8382058413666608}} {"text": "# Astronomy example from Hairer et al 1992 p.245. As Hairer writes, \"a\n# celestial mechanics problem( which we call 'the Pleiades'): seven stars in\n# the plan with coordinates x_i,y_i and masses m_i = i\". Time span from\n#t =0 to t= 3. This is a non-stiff problem.\n#\n# Reference solution and a more in depth description can be found in\n# https://archimede.dm.uniba.it/~testset/report/plei.pdf\n\n\nexport plei\n\n# create an instance of TestCaseExplicit by filling in the ...:\nplei = let\n tcname = :plei ::Symbol # name should be same as variable name (except for upper/lower case)\n\n T = Float64 # the datatype used, probably Float64\n Tarr = [Matrix, SparseMatrixCSC][2] # the container datatype used\n # for the Jacobian and mass\n # matrix, probably Matrix\n # (default) or\n # SparseMatrixCSC.\n const N = 7\n const dof = 4N::Int # degrees of freedom\n dae = 0 ::Int # index of DAE, ==0 for ODE\n # stiffness of system, one of the three constants\n stiffness = [nonstiff, mildlystiff, stiff][1]\n\n ## the problem function\n function fn!(t::T,y::Vector{T},dydt::Vector{T})\n # The ode function dydt = f(t,y) modifying dydt in-place.\n # Note that all indices of dydt need to be written!\n\n # Problem is of the form z = (x,y) and z'' = f(z), (z(0),z'(0)) = (z_0,z'_0)\n\n #input (z,w), where w = z'\n #output dydt = (z,w)' = (w, f(z)) , where f(z) = z''\n\n for i=1:2N\n dydt[i] = y[2N+i]\n end\n\n dydt[2N+1:end] = 0\n\n #parameters\n for i = 1:N\n for j =1:N\n if i != j\n r = ((y[i] -y[j])^2 + (y[i+N] -y[j+N])^2)^(3/2)\n #Note, for what follows, dydt[2N+i] = x″[i] and dydt[3N+i] = y″[i]\n dydt[2N+i] += j*(y[j] - y[i])/r #j factor is mass of particles,\n dydt[3N+i] += j*(y[j+N] - y[i+N])/r\n end\n end\n end\n\n return nothing\n end\n # initializes storage for y:\n fn!( ; T_::Type=T, dof_=dof) = zeros(T_,dof_)\n\n # NOTE, using keyword arguments more intuitively like:\n # fn!( ; T::Type=T, dof=dof) = zeros(T,dof)\n # does not work: https://github.com/JuliaLang/julia/issues/9948\n\n jac! = nothing\n mass! = nothing\n\n ic = T[3, 3, -1, -3, 2, -2, 2, #x(0)\n 3, -3, 2, 0, 0, -4, 4, #y(0)\n 0, 0, 0, 0, 0, 1.75, -1.5, #x'(0)\n 0, 0, 0, -1.25, 1, 0, 0] #y'(0)\n # vector of initial conditions\n tspan = T[0, 3] # integration interval\n\n refsol = T[0.3706139143970502,3.237284092057233,-3.222559032418324,0.6597091455775310, 0.3425581707156584, 1.562172101400631,-0.7003092922212495,\n -3.943437585517392,-3.271380973972550, 5.225081843456543, -2.590612434977470, 1.198213693392275, -0.2429682344935824,1.091449240428980,\n 3.417003806314313, 1.354584501625501, -2.590065597810775, 2.025053734714242, -1.155815100160448, -0.8072988170223021, 0.5952396354208710,\n -3.741244961234010, 0.3773459685750630, 0.9386858869551073, 0.3667922227200571, -0.3474046353808490, 2.344915448180937, -1.947020434263292]\n # reference solution at tspan[2]\n\n\n refsolinds = trues(dof) # if refsol does not contain all indices\n # then specify which indices of the\n # solution are to be compared to refsol\n\n scd_absinds = Int[] # set where refsol is very small or\n # zero. To avoid it dominating the\n # relative error\n\n tc = TestCaseExplicit{tcname, T, Tarr}(\n stiffness,\n dae,\n dof,\n fn!,\n jac!,\n mass!,\n ic,\n tspan,\n refsol,\n refsolinds,\n scd_absinds)\n\n # put into the right buckets\n tc_all[tcname] = tc\n tc_nonstiff[tcname] = tc\n # Note that the return-result of the last statement of the let\n # block needs to be tc!\n tc\nend\n", "meta": {"hexsha": "f21b133048bf9d211e98574b45282e3f8e3b246c", "size": 4329, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/testcases/plei.jl", "max_stars_repo_name": "pwl/IVPTestSuite.jl", "max_stars_repo_head_hexsha": "15d92b5b943c35493ce29e8aa8def14619d96760", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/testcases/plei.jl", "max_issues_repo_name": "pwl/IVPTestSuite.jl", "max_issues_repo_head_hexsha": "15d92b5b943c35493ce29e8aa8def14619d96760", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/testcases/plei.jl", "max_forks_repo_name": "pwl/IVPTestSuite.jl", "max_forks_repo_head_hexsha": "15d92b5b943c35493ce29e8aa8def14619d96760", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.3545454545, "max_line_length": 155, "alphanum_fraction": 0.5255255255, "num_tokens": 1324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037384317887, "lm_q2_score": 0.9046505267461572, "lm_q1q2_score": 0.8379811648992522}} {"text": "using ProgressBars, Plots, LaTeXStrings, JLD\n\nchoices = ((1,0),(0,1),(-1,0),(0,-1))\n\nfunction RecurseSAW(R, Network, N)\n if N == 0\n return 1\n end\n count_ = 0\n Network[R...] = true\n for step in choices\n Rₙ = R .+ step\n if !Network[Rₙ...]\n count_ += RecurseSAW(Rₙ, Network, N-1)\n end\n end\n Network[R...] = false\n return count_\nend\n\nfunction maincal(N)\n dim = 2N+1\n Network = falses(dim,dim)\n R = [N+1,N+1]\n return RecurseSAW(R, Network, N)\nend\n\nTotList = [maincal(n) for n ∈ ProgressBar(0:17)]\nsave(\"../../Data/Q3/Q3-SAW.jld\", \"Data\", TotList)\n\nP1 = begin\n plot(0:17,log.(TotList), c = :black, label = nothing)\n scatter!(0:17,log.(TotList), c = :steelblue,framestyle = :box,\n ylabel = L\"ln\\ (Number\\ of\\ Paths)\", xlabel = L\"N\",\n label = L\"Self-Avoiding\\ Walker\", legend = 140)\n plot!(0:17, log.(4 .^(0:17)), c = :black, label = nothing)\n scatter!(0:17, log.(4 .^(0:17)), c = :purple, label = L\"Random\\ Walker\")\nend\n\n\nP2 = begin\n plot(0:17,TotList, c = :black, label = nothing)\n scatter!(0:17,TotList, c = :steelblue,framestyle = :box,\n ylabel = L\"Number\\ of\\ Paths\", xlabel = L\"N\",\n label = L\"Self-Avoiding\\ Walker\", legend = 140)\n plot!(0:13,4 .^(0:13), c = :black, label = nothing)\n scatter!(0:13, 4 .^(0:13), c = :purple, label = L\"Random\\ Walker\")\nend\n\nsavefig(P1,\"../../Figs/Q3/Q3-1.pdf\")\nsavefig(P2,\"../../Figs/Q3/Q3-2.pdf\")\n\nP3 = begin\n plot(0:17, TotList./ 4 .^(0:17), c = :black, label = nothing)\n scatter!(0:17, TotList./ 4 .^(0:17), c = :steelblue,framestyle = :box,\n ylabel = L\"Ratio\\ of\\ Number\\ of\\ Paths\", xlabel = L\"N\", legend = nothing,\n title = L\"Ratio\\ of\\ Number\\ of\\ Paths\\ of\\ SAW\\ and\\ RW\")\nend\n\nsavefig(P3,\"../../Figs/Q3/Q3-3.pdf\")\n", "meta": {"hexsha": "3bfc7476eefed92219798a3465c091b8363f316a", "size": 1821, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ProblemSet5/Codes/Q3/Q3-SAW.jl", "max_stars_repo_name": "shahmari/ComputationalPhysics-Fall2021", "max_stars_repo_head_hexsha": "f1681e32258c55697d11009e1702eb86d5f119d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ProblemSet5/Codes/Q3/Q3-SAW.jl", "max_issues_repo_name": "shahmari/ComputationalPhysics-Fall2021", "max_issues_repo_head_hexsha": "f1681e32258c55697d11009e1702eb86d5f119d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ProblemSet5/Codes/Q3/Q3-SAW.jl", "max_forks_repo_name": "shahmari/ComputationalPhysics-Fall2021", "max_forks_repo_head_hexsha": "f1681e32258c55697d11009e1702eb86d5f119d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-21T11:07:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-21T11:07:08.000Z", "avg_line_length": 29.8524590164, "max_line_length": 82, "alphanum_fraction": 0.5579352004, "num_tokens": 651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425223682086, "lm_q2_score": 0.9111797015700343, "lm_q1q2_score": 0.8379595990825779}} {"text": "import Pkg; Pkg.add(Pkg.PackageSpec(url=\"https://github.com/JuliaComputing/JuliaAcademyData.jl\"))\nusing JuliaAcademyData; activate(\"Parallel_Computing\")\n\n# # Parallel Algorithms: Thinking in Parallel\n#\n# Now that we're starting to see the challenges of parallelism, it's worth taking\n# a step back and examining how we might go about designing parallel algorithms.\n#\n# This is adapted from a [workshop paper](http://jiahao.github.io/parallel-prefix/) by Jiahao Chen and\n# Alan Edelman entitled \"Parallel Prefix Polymorphism Permits Parallelization, Presentation & Proof\" and\n# will appear in the proceedings of the [First Workshop for High Performance Technical Computing in Dynamic\n# Languages](http://jiahao.github.io/hptcdl-sc14/), held in conjunction with [SC14: The International Conference on High Performance Computing, Networking, Storage and Analysis](http://sc14.supercomputing.org/)\n\n#-\n\nusing Compose, Gadfly\n\n# # `reduce()`\n#\n# Reduction applies a binary operator to a vector repeatedly to return a scalar. Thus + becomes sum, and * becomes prod.\n#\n# It is considered a basic parallel computing primitive.\n\nreduce(+, 1:8), sum(1:8) # triangular numbers\n\n#-\n\nreduce(*, 1:8), prod(1:8) # factorials\n\n#-\n\nboring(a,b)=a\n@show reduce(boring, 1:8)\nboring2(a,b)=b\n@show reduce(boring2, 1:8)\n\n# You can also use reduce to compute Fibonacci numbers using their recurrences.\n#\n# $$\\begin{pmatrix} f_2 \\\\f_1 \\end{pmatrix} = \\begin{pmatrix} f_1 + f_0 \\\\ f_1 \\end{pmatrix}\n# = \\begin{pmatrix} 1 & 1 \\\\ 1 & 0 \\end{pmatrix} \\begin{pmatrix} f_1 \\\\ f_0 \\end{pmatrix} $$\n#\n# $$\\begin{pmatrix} f_{n+1} \\\\ f_n \\end{pmatrix} = \\dots\n# = \\begin{pmatrix} 1 & 1 \\\\ 1 & 0 \\end{pmatrix}^n \\begin{pmatrix} f_1 \\\\ f_0 \\end{pmatrix} $$\n#\n# From this, you can show that\n#\n# $$\\begin{pmatrix} 1 & 1 \\\\ 1 & 0 \\end{pmatrix}^n = \\begin{pmatrix} f_{n+1} & f_n \\\\ f_n & f_{n-1} \\end{pmatrix} $$\n#\n# (this applies reduce to the same argument over and over again -- there are of course other ways)\n\nM=[1 1; 1 0]\nreduce(*,fill(M,3))\nprod(fill(M,3))\n\n#-\n\nn= 50 # Try manipulating n to pick different values (try between 0-100)\nprod(fill(big.(M),n))\n\n#-\n\nfib(j)=reduce(*, fill(M,j))\nfib.([4,7])\n\n# You can solve recurrences of any complexity using `reduce`. For example, `reduce` can compute a Hadamard matrix from its definition in terms of its submatrices:\n#\n# $$H_2 = \\begin{pmatrix} H_1 & H_1 \\\\ H_1 & -H_1 \\end{pmatrix} = \\begin{pmatrix} 1 & 1 \\\\ 1 & -1 \\end{pmatrix} \\otimes H_1$$\n#\n# and so on.\n#\n# (Note: this is just using reduce to compute a matrix power.\n# One can think of alternative ways for sure.)\n\n## If A is m x n\n## If B is p x q\n## then kron(A,B) is mp x nq and has all the elements of A times all of the elements of B\n\n#-\n\nA=[1 2;3 4]\nB=[10 100; 1 -10]\n⊗(A,B)=kron(A,B)\n\nM=[ 1 1;1 -1]\nH=⊗(⊗(⊗(M,M),M),M)\n\n#-\n\nH'H\n\n#-\n\nHadamard(n)=reduce(⊗, fill(M,n))\nH=Hadamard(4)\n\n#-\n\nusing LinearAlgebra\ncumsum(1:8) # It is useful to know that cumsum is a linear operator\n## You can use power method! Below is the underlying matrix\nA=tril(ones(Int,8,8))\n\n#-\n\n[A*(1:8),cumsum(1:8)]\n\n# # `prefix`\n\n#-\n\n# Having discussed `reduce`, we are now ready for the idea behind prefix sum.\n# Prefix or scan is long considered an important parallel\n# primitive as well.\n#\n# Suppose you wanted to compute the partial sums of a vector, i.e. given\n# `y[1:n]`, we want to overwrite the vector `y` with the vector of partial sums\n#\n# ```julia\n# new_y[1] = y[1]\n# new_y[2] = y[1] + y[2]\n# new_y[3] = y[1] + y[2] + y[3]\n# ...\n# ```\n#\n# At first blush, it seems impossible to parallelize this, since\n#\n# ```julia\n# new_y[1] = y[1]\n# new_y[2] = new_y[1] + y[2]\n# new_y[3] = new_y[2] + y[3]\n# ...\n# ```\n#\n# which appears to be an intrinsically serial process. As written with a `+`\n# operator, this is `cumsum` — but note that it can generalize to any operation.\n\nfunction prefix_serial!(y, ⊕)\n for i=2:length(y)\n y[i] = y[i-1] ⊕ y[i]\n end\n y\nend\n\n#-\n\nprefix_serial!([1:8;],+)\n\n#-\n\ncumsum(1:8)\n\n#-\n\nprefix_serial!([1:8;], *)\n\n#-\n\ncumprod(1:8)\n\n# However, it turns out that because these operations are associative, we can regroup the _order_ of how these sums or products are carried out. (This of course extends to other associative operations, too.) Another ordering of 8 associative operations is provided by `prefix8!`:\n\n## Magic :)\nfunction prefix8!(y, ⊕)\n length(y)==8 || error(\"length 8 only\")\n for i in (2,4,6,8); y[i] = y[i-1] ⊕ y[i]; end\n for i in ( 4, 8); y[i] = y[i-2] ⊕ y[i]; end\n for i in ( 8); y[i] = y[i-4] ⊕ y[i]; end\n for i in ( 6 ); y[i] = y[i-2] ⊕ y[i]; end\n for i in ( 3,5,7 ); y[i] = y[i-1] ⊕ y[i]; end\n y\nend\n\n#-\n\nprefix8!([1:8;], +) == cumsum(1:8)\n\n# In fact, this can generalize beyond just length-8 arrays:\n\n## More magic\nfunction prefix!(y, ⊕)\n l=length(y)\n k=ceil(Int, log2(l))\n @inbounds for j=1:k, i=2^j:2^j:min(l, 2^k) #\"reduce\"\n y[i] = y[i-2^(j-1)] ⊕ y[i]\n end\n @inbounds for j=(k-1):-1:1, i=3*2^(j-1):2^j:min(l, 2^k) #\"expand\"\n y[i] = y[i-2^(j-1)] ⊕ y[i]\n end\n y\nend\n\n# -\n\nA = rand(0:9, 123)\nprefix!(copy(A), *) == cumprod(A)\n\n# ## What is this magic?\n\n#-\n\n# We can visualize the operations with a little bit of trickery. In Julia, arrays are simply types that expose the array protocol. In particular, they need to implement methods for the generic functions `length`, `getindex` and `setindex!`. The last two are used in indexing operations, since statements\n#\n# y = A[1]\n# A[3] = y\n#\n# get desugared to\n#\n# y = getindex(A, 1)\n# setindex!(A, y, 3)\n#\n# respectively.\n#\n# We can trace through the iterable by introduce a dummy array type, `AccessArray`, which records every access to `getindex` and `setindex!`.\n#\n# Specifically:\n#\n# - `length(A::AccessArray)` returns the length of the array it wraps\n# - `getindex(A::AccessArray, i)` records read access to the index `i` in the `A.read` field and then actually retuns the value in the array it wraps.\n# - `setindex!(A::AccessArray, x, i)` records write access to the index `i`. The `A.history` field is appended with a new tuple consisting of the current `A.read` field and the index `i`, and then it performs the assignment.\n#\n# The way `AccessArray` works, it assumes an association between a single `setindex!` call and and all the preceding `getindex` calls since the previous `setindex!` call, which is sufficient for the purposes of tracing through prefix calls.\n\nmutable struct AccessArray{T,N,A}\n data :: A\n read :: Vector{Int}\n history :: Vector{Tuple{Vector{Int},Int}}\nend\nAccessArray(A) = AccessArray{eltype(A), ndims(A), typeof(A)}(A, Int[], Int[])\n\nBase.length(A::AccessArray) = length(A.data)\n\nfunction Base.getindex(A::AccessArray, i::Int)\n push!(A.read, i)\n A.data[i]\nend\n\nfunction Base.setindex!(A::AccessArray, x, i::Int)\n push!(A.history, (A.read, i))\n A.read = Int[]\n A.data[i] = x\nend\n\n#-\n\nM = AccessArray(rand(8))\n\n#-\n\nM[7] = M[3] + M[2]\n\n#-\n\nM.history\n\n# So now we can trace the access pattern when calling `prefix8`!\n\nA=prefix8!(AccessArray(rand(8)),+)\n\n#-\n\nA.history\n\n# Now let's visualize this! Each entry in `A.history` is rendered by a gate object:\n\nusing Compose: circle, mm\n\n#-\n\nstruct Gate{I,O}\n ins :: I\n outs :: O\nend\n\nimport Gadfly.render\n\nfunction render(G::Gate, x₁, y₁, y₀; rᵢ=0.1, rₒ=0.25)\n ipoints = [(i, y₀+rᵢ) for i in G.ins]\n opoints = [(i, y₀+0.5) for i in G.outs]\n igates = [circle(i..., rᵢ) for i in ipoints]\n ogates = [circle(i..., rₒ) for i in opoints]\n lines = [line([i, j]) for i in ipoints, j in opoints]\n compose(context(units=UnitBox(0.5,0,x₁,y₁+1)),\n compose(context(), stroke(colorant\"black\"), fill(colorant\"white\"),\n igates..., ogates...),\n compose(context(), linewidth(0.3mm), stroke(colorant\"black\"),\n lines...))\nend\n\nA=Gate([1,2],2)\nrender(A,2,0,0)\n\n# Now we render the whole algorithm. We have to scan through the trace twice; the first time merely calculates the maximum depth that needs to be drawn and the second time actually generates the objects.\n\nfunction render(A::AccessArray)\n #Scan to find maximum depth\n olast = depth = 0\n for y in A.history\n (any(y[1] .≤ olast)) && (depth += 1)\n olast = maximum(y[2])\n end\n maxdepth = depth\n\n olast = depth = 0\n C = []\n for y in A.history\n (any(y[1] .≤ olast)) && (depth += 1)\n push!(C, render(Gate(y...), length(A), maxdepth, depth))\n olast = maximum(y[2])\n end\n\n push!(C, compose(context(units=UnitBox(0.5,0,length(A),1)),\n [line([(i,0), (i,1)]) for i=1:length(A)]...,\n linewidth(0.1mm), stroke(colorant\"grey\")))\n compose(context(), C...)\nend\n\n#-\n\nrender(prefix!(AccessArray(zeros(8)), +))\n\n# Now we can see that `prefix!` rearranges the operations to form two spanning trees:\n\nrender(prefix!(AccessArray(zeros(120)),+))\n\n# as contrasted with the serial code:\n\nrender(prefix_serial!(AccessArray(zeros(8)),+))\n\n#-\n\nnpp=90 # Try manipulating npp to choose different values between 1 and 180\nrender(prefix!(AccessArray(zeros(npp)),+))\n\n#-\n\nnpp=90 # And manipulate it again, this time with the serial algorithm\nrender(prefix_serial!(AccessArray(zeros(npp)),+))\n\n# # Now exploit the parallelism in the _algorithm_ to use a parallel _implementation_\n\nusing .Threads\nfunction prefix_threads!(y, ⊕)\n l=length(y)\n k=ceil(Int, log2(l))\n for j=1:k\n @threads for i=2^j:2^j:min(l, 2^k) #\"reduce\"\n @inbounds y[i] = y[i-2^(j-1)] ⊕ y[i]\n end\n end\n for j=(k-1):-1:1\n @threads for i=3*2^(j-1):2^j:min(l, 2^k) #\"expand\"\n @inbounds y[i] = y[i-2^(j-1)] ⊕ y[i]\n end\n end\n y\nend\n\nA = rand(500_000);\n\nusing BenchmarkTools\n@btime prefix_serial!($(copy(A)), +);\n@btime prefix!($(copy(A)), +);\n@btime prefix_threads!($(copy(A)), +);\n\nprefix_threads!(copy(A), +) == prefix!(copy(A), +) ≈ cumsum(A)\n\n# # Thinking in parallel\n#\n# Notice how we didn't need to contort ourselves in making our algorithm\n# work with `@threads`. We really did _just_ take a `@threads` on it and it\n# just worked. It was both accurate _and_ fast.\n#\n# Coming up with rearrangements that make your particular algorithm parallel\n# friendly isn't always easy, but when possible it makes everything else\n# just fall out naturally.\n#\n# Finally, note that there can be clever ways to visualize algorithms as sanity checks.\n\n", "meta": {"hexsha": "79100a5579ccd7234a83e2886e1c4fe0184ad490", "size": 10360, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Courses/Parallel_Computing/050 Parallel Algorithms.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/Parallel_Computing/050 Parallel Algorithms.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/Parallel_Computing/050 Parallel Algorithms.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": 27.3350923483, "max_line_length": 304, "alphanum_fraction": 0.6466216216, "num_tokens": 3367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425245706048, "lm_q2_score": 0.9111796991580949, "lm_q1q2_score": 0.8379595988712346}} {"text": "## matern.jl : implementation of Mat\\'ern covariance function?\n\n## Matern ##\nstruct Matern{T} <: IsotropicCovarianceStructure{T}\n λ::T\n ν::T\n σ::T\n p::T\n\n function Matern{T}(λ::T, ν::T, σ::T, p::T) where T\n λ > 0 || throw(DomainError(λ, \"correlation length λ of Mat\\u00E9rn covariance cannot be negative or zero\"))\n ν > 0 || throw(DomainError(ν, \"smoothness ν of Mat\\u00E9rn covariance cannot be negative or zero\"))\n σ > 0 || throw(DomainError(σ, \"marginal standard deviation σ of Mat\\u00E9rn covariance cannot be negative or zero\"))\n p >= 1 || throw(DomainError(p, \"in p-norm, p must be greater than or equal to 1\"))\n \tisinf(p) && throw(DomainError(p, \"in p-norm, p cannot be infinity\"))\n\n new{T}(λ, ν, σ, p)\n end\nend\n\n\"\"\"\n Matern(λ, ν, [σ = 1], [p = 2])\n\nMat\\u00E9rn covariance structure with correlation length `λ`, smoothness `ν`, (optional) marginal standard deviation `σ` and (optional) `p`-norm, defined as\n\n``C(x, y) = σ \\\\displaystyle\\\\frac{2^{1 - ν}}{Γ(ν)} \\\\left(\\\\frac{\\sqrt{2\\nu}ρ}{λ}\\\\right)^ν K_ν\\\\left(\\\\frac{\\sqrt{2\\nu}ρ}{λ}\\\\right)``\n\nwith ``ρ = ||x - y||_p``.\n\n# Examples\n```jldoctest\njulia> Matern(0.1, 1.0)\nMatérn (λ=0.1, ν=1.0, σ=1.0, p=2.0)\n\njulia> Matern(1, 1, σ=2.0)\nMatérn (λ=1.0, ν=1.0, σ=2.0, p=2.0)\n\n```\nSee also: [`Exponential`](@ref), [`Linear`](@ref), [`Spherical`](@ref), [`Whittle`](@ref), [`Gaussian`](@ref), [`SquaredExponential`](@ref)\n\"\"\"\nMatern(λ::Real, ν::Real; σ::Real=1.0, p::Real=2) =\n Matern{promote_type(typeof(λ),typeof(ν),typeof(σ),typeof(p))}(promote(λ, ν, σ, p)...)\n\n# TODO : Evaluation of the besselk function is extremely expensive; maybe try to catch special cases for ν = 1/2, 3/2 etc.\n# evaluate Matern covariance\nfunction apply(m::Matern, x::Real)\n if iszero(x)\n float(one(x))\n else\n 2^(1 - m.ν) / gamma(m.ν) * (sqrt(2 * m.ν) * x / m.λ)^m.ν * besselk(m.ν, sqrt(2 * m.ν) * x / m.λ)\n end\nend\n\n# short name\nshortname(::Matern) = \"Mat\\u00E9rn\"\n", "meta": {"hexsha": "687cb3471a5b2b8998de3cdcb82c285128f66f65", "size": 1980, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/covariance_functions/matern.jl", "max_stars_repo_name": "gerrygralton/GaussianRandomFields.jl", "max_stars_repo_head_hexsha": "be2740877a18a82e015e1a6d149036312ce79504", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/covariance_functions/matern.jl", "max_issues_repo_name": "gerrygralton/GaussianRandomFields.jl", "max_issues_repo_head_hexsha": "be2740877a18a82e015e1a6d149036312ce79504", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/covariance_functions/matern.jl", "max_forks_repo_name": "gerrygralton/GaussianRandomFields.jl", "max_forks_repo_head_hexsha": "be2740877a18a82e015e1a6d149036312ce79504", "max_forks_repo_licenses": ["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.3571428571, "max_line_length": 156, "alphanum_fraction": 0.6090909091, "num_tokens": 740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308128813471, "lm_q2_score": 0.8976952941600963, "lm_q1q2_score": 0.8379364481476187}} {"text": "# Computing deviation in a variety of ways\n\n# squared L2 distance\nfunction sqL2dist{T<:Number}(a::AbstractArray{T}, b::AbstractArray{T})\n n = length(a)\n length(b) == n || throw(DimensionMismatch(\"Input dimension mismatch\"))\n r = 0.0\n for i = 1:n\n @inbounds r += abs2(a[i] - b[i]) \n end\n return r\nend\n\n# L2 distance\nL2dist{T<:Number}(a::AbstractArray{T}, b::AbstractArray{T}) = sqrt(sqL2dist(a, b))\n\n# L1 distance\nfunction L1dist{T<:Number}(a::AbstractArray{T}, b::AbstractArray{T})\n n = length(a)\n length(b) == n || throw(DimensionMismatch(\"Input dimension mismatch\"))\n r = 0.0\n for i = 1:n\n @inbounds r += abs(a[i] - b[i]) \n end\n return r \nend\n\n# Linf distance\nfunction Linfdist{T<:Number}(a::AbstractArray{T}, b::AbstractArray{T})\n n = length(a)\n length(b) == n || throw(DimensionMismatch(\"Input dimension mismatch\"))\n r = 0.0\n for i = 1:n\n @inbounds v = abs(a[i] - b[i]) \n if r < v\n r = v\n end\n end\n return r \nend\n\n# Generalized KL-divergence\nfunction gkldiv{T<:FloatingPoint}(a::AbstractArray{T}, b::AbstractArray{T})\n n = length(a)\n r = 0.0\n for i = 1:n\n @inbounds ai = a[i]\n @inbounds bi = b[i]\n if ai > 0\n r += (ai * log(ai / bi) - ai + bi)\n else\n r += bi\n end\n end\n return r::Float64\nend\n\n# MeanAD: mean absolute deviation\nmeanad{T<:Number}(a::AbstractArray{T}, b::AbstractArray{T}) = L1dist(a, b) / length(a)\n\n# MaxAD: maximum absolute deviation\nmaxad{T<:Number}(a::AbstractArray{T}, b::AbstractArray{T}) = Linfdist(a, b)\n\n# MSD: mean squared deviation\nmsd{T<:Number}(a::AbstractArray{T}, b::AbstractArray{T}) = sqL2dist(a, b) / length(a)\n\n# RMSD: root mean squared deviation\nfunction rmsd{T<:Number}(a::AbstractArray{T}, b::AbstractArray{T}; normalize::Bool=false) \n\tv = sqrt(msd(a, b))\n\tif normalize\n\t\tamin, amax = extrema(a)\n\t\tv /= (amax - amin)\n\tend\n\treturn v\nend\n\n# PSNR: peak signal-to-noise ratio\nfunction psnr{T<:Real}(a::AbstractArray{T}, b::AbstractArray{T}, maxv::Real)\n 20. * log10(maxv) - 10. * log10(msd(a, b))\nend\n", "meta": {"hexsha": "b15c80f93d4e56e3e626763bbf6c136b53837644", "size": 2120, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/deviation.jl", "max_stars_repo_name": "wildart/StatsBase.jl", "max_stars_repo_head_hexsha": "3885542a93d2de71a1102da030c798cd51749481", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/deviation.jl", "max_issues_repo_name": "wildart/StatsBase.jl", "max_issues_repo_head_hexsha": "3885542a93d2de71a1102da030c798cd51749481", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/deviation.jl", "max_forks_repo_name": "wildart/StatsBase.jl", "max_forks_repo_head_hexsha": "3885542a93d2de71a1102da030c798cd51749481", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1728395062, "max_line_length": 90, "alphanum_fraction": 0.6033018868, "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582612793112, "lm_q2_score": 0.9005297921244243, "lm_q1q2_score": 0.8379053846103114}} {"text": "\"\"\"\n Difference array\n\n# Brief:\n For any array A with N numbers, we can create difference array D with N numbers also.\n Every k-th element of D is equal to difference between A[k] and A[k-1]\n D[k] = A[k-1] - A[k] \n\n# Complexity of some operations\n - add some value x to the m consecutive elements of array - O(1)\n - print array after any numbers of changes - O(N)\n\n# Functions\n - create_diff_arr(original::Array{T}) - Create difference array for array 'original'\n - calculate_arr(diff_arr::Array{T}) - Create a original array from the given difference array\n - add_to_arr(diff_arr::Array{T}, l::Int, r::Int, x::Number) - Add x to all elements with index from [l, r]\n\n\n# Contributed by: [Nikola Mircic](https://github.com/Nikola-Mircic)\n\"\"\"\nmodule DifferenceArray\n# Create difference array for array 'original'\n# Parameters:\n# - original - an array which is used for calculating the difference array\nfunction create_diff_arr(original::Array{T}) where {T<:Number}\n n = length(original)\n\n diff_arr = Array(original)\n\n for i in 2:n\n diff_arr[i] = original[i] - original[i-1]\n end\n\n return diff_arr\nend\n\n# Create a original array from the given difference array\n# Parameters:\n# - diff_arr - an difference array which is used for calculating the original array\nfunction calculate_arr(diff_arr::Array{T}) where {T<:Number}\n n = length(diff_arr)\n\n arr = Array(diff_arr)\n\n for i in 2:n\n arr[i] = diff_arr[i] + arr[i-1]\n end\n\n return arr\nend\n\n# Add x to all elements with index from [l, r]\n# Parameters:\n# - dif_arr - a difference array of the array you want to change\n# - l - leftmost index of the affected range\n# - r - rightmost index of the affected range\n# - x - a value to be added to all elements from a given range\nfunction add_to_arr(\n diff_arr::Array{T},\n l::Int,\n r::Int,\n x::Number,\n) where {T<:Number}\n diff_arr[l] += x\n if r < length(diff_arr)\n diff_arr[r+1] -= x\n end\nend\nend\n", "meta": {"hexsha": "005ff439f0816d18ac9b5be26c722fe7fb33cbcd", "size": 2011, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/basic/difference_arr.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/basic/difference_arr.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/basic/difference_arr.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": 28.7285714286, "max_line_length": 110, "alphanum_fraction": 0.6663351566, "num_tokens": 541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509315, "lm_q2_score": 0.9005297861178929, "lm_q1q2_score": 0.8379053772849213}} {"text": "# ------------------------------------------------------------------------------------------\n# # An Intro to DifferentialEquations.jl\n#\n# ## Basic Introduction Via Ordinary Differential Equations\n#\n# This notebook will get you started with DifferentialEquations.jl by introducing you to the\n# functionality for solving ordinary differential equations (ODEs). The corresponding\n# documentation page is the [ODE\n# tutorial](http://docs.juliadiffeq.org/latest/tutorials/ode_example.html). While some of\n# the syntax may be different for other types of equations, the same general principles hold\n# in each case. Our goal is to give a gentle and thorough introduction that highlights these\n# principles in a way that will help you generalize what you have learned.\n#\n# ### Background\n#\n# If you are new to the study of differential equations, it can be helpful to do a quick\n# background read on [the definition of ordinary differential\n# equations](https://en.wikipedia.org/wiki/Ordinary_differential_equation). We define an\n# ordinary differential equation as an equation which describes the way that a variable $u$\n# changes, that is\n#\n# $$ u' = f(u,p,t) $$\n#\n# where $p$ are the parameters of the model, $t$ is the time variable, and $f$ is the\n# nonlinear model of how $u$ changes. The initial value problem also includes the\n# information about the starting value:\n#\n# $$ u(t_0) = u_0 $$\n#\n# Together, if you know the starting value and you know how the value will change with time,\n# then you know what the value will be at any time point in the future. This is the\n# intuitive definition of a differential equation.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# ### First Model: Exponential Growth\n#\n# Our first model will be the canonical exponential growth model. This model says that the\n# rate of change is proportional to the current value, and is this:\n#\n# $$ u' = au $$\n#\n# where we have a starting value $u(0)=u_0$. Let's say we put 1 dollar into Bitcoin which is\n# increasing at a rate of $98\\%$ per year. Then calling now $t=0$ and measuring time in\n# years, our model is:\n#\n# $$ u' = 0.98u $$\n#\n# and $u(0) = 1.0$. We encode this into Julia by noticing that, in this setup, we match the\n# general form when\n#\n# $$ f(u,p,t) = 0.98u $$\n#\n# with $ u_0 = 1.0 $. If we want to solve this model on a time span from `t=0.0` to `t=1.0`,\n# then we define an `ODEProblem` by specifying this function `f`, this initial condition\n# `u0`, and this time span as follows:\n# ------------------------------------------------------------------------------------------\n\nusing DifferentialEquations\nf(u,p,t) = 0.98u\nu0 = 1.0\ntspan = (0.0,1.0)\nprob = ODEProblem(f,u0,tspan)\n\n# ------------------------------------------------------------------------------------------\n# To solve our `ODEProblem` we use the command `solve`.\n# ------------------------------------------------------------------------------------------\n\nsol = solve(prob)\n\n# ------------------------------------------------------------------------------------------\n# and that's it: we have succesfully solved our first ODE!\n#\n# #### Analyzing the Solution\n#\n# Of course, the solution type is not interesting in and of itself. We want to understand\n# the solution! The documentation page which explains in detail the functions for analyzing\n# the solution is the [Solution\n# Handling](http://docs.juliadiffeq.org/latest/basics/solution.html) page. Here we will\n# describe some of the basics. You can plot the solution using the plot recipe provided by\n# [Plots.jl](http://docs.juliaplots.org/latest/):\n# ------------------------------------------------------------------------------------------\n\nusing Plots; gr()\nplot(sol)\n\n# ------------------------------------------------------------------------------------------\n# From the picture we see that the solution is an exponential curve, which matches our\n# intuition. As a plot recipe, we can annotate the result using any of the [Plots.jl\n# attributes](http://docs.juliaplots.org/latest/attributes/). For example:\n# ------------------------------------------------------------------------------------------\n\nplot(sol,linewidth=5,title=\"Solution to the linear ODE with a thick line\",\n xaxis=\"Time (t)\",yaxis=\"u(t) (in μm)\",label=\"My Thick Line!\") # legend=false\n\n# ------------------------------------------------------------------------------------------\n# Using the mutating `plot!` command we can add other pieces to our plot. For this ODE we\n# know that the true solution is $u(t) = u_0 exp(at)$, so let's add some of the true\n# solution to our plot:\n# ------------------------------------------------------------------------------------------\n\nplot!(sol.t, t->1.0*exp(0.98t),lw=3,ls=:dash,label=\"True Solution!\")\n\n# ------------------------------------------------------------------------------------------\n# In the previous command I demonstrated `sol.t`, which grabs the array of time points that\n# the solution was saved at:\n# ------------------------------------------------------------------------------------------\n\nsol.t\n\n# ------------------------------------------------------------------------------------------\n# We can get the array of solution values using `sol.u`:\n# ------------------------------------------------------------------------------------------\n\nsol.u\n\n# ------------------------------------------------------------------------------------------\n# `sol.u[i]` is the value of the solution at time `sol.t[i]`. We can compute arrays of\n# functions of the solution values using standard comprehensions, like:\n# ------------------------------------------------------------------------------------------\n\n[t+u for (u,t) in tuples(sol)]\n\n# ------------------------------------------------------------------------------------------\n# However, one interesting feature is that, by default, the solution is a continuous\n# function. If we check the print out again:\n# ------------------------------------------------------------------------------------------\n\nsol\n\n# ------------------------------------------------------------------------------------------\n# you see that it says that the solution has a 4th order interpolation, meaning that it is a\n# continuous function of 4th order accuracy. We can call the solution as a function of time\n# `sol(t)`. For example, to get the value at `t=0.45`, we can use the command:\n# ------------------------------------------------------------------------------------------\n\nsol(0.45)\n\n# ------------------------------------------------------------------------------------------\n# #### Controlling the Solver\n#\n# DifferentialEquations.jl has a common set of solver controls among its algorithms which\n# can be found [at the Common Solver\n# Options](http://docs.juliadiffeq.org/latest/basics/common_solver_opts.html) page. We will\n# detail some of the most widely used options.\n#\n# The most useful options are the tolerances `abstol` and `reltol`. These tell the internal\n# adaptive time stepping engine how precise of a solution you want. Generally, `reltol` is\n# the relative accuracy while `abstol` is the accuracy when `u` is near zero. These\n# tolerances are local tolerances and thus are not global guarantees. However, a good rule\n# of thumb is that the total solution accuracy is 1-2 digits less than the relative\n# tolerances. Thus for the defaults `abstol=1e-6` and `reltol=1e-3`, you can expect a global\n# accuracy of about 1-2 digits. If we want to get around 6 digits of accuracy, we can use\n# the commands:\n# ------------------------------------------------------------------------------------------\n\nsol = solve(prob,abstol=1e-8,reltol=1e-8)\n\n# ------------------------------------------------------------------------------------------\n# Now we can see no visible difference against the true solution:\n# ------------------------------------------------------------------------------------------\n\nplot(sol)\nplot!(sol.t, t->1.0*exp(0.98t),lw=3,ls=:dash,label=\"True Solution!\")\n\n# ------------------------------------------------------------------------------------------\n# Notice that by decreasing the tolerance, the number of steps the solver had to take was\n# `9` instead of the previous `5`. There is a trade off between accuracy and speed, and it\n# is up to you to determine what is the right balance for your problem.\n#\n# Another common option is to use `saveat` to make the solver save at specific time points.\n# For example, if we want the solution at an even grid of `t=0.1k` for integers `k`, we\n# would use the command:\n# ------------------------------------------------------------------------------------------\n\nsol = solve(prob,saveat=0.1)\n\n# ------------------------------------------------------------------------------------------\n# Notice that when `saveat` is used the continuous output variables are no longer saved and\n# thus `sol(t)`, the interpolation, is only first order. We can save at an uneven grid of\n# points by passing a collection of values to `saveat`. For example:\n# ------------------------------------------------------------------------------------------\n\nsol = solve(prob,saveat=[0.2,0.7,0.9])\n\n# ------------------------------------------------------------------------------------------\n# By default it always saves the first and last values, but we can turn this off as well:\n# ------------------------------------------------------------------------------------------\n\nsol = solve(prob,saveat=[0.2,0.7,0.9],save_start = false, save_end = false)\n\n# ------------------------------------------------------------------------------------------\n# If we need to reduce the amount of saving, we can also turn off the continuous output\n# directly via `dense=false`:\n# ------------------------------------------------------------------------------------------\n\nsol = solve(prob,dense=false)\n\n# ------------------------------------------------------------------------------------------\n# and to turn off all intermediate saving we can use `save_everystep=false`:\n# ------------------------------------------------------------------------------------------\n\nsol = solve(prob,save_everystep=false)\n\n# ------------------------------------------------------------------------------------------\n# More advanced saving behaviors, such as saving functionals of the solution, are handled\n# via the `SavingCallback` in the [Callback Library](http://docs.juliadiffeq.org/latest/feat\n# ures/callback_library.html#SavingCallback-1) which will be addressed later in the\n# tutorial.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# #### Choosing Solver Algorithms\n#\n# There is no best algorithm for numerically solving a differential equation. When you call\n# `solve(prob)`, DifferentialEquations.jl makes a guess at a good algorithm for your\n# problem, given the properties that you ask for (the tolerances, the saving information,\n# etc.). However, in many cases you may want more direct control. A later notebook will help\n# introduce the various *algorithms* in DifferentialEquations.jl, but for now let's\n# introduce the *syntax*.\n#\n# The most crucial determining factor in choosing a numerical method is the stiffness of the\n# model. Stiffness is roughly characterized by a Jacobian `f` with large eigenvalues. That's\n# quite mathematical, and we can think of it more intuitively: if you have big numbers in\n# `f` (like parameters of order `1e5`), then it's probably stiff. Or, as the creator of the\n# MATLAB ODE Suite, Lawrence Shampine, likes to define it, if the standard algorithms are\n# slow, then it's stiff. We will go into more depth about diagnosing stiffness in a later\n# tutorial, but for now note that if you believe your model may be stiff, you can hint this\n# to the algorithm chooser via `alg_hints = [:stiff]`.\n# ------------------------------------------------------------------------------------------\n\nsol = solve(prob,alg_hints=[:stiff])\n\n# ------------------------------------------------------------------------------------------\n# Stiff algorithms have to solve implicit equations and linear systems at each step so they\n# should only be used when required.\n#\n# If we want to choose an algorithm directly, you can pass the algorithm type after the\n# problem as `solve(prob,alg)`. For example, let's solve this problem using the `Tsit5()`\n# algorithm, and just for show let's change the relative tolerance to `1e-6` at the same\n# time:\n# ------------------------------------------------------------------------------------------\n\nsol = solve(prob,Tsit5(),reltol=1e-6)\n\n# ------------------------------------------------------------------------------------------\n# ### Systems of ODEs: The Lorenz Equation\n#\n# Now let's move to a system of ODEs. The [Lorenz\n# equation](https://en.wikipedia.org/wiki/Lorenz_system) is the famous \"butterfly attractor\"\n# that spawned chaos theory. It is defined by the system of ODEs:\n#\n# $$ \\frac{dx}{dt} = \\sigma (y - x) $$\n# $$ \\frac{dy}{dt} = x (\\rho - z) -y $$\n# $$ \\frac{dz}{dt} = xy - \\beta z $$\n#\n# To define a system of differential equations in DifferentialEquations.jl, we define our\n# `f` as a vector function with a vector initial condition. Thus, for the vector `u =\n# [x,y,z]'`, we have the derivative function:\n# ------------------------------------------------------------------------------------------\n\nfunction lorenz!(du,u,p,t)\n σ,ρ,β = p\n du[1] = σ*(u[2]-u[1])\n du[2] = u[1]*(ρ-u[3]) - u[2]\n du[3] = u[1]*u[2] - β*u[3] \nend\n\n# ------------------------------------------------------------------------------------------\n# Notice here we used the in-place format which writes the output to the preallocated vector\n# `du`. For systems of equations the in-place format is faster. We use the initial condition\n# $u_0 = [1.0,0.0,0.0]$ as follows:\n# ------------------------------------------------------------------------------------------\n\nu0 = [1.0,0.0,0.0]\n\n# ------------------------------------------------------------------------------------------\n# Lastly, for this model we made use of the parameters `p`. We need to set this value in the\n# `ODEProblem` as well. For our model we want to solve using the parameters $\\sigma = 10$,\n# $\\rho = 28$, and $\\beta = 8/3$, and thus we build the parameter collection:\n# ------------------------------------------------------------------------------------------\n\np = (10,28,8/3) # we could also make this an array, or any other type!\n\n# ------------------------------------------------------------------------------------------\n# Now we generate the `ODEProblem` type. In this case, since we have parameters, we add the\n# parameter values to the end of the constructor call. Let's solve this on a time span of\n# `t=0` to `t=100`:\n# ------------------------------------------------------------------------------------------\n\ntspan = (0.0,100.0)\nprob = ODEProblem(lorenz!,u0,tspan,p)\n\n# ------------------------------------------------------------------------------------------\n# Now, just as before, we solve the problem:\n# ------------------------------------------------------------------------------------------\n\nsol = solve(prob)\n\n# ------------------------------------------------------------------------------------------\n# The same solution handling features apply to this case. Thus `sol.t` stores the time\n# points and `sol.u` is an array storing the solution at the corresponding time points.\n#\n# However, there are a few extra features which are good to know when dealing with systems\n# of equations. First of all, `sol` also acts like an array. `sol[i]` returns the solution\n# at the `i`th time point.\n# ------------------------------------------------------------------------------------------\n\nsol.t[10],sol[10]\n\n# ------------------------------------------------------------------------------------------\n# Additionally, the solution acts like a matrix where `sol[j,i]` is the value of the `j`th\n# variable at time `i`:\n# ------------------------------------------------------------------------------------------\n\nsol[2,10]\n\n# ------------------------------------------------------------------------------------------\n# We can get a real matrix by performing a conversion:\n# ------------------------------------------------------------------------------------------\n\nA = convert(Array,sol)\n\n# ------------------------------------------------------------------------------------------\n# This is the same as sol, i.e. `sol[i,j] = A[i,j]`, but now it's a true matrix. Plotting\n# will by default show the time series for each variable:\n# ------------------------------------------------------------------------------------------\n\nplot(sol)\n\n# ------------------------------------------------------------------------------------------\n# If we instead want to plot values against each other, we can use the `vars` command. Let's\n# plot variable `1` against variable `2` against variable `3`:\n# ------------------------------------------------------------------------------------------\n\nplot(sol,vars=(1,2,3))\n\n# ------------------------------------------------------------------------------------------\n# This is the classic Lorenz attractor plot, where the `x` axis is `u[1]`, the `y` axis is\n# `u[2]`, and the `z` axis is `u[3]`. Note that the plot recipe by default uses the\n# interpolation, but we can turn this off:\n# ------------------------------------------------------------------------------------------\n\nplot(sol,vars=(1,2,3),denseplot=false)\n\n# ------------------------------------------------------------------------------------------\n# Yikes! This shows how calculating the continuous solution has saved a lot of computational\n# effort by computing only a sparse solution and filling in the values! Note that in vars,\n# `0=time`, and thus we can plot the time series of a single component like:\n# ------------------------------------------------------------------------------------------\n\nplot(sol,vars=(0,2))\n\n# ------------------------------------------------------------------------------------------\n# ### A DSL for Parameterized Functions\n#\n# In many cases you may be defining a lot of functions with parameters. There exists the\n# domain-specific language (DSL) defined by the `@ode_def` macro for helping with this\n# common problem. For example, we can define the Lotka-Volterra equation:\n#\n# $$ \\frac{dx}{dt} = ax - bxy $$\n# $$ \\frac{dy}{dt} = -cy + dxy $$\n#\n# as follows:\n# ------------------------------------------------------------------------------------------\n\nfunction lotka_volterra!(du,u,p,t)\n du[1] = p[1]*u[1] - p[2]*u[1]*u[2]\n du[2] = -p[3]*u[2] + p[4]*u[1]*u[2]\nend\n\n# ------------------------------------------------------------------------------------------\n# However, that can be hard to follow since there's a lot of \"programming\" getting in the\n# way. Instead, you can use the `@ode_def` macro:\n# ------------------------------------------------------------------------------------------\n\nlv! = @ode_def LotkaVolterra begin\n dx = a*x - b*x*y\n dy = -c*y + d*x*y\nend a b c d\n\n# ------------------------------------------------------------------------------------------\n# We can then use the result just like an ODE function from before:\n# ------------------------------------------------------------------------------------------\n\nu0 = [1.0,1.0]\np = (1.5,1.0,3.0,1.0)\ntspan = (0.0,10.0)\nprob = ODEProblem(lv!,u0,tspan,p)\nsol = solve(prob)\nplot(sol)\n\n# ------------------------------------------------------------------------------------------\n# Not only is the DSL convenient syntax, but it does some magic behind the scenes. For\n# example, further parts of the tutorial will describe how solvers for stiff differential\n# equations have to make use of the Jacobian in calculations. Here, the DSL uses symbolic\n# differentiation to automatically derive that function:\n# ------------------------------------------------------------------------------------------\n\nlv!.Jex\n\n# ------------------------------------------------------------------------------------------\n# The DSL can derive many other functions; this ability is used to speed up the solvers. An\n# extension to DifferentialEquations.jl, [Latexify.jl](https://korsbo.github.io/Latexify.jl/\n# latest/tutorials/parameterizedfunctions.html), allows you to extract these pieces as LaTeX\n# expressions.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# ## Internal Types\n#\n# The last basic user-interface feature to explore is the choice of types.\n# DifferentialEquations.jl respects your input types to determine the internal types that\n# are used. Thus since in the previous cases, when we used `Float64` values for the initial\n# condition, this meant that the internal values would be solved using `Float64`. We made\n# sure that time was specified via `Float64` values, meaning that time steps would utilize\n# 64-bit floats as well. But, by simply changing these types we can change what is used\n# internally.\n#\n# As a quick example, let's say we want to solve an ODE defined by a matrix. To do this, we\n# can simply use a matrix as input.\n# ------------------------------------------------------------------------------------------\n\nA = [1. 0 0 -5\n 4 -2 4 -3\n -4 0 0 1\n 5 -2 2 3]\nu0 = rand(4,2)\ntspan = (0.0,1.0)\nf(u,p,t) = A*u\nprob = ODEProblem(f,u0,tspan)\nsol = solve(prob)\n\n# ------------------------------------------------------------------------------------------\n# There is no real difference from what we did before, but now in this case `u0` is a `4x2`\n# matrix. Because of that, the solution at each time point is matrix:\n# ------------------------------------------------------------------------------------------\n\nsol[3]\n\n# ------------------------------------------------------------------------------------------\n# In DifferentialEquations.jl, you can use any type that defines `+`, `-`, `*`, `/`, and has\n# an appropriate `norm`. For example, if we want arbitrary precision floating point numbers,\n# we can change the input to be a matrix of `BigFloat`:\n# ------------------------------------------------------------------------------------------\n\nbig_u0 = big.(u0)\n\n# ------------------------------------------------------------------------------------------\n# and we can solve the `ODEProblem` with arbitrary precision numbers by using that initial\n# condition:\n# ------------------------------------------------------------------------------------------\n\nprob = ODEProblem(f,big_u0,tspan)\nsol = solve(prob)\n\nsol[1,3]\n\n# ------------------------------------------------------------------------------------------\n# To really make use of this, we would want to change `abstol` and `reltol` to be small!\n# Notice that the type for \"time\" is different than the type for the dependent variables,\n# and this can be used to optimize the algorithm via keeping multiple precisions. We can\n# convert time to be arbitrary precision as well by defining our time span with `BigFloat`\n# variables:\n# \n# ------------------------------------------------------------------------------------------\n\nprob = ODEProblem(f,big_u0,big.(tspan))\nsol = solve(prob)\n\n# ------------------------------------------------------------------------------------------\n# Let's end by showing a more complicated use of types. For small arrays, it's usually\n# faster to do operations on static arrays via the package\n# [StaticArrays.jl](https://github.com/JuliaArrays/StaticArrays.jl). The syntax is similar\n# to that of normal arrays, but for these special arrays we utilize the `@SMatrix` macro to\n# indicate we want to create a static array.\n# ------------------------------------------------------------------------------------------\n\nusing StaticArrays\nA = @SMatrix [ 1.0 0.0 0.0 -5.0\n 4.0 -2.0 4.0 -3.0\n -4.0 0.0 0.0 1.0\n 5.0 -2.0 2.0 3.0]\nu0 = @SMatrix rand(4,2)\ntspan = (0.0,1.0)\nf(u,p,t) = A*u\nprob = ODEProblem(f,u0,tspan)\nsol = solve(prob)\n\nsol[3]\n\n# ------------------------------------------------------------------------------------------\n# ## Conclusion\n#\n# These are the basic controls in DifferentialEquations.jl. All equations are defined via a\n# problem type, and the `solve` command is used with an algorithm choice (or the default) to\n# get a solution. Every solution acts the same, like an array `sol[i]` with `sol.t[i]`, and\n# also like a continuous function `sol(t)` with a nice plot command `plot(sol)`. The Common\n# Solver Options can be used to control the solver for any equation type. Lastly, the types\n# used in the numerical solving are determined by the input types, and this can be used to\n# solve with arbitrary precision and add additional optimizations (this can be used to solve\n# via GPUs for example!). While this was shown on ODEs, these techniques generalize to other\n# types of equations as well.\n# ------------------------------------------------------------------------------------------\n", "meta": {"hexsha": "3623c073acdd1e52d683a579fa4322590072b9ba", "size": 25247, "ext": "jl", "lang": "Julia", "max_stars_repo_path": ".nbexports/introductory-tutorials/broader-topics-and-ecosystem/intro-to-solving-diffeq-in-julia/1.ODEIntroduction.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-solving-diffeq-in-julia/1.ODEIntroduction.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-solving-diffeq-in-julia/1.ODEIntroduction.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.9940594059, "max_line_length": 92, "alphanum_fraction": 0.4825127738, "num_tokens": 4990, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582477806521, "lm_q2_score": 0.9005297761070067, "lm_q1q2_score": 0.8379053575508284}} {"text": "import Pkg; Pkg.add(Pkg.PackageSpec(url=\"https://github.com/JuliaComputing/JuliaAcademyData.jl\"))\nusing JuliaAcademyData; activate(\"Foundations of machine learning\")\n\n# # Minimizing functions - how a computer learns\n\n#-\n\n# In the previous notebooks, we've seen that by changing **parameters** in a function, we could find a \"best fit\" of that function to some data. We use a **loss function** to quantify the \"goodness\" of a set of parameters and we look for those parameters that **optimize**, in fact **minimize**, the loss function. If we teach a machine how to minimize the loss function on its own, we say that machine is able to **learn** how to model our data.\n#\n# In the last notebook, we threw around terms like **derivative**, **gradient**, and **gradient descent** to give you a rough sense of how we minimize a function on a computer. In this notebook, we will step through these concepts more carefully, with the aim of being able to implement them using Julia.\n\n#-\n\n# ## Minimizing a 1D function using calculus\n\n#-\n\n# Let's draw the 1D loss function $L_1$ from a previous notebook again:\n\nσ(x) = 1 / (1 + exp(-x))\nf(x, w) = σ(w * x)\n\nx1 = 2\ny1 = 0.8\n\nL1(w) = (y1 - f(x1, w))^2\n\n#-\n\nusing Plots; gr()\n\n#-\n\nplot(L1, -2, 1.5, xlabel=\"w\", ylabel=\"L1(w)\", leg=false)\n\n# By eye, we can see that the minimum is around $w=0.6$. But how can we get the computer to work this out on its own?\n\n#-\n\n# In the previous notebook, we thought of this function plot as a hill, viewed from the side. We could find the minimum by making the hill sticky, and letting a ball roll down it. The ball will find and settle in the minimum of the function. Now let's see how to teach a computer to do this.\n#\n# We need to find the downhill direction along the hill, which is related to its *slope* (how steep it is). Calculus provides us with tools to calculate that slope!\n\n#-\n\n# Namely, the slope of a curve $L_1(w)$ at $w$ is given by its **derivative** $L_1'(w)$; geometrically, this is the slope of the **tangent line** to the curve at that point, i.e. the straight line which touches the curve at that point.\n\n#-\n\n# Calculus provides us with some rules to calculate an analytical formula for the derivative, and we will see later how to apply these rules, albeit indirectly, for machine learning.\n# To gain understanding, however, we will see here how to get the computer to help us out by calculating the derivatives numerically instead!\n\n#-\n\n# ## Approximating derivatives\n\n#-\n\n# Let's recall that the derivative $L_1'(w)$ of a function is defined as\n#\n# $$L_1'(w) \\simeq \\frac{L_1(w+h) - L_1(w)}{h},$$\n#\n# for a small step size $h$. (Strictly speaking, we must take the limit when $h$ tends to $0$ to obtain the exact value of the derivative.)\n\n#-\n\n# #### Exercise 1\n#\n# Write a function to calculate the derivative of a function at a given point. Note that in Julia, we can easily pass functions as arguments to other functions!\n# The function should take the function, the point $w$ at which to calculate the derivative, and the value of $h$, which should have a default value of 0.001.\n#\n# *Note*: A function input argument can have a *default value* if we set the input argument equal to that default value when we define the function. For example,\n#\n# ```julia\n# f(x, a = 3) = a * x^2\n# ```\n#\n# The function `f` will square the input we give it and multiply by `a`. However, if we choose to call `f(x)` *without* passing it an `a` input, it will assume `a` is `3` and return `3*x^2`.\n\n#-\n\n# #### Solution\n#\n# We could define the `derivative` function as\n\nfunction derivative(f, w, h=0.001)\n return ( f(w + h) - f(w) ) / h\nend\n## Or the short form with:\n## derivative(f, w, h=0.001) = ( f(w + h) - f(w) ) / h\n\n# **Tests**\n\n@assert derivative(x->x^2, 0.2) ≈ 0.401 # check default h works\n@assert derivative(x->x^2, 0.2, 0.5) ≈ .9 # check we can specify our own h\n@assert derivative(x->x^3, 0.2) ≈ 0.120601\n@assert derivative(x->x^3, -0.2) ≈ 0.119401\n\n# #### Exercise 2\n#\n# Write an interactive visualization of the tangent line to the graph of $L_1$, so that we can visualize the tangent at any point on $L_1$. Include the current value of the derivative in the title.\n#\n# *Hint*: Recall that the straight line through the point $(x_0, y_0)$ with slope $m$ is given by\n#\n# $$ \\frac{y - y_0}{x - x_0} = m,$$\n#\n# so\n#\n# $$y = y_0 + m*(x - x_0).$$\n\n#-\n\n# #### Solution\n\nwmin = -2\nwmax = 1\n\nw = 0.5 # Try manipulating w between wmin and wmax (-2 to 1)\nplot(L1, wmin, wmax, label=\"L_1\")\n\nx0 = w\ny0 = L1(w)\n\nscatter!([x0], [y0], label=\"\")\n\nm = derivative(L1, w)\n\nplot!(x->y0 + m*(x - x0), ls=:dash, label=\"tangent line\")\n\nylims!(-0.1, 0.6)\nxlims!(wmin, wmax)\n\ntitle!(\"Derivative = $m\")\nxlabel!(\"w\")\nylabel!(\"L1(w)\")\n\n# #### Exercise 3\n#\n# What is the value of the derivative (slope of the tangent line) at a minimum? Can this happen anywhere else?\n\n#-\n\n# #### Solution\n\n#-\n\n# The derivative is `0` at a minimum. This happens at any minimum, maximum or \"point of inflection\" of a smooth function.\n\n#-\n\n# ## Minimization by gradient descent\n\n#-\n\n# The tangent line at a point is a good approximation of the function near that point. Therefore the derivative tells us in which direction, and how fast, a function grows or shrinks when we move a small distance away from that point.\n#\n# As we saw in the previous notebook, we can think of the function as being a hill, and having a ball that we want to move down the hill. Gravity will automatically pull the ball in the direction *down* the hill; we want to emulate this in the computer!\n\n#-\n\n# #### Exercise 4\n#\n# When the derivative $L_1'(w)$ is positive, that means that $L_1$ increases from left to right at point $w$.\n#\n# If the derivative $L_1'(w)$ is positive (> 0), in which direction should we move $w$ to *decrease* $L_1$?\n\n#-\n\n# #### Solution\n#\n# We should move $w$ left, i.e. decrease it.\n\n#-\n\n# #### Exercise 5\n#\n# If the derivative $L_1'(w)$ is negative (< 0), in which direction should we move $w$ to *decrease* $L_1$?\n\n#-\n\n# We can use this information to tell the computer which way to take a step. This constitutes the numerical algorithm called **gradient descent**; it is called this since we are descending (moving downwards) along the graph of the function by using information about its gradient (slope).\n\n#-\n\n# #### Exercise 6\n#\n# Implement gradient descent by following this prescription for an **iterative (repetitive) algorithm**:\n#\n# 1. Start at an initial guess $w_0$ for $w$.\n#\n# 2. At each step, calculate the derivative, $L_1'(w_n)$ at the current value of $w_n$ using the function that you created above.\n#\n# 3. Modify the value of $w$ by a small multiple (for example, $\\eta=0.01$) of the value of the derivative you just created, via $w_{n+1} = w_n - \\eta L_1'(w_n)$.\n#\n# For this problem, start with $w_0 = -2.0$. Repeat steps 2 and 3 a total of `2000` times.\n#\n# Package this code into a function called `gradient_descent` that takes two inputs, a function and a range for values of $w$, and returns the final value of $w$ and $L_1(w)$.\n#\n# Using `L1` and `-2:0.01:1.5` as your inputs to `gradient_descent`, for what value of $w$ is $L_1$ at a minimum?\n\n#-\n\n# #### Solution\n\nfunction gradient_descent(f, wrange)\n derivative(f, w, h=0.001) = ( f(w + h) - f(w) ) / h\n w = -2.0\n for i in 1:2000\n fderiv = derivative(f, w)\n step = .01 * fderiv\n w = w - step\n end\n return w, f(w)\nend\n\ngradient_descent(L1, -2:0.01:1.5)\n\n# **Tests**\n\n@assert 0.6383 < gradient_descent(L1, -2:0.01:1.5)[1] < 0.6385\n@assert 0.00032 < gradient_descent(L1, -2:0.01:1.5)[2] < 0.00033\n\n# #### Exercise 7\n#\n# Modify your code for gradient descent to return the result once it has found an answer within some *tolerance*, rather than taking a set number of steps. The new prescription for this algorithm is:\n#\n# 1. Start at an initial guess $w_0$ for $w$.\n#\n# 2. At each step, calculate the derivative, $L_1'(w_n)$ at the current value of $w_n$, using the function that you created above.\n#\n# 3. Modify the value of $w$ by a small multiple (for example, $\\eta=0.01$) of the value of the derivative you just created, via $w_{n+1} = w_n - \\eta L_1'(w_n)$.\n#\n# 4. Check how different $w_{n+1}$ is from $w_n$. If you're satisfied that $L_1(w_{n+1})$ is minimized, return $w_{n+1}$ and $L_1(w_{n+1})$. Otherwise, go to step (2) and continue.\n#\n# Edit `gradient_descent` so that it takes three inputs: a function, a range for values of $w$, and a tolerance that tells you how close $w_{n+1}$ must be to $w_n$ before you can stop iterating.\n#\n# Using `L1`, `-2:0.01:1.5`, and `.000001` as your inputs to `gradient_descent`, for what value of $w$ is $L_1$ at a minimum?\n\n#-\n\n# #### Solution\n#\n#\n# Your code should look something like this\n#\n# $L_1$ is at a minimum when `gradient_descent(L1, -2:0.01:1.5, .000001)[1]`, or $w$, is around `0.69216`.\n\nfunction gradient_descent(f, wrange, tol)\n w = -2.0\n while true\n fderiv = derivative(f, w)\n step = .01 * fderiv\n w = w - step\n if abs(step) < tol\n return w, f(w)\n end\n end\nend\n\ngradient_descent(L1, -2:0.01:1.5, .000001)\n\n# **Tests**\n\n@assert 0.69215 < gradient_descent(L1, -2:0.01:1.5, .000001)[1] < 0.69217\n\n# After you've completed this step, you will have found a good approximation to the value $w^*$ where $L_1$ reaches its minimum, and the minimum value $L_1(w^*)$, which in this case is (almost) $0$.\n\n#-\n\n# #### Exercise 8\n#\n# Alter the function `gradient_descent` so that it stores the results `(w, L1(w))` at each step of the algorithm as an array and returns this array. How many steps does the algorithm take for input parameters `(L1, -2:0.01:1.5, .000001)` before terminating? You should count your starting $w_0$ as your first step.\n\n#-\n\n# #### Solution\n\n#-\n\n# Your altered code should look like this, getting the number of steps with `length`:\n\nfunction gradient_descent(f, wrange, tol)\n w = -2.0\n store_w = [(w, f(w))]\n while true\n fderiv = derivative(f, w)\n step = .01 * fderiv\n w = w - step\n push!(store_w, (w, f(w)))\n if abs(step) < tol\n return store_w\n end\n end\nend\n\nlength(gradient_descent(L1, -2:0.01:1.5, .000001))\n\n# **Tests**\n\n@assert length(gradient_descent(L1, -2:0.01:1.5, .000001)) == 4255\n\n# #### Exercise 9\n#\n# Overlay the steps taken in the last exercise with a plot of $L_1(w)$ vs. $w$.\n#\n# Where does our algorithm take the largest steps? (Where does the ball move fastest down the hill?)\n#\n# A) Between w = -2:-1
\n# B) Between w = -1:0
\n# C) Between w = 0:.6\n#\n# *Hint*: It may be easier to see what's going on if you only plot, for example, every 15th step.\n\n#-\n\n# #### Solution\n#\n# B) The following code generates the desired figure:\n\nwsteps = gradient_descent(L1, -2:0.01:1.5, .000001)\nfig1 = plot(L1, -2, 1.5, xlabel=\"w\", ylabel=\"C1(w)\", leg=false)\nfor step in wsteps[1:15:end]\n scatter!([step[1]], [step[2]])\nend\nfig1\n\n# ## Functions of 2 variables and their derivatives\n\n#-\n\n# So far, we have been looking at the minimizing a loss function $L_1(w)$ that depends on a single parameter, $w$. Now let's turn to the cost function $L_2(w, b)$ from a previous notebook, that is a function of *two* parameters, $w$ and $b$, and try to minimize it.\n#\n# As we've seen, we get a **surface**, instead of a curve, when we graph $L_2$ as a function of both of its parameters.\n\n#-\n\n# **Exercise 10**\n#\n# Draw a surface plot of $L_2$, given by\n#\n# $$L_{2}(w, b) = \\sum_i(y_i - g(x_i, w, b))^2$$\n#\n# using the `surface` function from `Plots.jl`. For this plot, use the values of `xs` and `ys` from notebook 5:\n#\n# We can get a nice interactive 3D plot by using the Plotly backend of `Plots.jl` by executing the command\n#\n# plotly()\n\nxs = [2, -3, -1, 1]\nys = [0.8, 0.3, 0.4, 0.4]\n\n# #### Solution\n\n#-\n\n# The following code will generate the desired graphic:\n\nplotly()\nσ(x) = 1 / (1 + exp(-x))\ng(x, w, b) = σ(w*x) + b\n\nxs = [2, -3, -1, 1]\nys = [0.8, 0.3, 0.4, 0.4]\n\nL2(w, b) = sum(abs2, ys .- g.(xs, w, b))\n\nsurface(-2:0.02:2, -2:0.02:2, L2, alpha=0.6, xlabel = \"w\", ylabel = \"b\", zlabel = \"L2(w, b)\")\n\n# ### Finding the minimum\n\n#-\n\n# We can just about see, by rotating the graph, that $L_2$ has a single minimum. We want to find the values of $w$ and $b$ where this minimum value is reached.\n\n#-\n\n# Following what we did for the function $L_1$ above, we expect that we will need to calculate derivatives of $L_2$. Since the function is more complicated, though, the derivatives are too!\n#\n# It turns out that the right concept is that of the [**gradient**](https://en.wikipedia.org/wiki/Gradient) of $L_2$, denoted $\\nabla L_2(w, b)$. This is a **vector** consisting of $2$ numbers if there are $2$ parameters [or, in general, $n$ numbers if there are $n$ parameters].\n#\n# The numbers that form the gradient $\\nabla L_2(w, b)$ are called the **partial derivatives** of $L_2$ with respect to $w$ and $b$, written as\n#\n# $$\\frac{\\partial L_2}{\\partial w} \\quad \\text{and} \\quad \\frac{\\partial L_2}{\\partial b}.$$\n#\n# Although this notation might look complicated, all it means is that we calculate derivatives just like we did before, except that we fix the value of the other variable.\n# For example, to calculate $\\frac{\\partial L_2}{\\partial w}$, the partial derivative of $L_2$ with respect to $w$, we fix the value of $b$ and think of the resulting function as a function of the single variable $w$; then we use the formula for derivatives of functions of a single variable.\n#\n# [Note that $\\frac{\\partial L_2}{\\partial w}$ is itself a function of $w$ and $b$; we could write $\\frac{\\partial L_2}{\\partial w}(w, b)$.]\n\n#-\n\n# #### Exercise 11\n#\n# Write functions that will allow you to calculate the partial derivatives of a function $f$ of two variables.\n#\n# In particular, declare functions called `partial_w` and `partial_b`. Each should take four inputs - a function $f$ of two variables, the first input argument to $f$, the second input argument to $f$, and a step size `h` with default value `0.001`. `partial_w` should return the partial derivative of $f$ with respect to its first input argument and `partial_b` should return the partial derivative of $f$ with respect to its second input argument.\n\n#-\n\n# #### Solution\n#\n# The partial derivatives are\n\npartial_w(f, w, b, h = 0.001) = ( f(w + h, b) - f(w, b) ) / h\npartial_b(f, w, b, h = 0.001) = ( f(w, b + h) - f(w, b) ) / h\n\n# **Tests**\n\n## Test that default parameters work:\n@assert partial_w((x, y) -> 3 * x * y, 0.3, 0.3) ≈ 0.9\n@assert partial_b((x, y) -> 3 * x * y, 0.3, 0.3) ≈ 0.9\n## Test that you can specify your own step sizes:\n@assert partial_w((x, y) -> 3 * x^2 * y^3, 2.3, 10.2, 1) ≈ 17828.2944\n@assert partial_b((x, y) -> 3 * x^2 * y^3, 2.3, 10.2, 1) ≈ 5454.8364\n## Test that x and y are treated separately:\n@assert partial_w((x, y) -> 3 * x * y^2, 0.3, 0.2) ≈ 0.12\n@assert partial_b((x, y) -> 3 * x * y^2, 0.3, 0.2) ≈ 0.3609\n@assert partial_w((x, y) -> 3 * x^2 * y, 0.3, 0.2, 0.1) ≈ 0.42\n@assert partial_b((x, y) -> 3 * x^2 * y, 0.3, 0.2, 0.1) ≈ 0.27\n\n# #### Exercise 12\n#\n# Use `partial_b` from the last exercise to find the partial derivative of $L_2$ with respect to $w$ at b = 0.3, $\\frac{\\partial L_2}{\\partial w}|_{b = 0.3}$ for `w = -2:0.01:1`\n\n#-\n\n# #### Solution\n\nwrange = -2:0.01:1\npartialw = partial_w.(L2, wrange, 0.3 )\n\n# **Tests**\n\n@assert isapprox(partialw[3], -0.212573, rtol=2e-6)\n\n# #### Exercise 13\n#\n# Plot the cross section of the surface of $L_2(w, b)$ at $b = 0.3$. Make this plot interactive to show that the function `partial_w` gives the slope of the tangent to this cross section for any point `w` in the range `-2:0.01:1`.\n#\n# For what value of $w$ in this range is the slope of the cross section closest to -1?\n\n#-\n\n# #### Solution\n\n#-\n\n# The slope is closest to -1.0 at w = -0.55. You can see this by running the following code:\n\nL2_fixedb = L2.(wrange, 0.3)\n\nw = 0.0 # Try manipulating w to pick a value within `wrange`\nplot(wrange, L2_fixedb)\nscatter!([w], [L2(w, 0.3)])\nslope = partial_w(L2, w, 0.3)\ntangent_points = slope .* wrange .- slope * w .+ L2.(w, 0.3)\nplot!(wrange, tangent_points)\nylims!(0.3, 2.0)\ntitle!(\"Slope = $slope @ $(w)\")\n\n# ## ***Optional**: Functions with $n$ inputs\n\n#-\n\n# If a function $f$ takes $n$ input arguments, we can write them as $p_1, \\ldots, p_n$, where $p_i$ means the \"$i$th parameter\". In Julia, we can wrap them up into a single **vector**. Now we can calculate the partial derivative $\\frac{\\partial L_2}{\\partial p_i}$ with respect to the $i$th variable.\n\n#-\n\n# #### Exercise 14\n#\n# For the next exercise, you will need to use the splat command, `...`. You can use this command to \"open up\" a collection and pass all the elements of that collection as inputs to a function.\n#\n# For example, say you have an array, `numbers`,\n#\n# ```julia\n# numbers = [4, 3, 2]\n# ```\n#\n# and you want to use `numbers` to create a $4\\times3\\times3$ randomly populated array via `rand`. `rand(numbers)` will not do what you want. You could index into `numbers` to grab the values you want and pass them to `rand`, as in\n#\n# ```julia\n# rand(numbers[1], numbers[2], numbers[3])\n# ```\n#\n# or you could use a splat:\n#\n# ```julia\n# rand(numbers...)\n# ```\n#\n# Use `...` to pass the contents of `inputs`\n#\n# ```julia\n# inputs = [30, 12, \"cats\"]\n# ```\n#\n# to the function `dreams`\n#\n# ```julia\n# dreams(i, j, perfect_mammal) = \"I wish I had $(i + j) $perfect_mammal.\"\n# ```\n\n#-\n\n# #### Solution\n\ninputs = [30, 12, \"cats\"]\ndreams(i, j, perfect_mammal) = \"I wish I had $(i + j) $perfect_mammal.\"\ndreams(inputs...)\n\n# **Tests**\n\n@assert dreams(inputs...) == \"I wish I had 42 cats.\"\n\n# #### Exercise 15:\n#\n# Write a function, `partial`, to calculate the $i$th partial derivative of a function. This function should have four inputs\n#\n# * a function, $f$, for which you want to compute the partial derivative\n# * an array, *p*, specifying the values of all input arguments to $f$ at the point where you want $\\frac{\\partial f}{\\partial p_i}$ computed\n# * the index, $i$, of the variable with respect to which you want to calculate the partial derivative of $f$\n# * a step size with default value 0.001\n#\n# Hint: you will need to `copy` and modify `p` within `partial`.\n\n#-\n\n# #### Solution\n\nfunction partial(f, p, i, h = 0.001)\n p_next = copy(p)\n p_next[i] += h\n return ( f(p_next...) - f(p...) ) / h\nend\n\n# **Tests**\n\n@assert partial((x, y, z) -> x^2 * y * z, [1.0, 2.0, 1.0], 1, 0.0001) ≈ 4.0002\n@assert partial((x, y, z) -> x^2 * y * z, [1.0, 2.0, 1.0], 1, 1) ≈ 6\n\n@assert partial((w, x, y, z) -> w * x^2 * y^3 * z^4, [1.1, 2.2, 3.3, 4.4], 1) ≈ 65192.53776074038\n@assert partial((w, x, y, z) -> w * x^2 * y^3 * z^4, [1.1, 2.2, 3.3, 4.4], 2) ≈ 65207.35424659506\n@assert partial((w, x, y, z) -> w * x^2 * y^3 * z^4, [1.1, 2.2, 3.3, 4.4], 3) ≈ 65212.29507069802\n@assert partial((w, x, y, z) -> w * x^2 * y^3 * z^4, [1.1, 2.2, 3.3, 4.4], 4) ≈ 65214.7658571339\n\n# ## Gradient descent in 2 dimensions\n\n#-\n\n# It turns out that the gradient vector of the function $L_2(w, b)$ gives the direction in the plane $(w, b)$ in which the function $L_2$ **increases fastest**.\n#\n# In other words, if you start at the position $(w_0, b_0)$ and take a small step of length $\\eta$ to new values $(w', b')$, the value of the function will change to a new value $L_2(w', b')$. How do we get to the minimum of $L_2(w, b)$ as fast as possible? We want to step in the direction where $L_2$ decreases fastest!\n#\n# In multivariable calculus courses, it is shown that $L_2$ will *increase* fastest if you take a step **in the direction of the gradient $\\nabla L_2(w, b)$**! To decrease $L_2$ the fastest, we should take a step in the *opposite* direction, $-\\nabla L_2(w, b)$.\n#\n# Let's now generalize the gradient descent algorithm that we wrote previously to work our 2-dimensional function.\n\n#-\n\n# #### Exercise 16\n#\n# Extend your 1D implementation of `gradient_descent` so that it will minimize the function $L_2$.\n#\n# Requirements:\n#\n# * Your new method for `gradient_descent` will take four input arguments: the function $f$ for which you seek the minimum, the range of values for $f$'s first input argument that you will consider, the range of values for $f$'s second input argument that you will consider, and a tolerance that will specify the maximum allowable step size, $\\sum_i \\eta \\frac{\\partial f}{\\partial p_i}$\n#\n# * Use $\\eta = .01$. For example, for a function $f(w, b)$, update $w$ such that $w_{n+1} = w_n - 0.01 * \\frac{\\partial f}{\\partial w_n}$\n#\n# * Seed `gradient_descent` with the starting coordinates [-2.0, -2.0], i.e. $w_0 = -2.0$ and $b_0 = -2.0$.\n#\n# * Return all steps (their coordinates) taken during gradient descent and the values of the loss function at these coordinates.\n#\n# Once you have done this, execute\n#\n# ```julia\n# gradient_descent(L2, -2:0.02:2, -2:0.02:2, .001)\n# ```\n#\n# How many steps were taken by gradient descent?\n#\n# Hint: Do not count your starting coordinates `[-2.0, -2.0]` as a step.\n\n#-\n\n# #### Solution\n#\n#\n# The new code for `gradient_descent` should look something like\n\nfunction gradient_descent(f, wrange, brange, tol)\n w, b = -2.0, -2\n store_steps = [[w, b]]\n store_C2_vals = [f(w, b)]\n while true\n # Calculate partial derivatives\n fpartial1 = partial(f, [w, b], 1)\n fpartial2 = partial(f, [w, b], 2)\n # Update parameters\n w = w - .01 * fpartial1\n b = b - .01 * fpartial2\n # Store parameters and resulting function\n push!(store_steps, [w, b])\n push!(store_C2_vals, f(w, b))\n\n if abs(w + b) < tol\n return store_steps, store_C2_vals\n end\n end\nend\n\n# **Tests**\n\nsteps, values = gradient_descent(L2, -2:0.02:2, -2:0.02:2, .001 )\n@assert length(values) == 396\n\n# #### Exercise 17\n#\n# Use the `surface` and `scatter!` commands to illustrate the path taken by `gradient_descent` from [-2.0, -2.0] to wherever the algorithm terminates.\n#\n# Where do the scattered points representing the steps of gradient descent appear the most dense?\n#\n# A) Near the starting point at [-2.0, -2.0]
\n# B) Near the point [-1.8, 0] where $C_2$ appears nearly flat
\n# C) Near the minimum of $C_2$\n\n#-\n\n# #### Solution\n#\n# B) The following code will plot the function `C2` with an overlay of the steps taken in gradient descent\n#\n# You can change the frequency with which steps are plotted by changing the iterator in the `for` loop from `1:length(values)` to `1:n:length(values)` for varying values of `n`. This will allow you to see more clearly where steps are densely or sparsely packed.\n\nfig = surface(-2:0.02:2, -2:0.02:2, L2, alpha=0.6, xlabel = \"w\", ylabel = \"b\", zlabel = \"C2(w, b)\")\nfor i in 1:length(values)\n scatter!([steps[i][1]], [steps[i][2]], [values[i]])\nend\nfig\n\n# ## What we have learnt\n\n#-\n\n# To recap, in this notebook, we have seen that the computer can calculate approximate derivatives, and that we can use those inside a relatively simple algorithm, gradient descent, to minimize functions of 1 and 2 variables!\n#\n# Now that we've used gradient descent to **learn** the best values of `b` and `w` for a cost function, we can imagine how we could do our classification of apples vs. bananas by allowing the machine to choose our parameters! To do this, we need to define a loss function for apple vs. banana classification, using images that have already been categorised as apples or bananas.\n\n", "meta": {"hexsha": "3c19d7c4a370ed67c9e10cd6dac7af29be846af1", "size": 23353, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Courses/Foundations of machine learning/0900.What-is-learning-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/0900.What-is-learning-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/0900.What-is-learning-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": 35.9830508475, "max_line_length": 449, "alphanum_fraction": 0.6626129405, "num_tokens": 7444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119663, "lm_q2_score": 0.9099070115349837, "lm_q1q2_score": 0.837832988175719}} {"text": "# # Investment Science - Module 1\n#\n# \\tableofcontents\n#\n# ## Problem 4\n# The IRR is generally calculated using an iterative procedure.\n# Suppose that we define $f(\\lambda) = -a_{1} + a_{2}\\lambda^{2} + \\ldots + a_{n}\\lambda^{n}$,\n# where all $a_{i}$'s are positive and $n > 1$.\n# Here is an iterative technique that generates a sequence\n# $\\lambda_{0}, \\lambda_{1}, \\lambda_{2}, \\ldots \\lambda_{k}, \\ldots$\n# of estimates that converges to the root $\\overline{\\lambda} > 0$, solving $f(\\overline{\\lambda}) = 0$.\n# Start with any $\\lambda_{0} > 0$ close to the solution.\n# Assuming $\\lambda_{k}$ has been calculated, evaluate\n#\n# $$\n# f'(\\lambda_{k}) = a_{1} + 2a_{2}\\lambda_{k} + 3a_{3}\\lambda_{k}^{2} + \\ldots + na_{n}\\lambda_{k}^{n-1}\n# $$\n#\n# and define\n#\n# $$\n# \\lambda_{k+1} = \\lambda_{k} - \\frac{f(\\lambda_{k})}{f'(\\lambda_{k})}\n# $$\n#\n# This is Newton's method.\n# It is based on approximating the function $f$ by a line tangent to its graph at $\\lambda_{k}$.\n# Try the procedure on $f(\\lambda) = -1 + \\lambda + \\lambda^{2}$.\n# Start with $\\lambda_{0} = 1$ and compute four additional estimates.\n#\n# ### Solution\n#\n# We know\n#\n# $$\n# \\begin{aligned}\n# \\lambda_{0} &= 1 \\\\\n# \\lambda_{k+1} &= \\lambda_{k} - \\frac{f(\\lambda_{k})}{f'(\\lambda_{k})} \\\\\n# f(\\lambda) &= -1 + \\lambda + \\lambda^{2} \\\\\n# f'(\\lambda) &= 1 + 2\\lambda \\\\\n# \\end{aligned}\n# $$\n#\n# Using all these equations we can compute four additional estimates.\n\n## define function f\nf(λ) = -1 + λ + λ^2\n## define derivative of f\nḟ(λ) = 1 + 2*λ\n## define function to calculate the next λ\nnext(λ) = λ - f(λ)/ḟ(λ)\n## create a list of λs starting with 1\nλs = [1.0]\n## calculate next four\nfor n ∈ 1:4\n push!(λs, next(λs[n]))\nend\n## display results\n@show λs\n\n# ## Problem 5\n#\n# Suppose that you have the opportunity to plant trees that alter can be sold for lumber. This project requires an initial outlay of money in order to purchase and plant the seedlings. No other cash flow occurs until trees are harvested. However, you have a choice as to when to harvest. If you harvest after 1 year, you get your return quickly; but if you wait, the trees will have additional growth and the revenue generated from the sale of the trees will be greater. Assume that the case flow streams associated with these alternatives are:\n#\n# - Wait $1$ year: $(-1, 2)$\n# - Wait $2$ year: $(-1, ,0, 3)$\n# - Wait $3$ year: $(-1, 0, 0, 4)$\n# - $\\vdots$\n# - Wait $n$ year: $(-1, 0, 0, \\ldots, n+1)$\n#\n# The prevailing interest rate is 10%. When is the best time to cut the trees?\n#\n# ### Solution\n#\n# Let’s first define a function for calculating the Net Present Value, say on a cash flow stream that looks like $(x_{0}, \\ldots, x_{n})$ where $r$ is the prevailing interest rate and $k$ is the number of years waited to harvest:\n#\n# $$\n# NPV = -x_{0} + \\frac{x_{k}}{(1+r)^{k}}\n# $$\n#\n# We can create a function to calculate the **_NPV_** given a _cash flow stream_ and _interest rate_. Let's create a table of the first several values to determine the optimal time to harvest.\n\n## define function to calculate net present value\nfunction net_present_value(investment, revenue, year, rate)\n -investment + revenue/(1+rate)^year\nend\n## define empty array for values\nvalues = []\n## populate some values\nfor i ∈ 1:20\n append!(values, net_present_value(1, i+1, i, 0.10))\nend\n## display some values\n@show values\n\n# To make reading easier, we can create a table or `dataframe`.\n\nusing DataFrames\ndf = DataFrame(Dict(:year => 1:20, :revenue => values))\nshow(df)\n\n# A quick glance reveals the maximum revenue.\n\nmaximum(values)\n#+\nusing PyPlot;\nfigure(figsize=(8, 6));\nplot(df.year, df.revenue);\n\nxlabel(\"Year\", fontsize=14);\nylabel(\"Revenue\", fontsize=14);\n\nplt.savefig(joinpath(@OUTPUT, \"invsci-01-time-to-harvest.svg\")); # hide\n\n# \\figalt{Time to Harvest}{invsci-01-time-to-harvest.svg}\n#\n# We can see that the graph levels off at the top, and upon inspection of the table we confirm that **years 9 and 10** will yield optimal revenue.\n", "meta": {"hexsha": "cf68a568156495ef3f7997535fcdec83b6c4ae12", "size": 3976, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "_literate/invsci-01.jl", "max_stars_repo_name": "jvaverka/lvaverka.github.io", "max_stars_repo_head_hexsha": "1cb38637671e50439fb873b766e023aa450f3a42", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "_literate/invsci-01.jl", "max_issues_repo_name": "jvaverka/lvaverka.github.io", "max_issues_repo_head_hexsha": "1cb38637671e50439fb873b766e023aa450f3a42", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2022-02-09T17:10:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-11T17:26:04.000Z", "max_forks_repo_path": "_literate/invsci-01.jl", "max_forks_repo_name": "jvaverka/XranklinTest", "max_forks_repo_head_hexsha": "1cb38637671e50439fb873b766e023aa450f3a42", "max_forks_repo_licenses": ["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.9829059829, "max_line_length": 544, "alphanum_fraction": 0.6680080483, "num_tokens": 1249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070133672955, "lm_q2_score": 0.9207896693699845, "lm_q1q2_score": 0.8378329779959022}} {"text": "# Question 1\nimport Pkg; Pkg.add(\"Distributions\"); Pkg.add(\"QuantEcon\")\nusing Distributions, QuantEcon\n\nfunction profit_max_q(a, c, mu, sigma, method, n)\n b = rand(LogNormal(mu, sigma), n)\n if method == \"mc\"\n q = Float64((a-c)/(2*mean(b)))\n return q\n elseif method == \"quad\"\n nodes_weights = qnwlogn(n, mu, sigma) #http://quantecon.github.io/QuantEcon.jl/latest/api/QuantEcon.html\n nodes = nodes_weights[1]\n weights = nodes_weights[2]\n mean_b = sum(nodes .* weights)\n q = Float64((a-c)/(2*mean_b))\n end\n return q\n end\n\nprofit_max_q(3,1,1,1,\"mc\",10)\n\n# we dont have to worry about code_warntype\n@code_warntype profit_max_q(3,1,1,1,\"mc\",10)\n\n\n# Question 2\nusing Distributions\nfunction estimate_pi(lower,upper,num_draws)\n n_land_in_circle = 0\n x = rand(Uniform(lower, upper), num_draws)\n y = rand(Uniform(lower, upper), num_draws)\n for i in 1:num_draws\n r_sq = x[i]^2 + y[i]^2\n if r_sq < 1\n n_land_in_circle += 1\n end\n end\n return n_land_in_circle / num_draws * 4\n end\n\nestimate_pi(0,1,1000000)\n", "meta": {"hexsha": "0f48ab5ec0fe5e52717894febc1d282e8920333d", "size": 1177, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "hw1_jh2737.jl", "max_stars_repo_name": "jh2737/AEM7130_test", "max_stars_repo_head_hexsha": "db2f7ef1f6030c012ddc983545a891516bb0264b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hw1_jh2737.jl", "max_issues_repo_name": "jh2737/AEM7130_test", "max_issues_repo_head_hexsha": "db2f7ef1f6030c012ddc983545a891516bb0264b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-02-24T20:52:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-24T20:52:44.000Z", "max_forks_repo_path": "hw1_jh2737.jl", "max_forks_repo_name": "jh2737/AEM7130_test", "max_forks_repo_head_hexsha": "db2f7ef1f6030c012ddc983545a891516bb0264b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0238095238, "max_line_length": 116, "alphanum_fraction": 0.5964316058, "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850110816423, "lm_q2_score": 0.8947894604912848, "lm_q1q2_score": 0.8377779599318194}} {"text": "\"\"\"\n jacobi(x, p::Integer, α, β)\n\nEvaluate the Legendre polynomial with parameters `α`, `β` of degree `p` at `x`\nusing the three term recursion [Karniadakis and Sherwin, Spectral/hp Element\nMethods for CFD, Appendix A].\n\"\"\"\nfunction jacobi(x, p::Integer, α, β)\n T = typeof( (2+α+β)*x / 2 )\n a = one(T)\n b = ((2+α+β)*x + α - β) / 2\n\n if p <= 0\n return a\n elseif p == 1\n return b\n end\n\n for n in 2:p\n a1 = 2n*(n+α+β)*(2n-2+α+β)\n a2 = (2n-1+α+β)*(α+β)*(α-β)\n a3 = (2n-2+α+β)*(2n-1+α+β)*(2n+α+β)\n a4 = 2*(n-1+α)*(n-1+β)*(2n+α+β)\n a, b = b, ( (a2+a3*x)*b - a4*a ) / a1\n end\n\n b\nend\n\n\"\"\"\n jacobi_and_derivative(x, p::Integer, α, β)\n\nEvaluate the Jacobi polynomial with parameters `α`, `β` of degree `p` and its\nderivative at `x` using the three term recursion [Karniadakis and Sherwin,\nSpectral/hp Element Methods for CFD, Appendix A].\n\"\"\"\nfunction jacobi_and_derivative(x, p::Integer, α, β)\n T = typeof( (2+α+β)*x / 2 )\n # Coefficients for the polynomial...\n a = one(T)\n b = ((2+α+β)*x + α - β) / 2\n # ... and for the derivative. The derivative is computed via eq. (A.1.8)\n # of Karniadakis and Sherwin as Jacobi polynomial with parameters α+1, β+1.\n aa = one(T)\n bb = ((4+α+β)*x + α - β) / 2\n\n if p <= 0\n return a, zero(T)\n elseif p == 1\n return b, (2+α+β)/2\n end\n\n for n in 2:p\n a1 = 2n*(n+α+β)*(2n-2+α+β)\n a2 = (2n-1+α+β)*(α+β)*(α-β)\n a3 = (2n-2+α+β)*(2n-1+α+β)*(2n+α+β)\n a4 = 2*(n-1+α)*(n-1+β)*(2n+α+β)\n a, b = b, ( (a2+a3*x)*b - a4*a ) / a1\n\n b1 = 2n*(n+2+α+β)*(2n+α+β)\n b2 = (2n+1+α+β)*(α+β+2)*(α-β)\n b3 = (2n+α+β)*(2n+1+α+β)*(2n+2+α+β)\n b4 = 2*(n+α)*(n+β)*(2n+2+α+β)\n aa, bb = bb, ( (b2+b3*x)*bb - b4*aa ) / b1\n end\n\n b, (α+β+p+1)*aa/2\nend\n\n\n\"\"\"\n gauss_jacobi_nodes_and_weights(p, α, β, T=Float64::Type, tol=4*eps(T), maxit=100)\n\nCompute the Gauss-Jacobi nodes and weights for polynomials of degree `p` with\nparameters `α`, `β` using the scalar type `T`, tolerance `tol` and maximal number\nof Newton iterations `maxit` [Karniadakis and Sherwin, Spectral/hp Element\nMethods for CFD, Appendix B].\n\"\"\"\nfunction gauss_jacobi_nodes_and_weights(p, α, β, T=Float64::Type, tol=4*eps(T), maxit=1000)\n T = promote_type(typeof(α), typeof(β), T)\n nodes = Vector{T}(undef, p+1)\n weights = Vector{T}(undef, p+1)\n for j in 0:p\n x = -cospi(T(2j+1)/(2p+2))\n if j > 0\n x = (x + nodes[j]) / 2\n end\n for k in 1:maxit\n s = zero(T)\n for l in 1:j\n s += 1 / (x - nodes[l])\n end\n pol, der = jacobi_and_derivative(x, p+1, α, β)\n Δ = -pol / (der - s*pol)\n x = x + Δ\n abs(Δ) <= tol*abs(x) && break\n end\n pol, der = jacobi_and_derivative(x, p+1, α, β)\n nodes[j+1] = x\n weights[j+1] = 2^(α+β+1) * gamma(α+p+2) * gamma(β+p+2) /\n (gamma(p+2) * gamma(α+β+p+2) * (1-x^2) * der^2)\n end\n\n return nodes, weights\nend\n\n\n\n\"\"\"\n jacobi_vandermonde(nodes, α, β)\n\nComputes the Vandermonde matrix with respect to the Jacobi polynomials with\nparameters `α`, `β` and the nodal basis on `nodes`.\nThe Vandermonde matrix `V` is the transformation matrix from the modal Jacobi\nbasis to the nodal Lagrange basis associated with `nodes`.\n\"\"\"\nfunction jacobi_vandermonde(nodes::AbstractVector, α, β)\n T = eltype(nodes)\n pp1 = length(nodes)\n V = Array{T}(undef, pp1, pp1)\n for j in 1:pp1, (i,x) in enumerate(nodes)\n V[i, j] = jacobi(x, j-1, α, β)\n end\n V\nend\n\njacobi_vandermonde(basis::NodalBasis{Line}, α, β) = jacobi_vandermonde(basis.nodes, α, β)\n", "meta": {"hexsha": "8a5f132ba41e292fe9cfce401918facdc04fd336", "size": 3734, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/jacobi.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/PolynomialBases.jl-c74db56a-226d-5e98-8bb0-a6049094aeea", "max_stars_repo_head_hexsha": "7a1ac70cbdae378323a4dd611c8dc1386222c71f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-09-11T18:12:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T21:08:56.000Z", "max_issues_repo_path": "src/jacobi.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/PolynomialBases.jl-c74db56a-226d-5e98-8bb0-a6049094aeea", "max_issues_repo_head_hexsha": "7a1ac70cbdae378323a4dd611c8dc1386222c71f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2018-02-15T06:32:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-11T15:59:07.000Z", "max_forks_repo_path": "src/jacobi.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/PolynomialBases.jl-c74db56a-226d-5e98-8bb0-a6049094aeea", "max_forks_repo_head_hexsha": "7a1ac70cbdae378323a4dd611c8dc1386222c71f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-02-26T18:34:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:01:42.000Z", "avg_line_length": 29.171875, "max_line_length": 91, "alphanum_fraction": 0.5431173005, "num_tokens": 1442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362849986365571, "lm_q2_score": 0.8947894696095783, "lm_q1q2_score": 0.8377779573334097}} {"text": "function sum_n_below(factor, max)\n # Return the sum of all the natural numbers of factor below max\n max_nb = div(max-1,factor)\n ((factor / 2 * max_nb * (max_nb + 1)))\nend\n\nfunction n_below(n)\n # Return all the natural number of 3 and 5 multipliers\n return sum_n_below(3, n) + sum_n_below(5, n) - sum_n_below(3*5, n)\nend\n\n@assert n_below(10) == 23\nprintln(n_below(1000))\n", "meta": {"hexsha": "962fb35ac990fb335d90ed4a8bf54a1852a7568a", "size": 385, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "1.jl", "max_stars_repo_name": "ddugue/project-euler", "max_stars_repo_head_hexsha": "ab373d896ac5051bb53a706cccfdfa3987ca9272", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "1.jl", "max_issues_repo_name": "ddugue/project-euler", "max_issues_repo_head_hexsha": "ab373d896ac5051bb53a706cccfdfa3987ca9272", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1.jl", "max_forks_repo_name": "ddugue/project-euler", "max_forks_repo_head_hexsha": "ab373d896ac5051bb53a706cccfdfa3987ca9272", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5, "max_line_length": 70, "alphanum_fraction": 0.6831168831, "num_tokens": 124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9724147177732101, "lm_q2_score": 0.8615382058759128, "lm_q1q2_score": 0.8377724313176635}} {"text": "\"\"\"\n newton(f::Function, x0::Real; niters=10^2, tol=1e-8)\n\nCompute roots of scalar `f` by Newton's method\n\n\"\"\"\n\nfunction newton(f::Function, x0::Real; niters=10^2, tol=1e-8)\n x = xnew = x0\n for it in 1:niters\n df = ForwardDiff.derivative(f, x)\n xnew = x - f(x)/df\n abs(x - xnew) < tol && return xnew\n x, xnew = xnew, x\n end\n xnew\nend", "meta": {"hexsha": "9b8fe5ca703fd1507ee21114c0e79800e646f2b6", "size": 376, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/newton.jl", "max_stars_repo_name": "stecrotti/JuliaUtils.jl", "max_stars_repo_head_hexsha": "51e09a622a0ae96de6b8cc162ef985fc9b11c915", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/newton.jl", "max_issues_repo_name": "stecrotti/JuliaUtils.jl", "max_issues_repo_head_hexsha": "51e09a622a0ae96de6b8cc162ef985fc9b11c915", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/newton.jl", "max_forks_repo_name": "stecrotti/JuliaUtils.jl", "max_forks_repo_head_hexsha": "51e09a622a0ae96de6b8cc162ef985fc9b11c915", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.1176470588, "max_line_length": 61, "alphanum_fraction": 0.5638297872, "num_tokens": 140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.951142221377825, "lm_q2_score": 0.8807970779778825, "lm_q1q2_score": 0.8377632893309805}} {"text": "\"\"\"\nComputes entropy of a sequence.\n\"\"\"\nfunction entropy(X :: AbstractVector)\n counts = Dict{eltype(X), Int}()\n n = length(X)\n for i = 1:length(X)\n counts[X[i]] = get(counts, X[i], 0) + 1\n end\n sum(kv -> log2(n / kv[2]) * kv[2], counts) / n\nend\n\n\"\"\"\nComputes conditional entropy `H(Y | X)`.\n\"\"\"\nfunction conditional_entropy(X :: AbstractVector, Y :: AbstractVector)\n cnts_for_pref = Dict{eltype(X), Dict{eltype(Y), Int}}()\n n = length(X)\n for i = 1:length(X)\n if !haskey(cnts_for_pref, X[i])\n cnts_for_pref[X[i]] = Dict{eltype(Y), Int}()\n end\n counts = cnts_for_pref[X[i]]\n counts[Y[i]] = get(counts, Y[i], 0) + 1\n end\n\n # this helper function computes \"unnormalized entropy\" for given counts dict\n # i.e. entropy multiplied by sum of counts\n function _prefix_helper(counts :: Dict{eltype(Y), Int})\n counts_sum = sum(kv -> kv[2], counts)\n sum(kv -> log2(counts_sum / kv[2]) * kv[2], counts)\n end\n\n sum(kv -> _prefix_helper(kv[2]), cnts_for_pref) / n\nend\n", "meta": {"hexsha": "5a757d8bf60278327afe563a8be916a4746bdf88", "size": 994, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/entropy.jl", "max_stars_repo_name": "krcz/ChaosQuantified.jl", "max_stars_repo_head_hexsha": "f6795a42f7d2bd266865f2c436d3065652fb1ba8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/entropy.jl", "max_issues_repo_name": "krcz/ChaosQuantified.jl", "max_issues_repo_head_hexsha": "f6795a42f7d2bd266865f2c436d3065652fb1ba8", "max_issues_repo_licenses": ["MIT"], "max_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": "krcz/ChaosQuantified.jl", "max_forks_repo_head_hexsha": "f6795a42f7d2bd266865f2c436d3065652fb1ba8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6111111111, "max_line_length": 78, "alphanum_fraction": 0.6277665996, "num_tokens": 319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399051935107, "lm_q2_score": 0.8633916099737806, "lm_q1q2_score": 0.8376969938058334}} {"text": "#simple DFT function\nfunction DFT(x)\n N = length(x)\n\n # We want two vectors here for real space (n) and frequency space (k)\n n = 0:N-1\n k = n'\n transform_matrix = exp.(-2im*pi*n*k/N)\n return transform_matrix*x\n\nend\n\n# Implementing the Cooley-Tukey Algorithm\nfunction cooley_tukey(x)\n N = length(x)\n\n if (N > 2)\n x_odd = cooley_tukey(x[1:2:N])\n x_even = cooley_tukey(x[2:2:N])\n else\n x_odd = x[1]\n x_even = x[2]\n end\n n = 0:N-1\n half = div(N,2)\n factor = exp.(-2im*pi*n/N)\n return vcat(x_odd + x_even .* factor[1:half],\n x_odd - x_even .* factor[1:half])\n\nend\n\nfunction bitreverse(a::Array)\n # First, we need to find the necessary number of bits\n digits = convert(Int,ceil(log2(length(a))))\n\n indices = [i for i = 0:length(a)-1]\n\n bit_indices = []\n for i = 1:length(indices)\n push!(bit_indices, bits(indices[i]))\n end\n\n # Now stripping the unnecessary numbers\n for i = 1:length(bit_indices)\n bit_indices[i] = bit_indices[i][end-digits:end]\n end\n\n # Flipping the bits\n for i =1:length(bit_indices)\n bit_indices[i] = reverse(bit_indices[i])\n end\n\n #replacing indices\n for i = 1:length(indices)\n indices[i] = 0\n for j = 1:digits\n indices[i] += 2^(j-1) * parse(string(bit_indices[i][end-j]))\n end\n indices[i] += 1\n end\n\n b = [float(i) for i = 1:length(a)]\n for i = 1:length(indices)\n b[i] = a[indices[i]]\n end\n\n return b\nend\n\nfunction iterative_cooley_tukey(x)\n N = length(x)\n logN = convert(Int,ceil(log2(length(x))))\n bnum = div(N,2)\n stride = 0;\n\n x = bitreverse(x)\n\n z = [Complex(x[i]) for i = 1:length(x)]\n for i = 1:logN\n stride = div(N, bnum)\n for j = 0:bnum-1\n start_index = j*stride + 1\n y = butterfly(z[start_index:start_index + stride - 1])\n for k = 1:length(y)\n z[start_index+k-1] = y[k]\n end\n end\n bnum = div(bnum,2)\n end\n\n return z\nend\n\nfunction butterfly(x)\n N = length(x)\n half = div(N,2)\n n = [i for i = 0:N-1]\n half = div(N,2)\n factor = exp.(-2im*pi*n/N)\n\n y = [0 + 0.0im for i = 1:length(x)]\n\n for i = 1:half\n y[i] = x[i] + x[half+i]*factor[i]\n y[half+i] = x[i] - x[half+i]*factor[i]\n end\n\n return y\nend\n\nfunction approx(x, y)\n val = true\n for i = 1:length(x)\n if (abs(x[i]) - abs(y[i]) > 1e-5)\n val = false\n end\n end\n println(val)\nend\n\nfunction main()\n x = rand(128)\n y = cooley_tukey(x)\n z = iterative_cooley_tukey(x)\n w = fft(x)\n approx(y, w)\n approx(z, w)\nend\n\nmain()\n", "meta": {"hexsha": "03291fb8c44586a334e520d07c0384d666fe69be", "size": 2695, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "chapters/FFT/code/julia/fft.jl", "max_stars_repo_name": "sanstorik/algorithm-archive", "max_stars_repo_head_hexsha": "74d54d09449fcf303c867834d68ea2399573b369", "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/FFT/code/julia/fft.jl", "max_issues_repo_name": "sanstorik/algorithm-archive", "max_issues_repo_head_hexsha": "74d54d09449fcf303c867834d68ea2399573b369", "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": "chapters/FFT/code/julia/fft.jl", "max_forks_repo_name": "sanstorik/algorithm-archive", "max_forks_repo_head_hexsha": "74d54d09449fcf303c867834d68ea2399573b369", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-19T10:04:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-19T10:04:37.000Z", "avg_line_length": 20.572519084, "max_line_length": 73, "alphanum_fraction": 0.5395176252, "num_tokens": 873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768635777511, "lm_q2_score": 0.8872046011730965, "lm_q1q2_score": 0.8376780576873638}} {"text": "\"\"\"\nbarychebinit(n)\n\nGet Chebyshev nodes of first kind and corresponding barycentric Lagrange interpolation weights. \nReference: Berrut, J.P. and Trefethen, L.N., 2004. Barycentric lagrange interpolation. SIAM review, 46(3), pp.501-517.\n\n# Arguments\n- `n`: order of the Chebyshev interpolation\n\n# Returns\n- Chebyshev nodes\n- Barycentric Lagrange interpolation weights\n\"\"\"\nfunction barychebinit(n)\n x = zeros(Float64, n)\n w = similar(x)\n for i in 1:n\n c = (2i - 1)π / (2n)\n x[n - i + 1] = cos(c)\n w[n - i + 1] = (-1)^(i - 1) * sin(c)\n end\n return x, w\nend\n\n\"\"\"\nfunction barycheb(n, x, f, wc, xc)\n\nBarycentric Lagrange interpolation at Chebyshev nodes\nReference: Berrut, J.P. and Trefethen, L.N., 2004. Barycentric lagrange interpolation. SIAM review, 46(3), pp.501-517.\n\n# Arguments\n- `n`: order of the Chebyshev interpolation\n- `x`: coordinate to interpolate\n- `f`: array of size n, function at the Chebyshev nodes\n- `wc`: array of size n, Barycentric Lagrange interpolation weights\n- `xc`: array of size n, coordinates of Chebyshev nodes\n\n# Returns\n- Interpolation result\n\"\"\"\nfunction barycheb(n, x, f, wc, xc)\n for j in 1:n\n if x == xc[j]\n return f[j]\n end \n end\n\n num, den = 0.0, 0.0\n for j in 1:n\n q = wc[j] / (x - xc[j])\n num += q * f[j]\n den += q\n end\n return num / den\nend\n\nfunction barycheb2(n, x, f, wc, xc)\n for j in 1:n\n if x == xc[j]\n return f[j, :]\n end \n end\n\n den = 0.0\n num = zeros(eltype(f), size(f)[2])\n for j in 1:n\n q = wc[j] / (x - xc[j])\n num += q .* f[j, :]\n den += q\n end\n return num ./ den\nend", "meta": {"hexsha": "9f7502c6bb8f65d1df038ef2591b680a63d19946", "size": 1691, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/old/chebyshev.jl", "max_stars_repo_name": "quantumstatistics/CompositeGrids.jl", "max_stars_repo_head_hexsha": "6bf230eb4267749adbcfb1a80ddffd6899e7317d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-08-21T03:44:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T22:58:02.000Z", "max_issues_repo_path": "src/old/chebyshev.jl", "max_issues_repo_name": "quantumstatistics/CompositeGrids.jl", "max_issues_repo_head_hexsha": "6bf230eb4267749adbcfb1a80ddffd6899e7317d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2021-08-16T19:16:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-17T01:55:31.000Z", "max_forks_repo_path": "src/old/chebyshev.jl", "max_forks_repo_name": "quantumstatistics/CompositeGrids.jl", "max_forks_repo_head_hexsha": "6bf230eb4267749adbcfb1a80ddffd6899e7317d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-22T21:04:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T21:04:22.000Z", "avg_line_length": 23.4861111111, "max_line_length": 118, "alphanum_fraction": 0.585452395, "num_tokens": 576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897442783527, "lm_q2_score": 0.8902942239389253, "lm_q1q2_score": 0.8375796752719961}} {"text": "using Polynomials: Polynomial,fit,coeffs\nusing Plots\nusing Distributions: Normal\nusing Random\nusing Statistics: mean, std\n\np = Polynomial([1,2,3])\n@show coeffs(p)\n\nerrstd = 3\nerrNormal = Normal(0,errstd)\n\nx = 0:10\ny = 2 .+ 3 .* x .+rand(errNormal,11)\n\nscatter(x,y,yerror=errstd,label=false)\n\nfit_line = fit(x,y,1)\n@show coeffs(fit_line)\nplot!(x,fit_line.(x),label=false)\n\nb_list = []\nm_list = []\nN = 1000\nfor i in 1:N\n y = 2 .+ 3 .* x .+rand(errNormal,11)\n fit_c = coeffs(fit(x,y,1))\n push!(b_list,fit_c[1])\n push!(m_list,fit_c[2])\nend\n\n@show mean(b_list)\n@show mean(m_list)\n@show std(b_list)\n@show std(m_list)\n\nhistogram(b_list,bins=30)\nhistogram(m_list,bins=30)\n\n", "meta": {"hexsha": "9718b87f5bae9ce257b1e47293895de04d05d8da", "size": 677, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "least-squares.jl", "max_stars_repo_name": "hstrey/BME-502-2022", "max_stars_repo_head_hexsha": "01ae3787874a13adbed69cb16913f73594107f33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "least-squares.jl", "max_issues_repo_name": "hstrey/BME-502-2022", "max_issues_repo_head_hexsha": "01ae3787874a13adbed69cb16913f73594107f33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "least-squares.jl", "max_forks_repo_name": "hstrey/BME-502-2022", "max_forks_repo_head_hexsha": "01ae3787874a13adbed69cb16913f73594107f33", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-02-15T18:19:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T18:26:08.000Z", "avg_line_length": 16.925, "max_line_length": 40, "alphanum_fraction": 0.6765140325, "num_tokens": 237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799441350253, "lm_q2_score": 0.8688267728417087, "lm_q1q2_score": 0.8373578185923963}} {"text": "#=~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~=#\r\n# Problem set 7 solutions\r\n# Written by Tyler Ransom\r\n# Commented by Giuseppe Grasso\r\n#=~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~=#\r\n\r\nusing Random\r\nusing LinearAlgebra\r\nusing Statistics\r\nusing Distributions\r\nusing Optim\r\nusing DataFrames\r\nusing CSV\r\nusing HTTP\r\nusing GLM\r\nusing FreqTables\r\nusing ForwardDiff\r\nusing LineSearches\r\nusing SMM\r\ncd(\"/Users/peppegrass/Documents/GitHub/fall-2020/ProblemSets/PS6-ccp/\") # GG: sets working directory\r\npwd() ## GG: prints working directory\r\nreaddir() # GG: equivalent to -ls- to see elements of working directory\r\n\r\nfunction allwrap()\r\n\r\n #=\r\n GG: In this problem set, we will practice estimating models by\r\n Generalized Method of Moments (GMM) and Simulated Method of Moments (SMM).\r\n =#\r\n\r\n #:::::::::::::::::::::::::::::::::::::::::::::::::::\r\n # Question 1 - GMM for simple regression model\r\n # data & model are SAME AS PS2, QUESTION 2\r\n #\r\n # 1. Estimate the linear regression model from Question 2 of Problem Set 2 by GMM.\r\n # Write down the moment function as in slide #8 of the Lecture 9 slide deck and use Optim for estimation.\r\n # Use the N × N Identity matrix as your weighting matrix. Check your answer using the closed-form matrix formula for the OLS estimator.\r\n #:::::::::::::::::::::::::::::::::::::::::::::::::::\r\n url = \"https://raw.githubusercontent.com/OU-PhD-Econometrics/fall-2020/master/ProblemSets/PS1-julia-intro/nlsw88.csv\"\r\n df = CSV.read(HTTP.get(url).body)\r\n X = [ones(size(df,1),1) df.age df.race.==1 df.collgrad.==1]\r\n y = log.(df.wage)\r\n\r\n function ols_gmm(β, X, y) # GG: GMM function\r\n K = size(X,2) # GG: don't really needed for GMM, unless for computing RMSE in step below\r\n N = size(y,1) # GG: don't really needed for GMM, unless for computing RMSE in step below\r\n ŷ = X*β\r\n g = y .- ŷ # GG: force y and y_hat to be as close as possible\r\n J = g'*I*g # GG: GMM objective function\r\n return J\r\n end\r\n\r\n # we can also estimate the RMSE of the regression by ADDING ANOTHER MOMENT (and assuming homoskedasticity)\r\n function ols_gmm_with_σ(θ, X, y)\r\n K = size(X,2)\r\n N = size(y,1)\r\n β = θ[1:end-1]\r\n σ = θ[end]\r\n g = y .- X*β\r\n g = vcat(g,( (N-1)/(N-K) )*var(g) .- σ^2) # this builds on the assumption that MSE: SSR/(N-K) = σ² # GG: performing DOFs corrections\r\n J = g'*I*g\r\n return J\r\n end\r\n\r\n β_hat_gmm = optimize(b -> ols_gmm(b, X, y), rand(size(X,2)), LBFGS(), Optim.Options(g_tol=1e-6, iterations=100_000, show_trace=true))\r\n println(β_hat_gmm.minimizer)\r\n println(\"ans: \",X\\y) # GG: X\\y gives the least squares; cool uh!?\r\n β_hat_gmm = optimize(b -> ols_gmm_with_σ(b, X, y), rand(size(X,2)+1), LBFGS(), Optim.Options(g_tol=1e-6, iterations=100_000, show_trace=true))\r\n println(β_hat_gmm.minimizer)\r\n println(\"ans: \",vcat(X\\y,sqrt( sum( (y .- X*β_hat_gmm.minimizer[1:end-1]).^2 )/( size(y,1)-size(X,2) ) )))\r\n\r\n # GG: of course ols_gmm(b, X, y) and ols_gmm_with_σ(b, X, y) yield same results but latter with MSE\r\n\r\n #:::::::::::::::::::::::::::::::::::::::::::::::::::\r\n # Question 2 - GMM for multinomial logit model\r\n # data & model are SAME AS PS2, QUESTION 5\r\n #\r\n # 2. Estimate the multinomial logit model from Question 5 of Problem Set 2 by the following means:\r\n # (a) Maximum likelihood (i.e. re-run your code [or mine] from Question 5 of Problem Set 2)\r\n # (b) GMM with the MLE estimates as starting values. Your g object should be a vector of dimension N ×J where\r\n # N is the number of rows of the X matrix and J is the dimension of the choice set. Each element, g should equal d − P,\r\n # where d and P are “stacked” vectors of dimension N×J\r\n # (c) GMM with random starting values\r\n # Compare your estimates from part (b) and (c). Is the objective function globally concave?\r\n #:::::::::::::::::::::::::::::::::::::::::::::::::::\r\n df = dropmissing(df, :occupation)\r\n df[df.occupation.==8 ,:occupation] .= 7\r\n df[df.occupation.==9 ,:occupation] .= 7\r\n df[df.occupation.==10,:occupation] .= 7\r\n df[df.occupation.==11,:occupation] .= 7\r\n df[df.occupation.==12,:occupation] .= 7\r\n df[df.occupation.==13,:occupation] .= 7\r\n\r\n #df = @transform(df, white = race.==1)\r\n df[:,:white] = df.race .== 1\r\n X = [ones(size(df,1),1) df.age df.white df.collgrad]\r\n y = df.occupation\r\n\r\n # get starting values for mlogit from series of binary logits\r\n svals = zeros(size(X,2),7)\r\n for j=1:7\r\n tempname = Symbol(string(\"occ\",j))\r\n df[:,tempname] = df.occupation.==j\r\n end\r\n # GG: this is to derive some \"reasonable starting values\" for a multinomial logit model\r\n # GG: what do we mean for \"reasonable starting values\". You don't wanna have neither a vector of 0 nor a vector of random numbers\r\n # GG: So what starting values for a Multinomial logit. Estimate a bunch of binary logits and then...\r\n svals[:,1] = coef(lm(@formula(occ1 ~ age + white + collgrad), df))\r\n svals[:,2] = coef(lm(@formula(occ2 ~ age + white + collgrad), df))\r\n svals[:,3] = coef(lm(@formula(occ3 ~ age + white + collgrad), df))\r\n svals[:,4] = coef(lm(@formula(occ4 ~ age + white + collgrad), df))\r\n svals[:,5] = coef(lm(@formula(occ5 ~ age + white + collgrad), df))\r\n svals[:,6] = coef(lm(@formula(occ6 ~ age + white + collgrad), df))\r\n svals[:,7] = coef(lm(@formula(occ7 ~ age + white + collgrad), df))\r\n svals = svals[:,1:6] .- svals[:,7] # GG: ... impose the identification normalization (i.e. you subtract for the first 6 estimates the one of the 7th)\r\n svals = svals[:] # GG: then vectorize it and use it as a starting value\r\n\r\n function mlogit_mle(α, X, y)\r\n\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 bigα = [reshape(α,K,J-1) zeros(K)]\r\n\r\n P = exp.(X*bigα) ./ sum.(eachrow(exp.(X*bigα)))\r\n\r\n loglike = -sum( bigY.*log.(P) ) # GG: MLE objective function\r\n\r\n return loglike\r\n end\r\n\r\n α_zero = zeros(6*size(X,2))\r\n α_rand = rand(6*size(X,2))\r\n # α_true = [-.5120867,-.6950393,.3165616,-1.646016,-2.300697,-.7656569]\r\n α_true = [.1910213,-.0335262,.5963968,.4165052,-.1698368,-.0359784,1.30684,-.430997,.6894727,-.0104578,.5231634,-1.492475,-2.26748,-.0053001,1.391402,-.9849661,-1.398468,-.0142969,-.0176531,-1.495123,.2454891,-.0067267,-.5382892,-3.78975]\r\n α_start = α_true.*rand(size(α_true))\r\n println(size(α_true))\r\n α_hat_optim = optimize(a -> mlogit_mle(a, X, y), svals, LBFGS(), Optim.Options(g_tol = 1e-5, iterations=100_000, show_trace=true, show_every=50))\r\n α_hat_mle = α_hat_optim.minimizer\r\n println(\"mlogit MLE estimates: \",α_hat_mle)\r\n\r\n function mlogit_gmm(α, X, y)\r\n K = size(X,2)\r\n J = length(unique(y))\r\n N = length(y)\r\n bigY = zeros(N,J)\r\n for j=1:J\r\n bigY[:,j] = y.==j\r\n end\r\n bigα = [reshape(α,K,J-1) zeros(K)]\r\n\r\n P = exp.(X*bigα) ./ sum.(eachrow(exp.(X*bigα)))\r\n\r\n g = zeros((J-1)*K)\r\n for j=1:(J-1)\r\n for k = 1:K\r\n g[(j-1)*K+k] = mean( (bigY[:,j] .- P[:,j]) .* X[:,k] ) # GG: GMM (exactly-identified) objective function\r\n # GG: (j-1)*K moment conditions; (j-1) equations and K betas; same number of elements as number non-zero elements in bigαlpha\r\n end\r\n end\r\n J = N*g⋅g #GG: exactly identified; no weighting matrix\r\n return J\r\n end\r\n\r\n function mlogit_gmm_overid(α, X, y)\r\n K = size(X,2)\r\n J = length(unique(y))\r\n N = length(y)\r\n bigY = zeros(N,J)\r\n for j=1:J\r\n bigY[:,j] = y.==j\r\n end\r\n bigα = [reshape(α,K,J-1) zeros(K)]\r\n\r\n P = exp.(X*bigα) ./ sum.(eachrow(exp.(X*bigα))) # GG: same as before P = exp.(X*bigα) ./ sum.(eachrow(exp.(X*bigα)))\r\n\r\n g = bigY[:] .- P[:] # GG: now in over-identified case; we vectorize big Y and P with the [:] operator and subtract the two\r\n # GG: this will be equivalent to NONLINEAR LEAST SQUARES\r\n\r\n J = g'*I*g # GG: now we have weighting matrix\r\n return J\r\n end\r\n #α_zero = zeros(6*size(X,2))\r\n #α_rand = rand(6*size(X,2))\r\n α_true = [.1910213,-.0335262,.5963968,.4165052,-.1698368,-.0359784,1.30684,-.430997,.6894727,-.0104578,.5231634,-1.492475,-2.26748,-.0053001,1.391402,-.9849661,-1.398468,-.0142969,-.0176531,-1.495123,.2454891,-.0067267,-.5382892,-3.78975]\r\n #α_start = α_true.*rand(size(α_true))\r\n #println(\"starting values: \",α_rand)\r\n\r\n # GG: here we're playing around with different optimization algorithms, starting values, and later using autodiff\r\n\r\n # LBFGS\r\n α_hat_optim = optimize(a -> mlogit_gmm_overid(a, X, y), α_true .+ .0001*rand(size(α_true)), LBFGS(), Optim.Options(g_tol = 1e-5, iterations=1_000, show_trace=true, show_every=100))\r\n α_hat_gmm = α_hat_optim.minimizer\r\n println(\"LBFGS GMM minimum: \",α_hat_optim.minimum)\r\n println(\"LBFGS GMM estimates: \",α_hat_gmm)\r\n\r\n # use autodiff with LBFGS\r\n td = TwiceDifferentiable(b -> mlogit_gmm_overid(b, X, y), svals; autodiff = :forward)\r\n α_hat_optim_ad = optimize(td, α_true .+ .0001*rand(size(α_true)), LBFGS(), Optim.Options(g_tol = 1e-5, iterations=10_000, show_trace=true, show_every=100))\r\n α_hat_gmm_ad = α_hat_optim_ad.minimizer\r\n println(\"LBFGS GMM autodiff minimum: \",α_hat_optim_ad.minimum)\r\n println(\"LBFGS GMM autodiff estimates: \",α_hat_gmm_ad)\r\n\r\n # use autodiff with Newton\r\n α_hat_optim_ad_newton = optimize(td, α_true .+ .0001*rand(size(α_true)), Newton(linesearch = BackTracking()), Optim.Options(g_tol = 1e-5, iterations=10_000, show_trace=true, show_every=100))\r\n α_hat_gmm_ad_newton = α_hat_optim_ad_newton.minimizer\r\n println(\"Newton GMM autodiff minimum: \",α_hat_optim_ad_newton.minimum)\r\n println(\"Newton GMM autodiff estimates: \",α_hat_gmm_ad_newton)\r\n\r\n # autodiff from bad starting values\r\n α_hat_optim_ad_fr_bad = optimize(td, α_rand.*sign.(α_true), LBFGS(), Optim.Options(g_tol = 1e-10, f_tol = 1e-10, x_tol = 1e-10, iterations=10_000, show_trace=true, show_every=50))\r\n α_hat_gmm_ad_fr_bad = α_hat_optim_ad_fr_bad.minimizer\r\n println(\"LBFGS GMM autodiff minimum: \",α_hat_optim_ad_fr_bad.minimum)\r\n println(\"LBFGS GMM autodiff estimates: \",α_hat_gmm_ad_fr_bad)\r\n\r\n # GG: putting different answers in a DataFrame and comparing them\r\n # GG: found out close answers; the one using bad starting value didn't get close to other solutions; some times GMM tolerance values needed to be played around with\r\n compare = DataFrame(mle = α_hat_mle, gmm = α_hat_gmm, gmm_ad = α_hat_gmm_ad, gmm_ad_newton = α_hat_gmm_ad_newton, gmm_ad_fr_bad = α_hat_gmm_ad_fr_bad)\r\n println(compare)\r\n # GG: objective function globally concave, but couldn't get to global maximum from random starting values, although pretty close\r\n\r\n #:::::::::::::::::::::::::::::::::::::::::::::::::::\r\n # Question 3 - SIMULATE DATA from a logit model\r\n #\r\n # 3. SIMULATE A DATASET FROM A MULTINOMIAL LOGIT MODEL, and then estimate its parameter values and verify that the estimates are close to the\r\n # parameter values you set. That is, for a given sample size N, choice set dimension J and parameter vector β, write a function that outputs\r\n # data X and Y. I will let you choose N, J, β and the number of covariates in X (K), but J should be larger than 2 and K should be larger than 1.\r\n # If you haven’t done this before, you may want to follow these steps:\r\n # (a) Generate X using a random number generator—rand() or randn().\r\n # (b) Set values for β such that conformability with X and J is satisfied\r\n # (c) Generate the N×J matrix of choice probabilities P\r\n # (d) Draw the preference shocks ε as a N×1 vector of U[0,1] random numbers\r\n # (e) Generate Y as follows:\r\n # • Initialize Y as an N ×1 vector of 0s\r\n # • Update Y i = ∑ j=1 J 1 P ik > εi ∑k=j J [see text of problem set]\r\n # (f) An alternative way to generate choices would be to draw a N × J matrix of ε’s from a T1EV distribution.\r\n # This distribution is already defined in the Distributions package. Then Y i = argmax j X i β j + ε i j .\r\n # I’ll show you an example of how to do that in the solutions code for this problem set.\r\n #:::::::::::::::::::::::::::::::::::::::::::::::::::\r\n function sim_logit(N=100_000,J=4) # putting \"=\" after the arguments here sets default values for these arguments\r\n # generate X, β and P\r\n X = hcat(ones(N),randn(N),2 .+ 2 .* randn(N))\r\n if J==4\r\n β = hcat([1, -1, 0.5],[-2, 0.5, 0.3],[0, -0.5, 2],zeros(3)) # GG: numbers that square nicely with 4\r\n else\r\n β = 2 .* rand(size(X,2),J) .- 1\r\n end\r\n P = exp.(X*β) ./ sum.(eachrow(exp.(X*β))) # GG: usual one-liner to generate multinomial ogit choice probabilities; eachrow is summation\r\n # draw choices\r\n draw = rand(N)\r\n Y = zeros(N) # Initializing Y as an Nx1 vector of 0s\r\n for j=1:J\r\n Ytemp = sum(P[:,j:J];dims=2) .> draw # GG: then updating it (summing across j) based on whether choice probability is above or below draw [see formula of problem set]\r\n Y += Ytemp # GG: for each iteration of the loop adding Ytemp to Y\r\n end\r\n return Y,X\r\n end\r\n ySim,XSim = sim_logit() # GG: it will use \"default values\" for N and J set in line 244 through s\"et to the default operator =\"\"\r\n α_hat_sim_optim = optimize(a -> mlogit_mle(a, XSim, ySim), rand(9), LBFGS(), Optim.Options(g_tol = 1e-5, iterations=100_000, show_trace=true, show_every=50))\r\n α_hat_sim_mle = α_hat_sim_optim.minimizer\r\n println(\"simulated mlogit MLE estimates: \",α_hat_sim_mle) # GG: and here are our simulated estimates; values pretty close because sample size big and SEs low\r\n\r\n # now with drawing from Gumbel instead (#GG: i.e T1EV)\r\n # GG: python does not have the nice Distributions package as in Julia\r\n function sim_logit_w_gumbel(N=100_000,J=4) # putting = here sets default values for these arguments\r\n # generate X and β (No P needed)\r\n X = hcat(ones(N),randn(N),2 .+ 2 .* randn(N))\r\n if J==4\r\n β = hcat([1, -1, 0.5],[-2, 0.5, 0.3],[0, -0.5, 2],zeros(3))\r\n else\r\n β = 2 .* rand(size(X,2),J) .- 1\r\n end\r\n # draw choices\r\n ϵ = rand(Gumbel(0,1),N,J) # GG: using Julia's Distributions package; Gumbel(0,1) is \"standard\" T1EV\r\n Y = argmax.(eachrow(X*β .+ ϵ)) # GG: getting argmax of eachrow; eachrow allows avoiding to have to write a loop; tells Julia to do argmax computation row-wise and find column j maximizer\r\n # GG: that's just another way of deriving the Y; the loop in the previous function is just as fine\r\n return Y,X\r\n end\r\n ySim,XSim = sim_logit_w_gumbel()\r\n α_hat_sim_optim = optimize(a -> mlogit_mle(a, XSim, ySim), rand(9), LBFGS(), Optim.Options(g_tol = 1e-5, iterations=100_000, show_trace=true, show_every=50))\r\n α_hat_sim_mle = α_hat_sim_optim.minimizer\r\n println(\"simulated mlogit MLE estimates: \",α_hat_sim_mle)\r\n\r\n #:::::::::::::::::::::::::::::::::::::::::::::::::::\r\n # Question 4 - run SMM.parallelNormal()\r\n #\r\n # 4. Use SMM.jl to run the example code on slide #21 of the Lecture 9 slide deck.\r\n #:::::::::::::::::::::::::::::::::::::::::::::::::::\r\n # GG: SMM.jl has a nice count-down that Optim does not have\r\n MA = SMM.parallelNormal()\r\n dc = SMM.history(MA.chains[1])\r\n dc = dc[dc[:accepted].==true, :]\r\n println(describe(dc)) # GG: can verify you get the mean of the MVN distribution\r\n\r\n #:::::::::::::::::::::::::::::::::::::::::::::::::::\r\n # Question 5 - estimate mlogit by SMM\r\n # GG: Wanna use SIMULATED METHOD OF MOMENTS (using code of Q3) to ESTIMATE RESULT OF Q2\r\n #\r\n # 5. Use your code from Question 3 to estimate the multinomial logit model from Question 2 using SMM and the code example from slide #18 of\r\n # the Lecture 9 slide deck.\r\n #:::::::::::::::::::::::::::::::::::::::::::::::::::\r\n # GG: X and y of Q2\r\n X = [ones(size(df,1),1) df.age df.white df.collgrad]\r\n y = df.occupation\r\n # GG: chunk below was commented out by Tyler beacuse the set of moment conditions used were just not working out for him\r\n #function mlogit_smm(α, X, y, D)\r\n # K = size(X,2)\r\n # J = length(unique(y))\r\n # N = length(y)\r\n # bigY = zeros(N,J)\r\n # bigỸ = zeros(N,J)\r\n # for j=1:J\r\n # bigY[:,j] = y.==j\r\n # end\r\n # bigα = [reshape(α,K,J-1) zeros(K)]\r\n\r\n # T = promote_type(eltype(α),eltype(X))\r\n # gmodel = zeros(T,(J-1)*K,D)\r\n # gdata = zeros(T,(J-1)*K)\r\n\r\n # # data moments\r\n # for j=1:(J-1)\r\n # gdata[(j-1)*K+1] = mean( (bigY[:,j]) )\r\n # for k = 2:K\r\n # gdata[(j-1)*K+k] = cov( bigY[:,j], X[:,k] )\r\n # end\r\n # end\r\n\r\n # Random.seed!(1234)\r\n # # simulated model moments\r\n # for d=1:D\r\n # # draw choices\r\n # ε = rand(Gumbel(0,1),N,J)\r\n # ỹ = argmax.(eachrow(X*bigα .+ ε))\r\n # for j=1:J\r\n # bigỸ[:,j] = ỹ.==j\r\n # end\r\n # # data moments\r\n # for j=1:(J-1)\r\n # gmodel[(j-1)*K+1,d] = mean( (bigỸ[:,j]) )\r\n # for k = 2:K\r\n # gmodel[(j-1)*K+k,d] = cov( bigỸ[:,j], X[:,k] )\r\n # end\r\n # end\r\n # end\r\n\r\n # # minimize squared difference between data and moments\r\n # g = mean(gmodel .- gdata; dims=2)\r\n # J = N*g⋅g\r\n # return J\r\n #\r\n\r\n # GG: the function below for the SIMULATED METHOD OF MOMENTS is the one from the SLIDES OF LECTURE 9 (mind the SCROLLER; gotta use HTML and not PDF version)\r\n function mlogit_smm_overid(α, X, y, D) # GG: D is the number of draws\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 bigỸ = zeros(N,J)\r\n for j=1:J\r\n bigY[:,j] = y.==j # GG: bigY is our real data that we're trying to MATCH\r\n end\r\n bigα = [reshape(α,K,J-1) zeros(K)] # GG: bigα is our parameter vector that we're gonna try to guess value of, so that we get values so that simulated data match actual ones as closely as possible\r\n\r\n Random.seed!(1234) # GG: cardinal rule, set up the seed; don't forget that!\r\n for d=1:D\r\n # draw choices\r\n ε = rand(Gumbel(0,1),N,J) # GG: if we change the distribution of ε to a multivariate normal, we can do MNP without having to do any Monte Carlo integration. We don't need to have a closed form solution for this.\r\n # GG: and if we want to do GEV models, we need to specify nest-specific and alternative-specific component; just two errors but same principle.\r\n ỹ = argmax.(eachrow(X*bigα .+ ε)) # GG: we're goona draw ỹ through ε\r\n for j=1:J\r\n bigỸ[:,j] .+= (ỹ.==j)*(1/D) # GG: bigỹ is our SIMULATED data\r\n # GG: we set the jth column of bigỸ to a dummy if ỹ is equal to j\r\n end\r\n end\r\n\r\n g = bigY[:] .- bigỸ[:] # GG: exactly like g in Question 2; very same principle\r\n\r\n J = g'*I*g\r\n return J\r\n end\r\n println(size(X,2))\r\n println(length(unique(y))-1)\r\n println(\"size of svals: \",size(α_true .+ .0001*rand(size(α_true))))\r\n bigα = [reshape(α_true,size(X,2),length(unique(y))-1) zeros(size(X,2))]\r\n println(\"size of bigα: \",size(bigα))\r\n td = TwiceDifferentiable(th -> mlogit_smm_overid(th, X, y, 2_000), α_true .+ .0001*rand(size(α_true)); autodiff = :forward)\r\n α_hat_smm_overid = optimize(td, α_true .+ .0001*rand(size(α_true)), LBFGS(), Optim.Options(g_tol=1e-8, x_tol=1e-8, f_tol=1e-8, iterations=100_000, show_trace=true, show_every=5))\r\n println(α_hat_smm_overid.minimizer)\r\n return nothing\r\nend\r\n\r\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\r\n# Question 6\r\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\r\n@time allwrap()\r\n", "meta": {"hexsha": "ecf23e19285d4a1d1aa64b1328cd83e573f46fce", "size": 20255, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ProblemSets/PS7-smm/PS7solutions_GG.jl", "max_stars_repo_name": "peppegrass/fall-2020", "max_stars_repo_head_hexsha": "03f90548ca4d800146bbeaf9dceca917a21c1195", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-01T08:58:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-01T08:58:14.000Z", "max_issues_repo_path": "ProblemSets/PS7-smm/PS7solutions_GG.jl", "max_issues_repo_name": "peppegrass/fall-2020", "max_issues_repo_head_hexsha": "03f90548ca4d800146bbeaf9dceca917a21c1195", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ProblemSets/PS7-smm/PS7solutions_GG.jl", "max_forks_repo_name": "peppegrass/fall-2020", "max_forks_repo_head_hexsha": "03f90548ca4d800146bbeaf9dceca917a21c1195", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-12T17:24:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-12T17:24:05.000Z", "avg_line_length": 50.5112219451, "max_line_length": 243, "alphanum_fraction": 0.5925944211, "num_tokens": 6261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087946129329, "lm_q2_score": 0.9019206738932334, "lm_q1q2_score": 0.8373510856857009}} {"text": "# A variety of means\n\n# Geometric mean\nfunction geomean(a::RealArray)\n s = 0.0\n n = length(a)\n for i = 1 : n\n @inbounds s += log(a[i])\n end\n return exp(s / n)\nend\n\n\n# Harmonic mean\nfunction harmmean(a::RealArray)\n s = 0.0\n n = length(a)\n for i in 1 : n\n @inbounds s += inv(a[i])\n end\n return n / s\nend\n\n\n# Trimmed mean\n\nfunction trimmean(x::RealArray, p::FloatingPoint)\n n = length(x)\n n > 0 || error(\"x can not be empty.\")\n rn = min(iround(n * p), n-1)\n if rn == n - 1\n return median(x)\n else\n sx = sort(x)\n nl = rn >> 1\n nh = (rn - nl)\n s = 0.0\n @inbounds for i = (1+nl) : (n-nh)\n s += x[i]\n end\n return s / (n - rn)\n end\nend\n\n\n# Weighted mean\nfunction wmean{T<:Number,W<:Real}(v::AbstractArray{T}, w::AbstractArray{W}; wsum::W=NaN)\n\t# wsum is the pre-computed sum of weights\n\n\tn = length(v)\n\tlength(w) == n || raise_dimerror()\n sv = zero(T)\n\n if isnan(wsum)\n \tsw = zero(W)\n \tfor i = 1 : n\n \t\t@inbounds wi = w[i]\n \t@inbounds sv += v[i] * wi\n \tsw += wi\n \tend\n else\n \tfor i = 1 : n\n \t\t@inbounds sv += v[i] * w[i]\n \tend\n \tsw = wsum\n end\n\n return sv / sw\nend\n\n# Weighted mean (fast version for contiguous arrays using BLAS)\nfunction wmean{T<:BlasReal}(v::Array{T}, w::Array{T}; wsum::T=NaN) \n\tsw = (isnan(wsum) ? sum(w) : wsum)\n\tdot(v, w) / sw\nend\n\nmean{T<:Number}(v::AbstractArray{T}, w::WeightVec) = wmean(v, values(w); wsum=sum(w))\n\n", "meta": {"hexsha": "4c14ff8a0c3dcf885d12cd3adcb472b79395d42a", "size": 1516, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/means.jl", "max_stars_repo_name": "rened/Stats.jl", "max_stars_repo_head_hexsha": "0efba512a2bf8faa21e61c9568222ae1ae96acbb", "max_stars_repo_licenses": ["Xnet", "X11"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-20T16:09:54.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-20T16:09:54.000Z", "max_issues_repo_path": "src/means.jl", "max_issues_repo_name": "aviks/StatsBase.jl", "max_issues_repo_head_hexsha": "2e3401eb239454d3c38b68a8ccd0c665005acf44", "max_issues_repo_licenses": ["Xnet", "X11"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/means.jl", "max_forks_repo_name": "aviks/StatsBase.jl", "max_forks_repo_head_hexsha": "2e3401eb239454d3c38b68a8ccd0c665005acf44", "max_forks_repo_licenses": ["Xnet", "X11"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.1898734177, "max_line_length": 88, "alphanum_fraction": 0.5250659631, "num_tokens": 530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172673767973, "lm_q2_score": 0.8824278726384089, "lm_q1q2_score": 0.8373510455611595}} {"text": "@doc raw\"\"\"\n ExponentiatedKernel([a=1])\n\nThe exponentiated kernel is a Mercer kernel given by:\n\n```math\n\\kappa(\\mathbf{x},\\mathbf{y}) = \\exp\\left(a \\mathbf{x}^\\intercal \\mathbf{y} \\right) \n\\qquad a > 0\n```\n\"\"\"\nstruct ExponentiatedKernel{T<:AbstractFloat} <: MercerKernel{T}\n alpha::HyperParameter{T}\n ExponentiatedKernel{T}(α::Real) where {T<:AbstractFloat} = new{T}(\n HyperParameter(convert(T,α), interval(OpenBound(zero(T)), nothing))\n )\nend\nExponentiatedKernel(α::T1 = 1.0) where {T1<:Real} = ExponentiatedKernel{floattype(T1)}(α)\n\n@inline exponentiatedkernel(z::T, α::T) where {T<:AbstractFloat} = exp(α*z)\n\n@inline basefunction(::ExponentiatedKernel) = ScalarProduct()\n@inline kappa(κ::ExponentiatedKernel{T}, z::T) where {T} = exponentiatedkernel(z, getvalue(κ.alpha))", "meta": {"hexsha": "e1aac9db822cf8528b754ec00b82660698ea0fc2", "size": 793, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernelfunctions/mercer/exponentiated.jl", "max_stars_repo_name": "holtri/MLKernels.jl", "max_stars_repo_head_hexsha": "d7b84b1bd7b9d9ca4cb7c413d0e34b04c09a331c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernelfunctions/mercer/exponentiated.jl", "max_issues_repo_name": "holtri/MLKernels.jl", "max_issues_repo_head_hexsha": "d7b84b1bd7b9d9ca4cb7c413d0e34b04c09a331c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernelfunctions/mercer/exponentiated.jl", "max_forks_repo_name": "holtri/MLKernels.jl", "max_forks_repo_head_hexsha": "d7b84b1bd7b9d9ca4cb7c413d0e34b04c09a331c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0454545455, "max_line_length": 100, "alphanum_fraction": 0.6986128625, "num_tokens": 256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122756889438, "lm_q2_score": 0.874077222043951, "lm_q1q2_score": 0.8372893008959913}} {"text": "\"\"\"\r\n M = time_to_mean(t, T, Mo=0., epoch=0.)\r\n\r\nComputes the mean anomaly of an orbit with period `T` from a time `t`, the orbit's mean anomaly\r\nat epoch `Mo`, and the epoch.\r\n\"\"\"\r\nfunction time_to_mean(t, T, Mo=0., epoch=0.) \r\n return Mo + 2π*(t - epoch)/T\r\nend\r\n\r\nfunction time_to_mean(t, orb::Orbit)\r\n M = time_to_mean(t, orb.period, orb.Mo, orb.epoch)\r\n if orb.e < 1\r\n return wrap_angle(M)\r\n else\r\n return M\r\n end\r\nend\r\n\r\n\"\"\"\r\n t = mean_to_time(M, T, Mo=0, epoch=0, tmin=nothing)\r\n\r\nComputes the time at which an orbit with period `T`, mean anomaly\r\nat epoch `Mo`, and epoch `epoch` has the specified mean anomaly `M`.\r\n\r\nBecause this time is not uniquely defined for elliptical orbits, `tmin` can be specified\r\nto ensure that the returned time falls between `tmin` and `tmin + T`.\r\n\"\"\"\r\nfunction mean_to_time(M, T, Mo=0, epoch=0, tmin=nothing) \r\n t = epoch + (M-Mo)*T/(2π)\r\n if tmin === nothing\r\n return t\r\n else\r\n return t + T*ceil((tmin-t)/T)\r\n end\r\nend\r\n\r\nmean_to_time(M, orb::Orbit, tmin=nothing) = mean_to_time(M, orb.period, orb.Mo, orb.epoch, orb.e<1 ? tmin : nothing)\r\n\r\n\"\"\"\r\n θ = mean_to_true(M, e)\r\n\r\nComputes the true anomaly of an orbit with eccentricity `e` at the specified mean anomaly `M`.\r\n\"\"\"\r\nfunction mean_to_true(M, e)\r\n if e == 1 # Parabolic case\r\n throw(ArgumentError(\"Parabolic case (e=1) not implemented\"))\r\n elseif e < 1 # Elliptical case\r\n E = kepler(M, e)\r\n return 2*atan(√(1+e)*sin(E/2), √(1-e)*cos(E/2))\r\n else # Hyperbolic case\r\n H = kepler(M, e)\r\n return 2*atan(√(e+1)*sinh(H/2), √(e-1)*cosh(H/2))\r\n end\r\nend\r\n\r\n\"\"\"\r\n θ = time_to_true(t, e, T, Mo=0., epoch=0.)\r\n\r\nComputes the mean anomaly of an orbit with eccentricity `e` and period `T` from a time `t`, the orbit's mean anomaly\r\nat epoch `Mo`, and the epoch.\r\n\"\"\"\r\nfunction time_to_true(t, e, T, Mo=0, epoch=0)\r\n M = time_to_mean(t, T, Mo, epoch)\r\n return mean_to_true(M, e)\r\nend\r\n\r\ntime_to_true(t, orb::Orbit) = time_to_true(t, orb.e, orb.period, orb.Mo, orb.epoch)\r\n\r\n\"\"\"\r\n M = true_to_mean(θ, e)\r\n\r\nComputes the mean anomaly of an orbit with eccentricity `e` at the specified true anomaly `θ`.\r\n\"\"\"\r\nfunction true_to_mean(θ, e)\r\n if e == 1 # Parabolic case\r\n throw(ArgumentError(\"Parabolic case (e=1) not implemented\"))\r\n elseif e < 1 # Elliptical case\r\n E = 2*atan(sin(θ/2)*√(1-e), cos(θ/2)*√(1+e))\r\n return wrap_angle(E - e*sin(E))\r\n else # Hyperbolic case\r\n H = 2*atanh(tan(θ/2)*√((e-1)/(e+1)))\r\n # H = copysign(acosh((e+cos(θ))/(1+e*cos(θ))), θ)\r\n return e*sinh(H) - H\r\n end\r\nend\r\n\r\ntrue_to_mean(θ, orb::Orbit) = true_to_mean(θ, orb.e)\r\n\r\n\"\"\"\r\n t = true_to_time(θ, e, T, Mo=0, epoch=0, tmin=nothing)\r\n\r\nComputes the time at which an orbit with eccentricity `e`, period `T`, mean anomaly\r\nat epoch `Mo`, and epoch `epoch` has the specified true anomaly `θ`.\r\n\r\nBecause this time is not uniquely defined for elliptical orbits, `tmin` can be specified\r\nto ensure that the returned time falls between `tmin` and `tmin + T`.\r\n\"\"\"\r\nfunction true_to_time(θ, e, T, Mo=0, epoch=0, tmin=nothing)\r\n M = true_to_mean(θ, e)\r\n return mean_to_time(M, T, Mo, epoch, e<1 ? tmin : nothing)\r\nend\r\n\r\n# true_to_time(θ, e, a, μ, Mo=0, epoch=0, tmin=nothing) = true_to_time(θ, e, period(a, μ), Mo, epoch, tmin)\r\ntrue_to_time(θ, orb::Orbit, tmin=nothing) = true_to_time(θ, orb.e, orb.period, orb.Mo, orb.epoch, tmin)\r\n", "meta": {"hexsha": "664b60248f45fe8e379dc86bfc188b7a0db5699e", "size": 3519, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/anomaly.jl", "max_stars_repo_name": "tmcgrath325/KeplerTools.jl", "max_stars_repo_head_hexsha": "bb95d6c24ca7e1cea6f7f8057f01a415f5719f6e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/anomaly.jl", "max_issues_repo_name": "tmcgrath325/KeplerTools.jl", "max_issues_repo_head_hexsha": "bb95d6c24ca7e1cea6f7f8057f01a415f5719f6e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-19T16:28:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-19T16:28:17.000Z", "max_forks_repo_path": "src/anomaly.jl", "max_forks_repo_name": "tmcgrath325/KeplerTools.jl", "max_forks_repo_head_hexsha": "bb95d6c24ca7e1cea6f7f8057f01a415f5719f6e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1981132075, "max_line_length": 117, "alphanum_fraction": 0.6109690253, "num_tokens": 1151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620585273153, "lm_q2_score": 0.872347368040789, "lm_q1q2_score": 0.8372459057017133}} {"text": "using PyPlot\nusing OffsetArrays\n\nfunction bary_grid(n, a)\n x = OffsetArray{Float64}(undef, 0:n, 0:n)\n y = OffsetArray{Float64}(undef, 0:n, 0:n)\n pts = OffsetArray(range(0, 1, length=n+1), 0:n)\n for i = 0:n\n ξ₁ = pts[i]\n for j = 0:n-i\n ξ₂ = pts[j]\n ξ₃ = 1 - ξ₁ - ξ₂\n x[i,j] = ξ₁ * a[1,1] + ξ₂ * a[1,2] + ξ₃ * a[1,3]\n y[i,j] = ξ₁ * a[2,1] + ξ₂ * a[2,2] + ξ₃ * a[2,3]\n end\n for j = n-i+1:n\n x[i,j] = NaN\n y[i,j] = NaN\n end\n end\n return x, y\nend\n\nfunction bary_func(f, n, a)\n z = OffsetArray{Float64}(undef, 0:n, 0:n)\n pts = OffsetArray(range(0, 1, length=n+1), 0:n)\n ξ = Vector{Float64}(undef, 3)\n for i = 0:n\n ξ[1] = pts[i]\n for j = 0:n-i\n ξ[2] = pts[j]\n ξ[3] = 1 - ξ[1] - ξ[2]\n z[i,j] = f(ξ)\n end\n end\n return z\nend\n\nfunction bary_plot(x, y, z)\n n = size(x, 1) - 1\n xd = [ x[i,n-i] for i = 0:n ]\n yd = [ y[i,n-i] for i = 0:n ]\n zd = [ z[i,n-i] for i = 0:n ]\n idx = [1, 2, 3, 1]\n plot3D(a[1,idx], a[2,idx], zeros(4), \"k\")\n for i = 0:n\n plot3D(x[i,0:n-i], y[i,0:n-i], z[i,0:n-i], \"c\")\n end\n for j = 0:n\n plot3D(x[0:n-j,j], y[0:n-j,j], z[0:n-j,j], \"c\")\n end\n for i = 0:n\n plot3D(xd, yd, zd, \"c\")\n end\n axis(\"off\")\n# xlabel(L\"$x$\")\n# ylabel(L\"$y$\")\nend\n\nfunction midpoints(a)\n prev = [ 3, 1, 2 ]\n succ = [ 2, 3, 1 ]\n m = Matrix{Float64}(undef, 2, 3)\n for i = 1:3\n m[:,i] = ( a[:,prev[i]] + a[:,succ[i]] ) / 2\n end\n return m\nend\n\nψ₁(ξ) = 2 * ξ[1] * ( ξ[1] - 0.5 )\nψ₂(ξ) = 2 * ξ[2] * ( ξ[2] - 0.5 )\nψ₃(ξ) = 2 * ξ[3] * ( ξ[3] - 0.5 )\nψ₄(ξ) = 4 * ξ[2] * ξ[3]\nψ₅(ξ) = 4 * ξ[3] * ξ[1]\nψ₆(ξ) = 4 * ξ[1] * ξ[2]\n\na = Float64[ 0 1 2\n 2 0 3 ]\nm = midpoints(a)\nn = 20\nx, y = bary_grid(n, a)\n\nfigure(1)\nz = bary_func(ψ₁, n, a)\nbary_plot(x, y, z)\nplot3D(a[1,1], a[2,1], \"ro\")\nsavefig(\"psi1.pdf\")\n\nfigure(2)\nz = bary_func(ψ₂, n, a)\nbary_plot(x, y, z)\nplot3D(a[1,2], a[2,2], \"ro\")\nsavefig(\"psi2.pdf\")\n\nfigure(3)\nz = bary_func(ψ₃, n, a)\nbary_plot(x, y, z)\nplot3D(a[1,3], a[2,3], \"ro\")\nsavefig(\"psi3.pdf\")\n\nfigure(4)\nz = bary_func(ψ₄, n, a)\nbary_plot(x, y, z)\nplot3D(m[1,1], m[2,1], \"ro\")\nsavefig(\"psi4.pdf\")\n\nfigure(5)\nz = bary_func(ψ₅, n, a)\nbary_plot(x, y, z)\nplot3D(m[1,2], m[2,2], \"ro\")\nsavefig(\"psi5.pdf\")\n\nfigure(6)\nz = bary_func(ψ₆, n, a)\nbary_plot(x, y, z)\nplot3D(m[1,3], m[2,3], \"ro\")\nsavefig(\"psi6.pdf\")\n", "meta": {"hexsha": "71658b37f8b529e95806166c83c2401f1fce5724", "size": 2490, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chap6/quad_shape_funcs/quadratic_shape_funcs.jl", "max_stars_repo_name": "billmclean/ComputationalMathsNotes", "max_stars_repo_head_hexsha": "9d521fdf7ec407cca287997885d81c3150973415", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-30T21:30:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T21:30:20.000Z", "max_issues_repo_path": "src/chap6/quad_shape_funcs/quadratic_shape_funcs.jl", "max_issues_repo_name": "billmclean/ComputationalMathsNotes", "max_issues_repo_head_hexsha": "9d521fdf7ec407cca287997885d81c3150973415", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/chap6/quad_shape_funcs/quadratic_shape_funcs.jl", "max_forks_repo_name": "billmclean/ComputationalMathsNotes", "max_forks_repo_head_hexsha": "9d521fdf7ec407cca287997885d81c3150973415", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1016949153, "max_line_length": 60, "alphanum_fraction": 0.4602409639, "num_tokens": 1231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813538993888, "lm_q2_score": 0.8757869803008765, "lm_q1q2_score": 0.8372360231554893}} {"text": "doc\"\"\"\n second_derivative(f::Function, x::AbstractFloat)\n\n# Description\n\nEvaluate the second derivative of `f` at `x` using finite differences. In\nmathematical notation, we calculate,\n\n```math\n\\frac{f(x + \\epsilon) - 2 f(x) + f(x - \\epsilon)}{\\epsilon^2},\n```\n\nwhere ``\\epsilon`` is chosen to be small enough to approximate the second\nderivative, but not so small as to suffer from extreme numerical inaccuracy.\n\n# Arguments\n\n* `f::Function`: The function to be differentiated.\n* `x::AbstractFloat`: The point at which to evaluate the derivative of `f`. Its\n type must implement `eps`.\n\n# Returns\n\n* `y::Real`: The second derivative of `f` evaluated at `x`.\n\n# Examples\n\n```jl\nimport FiniteDiff: second_derivative\ny = second_derivative(sin, 1.0)\n```\n\"\"\"\n@inline function second_derivative(f::Function, x::AbstractFloat)::Real\n ϵ = step_size(HessianMode(), x)\n return (f(x + ϵ) - 2 * f(x) + f(x - ϵ)) / (ϵ * ϵ)\nend\n\ndoc\"\"\"\n second_derivative!(\n output::AbstractArray,\n f::Function,\n x::AbstractFloat,\n )\n\n# Description\n\nEvaluate the second derivative of `f` at `x` using finite differences. In\nmathematical notation, we calculate,\n\n```math\n\\frac{f(x + \\epsilon) - 2 f(x) + f(x - \\epsilon)}{\\epsilon^2},\n```\n\nwhere ``\\epsilon`` is chosen to be small enough to approximate the second\nderivative, but not so small as to suffer from extreme numerical inaccuracy.\n\nThe first argument, `output`, will be mutated so that the value of the second\nderivative is its first element.\n\n# Arguments\n\n* `output::AbstractArray`: An array whose first element will be mutated.\n* `f::Function`: The function to be differentiated.\n* `x::AbstractFloat`: The point at which to evaluate the derivative of `f`. Its\n type must implement `eps`.\n\n# Returns\n\n* `void::Nothing`: This function is called for its side-effects.\n\n# Examples\n\n```jl\nimport FiniteDiff: second_derivative\ny = Array(Float64, 1)\nsecond_derivative!(y, sin, 1.0)\n```\n\"\"\"\nfunction second_derivative!(\n output::AbstractArray,\n f::Function,\n x::AbstractFloat,\n)::Void\n output[1] = second_derivative(f, x)\n return\nend\n\n\"\"\"\n second_derivative(f::Function; mutates::Bool=false)\n\n# Description\n\nConstruct a new function that will evaluate the second derivative of `f` at\nany point `x`. A keyword argument specifies whether the resulting function\nshould be mutating or non-mutating.\n\n# Arguments\n\n* `f::Function`: The function to be differentiated.\n\n# Keyword Arguments\n\n* `mutates::Bool = false`: Determine whether the resulting function will mutate\n its inputs or will be a pure function.\n\n# Returns\n\n* `void::Nothing`: This function is called for its side-effects.\n\n# Examples\n\n```jl\nimport FiniteDiff: second_derivative\nf′′ = second_derivative(sin)\nf′′(1.0)\n```\n\"\"\"\nfunction second_derivative(f::Function; mutates::Bool=false)::Function\n if mutates\n return (output, x) -> second_derivative!(output, f, x)\n else\n return (x, ) -> second_derivative(f, x)\n end\nend\n", "meta": {"hexsha": "a8b16c95b6a3ed622a28db881e763674bb272c19", "size": 2984, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/second_derivative.jl", "max_stars_repo_name": "johnmyleswhite/FiniteDiff.jl", "max_stars_repo_head_hexsha": "d9c3da50b0c214b7be008b60cb04d6701548ff92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-01-19T14:57:24.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-27T06:04:07.000Z", "max_issues_repo_path": "src/second_derivative.jl", "max_issues_repo_name": "johnmyleswhite/FiniteDiff.jl", "max_issues_repo_head_hexsha": "d9c3da50b0c214b7be008b60cb04d6701548ff92", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2016-08-17T22:35:39.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-22T16:09:43.000Z", "max_forks_repo_path": "src/second_derivative.jl", "max_forks_repo_name": "johnmyleswhite/FiniteDiff.jl", "max_forks_repo_head_hexsha": "d9c3da50b0c214b7be008b60cb04d6701548ff92", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-01-16T20:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-18T22:51:01.000Z", "avg_line_length": 23.872, "max_line_length": 79, "alphanum_fraction": 0.6987265416, "num_tokens": 767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.953966093674472, "lm_q2_score": 0.8774767986961401, "lm_q1q2_score": 0.8370831139421379}} {"text": "###############################################################################\n#\n# Linear regression of Y~X\n#\n###############################################################################\n\"\"\"\n linear_df_xy(df::DataFrame, intercept::Bool)\n\nLinear fit the X and Y in a given DataFrame, given\n- `df` DataFrame that use `X` and `Y` to store values\n- `intercept` Whether using intercept when making the regression\n\"\"\"\nfunction linear_df_xy(df::DataFrame, intercept::Bool)\n # run the fitting\n if intercept\n lr = lm(@formula(Y ~ X), df);\n else\n lr = lm(@formula(Y ~ 0 + X), df);\n end\n\n return lr\nend\n\n\n\n\n\"\"\"\n line_regress(\n xs::Array,\n ys::Array;\n intercept::Bool = true,\n sorting::Bool = true\n )\n\nMake linear regression and return the fitted results, given\n- `xs` Array of x, can be NaN\n- `ys` Array of y, can be NaN\n- `intercept` Optional: if true use intercept in the fitting\n- `sorting` Optional: if true, sort the values\n\"\"\"\nfunction line_regress(\n xs::Array,\n ys::Array;\n intercept::Bool = true,\n sorting::Bool = true\n)\n # filter out NaN from the lists\n new_x = Float64[];\n new_y = Float64[];\n for (x,y) in zip(xs, ys)\n if ~isnan(x) && ~isnan(y)\n push!(new_x, x);\n push!(new_y, y);\n end\n end\n\n # put new_x and new_y into a DataFrame\n df = DataFrame(X=new_x, Y=new_y);\n sorting ? sort!(df) : nothing;\n\n # run the fitting\n lr = linear_df_xy(df, intercept);\n _r2 = adjr2(lr);\n\n # create items for the struct\n if intercept\n _inter = coef(lr)[1];\n _slope = coef(lr)[2];\n _inter_p = coeftable(lr).cols[4][1];\n _slope_p = coeftable(lr).cols[4][2];\n _inter_ci = confint(lr)[1,:];\n _slope_ci = confint(lr)[2,:];\n else\n _inter = Inf;\n _slope = coef(lr)[1];\n _inter_p = Inf;\n _slope_p = coeftable(lr).cols[4][1];\n _inter_ci = [-Inf, Inf];\n _slope_ci = confint(lr)[1,:];\n end\n\n # calculate the predictions\n if intercept\n mt = [ones(length((df).X)) (df).X];\n else\n mt = (df).X[:,:];\n end\n pred = predict(lr, mt; interval=:confidence);\n df[!,\"predY\" ] = pred.prediction;\n df[!,\"lowerY\"] = pred.lower[:,1];\n df[!,\"upperY\"] = pred.upper[:,1];\n\n return LinearRegressionResult(\n lr,\n _r2,\n _inter,\n _slope,\n _inter_p,\n _slope_p,\n _inter_ci,\n _slope_ci,\n df\n )\nend\n", "meta": {"hexsha": "440a76b132435685da90228841e0bf91292d372b", "size": 2651, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/regression/linear.jl", "max_stars_repo_name": "Yujie-W/PlotPlants.jl", "max_stars_repo_head_hexsha": "8ad793bfccb2f1158d39724d930c69451acb8534", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-05T21:20:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-05T21:20:06.000Z", "max_issues_repo_path": "src/regression/linear.jl", "max_issues_repo_name": "Yujie-W/PlotPlants.jl", "max_issues_repo_head_hexsha": "8ad793bfccb2f1158d39724d930c69451acb8534", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 31, "max_issues_repo_issues_event_min_datetime": "2020-10-01T01:51:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T15:30:06.000Z", "max_forks_repo_path": "src/regression/linear.jl", "max_forks_repo_name": "Yujie-W/PlotPlants.jl", "max_forks_repo_head_hexsha": "8ad793bfccb2f1158d39724d930c69451acb8534", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2476190476, "max_line_length": 79, "alphanum_fraction": 0.4903809883, "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660976007597, "lm_q2_score": 0.877476785879798, "lm_q1q2_score": 0.8370831051610084}} {"text": "### A Pluto.jl notebook ###\n# v0.16.1\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 987c5c4d-3257-41cf-b8a9-7b3e814ba61b\nbegin\n\tusing Pkg\n\tPkg.add(\"Plots\")\n\tusing Plots\nend\n\n# ╔═╡ 9215d698-38ed-11ec-1e52-45e96b1bc12e\nmd\"\"\"\n# Chapter 1\n## Section 1\n\nTaylor series in the neighborhood of x = a\n\n$$f(x) = \\sum_{n=0}^{\\infty}\\frac{f^{(n)}(a)}{n!}(x-a)^n$$\n\nNear a = 0 and for x = $\\pm$h we can write at the third order\n\n$$f(h) = f_0 + hf' + \\frac{h^2}{2}f''$$\n$$f(-h) = f_0 - hf' + \\frac{h^2}{2}f''$$\n\nIf we sub\n\n$$f(h) - f(-h) = 2hf'$$\n$$\\Rightarrow f' = \\frac{f(h) - f(-h)}{2h}$$\n\nCentered difference\n\"\"\"\n\n# ╔═╡ c7732e76-19b9-4aa6-a61e-5b142dae1d3e\nfunction funcdiff(f, x::T, dx::T)::T where T <: Number\n\t(f(x + dx) - f(x - dx)) / (2 * dx)\nend\n\n# ╔═╡ 5137159c-90a8-49a5-9aa3-5356f3137662\nbegin\n\tx = collect(0:0.01:7)\n\ty = funcdiff.(sin, x, 0.01) \n\tplot(x, y)\nend\n\n# ╔═╡ 72affc38-4df9-48af-98b7-0b1b92d9d980\nfunction arraydiff(x::Vector{T}, dx::T)::Vector{T} where T <: Number\n\t(x[2:end] - x[1:end-1]) / (2 * dx)\nend\n\n# ╔═╡ 42d3c309-bb3a-479b-91fd-3d26adda0555\nbegin\n\tu = collect(0:0.01:7)\n\tv = arraydiff(sin.(x), 0.01) \n\tplot(u[2:end], v)\nend\n\n# ╔═╡ cb996ce0-a6f1-4176-b226-b1e4b322fabb\nmd\"\"\"\nWe can apply this method to other orders of derivations and order of the Taylor series.\n\nIncreasing the order of the series will increase the accuracy but it will also increase the calculation time.\n\nThe value of h also influences the precision\n\nExercice: For the same function and interval, evaluate the mean error with the analytic derivation.\n\"\"\"\n\n# ╔═╡ 7b6412e5-2f4f-409a-b959-6c9c4eb29a9e\nbegin\n\tallh = collect(0.01:0.01:1)\n\talleps = Float64[]\n\tfor h in allh\n\t\tx = 0:h:7\n\t\tcosine = cos.(x)\n\t\tsinus = funcdiff.(sin, x, h)\n\t\teps = sum(sqrt.(cosine.^2 + sinus.^2)) / length(x)\n\t\tappend!(alleps, eps)\n\tend\n\tplot(allh, alleps)\nend\n\n# ╔═╡ Cell order:\n# ╠═987c5c4d-3257-41cf-b8a9-7b3e814ba61b\n# ╟─9215d698-38ed-11ec-1e52-45e96b1bc12e\n# ╠═c7732e76-19b9-4aa6-a61e-5b142dae1d3e\n# ╠═5137159c-90a8-49a5-9aa3-5356f3137662\n# ╠═72affc38-4df9-48af-98b7-0b1b92d9d980\n# ╠═42d3c309-bb3a-479b-91fd-3d26adda0555\n# ╟─cb996ce0-a6f1-4176-b226-b1e4b322fabb\n# ╠═7b6412e5-2f4f-409a-b959-6c9c4eb29a9e\n", "meta": {"hexsha": "25b0c025c2590b340411678f3943a98d25cb319a", "size": 2169, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "differentiation.jl", "max_stars_repo_name": "zazbone/ComputationalPhysics", "max_stars_repo_head_hexsha": "be3c4dd0b75fefb71aab5ccbd91fa1a5e837b598", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "differentiation.jl", "max_issues_repo_name": "zazbone/ComputationalPhysics", "max_issues_repo_head_hexsha": "be3c4dd0b75fefb71aab5ccbd91fa1a5e837b598", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "differentiation.jl", "max_forks_repo_name": "zazbone/ComputationalPhysics", "max_forks_repo_head_hexsha": "be3c4dd0b75fefb71aab5ccbd91fa1a5e837b598", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0744680851, "max_line_length": 109, "alphanum_fraction": 0.6648224988, "num_tokens": 1041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9539660976007596, "lm_q2_score": 0.8774767826757123, "lm_q1q2_score": 0.837083102104419}} {"text": "using Polynomials\n\n\n\"\"\"\nCalculate Chebyshev polynomials coefficients\n\nInstead of computing the polynomial at a specific point, \nuse `Polynomials` package to compute the actual polynomial\n\"\"\"\nfunction poly_chebyshev{T<:Number}(n, ::Type{T}=Int, var=:x)\n\n if n==0\n return Poly{T}([one(T)], var)\n elseif n==1\n return Poly{T}([zero(T), one(T)], var) \n end\n\n px = Poly{T}([zero(T), one(T)], var)\n T0 = Poly{T}([one(T)], var)\n T1 = px\n \n for i = 2:n\n T2 = 2*px*T1 - T0\n T0 = T1\n T1 = T2\n end\n\n return T1\n\nend\n\n\"\"\"\nCalculate derivative of Chebyshev polynomials coefficients\n\nInstead of computing the polynomial at a specific point, \nuse `Polynomials` package to compute the actual polynomial\n\"\"\"\npoly_dchebyshev{T<:Number}(n, ::Type{T}=Int, var=:x) = polyder(poly_chebyshev(n,T, var))\n\n\n\n\"\"\"\nCalculate the coefficients of Chebyshev polynomials of the second kind\n\nInstead of computing the polynomial at a specific point, \nuse `Polynomials` package to compute the actual polynomial\n\"\"\"\nfunction poly_chebyshev2{T<:Number}(n, ::Type{T}=Int, var=:x)\n\n if n==0\n return Poly{T}([one(T)], var)\n elseif n==1\n return Poly{T}([zero(T), 2*one(T)], var) \n end\n\n px = Poly{T}([zero(T), one(T)], var)\n U0 = Poly{T}([one(T)], var)\n U1 = Poly{T}([zero(T), 2*one(T)], var)\n \n for i = 2:n\n U2 = 2*px*U1 - U0\n U0 = U1\n U1 = U2\n end\n\n return U1\n\nend\n\n\"\"\"\nCalculate the coefficients of the derivative of Chebyshev polynomials of the second kind\n\nInstead of computing the polynomial at a specific point, \nuse `Polynomials` package to compute the actual polynomial\n\"\"\"\npoly_dchebyshev2{T<:Number}(n, ::Type{T}=Int, var=:x) = polyder(poly_chebyshev2(n,T, var))\n\n\n\"\"\"\nCalculate the coefficients of Legendre polynomials \n\nInstead of computing the polynomial at a specific point, \nuse `Polynomials` package to compute the actual polynomial\n\"\"\"\nfunction poly_legendre{T<:Number}(n, ::Type{T}=Float64, var=:x)\n\n\n if n==0\n return Poly{T}([one(T)], var)\n elseif n==1\n return Poly{T}([zero(T), one(T)], var) \n end\n\n px = Poly{T}([zero(T), one(T)], var)\n p0 = Poly{T}([one(T)], var)\n p1 = px\n\n for i = 2:n\n p2 = ( (2i-1)*px*p1 - (i-1)*p0 ) / i\n p0 = p1\n p1 = p2\n end\n\n return p1\nend\n\n\n\"\"\"\nCalculate the coefficients of the derivativ of Legendre polynomials \n\nInstead of computing the polynomial at a specific point, \nuse `Polynomials` package to compute the actual polynomial\n\"\"\"\npoly_dlegendre{T<:Number}(n, ::Type{T}=Int, var=:x) = polyder(poly_legendre(n,T, var))\n\n\n\n\n\n\"\"\"\nCalculate the coefficients of Jacobi polynomials \n\nInstead of computing the polynomial at a specific point, \nuse `Polynomials` package to compute the actual polynomial\n\"\"\"\nfunction poly_jacobi{T<:Number}(n, a, b, ::Type{T}=Float64, var=:x)\n\n ox = one(T)\n zx = zero(T)\n if n==0\n return Poly{T}([one(T)], var)\n elseif n==1\n return Poly{T}([(a-b)/2, (a+b+2)/2], var)\n end\n p0 = Poly{T}([one(T)], var)\n p1 = Poly{T}([(a-b)/2, (a+b+2)/2], var)\n px = Poly{T}([zero(T), one(T)], var)\n \n for i = 1:(n-1)\n\ta1 = 2*(i+1)*(i+a+b+1)*(2*i+a+b);\n\ta2 = (2*i+a+b+1)*(a*a-b*b);\n\ta3 = (2*i+a+b)*(2*i+a+b+1)*(2*i+a+b+2);\n\ta4 = 2*(i+a)*(i+b)*(2*i+a+b+2);\n\tp2 = ox/a1*( (a2 + a3*px)*p1 - a4*p0);\n\n p0 = p1\n p1 = p2\n end\n\n return p1\nend\n\n\n\"\"\"\nCalculate the coefficients of the derivative of Jacobi polynomials \n\nInstead of computing the polynomial at a specific point, \nuse `Polynomials` package to compute the actual polynomial\n\"\"\"\npoly_djacobi{T<:Number}(n, a, b, ::Type{T}=Float64, var=:x) = polyder(poly_jacobi(n,a,b,T,var))\n", "meta": {"hexsha": "c11e2152e6f2784176306c011ac00d7398731a31", "size": 3699, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/polynomials.jl", "max_stars_repo_name": "tkf/Jacobi.jl", "max_stars_repo_head_hexsha": "8a2d769cd78cb0bb9470082d1477fad485866b40", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/polynomials.jl", "max_issues_repo_name": "tkf/Jacobi.jl", "max_issues_repo_head_hexsha": "8a2d769cd78cb0bb9470082d1477fad485866b40", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/polynomials.jl", "max_forks_repo_name": "tkf/Jacobi.jl", "max_forks_repo_head_hexsha": "8a2d769cd78cb0bb9470082d1477fad485866b40", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9751552795, "max_line_length": 95, "alphanum_fraction": 0.6134090295, "num_tokens": 1185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660949832345, "lm_q2_score": 0.8774767794716264, "lm_q1q2_score": 0.8370830967510122}} {"text": "########################################\n###### Vectorized \"dot\" operators ######\n########################################\n\n# For every binary operation like ^, there is a corresponding \"dot\" operation .^ that is \n# automatically defined to perform ^ element-by-element on arrays. For example, [1,2,3] ^ 3 \n# is not defined, since there is no standard mathematical meaning to \"cubing\" a (non-square) array, \n# but [1,2,3] .^ 3 is defined as computing the elementwise (or \"vectorized\") result [1^3, 2^3, 3^3]. \n# Similarly for unary operators like ! or √, there is a corresponding .√ that applies the operator elementwise.\n\n# [1,2,3] .^ 3\nprintln([1,2,3] .^ 3) # [1, 8, 27]\n\n\n", "meta": {"hexsha": "2053e7e5d3cef8267e3e1e93b2849bb68c08bfaf", "size": 676, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "basics/vectorized-dot-op.jl", "max_stars_repo_name": "mauricioriva/learn-julia", "max_stars_repo_head_hexsha": "f4ff81ff412ba4f1243a8cee1123ebc8b3335f01", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "basics/vectorized-dot-op.jl", "max_issues_repo_name": "mauricioriva/learn-julia", "max_issues_repo_head_hexsha": "f4ff81ff412ba4f1243a8cee1123ebc8b3335f01", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "basics/vectorized-dot-op.jl", "max_forks_repo_name": "mauricioriva/learn-julia", "max_forks_repo_head_hexsha": "f4ff81ff412ba4f1243a8cee1123ebc8b3335f01", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.0666666667, "max_line_length": 111, "alphanum_fraction": 0.5931952663, "num_tokens": 191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9353465116437761, "lm_q2_score": 0.894789464699728, "lm_q1q2_score": 0.8369382044624923}} {"text": "# Rank-based correlations\n#\n# - Spearman's correlation\n# - Kendall's correlation\n#\n\n#######################################\n#\n# Spearman correlation\n#\n#######################################\n\ncorspearman(x::RealVector, y::RealVector) = cor(tiedrank(x), tiedrank(y))\n\ncorspearman(X::RealMatrix, Y::RealMatrix) = cor(mapslices(tiedrank, X, 1), mapslices(tiedrank, Y, 1))\ncorspearman(X::RealMatrix, y::RealVector) = cor(mapslices(tiedrank, X, 1), tiedrank(y))\ncorspearman(x::RealVector, Y::RealMatrix) = cor(tiedrank(x), mapslices(tiedrank, Y, 1))\n\ncorspearman(X::RealMatrix) = (Z = mapslices(tiedrank, X, 1); cor(Z, Z))\n\n\n#######################################\n#\n# Kendall correlation\n#\n#######################################\n\n# Knigh JASA (1966)\n\nfunction corkendall!(x::RealVector, y::RealVector)\n if any(isnan(x)) || any(isnan(y)) return NaN end\n n = length(x)\n if n != length(y) error(\"Vectors must have same length\") end\n \n # Initial sorting\n pm = sortperm(y)\n x[:] = x[pm]\n y[:] = y[pm]\n pm[:] = sortperm(x)\n x[:] = x[pm]\n\n # Counting ties in x and y\n iT = 1\n nT = 0\n iU = 1\n nU = 0\n for i = 2:n\n if x[i] == x[i-1] \n iT += 1\n else\n nT += iT*(iT - 1)\n iT = 1\n end\n if y[i] == y[i-1]\n iU += 1\n else\n nU += iU*(iU - 1)\n iU = 1\n end\n end\n if iT > 1 nT += iT*(iT - 1) end\n nT = div(nT,2)\n if iU > 1 nU += iU*(iU - 1) end\n nU = div(nU,2)\n\n # Sort y after x\n y[:] = y[pm]\n\n # Calculate double ties\n iV = 1\n nV = 0\n jV = 1\n for i = 2:n\n if x[i] == x[i-1] && y[i] == y[i-1] \n iV += 1\n else\n nV += iV*(iV - 1)\n iV = 1\n end\n end\n if iV > 1 nV += iV*(iV - 1) end\n nV = div(nV,2)\n\n nD = div(n*(n - 1),2)\n return (nD - nT - nU + nV - 2swaps!(y)) / (sqrt(nD - nT) * sqrt(nD - nU))\nend\n\n\ncorkendall(x::RealVector, y::RealVector) = corkendall!(float(copy(x)), float(copy(y)))\n\ncorkendall(X::RealMatrix, y::RealVector) = Float64[corkendall!(float(X[:,i]), float(copy(y))) for i in 1:size(X, 2)]\n\ncorkendall(x::RealVector, Y::RealMatrix) = (n = size(Y,2); reshape(Float64[corkendall!(float(copy(x)), float(Y[:,i])) for i in 1:n], 1, n))\n\ncorkendall(X::RealMatrix, Y::RealMatrix) = Float64[corkendall!(float(X[:,i]), float(Y[:,j])) for i in 1:size(X, 2), j in 1:size(Y, 2)]\n\nfunction corkendall(X::RealMatrix)\n n = size(X, 2)\n C = eye(n)\n for j = 2:n\n for i = 1:j-1\n C[i,j] = corkendall!(X[:,i],X[:,j])\n C[j,i] = C[i,j]\n end\n end\n return C\nend\n\n# Auxilliary functions for Kendall's rank correlation\n\nfunction swaps!(x::RealVector)\n n = length(x)\n if n == 1 return 0 end\n n2 = div(n, 2)\n xl = sub(x, 1:n2)\n xr = sub(x, n2+1:n)\n nsl = swaps!(xl)\n nsr = swaps!(xr)\n sort!(xl)\n sort!(xr)\n return nsl + nsr + mswaps(xl,xr)\nend\n\nfunction mswaps(x::RealVector, y::RealVector)\n i = 1\n j = 1\n nSwaps = 0\n n = length(x)\n while i <= n && j <= length(y)\n if y[j] < x[i]\n nSwaps += n - i + 1\n j += 1\n else\n i += 1\n end\n end\n return nSwaps\nend\n\n", "meta": {"hexsha": "19c5346584cabd8ea2c68f0086371cf05b5df8a3", "size": 3238, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/rankcorr.jl", "max_stars_repo_name": "jpata/StatsBase.jl", "max_stars_repo_head_hexsha": "3148a43686962e096f3ccbc063264908e42fb2c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/rankcorr.jl", "max_issues_repo_name": "jpata/StatsBase.jl", "max_issues_repo_head_hexsha": "3148a43686962e096f3ccbc063264908e42fb2c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rankcorr.jl", "max_forks_repo_name": "jpata/StatsBase.jl", "max_forks_repo_head_hexsha": "3148a43686962e096f3ccbc063264908e42fb2c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1285714286, "max_line_length": 139, "alphanum_fraction": 0.4873378629, "num_tokens": 1161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947132556618, "lm_q2_score": 0.8856314723088733, "lm_q1q2_score": 0.8369170592247133}} {"text": "### A Pluto.jl notebook ###\n# v0.15.1\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ a6e71018-ab69-42d0-9a15-ffb477b4bd64\nbegin\n\tusing ModelingToolkit\n\tusing DifferentialEquations\n\tusing Plots\nend\n\n# ╔═╡ d4f1e3a9-d1c8-4e3e-8b88-f0a901a894f7\nmd\"\"\"\n# Symbolic ODE Modeling \n\nI recently stumbled upon the [DifferentialEquations.jl](https://github.com/SciML/DifferentialEquations.jl) and [ModelingToolkit.jl](https://github.com/SciML/ModelingToolkit.jl) which are pretty cool packages. \n\nThe idea is that we can represent ordinary differential equation models symbolically using the ModelingToolkit.jl and then use the DifferentialEquations.jl package to find our solutions.\n\nBelow will be a simple example in doing so.\n\"\"\"\n\n# ╔═╡ 656cae30-e450-11eb-266a-f7572588b91b\nmd\"\"\"\n## An example in chemical kinetics\nDetermining the concentration of species involved in reaction kinetics is done by solving a set of ordinary differential equations goverened by [law of mass action](https://en.wikipedia.org/wiki/Law_of_mass_action) which can be expressed as:\n\n```math\n\\begin{align}\n\\frac{dC_i}{dt} &= \\sum_j N_{i,j} K_j \\\\\nK_j &= k_j \\prod_k C_k^{S_j}\n\\end{align}\n```\n\nwhere $N_{i,j}$ is the net stoichiometric value of species $i$ over reactions $j$, $K_j$ is the reaction coefficient, and $S_j$ the stoichiometry of species $k$ in reaction $j$. We can solve the Robertson's 3-species reacting system:\n\n$r_1 = k_1 [A]$\n$r_2 = k_2 [B] [C]$\n$r_3 = k_3 [B]$\n\nThis corresponds to the chemical processes:\n\n$A \\rightarrow B$\n$B + C \\rightarrow A + C$\n$2B \\rightarrow B + C$\n\nOne now needs to determine the concentrations of species A, B, and C as a function of time by solving the ODEs. When a species is consumed/reacted the sign is negative and when it is produced it is positive.\n\n$\\frac{d[A]}{dt} = r_2 - r_1$\n$\\frac{d[B]}{dt} = r_1 - r_2 - r_3$\n$\\frac{d[C]}{dt} = r_3$\n\nThe neat thing is we can solve this in a few lines of code using the [ModelingToolkit.jl](https://github.com/SciML/ModelingToolkit.jl) and [DifferentialEquations.jl](https://github.com/SciML/DifferentialEquations.jl) Julia packages.\n\nThis does the same thing that the [SymPy Code generation tutorial on youtube](https://www.youtube.com/watch?v=5jzIVp6bTy0).\n\"\"\"\n\n# ╔═╡ 53eaf1ae-6d16-4606-b5d2-97fd61ac7da6\nfunction chemicalreaction_ode_solution()\n\t@parameters t k₁ k₂ k₃\n\t@variables A(t) B(t) C(t)\n\tD = Differential(t);\n\t\n\t@named eq = ODESystem([D(A) ~ -A*k₁ + B*C*k₂,\n\t\t\t D(B) ~ A*k₁ - B^2 * k₃ - B*C*k₂,\n\t\t D(C) ~ B^2 * k₃],\n\t t,[A,B,C],[k₁,k₂,k₃])\n\n\t\n\tk0 = [k₁ => 4.0e-2, k₂=>1.0e4, k₃=>3.0e7]\n\tc0 = [A => 1, B=>0, C=>0]\n\tτ = (1.0e-6,1.0e6)\n\tprob = ODEProblem(structural_simplify(eq),\n\t\t c0,τ,k0,jac=true)\n\t\n\t#Use stiff numerical integration solver\n\tsol = solve(prob, TRBDF2())\n\t\n\t#Plotting solution with Plots.jl\n\tp1 = plot(sol,vars=[A,B,C],\n\t\txaxis=:log,\n\t\tlegend=(0.35,0.35),lw=3,size=(1100,400),\n\t\ttitle=\"semi-log scale\")\n\tp2 = plot(sol,vars=[A,B,C],\n\t\txaxis=:log,yaxis=(:log,[1.0e-12,:auto]),\n\t\tlegend=(0.35,0.35),lw=3,size=(1100,400),\n\t\ttitle=\"log-log scale\")\n\ttimep = plot(p1,p2,layout=(1,2),margin=5Plots.mm,\n\t\txlabel=\"time\",ylabel=\"concentration\")\n\t\n\treturn eq,sol,timep\nend;\n\n# ╔═╡ 0267b2d1-f8da-48e8-991b-163497c0cd91\nmd\"\"\"\n!!! note\n\tCreated a function since the scope using Pluto.jl with these packages is a bit strange due to how Pluto.jl evaluates cells.\n\"\"\"\n\n# ╔═╡ 6da13129-b9f4-45c6-89fb-714200bce2d4\neqs,solution,timeplot = chemicalreaction_ode_solution();\n\n# ╔═╡ 65cd1b1f-24df-4a48-bd26-0f394bc06c1f\nmd\"\"\"\nDisplaying the equation generated by the ModelingToolkit:\n\"\"\"\n\n# ╔═╡ 367a7c95-4655-4797-a62e-0f817d527dab\neqs\n\n# ╔═╡ 56ba790d-0c78-46fb-b5b7-4711c77f4b54\nmd\"\"\"\nand now displaying the plots from the solution.\n\"\"\"\n\n# ╔═╡ efe47a33-ea39-4f58-bc26-1517427f43f8\ntimeplot\n\n# ╔═╡ 4f208f0a-7ff4-444d-b271-08f07ec31e72\nmd\"\"\"\nSo thats it! Pretty cool that we can solve this ODE so straightfowardly.\n\n\nThe thing to do is generalize the procedure to create a macro that returns an `ODESystem` for any arbitrary number of reactions and species. This would be similiar to the code below done for `SymPy.jl` but doing it using these packages. \n\n```julia\nusing SymPy\n\nstruct RXN \n\tcoeff::String\n\treactants::Dict\n\tproducts::Dict\nend\n\nfunction getequations(species::Tuple,reactions::Array{RXN})\n\tsymspecies = symbols(join(species,\" \"),real=true,nonnegative=true)\n\tdicspecies = Dict(zip(species,symspecies))\n\tdequations = Dict(s=>Sym(0) for s in species)\n\tcoeffs = Array{Sym}(undef,length(reactions))\n\tfor (i,reaction) in enumerate(reactions)\n\t\tcoeffs[i] = symbols(reaction.coeff)\n\t\tprodstoich = prod([dicspecies[s]^p for (s,p) in reaction.reactants])\n\t\tr = coeffs[i]*prodstoich\n\t\tfor (name,stoich) in reaction.products\n\t\t\tdequations[name] += stoich*r\n\t\tend\n\tend\n\t#Generate array of equations rather than dictionary\n\tequations = [dequations[s] for s in species]\n\treturn (equations,symspecies,coeffs)\nend;\n```\n\"\"\"\n\n# ╔═╡ 4d326031-3ec0-4faa-b6d2-531add859e06\nhtml\"\"\"\n\"\"\"\n\n# ╔═╡ bcbed56c-0c94-11eb-0e8c-2de8d1a20f47\nmd\"\"\"\n\n# Simulation - a small intro\n\n\n## General approach\nWhen a simulation is used to answer a question or to solve a problem, the following steps are involved:\n* Formulate the problem and plan the study\n* Collect the data and formulate the simulation model\n* Check the accuracy of the simulation model (assumptions, limitations etc.)\n* Construct a computer program\n* Test the validity of the simulation model\n* Plan the simulations to be performed\n* Conduct the simulation runs and analyze the results\n* Present the conclusions\n\nDuring this practical session, we will run small simulations going over all these steps.\n\n\n\"\"\"\n\n# ╔═╡ 349b8586-0c96-11eb-2e7b-5b3230d1cf27\nmd\"\"\"\n## Casino game\nA casino offers a coin flipping game with the following rules:\n1. Each play of the game involves repeatedly flipping an unbiased coin \n2. The game stops when the difference between the number of heads tossed and the number of tails is 3\n3. If you decide to play, each flip costs you € 1. You are not allowed to quit during a play of the game.\n4. You receive € 8 at the end of each play of the game.\n\n\nThe problem at hand is to decide whether to play or not and to get an idea of the expected gains and the length of each game. We might also look into the required simulation size and into a parametric study (e.g. influence of the required difference between heads/tails and/or the default gain).\n\n*Tip:* it can be analytically proven that the true mean of the number of flips required for a play of this game is 9. \n\n\n##### Steps in the simulation process\n\n###### Formulate the problem and plan the study:\nthe problem is described in a clear way (cf. suppra). Given these rules, we want to find out\n1. if it is a good idea to play\n2. the value of the expected profit\n\n###### Collect the data and formulate the simulation model:\nLet $X$ be the outcome of one coin flip $\\Rightarrow X\\sim \\mathcal{Be}(1/2)$\n\n###### Check the accuracy of the simulation model:\nOur model is complete, we make no assumptions\n\n###### Construct a computer program\n\"\"\"\n\n# ╔═╡ 3a20552e-0c97-11eb-3f0d-2586b1bb46ed\nbegin\n\t\"\"\"\n\t\tgame(limit::Int=3)\n\t\n\tPlay a game for a given limit. Returns a dict with the scores and the game length\n\t\"\"\"\n\tfunction game(limit::Int=3)\n\t\td = Dict(\"heads\"=>0, \"tails\"=>0, \"length\"=>0)\n\t\twhile abs(d[\"heads\"] - d[\"tails\"]) < limit \n\t\t\td[\"length\"] += 1\n\t\t\tif rand()<=1/2\n\t\t\t\td[\"heads\"]+=1\n\t\t\telse\n\t\t\t\td[\"tails\"]+=1\n\t\t\tend\n\t\tend\n\t\t\n\t\treturn d\n\tend\n\t\n\t\"\"\"\n\t\tsim(N::Int=1000; limit::Int=3)\n\t\n\trun a simulation of the game. \n\t\"\"\"\n\tfunction sim(N::Int=1000; limit::Int=3, gain::Real=8)\n\t\tL = Array{Int64,1}()\n\t\tG = Array{Int64,1}()\n\t\tfor _ in 1:N\n\t\t\tg = game(limit)\n\t\t\tpush!(L,g[\"length\"])\n\t\t\tpush!(G,gain - g[\"length\"])\n\t\tend\n\t\t\n\t\treturn L,G\n\tend\n\n\tnothing\nend\n\n# ╔═╡ b1bae776-0dfe-11eb-291b-53f9a87c4a41\n# other method of creating a game\nbegin\n\tmutable struct Game\n\t\theads::Int\n\t\ttails::Int\n\t\tlength::Int\n\tend\n\t\n\tfunction play!(g::Game, limit::Int=3)\n\t\twhile abs(g.heads - g.tails) < limit \n\t\t\tg.length += 1\n\t\t\tif rand()<=1/2\n\t\t\t\tg.heads += 1\n\t\t\telse\n\t\t\t\tg.tails += 1\n\t\t\tend\n\t\t\t\n\t\tend\n\t\t\n\t\treturn g\n\tend\n\t\n\tg = Game(0,0,0)\n\tplay!(g)\nend\n\n# ╔═╡ 65c6476c-0c98-11eb-2c7d-3bc3ba8d51e2\nmd\"\"\"\n###### Test the validity of the simulation model\nA game should stop when the difference between the amount of heads and tails equals 3\n```julia\nbegin \n\tg = game()\n\t@assert abs(g[\"heads\"] - g[\"tails\"]) == 3\nend\n```\n\"\"\"\n\n# ╔═╡ 5b08b538-0c97-11eb-0319-877b39c4c4ed\nmd\"\"\"\n###### Plan the simulations to be performed\nWe will run a certain number of simulations. At this time we do not have additional information that we can use (optimal number to be determined later).\n\"\"\"\n\n# ╔═╡ 607e4392-0c98-11eb-0a9d-ddfab6b42b26\nmd\"\"\"\n###### Conduct the simulation runs and analyze the results\n\"\"\"\n\n# ╔═╡ 75d35828-0c99-11eb-1888-e9e7be234e89\nbegin\n\t# get data for game length and gains\n\tL,G = sim()\nend;\n\n# ╔═╡ fae1e448-0c98-11eb-3721-dddb169e403f\n# show results\nplot(histogram(L,xlabel=\"Game length\"),histogram(G,xlabel=\"Gains\"),\n label=\"\",grid=false,ylabel=\"Frequency\",size=(600,250) ,bottom_margin=5mm)\n\n# ╔═╡ a39a3a72-0c99-11eb-00df-e92eb7a6ce07\nplot([boxplot(L,ylabel=\"Game length\", ylims=(0,maximum(L)+4)),\n\t boxplot(G,ylabel=\"Gains\")]...,\n label=\"\",grid=false,size=(300,250),xaxis=false)\n\n# ╔═╡ ac87cb8a-0c9a-11eb-21d5-9981e408db29\nmd\"\"\"\n#### Simulation length\nUp to now we have worked with a simulation length 1000. We have no idea about the variation of each simulation result. We investigate this in order to find out how simulation length impacts our estimate.\n\"\"\"\n\n# ╔═╡ 1aa54e8a-0c9b-11eb-3b7c-f3be005991df\nbegin\n\t# evolution of the mean in function of the sample length\n\tx = Array{Int,1}()\n\ty = Array{Float64,1}()\n\tntests = 30\n\tfor N in 10 .^(1:5)\n\t\tfor _ in 1:ntests\n\t\t\t(L,_) = sim(N,limit=3)\n\t\t\tpush!(x,N)\n\t\t\tpush!(y,mean(L))\n\t\tend\n\tend\nend\n\n# ╔═╡ 3236977a-0c9b-11eb-3875-2304eaec0a8e\nbegin\n\tscatter(x,y,xscale=:log10,\n\t\t\txlabel=\"Number of games per simulation\",\n\t\t\tylabel=\"Average game length\",title=\"\",label=\"\")\n\tplot!(x,9*ones(size(x)),color=:red,label=\"\")\n\ttitle!(\"Towards optimal simulation length\\n (30 datapoints per config)\")\nend\n\n# ╔═╡ 7fafde70-0c9c-11eb-0403-9bfb6e42045b\nmd\"\"\"\n#### Parametric study\nsuppose we consider a range of differences [2,4] and a range of gains [4, 12] where we play 1e5 games for each config.\n\"\"\"\n\n# ╔═╡ c8b107ba-0c9d-11eb-11c7-830d112ca82f\nlet\n\tΔ = 1:5\n\tΓ = 0:15\n\tN = Int(1e5)\n\tres = []\n\ti = 1\n\tfor d in Δ\n\t\tfor g in Γ\n\t\t\t_,G = sim(N; limit=d, gain=g)\n\t\t\tpush!(res, mean(G))\n\t\tend\n\tend\n\tblup = reshape(res,:,length(Δ))\n\tp1 = heatmap(Δ, Γ, blup, xlabel=\"diff\", ylabel=\"guaranteed gain\", title=\"mean gain\")\n\tp2 = heatmap(Δ, Γ, blup .>= 0, xlabel=\"diff\", ylabel=\"guaranteed gain\", title=\"positive gain\")\n\tplot(p1,p2, size=(600, 300))\nend\n\n# ╔═╡ 0bfa3ffe-0c9a-11eb-2c99-3d8e57983c4c\nmd\"\"\"\n###### Present the conclusions\nWe find that on average a game takes 9 turns, which will lead you to lose on average € 1. The game could be tempting given that in six out of ten cases the player will actually win (a small amount).\n\"\"\"\n\n# ╔═╡ 8df49b7e-0c9e-11eb-0048-9368c9d7bee9\nmd\"\"\"\n## Project management\nSuppose we want to simulate a industrial process that can be presented as the table shown below:\n\n| Activity | Predecessors | Completion time |\n|----------|--------------|---------------- |\n| A | - | $\\sim \\mathcal{N}(6,1)$ |\n| B | A | $\\sim \\mathcal{U}(6,10)$ |\n| C | A | $\\sim \\mathcal{U}(1.5,2.5)$ |\n| D | B,C | $\\sim \\mathcal{U}(1.5,3)$ |\n| E | D | $\\sim \\mathcal{U}(3,6)$ |\n| F | E | $\\sim \\mathcal{U}(2,5)$ |\n| G | E | $\\sim \\mathcal{U}(3,5)$ |\n| H | F,G | $\\sim \\mathcal{U}(4,7)$ |\n| I | H | $\\sim \\mathcal{U}(5,7)$ |\n| J | H | $\\le 5$ |\n\nWe want to get an idea of:\n1. the mean project completion time\n2. the probability that the project will be finished in less than 36 time units\n3. determine the critical subprocesses with a sensitivity chart (i.e. determine the impact of changing a specific subprocess on the completion time given all the others remain the same)\n\n\"\"\"\n\n# ╔═╡ 7aceebea-0d1d-11eb-05fa-d7374004b881\nmd\"\"\"\n###### Formulate the problem and plan the study\nThe problem and the tasks are described above\n\n###### Collect the data and formulate the simulation Model\nData model (coming from historical data) is known. The duration can be obtained from the a vector of duration times.\n\n###### Construct a computer program\n\"\"\"\n\n# ╔═╡ 8f99cf60-0c9e-11eb-2b6d-b5ca5ed20a65\nbegin\n\t# completion time distributions\n\tD = [Normal(6,1); \n\t\tUniform(6,10); \n\t\tUniform(1.5,2.5); \n\t\tUniform(1.5,4); \t\t \t\t\n\t\tUniform(3,6);\n\t\tUniform(2,5); \n\t\tUniform(3,5); \n\t\tUniform(4,7); \n\t\tUniform(5,7); \n\t\tUniform(0,5)]\n\t\n\t# central positions (for sensitivity analysis)\n\tp = [6; 8; 2; 2.25; 4.5; 3.5; 4; 5.5; 6; 2.5]\n\t\"\"\"\n\t\t duration(t::Array)\n\n\tgenerate a random sample from an array of distributions for the production process\n\t\"\"\"\n\tfunction duration(t::Array)\n\t\tt[1] + max(t[2],t[3]) + t[4] + t[5] + max(t[6], t[7]) + t[8] + max(t[9], t[10])\n\tend\n\t\n\t\"\"\"\n\t\tPM(N::Int)\n\t\n\tRun a Project Management simulation N times that returns a vector of duration times\n\t\"\"\"\n\tfunction PM(D::Array, N::Int=100)\n\t\t# Generate data\n\t\tS = [rand.(D) for _ in 1:N]\n\t\t# get durations\n\t\treturn map(duration, S)\n\tend\n\n\tnothing;\nend\n\n# ╔═╡ 864b050c-0d1e-11eb-03d8-8ffcf23e019e\nmd\"\"\"\n###### Check the accuracy of the simulation model (assumptions, limitations etc.)\nWe use a normal distribution for the first activity, so it is theoretically possible that a negative value for A occurs, which does not make sense. In a similar way, using a uniform distribution sets hard limits for task durations.\n\nYou can make testcases to assert the correctness of the result calculated by the duration function.\n\"\"\"\n\n# ╔═╡ f9562612-0d1e-11eb-1e16-bfa53760c18c\nbegin \n\tv = [0 0 1 0 0 1 0 0 0 0] \n\t@assert duration(v) == 2\nend\n\n# ╔═╡ d18a68b2-0d20-11eb-0f39-150f9bc9e0e9\nmd\"\"\"\n###### Plan the simulations to be performed\nWe will generate a sample of a given length an look at the experimental CDF.\n\"\"\"\n\n# ╔═╡ da7801bc-0ca0-11eb-0480-33f07e16c85b\nlet\n\t# idea mean value\n\tN = 1000; x = 36;\n\tres = PM(D,N)\n\tavg_D = mean(res)\n\t# CDF\n\tp1 = StatsPlots.cdensity(res,label=\"Experimental CDF\",legend=:bottomright)\n\ttitle!(\"P(X <= $(x)): $(sum(res .< x)/N)\")\n\t\n\tplot!([avg_D; avg_D], [0; 1], line=:dash, label=\"mean duration $(round(avg_D,digits=2))\")\n\tylabel!(\"F_{X}(x) \")\n\txlabel!(\"duration\")\n\t# PDF\n\tp2 = StatsPlots.density(res, label=\"Experimental PDF\")\n\txlabel!(\"duration\")\n\tylabel!(\"f_{X}(x)\")\n\t# total plot\n\tplot(p1, p2)\nend\n\n# ╔═╡ 3d5f9648-0d21-11eb-14c4-65704b349ed6\nmd\"\"\"\n###### Conduct the simulation runs and analyze the results\nWe have obtained the results. We can do some additional testing such as validating the normality of our simulation data. \n\n\nThe sensitivity analysis can be done by changing one-factor-at-a-time (OAT), to see what effect this produces on the output. I.e. we move one input variable, keeping others at their baseline (nominal) values and repeat this for each of the other inputs in the same way.\n\"\"\"\n\n# ╔═╡ d8b821a0-0d21-11eb-08bc-f7027b1cbea1\nbegin\n\ts = PM(D,1000)\n\tHypothesisTests.ExactOneSampleKSTest(s,Normal(mean(s),std(s)))\nend\n\n# ╔═╡ d89eb800-0d21-11eb-29d9-c119c9347dbc\nbegin \n\t\"\"\"\n\t\tsensitivity(D, p, i::Int, N::Int=1000)\n\t\n\tGenerate a sample where all values keep their baseline values with the exception of component i\n\t\"\"\"\n\tfunction sensitivity(D, p, i, N::Int=1000)\n\t\t# generate data\n\t\tdata = [[p[1:i-1]; rand(D[i]); p[i+1:end]] for _ in 1:N]\n\t\t# return durations\n\t\tmap(duration,data)\n\tend\n\t\n\tblup = [sensitivity(D,p, i) for i in 1:10]\n\tStatsPlots.boxplot(blup, label=\"\")\n\txlabel!(\"process step\")\n\tylabel!(\"duration boxplot\")\n\tylims!(30,40)\n\txlims!(0,11)\n\txticks!(collect(1:10))\n\ttitle!(\"Sensitivity analysis\")\nend\n\n# ╔═╡ d148f3ea-0d21-11eb-2d67-f1f4c77248d5\nmd\"\"\"\n###### Present the conclusions\nWith respect to the initial goals, we can conclude the following:\n* the mean project completion time is around 37 time units\n* the probability that the project will be finished in less than 36 time units is around 34%\n* processes 3 and 10 do not impact the total project duration. Steps two and four account for the largest variability.\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─86a87f27-7b57-4420-8cef-836ac531a254\n# ╠═b77c944b-88e4-421d-a629-0d96bf95ea70\n# ╟─bcbed56c-0c94-11eb-0e8c-2de8d1a20f47\n# ╟─349b8586-0c96-11eb-2e7b-5b3230d1cf27\n# ╠═3a20552e-0c97-11eb-3f0d-2586b1bb46ed\n# ╠═b1bae776-0dfe-11eb-291b-53f9a87c4a41\n# ╟─65c6476c-0c98-11eb-2c7d-3bc3ba8d51e2\n# ╟─5b08b538-0c97-11eb-0319-877b39c4c4ed\n# ╟─607e4392-0c98-11eb-0a9d-ddfab6b42b26\n# ╠═75d35828-0c99-11eb-1888-e9e7be234e89\n# ╠═fae1e448-0c98-11eb-3721-dddb169e403f\n# ╠═a39a3a72-0c99-11eb-00df-e92eb7a6ce07\n# ╟─ac87cb8a-0c9a-11eb-21d5-9981e408db29\n# ╠═1aa54e8a-0c9b-11eb-3b7c-f3be005991df\n# ╠═3236977a-0c9b-11eb-3875-2304eaec0a8e\n# ╟─7fafde70-0c9c-11eb-0403-9bfb6e42045b\n# ╠═c8b107ba-0c9d-11eb-11c7-830d112ca82f\n# ╟─0bfa3ffe-0c9a-11eb-2c99-3d8e57983c4c\n# ╟─8df49b7e-0c9e-11eb-0048-9368c9d7bee9\n# ╟─7aceebea-0d1d-11eb-05fa-d7374004b881\n# ╠═8f99cf60-0c9e-11eb-2b6d-b5ca5ed20a65\n# ╟─864b050c-0d1e-11eb-03d8-8ffcf23e019e\n# ╠═f9562612-0d1e-11eb-1e16-bfa53760c18c\n# ╟─d18a68b2-0d20-11eb-0f39-150f9bc9e0e9\n# ╠═da7801bc-0ca0-11eb-0480-33f07e16c85b\n# ╟─3d5f9648-0d21-11eb-14c4-65704b349ed6\n# ╠═d8b821a0-0d21-11eb-08bc-f7027b1cbea1\n# ╠═d89eb800-0d21-11eb-29d9-c119c9347dbc\n# ╟─d148f3ea-0d21-11eb-2d67-f1f4c77248d5\n", "meta": {"hexsha": "7339026d8ea70fd1ce0c4ebed0156b28c43c57f9", "size": 14047, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Exercises/PS06 - Intro simulation.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/PS06 - Intro simulation.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/PS06 - Intro simulation.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": 29.6976744186, "max_line_length": 295, "alphanum_fraction": 0.6825656724, "num_tokens": 5075, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9252299550303295, "lm_q2_score": 0.8856314692902446, "lm_q1q2_score": 0.8194127645048577}} {"text": "using StatisticalRethinking, DataFrames, NamedArrays, OrderedCollections\n\nna = NamedArray(\n [18 134 152; 3 4 7; 21 138 159], \n ( [:vaccinated, :unvaccinated, :total], \n [:varicella, :noninfected, :total]\n ),\n (\"Rows\", \"Cols\")\n)\n\nna |> display\nprintln()\n\n# Risk of varicella among vaccinated children = 18 / 152 = 0.118 = 11.8%\n\nrisk_vac = na[:vaccinated, :varicella] / na[:vaccinated, :total]\n\n# Risk of varicella among unvaccinated children = 3 / 7 = 0.429 = 42.9%\n\nrisk_unvac = na[:unvaccinated, :varicella] / na[:unvaccinated, :total]\n\n# Risk ratio = 0.118 / 0.429 = 0.28\n\nrr = risk_vac / risk_unvac\n\n# EXAMPLE: Calculating Vaccine Effectiveness\n# Calculate the vaccine effectiveness from the varicella data in Table 3.13.\n\n# VE = (42.9 – 11.8) / 42.9 = 31.1 / 42.9 = 72%\n\nve = (risk_unvac - risk_vac) /risk_unvac\n\n# Alternatively, VE = 1 – RR = 1 – 0.28 = 72%\n\n1 - rr |> display\n\n# So, the vaccinated group experienced 72% fewer varicella cases\n# than they would have if they had not been vaccinated.\n\ndf_covid = DataFrame(\n :completed => [true, true, false, false],\n :company => [:pfizer, :moderna, :jj, :astra],\n :unvaccinated => [18261, 15000, missing, missing],\n :vaccinated => [18262, 15000, missing, missing],\n :inf_unv => [162, 185, missing, missing],\n :inf_vac => [8, 11, missing, missing]\n)\n\ndf_covid |> display\n\ndf = df_covid[df_covid.completed, :]\n", "meta": {"hexsha": "96225afb6e0aa751aa7ec850e3a93b00aacc1bad", "size": 1402, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/varicella.jl", "max_stars_repo_name": "goedman/CovidNYT.jl", "max_stars_repo_head_hexsha": "4fda8a920a9d25241d6a96b0d3ca52b9b2f8add1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/varicella.jl", "max_issues_repo_name": "goedman/CovidNYT.jl", "max_issues_repo_head_hexsha": "4fda8a920a9d25241d6a96b0d3ca52b9b2f8add1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/varicella.jl", "max_forks_repo_name": "goedman/CovidNYT.jl", "max_forks_repo_head_hexsha": "4fda8a920a9d25241d6a96b0d3ca52b9b2f8add1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9615384615, "max_line_length": 76, "alphanum_fraction": 0.6569186876, "num_tokens": 482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299509069106, "lm_q2_score": 0.8856314632529872, "lm_q1q2_score": 0.8194127552671768}} {"text": "# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n# jupytext:\n# text_representation:\n# extension: .jl\n# format_name: light\n# format_version: '1.5'\n# jupytext_version: 1.4.2\n# kernelspec:\n# display_name: Julia 1.4.1\n# language: julia\n# name: julia-1.4\n# ---\n\n# # ヒストグラム平坦化\n\n# # 準備\n\n# ## Load Julia Packages\n\nusing Images\nusing TestImages\nusing Plots\n\n# ## read testimage\n\nc = testimage(\"c\")\n\n# ## Visualize gray scale image histogram\n\ndata=reshape(255 .* channelview(c),prod(size(c)))\nhistogram(data, bins=0:255,normalize=:pdf)\n\n# ## Visualize cumulative distribution function (so called CDF)\n\n# +\ni2c = Dict{Int,Int}()\nfor i in 0:255\n i2c[i] = 0 \nend\n\nfor i in Int.(255 .* channelview(c))\n i2c[i] += 1\nend\n# -\n\narr = [i2c[i] for i in 0:255]\ncdf = [sum(arr[begin:i]) for i in 1:length(arr)]\nplot(cdf./length(c), label=\"CDF\")\n\n# # Histogram Equalization\n\n# - $q$ を画像の輝度の分布を表す確率密度関数とする. ヒストグラムを平坦化することは分布が(なるべく)一様分布に近似されれば良い.つまり累積分布関数が $y=ax$ のように原点と積分範囲の右端(画像であれば255=256-1)で $y=1$ となる一次関数になっていれば良い. \n# - 今述べたことを定式化する. $X$ を画像の分布を表す確率変数だとする. $Y$ をヒストグラム平坦化により得られら分布とし滑らかに $Y=f(X)$ と変化したとする. さらに変換が可逆だと仮定する. $p$ を $Y$ の確率密度函数とすれば, 次のことを要請する.\n#\n# $$\n# \\frac{y}{255} = \\int_{0}^{y} p(\\tilde{y})d\\tilde{y} \n# $$\n\n# 一般に $Y=f(X)$ と変換された確率変数の確率密度関数 $p$ は\n#\n# $$\n# p(y) = \\int \\delta(y-f(x))q(x)dx\n# $$\n#\n# である. この一般論を上式の右辺に適用すれば $p(y) = \\frac{q(x)}{f'(x)}\\ \\mathrm{where}\\ y=f(x)$ が従う.\n#\n# $$\n# \\begin{aligned}\n# \\frac{1}{255} &= \\frac{d}{dy}\\left(\\frac{y}{255}\\right) \\\\\n# &= \\frac{d}{dy}\\int_{0}^{y} p(\\tilde{y})d\\tilde{y} \\\\\n# &= p(y) \\\\\n# &= \\frac{q(x)}{f'(x)}\\ \\mathrm{where}\\ y=f(x) \\\\\n# \\end{aligned}\n# $$\n#\n# よって\n#\n# $$\n# f'(x) = 255q(x)\n# $$\n#\n# 要するに欲しい変換は累積分布函数に255(確率変数 $X$ がとる最大値) を乗じたものである.\n#\n# $$\n# f(x) = 255 \\int_{0}^x q(\\tilde{x}) d\\tilde{x}\n# $$\n#\n# これを画像処理に適用することを考えると積分は離散和になる. $q(x)$ は輝度が$x\\in [0, 255]$である確率になる. 平たくいうと $x$ での(正規化された)ヒストグラムの値である.これを踏まえて下記のように実装をしてみよう.\n\nn_pixels = length(c)\nfunction hist_eq(p)\n s = 0\n for i in 0:p\n s+=i2c[i]\n end\n floor(255*s/n_pixels)\nend\n\nnew_c=hist_eq.(255 .* channelview(c))\n\ncolorview(Gray, new_c./255)\n\nhistogram(new_c[:], normalize=:pdf, bins=0:255)\n\n# +\nnew_i2c = Dict{Int,Int}()\nfor i in 0:255\n new_i2c[i] = 0 \nend\n\nfor i in new_c\n new_i2c[i] += 1\nend\n# -\n\n# # 結果の確認\n\narr = [new_i2c[i] for i in 0:255]\ncdf = [sum(arr[begin:i]) for i in 1:length(arr)]\nplot(cdf./length(c))\n# 直線になっている様子がわかるはず\n", "meta": {"hexsha": "20401df0f9b2b814caa3ed5c8e169eddc4a107d6", "size": 2454, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "experiments/notebook/histogram_eq.jl", "max_stars_repo_name": "nash1111/MyWorkflow.jl", "max_stars_repo_head_hexsha": "027f8a176f473bb355d2cd28b881dd55f06f3526", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "experiments/notebook/histogram_eq.jl", "max_issues_repo_name": "nash1111/MyWorkflow.jl", "max_issues_repo_head_hexsha": "027f8a176f473bb355d2cd28b881dd55f06f3526", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-09-06T12:34:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-06T12:39:46.000Z", "max_forks_repo_path": "experiments/notebook/histogram_eq.jl", "max_forks_repo_name": "hsugawa8651/MyWorkflow.jl", "max_forks_repo_head_hexsha": "48edcbcc3fd9e425895ef91bea833ef1e5d4c3fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.7903225806, "max_line_length": 144, "alphanum_fraction": 0.5969845151, "num_tokens": 1308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.9099069968764883, "lm_q1q2_score": 0.8193983532843583}} {"text": "# 'cstrt_reinhardt_ngon' provides the vertices coordinates (a,b) of a\r\n# Reinhardt (m*k)-gon\r\nfunction cstrt_reinhardt_ngon(m,k)\r\nif mod(m,2) == 1 && m>=3 && k>=1\r\n a = zeros(m*k-1); b = zeros(m*k-1);\r\n for i = 1:m-1\r\n a[i*k] = sin(2*pi*i/m)/(2*cos(pi/(2*m)));\r\n b[i*k] = (1 - cos(2*pi*i/m))/(2*cos(pi/(2*m)));\r\n end\r\n if k>1\r\n for j = 1:k-1\r\n a[Int(k*(m-1)/2+j)] = cos((1+(m-3)/2+j/k)*(pi/m));\r\n b[Int(k*(m-1)/2+j)] = sin((1+(m-3)/2+j/k)*(pi/m));\r\n for i = 1:Int((m-1)/2)\r\n a[Int((i+(m-1)/2)*k+j)] = a[i*k] + cos((2*i+1+(m-3)/2+j/k)*(pi/m));\r\n b[Int((i+(m-1)/2)*k+j)] = b[i*k] + sin((2*i+1+(m-3)/2+j/k)*(pi/m));\r\n a[Int(m*k-((i+(m-1)/2)*k+j))] = -a[Int((i+(m-1)/2)*k+j)];\r\n b[Int(m*k-((i+(m-1)/2)*k+j))] = b[Int((i+(m-1)/2)*k+j)];\r\n end\r\n end\r\n end\r\n return(a,b)\r\nend\r\nend", "meta": {"hexsha": "3a83568e7d60bbd6be2a0a51318ddbfc3b5555ee", "size": 923, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "cstrt_ngon/cstrt_reinhardt_ngon.jl", "max_stars_repo_name": "cbingane/optigon", "max_stars_repo_head_hexsha": "f585de7a2b01ff1e7a15c566596a7ba8f77f782a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cstrt_ngon/cstrt_reinhardt_ngon.jl", "max_issues_repo_name": "cbingane/optigon", "max_issues_repo_head_hexsha": "f585de7a2b01ff1e7a15c566596a7ba8f77f782a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cstrt_ngon/cstrt_reinhardt_ngon.jl", "max_forks_repo_name": "cbingane/optigon", "max_forks_repo_head_hexsha": "f585de7a2b01ff1e7a15c566596a7ba8f77f782a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4583333333, "max_line_length": 84, "alphanum_fraction": 0.3932827736, "num_tokens": 380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9732407168145568, "lm_q2_score": 0.8418256412990658, "lm_q1q2_score": 0.8192989905707768}} {"text": "#=\nP34 (**) Calculate Euler's totient function phi(m).\nEuler's so-called totient function phi(m) is defined as the number of positive integers r (1 <= r < m) that are coprime to m.\nExample: m = 10: r = 1,3,7,9; thus phi(m) = 4. Note the special case: phi(1) = 1.\n\n* (totient-phi 10)\n4\n\nFind out what the value of phi(m) is if m is a prime number. Euler's totient function plays an important role in one of the most widely used public key cryptography methods (RSA). In this exercise you should use the most primitive method to calculate this function (there are smarter ways that we shall discuss later).\n=#\n\n# From P32 but more terse\nfunction gcd(a, b)\n b == 0 ? a : gcd(b, mod(a, b))\nend\n\n# From P33\nfunction coprime(a, b)\n gcd(a, b) == 1\nend\n\nfunction totient_phi(m)\n # Starting at 2, not 1 (special case)\n coprime_to_m = filter(r -> coprime(r, m), 2:m)\n length(coprime_to_m) + 1\nend\n\n@assert totient_phi(10) == 4\n\nprintln(\"Tests passed: JL-34.jl\")\n", "meta": {"hexsha": "4930b955100a721aa9ce2e256970e57069b62ae4", "size": 967, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "JL-34.jl", "max_stars_repo_name": "microamp/jl-99", "max_stars_repo_head_hexsha": "5d49a7e1617394e6cbc06f1a94fe6230b3025d73", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "JL-34.jl", "max_issues_repo_name": "microamp/jl-99", "max_issues_repo_head_hexsha": "5d49a7e1617394e6cbc06f1a94fe6230b3025d73", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "JL-34.jl", "max_forks_repo_name": "microamp/jl-99", "max_forks_repo_head_hexsha": "5d49a7e1617394e6cbc06f1a94fe6230b3025d73", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1935483871, "max_line_length": 318, "alphanum_fraction": 0.6866597725, "num_tokens": 302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.957277806109987, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.8192873136049853}} {"text": "using DifferentialEquations\nusing Plots\n\n\nmicro_1 = @ode_def Micro1 begin\n dS = r*(1-S/K)*S - β*S*I\n dI = β*S*I-(μ+α)*I\n end β r μ K α\n\nw = 1;\nm = 10;\nβ = 0.0247*m*w^0.44;\nr = 0.6*w^-0.27;\nμ = 0.4*w^-0.26;\nK = 16.2*w^-0.7;\nα = (m-1)*μ;\n\nparms = [β,r,μ,K,α];\ninit = [K,1.];\ntspan = (0.0,10.0);\n\nsir_prob = ODEProblem(micro_1,init,tspan,parms)\n\nsir_sol = solve(sir_prob);\n\n# Plot\nplot(sir_sol,xlabel=\"Time\",ylabel=\"Number\")\n\nm = [5,10,20,40]\nws = 10.^linspace(-3,3,601)\nβs = zeros(601,4)\nfor i = 1:4\n βs[:,i] = 0.0247*m[i]*ws.^0.44\nend\n\n# Plot\nplot(ws,βs,xlabel=\"Weight\",ylabel=\"\\\\beta_min\", xscale=:log10,yscale=:log10, label=[\"m = 5\" \"m = 10\" \"m = 20\" \"m = 40\"],lw=3)\n", "meta": {"hexsha": "96c4eed77f2f33f68e20451f730b17e55ca7148f", "size": 680, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "models/simple_deterministic_models/scaling/scaling.jl", "max_stars_repo_name": "epimodels/epicookbook", "max_stars_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/simple_deterministic_models/scaling/scaling.jl", "max_issues_repo_name": "epimodels/epicookbook", "max_issues_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/simple_deterministic_models/scaling/scaling.jl", "max_forks_repo_name": "epimodels/epicookbook", "max_forks_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-10T12:46:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-10T12:46:31.000Z", "avg_line_length": 17.8947368421, "max_line_length": 125, "alphanum_fraction": 0.5720588235, "num_tokens": 325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778012346835, "lm_q2_score": 0.8558511506439707, "lm_q1q2_score": 0.8192873076726341}} {"text": "using Plots\nusing LaTeXStrings\n\n# Probability of v±dv\np(v;m=1.,R=8.3145,T=298.15) = m/(R*T) * v * exp(-m*v^2/(2R*T)) \n\n# Probability of v < x, given m and T\npcum(x;m = 1., T = 298.15, R = 8.3145) = -exp(-m*x^2/(2*R*T)) + 1\n\n# Inverse Cumulative Probability of v < x, given m and T\npinv(x;m=1., T=298.15, R=8.3145) = sqrt(-(2*R*T/m)*log(1-x))\n\n# Start plot\nplot(layout=(1,2))\n\n# Collect x\nx = collect(0:0.1:200)\n\n# Set y with m = 1, T = 298.15K, R = 8.3145 J/Kmol\ny = pcum.(x)\n\n# plot\nplot!(x,y,label=\"\",subplot=1)\nplot!(xlabel=L\"x / m s^{-1}\",ylabel=L\"p~(vones(n)) # ones on main diagonal, zeros elsewhere\nU = float(copy(A))\n\n# Gaussian elimination\nfor j = 1:n-1\n for i = j+1:n\n L[i,j] = U[i,j] / U[j,j] # row multiplier\n U[i,j:n] -= L[i,j]*U[j,j:n]\n end\nend\n\nreturn L,triu(U)\nend\n", "meta": {"hexsha": "677257d71d6186b7f2ad22d1282f7cf841058111", "size": 953, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chapter02.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/chapter02.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/chapter02.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": 15.6229508197, "max_line_length": 64, "alphanum_fraction": 0.5834207765, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572777987970316, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.8192872985470987}} {"text": "\r\nfunction simp13(f,a,b,h)\r\n t = collect(Float64,a:h:b)\r\n oddsum, evensum = 0,0 #initialize\r\n for j in 2:2:(length(t) -1)\r\n oddsum += f(t[j])\r\n end\r\n for j in 3:2:(length(t) -1)\r\n evensum += f(t[j])\r\n end\r\n I = (b-a)* ( f(t[1]) + 4*oddsum + 2*evensum + f(t[end]) )/(3*(length(t)-1))\r\n return I\r\nend\r\n\r\nfunction simp38(f,a,b,h)\r\n t = collect(Float64,a:h:b)\r\n return (b-a)/8*( f(t[1]) + 3*f(t[2]) + 3*f(t[3]) + f(t[4]) )\r\nend\r\n\r\nfunction testsimp2(f,a,b,h)\r\n t = collect(Float64,a:h:b)\r\n if mod(length(t)-1,2) == 0 #i.e. we have an even number of intervals\r\n return simp13(f,a,b,h)\r\n else #i.e. we have an odd number of intervals\r\n I1 = simp13(f,a,t[end-3],h)\r\n I2 = simp38(f,t[end-3],b,h)\r\n return I1 + I2\r\n end\r\nend\r\n\r\n#This seems to be the fastest\r\nfunction intsimp(f,a,b,h)\r\n t = collect(Float64,a:h:b)\r\n\r\n if mod(length(t)-1,2) == 0 #i.e. we have an even number of intervals\r\n oddsum, evensum = 0,0 #initialize\r\n for j in 2:2:(length(t) -1)\r\n oddsum += f(t[j])\r\n end\r\n for j in 3:2:(length(t) -1)\r\n evensum += f(t[j])\r\n end\r\n I = (b-a)* ( f(t[1]) + 4*oddsum + 2*evensum + f(t[end]) )/(3*(length(t)-1))\r\n return I\r\n else #i.e. we have an odd number of intervals\r\n # First we need to calculate the simpson 1/3 up until... end-3\r\n # since we have N-3 points for simpson 1/3 and N-4 intervals\r\n oddsum, evensum = 0,0 #initialize\r\n for j in 2:2:(length(t) - 4)\r\n oddsum += f(t[j])\r\n end\r\n for j in 3:2:(length(t) - 4)\r\n evensum += f(t[j])\r\n end\r\n I1 = (t[end-3]-a)* ( f(t[1]) + 4*oddsum + 2*evensum + f(t[end-3]) )/(3*(length(t)-4)) \r\n\r\n I2 = (b-t[end-3])/8*( f(t[end-3]) + 3*f(t[end-2]) + 3*f(t[end-1]) + f(t[end]) )\r\n\r\n return I1 + I2\r\n\r\n end\r\nend\r\n\r\n# Integration whenever a pair of vectors is given as a function, x and y\r\nfunction intsimp(x::Array{Float64,1},y::Array{Float64,1})\r\n h = abs( x[2] - x[1] )\r\n\r\n if mod(length(x)-1,2) == 0 #i.e. we have an even number of intervals\r\n oddsum, evensum = 0,0 #initialize\r\n for j in 2:2:(length(x) -1)\r\n oddsum += y[j]\r\n end\r\n for j in 3:2:(length(x) -1)\r\n evensum += y[j]\r\n end\r\n I = (x[end]-x[1])* ( y[1] + 4*oddsum + 2*evensum + y[end] )/(3*(length(x)-1))\r\n return I\r\n else #i.e. we have an odd number of intervals\r\n # First we need to calculate the simpson 1/3 up until... end-3\r\n # since we have N-3 points for simpson 1/3 and N-4 intervals\r\n oddsum, evensum = 0,0 #initialize\r\n for j in 2:2:(length(x) - 4)\r\n oddsum += y[j]\r\n end\r\n for j in 3:2:(length(x) - 4)\r\n evensum += y[j]\r\n end\r\n I1 = (x[end-3]-x[1])* ( y[1] + 4*oddsum + 2*evensum + y[end-3] )/(3*(length(x)-4)) \r\n\r\n I2 = (x[end]-x[end-3])/8*( y[end-3] + 3*y[end-2] + 3*y[end-1] + y[end] )\r\n\r\n return I1 + I2\r\n\r\n end\r\nend", "meta": {"hexsha": "f0f9de908843ef9097a07f256c12719bb7c554a6", "size": 3069, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/intsimp.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/intsimp.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/intsimp.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": 32.3052631579, "max_line_length": 95, "alphanum_fraction": 0.4903877485, "num_tokens": 1114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172673767973, "lm_q2_score": 0.8633916082162403, "lm_q1q2_score": 0.8192872055446131}} {"text": "# The Fibonacci sequence is defined by the recurrence relation:\n#\n# F_n = F_n−1 + F_n−2, where F_1 = 1 and F_2 = 1.\n# Hence the first 12 terms will be:\n#\n# F_1 = 1\n# F_2 = 1\n# F_3 = 2\n# F_4 = 3\n# F_5 = 5\n# F_6 = 8\n# F_7 = 13\n# F_8 = 21\n# F_9 = 34\n# F_10 = 55\n# F_11 = 89\n# F_12 = 144\n# The 12th term, F_12, is the first term to contain three digits.\n#\n# What is the index of the first term in the Fibonacci sequence to contain 1000\n# digits?\n\nusing ProjectEulerSolutions\n\n# There's a pattern in the number of digits in Fibonacci numbers. It appears\n# to be a new digit every 5 numbers or so. We use that to estimate the upper\n# bound for how far to generate numbers.\n#\n# map(x -> ndigits(x), fibonacci_count(48))\n# [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5,\n# 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10]\nfunction p025solution(n_digits::Integer=1)::Integer\n\n fibs = fibonacci_bound(BigInt(10)^(n_digits-1))\n n = length(fibs) + 1\n\n if ndigits(fibs[end]) < n_digits\n return n + 1\n else\n return n\n end\nend\n\np025 = Problems.Problem(p025solution)\n\nProblems.benchmark(p025, 1000)", "meta": {"hexsha": "c5367b2df857563686095c19d6a6031b35c5b4f3", "size": 1167, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/025.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/025.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/025.jl", "max_forks_repo_name": "gnujosh/julia-euler-project", "max_forks_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3695652174, "max_line_length": 79, "alphanum_fraction": 0.6281062554, "num_tokens": 502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172587090974, "lm_q2_score": 0.8633916082162403, "lm_q1q2_score": 0.8192871980609937}} {"text": "\"\"\"\n eigenvector_centrality(g)\n\nCompute the eigenvector centrality for the graph `g`.\n\nEigenvector centrality computes the centrality for a node based on the\ncentrality of its neighbors. The eigenvector centrality for node `i` is\nthe \\$i^{th}\\$ element of \\$\\\\mathbf{x}\\$ in the equation\n``\n \\\\mathbf{Ax} = λ \\\\mathbf{x}\n``\nwhere \\$\\\\mathbf{A}\\$ is the adjacency matrix of the graph `g` \nwith eigenvalue λ.\n\nBy virtue of the Perron–Frobenius theorem, there is a unique and positive\nsolution if λ is the largest eigenvalue associated with the\neigenvector of the adjacency matrix \\$\\\\mathbf{A}\\$.\n\n### References\n\n- Phillip Bonacich: Power and Centrality: A Family of Measures.\n American Journal of Sociology 92(5):1170–1182, 1986\n http://www.leonidzhukov.net/hse/2014/socialnetworks/papers/Bonacich-Centrality.pdf\n- Mark E. J. Newman: Networks: An Introduction.\n Oxford University Press, USA, 2010, pp. 169.\n\"\"\"\neigenvector_centrality(g::AbstractGraph) = abs.(vec(eigs(adjacency_matrix(g), nev=1)[2]))::Vector{Float64}\n", "meta": {"hexsha": "191734450f1217d3c2dec3b52c11cd87278a6951", "size": 1036, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/centrality/eigenvector.jl", "max_stars_repo_name": "mschauer/LightGraphs.jl", "max_stars_repo_head_hexsha": "ea21c7046495ca8595eb6b0fd4ed7a621ddd3c5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-10-18T02:45:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-18T02:45:49.000Z", "max_issues_repo_path": "src/centrality/eigenvector.jl", "max_issues_repo_name": "mschauer/LightGraphs.jl", "max_issues_repo_head_hexsha": "ea21c7046495ca8595eb6b0fd4ed7a621ddd3c5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-08-24T08:03:16.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-24T08:03:16.000Z", "max_forks_repo_path": "src/centrality/eigenvector.jl", "max_forks_repo_name": "mschauer/LightGraphs.jl", "max_forks_repo_head_hexsha": "ea21c7046495ca8595eb6b0fd4ed7a621ddd3c5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-12-14T04:02:43.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-14T04:02:43.000Z", "avg_line_length": 37.0, "max_line_length": 106, "alphanum_fraction": 0.7335907336, "num_tokens": 306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9780517418068649, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.8192356700571191}} {"text": "#===============================================================================\n\nThe minimum number of cubes to cover every visible face on a cuboid measuring 3 x 2 x 1 is twenty-two.\n\nIf we then add a second layer to this solid it would require forty-six cubes to\ncover every visible face, the third layer would require seventy-eight cubes, and\nthe fourth layer would require one-hundred and eighteen cubes to cover every\nvisible face.\n\nHowever, the first layer on a cuboid measuring 5 x 1 x 1 also requires\ntwenty-two cubes; similarly the first layer on cuboids measuring 5 x 3 x 1, 7 x\n2 x 1, and 11 x 1 x 1 all contain forty-six cubes.\n\nWe shall define C(n) to represent the number of cuboids that contain n cubes in\none of its layers. So C(22) = 2, C(46) = 4, C(78) = 5, and C(118) = 8.\n\nIt turns out that 154 is the least value of n for which C(n) = 10.\n\nFind the least value of n for which C(n) = 1000.\n\n--------------------------------------------------------------------------------\n\nLet's first compute the number of cube a layer is composed of given an initial\nrectangular parallelepiped of sides a, b and c along 1x, 1y and 1z.\n\nLet chose a slice of size 1 along the plane 1xy, and consider the successive\nlayers. The figure below represent the initial cut with 0 (here for a=3 and\nb=2), and three successive layers grown around it:\n\n 3333\n 322223\n 32111123\n 3210000123\n 3210000123\n 32111123\n 322223\n 3333\n\nIf P=2*(a+b) is the perimeter, then we see that the number of cubes is:\n Layer 1: P\n Layer 2: P+4\n Layer 3: P+8\n => For the layer n, the number of cubes is P+4(n-1). This is valid for all\nslices of length 1, so it comes that the number of cubes in the layer N for all\nslices is c(P+4(n-1)).\n\nDoing so, we have covered the faces that are parallel to 1xz and 1yz, but we\nstill have to cover the two faces parallel to 1xy. Looking again that the\nfigure, it comes that the number of Cube to cover that face is\n Layer 1: A = ab, the initial area of that face\n Layer 2: Layer 1 + size(border Layer 1) = A + P\n Layer 3: Layer 2 + size(border Layer 2) = A + P + P + 4\n Layer 4: Layer 3 + size(border Layer 3) = A + P + P + 4 + P + 8\n\n=> Layer n = A + (n-1) P + 4 (1+n-2)(n-2)/2\n = A + (n-1) (P + 2 (n-2))\n\nOf course there is a front face and a back face.\n\nSo, all put together, it comes that the number of cubes composing the layer n\nis N(n) = c(P+4(n-1)) + 2ab + 2(n-1) (P + 2 (n-2)). Replacing P by 2(a+b) and\nsimplifying, it comes:\n\n N(n) = 2(ab+bc+ac) + 4(n-1)(a+b+c+n-2)\n\nThe formula is obviously symmetric in a, b and c.\n\n===============================================================================#\n\n\n# Let check it the formula for N(n)\n\ninclude(\"Euler.jl\")\nusing Base.Test\n\nn_cubes(n, a, b, c) = 2*(a*b+b*c+a*c) + 4*(n-1)*(a+b+c+n-2)\n\n@test n_cubes(1, 1, 2, 3) == 22\n@test n_cubes(2, 1, 2, 3) == 46\n@test n_cubes(3, 1, 2, 3) == 78\n@test n_cubes(4, 1, 2, 3) == 118\n\nfunction euler(threshold::Int)\n\n for half_nc in Euler.naturals(3)\n # nc is the number of cubes in a layer; half_nc is just the half of it\n\n # Assuming 1 ≤ a ≤ b ≤ c, we have to determine the number of solutions\n # of the equation nc == n_cubes(n, a , b, c).\n\n nbr_sol = 0\n\n for n in Euler.naturals(1)\n 3 + 2*(n^2-1) ≤ half_nc || break\n\n for a in Euler.naturals(1)\n 3a^2 + 2*(n-1)*(3a+n-2) ≤ half_nc || break\n\n for b in Euler.naturals(a)\n b*(2a+b) + 2(n-1)*(a + 2b + n - 2) ≤ half_nc || break\n\n num_c = half_nc - a*b -2*(n-1)*(a+b+n-2)\n den_c = a + b + 2(n-1)\n\n if rem(num_c, den_c) == 0\n nbr_sol += 1\n end\n end\n end\n end\n\n if nbr_sol == threshold\n return 2*half_nc\n end\n end\nend\n\n@test euler(10) == 154\n\n@time println(\"Euler 126: $(euler(1000))\")\n", "meta": {"hexsha": "a10ac7c5fd14a62cceb8d9acaaedc99a6cc53ec2", "size": 3988, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "0126.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": "0126.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": "0126.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": 32.958677686, "max_line_length": 102, "alphanum_fraction": 0.5712136409, "num_tokens": 1261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107931567177, "lm_q2_score": 0.8740772220439509, "lm_q1q2_score": 0.8191946065520317}} {"text": "#Julia 1.4 Environment\nusing Pkg\npkg\"add ForwardDiff; precompile;\"\npkg\"add Plots; precompile;\"\npkg\"add PyPlot; precompile;\"\nimport ForwardDiff # calcula derivadas usando automatic differentiation in forward mode\nusing LinearAlgebra #adiciona operações de algebra linear\n\n\npyplot()#usa PyPlot como backend engine\n∇ = (h,x)->ForwardDiff.gradient(h,x) #gradiente de h(x)\nHessian = (h,x)->ForwardDiff.hessian(h,x) # hessian de h(x)\nDf = (h,x)->ForwardDiff.derivative(h,x); # primeira derivada de h'(x)\nD_2f = (h,x)->ForwardDiff.derivative(z->ForwardDiff.derivative(h,z),x) # segunda derivada h\"(x)\n\n#função de busca linear\nfunction linear_search(f::Function,x::Vector,d::Vector,method::Function)\n ϕ = t->f(x+t*d)\n α = method(f,x,d)\n return (ϕ(α),x+α*d)\nend\n\nfunction secao_aurea(f::Function,x::Vector,d::Vector;φ::Function = t->f(x+t*d),ρ = 1/2,ϵ = 1e-9)::Float64\n θ_1 = (3 - sqrt(5))/2.0\n θ_2 = (sqrt(5) - 1)/2.0\n #Obtenção intervalo\n a=0\n b=2*ρ\n s = b / 2\n while(φ(b)<φ(s))\n a = s\n s = b\n b *= 2\n end\n #Obtenção de t\n u = a + θ_1*(b - a)\n v = a + θ_2*(b - a)\n while(b - a > ϵ)\n if(φ(u)<φ(v))\n b = v\n v = u\n u = a + θ_1*(b - a)\n else\n a = u\n u = v\n v = a + θ_2*(b - a)\n end\n end\n return (u+v)/2\nend\n\nfunction secao_aurea(f::Function,x::Vector,d::Vector,(a,b)::Tuple{Float64,Float64};φ::Function = t->f(x+t*d),ϵ = 1e-9)::Float64\n θ_1 = (3 - sqrt(5))/2.0\n θ_2 = (sqrt(5) - 1)/2.0\n #Obtenção de t\n u = a + θ_1*(b - a)\n v = a + θ_2*(b - a)\n while(b - a > ϵ)\n if(φ(u)< φ(v))\n b = v\n v = u\n u = a + θ_1*(b - a)\n else\n a = u\n u = v\n v = a + θ_2*(b - a)\n end\n end\n return (u+v)/2\nend\n\nfunction newton(f::Function,x::Vector,d::Vector;φ::Function = y->f(x+y*d),t::Float64=0.25,ϵ = 1e-9,n_iter=10000)::Float64\n iter = 0\n while (abs(Df(φ,t)) > ϵ && iter < n_iter)\n t = t - (Df(φ,t)/D_2f(φ,t))\n iter = iter + 1\n end \n return t\nend\n\n\nfunction armijo(f::Function,x::Vector,d::Vector;φ::Function = y->f(x+y*d),t::Float64= 1.0,η::Float64 = 0.25)\n # f(x + td) > f(x) +t(∇f(x)⋅ d)\n while (φ(t)>φ(0)+ η*t*(∇(f,x)⋅d))\n t *=0.8\n end\n return t\nend\n", "meta": {"hexsha": "ae27f817494ff749db44b2cd9087d159f38a8c80", "size": 2335, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "projeto1_on_collab.jl", "max_stars_repo_name": "Huebr/BuscaLinear", "max_stars_repo_head_hexsha": "a868de48f6d832f79388d9647df3a085f970f8d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "projeto1_on_collab.jl", "max_issues_repo_name": "Huebr/BuscaLinear", "max_issues_repo_head_hexsha": "a868de48f6d832f79388d9647df3a085f970f8d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "projeto1_on_collab.jl", "max_forks_repo_name": "Huebr/BuscaLinear", "max_forks_repo_head_hexsha": "a868de48f6d832f79388d9647df3a085f970f8d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2359550562, "max_line_length": 127, "alphanum_fraction": 0.5233404711, "num_tokens": 923, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465170505204, "lm_q2_score": 0.8757869981319863, "lm_q1q2_score": 0.8191643183808841}} {"text": "# Collection of utilities for special functions (Bessel/Hankel)\n\n\"Derivative of Hankel function of first kind, with respect to argument (z)\"\nfunction diffhankelh1(n,z)\n if n!=0\n 0.5*(hankelh1(-1 + n, z) - hankelh1(1 + n, z))\n else\n - hankelh1(1, z)\n end\nend\n\n\"Derivative of Bessel function of first kind, with respect to argument (z)\"\nfunction diffbesselj(n,z)\n if n!=0\n 0.5*(besselj(-1 + n, z) - besselj(1 + n, z))\n else\n - besselj(1, z)\n end\nend\n\nfresnels(z::T) where T = T((1+im)//4*(erf((1+im)//2*sqrt(T(π))*z) - im*erf((1-im)//2*sqrt(T(π))*z) ))\n\nfresnelc(z::T) where T = T((1-im)//4*(erf((1+im)//2*sqrt(T(π))*z) + im*erf((1-im)//2*sqrt(T(π))*z) ))\n", "meta": {"hexsha": "0e3605264c6dd8dd6c8096b12d789ea26adde5c1", "size": 700, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/special_functions.jl", "max_stars_repo_name": "jondea/JondeaUtils.jl", "max_stars_repo_head_hexsha": "09aec8840a4bbaaec3f5bfbd1a543ba60ab349a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/special_functions.jl", "max_issues_repo_name": "jondea/JondeaUtils.jl", "max_issues_repo_head_hexsha": "09aec8840a4bbaaec3f5bfbd1a543ba60ab349a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/special_functions.jl", "max_forks_repo_name": "jondea/JondeaUtils.jl", "max_forks_repo_head_hexsha": "09aec8840a4bbaaec3f5bfbd1a543ba60ab349a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1666666667, "max_line_length": 101, "alphanum_fraction": 0.5828571429, "num_tokens": 282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877700966099, "lm_q2_score": 0.8438950966654772, "lm_q1q2_score": 0.8191586495776751}} {"text": "export kaplanyorke_dim\n\n\"\"\"\n kaplanyorke_dim(λs::AbstractVector)\nCalculate the Kaplan-Yorke dimension, a.k.a. Lyapunov dimension[^Kaplan1970].\n\n## Description\nThe Kaplan-Yorke dimension is simply the point where\n`cumsum(λs)` becomes zero (interpolated):\n```math\n D_{KY} = k + \\\\frac{\\\\sum_{i=1}^k \\\\lambda_i}{|\\\\lambda_{k+1}|},\\\\quad k = \\\\max_j \\\\left[ \\\\sum_{i=1}^j \\\\lambda_i > 0 \\\\right].\n```\n\nIf the sum of the exponents never becomes negative the function\nwill return the length of the input vector.\n\nUseful in combination with [`lyapunovspectrum`](@ref).\n\n[^Kaplan1970]: J. Kaplan & J. Yorke, *Chaotic behavior of multidimensional difference equations*, Lecture Notes in Mathematics vol. **730**, Springer (1979)\n\"\"\"\nfunction kaplanyorke_dim(v::AbstractVector)\n issorted(v, rev = true) || throw(ArgumentError(\n \"The lyapunov vector must be sorted from most positive to most negative\"))\n\n s = cumsum(v); k = length(v)\n # Find k such that sum(λ_i for i in 1:k) is still possitive\n for i in eachindex(s)\n if s[i] < 0\n k = i-1\n break\n end\n end\n\n if k == 0\n return zero(v[1])\n elseif k < length(v)\n return k + s[k]/abs(v[k+1])\n else\n return typeof(v[1])(length(v))\n end\nend\n", "meta": {"hexsha": "6a56a06f76aae6b097c92a422227fe5f216f684d", "size": 1266, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/dimensions/kaplanyorke.jl", "max_stars_repo_name": "onkyo14taro/ChaosTools.jl", "max_stars_repo_head_hexsha": "2b7d157de60027f9fbf6efcfaeb8cdccf8f480f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 168, "max_stars_repo_stars_event_min_datetime": "2018-01-07T15:46:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T13:38:24.000Z", "max_issues_repo_path": "src/dimensions/kaplanyorke.jl", "max_issues_repo_name": "onkyo14taro/ChaosTools.jl", "max_issues_repo_head_hexsha": "2b7d157de60027f9fbf6efcfaeb8cdccf8f480f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 176, "max_issues_repo_issues_event_min_datetime": "2017-12-19T20:26:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T20:08:23.000Z", "max_forks_repo_path": "src/dimensions/kaplanyorke.jl", "max_forks_repo_name": "onkyo14taro/ChaosTools.jl", "max_forks_repo_head_hexsha": "2b7d157de60027f9fbf6efcfaeb8cdccf8f480f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 39, "max_forks_repo_forks_event_min_datetime": "2018-01-27T07:59:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-06T10:08:36.000Z", "avg_line_length": 30.1428571429, "max_line_length": 156, "alphanum_fraction": 0.6484992101, "num_tokens": 385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248259606259, "lm_q2_score": 0.8723473829749844, "lm_q1q2_score": 0.8191558494752922}} {"text": "using Plots, Distributions, Statistics, LaTeXStrings, ProgressBars, StatsBase, JLD\n\nfunction SSMC(f :: Function , R :: Real, r :: Real, Θ :: Real, θ ::Real , N :: Integer)\n ΔR= R - r\n Δθ= Θ - θ\n dist=[ ΔR .* rand(N) .+ r, Δθ .* rand(N) .+ θ ]\n f₍ₓ₎=[]\n for n in 1:N\n push!(f₍ₓ₎, f(getindex.(dist, n)...))\n end\n ∫f₍ₓ₎dx= mean(f₍ₓ₎)* ΔR * Δθ\n error= std(f₍ₓ₎)/sqrt(N)\n return ∫f₍ₓ₎dx, error\nend\n\nsamples=10^4\nErrorList=[]\nIntegralRes=[]\nfor i in ProgressBar(1:samples)\n I, E=SSMC((r, θ) -> r^3 * sin(θ) * cos(θ) * (3 + r * cos(θ)), 1, 0 , π, 0, 10^5)\n push!(IntegralRes, I)\n push!(ErrorList, E)\nend\nhistogram(IntegralRes, dpi=600, ylabel=\"Probability Density\", xlabel=\"I\",\n title=\"The Distribution of I's Results\")\nsavefig(\"C:\\\\Users\\\\Narges\\\\Documents\\\\GitHub\\\\computational_physics\\\\chapter7\\\\7.2\\\\Figs\\\\IHistogram.png\")\nhistogram(ErrorList, dpi=600,xlabel=\"Probability Density\", ylabel=\"Error\",\n title=\"The Distribution of Errors\")\nsavefig(\"C:\\\\Users\\\\Narges\\\\Documents\\\\GitHub\\\\computational_physics\\\\chapter7\\\\7.2\\\\Figs\\\\EHistogram.png\")\nsave(\"../../chapter7/7.2/data.jld\",\"Idata\",IntegralRes, \"Edata\", ErrorList )\n", "meta": {"hexsha": "3f09982b0f4948f2bdfd17222903e7becf66cf64", "size": 1167, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "chapter7/7.2/7.2.jl", "max_stars_repo_name": "narges8k/computational_physics", "max_stars_repo_head_hexsha": "a24229aa7b31648735aab120cd667dffd788df1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapter7/7.2/7.2.jl", "max_issues_repo_name": "narges8k/computational_physics", "max_issues_repo_head_hexsha": "a24229aa7b31648735aab120cd667dffd788df1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter7/7.2/7.2.jl", "max_forks_repo_name": "narges8k/computational_physics", "max_forks_repo_head_hexsha": "a24229aa7b31648735aab120cd667dffd788df1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-13T09:55:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T09:55:00.000Z", "avg_line_length": 37.6451612903, "max_line_length": 107, "alphanum_fraction": 0.6298200514, "num_tokens": 430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294984, "lm_q2_score": 0.8774767954920547, "lm_q1q2_score": 0.8190638768757139}} {"text": "#-------------julia-fractal.jl-------------------------------------------------#\n#\n# Purpose: This file tests the creation of the julia fractal in julia for fun\n#\n#------------------------------------------------------------------------------#\n\n# We will need a few libraries for visualization\nusing PyPlot\n\n# Function to calculate and output julia fractal to image\nfunction create_fractal(cutoff::Float64, step::Float64, c_val::Float64, \n res::Int64, range::Float64)\n # Setting up the array to be used\n carr = Array{Float64}(res, res)\n\n # For now, let's just assume that the imaginary and real ranges are from \n # -range < x < range\n for i = 1:res\n for j = 1:res\n z = complex((i/res)*range - range/2.0,(j/res)*range - range/2.0)\n c = complex(0,c_val)\n n = 255\n while (abs(z) < cutoff && n > 5)\n z = z*z + c\n n -= 5\n end\n carr[i,j] = n/255.0;\n end\n end\n\n return carr\n\nend\n\n# Fuction to scan through C values\nfunction c_scan(cutoff::Float64, step::Float64, res::Int64,\n range::Float64, max_c::Float64, c_step::Float64)\n\n id = 0\n for i = 0:c_step:max_c\n println(i)\n carr = create_fractal(cutoff, step, i, res, range)\n figure(figsize = (10,10))\n imshow(carr, cmap=ColorMap(\"Blues\"))\n subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, \n hspace = 0, wspace = 0)\n savefig(string(\"c_scan\", lpad(id, 5, 0), \".png\"))\n id += 1\n end\nend\n\n# Function to zoom in on fractal\nfunction fractal_zoom(cutoff::Float64, step::Float64, c_val::Float64,\n res::Int64, max_range::Float64, \n min_range::Float64)\n id = 0\n range = max_range\n while range > min_range\n println(range)\n carr = create_fractal(cutoff, step, c_val, res, range)\n figure(figsize = (10,10))\n imshow(carr, cmap=ColorMap(\"Blues\"))\n subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, \n hspace = 0, wspace = 0)\n savefig(string(\"fractal_zoom\", lpad(id, 5, 0), \".png\"))\n id += 1\n range -= range*0.05\n end\nend\n\nfractal_zoom(10.0, 0.1, 1.0, 1024, 1.0, 0.0001)\n\n#c_scan(10.,5., 1024, 3.0, 1.0, 0.025)\n", "meta": {"hexsha": "14b1f77e68d4961714372799be05f4387c20472c", "size": 2339, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/fractal/julia-fractal.jl", "max_stars_repo_name": "vchuravy/skillpill-julia", "max_stars_repo_head_hexsha": "4ef5de50fe6fdc846278ed47eaeeb73acb121a02", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-07-11T18:24:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-19T01:00:44.000Z", "max_issues_repo_path": "examples/fractal/julia-fractal.jl", "max_issues_repo_name": "oist/skillpill-julia", "max_issues_repo_head_hexsha": "eb719677ae84bd26c1e3fdb889cf2b54f65d47ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/fractal/julia-fractal.jl", "max_forks_repo_name": "oist/skillpill-julia", "max_forks_repo_head_hexsha": "eb719677ae84bd26c1e3fdb889cf2b54f65d47ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-06-23T01:55:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-13T03:44:47.000Z", "avg_line_length": 31.6081081081, "max_line_length": 80, "alphanum_fraction": 0.5198802907, "num_tokens": 689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.8774767842777551, "lm_q1q2_score": 0.8190638696578495}} {"text": "# illustrates effects of collinearity\n# try setting rho=0.1 or rho=0.9, and observe\n# the effect on standard dev of coefficients\nusing Econometrics, Plots, LinearAlgebra\nfunction wrapper(rho, n)\n V = [1.0 rho; rho 1.0]\n P = cholesky(V).U\n x = randn(n,2)*P\n x = [ones(n,1) x]\n b = ones(3)\n y = x*b + randn(n,1)\n b1 = x\\y\n\n z = x[:,1:2]\n b2 = z\\y\n\n R = [0.0 1.0 -1.0]\n r = 0.0\n b3 = ols(y, x, R=R, r=r, silent=true)[1]\n results = [b1' b2' b3']\nend\n\nfunction main()\nreps = 1000\nrho = 0.9\nn = 30\ndata = zeros(reps,8)\nfor rep = 1:reps\n data[rep,:] = wrapper(rho,n)\nend\nprintln(\"correlation between x2 and x3: \",rho)\nprintln(\"descriptive statistics for 1000 OLS replications\")\ndstats(data[:,1:3])\nprintln(\"descriptive statistics for 1000 OLS replications, dropping x3\")\ndstats(data[:,4:5])\nprintln(\"descriptive statistics for 1000 Restricted OLS replications, b2=b3\")\ndstats(data[:,6:8])\np1 = histogram(data[:,2],title=\"OLS\")\np2 = histogram(data[:,5],title=\"Drop X3\")\np3 = histogram(data[:,7],title=\"Restricted LS\")\nplot(p1,p2,p3, layout=(3,1), show=true, legend=false)\ngui()\nsavefig(\"collin.png\")\nreturn\nend\nmain()\n", "meta": {"hexsha": "6869fde4d514c243fe9578c980d686e047d40c3d", "size": 1126, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/DataProblems/collinearity.jl", "max_stars_repo_name": "Hiroakiyusheng/Econometrics", "max_stars_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 209, "max_stars_repo_stars_event_min_datetime": "2016-02-12T16:41:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T21:18:55.000Z", "max_issues_repo_path": "Examples/DataProblems/collinearity.jl", "max_issues_repo_name": "Hiroakiyusheng/Econometrics", "max_issues_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2019-09-10T12:45:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-05T07:22:46.000Z", "max_forks_repo_path": "Examples/DataProblems/collinearity.jl", "max_forks_repo_name": "Hiroakiyusheng/Econometrics", "max_forks_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 104, "max_forks_repo_forks_event_min_datetime": "2015-12-12T23:46:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T10:10:27.000Z", "avg_line_length": 23.9574468085, "max_line_length": 77, "alphanum_fraction": 0.6580817052, "num_tokens": 420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897426182321, "lm_q2_score": 0.8705972583359805, "lm_q1q2_score": 0.8190489705940456}} {"text": "\n# ------------------------------------------------------------------------------------------\n# # 矩阵分解与其他妙用\n# 该教程由Andreas Noack所做的工作改编而成\n#\n# ## 大纲\n# - 矩阵分解\n# - 特殊矩阵\n# - 一般化线性代数\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# 正式开始之前,让我们先来建立一个线性系统,并利用`LinearAlgebra`库来进行矩阵分解或处理特殊矩阵。\n# ------------------------------------------------------------------------------------------\n\nusing LinearAlgebra\nA = rand(3, 3)\nx = fill(1, (3,))\nb = A * x\n\n# ------------------------------------------------------------------------------------------\n# ## 矩阵分解\n#\n# #### LU分解\n# 在Julia中,我们可以使用`lufact`进行LU分解:\n# ```julia\n# PA = LU\n# ```\n# 其中`P`是置换矩阵,`L`是对角全为1的下三角矩阵(单位下三角矩阵),`U`是上三角矩阵。\n#\n# Julia可以计算LU分解,并定义一个复合分解数据类型用以储存分解后的结果。\n# ------------------------------------------------------------------------------------------\n\nAlu = lu(A)\n\ntypeof(Alu)\n\n# ------------------------------------------------------------------------------------------\n# 可以通过这个类的特殊属性来调取分解出来的矩阵:\n# ------------------------------------------------------------------------------------------\n\nAlu.P\n\nAlu.L\n\nAlu.U\n\n# ------------------------------------------------------------------------------------------\n# Julia可以对储存分解结果的对象派发方法。\n#\n# 比如,在解算当前的线性系统时,我们既可以使用原本的矩阵,也可以使用分解运算所生成的对象:\n# ------------------------------------------------------------------------------------------\n\nA\\b\n\nAlu\\b\n\n# ------------------------------------------------------------------------------------------\n# 相似地,要计算矩阵`A`的行列式,既可以使用原本的矩阵,也可以使用分解运算所生成的对象:\n# ------------------------------------------------------------------------------------------\n\ndet(A) ≈ det(Alu)\n\n# ------------------------------------------------------------------------------------------\n# #### QR分解\n#\n# 在Julia中,可以使用`qrfact`来计算QR分解:\n# ```\n# A=QR\n# ```\n#\n# 其中`Q`是正交阵/酉矩阵,`R`是上三角矩阵。\n# ------------------------------------------------------------------------------------------\n\nAqr = qr(A)\n\n# ------------------------------------------------------------------------------------------\n# 与LU分解类似,矩阵`Q`和`R`可以通过以下语句从QR分解对象中调取:\n# ------------------------------------------------------------------------------------------\n\nAqr.Q\n\nAqr.R\n\n# ------------------------------------------------------------------------------------------\n# #### 特征分解\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# 特征分解、奇异值分解(SVD)、Hessenberg分解、Schur分解的结果都是以`Factorization`类型来储存的。\n#\n# 以下语句可用于计算特征值:\n# ------------------------------------------------------------------------------------------\n\nAsym = A + A'\nAsymEig = eigen(Asym)\n\n# ------------------------------------------------------------------------------------------\n# 通过特殊索引,可以从Eigen类型中提取计算得到的特征值和特征向量:\n# ------------------------------------------------------------------------------------------\n\nAsymEig.values\n\nAsymEig.vectors\n\n# ------------------------------------------------------------------------------------------\n# 再一次地,当分解结果被储存为特定的类型时,我们可以对它使用派发方法,也可以编写一些具有针对性的方法以充分利用矩阵分解的性质。例如,$A^{-1}=(V\\Lambda\n# V^{-1})^{-1}=V\\Lambda^{-1}V^{-1}$。\n# ------------------------------------------------------------------------------------------\n\ninv(AsymEig)*Asym\n\n# ------------------------------------------------------------------------------------------\n# ## 特殊矩阵结构\n# 矩阵结构在线性代数中有着尤为重要的作用。让我们通过一个大型线性系统来看看它到底有*多重要*吧:\n# ------------------------------------------------------------------------------------------\n\nn = 1000\nA = randn(n,n);\n\n# ------------------------------------------------------------------------------------------\n# 通常,Julia可以自动推断出特殊矩阵结构:\n# ------------------------------------------------------------------------------------------\n\nAsym = A + A'\nissymmetric(Asym)\n\n# ------------------------------------------------------------------------------------------\n# 但有时浮点误差会阻碍这一功能:\n# ------------------------------------------------------------------------------------------\n\nAsym_noisy = copy(Asym)\nAsym_noisy[1,2] += 5eps()\n\nissymmetric(Asym_noisy)\n\n# ------------------------------------------------------------------------------------------\n# 幸运的是,我们可以使用`Diagonal`(对角)、`Triangular`(三角)、`Symmetric`(对称)、`Hermitian`(厄米/自共轭矩阵)、`Tridiago\n# nal`(三对角)、`SymTridiagonal`(对称三对角)等函数显式地定义特殊矩阵。\n# ------------------------------------------------------------------------------------------\n\nAsym_explicit = Symmetric(Asym_noisy);\n\n# ------------------------------------------------------------------------------------------\n# 现在,我们来比较Julia在计算`Asym`、`Asym_noisy`和`Asym_explicit`的特征值时各自需要多长时间:\n# ------------------------------------------------------------------------------------------\n\n@time eigvals(Asym);\n\n@time eigvals(Asym_noisy);\n\n@time eigvals(Asym_explicit);\n\n# ------------------------------------------------------------------------------------------\n# 在这个示例中,对`Asym_noisy`使用`Symmetric()`使得我们的运算效率提高了`5倍` :)\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# #### 一个“大”问题\n# 用`Tridiagonal`和`SymTridiagonal`类型储存三对角矩阵让我们得以处理有可能非常庞大的三对角问题。对于下面的示例问题而言,如果矩阵被储存为一个(稠密的)`M\n# atrix`类型,那么一台笔记本电脑的配置将会不足以支持该问题的解算。\n# ------------------------------------------------------------------------------------------\n\nn = 1_000_000;\nA = SymTridiagonal(randn(n), randn(n-1));\n@time eigmax(A)\n\n# ------------------------------------------------------------------------------------------\n# ## 一般化线性代数\n# 要在语言中添加对数值化的线性代数的支持,常规的手段是包装BLAS和LAPACK中的子程序。对于含有`Float32`、`Float64`、`Complex{Float32}`或`C\n# omplex{Float64}`等类型的元素的矩阵,这正是Julia的处理方式。\n#\n# 然而,Julia也支持一般化的线性代数。运用这一特性的其中一个例子便是处理有理数矩阵和向量。\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# #### 有理数\n# Julia内嵌有对有理数的支持。使用双斜杠以构建一个有理数:\n# ------------------------------------------------------------------------------------------\n\n1//2\n\n# ------------------------------------------------------------------------------------------\n# #### 示例:有理数线性方程组\n# 下面的例子将会演示如何在不将矩阵元素转化为浮点类型的前提下求解一个含有有理数的线性方程组。在处理有理数时,数值溢出很容易成为一个问题,因此我们使用`BigInt`类型:\n# ------------------------------------------------------------------------------------------\n\nArational = Matrix{Rational{BigInt}}(rand(1:10, 3, 3))/10\n\nx = fill(1, 3)\nb = Arational*x\n\nArational\\b\n\nlu(Arational)\n\n# ------------------------------------------------------------------------------------------\n# ### 练习\n#\n# #### 11.1\n# 求解矩阵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# 并将它赋给变量`A_eigv`。\n# ------------------------------------------------------------------------------------------\n\nusing LinearAlgebra\n\n\n\n@assert A_eigv == [-128.49322764802145, -55.887784553056875, 42.7521672793189, 87.16111477514521, 542.4677301466143]\n\n# ------------------------------------------------------------------------------------------\n# #### 11.2\n# 由`A`的特征值构建一个`Diagonal`(对角)矩阵。\n# ------------------------------------------------------------------------------------------\n\n\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\n# ------------------------------------------------------------------------------------------\n# #### 11.3\n# 由`A`构建一个`LowerTriangular`(下三角)矩阵,并将其储存为`A_lowertri`。\n# ------------------------------------------------------------------------------------------\n\n\n\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# ------------------------------------------------------------------------------------------\n# ### 反馈与评价(英文):\n# https://tinyurl.com/introJuliaFeedback\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# 完成练习后请点击顶部的`Validate`按钮。\n# ------------------------------------------------------------------------------------------\n", "meta": {"hexsha": "4c2806da1d7d5ee045d97e2b5cf9ce4785f61876", "size": 8439, "ext": "jl", "lang": "Julia", "max_stars_repo_path": ".nbexports/zh-cn/intro-to-julia-ZH/12. 矩阵分解与其他妙用.jl", "max_stars_repo_name": "NahsiN/JuliaTutorials", "max_stars_repo_head_hexsha": "6d61077a0f6565e19305cddab0adde79d232e147", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 535, "max_stars_repo_stars_event_min_datetime": "2020-07-15T14:56:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T12:50:32.000Z", "max_issues_repo_path": ".nbexports/zh-cn/intro-to-julia-ZH/12. 矩阵分解与其他妙用.jl", "max_issues_repo_name": "NahsiN/JuliaTutorials", "max_issues_repo_head_hexsha": "6d61077a0f6565e19305cddab0adde79d232e147", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 42, "max_issues_repo_issues_event_min_datetime": "2018-02-25T22:53:47.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-14T02:15:50.000Z", "max_forks_repo_path": ".nbexports/zh-cn/intro-to-julia-ZH/12. 矩阵分解与其他妙用.jl", "max_forks_repo_name": "NahsiN/JuliaTutorials", "max_forks_repo_head_hexsha": "6d61077a0f6565e19305cddab0adde79d232e147", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 394, "max_forks_repo_forks_event_min_datetime": "2020-07-14T23:22:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T20:12:57.000Z", "avg_line_length": 32.96484375, "max_line_length": 117, "alphanum_fraction": 0.2640123237, "num_tokens": 2425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154281754899, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.8190340696728797}} {"text": "module GellMannMatrices\n\nusing LinearAlgebra, SparseArrays\nexport gellmann\n\n# ---------------------------------------------------------------------------------------- #\n# direct sum (i.e., block-diagonalization of matrices As)\nif VERSION < v\"1.8\"\n # work around for https://github.com/JuliaLang/julia/pull/44211 for Julia ≤ v1.7\n @inline ⊕(As...) = cat(As..., dims=(1,2))::typeof((.+)(As...))\nelse\n @inline ⊕(As...) = cat(As..., dims=Val((1,2)))\nend\n\n# https://en.wikipedia.org/wiki/Matrix_unit\nunit(::Type{<:SparseMatrixCSC}, i, j, n, m) = sparse([i], [j], [1], n, m)\nunit(T::Type{<:AbstractMatrix}, i, j, n, m) = (A = zeros(eltype(T), n, m); A[i,j] = one(eltype(T)); A)\n\n# ---------------------------------------------------------------------------------------- #\n# implementation following https://en.wikipedia.org/wiki/Generalizations_of_Pauli_matrices\n\n# off-diagonal matrices (f_ij on Wiki)\nfunction offdiag_gellmann(T::Type{<:AbstractMatrix}, i, j, d)\n if i < j\n return unit(T, i, j, d, d) + unit(T, j, i, d, d)\n elseif i > j\n return -1im * (unit(T, j, i, d, d) - unit(T, i, j, d, d))\n else\n throw(DomainError((j, i), \"i and j must differ\"))\n end\nend\n\n# \"diagonal\"-like matrices (h_i on Wiki)\nfunction diag_gellmann(T::Type{<:AbstractMatrix}, i, d; norm_identity::Bool=false)\n if i == 1\n return norm_identity ? T(I(d) / sqrt(d/2)) : T(I(d))\n elseif i < d\n return diag_gellmann(T, i, d-1) ⊕ zero(eltype(T))\n elseif i == d\n return sqrt(2/(d*(d-1))) * (T(I(d-1)) ⊕ convert(eltype(T), (1-d)))\n else\n throw(DomainError((i,d), \"invalid combination of (i,d); must have i ≤ d and d ≥ 1\"))\n end\nend\n\n# ---------------------------------------------------------------------------------------- #\n\n\"\"\"\n gellmann([T::Type{<:AbstractMatrix}=Matrix{ComplexF64},] d::Integer; skip_identity=true)\n\nReturn the generalized Gell-Mann matrices in `d` dimensions as a vector of matrices of type\n`T`.\n\n`T` can be any mutable `AbstractMatrix`, including `SparseMatrixCSC`, with complex floating\npoint element type.\n\n## Keyword arguments\n- `skip_identity` (default, `true`): if `false`, the identity matrix of dimension `d` is\n included as the last element of the returned vector.\n- `norm_identity` (default, `false`): if `true`, the elements of the identity are normalized\n by `sqrt(D/2)` to ensure the the orthogonality relation `tr(A'*A) = 2`.\n\n## Examples\nCompute the Pauli matrices ``σ_i`` (`d=2`) and Gell-Mann matrices ``Λ_i`` (`d=3`):\n```jl\njulia> σᵢ = gellmann(2)\njulia> Λᵢ = gellmann(3)\n```\n\"\"\"\ngellmann(d::Integer; kwargs...) = gellmann(Matrix{ComplexF64}, d; kwargs...)\n\nfunction gellmann(T::Type{<:AbstractMatrix}, d::Integer; \n skip_identity=true, norm_identity=false)\n d > 0 || throw(DomainError(d, \"dimension must be a positive integer\"))\n eltype(T) == complex(eltype(T)) || throw(DomainError(T, \"the element type of T must be complex\"))\n # we collect the matrices in the slightly odd-looking manner below in order to be\n # consistent with the conventional number of Pauli and Gell-Mann matrices.\n ms = Vector{T}(undef, d*d - skip_identity)\n k = 0\n for i in 2:d\n for j in 1:i-1\n ms[k+=1] = offdiag_gellmann(T, j, i, d)\n ms[k+=1] = offdiag_gellmann(T, i, j, d)\n end\n ms[k+=1] = diag_gellmann(T, i, d)\n end\n skip_identity || (ms[k+=1] = diag_gellmann(T, 1, d; norm_identity))\n return ms\nend\n\nend\n", "meta": {"hexsha": "261d80ea6046bf0f90edb9794a296d9b8e6bf441", "size": 3473, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/GellMannMatrices.jl", "max_stars_repo_name": "thchr/GellMannMatrices.jl", "max_stars_repo_head_hexsha": "5dba575b256440b310e49fe3b75cf03303520576", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-17T11:10:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T11:10:02.000Z", "max_issues_repo_path": "src/GellMannMatrices.jl", "max_issues_repo_name": "thchr/GellMannMatrices.jl", "max_issues_repo_head_hexsha": "5dba575b256440b310e49fe3b75cf03303520576", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-19T20:16:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-22T16:35:28.000Z", "max_forks_repo_path": "src/GellMannMatrices.jl", "max_forks_repo_name": "thchr/GellMannMatrices.jl", "max_forks_repo_head_hexsha": "5dba575b256440b310e49fe3b75cf03303520576", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.75, "max_line_length": 102, "alphanum_fraction": 0.5824935215, "num_tokens": 1040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039739, "lm_q2_score": 0.8872045996818986, "lm_q1q2_score": 0.8189245922570214}} {"text": "# p38.jl - solve u_xxxx = exp(x), u(-1)=u(1)=u'(-1)=u'(1)=0\n# (compare p13.jl)\n\n# Construct discrete biharmonic operator:\nN = 15; (D,x) = cheb(N);\nS = diagm([0; 1 ./(1-x[2:N].^2); 0]);\nD4 = (diagm(1-x.^2)*D^4 - 8*diagm(x)*D^3 - 12*D^2)*S;\nD4 = D4[2:N,2:N];\n\n# Solve boundary-value problem and plot result:\nf = @. exp(x[2:N]); u = D4\\f; u = [0;u;0];\nclf(); axes([.1,.4,.8,.5]);\nplot(x,u,\".\",markersize=10);\naxis([-1,1,-.01,.06]); grid(true);\nxx = (-1:.01:1);\nuu = (1-xx.^2).*polyval(polyfit(x,S*u),xx);\nplot(xx,uu);\n\n# Determine exact solution and print maximum error:\nA = [1 -1 1 -1; 0 1 -2 3; 1 1 1 1; 0 1 2 3];\nV = xx.^(0:3)';\nc = A\\exp.([-1,-1,1,1]); exact = exp.(xx) - V*c;\ntitle(\"max err = $(signif(norm(uu-exact,Inf),5))\",fontsize=12);\n", "meta": {"hexsha": "2c0d7c62053c688fd9056a74fd0cd410c13e2e6a", "size": 750, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/scripts/p38.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/p38.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/p38.jl", "max_forks_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_forks_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.25, "max_line_length": 63, "alphanum_fraction": 0.5333333333, "num_tokens": 342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741308615412, "lm_q2_score": 0.8596637523076225, "lm_q1q2_score": 0.8188934516876047}} {"text": "\"\"\"\nGray Code Generator\n===================\n\n## References\n\n- [knuth]: The Art of Computer Programming, Volume 4 Fascicle 2A, 7.2.1.1 Generating all n-tuples.\n- [manber]: Introduction to Algorithms: A Creative Approach, 2.9 Gray Codes.\n- [wiki]: https://en.wikipedia.org/wiki/Gray_code#Constructing_an_n-bit_Gray_code\n\"\"\"\nmodule GrayCode\n\n# From [wiki]:\n#\n# \"Once a binary number appears in $G_n$ it appears in the same position in all longer lists; so it\n# makes sense to talk about the reflective Gray code value of a number.\"\n#\n# \"These characteristics suggest a simple and fast method of translating a binary value into the\n# corresponding Gray code. Each bit is inverted if the next higher bit of the input value is set to\n# one.\"\n#\n# From [knuth]:\n#\n# \"[R]eversing the order of Gray binary code is equivalent to complementing the fist bit.\"\n#\n# - - - -\n#\n# We have\n#\n# g(i) = b(i) ⊕ b(i + 1)\n#\n# So g(i) of the MSbit is b(i) as b(i + 1) is 0. And for converting from Gray code to binary\n# (c.f. https://math.stackexchange.com/a/1829662):\n#\n# b(i) = g(i) ⊕ b(i + 1)\n#\n# or,\n#\n# b(i) = g(i) ⊕ g(i + 1) ⊕ g(i + 2) ⊕ ...\n\n#===== Gray code <-> Binary =====#\n\n# b -> g (n-th is 1-based)\n\"Computes the `n`-th reflective gray code.\"\nfunction gray_nth(n::Integer)::Vector{Int8}\n @assert n > 0\n n -= 1\n g = xor(n, n >>> 1)\n digits(Int8, g, base=2)\nend\n\n# g -> b\nfunction gray_to_binary(g::Vector{Int8})::Vector{Int8}\n b = copy(g)\n for i in (length(g) - 1):-1:1\n b[i] = xor(g[i], b[i + 1])\n end\n b\nend\n\n#===== Constructs Gray code by recursion =====#\n\n# A slow implementation, just for proof-of-concept. See [manber].\nfunction gray_codes_of_len(len::Integer)::Vector{Vector{Int8}}\n @assert iseven(len) \"Gray code of odd length does not exist.\"\n @assert len > 0 \"Length should be greater than 0.\"\n gray_codes_of_len_r(len)\nend\n\nfunction gray_codes_of_len_r(len::Integer)::Vector{Vector{Int8}}\n if len == 0\n return [[]]\n elseif len == 2\n g =\n [\n Int8[0],\n Int8[1],\n ]\n return g\n end\n\n if isodd(len)\n _2k = len - 1\n g_2k = gray_codes_of_len_r(_2k)\n if ispow2(_2k)\n g =\n [\n [[0; g] for g in g_2k]...,\n [1; g_2k[end]],\n ]\n return g\n else\n # There are some unused strings of length `ceil(log2(k * 2))`, one of which is connected\n # to one of the used strings.\n\n # Oops, this construction is useful for the proof but cannot be elegantly expressed as\n # code.\n len_pow2 = nextpow(2, _2k)\n g_pow2 = gray_codes_of_len_r(len_pow2) # slow, fvck\n used = Set(g_2k)\n for (s, t) in [(i, mod1(i + 1, len_pow2)) for i in 1:len_pow2]\n if g_pow2[s] in used && !(g_pow2[t] in used)\n index_2k = findfirst(x -> x == g_pow2[s], g_2k)\n g =\n [\n g_2k[(index_2k + 1):end]\n g_2k[1:index_2k]\n [g_pow2[t]]\n ]\n return g\n end\n end\n error(\"Should not reach here.\")\n end\n end\n\n half_len = div(len, 2)\n g_half = gray_codes_of_len_r(half_len)\n g_half_rev = reverse(g_half)\n\n [\n [[0; g] for g in g_half];\n [[1; g] for g in g_half_rev];\n ]\nend\n\n#===== Gray code iterating =====#\n\n# c.f. [knuth] Algorithm G.\nmutable struct GrayCodeIter\n n::Int\n code::Union{UInt128, Nothing}\n parity::Int8\n\n GrayCodeIter(n::Int) = new(n, 0, 0)\nend\n\nfunction Base.iterate(iter::GrayCodeIter, state=iter)\n if iter.code == nothing\n nothing\n else\n curr_code = iter.code\n iter.parity ⊻= 1\n if iter.parity == 1\n iter.code ⊻= 1\n elseif iter.code == 1 << (iter.n - 1)\n iter.code = nothing\n else\n iter.code ⊻= curr_code ⊻ (curr_code - 1) + 1\n end\n (curr_code, iter)\n end\nend\n\nBase.length(iter::GrayCodeIter) = UInt128(2) ^ iter.n\n\n# TODO: [knuth] Fig. 14\n\n#===== Unit Tests =====#\nusing Test\nusing Random: seed!\n\n# Helpers for testing\nfunction diff_one(a::Vector{T}, b::Vector{T})::Bool where T<:Integer\n len_diff = length(a) - length(b)\n if len_diff == 0\n return sum(xor.(a, b)) == 1\n elseif len_diff == 1\n # does nothing\n elseif len_diff == -1\n a, b = b, a\n else\n return false\n end\n\n a[end] == 1 && @view(a[1:(end - 1)]) == b\nend\n\nfunction binary_array_to_value(ba::Vector{Int8})::UInt64\n @assert length(ba) <= 64\n reduce((acc, x) -> (acc << 1) + x, @view ba[end:-1:1]; init=UInt64(0))\nend\n\nfunction check_grayness(gray_codes::Vector{Vector{Int8}})\n len = length(gray_codes)\n for i in 1:len\n @test diff_one(gray_codes[i], gray_codes[mod1(i + 1, len)])\n end\n @test length(unique(map(binary_array_to_value, gray_codes))) == len\nend\n\n@testset \"N-th Gray code\" begin\n seed!()\n N = 2^16\n for _ in 1:100\n n = rand(1:N)\n n_minus1 = mod1(n - 1, N)\n n_plus1 = mod1(n + 1, N)\n g = gray_nth(n)\n g_minus1 = gray_nth(n_minus1)\n g_plus1 = gray_nth(n_plus1)\n @test diff_one(g_minus1, g)\n @test diff_one(g, g_plus1)\n\n b = gray_to_binary(g)\n nb = binary_array_to_value(b) + 1\n @test n == nb\n end\nend\n\n@testset \"Gray code of given length\" begin\n for len in 2:2:64\n gray_codes = gray_codes_of_len(len)\n check_grayness(gray_codes)\n end\nend\n\n@testset \"Gray code - Chinese ring puzzle\" begin\n for n in 2:8\n gc_gen = GrayCodeIter(n)\n gray_codes = [digits(Int8, g, base=2, pad=n) for g in gc_gen]\n check_grayness(gray_codes)\n end\nend\nend # module\n", "meta": {"hexsha": "62396515adac12f5a8c51f0cb90e4c11d1ab0f26", "size": 5844, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "GrayCode/GrayCode.jl", "max_stars_repo_name": "gyk/TrivialSolutions", "max_stars_repo_head_hexsha": "dc461ebfca5756ac261576785c227d77d578cb33", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-07T13:20:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T05:51:37.000Z", "max_issues_repo_path": "GrayCode/GrayCode.jl", "max_issues_repo_name": "gyk/TrivialSolutions", "max_issues_repo_head_hexsha": "dc461ebfca5756ac261576785c227d77d578cb33", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GrayCode/GrayCode.jl", "max_forks_repo_name": "gyk/TrivialSolutions", "max_forks_repo_head_hexsha": "dc461ebfca5756ac261576785c227d77d578cb33", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8584070796, "max_line_length": 100, "alphanum_fraction": 0.5578370979, "num_tokens": 1779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037363973295, "lm_q2_score": 0.8840392817460332, "lm_q1q2_score": 0.818888889803362}} {"text": "# elastic-net regularization\n\n\"\"\"\n ElasticNet(λ::Real=1.0, μ::Real=1.0)\n\nReturns the function `g(x) = μ||x||_1 + (λ/2)||x||²`, for a real parameters `μ, λ ⩾ 0`.\n\"\"\"\n\nimmutable ElasticNet{R <: Real} <: ProximableFunction\n mu::R\n lambda::R\n function ElasticNet(mu::R, lambda::R)\n if lambda < 0 || mu < 0\n error(\"parameters μ, λ must be nonnegative\")\n else\n new(mu, lambda)\n end\n end\nend\n\nElasticNet{R <: Real}(mu::R=1.0, lambda::R=1.0) = ElasticNet{R}(mu, lambda)\n\nfunction (f::ElasticNet){T <: RealOrComplex}(x::AbstractArray{T})\n return f.mu*vecnorm(x,1) + (f.lambda/2)*vecnorm(x,2)^2\nend\n\nfunction prox!{T <: Real}(f::ElasticNet, x::AbstractArray{T}, y::AbstractArray{T}, gamma::Real=1.0)\n sqnorm2x = zero(Float64)\n norm1x = zero(Float64)\n gm = gamma*f.mu\n gl = gamma*f.lambda\n for i in eachindex(x)\n y[i] = (x[i] + (x[i] <= -gm ? gm : (x[i] >= gm ? -gm : -x[i])))/(1 + gl)\n sqnorm2x += abs2(y[i])\n norm1x += abs(y[i])\n end\n return f.mu*norm1x + (f.lambda/2)*sqnorm2x\nend\n\nfunction prox!{T <: Complex}(f::ElasticNet, x::AbstractArray{T}, y::AbstractArray{T}, gamma::Real=1.0)\n sqnorm2x = zero(Float64)\n norm1x = zero(Float64)\n gm = gamma*f.mu\n gl = gamma*f.lambda\n for i in eachindex(x)\n y[i] = sign(x[i])*max(0, abs(x[i]) - gm)/(1 + gl)\n sqnorm2x += abs2(y[i])\n norm1x += abs(y[i])\n end\n return f.mu*norm1x + (f.lambda/2)*sqnorm2x\nend\n\nfun_name(f::ElasticNet) = \"elastic-net regularization\"\nfun_dom(f::ElasticNet) = \"AbstractArray{Real}, AbstractArray{Complex}\"\nfun_expr(f::ElasticNet) = \"x ↦ μ||x||_1 + (λ/2)||x||²\"\nfun_params(f::ElasticNet) = \"μ = $(f.mu), λ = $(f.lambda)\"\n\nfunction prox_naive{T <: RealOrComplex}(f::ElasticNet, x::AbstractArray{T}, gamma::Real=1.0)\n uz = max.(0, abs.(x) - gamma*f.mu)/(1 + f.lambda*gamma);\n return sign.(x).*uz, f.mu*vecnorm(uz,1) + (f.lambda/2)*vecnorm(uz)^2\nend\n", "meta": {"hexsha": "0c130073517909fe2005e158e43fd0d82be808d9", "size": 1863, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/elasticNet.jl", "max_stars_repo_name": "mfalt/ProximalOperators.jl", "max_stars_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functions/elasticNet.jl", "max_issues_repo_name": "mfalt/ProximalOperators.jl", "max_issues_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions/elasticNet.jl", "max_forks_repo_name": "mfalt/ProximalOperators.jl", "max_forks_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0483870968, "max_line_length": 102, "alphanum_fraction": 0.6162104133, "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037363973294, "lm_q2_score": 0.8840392725805822, "lm_q1q2_score": 0.8188888813133706}} {"text": "### A Pluto.jl notebook ###\n# v0.16.1\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ e8595a60-222f-11ec-0595-c9717ac06507\nbegin\n\tusing Plots,SymPy, LaTeXStrings, LinearAlgebra\n\timport PlotlyJS\n\tplotlyjs()\nend\n\n# ╔═╡ 431922d9-e97a-4300-a482-2d458b66c67a\nmd\"\"\" ### Ejercicio 1\nConsidere la cónica dada por $y = x^2 − 4x + 5$ y la recta $L$ que pasa por $(2, 7)$ con\ndirecci´on $v = (1, 1)$\n\"\"\"\n\n# ╔═╡ 85cf0b95-4446-4e84-a6c3-f9d3fcf4cd61\nmd\"\"\"\n1. En un mismo plano cartesiano grafique la recta y la c´onica, obtenga anal´ıticamente los\npuntos de intersecci´on entre ambas y m´arquelos en su gr´afico.\n\n2. Halle el ´area del tri´angulo definido por el v´ertice de la c´onica y los puntos de intersecci´on\nobtenidos anteriormente.\n\"\"\"\n\n# ╔═╡ 53b8d020-b4a9-4c74-b0cc-dba03b6edbd3\n# Definimos las variables s'imbolicas\n@syms x λ\n\n# ╔═╡ 4257606e-3eff-4124-aad3-517998f97d24\nmd\"\"\"\nDefinamos la conica\n\"\"\"\n\n# ╔═╡ 61b1bf99-507b-4379-b537-86ce040f1418\ny = x^2 - 4x + 5\n\n# ╔═╡ d17a8914-6ecf-4606-a664-7242d0f8f06c\nmd\"\"\"\nPara la recta tenemos la siguiente representaci'o \n\n$$L = \\lambda (1, 1) + (2, 7)$$ \n\npero para encontrar la interseccion con la par'abola va a ser m'as 'util representarlo en la forma can'onica de $y = m * x + b$\n\n$$(x,y) = ( \\lambda + 2, \\lambda + 7 )$$\n\nIgualando cada una de las componentes tenemos que\n\n$$y = \\lambda + 7 = (x-2) + 7 = x + 5$$\n\"\"\"\n\n# ╔═╡ 2056778d-12f0-4325-920f-f6c7e453918b\nL =\tx + 5\n\n# ╔═╡ 4f6feaf8-5322-4afc-b31d-211761e222c2\nmd\"\"\"\nGraficando ambas \n\"\"\"\n\n# ╔═╡ f676a35a-c61e-4547-b176-211dd3dc647b\nbegin\n\tp = plot()\n\tplot!(y,label=sympy.latex(y),xlims=(-2,6))\n\tplot!(L, label=sympy.latex(L))\nend\n\n# ╔═╡ d8e3eda0-cada-4047-81cc-137a54e1b5e6\nmd\"\"\"\nCalculamos la intersecci'on entre la recta y la para'bola\n\n`solve` busca las soluciones del sistema $S = 0$ entonces planteamos la igualdad como\n$S = L - y = 0$ que es equivalente a tener $L=y$\n\"\"\"\n\n# ╔═╡ 897cfd67-1be7-40e4-87d9-c11bc9de55d4\ninterseccion = solve(y - L)\n\n# ╔═╡ 67e7f9f5-6e78-4579-97f7-7c0349b39afd\ny_interseccion = y.(interseccion)\n\n# ╔═╡ 4d6550b8-4e9d-4437-84bd-d978e33bfdb8\nmd\"\"\"\nAgregamos los puntos de la intersecci'on al gr'afico\n\"\"\"\n\n# ╔═╡ 997c5ff7-ac5d-484f-bcdf-a89194d112ee\np2 = scatter!(interseccion,y_interseccion,color=:black,label=\"interseccion\",ax=p)\n\n# ╔═╡ 19f1f8b8-0f5c-4388-b550-f4cdd7619311\nmd\"\"\"\nCalculamos el vertice usando la formula de $x_{vert} = \\frac{-b}{2a}$ \ny en nuestro caso queda \n\n$$x_{vert} = \\frac{-(-4)}{2*1} = 2$$\n$$y_{vert} = y(x_{vert}) = 2^{2} - 4 * 2 + 5 = 4 - 8 + 5 = 1$$\n\"\"\"\n\n# ╔═╡ 8e1588d8-1d7a-4151-b8a1-afc3c1298887\np3 = scatter!([2],[1],color=:green,label=\"vertice\",ax=p2)\n\n# ╔═╡ 09baa7ce-fc86-42a5-8130-3c8125c93f5b\nmd\"\"\"\nEntonces ya tenemos los tres vertices del triangulo\n\"\"\"\n\n# ╔═╡ 653aa355-0c9d-4520-befd-d3f91678ffaa\nbegin\n\t# defino con decimales por una cuestion del programa\n\tv₁ = [0.0, 5.0]\n\tv₂ = [5.0, 10.0]\n\tv₃ = [2.0, 1.0]\n\tnothing\nend\n\n# ╔═╡ 1938fc99-5366-4bc0-a2b3-892d7281db93\nmd\"\"\"\nAhora para hallar el area vamos a utilizar el determinante entre dos vectores que definan el triangulo. Voy a considerar los vectores que van desde el vertice $v_{3}$ a los dos puntos de las intersecciones, abusando un poco la notacion $V_{1,3} = v_{1} - v_{3}$, $V_{1,3} = v_{2} - v_{3}$\n\"\"\"\n\n# ╔═╡ 0f723758-c34e-4a3b-ad72-853cc23b29fc\nm = [v₁-v₃ v₂-v₃]\n\n# ╔═╡ 253ae086-b3b0-4243-b05d-4e575166aa53\ndet(m)\n\n# ╔═╡ 9003d85b-eaf0-44f9-b2b7-1dd990e4fd76\nmd\"\"\"\nEl determinante es negativo porque estamos tomando como primer vector el que est'a m'as a la izquierda. Si invertimos el orden en el que armamos la matriz, el determinante va a dar positivo, estamos alternando dos columnas :)\n\nEn conclusion el a'rea es el valor absoluto del determinante dividido dos, entonces tenemos que \n\n``area =`` $(abs(det(m))/2)\n\"\"\"\n\n# ╔═╡ c18c2f4b-1e5f-463f-8464-0a6387896efc\nmd\"\"\"\n## Ejercicio 2. \n\nSean $\\pi : x + 2y + 2z = 12$ y $P = (1, 0, 1)$.\n\na) Hallar el punto de π que se encuentra a menor distancia del punto P y calcular la distancia\nde $P$ al plano $\\pi$.\n\nb) Hallar el volumen del tetraedro (pir´amide de base triangular) definido por P y las intersecciones del plano π con los ejes coordenados. (Recuerde que el volumen del tetraedo es un\nsexto del volumen del paralelep´ıdedo)\n\"\"\"\n\n# ╔═╡ 0f3486cc-8de9-452c-a0a1-b8c5277c1592\nn = [1, 2, 2]\n\n# ╔═╡ f4ee2c3e-7a1b-4d4a-99cf-0dda3ae572d7\nP = [1,0,1]\n\n# ╔═╡ cf0c4904-6b99-4af7-8aee-d03593bc2091\nL₂ = λ*n + P \n\n# ╔═╡ e86f3da1-ab64-4582-9fc7-8f12966c318f\nπ(v) = n ⋅ v - 12\n\n# ╔═╡ 84f78af9-2866-404e-a121-3e3c6afe617b\n# SymMatrix esta indexada desde 0 :(\nπ(L₂)\n\n# ╔═╡ 9bf041fa-c284-4425-831c-2d8a207e54e2\nλₛₒₗ = solve(π(L₂))[1]\n\n# ╔═╡ 512fadab-9352-4d45-b73e-d754b30114e4\nQ = subs.(L₂,λ => λₛₒₗ)\n\n# ╔═╡ 6612a222-06c1-47a8-b024-146ca8caea08\nmd\"\"\"\nUn poco de sanity check, comprobamos que $Q \\in \\pi$\n\"\"\"\n\n# ╔═╡ 604e2572-57d6-4076-b4bc-35adcceb7994\nπ(Q)\n\n# ╔═╡ ef868e86-0a6a-47fb-b2a5-d9190cd03c0a\nmd\"\"\"\nCon esto ya podemos calcular la distancia entre $P$ y $Q$\n\"\"\"\n\n# ╔═╡ 74bf0f00-bc45-4d26-9c61-f164de3d21e0\nmd\"\"\"\n``dist(P,Q) = \\vert P- Q \\vert =`` $(norm(P - Q))\n\"\"\"\n\n# ╔═╡ 50432a00-fdbe-448e-a6c1-89b1d01d435d\nmd\"\"\"\n#### b) Buscamos la interseccion de $\\pi$ con los ejes coordenados\n\"\"\"\n\n# ╔═╡ 4bf801a5-b443-46d1-a110-ab8096527116\nmd\"\"\"\nPrimero definimos el vector can'onico en una direccio'on\n\"\"\"\n\n# ╔═╡ 2136e05b-bef2-4dc8-8723-3fbb8360cba0\ne₁ = [1,0,0]\n\n# ╔═╡ 5532b807-94e2-4ff2-9b65-41d1423863c6\nmd\"\"\"\nComo queremos encontrar la intersecci'on entre el eje y el plano, definimos la recta que sigue al eje coordenado como\n\"\"\"\n\n# ╔═╡ 904d25d1-2244-4f76-ac1c-b1fef76ff41a\nλ * e₁\n\n# ╔═╡ 2ba19d1c-f22e-47c8-b81c-979e0edd7348\nmd\"\"\"\nCuando lo evaluamos en la definici'on del plano tenemos que la interseccio'n occurre cuando la siguiente es igual a $0$\n\"\"\"\n\n# ╔═╡ 9eeb302c-a277-437d-9e95-345b72d1a3a4\nπ(λ * e₁)\n\n# ╔═╡ 15949e72-93cf-4aa6-8524-5b55fe9eb229\nmd\"\"\"\nY eso ocurre cuando ``\\lambda =`` $(solve(π(λ * e₁)))\n\"\"\"\n\n# ╔═╡ 6935e6f6-e926-4766-89a4-8d86408cc15d\ninterseccion_con_π(v) = solve(π(λ * v))[1]\n\n# ╔═╡ aed97c10-bcae-4552-b522-afb0a6073c7a\nmd\"\"\"\nExtendemos el c'alculo de la intersecci'on del plano con los otros dos ejes obteniendo los siguentes puntos \n\"\"\"\n\n# ╔═╡ 760596e6-3937-4024-b3b4-7bfae97c4a4f\nbegin\n\te₂ = [0,1,0]\n\te₃ = [0,0,1]\n\tx₁ = interseccion_con_π(e₁) * e₁\n\tx₂ = interseccion_con_π(e₂) * e₂\n\tx₃ = interseccion_con_π(e₃) * e₃\n\tx₁, x₂, x₃\nend\n\n# ╔═╡ 64d47104-23e7-492c-aa5e-c6eee7f6d10d\nmd\"\"\"\nPara tener un poco m'as de intuici'on los graficamos\n\"\"\"\n\n# ╔═╡ ff31fe54-2f96-4e12-bf62-395dd29fa515\nbegin \n\tfigura = scatter3d([P[1]],[P[2]],[P[3]],label=\"P\",xlabel=\"x\",ylabel=\"y\",zlabel=\"z\")\n\tfor p in [x₁, x₂, x₃]\n\t\tscatter3d!([p[1]],[p[2]],[p[3]],label=false,ax=figura)\n\tend\n\tfigura\nend\n\n# ╔═╡ 6867d0da-516e-4924-b3f3-be7bbe75d4fc\nmd\"\"\"\nPara calcular el volumen primero consideramos los vectores que van de $P$ a cada uno de los tres puntos $V_{i}$ que encontramos antes. Para eso calculamos $V_{i} - P$, para cada uno de los ejes y los ordenamos a cada uno como una columna de una matriz de manera de que podamos calcular el determinante\n\"\"\"\n\n# ╔═╡ 9ca33e7d-aa40-4970-9072-bcf0f754ec04\nM = [x₁ x₂ x₃] .- P\n\n# ╔═╡ fe385398-3bd1-4662-8411-e2c9beda9a9f\nmd\"\"\"\nQue tiene el determinante igual a\n\"\"\"\n\n# ╔═╡ 672d62df-7c33-4260-8c4f-a72e8a900bd3\ndet(M)\n\n# ╔═╡ c389944d-1d91-44aa-a28d-d0848bb10228\nmd\"\"\"\nUsando la ayuda del enunciado tenemos que el volumen del tetaedro es ``\\frac{\\vert det(M)\\vert}{6} = `` $(det(M)/6)\n\"\"\"\n\n# ╔═╡ e7d5a0e0-0b6b-4012-88cd-7e50283fb721\nmd\"\"\"\n### Ejercicio 3. \n\nPara $\\alpha \\in \\mathbb{R}$ considere la matriz $A \\in \\mathbb{R}^{3×3}$ dada por\n\n$\\left[ \n\\begin{array}{rrr}\n 1 & 0 & \\alpha \\\\\n \\alpha & \\alpha - 1 & \\alpha^{2} \\\\\n 0 & 1 & \\alpha - 2\n\\end{array}\\right]$\n\n\n1. Halle todos los valores de $\\alpha$ para los cuales $A^{2021} − A^{2022}$ no resulte inversible.\n\n2. Ponga $\\alpha = 2$. Utilice el m´etodo de Gauss para resolver\n\n$$Ax = e_{1} + e_{2} − e_{3}$$\n\n`INDICANDO TODAS LAS OPERACIONES DE FILAS QUE UTILIZA. Exhiba la solucien forma param´etrica y la matriz escalonada reducida del sistema; se˜nale el rango de\nA.`\n\"\"\"\n\n# ╔═╡ fc2349c9-fb1f-4ce3-94fc-adb98f3170b8\n# Definimos el simbolo\n@syms α\n\n# ╔═╡ 30e16586-b504-4332-9f6c-cdeb3f9c686c\nA = [1 0 α;\n\tα α-1 α^2;\n\t0 1 α-2]\n\n# ╔═╡ 2f8356bc-311a-4826-861e-4852ed01bca1\nmd\"\"\"\nEl ejercicio nos pide que calculemos cuando la siguiente matriz no es inversible $A^{2021} − A^{2022}$, lo cual parece una locura. Pero recordemos que una manera de evaluar si una matriz es inversible es a partir del determinante. Y la matriz va a ser inversible en el caso de que su determinante sea distinto de 0 \n\"\"\"\n\n# ╔═╡ 45d7938f-a9ff-4a21-b0f8-74a7b69e1a3d\nmd\"\"\"\n$\\begin{align}\ndet(A^{2021} − A^{2022}) &= det( A^{2021}*(I-A) ) \\\\\n &= det( A^{2021} ) * det(I-A)\\\\\n &= det( A )^{2021} * det(I-A)\n\\end{align}$\n\"\"\"\n\n# ╔═╡ af547106-640f-4d89-b96d-b1d625822697\nI - A\n\n# ╔═╡ a2779834-7808-4bad-a97a-bc90dba2adc7\ndeterminante = det(A)^2021 * det(I-A)\n\n# ╔═╡ d9ef00bd-1ac5-4406-9cb7-ae9d90d2387e\nmd\"\"\"\nEl determinante se anula en el caso de que cualquiera de los terminos sea igual a cero, entonces tenemos que\n\"\"\"\n\n# ╔═╡ 76c7aed0-4bac-4a03-8a07-00583c571c52\nsolve(det(A))\n\n# ╔═╡ 180d6fe0-baeb-4c05-bfc9-213a6f1ec07c\nsolve(det(I-A))\n\n# ╔═╡ a7da009c-b867-46d2-84a2-087287521aa8\nmd\"\"\"\nEntonces es la matriz no es inversible si $\\alpha \\in \\{0,1,2\\}$\n\"\"\"\n\n# ╔═╡ 5522536b-a0df-41f8-8525-856923f49104\nmd\"\"\"\nPara resolver el punto b), reemplazamos $\\alpha = 2$. Notemos que es uno de los valores en los que el la matriz no era inversible, eso nos esta diciendo que el sistema no est'a completamete determinado.\n\"\"\"\n\n# ╔═╡ 337404a1-514b-4f40-9aa7-738d0c07d34f\nAₛ = subs.(A, α=>2)\n\n# ╔═╡ 7dcb7519-f6cc-47b6-bbf2-1896a0053a85\nmd\"\"\"\nResolviendo el sistema por el metodo de Gauss-Jordan\n\n$$A x = (1,1,-1)$$\n\"\"\"\n\n# ╔═╡ dd6b45de-fa40-4697-a372-d7f6a75bc704\nmd\"\"\"\nLlegamos a que la solucion es el siguiente vector\n\"\"\"\n\n# ╔═╡ e052a4ad-90a0-4f7f-a1e7-a35b92270d74\nAₛ\\[1,1,-1]\n\n# ╔═╡ 65dcc377-8278-4c08-867b-012065989b1f\nmd\"\"\"\nQue representa la recta \n\n``\nL_{s} = λ (-2,0,1) + (1,-1,0)\n``\n\"\"\"\n\n# ╔═╡ c2c157cb-29fa-488b-a5dd-caef9e392c6b\nmd\"\"\"\n### Ejercicio 4.\n\na) Sean $u, v \\in \\mathbb{R}^{2}$ dos vectores tales que $det(u, v) = 3$.\nHallar el ´area del paralelogramo determinado por los vectores $2u + 3v$ y $u − 4v$.\n\nb) Decidir si la siguiente afirmaci´on es verdadera o falsa. Si es verdadera, dar una demostraci´on. Si es falsa, dar un contraejemplo.\n\nSean $L_{1}$ y $L_{2}$ son dos rectas en $R^{3}$\n\nSi $L_{1} \\cap L_{2} = \\emptyset$, entonces $L_{1}$ y $L_{2}$ son paralelas.\n\"\"\"\n\n# ╔═╡ 1dd55ddd-2c09-4d8c-83d3-442ebcf0d579\n# definimos los vectores simbolicos\nbegin\n\t@syms u[1:2] v[1:2]\nend\n\n# ╔═╡ 0bd81932-75a6-4b74-a264-bb16ae798a44\ndet([u v])\n\n# ╔═╡ c3ca6592-a758-40fc-96c5-e8609071697f\ndet([2u+3v u-4v])\n\n# ╔═╡ 279a2774-a565-4ffa-9577-b2e987abed37\nsimplify(det([2u+3v u-4v]) / det([u v]))\n\n# ╔═╡ 1dd28947-9fa2-42bc-9666-6e1b5e12a147\nmd\"\"\"\nEn el punto **b)** La afirmación es **falsa**, pues pueden existir dos rectas que no sean paralelas y no tengan intersección\n\nPor ejemplo, si tomamos:\n\n$$L_{a} = \\lambda_{a} (1,0,0) + (0,0,0)$$\n\n$$L_{b} = \\lambda_{b} (0,1,0) + (0,0,1)$$\n\"\"\"\n\n# ╔═╡ 2b0dc6fe-ae32-48c9-a400-ad5fb8fbef4e\nLₐ(λ) = λ*[1,0,0]\n\n# ╔═╡ 40420c6d-122b-454d-9954-8ec29765f3f2\nLₚ(λ) = λ*[0,1,0] + [0,0,1]\n\n# ╔═╡ be180c4f-177b-41a7-83d3-5a0220c9ad0e\nbegin\nt = -1:1\n# scatter3d(,)\nend\n\n# ╔═╡ 067ffcf8-a398-4e50-bcf7-5425906f4a87\ncollect(map(Array,zip(Lₐ.(t)...)))\n\n# ╔═╡ a1ce3aac-6e19-4de0-bcd5-4e86b26aab71\nlet \nx,y,z =\tcollect(zip(Lₐ.(t)...))\n# plot3d([x],[y],[z],xlabel=\"x\",ylabel=\"y\",zlabel=\"z\")\nend\n\n# ╔═╡ 3cf6ffc2-0f08-41f7-adaa-9fa22f585881\n# Para referencia\nrepr(\"text/latex\",A);\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nLaTeXStrings = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nLinearAlgebra = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\nPlotlyJS = \"f0f68f2c-4968-5e81-91da-67840de0976a\"\nPlots = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nSymPy = \"24249f21-da20-56a4-8eb1-6a02cf4ae2e6\"\n\n[compat]\nLaTeXStrings = \"~1.2.1\"\nPlotlyJS = \"~0.18.7\"\nPlots = \"~1.22.3\"\nSymPy = \"~1.0.52\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\n[[Adapt]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"84918055d15b3114ede17ac6a7182f68870c16f7\"\nuuid = \"79e6a3ab-5dfb-504d-930d-738a2a938a0e\"\nversion = \"3.3.1\"\n\n[[ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[AssetRegistry]]\ndeps = [\"Distributed\", \"JSON\", \"Pidfile\", \"SHA\", \"Test\"]\ngit-tree-sha1 = \"b25e88db7944f98789130d7b503276bc34bc098e\"\nuuid = \"bf4720bc-e11a-5d0c-854e-bdca1663c893\"\nversion = \"0.1.0\"\n\n[[Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[BinDeps]]\ndeps = [\"Libdl\", \"Pkg\", \"SHA\", \"URIParser\", \"Unicode\"]\ngit-tree-sha1 = \"1289b57e8cf019aede076edab0587eb9644175bd\"\nuuid = \"9e28174c-4ba2-5203-b857-d8d62c4213ee\"\nversion = \"1.0.2\"\n\n[[Blink]]\ndeps = [\"Base64\", \"BinDeps\", \"Distributed\", \"JSExpr\", \"JSON\", \"Lazy\", \"Logging\", \"MacroTools\", \"Mustache\", \"Mux\", \"Reexport\", \"Sockets\", \"WebIO\", \"WebSockets\"]\ngit-tree-sha1 = \"08d0b679fd7caa49e2bca9214b131289e19808c0\"\nuuid = \"ad839575-38b3-5650-b840-f874b8c74a25\"\nversion = \"0.12.5\"\n\n[[Bzip2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"19a35467a82e236ff51bc17a3a44b69ef35185a2\"\nuuid = \"6e34b625-4abd-537c-b88f-471c36dfa7a0\"\nversion = \"1.0.8+0\"\n\n[[Cairo_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"JLLWrappers\", \"LZO_jll\", \"Libdl\", \"Pixman_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"f2202b55d816427cd385a9a4f3ffb226bee80f99\"\nuuid = \"83423d85-b0ee-5818-9007-b63ccbeb887a\"\nversion = \"1.16.1+0\"\n\n[[ChainRulesCore]]\ndeps = [\"Compat\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"e8a30e8019a512e4b6c56ccebc065026624660e8\"\nuuid = \"d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4\"\nversion = \"1.7.0\"\n\n[[ColorSchemes]]\ndeps = [\"ColorTypes\", \"Colors\", \"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"a851fec56cb73cfdf43762999ec72eff5b86882a\"\nuuid = \"35d6a980-a343-548e-a6ea-1d62b119f2f4\"\nversion = \"3.15.0\"\n\n[[ColorTypes]]\ndeps = [\"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"024fe24d83e4a5bf5fc80501a314ce0d1aa35597\"\nuuid = \"3da002f7-5984-5a60-b8a6-cbb66c0b333f\"\nversion = \"0.11.0\"\n\n[[Colors]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"Reexport\"]\ngit-tree-sha1 = \"417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40\"\nuuid = \"5ae59095-9a9b-59fe-a467-6f913c188581\"\nversion = \"0.12.8\"\n\n[[CommonEq]]\ngit-tree-sha1 = \"d1beba82ceee6dc0fce8cb6b80bf600bbde66381\"\nuuid = \"3709ef60-1bee-4518-9f2f-acd86f176c50\"\nversion = \"0.2.0\"\n\n[[CommonSolve]]\ngit-tree-sha1 = \"68a0743f578349ada8bc911a5cbd5a2ef6ed6d1f\"\nuuid = \"38540f10-b2f7-11e9-35d8-d573e4eb0ff2\"\nversion = \"0.2.0\"\n\n[[Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"31d0151f5716b655421d9d75b7fa74cc4e744df2\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.39.0\"\n\n[[CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[Conda]]\ndeps = [\"JSON\", \"VersionParsing\"]\ngit-tree-sha1 = \"299304989a5e6473d985212c28928899c74e9421\"\nuuid = \"8f4d0f93-b110-5947-807f-2305c1781a2d\"\nversion = \"1.5.2\"\n\n[[Contour]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"9f02045d934dc030edad45944ea80dbd1f0ebea7\"\nuuid = \"d38c429a-6771-53c6-b99e-75d170b6e991\"\nversion = \"0.5.7\"\n\n[[DataAPI]]\ngit-tree-sha1 = \"cc70b17275652eb47bc9e5f81635981f13cea5c8\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.9.0\"\n\n[[DataStructures]]\ndeps = [\"Compat\", \"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"7d9d316f04214f7efdbb6398d545446e246eff02\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.18.10\"\n\n[[DataValueInterfaces]]\ngit-tree-sha1 = \"bfc1187b79289637fa0ef6d4436ebdfe6905cbd6\"\nuuid = \"e2d170a0-9d28-54be-80f0-106bbe20a464\"\nversion = \"1.0.0\"\n\n[[Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[DocStringExtensions]]\ndeps = [\"LibGit2\"]\ngit-tree-sha1 = \"a32185f5428d3986f47c2ab78b1f216d5e6cc96f\"\nuuid = \"ffbed154-4ef7-542d-bbb7-c09d3a79fcae\"\nversion = \"0.8.5\"\n\n[[Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[EarCut_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"3f3a2501fa7236e9b911e0f7a588c657e822bb6d\"\nuuid = \"5ae413db-bbd1-5e63-b57d-d24a61df00f5\"\nversion = \"2.2.3+0\"\n\n[[Expat_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b3bfd02e98aedfa5cf885665493c5598c350cd2f\"\nuuid = \"2e619515-83b5-522b-bb60-26c02a35a201\"\nversion = \"2.2.10+0\"\n\n[[FFMPEG]]\ndeps = [\"FFMPEG_jll\"]\ngit-tree-sha1 = \"b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8\"\nuuid = \"c87230d0-a227-11e9-1b43-d7ebe4e7570a\"\nversion = \"0.4.1\"\n\n[[FFMPEG_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"JLLWrappers\", \"LAME_jll\", \"Libdl\", \"Ogg_jll\", \"OpenSSL_jll\", \"Opus_jll\", \"Pkg\", \"Zlib_jll\", \"libass_jll\", \"libfdk_aac_jll\", \"libvorbis_jll\", \"x264_jll\", \"x265_jll\"]\ngit-tree-sha1 = \"d8a578692e3077ac998b50c0217dfd67f21d1e5f\"\nuuid = \"b22a6f82-2f65-5046-a5b2-351ab43fb4e5\"\nversion = \"4.4.0+0\"\n\n[[FileWatching]]\nuuid = \"7b1f6079-737a-58dc-b8bc-7a2ca5c1b5ee\"\n\n[[FixedPointNumbers]]\ndeps = [\"Statistics\"]\ngit-tree-sha1 = \"335bfdceacc84c5cdf16aadc768aa5ddfc5383cc\"\nuuid = \"53c48c17-4a7d-5ca2-90c5-79b7896eea93\"\nversion = \"0.8.4\"\n\n[[Fontconfig_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Expat_jll\", \"FreeType2_jll\", \"JLLWrappers\", \"Libdl\", \"Libuuid_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"21efd19106a55620a188615da6d3d06cd7f6ee03\"\nuuid = \"a3f928ae-7b40-5064-980b-68af3947d34b\"\nversion = \"2.13.93+0\"\n\n[[Formatting]]\ndeps = [\"Printf\"]\ngit-tree-sha1 = \"8339d61043228fdd3eb658d86c926cb282ae72a8\"\nuuid = \"59287772-0a20-5a39-b81b-1366585eb4c0\"\nversion = \"0.4.2\"\n\n[[FreeType2_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"87eb71354d8ec1a96d4a7636bd57a7347dde3ef9\"\nuuid = \"d7e528f0-a631-5988-bf34-fe36492bcfd7\"\nversion = \"2.10.4+0\"\n\n[[FriBidi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"aa31987c2ba8704e23c6c8ba8a4f769d5d7e4f91\"\nuuid = \"559328eb-81f9-559d-9380-de523a88c83c\"\nversion = \"1.0.10+0\"\n\n[[FunctionalCollections]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"04cb9cfaa6ba5311973994fe3496ddec19b6292a\"\nuuid = \"de31a74c-ac4f-5751-b3fd-e18cd04993ca\"\nversion = \"0.5.0\"\n\n[[GLFW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"Pkg\", \"Xorg_libXcursor_jll\", \"Xorg_libXi_jll\", \"Xorg_libXinerama_jll\", \"Xorg_libXrandr_jll\"]\ngit-tree-sha1 = \"dba1e8614e98949abfa60480b13653813d8f0157\"\nuuid = \"0656b61e-2033-5cc2-a64a-77c0f6c09b89\"\nversion = \"3.3.5+0\"\n\n[[GR]]\ndeps = [\"Base64\", \"DelimitedFiles\", \"GR_jll\", \"HTTP\", \"JSON\", \"Libdl\", \"LinearAlgebra\", \"Pkg\", \"Printf\", \"Random\", \"Serialization\", \"Sockets\", \"Test\", \"UUIDs\"]\ngit-tree-sha1 = \"c2178cfbc0a5a552e16d097fae508f2024de61a3\"\nuuid = \"28b8d3ca-fb5f-59d9-8090-bfdbd6d07a71\"\nversion = \"0.59.0\"\n\n[[GR_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Cairo_jll\", \"FFMPEG_jll\", \"Fontconfig_jll\", \"GLFW_jll\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Libtiff_jll\", \"Pixman_jll\", \"Pkg\", \"Qt5Base_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"ef49a187604f865f4708c90e3f431890724e9012\"\nuuid = \"d2c73de3-f751-5644-a686-071e5b155ba9\"\nversion = \"0.59.0+0\"\n\n[[GeometryBasics]]\ndeps = [\"EarCut_jll\", \"IterTools\", \"LinearAlgebra\", \"StaticArrays\", \"StructArrays\", \"Tables\"]\ngit-tree-sha1 = \"58bcdf5ebc057b085e58d95c138725628dd7453c\"\nuuid = \"5c1252a2-5f33-56bf-86c9-59e7332b4326\"\nversion = \"0.4.1\"\n\n[[Gettext_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"9b02998aba7bf074d14de89f9d37ca24a1a0b046\"\nuuid = \"78b55507-aeef-58d4-861c-77aaff3498b1\"\nversion = \"0.21.0+0\"\n\n[[Glib_jll]]\ndeps = [\"Artifacts\", \"Gettext_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Libiconv_jll\", \"Libmount_jll\", \"PCRE_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"7bf67e9a481712b3dbe9cb3dac852dc4b1162e02\"\nuuid = \"7746bdde-850d-59dc-9ae8-88ece973131d\"\nversion = \"2.68.3+0\"\n\n[[Graphite2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"344bf40dcab1073aca04aa0df4fb092f920e4011\"\nuuid = \"3b182d85-2403-5c21-9c21-1e1f0cc25472\"\nversion = \"1.3.14+0\"\n\n[[Grisu]]\ngit-tree-sha1 = \"53bb909d1151e57e2484c3d1b53e19552b887fb2\"\nuuid = \"42e2da0e-8278-4e71-bc24-59509adca0fe\"\nversion = \"1.0.2\"\n\n[[HTTP]]\ndeps = [\"Base64\", \"Dates\", \"IniFile\", \"Logging\", \"MbedTLS\", \"NetworkOptions\", \"Sockets\", \"URIs\"]\ngit-tree-sha1 = \"14eece7a3308b4d8be910e265c724a6ba51a9798\"\nuuid = \"cd3eb016-35fb-5094-929b-558a96fad6f3\"\nversion = \"0.9.16\"\n\n[[HarfBuzz_jll]]\ndeps = [\"Artifacts\", \"Cairo_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"Graphite2_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\"]\ngit-tree-sha1 = \"8a954fed8ac097d5be04921d595f741115c1b2ad\"\nuuid = \"2e76f6c2-a576-52d4-95c1-20adfe4de566\"\nversion = \"2.8.1+0\"\n\n[[Hiccup]]\ndeps = [\"MacroTools\", \"Test\"]\ngit-tree-sha1 = \"6187bb2d5fcbb2007c39e7ac53308b0d371124bd\"\nuuid = \"9fb69e20-1954-56bb-a84f-559cc56a8ff7\"\nversion = \"0.2.2\"\n\n[[IniFile]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"098e4d2c533924c921f9f9847274f2ad89e018b8\"\nuuid = \"83e8ac13-25f8-5344-8a64-a9f2b223428f\"\nversion = \"0.5.0\"\n\n[[InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[IrrationalConstants]]\ngit-tree-sha1 = \"f76424439413893a832026ca355fe273e93bce94\"\nuuid = \"92d709cd-6900-40b7-9082-c6be49f344b6\"\nversion = \"0.1.0\"\n\n[[IterTools]]\ngit-tree-sha1 = \"05110a2ab1fc5f932622ffea2a003221f4782c18\"\nuuid = \"c8e1da08-722c-5040-9ed9-7db0dc04731e\"\nversion = \"1.3.0\"\n\n[[IteratorInterfaceExtensions]]\ngit-tree-sha1 = \"a3f24677c21f5bbe9d2a714f95dcd58337fb2856\"\nuuid = \"82899510-4779-5014-852e-03e436cf321d\"\nversion = \"1.0.0\"\n\n[[JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"642a199af8b68253517b80bd3bfd17eb4e84df6e\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.3.0\"\n\n[[JSExpr]]\ndeps = [\"JSON\", \"MacroTools\", \"Observables\", \"WebIO\"]\ngit-tree-sha1 = \"bd6c034156b1e7295450a219c4340e32e50b08b1\"\nuuid = \"97c1335a-c9c5-57fe-bc5d-ec35cebe8660\"\nversion = \"0.5.3\"\n\n[[JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"8076680b162ada2a031f707ac7b4953e30667a37\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.2\"\n\n[[JpegTurbo_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d735490ac75c5cb9f1b00d8b5509c11984dc6943\"\nuuid = \"aacddb02-875f-59d6-b918-886e6ef4fbf8\"\nversion = \"2.1.0+0\"\n\n[[Kaleido_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"2ef87eeaa28713cb010f9fb0be288b6c1a4ecd53\"\nuuid = \"f7e6163d-2fa5-5f23-b69c-1db539e41963\"\nversion = \"0.1.0+0\"\n\n[[LAME_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"f6250b16881adf048549549fba48b1161acdac8c\"\nuuid = \"c1c5ebd0-6772-5130-a774-d5fcae4a789d\"\nversion = \"3.100.1+0\"\n\n[[LZO_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e5b909bcf985c5e2605737d2ce278ed791b89be6\"\nuuid = \"dd4b983a-f0e5-5f8d-a1b7-129d4a5fb1ac\"\nversion = \"2.10.1+0\"\n\n[[LaTeXStrings]]\ngit-tree-sha1 = \"c7f1c695e06c01b95a67f0cd1d34994f3e7db104\"\nuuid = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nversion = \"1.2.1\"\n\n[[Latexify]]\ndeps = [\"Formatting\", \"InteractiveUtils\", \"LaTeXStrings\", \"MacroTools\", \"Markdown\", \"Printf\", \"Requires\"]\ngit-tree-sha1 = \"a4b12a1bd2ebade87891ab7e36fdbce582301a92\"\nuuid = \"23fbe1c1-3f47-55db-b15f-69d7ec21a316\"\nversion = \"0.15.6\"\n\n[[Lazy]]\ndeps = [\"MacroTools\"]\ngit-tree-sha1 = \"1370f8202dac30758f3c345f9909b97f53d87d3f\"\nuuid = \"50d2b5c4-7a5e-59d5-8109-a42b560f39c0\"\nversion = \"0.15.1\"\n\n[[LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[Libffi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"761a393aeccd6aa92ec3515e428c26bf99575b3b\"\nuuid = \"e9f186c6-92d2-5b65-8a66-fee21dc1b490\"\nversion = \"3.2.2+0\"\n\n[[Libgcrypt_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgpg_error_jll\", \"Pkg\"]\ngit-tree-sha1 = \"64613c82a59c120435c067c2b809fc61cf5166ae\"\nuuid = \"d4300ac3-e22c-5743-9152-c294e39db1e4\"\nversion = \"1.8.7+0\"\n\n[[Libglvnd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"7739f837d6447403596a75d19ed01fd08d6f56bf\"\nuuid = \"7e76a0d4-f3c7-5321-8279-8d96eeed0f29\"\nversion = \"1.3.0+3\"\n\n[[Libgpg_error_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c333716e46366857753e273ce6a69ee0945a6db9\"\nuuid = \"7add5ba3-2f88-524e-9cd5-f83b8a55f7b8\"\nversion = \"1.42.0+0\"\n\n[[Libiconv_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"42b62845d70a619f063a7da093d995ec8e15e778\"\nuuid = \"94ce4f54-9a6c-5748-9c1c-f9c7231a4531\"\nversion = \"1.16.1+1\"\n\n[[Libmount_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"9c30530bf0effd46e15e0fdcf2b8636e78cbbd73\"\nuuid = \"4b2f31a3-9ecc-558c-b454-b3730dcb73e9\"\nversion = \"2.35.0+0\"\n\n[[Libtiff_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Pkg\", \"Zlib_jll\", \"Zstd_jll\"]\ngit-tree-sha1 = \"340e257aada13f95f98ee352d316c3bed37c8ab9\"\nuuid = \"89763e89-9b03-5906-acba-b20f662cd828\"\nversion = \"4.3.0+0\"\n\n[[Libuuid_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7f3efec06033682db852f8b3bc3c1d2b0a0ab066\"\nuuid = \"38a345b3-de98-5d2b-a5d3-14cd9215e700\"\nversion = \"2.36.0+0\"\n\n[[LinearAlgebra]]\ndeps = [\"Libdl\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[LogExpFunctions]]\ndeps = [\"ChainRulesCore\", \"DocStringExtensions\", \"IrrationalConstants\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"34dc30f868e368f8a17b728a1238f3fcda43931a\"\nuuid = \"2ab3a3ac-af41-5b50-aa03-7779005ae688\"\nversion = \"0.3.3\"\n\n[[Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"5a5bc6bf062f0f95e62d0fe0a2d99699fed82dd9\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.8\"\n\n[[Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[MbedTLS]]\ndeps = [\"Dates\", \"MbedTLS_jll\", \"Random\", \"Sockets\"]\ngit-tree-sha1 = \"1c38e51c3d08ef2278062ebceade0e46cefc96fe\"\nuuid = \"739be429-bea8-5141-9913-cc70e7f3736d\"\nversion = \"1.0.3\"\n\n[[MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[Measures]]\ngit-tree-sha1 = \"e498ddeee6f9fdb4551ce855a46f54dbd900245f\"\nuuid = \"442fdcdd-2543-5da2-b0f3-8c86c306513e\"\nversion = \"0.3.1\"\n\n[[Missings]]\ndeps = [\"DataAPI\"]\ngit-tree-sha1 = \"bf210ce90b6c9eed32d25dbcae1ebc565df2687f\"\nuuid = \"e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28\"\nversion = \"1.0.2\"\n\n[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[Mustache]]\ndeps = [\"Printf\", \"Tables\"]\ngit-tree-sha1 = \"36995ef0d532fe08119d70b2365b7b03d4e00f48\"\nuuid = \"ffc61752-8dc7-55ee-8c37-f3e9cdd09e70\"\nversion = \"1.0.10\"\n\n[[Mux]]\ndeps = [\"AssetRegistry\", \"Base64\", \"HTTP\", \"Hiccup\", \"Pkg\", \"Sockets\", \"WebSockets\"]\ngit-tree-sha1 = \"82dfb2cead9895e10ee1b0ca37a01088456c4364\"\nuuid = \"a975b10e-0019-58db-a62f-e48ff68538c9\"\nversion = \"0.7.6\"\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[[Observables]]\ngit-tree-sha1 = \"fe29afdef3d0c4a8286128d4e45cc50621b1e43d\"\nuuid = \"510215fc-4207-5dde-b226-833fc4488ee2\"\nversion = \"0.4.0\"\n\n[[Ogg_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7937eda4681660b4d6aeeecc2f7e1c81c8ee4e2f\"\nuuid = \"e7412a2a-1a6e-54c0-be00-318e2571c051\"\nversion = \"1.3.5+0\"\n\n[[OpenLibm_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"05823500-19ac-5b8b-9628-191a04bc5112\"\n\n[[OpenSSL_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"15003dcb7d8db3c6c857fda14891a539a8f2705a\"\nuuid = \"458c3c95-2e84-50aa-8efc-19380b2a3a95\"\nversion = \"1.1.10+0\"\n\n[[OpenSpecFun_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"13652491f6856acfd2db29360e1bbcd4565d04f1\"\nuuid = \"efe28fd5-8261-553b-a9e1-b2916fc3738e\"\nversion = \"0.5.5+0\"\n\n[[Opus_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"51a08fb14ec28da2ec7a927c4337e4332c2a4720\"\nuuid = \"91d4177d-7536-5919-b921-800302f37372\"\nversion = \"1.3.2+0\"\n\n[[OrderedCollections]]\ngit-tree-sha1 = \"85f8e6578bf1f9ee0d11e7bb1b1456435479d47c\"\nuuid = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nversion = \"1.4.1\"\n\n[[PCRE_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b2a7af664e098055a7529ad1a900ded962bca488\"\nuuid = \"2f80f16e-611a-54ab-bc61-aa92de5b98fc\"\nversion = \"8.44.0+0\"\n\n[[Parameters]]\ndeps = [\"OrderedCollections\", \"UnPack\"]\ngit-tree-sha1 = \"34c0e9ad262e5f7fc75b10a9952ca7692cfc5fbe\"\nuuid = \"d96e819e-fc66-5662-9728-84c9c7592b0a\"\nversion = \"0.12.3\"\n\n[[Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"9d8c00ef7a8d110787ff6f170579846f776133a9\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.0.4\"\n\n[[Pidfile]]\ndeps = [\"FileWatching\", \"Test\"]\ngit-tree-sha1 = \"1be8660b2064893cd2dae4bd004b589278e4440d\"\nuuid = \"fa939f87-e72e-5be4-a000-7fc836dbe307\"\nversion = \"1.2.0\"\n\n[[Pixman_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b4f5d02549a10e20780a24fce72bea96b6329e29\"\nuuid = \"30392449-352a-5448-841d-b1acce4e97dc\"\nversion = \"0.40.1+0\"\n\n[[Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[PlotThemes]]\ndeps = [\"PlotUtils\", \"Requires\", \"Statistics\"]\ngit-tree-sha1 = \"a3a964ce9dc7898193536002a6dd892b1b5a6f1d\"\nuuid = \"ccf2f8ad-2431-5c83-bf29-c5338b663b6a\"\nversion = \"2.0.1\"\n\n[[PlotUtils]]\ndeps = [\"ColorSchemes\", \"Colors\", \"Dates\", \"Printf\", \"Random\", \"Reexport\", \"Statistics\"]\ngit-tree-sha1 = \"2537ed3c0ed5e03896927187f5f2ee6a4ab342db\"\nuuid = \"995b91a9-d308-5afd-9ec6-746e21dbc043\"\nversion = \"1.0.14\"\n\n[[PlotlyBase]]\ndeps = [\"ColorSchemes\", \"Dates\", \"DelimitedFiles\", \"DocStringExtensions\", \"JSON\", \"LaTeXStrings\", \"Logging\", \"Parameters\", \"Pkg\", \"REPL\", \"Requires\", \"Statistics\", \"UUIDs\"]\ngit-tree-sha1 = \"180d744848ba316a3d0fdf4dbd34b77c7242963a\"\nuuid = \"a03496cd-edff-5a9b-9e67-9cda94a718b5\"\nversion = \"0.8.18\"\n\n[[PlotlyJS]]\ndeps = [\"Base64\", \"Blink\", \"DelimitedFiles\", \"JSExpr\", \"JSON\", \"Kaleido_jll\", \"Markdown\", \"Pkg\", \"PlotlyBase\", \"REPL\", \"Reexport\", \"Requires\", \"WebIO\"]\ngit-tree-sha1 = \"ec6bc7270269be2d565b272116ca74ca2f8bd9ab\"\nuuid = \"f0f68f2c-4968-5e81-91da-67840de0976a\"\nversion = \"0.18.7\"\n\n[[Plots]]\ndeps = [\"Base64\", \"Contour\", \"Dates\", \"Downloads\", \"FFMPEG\", \"FixedPointNumbers\", \"GR\", \"GeometryBasics\", \"JSON\", \"Latexify\", \"LinearAlgebra\", \"Measures\", \"NaNMath\", \"PlotThemes\", \"PlotUtils\", \"Printf\", \"REPL\", \"Random\", \"RecipesBase\", \"RecipesPipeline\", \"Reexport\", \"Requires\", \"Scratch\", \"Showoff\", \"SparseArrays\", \"Statistics\", \"StatsBase\", \"UUIDs\"]\ngit-tree-sha1 = \"cfbd033def161db9494f86c5d18fbf874e09e514\"\nuuid = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nversion = \"1.22.3\"\n\n[[Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"00cfd92944ca9c760982747e9a1d0d5d86ab1e5a\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.2\"\n\n[[Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[PyCall]]\ndeps = [\"Conda\", \"Dates\", \"Libdl\", \"LinearAlgebra\", \"MacroTools\", \"Serialization\", \"VersionParsing\"]\ngit-tree-sha1 = \"169bb8ea6b1b143c5cf57df6d34d022a7b60c6db\"\nuuid = \"438e738f-606a-5dbb-bf0a-cddfbfd45ab0\"\nversion = \"1.92.3\"\n\n[[Qt5Base_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Fontconfig_jll\", \"Glib_jll\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"OpenSSL_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libxcb_jll\", \"Xorg_xcb_util_image_jll\", \"Xorg_xcb_util_keysyms_jll\", \"Xorg_xcb_util_renderutil_jll\", \"Xorg_xcb_util_wm_jll\", \"Zlib_jll\", \"xkbcommon_jll\"]\ngit-tree-sha1 = \"ad368663a5e20dbb8d6dc2fddeefe4dae0781ae8\"\nuuid = \"ea2cea3b-5b76-57ae-a6ef-0a8af62496e1\"\nversion = \"5.15.3+0\"\n\n[[REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[RecipesBase]]\ngit-tree-sha1 = \"44a75aa7a527910ee3d1751d1f0e4148698add9e\"\nuuid = \"3cdcf5f2-1ef4-517c-9805-6587b60abb01\"\nversion = \"1.1.2\"\n\n[[RecipesPipeline]]\ndeps = [\"Dates\", \"NaNMath\", \"PlotUtils\", \"RecipesBase\"]\ngit-tree-sha1 = \"7ad0dfa8d03b7bcf8c597f59f5292801730c55b8\"\nuuid = \"01d81517-befc-4cb6-b9ec-a95719d0359c\"\nversion = \"0.4.1\"\n\n[[Reexport]]\ngit-tree-sha1 = \"45e428421666073eab6f2da5c9d310d99bb12f9b\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.2.2\"\n\n[[Requires]]\ndeps = [\"UUIDs\"]\ngit-tree-sha1 = \"4036a3bd08ac7e968e27c203d45f5fff15020621\"\nuuid = \"ae029012-a4dd-5104-9daa-d747884805df\"\nversion = \"1.1.3\"\n\n[[SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[Scratch]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"0b4b7f1393cff97c33891da2a0bf69c6ed241fda\"\nuuid = \"6c6a2e73-6563-6170-7368-637461726353\"\nversion = \"1.1.0\"\n\n[[Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[Showoff]]\ndeps = [\"Dates\", \"Grisu\"]\ngit-tree-sha1 = \"91eddf657aca81df9ae6ceb20b959ae5653ad1de\"\nuuid = \"992d4aef-0814-514b-bc4d-f2e9a6c4116f\"\nversion = \"1.0.3\"\n\n[[Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[SortingAlgorithms]]\ndeps = [\"DataStructures\"]\ngit-tree-sha1 = \"b3363d7460f7d098ca0912c69b082f75625d7508\"\nuuid = \"a2af1166-a08f-5f64-846c-94a0d3cef48c\"\nversion = \"1.0.1\"\n\n[[SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[SpecialFunctions]]\ndeps = [\"ChainRulesCore\", \"IrrationalConstants\", \"LogExpFunctions\", \"OpenLibm_jll\", \"OpenSpecFun_jll\"]\ngit-tree-sha1 = \"793793f1df98e3d7d554b65a107e9c9a6399a6ed\"\nuuid = \"276daf66-3868-5448-9aa4-cd146d93841b\"\nversion = \"1.7.0\"\n\n[[StaticArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"3240808c6d463ac46f1c1cd7638375cd22abbccb\"\nuuid = \"90137ffa-7385-5640-81b9-e52037218182\"\nversion = \"1.2.12\"\n\n[[Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[StatsAPI]]\ngit-tree-sha1 = \"1958272568dc176a1d881acb797beb909c785510\"\nuuid = \"82ae8749-77ed-4fe6-ae5f-f523153014b0\"\nversion = \"1.0.0\"\n\n[[StatsBase]]\ndeps = [\"DataAPI\", \"DataStructures\", \"LinearAlgebra\", \"Missings\", \"Printf\", \"Random\", \"SortingAlgorithms\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"8cbbc098554648c84f79a463c9ff0fd277144b6c\"\nuuid = \"2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91\"\nversion = \"0.33.10\"\n\n[[StructArrays]]\ndeps = [\"Adapt\", \"DataAPI\", \"StaticArrays\", \"Tables\"]\ngit-tree-sha1 = \"2ce41e0d042c60ecd131e9fb7154a3bfadbf50d3\"\nuuid = \"09ab397b-f2b6-538f-b94a-2f83cf4a842a\"\nversion = \"0.6.3\"\n\n[[SymPy]]\ndeps = [\"CommonEq\", \"CommonSolve\", \"LinearAlgebra\", \"Markdown\", \"PyCall\", \"RecipesBase\", \"SpecialFunctions\"]\ngit-tree-sha1 = \"1ef257ecbcab8058595a68ca36a6844b41babcbd\"\nuuid = \"24249f21-da20-56a4-8eb1-6a02cf4ae2e6\"\nversion = \"1.0.52\"\n\n[[TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[TableTraits]]\ndeps = [\"IteratorInterfaceExtensions\"]\ngit-tree-sha1 = \"c06b2f539df1c6efa794486abfb6ed2022561a39\"\nuuid = \"3783bdb8-4a98-5b6b-af9a-565f29a5fe9c\"\nversion = \"1.0.1\"\n\n[[Tables]]\ndeps = [\"DataAPI\", \"DataValueInterfaces\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"TableTraits\", \"Test\"]\ngit-tree-sha1 = \"1162ce4a6c4b7e31e0e6b14486a6986951c73be9\"\nuuid = \"bd369af6-aec1-5ad0-b16a-f7cc5008161c\"\nversion = \"1.5.2\"\n\n[[Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[URIParser]]\ndeps = [\"Unicode\"]\ngit-tree-sha1 = \"53a9f49546b8d2dd2e688d216421d050c9a31d0d\"\nuuid = \"30578b45-9adc-5946-b283-645ec420af67\"\nversion = \"0.4.1\"\n\n[[URIs]]\ngit-tree-sha1 = \"97bbe755a53fe859669cd907f2d96aee8d2c1355\"\nuuid = \"5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4\"\nversion = \"1.3.0\"\n\n[[UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[UnPack]]\ngit-tree-sha1 = \"387c1f73762231e86e0c9c5443ce3b4a0a9a0c2b\"\nuuid = \"3a884ed6-31ef-47d7-9d2a-63182c4928ed\"\nversion = \"1.0.2\"\n\n[[Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[VersionParsing]]\ngit-tree-sha1 = \"80229be1f670524750d905f8fc8148e5a8c4537f\"\nuuid = \"81def892-9a0e-5fdd-b105-ffc91e053289\"\nversion = \"1.2.0\"\n\n[[Wayland_jll]]\ndeps = [\"Artifacts\", \"Expat_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"3e61f0b86f90dacb0bc0e73a0c5a83f6a8636e23\"\nuuid = \"a2964d1f-97da-50d4-b82a-358c7fce9d89\"\nversion = \"1.19.0+0\"\n\n[[Wayland_protocols_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\"]\ngit-tree-sha1 = \"2839f1c1296940218e35df0bbb220f2a79686670\"\nuuid = \"2381bf8a-dfd0-557d-9999-79630e7b1b91\"\nversion = \"1.18.0+4\"\n\n[[WebIO]]\ndeps = [\"AssetRegistry\", \"Base64\", \"Distributed\", \"FunctionalCollections\", \"JSON\", \"Logging\", \"Observables\", \"Pkg\", \"Random\", \"Requires\", \"Sockets\", \"UUIDs\", \"WebSockets\", \"Widgets\"]\ngit-tree-sha1 = \"5fe32e4086d49f7ab9b087296742859f3ae6d62a\"\nuuid = \"0f1e0344-ec1d-5b48-a673-e5cf874b6c29\"\nversion = \"0.8.16\"\n\n[[WebSockets]]\ndeps = [\"Base64\", \"Dates\", \"HTTP\", \"Logging\", \"Sockets\"]\ngit-tree-sha1 = \"f91a602e25fe6b89afc93cf02a4ae18ee9384ce3\"\nuuid = \"104b5d7c-a370-577a-8038-80a2059c5097\"\nversion = \"1.5.9\"\n\n[[Widgets]]\ndeps = [\"Colors\", \"Dates\", \"Observables\", \"OrderedCollections\"]\ngit-tree-sha1 = \"80661f59d28714632132c73779f8becc19a113f2\"\nuuid = \"cc8bc4a8-27d6-5769-a93b-9d913e69aa62\"\nversion = \"0.6.4\"\n\n[[XML2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"1acf5bdf07aa0907e0a37d3718bb88d4b687b74a\"\nuuid = \"02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a\"\nversion = \"2.9.12+0\"\n\n[[XSLT_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgcrypt_jll\", \"Libgpg_error_jll\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\", \"Zlib_jll\"]\ngit-tree-sha1 = \"91844873c4085240b95e795f692c4cec4d805f8a\"\nuuid = \"aed1982a-8fda-507f-9586-7b0439959a61\"\nversion = \"1.1.34+0\"\n\n[[Xorg_libX11_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\", \"Xorg_xtrans_jll\"]\ngit-tree-sha1 = \"5be649d550f3f4b95308bf0183b82e2582876527\"\nuuid = \"4f6342f7-b3d2-589e-9d20-edeb45f2b2bc\"\nversion = \"1.6.9+4\"\n\n[[Xorg_libXau_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4e490d5c960c314f33885790ed410ff3a94ce67e\"\nuuid = \"0c0b7dd1-d40b-584c-a123-a41640f87eec\"\nversion = \"1.0.9+4\"\n\n[[Xorg_libXcursor_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXfixes_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"12e0eb3bc634fa2080c1c37fccf56f7c22989afd\"\nuuid = \"935fb764-8cf2-53bf-bb30-45bb1f8bf724\"\nversion = \"1.2.0+4\"\n\n[[Xorg_libXdmcp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fe47bd2247248125c428978740e18a681372dd4\"\nuuid = \"a3789734-cfe1-5b06-b2d0-1dd0d9d62d05\"\nversion = \"1.1.3+4\"\n\n[[Xorg_libXext_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"b7c0aa8c376b31e4852b360222848637f481f8c3\"\nuuid = \"1082639a-0dae-5f34-9b06-72781eeb8cb3\"\nversion = \"1.3.4+4\"\n\n[[Xorg_libXfixes_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"0e0dc7431e7a0587559f9294aeec269471c991a4\"\nuuid = \"d091e8ba-531a-589c-9de9-94069b037ed8\"\nversion = \"5.0.3+4\"\n\n[[Xorg_libXi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXfixes_jll\"]\ngit-tree-sha1 = \"89b52bc2160aadc84d707093930ef0bffa641246\"\nuuid = \"a51aa0fd-4e3c-5386-b890-e753decda492\"\nversion = \"1.7.10+4\"\n\n[[Xorg_libXinerama_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"26be8b1c342929259317d8b9f7b53bf2bb73b123\"\nuuid = \"d1454406-59df-5ea1-beac-c340f2130bc3\"\nversion = \"1.1.4+4\"\n\n[[Xorg_libXrandr_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"34cea83cb726fb58f325887bf0612c6b3fb17631\"\nuuid = \"ec84b674-ba8e-5d96-8ba1-2a689ba10484\"\nversion = \"1.5.2+4\"\n\n[[Xorg_libXrender_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"19560f30fd49f4d4efbe7002a1037f8c43d43b96\"\nuuid = \"ea2f1a96-1ddc-540d-b46f-429655e07cfa\"\nversion = \"0.9.10+4\"\n\n[[Xorg_libpthread_stubs_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"6783737e45d3c59a4a4c4091f5f88cdcf0908cbb\"\nuuid = \"14d82f49-176c-5ed1-bb49-ad3f5cbd8c74\"\nversion = \"0.1.0+3\"\n\n[[Xorg_libxcb_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"XSLT_jll\", \"Xorg_libXau_jll\", \"Xorg_libXdmcp_jll\", \"Xorg_libpthread_stubs_jll\"]\ngit-tree-sha1 = \"daf17f441228e7a3833846cd048892861cff16d6\"\nuuid = \"c7cfdc94-dc32-55de-ac96-5a1b8d977c5b\"\nversion = \"1.13.0+3\"\n\n[[Xorg_libxkbfile_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"926af861744212db0eb001d9e40b5d16292080b2\"\nuuid = \"cc61e674-0454-545c-8b26-ed2c68acab7a\"\nversion = \"1.1.0+4\"\n\n[[Xorg_xcb_util_image_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"0fab0a40349ba1cba2c1da699243396ff8e94b97\"\nuuid = \"12413925-8142-5f55-bb0e-6d7ca50bb09b\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\"]\ngit-tree-sha1 = \"e7fd7b2881fa2eaa72717420894d3938177862d1\"\nuuid = \"2def613f-5ad1-5310-b15b-b15d46f528f5\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_keysyms_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"d1151e2c45a544f32441a567d1690e701ec89b00\"\nuuid = \"975044d2-76e6-5fbe-bf08-97ce7c6574c7\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_renderutil_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"dfd7a8f38d4613b6a575253b3174dd991ca6183e\"\nuuid = \"0d47668e-0667-5a69-a72c-f761630bfb7e\"\nversion = \"0.3.9+1\"\n\n[[Xorg_xcb_util_wm_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"e78d10aab01a4a154142c5006ed44fd9e8e31b67\"\nuuid = \"c22f9ab0-d5fe-5066-847c-f4bb1cd4e361\"\nversion = \"0.4.1+1\"\n\n[[Xorg_xkbcomp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxkbfile_jll\"]\ngit-tree-sha1 = \"4bcbf660f6c2e714f87e960a171b119d06ee163b\"\nuuid = \"35661453-b289-5fab-8a00-3d9160c6a3a4\"\nversion = \"1.4.2+4\"\n\n[[Xorg_xkeyboard_config_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xkbcomp_jll\"]\ngit-tree-sha1 = \"5c8424f8a67c3f2209646d4425f3d415fee5931d\"\nuuid = \"33bec58e-1273-512f-9401-5d533626f822\"\nversion = \"2.27.0+4\"\n\n[[Xorg_xtrans_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"79c31e7844f6ecf779705fbc12146eb190b7d845\"\nuuid = \"c5fb5394-a638-5e4d-96e5-b29de1b5cf10\"\nversion = \"1.4.0+3\"\n\n[[Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[Zstd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"cc4bf3fdde8b7e3e9fa0351bdeedba1cf3b7f6e6\"\nuuid = \"3161d3a3-bdf6-5164-811a-617609db77b4\"\nversion = \"1.5.0+0\"\n\n[[libass_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"HarfBuzz_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"5982a94fcba20f02f42ace44b9894ee2b140fe47\"\nuuid = \"0ac62f75-1d6f-5e53-bd7c-93b484bb37c0\"\nversion = \"0.15.1+0\"\n\n[[libfdk_aac_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"daacc84a041563f965be61859a36e17c4e4fcd55\"\nuuid = \"f638f0a6-7fb0-5443-88ba-1cc74229b280\"\nversion = \"2.0.2+0\"\n\n[[libpng_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"94d180a6d2b5e55e447e2d27a29ed04fe79eb30c\"\nuuid = \"b53b4c65-9356-5827-b1ea-8c7a1a84506f\"\nversion = \"1.6.38+0\"\n\n[[libvorbis_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Ogg_jll\", \"Pkg\"]\ngit-tree-sha1 = \"c45f4e40e7aafe9d086379e5578947ec8b95a8fb\"\nuuid = \"f27f6e37-5d2b-51aa-960f-b287f2bc3b7a\"\nversion = \"1.3.7+0\"\n\n[[nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\n[[x264_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fea590b89e6ec504593146bf8b988b2c00922b2\"\nuuid = \"1270edf5-f2f9-52d2-97e9-ab00b5d0237a\"\nversion = \"2021.5.5+0\"\n\n[[x265_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"ee567a171cce03570d77ad3a43e90218e38937a9\"\nuuid = \"dfaa095f-4041-5dcd-9319-2fabd8486b76\"\nversion = \"3.5.0+0\"\n\n[[xkbcommon_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\", \"Wayland_protocols_jll\", \"Xorg_libxcb_jll\", \"Xorg_xkeyboard_config_jll\"]\ngit-tree-sha1 = \"ece2350174195bb31de1a63bea3a41ae1aa593b6\"\nuuid = \"d8fb68d0-12a3-5cfd-a85a-d49703b185fd\"\nversion = \"0.9.1+5\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╠═e8595a60-222f-11ec-0595-c9717ac06507\n# ╟─431922d9-e97a-4300-a482-2d458b66c67a\n# ╟─85cf0b95-4446-4e84-a6c3-f9d3fcf4cd61\n# ╟─53b8d020-b4a9-4c74-b0cc-dba03b6edbd3\n# ╟─4257606e-3eff-4124-aad3-517998f97d24\n# ╠═61b1bf99-507b-4379-b537-86ce040f1418\n# ╟─d17a8914-6ecf-4606-a664-7242d0f8f06c\n# ╠═2056778d-12f0-4325-920f-f6c7e453918b\n# ╟─4f6feaf8-5322-4afc-b31d-211761e222c2\n# ╟─f676a35a-c61e-4547-b176-211dd3dc647b\n# ╟─d8e3eda0-cada-4047-81cc-137a54e1b5e6\n# ╟─897cfd67-1be7-40e4-87d9-c11bc9de55d4\n# ╟─67e7f9f5-6e78-4579-97f7-7c0349b39afd\n# ╟─4d6550b8-4e9d-4437-84bd-d978e33bfdb8\n# ╠═997c5ff7-ac5d-484f-bcdf-a89194d112ee\n# ╟─19f1f8b8-0f5c-4388-b550-f4cdd7619311\n# ╠═8e1588d8-1d7a-4151-b8a1-afc3c1298887\n# ╟─09baa7ce-fc86-42a5-8130-3c8125c93f5b\n# ╠═653aa355-0c9d-4520-befd-d3f91678ffaa\n# ╟─1938fc99-5366-4bc0-a2b3-892d7281db93\n# ╠═0f723758-c34e-4a3b-ad72-853cc23b29fc\n# ╠═253ae086-b3b0-4243-b05d-4e575166aa53\n# ╟─9003d85b-eaf0-44f9-b2b7-1dd990e4fd76\n# ╟─c18c2f4b-1e5f-463f-8464-0a6387896efc\n# ╠═0f3486cc-8de9-452c-a0a1-b8c5277c1592\n# ╠═f4ee2c3e-7a1b-4d4a-99cf-0dda3ae572d7\n# ╠═cf0c4904-6b99-4af7-8aee-d03593bc2091\n# ╠═e86f3da1-ab64-4582-9fc7-8f12966c318f\n# ╟─84f78af9-2866-404e-a121-3e3c6afe617b\n# ╠═9bf041fa-c284-4425-831c-2d8a207e54e2\n# ╠═512fadab-9352-4d45-b73e-d754b30114e4\n# ╟─6612a222-06c1-47a8-b024-146ca8caea08\n# ╠═604e2572-57d6-4076-b4bc-35adcceb7994\n# ╟─ef868e86-0a6a-47fb-b2a5-d9190cd03c0a\n# ╟─74bf0f00-bc45-4d26-9c61-f164de3d21e0\n# ╟─50432a00-fdbe-448e-a6c1-89b1d01d435d\n# ╟─4bf801a5-b443-46d1-a110-ab8096527116\n# ╠═2136e05b-bef2-4dc8-8723-3fbb8360cba0\n# ╟─5532b807-94e2-4ff2-9b65-41d1423863c6\n# ╠═904d25d1-2244-4f76-ac1c-b1fef76ff41a\n# ╟─2ba19d1c-f22e-47c8-b81c-979e0edd7348\n# ╠═9eeb302c-a277-437d-9e95-345b72d1a3a4\n# ╟─15949e72-93cf-4aa6-8524-5b55fe9eb229\n# ╟─6935e6f6-e926-4766-89a4-8d86408cc15d\n# ╟─aed97c10-bcae-4552-b522-afb0a6073c7a\n# ╟─760596e6-3937-4024-b3b4-7bfae97c4a4f\n# ╟─64d47104-23e7-492c-aa5e-c6eee7f6d10d\n# ╟─ff31fe54-2f96-4e12-bf62-395dd29fa515\n# ╟─6867d0da-516e-4924-b3f3-be7bbe75d4fc\n# ╟─9ca33e7d-aa40-4970-9072-bcf0f754ec04\n# ╟─fe385398-3bd1-4662-8411-e2c9beda9a9f\n# ╟─672d62df-7c33-4260-8c4f-a72e8a900bd3\n# ╟─c389944d-1d91-44aa-a28d-d0848bb10228\n# ╟─e7d5a0e0-0b6b-4012-88cd-7e50283fb721\n# ╟─fc2349c9-fb1f-4ce3-94fc-adb98f3170b8\n# ╠═30e16586-b504-4332-9f6c-cdeb3f9c686c\n# ╟─2f8356bc-311a-4826-861e-4852ed01bca1\n# ╟─45d7938f-a9ff-4a21-b0f8-74a7b69e1a3d\n# ╠═af547106-640f-4d89-b96d-b1d625822697\n# ╠═a2779834-7808-4bad-a97a-bc90dba2adc7\n# ╟─d9ef00bd-1ac5-4406-9cb7-ae9d90d2387e\n# ╠═76c7aed0-4bac-4a03-8a07-00583c571c52\n# ╠═180d6fe0-baeb-4c05-bfc9-213a6f1ec07c\n# ╟─a7da009c-b867-46d2-84a2-087287521aa8\n# ╟─5522536b-a0df-41f8-8525-856923f49104\n# ╠═337404a1-514b-4f40-9aa7-738d0c07d34f\n# ╟─7dcb7519-f6cc-47b6-bbf2-1896a0053a85\n# ╟─dd6b45de-fa40-4697-a372-d7f6a75bc704\n# ╟─e052a4ad-90a0-4f7f-a1e7-a35b92270d74\n# ╟─65dcc377-8278-4c08-867b-012065989b1f\n# ╟─c2c157cb-29fa-488b-a5dd-caef9e392c6b\n# ╟─1dd55ddd-2c09-4d8c-83d3-442ebcf0d579\n# ╠═0bd81932-75a6-4b74-a264-bb16ae798a44\n# ╠═c3ca6592-a758-40fc-96c5-e8609071697f\n# ╠═279a2774-a565-4ffa-9577-b2e987abed37\n# ╟─1dd28947-9fa2-42bc-9666-6e1b5e12a147\n# ╠═2b0dc6fe-ae32-48c9-a400-ad5fb8fbef4e\n# ╠═40420c6d-122b-454d-9954-8ec29765f3f2\n# ╠═be180c4f-177b-41a7-83d3-5a0220c9ad0e\n# ╠═067ffcf8-a398-4e50-bcf7-5425906f4a87\n# ╠═a1ce3aac-6e19-4de0-bcd5-4e86b26aab71\n# ╟─3cf6ffc2-0f08-41f7-adaa-9fa22f585881\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "d175ccfb17bad49eb87321919ebc6694f485725a", "size": 49455, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "cuadernos/primer_parcial.jl", "max_stars_repo_name": "akielbowicz/cbc-algebra-ingenieria", "max_stars_repo_head_hexsha": "efd86641733cbdf120338d53dcb4508ac364e87c", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cuadernos/primer_parcial.jl", "max_issues_repo_name": "akielbowicz/cbc-algebra-ingenieria", "max_issues_repo_head_hexsha": "efd86641733cbdf120338d53dcb4508ac364e87c", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-10-08T07:26:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-08T07:26:23.000Z", "max_forks_repo_path": "cuadernos/primer_parcial.jl", "max_forks_repo_name": "akielbowicz/cbc-algebra-ingenieria", "max_forks_repo_head_hexsha": "efd86641733cbdf120338d53dcb4508ac364e87c", "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": 31.9683257919, "max_line_length": 352, "alphanum_fraction": 0.723364675, "num_tokens": 23732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765140114859, "lm_q2_score": 0.8962513655129178, "lm_q1q2_score": 0.8188838233198769}} {"text": "# Seasonality and unobserved components\n# models: an overview\n# Andrew Harvey\n# December 4, 2006\n\n# Are Seasonal Patterns Constant Over Time?\n# A Test for Seasonal Stability \n# Fabio CANOVA\n# Bruce E. HANSEN\n# Journal of Business & Economic Statistics, July 1995, Vol. 13, No. 3\n\nλ(j::Int, s::Int) = (2*pi*j)/s\n\nconst CRIT_VALS_05 = [0.470, 0.749, 1.01, 1.24, 1.47, 1.68, 1.9, 2.11, 2.32, 2.54, 2.75, 2.96]\n\nfunction crit_val_05_generalized_von_mises_distribution(s::Int)\n return s > 12 ? 0.269 * s^0.928 : CRIT_VALS_05[s]\nend\n\nfunction π_statistic(ε::Vector{Fl}, σ::Fl, T::Int) where Fl\n return (T^(-2)*σ^(-2))*\n sum(\n sum(ε[i]*(-1)^(i) for i = 1:t) for t = 1:T\n )\nend\n\nfunction std_statistic(ε::Vector{Fl}, σ::Fl, T::Int, s::Int, j::Int) where Fl\n return (2*T^(-2)*σ^(-2))*\n sum(\n sum(ε[i]*cos(λ(j, s)*i) for i = 1:t)^2 \n +\n sum(ε[i]*sin(λ(j, s)*i) for i = 1:t)^2 for t = 1:T\n )\nend\n\nfunction test_statistic(ε::Vector{Fl}, σ::Fl, T::Int, s::Int) where Fl\n # joint statistical test for all frequencies in \n # trigonometric pattern\n ω = 0\n # for each frequency in the trigonometric pattern\n for j = 1:floor(Int, s/2)\n ω += j == s/2 ? π_statistic(ε, σ, T) : std_statistic(ε, σ, T, s, j)\n end\n return ω\nend\n\nfunction build_std(T::Int, s::Int, j::Int)\n # add cossine and sine with frequency (2*pi*j)/s\n # to exogenous matrix X\n return hcat(cos.(λ(j, s)*(1:T)), sin.(λ(j, s)*(1:T)))\nend\n\nfunction build_π(T::Int, s::Int, j::Int)\n # when j = s/2\n # add cossine with frequency pi and intercept\n # to exogenous matrix X\n return hcat(cos.(λ(j, s)*(1:T)), ones(T))\nend\n\nfunction build_X(s::Int, T::Int, Fl::Type)\n # create the exogenous matrix \n X = Array{Fl, 2}(undef, T, s)\n # for each frequency in the trigonometric pattern\n for j = 1:floor(Int, s/2)\n X[:,[2*j-1, 2*j]] = j == s/2 ? build_π(T, s, j) : build_std(T, s, j)\n end\n return X\nend\n\nfunction seasonal_regression(y::Vector{Fl}, s::Int, T::Int) where Fl\n X = build_X(s, T, Fl)\n return y - X * (X \\ y)\nend\n\nfunction seasonal_stationarity_test(y::Vector{Fl}, s::Int) where Fl\n T = length(y)\n ε = seasonal_regression(y, s, T)\n σ = std(ε)\n ω = test_statistic(ε, σ, T, s)\n crit_val = crit_val_05_generalized_von_mises_distribution(s)\n res = ω - crit_val\n res > 0 ? println(\"Rejected seasonal stationarity at 5% significance level\"*\n \" Test Statistic: $ω - Critical Value: $crit_val\") :\n println(\"Didn't reject seasonal stationarity at 5% significance level\"*\n \" Test Statistic: $ω - Critical Value: $crit_val\")\n return res > 0 ? false : true\nend\n\n", "meta": {"hexsha": "0de9d0bd8dcee964ecc97c12bddeebe1dc179aac", "size": 2748, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/statistical_tests/canova_hansen.jl", "max_stars_repo_name": "gionikola/StateSpaceModels.jl", "max_stars_repo_head_hexsha": "477426b6b1a40809b793bdc46574bfa3909e6182", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 189, "max_stars_repo_stars_event_min_datetime": "2018-03-08T18:13:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:55:22.000Z", "max_issues_repo_path": "src/statistical_tests/canova_hensen.jl", "max_issues_repo_name": "PaulMainwood/StateSpaceModels.jl", "max_issues_repo_head_hexsha": "b1723e74f3c6243020a9909d49639a3ca8325985", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 270, "max_issues_repo_issues_event_min_datetime": "2018-04-02T15:48:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:35:16.000Z", "max_forks_repo_path": "src/statistical_tests/canova_hensen.jl", "max_forks_repo_name": "PaulMainwood/StateSpaceModels.jl", "max_forks_repo_head_hexsha": "b1723e74f3c6243020a9909d49639a3ca8325985", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21, "max_forks_repo_forks_event_min_datetime": "2019-07-24T14:56:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T17:13:07.000Z", "avg_line_length": 30.8764044944, "max_line_length": 94, "alphanum_fraction": 0.5931586608, "num_tokens": 967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067244294587, "lm_q2_score": 0.8688267660487573, "lm_q1q2_score": 0.8188750693652539}} {"text": "using LinearAlgebra\n\nfunction decomp_qr(A)\n\n (m,n) = size(A);\n R = zeros(n,n);\n Q = zeros(m,n);\n \n\n for j = 1:n\n\n soma = zeros(m,1);\n \n for i = 1 : j-1\n R[i,j] = Q[:,i]' * A[:,j];\n soma = soma + R[i,j]*Q[:,i];\n end\n\n v = A[:,j] - soma;\n R[j,j] = norm(v);\n Q[:,j] = v/R[j,j];\n\n end\n\n return (Q,R);\n\nend", "meta": {"hexsha": "56d8b334090d7789b474babfa79ccd3e120c4d8a", "size": 393, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/decomp_qr.jl", "max_stars_repo_name": "italonicacio/Algebra_Linear_Computacional_2019.1", "max_stars_repo_head_hexsha": "b7f1540fb16cdbf6db15d88da8c38ba83db866b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-30T02:51:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-30T02:51:30.000Z", "max_issues_repo_path": "julia/decomp_qr.jl", "max_issues_repo_name": "italonicacio/Algebra_Linear_Computacional_2019.1", "max_issues_repo_head_hexsha": "b7f1540fb16cdbf6db15d88da8c38ba83db866b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/decomp_qr.jl", "max_forks_repo_name": "italonicacio/Algebra_Linear_Computacional_2019.1", "max_forks_repo_head_hexsha": "b7f1540fb16cdbf6db15d88da8c38ba83db866b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.5555555556, "max_line_length": 40, "alphanum_fraction": 0.358778626, "num_tokens": 135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474181553805, "lm_q2_score": 0.8577681122619883, "lm_q1q2_score": 0.8188661137469218}} {"text": "using Random, Distributions, Plots; pyplot()\nRandom.seed!(0)\n\nlambda = 1/4.5\nexpDist = Exponential(1/lambda)\nn, N = 10, 10^6\n\nmeans = Array{Float64}(undef, N)\nvariances = Array{Float64}(undef, N)\n\nfor i in 1:N\n data = rand(expDist,n)\n means[i] = mean(data)\n variances[i] = var(data)\nend\n\nprintln(\"Actual mean: \",mean(expDist),\n\t\t\"\\nMean of sample means: \",mean(means))\nprintln(\"Actual variance: \",var(expDist),\n\t\"\\nMean of sample variances: \",mean(variances))\n\nstephist(means, bins=200, c=:blue, normed=true, \n\tlabel=\"Histogram of Sample Means\")\nstephist!(variances, bins=600, c=:red, normed=true, \n\tlabel=\"Histogram of Sample Variances\", xlims=(0,40), ylims=(0,0.4),\n \txlabel = \"Statistic value\", ylabel = \"Density\")", "meta": {"hexsha": "55ade19d7f785740230611b9d46f2d84aac3be76", "size": 737, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "5_chapter/statisticsOfARandomSample.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/statisticsOfARandomSample.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/statisticsOfARandomSample.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 28.3461538462, "max_line_length": 68, "alphanum_fraction": 0.6729986431, "num_tokens": 236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474207360066, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.8188661038118499}} {"text": "# Algorithm 2.8\n# Approximate the root of a function by constructing a parabola\n# between three points and intersect it with y = 0 to find the\n# next approximation.\n\nfunction muller(f, x0, x1, x2, tol, n0)\n\th1 = x1 - x0\n\th2 = x2 - x1\n\tδ1 = (f(x1) - f(x0))/h1\n\tδ2 = (f(x2) - f(x1))/h2\n\td = (δ2 - δ1)/(h2 + h1)\n\tfor i ∈ 3:n0\n\t\tb = δ2 + h2 * d\n\t\tD = (b^2 -4f(x2)d)^(1/2)\n\t\tE = 0\n\t\tif abs(b - D) < abs(b + D)\n\t\t\tE = b + D\n\t\telse\n\t\t\tE = b - D\n\t\tend\n\t\th = (-2f(x2))/E\n\t\tp = x2 + h\n\t\tif abs(h) < tol\n\t\t\treturn p\n\t\tend\n\t\tx0 = x1\n\t\tx1 = x2\n\t\tx2 = p\n\t\th1 = x1 - x0\n\t\th2 = x2 - x1\n\t\tδ1 = (f(x1) - f(x0))/h1\n\t\tδ2 = (f(x2) - f(x1))/h2\n\t\td = (δ2 - δ1)/(h2 + h1)\n\tend\n\tthrow(ArgumentError(\"Method failed\"))\nend\n\nprintln(muller(x -> (16x^4 - 40x^3 + 5x^2 + 20x +6), 0.5, 1.0, 1.5, 10^-5, 50))\n", "meta": {"hexsha": "477ae73cd887b8df27fd05b5eba5fc8eb2542a12", "size": 777, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "chapter2/muller.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/muller.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/muller.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.9230769231, "max_line_length": 79, "alphanum_fraction": 0.5160875161, "num_tokens": 397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341962906709, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.8187364706062052}} {"text": "# p21.jl - eigenvalues of Mathieu operator -u_xx + 2qcos(2x)u\n# (compare p8.jl and p. 724 of Abramowitz & Stegun)\n\nN = 42; h = 2*pi/N; x = h*(1:N);\nD2 = toeplitz([-pi^2/(3*h^2)-1/6; @. -.5*(-1)^(1:N-1)/sin(h*(1:N-1)/2)^2]);\nqq = 0:.2:15; data = [];\nfor q = qq;\n e = sort(eigvals(-D2 + 2*q*diagm(cos.(2*x))));\n data = [data; e[1:11]'];\nend\nclf(); subplot(1,2,1);\nplot(qq,data[:,1:2:end],\"b-\");\nplot(qq,data[:,2:2:end],\"b--\");\nxlabel(\"q\"); ylabel(\"λ\");\naxis([0,15,-24,32]); yticks(-24:4:32);\n", "meta": {"hexsha": "0db8f4f48c3d71eab3a482c37f97acf3cfae66e3", "size": 504, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/scripts/p21.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/p21.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/p21.jl", "max_forks_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_forks_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5, "max_line_length": 75, "alphanum_fraction": 0.5218253968, "num_tokens": 227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305349799243, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.8187181939068199}} {"text": "using Distributions\n\n\nlRange = 1; uRange = 9; unidd = DiscreteUniform(lRange,uRange)\np = 0.8; bernd = Bernoulli(p)\nn = 20; p = 0.8; bind = Binomial(n,p)\nps = [0.2,0.5,0.2,0.1]; catd = Categorical(ps)\nn=20; ps = [0.2,0.5,0.3]; multind = Multinomial(n, ps)\np = 0.2; geomd = Geometric(p)\nsAv = 10; fAv = 20; nTrials = 3; hypgeomd = Hypergeometric(sAv, fAv, nTrials)\n# hypergeometrical multivariate form not available\nrate = 10; poissd = Poisson(rate)\nnSucc =10; p = 0.2; pascd = NegativeBinomial(nSucc,p) # Return the number of failures before n successes instead of total trials to n successes\n\nlRange = 1; uRange = 9; unicd = Uniform(lRange,uRange)\nrate = 2.5; expd = Exponential(rate)\nμ = 2; σsq = 5 ; normd = Normal(μ,sqrt(σsq)) # parametrised by sd!\nn = 5; rate = 2.5; erld = Erlang(n,rate)\nμ = 2.5; σ = 2.5; cuachyd = Cauchy(μ, σ)\ndf = 3; chisqd = Chisq(df)\ndf = 4.5; td = TDist(df)\ndf1 = 6 ; df2 = 7; fd = FDist(df1, df2)\nshapeα = 2.5; shapeβ=4.5; betad = Beta(shapeα,shapeβ)\nshapeα = 2.5; rateβ = 4.5; gammad = Gamma(shapeα,1/rateβ)\n\nuvds = [unidd, bernd, bind, catd, geomd, hypgeomd, poissd, pascd,\n unicd, expd, normd, erld, cuachyd, chisqd, td, fd, betad, gammad]\nmvds = [multind]\n\nx = 3\nfor d in uvds\n println(\"--------\")\n println(d)\n println(\"Mean: $(mean(d))\")\n println(\"Variance: $(var(d))\")\n d != chisqd && println(\"Median: $(median(d))\")\n println(\"Sample: $(rand(d))\")\n println(\"PDF: $(pdf(d,x))\")\n println(\"CDF: $(cdf(d,x))\")\n println(\"20% quantile: $(quantile(d,0.2))\")\nend\n\nxs = [3,12,5]\nfor d in mvds\n println(\"--------\")\n println(d)\n println(\"Mean: $(mean(d))\")\n println(\"Variance: $(var(d))\")\n #println(\"Median: $(median(d))\")\n println(\"Sample: $(rand(d))\")\n println(\"PDF: $(pdf(d,xs))\")\n #println(\"CDF: $(cdf(d,xs))\")\n #println(\"20% quantile: $(quantile(d,0.2))\")\nend\n", "meta": {"hexsha": "c873526f06116b41be94a8984e020fac1740ee69", "size": 2182, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples.jl", "max_stars_repo_name": "sylvaticus/commonDistributionsInJuliaPythonR", "max_stars_repo_head_hexsha": "041ec8404598e57e4237899a783a1df3960f679c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-13T18:21:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-13T18:21:44.000Z", "max_issues_repo_path": "examples.jl", "max_issues_repo_name": "sylvaticus/commonDistributionsInJuliaPythonR", "max_issues_repo_head_hexsha": "041ec8404598e57e4237899a783a1df3960f679c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples.jl", "max_forks_repo_name": "sylvaticus/commonDistributionsInJuliaPythonR", "max_forks_repo_head_hexsha": "041ec8404598e57e4237899a783a1df3960f679c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-08-28T19:42:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T01:39:11.000Z", "avg_line_length": 39.6727272727, "max_line_length": 159, "alphanum_fraction": 0.5132905591, "num_tokens": 771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960951703918909, "lm_q2_score": 0.8519528094861981, "lm_q1q2_score": 0.8186855039342638}} {"text": "#' ---\r\n#' title: Problems on Graphs\r\n#' ---\r\n\r\n#' **Originally Contributed by**: Arpit Bhatia\r\n\r\n#' In the mathematical discipline of graph theory, a number of problems can be solved by modelling them as optimization problems.\r\n#' We will see some examples of such problems in the tutorial. \r\n#' These problems are also sometimes referred to as combinatorial optimization problems as \r\n#' they consist of finding an optimal object from a finite set of objects.\r\n\r\n#' Let's first import all the packages we will be using for this tutorial.\r\n#' We'll be plotting all the graphs we work with in this tutorial for which we will need some additional packages.\r\n\r\nusing JuMP\r\nusing GLPK\r\nusing GraphPlot \r\nusing LightGraphs\r\nusing Colors\r\n\r\n#' ## Representing Graphs\r\n#' For the purpose of this tutorial, we will represent graphs using adjacency matrices. \r\n#' An adjacency matrix, sometimes also called the connection matrix, is a square matrix used to represent a finite graph. \r\n#' Its rows and columns are labeled by the graph vertices, \r\n#' with a 1 or 0 in position ($v_{i}$,$v_{j}$) according to whether $v_{i}$ and $v_{j}$ are adjacent or not. \r\n\r\n#' ## Minimum Vertex Cover\r\n#' Given a graph $G = (V, E)$, a vertex-cover $V' \\subset V$ of $G$ is a collection of vertices such that \r\n#' each edge in $E$ is incident to at least one of the vertices in $V'$. \r\n#' The size of a vertex-cover $|V'|$ is the number of vertices present in the cover. \r\n#' We wish to find the minimum vertex cover of $G$ i.e. a minimum size vertex cover.\r\n#' We model this problem as an ILP by defining a decision variable $y_{v}$ for each vertex $v \\in V$ and \r\n#' a constraint for each edge $e \\in E$ as follows:\r\n\r\n#' $$\r\n#' \\begin{align*}\r\n#' \\min && \\sum_{v \\in V} y_{v} \\\\\r\n#' s.t. && y_{u} + y_{v} \\geq 1 && \\forall \\{u,v\\} \\in E \\\\\r\n#' && y_{v} \\in \\{0,1\\} && \\forall v \\in V\r\n#' \\end{align*}\r\n#' $$\r\n\r\nG = [\r\n0 1 0 0 0 0;\r\n1 0 1 1 0 0;\r\n0 1 0 0 1 1;\r\n0 1 0 0 1 0;\r\n0 0 1 1 0 0;\r\n0 0 1 0 0 0\r\n]\r\n\r\ng = SimpleGraph(G)\r\n \r\ngplot(g)\r\n\r\n#+\r\n\r\nvertex_cover = Model(with_optimizer(GLPK.Optimizer))\r\n\r\n@variable(vertex_cover, y[1:nv(g)], Bin)\r\n@constraint(vertex_cover, [i = 1:nv(g), j = 1:nv(g); G[i,j] == 1], y[i] + y[j] >= 1)\r\n@objective(vertex_cover, Min, sum(y))\r\n\r\noptimize!(vertex_cover)\r\n@show value.(y);\r\n\r\n#+\r\n\r\nmembership = convert(Array{Int},value.(y)) # Change to Int \r\nmembership = membership + ones(Int, nv(g)) # Make the color groups one indexed\r\nnodecolor = [colorant\"red\", colorant\"blue\"] # Blue to represent vertices in the cover\r\nnodefillc = nodecolor[membership]\r\ngplot(g, nodefillc = nodefillc)\r\n\r\n#' ## Dominating Set\r\n#' A dominating set in a graph $G = (V, E)$ is a set $S \\subset V$ such that \r\n#' for each vertex $v \\in V$ either $v$ or one of its neighbour should be in $S$. \r\n#' Note that for some vertex $u$, $u$ and its neighbour both can be present in $S$.\r\n#' We wish to find the smallest dominating set for a graph.\r\n#' We model this problem as an ILP by defining a decision variable $x_{v}$ for each vertex $v \\in V$ along with\r\n#' a constraint for its neighbourhood.\r\n\r\n#' $$\r\n#' \\begin{align*}\r\n#' \\min && \\sum_{v \\in V} x_{v} \\\\\r\n#' s.t. && \\sum_{u \\in N(v)}x_{u} \\geq 1 && \\forall v \\in V \\\\\r\n#' && x_{v} \\in \\{0,1\\} && \\forall v \\in V\r\n#' \\end{align*}\r\n#' $$\r\n\r\nG = [\r\n0 1 0 0 0 0 0 0 0 1 0 ;\r\n1 0 1 0 0 0 0 0 0 0 1;\r\n0 1 0 1 0 1 0 0 0 0 0;\r\n0 0 1 0 1 0 0 0 0 0 0;\r\n0 0 0 1 0 1 0 0 0 0 0;\r\n0 0 1 0 1 0 1 0 0 0 0;\r\n0 0 0 0 0 1 0 1 0 0 0;\r\n0 0 0 0 0 0 1 0 1 0 1;\r\n0 0 0 0 0 0 0 1 0 1 1;\r\n1 0 0 0 0 0 0 0 1 0 1;\r\n0 1 0 0 0 0 0 1 1 1 0\r\n]\r\n\r\ng = SimpleGraph(G)\r\n \r\ngplot(g)\r\n\r\n#+\r\n\r\ndominating_set = Model(with_optimizer(GLPK.Optimizer))\r\n\r\n@variable(dominating_set, x[1:nv(g)], Bin)\r\n@constraint(dominating_set, [i = 1:nv(g)], sum(G[i,:] .* x) >= 1)\r\n@objective(dominating_set, Min, sum(x))\r\n\r\noptimize!(dominating_set)\r\n@show value.(x);\r\n\r\n#+\r\n\r\nmembership = convert(Array{Int},value.(x)) # Change to Int \r\nmembership = membership + ones(Int, nv(g)) # Make the color groups one indexed\r\nnodecolor = [colorant\"red\", colorant\"blue\"] # Blue to represent vertices in the set\r\nnodefillc = nodecolor[membership]\r\ngplot(g, nodefillc = nodefillc)\r\n\r\n\r\n#' ## Maximum Matching Problem\r\n#' Given a graph $G = (V, E)$, a matching $M \\subset E$ of $G$ is a collection of vertex disjoint edges. \r\n#' The size of the matching $M$ is the number of edges present in $M$ i.e. $|M|$. \r\n#' We wish to find the Maximum matching of $G$ i.e. a matching of maximum size.\r\n#' We can solve this problem by modelling it as an integer linear program (ILP). \r\n#' We define a decision variable $m_{e}$ for each edge $e \\in E$ and a constraint for each vertex $u \\in V$ as follows:\r\n\r\n#' $$\r\n#' \\begin{align*}\r\n#' \\max && \\sum_{e \\in E} m_{e} \\\\\r\n#' s.t. && \\sum_{e \\sim u} m_{e} \\leq 1 && \\forall u \\in V \\\\\r\n#' && m_{e} \\in \\{0,1\\} && \\forall e \\in E\r\n#' \\end{align*}\r\n#' $$\r\n\r\n#' Let's now use JuMP to solve this problem for a sample graph.\r\n\r\nG = [\r\n0 0 0 0 1 0 0 0;\r\n0 0 0 0 0 1 0 0;\r\n0 0 0 0 0 0 1 0;\r\n0 0 0 0 0 0 0 1;\r\n1 0 0 0 0 1 0 1;\r\n0 1 0 0 1 0 1 0;\r\n0 0 1 0 0 1 0 1;\r\n0 0 0 1 1 0 1 0;\r\n]\r\n\r\ng = SimpleGraph(G)\r\n \r\ngplot(g)\r\n\r\n#+\r\n\r\nmatching = Model(with_optimizer(GLPK.Optimizer))\r\n\r\n@variable(matching, m[i = 1:nv(g), j = 1:nv(g)], Bin)\r\n@constraint(matching, [i = 1:nv(g)], sum(m[i,:]) <= 1)\r\n@constraint(matching, [i = 1:nv(g), j = 1:nv(g); G[i,j] == 0], m[i,j] == 0)\r\n@constraint(matching, [i = 1:nv(g), j = 1:nv(g)], m[i,j] == m[j,i])\r\n@objective(matching, Max, sum(m))\r\n\r\noptimize!(matching)\r\n@show value.(m);\r\n\r\n#' The edges corresponding to the Matching are marked as one in the above matrix.\r\n\r\n#' ## k-Coloring Problem\r\n#' A k-coloring of a graph $G=(V,E)$ is a function $c: V \\rightarrow \\{1,2...k\\}$ such that \r\n#' $c(u) \\neq c(v)$ for every edge $(u,v) \\in E$. In other words, the numbers 1,2...k represent k colors, \r\n#' and adjacent vertices must have different colours.\r\n#' The goal of a graph coloring problem is to find a minimum number of colours needed to colour a graph.\r\n\r\n#' We model this problem as an ILP by defining a variable decision variable $z_{i}$ for each colour we have available.\r\n#' Given an upper bound $k$ on the number of colors needed, \r\n#' we use $|V| \\times k$ decision variables $c_{v,k}$ denoting if vertex $v$ is assigned color $k$.\r\n#' Our model will become:\r\n\r\n#' $$\r\n#' \\begin{align*}\r\n#' \\min && \\sum_{i=1}^{k} z_{i} \\\\\r\n#' s.t. && \\sum_{i=1}^{k} c_{v,i} = 1 && \\forall v \\in V \\\\\r\n#' && c_{u,i} + c_{v,i} \\leq 1 && \\forall (u,v) \\in V, i \\in \\{1,2...k\\} \\\\\r\n#' && c_{v,i} \\in \\{0,1\\} && \\forall v \\in V, i \\in \\{1,2...k\\} \\\\\r\n#' && z_{i} \\in \\{0,1\\} && \\forall i \\in \\{1,2...k\\}\r\n#' \\end{align*}\r\n#' $$\r\n\r\nG = [\r\n0 1 0 0 1 1 0 0 0 0;\r\n1 0 1 0 0 0 1 0 0 0;\r\n0 1 0 1 0 0 0 1 0 0;\r\n0 0 1 0 1 0 0 0 1 0;\r\n1 0 0 1 0 0 0 0 0 1;\r\n1 0 0 0 0 0 1 0 0 1;\r\n0 1 0 0 0 1 0 1 0 0;\r\n0 0 1 0 0 0 1 0 1 0;\r\n0 0 0 1 0 0 0 1 0 1;\r\n0 0 0 0 1 1 0 0 1 0;\r\n]\r\n\r\ng = SimpleGraph(G)\r\n \r\ngplot(g)\r\n\r\n#+\r\n\r\nk = nv(g)\r\n\r\nk_colouring = Model(with_optimizer(GLPK.Optimizer))\r\n\r\n@variable(k_colouring, z[1:k], Bin)\r\n@variable(k_colouring, c[1:nv(g),1:k], Bin)\r\n@constraint(k_colouring, [i = 1:nv(g)], sum(c[i,:]) == 1)\r\n@constraint(k_colouring, [i = 1:nv(g), j = 1:nv(g), l = 1:k; G[i,j] == 1], c[i,l] + c[j,l] <= 1)\r\n@constraint(k_colouring, [i = 1:nv(g), l = 1:k], c[i,l] <= z[l])\r\n\r\n@objective(k_colouring, Min, sum(z))\r\n\r\noptimize!(k_colouring)\r\n@show value.(z);\r\n@show value.(c);\r\n\r\n#+\r\n\r\nc = value.(c)\r\nmembership = zeros(nv(g))\r\nfor i in 1:nv(g)\r\n for j in 1:k\r\n if c[i,j] == 1\r\n membership[i] = j\r\n break\r\n end\r\n end\r\nend\r\nmembership = convert(Array{Int},membership)\r\n\r\nnodecolor = distinguishable_colors(nv(g), colorant\"green\")\r\nnodefillc = nodecolor[membership]\r\ngplot(g, nodefillc = nodefillc)", "meta": {"hexsha": "ada55076e06f272c4120169fba787822871ff68d", "size": 7786, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/modelling/problems_on_graphs.jl", "max_stars_repo_name": "carlosal1015/JuMPTutorials.jl", "max_stars_repo_head_hexsha": "4d9a86ea310ecc7a22de7f14b783dbd218e4b612", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "script/modelling/problems_on_graphs.jl", "max_issues_repo_name": "carlosal1015/JuMPTutorials.jl", "max_issues_repo_head_hexsha": "4d9a86ea310ecc7a22de7f14b783dbd218e4b612", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/modelling/problems_on_graphs.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": 31.3951612903, "max_line_length": 130, "alphanum_fraction": 0.6046750578, "num_tokens": 2844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9773708019443873, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.8186652913259163}} {"text": "export Cubic, Spline, npatches, funk\n\n# see http://mathworld.wolfram.com/CubicSpline.html\n\nimport Base: getindex, show\n\n\"\"\"\n`Cubic(a,b,c,d)` is a 3rd degree polynomial `a+bx+cx^2+dx^3`.\nUse `f(x)` to evalue `f` at the value `x`.\n\"\"\"\nstruct Cubic\n a::Number\n b::Number\n c::Number\n d::Number\nend\n\n(f::Cubic)(x::Number) = f.a + x * (f.b + x * (f.c + x * f.d))\n\n\"\"\"\n`f'` where `f` is a `Cubic` or `Spline` is the derivative\nof `f`.\n\"\"\"\nBase.adjoint(f::Cubic) = Cubic(f.b, 2f.c, 3f.d, 0)\n\nstruct Spline\n patches::Array{Cubic,1}\n closed::Bool\nend\n\nis_closed(S::Spline) = S.closed\n\n\nfunction Base.adjoint(S::Spline)\n plist = adjoint.(S.patches)\n return Spline(plist, S.closed)\nend\n\n\"\"\"\n`Spline(vals,kind)` returns a cubic spline based on the values in `vals`.\nThe resulting spline `S` will have the property that `S(1)==y[1]`,\n`S(2)==y[2]`, and so on up to `S(n)==y[n]` where `n` is the length of `y`.\n\n+ If `kind` is `:open` then the second derivatives at the end points will be zero. (This is the default.)\n+ If `kind` is `:closed` then we assume that we are interpolating a periodic function where `S(n+1)==S(1)`.\n\"\"\"\nfunction Spline(y::Array{T,1}, kind::Symbol = :open)::Spline where {T<:Number}\n n = length(y)\n if kind == :open\n @assert n > 2 \"Open splines must have at least three points\"\n return open_spline(y)\n end\n if kind == :closed\n @assert n > 3 \"Closed splines must have at least four points\"\n return closed_spline(y)\n end\n\n error(\"Spline type must be :open or :closed, not $kind\")\nend\n\nfunction npatches(S::Spline)\n return length(S.patches)\nend\n\nfunction show(io::IO, S::Spline)\n adjective = is_closed(S) ? \"Closed\" : \"Open\"\n print(io, \"$adjective spline with $(npatches(S)) patches\")\nend\n\n\ngetindex(S::Spline, idx::Int) = S.patches[idx]\n\n\"\"\"\n`funk(S)` converts the Spline `S` into a callable function\n(e.g., that can be passed to `plot`).\n\"\"\"\nfunction funk(S)::Function\n return x -> S(x)\nend\n\nfunction (S::Spline)(x::Real)\n np = npatches(S)\n\n if is_closed(S)\n\n p = Int(floor(x))\n x = mod(x, np)\n p = Int(floor(x))\n\n if p == 0\n p = np\n x += np\n end\n f = S[p]\n return f(x - p)\n end\n\n # open spline\n p = Int(floor(x))\n if x < 1\n p = 1\n end\n\n if p > np\n p = np\n end\n f = S[p]\n return f(x - p)\nend\n\n\nfunction open_spline(y::Array{T,1})::Spline where {T<:Number}\n n = length(y)\n M = zeros(n, n)\n for i = 1:n\n M[i, i] = 4\n end\n M[1, 1] = 2\n M[n, n] = 2\n\n for i = 1:n-1\n M[i, i+1] = 1\n M[i+1, i] = 1\n end\n\n rhs = zeros(T, n)\n rhs[1] = 3 * (y[2] - y[1])\n for k = 2:n-1\n rhs[k] = 3 * (y[k+1] - y[k-1])\n end\n rhs[n] = 3 * (y[n] - y[n-1])\n\n D = M \\ rhs\n\n a = zeros(Number, n - 1)\n b = zeros(Number, n - 1)\n c = zeros(Number, n - 1)\n d = zeros(Number, n - 1)\n\n for j = 1:n-1\n a[j] = y[j]\n b[j] = D[j]\n c[j] = 3 * (y[j+1] - y[j]) - 2D[j] - D[j+1]\n d[j] = 2 * (y[j] - y[j+1]) + D[j] + D[j+1]\n end\n return Spline([Cubic(a[i], b[i], c[i], d[i]) for i = 1:n-1], false)\nend\n\nfunction closed_spline(y::Array{T,1})::Spline where {T<:Number}\n yy = copy(y)\n n = length(y)\n prepend!(yy, y[end-3:end])\n append!(yy, y[1:4])\n\n S = open_spline(yy)\n\n plist = S.patches[5:end-3]\n return Spline(plist, true)\n\nend\n", "meta": {"hexsha": "069b2fa40b4270c64822ac59a5baf02346bc8467", "size": 3430, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/cubic.jl", "max_stars_repo_name": "scheinerman/SimpleDrawing.jl", "max_stars_repo_head_hexsha": "2d446d715667170e94f81cd0ab87089b7d87fd0e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-10-24T10:11:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-24T00:58:19.000Z", "max_issues_repo_path": "src/cubic.jl", "max_issues_repo_name": "scheinerman/SimpleDrawing.jl", "max_issues_repo_head_hexsha": "2d446d715667170e94f81cd0ab87089b7d87fd0e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cubic.jl", "max_forks_repo_name": "scheinerman/SimpleDrawing.jl", "max_forks_repo_head_hexsha": "2d446d715667170e94f81cd0ab87089b7d87fd0e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.3043478261, "max_line_length": 107, "alphanum_fraction": 0.5419825073, "num_tokens": 1229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404018582426, "lm_q2_score": 0.8807970889295664, "lm_q1q2_score": 0.8186484002902665}} {"text": "# Regression\n\n## Auxiliary\n\nfunction lreg_chkdims(X::AbstractMatrix, Y::AbstractVecOrMat, trans::Bool)\n mX, nX = size(X)\n dX = ifelse(trans, mX, nX)\n dY = ifelse(trans, nX, mX)\n size(Y, 1) == dY || throw(DimensionMismatch(\"Dimensions of X and Y mismatch.\"))\n return dX\nend\n\nlrsoltype(::AbstractVector{T}) where T = Vector{T}\nlrsoltype(::AbstractMatrix{T}) where T = Matrix{T}\n\n_vaug(X::AbstractMatrix{T}) where T = vcat(X, ones(T, 1, size(X,2)))::Matrix{T}\n_haug(X::AbstractMatrix{T}) where T = hcat(X, ones(T, size(X,1), 1))::Matrix{T}\n\n\n## Linear Least Square Regression\n\n\n\"\"\"\n llsq(X, y; ...)\n\nSolve the linear least square problem.\n\nHere, `y` can be either a vector, or a matrix where each column is a response vector.\n\nThis function accepts two keyword arguments:\n\n- `dims`: whether input observations are stored as rows (`1`) or columns (`2`). (default is `1`)\n- `bias`: whether to include the bias term `b`. (default is `true`)\n\nThe function results the solution `a`. In particular, when `y` is a vector (matrix), `a` is also a vector (matrix). If `bias` is true, then the returned array is augmented as `[a; b]`.\n\"\"\"\nfunction llsq(X::AbstractMatrix{T}, Y::AbstractVecOrMat{T};\n trans::Bool=false, bias::Bool=true,\n dims::Union{Integer,Nothing}=nothing) where {T<:Real}\n if dims === nothing && trans\n Base.depwarn(\"`trans` argument is deprecated, use llsq(X, Y, dims=d) instead.\", :trans)\n dims = 1\n end\n if dims == 2\n mX, nX = size(X)\n size(Y, 1) == nX || throw(DimensionMismatch(\"Dimensions of X and Y mismatch.\"))\n mX <= nX || error(\"mX <= nX is required when trans is false.\")\n else\n mX, nX = size(X)\n size(Y, 1) == mX || throw(DimensionMismatch(\"Dimensions of X and Y mismatch.\"))\n mX >= nX || error(\"mX >= nX is required when trans is false.\")\n end\n _ridge(X, Y, zero(T), dims == 2, bias)\nend\nllsq(x::AbstractVector{T}, y::AbstractVector{T}; kwargs...) where {T<:Real} =\n llsq(x[:,:], y; dims=1, kwargs...)\n\n## Ridge Regression (Tikhonov regularization)\n\n\"\"\"\n\n ridge(X, y, r; ...)\n\nSolve the ridge regression problem.\n\nHere, ``y`` can be either a vector, or a matrix where each column is a response vector.\n\nThe argument `r` gives the quadratic regularization matrix ``Q``, which can be in either of the following forms:\n\n- `r` is a real scalar, then ``Q`` is considered to be `r * eye(n)`, where `n` is the dimension of `a`.\n- `r` is a real vector, then ``Q`` is considered to be `diagm(r)`.\n- `r` is a real symmetric matrix, then ``Q`` is simply considered to be `r`.\n\nThis function accepts two keyword arguments:\n\n- `dims`: whether input observations are stored as rows (`1`) or columns (`2`). (default is `1`)\n- `bias`: whether to include the bias term `b`. (default is `true`)\n\nThe function results the solution `a`. In particular, when `y` is a vector (matrix), `a` is also a vector (matrix). If `bias` is true, then the returned array is augmented as `[a; b]`.\n\"\"\"\nfunction ridge(X::AbstractMatrix{T}, Y::AbstractVecOrMat{T}, r::Union{Real, AbstractVecOrMat};\n trans::Bool=false, bias::Bool=true,\n dims::Union{Integer,Nothing}=nothing) where {T<:Real}\n if dims === nothing && trans\n Base.depwarn(\"`trans` argument is deprecated, use ridge(X, Y, r, dims=d) instead.\", :trans)\n dims = 1\n end\n d = lreg_chkdims(X, Y, dims == 2)\n if isa(r, Real)\n r >= zero(r) || error(\"r must be non-negative.\")\n r = convert(T <: AbstractFloat ? T : Float64, r)\n elseif isa(r, AbstractVector)\n length(r) == d || throw(DimensionMismatch(\"Incorrect length of r.\"))\n elseif isa(r, AbstractMatrix)\n size(r) == (d, d) || throw(DimensionMismatch(\"Incorrect size of r.\"))\n end\n _ridge(X, Y, r, dims == 2, bias)\nend\nridge(x::AbstractVector{T}, y::AbstractVector{T}, r::Union{Real, AbstractVecOrMat};\n kwargs...) where {T<:Real} = ridge(x[:,:], y, r; dims=1, kwargs...)\n\n### implementation\n\nfunction _ridge(_X::AbstractMatrix{T}, _Y::AbstractVecOrMat{T},\n r::Union{Real, AbstractVecOrMat}, trans::Bool, bias::Bool) where {T<:Real}\n # convert integer data to Float64\n X = T <: AbstractFloat ? _X : convert(Array{Float64}, _X)\n Y = T <: AbstractFloat ? _Y : convert(Array{Float64}, _Y)\n if bias\n if trans\n X_ = _vaug(X)\n A = cholesky!(Hermitian(_ridge_reg!(X_ * transpose(X_), r, bias))) \\ (X_ * Y)\n else\n X_ = _haug(X)\n A = cholesky!(Hermitian(_ridge_reg!(X_'X_, r, bias))) \\ (X_'Y)\n end\n else\n if trans\n A = cholesky!(Hermitian(_ridge_reg!(X * X', r, bias))) \\ (X * Y)\n else\n A = cholesky!(Hermitian(_ridge_reg!(X'X, r, bias))) \\ (X'Y)\n end\n end\n return A::lrsoltype(Y)\nend\n\nfunction _ridge_reg!(Q::Matrix, r::Real, bias::Bool)\n if r > zero(r)\n n = size(Q, 1) - Int(bias)\n for i = 1:n\n @inbounds Q[i,i] += r\n end\n end\n return Q\nend\n\nfunction _ridge_reg!(Q::AbstractMatrix, r::AbstractVector, bias::Bool)\n n = size(Q, 1) - Int(bias)\n @assert length(r) == n\n for i = 1:n\n @inbounds Q[i,i] += r[i]\n end\n return Q\nend\n\nfunction _ridge_reg!(Q::AbstractMatrix, r::AbstractMatrix, bias::Bool)\n n = size(Q, 1) - Int(bias)\n @assert size(r) == (n, n)\n for j = 1:n, i = 1:n\n @inbounds Q[i,j] += r[i,j]\n end\n return Q\nend\n\n## Isotonic Regression\n\n\"\"\"\n isotonic(x, y[, w])\n\nSolve the isotonic regression problem using the pool adjacent violators algorithm[^1].\n\nHere `x` is the regressor vector, `y` is response vector, and `w` is an optional\nweights vector.\n\nThe function returns a prediction vector of the same size as the regressor vector `x`.\n\"\"\"\nfunction isotonic(x::AbstractVector{T}, y::AbstractVector{T},\n w::AbstractVector{T} = ones(T, length(y))) where {T<:Real}\n n = length(x)\n n == length(y) || throw(DimensionMismatch(\"Dimensions of x and y mismatch.\"))\n\n idx = sortperm(x)\n\n # PVA algorithm\n J = map(i->(Float64(y[i]*w[i]), w[i], [i]), idx)\n i = 1\n B₀ = J[i]\n while i < length(J)\n B₊ = J[i+1]\n if B₀[1] <= B₊[1] # step 1\n B₀ = B₊\n i += 1\n else # step 2\n ww = B₀[2] + B₊[2]\n J[i] = ((B₀[1]*B₀[2]+B₊[1]*B₊[2])/ww, ww, append!(B₀[3], B₊[3]))\n deleteat!(J, i+1)\n B₀ = J[i]\n while i > 1 # step 2.1\n B₋ = J[i-1]\n if B₀[1] <= B₋[1]\n ww = B₀[2] + B₋[2]\n J[i] = ((B₀[1]*B₀[2]+B₋[1]*B₋[2])/ww, ww, append!(B₀[3], B₋[3]))\n deleteat!(J, i-1)\n i-=1\n else\n break\n end\n end\n end\n end\n [y for (y,w,ii) in J for i in sort(ii)]\nend\n\n", "meta": {"hexsha": "35e7f7d9ee0959905ba8e3a7d99cbc051fb5d93a", "size": 6880, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lreg.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/lreg.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/lreg.jl", "max_forks_repo_name": "KronosTheLate/MultivariateStats.jl", "max_forks_repo_head_hexsha": "99ee965df3a8e136ff2d0fcb10456b434e1f9001", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7254901961, "max_line_length": 184, "alphanum_fraction": 0.5761627907, "num_tokens": 2119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404018582427, "lm_q2_score": 0.8807970795424087, "lm_q1q2_score": 0.818648391565463}} {"text": "#=\nCreated on 09/01/2021 14:50:19\nLast update: -\n\n@author: Michiel Stock\nmichielfmstock@gmail.com\n\nImplement Stirling's approximation for the factorial.\n=#\n\nusing Plots\n\nstirling(n) = n * log(n / exp(1)) + 0.5log(2π*n)\n\n# here we use `m=:circle` to use the :circle symbols as a marker on our plots.\n\nplot(1:10, n->log(factorial(big(n))), m=:circle, label=\"log-factorial\")\nxlabel!(\"n\")\nplot!(stirling, 1:10, m=:circle, label = \"Stirling's approximation\")\n\n\n", "meta": {"hexsha": "8249de7937cd345e14fc5a40c789c646bfddd0fe", "size": 456, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/stirling.jl", "max_stars_repo_name": "Beramos/DS-Julia2925", "max_stars_repo_head_hexsha": "8496d623f9836bec1db9a4daf882f484ad87a0a9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-02-03T14:07:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-18T13:27:08.000Z", "max_issues_repo_path": "examples/stirling.jl", "max_issues_repo_name": "Beramos/DS-Julia2925", "max_issues_repo_head_hexsha": "8496d623f9836bec1db9a4daf882f484ad87a0a9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 74, "max_issues_repo_issues_event_min_datetime": "2020-11-23T22:50:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-27T12:49:00.000Z", "max_forks_repo_path": "examples/stirling.jl", "max_forks_repo_name": "Beramos/DS-Julia2925", "max_forks_repo_head_hexsha": "8496d623f9836bec1db9a4daf882f484ad87a0a9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-01-31T14:56:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-19T07:11:30.000Z", "avg_line_length": 20.7272727273, "max_line_length": 78, "alphanum_fraction": 0.6907894737, "num_tokens": 148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.948154531885212, "lm_q2_score": 0.8633916029436189, "lm_q1q2_score": 0.8186286611226299}} {"text": "# Unit classification.jl, part of PosDefManifold Package for julia language\n# v 0.1.3 - last update 7th of Mai 2019\n#\n# MIT License\n# Copyright (c) 2019, Marco Congedo, CNRS, Grenobe, France:\n# https://sites.google.com/site/marcocongedo/home\n#\n# DESCRIPTION\n# This Unit implements classification methods and related functions\n# useful in relation to the Riemannian Geometry on the manifold\n# of Symmetric Positive Definite (SPD) or Hermitian matrices.\n#\n# CONTENT\n# 1. Probability\n# __________________________________________________________________\n\n# ------------------------\n## 1. Probability\n# ------------------------\n\n\"\"\"\n softmax(χ::Vector{T}) where T<:Real\n\n Given a real vector of ``k`` non-negative scores ``χ=c_1,...,c_k``,\n return the vector ``π=p_1,...,p_k`` of their\n [softmax](https://en.wikipedia.org/wiki/Softmax_function) probabilities,\n as per\n\n `` p_i=\\\\frac{\\\\textrm{e}^{c_i}}{\\\\sum_{i=1}^{k}\\\\textrm{e}^{c_i}} ``.\n\n ## Examples\n χ=[1.0, 2.3, 0.4, 5.0]\n π=softmax(χ)\n\n\"\"\"\nsoftmax(χ::Vector{T}) where T<:Real = exp.(χ) ./ 𝚺(exp.(χ))\n", "meta": {"hexsha": "9932230b51f205cf7a54182150615e2d102473b2", "size": 1086, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "build/classification.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/PosDefManifold.jl-f45a3650-5c51-11e9-1e9a-133aa5e309cf", "max_stars_repo_head_hexsha": "f5351c8a9891784b6ac94ff0cf8bbdd5249824d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2019-04-12T14:36:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-30T08:17:48.000Z", "max_issues_repo_path": "build/classification.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/PosDefManifold.jl-f45a3650-5c51-11e9-1e9a-133aa5e309cf", "max_issues_repo_head_hexsha": "f5351c8a9891784b6ac94ff0cf8bbdd5249824d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 24, "max_issues_repo_issues_event_min_datetime": "2019-05-23T11:21:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-03T01:07:07.000Z", "max_forks_repo_path": "build/classification.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/PosDefManifold.jl-f45a3650-5c51-11e9-1e9a-133aa5e309cf", "max_forks_repo_head_hexsha": "f5351c8a9891784b6ac94ff0cf8bbdd5249824d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-04-11T13:02:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-11T08:38:29.000Z", "avg_line_length": 29.3513513514, "max_line_length": 77, "alphanum_fraction": 0.6473296501, "num_tokens": 336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.948154531885212, "lm_q2_score": 0.8633916029436189, "lm_q1q2_score": 0.8186286611226299}} {"text": "export hermite, HermiteBasis\n\n\"\"\"\n y = hermite(n::Int, x::Real)\n\nEvaluate the ``n``-degree Hermite polynomial at ``x``.\n\n```math\nn!\\\\sum_{m=0}^{[n/2]} \\\\frac{(-1)^m}{m!(n-2m)!} \\\\frac{x^{n-2m}}{2^m}\n```\n\"\"\"\nfunction hermite(n::Int, x::Real)\n if n == 0\n 1\n else\n N = Int(floor(n/2))\n fac = factorial\n s = reduce((s, m) -> s + (-1)^m * x^(n-2m) / (fac(m) * fac(n-2m) * 2^m), 0:N; init=0)\n fac(n) * s\n end\nend\n\n\"\"\"\n basis = HermiteBasis(vectors)\n\nEncode an ordered basis (`basis`) of polynomials ``(ψ_j)_{j\\\\in \\\\mathcal J_i}`` of the form\n\n```math\nψ_{(j_1,\\\\ldots,j_n)}(θ_1, \\\\ldots, θ_n) = \\\\prod_{k=1}^n φ_{j_k}(θ_k),\n```\n\nwhere ``φ_{j_k}`` is the Hermite polynomial of degree ``j_k``.\nThe indices ``\\\\mathcal J_i`` of the polynomials is provided by `vectors` in the natural \nway. For example, \n\n```julia\nHermiteBasis([[1, 2, 3], [0, 1, 1, 2]])\n```\n\nwill encode the ordered basis ``( ψ_{(1,2,3)}, ψ_{(0,1,1,2)} )``.\n\"\"\"\nstruct HermiteBasis <: OrderedBasis\n vectors::AbstractArray{<:AbstractArray{<:Int}}\n function HermiteBasis(vectors::AbstractArray{<:AbstractArray{<:Int}})\n if all(vec -> all(x -> x >= 0, vec), vectors)\n new(vectors)\n else\n throw(\n ArgumentError(\"A `HermiteBasis` must only include vectors with positive components.\")\n )\n end\n end\nend\n\nBase.length(basis::HermiteBasis) = length(basis.vectors)\n\nfunction Base.union(basis::HermiteBasis, bases...)\n HermiteBasis(union(basis.vectors, map(b -> b.vectors, bases)...))\nend\n\nfunction (basis::HermiteBasis)(theta::AbstractArray{<:Real})\n if any(vec -> length(vec) > length(theta), basis.vectors)\n throw(ArgumentError(\"$theta is not in the domain of $basis\"))\n else\n map(vec -> prod(map(p -> hermite(p[2], theta[p[1]]), enumerate(vec))), basis.vectors)\n end\nend\n", "meta": {"hexsha": "079f4c9c306c62d2c75c384b1a8600dc10849579", "size": 1790, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/transport/polynomials.jl", "max_stars_repo_name": "mvarble/gen-transport-mcmc", "max_stars_repo_head_hexsha": "1690445a89960a8e189b4e5a4e4fb22d9c6ae2d7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/transport/polynomials.jl", "max_issues_repo_name": "mvarble/gen-transport-mcmc", "max_issues_repo_head_hexsha": "1690445a89960a8e189b4e5a4e4fb22d9c6ae2d7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/transport/polynomials.jl", "max_forks_repo_name": "mvarble/gen-transport-mcmc", "max_forks_repo_head_hexsha": "1690445a89960a8e189b4e5a4e4fb22d9c6ae2d7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-23T05:14:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-23T05:14:33.000Z", "avg_line_length": 26.3235294118, "max_line_length": 93, "alphanum_fraction": 0.6167597765, "num_tokens": 640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377261041522, "lm_q2_score": 0.8539127566694178, "lm_q1q2_score": 0.818507592069232}} {"text": "# # Gaussian process prior samples\n#\n# The kernels defined in this package can also be used to specify the\n# covariance of a Gaussian process prior.\n# A Gaussian process (GP) is defined by its mean function $m(\\cdot)$ and its covariance function or kernel $k(\\cdot, \\cdot')$:\n# ```math\n# f \\sim \\mathcal{GP}\\big(m(\\cdot), k(\\cdot, \\cdot')\\big)\n# ```\n# In this notebook we show how the choice of kernel affects the samples from a GP (with zero mean).\n\n## Load required packages\nusing KernelFunctions, LinearAlgebra\nusing Plots, Plots.PlotMeasures\ndefault(; lw=1.0, legendfontsize=8.0)\nusing Random: seed!\nseed!(42); # reproducibility\n\n##\n# ## Evaluation at finite set of points\n#\n# The function values $\\mathbf{f} = \\{f(x_n)\\}_{n=1}^N$ of the GP at a finite number $N$ of points $X = \\{x_n\\}_{n=1}^N$ follow a multivariate normal distribution $\\mathbf{f} \\sim \\mathcal{MVN}(\\mathbf{m}, \\mathrm{K})$ with mean vector $\\mathbf{m}$ and covariance matrix $\\mathrm{K}$, where\n# ```math\n# \\begin{aligned}\n# \\mathbf{m}_i &= m(x_i) \\\\\n# \\mathrm{K}_{i,j} &= k(x_i, x_j)\n# \\end{aligned}\n# ```\n# with $1 \\le i, j \\le N$.\n#\n# We can visualize the infinite-dimensional GP by evaluating it on a fine grid to approximate the dense real line:\nnum_inputs = 101\nxlim = (-5, 5)\nX = range(xlim...; length=num_inputs);\n\n# Given a kernel `k`, we can compute the kernel matrix as `K = kernelmatrix(k, X)`.\n\n##\n# ## Random samples\n#\n# To sample from the multivariate normal distribution $p(\\mathbf{f}) = \\mathcal{MVN}(0, \\mathrm{K})$, we could make use of Distributions.jl and call `rand(MvNormal(K))`.\n# Alternatively, we could use the [AbstractGPs.jl](https://github.com/JuliaGaussianProcesses/AbstractGPs.jl) package and construct a `GP` object which we evaluate at the points of interest and from which we can then sample: `rand(GP(k)(X))`.\n\n# Here, we will explicitly construct samples using the Cholesky factorization $\\mathrm{L} = \\operatorname{cholesky}(\\mathrm{K})$,\n# with $\\mathbf{f} = \\mathrm{L} \\mathbf{v}$, where $\\mathbf{v} \\sim \\mathcal{N}(0, \\mathbf{I})$ is a vector of standard-normal random variables.\n\n# We will use the same randomness $\\mathbf{v}$ to generate comparable samples across different kernels.\nnum_samples = 7\nv = randn(num_inputs, num_samples);\n\n# Mathematically, a kernel matrix is by definition positive semi-definite, but due to finite-precision inaccuracies, the computed kernel matrix might not be exactly positive definite. To avoid Cholesky errors, we add a small \"nugget\" term on the diagonal:\nfunction mvn_sample(K)\n L = cholesky(K + 1e-6 * I)\n f = L.L * v\n return f\nend;\n\n##\n# ## Visualization\n# We now define a function that visualizes a kernel for us.\n\nfunction visualize(k::Kernel)\n K = kernelmatrix(k, X)\n f = mvn_sample(K)\n\n p_kernel_2d = heatmap(\n X,\n X,\n K;\n yflip=true,\n colorbar=false,\n ylabel=string(nameof(typeof(k))),\n ylim=xlim,\n yticks=([xlim[1], 0, xlim[end]], [\"\\u22125\", raw\"$x'$\", \"5\"]),\n vlim=(0, 1),\n title=raw\"$k(x, x')$\",\n aspect_ratio=:equal,\n left_margin=5mm,\n )\n\n p_kernel_cut = plot(\n X,\n k.(X, 0.0);\n title=string(raw\"$k(x, x_\\mathrm{ref})$\"),\n label=raw\"$x_\\mathrm{ref}=0.0$\",\n legend=:topleft,\n foreground_color_legend=nothing,\n )\n plot!(X, k.(X, 1.5); label=raw\"$x_\\mathrm{ref}=1.5$\")\n\n p_samples = plot(X, f; c=\"blue\", title=raw\"$f(x)$\", ylim=(-3, 3), label=nothing)\n\n return plot(\n p_kernel_2d,\n p_kernel_cut,\n p_samples;\n layout=(1, 3),\n xlabel=raw\"$x$\",\n xlim=xlim,\n xticks=collect(xlim),\n )\nend;\n\n##\n# We can now visualize a kernel and show samples from\n# a Gaussian process with a given kernel:\n\nplot(visualize(SqExponentialKernel()); size=(800, 210), bottommargin=5mm, topmargin=5mm)\n\n##\n# ## Kernel comparison\n# This also allows us to compare different kernels:\n\nkernels = [\n Matern12Kernel(),\n Matern32Kernel(),\n Matern52Kernel(),\n SqExponentialKernel(),\n WhiteKernel(),\n ConstantKernel(),\n LinearKernel(),\n compose(PeriodicKernel(), ScaleTransform(0.2)),\n NeuralNetworkKernel(),\n]\nplot(\n [visualize(k) for k in kernels]...;\n layout=(length(kernels), 1),\n size=(800, 220 * length(kernels) + 100),\n)\n", "meta": {"hexsha": "b1ba3dcee7ea6f41da28397aa9435b4588f899a2", "size": 4312, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/gaussian-process-priors/script.jl", "max_stars_repo_name": "bmharsha/KernelFunctions.jl", "max_stars_repo_head_hexsha": "3264a92b11af0293314a4b5caf503e2730a3afae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 200, "max_stars_repo_stars_event_min_datetime": "2020-04-07T11:28:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T02:14:13.000Z", "max_issues_repo_path": "examples/gaussian-process-priors/script.jl", "max_issues_repo_name": "bmharsha/KernelFunctions.jl", "max_issues_repo_head_hexsha": "3264a92b11af0293314a4b5caf503e2730a3afae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 324, "max_issues_repo_issues_event_min_datetime": "2020-03-24T16:26:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T07:34:54.000Z", "max_forks_repo_path": "examples/gaussian-process-priors/script.jl", "max_forks_repo_name": "bmharsha/KernelFunctions.jl", "max_forks_repo_head_hexsha": "3264a92b11af0293314a4b5caf503e2730a3afae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2020-03-25T10:25:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T21:19:06.000Z", "avg_line_length": 33.4263565891, "max_line_length": 290, "alphanum_fraction": 0.6525974026, "num_tokens": 1268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418178895029, "lm_q2_score": 0.8856314828740729, "lm_q1q2_score": 0.8184490885634219}} {"text": "module NewtonRaphson\r\n\r\nexport newton_raphson\r\n\r\nfunction newton_raphson(f::Function, x0::Number, fprime::Function, args::Tuple=();\r\n tol::AbstractFloat=1e-8, maxiter::Integer=50, eps::AbstractFloat=1e-10)\r\n for _ in 1:maxiter\r\n yprime = fprime(x0, args...)\r\n if abs(yprime) < eps\r\n warn(\"First derivative is zero\")\r\n return x0\r\n end\r\n y = f(x0, args...)\r\n x1 = x0 - y/yprime\r\n if abs(x1-x0) < tol\r\n return x1\r\n end\r\n x0 = x1\r\n end\r\n error(\"Max iteration exceeded\")\r\nend\r\n\r\nend", "meta": {"hexsha": "ade9af97ad9d83d370c9a83ad39a0ffdd852ccfe", "size": 586, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NewtonRaphson.jl", "max_stars_repo_name": "RohitRathore1/NumericalTechniques.jl", "max_stars_repo_head_hexsha": "66eacc0d31c555c42f9712b9187633e2ba0b514c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NewtonRaphson.jl", "max_issues_repo_name": "RohitRathore1/NumericalTechniques.jl", "max_issues_repo_head_hexsha": "66eacc0d31c555c42f9712b9187633e2ba0b514c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NewtonRaphson.jl", "max_forks_repo_name": "RohitRathore1/NumericalTechniques.jl", "max_forks_repo_head_hexsha": "66eacc0d31c555c42f9712b9187633e2ba0b514c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4782608696, "max_line_length": 88, "alphanum_fraction": 0.542662116, "num_tokens": 172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9362849986365572, "lm_q2_score": 0.874077230244524, "lm_q1q2_score": 0.8183853983277398}} {"text": "\n# # An Intro to DifferentialEquations.jl\n# \n# ## Basic Introduction Via Ordinary Differential Equations\n# \n# This notebook will get you started with DifferentialEquations.jl by introducing you to the functionality for solving ordinary differential equations (ODEs). The corresponding documentation page is the [ODE tutorial](http://docs.juliadiffeq.org/latest/tutorials/ode_example.html). While some of the syntax may be different for other types of equations, the same general principles hold in each case. Our goal is to give a gentle and thorough introduction that highlights these principles in a way that will help you generalize what you have learned.\n# \n# ### Background\n# \n# If you are new to the study of differential equations, it can be helpful to do a quick background read on [the definition of ordinary differential equations](https://en.wikipedia.org/wiki/Ordinary_differential_equation). We define an ordinary differential equation as an equation which describes the way that a variable $u$ changes, that is\n# \n# $$ u' = f(u,p,t) $$\n# \n# where $p$ are the parameters of the model, $t$ is the time variable, and $f$ is the nonlinear model of how $u$ changes. The initial value problem also includes the information about the starting value:\n# \n# $$ u(t_0) = u_0 $$\n# \n# Together, if you know the starting value and you know how the value will change with time, then you know what the value will be at any time point in the future. This is the intuitive definition of a differential equation.\n\n# ### First Model: Exponential Growth\n# \n# Our first model will be the canonical exponential growth model. This model says that the rate of change is proportional to the current value, and is this:\n# \n# $$ u' = au $$\n# \n# where we have a starting value $u(0)=u_0$. Let's say we put 1 dollar into Bitcoin which is increasing at a rate of $98\\%$ per year. Then calling now $t=0$ and measuring time in years, our model is:\n# \n# $$ u' = 0.98u $$\n# \n# and $u(0) = 1.0$. We encode this into Julia by noticing that, in this setup, we match the general form when\n# \n# $$ f(u,p,t) = 0.98u $$\n# \n# with $ u_0 = 1.0 $. If we want to solve this model on a time span from `t=0.0` to `t=1.0`, then we define an `ODEProblem` by specifying this function `f`, this initial condition `u0`, and this time span as follows:\n\nusing DifferentialEquations\nf(u,p,t) = 0.98u\nu0 = 1.0\ntspan = (0.0,1.0)\nprob = ODEProblem(f,u0,tspan)\n#----------------------------------------------------------------------------\n\n# To solve our `ODEProblem` we use the command `solve`.\n\nsol = solve(prob)\n#----------------------------------------------------------------------------\n\n# and that's it: we have succesfully solved our first ODE!\n# \n# #### Analyzing the Solution\n# \n# Of course, the solution type is not interesting in and of itself. We want to understand the solution! The documentation page which explains in detail the functions for analyzing the solution is the [Solution Handling](http://docs.juliadiffeq.org/latest/basics/solution.html) page. Here we will describe some of the basics. You can plot the solution using the plot recipe provided by [Plots.jl](http://docs.juliaplots.org/latest/):\n\nusing Plots; gr()\nplot(sol)\n#----------------------------------------------------------------------------\n\n# From the picture we see that the solution is an exponential curve, which matches our intuition. As a plot recipe, we can annotate the result using any of the [Plots.jl attributes](http://docs.juliaplots.org/latest/attributes/). For example:\n\nplot(sol,linewidth=5,title=\"Solution to the linear ODE with a thick line\",\n xaxis=\"Time (t)\",yaxis=\"u(t) (in μm)\",label=\"My Thick Line!\") ## legend=false\n#----------------------------------------------------------------------------\n\n# Using the mutating `plot!` command we can add other pieces to our plot. For this ODE we know that the true solution is $u(t) = u_0 exp(at)$, so let's add some of the true solution to our plot:\n\nplot!(sol.t, t->1.0*exp(0.98t),lw=3,ls=:dash,label=\"True Solution!\")\n#----------------------------------------------------------------------------\n\n# In the previous command I demonstrated `sol.t`, which grabs the array of time points that the solution was saved at:\n\nsol.t\n#----------------------------------------------------------------------------\n\n# We can get the array of solution values using `sol.u`:\n\nsol.u\n#----------------------------------------------------------------------------\n\n# `sol.u[i]` is the value of the solution at time `sol.t[i]`. We can compute arrays of functions of the solution values using standard comprehensions, like:\n\n[t+u for (u,t) in tuples(sol)]\n#----------------------------------------------------------------------------\n\n# However, one interesting feature is that, by default, the solution is a continuous function. If we check the print out again:\n\nsol\n#----------------------------------------------------------------------------\n\n# you see that it says that the solution has a 4th order interpolation, meaning that it is a continuous function of 4th order accuracy. We can call the solution as a function of time `sol(t)`. For example, to get the value at `t=0.45`, we can use the command:\n\nsol(0.45)\n#----------------------------------------------------------------------------\n\n# #### Controlling the Solver\n# \n# DifferentialEquations.jl has a common set of solver controls among its algorithms which can be found [at the Common Solver Options](http://docs.juliadiffeq.org/latest/basics/common_solver_opts.html) page. We will detail some of the most widely used options. \n# \n# The most useful options are the tolerances `abstol` and `reltol`. These tell the internal adaptive time stepping engine how precise of a solution you want. Generally, `reltol` is the relative accuracy while `abstol` is the accuracy when `u` is near zero. These tolerances are local tolerances and thus are not global guarantees. However, a good rule of thumb is that the total solution accuracy is 1-2 digits less than the relative tolerances. Thus for the defaults `abstol=1e-6` and `reltol=1e-3`, you can expect a global accuracy of about 1-2 digits. If we want to get around 6 digits of accuracy, we can use the commands:\n\nsol = solve(prob,abstol=1e-8,reltol=1e-8)\n#----------------------------------------------------------------------------\n\n# Now we can see no visible difference against the true solution:\n\nplot(sol)\nplot!(sol.t, t->1.0*exp(0.98t),lw=3,ls=:dash,label=\"True Solution!\")\n#----------------------------------------------------------------------------\n\n# Notice that by decreasing the tolerance, the number of steps the solver had to take was `9` instead of the previous `5`. There is a trade off between accuracy and speed, and it is up to you to determine what is the right balance for your problem.\n# \n# Another common option is to use `saveat` to make the solver save at specific time points. For example, if we want the solution at an even grid of `t=0.1k` for integers `k`, we would use the command:\n\nsol = solve(prob,saveat=0.1)\n#----------------------------------------------------------------------------\n\n# Notice that when `saveat` is used the continuous output variables are no longer saved and thus `sol(t)`, the interpolation, is only first order. We can save at an uneven grid of points by passing a collection of values to `saveat`. For example:\n\nsol = solve(prob,saveat=[0.2,0.7,0.9])\n#----------------------------------------------------------------------------\n\n# By default it always saves the first and last values, but we can turn this off as well:\n\nsol = solve(prob,saveat=[0.2,0.7,0.9],save_start = false, save_end = false)\n#----------------------------------------------------------------------------\n\n# If we need to reduce the amount of saving, we can also turn off the continuous output directly via `dense=false`:\n\nsol = solve(prob,dense=false)\n#----------------------------------------------------------------------------\n\n# and to turn off all intermediate saving we can use `save_everystep=false`:\n\nsol = solve(prob,save_everystep=false)\n#----------------------------------------------------------------------------\n\n# More advanced saving behaviors, such as saving functionals of the solution, are handled via the `SavingCallback` in the [Callback Library](http://docs.juliadiffeq.org/latest/features/callback_library.html#SavingCallback-1) which will be addressed later in the tutorial.\n\n# #### Choosing Solver Algorithms\n# \n# There is no best algorithm for numerically solving a differential equation. When you call `solve(prob)`, DifferentialEquations.jl makes a guess at a good algorithm for your problem, given the properties that you ask for (the tolerances, the saving information, etc.). However, in many cases you may want more direct control. A later notebook will help introduce the various *algorithms* in DifferentialEquations.jl, but for now let's introduce the *syntax*.\n# \n# The most crucial determining factor in choosing a numerical method is the stiffness of the model. Stiffness is roughly characterized by a Jacobian `f` with large eigenvalues. That's quite mathematical, and we can think of it more intuitively: if you have big numbers in `f` (like parameters of order `1e5`), then it's probably stiff. Or, as the creator of the MATLAB ODE Suite, Lawrence Shampine, likes to define it, if the standard algorithms are slow, then it's stiff. We will go into more depth about diagnosing stiffness in a later tutorial, but for now note that if you believe your model may be stiff, you can hint this to the algorithm chooser via `alg_hints = [:stiff]`.\n\nsol = solve(prob,alg_hints=[:stiff])\n#----------------------------------------------------------------------------\n\n# Stiff algorithms have to solve implicit equations and linear systems at each step so they should only be used when required. \n# \n# If we want to choose an algorithm directly, you can pass the algorithm type after the problem as `solve(prob,alg)`. For example, let's solve this problem using the `Tsit5()` algorithm, and just for show let's change the relative tolerance to `1e-6` at the same time:\n\nsol = solve(prob,Tsit5(),reltol=1e-6)\n#----------------------------------------------------------------------------\n\n# ### Systems of ODEs: The Lorenz Equation\n# \n# Now let's move to a system of ODEs. The [Lorenz equation](https://en.wikipedia.org/wiki/Lorenz_system) is the famous \"butterfly attractor\" that spawned chaos theory. It is defined by the system of ODEs:\n# \n# $$ \\frac{dx}{dt} = \\sigma (y - x) $$\n# $$ \\frac{dy}{dt} = x (\\rho - z) -y $$\n# $$ \\frac{dz}{dt} = xy - \\beta z $$\n# \n# To define a system of differential equations in DifferentialEquations.jl, we define our `f` as a vector function with a vector initial condition. Thus, for the vector `u = [x,y,z]'`, we have the derivative function:\n\nfunction lorenz!(du,u,p,t)\n σ,ρ,β = p\n du[1] = σ*(u[2]-u[1])\n du[2] = u[1]*(ρ-u[3]) - u[2]\n du[3] = u[1]*u[2] - β*u[3] \nend\n#----------------------------------------------------------------------------\n\n# Notice here we used the in-place format which writes the output to the preallocated vector `du`. For systems of equations the in-place format is faster. We use the initial condition $u_0 = [1.0,0.0,0.0]$ as follows:\n\nu0 = [1.0,0.0,0.0]\n#----------------------------------------------------------------------------\n\n# Lastly, for this model we made use of the parameters `p`. We need to set this value in the `ODEProblem` as well. For our model we want to solve using the parameters $\\sigma = 10$, $\\rho = 28$, and $\\beta = 8/3$, and thus we build the parameter collection:\n\np = (10,28,8/3) ## we could also make this an array, or any other type!\n#----------------------------------------------------------------------------\n\n# Now we generate the `ODEProblem` type. In this case, since we have parameters, we add the parameter values to the end of the constructor call. Let's solve this on a time span of `t=0` to `t=100`:\n\ntspan = (0.0,100.0)\nprob = ODEProblem(lorenz!,u0,tspan,p)\n#----------------------------------------------------------------------------\n\n# Now, just as before, we solve the problem:\n\nsol = solve(prob)\n#----------------------------------------------------------------------------\n\n# The same solution handling features apply to this case. Thus `sol.t` stores the time points and `sol.u` is an array storing the solution at the corresponding time points. \n# \n# However, there are a few extra features which are good to know when dealing with systems of equations. First of all, `sol` also acts like an array. `sol[i]` returns the solution at the `i`th time point.\n\nsol.t[10],sol[10]\n#----------------------------------------------------------------------------\n\n# Additionally, the solution acts like a matrix where `sol[j,i]` is the value of the `j`th variable at time `i`:\n\nsol[2,10]\n#----------------------------------------------------------------------------\n\n# We can get a real matrix by performing a conversion:\n\nA = convert(Array,sol)\n#----------------------------------------------------------------------------\n\n# This is the same as sol, i.e. `sol[i,j] = A[i,j]`, but now it's a true matrix. Plotting will by default show the time series for each variable:\n\nplot(sol)\n#----------------------------------------------------------------------------\n\n# If we instead want to plot values against each other, we can use the `vars` command. Let's plot variable `1` against variable `2` against variable `3`:\n\nplot(sol,vars=(1,2,3))\n#----------------------------------------------------------------------------\n\n# This is the classic Lorenz attractor plot, where the `x` axis is `u[1]`, the `y` axis is `u[2]`, and the `z` axis is `u[3]`. Note that the plot recipe by default uses the interpolation, but we can turn this off:\n\nplot(sol,vars=(1,2,3),denseplot=false)\n#----------------------------------------------------------------------------\n\n# Yikes! This shows how calculating the continuous solution has saved a lot of computational effort by computing only a sparse solution and filling in the values! Note that in vars, `0=time`, and thus we can plot the time series of a single component like:\n\nplot(sol,vars=(0,2))\n#----------------------------------------------------------------------------\n\n# ### A DSL for Parameterized Functions\n# \n# In many cases you may be defining a lot of functions with parameters. There exists the domain-specific language (DSL) defined by the `@ode_def` macro for helping with this common problem. For example, we can define the Lotka-Volterra equation:\n# \n# $$ \\frac{dx}{dt} = ax - bxy $$\n# $$ \\frac{dy}{dt} = -cy + dxy $$\n# \n# as follows:\n\nfunction lotka_volterra!(du,u,p,t)\n du[1] = p[1]*u[1] - p[2]*u[1]*u[2]\n du[2] = -p[3]*u[2] + p[4]*u[1]*u[2]\nend\n#----------------------------------------------------------------------------\n\n# However, that can be hard to follow since there's a lot of \"programming\" getting in the way. Instead, you can use the `@ode_def` macro:\n\nlv! = @ode_def LotkaVolterra begin\n dx = a*x - b*x*y\n dy = -c*y + d*x*y\nend a b c d\n#----------------------------------------------------------------------------\n\n# We can then use the result just like an ODE function from before:\n\nu0 = [1.0,1.0]\np = (1.5,1.0,3.0,1.0)\ntspan = (0.0,10.0)\nprob = ODEProblem(lv!,u0,tspan,p)\nsol = solve(prob)\nplot(sol)\n#----------------------------------------------------------------------------\n\n# Not only is the DSL convenient syntax, but it does some magic behind the scenes. For example, further parts of the tutorial will describe how solvers for stiff differential equations have to make use of the Jacobian in calculations. Here, the DSL uses symbolic differentiation to automatically derive that function:\n\nlv!.Jex\n#----------------------------------------------------------------------------\n\n# The DSL can derive many other functions; this ability is used to speed up the solvers. An extension to DifferentialEquations.jl, [Latexify.jl](https://korsbo.github.io/Latexify.jl/latest/tutorials/parameterizedfunctions.html), allows you to extract these pieces as LaTeX expressions.\n\n# ## Internal Types\n# \n# The last basic user-interface feature to explore is the choice of types. DifferentialEquations.jl respects your input types to determine the internal types that are used. Thus since in the previous cases, when we used `Float64` values for the initial condition, this meant that the internal values would be solved using `Float64`. We made sure that time was specified via `Float64` values, meaning that time steps would utilize 64-bit floats as well. But, by simply changing these types we can change what is used internally.\n# \n# As a quick example, let's say we want to solve an ODE defined by a matrix. To do this, we can simply use a matrix as input. \n\nA = [1. 0 0 -5\n 4 -2 4 -3\n -4 0 0 1\n 5 -2 2 3]\nu0 = rand(4,2)\ntspan = (0.0,1.0)\nf(u,p,t) = A*u\nprob = ODEProblem(f,u0,tspan)\nsol = solve(prob)\n#----------------------------------------------------------------------------\n\n# There is no real difference from what we did before, but now in this case `u0` is a `4x2` matrix. Because of that, the solution at each time point is matrix:\n\nsol[3]\n#----------------------------------------------------------------------------\n\n# In DifferentialEquations.jl, you can use any type that defines `+`, `-`, `*`, `/`, and has an appropriate `norm`. For example, if we want arbitrary precision floating point numbers, we can change the input to be a matrix of `BigFloat`:\n\nbig_u0 = big.(u0)\n#----------------------------------------------------------------------------\n\n# and we can solve the `ODEProblem` with arbitrary precision numbers by using that initial condition:\n\nprob = ODEProblem(f,big_u0,tspan)\nsol = solve(prob)\n#----------------------------------------------------------------------------\n\nsol[1,3]\n#----------------------------------------------------------------------------\n\n# To really make use of this, we would want to change `abstol` and `reltol` to be small! Notice that the type for \"time\" is different than the type for the dependent variables, and this can be used to optimize the algorithm via keeping multiple precisions. We can convert time to be arbitrary precision as well by defining our time span with `BigFloat` variables:\n# \n\nprob = ODEProblem(f,big_u0,big.(tspan))\nsol = solve(prob)\n#----------------------------------------------------------------------------\n\n# Let's end by showing a more complicated use of types. For small arrays, it's usually faster to do operations on static arrays via the package [StaticArrays.jl](https://github.com/JuliaArrays/StaticArrays.jl). The syntax is similar to that of normal arrays, but for these special arrays we utilize the `@SMatrix` macro to indicate we want to create a static array.\n\nusing StaticArrays\nA = @SMatrix [ 1.0 0.0 0.0 -5.0\n 4.0 -2.0 4.0 -3.0\n -4.0 0.0 0.0 1.0\n 5.0 -2.0 2.0 3.0]\nu0 = @SMatrix rand(4,2)\ntspan = (0.0,1.0)\nf(u,p,t) = A*u\nprob = ODEProblem(f,u0,tspan)\nsol = solve(prob)\n#----------------------------------------------------------------------------\n\nsol[3]\n#----------------------------------------------------------------------------\n\n# ## Conclusion\n# \n# These are the basic controls in DifferentialEquations.jl. All equations are defined via a problem type, and the `solve` command is used with an algorithm choice (or the default) to get a solution. Every solution acts the same, like an array `sol[i]` with `sol.t[i]`, and also like a continuous function `sol(t)` with a nice plot command `plot(sol)`. The Common Solver Options can be used to control the solver for any equation type. Lastly, the types used in the numerical solving are determined by the input types, and this can be used to solve with arbitrary precision and add additional optimizations (this can be used to solve via GPUs for example!). While this was shown on ODEs, these techniques generalize to other types of equations as well.\n", "meta": {"hexsha": "6ebc0c553ec654f6f6c3b821344077a1fe39b6c8", "size": 20017, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "demo/ODEIntroduction.jl", "max_stars_repo_name": "hdrake/ipynb2LiterateJulia", "max_stars_repo_head_hexsha": "a03b077cdd02bb3adcf25c58f742dce9142292e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2020-03-18T02:47:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T00:27:06.000Z", "max_issues_repo_path": "demo/ODEIntroduction.jl", "max_issues_repo_name": "hdrake/ipynb2LiterateJulia", "max_issues_repo_head_hexsha": "a03b077cdd02bb3adcf25c58f742dce9142292e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-05-04T12:57:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-19T20:12:29.000Z", "max_forks_repo_path": "demo/ODEIntroduction.jl", "max_forks_repo_name": "hdrake/ipynb2LiterateJulia", "max_forks_repo_head_hexsha": "a03b077cdd02bb3adcf25c58f742dce9142292e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-03-27T00:44:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-30T18:00:41.000Z", "avg_line_length": 60.1111111111, "max_line_length": 751, "alphanum_fraction": 0.6085827047, "num_tokens": 4603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294209307224, "lm_q2_score": 0.9059898114992677, "lm_q1q2_score": 0.818375350418632}} {"text": "using Distributions\nusing Plots\nusing QuadGK\n\nΣ₁₁, Σ₁₂, Σ₁₃ = 1.0, 0.5, 0.1\nΣ₂₁, Σ₂₂, Σ₂₃ = 0.5, 2.0, 0.2\nΣ₃₁, Σ₃₂, Σ₃₃ = 0.1, 0.2, 0.5\nμ₁=0\nμ₂=-1.0\nμ₃=2.0\n\nμ = [\n μ₁\n μ₂\n μ₃\n]\n\nΣ = [\n Σ₁₁ Σ₁₂ Σ₁₃\n Σ₂₁ Σ₂₂ Σ₂₃\n Σ₃₁ Σ₃₂ Σ₃₃\n]\n\n\nμ_marginal = [\n μ₁\n μ₂\n]\n\nΣ_marginal = [\n Σ₁₁ Σ₁₂\n Σ₂₁ Σ₂₂\n]\n\n\nd = MvNormal(μ, Σ)\ndata = rand(d,250)\n\n\"\"\"\np(x,y) = \\\\int p(x,y,z) dz\n\"\"\"\nfunction marginal(d, x, y)\n integral, err = quadgk(\n z->pdf(d,[x,y,z]),\n μ[2] - maximum(abs.(Σ)),\n μ[2] + maximum(abs.(Σ)),\n rtol = 1e-8,\n )\n return integral\nend\n\nmarginal(y,z)=marginal(d,y,z)\ncontour(collect(-5:0.1:5), collect(-5:0.1:5), marginal)\nscatter!(data[1,:], data[2,:], label=\"numeric\")\n\n# the pdf function p(x,y) should be 𝒩(μ_marginal, Σ_marginal).\nd = MvNormal(μ_marginal, Σ_marginal)\ndata = rand(d,250)\nscatter!(data[1,:],data[2,:],label=\"theoretial\")\n", "meta": {"hexsha": "aa9a31839f6a860fc34c46e76b634988b6c4ba95", "size": 897, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "plotExer/mutivariateGaussian/marginal_3.jl", "max_stars_repo_name": "terasakisatoshi/juliaExer", "max_stars_repo_head_hexsha": "e3c2195f39de858915a3dcd47684eccbb7ecb552", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-02T01:24:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-04T12:03:25.000Z", "max_issues_repo_path": "plotExer/mutivariateGaussian/marginal_3.jl", "max_issues_repo_name": "terasakisatoshi/juliaExer", "max_issues_repo_head_hexsha": "e3c2195f39de858915a3dcd47684eccbb7ecb552", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "plotExer/mutivariateGaussian/marginal_3.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": 14.95, "max_line_length": 62, "alphanum_fraction": 0.5585284281, "num_tokens": 466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102524151827, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.8183733924414085}} {"text": "## Simple random graph generators ##\n\n\"\"\"\n rand_geom(p::Real)\n \nSample a value from geometric distribution with probability of success `p`.\nThis code is adapted from the [Distributions.jl](https://github.com/JuliaStats/Distributions.jl)\npackage.\n\"\"\"\nrand_geom(p::Real) = floor(Int, -randexp() / log1p(-p))\n\n\"\"\"\n gilbert_fill!(g::Graph, p::Real)\n\nFill graph by choosing each edge randomly with probability `p`.\n\"\"\"\nfunction gilbert_fill!(g::UndirectedGraph, p::Real)\n i, j = 1, 1\n n = nodecount(g)\n while true\n j += 1 + rand_geom(p)\n while j > n\n i += 1\n i > n && return\n j = j - n + i\n end\n addedge!(g, i, j)\n end\nend\n\nfunction gilbert_fill!(g::DirectedGraph, p::Real)\n i, j = 1, 1\n n = nodecount(g)\n while true\n j_ = j + 1 + rand_geom(p)\n j = (j < i && j_ >= i) ? j_ + 1 : j_\n while j > n\n i += 1\n i > n && return\n j -= n\n j += j >= i\n end\n addedge!(g, i, j)\n end\nend\n\n\"\"\"\n graph_gilbert(n::Integer, p::Real)\n\nGenerate a random graph according to Gilbert model with `n` nodes\nand expected density `p`.\n\nAn independent Bernoulli trial is simulated for each possible edge in the graph\nand it is added with probability `p`.\nNote that in this case the number of edges is different each time, but the\nmatiematical expectation for the graph's density is `p`.\n\n# References\n\nGilbert, E.N. (1959). \"Random Graphs\". Annals of Mathematical Statistics. 30 (4): 1141–1144.\ndoi:10.1214/aoms/1177706098.\n\nBatagelj, V. and Brandes, U. (2005) \"Efficient generation of large random networks\".\nPhysical Review E. 71 (3).\n\"\"\"\nfunction graph_gilbert(n::Integer, p::Real; kwargs...)\n @assert(0 <= p <= 1, \"edge probability (p) should be in [0, 1] interval\")\n g = Graph(n; kwargs...)\n p > eps() && gilbert_fill!(g, p)\n return g\nend\n\n\n\"\"\"\n graph_erdos_renyi(n::Integer, m::Integer)\n\nGenerate an [Erdős–Rényi random graph](https://en.wikipedia.org/wiki/Erdős–Rényi_model)\nwith `n` nodes and `m` edges.\n\nFrom mathematical viewpoint, the graph is picked at random with uniform probability\nfrom a set of all possible graphs having `n` nodes and `m` edges. \nIn practice, an empty graph with `n` nodes is created first and\n`m` edges get added between the randomly chosen pairs of its nodes.\n\n# References\n\nErdős, P.; Rényi, A. (1959). \"On Random Graphs. I\". Publicationes Mathematicae. 6: 290–297.\n\"\"\"\nfunction graph_erdos_renyi(n::Integer, m::Integer; kwargs...)\n g = Graph(n; kwargs...)\n if m < maxedgecount(g)\n while edgecount(g) < m\n x, y = rand(1:n), rand(1:n)\n if x == y || hasedge(g, x, y)\n continue\n else\n addedge!(g, x, y)\n end\n end\n elseif m == maxedgecount(g)\n gilbert_fill!(g, 1.)\n else\n error(\"too many edges (m) for Erdős–Rényi graph with n nodes\")\n end\n return g\nend\n\n@deprecate(erdosrenyi, graph_erdos_renyi)\n@deprecate(graph_erdosrenyi, graph_erdos_renyi)\n\n\n\"\"\"\n graph_random(n::Integer, m::Integer)\n graph_random(n::Integer, p::AbstractFloat)\n\nA shorthand for creating random networks. There are two similar but distinct models:\n\n* `(n, m)` model, also known as Erdős–Rényi model. It randomly selects a \n graph from a set of all possible graphs which have `n` nodes and `m` edges.\n\n* `(n, p)` model, introduced by Gilbert. For a graph on `n` nodes,\n it includes each edge with probability `p` independently of the others.\n This gives a graph with mathematical expectation of density equal to `p`.\n\nThis method is just a shorthand for [`graph_erdos_renyi`](@ref) and \n[`graph_gilbert`](@ref), which implement these models and are chosen automatically\nbased on the argument types.\n\nIf you need a graph of high density, use `(n, p)` model as it is much faster.\nIf you want an exact number of edges with lower density, use `(n, m)` model.\n\n# Examples\n\n```julia-repl\njulia> g = graph_random(4, 1.)\n4-node 12-edge directed multigraph\n\njulia> g = graph_random(4, 1)\n4-node 1-edge directed multigraph\n```\n\n# References\n\n[Wikipedia](https://en.wikipedia.org/wiki/Erdős–Rényi_model)\n\"\"\"\ngraph_random(n::Integer, m::Integer; kwargs...) =\n graph_erdos_renyi(n::Integer, m::Integer; kwargs...)\ngraph_random(n::Integer, p::AbstractFloat; kwargs...) =\n graph_gilbert(n::Integer, p::AbstractFloat; kwargs...)\n", "meta": {"hexsha": "d6011764a41b01fd75c40e16c4758c1cb5762793", "size": 4409, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/generate/random.jl", "max_stars_repo_name": "inguar/Junet.jl", "max_stars_repo_head_hexsha": "168d8e4b6c8f6473cec336d0e29bd3926bfe3305", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37, "max_stars_repo_stars_event_min_datetime": "2017-05-21T18:22:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-29T20:21:47.000Z", "max_issues_repo_path": "src/generate/random.jl", "max_issues_repo_name": "inguar/Junet.jl", "max_issues_repo_head_hexsha": "168d8e4b6c8f6473cec336d0e29bd3926bfe3305", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2017-06-06T19:01:07.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-09T17:07:01.000Z", "max_forks_repo_path": "src/generate/random.jl", "max_forks_repo_name": "inguar/Junet.jl", "max_forks_repo_head_hexsha": "168d8e4b6c8f6473cec336d0e29bd3926bfe3305", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-04-26T08:13:10.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-17T02:55:09.000Z", "avg_line_length": 29.3933333333, "max_line_length": 96, "alphanum_fraction": 0.6488999773, "num_tokens": 1275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896737173119, "lm_q2_score": 0.8887587905460026, "lm_q1q2_score": 0.8183599167602464}} {"text": "include(\"header.jl\")\n\n#=\n# Submerged surfaces\nIn this notebook, we will learn how to calculate force and moment on\nflat surfaces immersed in static fluids\n=#\n\n# ### Set up the module\nusing MAE103\n#-\nusing Plots\n\n\n#=\n# Example\nA circular gate of 3 m diameter is located in an inclined wall (60 degrees\nfrom horizontal) of a large reservoir filled with water. A horizontal shaft runs through\nthe center of the gate. The shaft is at a depth of 12 m. The other side\nof the gate is exposed to air at atmospheric pressure.\n* What is the force on the gate?\n* Where does this force effectively act?\n* What is the moment applied by the water on the gate shaft?\n=#\n#-\n#=\nHere, we are working with a simple, symmetric shape (a circle), and we\nknow that the centroid of a circle is at its center. Since the shaft runs\nthrough the center, we know that the centroid is at a depth of 12 m.\n=#\nhc = Depth(12)\nd = Diameter(3)\nΘ = 60*π/180\n\n#=\nThe force is easy to compute, since it is just the specific weight times\narea times depth.\n\n$$F_R = \\gamma h_c A$$\n\n(The atmospheric pressure contributes nothing in this problem, since it\nacts the same on both sides.)\n=#\nA = Area(Circle,d/2)\nFR = Force(SpecificWeight(Water)*A*hc)\n\n#=\nTo find the center of pressure, we use the formula\n\n$$y_R = \\dfrac{I_{xc}}{y_c A} + y_c$$\n\nThis the location along the $y$ axis, which runs from the free surface downward, parallel\nto the plate. In the formula, $I_{xc}$ is the second area moment about the $x$ axis running\nthrough the centroid of the plate, and $y_c$ is the $y$ coordinate of the centroid.\n\nBut $y_c$ is simply $h_c/\\sin\\theta$:\n=#\nyc = Length(hc/sin(Θ))\n\n#=\nand $I_{xc}$ we can compute with a handy function:\n=#\nIxc = SecondAreaMomentX(Circle,d/2)\n\n#=\nNow put them together to get the center of pressure\n=#\nyR = Length(Ixc/(yc*A) + yc)\n\n#=\nHow far is this from the centroid?\n=#\nyR - yc\n\n#=\nRemember, it is lower than the centroid, because there are higher pressures\nacting below the centroid than above it.\n\nTo determine the moment $M_R$ about the shaft, we simply need to remember that the\nforce is acting at the center of pressure, so the moment is equal to the force times the distance\nof this center of pressure from the shaft (i.e., from the centroid)\n=#\nMR = Moment((yR - yc)*FR)\n\n#=\n#### A follow-up question\nWhat happens to these values as the plate gets deeper?\n\nObviously force gets larger. What about $y_R$ and $M_R$? Let's set the depth\nat 20 m, and recalculate:\n=#\nhc = Depth(20)\nFR = Force(SpecificWeight(Water)*A*hc)\nyc = Length(hc/sin(Θ))\nyR = Length(Ixc/(yc*A) + yc)\nyR - yc\n#=\nso it gets a little closer to the centroid as the plate gets lower. What about\nthe moment?\n=#\nMR = Moment((yR - yc)*FR)\n#=\nIt's exactly the same! In fact, **the moment about the centroid does not\ndepend on how deep the plate is**.\n=#\n\n#=\n#### Another follow-up question\nWhat happens if the plate becomes more vertical? We'll set $h_c$ to 12 m again\nand make $Θ = 90^\\circ$. Only $y_c$ changes:\n=#\nhc = Depth(12)\nΘ = 90*π/180\nFR = Force(SpecificWeight(Water)*A*hc)\n#=\nNote that **force is not affected** by a change in angle, since only depth\nof the centroid matters.\n=#\nyc = Length(hc/sin(Θ))\nyR = Length(Ixc/(yc*A) + yc)\nyR - yc\n\n#=\nSo the center of pressure is a little further now from the centroid than\nwhen it was at 60 degrees.\n\nThe moment:\n=#\nMR = Moment((yR - yc)*FR)\n\n#=\nSo **moment gets larger as the surface becomes more vertical**. This is because the\ncenter of pressure has moved away from the centroid. This is intuitive if you\nthink about the other extreme: a completely horizontal surface. In that situation,\nthe pressure acts uniformly across the plate, so there is **zero net moment**\non a horizontal surface.\n=#\n", "meta": {"hexsha": "a04ffabbeb44ba4e3487a1b3f2034e05b416e39f", "size": 3705, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/literate/2.2-SubmergedSurfaces.jl", "max_stars_repo_name": "jdeldre/MAE103", "max_stars_repo_head_hexsha": "1417d573636e7e88fc0dce795073b8f0a82634f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/literate/2.2-SubmergedSurfaces.jl", "max_issues_repo_name": "jdeldre/MAE103", "max_issues_repo_head_hexsha": "1417d573636e7e88fc0dce795073b8f0a82634f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-04-03T22:18:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-03T22:18:15.000Z", "max_forks_repo_path": "test/literate/2.2-SubmergedSurfaces.jl", "max_forks_repo_name": "jdeldre/MAE103", "max_forks_repo_head_hexsha": "1417d573636e7e88fc0dce795073b8f0a82634f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.847826087, "max_line_length": 97, "alphanum_fraction": 0.7190283401, "num_tokens": 1039, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242073, "lm_q2_score": 0.8824278757303677, "lm_q1q2_score": 0.8183312176934151}} {"text": "import Distributions: quantile, Normal\n\n\"\"\"\n```julia\np₁ = binom_confidence(n::Int,c::Real)\n```\nReturns the probability `p₁` of successes in the binomial distribution (p=1/2) of\n`n` trials with confidence `c`.\n\n# Example\nAt c=0.95, i.e. 95% confidence, n=1000 tosses of \na coin will yield not more than\n```julia\njulia> p₁ = BitInformation.binom_confidence(1000,0.95)\n0.5309897516152281\n```\nabout 53.1% heads (or tails).\"\"\"\nfunction binom_confidence(n::Int,c::Real)\n return 0.5 + quantile(Normal(),1-(1-c)/2)/(2*sqrt(n))\nend\n\n\"\"\"\n```julia\nHf = binom_free_entropy(n::Int,c::Real,base::Real=2)\n```\nReturns the free entropy `Hf` associated with `binom_confidence`.\"\"\"\nfunction binom_free_entropy(n::Int,c::Real,base::Real=2)\n p = binom_confidence(n,c)\n return 1 - entropy([p,1-p],base)\nend", "meta": {"hexsha": "e455e72d6ec9252213a8a023f2f0450723fa969f", "size": 793, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/binomial.jl", "max_stars_repo_name": "esowc/BitInformation.jl", "max_stars_repo_head_hexsha": "ba587d9565864139af18e9ae68b189e98586514f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-04-16T20:43:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T20:36:23.000Z", "max_issues_repo_path": "src/binomial.jl", "max_issues_repo_name": "esowc/BitInformation.jl", "max_issues_repo_head_hexsha": "ba587d9565864139af18e9ae68b189e98586514f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2021-04-13T16:06:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:39:57.000Z", "max_forks_repo_path": "src/binomial.jl", "max_forks_repo_name": "esowc/BitInformation.jl", "max_forks_repo_head_hexsha": "ba587d9565864139af18e9ae68b189e98586514f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-17T03:28:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-17T03:28:55.000Z", "avg_line_length": 26.4333333333, "max_line_length": 81, "alphanum_fraction": 0.6973518285, "num_tokens": 268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9458012762876286, "lm_q2_score": 0.865224084314688, "lm_q1q2_score": 0.8183300432196267}} {"text": "function fixpnt(δ=1e-3, x0=1.0)\n x = x0\n iter = 0\n while true\n iter += 1\n x0 = x\n x = atan(2x0)\n if abs(x-x0) ≤ δ\n println(\"Terminating after $iter iterations, x = $x\")\n return\n end\n end\nend\n\nfixpnt()\n\nfixpnt(1e-10)\n\nfixpnt(1e-10, 0.1)\n\nfunction fixpnt2(δ=1e-3, x0=1.0; maxiter=10)\n x = x0\n iter = 0\n while true\n iter += 1\n x0 = x\n x = atan(2x0)\n if iter ≥ maxiter || abs(x-x0) ≤ δ\n println(\"Terminating after $iter iterations, x = $x\")\n return\n end\n end\nend\n\nfixpnt2(1e-10, maxiter=15)\n", "meta": {"hexsha": "30b7d8e817d7b18e50c11c6e5967d8955ac1da4e", "size": 625, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "textbook/_build/jupyter_execute/content/Introduction/Function_Arguments.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/Function_Arguments.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/Function_Arguments.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": 17.3611111111, "max_line_length": 65, "alphanum_fraction": 0.488, "num_tokens": 237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.9073122119620788, "lm_q1q2_score": 0.8183236440363515}} {"text": "\nusing SpecialFunctions: gamma\n\n\"\nEvaluate Jacobi polynomial of type \n(alpha, beta) > -1, (alpha+beta != -1)\nat points x for order N. Returns array of values, same length as x\n\nSee: https://en.wikipedia.org/wiki/Jacobi_polynomials\n\nNOTE: This calculates the normalised Jacobi polynomial\n\n\"\nfunction JacobiP(x, alpha, beta, N::Int)\n\n nvalues = length(x)\n \n PL = zeros(Float64, nvalues, N+1)\n\n gamma0 = 2^(alpha+beta+1)/(alpha+beta+1) * gamma(alpha+1) * gamma(beta+1)/gamma(alpha+beta+1)\n PL[:,1] .= 1.0 / sqrt(gamma0)\n \n if N == 0\n return PL[:,1]\n end\n\n gamma1 = (alpha+1)*(beta+1)/(alpha+beta+3)*gamma0\n PL[:,2] = ((alpha+beta+2)*x/2 .+ (alpha-beta)/2)/sqrt(gamma1)\n\n if N == 1\n return PL[:,2]\n end\n\n aold = 2/(2+alpha+beta)*sqrt((alpha+1)*(beta+1)/(alpha+beta+3))\n\n # Forward recurrence\n for i = 1:(N-1)\n h1 = 2*i + alpha + beta\n anew = 2/(h1+2)*sqrt( (i+1)*(i+1+alpha+beta)*(i+1+alpha)*(i+1+beta)/(h1+1)/(h1+3))\n bnew = - (alpha^2 - beta^2)/h1/(h1+2)\n PL[:,i+2] = (1/anew)*(-aold * PL[:,i] + (x .- bnew) .* PL[:,i+1])\n aold = anew\n end\n return PL[:,end]\nend\n\n\"Evaluate the derivative of the Jacobi polynomial\nof type (alpha,beta) > -1 at points r for order N\n\n## Returns\narray of the same length as r\n\"\nfunction GradJacobiP(r, alpha, beta, N::Int)\n if N == 0\n zeros(length(r))\n else\n sqrt(N * (N+alpha+beta+1))*JacobiP(r, alpha+1, beta+1, N-1)\n end\nend\n\nstruct JacobiBasis1D\n order::Int # Number of polynomials\nend\n\nfunction basisFunction(basis::JacobiBasis1D, locations, index::Int)\n JacobiP(locations, 0, 0, index-1)\nend\n\nfunction basisGradient(basis::JacobiBasis1D, locations, index::Int)\n GradJacobiP(locations,0,0,index-1)\nend\n", "meta": {"hexsha": "8a69eda168b9bb1bbb03b5309669407435b2299e", "size": 1767, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/jacobi-basis.jl", "max_stars_repo_name": "bendudson/NodalDG.jl", "max_stars_repo_head_hexsha": "5dcaebd2e7678914bca3525f1ff3bb9beef0a825", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-03-05T15:27:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T15:34:58.000Z", "max_issues_repo_path": "src/jacobi-basis.jl", "max_issues_repo_name": "bendudson/NodalDG.jl", "max_issues_repo_head_hexsha": "5dcaebd2e7678914bca3525f1ff3bb9beef0a825", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/jacobi-basis.jl", "max_forks_repo_name": "bendudson/NodalDG.jl", "max_forks_repo_head_hexsha": "5dcaebd2e7678914bca3525f1ff3bb9beef0a825", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-03-05T15:27:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-21T16:08:03.000Z", "avg_line_length": 24.5416666667, "max_line_length": 97, "alphanum_fraction": 0.6078098472, "num_tokens": 625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632316144274, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.8182823207956581}} {"text": "# p4.jl - periodic spectral differentiation\n\n# Set up grid and differentiation matrix:\nN = 24; h = 2*pi/N; x = h*(1:N);\ncolumn = [0; @. .5*(-1)^(1:N-1)*cot((1:N-1)*h/2)];\nD = toeplitz(column,column[[1;N:-1:2]]);\n\n# Differentiation of a hat function:\nv = @. max(0,1-abs(x-pi)/2); clf();\nsubplot(2,2,1); plot(x,v,\".-\",markersize=6);\naxis([0,2pi,-.5,1.5]); grid(true); title(\"function\");\nsubplot(2,2,2), plot(x,D*v,\".-\",markersize=6);\naxis([0,2pi,-1,1]); grid(true); title(\"spectral derivative\");\n\n# Differentiation of exp(sin(x)):\nv = @. exp(sin(x)); vprime = @. cos(x)*v;\nsubplot(2,2,3), plot(x,v,\".-\",markersize=6);\naxis([0,2pi,0,3]), grid(true);\nsubplot(2,2,4), plot(x,D*v,\".-\",markersize=6);\naxis([0,2pi,-2,2]), grid(true);\nerror = signif(norm(D*v-vprime,Inf),5);\ntext(2.2,1.4,\"max error = $error\",fontsize=8);\n", "meta": {"hexsha": "2b2e449f0c5f372c06fafe837fbf34193dcb2e2b", "size": 814, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/scripts/p4.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/p4.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/p4.jl", "max_forks_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_forks_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3913043478, "max_line_length": 61, "alphanum_fraction": 0.6007371007, "num_tokens": 317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632275178339, "lm_q2_score": 0.8596637469145054, "lm_q1q2_score": 0.8182823087181155}} {"text": "\n#= Fornberg algorithm\n\nImplements the Fornberg (1988) algorithm\n(https://doi.org/10.1090/S0025-5718-1988-0935077-0), adapted from the\nDiffEqOperators module.\n=#\n\"\"\"\n calculate_weights(m, n, s)\n\nReturn finite difference weights. Notation follows that of Fornberg, used in\nMathematica as well:\nhttps://reference.wolfram.com/language/tutorial/NDSolveMethodOfLines.html\n\n# Arguments\n* `m::Int`: order of the derivative\n* `n::Int`: number of grid intervals enclosed in the stencil\n* `s::Int`: number of grid intervals between the point at which the derivative\n is approximated and the leftmost edge of the stencil. centred\n formulas always have s=n/2.\n\"\"\"\nfunction calculate_weights(m::Int, n::Int, s::Int)\n stencil_length = n + 1\n\n # dummy array with the relative coordinates of the stencil (eg. central\n # differences need coordinates centred at 0)\n x = -s : (stencil_length - s - 1)\n # point in the array 'x' for which we need the coefficients\n x0 = x[1] + s\n\n N = length(x)\n @assert m < N \"Not enough points for the requested order.\"\n\n c1 = 1\n c4 = x[1] - x0\n C = zeros(Rational{Int}, N, m+1)\n C[1,1] = 1\n @inbounds for i in 1:N-1\n i1 = i + 1\n mn = Base.min(i, m)\n c2 = 1\n c5 = c4\n c4 = x[i1] - x0\n for j in 0:i-1\n j1 = j + 1\n c3 = x[i1] - x[j1]\n c2 *= c3\n if j == i-1\n for s in mn:-1:1\n s1 = s + 1\n C[i1,s1] = c1*(s*C[i,s] - c5*C[i,s1]) // c2\n end\n C[i1,1] = -c1*c5*C[i,1] // c2\n end\n for s in mn:-1:1\n s1 = s + 1\n C[j1,s1] = (c4*C[j1,s1] - s*C[j1,s]) // c3\n end\n C[j1,1] = c4 * C[j1,1] // c3\n end\n c1 = c2\n end\n\n #=\n Fix the problem of numerical instability which occurs when the sum of the\n stencil_coefficients is not exactly 0:\nhttps://scicomp.stackexchange.com/questions/11249/numerical-derivative-and-finite-difference-coefficients-any-update-of-the-fornb\n\n Stack Overflow answer on this issue:\n http://epubs.siam.org/doi/pdf/10.1137/S0036144596322507 - Modified Fornberg Algorithm\n =#\n\n _C = C[:,end]\n _C[div(N,2)+1] -= sum(_C)\n return _C\nend\n", "meta": {"hexsha": "9e6f850f101fa3387592c94f5339ecf235a7e47c", "size": 2302, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/fornberg.jl", "max_stars_repo_name": "Mikel-Sanchez-Garitaonandia/Jecco.jl", "max_stars_repo_head_hexsha": "d1e030ed0e3534c6bbb7aeaba4e3904fc59a3c35", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-09-08T23:37:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T06:19:01.000Z", "max_issues_repo_path": "src/fornberg.jl", "max_issues_repo_name": "Mikel-Sanchez-Garitaonandia/Jecco.jl", "max_issues_repo_head_hexsha": "d1e030ed0e3534c6bbb7aeaba4e3904fc59a3c35", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-12-02T17:57:23.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-02T17:57:23.000Z", "max_forks_repo_path": "src/fornberg.jl", "max_forks_repo_name": "Mikel-Sanchez-Garitaonandia/Jecco.jl", "max_forks_repo_head_hexsha": "d1e030ed0e3534c6bbb7aeaba4e3904fc59a3c35", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-02-26T15:37:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T08:46:55.000Z", "avg_line_length": 29.8961038961, "max_line_length": 129, "alphanum_fraction": 0.5725456125, "num_tokens": 737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603708, "lm_q2_score": 0.8774767986961403, "lm_q1q2_score": 0.8182061443924215}} {"text": "# Wilkinson-type polynomial defined by its roots:\n# wₙ(x) = (x-1)⋅(x-2)⋅ ⋯ ⋅ (x-n)\n\nusing Polynomials\n\n\n# function generate_wilkinson(n)#, T=BigFloat) # SLOW\n\n# p = poly(collect(1:n))\n# p_prime = polyder(p)\n\n# coeffs = p.a #[convert(T, coeff) for coeff in p.a]\n# # coeffs_prime = [convert(T, coeff) for coeff in p_prime.a]\n\n# function f(x)\n# total = coeffs[1]\n# for i in 2:length(coeffs)\n# total += coeffs[i]*x^(i-1)\n# end\n# total\n# end\n\n# f\n# end\n\nfunction generate_wilkinson_horner(n)\n p = poly(collect(1:n)) # make polynomial with roots 1 to n\n\n coeffs = p.a\n\n expr = :($(coeffs[end]))\n\n for i in length(coeffs)-1:-1:1\n expr = :($expr*x + $(coeffs[i]))\n end\n\n expr\nend\n\nfunction subscriptify(n::Int)\n subscript_digits = [c for c in \"₀₁₂₃₄₅₆₇₈₉\"]\n dig = reverse(digits(n))\n join([subscript_digits[i+1] for i in dig])\nend\n\n# Generate Wilkinson functions W₃ etc.:\nfor n in 1:15\n fn_name = symbol(string(\"W\", subscriptify(n)))\n expr = generate_wilkinson_horner(n)\n\n @eval $(fn_name)(x) = $(expr)\nend\n\n", "meta": {"hexsha": "dfdcf9a30f1344269283dc4e23fcd74283dffb3a", "size": 1118, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/root_finding_tests/wilkinson.jl", "max_stars_repo_name": "JuliaPackageMirrors/ValidatedNumerics.jl", "max_stars_repo_head_hexsha": "7fe2f72987aa676986e6d1bf5416a595438cdeff", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/root_finding_tests/wilkinson.jl", "max_issues_repo_name": "JuliaPackageMirrors/ValidatedNumerics.jl", "max_issues_repo_head_hexsha": "7fe2f72987aa676986e6d1bf5416a595438cdeff", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/root_finding_tests/wilkinson.jl", "max_forks_repo_name": "JuliaPackageMirrors/ValidatedNumerics.jl", "max_forks_repo_head_hexsha": "7fe2f72987aa676986e6d1bf5416a595438cdeff", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.7037037037, "max_line_length": 65, "alphanum_fraction": 0.5849731664, "num_tokens": 373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.8774767970940975, "lm_q1q2_score": 0.8182061428985915}} {"text": "#===============================================================================\n\nA row of five black square tiles is to have a number of its tiles replaced with\ncoloured oblong tiles chosen from red (length two), green (length three), or\nblue (length four).\n\nIf red tiles are chosen there are exactly seven ways this can be done. If green\ntiles are chosen there are three ways. And if blue tiles are chosen there are\ntwo ways.Assuming that colours cannot be mixed there are 7 + 3 + 2 = 12 ways of\nreplacing the black tiles in a row measuring five units in length.\n\nHow many different ways can the black tiles in a row measuring fifty units in\nlength be replaced if colours cannot be mixed and at least one coloured tile\nmust be used\n\n===============================================================================#\n\nusing Memoize\nusing Base.Test\n\n@memoize function ncases_swb(blocklen, rowlen)\n # Return the number of cases _s_tarting _w_ith a _b_lock\n\n if rowlen < blocklen\n return 0\n end\n\n result = 1\n # case for which there is only one block\n\n rowlen -= blocklen\n # remove room taken by the first block\n\n for nspace = 0:rowlen-blocklen\n # nbr spaces allowed between first block and second one\n\n result += ncases_swb(blocklen, rowlen-nspace)\n end\n\n result\nend\n\nfunction ncases(blocklen, rowlen)\n result = 0\n for nspace = 0:rowlen-blocklen\n # nbr spaces before first block\n result += ncases_swb(blocklen, rowlen-nspace)\n end\n\n result\nend\n\nfunction euler(rowlen)\n ncases(2, rowlen) + ncases(3, rowlen) + ncases(4, rowlen)\nend\n\n@test ncases(2, 5) == 7\n@test ncases(3, 5) == 3\n@test ncases(4, 5) == 2\n@test euler(5) == 12\n\n@printf(\"Euler 0116: %d\", euler(50))\n", "meta": {"hexsha": "5f12160c9488270379b96e6052a703b8a6db100a", "size": 1739, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "0116.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": "0116.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": "0116.jl", "max_forks_repo_name": "dpieroux/euler", "max_forks_repo_head_hexsha": "d9e7d39d93e588402cc13efcf2eddb0371540160", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6031746032, "max_line_length": 80, "alphanum_fraction": 0.6388729155, "num_tokens": 457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.8774767794716264, "lm_q1q2_score": 0.8182061264664601}} {"text": "\"\"\"\n lsnormal(A,b)\n\nSolve a linear least squares problem by the normal equations.\nReturns the minimizer of ||b-Ax||.\n\"\"\"\nfunction lsnormal(A,b)\n N = A'*A; z = A'*b;\n R = cholesky(N).U\n w = forwardsub(R',z) # solve R'z=c\n x = backsub(R,w) # solve Rx=z\n return x\nend\n\n\n\"\"\"\n lsqrfact(A,b)\n\nSolve a linear least squares problem by QR factorization. Returns\nthe minimizer of ||b-Ax||.\n\"\"\"\nfunction lsqrfact(A,b)\n Q,R = qr(A)\n c = Q'*b\n x = backsub(R,c)\n return x\nend\n\n\"\"\"\n qrfact(A)\n\nQR factorization by Householder reflections. Returns Q and R.\n\"\"\"\nfunction qrfact(A)\n m,n = size(A)\n Qt = diagm(ones(m))\n R = float(copy(A))\n for k in 1:n\n z = R[k:m,k]\n w = [ -sign(z[1])*norm(z) - z[1]; -z[2:end] ]\n nrmw = norm(w)\n if nrmw < eps() continue; end # skip this iteration\n v = w / nrmw;\n # Apply the reflection to each relevant column of R and Q\n for j in k:n\n R[k:m,j] -= v*( 2*(v'*R[k:m,j]) )\n end\n for j in 1:m\n Qt[k:m,j] -= v*( 2*(v'*Qt[k:m,j]) )\n end\n end\n return Qt',triu(R)\nend\n", "meta": {"hexsha": "463e67727ff969c1bbadf4aad7f2e3c5e3b4e0f4", "size": 1167, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chapter03.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/chapter03.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/chapter03.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": 21.6111111111, "max_line_length": 65, "alphanum_fraction": 0.5089974293, "num_tokens": 381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611620335328, "lm_q2_score": 0.8519528000888386, "lm_q1q2_score": 0.8181823810910391}} {"text": "\"\"\"\n non_relativistic_orbital(n, ℓ[, Z = 1])\n\nReturns a callable object to evaluate the _reduced_ radial orbital ``P_{nℓ}(r)`` of a\nhydrogen-like atom in non-relativistic theory, given by\n\n```math\nP_{nℓ}(r) =\n\\\\sqrt{\n \\\\left(\\\\frac{2Z}{n}\\\\right)^3\n \\\\frac{(n-\\\\ell-1)!}{2n(n+\\\\ell)!}\n}\n\\\\left(\\\\frac{2Z}{n} \\\\cdot r\\\\right)^\\\\ell\nL^{(2\\\\ell+1)}_{n-\\\\ell-1}\\\\left(\\\\frac{2Z}{n} \\\\cdot r\\\\right)\n\\\\exp\\\\left(-\\\\frac{Z}{n} \\\\cdot r\\\\right)\n```\n\n``P_{nℓ}(r)`` is defined through\n\n```math\n\\\\psi_{nlm}(r,\\\\theta,\\\\varphi) = \\\\frac{1}{r} P_{nℓ}(r) Y_{ℓm}(\\\\theta,\\\\varphi)\n```\n\nwhere ``\\\\psi_{nlm}`` are the normalized solutions to the non-relativistic single-particle\nSchrödinger equation for a point-like nucleus with charge `Z`, and where ``Y_{ℓm}`` are the\nspherical harmonics.\n\"\"\"\nfunction non_relativistic_orbital(n::Integer, ℓ::Integer, Z = 1)\n n > 0 || throw(ArgumentError(\"Invalid n = $n, must be n ≥ 1\"))\n 0 ≤ ℓ < n || throw(ArgumentError(\"Invalid ℓ = $ℓ for n = $n, must be 0 ≤ ℓ < n\"))\n # Normalization factor.\n # Note: n! = Γ(n+1), so (n-ℓ-1)!/(2n(n+ℓ)!) = Γ(n+1)/(2nΓ(n+ℓ+1))\n N = sqrt((2Z/n)^3*gamma(n-ℓ)/(2n*gamma(n+ℓ+1)))\n # Generalized Laguerre polynomial L^{(2ℓ+1)}_{n-ℓ-1}(q), where q = 2Zr/n:\n L = convert(Polynomial, Laguerre{2ℓ+1}([zeros(n-ℓ-1); 1], :q))\n # Single Polynomial object for the polynomial part, multiplied by r to get the\n # reduced polynomial:\n C = let r = Polynomial([0, 1], :r)\n N * (2*Z*r/n)^ℓ * L(2*Z*r/n) * r\n end\n # Multiply with the exponential exp(Zr/n) and return a callable object:\n q = -Z/n # pre-compute the coefficient in the exponential\n r -> C(r) * exp(q*r)\nend\n\nexport non_relativistic_orbital\n", "meta": {"hexsha": "0e1bc814b30ab2b43f8df3d4d8d2d7d1461582fa", "size": 1699, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/orbitals.jl", "max_stars_repo_name": "JuliaAtoms/Hydrogen.jl", "max_stars_repo_head_hexsha": "b92a18f86d42bbf60990960339748dc95d6ec655", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/orbitals.jl", "max_issues_repo_name": "JuliaAtoms/Hydrogen.jl", "max_issues_repo_head_hexsha": "b92a18f86d42bbf60990960339748dc95d6ec655", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-05-28T00:44:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-26T10:40:30.000Z", "max_forks_repo_path": "src/orbitals.jl", "max_forks_repo_name": "JuliaAtoms/Hydrogen.jl", "max_forks_repo_head_hexsha": "b92a18f86d42bbf60990960339748dc95d6ec655", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-16T01:57:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-16T01:57:06.000Z", "avg_line_length": 36.1489361702, "max_line_length": 91, "alphanum_fraction": 0.6080047087, "num_tokens": 660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.95598134762883, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.8181777346048742}} {"text": "module ModuleB\n\nusing LinearAlgebra\n\nexport myPower, myDeflation, myPowerMethod, myTridiag, myTridiagX, myTridiagG, myTridEigQR,\nmySymEigQR, stedc!, myJacobi, myLanczos, myBidiagX, myBidiagY, myBidiagG, myJacobiR\n\nfunction myPower(A::Matrix,x::Vector,tol::Real)\n y=A*x\n ν=x⋅y\n steps=1\n while norm(y-ν*x)>tol\n x=y/norm(y)\n y=A*x\n ν=x⋅y\n steps+=1\n end\n ν, y/norm(y), steps\nend\n\nfunction myDeflation(A::Matrix,x::Vector)\n X,R=qr(x[:,:])\n # To make sure the returned matrix symmetric use\n # full(Symmetric(X[:,2:end]'*A*X[:,2:end]))\n X[:,2:end]'*A*X[:,2:end]\nend\n\nfunction myPowerMethod(A::Matrix{T}, tol::Real) where T\n n=size(A,1)\n S = T==Int ? Float64 : T\n λ=Vector{S}(undef,n)\n for i=1:n\n λ[i],x,steps=myPower(A,ones(n-i+1),tol)\n A=myDeflation(A,x)\n end\n λ\nend\n\nfunction myTridiag(A::Matrix)\n # Normalized Householder vectors are stored in the lower \n # triangular part of A below the first subdiagonal\n n=size(A,1)\n T=Float64\n A=map(T,A)\n v=Vector{T}(undef,n)\n Trid=SymTridiagonal(zeros(n),zeros(n-1))\n for j = 1 : n-2\n μ = sign(A[j+1,j])*norm(A[j+1:n, j])\n if μ != zero(T)\n β =A[j+1,j]+μ\n v[j+2:n] = A[j+2:n,j] / β\n end\n A[j+1,j]=-μ\n A[j,j+1]=-μ\n v[j+1] = one(T)\n γ = -2 / (v[j+1:n]⋅v[j+1:n])\n w = γ* A[j+1:n, j+1:n]*v[j+1:n]\n q = w + γ * v[j+1:n]*(v[j+1:n]⋅w) / 2 \n A[j+1:n, j+1:n] = A[j+1:n,j+1:n] + v[j+1:n]*q' + q*v[j+1:n]'\n A[j+2:n, j] = v[j+2:n]\n end\n SymTridiagonal(diag(A),diag(A,1)), tril(A,-2)\nend\n\n# Extract X\nfunction myTridiagX(H::Matrix)\n n=size(H,1)\n T=Float64\n X = Matrix{T}(I,n,n)\n v=Vector{T}(undef,n)\n for j = n-2 : -1 : 1\n v[j+1] = one(T)\n v[j+2:n] = H[j+2:n, j]\n γ = -2 / (v[j+1:n]⋅v[j+1:n])\n w = γ * X[j+1:n, j+1:n]'*v[j+1:n]\n X[j+1:n, j+1:n] = X[j+1:n, j+1:n] + v[j+1:n]*w'\n end\n X\nend\n\n# Tridiagonalization using Givens rotations\nfunction myTridiagG(A::Matrix)\n n=size(A,1)\n T=Float64\n X=Matrix{T}(I,n,n)\n for j = 1 : n-2\n for i = j+2 : n\n G,r=givens(A,j+1,i,j)\n A=(G*A)*G'\n X*=G'\n end\n end\n SymTridiagonal(diag(A),diag(A,1)), X\nend\n\nfunction myTridEigQR(A1::SymTridiagonal)\n A=deepcopy(A1)\n n=length(A.dv)\n T=Float64\n λ=Vector{T}(undef,n)\n B=Matrix{T}\n if n==1\n return map(T,A.dv)\n end\n if n==2\n τ=(A.dv[end-1]-A.dv[end])/2\n μ=A.dv[end]-A.ev[end]^2/(τ+sign(τ)*sqrt(τ^2+A.ev[end]^2))\n # Only rotation\n B=A[1:2,1:2]\n G,r=givens(B-μ*I,1,2,1)\n B=(G*B)*G'\n return diag(B)[1:2]\n end\n steps=1\n k=0\n while k==0 && steps<=10\n # Shift\n τ=(A.dv[end-1]-A.dv[end])/2\n μ=A.dv[end]-A.ev[end]^2/(τ+sign(τ)*sqrt(τ^2+A.ev[end]^2))\n # First rotation\n B=A[1:3,1:3]\n G,r=givens(B-μ*I,1,2,1)\n B=(G*B)*G'\n A.dv[1:2]=diag(B)[1:2]\n A.ev[1:2]=diag(B,-1)\n bulge=B[3,1]\n # Bulge chasing\n for i = 2 : n-2\n B=A[i-1:i+2,i-1:i+2]\n B[3,1]=bulge\n B[1,3]=bulge\n G,r=givens(B,2,3,1)\n B=(G*B)*G'\n A.dv[i:i+1]=diag(B)[2:3]\n A.ev[i-1:i+1]=diag(B,-1)\n bulge=B[4,2]\n end\n # Last rotation\n B=A[n-2:n,n-2:n]\n B[3,1]=bulge\n B[1,3]=bulge\n G,r=givens(B,2,3,1)\n B=(G*B)*G'\n A.dv[n-1:n]=diag(B)[2:3]\n A.ev[n-2:n-1]=diag(B,-1)\n steps+=1\n # Deflation criterion\n k=findfirst(abs.(A.ev) .< sqrt.(abs.(A.dv[1:n-1].*A.dv[2:n]))*eps(T))\n k=k==nothing ? 0 : k\n end\n λ[1:k]=myTridEigQR(SymTridiagonal(A.dv[1:k],A.ev[1:k-1]))\n λ[k+1:n]=myTridEigQR(SymTridiagonal(A.dv[k+1:n],A.ev[k+1:n-1]))\n λ\nend\n\nfunction myTridEigQR(A1::SymTridiagonal,U::Matrix)\n # U is either the identity matrix or the output from myTridiagX()\n A=deepcopy(A1)\n n=length(A.dv)\n T=Float64\n λ=Vector{T}(undef,n)\n B=Matrix{T}\n if n==1\n return map(T,A.dv), U\n end\n if n==2\n τ=(A.dv[end-1]-A.dv[end])/2\n μ=A.dv[end]-A.ev[end]^2/(τ+sign(τ)*sqrt(τ^2+A.ev[end]^2))\n # Only rotation\n B=A[1:2,1:2]\n G,r=givens(B-μ*I,1,2,1)\n B=(G*B)*G'\n U*=G'\n return diag(B)[1:2], U\n end\n steps=1\n k=0\n while k==0 && steps<=10\n # Shift\n τ=(A.dv[end-1]-A.dv[end])/2\n μ=A.dv[end]-A.ev[end]^2/(τ+sign(τ)*sqrt(τ^2+A.ev[end]^2))\n # First rotation\n B=A[1:3,1:3]\n G,r=givens(B-μ*I,1,2,1)\n B=(G*B)*G'\n U[:,1:3]*=G'\n A.dv[1:2]=diag(B)[1:2]\n A.ev[1:2]=diag(B,-1)\n bulge=B[3,1]\n # Bulge chasing\n for i = 2 : n-2\n B=A[i-1:i+2,i-1:i+2]\n B[3,1]=bulge\n B[1,3]=bulge\n G,r=givens(B,2,3,1)\n B=(G*B)*G'\n U[:,i-1:i+2]=U[:,i-1:i+2]*G'\n A.dv[i:i+1]=diag(B)[2:3]\n A.ev[i-1:i+1]=diag(B,-1)\n bulge=B[4,2]\n end\n # Last rotation\n B=A[n-2:n,n-2:n]\n B[3,1]=bulge\n B[1,3]=bulge\n G,r=givens(B,2,3,1)\n B=(G*B)*G'\n U[:,n-2:n]*=G'\n A.dv[n-1:n]=diag(B)[2:3]\n A.ev[n-2:n-1]=diag(B,-1)\n steps+=1\n # Deflation criterion\n k=findfirst(abs.(A.ev) .< sqrt.(abs.(A.dv[1:n-1].*A.dv[2:n]))*eps())\n k=k==nothing ? 0 : k\n end\n λ[1:k], U[:,1:k]=myTridEigQR(SymTridiagonal(A.dv[1:k],A.ev[1:k-1]),U[:,1:k])\n λ[k+1:n], U[:,k+1:n]=myTridEigQR(SymTridiagonal(A.dv[k+1:n],A.ev[k+1:n-1]),U[:,k+1:n])\n λ, U\nend\n\nfunction mySymEigQR(A::Matrix)\n T,H=myTridiag(A)\n X=myTridiagX(H)\n myTridEigQR(T,X)\nend\n\n### DSTEDC\n# Part of the preamble of lapack.jl\nconst liblapack = Base.liblapack_name\nimport LinearAlgebra.BLAS.@blasfunc\n# import ..LinAlg: BlasFloat, Char, BlasInt, LAPACKException,\n # DimensionMismatch, SingularException, PosDefException, chkstride1, chksquare\nimport LinearAlgebra.BlasInt\nfunction chklapackerror(ret::BlasInt)\n if ret == 0\n return\n elseif ret < 0\n throw(ArgumentError(\"invalid argument #$(-ret) to LAPACK call\"))\n else # ret > 0\n throw(LAPACKException(ret))\n end\nend\n\nfor (stedc, elty) in\n ((:dstedc_,:Float64),\n (:sstedc_,:Float32))\n @eval begin\n \"\"\"\n COMPZ is CHARACTER*1\n = 'N': Compute eigenvalues only.\n = 'I': Compute eigenvectors of tridiagonal matrix also.\n = 'V': Compute eigenvectors of original dense symmetric\n matrix also. On entry, Z contains the orthogonal\n matrix used to reduce the original matrix to\n tridiagonal form.\n \"\"\"\n function stedc!(compz::Char, dv::Vector{$elty}, ev::Vector{$elty}, \n Z::Array{$elty})\n n = length(dv)\n ldz=n\n if length(ev) != n - 1\n throw(DimensionMismatch(\"ev has length $(length(ev)) \n but needs one less than dv's length, $n)\"))\n end\n w = deepcopy(dv)\n u = deepcopy(ev)\n lwork=5*n^2\n work = Array{$elty}(undef,lwork)\n liwork=6+6*n+5*n*round(Int,ceil(log(n)/log(2)))\n iwork = Array{BlasInt}(undef,liwork)\n # info = Array{BlasInt}(undef,5)\n info = Ref{BlasInt}()\n ccall((@blasfunc($stedc), liblapack), Cvoid,\n (Ref{UInt8}, Ref{BlasInt}, Ptr{$elty},\n Ptr{$elty}, Ptr{$elty}, Ref{BlasInt}, Ptr{$elty}, \n Ref{BlasInt}, Ptr{BlasInt}, Ref{BlasInt}, \n Ptr{BlasInt}), compz, n, w, u, Z, ldz, work, \n lwork, iwork, liwork, info) \n chklapackerror(info[])\n return w,Z\n end\n end\nend\n\nfunction myJacobi(A1::Array{T}) where T<:Real\n A=deepcopy(A1)\n n=size(A,1)\n U=Matrix{T}(I,n,n)\n # Tolerance for rotation\n tol=sqrt(map(T,n))*eps(T)\n # Counters\n p=n*(n-1)/2\n sweep=0\n pcurrent=0\n # First criterion is for standard accuracy, second one is for relative accuracy\n # while sweep<30 && vecnorm(A-diagm(diag(A)))>tol\n while sweep<30 && pcurrenttol*sqrt(abs(A[i,i]*A[j,j]))\n # Compute c and s\n τ=(A[i,i]-A[j,j])/(2*A[i,j])\n t=sign(τ)/(abs(τ)+sqrt(1+τ^2))\n c=1/sqrt(1+t^2)\n s=c*t\n G=LinearAlgebra.Givens(i,j,c,s)\n # A=G*A\n lmul!(G,A)\n # A*=G'\n rmul!(A,adjoint(G))\n A[i,j]=zero(T)\n A[j,i]=zero(T)\n # U*=G'\n rmul!(U,adjoint(G))\n pcurrent=0\n else\n pcurrent+=1\n end\n end\n end\n end\n diag(A), U\nend\n\nfunction myLanczos(A::Array{T}, x::Vector{T}, k::Int) where T\n n=size(A,1)\n X=Array{T}(undef,n,k)\n dv=Array{T}(undef,k)\n ev=Array{T}(undef,k-1)\n X[:,1]=x/norm(x)\n for i=1:k-1\n z=A*X[:,i]\n dv[i]=X[:,i]⋅z\n # Three-term recursion\n if i==1\n z=z-dv[i]*X[:,i]\n else\n # z=z-dv[i]*X[:,i]-ev[i-1]*X[:,i-1]\n # Full reorthogonalization - once or even twice\n z=z-sum([(z⋅X[:,j])*X[:,j] for j=1:i])\n z=z-sum([(z⋅X[:,j])*X[:,j] for j=1:i])\n end\n μ=norm(z)\n if μ==0\n Tr=SymTridiagonal(dv[1:i-1],ev[1:i-2])\n return eigvals(Tr), X[:,1:i-1]*eigvecs(Tr), X[:,1:i-1], μ\n else\n ev[i]=μ\n X[:,i+1]=z/μ\n end\n end\n # Last step\n z=A*X[:,end]\n dv[end]=X[:,end]⋅z\n z=z-dv[end]*X[:,end]-ev[end]*X[:,end-1]\n μ=norm(z)\n Tr=SymTridiagonal(dv,ev)\n eigvals(Tr), X*eigvecs(Tr), X, μ\nend\n\n# Extract X\nfunction myBidiagX(H::Matrix)\n m,n=size(H)\n T=typeof(H[1,1])\n X = Matrix{T}(I,m,n)\n v = Array{T}(undef,m)\n for j = n : -1 : 1\n v[j] = one(T)\n v[j+1:m] = H[j+1:m, j]\n γ = -2 / (v[j:m]⋅v[j:m])\n w = γ * X[j:m, j:n]'*v[j:m]\n X[j:m, j:n] = X[j:m, j:n] + v[j:m]*w'\n end\n X\nend\n\n# Extract Y\nfunction myBidiagY(H::AbstractMatrix)\n n,m=size(H)\n T=typeof(H[1,1])\n Y = Matrix{T}(I,n,n)\n v = Array{T}(undef,n)\n for j = n-2 : -1 : 1\n v[j+1] = one(T)\n v[j+2:n] = H[j+2:n, j]\n γ = -2 / (v[j+1:n]⋅v[j+1:n])\n w = γ * Y[j+1:n, j+1:n]'*v[j+1:n]\n Y[j+1:n, j+1:n] = Y[j+1:n, j+1:n] + v[j+1:n]*w'\n end\n Y\nend\n\n# Bidiagonalization using Givens rotations\nfunction myBidiagG(A1::Matrix)\n A=deepcopy(A1)\n m,n=size(A)\n T=typeof(A[1,1])\n X=Matrix{T}(I,m,m)\n Y=Matrix{T}(I,n,n)\n for j = 1 : n \n for i = j+1 : m\n G,r=givens(A,j,i,j)\n # Use the faster in-place variant\n # A=G*A\n lmul!(G,A)\n # X=G*X\n lmul!(G,X)\n end\n for i=j+2:n\n G,r=givens(A',j+1,i,j)\n # A*=adjoint(G)\n rmul!(A,adjoint(G))\n # Y*=adjoint(G)\n rmul!(Y,adjoint(G)) \n end\n end\n X',Bidiagonal(diag(A),diag(A,1),'U'), Y\nend\n\nfunction myJacobiR(A1::AbstractMatrix)\n A=deepcopy(A1)\n m,n=size(A)\n T=typeof(A[1,1])\n V=Matrix{T}(I,n,n)\n # Tolerance for rotation\n tol=sqrt(map(T,n))*eps(T)\n # Counters\n p=n*(n-1)/2\n sweep=0\n pcurrent=0\n # First criterion is for standard accuracy, second one is for relative accuracy\n # while sweep<30 && vecnorm(A-diagm(diag(A)))>tol\n while sweep<30 && pcurrenttol*sqrt(F[1,1]*F[2,2])\n # Compute c and s\n τ=(F[1,1]-F[2,2])/(2*F[1,2])\n t=sign(τ)/(abs(τ)+sqrt(1+τ^2))\n c=1/sqrt(1+t^2)\n s=c*t\n G=LinearAlgebra.Givens(i,j,c,s)\n A*=G'\n # rmul!(A,adjoint(G))\n V*=G'\n # rmul!(A,adjoint(G))\n pcurrent=0\n else\n pcurrent+=1\n end\n end\n end\n end\n σ=[norm(A[:,k]) for k=1:n]\n for k=1:n\n A[:,k]./=σ[k]\n end\n A, σ, V\nend\n\nend\n", "meta": {"hexsha": "d11e106062c04f396f55853b88f00619fe93d005", "size": 13127, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Module B - Eigenvalue and Singular Value Decompositions/ModuleB.jl", "max_stars_repo_name": "ivanslapnicar/GIAN-Applied-NLA-Course", "max_stars_repo_head_hexsha": "021628ccc9ade3049e96813108850d3641637aef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2016-06-10T09:40:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T23:00:08.000Z", "max_issues_repo_path": "src/Module B - Eigenvalue and Singular Value Decompositions/ModuleB.jl", "max_issues_repo_name": "ivanslapnicar/GIAN-Applied-NLA-Course", "max_issues_repo_head_hexsha": "021628ccc9ade3049e96813108850d3641637aef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Module B - Eigenvalue and Singular Value Decompositions/ModuleB.jl", "max_forks_repo_name": "ivanslapnicar/GIAN-Applied-NLA-Course", "max_forks_repo_head_hexsha": "021628ccc9ade3049e96813108850d3641637aef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2016-06-21T14:20:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-10T17:03:59.000Z", "avg_line_length": 27.6357894737, "max_line_length": 91, "alphanum_fraction": 0.4604250781, "num_tokens": 4760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693645535724, "lm_q2_score": 0.861538211208597, "lm_q1q2_score": 0.8181764455770898}} {"text": "using VectorSphericalWaves\n\nm, n, kr_r, kr_i, θ, ϕ = 1, 1, 1e6, 1e2, 0.2, 0.3;\nkr = complex(kr_r, kr_i);\n\nM_mn_wave(m, n, kr, θ, ϕ; kind=\"regular\");\nN_mn_wave(m, n, kr, θ, ϕ; kind=\"regular\");\n\n# BigFloat\nm, n, kr_r, kr_i, θ, ϕ = 1, 1, BigFloat(1e6), BigFloat(1e2), BigFloat(0.2), BigFloat(0.3);\nkr = complex(kr_r, kr_i);\n\nM_mn_wave(m, n, kr, θ, ϕ; kind=\"regular\");\nN_mn_wave(m, n, kr, θ, ϕ; kind=\"regular\");\n\n\n# SVector comparison\nm, n, kr_r, kr_i, θ, ϕ = 1, 1, 1e6, 1e2, 0.2, 0.3;\nkr = complex(kr_r, kr_i);\n\nθ_array, ϕ_array = LinRange(0, π, 1000), LinRange(0, π, 1000)\n\nprintln(\"M and N returning Arrays\")\n@time M_mn_wave.(m, n, kr, θ_array, ϕ_array; kind=\"regular\");\n@time N_mn_wave.(m, n, kr, θ_array, ϕ_array; kind=\"regular\");\n\nprintln(\"M and N returning SVector, you should notice the sligth speedup\")\n@time VectorSphericalWaves.M_mn_wave_SVector.(m, n, kr, θ_array, ϕ_array; kind=\"regular\");\n@time VectorSphericalWaves.N_mn_wave_SVector.(m, n, kr, θ_array, ϕ_array; kind=\"regular\");\n\n", "meta": {"hexsha": "0de91f402ee389f95230770e1565a2d0b3250915", "size": 991, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests_complex.jl", "max_stars_repo_name": "alok/VectorSphericalWaves.jl", "max_stars_repo_head_hexsha": "0f0dce5624bd97a560560ae2e4cbc67ae9b4a5bf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/runtests_complex.jl", "max_issues_repo_name": "alok/VectorSphericalWaves.jl", "max_issues_repo_head_hexsha": "0f0dce5624bd97a560560ae2e4cbc67ae9b4a5bf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-05-27T21:02:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-27T21:02:02.000Z", "max_forks_repo_path": "test/runtests_complex.jl", "max_forks_repo_name": "alok/VectorSphericalWaves.jl", "max_forks_repo_head_hexsha": "0f0dce5624bd97a560560ae2e4cbc67ae9b4a5bf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-09T04:56:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-09T04:56:05.000Z", "avg_line_length": 31.9677419355, "max_line_length": 90, "alphanum_fraction": 0.6670030272, "num_tokens": 429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693674025231, "lm_q2_score": 0.86153820232079, "lm_q1q2_score": 0.8181764395910915}} {"text": "using LinearAlgebra\nusing Combinatorics\n\nA = [3 1 2 2;\n 1 3 8 2;\n 2 3 5 1]\n\nB = [1 0 2;\n 1 3 6;\n 2 2 0;\n 0 1 1]\n\nfunction caychy_binet(A, B)\n comb = collect(combinations(1:size(A)[2], size(A)[1]))\n res = 0\n for S in comb\n res += det(A[:,S])*det(B[S,:])\n end\n\n res\nend\n\nprintln(\"det(AB)=\", det(A*B))\nprintln(\"cauchy-binet: \", caychy_binet(A, B))", "meta": {"hexsha": "08e35e3c5a4cb4debd1f389847731800862135de", "size": 386, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "linear_algebra/cauchy_binet.jl", "max_stars_repo_name": "nocotan/numerical_calculus.jl", "max_stars_repo_head_hexsha": "76b46b22d04e2e7e82cf44788c4f48ce25d59847", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-01-07T06:26:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-24T06:21:01.000Z", "max_issues_repo_path": "linear_algebra/cauchy_binet.jl", "max_issues_repo_name": "nocotan/numerical_calculus.jl", "max_issues_repo_head_hexsha": "76b46b22d04e2e7e82cf44788c4f48ce25d59847", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-01-10T08:22:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-08T13:31:00.000Z", "max_forks_repo_path": "linear_algebra/cauchy_binet.jl", "max_forks_repo_name": "nocotan/numerical_calculus.jl", "max_forks_repo_head_hexsha": "76b46b22d04e2e7e82cf44788c4f48ce25d59847", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-01-10T05:59:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T13:22:34.000Z", "avg_line_length": 16.0833333333, "max_line_length": 58, "alphanum_fraction": 0.5310880829, "num_tokens": 165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551525886194, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.8181660608998667}} {"text": "using PyPlot, LinearAlgebra, Roots, DifferentialEquations\r\n\r\nfunction f(u,v; b=0.10, i=0.00)\r\n\treturn u*(1.0-u)*(u-b) - v + i\r\nend\r\n\r\nfunction g(u,v; a=0.37, c=0.05)\r\n\treturn c*(a*u-v)\r\nend\r\n\r\nfunction FHNgrid(; a=0.37, b=0.1, c=0.05, i=0.0, NU=1025, NV=1025, ulims=[-2.,+2.],vlims=[-1.,+1.])\r\n\tuu = range(ulims[1],ulims[2],NU)\r\n\tvv = range(vlims[1],vlims[2],NV)\r\n\tU = zeros(Float64, NV, NU)\r\n\tV = zeros(Float64, NV, NU)\r\n\tF = zeros(Float64, NV, NU)\r\n\tG = zeros(Float64, NV, NU)\r\n\t\r\n\tfor m in 1:NV, n in 1:NU\r\n\t\tU[m,n] = uu[n]\r\n\t\tV[m,n] = vv[m]\r\n\t\tF[m,n] = f(U[m,n],V[m,n];b=b,i=i)\r\n\t\tG[m,n] = g(U[m,n],V[m,n];a=a,c=c)\r\n\tend\r\n\t\r\n\treturn U,V,F,G\r\nend\r\n\r\nfunction FHNnullclines(; a=0.37, b=0.1, c=0.05, i=0.0)\r\n\r\n\tU,V,F,G = FHNgrid(; a=a, b=b, c=c, i=i)\r\n\tfig = plt.contour(U,V,F,levels=[-1e-14,+1e-14],colors=\"C0\",linestyles=\"solid\")\r\n\tplt.contour(U,V,G,levels=[-1e-14,+1e-14],colors=\"C1\",linestyles=\"solid\")\r\n\tplt.xlabel(\"\\$ u \\$\")\r\n\tplt.ylabel(\"\\$ v \\$\")\r\n\tplt.xlim([-2,2])\r\n\tplt.ylim([-1,1])\r\n\treturn fig\r\nend\r\n\r\nfunction FHNequilibria(; a=0.37, b=0.1, c=0.05, i=0.0)\r\n\r\n\t# need to find ALL u s.t.:\r\n\t#\tf(u,v) = 0 && g(u,v) = 0\r\n\t#\tSince g(u,v) = 0 is linear, we invert to get v = a*u\r\n\t# plugging this into f(u,v=a*u) = 0, we have a single\r\n\t# scalar, cubic, equation to find the roots of.\r\n\t# There will be between 0 and 3 roots.\r\n\tulim = 2.0\r\n\tr = find_zeros((u)->f(u,a*u;b=b,i=i),-ulim,ulim)\r\n\twhile length(r) < 1 && ulim < 100.0\r\n\t\tulim = 2*ulim\r\n\t\tr = find_zeros((u)->f(u,a*u;b=b,i=i),-ulim,ulim)\r\n\tend\r\n\treturn reduce(hcat, (r,a*r))\r\n\t\r\n\t# NOTE: for the general case, where g(u,v) = 0 is not invertible,\r\n\t# you must use Newton's method:\r\n\t#\t[u;v] = [u;v] - FHNjac(u,v)\\[f(u,v);g(u,v)]\r\n\t# in a loop, until convergence (u & v do not change on successive iterations)\r\n\t# AND this only works for one root at a time, whereas we need all three!\r\n\t# AND we need good estimates to initialize this Newton iteration!\r\n\t#u = randn(); v = randn()\r\n\t#for n in 1:20\r\n\t#\t(u,v) = (u,v) .- FHNjac(u,v; a=a,b=b,c=c,i=i)\\[f(u,v;b=b,i=i);g(u,v;a=a,c=c)]\r\n\t#end\r\nend\r\n\r\nfunction FHNjac(u,v; a=0.37, b=0.1, c=0.05, i=0.0, h=1e-14)\r\n\t# this uses Complex-Step differentiation:\r\n\t# \thttps://blogs.mathworks.com/cleve/2013/10/14/complex-step-differentiation/\r\n\t# a method of computing derivatives efficiently and accurately\r\n\t# using complex arithmetic.\r\n\t# It may, however, fail if the functions are not holonomic!\r\n\tJ = zeros(Float64,2,2)\r\n\tJ[1,1] = imag(f(u+im*h,v;b=b,i=i))/h\r\n\tJ[1,2] = imag(f(u,v+im*h;b=b,i=i))/h\r\n\tJ[2,1] = imag(g(u+im*h,v;a=a,c=c))/h\r\n\tJ[2,2] = imag(g(u,v+im*h;a=a,c=c))/h\r\n\t\r\n\treturn J\r\nend\r\n\r\nfunction stability(J)\r\n\treturn maximum(real(eigvals(J)))\r\nend\r\n\r\nfunction stabilityplot(;N=10000)\r\n\r\n\ttrJ = zeros(Float64,N)\r\n\tdetJ = zeros(Float64, N)\r\n\tlJ = zeros(Float64, N)\r\n\tfor n in 1:N\r\n\t\tJ = randn(Float64, 2, 2)\r\n\t\tlJ[n] = stability(J)\r\n\t\ttrJ[n] = tr(J)\r\n\t\tdetJ[n] = det(J)\r\n\tend\r\n\tplt.scatter(trJ, detJ, c=lJ, s=1.0, cmap=\"bwr\", vmin=-1, vmax=+1)\r\n\tplt.colorbar(label=\"\\$ \\\\max \\\\, \\\\Re (\\\\lambda) \\$\", extend=\"both\")\r\n\tplt.plot(-5.0:0.1:5.0, ((-5.0:0.1:5.0).^2.0)./4.0, \"-k\", label=\"\\$ \\\\Delta = 0 \\$\")\r\n\tplt.xlabel(\"tr\\$ A \\$\")\r\n\tplt.ylabel(\"\\$ \\\\det A \\$\")\r\n\tplt.xlim([-5,5])\r\n\tplt.ylim([-5,5])\r\n\tplt.legend(loc=0, edgecolor=\"none\")\r\nend\r\n\r\nfunction oscillationplot(;N=10000)\r\n\r\n\ttrJ = zeros(Float64,N)\r\n\tdetJ = zeros(Float64, N)\r\n\tlJ = zeros(Float64, N)\r\n\tfor n in 1:N\r\n\t\tJ = randn(Float64, 2, 2)\r\n\t\tlJ[n] = maximum(abs.(imag.(eigvals(J))))\r\n\t\ttrJ[n] = tr(J)\r\n\t\tdetJ[n] = det(J)\r\n\tend\r\n\tplt.scatter(trJ, detJ, c=lJ, s=1.0, cmap=\"bwr\", vmin=-1, vmax=+1)\r\n\tplt.colorbar(label=\"\\$ \\\\max \\\\, \\\\Im (\\\\lambda) \\$\", extend=\"both\")\r\n\tplt.plot(-5.0:0.1:5.0, ((-5.0:0.1:5.0).^2.0)./4.0, \"-k\", label=\"\\$ \\\\Delta = 0 \\$\")\r\n\tplt.xlabel(\"tr\\$ A \\$\")\r\n\tplt.ylabel(\"\\$ \\\\det A \\$\")\r\n\tplt.xlim([-5,5])\r\n\tplt.ylim([-5,5])\r\n\tplt.legend(loc=0, edgecolor=\"none\")\r\nend\r\n\r\nfunction FHNstrmplt(; a=0.37, b=0.1, c=0.05, i=0.0)\r\n\tU,V,F,G = FHNgrid(; a=a, b=b, c=c, i=i)\r\n\t\r\n\tfig = plt.streamplot(U,V,F,G, color=sqrt.(F.^2 + G.^2))\r\n\tplt.colorbar(label=\"\\$ \\\\sqrt{\\\\dot u ^2 + \\\\dot v ^2} \\$\")\r\n\tplt.xlabel(\"\\$ u \\$\")\r\n\tplt.ylabel(\"\\$ v \\$\")\r\n\tplt.xlim([-2,2])\r\n\tplt.ylim([-1,1])\r\n\treturn fig\r\nend\r\n\r\nfunction FHNtotal(; a=0.37, b=0.1, c=0.05, i=0.0)\r\n\tfig = plt.figure()\r\n\tFHNstrmplt(;a=a,b=b,c=c,i=i)\r\n\tFHNnullclines(;a=a,b=b,c=c,i=i)\r\n\tr = FHNequilibria(;a=a,b=b,c=c,i=i)\r\n\tfor n in 1:size(r,1)\r\n\t\tu = r[n,1]; v = r[n,2]\r\n\t\tl = eigvals(FHNjac(u,v;a=a,b=b,c=c,i=i))\r\n\t\tii = argmax(real(l))\r\n\t\tif maximum(real(l)) > 0\r\n\t\t\tplt.plot([u],[v],\"ok\", markerfacecolor=\"w\", label=\"\\$ \\\\lambda = $(round(l[ii],sigdigits=2)) \\$\")\r\n\t\telseif maximum(real(l)) < 0\r\n\t\t\tplt.plot([u],[v],\"ok\", label=\"\\$ \\\\lambda = $(round(l[ii],sigdigits=2)) \\$\")\r\n\t\tend\r\n\tend\r\n\tplt.legend(loc=0, edgecolor=\"none\")\r\n\treturn fig\r\nend\r\n\r\nfunction FHNdyn(; a=0.37, b=0.1, c=0.05, i=0.0, x0=randn(Float64,2))\r\n\tfunction fhn!(dx, x, p, t)\r\n\t\tdx[1] = f(x[1],x[2];b=p[2],i=p[4])\r\n\t\tdx[2] = g(x[1],x[2];a=p[1],c=p[3])\r\n\t\treturn nothing\r\n\tend\r\n\tprob = ODEProblem(fhn!, x0, (0.0, 1000.0), [a,b,c,i])\r\n\tsol = solve(prob, abstol=1e-13, reltol=1e-13)\r\n\t\r\n\tFHNtotal(;a=a,b=b,c=c,i=i)\r\n\tplt.plot(sol[1,:], sol[2,:], \"-k\", linewidth=3)\r\n\tplt.plot(x0[1],x0[2],\"xk\")\r\n\tplt.title(\"\\$ \\\\alpha=$(a), \\\\beta=$(b), \\\\gamma=$(c), I=$(round(i,sigdigits=3)) \\$\")\r\n\tplt.xlabel(\"\\$ u \\$\")\r\n\tplt.ylabel(\"\\$ v \\$\")\r\n\tplt.xlim([-.5,1.5])\r\n\tplt.ylim([-.5,.5])\r\n\treturn nothing\r\n\r\nend\r\n\r\nfunction FHNexc(; a=0.37, b=0.1, c=0.05, i=0.0)\r\n\r\n\tU,V,F,G = FHNgrid(; a=a, b=b, c=c, i=i, ulims=[-0.3,1.3], vlims=[-0.3,0.3], NU=129, NV=65)\r\n\t\r\n\tfig, axs = plt.subplots(3,4,sharex=true, sharey=true, constrained_layout=true)\r\n\tfor (n,u) in enumerate(range(-0.1,0.2,step=0.1)), (m,v) in enumerate(range(0.05,-0.05,step=-0.05))\r\n\t\taxs[m,n].streamplot(U,V,F,G,color=sqrt.(F.^2 + G.^2),linewidth=sqrt.(F.^2 + G.^2))\r\n\t\taxs[m,n].contour(U,V,F,levels=[-1e-14,+1e-14],colors=\"C0\",linestyles=\"solid\")\r\n\t\taxs[m,n].contour(U,V,G,levels=[-1e-14,+1e-14],colors=\"C1\",linestyles=\"solid\")\r\n\t\t\r\n\t\tfunction fhn!(dx, x, p, t)\r\n\t\t\tdx[1] = f(x[1],x[2];b=p[2],i=p[4])\r\n\t\t\tdx[2] = g(x[1],x[2];a=p[1],c=p[3])\r\n\t\t\treturn nothing\r\n\t\tend\r\n\t\tprob = ODEProblem(fhn!, [u;v], (0.0, 1000.0), [a,b,c,i])\r\n\t\tsol = solve(prob, abstol=1e-13, reltol=1e-13)\r\n\t\t\r\n\t\taxs[m,n].plot(sol[1,:], sol[2,:], \"-k\", linewidth=2)\r\n\t\taxs[m,n].plot(u,v,\"xk\")\r\n\t\taxs[m,n].plot(0,0,\".k\")\r\n\r\n\t\t\r\n\t\tif n==1\r\n\t\t\taxs[m,n].set_ylabel(\"\\$ v_0 = $(v) \\$\")\r\n\t\tend\r\n\t\tif m==3\r\n\t\t\taxs[m,n].set_xlabel(\"\\$ u_0 = $(u) \\$\")\r\n\t\tend\r\n\t\taxs[m,n].set_xlim([-0.3,1.3])\r\n\t\taxs[m,n].set_ylim([-0.3,0.3])\r\n\tend\r\n\t\t\r\n\treturn fig, axs\r\n\r\nend\r\n\r\nfunction currentBif(;a=0.37,b=0.1,c=0.05,i=0.0)\r\n\tii = range(0.00,0.05,step=0.0001)\r\n\tli = zeros(Float64, length(ii))\r\n\tfor (n,i) in enumerate(ii)\r\n\t\tx0 = FHNequilibria(;i=i)\r\n\t\tx0 = x0[argmin(x0[:,1]),:]\r\n\t\tli[n] = stability(FHNjac(x0[1],x0[2];i=i))\r\n\tend\r\n\tfig = figure()\r\n\tplt.plot(ii, li, \"-\", label=\"\\$ \\\\max \\\\Re( \\\\lambda)(I) \\$\")\r\n\tind = argmin(abs.(li))\r\n\tplt.plot(ii[ind], li[ind], \".k\", label=\"\\$ I^* = $(ii[ind]) \\$\")\r\n\tplt.xlabel(\"\\$ I \\$\")\r\n\tplt.ylabel(\"\")\r\n\tplt.legend(loc=0,edgecolor=\"none\")\r\n\treturn fig\r\nend\r\n\r\nfunction currentBifTraj(;a=0.37,b=0.1,c=0.05,i=0.0)\r\n\tfunction fhn!(dx, x, p, t)\r\n\t\tdx[1] = f(x[1],x[2];b=p[2],i=p[4])\r\n\t\tdx[2] = g(x[1],x[2];a=p[1],c=p[3])\r\n\t\treturn nothing\r\n\tend\r\n\tfig, axs = plt.subplots(5,1,sharex=true,sharey=true,constrained_layout=true)\r\n\t\r\n\tfor (n,i) in enumerate(range(0.0,0.04,length=5))\r\n\t\tprob = ODEProblem(fhn!, [1.0;-0.1], (0.0, 1000.0), [a,b,c,i])\r\n\t\tsol = solve(prob, abstol=1e-13, reltol=1e-13)\r\n\t\taxs[n].plot(sol.t, sol[1,:], \"-C0\", label=\"\\$ u(t) \\$\")\r\n\t\taxs[n].plot(sol.t, sol[2,:], \"-C1\", label=\"\\$ v(t) \\$\")\r\n\t\taxs[n].set_ylabel(\"\\$ I = $(round(i,sigdigits=2)) \\$\")\r\n\tend\r\n\taxs[1].legend(loc=0, edgecolor=\"none\")\r\n\taxs[end].set_xlabel(\"\\$ t \\$\")\r\n\taxs[end].set_xlim([0,200])\r\n\tplt.savefig(\"/Users/christophermarcotte/Downloads/fhncurrentbiftraj.pdf\")\r\n\tplt.close(\"all\")\r\nend\r\n\r\nfunction alphaBifPlot(;a=0.37,b=0.1,c=0.05,i=0.0)\r\n\tfig = plt.figure()\r\n\tastar = 0.2025\r\n\tfor a in range(0.37, -0.07, length=4096)\r\n\t\trr = FHNequilibria(;a=a,b=b,c=c,i=i)\r\n\t\tfor n in 1:size(rr,1)\r\n\t\t\tJ = FHNjac(rr[n,1],rr[n,2]; a=a,b=b,c=c,i=i)\r\n\t\t\tl = eigvals(J)\r\n\t\t\tif maximum(real(l)) > 0\r\n\t\t\t\tplt.plot(a,rr[n,1],\".k\")\r\n\t\t\telseif maximum(real(l)) < 0\r\n\t\t\t\tplt.plot(a, rr[n,1],\"ok\")\r\n\t\t\tend\r\n\t\tend\t\t\t\r\n\tend\r\n\tplt.xlabel(\"\\$ \\\\alpha \\$\")\r\n\tplt.ylabel(\"\\$ \\\\bar{u} \\$\")\r\n\tplt.title(\"Thick - Stable; Thin - Unstable\")\r\n\treturn fig\r\nend\r\n\r\nfunction FHNLC(; a=0.37, b=0.1, c=0.05, i=0.04)\r\n\tFHNtotal(;a=a,b=b,c=c,i=i)\r\n\tfunction fhn!(dx, x, p, t)\r\n\t\tdx[1] = f(x[1],x[2];b=p[2],i=p[4])\r\n\t\tdx[2] = g(x[1],x[2];a=p[1],c=p[3])\r\n\t\treturn nothing\r\n\tend\r\n\tprob = ODEProblem(fhn!, [0.0;-0.1], (0.0, 1000.0), [a,b,c,i])\r\n\tsol = solve(prob, abstol=1e-13, reltol=1e-13)\r\n\tplt.plot(sol[1,:], sol[2,:], \"-k\", linewidth=2)\r\n\tplt.plot(sol[1,1], sol[2,1],\"xk\")\r\n\t\r\n\tprob = ODEProblem(fhn!, [0.0;0.1], (0.0, 1000.0), [a,b,c,i])\r\n\tsol = solve(prob, abstol=1e-13, reltol=1e-13)\r\n\tplt.plot(sol[1,:], sol[2,:], \"-k\", linewidth=2)\r\n\tplt.plot(sol[1,1], sol[2,1],\"xk\")\r\n\t\r\n\tplt.title(\"\\$ \\\\alpha=$(a), \\\\beta=$(b), \\\\gamma=$(c), I=$(round(i,sigdigits=3)) \\$\")\r\n\tplt.xlabel(\"\\$ u \\$\")\r\n\tplt.ylabel(\"\\$ v \\$\")\r\n\tplt.xlim([-.5,1.5])\r\n\tplt.ylim([-.2,.3])\r\n\r\n\tplt.savefig(\"/Users/christophermarcotte/Downloads/fhnLC.pdf\")\r\n\tplt.close(\"all\")\r\nend\r\n", "meta": {"hexsha": "a8c6906c3843e2ba9c3d61da87f80e7c73f4b689", "size": 9345, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "fhn_workshop_figs.jl", "max_stars_repo_name": "cmarcotte/Workshop2022", "max_stars_repo_head_hexsha": "8b8628189dc8f1ded8b1eda87c646d9b437b11d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fhn_workshop_figs.jl", "max_issues_repo_name": "cmarcotte/Workshop2022", "max_issues_repo_head_hexsha": "8b8628189dc8f1ded8b1eda87c646d9b437b11d7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fhn_workshop_figs.jl", "max_forks_repo_name": "cmarcotte/Workshop2022", "max_forks_repo_head_hexsha": "8b8628189dc8f1ded8b1eda87c646d9b437b11d7", "max_forks_repo_licenses": ["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.5392156863, "max_line_length": 101, "alphanum_fraction": 0.5549491707, "num_tokens": 3878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541643004809, "lm_q2_score": 0.8688267643505193, "lm_q1q2_score": 0.8181343407063791}} {"text": "# van_der_Pol_Poincare_section_v1.jl\n# =============================================\n\n\nusing DrWatson\n@quickactivate \"NonlinearDynamicsTextbook\"\ninclude(srcdir(\"style.jl\"))\nusing DynamicalSystems, PyPlot, OrdinaryDiffEq\nusing StaticArrays\nusing Random\nusing Statistics\n\n\nfunction van_der_Pol_ODE(du,u,p,t)\n d, a, omega = p\n du[1] = u[2]\n du[2] = - u[1] - d*(u[1]*u[1]-1) * u[2] + a*sin(omega*t)\nend\n\n# parameters and initial values\n# -----------------------------\nntrans = 5000. # transient periods\nnattr = 2000 # no. of points on the attractor used for estimating winding no.\ny_init = [0.1 0.1]\n\nd = 5.\na = 1.\nomega = 1.\n\np = [d a omega]\nperiod = 2*pi / omega\n\n\n # transient to attractor\n # ----------------------\ntspan = (0., ntrans*period)\nprob = ODEProblem(van_der_Pol_ODE, y_init, tspan, p)\nsol = solve(prob, Tsit5(), reltol=1e-8, abstol=1e-8, maxiters = 1e12 )\n\n# attractor\n# ---------\ntspan = (0., nattr*period)\ny_init = sol.u[end]\nprob = ODEProblem(van_der_Pol_ODE, y_init, tspan, p)\nsol = solve(prob, Tsit5(), reltol=1e-8, abstol=1e-8, maxiters = 1e12, saveat = period)\n \nu1vec = [u[1] for u in sol.u] \nu2vec = [u[2] for u in sol.u] \nnts = length(u1vec)\n\ntheta_vec = (atan.( u2vec , u1vec ) .+ pi ) ./ (2*pi) \n\n# open plot\n# ---------\n# %%\nfig = figure(figsize=(0.6*figx,figy)) \n\nax1 = subplot(1,2,1)\nplt.scatter(u1vec,u2vec,s=4, c = COLORS[1])\n\nxticks([-2,0,2], [\"-2\",\"\",\"2\"])\nyticks([-6,0,6], [\"-6\",\"\",\"6\"])\nxlabel(L\"u_1\";labelpad = -20) \nylabel(L\"u_2\";labelpad = -20) \n\nax2 = subplot(1,2,2)\nplt.scatter(theta_vec[1:end-1],theta_vec[2:end],s=4, c = COLORS[2])\nxlabel(L\"\\theta_n\"; labelpad = -20) \nylabel(L\"\\theta_{n+1}\"; labelpad = -20)\nxticks([0,0.5,1], [\"0\", \"\", \"2π\"])\nyticks([0,0.5,1], [\"0\", \"\", \"2π\"])\nyticks([0,0.5,1])\nxlim(0,1)\nylim(0,1)\nadd_identifiers!(fig)\nfig.tight_layout(pad=0.33)\n\nwsave(plotsdir(\"9\", \"vanderPol_poincare_section\"), fig)\n", "meta": {"hexsha": "3530c191f42be1c186525fee4cae63dc49d6454d", "size": 1884, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "figure_generation/9/9.5.jl", "max_stars_repo_name": "JuliaDynamics/NonlinearDynamicsTextbook", "max_stars_repo_head_hexsha": "bfae8cf867f458f00151da089332f2ce3bea5dd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 88, "max_stars_repo_stars_event_min_datetime": "2021-07-18T20:54:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T09:23:53.000Z", "max_issues_repo_path": "figure_generation/9/9.5.jl", "max_issues_repo_name": "JuliaDynamics/NonlinearDynamicsTextbook", "max_issues_repo_head_hexsha": "bfae8cf867f458f00151da089332f2ce3bea5dd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "figure_generation/9/9.5.jl", "max_forks_repo_name": "JuliaDynamics/NonlinearDynamicsTextbook", "max_forks_repo_head_hexsha": "bfae8cf867f458f00151da089332f2ce3bea5dd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2021-07-28T18:49:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T08:45:11.000Z", "avg_line_length": 23.8481012658, "max_line_length": 87, "alphanum_fraction": 0.5981953291, "num_tokens": 720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213853793453, "lm_q2_score": 0.9099070048165069, "lm_q1q2_score": 0.8181168467369883}} {"text": "# coding: utf-8\n\n\n# In[1]: \n\n\n#a simple day trading game\n#day trader is only allowed to make at maximum two trades\n#the strategy is long only\n#lets find out the maximum profit\n\n#more details can be found in the following link\n# https://www.geeksforgeeks.org/maximum-profit-by-buying-and-selling-a-share-at-most-twice/\n\n#an alternative version in dynamic programming exists\n#its done by using a different approach\n#strongly recommend you to take a look\n# https://github.com/je-suis-tm/recursion-and-dynamic-programming/blob/master/stock%20trading%20dynamic%20programming.jl\n\n\n# In[2]:\n\n\n#compute the maximum profit for long only strategy\nfunction compute_profit(prices)\n \n #initialize maximum price with the close price\n max_price=prices[end]\n \n #initialize minimum price with the open price\n min_price=prices[1]\n \n #initialize indices\n left=1\n right=length(prices)\n minind=1\n maxind=length(prices)\n \n #we have two indices moving at the same time\n #one from left to find the minimum value\n #the other from right to find the maximum value\n #we are not looking for global minimum\n #we only want local minimum before the global maximum\n while leftminind\n \n #when a larger value is found\n #update accordingly\n if prices[right]>max_price\n\n max_price=prices[right]\n maxind=copy(right)\n\n end\n \n #the same applies to a smaller value\n if prices[left]x!=0,degree)\n add!(G,last[1],last[2])\n\n return G\nend\n\n# Create the Cube graph with 2^n vertices\n\"\"\"\n`Cube(n)` creates the `n`-dimensional cube graph. This graph has `2^n`\nvertices named by all possible length-`n` strings of 0s and 1s. Two\nvertices are adjacent iff they differ in exactly one position.\n\"\"\"\nfunction Cube(n::Integer=3)\n G = StringGraph()\n for u=0:2^n-1\n for shift=0:n-1\n v = xor( (1<n\n error(\"k must not be greater than n\")\n end\n\n A = collect(1:n)\n vtcs = [Set{Int}(v) for v in IterTools.subsets(A,k)]\n G = SimpleGraph{Set{Int}}()\n\n for v in vtcs\n add!(G,v)\n\n for j=1:n\n if !in(j,v)\n for x in v\n w = deepcopy(v)\n push!(w,j)\n pop!(w,x)\n add!(G,v,w)\n end\n end\n end\n end\n\n name(G,\"Johnson($n,$k) graph\")\n return G\nend\n\n\n# Create the Petersen graph.\n\"\"\"\n`Petersen()` returns the Petersen graph. The vertices are labeled as\nthe 2-element subsets of `1:5`. Wrap in `relabel` to have vertices\nnamed `1:10`. See also: `Kneser`.\n\"\"\"\nfunction Petersen()\n G = Kneser(5,2)\n name(G,\"Petersen graph\")\n return G\nend\n\n# Create Paley graphs\n\n\"\"\"\n`Paley(p)` creates the Paley graph with `p` vertices named\n`0:(p-1)`. Here `p` must be a prime with `p%4==1`. Vertices `u` and\n`v` are adjacent iff `u-v` is a quadratic residue (perfect square)\nmodulo `p`.\n\"\"\"\nfunction Paley(p::Int)\n if mod(p,4) != 1 || ~isprime(p)\n error(\"p must be a prime congruent to 1 mod 4\")\n end\n\n # Quadratic residues mod p\n qrlist = unique( [ mod(k*k,p) for k=1:p ] )\n\n G = IntGraph()\n for u = 0:p-1\n for k in qrlist\n v = mod(u+k,p)\n add!(G,u,v)\n end\n end\n name(G,\"Paley($p) graph\")\n return G\nend\n\n\"\"\"\n`Frucht()` returns the Frucht graph: A 12-vertex, 3-regular\ngraph with no non-nontrivial automorphisms.\n\"\"\"\nfunction Frucht()\n G = Cycle(12)\n more_edges = [ (1,6), (2,4), (3,11), (5,7), (8,10), (9,12) ]\n add_edges!(G,more_edges)\n name(G,\"Frucht graph\")\n return G\nend\n\n# Called by RandomRegular ... one step\nfunction RandomRegularBuilder(n::Int, d::Int)\n # caller has already checked the values of n,d are legit\n vlist = randperm(n*d)\n G = IntGraph(n*d)\n for v=1:2:n*d\n add!(G,vlist[v], vlist[v+1])\n end\n\n for v = n:-1:1\n mushlist = collect( d*(v-1)+1 : v*d )\n for k=d-1:-1:1\n contract!(G,mushlist[k],mushlist[k+1])\n end\n end\n return relabel(G)\nend\n\n\"\"\"\n`RandomRegular(n,d)` creates a random `d`-regular graph on `n`\nvertices. This can take a while especially if the arguments are\nlarge. Call with an optional third argument to activate verbose\nprogress reports: `RandomRegular(n,p,true)`.\n\"\"\"\nfunction RandomRegular(n::Int, d::Int, verbose::Bool=false)\n # sanity checks\n if n<1 || d<1 || (n*d)%2==1\n error(\"n,d must be positive integers and n*d even\")\n end\n if verbose\n println(\"Trying to build \", d, \"-regular graph on \",\n n, \" vertices\")\n count::Int = 0\n end\n\n while true\n if verbose\n count += 1\n println(\"Attempt \", count)\n tic()\n end\n g = RandomRegularBuilder(n,d)\n if verbose\n toc();\n end\n dlist = deg(g)\n if dlist[1] == dlist[n]\n if verbose\n println(\"Success\")\n end\n name(g,\"Random regular graph, d=$d\")\n return g\n end\n if verbose\n println(\"Failed; trying again\")\n end\n end\nend\n\n\n\n\"\"\"\n`RandomSBM(bmap,pmat)` creates a random stochastic block model random graph.\nThe vector `bmap` is a list of `n` positive integers giving the block number\nof vertices `1:n`. The `i,j`-entry of the matrix `pmat` gives the probability\nof an edge from a vertex in block `i` to a vertex in block `j`.\n\n`RandomSBM(n,pvec,pmat)` creates such a graph with `n` vertices. The vector\n`pvec` gives the probabilities that vertices fall into a given block.\n\"\"\"\nfunction RandomSBM(bmap::Vector{Int}, pmat::Array{S,2}) where {S<:Real}\n n = length(bmap) # no of vertices\n b = maximum(bmap) # no of blocks\n\n @assert minimum(bmap)>0 \"Block numbers must be positive\"\n @assert pmat == pmat' \"Probability matrix must be square and symmetrical\"\n r = size(pmat,1)\n @assert b<=r \"Insufficient rows/cols in probability matrix\"\n @assert minimum(pmat)>=0 && maximum(pmat)<=1 \"Entries in probability matrix out of range\"\n\n G = IntGraph(n)\n for u=1:n-1\n bu = bmap[u]\n for v=u+1:n\n bv = bmap[v]\n p = pmat[bu,bv]\n if rand() <= p\n add!(G,u,v)\n end\n end\n end\n name(G,\"Random stochastic block model graph\")\n return G\nend\n\n\nfunction RandomSBM(n::Int, pvec::Vector{S}, pmat::Array{T,2}) where {S<:Real,T<:Real}\n @assert minimum(pvec)>=0 \"Entries in pvec must be nonnegative\"\n @assert sum(pvec)==1 \"Entries in pvec must sum to 1\"\n bmap = [ random_choice(pvec) for _=1:n]\n return RandomSBM(bmap,pmat)\nend\n\n\n\n\n\n\"\"\"\n`Knight(r::Int=8,c::Int=8)` creates a Knight's Moves graph on a\n`r`-by-`c` grid. That is, the vertices of this graph are the squares\nof an `r`-by-`c` chess board. Two vertices are adjacent if a Knight\ncan go from one of these squares to the other in a single move.\n\"\"\"\nfunction Knight(r::Int=8,c::Int=8)\n vtcs = collect(Base.Iterators.product(1:r,1:c))\n G = SimpleGraph{Tuple{Int64,Int64}}()\n for v in vtcs\n add!(G,v)\n end\n\n for v in vtcs\n for w in vtcs\n xv = collect(v)\n xw = collect(w)\n z = sort(map(abs,xv - xw))\n if z==[1,2]\n add!(G,v,w)\n end\n end\n end\n name(G,\"Knight's tour graph on $r-by-$c chess board\")\n return G\nend\n\n\n\n\"\"\"\n`HoffmanSingleton()` creates the Hoffman-Singleton graph. This is\na 7-regular graph whose diameter is 2 and whose girth is 5.\n\"\"\"\nfunction HoffmanSingleton()\n G = StringGraph()\n # P-pentagons\n for i=0:4\n for j=0:4\n jj = mod(j+1,5)\n v = \"P$i$j\"\n w = \"P$i$jj\"\n add!(G,v,w)\n end\n end\n\n # Q-pentagrams\n for i=0:4\n for j=0:4\n jj = mod(j+2,5)\n v = \"Q$i$j\"\n w = \"Q$i$jj\"\n add!(G,v,w)\n end\n end\n\n # Connections\n for i=0:4\n for j=0:4\n for k=0:4\n v = \"P$i$j\"\n x = mod(i*k+j,5)\n w = \"Q$k$x\"\n add!(G,v,w)\n end\n end\n end\n name(G,\"Hoffman-Singleton graph\")\n return G\nend\n\n\"\"\"\n`Hoffman()` creates the Hoffman graph which is cospectral with,\nbut not isomorphic to, `Cube(4)`.\n\"\"\"\nfunction Hoffman()\n D = [\n 1 1 1 1 0 0 0 0\n 1 1 1 0 1 0 0 0\n 1 0 0 1 0 1 1 0\n 0 1 0 1 0 1 0 1\n 0 0 1 1 0 0 1 1\n 1 0 0 0 1 1 1 0\n 0 1 0 0 1 1 0 1\n 0 0 1 0 1 0 1 1]\n\n A = [0*D D; D' 0*D]\n\n G = SimpleGraph(A)\n name(G,\"Hoffman graph\")\n return G\nend\n", "meta": {"hexsha": "d25e08cf987d35b6bbf55aee8081cc384f8a0c9f", "size": 15017, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/simple_constructors.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SimpleGraphs.jl-55797a34-41de-5266-9ec1-32ac4eb504d3", "max_stars_repo_head_hexsha": "a22fbfc7f37c5b4debf209a11f5b059a688d8676", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/simple_constructors.jl", "max_issues_repo_name": "UnofficialJuliaMirror/SimpleGraphs.jl-55797a34-41de-5266-9ec1-32ac4eb504d3", "max_issues_repo_head_hexsha": "a22fbfc7f37c5b4debf209a11f5b059a688d8676", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/simple_constructors.jl", "max_forks_repo_name": "UnofficialJuliaMirror/SimpleGraphs.jl-55797a34-41de-5266-9ec1-32ac4eb504d3", "max_forks_repo_head_hexsha": "a22fbfc7f37c5b4debf209a11f5b059a688d8676", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.6861198738, "max_line_length": 91, "alphanum_fraction": 0.5620296997, "num_tokens": 4949, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.891811041124754, "lm_q1q2_score": 0.8180606338231369}} {"text": "# I implement several simple but super loose bounds\n# These only apply to closed tours\n\n# the cost of a tour must be >= the sum over all vertices of\n# the cost of the cheapest edge leaving that vertex\n# likewise for the cheapest edge entering that vertex\n# since we must go to and leave each vertex\nfunction vertwise_bound(distmat::AbstractMatrix{T}) where {T<:Real}\n\t# the simple code below would tend to pick out the 0 costs on the diagonal\n\t# so make a doctored copy of the distance matrix with high costs on the diagonal\n\tm = maximum(distmat)\n\tdistmat_nodiag = distmat + m * I\n\tleaving = sum(minimum(distmat_nodiag, dims = 2))\n\tentering = sum(minimum(distmat_nodiag, dims = 1))\n\treturn maximum([leaving, entering])\nend\n\n# helper to get min spanning trees\n# returns a (n-1) long Vector of Tuple{Int, Int} where each tuple is an edge in the MST\n# and the total weight of the tree\n# the matrix passed in must be symmetric or you won't get out the minimum spanning tree\nfunction minspantree(dm::AbstractMatrix{T}) where {T<:Real} # accepts views\n\tmst_edges = Vector{Tuple{Int, Int}}()\n\tmst_cost = zero(T)\n\tn = size(dm, 1)\n\t\n\t# we keep a running list of the distance from each vertex to the partly formed tree\n\t# rather than using 0 for vertices already in the tree, we use a large value so that we\n\t# can find the closest non-tree vertex via call to Julia's `findmin`.\n\tbigval = maximum(dm) + one(T)\n\ttree_dists = dm[1,:] # distance to tree\n\tclosest_tree_verts = ones(Int, n)\n\ttree_dists[1] = bigval # vert 1 is in tree now\n\t\n\tfor _ in 1:(n-1) # need to add n - 1 other verts to tree\n\t\tcost, newvert = findmin(tree_dists)\n\t\ttreevert = closest_tree_verts[newvert]\n\t\t# add costs and edges\n\t\tmst_cost += cost\n\t\tif treevert < newvert\n\t\t\tpush!(mst_edges, (treevert, newvert))\n\t\telse\n\t\t\tpush!(mst_edges, (newvert, treevert))\n\t\tend\n\t\t# update distances to tree\n\t\ttree_dists[newvert] = bigval\n\t\tfor i in 1:n\n\t\t\tc = tree_dists[i]\n\t\t\tif c >= bigval # already in tree\n\t\t\t\tcontinue\n\t\t\tend\n\t\t\t# maybe this vertex is closer to the new vertex than the prior iteration's tree\n\t\t\tif c > dm[i, newvert]\n\t\t\t\ttree_dists[i] = dm[i, newvert]\n\t\t\t\tclosest_tree_verts[i] = newvert\n\t\t\tend\n\t\tend\n\tend\n\t\n\treturn mst_edges, mst_cost\nend\n\n# a simplified/looser version of Held-Karp bounds\n# any tour is a spanning tree on (n-1) verts plus two edges\n# from the left out vert\n# so the maximum over all verts (as the left out vert) of \n# MST cost on remaining vertices plus 2 cheapest edges from\n# the left out vert is a lower bound\n# for extra simplicity, the distance matrix is modified to be symmetric so we can treat\n# the underlying graph as undirected. This also doesn't help the bound!\nfunction hkinspired_bound(distmat::AbstractMatrix{T}) where {T<:Real}\n\tn = size(distmat, 1)\n\tif size(distmat, 2) != n\n\t\terror(\"Must pass square distance matrix to hkinspired_bound\")\n\tend\n\t\n\t# make a symmetric copy of the distance matrix\n\tdistmat = copy(distmat)\n\tfor i in 1:n, j in 1:n\n\t\tif i == j\n\t\t\tcontinue\n\t\tend\n\t\td = min(distmat[i,j], distmat[j,i])\n\t\tdistmat[i,j] = d\n\t\tdistmat[j,i] = d\n\tend\n\t\n\t# get a view of the distmat with one vertex deleted\n\tfunction del_vert(v)\n\t\tkeep = [1:(v-1) ; (v+1):n]\n\t\treturn view(distmat, keep, keep)\n\tend\n\t\n\t# make sure min(distmat[v,:]) doesn't pick diagonal elements\n\tm = maximum(distmat)\n\tdistmat_nodiag = distmat + m * I\n\t\n\t# lower bound the optimal cost by leaving a single vertex out\n\t# forming spanning tree on the rest\n\t# connecting the left-out vertex\n\tfunction cost_leave_out(v)\n\t\tdmprime = del_vert(v)\n\t\t_, c = minspantree(dmprime)\n\t\tc += minimum(distmat_nodiag[v,:])\n\t\tc += minimum(distmat_nodiag[:,v])\n\t\treturn c\n\tend\n\t\n\treturn maximum(map(cost_leave_out, 1:n))\nend\n\n# best lower bound we have\n\"\"\"\n lowerbound(distmat)\n\nLower bound the cost of the optimal TSP tour. At present, the bounds considered\nare a simple bound based on the minimum cost of entering and exiting each city and\na slightly better bound inspired by the Held-Karp bounds; note that the implementation\nhere is simpler and less tight than proper HK bounds.\n\nThe Held-Karp-inspired bound requires computing many spanning trees. For a faster but\ntypically looser bound, use `TravelingSalesmanHeuristics.vertwise_bound(distmat)`.\n\n!!! note\n The spanning tree bounds are only correct on symmetric problem instances and will not be\n used if the passed `distmat` is not symmetric. If you wish to use these bounds anyway,\n (e.g. for near-symmetric instances), use `TravelingSalesmanHeuristics.hkinspired_bound`.\n\"\"\"\nfunction lowerbound(distmat::AbstractMatrix{T} where {T<:Real})\n\tvb = vertwise_bound(distmat)\n\tif !issymmetric(distmat)\n\t\treturn vb\n\tend\n\treturn max(vb, hkinspired_bound(distmat))\nend", "meta": {"hexsha": "703d60b5f5c58b54f4d03d82582b7366f3e993a5", "size": 4682, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lowerbounds.jl", "max_stars_repo_name": "Wikunia/TravelingSalesmanHeuristics.jl", "max_stars_repo_head_hexsha": "570d68ef9742a34fb34020109b3d946d84c5e8fd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-03T04:03:57.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-03T04:03:57.000Z", "max_issues_repo_path": "lowerbounds.jl", "max_issues_repo_name": "BoyanXu/simulated_annealing", "max_issues_repo_head_hexsha": "b5f2df658c9f412c7876492ac845d3fd364467b6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lowerbounds.jl", "max_forks_repo_name": "BoyanXu/simulated_annealing", "max_forks_repo_head_hexsha": "b5f2df658c9f412c7876492ac845d3fd364467b6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-06-27T01:44:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-27T01:44:57.000Z", "avg_line_length": 34.6814814815, "max_line_length": 92, "alphanum_fraction": 0.7289619821, "num_tokens": 1305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582516374121, "lm_q2_score": 0.8791467706759584, "lm_q1q2_score": 0.8180093671758292}} {"text": "#=\n# 405: Generic Operator: 1D Nonlinear Poisson equation \n([source code](SOURCE_URL))\n\nSolve the nonlinear Poisson equation\n\n```math\n-\\nabla \\varepsilon \\nabla u + e^{u}-e^{-u} = f\n```\nin $\\Omega=(0,1)$ with boundary condition $u(0)=0$ and $u(1)=1$ with \n```math\nf(x)=\n \\begin{cases}\n 1&,x>0.5\\\\\n -1&, x<0.5\n \\end{cases}.\n```\n \nThis stationary problem is an example of a nonlinear Poisson equation or Poisson-Boltzmann equation.\nSuch equation occur e.g. in simulations of electrochemical systems and semicondutor devices.\n \n=#\n\nmodule Example405_GenericOperator\nusing Printf\nusing VoronoiFVM\nusing ExtendableGrids\nusing GridVisualize\n\nfunction main(;n=10,Plotter=nothing,verbose=false, unknown_storage=:sparse)\n \n ## Create a one-dimensional discretization\n h=1.0/convert(Float64,n)\n X=collect(0:h:1)\n grid=VoronoiFVM.Grid(X)\n\n ## A parameter which is \"passed\" to the flux function via scope\n ϵ=1.0e-3\n\n ## This generic operator works on the full solution seen as linear vector, and indexing\n ## into it needs to be performed with the help of idx (defined below for a solution vector)\n ## Here, instead of the flux function we provide a \"generic operator\"\n ## which provides the stiffness part of the problem. Its sparsity is detected automatically\n ## using SparsityDetection.jl \n function generic_operator!(f,u,sys)\n f.=0.0\n for i=1:length(X)-1\n du=ϵ*(u[idx[1,i]]-u[idx[1,i+1]])/(X[i+1]-X[i])\n f[idx[1,i]]+=du\n f[idx[1,i+1]]-=du\n end\n end\n \n ## Source term\n function source!(f,node)\n if node[1]<=0.5\n f[1]=1\n else\n f[1]=-1\n end\n end\n \n ## Reaction term\n function reaction!(f,u,node)\n f[1]=exp(u[1]) - exp(-u[1]) \n end\n \n ## Create a physics structure\n physics=VoronoiFVM.Physics(\n generic=generic_operator!,\n source=source!,\n reaction=reaction!)\n \n\n ## Create a finite volume system - either\n ## in the dense or the sparse version.\n ## The difference is in the way the solution object\n ## is stored - as dense or as sparse matrix\n\n sys=VoronoiFVM.System(grid,physics,unknown_storage=unknown_storage)\n\n ## Add species 1 to region 1\n enable_species!(sys,1,[1])\n\n ## Set boundary conditions\n boundary_dirichlet!(sys,1,1,0.0)\n boundary_dirichlet!(sys,1,2,1.0)\n\n ## Create a solution array\n inival=unknowns(sys,inival=0.5)\n solution=unknowns(sys)\n \n idx=unknown_indices(solution)\n ## Create solver control info\n control=VoronoiFVM.NewtonControl()\n control.verbose=verbose\n\n ## Stationary solution of the problem\n solve!(solution,inival,sys, control=control)\n \n scalarplot(grid,solution[1,:],title=\"Nonlinear Poisson\",Plotter=Plotter)\n return sum(solution)\nend\n\nfunction test()\n testval=1.5247901344230088\n main(unknown_storage=:sparse) ≈ testval && main(unknown_storage=:dense) ≈ testval\nend\n\nend \n\n", "meta": {"hexsha": "3a7bc8bd360a3f6624e940aa20ae1c5bb4ca1e63", "size": 2991, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Example405_GenericOperator.jl", "max_stars_repo_name": "PatricioFarrell/VoronoiFVM.jl", "max_stars_repo_head_hexsha": "690943ff455c91f16d114ad52cc83f2e8fa84e58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 80, "max_stars_repo_stars_event_min_datetime": "2019-11-18T05:04:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T04:11:01.000Z", "max_issues_repo_path": "examples/Example405_GenericOperator.jl", "max_issues_repo_name": "PatricioFarrell/VoronoiFVM.jl", "max_issues_repo_head_hexsha": "690943ff455c91f16d114ad52cc83f2e8fa84e58", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28, "max_issues_repo_issues_event_min_datetime": "2019-11-19T18:12:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T15:39:14.000Z", "max_forks_repo_path": "examples/Example405_GenericOperator.jl", "max_forks_repo_name": "PatricioFarrell/VoronoiFVM.jl", "max_forks_repo_head_hexsha": "690943ff455c91f16d114ad52cc83f2e8fa84e58", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 28, "max_forks_repo_forks_event_min_datetime": "2019-08-29T16:46:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T14:10:29.000Z", "avg_line_length": 26.7053571429, "max_line_length": 100, "alphanum_fraction": 0.6529588766, "num_tokens": 856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582497090321, "lm_q2_score": 0.8791467564270272, "lm_q1q2_score": 0.8180093522224645}} {"text": "function simpson(f::Function, a::Number, b::Number, n::Integer)\n h = (b - a) / n\n s = f(a + h / 2)\n for i in 1:(n-1)\n s += f(a + h * i + h / 2) + f(a + h * i) / 2\n end\n return h/6 * (f(a) + f(b) + 4*s)\nend\n\nrst =\n simpson(x -> x ^ 3, 0, 1, 100),\n simpson(x -> 1 / x, 1, 100, 1000),\n simpson(x -> x, 0, 5000, 5_000_000),\n simpson(x -> x, 0, 6000, 6_000_000)\n\n@show rst\n", "meta": {"hexsha": "3f004107b3c7f3ea6830fe920cb491eddc9d8848", "size": 402, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/numerical-integration.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/numerical-integration.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/numerical-integration.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.6470588235, "max_line_length": 63, "alphanum_fraction": 0.460199005, "num_tokens": 189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9693242000616579, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.8180079471224372}} {"text": "using Distributions, Plots; pyplot()\n\nn1, n2 = 10, 15\nN = 10^6\nmu, sigma = 10, 4\nnormDist = Normal(mu,sigma)\n\nfValues = Array{Float64}(undef, N)\n\nfor i in 1:N\n data1 = rand(normDist,n1)\n data2 = rand(normDist,n2)\n fValues[i] = var(data1)/var(data2)\nend\n\nfRange = 0:0.1:5\nstephist(fValues, bins=400, c=:blue, label=\"Simulated\", normed=true)\nplot!(fRange, pdf.(FDist(n1-1, n2-1), fRange), \n\tc=:red, label=\"Analytic\", xlims=(0,5), ylims=(0,0.8),\n \txlabel = \"F\", ylabel = \"Density\")", "meta": {"hexsha": "f90edf2a7d9a7d58ce90ade4f8afad4053197865", "size": 490, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "5_chapter/fDistribution.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/fDistribution.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/fDistribution.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 24.5, "max_line_length": 68, "alphanum_fraction": 0.6387755102, "num_tokens": 195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122684798184, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.8179735076056787}} {"text": "### A Pluto.jl notebook ###\n# v0.12.6\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 61a5b548-1ddc-11eb-2f7a-0d1b24e3cf48\nusing Pkg, DrWatson\n\n# ╔═╡ 61d2b2c8-1ddc-11eb-3ae7-a3c92d8a64b3\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Plots\nend\n\n# ╔═╡ 0fdee93c-1ddc-11eb-2bde-712854f4263e\nmd\"## Listing 1.11\"\n\n# ╔═╡ 61d33860-1ddc-11eb-1c60-eda2aa584f64\nfunction hailLength(x::Int)\n n = 0\n while x != 1\n if x % 2 == 0\n x = Int(x/2)\n else\n x = 3x +1\n end\n n += 1\n end\n return n\nend\n\n# ╔═╡ 61dc8cb4-1ddc-11eb-065a-fdfe7782833d\nlengths = [hailLength(x0) for x0 in 2:10^7];\n\n# ╔═╡ 61dda098-1ddc-11eb-19ba-c3b600208626\nhistogram(lengths, bins=1000, normed=:true, \n fill=(:blue, true), la=0, legend=:none,\n xlims=(0, 500), ylims=(0, 0.012),\n xlabel=\"Length\", ylabel=\"Frequency\")\n\n# ╔═╡ 61e6709c-1ddc-11eb-392c-97a365b3a46d\nmd\"## End of listing 1.11\"\n\n# ╔═╡ Cell order:\n# ╟─0fdee93c-1ddc-11eb-2bde-712854f4263e\n# ╠═61a5b548-1ddc-11eb-2f7a-0d1b24e3cf48\n# ╠═61d2b2c8-1ddc-11eb-3ae7-a3c92d8a64b3\n# ╠═61d33860-1ddc-11eb-1c60-eda2aa584f64\n# ╠═61dc8cb4-1ddc-11eb-065a-fdfe7782833d\n# ╠═61dda098-1ddc-11eb-19ba-c3b600208626\n# ╟─61e6709c-1ddc-11eb-392c-97a365b3a46d\n", "meta": {"hexsha": "b3d19b2773aabb7ec363bb232b7ade1b44e2d906", "size": 1235, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/01/listing1.11.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/01/listing1.11.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/01/listing1.11.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 23.3018867925, "max_line_length": 51, "alphanum_fraction": 0.6672064777, "num_tokens": 651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.897695283896349, "lm_q1q2_score": 0.8179617219640958}} {"text": "\nusing DiffEqBiological, Plots\ngr(); default(fmt = :png);\n\n\nbistable_switch = @reaction_network begin\n d, (X,Y) → ∅\n hillR(Y,v1,K1,n1), ∅ → X\n hillR(X,v2,K2,n2), ∅ → Y\nend d v1 K1 n1 v2 K2 n2\nd = 0.01;\nv1 = 1.5; K1 = 30; n1 = 3;\nv2 = 1.; K2 = 30; n2 = 3;\nbistable_switch_p = [d, v1 ,K1, n1, v2, K2, n2];\n\n\nss = steady_states(bistable_switch, bistable_switch_p)\n\n\nstability(ss,bistable_switch, bistable_switch_p)\n\n\nrn1 = @reaction_network begin\n p, ∅ → X\n hill(X,v,K,n), X → ∅\nend p v K n\np1 = [1.,2.5,1.5,1.5]\nsteady_states(rn1,p1)\n\n\nrn2 = @reaction_network begin\n p, ∅ → X\n log(X), X → ∅\nend p\np2 = [1.]\nsteady_states(rn2,p2)\n\n\nbif = bifurcations(bistable_switch, bistable_switch_p, :v1, (.1,5.))\nplot(bif,ylabel=\"[X]\",label=\"\")\nplot!([[],[]],color=[:blue :red],label = [\"Stable\" \"Unstable\"])\n\n\nplot(bif,2,ylabel=\"[Y]\")\nplot!([[],[]],color=[:blue :red],label = [\"Stable\" \"Unstable\"])\n\n\nbif = bifurcations(bistable_switch, bistable_switch_p,:v1,(.1,10.))\nplot(bif,linewidth=1.,title=\"A bifurcation diagram\",ylabel=\"Steady State concentration\")\nplot!([[],[]],color=[:blue :red],label = [\"Stable\" \"Unstable\"])\n\n\nbif = bifurcation_grid(bistable_switch, bistable_switch_p,:n1,1.:5.)\nplot(bif)\nscatter!([[],[]],color=[:blue :red],label = [\"Stable\" \"Unstable\"])\n\n\nbif = bifurcation_grid_diagram(bistable_switch, bistable_switch_p,:n1,0.:4.,:v1,(.1,5.))\nplot(bif)\nplot!([[],[]],color=[:blue :red],label = [\"Stable\" \"Unstable\"])\n\n\nbif = bifurcation_grid_2d(bistable_switch, bistable_switch_p,:n1,1.:3.,:n2,1.:10.)\nplot(bif)\nscatter!([[],[]],color=[:blue :red],label = [\"Stable\" \"Unstable\"])\n\n\nbrusselator = @reaction_network begin\n A, ∅ → X\n 1, 2X + Y → 3X\n B, X → Y\n 1, X → ∅\nend A B;\nA = 0.5; B = 4.;\nbrusselator_p = [A, B];\n\n\nbif = bifurcations(brusselator,brusselator_p,:B,(0.1,2.5))\nplot(bif,2)\nplot!([[],[],[],[]],color=[:blue :cyan :orange :red],label = [\"Stable Real\" \"Stable Complex\" \"Unstable Complex\" \"Unstable Real\"])\n\n\nbif = bifurcation_grid_diagram(brusselator,brusselator_p,:B,0.5:0.02:5.0,:A,(0.2,5.0))\nplot(bif)\nplot!([[],[],[],[]],color=[:blue :cyan :orange :red],label = [\"Stable Real\" \"Stable Complex\" \"Unstable Complex\" \"Unstable Real\"])\n\n\nusing DiffEqTutorials\nDiffEqTutorials.tutorial_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file], remove_homedir=true)\n\n", "meta": {"hexsha": "f01b21ffd3561b2dcdce5337cac92d53c3b2a875", "size": 2304, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/models/04b-diffeqbio_III_steadystates.jl", "max_stars_repo_name": "isaacsas/DiffEqTutorials.jl", "max_stars_repo_head_hexsha": "46c1701ef613aacbd678bde7437a3c8de363990d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-15T14:57:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-15T14:57:40.000Z", "max_issues_repo_path": "script/models/04b-diffeqbio_III_steadystates.jl", "max_issues_repo_name": "LoopGlitch26/SciMLTutorials.jl", "max_issues_repo_head_hexsha": "837d71ad59de12af2fa48babb9e5cd2e280dc71a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/models/04b-diffeqbio_III_steadystates.jl", "max_forks_repo_name": "LoopGlitch26/SciMLTutorials.jl", "max_forks_repo_head_hexsha": "837d71ad59de12af2fa48babb9e5cd2e280dc71a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3186813187, "max_line_length": 129, "alphanum_fraction": 0.6401909722, "num_tokens": 910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.925229948845201, "lm_q2_score": 0.8840392848011834, "lm_q1q2_score": 0.8179396222537471}} {"text": "#Running mean\n\"\"\"\n running_mean!(m, x)\n\nCompute (in-place) the mean, `m`, of a set of vectors, `x`.\n* `x` must be a matrix of Floats, with each column of `x` corresponding to a vector.\n* `m` must be a vector of Floats of appropriate length (equal to the number of rows in `x`).\n\"\"\"\nfunction running_mean!(m::AbstractVector{T}, x::AbstractMatrix{T}) where T<:AbstractFloat\n k = zero(T)\n fill!(m,zero(T))\n @inbounds for j ∈ axes(x,2)\n k = 1/j\n @turbo for i ∈ axes(x,1)\n temp = (x[i,j] - m[i])\n m[i] += temp*k\n end\n end\nend\n\n\"\"\"\n running_mean(x)\n\nCompute the mean of a set of vectors `x`.\n* `x` must be a matrix of Floats, with each column of `x` corresponding to a vector.\n\"\"\"\nfunction running_mean(x::AbstractMatrix{T}) where T<:AbstractFloat\n m = zeros(T,size(x,1))\n running_mean!(m, x)\n return m\nend\n\n\n#Update running mean with a nth data point where n is the running index\n\"\"\"\n update_running_mean!(m, x, n)\n\nUpdate the mean, `m`, of some set of `n-1` vectors to be the mean of the set of `n` vectors where `x` is the ``n^th`` vector.\n* `m` and `x` must be vectors of equal length.\n* Typically used when the mean of a part of a dataset has been previously computed and needs to be updated with a new data point (vector).\n\"\"\"\nfunction update_running_mean!(mean::AbstractVector{T}, data::AbstractVector{T}, n::Int) where T<:AbstractFloat\n k = 1/n\n @inbounds @turbo for i ∈ eachindex(mean)\n temp = (data[i] - mean[i])*k\n mean[i] += temp\n end\nend\n\n\n\n#Running mean and variance\n\"\"\"\n running_meanvar!(m, v, x)\n\nCompute (in-place) the mean, `m`, and variance along each dimension, `v`, of a set of vectors, `x`.\n* `x` must be a matrix of Floats, with each column of `x` corresponding to a vector.\n* `m` must be a vector of Floats of appropriate length (equal to the number of rows in `x`).\n* `v` must be a vector of Floats of appropriate length (equal to the number of rows in `x`).\n\"\"\"\nfunction running_meanvar!(m::AbstractVector{T}, v::AbstractVector{T}, x::AbstractMatrix{T}) where T<:AbstractFloat\n k = zero(T)\n fill!(m,zero(T))\n fill!(v,zero(T))\n @inbounds for j ∈ axes(x,2)\n k = 1/j\n @inbounds for i ∈ axes(x,1)\n temp = (x[i,j] - m[i])\n m[i] += temp*k\n v[i] += temp*(x[i,j] - m[i])\n end\n end\n N = 1/(size(x,2)-1)\n @turbo for i ∈ eachindex(v)\n v[i] *= N\n end\nend\n\n\"\"\"\n running_meanvar(x)\n\nCompute the mean and variance along each dimension of a set of vectors, `x`.\n* `x` must be a matrix of Floats, with each column of `x` corresponding to a vector.\n\"\"\"\nfunction running_meanvar(x::AbstractMatrix{T}) where T<:AbstractFloat\n m = zeros(T,size(x,1))\n v = zeros(T,size(x,1))\n running_meanvar!(m,v,x)\n return m, v\nend\n\n\n#Update running mean and variance with a nth data point where n is the running index\n\"\"\"\n update_running_meanvar!(m, v, x, n)\n\nUpdate the mean, `m`, and variance along each dimension, `v`, of some set of `n-1` vectors to be the mean and variance of the set of `n` vectors where `x` is the ``n^th`` vector (for `n>=3`).\n* `m`, `v` and `x` must be vectors of equal length.\n* Typically used when the mean and variance of a part of a dataset has been previously computed and needs to be updated with a new data point (vector).\n\n!!! note\n `n` must be 3 or greater.\n [`running_meanvar()`](@ref) or [`running_meanvar!()`](@ref) can be used to obtain an initial estimate of `m` and `v` from at least two vectors.\n\"\"\"\nfunction update_running_meanvar!(m::AbstractVector{T}, v::AbstractVector{T}, x::AbstractVector{T}, n::Int) where T<:AbstractFloat\n n >=3 || error(\"n must be greater than 2. Use running_meanvar() to obtain an initial estimate of mean and variance from at least two vectors before using update_running_meanvar() to update the estimates.\")\n k = 1/n\n k1 = 1/(n-1)\n @inbounds for i ∈ eachindex(m,v,x)\n temp = (x[i] - m[i])\n m[i] += temp*k\n v[i] *= (n-2)\n v[i] += temp*(x[i] - m[i])\n v[i] *= k1\n end\nend\n\n\n\n#running mean and covariance\n\"\"\"\n running_meancov!(m, C, x)\n\nCompute (in-place) the mean, `m`, and covariance matrix, `C`, of a set of vectors, `x`.\n* `x` must be a matrix of Floats, with each column of `x` corresponding to a vector.\n* `m` must be a vector of Floats of appropriate length (equal to the number of rows in `x`).\n* `C` must be a square matrix of Floats of appropriate size (side equal to the number of rows in `x`).\n\"\"\"\nfunction running_meancov!(m::AbstractVector{T}, C::AbstractMatrix{T}, x::AbstractMatrix{T}) where T<:AbstractFloat\n k = zero(T)\n temp = Vector{T}(undef,length(m))\n fill!(m,zero(T))\n fill!(C,zero(T))\n @inbounds for n ∈ axes(x,2)\n k = 1/n\n @turbo for i ∈ axes(x,1)\n temp[i] = (x[i,n] - m[i])\n m[i] += temp[i]*k\n end\n @turbo for i ∈ axes(x,1), j ∈ axes(x,1)\n C[j,i] += (x[j,n] - m[j])*temp[i]\n end\n end\n N = 1/(size(x,2)-1)\n @turbo for i ∈ eachindex(C)\n C[i] *= N\n end\n C += C'\n C /= 2\nend\n\n\n\"\"\"\n running_meancov(x)\n\nCompute the mean and covariance matrix a set of vectors, `x`.\n* `x` must be a matrix of Floats, with each column of `x` corresponding to a vector.\n\"\"\"\nfunction running_meancov(x::AbstractMatrix{T}) where T<:AbstractFloat\n m = Vector{T}(undef,size(x,1))\n C = Matrix{T}(undef,size(x,1),size(x,1))\n running_meancov!(m,C,x)\n return m, C\nend\n\n\n#Update running mean and covariance with a nth data point where n is the running index\n\"\"\"\n update_running_meancov!(m, C, x, n)\n\nUpdate the mean, `m`, and covariance, `C`, of some set of `n-1` vectors to be the mean and variance of the set of `n` vectors where `x` is the ``n^th`` vector (for `n>=3`).\n* `m` and `x` must be vectors of equal length.\n* `C` must be a square matrix of side equal to the length of `x`.\n* Typically used when the mean and covariance of a part of a dataset has been previously computed and needs to be updated with a new data point (vector).\n\n!!! note\n `n` must be 3 or greater.\n [`running_meancov()`](@ref) or [`running_meanvcov!()`](@ref) can be used to obtain an initial estimate of `m` and `v` from at least two vectors.\n\"\"\"\nfunction update_running_meancov!(m::AbstractVector{T}, C::AbstractMatrix{T}, x::AbstractVector{T}, n::Int) where T<:AbstractFloat\n n >=3 || error(\"n must be greater than 2. Use running_meanvar() to obtain an initial estimate of mean and variance from at least two vectors before using update_running_meanvar() to update the estimates.\")\n k = 1/n\n k1 = 1/(n-1)\n temp = Vector{T}(undef,length(m))\n @turbo for i ∈ eachindex(x)\n temp[i] = (x[i] - m[i])\n m[i] += temp[i]*k\n end\n @turbo for i ∈ eachindex(x), j ∈ eachindex(x)\n C[j,i] *= (n-2)\n C[j,i] += (x[j] - m[j])*temp[i]\n C[j,i] *= k1\n end\n C += C'\n C /= 2\nend", "meta": {"hexsha": "a8515561d3b99a3f4d557865bde80dcf44db2d9f", "size": 6937, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/running_stats.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/running_stats.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/running_stats.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": 35.3928571429, "max_line_length": 209, "alphanum_fraction": 0.6260631397, "num_tokens": 2086, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.8840392710530071, "lm_q1q2_score": 0.8179396131787868}} {"text": "\"\"\"\n newtonraphson(f::Function, x0::Number, fprime::Function, args::Tuple(); tol=1e-8, maxiter=50, eps0=1e-10)\n\nFind solution of f(x) = 0 (x is scalar) using Newton-Raphson iterations. \n\nThis code is from https://mmas.github.io/newton-julia. There was no license \n\n\"\"\"\nfunction newtonraphson(f::Function, x0::Number, fprime::Function, args::Tuple=();\n tol::AbstractFloat=1e-8, maxiter::Integer=50, eps0::AbstractFloat=1e-10)\n for _ in 1:maxiter\n yprime = fprime(x0, args...)\n if abs(yprime) < eps0\n @warn \"First derivative is zero\"\n return x0\n end\n y = f(x0, args...)\n x1 = x0 - y/yprime\n if abs(x1-x0) < tol\n return x1\n end\n x0 = x1\n end\n error(\"Max iteration exceeded\")\nend\n\n\n\"\"\"\n newtonraphson(f,x0,jac,args; tol=1e-8, maxiter=50, eps0=1e-10)\n\nNR solution for multidimensional problem f(x)=0. Requires jacobian.\n\n\"\"\"\nfunction newtonraphson(f::Function, x0::AbstractVector, jac::Function, args::Tuple=(); tol::AbstractFloat=1e-8, maxiter::Integer=50, eps0::AbstractFloat=1e-10)\n xc = copy(x0)\n for _ in 1:maxiter\n J = jac(xc, args...)\n if cond(J) > 1/eps0\n @warn \"Jacobian is ill-conditioned\"\n return xc\n end\n y = f(xc, args...)\n x1 = xc - J\\y\n if maximum(abs.(x1-xc)) < tol\n return x1\n end\n xc = x1\n end\n error(\"Max iteration exceeded\")\nend\n\n\"\"\"\n newtonraphson(f,x0,args; tol=1e-8, maxiter=50, eps0=1e-10)\n\n Method without explicit jacobian, using automatic differentiation.\n\"\"\"\nfunction newtonraphson(f::Function, x0::AbstractVector, args::Tuple=(); tol::AbstractFloat=1e-8, maxiter::Integer=50, eps0::AbstractFloat=1e-10)\n xc = copy(x0)\n for _ in 1:maxiter\n J = jacobian(x->f(x,args...), xc)\n if cond(J) > 1/eps0\n @warn \"Jacobian is ill-conditioned\"\n return xc\n end\n y = f(xc, args...)\n x1 = xc - J\\y\n if maximum(abs.(x1-xc)) < tol\n return x1\n end\n xc = x1\n end\n error(\"Max iteration exceeded\")\nend\n\n\"\"\"\n quasinewton(dobs::AbstractVector, g::Function, mprior::AbstractVector, jac::Function, CMi=0.0I, CDi=I, args::Tuple=();\n step=1,tol=1e-8,maxiter=50,eps0=1e-10)\n\nSolution of inverse problem dobs = g(m) using Quasi-Newton method. Direct implementation of Tarantola 2005, p. 69.\n\nReturn mean solution mpost and posterior covariance CMpost.\n\"\"\"\nfunction quasinewton(dobs::AbstractVector, g::Function,\n mprior::AbstractVector, jac::Function,\n CMi=0.0I, CDi=I, args::Tuple=();\n step::AbstractFloat=1.0, tol::AbstractFloat=1e-8,\n maxiter::Integer=50, eps0::AbstractFloat=1e-10)\n\n m = copy(mprior)\n \n for _ in 1:maxiter\n G = jac(m, args...)\n A = G'*CDi*G + CMi\n if cond(A)>1/eps0\n @warn \"Operator is ill conditioned. Consider Smoothing.\"\n return m, inv(A)\n end\n d = g(m, args...)\n b = G'*CDi*(d - dobs) + CMi*(m-mprior)\n dm = -step*(A\\b)\n m = m+dm\n if maximum(abs.(dm)) < tol\n CMpost = inv(A)\n return m, CMpost\n end\n end\n error(\"Max iteration exceeded\")\n \nend\n\n\"\"\"\n quasinewton(dobs, g, mprior, CMi=0.0I, CDi=I, args=();\n step=1,tol=1e-8,maxiter=50,eps0=1e-10)\n\nMethod without direct specification of jacobian, computed using forwarddiff.\n\"\"\"\nfunction quasinewton(dobs::AbstractVector, g::Function,\n mprior::AbstractVector,\n CMi=0.0I, CDi=I, args::Tuple=();\n step::AbstractFloat=1.0, tol::AbstractFloat=1e-8,\n maxiter::Integer=50, eps0::AbstractFloat=1e-10)\n\n m = copy(mprior)\n \n for _ in 1:maxiter\n G = jacobian(x-> g(x,args...), m)\n A = G'*CDi*G + CMi\n if cond(A)>1/eps0\n @warn \"Operator is ill conditioned. Consider Smoothing.\"\n return m, inv(A)\n end\n d = g(m, args...)\n b = G'*CDi*(d - dobs) + CMi*(m-mprior)\n dm = -step*(A\\b)\n m = m+dm\n if maximum(abs.(dm)) < tol\n CMpost = inv(A)\n return m, CMpost\n end\n end\n error(\"Max iteration exceeded\")\n \nend\n\n\"\"\"\n correlationmatrix(CM)\n\nCompute correlation matrix from covariance matrix.\n\"\"\"\nfunction correlationmatrix(CM)\n c = copy(CM)\n for b in 1:size(CM,2), a in 1:size(CM,1)\n c[a,b] /= sqrt(CM[a,a]*CM[b,b])\n end\n return c\nend\n", "meta": {"hexsha": "64aa1d9110d4aaa7a5506936460d65bce58e8ca2", "size": 4586, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/base.jl", "max_stars_repo_name": "BMElsigood/NewtonMethods.jl", "max_stars_repo_head_hexsha": "68a198379da41619b1b1e97fbb1243db0ca3b9b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/base.jl", "max_issues_repo_name": "BMElsigood/NewtonMethods.jl", "max_issues_repo_head_hexsha": "68a198379da41619b1b1e97fbb1243db0ca3b9b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/base.jl", "max_forks_repo_name": "BMElsigood/NewtonMethods.jl", "max_forks_repo_head_hexsha": "68a198379da41619b1b1e97fbb1243db0ca3b9b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2101910828, "max_line_length": 159, "alphanum_fraction": 0.5588748365, "num_tokens": 1406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475746920261, "lm_q2_score": 0.8670357494949105, "lm_q1q2_score": 0.8179160714573069}} {"text": "\"\"\"\n\n E1func(x)\n\nCompute the exponential integral function ``E_{1}(x)`` for a real number `x`. This function\nreturns zero if `x` is larger than 700, or `Inf + pi*1im` if `x` is smaller than -700. (This\ndefinition also defines the branch taken in the complex plane for ``x < 0``.) Note that even\nthough ``E_{1}(x)`` is real for ``x > 0``, the result of `E1func(x)` is cast as a complex\ntype, based on the type of `x`, for consistency.\n\nThis is a reimplementation of code at\n`https://github.com/mitmath/18S096/blob/iap2017/pset3/pset3-solutions.ipynb` by Steven G.\nJohnson, based on a combination of Taylor series and continued fraction expansions.\n\nSee also: [`E1taylor`](@ref), [`E1cf`](@ref)\n\n\"\"\"\nfunction E1func(x::AbstractFloat)\n \n if (x < -700*one(x))\n return Inf + pi*1im;\n elseif (x > 700*one(x))\n return zero(complex(x));\n else\n \n currfunc = E1taylor;\n if (x < -30*one(x) || x > 3*one(x))\n currfunc = E1cf;\n end\n mymaxorder = round(Int, 2 + 23/(1 + ((log10(abs(x)) - 0.4)/1.0)^2)); # useful empirical rule of thumb for largest order needed for positive x\n if (x < zero(x))\n mymaxorder = round(Int, 1 + 70/(1 + (log10(abs(x)) - 1.5)^2)); # useful empirical rule of thumb for largest order needed for negative x\n end\n myE1 = currfunc(x, mymaxorder);\n if (x < zero(x))\n return (complex(myE1) + pi*1im);\n end\n return complex(myE1);\n \n end\n \nend\n\nE1func(x::Real) = E1func(float(x));\n\n\"\"\"\n\n E1taylor(x, maxorder)\n\nCompute the exponential integral function ``E_{1}(x)`` for a real number `x`, using the\nTaylor series expansion up to a maximum order `maxorder`. This function works best for\n``-30 \\\\leq x \\\\leq 3``.\n\nThis is a reimplementation of code at\n`https://github.com/mitmath/18S096/blob/iap2017/pset3/pset3-solutions.ipynb` by Steven G.\nJohnson.\n\nSee also: [`E1func`](@ref), [`E1cf`](@ref)\n\n\"\"\"\nfunction E1taylor(x::AbstractFloat, maxorder::Integer)\n\n E1 = -1*MathConstants.eulergamma - log(abs(x));\n currterm = -1*x;\n E1 = E1 - currterm;\n \n for nn=2:maxorder\n \n currterm = -1*x*(nn-1)/(nn^2) * currterm;\n E1 = E1 - currterm;\n \n end\n \n return E1;\n \nend\n\nE1taylor(x::Real, maxorder::Integer) = E1taylor(float(x), maxorder);\n\n\"\"\"\n\n E1cf(x, maxorder)\n\nCompute the exponential integral function ``E_{1}(x)`` for a real number `x`, using the\ncontinued fraction expansion up to a maximum order `maxorder`. This function works best for\n``x < -30`` or ``x > 3``.\n\nThis is a reimplementation of code at\n`https://github.com/mitmath/18S096/blob/iap2017/pset3/pset3-solutions.ipynb` by Steven G.\nJohnson.\n\nSee also: [`E1func`](@ref), [`E1taylor`](@ref)\n\n\"\"\"\nfunction E1cf(x::AbstractFloat, maxorder::Integer)\n \n currcf = x;\n for nn=maxorder:-1:1\n currcf = x + (1+nn)/currcf;\n currcf = 1 + nn/currcf;\n end\n return (exp(-1*x)/(x + 1/currcf));\n \nend\n\nE1cf(x::Real, maxorder::Integer) = E1cf(float(x), maxorder);\n", "meta": {"hexsha": "d92a18ca3256d88414d10b517a16f23935c0395d", "size": 3037, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/E1func.jl", "max_stars_repo_name": "psv2/AARMBEM.jl", "max_stars_repo_head_hexsha": "d5d52df1f299b17e1db66d227f3d129101e46122", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/E1func.jl", "max_issues_repo_name": "psv2/AARMBEM.jl", "max_issues_repo_head_hexsha": "d5d52df1f299b17e1db66d227f3d129101e46122", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-05-27T16:10:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-02T21:16:54.000Z", "max_forks_repo_path": "src/E1func.jl", "max_forks_repo_name": "psv2/AARMBEM.jl", "max_forks_repo_head_hexsha": "d5d52df1f299b17e1db66d227f3d129101e46122", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3831775701, "max_line_length": 149, "alphanum_fraction": 0.6226539348, "num_tokens": 957, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.8962513634345443, "lm_q1q2_score": 0.8177721528744393}} {"text": "using NumericalMethodsforEngineers\n\nA = Float64[16 4 8;4 5 -4;8 -4 22]\nb = Float64[4, 2, 5]\nn = size(A, 1)\nd = zeros(n)\n\nldlt!(A, d)\nlower = zeros(3, 3)\nfor i in 1:n\n for j in 1:i\n lower[i, j] = A[i, j] / d[j]\n end\nend\n\nprintln(\"\\nLower Triangular Factors: \\n $lower\")\nprintln(\"\\nDiagonal Terms: \\n $d\")\n\nldlfor!(A, b)\nfor i in 1:n\n A[i, :] = A[i, :] / d[i]\nend\n\nsubbac!(A, b)\nprintln(\"\\nSolution Vector: \\n $b\")\n", "meta": {"hexsha": "39ebee50f7b9733122fa4079227cb98a90d6be2f", "size": 419, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ch02/f_02_03.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/NumericalMethodsforEngineers.jl-00e1d38a-71a9-5665-8612-32ae585a75a3", "max_stars_repo_head_hexsha": "e230c3045d98da0cf789e4a6acdccfbfb21ef49e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-01-02T01:16:31.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-02T01:16:31.000Z", "max_issues_repo_path": "examples/ch02/f_02_03.jl", "max_issues_repo_name": "OVGULIU/NumericalMethodsforEngineers.jl", "max_issues_repo_head_hexsha": "7ca0b79965a7abd58af29d8dfd1870a954fb3aec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/ch02/f_02_03.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": 16.1153846154, "max_line_length": 48, "alphanum_fraction": 0.584725537, "num_tokens": 183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075766298658, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.817763713501734}} {"text": "### A Pluto.jl notebook ###\n# v0.12.18\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 330763c4-f1e2-11ea-071a-b13a3bea37e9\nmd\"# Arrays: Slices and views\"\n\n# ╔═╡ 50e2aaa2-f1e2-11ea-37b2-9d23357ab558\nmd\"Since arrays are a very common way of storing data (but by no means the only way!), it is important to know how to manipulate them.\"\n\n# ╔═╡ 614126a8-f1e2-11ea-08ef-3d787d155416\nmd\"Suppose we start with a vector (1-dimensional array) of all ones:\"\n\n# ╔═╡ 6d6e5194-f1e2-11ea-116c-c191e52dd2af\nv = ones(Int, 10)\n\n# ╔═╡ 79332324-f1e2-11ea-3c82-39cad3d2391c\nmd\"\"\"We can **index** into the array to extract a certain element using square brackets (\"`[`\" and \"`]`\"):\"\"\"\n\n# ╔═╡ 8b0fca3e-f1e2-11ea-2b70-011aaeeb94cc\nv[3]\n\n# ╔═╡ 8cbf61b6-f1e2-11ea-3b49-cb59792e1fc1\nmd\"And we can modify that element using the same syntax:\"\n\n# ╔═╡ a87a0238-f1e2-11ea-272d-0d8cd4795df6\nv[3] = 2\n\n# ╔═╡ abbf2a72-f1e2-11ea-3e76-2bbe6e068c59\nv\n\n# ╔═╡ b0bafcae-f1e2-11ea-1c5a-a98c25cf6bd4\nmd\"If we want to extract a subset of the array, we can do so by indexing using a **range**:\"\n\n# ╔═╡ c8ec70ac-f1e2-11ea-30d6-7fc4e1f3cf63\nv[3:5]\n\n# ╔═╡ d6903d5e-f1e2-11ea-1525-35f7f6aa2f66\nmd\"We call this a **slice** of the array.\"\n\n# ╔═╡ 7c447b7a-f1e3-11ea-0ef2-c996690ae871\nmd\"## Modifying a slice: Broadcasting\"\n\n# ╔═╡ cd2c8f1a-f1e2-11ea-1449-73d40f742c60\nmd\"How can we *modify* this slice, say to replace them all by the value 4? Intuitively you might expect to be able to write\"\n\n# ╔═╡ edec3322-f1e2-11ea-32b8-ebd1445b18e2\nv[3:5] = 4\n\n# ╔═╡ 0ed6e116-f1e3-11ea-38ed-693262492cf2\nmd\"\"\"\nBut Julia does *not* allow this. The problem is that the two objects on the two sides of the assignment are different types: an array on the left, and a number on the right. What we want to do is modify the array *element by element*; for this we need to **broadcast** the assignment using \"`.`\":\n\"\"\"\n\n# ╔═╡ 446a93ba-f1e3-11ea-2957-e9c3bb7b66cd\nv[3:5] .= 4\n\n# ╔═╡ 4974c36c-f1e3-11ea-3543-63fce86af871\nmd\"Let's check if this modified the original array:\"\n\n# ╔═╡ 86be1e4e-f1e3-11ea-1212-6949dd55b8e8\nv\n\n# ╔═╡ 887640e0-f1e3-11ea-2d35-a9a9d1ae1897\nmd\"Success!\"\n\n# ╔═╡ 8d6fdcfa-f1e3-11ea-2f50-9783f4cd6339\nmd\"Following the above idea, if we provide a new array of the correct length, we can also modify the array:\"\n\n# ╔═╡ 9b504332-f1e3-11ea-35a2-8d33db468a83\nv[3:5] = [5, 6, 7]\n\n# ╔═╡ a1685124-f1e3-11ea-396c-cd12b8cdfdbd\nv\n\n# ╔═╡ b6e74bf4-f1e3-11ea-1eab-7db865915fe8\nmd\"## Array slices\"\n\n# ╔═╡ c1562b4e-f1e3-11ea-2b73-0d18fc361323\nmd\"Now suppose we give a name to that array slice:\"\n\n# ╔═╡ d69da0d8-f1e3-11ea-092b-7b7e9fd262ce\nw = v[3:5]\n\n# ╔═╡ afbeb970-f1e3-11ea-3658-c973f6808f6d\nmd\"An important question is the following: \n\n> *What happens if we modify `w`*?\n\nTake a moment to think about this before carrying on. What do you expect to happen? What are the possibilities?\n\"\n\n# ╔═╡ fc774f0c-f1e3-11ea-0e5a-3141ec04348d\nmd\"(Seriously, think about it!)\"\n\n# ╔═╡ ffa05138-f1e3-11ea-280e-bf7da83de269\nmd\"Of course, after thinking about it we should ask Julia what actually happens!\"\n\n# ╔═╡ 12dbdf38-f1e4-11ea-0449-b39ed2f5f12d\nmd\"Here's the current situation:\"\n\n# ╔═╡ 1123aade-f1e4-11ea-3cce-4534d7a72a60\nw\n\n# ╔═╡ 19ca7c32-f1e4-11ea-39a5-3dcf97e6fbcf\nmd\"Now let's change the first element of `w`:\"\n\n# ╔═╡ 21a48678-f1e4-11ea-1143-c709ee295e0d\nw[1] = 8\n\n# ╔═╡ 25abc85a-f1e4-11ea-156b-7f15f0474e3b\nw\n\n# ╔═╡ 2765efc0-f1e4-11ea-1324-ede5df51f047\nmd\"As expected, we modified `w`'s first element. But what happened to `v`?\"\n\n# ╔═╡ 3eb46116-f1e4-11ea-29e9-c74e8478d803\nv\n\n# ╔═╡ 4084ffca-f1e4-11ea-2d5d-abb022cd41cc\nmd\"We see that *`v` did not get modified!* This is surprising to many people.\n\nWhat is going on?\"\n\n# ╔═╡ 59e92208-f1e4-11ea-30a0-4d6d44bb9ae6\nmd\"What is happening is that the slice syntax `v[3:5]` actually creates a *copy* of the data in a new place in memory. Then `w` is a label, or pointer, for that new piece of memory. So modifying it does not touch the original values at all!\n\nWe should be aware of this whenever we are tempted to modify slices.\"\n\n# ╔═╡ aa48f298-f1e4-11ea-19ef-f120e959faa4\nmd\"## Array views\"\n\n# ╔═╡ addcc056-f1e4-11ea-0090-eb82f5545c37\nmd\"Of course, there are times when we do *not* want to make a copy. We might want to give a name to a slice of an array and manipulate the *original* array using the new name.\n\nTo do so we need to make a **view** of the array. This is literally like a window that allows us to view (read and write) to the *same data*.\n\nTo do this we use the `view` function:\n\"\n\n# ╔═╡ f5cc5e80-f1e4-11ea-027c-9bef1852423d\nz = view(v, 3:5)\n\n# ╔═╡ 218aa662-f1e5-11ea-1516-15ffd9c9ba08\nmd\"Now what happens if we modify `z` element by element using broadcasting?\"\n\n# ╔═╡ 2b955ddc-f1e5-11ea-1ca1-e91c81100478\nz .= 9\n\n# ╔═╡ 3a957e84-f1e5-11ea-2131-21fdd5d8c5d5\nz\n\n# ╔═╡ 3c96558c-f1e5-11ea-2109-79717714c977\nmd\"`z` changed as we expected. But what about the original vector `v`?\"\n\n# ╔═╡ 4ed5d79a-f1e5-11ea-1515-3be1b3fa9a2b\nv\n\n# ╔═╡ 50259ee6-f1e5-11ea-317b-11a542b6cd9e\nmd\"`v` also changed! This confirms that `z` is a window onto the same underlying data stored inside the block of memory labelled with the name `v`.\"\n\n# ╔═╡ ff65101a-f1e4-11ea-1b51-f5b09ae1f0eb\nmd\"Let's compare the types of `w` and `z`:\"\n\n# ╔═╡ fbd656aa-f1e4-11ea-2de2-61abc56ea71d\ntypeof(w), typeof(z)\n\n# ╔═╡ 0ab7d32e-f1e5-11ea-048b-a74d7515b0c5\nmd\"We see that they are of similar, but different types. `w` looks like other arrays we have seen, but `z` is a new type, called a `SubArray`.\"\n\n# ╔═╡ 781e93da-f1e5-11ea-3d3f-57842f69c032\nmd\"## Nicer syntax for views\"\n\n# ╔═╡ 83c8711a-f1e5-11ea-30c4-87104a7c1c2a\nmd\"Now we know how to produce views / `SubArray`s. But to do so we had to move away from the nice, compact array slicing syntax, from `v[3:5]` to `view(v, 3:5)`. Could there be a way to combine the two?\"\n\n# ╔═╡ fb50b922-f1e5-11ea-0049-773084392b80\nmd\"In fact there is: Julia provides a **macro** `@view` that converts the slicing syntax into a view:\"\n\n# ╔═╡ 0d25ffae-f1e6-11ea-05c4-49b25532ae49\nz2 = @view v[3:5]\n\n# ╔═╡ 27c47f2a-f1e6-11ea-3aa2-bb05fcd0e566\ntypeof(z2)\n\n# ╔═╡ 2998132a-f1e6-11ea-3ccc-7951c392e9f3\nz2 .= 10\n\n# ╔═╡ 2c010994-f1e6-11ea-0022-79d21e0764b8\nv\n\n# ╔═╡ 2d6f84e2-f1e6-11ea-2683-8be3ea0d39ac\nmd\"What is going on here? The macro `@view` literally takes the piece of Julia code `v[3:5]` and *replaces* it with the new piece of code `view(v, 3:5)`. Please see the separate video on macros for more detail!\"\n\n# ╔═╡ 4ff57544-f1e6-11ea-0274-15cc7917c3e3\nmd\"Finally, there is also a macro `@views`, which replaces *all* slices by views in an entire expression.\"\n\n# ╔═╡ ba6e586c-f1e8-11ea-1aba-ab1ba56ace6d\nmd\"## Matrices: slices and views\"\n\n# ╔═╡ f0753bec-f1e8-11ea-0776-99b556737a05\nmd\"Slices and views work the same way for matrices. For example, let's start with a matrix:\"\n\n# ╔═╡ cdf780b6-f1e8-11ea-2c90-bdae4d1dacaf\nM = [10i + j for i in 0:5, j in 1:4]\n\n# ╔═╡ 3464d66e-f1e9-11ea-0e53-e99f5c962594\nmd\"We can make slices and views of matrices using extensions of the syntax we saw above for vectors:\"\n\n# ╔═╡ 4f3451e0-f1e9-11ea-07b4-456c5a6fa4c5\nM[3:5, 1:2]\n\n# ╔═╡ 5cb68536-f1e9-11ea-272e-179f8dfe8acc\nview(M, 3:5, 1:2)\n\n# ╔═╡ 615a74ee-f1e9-11ea-1f71-3be78c5545b2\n@view M[3:5, 1:2]\n\n# ╔═╡ 670bbc0e-f1e9-11ea-01a1-93cb78e8cb90\nmd\"You should check that slices and views have the same behaviour that we described above.\"\n\n# ╔═╡ 94c85c38-f1e9-11ea-3ab8-976569b36e23\nmd\"## Reshaping matrices\"\n\n# ╔═╡ eb96a16a-f1e8-11ea-0398-1715aac5fb2d\nmd\"There's something else we would like to be able to do with matrices: **reshape** them. We can do so using the `reshape` function:\"\n\n# ╔═╡ 24cefdea-f1e9-11ea-3c37-c3626e555e4e\nM2 = reshape(M, 3, 8)\n\n# ╔═╡ c0dca20e-5d6f-11eb-16dc-efa62e027511\ntypeof(M2)\n\n# ╔═╡ c9e36c90-5d6f-11eb-0b8e-6538834cc678\nM2[1, 2] = 42\n\n# ╔═╡ dec30d50-5d6f-11eb-2b8a-6d3bb29422e4\nM\n\n# ╔═╡ e40f19c0-5d6f-11eb-3989-490c5629d307\nM2[2, 1] = 42\n\n# ╔═╡ 0a056c60-5d70-11eb-11fc-85569c278285\nM\n\n# ╔═╡ cae01608-f1e9-11ea-0878-a7b281aa6113\nmd\"(Note the order in which the elements were taken.)\"\n\n# ╔═╡ 2b3cbb88-f1e9-11ea-16f1-436de44841de\nmd\"Given the discussion so far, you are hopefully asking yourself: Is this a copy or a view? We'll leave it to you to find out!\"\n\n# ╔═╡ c36d3770-f1e9-11ea-2fa5-5ddb60c2adce\nmd\"Similarly, we might want to turn the matrix into a vector. For this we can use the `vec` function:\"\n\n# ╔═╡ ecb7395a-f1e9-11ea-2346-abbd7f1bd73e\nvv = vec(M)\n\n# ╔═╡ 663c99e0-5d70-11eb-3e33-0fa3b4241e9e\nvv[7] = 42\n\n# ╔═╡ 785615be-5d70-11eb-1089-236000da5068\nM\n\n# ╔═╡ f0eb9eaa-f1e9-11ea-1bd5-3f47ff24cbf6\nmd\"Again you should check if this is a copy or a view. The order of the elements here is showing us the **storage order** of a matrix, i.e. in which order in the (linear) memory inside the computer the elements of the 2D matrix are being stored.\"\n\n# ╔═╡ 648b17b6-f1e6-11ea-3351-23b46a2e265d\nmd\"## Summary\"\n\n# ╔═╡ 689e4c60-f1e6-11ea-3782-43decd275b5f\nmd\"In summary, we need to be aware of when we want to copy data from an array, and when we actually want to avoid copying and make views instead. A slice like `v[1:3]` makes a copy *unless* there's an `@view` or `@views` macro telling you otherwise.\n\nFor other operations like `reshape` and `vec` it's also critical to know if they make copies or views.\n\"\n\n# ╔═╡ Cell order:\n# ╟─330763c4-f1e2-11ea-071a-b13a3bea37e9\n# ╟─50e2aaa2-f1e2-11ea-37b2-9d23357ab558\n# ╟─614126a8-f1e2-11ea-08ef-3d787d155416\n# ╠═6d6e5194-f1e2-11ea-116c-c191e52dd2af\n# ╟─79332324-f1e2-11ea-3c82-39cad3d2391c\n# ╠═8b0fca3e-f1e2-11ea-2b70-011aaeeb94cc\n# ╟─8cbf61b6-f1e2-11ea-3b49-cb59792e1fc1\n# ╠═a87a0238-f1e2-11ea-272d-0d8cd4795df6\n# ╠═abbf2a72-f1e2-11ea-3e76-2bbe6e068c59\n# ╟─b0bafcae-f1e2-11ea-1c5a-a98c25cf6bd4\n# ╠═c8ec70ac-f1e2-11ea-30d6-7fc4e1f3cf63\n# ╟─d6903d5e-f1e2-11ea-1525-35f7f6aa2f66\n# ╟─7c447b7a-f1e3-11ea-0ef2-c996690ae871\n# ╟─cd2c8f1a-f1e2-11ea-1449-73d40f742c60\n# ╠═edec3322-f1e2-11ea-32b8-ebd1445b18e2\n# ╟─0ed6e116-f1e3-11ea-38ed-693262492cf2\n# ╠═446a93ba-f1e3-11ea-2957-e9c3bb7b66cd\n# ╟─4974c36c-f1e3-11ea-3543-63fce86af871\n# ╠═86be1e4e-f1e3-11ea-1212-6949dd55b8e8\n# ╟─887640e0-f1e3-11ea-2d35-a9a9d1ae1897\n# ╟─8d6fdcfa-f1e3-11ea-2f50-9783f4cd6339\n# ╠═9b504332-f1e3-11ea-35a2-8d33db468a83\n# ╠═a1685124-f1e3-11ea-396c-cd12b8cdfdbd\n# ╟─b6e74bf4-f1e3-11ea-1eab-7db865915fe8\n# ╟─c1562b4e-f1e3-11ea-2b73-0d18fc361323\n# ╠═d69da0d8-f1e3-11ea-092b-7b7e9fd262ce\n# ╟─afbeb970-f1e3-11ea-3658-c973f6808f6d\n# ╟─fc774f0c-f1e3-11ea-0e5a-3141ec04348d\n# ╟─ffa05138-f1e3-11ea-280e-bf7da83de269\n# ╟─12dbdf38-f1e4-11ea-0449-b39ed2f5f12d\n# ╠═1123aade-f1e4-11ea-3cce-4534d7a72a60\n# ╟─19ca7c32-f1e4-11ea-39a5-3dcf97e6fbcf\n# ╠═21a48678-f1e4-11ea-1143-c709ee295e0d\n# ╠═25abc85a-f1e4-11ea-156b-7f15f0474e3b\n# ╟─2765efc0-f1e4-11ea-1324-ede5df51f047\n# ╠═3eb46116-f1e4-11ea-29e9-c74e8478d803\n# ╟─4084ffca-f1e4-11ea-2d5d-abb022cd41cc\n# ╟─59e92208-f1e4-11ea-30a0-4d6d44bb9ae6\n# ╟─aa48f298-f1e4-11ea-19ef-f120e959faa4\n# ╟─addcc056-f1e4-11ea-0090-eb82f5545c37\n# ╠═f5cc5e80-f1e4-11ea-027c-9bef1852423d\n# ╟─218aa662-f1e5-11ea-1516-15ffd9c9ba08\n# ╠═2b955ddc-f1e5-11ea-1ca1-e91c81100478\n# ╠═3a957e84-f1e5-11ea-2131-21fdd5d8c5d5\n# ╟─3c96558c-f1e5-11ea-2109-79717714c977\n# ╠═4ed5d79a-f1e5-11ea-1515-3be1b3fa9a2b\n# ╟─50259ee6-f1e5-11ea-317b-11a542b6cd9e\n# ╟─ff65101a-f1e4-11ea-1b51-f5b09ae1f0eb\n# ╠═fbd656aa-f1e4-11ea-2de2-61abc56ea71d\n# ╟─0ab7d32e-f1e5-11ea-048b-a74d7515b0c5\n# ╟─781e93da-f1e5-11ea-3d3f-57842f69c032\n# ╟─83c8711a-f1e5-11ea-30c4-87104a7c1c2a\n# ╟─fb50b922-f1e5-11ea-0049-773084392b80\n# ╠═0d25ffae-f1e6-11ea-05c4-49b25532ae49\n# ╠═27c47f2a-f1e6-11ea-3aa2-bb05fcd0e566\n# ╠═2998132a-f1e6-11ea-3ccc-7951c392e9f3\n# ╠═2c010994-f1e6-11ea-0022-79d21e0764b8\n# ╟─2d6f84e2-f1e6-11ea-2683-8be3ea0d39ac\n# ╟─4ff57544-f1e6-11ea-0274-15cc7917c3e3\n# ╟─ba6e586c-f1e8-11ea-1aba-ab1ba56ace6d\n# ╟─f0753bec-f1e8-11ea-0776-99b556737a05\n# ╠═cdf780b6-f1e8-11ea-2c90-bdae4d1dacaf\n# ╟─3464d66e-f1e9-11ea-0e53-e99f5c962594\n# ╠═4f3451e0-f1e9-11ea-07b4-456c5a6fa4c5\n# ╠═5cb68536-f1e9-11ea-272e-179f8dfe8acc\n# ╠═615a74ee-f1e9-11ea-1f71-3be78c5545b2\n# ╟─670bbc0e-f1e9-11ea-01a1-93cb78e8cb90\n# ╟─94c85c38-f1e9-11ea-3ab8-976569b36e23\n# ╟─eb96a16a-f1e8-11ea-0398-1715aac5fb2d\n# ╠═24cefdea-f1e9-11ea-3c37-c3626e555e4e\n# ╠═c0dca20e-5d6f-11eb-16dc-efa62e027511\n# ╠═c9e36c90-5d6f-11eb-0b8e-6538834cc678\n# ╠═dec30d50-5d6f-11eb-2b8a-6d3bb29422e4\n# ╠═e40f19c0-5d6f-11eb-3989-490c5629d307\n# ╠═0a056c60-5d70-11eb-11fc-85569c278285\n# ╟─cae01608-f1e9-11ea-0878-a7b281aa6113\n# ╟─2b3cbb88-f1e9-11ea-16f1-436de44841de\n# ╟─c36d3770-f1e9-11ea-2fa5-5ddb60c2adce\n# ╠═ecb7395a-f1e9-11ea-2346-abbd7f1bd73e\n# ╠═663c99e0-5d70-11eb-3e33-0fa3b4241e9e\n# ╠═785615be-5d70-11eb-1089-236000da5068\n# ╟─f0eb9eaa-f1e9-11ea-1bd5-3f47ff24cbf6\n# ╟─648b17b6-f1e6-11ea-3351-23b46a2e265d\n# ╟─689e4c60-f1e6-11ea-3782-43decd275b5f\n", "meta": {"hexsha": "e58eb9a4a0bb0644a53d42a4ac560f8cdd7f4ed5", "size": 12658, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lecture_notebooks/week2/03-array_slices_and_views MvdV.jl", "max_stars_repo_name": "mathijsvdv/ComputationalThinking", "max_stars_repo_head_hexsha": "a69af04a4fee4427eb2c52edc26d9528addf850e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lecture_notebooks/week2/03-array_slices_and_views MvdV.jl", "max_issues_repo_name": "mathijsvdv/ComputationalThinking", "max_issues_repo_head_hexsha": "a69af04a4fee4427eb2c52edc26d9528addf850e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lecture_notebooks/week2/03-array_slices_and_views MvdV.jl", "max_forks_repo_name": "mathijsvdv/ComputationalThinking", "max_forks_repo_head_hexsha": "a69af04a4fee4427eb2c52edc26d9528addf850e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.870523416, "max_line_length": 296, "alphanum_fraction": 0.7380312846, "num_tokens": 6543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942377652497, "lm_q2_score": 0.9184802501617066, "lm_q1q2_score": 0.8177176742201525}} {"text": "# Multinomial theorem\n# https://en.wikipedia.org/wiki/Multinomial_theorem\n\nexport multiexponents\n\nstruct MultiExponents{T}\n c::T\n nterms::Int\nend\n\n# Standard stars and bars:\n# https://en.wikipedia.org/wiki/Stars_and_bars_(combinatorics)\nfunction Base.iterate(m::MultiExponents, s = nothing)\n next = s === nothing ? iterate(m.c) : iterate(m.c, s)\n next === nothing && return\n stars, ss = next\n\n # stars minus their consecutive\n # position becomes their index\n result = zeros(Int, m.nterms)\n for (i, s) in enumerate(stars)\n result[s-i+1] += 1\n end\n\n result, ss\nend\n\nBase.length(m::MultiExponents) = length(m.c)\n\n\"\"\"\n multiexponents(m, n)\n\nReturns the exponents in the multinomial expansion (x₁ + x₂ + ... + xₘ)ⁿ.\n\nFor example, the expansion (x₁ + x₂ + x₃)² = x₁² + x₁x₂ + x₁x₃ + ...\nhas the exponents:\n\n julia> collect(multiexponents(3, 2))\n\n 6-element Array{Any,1}:\n [2, 0, 0]\n [1, 1, 0]\n [1, 0, 1]\n [0, 2, 0]\n [0, 1, 1]\n [0, 0, 2]\n\"\"\"\nfunction multiexponents(m, n)\n # number of stars and bars = m+n-1\n c = combinations(1:m+n-1, n)\n\n MultiExponents(c, m)\nend\n", "meta": {"hexsha": "c3e5426ae26c1fd18534cd406047eb1ab2788799", "size": 1140, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/multinomials.jl", "max_stars_repo_name": "Sedictious/Combinatorics.jl", "max_stars_repo_head_hexsha": "fa6c6a893ad5a419ffa56b3aacf64c1053cbc507", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 165, "max_stars_repo_stars_event_min_datetime": "2016-09-13T17:00:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T02:29:52.000Z", "max_issues_repo_path": "src/multinomials.jl", "max_issues_repo_name": "Sedictious/Combinatorics.jl", "max_issues_repo_head_hexsha": "fa6c6a893ad5a419ffa56b3aacf64c1053cbc507", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 86, "max_issues_repo_issues_event_min_datetime": "2016-08-25T18:09:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T12:58:42.000Z", "max_forks_repo_path": "src/multinomials.jl", "max_forks_repo_name": "Sedictious/Combinatorics.jl", "max_forks_repo_head_hexsha": "fa6c6a893ad5a419ffa56b3aacf64c1053cbc507", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 49, "max_forks_repo_forks_event_min_datetime": "2016-10-29T00:18:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T10:21:39.000Z", "avg_line_length": 21.1111111111, "max_line_length": 73, "alphanum_fraction": 0.6192982456, "num_tokens": 389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750360641186, "lm_q2_score": 0.8577681104440172, "lm_q1q2_score": 0.8176889264181714}} {"text": "using LightGraphs, SimpleWeightedGraphs, LinearAlgebra\n\"\"\"\n SunFlowerGraph(; N = 400)\n\nSUNFLOWERGRAPH construct a simple weighted sunflower graph with N vertices. Edge weights are the reciprocal of Euclidean distances.\n\n# Input Arguments\n- `N::Int64`: default is 400, the number of vertices. Requires N > 26.\n\n# Output Argument\n- `G::SimpleWeightedGraph{Int64,Float64}`: a simple weighted graph of the sunflower.\n- `L::Matrix{Float64}`: the weighted unnormalized graph Laplacian matrix.\n- `X::Matrix{Float64}`: a matrix whose i-th row represent the 2D coordinates of the i-th node.\n\n\"\"\"\nfunction SunFlowerGraph(; N = 400)\n c=1.0/N; θ=(sqrt(5.0)-1)*π;\n X = zeros(N,2); for k=1:N X[k,:]=c*(k-1)*[cos((k-1)*θ) sin((k-1)*θ)]; end\n\n G = SimpleWeightedGraph(N)\n for k = 2:8\n G.weights[1,k] = 1/norm(X[1,:] - X[k,:])\n G.weights[k,1] = 1/norm(X[1,:] - X[k,:])\n end\n\n for k = 1:N\n if k+8 <= N\n G.weights[k,k+8] = 1/norm(X[k,:] - X[k+8,:])\n G.weights[k+8,k] = 1/norm(X[k,:] - X[k+8,:])\n end\n if k+13 <= N\n G.weights[k,k+13] = 1/norm(X[k,:] - X[k+13,:])\n G.weights[k+13,k] = 1/norm(X[k,:] - X[k+13,:])\n end\n end\n W = weights(G) #weighted adjacency_matrix\n Lw = Diagonal(sum(W, dims = 2)[:]) - W #weighted laplacian_matrix\n return G, Lw, X\nend\n", "meta": {"hexsha": "b0f515f779990e44c40ad327a6b14deffeeb1ee5", "size": 1351, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SunFlowerGraph.jl", "max_stars_repo_name": "BoundaryValueProblems/MTSG.jl", "max_stars_repo_head_hexsha": "8cf8e2b3035876b5ceda45109b0847a60b581a7c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-02T18:39:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-19T15:45:17.000Z", "max_issues_repo_path": "src/SunFlowerGraph.jl", "max_issues_repo_name": "haotian127/MultiscaleGraphSignalTransforms.jl", "max_issues_repo_head_hexsha": "85ba99e505283491ac69e979737bbb712b698a6e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2021-04-27T23:00:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-03T11:03:17.000Z", "max_forks_repo_path": "src/SunFlowerGraph.jl", "max_forks_repo_name": "haotian127/MultiscaleGraphSignalTransforms.jl", "max_forks_repo_head_hexsha": "85ba99e505283491ac69e979737bbb712b698a6e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-04-24T21:46:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-05T04:32:31.000Z", "avg_line_length": 33.775, "max_line_length": 131, "alphanum_fraction": 0.5862324204, "num_tokens": 466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620539235895, "lm_q2_score": 0.8519528038477825, "lm_q1q2_score": 0.8176719728669086}} {"text": "function tau(n::Integer)::Integer\n ans = 0\n for i = 1:n\n if n % i == 0\n ans = 1 + ans\n end\n end\n return ans\nend\n\nτf = tau\n\nfunction sigma(n::Integer)::Integer\n ans = 0\n for i = 1:n\n if n % i == 0\n ans = i + ans\n end\n end\n return ans\nend\n\nσf = sigma\n\nfunction s(n::Integer)::Integer\n return sigma(n) - n\nend\n\n# Adding cache to this function can make thing easier\nfunction getMappingFromSFunction(n::Integer)::Array{Bool}\n sn = s(n)\n mappingSofNProperty = [sn < n, sn == n, sn > n]\n return mappingSofNProperty\nend\n\nfunction isDeficient(n::Integer)::Bool\n return getMappingFromSFunction(n)[1]\nend\n\nfunction isPerfect(n::Integer)::Bool\n return getMappingFromSFunction(n)[2]\nend\n\nfunction isAbundant(n::Integer)::Bool\n return getMappingFromSFunction(n)[3]\nend\n\n# Including N\nfunction pic(n::Integer)::Integer\n numberOfPrimesTillN = 0\n for i = 2:n\n isPrime = true\n for j = 1:i\n if (i % j == 0 && i != j) || j == 1\n isPrime = false\n break\n end\n end\n if isPrime\n numberOfPrimesTillN += 1\n end\n end\n return numberOfPrimesTillN\nend\n\n# Not Including N\nfunction pi(n::Integer)::Integer\n numberOfPrimesTillN = 0\n for i = 2:n-1\n isPrime = true\n for j = 2:i\n if (i % j == 0 && i != j)\n isPrime = false\n break\n end\n end\n if isPrime && (i != n - 1)\n numberOfPrimesTillN += 1\n end\n end\n return numberOfPrimesTillN\nend\n\nπf = pi\nπfc = pic\n\nfunction 𝞋(n::Integer)::Float64\n value = 0.0\n for i = 2:n\n isPrime = true\n for j = 2:i\n if (i % j == 0 && i != j)\n isPrime = false\n break\n end\n end\n if isPrime && (i != n - 1)\n value += log(ℯ, p)\n end\n end\n return value\nend\n\nchebyshev_theta = 𝞋\n\nfunction ψ(n::Integer)::Float64\n value = 0.00\n for p = 2:n\n isPrime = true\n for j = 2:p\n if (p % j == 0 && p != j)\n isPrime = false\n break\n end\n end\n if isPrime\n pk = p^1\n sum = 0.0\n while pk <= n\n sum += log(ℯ, p)\n pk *= p\n println(\"ln $p\")\n end\n value += sum\n end\n end\n return value\nend\n\nchebyshev_psi = ψ", "meta": {"hexsha": "f7f25ac5a6f651e983e1d3e38d1c5c543c9681a1", "size": 2497, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions.jl", "max_stars_repo_name": "EllianCarlos/number-theory-but-in-julia", "max_stars_repo_head_hexsha": "74368fee8002bc53031b8ef6026e72f806efe84d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functions.jl", "max_issues_repo_name": "EllianCarlos/number-theory-but-in-julia", "max_issues_repo_head_hexsha": "74368fee8002bc53031b8ef6026e72f806efe84d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions.jl", "max_forks_repo_name": "EllianCarlos/number-theory-but-in-julia", "max_forks_repo_head_hexsha": "74368fee8002bc53031b8ef6026e72f806efe84d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.2076923077, "max_line_length": 57, "alphanum_fraction": 0.4845814978, "num_tokens": 759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947117065459, "lm_q2_score": 0.8652240964782011, "lm_q1q2_score": 0.8176321956129743}} {"text": "\"\"\"\n lagrange_polynomials(nodes::Array{Float64, 1}, evalPt::Float64)\n\nEvaluate the lagrange interpolating polynomials defied by `nodes` at the point `evalPt`.\n\"\"\"\nfunction lagrange_polynomials(nodes::Array{Float64,1}, evalPt::Float64)\n order = length(nodes)\n poly_coefs = zeros(order)\n if order > 1\n for n in 1:order\n notn = [1:n-1;n+1:order]\n poly_coefs[n] = prod(evalPt.-nodes[notn])./prod(nodes[n].-nodes[notn])\n end\n else \n poly_coefs = [1.0]\n end\n return poly_coefs\nend\n\n\"\"\"\n gauss_lobatto_points(a::Float64, b::Float64, n_evals::Int)\n\nReturn array containing `n_evals` gauss lobatto points in the interval `[a,b]`.\n\"\"\"\nfunction gauss_lobatto_points(a::Float64,b::Float64,n_evals::Int)\n (b 0\"))\n if n_evals > 1\n # the GL nodes\n # nodes in [-1,1]\n nodes = Jacobi.zglj(n_evals, 0, 0)\n # shift nodes to [a,b]\n nodes *= 0.5*(b-a)\n nodes .+= 0.5*(a+b)\n else\n nodes = [0.5*(a+b)]\n end\n return nodes\nend\n\n\"\"\"\n gauss_lobatto_weights(a::Float64, b::Float64, n_evals::Int)\n\nReturn array containing `n_evals` weights of the polynomials associated with the\ngauss lobatto points in the interval `[a,b]`. i.e. the itegrals over the interval `[a,b]` \nof the lagrange polynomials defined by the nodes given by `nodes = gauss_lobatto_points(a,b,n_evals)`\n\"\"\"\nfunction gauss_lobatto_weights(a::Float64,b::Float64,n_evals::Int)\n (b 0\"))\n if n_evals > 1\n nodes = Jacobi.zglj(n_evals, 0, 0)\n weights = Jacobi.wglj(nodes,0,0)*(b-a)/2.0\n else\n weights = [(b-a)]\n end\n return weights\nend\n\n\"\"\"\n lagrange_interpolation(fun::Function, a::Float64, b::Float64, n_evals::Int)\n\nReturn a polynomial approximation to `fun` of order `n_evals-1` on the interval `[a,b]` using \nthe `gauss_lobatto_points` as the nodes of the lagrange polynomials.\n\"\"\"\nfunction lagrange_interpolation(fun::Function,a::Float64,b::Float64,n_evals::Int)\n nodes = gauss_lobatto_points(a,b,n_evals)\n \n fun_vals = fun.(nodes)\n interpolant(x) = LinearAlgebra.dot(fun_vals,lagrange_polynomials(nodes,x))\n return interpolant\nend\n\n\"\"\"\n gauss_lobatto_quadrature(fun::Function, a::Float64, b::Float64, n_evals::Int)\n\nCompute a quadrature approximation of `fun` on the interval `[a,b]` with `n_evals` function \nevaluations using the `gauss_lobatto_points`\n\"\"\"\nfunction gauss_lobatto_quadrature(fun::Function,a::Float64,b::Float64,n_evals::Int)\n nodes = gauss_lobatto_points(a,b,n_evals)\n weights = gauss_lobatto_weights(a,b,n_evals)\n fun_vals = fun.(nodes)\n quad = LinearAlgebra.dot(fun_vals,weights)\n \n return quad\nend\n\"\"\"\n gauss_lobatto_quadrature(fun::Function, nodes::Array{Float64,1})\n\nCompute a quadrature approximation of `fun` on the interval `nodes[1]` to `nodes[end]`\nevaluating the function `fun` at `nodes`\n\"\"\"\nfunction gauss_lobatto_quadrature(fun::Function,nodes::Array{Float64,1})\n weights = gauss_lobatto_weights(a,b,length(nodes))\n fun_vals = fun.(nodes)\n quad = LinearAlgebra.dot(fun_vals,weights)\n \n return quad\nend\n\n\"\"\"\nConstruct a generalised vandermonde matrix.\n\n vandermonde( nBases::Int)\n\nNote: requires Jacobi package Pkg.add(\"Jacobi\")\n\n# Arguments\n- `nBases::Int`: the degree of the basis\n\n# Output\n- a tuple with keys\n - `:V::Array{Float64,2}`: where `:V[:,i]` contains the values of the `i`th\n legendre polynomial evaluate at the GLL nodes.\n - `:inv`: the inverse of :V\n - `:D::Array{Float64,2}`: where `V.D[:,i]` contains the values of the derivative\n of the `i`th legendre polynomial evaluate at the GLL nodes.\n\"\"\"\nfunction vandermonde(nBases::Int)\n if nBases > 1\n z = Jacobi.zglj(nBases, 0, 0) # the LGL nodes\n elseif nBases == 1\n z = 0.0\n end\n V = zeros(Float64, nBases, nBases)\n DV = zeros(Float64, nBases, nBases)\n if nBases > 1\n for j = 1:nBases\n # compute the polynomials at gauss-labotto quadrature points\n V[:, j] = Jacobi.legendre.(z, j - 1) .* sqrt((2 * (j - 1) + 1) / 2)\n DV[:, j] = Jacobi.dlegendre.(z, j - 1) .* sqrt((2 * (j - 1) + 1) / 2)\n end\n # Compute the Gauss-Lobatto weights for numerical quadrature\n w =\n 2.0 ./ (\n nBases *\n (nBases - 1) *\n Jacobi.legendre.(Jacobi.zglj(nBases, 0, 0), nBases - 1) .^ 2\n )\n elseif nBases == 1\n V .= [1.0/sqrt(2)]\n DV .= [0.0]\n w = [2.0]\n end\n return (V = V, inv = inv(V), D = DV, w = w)\nend\n\nfunction legendre_to_lagrange(coeffs::Vector{Float64})\n order = length(coeffs)\n V = vandermonde(order)\n return V.V*coeffs\nend\n\nfunction lagrange_to_legendre(coeffs::Vector{Float64})\n order = length(coeffs)\n V = vandermonde(order)\n return V.inv*coeffs\nend\n\nfunction legendre_to_lagrange(coeffs::Array{Float64,3})\n order = size(coeffs,1)\n V = vandermonde(order)\n for i in 1:size(coeffs,3)\n coeffs[:,:,i] = V.V*coeffs[:,:,i]\n end\n return coeffs\nend\n\nfunction lagrange_to_legendre(coeffs::Array{Float64,3})\n order = size(coeffs,1)\n V = vandermonde(order)\n for i in 1:size(coeffs,3)\n coeffs[:,:,i] = V.inv*coeffs[:,:,i]\n end\n return coeffs\nend", "meta": {"hexsha": "b634e4f73aad198f72e181fb0e9f95204ab1a69c", "size": 5446, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/polynomials.jl", "max_stars_repo_name": "angus-lewis/DiscretisedFluidQueues.jl", "max_stars_repo_head_hexsha": "aa60fa272b61c088695dd29a2fe768fd2f375378", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/polynomials.jl", "max_issues_repo_name": "angus-lewis/DiscretisedFluidQueues.jl", "max_issues_repo_head_hexsha": "aa60fa272b61c088695dd29a2fe768fd2f375378", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/polynomials.jl", "max_forks_repo_name": "angus-lewis/DiscretisedFluidQueues.jl", "max_forks_repo_head_hexsha": "aa60fa272b61c088695dd29a2fe768fd2f375378", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7683615819, "max_line_length": 101, "alphanum_fraction": 0.6391847227, "num_tokens": 1709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947132556618, "lm_q2_score": 0.8652240947405565, "lm_q1q2_score": 0.8176321953112418}} {"text": "doc\"\"\"\r\napply Hodrick-Prescott filter to `AbstractVector`.\r\n\r\n##### Arguments\r\n- `y::AbstractVector` : data to be detrended\r\n- `λ::Real` : penalty on variation in trend\r\n\r\n##### Returns\r\n- `y_cyclical::Vector`: cyclical component\r\n- `y_trend::Vector`: trend component\r\n\"\"\"\r\nfunction hp_filter(y::AbstractVector{T}, λ::Real) where T <: Real\r\n y = Vector(y)\r\n N = length(y)\r\n H = spdiagm(-2 => fill(λ, N-2),\r\n -1 => vcat(-2λ, fill(-4λ, N - 3), -2λ),\r\n 0 => vcat(1 + λ, 1 + 5λ, fill(1 + 6λ, N-4),\r\n 1 + 5λ, 1 + λ),\r\n 1 => vcat(-2λ, fill(-4λ, N - 3), -2λ),\r\n 2 => fill(λ, N-2))\r\n y_trend = H \\ y\r\n y_cyclical = y - y_trend\r\n return y_cyclical, y_trend\r\nend\r\n\r\ndoc\"\"\"\r\nThis function applies \"Hamilton filter\" to `AbstractVector`.\r\n\r\nhttp://econweb.ucsd.edu/~jhamilto/hp.pdf\r\n\r\n##### Arguments\r\n- `y::AbstractVector` : data to be filtered\r\n- `h::Integer` : Time horizon that we are likely to predict incorrectly.\r\n Original paper recommends 2 for annual data, 8 for quarterly data,\r\n 24 for monthly data.\r\n- `p::Integer` : Number of lags in regression. Must be greater than `h`.\r\nNote: For seasonal data, it's desirable for `p` and `h` to be integer multiples\r\n of the number of obsevations in a year.\r\n e.g. For quarterly data, `h = 8` and `p = 4` are recommended.\r\n##### Returns\r\n- `y_cycle::Vector` : cyclical component\r\n- `y_trend::Vector` : trend component\r\n\"\"\"\r\nfunction hamilton_filter(y::AbstractVector, h::Integer, p::Integer)\r\n y = Vector(y)\r\n T = length(y)\r\n y_cycle = fill(NaN, T)\r\n\r\n # construct X matrix of lags\r\n X = ones(T-p-h+1)\r\n for j = 1:p\r\n X = hcat(X, y[p-j+1:T-h-j+1])\r\n end\r\n\r\n # do OLS regression\r\n b = (X'*X)\\(X'*y[p+h:T])\r\n y_cycle[p+h:T] = y[p+h:T] - X*b\r\n y_trend = vcat(fill(NaN, p+h-1), X*b)\r\n return y_cycle, y_trend\r\nend\r\n\r\ndoc\"\"\"\r\nThis function applies \"Hamilton filter\" to `<:AbstractVector`\r\nunder random walk assumption.\r\n\r\nhttp://econweb.ucsd.edu/~jhamilto/hp.pdf\r\n\r\n##### Arguments\r\n- `y::AbstractVector` : data to be filtered\r\n- `h::Integer` : Time horizon that we are likely to predict incorrectly.\r\n Original paper recommends 2 for annual data, 8 for quarterly data,\r\n 24 for monthly data.\r\nNote: For seasonal data, it's desirable for `h` to be an integer multiple\r\n of the number of obsevations in a year.\r\n e.g. For quarterly data, `h = 8` is recommended.\r\n##### Returns\r\n- `y_cycle::Vector` : cyclical component\r\n- `y_trend::Vector` : trend component\r\n\"\"\"\r\nfunction hamilton_filter(y::AbstractVector, h::Integer)\r\n y = Vector(y)\r\n T = length(y)\r\n y_cycle = fill(NaN, T)\r\n y_cycle[h+1:T] = y[h+1:T] - y[1:T-h]\r\n y_trend = y - y_cycle\r\n return y_cycle, y_trend\r\nend\r\n", "meta": {"hexsha": "5475d43c154a089a61117a82a2a6e8c10e53500e", "size": 2856, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/filter.jl", "max_stars_repo_name": "femtotrader/QuantEcon.jl", "max_stars_repo_head_hexsha": "785c71b99b04c49c8638d499591584c1e33f3745", "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/filter.jl", "max_issues_repo_name": "femtotrader/QuantEcon.jl", "max_issues_repo_head_hexsha": "785c71b99b04c49c8638d499591584c1e33f3745", "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/filter.jl", "max_forks_repo_name": "femtotrader/QuantEcon.jl", "max_forks_repo_head_hexsha": "785c71b99b04c49c8638d499591584c1e33f3745", "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.4545454545, "max_line_length": 84, "alphanum_fraction": 0.5899859944, "num_tokens": 860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947070591977, "lm_q2_score": 0.8652240947405564, "lm_q1q2_score": 0.8176321899499116}} {"text": "# 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.\n#\n# What is the sum of the digits of the number 2^1000?\n\nusing ProjectEulerSolutions\n\n# Simple with Julia's built-in BigInt and the digits function.\nfunction p016solution(mantissa::Integer=2, exponent::Integer=3)::Integer\n return sum(digits(BigInt(mantissa) ^ exponent))\nend\n\np016 = Problems.Problem(p016solution)\n\nProblems.benchmark(p016, 2, 1000)", "meta": {"hexsha": "c1bbea67464d3e87f774ed402f737c1d23a4071a", "size": 419, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/016.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/016.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/016.jl", "max_forks_repo_name": "gnujosh/julia-euler-project", "max_forks_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9285714286, "max_line_length": 72, "alphanum_fraction": 0.7326968974, "num_tokens": 132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947163538936, "lm_q2_score": 0.8652240860523328, "lm_q1q2_score": 0.8176321897815811}} {"text": "######### function for a sigmoid curve\n### dose input\n# x is a vector of concentrations\n### parameters for a sigmoid curve \n# slope \n# upper asymptote (fixed)\n# lower asymptote (varying)\n# inflection point (xmid)\n\nfunction log_logistic(upper = 1.0; dose, slope::Float64, lower::Float64, xmid::Float64)\n num = upper - lower\n denom = 1 .+ ((dose ./ xmid) .^ slope)\n return lower .+ num ./ denom\nend\n\ndoses = [0:1:100.0;]\n\n# example to test \nresponses = log_logistic(dose = doses, slope = 5.0, lower = 0.0, xmid = 50.0)\nplot(doses, responses, ylim = 1.0, label = \"b=5, c=0, d=1, e=50\")\n\n\n\n### Vary slope ###\nplt1 = plot([NaN], [NaN], label = \"\", title = \"Varying slopes\", xlabel = \"dose\", ylabel = \"response\")\n\n# range of slope values\nslopes = [4.0, 8.0, 16.0, 32.0, 64.0]\nfor sl in slopes\n responses = log_logistic(dose = doses, slope = sl, lower = 0.0, xmid = 50.0)\n plot!(doses, responses, label = \"$sl\")\nend\nplt1\n\n### Vary asymptote\nplt2 = plot([NaN], [NaN], label = \"\", title = \"Varying asymptotes\"\n, xlabel = \"dose\", ylabel = \"response\")\n\n# range of asymptote values\nasymptotes = [0.0, 0.1, 0.2, 0.3, 0.4]\nfor as in asymptotes\n responses = log_logistic(dose = doses, slope = 8.0, lower = as, xmid = 50.0)\n plot!(doses, responses, label = \"$as\")\nend\nplt2\n\n\n### Vary inflection point\nplt3 = plot([NaN], [NaN], label = \"\", title = \"Varying inflection points\"\n, xlabel = \"dose\", ylabel = \"response\")\n\n# range of xmid values\ninflections = [20.0, 30.0, 40.0, 50.0, 60.0]\nfor infl in inflections\n responses = log_logistic(dose = doses, slope = 8.0, lower = 0.0, xmid = infl)\n plot!(doses, responses, label = \"$infl\")\nend\nplt3\n\nplot(plt1, plt2, plt3)\n\n### loop for high low combos\nplt4 = plot([NaN], [NaN], label = \"\", title = \"High/low parameters\")\n\nslopes2 = [5.0, 50.0]\nasymps2 = [0.0, 0.5]\ninflex2 = [10.0, 50.0]\n\nfor b in slopes2\n for d in asymps2\n for e in inflex2\n responses = log_logistic(dose = doses, slope = b, lower = d, xmid = e)\n plot!(doses, responses, label = \"b = $b, d = $d, e = $e\")\n end\n end\nend\nplt4 \n\n\n\n# function Hill_equation(; dose::Vector{Float64}, slope::Float64, asym::Float64, xmid::Float64)\n# xb = dose .^ (-slope)\n# num = (1-asym) .* xb\n# denom = xb .+ (xmid .^ (-slope))\n# sigmoid = num ./ denom \n# return sigmoid \n# end\n\n# responses = Hill_equation(x = doses, slope = 10.0, asym = 1.0, xmid = 30.0)\n# plot(doses, responses, ylim = 1.0)", "meta": {"hexsha": "63fb8f4db515957c9950bd1c29b5e13b1597c962", "size": 2452, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "dose_response.jl", "max_stars_repo_name": "hanamayall/simple-feeding-DR", "max_stars_repo_head_hexsha": "10905fbf6f1cb1e5c8145ae9762e3f7ce768cd27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dose_response.jl", "max_issues_repo_name": "hanamayall/simple-feeding-DR", "max_issues_repo_head_hexsha": "10905fbf6f1cb1e5c8145ae9762e3f7ce768cd27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dose_response.jl", "max_forks_repo_name": "hanamayall/simple-feeding-DR", "max_forks_repo_head_hexsha": "10905fbf6f1cb1e5c8145ae9762e3f7ce768cd27", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2444444444, "max_line_length": 101, "alphanum_fraction": 0.6109298532, "num_tokens": 885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947101574299, "lm_q2_score": 0.865224091265267, "lm_q1q2_score": 0.8176321893464467}} {"text": "using ForwardDiff, Roots, Plots, LinearAlgebra, Optim\n\nfunction backtracking_line_search(f, ∇f, x, d, α; p=0.5, β=0.1)\n y, g = f(x), ∇f(x)\n aux = 0\n while f(x + α*d) > y + β*α*(g'⋅d)\n α *= p\n aux = α\n end\n α\n return aux\nend\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))\nbeta = 0.1\nalpha_f = 1.0\n\nphi(alpha) = f(xk+alpha*dk)\nd_phi(alpha) = grad_f(xk+alpha*dk)'dk\nl_alpha(alpha) = phi(0)+alpha*beta*d_phi(0)\n\n#condicao de Armijo\narmj = []\nfor alpha = 0:0.01:alpha_f\n if phi(alpha) <= l_alpha(alpha)\n push!(armj,alpha)\n end\nend\n\n#Armijo com Backtracking \narmjbt = backtracking_line_search(f,grad_f,xk,dk,alpha_f)\n\nplot(phi,0,alpha_f,lw=2,lab=\"phi\")\nplot!(l_alpha,0,alpha_f,lw=2,lab=\"L_phi\",c=:black)\nscatter!(armj,phi.(armj),lab=\"Armijo\",ms=3,c=:red)\nscatter!([armjbt],[phi(armjbt)],lab=\"Armijo - BT\",c=:yellow)\nplot!(legend=:outerbottomright)\nplot!(title=\"beta = 0.1\",xlabel = \"alpha\", ylabel = \"phi(alpha), l_alpha(alpha\")", "meta": {"hexsha": "b99909956569d870fd9d082ecaa21ae292939c18", "size": 1119, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "armijo.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": "armijo.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": "armijo.jl", "max_forks_repo_name": "GilbertoLucas/Structural_Optimization", "max_forks_repo_head_hexsha": "e12ed13bbb97db275d79a0e5bfcad6438a643441", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8666666667, "max_line_length": 80, "alphanum_fraction": 0.6219839142, "num_tokens": 451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947086083138, "lm_q2_score": 0.8652240773641088, "lm_q1q2_score": 0.8176321748695932}} {"text": "function ffdiff(f::Function, x1::Number, h::Number)\n # Estimates the derivative of a function using a forward finite difference\n # approximation\n (f(x1 + h) - f(x1)) / (x1+h - x1);\nend\n\nfunction bfdiff(f::Function, x1::Number, h::Number)\n # Estimates the derivative of a function using a backwards finite difference\n # approximation\n (f(x1) - f(x1-h)) / (x1 + h - x1);\nend\n\nfunction cfdiff(f::Function, x1::Number, h::Number)\n # Estimates the derivative of a function using a centred finite difference\n # approximation \n (f(x1 + h) - f(x1 - h)) / 2(x1 + h - x1);\nend", "meta": {"hexsha": "d9e436cc61d0a09ca94b4960b49f273c053fd27d", "size": 577, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/Differentiation/differentiation.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/Differentiation/differentiation.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/Differentiation/differentiation.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": 33.9411764706, "max_line_length": 78, "alphanum_fraction": 0.6724436742, "num_tokens": 181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561712637256, "lm_q2_score": 0.8438951104066295, "lm_q1q2_score": 0.817612985616746}} {"text": "@doc raw\"\"\"\n SIR(du,u,p,t)\n\nDefine classic SIR(suspected-infected-recovered) model. \n\nParameters: (birth rate, natural death rate, disaese induced death rate, population, infection rate, recovery rate)\n\n```math\n\\begin{aligned}\n& \\frac{\\rm{d}S}{\\rm{dt}} = \\Lambda -\\beta S I/N - d S,\\\\\n&\\frac{\\rm{d}I}{\\rm{dt}} = \\beta S I/N - \\gamma I - d I - \\alpha I,\\\\\n&\\frac{\\rm{d}R}{\\rm{dt}} = \\gamma I - d R,\\\\\n\\end{aligned}\n```\n\"\"\"\nfunction SIRbasic(du, u, p, t)\n Λ, d, α, N, β, γ = p\n pop = (Λ > 0 & d > 0) ? Λ / d : N\n S, I, R = u\n du[1] = Λ - β * S * I / pop - d * S\n du[2] = β * S * I / pop - γ * I - d * I - α * I\n du[3] = γ * I - d * R\nend\n\n\n@doc raw\"\"\"\n SEIR(du,u,p,t)\n\nDefine classic SEIR(suspected-exposed-infected-recovered) model. \n\nParameters: (birth rate, natural death rate, disaese induced death rate, population, infection rate, recovery rate, incubation period,\nexposed decreasing infection ratio)\n\n```math\n\\begin{aligned}\n& \\frac{\\rm{d}S}{\\rm{dt}} = \\Lambda -\\beta S (I+k_{E}E)/N - d S,\\\\\n&\\frac{\\rm{d}E}{\\rm{dt}} = \\beta S (I+k_{E}E)/N - \\sigma E -d E,\\\\\n&\\frac{\\rm{d}I}{\\rm{dt}} =\\sigma E - \\gamma I - d I - \\alpha I,\\\\\n&\\frac{\\rm{d}R}{\\rm{dt}} = \\gamma I - d R,\\\\\n\\end{aligned}\n```\n\"\"\"\nfunction SEIRbasic(du, u, p, t)\n Λ, d, α, N, β, γ, σ, ke = p\n pop = (Λ > 0 & d > 0) ? Λ / d : N\n S, E, I, R = u\n du[1] = Λ - β * S * (I + ke * E) / pop - d * S\n du[2] = β * S * (I + ke * E) / pop - σ * E - d * E\n du[3] = σ * E - γ * I - d * I - α * I\n du[4] = γ * I - d * R\nend\n\n@doc raw\"\"\"\n SEIAR(du,u,p,t)\n\nDefine classic SEIR(suspected-exposed-infected-asymptomatic-recovered) model. \n\nParameters: (birth rate, natural death rate, disaese induced death rate, population, infection rate, recovery rate, incubation period,\nexposed decreasing infection ratio, asymptomatic infection decreasing infection ratio, asymptomatic rate,recovery rate of asymptomatic)\n\n```math\n\\begin{aligned}\n& \\frac{\\rm{d}S}{\\rm{dt}} = \\Lambda -\\beta S (I+k_{E}E+k_{A}A)/N - d S,\\\\\n&\\frac{\\rm{d}E}{\\rm{dt}} = \\beta S (I+k_{E}E++k_{A}A)/N - \\sigma E -d E,\\\\\n&\\frac{\\rm{d}I}{\\rm{dt}} =(1-\\rho)\\sigma E - \\gamma I - d I - \\alpha I,\\\\\n&\\frac{\\rm{d}A}{\\rm{dt}} =\\rho\\sigma E - \\gamma_{A} A - d A,\\\\\n&\\frac{\\rm{d}R}{\\rm{dt}} = \\gamma I +\\gamma_{A} A - d R,\\\\\n\\end{aligned}\n```\n\"\"\"\nfunction SEIARbasic(du, u, p, t)\n Λ, d, α, N, β, γ, σ, ke, ka, ρ, γA= p\n pop = (Λ > 0 & d > 0) ? Λ / d : N\n S, E, I, A, R = u\n du[1] = Λ - β * S * (I + ke * E + ka * A) / pop - d * S\n du[2] = β * S * (I + ke * E + ka * A) / pop - σ * E - d * E\n du[3] = (1-ρ)*σ * E - γ * I - d * I - α * I\n du[3] = ρ * σ * E - γA * A - d * A\n du[4] = γ * I + γA * A - d * R\nend\n\n@doc raw\"\"\"\n SIS(du,u,p,t)\n\nDefine classic SIR(suspected-infected-suspected) model. \n\nParameters: (population, infection rate, recovery rate)\n\n```math\n\\begin{aligned}\n& \\frac{\\rm{d}S}{\\rm{dt}} = -\\beta S I/N + \\gamma I,\\\\\n&\\frac{\\rm{d}I}{\\rm{dt}} = \\beta S I/N - \\gamma I,\\\\\n\\end{aligned}\n```\n\"\"\"\nfunction SISbasic(du, u, p, t)\n pop, β, γ = p\n S, I = u\n du[1] = - β * S * I / pop + γ * I\n du[2] = β * S * I / pop - γ * I \nend", "meta": {"hexsha": "c6e772733e52ce16d431d641f8697f2ef89db80e", "size": 3128, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Models/odecompartmentsmodel.jl", "max_stars_repo_name": "Song921012/MathepiaModels.jl", "max_stars_repo_head_hexsha": "d70d9c249534c1d0af00bb135ce62237e29cf260", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-22T13:16:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-22T13:16:34.000Z", "max_issues_repo_path": "src/Models/odecompartmentsmodel.jl", "max_issues_repo_name": "Song921012/MathepiaModels.jl", "max_issues_repo_head_hexsha": "d70d9c249534c1d0af00bb135ce62237e29cf260", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-11-19T20:40:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-22T23:12:27.000Z", "max_forks_repo_path": "src/Models/odecompartmentsmodel.jl", "max_forks_repo_name": "Song921012/MathepiaModels.jl", "max_forks_repo_head_hexsha": "d70d9c249534c1d0af00bb135ce62237e29cf260", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9702970297, "max_line_length": 135, "alphanum_fraction": 0.5287723785, "num_tokens": 1344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561658682131, "lm_q2_score": 0.8438950947024555, "lm_q1q2_score": 0.8176129658484136}} {"text": "module PhaseSpaces\n\nexport Q_of_θφ,Q_of_θϕ,P_of_θφ,P_of_θϕ,θ_of_QP,φ_of_QP,ϕ_of_QP,jz,jx,jy,arc_between_θφ,arc_between_θϕ,arc_between_QP\n \"\"\"\n ```julia\n function Q_of_θϕ(θ,ϕ)\n ```\n \n Returns\n ```math\n Q=\\\\sqrt{2 (1 - \\\\cos(\\\\theta))}\\\\cos(\\\\phi).\n ```\n \n Also [`Q_of_θφ(θ,φ)`](@ref Q_of_θφ).\n \"\"\"\n Q_of_θϕ(θ::Real,ϕ::Real)=sqrt(2*(1-cos(θ)))*cos(ϕ)\n \n \"\"\"\n See [`Q_of_θϕ`](@ref).\n \"\"\"\n Q_of_θφ(θ::Real,φ::Real)=Q_of_θϕ(θ,φ)\n\n \"\"\"\n ```julia\n function P_of_θϕ(θ,ϕ)\n ```\n \n Returns\n ```math\n P=- \\\\sqrt{2 (1 - \\\\cos(\\\\theta))}\\\\sin(\\\\phi).\n ```\n Also [`P_of_θφ(θ,φ)`](@ref P_of_θφ).\n \"\"\"\n P_of_θϕ(θ::Real,ϕ::Real)=-sqrt(2*(1-cos(θ)))*sin(ϕ)\n \n \"\"\"\n See [`P_of_θϕ`](@ref).\n \"\"\"\n P_of_θφ(θ::Real,φ::Real)=P_of_θϕ(θ,φ)\n \"\"\"\n ```julia\n function θ_of_QP(Q,P)\n ```\n Returns\n ```math\n \\\\theta =- \\\\arccos\\\\left(1 - \\\\frac{Q^2 + P^2}{2}\\\\right).\n ```\n \"\"\"\n θ_of_QP(Q::Real,P::Real)=acos(1-(Q^2+P^2)/2)\n \"\"\"\n ```julia\n function ϕ_of_QP(Q,P)\n ```\n \n Returns\n ```math\n \\\\phi = \\\\text{arctan2}(-P,Q)\\\\in [0,2 \\\\pi ],\n ```\n where ``\\\\text{arctan2}`` is the [2-argument arctangent](https://en.wikipedia.org/wiki/Atan2).\n \n Also [`φ_of_QP(Q,P)`](@ref φ_of_QP).\n \"\"\"\n ϕ_of_QP(Q::Real,P::Real)=mod(atan(-P,Q),2*pi)\n \n \"\"\"\n See [`ϕ_of_QP`](@ref).\n \"\"\"\n φ_of_QP(Q::Real,P::Real)=ϕ_of_QP(Q,P)\n\n \"\"\"\n ```julia\n function jz(Q,P)\n ```\n Returns\n ```math\n j_z = - \\\\cos(\\\\theta(Q,P)).\n ```\n where ``\\\\text{arctan2}`` is the [2-argument arctangent](https://en.wikipedia.org/wiki/Atan2).\n \"\"\"\n jz(Q::Real,P::Real)=-cos(θ_of_QP(Q,P))\n \"\"\"\n ```julia\n function jx(Q,P)\n ```\n Returns\n ```math\n j_x = \\\\sin(\\\\theta(Q,P))\\\\cos(\\\\phi(Q,P)).\n ```\n \"\"\"\n jx(Q::Real,P::Real)=sin(θ_of_QP(Q,P))*cos(φ_of_QP(Q,P))\n \"\"\"\n ```julia\n function jy(Q,P)\n ```\n Returns \n ```math\n j_y = \\\\sin(\\\\theta(Q,P))\\\\sin(\\\\phi(Q,P)).\n ```\n \"\"\"\n jy(Q::Real,P::Real)=sin(θ_of_QP(Q,P))*sin(φ_of_QP(Q,P))\n \"\"\"\n ```julia\n function arc_between_θϕ(θ1,φ1,θ2,φ2)\n ```\n Returns \n ```math\n \\\\Theta = \\\\arccos(\\\\cos(\\\\theta_1)\\\\cos(\\\\theta_2)+ \\\\sin(\\\\theta_1)\\\\sin(\\\\theta_2)\\\\cos(\\\\phi_1 - \\\\phi_2)).\n ```\n Also [`arc_between_θφ(θ1,φ1,θ2,φ2)`](@ref arc_between_θφ).\n\n \"\"\"\n arc_between_θϕ(θ1::Real,ϕ1::Real,θ2::Real,ϕ2::Real)=acos(clamp(cos(θ1)*cos(θ2)+ sin(θ1)*sin(θ2)*cos(ϕ1 - ϕ2),-1,1))\n \n \"\"\"\n See [`arc_between_θϕ`](@ref).\n \"\"\"\n arc_between_θφ(θ1::Real,φ1::Real,θ2::Real,φ2::Real)=arc_between_θϕ(θ1,φ1,θ2,φ2)\n \"\"\"\n ```julia\n function arc_between_QP(Q1,P1,Q2,P2)\n ```\n Returns \n ```julia\n arc_between_θϕ(θ_of_QP(Q1,P1),ϕ_of_QP(Q1,P1),θ_of_QP(Q2,P2),ϕ_of_QP(Q2,P2)).\n ```\n \"\"\"\n arc_between_QP(Q1::Real,P1::Real,Q2::Real,P2::Real)=arc_between_θϕ(θ_of_QP(Q1,P1),ϕ_of_QP(Q1,P1),θ_of_QP(Q2,P2),ϕ_of_QP(Q2,P2))\nend\n", "meta": {"hexsha": "5ace681bc7590b8e193b31f7e14797d66e6fb5cc", "size": 3041, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/PhaseSpaces.jl", "max_stars_repo_name": "saulpila/Dicke.jl", "max_stars_repo_head_hexsha": "8670fdce9102d657d5e4168866e2ded8d731ee6b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-07-19T19:12:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-11T09:39:08.000Z", "max_issues_repo_path": "src/PhaseSpaces.jl", "max_issues_repo_name": "saulpila/Dicke.jl", "max_issues_repo_head_hexsha": "8670fdce9102d657d5e4168866e2ded8d731ee6b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-07-22T16:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-21T14:44:05.000Z", "max_forks_repo_path": "src/PhaseSpaces.jl", "max_forks_repo_name": "saulpila/DickeModel.jl", "max_forks_repo_head_hexsha": "8670fdce9102d657d5e4168866e2ded8d731ee6b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5736434109, "max_line_length": 131, "alphanum_fraction": 0.5044393292, "num_tokens": 1288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191322715436, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.8176109715619349}} {"text": "\"\"\"\r\n findiff(p,q,r,a,b,alpha,beta,M)\r\nberisi program untuk mencari solusi persamaan differensial\r\n`x''=f(t,x,x')` dengan masalah nilai batas `x(a)=alpha` dan `x(b)=beta` pada interval `[a,b]`.\r\nProgram ini secara default berisi 7 masukan, yaitu fungsi `p(t)`, `q(t)` dan `r(t)` dari persamaan\r\n`x''=p(t)x'+q(t)x+r(t)`, titik ujung interval `[a,b]`, nilai batas `[alpha,beta]`, dan\r\njumlah sub-interval `M`.\r\n# Example\r\n```jl\r\njulia> p(t)= 2*t/(1+t^2);\r\n q(t)= -2/(1+t^2);\r\n r(t)= 1 + 0*t;\r\n\r\njulia> solusi = findiff(p,q,r,0,4,1.25,-0.95,40)\r\n41×2 Array{Float64,2}:\r\n 0.0 1.25\r\n 0.1 1.29077\r\n 0.2 1.31665\r\n 0.3 1.32791\r\n ⋮\r\n 3.7 -1.03501\r\n 3.8 -1.01924\r\n 3.9 -0.991063\r\n 4.0 -0.95\r\n```\r\nreturn solusi masalah nilai batas `sol`.\r\n\"\"\"\r\nfunction findiff(p,q,r,a,b,alpha,beta,M)\r\n h = (b-a)/M;\r\n T = a:h:b;\r\n T = T[2:end-1];\r\n #% Bangun Matriks B\r\n B = -h^2*r.(T);\r\n B[1] = B[1] + (1+h/2*p(T[1]))*alpha;\r\n B[end] = B[end] + (1-h/2*p(T[end]))*beta;\r\n # Bangun Matriks A - Bagian Diagonal\r\n Ad = 2 .+h^2*q.(T);\r\n #% Bangun Matriks A - Bagian Bawah Diagonal\r\n Tbawah = T[2:end];\r\n Abawah = -1 .-h/2*p.(Tbawah);\r\n #% Bangun Matriks A - Bagian Atas Diagonal\r\n Tatas = T[1:end-1];\r\n Aatas = -1 .+h/2*p.(Tatas);\r\n A = Tridiagonal(Abawah,Ad,Aatas)\r\n #% Selesaikan AX=B\r\n X = A\\B;\r\n T = [a; T; b];\r\n X = [alpha; X ;beta];\r\n solusi = [T X];\r\nend\r\n", "meta": {"hexsha": "cdcbe5b3403700baee090c83e3172e2cab25b963", "size": 1381, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/findiff.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/findiff.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/findiff.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": 27.0784313725, "max_line_length": 99, "alphanum_fraction": 0.5496017379, "num_tokens": 609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191259110588, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.8176109696307394}} {"text": "### A Pluto.jl notebook ###\n# v0.12.16\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# ╔═╡ e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, Distributions, Plots, LaTeXStrings\n\tusing SpecialFunctions, Roots\n\tRandom.seed!(0)\nend\n\n# ╔═╡ ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing5.10\"\n\n# ╔═╡ fa68607e-22e5-11eb-0558-c9a4d9f77426\neq(alpha, xb, xbl) = log(alpha) - digamma(alpha) - log(xb) + xbl\n\n# ╔═╡ 06e24b20-3a9d-11eb-3557-97a1adc9f46e\nbegin\n\tactualAlpha, actualLambda = 2, 3\n\tgammaDist = Gamma(actualAlpha,1/actualLambda)\nend\n\n# ╔═╡ 06e27366-3a9d-11eb-211e-df469e196f9d\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\n# ╔═╡ 7f6ea3be-3a9e-11eb-1287-4f1bc371585a\nalpha\n\n# ╔═╡ 06e2dc20-3a9d-11eb-2aed-6745e3221343\nbegin\n\tN = 10^4\n\tmles10 = [mle(rand(gammaDist,10)) for _ in 1:N]\n\tmles100 = [mle(rand(gammaDist,100)) for _ in 1:N]\n\tmles1000 = [mle(rand(gammaDist,1000)) for _ in 1:N]\nend\n\n# ╔═╡ 06ef2bc2-3a9d-11eb-3563-8b81e34087da\nbegin\n\tscatter(first.(mles10), last.(mles10), \n\t\tc=:blue, ms=1, msw=0, label=\"n = 10\")\n\tscatter!(first.(mles100), last.(mles100), \n\t\tc=:red, ms=1, msw=0, label=\"n = 100\")\n\tscatter!(first.(mles1000), last.(mles1000), \n\t\tc=:green, ms=1, msw=0, label=\"n = 1000\", \n\t\txlims=(0,6), ylims=(0,8), xlabel=L\"\\alpha\", ylabel=L\"\\lambda\")\nend\n\n# ╔═╡ 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing5.10\"\n\n# ╔═╡ Cell order:\n# ╟─ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# ╠═e077ab16-22e5-11eb-15ed-5f0654bf7328\n# ╠═e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# ╠═fa68607e-22e5-11eb-0558-c9a4d9f77426\n# ╠═06e24b20-3a9d-11eb-3557-97a1adc9f46e\n# ╠═06e27366-3a9d-11eb-211e-df469e196f9d\n# ╠═7f6ea3be-3a9e-11eb-1287-4f1bc371585a\n# ╠═06e2dc20-3a9d-11eb-2aed-6745e3221343\n# ╠═06ef2bc2-3a9d-11eb-3563-8b81e34087da\n# ╟─475ff888-22e6-11eb-2354-09f8f40a8e12\n", "meta": {"hexsha": "1c57911168ea8d7d93983950a42beaec8cc9a919", "size": 1994, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/05/listing5.10.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/05/listing5.10.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/05/listing5.10.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 27.3150684932, "max_line_length": 70, "alphanum_fraction": 0.7081243731, "num_tokens": 1027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9372107861416413, "lm_q2_score": 0.8723473879530492, "lm_q1q2_score": 0.8175733812520847}} {"text": "# Low Rank Singular Value Decomposition\n\"\"\"\n get_approximate_basis(A, l::Int; niter::Int = 2, M = nothing) -> Q\nReturn Matrix ``Q`` with ``l`` orthonormal columns such that ``Q Q^H A`` approximates ``A``. If ``M`` is specified, then ``Q`` is such that ``Q Q^H (A - M)`` approximates ``A - M``.\n\"\"\"\n\nstruct Normal_QR{QT, RT}\n Q::QT\n R::RT\n function Normal_QR(Q::QT, R::RT) where {QT<:AbstractMatrix, RT<:AbstractMatrix}\n size(Q, 2) == size(R, 1) || throw(DimensionMismatch(\"$(size(Q)), $(length(R)) not compatible\"))\n new{QT, RT}(Q, R)\n end\nend\n\nfunction private_qr(A::AbstractMatrix{T}) where T\n\tres = LinearAlgebra.qr(A)\n\tNormal_QR(Matrix(res.Q), res.R)\nend\n\nfunction get_approximate_basis(\n A::AbstractSparseMatrix{T}, l::Int, niter::Int = 2, M::Union{AbstractMatrix{T}, Nothing} = nothing) where T\n m, n = size(A)\n Ω = rand(T, (n, l))\n if M === nothing \n F_j = private_qr(A * Ω)\n for j = 1:niter\n F_H_j = private_qr(A' * Matrix(F_j.Q))\n F_j = qr(A * Matrix(F_H_j.Q))\n end\n else\n F_j = qr(A * Ω .- M * Ω)\n for j = 1:niter\n F_H_j = private_qr(A' * Matrix(F_j.Q) - M' * sum(Matrix(F_j.Q), dims=1))\n F_j = private_qr(A * Matrix(F_H_j.Q) .- M * Matrix(F_H_j.Q))\n end\n end\n Matrix(F_j.Q)\nend\n\n\n\n\n\"\"\"\n low_rank_svd(A, l::Int; niter::Int = 2, M = nothing) -> U, S, Vt\nReturn the singular value decomposition of a sparse matrix ``A`` with estimated rank ``l`` such that ``A ≈ U diag(S) Vt``. In case row vector ``M`` is given, then SVD is computed for the matrix ``A - M``.\n\"\"\"\n\nfunction low_rank_svd(A::AbstractSparseMatrix{T}, l::Int, niter::Int = 2, M::Union{AbstractMatrix{T}, Nothing} = nothing) where T\n \n if M === nothing\n Q = get_approximate_basis(A, l, niter, M)\n B = Q' * A\n else\n size(M, 2) == size(A, 2) || throw(DimensionMismatch())\n Q = get_approximate_basis(A, l, niter, M)\n B = Q' * A - sum(Q', dims=2) * M\n end\n\n dense_svd = svd(B)\n U = Q * dense_svd.U\n return U, dense_svd.S, dense_svd.Vt\nend\n", "meta": {"hexsha": "702e75d4f38127e9f895ab34775ea31abe1b25a2", "size": 2100, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lowranksvd.jl", "max_stars_repo_name": "jieli-matrix/SparseADRules.jl", "max_stars_repo_head_hexsha": "d7b1fc21bf13c1caf1e962c3ce19bf9972c40933", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-10-01T14:50:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T11:56:47.000Z", "max_issues_repo_path": "src/lowranksvd.jl", "max_issues_repo_name": "jieli-matrix/SparseADRules.jl", "max_issues_repo_head_hexsha": "d7b1fc21bf13c1caf1e962c3ce19bf9972c40933", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-10-03T07:23:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-03T07:23:55.000Z", "max_forks_repo_path": "src/lowranksvd.jl", "max_forks_repo_name": "jieli-matrix/SparseArraysAD.jl", "max_forks_repo_head_hexsha": "d7b1fc21bf13c1caf1e962c3ce19bf9972c40933", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-13T00:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T00:59:17.000Z", "avg_line_length": 32.8125, "max_line_length": 204, "alphanum_fraction": 0.5785714286, "num_tokens": 698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029486, "lm_q2_score": 0.8723473680407889, "lm_q1q2_score": 0.8175733671797871}} {"text": "# Julia translation of http://nbviewer.jupyter.org/github/barbagroup/AeroPython/blob/master/lessons/01_Lesson01_sourceSink.ipynb\n# Lession 2 Source and Sink in a Freestream\n\nusing PyPlot\nusing Distributions\n\nclose(\"all\")\nmeshgrid(x,y) = (repmat(x',length(y),1),repmat(y,1,length(x)))\n\nN = 200 # number of points in each direction\nx_start, x_end = -4.0, 4.0 # boundaries in the x-direction\ny_start, y_end = -2.0, 2.0 # boundaries in the y-direction\nx = linspace(x_start, x_end, N) # creates a 1D-array with the x-coordinates\ny = linspace(y_start, y_end, N) # creates a 1D-array with the y-coordinates\n\nX,Y=meshgrid(x,y)\n\nu_inf = 1.0\n\n# computes the freestream velocity field\nu_freestream = u_inf * ones((N, N))\nv_freestream = zeros((N, N))\n\n# computes the stream-function\npsi_freestream = u_inf * Y\n\nfunction get_velocity(strength, xs, ys, X, Y):\n \"\"\"Returns the velocity field generated by a source/sink.\n\n Arguments\n ---------\n strength -- strength of the source/sink.\n xs, ys -- coordinates of the source/sink.\n X, Y -- mesh grid.\n \"\"\"\n u = strength/(2*pi).*(X-xs)./((X-xs).^2+(Y-ys).^2)\n v = strength/(2*pi).*(Y-ys)./((X-xs).^2+(Y-ys).^2)\n\n return u, v\n end\n\nfunction get_stream_function(strength, xs, ys, X, Y):\n \"\"\"Returns the stream-function generated by a source/sink.\n\n Arguments\n ---------\n strength -- strength of the source/sink.\n xs, ys -- coordinates of the source/sink.\n X, Y -- mesh grid.\n \"\"\"\n psi = strength/(2*pi).*atan2((Y-ys), (X-xs))\n\n return psi\n end\n\nstrength_source = 5.0 # strength of the source\nx_source, y_source = -1.0, 0.0 # location of the source\n\n# computes the velocity field\nu_source, v_source = get_velocity(strength_source, x_source, y_source, X, Y)\n\n# computes the stream-function\npsi_source = get_stream_function(strength_source, x_source, y_source, X, Y)\n\n\n # superposition of the source on the freestream\n u = u_freestream + u_source\n v = v_freestream + v_source\n psi = psi_freestream + psi_source\n\n # plots the streamlines\n\n\n size = 10\n PyPlot.figure(figsize=(size, (y_end-y_start)/(x_end-x_start)*size))\n PyPlot.grid(true)\n PyPlot.xlabel(\"x\", fontsize=16)\n PyPlot.ylabel(\"y\", fontsize=16)\n PyPlot.xlim(x_start, x_end)\n PyPlot.ylim(y_start, y_end)\n PyPlot.streamplot(X, Y, u, v, density=2, linewidth=1, arrowsize=1, arrowstyle=\"->\")\n PyPlot.scatter(x_source, y_source, color=\"#CD2305\", s=80, marker=\"o\")\n\n # calculates the stagnation point\n x_stagnation = x_source - strength_source/(2*pi*u_inf)\n y_stagnation = y_source\n\n # adding the stagnation point to the figure\n PyPlot.scatter(x_stagnation, y_stagnation, color=\"g\", s=80, marker=\"o\")\n\n # adds the dividing line to the figure\n PyPlot.contour(X, Y, psi,\n levels=[-strength_source/2, +strength_source/2],\n colors=\"#CD2305\", linewidths=2, linestyles=\"solid\");\n\nstrength_sink = -5.0 # strength of the sink\nx_sink, y_sink = 1.0, 0.0 # location of the sink\n\n# computes the velocity field on the mesh grid\nu_sink, v_sink = get_velocity(strength_sink, x_sink, y_sink, X, Y)\n\n# computes the stream-function on the grid mesh\npsi_sink = get_stream_function(strength_sink, x_sink, y_sink, X, Y)\n\n\n# superposition of a source and a sink on the freestream\nu = u_freestream + u_source + u_sink\nv = v_freestream + v_source + v_sink\npsi = psi_freestream + psi_source + psi_sink\n\n# plots the streamlines\nsize = 10\nPyPlot.figure(figsize=(size, (y_end-y_start)/(x_end-x_start)*size))\nPyPlot.xlabel(\"x\", fontsize=16)\nPyPlot.ylabel(\"y\", fontsize=16)\nPyPlot.xlim(x_start, x_end)\nPyPlot.ylim(y_start, y_end)\nPyPlot.streamplot(X, Y, u, v, density=2, linewidth=1, arrowsize=1, arrowstyle=\"->\")\nPyPlot.scatter([x_source, x_sink], [y_source, y_sink], color=\"#CD2305\", s=80, marker=\"o\")\nPyPlot.contour(X, Y, psi, levels=[0.], colors=\"#CD2305\", linewidths=2, linestyles=\"solid\");\n\n# computes the pressure coefficient field\ncp = 1.0 - (u.^2+v.^2)./u_inf^2\n\n# plots the pressure coefficient field\nsize = 10\nPyPlot.figure(figsize=(1.1*size, (y_end-y_start)/(x_end-x_start)*size))\nPyPlot.xlabel(\"x\", fontsize=16)\nPyPlot.ylabel(\"y\", fontsize=16)\nPyPlot.xlim(x_start, x_end)\nPyPlot.ylim(y_start, y_end)\ncontf = PyPlot.contourf(X, Y, cp, levels=linspace(-2.0, 1.0, 100), extend=\"both\")\ncbar = PyPlot.colorbar(contf)\ncbar[:set_label](L\"$C_p$\", fontsize=16)\ncbar[:set_ticks]([-2.0, -1.0, 0.0, 1.0])\nPyPlot.scatter([x_source, x_sink], [y_source, y_sink], color=\"#CD2305\", s=80, marker=\"o\")\nPyPlot.contour(X, Y, psi, levels=[0.], colors=\"#CD2305\", linewidths=2, linestyles=\"solid\");\n", "meta": {"hexsha": "602f83ce06a7eade32280465fbe9da5f39f52f5b", "size": 4644, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Lesson2_SourceSinkFreestream.jl", "max_stars_repo_name": "moore54/JuliaPotentialFlowTranslations", "max_stars_repo_head_hexsha": "2aad7750c23057518ca988ba4a02a4c99f4fde5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lesson2_SourceSinkFreestream.jl", "max_issues_repo_name": "moore54/JuliaPotentialFlowTranslations", "max_issues_repo_head_hexsha": "2aad7750c23057518ca988ba4a02a4c99f4fde5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lesson2_SourceSinkFreestream.jl", "max_forks_repo_name": "moore54/JuliaPotentialFlowTranslations", "max_forks_repo_head_hexsha": "2aad7750c23057518ca988ba4a02a4c99f4fde5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.652173913, "max_line_length": 128, "alphanum_fraction": 0.680878553, "num_tokens": 1432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107861416414, "lm_q2_score": 0.8723473663814338, "lm_q1q2_score": 0.8175733610349342}} {"text": "using LinearAlgebra: eigen, cholesky, diag, diagm, UpperTriangular, LowerTriangular\nusing Statistics: mean\n\n\"\"\"\n Functions for mvrnorm, covriance to correlation conversion (cov2cor)\n and vice versa cor2cov.\n\"\"\"\nfunction generateRandomMatrix(p::Int64, n::Int64)\n x = rand(n, p)\n return x' * x\nend\n\n\"\"\"\n Function to convert covariance to correlation matrix\n\"\"\"\nfunction cov2cor(E::Array{T, 2}) where {T <: AbstractFloat}\n p = size(E)[1]\n d::Array{T, 1} = diag(E)\n d .^= -0.5\n C = (d * d') .* E\n C = 0.5.*(UpperTriangular(C) + LowerTriangular(C)')\n C = C + C'\n for i in 1:p\n C[i, i] = T(1)\n end\n return C\nend\n\n\"\"\"\n Function to convert correlation to covariance matrix\n d is the variance vector of the covariance matrix\n\"\"\"\nfunction cor2cov(C::Array{T, 2}, d::Array{T, 1}) where {T <: AbstractFloat}\n p = size(C)[1]\n d1 = d .^0.5\n E = (d1 * d1') .* C\n E = 0.5.*(UpperTriangular(E) + LowerTriangular(E)')\n E = E + E'\n for i in 1:p\n E[i, i] /= 2\n end\n return E\nend\n\n\"\"\"\n Function that carries samples from a multivariate normal\n distribution when supplied with the number of samples (n),\n the mean vector (mu), and the covariance matrix (sigma).\n\n Example:\n mvrnorm(100, zeros(10), cov2cor(generateRandomMatrix(10, 10000)))\n\"\"\"\nfunction mvrnorm(n::Int64, mu::Array{T, 1}, sigma::Array{T, 2}) where {T <: AbstractFloat}\n p = size(sigma)[1]\n A = cholesky(sigma).L\n output = zeros(T, (n, p))\n for i = 1:n\n output[i, :] = mu + A * randn(p)\n end\n return output\nend\n\n#=======================================================================================================#\n\"\"\"\n Random Number Generator for Beta (and Uniform) Distribution\n\"\"\"\nabstract type AbstractSampleDistribution end\nstruct BetaSampleDistribution{T} <: AbstractSampleDistribution\n alpha::T\n beta::T\n function BetaSampleDistribution(alpha::T, beta::T) where {T <: AbstractFloat}\n return new{T}(alpha, beta)\n end\n function BetaSampleDistribution(alpha::T, beta::T) where {T <: Integer}\n return BetaSampleDistribution(Float64(alpha), Float64(beta))\n end\nend\n\nfunction calcSample(ualpha::T, vbeta::T) where {T <: AbstractFloat}\n return ualpha/(ualpha + vbeta)\nend\nfunction condition(ualpha::T, vbeta::T) where {T <: AbstractFloat}\n return (ualpha + vbeta) > T(1)\nend\n\n\n\"\"\"\n Version 1 of the random sample from beta distribution\n Reference: C. P. Robert, G. Casella, \n Monte Carlo Statistical Methods, Example 2.11 p44\n\"\"\"\nfunction sample(distrib::BetaSampleDistribution{T}, shape::Tuple{Vararg{Int64}}) where {T <: AbstractFloat}\n n = prod(shape)\n U = rand(T, n); V = rand(T, n)\n Y::Array{T} = zeros(T, shape)\n ialpha = 1/distrib.alpha; ibeta = 1/distrib.beta\n for i in 1:n\n u::T = U[i]; v::T = V[i]\n ualpha = u .^ialpha; vbeta = v .^ibeta;\n while condition(ualpha, vbeta)\n u = rand(T, 1)[1]; v = rand(T, 1)[1]\n ualpha = u .^ialpha; vbeta = v .^ibeta;\n end\n Y[i] = calcSample(ualpha, vbeta)\n end\n return Y\nend\n\nfunction sample(distrib::BetaSampleDistribution{T}, shape::Int64) where {T <: AbstractFloat}\n return sample(distrib, (shape,))\nend\n\n#=======================================================================================================#\n\nstruct UniformSampleDistribution{T} <: AbstractSampleDistribution\n min::T\n max::T\n function UniformSampleDistribution(min::T, max::T) where {T <: AbstractFloat}\n @assert(min < max, \"Minimum value is not less than maximum value\")\n return new{T}(min, max)\n end\n function UniformSampleDistribution(min::T, max::T) where {T <: Integer}\n return UniformSampleDistribution(Float64(min), Float64(max))\n end\nend\n\nfunction sample(distrib::UniformSampleDistribution{T}, shape::Tuple{Vararg{Int64}}) where {T <: AbstractFloat}\n rsample::Array{T} = rand(T, shape)\n return (rsample .* (distrib.max - distrib.min)) .+ distrib.min\nend\nfunction sample(distrib::UniformSampleDistribution{T}, shape::Int64) where {T <: AbstractFloat}\n return sample(distrib, (shape,))\nend\n\n\nfunction Base.min(x::Array{T}) where {T <: AbstractFloat}\n n = length(x)\n @assert(n > 0, \"Length of array is zero.\")\n if n == 1\n return x[1]\n end\n ret::T = x[1]\n for i in 2:n\n ret = ret > x[i] ? x[i] : ret\n end\n return ret\nend\n\nfunction Base.max(x::Array{T}) where {T <: AbstractFloat}\n n = length(x)\n @assert(n > 0, \"Length of array is zero.\")\n if n == 1\n return x[1]\n end\n ret::T = x[1]\n for i in 2:n\n ret = ret < x[i] ? x[i] : ret\n end\n return ret\nend\n\nfunction Base.range(x::Array{T}) where {T <: AbstractFloat}\n return [min(x), max(x)]\nend\n\n\n#=======================================================================================================#\n\n\"\"\"\n Identity Matrix\n\"\"\"\nfunction I(::Type{T}, p::Int64) where {T <: Number}\n x = zeros(T, (p, p))\n for i in 1:p\n x[i, i] = T(1)\n end\n return x\nend\n\"\"\"\n Convenience overload\n\"\"\"\nfunction I(p::Int64)\n return I(Float64, p)\nend\n\n\"\"\"\n Types for generating random correlation matrices\n\"\"\"\nabstract type AbstractRandomCorrelationMatrix end\n\nstruct BetaGenerator <: AbstractRandomCorrelationMatrix end\nstruct OnionGenerator <: AbstractRandomCorrelationMatrix end\nstruct UniformGenerator <: AbstractRandomCorrelationMatrix end\nstruct VineGenerator <: AbstractRandomCorrelationMatrix end\n\n\"\"\"\n Vine method for generating a random correlation matrix\n Source:\n https://stats.stackexchange.com/questions/2746/how-to-efficiently-generate-random-positive-semidefinite-correlation-matrices/125017#125017\n \n Check it with to make sure the solutions are correct:\n Journal of Multivariate Analysis 100 (2009) 1989–2001\n Generating random correlation matrices based on vines and extended\n onion method. Daniel Lewandowski(a)*, Dorota Kurowicka (a), \n Harry Joe (b).\n \n randomCorrelationMatrix(VineGenerator(), 10, 2.0)\n\"\"\"\nfunction randomCorrelationMatrix(::VineGenerator, d::Int64, eta::T) where {T <: AbstractFloat}\n \n beta = eta + (d - 1)/2\n P = zeros(T, (d, d))\n S = I(T, d)\n \n for k in 1:(d - 1)\n beta = beta - (1/2)\n distrib = BetaSampleDistribution(beta, beta)\n \n for i in (k + 1):d\n P[k, i] = sample(distrib, 1)[1]\n P[k, i] = (P[k, i] - 0.5)*2\n p = P[k, i]\n \n for l in (k - 1):-1:1\n p = p * sqrt((1 - P[l, i]^2)*(1 - P[l, k]^2)) + P[l, i]*P[l, k]\n end\n \n S[k, i] = p\n S[i, k] = p\n end\n end\n \n return S\nend\n\n\"\"\"\n Random correlation matrix using the Onion Generator\n\"\"\"\nfunction randomCorrelationMatrix(::OnionGenerator, d::Int64, eta::T) where {T <: AbstractFloat}\n beta::T = eta + (d - 2)/2\n distrib = BetaSampleDistribution(beta, beta)\n u = sample(distrib, 1)[1]\n r = I(T, 2)\n r[1, 2] = r[2, 1] = 2*u - 1\n for k in 2:(d - 1)\n beta -= T(1/2)\n distrib = BetaSampleDistribution(T(k/2), beta)\n y = sample(distrib, 1)[1]\n U = rand(T, k)\n w = sqrt(y) .* U\n \n ev = eigen(r)\n A = ev.vectors * diagm(abs.(ev.values).^(0.5)) * ev.vectors'\n z = A * w\n r = [r z; z' T(1)]\n end\n return r\nend\n\n\"\"\"\n Random correlation matrix by sampling from Beta Distribution\n # Example:\n randomCorrelationMatrix(BetaGenerator(), 10, (1.0, 1.0))\n\"\"\"\nfunction randomCorrelationMatrix(::BetaGenerator, d::Int64, (alpha, beta)::Tuple{T, T}) where {T <: AbstractFloat}\n distrib = BetaSampleDistribution(alpha, beta)\n r = sample(distrib, (d, d))\n # Change range to (-1, 1)\n r .= (r .* 2) .+ T(-1)\n # Symmetry\n r .= T(0.5) .* (r + r')\n for i in 1:d\n r[i, i] = T(1)\n end\n ev = eigen(r)\n r = ev.vectors * diagm(sort(abs.(ev.values))) * ev.vectors'\n maxR = max(r)\n r ./= maxR\n r .= T(0.5) .* (r + r')\n for i in 1:d\n r[i, i] = T(1)\n end\n return r\nend\n\n\"\"\"\n Random correlation matrix by sampling from Uniform Distribution\n # Example:\n randomCorrelationMatrix(Float64, UniformGenerator(), 10)\n\"\"\"\nfunction randomCorrelationMatrix(::Type{T}, ::UniformGenerator, d::Int64) where {T <: AbstractFloat}\n distrib = UniformSampleDistribution(T(-1), T(1))\n r = sample(distrib, (d, d))\n r .= T(0.5) .* (r + r')\n for i in 1:d\n r[i, i] = T(1)\n end\n ev = eigen(r)\n r = ev.vectors * diagm(sort(abs.(ev.values))) * ev.vectors'\n maxR = max(abs.(r)...)\n r ./= maxR\n r .= T(0.5) .* (r + r')\n for i in 1:d\n r[i, i] = T(1)\n end\n return r\nend\n\n#=======================================================================================================#\n\n\"\"\"\n Function to simulate X and eta, p = number of parameters \n (including intercept), n = number of samples.\n\n # Example:\n using Random: seed!\n seed!(0)\n simulateData(Float64, 10, 1000)\n\"\"\"\nfunction simulateData(::Type{T}, p::Int64, n::Int64, delta::T = T(0)) where {T <: AbstractFloat}\n \n corr = randomCorrelationMatrix(T, UniformGenerator(), p)\n mu = zeros(T, p)\n X = mvrnorm(n, mu, corr)\n\n #= The intercept =#\n X[:, 1] .= T(1)\n \n b = zeros(T, p)\n idist = UniformSampleDistribution(T(0), T(0.3))\n b[1] = sample(idist, 1)[1]\n if length(b) > 1\n distrib = UniformSampleDistribution(T(-0.1), T(0.1))\n b[2:p] = sample(distrib, p - 1)\n end\n \n eta = X*b\n sd = 0.5*abs(mean(eta))\n eta = delta .+ eta .+ sd .* randn(n)\n\n return (X = X, eta = eta)\nend\n\n", "meta": {"hexsha": "3b001879b47d95c563b29d45d317ea27d02ffaf4", "size": 9121, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "glmSolverjl/src/sample.jl", "max_stars_repo_name": "dataPulverizer/glmSolver", "max_stars_repo_head_hexsha": "d82623caac1e14d29ee09fbafa7efbbd5d6ee0bf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-17T15:34:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-17T15:34:44.000Z", "max_issues_repo_path": "glmSolverjl/src/sample.jl", "max_issues_repo_name": "dataPulverizer/glmSolver", "max_issues_repo_head_hexsha": "d82623caac1e14d29ee09fbafa7efbbd5d6ee0bf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "glmSolverjl/src/sample.jl", "max_forks_repo_name": "dataPulverizer/glmSolver", "max_forks_repo_head_hexsha": "d82623caac1e14d29ee09fbafa7efbbd5d6ee0bf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5145348837, "max_line_length": 142, "alphanum_fraction": 0.6039907905, "num_tokens": 2860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107878954106, "lm_q2_score": 0.8723473630627235, "lm_q1q2_score": 0.8175733594544989}} {"text": "function LGnodes(alpha::Real, N::Int)\n # generate nodes of Laguerre-Gauss quadrature nodes.\n alpha > -1 || error(\"alpha <= -1 not allowed.\")\n j = 1:N |> collect\n b = j .* (j .+ alpha)\n # +- diagonal\n dl = -sqrt.(b) \n j = 0:N |> collect\n # main diagonal\n d = 2.0 * j .+ alpha .+ 1\n A = SymTridiagonal(d, dl)\n return eigvals(A)\nend\n\n\n\nfunction LGRnodes(N::Int)\n # Laguerre-Gauss-Radau quadrature nodes.\n xi = LGnodes(1.0, N - 1)\n x = [0; xi]\n return x\nend\n\n\nfunction LGR(N::Int)\n # get nodes and weights for LGR.\n x = LGRnodes(N)\n LN = eval_laguerre_function.(N, x)\n # equation 7.37 in Shen, Tang & Wang.\n w = 1 ./ ( (N + 1) * LN.^2)\n return x, w\nend\n\n\n\nfunction eval_laguerre_function(n::Int, x::Real)\n # evaluate Laguerre function using the recurrence relation\n L0 = exp(-x / 2)\n L1 = (1 - x) * exp(-x / 2)\n if n == 0\n return L0\n end\n if n == 1\n return L1\n end\n # n >= 2 case\n Lnew = 0.0\n for i = 2:n\n Lnew = (2 - 1 / i - x / i) * L1 - (1 - 1 / i) * L0\n L0 = L1\n L1 = Lnew \n end\n return Lnew\nend\n\nfunction eval_LaguerreFunction(n::Int, x::Real)\n # method in Shen, SIAM J NUMER ANAL, Vol 38, No 4, pp. 1113-1133\n # STABLE AND EFFICIENT SPECTRAL METHODS IN UNBOUNDED\n # DOMAINS USING LAGUERRE FUNCTIONS\n signL0 = 1\n # TODO: need to indentify the error in the equations cited.\n # d0 = 1\n # signL1 = sign(1 - x)\n # d1 = abs(1 - x) * exp(-x / 2)\n # if n == 0 \n # return exp(-x / 2)\n # end\n # if n == 1\n # return signL1 * d1\n # end\n # for i = 2:n\n # # common term \n # t = (2 * i - 1 - x) / i * signL1 * d1 * (d1 / d0)^(i - 2) - (1 - 1 / i) * signL0\n # signLi = sign(t)\n # di = d0^(1. - 2 / i) * abs(t)^(1.0 / n) \n # # update old variables. \n # signL0 = signL1\n # signL1 = signLi \n # d0 = d1\n # d1 = di\n # if i == n \n # return signLi * di^n\n # end\n # end\n \nend\n\nfunction LGRquad(f::Function, N::Int)\n # numerical integration using Laguerre-Gauss-Radau quadrature.\n # from 0 to infinity.\n x, w = LGR(N)\n return sum(f.(x) .* w)\nend\n\n\nfunction laguerre_transform(f::Function, N::Int)\n # interpolation: represent f in a series expansion\n # f = sum_{n=0}^N a_n Lnhat(x)\n # where Lnhat is the Laguerre function.\n # an = \\sum_{j=0}^N f(x_j)Lnh(x_j)what_j\n x, w = LGR(N)\n an = zeros(N + 1)\n for i = 1:N + 1\n Ln = eval_laguerre_function.(i - 1, x)\n an[i] = sum(f.(x) .* Ln .* w)\n end\n return an\nend\n\n\nfunction inverse_laguerre_transform(an::AbstractVector, x::AbstractArray)\n # take an array of coefficients and reconstruct the function.\n N = length(an) - 1\n # f = sum_{n=0}^N an Lnh(x)\n f = zeros(size(x))\n\n for (a, n) in zip(an, 0:N)\n Lnh = eval_laguerre_function.(n, x)\n f += a * Lnh\n end\n return f\nend\n\n\n", "meta": {"hexsha": "f3b39fe70b9207070021899bd28b6f89bbaeaf07", "size": 2962, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/quadratures.jl", "max_stars_repo_name": "zpeng2/Laguerre.jl", "max_stars_repo_head_hexsha": "e993b4bd894b902f4dc53b38a7010cda3ff95018", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/quadratures.jl", "max_issues_repo_name": "zpeng2/Laguerre.jl", "max_issues_repo_head_hexsha": "e993b4bd894b902f4dc53b38a7010cda3ff95018", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/quadratures.jl", "max_forks_repo_name": "zpeng2/Laguerre.jl", "max_forks_repo_head_hexsha": "e993b4bd894b902f4dc53b38a7010cda3ff95018", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.696, "max_line_length": 90, "alphanum_fraction": 0.5283592167, "num_tokens": 1099, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172673767973, "lm_q2_score": 0.8615382094310355, "lm_q1q2_score": 0.8175284834339971}} {"text": "export rayleigh_criterion\n\n\"\"\"\n rayleigh_criterion(focal_length, diameter; λ=500e-9)\n\nCalculates the resolution of a microscope according to Rayleigh.\n`focal_length` is the focal length of the lens.\n`λ` is the wavelength and `diameter` is the diameter of the aperture of the lens.\nSee [Wikipedia](https://en.wikipedia.org/wiki/Angular_resolution#The_Rayleigh_criterion).\n\n # Examples\n```julia-repl\njulia> rayleigh_criterion(100, 200)\n3.05e-7\n\njulia> rayleigh_criterion(100, 200, λ=100e-9)\n6.099999999999999e-8\n```\n\"\"\"\nfunction rayleigh_criterion(focal_length, diameter; λ=500e-9)\n return rayleigh_criterion(calc_NA(focal_length, diameter), λ=λ) \nend\n\n\"\"\"\n rayleigh_criterion(NA; λ=500e-9)\n\nCalculates the resolution of a microscope according to Rayleigh.\n`λ` is the wavelength and `NA` the numerical aperture of the system.\nSee [Wikipedia](https://en.wikipedia.org/wiki/Angular_resolution#The_Rayleigh_criterion).\n\n # Examples\n```julia-repl\njulia> rayleigh_criterion(1.0)\n3.05e-7\n\njulia> rayleigh_criterion(1.0, λ=100e-9)\n6.099999999999999e-8\n```\n\"\"\"\nfunction rayleigh_criterion(NA; λ=500e-9)\n return 0.61 * λ / NA\nend\n", "meta": {"hexsha": "8190fea5d74bd1c260d6bc5f2fe4e98de32720ee", "size": 1131, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/resolution_equations.jl", "max_stars_repo_name": "JuliaPhysics/PhysicalOptics", "max_stars_repo_head_hexsha": "47efb1d816756fe7ea57b01061776cad8dbe47c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 35, "max_stars_repo_stars_event_min_datetime": "2020-11-04T11:52:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T10:13:22.000Z", "max_issues_repo_path": "src/resolution_equations.jl", "max_issues_repo_name": "JuliaPhysics/PhysicalOptics", "max_issues_repo_head_hexsha": "47efb1d816756fe7ea57b01061776cad8dbe47c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-01-06T12:58:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-01T13:48:37.000Z", "max_forks_repo_path": "src/resolution_equations.jl", "max_forks_repo_name": "JuliaPhysics/PhysicalOptics", "max_forks_repo_head_hexsha": "47efb1d816756fe7ea57b01061776cad8dbe47c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-02-05T09:40:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T23:19:30.000Z", "avg_line_length": 26.3023255814, "max_line_length": 89, "alphanum_fraction": 0.7621573828, "num_tokens": 354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.8757869965109764, "lm_q1q2_score": 0.8174865696859791}} {"text": "using PyCall\nusing PyPlot\nusing SpecialFunctions\n# uncomment for non-jupyter use:\n#pygui(true)\n\n### FUNCTIONS, used for several subtasks:\n# %%\n\n# the Bernoulli PDF:\nfunction bernoulli_pdf(θ, y)\n if 0 <= θ <= 1 && (y==0 || y==1) # Only admissible values\n return θ^y * (1-θ)^(1-y)\n else\n return 0\n end\nend\n\n# Likelihood fct of a (series of) coin tosses with bias:\nfunction likelihood_fct(θ,y)\n # Make array s.t. multiple theta values can be input:\n likelihood = Array{Float64}(undef,length(θ))\n # Do that for every theta value requested:\n for ii in 1:length(θ)\n # Elementwise application of the beronoulli_pdf over outcome vector y, then MULTIPLY together:\n likelihood[ii] = prod(bernoulli_pdf.(θ[ii], y))\n end\n return likelihood\nend\n\n#%%\n\n# Log-Bernoulli PDF:\nfunction log_bernoulli_pdf(θ,y)\n if 0 < θ < 1 && (y==0 || y==1) # Only admissible values\n return y * log(θ) + (1-y) * log(1-θ)\n else\n return -Inf\n end\nend\n\n# Log-Likelihood fct of a (series of) coin tosses with bias:\nfunction log_likelihood_fct(θ, y)\n # Make array s.t. multiple theta values can be input:\n likelihood = Array{Float64}(undef,length(θ))\n # Do that for every theta value requested:\n for ii in 1:length(θ)\n # Elementwise application of the log_beronoulli_pdf over outcome vector y, then SUM together:\n likelihood[ii] = sum(log_bernoulli_pdf.(θ[ii],y))\n end\n return likelihood\nend\n\n#%%\n\n### Choose and run the subtask:\n\n###########\n### Task 2\n# Given the parameter, plot outcome probabilities\n#%%\nθ = 0.5\noutcomes = [0, 1]\n\nfigure()\nbar(outcomes, bernoulli_pdf.(θ,outcomes))\nxticks([0, 1])\nxlabel(\"y\")\nylabel(\"θ\")\nplt.show()\n\n#%%\n\nθ = 0.25\n\nfigure()\nbar(outcomes, bernoulli_pdf.(θ,outcomes))\nxticks([0, 1])\nxlabel(\"y\")\nylabel(\"θ\")\nplt.show()\n\n#%%\n\n###########\n### Task 3\n# Given the outcome, plot parameter likelihoods\n#%%\nθ = 0:0.01:1;\noutcome = 1;\n\nfigure()\nplot(likelihood_fct.(θ,outcome))\nplt.show()\n\n#%%\noutcome = 0\n\nfigure()\nplot(likelihood_fct.(θ,outcome))\nplt.show()\n#%%\n\n###########\n### Task 4\n# Evaluate likelihood fct after n flips\n\n#%%\nθ = 0.5\n\n# a)\nprintln(\"a) Regular Likelihood:\")\n\nfor i in 1:3\n n = 10 * 100^(i-1)\n\n outcome = (rand(n) .>= 0.5) * 1\n\n print(\"L(y_1,y_2,...,y_$n | θ = $θ) = \")\n println(likelihood_fct(θ,outcome))\nend\n\nprintln(\"\\nWith rising n, the likelihood -> 0\")\n\n#%%\n# b) and c)\nprintln(\"\\nb) log-likelihoods, l, and L = exp(l):\")\n\nfor i in 1:4\n n = 10 * 100^(i-1)\n\n outcome = (rand(n) .>= 0.5) * 1\n l = log_likelihood_fct(θ,outcome)\n L = exp.(l)\n\n print(\"l(y_1,y_2,...,y_$n | θ = $θ) = \")\n println(l)\n print(\"L(y_1,y_2,...,y_$n | θ = $θ) = \")\n println(L)\nend\n\nprintln(\"\\nYes, n > 100000 could be evaluated without over-/underflow in logarithmic space.\")\n\n#%%\n# d)\nprintln(\"\\nd) Plotting the likelihood function for a series\")\nθ = 0:0.01:1;\n\noutcomeSeries = [[1], [1 1], [1 1 0 1]]\n\nfor thisOutcome in outcomeSeries\n figure()\n subplot(1,2,1)\n plot(θ,likelihood_fct(θ,thisOutcome),label=\"L($thisOutcome|θ)\")\n grid()\n legend()\n subplot(1,2,2)\n plot(θ,log_likelihood_fct(θ,thisOutcome),label=\"l($thisOutcome|θ)\")\n grid()\n legend()\n plt.show()\nend\n#%%\n\n###########\n### Task 5\n# Implement the beta function and create plots\n\n### i)\n# Logarithmic version of the beta-distribution\nfunction Log_Beta(θ,a::Any,b::Any)\n #using SpecialFunctions\n if 0 < θ < 1\n # Numerator\n num = log(θ)*(a-1) + log(1-θ)*(b-1)\n # The denominator (Beta-function) can be integrated or made up of Gamma-functions\n # Since we only treat integer values here, Γ(a) = (a-1)!\n #den = log(factorial(a-1) * factorial(b-1) / factorial(a+b-1))\n den = log(SpecialFunctions.beta(a,b))\n return num - den\n else\n return -Inf\n end\nend\n\n\n#%%\n### ii) sub-tasks 1-3\nfunction Log_posterior(θ,a,b,y)\n heads = sum(y)\n tails = length(y) - heads\n posterior = Array{Float64}(undef,length(θ))\n # Log addition, the brackets are for converting into a single float:\n for ii in 1:length(θ)\n posterior[ii] = (Log_Beta(θ[ii],a,b) .+ log_likelihood_fct(θ[ii], y) .-\n log(SpecialFunctions.beta(a+heads,b+tails)))[1];\n #log(factorial(a+heads-1) * factorial(b+tails-1) / factorial(a+heads+b+tails-1)))[1];\n end\n return posterior\nend\n\n#%%\n\nprintln(\"\\nd) Plotting the likelihood function for a series\")\nθ = 0:0.001:1;\n\n#%%\n# Flat prior:\na = 1;\nb = 1;\n\nfigure()\nsubplot(1,2,1)\nplot(θ,exp.(Log_Beta.(θ,a,b)), label=\"beta(θ,$a,$b)\")\ngrid()\nlegend()\nsubplot(1,2,2)\nplot(θ,Log_Beta.(θ,a,b), label=\"log(beta(θ,$a,$b))\")\ngrid()\nlegend()\nplt.show()\n\n# %%\ny = [1]\na = 1\nb = 1\n\nfigure()\nsubplot(1,2,1)\nplot(θ,exp.(Log_posterior(θ,a,b,y)), label=\"posterior for $y\")\ngrid()\nlegend()\nsubplot(1,2,2)\nplot(θ,Log_posterior(θ,a,b,y), label=\"log-posterior for $y\")\ngrid()\nlegend()\nplt.show()\n\n# Alternatively directly by Beta:\nheads = sum(y)\ntails = length(y) - heads\n\nfigure()\nsubplot(1,2,1)\nplot(θ,exp.(Log_Beta.(θ,a+heads,b+tails)), label=\"beta(θ,$(a+heads),$(b+tails))\")\ngrid()\nlegend()\nsubplot(1,2,2)\nplot(θ,Log_Beta.(θ,a+heads,b+tails), label=\"beta(θ,$(a+heads),$(b+tails))\")\ngrid()\nlegend()\nplt.show()\n\n\n# %%\ny = [1 1]\na = 1\nb = 1\n\nfigure()\nsubplot(1,2,1)\nplot(θ,exp.(Log_posterior(θ,a,b,y)), label=\"posterior for $y\")\ngrid()\nlegend()\nsubplot(1,2,2)\nplot(θ,Log_posterior(θ,a,b,y), label=\"log-posterior for $y\")\ngrid()\nlegend()\nplt.show()\n\n# Alternatively directly by Beta:\nheads = sum(y)\ntails = length(y) - heads\n\nfigure()\nsubplot(1,2,1)\nplot(θ,exp.(Log_Beta.(θ,a+heads,b+tails)), label=\"beta(θ,$(a+heads),$(b+tails))\")\ngrid()\nlegend()\nsubplot(1,2,2)\nplot(θ,Log_Beta.(θ,a+heads,b+tails), label=\"beta(θ,$(a+heads),$(b+tails))\")\ngrid()\nlegend()\nplt.show()\n\n# %%\ny = [1 1 0 1]\na = 1\nb = 1\n\nfigure()\nsubplot(1,2,1)\nplot(θ,exp.(Log_posterior(θ,a,b,y)), label=\"posterior for $y\")\ngrid()\nlegend()\nsubplot(1,2,2)\nplot(θ,Log_posterior(θ,a,b,y), label=\"log-posterior for $y\")\ngrid()\nlegend()\nplt.show()\n\n# Alternatively directly by Beta:\nheads = sum(y)\ntails = length(y) - heads\n\nfigure()\nsubplot(1,2,1)\nplot(θ,exp.(Log_Beta.(θ,a+heads,b+tails)), label=\"beta(θ,$(a+heads),$(b+tails))\")\ngrid()\nlegend()\nsubplot(1,2,2)\nplot(θ,Log_Beta.(θ,a+heads,b+tails), label=\"beta(θ,$(a+heads),$(b+tails))\")\ngrid()\nlegend()\nplt.show()\n\n#%%\n\nprintln(\"The differences are a scaling in the non-log curves and thus\na shifting in the log-curves.\nThe differences arise because before we only used the LIKELIHOOD function\nbefore, but now we use a normalised POSTERIOR.\")\n\n# %%\n### iii) More informative prior and reproduce Fig 6.4\n\n# First Column\nθ = 0:.01:1\na = 100\nb = 100\n\ny = [ones(1,17) zeros(1,3)]\n\nsubplot(3,1,1)\nplot(θ,exp.(Log_Beta.(θ,a,b)))\ngrid()\nsubplot(3,1,2)\nplot(θ,exp.(log_likelihood_fct(θ,y)))\ngrid()\nsubplot(3,1,3)\nplot(θ,exp.(Log_posterior(θ,a,b,y)))\ngrid()\nplt.show()\n#%%\n\n# Second Column\nθ = 0:.01:1\na = 18.25\nb = 6.75\n\ny = [ones(1,17) zeros(1,3)]\n\nsubplot(3,1,1)\nplot(θ,exp.(Log_Beta.(θ,a,b)))\ngrid()\nsubplot(3,1,2)\nplot(θ,exp.(log_likelihood_fct(θ,y)))\ngrid()\nsubplot(3,1,3)\nplot(θ,exp.(Log_posterior(θ,a,b,y)))\ngrid()\nplt.show()\n\n#%%\n\n# Third Column\nθ = 0:.001:1\na = 1\nb = 1\n\ny = [ones(1,17) zeros(1,3)]\n\nsubplot(3,1,1)\nplot(θ,exp.(Log_Beta.(θ,a,b)))\ngrid()\nsubplot(3,1,2)\nplot(θ,exp.(log_likelihood_fct(θ,y)))\ngrid()\nsubplot(3,1,3)\nplot(θ,exp.(Log_posterior(θ,a,b,y)))\ngrid()\nplt.show()\n", "meta": {"hexsha": "565ec63f5cc37de76da8eacc5053758a9bd727f7", "size": 7422, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "A3/A3-TaskB.jl", "max_stars_repo_name": "vis-florum/Applied-Bayesian-Data-Analysis", "max_stars_repo_head_hexsha": "6d460443269d920ea61859df9434938139245c2b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "A3/A3-TaskB.jl", "max_issues_repo_name": "vis-florum/Applied-Bayesian-Data-Analysis", "max_issues_repo_head_hexsha": "6d460443269d920ea61859df9434938139245c2b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "A3/A3-TaskB.jl", "max_forks_repo_name": "vis-florum/Applied-Bayesian-Data-Analysis", "max_forks_repo_head_hexsha": "6d460443269d920ea61859df9434938139245c2b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.3785900783, "max_line_length": 105, "alphanum_fraction": 0.622069523, "num_tokens": 2577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430805473952, "lm_q2_score": 0.8757869965109765, "lm_q1q2_score": 0.817486561576854}} {"text": "# # Wasserstein non-negative matrix factorisation\n#\n# In this example, we implement Wasserstein non-negative matrix factorisation (W-NMF) \n# following the paper [^RCP16] by Rolet et al. \n# \n# [^RCP16]: Rolet, Antoine, Marco Cuturi, and Gabriel Peyré. [\"Fast dictionary learning with a smoothed Wasserstein loss.\"](https://marcocuturi.net/Papers/rolet16fast.pdf) Artificial Intelligence and Statistics. PMLR, 2016.\n#\n# ## Introduction\n# \n# Matrix decomposition is a classical problem in machine learning. Given a $m \\times n$ matrix $X$ representing $n$ repeated $m$-dimensional observations, one may seek matrices $D, \\Lambda$ of appropriate dimensions such that \n# ```math\n# X \\approx D \\Lambda. \n# ```\n# For a target rank $k < \\min \\{ m, n \\}$, i.e. $D \\in \\mathbb{R}^{m \\times k}, \\Lambda \\in \\mathbb{R}^{k \\times n}$, this problem can be thought of as seeking a low-dimensional linear representation $D \\Lambda$ of the potentially high-dimensional dataset $X$. \n#\n# Lee and Seung [^LS99] observed that the data matrix $X$ is non-negative in many practical applications, and that naturally one may want the factor matrices $D, \\Lambda$ to be also non-negative. \n#\n# [^LS99]: Lee, Daniel D., and H. Sebastian Seung. \"Learning the parts of objects by non-negative matrix factorization.\" Nature 401.6755 (1999): 788-791.\n#\n# For a given $m \\times n$ matrix $X \\ge 0$, finding the factor matrices $D \\in \\mathbb{R}^{m \\times k}, \\Lambda \\in \\mathbb{R}^{k \\times n}$ such that $X \\approx D \\Lambda$ with $D \\ge 0, \\Lambda \\ge 0$ is known as the rank-$k$ non-negative matrix factorization (NMF) problem. Typically, such an approximate representation is sought by solving a minimisation problem\n# ```math\n# \\min_{D \\in \\mathbb{R}^{m \\times k}, \\Lambda \\in \\mathbb{R}^{k \\times n}, D \\ge 0, \\Lambda \\ge 0} \\Phi(X, D \\Lambda), \n# ```\n# where $(X, Y) \\mapsto \\Psi(X, Y)$ is a loss function defined on matrices. Commonly used choices of $\\Phi$ include the squared Frobenius loss $\\Phi(X, Y) = \\| X - Y \\|_F^2$ and Kullback-Leibler divergence $\\Phi(X, Y) = \\sum_{ij} X_{ij} \\log(X_{ij}/Y_{ij})$. \n#\n# Both these loss functions (and many other common choices) decompose elementwise in their arguments, that is, they can be written as $\\Phi(X, Y) = \\sum_{ij} f(X_{ij}, Y_{ij})$ for some function $f$ acting on scalars. \n#\n# Rolet et al. note that pointwise loss functions cannot account for spatial correlations in datasets with underlying geometry, and propose to use entropy-regularised optimal transport as a loss function that is sensitive to the spatial arrangement of the data.\n# They argue that for datasets such as images, optimal transport is a more natural choice of loss function, and that it achieves superior performance. \n# \n# In particular, suppose that the columns of $X$ encode image data, and that $C \\in \\mathbb{R}^{m \\times m}$ encodes the squared Euclidean distances on the imaging domain. The problem that Rolet et al. pose is \n# ```math\n# \\min_{D \\in \\mathbb{R}^{m \\times k}_{\\ge 0}, \\Lambda \\in \\mathbb{R}^{k \\times n}_{\\ge 0}} \\sum_{i = 1}^{n} \\operatorname{OT}_{\\varepsilon}(X_i, (D\\Lambda)_i) + \\rho_1 E(D) + \\rho_2 E(\\Lambda),\n# ```\n# where $\\operatorname{OT}_{\\varepsilon}(\\alpha, \\beta)$ is the entropy-regularised optimal transport loss between two probability distributions $\\alpha, \\beta$ for a cost $C$, and $E$ is an entropy barrier function (a smooth approximation to the non-negativity constraint),\n# ```math\n# E(A) = \\sum_{ij} (A_{ij} \\log(A_{ij}) - 1). \n# ```\n# The parameters $\\rho_1, \\rho_2$ control how \"sharp\" the non-negativity constraints are. As $\\rho_1, \\rho_2 \\to 0$, the smoothed constraint approaches the hard non-negativity constraint. Finally, $\\varepsilon$ controls the regularisation level for the optimal transport loss. \n# \n# This example shows how this method can be implemented using functions from the `Dual` submodule of OptimalTransport.jl. \n# \n# ## Set up prerequisites\n# \n# Load packages that will be required later.\n#\nusing OptimalTransport\nimport OptimalTransport.Dual: Dual\nusing MLDatasets: MLDatasets\nusing StatsBase\nusing Plots;\ndefault(; palette=:Set1_3)\nusing LogExpFunctions\nusing NNlib: NNlib\nusing LinearAlgebra\nusing Distances\nusing Base.Iterators\nusing NMF\nusing Optim\n# \n# Define `simplex_norm!`, which normalises `x` to sum to `1` along `dims`. \n#\nfunction simplex_norm!(x; dims=1)\n return x .= x ./ sum(x; dims=dims)\nend\n# \n# ## Implementation\n#\n# We now implement Wasserstein-NMF. Rolet et al. split the original non-convex problem into a pair of convex problems, one for $D$ and one for $\\Lambda$. \n# ```math\n# \\begin{aligned}\n# &\\min_{D \\in \\mathbb{R}^{m \\times k}} \\sum_{i = 1}^{n} \\operatorname{OT}_{\\varepsilon}(X_i, (D\\Lambda)_i) + \\rho_2 E(D), \\\\ \n# &\\min_{\\Lambda \\in \\mathbb{R}^{k \\times n}} \\sum_{i = 1}^{n} \\operatorname{OT}_{\\varepsilon}(X_i, (D\\Lambda)_i) + \\rho_1 E(\\Lambda). \n# \\end{aligned}\n# ```\n# For each of these problems, the dual problem can be derived (see Section 3.3 of Rolet et al. for details on how this is done). These turn out to be \n# ```math \n# \\begin{aligned}\n# &\\min_{G \\in \\mathbb{R}^{m \\times n}} \\sum_{i = 1}^n \\operatorname{OT}_{\\varepsilon}^*(X_i, G_i) + \\rho_2 \\sum_{i = 1}^{n} E^*(-(G \\Lambda^\\top)_i / \\rho_2) \\\\ \n# &\\min_{G \\in \\mathbb{R}^{m \\times n}} \\sum_{i = 1}^n \\operatorname{OT}_{\\varepsilon}^*(X_i, G_i) + \\rho_1 \\sum_{i = 1}^{n} E^*(-(D^\\top G)_i / \\rho_1). \n# \\end{aligned}\n# ```\n# The semi-dual of entropy-regularised optimal transport loss, $\\operatorname{OT}_{\\varepsilon}$, is implemented as `Dual.ot_entropic_semidual` and its gradient can be computed by `Dual.ot_entropic_semidual_grad`. $E^*$ turns out to be `logsumexp`, for which we implement a wrapper function:\n#\nfunction E_star(x; dims=1)\n return logsumexp(x; dims=dims)\nend;\n# \n# The gradient of `logsumexp` is `softmax`, so we define also its gradient:\n#\nfunction E_star_grad(x; dims=1)\n return NNlib.softmax(x; dims=1)\nend;\n# \n# Thus, for each problem we may define the dual objective and its gradient. We note that `ot_entropic_semidual(_grad)` automatically broadcasts along columns of its input. There is therefore no need to make multiple calls to the function, thus allowing for more efficient evaluation.\n#\nfunction dual_obj_weights(X, K, ε, D, G, ρ1)\n return sum(Dual.ot_entropic_semidual(X, G, ε, K)) + ρ1 * sum(E_star(-D' * G / ρ1))\nend\nfunction dual_obj_weights_grad!(∇, X, K, ε, D, G, ρ1)\n return ∇ .= Dual.ot_entropic_semidual_grad(X, G, ε, K) - D * E_star_grad(-D' * G / ρ1)\nend\nfunction dual_obj_dict(X, K, ε, Λ, G, ρ2)\n return sum(Dual.ot_entropic_semidual(X, G, ε, K)) + ρ2 * sum(E_star(-G * Λ' / ρ2))\nend\nfunction dual_obj_dict_grad!(∇, X, K, ε, Λ, G, ρ2)\n return ∇ .= Dual.ot_entropic_semidual_grad(X, G, ε, K) - E_star_grad(-G * Λ' / ρ2) * Λ\nend;\n# \n# The only remaining part of Wasserstein-NMF to implement is the conversion at optimality from the dual variable $G$ to the primal variables $D, \\Lambda$. From the results of Theorems 3 and 4 in Rolet et al., we have for $\\Lambda$:\n# ```math\n# \\Lambda_i = \\operatorname{softmax}((-D^\\top G)_i / \\rho_1),\n# ```\n# and we have for $D$:\n# ```math\n# D_i = \\operatorname{softmax}((-G \\Lambda^\\top)_i / \\rho_2). \n# ```\n#\nfunction getprimal_weights(D, G, ρ1)\n return NNlib.softmax(-D' * G / ρ1; dims=1)\nend\nfunction getprimal_dict(Λ, G, ρ2)\n return NNlib.softmax(-G * Λ' / ρ2; dims=1)\nend;\n# \n# We can now implement functions `solve_weights` and `solve_dict` that solve the respective dual problems for the next iterates of `Λ` and `D`. \n#\nfunction solve_weights(X, K, ε, D, ρ1; alg, options)\n opt = optimize(\n g -> dual_obj_weights(X, K, ε, D, g, ρ1),\n (∇, g) -> dual_obj_weights_grad!(∇, X, K, ε, D, g, ρ1),\n zero.(X),\n alg,\n options,\n )\n return getprimal_weights(D, Optim.minimizer(opt), ρ1)\nend\nfunction solve_dict(X, K, ε, Λ, ρ2; alg, options)\n opt = optimize(\n g -> dual_obj_dict(X, K, ε, Λ, g, ρ2),\n (∇, g) -> dual_obj_dict_grad!(∇, X, K, ε, Λ, g, ρ2),\n zero.(X),\n alg,\n options,\n )\n return getprimal_dict(Λ, Optim.minimizer(opt), ρ2)\nend;\n\n#\n# ## Example: noisy univariate Gaussians\n# \n# We set up each observation as a mixture of 3 Gaussians with means sampled from `N(6, σ), N(0, σ), N(-6, σ)` respectively, and mixture weights sampled uniformly from `[0, 1]`. The resulting mixture model is normalised to sum to 1 on the discrete domain `coord`. \n#\nf(x, μ, σ) = exp.(-(x .- μ) .^ 2)\ncoord = range(-12, 12; length=100)\nN = 100\nσ = 1\nX = hcat(\n [\n rand() * f(coord, σ * randn() + 6, 1) +\n rand() * f(coord, σ * randn(), 1) +\n rand() * f(coord, σ * randn() - 6, 1) for _ in 1:N\n ]...,\n)\nX = simplex_norm!(X);\n# \n# We visualise the observations. \n#\nplot(coord, X; alpha=0.1, color=:blue, title=\"Input data\", legend=nothing)\n# \n# We can apply NMF with a squared Frobenius loss using the NMF.jl package. We seek `k = 3` components. This performs poorly, since the pointwise nature of the loss function cannot handle the translational noise in the data.\n# \nk = 3\nresult = nnmf(X, k; alg=:multmse)\nplot(coord, result.W; title=\"NMF with Frobenius loss\", palette=:Set1_3)\n#\n# We can now set up a cost matrix corresponding to the domain `coord`. \n#\nC = pairwise(SqEuclidean(), coord)\nC = C / mean(C);\n# Specify parameters\nε = 0.025\nρ1, ρ2 = (5e-2, 5e-2);\n# Compute Gibbs kernel \nK = exp.(-C / ε);\n# \n# Now we use a random initialisation, where columns of `D` and `Λ` are normalised to sum to 1. \n# \nD = rand(size(X, 1), k) # dictionary \nsimplex_norm!(D; dims=1) # norm columnwise\nΛ = rand(k, size(X, 2)) # weights\nsimplex_norm!(Λ; dims=1); # norm rowwise\n# \n# We now run 10 iterations of Wasserstein-NMF.\n#\nn_iter = 10\nfor iter in 1:n_iter\n @info \"Wasserstein-NMF: iteration $iter\"\n D .= solve_dict(\n X,\n K,\n ε,\n Λ,\n ρ2;\n alg=LBFGS(),\n options=Optim.Options(;\n iterations=250, g_tol=1e-4, show_trace=false, show_every=10\n ),\n )\n Λ .= solve_weights(\n X,\n K,\n ε,\n D,\n ρ1;\n alg=LBFGS(),\n options=Optim.Options(;\n iterations=250, g_tol=1e-4, show_trace=false, show_every=10\n ),\n )\nend\n# \n# We observe that Wasserstein-NMF learns atoms (columns of $D$) corresponding to the three Gaussians used to generate the input data.\n#\nplot(coord, D; title=\"NMF with Wasserstein loss\", palette=:Set1_3)\n\n# ## Example: image data (MNIST)\n# Here we will download MNIST dataset using MLDatasets.jl and downscale each image to 14x14 to allow for faster runtime (since we are running on CPU). \n#\nsizex, sizey = 28, 28\nfactor = 2 # downscale factor \nΣ = hcat([sum(I(sizex)[:, i:(i + factor - 1)]; dims=2) for i in 1:factor:sizex]...)\nsizex, sizey = sizex ÷ factor, sizey ÷ factor\nN = 256\nx, y = MLDatasets.MNIST.traindata(Float64, sample(1:60_000, N; replace=false))\nx = permutedims(x, (2, 1, 3))\nx = cat([Σ' * x[:, :, i] * Σ for i in 1:N]...; dims=3)\nX = simplex_norm!(reshape(x, (sizex * sizey, :)));\n# \n# The columns of `X` now correspond to images \"flattened\" as vectors. We can preview a few images.\n#\nM = 25\nplot(\n [\n heatmap(\n reshape(X[:, i], sizex, sizey);\n legend=:none,\n axis=nothing,\n showaxis=false,\n aspect_ratio=:equal,\n c=:Blues,\n yflip=true,\n ) for i in 1:M\n ]...;\n layout=(5, M ÷ 5),\n plot_title=\"Input images\",\n)\n\n# Now we can set up `coord`, cost matrix `C`, and specify parameters.\n#\ncoord = reshape(collect(product(1:sizex, 1:sizey)), :)\nC = pairwise(SqEuclidean(), coord)\nC = C / mean(C);\nε = 0.0025\nρ1, ρ2 = (5e-3, 5e-3);\n# We compute the Gibbs kernel from `C`:\nK = exp.(-C / ε);\n# \n# Let us aim to learn `k = 25` atoms.\nk = 25;\n# \n# Initialise again randomly \n#\nD = rand(size(X, 1), k) # dictionary \nsimplex_norm!(D; dims=1) # norm columnwise\nΛ = rand(k, size(X, 2)) # weights\nsimplex_norm!(Λ; dims=1); # norm rowwise\n# \n# We now run 15 iterations of Wasserstein-NMF.\n#\nn_iter = 15\nfor iter in 1:n_iter\n @info \"Wasserstein-NMF: iteration $iter\"\n D .= solve_dict(\n X,\n K,\n ε,\n Λ,\n ρ2;\n alg=LBFGS(),\n options=Optim.Options(;\n iterations=250, g_tol=1e-4, show_trace=false, show_every=10\n ),\n )\n Λ .= solve_weights(\n X,\n K,\n ε,\n D,\n ρ1;\n alg=LBFGS(),\n options=Optim.Options(;\n iterations=250, g_tol=1e-4, show_trace=false, show_every=10\n ),\n )\nend\n# \n# We can inspect the atoms learned (columns of `D`):\n#\n\nplot(\n [\n heatmap(\n reshape(D[:, i], sizex, sizey);\n legend=:none,\n axis=nothing,\n showaxis=false,\n aspect_ratio=:equal,\n c=:Blues,\n yflip=true,\n ) for i in 1:k\n ]...;\n layout=(5, k ÷ 5),\n plot_title=\"Learned atoms\",\n)\n\n# \n# Finally, we can look at the images constructed by the low-rank approximation `DΛ` and compare to the original images that we previewed earlier. \n#\nX_hat = D * Λ\nplot(\n [\n heatmap(\n reshape(X_hat[:, i], sizex, sizey);\n legend=:none,\n axis=nothing,\n showaxis=false,\n aspect_ratio=:equal,\n c=:Blues,\n yflip=true,\n ) for i in 1:M\n ]...;\n layout=(5, M ÷ 5),\n plot_title=\"Low rank approximation\",\n)\n", "meta": {"hexsha": "9678360277b26d761dbe88e08827283e8de01d63", "size": 13426, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/nmf/script.jl", "max_stars_repo_name": "zsteve/ot.jl", "max_stars_repo_head_hexsha": "a82e3fb19b00839ba809225e76a4ea43b49a315d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 41, "max_stars_repo_stars_event_min_datetime": "2021-05-28T14:16:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T17:38:40.000Z", "max_issues_repo_path": "examples/nmf/script.jl", "max_issues_repo_name": "zsteve/ot.jl", "max_issues_repo_head_hexsha": "a82e3fb19b00839ba809225e76a4ea43b49a315d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 109, "max_issues_repo_issues_event_min_datetime": "2021-05-18T18:45:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-30T12:30:01.000Z", "max_forks_repo_path": "examples/nmf/script.jl", "max_forks_repo_name": "zsteve/ot.jl", "max_forks_repo_head_hexsha": "a82e3fb19b00839ba809225e76a4ea43b49a315d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-08-30T12:11:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T19:11:56.000Z", "avg_line_length": 38.8034682081, "max_line_length": 367, "alphanum_fraction": 0.6428571429, "num_tokens": 4280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.8757869851639066, "lm_q1q2_score": 0.8174865558506246}} {"text": "\nusing JuMP\nusing GLPK\nusing GraphPlot \nusing LightGraphs\nusing Colors\nusing LinearAlgebra\n\n\nG = [\n 0 1 0 0 0 0;\n 1 0 1 1 0 0;\n 0 1 0 0 1 1;\n 0 1 0 0 1 0;\n 0 0 1 1 0 0;\n 0 0 1 0 0 0;\n]\n\ng = SimpleGraph(G)\n \ngplot(g)\n\n\nvertex_cover = Model(GLPK.Optimizer)\n\n@variable(vertex_cover, y[1:nv(g)], Bin)\n@constraint(vertex_cover, [i = 1:nv(g), j = 1:nv(g); G[i,j] == 1], y[i] + y[j] >= 1)\n@objective(vertex_cover, Min, sum(y))\n\noptimize!(vertex_cover)\n@show value.(y);\n\n\nmembership = round.(Int, value.(y)) # Change to Int \nmembership = membership + ones(Int, nv(g)) # Make the color groups one indexed\nnodecolor = [colorant\"red\", colorant\"blue\"] # Blue to represent vertices in the cover\nnodefillc = nodecolor[membership]\ngplot(g, nodefillc = nodefillc)\n\n\nG = [\n 0 1 0 0 0 0 0 0 0 1 0 ;\n 1 0 1 0 0 0 0 0 0 0 1;\n 0 1 0 1 0 1 0 0 0 0 0;\n 0 0 1 0 1 0 0 0 0 0 0;\n 0 0 0 1 0 1 0 0 0 0 0;\n 0 0 1 0 1 0 1 0 0 0 0;\n 0 0 0 0 0 1 0 1 0 0 0;\n 0 0 0 0 0 0 1 0 1 0 1;\n 0 0 0 0 0 0 0 1 0 1 1;\n 1 0 0 0 0 0 0 0 1 0 1;\n 0 1 0 0 0 0 0 1 1 1 0;\n]\n\ng = SimpleGraph(G)\n \ngplot(g)\n\n\ndominating_set = Model(GLPK.Optimizer)\n\n@variable(dominating_set, x[1:nv(g)], Bin)\n@constraint(dominating_set, [i = 1:nv(g)], dot(G[i,:], x) >= 1)\n@objective(dominating_set, Min, sum(x))\n\noptimize!(dominating_set)\n@show value.(x);\n\n\nmembership = convert(Array{Int},value.(x)) # Change to Int \nmembership = membership + ones(Int, nv(g)) # Make the color groups one indexed\nnodecolor = [colorant\"red\", colorant\"blue\"] # Blue to represent vertices in the set\nnodefillc = nodecolor[membership]\ngplot(g, nodefillc = nodefillc)\n\n\nG = [\n 0 0 0 0 1 0 0 0;\n 0 0 0 0 0 1 0 0;\n 0 0 0 0 0 0 1 0;\n 0 0 0 0 0 0 0 1;\n 1 0 0 0 0 1 0 1;\n 0 1 0 0 1 0 1 0;\n 0 0 1 0 0 1 0 1;\n 0 0 0 1 1 0 1 0;\n]\n\ng = SimpleGraph(G)\n \ngplot(g)\n\n\nmatching = Model(GLPK.Optimizer)\n\n@variable(matching, m[i = 1:nv(g), j = 1:nv(g)], Bin)\n@constraint(matching, [i = 1:nv(g)], sum(m[i,:]) <= 1)\n@constraint(matching, [i = 1:nv(g), j = 1:nv(g); G[i,j] == 0], m[i,j] == 0)\n@constraint(matching, [i = 1:nv(g), j = 1:nv(g)], m[i,j] == m[j,i])\n@objective(matching, Max, sum(m))\n\noptimize!(matching)\n@show value.(m);\n\n\nG = [\n 0 1 0 0 1 1 0 0 0 0;\n 1 0 1 0 0 0 1 0 0 0;\n 0 1 0 1 0 0 0 1 0 0;\n 0 0 1 0 1 0 0 0 1 0;\n 1 0 0 1 0 0 0 0 0 1;\n 1 0 0 0 0 0 1 0 0 1;\n 0 1 0 0 0 1 0 1 0 0;\n 0 0 1 0 0 0 1 0 1 0;\n 0 0 0 1 0 0 0 1 0 1;\n 0 0 0 0 1 1 0 0 1 0;\n]\n\ng = SimpleGraph(G)\n \ngplot(g)\n\n\nk = nv(g)\n\nk_colouring = Model(GLPK.Optimizer)\n\n@variable(k_colouring, z[1:k], Bin)\n@variable(k_colouring, c[1:nv(g),1:k], Bin)\n@constraint(k_colouring, [i = 1:nv(g)], sum(c[i,:]) == 1)\n@constraint(k_colouring, [i = 1:nv(g), j = 1:nv(g), l = 1:k; G[i,j] == 1], c[i,l] + c[j,l] <= 1)\n@constraint(k_colouring, [i = 1:nv(g), l = 1:k], c[i,l] <= z[l])\n\n@objective(k_colouring, Min, sum(z))\n\noptimize!(k_colouring)\n@show value.(z);\n@show value.(c);\n\n\nc = value.(c)\nmembership = zeros(nv(g))\nfor i in 1:nv(g)\n for j in 1:k\n if c[i,j] == 1\n membership[i] = j\n break\n end\n end\nend\nmembership = convert(Array{Int},membership)\n\nnodecolor = distinguishable_colors(nv(g), colorant\"green\")\nnodefillc = nodecolor[membership]\ngplot(g, nodefillc = nodefillc)\n\n", "meta": {"hexsha": "a97bc687dde743a9c198cd38ffbbcf2ae7086a94", "size": 3302, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/modelling/problems_on_graphs.jl", "max_stars_repo_name": "mtanneau/JuMPTutorials.jl", "max_stars_repo_head_hexsha": "f91839c6b127966c3cb17e8971cc95fe3adfa814", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 75, "max_stars_repo_stars_event_min_datetime": "2020-06-15T13:05:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T12:58:48.000Z", "max_issues_repo_path": "test/modelling/problems_on_graphs.jl", "max_issues_repo_name": "mtanneau/JuMPTutorials.jl", "max_issues_repo_head_hexsha": "f91839c6b127966c3cb17e8971cc95fe3adfa814", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34, "max_issues_repo_issues_event_min_datetime": "2019-05-27T05:36:48.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-22T09:52:29.000Z", "max_forks_repo_path": "test/modelling/problems_on_graphs.jl", "max_forks_repo_name": "mtanneau/JuMPTutorials.jl", "max_forks_repo_head_hexsha": "f91839c6b127966c3cb17e8971cc95fe3adfa814", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2019-10-09T09:32:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-02T17:41:21.000Z", "avg_line_length": 21.1666666667, "max_line_length": 96, "alphanum_fraction": 0.5748031496, "num_tokens": 1542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897492587141, "lm_q2_score": 0.8688267864276108, "lm_q1q2_score": 0.8173833345524862}} {"text": "using OrdinaryDiffEq\r\nusing LabelledArrays\r\n\r\nfunction f(out,du,u,p,t)\r\n out.x = - 0.04u.x + 1e4*u.y*u.z - du.x\r\n out.y = + 0.04u.x - 3e7*u.y^2 - 1e4*u.y*u.z - du.y\r\n out.z = u.x + u.y + u.z - 1.0\r\nend\r\n\r\nu₀ = LVector(x=1.0, y=0.0, z=0.0)\r\ndu₀ = LVector(x=-0.04, y=0.04, z=0.0)\r\ntspan = (0.0,100000.0)\r\n\r\ndifferential_vars = LVector(x=true, y=true, z=false)\r\nprob = DAEProblem(f,du₀,u₀,tspan,differential_vars=differential_vars)\r\n\r\nsol = solve(prob, DImplicitEuler())\r\n\r\nfunction f1(du,u,p,t)\r\n du.x .= -1 .* u.x .* u.y .* p[1]\r\n du.y .= -1 .* u.y .* p[2]\r\nend\r\nconst n = 1000\r\nu_0 = @LArray fill(1000.0,2*n) (x = (1:n),y = (n+1:2*n))\r\np = [0.1,0.1]\r\nprob1 = ODEProblem(f1,u_0,(0,100.0),p)\r\nsol = solve(prob1, Rodas5())\r\nsol = solve(prob1, Rodas5(autodiff=false))\r\n", "meta": {"hexsha": "2eaf4b00e2fec6b80398e7ecebb6e13dfdbea98d", "size": 786, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/downstream/labelledarrays.jl", "max_stars_repo_name": "frankschae/DiffEqBase.jl", "max_stars_repo_head_hexsha": "406640750d8bf6e38009a40d377fa6d95717fe04", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 134, "max_stars_repo_stars_event_min_datetime": "2020-04-05T14:58:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T22:12:24.000Z", "max_issues_repo_path": "test/downstream/labelledarrays.jl", "max_issues_repo_name": "frankschae/DiffEqBase.jl", "max_issues_repo_head_hexsha": "406640750d8bf6e38009a40d377fa6d95717fe04", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 130, "max_issues_repo_issues_event_min_datetime": "2020-03-25T17:50:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:37:59.000Z", "max_forks_repo_path": "test/downstream/labelledarrays.jl", "max_forks_repo_name": "frankschae/DiffEqBase.jl", "max_forks_repo_head_hexsha": "406640750d8bf6e38009a40d377fa6d95717fe04", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 45, "max_forks_repo_forks_event_min_datetime": "2020-03-27T09:11:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T11:32:35.000Z", "avg_line_length": 27.1034482759, "max_line_length": 70, "alphanum_fraction": 0.5699745547, "num_tokens": 342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897492587141, "lm_q2_score": 0.868826784729373, "lm_q1q2_score": 0.8173833329548016}} {"text": "\"\"\"\n\n```\nsphereradiusfromshellvolume(volume,step)\n```\n\nComputes the radius that corresponds to a spherical shell of\na given volume.\n\n\"\"\"\nfunction sphereradiusfromshellvolume(volume,step)\n\n fourthirdsofpi = 4*pi/3\n if 3*step*volume - pi*step^4 <= 0.\n return 0.\n end\n rmin = (sqrt(3*pi)*sqrt(3*step*volume-pi*step^4)-3*pi*step^2)/(6*pi*step)\n return ( 0.5*( volume/fourthirdsofpi + 2*rmin^3 ) )^(1/3)\n\nend\n\n", "meta": {"hexsha": "bc12aa59e0659ecd68e0123eb05410588178ee91", "size": 413, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/sphereradiusfromshellvolume.jl", "max_stars_repo_name": "m3g/ComplexMixtures.jl", "max_stars_repo_head_hexsha": "0ba3d05f31742752dae37bd4192122d95c984c7f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-05-14T02:35:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-22T15:56:19.000Z", "max_issues_repo_path": "src/sphereradiusfromshellvolume.jl", "max_issues_repo_name": "m3g/ComplexMixtures.jl", "max_issues_repo_head_hexsha": "0ba3d05f31742752dae37bd4192122d95c984c7f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2021-03-18T19:41:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-26T13:56:17.000Z", "max_forks_repo_path": "src/sphereradiusfromshellvolume.jl", "max_forks_repo_name": "m3g/ComplexMixtures.jl", "max_forks_repo_head_hexsha": "0ba3d05f31742752dae37bd4192122d95c984c7f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.7727272727, "max_line_length": 75, "alphanum_fraction": 0.6803874092, "num_tokens": 151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799462157138, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.8172543261164037}} {"text": "\"\"\"\n game(decisionMatrix; verbose = false)\n\n Solve the zero-sum game.\n\n# Arguments:\n - `decisionMatrix::Array{Float,2}`: n × m matrix of gain values for row player. \n - `verbose::Bool`: Logical value indicating whether the optimization logs are shown or not. Default is false. \n\n# Description \ngame() solves zero-sum games using a gain matrix designed for the row player. The game matrix has n rows \nand m columns for n and m strategies of row and column players, respectively. \n\n# Output \n- `::GameResult`: GameResult object that holds mixed strategy probabilities for row player and the value of game.\nIf a pure strategy exists for the row player, than the propabilities vector is a one-hat vector.\n\n# Examples\n```julia-repl\njulia> # Rock & Paper & Scissors game\njulia> mat = [0 -1 1; 1 0 -1; -1 1 0]\n3×3 Array{Int64,2}:\n 0 -1 1\n 1 0 -1\n -1 1 0\n\njulia> dm = makeDecisionMatrix(mat)\n3×3 DataFrame\n Row │ Crt1 Crt2 Crt3 \n │ Float64 Float64 Float64 \n─────┼───────────────────────────\n 1 │ 0.0 -1.0 1.0\n 2 │ 1.0 0.0 -1.0\n 3 │ -1.0 1.0 0.0\n\njulia> result = game(dm);\n\njulia> result.row_player_probabilities\n3-element Array{Float64,1}:\n 0.3333333333333333\n 0.33333333333333337\n 0.3333333333333333\n\njulia> result.value\n0.0\n\n```\n\n# References\nZhou, Hai-Jun. \"The rock–paper–scissors game.\" Contemporary Physics 57.2 (2016): 151-163.\n\"\"\"\n function game(decisionMatrix::DataFrame; verbose::Bool=false)::GameResult\n \n newDecisionMatrix = similar(decisionMatrix)\n \n nrow, ncol = size(decisionMatrix)\n\n minmat = minimum(decisionMatrix)\n modified = false\n\n if minmat < 0\n modified = true\n newDecisionMatrix = decisionMatrix .- minmat \n end\n\n # dm = convert(Matrix, newDecisionMatrix)\n dm = Matrix(newDecisionMatrix)\n \n model = Model(GLPK.Optimizer);\n MOI.set(model, MOI.Silent(), !verbose)\n\n\n @variable(model, x[1:nrow])\n @objective(model, Min, sum(x))\n\n for i in 1:nrow\n @constraint(model, sum(x[1:nrow] .* dm[:, i]) >= 1)\n end\n\n for i in 1:nrow\n @constraint(model, x[i] >= 0)\n end\n\n optimize!(model);\n\n values = JuMP.value.(x)\n\n gamevalue = 1 / objective_value(model)\n p = gamevalue * values\n \n if modified\n gamevalue -= abs(minmat)\n end\n\nresult = GameResult(\n p,\n gamevalue\n )\n \n return result\n\nend", "meta": {"hexsha": "31859a2db047ce6bd687d48bc9d02740bbac64e8", "size": 2415, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/game.jl", "max_stars_repo_name": "jbytecode/jMCDM", "max_stars_repo_head_hexsha": "04fd374fd8cff2ba359e2f51568c65ea1675b93d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2021-02-09T17:42:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T22:21:26.000Z", "max_issues_repo_path": "src/game.jl", "max_issues_repo_name": "jbytecode/jMCDM", "max_issues_repo_head_hexsha": "04fd374fd8cff2ba359e2f51568c65ea1675b93d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2021-02-09T16:56:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T18:11:34.000Z", "max_forks_repo_path": "src/game.jl", "max_forks_repo_name": "jbytecode/jMCDM", "max_forks_repo_head_hexsha": "04fd374fd8cff2ba359e2f51568c65ea1675b93d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2021-02-12T16:01:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T22:02:44.000Z", "avg_line_length": 23.6764705882, "max_line_length": 113, "alphanum_fraction": 0.6293995859, "num_tokens": 732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.942506716354847, "lm_q2_score": 0.8670357563664174, "lm_q1q2_score": 0.8171870236951532}} {"text": "\n\"\"\"\n ways_place_containers(x,m)\n\nGiven containers of sizes x, and m balls, enumerate all the ways to place the balls\ninto the containers without violating the constraints.\n\nLets illustrate this function through an example. Suppose we want to find\nall the ways to place 4 balls into 4 containers with capacities [2,1,3,4]\n\nWe define f(m,e) as the number of solutions of placing m balls into the\ne leftmost containers. Then we could build a table, vertically m and horizontally e.\n\nThe base cases are\nm e| 1 2 3 4\n--------------------------\n0 | 1 1 1 1\n1 | 1\n2 | 1\n3 | 0\n4 | 0\n\nAnd then we could fill in the rest of the table using the recursive formula\nf(m,e)=∑f(m-i,e-1) where i=0:min(m,c[e]), where c[e] is the capacity of the e^th container.\n\nm e| 1 2 3 4\n--------------------------\n0 | 1 1 1 1\n1 | 1 2 3 4\n2 | 1 2 5 9\n3 | 0 1 6 15\n4 | 0 0 5 20\n\nThen we could use this table to build the actual solutions with another builder function.\n\"\"\"\nfunction ways_place_containers(x,m)\n #assume x=[x_1,x_2,x_3...x_n] respresents n containers each with\n #positive capacity x_i. Now we want to place m balls into these containers\n #without breaking the capacity\n #this solution will use a dynamic programming approach.\n #First, find the number of solutions, then allocate an array, then\n #build that table using the solution table and a builder function.\n\n #base cases\n solution_table = zeros(Int64,m+1,length(x))\n solution_table[1,1:end] .= 1\n for r = 2:m+1\n solution_table[r,1] = r-1 <= x[1]\n end\n\n #build solution table\n for c=2:length(x)\n for r=2:m+1\n solution_table[r,c] = sum(solution_table[r-min(r-1,x[c]):r,c-1])\n end\n end\n\n ways = zeros(Int64,solution_table[end,end],length(x))\n table_builder!(ways,solution_table,x,1,length(x),m)\n return ways\nend\n\nfunction table_builder!(output,solution_table,container_sizes,row,col,balls_left)\n (balls_left <= 0) && return\n r1 = row\n for balls_to_place = 0:min(balls_left,container_sizes[col])\n if col==1\n output[row,col] = balls_left\n continue\n end\n ways = solution_table[balls_left + 1 - balls_to_place,col-1]\n ways <= 0 && continue\n output[r1:r1+ways-1,col] .= balls_to_place\n table_builder!(output,solution_table,container_sizes,r1,col-1,balls_left - balls_to_place)\n\n r1 = r1 +ways\n end\nend\n\n\"\"\"\n canonical_placement(x,y)\n\nGiven containers of size x, and number of balls to place into each container y,\nreturn the placement as a tuple of 1s and 0s.\n\nExample:\n\ncanonical_placement([2,3,4],[1,1,1]) returns\n\n(1,0,1,0,0,1,0,0,0)\n\nWhich one could think of as 10|100|1000\n\n\"\"\"\nfunction canonical_placement(x,y)\n #assume x=[x_1,x_2,x_3...x_n] respresents n containers each with positive capacity x_i.\n #assume y=[y_1,y_2,y_3...y_n] means placed 0<=y_i<=x_i balls into container i\n #returns one way this could have happened.\n #For example, x=[1,2,6],y=[1,1,2] could be 1|10|010100 or 1|01|110000\n tmp = zeros(Int,sum(x))\n ind = 1\n for i = 1:length(x)\n tmp[ind:ind+y[i]-1] .= 1\n ind += x[i]\n end\n return tmp\nend\n\nfunction count_occurrences(factor)\n #assume factor is a sorted tuple like (0,0,0,1,1,3,3)\n #returns two arrays, the first one keys, the second one\n #number of occurrences, like for this case,\n #[0,1,3],[3,2,2]\n x = [factor[1]]\n y = [1]\n for i=2:length(factor)\n if factor[i] == factor[i-1]\n y[end] += 1\n else\n push!(x,factor[i])\n push!(y,1)\n end\n end\n return x,y\nend\n", "meta": {"hexsha": "f4d678c81ab6ed45a8155c120eb72b1918108d3b", "size": 3702, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utilities.jl", "max_stars_repo_name": "yushoteke/SymmetricPolynomials", "max_stars_repo_head_hexsha": "fc721fbd6995e123f246cb69f1fbac2eb1844a2c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-09-28T14:20:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-01T15:37:23.000Z", "max_issues_repo_path": "src/utilities.jl", "max_issues_repo_name": "yushoteke/SymmetricPolynomials", "max_issues_repo_head_hexsha": "fc721fbd6995e123f246cb69f1fbac2eb1844a2c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utilities.jl", "max_forks_repo_name": "yushoteke/SymmetricPolynomials", "max_forks_repo_head_hexsha": "fc721fbd6995e123f246cb69f1fbac2eb1844a2c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.380952381, "max_line_length": 98, "alphanum_fraction": 0.6285791464, "num_tokens": 1153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067228145364, "lm_q2_score": 0.8670357477770336, "lm_q1q2_score": 0.8171870212003829}} {"text": "module problem123\n\ndescription = \"\"\"\nPrime square remainders\n\nLet pn be the nth prime: 2, 3, 5, 7, 11, ..., and let r be the remainder when (pn−1)^n + (pn+1)^n is divided by pn^2.\nFor example, when n = 3, p3 = 5, and 4^3 + 6^3 = 280 ≡ 5 mod 25.\nThe least value of n for which the remainder first exceeds 10^9 is 7037.\n\nFind the least value of n for which the remainder first exceeds 10^10.\n\"\"\"\n\n# Computes a^b % n\n# Definition from Wikipedia on Modular exponentiation: http://en.wikipedia.org/wiki/Modular_exponentiation\n# BigInt is required, as a*a will overflow for large a and n\nfunction powmod(a :: BigInt, b :: Integer, n :: Integer)\n x = BigInt(1)\n a = a % n\n while b > 0\n if (b % 2) == 1\n x = (x * a) % n\n end\n b = b >> 1\n a = (a * a) % n\n end\n return x\nend\n\nfunction solve(rmin = 10^10, maxprime = 10^6)\n ps = primes(maxprime)\n for n = 1:length(ps)\n p = BigInt(ps[n])\n psq = p * p\n if psq < rmin\n continue\n end\n r = (powmod(p-1, n, psq) + powmod(p+1, n, psq)) % psq\n if r > rmin\n return n\n end\n end\n error(\"No solution for rmin=$rmin maxprime=$maxprime\")\nend\n\nusing Base.Test\n\n@test (powmod(BigInt(4), 3, 25) + powmod(BigInt(6), 3, 25)) % 25 == 5\n@test solve(10^9) == 7037\n\nend", "meta": {"hexsha": "3892ae6b318c935800ead6f8df9cbf5f6db1e5cc", "size": 1242, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/problem123.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/problem123.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/problem123.jl", "max_forks_repo_name": "mbuhot/mbuhot-euler-solutions", "max_forks_repo_head_hexsha": "30066543cfd2d84976beb0605839750b64f4b8ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.84, "max_line_length": 117, "alphanum_fraction": 0.6119162641, "num_tokens": 457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542864252023, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.8171541782344595}} {"text": "# ------------------------------------------------------------------\n# Licensed under the MIT License. See LICENSE in the project root.\n# ------------------------------------------------------------------\n\n\"\"\"\n Scale(; low=0.25, high=0.75)\n\nThe scale transform of `x` is the value `(x .- xl) ./ (xh .- xl))`\nwhere `xl = quantile(x, low)` and `xh = quantile(x, high)`.\n\"\"\"\nstruct Scale <: Colwise\n low::Float64\n high::Float64\n\n function Scale(low, high)\n @assert 0 ≤ low ≤ high ≤ 1 \"invalid quantiles\"\n new(low, high)\n end\nend\n\nScale(; low=0.25, high=0.75) = Scale(low, high)\n\nassertions(::Type{Scale}) = [assert_continuous]\n\nisrevertible(::Type{Scale}) = true\n\nfunction colcache(transform::Scale, x)\n levels = (transform.low, transform.high)\n xl, xh = quantile(x, levels)\n xl == xh && ((xl, xh) = (zero(xl), one(xh)))\n (xl=xl, xh=xh)\nend\n\ncolapply(::Scale, x, c) = @. (x - c.xl) / (c.xh - c.xl)\n\ncolrevert(::Scale, y, c) = @. (c.xh - c.xl) * y + c.xl\n\n\"\"\"\n MinMax()\n\nThe transform that is equivalent to `Scale(low=0, high=1)`.\n\"\"\"\nMinMax() = Scale(low=0.0, high=1.0)\n\n\"\"\"\n Interquartile()\n\nThe transform that is equivalent to `Scale(low=0.25, high=0.75)`.\n\"\"\"\nInterquartile() = Scale(low=0.25, high=0.75)\n", "meta": {"hexsha": "8610022ad62dc58a7fd05debd7ccd49c5b04234f", "size": 1229, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/transforms/scale.jl", "max_stars_repo_name": "ablaom/TableTransforms.jl", "max_stars_repo_head_hexsha": "d65b4ba141ab9cf294e00331e32e579c51e246c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/transforms/scale.jl", "max_issues_repo_name": "ablaom/TableTransforms.jl", "max_issues_repo_head_hexsha": "d65b4ba141ab9cf294e00331e32e579c51e246c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/transforms/scale.jl", "max_forks_repo_name": "ablaom/TableTransforms.jl", "max_forks_repo_head_hexsha": "d65b4ba141ab9cf294e00331e32e579c51e246c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0980392157, "max_line_length": 68, "alphanum_fraction": 0.5427176566, "num_tokens": 393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403959948494, "lm_q2_score": 0.8791467643431002, "lm_q1q2_score": 0.8171145167886417}} {"text": "export sample_banana, log_pdf_banana\n\n\"\"\"\n sample_banana(N; μ = 0.0, σ = 2.0, bananicity = 0.2)\n\nGenerate `N` samples [x₁; x₂] of the Banana distribution defined as:\n x₁ ∼ N(μ, σ²),\n ϵ ∼ N(0, 1),\n x₂ ∼ bananicity × (x₁ - σ²) + ϵ.\n\"\"\"\nfunction sample_banana(N; μ = 0.0, σ = 2.0, bananicity = 0.2)\n X = zeros(2,N)\n for i=1:N\n X[1,i] = μ + σ*randn()\n X[2,i] = bananicity*(X[1,i]^2 - σ^2) + randn()\n end\n return X\nend\n\n# log_pdf_banana(X) = log_pdf(X[1]) + log_pdf(X[2] - X[1]^2)\n# log_pdf_banana(X; a = 0.0, b = 1.0, c = 1.0) = log_pdf((X[1] -a)/b) + log_pdf(X[2] - c*X[1]^2)\n\n\"\"\"\n log_pdf_banana(X; μ = 0.0, σ = 2.0, bananicity = 0.2)\n\nCompute the logarithm of the porbability density function (pdf) of the Banana distribution at `X`.\nSee documentation of sample_banana for details on the Banana distribution.\n\"\"\"\nlog_pdf_banana(X::AbstractVector; μ = 0.0, σ = 2.0, bananicity = 0.2) = log_pdf((X[1]-μ)/σ) + log_pdf(X[2] - bananicity*(X[1]^2 - σ^2))\n", "meta": {"hexsha": "06f074d8a1df565df8903f8343e67bb173aaff91", "size": 990, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/tools/banana.jl", "max_stars_repo_name": "mleprovost/TransportBasedInference.jl", "max_stars_repo_head_hexsha": "bdcedf72e9ea23c24678fe6af7a00202c5f9d5d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-23T03:16:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T03:16:56.000Z", "max_issues_repo_path": "src/tools/banana.jl", "max_issues_repo_name": "mleprovost/TransportBasedInference.jl", "max_issues_repo_head_hexsha": "bdcedf72e9ea23c24678fe6af7a00202c5f9d5d7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tools/banana.jl", "max_forks_repo_name": "mleprovost/TransportBasedInference.jl", "max_forks_repo_head_hexsha": "bdcedf72e9ea23c24678fe6af7a00202c5f9d5d7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0, "max_line_length": 135, "alphanum_fraction": 0.5929292929, "num_tokens": 424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403979493139, "lm_q2_score": 0.8791467564270271, "lm_q1q2_score": 0.8171145111493846}} {"text": "using LinearAlgebra\n\n# Base transition matrix\nT = [-1 1 0 0; 0 -1 1 0; 0 0 -1 1; 1 0 0 -1]\n\nΛ, V = eigen(T)\nΛ, W = eigen(T')\n\n# Right eigenvectors\nV⁴ = round.(V[:, 1] ./ V[1, 1])\nV³ = round.(V[:, 2] ./ V[1, 2])\nV² = round.(V[:, 3] ./ V[1, 3])\nV¹ = round.(V[:, 4] ./ V[1, 4])\n\n# Left eigenvectors\nW⁴ = round.(W[:, 1] ./ W[1, 1])\nW³ = round.(W[:, 2] ./ W[1, 2])\nW² = round.(W[:, 3] ./ W[1, 3])\nW¹ = round.(W[:, 4] ./ W[1, 4])\n\n# Flip Order (take into account later)\nW[:, 1] .= W¹\nW[:, 2] .= W²\nW[:, 3] .= W³\nW[:, 4] .= W⁴\ninv(W) * 4\n\n# Quick Check (right eigenvector)\nT * V - V * Diagonal(Λ)\nmaximum(abs.(T * V - V * Diagonal(Λ))) ≤ eps(10.0)\n# Quick Check (left eigenvector)\nT' * W - W * Diagonal(reverse(Λ)) # since we flipped the order so that index 1 corresponds to the lowest eigenvalue\nW' * T - Diagonal(reverse(Λ))' * W' # same thing, recall that ' means adjoint, thus takes the conjucate\nmaximum(abs.(T' * W - W * Diagonal(reverse(Λ)))) ≤ eps(10.0)\n\n# The following transformation is what is used\nS = real.(V)\nS[:, 1] .= real.(W¹)\nS[:, 2] .= real.(0.5 * (W² + W³))\nS[:, 3] .= real.(0.5 * im * (W² - W³))\nS[:, 4] .= real.(W⁴)\n\ndisplay(S)\ndisplay(inv(S))\ndisplay(inv(S) * T * S)\n\n# The following partitions the magnitude of\n# the anti-symmetric component and the symmetric component\n# of the transition matrix\nsT = (T + T') / 2\naT = (T - T') / 2\nλ = 1.0\nω = 1.0\ninv(S) * (λ * sT + ω * aT) * S\n\n## check kronecker products corresponding to random phase\nkroneckered_phase = kron(sT, I + 0 * sT) + kron(I + 0 * sT, sT)\nΛ, V = eigen(kroneckered_phase)\n\n## check out higher dimensional one\nidmat = I + 0 * sT # the identity matrix\nkroneckered_phase = kron(sT, idmat, idmat) + kron(idmat, sT, idmat) + kron(idmat, idmat, sT)\nΛ, V = eigen(kroneckered_phase)\n", "meta": {"hexsha": "9546900af7a685e80823607226cf4dced6fadc88", "size": 1759, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/four_state_transition_matrix.jl", "max_stars_repo_name": "sandreza/StatisticalNonlocality", "max_stars_repo_head_hexsha": "0e58dcd6a1a8a8c2594ffe428760520556211aa9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/four_state_transition_matrix.jl", "max_issues_repo_name": "sandreza/StatisticalNonlocality", "max_issues_repo_head_hexsha": "0e58dcd6a1a8a8c2594ffe428760520556211aa9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-07T18:48:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-07T18:48:00.000Z", "max_forks_repo_path": "examples/four_state_transition_matrix.jl", "max_forks_repo_name": "sandreza/StatisticalNonlocality", "max_forks_repo_head_hexsha": "0e58dcd6a1a8a8c2594ffe428760520556211aa9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.484375, "max_line_length": 118, "alphanum_fraction": 0.5884025014, "num_tokens": 721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741254760638, "lm_q2_score": 0.8577681031721325, "lm_q1q2_score": 0.8170877007404561}} {"text": "\n\"\"\"\n Chebyshev\n\nA functor struct representing the basis of Chebyshev polynomials.\n\"\"\"\nstruct Chebyshev end\n\n\"\"\"\n chebyshev_basis(k,x)\n\nEvaluate the `k`-th Chebyshev basis function at `x`.\n\"\"\"\nfunction chebyshev_basis(k,x)\n if abs(x) < 1\n cos(k * acos(x))\n elseif x >= 1\n cosh(k * acosh(x))\n else\n (-1)^k * cosh(k * acosh(-x))\n end\nend\n\nchebyshev_basis(k,x::AbstractVector) = chebyshev_basis.(k,x)\n\n(::Chebyshev)(k,x) = chebyshev_basis(k,x)\n\n", "meta": {"hexsha": "76a06f16baa906bdb00cacb0f6eb4af4dac65933", "size": 481, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/parametric_functions/chebyshev_basis.jl", "max_stars_repo_name": "csimal/SpectralLearning.jl", "max_stars_repo_head_hexsha": "4999657700a0d84dfff470a52ddb3e3b37a44aae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/parametric_functions/chebyshev_basis.jl", "max_issues_repo_name": "csimal/SpectralLearning.jl", "max_issues_repo_head_hexsha": "4999657700a0d84dfff470a52ddb3e3b37a44aae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/parametric_functions/chebyshev_basis.jl", "max_forks_repo_name": "csimal/SpectralLearning.jl", "max_forks_repo_head_hexsha": "4999657700a0d84dfff470a52ddb3e3b37a44aae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.1785714286, "max_line_length": 65, "alphanum_fraction": 0.6195426195, "num_tokens": 161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9525741281688025, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.8170876995866967}} {"text": "module SonarEquations\n\nusing SpecialFunctions\n\n\"\"\"\n\tSE = signal_excess_passive(SL, TL, NL, DI, DT)\n\nCalculates the signal excess in a passive sonar scenario for source level `SL` (dB), transmission loss `TL` (dB), noise level `NL` (dB), directivity index `DI` (dB) and detection threshold `DT` (dB).\n\"\"\"\nfunction signal_excess_passive(SL, TL, NL, DI, DT)\n\tSE = SL - TL - NL + DI - DT\nend\n\n\"\"\"\n\tdetection_index_gaussian(p_dtc, p_fal)\n\nCalculates the detection index for a non-fluctuating signal in a Gaussian-distributed noise environment for a probability of detection `p_dtc` and probability of false alarm `p_fal`.\n\"\"\"\nfunction detection_index_gaussian(p_dtc, p_fal)\n\tif p_fal ≥ p_dtc\n\t\td = 0\n\telse\n\t\t# d = 2(erfcinv(2p_dtc) - erfcinv(2p_fal))^2\n\t\td = 2(erfinv(1 - 2p_dtc) - erfinv(1 - 2p_fal))^2\n\tend\n\treturn d\nend\n# function detection_index_gaussian(p_dtc, p_fal)\n# \td = 2(erfcinv(2p_dtc) - erfcinv(2p_fal))^2\n# \t# d = 2(erfinv(1 - 2p_dtc) - erfinv(1 - 2p_fal))^2\n# end\n\n# function detection_index_gaussian(SL, TL, NL, B, t)\n# \td = B*t*((SL - TL)/(B*NL))^2\n# end\nfunction detection_index_gaussian(SL, TL, NL, B, t)\n\tif TL ≥ SL\n\t\td = 0\n\telse\n\t\td = B*t*((SL - TL)/NL)^2\n\tend\n\treturn d\nend\n\n\"\"\"\n\n\"\"\"\nfunction detection_index_exponential(p_dtc, p_fal)\n\td = (log(p_fal)/log(p_dtc) - 1)^2\nend\n\n\"\"\"\n\n\"\"\"\nfunction detection_index_rayleigh(p_dtc, p_fal)\n\td = π/(4 - π)*(sqrt(log(p_fal)/log(p_dtc)) - 1)^2\nend\n\n\"\"\"\n\n\"\"\"\nfunction detection_threshold(d, B, t)\n\tDT = 5log10(d*B/t)\nend\n\n\"\"\"\n\tprobability_of_detection_gaussian(d, p_fal)\n\nCalculates the probability of detection for a non-fluctuating signal in a Gaussian-distributed noise environment for detection index `d` and probability of false alarm `p_fal`.\n\"\"\"\nfunction probability_of_detection_gaussian(d, p_fal)\n\tp_dtc = erfc(erfcinv(2p_fal) - sqrt(d/2))/2\nend\n\n\"\"\"\n\t\n\"\"\"\nfunction probability_of_detection_exponential(d, p_fal)\n\tp_dtc = exp(log(p_fal)/(sqrt(d) + 1))\nend\n\n\"\"\"\n\n\"\"\"\nfunction probability_of_detection_rayleigh(d, p_fal)\n\tp_dtc = exp(log(p_fal)/(sqrt((4 - π)/π*d) + 1)^2)\nend\n\nend", "meta": {"hexsha": "9a80576ba3611fa3066d046e2d78d5504f0b829a", "size": 2042, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SonarEquations.jl", "max_stars_repo_name": "kapple19/OceanAcousticsModelling", "max_stars_repo_head_hexsha": "9fdc1cefa51894661543428022d4fe45cd952e4f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-21T11:08:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-21T11:08:53.000Z", "max_issues_repo_path": "src/SonarEquations.jl", "max_issues_repo_name": "kapple19/OceanAcousticsModelling", "max_issues_repo_head_hexsha": "9fdc1cefa51894661543428022d4fe45cd952e4f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SonarEquations.jl", "max_forks_repo_name": "kapple19/OceanAcousticsModelling", "max_forks_repo_head_hexsha": "9fdc1cefa51894661543428022d4fe45cd952e4f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-05T02:54:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-05T02:54:21.000Z", "avg_line_length": 22.9438202247, "max_line_length": 199, "alphanum_fraction": 0.6958863859, "num_tokens": 699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109784205502, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.8170338713604874}} {"text": "# This file includes utilities\n\nexport Q, dbtoval, valtodb, energy \n\n\"\"\"\n $SIGNATURES\n\nComputes the energy of the discrete time signal `s` sampled with `ts` (defaults to 1) seconds. \n\"\"\"\nenergy(s::AbstractVector, ts=1.) = sum(abs.(s).^2) * ts\n\n\"\"\"\n $SIGNATURES\n\nConverts `γ` from `dB` value to its real value.\n\n# Example \n```julia \njulia> dbtoval(2) # γ = 2 dB\n1.5848931924611136\n```\n\"\"\"\ndbtoval(γ) = 10^(γ / 10)\n\n\n\"\"\"\n $SIGNATURES\n\nConverts `val` tı dB scale. \n\"\"\"\nvaltodb(val) = 10 * log10(val)\n\n\"\"\" \n $SIGNATURES \n\nQ-function defined as. \n```math \n Q(x) = \\\\int_{x}^{\\\\infty} exp(-\\\\dfrac{x^2}{2}) dx\n```\n\"\"\"\nQ(x) = 1 / 2 * erfc(x / sqrt(2))\n\n\n", "meta": {"hexsha": "d13aaab5ebb865b9eb57b44b344555c8092bba64", "size": 663, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "zekeriyasari/DigitalCommunications.jl", "max_stars_repo_head_hexsha": "7ac2e6afe42aa996d94d211c1ea590ac3c0beb15", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-03T20:02:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-13T06:43:38.000Z", "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "zekeriyasari/DigitalCommunications.jl", "max_issues_repo_head_hexsha": "7ac2e6afe42aa996d94d211c1ea590ac3c0beb15", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2020-11-26T21:56:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-03T19:54:59.000Z", "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "zekeriyasari/DigitalCommunications.jl", "max_forks_repo_head_hexsha": "7ac2e6afe42aa996d94d211c1ea590ac3c0beb15", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-20T12:53:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T12:53:43.000Z", "avg_line_length": 15.0681818182, "max_line_length": 95, "alphanum_fraction": 0.5912518854, "num_tokens": 245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418262465169, "lm_q2_score": 0.8840392802184581, "lm_q1q2_score": 0.8169776748947422}} {"text": "using CompScienceMeshes\nusing LinearAlgebra\n\no = point(3,4,2)\na = point(4,2,4)\nb = point(2,8,2)\nc = point(0,4,6)\n\ntet = simplex(o,a,b,c)\nqw = quadpoints(tet,4)\nprint(volume(tet),\"==\",abs(dot(a-o,cross(b-o,c-o)))/6,\"==\",abs(sum(w for (p,w) in qw)),\"\\n\")\n\no,x,y,z = CompScienceMeshes.euclidianbasis(3)\n\ntet = simplex(o,x,2y,3z)\nvolume(tet)\n\nqw = quadpoints(tet,4)\nlength(qw)\n\nprint(abs(sum(w for (p,w) in qw)-volume(tet)) < 0.001,\"\\n\")\nprint(sum(w*sin(p[1])*p[2]^2*p[3]^3 for (p,w) in qw))\n#https://www.wolframalpha.com/input/?i=int_0^1+int_0^(2-2x)+int_0^(3-3x-1.5y)+sin(x)y^2z^3+dz+dy+dx\n", "meta": {"hexsha": "521967a704ce648fdaa10c10b0921797cd6a2c5c", "size": 588, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ex_quad.jl", "max_stars_repo_name": "sbadrian/CompScienceMeshes.jl", "max_stars_repo_head_hexsha": "27c6737d2a39bca7e97aa204f4595ef007defe9e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2018-05-30T20:31:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T13:10:58.000Z", "max_issues_repo_path": "examples/ex_quad.jl", "max_issues_repo_name": "sbadrian/CompScienceMeshes.jl", "max_issues_repo_head_hexsha": "27c6737d2a39bca7e97aa204f4595ef007defe9e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2017-04-11T14:45:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T14:06:03.000Z", "max_forks_repo_path": "examples/ex_quad.jl", "max_forks_repo_name": "sbadrian/CompScienceMeshes.jl", "max_forks_repo_head_hexsha": "27c6737d2a39bca7e97aa204f4595ef007defe9e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2017-03-29T17:00:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-13T11:45:35.000Z", "avg_line_length": 24.5, "max_line_length": 99, "alphanum_fraction": 0.6326530612, "num_tokens": 256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.972830769252026, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.8169190378357901}} {"text": "__precompile__(true)\nmodule FourierSeries\n\n using FFTW\n export\n fourierSeriesStepReal,\n fourierSeriesSampledReal,\n fourierSeriesSynthesisReal,\n repeatPeriodically\n\n @doc raw\"\"\"\n # Function call\n\n `fourierSeriesStepReal(t, u, T, hMax)`\n\n # Description\n\n Calculates the real Fourier coefficients of a step function `u(t)` based on\n the data pairs `t` and `u` according to the following variables:\n\n ```math\n \\mathtt{a[k]} =\n \\frac{2}{\\mathtt{T}} \\int_{\\mathtt{t[1]}}^{\\mathtt{t[1]+T}}\n \\mathtt{u(t)} \\cos(k\\omega \\mathtt{t}) \\operatorname{d}\\mathtt{t} \\\\\n ```\n\n ```math\n \\mathtt{b[k]} =\n \\frac{2}{\\mathtt{T}} \\int_{\\mathtt{t[1]}}^{\\mathtt{t[1]+T}}\n \\mathtt{u(t)} \\sin(k\\omega \\mathtt{t}) \\operatorname{d}\\mathtt{t}\n ```\n\n # Function arguments\n\n `t` Time vector instances where a step occurs\n\n `u` Data vector of which Fourier coefficients shall be determined of, i.e.,\n `u[k]` is the data value from the right at `t[k]`\n\n `T` Time period of `u`\n\n `hMax` Maximum harmonic number to be determined\n\n # Return values\n\n `h` Vector of harmonic numbers start at, i.e., `h[1] = 0` (dc value of `u`),\n `h[hMax+1] = hMax`\n\n `f` Frequency vector associated with harmonic numbers, i.e. `f = h / T`\n\n `a` Cosine coefficients of Fourier series, where `a[1]` = dc value of `u`\n\n `b` Sine coefficients of Fourier series, where `b[1] = 0`\n\n # Examples\n\n Copy and paste code:\n\n ```julia\n # Fourier approximation of square wave form\n ts = [0; 1] # Sampled time data\n us = [-1; 1] # Step function of square wave\n T = 2 # Period\n hMax = 7 # Maximum harmonic number\n (h, f, a, b) = fourierSeriesStepReal(ts, us, 2, hMax)\n (t, u)=fourierSeriesSynthesisReal(f, a, b)\n using PyPlot\n # Extend (t, u) by one element to right periodically\n (tx, ux) = repeatPeriodically(ts, us, right=1)\n step(tx, ux, where=\"post\") # Square wave function\n plot(t, u) # Fourier approximation up to hMax = 7\n ```\n \"\"\"\n function fourierSeriesStepReal(t,u,T,hMax)\n # Check if t and have equal lengths\n if length(t) != length(u)\n error(\"module FourierSeries: function fourierSeriesStepReal:\\n\n Vectors t and u have different lengths\")\n end\n # Check if vector u is NOT of type Complex\n if u[1] isa Complex\n error(\"module FourierSeries: function fourierSeriesStepReal:\\n\n The analyzed functions `u` must not be of Type ::Complex\")\n end\n # Determine length of function u\n N = length(u)\n # Initialization of real result vectors\n a = zeros(hMax+1)\n b = zeros(hMax+1)\n # Cycle through loop to determine coefficients\n i = collect(1:N)\n # Time vector, extended by period T\n τ = cat(t, [T+t[1]], dims = 1)\n # DC value\n a[1] = sum(u .* (τ[i.+1] - τ[i])) / T\n b[1] = 0\n global a, b, τ, i, T\n for k in collect(1:hMax)\n a[k+1] = sum(u.*(+sin.(k * τ[i.+1] * 2 * pi / T)\n .-sin.(k * τ[i] * 2 * pi / T))) / (k * pi)\n b[k+1] = sum(u.*(-cos.(k * τ[i.+1] * 2 * pi / T)\n .+cos.(k * τ[i] * 2 * pi / T))) / (k * pi)\n end\n # Number of harmonics\n h = collect(0:hMax)\n # Frequencies\n f = h / T\n return (h,f,a,b)\n end\n\n \"\"\"\n # Function call\n\n `fourierSeriesSampledReal(t,u,T,hMax)`\n\n # Description\n\n Calculates the real Fourier coefficients of a sampled function `u(t)` based\n on the data pairs `t` and `u`\n\n # Function arguments\n\n `t` Vector of sample times\n\n `u` Data vector of which Fourier coefficients shall be determined of, i.e.,\n `u[k]` is the sampled data value associated with `t[k]`\n\n `T` Time period of `u`\n\n `hMax` Maximum harmonic number to be determined\n\n # Return values\n\n `h` Vector of harmonic numbers start at, i.e., `h[1] = 0` (dc value of `u`),\n `h[hMax+1] = hMax`\n\n `f` Frequency vector associated with harmonic numbers, i.e. `f = h / T`\n\n `a` Cosine coefficients of Fourier series, where `a[1]` = dc value of `u`\n\n `b` Sine coefficients of Fourier series, where `b[1] = 0`\n\n # Examples\n\n Copy and paste code:\n\n ```julia\n # Fourier approximation of square wave form\n ts = [ 0; 1; 2; 3; 4; 5; 6; 7; 8; 9] # Sampled time data\n us = [-1;-1;-1;-1;-1; 1; 1; 1; 1; 1] # Step function of square wave\n T = 10 # Period\n hMax = 7 # Maximum harmonic number\n (h, f, a, b) = fourierSeriesSampledReal(ts, us, hMax)\n (t, u) = fourierSeriesSynthesisReal(f, a, b)\n using PyPlot\n # Extend (t, u) by one element to right periodically\n (tx, ux) = repeatPeriodically(ts, us, right=1)\n plot(tx, ux, marker=\"o\") # Square wave function\n plot(t, u) # Fourier approximation up to hMax = 7\n ```\n \"\"\"\n function fourierSeriesSampledReal(t, u, hMax::Int64=typemax(Int64))\n # Check if vector u is NOT of type Complex\n if u[1] isa Complex\n error(\"module FourierSeries: function fourierSeriesSampledReal:\\n\n The analyzed functions `u` must not be of Type ::Complex\")\n end\n # Determine length of function u\n N = length(u)\n # Determine period of function u\n T = t[end] - t[1] + t[2] - t[1]\n # Apply fast Fourier transform\n c = 2 * fft(u) / N\n # Correct DC value by factor 1/2\n c[1] = c[1] / 2;\n if mod(N,2) == 1\n # Number of sampled data, N, is odd\n hMaxMax = div(N-1, 2)\n else\n # Number of sampled data, N, is even\n hMaxMa x =div(N, 2)\n end\n # Number of harmonics\n h = collect(0:hMaxMax)\n # Frequencies\n f = h / T\n # Real and imaginary coefficients\n a = +real(c[1:min(hMax,hMaxMax) + 1])\n b = -imag(c[1:min(hMax,hMaxMax) + 1])\n # Return vectors\n return (h, f, a, b)\n end\n\n function fourierSeriesSynthesisReal(f, a, b;hMax=length(a)-1, N=1000, t0=0)\n # Check if vectors f, a and b have equal lengths\n if length(f) != length(a)\n error(\"module Fourier: function fourierSeriesSynthesisReal:\\n\n Vectors `f` and `a` have different lengths\")\n end\n if length(a) != length(b)\n error(\"module Fourier: function fourierSeriesSynthesisReal:\\n\n Vectors `a` and `b` have different lengths\")\n end\n # Determine Period of synthesized function\n T = 1 / f[2]\n # Initialization of synthesis function f\n u = fill(a[1],N)\n # time samples of synthesis function, considering start time t0\n t = collect(0:N-1) / N * T + fill(t0, N)\n # hMax may either be a scalar of vector\n if hMax isa Array\n # If hMax is an array, then synthesize only harmonic numbers\n # indicated by hMax\n kRange = hMax\n else\n # If hMax is a scalar, then treat hMax as the maximum harmonic\n # number, which may not exceed length(a)-1, as a[1] equals the dc\n # component (harmonic 0) and a[hMax-1] represents harmonic number\n # hMax\n kRange = collect(1:min(hMax, length(a)-1))\n end\n # Calculate superosition\n for k in kRange\n u = u + a[k+1] * cos.(k * t * 2 * pi / T)\n + b[k+1] * sin.(k * t * 2 * pi / T)\n end\n return (t, u)\n end\n\n function repeatPeriodically(t, u; left = 0, right = 1)\n # Check if vectors t and u have equal lengths\n if length(t) != length(u)\n error(\"module Fourier: function repeatPeriodically:\\n\n Vectors `t` and `u` have different lengths\")\n end\n # Determine length of arrays t and u\n N = length(t)\n # Determine period of time axis\n T = t[end] - t[1] + t[2] - t[1]\n # Determine how many times the vectors t and u shall be repeated\n outerRight = Int(floor((right-1)/N) + 1)\n outerLeft = Int(floor((left -1)/N) + 1)\n # Repeat vector t by full periods and consider period T\n tx = repeat(t, outer = outerRight+outerLeft + 1) +\n repeat(collect(-outerLeft: outerRight), inner = N) * T\n # Repeat vector u by full periods\n ux = repeat(u, outer = outerLeft + outerRight + 1)\n # Limit output vectors elements\n tx = tx[outerLeft * N - left + 1:(outerLeft * N) + N + right]\n ux = ux[outerLeft * N - left + 1:(outerLeft * N) + N + right]\n return (tx, ux)\n end\n\nend\n", "meta": {"hexsha": "a24faefb57085f94b3991334459ace01f92cf6cd", "size": 8715, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/FourierSeries.jl", "max_stars_repo_name": "christiankral/FourierSeries.jl", "max_stars_repo_head_hexsha": "ca0f1c71df666eaa0836b8c324eb4ee35e25c049", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-01-12T09:50:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-07T22:36:14.000Z", "max_issues_repo_path": "src/FourierSeries.jl", "max_issues_repo_name": "christiankral/FourierSeries.jl", "max_issues_repo_head_hexsha": "ca0f1c71df666eaa0836b8c324eb4ee35e25c049", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-29T23:08:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-29T23:08:53.000Z", "max_forks_repo_path": "src/FourierSeries.jl", "max_forks_repo_name": "christiankral/FourierSeries.jl", "max_forks_repo_head_hexsha": "ca0f1c71df666eaa0836b8c324eb4ee35e25c049", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-12T09:51:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-12T09:51:25.000Z", "avg_line_length": 34.1764705882, "max_line_length": 80, "alphanum_fraction": 0.5578886976, "num_tokens": 2588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342037088043, "lm_q2_score": 0.8539127455162773, "lm_q1q2_score": 0.8168821393437627}} {"text": "#==============================================================================\n Code for solving the Hamiltonian Jacboi Bellman for\n\t an basic model: a neoclassical growth model: ρV(k) = max_{c} U(c) + V'(k)[F(k)-δk - c]\n\t Where s(k) = F(k) - δk - c(k) and c(k) = U'^{-1}(V'(k))\n\n\tTranslated Julia code from Matlab code by Ben Moll:\n http://www.princeton.edu/~moll/HACTproject.htm\n\n Updated to Julia 1.0.0\n==============================================================================#\n\nusing Distributions, Plots, SparseArrays, LinearAlgebra\n\n\nσ= 2.0 #\nρ = 0.05 #the discount rate\nδ = 0.05 # the depreciation rate\nA = 1.0\nα= 0.3\n\n\nk_ss = (α*A/(ρ+δ))^(1/(1-α))\n\nH = 10000\nk_min = 0.001*k_ss\nk_max = 2.0*k_ss\n\nk = LinRange(k_min, k_max, H)\nk = convert(Array, k) # create grid for a values\ndk = (k_max-k_min)/(H-1)\n\nΔ = 1000\n\nmaxit = 10\nε = 10e-6\n\ndVf, dVb = [zeros(H,1) for i in 1:6]\n\n#initial guess for V\nv0 = (A.*k.^α).^(1-σ)/(1-σ)/ρ\nv= v0\n\ndist=[]\n\nfor n=1:maxit\n\tV=v\n\n # forward difference\n\tdVf[1:H-1] = (V[2:H]-V[1:H-1])/dk\n\tdVf[H] = (A.*k_max.^α - δ.*k_max)^(-σ)\n\n\t# backward difference\n\tdVb[2:H] = (V[2:H]-V[1:H-1])/dk\n\tdVb[1] = (A.*k_min.^α - δ.*k_min)^(-σ) # the boundary condition\n\n\tI_concave = dVb .> dVf\n\n # consumption and savings with forward difference\n cf = dVf.^(-1/σ)\n μ_f = A.*k.^α - δ.*k -cf\n\n # consumption and savings with backward difference\n cb = dVb.^(-1/σ)\n μ_b = A.*k.^α - δ.*k -cb\n\n\tc0 = A.*k.^α - δ.*k\n dV0 = c0.^(-σ)\n\n # Now to make a choice between forward and backward difference\n If = μ_f .> 0\n Ib = μ_b .< 0\n I0 = (1.0.-If-Ib)\n\n global dV_Upwind= dVf.*If + dVb.*Ib + dV0.*I0\n\n global c = dV_Upwind.^(-1/σ)\n u = c.^(1-σ)/(1-σ)\n\n # create the transition matrix\n X = -min.(μ_b,0)/dk\n Y = -max.(μ_f,0)/dk + min.(μ_b,0)/dk\n Z = max.(μ_f,0)/dk\n\n\n AA = sparse(Diagonal((Y[:]))) + [zeros(1,H); sparse(Diagonal((X[2:H]))) zeros(H-1,1)] + [zeros(H-1,1) sparse(Diagonal((Z[1:H-1]))); zeros(1,H)]\n B = (ρ + 1/Δ)*sparse(I,H,H) - AA\n b = u + V./Δ\n\n V = B\\b\n V_change = V-v\n global v= V\n\n\tpush!(dist,findmax(abs.(V_change))[1])\n\tif dist[n] .< ε\n\t\tprintln(\"Value Function Converged Iteration=\")\n\t\tprintln(n)\n\t\tbreak\n\tend\nend\n\nplot(dist, grid=false,\n\t\txlabel=\"Iteration\", ylabel=\"||V^{n+1} - V^n||\",\n\t\tylims=(-0.001,0.030),\n\t\tlegend=false, title=\"\")\npng(\"Convergence\")\n\n\nv_err = c.^(1-σ)/(1-σ) + dV_Upwind.*(A.*k.^α - δ.*k -c) - ρ.*v\n\nplot(k, v_err, grid=false,\n\t\txlabel=\"k\", ylabel=\"Error in the HJB equation\",\n\t\txlims=(k_min,k_max),\n\t\tlegend=false, title=\"\")\npng(\"HJB_error\")\n\n\nplot(k, v, grid=false,\n\t\txlabel=\"k\", ylabel=\"V(k)\",\n\t\txlims=(k_min,k_max),\n\t\tlegend=false, title=\"\")\npng(\"Value_function_vs_k\")\n\nplot(k, c, grid=false,\n\t\txlabel=\"k\", ylabel=\"c(k)\",\n\t\txlims=(k_min,k_max),\n\t\tlegend=false, title=\"\")\npng(\"c(k)_vs_k\")\n\n# approximation at the borrowing constraint\nk_dot = (A.*k.^α - δ.*k -c)\n\nplot(k, k_dot, grid=false,\n\t\txlabel=\"k\", ylabel=\"s(k)\",\n\t\txlims=(k_min,k_max), title=\"\", label=\"s(k)\", legend=false)\nplot!(k, zeros(H,1), label=\"\", line=:dash)\npng(\"stateconstraint\")\n", "meta": {"hexsha": "f079a40009a805cd184f9d10cbe28d098f725586", "size": 3093, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Moll_Code/Section15-General_Continuous_Time_Models/HJB_NGM_implicit/HJB_NGM_implicit.jl", "max_stars_repo_name": "chandlerlester/Radio_Free_Julia", "max_stars_repo_head_hexsha": "16a2e52741e20b5d74cdc01dd2fd0722614a6377", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-02-26T11:52:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-30T12:41:38.000Z", "max_issues_repo_path": "Moll_Code/Section15-General_Continuous_Time_Models/HJB_NGM_implicit/HJB_NGM_implicit.jl", "max_issues_repo_name": "chandlerlester/Radio_Free_Julia", "max_issues_repo_head_hexsha": "16a2e52741e20b5d74cdc01dd2fd0722614a6377", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Moll_Code/Section15-General_Continuous_Time_Models/HJB_NGM_implicit/HJB_NGM_implicit.jl", "max_forks_repo_name": "chandlerlester/Radio_Free_Julia", "max_forks_repo_head_hexsha": "16a2e52741e20b5d74cdc01dd2fd0722614a6377", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-05-11T08:09:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-30T18:54:12.000Z", "avg_line_length": 22.5766423358, "max_line_length": 147, "alphanum_fraction": 0.5502748141, "num_tokens": 1189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545377452443, "lm_q2_score": 0.861538211208597, "lm_q1q2_score": 0.8168713643983518}} {"text": "function thomas(a::Vector{Float64}, b::Vector{Float64}, c::Vector{Float64},\n d::Vector{Float64}, n::Int64)\n\n x = copy(d)\n c_prime = copy(c)\n\n # Setting initial elements\n c_prime[1] /= b[1]\n x[1] /= b[1]\n\n for i = 2:n\n # Scale factor is for c_prime and x\n scale = 1.0 / (b[i] - c_prime[i-1]*a[i])\n c_prime[i] *= scale\n x[i] = (x[i] - a[i] * x[i-1]) * scale\n end\n\n # Back-substitution\n for i = n-1:-1:1\n x[i] -= (c_prime[i] * x[i+1])\n end\n\n return x\n\nend\n\nfunction main()\n a = [0.0, 2.0, 3.0]\n b = [1.0, 3.0, 6.0]\n c = [4.0, 5.0, 0.0]\n d = [7.0, 5.0, 3.0]\n\n println(\n \"\"\"The system\n $(join((b[1], c[1], \"\", \"|\", d[1]), \"\\t\"))\n $(join((a[2], b[2], c[2], \"|\", d[2]), \"\\t\"))\n $(join((\"\", a[3], b[3], \"|\", d[3]), \"\\t\"))\n Has the solution:\"\"\"\n )\n\n soln = thomas(a, b, c, d, 3)\n\n println(soln)\nend\n\nmain()\n", "meta": {"hexsha": "a43be8eb240e2f851fab4c908c9e821516aeb676", "size": 944, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "contents/thomas_algorithm/code/julia/thomas.jl", "max_stars_repo_name": "Iinguistics/algorithm-archivists.github.io", "max_stars_repo_head_hexsha": "3759b22a9c21b8b7a9bf075ca880e02ec524abc5", "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/thomas_algorithm/code/julia/thomas.jl", "max_issues_repo_name": "Aarif1430/algorithm-archive", "max_issues_repo_head_hexsha": "1bb82d96c5edc03922918dda0c818bbbcd08417f", "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/thomas_algorithm/code/julia/thomas.jl", "max_forks_repo_name": "Aarif1430/algorithm-archive", "max_forks_repo_head_hexsha": "1bb82d96c5edc03922918dda0c818bbbcd08417f", "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": 20.085106383, "max_line_length": 75, "alphanum_fraction": 0.4247881356, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545304202039, "lm_q2_score": 0.8615382129861583, "lm_q1q2_score": 0.8168713597729526}} {"text": "function translation(x::T,y::T,z::T)::Array{T,2} where {T<:Real}\n return [1 0 0 x; 0 1 0 y; 0 0 1 z; 0 0 0 1]\nend\n\nfunction translation(x::Real,y::Real,z::Real)\n return translation(promote(x,y,z)...)\nend\n\nfunction scaling(x::T,y::T,z::T)::Array{T,2} where {T<:Real}\n return [x 0 0 0; 0 y 0 0; 0 0 z 0; 0 0 0 1]\nend\n\nfunction scaling(x::Real,y::Real,z::Real)\n return scaling(promote(x,y,z)...)\nend\n\nfunction rotation_x(angle::T)::Array{T,2} where {T<:Real}\n return [1 0 0 0; 0 cos(angle) -sin(angle) 0; 0 sin(angle) cos(angle) 0; 0 0 0 1]\nend\n\nfunction rotation_y(angle::T)::Array{T,2} where {T<:Real}\n return [cos(angle) 0 sin(angle) 0; 0 1 0 0; -sin(angle) 0 cos(angle) 0; 0 0 0 1]\nend\n\nfunction rotation_z(angle::T)::Array{T,2} where {T<:Real}\n return [cos(angle) -sin(angle) 0 0; sin(angle) cos(angle) 0 0; 0 0 1 0; 0 0 0 1]\nend\n\nfunction shearing(x_y::T,x_z::T,y_x::T,y_z::T,z_x::T,z_y::T)::Array{T,2} where {T<:Real}\n return [1 x_y x_z 0; y_x 1 y_z 0; z_x z_y 1 0; 0 0 0 1]\nend", "meta": {"hexsha": "518f7d8da23be255610d270156da65ac1d1ebcab", "size": 1006, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/transformations.jl", "max_stars_repo_name": "etenedrac/RayTracer.jl", "max_stars_repo_head_hexsha": "a0eb8508105a74becfb09289999371ac0bffd1bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/transformations.jl", "max_issues_repo_name": "etenedrac/RayTracer.jl", "max_issues_repo_head_hexsha": "a0eb8508105a74becfb09289999371ac0bffd1bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/transformations.jl", "max_forks_repo_name": "etenedrac/RayTracer.jl", "max_forks_repo_head_hexsha": "a0eb8508105a74becfb09289999371ac0bffd1bd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4516129032, "max_line_length": 88, "alphanum_fraction": 0.6222664016, "num_tokens": 444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9777138131620183, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.8168637948954919}} {"text": "\"\"\"Julia program to print the n'th term in the Golomb sequence \nGolomb sequence is a non-decreasing integer sequence where n'th \nterm is equal to the number of times n appears in the sequence\"\"\"\n\nfunction golomb_sequence(n)\n dp = zeros(Int, n + 1)\n dp[1] = 1\n\n for i in 2:n\n dp[i] = 1 + dp[i - dp[dp[i - 1]]]\n end\n return dp[n]\nend\n\nprint(\"Enter the value of n?, where you need the n'th number in the golomb sequence. \")\nn = readline()\nn = parse(Int, n)\nif (n <= 0)\n println(\"The given value of n is invalid.\")\n exit()\nend\nres = golomb_sequence(n)\nprintln(\"The $n'th term in the golomb sequence is $res.\")\n\n\"\"\"\nTime Complexity: O(n), where 'n' is the given number\nSpace Complexity: O(n)\n\nSAMPLE INPUT AND OUTPUT\n\nSAMPLE 1\nEnter the value of n?, where you need the n'th number in the golomb sequence. 5\nThe 5'th term in the golomb sequence is 3.\n\nSAMPLE 2\nEnter the value of n?, where you need the n'th number in the golomb sequence. 867\nThe 867'th term in the golomb sequence is 79.\n\n\"\"\"\n", "meta": {"hexsha": "089b6a620660b8f9430d9c280840c8b2e3731249", "size": 1017, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/dp/golomb_sequence.jl", "max_stars_repo_name": "zhcet19/NeoAlgo-1", "max_stars_repo_head_hexsha": "c534a23307109280bda0e4867d6e8e490002a4ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 897, "max_stars_repo_stars_event_min_datetime": "2020-06-25T00:12:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:49:31.000Z", "max_issues_repo_path": "Julia/dp/golomb_sequence.jl", "max_issues_repo_name": "zhcet19/NeoAlgo-1", "max_issues_repo_head_hexsha": "c534a23307109280bda0e4867d6e8e490002a4ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5707, "max_issues_repo_issues_event_min_datetime": "2020-06-24T17:53:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-22T05:03:15.000Z", "max_forks_repo_path": "Julia/dp/golomb_sequence.jl", "max_forks_repo_name": "zhcet19/NeoAlgo-1", "max_forks_repo_head_hexsha": "c534a23307109280bda0e4867d6e8e490002a4ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1817, "max_forks_repo_forks_event_min_datetime": "2020-06-25T03:51:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:14:07.000Z", "avg_line_length": 25.425, "max_line_length": 87, "alphanum_fraction": 0.6794493609, "num_tokens": 305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273633016692236, "lm_q2_score": 0.8807970732843033, "lm_q1q2_score": 0.8168188819815206}} {"text": "using LinearAlgebra\nusing Plots\n\nfunction secant_method(f′, x0, x1, ϵ)\n g0 = f′(x0)\n Δ = Inf\n while abs(Δ) > ϵ\n g1 = f′(x1)\n Δ = (x1 - x0)/(g1 - g0)*g1\n x0, x1, g0 = x1, x1 - Δ, g1\n end\n return x1\nend\n\nf = x->sin(10x)+cos(3x)\ndf(x) = 10*cos(10*x)-3*sin(3*x)\n\n#dois pontos iniciais\nx0 = 3.4\nx1 = 3.8\n\n#convergencia\nconvergence = 1e-8 \n\nxs = secant_method(df,x0,x1,convergence)\nxs,f(xs),df(xs)\n\nplot(f,0.,8.,lw=2,draw_arrow=\"true\")\n#scatter!([a,c],[f(a),f(c)])\nscatter!([x0,x1],[f(x0),f(x1)])\nscatter!([xs],[f(xs)])", "meta": {"hexsha": "2686bf0a3ab46b361596801ded24458c6f5b9f09", "size": 555, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Secant_Method.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": "Secant_Method.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": "Secant_Method.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.9032258065, "max_line_length": 40, "alphanum_fraction": 0.5513513514, "num_tokens": 256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992969868543, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.8168054745931838}} {"text": "\"\"\"`semimajoraxis(x, y, z, u, v, w, m1, m2)`\n\nCalculates semimajor axis for the two\nbody problem defined by the relative position `(x,y,z)` and velocity `(u,v,w)` vectors between two bodies\nwith masses `m1` and `m2`.\"\"\"\nfunction semimajoraxis(x, y, z, u, v, w, m1, m2)\n r = sqrt(x^2+y^2+z^2)\n vsq = u^2+v^2+w^2\n M = m1+m2\n return 1/( (2/r)-(vsq/M) )\nend\n\n\"\"\"`eccentricity(x, y, z, u, v, w, m1, m2)`\n\nCalculates eccentricity for the two\nbody problem defined by the relative position `(x,y,z)` and velocity `(u,v,w)` vectors between two bodies\nwith masses `m1` and `m2`.\"\"\"\nfunction eccentricity(x, y, z, u, v, w, m1, m2)\n hsq = (y*w-z*v)^2 + (z*u-x*w)^2 + (x*v-y*u)^2\n a = semimajoraxis(x, y, z, u, v, w, m1, m2)\n M = m1+m2\n quotient = hsq/( M*a )\n return sqrt(1 - quotient)\nend\n\n\"\"\"`inclination(x, y, z, u, v, w)`\n\nCalculates inclination for the two\nbody problem defined by the relative position `(x,y,z)` and velocity `(u,v,w)` vectors between two bodies.\"\"\"\nfunction inclination(x, y, z, u, v, w)\n hz = x*v-y*u\n h = sqrt( (y*w-z*v)^2 + (z*u-x*w)^2 + (x*v-y*u)^2 )\n return acos(hz/h)\nend\n\n\"\"\"`aei(x, y, z, u, v, w, m1, m2)`\n\nReturns semimajor axis `a`, eccentricity `e` and inclination `I` for the two-body\nproblem defined by the relative position `(x,y,z)` and velocity `(u,v,w)`vectors\nbetween two bodies with masses `m1` and `m2`.\"\"\"\nfunction aei(x, y, z, u, v, w, m1, m2)\n r = sqrt(x^2+y^2+z^2)\n vsq = u^2+v^2+w^2\n M = m1+m2\n a = 1/( (2/r)-(vsq/M) )\n hsq = (y*w-z*v)^2 + (z*u-x*w)^2 + (x*v-y*u)^2\n h = sqrt(hsq)\n quotient = hsq/( M*a )\n e = sqrt(1 - quotient)\n hz = x*v-y*u\n inc = acos(hz/h)\n return a, e, inc\nend\n\n\"\"\"`ae(x, y, z, u, v, w)`\n\nReturns semimajor axis `a` and eccentricity `e` for the two-body problem defined\nby the relative position `(x,y,z)` and velocity `(u,v,w)` vectors between two\nbodies with masses `m1` and `m2`.\"\"\"\nfunction ae(x, y, z, u, v, w, m1, m2)\n r = sqrt(x^2+y^2+z^2)\n vsq = u^2+v^2+w^2\n M = m1+m2\n a = 1/( (2/r)-(vsq/M) )\n hsq = (y*w-z*v)^2 + (z*u-x*w)^2 + (x*v-y*u)^2\n quotient = hsq/( M*a )\n e = sqrt(1 - quotient)\n return a, e\nend\n\n\"\"\"`longascnode(x, y, z, u, v, w)`\n\nCalculates longitude of ascending node for the two\nbody problem defined by the relative position `(x,y,z)` and velocity `(u,v,w)` vectors between two bodies.\"\"\"\nfunction longascnode(\n x, y, z,\n u, v, w\n )\n\n #the longitude of ascending node is computed as\n #the angle between x-axis and the vector n = (-hy,hx,0)\n #where hx, hy, are resp., the x and y comps. of ang mom vector per unit mass, h\n\n res = atan( y*w-z*v, x*w-z*u)\n\n if constant_term(res) ≥ zero(constant_term(res))\n return res\n else\n return res+2pi\n end\n\nend\n\n\"\"\"`argperi(x, y, z, u, v, w, m1, m2)`\n\nCalculates the instantaneous (osculating) argument of pericentre for the two\nbody problem defined by the relative position `(x,y,z)` and velocity `(u,v,w)` vectors between two bodies\nwith masses `m1` and `m2`.\"\"\"\nfunction argperi(\n x, y, z,\n u, v, w,\n m1, m2\n )\n\n #n = (z-axis unit vector)×h = (-hy, hx, 0)\n n = [x*w-z*u, y*w-z*v, zero(x)]\n e = lrlvec(x,y,z,u,v,w,m1,m2) #cartesian comps. of Laplace-Runge-Lenz vector\n n = n/sqrt(n[1]^2+n[2]^2+n[3]^2)\n e = e/sqrt(e[1]^2+e[2]^2+e[3]^2)\n cosω = dot(n, e)\n\n if constant_term(e[3]) >= zero(constant_term(x))\n return acos(cosω)\n else\n return 2pi-acos(cosω)\n end\n\nend\n\n\"\"\"`longperi(x, y, z, u, v, w, m1, m2)`\n\nCalculates the instantaneous (osculating) longitude of pericentre for the two\nbody problem defined by the relative position `(x,y,z)` and velocity `(u,v,w)` vectors between two bodies\nwith masses `m1` and `m2`.\"\"\"\nfunction longperi(\n x, y, z,\n u, v, w,\n m1, m2\n )\n\n return argperi(x, y, z, u, v, w, m1, m2)+longascnode(x, y, z, u, v, w)\nend\n\n\"\"\"`trueanomaly(x, y, z, u, v, w, m1, m2)`\n\nCalculates the instantaneous (osculating) true anomaly for the two\nbody problem defined by the relative position `(x,y,z)` and velocity `(u,v,w)` vectors between two bodies\nwith masses `m1` and `m2`.\"\"\"\nfunction trueanomaly(\n x, y, z,\n u, v, w,\n m1, m2\n )\n\n R = sqrt(x^2+y^2+z^2)\n V2 = u^2+v^2+w^2\n V = sqrt(V2)\n\n a = 1.0/( (2.0/R)-(V2/(m1+m2)) )\n\n h2 = (y*w-z*v)^2 + (z*u-x*w)^2 + (x*v-y*u)^2\n h = sqrt(h2)\n\n quotient=h2/( (m1+m2)*a )\n\n e = sqrt(1.0 - quotient)\n\n Rdot = (x*u+y*v+z*w)/R\n\n sin_f = Rdot*a*(1.0-e^2)/( e*h )\n cos_f = (1.0/e)*( -1.0+a*(1.0-e^2)/R )\n\n res = atan(sin_f, cos_f)\n\n if res ≥ zero(res)\n return res\n else\n return res+2pi\n end\nend\n\n\"\"\"`ecanomaly(x, y, z, u, v, w, m1, m2)`\n\nCalculates the instantaneous (osculating) eccentric anomaly for the two\nbody problem defined by the relative position `(x,y,z)` and velocity `(u,v,w)` vectors between two bodies\nwith masses `m1` and `m2`.\"\"\"\nfunction ecanomaly(\n x, y, z,\n u, v, w,\n m1, m2\n )\n\n a = semimajoraxis(x, y, z, u, v, w, m1, m2)\n e = eccentricity(x, y, z, u, v, w, m1, m2)\n R = sqrt(x^2+y^2+z^2)\n Rdot = (x*u+y*v+z*w)/R\n mu = m1+m2\n\n cosE = (a-R)/(a*e)\n sinE = Rdot*R/( e*sqrt(mu*a) )\n\n res = atan(sinE, cosE)\n\n return res\n\nend\n\n\"\"\"`meananomaly(x, y, z, u, v, w, m1, m2)`\n\nCalculates the instantaneous (osculating) mean anomaly for the two\nbody problem defined by the relative position `(x,y,z)` and velocity `(u,v,w)` vectors between two bodies\nwith masses `m1` and `m2`.\"\"\"\nfunction meananomaly(\n x, y, z,\n u, v, w,\n m1, m2\n )\n\n E = ecanomaly(x, y, z, u, v, w, m1, m2)\n e = eccentricity(x, y, z, u, v, w, m1, m2)\n\n return E-e*sin(E)\nend\n\n\"\"\"`timeperipass(t, x, y, z, u, v, w, m1, m2)`\n\nCalculates the instantaneous (osculating) time of pericentre passage, at time `t`, for the two\nbody problem defined by the relative position `(x,y,z)` and velocity `(u,v,w)` vectors between two bodies\nwith masses `m1` and `m2`.\"\"\"\nfunction timeperipass(\n t, x, y, z,\n u, v, w,\n m1, m2\n )\n\n me_an = meananomaly(x, y, z, u, v, w, m1, m2) #mean anomaly\n a = semimajoraxis(x, y, z, u, v, w, m1, m2)\n me_mo = meanmotion(m1+m2, a) #mean motion\n\n return t-me_an/me_mo\nend\n\n\"\"\"`rungelenzx(x, y, z, u, v, w, m1, m2)`\n\nCalculates the instantaneous (osculating) x-component of the Laplace-Runge-Lenz vector for the two\nbody problem defined by the relative position `(x,y,z)` and velocity `(u,v,w)` vectors between two bodies\nwith masses `m1` and `m2`.\"\"\"\nfunction rungelenzx(\n x, y, z,\n u, v, w,\n m1, m2\n )\n\n # v = [u, v, w]\n # h = [y.*w-z.*v, z.*u-x.*w, x.*v-y.*u]\n mu = m1+m2\n # r = [x, y, z]\n rmag = sqrt(x^2+y^2+z^2)\n\n lrl_x = ( -(z*u-x*w)*w+(x*v-y*u)*v )/(mu)-x/rmag\n\n return lrl_x\nend\n\n\"\"\"`rungelenzy(x, y, z, u, v, w, m1, m2)`\n\nCalculates the instantaneous (osculating) y-component of the Laplace-Runge-Lenz vector for the two\nbody problem defined by the relative position `(x,y,z)` and velocity `(u,v,w)` vectors between two bodies\nwith masses `m1` and `m2`.\"\"\"\nfunction rungelenzy(\n x, y, z,\n u, v, w,\n m1, m2\n )\n\n # v = [u, v, w]\n # h = [y.*w-z.*v, z.*u-x.*w, x.*v-y.*u]\n mu = m1+m2\n # r = [x, y, z]\n rmag = sqrt(x^2+y^2+z^2)\n\n lrl_y = ( -(x*v-y*u)*u+(y*w-z*v)*w )/(mu)-y/rmag\n\n return lrl_y\nend\n\n\"\"\"`rungelenzz(x, y, z, u, v, w, m1, m2)`\n\nCalculates the instantaneous (osculating) z-component of the Laplace-Runge-Lenz vector for the two\nbody problem defined by the relative position `(x,y,z)` and velocity `(u,v,w)` vectors between two bodies\nwith masses `m1` and `m2`.\"\"\"\nfunction rungelenzz(\n x, y, z,\n u, v, w,\n m1, m2\n )\n\n # v = [u, v, w]\n # h = [y.*w-z.*v, z.*u-x.*w, x.*v-y.*u]\n mu = m1+m2\n # r = [x, y, z]\n rmag = sqrt(x^2+y^2+z^2)\n\n lrl_z = ( -(y*w-z*v)*v+(z*u-x*w)*u )/(mu)-z/rmag\n\n return lrl_z\nend\n\n\"\"\"`rungelenzmag(x, y, z, u, v, w, m1, m2)`\n\nCalculates the instantaneous (osculating) magnitude of the Laplace-Runge-Lenz vector for the two\nbody problem defined by the relative position `(x,y,z)` and velocity `(u,v,w)` vectors between two bodies\nwith masses `m1` and `m2`.\"\"\"\nfunction rungelenzmag(\n x, y, z,\n u, v, w,\n m1, m2\n )\n\n # v = [u, v, w]\n # h = [y.*w-z.*v, z.*u-x.*w, x.*v-y.*u]\n mu = m1+m2\n # r = [x, y, z]\n rmag = sqrt(x^2+y^2+z^2)\n\n lrl_x = ( -(z*u-x*w)*w+(x*v-y*u)*v )/(mu)-x/rmag\n lrl_y = ( -(x*v-y*u)*u+(y*w-z*v)*w )/(mu)-y/rmag\n lrl_z = ( -(y*w-z*v)*v+(z*u-x*w)*u )/(mu)-z/rmag\n\n return sqrt(lrl_x^2+lrl_y^2+lrl_z^2)\nend\n\n\"\"\"`lrlvec(x, y, z, u, v, w, m1, m2)`\n\nCalculates the instantaneous (osculating) cartesian components of the Laplace-Runge-Lenz vector for the two\nbody problem defined by the relative position `(x,y,z)` and velocity `(u,v,w)` vectors between two bodies\nwith masses `m1` and `m2`.\"\"\"\nfunction lrlvec(\n x, y, z,\n u, v, w,\n m1, m2\n )\n\n mu = m1+m2\n rmag = sqrt(x^2+y^2+z^2)\n\n lrl_x = ( -(z*u-x*w)*w+(x*v-y*u)*v )/(mu)-x/rmag\n lrl_y = ( -(x*v-y*u)*u+(y*w-z*v)*w )/(mu)-y/rmag\n lrl_z = ( -(y*w-z*v)*v+(z*u-x*w)*u )/(mu)-z/rmag\n\n return [lrl_x, lrl_y, lrl_z]\nend\n\n# compute eccentric anomaly (E) from eccentricity (e) and mean anomaly (M)\nfunction eccentricanomaly(e::T, M::T) where {T <: Number}\n M0 = mod2pi(M)\n E0 = M0 + sign(sin(M0))*0.85*e #Murray-Dermotts' initial estimate\n # successive approximations via Newtons' method\n for i in 0:4\n #TODO: implement modified Newton's method for Kepler's equation (Murray-Dermott)\n Eans = E0 - (E0-e*sin(E0)-M0)/(1.0-e*cos(E0))\n E0 = Eans\n end\n return E0\nend\n\n# compute true anomaly (f) from eccentricity (e) and eccentric anomaly (E)\nfunction trueanomaly(e,E)\n Enew = mod2pi(E)\n return 2.0*atan( sqrt((1.0+e)/(1.0-e))*tan(Enew/2) )\nend\n\n# compute true anomaly from eccentricity and mean anomaly\nfunction meanan2truean(e,M)\n return trueanomaly(e, eccentricanomaly(e, M))\nend\n\n# get mean motion from mass parameter (mu) and semimajor axis (a)\nfunction meanmotion(mu,a)\n return sqrt(mu/(a^3))\nend\n\n# get mean anomaly from mean motion (n), time (t) and time of pericenter passage (taup)\nfunction meananomaly(n, t, taup)\n return n*(t-taup)\nend\n\n# compute true anomaly from time, a, e, mu and taup\nfunction time2truean(a, e, mu, t, taup)\n return meanan2truean(e, meananomaly(meanmotion(mu, a), t, taup))\nend\n", "meta": {"hexsha": "ea90cb8136c5174c625117520e84676311a57b79", "size": 10350, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/osculating.jl", "max_stars_repo_name": "PerezHz/PlanetaryEphemeris.jl", "max_stars_repo_head_hexsha": "bcab105a98aee737642486c552ba4c14ed0364bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-03T08:34:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-03T08:34:12.000Z", "max_issues_repo_path": "src/osculating.jl", "max_issues_repo_name": "PerezHz/PlanetaryEphemeris.jl", "max_issues_repo_head_hexsha": "bcab105a98aee737642486c552ba4c14ed0364bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-26T20:23:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-26T20:23:01.000Z", "max_forks_repo_path": "src/osculating.jl", "max_forks_repo_name": "PerezHz/PlanetaryEphemeris.jl", "max_forks_repo_head_hexsha": "bcab105a98aee737642486c552ba4c14ed0364bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-03-16T15:10:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T01:15:00.000Z", "avg_line_length": 27.0942408377, "max_line_length": 109, "alphanum_fraction": 0.5856038647, "num_tokens": 3935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517106286379, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.8167812497551835}} {"text": "using Plots, LaTeXStrings, Statistics, Distributions,StatsPlots, JLD\n\nN=1000000\nσList=[1, 2, 3, 4, 5 ]\nfunction GaussianD(σ, UniformD)\n x1=rand(UniformD, round(Int,N/2))\n x2=rand(UniformD, round(Int,N/2))\n ρ=σ * .√(2 * log.(1 ./ (1 .- x1)))\n θ=2π * x2\n y1=ρ.*cos.(θ)\n y2=ρ.*sin.(θ)\n return [y1 ; y2]\nend\nData=[GaussianD(σList[i], rand(N)) for i in 1:5]\nsave(\"../../chapter6/6.4/samples.jld\",\"Samples\", Data)\ncolors=[:rosybrown, :turquoise,:khaki1,:lightblue1, :lightpink2]\nplot()\nfor i in 1:length(σList)\n histogram!(Data[i],bins=70,linecolor=:gray, color=colors[i],normalize = true, label=L\"Histogram\\ of\\ Samples\")\n plot!(Normal(mean(Data[i]),std(Data[i])), c = :black, label= L\"\\sigma = %$(round(std(Data[i]),digits = 2)))\")\nend\nplot!(xlabel=L\"\",title=L\"Normalized\\ Distribution\\ of\\ Samples\")\n# plot(plots..., size = (1000,1000), plot_title = \"Normalized Distribution of Samples\", dpi=600)\nsavefig(\"C:\\\\Users\\\\Narges\\\\Documents\\\\GitHub\\\\computational_physics\\\\chapter6\\\\6.4\\\\Figs\\\\N_Distribution.png\")\n", "meta": {"hexsha": "edf96cd20ecdd9b1a911fc04c63a694dbc3f64a9", "size": 1043, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "chapter6/6.4/6.4.jl", "max_stars_repo_name": "narges8k/computational_physics", "max_stars_repo_head_hexsha": "a24229aa7b31648735aab120cd667dffd788df1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapter6/6.4/6.4.jl", "max_issues_repo_name": "narges8k/computational_physics", "max_issues_repo_head_hexsha": "a24229aa7b31648735aab120cd667dffd788df1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter6/6.4/6.4.jl", "max_forks_repo_name": "narges8k/computational_physics", "max_forks_repo_head_hexsha": "a24229aa7b31648735aab120cd667dffd788df1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-13T09:55:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T09:55:00.000Z", "avg_line_length": 41.72, "max_line_length": 118, "alphanum_fraction": 0.6538830297, "num_tokens": 366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850057480347, "lm_q2_score": 0.8723473630627235, "lm_q1q2_score": 0.8167657558394651}} {"text": "# Astronomy example from Hairer et al 1992 p.129 (see also Szebehely\n# 1967): the orbit of a satellite in planet-moon system. This system\n# has know periodic solutions, so called “Arenstorf orbits”\n# (Arenstorf, 1963); one of which is used as a test-case.\n#\n# This is a non-stiff problem. Adaptive solvers will fare much better\n# as there are three regions where the satellite experiences very\n# strong acceleration interspersed with regions of very small\n# acceleration.\n\nexport threebody\n\nthreebody = let\n tcname = :threebody\n T = Float64 # the datatype used\n Tarr = Matrix\n dof = 4 # degrees of freedom\n dae=0 # index of DAE, ==0 for ODE\n # stiffness of system, one of the three constants\n stiffness = [nonstiff, mildlystiff, stiff][1] \n\n # parameters\n μ = 0.012277471\n μ′ = 1-μ\n \n function fn!(t,y,dydt)\n # the ode function\n \n y1, y2, y1′, y2′ = y[:] # this allocates memory... but less than below\n D1 = ((y1+μ )^2 + y2^2)^(3/2)\n D2 = ((y1-μ′)^2 + y2^2)^(3/2)\n y1″ = y1 + 2*y2′ - μ′*(y1+μ)/D1 - μ*(y1-μ′)/D2\n y2″ = y2 - 2*y1′ - μ′*y2/D1 - μ*y2/D2\n dydt[:] = [y1′, y2′, y1″, y2″] # this allocates memory...\n return nothing\n end\n fn!( ; T_::Type=T, dof_=dof) = zeros(T_,dof_)\n \n jac! = nothing\n mass! = nothing\n \n ic = T[0.994, 0.0, 0.0, -2.00158510637908252240537862224] # vector of initial conditions\n tspan = T[0, 17.0652165601579625588917206249] # integration interval\n refsol = ic # reference solution at tspan[2]\n refsolinds = trues(dof)\n scd_absinds = ic.==0.0\n tc = TestCaseExplicit{tcname, T, Tarr}(\n stiffness,\n dae,\n dof,\n fn!,\n jac!,\n mass!,\n ic,\n tspan,\n refsol,\n refsolinds,\n scd_absinds)\n\n # put into the right buckets\n tc_all[tcname] = tc\n tc_nonstiff[tcname] = tc\nend\n", "meta": {"hexsha": "1afdc512ae021122ca0b310d40adb6f0255a8adc", "size": 2146, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/testcases/threebody.jl", "max_stars_repo_name": "pwl/IVPTestSuite.jl", "max_stars_repo_head_hexsha": "15d92b5b943c35493ce29e8aa8def14619d96760", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/testcases/threebody.jl", "max_issues_repo_name": "pwl/IVPTestSuite.jl", "max_issues_repo_head_hexsha": "15d92b5b943c35493ce29e8aa8def14619d96760", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/testcases/threebody.jl", "max_forks_repo_name": "pwl/IVPTestSuite.jl", "max_forks_repo_head_hexsha": "15d92b5b943c35493ce29e8aa8def14619d96760", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.53125, "max_line_length": 92, "alphanum_fraction": 0.5307548928, "num_tokens": 652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850004144266, "lm_q2_score": 0.8723473647220786, "lm_q1q2_score": 0.8167657527403354}} {"text": "##\n## i n t e r p o l a t e . j l Interpolation\n##\n\n\nfunction interp1d{T<:Real}(xi::Array{T,1}, yi::Array{T,1}, x::T;\n method::Symbol = :cubic)\n n = length(xi)\n if length(yi) != n\n error(\"Vectors 'xi', 'yi' must be of same length.\")\n end\n if n == 1\n error(\"At least two data points must be provided.\")\n end\n if any(xi[1:end-1] .> xi[2:end])\n error(\"Elements in 'xi' must be strictly increasing.\")\n end\n\n local k::Int = 0\n if x < xi[1]; k = 0\n elseif x >= xi[end]; k = n\n else\n k = maximum(find(xi[1:(end-1)] .<= x))\n end\n \n if method == :constant\n if k == 0; k = 1; end\n return yi[k]\n\n elseif method == :nearest\n if k == 0; k = 1\n elseif k < n\n if x >= (xi[k] + xi[k+1]) / 2.0\n k += 1\n end\n end\n return yi[k]\n \n elseif method == :linear\n if k == 0; k = 1\n elseif k == n; k = n-1; end\n s = x - xi[k]\n delta = (yi[k+1] - yi[k]) / (xi[k+1] - xi[k])\n return yi[k] + (x - xi[k])*delta\n\n elseif method == :spline\n error(\"Method $(method) is not yet implemented.\")\n\n elseif method == :cubic\n return pchip(xi, yi, x)\n\n else\n error(\"Unknown interpolation method: $(method)\")\n end\nend\n\n\nfunction interp1d{T<:Real}(xi::Array{T,1}, yi::Array{T,1}, x::Array{T,1};\n method::Symbol = :cubic)\n local m::Int = length(x)\n y = zeros(m)\n for i = 1:m\n y[i] = interp1d(xi, yi, x[i], method = method)\n end\n return y\nend\n\n\n#-- Moler: Piecewise Cubic Hermitean Interpolation Polynomials\n#\nfunction pchip{T<:Real}(xi::Array{T,1}, yi::Array{T,1}, x::T)\n n = length(xi)\n if length(yi) != n\n error(\"Vectors 'xi', 'yi' must be of same length.\")\n end\n if any(xi[1:end-1] .> xi[2:end])\n error(\"Elements in 'xi' must be strictly increasing.\")\n end\n\n # First derivatives\n h = diff(xi)\n delta = diff(yi) ./ h\n d = pchip_slopes(h, delta)\n\n # Piecewise polynomial coefficients\n a = (3.0*delta .- 2.0*d[1:(n-1)] .- d[2:n]) ./ h\n b = (d[1:(n-1)] .- 2.0*delta .+ d[2:n]) ./ h.^2\n\n # Find subinterval index k so that xi[k] <= x < xi[k+1]\n if x < xi[1]\n k = 1\n else\n k = maximum(find(xi[1:(n-1)] .<= x))\n end\n\n # Evaluate interpolant\n s = x - xi[k]\n v = yi[k] + s*(d[k] + s*(a[k] + s*b[k]))\n\n return v\nend\n\nfunction pchip_slopes(h, delta)\n\n # Slopes at interior points\n local n = length(h) + 1\n d = zeros(n)\n k = find(sign(delta[1:(n-2)]) .* sign(delta[2:(n-1)]) .> 0.0) .+ 1\n w1 = 2.0*h[k] .+ h[k.-1]\n w2 = h[k] .+ 2.0*h[k.-1]\n d[k] = (w1+w2) ./ (w1./delta[k.-1] + w2./delta[k])\n\n # Slopes at endpoints\n d[1] = pchip_end(h[1], h[2], delta[1], delta[2])\n d[n] = pchip_end(h[n-1], h[n-2], delta[n-1], delta[n-2])\n\n return d\nend\n\nfunction pchip_end(h1, h2, del1, del2)\n\n # Noncentered, shape-preserving, three-point formula.\n d = ((2.0*h1 + h2)*del1 - h1*del2) / (h1 + h2)\n if sign(d) != sign(del1)\n d = 0\n elseif sign(del1) != sign(del2) && abs(d) > abs(3*del1)\n d = 3.0*del1\n end\n\n return d\nend\n", "meta": {"hexsha": "465ebb2cb01cfd1d94a93b8426f9664473dceecc", "size": 3213, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/interpolate.jl", "max_stars_repo_name": "hwborchers/NumericalMath.jl", "max_stars_repo_head_hexsha": "5afaa8d71e496dd71a2dbd642a688999b5f9963d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-03-11T19:26:16.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-12T21:39:58.000Z", "max_issues_repo_path": "src/interpolate.jl", "max_issues_repo_name": "hwborchers/NumericalMath.jl", "max_issues_repo_head_hexsha": "5afaa8d71e496dd71a2dbd642a688999b5f9963d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2016-02-05T14:03:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-26T03:45:52.000Z", "max_forks_repo_path": "src/interpolate.jl", "max_forks_repo_name": "hwborchers/NumericalMath.jl", "max_forks_repo_head_hexsha": "5afaa8d71e496dd71a2dbd642a688999b5f9963d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2015-01-25T21:38:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-26T04:30:29.000Z", "avg_line_length": 24.3409090909, "max_line_length": 73, "alphanum_fraction": 0.4939309057, "num_tokens": 1155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240073565739, "lm_q2_score": 0.8705972566572503, "lm_q1q2_score": 0.8167281872089392}} {"text": "using LinearAlgebra\nusing Plots\n\n\nfunction newtons_method(∇f, H, x, ϵ, k_max)\n k, Δ = 1, Inf\n while abs(Δ) > ϵ && k ≤ k_max\n Δ = ∇f(x)/abs(H(x))\n x -= Δ\n k += 1\n end\n return x\nend\n\n\n#definicao da funcao\nf = x-> -(0.4/((x^2+1))^(1/2))+((x^2+1)^(1/2))*(1-0.4/(x^2+1))-x #multiplicada por -1 para encontrar o minimo\ng = x-> -(-(0.4/((x^2+1))^(1/2))+((x^2+1)^(1/2))*(1-0.4/(x^2+1))-x) #funcao original\n\n#definicao da primeira derivada\ndf(x) = 1.2*x/((x^2+1)^(3/2))+(1-0.4/(x^2+1))*x/((x^2+1)^(1/2))-1\n\n#definicao da segunda derivada\nddf(x) = (-0.6*x^2+1.8)/((x^2+1)^(5/2))\n\n#converge para o ponto de minimo\ninitial_point = 1 #ponto inicial\nconvergence = 1e-8 #convergencia\nmaximum_iterations = 10 #numero maximo de iteracoes\nxs = newtons_method(df,ddf,initial_point,convergence,maximum_iterations)\n#xs,f(xs),ddf(xs),df(xs)\n\nprintln(\"initial_point = \", initial_point)\nprintln(\"x* = \", xs)\nprintln(\"f(x*) = \", g(xs))\n\n\nplot(g,min(initial_point,xs)-1.,max(initial_point,xs)+1.,lw=2,draw_arrow=\"true\",label=\"Function\")\nscatter!([initial_point],[g(initial_point)])\nscatter!([xs],[g(xs)])\n", "meta": {"hexsha": "4ed28a824531af328a1a58b12d4c1cf578e21448", "size": 1128, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "exercicio01_newtons_method.jl", "max_stars_repo_name": "GilbertoLucas/Structural_Optimization", "max_stars_repo_head_hexsha": "e12ed13bbb97db275d79a0e5bfcad6438a643441", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exercicio01_newtons_method.jl", "max_issues_repo_name": "GilbertoLucas/Structural_Optimization", "max_issues_repo_head_hexsha": "e12ed13bbb97db275d79a0e5bfcad6438a643441", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exercicio01_newtons_method.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": 27.512195122, "max_line_length": 112, "alphanum_fraction": 0.6019503546, "num_tokens": 461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.958537730841905, "lm_q2_score": 0.8519528038477824, "lm_q1q2_score": 0.8166289073846519}} {"text": "function chebyshev_polynomial(order::S,x::T) where {T<:Number,S<:Integer}\n\n polynomial = Array{T}(undef,1,order+1)\n polynomial[1] = one(T)\n \n for i = 2:order+1\n if i == 2\n polynomial[i] = x\n else\n polynomial[i] = 2*x*polynomial[i-1]-polynomial[i-2]\n end\n end\n \n return polynomial\n \nend\n \nfunction chebyshev_polynomial(order::S,x::AbstractArray{T,1}) where {T<:Number,S<:Integer}\n \n polynomial = Array{T}(undef,length(x),order+1)\n polynomial[:,1] = ones(T,length(x))\n \n for i = 2:order+1\n for j = 1:length(x)\n if i == 2\n polynomial[j,i] = x[j]\n else\n polynomial[j,i] = 2*x[j]*polynomial[j,i-1]-polynomial[j,i-2]\n end\n end\n end\n \n return polynomial\n \nend\n \nfunction derivative_of_chebyshev_polynomial(order::S,x::T) where {T<:Number,S<:Integer}\n \n polynomial = Array{T}(undef,1,order+1)\n poly_deriv = Array{T}(undef,1,order+1)\n polynomial[1] = one(T)\n poly_deriv[1] = zero(T)\n \n for i = 2:order+1\n if i == 2\n polynomial[i] = x\n poly_deriv[i] = one(T)\n else\n polynomial[i] = 2*x*polynomial[i-1]-polynomial[i-2]\n poly_deriv[i] = 2*polynomial[i-1]+2*x*poly_deriv[i-1]-poly_deriv[i-2] \n end\n end\n \n return poly_deriv\n \nend\n", "meta": {"hexsha": "0cac718bcf0edd7ae411ce39e891fe1c05ab61d5", "size": 1244, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chebyshev_polynomial.jl", "max_stars_repo_name": "RJDennis/ChebyshevApprox.jl", "max_stars_repo_head_hexsha": "f3052ad7b6eab8bcec2930b111b52f92d5b00586", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2016-12-05T19:52:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T03:08:35.000Z", "max_issues_repo_path": "src/chebyshev_polynomial.jl", "max_issues_repo_name": "RJDennis/ChebyshevApprox.jl", "max_issues_repo_head_hexsha": "f3052ad7b6eab8bcec2930b111b52f92d5b00586", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2016-08-05T15:45:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-20T19:08:32.000Z", "max_forks_repo_path": "src/chebyshev_polynomial.jl", "max_forks_repo_name": "RJDennis/ChebyshevApprox.jl", "max_forks_repo_head_hexsha": "f3052ad7b6eab8bcec2930b111b52f92d5b00586", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-08-23T23:50:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T12:21:55.000Z", "avg_line_length": 21.8245614035, "max_line_length": 90, "alphanum_fraction": 0.6012861736, "num_tokens": 428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012671214071, "lm_q2_score": 0.8633916134888613, "lm_q1q2_score": 0.8165968820597612}} {"text": "# # Numerical Stability\n\nusing Distributions\nusing HMMBase\nusing PyPlot\nusing Seaborn\n\nrc(\"axes\", xmargin = 0) # hide\nset_style(\"whitegrid\") # hide\n\n# Let's consider the case of a Normal distribution with null variance,\n# such a case can appear during maximum likelihood estimation if only\n# one observation is associated to a state:\n\nA = [0.99 0.01; 0.1 0.9]\nB = [Normal(0, 1), Normal(10.5, 0)]\nhmm = HMM(A, B)\n#-\n\ny = rand(hmm, 500)\nfigure(figsize = (9,2)) # hide\nplot(y)\ngcf() # hide\n#-\n\n# The likelihood of a Normal distribution with null variance goes to infinity for `y = μ`,\n# as there is a division by zero in the density function:\nprintln(extrema(likelihoods(hmm, y)))\nprintln(extrema(likelihoods(hmm, y, logl = true)))\n\n# To avoid propagating these non-finite quantities (for example in the forward-backward algorithm),\n# you can use the `robust` option:\nprintln(extrema(likelihoods(hmm, y, robust = true)))\nprintln(extrema(likelihoods(hmm, y, logl = true, robust = true)))\n\n# This truncates `+Inf` to the largest Float64, and `-Inf` to the smallest Float64:\nprevfloat(Inf), nextfloat(-Inf)\n\n# In the log. case we use `log(prevfloat(Inf))` to avoid overflows when taking\n# the exp. of the log-likelihood.\n", "meta": {"hexsha": "0b6ade6f3c7a3e77c860bb7045d290d4bc104af1", "size": 1216, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/numerical_stability.jl", "max_stars_repo_name": "Shu-Lea-Lai/module-MultiHMMBase", "max_stars_repo_head_hexsha": "3d467458b498a2ba6b1c81eb4fee4467aeea121b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-28T18:51:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-28T18:51:59.000Z", "max_issues_repo_path": "examples/numerical_stability.jl", "max_issues_repo_name": "Shu-Lea-Lai/module-MultiHMMBase.jl", "max_issues_repo_head_hexsha": "3d467458b498a2ba6b1c81eb4fee4467aeea121b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/numerical_stability.jl", "max_forks_repo_name": "Shu-Lea-Lai/module-MultiHMMBase.jl", "max_forks_repo_head_hexsha": "3d467458b498a2ba6b1c81eb4fee4467aeea121b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6585365854, "max_line_length": 99, "alphanum_fraction": 0.7195723684, "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218412907381, "lm_q2_score": 0.8856314813647588, "lm_q1q2_score": 0.8164830060048424}} {"text": "@model SDTmodel(data) = begin\n d ~ Normal(0, 1/sqrt(.5))\n c ~ Normal(0, 1/sqrt(2))\n data ~ SDT(d, c)\nend\n\nAHMC_SDT(hits, fas, Nd) = SDTmodel((hits, fas, Nd))\n\nAHMCconfig = Turing.NUTS(1000, .85)\n\nCmdStan_SDT = \"\ndata {\n int Nd;\n int hits;\n int fas;\n}\nparameters {\n real d;\n real c;\n}\n\nmodel {\n real thetah;\n real thetaf;\n\n d ~ normal(0, inv_sqrt(.5));\n c ~ normal(0, inv_sqrt(2));\n\n thetah = Phi(d/2-c);\n thetaf = Phi(-d/2-c);\n\n // Observed counts\n hits ~ binomial(Nd, thetah);\n fas ~ binomial(Nd, thetaf);\n}\n\"\n\nCmdStanConfig = Stanmodel(name=\"CmdStan_SDT\", model=CmdStan_SDT, nchains=1, output_format=:mcmcchains,\n Sample(num_samples=1000, num_warmup=1000, adapt=CmdStan.Adapt(delta=0.8),\n save_warmup=true))\n\n struct SDTProblem\n hits::Int64\n fas::Int64\n Nd::Int64\n end\n\n function (problem::SDTProblem)(θ)\n @unpack hits,fas,Nd=problem # extract the data\n @unpack d,c=θ\n logpdf(SDT(d, c),[hits, fas, Nd]) + logpdf(Normal(0, 1/sqrt(.5)), d) +\n logpdf(Normal(0, 1/sqrt(2)), c)\n end\n\n # Define problem with data and inits.\n function sampleDHMC(hits, fas, Nd, nsamples, autodiff)\n p = SDTProblem(hits, fas, Nd)\n p((d=2.0, c=.0))\n # Write a function to return properly dimensioned transformation.\n trans = as((d=asℝ, c=asℝ))\n P = TransformedLogDensity(trans, p)\n ∇P = ADgradient(autodiff, P)\n # Sample from the posterior.\n results = mcmc_with_warmup(Random.GLOBAL_RNG, ∇P, nsamples; reporter = NoProgressReport())\n # Undo the transformation to obtain the posterior from the chain.\n posterior = TransformVariables.transform.(trans, results.chain)\n chns = nptochain(results, posterior)\n return chns\n end\n\n function simulateSDT(;d=2., c=0., Nd, kwargs...)\n θhit = cdf(Normal(0, 1), d/2-c)\n θfa = cdf(Normal(0, 1), -d/2-c)\n hits = rand(Binomial(Nd, θhit))\n fas = rand(Binomial(Nd, θfa))\n return (hits=hits, fas=fas, Nd=Nd)\n end\n", "meta": {"hexsha": "101fb25f5f306f08fc8dfa6f1cb5fc9f70580d1e", "size": 1971, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SDT/SDT.jl", "max_stars_repo_name": "StatisticalRethinkingJulia/MCMCBenchmarkSuite", "max_stars_repo_head_hexsha": "6e3e460d9b19b2c370d4046f5d89e80c3ae02003", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-01-04T14:22:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-10T13:02:48.000Z", "max_issues_repo_path": "src/SDT/SDT.jl", "max_issues_repo_name": "StatisticalRethinkingJulia/MCMCBenchmarkSuite.jl", "max_issues_repo_head_hexsha": "6e3e460d9b19b2c370d4046f5d89e80c3ae02003", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-01-04T15:16:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-25T15:52:58.000Z", "max_forks_repo_path": "src/SDT/SDT.jl", "max_forks_repo_name": "StatisticalRethinkingJulia/MCMCBenchmarkSuite.jl", "max_forks_repo_head_hexsha": "6e3e460d9b19b2c370d4046f5d89e80c3ae02003", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-01-04T14:05:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-25T16:28:55.000Z", "avg_line_length": 25.2692307692, "max_line_length": 102, "alphanum_fraction": 0.6377473364, "num_tokens": 701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455084, "lm_q2_score": 0.8856314753275017, "lm_q1q2_score": 0.8164829985390804}} {"text": "# softmax illustration\nfunction softmax(v)\n max = maximum(v)\n explist = [exp(x - max) for x in v]\n expsum = sum(explist)\n dist = [exp_ / expsum for exp_ in explist]\nend\n\nv = rand(5)\ndist = softmax(v)\n\nprintln(dist)\n# softmax function: sum of classes is 1.0\nprintln(sum(dist))", "meta": {"hexsha": "384a0c5cdb71a32ded9e41a2d0f77465dd3d9b1d", "size": 287, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "memos/deeplearning/softmax.jl", "max_stars_repo_name": "Bingwen-Hu/hackaway", "max_stars_repo_head_hexsha": "69727d76fd652390d9660e9ea4354ba5cc76dd5c", "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": "memos/deeplearning/softmax.jl", "max_issues_repo_name": "Bingwen-Hu/hackaway", "max_issues_repo_head_hexsha": "69727d76fd652390d9660e9ea4354ba5cc76dd5c", "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": "memos/deeplearning/softmax.jl", "max_forks_repo_name": "Bingwen-Hu/hackaway", "max_forks_repo_head_hexsha": "69727d76fd652390d9660e9ea4354ba5cc76dd5c", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.5, "max_line_length": 46, "alphanum_fraction": 0.6620209059, "num_tokens": 86, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632247867715, "lm_q2_score": 0.8577681013541613, "lm_q1q2_score": 0.8164779110741982}} {"text": "# Code from first section\nusing PyPlot\nusing Statistics\nA = imread(\"sample_photo.png\")\nB = mean(A, dims=3)[:,:,1]\nfunction imshow_scale(A)\n # Like imshow(A) but scales the values to [0,1] and supports grayscale\n \n A .-= minimum(A) # Scale and shift to [0,1]\n A ./= maximum(A)\n if ndims(A) < 3\n A = reshape(A, size(A,1), size(A,2), 1)\n end\n if size(A,3) == 1\n A = repeat(A, 1, 1, 3) # Set R=G=B for grayscale\n end\n imshow(A)\nend\nfunction image_threshold(A, th)\n return Float64.(A .> th)\n end;\n\nfunction image_avgfilter(A)\n B = 0*A\n for i = 2:size(A,1)-1, j = 2:size(A,2)-1\n B[i,j] = mean(A[i-1:i+1, j-1:j+1])\n end\n return B\nend\n\nfunction filter_demo(B, filter_function)\n E = copy(B);\n for i = 0:3\n subplot(2,2,i+1); imshow_scale(E[260:350,300:420,:])\n title(\"$(i) times average filter\")\n E = filter_function(E);\n end\n tight_layout()\nend\nfilter_demo(B, image_avgfilter)\n\nBnoise = B + 0.1randn(size(B)) # Add noise\nBnoise = max.(min.(Bnoise, 1.0), 0.0) # Ensure values in [0,1]\nfilter_demo(Bnoise, image_avgfilter)\n\nfunction image_medianfilter(A)\n B = 0*A\n for i = 2:size(A,1)-1, j = 2:size(A,2)-1\n B[i,j] = median(A[i-1:i+1, j-1:j+1])\n end\n return B\nend\n\nBnoise2 = copy(B)\nBnoise2[rand(1:length(B), 10000)] = 0.1rand(10000)\nfilter_demo(Bnoise2, image_medianfilter)\n\nfunction image_maxabsgradfilter(A)\n B = 0*A\n for i = 2:size(A,1)-1, j = 2:size(A,2)-1\n a = A[i-1:i+1, j-1:j+1]\n B[i,j] = max(abs(a[3,2] - a[1,2]), abs(a[2,3] - a[2,1]))\n end\n return B\nend\n\nBsmooth = image_avgfilter(B);\nBgrad = image_maxabsgradfilter(Bsmooth);\nimshow_scale(Bgrad); title(\"Gradient filter\");\n\nBedges = 1.0 .- image_threshold(Bgrad, 0.1)\nimshow_scale(Bedges); title(\"Edge detection\");\n", "meta": {"hexsha": "54217ac964892edcb7ac9c5b5186abb719c4a661", "size": 1821, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "textbook/_build/jupyter_execute/content/Image_Processing/Filtering.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/Image_Processing/Filtering.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/Image_Processing/Filtering.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.9452054795, "max_line_length": 74, "alphanum_fraction": 0.5974739154, "num_tokens": 651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.930458253565792, "lm_q2_score": 0.8774767970940974, "lm_q1q2_score": 0.8164555281686787}} {"text": "#=\n\n Euler #5 in Julia.\n\n Problem 5\n \"\"\"\n 2520 is the smallest number that can be divided by each of the numbers\n from 1 to 10 without any remainder.\n\n What is the smallest number that is evenly divisible by all of the numbers\n from 1 to 20?\n \"\"\"\n\n This Julia program was created by Hakan Kjellerstrand, hakank@gmail.com\n See also my Julia page: http://www.hakank.org/julia/\n\n=#\n\ninclude(\"Euler.jl\")\n\n# 0.00000113s\nfunction euler5a()\n a = 1\n for i in 2:20\n a = lcm(a,i)\n end\n return a\nend\n\n#\n# 0.00000113s\nfunction euler5b()\n return reduce(lcm,2:20)\nend\n\n#\nfunction euler5c()\n return lcm(2:20)\nend\n\n\nrun_euler(euler5a)\n# run_euler(euler5b)\n# run_euler(euler5c)\n", "meta": {"hexsha": "d15e47838b976bfc79a66a8957ffbbbee7e9c76d", "size": 696, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/euler5.jl", "max_stars_repo_name": "Wikunia/hakank", "max_stars_repo_head_hexsha": "030bc928d2efe8dcbc5118bda3f8ae9575d0fd13", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/euler5.jl", "max_issues_repo_name": "Wikunia/hakank", "max_issues_repo_head_hexsha": "030bc928d2efe8dcbc5118bda3f8ae9575d0fd13", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/euler5.jl", "max_forks_repo_name": "Wikunia/hakank", "max_forks_repo_head_hexsha": "030bc928d2efe8dcbc5118bda3f8ae9575d0fd13", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 15.4666666667, "max_line_length": 76, "alphanum_fraction": 0.6724137931, "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.930458253565792, "lm_q2_score": 0.8774767874818408, "lm_q1q2_score": 0.8164555192248752}} {"text": "# L2 norm (times a constant)\n\n\"\"\"\n NormL2(λ::Real=1.0)\n\nReturns the function `g(x) = λ||x||_2`, for a real parameter `λ ⩾ 0`.\n\"\"\"\n\nimmutable NormL2{R <: Real} <: ProximableConvex\n lambda::R\n function NormL2(lambda::R)\n if lambda < 0\n error(\"parameter λ must be nonnegative\")\n else\n new(lambda)\n end\n end\nend\n\nNormL2{R <: Real}(lambda::R=1.0) = NormL2{R}(lambda)\n\nfunction (f::NormL2)(x::AbstractArray)\n return f.lambda*vecnorm(x)\nend\n\nfunction prox!{T <: RealOrComplex}(f::NormL2, x::AbstractArray{T}, y::AbstractArray{T}, gamma::Real=1.0)\n vecnormx = vecnorm(x)\n scale = max(0, 1-f.lambda*gamma/vecnormx)\n for i in eachindex(x)\n y[i] = scale*x[i]\n end\n return f.lambda*scale*vecnormx\nend\n\nfun_name(f::NormL2) = \"Euclidean norm\"\nfun_dom(f::NormL2) = \"AbstractArray{Real}, AbstractArray{Complex}\"\nfun_expr(f::NormL2) = \"x ↦ λ||x||_2\"\nfun_params(f::NormL2) = \"λ = $(f.lambda)\"\n\nfunction prox_naive{T <: RealOrComplex}(f::NormL2, x::AbstractArray{T}, gamma::Real=1.0)\n vecnormx = vecnorm(x)\n scale = max(0, 1-f.lambda*gamma/vecnormx)\n y = scale*x\n return y, f.lambda*scale*vecnormx\nend\n", "meta": {"hexsha": "72ee6acf2c8d113ea9d4675dc4417d78b285bea4", "size": 1119, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/normL2.jl", "max_stars_repo_name": "mfalt/ProximalOperators.jl", "max_stars_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functions/normL2.jl", "max_issues_repo_name": "mfalt/ProximalOperators.jl", "max_issues_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions/normL2.jl", "max_forks_repo_name": "mfalt/ProximalOperators.jl", "max_forks_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3260869565, "max_line_length": 104, "alphanum_fraction": 0.6595174263, "num_tokens": 405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582516374121, "lm_q2_score": 0.8774767794716264, "lm_q1q2_score": 0.8164555100795965}} {"text": "# Plot PSD of simple harmonic oscillator with different values of Q:\n\nusing PyPlot\n\n\nsho_psd(x,Q) = 1./((x.^2-1.).^2+x.^2./Q^2)\n\nx = logspace(-1.5,1.5,100000)\n\nlw = 3\n\nfig,ax= subplots(1,1)\nQ = 0.5\nax[:loglog](x,sho_psd(x,Q),label=L\"$Q=\\frac{1}{2}$; Matern 3/2\",linewidth=lw)\nQ = 1./sqrt(2.)\nax[:loglog](x,sho_psd(x,Q),label=L\"$Q=\\frac{1}{\\sqrt{2}}$\",linewidth=lw)\n#Q = 1.\n#ax[:loglog](x,sho_psd(x,Q),label=L\"$Q=1$\",linewidth=lw)\nQ = 2.0\nax[:loglog](x,sho_psd(x,Q),label=L\"$Q=2$\",linewidth=lw)\n#Q = 4.0\n#ax[:loglog](x,sho_psd(x,Q),label=\"Q=4\",linewidth=lw)\nQ = 10.0\nax[:loglog](x,sho_psd(x,Q),label=L\"$Q=10$\",linewidth=lw)\n#lorentz_psd(x,Q) = Q^2./ ((x-sqrt(1.-1/2/Q^2)).^2.*(1-1/2/Q^2) * (2*Q)^2 + 1-1/4/Q^2)\n#lorentz_psd(x,Q) = Q^2.* (1./ ((x-sqrt(1.-1/2/Q^2)).^2 * (2*Q)^2 + 1-1/4/Q^2) +\nlorentz_psd(x,Q) = Q^2.*(1./ ((x-sqrt(1.-1/2/Q^2)).^2.*(1-1/2/Q^2) * (2*Q)^2 + 1-1/4/Q^2)\n +1./ ((x+sqrt(1.-1/2/Q^2)).^2.*(1-1/2/Q^2) * (2*Q)^2 + 1-1/4/Q^2))\n\n#lorentzian = 1./((4-2./Q^2).*(x-sqrt(1-.5/Q^2)).^2+(1./Q^2-.25/Q^4))\nax[:loglog](x,lorentz_psd(x,Q),label=\"Lorentzian\",ls=\"dashed\",linewidth=lw)\n\nqgrid = linspace(1./sqrt(2.)+1e-3,10,1000)\nxmax = sqrt(1.-.5./qgrid.^2)\nax[:loglog](xmax,4.*qgrid.^4./(4.*qgrid.^2-1.),linewidth=2,ls=\"dotted\",color=\"black\")\n\n#matern= 1./(1+x.^2).^2\n#ax[:loglog](x,matern,label=\"Matern\",ls=\"dashed\",linewidth=lw)\n\nfontsize=20\nax[:legend](loc=\"upper right\",fontsize=fontsize)\nax[:set_xlabel](L\"$\\omega/\\omega_0$\",fontsize=fontsize*2)\nax[:set_ylabel](L\"$P(\\omega)/P(0)$\",fontsize=fontsize*2)\n\nax[:axis]([1./10.^1.5,10^1.5,1e-4,1e2])\n\nfunction sho_acf(omtau,Q)\n# omtau is \\omega_0*\\tau\n# ACF is normalized by P_0*\\omega_0\n# This is only valid for Q >= 1/2\n@assert(Q >= 0.5)\nlam = sqrt(1.-.25/Q^2).*omtau\nphi = atan(1/sqrt(4.*Q^2-1.))\nacf = exp(-.5.*omtau./Q).*cos(lam-phi)\nreturn acf/acf[1]\nend\n\nomtau = collect(linspace(0,6*pi,1000))\n\nfig,ax= subplots(1,1)\nQ = 0.50001\nax[:plot](omtau,sho_acf(omtau,Q),label=L\"$Q=\\frac{1}{2}$\",linewidth=lw,color=\"blue\")\nQ = 1/sqrt(2)\nax[:plot](omtau,sho_acf(omtau,Q),label=L\"$Q=\\frac{1}{\\sqrt{2}}$\",linewidth=lw,color=\"orange\")\nQ = 2.0\nax[:plot](omtau,sho_acf(omtau,Q),label=L\"$Q=2$\",linewidth=lw,color=\"green\")\nQ = 10.0\nax[:plot](omtau,sho_acf(omtau,Q),label=L\"$Q=10$\",linewidth=lw,color=\"red\")\nax[:plot](omtau,exp(-omtau./2/Q).*cos(omtau),label=\"Lorentzian\",linewidth=lw,color=\"black\",linestyle=\"dashed\")\n#ax[:plot](omtau,exp(-omtau/2).*cos(omtau))\n\n#ax[:legend](loc=\"lower right\",fontsize=fontsize)\nax[:set_xlabel](L\"$\\omega_0 \\tau$\",fontsize=fontsize*2)\nax[:set_ylabel](L\"$k(\\tau)/k(0)$\",fontsize=fontsize*2)\n\n#ax[:axis]([1./10.^1.5,10^1.5,1e-4,1e2])\n\nsavefig(\"acf_sho.pdf\", bbox_inches=\"tight\")\n\n", "meta": {"hexsha": "cc8875902f9ec4633c085a9ea88176c21d9b2402", "size": 2663, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "paper/notes/sho.jl", "max_stars_repo_name": "dfm/ess", "max_stars_repo_head_hexsha": "09ee14e516bb3bc3b517c0c1b6716eaeb28183b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 172, "max_stars_repo_stars_event_min_datetime": "2017-02-10T21:23:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T23:02:20.000Z", "max_issues_repo_path": "paper/notes/sho.jl", "max_issues_repo_name": "dfm/ess", "max_issues_repo_head_hexsha": "09ee14e516bb3bc3b517c0c1b6716eaeb28183b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 90, "max_issues_repo_issues_event_min_datetime": "2017-01-12T21:31:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T13:13:50.000Z", "max_forks_repo_path": "paper/notes/sho.jl", "max_forks_repo_name": "dfm/ess", "max_forks_repo_head_hexsha": "09ee14e516bb3bc3b517c0c1b6716eaeb28183b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 39, "max_forks_repo_forks_event_min_datetime": "2017-03-14T21:17:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T19:22:03.000Z", "avg_line_length": 33.2875, "max_line_length": 110, "alphanum_fraction": 0.6184754037, "num_tokens": 1245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541659378681, "lm_q2_score": 0.8670357615200475, "lm_q1q2_score": 0.8164478368524646}} {"text": "abstract type Dist end\r\n\r\n\r\n\"\"\"\r\n GetDistante(dist::Dist, p1::AbstractArray, p2::AbstractArray)\r\n\r\nReturns the distance \"dist\" between array \"p1\" and array \"p2\".\r\n\r\n# Examples\r\n GetDistance(Euclidean(), [2,2], [2,4])\r\n GetDistance(CityBlock(), [1, 2, 3], [4, 5, 6])\r\n\"\"\"\r\nfunction GetDistance(dist::Dist, p1::AbstractArray, p2::AbstractArray)\r\n if length(p1) != length(p2)\r\n throw(DimensionMismatch(\"Arrays with different dimensions, first array: $(length(p1)) != second array: $(length(p2)).\"))\r\n end\r\n if length(p1) == 0\r\n throw(DimensionMismatch(\"Can not calculate distance for empty arrays\"))\r\n end\r\n\r\n return calculate(dist, p1, p2)\r\nend\r\n\r\n\r\n\r\nstruct Euclidean <: Dist end\r\n\"\"\"\r\n calculate(::Euclidean, p1::AbstractArray, p2::AbstractArray)\r\n\r\nReturn the euclidean distance between arrays \"p1\" and \"p2\".\r\n\"\"\"\r\ncalculate(::Euclidean, p1::AbstractArray, p2::AbstractArray) = sqrt(sum((p1 - p2) .^ 2))\r\n\r\n\r\n\r\nstruct CityBlock <: Dist end\r\n\"\"\"\r\n calculate(::CityBlock, p1::AbstractArray, p2::AbstractArray)\r\n\r\nReturn the city block distance between arrays \"p1\" and \"p2\".\r\n\"\"\"\r\ncalculate(::CityBlock, p1::AbstractArray, p2::AbstractArray) = sum(abs.(p1 - p2))\r\n\r\n\r\n\r\nstruct TotalVariation <: Dist end\r\n\"\"\"\r\n calculate(::TotalVariation, p1::AbstractArray, p2::AbstractArray)\r\n\r\nReturn the total variation distance between arrays \"p1\" and \"p2\".\r\n\"\"\"\r\ncalculate(::TotalVariation, p1::AbstractArray, p2::AbstractArray) = sum(abs.(p1 - p2)) / 2\r\n\r\n\r\n\r\nstruct Chebyshev <: Dist end\r\n\"\"\"\r\n calculate(::Chebyshev, p1::AbstractArray, p2::AbstractArray)\r\n\r\nReturn the Chebyshev distance between arrays \"p1\" and \"p2\".\r\n\"\"\"\r\ncalculate(::Chebyshev, p1::AbstractArray, p2::AbstractArray) = maximum(abs.(p1-p2))\r\n\r\n\r\n\r\nstruct Jaccard <: Dist end\r\n\"\"\"\r\n calculate(::Jaccard, p1::AbstractArray, p2::AbstractArray)\r\n\r\nReturn the Jaccard distance between arrays \"p1\" and \"p2\".\r\n\"\"\"\r\ncalculate(::Jaccard, p1::AbstractArray, p2::AbstractArray) = 1 - sum(min(p1, p2)) / sum(max(p1,p2))\r\n\r\n\r\n\r\nstruct BrayCurtis <: Dist end\r\n\"\"\"\r\n calculate(::BrayCurtis, p1::AbstractArray, p2::AbstractArray)\r\n\r\nReturn the Bray Curtis distance between arrays \"p1\" and \"p2\".\r\n\"\"\"\r\ncalculate(::BrayCurtis, p1::AbstractArray, p2::AbstractArray) = sum(abs.(p1 - p2)) / sum(abs.(p1 + p2))\r\n\r\n\r\n\r\nstruct CosineDist <: Dist end\r\n\"\"\"\r\n calculate(::CosineDist, p1::AbstractArray, p2::AbstractArray)\r\n\r\nReturn the cosine distance between arrays \"p1\" and \"p2\".\r\n\"\"\"\r\ncalculate(::CosineDist, p1::AbstractArray, p2::AbstractArray) = 1 - sum(p1 .* p2) / ((sqrt(sum(p1 .^ 2))) * (sqrt(sum(p2 .^ 2))))\r\n\r\n\r\n\r\nstruct SpanNormDist <: Dist end\r\n\"\"\"\r\n calculate(::SpanNormDist, p1::AbstractArray, p2::AbstractArray)\r\n\r\nReturn the span-norm distance between arrays \"p1\" and \"p2\".\r\n\"\"\"\r\ncalculate(::SpanNormDist, p1::AbstractArray, p2::AbstractArray) = maximum(p1 - p2) - minimum(p1 - p2)\r\n", "meta": {"hexsha": "37e59d130067f2b2a0ea2a36e34b7656f770aad8", "size": 2892, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/dist.jl", "max_stars_repo_name": "Sergiorezende22/Distance.jl", "max_stars_repo_head_hexsha": "5d00072f506fc4ac09bc893180269ddbf78ac27b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-12T04:26:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-12T04:26:30.000Z", "max_issues_repo_path": "src/dist.jl", "max_issues_repo_name": "Sergiorezende22/Distance.jl", "max_issues_repo_head_hexsha": "5d00072f506fc4ac09bc893180269ddbf78ac27b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dist.jl", "max_forks_repo_name": "Sergiorezende22/Distance.jl", "max_forks_repo_head_hexsha": "5d00072f506fc4ac09bc893180269ddbf78ac27b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-04T00:29:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-04T00:29:51.000Z", "avg_line_length": 28.0776699029, "max_line_length": 130, "alphanum_fraction": 0.6607883817, "num_tokens": 853, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541561135442, "lm_q2_score": 0.8670357701094303, "lm_q1q2_score": 0.8164478364226525}} {"text": "# ==================================== bernoulli_numbers(nmax) =================\n\n@doc raw\"\"\"\n bernoulli_numbers(nmax [, T=Int])\n\nBernoulli numbers ``B_0,\\ \\cdots,\\ B_{nmax}`` calculated by repetative use of the recurrence relation\n```math\n B_n = - \\frac{1}{n+1}\\sum_{k=0}^{n-1}\\frac{(n+1)!}{k!(n+1-k)}B_k.\n```\nSpecial numbers: ``B_0=1,\\ B_1=-1/2,\\ B_{2n+1}=0\\ (\\rm{for}\\ n>1)``.\n### Examples:\n```\nbernoulli_numbers(10)\n11-element Vector{Rational{Int64}}:\n 1//1\n -1//2\n 1//6\n 0//1\n -1//30\n 0//1\n 1//42\n 0//1\n -1//30\n 0//1\n 5//66\n```\n\"\"\"\nfunction bernoulli_numbers(nmax::Int; T=Int)\n\n B = Base.ones(Rational{T},nmax+1)\n\n for m = 2:nmax+1\n B[m] = m > 2 ? 0//1 : -1\n if Base.isodd(m)\n b = 1\n for j = 1:m-1\n B[m] -= B[j] * b\n b *= m+1-j\n b = b÷j # binomial coefficients are integers\n end\n end\n B[m] = B[m] // m\n end\n\n return B\n\nend\nfunction bernoulli_numbers(nmax::Int) # short argument: better performance\n\n B = Base.ones(Rational{Int},nmax+1)\n\n for m = 2:nmax+1\n B[m] = m > 2 ? 0//1 : -1\n if Base.isodd(m)\n b = 1\n for j = 1:m-1\n B[m] -= B[j] * b\n b *= m+1-j\n b = b÷j # binomial coefficients are integers\n end\n end\n B[m] = B[m] // m\n end\n\n return B\n\nend\n\n# ==================================== faulhaber_polynom(p) ====================\n\n@doc raw\"\"\"\n faulhaber_polynom(p [, T=Int])\n\nVector representation of the Faulhaber polynomial of degree ``p``,\n```math\n F(n,p)=\\frac{1}{p}\\sum_{j=1}^{p}{\\binom {p}{p-j}}B_{p-j}n^{j}.\n```\n``F(n,p)=`` `polynom(c,n)`, where ``c=[c_0,\\cdots,\\ c_p]`` is the coefficient vector, with\n```math\n c_0=0,\\ c_j=\\frac{1}{p}{\\binom {p}{p-j}}B_{p-j},\n```\nwith ``j∈\\{ 1,\\cdots,\\ p\\}``. The ``B_0,\\cdots,\\ B_{p-1}`` are Bernoulli numbers\n(but with ``B_1=+\\frac{1}{2}`` rather than ``-\\frac{1}{2}``).\n### Example:\n```\nfaulhaber_polynom(6)\n7-element Vector{Rational{Int64}}:\n 0//1\n 0//1\n -1//12\n 0//1\n 5//12\n 1//2\n 1//6\n```\n\"\"\"\nfunction faulhaber_polynom(k::Int; T=Int)\n\n k < 1 && return 0\n k > 1 || return 1//1\n\n P = CamiXon.pascal_triangle(k; T)[end][1:end-1]\n B = CamiXon.bernoulli_numbers(k-1; T); B[2]=-B[2]\n\n F = (B .* P) // k\n\n F = Base.append!(F,0//1) # add polynomial constant (zero in this case)\n\n return Base.reverse(F) # reverse to standard order\n\nend\nfunction faulhaber_polynom(k::Int) # short argument: better performance\n\n k < 1 && return 0\n k > 1 || return 1//1\n\n P = CamiXon.pascal_triangle(k)[end][1:end-1]\n B = CamiXon.bernoulli_numbers(k-1); B[2]=-B[2]\n\n F = (B .* P) // k\n\n F = Base.append!(F,0//1) # add polynomial constant (zero in this case)\n\n return Base.reverse(F) # reverse to standard order\n\nend\n\n# =================================== faulhaber_summation(n,p;T) ===============\n\n@doc raw\"\"\"\n faulhaber_summation(n, p [, T=Int])\n\nSum of powers of natural numbers ``1,\\ \\cdots,\\ n``,\n```math\n FS(n,p)=\\sum_{k=1}^{n}k^{p}=F(n,p+1).\n```\nwhere ``F(n,p)`` is the Faulhamer polynomial of degree ``p``.\n### Examples:\n```\nfaulhaber_summation(5,1)\n 15\n\nfaulhaber_summation(3,60; T=BigInt)\n 42391158276369125018901280178\n```\n\"\"\"\nfunction faulhaber_summation(n::Int, p::Int; T=Int)\n\n n ≠ 0 || return nothing\n\n F = CamiXon.faulhaber_polynom(p+1; T)\n o = 0\n for k=1:p+1\n for i=1:k\n F[k+1] *= n # avoid n^k in o = Base.sum([F[k+1]*n^k for k=1:p+1])\n end\n o += F[k+1]\n end\n\n Base.denominator(o) == 1 || error(\"jwError: Faulhaber sum failed\")\n\n return Base.numerator(o)\n\nend\nfunction faulhaber_summation(n::Int, p::Int) # short argument: better performance\n\n n ≠ 0 || return 0\n\n F = CamiXon.faulhaber_polynom(p+1)\n o = 0\n for k=1:p+1\n for i=1:k\n F[k+1] *= n # avoid n^k in o = Base.sum([F[k+1]*n^k for k=1:p+1])\n end\n o += F[k+1]\n end\n\n Base.denominator(o) == 1 || error(\"jwError: Faulhaber sum failed\")\n\n return Base.numerator(o)\n\nend\n\n# =================================== harmonic number(n;T) ===============\n\n@doc raw\"\"\"\n harmonic_number(n [, T=Int])\n\nSum of the reciprocals of the first ``n`` natural numbers\n```math\n H_n=\\sum_{k=1}^{n}\\frac{1}{k}.\n```\n### Examples:\n```\no = [harmonic_number(i) for i=1:10]; println(o)\n [1//1, 3//2, 11//6, 25//12, 137//60, 49//20, 363//140, 761//280, 7129//2520, 7381//2520]\n\nharmonic_number(60; T=BigInt)\n 15117092380124150817026911//3230237388259077233637600\n\nharmonic_number(12) == harmonic_number(12, 1)\n true\n```\n\"\"\"\nfunction harmonic_number(n::Int; T=Int)\n\n n ≠ 0 || return 0\n\n o::Base.Rational{T} = 0//1\n for j=1:n\n o += 1//j\n end\n\n return o\n\nend\nfunction harmonic_number(n::Int) # short argument: better performance\n\n n ≠ 0 || return 0\n\n o = 0//1\n for j=1:n\n o += 1//j\n end\n\n return o\n\nend\n\n\n\n# =================================== harmonic number(n, p;T) ===============\n\n@doc raw\"\"\"\n harmonic_number(n, p [, T=Int])\n\nSum of the ``p_{th}`` power of reciprocals of the first ``n`` numbers\n```math\n H_{n,p}=\\sum_{k=1}^{n}\\frac{1}{k^p}.\n```\n### Examples:\n```\nharmonic_number(12, 3)\n 25535765062457//21300003648000\n\nharmonic_number(12, 5; T=BigInt)\n 16971114472329088045481//16366888723117363200000\n\nharmonic_number(12, -3) == faulhaber_summation(12, 3)\n true\n```\n\"\"\"\nfunction harmonic_number(n::Int, p::Int; T=Int)\n\n n ≠ 0 || return 0\n\n if p > 0\n o::Base.Rational{T} = 0//1\n for j=1:n\n a = 1\n for i=1:p\n a *= j\n end\n o += 1//a\n end\n else\n p = -p\n F = CamiXon.faulhaber_polynom(p+1; T)\n o = 0\n for k=1:p+1\n for i=1:k\n F[k+1] *= n\n end\n o += F[k+1]\n end\n Base.denominator(o) == 1 || error(\"jwError: Faulhaber sum failed\")\n o = Base.numerator(o)\n end\n\n return o\n\nend\nfunction harmonic_number(n::Int, p::Int) # short argument: better performance\n\n n ≠ 0 || return 0\n\n if p > 0\n o = 0//1\n for j=1:n\n a = 1\n for i=1:p\n a *= j\n end\n o += 1//a\n end\n else\n p = -p\n F = CamiXon.faulhaber_polynom(p+1)\n o = 0\n for k=1:p+1\n for i=1:k\n F[k+1] *= n\n end\n o += F[k+1]\n end\n Base.denominator(o) == 1 || error(\"jwError: Faulhaber sum failed\")\n o = Base.numerator(o)\n end\n\n return o\n\nend\n\n# ==================================== _canonical_partition(n, m) =======================\n\nfunction _canonical_partition(n::Int, m::Int)\n\n o = Base.fill(m,Base.cld(n,m)) # init partition\n o[Base.cld(n,m)]=((n%m)≠0 ? n%m : m) # adjust last element of partition\n\n return o\n\nend\n\n\"\"\"\n canonical_partitions(n; header=false, reverse=true)\n\nThe canonical partition in integers of the integer n\n\nheader=true : unit patition included in output\n#### Examples:\n```\ncanonical_partitions(6; header=true, reverse=false)\n6-element Array{Array{Int64,1},1}:\n [6]\n [5, 1]\n [4, 2]\n [3, 3]\n [2, 2, 2]\n [1, 1, 1, 1, 1, 1]\n\ncanonical_partitions(6; header=true)\n6-element Array{Array{Int64,1},1}:\n [1, 1, 1, 1, 1, 1]\n [2, 2, 2]\n [3, 3]\n [4, 2]\n [5, 1]\n [6]\n\ncanonical_partitions(6)\n5-element Array{Array{Int64,1},1}:\n [1, 1, 1, 1, 1, 1]\n [2, 2, 2]\n [3, 3]\n [4, 2]\n [5, 1]\n```\n\"\"\"\nfunction canonical_partitions(n::Int, m=0; header=true, reverse=true)\n\n h = header ? n : n-1\n\n if m == 0\n if reverse\n o = [_canonical_partition(n,m) for m=1:h]\n else\n o = [_canonical_partition(n,m) for m=h:-1:1]\n end\n elseif 0 < m <= n\n o = _canonical_partition(n,m)\n else\n o = nothing\n end\n\n return o\n\nend\n\n\n\nfunction _partition_count(n::Int,k::Int)\n\n (n<0)|(k<0)|(k>n) ? 0 : (k==n)|(k==1) ? 1 : _partition_count(n-k,k) + _partition_count(n-1,k-1)\n\nend\n\nfunction _partition(a::Array{Int,1}, n::Int, i::Int, cp::Array{Array{Array{Int,1},1},1})\n\n o = a[1:i-1]\n m = a[i]-1 # m: partition value\n ni = n - Base.sum(o) # ni: sub-partition index at partition index i\n\n Base.append!(o,cp[ni][m]) # complete partition by appending it to a\n\n return o\n\nend\n\nfunction _restricted_partitions(o::Array{Int,1}, n::Int, np::Int, cp::Array{Array{Array{Int,1},1},1})\n\n oo = [o]\n\n for p=1:np-1\n i = Base.findlast(x -> x > 1, oo[p])\n Base.append!(oo,[_partition(oo[p],n,i,cp)])\n end\n\n return oo\n\nend\n\n\"\"\"\n integer_partitions(n [,m]; transpose=false, count=false)\n\ndefault : The integer partitions of n\n\ncount=true : The number of integer partitions of n\n\ntranspose=false/true : for m>0 restricted to partitions with maximum part/length m\n\ndefinitions:\n\nThe integer partition of the positive integer n is a nonincreasing sequence of positive integers p1, p2,... pk whose sum is n.\n\nThe elements of the sequence are called the parts of the partition.\n#### Examples:\n```\ninteger_partitions(7)\n15-element Array{Array{Int64,1},1}:\n [1, 1, 1, 1, 1, 1, 1]\n [2, 2, 2, 1]\n [3, 3, 1]\n [4, 3]\n [5, 2]\n [6, 1]\n [7]\n [2, 2, 1, 1, 1]\n [3, 2, 2]\n [4, 2, 1]\n [5, 1, 1]\n [2, 1, 1, 1, 1, 1]\n [3, 2, 1, 1]\n [4, 1, 1, 1]\n [3, 1, 1, 1, 1]\n\ninteger_partitions(7; count=true)\n15\n\ninteger_partitions(7,4; count=true)\n3\n\ninteger_partitions(7,4)\n3-element Array{Array{Int64,1},1}:\n [4, 3]\n [4, 2, 1]\n [4, 1, 1, 1]\n\ninteger_partitions(7,4; transpose=true)\n3-element Array{Array{Int64,1},1}:\n [2, 2, 2, 1]\n [3, 2, 1, 1]\n [4, 1, 1, 1]\n```\n\"\"\"\nfunction integer_partitions(n::Int, m=0; transpose=false, count=false)\n\n cp = [canonical_partitions(m) for m=1:n]\n pc = [_partition_count(n,m) for m=1:n]\n oo = [ones(Int,n)]\n\n np = m > 0 ? pc[m] : sum(pc)\n\n if !count\n\n if m == 0\n o = [_restricted_partitions(cp[n][p],n,pc[p],cp) for p=2:n]\n for p=1:n-1 append!(oo,o[p]) end\n else\n oo = _restricted_partitions(cp[n][m],n,pc[m],cp)\n end\n\n if transpose\n for p=1:np\n l = length(oo[p])\n s=max(oo[p][1],l)\n mat = zeros(Int,s,s)\n for j=1:l for i=1:oo[p][j] mat[i,j]=1 end end\n oo[p] = [sum(mat[i,:]) for i=1:oo[p][1]]\n end\n\n end\n\n end\n\n return count ? np : oo\n\nend\n\n# ===================================== log10_characteristic_power(x) ==============================================\n\"\"\"\n log10_characteristic_power(x)\n\ncharacteristic power-of-10 of the number x\n#### Examples:\n```\nlog10_characteristic_power.([3,30,300])\n3-element Vector{Int64}:\n 0\n 1\n 2\n```\n\"\"\"\nlog10_characteristic_power(x) = Base.round(Int,Base.floor(log10(x)))\n\n# ==================================== log10_mantissa(x) ============================================================\n\"\"\"\n log10_mantissa(x)\n\nlog10 mantissa of the number x\n#### Examples:\n```\nlog10_mantissa.([3,30,300])\n3-element Vector{Float64}:\n 0.47712125471966244\n 0.4771212547196624\n 0.4771212547196626\n```\n\"\"\"\nlog10_mantissa(x) = Base.log10(x)-Base.floor(Base.log10(x))\n\n# ==================================== pascal_triangle(nmax) ============\n\n@doc raw\"\"\"\n pascal_triangle(nmax [, T=Int])\n\nPascal triangle of binomial coefficients ``\\binom{n}{k}`` for ``n=0,\\ 1,\\ \\cdots,\\ nmax``\n### Example:\n```\npascal_triangle(5)\n6-element Vector{Vector{Int64}}:\n [1]\n [1, 1]\n [1, 2, 1]\n [1, 3, 3, 1]\n [1, 4, 6, 4, 1]\n [1, 5, 10, 10, 5, 1]\n```\n\"\"\"\nfunction pascal_triangle(nmax::Int; T=Int)\n\n nmax < 0 && error(\"jwError: nmax must be a non-negative integer\")\n\n o = [Base.ones(T,n+1) for n=0:nmax]\n\n for n=2:nmax\n for k=1:n÷2\n o[n+1][k+1] = o[n][k+1] + o[n][k]\n o[n+1][n+1-k] = o[n+1][k+1]\n end\n end\n\n return o\n\nend\nfunction pascal_triangle(nmax::Int)\n\n nmax < 0 && error(\"jwError: nmax must be a non-negative integer\")\n\n o = [Base.ones(Int,n+1) for n=0:nmax]\n\n for n=2:nmax\n for k=1:n÷2\n o[n+1][k+1] = o[n][k+1] + o[n][k]\n o[n+1][n+1-k] = o[n+1][k+1]\n end\n end\n\n return o\n\nend\n\n# ==================================== pascal_next(nmax) ============\n\n@doc raw\"\"\"\n pascal_next(nmax)\n\nNext row of Pascal triangle\n### Example:\n```\na = [1, 4, 6, 4, 1]\npascal_next(a)\n [1, 5, 10, 10, 5, 1]\n```\n\"\"\"\nfunction pascal_next(a::Vector{Int})\n\n n = Base.length(a) + 1\n o = Base.ones(Int,n)\n\n for k=1:n÷2\n o[k+1] = a[k+1] + a[k]\n o[n-k] = o[k+1]\n end\n\n return o\n\nend\n\n# ==================================== permutations_unique_count(p, i) =======================\n\n@doc raw\"\"\"\n permutations_unique_count(p::Array{Array{Int64,1},1}, i::Int)\n\nNumber of unique permutations of the subarray ``p[i]``.\n#### Example:\n```\np = [[1,2,3],[2,3,1,4,3]]\npermutations_unique_count(p,2)\n 60\n```\n\"\"\"\nfunction permutations_unique_count(p::Array{Array{Int64,1},1}, i::Int)\n\n o = Base.factorial(Base.length(p[i]))\n d = Base.Dict([(n,Base.count(x->x==n,p[i])) for n ∈ Base.unique(p[i])])\n\n for j ∈ Base.eachindex(Base.unique(p[i]))\n o = o ÷ Base.factorial(d[Base.unique(p[i])[j]])\n end\n\n return o\n\nend\n\n# ==================================== polynom(c,x) ============================================================\n\n@doc raw\"\"\"\n polynom(coords,x)\n\nMethod to evaluate the function ``f(x)=polynom(c,x)``, where\n``c=[c_0,\\ \\ldots,\\ c_d]`` is the vector representation of a polynomial of degree ``d``.\n```math\n p(c,x)=c_0 + c_1 x + \\cdots + c_d x^d.\n```\n### Examples:\n```\ncoords = ones(6) # for polynomial of degree 5 with unit coefficients\nf(x) = polynom(coords,x)\nprintln([f(1.0),f(2.0)]) # values of polynomial for x = 1.0 and x = 2.0\n [6.0, 63.0]\n```\n\"\"\"\nfunction polynom(coords::Vector{T}, x::T) where T<:Number\n\n k = Base.length(coords)\n X = Base.ones(T,k)\n\n for i=2:k\n X[i] = X[i-1] * x\n end\n\n return LinearAlgebra.dot(coords, X)\n\nend\n\n# ==================================== polynom_derivative(coords) ==============\n\n@doc raw\"\"\"\n polynom_derivative(coords)\n\nVector representation of the first derivative of the polynomial `coords`,\n```math\n p'(c,x)=c_1 + 2 c_2 x + \\cdots + d c_d x^{d-1},\n```\nPolynomials of degree ``d`` are represented by a vector in a vector space of dimension ``d+1``.\nThe polynomial `coords` is specified by the coordinates vector ``c=[c_0,\\ \\ldots,\\ c_d]``\nconsisting of the polynomial coefficients.\n### Examples:\n```\ncoords=[1,1,1,1,1] # vector representation of polynomial of degree d=4\npolynom_derivative(coords) # (first) derivative of polynomial `coords`\n4-element Vector{Int64}:\n 1\n 2\n 3\n 4\n```\n\"\"\"\nfunction polynom_derivative(coords::Vector{<:Number})\n\n k = Base.length(coords)\n k > 1 || return [0]\n\n return coords[2:end] .* Base.OneTo(k-1)\n\nend\n\n# =============================== polynom_derivative(coords[,deriv=0]) =========\n\n@doc raw\"\"\"\n polynom_derivatives(coords[,deriv=0])\n\nVector representation of derivatives of the polynomial `coords`.\n\nPolynomials of degree ``d`` are represented by a vector in a vector space of dimension ``d+1``.\nThe polynomial `coords` is specified by the coordinates vector ``c=[c_0,\\ \\ldots,\\ c_d]``\nconsisting of the polynomial coefficients.\n\n`deriv`: derivative of choice; `default`: collection of all (nontrivial) derivatives.\n\n### Examples:\n```\ncoords=[1,1,1,1,1] # vector representation of a polynomial of degree d=4\npolynom_derivatives(coords) # `all' (nontrivial) derivatives of polynomial `coords`\n5-element Vector{Vector{Int64}}:\n [1, 2, 3, 4]\n [2, 6, 12]\n [6, 24]\n [24]\n [0]\n\npolynom_derivatives(coords; deriv=2) # second derivative of polynomial `coords`\n3-element Vector{Int64}:\n 2\n 6\n 12\n```\n\"\"\"\nfunction polynom_derivatives(coords::Vector{<:Number}; deriv=0)\n\n deriv < 0 && error(\"jwError: negative derivative not defined\")\n\n k = deriv > 0 ? deriv+1 : Base.length(coords)\n\n coords = CamiXon.polynom_derivative(coords)\n\n deriv ≠ 1 ? o = [coords] : return coords\n\n for i=2:k-1\n coords = polynom_derivative(coords)\n Base.push!(o,coords)\n end\n\n deriv == 0 ? Base.push!(o,[0]) : return o[deriv]\n\n return o\n\nend\n\n# ==================================== polynom_power(coords, p) ================\n\n@doc raw\"\"\"\n polynom_power(coords, p)\n\nVector representation of the polynomial `coords` raised to the power `p` which\nresults in a polynomial in a vector space of dimension ``p d + 1``.\n\nPolynomials of degree ``d`` are represented by a vector in a vector space of dimension ``d+1``.\nThe polynomial `coords` is specified by the coordinates vector ``c=[c_0,\\ \\ldots,\\ c_d]``\nconsisting of the polynomial coefficients.\n### Examples:\n```\ncoords=[1,1,1] # vector representation of polynomial of degree ``d=2``\npolynom_power(coords,2)\n5-element Vector{Int64}:\n 1\n 2\n 3\n 2\n 1\n```\n\"\"\"\nfunction polynom_power(coords::Vector{<:Number}, power::Int)\n\n power >= 0 || error(\"jwError: negative powers not allowed\")\n power == 2 && return polynom_product(coords, coords)\n power == 1 && return coords\n power == 0 && return [1]\n\n o = CamiXon.polynom_product(coords, coords)\n\n for i=1:power-2\n o = CamiXon.polynom_product(o, coords)\n end\n\n return o\n\nend\n\n# ==================================== polynom_powers(coords, pmax) ============\n\n@doc raw\"\"\"\n polynom_powers(coords, pmax)\n\nThe polynomial `coords` raised to the powers 1,...,pmax which\nresults in a collection of polynomials in vector spaces of dimension ``d+1`` tot ``p d + 1``.\n\nPolynomials of degree ``d`` are represented by a vector in a vector space of dimension ``d+1``.\nThe polynomial `coords` is specified by the coordinates vector ``c=[c_0,\\ \\ldots,\\ c_d]``\nconsisting of the polynomial coefficients.\n### Examples:\n```\ncoords=[1,1,1] # vector representation of polynomial of degree d=2\npolynom_powers(coords,3)\n3-element Vector{Vector{Int64}}:\n [1, 1, 1]\n [1, 2, 3, 2, 1]\n [1, 3, 6, 7, 6, 3, 1]\n```\n\"\"\"\nfunction polynom_powers(coords::Vector{<:Number}, pmax::Int)\n\n pmax > 0 || error(\"jwError: minimum power included is unity\")\n\n o = [coords]\n\n for i=1:pmax-1\n Base.push!(o,CamiXon.polynom_product(o[end], coords))\n end\n\n return o\n\nend\n\n# ==================================== polynom_primitive(coords) ====================\n\n@doc raw\"\"\"\n polynom_primitive(coords)\n\nVector representation of the primitive of the polynomial `coords` which is a\npolynomial in a vector space of dimension ``p d + 1``.\n```math\n P(c,x)=c_{int} +c_0 x + \\frac{1}{2} c_1 x^2 + \\frac{1}{3} c_2 x^3 + \\cdots + \\frac{1}{d+1} c_d x^{d+1},\n```\nThe constant of integration is set to zero, ``c_{int} = 0``.\n\nPolynomials of degree ``d`` are represented by a vector in a vector space of dimension ``d+1``.\nThe polynomial `coords` is specified by the coordinates vector ``c=[c_0,\\ \\ldots,\\ c_d]``\nconsisting of the polynomial coefficients.\n### Examples:\n```\ncoords=[1,1,1,1,1] # vector representation of polynomial of degree ``d=4``\npolynom_primitive(coords)\n6-element Vector{Rational{Int64}}:\n 0//1\n 1//1\n 1//2\n 1//3\n 1//4\n 1//5\n```\n\"\"\"\nfunction polynom_primitive(coords::Vector{<:Number})\n\n d = [1//p for p ∈ Base.eachindex(coords)]\n\n coords = coords .* d\n\n return Base.pushfirst!(coords,0) # constant of integration equal to zero\n\nend\n\n# ==================================== polynom_product(a, b) ============================================================\n\n@doc raw\"\"\"\n polynom_product(a::Vector{<:Number}, b::Vector{<:Number})\n\nVector representation of the product of two polynomials, ``a`` and ``b`` which\nis a polynomial in a vector space of dimension ``d=m+n``,\n```math\n p(c,x)=a_0b_0 + (a_0b_1 + b_0a_1)x + \\cdots + a_n b_m x^{n+m}.\n```\nPolynomials of degree ``d`` are represented by a vector in a vector space of dimension ``d+1``\nThe polynomial `coords` is specified by the coordinates vector ``c=[c_0,\\ \\ldots,\\ c_d]``\nconsisting of the polynomial coefficients.\n####\n```\na = [1,1]\nb = [1,- 1]\no = polynomial_product(a, b); println(o)\n [1, 0, -1]\n```\n\"\"\"\nfunction polynom_product(a::Vector{<:Number}, b::Vector{<:Number})\n\n n = Base.length(a)\n m = Base.length(b)\n\n if m ≥ n\n o = [Base.sum(a[1+j-i]*b[1+i] for i=0:j) for j=0:n-1]\n if m≠n Base.append!(o,[Base.sum(a[n-i]*b[1+i+j] for i=0:n-1) for j=1:m-n]) end\n Base.append!(o,[Base.sum(a[n-i]*b[1+i+j+m-n] for i=0:n-1-j) for j=1:n-1])\n else\n o = [Base.sum(b[1+j-i]*a[1+i] for i=0:j) for j=0:m-1]\n if m≠n Base.append!(o,[Base.sum(b[m-i]*a[1+i+j] for i=0:m-1) for j=1:n-m]) end\n Base.append!(o,[Base.sum(b[m-i]*a[1+i+j+n-m] for i=0:m-1-j) for j=1:m-1])\n end\n\n return o\n\nend\n\n# ==================================== polynom_product_expansion(a, b, p) ============================================================\n\n@doc raw\"\"\"\n polynom_product_expansion(a::Vector{<:Number}, b::Vector{<:Number}, p::Int)\n\nVector representation of the product of two polynomials, ``a`` (of degree ``n``) and ``b`` (of degree ``m``), with ``m≤n``\ntruncated at the order ``p`` is a polynomial in a vector space of dimension ``d=p+1``. If ``ab`` is the `polynom_product`,\nthe `polynom_product_expansion` is ``ab[1:p+1]``\n####\n```\na = [1,-1,1]\nb = [1,1,-1,1,1,1]\no = polynom_product(a, b); println(o)\n [1, 0, -1, 3, -1, 1, 0, 1]\n\no = expand_product(a, b, 4); println(o)\n [1, 0, -1, 3, -1]\n\n```\n\"\"\"\nfunction polynom_product_expansion(a::Vector{<:Number}, b::Vector{<:Number}, p::Int)\n\n n = Base.length(a)\n m = Base.length(b)\n\n if m ≥ n\n o = [Base.sum(a[1+j-i]*b[1+i] for i=0:j) for j=0:min(n-1,p)]\n p+1 == length(o) && return o\n if m≠n Base.append!(o,[Base.sum(a[n-i]*b[1+i+j] for i=0:n-1) for j=1:min(m-n,p-n+1)]) end\n p+1 == length(o) && return o\n Base.append!(o,[Base.sum(a[n-i]*b[1+i+j+m-n] for i=0:n-1-j) for j=1:min(n-1,p-m+1)])\n p+1 == length(o) && return o\n else\n o = [Base.sum(b[1+j-i]*a[1+i] for i=0:j) for j=0:min(m-1,p)]\n p+1 == length(o) && return o\n Base.append!(o,[Base.sum(b[m-i]*a[1+i+j] for i=0:m-1) for j=1:min(n-m,p-m+1)])\n p+1 == length(o) && return o\n Base.append!(o,[Base.sum(b[m-i]*a[1+i+j+n-m] for i=0:m-1-j) for j=1:min(m-1,p-n+1)])\n p+1 == length(o) && return o\n end\n\n return o\n\nend\n\n# ...................................................... VectorRational .........................................................\n\n@doc raw\"\"\"\n VectorRational\n\nObject to decompose a vector of rational numbers\n\nThe fields are:\n* `.num::Vector{Int}``: vector of normalized numerators\n* `.den::Int`: common denominator\n* `.val::Vector{Rational}`: vector of rational numbers (simplified = not normalized)\n\"\"\"\nstruct VectorRational\n\n num::Vector{Int}\n den::Int\n val::Vector{Rational{Int64}}\n\nend\n\n# ==================================== analyzeVectorRational(vec) =======================\n\n@doc raw\"\"\"\n normalize_VectorRational(vec::Vector{Rational{Int}})\n\nDecompose vector of rational numbers.\n#### Example:\n```\nv = [2//3,4//5]\nnormalize_VectorRational(v)\n VectorRational([10, 12], 15, Rational{Int64}[2//3, 4//5])\n```\n\"\"\"\nfunction normalize_VectorRational(vec::Vector{Rational{Int}})\n\n val = Base.gcd(vec)\n den = val.den\n num = Base.convert(Vector{Int},(vec .* den))\n\n return CamiXon.VectorRational(num, den, vec)\n\nend\n", "meta": {"hexsha": "9f0bf729058a9688dee01c6d4e6784bf81b23e59", "size": 23606, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mathematics.jl", "max_stars_repo_name": "walra356/CamiXon", "max_stars_repo_head_hexsha": "55692d1a98f2d39bfe606ac3818e403f50346492", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mathematics.jl", "max_issues_repo_name": "walra356/CamiXon", "max_issues_repo_head_hexsha": "55692d1a98f2d39bfe606ac3818e403f50346492", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mathematics.jl", "max_forks_repo_name": "walra356/CamiXon", "max_forks_repo_head_hexsha": "55692d1a98f2d39bfe606ac3818e403f50346492", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8203834511, "max_line_length": 134, "alphanum_fraction": 0.5462170635, "num_tokens": 7828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541577509316, "lm_q2_score": 0.8670357683915538, "lm_q1q2_score": 0.8164478362246804}} {"text": "\"\"\"\n decasteljau(control, t)\n\nEvaluate de Casteljau's algorithm.\n\"\"\"\nfunction decasteljau(control::AbstractArray{T,2}, t::T) where {T<:AbstractFloat}\n n = size(control, 2) - 1\n β = zeros(size(control, 1), n+1, n+1)\n @inbounds β[:,:,1] = control\n for j = 2:n+1, i = 1:n-j+2\n @inbounds β[:,i,j] = β[:,i,j-1]*(1-t) + β[:,i+1,j-1]*t\n end\n β\nend\n\n\"\"\"\n subdivide(control, t)\n\nSubdivide a Bezier curve using de Casteljau's algorithm.\n\"\"\"\nfunction subdivide(control::AbstractArray{T,2}, t::T) where {T<:AbstractFloat}\n β = decasteljau(control, t)\n β₁ = β[:,1,:]\n β₂ = zeros(control)\n n = size(control, 2) - 1\n for i = 1:n+1\n @inbounds β₂[:,i] = β[:,i,n-i+2]\n end\n β₁, β₂\nend\n", "meta": {"hexsha": "cd963db109f7e946600e87302d25d29e7b3b5ed2", "size": 726, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/subdivide.jl", "max_stars_repo_name": "arlk/Bezier.jl", "max_stars_repo_head_hexsha": "308e376c83bd419870083df4b1891e994c712dc0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-07T00:00:42.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-07T00:00:42.000Z", "max_issues_repo_path": "src/subdivide.jl", "max_issues_repo_name": "arlk/Bezier.jl", "max_issues_repo_head_hexsha": "308e376c83bd419870083df4b1891e994c712dc0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/subdivide.jl", "max_forks_repo_name": "arlk/Bezier.jl", "max_forks_repo_head_hexsha": "308e376c83bd419870083df4b1891e994c712dc0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4193548387, "max_line_length": 80, "alphanum_fraction": 0.5702479339, "num_tokens": 276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541561135442, "lm_q2_score": 0.8670357512127872, "lm_q1q2_score": 0.81644781862855}} {"text": "using CSV, Distributions, HypothesisTests\n\ndata = CSV.read(\"../data/machine1.csv\", header=false)[:,1]\nxBar, n = mean(data), length(data)\nsigma = 1.2\nmu0A, mu0B = 52.2, 53\n\ntestStatistic = ( xBar - mu0A ) / ( sigma/sqrt(n) )\npVal = 2*ccdf(Normal(), abs(testStatistic))\n\ntestA = OneSampleZTest(xBar, sigma, n, mu0A)\ntestB = OneSampleZTest(xBar, sigma, n, mu0B)\n\nprintln(\"Results for mu0 = \", mu0A,\":\")\nprintln(\"Manually calculated test statistic: \", testStatistic)\nprintln(\"Manually calculated p-value: \", pVal,\"\\n\")\nprintln(testA)\n\nprintln(\"\\n In case of mu0 = \", mu0B, \" then p-value = \", pvalue(testB))\n", "meta": {"hexsha": "48b67912c48a61cc86d3a08a768f7572c8632cc9", "size": 605, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "7_chapter/infMeanSingleVarKnown.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/infMeanSingleVarKnown.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/infMeanSingleVarKnown.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.25, "max_line_length": 73, "alphanum_fraction": 0.6809917355, "num_tokens": 202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.95598134762883, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.8163246661012469}} {"text": "module GeoMapping\n\nexport distance, azimuth, reckon\n\n\"\"\"\n d = distance(lat1,lon1,lat2,lon2)\n\nCompute the great-circle distance between the points (`lat1`,`lon1`) and (`lat2`,`lon2`).\nThe units of all input and output parameters are degrees.\n\"\"\"\nfunction distance(lat1,lon1,lat2,lon2)\n #https://en.wikipedia.org/w/index.php?title=Great-circle_distance&oldid=749078136#Computational_formulas\n\n Δλ = π/180 * (lon2 - lon1)\n ϕ1 = π/180 * lat1\n ϕ2 = π/180 * lat2\n\n cosΔσ = sin(ϕ1)*sin(ϕ2) + cos(ϕ1)*cos(ϕ2)*cos(Δλ)\n\n eins = one(cosΔσ)\n cosΔσ = max(min(cosΔσ,eins),-eins)\n Δσ = acos(cosΔσ)\n return 180/π * Δσ\nend\n\n\"\"\"\n az = azimuth(lat1,lon1,lat2,lon2)\n\nCompute azimuth, i.e. the angle between the line segment defined by the points (`lat1`,`lon1`) and (`lat2`,`lon2`)\nand the North.\nThe units of all input and output parameters are degrees.\n\"\"\"\nfunction azimuth(lat1,lon1,lat2,lon2)\n # https://en.wikipedia.org/w/index.php?title=Azimuth&oldid=750059816#Calculating_azimuth\n\n Δλ = π/180 * (lon2 - lon1)\n ϕ1 = π/180 * lat1\n ϕ2 = π/180 * lat2\n\n α = atan(sin(Δλ), cos(ϕ1)*tan(ϕ2) - sin(ϕ1)*cos(Δλ))\n return 180/π * α\nend\n\n# Base on reckon from myself\n# https://sourceforge.net/p/octave/mapping/ci/3f19801d4b93d3b3923df9fa62d268660e5cb4fa/tree/inst/reckon.m\n# relicenced to LGPL-v3\n\n\"\"\"\n lato,lono = reckon(lat,lon,range,azimuth)\n\nCompute the coordinates of the end-point of a displacement on a\nsphere. `lat`,`lon` are the coordinates of the starting point, `range`\nis the covered distance of the displacements along a great circle and\n`azimuth` is the direction of the displacement relative to the North.\nThe units of all input and output parameters are degrees.\nThis function can also be used to define a spherical coordinate system\nwith rotated poles.\n\"\"\"\nfunction reckon(lat,lon,range,azimuth)\n\n # convert to radian\n rad2deg = π/180\n\n lat = lat*rad2deg\n lon = lon*rad2deg\n range = range*rad2deg\n azimuth = azimuth*rad2deg\n\n tmp = sin.(lat).*cos.(range) + cos.(lat).*sin.(range).*cos.(azimuth)\n\n # clip tmp to -1 and 1\n eins = one(eltype(tmp))\n tmp = max.(min.(tmp,eins),-eins)\n\n lato = π/2 .- acos.(tmp)\n\n cos_γ = (cos.(range) - sin.(lato).*sin.(lat))./(cos.(lato).*cos.(lat))\n sin_γ = sin.(azimuth).*sin.(range)./cos.(lato)\n\n γ = atan.(sin_γ,cos_γ)\n\n lono = lon .+ γ\n\n # bring the lono in the interval [-π π[\n\n lono = mod.(lono .+ π,2*π) .- π\n\n # convert to degrees\n\n lono = lono/rad2deg\n lato = lato/rad2deg\n\n return lato,lono\nend\n\n\n\n\nend\n", "meta": {"hexsha": "97f627b5df62af56bb0dcef77c476160f238199e", "size": 2551, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/GeoMapping.jl", "max_stars_repo_name": "rctngle/OpenWeatherDecoder", "max_stars_repo_head_hexsha": "84629817da31522c5dffc66ad28c320de51274f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-09-24T23:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T19:12:45.000Z", "max_issues_repo_path": "src/GeoMapping.jl", "max_issues_repo_name": "rctngle/OpenWeatherDecoder", "max_issues_repo_head_hexsha": "84629817da31522c5dffc66ad28c320de51274f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-09-08T10:09:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-14T09:32:26.000Z", "max_forks_repo_path": "src/GeoMapping.jl", "max_forks_repo_name": "rctngle/OpenWeatherDecoder", "max_forks_repo_head_hexsha": "84629817da31522c5dffc66ad28c320de51274f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-16T23:01:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-16T23:01:56.000Z", "avg_line_length": 25.51, "max_line_length": 114, "alphanum_fraction": 0.6667973344, "num_tokens": 867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731126558705, "lm_q2_score": 0.8479677602988601, "lm_q1q2_score": 0.8163157632387308}} {"text": "\"\"\"\n M_Einasto(r, rs, rhos, alpha)\n\nCompute the enclosed mass for Einasto model.\n\n* `r`: radii in kpc\n* `rs`: scale radius in kpc\n* `rhos`: scale density in Msun / kpc3\n* `alpha`: Einasto shape index, lower is more cored\n\"\"\"\nfunction M_Einasto(r, rs, rhos, alpha)\n x = r / rs\n M = (4π * rhos * rs *\n exp(2.0 / alpha) * gamma(3.0 / alpha) * (2.0 / alpha) ^ (-3.0 / alpha))\n return @. M * gamma_inc(3.0 / alpha, 2.0 / alpha * x ^ alpha)\nend\n\n\"\"\"\n rho_Einasto(r, rs, rhos, alpha)\n\nCompute the local volume density for Einasto model.\n\n* `r`: radii in kpc\n* `rs`: scale radius in kpc\n* `rhos`: scale density in Msun / kpc3\n* `alpha`: Einasto shape index, lower is more cored\n\"\"\"\nfunction rho_Einasto(r, rs, rhos, alpha)\n x = r / rs\n return @. rhos * exp(- 2.0 / alpha * (x^alpha - 1.0))\nend\n\n\"\"\"\n EinastoModel(rs, rhos, alpha)\n\nEinasto halo model\n\n- [Einasto 1965](http://adsabs.harvard.edu/abs/1965TrAlm...5...87E)\n\n* `rs`: scale radius in kpc\n* `rhos`: scale density in Msun / kpc3\n* `alpha`: Einasto shape index, lower is more cored\n\"\"\"\nstruct EinastoModel <: HaloModel\n rs::Float64\n rhos::Float64\n alpha::Float64\nend\n\n# default to 1e12 Mvir / Msun halo\nEinastoModel() = EinastoModel(25.3, 8.4e5, 0.16)\ndensity(halo::EinastoModel, r) = rho_Einasto(r, halo.rs, halo.rhos, halo.alpha)\nmass(halo::EinastoModel, r) = M_Einasto(r, halo.rs, halo.rhos, halo.alpha)\nscale_radius(halo::EinastoModel) = halo.rs\n\n\"\"\"\n Einasto_from_virial(Mvir, cvir, alpha; )\n\nConstruct an Einasto halo from the halo mass, concentration, and shape parameter.\n\n# Arguments\n- `mdef::AbstractString = default_mdef`: halo mass definition (e.g., \"200c\", \"vir\")\n- `cosmo::AbstractCosmology = default_cosmo`: cosmology under which to evaluate the overdensity\n- `z::Real = 0.0`: redshift at which to evaluate the overdensity\n\"\"\"\nfunction Einasto_from_virial(Mvir, cvir, alpha;\n mdef = default_mdef,\n cosmo = default_cosmo,\n z = 0.0)\n Rvir = Rvir_from_Mvir(Mvir; mdef = mdef, cosmo = cosmo, z = z)\n rs = Rvir / cvir\n rhos = Mvir / M_Einasto(Rvir, rs, 1.0, alpha)\n return EinastoModel(rs, rhos, alpha)\nend\n", "meta": {"hexsha": "7593a47838d62d1db582e39fce20c829201e84ba", "size": 2225, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/halos/einasto.jl", "max_stars_repo_name": "adwasser/Slomo.jl", "max_stars_repo_head_hexsha": "9567c6f0e5af9be3f8686ef143134bf6bbc515be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/halos/einasto.jl", "max_issues_repo_name": "adwasser/Slomo.jl", "max_issues_repo_head_hexsha": "9567c6f0e5af9be3f8686ef143134bf6bbc515be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/halos/einasto.jl", "max_forks_repo_name": "adwasser/Slomo.jl", "max_forks_repo_head_hexsha": "9567c6f0e5af9be3f8686ef143134bf6bbc515be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-18T00:57:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-18T00:57:50.000Z", "avg_line_length": 29.6666666667, "max_line_length": 95, "alphanum_fraction": 0.6404494382, "num_tokens": 742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960361162033533, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.8162793077743938}} {"text": "## Classical derivative-based, iterative, root-finding algorithms: Newton and Halley\n\n## Newton\nfunction newton_itr(f, fp, x0; \n xtol=4*eps(), xtolrel=4*eps(), ftol=4*eps(),\n maxsteps=100, maxfnevals=100)\n update = (o) -> begin\n xn = o.xn[end]\n fxn = o.fxn[end]\n fpxn = o.fp(xn)\n incfn(o)\n\n xn1 = xn - fxn / fpxn\n fxn1 = o.f(xn1)\n incfn(o)\n\n push!(o.xn, xn1)\n push!(o.fxn, fxn1)\n\n end\n\n x, fx = promote(float(x0), f(float(x0)))\n out = ZeroType(f, fp, nothing, update, [x], [fx],\n xtol, xtolrel, ftol,:not_converged, \n 0, maxsteps, 1, maxfnevals)\n\n\n out\nend\n\n\n\nfunction newton_method{T}(f, fp, x0::T;\n xtol=4*eps(), xtolrel=4*eps(), ftol=4eps(),\n maxsteps::Int=100, maxfnevals=100,\n verbose::Bool=false)\n\n o = newton_itr(f, fp, x0;\n xtol=xtol, xtolrel=xtolrel, ftol=ftol,\n maxsteps=maxsteps, maxfnevals=maxfnevals)\n\n\n for x in o\n nothing\n end\n verbose && verbose_output(o)\n o.xn[end]\nend\nnewton_method{T<:AbstractFloat}(f, x::T; kwargs...) = newton_method(f, D(f), x; kwargs...)\n\n\"\"\"\n\nImplementation of Newton's method: `x_n1 = x_n - f(x_n)/ f'(x_n)`\n\nArguments:\n\n* `f::Function` -- function to find zero of\n\n* `fp::Function=D(f)` -- derivative of `f`. Defaults to automatic derivative\n\n* `x0::Real` -- initial guess\n\nKeyword arguments:\n\n* `ftol`. Stop iterating when |f(xn)| <= max(1, |xn|) * ftol.\n\n* `xtol`. Stop iterating when |xn+1 - xn| <= xtol + max(1, |xn|) * xtolrel\n\n* `xtolrel`. Stop iterating when |xn+1 - xn| <= xtol + max(1, |xn|) * xtolrel\n\n* `maxeval`. Stop iterating if more than this many steps, throw error.\n\n* `maxfneval`. Stop iterating if more than this many function calls, throw error.\n\n* `verbose::Bool=false` Set to `true` to see trace.\n\n\"\"\"\nnewton{T<:Number}(f, fp, x0::T; kwargs...) = newton_method(f, fp, float(x0); kwargs...)\nnewton{T<:Real}(f, x0::T; kwargs...) = newton(f, D(f), float(x0); kwargs...)\n\n\n\n## Halley's method (cubic convergence)\nfunction halley_itr(f, fp, fpp, x0::Real;\n xtol=4*eps(), xtolrel=4*eps(), ftol=4*eps(),\n maxsteps=100, maxfnevals=100)\n\n update = (o) -> begin\n xn = o.xn[end]\n fxn = o.fxn[end]\n fpxn = o.fp(xn)\n fppxn = o.fpp(xn)\n\n xn1 = xn - 2fxn*fpxn / (2*fpxn*fpxn - fxn * fppxn)\n fxn1 = o.f(xn1)\n\n incfn(o, 3)\n push!(o.xn, xn1)\n push!(o.fxn, fxn1)\n\n end\n\n x, fx = promote(float(x0), f(float(x0)))\n out = ZeroType(f, fp, fpp, update, [x], [fx],\n xtol, xtolrel, ftol,:not_converged, \n 0, maxsteps, 1, maxfnevals)\n\n out\nend\n\nfunction halley_method{T<:AbstractFloat}(f, fp, fpp, x0::T;\n xtol=4*eps(), xtolrel=4*eps(), ftol=4eps(),\n maxsteps::Int=100, maxfnevals=100,\n verbose::Bool=false)\n\n o = halley_itr(f, fp, fpp, float(x0);\n xtol=xtol, xtolrel=xtolrel, ftol=ftol,\n maxsteps=maxsteps, maxfnevals=maxfnevals)\n\n for x in o\n nothing\n end\n verbose && verbose_output(o)\n o.xn[end]\nend\n\n\n\"\"\"\n\nImplementation of Halley's method. `xn1 = xn - 2f(xn)*f'(xn) / (2*f'(xn)^2 - f(xn) * f''(xn))`\n\nArguments:\n\n* `f::Function` -- function to find zero of\n\n* `fp::Function=D(f)` -- derivative of `f`. Defaults to automatic derivative\n\n* `fpp:Function=D(f,2)` -- second derivative of `f`.\n\n* `x0::Real` -- initial guess\n\nKeyword arguments:\n\n* `ftol`. Stop iterating when |f(xn)| <= max(1, |xn|) * ftol.\n\n* `xtol`. Stop iterating when |xn+1 - xn| <= xtol + max(1, |xn|) * xtolrel\n\n* `xtolrel`. Stop iterating when |xn+1 - xn| <= xtol + max(1, |xn|) * xtolrel\n\n* `maxeval`. Stop iterating if more than this many steps, throw error.\n\n* `verbose::Bool=false` Set to `true` to see trace.\n\n\"\"\"\nhalley(f,fp, fpp, x::Number; kwargs...) = halley_method(f, fp, fpp, float(x); kwargs...)\nhalley(f, fp, x::Real; kwargs...) = halley(f, fp, D(fp), x; kwargs...)\nhalley(f, x::Real; kwargs...) = halley(f, D(f), D(f,2), x; kwargs...)\n", "meta": {"hexsha": "7c96f417b642408a7d4641f3b180c4b6a98a0e2a", "size": 4208, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/newton.jl", "max_stars_repo_name": "JuliaPackageMirrors/Roots.jl", "max_stars_repo_head_hexsha": "943cf897e9ea6b31ab3ec70238ac4931065d365a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/newton.jl", "max_issues_repo_name": "JuliaPackageMirrors/Roots.jl", "max_issues_repo_head_hexsha": "943cf897e9ea6b31ab3ec70238ac4931065d365a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-06-10T17:15:03.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-10T17:35:11.000Z", "max_forks_repo_path": "src/newton.jl", "max_forks_repo_name": "JuliaPackageMirrors/Roots.jl", "max_forks_repo_head_hexsha": "943cf897e9ea6b31ab3ec70238ac4931065d365a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6329113924, "max_line_length": 94, "alphanum_fraction": 0.5525190114, "num_tokens": 1397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475746920262, "lm_q2_score": 0.8652240947405564, "lm_q1q2_score": 0.8162070513386078}} {"text": "module NewtonsMethod\n\nusing LinearAlgebra, ForwardDiff\n\nfunction newtonroot(f, f_prime; x₀ = 1.0, tolerance = 1E-7, maxiter = 1000)\n x_old = x₀\n normdiff = Inf\n iter = 1\n\n while normdiff > tolerance && iter <= maxiter\n x_new = x_old - f(x_old)/f_prime(x_old)\n normdiff = norm(x_new - x_old)\n x_old = x_new\n iter = iter + 1\n end\n\n if normdiff > tolerance\n return nothing\n else\n return value = x_old\n end\nend\n\nfunction newtonroot(f, x₀::Float64; tolerance = 1E-7, maxiter = 1000)\n f_prime(x) = ForwardDiff.derivative(f, x)\n x_old = x₀\n normdiff = Inf\n iter = 1\n\n while normdiff > tolerance && iter <= maxiter\n x_new = x_old - f(x_old)/f_prime(x_old)\n normdiff = norm(x_new - x_old)\n x_old = x_new\n iter = iter + 1\n end\n\n if normdiff > tolerance\n return nothing\n else\n return value = x_old\n end\nend\n\n\nexport newtonroot\n\nend # module\n", "meta": {"hexsha": "0e02cd4966f5276fc25cb07d5e0ba358956008b4", "size": 965, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NewtonsMethod.jl", "max_stars_repo_name": "XiaojunGuan/NewtonsMethod.jl", "max_stars_repo_head_hexsha": "98802b6d427b8f0c97be53d129f97579b914c296", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NewtonsMethod.jl", "max_issues_repo_name": "XiaojunGuan/NewtonsMethod.jl", "max_issues_repo_head_hexsha": "98802b6d427b8f0c97be53d129f97579b914c296", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NewtonsMethod.jl", "max_forks_repo_name": "XiaojunGuan/NewtonsMethod.jl", "max_forks_repo_head_hexsha": "98802b6d427b8f0c97be53d129f97579b914c296", "max_forks_repo_licenses": ["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.1041666667, "max_line_length": 75, "alphanum_fraction": 0.6010362694, "num_tokens": 299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.943347579470196, "lm_q2_score": 0.8652240825770432, "lm_q1q2_score": 0.8162070439983746}} {"text": "append!(truths, [\n Axiom(\"Definition of And\", P ∧ False ⟹ False),\n Axiom(\"Definition of And\", False ∧ P ⟹ False),\n Axiom(\"Definition of And\", P ∧ True ⩶ P),\n Axiom(\"Definition of And\", True ∧ P ⩶ P),\n Axiom(\"And is associative\", @associative(∧, P, Q, R)),\n Axiom(\"And is commutative\", @commutative(∧, P, Q)),\n Axiom(\"And is idempotent\", @idempotent(∧, P)),\n Axiom(\"De Morgan's laws\", P ∧ Q ⩶ ~(~P ∨ ~Q)),\n Axiom(\"And is absorbing over Or\", P ∧ (P ∨ Q) ⟹ Q),\n Axiom(\"And is distributive over Or\", @distributive(∧, ∨, P, Q, R)),\n Axiom(\"And is factorisable over Or\", @factorisable(∧, ∨, P, Q, R)),\n\n Axiom(\"Law of noncontradiction\", P ∧ ~P ⩶ False),\n Axiom(\"Law of excluded middle\", P ∨ ~P ⩶ True)\n\n Axiom(\"Definition of Or\", P ∨ True ⟹ True),\n Axiom(\"Definition of Or\", True ∨ P ⟹ True),\n Axiom(\"Definition of Or\", P ∨ False ⩶ P),\n Axiom(\"Definition of Or\", False ∨ P ⩶ P),\n Axiom(\"Or is associative\", @associative(∨, P, Q, R)),\n Axiom(\"Or is commutative\", @commutative(∨, P, Q)),\n Axiom(\"Or is idempotent\", @idempotent(∨, P)),\n Axiom(\"De Morgan's laws\", P ∨ Q ⩶ ~(~P ∧ ~Q)),\n Axiom(\"Or is absorbing over And\", P ∨ (P ∧ Q) ⟹ Q),\n Axiom(\"Or is distributive over And\", @distributive(∨, ∧, P, Q, R)),\n Axiom(\"Or is factorisable over And\", @factorisable(∨, ∧, P, Q, R)),\n Axiom(\"Or is the weaker And\", P ∧ Q ⟹ P ∨ Q),\n\n Axiom(\"Definition of Not\", ~False ⩶ True),\n Axiom(\"Definition of Not\", ~True ⩶ False),\n # prove these\n #Axiom(\"De Morgan's laws\", ~(P ∨ Q), ~P ∧ ~Q),\n #Axiom(\"De Morgan's laws\", ~(P ∨ Q), ~P ∧ ~Q),\n Axiom(\"Not is involute\", @involute(~, P)),\n\n Axiom(\"Definition of Implies\", (P ⟹ Q) ⩶ ~P ∨ Q),\n # Theorem(\"Contrapositive\", P ⟹ Q, ~Q ⟹ ~P, Proof([])),\n\n Axiom(\"Definition of Equivalent\", (P ⩶ Q) ⩶ (P ⟹ Q) ∧ (Q ⟹ P)),\n])\n", "meta": {"hexsha": "05fffff0809d9acd7b767c021b281a6fdde2c185", "size": 1837, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/tree_type3/corpus/Logic.jl", "max_stars_repo_name": "Maelstrom6/Breadth.jl", "max_stars_repo_head_hexsha": "5ccb6ec063e1d0337856257608ad887a7bd53eb8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tree_type3/corpus/Logic.jl", "max_issues_repo_name": "Maelstrom6/Breadth.jl", "max_issues_repo_head_hexsha": "5ccb6ec063e1d0337856257608ad887a7bd53eb8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-26T00:50:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-26T00:50:17.000Z", "max_forks_repo_path": "src/tree_type3/corpus/Logic.jl", "max_forks_repo_name": "Maelstrom6/Breadth.jl", "max_forks_repo_head_hexsha": "5ccb6ec063e1d0337856257608ad887a7bd53eb8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.7380952381, "max_line_length": 71, "alphanum_fraction": 0.5568862275, "num_tokens": 727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122708828602, "lm_q2_score": 0.851952809486198, "lm_q1q2_score": 0.8160960504199567}} {"text": "#=\n\n# 106: 1D Nonlinear Diffusion equation \n([source code](SOURCE_URL))\n\nSolve the nonlinear diffusion equation\n\n```math\n\\partial_t u -\\Delta u^m = 0\n```\nin $\\Omega=(-1,1)$ with homogeneous Neumann boundary condtions using the implicit Euler method.\n\nThis equation is also called \"porous medium equation\". \nThe Barenblatt solution is an exact solution of this problem which for m>1 has a finite support.\nWe initialize this problem with the exact solution for $t=t_0=0.001$.\n\n(see Barenblatt, G. I. \"On nonsteady motions of gas and fluid in porous medium.\" Appl. Math. and Mech.(PMM) 16.1 (1952): 67-78.)\n=#\n\nmodule Example106_NonlinearDiffusion1D\nusing Printf\nusing VoronoiFVM\nusing ExtendableGrids\nusing GridVisualize\n\nfunction barenblatt(x,t,m)\n tx=t^(-1.0/(m+1.0))\n xx=x*tx\n xx=xx*xx\n xx=1- xx*(m-1)/(2.0*m*(m+1));\n if xx<0.0\n xx=0.0\n end\n return tx*xx^(1.0/(m-1.0))\nend\n\n\nfunction main(;n=20,m=2,Plotter=nothing,verbose=false, unknown_storage=:sparse,tend=0.01,tstep=0.0001,DiffEq=nothing)\n \n ## Create a one-dimensional discretization\n h=1.0/convert(Float64,n/2)\n X=collect(-1:h:1)\n grid=VoronoiFVM.Grid(X)\n\n ## Flux function which describes the flux\n ## between neigboring control volumes\n function flux!(f,u0,edge)\n u=unknowns(edge,u0)\n f[1]=u[1,1]^m-u[1,2]^m\n end\n\n ## Storage term\n function storage!(f,u,node)\n f[1]=u[1]\n end\n \n ## Create a physics structure\n physics=VoronoiFVM.Physics(\n flux=flux!,\n storage=storage!)\n \n \n ## Create a finite volume system - either\n ## in the dense or the sparse version.\n ## The difference is in the way the solution object\n ## is stored - as dense or as sparse matrix\n sys=VoronoiFVM.System(grid,physics,unknown_storage=unknown_storage)\n\n ## Add species 1 to region 1\n enable_species!(sys,1,[1])\n \n\n ## Create a solution array\n inival=unknowns(sys)\n t0=0.001\n\n ## Broadcast the initial value\n inival[1,:].=map(x->barenblatt(x,t0,m),X)\n\n\n ## Create solver control info for constant time step size\n control=VoronoiFVM.NewtonControl()\n control.verbose=verbose\n control.Δt_min=tstep\n control.Δt_max=tstep\n control.Δt=tstep\n control.Δu_opt=1\n\n if isnothing(DiffEq)\n tsol=solve(inival,sys,[t0,tend],control=control)\n else\n tsol=solve(DiffEq,inival,sys,[t0,tend])\n end\n\n p=GridVisualizer(Plotter=Plotter,layout=(2,1),fast=true)\n for i=1:length(tsol)\n time=tsol.t[i]\n scalarplot!(p[1,1],grid,tsol[1,:,i],title=@sprintf(\"numerical, t=%.3g\",time))\n scalarplot!(p[2,1],grid,map(x->barenblatt(x,time,m),grid),title=@sprintf(\"exact, t=%.3g\",time))\n reveal(p)\n end\n return sum(tsol[end])\nend\n\n\nfunction test()\n testval=46.66666666647518\n main(unknown_storage=:sparse) ≈ testval && main(unknown_storage=:dense) ≈ testval\nend\n\nend \n\n", "meta": {"hexsha": "15c1065804c56d8c4f598432375555fb06491a5f", "size": 2908, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Example106_NonlinearDiffusion1D.jl", "max_stars_repo_name": "NunoEdgarGFlowHub/VoronoiFVM.jl", "max_stars_repo_head_hexsha": "c9f5834a2052414e9d174e7c423d9d68e1406fd1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/Example106_NonlinearDiffusion1D.jl", "max_issues_repo_name": "NunoEdgarGFlowHub/VoronoiFVM.jl", "max_issues_repo_head_hexsha": "c9f5834a2052414e9d174e7c423d9d68e1406fd1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/Example106_NonlinearDiffusion1D.jl", "max_forks_repo_name": "NunoEdgarGFlowHub/VoronoiFVM.jl", "max_forks_repo_head_hexsha": "c9f5834a2052414e9d174e7c423d9d68e1406fd1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7345132743, "max_line_length": 128, "alphanum_fraction": 0.6609353508, "num_tokens": 927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.872347369700144, "lm_q1q2_score": 0.8159470723350261}} {"text": "#=\n From the AgenaRisk model Tutorial/Hypothesis Testing\n Comparison of two materials A and B which has different number of tests of faultyness:\n\n - A was tested in 200 cases where 10 was faulty\n - B was tested in 100 cases where 9 was fault.\n\n Is A better then B?\n\n (Note: This is - yet another variant of A/B tests.)\n\n Summary Statistics\n parameters mean std naive_se mcse ess rhat ess_per_sec \n Symbol Float64 Float64 Float64 Float64 Float64 Float64 Float64 \n\n prob_a_is_faulty 0.0548 0.0156 0.0002 0.0013 55.1602 1.0480 7.1572\n prob_b_is_faulty 0.0969 0.0282 0.0003 0.0019 143.2899 1.0096 18.5922\n aBetterThanB 0.9136 0.2810 0.0028 0.0231 60.4603 1.0264 7.8449\n\n Compare with [10/200, 9/100]: [0.05, 0.09]\n\n Cf ~/blog/hypothesis_test.blog\n ~/webppl/gaussian_mixture_model2.wppl\n\n=#\n\nusing Turing, StatsPlots, DataFrames\ninclude(\"jl_utils.jl\")\n\n@model function hypothesis_testing(a_tests=200,a_faults=10,b_tests=100,b_faults=9)\n\n prob_a_is_faulty ~ Uniform(0,1)\n prob_b_is_faulty ~ Uniform(0,1)\n \n a_faults ~ Binomial(a_tests,prob_a_is_faulty)\n b_faults ~ Binomial(b_tests,prob_b_is_faulty)\n\n # Does A has less faults than B?\n aBetterThanB ~ Dirac(prob_a_is_faulty < prob_b_is_faulty)\n\nend\n\na_tests = 200\na_faults = 10\nb_tests = 100\nb_faults = 9\nmodel = hypothesis_testing(a_tests,a_faults,b_tests,b_faults)\n\n# chns = sample(model, Prior(), 10_000)\n# chns = sample(model, MH(), 100_000)\nchns = sample(model, PG(5), 10_000)\n# chns = sample(model, SMC(), 10_000)\n# chns = sample(model, IS(), 10_000)\n\ndisplay(chns)\n# display(plot(chns))\n\n", "meta": {"hexsha": "a9425fefd94915d0f4213f0a3774bfdd6787ab32", "size": 1731, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/hypothesis_testing.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/turing/hypothesis_testing.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/turing/hypothesis_testing.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 29.8448275862, "max_line_length": 95, "alphanum_fraction": 0.6666666667, "num_tokens": 593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302034, "lm_q2_score": 0.9019206831203063, "lm_q1q2_score": 0.81592302628479}} {"text": "function make_lists(d::Dict{Int,Vector{Int}})\n n = maximum(keys(d))\n allow = [d[k] for k = 1:n]\n return allow\nend\n\n\n\"\"\"\n iter_perms\n\nThis unexported method is the engine beneth `GenPerms`. The difference is this \nreturns a list of vectors, where each vector is a permutation of `1:n` based \non the table in `allow`.\n\"\"\"\nfunction iter_perms(allow::Vector{Vector{Int}}, p::Vector{Int} = Int[])\n n = length(allow)\n k = length(p)\n\n if n == k\n return [p]\n end\n\n valid_nexts = setdiff(allow[k+1], p)\n nested_its = Iterators.map((x) -> iter_perms(allow, [p; x]), valid_nexts)\n return Iterators.flatten(nested_its)\nend\n\niter_perms(d::Dict{Int,Vector{Int}}) = iter_perms(make_lists(d))\n\n\n\n\n\nexport PermGen\n\n\n\"\"\"\n PermGen\n\nCreate an iterator for permutations.\n* `PermGen(n::Int)` creates an iterator for all permutations of length `n`.\n* `PermGen(d::Dict{Int,Vector{Int}})` creates an iterator for all permutations in which \n element `k` may be a value in `d[k]`. Alternatively, `d` may be a `Vector` of `Vectors`.\n\nExamples\n--------\n```\njulia> for p in PermGen(3)\n println(p)\n end\n(1)(2)(3)\n(1)(2,3)\n(1,2)(3)\n(1,2,3)\n(1,3,2)\n(1,3)(2)\n\n\njulia> d = [[2,3,4], [1,3,4], [1,2,4], [1,2,3]];\n\njulia> for p in PermGen(d)\n println(p)\n end\n(1,4)(2,3)\n(1,3,2,4)\n(1,2,3,4)\n(1,4,2,3)\n(1,3)(2,4)\n(1,3,4,2)\n(1,2,4,3)\n(1,4,3,2)\n(1,2)(3,4)\n```\n\"\"\"\nfunction PermGen(allow::Vector{Vector{Int}})\n X = iter_perms(allow)\n return Iterators.map(Permutation, X)\nend\nPermGen(d::Dict{Int,Vector{Int}}) = PermGen(make_lists(d))\n\nPermGen(n::Int) = Base.Generator(Permutation, permutations(1:n))\n\n\n\n\nfunction deranged_allow(n::Int)\n d = Dict{Int,Vector{Int}}()\n base = collect(1:n)\n for k = 1:n\n d[k] = setdiff(base, k)\n end\n return d\nend\n\nfunction all_allow(n::Int)\n d = Dict{Int,Vector{Int}}()\n base = collect(1:n)\n for k = 1:n\n d[k] = base\n end\n return d\nend\n\nexport DerangeGen\n\n\"\"\"\n DerangeGen(n::Int)\n\nCreate an iterator for all derangements of `{1,2,...,n}`. These are \nall permutations without any fixed points. \n\"\"\"\nDerangeGen(n::Int) = PermGen(deranged_allow(n))\n", "meta": {"hexsha": "7dadc1d315b18379a0b3efeb65e1193c36f3c9e0", "size": 2155, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/perm_gen.jl", "max_stars_repo_name": "scheinerman/Permutations.jl", "max_stars_repo_head_hexsha": "1a1accf58669ae84e00b6491748c8e1c2db4e477", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 46, "max_stars_repo_stars_event_min_datetime": "2015-06-19T16:01:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T15:12:24.000Z", "max_issues_repo_path": "src/perm_gen.jl", "max_issues_repo_name": "scheinerman/Permutations.jl", "max_issues_repo_head_hexsha": "1a1accf58669ae84e00b6491748c8e1c2db4e477", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2015-11-20T17:57:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-30T19:40:41.000Z", "max_forks_repo_path": "src/perm_gen.jl", "max_forks_repo_name": "scheinerman/Permutations.jl", "max_forks_repo_head_hexsha": "1a1accf58669ae84e00b6491748c8e1c2db4e477", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2015-04-27T21:16:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-01T12:14:12.000Z", "avg_line_length": 19.0707964602, "max_line_length": 91, "alphanum_fraction": 0.6167053364, "num_tokens": 741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726545, "lm_q2_score": 0.8918110368115781, "lm_q1q2_score": 0.8159187671829006}} {"text": "#=Given a number N, find its factorial using recursion. It is quite easy\nbut we want to add recursion algorithms in Julia.=#\n\n## Function \n\nfunction fact(n)\n if (n == 0)\n return 1\n end\n if (n == 1)\n return 1\n end\n return n * fact(n - 1)\nend\n\n## Input\n\nn = readline()\nn = parse(Int64, n)\n\n## Calling the Function\n\nfact(n)\n\n#=\nSample Test Case:\nInput:\n n=10\nOutput:\n 3628800\nTime complexity: O( N )\n=#\n", "meta": {"hexsha": "86448eb3763d5aa1bdecb3f0dff2ef928014bdf9", "size": 435, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/cp/factorials.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/factorials.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/factorials.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.1818181818, "max_line_length": 72, "alphanum_fraction": 0.6, "num_tokens": 132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.8872045937171068, "lm_q1q2_score": 0.8159110782385655}} {"text": "using StatsBase, Distributions, Random, LinearAlgebra\nRandom.seed!(1)\n\nfunction crudeSimulation(deltaT,T,Q,initProb)\n n = size(Q)[1]\n Pdelta = I + Q*deltaT\n state = sample(1:n,weights(initProb))\n t = 0.0\n while t < T\n t += deltaT\n state = sample(1:n,weights(Pdelta[state,:]))\n end\n return state\nend\n\nfunction doobGillespie(T,Q,initProb)\n n = size(Q)[1]\n Pjump = (Q-diagm(0 => diag(Q)))./-diag(Q)\n lamVec = -diag(Q)\n state = sample(1:n,weights(initProb))\n sojournTime = rand(Exponential(1/lamVec[state]))\n t = 0.0\n while t + sojournTime < T\n t += sojournTime\n state = sample(1:n,weights(Pjump[state,:]))\n sojournTime = rand(Exponential(1/lamVec[state]))\n end\n return state\nend\n\nT, N = 0.25, 10^5\n\nQ = [-3 1 2\n 1 -2 1\n 0 1.5 -1.5]\n\np0 = [0.4 0.5 0.1]\n\ncrudeSimEst = counts([crudeSimulation(10^-3., T, Q, p0) for _ in 1:N])/N\ndoobGillespieEst = counts([doobGillespie(T, Q, p0) for _ in 1:N])/N\nexplicitEst = p0*exp(Q*T)\n\nprintln(\"CrudeSim: \\t\\t\", crudeSimEst)\nprintln(\"Doob Gillespie Sim: \\t\", doobGillespieEst)\nprintln(\"Explicit: \\t\\t\", explicitEst)\n", "meta": {"hexsha": "33e39afadc15de25c63577d6b56cac98210a1b35", "size": 1142, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "10_chapter/qMatrixSimulation.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "10_chapter/qMatrixSimulation.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "10_chapter/qMatrixSimulation.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 24.8260869565, "max_line_length": 72, "alphanum_fraction": 0.61558669, "num_tokens": 422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947148047777, "lm_q2_score": 0.863391617003942, "lm_q1q2_score": 0.815900514875476}} {"text": "using LinearAlgebra\n\nA = [1 1 1 1;\n 2 3 5 4;\n 4 9 25 16;\n 8 27 125 64]\n\nfunction vandermonde(A)\n det = 1\n for j in 2:4\n for i in 1:j-1\n det *= (A[2,j]-A[2,i])\n end\n end\n\n det\nend\n\nprintln(\"vandermonde: \", vandermonde(A))\nprintln(\"det(A): \", det(A))", "meta": {"hexsha": "d4f3d3a6fe68a12abd37272ad6634e57be932d4d", "size": 297, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "linear_algebra/vandermonde.jl", "max_stars_repo_name": "nocotan/numerical_calculus.jl", "max_stars_repo_head_hexsha": "76b46b22d04e2e7e82cf44788c4f48ce25d59847", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-01-07T06:26:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-24T06:21:01.000Z", "max_issues_repo_path": "linear_algebra/vandermonde.jl", "max_issues_repo_name": "nocotan/numerical_calculus.jl", "max_issues_repo_head_hexsha": "76b46b22d04e2e7e82cf44788c4f48ce25d59847", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-01-10T08:22:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-08T13:31:00.000Z", "max_forks_repo_path": "linear_algebra/vandermonde.jl", "max_forks_repo_name": "nocotan/numerical_calculus.jl", "max_forks_repo_head_hexsha": "76b46b22d04e2e7e82cf44788c4f48ce25d59847", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-01-10T05:59:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T13:22:34.000Z", "avg_line_length": 14.85, "max_line_length": 40, "alphanum_fraction": 0.4983164983, "num_tokens": 126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947179030095, "lm_q2_score": 0.8633916064586998, "lm_q1q2_score": 0.8159005075852652}} {"text": "T = [.80 .05 .15 # sunny\n .20 .60 .20 # rainy\n .20 .30 .50] # foggy\n\nE = [.10 .90 # sunny\n .80 .20 # rainy\n .30 .70] # foggy\n\n\nx = [2, 1, 1] # 1: umbrella 2: no umbrella\nstates = Dict(1 => \"sunny\", 2 => \"rainy\", 3 => \"foggy\")\n\n\nfunction viterbi(x, states, T::Array{Float64, 2}, E::Array{Float64, 2})\n n = length(x)\n p = length(states)\n prior = 1 / p # assume equal priors\n\n delta = zeros(n, p) # holds the most likely path\n gamma = convert(Array{Int64, 2}, zeros(n, p)) # holds the arguments for the most likely path\n\n delta[1, :] = prior * E[:, 2]\n\n for i in 2:n\n b = x[i] # current observation\n\n for j in 1:p\n a = T[:, j] # transition probability *to* hidden state j {sunny, rainy, foggy}\n prev = delta[i-1, :] # previous deltas\n\n cont = diag(a * prev)\n delta[i, j] = maximum(cont) * E[j, b]\n _, gamma[i, j] = findmax(cont)\n end\n end\n\n _, dlast = findmax(delta[n, :])\n sequence = [dlast]\n\n for i in n:-1:2\n _, prev = findmax(delta[i, :])\n unshift!(sequence, gamma[i, prev])\n end\n\n return delta, [states[i] for i in sequence]\nend\n", "meta": {"hexsha": "aaba198fe8effbdab15e4c37e79d8d214ac0bbc2", "size": 1176, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/HMM.jl", "max_stars_repo_name": "fdabl/EyeFix.jl", "max_stars_repo_head_hexsha": "1bc6540d8620a144af5c01a00b2c884edc174d1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/HMM.jl", "max_issues_repo_name": "fdabl/EyeFix.jl", "max_issues_repo_head_hexsha": "1bc6540d8620a144af5c01a00b2c884edc174d1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/HMM.jl", "max_forks_repo_name": "fdabl/EyeFix.jl", "max_forks_repo_head_hexsha": "1bc6540d8620a144af5c01a00b2c884edc174d1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0212765957, "max_line_length": 96, "alphanum_fraction": 0.5263605442, "num_tokens": 391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947070591977, "lm_q2_score": 0.8633916099737806, "lm_q1q2_score": 0.815900501544542}} {"text": "function (+)(x::SimpleQuaternion, y::SimpleQuaternion)\n cz = get_parts(x) .+ get_parts(y)\n return SimpleQuaternion(cz...)\nend \n\n(+)(x::SimpleQuaternion, y::Number) = x + SimpleQuaternion(y)\n(+)(x::Number, y::SimpleQuaternion) = SimpleQuaternion(x) + y\n\n\nfunction (-)(x::SimpleQuaternion)\n a,b,c,d = get_parts(x)\n return SimpleQuaternion(-a,-b,-c,-d)\nend \n\nfunction (-)(x::SimpleQuaternion,y::SimpleQuaternion)\n cz = get_parts(x) .- get_parts(y)\n return SimpleQuaternion(cz...)\nend \n\n(-)(x::SimpleQuaternion,y::Number) = x - SimpleQuaternion(y)\n(-)(x::Number, y::SimpleQuaternion) = SimpleQuaternion(x) - y \n\nfunction (*)(x::SimpleQuaternion, y::SimpleQuaternion)\n a,b,c,d = get_parts(x)\n aa,bb,cc,dd, = get_parts(y)\n\n w = a*aa - b*bb - c*cc - d*dd\n x = a*bb + b*aa + c*dd - d*cc\n y = a*cc - b*dd + c*aa + d*bb \n z = a*dd + b*cc - c*bb + d*aa\n \n return SimpleQuaternion(w,x,y,z)\nend \n\n(*)(x::SimpleQuaternion, y::Number) = x * SimpleQuaternion(y)\n(*)(x::Number, y::SimpleQuaternion) = SimpleQuaternion(x) * y\n\n\nfunction norm(x::SimpleQuaternion)\n a,b,c,d = get_parts(x)\n return sqrt(a*a + b*b + c*c + d*d)\nend\n\nfunction (inv)(x::SimpleQuaternion)\n a,b,c,d = get_parts(x)\n n = a*a + b*b + c*c + d*d\n return SimpleQuaternion(a/n, -b/n, -c/n, -d/n)\nend\n\nfunction (_inv)(x::SimpleQuaternion)\n a,b,c,d = get_parts(x)\n n = a*a + b*b + c*c + d*d\n return SimpleQuaternion(a//n, -b//n, -c//n, -d//n)\nend\n\n(/)(x::SimpleQuaternion, y::SimpleQuaternion) = x * inv(y)\n(/)(x::SimpleQuaternion,y::Number) = x * inv(y)\n(/)(x::Number,y::SimpleQuaternion) = x * inv(y)\n\n(//)(x::SimpleQuaternion, y::SimpleQuaternion) = x * _inv(y)\n(//)(x::SimpleQuaternion, y::Number) = x * (1//y)\n(//)(x::Number,y::SimpleQuaternion) = SimpleQuaternion(x) // y\n\n\"\"\"\n`adjoint(x::SimpleQuaternion)` or `x'` returns the adjoint of `x`.\n\nIf `x` is `a + b*im + c*jm + d*km` then `x'` is `a - b*im - c*im - d*im`.\n\"\"\"\nadjoint(x::SimpleQuaternion) = conj(x)\n \n\n\"\"\"\n`conj(x::SimpleQuaternion)` returns the conjugate of `x`.\n\nIf `x` is `a + b*im + c*jm + d*km` then `conj(x)` is `a - b*im - c*im - d*im`.\n\"\"\"\nfunction conj(x::SimpleQuaternion)\n a,b,c,d = get_parts(x)\n return SimpleQuaternion(a,-b,-c,-d)\nend \n", "meta": {"hexsha": "91e05b91fb7c7980c189020c18b9c9fb031dc7a3", "size": 2242, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/arithmetic.jl", "max_stars_repo_name": "scheinerman/SimpleQuaternions.jl", "max_stars_repo_head_hexsha": "ad494b7d866fc74c359177155bc58fa2c6b66f07", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/arithmetic.jl", "max_issues_repo_name": "scheinerman/SimpleQuaternions.jl", "max_issues_repo_head_hexsha": "ad494b7d866fc74c359177155bc58fa2c6b66f07", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/arithmetic.jl", "max_forks_repo_name": "scheinerman/SimpleQuaternions.jl", "max_forks_repo_head_hexsha": "ad494b7d866fc74c359177155bc58fa2c6b66f07", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-13T11:56:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-13T11:56:34.000Z", "avg_line_length": 27.6790123457, "max_line_length": 78, "alphanum_fraction": 0.6043710972, "num_tokens": 758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430805473952, "lm_q2_score": 0.8740772466456688, "lm_q1q2_score": 0.8158906283829208}} {"text": "module NewtonsMethod\n\nusing ForwardDiff, LinearAlgebra\n\nfunction newtonroot(f, f′; x_0, tol=1E-7, maxiter=1000)\n # setup the algorithm\n x_old = x_0\n normdiff = Inf\n iter = 1\n while normdiff > tol && iter <= maxiter\n x_new = x_old - ( f(x_old) / f′(x_old) ) # use Newton's method\n normdiff = norm(x_new - x_old)\n x_old = x_new\n iter = iter + 1\n end\n if iter <= maxiter\n return (value = x_old, normdiff=normdiff, iter=iter) # A named tuple\n else\n println(\"No unit root found with tolerance level $tol and Maximum Number of Iterations $maxiter\")\n return nothing\n end\nend\n\nfunction newtonroot(f; x_0, tol=1E-7, maxiter=1000)\n # setup the algorithm\n x_old = x_0\n normdiff = Inf\n iter = 1\n D(f) = x -> ForwardDiff.derivative(f, x)\n f′ = D(f) # use auto diff\n while normdiff > tol && iter <= maxiter\n x_new = x_old - ( f(x_old) / f′(x_old) ) # use Newton's method\n normdiff = norm(x_new - x_old)\n x_old = x_new\n iter = iter + 1\n end\n if iter <= maxiter\n return (value = x_old, normdiff=normdiff, iter=iter) # A named tuple\n else\n println(\"No unit root found with tolerance level $tol and Maximum Number of Iterations $maxiter\")\n return nothing\n end\nend\n\nexport newtonroot\n\nend\n", "meta": {"hexsha": "925a1d194972b7081c8361fe4ff169e4df3c92b5", "size": 1328, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NewtonsMethod.jl", "max_stars_repo_name": "oliver-vogt/NewtonsMethod.jl", "max_stars_repo_head_hexsha": "1556f09381f230af897d0502748931bce502a400", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NewtonsMethod.jl", "max_issues_repo_name": "oliver-vogt/NewtonsMethod.jl", "max_issues_repo_head_hexsha": "1556f09381f230af897d0502748931bce502a400", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NewtonsMethod.jl", "max_forks_repo_name": "oliver-vogt/NewtonsMethod.jl", "max_forks_repo_head_hexsha": "1556f09381f230af897d0502748931bce502a400", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6666666667, "max_line_length": 105, "alphanum_fraction": 0.6144578313, "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308184368928, "lm_q2_score": 0.8740772253241803, "lm_q1q2_score": 0.815890619811398}} {"text": "function myrouwenhorst(N::Integer,ρ::Real,σ::Real)\r\n \r\n \"\"\"\r\n Consider the follwoing process\r\n z_{t+1} = ρz_t + ϵ_{t+1}\r\n\r\n Arguments:\r\n N::Int64 :grid size \r\n ρ::Float64 :persistence of AR(1) process\r\n σ::Float64 :standard diviation of random components\r\n \r\n Return:\r\n z::array{float64,1} :discretized grid \r\n Π::array{float64,2} :transition matrix \r\n \r\n \"\"\"\r\n \r\n \r\n #####################################################\r\n # step 2. create state grid\r\n #####################################################\r\n σ_z = σ/sqrt(1.0-ρ^2)\r\n ψ = sqrt(N-1)* σ_z # end points\r\n # create shock grid\r\n zgrid = collect(linspace(-ψ,ψ,N))\r\n \r\n #####################################################\r\n # step 3. compute trandition matrix\r\n #####################################################\r\n \r\n p = (1.0+ρ)/2.0\r\n Π = [p 1-p;1-p p]\r\n @inbounds for i in 3:N\r\n zero_v = zeros(i-1,1)\r\n zero_v_long = zeros(1,i)\r\n Π = p.*[Π zero_v; zero_v_long] +\r\n (1-p).*[zero_v Π; zero_v_long] +\r\n (1-p).*[zero_v_long; Π zero_v] +\r\n p.*[zero_v_long; zero_v Π]\r\n ######################################################\r\n # step 4. devide matrix by 2 except the top and bottom\r\n ######################################################\r\n @views Π[2:end-1,:] ./= 2.0 \r\n end\r\n \r\n return zgrid, Π\r\nend", "meta": {"hexsha": "425e9ce2a661a48e708ca9193409502bd8b9050a", "size": 1449, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "myrouwenhorst.jl", "max_stars_repo_name": "tokupooh/Quant-Macro", "max_stars_repo_head_hexsha": "780735ccf3eb82373b5b101ac385756bf9975c2c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-01T10:58:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-01T10:58:25.000Z", "max_issues_repo_path": "myrouwenhorst.jl", "max_issues_repo_name": "tokupooh/Quant-Macro", "max_issues_repo_head_hexsha": "780735ccf3eb82373b5b101ac385756bf9975c2c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "myrouwenhorst.jl", "max_forks_repo_name": "tokupooh/Quant-Macro", "max_forks_repo_head_hexsha": "780735ccf3eb82373b5b101ac385756bf9975c2c", "max_forks_repo_licenses": ["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.829787234, "max_line_length": 59, "alphanum_fraction": 0.3926846101, "num_tokens": 402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422269175634, "lm_q2_score": 0.8577681068080748, "lm_q1q2_score": 0.8158594672882947}} {"text": "# p23a.jl - eigenvalues of UNperturbed Laplacian on [-1,1]x[-1,1]\n# (compare p16.jl)\n\n# Set up tensor product Laplacian and compute 4 eigenmodes:\nN = 16; (D,x) = cheb(N); y = x;\nxx = x[2:N]; yy = y[2:N];\nD2 = D^2; D2 = D2[2:N,2:N]; I = eye(N-1);\nL = -kron(I,D2) - kron(D2,I); # Laplacian\n#f = @. exp(20*(yy-xx'-1)); # perturbation\n#L = L + diagm(f[:]);\n(D,V) = eig(L); ii = sortperm(D)[1:4];\nD = D[ii]; V = V[:,ii];\n\n# Reshape them to 2D grid, interpolate to finer grid, and plot:\nxx = yy = x[end:-1:1];\nxxx = yyy = -1:.02:1;\nuu = zeros(N+1,N+1);\n(ay,ax) = (repmat([.56 .04],2,1),repmat([.1,.5],1,2)); clf();\nfor i = 1:4\n uu[2:N,2:N] = reshape(V[:,i],N-1,N-1);\n uu = uu/norm(uu[:],Inf);\n s = Spline2D(xx,yy,reduce(flipdim,uu,1:2));\n uuu = evalgrid(s,xxx,yyy);\n axes([ax[i],ay[i],.38,.38]);\n contour(xxx,yyy,uuu,levels=-.9:.2:.9);\n axis(\"square\");\n title(\"eig = $(signif(D[i]/(pi^2/4),13)) π^2/4\");\nend\n", "meta": {"hexsha": "a3be509c7723d479afa95a5528281b71519b4b3a", "size": 955, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/scripts/p23a.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/p23a.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/p23a.jl", "max_forks_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_forks_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9310344828, "max_line_length": 65, "alphanum_fraction": 0.522513089, "num_tokens": 417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422227627597, "lm_q2_score": 0.8577681013541613, "lm_q1q2_score": 0.8158594585369892}} {"text": "struct Ellipse\n x::Number\n y::Number\n\n rh::Number\n rv::Number\nend\n\nfunction circumference(ellipse::Ellipse)\n return pi * (3 * (ellipse.rh + ellipse.rv) - sqrt(10 * ellipse.rh * ellipse.rv + 3 * (ellipse.rh^2 + ellipse.rv^2)))\nend\n\nBase.:(==)(lhs::Ellipse, rhs::Ellipse) = lhs.x == rhs.x && lhs.y == rhs.y && lhs.rv == rhs.rv && lhs.rh == rhs.rh\n\nellipse_t(theta, e::Ellipse) = atan(e.rh / e.rv * tan(theta))\n\nellipse_f(t, e::Ellipse) = sqrt(e.rh^2 * sin(t)^2 + e.rv^2 * cos(t)^2)\n\n# Calculates step size based on estimated arc length at current section compared to the 'optimum'.\n# https://math.stackexchange.com/questions/433094/how-to-determine-the-arc-length-of-ellipse\nfunction pointsOnEllipse(ellipse::Ellipse; filled::Bool=false, checks::Int=max(180, ceil(Int, circumference(ellipse) / 2)))\n res = Set{Tuple{Number, Number}}()\n step = 2 * pi / checks\n\n if checks > 0\n theta = -pi / 2\n while theta <= pi / 2\n ox = cos(theta) * ellipse.rh\n oy = sin(theta) * ellipse.rv\n\n push!(res, (round(Int, ellipse.x + ox), round(Int, ellipse.y + oy)))\n push!(res, (round(Int, ellipse.x - ox), round(Int, ellipse.y + oy)))\n\n if filled\n for i in floor(Int, -ox + 1):ceil(Int, ox - 1)\n push!(res, (round(Int, ellipse.x + i), round(Int, ellipse.y + oy)))\n end\n end\n\n t = ellipse_t(theta, ellipse)\n f = ellipse_f(t, ellipse)\n mr = step * f\n theta += min(step / mr, step)\n end\n end\n\n return collect(res)\nend", "meta": {"hexsha": "54c0b8c83174df54e23853c8bad834ceedac0046", "size": 1603, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/shapes/ellipse.jl", "max_stars_repo_name": "kingW3/Ahorn", "max_stars_repo_head_hexsha": "a064bf0a953620415ea6eb8b0d610c8c606b2b05", "max_stars_repo_licenses": ["FSFAP"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/shapes/ellipse.jl", "max_issues_repo_name": "kingW3/Ahorn", "max_issues_repo_head_hexsha": "a064bf0a953620415ea6eb8b0d610c8c606b2b05", "max_issues_repo_licenses": ["FSFAP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/shapes/ellipse.jl", "max_forks_repo_name": "kingW3/Ahorn", "max_forks_repo_head_hexsha": "a064bf0a953620415ea6eb8b0d610c8c606b2b05", "max_forks_repo_licenses": ["FSFAP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3958333333, "max_line_length": 123, "alphanum_fraction": 0.5664379289, "num_tokens": 462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075744568838, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.8158362087752561}} {"text": "include(\"interps.jl\")\n\nf(x) = 1 / (25 * x * x + 1)\n\nfunction myerror(w)\n N = 1000\n res = abs(f(-1.) - w(-1.))\n for i=1:N\n temp = abs(f(-1. + (2*i/N)) - w(-1. + (2*i/N)))\n if temp > res\n res = temp\n end\n end\n return res\nend\n\nfunction sredniokwadratowa(w)\n N = 1000\n res = abs(f(-1.) - w(-1.))\n for i=1:N\n temp = abs(f(-1. + (2*i/N)) - w(-1. + (2*i/N)))\n if temp > res\n res = temp\n end\n end\n return res\nend\n\n# Rownoodlegle 10\nxss = linspace(-1,1,10)\nw = interpNewton(xss, map(f,xss))\nmyerror(w)\n\n#zera czebyszewa\nxss = czebyszew_zeroes(10)\nw = interpNewton(xss, map(f,xss))\nmyerror(w)\n\n#punkty ekstyrmalne czebyszewa\nxss = czebyszew_extreme(9)\nw = interpNewton(xss, map(f,xss))\nmyerror(w)\n\n#lagrande\nw = x -> lagrandePolymonial(9,x)\nw(1)\nmyerror(w)\n\n#czebyszew optymalny\nw = x -> czebyszewPolymonial(9,x)\nw(0.15)\nmyerror(w)\n\n``\n", "meta": {"hexsha": "b6e5213bf0f8cc5aa3495158b7e0f2e94d7e375a", "size": 864, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Analiza_Numeryczna_M/10Lista/kwadratury.jl", "max_stars_repo_name": "Magikis/Uniwersity", "max_stars_repo_head_hexsha": "06964ef31d721af85740df1dce3f966006ab9f78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2017-11-30T08:45:48.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-26T14:15:45.000Z", "max_issues_repo_path": "Analiza_Numeryczna_M/10Lista/kwadratury.jl", "max_issues_repo_name": "Magikis/Uniwersity", "max_issues_repo_head_hexsha": "06964ef31d721af85740df1dce3f966006ab9f78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Analiza_Numeryczna_M/10Lista/kwadratury.jl", "max_forks_repo_name": "Magikis/Uniwersity", "max_forks_repo_head_hexsha": "06964ef31d721af85740df1dce3f966006ab9f78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2017-10-16T09:42:59.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-27T19:48:45.000Z", "avg_line_length": 15.7090909091, "max_line_length": 51, "alphanum_fraction": 0.587962963, "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620539235896, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.815770086796178}} {"text": "using Plots ; pyplot()\n\noccupancyAnalytic(n,r) = sum([(-1)^k*binomial(n,k)*(1 - k/n)^r for k in 0:n])\n\nfunction occupancyMC(n,r,N)\n fullCount = 0\n for _ in 1:N\n envelopes = zeros(Int,n)\n for k in 1:r\n target = rand(1:n)\n envelopes[target] += 1\n end\n numFilled = sum(envelopes .> 0)\n if numFilled == n\n fullCount += 1\n end\n end\n return fullCount/N\nend\n\nmax_n, N, Kvals = 100, 10^3, [2,3,4]\n\nanalytic = [[occupancyAnalytic(big(n),big(k*n)) for n in 1:max_n] for k in Kvals]\nmonteCarlo = [[occupancyMC(n,k*n,N) for n in 1:max_n] for k in Kvals] \n\nplot(1:max_n, analytic, c=[:blue :red :green], \n\tlabel=[\"K=2\" \"K=3\" \"K=4\"])\nscatter!(1:max_n, monteCarlo, mc=:black, shape=:+, \n\tlabel=\"\", xlims=(0,max_n),ylims=(0,1), \n\txlabel=\"n Envelopes\", ylabel=\"Probability\", legend=:topright)", "meta": {"hexsha": "86b639f51de7cab6435e575df8ec4934c5eaeee6", "size": 863, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "2_chapter/occupancyProblem.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "2_chapter/occupancyProblem.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "2_chapter/occupancyProblem.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 28.7666666667, "max_line_length": 81, "alphanum_fraction": 0.5793742758, "num_tokens": 306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314624993576759, "lm_q2_score": 0.8757869932689566, "lm_q1q2_score": 0.8157627416552464}} {"text": "# ---\n# title: 368. Largest Divisible Subset\n# id: problem368\n# author: Indigo\n# date: 2021-06-14\n# difficulty: Medium\n# categories: Math, Dynamic Programming\n# link: \n# hidden: true\n# ---\n# \n# Given a set of **distinct** positive integers, find the largest subset such\n# that every pair (Si, Sj) of elements in this subset satisfies:\n# \n# Si % Sj = 0 or Sj % Si = 0.\n# \n# If there are multiple solutions, return any subset is fine.\n# \n# **Example 1:**\n# \n# \n# \n# Input: [1,2,3]\n# Output: [1,2] (of course, [1,3] will also be ok)\n# \n# \n# **Example 2:**\n# \n# \n# \n# Input: [1,2,4,8]\n# Output: [1,2,4,8]\n# \n# \n# \n## @lc code=start\nusing LeetCode\n\nfunction largest_divisible_subset(nums::Vector{Int})\n sort!(nums)\n len = length(nums)\n dp = fill(1, len)\n prev = fill(0, len)\n for i in 2:len, j in 1:(i - 1)\n if nums[i] % nums[j] == 0 && dp[i] < dp[j] + 1\n dp[i] = dp[j] + 1\n prev[i] = j\n end\n end\n idx = argmax(dp)\n res = Int[]\n while idx != 0\n push!(res, nums[idx])\n idx = prev[idx]\n end\n return res\nend\n## @lc code=end\n", "meta": {"hexsha": "13a59689fa468b179259a6b925ec89d452830246", "size": 1209, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/368.largest-divisible-subset.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2020-10-27T18:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:27:49.000Z", "max_issues_repo_path": "src/problems/368.largest-divisible-subset.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-01T07:26:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T11:57:53.000Z", "max_forks_repo_path": "src/problems/368.largest-divisible-subset.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2020-10-30T11:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:35:11.000Z", "avg_line_length": 20.4915254237, "max_line_length": 77, "alphanum_fraction": 0.5508684864, "num_tokens": 408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9314625012602594, "lm_q2_score": 0.8757869835428966, "lm_q1q2_score": 0.8157627342620442}} {"text": "# bernstein basis\n\n\nusing Plots\n# for the LaTeX labels in the legend\nusing LaTeXStrings \n\nfunction compute_bernstein(i,n; steps=100)\n return [binomial(n,i)*t^i*(1-t)^(n-i) for t in LinRange(0,1,steps)]\nend\n\nfunction compute_bernstein_poly(px,py; steps=100)\n n = length(px)-1\n bernsteins = [compute_bernstein(i,n) for i=0:n]\n x_vals = [sum(px[k]*bernsteins[k][t] for k=1:n+1) for t=1:steps]\n y_vals = [sum(py[k]*bernsteins[k][t] for k=1:n+1) for t=1:steps]\n return x_vals, y_vals\nend\n\n\nfunction plot_bernstein_poly()\n bernsteins = [compute_bernstein(i,2) for i=0:n]\n plot(bernsteins, leg=false)\n png(\"bernsteins\")\nend\n\nfunction plot_with_bernstein(px,py; steps=100, subplot=1)\n x_vals, y_vals = compute_bernstein_poly(px,py; steps=steps)\n plot!(x_vals, y_vals, color=:blue, label=\"\",subplot=subplot)\nend\n\nfunction main()\n px = [0, 3, 7]\n py = [2, 9, 3]\n\n plot(;size=(700,500), axisratio=:equal, legendfont=font(13))\n plot!(px, py, linetype=:scatter, label=\"control points\")\n plot_with_bernstein(px,py)\n png(\"using_bernstein\")\nend\n", "meta": {"hexsha": "f739bae951539a061e6002fd13ad8870fd56eb46", "size": 1080, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lines/bernstein.jl", "max_stars_repo_name": "Ellon-M/visualizations", "max_stars_repo_head_hexsha": "5a42c213ea8fd0597e2035778d9ae6460eb9e821", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lines/bernstein.jl", "max_issues_repo_name": "Ellon-M/visualizations", "max_issues_repo_head_hexsha": "5a42c213ea8fd0597e2035778d9ae6460eb9e821", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lines/bernstein.jl", "max_forks_repo_name": "Ellon-M/visualizations", "max_forks_repo_head_hexsha": "5a42c213ea8fd0597e2035778d9ae6460eb9e821", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3414634146, "max_line_length": 71, "alphanum_fraction": 0.6787037037, "num_tokens": 370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172673767972, "lm_q2_score": 0.8596637523076225, "lm_q1q2_score": 0.8157497787026329}} {"text": "\"\"\"\n binomial_rng(p, n, shape=1; seed=nothing)\n\nGenerate a `shape` element array of random variables from a Binomial(`p`, `n`) distribution. Optionally you can set a specific seed.\n\n# Notes\n\nThe Binomial(x, n, p) distribution describes the total number of successes in a sequence of n Bernoulli(p) trials.\n\nThe pdf is given:\n\n``f(x,n,p) = \\\\binom{n}{x} p^x (1-p)^{n-x} \\\\quad x = 0,1,\\\\dots, n``\n\n# Examples\n\n```julia-repl\njulia> binomial_rng(.3, 10)\n1×1 Matrix{Int64}:\n 3\n\njulia> binomial_rng(.3, 10, (2,2))\n2×2×1 Array{Int64, 3}:\n[:, :, 1] =\n 2 1\n 2 2\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\"\"\"\nfunction binomial_rng(p::Real, n::Int, shape::Union{Int, Tuple{Vararg{Int}}}=1; seed::Union{Int, Nothing}=nothing)\n check_p(p)\n U = bernoulli_rng(p, (shape..., n), seed=seed)\n X = sum(U, dims=ndims(U)) # want sum over final or `n` dimension\n return X\nend\n", "meta": {"hexsha": "ebb7e0c94e83d08bc9701ad8c41bcd00dbf2acba", "size": 1001, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/binomial.jl", "max_stars_repo_name": "chris-santiago/RandomVariates.jl", "max_stars_repo_head_hexsha": "75cf7057d06482f5208233f0f78f08e0dcfee58f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/binomial.jl", "max_issues_repo_name": "chris-santiago/RandomVariates.jl", "max_issues_repo_head_hexsha": "75cf7057d06482f5208233f0f78f08e0dcfee58f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/binomial.jl", "max_forks_repo_name": "chris-santiago/RandomVariates.jl", "max_forks_repo_head_hexsha": "75cf7057d06482f5208233f0f78f08e0dcfee58f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6666666667, "max_line_length": 132, "alphanum_fraction": 0.6543456543, "num_tokens": 348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897459384732, "lm_q2_score": 0.8670357735451835, "lm_q1q2_score": 0.8156983651131408}} {"text": "using GaussQuadrature, Plots\nusing ClimateMachine.Mesh.Elements\nusing ClimateMachine\ngr(size = (400,400))\nn = 4\nr,w = GaussQuadrature.legendre(n+1, both)\nT = eltype(r)\na, b = GaussQuadrature.legendre_coefs(T, n)\nx = collect(range(-1,1,length = 100))\nV = GaussQuadrature.orthonormal_poly(x, a, b)\np = []\npush!(p,plot(x, V[:,1], ylims = (-2,2), \n title = string(1-1) * \"'th\",\n legend = false)\n)\nfor i in 2:n+1\n push!(p,\n plot(x, V[:,i], ylims = (-2,2), \n title = string(i-1) * \"'th\", \n legend = false)\n )\nend\ndisplay(plot(p...))\n## Show decomposition\nf(x) = sin(π*x) * exp(x) / 2\nry = @. f(r)\nxy = @. f(x)\nplot(r,ry)\nplot!(x, xy)\n𝒯 = GaussQuadrature.orthonormal_poly(r, a, b)\nspectrum = inv(𝒯) * f.(r)\nindex = collect(range(0, n,length = n+1))\nscatter(index, log10.(abs.(spectrum)), \nxlabel = \"Legendre Index\", \nylabel = \"Log10(Abs(Amplitude))\", \nlabel = false,\ntitle = \"Legendre Modal Amplitudes\")\n##\nfunction plot_approximation(V, spectrum, i; exact = true)\n p1 = plot(x, V[:,1:i] * spectrum[1:i], ylims = (-1.1,1.1), \n title = \"Modes 0 through \" * string(i-1),\n label = \"approximation\", legend = :bottomright)\n if exact\n plot!(x, xy, color = :red, label = \"truth\")\n end\n return p1\nend\n\np = []\nfor i in 1:n+1\n push!(p,\n plot_approximation(V, spectrum, i)\n )\nend\ndisplay(plot(p...))\nfor i in 1:n+1\n display(p[i])\n sleep(0.3)\nend\n\n## Mass Matrix and Stiffness Matrix\nMi = 𝒯 * 𝒯'\nM = inv(Mi)\nD = ClimateMachine.Mesh.Elements.spectralderivative(r)\nSᵀ = (M * D)'\n\n## Show that derivatives are not accurate for polynomials of order n+1\n# but accurate for polynomials below that order\nL = hcat([r .^ i for i in 1:n+1]...)\nDL = hcat([i * r .^(i-1) for i in 1:n+1]...)\nD * L - DL\n## Compute Differentiation Matrix (numerically unstable for large N)\nL = hcat([r .^ i for i in 0:n]...)\nDL = hcat([i * r .^ (i-1) for i in 0:n]...)\nD*L - DL\nD - DL / L # check computation of differentiation matrix\n", "meta": {"hexsha": "a62b97702dc008e1b631ace8c57df8e974d8c943", "size": 1960, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/plotting_legendre.jl", "max_stars_repo_name": "CliMA/ImperoHooks", "max_stars_repo_head_hexsha": "d19cbd335fb1d25f30b03881233a1303410c5eea", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-24T11:28:12.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-24T11:28:12.000Z", "max_issues_repo_path": "examples/plotting_legendre.jl", "max_issues_repo_name": "CliMA/ImperoHooks", "max_issues_repo_head_hexsha": "d19cbd335fb1d25f30b03881233a1303410c5eea", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-01T22:07:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-01T22:07:44.000Z", "max_forks_repo_path": "examples/plotting_legendre.jl", "max_forks_repo_name": "CliMA/ImperoHooks", "max_forks_repo_head_hexsha": "d19cbd335fb1d25f30b03881233a1303410c5eea", "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.4545454545, "max_line_length": 70, "alphanum_fraction": 0.6096938776, "num_tokens": 698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897509188344, "lm_q2_score": 0.8670357477770336, "lm_q1q2_score": 0.8156983451888808}} {"text": "\"\"\"\n trapezint(x::AbstractVector, y::AbstractVector)\n trapezint(step::Real, y::AbstractVector)\nCalculate the integral of `y` versus `x` using the trapezoidal rule.\nThe second method assumes equally-spaced `y`.\n\"\"\"\nfunction trapezint{X<:Real, Y<:Real}(x::AbstractVector{X}, y::AbstractVector{Y})\n integral::Float64 = 0.0\n @inbounds for i in 1:(length(x)-1)\n integral += (x[i+1] - x[i])*(y[i+1] + y[i])\n end\n integral *= 0.5\nend\nfunction trapezint{Y<:Real}(step::Real, y::AbstractVector{Y})\n integral::Float64 = 0.0\n @inbounds for i in 1:(length(y)-1)\n integral += step*(y[i+1] + y[i])\n end\n integral *= 0.5\nend\n\n\"\"\"\n fdderiv(x::AbstractVector, y::AbstractVector)\n fdderiv(step::Real, y::AbstractVector)\nCalculate the derivative of `y` versus `x` using the forward difference approximation.\nThe second method assumes equally-spaced `y`. Notice that the last element of the\nderivative cannot be computed and therefore it is equalled to the second-to-last.\n\"\"\"\nfunction fdderiv(x::AbstractVector, y::AbstractVector)\n der = zeros(y)\n @inbounds @simd for i in 1:length(y)-1\n der[i] = (y[i+1]-y[i])/(x[i+1] - x[i])\n end\n der[end] = der[end-1]\n return der\nend\nfunction fdderiv(x::Real, y::AbstractVector)\n der = zeros(y)\n @inbounds @simd for i in 1:length(y)-1\n der[i] = (y[i+1]-y[i])/(x)\n end\n der[end] = der[end-1]\n return der\nend\n\n\"\"\"\n fdderiv!(der::AbstractVector, x::AbstractVector, y::AbstractVector)\n fdderiv!(der::AbstractVector, step::Real, y::AbstractVector)\nCalculate the derivative of `y` versus `x` using the forward difference approximation\nand write it in-place for `der`.\nThe second method assumes equally-spaced `y`. Notice that the last element of\nthe derivative\ncannot be computed and therefore it is equalled to the second-to-last.\n\"\"\"\nfunction fdderiv!(der::AbstractVector, x::AbstractVector, y::AbstractVector)\n @inbounds @simd for i in 1:length(y)-1\n der[i] = (y[i+1]-y[i])/(x[i+1] - x[i])\n end\n der[end] = der[end-1]\n return der\nend\nfunction fdderiv!(der::AbstractVector, x::Real, y::AbstractVector)\n @inbounds @simd for i in 1:length(y)-1\n der[i] = (y[i+1]-y[i])/(x)\n end\n der[end] = der[end-1]\n return der\nend\n\n\"\"\"Return the order of magnitude of a number\"\"\"\nmag(x::Real) = ceil(log10(x))\n", "meta": {"hexsha": "9934d55adc29c23857a233cb1d1bc2d0f7cc536f", "size": 2269, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/calculus.jl", "max_stars_repo_name": "JuliaTagBot/RenewalProcesses.jl", "max_stars_repo_head_hexsha": "6d62687d27e3c8df4957d9c9d85375d156ed3a6f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/calculus.jl", "max_issues_repo_name": "JuliaTagBot/RenewalProcesses.jl", "max_issues_repo_head_hexsha": "6d62687d27e3c8df4957d9c9d85375d156ed3a6f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/calculus.jl", "max_forks_repo_name": "JuliaTagBot/RenewalProcesses.jl", "max_forks_repo_head_hexsha": "6d62687d27e3c8df4957d9c9d85375d156ed3a6f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-09-12T08:06:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T12:01:54.000Z", "avg_line_length": 31.5138888889, "max_line_length": 86, "alphanum_fraction": 0.6782723667, "num_tokens": 739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096158798117, "lm_q2_score": 0.8902942275774319, "lm_q1q2_score": 0.8156071028459748}} {"text": "#=\nIt was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square.\n\n9 = 7 + 2×1^2\n15 = 7 + 2×2^2\n21 = 3 + 2×3^2\n25 = 7 + 2×3^2\n27 = 19 + 2×2^2\n33 = 31 + 2×1^2\n\nIt turns out that the conjecture was false.\n\nWhat is the smallest odd composite that cannot be written as the sum of a prime and twice a square?\n=#\n\nusing Primes\n\nfunction nextoddcomposite(x)\n n = x\n while true\n n += 2\n if isprime(n) == false\n return n\n end\n end\nend\n\nfunction calc()\n composite = 7\n while true\n composite = nextoddcomposite(composite)\n primesless = reverse(primes(composite))\n canbecalculated = false\n for p in primesless, i in 1:54\n if p + 2*(i^2) == composite\n canbecalculated = true\n end\n end\n if canbecalculated == false\n return composite\n end\n end\nend\n@time println(calc())\n\n", "meta": {"hexsha": "c0871db605c989b80d49f5fcee5b6adf332bbb03", "size": 883, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p46.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/p46.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/p46.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 19.1956521739, "max_line_length": 126, "alphanum_fraction": 0.6489241223, "num_tokens": 287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778000158575, "lm_q2_score": 0.8519528057272543, "lm_q1q2_score": 0.8155555075839233}} {"text": "#=\n-----------------------------------------------------------------------------------------------\nThis program constructs points and weights using:\n 1) Chebyshev, \n 2) Legendre, \n 3) Lobatto, and\n 4) Equi-spaced points\n\n This constitutes Project 1 and the results are described in Secs. 3.4 and 4.4 in the textbook.\n Written by F.X. Giraldo\n Department of Applied Mathematics\n Naval Postgraduate School\n Monterey, California 93943-5216\n-----------------------------------------------------------------------------------------------\n=#\n\nusing Plots\ninclude(\"QuadraturePoints.jl\")\n\n#Some Constants\nDFloat = Float64\n#----------------------------------------Only Change this---------------------------------------\nN=4\n#-----------------------------------------------------------------------------------------------\n\nfunction main()\n\n #Allocate arrays\n ξarray=zeros(DFloat,N+1,4)\n ωarray=zeros(DFloat,N+1,4)\n\n #Some Output\n @show (N)\n\n #Chebyshev Points\n (ξ,ω) = QuadraturePoints.chebyshev_gauss(N+1)\n println(\"Chebyshev Points \") #output\n @show (ξ,ω)\n ξarray[:,1]=ξ\n ωarray[:,1]=ω\n\n #Legendre Points\n (ξ,ω) = QuadraturePoints.legendre_gauss(N+1)\n println(\"Legendre Points \") #output\n @show (ξ,ω)\n ξarray[:,2]=ξ\n ωarray[:,2]=ω\n\n #Lobatto Points\n (ξ,ω) = QuadraturePoints.lobatto_gauss(N+1)\n println(\"Lobatto Points \") #output\n @show (ξ,ω)\n ξarray[:,3]=ξ\n ωarray[:,3]=ω\n\n #Equispaced Points\n (ξ,ω) = QuadraturePoints.equispaced_points(N+1)\n println(\"Equispaced Points \") #output\n @show (ξ,ω)\n ξarray[:,4]=ξ\n ωarray[:,4]=ω\n\n #Plot Example\n plot_handle=plot(ξarray,ωarray,xlabel=\"Root\",ylabel=\"Weight\",legend=true,lw=3,label=[\"Chebyshev\" \"Legendre\" \"Lobatto\" \"Equispaced\"],title=\"Roots and Weights\")\n display(plot_handle)\n savefig(plot_handle,\"QuadraturePoints.png\")\n\n #Plot Interpolation\n println(\"Done\") #output\n\nend\n\n#Call Main Program\nmain()\n", "meta": {"hexsha": "4f4d6bf328f0751356c5bb323cee3560e442c2a6", "size": 1978, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Projects/Project_01_1D_Interpolation/For_Instructors/julia/A_Main_Driver_QuadraturePoints.jl", "max_stars_repo_name": "fxgiraldo/Element-based-Galerkin-Methods", "max_stars_repo_head_hexsha": "3e7cd28b5d6000a95b00710f15a282b9320b0007", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2019-12-28T06:19:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:40:33.000Z", "max_issues_repo_path": "Projects/Project_01_1D_Interpolation/For_Students/julia/A_Main_Driver_QuadraturePoints.jl", "max_issues_repo_name": "fxgiraldo/Element-based-Galerkin-Methods", "max_issues_repo_head_hexsha": "3e7cd28b5d6000a95b00710f15a282b9320b0007", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-29T19:12:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-29T21:53:41.000Z", "max_forks_repo_path": "Projects/Project_01_1D_Interpolation/For_Students/julia/A_Main_Driver_QuadraturePoints.jl", "max_forks_repo_name": "fxgiraldo/Element-based-Galerkin-Methods", "max_forks_repo_head_hexsha": "3e7cd28b5d6000a95b00710f15a282b9320b0007", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2020-09-10T21:35:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T06:53:34.000Z", "avg_line_length": 26.3733333333, "max_line_length": 162, "alphanum_fraction": 0.5343781598, "num_tokens": 561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966747198242, "lm_q2_score": 0.8615382165412809, "lm_q1q2_score": 0.8155292109220244}} {"text": "module problem127\n\ndescription = \"\"\"\nabc-hits\nThe radical of n, rad(n), is the product of distinct prime factors of n. For example, 504 = 23 × 32 × 7, so rad(504) = 2 × 3 × 7 = 42.\n\nWe shall define the triplet of positive integers (a, b, c) to be an abc-hit if:\nGCD(a, b) = GCD(a, c) = GCD(b, c) = 1\na < b\na + b = c\nrad(abc) < c\n\nFor example, (5, 27, 32) is an abc-hit, because:\nGCD(5, 27) = GCD(5, 32) = GCD(27, 32) = 1\n5 < 27\n5 + 27 = 32\nrad(4320) = 30 < 32\n\nIt turns out that abc-hits are quite rare and there are only thirty-one abc-hits for c < 1000, with ∑c = 12523.\nFind ∑c for c < 120000.\n\"\"\"\n\n# calculate rad(x) for x=1:n using prime sieve \nfunction radsieve(n :: Int)\n r = ones(Int, n) \n for i = 2:n\n if r[i] == 1 \n for j = i:i:n\n r[j] *= i\n end\n end\n end\n return r\nend\n\n# Calculate sum(c) for c < cmax and a,b,c is an ABC-Hit\nfunction abchits(cmax :: Int = 120000)\n # Pre-compute rad, and sort 1:cmax by rad\n r = radsieve(cmax)\n p = sortperm(r)\n\n csum = 0\n for c = 3:cmax\n radc = r[c]\n\n # rad(a*b*c) == rad(a) * rad(b) * rad(c) when a,b,c are coprime\n # rad(a)*rad(b)*rad(c) < c implies rad(a) < c / (rad(c) * rad(b))\n # using 2 as a lower bound for rad(b), max value for rad(a) is c / (2 * rad(c))\n radamax = div(c, radc * 2)\n amax = div(c, 2)\n\n # search the sorted list for suitable rad(a), a\n for i = 1:cmax\n a = p[i]\n rada = r[a]\n if rada > radamax break end # stop searching once rad(a) is too large\n if a > amax continue end # skip over a that are too large\n b = c - a\n radb = r[b]\n\n # gcd(a,c) == 1 implies gcd(a,b) == 1 and gcd(b,c) == 1\n # if there were some d that divides a and b, then d would also divide (a+b)\n if rada * radb * radc < c && gcd(a, c) == 1 \n csum += c\n end\n end\n end\n\n return csum\nend\n\t\nend", "meta": {"hexsha": "2e9984c538e19ffa4374b00a0d49230ba1d6171c", "size": 1856, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/problem127.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/problem127.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/problem127.jl", "max_forks_repo_name": "mbuhot/mbuhot-euler-solutions", "max_forks_repo_head_hexsha": "30066543cfd2d84976beb0605839750b64f4b8ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7777777778, "max_line_length": 134, "alphanum_fraction": 0.5630387931, "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966686936262, "lm_q2_score": 0.8615382058759129, "lm_q1q2_score": 0.8155291956344227}} {"text": "\"\"\"\n solve_newton is a symbolic Newton-Ralphson solver\n f is a symbolic equation to be solved (f ~ 0)\n x is the variable to solve\n x₀ is the initial guess\n\"\"\"\nfunction solve_newton(T, p, ∂p, x, x₀, zs; abstol=1e-10, maxiter=50, s=1)\n d = Dict(x => x₀)\n xₙ = x₀\n\n for i = 1:maxiter\n d[x] = xₙ\n f = T(substitute(p, d))\n f′ = T(substitute(∂p, d))\n ρ = sum(1 / (xₙ-z) for z in zs; init=0)\n xₙ₊₁ = xₙ - s*f / (f′ - s*ρ*f)\n\n if abs(xₙ₊₁ - xₙ) < abstol\n return xₙ₊₁\n else\n xₙ = xₙ₊₁\n end\n end\n return nothing\nend\n\nfunction find_roots(T, p, x; abstol=1e-8, num_roots=0)\n n = (num_roots == 0 ? poly_deg(p) : num_roots)\n abstol = T(abstol)\n\n zs = Complex{T}[]\n r = T[]\n s = Complex{T}[]\n\n while !isequal(p, 0)\n q = expand(p * x^-1)\n if !is_poly(q) break end\n push!(r, 0)\n p = q\n n -= 1\n end\n\n if isequal(p, 0) return r, s end\n\n ∂p = expand_derivatives(Differential(x)(p))\n\n while length(zs) < n\n z = solve_newton(Complex{T}, p, ∂p, x, cis(2π*rand()), zs; abstol)\n if z != nothing\n if abs(imag(z)) < abstol\n push!(zs, Complex(real(z)))\n push!(r, real(z))\n else\n if abs(real(z)) < abstol\n z = Complex(0, imag(z))\n end\n push!(zs, z)\n push!(s, z)\n\n z = conj(z)\n if abs(Complex{T}(substitute(p, Dict(x => z)))) < abstol\n push!(zs, z)\n push!(s, z)\n end\n end\n else\n break\n end\n end\n\n sort(r), s\nend\n\nfind_roots(p, x; abstol=1e-8, num_roots=0) = find_roots(Float64, p, x; num_roots, abstol)\n\nfunction find_poles(T, p, x; abstol=1e-10)\n abstol = Float64(abstol)\n ∂p = expand_derivatives(Differential(x)(p))\n\n zs = Complex{T}[]\n r = Float64[]\n s = Complex{T}[]\n\n while true\n z = solve_newton(Complex{T}, p, ∂p, x, cis(2π*rand()), zs; abstol, s=-1)\n if z != nothing\n if abs(imag(z)) < abstol\n push!(zs, Complex(real(z)))\n push!(r, real(z))\n else\n if abs(real(z)) < abstol\n z = Complex(0, imag(z))\n end\n push!(zs, z)\n push!(s, z)\n\n z = conj(z)\n if abs(Complex{Float64}(substitute(p, Dict(x => z)))) < abstol\n push!(zs, z)\n push!(s, z)\n end\n end\n else\n break\n end\n end\n\n sort(r), s\nend\n\nfind_poles(p, x; abstol=1e-10) = find_poles(Float64, p, x; abstol)\n", "meta": {"hexsha": "dfa7dbb7e3f4a10feaffd90df12d25484631834b", "size": 2759, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/roots.jl", "max_stars_repo_name": "SciML/SymbolicNumericIntegration.jl", "max_stars_repo_head_hexsha": "d27efa5c5bee5935783bc173feace2e7d2d6fe2c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 46, "max_stars_repo_stars_event_min_datetime": "2021-12-22T16:08:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T18:21:42.000Z", "max_issues_repo_path": "src/roots.jl", "max_issues_repo_name": "SciML/SymbolicNumericIntegration.jl", "max_issues_repo_head_hexsha": "d27efa5c5bee5935783bc173feace2e7d2d6fe2c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2022-02-20T23:03:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T15:33:14.000Z", "max_forks_repo_path": "src/roots.jl", "max_forks_repo_name": "siravan/SymbolicNumericIntegration.jl", "max_forks_repo_head_hexsha": "c21accaf5a9711b1df96e50cd9a112db2ce5c2bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-02-02T19:22:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T22:41:17.000Z", "avg_line_length": 24.6339285714, "max_line_length": 89, "alphanum_fraction": 0.4472635013, "num_tokens": 886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966641739773, "lm_q2_score": 0.8615382040983515, "lm_q1q2_score": 0.8155291900579387}} {"text": "import RowEchelon\nimport LinearAlgebra\n\n#=\nHomework 6\nSection 2.5\nProblems 17\n=#\n\n# Create the matrix\nA = [2 -6 4 ; -4 8 0 ; 0 -4 6]\nLU = LinearAlgebra.lu(A)\nprint(\"L = \\t\")\nprintln(LU.L)\nprint(\"U = \\t\")\nprintln(LU.U)\n\n# Create inverses of LU\ninvL = inv(LU.L)\ninvU = inv(LU.U)\nprint(\"invL = \\t\")\nprintln(invL)\nprint(\"invU = \\t\")\nprintln(invU)\n\n# Solve for invA\nprint(\"invA = \\t\")\nprintln(invU*invL)\n", "meta": {"hexsha": "518f1ad4319d2681f3f589bf600974b5c9f87662", "size": 399, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "HW6_S2.5_P17.jl", "max_stars_repo_name": "tleecsm/J4LA", "max_stars_repo_head_hexsha": "0ff51fa1771e9b5fc0b8a684a65cb36cebb8eefb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HW6_S2.5_P17.jl", "max_issues_repo_name": "tleecsm/J4LA", "max_issues_repo_head_hexsha": "0ff51fa1771e9b5fc0b8a684a65cb36cebb8eefb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW6_S2.5_P17.jl", "max_forks_repo_name": "tleecsm/J4LA", "max_forks_repo_head_hexsha": "0ff51fa1771e9b5fc0b8a684a65cb36cebb8eefb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.7586206897, "max_line_length": 30, "alphanum_fraction": 0.6441102757, "num_tokens": 159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.97112909472487, "lm_q2_score": 0.8397339676722392, "lm_q1q2_score": 0.8154900878352649}} {"text": "# indicator of a point\n\nexport IndPoint\n\n\"\"\"\n**Indicator of a singleton**\n\n IndPoint(p=0.0)\n\nReturns the indicator of the set\n```math\nC = \\\\{p \\\\}.\n```\nParameter `p` can be a scalar, in which case the unique element of `S` has uniform coefficients.\n\"\"\"\nstruct IndPoint{T <: Union{Real, Complex, AbstractArray{<:RealOrComplex}}} <: ProximableFunction\n p::T\n function IndPoint{T}(p::T) where {T <: Union{Real, Complex, AbstractArray{<:RealOrComplex}}}\n new(p)\n end\nend\n\nis_separable(f::IndPoint) = true\nis_convex(f::IndPoint) = true\nis_singleton(f::IndPoint) = true\nis_cone(f::IndPoint) = norm(f.p) == 0\nis_affine(f::IndPoint) = true\n\nIndPoint(p::T=0.0) where {T <: Union{Real, Complex, AbstractArray{<:RealOrComplex}}} = IndPoint{T}(p)\n\nfunction (f::IndPoint{R})(x::AbstractArray{T}) where {R <: RealOrComplex, T <: RealOrComplex}\n for k in eachindex(x)\n if abs(x[k] - f.p) > 1e-14\n return +Inf\n end\n end\n return zero(T)\nend\n\nfunction (f::IndPoint{A})(x::AbstractArray{T}) where {A <: AbstractArray, T <: RealOrComplex}\n for k in eachindex(x)\n if abs(x[k] - f.p[k]) > 1e-14\n return +Inf\n end\n end\n return zero(T)\nend\n\nfunction prox!(y::AbstractArray{T}, f::IndPoint{R}, x::AbstractArray{T}, gamma::Real=1.0) where {R <: RealOrComplex, T <: RealOrComplex}\n for k in eachindex(x)\n y[k] = f.p\n end\n return zero(T)\nend\n\nfunction prox!(y::AbstractArray{T}, f::IndPoint{A}, x::AbstractArray{T}, gamma::Real=1.0) where {A <: AbstractArray, T <: RealOrComplex}\n for k in eachindex(x)\n y[k] = f.p[k]\n end\n return zero(T)\nend\n\nprox!(y::AbstractArray{T}, f::IndPoint, x::AbstractArray{T}, gamma::AbstractArray) where {T <: RealOrComplex} = prox!(y, f, x, 1.0)\n\nfun_name(f::IndPoint) = \"indicator of a point\"\nfun_dom(f::IndPoint) = \"AbstractArray{Real}, AbstractArray{Complex}\"\nfun_expr(f::IndPoint) = \"x ↦ 0 if x = p, +∞ otherwise\"\nfun_params(f::IndPoint) =\n string( \"p = \", typeof(f.p) <: AbstractArray ? string(typeof(f.p), \" of size \", size(f.p)) : f.p, \", \")\n\nfunction prox_naive(f::IndPoint, x::AbstractArray{T}, gamma=1.0) where T <: RealOrComplex\n y = similar(x)\n y .= f.p\n return y, 0.0\nend\n", "meta": {"hexsha": "991a98fee43bb6c9f6c1fc90dca2bb76d653e9ce", "size": 2146, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/indPoint.jl", "max_stars_repo_name": "lostella/ProximalOperators.jl", "max_stars_repo_head_hexsha": "9935cd0c24b325667e688b5c35703dde71bfd3a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-12-15T13:57:52.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T13:57:52.000Z", "max_issues_repo_path": "src/functions/indPoint.jl", "max_issues_repo_name": "lostella/ProximalOperators.jl", "max_issues_repo_head_hexsha": "9935cd0c24b325667e688b5c35703dde71bfd3a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions/indPoint.jl", "max_forks_repo_name": "lostella/ProximalOperators.jl", "max_forks_repo_head_hexsha": "9935cd0c24b325667e688b5c35703dde71bfd3a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2368421053, "max_line_length": 136, "alphanum_fraction": 0.6533084809, "num_tokens": 716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909756, "lm_q2_score": 0.8856314828740729, "lm_q1q2_score": 0.8154803260744616}} {"text": "module FEASTsolver\n\nusing LinearAlgebra, FastGaussQuadrature\n\nexport feast, cauchynodes\n\n\"\"\"\n feast(A, M0, λmin, λmax; cpts=8, tol=1.0e-12, maxiter=20)\n feast(A, Y, zs, ws, λmin, λmax; tol=1.0e-12, maxiter=20)\n\nDetermines all the eigenvalues and vectors of an Hermitian matrix `A` inside the interval `]λmin, λmax]`. \n\n`tol` is the relative error tolerance. The error is estimated using the variation of the trace of the eigenvalues in `]λmin, λmax]`.\n`maxiter` is the number of FEAST outer iterations.\n\n`M0` is the size of the subspace search. It must be a bit larger than the number of eigenvalues in the interval. \nIt is also possible to provide an initial matrix `Y` as the initial search basis. In that case `M0=size(Y, 2)`.\n\n`cpts` is the number of Gauss-Legendre points using in the approximation of the Cauchy contour integral. \nThe nodes `zs` and weights `ws` for the quadrature rule can also be passed explicitly.\n\"\"\"\nfunction feast(A, M0::Integer, λmin::Real, λmax::Real; cpts::Integer=8, tol::Real=1.0e-12, maxiter::Integer=20)\n # initial search space of size M0\n V0 = rand(complex(eltype(A)), size(A, 1), M0)\n # contour integral nodes and and weights\n zs, ws = cauchynodes(λmin, λmax, cpts)\n \n return feast(A, V0, zs, ws, λmin, λmax; tol=tol, maxiter=maxiter)\nend\n\nfunction feast(A, Y, zs, ws, λmin::Real, λmax::Real; tol::Real=1.0e-12, maxiter::Integer=20)\n \n # dimension of problem and of subspace search\n N, M0 = size(Y)\n \n # allocate output\n ritzvals = Vector{Complex{eltype(A)}}(undef, M0)\n ritzvecs = Matrix{Complex{eltype(A)}}(undef, M0, M0)\n \n # allocate computation arrays\n Q = similar(Y)\n q = Vector{eltype(Y)}(undef, N)\n AQ = Matrix{eltype(Y)}(undef, M0, M0)\n temp = similar(Y)\n BQ = Matrix{eltype(Y)}(undef, M0, M0)\n \n \n # convercenve history\n neighistory = zeros(Int, maxiter)\n errorhistory = zeros(Float64, maxiter)\n \n # error estimation\n previous = 0.0\n rerror = 0.0 \n iter = 1\n \n # evaluate and store necessary factorizations\n F = [lu(z*I - A) for z in zs]\n \n while true\n \n # apply rational filter to Y basis\n fill!(Q, zero(eltype(Q)))\n \n for i in 1:length(zs)\n for n in axes(Y, 2)\n \n ldiv!(q, F[i], view(Y, :, n))\n \n Q[:, n] .+= ws[i]*q\n\n end\n end\n \n # form effective matrices in reduced subspace\n mul3mat!(AQ, Q, A, Q, temp)\n mul!(BQ, Q', Q)\n \n # diagonalize subspace problem\n ritzvals, ritzvecs = eigen!(Hermitian(AQ), Hermitian(BQ), sortby = λ -> (!(λmin*(1+tol) < real(λ) <= λmax*(1+tol)), real(λ), imag(λ)))\n \n # update eigenvectors\n mul!(Y, Q, ritzvecs)\n \n # determine number of eigenvalues is inside\n neig = 0\n for λ in ritzvals\n if λmin < real(λ) <= λmax\n neig += 1\n end\n end\n neighistory[iter] = neig\n \n # estimate relative error of the trace of the eigenvalues\n tr = sum(ritzvals[1:neig])\n rerror = abs(tr - previous)/abs(tr)\n previous = sum(ritzvals[1:neig])\n errorhistory[iter] = rerror\n \n if rerror >= tol \n if iter < maxiter # if tolerance is not satisfied and number of iterations small than max, go to next iteration\n iter += 1\n else # if tolerance is not satisfied but max number of iterations is exceded, throw warning and return result\n @warn \"maximum number of iterations, $maxiter, reached\"\n return ritzvals, Y, neighistory, errorhistory\n end\n else # if tolerance is satisfied, return result\n return ritzvals, Y, neighistory, errorhistory\n end\n \n end # end while\n\nend\n\nfunction mul3mat!(Out, A, B, C, temp)\n mul!(temp, B, C)\n mul!(Out, A', temp)\n return Out\nend\n\n\"\"\"\n cauchynodes(λmin, λmax, cpts)\n\nBuilds the nodes and weights for a `cpts`-points Gauss-Legendre quadrature rule along a circle in the complex plane which includes `]λmin, λmax]`.\n\"\"\"\nfunction cauchynodes(λmin, λmax, cpts)\n \n xs, ws = gausslegendre(cpts)\n \n c = (λmax + λmin)/2\n R = (λmax - λmin)/2\n \n weights = zeros(Complex{Float64}, 2*cpts)\n points = zeros(Complex{Float64}, 2*cpts)\n \n for k in 1:cpts\n weights[k] = ws[k]*R*cis(pi*(xs[k]+1)/2)/4\n points[k] = c + R*cis(pi*(xs[k]+1)/2)\n \n weights[k + cpts] = ws[k]*R*cis(-pi*(xs[k]+1)/2)/4\n points[k + cpts] = c + R*cis(-pi*(xs[k]+1)/2)\n end\n \n return points, weights\nend\n\nend\n", "meta": {"hexsha": "3bf37b7fda04181ae2744e23378e09f03132d8e0", "size": 4676, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/FEASTsolver.jl", "max_stars_repo_name": "BacAmorim/FEASTsolver.jl", "max_stars_repo_head_hexsha": "17fd43d86164cb99fadced8db2f2546d714f997a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-21T06:06:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-21T06:06:42.000Z", "max_issues_repo_path": "src/FEASTsolver.jl", "max_issues_repo_name": "BacAmorim/FEASTsolver.jl", "max_issues_repo_head_hexsha": "17fd43d86164cb99fadced8db2f2546d714f997a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/FEASTsolver.jl", "max_forks_repo_name": "BacAmorim/FEASTsolver.jl", "max_forks_repo_head_hexsha": "17fd43d86164cb99fadced8db2f2546d714f997a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5945945946, "max_line_length": 146, "alphanum_fraction": 0.5940975192, "num_tokens": 1407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067244294587, "lm_q2_score": 0.8652240930029117, "lm_q1q2_score": 0.8154795257936236}} {"text": "# A SVM solver based on the dual coordinate descent method.\n\n# The naif implementation.\nfunction svm_dualcoordinatedescent(X::AbstractMatrix,\n Y::AbstractVector,\n C::Real,\n ϵ::Real;\n maxiter::Integer=10000)\n α = C/2*ones(Y)\n w = X'*(Y.*α)\n Q = Diagonal(Y)*X*X'*Diagonal(Y)\n primal(w) = norm(w)^2/2 + C*sum(max.(0, ones(Y)-Y.*(X*w)))\n dual(α) = -α⋅(Q*α)/2 + sum(α)\n wmin = copy(w)\n wminvalue = primal(w)\n dualitygaps = [wminvalue-dual(α)]\n n = 0\n while dualitygaps[end] > ϵ && n < maxiter\n for i = 1:length(Y)\n ∇ᵢ = Q[i,:]⋅α - 1\n αᵢ = α[i]\n α[i] = min(max(α[i]-∇ᵢ/Q[i, i], 0), C)\n w += (α[i]-αᵢ)*Y[i]*X[i,:]\n end\n wvalue = primal(w)\n if wvalue < wminvalue \n wmin, wminvalue = copy(w), wvalue\n end\n push!(dualitygaps, wminvalue-dual(α))\n n += 1\n end\n wmin, α, dualitygaps\nend\n\n# Add random permutation of indices inside each outer iteration and a\n# more efficient way to compute the gradient of each univariate function.\nfunction svm_dualcoordinatedescentopt(X::AbstractMatrix,\n Y::AbstractVector,\n C::Integer,\n iter::Integer)\n α = C/2*ones(Y)\n w = X'*(Y.*α)\n Qdiag = sum(X.^2, 2)\n primal(w) = norm(w)^2/2 + C*sum(max.(0, ones(Y)-Y.*(X*w)))\n wmin = copy(w)\n wminvalue = primal(w)\n for k = 1:iter\n for i = randperm(length(Y))\n ∇ᵢ = Y[i]*w⋅X[i,:] - 1\n p∇ᵢ = α[i]==0?min(∇ᵢ, 0):α[i]==C?max(∇ᵢ, 0):∇ᵢ\n if p∇ᵢ ≠ 0\n αᵢ = α[i]\n α[i] = min(max(α[i]-∇ᵢ/Qdiag[i], 0), C)\n w += (α[i]-αᵢ)*Y[i]*X[i,:]\n end\n end\n wvalue = primal(w)\n if wvalue < wminvalue \n wmin, wminvalue = copy(w), wvalue\n end\n end\n wmin, α\nend\n", "meta": {"hexsha": "bb86e3206452d5031a148b8c34d36d3765cf35dc", "size": 1874, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "SVM/dualcoordinatedescent.jl", "max_stars_repo_name": "cyber-meow/Optimization_algos", "max_stars_repo_head_hexsha": "ae38b156fbd6ca71bf200fb8d2af7a5d5f817b68", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SVM/dualcoordinatedescent.jl", "max_issues_repo_name": "cyber-meow/Optimization_algos", "max_issues_repo_head_hexsha": "ae38b156fbd6ca71bf200fb8d2af7a5d5f817b68", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SVM/dualcoordinatedescent.jl", "max_forks_repo_name": "cyber-meow/Optimization_algos", "max_forks_repo_head_hexsha": "ae38b156fbd6ca71bf200fb8d2af7a5d5f817b68", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.28125, "max_line_length": 73, "alphanum_fraction": 0.4909284952, "num_tokens": 677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067179697694, "lm_q2_score": 0.8652240895276223, "lm_q1q2_score": 0.8154795169290612}} {"text": "# this file is for visualizing the logistic equation with different parameters\nusing PyPlot\nusing LaTeXStrings\n\nfunction general_logistic(x::Array{Float64};k::Float64=1.,x0::Float64=0.,L::Float64=1.)\n return L./(1+exp.(-k.*(x-x0)))\nend\n\nx = collect(linspace(-20.,20.,500))\n\nks = [1/3,1/2,1.,2.]\nys = zeros(length(x),length(ks))\ni = 1\nfor k in ks\n ys[:,i] = general_logistic(x,L=1.,k=k)\n i += 1\nend\n\nfig = PyPlot.figure()\nfig[:set_size_inches](6.,3.)\nax = fig[:add_subplot](1,1,1)\nfontsize = 10\nax[:set_title](LaTeXString(\"Location of \\$x_{sat}\\$ for different \\$k\\$\\n\\$x_{sat}\\\\approx 5/k\\$, or \\$k\\\\approx 5/x_{sat}\\$\"),size=fontsize)\nax[:set_xlabel](\"x\",size=fontsize)\nax[:set_ylabel](\"y\",size=fontsize)\n\nfor i = 1:length(ks)\n k = ks[i]\n k_str = LaTeXString(@sprintf(\"\\$k=%0.2f\\$\",k))\n x_str = LaTeXString(@sprintf(\"\\$x_{sat}\\\\approx %0.2f\\$\",5/k))\n lbl = LaTeXString(\"$k_str, $x_str\")\n # println(lbl)\n ax[:plot](x,ys[:,i],label=lbl)\n ax[:axvline](x=[5/k],lw=1,color=:gray,label=\"\")\nend\nfig[:tight_layout]()\nax[:legend]()\nshow()\nPyPlot.savefig(\"figs/logistic_saturation.pdf\",dpi=300,transparent=true)\n\n# conclusions, x_saturation (the x at which the logistic reaches its limit, is approximately equal to 5*k, or choose k=5/x_sat for saturation at x_sat\n", "meta": {"hexsha": "f27624772e4e48d8e8f6eb2650c2abf81c2d4156", "size": 1286, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "logistic_tests.jl", "max_stars_repo_name": "COHRINT/FaMSeC", "max_stars_repo_head_hexsha": "91fffe8913abc3c187fe70fd45892330453f6a24", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "logistic_tests.jl", "max_issues_repo_name": "COHRINT/FaMSeC", "max_issues_repo_head_hexsha": "91fffe8913abc3c187fe70fd45892330453f6a24", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "logistic_tests.jl", "max_forks_repo_name": "COHRINT/FaMSeC", "max_forks_repo_head_hexsha": "91fffe8913abc3c187fe70fd45892330453f6a24", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.619047619, "max_line_length": 150, "alphanum_fraction": 0.6594090202, "num_tokens": 437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338112885303, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.8153496668685432}} {"text": "### A Pluto.jl notebook ###\n# v0.12.16\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ b56a7126-46ba-11eb-2fdf-7f93842fc501\nmd\"## _BroadCasting_\nIn this lesson we will talk about one of the most handy, if not useful, features of Julia: **array broadcasting**. Furthermore we will deal with some important differences between Julia and other programming languages (like Python or Matlab) which make extensive use of operations on arrays and with arrays.\"\n\n# ╔═╡ 1fa5aed2-46bb-11eb-3d2c-37d60ffb1698\nmd\" ## Working with Functions and Arrays\n**Introduction**\n\nMany languages (such as Python with numpy and Matlab) make extensive use of optimised C or Fortran routines under the hood to perform fast mathematical operations, as such the user is encouraged to write vectorised code, so that these routines can perform faster for loops, as a big part of the CPU time is spent on calling the underlying compiled routine, and not computing the actual result. More or less what happens is that the user writes vectorised code which communicates to C code that can run fast for loops and the result is then returned to the user in the form of an array (or matrix).\n\nIn Julia, since for loops are already as fast as they can be (close to the speed of C) there is no need to write vectorised code, as the interpreter will directly compile your code in optimised machine code which will run as fast as possible on your machine. In Julia nothing happens under the hood (beside the compilation of the functions) and almost all the functions in Julia are written in Julia, just like all the functions in C are written in C.\n\n**Operations with Arrays**\n\nJulia by default deals with operations on arrays and matrices as one would do in mathematics.\n\nLet’s start with an example: from a mathematical point of view, we don’t know how to compute the sin of an array, as the sine function is defined only on single (dimensionless) values. At the same time the exp can work both on single values and matrices (as the exponential of a matrix has a well-defined geometrical meaning). For the same reason, you cannot multiply two arrays together, unless their size is matching correctly (i.e. one array is a row array and the other one is a column array) and in this case the multiplication of two arrays becomes the well-defined geometrical product of two arrays (which can be a scalar or a matrix, depending on the order of the multiplication):\n\"\n\n# ╔═╡ bcbc3b46-46bb-11eb-1532-c561f25a9943\na = [1,2,3]\n\n# ╔═╡ c6571362-46bb-11eb-2a5f-51ffab5cd8ab\nb = [4,5,6]\n\n# ╔═╡ ce409166-46bb-11eb-1ea6-d52e8922a64f\na*b\n\n# ╔═╡ d39e1610-46bb-11eb-2e3b-71b169116ea1\nc = [4 5 6]\n\n# ╔═╡ e41dbb1c-46bb-11eb-07d3-ebd94d38fe07\na*c\n\n# ╔═╡ 0db631e8-46bc-11eb-3684-85af439fcfb1\nc*a\n\n# ╔═╡ 1168dac0-46bc-11eb-1898-696d8b3565a5\nd = reshape([1,2,3,4,5,6,7,8,9],3,3)\n\n# ╔═╡ 1e6c7ef4-46bc-11eb-16a6-7bf5d86af426\nd*a\n\n# ╔═╡ 23dc16ae-46bc-11eb-3145-25a33518b1b2\nmd\" This makes perfectly sense from a mathematical point of view and operators behave how we would mathematically expect. Nonetheless, in programming it is often useful to write operations which work on an element by element basis, and for this reason broadcasting comes to our help.\n\"\n\n# ╔═╡ 3cf1e0e2-46bc-11eb-280d-01cb5a9b5043\nmd\" ## Broadcasting\nIn Julia, with broadcasting we indicate the action of mapping a function or an operation (which are the same in Julia) over an array or a matrix element by element.\n\nThe broadcasting notation for operators consists of adding a dot . before the operator (for example .*)\n\nConsidering the example we get:\n\"\n\n# ╔═╡ 6aef8c38-46bc-11eb-1329-8ba6c0556433\na .* c\n\n# ╔═╡ 6d66571a-46bc-11eb-0821-2fcb49952c0e\nc .* a\n\n# ╔═╡ 7844aa58-46bc-11eb-0ebf-051cad17621a\na .* d\n\n# ╔═╡ 7b144928-46bc-11eb-1c61-b76df7fe294d\nmd\"\nNotice that when we broadcast the multiplication with a matrix and an array, the array gets multiplied “in the same direction” as it is written, in the sense that if a vector is a column it gets applied column by column etc.\n\nWe can use the broadcasting notation also to map a function over an n-dimensional array. There is no speed gain in doing so, as it will be exactly equivalent to writing a for loop, but its conciseness may be useful sometimes. So the core idea in Julia is to write functions that take single values and use broadcasting when needed, unless the functions must explicitly work on arrays (for example to compute the mean of a series of values, perform matrix operations, vector multiplications, etc).\n\nTo broadcast a function over an array it is sufficient to put a dot before the brackets `.()`\n\"\n\n# ╔═╡ 8ade4caa-46bc-11eb-1ed3-938b46b63dfa\nsin.(a)\n\n# ╔═╡ a590b9a2-46bc-11eb-04b6-4703bf84cbdd\nmd\"\nIt is also possible to map a function over several values using the map function, but there are no real advantages in doing so and the broadcasting syntax is often more flexible.\n\nAs we will see in the future, in Julia it is really easy to write parallel code using multi-processing and multi-threading, and it is particularly simple to write such parallel structures when we encounter a for loop or a map function (which will become a parallel map through pmap), thus it is convenient to get used to writing your code in such paradigm.\n\nIf you are new to programming or you come from a compiled language (like C++), you should find it easy to think in terms of for loops and you should think of broadcasting as a fast and concise way to compute the value of a function over several input values.\n\"\n\n# ╔═╡ add08b24-46bc-11eb-0637-43c62f9bfc00\nmd\" ## Conclusion\nWe have learned what is broadcasting and how it can be used to perform element by element operations between vectors and how to map a function over an array using the concise broadcasting syntax.\n\nWe have also pointed out how Julia does not gain in performance by using “vectorised” notations (while other languages do) because the core Julia operations are implemented directly in the Julia language and thus there is no need to call compiled routines coded in other languages under the hood to offload all the heavy work.\n\n\"\n\n# ╔═╡ Cell order:\n# ╟─b56a7126-46ba-11eb-2fdf-7f93842fc501\n# ╟─1fa5aed2-46bb-11eb-3d2c-37d60ffb1698\n# ╠═bcbc3b46-46bb-11eb-1532-c561f25a9943\n# ╠═c6571362-46bb-11eb-2a5f-51ffab5cd8ab\n# ╠═ce409166-46bb-11eb-1ea6-d52e8922a64f\n# ╠═d39e1610-46bb-11eb-2e3b-71b169116ea1\n# ╠═e41dbb1c-46bb-11eb-07d3-ebd94d38fe07\n# ╠═0db631e8-46bc-11eb-3684-85af439fcfb1\n# ╠═1168dac0-46bc-11eb-1898-696d8b3565a5\n# ╠═1e6c7ef4-46bc-11eb-16a6-7bf5d86af426\n# ╟─23dc16ae-46bc-11eb-3145-25a33518b1b2\n# ╟─3cf1e0e2-46bc-11eb-280d-01cb5a9b5043\n# ╠═6aef8c38-46bc-11eb-1329-8ba6c0556433\n# ╠═6d66571a-46bc-11eb-0821-2fcb49952c0e\n# ╠═7844aa58-46bc-11eb-0ebf-051cad17621a\n# ╟─7b144928-46bc-11eb-1c61-b76df7fe294d\n# ╠═8ade4caa-46bc-11eb-1ed3-938b46b63dfa\n# ╟─a590b9a2-46bc-11eb-04b6-4703bf84cbdd\n# ╟─add08b24-46bc-11eb-0637-43c62f9bfc00\n", "meta": {"hexsha": "1547b214d500203271c7013283aa209e55015605", "size": 6868, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/broadcasting.jl", "max_stars_repo_name": "22natarajank/Highschool-Julia", "max_stars_repo_head_hexsha": "9d37e181178876c84aae3ebad7071cd61757daa7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-02-04T11:01:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-19T08:36:58.000Z", "max_issues_repo_path": "julia/broadcasting.jl", "max_issues_repo_name": "22natarajank/Highschool-Julia", "max_issues_repo_head_hexsha": "9d37e181178876c84aae3ebad7071cd61757daa7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/broadcasting.jl", "max_forks_repo_name": "22natarajank/Highschool-Julia", "max_forks_repo_head_hexsha": "9d37e181178876c84aae3ebad7071cd61757daa7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.7603305785, "max_line_length": 688, "alphanum_fraction": 0.776354106, "num_tokens": 2217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.9111797124237605, "lm_q1q2_score": 0.8153140058466928}} {"text": "### A Pluto.jl notebook ###\n# v0.16.1\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ f1068fca-0331-11eb-20de-a98c65d5c2dc\nbegin\n\tusing Pkg\n\tcd(joinpath(dirname(@__FILE__),\"..\"))\n Pkg.activate(pwd())\n\tusing Optim, Plots\n using Distributions\n\tusing GeneralQP\n\tusing JuMP, Ipopt\nend\n\n\n\n# ╔═╡ b4764948-0330-11eb-3669-974d75ab1134\nmd\"\"\"\n# Optimisation techniques\n\"\"\"\n\n# ╔═╡ 1b769f0c-0332-11eb-1efb-178c1985f3df\nmd\"\"\"\nWe will be using [`Optim`](https://julianlsolvers.github.io/Optim.jl/stable/) for several applications, both uni- and multivariate optimization.\n\"\"\"\n\n# ╔═╡ 165f35b0-0332-11eb-12e7-f7939d389e58\nmd\"\"\"\n## Optimizing a function without gradient information\n### Straightforward example\nFor a univariation function, you need to provide an upper and lower bound\n```Julia\noptimize(f, lower, upper)\n```\nTry to optimize $x^3 - 6x + x^2 +2$\n* Compare the result between both methods (`Brent()` vs `GoldenSection()`).\n* Intermediate results can be store by using the `store_trace=true` keyword argument. The type of the returned object is `Optim.UnivariateOptimizationResults`. The numerical value of each entry can be read by using `.value`.\n* Illustrate the evolution of the estimated optimum.\n\"\"\"\n\n# ╔═╡ 77d89aa8-07d2-11eb-1bbd-a5c896e3ecfe\nbegin\n\tf(x) = x .^3 - 6 * x + x.^2 + 2\n\tres_brent = optimize(f, 0, 10, Optim.Brent(), store_trace=true)\n\tres_golden = optimize(f, 0, 10, Optim.GoldenSection(), store_trace=true)\n\tres_brent.trace\nend\n\n# ╔═╡ f27797e5-b83f-4375-ab17-480c09fd7b7f\nlet\n\t# generating the illustration\n\tp1 = plot([v.iteration for v in res_brent.trace], [v.value for v in res_brent.trace], label=\"brent method\", marker=:circle)\n\tplot!([v.iteration for v in res_golden.trace], [v.value for v in res_golden.trace], label=\"golden section method\", marker=:circle, markeralpha=0.5)\n\ttitle!(\"function value\")\n\tp2 = plot([v.iteration for v in res_brent.trace], [v.metadata[\"minimizer\"] for v in res_brent.trace], label=\"brent method\", marker=:circle)\n\tplot!([v.iteration for v in res_golden.trace], [v.metadata[\"minimizer\"] for v in res_golden.trace], label=\"golden section method\", marker=:circle, markeralpha=0.5)\n\ttitle!(\"minimizer\")\n\t\n\tplot(p1,p2)\n\txlabel!(\"Iterations\")\nend\n\n# ╔═╡ 7bce2500-0332-11eb-2b63-87dc0d713825\n\n\n# ╔═╡ e6294d6a-0334-11eb-3829-51ee2b8cadaf\nmd\"\"\"\n### Data fitting\nSuppose we have a random periodic signal with noise, i.e. $y_i = a \\sin(x_i-b) + c + \\epsilon_i$ and we wish to determine the values of $a,b$ and $c$ that minimize the difference between the “model” and the measured points.\n\n* Define an error function\n* Determine possible values for $a,b$ and $c$\n* What is the effect of the initial values? Make an illustration of the error for different starting values.\n\"\"\"\n\n# ╔═╡ 66be5114-0335-11eb-01a9-c594b92937bf\n# data generation (simulated sample)\nbegin\n\t# actual values\n\ta = 3; b = pi/3; c=10; \n\t# noise distribution\n\te=Normal(0,0.1)\n\t# function\n\tF(x;a=a,b=b,c=c) = a*sin.(x .- b) .+ c\n\t# sample length\n\tn = 10;\n\t# domain\n\txmin = 0; xmax = 20\n\td=Uniform(xmin, xmax)\n\t# random data points (independent variable)\n\tx = sort(rand(d, n))\n\t# dependent variable with noise\n\ty = F.(x) .+ rand(e,n);\nend\n\n# ╔═╡ 15ef34dc-0336-11eb-0de5-b942e8871db8\n# illustration\nbegin\n\tsettings = Dict(:xlabel=>\"x\",:ylabel=>\"y\",:title=>\"a sin(x - b) + c\")\n\tX = range(xmin, xmax, length=50)\n\tscatter(x,y, label=\"sample\")\n\tplot!(X,F.(X), label=\"ground truth\"; settings...)\nend\n\n# ╔═╡ e949078a-07d3-11eb-0146-8115e335b2e9\nbegin\n\t\"\"\"\n\t\terrfun(v, x=x, y=y)\n\t\n\toù v = [a;b;c ] pour minimiser F(x;a=a,b=b,c=c)\n\t\"\"\"\n\tfunction errfun(v, x=x, y=y)\n\t\ta,b,c = v\n\t\treturn sum((F.(x,a=a;b=b,c=c) .- y ) .^2)\n\tend\n\t\n\tres = optimize(errfun, Float64[1;1;1])\n\ta_opt, b_opt, c_opt = res.minimizer\n\tplot(X,F.(X), label=\"ground truth\"; settings...)\n\tplot!(X, F.(X,a=a_opt, b=b_opt, c=c_opt), label=\"optimised\"; settings...)\nend\n\n# ╔═╡ 901eed25-2aea-42a4-bd7e-68b919a8766c\nres\n\n# ╔═╡ 71d2bf30-0336-11eb-28ed-95518b9204a7\n\n\n# ╔═╡ d0a304f2-0336-11eb-0d20-6de833d964b3\n\n\n# ╔═╡ add5faba-03b8-11eb-0cc7-15f19eb1e0e2\nmd\"\"\"\n## Optimisation with gradient information\nSuppose we want to minimize a function ``\\mathbb{R}^3 \\mapsto \\mathbb{R}``:\n\n``\\min g(\\bar{x}) = x_1 ^2 + 2.5\\sin(x_2) - x_1^2x_2^2x_3^2 ``\n\nCompare the results (computation time) using\n1. a zero order method (i.e. no gradients used)\n2. the function and its gradient (both newton and bfgs method)\n3. the function, its gradient and the hessian\n\nYou can evaluate the performance using the `@time` macro. For a more detailed and representative analysis, you can use the package [`BenchmarkTools`](https://github.com/JuliaCI/BenchmarkTools.jl) (we will go into detail in the session about performance)\n\"\"\"\n\n# ╔═╡ 9396ccae-03ba-11eb-27a9-1b88ee4fb45f\nbegin \n\tg(x) = x[1]^2 + 2.5*sin(x[2]) - x[1]^2*x[2]^2*x[3]^2\n\tinitial_x = [-0.6;-1.2; 0.135];\nend\n\n# ╔═╡ 94abb7a2-03bb-11eb-1ceb-1dff8aa3cce7\nbegin\n\t# gradients\n\tfunction dg!(G, x)\n\t\tG[1] = 2*x[1] - 2*x[1]*x[2]^2*x[3]^2\n\t\tG[2] = 2.5*cos(x[2]) - 2*x[1]^2*x[2]*x[3]^2\n\t\tG[3] = -2*x[1]^2*x[2]^2*x[3]\n\tend\n\n\tfunction h!(H,x)\n\t\tH[1,1] = 2 - 2*x[2]^2*x[3]^2 \n\t\tH[1,2] = -4*x[1]*x[2]*x[3]^2 \n\t\tH[1,3] = -4*x[1]*x[2]^2*x[3]\n\t\tH[2,1] = -4*x[1]*x[2]*x[3]^2 \n\t\tH[2,2] = -2.5*sin(x[2]) - 2*x[1]^2*x[3]^2\n\t\tH[2,3] = -4*x[1]^2*x[2]*x[3]\n\t\tH[3,1] = -4*x[1]*x[2]^2*x[3]\n\t\tH[3,2] = -4*x[1]^2*x[2]*x[3]\n\t\tH[3,3] = -2*x[1]^2*x[2]^2\n\tend\nend\n\n# ╔═╡ 6f552aa6-07d5-11eb-18a5-b32ed233c403\nbegin\n\tprintln(\"start method comparison\")\n\tfor _ in 1:2\n\t\t@time optimize(g, initial_x)\n\t\t@time optimize(g, dg!, initial_x, Newton())\n\t\t@time optimize(g, dg!, initial_x, BFGS())\n\t\t@time optimize(g, dg!, h!, initial_x)\n\tend\n\tprintln(\"finished method comparison\")\nend\n\n# ╔═╡ 966b88dc-03bc-11eb-15a4-b5492ddf4ede\nmd\"\"\"\n## Optimize the optimizer\nYou could study the influence of the optimization methods and try to optimize them as well (this is sometimes refered to as hyperparameter tuning). \n\nTry to create a method that minimizes the amount of iterations by modifying the parameter $\\eta$ from the `BFGS` method.\n\n**Note:** \n* Look at the documentation for possible values of $\\eta$.\n* This is merely as a proof of concept and will not come up with a significant improvement for this case.\n\n\"\"\"\n\n# ╔═╡ 68263aea-07d0-11eb-24f8-6383a3a1e09d\nbegin\n\tfunction optimme(η)\n\t\tres = optimize(g, dg!, initial_x,ConjugateGradient(eta=η))\n\t\treturn res.iterations\n\tend\n\t\n\toptimize(optimme, 0, 20)\nend\n\n# ╔═╡ d5feb956-058b-11eb-1a7d-eb56768f00b1\n\n\n# ╔═╡ ec264b44-03c2-11eb-1695-cbf638f8cea9\nmd\"\"\"\n## Sequential Quadratic Programming\n**Reminder**: typical problem layout:\n\n\n\n```math\n\\begin{align}\n\\min_{\\vec{x}}\\, & f\\left(\\vec{x}\\right)\\, \\textrm{subject to}\\, \\begin{cases}\n\\vec{h}\\left(\\vec{x}\\right)=\\vec{0}\\, \\\\\n\\vec{g}\\left(\\vec{x}\\right)\\leq\\vec{0}\n\\end{cases}\n\\end{align}\n```\n\nwhere ``f:\\mathbb{R}^{n}\\rightarrow\\mathbb{R}``, ``\\vec{h}:\\mathbb{R}^{n}\\rightarrow\\mathbb{R}^{m}``,\n``m\\leq n, \\text{and } \\vec{g}:\\mathbb{R}^{n}\\rightarrow\\mathbb{R}^{p}``.\n\n\nThis allows you to deal with non-linear constraints. \n\nTry to solve the following problem:\n```math\n\\begin{align}\n\\min_{\\bar{x}} f(\\bar{x}) = -x_1 - x_2 \\\\\n\\text{ST:} \\begin{cases}-x_1^2 + x_2 \\ge 0\\\\1- x_1^2 - x_2^2 \\ge 0\\end{cases}\n\\end{align}\n```\n\n\n1. Solve the problem with [NLopt](https://github.com/JuliaOpt/NLopt.jl) (placed in a seperate notebook)\n2. Solve the problem with [JuMP](https://github.com/jump-dev/JuMP.jl) (combined with [Ipopt](https://github.com/jump-dev/Ipopt.jl))\n\"\"\"\n\n# ╔═╡ 02aedfec-d075-425b-8db6-e60d5d8a79c3\nmodel\n\n# ╔═╡ 053bae8a-087d-11eb-2e8c-73c41fb4e005\nlet \n\tmodel = Model(Ipopt.Optimizer)\n\t@variable(model, x[1:2])\n\t@objective(model, Min, -x[1] - x[2])\n\t@constraint(model, - x[1] ^2 + x[2] >= 0)\n\t@constraint(model, 1 - x[1] ^2 - x[2] ^2 >= 0)\n\toptimize!(model)\n\tprintln(termination_status(model))\n\tprintln(\"minimum: $(objective_value(model))\")\n\tvalue.(x)\nend\n\n# ╔═╡ b5cf333b-5ffa-45d5-b9c0-00abc4b63196\n\n\n# ╔═╡ Cell order:\n# ╟─b4764948-0330-11eb-3669-974d75ab1134\n# ╟─1b769f0c-0332-11eb-1efb-178c1985f3df\n# ╠═f1068fca-0331-11eb-20de-a98c65d5c2dc\n# ╟─165f35b0-0332-11eb-12e7-f7939d389e58\n# ╠═77d89aa8-07d2-11eb-1bbd-a5c896e3ecfe\n# ╠═f27797e5-b83f-4375-ab17-480c09fd7b7f\n# ╟─7bce2500-0332-11eb-2b63-87dc0d713825\n# ╟─e6294d6a-0334-11eb-3829-51ee2b8cadaf\n# ╠═66be5114-0335-11eb-01a9-c594b92937bf\n# ╠═15ef34dc-0336-11eb-0de5-b942e8871db8\n# ╠═e949078a-07d3-11eb-0146-8115e335b2e9\n# ╠═901eed25-2aea-42a4-bd7e-68b919a8766c\n# ╟─71d2bf30-0336-11eb-28ed-95518b9204a7\n# ╟─d0a304f2-0336-11eb-0d20-6de833d964b3\n# ╟─add5faba-03b8-11eb-0cc7-15f19eb1e0e2\n# ╠═9396ccae-03ba-11eb-27a9-1b88ee4fb45f\n# ╠═94abb7a2-03bb-11eb-1ceb-1dff8aa3cce7\n# ╠═6f552aa6-07d5-11eb-18a5-b32ed233c403\n# ╟─966b88dc-03bc-11eb-15a4-b5492ddf4ede\n# ╠═68263aea-07d0-11eb-24f8-6383a3a1e09d\n# ╠═d5feb956-058b-11eb-1a7d-eb56768f00b1\n# ╟─ec264b44-03c2-11eb-1695-cbf638f8cea9\n# ╠═02aedfec-d075-425b-8db6-e60d5d8a79c3\n# ╠═053bae8a-087d-11eb-2e8c-73c41fb4e005\n# ╠═b5cf333b-5ffa-45d5-b9c0-00abc4b63196\n", "meta": {"hexsha": "b3fdf00dcd38549d850aff29f53d1c331a1b27b8", "size": 8909, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Exercises/PS04 - Optimisation techniques 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/PS04 - Optimisation techniques 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/PS04 - Optimisation techniques 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": 30.097972973, "max_line_length": 253, "alphanum_fraction": 0.6871702772, "num_tokens": 3749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.9111797075998822, "lm_q1q2_score": 0.8153140015303373}} {"text": "#=\n What is the color of the taxi?\n\n From https://www.bayesia.com/2018-03-02-probabilistic-reasoning-under-uncertainty\n\n Originally from Kahnemann, Slovic, Tversky \"Judgement under uncertainty\"\n \n\n There has been an accicent involving a taxi.\n There are two kinds of taxis:\n - yellow taxi: 85% \n - white taxi: 15%\n\n A witness say: It was a white taxi involved in the accident.\n\n Researcher:\n - 80% of all witness statements are true\n - 20% of all witness statements are false.\n\n What is the probability that it was a white taxi involved in\n the accident?\n\n Answer: The probability that it was a white taxi involved in the accident\n is about 41-42%. And it's the same as in the talk.\n \n This model:\n Distributions of variable involved\n yellow => 5897 (0.589700)\n white => 4103 (0.410300)\n\n Distributions of variable witness_white (num:0)\n 1.00000 => 9999 (0.999900)\n 0.00000 => 1 (0.000100)\n\n Distributions of variable witness_yellow (num:0)\n 1.00000 => 5614 (0.561400)\n 0.00000 => 4386 (0.438600)\n\n Cf ~/blog/color_of_the_taxi.blog\n ~/psi/color_of_the_taxi.psi\n ~/webppl/color_of_the_taxi.wppl\n\n\n=#\n\nusing Turing, StatsPlots, DataFrames\ninclude(\"jl_utils.jl\")\n\n@model function color_of_the_taxi()\n white = 1\n yellow = 2\n # Prior distributions of the different taxis.\n involved ~ Categorical([0.15,0.85]) # [white,yellow]\n \n # Witness says color but is is only x percent reliable.\n # Witness experts states that a witness can only be 80% reliable\n # (given the same circumstances as the accidents).\n witness = tzeros(2)\n for c in 1:2\n if c == involved\n witness[c] ~ flip(0.80)\n else\n witness[c] ~ flip(0.20)\n end\n end\n \n true ~ Dirac(witness[white] == true)\n # true ~ Dirac(witness[yellow] == true)\n\n witness_white ~ Dirac(witness[white])\n witness_yellow ~ Dirac(witness[yellow])\n\nend\n\nmodel = color_of_the_taxi()\nnum_chains = 4\n\n# chns = sample(model, Prior(), 10_000)\n# chns = sample(model, MH(), 10_000)\nchns = sample(model, PG(5), 10_000)\n# chns = sample(model, SMC(), 10_000)\n# chns = sample(model, IS(), 10_000)\n\ndisplay(chns)\n# display(plot(chns))\n\nprintln(\"white: 1 yellow: 2\")\nshow_var_dist_pct(chns,:involved,[\"white\",\"yellow\"])\nshow_var_dist_pct(chns,:witness_white)\nshow_var_dist_pct(chns,:witness_yellow)\n", "meta": {"hexsha": "cc29e958697c97897ecefcd17ee8d5fd961060cd", "size": 2400, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/color_of_the_taxi.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/turing/color_of_the_taxi.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/turing/color_of_the_taxi.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 26.3736263736, "max_line_length": 83, "alphanum_fraction": 0.66625, "num_tokens": 731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.894789454880027, "lm_q1q2_score": 0.8153139960192188}} {"text": "module NumericalDifferentiation\n\nexport differentiate, integrationoperator, TotalVariation, Tikhonov\n\nusing LinearAlgebra, SparseArrays\nusing LinearMaps, IterativeSolvers\n\nabstract type DifferentiationMethod end\n\nstruct TotalVariation{T<:AbstractFloat} <: DifferentiationMethod\n ϵ::T\nend\nTotalVariation() = TotalVariation(1e-12)\n\nstruct Tikhonov <: DifferentiationMethod end\n\n\"\"\"\n\tdiffmatrix(x::AbstractVector)\n\nGenerate differentiation matrix from node positions `x`.\n\"\"\"\nfunction diffmatrix(x::AbstractVector)\n D = zeros(eltype(x), length(x)-1, length(x))\n for i in 1:size(D,1)\n D[i,i] = -1/(x[i+1]-x[i])\n D[i,i+1] = 1/(x[i+1]-x[i])\n end\n return D\nend\n\n\"\"\"\n\tspdiffmatrix(x::AbstractVector)\n\nGenerate sparse differentiation matrix from node positions `x`.\n\"\"\"\nfunction spdiffmatrix(x::AbstractVector)\n el = 1 ./diff(x)\n I = [1:length(x)-1;1:length(x)-1]\n J = [1:length(x)-1;2:length(x)]\n K = [-el;el]\n\n return sparse(I,J,K)\nend\n\n\"\"\"\n\tintgmatrix(x::AbstractVector)\n\nGenerate integration matrix using Trapezoidal rule from node positions `x`.\n\"\"\"\nfunction intgmatrix(x::AbstractVector)\n K = zeros(eltype(x), length(x), length(x))\n for j in 2:size(K,2), i in j:size(K,1)\n K[i,j-1] += .5*(x[j] - x[j-1])\n K[i,j] += .5*(x[j] - x[j-1]) \n end\n return K\nend\n\n\"\"\"\n\tintegrationoperator(x,y)\n\nIntegration operator using trapezoidal rule. Return the integral ``\\\\int_0^x y(u)du`` for all `x`. This code is reproduced from NumericalIntegration.jl (copied to avoid unnecessary dependencies and compatibility issues).\n\"\"\"\nfunction integrationoperator(x,y)\n retarr = zeros(eltype(x),size(x)) + zeros(eltype(y),size(y))\n for i in 2 : length(y)\n retarr[i] = retarr[i-1] + (x[i] - x[i-1]) * (y[i-1] + y[i])\n end\n return 0.5 * retarr\nend\n\n\"\"\"\n\tintegrationadjoint(x,y)\n\nAdjoint of integration operator. Constructed such that the corresponding matrix is truly the transpose of the matrix of the integration operator.\n\"\"\"\nfunction integrationadjoint(x,y)\n z = zeros(eltype(x),size(x)) + zeros(eltype(y),size(y))\n N = length(z)\n \n z[N] = y[N]*(x[N]-x[N-1])\n\n sumy = y[N]\n \n for i in N-1:-1:2\n z[i] = (x[i]-x[i-1])*y[i] + (x[i+1]-x[i-1])*sumy\n sumy += y[i]\n end\n\n z[1] = (x[2]-x[1])*sumy\n \n return 0.5*z\nend\n\n\"\"\"\n\tdiffoperator(du,Δx,D)\n\nConstruct differentiation operator for TV method.\n\"\"\"\nfunction diffoperator(du,Δx,D,epsilon)\n psi = Diagonal(1 ./sqrt.(du.^2 .+ epsilon))\n δx = Diagonal(Δx)\n return (D')*(δx*psi)*D\nend\n\n\"\"\"\n\tdifferentiate(x::AbstractVector, f::AbstractVector, tv::TotalVariation, α, tol; maxit=2000, pbsize=:auto, verbose=false, precond=false, u0=[0;diff(f)])\n\nCompute the derivative of vector `f` defined at positions `x`, using Total Variation regularisation with parameter `α`. The method is described in Chartrand, R. (2011), \"Numerical Differentiation of Noisy, Nonsmooth Data\", ISRN Appl. Math., doi:10.5402/2011/164564.\n\n# Arguments\n- `x::AbstractVector`: x coordinates where vector f is defined.\n- `f::AbstractVector`: input vector to take derivative of.\n- `tv::TotalVariation`: instance of TotalVariation type to specify method.\n- 'α': regularisation parameter.\n- 'tol': tolerance on magnitude of gradient to stop iterations.\n\n# Optional keyword arguments\n- `maxit=2000`: maximum number of iterations.\n- 'pbsize=:auto': if `:auto` (default), selects the matrix-based computation method only for problems with less than 1001 points. Enforce use of matrix-based method if set to `:small`, and enforce use of matrix-free method is set to `:large`.\n- verbose=false. if true, shows convergence info.\n- precond=false. if true, use simple preconditioner. Not used for small systems.\n- 'u0=[0;diff(f)]': Can be used to set initial guess for derivative.\n\n\"\"\"\nfunction differentiate(x::AbstractVector, f::AbstractVector, tv::TotalVariation, α, tol; maxit=2000, pbsize=:auto, verbose=false, precond=false, u0=[0;diff(f)])\n\n (length(x) == length(f)) || throw(DimensionMismatch(\"Inputs `x` and `f` should have same dimension\"))\n\n c = 0\n u = u0\n Δx = diff(x)\n\n if pbsize==:small || (pbsize==:auto && length(f)<1001)\n D = diffmatrix(x)\n A = intgmatrix(x)\n df = A'*(f .- f[1])\n \n keep = true\n\n while keep && ctol)\n \n !verbose || print(\"iteration $c | change $(norm(s)/norm(u)) | grad $(norm(g))\\r\")\n\n end\n elseif pbsize==:large || (pbsize==:auto && length(f)>=1001)\n D = spdiffmatrix(x)\n df = integrationadjoint(x, f .- f[1])\n\n keep = true\n \n while keep && c integrationadjoint(x, integrationoperator(x,v)) + α*L*v, length(x))\n if precond\n P = Diagonal(α*diag(L) .+1)\n else\n P = I\n end\n # QN step\n s = cg(H, -g, Pl=P)\n\n u += s\n\n keep = (norm(s)/norm(u)>tol)\n\n !verbose || print(\"iteration $c | change $(norm(s)/norm(u)) | grad $(norm(g))\\r\")\n\n end\n\n end\n\n !verbose || println(\"\\nMax. iterations $c\")\n \n return u\nend\n\n\"\"\"\n\tdifferentiate(x::AbstractVector, f::AbstractVector, ::Tikhonov, α; pbsize=:auto)\n\nCompute the derivative of vector `f` defined at positions `x`, using Tikhonov regularisation with parameter `α`. Optional keyword argument `pbsize` can be set to `:small` (uses matrix-based method), `:large` (uses matrix-free method), or `:auto` (default; chooses matrix-based method if `f` has less than 1001 points).\n\n\"\"\"\nfunction differentiate(x::AbstractVector, f::AbstractVector, ::Tikhonov, α; pbsize=:auto, maxit=length(x))\n if pbsize==:small || (pbsize==:auto && length(f)<1001)\n D = diffmatrix(x)\n A = intgmatrix(x)\n r = A'*(f .- f[1])\n δ = tr(D'D)/length(x)^3\n H = (α/δ)*D'D + A'A\n u = H\\r \n elseif pbsize==:large || (pbsize==:auto && length(f)>=1001)\n D = spdiffmatrix(x)\n δ = tr(D'D)/length(x)^3\n L = (α/δ)*D'D\n r = integrationadjoint(x, f .- f[1])\n H = LinearMap(v -> integrationadjoint(x, integrationoperator(x,v)) + L*v, length(x))\n u, ch = cg(H, r; log=true, maxiter=maxit)\n\n ch.isconverged || @warn \"Solver did not converge after $(ch.iters) iterations. Result might be inaccurate.\"\n end\n\n return u\nend\n\nend\n", "meta": {"hexsha": "99dc577ef1a1bf7a2e03d44de4bcff57cb424461", "size": 6996, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NumericalDifferentiation.jl", "max_stars_repo_name": "nbrantut/NumericalDifferentiation.jl", "max_stars_repo_head_hexsha": "a522539b9a78906b6bdd695f1cc0e2361890a7ec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-18T07:54:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T16:09:32.000Z", "max_issues_repo_path": "src/NumericalDifferentiation.jl", "max_issues_repo_name": "nbrantut/NumericalDifferentiation.jl", "max_issues_repo_head_hexsha": "a522539b9a78906b6bdd695f1cc0e2361890a7ec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NumericalDifferentiation.jl", "max_forks_repo_name": "nbrantut/NumericalDifferentiation.jl", "max_forks_repo_head_hexsha": "a522539b9a78906b6bdd695f1cc0e2361890a7ec", "max_forks_repo_licenses": ["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.4173913043, "max_line_length": 318, "alphanum_fraction": 0.6014865638, "num_tokens": 2047, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741322079104, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.8152616601191418}} {"text": "using LinearAlgebra\nusing FFTW\nusing Pipe.Pipe\n\n\"\"\"\nCooley-Tukey recursive Fast Walsh-Hadamard Transform.\n\"\"\"\nfunction fwht(x::Array{Float64,1}; recurses=false)\n N = length(x)\n if N == 1\n return x\n else\n X_even = fwht(x[1 : N÷2]; recurses=true)\n X_odd = fwht(x[N÷2+1 : N]; recurses=true)\n res = cat(X_even + X_odd, X_even - X_odd, dims=1)\n return res\n end\nend\n\n\"\"\"\nTakes in a binary array and returns the corresponding integer.\n\"\"\"\nfunction bin_to_dec(x::AbstractArray{Bool})\n return 2 .^(length(x)-1 : -1 : 0) ⋅ x\nend\n\n\"\"\"\nTakes in an integer and returns the corresponding binary array.\n\"\"\"\nfunction dec_to_bin(x::Int64, num_bits::Int64)\n @assert x < 2^num_bits \"number of bits too small\"\n return @pipe string(x, base=2) |> lpad(_, num_bits, \"0\") |> split(_, \"\") |> parse.(Bool, _)\nend\n\n\"\"\"\nReturns a matrix where row 'i' is dec_to_bin(i, m),\nfor i from 0 to 2 ** m - 1.\n\"\"\"\nfunction binary_ints(m::Int64)\n return @pipe dec_to_bin.(0:2^m-1, m) |> hcat(_...)\nend\n\n\"\"\"\nSign function that matches the convention (footnote 2 on page 11):\nreturns 0 for positive reals and 1 for negative reals.\n\"\"\"\nfunction sign_spright(x)\n return Bool(x < 0)\nend\n\nfunction expected_bin(k::BitArray{1}, M::BitArray{2})\n return @pipe M'k .% 2 |> Bool.(_) |> bin_to_dec(_) + 1\nend\n", "meta": {"hexsha": "76eaf5e83ed4a4fbc23e981821229ba4e66c902f", "size": 1323, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "aditya-sengupta/SparseTransforms.jl", "max_stars_repo_head_hexsha": "29a88045e154f6102821c8557e0afd0fa0508941", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-11-10T00:50:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-14T11:44:20.000Z", "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "aditya-sengupta/SparseTransforms.jl", "max_issues_repo_head_hexsha": "29a88045e154f6102821c8557e0afd0fa0508941", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-12-12T06:34:23.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-12T06:34:25.000Z", "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "aditya-sengupta/SparseTransforms.jl", "max_forks_repo_head_hexsha": "29a88045e154f6102821c8557e0afd0fa0508941", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5, "max_line_length": 95, "alphanum_fraction": 0.6447467876, "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542840900508, "lm_q2_score": 0.8499711832583695, "lm_q1q2_score": 0.8152535017753547}} {"text": "## Julia program for Generation of Gamma Random Variable\r\n## author: weiya \r\n## date: 2018-08-21\r\n\r\n## sample from Ga(a, beta)\r\nfunction rgamma_int(a::Int, beta)\r\n u = rand(a)\r\n return(-1.0 / beta * sum(log.(u)))\r\nend\r\n\r\n## density of Ga(alpha, beta)\r\ninclude(\"func_gamma.jl\")\r\nfunction dgamma(x, alpha, beta)\r\n return(beta^alpha / lanczos_gamma(alpha) * x^(alpha-1) * exp(-1*beta*x))\r\nend\r\n\r\n## accept-reject algorithm\r\nfunction rgamma(alpha = 1.5, beta = 2.1)\r\n a = Int(floor(alpha))\r\n b = a * beta / alpha\r\n #M = exp(a * (log(a) - 1) - alpha * (log(alpha) - 1))\r\n M = exp(alpha * (log(alpha) - 1) - a * (log(a) - 1))\r\n while true\r\n x = rgamma_int(a, b)\r\n u = rand()\r\n cutpoint = dgamma(x, alpha, beta)/(M*dgamma(x, a, b))\r\n if u <= cutpoint\r\n return x\r\n end\r\n end\r\nend\r\n\r\n# example\r\nprintln(rgamma())\r\n\r\n", "meta": {"hexsha": "77fae75f2ecba4a09a7b6819c64c3601823c226d", "size": 901, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "GenRV/gamma.jl", "max_stars_repo_name": "szcf-weiya/MCMC", "max_stars_repo_head_hexsha": "b5353bdd8ca1578a2023676458ab231a413a2b46", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2017-07-19T12:50:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T08:06:50.000Z", "max_issues_repo_path": "GenRV/gamma.jl", "max_issues_repo_name": "szcf-weiya/MCMC", "max_issues_repo_head_hexsha": "b5353bdd8ca1578a2023676458ab231a413a2b46", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-02-03T15:08:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-05T15:41:39.000Z", "max_forks_repo_path": "GenRV/gamma.jl", "max_forks_repo_name": "szcf-weiya/MCMC", "max_forks_repo_head_hexsha": "b5353bdd8ca1578a2023676458ab231a413a2b46", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-07-19T12:50:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T08:06:52.000Z", "avg_line_length": 25.0277777778, "max_line_length": 77, "alphanum_fraction": 0.5560488346, "num_tokens": 283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542817548989, "lm_q2_score": 0.8499711756575749, "lm_q1q2_score": 0.8152534925002082}} {"text": "function vandermonde_matrix(offsets::Array{Int64, 1})\n num_points = size(offsets)[1]\n ret_matrix = reshape([0 // 1 for i in 1:num_points ^ 2],\n (num_points, num_points))\n for i in 1:num_points\n ret_matrix[1, i] = 1 // 1\n end\n for i in 2:num_points\n for j in 1:num_points\n ret_matrix[i, j] = ret_matrix[i - 1, j] * offsets[j]\n end\n end\n return ret_matrix\nend # vandermonde_matrix\n\nfunction scheme_coefficients(offsets::Array{Int64, 1})\n num_points = size(offsets)[1]\n coefficient_matrix = vandermonde_matrix(offsets)\n right_vector = reshape([0 // 1 for i in 1:num_points],\n (num_points, 1))\n right_vector[2, 1] = 1 // 1\n return reshape(coefficient_matrix \\ right_vector, (num_points, ))\nend # scheme_coefficients\n\nfunction rational_flux_coefficients(offsets::Array{Int64, 1})\n num_points = size(offsets)[1]\n coeff = scheme_coefficients(offsets)\n ret = [0 // 1 for i in 1:num_points]\n for i in 2:num_points\n ret[i] = ret[i - 1] - coeff[i - 1]\n end\n return ret[2:num_points]\nend # rational_flux_coefficients\n\nfunction float_flux_coefficients(offsets::Array{Int64, 1})\n rational_coeff = rational_flux_coefficients(offsets)\n num_points = size(rational_coeff)[1]\n return [float(rational_coeff[i]) for i in 1:num_points]\nend # float_flux_coefficients\n", "meta": {"hexsha": "ce1b84afba98a9914c18dab4597d23fb9a358155", "size": 1396, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/linear_scheme_coefficients.jl", "max_stars_repo_name": "jian-kang-computational-physics/FiniteDifferenceSchemes.jl", "max_stars_repo_head_hexsha": "52e5018a9f4734140ddaf5b20ae963a5ce805a65", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/linear_scheme_coefficients.jl", "max_issues_repo_name": "jian-kang-computational-physics/FiniteDifferenceSchemes.jl", "max_issues_repo_head_hexsha": "52e5018a9f4734140ddaf5b20ae963a5ce805a65", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/linear_scheme_coefficients.jl", "max_forks_repo_name": "jian-kang-computational-physics/FiniteDifferenceSchemes.jl", "max_forks_repo_head_hexsha": "52e5018a9f4734140ddaf5b20ae963a5ce805a65", "max_forks_repo_licenses": ["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.9, "max_line_length": 69, "alphanum_fraction": 0.6611747851, "num_tokens": 399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109742068042, "lm_q2_score": 0.8577681013541613, "lm_q1q2_score": 0.8152322168515291}} {"text": "# ---\n# title: 1523. Count Odd Numbers in an Interval Range\n# id: problem1523\n# author: zhwang\n# date: 2022-03-18\n# difficulty: Easy\n# categories: Math\n# link: \n# hidden: true\n# ---\n# \n# Given two non-negative integers `low` and `high`. Return the _count of odd\n# numbers between_`low` _and_` high` _ (inclusive)_.\n# \n# \n# \n# **Example 1:**\n# \n# \n# \n# Input: low = 3, high = 7\n# Output: 3\n# Explanation: The odd numbers between 3 and 7 are [3,5,7].\n# \n# **Example 2:**\n# \n# \n# \n# Input: low = 8, high = 10\n# Output: 1\n# Explanation: The odd numbers between 8 and 10 are [9].\n# \n# \n# \n# **Constraints:**\n# \n# * `0 <= low <= high <= 10^9`\n# \n# \n## @lc code=start\nusing LeetCode\n\ncount_odd_numbers(low::Int, high::Int) = (high - low + 1 + (low & 1)) >> 1\n\n## @lc code=end\n", "meta": {"hexsha": "7fb270ba9eacf47f2b470f33da6941af59d6ad6c", "size": 895, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/1523.count-odd-numbers-in-an-interval-range.jl", "max_stars_repo_name": "RexWzh/LeetCode.jl", "max_stars_repo_head_hexsha": "d86109b9d5a15491304ff9d2ee66e506f60d2146", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/problems/1523.count-odd-numbers-in-an-interval-range.jl", "max_issues_repo_name": "RexWzh/LeetCode.jl", "max_issues_repo_head_hexsha": "d86109b9d5a15491304ff9d2ee66e506f60d2146", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/problems/1523.count-odd-numbers-in-an-interval-range.jl", "max_forks_repo_name": "RexWzh/LeetCode.jl", "max_forks_repo_head_hexsha": "d86109b9d5a15491304ff9d2ee66e506f60d2146", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.4565217391, "max_line_length": 91, "alphanum_fraction": 0.5832402235, "num_tokens": 314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768620069626, "lm_q2_score": 0.8633916222765629, "lm_q1q2_score": 0.8151943926041859}} {"text": "\"\"\"\n weibull_rng(λ, β, shape=1; seed=nothing)\n\nGenerate a `shape` element array of random variables from a Weibull(`λ`, `β`) distribution. Optionally you can set a specific seed.\n\n# Notes\n\nThe pdf of an Weibull(λ, β) distribution is given as:\n\n``f(x, λ, β) = λ e^{-λx^β} \\\\quad x ≥ 0``\n\n# Examples\n\n```julia-repl\njulia> weibull_rng(2, 2, seed=42)\n1-element Vector{Float64}:\n 0.31445725834527055\n\njulia> weibull_rng(2, 2, 2)\n2-element Vector{Float64}:\n 0.39561285703154575\n 0.6021921673483441\n\njulia> weibull_rng(2, 2, (2,2))\n2×2 Matrix{Float64}:\n 0.428896 0.109897\n 0.812854 0.427906\n \n```\n\n# References\n\nC. Alexopoulos, D. Goldsman. Random variate generation. 2020.\n\nLaw, A. Simulation modeling and analysis, 5th Ed. McGraw Hill Education, Tuscon, 2013.\n\"\"\"\nfunction weibull_rng(λ::Real, β::Real, shape::Union{Int, Tuple{Vararg{Int}}}=1; seed::Union{Int, Nothing}=nothing)\n U = get_std_uniform(shape, seed=seed)\n X = (1/λ) .* (-log.(1 .- U)) .^ (1/β)\n return X\nend\n", "meta": {"hexsha": "d0fdb3920510f1decffb5061a9f360c8bb4f2cc2", "size": 980, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/weibull.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/weibull.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/weibull.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.3333333333, "max_line_length": 131, "alphanum_fraction": 0.6795918367, "num_tokens": 368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.8723473829749844, "lm_q1q2_score": 0.815117174707066}} {"text": "function golden(f::Function, xl::Number, xu::Number, ea::Number, maxIter::Int64)\n # Estimate the optimum of a function using the golden-section search method\n # Interesting note, removing array allocations from this function improved execution\n # time by a factor of 100!\n\n const ϕ = (1+sqrt(5)) / 2; # Hope you like unicode 'cause I'm using it\n xo = NaN; # Current estimate for the optimum\n\n # Calculate x1, x2 & f(x1), f(x2) for the initial lower and upper bounds\n x1 = xl + (xu - xl) / ϕ; # Upper test point\n x2 = xu - (xu - xl) / ϕ; # Lower test point\n\n f1 = f(x1);\n f2 = f(x2);\n\n for i = 1:maxIter\n if f1 > f2\n # The optimum is to the left of x1. Make the upper bound x1, set the\n # upper test point to the previous lower test point and calculate a\n # new lower test point for the new upper bound.\n xo = x2;\n xu = x1;\n x1 = x2;\n f1 = f2;\n x2 = xu - (xu - xl) / ϕ;\n f2 = f(x2);\n\n err = abs((x2 - xl) / xo) * 100;\n\n if err < ea\n break;\n end\n\n else\n # The optimum is to the right of x1. Make the lower bound x2, set the\n # lower test point to the previous upper test point and calculate a\n # new upper test point for the new lower bounds.\n xo = x1;\n xl = x2;\n x2 = x1;\n f2 = f1;\n x1 = xl + (xu - xl) / ϕ;\n f1 = f(x1);\n\n err = abs((x2 - xl) / xo) * 100;\n\n if err < ea\n break;\n end\n end\n end\n return xo;\nend\n", "meta": {"hexsha": "6a5e346878d969b4a09fd04012a3aba080dc3770", "size": 1464, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/One-Dimensional Optimisation/golden.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/golden.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/golden.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": 27.1111111111, "max_line_length": 86, "alphanum_fraction": 0.5717213115, "num_tokens": 474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545362802363, "lm_q2_score": 0.8596637487122111, "lm_q1q2_score": 0.815094083017156}} {"text": "#\n# Circular Restricted Three-body Problem models\n# \n\n\"\"\"\nA `ModelingToolkit.ODESystem` for the Circular Restricted Three-body Problem. \n\nThe order of the states follows: `[x, y, z, ẋ, ẏ, ż]`.\n\nThe order of the parameters follows: `[μ]`.\n\n# Extended Help\nThe Circular Restricted Three-body Problem is a simplified dynamical model \ndescribing one small body (spacecraft, etc.) and two celestial \nbodies moving in a circle about their common center of mass. \nThis may seem like an arbitrary simplification, but this assumption\nholds reasonably well for the Earth-Moon, Sun-Earth, and many other \nsystems in our solar system.\n\n### Usage\n\n```julia\nmodel = CR3BP(; stm=true) \n```\n\"\"\"\n@memoize function CR3BP(; stm=false, structural_simplify=true, name=:CR3BP)\n\n @parameters t μ \n @variables x(t) y(t) z(t) ẋ(t) ẏ(t) ż(t)\n δ = Differential(t)\n r = @SVector [x,y,z]\n v = @SVector [ẋ,ẏ,ż]\n \n eqs = vcat(\n δ.(r) .~ v,\n δ(ẋ) ~ x + 2ẏ - (μ*(x + μ - 1)*(sqrt(y^2 + z^2 + (x + μ - 1)^2)^-3)) - ((x + μ)*(sqrt(y^2 + z^2 + (x + μ)^2)^-3)*(1 - μ)),\n δ(ẏ) ~ y - (2ẋ) - (y*(μ*(sqrt(y^2 + z^2 + (x + μ - 1)^2)^-3) + (sqrt(y^2 + z^2 + (x + μ)^2)^-3)*(1 - μ))),\n δ(ż) ~ z*(-μ*(sqrt(y^2 + z^2 + (x + μ - 1)^2)^-3) - ((sqrt(y^2 + z^2 + (x + μ)^2)^-3)*(1 - μ)))\n )\n\n if stm \n @variables Φ[1:6,1:6](t)\n Φ = Symbolics.scalarize(Φ)\n A = Symbolics.jacobian(map(el -> el.rhs, eqs), vcat(r,v))\n \n LHS = map(δ, Φ)\n RHS = map(simplify, A * Φ)\n\n eqs = vcat(eqs, [LHS[i] ~ RHS[i] for i in 1:length(LHS)])\n end\n\n if string(name) == \"CR3BP\" && stm \n modelname = Symbol(\"CR3BPWithSTM\")\n else\n modelname = name\n end\n sys = ODESystem(\n eqs, t, stm ? vcat(r,v,Φ...) : vcat(r,v), [μ]; \n name = modelname\n )\n\n return structural_simplify ? ModelingToolkit.structural_simplify(sys) : sys\nend\n\n\"\"\"\nReturns an `ODEFunction` for CR3BP dynamics. \nResults are cached with `Memoize.jl`.\n\nThe order of the states follows: `[x, y, z, ẋ, ẏ, ż]`.\n\nThe order of the parameters follows: `[μ]`.\n\n# Extended Help\n\n### Usage\n\nThe `stm`, `structural_simplify`, and `name` keyword arguments \nare passed to `CR3BP`. All other keyword arguments are passed\ndirectly to `SciMLBase.ODEFunction`.\n\n```julia\nf = CR3BPFunction(; stm=false, jac=true)\nlet u = randn(6), p = randn(1), t = 0\n f(u, p, t)\nend\n```\n\"\"\"\n@memoize function CR3BPFunction(; stm=false, structural_simplify=true, name=:CR3BP, kwargs...)\n defaults = (; jac=true)\n options = merge(defaults, kwargs)\n return ODEFunction(\n CR3BP(; stm=stm, structural_simplify=structural_simplify, name=name);\n options...\n )\nend", "meta": {"hexsha": "2d05e255d46b2b6e53b783dde7ee8ab7b79b5170", "size": 2719, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/CR3BP.jl", "max_stars_repo_name": "cadojo/AstrodynamicalSystems.jl", "max_stars_repo_head_hexsha": "6b9521b9bef2eda6cf00ea9ab1be156ddc3fb074", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-06-05T18:49:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T19:41:59.000Z", "max_issues_repo_path": "src/CR3BP.jl", "max_issues_repo_name": "cadojo/AstrodynamicalSystems.jl", "max_issues_repo_head_hexsha": "6b9521b9bef2eda6cf00ea9ab1be156ddc3fb074", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-19T05:38:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-06T02:18:43.000Z", "max_forks_repo_path": "src/CR3BP.jl", "max_forks_repo_name": "cadojo/AstrodynamicalSystems.jl", "max_forks_repo_head_hexsha": "6b9521b9bef2eda6cf00ea9ab1be156ddc3fb074", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6210526316, "max_line_length": 133, "alphanum_fraction": 0.5869805075, "num_tokens": 928, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.948154531885212, "lm_q2_score": 0.8596637487122111, "lm_q1q2_score": 0.8150940792389131}} {"text": "using ForwardDiff\nusing LinearAlgebra\nusing Plots\nusing Statistics\n\nn = 1\n\n# Params\nmass = 1\ng = -9.81\nℓ = 0.5\n\n# Lagrangian\nL(q,q̇) = 1/2*mass*ℓ^2*q̇^2 - mass*g*ℓ*(1-cos(q))\n\n# Discrete Lagrangian (midpoint)\nLd(q,q_,h) = h*L((q+q_)/2, (q_-q)/h)\nLd2(q,q_,h) = h*mass*ℓ*( 1/2*ℓ*((q_-q)/h)^2 - g*(1-cos((q+q_)/2)) )\n# Ld2(q,q_,h) = g*(1-cos((q+q_)/2))\n\nq = rand()\nq_ = rand()\nh = 0.01\nLd(q,q_,h) - Ld2(q,q_,h)\n\n# Discrete Euler Lagrange\nD1(q,q_,h) = h*mass*ℓ*( -ℓ/h^2*(q_-q) - g/2*sin((q+q_)/2) )\nD2(_q,q,h) = mass*ℓ^2/h*(q-_q) - mass*ℓ*h*g/2*sin((_q+q)/2)\n\nLd_aug(Q) = Ld2(Q[1],Q[2],h)\n\nQ = [q,q_]\nu = [0.0]\nForwardDiff.gradient(Ld_aug,Q)\nD1(q,q_,h)\nD2(q,q_,h)\n\n\nfunction dyn_discrete(q1,q2,u; eps=1e-10)\n q3 = 2*q2-q1 # Guess using Euler\n\n # Discrete Euler-Lagrange\n P(q1,q2,q3,u) = D2(q1,q2,h) + D1(q2,q3,h) + u[1]\n D2_Ld = ForwardDiff.gradient(Ld_aug,[q1;q2])[n+1:end]\n\n for i = 1:10\n hessLd = ForwardDiff.hessian(Ld_aug,[q2;q3])\n gradLd = ForwardDiff.gradient(Ld_aug,[q2;q3])\n D1_Ld = gradLd[1:n]\n val = D2_Ld + D1_Ld + u\n q3 = q3 - hessLd[1:n,n+1:end]\\val\n if norm(val,Inf) < eps\n break\n end\n end\n return q3\nend\nq1 = q\nq2 = q + q_*h\nq3 = dyn_discrete([q1],[q2],u)\n\n\n# Continuous\nL_aug(Q) = L(Q[1],Q[2])\ngradL = ForwardDiff.gradient(L_aug,Q)\nhessL = ForwardDiff.hessian(L_aug,Q)\nfunction dyn(Q,u)\n gradL = ForwardDiff.gradient(L_aug,Q)\n hessL = ForwardDiff.hessian(L_aug,Q)\n Ldd = hessL[n+1:end,n+1:end]\n qdd = Ldd\\(u + gradL[1:n] - hessL[1:n,n+1:end]*Q[n+1:end])\n return [Q[2]; qdd]\nend\ndyn(Q,u)\n\n# Analytical\nfunction dyn0(Q,u)\n return [Q[2]; u[1] - g/ℓ*sin(Q[1])]\nend\ndyn0(Q,u)\ndyn0(Q,u) ≈ dyn(Q,u)\n\nfunction rk3(f::Function, dt::Float64)\n # Runge-Kutta 3 (zero order hold)\n fd(x,u,dt=dt) = begin\n k1 = f(x,u)*dt\n k2 = f(x+k1/2,u)*dt\n k3 = f(x - k1 + 2*k2,u)*dt\n return x + (k1 + 4k2 + k3)/6\n end\nend\n\ndyn_discrete_rk3 = rk3(dyn,h)\ndyn_discrete_rk3(Q,u)\n\n\nfunction simulate1(Q0,N)\n Qs = zeros(length(Q0),N)\n Qs[:,1] = Q0\n for k = 2:N\n Qs[:,k] = dyn_discrete_rk3(Qs[:,k-1],[0])\n end\n return Qs\nend\n\nfunction simulate2(Q0,N)\n Q0 = [Q0[1:n];Q0[1:n]+Q[n+1:end]*h]\n Qs = zeros(n,N)\n Qs[:,1] = Q0[1:n]\n Qs[:,2] = Q0[n+1:end]\n for k = 3:N\n Qs[:,k] = dyn_discrete(Qs[:,k-2],Qs[:,k-1],[0])\n end\n return Qs\nend\n\nQ0 = [deg2rad(170),0]\nres1 = simulate1(Q0,501)\nplot(rad2deg.(res1[1,3:end]),label=:continuous)\n\nres2 = simulate2(Q0,501)\nplot!(rad2deg.(res2[1,:]),label=:discrete)\n", "meta": {"hexsha": "5631b68a0a19e932f05b05228ad904eddb37d455", "size": 2563, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/pendulum.jl", "max_stars_repo_name": "RoboticExplorationLab/DiscreteMechanics.jl", "max_stars_repo_head_hexsha": "799cf10f0c41fdd6f9c755d4015f4350cdd3ac23", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pendulum.jl", "max_issues_repo_name": "RoboticExplorationLab/DiscreteMechanics.jl", "max_issues_repo_head_hexsha": "799cf10f0c41fdd6f9c755d4015f4350cdd3ac23", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pendulum.jl", "max_forks_repo_name": "RoboticExplorationLab/DiscreteMechanics.jl", "max_forks_repo_head_hexsha": "799cf10f0c41fdd6f9c755d4015f4350cdd3ac23", "max_forks_repo_licenses": ["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.837398374, "max_line_length": 67, "alphanum_fraction": 0.5610612563, "num_tokens": 1157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240125464114, "lm_q2_score": 0.8688267796346599, "lm_q1q2_score": 0.815067264718644}} {"text": "#= \n Bayesian Null hypothesis test in Turing.jl\n From https://mhtess.github.io/bdappl/chapters/04-hypothesisTesting.html\n (WebPPL model)\n \"\"\"\n Let’s see an example: Consider our children helping study from the previous study. Rather than estimate the \n propensity_to_help, we might want to perform a “Null Hypothesis” test: What is the probability that the behavior \n observed in our experiment (that 15 out of 20 kids helped) could be explained by true randomness (i.e., \n propensity_to_help = 0.5)? \n \n ...\n \n Bayesian Null Hypothesis Testing requires you to specify both hypotheses: \n It is not enough to define what the null hypothesis is. The alternative \n hypothesis is intuitively M1:θ≠0.5\\mathcal{M}_1: \\theta \\neq 0.5M1​:θ≠0.5, \n but we must be more specific. One standard way of defining the null \n hypothesis is to put say that the parameter is drawn from a uniform \n distribution.\n \"\"\"\n\n From the WebPPL model:\n Marginal:\n {\"the_better_model\":\"alternative\"} : 0.758\n {\"the_better_model\":\"null\"} : 0.242\n\n This Turing.jl model:\n Distributions of variable the_better_model (num:0)\n alternative model => 7612 (0.761200)\n null => 2388 (0.238800)\n\n=#\n\nusing Turing\ninclude(\"jl_utils.jl\")\n\n@model function supermodel(k=15,n=20)\n null_model ~ Dirac(0.5)\n alternative_model ~ Uniform(0,1)\n\n # Pick one of the models\n null = 1\n alternative = 2\n the_better_model ~ DiscreteUniform(1,2) # Categorical([0.5,0.5])\n p ~ Dirac(the_better_model == null ? null_model : alternative_model)\n k ~ Binomial(n,p)\n\n \nend\n\n# data\nk=15\nn=20\nprintln(\"We observe $(k) successes of $(n) attempts\")\nmodel = supermodel(k,n)\n# chns = sample(model, Prior(), 10_000)\n# chns = sample(model, MH(), 10_000)\n# chns = sample(model, PG(15), 10_000)\n# chns = sample(model, IS(), 10_000)\nchns = sample(model, SMC(), 10_000)\n\ndisplay(chns)\n\n\nshow_var_dist_pct(chns,:the_better_model,[\"null\",\"alternative model\"])\n\n", "meta": {"hexsha": "43fc57eefc2a068ec5bf2099cfe7672cb1606a0c", "size": 1956, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/bayesian_null_hypothesis_test.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/turing/bayesian_null_hypothesis_test.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/turing/bayesian_null_hypothesis_test.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 29.6363636364, "max_line_length": 115, "alphanum_fraction": 0.6993865031, "num_tokens": 585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533013520765, "lm_q2_score": 0.8740772466456689, "lm_q1q2_score": 0.8150362142714872}} {"text": "N = 13\n\tnum = string(\"73167176531330624919225119674426574742355349194934\",\n\t\t\t\"96983520312774506326239578318016984801869478851843\",\n\t\t\t\"85861560789112949495459501737958331952853208805511\",\n\t\t\t\"12540698747158523863050715693290963295227443043557\",\n\t\t\t\"66896648950445244523161731856403098711121722383113\",\n\t\t\t\"62229893423380308135336276614282806444486645238749\",\n\t\t\t\"30358907296290491560440772390713810515859307960866\",\n\t\t\t\"70172427121883998797908792274921901699720888093776\",\n\t\t\t\"65727333001053367881220235421809751254540594752243\",\n\t\t\t\"52584907711670556013604839586446706324415722155397\",\n\t\t\t\"53697817977846174064955149290862569321978468622482\",\n\t\t\t\"83972241375657056057490261407972968652414535100474\",\n\t\t\t\"82166370484403199890008895243450658541227588666881\",\n\t\t\t\"16427171479924442928230863465674813919123162824586\",\n\t\t\t\"17866458359124566529476545682848912883142607690042\",\n\t\t\t\"24219022671055626321111109370544217506941658960408\",\n\t\t\t\"07198403850962455444362981230987879927244284909188\",\n\t\t\t\"84580156166097919133875499200524063689912560717606\",\n\t\t\t\"05886116467109405077541002256983155200055935729725\",\n\t\t\t\"71636269561882670428252483600823257530420752963450\")\n\t\n\tp = 0;\n\t\t\t\n\tfor i = 1:(endof(num)-N)\n\t\t\n\t\tpn = prod([int(string(x)) for x in num[i:i+N-1]])\n\t\tif pn>p\n\t\t\tp=pn\n\t\tend\n\tend\n\t\n\tprintln(p)\n\t", "meta": {"hexsha": "58b8f3235cc68218eb6d5f69ba28e67fa36460da", "size": 1297, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/OldFiles/problem_8.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_8.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_8.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": 38.1470588235, "max_line_length": 67, "alphanum_fraction": 0.831919815, "num_tokens": 485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533126145178, "lm_q2_score": 0.8740772318846386, "lm_q1q2_score": 0.8150362103517593}} {"text": "using Polynomials\n\n\n\"\"\"\n poly_chebyshev(n, [::Type{T}=Int, [var=:x]])\n\nCreate a Chebyshev polynomial of order n `Polynomial` object.\n\nInstead of computing the polynomial at a specific point, \nuse `Polynomials` package to compute the actual polynomial\n\nParameters:\n\n * `n` Order of polynomials\n * `T` Type of polynomial coefficients\n * `var` symbol to be used as variable by the polynomial\n\n# Examples\n```julia-repl\njulia> p = poly_chebyshev(4)\nPolynomials.Polynomial(1 - 8*x^2 + 8*x^4)\n\njulia> p2 = poly_chebyshev(4, BigInt)\nPolynomials.Polynomial(1 - 8*x^2 + 8*x^4)\n\njulia> p3 = poly_chebyshev(4, Float64, :y)\nPolynomials.Polynomial(1.0 - 8.0*y^2 + 8.0*y^4)\n\n```\n\n\"\"\"\nfunction poly_chebyshev(n, ::Type{T}=Int, var=:x) where {T<:Number}\n\n if n==0\n return Polynomial{T}([one(T)], var)\n elseif n==1\n return Polynomial{T}([zero(T), one(T)], var) \n end\n\n px = Polynomial{T}([zero(T), one(T)], var)\n T0 = Polynomial{T}([one(T)], var)\n T1 = px\n \n for i = 2:n\n T2 = 2*px*T1 - T0\n T0 = T1\n T1 = T2\n end\n\n return T1\n\nend\n\n\"\"\"\n poly_dchebyshev(n, [::Type{T}=Int, [var=:x]])\n\nCreate the derivative of Chebyshev polynomial of order n `Polynomial` object.\n\nInstead of computing the polynomial at a specific point, \nuse `Polynomials` package to compute the actual polynomial\n\nParameters:\n\n * `n` Order of polynomials\n * `T` Type of polynomial coefficients\n * `var` symbol to be used as variable by the polynomial\n\n# Examples\n```julia-repl\njulia> p = poly_dchebyshev(4)\nPolynomials.Polynomial(-16*x + 32*x^3)\n\njulia> p2 = poly_dchebyshev(4, BigInt)\nPolynomials.Polynomial(-16*x + 32*x^3)\n\njulia> p3 = poly_dchebyshev(4, Float64, :y)\nPolynomials.Polynomial(-16.0*y + 32.0*y^3)\n```\n\"\"\"\npoly_dchebyshev(n, ::Type{T}=Int, var=:x) where {T<:Number} = derivative(poly_chebyshev(n,T, var))\n\n\n\n\"\"\"\n poly_chebyshev2(n, [::Type{T}=Int, [var=:x]])\n\nCreate a Chebyshev of the second kind of order n `Polynomial` object.\n\nInstead of computing the polynomial at a specific point, \nuse `Polynomials` package to compute the actual polynomial\n\nParameters:\n\n * `n` Order of polynomials\n * `T` Type of polynomial coefficients\n * `var` symbol to be used as variable by the polynomial\n\n# Examples\n```julia-repl\njulia> p = poly_chebyshev2(4)\nPolynomials.Polynomial(1 - 12*x^2 + 16*x^4)\n\njulia> p2 = poly_chebyshev2(4, BigInt)\nPolynomials.Polynomial(1 - 12*x^2 + 16*x^4)\n\njulia> p3 = poly_chebyshev2(4, Float64, :y)\nPolynomials.Polynomial(1.0 - 12.0*y^2 + 16.0*y^4)\n```\n\n\"\"\"\nfunction poly_chebyshev2(n, ::Type{T}=Int, var=:x) where {T<:Number}\n\n if n==0\n return Polynomial{T}([one(T)], var)\n elseif n==1\n return Polynomial{T}([zero(T), 2*one(T)], var) \n end\n\n px = Polynomial{T}([zero(T), one(T)], var)\n U0 = Polynomial{T}([one(T)], var)\n U1 = Polynomial{T}([zero(T), 2*one(T)], var)\n \n for i = 2:n\n U2 = 2*px*U1 - U0\n U0 = U1\n U1 = U2\n end\n\n return U1\n\nend\n\n\"\"\"\n poly_dchebyshev2(n, [::Type{T}=Int, [var=:x]])\n\nCreate a derivative of Chebyshev polynomial of the second kind of order n `Polynomial` object.\n\nInstead of computing the polynomial at a specific point, \nuse `Polynomials` package to compute the actual polynomial\n\nParameters:\n\n * `n` Order of polynomials\n * `T` Type of polynomial coefficients\n * `var` symbol to be used as variable by the polynomial\n\n# Examples\n```julia-repl\njulia> p = poly_dchebyshev2(4)\nPolynomials.Polynomial(-24*x + 64*x^3)\n\njulia> p2 = poly_dchebyshev2(4, BigInt)\nPolynomials.Polynomial(-24*x + 64*x^3)\n\njulia> p3 = poly_dchebyshev2(4, Float64, :y)\nPolynomials.Polynomial(-24.0*y + 64.0*y^3)\n```\n\n\"\"\"\npoly_dchebyshev2(n, ::Type{T}=Int, var=:x) where {T<:Number} = derivative(poly_chebyshev2(n,T, var))\n\n\n\"\"\"\n poly_legendre(n, [::Type{T}=Int, [var=:x]])\n\nCreate a Legendre polynomial of order n `Polynomial` object.\n\nInstead of computing the polynomial at a specific point, \nuse `Polynomials` package to compute the actual polynomial\n\nParameters:\n\n * `n` Order of polynomials\n * `T` Type of polynomial coefficients\n * `var` symbol to be used as variable by the polynomial\n\n# Examples\n```julia-repl\njulia> p = poly_legendre(4)\nPolynomials.Polynomial(0.375 - 3.75*x^2 + 4.375*x^4)\n\njulia> p2 = poly_legendre(4, Rational{Int})\nPolynomials.Polynomial(3//8 - 15//4*x^2 + 35//8*x^4)\n\njulia> p3 = poly_legendre(4, BigFloat, :y)\nPolynomials.Polynomial(0.375 - 3.75*y^2 + 4.375*y^4)\n```\n\n\"\"\"\nfunction poly_legendre(n, ::Type{T}=Float64, var=:x) where {T<:Number}\n\n\n if n==0\n return Polynomial{T}([one(T)], var)\n elseif n==1\n return Polynomial{T}([zero(T), one(T)], var) \n end\n\n px = Polynomial{T}([zero(T), one(T)], var)\n p0 = Polynomial{T}([one(T)], var)\n p1 = px\n\n for i = 2:n\n p2 = ( (2i-1)*px*p1 - (i-1)*p0 ) / i\n p0 = p1\n p1 = p2\n end\n\n return p1\nend\n\n\n\"\"\"\n poly_dlegendre(n, [::Type{T}=Int, [var=:x]])\n\nCreate a derivative of Legendre polynomial of order n `Polynomial` object.\n\nInstead of computing the polynomial at a specific point, \nuse `Polynomials` package to compute the actual polynomial\n\nParameters:\n\n * `n` Order of polynomials\n * `T` Type of polynomial coefficients\n * `var` symbol to be used as variable by the polynomial\n\n# Examples\n```julia-repl\njulia> p = poly_dlegendre(4)\nPolynomials.Polynomial(-7.5*x + 17.5*x^3)\n\njulia> p2 = poly_dlegendre(4, Rational{Int})\nPolynomials.Polynomial(-15//2*x + 35//2*x^3)\n\njulia> p3 = poly_dlegendre(4, BigFloat, :y)\nPolynomials.Polynomial(-7.5*y + 17.5*y^3)\n```\n\n\"\"\"\npoly_dlegendre(n, ::Type{T}=Int, var=:x) where {T<:Number} = derivative(poly_legendre(n,T, var))\n\n\n\n\n\n\"\"\"\n poly_jacobi(n, [::Type{T}=Int, [var=:x]])\n\nCreate a Jacobi polynomial of order n `Polynomial` object.\n\nInstead of computing the polynomial at a specific point, \nuse `Polynomials` package to compute the actual polynomial\n\nParameters:\n\n * `n` Order of polynomials\n * `a` Weight α of the Jacobi polynomial\n * `b` Weight β of the Jacobi polynomial\n * `T` Type of polynomial coefficients\n * `var` symbol to be used as variable by the polynomial\n\n# Examples\n```julia-repl\njulia> p = poly_jacobi(4, 1, 1)\nPolynomials.Polynomial(0.625 - 8.75*x^2 + 13.125*x^4)\n\njulia> p2 = poly_jacobi(4, 1, 1, Rational{Int})\nPolynomials.Polynomial(5//8 - 35//4*x^2 + 105//8*x^4)\n\njulia> p3 = poly_jacobi(4, 1, 1, BigFloat, :y)\nPolynomials.Polynomial(0.625 - 8.75*y^2 + 13.125*y^4)\n```\n\"\"\"\nfunction poly_jacobi(n, a, b, ::Type{T}=Float64, var=:x) where {T<:Number}\n\n ox = one(T)\n zx = zero(T)\n if n==0\n return Polynomial{T}([one(T)], var)\n elseif n==1\n return Polynomial{T}([(a-b)/2, (a+b+2)/2], var)\n end\n p0 = Polynomial{T}([one(T)], var)\n p1 = Polynomial{T}([(a-b)/2, (a+b+2)/2], var)\n px = Polynomial{T}([zero(T), one(T)], var)\n \n for i = 1:(n-1)\n\ta1 = 2*(i+1)*(i+a+b+1)*(2*i+a+b);\n\ta2 = (2*i+a+b+1)*(a*a-b*b);\n\ta3 = (2*i+a+b)*(2*i+a+b+1)*(2*i+a+b+2);\n\ta4 = 2*(i+a)*(i+b)*(2*i+a+b+2);\n\tp2 = ox/a1*( (a2 + a3*px)*p1 - a4*p0);\n\n p0 = p1\n p1 = p2\n end\n\n return p1\nend\n\n\n\"\"\"\n poly_djacobi(n, [::Type{T}=Int, [var=:x]])\n\nCreate a derivative of Jacobi polynomial of order n `Polynomial` object.\n\nInstead of computing the polynomial at a specific point, \nuse `Polynomials` package to compute the actual polynomial\n\nParameters:\n\n * `n` Order of polynomials\n * `a` Weight α of the Jacobi polynomial\n * `b` Weight β of the Jacobi polynomial\n * `T` Type of polynomial coefficients\n * `var` symbol to be used as variable by the polynomial\n\n# Examples\n```julia-repl\njulia> p = poly_djacobi(4, 1, 1)\nPolynomials.Polynomial(-17.5*x + 52.5*x^3)\n\njulia> p2 = poly_djacobi(4, 1, 1, Rational{Int})\nPolynomials.Polynomial(-35//2*x + 105//2*x^3)\n\njulia> p3 = poly_djacobi(4, 1, 1, BigFloat, :y)\nPolynomials.Polynomial(-17.5*y + 52.5*y^3)\n```\n\"\"\"\npoly_djacobi(n, a, b, ::Type{T}=Float64, var=:x) where {T<:Number} = derivative(poly_jacobi(n,a,b,T,var))\n", "meta": {"hexsha": "2a117ee236af6f481a7aa8328f4318ea26f7a2b9", "size": 7911, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/polynomials.jl", "max_stars_repo_name": "pjabardo/Jacobi.jl", "max_stars_repo_head_hexsha": "c1bfe73688ca47da70a5dc3b46083237382d41c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2015-11-23T03:17:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T16:38:43.000Z", "max_issues_repo_path": "src/polynomials.jl", "max_issues_repo_name": "pjabardo/Jacobi.jl", "max_issues_repo_head_hexsha": "c1bfe73688ca47da70a5dc3b46083237382d41c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2018-08-08T20:38:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-09T15:22:25.000Z", "max_forks_repo_path": "src/polynomials.jl", "max_forks_repo_name": "pjabardo/Jacobi.jl", "max_forks_repo_head_hexsha": "c1bfe73688ca47da70a5dc3b46083237382d41c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2016-01-08T20:07:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T12:22:22.000Z", "avg_line_length": 23.9003021148, "max_line_length": 105, "alphanum_fraction": 0.648084945, "num_tokens": 2714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218284193597, "lm_q2_score": 0.8840392863287585, "lm_q1q2_score": 0.8150151152467549}} {"text": "\"\"\"\n\tvoronoiarea(tess::Tessellation) -> Vector\n\nCompute the area of all Voronoi cells in a tesselation.\n\"\"\"\nfunction voronoiarea(tess::Tessellation)\n\tmap(polyarea, tess.Cells)\nend\n\n\n\"\"\"\n\tpolyarea(p::Vector)\n\nCompute the area of the polygon with vertices `p` using the shoelace formula. \nIt is assumed that `p` is sorted.\n\"\"\"\nfunction polyarea(pts)\n\tn_pts = length(pts)\n\tA = getx(pts[1]) * (gety(pts[2]) - gety(pts[n_pts])) + getx(pts[n_pts]) * (gety(pts[1]) - gety(pts[n_pts - 1]))\n\n\tfor n in 2:n_pts - 1\n\t\tA += getx(pts[n])*(gety(pts[n + 1]) - gety(pts[n - 1]))\n\tend\n\n\treturn 0.5 * abs(A)\nend\n\n", "meta": {"hexsha": "f2b6346376281301ca24e8361b20f7110f3014df", "size": 596, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Area.jl", "max_stars_repo_name": "philbit/VoronoiCells.jl", "max_stars_repo_head_hexsha": "19ac0d1dcc222fbf10c9f27c1afc83dd3c47e8c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2016-09-08T07:36:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T02:03:45.000Z", "max_issues_repo_path": "src/Area.jl", "max_issues_repo_name": "philbit/VoronoiCells.jl", "max_issues_repo_head_hexsha": "19ac0d1dcc222fbf10c9f27c1afc83dd3c47e8c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2017-07-21T21:25:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-04T20:32:02.000Z", "max_forks_repo_path": "src/Area.jl", "max_forks_repo_name": "philbit/VoronoiCells.jl", "max_forks_repo_head_hexsha": "19ac0d1dcc222fbf10c9f27c1afc83dd3c47e8c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2016-09-10T05:12:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-24T13:06:08.000Z", "avg_line_length": 21.2857142857, "max_line_length": 112, "alphanum_fraction": 0.6543624161, "num_tokens": 199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341962906709, "lm_q2_score": 0.851952809486198, "lm_q1q2_score": 0.8150071911804081}} {"text": "using Distributions, Plots; pyplot()\n\nmu, sigma = 10, 4\nn, N = 10, 10^6\n\nsMeans = Array{Float64}(undef, N)\nsVars = Array{Float64}(undef, N)\ntStats = Array{Float64}(undef, N)\n\nfor i in 1:N\n data = rand(Normal(mu,sigma),n)\n sampleMean = mean(data)\n sampleVars = var(data)\n sMeans[i] = sampleMean\n sVars[i] = sampleVars\n tStats[i] = (sampleMean - mu)/(sqrt(sampleVars/n))\nend\n\nxRangeMean = 5:0.1:15\nxRangeVar = 0:0.1:60\nxRangeTStat = -5:0.1:5\n\np1 = stephist(sMeans, bins=50, c=:blue, normed=true, legend=false)\np1 = plot!(xRangeMean, pdf.(Normal(mu,sigma/sqrt(n)), xRangeMean),\n c=:red, xlims=(5,15), ylims=(0,0.35), xlabel=\"Sample mean\",ylabel=\"Density\")\n\np2 = stephist(sVars, bins=50, c=:blue, normed=true, label=\"Simulated\")\np2 = plot!(xRangeVar, (n-1)/sigma^2*pdf.(Chisq(n-1), xRangeVar*(n-1)/sigma^2),\n c=:red, label=\"Analytic\", xlims=(0,60), ylims=(0,0.06),\n xlabel=\"Sample Variance\",ylabel=\"Density\")\n\np3 = stephist(tStats, bins=100, c=:blue, normed=true, legend=false)\np3 = plot!(xRangeTStat, pdf.(TDist(n-1), xRangeTStat), \n c=:red, xlims=(-5,5), ylims=(0,0.4), xlabel=\"t-statistic\",ylabel=\"Density\")\n\nplot(p1, p2, p3, layout = (1,3), size=(1200, 400))\n", "meta": {"hexsha": "c84b333a9e8ee97caacae12357c9ca5adde33895", "size": 1200, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "5_chapter/friendOfANormalDistribution.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/friendOfANormalDistribution.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/friendOfANormalDistribution.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.4324324324, "max_line_length": 80, "alphanum_fraction": 0.6433333333, "num_tokens": 462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342049451595, "lm_q2_score": 0.8519527982093668, "lm_q1q2_score": 0.8150071877658215}} {"text": "\n\n####################################################\n\n\"\"\"\n$(TYPEDSIGNATURES)\n\nLeast squares linear regression in its simplest form.\n\"\"\"\nfunction lssqregr(points::Array{<:Real,2})\n \n ## G = [protc ones(length(protc))]\n ## dobs = sdsc\n G = [points[:,2] ones(size(points,1))]\n dobs = points[:,1]\n\n ## overdetermined least squares\n ## mpost = (G'*G)*G'*dobs\n ## (G'*G) * h = G'\n lstmp = (G'*G) \\ G'\n mpost = lstmp * dobs\n\n angcoe = mpost[1]\n intercept = mpost[2]\n\n # residuals\n r = (G * mpost) .- dobs\n sse = sum(r.^2)\n if length(r)>2\n resstderr = sqrt(sse/(length(dobs)-2))\n else\n resstderr = sqrt(sse/(length(dobs)))\n end\n \n return angcoe,intercept,resstderr\nend\n\n####################################################\n\n# \"\"\"\n# $(TYPEDSIGNATURES)\n\n# Least squares linear regression including a covariance \n# matrix on the observed/measured data.\n\n# Cd is the covariance matrix on the observed data.\n# \"\"\"\n# function lssqregr(points::Array{<:Real,2},Cd::AbstractMatrix{<:Real})\n\n# # take the inverse of the covariance matrix\n# invCd = inv( Cd )\n\n# ## G = [protc ones(length(protc))]\n# ## dobs = sdsc\n# G = [points[:,2] ones(size(points,1))]\n# dobs = points[:,1]\n \n# ## overdetermined least squares\n# ## mpost = (G'*G)*G'*dobs\n# ## (G'*G) * h = G'\n# lstmp = (G'*invCd*G) \\ (G'*invCd)\n# mpost = lstmp * dobs\n\n# # see Tarantola 2005, page 67, eq. 3.40-3.44\n# # posterior covariance on model parameters\n# Cmpost = inv( transpose(G) * invCd * G )\n# # # posterior covariance on observed data\n# # Cdpost = G * Cmpost * transpose(G)\n\n# angcoe = mpost[1]\n# intercept = mpost[2]\n\n# # posterior variance\n# #varangcoe,varintercept = Cmpost[1,1],Cmpost[2,2]\n\n# # residuals\n# r = (G * mpost) .- dobs\n# sse = sum(r.^2)\n# if length(r)>2\n# resstderr = sqrt(sse/(length(dobs)-2))\n# else\n# resstderr = sqrt(sse/(length(dobs)))\n# end\n \n\n# @show G\n# @show dobs\n \n# return angcoe,intercept,resstderr #varangcoe,varintercept\n# end\n\n# ####################################################\n", "meta": {"hexsha": "49178bac2d5b24969475b0fa8a715bb964cb1a83", "size": 2177, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "inverseproblem/ANISPROU.jl", "max_stars_repo_head_hexsha": "62c97f11f37dda937c56724fb2d906b82509484d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "inverseproblem/ANISPROU.jl", "max_issues_repo_head_hexsha": "62c97f11f37dda937c56724fb2d906b82509484d", "max_issues_repo_licenses": ["MIT"], "max_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": "inverseproblem/ANISPROU.jl", "max_forks_repo_head_hexsha": "62c97f11f37dda937c56724fb2d906b82509484d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4086021505, "max_line_length": 71, "alphanum_fraction": 0.5227377124, "num_tokens": 681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299632771662, "lm_q2_score": 0.8807970811069351, "lm_q1q2_score": 0.8149398510072048}} {"text": "module MooreJuliaMultigrid\n\nusing LinearAlgebra\nusing SparseArrays\n\n\"\"\"\nRun the Weighted Jacobi method on matrix system Ax=b for a total of numiters\n iterations, starting with an initial guess of x0\n\"\"\"\nfunction Jacobi(A,b,x0; numiters=1,weight=1)\n wDinv = weight*inv(Diagonal(diag(A)))\n R = UniformScaling(1-weight) + wDinv*(A - Diagonal(diag(A)))\n for i = 1:numiters\n x0 = wDinv*b - R*x0\n end\n return x0\nend\n\n\"\"\"\nV-cycle method to solve the matrix system Ax=b\nInputs:\n A, b, x0 : A matrix, RHS vector, initial guess\n relaxFunc : Function to complete the relaxation\n -- argument form : relaxFunc(A,b,x0; named options)\n preRelaxOpts : Options for relaxFunc before coarse-grid transfer\n -- named tuple with named options for relaxFunc\n postRelaxOpts : Options for relaxFunc after coarse-grid correction\n -- named tuple with named options for relaxFunc\n prolongOp : Prolongation (interpolation) operator\n -- matrix expected - may change\n restrictOp : Restriction operator\n -- matrix expected - may change\n\"\"\"\nfunction Vcycle(A,b,x0,relaxFunc,preRelaxOpts, postRelaxOpts, prolongOp, restrictOp)\n # First relax numprerelax times\n if preRelaxOpts[:numiters] > 0\n x0 = relaxFunc(A,b,x0;preRelaxOpts...)\n end\n\n # Transfer residual to coarser grid\n r = restrictOp*(b - A*x0)\n\n # Transfer A to coarser grid\n Acoarse = restrictOp*A*prolongOp\n\n # Solve the coarse problem\n ecourse = Acoarse \\ r\n\n # Interp ecourse to fine grid\n e = prolongOp*ecourse\n\n # Correct approximation with the residual\n x0 = x0 + e\n\n # Relax numpostrelax times\n if postRelaxOpts[:numiters] > 0\n x0 = relaxFunc(A,b,x0;postRelaxOpts...)\n end\n return x0\nend\n\n\"\"\"\nBuildLinearInterpOp builds the linear interpoltion operator for transferring\n a vector of length fineSize to a vector of length (fineSize+1)/2 - 1.\n\n Currently expects only an odd length vector\n\n TODO: Add support for even length vectors\n\"\"\"\nfunction BuildLinearInterpOp(fineSize)\n numCols::Int = (fineSize+1)/2 - 1\n I = Vector{Int}(undef,3*numCols)\n J = Vector{Int}(undef,3*numCols)\n V = Vector{Float64}(undef,3*numCols)\n for i = 1:numCols\n I[3i-2:3i] = [2i-1; 2i; 2i+1]\n J[3i-2:3i] = i*ones(3,1)\n V[3i-2:3i] = [1; 2; 1]\n end\n return 0.5*sparse(I,J,V)\nend\n\nexport Jacobi, Vcycle, BuildLinearInterpOp\n\nend # module\n", "meta": {"hexsha": "fff5f59414c61fca39c7924d905d82cd26654eb7", "size": 2424, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MooreJuliaMultigrid.jl", "max_stars_repo_name": "nsmoore57/MooreJuliaMultigrid.jl", "max_stars_repo_head_hexsha": "8b258817ee6ba957d1a380bd3fa48cf982ba7d7d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MooreJuliaMultigrid.jl", "max_issues_repo_name": "nsmoore57/MooreJuliaMultigrid.jl", "max_issues_repo_head_hexsha": "8b258817ee6ba957d1a380bd3fa48cf982ba7d7d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MooreJuliaMultigrid.jl", "max_forks_repo_name": "nsmoore57/MooreJuliaMultigrid.jl", "max_forks_repo_head_hexsha": "8b258817ee6ba957d1a380bd3fa48cf982ba7d7d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1860465116, "max_line_length": 84, "alphanum_fraction": 0.6778052805, "num_tokens": 744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509315, "lm_q2_score": 0.8757869884059266, "lm_q1q2_score": 0.8148832367943729}} {"text": "# Probabilistic Principal Component Analysis\n\n\"\"\"\nThis type contains probabilistic PCA model parameters.\n\"\"\"\nstruct PPCA{T<:Real} <: LatentVariableDimensionalityReduction\n mean::Vector{T} # sample mean: of length d (mean can be empty, which indicates zero mean)\n W::Matrix{T} # weight matrix: of size d x p\n σ²::T # residual variance\nend\n\n## properties\n\"\"\"\n size(M::PPCA)\n\nReturns a tuple with values of the input dimension ``d``, *i.e* the dimension of\nthe observation space, and the output dimension ``p``, *i.e* the dimension of\nthe principal subspace.\n\"\"\"\nsize(M::PPCA) = size(M.W)\n\n\"\"\"\n mean(M::PPCA)\n\nGet the mean vector (of length ``d``).\n\"\"\"\nmean(M::PPCA) = fullmean(size(M)[1], M.mean)\n\n\"\"\"\n projection(M::PPCA)\n\nReturns the projection matrix (of size ``(d, p)``). Each column of the projection\nmatrix corresponds to a principal component.\n\nThe principal components are arranged in descending order of the corresponding variances.\n\n\"\"\"\nprojection(M::PPCA) = svd(M.W).U # recover principle components from the weight matrix\n\n\"\"\"\n var(M::PPCA)\n\nReturns the total residual variance of the model `M`.\n\"\"\"\nvar(M::PPCA) = M.σ²\n\n\"\"\"\n loadings(M::PPCA)\n\nReturns the factor loadings matrix (of size ``(d, p)``) of the model `M`.\n\"\"\"\nloadings(M::PPCA) = M.W\n\n\"\"\"\n cov(M::PPCA)\n\nReturns the covariance of the model `M`.\n\"\"\"\ncov(M::PPCA) = M.W'*M.W + M.σ²*I\n\n## use\n\"\"\"\n predict(M::PPCA, x)\n\nTransform observations `x` into latent variables. Here, `x` can be either a vector\nof length `d` or a matrix where each column is an observation.\n\"\"\"\nfunction predict(M::PPCA, x::AbstractVecOrMat{T}) where {T<:Real}\n xn = centralize(x, M.mean)\n n = size(M)[2]\n return inv(cov(M))*M.W'*xn\nend\n\n\"\"\"\n reconstruct(M::PPCA, z)\n\nApproximately reconstruct observations from the latent variable given in `z`.\nHere, `z` can be either a vector of length `p` or a matrix where each column gives\nthe latent variables for an observation.\n\"\"\"\nfunction reconstruct(M::PPCA, z::AbstractVecOrMat{T}) where {T<:Real}\n W = M.W\n WTW = W'W\n n = size(M)[2]\n C = WTW + var(M) * I\n return W*inv(WTW)*C*z .+ mean(M)\nend\n\n## show\n\nfunction Base.show(io::IO, M::PPCA)\n i, o = size(M)\n print(io, \"Probabilistic PCA(indim = $i, outdim = $o, σ² = $(var(M)))\")\nend\n\n## core algorithms\n\"\"\"\n ppcaml(Z, mean; ...)\n\nCompute probabilistic PCA using on maximum likelihood formulation for a centralized\nsample matrix `Z`.\n\n*Parameters*:\n- `Z`: a centralized samples matrix\n- `mean`: The mean vector of the **original** samples, which can be a vector of\nlength `d`, or an empty vector indicating a zero mean.\n\nReturns the resultant [`PPCA`](@ref) model.\n\n**Note:** This function accepts two keyword arguments: `maxoutdim` and `tol`.\n\"\"\"\nfunction ppcaml(Z::AbstractMatrix{T}, mean::Vector{T};\n tol::Real=1.0e-6, # convergence tolerance\n maxoutdim::Int=size(Z,1)-1) where {T<:Real}\n\n check_pcaparams(size(Z,1), mean, maxoutdim, 1.)\n\n d, n = size(Z)\n\n # SVD decomposition\n Svd = svd(Z)\n λ = Svd.S\n ord = sortperm(λ; rev=true)\n V = abs2.(λ[ord]) ./ (n-1)\n\n # filter 0 eigenvalues and adjust number of latent dimensions\n idxs = findall(V .< tol)\n l = length(idxs)\n l = l == 0 ? maxoutdim : l\n\n # variance \"loss\" in the projection\n σ² = sum(V[l+1:end])/(d-l)\n\n @inbounds for i in 1:l\n V[i] = sqrt(V[i] - σ²)\n end\n\n W = Svd.U[:,ord[1:l]]*diagm(0 => V[1:l])\n\n return PPCA(mean, W, σ²)\nend\n\n\"\"\"\n ppcaem(S, mean, n; ...)\n\nCompute probabilistic PCA based on expectation-maximization algorithm for a given sample covariance matrix `S`.\n\n*Parameters*:\n- `S`: The sample covariance matrix.\n- `mean`: The mean vector of original samples, which can be a vector of length `d`,\nor an empty vector indicating a zero mean.\n- `n`: The number of observations.\n\nReturns the resultant [`PPCA`](@ref) model.\n\n**Note:** This function accepts three keyword arguments: `maxoutdim`, `tol`, and `maxiter`.\n\"\"\"\nfunction ppcaem(S::AbstractMatrix{T}, mean::Vector{T}, n::Int;\n maxoutdim::Int=size(S,1)-1,\n tol::Real=1.0e-6, # convergence tolerance\n maxiter::Integer=1000) where {T<:Real}\n\n check_pcaparams(size(S,1), mean, maxoutdim, 1.)\n\n d = size(S,1)\n q = maxoutdim\n Iq = Matrix{T}(I, q, q)\n Id = Matrix{T}(I, d, d)\n W = Matrix{T}(I, d, q)\n σ² = zero(T)\n M⁻¹ = inv(W'W .+ σ² * Iq)\n\n i = 1\n L_old = 0.\n chg = NaN\n converged = false\n while i < maxiter\n # EM-steps\n SW = S*W\n W⁺ = SW*inv(σ²*Iq + M⁻¹*W'*SW)\n σ²⁺ = tr(S - SW*M⁻¹*(W⁺)')/d\n # new parameters\n W = W⁺\n σ² = σ²⁺\n # log likelihood\n C = W*W'.+ σ²*Id\n M⁻¹ = inv(W'*W .+ σ²*Iq)\n C⁻¹ = (Id - W*M⁻¹*W')/σ²\n L = (-n/2)*(log(det(C)) + tr(C⁻¹*S)) # (-n/2)*d*log(2π) omitted\n\n @debug \"Likelihood\" iter=i L=L ΔL=abs(L_old - L)\n chg = abs(L_old - L)\n if chg < tol\n converged = true\n break\n end\n L_old = L\n i += 1\n end\n converged || throw(ConvergenceException(maxiter, chg, oftype(chg, tol)))\n\n return PPCA(mean, W, σ²)\nend\n\n\n\"\"\"\n bayespca(S, mean, n; ...)\n\nCompute probabilistic PCA using a Bayesian algorithm for a given sample covariance matrix `S`.\n\n*Parameters*:\n- `S`: The sample covariance matrix.\n- `mean`: The mean vector of original samples, which can be a vector of length `d`,\nor an empty vector indicating a zero mean.\n- `n`: The number of observations.\n\nReturns the resultant [`PPCA`](@ref) model.\n\n**Notes:**\n- This function accepts three keyword arguments: `maxoutdim`, `tol`, and `maxiter`.\n- Function uses the `maxoutdim` parameter as an upper boundary when it automatically\ndetermines the latent space dimensionality.\n\"\"\"\nfunction bayespca(S::AbstractMatrix{T}, mean::Vector{T}, n::Int;\n maxoutdim::Int=size(S,1)-1,\n tol::Real=1.0e-6, # convergence tolerance\n maxiter::Integer=1000) where {T<:Real}\n\n check_pcaparams(size(S,1), mean, maxoutdim, 1.)\n\n d = size(S,1)\n q = maxoutdim\n Iq = Matrix{T}(I, q, q)\n Id = Matrix{T}(I, d, d)\n W = Matrix{T}(I, d, q)\n wnorm = zeros(T, q)\n σ² = zero(T)\n M = W'*W .+ σ²*Iq\n M⁻¹ = inv(M)\n α = zeros(T, q)\n\n i = 1\n chg = NaN\n L_old = 0.\n converged = false\n while i < maxiter\n # EM-steps\n SW = S*W\n W⁺ = SW*inv(σ²*(Iq+diagm(0=>α)*M/n) + M⁻¹*W'*SW)\n σ²⁺ = tr(S - SW*M⁻¹*(W⁺)')/d\n # new parameters\n W = W⁺\n σ² = σ²⁺\n @inbounds for j in 1:q\n wnorm[j] = norm(W[:,j])^2\n α[j] = wnorm[j] < eps() ? maxintfloat(Float64) : d/wnorm[j]\n end\n # log likelihood\n C = W*W'.+ σ²*Id\n M = W'*W .+ σ²*Iq\n M⁻¹ = inv(M)\n C⁻¹ = (Id - W*M⁻¹*W')/σ²\n L = (-n/2)*(log(det(C)) + tr(C⁻¹*S)) # (-n/2)*d*log(2π) omitted\n\n @debug \"Likelihood\" iter=i L=L ΔL=abs(L_old - L)\n chg = abs(L_old - L)\n if chg < tol\n converged = true\n break\n end\n L_old = L\n i += 1\n end\n converged || throw(ConvergenceException(maxiter, chg, oftype(chg, tol)))\n\n return PPCA(mean, W[:,wnorm .> 0.], σ²)\nend\n\n## interface functions\n\"\"\"\n\n fit(PPCA, X; ...)\n\nPerform probabilistic PCA over the data given in a matrix `X`.\nEach column of `X` is an observation. This method returns an instance of [`PPCA`](@ref).\n\n**Keyword arguments:**\n\nLet `(d, n) = size(X)` be respectively the input dimension and the number of observations:\n\n- `method`: The choice of methods:\n - `:ml`: use maximum likelihood version of probabilistic PCA (*default*)\n - `:em`: use EM version of probabilistic PCA\n - `:bayes`: use Bayesian PCA\n- `maxoutdim`: Maximum output dimension (*default* `d-1`)\n- `mean`: The mean vector, which can be either of:\n - `0`: the input data has already been centralized\n - `nothing`: this function will compute the mean (*default*)\n - a pre-computed mean vector\n- `tol`: Convergence tolerance (*default* `1.0e-6`)\n- `maxiter`: Maximum number of iterations (*default* `1000`)\n\n**Notes:** This function calls [`ppcaml`](@ref), [`ppcaem`](@ref) or\n[`bayespca`](@ref) internally, depending on the choice of method.\n\"\"\"\nfunction fit(::Type{PPCA}, X::AbstractMatrix{T};\n method::Symbol=:ml,\n maxoutdim::Int=size(X,1)-1,\n mean=nothing,\n tol::Real=1.0e-6, # convergence tolerance\n maxiter::Integer=1000) where {T<:Real}\n\n @assert !SparseArrays.issparse(X) \"Use Kernel PCA for sparse arrays\"\n\n d, n = size(X)\n\n # process mean\n mv = preprocess_mean(X, mean)\n if !(isempty(mv) || length(mv) == d)\n throw(DimensionMismatch(\"Dimensions of weight matrix and mean are inconsistent.\"))\n end\n\n if method == :ml\n Z = centralize(X, mv)\n M = ppcaml(Z, mv, maxoutdim=maxoutdim, tol=tol)\n elseif method == :em || method == :bayes\n S = covm(X, isempty(mv) ? 0 : mv, 2)\n if method == :em\n M = ppcaem(S, mv, n, maxoutdim=maxoutdim, tol=tol, maxiter=maxiter)\n elseif method == :bayes\n M = bayespca(S, mv, n, maxoutdim=maxoutdim, tol=tol, maxiter=maxiter)\n end\n else\n throw(ArgumentError(\"Invalid method name $(method)\"))\n end\n\n return M::PPCA\nend\n\n", "meta": {"hexsha": "84008903353a81ade86cc641279994ad5bbd8387", "size": 9416, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ppca.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/ppca.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/ppca.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": 27.6941176471, "max_line_length": 111, "alphanum_fraction": 0.5936703483, "num_tokens": 2921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582612793112, "lm_q2_score": 0.8757869835428965, "lm_q1q2_score": 0.8148832339583763}} {"text": "using LinearAlgebra\r\ninclude(\"poisson_linear_system.jl\")\r\n\r\nfunction step_jacobi!(unext, uprev, rhs, stepsize)\r\n numpts = length(unext)\r\n for i = 2:numpts-1\r\n unext[i] = 0.5 * (uprev[i-1] + uprev[i+1] + stepsize^2 * rhs[i])\r\n end\r\nend\r\n\r\nfunction run_jacobi_iterations(u0, rhs, stepsize, numiter)\r\n uprev = copy(u0)\r\n unext = copy(u0)\r\n for iter = 1:numiter\r\n step_jacobi!(unext, uprev, rhs, stepsize)\r\n uprev .= unext\r\n end\r\n return unext\r\nend\r\n\r\nfunction run_jacobi_measure_error(u0, rhs, stepsize, numiter, uexact)\r\n numpts = length(u0)\r\n uprev = copy(u0)\r\n unext = copy(u0)\r\n err = zeros(numiter)\r\n for iter = 1:numiter\r\n step_jacobi!(unext, uprev, rhs, stepsize)\r\n uprev .= unext\r\n err[iter] = norm(unext - uexact) / numpts\r\n end\r\n return unext, err\r\nend\r\n\r\nfunction solve_direct(rhs, bcleft, bcright, stepsize)\r\n numpts = length(rhs)\r\n op = -poisson_linear_system(numpts)\r\n copyrhs = copy(rhs)\r\n copyrhs[1] = bcleft / stepsize^2\r\n copyrhs[numpts] = bcright / stepsize^2\r\n sol = stepsize^2 * (op \\ copyrhs)\r\n return sol\r\nend\r\n\r\nfunction jacobi_error_vs_iterations(numiter, numelements, wavenumber)\r\n xL = -1.0\r\n xR = +1.0\r\n bcleft = bcright = 0.0\r\n\r\n numpts = numelements + 1\r\n stepsize = (xR - xL) / numelements\r\n xrange = range(xL, stop = xR, length = numpts)\r\n rhs = cos.(wavenumber * xrange)\r\n\r\n u0 = zeros(numpts)\r\n udirect = solve_direct(rhs, bcleft, bcright, stepsize)\r\n\r\n ujacobi, err = run_jacobi_measure_error(u0, rhs, stepsize, numiter, udirect)\r\n\r\n return err\r\nend\r\n\r\n# numelements = [4, 8, 16, 32]\r\n# numiter = numelements .^ 2\r\n# wavenumber = 2pi\r\n# err = [\r\n# jacobi_error_vs_iterations(numiter[i], numelements[i], wavenumber) for\r\n# i = 1:length(numelements)\r\n# ]\r\n#\r\n#\r\n# using Plots\r\n# plot( err[1], yscale = :log10, label = string(numelements[1]))\r\n# plot!(err[2], yscale = :log10, label = string(numelements[2]))\r\n# plot!(err[3], yscale = :log10, label = string(numelements[3]))\r\n# plot!(err[4], yscale = :log10, label = string(numelements[4]))\r\n# plot!(err[5], yscale = :log10, label = string(numelements[5]))\r\n", "meta": {"hexsha": "d9a105070a743f4ba54092a6bbc163d07cb15033", "size": 2186, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "jacobi.jl", "max_stars_repo_name": "ArjunNarayanan/ExploreJacobi", "max_stars_repo_head_hexsha": "cbeeba2a165ecc61ea294c8974929a28edea6481", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "jacobi.jl", "max_issues_repo_name": "ArjunNarayanan/ExploreJacobi", "max_issues_repo_head_hexsha": "cbeeba2a165ecc61ea294c8974929a28edea6481", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jacobi.jl", "max_forks_repo_name": "ArjunNarayanan/ExploreJacobi", "max_forks_repo_head_hexsha": "cbeeba2a165ecc61ea294c8974929a28edea6481", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3896103896, "max_line_length": 81, "alphanum_fraction": 0.6230558097, "num_tokens": 721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582477806522, "lm_q2_score": 0.8757869916479466, "lm_q1q2_score": 0.8148832296778371}} {"text": "function lgd100()\n#\n# test polynomial suggested by Goedecker\n# Legendre polynomial of degree 100\n#\n p = lgd(100);\n z = [-.9997137267734412; -.9984919506395958; -.9962951347331251; -.9931249370374435;\n -.9889843952429917; -.9838775407060570; -.9778093584869183; -.9707857757637063;\n -.9628136542558155; -.9539007829254917; -.9440558701362560; -.9332885350430795;\n -.9216092981453340; -.9090295709825297; -.8955616449707270; -.8812186793850184;\n -.8660146884971646; -.8499645278795913; -.8330838798884008; -.8153892383391763;\n -.7968978923903145; -.7776279096494955; -.7575981185197072; -.7368280898020207;\n -.7153381175730564; -.6931491993558020; -.6702830156031410; -.6467619085141293;\n -.6226088602037078; -.5978474702471787; -.5725019326213812; -.5465970120650942;\n -.5201580198817631; -.4932107892081909; -.4657816497733580; -.4378974021720315;\n -.4095852916783015; -.3808729816246300; -.3517885263724217; -.3223603439005292;\n -.2926171880384720; -.2625881203715035; -.2323024818449740; -.2017898640957360;\n -.1710800805386033; -.1402031372361140; -.1091892035800611; -.7806858281343664e-1;\n -.4687168242159163e-1; -.1562898442154308e-1; .1562898442154308e-1; .4687168242159163e-1;\n .7806858281343664e-1; .1091892035800611; .1402031372361140; .1710800805386033;\n .2017898640957360; .2323024818449740; .2625881203715035; .2926171880384720;\n .3223603439005292; .3517885263724217; .3808729816246300; .4095852916783015;\n .4378974021720315; .4657816497733580; .4932107892081909; .5201580198817631;\n .5465970120650942; .5725019326213812; .5978474702471787; .6226088602037078;\n .6467619085141293; .6702830156031410; .6931491993558020; .7153381175730564;\n .7368280898020207; .7575981185197072; .7776279096494955; .7968978923903145;\n .8153892383391763; .8330838798884008; .8499645278795913; .8660146884971646;\n .8812186793850184; .8955616449707270; .9090295709825297; .9216092981453340;\n .9332885350430795; .9440558701362560; .9539007829254917; .9628136542558155;\n .9707857757637063; .9778093584869183; .9838775407060570; .9889843952429917;\n .9931249370374435; .9962951347331251; .9984919506395958; .9997137267734412]\n z = [z ones(100)]\n # Legendre polynomial, roots are sensitive, see plot.\n \n p, PolyZeros(z)\nend\n", "meta": {"hexsha": "f85503354dad8fbf325b4c4fb7384069a8e1861a", "size": 2422, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/testsuit/lgd100.m.jl", "max_stars_repo_name": "KlausC/Multroot.jl", "max_stars_repo_head_hexsha": "df3978ad1af9829f644155d834a1305b73623b7f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/testsuit/lgd100.m.jl", "max_issues_repo_name": "KlausC/Multroot.jl", "max_issues_repo_head_hexsha": "df3978ad1af9829f644155d834a1305b73623b7f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/testsuit/lgd100.m.jl", "max_forks_repo_name": "KlausC/Multroot.jl", "max_forks_repo_head_hexsha": "df3978ad1af9829f644155d834a1305b73623b7f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 65.4594594595, "max_line_length": 98, "alphanum_fraction": 0.7274979356, "num_tokens": 914, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802350995702, "lm_q2_score": 0.8872046041554922, "lm_q1q2_score": 0.8148798934061576}} {"text": "alpine1(x) = sum(abs(x .* sin(x) + 0.1 .* x))\nalpine2(x) = prod(sqrt(x) .* sin(x))\nchung_reynolds(x) = sum(x .^ 2) ^ 2\nqing(x) = sum((x .^ 2 - (1:length(x))) .^ 2)\n", "meta": {"hexsha": "394b5004d015ff60de831655037454ce23e49e1d", "size": 164, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Functions.jl", "max_stars_repo_name": "ozanarkancan/ParticleSwarmOptimization.jl", "max_stars_repo_head_hexsha": "46d0644efa8bf666a90bb540f736f8107083b5a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-01-16T01:59:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-26T15:10:20.000Z", "max_issues_repo_path": "examples/Functions.jl", "max_issues_repo_name": "ozanarkancan/ParticleSwarmOptimization.jl", "max_issues_repo_head_hexsha": "46d0644efa8bf666a90bb540f736f8107083b5a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2016-03-30T21:51:57.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-19T18:18:31.000Z", "max_forks_repo_path": "examples/Functions.jl", "max_forks_repo_name": "ozanarkancan/ParticleSwarmOptimization.jl", "max_forks_repo_head_hexsha": "46d0644efa8bf666a90bb540f736f8107083b5a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-09-25T22:12:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-05T19:11:02.000Z", "avg_line_length": 32.8, "max_line_length": 45, "alphanum_fraction": 0.506097561, "num_tokens": 76, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.972830769252026, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.8148624732703775}} {"text": "using LinearAlgebra\nusing SparseArrays\nusing Plots\n\n\"This routine solves the advection equation with an inflow boundary condition using\nForward Euler in time and finite differences in space.\"\n\nm = 100 # number of points\n\n# define spatial grid\nx = LinRange(-1,1,m+2)\nxint = x[2:end]\nh = x[2]-x[1]\n\nα(t) = sin(pi*t)\ndt = h # timestep\nT = 4.0 # final time\n\n# initial condition and forcing\nu0(x) = 0.0\nf(x,t) = 0.0\nfunction F(α,xint,t,h)\n fvec = f.(xint,t)\n fvec[1] += α(t)/h\n return fvec\nend\n\n# upwind approximation of first derivative\nQ = (1/h) * spdiagm(0=>ones(m+1),-1=>-ones(m))\n\nu = u0.(xint)\nNsteps = ceil(Int,T/dt)\ndt = T / Nsteps\n\ninterval = 1\nplot()\n@gif for k = 1:Nsteps\n tk = k*dt\n u .= u + dt * (F(α,xint,tk,h) - Q*u)\n if k % interval==0\n plot(xint,u,linewidth=2,label=\"Solution\")\n println(\"on timestep $k out of $Nsteps.\")\n end\nend every interval\n\n# plot(xint,u,linewidth=2,label=\"Solution\")\n# plot!(x,u0.(x .- T),linewidth=2,label=\"Exact solution\",ylims=(-1.0,2.0))\n", "meta": {"hexsha": "65a10f17bc8eeee197073867f3d529f447b0be63", "size": 1012, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "week4/fd_advec_inflow.jl", "max_stars_repo_name": "jlchan/caam452_s21", "max_stars_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-01-29T01:52:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T15:38:43.000Z", "max_issues_repo_path": "week4/fd_advec_inflow.jl", "max_issues_repo_name": "jlchan/caam452_s21", "max_issues_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week4/fd_advec_inflow.jl", "max_forks_repo_name": "jlchan/caam452_s21", "max_forks_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0833333333, "max_line_length": 83, "alphanum_fraction": 0.6373517787, "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012701768145, "lm_q2_score": 0.8615382165412808, "lm_q1q2_score": 0.8148439395106108}} {"text": "# Based on PWSCF documentation (version 6.2)\n\nfunction gen_lattice_cubic( a::Float64 )\n v1 = a*[1,0,0]\n v2 = a*[0,1,0]\n v3 = a*[0,0,1]\n #\n LL = zeros(3,3)\n LL[:,1] = v1\n LL[:,2] = v2\n LL[:,3] = v3\n return LL\nend\n\ngen_lattice_sc(a::Float64) = gen_lattice_cubic(a)\n\nfunction gen_lattice_fcc( a::Float64 )\n v1 = 0.5*a*[-1,0,1]\n v2 = 0.5*a*[0,1,1]\n v3 = 0.5*a*[-1,1,0]\n #\n LL = zeros(3,3)\n LL[:,1] = v1\n LL[:,2] = v2\n LL[:,3] = v3\n return LL\nend\n\nfunction gen_lattice_bcc( a::Float64 )\n v1 = 0.5*a*[1,1,1]\n v2 = 0.5*a*[-1,1,1]\n v3 = 0.5*a*[-1,-1,1]\n #\n LL = zeros(3,3)\n LL[:,1] = v1\n LL[:,2] = v2\n LL[:,3] = v3\n return LL \nend\n\n# more symmetric axis:\nfunction gen_lattice_bcc_v2( a::Float64 )\n v1 = 0.5*a*[-1,1,1]\n v2 = 0.5*a*[1,-1,1]\n v3 = 0.5*a*[1,1,-1]\n #\n LL = zeros(3,3)\n LL[:,1] = v1\n LL[:,2] = v2\n LL[:,3] = v3\n return LL\nend\n\n# also for trigonal P\nfunction gen_lattice_hexagonal( a::Float64, c::Float64 )\n v1 = a*[1,0,0]\n v2 = a*[-1/2,sqrt(3)/2,0]\n v3 = [0,0,c]\n #\n LL = zeros(3,3)\n LL[:,1] = v1\n LL[:,2] = v2\n LL[:,3] = v3\n return LL \nend\n\n\n# 5 Trigonal R, 3fold axis c celldm(4)=cos(gamma)\n# The crystallographic vectors form a three-fold star around\n# the z-axis, the primitive cell is a simple rhombohedron:\n# v1 = a(tx,-ty,tz), v2 = a(0,2ty,tz), v3 = a(-tx,-ty,tz)\n# where c=cos(gamma) is the cosine of the angle gamma between\n# any pair of crystallographic vectors, tx, ty, tz are:\n# tx=sqrt((1-c)/2), ty=sqrt((1-c)/6), tz=sqrt((1+2c)/3)\nfunction gen_lattice_trigonal( a::Float64, gamma_degree::Float64 )\n c = cos( gamma_degree*pi/180 )\n tx = sqrt((1-c)/2)\n ty = sqrt((1-c)/6)\n tz = sqrt((1+2c)/3)\n #\n v1 = a*[tx,-ty,tz]\n v2 = a*[0,2*ty,tz]\n v3 = a*[-tx,-ty,tz]\n #\n LL = zeros(3,3)\n LL[:,1] = v1\n LL[:,2] = v2\n LL[:,3] = v3\n return LL\nend\n\n# -5 Trigonal R, 3fold axis <111> celldm(4)=cos(gamma)\n# The crystallographic vectors form a three-fold star around\n# <111>. Defining a' = a/sqrt(3) :\n# v1 = a' (u,v,v), v2 = a' (v,u,v), v3 = a' (v,v,u)\n# where u and v are defined as\n# u = tz - 2*sqrt(2)*ty, v = tz + sqrt(2)*ty\n# and tx, ty, tz as for case ibrav=5\n# Note: if you prefer x,y,z as axis in the cubic limit,\n# set u = tz + 2*sqrt(2)*ty, v = tz - sqrt(2)*ty\n# See also the note in Modules/latgen.f90\nfunction gen_lattice_trigonal_v2( a::Float64, gamma_degree::Float64 )\n c = cos( gamma_degree*pi/180 ) \n tx = sqrt((1-c)/2)\n ty = sqrt((1-c)/6)\n tz = sqrt((1+2c)/3)\n u = tz - 2*sqrt(2)*ty\n v = tz + sqrt(2)*ty\n ap = a/sqrt(3)\n #\n v1 = ap*[u,v,v]\n v2 = ap*[v,u,v]\n v3 = ap*[v,v,u]\n #\n LL = zeros(3,3)\n LL[:,1] = v1\n LL[:,2] = v2\n LL[:,3] = v3\n return LL\nend\n\n#Tetragonal P (st) celldm(3)=c/a\n#v1 = a(1,0,0), v2 = a(0,1,0), v3 = a(0,0,c/a)\nfunction gen_lattice_tetragonal_P( a::Float64, c::Float64)\n v1 = a*[1,0,0]\n v2 = a*[0,1,0]\n v3 = [0,0,c]\n #\n LL = zeros(3,3)\n LL[:,1] = v1\n LL[:,2] = v2\n LL[:,3] = v3\n return LL\nend\n\n\n#7 Tetragonal I (bct) celldm(3)=c/a\n#v1=(a/2)(1,-1,c/a), v2=(a/2)(1,1,c/a), v3=(a/2)(-1,-1,c/a)\nfunction gen_lattice_tetragonal_I( a::Float64, c::Float64 )\n v1 = 0.5*[a,-a,c]\n v2 = 0.5*[a,a,c]\n v3 = 0.5*[-a,-a,c]\n #\n LL = zeros(3,3)\n LL[:,1] = v1\n LL[:,2] = v2\n LL[:,3] = v3\n return LL\nend\n\n# 8 Orthorhombic P celldm(2)=b/a\n# celldm(3)=c/a\n# v1 = (a,0,0), v2 = (0,b,0), v3 = (0,0,c)\nfunction gen_lattice_orthorhombic_P( a::Float64, b::Float64, c::Float64 )\n v1 = [a,0,0]\n v2 = [0,b,0]\n v3 = [0,0,c]\n #\n LL = zeros(3,3)\n LL[:,1] = v1\n LL[:,2] = v2\n LL[:,3] = v3\n return LL\nend\n\n# 12 Monoclinic P, unique axis c celldm(2)=b/a\n# celldm(3)=c/a,\n# celldm(4)=cos(ab)\n# v1=(a,0,0), v2=(b*cos(gamma),b*sin(gamma),0), v3 = (0,0,c)\n# where gamma is the angle between axis a and b.\nfunction gen_lattice_monoclinic_P( a::Float64, b::Float64, c::Float64, gamma_degree::Float64 )\n gamma = gamma_degree*pi/180\n v1 = [a,0,0]\n v2 = [b*cos(gamma), b*sin(gamma), 0]\n v3 = [0,0,c]\n #\n LL = zeros(3,3)\n LL[:,1] = v1\n LL[:,2] = v2\n LL[:,3] = v3\n return LL\nend\n\n# 14 Triclinic celldm(2)= b/a,\n# celldm(3)= c/a,\n# celldm(4)= cos(bc),\n# celldm(5)= cos(ac),\n# celldm(6)= cos(ab)\n# v1 = (a, 0, 0),\n# v2 = (b*cos(gamma), b*sin(gamma), 0)\n# v3 = (c*cos(beta), c*(cos(alpha)-cos(beta)cos(gamma))/sin(gamma),\n# c*sqrt( 1 + 2*cos(alpha)cos(beta)cos(gamma)\n# - cos(alpha)^2-cos(beta)^2-cos(gamma)^2 )/sin(gamma) )\n# where alpha is the angle between axis b and c\n# beta is the angle between axis a and c\n# gamma is the angle between axis a and b\n\nfunction gen_lattice_triclinic(a::Float64, b::Float64, c::Float64,\n alpha_degree::Float64, beta_degree::Float64, gamma_degree::Float64)\n\n if alpha_degree + beta_degree + gamma_degree <= 180.0\n println(\"ERROR in gen_lattice_triclinic\")\n println(\"sum of angles must be larger than 180°\")\n exit()\n end\n\n alpha = alpha_degree*pi/180\n beta = beta_degree*pi/180\n gamma = gamma_degree*pi/180\n\n #\n v1 = [a, 0, 0]\n v2 = [b*cos(gamma), b*sin(gamma), 0]\n t1 = c*(cos(alpha)-cos(beta)cos(gamma))/sin(gamma)\n t2 = c*sqrt( 1 + 2*cos(alpha)cos(beta)cos(gamma) -\n cos(alpha)^2-cos(beta)^2-cos(gamma)^2 )/sin(gamma)\n v3 = [c*cos(beta), t1, t2]\n #\n LL = zeros(3,3)\n LL[:,1] = v1\n LL[:,2] = v2\n LL[:,3] = v3\n return LL\nend\n", "meta": {"hexsha": "99bda8549fc5726626fcf2718d1a163b6b54ddc4", "size": 6096, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "PW/common/gen_lattice_pwscf.jl", "max_stars_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_stars_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2018-01-03T02:19:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-29T13:30:20.000Z", "max_issues_repo_path": "PW/common/gen_lattice_pwscf.jl", "max_issues_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_issues_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PW/common/gen_lattice_pwscf.jl", "max_forks_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_forks_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-03-23T06:58:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-03T00:54:28.000Z", "avg_line_length": 27.0933333333, "max_line_length": 98, "alphanum_fraction": 0.4886811024, "num_tokens": 2416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012655937034, "lm_q2_score": 0.8615382129861582, "lm_q1q2_score": 0.814843932199646}} {"text": "\"\"\"julia\n rotx(θ::Real)\n\nA matrix representing the rotation about the X-axis by an angle θ.\n\"\"\"\nfunction rotx(θ::Real)\ncosθ = cos(θ);\nsinθ = sin(θ);\n𝐑ˣ = [1.0 0.0 0.0 ;\n 0. cosθ -sinθ ;\n 0 sinθ cosθ ]\nend\n\n\"\"\"juliaa\n roty(θ::Real)\n\nA matrix representing rotation about the Y-axis by an angle θ.\n\"\"\"\nfunction roty(θ::Real)\ncosθ = cos(θ);\nsinθ = sin(θ);\n𝐑ʸ = [cosθ 0.0 sinθ ;\n 0.0 1.0 0.0 ;\n -sinθ 0.0 cosθ]\nend\n\n\"\"\"julia\n rotz(θ::Real)\n\nA matrix representing the rotation about the Z-axis by an angle θ.\n\"\"\"\nfunction rotz(θ::Real)\ncosθ = cos(θ);\nsinθ = sin(θ);\n𝐑ᶻ = [cosθ -sinθ 0.0 ;\n sinθ cosθ 0.0 ;\n 0.0 0.0 1.0 ]\nend\n\n\"\"\"julia\n rotz(θ::Real)\n\nA matrix representing the rotation about the X-axis, Y-axis and Z-axis by the angles θˣ, θʸ, and θᶻ respectively.\n\"\"\"\nfunction rotxyz(θˣ::Real,θʸ::Real,θᶻ::Real)\n rotx(θˣ)*roty(θʸ)*rotz(θᶻ)\nend\n\n\"\"\"\n rotate!(camera::CameraModel, 𝐑::AbstractArray)\n\nRotates a camera around its optical center by a rotation matrix 𝐑.\n\"\"\"\nfunction rotate!(camera::CameraModel, 𝐑::AbstractArray)\n camera.𝐞₁ = 𝐑₂*camera.𝐞₁\n camera.𝐞₂ = 𝐑₂*camera.𝐞₂\n camera.𝐞₃ = 𝐑₂*camera.𝐞₃\n camera\nend\n\n\nfunction rodrigues2matrix(vˣ::Real,vʸ::Real,vᶻ::Real)\n 𝐯 = [vˣ, vʸ, vᶻ]\n θ = norm(𝐯)\n 𝐯 = θ == 0 ? 𝐯 : 𝐯/θ\n 𝐈 = Matrix(1.0I, 3, 3)\n 𝐖 = vec2antisym(𝐯)\n 𝐑 = 𝐈 + 𝐖 * sin(θ) + 𝐖^2 * (1-cos(θ))\nend\n", "meta": {"hexsha": "1abae9f960bd0195640d769fd475f9384a49eefa", "size": 1472, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/rotation/rotations.jl", "max_stars_repo_name": "JuliaTagBot/MultipleViewGeometry.jl", "max_stars_repo_head_hexsha": "cafd7f61f30258f804ac31c5f9648b54edc6b347", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-29T18:45:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-29T18:45:09.000Z", "max_issues_repo_path": "src/rotation/rotations.jl", "max_issues_repo_name": "JuliaTagBot/MultipleViewGeometry.jl", "max_issues_repo_head_hexsha": "cafd7f61f30258f804ac31c5f9648b54edc6b347", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-03-17T16:03:51.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-18T09:13:22.000Z", "max_forks_repo_path": "src/rotation/rotations.jl", "max_forks_repo_name": "JuliaTagBot/MultipleViewGeometry.jl", "max_forks_repo_head_hexsha": "cafd7f61f30258f804ac31c5f9648b54edc6b347", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:18:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-27T20:13:09.000Z", "avg_line_length": 21.0285714286, "max_line_length": 113, "alphanum_fraction": 0.5747282609, "num_tokens": 648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305307578324, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.8148375884909677}} {"text": "\n# coding: utf-8\n\n# In[1]:\n\n\n#radix sort is fun\n#there are two ways to do it\n#the first approach is we start from the right\n#the second one is to start from the left\n#in this context, i choose the first approach\n#they are equivalent\n#we get the first digit of all elements\n#sort these elements based upon the first digit\n#for instance, 215 and 19\n#9 for 19 is larger than 5 for 215\n#for the first round, we get 215,19\n#we move on to the second digit of all elements from the right\n#we apply the same technique of sorting based upon the second digit\n#until we reach to the very left digit of the maximum value in the list\n#the sort is completed\n#for instance, the second round would be 215,19\n#since the second digit of both numbers are 1\n#the final round is 19,215\n#as 0 for 19 is smaller than 2 for 215\n#period\n\n#to implement this method in python\n#we can apply fld(x,10)%10 technique\n#for the first round, fld(x,1)%10 gets the first digit from the left\n#for the second round, fld(x,10)%10 gets the second digit from the left\n#and so on\n#we can use a nested list to store elements in its rightful place\n#i use digits its index indicates its digit+1\n#becuz julia starts from 1\n#there are other elegant solutions, plz check the link at the very end\n\n\n# In[2]:\n\n\nfunction radix_sort(arr)\n\n maxval=maximum(arr)\n digits=0\n \n #the first part is to find the largest element in the list\n #next, we find out how many digits it contains\n #so we can determine how many times we need to divide in the later stage\n while maxval>=1\n maxval=maxval/10\n digits+=1\n end\n \n \n for digit in 1:digits\n \n #each time, we clear the nested list\n digit_sort=[[] for _ in 1:10]\n radix=10^(digit-1)\n \n #this is a traversal on all elements in the list\n for i in arr\n \n #fld(i,radix)%10 is the technique to get digits\n #when we get it, we use i+1 as index\n #so that we can store the element in its rightful place \n ind=fld(i,radix)%10\n \n push!(digit_sort[ind+1],i)\n \n end\n \n #we have to empty the list after we put all elements into a nested list \n arr=[]\n \n #this loop is unnecessary\n #we can use append(digit_sort[1],...digit_sort[10])\n #again, i am a lazy person\n #cut me some slack, s’il vous plaît \n for j in 1:10 \n append!(arr,digit_sort[j])\n end\n \n end\n \n return arr\n\nend\n\n\n# In[3]:\n\n\n#surprisingly, the radix sort is really fast\n#the time complexity of radix sort is o(k*n)\n#k depends on the digits of the maximum value in the list\n#well, its harder to get a number like 10^1000 than getting a list with 10^1000 elements\n#when we get a list with smaller n and larger k\n#radix sort may be a terrible choice\n\n#there are other ways of writing radix sort\n#i believe my way has too much space complexity\n#this one is rather smart and elegant\n# https://www.geeksforgeeks.org/radix-sort/\n\n\n# In[4]:\n\n\nfor _ in 1:100\n \n test_arr=rand(1:1000,100)\n\n if !(radix_sort(test_arr)==sort(test_arr))\n printstyled(\"Erreur\",color=:red)\n end\n\nend\n\n", "meta": {"hexsha": "529d6ff5fffd5c6baa2574e2e0dc2f6af10d1c12", "size": 3249, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "radix sort.jl", "max_stars_repo_name": "je-suis-tm/search-and-sort", "max_stars_repo_head_hexsha": "822bbb1c53ac8ed6c244a18bd4ee03fcc577438e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2019-04-30T23:50:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T04:26:29.000Z", "max_issues_repo_path": "radix sort.jl", "max_issues_repo_name": "HafizSabia/search-and-sort", "max_issues_repo_head_hexsha": "b2a720b154f12549ae31f8647dc460ee343ec119", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "radix sort.jl", "max_forks_repo_name": "HafizSabia/search-and-sort", "max_forks_repo_head_hexsha": "b2a720b154f12549ae31f8647dc460ee343ec119", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-10-04T20:07:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-29T08:54:30.000Z", "avg_line_length": 26.8512396694, "max_line_length": 88, "alphanum_fraction": 0.6546629732, "num_tokens": 858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110425624792, "lm_q2_score": 0.9136765204755286, "lm_q1q2_score": 0.8148268102901396}} {"text": "# This file includes an example for two dimensional interpolation over triangular interpolation domain.\n\nusing FractalTools\nusing Triangulation\nusing PyPlot \nusing Statistics\n\nclose(\"all\")\n\ndatapath = joinpath(@__DIR__, \"data/gmsh_data\")\nfilename = \"t3.msh\"\n\n# Read mesh file.\nmesh = read_mesh(joinpath(datapath, filename))\nscale_factor = 1 / 10 # Rescale the mesh.\nfor node in mesh.nodes\n node.x /= scale_factor\n node.y /= scale_factor\nend\nmeshes = triangular_partition(mesh)\nregions = gmsh2matplotlibtri.(meshes)\n# region = regions[1]\n\n# Compute z-values on mesh points.\nfunc(x, y) = [\n x^2 + y^2,\n x^2 - y^2\n]\nnumber_of_regions = length(regions)\nz = Vector{Vector}(undef, number_of_regions)\nt = Vector{Vector}(undef, number_of_regions)\nfor k = 1 : number_of_regions\n z[k] = getindex.(func.(regions[k].x, regions[k].y), 1)\n t[k] = getindex.(func.(regions[k].x, regions[k].y), 2)\nend\n\n# Refine region to evaluate interpolated function\nsubdiv = 3\nx, y = refine(gmsh2matplotlibtri(mesh), subdiv, true)\n\n# Compute initial and real values.\nfunc0(xi, yi) = [0., 0.]\n\n# Perform interpolation.\nα7, α8, α11, α12 = fill(0.001, 4)\ninterpolant, coeffs = hiddenfis(regions, z, t, α7=α7, α8=α8, α11=α11, α12=α12, func0=func0, num_iter=10, get_coeffs=true)\n\n# Interpolation and error\nreal_values = func.(x, y)\nreal_values_z = getindex.(real_values, 1)\nreal_values_t = getindex.(real_values, 2)\ninterpolated_values = interpolant.(x, y)\ninterpolated_values_z = getindex.(interpolated_values, 1)\ninterpolated_values_t = getindex.(interpolated_values, 2)\nabsolute_error_z = abs.(real_values_z - interpolated_values_z)\nabsolute_error_t = abs.(real_values_t - interpolated_values_t)\nrelative_error_z = absolute_error_z ./ (abs.(real_values_z .+ eps())) * 100\nrelative_error_t = absolute_error_t ./ (abs.(real_values_t .+ eps())) * 100\nfrerr_z = mean(absolute_error_z.^2)\nfrerr_t = mean(absolute_error_t.^2)\n\n# Plot the results.\nxd = xcoords(mesh)\nyd = ycoords(mesh)\nztd = func.(xd, yd)\nzd = getindex.(ztd, 1)\ntd = getindex.(ztd, 2)\nminx, meanx, maxx = minimum(x), mean(x), maximum(x)\nminy, meany, maxy = minimum(y), mean(y), maximum(y)\n\n# Plot the results\nfigure(\"Real and Interpolated Values z\")\nplot_trisurf(x, y, real_values_z)\ncolors = [\"black\", \"red\", \"blue\", \"green\", \"purple\", \"magenta\"]\nfor (color, region) in zip(colors, regions)\n triplot(region, color=color)\n plot(region.x, region.y, \".\", color=\"orange\")\nend\nxlabel(\"x\", labelpad=10, fontsize=12)\nylabel(\"y\", labelpad=10, fontsize=12)\nzlabel(\"z\", labelpad=10, fontsize=12)\nxticks(range(minx, maxx, length=5))\nyticks(range(miny, maxy, length=5))\n# zticks(range(minimum(real_values_z), maximum(real_values_z), length=5))\ntight_layout()\n\nplot_trisurf(x, y, interpolated_values_z)\ncolors = [\"black\", \"red\", \"blue\", \"green\", \"purple\", \"magenta\"]\nfor (color, region) in zip(colors, regions)\n triplot(region, color=color)\n plot(region.x, region.y, \".\", color=\"orange\")\nend\nxlabel(\"x\", labelpad=10, fontsize=12)\nylabel(\"y\", labelpad=10, fontsize=12)\nzlabel(\"z\", labelpad=10, fontsize=12)\nxticks(range(minx, maxx, length=5))\nyticks(range(miny, maxy, length=5))\n# zticks(range(minimum(interpolated_values_z), maximum(interpolated_values_z), length=5))\ntight_layout()\ndisplay(gcf())\n\nfigure(\"Absolute Values z\")\nplot_trisurf(x, y, absolute_error_z)\ncolors = [\"black\", \"red\", \"blue\", \"green\", \"purple\", \"magenta\"]\nfor (color, region) in zip(colors, regions)\n triplot(region, color=color)\n plot(region.x, region.y, \".\", color=\"orange\")\nend\nxlabel(\"x\", labelpad=10, fontsize=12)\nylabel(\"y\", labelpad=10, fontsize=12)\nzlabel(\"z\", labelpad=10, fontsize=12)\nxticks(range(minx, maxx, length=5))\nyticks(range(miny, maxy, length=5))\n# zticks(range(minimum(absolute_error_z), maximum(absolute_error_z), length=5))\ntight_layout()\ndisplay(gcf())\n\nfigure(\"Relative Error z\")\nplot_trisurf(x, y, relative_error_z)\ncolors = [\"black\", \"red\", \"blue\", \"green\", \"purple\", \"magenta\"]\nfor (color, region) in zip(colors, regions)\n triplot(region, color=color)\n plot(region.x, region.y, \".\", color=\"orange\")\nend\nxlabel(\"x\", labelpad=10, fontsize=12)\nylabel(\"y\", labelpad=10, fontsize=12)\nzlabel(\"z\", labelpad=10, fontsize=12)\nxticks(range(minx, maxx, length=5))\nyticks(range(miny, maxy, length=5))\n# zticks(range(minimum(relative_error_z), maximum(relative_error_z), length=5))\ntight_layout()\ndisplay(PyPlot.gcf())\n\nfigure(\"Real and Interpolated Values t\")\nplot_trisurf(x, y, real_values_t)\ncolors = [\"black\", \"red\", \"blue\", \"green\", \"purple\", \"magenta\"]\nfor (color, region) in zip(colors, regions)\n triplot(region, color=color)\n plot(region.x, region.y, \".\", color=\"orange\")\nend\nxlabel(\"x\", labelpad=10, fontsize=12)\nylabel(\"y\", labelpad=10, fontsize=12)\nzlabel(\"z\", labelpad=10, fontsize=12)\nxticks(range(minx, maxx, length=5))\nyticks(range(miny, maxy, length=5))\n# zticks(range(minimum(real_values_t), maximum(real_values_t), length=5))\ntight_layout()\n\nplot_trisurf(x, y, interpolated_values_t)\ncolors = [\"black\", \"red\", \"blue\", \"green\", \"purple\", \"magenta\"]\nfor (color, region) in zip(colors, regions)\n triplot(region, color=color)\n plot(region.x, region.y, \".\", color=\"orange\")\nend\nxlabel(\"x\", labelpad=10, fontsize=12)\nylabel(\"y\", labelpad=10, fontsize=12)\nzlabel(\"z\", labelpad=10, fontsize=12)\nxticks(range(minx, maxx, length=5))\nyticks(range(miny, maxy, length=5))\n# zticks(range(minimum(interpolated_values_t), maximum(interpolated_values_t), length=5))\ntight_layout()\ndisplay(gcf())\n\nfigure(\"Absolute Values t\")\nplot_trisurf(x, y, absolute_error_t)\ncolors = [\"black\", \"red\", \"blue\", \"green\", \"purple\", \"magenta\"]\nfor (color, region) in zip(colors, regions)\n triplot(region, color=color)\n plot(region.x, region.y, \".\", color=\"orange\")\nend\nxlabel(\"x\", labelpad=10, fontsize=12)\nylabel(\"y\", labelpad=10, fontsize=12)\nzlabel(\"z\", labelpad=10, fontsize=12)\nxticks(range(minx, maxx, length=5))\nyticks(range(miny, maxy, length=5))\n# zticks(range(minimum(absolute_error_t), maximum(absolute_error_t), length=5))\ntight_layout()\ndisplay(gcf())\n\nfigure(\"Relative Error t\")\nplot_trisurf(x, y, relative_error_t)\ncolors = [\"black\", \"red\", \"blue\", \"green\", \"purple\", \"magenta\"]\nfor (color, region) in zip(colors, regions)\n triplot(region, color=color)\n plot(region.x, region.y, \".\", color=\"orange\")\nend\nxlabel(\"x\", labelpad=10, fontsize=12)\nylabel(\"y\", labelpad=10, fontsize=12)\nzlabel(\"z\", labelpad=10, fontsize=12)\nxticks(range(minx, maxx, length=5))\nyticks(range(miny, maxy, length=5))\n# zticks(range(minimum(relative_error_t), maximum(relative_error_t), length=5))\ntight_layout()\ndisplay(PyPlot.gcf())\n", "meta": {"hexsha": "5508d67090fb705c86a62163ca159830322cc485", "size": 6576, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/stash/hidden_fis/hidden_fis_triangular.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/hidden_fis/hidden_fis_triangular.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/hidden_fis/hidden_fis_triangular.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": 33.7230769231, "max_line_length": 121, "alphanum_fraction": 0.7133515815, "num_tokens": 1988, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541626630937, "lm_q2_score": 0.8652240808393984, "lm_q1q2_score": 0.8147418573587686}} {"text": "@doc raw\"\"\"\r\n```\r\nZ = retrieve_surface(algorithm::Pentland, img::AbstractArray)\r\n```\r\nAttempts to produce a heightmap from a grayscale image using Pentland's algorithm.\r\n\r\nUnder the assumptions of Lambertian surface, orthographic projections,\r\nthe surface being illuminated by distant light sources, the surface is\r\nnot self-shadowing and the surface has constant albedo, hence it can be ignored.\r\nThe algorithm employs Tayler series expansion and Fourier transforms to compute\r\na non-iterative solution.\r\n# Output\r\nReturns an M by N array (matching dimensions of original image) of Float `Z`\r\nthat represents the reconstructed height at the point.\r\n# Details\r\nIn Pentlands algorithm the image irradiance is defined as:\r\n```math\r\nE(x,y)=R(p,q)=\\dfrac{\\rho(i_xp+i_yq-i_z)}{\\sqrt{1+p^2+q^2}}=\\dfrac{p\\sin\\sigma\\cos\r\n\\tau+q\\sin\\sigma\\sin\\tau+\\cos\\sigma}{\\sqrt{1+p^2+q^2}}\r\n```\r\nThis can be reduced using the Taylor series expansion about ``p=p_0`` and ``p=p_0``\r\nand ignoring the higher order terms becomes:\r\n```math\r\nE(x,y)=R(p,q)\\approx R(p_0,q_0)+(p-p_0)\\dfrac{\\delta R}{\\delta p}(p_0,q_0)+(q-q_0)\r\n\\dfrac{\\delta R}{\\delta q}(p_0,q_0)\r\n```\r\nwhich for ``p_0=q_0=0`` further reduces to:\r\n```math\r\nE(x,y)\\approx\\cos\\sigma+p\\cos\\tau\\sin\\sigma+q\\sin\\tau\\sin\\sigma\r\n```\r\nThis gives the following transform identities:\r\n```math\r\n\\begin{gathered}\r\np=\\dfrac{\\delta}{\\delta x}Z(x,y)\\xleftrightarrow{\\Im}(-j\\omega_x)F_z(\r\n\\omega_x,\\omega_y)\\\\q=\\dfrac{\\delta}{\\delta y}Z(x,y)\\xleftrightarrow{\\Im}(-j\r\n\\omega_y)F_z(\\omega_x,\\omega_y)\r\n\\end{gathered}\r\n```\r\nBy taking the Fourier transform of both sides if ``E(x,y)`` yields the following:\r\n```math\r\nF_E=(-j\\omega_x)F_z(\\omega_x,\\omega_y)\\cos\\tau\\sin\\sigma+(-j\\omega_y)F_z(\\omega_x\r\n,\\omega_y)\\sin\\tau\\sin\\sigma\r\n```\r\nwhere ``F_z`` is the Fourier transform of ``Z(x,y)``.\r\n\r\nThese can be rearranged, and the Inverse Fourier transform used to recover the\r\nsurface ``Z(x,y)`` as per the following:\r\n```math\r\n\\begin{gathered}\r\nF_E=F_z(\\omega_x,\\omega_y)[-j\\omega_x\\cos\\tau\\sin\\sigma-j\\omega_y\\sin\\tau\\sin\r\n\\sigma]\\\\\\Rightarrow F_z(\\omega_x,\\omega_y)=\\dfrac{F_E}{-j\\omega_x\\cos\\tau\\sin\r\n\\sigma-j\\omega_y\\sin\\tau\\sin\\sigma}\\\\Z(x,y)=\\Im^{-1}\\{F_z(\\omega_x,\\omega_y)\\}\r\n\\end{gathered}\r\n```\r\n\r\nThe `slant` and `tilt` can be manually defined using the function signature:\r\n```\r\nZ = retrieve_surface(algorithm::Pentland, img::AbstractArray, slant::Real, tilt::Real)\r\n```\r\nNote: if `slant` and `tilt` are not defined they will be calculated at runtime\r\nusing `estimate_img_properties`.\r\n# Arguments\r\nThe function arguments are described in more detail below.\r\n## `img`\r\nAn `AbstractArray` storing the grayscale value of each pixel within\r\nthe range [0,1].\r\n## `slant`\r\nA `Real` that specifies the slant value to be used by the algorithm. The `slant`\r\nshould be a value in the range [0,π/2]. If `slant` is specified to must the `tilt`.\r\n## `tilt`\r\nA `Real` that specifies the tilt value to be used by the algorithm. The `tilt`\r\nshould be a value in the range [0,2π]. If `tilt` is specified to must\r\nthe `slant`.\r\n# Example\r\nCompute the heightmap for a synthetic image generated by `generate_surface`.\r\n```julia\r\nusing Images, Makie, ShapeFromShading\r\n\r\n#generate synthetic image\r\nimg = generate_surface(SynthSphere(), 1, [0.2,0,0.9], radius = 5)\r\n\r\n#calculate the heightmap\r\nZ = retrieve_surface(Pentland(), img)\r\n\r\n#normalize to maximum of 1 (not necessary but makes displaying easier)\r\nZ = Z./maximum(Z)\r\n\r\n#display using Makie (Note: Makie can often take several minutes first time)\r\nr = 0.0:0.1:2\r\nsurface(r, r, Z)\r\n```\r\n# Reference\r\n1. A. Pentland, \"Shape Information From Shading: A Theory About Human Perception,\" [1988 Proceedings] Second International Conference on Computer Vision, Tampa, FL, USA, 1988, pp. 404-413. [doi: 10.1109/CCV.1988.590017](https://doi.org/10.1109/ccv.1988.590017)\r\n\"\"\"\r\nfunction retrieve_surface(algorithm::Pentland, img::AbstractArray)\r\n ρ, I, σ, τ = estimate_img_properties(img)\r\n return retrieve_surface(Pentland(),img,σ,τ)\r\nend\r\n\r\nfunction retrieve_surface(algorithm::Pentland, img::AbstractArray, slant::Real, tilt::Real)\r\n #find illumination and albedo\r\n σ = slant\r\n τ = tilt\r\n E = Complex{Float64}.(reinterpret(Float64, img))\r\n #take Fourier transform\r\n fft!(E)\r\n M, N = size(E)\r\n\r\n #setup wx and wy\r\n wx, wy = setup_transform_values_pentland(M, N)\r\n\r\n #using the illumination direction calculate the transformed Z\r\n Zₜ = zeros(Complex{Float64}, size(E))\r\n for i in CartesianIndices(Zₜ)\r\n Zₜ[i] = E[i] / (-1im * wx[i] * cos(τ) * sin(σ) - 1im * wy[i] * sin(τ)\r\n * sin(σ))\r\n end\r\n\r\n #recover Z\r\n ifft!(Zₜ)\r\n Z = zeros(Float64, size(E))\r\n for i in CartesianIndices(Z)\r\n Z[i] = abs(Zₜ[i])\r\n end\r\n return Z\r\nend\r\n", "meta": {"hexsha": "8b6c20e082fcffd0498ec5e7060b2e1a3168d6df", "size": 4762, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/pentland.jl", "max_stars_repo_name": "JuliaTagBot/ShapeFromShading.jl", "max_stars_repo_head_hexsha": "c602cf16e4c795b65164e6d96b26cbdfc0d2e0c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pentland.jl", "max_issues_repo_name": "JuliaTagBot/ShapeFromShading.jl", "max_issues_repo_head_hexsha": "c602cf16e4c795b65164e6d96b26cbdfc0d2e0c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-02-08T06:23:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-08T17:29:42.000Z", "max_forks_repo_path": "src/pentland.jl", "max_forks_repo_name": "JuliaTagBot/ShapeFromShading.jl", "max_forks_repo_head_hexsha": "c602cf16e4c795b65164e6d96b26cbdfc0d2e0c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-01-08T04:40:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-27T20:13:00.000Z", "avg_line_length": 37.4960629921, "max_line_length": 261, "alphanum_fraction": 0.6925661487, "num_tokens": 1454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377272885903, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.8147294371542109}} {"text": "### A Pluto.jl notebook ###\n# v0.14.3\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 7a63ed47-abf4-4432-bdce-23b7375dc02c\nusing Pkg, DrWatson\n\n# ╔═╡ fc142be9-b765-4930-8d70-00a9cfda6110\nbegin\n\t@quickactivate \"NumericalMethodsforEngineers\"\n\tusing NumericalMethodsforEngineers, Test\nend\n\n# ╔═╡ 44feedf7-0c4a-4f17-9384-8cdb3d30f743\nbegin\n\ta = [10. 1. -5.; -20. 3. 20.; 5. 3. 5.]\n\tb = [1., 2., 6.]\nend;\n\n# ╔═╡ 7813d567-6e63-4056-95e3-0b0872a0d21a\n# Convert to upper triang;e\nfunction to_upper(a::Matrix, b::Vector)\n at = deepcopy(a)\n bt = deepcopy(b) \n r, c = size(at)\n\n for k in 1:r-1\n if abs(at[k, k]) > 1.0e-6\n for i in k+1:r\n x = at[i, k] / at[k, k]\n at[i, k] = 0.0\n for j in k+1:r\n at[i, j] -= at[k, j] * x\n end\n bt[i] -= bt[k] * x\n end\n else\n md\"Zero pivot found in row $k\"\n end\n end\n (a=at, b=bt)\nend\n\n# ╔═╡ 67af792e-5577-45ed-a1b5-1e977180de34\n# Direct solve upper triangular set of equations\nfunction direct_solve(a::Matrix, b::Vector)\n at = deepcopy(a)\n bt = deepcopy(b)\n r, c = size(at)\n\n for i in r:-1:1\n x = bt[i]\n if i < r\n for j in i+1:r\n x -= at[i, j] * bt[j]\n end\n end\n bt[i] = x / at[i, i]\n end\n bt\nend\n\n# ╔═╡ 08b41bf9-e8d6-4773-a173-605de915441d\nmd\" ##### Modified lhs matrix and rhs\"\n\n# ╔═╡ 0d465be8-722f-4f51-ba82-f9a41915dc4e\nat, bt = to_upper(a, b)\n\n# ╔═╡ 8ede85a1-1270-423a-86a1-58ef53f33ca6\nmd\" ##### Solution vector:\"\n\n# ╔═╡ b817e219-d7f7-4de3-a0d6-691f3f33827b\nc_nmfe = direct_solve(at, bt)\n\n# ╔═╡ 6a048f48-eadc-4657-bd01-042f43cac5e3\nc = a\\b\n\n# ╔═╡ 96afae01-56d3-4b33-8cf6-9cf9ef9490c5\n@test round.(c; digits=14) == round.(c_nmfe, digits=14)\n\n# ╔═╡ 2e4ee9a0-85e1-4933-97a5-4e15ffbcafea\n@test round.(a * c; digits=14) == b\n\n# ╔═╡ Cell order:\n# ╠═7a63ed47-abf4-4432-bdce-23b7375dc02c\n# ╠═fc142be9-b765-4930-8d70-00a9cfda6110\n# ╠═44feedf7-0c4a-4f17-9384-8cdb3d30f743\n# ╠═7813d567-6e63-4056-95e3-0b0872a0d21a\n# ╠═67af792e-5577-45ed-a1b5-1e977180de34\n# ╟─08b41bf9-e8d6-4773-a173-605de915441d\n# ╠═0d465be8-722f-4f51-ba82-f9a41915dc4e\n# ╟─8ede85a1-1270-423a-86a1-58ef53f33ca6\n# ╠═b817e219-d7f7-4de3-a0d6-691f3f33827b\n# ╠═6a048f48-eadc-4657-bd01-042f43cac5e3\n# ╠═96afae01-56d3-4b33-8cf6-9cf9ef9490c5\n# ╠═2e4ee9a0-85e1-4933-97a5-4e15ffbcafea\n", "meta": {"hexsha": "959d80f9761e7446fe5c0b9fa46b74e2fbb9b75f", "size": 2240, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/02/f-02-01.jl", "max_stars_repo_name": "PtFEM/NumericalMethodsforEngineers.jl", "max_stars_repo_head_hexsha": "e4a997a14adbb86b7efe1586962df39eb9285ebb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-07-23T18:12:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-25T03:32:45.000Z", "max_issues_repo_path": "notebooks/02/f-02-01.jl", "max_issues_repo_name": "PtFEM/NumericalMethodsforEngineers.jl", "max_issues_repo_head_hexsha": "e4a997a14adbb86b7efe1586962df39eb9285ebb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2018-07-23T21:46:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-27T23:14:46.000Z", "max_forks_repo_path": "notebooks/02/f-02-01.jl", "max_forks_repo_name": "PtFEM/NumericalMethodsforEngineers.jl", "max_forks_repo_head_hexsha": "e4a997a14adbb86b7efe1586962df39eb9285ebb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-10-27T14:13:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T18:54:06.000Z", "avg_line_length": 22.6262626263, "max_line_length": 55, "alphanum_fraction": 0.6495535714, "num_tokens": 1174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505248181418, "lm_q2_score": 0.9005297821135385, "lm_q1q2_score": 0.8146647400033795}} {"text": "function computus(year; servois=false)\n\n # Year's position on the 19 year metonic cycle\n a = mod(year, 19)\n\n # Century index\n k = fld(year, 100)\n\n # Shift of metonic cycle, add a day offset every 300 years\n p = fld(13 + 8 * k, 25)\n\n # Correction for non-observed leap days\n q = fld(k, 4)\n\n # Correction to starting point of calculation each century\n M = mod(15 - p + k - q, 30)\n\n # Number of days from March 21st until the full moon\n d = mod(19 * a + M, 30)\n\n # Returning if user wants value for Servois' table\n if servois\n return string(mod(21 + d,31))\n end\n\n # Finding the next Sunday\n # Century-based offset in weekly calculation\n N = mod(4 + k - q, 7)\n\n # Correction for leap days\n b = mod(year, 4)\n c = mod(year, 7)\n\n # Days from d to next Sunday\n e = mod(2 * b + 4 * c + 6 * d + N, 7)\n\n # Historical corrections for April 26 and 25\n if (d == 29 && e == 6) || (d == 28 && e == 6 && a > 10)\n e = -1\n end\n\n # Determination of the correct month for Easter\n if(22 + d + e > 31)\n return \"April \" * string(d + e - 9)\n else\n return \"March \" * string(22 + d + e)\n end\nend\n\n# Here, we will output the date of the Paschal full moon\n# (using Servois notation), and Easter for 2020-2030\n\na = collect(2020:2030)\nservois_numbers = computus.(a; servois=true)\neaster_dates = computus.(a)\n\nprintln(\"The following are the dates of the Paschal full moon (using Servois \" *\n \"notation) and the date of Easter for 2020-2030 AD:\")\nprintln(\"Year\\tServois number\\tEaster\")\nfor i = 1:length(a)\n println(\"$(a[i])\\t$(servois_numbers[i])\\t\\t$(easter_dates[i])\")\nend\n", "meta": {"hexsha": "676cad4f6e57bf08067c8fe9eef5d821c774aade", "size": 1671, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "contents/computus/code/julia/gauss_easter.jl", "max_stars_repo_name": "Iinguistics/algorithm-archivists.github.io", "max_stars_repo_head_hexsha": "3759b22a9c21b8b7a9bf075ca880e02ec524abc5", "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/computus/code/julia/gauss_easter.jl", "max_issues_repo_name": "Iinguistics/algorithm-archivists.github.io", "max_issues_repo_head_hexsha": "3759b22a9c21b8b7a9bf075ca880e02ec524abc5", "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/computus/code/julia/gauss_easter.jl", "max_forks_repo_name": "Iinguistics/algorithm-archivists.github.io", "max_forks_repo_head_hexsha": "3759b22a9c21b8b7a9bf075ca880e02ec524abc5", "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": 26.5238095238, "max_line_length": 80, "alphanum_fraction": 0.605625374, "num_tokens": 531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632261523028, "lm_q2_score": 0.8558511432905481, "lm_q1q2_score": 0.8146532303586779}} {"text": "\nfunction func(t,x)\n return exp(2*t)*x^2\nend\n\nfunction newtonFunc(yn1, tn1, yn)\n return yn1-yn-h*func(tn1, yn)\n # x_{n+1} - x_n -hfunc(t_{n+1}, x_{n+1}) =0\nend\n\n\nfunction fixedpointFunc(tn, yn)\n return yn+h*func(tn, yn)\n # x_{n+1} - x_n -hfunc(t_{n+1}, x_{n+1}) =0\nend\n\n\nfunction newton(a, b, index, previous)\n steps = 0\n mid = (a + b)/2\n while b-a>=2*tolerance \n #println(\"Step\", \" \", steps)\n mid = (a + b)/2\n if (abs(newtonFunc(mid, time[index],previous ))100\n if index==N\n println(\"newton steps: \", steps)\n end\n return mid\n end\n if index==N\n println(\"newton steps: \", steps)\n end\n end\n if index==N\n println(\"newton steps: \", steps)\n end\n return mid\nend\n\nfunction fixedpoint(x0, index)\n\n ## x = hf(t,x) -x0\n\n x1 = fixedpointFunc(time[index], x0)\n x2 = fixedpointFunc(time[index], x1)\n k = 0\n shouldReturn=0\n while(abs(x2-x1)>=tolerance && abs(fixedpointFunc(time[index], x2)-x2)>=tolerance && k<=maxSteps-1)\n x2temp=x2;\n x2=fixedpointFunc(time[index],x1);\n x1=x2temp;\n k=k+1;\n if (abs(fixedpointFunc(time[index],x2)-x2)0 && i+i1<=size\n row[count]=l\n col[count]=I(i+i1,j)\n v[count]=hd\n count+=1\n end\n if j+i1>0 && j+i1<=size\n row[count]=l\n col[count]=I(i,j+i1)\n v[count]=hd\n count+=1\n end\n end\n\n end\n end\n\n M=sparse(row,col,v)\n return M,size2,count-1\nend\nfunction PreLapl3(size)\n #const size2=size*size\n I(i::Int64,j::Int64,k::Int64)=(k-1)*size*size+(j-1)*size+i\n nc= 7*(size-2)^3 + 36*(size-2)^2 + 60*(size-2)+ 8*4\n row=Array{Int64}(nc)\n col=Array{Int64}(nc)\n v=Array{Float64}(nc)\n h=1./(size-1)\n h2=h*h\n cd=-6.0/h2\n hd=1.0/h2\n count=1\n for k=1:size\n for j=1:size\n for i=1:size\n l=I(i,j,k)\n row[count]=l\n col[count]=l\n v[count]=cd\n count+=1\n for ii1 =0:2:2\n i1=ii1-1\n if i+i1>0 && i+i1<=size\n row[count]=l\n col[count]=I(i+i1,j,k)\n v[count]=hd\n count+=1\n end\n if j+i1>0 && j+i1<=size\n row[count]=l\n col[count]=I(i,j+i1,k)\n v[count]=hd\n count+=1\n end\n if k+i1>0 && k+i1<=size\n row[count]=l\n col[count]=I(i,j,k+i1)\n v[count]=hd\n count+=1\n end \n end \n end\n end\n end\n\n M=sparse(row,col,v)\n return M,size^3,count-1\nend\nend\n", "meta": {"hexsha": "032fb1a61f1b08b64de7781cf8ba696394640f9c", "size": 2417, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Sparse/Ju/Sparse23.jl", "max_stars_repo_name": "wolfv/BenchmarksPythonJuliaAndCo", "max_stars_repo_head_hexsha": "b0b6a0ed752069539085d7f2d57b4341bce8feb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Sparse/Ju/Sparse23.jl", "max_issues_repo_name": "wolfv/BenchmarksPythonJuliaAndCo", "max_issues_repo_head_hexsha": "b0b6a0ed752069539085d7f2d57b4341bce8feb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sparse/Ju/Sparse23.jl", "max_forks_repo_name": "wolfv/BenchmarksPythonJuliaAndCo", "max_forks_repo_head_hexsha": "b0b6a0ed752069539085d7f2d57b4341bce8feb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7127659574, "max_line_length": 62, "alphanum_fraction": 0.3611915598, "num_tokens": 717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693617046216, "lm_q2_score": 0.8577681104440172, "lm_q1q2_score": 0.8145960939359492}} {"text": "using LinearAlgebra\nusing SparseArrays\nusing Plots\nusing ForwardDiff\n\n\"This routine solves Poisson's equation using piecewise linear finite element methods.\nThe matrix is assembled locally, and boundary nodes are not removed.\"\n\nm = 100 # number of elements\n\nα = 0.0\nβ = 0.0\nf(x) = sin(2*pi*x)\nκ(x) = 1.0 + 2.0*(x > 0)\n\n# define spatial grid\nx = LinRange(-1,1,m+2) # x_0, x_1, ..., x_m, x_{m+1} = x_0\nxint = x[1:end-1]\nh = x[2]-x[1]\n\n# x = x + randn(size(x))/(2*m)\n# x = @. x + (1+x)*(1-x)/3\n\n# construct local FEM matrix\nmap_point(x,a,b) = a + (b-a) * x # maps x ∈ [0,1] to interval [a,b]\nA = spzeros(m+2,m+2)\nb = zeros(m+2)\nA_local = [1 -1;-1 1]\nfor e = 1:m+1\n h_e = x[e+1] - x[e]\n ids = e:e+1\n\n # use 1-point quadrature to approximate integrals\n x_e = map_point(0, x[e], x[e+1])\n w_e = 2.0\n\n # accumulate local contributions\n A[ids,ids] += A_local * κ(x_e) / h_e\n b[ids] += h_e/2 * w_e * f(x_e) * [.5;.5]\nend\n\n# modify for boundary conditions\nfunction impose_Dirichlet_BC!(A,b,i,val)\n b .-= A[:,i]*val\n b[i] = val\n A[i,:] .= 0\n A[:,i] .= 0\n A[i,i] = 1.0\nend\nfunction impose_Neumann_BC!(A,b,i,val)\n b[i] += val\nend\n\nimpose_Dirichlet_BC!(A,b,1,α)\nimpose_Dirichlet_BC!(A,b,m+2,β)\n\nu = A\\b\n\n# uex = @. (1+x)*(1-x)/2\nplot(x,u,legend=false,mark=:dot,ms=2)\n", "meta": {"hexsha": "8617abcb657aa4dd11b52a35383df30a84bee0c8", "size": 1294, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "week8/fem_laplace_1D_local.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": "week8/fem_laplace_1D_local.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": "week8/fem_laplace_1D_local.jl", "max_forks_repo_name": "jlchan/caam452_s21", "max_forks_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.2131147541, "max_line_length": 86, "alphanum_fraction": 0.5927357032, "num_tokens": 527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391706552538, "lm_q2_score": 0.8824278618165526, "lm_q1q2_score": 0.8145154817342396}} {"text": "\n#=\ndef logx(x, n): \n for i in range(0, n):\n x = math.log(x) if x>0 else 0\n return x\n=#\n\nfunction logx(x, n) # iterative logarithm function\n for i in 0:n-1\n \tx = x > 0.0 ? log(x) : 0.0\n end\n return x\nend\n\n", "meta": {"hexsha": "98a2eb36139338a15dd02e3cb1ec7ec4834dd212", "size": 242, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "approaches/dynamic_pricing/utils/logx.jl", "max_stars_repo_name": "StatisticalRethinkingJulia/DynamicPricingExamples.jl", "max_stars_repo_head_hexsha": "a6fae1736bf30f7aeed22452630c3ca3f018c50a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-02-19T06:59:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-21T07:57:57.000Z", "max_issues_repo_path": "approaches/dynamic_pricing/utils/logx.jl", "max_issues_repo_name": "StatisticalRethinkingJulia/DynamicPricingExamples.jl", "max_issues_repo_head_hexsha": "a6fae1736bf30f7aeed22452630c3ca3f018c50a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "approaches/dynamic_pricing/utils/logx.jl", "max_forks_repo_name": "StatisticalRethinkingJulia/DynamicPricingExamples.jl", "max_forks_repo_head_hexsha": "a6fae1736bf30f7aeed22452630c3ca3f018c50a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.125, "max_line_length": 62, "alphanum_fraction": 0.4917355372, "num_tokens": 94, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9230391558356, "lm_q2_score": 0.8824278664544912, "lm_q1q2_score": 0.8145154729379632}} {"text": "\"\"\"\n lagrange(xⁱ, m, x)\n\nCalculate the Lagrange interpolating polynomial Lⁱₘ(x), given the roots\n`xⁱ`.\n\nLⁱₘ(x) = ∏(j≠m) (x-xⁱⱼ)/(xⁱₘ-xⁱⱼ)\n\nEq. (8) Rescigno2000\n\"\"\"\nfunction lagrange(xⁱ::AbstractVector, m::Integer, x::AbstractVector)\n Lₘ = fill(1.0, length(x))\n for j in eachindex(xⁱ)\n j == m && continue\n Lₘ .*= (x .- xⁱ[j])/(xⁱ[m]-xⁱ[j])\n end\n Lₘ\nend\nlagrange(xⁱ::AbstractVector, m::Integer, x::Number) =\n lagrange(xⁱ, m, [x])[1]\n\n\"\"\"\n δ(a,b)\n\nKronecker δ function\"\"\"\nδ(a,b) = a == b ? 1 : 0\n\n\"\"\"\n lagrangeder!(xⁱ, m, L′)\n\nCalculate the derivative of the Lagrange interpolating polynomial\nLⁱₘ(x), given the roots `xⁱ`, *at* the roots, and storing the result\nin `L′`.\n\nLⁱₘ′(x) = (xⁱₘ-xⁱₘ,)⁻¹ ∏(k≠m,m′) (xⁱₘ,-xⁱₖ)/(xⁱₘ-xⁱₖ), m≠m′,\n [δ(m,n) - δ(m,1)]/2wⁱₘ, m=m′\n\nEq. (20) Rescigno2000\n\"\"\"\nfunction lagrangeder!(xⁱ::AbstractVector, wⁱ::AbstractVector,\n L′::AbstractMatrix)\n n = length(xⁱ)\n for m in 1:n\n L′[m,m] = (δ(m,n)-δ(m,1))/2wⁱ[m]\n for m′ in 1:n\n m′ == m && continue\n f = 1\n for k = 1:n\n k in [m,m′] && continue\n f *= (xⁱ[m′]-xⁱ[k])/(xⁱ[m]-xⁱ[k])\n end\n L′[m,m′] = f/(xⁱ[m]-xⁱ[m′])\n end\n end\nend\n\nfunction lagrangeder(grid::Grid)\n n = order(grid)\n\n L′ = zeros(elcount(grid), n, n)\n for i = elems(grid)\n sel = (1:n) .+ (i-1)*(n-1)\n lagrangeder!(grid.X[i,:], grid.W[i,:],\n view(L′, i, :, :))\n end\n L′\nend\n", "meta": {"hexsha": "a3ce47c9cf34b89d32b76dfe07b53d4828c8579c", "size": 1556, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lagrange.jl", "max_stars_repo_name": "jfeist/FEDVR.jl", "max_stars_repo_head_hexsha": "90abda07d43df9c027f5739b3fa08a9bfcdd4d15", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2017-08-30T23:56:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-17T03:24:00.000Z", "max_issues_repo_path": "src/lagrange.jl", "max_issues_repo_name": "jfeist/FEDVR.jl", "max_issues_repo_head_hexsha": "90abda07d43df9c027f5739b3fa08a9bfcdd4d15", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2018-01-03T20:21:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-17T09:36:20.000Z", "max_forks_repo_path": "src/lagrange.jl", "max_forks_repo_name": "jfeist/FEDVR.jl", "max_forks_repo_head_hexsha": "90abda07d43df9c027f5739b3fa08a9bfcdd4d15", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-11-11T12:14:02.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-26T15:37:31.000Z", "avg_line_length": 22.8823529412, "max_line_length": 71, "alphanum_fraction": 0.4922879177, "num_tokens": 647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475730993028, "lm_q2_score": 0.8633916222765627, "lm_q1q2_score": 0.8144783915088655}} {"text": "module NewtonsMethod\n\n using Expectations, Distributions, ForwardDiff, LinearAlgebra\n\n function newtonroot(f,f′; x₀,tol=1E-7,maxiter=1000)\n x_old=x₀\n iter=0\n diff=1000\n while diff>tol && iter<=maxiter\n x_new=x_old-f(x_old)/f′(x_old)\n iter=iter+1\n diff=norm(x_old-x_new)\n x_old=x_new\n end\n if iter ForwardDiff.derivative(f, x)\n\nnewtonroot(f;x₀,tol=1E-7,maxiter=1000)=newtonroot(f,D(f),x₀=x₀,tol=tol,maxiter=maxiter)\n\nexport newtonroot\n\nend # module\n", "meta": {"hexsha": "74b6bb31dc714422e1ac4794eb5e92124caa63c4", "size": 644, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NewtonsMethod.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": "src/NewtonsMethod.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": "src/NewtonsMethod.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": 23.0, "max_line_length": 87, "alphanum_fraction": 0.5931677019, "num_tokens": 198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475746920261, "lm_q2_score": 0.8633916064586998, "lm_q1q2_score": 0.8144783779622667}} {"text": "include(\"../utils/format/Heading.jl\")\n\nHeading.main(\"Default type\")\nHeading.sub(\"type for an integer literal depends on whether the target system is 32/64 bit\")\n\n\nprintln(Sys.WORD_SIZE)\n#: 64\n\n\nprintln(typeof(1))\n#: Int64\n\n\n# explicitly give make 32\nprintln(typeof(Int32(1)))\n#: Int32\n\n\n# unsigned UInt is given by hex. \n# size of UInt increases with num of hex\nprintln(typeof(UInt(1)))\nprintln(typeof(0x1)) # small => UInt8\nprintln(typeof(0x0123456789abcdef)) # big => UInt64\n#: UInt64\n#: UInt8 \n#: UInt64\n\n\nHeading.main(\"All types with ranges\")\nrpadval = 50\nfor T in [Int8, Int16, Int32, Int64, Int128, UInt8, UInt16, UInt32, UInt64, UInt128]\n println(\"$(T)\\t:\\t\\t $(rpad(typemin(T), rpadval)) $(typemax(T))\")\nend\n#: Int8 : -128 127\n#: Int16 : -32768 32767\n#: Int32 : -2147483648 2147483647\n#: Int64 : -9223372036854775808 9223372036854775807\n#: Int128 : -170141183460469231731687303715884105728 170141183460469231731687303715884105727\n#: UInt8 : 0 255\n#: UInt16 : 0 65535\n#: UInt32 : 0 4294967295\n#: UInt64 : 0 18446744073709551615\n#: UInt128 : 0 340282366920938463463374607431768211455\n\n\nHeading.main(\"Modular arithematic overflow\")\nmax_int8 = typemax(Int8)\na = Int8(max_int8) + Int8(1)\nprint(a == typemin(Int8))\n#: true\n\n\n# Note: Int8 + Int64 => Int64\na = Int8(max_int8) + 1 # type of `1` is `Sys.WORD_SIZE` i.e 64\nprint(typeof(a))\n#: Int64\n\n\nHeading.main(\"Solution to Overflow\")\nHeading.sub(\"In logics where overflow is possible, do not use Int!!!! Use BigInt\")\n# BigInt is arbitary precision used as `big`\n\n\nprintln(typemax(Int64))\n#: 9223372036854775807\n\n\nprintln(10^19)\n#! -8446744073709551616 (wrong)\n\n\nprintln(big(10)^20)\n#: 100000000000000000000", "meta": {"hexsha": "5df24a93e64039e60d0beb50b92bf5db25667053", "size": 2239, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "02-Data-Types/02-00-Integer.jl", "max_stars_repo_name": "rakesh4real/master-julia", "max_stars_repo_head_hexsha": "b7677184296201e29e90bc768385747c82072cf1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "02-Data-Types/02-00-Integer.jl", "max_issues_repo_name": "rakesh4real/master-julia", "max_issues_repo_head_hexsha": "b7677184296201e29e90bc768385747c82072cf1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "02-Data-Types/02-00-Integer.jl", "max_forks_repo_name": "rakesh4real/master-julia", "max_forks_repo_head_hexsha": "b7677184296201e29e90bc768385747c82072cf1", "max_forks_repo_licenses": ["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.2567567568, "max_line_length": 118, "alphanum_fraction": 0.532380527, "num_tokens": 585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.8856314723088733, "lm_q1q2_score": 0.8144643688848476}} {"text": "function chirp_lin(f0,t1,f1,fs,phase)\n\t#\n\t# f0: frequency at t=0 (Hz)\n\t# f1: frequency at t=t1 (seconds)\n\t# fs: sampling frequency (Hz)\n\t# phase: phase at t=0 (degrees)\n\t#\n\t# variable frequency - linear\n\t# f(t) = f0 + b*t, where b = (f1-f0)/t1\n\t# \n\t# javier.cara@upm.es, 2016 - january\n\n\tnt = Int(t1*fs)\n\tt = (0:nt-1)*(1/fs)\n\n\tb = (f1-f0)/t1\n\tx = Array(Float64,1,nt)\n\tfor k in 1:nt\n\t\t x[k] = sin(2*pi*(f0*t[k] + b/2*t[k]^2) + phase/360*2*pi)\n\tend\n\n\treturn x\n\nend\n\n# ***************************************************************\nfunction chirp_lin_test()\n\t\n\tf0=0.\n\tf1=20.\n\tt1=50.\n\tfs=100.\n\tphase=90.\n\n\tnt = Int(t1*fs)\n\tt = (0:nt-1)*(1/fs)\n\t\t\n\tx = chirp_lin(f0,t1,f1,fs,phase)\n\t\t\n\treturn x,t\nend\n\n# **************************************************************\nfunction chirp_log(f0,t1,f1,fs,phase)\n\t#\n\t# f0: frequency at t=0 (Hz)\n\t# f1: frequency at t=t1 (seconds)\n\t# fs: sampling frequency (Hz)\n\t# phase: phase at t=0 (degrees)\n\t#\n\t# variable frequency - linear\n\t# f(t) = f0*b^t, where b = (f1/f0)(1/t1)\n\t# \n\t# javier.cara@upm.es, 2016 - january\n\t\n\tif f0 == 0\n\t# f0 can't be zero\n\t\tf0 = 1.0e-6\n\tend\n\t\n\tnt = Int(t1*fs)\n\tt = (0:nt-1)*(1/fs)\n\n\tb = (f1/f0)^(1/t1)\n\tx = Array(Float64,1,nt)\n\tfor k in 1:nt\n\t\t x[k] = sin(2*pi*f0*(b^t[k]-1)/log(b) + phase/360*2*pi)\n\tend\n\n\treturn x\n\nend\n\n# ***************************************************************\nfunction chirp_log_test()\n\t\n\tf0=0.\n\tf1=20.\n\tt1=50.\n\tfs=100.\n\tphase=90.\n\n\tnt = Int(t1*fs)\n\tt = (0:nt-1)*(1/fs)\n\t\t\n\tx = chirp_log(f0,t1,f1,fs,phase)\n\t\t\n\treturn x,t\nend\n\n", "meta": {"hexsha": "d29c27c8f658c0a2bdfc12ab9f56b100a94b6e62", "size": 1518, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chirp.jl", "max_stars_repo_name": "javiercara/DynaSEM.jl", "max_stars_repo_head_hexsha": "6b1a3d873bf7230738a47d51d5fc5915f0126e8b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/chirp.jl", "max_issues_repo_name": "javiercara/DynaSEM.jl", "max_issues_repo_head_hexsha": "6b1a3d873bf7230738a47d51d5fc5915f0126e8b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/chirp.jl", "max_forks_repo_name": "javiercara/DynaSEM.jl", "max_forks_repo_head_hexsha": "6b1a3d873bf7230738a47d51d5fc5915f0126e8b", "max_forks_repo_licenses": ["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.6813186813, "max_line_length": 65, "alphanum_fraction": 0.5, "num_tokens": 607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810525948928, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.8144291522419829}} {"text": "function beam01(E,rho,A,I,L,ne,k1,k2)\n\t#\n\t# mass and stiffness matrices for a beam using Hermite elements\n\t# degres of freedom of the element: [y1 rot1 y2 rot2]\n\t# \n\t# E: elasticity modulus\n\t# rho: density\n\t# A: element section\n\t# I: inercia\n\t# L: length of the beam\n\t# ne: number of elements\n\t# k1: added stiffness in vertical direction of first node\n\t# k2: added stiffness in vertical direction of last node\n\t# \n\t# javier.cara@upm.es, \n\t#\n\n\t# local matrices\n\t# *******************************\n\n\t# element length\n\tle = L/ne\n\n\t# matriz de rigidez del elemento\n\tke = [12 6*le -12 6*le;\n\t6*le 4*le^2 -6*le 2*le^2;\n\t-12 -6*le 12 -6*le;\n\t6*le 2*le^2 -6*le 4*le^2]\n\tke = E*I/(le^3)*ke\n\t\t \n\t# matriz de masa del elemento (consistente)\n\tme = [156 22*le 54 -13*le;\n\t22*le 4*le^2 13*le -3*le^2;\n\t54 13*le 156 -22*le;\n\t-13*le -3*le^2 -22*le 4*le^2]\n\tme = rho*A*le/420*me\n\n\t# matrices globales\n\t# *******************************\n\n\t# numero de grados de libertad\n\tndof = (ne+1)*2\n\n\tK = zeros(ndof,ndof)\n\tM = zeros(ndof,ndof)\n\tfor e=1:ne\n\t\t dof1 = (e-1)*2 + 1\n\t\t dof2 = (e-1)*2 + 4\n\t\t K[dof1:dof2,dof1:dof2] = K[dof1:dof2,dof1:dof2] + ke\n\t\t M[dof1:dof2,dof1:dof2] = M[dof1:dof2,dof1:dof2] + me\n\tend\n\n\t# muelles en los extremos en direccion y\n\tK[1,1] = K[1,1] + k1\n\tK[2*ne+1,2*ne+1] = K[2*ne+1,2*ne+1] + k2\n\n\treturn K,M\n\nend\n\n# ================================================================\nfunction beam01_test()\n\n\tE = 2.1e11\n\trho = 7850.\n\tb = 2.\n\th = 0.20\n\tL = 20.\n\tne = 18\n\n\tI = 1/12*b*h^3\n\tA = b*h\n\n\tk1 = 100*E*I\n\tk2 = 100*E*I\n\n\t(K,M) = beam01(E,rho,A,I,L,ne,k1,k2)\n\n\t# frecuencias naturales del model FEM\n\t(W,V) = eig(K,M)\n\two = sqrt(W) # (rad/s)\n\n\t# frecuencias naturales teoricas\n\t# wn=Cn*sqrt(E*I/(rho**L^4), donde Cn=(n*pi)^2\n\twn = zeros(5)\n\tfor m=1:5\n\t\t wn[m] = (m*pi)^2*sqrt(E*I/(rho*A*L^4))\n\tend\n\n\treturn wn,wo[1:5]\n\nend\n\n", "meta": {"hexsha": "4cfa7b1c650fbc49ee9089f80a3c838d46198c2f", "size": 1837, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/beam01.jl", "max_stars_repo_name": "javiercara/DynaSEM.jl", "max_stars_repo_head_hexsha": "6b1a3d873bf7230738a47d51d5fc5915f0126e8b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/beam01.jl", "max_issues_repo_name": "javiercara/DynaSEM.jl", "max_issues_repo_head_hexsha": "6b1a3d873bf7230738a47d51d5fc5915f0126e8b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/beam01.jl", "max_forks_repo_name": "javiercara/DynaSEM.jl", "max_forks_repo_head_hexsha": "6b1a3d873bf7230738a47d51d5fc5915f0126e8b", "max_forks_repo_licenses": ["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.5425531915, "max_line_length": 66, "alphanum_fraction": 0.5557974959, "num_tokens": 801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810466522862, "lm_q2_score": 0.8596637451167995, "lm_q1q2_score": 0.8144291386177778}} {"text": "\n# linear algebra\ncd(\"G:\\\\My Drive\\\\18. Github Repo\\\\DataScience\");\n# load the packages\nusing LinearAlgebra, Images, SparseArrays\n\n# Basic operations\nA = rand(10, 10);\nA = A * A';\nb = rand(10);\nx = A \\ b; # solving linear system\n\n@show norm(b - A * x)\n\n# LU factor\nluA = lu(A)\n\n# QR factor\nqrA = qr(A);\n\n# cholesky\nisposdef(A)\ncholA = cholesky(A)\n\n\n# diag\na = Diagonal([1,2,3])\n\n\n# images\nX1 = load(\".\\\\data\\\\khiam-small.jpg\");\nX1\nXgray = Gray.(X1)\nXgrayvalues = Float64.(Xgray)\n\n# svd\nsSVD_V = svd(Xgrayvalues);\n\n# using the top 10 singular values\nglobal img = zeros(size(Xgrayvalues));\nfor i = 1:50\n global img += sSVD_V.S[i] * sSVD_V.U[:, i] * sSVD_V.V[:, i]';\nend\n\nGray.(img)\n\n@show norm(Xgrayvalues - img)\n\n#\n", "meta": {"hexsha": "b09fb429727771239b9f6108fdf96c332a050f8c", "size": 717, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "02. Linear Algebra.jl", "max_stars_repo_name": "jipq6175/DataScience", "max_stars_repo_head_hexsha": "e601642a6ca992c184781d2850dd60056b9b024d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-25T18:37:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-25T18:37:24.000Z", "max_issues_repo_path": "02. Linear Algebra.jl", "max_issues_repo_name": "jipq6175/DataScience", "max_issues_repo_head_hexsha": "e601642a6ca992c184781d2850dd60056b9b024d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "02. Linear Algebra.jl", "max_forks_repo_name": "jipq6175/DataScience", "max_forks_repo_head_hexsha": "e601642a6ca992c184781d2850dd60056b9b024d", "max_forks_repo_licenses": ["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.34, "max_line_length": 65, "alphanum_fraction": 0.6345885635, "num_tokens": 254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102514755853, "lm_q2_score": 0.8418256432832332, "lm_q1q2_score": 0.814390757267229}} {"text": "using JuMP\nusing Cbc\n\nLP=Model(Cbc.Optimizer)\n@variable(LP, x11>=0)\n@variable(LP, x12>=0)\n@variable(LP, x21>=0)\n@variable(LP, x22>=0)\n@variable(LP, x31>=0)\n@variable(LP, x32>=0)\n@variable(LP, z>=0)\n@constraint(LP, x11+x21+x31<=z)\n@constraint(LP, x12+x22+x32<=24)\n@constraint(LP, x11+2*x12<=15)\n@constraint(LP, 1.2*x21+3x22<=24)\n@constraint(LP, 2*x31+3x32<=18)\n@objective(LP, Max, x11+2*x12+1.2*x21+3*x22+2*x31+3*x32)\nstatus= JuMP.optimize!(LP)\n\nLP=Model(Cbc.Optimizer)\n@variable(LP, x11>=0)\n@variable(LP, x12>=0)\n@variable(LP, x21>=0)\n@variable(LP, x22>=0)\n@variable(LP, x31>=0)\n@variable(LP, x32>=0)\n@variable(LP, z>=0)\n@constraint(LP, x11+x21+x31<=z)\n@constraint(LP, x12+x22+x32<=z)\n@constraint(LP, x11+2*x12>=15)\n@constraint(LP, 1.2*x21+3*x22>=24)\n@constraint(LP, 2*x31+3*x32>=18)\n@objective(LP, Min, z)\nstatus= JuMP.optimize!(LP)\n\nLP=Model(Cbc.Optimizer)\n@variable(LP, x>=0)\n@variable(LP, y>=0)\n@constraint(LP, 4x+6y>=30)\n@constraint(LP, 6x+2y>=20)\n@constraint(LP, x+2y>=12)\n@objective(LP, Min, 2x+3y)\nstatus= JuMP.optimize!(LP)\nprintln(\"X: $(JuMP.value(x))\")\nprintln(\"Y : $(JuMP.value(y))\")\n", "meta": {"hexsha": "110acb8bed2de618553e69cab5145dd3729eec32", "size": 1096, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples_JuliaJUMP/Q2Mar25.jl", "max_stars_repo_name": "valenmgama/optimization-tec", "max_stars_repo_head_hexsha": "b0469628f5ac51dec52052886cd4d561806a9d0a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-07T17:21:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-07T17:21:08.000Z", "max_issues_repo_path": "Examples_JuliaJUMP/Q2Mar25.jl", "max_issues_repo_name": "valenmgama/optimization-tec", "max_issues_repo_head_hexsha": "b0469628f5ac51dec52052886cd4d561806a9d0a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Examples_JuliaJUMP/Q2Mar25.jl", "max_forks_repo_name": "valenmgama/optimization-tec", "max_forks_repo_head_hexsha": "b0469628f5ac51dec52052886cd4d561806a9d0a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8260869565, "max_line_length": 56, "alphanum_fraction": 0.6669708029, "num_tokens": 452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731126558705, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.8143660392514813}} {"text": "Approaching the Unit Circle\n\n x(t) = cospi(t); y(t) = sinpi(t)\n (x(t), y(t)) circles as t ↦ 0..2\n\n```julia\nusing CatmullRom, Plots\n\nfx(t) = cospi(t);\nfy(t) = sinpi(t);\n\nxs = [fx(t) for t=range(0.0, stop=2.0, length=17)];\nys = [fy(t) for t=range(0.0, stop=2.0, length=17)];\npoints = collect(zip(xs, ys));\n\ncxs,cys = catmullrom(points, 16);\n\nplot(cxs,cys, linecolor=:grey, linewidth=4, size=(600,600), legend=nothing, xaxis=nothing, yaxis=nothing)\nplot!(xs, ys, linecolor=:blue, linewidth=2, size=(600,600), legend=nothing, xaxis=nothing, yaxis=nothing)\n```\n", "meta": {"hexsha": "5c21296eda46193507737d6c48ea8057f3dedd4f", "size": 563, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/circle.jl", "max_stars_repo_name": "JeffreySarnoff/-CentripetalCatmullRom.jl", "max_stars_repo_head_hexsha": "49e6536c184dfc4200b980f89aa55bc5cf357b82", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-07-14T17:13:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-12T20:43:13.000Z", "max_issues_repo_path": "examples/circle.jl", "max_issues_repo_name": "JeffreySarnoff/-CentripetalCatmullRom.jl", "max_issues_repo_head_hexsha": "49e6536c184dfc4200b980f89aa55bc5cf357b82", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2018-08-09T20:29:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-08T14:45:14.000Z", "max_forks_repo_path": "examples/circle.jl", "max_forks_repo_name": "JeffreySarnoff/-CentripetalCatmullRom.jl", "max_forks_repo_head_hexsha": "49e6536c184dfc4200b980f89aa55bc5cf357b82", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:26:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-25T12:17:47.000Z", "avg_line_length": 26.8095238095, "max_line_length": 105, "alphanum_fraction": 0.6412078153, "num_tokens": 215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611654370414, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.8143553009989905}} {"text": "\"\"\"\r\n linearshooting(F1,F2,a,b,alpha,beta,M)\r\nberisi program untuk mencari solusi persamaan differensial\r\n`x''=f(t,x,x')` dengan masalah nilai batas `x(a)=alpha` dan `x(b)=beta` pada interval `[a,b]`.\r\nProgram ini secara default berisi 5 masukan, yaitu fungsi `F1` dan `F2` (sistem persamaan\r\ndifferensial hasil transformasi dari `x''`), titik ujung interval `[a,b]`, nilai batas `[alpha,beta]`, dan\r\njumlah sub-interval `M`.\r\n# Example\r\n```jl\r\njulia> F1(t,z) = [ z[2], 2*t/(1+t^2)*z[2]-2/(1+t^2)*z[1]+1 ];\r\n\r\njulia> F2(t,z) = [ z[2], 2*t/(1+t^2)*z[2]-2/(1+t^2)*z[1] ];\r\n\r\njulia> solusi = linearshooting(F1,F2,0,4,1.25,-0.95,40)\r\n41×2 Array{Float64,2}:\r\n 0.0 1.25\r\n 0.1 1.29112\r\n 0.2 1.31735\r\n 0.3 1.32899\r\n ⋮\r\n 3.7 -1.03334\r\n 3.8 -1.01809\r\n 3.9 -0.990472\r\n 4.0 -0.95\r\n```\r\nreturn solusi masalah nilai batas `sol`.\r\n\"\"\"\r\nfunction linearshooting(F1,F2,a,b,alpha,beta,M)\r\n M = Int(M)\r\n Za = [alpha,0];\r\n sol = rungekuttasistem(F1,a,b,Za,M);\r\n U = sol[:,2];\r\n\r\n Za = [0,1];\r\n sol = rungekuttasistem(F2,a,b,Za,M);\r\n V = sol[:,2];\r\n\r\n T = sol[:,1];\r\n X = U + (beta-U[M+1])*V/V[M+1];\r\n solusi = [T X];\r\nend\r\n", "meta": {"hexsha": "6fea17857f24a8ce8db46e1f24d114b3094a18b9", "size": 1127, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/linearshooting.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/linearshooting.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/linearshooting.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.8333333333, "max_line_length": 107, "alphanum_fraction": 0.5803016859, "num_tokens": 494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465062370312, "lm_q2_score": 0.8705972784807408, "lm_q1q2_score": 0.8143101227664286}} {"text": "\"\"\"\nJulia program to find the n-th element from Stern's Diatomic Series\nStern's diatomic series is the sequence which generates the integer sequence that arises\nin the Calkin-Wilf tree. This sequence can be computed by the fusc function.\n\"\"\"\n\nfunction stern_diatomic_num(n)\n if(n == 0)\n return 0\n end \n \n dp = zeros(Int, n)\n\n dp[1] = 1\n # Traverse and Fill the `dp` array.\n for i in 2:n\n # If i is even\n if(i % 2 == 0)\n dp[i] = dp[i ÷ 2]\n # If i is odd\n else\n dp[i] = dp[(i - 1) ÷ 2 ] + dp[(i + 1) ÷ 2]\n end\n end\n return dp[n]\nend\n\nprint(\"Enter the value of n(where you need the nth Stern's Diatomic number): \")\nn = readline()\nn = parse(Int, n)\nif(n < 0)\n print(\"Invalid Value of n !!!\")\n exit()\nend\nres = stern_diatomic_num(n)\nprintln(\"The $n'th Stern's Diatomic is $res.\")\n\n\n\"\"\"\nTime Complexity: O(n), where 'n' is the given number\nSpace Complexity: O(1)\n\nSAMPLE INPUT AND OUTPUT\n\nSAMPLE 1\nEnter the value of n(where you need the nth Stern's Diatomic number): 258\nThe 258'th Stern's Diatomic is 8.\n\nSAMPLE 2\nEnter the value of n(where you need the nth Stern's Diatomic number): -98\nInvalid Value of n !!!\n\"\"\"\n", "meta": {"hexsha": "ecfcd9db91b2a7c83cf4d0184ac4b7b3edcbba65", "size": 1211, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/math/sterns_diatomic_series.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/sterns_diatomic_series.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/sterns_diatomic_series.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.8490566038, "max_line_length": 88, "alphanum_fraction": 0.6184971098, "num_tokens": 364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308073258007, "lm_q2_score": 0.8723473862936942, "lm_q1q2_score": 0.8142759250566752}} {"text": "module problem129\n\ndescription = \"\"\"\nRepunit divisibility\n\nA number consisting entirely of ones is called a repunit. We shall define R(k) to be a repunit of length k; for example, R(6) = 111111.\nGiven that n is a positive integer and GCD(n, 10) = 1, it can be shown that there always exists a value, k, for which R(k) is divisible by n, \nand let A(n) be the least such value of k; for example, A(7) = 6 and A(41) = 5.\nThe least value of n for which A(n) first exceeds ten is 17.\n\nFind the least value of n for which A(n) first exceeds one-million.\n\"\"\"\n\n# Calculate repunit length k = (10^k - 1) / 9\nfunction R(k :: Int)\n return div(BigInt(10)^k - 1, 9)\nend\n\n# find the least value of k such that R(k) is a multiple of n\n# Insight from the Project Euler forums:\n# A(n) is the minimum k, such that n divides R(k) \n# => (10^k - 1)/9 == 0 mod n\n# => 10^k - 1 == 0 mod 9n\n# => 10^k == 1 mod 9n\n# Iteratively generate powers of 10 mod 9n, and terminate when the result is 1.\nfunction A(n)\n tenK = 10\n for k = 1:Inf\n if tenK == 1\n return k\n end\n tenK = (tenK * 10) % (9*n)\n end\nend\n\n# Search for the least value of n, such that A(n) > x\n# The main insight here is that search(x) >= x, so search 1,000,000 doesn't require\n# searching 1..1000000. \nfunction search(x = 1000000)\n for n = x:Inf\n if gcd(n, 10) == 1\n k = A(n)\n if k > x\n return n\n end\n end\n end\nend\n\nusing Base.Test\n\n@test R(6) == 111111\n@test A(7) == 6\n@test A(41) == 5\n@test search(10) == 17\n\nend", "meta": {"hexsha": "4d286fc3f894a24a6a6dab89c1167dc5df94665d", "size": 1512, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/problem129.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/problem129.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/problem129.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": 26.5263157895, "max_line_length": 142, "alphanum_fraction": 0.630952381, "num_tokens": 526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308073258009, "lm_q2_score": 0.872347369700144, "lm_q1q2_score": 0.8142759095677443}} {"text": "module RootsNewton\n\ngreet() = print(\"Hello World!\")\n\nusing LinearAlgebra, ForwardDiff\n\n#This function finds the roots of f(x) taking iv as initial point. The derivative is calculated using ForwardDiff\nfunction newtonroot(f; iv, tolerance=1E-7, maxiter=1000)\n D(f) = x -> ForwardDiff.derivative(f, x)\n f_prime=D(f)\n return newtonroot(f,f_prime;iv=iv,tolerance=tolerance,maxiter=maxiter)\nend\n\n#This function finds the roots of f(x) taking iv as initial point\nfunction newtonroot(f,f_prime; iv, tolerance=1E-7, maxiter=1000)\n # setup the algorithm\n x_old = iv\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\tif iter>=maxiter || isnan(x_old)\n\t\treturn (value = nothing, funcRes=nothing, iter=iter-1) # A named tuple\n\telse\n\t\treturn (value = x_old, funcRes=f(x_old), iter=iter-1) # A named tuple\n\tend\nend\n\nexport newtonroot\n\nend # module\n", "meta": {"hexsha": "fa98e24d824dd3efcd7217eeda660bce82b51a97", "size": 1046, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/RootsNewton.jl", "max_stars_repo_name": "sebastiangomez87/RootsNewton.jl", "max_stars_repo_head_hexsha": "50c1fe6630791afeef299ba0280c10743d29522f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/RootsNewton.jl", "max_issues_repo_name": "sebastiangomez87/RootsNewton.jl", "max_issues_repo_head_hexsha": "50c1fe6630791afeef299ba0280c10743d29522f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/RootsNewton.jl", "max_forks_repo_name": "sebastiangomez87/RootsNewton.jl", "max_forks_repo_head_hexsha": "50c1fe6630791afeef299ba0280c10743d29522f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0555555556, "max_line_length": 113, "alphanum_fraction": 0.6912045889, "num_tokens": 313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107984180245, "lm_q2_score": 0.8688267677469952, "lm_q1q2_score": 0.8142738286871128}} {"text": "function phantom(N::Int64, n::Int64) #N:이미지 크기, n:팬텀의 타입\n #Shepp-Logan phantom n=1\n # A a b x0 y0 phi \n # k1 k2 k3 k4 k5 k6 \n # ---------------------------------------------------------\n sheplog = [ 1.0 0.69 0.92 0.0 0.0 0.0 ; \n -0.98 0.6624 0.8740 0.0 -0.0184 0.0 ;\n 0.01 0.2100 0.2500 0.0 0.35 0.0 ;\n 0.01 0.0460 0.0460 0.0 0.1 0.0 ;\n 0.01 0.0460 0.0460 0.0 -0.1 0.0 ;\n 0.01 0.0460 0.0230 -0.08 -0.605 0.0 ;\n 0.01 0.0230 0.0230 0.0 -0.606 0.0 ;\n 0.01 0.0230 0.0460 0.06 -0.605 0.0 ;\n -0.02 0.1100 0.3100 0.22 0.0 -0.314 ;\n -0.02 0.1600 0.4100 -0.22 0.0 0.314 ]\n \n #modified-Shepp_Logan phantom n=2\n # A a b x0 y0 phi \n # k1 k2 k3 k4 k5 k6 \n #----------------------------------------------------------\n modishep = [ 1.0 0.69 0.92 0.0 0.0 0.0 ; \n -0.8 0.6624 0.8740 0.0 -0.0184 0.0 ;\n 0.1 0.2100 0.2500 0.0 0.35 0.0 ;\n 0.1 0.0460 0.0460 0.0 0.1 0.0 ;\n 0.1 0.0460 0.0460 0.0 -0.1 0.0 ;\n 0.1 0.0460 0.0230 -0.08 -0.605 0.0 ;\n 0.1 0.0230 0.0230 0.0 -0.606 0.0 ;\n 0.1 0.0230 0.0460 0.06 -0.605 0.0 ;\n -0.2 0.1100 0.3100 0.22 0.0 -0.314 ;\n -0.2 0.1600 0.4100 -0.22 0.0 0.314 ]\n \n if n==1\n sl=sheplog\n elseif n==2\n sl=modishep\n end\n \n P = zeros(Float64, N, N)\n x = LinRange(-1,1,N)\n y = - x\n \n for k=1:10\n \n if k < 9 #회전이 없는 타원\n for i=1:N, j=1:N #i, j 헷갈리지 않게 주의\n if ( (x[j]-sl[k,4])/sl[k,2] )^2 + ( (y[i]-sl[k,5])/sl[k,3] )^2 < 1\n P[i, j]+= sl[k,1]\n end\n end\n \n else #회전이 있는 타원\n for i=1:N, j=1:N\n if ( (cos(sl[k,6])*(x[j]-sl[k,4])+sin(sl[k,6])*(y[i]-sl[k,5]))/sl[k,2] )^2+( (sin(sl[k,6])*(x[j]-sl[k,4])-cos(sl[k,6])*(y[i]-sl[k,5]))/sl[k,3] )^2< 1\n P[i, j]+= sl[k,1]\n end\n end\n end\n \n end\n \n return P\n \nend", "meta": {"hexsha": "53ea34e8f1851ee459299067e4645fa823e92852", "size": 2487, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/phantom.jl", "max_stars_repo_name": "physimatics/Tomography.jl", "max_stars_repo_head_hexsha": "97bbddeb5b74026f64751b2948d292d339df021e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-01-20T08:03:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T06:55:22.000Z", "max_issues_repo_path": "src/phantom.jl", "max_issues_repo_name": "physimatics/Tomography.jl", "max_issues_repo_head_hexsha": "97bbddeb5b74026f64751b2948d292d339df021e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/phantom.jl", "max_forks_repo_name": "physimatics/Tomography.jl", "max_forks_repo_head_hexsha": "97bbddeb5b74026f64751b2948d292d339df021e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-11T04:26:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T04:26:55.000Z", "avg_line_length": 39.4761904762, "max_line_length": 159, "alphanum_fraction": 0.3192601528, "num_tokens": 1141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551515780319, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.8142365427733168}} {"text": "using Primes, Printf\n\nfunction addmsdigit(p::Integer, b::Integer, s::Integer)\n a = Vector{typeof(p)}()\n q = p\n for i in 1:(b-1)\n q += s\n isprime(q) || continue\n push!(a, q)\n end\n return a\nend\n\nfunction lefttruncprime(pbase::Integer)\n a = Vector{BigInt}()\n append!(a, primes(pbase - 1))\n mlt = zero(BigInt)\n s = one(BigInt)\n while !isempty(a)\n mlt = maximum(a)\n s *= pbase\n for i in 1:length(a)\n p = popfirst!(a)\n append!(a, addmsdigit(p, pbase, s))\n end\n end\n return mlt\nend\n\nlo, hi = 3, 17\nprintln(\"The largest left truncatable primes for bases\", @sprintf(\" %d to %d.\", lo, hi))\nfor i in lo:hi\n mlt = lefttruncprime(i)\n @printf(\"%10d %-30d (%s)\\n\", i, mlt, string(mlt, base=i))\nend\n", "meta": {"hexsha": "d1f3620156155f4ab3085ddea820f54ce6cb3392", "size": 796, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/find-largest-left-truncatable-prime-in-a-given-base.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/find-largest-left-truncatable-prime-in-a-given-base.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/find-largest-left-truncatable-prime-in-a-given-base.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.1111111111, "max_line_length": 88, "alphanum_fraction": 0.5489949749, "num_tokens": 265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122720843812, "lm_q2_score": 0.8499711718571775, "lm_q1q2_score": 0.8141978164399329}} {"text": "# Useful integer math stuff\n\nexport trinum, triinv, triinv_strict, triinv_rem\n\n\n\"\"\"\n$(TYPEDSIGNATURES)\n\nGet the `n`th triangular number.\n\n# See also\n[`triinv`](@ref)\n\"\"\"\n@inline trinum(n::Integer) = n * (n + 1) ÷ 2\n\n\n\"\"\"\n$(TYPEDSIGNATURES)\n\nGet the largest `n` such that `t >= trinum(n)`.\n\n# See also\n[`triinv_strict`](@ref), [`trinum`](@ref)\n\"\"\"\n@inline triinv(t::Integer) = _triinv(t, Val{false}())\n\n\n\"\"\"\n$(TYPEDSIGNATURES)\n\nGet `n` such that `t` is the `n`th triangular number.\nIf `t` is not a triangular number, throw a `DomainError`.\n\n# See also\n[`triinv`](@ref), [`trinum`](@ref)\n\"\"\"\n@inline triinv_strict(t::Integer) = _triinv(t, Val{true}())\n\nfunction _triinv(t::Integer, ::Val{strict}) where strict\n\tt >= 0 || throw(DomainError(t, \"Must be nonnegative\"))\n\ts = 8 * t + 1\n\trs = isqrt(s)\n\tstrict && rs^2 != s && throw(DomainError(t, \"Not a triangular number\"))\n\treturn (rs - 1) ÷ 2\nend\n\n\n\"\"\"\n$(TYPEDSIGNATURES)\n\nGet `n` and `r >= 0` such that `t == trinum(n) + r` and `t < trinum(n + 1)`.\n\n# See also\n[`triinv`](@ref), [`trinum`](@ref)\n\"\"\"\nfunction triinv_rem(t::Integer)\n\tn = triinv(t)\n\treturn n, t - trinum(n)\nend\n", "meta": {"hexsha": "c67157172f7837171aeccf3f1e20805ec10b1213", "size": 1122, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Indexing/math.jl", "max_stars_repo_name": "jlumpe/TriMatrix.jl", "max_stars_repo_head_hexsha": "42c111e3b2b488cae5326f57f96d10d938ebe795", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-28T12:24:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-28T12:24:59.000Z", "max_issues_repo_path": "src/Indexing/math.jl", "max_issues_repo_name": "jlumpe/TriMatrix.jl", "max_issues_repo_head_hexsha": "42c111e3b2b488cae5326f57f96d10d938ebe795", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-02-27T19:26:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-28T12:27:35.000Z", "max_forks_repo_path": "src/Indexing/math.jl", "max_forks_repo_name": "jlumpe/TriMatrix.jl", "max_forks_repo_head_hexsha": "42c111e3b2b488cae5326f57f96d10d938ebe795", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.7, "max_line_length": 76, "alphanum_fraction": 0.6221033868, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248259606259, "lm_q2_score": 0.8670357494949105, "lm_q1q2_score": 0.8141680937710991}} {"text": "# Section 6.4.2\n# Boyd & Vandenberghe \"Convex Optimization\"\n# Original by Lieven Vandenberghe\n# Adapted for Convex by Joelle Skaf - 10/03/05\n#\n# Adapted for Convex.jl by Karanveer Mohan and David Zeng - 26/05/14\n# Original cvx code and plots here:\n# http://web.cvxr.com/cvx/examples/cvxbook/Ch06_approx_fitting/html/fig6_15.html\n#\n# Consider the least-squares problem:\n# minimize ||(A + tB)x - b||_2\n# where t is an uncertain parameter in [-1,1]\n# Three approximate solutions are found:\n# 1- nominal optimal (i.e. letting t=0)\n# 2- stochastic robust approximation:\n# minimize E||(A+tB)x - b||_2\n# assuming u is uniformly distributed on [-1,1] )\n# (reduces to minimizing E ||(A+tB)x-b||^2 = ||A*x-b||^2 + x^TPx\n# where P = E(t^2) B^TB = (1/3) B^TB )\n# 3- worst-case robust approximation:\n# minimize sup{-1<=u<=1} ||(A+tB)x - b||_2)\n# (reduces to minimizing max{||(A-B)x - b||_2, ||(A+B)x - b||_2} )\n\nusing Convex\n\n# Input Data\nm = 20;\nn = 10;\nA = randn(m,n);\n(U,S,V) = svd(A);\nS = diagm(logspace(-1, 1, n));\nA = U[:, 1:n] * S * V';\n\nB = randn(m, n);\nB = B / Base.norm(B);\n\nb = randn(m, 1);\nx = Variable(n)\n\n# Case 1: Nominal optimal solution\np = minimize(norm(A * x - b, 2))\nsolve!(p)\nx_nom = x.evaluate()\n\n# Case 2: Stochastic robust approximation\nP = 1 / 3 * B' * B;\np = minimize(square_pos(norm(A * x - b)) + quadform(x, P))\nsolve!(p)\nx_stoch = x.evaluate()\n\n# Case 3: Worst-case robust approximation\np = minimize(max(norm((A - B) * x - b), norm((A + B) * x - b)))\nsolve!(p)\nx_wc = x.evaluate()\n\n# plot residuals\nnovals = 100;\nparvals = linspace(-2, 2, novals);\n\nerrvals_ls = [];\nerrvals_stoch = [];\nerrvals_wc = [];\n\nfor k=1:novals\n errvals_ls = [errvals_ls, Base.norm((A + parvals[k] * B) * x_nom - b)];\n errvals_stoch = [errvals_stoch, Base.norm((A + parvals[k] * B) * x_stoch - b)];\n errvals_wc = [errvals_wc, Base.norm((A + parvals[k] * B) * x_wc - b)];\nend\n\n# Plots. You'll need Gaston and gnuplot installed.\n# For other plotting libraries, you probably have to change the next few lines.\nusing Gaston\nGaston.set_terminal(\"x11\")\nplot(parvals, errvals_ls, \"color\",\"blue\", \"legend\", \"Nominal problem\",\n parvals, errvals_stoch, \"color\", \"black\", \"legend\", \"Stochastic Robust Approximation\",\n parvals, errvals_wc, \"color\", \"red\", \"legend\", \"Worst-Case Robust Approximation\",\n \"title\", \"Residual r(u) vs a parameter u for three approximate solutions\",\n \"xlabel\", \"u\", \"ylabel\", \"r(u) = ||A(u)x-b||_2\")\n", "meta": {"hexsha": "0a457a2f9b9f22c82278ee6be80ccb00860a6735", "size": 2479, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/robust_approx_fitting.jl", "max_stars_repo_name": "ranocha/Convex.jl", "max_stars_repo_head_hexsha": "ee58743611756e5cbb104682686031ab8d0feec4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-10-10T16:38:59.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-13T06:35:58.000Z", "max_issues_repo_path": "examples/robust_approx_fitting.jl", "max_issues_repo_name": "ranocha/Convex.jl", "max_issues_repo_head_hexsha": "ee58743611756e5cbb104682686031ab8d0feec4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/robust_approx_fitting.jl", "max_forks_repo_name": "ranocha/Convex.jl", "max_forks_repo_head_hexsha": "ee58743611756e5cbb104682686031ab8d0feec4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-10-19T20:58:10.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-20T01:12:01.000Z", "avg_line_length": 31.3797468354, "max_line_length": 91, "alphanum_fraction": 0.6296893909, "num_tokens": 852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248157222395, "lm_q2_score": 0.8670357512127872, "lm_q1q2_score": 0.814168086507181}} {"text": "#! /usr/bin/julia\n\n# Rosetta Code, Abundant, deficient and perfect number classifications\n\n# A natural number, n, can be written as a product of powers of it's\n# prime factors, n = Prod(p_i^(a_i)). The sum of all of n's divisors,\n# including n itself, is dsum = Prod((p_i^(a_i+1) - 1)/(p_i - 1)).\n\nconst L = 2*10^4\n\nfunction pcontrib(p::Int64, a::Int64)\n # (p^(a+1) - 1)/(p_i - 1) = p^a + p^(a-1) + ... + p + 1, Perhaps\n # this could be made more efficient by caching results to avoid\n # repeated calculations.\n n = one(p)\n pcon = one(p)\n for i in 1:a\n n *= p\n pcon += n\n end\n return pcon\nend\n\nfunction divisorsum(n::Int64)\n #the \"proper divisor sum\", or aliquot sum of n's divisors,\n #excluding n itself\n dsum = one(n)\n for (p, a) in factor(n)\n dsum *= pcontrib(p, a)\n end\n dsum -= n\nend\n\n# Work with a three element array, rather than three separate\n# variables, and take advantage of the fact that the sign of dsum - n\n# depends upon its class to increment this array of classifications.\n\niclasslabel = [\"Deficient\", \"Perfect\", \"Abundant\"]\niclass = zeros(Int64, 3)\niclass[1] = one(Int64) #by convention 1 is deficient\n\nfor n in 2:L\n if isprime(n)\n iclass[1] += 1\n else\n iclass[sign(divisorsum(n)-n)+2] += 1\n end\nend\n\n\nprintln(\"Classification of integers from 1 to \", L)\nfor i in 1:3\n println(\" \", iclasslabel[i], \", \", iclass[i])\nend\n\n\n \n", "meta": {"hexsha": "623c8e4c2f2663f72ba230c42ad4ae37f4bace58", "size": 1436, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/completed/abundant_perfect_deficient.jl", "max_stars_repo_name": "MichaeLeroy/rosetta-code", "max_stars_repo_head_hexsha": "cb0f45f79704912967cbd37c0c9bdc1e78c964b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "julia/completed/abundant_perfect_deficient.jl", "max_issues_repo_name": "MichaeLeroy/rosetta-code", "max_issues_repo_head_hexsha": "cb0f45f79704912967cbd37c0c9bdc1e78c964b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/completed/abundant_perfect_deficient.jl", "max_forks_repo_name": "MichaeLeroy/rosetta-code", "max_forks_repo_head_hexsha": "cb0f45f79704912967cbd37c0c9bdc1e78c964b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7586206897, "max_line_length": 70, "alphanum_fraction": 0.6218662953, "num_tokens": 463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422186079557, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.8140361552275273}} {"text": "### A Pluto.jl notebook ###\n# v0.12.16\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ d627801e-3479-11eb-1fab-1dfaf4af1144\nbegin\n\tusing Random\n\tRandom.seed!()\n\t\n\tpassLength, numMatchesForLog = 8, 4\n\tpossibleChars = ['a':'z' ; 'A':'Z' ; '0':'9']\n\t\n\tcorrectPassword = \"3xsfe6p3\"\n\t\n\tnumMatch(loginPassword) = sum([loginPassword[i] == correctPassword[i] for i in 1:passLength])\n\t\n\tNₚ = 10^7\n\t\n\tpasswords = [String(rand(possibleChars, passLength)) for _ in 1:Nₚ]\n\tnumLogs = sum([numMatch(p) >= numMatchesForLog for p in passwords])\nend\n\n# ╔═╡ 81248f92-347b-11eb-046d-1327fefd71be\nbegin\n\tusing StatsBase, Combinatorics, Plots; gr()\n\tmatchExists1(n) = 1 - prod([k/365 for k in 365:-1:365-n+1])\n\tmatchExists2(n) = 1 - factorial(365, 365 - big(n))/365^big(n)\n\tfunction bdEvent(n)\n\t\tbirthdays = rand(1:365, n)\n\t\tdayCounts = counts(birthdays, 1:365)\n\t\treturn maximum(dayCounts) > 1\n\tend\n\t\n\tprobEst(n) = sum([bdEvent(n) for _ in 1:Nᵦ]) / Nᵦ\n\t\n\txGrid = 1:50\n\tanalyticSolution1 = [matchExists1(n) for n in xGrid]\n\tanalyticSolution2 = [matchExists2(n) for n in xGrid]\n\t\n\tNᵦ = 10^3\n\tmcEstimates = [probEst(n) for n in xGrid]\n\tplot(xGrid, analyticSolution1, c=:blue, label=\"Analytic solution\")\n\tscatter!(xGrid, mcEstimates, c=:red, ms=4, msw=1, shape=:xcross, label=\"MC estimate\", xlims=(0, 50), ylim=(0, 1), xlabel=\"Number of people in room\", ylabel=\"Probaility of birthday match\", leg=:topleft)\n\t\n\t\t\nend\n\n# ╔═╡ fcc139c4-3481-11eb-3765-6fe44d8b9951\nbegin\n\tusing LaTeXStrings\n\t\n\t\n\tnₗ, Nₗ = 5, 10^5\n\t\n\tfunction isUpperLattice(v)\n\t\tfor i in 1:Int(length(v)/2)\n\t\t\tsum(v[1:2*i-1]) >= i ? continue : return false\n\t\tend\n\t\treturn true\n\tend\n\t\n\tomega = unique(permutations([zeros(Int, nₗ);ones(Int, nₗ)]))\n\tA = omega[isUpperLattice.(omega)]\n\tpA_modelI = length(A)/length(omega)\n\t\n\tfunction randomWalkPath(n)\n\t\tx, y = 0, 0\n\t\tpath = []\n\t\twhile xx==fished, fishInPond))\n\t\t\t\tend\n\t\t\tend\n\t\t\tsum(fishCaught)\n\t\tend\n\t\tsimulations = [fishing() for _ in 1:N]\n\t\tproportions = counts(simulations, 0:n)/N\n\t\t\n\t\tif withReplacement\n\t\t\tplot!(0:n, proportions,line=:stem, marker=:circle, c=:blue, ms=4, msw=1, label=\"With Replacement\", xlabel=\"n\", ylabel=\"Probaility\", ylims=(0, 0.6))\n\t\telse\n\t\t\tplot!(0:n, proportions, line=:stem, marker=:xcross, c=:red, msw=4, label=\"Without replacement\")\n\t\tend\n\tend\n\t\n\tN₄ = 10^6\n\tgoldFish, silverFish, n = 3, 4, 3\n\tplot()\n\tproportionFished(goldFish, silverFish, n, N₄)\n\tproportionFished(goldFish, silverFish, n, N₄, true)\nend\n\t\t\n\n# ╔═╡ ac4a60ee-347f-11eb-2580-659176e69bb2\nmd\"## Lattice paths\"\n\n# ╔═╡ abacb3da-347f-11eb-06fd-df1a2f6812b6\n\n\n# ╔═╡ ab179624-347f-11eb-141e-815098dddcd0\n\n\n# ╔═╡ Cell order:\n# ╟─2462b3a2-3478-11eb-2047-d17d9419ef0a\n# ╟─5235dc84-3478-11eb-2f71-11b5b2f75b44\n# ╟─8e828a70-3478-11eb-2539-f5be394fbbdf\n# ╠═a8ab5e90-3478-11eb-3f35-339109ff8c54\n# ╠═7c6ca8f6-3479-11eb-3f7c-d35794372677\n# ╠═826c806e-3479-11eb-022d-53c8acda5a74\n# ╟─c95a38d6-3479-11eb-2aed-d9ce01229a1f\n# ╠═d627801e-3479-11eb-1fab-1dfaf4af1144\n# ╟─5b1c6338-347b-11eb-043a-49549cd35c32\n# ╠═81248f92-347b-11eb-046d-1327fefd71be\n# ╟─592036ba-347e-11eb-07da-1134d98b2a0f\n# ╠═5f033766-347f-11eb-3dce-9d840202929b\n# ╟─ac4a60ee-347f-11eb-2580-659176e69bb2\n# ╠═fcc139c4-3481-11eb-3765-6fe44d8b9951\n# ╠═abacb3da-347f-11eb-06fd-df1a2f6812b6\n# ╠═ab179624-347f-11eb-141e-815098dddcd0\n", "meta": {"hexsha": "5a53aa49e484d299605a96d7f7ed113af1e434fe", "size": 5299, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "probaility.jl", "max_stars_repo_name": "ZhouZhuofei/juliaDL", "max_stars_repo_head_hexsha": "c9e8e7d9064c0651f5c01fc0c7a3f55beef7571a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "probaility.jl", "max_issues_repo_name": "ZhouZhuofei/juliaDL", "max_issues_repo_head_hexsha": "c9e8e7d9064c0651f5c01fc0c7a3f55beef7571a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "probaility.jl", "max_forks_repo_name": "ZhouZhuofei/juliaDL", "max_forks_repo_head_hexsha": "c9e8e7d9064c0651f5c01fc0c7a3f55beef7571a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8487804878, "max_line_length": 202, "alphanum_fraction": 0.6782411776, "num_tokens": 2343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9207896693699844, "lm_q2_score": 0.8840392848011834, "lm_q1q2_score": 0.8140142407621592}} {"text": "# See https://en.wikipedia.org/wiki/Padovan_sequence\n# Inspired by https://math.stackexchange.com/questions/3798107/is-there-a-better-way-to-calculate-padovan-sequence-than-on\n\npadovan(n) = ([0 1 0; 0 0 1; 1 1 0]^n)[3, 2]\n\nexpressions = [\n :(padovan(1))\n :(padovan(2))\n :(padovan(3))\n :(padovan(4))\n :(padovan(5))\n :(padovan(6))\n :(padovan(7))\n :(padovan(8))\n :(padovan(9))\n :(padovan(10))\n :(padovan(91))\n :(padovan(big(283)))\n :(padovan(big(3674)))\n]\n\nfor expr in expressions\n println(\"[] :julia-answer \\\"\\\"\\\"\", escape_string(string(expr)), \" = \", eval(expr), \"\\\"\\\"\\\".\")\nend\n", "meta": {"hexsha": "a070f03f6832347ffb2bb749c40549fe5e314c52", "size": 619, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "reasoning/julia/padovan.jl", "max_stars_repo_name": "pmoura/eye", "max_stars_repo_head_hexsha": "03a4be110f5e9f8f21a6b1ac2756d79cc6518386", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "reasoning/julia/padovan.jl", "max_issues_repo_name": "pmoura/eye", "max_issues_repo_head_hexsha": "03a4be110f5e9f8f21a6b1ac2756d79cc6518386", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "reasoning/julia/padovan.jl", "max_forks_repo_name": "pmoura/eye", "max_forks_repo_head_hexsha": "03a4be110f5e9f8f21a6b1ac2756d79cc6518386", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.76, "max_line_length": 122, "alphanum_fraction": 0.5848142165, "num_tokens": 209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750400464604, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.8140137137662191}} {"text": "X = Float64[2 5; 6 4; 5 3; 2 2; 1 4; 5 4; 3 3; 2 3; 2 4; 8 2; 9 2; 10 2; 11 2; 10 3; 9 1]\nd2(x⃗, y⃗) = sqrt(sum((x⃗ - y⃗).^2))\nd2²(x⃗, y⃗) = sum((x⃗ - y⃗).^2)\nN = size(X)[1]\n\n# prototypes = X[1:4, :]\nprototypes = X[12:15, :]\nK = size(prototypes)[1]\n\nfunction compute_distances(X, prototypes)\n N = size(X)[1]\n K = size(prototypes)[1]\n\n distances = Matrix{Float64}(undef, N, K)\n for k = 1:K\n for n = 1:N\n distances[n, k] = d2(X[n, :], prototypes[k, :])\n end\n end\n distances\nend\n\nfor t = 1:10\n previous_prototypes = copy(prototypes)\n\n distances = compute_distances(X, prototypes)\n \n cluster_assignments = map(argmin, eachrow(distances))\n println(\"cluster t=$t @ \", cluster_assignments)\n for k = 1:K\n indices = findall(x->x==k, cluster_assignments)\n prototypes[k, :] = sum(X[indices, :], dims=1) / length(indices)\n end\n if all(prototypes == previous_prototypes)\n break\n end\nend\n\ndistances = compute_distances(X, prototypes)\ncluster_assignments = map(argmin, eachrow(distances))\nprintln(\"cluster @ \", cluster_assignments)\n\nJ = 0.0\nfor k = 1:K\n indices = findall(x->x==k, cluster_assignments)\n for i = 1:length(indices)\n J += d2²(X[indices[i], :], prototypes[k, :])\n end\nend\nprintln(\"J = \", J)\n", "meta": {"hexsha": "f1a484383b462618e81f56a5fa424af48d6bde57", "size": 1295, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/KMeans.jl", "max_stars_repo_name": "tmwatchanan/UnsupervisedLearning.jl", "max_stars_repo_head_hexsha": "d3b54c334bcb0651023da2a0fd1990f1db218a3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/KMeans.jl", "max_issues_repo_name": "tmwatchanan/UnsupervisedLearning.jl", "max_issues_repo_head_hexsha": "d3b54c334bcb0651023da2a0fd1990f1db218a3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/KMeans.jl", "max_forks_repo_name": "tmwatchanan/UnsupervisedLearning.jl", "max_forks_repo_head_hexsha": "d3b54c334bcb0651023da2a0fd1990f1db218a3b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3921568627, "max_line_length": 89, "alphanum_fraction": 0.5891891892, "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897475985937, "lm_q2_score": 0.865224091265267, "lm_q1q2_score": 0.8139939544376731}} {"text": "using LinearAlgebra\nusing SparseArrays\nusing Plots\nusing ForwardDiff\n\n\"This routine runs a convergence test for the heat equation using Backwards Euler\nin time and finite differences in space. The exact solution is generated using the\nmethod 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α(t) = uexact(-1,t)\nβ(t) = uexact(1,t)\n\nfunction build_FD(m,f,α,β)\n x = LinRange(-1,1,m+2)\n xint = x[2:end-1]\n h = x[2]-x[1]\n A = (1/h^2) * spdiagm(0=>2*ones(m),-1=>-ones(m-1),1=>-ones(m-1))\n\n function F(t)\n b = f.(xint,t)\n b[1] += α(t)/h^2\n b[m] += β(t)/h^2\n return b\n end\n return A,x,xint,h,F\nend\n\nfunction solve_backward_Euler(m, f, α, β, u0, T, dt)\n\n A,x,xint,h,F = build_FD(m,f,α,β)\n\n u = u0.(xint)\n Nsteps = ceil(Int,T/dt)\n dt = T/Nsteps\n tvec = Float64[]\n energy = Float64[]\n for i = 1:Nsteps\n t = i*dt\n u .= (I + dt*A)\\(u .+ dt*F(t))\n push!(tvec,t)\n push!(energy,h*dot(u,u))\n end\n return u,x,xint,h,tvec,energy\nend\n\nfunction solve_Crank_Nicolson(m, f, α, β, u0, T, dt)\n\n A,x,xint,h,F = build_FD(m,f,α,β)\n\n u = u0.(xint)\n Nsteps = ceil(Int,T/dt)\n dt = T/Nsteps\n tvec = Float64[]\n energy = Float64[]\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 push!(tvec,t)\n push!(energy,h*dot(u,u))\n end\n return u,x,xint,h,tvec,energy\nend\n\nm = 100\nT = 5.0\ndt = 100/m\nf(x,t) = 0.0\nα(t) = 0.0\nβ(t) = 0.0\nu0(x) = exp(-10*x^2)\nu,x,xint,h,tvec,E1 = solve_backward_Euler(m, f, α, β, u0, T, dt)\nu,x,xint,h,tvec,E2 = solve_Crank_Nicolson(m, f, α, β, u0, T, dt)\nplot(tvec,E1,yaxis=:log,label=\"Backwards Euler\")\nplot!(tvec,E2,yaxis=:log,label=\"Crank Nicolson\")\nplot!(leg=:bottomleft)\n", "meta": {"hexsha": "4ac4b03870454cdd83b6d8d69f111e5cac42ae62", "size": 2019, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "hw3/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": "hw3/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": "hw3/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": 24.3253012048, "max_line_length": 82, "alphanum_fraction": 0.5720653789, "num_tokens": 787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216355, "lm_q2_score": 0.8757869932689566, "lm_q1q2_score": 0.8139918201012043}} {"text": "using StatsPlots\n\n\n\"\"\"\n coinflip_discrete_bayes_update(p_θ, data)\n\nGiven a discrete (possibly unnormalized) prior and some binary data\nreturns the likelihood and posterior.\n\"\"\"\nfunction coinflip_discrete_bayes_update(p_θ, data; plot_result=true)\n n_vals = length(p_θ) # number of candidates for θ\n θ = collect(0 : 1/(n_vals -1) : 1) # equally spaced bins\n p_θ = p_θ / sum(p_θ) # Makes sure that beliefs sum to 1.\n heads = sum(data)\n tails = length(data) - heads\n likelihood = θ.^heads .* (1 .- θ).^tails\n p_data = sum(likelihood .* p_θ)\n posterior = (likelihood .* p_θ) ./ p_data\n return (likelihood = likelihood, posterior = posterior)\nend\n\n\"\"\"\n plot_coinflip_discrete_bayes_update(p_θ, data)\n\nReproduces figure 5.1 with custom prior and data.\nTo reproduce the figure exactly use:\n```julia-repl\njulia> θ = range(0.1,1, step=0.1)\njulia> p_θ = min.(θ, 1 .- θ)\njulia> plot_coinflip_discrete_bayes_update(p_θ, [1])\n```\n\"\"\"\nfunction plot_coinflip_discrete_bayes_update(p_θ, data)\n n_vals = length(p_θ)\n θ = collect(0 : 1/(n_vals -1) : 1)\n p_θ = p_θ / sum(p_θ)\n likelihood, posterior = coinflip_discrete_bayes_update(p_θ, data)\n l = @layout (3,1)\n # Plot the prior\n plot1 = bar(θ, p_θ, title=\"Prior\", leg=false, bar_width = 0.01)\n\n # Plot likelihood\n plot2 = bar(θ, likelihood, title=\"Likelihood\", leg=false, bar_width = 0.01)\n\n # Plot the posterior\n plot3 = bar(θ, posterior, title=\"Posterior\", leg=false, bar_width = 0.01)\n plt = plot(plot1, plot2, plot3, layout=l, xlims=(-0.02,1.02), xticks=round.(θ,digits=2))\n display(plt)\nend\n\n", "meta": {"hexsha": "e357a096a50d4002b71f1c511e23d3403b71a063", "size": 1605, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/04_bayes_update.jl", "max_stars_repo_name": "alesasse/PuppyBook.jl", "max_stars_repo_head_hexsha": "35021e2d570c45d44ee05a8c4ceca551b63f2de1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/04_bayes_update.jl", "max_issues_repo_name": "alesasse/PuppyBook.jl", "max_issues_repo_head_hexsha": "35021e2d570c45d44ee05a8c4ceca551b63f2de1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/04_bayes_update.jl", "max_forks_repo_name": "alesasse/PuppyBook.jl", "max_forks_repo_head_hexsha": "35021e2d570c45d44ee05a8c4ceca551b63f2de1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4705882353, "max_line_length": 92, "alphanum_fraction": 0.6747663551, "num_tokens": 532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403959948494, "lm_q2_score": 0.8757869803008764, "lm_q1q2_score": 0.8139917977779799}} {"text": "export get_filter_params, FilterBank1d, get_FilterBanks, FilterBank1dBlock\n\n\"\"\"\n ξmax(Q)\n\nCalculate the maximum central frequency of a Morlet wavelet.\n\n# Arguments\n - `Q::Int64`: Number of wavelets per octave.\n\"\"\"\nfunction ξmax(Q::Int64)\n return max(1/(1+2^(3/Q)), 0.35)\nend\n\n\"\"\"\n σmin(σ0, J)\n\nCalculate the bandwidth of the lowpass filter ϕ.\n\n# Arguments\n - `σ0::Float64`: Bandwidth of lowpass filter ϕ at scale 0.\n - `J::Int64`: Maximum wavelet scale.\n\"\"\"\nfunction σmin(σ0::Float64, J::Int64)\n return σ0/2^J\nend\n\n\"\"\"\n σmax(ξmax, Q, rψ)\n\nCalculate the bandwidth of a Morlet wavelet in a family of Q per octave.\n\n# Arguments\n - `ξmax::Float64`: Maximum central frequency.\n - `Q::Int64`: Number of wavelets per octave.\n - `rψ::Float64`: Parameter controlling frequency width of filters.\n\"\"\"\nfunction σmax(ξmax::Float64, Q::Int64, rψ::Float64)\n return ξmax * ((1-2^(-1/Q))/(1+2^(-1/Q))) / (2*log(1/rψ))^(1/2)\nend\n\n\"\"\"\n max_dyadic_subsampling(ξ, σ, α)\n\nCompute the maximal subsampling possible for a Gabor wavelet without aliasing.\n\n# Arguments\n - `ξ::Float64`: Central frequency of the wavelet\n - `σ::Float64`: Bandwidth of the wavelet\n - `α::Float64`: Parameter controlling allowable error, with error∝1/α\n\"\"\"\nfunction max_dyadic_subsampling(ξ::Float64, σ::Float64, α::Float64)\n upper_bound = min(ξ+α*σ, 0.5)\n j = convert(Int, floor(-log2(upper_bound))) - 1\n return j\nend\n\n\"\"\"\n n_dyadic_steps(Q, σ_min, σ_max)\n\nGet the number of dyadic steps between σ_min and σ_max given Q wavelets per octave.\n\n# Arguments\n - `Q::Int64`: Number of wavelets per octave.\n - `σ_min::Float64`: Bandwidth of the lowpass filter\n - `σ_max::Float64`: Maximum filter bandwidth\n\"\"\"\nfunction n_dyadic_steps(Q::Int64, σ_min::Float64, σ_max::Float64)\n return convert(Int, ceil(Q*log2(σ_max/σ_min)))\nend\n\n\"\"\"\n get_filter_params(Q, J, σ0, rψ=rψ, α=α)\n\nGet the central frequencies, bandwidths, and maximum subsampling for a family of Morlet wavelets.\n\n# Arguments\n - `Q::Int64`: Number of wavelets per octave.\n - `J::Int64`: Maximum scale of the filters.\n - `σ_min::Float64`: Bandwidth of the low-pass filter.\n - `rψ`::Float64: Parameter controlling frequency width of filters.\n - `α::Float64`: Parameter controlling allowable error, with error∝1/α\n\"\"\"\nfunction get_filter_params(Q::Int64, σ_min::Float64; rψ::Float64=sqrt(0.5), α::Float64=5.0)\n @assert Q>=1 \"At least one wavelet per octave is required.\"\n\n # maximum central frequency\n ξ_max = ξmax(Q)\n\n # maximum filter bandwidth\n σ_max = σmax(ξ_max, Q, rψ)\n\n # number of dyadic steps between σ_min and σ_max\n n = n_dyadic_steps(Q, σ_min, σ_max)\n\n # initialize vectors\n σ = collect(0.0:n+Q-2)\n ξ = collect(0.0:n+Q-2)\n j = Vector{Int64}(undef, n+Q-1)\n\n # σ_i = σ_max/2^(i/Q)\n σ[1:n] .= σ_max./2.0.^(σ[1:n]./Q)\n σ[n+1:end] .= σ_min\n # ξ_i = ξ_max/2^(i/Q)\n ξ[1:n] .= ξ_max./2.0.^(ξ[1:n]./Q)\n ξ[n+1:end] .= ξ[n].*((Q.-collect(1:Q-1))./Q)\n\n # js\n j .= max_dyadic_subsampling.(ξ, σ, α)\n\n return σ, ξ, j\nend\n\n\"\"\"\n get_filter_params(Q, J, σ0, rψ=rψ, α=α)\n\nGet the central frequencies, bandwidths, and maximum subsampling for families of\nMorlet wavelets for each layer of the scattering transform.\n\n# Arguments\n- `Q::Array{Int64}`: Number of wavelets per octave for each layer.\n- `J::Int64`: Maximum scale of the filters.\n- `σ0::Float64`: Bandwidth of the low-pass filter.\n- `rψ`::Float64: Parameter controlling frequency width of filters.\n- `α::Float64`: Parameter controlling allowable error, with error∝1/α\n\"\"\"\nfunction get_filter_params(Q::Vector{Int64}, J::Int64, σ0::Float64; rψ::Float64=sqrt(0.5), α::Float64=5.0)\n # minimum filter bandwidth\n σ_min = σ0/2^J\n\n # initialize arrays for the parameters for each layer\n ξs = Vector{Vector{Float64}}(undef, length(Q))\n σs = Vector{Vector{Float64}}(undef, length(Q))\n js = Vector{Vector{Float64}}(undef, length(Q))\n\n # get filter parameters for each layer\n for i=1:length(Q)\n σs[i], ξs[i], js[i] = get_filter_params(Q[i], σ_min, rψ=rψ, α=α)\n end\n\n return σs, ξs, js\nend\n\n\nabstract type AbstractFilterBank end\n\n\"\"\"\n FilterBank1d\n\nA structure for collections of 1D Morlet Wavelets and a Gaussian lowpass filter\n\n## Fields: FilterBank1d\n | **Field** | **Description** |\n |:----------|:----------------|\n | :N | log2(signal length) |\n | :J | log2(max filter scale) |\n | :Q | Number of wavelets per octave |\n | :ω | Frequencies |\n | :ϕ | Fourier transformed low-pass Gaussian filter |\n | :Λ | Fourier transformed Morlet wavelets |\n\"\"\"\nstruct FilterBank1d <: AbstractFilterBank\n N::Int # log2 length of the signal in the time domain\n J::Int # log2 maximum scale of filters\n Q::Int # Number of wavelets per octave\n\n ω::Vector{Float64} # frequencies\n ϕ::GaussianFilter # low-pass filter\n Λ::Vector{MorletWavelet} # Fourier-transformed Morlet wavelets stored in a vector\n\n function FilterBank1d(N::Int64, Q::Int64, J::Int64, σ0::Float64; rψ::Float64=sqrt(0.5), α::Float64=5.0)\n σs, ξs, js = get_filter_params(Q, σ0/2^J, rψ=rψ, α=α)\n ω = FFTW.fftfreq(2^N)\n\n Λ = Vector{MorletWavelet}(undef, length(σs))\n ϕ = GaussianFilter(2^N, σ0/2^J)\n for i=1:length(σs)\n γ = GaborWavelet(2^N, σs[i], ξs[i], js[i])\n Λ[i] = MorletWavelet(γ, ϕ)\n end\n\n return new(N, J, Q, ω, ϕ, Λ)\n end\nend\n\n\"\"\"\n FilterBank1dBlock\n\nA structure for collections of 1D Morlet Wavelets and a Gaussian lowpass filter,\nboth stored as arrays.\n\n## Fields: FilterBank1d\n | **Field** | **Description** |\n |:----------|:----------------|\n | :N | log2(signal length) |\n | :J | log2(max filter scale) |\n | :Q | Number of wavelets per octave |\n | :σs | Bandwidth of filters |\n | :ξs | Central frequencies of filters |\n | :js | Maximum acceptable subsampling |\n | :σg | Bandwidth of gaussian lowpass filter |\n | :ω | Frequencies |\n | :ϕ | Fourier transformed low-pass Gaussian filter |\n | :Λ | Fourier transformed Morlet wavelets |\n\"\"\"\nstruct FilterBank1dBlock <: AbstractFilterBank\n N::Int64 # log2 length of filter in time domain\n J::Int # log2 maximum scale of filters\n Q::Int # Number of wavelets per octave\n\n # these would have been in the MorletWavelet objects\n σs::Vector{Float64}\n ξs::Vector{Float64}\n js::Vector{Int64}\n # this would have been in the GaussianFilter object\n σg::Float64\n\n ω::Vector{Float64} # frequencies\n ϕ::Vector{Float64} # low-pass filter\n Λ::Array{Float64,2} # Fourier-transformed Morlet wavelets stored in a block\n\n function FilterBank1dBlock(N::Int64, Q::Int64, J::Int64, σ0::Float64; rψ::Float64=sqrt(0.5), α::Float64=5.0)\n σs, ξs, js = get_filter_params(Q, σ0/2^J, rψ=rψ, α=α)\n ω = FFTW.fftfreq(2^N)\n\n Λ = Array{Float64,2}(undef, 2^N, length(σs))\n ϕ = GaussianFilter(2^N, σ0/2^J)\n for i=1:length(σs)\n γ = GaborWavelet(2^N, σs[i], ξs[i], js[i])\n Λ[:, i] = MorletWavelet(γ, ϕ).ψ\n end\n\n return new(N, J, Q, σs, ξs, js, ϕ.σ, ω, ϕ.ϕ, Λ)\n end\n\n function FilterBank1dBlock(F::FilterBank1d)\n Λ = Array{Float64,2}(undef, 2^F.N, length(F.Λ))\n σs = Vector{Float64}(undef, length(F.Λ))\n ξs = Vector{Float64}(undef, length(F.Λ))\n js = Vector{Int64}(undef, length(F.Λ))\n for i=1:length(F.Λ)\n Λ[:,i].=F.Λ[i].ψ\n σs[i]=F.Λ[i].σ\n ξs[i]=F.Λ[i].ξ\n js[i]=F.Λ[i].j\n end\n return new(F.N, F.J, F.Q, σs, ξs, js, F.ω, F.ϕ.ϕ, Λ)\n end\nend\n\n\n\"\"\"\n get_FilterBanks(N, Q, J, σ0, rψ=rψ, α=α)\n\nGet filter banks for every layer.\n\n# Arguments\n- `N::Int64`: log2(signal length)\n- `Q::Vector{Int64}`: Number of wavelets per octave for each layer.\n- `J::Vector{Int64}`: Maximum scale of the filters for each layer\n- `σ0::Vector{Float64}`: Bandwidth of the low-pass filter for each layer\n- `rψ`::Float64: Parameter controlling frequency width of filters.\n- `α::Float64`: Parameter controlling allowable error, with error∝1/α\n- `typ::Any`: FilterBank1d or FilterBank1dBlock\n\"\"\"\nfunction get_FilterBanks(N::Int64, Q::Vector{Int64}, J::Vector{Int64}, σ0::Vector{Float64}; rψ::Float64=sqrt(0.5), α::Float64=5.0, typ::Type{T}=FilterBank1d) where T<:AbstractFilterBank\n FilterBanks=Vector{typ}(undef, length(Q))\n for i=1:length(Q)\n if typ==FilterBank1d\n FilterBanks[i] = FilterBank1d(N, Q[i], J[i], σ0[i], rψ=rψ, α=α)\n elseif typ==FilterBank1dBlock\n FilterBanks[i] = FilterBank1dBlock(N, Q[i], J[i], σ0[i], rψ=rψ, α=α)\n end\n end\n return FilterBanks\nend\n\"\"\"\n get_FilterBanks(N, Q, J, σ0, rψ=rψ, α=α)\n\nConvenience method fo getting filter banks for each layer with common σ0.\n\"\"\"\nfunction get_FilterBanks(N::Int64, Q::Vector{Int64}, J::Vector{Int64}, σ0::Float64; rψ::Float64=sqrt(0.5), α::Float64=5.0, typ::Type{T}=FilterBank1d) where T<:AbstractFilterBank\n σ0s = repeat([σ0], length(Q))\n get_FilterBanks(N, Q, J, σ0s; rψ=rψ, α=α, typ=typ)\nend\n\"\"\"\n get_FilterBanks(N, Q, J, σ0, rψ=rψ, α=α)\n\nConvenience method fo getting filter banks for each layer with common J.\n\"\"\"\nfunction get_FilterBanks(N::Int64, Q::Vector{Int64}, J::Int64, σ0::Vector{Float64}; rψ::Float64=sqrt(0.5), α::Float64=5.0, typ::Type{T}=FilterBank1d) where T<:AbstractFilterBank\n Js = repeat([J], length(Q))\n get_FilterBanks(N, Q, Js, σ0; rψ=rψ, α=α, typ=typ)\nend\n\"\"\"\n get_FilterBanks(N, Q, J, σ0, rψ=rψ, α=α)\n\nConvenience method fo getting filter banks for each layer with common σ0 and J.\n\"\"\"\nfunction get_FilterBanks(N::Int64, Q::Vector{Int64}, J::Int64, σ0::Float64; rψ::Float64=sqrt(0.5), α::Float64=5.0, typ::Type{T}=FilterBank1d) where T<:AbstractFilterBank\n σ0s = repeat([σ0], length(Q))\n Js = repeat([J], length(Q))\n get_FilterBanks(N, Q, Js, σ0s; rψ=rψ, α=α, typ=typ)\nend\n", "meta": {"hexsha": "daeb26a1217c138521293af8af062a3bfaab9023", "size": 9885, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/filters/filterBank.jl", "max_stars_repo_name": "jaredbryan881/Scat.jl", "max_stars_repo_head_hexsha": "743f51629bec62767c64c51ae932e1a8f4926d0f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/filters/filterBank.jl", "max_issues_repo_name": "jaredbryan881/Scat.jl", "max_issues_repo_head_hexsha": "743f51629bec62767c64c51ae932e1a8f4926d0f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/filters/filterBank.jl", "max_forks_repo_name": "jaredbryan881/Scat.jl", "max_forks_repo_head_hexsha": "743f51629bec62767c64c51ae932e1a8f4926d0f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4098360656, "max_line_length": 185, "alphanum_fraction": 0.6410723318, "num_tokens": 3395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172673767973, "lm_q2_score": 0.8577681122619883, "lm_q1q2_score": 0.8139509731305998}} {"text": "\ninclude(\"tools.jl\")\nusing Main.tools\nusing LinearAlgebra\n\nn = 200\nprintln(\"Using n=\",n)\nxi = get_xi(n)\n\n\n# for JIT Compiler to do the work\nrhs = get_rhs_norm(50)\nrhs = get_rhs_sin(50)\na1, s1 = hosvd(rhs, 1e-4, true)\n\nprintln()\nprintln(\"First example with sinus\")\n\nrhs = get_rhs_sin(xi)\nprintln(\"Starting hosvd\")\n# tic()\nelapsed_time = @elapsed a1, s1 = hosvd(rhs, 1e-4, true)\n# toc()\nprintln(\"Elapsed time: \", elapsed_time)\nprintln(\"The core tensor has size \",size(a1.core))\nresidual = rhs - fullten(a1)\nerr = norm(residual[:])\nprintln(\"The error ||rhs - full(a1)||_F is: \", err)\nprintln(\"10⁻⁴ ⋅ ||B₁|| \", 1e-4*norm(rhs[:]))\nprintln(\"Relative error is: \", err/norm(rhs[:]))\n\nprintln()\nprintln(\"Second example with norm\")\n\nrhs = get_rhs_norm(xi)\nprintln(\"Starting hosvd\")\n# tic()\nelapsed_time = @elapsed a2, s2 = hosvd(rhs, 1e-4, true)\n# toc()\nprintln(\"Elapsed time: \", elapsed_time)\nprintln(\"The core tensor has size \", size(a2.core))\nresidual = rhs - fullten(a2)\nerr = norm(residual[:])\nprintln(\"The error ||rhs - full(a2)||_F is: \", err)\nprintln(\"10⁻⁴ ⋅ ||B₂|| \", 1e-4*norm(rhs[:]))\nprintln(\"Relative Error is: \", err/norm(rhs[:]))\n\n\n\n### Plotting\n# println(\"creating Plots\")\n# ENV[\"GKSwstype\"]=\"png\"\n# using Plots;\n\n# p1 = scatter(s1[1], yaxis=(:log))\n# # savefig(p1, \"report/eigvalb1.png\")\n# savefig(p1, \"eigvalb1.png\")\n\n# p2 = scatter(s2[1], yaxis=(:log))\n# # savefig(p2, \"report/eigvalb2.png\")\n# savefig(p2, \"eigvalb2.png\")\n", "meta": {"hexsha": "435c633b2e4a70e9950d58c358f4906f63f8a396", "size": 1432, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script1.jl", "max_stars_repo_name": "kipfstuhl/LowRankApprox_Projekt", "max_stars_repo_head_hexsha": "c9143c398d644ea03402a6d5e7fd14f5828abcec", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "script1.jl", "max_issues_repo_name": "kipfstuhl/LowRankApprox_Projekt", "max_issues_repo_head_hexsha": "c9143c398d644ea03402a6d5e7fd14f5828abcec", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script1.jl", "max_forks_repo_name": "kipfstuhl/LowRankApprox_Projekt", "max_forks_repo_head_hexsha": "c9143c398d644ea03402a6d5e7fd14f5828abcec", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0967741935, "max_line_length": 55, "alphanum_fraction": 0.656424581, "num_tokens": 490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172659321807, "lm_q2_score": 0.8577681031721325, "lm_q1q2_score": 0.8139509632659326}} {"text": "using EngEconomics, Roots\n\n# Given\naInit = -1500000\naAnnual = 900000 - 600000\naScrap = 100000\naLife = 5\n\nbInit = -2000000\nbAnnual = 1100000 - 800000\nbScrap = 200000\nbLife = 10\n\nMARR = 0.08\n\n# Find Annual Worth\naAW = aInit * capitalRecoveryFactor(MARR, aLife) + aAnnual + aScrap * sinkingFundFactor(MARR, aLife)\nbAW = bInit * capitalRecoveryFactor(MARR, bLife) + bAnnual + bScrap * sinkingFundFactor(MARR, bLife)\n\nif aAW >= 0 && bAW >= 0\n\tprintln(\"Both\")\nelseif aAW >= 0\n\tprintln(\"A\")\nelseif bAW >= 0\n\tprintln(\"B\")\nelse\n\tprintln(\"Neither\")\nend\n\n# Find Present Worth\naPW = aInit + aAnnual * seriesPresentAmountFactor(MARR, aLife) + aScrap * presentWorthFactor(MARR, aLife)\nbPW = bInit + bAnnual * seriesPresentAmountFactor(MARR, bLife) + bScrap * presentWorthFactor(MARR, bLife)\n\nif aPW >= 0 && bPW >= 0\n\tprintln(\"Both\")\nelseif aPW >= 0\n\tprintln(\"A\")\nelseif bPW >= 0\n\tprintln(\"B\")\nelse\n\tprintln(\"Neither\")\nend\n\n# Payback Period\n# - FirstCost / AnnualSavings\naPP = -aInit / aAnnual\nbPP = -bInit / bAnnual\nminPP = 3\n\nif aPP <= minPP && bPP <= minPP\n\tprintln(\"Both\")\nelseif aPP <= minPP\n\tprintln(\"A\")\nelseif bPP <= minPP\n\tprintln(\"B\")\nelse\n\tprintln(\"Neither\")\nend\n", "meta": {"hexsha": "b5f7d13ea0f9597d3b034b1cfc032f8a69246ad0", "size": 1159, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problems/ps5/p1.jl", "max_stars_repo_name": "zborffs/EngineeringEconomics.jl", "max_stars_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problems/ps5/p1.jl", "max_issues_repo_name": "zborffs/EngineeringEconomics.jl", "max_issues_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problems/ps5/p1.jl", "max_forks_repo_name": "zborffs/EngineeringEconomics.jl", "max_forks_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.6440677966, "max_line_length": 105, "alphanum_fraction": 0.6937014668, "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214511730025, "lm_q2_score": 0.8438950947024555, "lm_q1q2_score": 0.8137861423612502}} {"text": "using LinearAlgebra\nusing Symbolics\n\n# r=1 in simulations always\nstruct SphericalCoord\n theta::Float64 # angle from z-axis\n phi::Float64 # angle from x-axis in x-y plane\nend\n\nBase.:+(x::SphericalCoord, y::SphericalCoord) = SphericalCoord(x.theta+y.theta, x.phi+y.phi)\n\nstruct CartesianCoord\n x::Float64\n y::Float64\n z::Float64\nend\n\nLinearAlgebra.normalize( c::CartesianCoord ) = begin\n n = normalize( [c.x, c.y, c.z ] )\n CartesianCoord( n[1], n[2], n[3])\nend\n\nLinearAlgebra.norm( c::CartesianCoord ) = norm( [c.x, c.y, c.z ] )\n\nfunction cartesianToSpherical( p::CartesianCoord )\n r = sqrt( p.x^2 + p.y^2 + p.z^2 )\n theta = acos(p.z/r)\n phi = atan(p.y,p.x)\n SphericalCoord( theta, phi )\nend\n\nfunction sphericalToCartesian( p::SphericalCoord )\n x = cos(p.phi)*sin(p.theta)\n y = sin(p.phi)*sin(p.theta)\n z = cos(p.theta)\n CartesianCoord( x, y, z )\nend\n\n# p is the position, v is the velocity\nfunction sphericalToCartesianVelocity( p::SphericalCoord, v::SphericalCoord )\n # p.theta is dtheta, p.phi is dphi\n vx = [cos(p.phi)*cos(p.theta), - sin(p.phi)]' * [v.theta, v.phi]\n vy = [sin(p.phi)*cos(p.theta), cos(p.phi)]' * [v.theta, v.phi]\n vz = -sin(p.theta)*v.theta\n CartesianCoord( vx, vy, vz )\nend\n\n# geodesic distance\nrho( p1::SphericalCoord, p2 ::SphericalCoord) = acos( cos(p1.theta)*cos(p2.theta) + sin(p1.theta)*sin(p2.theta)*cos(p1.phi - p2.phi) )\n# derivative of geodesic distance \\rho wrt \\phi\nalpha( p1::SphericalCoord, p2 ::SphericalCoord) = sin(p1.theta) * sin(p2.theta) * sin(p1.phi-p2.phi) / sin(rho(p1,p2))\n# derivative of geodesic distance \\rho wrt \\theta\nbeta( p1::SphericalCoord, p2 ::SphericalCoord) = ( cos(p2.theta) * sin(p1.theta) - cos(p1.theta) * sin(p2.theta) * cos(p1.phi-p2.phi) ) / sin(rho(p1,p2))", "meta": {"hexsha": "32a7a8e1a198165ac5a74419928863bc83264286", "size": 1782, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "geometry/sphere.jl", "max_stars_repo_name": "sarthakbagaria/curved-membrane-fluid-dynamics", "max_stars_repo_head_hexsha": "6b6223c89011a179595a39656a4f866816dffc8c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "geometry/sphere.jl", "max_issues_repo_name": "sarthakbagaria/curved-membrane-fluid-dynamics", "max_issues_repo_head_hexsha": "6b6223c89011a179595a39656a4f866816dffc8c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geometry/sphere.jl", "max_forks_repo_name": "sarthakbagaria/curved-membrane-fluid-dynamics", "max_forks_repo_head_hexsha": "6b6223c89011a179595a39656a4f866816dffc8c", "max_forks_repo_licenses": ["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.6226415094, "max_line_length": 154, "alphanum_fraction": 0.6599326599, "num_tokens": 599, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966732132748, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.8137548497181383}} {"text": "module NewtonsMethod\n\ngreet() = print(\"Hello World!\")\n\nusing LinearAlgebra\nfunction newtonroot(f, f_prime, x_0; tolerance= 1E-7, maxiter= 1000)\n x_old = x_0\n error = Inf\n iter = 1\n while iter <= maxiter && error > tolerance\n x_new = x_old - (f(x_old)/f_prime(x_old))\n error = norm(x_new - x_old)\n x_old = x_new\n iter = iter+1\n end\n if error > tolerance\n return nothing\n else\n return (x_old)\n end\nend\n\n\nusing ForwardDiff\n\nD(f) = x -> ForwardDiff.derivative(f, x)\n\nfunction newtonroot(f, x_0; tolerance= 1E-7, maxiter= 1000)\n x_old = x_0\n error = Inf\n iter = 1\n f_prime = D(f)\n while iter <= maxiter && error > tolerance\n x_new = x_old - (f(x_old)/f_prime(x_old))\n error = norm(x_new - x_old)\n x_old = x_new\n iter = iter+1\n end\n if error > tolerance\n return nothing\n else\n return (x_old)\n end\nend\n\nexport newtonroot\nend # module\n", "meta": {"hexsha": "33abe977412dd6bd7819fb41ee26859764d63314", "size": 953, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NewtonsMethod.jl", "max_stars_repo_name": "AliKarimirad/NewtonsMethod.jl", "max_stars_repo_head_hexsha": "b488425a36860748aa642321e5b6bf6d6dfc389d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NewtonsMethod.jl", "max_issues_repo_name": "AliKarimirad/NewtonsMethod.jl", "max_issues_repo_head_hexsha": "b488425a36860748aa642321e5b6bf6d6dfc389d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NewtonsMethod.jl", "max_forks_repo_name": "AliKarimirad/NewtonsMethod.jl", "max_forks_repo_head_hexsha": "b488425a36860748aa642321e5b6bf6d6dfc389d", "max_forks_repo_licenses": ["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.8541666667, "max_line_length": 68, "alphanum_fraction": 0.5981112277, "num_tokens": 305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067244294588, "lm_q2_score": 0.8633916047011595, "lm_q1q2_score": 0.813752393246784}} {"text": "@doc \"\"\"\n\ttrapezquad(x::Vector, y::Vector) -> Number\n\nApproximate the integral of `y` over the the interval `[min(x), max(x)]`, using the divisions in `x`.\n\"\"\"->\nfunction trapezquad(x::AbstractVector, y::AbstractVector)\n\t2 <= (Nx = length(x)) == length(y) || throw(DimensionMismatch())\n\t!issorted(x) && throw(AssertionError(\"x must be sorted\"))\n\n\tintegral = 0.0\n\tfor n in 2:Nx\n\t\t@inbounds integral += (x[n]-x[n-1])*0.5*(y[n]+y[n-1])\n\tend\n\n\treturn integral\nend\n\n@doc \"\"\"\n\tinner(x::Vector, y::Vector, z::Vector) -> Number\n\nApproximate the inner product between `y` and `z` over the the interval `[min(x), max(x)]`, using the divisions in `x`.\nThe inner product is conjugate linear in `z`.\n\"\"\"->\nfunction inner(x::AbstractVector, y::AbstractVector, z::AbstractVector)\n\ttrapezquad( x, y.*conj(z) )\nend\n\n@doc \"\"\"\n\tl2norm(x::Vector, y::Vector) -> Number\n\nApproximate the L2 norm squared of `y` over the the interval `[min(x), max(x)]`, using the divisions in `x`.\n\"\"\"->\nfunction l2norm(x::AbstractVector, y::AbstractVector)\n\ttrapezquad( x, abs2(y) )\nend\n\n", "meta": {"hexsha": "e78ebbf726c30c4726145f28eb84d3c19c20e842", "size": 1049, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Quad.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/IntervalWavelets.jl-8574dada-bbe2-5b14-8c04-14b17cae11e5", "max_stars_repo_head_hexsha": "f456d0bbb58d8c4dc53dd307ef28add49176a4f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Quad.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/IntervalWavelets.jl-8574dada-bbe2-5b14-8c04-14b17cae11e5", "max_issues_repo_head_hexsha": "f456d0bbb58d8c4dc53dd307ef28add49176a4f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Quad.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/IntervalWavelets.jl-8574dada-bbe2-5b14-8c04-14b17cae11e5", "max_forks_repo_head_hexsha": "f456d0bbb58d8c4dc53dd307ef28add49176a4f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3513513514, "max_line_length": 119, "alphanum_fraction": 0.6663489037, "num_tokens": 325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067147399245, "lm_q2_score": 0.8633916011860785, "lm_q1q2_score": 0.813752381567934}} {"text": "function sigmoid(z::Array{Float64})\n return 1 ./ (1 .+ exp.(-z))\nend\n\n# function tanh(z::Array{Float64})\n# x = exp.(z)\n# y = exp.(-z)\n# return (x .- y) ./ (x .+ y)\n# end\n\nfunction ReLU(z::Array{Float64})\n return map(x -> max(0, x), z)\nend\n\nfunction ReLUα(z::Array{Float64}, α = 0.1)\n return map(x -> max(0, x) - α * max(0, -x), z)\nend\n\nusing Plots\nz = collect(-2:0.2:2)\nplot(z, sigmoid(z), label = \"sigmoid\")\nplot!(z, tanh.(z), label = \"tanh\")\nplot!(z, ReLU(z), label = \"ReLU\")\nplot!(z, ReLUα(z), label = \"leaky ReLU\")\n\n\nplot(z, hcat(sigmoid(z), tanh.(z), ReLU(z), ReLUα(z)), \n label = [\"sigmoid\", \"tanh\", \"ReLU\", \"leaky ReLU\"], \n lw = 2,\n ylims = (-1, 1), \n legend = :topleft, \n xlabel = \"z\", ylabel = \"g(z)\", \n title = \"Activation functions\")", "meta": {"hexsha": "1bfde0e8a5f2d3baa124a59b895bb753232d8497", "size": 807, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "elements_of_statistical_learning/11-Neural-Networks/assets/script.jl", "max_stars_repo_name": "xishansnow/ElementsOfStatisticalLearning", "max_stars_repo_head_hexsha": "23c636a9818572ac87cce3dc1118791fb3ce578e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "elements_of_statistical_learning/11-Neural-Networks/assets/script.jl", "max_issues_repo_name": "xishansnow/ElementsOfStatisticalLearning", "max_issues_repo_head_hexsha": "23c636a9818572ac87cce3dc1118791fb3ce578e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "elements_of_statistical_learning/11-Neural-Networks/assets/script.jl", "max_forks_repo_name": "xishansnow/ElementsOfStatisticalLearning", "max_forks_repo_head_hexsha": "23c636a9818572ac87cce3dc1118791fb3ce578e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4545454545, "max_line_length": 59, "alphanum_fraction": 0.5241635688, "num_tokens": 301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242074, "lm_q2_score": 0.8774767906859264, "lm_q1q2_score": 0.8137397631793929}} {"text": "function fibonacci_search(f, a, b, n; ϵ=0.01)\n ϕ = (1+√5)/2;\n s = (1-√5) / (1+√5);\n ρ = 1 / (ϕ*(1-s^(n+1))/(1-s^n));\n d = ρ*b + (1-ρ) * a;\n yd = f(d);\n for i in 1: n-1\n if i == n-1\n c = ϵ*a + (1-ϵ)*d;\n else\n c = ρ*a + (1-ρ)*b;\n end\n\n yc = f(c);\n if yc < yd\n b, d, yd = b, c, yc;\n else\n a, b = b, c;\n end\n ρ = 1 / (ϕ*(1-s^(n-i+1))/(1-s^(b-i)));;\n end\n return a < b ? (a, b) : (b, a)\nend\n", "meta": {"hexsha": "a3dc0c72a51e0189995d5a1f870c36776ec40138", "size": 510, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "bracketing/3.3-fibonacci_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.3-fibonacci_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.3-fibonacci_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": 21.25, "max_line_length": 47, "alphanum_fraction": 0.3, "num_tokens": 237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104962847373, "lm_q2_score": 0.8418256472515684, "lm_q1q2_score": 0.8135491415456084}} {"text": "using Printf\n\nfunction monteπ(n)\n s = count(rand() ^ 2 + rand() ^ 2 < 1 for _ in 1:n)\n return 4s / n\nend\n\nfor n in 10 .^ (3:8)\n p = monteπ(n)\n println(\"$(lpad(n, 9)): π ≈ $(lpad(p, 10)), pct.err = \", @sprintf(\"%2.5f%%\", abs(p - π) / π))\nend\n", "meta": {"hexsha": "0e3b9125ec08ef70ceec0e29f7430d97b8fda06a", "size": 253, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/monte-carlo-methods.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/monte-carlo-methods.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/monte-carlo-methods.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0833333333, "max_line_length": 97, "alphanum_fraction": 0.5019762846, "num_tokens": 109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9664104933824753, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.8135491352673692}} {"text": "\nusing DifferentialEquations, DiffEqParamEstim, Plots, Optim\n\n# Monte Carlo Problem Set Up for solving set of ODEs with different initial conditions\n\n# Set up Lotka-Volterra system\nfunction pf_func(du,u,p,t)\n du[1] = p[1] * u[1] - p[2] * u[1]*u[2]\n du[2] = -3 * u[2] + u[1]*u[2]\nend\np = [1.5,1.0]\nprob = ODEProblem(pf_func,[1.0,1.0],(0.0,10.0),p)\n\n\n# Setting up to solve the problem N times (for the N different initial conditions)\nN = 10;\ninitial_conditions = [[1.0,1.0], [1.0,1.5], [1.5,1.0], [1.5,1.5], [0.5,1.0], [1.0,0.5], [0.5,0.5], [2.0,1.0], [1.0,2.0], [2.0,2.0]]\nfunction prob_func(prob,i,repeat)\n ODEProblem(prob.f,initial_conditions[i],prob.tspan,prob.p)\nend\nmonte_prob = MonteCarloProblem(prob,prob_func=prob_func)\n\n\n# Check above does what we want\nsim = solve(monte_prob,Tsit5(),num_monte=N)\nplot(sim)\n\n\n# Generate a dataset from these runs\ndata_times = 0.0:0.1:10.0\nsim = solve(monte_prob,Tsit5(),num_monte=N,saveat=data_times)\ndata = Array(sim)\n\n\n# Building a loss function\nlosses = [L2Loss(data_times,data[:,:,i]) for i in 1:N]\n\n\nloss(sim) = sum(losses[i](sim[i]) for i in 1:N)\n\n\nprob = ODEProblem(pf_func,[1.0,1.0],(0.0,10.0),[1.2,0.8])\nfunction prob_func(prob,i,repeat)\n ODEProblem(prob.f,initial_conditions[i],prob.tspan,prob.p)\nend\nmonte_prob = MonteCarloProblem(prob,prob_func=prob_func)\nsim = solve(monte_prob,Tsit5(),num_monte=N,saveat=data_times)\nloss(sim)\n\n\nobj = build_loss_objective(monte_prob,Tsit5(),loss,num_monte=N,\n saveat=data_times)\n\n\nlower = zeros(2)\nupper = fill(2.0,2)\nresult = optimize(obj, lower, upper, [1.3,0.9], Fminbox(BFGS()))\n\n\nresult\n\n\nobj = build_loss_objective(monte_prob,Tsit5(),loss,num_monte=N,\n abstol=1e-8,reltol=1e-8,\n saveat=data_times)\nresult = optimize(obj, lower, upper, [1.3,0.9], Fminbox(BFGS()))\n\n\nresult\n\n\nusing DiffEqTutorials\nDiffEqTutorials.tutorial_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])\n\n", "meta": {"hexsha": "4148c5ca6a93cf520b9c11d035c9cedf6251f21d", "size": 1944, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/ode_extras/04-monte_carlo_parameter_estim.jl", "max_stars_repo_name": "isaacsas/DiffEqTutorials.jl", "max_stars_repo_head_hexsha": "46c1701ef613aacbd678bde7437a3c8de363990d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-05-24T10:30:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-17T12:13:03.000Z", "max_issues_repo_path": "script/ode_extras/04-monte_carlo_parameter_estim.jl", "max_issues_repo_name": "isaacsas/DiffEqTutorials.jl", "max_issues_repo_head_hexsha": "46c1701ef613aacbd678bde7437a3c8de363990d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-07T21:39:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T03:48:31.000Z", "max_forks_repo_path": "script/ode_extras/04-monte_carlo_parameter_estim.jl", "max_forks_repo_name": "isaacsas/DiffEqTutorials.jl", "max_forks_repo_head_hexsha": "46c1701ef613aacbd678bde7437a3c8de363990d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-24T14:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-24T14:30:36.000Z", "avg_line_length": 25.92, "max_line_length": 131, "alphanum_fraction": 0.6738683128, "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.9019206765295399, "lm_q1q2_score": 0.8134609067515031}} {"text": "function Legendre_polynomials!(x::Float64, lmax::Int64; Pₗ = nothing) \n #### returns an array of size lmax_half. Each cell contains one (even) Legendre polynomials evaluated at point x ####\n # getting all the constant we will need\n lmax_half = div(lmax, 2)\n\n # Preallocating Pₗ if it hasn't been given\n if isnothing(Pₗ)\n Pₗ = zeros(lmax_half) # will store all the Legendre polynomials\n end\n\n # Let's start the recurrence relation -- We use Bonnet's recurrence formula\n P_l = nothing # these 3 lines just to help the interpreter with scopes\n P_lmin = nothing\n P_lminmin = nothing\n\n for l = 0:lmax\n if (l == 0)\n P_l = 1\n elseif (l == 1)\n P_l = x\n else\n P_l = x * P_lmin * (2 * l - 1) / l - P_lminmin * (l - 1) / l # l Pₗ = x * (2 l - 1) Pₗ₋₁ + (l - 1) Pₗ₋₂\n end\n\n if ((l % 2 == 0) && (l > 0)) # we only store the even harmonics, and l = 0 is useless because it brings a constant to the energy\n l_half = div(l, 2)\n Pₗ[l_half] = P_l\n end\n\n P_lminmin = P_lmin\n P_lmin = P_l\n end\nend\n\nfunction Normalized_associated_Legendre_polynomials!(x::Float64, lmax::Int64; P = nothing) \n #### Returns an array of size lmax_half * (lmax + 1). Each cell contains one normalized associated Legendre polynomails Pᴺₗₘ(x) ####\n #### The definition is Pᴺₗₘ = √((2l + 1) / (4 π)) × √(l - m)! / (l + m)! × Pₗₘ where Pₗₘ is the standard associated Legendre polynomial. ####\n # getting all the constants we will need\n lmax_half = div(lmax, 2)\n\n # Preallocating P if it hasn't been given\n if isnothing(P)\n P = zeros(lmax + 1, lmax_half) # Will store the normalized associated Legendre polynomials\n end\n\n # Let's start the recurrence -- We use the method from Numerical Recipes (eq. 6.7.9)\n Pₘₘ = nothing # this is just to help the compilator with scopes\n\n for m = 0:lmax\n # First let's get Pₘₘ by a first recurrence relation\n if (m == 0)\n Pₘₘ = sqrt(1 / (4 * π)) # P₀₀ = sqrt(1 / 4π)\n else\n Pₘₘ = -1.0 * sqrt((2 * m + 1) / (2 * m)) * sqrt(1 - x^(2)) * Pₘₘ # Pₘ,ₘ = - sqrt((2m + 1) / 2m) * sqrt(1 - x²) * Pₘ₋₁,ₘ₋₁\n end\n \n # The we go from m,m to m,l step by step\n Pₗₘ = nothing # this is just to help the compilator with scopes\n Pₗₘ_min = nothing\n Pₗₘ_minmin = nothing\n\n for l = m:lmax\n if (l == m)\n Pₗₘ = Pₘₘ\n elseif (l == (m + 1))\n Pₗₘ = x * sqrt(2 * m + 3) * Pₘₘ # Pₘ,ₘ₊₁ = x sqrt(2m + 3) Pₘₘ\n else\n Pₗₘ = sqrt((4 * l^2 - 1) / (l^2 - m^2)) * ( x * Pₗₘ_min - sqrt( ((l - 1)^2 - m^2) / (4 * (l - 1)^2 -1)) * Pₗₘ_minmin )\n # Pₘₗ = sqrt((4l² - 1) / (l² - m²)) * [x Pₘ,ₗ₋₁ - sqrt(((l - 1)² - m²) / (4 (l - 1)² - 1)) Pₘₗ₋₂]\n end\n\n if (((l % 2) == 0) && (l > 0)) # We store the coefficients only if l is even\n l_half = div(l, 2)\n P[m + 1, l_half] = Pₗₘ\n end\n\n Pₗₘ_minmin = Pₗₘ_min\n Pₗₘ_min = Pₗₘ\n end\n end\n\n return(P)\nend", "meta": {"hexsha": "9bcf1a5b40fe927a16ad2f7dcf05174f72b23661", "size": 3169, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Code/Legendre_polynomials.jl", "max_stars_repo_name": "NathanMagnan/VRROOMe", "max_stars_repo_head_hexsha": "9047b050687598c99d818b1498c8deae835be756", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Code/Legendre_polynomials.jl", "max_issues_repo_name": "NathanMagnan/VRROOMe", "max_issues_repo_head_hexsha": "9047b050687598c99d818b1498c8deae835be756", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/Legendre_polynomials.jl", "max_forks_repo_name": "NathanMagnan/VRROOMe", "max_forks_repo_head_hexsha": "9047b050687598c99d818b1498c8deae835be756", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.1807228916, "max_line_length": 145, "alphanum_fraction": 0.5276112338, "num_tokens": 1177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768541530197, "lm_q2_score": 0.861538211208597, "lm_q1q2_score": 0.8134444379915529}} {"text": "#' ---\n#' title: Maximum cut problem, linear and semidefinite optimization formulations\n#' ---\n\n#' **Originally Contributed by**: Mathieu Besançon\n\nusing LinearAlgebra\nusing SparseArrays\nusing Test\nimport Random\n\nusing JuMP\nusing GLPK\nusing LightGraphs\nusing GraphPlot\nimport SCS\nusing Colors: @colorant_str\n\n#' ## The Maximum Cut problem\n\n# TODO explain problem\n\n#' The Integer Linear Formulation\n\n#' $$\n#' \\begin{align*}\n#' \\max_{x,z} & \\sum_{\\forall (i,j) \\in E} w_{i,j} z_{ij} \\\\\n#' \\text{s.t. } & z_{ij} \\leq x_i + x_j \\\\\n#' & z_ij \\leq 2 - (x_i + x_j)\\\\\n#' & z_{ij} \\in \\{0,1\\} \\forall (i,j) \\in E \\\\\n#' & x_{i} \\in \\{0,1\\} \\forall i \\in V\n#' \\end{align*}\n#' $$\n\nfunction compute_cut_value(g::LightGraphs.AbstractGraph, w::AbstractMatrix, vertex_subset)\n return sum(w[i,j] for i in vertices(g) for j in neighbors(g, i) if in(i, vertex_subset) != in(j, vertex_subset))\nend\n\n#' The following example graph is taken from https://en.wikipedia.org/wiki/Graph_theory#/media/File:6n-graf.svg\n#'\n\ng = SimpleGraph(6)\nadd_edge!(g, 1, 2)\nadd_edge!(g, 1, 5)\nadd_edge!(g, 2, 3)\nadd_edge!(g, 2, 5)\nadd_edge!(g, 3, 4)\nadd_edge!(g, 4, 5)\nadd_edge!(g, 4, 6);\n\nGraphPlot.gplot(g, nodelabel=1:6)\n\n#' Creating a unit weight matrix\n\nw = spzeros(6, 6)\n\nfor e in edges(g)\n (i, j) = Tuple(e)\n w[i,j] = 1\nend\n\n#' Computing value for a solution\n\n@test compute_cut_value(g, w, (2, 5, 6)) ≈ 5\n@show compute_cut_value(g, w, (2, 5, 6));\n\n#' Building the linear optimization model\n\nn = nv(g)\n\nlinear_max_cut = Model(GLPK.Optimizer)\n\n@variable(linear_max_cut, z[1:n,1:n], Bin)\n@variable(linear_max_cut, x[1:n], Bin)\n@constraint(linear_max_cut, [i = 1:n, j = 1:n; (i, j) in edges(g)], z[i,j] <= x[i] + x[j])\n@constraint(linear_max_cut, [i = 1:n, j = 1:n; (i, j) in edges(g)], z[i,j] <= 2 - (x[i] + x[j]))\n\n@objective(linear_max_cut, Max, dot(w, z))\n\noptimize!(linear_max_cut)\n\n@test objective_value(linear_max_cut) ≈ 6.0\n@show objective_value(linear_max_cut);\n\nx_linear = value.(x)\n@show x_linear;\n@show [(i,j) for i in 1:n-1 for j in i+1:n if JuMP.value.(z)[i,j] > 0.5];\n\n#' Visualizing a solution\n\nnodecolor = [colorant\"lightseagreen\", colorant\"orange\"]\nall_node_colors = [nodecolor[round(Int, xi + 1)] for xi in x_linear]\nGraphPlot.gplot(g, nodelabel=1:6, nodefillc=all_node_colors)\n\n#' ### Semidefinite formulation\n\n#' The maximum cut problem can also be formulated as a quadratic optimization model.\n#' If the solution vector is composed of $\\{-1, 1\\}$ for belonging to the subset or not.\n#' Then, the product $x_i x_j$ is $-1$ if i and j are in different subsets, and 1 otherwise.\n#' This implies $1 - x_i x_j$ is $0$ if i and j are in the same subset, and 2 otherwise.\n#' Since each pair is counted twice with (i,j) and (j,i), we need to divide it by 4:\n#' $\\frac{w_{ij}}{4} (1 - x_i x_j)$ is $0$ if i and j are in the same subset, and $z_{ij}$ otherwise.\n\n#' The resulting model is given by:\n#' $$\n#' \\begin{align*}\n#' \\max_{x} & \\frac{w_{ij}}{4} (1 - x_i x_j) \\\\\n#' \\text{s.t. } & x_i \\in \\{-1, 1\\} \\forall i \\in V\n#' \\end{align*}\n#' $$\n\n#' Introducing a matrix variable $Y_{ij} = x_i x_j$,\n#' we can equivalently reformulate the above quatratic problem as follows:\n#' $$\n#' \\begin{align*}\n#' \\max_{x,Y} & \\frac{w_{ij}}{4} (1 - Y_{ij}) \\\\\n#' \\text{s.t. } & Y_{ii} = 1 \\forall i \\in V \\\\\n#' & Y = x x^T\n#' \\end{align*}\n#' $$\n\n#' The constraint $Y = x x^T$ requires $Y$ to be a Positive Semidefinite matrix\n#' of rank one. This optimization problem is fully equivalent to the initial\n#' quadratic problem and hard to solve.\n#' A possible relaxation is to remove the rank-1 constraint, yielding the following problem:\n#' $$\n#' \\begin{align*}\n#' \\max_{Y} & \\frac{w_{ij}}{4} (1 - Y_{ij}) \\\\\n#' \\text{s.t. } & Y_{ii} = 1 \\forall i \\in V \\\\\n#' & Y \\in \\mathcal{S}_n^+\n#' \\end{align*}\n#' $$\n\n#' with $\\mathcal{S}_n^+$ the set of positive semidefinite matrices.\n#' Such model can be implemented in JuMP and solved using an underlying solver\n#' which supports semidefinite optimization.\n\nsdp_max_cut = Model(optimizer_with_attributes(SCS.Optimizer, \"verbose\" => 0))\n\n@variable(sdp_max_cut, Y[1:n,1:n] in PSDCone())\n@constraint(sdp_max_cut, [i = 1:n], Y[i,i] == 1)\n@objective(sdp_max_cut, Max, 1/4 * sum(w[i,j] * (1 - Y[i,j]) for i in 1:n for j in 1:n))\n\noptimize!(sdp_max_cut)\n\n@test objective_value(linear_max_cut) >= 6.0\n@show objective_value(linear_max_cut);\n\n#' Re-computing the vector:\n#' $Y$ approximates $x x^T$, we can compute the estimate by randomized rounding.\n#' Goemans, M. X., & Williamson, D. P. (1995).\n#' Improved approximation algorithms for maximum cut and satisfiability problems using semidefinite programming.\n#' Journal of the ACM (JACM), 42(6), 1115-1145.\n\nF = svd(value.(Y))\nU = F.U * Diagonal(sqrt.(F.S))\n\nRandom.seed!(33)\n\n#' Generating a normal random vector: the vector\n#' needs to be uniformly generated on a sphere centered at 0.\n\nx = randn(size(U, 2))\nxhat = sign.(U * x) .> 0\n\n@show collect(zip(round.(Int, x_linear), xhat))\n@test LinearAlgebra.norm1(round.(Int, x_linear) .- xhat) == 0 || LinearAlgebra.norm1(round.(Int, x_linear) .- xhat) == n\n\n#' ### Representing the SDP approximated solution\n\nnodecolor = [colorant\"lightseagreen\", colorant\"orange\"]\nall_node_colors = [nodecolor[xi + 1] for xi in xhat]\nGraphPlot.gplot(g, nodelabel=1:6, nodefillc=all_node_colors)\n", "meta": {"hexsha": "d62ae8718e4ae25a3d19f6c4f4911f1033012d48", "size": 5308, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/modelling/maxcut.jl", "max_stars_repo_name": "mtanneau/JuMPTutorials.jl", "max_stars_repo_head_hexsha": "f91839c6b127966c3cb17e8971cc95fe3adfa814", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 75, "max_stars_repo_stars_event_min_datetime": "2020-06-15T13:05:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T12:58:48.000Z", "max_issues_repo_path": "script/modelling/maxcut.jl", "max_issues_repo_name": "mtanneau/JuMPTutorials.jl", "max_issues_repo_head_hexsha": "f91839c6b127966c3cb17e8971cc95fe3adfa814", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34, "max_issues_repo_issues_event_min_datetime": "2019-05-27T05:36:48.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-22T09:52:29.000Z", "max_forks_repo_path": "script/modelling/maxcut.jl", "max_forks_repo_name": "mtanneau/JuMPTutorials.jl", "max_forks_repo_head_hexsha": "f91839c6b127966c3cb17e8971cc95fe3adfa814", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2019-10-09T09:32:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-02T17:41:21.000Z", "avg_line_length": 30.5057471264, "max_line_length": 120, "alphanum_fraction": 0.6607008289, "num_tokens": 1781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176857294597, "lm_q2_score": 0.8615382076534743, "lm_q1q2_score": 0.8134444373414773}} {"text": "### A Pluto.jl notebook ###\n# v0.10.0\n\nusing Markdown\n\n# ╔═╡ b7d4165b-d051-441d-b4d1-251eba60a0d2\nmd\"\"\"\n# Funciones\n\nTemas:\n1. Cómo declara una función\n2. Duck-typing en Julia\n3. Funciones mutantes vs. no-mutantes\n4. Broadcasting\n\"\"\"\n\n# ╔═╡ 39434826-4c89-4074-9c9e-770bde3463dd\nmd\"\"\"\n## Cómo declarar una función\nJulia nos permite definir una función de varias maneras. La primera requiere de las palabras reservadas `function` y `end`\n\"\"\"\n\n# ╔═╡ 0adc05a6-8428-4722-94cc-355e65437395\nfunction sayhi(name)\n println(\"Hi $name, it's great to see you!\")\nend\n\n# ╔═╡ 158e67af-59ce-4d4f-8256-f635ffedf5a0\nfunction f(x)\n x^2\nend\n\n# ╔═╡ b1bc4d5d-33b5-4698-8fb8-f4126af5463d\nmd\"\"\"\nY las podemos llamar así\n\"\"\"\n\n# ╔═╡ eaf96975-d1e6-4369-9fa1-8ab49b69b6d9\nsayhi(\"C-3PO\")\n\n# ╔═╡ 7a5019b7-6ae4-4fcd-9859-118a6e000033\nf(42)\n\n# ╔═╡ e3585fc6-78ed-4ccf-a9f0-3387e41b1193\nmd\"\"\"\nAlternativamente, las podemos declarar en una sóla línea\n\"\"\"\n\n# ╔═╡ 311a5abb-86ad-411f-9118-8827b65fb833\nsayhi2(name) = println(\"Hi $name, it's great to see you!\")\n\n# ╔═╡ 25594aa9-0d0d-49e6-84cb-33d195e7bd62\nf2(x) = x^2\n\n# ╔═╡ 99fae709-86fd-4962-a47f-0dadfcebf9fc\nsayhi2(\"R2D2\")\n\n# ╔═╡ c66327e0-3ac1-4078-96df-4c0132eeb5e9\nf2(42)\n\n# ╔═╡ 707831b6-e85a-4a11-9648-0af16acf71f7\nmd\"\"\"\nFinalmente, pudimos declararlas como funciones \"anónimas\"\n\"\"\"\n\n# ╔═╡ c71820ac-4ae6-42a1-a1cb-d05ab25afc75\nsayhi3 = name -> println(\"Hi $name, it's great to see you!\")\n\n# ╔═╡ 7a5b1e40-def3-4cca-9c81-73addb86aa18\nf3 = x -> x^2\n\n# ╔═╡ ca7f38ca-1b81-4425-ba04-32c40ba329cd\nsayhi3(\"Chewbacca\")\n\n# ╔═╡ 59382902-5270-44f5-a19e-d8c296e630f3\nf3(42)\n\n# ╔═╡ 10880ded-73a9-4165-b993-623d93e08630\nmd\"\"\"\n## Duck-typing en Julia\n*\"If it quacks like a duck, it's a duck.\"* \n*\"Si suena como pato, es un pato\"*\n

\nEn Julia, las funciones operaran con el cualquier valor que haga sentido.

\nPor ejemplo, `sayhi` funciona con el nombre de este personaje de tele, escrito como entero...\n\"\"\"\n\n# ╔═╡ 10205f9e-6758-44a7-a1ed-f1daae906893\nsayhi(55595472)\n\n# ╔═╡ 5d4f722a-3e68-422c-8dab-4c92be5b9804\nmd\"\"\"\nY `f` va a funcionar en una matriz.\n\"\"\"\n\n# ╔═╡ b9bfd357-22e7-4d75-a251-53e8379f8017\nA = rand(3, 3)\nA\n\n# ╔═╡ 779781b3-5092-4559-9d61-b2e83d2b259a\nf(A)\n\n# ╔═╡ f16551eb-e665-4922-8e98-548a55872ebd\nmd\"\"\"\n`f` funcionará con \"hi\" porque `*` para inputs de cadenas como concatenación.\n\"\"\"\n\n# ╔═╡ b626e299-7afd-4b62-b070-738fff6cb6cb\nf(\"hi\")\n\n# ╔═╡ 2c44a8ae-c8e7-49ad-9de2-0537c56a6f23\nmd\"\"\"\nPor el otro lado, `f` no funcionará sobre un vector. A diferencia de `A^2`, la cual es una operación bien definida, el signifiado de `v^2` para un vector, `v`, es ambigua. \n\"\"\"\n\n# ╔═╡ 747e9a83-7886-4b33-a8d6-fd60293b2a0a\nv = rand(3)\n\n# ╔═╡ fb3682c1-674c-4ea3-a222-103bf960cbe8\nf(v)\n\n# ╔═╡ 81a0e65a-e4fb-427b-b59c-3248eff10b61\nmd\"\"\"\n## Funciones mutantes vs no-mutantes\n\nPor convención, funciones seguidas por un `!` alteran, o bien mutan, sus contenidos y las que carecen de un `!` no lo hacen.\n\nPor ejemplo, `sort` y `sort!`.\n\n\"\"\"\n\n# ╔═╡ 3ce811b3-19aa-4f4f-8cf5-28f0032cc878\nv = [3, 5, 2]\n\n# ╔═╡ 284c7800-9dc2-4f0c-b3c0-da82e020cdfa\nsort(v)\n\n# ╔═╡ eec63ee5-9d20-4892-92df-9d0aeecfb323\nv\n\n# ╔═╡ 99dfcd21-d511-40d5-8119-fdf943bb2708\nmd\"\"\"\n`sort(v)` regresa el arreglo ordenado de `v`, pero `v` no cambia.

\n\nPor otro lado, si corremos `sort!(v)`, el contenido del arreglo es ordenado dentro de `v`.\n\"\"\"\n\n# ╔═╡ 11a3c01b-0ac1-4538-8103-8e7e35eadd3c\nsort!(v)\n\n# ╔═╡ 017e9146-e1ab-46c0-b6e8-e36f14965639\nv\n\n# ╔═╡ ca47c936-e9e4-4039-9ff2-3e6f6f395f89\nmd\"\"\"\n## Broadcasting\n\nSi ponemos `.` entre el nombre de la funcion y su lista de argumento,
\nle estamos diciendo a la función que se \"difunda\"/haga broadcasting sobre los elementos del input.
\n\nPrimero veamos la diferencia entre `f()` y `f.()`.
\n\nPrimero definimos una nueva matriz `A` que hará la diferencia fácil de observar\n\"\"\"\n\n# ╔═╡ 0e5e8129-b03f-4010-8e33-d57d4aa49529\nA = [i + 3*j for j in 0:2, i in 1:3]\n\n# ╔═╡ 96b1c681-280a-43b0-bc00-2abb315549f6\nf(A)\n\n# ╔═╡ ac7f99d1-0eef-43b6-a01a-0da4bf0d5ef5\nmd\"\"\"\nCómo se vio antes, para una matriz, `A`,\n```\nf(A) = A^2 = A * A\n``` \n\n`f.(A)` por el otro lado va a regresar un objeto que contiene el cuadrado de `A[i, j]` en su entrada correspondiente.\n\"\"\"\n\n# ╔═╡ 5d1d011e-2399-4d33-858c-b7b7e89e81b6\nB = f.(A)\n\n# ╔═╡ b5c3116e-f7dd-4ead-a554-c539eb152a32\nA[2, 2]\n\n# ╔═╡ 9144bda4-a4d0-4c30-b551-0324c35761eb\nA[2, 2]^2\n\n# ╔═╡ 918a6647-80e5-4a5a-820c-cdaf6f835fc7\nB[2, 2]\n\n# ╔═╡ 6469d0a9-860b-4bc0-b791-40edc1cea224\nmd\"\"\"\nEsto significa que para `v`, `f.(v)` está definido, pero no para `f(v)` :\n\"\"\"\n\n# ╔═╡ 72658881-9638-4264-8d65-5766423ace70\nv = [1, 2, 3]\n\n# ╔═╡ 5c26b16d-4d73-4b79-b5e4-3b1e20c5cd9d\nf.(v)\n\n# ╔═╡ fb497c48-76e2-4eb1-8e21-785c93f39dc4\nmd\"\"\"\n### Ejercicios\n\n6.1 En vez de broadcastear `f` sobre `v`, pudimos haber hecho `v .^ 2`.\n\nSin declarar una nueva funcion, agrega 1 a cada elemento de una matriz de `3x3` llena de `0`'s.\n\"\"\"\n\n# ╔═╡ f681fc78-679f-45b8-ae95-14b2d9eb6366\n\n\n# ╔═╡ 62c8731f-63a7-4fae-8980-0d0665cb556a\nmd\"\"\"\n\n\"\"\"\n\n# ╔═╡ 7dbb40ed-0b51-4825-bbc8-9e6f4d0c4738\n\n\n# ╔═╡ be113c25-4aec-4ead-a812-50a54aa7428d\nmd\"\"\"\n6.3 Una cifra de César recorre cada letra un número determinado de plazas más adelante en el abecedario. Un corrimiento, o shift, de 1 manda \"A\" a \"B\". Escribe una función llamada `cesar` que toma una cadena como input y un corrimiento y regresa una cadena desencriptada tal que obtengas\n\n```julia\ncesar(\"abc\", 1)\n\"bcd\"\n\ncesar(\"hello\", 4)\n\"lipps\"\n```\n\"\"\"\n\n# ╔═╡ 14e4057a-96f3-4cec-b1f0-e0c01e73dd86\n\n\n# ╔═╡ Cell order:\n# ╟─b7d4165b-d051-441d-b4d1-251eba60a0d2\n# ╟─39434826-4c89-4074-9c9e-770bde3463dd\n# ╠═0adc05a6-8428-4722-94cc-355e65437395\n# ╠═158e67af-59ce-4d4f-8256-f635ffedf5a0\n# ╟─b1bc4d5d-33b5-4698-8fb8-f4126af5463d\n# ╠═eaf96975-d1e6-4369-9fa1-8ab49b69b6d9\n# ╠═7a5019b7-6ae4-4fcd-9859-118a6e000033\n# ╟─e3585fc6-78ed-4ccf-a9f0-3387e41b1193\n# ╠═311a5abb-86ad-411f-9118-8827b65fb833\n# ╠═25594aa9-0d0d-49e6-84cb-33d195e7bd62\n# ╠═99fae709-86fd-4962-a47f-0dadfcebf9fc\n# ╠═c66327e0-3ac1-4078-96df-4c0132eeb5e9\n# ╟─707831b6-e85a-4a11-9648-0af16acf71f7\n# ╠═c71820ac-4ae6-42a1-a1cb-d05ab25afc75\n# ╠═7a5b1e40-def3-4cca-9c81-73addb86aa18\n# ╠═ca7f38ca-1b81-4425-ba04-32c40ba329cd\n# ╠═59382902-5270-44f5-a19e-d8c296e630f3\n# ╟─10880ded-73a9-4165-b993-623d93e08630\n# ╠═10205f9e-6758-44a7-a1ed-f1daae906893\n# ╟─5d4f722a-3e68-422c-8dab-4c92be5b9804\n# ╠═b9bfd357-22e7-4d75-a251-53e8379f8017\n# ╠═779781b3-5092-4559-9d61-b2e83d2b259a\n# ╟─f16551eb-e665-4922-8e98-548a55872ebd\n# ╠═b626e299-7afd-4b62-b070-738fff6cb6cb\n# ╟─2c44a8ae-c8e7-49ad-9de2-0537c56a6f23\n# ╠═747e9a83-7886-4b33-a8d6-fd60293b2a0a\n# ╠═fb3682c1-674c-4ea3-a222-103bf960cbe8\n# ╟─81a0e65a-e4fb-427b-b59c-3248eff10b61\n# ╠═3ce811b3-19aa-4f4f-8cf5-28f0032cc878\n# ╠═284c7800-9dc2-4f0c-b3c0-da82e020cdfa\n# ╠═eec63ee5-9d20-4892-92df-9d0aeecfb323\n# ╟─99dfcd21-d511-40d5-8119-fdf943bb2708\n# ╠═11a3c01b-0ac1-4538-8103-8e7e35eadd3c\n# ╠═017e9146-e1ab-46c0-b6e8-e36f14965639\n# ╟─ca47c936-e9e4-4039-9ff2-3e6f6f395f89\n# ╠═0e5e8129-b03f-4010-8e33-d57d4aa49529\n# ╠═96b1c681-280a-43b0-bc00-2abb315549f6\n# ╟─ac7f99d1-0eef-43b6-a01a-0da4bf0d5ef5\n# ╠═5d1d011e-2399-4d33-858c-b7b7e89e81b6\n# ╠═b5c3116e-f7dd-4ead-a554-c539eb152a32\n# ╠═9144bda4-a4d0-4c30-b551-0324c35761eb\n# ╠═918a6647-80e5-4a5a-820c-cdaf6f835fc7\n# ╟─6469d0a9-860b-4bc0-b791-40edc1cea224\n# ╠═72658881-9638-4264-8d65-5766423ace70\n# ╠═5c26b16d-4d73-4b79-b5e4-3b1e20c5cd9d\n# ╟─fb497c48-76e2-4eb1-8e21-785c93f39dc4\n# ╠═f681fc78-679f-45b8-ae95-14b2d9eb6366\n# ╟─62c8731f-63a7-4fae-8980-0d0665cb556a\n# ╠═7dbb40ed-0b51-4825-bbc8-9e6f4d0c4738\n# ╟─be113c25-4aec-4ead-a812-50a54aa7428d\n# ╠═14e4057a-96f3-4cec-b1f0-e0c01e73dd86\n", "meta": {"hexsha": "785d3c234c1bd80add18fe614d2a2dc9e0d65cff", "size": 7581, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "es-es/intro-to-julia-ES/plutos/plutos2/06.Funciones.jl", "max_stars_repo_name": "miguelraz/JuliaTutorials", "max_stars_repo_head_hexsha": "1d427c70c7254844c9734a20e7402e60a000528f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-11-22T00:48:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T15:10:03.000Z", "max_issues_repo_path": "es-es/intro-to-julia-ES/plutos/plutos2/06.Funciones.jl", "max_issues_repo_name": "miguelraz/JuliaTutorials", "max_issues_repo_head_hexsha": "1d427c70c7254844c9734a20e7402e60a000528f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "es-es/intro-to-julia-ES/plutos/plutos2/06.Funciones.jl", "max_forks_repo_name": "miguelraz/JuliaTutorials", "max_forks_repo_head_hexsha": "1d427c70c7254844c9734a20e7402e60a000528f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8737201365, "max_line_length": 287, "alphanum_fraction": 0.7166600712, "num_tokens": 4064, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.8902942203004186, "lm_q1q2_score": 0.8134409238340421}} {"text": "#\n# Non linear model fitting \n#\n# author: Atsushi Sakai\n#\n\nusing PyPlot\nusing ArgMin\n\n\nfunction calc_y(theta, x)\n \ty = theta[1]*exp.(theta[2]*x) .* cos.(theta[3]*x .+ theta[4]);\n\treturn y\nend\n\nfunction main()\n println(PROGRAM_FILE,\" start!!\")\n\ttheta_true = [1, -0.2, 2*pi/5, pi/3] # true parameters\n\n\t# Input data \n\tM = 30\n\txd = [5*rand(M); 5 .+ 15*rand(M)]\n\tyd = calc_y(theta_true, xd)\n\n\tf(theta) = theta[1] * exp.(theta[2]*xd) .* cos.(theta[3] * xd .+ theta[4]) - yd;\n \tDf(theta) = hcat( exp.(theta[2]*xd) .* cos.(theta[3] * xd .+ theta[4]),\n \t\t\t\ttheta[1] * ( xd .* exp.(theta[2]*xd) .* cos.(theta[3] * xd .+ theta[4])),\n \t\t\t\t-theta[1] * ( exp.(theta[2]*xd) .* xd .* sin.(theta[3] * xd .+ theta[4])),\n \t\t\t\t-theta[1] * ( exp.(theta[2]*xd) .* sin.(theta[3] * xd .+ theta[4])) );\n\ttheta0 = [1, 0, 1, 0]; # initial parameters\n\tx = linspace(0, 20, 500);\n\ty1 = calc_y(theta0, x)\n\t\n\ttheta, history = solve_nonlinear_least_square_with_levenberg_marquardt(f, Df, theta0, 1.0)\n\n\tprintln(\"theta_true:\", theta_true)\n\tprintln(\"theta:\",theta)\n \ty = calc_y(theta, x)\n\tplot(xd, yd, \"ob\", label=\"Input data\")\n\tplot(x, y1, \"--r\", label=\"Initial param\")\n\tplot(x, y, \"-r\", label=\"Optimized param\")\n\tlegend()\n\tshow()\n\n println(PROGRAM_FILE,\" Done!!\")\nend\n\nmain()\n\n", "meta": {"hexsha": "d781310d2305cdd9fda365933703bd9e16c02936", "size": 1297, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/nonlinear_model_fitting/nonlinear_model_fitting.jl", "max_stars_repo_name": "AtsushiSakai/ArgMin.jl", "max_stars_repo_head_hexsha": "8584acd49640ac775f5ac5e47860a0d2d4953d54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/nonlinear_model_fitting/nonlinear_model_fitting.jl", "max_issues_repo_name": "AtsushiSakai/ArgMin.jl", "max_issues_repo_head_hexsha": "8584acd49640ac775f5ac5e47860a0d2d4953d54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/nonlinear_model_fitting/nonlinear_model_fitting.jl", "max_forks_repo_name": "AtsushiSakai/ArgMin.jl", "max_forks_repo_head_hexsha": "8584acd49640ac775f5ac5e47860a0d2d4953d54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.94, "max_line_length": 92, "alphanum_fraction": 0.565921357, "num_tokens": 477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.8856314632529871, "lm_q1q2_score": 0.8134350044612928}} {"text": "using Distributions, Random, Plots, LaTeXStrings; pyplot()\nRandom.seed!(1)\n\na, c, d = 2, 1, 5\nsig = 0.02\nnext(x,y) = [a*x*(1-x) - x*y, -c*y + d*x*y]\nequibPoint = [(1+c)/d ,(d*(a-1)-a*(1+c))/d]\n\ninitX = [0.8,0.05]\ntEnd,tEndStoch = 100, 10\n\ntraj = [[] for _ in 1:tEnd]\ntrajStoch = [[] for _ in 1:tEndStoch]\ntraj[1], trajStoch[1] = initX, initX\n\nfor t in 2:tEnd\n traj[t] = next(traj[t-1]...)\nend\n\nfor t in 2:tEndStoch\n trajStoch[t] = next(trajStoch[t-1]...) + [rand(Normal(0,sig)),0.0]\nend\n\nscatter([traj[1][1]], [traj[1][2]], \n\tc=:black, ms=10, label=\"Initial state\")\nplot!(first.(traj), last.(traj), \n\tc=:blue, ls=:dash, m=(:dot, 5, Plots.stroke(0)), \n\tlabel=\"Deterministic trajectory\")\nplot!(first.(trajStoch),last.(trajStoch), \n\tc=:green, ls=:dash, m=(:dot, 5, Plots.stroke(0)), \n\tlabel=\"Stochastic trajectory\")\nscatter!([equibPoint[1]], [equibPoint[2]], \n\tc=:red, shape=:cross, ms=10, label=\"Equlibrium point\", \n\txlabel=L\"X_1\", ylabel=L\"X_2\")", "meta": {"hexsha": "38b0a05e7db30ceeeff431208a395e8cedf61727", "size": 951, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "10_chapter/predatorPreyStoch.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "10_chapter/predatorPreyStoch.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "10_chapter/predatorPreyStoch.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 27.9705882353, "max_line_length": 70, "alphanum_fraction": 0.6140904311, "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533107374444, "lm_q2_score": 0.8723473879530492, "lm_q1q2_score": 0.8134232100099826}} {"text": "\nusing ..CommonFunctions\n\n\n@doc raw\"\"\"\n# Hermite's Interpolating Polynomials\n\nHere, we implement a two point Hermite interpolation function which passes\nthrough the function and its first derivative for the interval ``[0,1]``.\nThe polynomial is determined by four constraint equations, matching the\nfunction and its derivative at the points ``0`` and ``1``.\n\nStart by defining the 3rd degree polynomial and its derivative by\n```math\n\\begin{align*}\ng(x) &= a_0 + a_1 x + a_2 x^2 + a_3 x^3 , \\\\\ng'(x) &= a_1 + 2 a_2 x + 3 a_3 x^2 ,\n\\end{align*}\n```\nand apply the constraints\n```math\n\\begin{align*}\ng(0) &= f_0 & & \\Rightarrow & a_0 &= f_0 , \\\\\ng(1) &= f_1 & & \\Rightarrow & a_0 + a_1 + a_2 + a_3 &= f_1 , \\\\\ng'(0) &= f'_0 & & \\Rightarrow & a_1 &= f'_0 , \\\\\ng'(1) &= f'_1 & & \\Rightarrow & a_1 + 2 a_2 + 3 a_3 &= f'_1 . \\\\\n\\end{align*}\n```\nSolving for ``a_0, a_1, a_2, a_3`` leads to\n```math\n\\begin{align*}\na_0 &= f_0 , &\na_1 &= f'_0 , &\na_2 &= - 3 f_0 + 3 f_1 - 2 f'_0 - f'_1 , &\na_3 &= 2 f_0 - 2 f_1 + f'_0 + f'_1 ,\n\\end{align*}\n```\nso that the polynomial ``g(x)`` reads\n```math\ng(x) = f_0 + f'_0 x + (- 3 f_0 + 3 f_1 - 2 f'_0 - f'_1) x^2 + (2 f_0 - 2 f_1 + f'_0 + f'_1) x^3 .\n```\nThe function and derivative values can be factored out, so that ``g(x)`` can be rewritten as\n```math\ng(x) = f_0 (1 - 3 x^2 + 2 x^3) + f_1 (3 x^2 - 2 x^3) + f'_0 (x - 2 x^2 + x^3) + f'_1 (- x^2 + x^3) ,\n```\nor in generic form as\n```math\ng(x) = f_0 a_0(x) + f_1 a_1(x) + f'_0 b_0(x) + f'_1 b_1(x) ,\n```\nwith basis functions\n```math\n\\begin{align*}\na_0 (x) &= 1 - 3 x^2 + 2 x^3 , &\nb_0 (x) &= x - 2 x^2 + x^3 , \\\\\na_1 (x) &= 3 x^2 - 2 x^3 , &\nb_1 (x) &= - x^2 + x^3 .\n\\end{align*}\n```\nThe derivative ``g'(x)`` accordingly reads\n```math\ng'(x) = f_0 a'_0(x) + f_1 a'_1(x) + f'_0 b'_0(x) + f'_1 b'_1(x) ,\n```\nwith\n```math\n\\begin{align*}\na'_0 (x) &= - 6 x + 6 x^2 , &\nb'_0 (x) &= 1 - 4 x + 3 x^2 , \\\\\na'_1 (x) &= 6 x - 6 x^2 , &\nb'_1 (x) &= - 2 x + 3 x^2 .\n\\end{align*}\n```\nThe basis functions ``a_0``and ``a_1`` are associated with the function\nvalues at ``x_0`` and ``x_1``, respectively, while the basis functions\n``b_0`` and ``b_1`` are associated with the derivative values at\n``x_0`` and ``x_1``.\nThe basis functions satisfy the following relations,\n```math\n\\begin{align*}\na_i (x_j) &= \\delta_{ij} , &\nb_i (x_j) &= 0 , &\na'_i (x_j) &= 0 , &\nb'_i (x_j) &= \\delta_{ij} , &\ni,j &= 0, 1 ,\n\\end{align*}\n```\nwhere ``\\delta_{ij}`` denotes the Kronecker-delta, so that\n```math\n\\begin{align*}\ng(0) &= f_0 , &\ng(1) &= f_1 , &\ng'(0) &= f'_0 , &\ng'(1) &= f'_1 .\n\\end{align*}\n```\n\"\"\"\nstruct HermiteInterpolation{T} <: Interpolator{T}\n x₀::T\n x₁::T\n Δx::T\n\n function HermiteInterpolation{T}(x₀, x₁, Δx, d) where {T}\n new(x₀, x₁, Δx)\n end\nend\n\nfunction HermiteInterpolation(x₀::T, x₁::T, Δx::T, d::Int) where {T}\n HermiteInterpolation{T}(x₀, x₁, Δx, d)\nend\n\n\nfunction CommonFunctions.evaluate!(int::HermiteInterpolation{T}, y₀::Vector{T}, y₁::Vector{T}, f₀::Vector{T}, f₁::Vector{T}, x::T, y::Vector{T}) where {T}\n local a₀::T\n local a₁::T\n local b₀::T\n local b₁::T\n\n # Interpolate y values at required locations\n if x == int.x₀\n y .= y₀\n elseif x == int.x₁\n y .= y₁\n else\n a₁ = 3x^2 - 2x^3\n a₀ = 1 - a₁\n b₁ = x^2*(x-1)\n b₀ = x*(1-x)+b₁\n y .= a₀ .* y₀ .+ a₁ .* y₁ .+ b₀ .* int.Δx .* f₀ .+ b₁ .* int.Δx .* f₁\n end\nend\n\nfunction CommonFunctions.evaluate!(int::HermiteInterpolation{T}, y₀::Vector{T}, y₁::Vector{T}, f₀::Vector{T}, f₁::Vector{T}, x::T, y::Vector{T}, f::Vector{T}) where {T}\n local a₀::T\n local a₁::T\n local b₀::T\n local b₁::T\n\n evaluate!(int, y₀, y₁, f₀, f₁, x, y)\n\n # Interpolate f values at required locations\n if x == int.x₀\n f .= f₀\n elseif x == int.x₁\n f .= f₁\n else\n a₁ = (6x - 6x^2) / int.Δx\n a₀ = - a₁\n b₁ = x*(3x-2)\n b₀ = 1-2x+b₁\n f .= b₀ .* f₀ .+ b₁ .* f₁ .+ a₀ .* y₀ .+ a₁ .* y₁\n end\nend\n", "meta": {"hexsha": "a7086ca1186b44a5e01af51ab04319e22d4aff44", "size": 3955, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/interpolation/hermite_interpolation.jl", "max_stars_repo_name": "krystophny/GeometricIntegrators.jl", "max_stars_repo_head_hexsha": "7855e977b014c8ba119f6bb73c6ed9bf96f04b1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-02-04T11:52:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-04T11:52:47.000Z", "max_issues_repo_path": "src/interpolation/hermite_interpolation.jl", "max_issues_repo_name": "krystophny/GeometricIntegrators.jl", "max_issues_repo_head_hexsha": "7855e977b014c8ba119f6bb73c6ed9bf96f04b1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/interpolation/hermite_interpolation.jl", "max_forks_repo_name": "krystophny/GeometricIntegrators.jl", "max_forks_repo_head_hexsha": "7855e977b014c8ba119f6bb73c6ed9bf96f04b1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0197368421, "max_line_length": 168, "alphanum_fraction": 0.5481668774, "num_tokens": 1687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.952574129515172, "lm_q2_score": 0.8539127566694177, "lm_q1q2_score": 0.8134152008662714}} {"text": "export Resolvent, qresolvent\n\nabstract type MatrixTransformations end\n\n\"\"\"\n```julia\nResolvent(A::Matrix)\n```\n\n- return the resolvent **function** of `A`, ``R(z)= (A-zI)^{-1}``\n\n# Examples\n\nGet the resolvent **function** of a normalized GOE(500).\n\nAnd evaluate the resolvent at `0`\n```julia\nR = Resolvent(rand(GOE(500),norm = true)) # this a function\n\nR(0)\n\n500×500 Matrix{Float64}:\n 0.460903 -0.384016 0.268931 … -0.59029 -0.178288\n -0.384016 0.489355 -0.366855 0.452094 -0.190179\n 0.268931 -0.366855 -0.697169 -0.221433 0.535448\n 0.388846 0.946668 -0.354459 -0.796717 0.207156\n ⋮ ⋱\n -0.532533 0.950826 -0.366618 0.0926931 -0.288692\n -0.0874979 -0.553262 -0.388048 -0.0156897 0.177695\n -0.59029 0.452094 -0.221433 0.9136 0.343194\n -0.178288 -0.190179 0.535448 0.343194 -0.141701\n```\n\"\"\"\nstruct Resolvent<:MatrixTransformations\n M::Matrix\nend\n\n\nfunction (Resolvent::MatrixTransformations)(z)\n (Resolvent.M-UniformScaling(z))^(-1)\nend\n\nfunction Base.show(io::IO, R::Resolvent) \n print(\"Resolvent{Matrix}\")\nend\n\n\"\"\"\n```julia\nqresolvent(A)\n```\nreturns the quaternion resolvent **function** of A.\n\"\"\"\nfunction qresolvent(A::AbstractMatrix)\n return function f(z::Number,η::Number)\n ([UniformScaling(-η) A-UniformScaling(z) \n A'-UniformScaling(z') UniformScaling(-η)])^(-1)\nend\nend", "meta": {"hexsha": "6bab56c5beb3d74b3d01d979e7aed0ee8cab2150", "size": 1412, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Transformations.jl", "max_stars_repo_name": "weiyang2048/RandomMatrix.jl", "max_stars_repo_head_hexsha": "d112a17d928c84583759177849a76eae1942e947", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-04-27T04:28:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T17:21:23.000Z", "max_issues_repo_path": "src/Transformations.jl", "max_issues_repo_name": "weiyang607/RandomMatrix.jl", "max_issues_repo_head_hexsha": "d112a17d928c84583759177849a76eae1942e947", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2021-04-13T02:48:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-19T22:13:44.000Z", "max_forks_repo_path": "src/Transformations.jl", "max_forks_repo_name": "weiyang607/RandomMatrix.jl", "max_forks_repo_head_hexsha": "d112a17d928c84583759177849a76eae1942e947", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3448275862, "max_line_length": 65, "alphanum_fraction": 0.6324362606, "num_tokens": 534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.8791467548438126, "lm_q1q2_score": 0.8134129106366556}} {"text": "################################\n ### Problem Set 0 - ECON 603 ###\n ################################\n\n #Sebastian Melo-Martin\n\n\n# Call some useful packages \nusing Distributions\nusing Random\nusing QuantEcon\nusing Plots\n\n\n############\n# Question 1\n############\n\nfunction tauchen(N::Integer, ρ::T1, σ::T2, μ=zero(promote_type(T1, T2)), n_std::T3=3) where {T1 <: Real, T2 <: Real, T3 <: Real}\n # Discretized space\n a_bar = n_std * sqrt(σ^2 / (1 - ρ^2))\n y = range(-a_bar, stop=a_bar, length=N)\n d = y[2] - y[1]\n\n # Transition probabilities\n Π = zeros(promote_type(T1, T2), N, N)\n for row = 1:N\n # Do end points first\n Π[row, 1] = cdf(Normal(),((y[1] - ρ*y[row] + d/2) / σ))\n Π[row, N] = 1 - cdf(Normal(),((y[N] - ρ*y[row] - d/2) / σ))\n\n # Fill in columns\n for col = 2:N-1\n Π[row, col] = (cdf(Normal(),((y[col] - ρ*y[row] + d/2) / σ)) -\n cdf(Normal(),((y[col] - ρ*y[row] - d/2) / σ)))\n end\n end\n\n return Π, y\n \nend\n\nz = tauchen(3,0.2,0.4)\nprob_tau = z[1]\nybar_tau = @show Vector(z[2])\n\ny_tau = zeros(1000,1)\npos = zeros(1000,1)\ny_tau[1] = ybar_tau[rand(1:3)]\n\nfor i=2:1000\n x=rand()\n for j=1:3\n if y_tau[i-1]==ybar_tau[j]\n pos[i] = j\n end\n end\n prob_row = prob_tau[floor(Int, pos[i]),:]\n thr_1 = prob_row[1]\n thr_2 = thr_1 + prob_row[2]\n if x<=thr_1\n y_tau[i]=ybar_tau[1]\n elseif x>thr_1 && x<=thr_2\n y_tau[i] = ybar_tau[2]\n else\n y_tau[i] = ybar_tau[3]\n end\nend\n\nt = collect(range(1,stop=1000,length=1000))\nplot(t, y_tau)\n\n##############\n# Question 2 #\n##############\n\n#Getting initial vector and probability matrix\nfunction rouwenhorst(N::Integer, ρ::Real, σ::Real, μ::Real)\n\n σ_y = σ / sqrt(1-ρ^2)\n p = (1+ρ)/2\n Θ = [p 1-p; 1-p p]\n ψ = sqrt(N-1) * σ_y\n m = μ / (1 - ρ)\n\n state_values, p = _rouwenhorst(p, p, m, ψ, N)\n\n return p, state_values\nend\n\nfunction _rouwenhorst(p::Real, q::Real, m::Real, Δ::Real, n::Integer)\n if n == 2\n return [m-Δ, m+Δ], [p 1-p; 1-q q]\n else\n _, θ_nm1 = _rouwenhorst(p, q, m, Δ, n-1)\n θN = p *[θ_nm1 zeros(n-1, 1); zeros(1, n)] +\n (1-p)*[zeros(n-1, 1) θ_nm1; zeros(1, n)] +\n q *[zeros(1, n); zeros(n-1, 1) θ_nm1] +\n (1-q)*[zeros(1, n); θ_nm1 zeros(n-1, 1)]\n\n θN[2:end-1, :] ./= 2\n\n return range(m-Δ, stop=m+Δ, length=n), θN\n end\nend\n\nz = rouwenhorst(3,0.2,0.4,0)\nprob_rou = z[1]\nybar_rou = @show Vector(z[2])\n\n#Simulating the time series\ny_rou = zeros(1000,1)\npos = zeros(1000,1)\ny_rou[1] = ybar_rou[rand(1:3)]\n\nfor i=2:1000\n x=rand()\n for j=1:3\n if y_rou[i-1]==ybar_rou[j]\n pos[i] = j\n end\n end\n prob_row = prob_rou[floor(Int, pos[i]),:]\n thr_1 = prob_row[1]\n thr_2 = prob_row[1] + prob_row[2]\n if x<=thr_1\n y_rou[i]=ybar_rou[1]\n elseif x>thr_1 && x<=thr_2\n y_rou[i] = ybar_rou[2]\n else\n y_rou[i] = ybar_rou[3]\n end\nend\n\nt = collect(range(1,stop=1000,length=1000))\nplot(t, y_rou)\n\n##############\n# Question 3 #\n##############\n\nfunction normal_ar(ρ, N)\n d = Normal(0, 0.16)\n y = [0.0 for i = 1:N]\n Random.seed!(641993)\n ϵ = rand(d, N)\n for i in 1:(N-1)\n y[i+1] = ρ*y[i] + ϵ[i] \n end\n return y\nend\n\nρ=0.2\nN=1000\ny_ar = normal_ar(ρ,N)\nt = collect(range(1,stop=1000,length=1000))\n\nplot(t, y_ar)\n\n\n##############\n# Question 4 #\n##############\n\n# Tauchen\nz = tauchen(10,0.2,0.4)\nprob_tau = z[1]\nybar_tau = @show Vector(z[2])\n\ny_tau = zeros(1000,1)\npos = zeros(1000,1)\ny_tau[1] = ybar_tau[rand(1:10)]\n\nfor i=2:1000\n x=rand()\n for j=1:10\n if y_tau[i-1]==ybar_tau[j]\n pos[i] = j\n end\n end\n prob_row = prob_tau[floor(Int, pos[i]),:]\n thr_1 = prob_row[1]\n thr_2 = thr_1 + prob_row[2]\n thr_3 = thr_2 + prob_row[3]\n thr_4 = thr_3 + prob_row[4]\n thr_5 = thr_4 + prob_row[5]\n thr_6 = thr_5 + prob_row[6]\n thr_7 = thr_6 + prob_row[7]\n thr_8 = thr_7 + prob_row[8]\n thr_9 = thr_8 + prob_row[9]\n if x<=thr_1\n y_tau[i]=ybar_tau[1]\n elseif x>thr_1 && x<=thr_2\n y_tau[i] = ybar_tau[2]\n elseif x>thr_2 && x<=thr_3\n y_tau[i] = ybar_tau[3]\n elseif x>thr_3 && x<=thr_4\n y_tau[i] = ybar_tau[4]\n elseif x>thr_4 && x<=thr_5\n y_tau[i] = ybar_tau[5]\n elseif x>thr_5 && x<=thr_6\n y_tau[i] = ybar_tau[6]\n elseif x>thr_6 && x<=thr_7\n y_tau[i] = ybar_tau[7]\n elseif x>thr_7 && x<=thr_8\n y_tau[i] = ybar_tau[8]\n elseif x>thr_8 && x<=thr_9\n y_tau[i] = ybar_tau[9]\n else\n y_tau[i] = ybar_tau[10]\n end\nend\n\nt = collect(range(1,stop=1000,length=1000))\nplot(t, y_tau)\n\n# Rouwenhorst\nz = rouwenhorst(10,0.2,0.4,0)\nprob_rou = z[1]\nybar_rou = @show Vector(z[2])\n\ny_rou = zeros(1000,1)\npos = zeros(1000,1)\ny_rou[1] = ybar_tau[rand(1:10)]\n\nfor i=2:1000\n x=rand()\n for j=1:10\n if y_rou[i-1]==ybar_rou[j]\n pos[i] = j\n end\n end\n prob_row = prob_rou[floor(Int, pos[i]),:]\n thr_1 = prob_row[1]\n thr_2 = thr_1 + prob_row[2]\n thr_3 = thr_2 + prob_row[3]\n thr_4 = thr_3 + prob_row[4]\n thr_5 = thr_4 + prob_row[5]\n thr_6 = thr_5 + prob_row[6]\n thr_7 = thr_6 + prob_row[7]\n thr_8 = thr_7 + prob_row[8]\n thr_9 = thr_8 + prob_row[9]\n if x<=thr_1\n y_rou[i]=ybar_rou[1]\n elseif x>thr_1 && x<=thr_2\n y_rou[i] = ybar_rou[2]\n elseif x>thr_2 && x<=thr_3\n y_rou[i] = ybar_rou[3]\n elseif x>thr_3 && x<=thr_4\n y_rou[i] = ybar_rou[4]\n elseif x>thr_4 && x<=thr_5\n y_rou[i] = ybar_rou[5]\n elseif x>thr_5 && x<=thr_6\n y_rou[i] = ybar_rou[6]\n elseif x>thr_6 && x<=thr_7\n y_rou[i] = ybar_rou[7]\n elseif x>thr_7 && x<=thr_8\n y_rou[i] = ybar_rou[8]\n elseif x>thr_8 && x<=thr_9\n y_rou[i] = ybar_rou[9]\n else\n y_rou[i] = ybar_rou[10]\n end\nend\n\nt = collect(range(1,stop=1000,length=1000))\nplot(t, y_rou)\n\n\n##############\n# Question 5 #\n##############\n\n#= The coding for this question is already included previously in a loop\n =#\n", "meta": {"hexsha": "a09b61a575fa429a6c4978e735507d8913d17ad1", "size": 6245, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "PS_0_first_version.jl", "max_stars_repo_name": "sebaschoo/Second_Term_PS", "max_stars_repo_head_hexsha": "21bc623a99bf60929bf46d07a662cc120e6d6d38", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PS_0_first_version.jl", "max_issues_repo_name": "sebaschoo/Second_Term_PS", "max_issues_repo_head_hexsha": "21bc623a99bf60929bf46d07a662cc120e6d6d38", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PS_0_first_version.jl", "max_forks_repo_name": "sebaschoo/Second_Term_PS", "max_forks_repo_head_hexsha": "21bc623a99bf60929bf46d07a662cc120e6d6d38", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6268115942, "max_line_length": 128, "alphanum_fraction": 0.514011209, "num_tokens": 2476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109812297141, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.8134103248813424}} {"text": "\"\"\"\n**Adagrad constructor**\n\n```julia\n Adagrad(; η::Real=0.01, ϵ::Real=1e-8)\n```\n\nAlgorithm :\n\n```math\n\\\\begin{align*}\nG_t =& g_t^2\\\\\\\\\n\\\\Delta x_t =& \\\\frac{\\\\eta}{\\\\sqrt{G_t+ϵ}} g_t\n\\\\end{align*}\n```\n\n[Algorithm Reference](http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf)\n\"\"\"\nmutable struct Adagrad <: Optimizer\n opt_type::String\n t::Int64\n ϵ::Float64\n η::Float64\n G_t::AbstractArray\nend\n\n\nfunction Adagrad(; η::Real=0.01, ϵ::Real=1e-8)\n @assert η > 0.0 \"η must be greater than 0\"\n @assert ϵ > 0.0 \"ϵ must be greater than 0\"\n\n Adagrad(\"Adagrad\", 0, ϵ, η, [])\nend\n\nparams(opt::Adagrad) = \"ϵ=$(opt.ϵ), η=$(opt.η)\"\n\nfunction update(opt::Adagrad, g_t::AbstractArray{T}) where {T<:Real}\n # resize squares of gradients\n if opt.t == 0\n opt.G_t = zero(g_t)\n end\n\n # update timestep\n opt.t += 1\n\n # accumulate squares of gradients\n opt.G_t .+= (g_t .^ 2)\n\n δ = opt.η ./ (sqrt.(opt.G_t .+ opt.ϵ)) .* g_t\n\n return δ\nend\n", "meta": {"hexsha": "d72b4e60cfd983a88f807156039e17ea7fc738d3", "size": 983, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/AdaGradOptimizer.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/GradDescent.jl-e1397348-e965-55d8-8fb3-3dd9faf6e4f1", "max_stars_repo_head_hexsha": "a3b2c35983a3cf5c88e1f3bb0df4f43bbacb44c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2017-08-20T00:43:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-12T03:09:32.000Z", "max_issues_repo_path": "src/AdaGradOptimizer.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/GradDescent.jl-e1397348-e965-55d8-8fb3-3dd9faf6e4f1", "max_issues_repo_head_hexsha": "a3b2c35983a3cf5c88e1f3bb0df4f43bbacb44c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-11-19T22:38:05.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-25T20:33:14.000Z", "max_forks_repo_path": "src/AdaGradOptimizer.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/GradDescent.jl-e1397348-e965-55d8-8fb3-3dd9faf6e4f1", "max_forks_repo_head_hexsha": "a3b2c35983a3cf5c88e1f3bb0df4f43bbacb44c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-08-03T16:14:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:48:41.000Z", "avg_line_length": 18.5471698113, "max_line_length": 80, "alphanum_fraction": 0.5890132248, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109812297141, "lm_q2_score": 0.8558511396138365, "lm_q1q2_score": 0.8134103213869555}} {"text": "#=\nThis is an implementation of the \"Babylonian method\" of approximating square roots.\n(https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)\n=#\nconst steps = 10\nconst example = 20740\n\nfunction sqrt(s)\n x = s/2 # arbitrary initial guess for x ≈ √s\n for i in 1:steps\n x = (x + s/x)/2\n end\n x\nend\n\nprintln(\"√$example ≈ $(sqrt(example)), error = $(abs(sqrt(example)) - (example)^0.5)\")\n", "meta": {"hexsha": "02a85214bd0bf77433ecdddc0fb4324ef0241f5d", "size": 431, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "algorithms/math/babyloniansqrt.jl", "max_stars_repo_name": "landrumb/julia", "max_stars_repo_head_hexsha": "b57d478825c4bea8d0780efab80b7cbe32f3ea45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26, "max_stars_repo_stars_event_min_datetime": "2018-10-08T05:29:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-21T09:27:27.000Z", "max_issues_repo_path": "algorithms/math/babyloniansqrt.jl", "max_issues_repo_name": "landrumb/julia", "max_issues_repo_head_hexsha": "b57d478825c4bea8d0780efab80b7cbe32f3ea45", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2018-10-08T05:44:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-20T15:33:02.000Z", "max_forks_repo_path": "algorithms/math/babyloniansqrt.jl", "max_forks_repo_name": "landrumb/julia", "max_forks_repo_head_hexsha": "b57d478825c4bea8d0780efab80b7cbe32f3ea45", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-10-26T18:07:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-21T09:27:30.000Z", "avg_line_length": 25.3529411765, "max_line_length": 86, "alphanum_fraction": 0.6728538283, "num_tokens": 136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9615338112885303, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.8134022596105165}} {"text": "include(\"../utils/format/Heading.jl\")\n\n\n# float32/64\nfloat_64= 1e-2\nfloat_32= 1f-2\nprintln(typeof(float_64), \" \", typeof(float_32))\n#: Float64 Float32\n\n\n# underscore as digit separator\nprintln(100_000, \" \", 0.00_00_5)\n#: 100000 5.0e-5\n\n\n# flotiing point has two zeros - positive and negative\n# both are `=` same but `bitstring` different \nprintln(0.0 == -0.0)\n#: true\nprintln(bitstring(0.0) == bitstring(-0.0))\n#: false\n\n\nHeading.main(\"Special floating point values\")\n\n\nprintln(-5/0)\nprintln(-5/Inf)\n#: -Inf\n#: -0.0\n\n\nprintln(Inf+500)\n#: Inf\n\n\n# as Inf+x (or) Inf-x (or) Inf + Inf all equal to Inf\n# Information is lost. So, Inf - Inf cannot be exactly 0 \nprintln(Inf - Inf)\n#: NaN \n\n\n\n# epsilon: distance between 1.0 and the next larger \n# representable floating-point value i.e smallest distance \n# possible from 1.0\nprintln(eps(Float16))\nprintln(eps(Float32))\nprintln(eps(Float64))\nprintln(eps()) # same as 64\n#: 0.000977\n#: 1.1920929e-7\n#: 2.220446049250313e-16\n#: 2.220446049250313e-16\n\n\nprintln(typemax(BigFloat))\n#: Inf", "meta": {"hexsha": "e44fab0f972316af538cdf295a0bd9a873596e2d", "size": 1026, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "02-Data-Types/02-01-float.jl", "max_stars_repo_name": "rakesh4real/master-julia", "max_stars_repo_head_hexsha": "b7677184296201e29e90bc768385747c82072cf1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "02-Data-Types/02-01-float.jl", "max_issues_repo_name": "rakesh4real/master-julia", "max_issues_repo_head_hexsha": "b7677184296201e29e90bc768385747c82072cf1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "02-Data-Types/02-01-float.jl", "max_forks_repo_name": "rakesh4real/master-julia", "max_forks_repo_head_hexsha": "b7677184296201e29e90bc768385747c82072cf1", "max_forks_repo_licenses": ["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.6896551724, "max_line_length": 59, "alphanum_fraction": 0.6910331384, "num_tokens": 346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505248181418, "lm_q2_score": 0.8991213820004279, "lm_q1q2_score": 0.8133906301019}} {"text": "function bisection(f::Function, xl::Number, xu::Number, ea::Number, maxIter::Int64)\n # Estimate roots of functions using the bisection method\n xr = NaN;\n fxl = f(xl);\n\n for i = 1:maxIter\n xrlast = xr;\n xr = 0.5(xl+xu);\n fxr = f(xr);\n relativeError = abs((xr - xrlast) / 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 end\n\n if relativeError < ea\n break;\n end\n end\n\n return xr;\nend\n", "meta": {"hexsha": "fd351d9d23a8082e39d752a1f657d4e232515ec0", "size": 493, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/Root Estimation/bisection.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/bisection.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/bisection.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": 17.6071428571, "max_line_length": 83, "alphanum_fraction": 0.5476673428, "num_tokens": 177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9381240142763573, "lm_q2_score": 0.8670357494949105, "lm_q1q2_score": 0.8133870578372755}} {"text": "using SpecialFunctions, Distributions\n\na,b = 0.2, 0.7\nx = 0.75\n\nbetaAB1 = beta(a,b)\nbetaAB2 = (gamma(a)gamma(b))/gamma(a+b)\nbetaAB3 = (factorial(a-1)factorial(b-1))/factorial(a+b-1)\nbetaPDFAB1 = pdf(Beta(a,b),x)\nbetaPDFAB2 = (1/beta(a,b))*x^(a-1) * (1-x)^(b-1)\n\nprintln(\"beta($a,$b) = $betaAB1,\\t$betaAB2,\\t$betaAB3 \")\nprintln(\"betaPDF($a,$b) at $x = $betaPDFAB1,\\t$betaPDFAB2\")", "meta": {"hexsha": "ebcc436c9d839b6330161cd4cb3b859bd2b7c707", "size": 381, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "3_chapter/betaDist.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "3_chapter/betaDist.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "3_chapter/betaDist.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.3076923077, "max_line_length": 59, "alphanum_fraction": 0.6404199475, "num_tokens": 168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9591542887603536, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.8133319103360265}} {"text": "\"\"\"\n frct(signal, α, p)\n\nComputing the α order fractional cosine transform of the input **signal**.\n\n# Example\n\n```julia-repl\njulia> frct([1,2,3], 0.5, 2)\n3-element Vector{ComplexF64}:\n1.707106781186547 + 0.9874368670764581im\n1.5606601717798205 - 1.3964466094067267im\n-0.3535533905932727 - 0.6982233047033652im\n```\n\n### References\n\n```tex\n@article{article,\nauthor = {Pei, Soo-Chang and Yeh, Min-Hung},\nyear = {2001},\nmonth = {07},\npages = {1198 - 1207},\ntitle = {The discrete fractional cosine and sine transforms},\nvolume = {49},\njournal = {Signal Processing, IEEE Transactions on},\ndoi = {10.1109/78.923302}\n}\n```\n\"\"\"\nfunction frct(signal, α, p)\n N = length(signal)\n @views signal = signal[:]\n p = min(max(2, p), N-1)\n E = dFRCT(N,p)\n result = E *(exp.(-im*pi*α*collect(0:N-1)) .*(E' *signal))\n return result\nend\n\nfunction dFRCT(N, p)\n N1 = 2*N-2\n d2 = [1, -2, 1]\n\n d_p = 1\n s = 0\n st = zeros(1, N1)\n\n for k = 1:floor(Int, p/2)\n if typeof(d_p) <: Number\n d_p = @. d2*d_p\n else\n d_p = conv(d2, d_p)\n end\n st[vcat(collect(N1-k+1:N1), collect(1:k+1))] = d_p\n st[1] = 0\n temp = vcat(union(1, collect(1:k-1)), union(1,collect(1:k-1)))\n temp = temp[:] ./collect(1:2*k)\n s = s.+(-1)^(k-1)*prod(temp)*2*st\n end\n\n H = Toeplitz(s[:], s[:]) + diagm(real.(fft(s[:])))\n\n V = hcat(zeros(N-2), zeros(N-2, N-2)+I, zeros(N-2), reverse(zeros(N-2, N-2)+I, dims=1)) ./sqrt(2)\n V = vcat([1 zeros(1, N1-1)], V, [zeros(1, N-1) 1 zeros(1, N-2)])\n\n Ev = V*H*V'\n\n _, ee = eigen(Ev)\n\n E = reverse(ee, dims=2)\n E[end,:] = E[end,:]/sqrt(2)\n return E\nend", "meta": {"hexsha": "58d877bf9f54f33fd4218b71a8ce592bf6b9e117", "size": 1670, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/frct.jl", "max_stars_repo_name": "SciFracX/FractionalTransforms.jl", "max_stars_repo_head_hexsha": "f343419db8e79a3f08ae1d95faae5495f877317b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-11-07T22:00:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T00:49:40.000Z", "max_issues_repo_path": "src/frct.jl", "max_issues_repo_name": "SciFracX/FractionalTransforms.jl", "max_issues_repo_head_hexsha": "f343419db8e79a3f08ae1d95faae5495f877317b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-11-16T15:53:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-10T06:08:16.000Z", "max_forks_repo_path": "src/frct.jl", "max_forks_repo_name": "SciFracX/FractionalTransforms.jl", "max_forks_repo_head_hexsha": "f343419db8e79a3f08ae1d95faae5495f877317b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-08T12:06:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-08T12:06:40.000Z", "avg_line_length": 22.8767123288, "max_line_length": 101, "alphanum_fraction": 0.5556886228, "num_tokens": 653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154281754899, "lm_q2_score": 0.8479677622198946, "lm_q1q2_score": 0.8133319099233319}} {"text": "export rosenbrock, rastrigin\n\n\"\"\"\nThe rastrigin function is notorious for having multiple local minima and only one global optima at (0,0)\n\n\"\"\"\nfunction rastrigin(x::Vector{T}) where {T <: AbstractFloat}\n a = one(eltype(x)) * 10\n return size(x, 1) * a + sum(@. x^2 - a * cos(2 * π * x))\nend\n\nfunction rosenbrock(x::Vector{T}) where {T <: AbstractFloat}\n f = zero(eltype(x))\n a = one(eltype(x))\n b = 100 * a\n for i in 1:(length(x) - 1)\n @inbounds f += b * (x[i + 1] - x[i]^2)^2 + (a - x[i])^2\n end\n return f\nend\n", "meta": {"hexsha": "50fe5f26c2850e4b47778e4e242d34d5d0767006", "size": 541, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lossfunction.jl", "max_stars_repo_name": "Pramodh-G/VisualOptim.jl", "max_stars_repo_head_hexsha": "e0923e8acc8f91465d61bc75abecc520fc79fd8c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-24T09:27:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-24T10:54:20.000Z", "max_issues_repo_path": "src/lossfunction.jl", "max_issues_repo_name": "Pramodh-G/VisualOptim.jl", "max_issues_repo_head_hexsha": "e0923e8acc8f91465d61bc75abecc520fc79fd8c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lossfunction.jl", "max_forks_repo_name": "Pramodh-G/VisualOptim.jl", "max_forks_repo_head_hexsha": "e0923e8acc8f91465d61bc75abecc520fc79fd8c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7619047619, "max_line_length": 104, "alphanum_fraction": 0.5859519409, "num_tokens": 191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154287592778, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.81333190934596}} {"text": "\nusing JuMP\nusing GLPK\n\n\nG = [\n0 100 30 0 0;\n0 0 20 0 0; \n0 0 0 10 60;\n0 15 0 0 50;\n0 0 0 0 0\n]\n\nn = size(G)[1]\n\nshortest_path = Model(with_optimizer(GLPK.Optimizer))\n\n@variable(shortest_path, x[1:n,1:n], Bin)\n@constraint(shortest_path, [i = 1:n, j = 1:n; G[i,j] == 0], x[i,j] == 0) # Arcs with zero cost are not a part of the path as they do no exist\n@constraint(shortest_path, [i = 1:n; i != 1 && i != 2], sum(x[i,:]) == sum(x[:,i])) # Flow conservation constraint\n@constraint(shortest_path, sum(x[1,:]) - sum(x[:,1]) == 1) # Flow coming out of source = 1\n@constraint(shortest_path, sum(x[2,:]) - sum(x[:,2]) == -1) # Flowing coming out of destination = -1 i.e. Flow entering destination = 1 \n@objective(shortest_path, Min, sum(G .* x))\n\noptimize!(shortest_path)\n@show objective_value(shortest_path);\n@show value.(x);\n\n\nG = [\n6 4 5 0;\n0 3 6 0;\n5 0 4 3;\n7 5 5 5;\n]\n\nn = size(G)[1]\n\nassignment = Model(with_optimizer(GLPK.Optimizer))\n@variable(assignment, y[1:n,1:n], Bin)\n@constraint(assignment, [i = 1:n], sum(y[:,i]) == 1) # One person can only be assigned to one object\n@constraint(assignment, [j = 1:n], sum(y[j,:]) == 1) # One object can only be assigned to one person\n@objective(assignment, Max, sum(G .* y))\n\noptimize!(assignment)\n@show objective_value(assignment);\n@show value.(y);\n\n\nG = [\n0 3 2 2 0 0 0 0 \n0 0 0 0 5 1 0 0 \n0 0 0 0 1 3 1 0 \n0 0 0 0 0 1 0 0 \n0 0 0 0 0 0 0 4 \n0 0 0 0 0 0 0 2 \n0 0 0 0 0 0 0 4 \n0 0 0 0 0 0 0 0 \n]\n\nn = size(G)[1]\n\nmax_flow = Model(with_optimizer(GLPK.Optimizer))\n\n@variable(max_flow, f[1:n,1:n] >= 0)\n@constraint(max_flow, [i = 1:n, j = 1:n], f[i,j] <= G[i,j]) # Capacity constraints\n@constraint(max_flow, [i = 1:n; i != 1 && i != 8], sum(f[i,:]) == sum(f[:,i])) # Flow conservation contraints\n@objective(max_flow, Max, sum(f[1, :]))\n\noptimize!(max_flow)\n@show objective_value(max_flow);\n@show value.(f);\n\n", "meta": {"hexsha": "c3d3c07cc2842eec2ec51c7dbe372e16b42e872c", "size": 1865, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/modelling/network_flows.jl", "max_stars_repo_name": "carlosal1015/JuMPTutorials.jl", "max_stars_repo_head_hexsha": "4d9a86ea310ecc7a22de7f14b783dbd218e4b612", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/modelling/network_flows.jl", "max_issues_repo_name": "carlosal1015/JuMPTutorials.jl", "max_issues_repo_head_hexsha": "4d9a86ea310ecc7a22de7f14b783dbd218e4b612", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/modelling/network_flows.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": 25.2027027027, "max_line_length": 141, "alphanum_fraction": 0.6198391421, "num_tokens": 741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542817548989, "lm_q2_score": 0.8479677602988601, "lm_q1q2_score": 0.8133319080807635}} {"text": "@doc raw\"\"\"\n# Lotka-Volterra Model in 3D\n\nThe Lotka–Volterra model in 3D is an example of a Hamiltonian system with degenerate Poisson structure.\n\nThe equations read\n```math\n\\begin{aligned}\n\\dot{q}_{1} &= q_{1} ( - a_{2} q_{2} + a_{3} q_{3} - b_{2} + b_{3} ) , \\\\\n\\dot{q}_{2} &= q_{2} ( \\hphantom{-} a_{1} q_{1} - a_{3} q_{3} + b_{1} - b_{3} ) , \\\\\n\\dot{q}_{3} &= q_{3} ( - a_{1} q_{1} + a_{2} q_{2} - b_{1} + b_{2} ) , \\\\\n\\end{aligned}\n```\nwhich can be written in Poisson-form as\n```math\n\\dot{q} = P(q) \\nabla H(q) ,\n```\nwith Poisson matrix\n```math\nP(q) = \\begin{pmatrix}\n 0 & - q_{1} q_{2} & \\hphantom{-} q_{1} q_{3} \\\\\n\\hphantom{-} q_{1} q_{2} & 0 & - q_{2} q_{3} \\\\\n- q_{1} q_{3} & \\hphantom{-} q_{2} q_{3} & 0 \\\\\n\\end{pmatrix} ,\n```\nand Hamiltonian\n```math\nH(q) = a_{1} q_{1} + a_{2} q_{2} + a_{3} q_{3} + b_{1} \\ln q_{1} + b_{2} \\ln q_{2} + b_{3} \\ln q_{3} .\n```\n\nReferences:\n* A. M. Perelomov. Selected topics on classical integrable systems,\n Troisième cycle de la physique, expanded version of lectures\n delivered in May 1995.\n\n* Yuri B. Suris. Integrable discretizations for lattice systems: local\n equations of motion and their Hamiltonian properties,\n Rev. Math. Phys. 11, pp. 727–822, 1999.\n\"\"\"\nmodule LotkaVolterra3d\n\n using GeometricBase\n using GeometricEquations\n\n export lotka_volterra_3d_ode\n\n export hamiltonian, casimir\n export compute_energy_error, compute_casimir_error\n\n\n Δt = 0.01\n nt = 1000\n\n const A1=+1.0\n const A2=+1.0\n const A3=+1.0\n\n const B1= 0.0\n const B2=+1.0\n const B3=+1.0\n\n const X0=1.0\n const Y0=1.0\n const Z0=2.0\n\n\n function v₁(t, q)\n q[1] * ( - A2 * q[2] + A3 * q[3] + B2 - B3)\n end\n\n function v₂(t, q)\n q[2] * ( + A1 * q[1] - A3 * q[3] - B1 + B3)\n end\n\n function v₃(t, q)\n q[3] * ( - A1 * q[1] + A2 * q[2] + B1 - B2)\n end\n\n\n const q₀=[X0, Y0, Z0]\n const v₀=[v₁(0, q₀), v₂(0, q₀), v₃(0, q₀)]\n\n\n function hamiltonian(t, q)\n A1*q[1] + A2*q[2] + A3*q[3] - B1*log(q[1]) - B2*log(q[2]) - B3*log(q[3])\n end\n\n hamiltonian_iode(t, q, v) = hamiltonian(t, q)\n\n function casimir(t, q)\n log(q[1]) + log(q[2]) + log(q[3])\n end\n\n\n function lotka_volterra_3d_v(t, q, v)\n v[1] = v₁(t, q)\n v[2] = v₂(t, q)\n v[3] = v₃(t, q)\n nothing\n end\n\n\n function lotka_volterra_3d_ode(q₀=q₀)\n ODE(lotka_volterra_3d_v, q₀; invariants=(h=hamiltonian,))\n end\n\n\n function compute_energy_error(t, q::AbstractDataSeries{<:AbstractVector{T}}) where {T}\n h = DataSeries(T, ntime(q))\n e = DataSeries(T, ntime(q))\n\n for i in axes(q,1)\n h[i] = hamiltonian(t[i], q[i])\n e[i] = (h[i] - h[0]) / h[0]\n end\n\n (h, e)\n end\n\n function compute_casimir_error(t, q::AbstractDataSeries{<:AbstractVector{T}}) where {T}\n c = DataSeries(T, ntime(q))\n e = DataSeries(T, ntime(q))\n\n for i in axes(q,1)\n c[i] = casimir(t[i], q[i])\n e[i] = (c[i] - c[0]) / c[0]\n end\n\n (c, e)\n end\n\nend\n", "meta": {"hexsha": "900a376c6ab349e49086eada05a28a21719d8d40", "size": 3119, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lotka_volterra_3d.jl", "max_stars_repo_name": "DDMGNI/GeometricProblems.jl", "max_stars_repo_head_hexsha": "367f4cf63ff614c3051c7760b835889fdb7a040f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lotka_volterra_3d.jl", "max_issues_repo_name": "DDMGNI/GeometricProblems.jl", "max_issues_repo_head_hexsha": "367f4cf63ff614c3051c7760b835889fdb7a040f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-02-11T01:23:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-24T11:06:23.000Z", "max_forks_repo_path": "src/lotka_volterra_3d.jl", "max_forks_repo_name": "DDMGNI/GeometricProblems.jl", "max_forks_repo_head_hexsha": "367f4cf63ff614c3051c7760b835889fdb7a040f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4511278195, "max_line_length": 103, "alphanum_fraction": 0.5328630971, "num_tokens": 1250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474207360066, "lm_q2_score": 0.8519528000888386, "lm_q1q2_score": 0.8133145431936284}} {"text": "\"\"\"\r\n basis = basis_rotation(Ω, i, ω)\r\n basis = basis_rotation(xvec, yvec)\r\n basis_rotation() = one(RotMatrix{3, Float64})\r\n\r\nFrom the RAAN `Ω`, inclination `i`, and argument of the periapsis `ω`, computes the rotation matrix that transforms \r\nan orbit's perifocal plane to the inertial frame. For this matrix, the first column is a unit vector that points toward \r\nthe periapsis of the orbit, and the third column is a unit vector that points in the normal direction. \r\n\r\nIf two vectors `xvec` and `yvec` are provided, a rotation matrix is constructed that describes the plane the two vectors\r\ndefine, where `normalize(xvec)` is the first basis vector.\r\n\"\"\"\r\nfunction basis_rotation(Ω, i, ω)\r\n # Ω, ω, i = Float64(Ω), Float64(ω), Float64(i)\r\n # R₁ = [cos(Ω) -sin(Ω) 0.; # rotate around z-axis to match Ω\r\n # sin(Ω) cos(Ω) 0.;\r\n # 0. 0. 1.]\r\n # R₂ = [1. 0. 0.; # rotate around x-axis to match i\r\n # 0. cos(i) -sin(i);\r\n # 0. sin(i) cos(i)]\r\n # R₃ = [cos(ω) -sin(ω) 0.; # rotate around z-axis to match ω\r\n # sin(ω) cos(ω) 0.;\r\n # 0. 0. 1.]\r\n # return R₃*R₂*R₁\r\n return RotZXZ(Ω, i, ω)\r\nend\r\n\r\nfunction basis_rotation(xvec::AbstractVector{<:Real}, yvec::AbstractVector{<:Real})\r\n @assert length(xvec) == length(yvec) == 3\r\n xbasisvec = normalize(xvec)\r\n ybasisvec = normalize(yvec - xbasisvec .* dot(xbasisvec, yvec))\r\n zbasisvec = cross(xbasisvec, ybasisvec)\r\n return RotMatrix(hcat(xbasisvec,ybasisvec,zbasisvec))\r\nend\r\n\r\nbasis_rotation() = one(RotMatrix{3, Float64})\r\n\r\n# methods for switching orbital reference frames\r\n\r\n\"\"\"\r\n pvec = inertial_to_perifocal_bases(vec, basis)\r\n pvec = inertial_to_perifocal_bases(vec, orb)\r\n\r\nTransforms a vector `vec` from the inertial frame to an orbit's perifocal frame,\r\ndefined by `basis`.\r\n\"\"\"\r\ninertial_to_perifocal_bases(vec::AbstractVector{<:Real}, basis::Rotation{3,Float64}) = basis\\vec\r\ninertial_to_perifocal_bases(vec::AbstractVector{<:Real}, orb::Orbit) = inertial_to_perifocal_bases(vec, orb.basis)\r\n\r\n\"\"\"\r\n ivec = perifocal_to_inertial_bases(vec, basis)\r\n ivec = perifocal_to_inertial_bases(vec, orb)\r\n\r\nTransforms a vector `vec` from an orbit's perifocal frame, defined by `basis`, \r\nto the inertial frame.\r\n\"\"\"\r\nperifocal_to_inertial_bases(vec::AbstractVector{<:Real}, basis::Rotation{3,Float64}) = basis*vec\r\nperifocal_to_inertial_bases(vec::AbstractVector{<:Real}, orb::Orbit) = perifocal_to_inertial_bases(vec, orb.basis)\r\n\r\n\"\"\"\r\n rotmat = align_vectors(vec, vecref)\r\n\r\nComputes the rotation matrix to align `vec` with `vecref`.\r\n\"\"\"\r\nfunction align_vectors(vec::AbstractVector{<:Real}, vecref::AbstractVector{<:Real})\r\n nvec, nvecref = normalize(vec), normalize(vecref)\r\n axis = normalize(cross(nvec, nvecref))\r\n angle = wrap_acos(dot(nvec, nvecref))\r\n if angle == 0\r\n return one(RotMatrix{3, Float64})\r\n end\r\n return AngleAxis(angle, axis...)\r\nend\r\n", "meta": {"hexsha": "5230432c9c1e2796e63eb0867e9ee5c6ee864253", "size": 2989, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/basis.jl", "max_stars_repo_name": "tmcgrath325/KeplerTools.jl", "max_stars_repo_head_hexsha": "bb95d6c24ca7e1cea6f7f8057f01a415f5719f6e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/basis.jl", "max_issues_repo_name": "tmcgrath325/KeplerTools.jl", "max_issues_repo_head_hexsha": "bb95d6c24ca7e1cea6f7f8057f01a415f5719f6e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-19T16:28:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-19T16:28:17.000Z", "max_forks_repo_path": "src/basis.jl", "max_forks_repo_name": "tmcgrath325/KeplerTools.jl", "max_forks_repo_head_hexsha": "bb95d6c24ca7e1cea6f7f8057f01a415f5719f6e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.3918918919, "max_line_length": 121, "alphanum_fraction": 0.6634325861, "num_tokens": 923, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545289551958, "lm_q2_score": 0.8577681013541613, "lm_q1q2_score": 0.8132967100922475}} {"text": "module Searching \n\nexport binarysearch, BinarySearchTree, BinaryNode, delete!\nexport size, get, maximum, minimum\n\n# Binary search \nstruct UnsortedException <: Exception end\nBase.showerror(io::IO, e::UnsortedException) = print(io, \"input vecotr v is not sorted\")\n\nmidpoint(lo::Integer, hi::Integer) = lo + div(hi - lo, 2)\n\nfunction binarysearch(key, v::AbstractVector; algo=:recursive)\n issorted(v) || throw(UnsortedException())\n lo, hi = 1, length(v)\n if algo == :recursive\n binarysearch_rec(key, v, lo, hi)\n elseif algo == :iterative\n binarysearch_iter(key, v, lo, hi)\n end\nend\n\nfunction binarysearch_rec(key, v::AbstractVector, lo::Integer, hi::Integer)\n i, j = lo, hi\n if i <= j\n mid = midpoint(i, j)\n if key < v[mid] \n binarysearch_rec(key, v, i, mid-1)\n elseif key > v[mid]\n binarysearch_rec(key, v, mid+1, j)\n else\n return mid\n end\n else\n return -1\n end\nend\n\nfunction binarysearch_iter(key, v::AbstractVector, lo::Integer, hi::Integer)\n i, j = lo, hi\n while i <= j\n mid = midpoint(i, j) \n if key < v[mid]\n j = mid - 1\n elseif key > v[mid]\n i = mid + 1\n else\n return mid\n end\n end\n return -1\nend\n\n# Binary search tree\n\nmutable struct BinaryNode{T} \n val::T\n numnodes::Int\n left::Union{BinaryNode{T}, Nothing}\n right::Union{BinaryNode{T}, Nothing}\n\n # root constructor\n BinaryNode(val::T) where T = new{T}(val, 1, nothing, nothing)\nend\n\nabstract type SearchTree end\n\n\"\"\"\nBinary search tree.\n\"\"\"\nstruct BinarySearchTree{T} <: SearchTree \n root::BinaryNode{T}\nend\n\nfunction BinarySearchTree(v::AbstractVector)\n !isempty(v) || error(\"empty vector\")\n \n bst = BinarySearchTree(BinaryNode(v[1]))\n for val in v[2:end]\n put!(bst, val)\n end\n\n return bst\nend\n\nSearching.size(::Nothing) = 0\nSearching.size(node::BinaryNode{T}) where T = node.numnodes\nSearching.size(tree::BinarySearchTree{T}) where T = Searching.size(tree.root)\n\nfunction updatesize!(node)\n node.numnodes = Searching.size(node.left) + Searching.size(node.right) + 1\n nothing\nend\n\n\"\"\"\n put!(tree, val)\n\nInsert a value into the binary search tree.\n\n put!(node, val)\n\nInsert a value following the node.\n\"\"\"\nfunction put!(node::BinaryNode{T}, val::T) where T\n if val < node.val\n node.left = put!(node.left, val)\n elseif val > node.val \n node.right = put!(node.right, val)\n else\n node.val = val\n end\n updatesize!(node)\n return node\nend\n\nput!(tree::BinarySearchTree{T}, val::T) where T = BinarySearchTree(put!(tree.root, val))\nput!(::Nothing, val) = BinaryNode(val)\n\n\"\"\"\n get(node, val)\n\nSearch for the node by value. Return `nothing` if not found.\n\"\"\"\nfunction get(node::BinaryNode, val)\n if val < node.val\n return get(node.left, val)\n elseif val > node.val\n return get(node.right, val)\n else\n return node\n end\nend\n\nget(tree::BinarySearchTree, val) = get(tree.root, val)\nget(::Nothing, val)= nothing\n\n\"\"\"\n maximum(BinarySearchTree)\n\nReturn node with maximum value.\n\"\"\"\nfunction maximum(node) \n isnothing(node) && return nothing\n\n while !isnothing(node.right)\n node = node.right\n end\n\n return node\nend\n\nmaximum(tree::BinarySearchTree) = maximum(tree.root)\n\nfunction minimum(node)\n isnothing(node) && return nothing\n\n while !isnothing(node.left)\n node = node.left\n end\n\n return node\nend\n\nminimum(tree::BinarySearchTree) = minimum(tree.root)\n\n\"\"\"\n rank(node, val)\n\nFind the rank for value `val`: number of nodes with values less \nthan `val` + 1.\n\"\"\"\nfunction rank(node::BinaryNode, val)\n if val < node.val\n valrank = rank(node.left, val)\n elseif val > node.val\n valrank = rank(node.right, val) + Searching.size(node.left) + 1\n else\n valrank = Searching.size(node.left)\n end\n\n return valrank\nend\n\nrank(::Nothing, val) = 0\nrank(tree::BinarySearchTree, val) = rank(tree.root, val) + 1\n\n\"\"\"\n select(node, rankval)\n\nSelect the node with ranking `rankval`. \nWe assume rankval is in range between 1 to the size of the tree.\n\"\"\"\nfunction select(node::BinaryNode, valrank)\n noderank = Searching.size(node.left) + 1\n if valrank < noderank\n node = select(node.left, valrank)\n elseif valrank > noderank\n node = select(node.right, valrank - noderank)\n else\n # found position with `valrank`\n # return node\n end\n\n return node\nend\n\nselect(::Nothing, valrank) = nothing\nselect(tree::BinarySearchTree, valrank) = select(tree.root, valrank)\n\n\"\"\"\n deletemin!(node)\nFind the minimum node and delete it from the tree.\nWe can find the minimum node by move left recursively, until \nwe find the node with no left child.\n\n\"\"\"\nfunction deletemin!(node)\n if isnothing(node.left)\n node = node.right\n else\n node.left = deletemin!(node.left)\n end\n updatesize!(node)\n return node\nend\n\ndeletemin!(tree::BinarySearchTree) = BinarySearchTree(deletemin!(tree.root))\n\n\"\"\"\n copyval!(tonode, fromnode)\n\nCopy values from `fromnode` to `tonode`.\n\"\"\"\nfunction copyval!(tonode::BinaryNode, fromnode::BinaryNode)\n tonode.val = fromnode.val \n tonode.numnodes = fromnode.numnodes\n nothing\nend\n\n\"\"\"\n delete!(tree, val)\n\nDelete the node from the binary search tree.\nIt returns the successor of the deleted node.\n\n delete!(node, val)\n\nDelete the node with value `val` in the substree \nstarts with `node`.\n\"\"\"\nfunction delete!(node, val)\n if isnothing(node)\n return nothing\n elseif val < node.val\n node.left = delete!(node.left, val)\n elseif val > node.val\n node.right = delete!(node.right, val)\n # found the value and node has only one child node\n elseif isnothing(node.right)\n node = node.left\n elseif isnothing(node.left)\n node = node.right\n # node has both left and right child nodes\n else \n # replace current node with its successor\n # here I cheated using copy value (without links), \n # instead of replacing the object\n # This way we keep the original reference to make the\n # side effect consistent: the returned node and original \"node\"\n # refers to the same object (a substree starting from that node)\n copyval!(node, minimum(node.right)) \n\n # left child remain the same \n # delete the the successor from the right subtree\n # link successor the right child to the pruned subtree\n node.right = deletemin!(node.right)\n end\n\n updatesize!(node)\n return node\nend\n\ndelete!(tree::BinarySearchTree, val) = BinarySearchTree(delete!(tree.root, val))\n\nend # module", "meta": {"hexsha": "0870a3acb17d3eed20773a49ee2edb87688b66ee", "size": 6717, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/searching.jl", "max_stars_repo_name": "Jetafull/AlgorithmsInJulia", "max_stars_repo_head_hexsha": "6e4d8a58e063861967de9260f15d182eb7d35ada", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-21T03:27:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-21T03:27:23.000Z", "max_issues_repo_path": "src/searching.jl", "max_issues_repo_name": "Jetafull/algorithms-in-julia", "max_issues_repo_head_hexsha": "6e4d8a58e063861967de9260f15d182eb7d35ada", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/searching.jl", "max_forks_repo_name": "Jetafull/algorithms-in-julia", "max_forks_repo_head_hexsha": "6e4d8a58e063861967de9260f15d182eb7d35ada", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.6514084507, "max_line_length": 88, "alphanum_fraction": 0.6471639125, "num_tokens": 1736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582516374121, "lm_q2_score": 0.8740772351648677, "lm_q1q2_score": 0.8132923760275659}} {"text": "# # Minimization of simple loss functions\n#\n# First we load the required packages.\n\nusing Distributions, LinearAlgebra, Random, Plots\n\nusing EnsembleKalmanProcesses.EnsembleKalmanProcessModule, EnsembleKalmanProcesses.ParameterDistributionStorage\n\n# ## Loss function with single minimum\n#\n# Here, we minimize the loss function\n# ```math\n# G₁(u) = \\|u - u_*\\| ,\n# ```\n# where ``u`` is a 2-vector of parameters and ``u_*`` is given; here ``u_* = (-1, 1)``. \nu★ = [1, -1]\nG₁(u) = [sqrt((u[1] - u★[1])^2 + (u[2] - u★[2])^2)]\nnothing # hide\n\n# We set the seed for pseudo-random number generator for reproducibility.\nrng_seed = 41\nRandom.seed!(rng_seed)\nnothing # hide\n\n# We set a stabilization level, which can aid the algorithm convergence\ndim_output = 1\nstabilization_level = 1e-3\nΓ_stabilization = stabilization_level * Matrix(I, dim_output, dim_output)\n\n# The functional is positive so to minimize it we may set the target to be 0,\nG_target = [0]\nnothing # hide\n\n# ### Prior distributions\n#\n# As we work with a Bayesian method, we define a prior. This will behave like an \"initial guess\"\n# for the likely region of parameter space we expect the solution to live in.\nprior_distributions = [Parameterized(Normal(0, 1)), Parameterized(Normal(0, 1))]\n\nconstraints = [[no_constraint()], [no_constraint()]]\n\nparameter_names = [\"u1\", \"u2\"]\n\nprior = ParameterDistribution(prior_distributions, constraints, parameter_names)\n\n# ### Calibration\n#\n# We choose the number of ensemble members and the number of iterations of the algorithm\nN_ensemble = 20\nN_iterations = 10\nnothing # hide\n\n# The initial ensemble is constructed by sampling the prior\ninitial_ensemble = EnsembleKalmanProcessModule.construct_initial_ensemble(prior, N_ensemble; rng_seed = rng_seed)\n\n# We then initialize the Ensemble Kalman Process algorithm, with the initial ensemble, the\n# target, the stabilization and the process type (for EKI this is `Inversion`, initialized \n# with `Inversion()`). \nensemble_kalman_process =\n EnsembleKalmanProcessModule.EnsembleKalmanProcess(initial_ensemble, G_target, Γ_stabilization, Inversion())\n\n# Then we calibrate by *(i)* obtaining the parameters, *(ii)* calculate the loss function on\n# the parameters (and concatenate), and last *(iii)* generate a new set of parameters using\n# the model outputs:\nfor i in 1:N_iterations\n params_i = get_u_final(ensemble_kalman_process)\n\n g_ens = hcat([G₁(params_i[:, i]) for i in 1:N_ensemble]...)\n\n EnsembleKalmanProcessModule.update_ensemble!(ensemble_kalman_process, g_ens)\nend\n\n# and visualize the results:\nu_init = get_u_prior(ensemble_kalman_process)\n\nanim_unique_minimum = @animate for i in 1:N_iterations\n u_i = get_u(ensemble_kalman_process, i)\n\n plot(\n [u★[1]],\n [u★[2]],\n seriestype = :scatter,\n markershape = :star5,\n markersize = 11,\n markercolor = :red,\n label = \"optimum u⋆\",\n )\n\n plot!(\n u_i[1, :],\n u_i[2, :],\n seriestype = :scatter,\n xlims = extrema(u_init[1, :]),\n ylims = extrema(u_init[2, :]),\n xlabel = \"u₁\",\n ylabel = \"u₂\",\n markersize = 5,\n markeralpha = 0.6,\n markercolor = :blue,\n label = \"particles\",\n title = \"EKI iteration = \" * string(i),\n )\nend\nnothing # hide\n\n# The results show that the minimizer of ``G_1`` is ``u=u_*``. \n\ngif(anim_unique_minimum, \"unique_minimum.gif\", fps = 1) # hide\n\n# ## Loss function with two minima\n\n# Now let's do an example in which the loss function has two minima. We minimize the loss\n# function\n# ```math\n# G₂(u) = \\|u - v_{*}\\| \\|u - w_{*}\\| ,\n# ```\n# where again ``u`` is a 2-vector, and ``v_{*}`` and ``w_{*}`` are given 2-vectors. Here, we take ``v_{*} = (1, -1)`` and ``w_{*} = (-1, -1)``.\n\nv★ = [1, -1]\nw★ = [-1, -1]\nG₂(u) = [sqrt(((u[1] - v★[1])^2 + (u[2] - v★[2])^2) * ((u[1] - w★[1])^2 + (u[2] - w★[2])^2))]\nnothing # hide\n#\n# The procedure is same as the single-minimum example above.\n\n# We set the seed for pseudo-random number generator for reproducibility,\nrng_seed = 10\nRandom.seed!(rng_seed)\nnothing # hide\n\n# A positive function can be minimized with a target of 0,\nG_target = [0]\n\n# We choose the stabilization as in the single-minimum example\n\n# ### Prior distributions\n#\n# We define the prior. We can place prior information on e.g., ``u₁``, demonstrating a belief\n# that ``u₁`` is more likely to be negative. This can be implemented by setting a bias in the\n# mean of its prior distribution to e.g., ``-0.5``:\n\nprior_distributions = [Parameterized(Normal(-0.5, sqrt(2))), Parameterized(Normal(0, sqrt(2)))]\n\nconstraints = [[no_constraint()], [no_constraint()]]\n\nparameter_names = [\"u1\", \"u2\"]\n\nprior = ParameterDistribution(prior_distributions, constraints, parameter_names)\n\n# ### Calibration\n#\n# We choose the number of ensemble members, the number of EKI iterations, construct our initial ensemble and the EKI with the `Inversion()` constructor (exactly as in the single-minimum example):\nN_ensemble = 20\nN_iterations = 20\n\ninitial_ensemble = EnsembleKalmanProcessModule.construct_initial_ensemble(prior, N_ensemble; rng_seed = rng_seed)\n\nensemble_kalman_process =\n EnsembleKalmanProcessModule.EnsembleKalmanProcess(initial_ensemble, G_target, Γ_stabilization, Inversion())\n\n# We calibrate by *(i)* obtaining the parameters, *(ii)* calculating the\n# loss function on the parameters (and concatenate), and last *(iii)* generate a new set of\n# parameters using the model outputs:\nfor i in 1:N_iterations\n params_i = get_u_final(ensemble_kalman_process)\n\n g_ens = hcat([G₂(params_i[:, i]) for i in 1:N_ensemble]...)\n\n EnsembleKalmanProcessModule.update_ensemble!(ensemble_kalman_process, g_ens)\nend\n\n# and visualize the results:\nu_init = get_u_prior(ensemble_kalman_process)\n\nanim_two_minima = @animate for i in 1:N_iterations\n u_i = get_u(ensemble_kalman_process, i)\n\n plot(\n [v★[1]],\n [v★[2]],\n seriestype = :scatter,\n markershape = :star5,\n markersize = 11,\n markercolor = :red,\n label = \"optimum v⋆\",\n )\n\n plot!(\n [w★[1]],\n [w★[2]],\n seriestype = :scatter,\n markershape = :star5,\n markersize = 11,\n markercolor = :green,\n label = \"optimum w⋆\",\n )\n\n plot!(\n u_i[1, :],\n u_i[2, :],\n seriestype = :scatter,\n xlims = extrema(u_init[1, :]),\n ylims = extrema(u_init[2, :]),\n xlabel = \"u₁\",\n ylabel = \"u₂\",\n markersize = 5,\n markeralpha = 0.6,\n markercolor = :blue,\n label = \"particles\",\n title = \"EKI iteration = \" * string(i),\n )\nend\nnothing # hide\n\n# Our bias in the prior shifts the initial ensemble into the negative ``u_1`` direction, and\n# thus increases the likelihood (over different instances of the random number generator) of\n# finding the minimizer ``u=w_*``.\n\ngif(anim_two_minima, \"two_minima.gif\", fps = 1) # hide\n", "meta": {"hexsha": "6bff8f5c6b53a7c849c92f265e7dd8a8dece5410", "size": 6919, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/LossMinimization/loss_minimization.jl", "max_stars_repo_name": "lm2612/EnsembleKalmanProcesses.jl", "max_stars_repo_head_hexsha": "1fee0bc06b9578d4b97851831a280267e0bce7b4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2021-03-02T08:35:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T18:50:04.000Z", "max_issues_repo_path": "examples/LossMinimization/loss_minimization.jl", "max_issues_repo_name": "lm2612/EnsembleKalmanProcesses.jl", "max_issues_repo_head_hexsha": "1fee0bc06b9578d4b97851831a280267e0bce7b4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 129, "max_issues_repo_issues_event_min_datetime": "2021-02-24T17:44:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T17:38:35.000Z", "max_forks_repo_path": "examples/LossMinimization/loss_minimization.jl", "max_forks_repo_name": "lm2612/EnsembleKalmanProcesses.jl", "max_forks_repo_head_hexsha": "1fee0bc06b9578d4b97851831a280267e0bce7b4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2021-05-21T20:46:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-03T20:53:46.000Z", "avg_line_length": 31.45, "max_line_length": 195, "alphanum_fraction": 0.6722069663, "num_tokens": 1949, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582516374121, "lm_q2_score": 0.8740772318846386, "lm_q1q2_score": 0.8132923729754497}} {"text": "### A Pluto.jl notebook ###\n# v0.14.5\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 19cc5ec6-f7cb-4736-98c3-498d91eb2414\nusing BarycentricInterpolation\n\n# ╔═╡ 53285b2c-3704-4adc-9bdd-9dea619b5140\nmd\" ## BarycentricInterpolation.jl\"\n\n# ╔═╡ 7ba7dd56-4ee9-4c5c-97a8-5f99a9ba507e\np = Chebyshev2{20}() # create a Chebyshev type 2 polynomial of order 20\n\n# ╔═╡ ddacc062-c4cb-40e1-8645-a1f8619eabea\nx = nodes(p) # get the nodes\n\n# ╔═╡ 7fdcd309-5e3e-4c65-9d8c-96d19fdc923c\ny = sinpi.(x) # generate y values at the nodes\n\n# ╔═╡ 9c9fdfad-44eb-4f5b-a5e0-82eaade02ed1\nx_new = rand()*2 -1 # a random number in [-1, +1]\n\n# ╔═╡ f3f7c1ea-f4aa-4dc2-a630-0fb37e4bdadb\nprintln(interpolate(p, y, x_new) ≈ sinpi(x_new)) # hopefully true!\n\n# ╔═╡ d0ca3867-a266-4299-ac49-9745154b3ad4\nD = differentiation_matrix(p) # get the differentiation matrix\n\n# ╔═╡ 880d1ae8-5a5a-463a-8e35-a73bdc40208a\nprintln(interpolate(p, D*y, x_new) ≈ pi*cospi(x_new)) # hopefully true!\n\n# ╔═╡ c2fcf437-bd86-4b24-8c77-29702cf5373d\nmd\" ## End of BarycentricInterpolation.jl\"\n\n# ╔═╡ Cell order:\n# ╟─53285b2c-3704-4adc-9bdd-9dea619b5140\n# ╠═19cc5ec6-f7cb-4736-98c3-498d91eb2414\n# ╠═7ba7dd56-4ee9-4c5c-97a8-5f99a9ba507e\n# ╠═ddacc062-c4cb-40e1-8645-a1f8619eabea\n# ╠═7fdcd309-5e3e-4c65-9d8c-96d19fdc923c\n# ╠═9c9fdfad-44eb-4f5b-a5e0-82eaade02ed1\n# ╠═f3f7c1ea-f4aa-4dc2-a630-0fb37e4bdadb\n# ╠═d0ca3867-a266-4299-ac49-9745154b3ad4\n# ╠═880d1ae8-5a5a-463a-8e35-a73bdc40208a\n# ╟─c2fcf437-bd86-4b24-8c77-29702cf5373d\n", "meta": {"hexsha": "9b46ed631bf8a48df1147a1d0b3da602999e6aff", "size": 1520, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/05/j-05-BarycentricInterpolation.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-BarycentricInterpolation.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-BarycentricInterpolation.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.6666666667, "max_line_length": 81, "alphanum_fraction": 0.7072368421, "num_tokens": 787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9399133515091156, "lm_q2_score": 0.865224091265267, "lm_q1q2_score": 0.813235675427566}} {"text": "## Demo: Sonar Equations\n# Demonstrate calculation of the sonar equations, with focus on signal excess and probability of detection.\nusing Plots; gr()\nusing SpecialFunctions\nusing ColorSchemes\n\ninclude(\"../SonarEquations.jl\")\n\n## Single Propagation\nB = 1. # bandwidth\nt = 1. # integration time\nSL = 52. # source level\nNL = 5. # noise level\np_fal = 1e-4 # probability of false alarm\n\nc = 1500. # sound speed\nf = 100. # frequency\nλ = c/f # wavelength\nk = 2π/λ # wavenumber\n\nr₀ = 0. # source range\nz₀ = 100. # source depth\n\nR(r, z) = sqrt.((r - r₀)^2 + (z - z₀)^2) # distance from source\np(r, z) = R(r, z)\\exp(im*k*R(r, z)) # complex pressure\nTL(r, z) = -10log10(abs(p(r, z))) # transmission loss\nDI = 20 # directivity index\n# DT(r, z) = 5log10(d(r, z)*B/t)\nDT(r, z) = SonarEquations.detection_threshold(d(r, z), B, t)\n# SE(r, z) = SL - TL(r, z) - NL + DI - DT(r, z)\nSE(r, z) = SonarEquations.signal_excess_passive(SL, TL(r, z), NL, DI, DT(r, z))\n\n# d(r, z) = B*t*((SL - TL(r, z))/(B*NL))^2\nd(r, z) = SonarEquations.detection_index_gaussian(SL, TL(r, z), NL, B, t)\n# p_dtc(r, z) = erfc(erfcinv(2p_fal) - sqrt(d(r, z)/2))/2\n# POD(r, z) = 100p_dtc(r, z)\nPOD(r, z) = 100SonarEquations.probability_of_detection_gaussian(d(r, z), p_fal)\n\nr = range(1., 1e3, length = 100)\nz = range(1., 400., length = 50)\n\npTL = heatmap(r, z, TL,\n\tseriescolor = cgrad(:jet, rev = true),\n\ttitle = \"TL (dB)\",\n\tyaxis = (\"Depth (m)\", :flip))\n\npd = heatmap(r, z, d,\n\tseriescolor = :jet,\n\ttitle = \"d\",\n\tyaxis = :flip)\n\npSE = heatmap(r, z, SE,\n\tseriescolor = :jet,\n\ttitle = \"SE (dB)\",\n\txaxis = \"Range (m)\",\n\tyaxis = (\"Depth (m)\", :flip))\n\npPOD = heatmap(r, z, POD,\n\tseriescolor = :jet,\n\ttitle = \"POD (%)\",\n\txaxis = \"Range (m)\",\n\tyaxis = :flip)\n\nl = @layout [a b; c d]\n\npt = plot(pTL, pd, pSE, pPOD,\n\tlayout = l)\ndisplay(pt)\nsavefig(pt, \"img/SonarEqs_SimplePropagation.png\")\n\n## Simple Lloyd's Mirror\ninclude(\"../LloydsMirror.jl\")\n\nSL = 50.\nNL = 5.\nB = 1.\nt = 1.\nDI = 20.\np_fal = 1e-2\n\nc = 1500.0\nf = 1e2\nλ = c/f\nr_src = 0.0\nz_src = 2λ\nr = range(0, 3e2, length = 201)\nz = range(0, 10λ, length = 101)\nzTemp = 5λ\n\nTL(r, z) = LloydsMirror.lloydsmirror_singlereflection.(c, f, r_src, r, z_src, z)\nd(r, z) = SonarEquations.detection_index_gaussian(SL, TL(r, z), NL, B, t)\nDT(r, z) = SonarEquations.detection_threshold(d(r, z), B, t)\nSE(r, z) = SonarEquations.signal_excess_passive(SL, TL(r, z), NL, DI, DT(r, z))\nPOD(r, z) = 100SonarEquations.probability_of_detection_gaussian(d(r, z), p_fal)\n\npTL = heatmap(r, z, TL,\n\tseriescolor = cgrad(:jet, rev = true),\n\ttitle = \"TL (dB)\",\n\tyaxis = (\"Depth (m)\", :flip))\n\npd = heatmap(r, z, d,\n\tseriescolor = :jet,\n\ttitle = \"d\",\n\tyaxis = :flip)\n\npSE = heatmap(r, z, SE,\n\tseriescolor = :jet,\n\ttitle = \"SE (dB)\",\n\txaxis = \"Range (m)\",\n\tyaxis = (\"Depth (m)\", :flip))\n\npPOD = heatmap(r, z, POD,\n\tseriescolor = :jet,\n\ttitle = \"POD (%)\",\n\txaxis = \"Range (m)\",\n\tyaxis = :flip)\n\nl = @layout [a b; c d]\n\npt = plot(pTL, pd, pSE, pPOD,\n\tlayout = l)\ndisplay(pt)\nsavefig(pt, \"img/SonarEqs_LloydsMirror.png\")\n\nheatmap(r, z, DT,\n\tyaxis = :flip)\n\n## Multipath Propagation\n\n", "meta": {"hexsha": "33736d75a42c4d80c7a1782d53401a1c1938e301", "size": 3056, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/demo/Demo_SonarEquations.jl", "max_stars_repo_name": "kapple19/OceanAcousticsModelling", "max_stars_repo_head_hexsha": "9fdc1cefa51894661543428022d4fe45cd952e4f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-21T11:08:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-21T11:08:53.000Z", "max_issues_repo_path": "src/demo/Demo_SonarEquations.jl", "max_issues_repo_name": "kapple19/OceanAcousticsModelling", "max_issues_repo_head_hexsha": "9fdc1cefa51894661543428022d4fe45cd952e4f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/demo/Demo_SonarEquations.jl", "max_forks_repo_name": "kapple19/OceanAcousticsModelling", "max_forks_repo_head_hexsha": "9fdc1cefa51894661543428022d4fe45cd952e4f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-05T02:54:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-05T02:54:21.000Z", "avg_line_length": 23.5076923077, "max_line_length": 107, "alphanum_fraction": 0.6178010471, "num_tokens": 1185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133548753619, "lm_q2_score": 0.8652240877899775, "lm_q1q2_score": 0.8132356750736524}} {"text": "### routines related to geometric transforms of a set of coordinates.\n\n\nfunction shiftthenstretch(x,n::Int,T,N)\n return (x-n*T)/N\nend\n\nfunction shiftthencompress(x,n::Int,T,N)\n return (x-n*T)*N\nend\n\n# evaluates f(x/M)\nfunction evalstretchedsignal(x, f::Function, M::Int)\n return f(x/M)\nend\n\n\"\"\"\n convertcompactdomain(x::T, a::T, b::T, c::T, d::T)::T\n\nconverts compact domain x ∈ [a,b] to compact domain out ∈ [c,d].\n\"\"\"\nfunction convertcompactdomain(x::T, a::T, b::T, c::T, d::T)::T where T <: Real\n\n return (x-a)*(d-c)/(b-a)+c\nend\n\nfunction convertcompactdomain(x::Vector{T}, a::Vector{T}, b::Vector{T}, c::Vector{T}, d::Vector{T})::Vector{T} where T <: Real\n\n return collect( convertcompactdomain(x[i], a[i], b[i], c[i], d[i]) for i = 1:length(x) )\nend\n", "meta": {"hexsha": "63230b5db1a06c6c4cf15778bf53767fb4111b6d", "size": 773, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/geometric_transforms.jl", "max_stars_repo_name": "RoyCCWang/RWJuliaUtilities", "max_stars_repo_head_hexsha": "3796a8dd251470a127d4fdb2f2ff19be4a5320aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/geometric_transforms.jl", "max_issues_repo_name": "RoyCCWang/RWJuliaUtilities", "max_issues_repo_head_hexsha": "3796a8dd251470a127d4fdb2f2ff19be4a5320aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/geometric_transforms.jl", "max_forks_repo_name": "RoyCCWang/RWJuliaUtilities", "max_forks_repo_head_hexsha": "3796a8dd251470a127d4fdb2f2ff19be4a5320aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.935483871, "max_line_length": 126, "alphanum_fraction": 0.6364812419, "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133548753619, "lm_q2_score": 0.8652240686758841, "lm_q1q2_score": 0.8132356571080607}} {"text": "module ProtonFunctions\r\n\r\nusing QuadGK\r\nusing Trapz\r\n\r\nexport adiabatic_energy_loss, interaction_rate, hubbles_law, survival_probability\r\n\r\n\"\"\"\r\n `adiabatic_energy_loss(lorentz_initial, z_initial, z_final)`\r\n\r\nCalculates the Lorentz factor of a particle after it propagates from a redshift z_initial to a redshift z_final.\r\nThe particle loses energy due to the adiabatic expansion of the universe.\r\n\r\nBased on eq. (2-4) from arXiv:1505.01347 https://arxiv.org/abs/1505.01347\r\n\"\"\"\r\nfunction adiabatic_energy_loss(lorentz_initial::Real, z_initial::Real, z_final::Real)\r\n integral, err = quadgk(z -> 1/(1+z), z_initial, z_final) # numerical integration using QuadGK.jl\r\n energy_loss = ℯ^(-integral)\r\n return lorentz_initial/energy_loss\r\nend\r\n\r\n\r\n\"\"\"\r\n `interaction_rate(Γ, ϵ, σ)`\r\nCalculates the interaction rate of protons with photons for a given proton Lorentz factor, redshift, photon energy, and interaction cross section.\r\n\r\nInputs:\r\n- Γ: proton Lorentz factor\r\n- z: redshift\r\n- ϵ: photon energy (in the proton rest frame) (eV)\r\n- σ: pγ interaction cross-section (micrometer^2)\r\n\r\nSource: Eq. (10.9) from Cosmic Rays and Particle Physics, 2nd Edition, by Thomas K. Gaisser, Ralph Engel, and Elisa Resconi.\r\n\"\"\"\r\nfunction interaction_rate(Γ::Real, z::Real, ϵ::Vector{T1}, σ::Vector{T2}) where {T1<:Number, T2<:Number}\r\n c = (2.99792e8)*1e9 # speed of light, nanometer/s\r\n kT = 0.234822*1e-9 # boltzmann constant * z=0 CMB temperature, MeV\r\n ħc = .197327*1e-3 # reduced planck constant * speed of light, MeV * nanometer\r\n M = @. ϵ*σ*(-log(1-ℯ^(-ϵ/(2*Γ*kT))))\r\n # trapezoidal integration of M over the array of ϵ\r\n I = trapz(ϵ, M) \r\n @assert I >= 0.0 # An interaction rate will never be negative\r\n rate_at_zero_redshift = (c*kT)/((2*π^2)*(ħc^3)*(Γ^2)) * I\r\n return rate_at_zero_redshift*(1+z)^3\r\nend\r\n\r\n\r\n\"\"\"\r\n 'hubbles_law(z)'\r\n\r\nCalculates dt/dz at the input redshift z. Source: eq. (3) from arXiv:1505.01347 https://arxiv.org/abs/1505.01347\r\n\"\"\"\r\nfunction hubbles_law(z::Real)\r\n H0 = 2.198e-18 # Hubble constant in s^-1\r\n Ωm = 0.3 # matter density parameter\r\n ΩΛ = 0.7 # dark energy density parameter\r\n return -1/(H0*(1+z)*sqrt((1+z^3)*Ωm + ΩΛ))\r\nend\r\n\r\n\r\n\"\"\"\r\n 'survival_probability(p_prev, rate_prev, z_prev, rate, z)'\r\n\r\nThe probability that the proton has not undergone a reaction at each redshift step, approximated\r\nusing the trapezoidal rule. Source: Eq. (7) arXiv:1505.01347 https://arxiv.org/abs/1505.01347\r\n\r\nInputs:\r\n- p_prev = the survival probability at the previous redshift step\r\n- rate_prev = the interaction rate at the previous redshift step\r\n- z_prev = the redshift at the previous redshift step\r\n- rate = the interaction rate at the current redshift step\r\n- z = the redshift at the current redshift step\r\n\"\"\"\r\nfunction survival_probability(p_prev::Real, rate_prev::Real, z_prev::Real, rate::Real, z::Real)\r\n @assert p_prev >= 0 # probabilites cannot be negative\r\n logp = log(p_prev) - (rate_prev*hubbles_law(z_prev) + rate*hubbles_law(z))*(0.5)*(z - z_prev)\r\n return ℯ^logp\r\nend\r\n\r\nend", "meta": {"hexsha": "dc24ed90d8ebf6744268e30f4aedca93174e3471", "size": 3077, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/proton.jl", "max_stars_repo_name": "azeolla/GZK_sim.jl", "max_stars_repo_head_hexsha": "715ab6c4076446a3563ce06c009c33c5067850e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/proton.jl", "max_issues_repo_name": "azeolla/GZK_sim.jl", "max_issues_repo_head_hexsha": "715ab6c4076446a3563ce06c009c33c5067850e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/proton.jl", "max_forks_repo_name": "azeolla/GZK_sim.jl", "max_forks_repo_head_hexsha": "715ab6c4076446a3563ce06c009c33c5067850e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4625, "max_line_length": 147, "alphanum_fraction": 0.7010074748, "num_tokens": 964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812336438724, "lm_q2_score": 0.8397339716830606, "lm_q1q2_score": 0.8131826194311109}} {"text": "\"\"\"Julia program to implement Merge sort\nMerge Sort is a Divide and Conquer algorithm. It divides the input array into two halves, calls itself for the two halves, and then merges the two sorted halves.\nFirst divide the list into the smallest unit (1 element), then compare each element with the adjacent list to sort and merge the two adjacent lists. \nFinally all the elements are sorted and merged.\n\"\"\"\nfunction merge_sort(arr)\n if length(arr) <= 1\n return arr\n end\n middle = trunc(Int, length(arr) / 2) # Finding the mid of the array\n L = arr[1:middle]\n R = arr[middle+1:end]\n \n merge_sort(L) # Sorting the first half\n merge_sort(R) # Sorting the second half\n \n # Copy data to temp arrays L[] and R[]\n i = j = k = 1\n while i <= length(L) && j <= length(R)\n if L[i] < R[j]\n arr[k] = L[i]\n i+=1\n else\n arr[k] = R[j]\n j+=1\n end\n k+=1\n end\n # Checking if any element was left\n while i <= length(L)\n arr[k] = L[i]\n i+=1\n k+=1\n end\n while j <= length(R)\n arr[k] = R[j]\n j+=1\n k+=1\n end\n arr\nend\n\nprint(\"How many numbers do you want to sort? \")\nn = readline()\nn = parse(Int64, n)\nif (n <= 0)\n println(\"No numbers to sort!!!\")\n exit()\nend\narr = Int[]\nprint(\"Enter the numbers: \")\narr = [parse(Int, num) for num in split(readline())]\nmerge_sort(arr)\nprint(\"The numbers in sorted order is \")\nprint(arr)\n\n\n\"\"\"\nTime Complexity - O(n*Log n), where 'n' is the size of the array\nSpace Complexity - O(n)\n\nSAMPLE INPUT AND OUTPUT\nHow many numbers do you want to sort? 4\nEnter the numbers: 8 2 7 6 \nThe numbers in sorted order is [2, 6, 7, 8]\n\"\"\"\n\n\n", "meta": {"hexsha": "84d956ba5da8e57e630324665e729669c1e4c9e6", "size": 1742, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/sort/merge_sort.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/sort/merge_sort.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/sort/merge_sort.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": 25.2463768116, "max_line_length": 161, "alphanum_fraction": 0.588978186, "num_tokens": 485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.8962513793687401, "lm_q1q2_score": 0.8131798254200635}} {"text": "### A Pluto.jl notebook ###\n# v0.14.0\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ b2d786ec-7f73-11ea-1a0c-f38d7b6bbc1e\nmd\"\"\"\n# The Basel problem\n\n_Leonard Euler_ proved in 1741 that the series\n\n```math\n\\frac{1}{1} + \\frac{1}{4} + \\frac{1}{9} + \\cdots\n```\n\nconverges to\n\n```math\n\\frac{\\pi^2}{6}.\n```\n\"\"\"\n\n# ╔═╡ b2d79330-7f73-11ea-0d1c-a9aad1efaae1\nn = 1:100000\n\n# ╔═╡ b2d79376-7f73-11ea-2dce-cb9c449eece6\nseq = n .^ -2\n\n# ╔═╡ b2d792c2-7f73-11ea-0c65-a5042701e9f3\nsqrt(sum(seq) * 6.0)\n\n# ╔═╡ Cell order:\n# ╟─b2d786ec-7f73-11ea-1a0c-f38d7b6bbc1e\n# ╠═b2d792c2-7f73-11ea-0c65-a5042701e9f3\n# ╠═b2d79330-7f73-11ea-0d1c-a9aad1efaae1\n# ╠═b2d79376-7f73-11ea-2dce-cb9c449eece6\n", "meta": {"hexsha": "c3d46b7f2b3c25a0f401671999a35877db5d91cf", "size": 668, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "sample/Basic.jl", "max_stars_repo_name": "Mechachleopteryx/Pluto.jl", "max_stars_repo_head_hexsha": "78fbd9f00a3323208a6df9a4ff0ecbdcf2d9845a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3974, "max_stars_repo_stars_event_min_datetime": "2020-03-06T10:50:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:39:46.000Z", "max_issues_repo_path": "sample/Basic.jl", "max_issues_repo_name": "Mechachleopteryx/Pluto.jl", "max_issues_repo_head_hexsha": "78fbd9f00a3323208a6df9a4ff0ecbdcf2d9845a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1585, "max_issues_repo_issues_event_min_datetime": "2020-03-01T23:46:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:04:08.000Z", "max_forks_repo_path": "sample/Basic.jl", "max_forks_repo_name": "Mechachleopteryx/Pluto.jl", "max_forks_repo_head_hexsha": "78fbd9f00a3323208a6df9a4ff0ecbdcf2d9845a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 280, "max_forks_repo_forks_event_min_datetime": "2020-03-28T10:47:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T19:50:31.000Z", "avg_line_length": 17.5789473684, "max_line_length": 48, "alphanum_fraction": 0.6751497006, "num_tokens": 379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284088045171237, "lm_q2_score": 0.8757869948899665, "lm_q1q2_score": 0.8130883569374381}} {"text": "using DataFrames, Plots, Calculus\npyplot()\n\nProjDir = dirname(@__FILE__)\ncd(ProjDir) do\n \n function euler_ex71(f::Function, y0::Float64, x::FloatRange{Float64})\n y = Vector{Real}(length(x))\n y[1] = y0\n h = x.step/x.divisor\n for i in 2:length(x)\n y[i] = y[i-1] + h * f(x[i-1], y[i-1])\n end\n columns=[]\n push!(columns, collect(x))\n push!(columns, y)\n df = DataFrame(columns, [:x, :y])\n end\n\n f(x,y) = 3x^2 + 2x\n fy(x) = x^3+x^2+1\n \n x1 = 1.0:0.25:2.0\n x2 = 1.0:0.1:2.0\n x3 = 0.8:0.1:2.2\n df1 = euler_ex71(f, 3.0, x1)\n df2 = euler_ex71(f, 3.0, x2)\n\n df1 |> display\n println()\n df2 |> display\n println()\n\n global p2\n \n p1 = plot(x3, fy.(x3), ylims=(0.8, 13.0))\n plot!(p1, df1[:x], df1[:y], line=(:dash, 1), marker=(:cross))\n plot!(p1, df2[:x], df2[:y], line=(:dash, 1), marker=(:circle))\n show(p1)\n savefig(\"euler_ex7.1A.png\")\n show(p1)\n gui()\nend", "meta": {"hexsha": "cc0e44ac5d5cade77a1b8e20ab1d18d26e41b84b", "size": 899, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ch07/IVP/euler_ex7.1a.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/NumericalMethodsforEngineers.jl-00e1d38a-71a9-5665-8612-32ae585a75a3", "max_stars_repo_head_hexsha": "e230c3045d98da0cf789e4a6acdccfbfb21ef49e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-07-23T18:12:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-25T03:32:45.000Z", "max_issues_repo_path": "examples/ch07/IVP/euler_ex7.1a.jl", "max_issues_repo_name": "OVGULIU/NumericalMethodsforEngineers.jl", "max_issues_repo_head_hexsha": "7ca0b79965a7abd58af29d8dfd1870a954fb3aec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2018-07-23T21:46:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-27T23:14:46.000Z", "max_forks_repo_path": "examples/ch07/IVP/euler_ex7.1a.jl", "max_forks_repo_name": "OVGULIU/NumericalMethodsforEngineers.jl", "max_forks_repo_head_hexsha": "7ca0b79965a7abd58af29d8dfd1870a954fb3aec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-10-27T14:13:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T18:54:06.000Z", "avg_line_length": 20.9069767442, "max_line_length": 71, "alphanum_fraction": 0.552836485, "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087926320945, "lm_q2_score": 0.8757869900269367, "lm_q1q2_score": 0.8130883420138045}} {"text": "\"\"\"\nBackground for the example in the README\n\"\"\"\n\nloc_coords=InterpolationFunction(\n :(a0+a1*xi+a2*eta), # expression\n [:xi, :eta], # symbols for coordinates\n [:a0, :a1, :a2], # symbols for interpolation coefficients\n [ # degrees of freedom\n [0, 0] # values at corners (see explanation below)\n ];\n maximum_derivative=1 # we'll only really need first order derivatives\n)\n\nabs_coords=InterpolationFunction(\n :(a0+a1*x+a2*y),\n [:x, :y],\n [:a0, :a1, :a2],\n [\n [0, 0]\n ];\n maximum_derivative=1\n)\n\ndmn=Domain(\n loc_coords, # local coordinates InterpolationFunction struct\n [ # frontier of the domain in each coordinate of loc_coords\n ( # xi\n 0.0, 1.0\n ),\n ( # eta\n 0.0, :(1.0-xi) # linear triangular element\n )\n ],\n [ # points at which the interpolation from local to absolute coordinates\n [0.0, 0.0], # is imposed (triangle corners)\n [1.0, 0.0],\n [0.0, 1.0] # (xi, eta)\n ]\n)\n\nfin=Finel(\n [ # corners\n [1.0, 1.0],\n [2.0, 1.0],\n [2.0, 2.0]\n ],\n dmn # domain of integration\n)\n\nresd=Residual(\n [\n ( # first variable: weight function\n :w, abs_coords, [] # no derivatives calculated\n ),\n ( # second variable: u\n :u, abs_coords, [\n (:du!dx, [1, 0]) # first order derivative in x axis calculated\n ]\n )\n ],\n :(w*(du!dx-v)), # expression for the residual\n 3; # Gauss-Legendre quadrature order\n extra_args=[:v] # v, a constant\n)\n\nresfunc=get_volume_residual_function(resd)\n\nws=[0.0, 1.0, 1.0] # format compatible with abs_coords InterpolationFunction,\nus=[0.5, 1.0, 1.0] # as detailed before\nv=-1.0\n\nR=resfunc([ws, us], fin, v) # and any other extra_args symbols\n\n# Test it!! :)\n@assert isapprox(R, 0.5)\n\nsurface_resd=Residual(\n [\n ( # first variable: weight function\n :w, abs_coords, [] # no derivatives calculated\n ),\n ( # second variable: u\n :u, abs_coords, [\n (:du!dx, [1, 0]) # first order derivative in x axis calculated\n ]\n )\n ],\n :(w.*[du!dx, v]), # expression for the residual\n 3; # Gauss-Legendre quadrature order, now at domain faces\n extra_args=[:v] # v, a constant\n)\n\nsurface_resfunc=get_surface_residual_function(surface_resd)\n\nR=surface_resfunc([ws, us], fin, v)\n\n# test it!! :)\n@assert isapprox(R, 0.25)\n", "meta": {"hexsha": "bdabe3a3517aa66d35f8b6514dda825da5fb6588", "size": 2452, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/READMEexample.jl", "max_stars_repo_name": "pedrosecchi67/SymFinel.jl", "max_stars_repo_head_hexsha": "24cc4110f48af1d33e1ba1837a6436e4d6506c95", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-01-11T03:50:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-02T15:56:29.000Z", "max_issues_repo_path": "examples/READMEexample.jl", "max_issues_repo_name": "pedrosecchi67/SymFinel.jl", "max_issues_repo_head_hexsha": "24cc4110f48af1d33e1ba1837a6436e4d6506c95", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/READMEexample.jl", "max_forks_repo_name": "pedrosecchi67/SymFinel.jl", "max_forks_repo_head_hexsha": "24cc4110f48af1d33e1ba1837a6436e4d6506c95", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-02T15:56:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-02T15:56:40.000Z", "avg_line_length": 24.52, "max_line_length": 78, "alphanum_fraction": 0.5672920065, "num_tokens": 735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.945801274759925, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.8130710761979943}} {"text": "using Pkg\nPkg.activate(pwd())\n\n# # Wave equation\n# ## Solving the wave equation\n\nstruct Wave\n f\n g\n c\nend\n\n# ### Exercise:\n# \n# Write the function `solve_wave(T, L, wave::Wave; n_t=100, n_x=100)` that solves the wave \n# equation.\n# \n# **Hint**: Follow the procedure from the previous exercise. Discretize time and space, \n# initialize the solution, add the boundary conditions, add the initial conditions and \n# finally, iterate over time.\n# \n# ---\n# ### Solution:\n\nfunction solve_wave(T, L, wave::Wave; n_t=100, n_x=100)\n ts = range(0, T; length=n_t)\n xs = range(0, L; length=n_x)\n Δt = ts[2] - ts[1]\n Δx = xs[2] - xs[1]\n y = zeros(n_t, n_x)\n \n # boundary conditions\n y[:,1] .= wave.f(0)\n y[:,end] .= wave.f(L)\n\n # initial conditions\n y[1,2:end-1] = wave.f.(xs[2:end-1])\n y[2,2:end-1] = y[1,2:end-1] + Δt*wave.g.(xs[2:end-1])\n\n # solution for t = 2Δt, 3Δt, ..., T\n for t in 2:n_t-1, x in 2:n_x-1\n ∂y_xx = (y[t, x+1] - 2*y[t, x] + y[t, x-1])/Δx^2\n y[t+1, x] = c^2 * Δt^2 * ∂y_xx + 2*y[t, x] - y[t-1, x]\n end\n\n return y\nend\n\n# ---\n\nusing Plots\n\nfunction plot_wave(y, file_name; fps = 60, kwargs...)\n anim = @animate for (i, y_row) in enumerate(eachrow(y))\n plot(\n y_row;\n title = \"t = $(i-1)Δt\",\n xlabel = \"x\",\n ylabel = \"y(t, x)\",\n legend = false,\n linewidth = 2,\n kwargs...\n )\n end\n gif(anim, file_name; fps, show_msg = false)\n \n return nothing\nend\n\n# ### Exercise:\n# \n# Solve the wave equation for $L=\\frac32\\pi$, $T=240$, $c=0.02$ and the initial \n# conditions\n# \n# $$\n# \\begin{aligned}\n# f(x) &= 2e^{-(x-\\frac L2)^2} + \\frac{x}{L}, \\\\\n# g(x) &= 0.\n# \\end{aligned}\n# $$\n# \n# Use time discretization with stepsize $\\Delta t=1$ and the space discretization with \n# number of points $n_x=101$ and $n_x=7$ steps. Plot two graphs.\n# \n# ---\n# ### Solution:\n\nf(x,L) = 2*exp(-(x-L/2)^2) + x/L\ng(x) = 0\n\nL = 1.5*pi\nT = 240\nc = 0.02\n\nwave = Wave(x -> f(x,L), g, c)\n\n#+\n\ny1 = solve_wave(T, L, wave; n_t=241, n_x=101)\nplot_wave(y1, joinpath(pwd(), \"lecture_13\", \"wave1.gif\"); ylims=(-2,3), label=\"\")\n\n#+\n\ny2 = solve_wave(T, L, wave; n_t=241, n_x=7)\nplot_wave(y2, joinpath(pwd(), \"lecture_13\", \"wave2.gif\"); ylims=(-2,3), label=\"\")", "meta": {"hexsha": "49075ba3e9ec97ed3a1bd3f162ca4a9ec754c99f", "size": 2299, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lecture_13/01-ode-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/01-ode-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/01-ode-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": 21.8952380952, "max_line_length": 91, "alphanum_fraction": 0.5467594606, "num_tokens": 853, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012762876287, "lm_q2_score": 0.8596637451167997, "lm_q1q2_score": 0.8130710673096718}} {"text": "mutable struct FTestResult <: TestResult\n levels::Union{Vector{String}, Nothing}\n n_obs::IntVector\n sds::FloatVector\n statistic::Float64\n dofs::IntVector\n pval::Float64\nend\n\nfunction show(io::IO, ftr::FTestResult)\n println(\"\\n F test to compare two variances\")\n println(\"Data (± SD)\")\n @printf(io, \" %s: ± %.2f\\n\",\n ftr.levels[1], ftr.sds[1])\n @printf(io, \" %s: ± %.2f\\n\",\n ftr.levels[2], ftr.sds[2])\n println(io, \"\\nResult:\\n\", coeftable(ftr))\nend\n\nfunction coeftable(ftr::FTestResult)\n CoefTable(\n [ftr.statistic, ftr.dofs[1], ftr.dofs[2], ftr.pval],\n [\"F\", \"DF₁\", \"DF₂\", \"P-value\"],\n [\"\"],\n 4, 1\n )\nend\n\n\"\"\"\n f_test(x1, x2)\n\nF-test\n\nThe arguments `x1` and `x2` can be numeric `Vector`.\n\"\"\"\nfunction f_test(\n x1::NumVector,\n x2::NumVector;\n levels::Union{Vector{String}, Nothing}=nothing\n)::FTestResult\n # use temporal sample names\n if isnothing(levels)\n @info \"Using the first and second sample names as 'Sample1' and 'Sample2'\"\n levels = [\"Sample1\", \"Sample2\"]\n end\n\n # check types\n if !(x1 isa FloatVector)\n @warn \"$levels[1] is converted to Float64\"\n x1 = convert(Vector{Float64}, x1)\n end\n if !(x2 isa FloatVector)\n @warn \"$levels[2] is converted to Float64\"\n x2 = convert(Vector{Float64}, x2)\n end\n\n # check length\n n1 = length(x1)\n n2 = length(x2)\n n1 > 1 || error(\"size of $levels[1] is not enough: actual size is $n1\")\n n2 > 1 || error(\"size of $levels[2] is not enough: actual size is $n2\")\n\n # perform f-test\n v1 = var(x1)\n v2 = var(x2)\n ν1 = v1 < v2 ? n2-1 : n1-1\n ν2 = v1 < v2 ? n1-1 : n2-1\n f_stat = v1 < v2 ? v2/v1 : v1/v2\n pval = 2.0 * D.ccdf(FDist(ν1, ν2), f_stat)\n res = FTestResult(levels, [n1, n2], [sqrt(v1), sqrt(v2)],\n f_stat, [ν1, ν2], pval)\n return res\nend\n\n\"\"\"\n FTestModel\n\nA `TestModel` type for f-test\n\n# Members\n\n- `X`: model matrix\n- `y`: vector to compare its means\n- `levels`: `String` vector of the unique levels (only 2 elements are allowed)\n\n\"\"\"\nstruct FTestModel{T<:Real} <: TestModel\n x1::AbstractVector{T}\n x2::AbstractVector{T}\n levels::Vector{String}\n function FTestModel(\n X::Matrix{T},\n y::AbstractVector{T},\n levels::Vector{String};\n ) where T\n dummy = X[:,2]\n x1 = y[dummy .== 0]\n x2 = y[dummy .== 1]\n new{T}(x1, x2, levels)\n end\nend\n\nfunction fit(obj::FTestModel)\n f_test(obj.x1, obj.x2, levels=obj.levels)\nend\nfunction fit(\n ::Type{FTestModel},\n X::AbstractMatrix{<:Real},\n y::AbstractVector{<:Real},\n levels::Vector{String}\n)\n ftest_obj = FTestModel(X, y, levels)\n fit(ftest_obj)\nend\n\n\"\"\"\n f_test(X, y)\n\nAn alias for `fit(FTestModel, X, y, levels)`\n\nThe arguments `X` and `y` can be a `Matrix` and a `Vector` or a `Formula` and `DataFrame`.\n\nThe argument `levels` can be a `Vector{String}`.\n\"\"\"\nfunction f_test(\n X::AbstractMatrix{<:Real},\n y::AbstractVector{<:Real}\n)\n @info \"Using the first and second sample names as 'Sample1' and 'Sample2'\"\n fit(FTestModel, X, y, [\"Sample1\", \"Sample2\"])\nend\nfunction f_test(\n formula::FormulaTerm{Term,Term},\n df::DataFrame\n)\n # obtain levels\n f = apply_schema(formula, schema(formula, df))\n levels = DataAPI.levels(df[!,f.rhs.terms[1].sym])\n if eltype(levels) <: Real\n levels = string.(levels)\n end\n\n # model matrix\n model_frame = ModelFrame(formula, df)\n X = ModelMatrix(model_frame).m\n y = response(model_frame)\n\n # perform f-test\n fit(FTestModel, X, y, levels)\nend\n", "meta": {"hexsha": "3be69b5e0d4cfdae322b739591f7641d4e698a2e", "size": 3645, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ftest.jl", "max_stars_repo_name": "i-kiwamu/StatisticalTests.jl", "max_stars_repo_head_hexsha": "9dfce365ed961b1365f4effc6644081fe3611216", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-10T19:11:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T19:11:18.000Z", "max_issues_repo_path": "src/ftest.jl", "max_issues_repo_name": "i-kiwamu/StatisticalTests.jl", "max_issues_repo_head_hexsha": "9dfce365ed961b1365f4effc6644081fe3611216", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ftest.jl", "max_forks_repo_name": "i-kiwamu/StatisticalTests.jl", "max_forks_repo_head_hexsha": "9dfce365ed961b1365f4effc6644081fe3611216", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1390728477, "max_line_length": 90, "alphanum_fraction": 0.5936899863, "num_tokens": 1186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541643004809, "lm_q2_score": 0.8633916222765627, "lm_q1q2_score": 0.8130163165388732}} {"text": "\"\"\"\nFile: Kmeans.jl\nAuthors: Reese Pathak, Stephen Boyd\n\nK-means implementation in Julia\n\nParameters:\n list_of_vectors - The vectors to cluster, represented as an array of N n-vectors\n (N column vectors of length n).\n k - The number of clusters (defaults to 2)\n\nReturns:\n representatives - The cluster representatives represented as an array of k\n column vectors of length n.\n labels - An array of N cluster assignments in the same order as data,\n so that the 1st data point's cluster assignment is labels[i].\n The labels themselves index into the representatives list,\n i.e. representatives[labels[1]] returns the first data\n point's representative.\n losses - An array containing the value of J at each iteration.\n\"\"\"\n\nmodule K_means\n\nexport k_means\n\nfunction k_means(list_of_vectors; k=2, epsilon=1e-6)\n losses = Float64[] # array of losses\n # initialize representatives and assignments\n representatives, assignments = initialize_representatives(list_of_vectors, k)\n while has_not_converged(losses, epsilon)\n assignments = partition_data(list_of_vectors, representatives)\n representatives = update_representatives(list_of_vectors, assignments,\n k, representatives)\n push!(losses, loss(list_of_vectors, representatives, assignments))\n end\n return representatives, assignments, losses\nend\n\nfunction has_not_converged(losses, epsilon)\n return !(length(losses) >= 2 && abs(losses[end] - losses[end-1]) <= epsilon)\nend\n# Assigns each data point to the closest representative\nfunction partition_data(data, representatives)\n labels = Int[]\n for i in 1:length(data)\n # calculate the euclidean distance from the ith data point to each representative\n representative_distances = pairwise_distance(data[i], representatives)\n # find the representative closest to the ith data point (argmin)\n distance, representative_index = findmin(representative_distances)\n push!(labels, representative_index)\n end\n return labels\nend\n\n# Calculates each representative as the mean of it's data points\nfunction update_representatives(data, labels, k, old_representatives)\n representatives = []\n for i = 1:k\n # get the data points assigned to the representative\n representative_pts = data[labels .== i]\n # if the representative has assigned data points, set it to be their mean\n if length(representative_pts) > 0\n push!(representatives, mean(representative_pts))\n else # otherwise, leave it alone\n push!(representatives, old_representatives[i])\n end\n end\n return representatives\nend\n\n# Calculates the loss (J) of the given clustering.\nfunction loss(data, representatives, assignments)\n N = length(data)\n J = 0.0\n for i = 1:N\n J += norm(data[i] - representatives[assignments[i]])^2\n end\n return J*(1/N)\nend\n\nfunction initialize_representatives(data, k)\n N = length(data)\n n = length(data[1])\n labels = rand(1:k,N)\n representatives = update_representatives(data, labels, k, [zeros(n) for i=1:k])\n return representatives, labels\nend\n\n# Calculates the Eudclidean distance between vector and each vectors in 'vectors',\n# returning an array.\nfunction pairwise_distance(vector, list_of_vectors)\n return Float64[norm(vector - list_of_vectors[i])\n for i=1:length(list_of_vectors)]\nend\n\nend\n", "meta": {"hexsha": "aec81fdfec5ee13b6b13593843eb7790290b886b", "size": 3461, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Kmeans.jl", "max_stars_repo_name": "reesepathak/mma-functions", "max_stars_repo_head_hexsha": "724e65608faf9da5038606555f4ae964c8ecd997", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Kmeans.jl", "max_issues_repo_name": "reesepathak/mma-functions", "max_issues_repo_head_hexsha": "724e65608faf9da5038606555f4ae964c8ecd997", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Kmeans.jl", "max_forks_repo_name": "reesepathak/mma-functions", "max_forks_repo_head_hexsha": "724e65608faf9da5038606555f4ae964c8ecd997", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-08T11:04:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-08T11:04:54.000Z", "avg_line_length": 35.3163265306, "max_line_length": 85, "alphanum_fraction": 0.709043629, "num_tokens": 769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526934, "lm_q2_score": 0.880797085800514, "lm_q1q2_score": 0.8130102004044927}} {"text": "export rand, Ginibre\nimport Base.rand\n\n#Samples a matrix from the Ginibre ensemble\n#This ensemble lives in GL(N, F), the set of all invertible N x N matrices\n#over the field F\n#For beta=1,2,4, F=R, C, H respectively\nstruct Ginibre <: ContinuousMatrixDistribution\n beta::Float64\n N::Integer\nend\n\nfunction rand(W::Ginibre)\n beta, n = W.beta, W.N\n if beta==1\n randn(n,n)\n elseif beta==2\n randn(n,n)+im*randn(n,n)\n elseif beta==4\n Q0=randn(n,n)\n Q1=randn(n,n)\n Q2=randn(n,n)\n Q3=randn(n,n)\n [Q0+im*Q1 Q2+im*Q3;-Q2+im*Q3 Q0-im*Q1]\n else \n error(string(\"beta = \", beta, \" not implemented\"))\n end\nend\n\nfunction jpdf(Z::AbstractMatrix{z}) where {z<:Complex}\n pi^(size(Z,1)^2)*exp(-trace(Z'*Z))\nend\n\n#Dyson Circular orthogonal, unitary and symplectic ensembles\nstruct CircularOrthogonal\n N :: Int64\nend\n\nfunction rand(M::CircularOrthogonal)\n U = rand(Ginibre(2, M.N))\n U * U'\nend\n\nstruct CircularUnitary\n N :: Int64\nend\n\nrand(M::CircularUnitary) = rand(Ginibre(2, M.N))\n\nstruct CircularSymplectic\n N :: Int64\nend\n\nrand(M::CircularSymplectic) = error(\"Not implemented\")\n\n", "meta": {"hexsha": "c921396681639a0e65990d6866ed4326307660d3", "size": 1157, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Ginibre.jl", "max_stars_repo_name": "shashi/RandomMatrices.jl", "max_stars_repo_head_hexsha": "603b9e9acd95133839e804d6ef068cdfee4cbbfb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 56, "max_stars_repo_stars_event_min_datetime": "2017-09-29T08:46:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T10:05:30.000Z", "max_issues_repo_path": "src/Ginibre.jl", "max_issues_repo_name": "shashi/RandomMatrices.jl", "max_issues_repo_head_hexsha": "603b9e9acd95133839e804d6ef068cdfee4cbbfb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 29, "max_issues_repo_issues_event_min_datetime": "2017-08-18T19:50:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-15T08:08:44.000Z", "max_forks_repo_path": "src/Ginibre.jl", "max_forks_repo_name": "shashi/RandomMatrices.jl", "max_forks_repo_head_hexsha": "603b9e9acd95133839e804d6ef068cdfee4cbbfb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2018-01-05T22:05:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-02T20:25:41.000Z", "avg_line_length": 20.6607142857, "max_line_length": 74, "alphanum_fraction": 0.6473638721, "num_tokens": 378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517028006208, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.812909831201361}} {"text": "# Random number generators for Julia\r\n# This is a slightly modified and reduced version of a Julia module by John D. Cook.\r\n# http://www.johndcook.com/julia_rng.html\r\n\r\nmodule Random\r\n\r\ninverse_gamma(shape, rate) = 1/gamma(shape, rate)\r\n\r\nfunction gamma(shape, rate)\r\n # Return a random sample from a gamma distribution\r\n # with pdf \\propto x^{shape-1}exp(-rate*x)\r\n\r\n if shape <= 0.0\r\n error(\"Shape parameter must be positive, but shape = $shape\")\r\n end\r\n if rate <= 0.0\r\n error(\"Rate parameter must be positive, but rate = $rate\")\r\n end\r\n \r\n ## Implementation based on \"A Simple Method for Generating Gamma Variables\"\r\n ## by George Marsaglia and Wai Wan Tsang. \r\n ## ACM Transactions on Mathematical Software\r\n ## Vol 26, No 3, September 2000, pages 363-372.\r\n\r\n if shape >= 1.0\r\n d = shape - 1.0/3.0\r\n c = 1.0/sqrt(9.0*d)\r\n while true\r\n x = randn()\r\n v = 1.0 + c*x\r\n while v <= 0.0\r\n x = randn()\r\n v = 1.0 + c*x\r\n end\r\n v = v*v*v\r\n u = rand()\r\n xsq = x*x\r\n if u < 1.0 -.0331*xsq*xsq || log(u) < 0.5*xsq + d*(1.0 - v + log(v))\r\n return d*v/rate\r\n end\r\n end\r\n else\r\n g = gamma(shape+1.0, 1.0)\r\n w = rand()\r\n return g*(w^(1.0/shape))/rate\r\n end\r\nend\r\n\r\n## return a random sample from a chi square distribution\r\n## with the specified degrees of freedom\r\nfunction chi_square(dof)\r\n return gamma(0.5*dof, 0.5)\r\n # This was corrected from gamma(0.5, 2.0*dof) in the original code\r\nend\r\n\r\n## return a random sample from a beta distribution\r\nfunction beta(a, b)\r\n if (a <= 0) || (b <= 0)\r\n error(\"Beta parameters must be positive\")\r\n end\r\n \r\n ## There are more efficient methods for generating beta samples.\r\n ## However such methods are a little more efficient and much more complicated.\r\n ## For an explanation of why the following method works, see\r\n ## http://www.johndcook.com/distribution_chart.html#gamma_beta\r\n\r\n u = gamma(a, 1.0)\r\n v = gamma(b, 1.0)\r\n return u / (u + v)\r\nend\r\n\r\nend\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "e2745c70e7b098078c270f8219d107ebaf28dc84", "size": 2189, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Random.jl", "max_stars_repo_name": "dicai/BayesianMixtures.jl", "max_stars_repo_head_hexsha": "4b71c07b79908891f74aed76f57d4493290c9e63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Random.jl", "max_issues_repo_name": "dicai/BayesianMixtures.jl", "max_issues_repo_head_hexsha": "4b71c07b79908891f74aed76f57d4493290c9e63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Random.jl", "max_forks_repo_name": "dicai/BayesianMixtures.jl", "max_forks_repo_head_hexsha": "4b71c07b79908891f74aed76f57d4493290c9e63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4285714286, "max_line_length": 85, "alphanum_fraction": 0.5637277296, "num_tokens": 609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250327, "lm_q2_score": 0.8774767842777551, "lm_q1q2_score": 0.8128100149524436}} {"text": "#' ---\n#' title: Facility Location\n#' ---\n\n#' **Originally Contributed by**: Mathieu Tanneau and Alexis Montoison\n\n#+\nusing Random\nusing LinearAlgebra\n\nusing JuMP\nimport GLPK\nusing Plots\n\n#' ## Uncapacitated facility location\n\n#' ### Problem description\n#' \n#' We are given\n#' * $M=\\{1, \\dots, m\\}$ clients\n#' * $N=\\{ 1, \\dots, n\\}$ sites where a facility can be built\n#' \n#' **Decision variables**\n#' Decision variables are split into two categories:\n#' * Binary variable $y_{j}$ indicates whether facility $j$ is built or not\n#' * Binary variable $x_{i, j}$ indicates whether client $i$ is assigned to facility $j$\n#' \n#' **Objective**\n#' The objective is to minimize the total cost of serving all clients.\n#' This costs breaks down into two components:\n#' * Fixed cost of building a facility.\n#' In this example, this cost is $f_{j} = 1, \\ \\forall j$.\n#' * Cost of serving clients from the assigned facility.\n#' In this example, the cost $c_{i, j}$\n#' of serving client $i$ from facility $j$\n#' is the Euclidean distance between the two.\n#' \n#' **Constraints**\n#' * Each customer must be served by exactly one facility\n#' * A facility cannot serve any client unless it is open\n\n#' ### MILP formulation\n#' \n#' The problem can be formulated as the following MILP:\n#' \n#' \\begin{align}\n#' \\min_{x, y} \\ \\ \\ &\n#' \\sum_{i, j} c_{i, j} x_{i, j} + \n#' \\sum_{j} f_{j} y_{j}\\\\\n#' s.t. &\n#' \\sum_{j} x_{i, j} = 1, && \\forall i \\in M\\\\\n#' & x_{i, j} \\leq y_{j}, && \\forall i \\in M, j \\in N\\\\\n#' & x_{i, j}, y_{j} \\in \\{0, 1\\}, && \\forall i \\in M, j \\in N\n#' \\end{align}\n#' \n#' where the first set of constraints ensures\n#' that each client is served exactly once,\n#' and the second set of constraints ensures\n#' that no client is served from an unopened facility.\n\n#' ### Problem data\n\n#+\nRandom.seed!(314)\n\nm = 12 # number of clients\nn = 5 # number of facility locations\n\n# Clients' locations\nXc = rand(m)\nYc = rand(m)\n\n# Facilities' potential locations\nXf = rand(n)\nYf = rand(n)\n\n# Fixed costs\nf = ones(n);\n\n# Distance\nc = zeros(m, n)\nfor i in 1:m\n for j in 1:n\n c[i, j] = norm([Xc[i] - Xf[j], Yc[i] - Yf[j]], 2)\n end\nend\n\n#+\n# Display the data\nscatter(Xc, Yc, label = \"Clients\", markershape=:circle, markercolor=:blue)\nscatter!(Xf, Yf, label=\"Facility\", \n markershape=:square, markercolor=:white, markersize=6,\n markerstrokecolor=:red, markerstrokewidth=2\n)\n\n#' ### JuMP implementation\n\n#+\n# Create a JuMP model\nufl = Model(GLPK.Optimizer)\n\n# Variables\n@variable(ufl, y[1:n], Bin);\n@variable(ufl, x[1:m, 1:n], Bin);\n\n# Each client is served exactly once\n@constraint(ufl, client_service[i in 1:m],\n sum(x[i, j] for j in 1:n) == 1\n);\n\n# A facility must be open to serve a client\n@constraint(ufl, open_facility[i in 1:m, j in 1:n],\n x[i, j] <= y[j]\n)\n\n# Objective\n@objective(ufl, Min, f'y + sum(c .* x));\n\n#+\n# Solve the uncapacitated facility location problem with GLPK\noptimize!(ufl)\nprintln(\"Optimal value: \", objective_value(ufl))\n\n\n#' ### Visualizing the solution\n\n#+\n# The threshold 1e-5 ensure that edges between clients and facilities are drawn when x[i, j] ≈ 1.\nx_ = value.(x) .> 1 - 1e-5\ny_ = value.(y) .> 1 - 1e-5\n\n# Display clients\np = scatter(Xc, Yc, markershape=:circle, markercolor=:blue, label=nothing)\n\n# Show open facility\nmc = [(y_[j] ? :red : :white) for j in 1:n]\nscatter!(Xf, Yf, \n markershape=:square, markercolor=mc, markersize=6,\n markerstrokecolor=:red, markerstrokewidth=2,\n label=nothing\n)\n\n# Show client-facility assignment\nfor i in 1:m\n for j in 1:n\n if x_[i, j] == 1\n plot!([Xc[i], Xf[j]], [Yc[i], Yf[j]], color=:black, label=nothing)\n end\n end\nend\n\ndisplay(p)\n\n\n#' ## Capacitated Facility location\n\n#' ### Problem formulation\n#' \n#' The capacitated variant introduces a capacity constraint on each facility, i.e., clients have a certain level of demand to be served, while each facility only has finite capacity which cannot be exceeded.\n#' \n#' Specifically, let\n#' * $a_{i} \\geq 0$ denote the demand of client $i$\n#' * $q_{j} \\geq 0$ denote the capacity of facility $j$\n#' \n#' The capacity constraints then write\n#' \\begin{align}\n#' \\sum_{i} a_{i} x_{i, j} &\\leq q_{j} y_{j} && \\forall j \\in N\n#' \\end{align}\n#' \n#' Note that, if $y_{j}$ is set to $0$, the capacity constraint above automatically forces $x_{i, j}$ to $0$.\n\n#' Thus, the capacitated facility location can be formulated as follows\n#'\n#' \\begin{align}\n#' \\min_{x, y} \\ \\ \\ &\n#' \\sum_{i, j} c_{i, j} x_{i, j} + \n#' \\sum_{j} f_{j} y_{j}\\\\\n#' s.t. &\n#' \\sum_{j} x_{i, j} = 1, && \\forall i \\in M\\\\\n#' & \\sum_{i} a_{i} x_{i, j} \\leq q_{j} y_{j}, && \\forall j \\in N\\\\\n#' & x_{i, j}, y_{j} \\in \\{0, 1\\}, && \\forall i \\in M, j \\in N\n#' \\end{align}\n#'\n#' For simplicity, we will assume that there is enough capacity to serve the demand,\n#' i.e., there exists at least one feasible solution.\n\n#+\n# Demands\na = rand(1:3, m);\n\n# Capacities\nq = rand(5:10, n);\n\n#+\n# Display the data\nscatter(Xc, Yc, label=nothing,\n markershape=:circle, markercolor=:blue, markersize= 2 .*(2 .+ a)\n)\n\nscatter!(Xf, Yf, label=nothing, \n markershape=:rect, markercolor=:white, markersize= q,\n markerstrokecolor=:red, markerstrokewidth=2\n)\n\n#' ### JuMP implementation\n\n#+\n# Create a JuMP model\ncfl = Model(GLPK.Optimizer)\n\n# Variables\n@variable(cfl, y[1:n], Bin);\n@variable(cfl, x[1:m, 1:n], Bin);\n\n# Each client is served exactly once\n@constraint(cfl, client_service[i in 1:m], sum(x[i, :]) == 1)\n\n# Capacity constraint\n@constraint(cfl, capacity, x'a .<= (q .* y))\n\n# Objective\n@objective(cfl, Min, f'y + sum(c .* x));\n\n#+\n# Solve the problem\noptimize!(cfl)\nprintln(\"Optimal value: \", objective_value(cfl))\n\n#' ### Visualizing the solution\n\n#+\n# The threshold 1e-5 ensure that edges between clients and facilities are drawn when x[i, j] ≈ 1.\nx_ = value.(x) .> 1 - 1e-5\ny_ = value.(y) .> 1 - 1e-5\n\n# Display the solution\np = scatter(Xc, Yc, label=nothing,\n markershape=:circle, markercolor=:blue, markersize= 2 .*(2 .+ a)\n)\n\nmc = [(y_[j] ? :red : :white) for j in 1:n]\nscatter!(Xf, Yf, label=nothing, \n markershape=:rect, markercolor=mc, markersize=q,\n markerstrokecolor=:red, markerstrokewidth=2\n)\n\n# Show client-facility assignment\nfor i in 1:m\n for j in 1:n\n if x_[i, j] == 1\n plot!([Xc[i], Xf[j]], [Yc[i], Yf[j]], color=:black, label=nothing)\n break\n end\n end\nend\n\ndisplay(p)\n\n\n#' ## Further\n#' * [Benders decomposition](https://github.com/JuliaOpt/JuMPTutorials.jl/blob/master/script/optimization_concepts/benders_decomposition.jl)\n#' is a method of choice for solving facility location problems.\n#' * Benchmark instances can be found\n#' [here](https://resources.mpi-inf.mpg.de/departments/d1/projects/benchmarks/UflLib/).\n", "meta": {"hexsha": "e054e097a4785445282ee00720ceb14b37742589", "size": 6709, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/modelling/facility_location.jl", "max_stars_repo_name": "ferrolho/JuMPTutorials.jl", "max_stars_repo_head_hexsha": "3e50e6f12d0542fd598d1cdbe0c602a6ae5ea271", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 75, "max_stars_repo_stars_event_min_datetime": "2020-06-15T13:05:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T12:58:48.000Z", "max_issues_repo_path": "script/modelling/facility_location.jl", "max_issues_repo_name": "ferrolho/JuMPTutorials.jl", "max_issues_repo_head_hexsha": "3e50e6f12d0542fd598d1cdbe0c602a6ae5ea271", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34, "max_issues_repo_issues_event_min_datetime": "2019-05-27T05:36:48.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-22T09:52:29.000Z", "max_forks_repo_path": "script/modelling/facility_location.jl", "max_forks_repo_name": "mthelm85/JuMPTutorials.jl", "max_forks_repo_head_hexsha": "b2285a74d05dc0c0e99df2ac999277c34e670afd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2019-10-09T09:32:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-02T17:41:21.000Z", "avg_line_length": 25.3169811321, "max_line_length": 207, "alphanum_fraction": 0.6412282009, "num_tokens": 2199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037221561136, "lm_q2_score": 0.8774767794716264, "lm_q1q2_score": 0.8128100069301267}} {"text": "function incident_field(D, f, n, gridL, cellL)\n ω = 2π * f\n k = n * ω\n\n function efield(x, y)\n r = √(x^2 + y^2 + D^2)\n ℯ ^ (k * r * im) / (4π * r)\n end\n\n grid = range(-gridL/2 + 1/2, gridL/2 - 1/2, length = gridL) .* cellL\n [efield(x, y) for x in grid, y in grid]\nend\n\n\"\"\"\n greens(D, f, ϵ, μ, gridL, cellL)\n\nReturns the Green's function for\nthe near to far transformation.\n\n# Arguments\n- `D`: distance between near and far plane\n- `f`: frequency\n- `ϵ`: relative permittivity\n- `μ`: relative permeability\n- `gridL`: side length of E-field grid (in cells)\n- `cellL`: length of each cell of grid\n\"\"\"\nfunction greens(D, f, ϵ, μ, gridL, cellL)\n ω = 2π * f\n n = √(ϵ*μ)\n k = n * ω\n\n function efield(x, y)\n r = √(x^2 + y^2 + D^2)\n D * (-1 + k * r * im) * ℯ ^ (k * r * im) / (4 * π * r^3)\n end\n\n gridout = range(-gridL, gridL - 1, length = gridL * 2) .* cellL\n g = [efield(x, y) * -μ / ϵ for x in gridout, y in gridout]\n\n g\nend\n", "meta": {"hexsha": "7ce489ff299c2e7b0bc6023573d7d7b4a89be159", "size": 992, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/fields.jl", "max_stars_repo_name": "gaurav-arya/WavePropagation.jl", "max_stars_repo_head_hexsha": "a547e657fcc2ea68d87f35d22f42f3358a352bf2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/fields.jl", "max_issues_repo_name": "gaurav-arya/WavePropagation.jl", "max_issues_repo_head_hexsha": "a547e657fcc2ea68d87f35d22f42f3358a352bf2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fields.jl", "max_forks_repo_name": "gaurav-arya/WavePropagation.jl", "max_forks_repo_head_hexsha": "a547e657fcc2ea68d87f35d22f42f3358a352bf2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0697674419, "max_line_length": 72, "alphanum_fraction": 0.5322580645, "num_tokens": 397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632302488963, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.812808151375337}} {"text": "module GeneralizedCRT\n\nexport crt\nusing Base.Threads\nimport Base.Threads.@spawn\n\nconst THRESHOLD1 = 7 # split longer input arrays to use binary instead of sequential algo\nconst THRESHOLD2 = 15 # split longer input arrays to different cpu threads\n\n\"\"\"\n crt(a, b, p, q)\n\nGiven `0 <= a < p` and `0 <= b < q` with `a == b mod(gcd(p, q)`\nreturn unique solution `x ≡ a mod p` and `x ≡ b mod q` \nwith `0 <= x < lcm(p, q)`.\n\nReturn `x, lcm(p, q)`.\n\"\"\"\nfunction crt(a::A, b::B, p::C, q::D) where {A,B,C,D}\n crt(promote(a, b, p, q)...)\nend\n\nfunction crt(a::T, b::T, p::T, q::T) where T\n c, u = gcdx(p, q)\n q1 = div(q, c)\n u = mod(u, q1)\n iszero(mod(b - a, c)) || throw(ArgumentError(\"remainders must have same rest when diveded by ($a, $b, gcd($p, $q))\"))\n bac = div(b - a, c)\n x = mod(bac * u, q1) * p + a\n lcm = Base.checked_mul(p, q1)\n return x, lcm\nend\n\nfunction crt(ap::AbstractVector{<:Tuple{<:Integer,<:Integer}})\n crt([x[1] for x in ap], [x[2] for x in ap])\nend\ncrt(t::Tuple{S,T}...) where {S<:Integer,T<:Integer} = crt(collect(t))\n\n\"\"\"\n crt(a::Vector, m::Vector; nthreads, splitstreads, splitbinary)\n\nGiven `0 <= a[i] < p[i] for all i` with `a[i] == a[j] mod(gcd(p[i], p[j]) for i != j`,\nreturn unique solution `x ≡ a[i] mod p[i] for all i`\nwith `0 <= x < lcm(p, q)`.\n\nOptional arguments:\nUse `nthreads=nthreads()` threads if `length(a) > splitthreads=($THRESHOLD2)`.\nUse binary algorithm is `length(a) > splitbinary=($THRESHOLD1)`.\n\nReturn `x, lcm(p, q)`.\n\"\"\"\nfunction crt(a::AbstractVector{T}, m::AbstractVector{S}; nt=nthreads()-1, splitthreads=THRESHOLD2, splitbinary=THRESHOLD1) where {S,T}\n # split input array and execute in parallel threads\n n = length(a)\n n == length(m) || throw(ArgumentError(\"vectors of same size required\"))\n if nt <= 1 || n <= splitthreads\n crts(a, m; splitbinary)\n else\n nt = max(nt, nthreads() - 1)\n R = promote_type(S, T)\n ni = max(n ÷ nt, 2)\n nt = (n + ni - 1) ÷ ni\n tasks = Vector{Any}(undef, nt)\n n2 = 0\n nth = nt\n for i = 1:nt\n n1 = n2 + 1\n n2 = n2 + (n - n2) ÷ nth\n nth -= 1\n av = view(a, n1:n2)\n mv = view(m, n1:n2)\n tasks[i] = @spawn crts($av, $mv; splitbinary=$splitbinary)\n end\n a0 = Vector{R}(undef, nt)\n m0 = Vector{R}(undef, nt)\n for i = 1:nt\n res = try\n fetch(tasks[i])\n catch ex\n ex isa TaskFailedException ? throw(ex.task.result) : rethrow()\n end\n a0[i] = first(res)\n m0[i] = last(res)\n end\n x, l = crt(a0, m0)\n x, l\n end\nend\n\n# split input array in halves a recombine output\nfunction crts(a::AbstractVector{T}, m::AbstractVector{S}; splitbinary) where {S,T}\n n = length(a)\n n == length(m) || throw(ArgumentError(\"vectors of same size required\"))\n if n <= max(splitbinary, 3)\n crtm(a, m)\n else\n n2 = (n + 1) ÷ 2\n xI, lcmI = crts(view(a,1:n2), view(m, 1:n2); splitbinary)\n xJ, lcmJ = crts(view(a, n2+1:n), view(m, n2+1:n); splitbinary)\n crt(xI, xJ, lcmI, lcmJ)\n end\nend\n\n# process input array sequentially\nfunction crtm(a::AbstractVector{T}, m::AbstractVector{S}) where {S,T}\n n = length(a)\n # println(\"crtm($n, $(length(m)))\")\n n == length(m) || throw(ArgumentError(\"vectors of same size required\"))\n R = promote_type(S, T)\n n == 0 && return zero(R), one(R)\n xI, lcmI = promote(a[1], m[1])\n xI = _mod(xI, lcmI)\n for i = 2:n\n xI, lcmI = crt(xI, _mod(a[i], m[i]), lcmI, m[i])\n end\n xI, lcmI\nend\n\n_mod(a, b) = 0 <=a < b ? oftype(b, a) : mod(a, b)\n\nend # module\n", "meta": {"hexsha": "8170837d873e2ec61f98283ba35a86ec6390b7e5", "size": 3710, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/GeneralizedCRT.jl", "max_stars_repo_name": "KlausC/GeneralizedCRT.jl", "max_stars_repo_head_hexsha": "cc69f64054bab68839c72ff29756df18b3b36ae5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/GeneralizedCRT.jl", "max_issues_repo_name": "KlausC/GeneralizedCRT.jl", "max_issues_repo_head_hexsha": "cc69f64054bab68839c72ff29756df18b3b36ae5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GeneralizedCRT.jl", "max_forks_repo_name": "KlausC/GeneralizedCRT.jl", "max_forks_repo_head_hexsha": "cc69f64054bab68839c72ff29756df18b3b36ae5", "max_forks_repo_licenses": ["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.4098360656, "max_line_length": 134, "alphanum_fraction": 0.5522911051, "num_tokens": 1270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632261523028, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.8128081443384488}} {"text": "\n## Things outside of the module won't get run when using the package.\n\n#You can create vectors of random normals.\nx = randn(40);\nx'\n# Adding the semicolon to the end hides the output.\n# Vectors are column vectors by default, which take up a good chunk of screen.\n# So often it's nicer to tranpose them.\n\n#You index into arrays with brackets, like in R\nx[3]\nx[end]\nx[2:5]\nx[end-4:end-1]\nx[36:end-1]\n\n#You also index into strings that way.\ngreeting = \"Hello world!\"\ngreeting[3:4]\ngreeting[7:end-1]\n\n#Or arrays of random uniforms.\nu = rand(3,2,2)\nu[:,:,1]\n\n#Standard syntax for randomly sampling is to call rand on the thing you want to sample from.\nrand(1:4, 10)\n\nusing Distributions\ngamma_3_3 = Gamma(3, 3)\nrand(gamma_3_3, 2, 4)\n\n#Julia Arrays are like the arrays/vectors/matrices of R. They will also automatically promote\n[3f0 4.0 2 π]\n\n#The individual elements were\n3f0 |> typeof\n4.0 |> typeof\n2 |> typeof\nπ |> typeof\n#Note that pi is an irrational number! It automatically converts to whatever you want it to be.\n2π\n2π |> typeof\nbig(2)π\nbig(2)π |> typeof\n# |> is the pipe operator in Julia.\n# However, it isn't as powerful or fancy as magrittr's \"%>%\".\n# You can look at Lazy.jl if you want more piping options.\n\n#In \"R\" a scalar is really a length 1 vector.\n#In julia, they are clearly distinct.\nscalar4double = 4.0\nzerodim4double = fill(4.0)\nvector4double = fill(4.0, 1)\nmatrix4double = fill(4.0, 1, 1)\ndim3array4double = fill(4.0, 1, 1, 1)\n\n#They all print differently, but there's also a fundamental difference under the hood.\nisbits(scalar4double)\nisbits(zerodim4double)\nisbits(vector4double)\n\n#Q: Are only numbers bits?\nisbits(gamma_3_3)\n\n#\"isbits\" is low level, referring to how the memory is handled under the hood.\n#\"isbits\" types are raw, they're handled directly, and an array of them will be one solid chunk of memory.\n# This makes them \n#If something is not bits, that normally means it \n#Why would we ever want a zero dim array?\nfunction f!(a::Number)\n a = 2.1\nend\nfunction f!(a::AbstractArray)\n a[:] = 2.1\nend\nf!(scalar4double)\nscalar4double\nf!(zerodim4double)\nzerodim4double\nf!(dim3array4double)\ndim3array4double\n\n# In Julia, variables are not copied.\n# The first f! replaced the input number with another number, but the original scalar4double remained bound to 4\n# The second f! modified the contents of the arrays\n# The arrays stayed the same, but the contents changed.\n# Be weary!\nzerodim2 = zerodim4double\nzerodim2[] = 17.0\nzerodim2\nzerodim4double\n# Julia does not copy unless you ask it to!\n# \"=\" binds a new name to the old variable.\nzerodim3 = copy(zerodim2)\nzerodim3[] = 9.4\nzerodim2\nzerodim3\n\n# It is convention in Julia that whenever a function has side effects -- whenever it modifies inputs\n# to end that function name with a \"bang\"!\n# The mutated arguments are also placed first.\ncopy!(zerodim2, zerodim3)\nzerodim2\nfill!(zerodim2, -1e9)\nzerodim4double\n\n# Also, adding commas makes a column vector.\n[3f0, 4.0, 2, π]\n# For a matrix\n[ 1 2 3 ; 4 5 6]\nreshape(1:6, 2, 3)\n# Note the differences! Order, and\n# In Julia, ranges are lazy -- even when reshaped.\n\n# Also, the colon operator also has low priority.\n# What is this in R?\n# using RCall\n3*1:5+7\n10:3:22\n10:3:22 |> collect\n\n# R is a lazy language, which is great.\n# Julia is eager, but many functions and operations are implemented to be lazy.\n# Array slices can also be lazy\n@views x[4:7]\n# On Julia 0.7, transposing matrices is also lazy. Not yet on 0.6.\n\n\n#If Julia can't promote them all to the same type, it'll give up and create a vector that can hold anything.\n[ 42im 9//2 \"fish\" π ]\n#This isn't a good idea. Don't that.\n\n\n#You can also create undefined arrays. Be cautious, they may contain NaNs, which can infect code if you're not careful!\nArray{Float64}(4, 12)\n\n#Or fill\nfill(1.2, 4, 7)\nfill(gamma_3_3, 2, 4)\n\n#Or if you just want zeros\nzeros(4,7)\nzeros(Int, 4, 7)\n\n\n\n#You can also use comprehensions. Remember x earlier?\nx'\n#Lets use it to create a design matrix!\nX = [xᵢ^j for xᵢ ∈ x, j ∈ 0:4]\n\n#Lets create some fake data! First, lets get a true beta:\nβ_true = [2, 3, -5, -2, 1.2]\n\n#And then add a little noise\ny = X * β_true .+ 0.1randn(40)\n\nβ_hat = X \\ y\n\n# \"\\\" is the left devision operator.\n# It just means use the thing on the left to divide the thing on the right\n2 \\ 4\n# If we tranpose both X and y, we can get dimensions to line up for a right division\ny' / X'\n\n\n# This is of course equivalent to what we're all used to:\ninv(X' * X) * X' * y\n\n# Realstically, we'd always prefer to just use LM and immediately get convenient summary statistics.\nusing DataFrames, GLM\ndf = DataFrame(x = x, x² = X[:,3], x³ = X[:,4], x⁴ = X[:,5], y = y)\nOLS = glm(@formula(y ~ x + x² + x³ + x⁴), df, Normal(), IdentityLink())\n\n\n# There are three ways to define functions.\n# For an anonymous function, use [arguments] -> [function body]\n# For example, if we want a random positive definite matrix\nΣ = randn(20,5) |> x -> x' * x\n\n# If we have more than one argument, we need to wrap them in a parenthesis.\nanon = (a, b) -> sin(a) - exp(b)\nanon(2, 3)\n\n# We can overwrite anon with anything.\nanon = 4\n\n# If we create a proper named function, we cannot replace it with something other than a function.\nf(a) = 2a\nf(4)\nf = 3\nf(a) = 3a\nf(4)\nf(a::Int) = \"Hello world!\"\nf(a, b) = 3a + 2b\nf(4)\nf(4.0)\nf(4, -5)\n\n# Julia uses multiple dispatch.\n# Julia compiles a different specialized version of that function for each combination of types you give it.\n# It then calls the type matching that combination.\n# This also lets you define a different body for the types if you want to.\n# That is, Julia compiles 4 separate functions for \"f\" when we do this:\nf(4, -5)\nf(4.0, -5)\nf(4, -5.0)\nf(4.0, -5.0)\n# And chooses the correct version to use.\n# If we want the compiled function to act differently, we can then give Julia a different function body to use for that type\n# Just like we did for \"Hellow world!\" above\n# For example:\nf(X, β_hat) #Error, dimensions don't line up!\nf(a::Matrix, b::Vector) = b' * a' * a * b\nf(X, β_hat)\nf(4, -5) #Still works!\n# Similar to match.call() in R:\npair = (4,-5)\nf(pair...)\n\n# The long form just makes it easier to write multi-line functions.\n#@inline function f(x, y)\nfunction f(x, y)\n out = zero(promote_type(typeof(x), eltype(y)))\n for yᵢ ∈ y\n out += x * yᵢ\n end\n out\nend\n\n\n@code_llvm f(e, x)\n\n#This is a tuple. A tuple's type is partly defined by its length.\n@code_llvm f(e, (1.2, -9.5, 3.2, 37.2))\n(1.2, -9.5, 3.2, 37.2) |> typeof\n\n@code_llvm f(e, 2.3)\n@code_llvm f(2, 3)\n\nfunction g(f, a, b, c)\n f(a, b) + c\nend\n\n# f is automatically inlined at -O3, not at -O2.\ng(f, 2, 3, 4)\n@code_llvm g(f, 2, 3, 4)\n\n# In Julia, you end a scope or expression via \"end\".\nf(√2) #Does not have the irrational type! It's just taking the square root of 2.\n\n\n# R has \"single dispatch\", which is useful for things like plot, print, and summary methods.\n\n# A simple example why this is useful in Julia is so that we can use \"*\" for matrix multiplication.\n# There are a lot of different methods for \"*\"!\nmethods(*) |> length\n#Run just methods(*) if you want to see the full list!\n\n# This also makes code faster!\n# Compare\nS_big = randn(10_000, 5_000) |> x -> x' * x;\nX_big = randn(5_000, 5_000);\n@time S_big * X_big;\nusing Compat.LinearAlgebra #This line is currently unnecessary\n@time eigfact(S_big);\n# However, we know S is symmetric! What happens if we tell Julia that?\nS_big2 = Symmetric(S);\n@time S_big2 * X_big;\n@time eigfact(S_big2);\n\n#The using Compat.LinearAlgebra line is unnecassary in Julia 0.6\n#However, starting in Julia 0.7 you'll need \"using LinearAlgebra\"\n#Saying \"using Compat.LinearAlgebra\" works on both versions.\n\n# Give Julia more information, and it will automatically pick the best method!\n\n# Multiple dispatch is magical, because\n# a) It makes code easier to read. When you want to multiply, you use \"*\".\n# When you want an eigenfactorization, you use \"eigfact\".\n# No \"eigfact\" here, \"eigfact_symmetric\" there.\n# No map_int here and map_dbl there.\n\n# However, what if we actually want elementise multiplication from \"*\"?\n# In Julia, adding a \".\" automatically broadcosts.\n# A broadcast is like an apply or map statement, except it will line up dimensions.\n\n# Recall\nsize(X)\nsize(y)\ny' * X # Regular matrix-vector product.\nX .* y # Broadcast\n# Both X and y have 40 rows, so it lines these up\n# and then replicates y across each of X's 5 columns.\nX .* β_hat'\n# β_hat' is 1 x 5, so it lines up with X's 5 columns, and is replicated down the 40 rows.\nX .+ 2\n# Here, 2 gets replcicated along both colums and rows.\n\nX .* y' # Does not line up -> error\nX .* β_hat # Does not line up -> error\n\n# This works for any function.\nf.(X)\nf.(X, y)\n\n# If we use multiple ones, they will all fuse.\nf.(X, y) .* β_hat' .+ 2\n\n# Too many dots can be annoying to write. So Julia offers the macro \"@. \"\n@. f(X, y) * β_hat + 2\n\n# Whenever you see something with an \"@\" in Julia, it is a macro.\n# Macros edit your code. Think of them as non-standard evaluation in R.\n# Because they can do extremely weird things, they always have an \"@\" to let you know something funky is going on.\n# A basic example of non-standard evaluation in R is how a lot of functions know the name of the variables you give them.\n# Consider -- straight out of Advanced R:\n\"\nx <- seq(0, 2 * pi, length = 100)\nsinx <- sin(x)\nplot(x, sinx, type = \"l\")\n\"\n# Similarly:\n@show anon;\n# If you ever want to know what it is a macro does to your code, there's a macro for that!\n@macroexpand @show anon\n@macroexpand @. f(X, y) * β_hat + 2\n\n# We can see that \"@.\" does us the favor of adding \".\" to every function call for us.\n\n# We can get creative!\nbunch_o_gammas = @. Gamma(exp(f(X)), exp(-2y))\n\n# What is the meaning of this? Good question!\nmean.(bunch_o_gammas)\n# Maybe we want to do parametric bootstrap?\nsamples = rand.(bunch_o_gammas, 4000)\n\n# Method of Moment's estimator for Gamma\nfunction gammas_MoM(x)\n x̄ = mean(x)\n s² = var(x)\n x̄^2 / s², s² / x̄\nend\nmom_estimators = gammas_MoM.(samples)\nfunction relative_error( estimate, truth )\n @. ( estimate - truth ) / truth\nend\n#Relative errors\n@. relative_error(mom_estimators, params(bunch_o_gammas))\n\n#We can easily condense the steps\nN = 4000\n@. relative_error(gammas_MoM(rand(bunch_o_gammas, N)), params(bunch_o_gammas))\n\n\n\n### Some more array manipulations and fun with broadcasting!\n# Remember Σ from earlier?\nΣ\n# Let's take N samples from a multivariate normal with that as the covariance matrix, and mean:\nμ = 2.* randn(5)\n\nW = chol(Σ) * randn(5, N) .+ μ\n\nmean(W, 2)\ncov(W')\n# We can also recall the definition from multivariate\nS = (W .- mean(W,2)) |> x -> x * x' ./ (size(x,2)-1)\n#and see that it is a pretty good estimator\nΣ\n# The matrix and broadcast syntax makes it easy to weave together array manipulations\n# and apply definitions, like we see in Johnson and Wichern for the sample Covariance matrix.\n\n\n# Remember this?\n[ 42im 9//2 \"fish\" π ]\n# What if we do want to hold a bunch of different types?\n# One straightforward approach is to build our own container!\n\nabstract type four_objects{A,B,C,D} end\nstruct FourThings{A,B,C,D} <: four_objects{A,B,C,D}\n a::A\n b::B\n c::C\n d::D\nend\nfunction FourThings(a::A, b::B, c::C, d::D) where {A,B,C,D}\n FourThings{A,B,C,D}(a,b,c,d)\nend\nft1 = FourThings(42im, 9//2, \"fish\", π)\nisbits(ft1)\nft2 = FourThings(42, 9//2, 4f0, π)\nisbits(ft2)\nmutable struct FourMutableThings{A,B,C,D} <: four_objects{A,B,C,D}\n a::A\n b::B\n c::C\n d::D\nend\nft3 = FourMutableThings(42, 9//2, 4f0, π)\nisbits(ft3)\nstruct MyMatrix{T}\n a::T\n b::T\n c::T\n d::T\n e::T\n f::T\n g::T\n h::T\n i::T\n j::T\n k::T\n l::T\n m::T\n n::T\n o::T\n p::T\nend\n# Then, we get define our operations. For example, multiplication\nfunction Base.:*(x::MyMatrix{T}, y::four) where {T, A,B,C,D,four <: four_objects{A,B,C,D}}\n (\n x.a*y.a + x.e * y.b + x.i * y.c + x.m * y.d,\n x.b*y.a + x.f * y.b + x.j * y.c + x.n * y.d,\n x.c*y.a + x.g * y.b + x.k * y.c + x.o * y.d,\n x.d*y.a + x.h * y.b + x.l * y.c + x.p * y.d,\n )\nend\nv16 = randn(Float32, 16);\nm16 = reshape(v16, 4, 4);\nv4 = randn(Float32, 4);\nmm = MyMatrix(v16...)\nmm * ft2\nmm * ft3\nft4 = FourThings(v4...)\nft5 = FourMutableThings(v4...)\nm16 * v4\nmm * ft4\n\n# What do you expect their performance to be?\n# Built in multiplication, vs our own custom version?\nusing BenchmarkTools\n@benchmark $m16 * $v4\n@benchmark $mm * $ft2\n@benchmark $mm * $ft3\n@benchmark $mm * $ft4\n@benchmark $mm * $ft5\n# Now compare with Julia launched with -O3\n# This is why I like -O3\n\n# More cool features\nusing ForwardDiff\n\nForwardDiff.derivative(f, 2.3)\nForwardDiff.derivative(sin, 2.3)\ncos(2.3)\n", "meta": {"hexsha": "659790d078040f5c7a2426eb8e3bc62db9b39550", "size": 12665, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/DemoScript.jl", "max_stars_repo_name": "JuliaTagBot/IntroJuliaStatsDemo.jl", "max_stars_repo_head_hexsha": "0dfbb027334ae0772610bed971d65ee5ec33b20d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/DemoScript.jl", "max_issues_repo_name": "JuliaTagBot/IntroJuliaStatsDemo.jl", "max_issues_repo_head_hexsha": "0dfbb027334ae0772610bed971d65ee5ec33b20d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/DemoScript.jl", "max_forks_repo_name": "JuliaTagBot/IntroJuliaStatsDemo.jl", "max_forks_repo_head_hexsha": "0dfbb027334ae0772610bed971d65ee5ec33b20d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T10:55:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T10:55:19.000Z", "avg_line_length": 27.5326086957, "max_line_length": 124, "alphanum_fraction": 0.685353336, "num_tokens": 4092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096227509861, "lm_q2_score": 0.8872045892435128, "lm_q1q2_score": 0.812776661554818}} {"text": "module KernelLibrary\n\nexport linear_kernel, polynomial_kernel, laplacian_kernel, gaussian_kernel, anova_kernel, rbf_kernel, fractrbf_kernel, rationalquad_kernel, multiquad_kernel, invmultiquad_kernel, circular_kernel, spherical_kernel, wave_kernel\nexport power_kernel, log_kernel, spline_kernel, cauchy_kernel, chisquare_kernel, histintersect_kernel, genhistintersect_kernel, gentstudent_kernel, fourier_kernel, sigmoid_kernel, wavelet_kernel, transinvwavelet_kernel\n# Julia implementation of most of the kernel functions from\n# crsouza.blogspot.com/2010/03/kernel-functions-for-machine-learning.html\n\nfunction linear_kernel{T}(x::Array{T}, y::Vector{T}; c::Real=0.)\n\tc=convert(T,c)\n\t(y'*x .+ c)\nend\n\nfunction polynomial_kernel{T}(x::Array{T}, y::Vector{T}, d::Real; α::Real=1., c::Real=1.)\n\td=convert(T,d); α=convert(T,α); c=convert(T,c);\n\t(α.*(y'*x) .+ c).^ d\nend\n\nfunction laplacian_kernel{T}(x::Array{T}, y::Vector{T}, σ::Real)\n\tσ=convert(T, σ)\n\texp(-sum((x.-y).^2.,1).^.5 ./ σ)\nend\n\nfunction gaussian_kernel{T}(x::Array{T}, y::Vector{T}, σ::Real)\n\tσ=convert(T, σ)\n\texp(-sum((x.-y).^2,1) ./ 2*σ.^ 2)\nend\n\nfunction anova_kernel{T}(x::Array{T}, y::Vector{T}, σ::Real, d::Real)\n\td=convert(T,d); σ=convert(T, σ)\n\tsum(exp(-σ*(x.-y).^2).^d,1)\nend\n\nfunction rbf_kernel{T}(x::Array{T}, y::Vector{T}, σ::Real)\n\tσ=convert(T, σ)\n\texp(-sum(abs(x.-y),1) ./ 2*σ.^ 2)\nend\n\nfunction fractrbf_kernel{T}(x::Array{T}, y::Vector{T}, σ::Real, fract::Real)\n\tσ=convert(T, σ); fract=convert(T, fract); \n\texp(-sum(abs(x .- y).^fract,1).^(1/fract) ./ 2*σ.^ 2)\nend\n\nfunction rationalquad_kernel{T}(x::Array{T}, y::Vector{T}, c::Real)\n\tc = convert(T, c)\n\tn = sum((x.-y).^2,1)\n\t1 .- n./(n .+ c)\nend\n\nfunction multiquad_kernel{T}(x::Array{T}, y::Vector{T}, c::Real)\n\tc = convert(T, c)\n\tsqrt(sum((x.-y).^2,1) .+ c^2)\nend\n\nfunction invmultiquad_kernel{T}(x::Array{T}, y::Vector{T}, c::Real)\n\tc = convert(T, c)\n\t1 ./ sqrt(sum((x.-y).^2,1) .+ c^2)\nend\n\nfunction circular_kernel{T}(x::Array{T}, y::Vector{T}, σ::Real)\n\tσ=convert(T, σ)\n\tn = sqrt(sum((x.-y).^2,1))./σ\n\tout = (2/π).*(acos(-n) - n.*sqrt(1 .- n.^2))\n\tout[n.>=σ] = 0\n\tout\nend\n\nfunction spherical_kernel{T}(x::Array{T}, y::Vector{T}, σ::Real)\n\tσ=convert(T, σ)\n\tn = sqrt(sum((x.-y).^2,1))./σ\n\tout = 1 - 1.5.*n + .5.*n.^3\n\tout[n.>=σ] = 0\n\tout\nend\n\nfunction wave_kernel{T}(x::Array{T}, y::Vector{T}, θ::Real)\n\tθ=convert(T, θ)\n\tn = sqrt(sum((x.-y).^2,1))\n\t(θ./n).*sin(n./θ)\nend\n\nfunction power_kernel{T}(x::Array{T}, y::Vector{T}, d::Real)\n\td=convert(T, d)\n\t-sqrt(sum((x.-y).^2,1)).^d\nend\n\nfunction log_kernel{T}(x::Array{T}, y::Vector{T}, d::Real)\n\td=convert(T, d)\n\t-log(sqrt(sum((x.-y).^2.,1)).^d + 1)\nend\n\nfunction spline_kernel{T}(x::Array{T}, y::Vector{T})\n\txy = x.*y\n\tmxy = broadcast(min, x,y)\n z = 1 .+ xy .+ xy.*mxy - ((x.+y)/2).*mxy.^2 + (mxy.^3)/3\n prod(z,1)\nend\n\nfunction cauchy_kernel{T}(x::Array{T}, y::Vector{T}, σ::Real)\n\tσ=convert(T, σ) \n\t1 ./ (1 .+ (sum((x.-y).^2,1) ./ σ.^2))\nend\n\nfunction chisquare_kernel{T}(x::Array{T}, y::Vector{T})\n\t1 .- sum((x.-y).^2 ./ ((x.+y)/2),1)\nend\n\nfunction histintersect_kernel{T}(x::Array{T}, y::Vector{T})\n\tsum(broadcast(min, x,y),1)\nend\n\nfunction genhistintersect_kernel{T}(x::Array{T}, y::Vector{T}, α::Real, β::Real)\n\tα=convert(T, α); β=convert(T, β);\n\tsum(broadcast(min, abs(x).^α,abs(y).^β),1)\nend\n\nfunction gentstudent_kernel{T}(x::Array{T}, y::Vector{T}, d::Real)\n\td=convert(T, d)\n\t1 ./ (1.0 .+ sqrt(sum((x.-y).^2.,1)).^d)\nend\n\nfunction fourier_kernel{T}(x::Array{T}, y::Vector{T}, a::Real)\n\ta=convert(T, a)\n dist = x.-y;\n dist[dist.==0] = eps(eltype(x))\n z = sin((a + 1/2)*dist)./sin(dist/2);\n prod(z,1)\nend\n\nfunction sigmoid_kernel{T}(x::Array{T}, y::Vector{T}; α::Real=1, c::Real=0)\n\tα=convert(T, α); c=convert(T, c);\n\ttanh(α*y'*x + c)\nend\n\nmotherwavelet(x::Array) = cos(1.75.*x).*exp(-(x.^2)./2)\n\nfunction wavelet_kernel{T}(x::Array{T}, y::Vector{T}, a::Real, c::Real)\n\ta=convert(T, a); c=convert(T, c);\n\tprod(motherwavelet((x.-c)./a).*motherwavelet((y.-c)./a),1)\nend\n\nfunction transinvwavelet_kernel{T}(x::Array{T}, y::Vector{T}, a::Real)\n\ta=convert(T, a);\n\tprod(motherwavelet((x.-y)./a),1)\nend\n\n\n\n\n\nend # module\n", "meta": {"hexsha": "4b1c8e2665a405ad31717b5b134066e7b1940015", "size": 4119, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/KernelLibrary.jl", "max_stars_repo_name": "the-moliver/KernelLibrary.jl", "max_stars_repo_head_hexsha": "651d6b44294b8ae7486a83233a770046f0a9525f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-10-17T15:59:43.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-14T19:34:10.000Z", "max_issues_repo_path": "src/KernelLibrary.jl", "max_issues_repo_name": "the-moliver/KernelLibrary.jl", "max_issues_repo_head_hexsha": "651d6b44294b8ae7486a83233a770046f0a9525f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-09-09T15:40:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-09T15:40:02.000Z", "max_forks_repo_path": "src/KernelLibrary.jl", "max_forks_repo_name": "the-moliver/KernelLibrary.jl", "max_forks_repo_head_hexsha": "651d6b44294b8ae7486a83233a770046f0a9525f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-05-14T19:34:14.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-14T19:34:14.000Z", "avg_line_length": 27.2781456954, "max_line_length": 225, "alphanum_fraction": 0.6224811848, "num_tokens": 1541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693702514737, "lm_q2_score": 0.8558511414521923, "lm_q1q2_score": 0.8127756145319084}} {"text": "#### Similarity and dissimilarity measures between images ####\n\n\"\"\"\n`hausdorff_distance(imgA, imgB)` is the modified Hausdorff distance\nbetween binary images (or point sets).\n\nReferences\n----------\nDubuisson, M-P; Jain, A. K., 1994. A Modified Hausdorff Distance for\nObject-Matching.\n\"\"\"\nfunction hausdorff_distance(imgA::AbstractArray, imgB::AbstractArray)\n @assert size(imgA) == size(imgB) \"Images must have the same dimensions\"\n\n # trivial case\n isequal(imgA, imgB) && return 0.\n\n A, B = find(imgA), find(imgB)\n\n # return if there is no object to match\n (isempty(A) || isempty(B)) && return Inf\n\n # grid coordinates (ndims by npoints)\n A = hcat([Float64[ind2sub(size(imgA), a)...] for a in A]...)\n B = hcat([Float64[ind2sub(size(imgB), b)...] for b in B]...)\n\n m = size(A, 2); n = size(B, 2)\n\n D = zeros(m, n)\n for j=1:n, i=1:m\n @inbounds D[i,j] = norm(A[:,i] - B[:,j])\n end\n\n dAB = mean(minimum(D, 2))\n dBA = mean(minimum(D, 1))\n\n max(dAB, dBA)\nend\n", "meta": {"hexsha": "52365b9b162b872e0e4a263bf70382f7b6ece65e", "size": 972, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distances.jl", "max_stars_repo_name": "JuliaPackageMirrors/Images.jl", "max_stars_repo_head_hexsha": "6a3f1ce49a432567b726696f70e3b650650919ec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/distances.jl", "max_issues_repo_name": "JuliaPackageMirrors/Images.jl", "max_issues_repo_head_hexsha": "6a3f1ce49a432567b726696f70e3b650650919ec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/distances.jl", "max_forks_repo_name": "JuliaPackageMirrors/Images.jl", "max_forks_repo_head_hexsha": "6a3f1ce49a432567b726696f70e3b650650919ec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9230769231, "max_line_length": 73, "alphanum_fraction": 0.6399176955, "num_tokens": 322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9539660976007597, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.8127340862478369}} {"text": "using LinearAlgebra, Statistics, Plots\n\nx_vals = [0 0 0; 2 -3 -4];\ny_vals = [0 0 0; 4 3 -3.5];\n\nplot(x_vals, y_vals, arrow = true, color = :blue,\n legend = :none, xlims = (-5, 5), ylims = (-5,5),\n annotations = [(2.2, 4.4, \"[2, 4]\"),\n (-3.3, 3.3, \"[-3, 3]\"),\n (-4.4, -3.85, \"[-4, -3.5]\")],\n xticks = -5:1:5, yticks = -5:1:5,\n framestyle = :origin)\n\n # Illustrate scalar multiplication\n x = [2];\n scalars = [-2 1 2]; \n vals = [0 0 0; x * scalars]\n labels = [(-3.6, -4.2, \"-2x\"), (2.4, 1.8, \"x\"), (4.4, 3.8, \"2x\")]\n \n plot(vals, vals, arrow = true, color = [:red :red :blue],\n legend = :none, xlims = (-5, 5), ylims = (-5, 5),\n annotations = labels, xticks = -5:1:5, yticks = -5:1:5,\n framestyle = :origin)\n\nx = ones(3);\ny = [2, 4, 6];\nx + y;\n4x; # equivalent to 4 * x and 4 .* x\n\ndot(x, y); \nnorm(x); # Norm of x\nsqrt(sum(abs2, x)); # Give the same result\n\n# fixed linear function, to generate a plane\nf(x, y) = 0.2x + 0.1y;\n\n# lines to vectors\nx_vec = [0 0; 3 3]\ny_vec = [0 0; 4 -4]\nz_vec = [0 0; f(3, 4) f(3, -4)]\n\n# draw the plane\nn = 20\ngrid = range(-5, 5, length = n)\nz2 = [ f(grid[row], grid[col]) for row in 1:n, col in 1:n ]\nwireframe(grid, grid, z2, fill = :blues, gridalpha =1 )\nplot!(x_vec, y_vec, z_vec, color = [:blue :green], linewidth = 3, labels = \"\",\n colorbar = false)\n\nA = [1 2\n 3 4]\nA'\nA = ones(3,3);\n2I\nA + I\n\n# Solve Linear Equations\nA = [1.0 2.0; 3.0 4.0];\ny = ones(2,1);\ndet(A);\nA_inv = inv(A)\nx = A_inv * y # solution\nA * x # should equal y (a vector of ones)\nA \\ y # produces the same solution\n\nA = [1.0 2.0; 2.0 1.0];\nevals, evecs = eigen(A);\n\n", "meta": {"hexsha": "2f38dab3d5808e2a3a2f04b23890493461ba7d8c", "size": 1644, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/Linear_Algebra.jl", "max_stars_repo_name": "wongr003/QuantEcon", "max_stars_repo_head_hexsha": "51d809564f8b653ba2e26b0050c0bb74dbb2c221", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Julia/Linear_Algebra.jl", "max_issues_repo_name": "wongr003/QuantEcon", "max_issues_repo_head_hexsha": "51d809564f8b653ba2e26b0050c0bb74dbb2c221", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Julia/Linear_Algebra.jl", "max_forks_repo_name": "wongr003/QuantEcon", "max_forks_repo_head_hexsha": "51d809564f8b653ba2e26b0050c0bb74dbb2c221", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8260869565, "max_line_length": 78, "alphanum_fraction": 0.5261557178, "num_tokens": 705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660976007597, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.8127340862478369}} {"text": "\"\"\"\n uniformprobvec(n)\n\nReturn a uniform probability distribution vector of size `n`.\n\"\"\"\nfunction uniformprobvec(n)\n return ones(n) ./ n\nend\n\n\"\"\"\n uniformtransmat(n)\n\nReturn a stochastic matrix of size `n` with uniform transition probability distributions.\n\"\"\"\nfunction uniformtransmat(n)\n return ones(n, n) ./ n\nend\n\n\"\"\"\n randprobvec(n)\n\nReturn a random probability distribution vector of size `n`.\n\"\"\"\nfunction randprobvec(n)\n p = rand(n)\n return p ./ sum(p)\nend\n\n\"\"\"\n randtransmat(n)\n\nReturn a stochastic matrix of size `n` with random transition probability distributions.\n\"\"\"\nfunction randtransmat(n)\n P = rand(n, n)\n return P ./ sum(P, dims = 2)\nend\n", "meta": {"hexsha": "a16d99b55fd5a3a2a5b1c6a8567b28ade5641dbd", "size": 687, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils/randvals.jl", "max_stars_repo_name": "gdalle/PointProcesses.jl", "max_stars_repo_head_hexsha": "32a68c5d263b980af2c38353f29652d97539ec88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2021-08-10T21:17:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-30T21:32:43.000Z", "max_issues_repo_path": "src/utils/randvals.jl", "max_issues_repo_name": "gdalle/PointProcesses.jl", "max_issues_repo_head_hexsha": "32a68c5d263b980af2c38353f29652d97539ec88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-17T18:16:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-18T08:26:54.000Z", "max_forks_repo_path": "src/utils/randvals.jl", "max_forks_repo_name": "gdalle/PointProcesses.jl", "max_forks_repo_head_hexsha": "32a68c5d263b980af2c38353f29652d97539ec88", "max_forks_repo_licenses": ["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.0789473684, "max_line_length": 89, "alphanum_fraction": 0.6826783115, "num_tokens": 167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.935346504434783, "lm_q2_score": 0.868826769445233, "lm_q1q2_score": 0.8126540817599638}} {"text": "# using LinearAlgebra\nfunction cart2sph(x::T, y::T, z::T) where {T <: Real}\n hxy = hypot(x, y)\n r = hypot(hxy, z)\n pol = atan(hxy, z)\n az = atan(y, x)\n return [Float64(pol), Float64(az), Float64(r)]\nend\n\nfunction cart2sph(xyz::Point)\n x, y, z = xyz[1], xyz[2], xyz[3]\n return cart2sph(x, y, z)\nend\n\nfunction sph2cart(pol::T, az::T, r::T) where {T <: Real}\n x = r * sin(pol) * cos(az)\n y = r * sin(pol) * sin(az)\n z = r * cos(pol)\n return x, y, z\nend\n\"\"\"\nChange array of vertex coordinates into array of vertex type\n\"\"\"\nfunction array_to_vertex(a::AbstractArray)\n return [Point3f0(vertex) for vertex in a]\nend\n\n\"\"\"\nChange array of face into array of face type\n\"\"\"\nfunction array_to_faces(a::AbstractArray)\n return [TriangleFace{OffsetInteger{-1,UInt32}}(face) for face in a]\nend\n\n\"\"\"\nChange array of array of into matrix\n\"\"\"\nfunction array_of_array_to_matrix(a::AbstractArray)\n return [a[i][j] for i = 1:length(a), j = 1:length(a[1])]\nend\n\"\"\"\nChange matrix to array of array\n\"\"\"\nfunction matrix_to_array_of_array(mat::AbstractMatrix)\n return [mat[i, :] for i = 1:size(mat, 1)]\nend # function]\n\n\"\"\"\nChange matrix to vertices\n\"\"\"\nfunction matrix_to_vertex(mat::AbstractMatrix)\n return [Point3f0(mat[i, :]) for i = 1:size(mat, 1)]\nend # function\n\n\n\"\"\"\nCentering the coordinates of mesh vertices to their mean\n\"\"\"\nfunction centroid(v::AbstractMatrix)\n return sum(v, dims=1) / size(v, 1)\nend\nfunction centroid(verts::Vector{T1}) where {T1}\n return reduce(+, verts) / length(verts)\nend\n\nfunction mesh_centering(verts::Vector{T1}, faces::Vector{T2}) where {T1,T2}\n mean_coord = reduce(+, verts) / length(verts)\n new_verts = similar(verts)\n for i in eachindex(verts)\n new_verts[i] = verts[i] - mean_coord\n end\n return new_verts, faces\nend\nfunction mesh_centering(mesh::Mesh)\n verts = decompose(Point3f0, mesh)\n triangles = decompose(TriangleFace{Int}, mesh)\n verts, triangles = mesh_centering(verts, triangles)\n return Mesh(verts, faces(mesh))\nend\n\n\n\nfunction signed_volume_of_triangle(\n p1::T,\n p2::T,\n p3::T,\n) where {T <: AbstractVector}\n return dot(p1, cross(p2, p3)) / 6.0\nend\n\n\n\"\"\"\nThese functions return the volume of mesh object\n\"\"\"\nfunction mesh_volume(\n verts::Array{Point{3,T1}},\n faces::Array{TriangleFace{T2}},\n) where {T1 <: Real,T2 <: Int}\n total_vol = 0.0\n for face in faces\n vol = signed_volume_of_triangle(\n verts[face[1]],\n verts[face[2]],\n verts[face[3]],\n )\n total_vol += vol\n end\n return abs(total_vol)\nend\n\nfunction mesh_volume(mesh::Mesh)\n verts = decompose(Point3f0, mesh)\n faces = decompose(TriangleFace{Int}, mesh)\n\n return mesh_volume(verts, faces)\nend\n\"\"\"\nThese functions return the copy of mesh object with volume one\n\"\"\"\nfunction volume_normalizing(\n verts::Array{Point{3,T1}},\n faces::Array{TriangleFace{T2}},\n) where {T1 <: Real,T2 <: Int}\n vol = mesh_volume(verts, faces)\n cbrt_vol = cbrt(vol)\n new_verts = similar(verts)\n for i in eachindex(verts)\n new_verts[i] = verts[i] / cbrt_vol\n end\n return new_verts, faces\nend\n\nfunction volume_normalizing2(\n verts::Array{Point{3,T1}},\n faces::Array{TriangleFace{T2}},\n) where {T1 <: Real,T2 <: Int}\n vol = mesh_volume(verts, faces)\n cbrt_vol = cbrt(vol)\n new_verts = similar(verts)\n for i in eachindex(verts)\n new_verts[i] = verts[i] / cbrt_vol\n end\n return new_verts, faces\nend\n\nfunction volume_normalizing(mesh::Mesh)\n verts = decompose(Point3f0, mesh)\n triangles = decompose(TriangleFace{Int}, mesh)\n verts, triangles = volume_normalizing(verts, triangles)\n return Mesh(verts, faces(mesh))\nend\n\"\"\"\nThis function return the mesh object from verts and faces\n\"\"\"\nfunction create_mesh(verts, faces)\n faces = convert(Vector{TriangleFace{OffsetInteger{-1,UInt32}}}, faces)\n return Mesh(verts, faces)\nend\n\"\"\"\nThis function return the angle at vertex v1 from triangle(v1,v2,v3)\n\"\"\"\nfunction calculate_angle(v1, v2, v3)\n v12 = v2 - v1\n v13 = v3 - v1\n v12 = v12 / norm(v12)\n v13 = v13 / norm(v13)\n cos_val = dot(v12, v13)\n angle = acos(cos_val)\n return angle\nend\n# \"\"\"\n# This function return the internal angles of vertices\n# \"\"\"\n# function internal_angles(verts,faces)\n# nrow,ncol = length(faces[1]),length(faces)\n# angles = Matrix{Float64}(undef,nrow,ncol)\n# for j in 1:ncol\n# f = faces[j]\n# for i in 1:nrow\n# v1 = verts[f[i]]\n# idx2 = mod(i+1,nrow) == 0 ? 3 : mod(i+1,nrow)\n# idx3 = mod(i-1,nrow) == 0 ? 3 : mod(i-1,nrow)\n# # @show i\n# # @show idx3\n# # @show f\n# v2 = verts[f[idx2]]\n# v3 = verts[f[idx3]]\n#\n# angles[i,j] = calculate_angle(v1,v2,v3)\n# end\n# end\n# return angles\n# end\n\"\"\"\nThis function return the internal angles of vertices\n\"\"\"\nfunction internal_angles_intrinsic(l)\n s23 = l[:, 1]\n s31 = l[:, 2]\n s12 = l[:, 3]\n\n a23 = acos.((s12.^2 + s31.^2 - s23.^2) ./ (2 * s12 .* s31))\n a31 = acos.((s23.^2 + s12.^2 - s31.^2) ./ (2 * s23 .* s12))\n a12 = acos.((s31.^2 + s23.^2 - s12.^2) ./ (2 * s31 .* s23))\n\n angles = [a23 a31 a12]\n return angles\nend\nfunction internal_angles(verts, faces)\n f1 = [face[1] for face in faces]\n f2 = [face[2] for face in faces]\n f3 = [face[3] for face in faces]\n\n s12 = norm.(verts[f2] - verts[f1])\n s13 = norm.(verts[f3] - verts[f1])\n s23 = norm.(verts[f3] - verts[f2])\n\n l = [s23 s13 s12]\n\n A = internal_angles_intrinsic(l)\nend\n\n\"\"\"\nThis function return the area of triangle made from vectors v1,v2, and v3)\n\"\"\"\nfunction calculate_area(v1, v2, v3)\n v12 = v2 - v1\n v13 = v3 - v1\n area = norm(cross(v12, v13)) / 2.0\n return area\nend\n\"\"\"\nThis function return the surface area)\n\"\"\"\nfunction surface_area(v::AbstractVector, f::AbstractVector)\n nv = length(v)\n nf = length(f)\n\n area = 0\n for i in 1:nf\n l1 = norm(v[f[i][2]] - v[f[i][3]])\n l2 = norm(v[f[i][3]] - v[f[i][1]])\n l3 = norm(v[f[i][1]] - v[f[i][2]])\n s = (l1 + l2 + l3) / 2.0\n square_area = s * (s - l1) * (s - l2) * (s - l3)\n if square_area < 0.0; square_area = 0.0 end\n\n area += sqrt(square_area)\n end\n return area\nend\n\nfunction surface_area_list(v::Matrix{<:AbstractFloat}, f::Matrix{<:Signed})\n f1 = @view f[:, 1]\n f2 = @view f[:, 2]\n f3 = @view f[:, 3]\n\n l1 = sqrt.(sum((view(v, f2, :) - view(v, f3, :)).^2, dims=2))\n l2 = sqrt.(sum((view(v, f3, :) - view(v, f1, :)).^2, dims=2))\n l3 = sqrt.(sum((view(v, f1, :) - view(v, f2, :)).^2, dims=2))\n s = (l1 + l2 + l3) / 2.0\n squared_area = s .* (s - l1) .* (s - l2) .* (s - l3)\n area = sqrt.(squared_area)\n return area\nend\nfunction surface_area(v::Matrix{<:AbstractFloat}, f::Matrix{<:Signed})\n area = surface_area_list(v, f)\n return sum(area)\nend\nfunction surface_area2(v::AbstractVector, f::AbstractVector)\n f1 = [face[1] for face in f]\n f2 = [face[2] for face in f]\n f3 = [face[3] for face in f]\n # F x 3 matrices of triangle edge vectors, named after opposite vertices\n v1 = [v[f3[i]] - v[f2[i]] for i in eachindex(f)]\n v2 = [v[f1[i]] - v[f3[i]] for i in eachindex(f)]\n # v3 = [v[f2[i]] - v[f1[i]] for i in eachindex(f)];\n n = cross.(v1, v2)\n area = norm.(n) / 2.0\n return sum(area)\nend\nfunction surface_area2(v::Matrix{<:AbstractFloat}, f::Matrix{<:Signed})\n f1 = @view f[:, 1]\n f2 = @view f[:, 2]\n f3 = @view f[:, 3]\n # F x 3 matrices of triangle edge vectors, named after opposite vertices\n v1 = view(v, f3, :) - view(v, f2, :)\n v2 = view(v, f1, :) - view(v, f3, :)\n # v3 = v[f2,:] - v[f1,:];\n n = [cross(v1[i, :], v2[i, :]) for i = 1:size(v1, 1)]\n area = norm.(n) / 2.0\n return sum(area)\nend\n\n\nfunction mesh_reorientation(mesh::Mesh, T, N, B)\n verts = decompose(Point3f0, mesh)\n mat_verts = array_of_array_to_matrix(verts)\n new_mat_verts = [T N B] \\ mat_verts'\n new_mat_verts = new_mat_verts'\n new_verts = matrix_to_vertex(new_mat_verts)\n return Mesh(new_verts, faces(mesh))\nend\nfunction mesh_reorientation(mat_verts::AbstractMatrix, T, N, B)\n new_mat_verts = [T N B] \\ mat_verts'\n return new_mat_verts'\nend\n", "meta": {"hexsha": "1e9471b043e7b3952a4a555c675d900e4de6b363", "size": 8302, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils_shape.jl", "max_stars_repo_name": "yusri-dh/MovingFrame.jl", "max_stars_repo_head_hexsha": "1be0d7e4ec1f20d898dfbaf9f85e5b9ac86c7b6e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-28T07:25:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-18T11:59:15.000Z", "max_issues_repo_path": "src/utils_shape.jl", "max_issues_repo_name": "yusri-dh/MovingFrame.jl", "max_issues_repo_head_hexsha": "1be0d7e4ec1f20d898dfbaf9f85e5b9ac86c7b6e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils_shape.jl", "max_forks_repo_name": "yusri-dh/MovingFrame.jl", "max_forks_repo_head_hexsha": "1be0d7e4ec1f20d898dfbaf9f85e5b9ac86c7b6e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9545454545, "max_line_length": 76, "alphanum_fraction": 0.6049144784, "num_tokens": 2714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.8705972751232809, "lm_q1q2_score": 0.8126423238228242}} {"text": "using Random, Plots, StatsPlots, Distributions, DataFrames, Printf\n# Define calculation of posterior\n\"\"\"\nPosterior Distribution (Gamma dist) for Poisson parameter λ\n\n Inputs\n ------\n data: data (0 or 1)\n α0: shape parameter of prior (Gamma dist)\n β0: inversed scale parameter of prior (Gamma dist)\n prob: credible interval probability (0 < prob < 1)\n\n Outputs\n -------\n results: posterior summary stats table (DataFrames)\n α_star: shape parameter of posterior (Gamma dist)\n β: inversed scale parameter (1 / θ) of posterior (Gamma dist)\n\n\"\"\"\nfunction poisson_stats(data, α0, β0, prob)\n # posterior\n n = size(data)[1]\n sum_data = sum(data)\n α_star = sum_data + α0\n β_star = n + β0\n θ_star = 1.0 / β_star\n d_posterior = Gamma(α_star, θ_star)\n # mean\n mean_λ = mean(d_posterior)\n # median\n median_λ = median(d_posterior)\n # mode\n mode_λ = mode(d_posterior)\n # Analytic Mode for Beta Dist\n # (a - 1.0) / (a + b - 2.0)\n # std\n sd_λ = std(d_posterior)\n # credible interval\n # ci upper boud\n ci_λ_upper = quantile(d_posterior, prob - (1-prob)/2)\n # ci lower boud\n ci_λ_lower = quantile(d_posterior, (1-prob)/2)\n ci_λ = [ci_λ_lower, ci_λ_upper]\n\n posterior_stats = reshape([mean_λ, median_λ, mode_λ, sd_λ, ci_λ], 1, 5)\n stats_string = [\"Mean\", \"Median\", \"Mode\", \"SD\", \"CI\"]\n results = DataFrame(posterior_stats, stats_string)\n return results, α_star, β_star\nend\n\n# Generate moc datas\nλ = 3.0\nn = 50\nRandom.seed!(99)\ndata = rand(Poisson(lam), n)\n\n# Set prior\nα0 = 1.0\nβ0 = 1.0\n\n# Calculate posterior statistics\nprob = 0.95\nresults, α_star, β_star = poisson_stats(data, α0, β0, prob)\nprint(results)\n\n# Visualize Posterior\nθ0, θ_star = 1.0/β0, 1.0/β_star\nplot(Gamma(α0, θ0), xlims=(0, 6), ylims=(0, 1.75), xlabel=\"λ\", ylabel=\"Probability Density\", label=@sprintf(\"prior: Gamma(%.1f, %.1f)\",α0, θ0), linestyle=:dash)\nplot!(Gamma(α_star, θ_star), label=@sprintf(\"prior: Gamma(%.1f, %.2f)\",α_star, θ_star), linestyle=:solid)", "meta": {"hexsha": "068ab8f53e0b6162ebee9305cc216da2ebd57d89", "size": 2023, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "jlbayes_conjugate_poisson.jl", "max_stars_repo_name": "hessihan/julia_bayes_intro", "max_stars_repo_head_hexsha": "e5a6c740dbba4a2794579afde196a4586703fbc9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "jlbayes_conjugate_poisson.jl", "max_issues_repo_name": "hessihan/julia_bayes_intro", "max_issues_repo_head_hexsha": "e5a6c740dbba4a2794579afde196a4586703fbc9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jlbayes_conjugate_poisson.jl", "max_forks_repo_name": "hessihan/julia_bayes_intro", "max_forks_repo_head_hexsha": "e5a6c740dbba4a2794579afde196a4586703fbc9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3188405797, "max_line_length": 160, "alphanum_fraction": 0.6544735541, "num_tokens": 678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430803622103, "lm_q2_score": 0.870597271765821, "lm_q1q2_score": 0.8126423110155807}} {"text": "#Maximum Compatibility Pairing \r\nusing JuMP,Gurobi\r\n\r\n#define the model\r\nm =Model(Gurobi.Optimizer)\r\n\r\n#Let n represents the number of cities to be paired\r\nn=4 \r\n\r\n#declaring variables\r\n@variable(m, x[1:n,1:n]>=0)\r\n\r\n#define the compatibility coefficients \r\nc = [\t80 65 83 77;\r\n\t54 87 61 66 ;\r\n\t92 45 53 59 ; \r\n\t70 61 81 76 ]\r\n\r\n#define the objective function\r\n@objective(m, Max, sum(c[i,j]* x[i,j] for i in 1:n for j in 1: n)) #objective is to maximize total compatibility pairing\r\n\r\n#define constraints\r\nfor j = 1: n\r\n @constraint(m ,sum(x[i,j] for i in 1: n) ==1)\r\nend\r\n\r\nfor i = 1: n\r\n @constraint(m ,sum(x[i,j] for j in 1: n) ==1 )\r\nend\r\n\r\nprint(m)\r\n\r\n#Printing the optimal solutions obtained\r\nprintln(\"Optimal Solutions:\")\r\nstatus = JuMP.optimize!(m)\r\nprintln(\" Objective value: \",JuMP.objective_value(m))\r\n\r\nprintln(\"Decision variable values:\")\r\nprintln(\"x = \", JuMP.value.(x))\r\n", "meta": {"hexsha": "4ac7e15886796ac52b599fff82dd88d2812638ea", "size": 892, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Compatibility.jl", "max_stars_repo_name": "Oyekanmi/Optimization-Julia", "max_stars_repo_head_hexsha": "9c89aa41fe14ead83f493c812c9f51d407870d6c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-14T14:36:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T14:36:32.000Z", "max_issues_repo_path": "Compatibility.jl", "max_issues_repo_name": "Oyekanmi/Optimization-Julia", "max_issues_repo_head_hexsha": "9c89aa41fe14ead83f493c812c9f51d407870d6c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Compatibility.jl", "max_forks_repo_name": "Oyekanmi/Optimization-Julia", "max_forks_repo_head_hexsha": "9c89aa41fe14ead83f493c812c9f51d407870d6c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3, "max_line_length": 121, "alphanum_fraction": 0.6591928251, "num_tokens": 273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9777138183570425, "lm_q2_score": 0.8311430436757312, "lm_q1q2_score": 0.8126200388330933}} {"text": "### A Pluto.jl notebook ###\n# v0.16.1\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 35dd2eca-2446-11ec-1de6-0feeace9d4f7\nmd\"\"\"\n\n#### Flash separation of a binary mixture of component A and component B\n\nA liquid feed stream that contains 60% component A (1) and 40% component B (2) is separated in a Flash Drum operating at P = 1.21 MPa and T = 150$^{\\circ}$C. The saturation pressures of pure component A and B can be modeled using the [Antoine equation](https://en.wikipedia.org/wiki/Antoine_equation): \n\n$$\\begin{eqnarray}\n\\ln\\left(P_{1}^{sat}\\right) &=& 15 -\\frac{3010}{T+250}\\\\\n\\ln\\left(P_{2}^{sat}\\right) &=& 14 -\\frac{2700}{T+205}\n\\end{eqnarray}$$\n\nwhere $T$ denotes the temperature in units of celcius $^{\\circ}$C and $P_{\\star}^{sat}$ denotes the saturation pressure in units of kPa for component $\\star$. \n\n##### Assumptions\n\n1. The liquid and vapor phases of all streams are ideal\n1. The liquid and vapor phases inside the Flash Drum are ideal (Raoult's law)\n1. The liquid and vapor phases inside the Flash Drum reach vapor-liquid equilibrium instantly \n\n##### Solve:\n\n * Calculate the fraction of the input stream that exits the drum as liquid\n * Calculate the fraction of the input stream that exits the drum as vapor\n * Calculate the composition of the liquid ($x_{1}$ and $x_{2}$) and vapor ($y_{1}$ and $y_{2}$) in the exit streams \n\n\"\"\"\n\n# ╔═╡ 92ff1f65-d717-47a8-9cd3-af71c2855210\nPlutoUI.LocalResource(\"./figs/Fig-Flash.png\")\n\n# ╔═╡ 98e43733-8711-4aa4-9081-697dd8865592\nbegin\n\t\n\t# write down some constants -\n\tT = 150 \t\t# units: C\n\tP = 1210 \t\t# units: kPa\n\tz₁ = 0.60 \t\t# units: dimensionless\n\tz₂ = (1-z₁)\t\t# units: dimensionless\n\t\n\t# return -\n\tnothing \nend\n\n# ╔═╡ 792e101b-e736-46d2-bbf3-a1197a0cc654\nmd\"\"\"\n\n##### Governing equations\n\nLet's start by writing down the governing equations. Starting from the total mol balance:\n\n$$\\dot{F} = \\dot{L}+\\dot{V}$$\n\nwe can divide both sides by $\\dot{F}$ to give a relationship which constrains the fraction(s) of liquid and vapor in the outlet streams:\n\n$$\\hat{L}+\\hat{V} = 1$$\n\nFurther, we know that the species mol balance around species $i$ is given by:\n\n$$\\dot{F}z_{i} = \\dot{L}x_{i}+\\dot{V}y_{i}\\qquad{i=1,2}$$\n\nHowever, because we assumed ideal vapor and liquid, we know that the liquid and vapor phase equlibrium compositions are related by the fugacity matching condition: $y_{i}P = x_{i}P_{i}^{sat}$. Lastly, we can sum the matching conditions to arrive at an expression which governs the pressure that is only in $x_{i}$:\n\n$$P = x_{1}P_{1}^{sat} + x_{2}P_{2}^{sat}$$\n\nwhich can be re-written (because we are in a binary mixture) as:\n\n$$P = x_{1}P_{1}^{sat} + \\left(1-x_{1}\\right)P_{2}^{sat}$$\n\n\"\"\"\n\n# ╔═╡ 9e171e7c-953d-4a75-b6f6-cbae930dd1ab\nmd\"\"\"\n\n#### Solve for $x_{1}$ and $x_{2}$:\n\nWe can re-arrange the pressure expression to solve for $x_{1}$:\n\n$$x_{1} = \\frac{P - P_{2}^{sat}}{P_{1}^{sat} - P_{2}^{sat}}$$\n\n\"\"\"\n\n# ╔═╡ 8e13e386-6fbc-4bdf-8eed-de5bd35247da\n# compute P1sat (units: kPa)\nP1_sat = exp(15 - (3010)/(T+250))\n\n# ╔═╡ 45a8e5fc-0929-496b-b01a-0e6f27f8b457\n# compute P2sat (units: kPa)\nP2_sat = exp(14 - (2700)/(T+205))\n\n# ╔═╡ 2bd63a06-0eb6-4e4e-b2b0-78b0ac87e341\n# solve for x₁:\nx₁ = (P - P2_sat)/(P1_sat - P2_sat)\n\n# ╔═╡ 6b3bcfa8-7487-4f84-abbe-185939d91a80\nx₂ = 1 - x₁\n\n# ╔═╡ 50a0b336-e14c-487a-9ba5-25a0024d9766\nmd\"\"\"\n#### Solve for $y_{1}$ and $y_{2}$:\n\nOnce we have the liquid phase composition, we can use the fugacity matching condition to relate the liquid phase and the vapr phase becuase we have asssumed they are in equilibrium i.e., \n\n$$y_{i} = x_{i}\\left(\\frac{P_{i}^{sat}}{P}\\right)\\qquad{i=1,2}$$\n\n\"\"\"\n\n# ╔═╡ 7608d2c9-eb24-4db1-9fb3-452d52770e17\n# solve for y₁:\ny₁ = x₁ * (P1_sat/P)\n\n# ╔═╡ 76f6cf32-8f87-4df0-b1db-a51ee102f709\n# solve for y₂:\ny₂ = x₂* (P2_sat/P)\n\n# ╔═╡ ec5378ba-ca2c-4d31-b176-454b2cd99302\nmd\"\"\"\n\n#### Solve for $\\hat{L}$ and $\\hat{V}$:\n\nNow that we have the composition values in the exit streams, we can use the total mol and species mol balances to estimate the fraction \nof the input feed that exited the unit as liquid $\\hat{L}$ and vapur $\\hat{V}$. If we divide both sides of the species mol balance by $\\dot{F}$ we get the relationship:\n\n$$z_{i} = \\hat{L}x_{i}+\\hat{V}y_{i}\\qquad{i=1,2}$$\n\nwhich we can use (along with the total mol balances) to solve for $\\hat{L}$ and $\\hat{V}$ i.e., \n\n$$\\begin{eqnarray}\n\\hat{L}x_{1}+\\hat{V}y_{1} &=& z_{1} \\\\\n\\hat{L}+\\hat{V} &=& 1\n\\end{eqnarray}$$\n\nThis is a system of 2-equations and 2-unknowns ($\\hat{L}$ and $\\hat{V}$) that can be solved by substitution or by linear algebra. \n\n###### Approach 1: Old school subsitution/elimination approach:\n\nLet's rearrange the total mol expression to get $\\hat{L}$ in terms of $\\hat{V}$:\n\n$$\\hat{L} = 1 - \\hat{V}$$\n\nwhich can be subsituted into the species mol balance (let's use component 1):\n\n$$z_{1} = \\left(1 - \\hat{V}\\right)x_{1}+\\hat{V}y_{1}$$\n\nand solved for $\\hat{V}$:\n\n$$\\hat{V} = \\frac{z_{1} - x_{1}}{y_{1} - x_{1}}$$\n\nOnce we have $\\hat{V}$, we can compute $\\hat{L}$ from the total mol balance.\n\"\"\"\n\n# ╔═╡ bb56b509-5279-40f5-b898-e8c1b29dfb5e\n# compute Vhat -\nVhat = (z₁ - x₁)/(y₁ - x₁)\n\n# ╔═╡ 3f13e0a8-b58b-4ac7-899b-412154acf0cb\n# what is Lhat -\nLhat = 1 - Vhat\n\n# ╔═╡ 745177ba-a88d-496d-b0f6-2e9aca506866\nmd\"\"\"\n###### Approach 2: Fancy linear algebra approach:\n\nWe can rewrite the 2$\\times$2 system of equations into matrix-vector form and then compute the matrix inverse. In particlar, \nthe species and total mass balances for component 1 can be written as:\n\n$$\\begin{pmatrix}\nx_{1} & y_{1} \\\\\n1 & 1 \n\\end{pmatrix}\n\\begin{pmatrix}\n\\hat{L} \\\\\n\\hat{V}\n\\end{pmatrix} = \n\\begin{pmatrix}\nz_{1} \\\\\n1\n\\end{pmatrix}$$\n\nwhich is the form $\\mathbf{A}\\mathbf{x} = \\mathbf{b}$, where the solution takes the form: $\\mathbf{x} = \\mathbf{A}^{-1}\\mathbf{b}$.\n\n\n\"\"\"\n\n# ╔═╡ 4c0a79c3-87b4-4452-ba9e-0de5bd324ac5\n# setup A -\nA = [x₁ y₁ ; 1 1]\n\n# ╔═╡ a835ed0a-a2d0-4a5b-a8a0-dffd7250e34b\n# setup b -\nbV = [z₁ ; 1]\n\n# ╔═╡ 2bf7b85f-3118-4fa9-842d-f2c9f3d16dce\n# compute the unknown (fractions of L and V)\nx = inv(A)*bV\n\n# ╔═╡ b091bbb6-13ce-4b1f-b36b-9964783767d4\nhtml\"\"\"\n\"\"\"\n\n# ╔═╡ 64af17f4-c632-425c-a101-9dfa5e8cbd84\n# julia setup -\nusing PlutoUI\n\n# ╔═╡ 79f99ade-b514-4768-9bc9-bcfa281ce02f\npng_joinpathsplit__FILE__1assetsimagepng = let\n import PlutoUI\n PlutoUI.LocalResource(joinpath(split(@__FILE__, '#')[1] * \".assets\", \"image.png\"))\nend\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nPlutoUI = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\n\n[compat]\nPlutoUI = \"~0.7.14\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\n[[Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[HypertextLiteral]]\ngit-tree-sha1 = \"72053798e1be56026b81d4e2682dbe58922e5ec9\"\nuuid = \"ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2\"\nversion = \"0.9.0\"\n\n[[IOCapture]]\ndeps = [\"Logging\", \"Random\"]\ngit-tree-sha1 = \"f7be53659ab06ddc986428d3a9dcc95f6fa6705a\"\nuuid = \"b5f81e59-6552-4d32-b1f0-c071b021bf89\"\nversion = \"0.2.2\"\n\n[[InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"8076680b162ada2a031f707ac7b4953e30667a37\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.2\"\n\n[[Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"a8709b968a1ea6abc2dc1967cb1db6ac9a00dfb6\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.0.5\"\n\n[[PlutoUI]]\ndeps = [\"Base64\", \"Dates\", \"HypertextLiteral\", \"IOCapture\", \"InteractiveUtils\", \"JSON\", \"Logging\", \"Markdown\", \"Random\", \"Reexport\", \"UUIDs\"]\ngit-tree-sha1 = \"d1fb76655a95bf6ea4348d7197b22e889a4375f4\"\nuuid = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nversion = \"0.7.14\"\n\n[[Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[Reexport]]\ngit-tree-sha1 = \"45e428421666073eab6f2da5c9d310d99bb12f9b\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.2.2\"\n\n[[SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╠═64af17f4-c632-425c-a101-9dfa5e8cbd84\n# ╟─35dd2eca-2446-11ec-1de6-0feeace9d4f7\n# ╟─92ff1f65-d717-47a8-9cd3-af71c2855210\n# ╠═79f99ade-b514-4768-9bc9-bcfa281ce02f\n# ╠═98e43733-8711-4aa4-9081-697dd8865592\n# ╟─792e101b-e736-46d2-bbf3-a1197a0cc654\n# ╟─9e171e7c-953d-4a75-b6f6-cbae930dd1ab\n# ╠═8e13e386-6fbc-4bdf-8eed-de5bd35247da\n# ╠═45a8e5fc-0929-496b-b01a-0e6f27f8b457\n# ╠═2bd63a06-0eb6-4e4e-b2b0-78b0ac87e341\n# ╠═6b3bcfa8-7487-4f84-abbe-185939d91a80\n# ╟─50a0b336-e14c-487a-9ba5-25a0024d9766\n# ╠═7608d2c9-eb24-4db1-9fb3-452d52770e17\n# ╠═76f6cf32-8f87-4df0-b1db-a51ee102f709\n# ╟─ec5378ba-ca2c-4d31-b176-454b2cd99302\n# ╠═bb56b509-5279-40f5-b898-e8c1b29dfb5e\n# ╠═3f13e0a8-b58b-4ac7-899b-412154acf0cb\n# ╟─745177ba-a88d-496d-b0f6-2e9aca506866\n# ╠═4c0a79c3-87b4-4452-ba9e-0de5bd324ac5\n# ╠═a835ed0a-a2d0-4a5b-a8a0-dffd7250e34b\n# ╠═2bf7b85f-3118-4fa9-842d-f2c9f3d16dce\n# ╟─b091bbb6-13ce-4b1f-b36b-9964783767d4\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "67062886b0e752f1a13cf15a0273639772ab785a", "size": 9750, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/Example-FlashSeparation.jl", "max_stars_repo_name": "agansky/ENGRI-1120-Cornell-Varner", "max_stars_repo_head_hexsha": "1a2103ed3a9cd94a677f09083c1bbef27db90a86", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-15T20:05:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-15T20:05:45.000Z", "max_issues_repo_path": "notebooks/Example-FlashSeparation.jl", "max_issues_repo_name": "agansky/ENGRI-1120-Cornell-Varner", "max_issues_repo_head_hexsha": "1a2103ed3a9cd94a677f09083c1bbef27db90a86", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/Example-FlashSeparation.jl", "max_forks_repo_name": "agansky/ENGRI-1120-Cornell-Varner", "max_forks_repo_head_hexsha": "1a2103ed3a9cd94a677f09083c1bbef27db90a86", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2021-11-10T20:59:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-19T06:58:07.000Z", "avg_line_length": 28.0172413793, "max_line_length": 314, "alphanum_fraction": 0.6947692308, "num_tokens": 4215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237605, "lm_q2_score": 0.8918110360927155, "lm_q1q2_score": 0.8126001234032965}} {"text": "using Distributions, CSV, DataFrames, LinearAlgebra, LaTeXStrings\n\n# Load observed data\nx_samples_df = CSV.read(\"gmm_observations.csv\")\nx_samples = hcat(x_samples_df[!, :X1], x_samples_df[!, :X2])\n\n# Computes πᵢ for all i with respect to the given parameters in θ\n# Inputs:\n# - θ: A vector containing the current estimates of [α₀, μ₀, Σ₀, μ₁, Σ₁]\n# - x: The (n x 2) matrix of observed X values\n# Ouputs:\n# 𝛑: An n dimensional vector where the ith coordinate is the value of πᵢ\nfunction compute_all_πᵢ(θ, x)\n # Get dataset size\n n = size(x, 1)\n\n # Get current parameters\n α, μ₀, Σ₀, μ₁, Σ₁ = θ\n\n # Set distributions\n 𝒩₁ = MvNormal(μ₁, Σ₁)\n 𝒩₀ = MvNormal(μ₀, Σ₀)\n\n # Compute all πᵢ\n 𝛑 = [α*pdf(𝒩₁, x[i,:])/(α*pdf(𝒩₁, x[i,:]) + (1-α)*pdf(𝒩₀, x[i,:])) for i=1:n]\n\n return 𝛑\nend\n\n# EM algorithm for GMM with observations x and Z ∈ {0,1}\n# Inputs:\n# - θ₀: The initial estimate of the θ parameter\n# - x: The observed X values\n# - iterations: The number of iterations for the EM algorithm\n# Outputs:\n# - θⱼ: The estimate of θ after 1000 iterations\nfunction gmm_EM(θ₀, x, iterations)\n # Get dataset size\n n = size(x, 1)\n\n # Store the value of θ on jth step\n θⱼ = θ₀\n\n for j=1:iterations\n # Get current πᵢ values for all i\n 𝛑 = compute_all_πᵢ(θⱼ, x)\n\n # Store the vector containing 1 - 𝛑\n 𝛑₁ = 1 .- 𝛑\n\n # Get next value of α\n α = sum(𝛑)/n\n\n # Get next value of μ₀\n μ₀ = [dot(𝛑₁, x[:,1]), dot(𝛑₁, x[:,2])]/sum(𝛑₁)\n\n # Get next value of μ₁\n μ₁ = [dot(𝛑, x[:,1]), dot(𝛑, x[:,2])]/sum(𝛑)\n\n # Get next value of Σ₀.\n Σ₀ = sum([(x[i,:] - μ₀)*((x[i,:] - μ₀))'*𝛑₁[i] for i=1:n])/sum(𝛑₁)\n\n # Get next value of Σ₁.\n Σ₁ = sum([(x[i,:] - μ₁)*((x[i,:] - μ₁))'*𝛑[i] for i=1:n])/sum(𝛑)\n\n # Update θ\n θⱼ = [α, μ₀, Σ₀, μ₁, Σ₁]\n\n end\n\n return θⱼ\nend\n\n\n# Initialize EM parameters\nα₀ = 0.3\nμ₀ = [1.0, 2.0]\nμ₁ = [2.0, 3.0]\nΣ₀ = 1.0*Matrix(I, 2, 2)\nΣ₁ = 1.0*Matrix(I, 2, 2)\nθ₀ = [α₀, μ₀, Σ₀, μ₁, Σ₁]\n\nprintln(gmm_EM(θ₀, x_samples, 20))\n\n\n\n## Plots ##\ngr(size=(300,300))\n\nfunction ellipse!(μ,Σ;kw...)\n for i=1:3\n plot!([tuple((i*sqrt(Σ)*[cos(t),sin(t)]+μ)...) for t in range(0,stop=2π,length=100)];\n seriestype=:shape,linealpha=0.5,linecolor=:gray,fillalpha=[0.4,0.2,0.1][i],kw...)\n end\n current()\nend\n\nfunction mixtureplot(X₁,X₂,μ₀,Σ₀,μ₁,Σ₁,Π, plot_title)\n scatter(X₁,X₂;fillalpha=0.5,markerstrokewidth=0.5,\n marker_z=Π,mc=ColorGradient([:lightblue,:orange]),\n colorbar=:false, title=plot_title)\n ellipse!(μ₀,Σ₀,fillcolor=:lightblue)\n ellipse!(μ₁,Σ₁,fillcolor=:orange)\n plot!(;bg=:transparent,xlims=(-4.5,8.5),ylims=(-3.5,10.5),\n leg=false,ticks=:none,ratio=:equal)\nend\n\n\none_step = gmm_EM(θ₀, x_samples, 1)\none_step_Π = compute_all_πᵢ(one_step, x_samples)\nfive_steps = gmm_EM(θ₀, x_samples, 5)\nfive_step_Π = compute_all_πᵢ(ten_steps, x_samples)\ntwenty_steps = gmm_EM(θ₀, x_samples, 20)\ntwenty_step_Π = compute_all_πᵢ(twenty_steps, x_samples)\n\n# Zero step plot\nmixtureplot(x_samples[:,1], x_samples[:,2], θ₀[2], θ₀[3], θ₀[4], θ₀[5], compute_all_πᵢ(θ₀, x_samples), L\"\\theta_0\")\nsavefig(\"../images/gmm_mixtureplot_0.svg\")\n\n# One step plot\nmixtureplot(x_samples[:,1], x_samples[:,2], one_step[2], one_step[3], one_step[4], one_step[5], one_step_Π, L\"\\theta_1\")\nsavefig(\"../images/gmm_mixtureplot_1.svg\")\n\n# Five step plot\nmixtureplot(x_samples[:,1], x_samples[:,2], five_steps[2], five_steps[3], five_steps[4], five_steps[5], five_step_Π, L\"\\theta_5\")\nsavefig(\"../images/gmm_mixtureplot_5.svg\")\n\n# Twenty step plot\nmixtureplot(x_samples[:,1], x_samples[:,2], twenty_steps[2], twenty_steps[3], twenty_steps[4], twenty_steps[5], twenty_step_Π, L\"\\theta_{20}\")\nsavefig(\"../images/gmm_mixtureplot_20.svg\")\n", "meta": {"hexsha": "704061298be541a1c27d4e31b87a10e4090524ba", "size": 3793, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "content/bayesian-inference-and-graphical-models/code/em_gmm_ex.jl", "max_stars_repo_name": "seanrattana/courses", "max_stars_repo_head_hexsha": "9453abc38af26ea49cb00fe1744066fc0de237b3", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2019-08-21T07:33:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-24T15:46:58.000Z", "max_issues_repo_path": "content/bayesian-inference-and-graphical-models/code/em_gmm_ex.jl", "max_issues_repo_name": "seanrattana/courses", "max_issues_repo_head_hexsha": "9453abc38af26ea49cb00fe1744066fc0de237b3", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-08-23T06:04:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-26T12:47:12.000Z", "max_forks_repo_path": "content/bayesian-inference-and-graphical-models/code/em_gmm_ex.jl", "max_forks_repo_name": "seanrattana/courses", "max_forks_repo_head_hexsha": "9453abc38af26ea49cb00fe1744066fc0de237b3", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-08-18T21:23:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-02T19:14:33.000Z", "avg_line_length": 28.9541984733, "max_line_length": 143, "alphanum_fraction": 0.6274716583, "num_tokens": 1518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813513911654, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.812556596781775}} {"text": "module NumericalRange\n\nusing LinearAlgebra\nusing Plots\n\n\"\"\"\n nrange(A; nk = 1, thmax = 32, noplot = false)\n\nNumerical range (or field of values) of the matrix `A`.\nEvaluates and plots the numerical range of the\n`nk` largest leading principal submatrices of `A`, using `thmax`\nequally spaced angles in the complex plane.\nThe defaults are `nk = 1` and `thmax = 32`\nThe eigenvalues of `A` are plotted as `x`. The function returns `f` and `e`, \nwhere `f` is the numerical range and `e` is a vector of eigenvalues of `A`.\nSetting `noplot = true` suppresses the plot.\n\nThis function is a direct translation of `fv.m` in Professor Nick Higham's Matrix Computation Toolbox,\nhttps://www.mathworks.com/matlabcentral/fileexchange/2360-the-matrix-computation-toolbox,\nbased on an original routine by A. Ruhe.\n\nReferences:\nR. A. Horn and C. R. Johnson, Topics in Matrix Analysis, Cambridge\n University Press, 1991; sec. 1.5.\nA. S. Householder, The Theory of Matrices in Numerical Analysis,\n Blaisdell, New York, 1964; sec. 3.3.\nC. R. Johnson, Numerical determination of the field of values of a\n general complex matrix, SIAM J. Numer. Anal., 15 (1978),\n pp. 595-602.\n\n\n\"\"\"\nfunction nrange(B; nk=1, thmax=32, noplot=false)\n function rq(A, x)\n return x'*A*x/(x'*x)\n end\n thmax -= 1 # the function uses thmax + 1 angles\n\n (n, p) = size(B)\n if n != p\n DimensionMismatch(\"Matrix must be square.\")\n end\n\n z = Matrix{ComplexF64}(undef, 2*thmax + 1, 1)\n F = eigen(B)\n e = F.values\n f = []\n\n # filter out cases where B is Hermitian or skew-Hermitian\n if B == B'\n f = [minimum(e), maximum(e)]\n elseif B == -B'\n e = imag(e)\n f = [minimum(e), maximum(e)]\n e *= im\n f *= im\n else\n for m = 1:nk\n ns = n + 1 - m\n A = B[1:ns, 1:ns]\n for i = 0:thmax\n th = i/thmax*pi\n Ath = exp(im*th)*A\n H = 0.5*(Ath + Ath')\n X = eigen(H, sortby = x -> real(x))\n V = X.vectors\n z[i + 1] = rq(A, V[:, 1])\n z[i + 1 + thmax] = rq(A, V[:, ns])\n end\n f = [f; z]\n end\n # join up the boundary\n f = [f; f[1, :]]\n end\n if thmax == 0\n f = e\n end\n\n if !noplot\n p = plot(real(f), imag(f), framestyle=:origin, aspect_ratio = 1, legend=false)\n scatter!(p, real(e), imag(e), markershape=:x, legend=false)\n display(p)\n end\n\n return f, e\nend\n\nend\n", "meta": {"hexsha": "47e456b3c97c5e846e1395b1eed0d700e931cbd2", "size": 2905, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NumericalRange.jl", "max_stars_repo_name": "ThomasChaffey/NumericalRange", "max_stars_repo_head_hexsha": "101186af417913e75974b810adeeb59bfba03c00", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-15T18:32:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-15T18:32:29.000Z", "max_issues_repo_path": "src/NumericalRange.jl", "max_issues_repo_name": "ThomasChaffey/NumericalRange.jl", "max_issues_repo_head_hexsha": "101186af417913e75974b810adeeb59bfba03c00", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-12-15T11:46:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-18T13:03:02.000Z", "max_forks_repo_path": "src/NumericalRange.jl", "max_forks_repo_name": "ThomasChaffey/NumericalRange.jl", "max_forks_repo_head_hexsha": "101186af417913e75974b810adeeb59bfba03c00", "max_forks_repo_licenses": ["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.6404494382, "max_line_length": 102, "alphanum_fraction": 0.4960413081, "num_tokens": 777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.8791467627598857, "lm_q1q2_score": 0.8124562856918317}} {"text": "using LightGraphs, Distributions, StatsBase, Random, Plots, LaTeXStrings;pyplot()\nRandom.seed!(0)\n\nfunction createNetwork(edges)\n network = Graph(maximum(maximum.(edges)))\n for e in edges\n add_edge!(network, e[1], e[2])\n end\n network\nend\n\nfunction uniformRandomEdge(network)\n outDegrees = length.(network.fadjlist)\n randI = sample(1:length(outDegrees),Weights(outDegrees))\n randJ = rand(network.fadjlist[randI])\n randI, randJ\nend\n\nfunction networkLife(network,source,dest,lambda)\n failureNetwork = copy(network)\n t = 0\n while has_path(failureNetwork, source, dest)\n t += rand(Exponential(1/(failureNetwork.ne*lambda)))\n i, j = uniformRandomEdge(failureNetwork)\n rem_edge!(failureNetwork, i, j)\n end\n t\nend\n\nlambda1, lambda2 = 0.5, 1.0\nroads = [(1,2), (1,3), (2,4), (2,5), (2,3), (3,4), (3,5), (4,5), (4,6), (5,6)]\nsource, dest = 1, 6\nnetwork = createNetwork(roads)\nN = 10^6\n\nfailTimes1 = [ networkLife(network,source,dest,lambda1) for _ in 1:N ]\nfailTimes2 = [ networkLife(network,source,dest,lambda2) for _ in 1:N ]\n\nprintln(\"Edge Failure Rate = $(lambda1): Mean failure time = \",\n\tmean(failTimes1), \" days.\")\nprintln(\"Edge Failure Rate = $(lambda2): Mean failure time = \",\n\tmean(failTimes2), \" days.\")\n\nstephist(failTimes1, bins=200, c=:blue, normed=true, label=L\"\\lambda=0.5\")\nstephist!(failTimes2, bins=200, c=:red, normed=true, label=L\"\\lambda=1.0\", \n xlims=(0,5), ylims=(0,1.1), xlabel=\"Network Life Time\", ylabel = \"Density\")", "meta": {"hexsha": "d5627b2d198906e436095fcdadf7ce93984a2ff3", "size": 1502, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "10_chapter/networkLifeTime.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "10_chapter/networkLifeTime.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "10_chapter/networkLifeTime.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.652173913, "max_line_length": 81, "alphanum_fraction": 0.6704394141, "num_tokens": 480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418178895029, "lm_q2_score": 0.8791467548438124, "lm_q1q2_score": 0.812456280213018}} {"text": "### A Pluto.jl notebook ###\n# v0.12.20\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ b9f84364-6b75-11eb-183f-9358dcc0e4d0\nbegin\n\tusing Test\n\tusing LinearAlgebra\nend\n\n# ╔═╡ 9c44adc6-6b7c-11eb-20b5-11ad83fee84b\nArrayFloatOrIntDim2 = Array{<:Union{Float64, Int64}, 2}\n\n# ╔═╡ 95a22bc2-6b77-11eb-2cd5-c50658a942b9\nmd\"\"\"\n## Gram - Schmidt\n\"\"\"\n\n# ╔═╡ 3d8a1668-6b70-11eb-293c-ab5ce07a3ce5\nbegin\n\tfunction GramSchmidt(A::ArrayFloatOrIntDim2)\n\t\tm, n = size(A)\n\t\tQ = zeros(m, n)\n\t\tR = zeros(n, n)\n\t\tfor j = 1:n\n\t\t\tv = A[:,j]\n\t\t\tfor i = 1:j-1\n\t\t\t\tR[i, j] = Q[:, i]' * v\n\t\t\t\tv = v - R[i, j] * Q[:, i]\n\t\t\tend\n\t\t\tR[j, j] = norm(v)\n\t\t\tQ[:,j] = v / R[j,j]\n\t\tend\n\t\treturn (Q, R)\n\tend\nend\n\n# ╔═╡ 7356cb64-6b71-11eb-01f7-91f369a9fb74\nbegin\n\tA = [\n\t\t1 0\n\t\t1 1\n\t\t1 3\n\t\t1 4\n\t]\n\tQ, R = GramSchmidt(A)\n\t\n\t@test A == round.(Int, Q * R)\nend\n\n# ╔═╡ 78c7863c-6b7c-11eb-0be7-cbfb3c368065\nmd\"\"\"\n## Householder (probably wrong)\n\"\"\"\n\n# ╔═╡ 83f357d4-6b7c-11eb-11b6-5ddf77041fe5\nbegin\n\tfunction householder(A::ArrayFloatOrIntDim2)\n\t\tA = convert(Array{Float64}, A)\n\t\tm, n = size(A)\n\t\tU = zeros(m, n)\n\t\tfor k = 1:n\n\t\t\tw = A[k:m, k]\n\t\t\twₙ = norm(w)\n\t\t\tw[1] = (w[1] - wₙ)\n\t\t\tu = w / wₙ\n\t\t\tU[k:m, k] = u\n\t\t\tA[k:m, k:n] = A[k:m, k:n] - 2 * u * (u' * A[k:m, k:n])\n\t\tend\n\t\tR = triu(A[:, 1:n])\n\t\treturn U, R\n\tend\nend\n\n# ╔═╡ 43133fa8-6b7d-11eb-331e-73d6eabd7d83\nbegin\n\tU, Rₕ = householder(A)\nend\n\n# ╔═╡ Cell order:\n# ╠═b9f84364-6b75-11eb-183f-9358dcc0e4d0\n# ╠═9c44adc6-6b7c-11eb-20b5-11ad83fee84b\n# ╟─95a22bc2-6b77-11eb-2cd5-c50658a942b9\n# ╠═3d8a1668-6b70-11eb-293c-ab5ce07a3ce5\n# ╠═7356cb64-6b71-11eb-01f7-91f369a9fb74\n# ╟─78c7863c-6b7c-11eb-0be7-cbfb3c368065\n# ╠═83f357d4-6b7c-11eb-11b6-5ddf77041fe5\n# ╠═43133fa8-6b7d-11eb-331e-73d6eabd7d83\n", "meta": {"hexsha": "ddb466026217be6d21e2cd2a4f078f0a6a3df9b3", "size": 1698, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "2.FrameworkForAppliedMath/3.LeastSquaresForRectangularMatrix/LectureNotes.jl", "max_stars_repo_name": "nickovchinnikov/Computational-Science-and-Engineering", "max_stars_repo_head_hexsha": "45620e432c97fce68a24e2ade9210d30b341d2e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-01-14T08:00:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T14:00:11.000Z", "max_issues_repo_path": "2.FrameworkForAppliedMath/3.LeastSquaresForRectangularMatrix/LectureNotes.jl", "max_issues_repo_name": "nickovchinnikov/Computational-Science-and-Engineering", "max_issues_repo_head_hexsha": "45620e432c97fce68a24e2ade9210d30b341d2e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2.FrameworkForAppliedMath/3.LeastSquaresForRectangularMatrix/LectureNotes.jl", "max_forks_repo_name": "nickovchinnikov/Computational-Science-and-Engineering", "max_forks_repo_head_hexsha": "45620e432c97fce68a24e2ade9210d30b341d2e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-25T15:21:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T15:21:40.000Z", "avg_line_length": 18.6593406593, "max_line_length": 57, "alphanum_fraction": 0.617196702, "num_tokens": 925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.960361158630024, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.8124102536329153}} {"text": "\"\"\"\n copy_eigenvalues!(λs, A) → λs\n\nPuts the eigenvalues of a quasi-upper triangular matrix A in the λs vector.\n\"\"\"\nfunction copy_eigenvalues!(λs, A::AbstractMatrix{T}, range = OneTo(size(A, 2)), tol = eps(real(T))) where {T}\n i = first(range)\n\n @inbounds while i < last(range)\n if is_offdiagonal_small(A, i, tol)\n λs[i] = A[i, i]\n i += 1\n else\n # Conjugate pair\n d = A[i,i] * A[i+1,i+1] - A[i,i+1] * A[i+1,i]\n x = (A[i,i] + A[i+1,i+1]) / 2\n y = sqrt(complex(x*x - d))\n λs[i + 0] = x + y\n λs[i + 1] = x - y\n i += 2\n end\n end\n\n @inbounds if i == last(range)\n λs[i] = A[i, i] \n end\n\n return λs\nend\n\n\"\"\"\n eigenvalue(R, i) → λ\n \nGet the `i`th eigenvalue of R. NOTE: assumes `i` points to the start of\na block.\n\"\"\"\nfunction eigenvalue(R, i)\n n = minimum(size(R))\n\n @inbounds begin\n if i == n || iszero(R[i+1,i])\n return complex(R[i,i])\n else\n d = R[i,i] * R[i+1,i+1] - R[i,i+1] * R[i+1,i]\n x = (R[i,i] + R[i+1,i+1]) / 2\n y = sqrt(complex(x*x - d))\n return x + y\n end\n end\nend\n\n\"\"\"\n eigenvalues(A::AbstractMatrix{T}) → Vector{complex(T)}\n\nComputes the eigenvalues of the matrix A. Assumes that A is quasi-upper triangular.\nThe eigenvalues are returned in complex arithmetic, even if their imaginary\npart is 0.\n\"\"\"\neigenvalues(A::AbstractMatrix{T}, tol = eps(real(T))) where {T} =\n copy_eigenvalues!(Vector{complex(T)}(undef, size(A, 2)), A, OneTo(size(A, 2)), tol)\n\n\"\"\"\n partialeigen(P::PartialSchur) → (Vector{<:Union{Real,Complex}}, Matrix{<:Union{Real,Complex}})\n\nTransforms a partial Schur decomposition into an eigendecomposition.\n\n!!! note\n\n For real-symmetric and Hermitian matrices the Schur vectors coincide with \n the eigenvectors, and hence it is not necessary to call this function in \n that case.\n\nThe method still relies on LAPACK to compute the eigenvectors of the (quasi)\nupper triangular matrix `R` from the partial Schur decomposition.\n\n!!! note\n\n This method is currently type unstable for real matrices, since we have not\n yet decided how to deal with complex conjugate pairs of eigenvalues. E.g.\n if almost all eigenvalues are real, but there are just a few conjugate \n pairs, should all eigenvectors be complex-valued?\n\"\"\"\nfunction partialeigen(P::PartialSchur)\n vals, vecs = eigen(P.R)\n return vals, P.Q*vecs\nend\n", "meta": {"hexsha": "a16d6b4b20ec8aba4a9b55e561ecf1cfc6244fa6", "size": 2505, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/eigvals.jl", "max_stars_repo_name": "andreasnoack/ArnoldiMethod.jl", "max_stars_repo_head_hexsha": "d44bac4022e5e39f9fa80f6398091c41180ec5a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 41, "max_stars_repo_stars_event_min_datetime": "2018-08-28T14:04:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-29T02:18:47.000Z", "max_issues_repo_path": "src/eigvals.jl", "max_issues_repo_name": "andreasnoack/ArnoldiMethod.jl", "max_issues_repo_head_hexsha": "d44bac4022e5e39f9fa80f6398091c41180ec5a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 37, "max_issues_repo_issues_event_min_datetime": "2018-05-21T12:53:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-27T08:58:38.000Z", "max_forks_repo_path": "src/eigvals.jl", "max_forks_repo_name": "andreasnoack/ArnoldiMethod.jl", "max_forks_repo_head_hexsha": "d44bac4022e5e39f9fa80f6398091c41180ec5a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2018-09-10T19:35:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T11:48:46.000Z", "avg_line_length": 28.7931034483, "max_line_length": 109, "alphanum_fraction": 0.6003992016, "num_tokens": 744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404018582426, "lm_q2_score": 0.874077230244524, "lm_q1q2_score": 0.81240269213361}} {"text": "# Description:\n# Dimensions: d\n#\n# The Michalewicz function has d! local minima, and it is multimodal. The parameter m defines the steepness of they valleys and ridges; a larger m leads to a more difficult search. The recommended value of m is m = 10. The function's two-dimensional form is shown in the plot above.\n#\n# Input Domain:\n# The function is usually evaluated on the hypercube xi ∈ [0, π], for all i = 1, …, d.\n#\n# Global Minima:\n# https://www.sfu.ca/~ssurjano/michal3.png\n\nfunction michal(xx, m = 10)\n\n d = length(xx);\n sum = 0;\n\n for ii = 1:d\n \txi = xx[ii];\n \tnew = sin(xi) * (sin(ii * xi^2 / pi))^(2 * m);\n \tsum = sum + new;\n end\n\n y = -sum;\n\n return [y]\nend\n", "meta": {"hexsha": "3f62f3208c6b22c99b9a8e489bf46976e5b35c62", "size": 709, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "michalewicz.jl", "max_stars_repo_name": "cagataycali/bacterial-foraging-optimization-algorithm", "max_stars_repo_head_hexsha": "b84ac0667707e36dbaa4a50457074245b174b491", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "michalewicz.jl", "max_issues_repo_name": "cagataycali/bacterial-foraging-optimization-algorithm", "max_issues_repo_head_hexsha": "b84ac0667707e36dbaa4a50457074245b174b491", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "michalewicz.jl", "max_forks_repo_name": "cagataycali/bacterial-foraging-optimization-algorithm", "max_forks_repo_head_hexsha": "b84ac0667707e36dbaa4a50457074245b174b491", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2592592593, "max_line_length": 282, "alphanum_fraction": 0.6262341326, "num_tokens": 217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9626731105140615, "lm_q2_score": 0.8438951104066293, "lm_q1q2_score": 0.8123951308827572}} {"text": "# Load Julia packages (libraries) needed\n\nusing StatisticalRethinking\n#gr(size=(600,600));\n\n# ### snippet 2.3\n\n# Define a grid\n\nN = 20\np_grid = range( 0 , stop=1 , length=N )\n\n# Define the (uniform) prior\n\nprior = ones( 20 );\n\n# Compute likelihood at each value in grid\n\nlikelihood = [pdf(Binomial(9, p), 6) for p in p_grid]\nlikelihood[1:5]\n\n# Compute product of likelihood and prior\n\nunstd_posterior = likelihood .* prior;\n\n# Standardize the posterior, so it sums to 1\n\nposterior = unstd_posterior ./ sum(unstd_posterior);\n\n# ### snippet 2.4\n\np1 = plot( p_grid , posterior ,\n xlab=\"probability of water\" , ylab=\"posterior probability\",\n lab = \"interpolated\", title=\"20 points\" )\np2 = scatter!( p1, p_grid , posterior, lab=\"computed\" )\n\n# ### snippet 2.5\n\nprior1 = [p < 0.5 ? 0 : 1 for p in p_grid]\nprior2 = [exp( -5*abs( p - 0.5 ) ) for p in p_grid]\n\np3 = plot(p_grid, prior1, \n xlab=\"probability of water\" , ylab=\"posterior probability\",\n lab = \"semi_uniform\", title=\"Other priors\" )\nscatter!(p3, p_grid, prior1, lab = \"semi_uniform grid point\")\nplot!(p3, p_grid, prior2, lab = \"double_exponential\" )\nscatter!(p3, p_grid, prior2, lab = \"double_exponential grid point\" )\n\n# End of `02/clip-03-05.jl`\n", "meta": {"hexsha": "fc092a506d548573d9fa585994e3a2bd897df3d1", "size": 1212, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/02/clip-03-05.jl", "max_stars_repo_name": "UnofficialJuliaMirror/StatisticalRethinking.jl-2d09df54-9d0f-5258-8220-54c2a3d4fbee", "max_stars_repo_head_hexsha": "08ee7b4244edcb2c94f4410829372e7d5082cb7a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/02/clip-03-05.jl", "max_issues_repo_name": "UnofficialJuliaMirror/StatisticalRethinking.jl-2d09df54-9d0f-5258-8220-54c2a3d4fbee", "max_issues_repo_head_hexsha": "08ee7b4244edcb2c94f4410829372e7d5082cb7a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/02/clip-03-05.jl", "max_forks_repo_name": "UnofficialJuliaMirror/StatisticalRethinking.jl-2d09df54-9d0f-5258-8220-54c2a3d4fbee", "max_forks_repo_head_hexsha": "08ee7b4244edcb2c94f4410829372e7d5082cb7a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.24, "max_line_length": 69, "alphanum_fraction": 0.6757425743, "num_tokens": 389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464796, "lm_q2_score": 0.8856314692902446, "lm_q1q2_score": 0.8123921041949501}} {"text": "using LinearAlgebra\nusing Plots\nusing Random\nusing BenchmarkTools\nusing JuMP\n\nfunction kernelf(X1, X2, l=1.0, sigma_f=1.0)\n\n # Isotropic squared exponential kernel. Computes\n # a covariance matrix from points in X1 and X2.\n\n #Σ = zeros(size(X1,1), size(X2,1))\n Σ = Array{Float64,2}(undef, size(X1,1), size(X2,1))\n for i in 1:size(Σ,1)\n for j in 1:size(Σ,2)\n Σ[i,j] = sigma_f^2*exp(-(X1[i]-X2[j])^2/(2*l^2))\n end\n end\n\n return Σ\n\nend\n\nfunction plot_gp(μ, Σ, X, X_train=nothing, Y_train=nothing)\n σ = 1.96*sqrt.(diag(Σ))\n p = plot([X X], [μ μ], fillrange=[μ+σ μ-σ], fillalpha=0.3, c=:blue, label=\"\")\n plot!(X, μ, c=:blue, label=\"GP mean\")\n if X_train!=nothing && Y_train!=nothing\n plot!(X_train, Y_train, seriestype=\"scatter\", color=\"red\", label=\"samples\")\n end\n display(p)\nend\n\nfunction kernelTest()\n X1 = collect(range(-5, step=1, 5))\n X2 = collect(range(-5, step=1, 5)) .+ 0.1.*randn(size(X1))\n plot(X1, label=\"original data\")\n plot!(X2, label=\"corrupted data\")\n μ = zeros(size(X1))\n Σ = kernelf(X1, X1)\n plot_gp(μ, Σ, X1)\nend\n\nfunction posteriorPredictor(X_s, X_train, Y_train, l=1.0, sigma_f=1.0, sigma_y=1e-8, K_inv=nothing)\n K_s = kernelf(X_train, X_s, l, sigma_f)\n K_ss = kernelf(X_s, X_s, l, sigma_f) + 1e-8*I\n if K_inv == nothing\n K = kernelf(X_train, X_train, l, sigma_f) + sigma_y^2*I\n K_inv = inv(K)\n end\n\n μ_s = K_s'*K_inv*Y_train\n #mu_s = K_s.T.dot(K_inv).dot(Y_train)\n Σ_s = K_ss - K_s'*K_inv*K_s\n #cov_s = K_ss - K_s.T.dot(K_inv).dot(K_s)\n\n return μ_s, Σ_s, K_inv\nend\n\nfunction testPredictor()\n lb = 0;\n ub = 5;\n n = 5;\n sigma_y = 0.0\n X_train = [-4 -3 -2 -1 1 4]'\n X_train = rand(n) .*(ub-lb) .+lb\n Y_train = sin.(X_train) + sigma_y*randn(size(X_train,1))\n X = collect(range(lb, ub, length=n))\n μ_s, Σ_s = posteriorPredictor(X, X_train, Y_train, 1.0, 1.0, sigma_y)\n plot_gp(μ_s, Σ_s, X, X_train, Y_train)\n plot!(X, sin.(X), lw=:2, color=:black, label=\"true function\")\nend\n\nfunction hyperParameterOptimization(X_train, Y_train, noise, naive=true)\n model = Model()\n @variable(theta[1:2] >= 1e-5) #hyperparam variables\n if naive\n end\nend\n\n\nfunction f(x)\n return 8*sin.(x) + 1/2*x.^2 + 1/8*x.^3 + 1/32*x.^4 - 1/128*x.^5\nend\n\n#kernelTest()\n#testPredictor()\n\nlb = 1;\nub = 7;\nn = 100;\nl = 1.0;\nsigma_f = 1.0\nsigma_y = 0.9\n#X_train = [-4 -3 -2 -1 1 4]'\n#X_train = rand(n).*(ub-lb) .+ lb\nX_train = 1.1*randn(n) .+ (ub - lb)/2 .+ lb\nY_train = f(X_train) + sigma_y*randn(size(X_train,1))\nX = collect(range(lb, ub, length=n))\nif sigma_y != 0.0\n μ_s, Σ_s, K_inv = posteriorPredictor(X, X_train, Y_train, l, sigma_f, sigma_y)\nelse\n μ_s, Σ_s, K_inv = posteriorPredictor(X, X_train, Y_train, l, sigma_f)\nend\nprintln(\"Timing training + inference\")\n@time posteriorPredictor(X, X_train, Y_train, 1.0, 1.0, sigma_y)\nprintln(\"Timing inference\")\n@time posteriorPredictor(X, X_train, Y_train, 1.0, 1.0, sigma_y, K_inv)\nplot_gp(μ_s, Σ_s, X, X_train, Y_train)\nplot!(X, f(X), lw=:2, color=:black, label=\"true function\", xlim=(lb,ub))\n", "meta": {"hexsha": "8dc0256a804f27f8e41aed8e6498ca6bef51d435", "size": 3111, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "my_gp_implementation.jl", "max_stars_repo_name": "gbarsih/Safe-Optimal-Rendezvous", "max_stars_repo_head_hexsha": "6acc9f11c092c81dbe19daeb0ff7363f7ab5bd5f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "my_gp_implementation.jl", "max_issues_repo_name": "gbarsih/Safe-Optimal-Rendezvous", "max_issues_repo_head_hexsha": "6acc9f11c092c81dbe19daeb0ff7363f7ab5bd5f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "my_gp_implementation.jl", "max_forks_repo_name": "gbarsih/Safe-Optimal-Rendezvous", "max_forks_repo_head_hexsha": "6acc9f11c092c81dbe19daeb0ff7363f7ab5bd5f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.027027027, "max_line_length": 99, "alphanum_fraction": 0.6194149791, "num_tokens": 1202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249612, "lm_q2_score": 0.8856314662716159, "lm_q1q2_score": 0.812392097421555}} {"text": "# Integration using a function\r\nfunction trapz(f, a, b, h)\r\n x = collect(Float64, a:h:b);\r\n suma = 0\r\n for j ∈ 2:(length(x) - 1)\r\n val = f(x[j])\r\n suma += val\r\n end\r\n I = (b - a) * (f(x[1]) + 2 * suma + f(x[end])) / (2 * (length(x) - 1));\r\n return I\r\nend\r\n\r\n\r\n# Integration of a table\r\nfunction trapz(x::Array{Float64,1}, y::Array{Float64,1})\r\n suma = 0;\r\n for j ∈ 2:(length(x) - 1)\r\n suma += y[j]\r\n end\r\n I = (x[end] - x[1]) * (y[1] + 2 * suma + y[end]) / (2 * (length(x) - 1));\r\n return I\r\nend\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "bcd2985c8505d64def1d5d951b3ba7639ebb2433", "size": 563, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/trapz.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/trapz.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/trapz.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": 19.4137931034, "max_line_length": 78, "alphanum_fraction": 0.4493783304, "num_tokens": 208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026482819238, "lm_q2_score": 0.8856314738181875, "lm_q1q2_score": 0.8123920963352467}} {"text": "# some simpler (and faster) implementations for root finding\n#\n# Not exported\n#\n# These avoid the setup costs of the `find_zero` method, so should be faster\n# though they will take similar number of function calls.\n#\n# `Roots.bisection(f, a, b)` (Bisection).\n# `Roots.secant_method(f, xs)` (Order1) secant method\n# `Roots.dfree(f, xs)` (Order0) more robust secant method\n#\n\n## Bisection\n##\n## Essentially from Jason Merrill https://gist.github.com/jwmerrill/9012954\n## cf. http://squishythinking.com/2014/02/22/bisecting-floats/\n## This also borrows a trick from https://discourse.julialang.org/t/simple-and-fast-bisection/14886\n## where we keep x1 so that y1 is negative, and x2 so that y2 is positive\n## this allows the use of signbit over y1*y2 < 0 which avoid < and a multiplication\n## this has a small, but noticeable impact on performance.\n\"\"\"\n bisection(f, a, b; [xatol, xrtol])\n\nPerforms bisection method to find a zero of a continuous\nfunction.\n\nIt is assumed that (a,b) is a bracket, that is, the function has\ndifferent signs at a and b. The interval (a,b) is converted to floating point\nand shrunk when a or b is infinite. The function f may be infinite for\nthe typical case. If f is not continuous, the algorithm may find\njumping points over the x axis, not just zeros.\n\n\nIf non-trivial tolerances are specified, the process will terminate\nwhen the bracket (a,b) satisfies `isapprox(a, b, atol=xatol,\nrtol=xrtol)`. For zero tolerances, the default, for Float64, Float32,\nor Float16 values, the process will terminate at a value `x` with\n`f(x)=0` or `f(x)*f(prevfloat(x)) < 0 ` or `f(x) * f(nextfloat(x)) <\n0`. For other number types, the A42 method is used.\n\n\"\"\"\nfunction bisection(f, a::Number, b::Number; xatol=nothing, xrtol=nothing)\n\n x1, x2 = adjust_bracket(float.((a,b)))\n T = eltype(x1)\n\n\n atol = xatol == nothing ? zero(T) : abs(xatol)\n rtol = xrtol == nothing ? zero(one(T)) : abs(xrtol)\n CT = iszero(atol) && iszero(rtol) ? Val(:exact) : Val(:inexact)\n\n x1, x2 = float(x1), float(x2)\n y1, y2 = f(x1), f(x2)\n\n _unitless(y1 * y2) >= 0 && error(\"the interval provided does not bracket a root\")\n\n if isneg(y2)\n x1, x2, y1, y2 = x2, x1, y2, y1\n end\n\n xm = Roots._middle(x1, x2) # for possibly mixed sign x1, x2\n ym = f(xm)\n\n while true\n\n if has_converged(CT, x1, x2, xm, ym, atol, rtol)\n return xm\n end\n\n if isneg(ym)\n x1, y1 = xm, ym\n else\n x2, y2 = xm, ym\n end\n\n xm = Roots.__middle(x1,x2)\n ym = f(xm)\n\n\n end\n\nend\n\n# -0.0 not returned by __middle, so isneg true on [-Inf, 0.0)\n@inline isneg(x::T) where {T <: AbstractFloat} = signbit(x)\n@inline isneg(x) = _unitless(x) < 0\n\n@inline function has_converged(::Val{:exact}, x1, x2, m, ym, atol, rtol)\n iszero(ym) && return true\n isnan(ym) && return true\n x1 != m && m != x2 && return false\n return true\nend\n\n@inline function has_converged(::Val{:inexact}, x1, x2, m, ym, atol, rtol)\n iszero(ym) && return true\n isnan(ym) && return true\n val = abs(x1 - x2) <= atol + max(abs(x1), abs(x2)) * rtol\n return val\nend\n\n\n\"\"\"\n secant_method(f, xs; [atol=0.0, rtol=8eps(), maxevals=1000])\n\nPerform secant method to solve f(x) = 0.\n\nThe secant method is an iterative method with update step\ngiven by b - fb/m where m is the slope of the secant line between\n(a,fa) and (b,fb).\n\nThe inital values can be specified as a pair of 2, as in `(a,b)` or\n`[a,b]`, or as a single value, in which case a value of `b` is chosen.\n\nThe algorithm returns m when `abs(fm) <= max(atol, abs(m) * rtol)`.\nIf this doesn't occur before `maxevals` steps or the algorithm\nencounters an issue, a value of `NaN` is returned. If too many steps\nare taken, the current value is checked to see if there is a sign\nchange for neighboring floating point values.\n\nThe `Order1` method for `find_zero` also implements the secant\nmethod. This one will be faster, as there are fewer setup costs.\n\nExamples:\n\n```julia\nRoots.secant_method(sin, (3,4))\nRoots.secant_method(x -> x^5 -x - 1, 1.1)\n```\n\nNote:\n\nThis function will specialize on the function `f`, so that the inital\ncall can take more time than a call to the `Order1()` method, though\nsubsequent calls will be much faster. Using `FunctionWrappers.jl` can\nensure that the initial call is also equally as fast as subsequent\nones.\n\n\"\"\"\nfunction secant_method(f, xs; atol=zero(float(real(first(xs)))), rtol=8eps(one(float(real(first(xs))))), maxevals=100)\n\n if length(xs) == 1 # secant needs x0, x1; only x0 given\n a = float(xs[1])\n\n h = eps(one(real(a)))^(1/3)\n da = h*oneunit(a) + abs(a)*h^2 # adjust for if eps(a) > h\n b = a + da\n\n else\n a, b = promote(float(xs[1]), float(xs[2]))\n end\n secant(f, a, b, atol, rtol, maxevals)\nend\n\n\nfunction secant(f, a::T, b::T, atol=zero(T), rtol=8eps(T), maxevals=100) where {T}\n nan = (0a)/(0a)\n cnt = 0\n\n fa, fb = f(a), f(b)\n fb == fa && return nan\n\n uatol = atol / oneunit(atol) * oneunit(real(a))\n adjustunit = oneunit(real(fb))/oneunit(real(b))\n\n while cnt < maxevals\n m = b - (b-a)*fb/(fb - fa)\n fm = f(m)\n\n iszero(fm) && return m\n isnan(fm) && return nan\n abs(fm) <= adjustunit * max(uatol, abs(m) * rtol) && return m\n if fm == fb\n sign(fm) * sign(f(nextfloat(m))) <= 0 && return m\n sign(fm) * sign(f(prevfloat(m))) <= 0 && return m\n return nan\n end\n\n a,b,fa,fb = b,m,fb,fm\n\n cnt += 1\n end\n\n return nan\nend\n\n\"\"\"\n muller(f, xᵢ; xatol=nothing, xrtol=nothing, maxevals=100)\n muller(f, xᵢ₋₂, xᵢ₋₁, xᵢ; xatol=nothing, xrtol=nothing, maxevals=100)\n\n> *Muller’s method* generalizes the secant method, but uses quadratic\n> interpolation among three points instead of linear interpolation between two.\n> Solving for the zeros of the quadratic allows the method to find complex\n> pairs of roots.\n> Given three previous guesses for the root `xᵢ₋₂`, `xᵢ₋₁`, `xᵢ`, and the values\n> of the polynomial `f` at those points, the next approximation `xᵢ₊₁` is produced.\n\nExcerpt and the algorithm taken from\n\n> W.H. Press, S.A. Teukolsky, W.T. Vetterling and B.P. Flannery\n> *Numerical Recipes in C*, Cambridge University Press (2002), p. 371\n\nConvergence here is decided by `xᵢ₊₁ ≈ xᵢ` using the tolerances specified,\nwhich both default to `eps(one(typeof(abs(xᵢ))))^4/5` in the appropriate units.\nEach iteration performs three evaluations of `f`.\nThe first method picks two remaining points at random in relative proximity of `xᵢ`.\n\nNote that the method may return complex result even for real intial values\nas this depends on the function.\n\nExamples:\n```\nmuller(x->x^3-1, 0.5, 0.5im, -0.5) # → -0.500 + 0.866…im\nmuller(x->x^2+2, 0.0, 0.5, 1.0) # → ≈ 0.00 - 1.41…im\nmuller(x->(x-5)*x*(x+5), rand(3)...) # → ≈ 0.00\nmuller(x->x^3-1, 1.5, 1.0, 2.0) # → 2.0, Not converged\n```\n\n\"\"\"\nmuller(f, x₀::T; kwargs...) where T = muller(f, (rand(T, 2).*x₀)..., x₀; kwargs...)\n\nmuller(f, xᵢ₋₂, xᵢ₋₁, xᵢ; kwargs...) =\n muller(f, promote(xᵢ₋₂, xᵢ₋₁, xᵢ)...; kwargs...)\n\nfunction muller(f, oldest::T, older::T, old::T;\n xatol=nothing, xrtol=nothing, maxevals=300) where {T}\n @assert old ≠ older ≠ oldest ≠ old # we want q to be non-degenerate\n xᵢ₋₂, xᵢ₋₁, xᵢ = oldest, older, old\n fxᵢ₋₂, fxᵢ₋₁ = f(xᵢ₋₂), f(xᵢ₋₁) \n\n RT = typeof(abs(oldest))\n atol = xatol !== nothing ? xatol : oneunit(RT) * (eps(one(RT)))^(4/5)\n rtol = xrtol !== nothing ? xrtol : eps(one(RT))^(4/5)\n\n for i in 1:maxevals÷3\n # one evaluation per iteration\n fxᵢ = f(xᵢ)\n x = muller_step(xᵢ₋₂, xᵢ₋₁, xᵢ, fxᵢ₋₂, fxᵢ₋₁, fxᵢ)\n\n if isnan(x)\n @warn \"The algorithm might not have converged, stopping at i=$i:\" abs(xᵢ - xᵢ₋₁)\n return xᵢ\n end\n\n # @debug \"Iteration $i:\" xᵢ₋₂ xᵢ₋₁ xᵢ x abs(x-xᵢ)\n xᵢ₋₂, xᵢ₋₁, xᵢ = xᵢ₋₁, xᵢ, x\n fxᵢ₋₂, fxᵢ₋₁ = fxᵢ₋₁, fxᵢ\n #stopping criterion\n isapprox(xᵢ, xᵢ₋₁, atol=atol, rtol=rtol) && return xᵢ\n end\n @warn \"The algorithm might not have converged, maxevals limit hit:\" abs(xᵢ₋₁- xᵢ)\n return xᵢ\nend\n\nfunction muller_step(a,b,c,fa,fb,fc)\n a,b,c = promote(a,b,c)\n q = qq(a, b, c)\n q² = q^2\n q1 = q+one(q)\n\n A = q*fc - q*q1*fb + q²*fa\n B = (q1+q)*fc - q1^2*fb + q²*fa\n C = q1*fc\n\n den = let\n Δ = B^2 - 4A*C\n typeof(Δ) <: Real && Δ < 0 && throw(\n DomainError(Δ, \"Discriminant is negative and the function most likely has complex roots. You might want to call muller with complex input.\"))\n Δ = √Δ\n d⁺ = B + Δ\n d⁻ = B - Δ\n abs(d⁺) > abs(d⁻) ? d⁺ : d⁻\n end\n return c - (c - b)*2C/den\nend\n\n@inline qq(a, b, c) = (c - b)/(b - a)\n\n\"\"\"\n newton((f, f'), x0; xatol=nothing, xrtol=nothing, maxevals=100)\n newton(fΔf, x0; xatol=nothing, xrtol=nothing, maxevals=100)\n\nNewton's method.\n\nFunction may be passed in as a tuple (f, f') *or* as function which returns (f,f/f').\n\nExamples:\n```\nnewton((sin, cos), 3.0)\nnewton(x -> (sin(x), sin(x)/cos(x)), 3.0, xatol=1e-10, xrtol=1e-10)\n```\n\nNote: unlike the call `newton(f, fp, x0)`--which dispatches to a method of `find_zero`, these\ntwo interfaces will specialize on the function that is passed in. This means, these functions\nwill be faster for subsequent calls, but may be slower for an initial call.\n\nConvergence here is decided by x_n ≈ x_{n-1} using the tolerances specified, which both default to\n`eps(T)^4/5` in the appropriate units.\n\n\"\"\"\nstruct TupleWrapper{F, Fp}\nf::F\nfp::Fp\nend\n(F::TupleWrapper)(x) = begin\n u, v = F.f(x), F.fp(x)\n return (u, u/v)\nend\n\nnewton(f::Tuple, x0; kwargs...) = newton(TupleWrapper(f[1],f[2]), x0; kwargs...)\nfunction newton(f, x0; xatol=nothing, xrtol=nothing, maxevals = 100)\n\n x = float(x0)\n T = typeof(x)\n atol = xatol != nothing ? xatol : oneunit(T) * (eps(one(T)))^(4/5)\n rtol = xrtol != nothing ? xrtol : eps(one(T))^(4/5)\n\n\n xo = Inf\n for i in 1:maxevals\n\n fx, Δx = f(x)\n iszero(fx) && return x\n\n x -= Δx\n\n if isapprox(x, xo, atol=atol, rtol=rtol)\n return x\n end\n\n xo = x\n end\n\n error(\"No convergence\")\nend\n\n\n\n\n## This is basically Order0(), but with different, default, tolerances employed\n## It takes more function calls, but works harder to find exact zeros\n## where exact means either iszero(fx), adjacent floats have sign change, or\n## abs(fxn) <= 8 eps(xn)\n\"\"\"\n dfree(f, xs)\n\nA more robust secant method implementation\n\nSolve for `f(x) = 0` using an alogorithm from *Personal Calculator Has Key\nto Solve Any Equation f(x) = 0*, the SOLVE button from the\n[HP-34C](http://www.hpl.hp.com/hpjournal/pdfs/IssuePDFs/1979-12.pdf).\n\nThis is also implemented as the `Order0` method for `find_zero`.\n\nThe inital values can be specified as a pair of two values, as in\n`(a,b)` or `[a,b]`, or as a single value, in which case a value of `b`\nis computed, possibly from `fb`. The basic idea is to follow the\nsecant method to convergence unless:\n\n* a bracket is found, in which case bisection is used;\n\n* the secant method is not converging, in which case a few steps of a\n quadratic method are used to see if that improves matters.\n\nConvergence occurs when `f(m) == 0`, there is a sign change between\n`m` and an adjacent floating point value, or `f(m) <= 2^3*eps(m)`.\n\nA value of `NaN` is returned if the algorithm takes too many steps\nbefore identifying a zero.\n\n# Examples\n\n```julia\nRoots.dfree(x -> x^5 - x - 1, 1.0)\n```\n\n\"\"\"\nfunction dfree(f, xs)\n\n if length(xs) == 1\n a = float(xs[1])\n fa = f(a)\n\n h = eps(one(a))^(1/3)\n da = h*oneunit(a) + abs(a)*h^2 # adjust for if eps(a) > h\n b = float(a + da)\n fb = f(b)\n else\n a, b = promote(float(xs[1]), float(xs[2]))\n fa, fb = f(a), f(b)\n end\n\n\n nan = (0*a)/(0*a) # try to preserve type\n cnt, MAXCNT = 0, 5 * ceil(Int, -log(eps(one(a)))) # must be higher for BigFloat\n MAXQUAD = 3\n\n if abs(fa) > abs(fb)\n a,fa,b,fb=b,fb,a,fa\n end\n\n # we keep a, b, fa, fb, gamma, fgamma\n quad_ctr = 0\n while !iszero(fb)\n cnt += 1\n\n if sign(fa) * sign(fb) < 0\n return bisection(f, a, b)\n end\n\n # take a secant step\n gamma = float(b - (b-a) * fb / (fb - fa))\n # modify if gamma is too small or too big\n if iszero(abs(gamma-b))\n gamma = b + 1/1000 * abs(b-a) # too small\n elseif abs(gamma-b) >= 100 * abs(b-a)\n gamma = b + sign(gamma-b) * 100 * abs(b-a) ## too big\n end\n fgamma = f(gamma)\n\n # change sign\n if sign(fgamma) * sign(fb) < 0\n return bisection(f, gamma, b)\n end\n\n # decreasing\n if abs(fgamma) < abs(fb)\n a,fa, b,fb = b, fb, gamma, fgamma\n quad_ctr = 0\n cnt < MAXCNT && continue\n end\n\n gamma = float(quad_vertex(a,fa,b,fb,gamma,fgamma))\n fgamma = f(gamma)\n # decreasing now?\n if abs(fgamma) < abs(fb)\n a,fa, b,fb = b, fb, gamma, fgamma\n quad_ctr = 0\n cnt < MAXCNT && continue\n end\n\n\n quad_ctr += 1\n if (quad_ctr > MAXQUAD) || (cnt > MAXCNT) || iszero(gamma - b) || isnan(gamma)\n bprev, bnext = prevfloat(b), nextfloat(b)\n fbprev, fbnext = f(bprev), f(bnext)\n sign(fb) * sign(fbprev) < 0 && return b\n sign(fb) * sign(fbnext) < 0 && return b\n for (u,fu) in ((b,fb), (bprev, fbprev), (bnext, fbnext))\n abs(fu)/oneunit(fu) <= 2^3*eps(u/oneunit(u)) && return u\n end\n return nan # Failed.\n end\n\n if abs(fgamma) < abs(fb)\n b,fb, a,fa = gamma, fgamma, b, fb\n else\n a, fa = gamma, fgamma\n end\n\n end\n b\n\nend\n", "meta": {"hexsha": "18e7803ed599a285e93bd7c29b9996f0421fb8fc", "size": 13846, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/simple.jl", "max_stars_repo_name": "alecloudenback/Roots.jl", "max_stars_repo_head_hexsha": "299e5ead40ad16d112d461ab2a736ccc44eeafd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/simple.jl", "max_issues_repo_name": "alecloudenback/Roots.jl", "max_issues_repo_head_hexsha": "299e5ead40ad16d112d461ab2a736ccc44eeafd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/simple.jl", "max_forks_repo_name": "alecloudenback/Roots.jl", "max_forks_repo_head_hexsha": "299e5ead40ad16d112d461ab2a736ccc44eeafd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.776344086, "max_line_length": 153, "alphanum_fraction": 0.6050122779, "num_tokens": 4776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391386, "lm_q2_score": 0.8902942363098472, "lm_q1q2_score": 0.8123366589130644}} {"text": "\nexport _build, _get_kernel, funcs, r\nusing Statistics\nusing LinearAlgebra\nusing StaticArrays\n#########################################################\n# Radial Basis functions #\n#########################################################\n\nphi_MQ(r, e) = sqrt(1 + (e .* r) .^ 2)\nphi_InvMQ(r, e) = phi_MQ(r, e)^-1\nphi_Q(r, e) = phi_MQ(r, e)^-2\nphi_Gauss(r, e) = exp(-(e .* r)^2)\nphi_Multiquadric(r, e) = -sqrt(1 + r .^ 2)\nphi_InvMultiquadric(r, e) = 1 / (-sqrt(1 + r .^ 2))\nphi_thin_plate_spline(r, e) = r .^ 2 .* log(r + 1e-5)\nphi_cubic(r, e) = (r + 1) .^ -3\nphi_quintic(r, e) = (r + 1) .^ -5\nfuncs = Dict([(\"MQ\", phi_MQ),\n (\"InvMQ\", phi_InvMQ),\n (\"Quadratic\", phi_Q),\n (\"Gaussian\", phi_Gauss),\n (\"minusMQ\", phi_Multiquadric),\n (\"minusInvMQ\", phi_InvMultiquadric),\n (\"Cubic\", phi_cubic),\n (\"Quintic\", phi_quintic),\n (\"ThinPlate\", phi_thin_plate_spline)\n])\n\n\"\"\"\nThe function to retrive the basis for interpolation\n -> Input:\n :basis: String with the name of the function\n being selected. The available options are:\n [\"MQ\" , \"InvMQ\" , \"Quadratic , \"Gaussian\"]\n ->Output:\n :basis function: two float parameters=> e (the epsilopn of the fuction)\n r (Distance form center)\n\n\"\"\"\nfunction _get_kernel(basis::String = \"MQ\"; func_dict = funcs)\n if basis ∉ keys(func_dict)\n throw(DomainError(basis, \"Basis function not implemented\\n If you want your own function set it using φ parameter\"))\n end\n func_dict[basis]\nend\n\n# Distance calculation function \nr(x, xi) = norm(x .- xi)\n\n\"\"\"\nbuild the onterpolation matrix\n\n-> Input:\n :basis: ::Matrix with data to be interpolated\n->Output:\n :Weights vector: Vector containing the weights of the interpolation\n\"\"\"\nfunction _build(X, y; φ = _get_kernel[\"QM\"], ϵ = 1.0)\n A = ones((size(X)[1], size(X)[1]))\n for i = 1:size(X)[1], j = 1:size(X)[1]\n A[i, j] = φ(r(X[i, :], X[j, :]), ϵ)\n end\n sigm_y = std(y)\n if std(y) != 0\n newy = (y .- mean(y)) / std(y)\n w = (pinv(A) * newy)\n else\n w = (pinv(A) * y)\n end\n w\nend", "meta": {"hexsha": "73e6f73a329c84b1e6c31eeaa9d4c6ae73955a71", "size": 2171, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils/RBFutils.jl", "max_stars_repo_name": "munozariasjm/RbfInterpolationTools.jl", "max_stars_repo_head_hexsha": "f9889bf24e774761a973db25c9a9540970e5cfbc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-03T19:26:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T19:26:24.000Z", "max_issues_repo_path": "src/utils/RBFutils.jl", "max_issues_repo_name": "munozariasjm/RbfInterpolationTools.jl", "max_issues_repo_head_hexsha": "f9889bf24e774761a973db25c9a9540970e5cfbc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-01-03T01:08:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-16T22:40:06.000Z", "max_forks_repo_path": "src/utils/RBFutils.jl", "max_forks_repo_name": "munozariasjm/RbfInterpolationTools.jl", "max_forks_repo_head_hexsha": "f9889bf24e774761a973db25c9a9540970e5cfbc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1527777778, "max_line_length": 124, "alphanum_fraction": 0.5393827729, "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122720843811, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.8122787165614551}} {"text": "# Methods to provide grids and distance-matrices for\n# different topologies of Kohonen maps (SOMs).\n\n\n\"\"\"\n gridRectangular(xdim, ydim)\n\nCreate coordinates of all neurons on a rectangular SOM.\n\nThe return-value is an array of size (Number-of-neurons, 2) with\nx- and y- coordinates of the neurons in the first and second\ncolumn respectively.\nThe distance between neighbours is 1.0.\nThe point of origin is bottom-left.\nThe first neuron sits at (0,0).\n\"\"\"\nfunction gridRectangular(xdim, ydim)\n\n grid = zeros(Float64, (xdim*ydim, 2))\n for ix in 1:xdim\n for iy in 1:ydim\n\n grid[ix+(iy-1)*xdim, 1] = ix-1\n grid[ix+(iy-1)*xdim, 2] = iy-1\n end\n end\n return grid\nend\n\n\n\n\"\"\"\n gridHexagonal(xdim, ydim)\n\nCreate coordinates of all neurons on a hexagonal SOM.\n\nThe return-value is an array of size (Number-of-neurons, 2) with\nx- and y- coordinates of the neurons in the first and second\ncolumn respectively.\nThe distance between neighbours is 1.0.\nThe point of origin is bottom-left.\nThe first neuron sits at (0,0).\n\"\"\"\nfunction gridHexagonal(xdim, ydim)\n\n grid = zeros(Float64, (xdim*ydim, 2))\n rowHeight = √(1-0.25)\n\n for ix in 1:xdim\n for iy in 1:ydim\n\n if iy % 2 != 0 # 1st, 3rd, ... line\n grid[ix+(iy-1)*xdim, 1] = ix - 1\n else # 2nd, 4th, ... line\n grid[ix+(iy-1)*xdim, 1] = ix - 0.5\n end\n\n grid[ix+(iy-1)*xdim, 2] = (iy-1) * rowHeight\n end\n end\n return grid\nend\n\n\n\"\"\"\n gridSpherical(numNeurons)\n\nCreate coordinates of dim neurons on a spherical SOM.\n\nThe neurons are almost equally distributed on a sphere by\napplying Fibonacci's spirals.\nThe radius of the sphere is adapted to get a distance of neighbours\nof about 1.0.\nThe return-value is an array of size (Number-of-neurons, 3) with\nx-, y- and z- coordinates of the neurons in the first, second and third\ncolumn respectively.\nThe point of origin is bottom-left.\nThe center of the sphere sits at (0,0).\n\"\"\"\nfunction gridSpherical(numNeurons)\n\n r = √(numNeurons/(4 * π))\n grid = zeros(Float64, (numNeurons, 3))\n\n # iterate Fibonacci spiral:\n for i in 1:(numNeurons)\n py = (i-1) * 2/numNeurons - 1 + (1/numNeurons)\n pr = √(1-py^2)\n ϕ = (i-1) * π * (3-√5)\n px = cos(ϕ) * pr\n pz = sin(ϕ) * pr\n\n #println(\"raw: $px $py $pz\")\n\n # shift point from origin to atom location:\n px = r * px\n py = r * py\n pz = r * pz\n\n #println(\"scaled: $px $py $pz\")\n grid[i,:] = [px, py, pz]\n end\n return grid\nend\n\n# verify sphere:\n# x = gridSpherical(50)\n# R\"\"\"\n# library(rgl)\n# plot3d($x)\n# #readline(prompt=\"Press [enter] to continue\")\n# \"\"\"\n\n\n\"\"\"\n distMatrix(grid::Array, toroidal::Bool)\n\nReturn the distance matrix for a non-toroidal or toroidal SOM.\n\n# Arguments\n- `grid`: coordinates of all neurons as generated by\n one of the `grid-`functions with x-coordinates in 1st column\n and y-coordinates in 2nd column.\n- `toroidal`: true for a toroidal SOM.\n\"\"\"\nfunction distMatrix(grid::Array, toroidal::Bool)\n\n X = 1\n Y = 2\n xdim = maximum(grid[:,X]) - minimum(grid[:,X]) + 1.0\n ydim = maximum(grid[:,Y]) - minimum(grid[:,Y]) + 1.0\n\n numNeurons = nrow(grid)\n\n dm = zeros(Float64, (numNeurons,numNeurons))\n for i in 1:numNeurons\n for j in 1:numNeurons\n Δx = abs(grid[i,X] - grid[j,X])\n Δy = abs(grid[i,Y] - grid[j,Y])\n\n if toroidal\n Δx = min(Δx, xdim-Δx)\n Δy = min(Δy, ydim-Δy)\n end\n\n dm[i,j] = √(Δx^2 + Δy^2)\n end\n end\n # show(STDOUT, \"text/plain\", grid)\n # show(STDOUT, \"text/plain\", dm)\n return dm\nend\n\n\n\n\"\"\"\n distMatrixSphere(grid::Array)\n\nReturn the distance matrix for a spherical SOM.\n\n# Arguments\n- `grid`: coordinates of all neurons as gereated by\n one of the `grid-`functions with x-coordinates in 1st,\n y-coordinates in 2nd and z-coordinates in 3rd column.\n Point of origin must be in the center of the spere.\n\"\"\"\nfunction distMatrixSphere(grid::Array)\n\n r = (maximum(grid) - minimum(grid)) / 2\n\n numNeurons = nrow(grid)\n\n dm = zeros(Float64, (numNeurons,numNeurons))\n for i in 1:numNeurons\n for j in 1:numNeurons\n len_i = norm(grid[i,:])\n len_j = norm(grid[j,:])\n bog = grid[i,:] ⋅ grid[j,:] / (len_i * len_j)\n if bog > 1\n bog = 1.0\n end\n α = acos(bog)\n dm[i,j] = r * α\n end\n end\n return dm\nend\n", "meta": {"hexsha": "7ac99912a8847d4f0362f96a44a9cf0355fb8d5b", "size": 4619, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/grids.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SOM.jl-172a5912-0be3-5bce-b68a-ea4f60b69b05", "max_stars_repo_head_hexsha": "51b9073c8e9f896f415b938ea15a65ea3b32558e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2018-10-31T10:17:26.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-09T17:55:05.000Z", "max_issues_repo_path": "src/grids.jl", "max_issues_repo_name": "andreasdominik/SOM.jl", "max_issues_repo_head_hexsha": "a0a85496bb7c15921bfeed636e9ff37ee8a138f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2018-04-25T06:25:09.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-08T17:14:57.000Z", "max_forks_repo_path": "src/grids.jl", "max_forks_repo_name": "andreasdominik/SOM.jl", "max_forks_repo_head_hexsha": "a0a85496bb7c15921bfeed636e9ff37ee8a138f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2018-05-07T16:14:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T10:45:10.000Z", "avg_line_length": 24.5691489362, "max_line_length": 71, "alphanum_fraction": 0.5886555532, "num_tokens": 1409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897558991953, "lm_q2_score": 0.8633916222765627, "lm_q1q2_score": 0.8122699935669777}} {"text": "# Locally Linear Embedding (LLE)\n# ------------------------\n# Nonlinear dimensionality reduction by locally linear embedding,\n# Roweis, S. & Saul, L., Science 290:2323 (2000)\n\n#### LLE type\nimmutable LLE{T <: Real} <: SpectralResult\n k::Int\n λ::AbstractVector{T}\n proj::Projection{T}\n\n LLE{T}(k::Int, λ::AbstractVector{T}, proj::Projection{T}) = new(k, λ, proj)\nend\n\n## properties\noutdim(M::LLE) = size(M.proj, 1)\nprojection(M::LLE) = M.proj\n\neigvals(M::LLE) = M.λ\nneighbors(M::LLE) = M.k\n\n## show & dump\nfunction show(io::IO, M::LLE)\n print(io, \"LLE(indim = $(indim(M)), outdim = $(outdim(M)), neighbors = $(neighbors(M)))\")\nend\n\nfunction dump(io::IO, M::LLE)\n show(io, M)\n println(io, \"eigenvalues: \")\n Base.showarray(io, M.λ', header=false, repr=false)\n println(io)\n println(io, \"projection:\")\n Base.showarray(io, M.proj, header=false, repr=false)\nend\n\n## interface functions\nfunction transform{T<:Real}(::Type{LLE}, X::DenseMatrix{T}; d::Int=2, k::Int=12)\n n = size(X, 2)\n\n # Construct NN graph\n D, E = find_nn(X, k)\n\n # Select largest connected component\n cc = components(E)\n c = cc[indmax(map(size, cc))]\n if length(cc) == 1\n c = cc[1]\n else\n c = cc[indmax(map(size, cc))]\n # renumber edges\n R = Dict(c, 1:length(c))\n Ec = zeros(Int,k,length(c))\n for i = 1 : length(c)\n Ec[:,i] = map(i->get(R,i,0), E[:,c[i]])\n end\n E = Ec\n X = X[:,c]\n end\n\n if k > d\n warn(\"K>D: regularization will be used\")\n tol = 1e-5\n else\n tol = 0\n end\n\n # Reconstruct weights\n W = zeros(k, n)\n for i = 1 : n\n Z = X[:, E[:,i]] .- X[:,i]\n C = Z'*Z\n C = C + eye(k, k) * tol * trace(C)\n wi = vec(C\\ones(k, 1))\n W[:, i] = wi./sum(wi)\n end\n\n # Compute embedding\n M = speye(n,n)\n for i = 1 : n\n w = W[:, i]\n jj = E[:, i]\n M[i,jj] = M[i,jj] - w'\n M[jj,i] = M[jj,i] - w\n M[jj,jj] = M[jj,jj] + w*w'\n end\n\n λ, V = decompose(M, d)\n return LLE{T}(k, λ, scale!(V', sqrt(n)))\nend\n", "meta": {"hexsha": "75ebc020b240c9f45973ca14604901ba95fffe77", "size": 2108, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lle.jl", "max_stars_repo_name": "JuliaPackageMirrors/ManifoldLearning.jl", "max_stars_repo_head_hexsha": "4f994ed07f1f7cd62c5b36efae9db473a5031ac3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lle.jl", "max_issues_repo_name": "JuliaPackageMirrors/ManifoldLearning.jl", "max_issues_repo_head_hexsha": "4f994ed07f1f7cd62c5b36efae9db473a5031ac3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lle.jl", "max_forks_repo_name": "JuliaPackageMirrors/ManifoldLearning.jl", "max_forks_repo_head_hexsha": "4f994ed07f1f7cd62c5b36efae9db473a5031ac3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4222222222, "max_line_length": 93, "alphanum_fraction": 0.5128083491, "num_tokens": 709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897509188344, "lm_q2_score": 0.863391611731321, "lm_q1q2_score": 0.8122699793461204}} {"text": "#=\n A/B test\n\n From http://rpubs.com/rasmusab/exercise_2_bayesian_ab_testing\n \"\"\"\n Exercise 2: Bayesian A/B testing for Swedish Fish Incorporated with Stan\n Rasmus Bååth\n\n Swedish Fish Incorporated is the largest Swedish company delivering fish by mail order,\n but you probably already knew that. The marketing department have done a pilot study and\n tried two different marketing methods:\n\n A: Sending a mail with a colorful brochure that invites people to sign up for a one year\n salmon subscription.\n\n B: Sending a colorful brochure that invites people to sign up for a one year\n salmon subscription nd that includes a free salmon.\n\n The marketing department sent out 16 mails of type A and 16 mails of type B.\n Six Danes that received a mail of type A signed up for one year of salmon, and\n ten Danes that received a mail of type B signed up!\n\n The marketing department now wants to know, which method should we use, A or B?\n\n At the bottom of this document you’ll find a solution. But try yourself first!\n Question I: Build a Bayesian model in Stan that answers the question: What is the\n probability that method B is better than method A?\n \"\"\"\n\n See ~/stan/ab_testing.R\n ~/blog/ab_testing.blog\n ~/psi/ab_testing.psi\n ~/webppl/ab_testing.wppl\n=#\n\nusing Turing, StatsPlots, DataFrames\n# using ReverseDiff, Zygote, Tracker\n# Turing.setadbackend(:reversediff)\n# Turing.setadbackend(:zygote)\n# Turing.setadbackend(:tracker)\n\ninclude(\"jl_utils.jl\")\n\n#=\nummary Statistics\n parameters mean std naive_se mcse ess rhat\n Symbol Float64 Float64 Float64 Float64 Float64 Float64\n\n rateA 0.3893 0.1126 0.0003 0.0009 15774.8462 1.0004\n rateB 0.6121 0.1108 0.0003 0.0008 16943.7123 1.0001\n\nQuantiles\n parameters 2.5% 25.0% 50.0% 75.0% 97.5%\n Symbol Float64 Float64 Float64 Float64 Float64\n\n rateA 0.1839 0.3088 0.3857 0.4659 0.6183\n rateB 0.3847 0.5397 0.6153 0.6918 0.8148\n\nmean(rateB > rateA): 0.91461875\nmean(rateB - rateA): 0.22276908208667892\n=#\n@model function ab_testing(nA=16,nB=16,obsSA=6, obsSB=10)\n # nA = 16 # Number of sent mail\n # nB = 16\n\n # obsSA = 6; # Number of signments (observed)\n # obsSB = 10\n\n rateA ~ Beta(1,1) # priors\n rateB ~ Beta(1,1)\n\n obsSA ~ Binomial(nA,rateA) # likelihood\n obsSB ~ Binomial(nB,rateB)\n\n # This variant don't work!\n # sA ~ Binomial(nA,rateA) # likelihood\n # sB ~ Binomial(nB,rateB)\n # sA == obsSA || begin Turing.@addlogprob! -Inf; return; end\n # sB == obsSB || begin Turing.@addlogprob! -Inf; return; end\n\nend\n\nmodel = ab_testing(16,16,6,10)\n# model = ab_testing(160,160,60,100)\nnum_chains = 4\n# chains = sample(model, Prior(), MCMCThreads(), 1000, num_chains)\nchains = sample(model, MH(), MCMCThreads(), 40_000, num_chains)\n# chains = sample(model, MH(), 40_000)\n\n# chains = sample(model, PG(20), MCMCThreads(), 10_000, num_chains)\n# chains = sample(model, IS(), MCMCThreads(), 10_000, num_chains)\n\n# chains = sample(model, Gibbs(MH(:sA,:sB),NUTS(1000,0.65,:rateA,:rateB)), MCMCThreads(), 40_000, num_chains)\n\ndisplay(chains)\n# display(plot(chains))\n\ndf = DataFrame(chains);\nprintln(\"mean(rateB > rateA): \", mean(df[!,\"rateB\"] .> df[!,\"rateA\"]))\nprintln(\"mean(rateB - rateA): \", mean(df[!,\"rateB\"] .- df[!,\"rateA\"]))\n", "meta": {"hexsha": "a065fb28dfc2c5d6e05dc3a943f926f5a5caafdb", "size": 3417, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/ab_testing.jl", "max_stars_repo_name": "Wikunia/hakank", "max_stars_repo_head_hexsha": "030bc928d2efe8dcbc5118bda3f8ae9575d0fd13", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "julia/turing/ab_testing.jl", "max_issues_repo_name": "Wikunia/hakank", "max_issues_repo_head_hexsha": "030bc928d2efe8dcbc5118bda3f8ae9575d0fd13", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/turing/ab_testing.jl", "max_forks_repo_name": "Wikunia/hakank", "max_forks_repo_head_hexsha": "030bc928d2efe8dcbc5118bda3f8ae9575d0fd13", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8316831683, "max_line_length": 109, "alphanum_fraction": 0.6701785192, "num_tokens": 1102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297887874625, "lm_q2_score": 0.90192067059785, "lm_q1q2_score": 0.8122064309965283}} {"text": "# Benchmarking the NLsolve.fixedpoint() function in the use case of: https://lectures.quantecon.org/jl/mccall_model_with_separation.html\n\n# Dependencies. \nusing Distributions # So that some method overwritten error from NLsolve doesn't intermingle with the benchmarks. \n\n# Wages (global since used in constructor)\nconst n = 60 # n possible outcomes for wage\nconst default_w_vec = linspace(10, 20, n) # wages between 10 and 20\nconst a, b = 600, 400 # shape parameters\nconst dist = BetaBinomial(n-1, a, b)\nconst default_p_vec = pdf.(dist, support(dist))\n\n# Model Struct (global since types can't be defined in local scope)\nmutable struct McCallModel{TF <: AbstractFloat,\n TAV <: AbstractVector{TF},\n TAV2 <: AbstractVector{TF}}\n α::TF # Job separation rate\n β::TF # Discount rate\n γ::TF # Job offer rate\n c::TF # Unemployment compensation\n σ::TF # Utility parameter\n w_vec::TAV # Possible wage values\n p_vec::TAV2 # Probabilities over w_vec\n\n McCallModel(α::TF=0.2,\n β::TF=0.98,\n γ::TF=0.7,\n c::TF=6.0,\n σ::TF=2.0,\n w_vec::TAV=default_w_vec,\n p_vec::TAV2=default_p_vec) where {TF, TAV, TAV2} =\n new{TF, TAV, TAV2}(α, β, γ, c, σ, w_vec, p_vec)\nend\n\n\n# Implementation from McCall with separation lecture on QuantEcon \nfunction default_quantecon()\n # Utility function. \n function u(c::Real, σ::Real)\n if c > 0\n return (c^(1 - σ) - 1) / (1 - σ)\n else\n return -10e6\n end\n end\n # Instantiate model object. \n mcm = McCallModel()\n # Define the function to be used in the iteration loop. \n \"\"\"\n A function to update the Bellman equations. Note that V_new is modified in\n place (i.e, modified by this function). The new value of U is returned.\n \"\"\"\n function update_bellman!(mcm::McCallModel,\n V::AbstractVector,\n V_new::AbstractVector,\n U::Real)\n # Simplify notation\n α, β, σ, c, γ = mcm.α, mcm.β, mcm.σ, mcm.c, mcm.γ\n\n for (w_idx, w) in enumerate(mcm.w_vec)\n # w_idx indexes the vector of possible wages\n V_new[w_idx] = u(w, σ) + β * ((1 - α) * V[w_idx] + α * U)\n end\n\n U_new = u(c, σ) + β * (1 - γ) * U +\n β * γ * dot(max.(U, V), mcm.p_vec)\n\n return U_new\n end\n # Define a function to carry out the iteration loop. \n function solve_mccall_model(mcm::McCallModel;\n tol::AbstractFloat=1e-5,\n max_iter::Integer=2000)\n\n V = ones(length(mcm.w_vec)) # Initial guess of V\n V_new = similar(V) # To store updates to V\n U = 1.0 # Initial guess of U\n i = 0\n error = tol + 1\n\n while error > tol && i < max_iter\n U_new = update_bellman!(mcm, V, V_new, U)\n error_1 = maximum(abs, V_new - V)\n error_2 = abs(U_new - U)\n error = max(error_1, error_2)\n V[:] = V_new\n U = U_new\n i += 1\n end\n\n return V, U\n end\n # Get results. \n return solve_mccall_model(mcm)\nend \n\n# Implementation of the above, but with one vector that holds the state of the calculation [U V]\nfunction stacked_quantecon()\n # Utility function. \n function u(c::Real, σ::Real)\n if c > 0\n return (c^(1 - σ) - 1) / (1 - σ)\n else\n return -10e6\n end\n end\n # Instantiate model object. \n mcm = McCallModel()\n # Function for each loop of the iteration. \n \"\"\"\n An (in-place) stacked implementation of the Bellman operator for the McCall model with separation. By convention, U is at the top of the vector. \n bellman_operator!(newVec::AbstractVector, oldVec::AbstractVector, model::McCallModel = mcm)\n \"\"\"\n function bellman_operator!(newVec, oldVec, model = mcm) \n # Unpack parameters. \n α, β, σ, c, γ = mcm.α, mcm.β, mcm.σ, mcm.c, mcm.γ\n # Add new V(w) values to newVec.\n for (w_idx, w) in enumerate(mcm.w_vec)\n # w_idx indexes the vector of possible wages\n newVec[w_idx + 1] = u(w, σ) + β * ((1 - α) * oldVec[1 + w_idx] + α * oldVec[1])\n end\n # Add new U value to newVec. \n newVec[1] = u(c, σ) + β * (1 - γ) * oldVec[1] + β * γ * dot(max.(oldVec[1], oldVec[2:end]), mcm.p_vec)\n end\n # Function to carry out the iteration. \n \"\"\"\n Modified version of solve_mccall_model(), which uses our bellman_operator! function. \n solve_mccall_model_inplace(mcm::McCallModel; tol::AbstractFloat=1e-5, max_iter::Integer=2000)\n \"\"\" \n function solve_mccall_model(mcm; tol=1e-5, max_iter=2000)\n oldVec = ones(length(mcm.w_vec) + 1) # Initial guess for states. Same as those in the QE implementation. \n newVec = similar(oldVec) # To store updates. \n iter = 0 # Initialize the iteration counter. \n error = tol + 1 # Initialize the error. \n\n while error > tol && iter < max_iter\n bellman_operator!(newVec, oldVec, mcm)\n error = maximum(abs.(newVec - oldVec))\n iter += 1\n oldVec .= newVec \n end \n\n return newVec\n end\n # Get results. \n return solve_mccall_model(mcm)\nend\n\n# Implementation of stacked_quantecon(), but using the NLsolve fixed point method. m = 0. \nfunction fixedpoint_iteration()\n # Utility function. \n function u(c::Real, σ::Real)\n if c > 0\n return (c^(1 - σ) - 1) / (1 - σ)\n else\n return -10e6\n end\n end\n # Instantiate model object. \n mcm = McCallModel()\n # Function for each loop of the iteration. \n \"\"\"\n An (in-place) stacked implementation of the Bellman operator for the McCall model with separation. By convention, U is at the top of the state vector. \n bellman_operator!(newVec::AbstractVector, oldVec::AbstractVector, model::McCallModel = mcm)\n \"\"\"\n function bellman_operator!(newVec, oldVec, model = mcm) \n # Unpack parameters. \n α, β, σ, c, γ = mcm.α, mcm.β, mcm.σ, mcm.c, mcm.γ\n # Add new V(w) values to newVec.\n for (w_idx, w) in enumerate(mcm.w_vec)\n # w_idx indexes the vector of possible wages\n newVec[w_idx + 1] = u(w, σ) + β * ((1 - α) * oldVec[1 + w_idx] + α * oldVec[1])\n end\n # Add new U value to newVec. \n newVec[1] = u(c, σ) + β * (1 - γ) * oldVec[1] + β * γ * dot(max.(oldVec[1], oldVec[2:end]), mcm.p_vec)\n end\n # Solve \n init = ones(length(mcm.w_vec)+1)\n return fixedpoint(bellman_operator!, init; ftol = 1e-5, iterations = 2000)\nend \n\n# Using fixedpoint() for variable m. \nfunction fixedpoint_anderson_m(m)\n # Utility function. \n function u(c::Real, σ::Real)\n if c > 0\n return (c^(1 - σ) - 1) / (1 - σ)\n else\n return -10e6\n end\n end\n # Instantiate model object. \n mcm = McCallModel()\n # Function for each loop of the iteration. \n \"\"\"\n An (in-place) stacked implementation of the Bellman operator for the McCall model with separation. By convention, U is at the top of the state vector. \n bellman_operator!(newVec::AbstractVector, oldVec::AbstractVector, model::McCallModel = mcm)\n \"\"\"\n function bellman_operator!(newVec, oldVec, model = mcm)\n # Unpack parameters. \n α, β, σ, c, γ = mcm.α, mcm.β, mcm.σ, mcm.c, mcm.γ\n # Add new V(w) values to newVec.\n for (w_idx, w) in enumerate(mcm.w_vec)\n # w_idx indexes the vector of possible wages\n newVec[w_idx + 1] = u(w, σ) + β * ((1 - α) * oldVec[1 + w_idx] + α * oldVec[1])\n end\n # Add new U value to newVec. \n newVec[1] = u(c, σ) + β * (1 - γ) * oldVec[1] + β * γ * dot(max.(oldVec[1], oldVec[2:end]), mcm.p_vec)\n end\n # Solve \n init = ones(length(mcm.w_vec)+1)\n return fixedpoint(bellman_operator!, init; m = m, ftol = 1e-5, iterations = 2000)\nend \n\nfunction fixedpoint_newton()\n # Utility function. \n function u(c::Real, σ::Real)\n if c > 0\n return (c^(1 - σ) - 1) / (1 - σ)\n else\n return -10e6\n end\n end\n # Instantiate model object. \n mcm = McCallModel()\n # Function for each loop of the iteration. \n \"\"\"\n An (in-place) stacked implementation of the Bellman operator for the McCall model with separation. By convention, U is at the top of the state vector. \n bellman_operator!(newVec::AbstractVector, oldVec::AbstractVector, model::McCallModel = mcm)\n \"\"\"\n function bellman_operator!(newVec, oldVec, model = mcm)\n # Unpack parameters. \n α, β, σ, c, γ = mcm.α, mcm.β, mcm.σ, mcm.c, mcm.γ\n # Add new V(w) values to newVec.\n for (w_idx, w) in enumerate(mcm.w_vec)\n # w_idx indexes the vector of possible wages\n newVec[w_idx + 1] = u(w, σ) + β * ((1 - α) * oldVec[1 + w_idx] + α * oldVec[1])\n end\n # Add new U value to newVec. \n newVec[1] = u(c, σ) + β * (1 - γ) * oldVec[1] + β * γ * dot(max.(oldVec[1], oldVec[2:end]), mcm.p_vec)\n end\n # Solve \n init = ones(length(mcm.w_vec)+1)\n return fixedpoint(bellman_operator!, init; method = :newton, ftol = 1e-5, iterations = 2000)\nend ", "meta": {"hexsha": "6b6e047e17af5211ba03273c35c06b95dbe67e8c", "size": 9502, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia_sandbox/QuantEcon-tests/mccall_utilities.jl", "max_stars_repo_name": "ajozefiak/computing_and_datascience", "max_stars_repo_head_hexsha": "ecc5a369adc5784e85614f3f74ae25ca1aede1f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2018-07-27T00:56:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-15T00:20:26.000Z", "max_issues_repo_path": "julia_sandbox/QuantEcon-tests/mccall_utilities.jl", "max_issues_repo_name": "ajozefiak/computing_and_datascience", "max_issues_repo_head_hexsha": "ecc5a369adc5784e85614f3f74ae25ca1aede1f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 96, "max_issues_repo_issues_event_min_datetime": "2017-12-22T18:26:34.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-13T22:53:47.000Z", "max_forks_repo_path": "julia_sandbox/QuantEcon-tests/mccall_utilities.jl", "max_forks_repo_name": "ajozefiak/computing_and_datascience", "max_forks_repo_head_hexsha": "ecc5a369adc5784e85614f3f74ae25ca1aede1f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2018-01-05T19:05:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-19T17:01:09.000Z", "avg_line_length": 38.7836734694, "max_line_length": 155, "alphanum_fraction": 0.5697747843, "num_tokens": 2811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658465, "lm_q2_score": 0.9005297794439687, "lm_q1q2_score": 0.8122064302851743}} {"text": "A = [1 2 3; -4 -5 -6]\n\nA[2,3]\n\nlength(A)\n\nsize(A,1)\n\nsize(A,2)\n\nsumA = 0\nfor i = 1:size(A,1)\n for j = 1:size(A,2)\n sumA += A[i,j]\n end\nend\n\nprintln(\"Sum of the elements in A = \", sumA)\n\nsumA = 0\nfor i = 1:size(A,1), j = 1:size(A,2)\n sumA += A[i,j]\nend\n\nprintln(\"Sum of the elements in A = \", sumA)\n\nsumAsquared = 0\nfor a in A\n sumAsquared += a^2\nend\n\nprint(\"Sum of the squares of the elements in A = \", sumAsquared)\n\nC = ones(5,3) # 5-by-4 matrix with all elements == 1\n\nones(5) # 1-d array (can be used as a column vector)\n\nones(5,1) # 2-d array, column vector\n\nones(1,5) # 2-d array, row vector\n\nD = [A; C] # Vertical concatenation - arrays must have same # columns\nE = [zeros(5) C] # Horizontal concatenation - arrays must have same # rows\nF = [A ones(2,2); zeros(1,5)] # General vertical-horizontal concatenation - all dimensions must match\n\nG = [1:5 ones(Int64,5) 101:105]\n\nB = A.^2 .- 3A # Apply function elementwise\n\nB = @. A^2 - 3A # Easier syntax - entire expression evaluated elementwise\n\nA[1,:] # Row 1\n\nA[:,1] # Column 1\n\nA[:,2:3] # Columns 2-3\n\nA[:,[1,3]] .= 0 # Set columns 1 and 3 to zero\nA\n\nA[:,2:3] = 2A[:,1:2] # Set columns 2 and 3 to twice of columns 1 and 2\nA\n\n\n", "meta": {"hexsha": "8865a94821067e3866474b06074ecc8269508bc2", "size": 1327, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "textbook/_build/jupyter_execute/content/Arrays_and_Dictionaries/Multi_Dimensional_Arrays.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/Arrays_and_Dictionaries/Multi_Dimensional_Arrays.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/Arrays_and_Dictionaries/Multi_Dimensional_Arrays.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": 20.4153846154, "max_line_length": 102, "alphanum_fraction": 0.5546345139, "num_tokens": 472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213853793453, "lm_q2_score": 0.9032941988938413, "lm_q1q2_score": 0.8121711315145564}} {"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 Plots, Distributions, Random, Statistics\ngr(fmt = :png, size = (900, 500))\n\nfunction ksl(distribution, n = 100)\n title = nameof(typeof(distribution))\n observations = rand(distribution, n)\n sample_means = cumsum(observations) ./ (1:n)\n μ = mean(distribution)\n plot(repeat((1:n)', 2),\n [zeros(1, n); observations'], label = \"\", color = :grey, alpha = 0.5)\n plot!(1:n, observations, color = :grey, markershape = :circle,\n alpha = 0.5, label = \"\", linewidth = 0)\n hline!([μ], color = :black, linewidth = 1.5, linestyle = :dash, grid = false, label = [\"Mean\"])\n plot!(1:n, sample_means, linewidth = 3, alpha = 0.6, color = :green,\n label = \"Sample mean\")\n return plot!(title = title)\nend\n\n# Example distributions\ndistributions = [TDist(10), Beta(2,2), Gamma(5,2), Poisson(4), LogNormal(0.5), Exponential(1)]\n\nRandom.seed!(0); #reproducible results\nksl(Normal())\nplot(ksl.(sample(distributions, 3, replace = false))..., layout = (3, 1), legend = false)\n\n# Cauchy distribution may not converge as E|X| < ∞ not satisfied (heavy tailed)\n\n\nfunction plotmeans(distribution::Distribution{Univariate,Continuous};n=1000)\n sample_mean = cumsum(rand(distribution,n)) ./ (1:n)\n plot(1:n, sample_mean, label = \"sample mean\")\n hline!([0], color = :black, linestyle = :dash)\nend\n\nRandom.seed!(0);\nplotmeans(Cauchy(),n=10000)\n\n\nusing StatsPlots\n\nfunction simulation1(distribution::Distribution{Univariate,Continuous}; n=250, k = 10_000)\n σ = std(distribution)\n y = rand(distribution,n,k)\n y .-= mean(distribution)\n y = mean(y,dims=1)\n y = √n *vec(y)\n density(y,label = \"Empirical Distribution\")\n return plot!(Normal(0,σ), linestyle = :dash, label = \"Normal(0.0, $(σ^2))\")\nend\n\nRandom.seed!(0);\nsimulation1(Exponential(0.5), n=100)\n\nfunction simulation2(distribution = Beta(2, 2), n = 5, k = 10_000)\n y = rand(distribution, k, n)\n for col in 1:n\n y[:,col] += rand([-0.5, 0.6, -1.1], k)\n end\n y = (y .- mean(distribution)) ./ std(distribution)\n y = cumsum(y, dims = 2) ./ sqrt.(1:5)' # return grid of data\nend\n\nys = simulation2()\nplots = [] # would preallocate in optimized code\nfor i in 1:size(ys, 2)\n p = density(ys[:, i], linealpha = i, title = \"n = $i\")\n push!(plots, p)\nend\n\nplot(plots..., legend = false)\n\n# Exercise 1\n\nfunction exercise1(a,b; g = sin, g′ = cos, n=250, k=10_000)\n distribution = Uniform(a,b)\n μ, σ = mean(distribution), std(distribution)\n gμ = sin.(mean(distribution))\n X = rand(distribution,n,k)\n X = mean(X, dims = 1)\n X = vec(X)\n y = √n .* vec(g.(X) .- g.(μ))\n density(y,label = \"Empirical Distribution\")\n return plot!(Normal(0,g′(μ).*σ), linestyle = :dash, label = \"Asymptotic\")\nend\n\nexercise1(0.0,π/2,k=15000)\n\n\n# Exercise 2\nfunction exercise2(;n = 250, k = 50_000, dw = Uniform(-1, 1), du = Uniform(-2, 2))\n vw = var(dw)\n vu = var(du)\n Σ = [vw vw; vw vu+vw]\n Q = inv(sqrt(Σ))\n\n function generate_data(dw, du, n)\n dw = rand(dw, n)\n X = [dw dw + rand(du, n)]\n return sqrt(n) * mean(X, dims = 1)\n end\n\n X = mapreduce(x -> generate_data(dw, du, n), vcat, 1:k)\n X = sqrt(n) .* mean(X, dims=1)\n X = Q*X'\n X = sum(abs2, X, dims = 1)\n X = vec(X)\n density(X, label = \"\", xlim = (0, 10))\n return plot!(Chisq(2), color = :black, linestyle = :dash,\n label = \"Chi-squared with 2 degrees of freedom\", grid = false)\nend\nexercise2()\n", "meta": {"hexsha": "7fd1069b04df5a6e91a19d8a84559c4063ee755b", "size": 3663, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ToolsandTechniques_LLNCLT.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_LLNCLT.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_LLNCLT.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": 31.3076923077, "max_line_length": 99, "alphanum_fraction": 0.6161616162, "num_tokens": 1184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.8887587890727754, "lm_q1q2_score": 0.8120380363752464}} {"text": "\r\n# Identity matrix\r\neye(m::Int64) = Diagonal(ones(m))\r\n\r\nunpack(s, f::Symbol) = reduce(hcat, getproperty.(s, f))\r\n\r\nfunction unpack(s, f::Vector{Symbol})\r\n A = []\r\n for i in f\r\n push!(A, reduce(hcat, getproperty.(s, i)))\r\n end\r\n return A\r\nend\r\n\r\nunpack_matrix(s, f) = getproperty.(s, f)\r\n\r\nfunction unpack_matrix(s, f::Vector{Symbol})\r\n A = []\r\n for i in f\r\n push!(A, getproperty.(s, i))\r\n end\r\n return A\r\nend\r\n\r\n_return_type(P::Matrix, C) = Matrix(C)\r\n_return_type(P, C) = Diagonal(C)\r\n\r\n_square_root_filter(filter::CholeskyFactorization, P) = _return_type(P, cholesky(P).L)\r\n\r\nfunction _square_root_filter(filter::ModifiedCholeskyFactorization, P)\r\n\tF = _modified_cholesky(P)\r\n\t_return_type(P, F.U * sqrt.(F.D))\r\nend\r\n\r\nfunction _square_root_filter(filter::SVDFactorization, P)\r\n\t_C = svd(Matrix(P))\r\n\treturn _return_type(P, _C.U * sqrt(Diagonal(_C.S)))\r\nend\r\n\r\n\"\"\"\r\n\r\n\tF = _modified_cholesky(P)\r\n\r\nComputes modified Cholesky factors F.U and F.D of a symmetric positive definite matrix P,\r\nsuch that F.U is unit upper triangular and F.D is diagonal. Thus, and P = F.U*F.D*F.U'.\r\n\r\nReference: Grewal - Kalman filtering theory and practice\r\n\r\n\"\"\"\r\nfunction _modified_cholesky(P::AbstractMatrix)\r\n\tisposdef(P) || throw(\"input matrix must be positive-definite. Modified Cholesky factorization failed.\")\r\n\tn = size(P, 1)\r\n\t_P = (P .+ P') ./ 2.0 # take symmetric part\r\n\tU, D = similar(_P), similar(_P)\r\n\tfor j in n:-1:1\r\n \t\tfor i in j:-1:1\r\n\t\t\ts = P[i, j]\r\n\t\t\tfor k in j+1:n\r\n\t\t\t\ts -= U[i, k]*D[k, k]*U[j, k]\r\n\t\t\tend\r\n\t\t\tif i==j\r\n\t\t\t\tD[j, j] = s\r\n\t\t\t\tU[j, j] = 1.0\r\n\t\t\telse\r\n\t\t\t\tU[i, j] = s / D[j, j]\r\n\t\t\tend\r\n\t\tend\r\n\tend\r\n\treturn (U=U, D=D)\r\nend\r\n", "meta": {"hexsha": "cc7025df42aa0b77c3f12e007cf54ce2a6c0aa93", "size": 1685, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Utils.jl", "max_stars_repo_name": "lnacquaroli/KalmanFilter.jl", "max_stars_repo_head_hexsha": "9746b6b1079c499323f777ecf7077a995ec49f78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Utils.jl", "max_issues_repo_name": "lnacquaroli/KalmanFilter.jl", "max_issues_repo_head_hexsha": "9746b6b1079c499323f777ecf7077a995ec49f78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Utils.jl", "max_forks_repo_name": "lnacquaroli/KalmanFilter.jl", "max_forks_repo_head_hexsha": "9746b6b1079c499323f777ecf7077a995ec49f78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7323943662, "max_line_length": 105, "alphanum_fraction": 0.6195845697, "num_tokens": 539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218434359676, "lm_q2_score": 0.8807970811069351, "lm_q1q2_score": 0.8120260687071251}} {"text": "function load_distributions_samples()\nreturn quote\n\nusing .Distributions: Distribution, Uniform, Normal\nimport .Distributions\n\n# ======================================================\n# Sampling from a uniform distribution on balls/spheres\n# ======================================================\n\n\"\"\"\n _sample_unit_nsphere_muller!(D::Vector{Vector{N}}, n::Int, p::Int;\n rng::AbstractRNG=GLOBAL_RNG,\n seed::Union{Int, Nothing}=nothing) where {N}\n\nDraw samples from a uniform distribution on an ``n``-dimensional unit\nsphere using Muller's method.\n\n### Input\n\n- `D` -- output, vector of points\n- `n` -- dimension of the sphere\n- `p` -- number of random samples\n- `rng` -- (optional, default: `GLOBAL_RNG`) random number generator\n- `seed` -- (optional, default: `nothing`) seed for reseeding\n\n### Output\n\nA vector of `nsamples` vectors.\n\n### Algorithm\n\nThis function implements Muller's method of normalised Gaussians [1] to uniformly\nsample over the ``n``-dimensional sphere ``S^n`` (which is the bounding surface\nof the ``n``-dimensional unit ball).\n\nGiven ``n`` canonical Gaussian random variables ``Z₁, Z₂, …, Z_n``, the\ndistribution of the vectors\n\n```math\n\\\\dfrac{1}{α}\\\\left(z₁, z₂, …, z_n\\\\right)^T,\n```\nwhere ``α := \\\\sqrt{z₁² + z₂² + … + z_n²}``, is uniform over ``S^n``.\n\n[1] Muller, Mervin E. *A note on a method for generating points uniformly on\n n-dimensional spheres.* Communications of the ACM 2.4 (1959): 19-20.\n\"\"\"\nfunction _sample_unit_nsphere_muller!(D::Vector{Vector{N}}, n::Int, p::Int;\n rng::AbstractRNG=GLOBAL_RNG,\n seed::Union{Int, Nothing}=nothing) where {N}\n rng = reseed(rng, seed)\n Zdims = [Normal() for _ in 1:n] # normal distributions, one for each dimension\n v = Vector{N}(undef, n) # sample direction\n @inbounds for j in 1:p\n α = zero(N)\n for i in 1:n\n v[i] = rand(rng, Zdims[i])\n α += v[i]^2\n end\n D[j] = v ./ sqrt(α)\n end\n return D\nend\n\n\"\"\"\n _sample_unit_nball_muller!(D::Vector{Vector{N}}, n::Int, p::Int;\n rng::AbstractRNG=GLOBAL_RNG,\n seed::Union{Int, Nothing}=nothing) where {N}\n\nDraw samples from a uniform distribution on an ``n``-dimensional unit ball\nusing Muller's method.\n\n### Input\n\n- `D` -- output, vector of points\n- `n` -- dimension of the ball\n- `p` -- number of random samples\n- `rng` -- (optional, default: `GLOBAL_RNG`) random number generator\n- `seed` -- (optional, default: `nothing`) seed for reseeding\n\n### Output\n\nA vector of `nsamples` vectors.\n\n### Algorithm\n\nThis function implements Muller's method of normalised Gaussians [1] to\nsample from the interior of the ball.\n\nGiven ``n`` Gaussian random variables ``Z₁, Z₂, …, Z_n`` and a uniformly\ndistributed random variable ``r`` with support in ``[0, 1]``, the distribution\nof the vectors\n\n```math\n\\\\dfrac{r^{1/n}}{α} \\\\left(z₁, z₂, …, z_n\\\\right)^T,\n```\nwhere ``α := \\\\sqrt{z₁² + z₂² + … + z_n²}``, is uniform over the\n``n``-dimensional unit ball.\n\n[1] Muller, Mervin E. *A note on a method for generating points uniformly on\n n-dimensional spheres.* Communications of the ACM 2.4 (1959): 19-20.\n\"\"\"\nfunction _sample_unit_nball_muller!(D::Vector{Vector{N}}, n::Int, p::Int;\n rng::AbstractRNG=GLOBAL_RNG,\n seed::Union{Int, Nothing}=nothing) where {N}\n\n rng = reseed(rng, seed)\n Zdims = [Normal() for _ in 1:n] # normal distributions, one for each dimension\n Zrad = Uniform() # distribution to pick random radius\n one_over_n = one(N)/n\n v = Vector{N}(undef, n) # sample direction\n @inbounds for j in 1:p\n α = zero(N)\n for i in 1:n\n v[i] = rand(rng, Zdims[i])\n α += v[i]^2\n end\n r = rand(rng, Zrad)\n β = r^one_over_n / sqrt(α)\n D[j] = v .* β\n end\n return D\nend\n\n# ========================\n# Sampling from a LazySet\n# ========================\n\n\"\"\"\n Sampler\n\nAbstract type for defining new sample methods.\n\n### Notes\n\nAll subtypes should implement a `_sample!` method.\n\"\"\"\nabstract type Sampler end\n\n\"\"\"\n sample(X::LazySet{N}, num_samples::Int;\n rng::AbstractRNG=GLOBAL_RNG,\n seed::Union{Int, Nothing}=nothing) where {N}\n\nSampling of an arbitrary `LazySet` `X`.\n\n### Input\n\n- `X` -- lazyset\n- `num_samples` -- number of random samples\n- `sampler` -- Sampler used (default: `RejectionSampler`)\n- `rng` -- (optional, default: `GLOBAL_RNG`) random number generator\n- `seed` -- (optional, default: `nothing`) seed for reseeding\n\n### Output\n\nA vector of `num_samples` vectors.\nIf `num_samples` is not passed one sample as a single vector is returned.\n\n### Algorithm\n\nSee the documentation of `RejectionSampler`.\n\"\"\"\nfunction sample(X::LazySet{N}, num_samples::Int;\n sampler=RejectionSampler,\n rng::AbstractRNG=GLOBAL_RNG,\n seed::Union{Int, Nothing}=nothing) where {N<:Real}\n require(:Distributions; fun_name=\"sample\")\n @assert isbounded(X) \"this function requires that the set `X` is bounded\"*\n \", but it is not\"\n\n D = Vector{Vector{N}}(undef, num_samples) # preallocate output\n _sample!(D, sampler(X); rng=rng, seed=seed)\n return D\nend\n\n# without argument, returns a single element (instead of a singleton)\nfunction sample(X::LazySet{N}; kwargs...) where {N<:Real}\n return sample(X, 1; kwargs...)[1]\nend\n\n# =====================\n# Rejection Sampling\n# =====================\n\n\"\"\"\n RejectionSampler{S<:LazySet, D<:Distribution} <: Sampler\n\nType used for rejection sampling of an arbitrary `LazySet` `X`.\n\n### Fields\n\n- `X` -- lazyset\n- `box_approx` -- Distribution from which the sample is drawn\n\n### Algorithm\n\nDraw a sample ``x`` from a uniform distribution of a box-overapproximation of the\noriginal set ``X`` in all ``n`` dimensions. The function rejects a drawn sample ``x``\nand redraws as long as the sample is not contained in the original set ``X``,\ni.e., ``x ∉ X``.\n\"\"\"\nstruct RejectionSampler{S<:LazySet, D<:Distribution} <: Sampler\n X::S\n box_approx::Vector{D}\nend\n\nfunction RejectionSampler(X, distribution=Uniform)\n B = box_approximation(X)\n canonical_support = hcat(low(B), high(B))\n dims = size(canonical_support, 1)\n box_approx = [distribution(canonical_support[i,:]...) for i = 1:dims]\n return RejectionSampler(X, box_approx)\nend\n\n\"\"\"\n _sample!(D::Vector{Vector{N}},\n sampler::RejectionSampler;\n rng::AbstractRNG=GLOBAL_RNG,\n seed::Union{Int, Nothing}=nothing) where {N<:Real}\n\nSample points using rejection sampling.\n\n### Input\n\n- `D` -- output, vector of points\n- `sampler` -- Sampler from which the points are sampled\n- `rng` -- (optional, default: `GLOBAL_RNG`) random number generator\n- `seed` -- (optional, default: `nothing`) seed for reseeding\n\n### Output\n\nA vector of `num_samples` vectors.\n\"\"\"\nfunction _sample!(D::Vector{Vector{N}},\n sampler::RejectionSampler;\n rng::AbstractRNG=GLOBAL_RNG,\n seed::Union{Int, Nothing}=nothing) where {N<:Real}\n rng = reseed(rng, seed)\n @inbounds for i in 1:length(D)\n w = rand.(Ref(rng), sampler.box_approx)\n while w ∉ sampler.X\n w = rand.(Ref(rng), sampler.box_approx)\n end\n D[i] = w\n end\n return D\nend\n\nend # quote\nend # function load_distributions_samples()\n", "meta": {"hexsha": "b4a0c8e1071d1b4f5cc8192a660dc761d117de02", "size": 7627, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Utils/samples.jl", "max_stars_repo_name": "UnofficialJuliaMirror/LazySets.jl-b4f0291d-fe17-52bc-9479-3d1a343d9043", "max_stars_repo_head_hexsha": "375c103128089b12d3c08f7011d24fdbffc65c47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Utils/samples.jl", "max_issues_repo_name": "UnofficialJuliaMirror/LazySets.jl-b4f0291d-fe17-52bc-9479-3d1a343d9043", "max_issues_repo_head_hexsha": "375c103128089b12d3c08f7011d24fdbffc65c47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Utils/samples.jl", "max_forks_repo_name": "UnofficialJuliaMirror/LazySets.jl-b4f0291d-fe17-52bc-9479-3d1a343d9043", "max_forks_repo_head_hexsha": "375c103128089b12d3c08f7011d24fdbffc65c47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2658730159, "max_line_length": 85, "alphanum_fraction": 0.6037760587, "num_tokens": 2048, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067244294588, "lm_q2_score": 0.8615382094310355, "lm_q1q2_score": 0.8120055557416664}} {"text": "using Random, PyPlot, StatsBase, Combinatorics\nRandom.seed!(1)\nfunction bruteSetsProbabilityAllMiss(n)\n omega = collect(permutations(1:n))\n matchEvents = []\n\n for i in 1:n\n event = []\n for p in omega\n if p[i] == i\n push!(event,p)\n end\n end\n push!(matchEvents,event)\n end\n\n noMatch = setdiff(omega,union(matchEvents...))\n return length(noMatch)/length(omega)\nend\n\nfunction formulaCalcAllMiss(n)\n return sum([(-1)^k/factorial(k) for k in 0:n])\nend\n\nfunction mcAllMiss(n,N)\n function envelopeStuffer()\n envelopes = Random.shuffle!(collect(1:n))\n return sum([envelopes[i] == i for i in 1:n]) == 0\n end\n\n data = [envelopeStuffer() for _ in 1:N]\n return sum(data)/N\nend\n\nN = 10^6\n\nprintln(\"n\\tBrute Force\\tFormula\\t\\tMonte Carlo\\t\\tAnalytic\",)\nfor n in 1:8\n bruteForce = bruteSetsProbabilityAllMiss(n)\n fromFormula = formulaCalcAllMiss(n)\n fromMC = mcAllMiss(n,N)\n println(n,\"\\t\",round(bruteForce,digits=4),\"\\t\\t\",round(fromFormula,digits=4),\n\t\"\\t\\t\",round(fromMC,digits=4),\"\\t\\t\",round(1/MathConstants.e,digits=4))\nend", "meta": {"hexsha": "54974d9c972955c0a6a7d4b99001535683a12576", "size": 1137, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/stats/secretaryEnvelopes.jl", "max_stars_repo_name": "mikiec84/SemanticModels.jl", "max_stars_repo_head_hexsha": "f81baf0789cc547375f300429d0fd49c866d5339", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-01-21T15:52:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-21T15:52:41.000Z", "max_issues_repo_path": "examples/stats/secretaryEnvelopes.jl", "max_issues_repo_name": "mikiec84/SemanticModels.jl", "max_issues_repo_head_hexsha": "f81baf0789cc547375f300429d0fd49c866d5339", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/stats/secretaryEnvelopes.jl", "max_forks_repo_name": "mikiec84/SemanticModels.jl", "max_forks_repo_head_hexsha": "f81baf0789cc547375f300429d0fd49c866d5339", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8409090909, "max_line_length": 81, "alphanum_fraction": 0.6341248901, "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.942506716354847, "lm_q2_score": 0.8615382040983515, "lm_q1q2_score": 0.8120055437589891}} {"text": "function four1(data::Array{T,1}, isign::Int64 = 1) where {T<:Number}\n\tnn = length(data)\n\tnnlog = log2(nn)\n\tif ceil(nnlog) != nnlog\n\t\terror(\"Length of data vector must be a power of 2.\")\n\tend\n\tj::Int64 = 1\n\tres::Array{Complex{Float64},1} = copy(data)\n\n\tfor i = 1:nn\n\t\tif j > i\n\t\t\tres[j], res[i] = data[i], data[j]\n\t\tend\n\t\tm = nn/2\n\t\twhile m >= 2 && j > m\n\t\t\tj -= m\n\t\t\tm = m/2\n\t\tend\n\t\tj += m\n\tend\n\n\tmmax = 1;\n\twhile nn > mmax\n\t\tistep = 2*mmax\n\t\ttheta = isign*(pi/mmax)\n\t\twp = -2*sin(theta/2)^2 + sin(theta)*im\n\t\tw = 1 + 0im\n\n\t\tfor m = 1:mmax\n\t\t\tfor i = m:istep:nn\n\t\t\t\tj = i + mmax\n\t\t\t\ttemp = w*res[j]\n\t\t\t\tres[j] = res[i] - temp\n\t\t\t\tres[i] += temp\n\t\t\tend\n\t\t\tw += w*wp\n\t\tend\n\t\tmmax = istep\n\tend\n\n\tres\nend\n\ninput_size = 2048\nFs = 1000\nT = 1/Fs # Sampling period \n\nt = T*(0:(input_size-1))\nX = 0.7*sin.(2*pi*50*t) + sin.(2*pi*120*t)\n\n@time Y = four1(X, 1)\n\n;\n", "meta": {"hexsha": "8904ba3274bd337847198c0456f6167788b44fe6", "size": 869, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "temp/fft/julia_fft.jl", "max_stars_repo_name": "Ashymad/praca.inz", "max_stars_repo_head_hexsha": "dbb1fba10e421c3610bb66a06b7601d2ca4366c6", "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": "temp/fft/julia_fft.jl", "max_issues_repo_name": "Ashymad/praca.inz", "max_issues_repo_head_hexsha": "dbb1fba10e421c3610bb66a06b7601d2ca4366c6", "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": "temp/fft/julia_fft.jl", "max_forks_repo_name": "Ashymad/praca.inz", "max_forks_repo_head_hexsha": "dbb1fba10e421c3610bb66a06b7601d2ca4366c6", "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.0925925926, "max_line_length": 68, "alphanum_fraction": 0.5327963176, "num_tokens": 370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191335436404, "lm_q2_score": 0.849971175657575, "lm_q1q2_score": 0.8119937270662639}} {"text": "my_number = 1.2 # Assignment\n\npi # Pre-defined variable\n\nMy_number # Error - was defined without capital M\n\nδ = 0.001 # Unicode characters allowed (type \\delta and press tab)\n\nmy_number_2 = (my_number + 1) * δ # Use pre-defined variables in expressions\n\ncounter = 1 # counter = 1\n\ncounter += 1 # counter = counter + 1\n\ncounter ^= 4 # counter = counter ^ 4\n\nangle = 60 # degrees\n\nangle *= π / 180 # convert to radians\n\nx = 3\nprintln(2x^2 - 3x + 1)\nprintln(1.5x^2 - .5x + 1)\nprintln(2(x-1)^2 - 3(x-1) + 1)\n\nprintln(360 / 2*π) # Left first - equals 180*π\nprintln(360 / 2π) # Right first - equals 180/π\n\nprintln(2^2x) # 2^(2x), not (4)x\nprintln(2x^2) # 2*(x^2), not (2x)^2\n\n#=\n Experiments with spheres\n=#\n\nradius1 = 100 # Outer sphere radius\nradius2 = 50 # Inner sphere radius \n\n# Compute the volume of each sphere\nvol1 = 4π * radius1^3 / 3\nvol2 = 4π * radius2^3 / 3\n\n# Compute the volume of a hollow sphere\nvol_hollow = vol1 - vol2\n", "meta": {"hexsha": "d302df7ad46c8bf214ae2a7dd9cc3aa00bde2d09", "size": 1093, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "textbook/_build/jupyter_execute/content/Introduction/Variables_And_Assignments.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/Variables_And_Assignments.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/Variables_And_Assignments.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.2888888889, "max_line_length": 83, "alphanum_fraction": 0.56084172, "num_tokens": 354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191309994468, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.8119937230884764}} {"text": "### A Pluto.jl notebook ###\n# v0.14.4\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 892fb737-6fc0-4438-b586-039a440b01f9\nusing LinearAlgebra, SparseArrays\n\n# ╔═╡ 069cf190-77cc-4757-9db3-1945ddd07438\nusing DifferentialEquations, Plots\n\n# ╔═╡ 7bc3e874-b7be-11eb-0792-cf4e21e8c8b2\nmd\"# Heat equation with Proportional control\n\nConsider a one-dimensional rod $\\Omega = (0,L)$ and time $t \\in (0,T).$ \n\"\n\n# ╔═╡ 1158de2e-b7a6-43f3-a4e6-2ef9598a4ca5\nL = 0.1 # Length of rod\n\n# ╔═╡ 30cebec3-9c70-4c6a-94a8-fdcbe6cda783\nTf = 2000.0 # Final simulation time\n\n# ╔═╡ 93fb0f90-c454-410f-aa5e-cd8e6c055dc0\nmd\"The rod has the physical properties\n- thermal conductivity $\\lambda$,\n- specific heat capacity $c$,\n- mass density $\\rho$.\n\nThe diffusivity constant is given by $\\alpha = \\frac{\\lambda}{c \\rho}$. The heat equation is noted as\n\n$\\dot{\\vartheta}(t,x) = \\alpha \\frac{\\partial^2}{\\partial x^2} \\vartheta(t,x)$\n\nfor $(t,x) \\in (0,T) \\times \\Omega$ with initial condition\n\n$\\vartheta(0,x) = \\vartheta_{0}(x)$ \n\nfor $x \\in \\overline{\\Omega}$.\" \n\n# ╔═╡ b294bbfc-45e7-4a15-a839-5ceb56746be7\nbegin\n\tλ = 45.0; # Thermal conductivity\n\tρ = 7800.0; # Mass density\n\tcap = 480.0; # Specific heat capacitivity\nend\n\n# ╔═╡ 543b3f13-4cef-46f1-9141-172b81e7d48b\nα = λ/(cap * ρ) # Diffusivity\n\n# ╔═╡ 1deb117d-21f7-4329-a7db-2be26e43129a\nmd\"## Boundary conditions \n\nOnly on the right side of the rod, heat transfer\n\n$\\phi_{t}(t,x=L) = - h (\\vartheta(t,x=L) - \\vartheta_{amb})$\n\nand heat radiation\n\n$\\phi_{r}(t,x=L) = - \\epsilon \\varrho (\\vartheta(t,x=L)^4 - \\vartheta_{amb}^4)$\n\nis assumed to operate. Parameter $\\vartheta_{amb}$ describes the ambient temperature, $h>0$ is called the heat transfer coefficient, $\\epsilon \\in (0,1)$ is called emissivity and $\\varrho\\approx 5.67 \\cdot 10^{-8}$ is known as Stefan-Boltzmann constant. For simplicity, $k=\\epsilon \\cdot \\varrho$. \n\nThe sum of $\\phi_{t}$ and $\\phi_{r}$ \n\n$\\phi_{out}(t,L) = \\phi_{t}(t,L) + \\phi_{r}(t,L) = - h (\\vartheta(t,L) - \\vartheta_{amb}) - k (\\vartheta(t,L)^4 - \\vartheta_{amb}^4)$\n\nis the flux from the rod to the environment.\"\n\n# ╔═╡ 78292b42-a203-496c-a143-def3ff128f69\nbegin\n\th = 10.0; # Heat transfer coefficient\n\tϵ = 0.6; # Emissivity\n\tsb = 5.67*10^(-8) # Stefan-Boltzmann constant\n\tk = ϵ * sb; \t # Radiation coefficient\nend\n\n# ╔═╡ 0ecea33b-bf24-48eb-b4b4-bbf288e62e6b\nθamb = 298.0 # Ambient temperature in Kelvin\n\n# ╔═╡ 3a059f15-d850-468a-bb1d-f42ef5b24609\nϕout(θ) = -h * (θ - θamb) - k*(θ^4 - θamb^4) \n\n# ╔═╡ 7202aa44-b393-4e0b-9c34-2a9b9376194c\nmd\"### Induced heat\n\nOn the left side of the rod, a heat source is assumed as \n\n$\\phi_{in}(t,x=0) = b ~ u(t)$\n\nwith constant $b>0$, input signal \n\n$u(t) = K_{p} ~ e(t)$\n\nand error\n\n$e(t) = y_{ref}(t) - y(t).$\n\nThe output is considered as the temperature on the right side, e.g.\n\n$y(t) = \\vartheta(t, x=L)$\n\nand the reference is as an arbitrary fixed value \n\n$y_{ref}(t) = y_{ref} > 0.$\n\nThus, the natural (Robin) boundary conditions are noted as \n\n$\\lambda ~ \\left.\\frac{\\partial}{\\partial x} \\vartheta(\\cdot, x) \\right\\rvert_{x = 0} \\cdot \\vec{n} ~=~ \\phi_{in}(t,0) = b ~ u(t)$\n\nand\n\n$\\lambda ~ \\left. \\frac{\\partial}{\\partial x} \\vartheta(\\cdot, x) \\right\\rvert_{x = L} \\cdot \\vec{n} ~=~ \\phi_{out}(t,x) = - h (\\vartheta(t,L) - \\vartheta_{amb}) - k (\\vartheta(t,L)^4 - \\vartheta_{amb}^4)$\n\nwith outer [normal vector](https://en.wikipedia.org/wiki/Normal_(geometry)) $\\vec{n}$ on the left or right boundary. Here, the normal vector $\\vec{n} = -1$ on the left boundary at $x=0$, and $\\vec{n} = 1$ on the right boundary at $x=L$.\"\n\n# ╔═╡ 2775433b-d8b1-48be-9b60-08641db15803\nb = 1;\n\n# ╔═╡ 4c59909b-ffb6-4dfc-94ab-142d41deeeab\nKp = 10^3 # Proportional gain\n\n# ╔═╡ 4f0c3671-d3bf-4e36-a1f3-8e8d0ac0e454\nyref = 400.0 # Reference temperature\n\n# ╔═╡ 23343fa0-6033-498d-b089-d43e4382e332\nu_in(err) = Kp * err # input signals\n\n# ╔═╡ daa17037-fd28-460c-97f5-826742b9a419\nmd\"### Spatial approximation\n\nThe one-dimensional rod is discretized as a one-dimensional grid with N points and the finite discretization is noted by\n\n$\\Delta x = \\frac{L}{N-1}.$\n\nThe resulting grid points have the position $x^{0} = 0$, $x^{n} = n~\\Delta x$ and $x^{N-1} = L$. The second order derivative is approximated using the [Taylor series](https://en.wikipedia.org/wiki/Taylor_series) as \n\n$\\left. \\frac{\\partial^2 f(x)}{\\partial x^2} \\right\\rvert_{x = \\tilde{x}} \\approx \\frac{1}{\\Delta x^2} \\left[ f(\\tilde{x} - \\Delta x) - 2 f(\\tilde{x}) + f(\\tilde{x} + \\Delta x) \\right].$\n\nThis [Finite Difference](https://en.wikipedia.org/wiki/Finite_difference_method) scheme is written in matrix-vector form as \n\n$\\frac{\\partial^2 \\vartheta(t,x)}{\\partial x^2} \\approx \\frac{1}{\\Delta x^2}\n\\begin{pmatrix}\n-2 & 1 & 0 & \\cdots & & 0 \\\\\n1 & -2 & 1 & 0 & \\cdots & \\vdots \\\\\n0 & 1 & -2 & 1 & \\ddots & \\\\\n & & \\ddots & \\ddots & \\ddots & & \\\\\n& & & 1 & -2 & 1 \\\\\n& & & & 1 & -2 \\\\\n\\end{pmatrix}\n~\n\\begin{pmatrix}\n\\vartheta(t, x^{0}) \\\\\n\\vartheta(t, x^{1}) \\\\\n\\vdots \\\\\n\\vartheta(t, x^{N-1}) \\\\\n\\end{pmatrix}.$\n\"\n\n# ╔═╡ 0309bf5e-4033-4832-86ed-146aea0863c0\nN = 101 # Number of grid elements\n\n# ╔═╡ 5c9ec071-6140-4af6-a418-df79c10daf5e\nΔx = L/(N-1) # Finite discretization \n\n# ╔═╡ 905337c5-9eee-4b67-b215-bfd7ca905e4c\n# Diffusion matrix\nM = spdiagm(-1 => ones(N-1), 0 => -2*ones(N), 1 => ones(N-1));\n\n# ╔═╡ f0e9f197-303b-48a6-a540-9b11513050d4\nMatrix(M)[1:5,1:5]\n\n# ╔═╡ 0e155080-2cfe-45c0-8166-ba91f95d6f8b\nmd\"### Approximated boundary conditions\n\nThe spatial approximation of the heat equation \n\n$\\frac{\\partial^2 \\vartheta(t,x)}{\\partial x^2} \\approx \\frac{1}{\\Delta x^2} \\left( \\vartheta(\\cdot, x^{n-1}) - 2 ~ \\vartheta(\\cdot, x^{n}) + \\vartheta(\\cdot, x^{n+1}) \\right)$\n\ncan not be evaluated directly at the grid points $x^{0}$ and $x^{N-1}$ because they depend on values from the not-existing grid points $x^{-1}$ and $x^{N}$. Therefore, the Neumann boundary condition is used to find $\\vartheta(\\cdot, x^{-1})$ and $\\vartheta(\\cdot, x^{N})$.\n\nThe Robin boundary condition states that the heat flux at both sides is described by\n\n$\\lambda \\left. \\frac{\\partial \\vartheta(\\cdot,x)}{\\partial x} \\right\\rvert_{x = 0} \\cdot \\vec{n} = -1 \\cdot \\lambda \\frac{\\vartheta(\\cdot, x^{1}) - \\vartheta(\\cdot, x^{-1})}{2 \\Delta x} = \\phi_{in}(t,x^{0})$\n\non the left boundary and \n\n$\\lambda \\left. \\frac{\\partial \\vartheta(\\cdot,x)}{\\partial x} \\right\\rvert_{x = L} \\cdot \\vec{n} = \\lambda \\frac{\\vartheta(\\cdot, x^{N}) - \\vartheta(\\cdot, x^{N-2})}{2 \\Delta x} = \\phi_{out}(t,x^{N-1})$\n\non the right boundary. Reformulating both equations lead to \n\n$\\vartheta(\\cdot, x^{-1}) = \\vartheta(\\cdot, x^{1}) + \\frac{2 \\Delta x}{\\lambda} ~ \\phi_{in}(t,x^{0})$\n\nand\n\n$\\vartheta(\\cdot, x^{N}) = \\vartheta(\\cdot, x^{N-2}) + \\frac{2 \\Delta x}{\\lambda} ~ \\phi_{out}(t,x^{N-1}).$\n\nOn the left boundary one yields \n\n$\\left. \\frac{\\partial^2 \\vartheta(t,x)}{\\partial x^2} \\right\\rvert_{x = 0} \\approx \\frac{1}{\\Delta x^2} \\left( - 2 ~ \\vartheta(\\cdot, x^{0}) + 2 ~ \\vartheta(\\cdot, x^{1}) \\right) + \\frac{2}{\\lambda ~ \\Delta x} \\phi_{in}(t,x^{0})$\n\nand analog on the right boundary\n\n$\\left. \\frac{\\partial^2 \\vartheta(t,x)}{\\partial x^2} \\right\\rvert_{x = 0} \\approx \\frac{1}{\\Delta x^2} \\left(2 ~ \\vartheta(\\cdot, x^{N-2}) - 2 ~ \\vartheta(\\cdot, x^{N-1}) \\right) + \\frac{2}{\\lambda ~ \\Delta x} \\phi_{out}(t,x^{N-1}).$\n\nThe induced and emitted flux are noted as \n\n$\\Phi_{in}(t) = \n\\begin{pmatrix}\nb \\\\\n0 \\\\\n\\vdots \\\\\n0 \\\\\n\\end{pmatrix}\n~ u(t)\n\n\\quad \\text{and} \\quad\n\n\\Phi_{out}(t) = \n\\begin{pmatrix}\n0 \\\\\n\\vdots \\\\\n0 \\\\\n1 \\\\\n\\end{pmatrix}\n~\\phi_{out}(t, x^{N-1})$\n\nand the diffusion matrix is described by\n\n$M = \n\\begin{pmatrix}\n-2 & 2 & 0 & \\cdots & & 0 \\\\\n1 & -2 & 1 & 0 & \\cdots & \\vdots \\\\\n0 & 1 & -2 & 1 & \\ddots & \\\\\n & & \\ddots & \\ddots & \\ddots & & \\\\\n& & & 1 & -2 & 1 \\\\\n& & & & 2 & -2 \\\\\n\\end{pmatrix}.$\n\"\n\n\n# ╔═╡ c61962e8-86bd-45ed-a62d-ffc812d8e35e\n# First row\nM[1,2] = 2;\n\n# ╔═╡ 33baab03-fbc1-4944-bc16-e4022b051c69\n# Last row\nM[end,end-1] = 2;\n\n# ╔═╡ facdbabf-6e2b-418a-a07e-36188244e585\nmd\"### Heat equation in State-space representation\n\nAfter the spatial approximation the heat equation has a form of \n\n$\\dot{\\theta}(t) = \\frac{\\alpha}{\\Delta x^2} ~ M ~ \\theta(t) + \\frac{2 \\alpha}{\\Delta x} ~ \\Phi_{in}(t) + \\frac{2 \\alpha}{\\Delta x} ~ \\Phi_{out}(t) \\tag{1}$\n\nwith M as diffusion matrix, temperature vector $\\quad \\theta(t) = \\left( \\vartheta(t, x^{0}), \\cdots, \\vartheta(t, x^{N-1}) \\right)^{\\top}$. \n\nThe original ODE $(1)$ is recasted in [state-space representation](https://en.wikipedia.org/wiki/State-space_representation) as\n\n$\\dot{\\theta}(t) = A ~ \\theta(t) + B ~ u(t) + E ~ w(t)$\n$y(t) = C \\theta(t)$\n\nwith \n- system matrix $A = \\frac{\\alpha}{\\Delta x^2} ~ M$, \n- input vector \n$B = \\frac{2 ~ \\alpha}{\\lambda ~ \\Delta x} \n\\begin{pmatrix}\nb \\\\\n0 \\\\\n\\vdots \\\\\n0\n\\end{pmatrix},$\n\n- disturbance vector \n$E = \\frac{2 ~ \\alpha}{\\lambda ~ \\Delta x} \n\\begin{pmatrix}\n0 \\\\\n\\vdots \\\\\n0 \\\\\n1\n\\end{pmatrix},$\n\n- emitted flux $w(t) = \\phi_{out}(t,x^{N-1})$ and\n- output vector $C = (0, \\cdots, 0, 1)$\n\nto describe the input-state-output behaviour including the integral controller. The emitted heat is considered as a disturbance. The PI controller is introduced as \n\n$u(t) = K_{p} ~ e(t)$ \n\nwith error \n$e(t) = y_{ref}(t) - y(t) = y_{ref}(t) - C ~ \\theta(t)$\n\n\nThe thermal dynamics with PI control is described by\n\n$\\dot{\\theta}(t) = A ~ \\theta(t) + B ~ K_{p} ~ e(t) + E ~ w(t).$\n\nThis is an ordinary differential equation (ODE) that can be solved with common solvers like forward Euler method or Runge-Kutta scheme.\n\n\"\n\n# ╔═╡ 5ef85c8f-cb69-42df-a098-ab98903a5f32\nA = α/(Δx^2) * M\n\n# ╔═╡ 25bb45ab-55af-4b8b-a11b-05be68631b78\nbegin\n\tB = spzeros(N); # Input vector\n\tB[1] = 2 * (α/(λ*Δx)) * b\n\tE = spzeros(N); # Disturbance vector\n\tE[end] = 2 * (α/(λ*Δx)) * b\n\tC = spzeros(1,N); # Output vector\n\tC[end] = 1;\nend\n\n# ╔═╡ 81a2d204-7386-4ed7-af89-7c076940817b\nw(θ) = ϕout(θ)\n\n# ╔═╡ 113d8c87-f4e6-4f1b-b188-879e7ad1e146\nfunction heat_eq!(dx,x,p,t)\n global u_hist\n \n err = yref - x[end]\n u = u_in(err)\n \n\n dx .= A * x + B * u + E * ϕout( x[end] ) # Integration of temperatures\n \n end\n\n# ╔═╡ d9138271-79fc-4b7c-8501-e8d8f3304cd5\nmd\"### Initial Conditions\n\nFor simplicity, the initial data of the heat equation is assumed as $\\vartheta_{0}(x)= 1000$ Kelvin for all $x \\in \\left[0,L\\right]$. This function is approximated to gain the initial conditions of the ODE \n\n$\\theta(0) = \\left( 300, \\cdots , 300 \\right)^{\\top}.$\n\"\n\n# ╔═╡ db6248c7-24b8-4f44-82d3-4892203297b5\nθ₀ = 300.0 * ones(N)\n\n# ╔═╡ 837632eb-b4db-47ec-8e4a-32a0fe81060b\nmd\"## Simulation\"\n\n# ╔═╡ 3f382fe5-2aa6-4d82-b939-977985ae8bbb\nΔt = 10^(-2) # Sampling time\n\n# ╔═╡ 02ba374a-15b4-4481-baf6-c1a3ce45ed5e\ntspan = (0.0, Tf)\n\n# ╔═╡ 0db82493-4dda-4992-aa5b-63734b556a90\nprob = ODEProblem( heat_eq!, θ₀, tspan ) # ODE Problem\n\n# ╔═╡ f7dcb8a6-0eb4-4762-942e-53362d4fe1ba\nsol = solve(prob,Euler(),dt=Δt,progress=true, saveat=1.0, save_start=true); # Solving the ODE\n\n# ╔═╡ 9c38b2b3-1622-41f3-a2c2-ff79b552e454\n# 1-dimensional grid\nxspan = 0 : Δx : L\n\n# ╔═╡ ba66c778-6c1c-4e32-934d-e8aca0eb1c66\nheatmap(sol.t, xspan, sol[1:end,1:end], xaxis=\"Time [s]\", yaxis=\"Position [m]\", title=\"Evolution of temperature\")\n\n# ╔═╡ 3dcfed19-8235-4309-b1c7-8d4e30ba6701\nplot(sol.t,[sol[1,:], sol[end-1,:]], label=[\"Left\" \"Right\"], title=\"Temperature at the left/right end\", legend=:bottomright)\n\n# ╔═╡ Cell order:\n# ╟─7bc3e874-b7be-11eb-0792-cf4e21e8c8b2\n# ╠═1158de2e-b7a6-43f3-a4e6-2ef9598a4ca5\n# ╠═30cebec3-9c70-4c6a-94a8-fdcbe6cda783\n# ╟─93fb0f90-c454-410f-aa5e-cd8e6c055dc0\n# ╠═b294bbfc-45e7-4a15-a839-5ceb56746be7\n# ╠═543b3f13-4cef-46f1-9141-172b81e7d48b\n# ╟─1deb117d-21f7-4329-a7db-2be26e43129a\n# ╠═78292b42-a203-496c-a143-def3ff128f69\n# ╠═0ecea33b-bf24-48eb-b4b4-bbf288e62e6b\n# ╠═3a059f15-d850-468a-bb1d-f42ef5b24609\n# ╟─7202aa44-b393-4e0b-9c34-2a9b9376194c\n# ╠═2775433b-d8b1-48be-9b60-08641db15803\n# ╠═4c59909b-ffb6-4dfc-94ab-142d41deeeab\n# ╠═4f0c3671-d3bf-4e36-a1f3-8e8d0ac0e454\n# ╠═23343fa0-6033-498d-b089-d43e4382e332\n# ╟─daa17037-fd28-460c-97f5-826742b9a419\n# ╠═892fb737-6fc0-4438-b586-039a440b01f9\n# ╠═0309bf5e-4033-4832-86ed-146aea0863c0\n# ╠═5c9ec071-6140-4af6-a418-df79c10daf5e\n# ╠═905337c5-9eee-4b67-b215-bfd7ca905e4c\n# ╠═f0e9f197-303b-48a6-a540-9b11513050d4\n# ╟─0e155080-2cfe-45c0-8166-ba91f95d6f8b\n# ╠═c61962e8-86bd-45ed-a62d-ffc812d8e35e\n# ╠═33baab03-fbc1-4944-bc16-e4022b051c69\n# ╟─facdbabf-6e2b-418a-a07e-36188244e585\n# ╠═5ef85c8f-cb69-42df-a098-ab98903a5f32\n# ╠═25bb45ab-55af-4b8b-a11b-05be68631b78\n# ╠═81a2d204-7386-4ed7-af89-7c076940817b\n# ╠═113d8c87-f4e6-4f1b-b188-879e7ad1e146\n# ╟─d9138271-79fc-4b7c-8501-e8d8f3304cd5\n# ╠═db6248c7-24b8-4f44-82d3-4892203297b5\n# ╠═837632eb-b4db-47ec-8e4a-32a0fe81060b\n# ╠═069cf190-77cc-4757-9db3-1945ddd07438\n# ╠═3f382fe5-2aa6-4d82-b939-977985ae8bbb\n# ╠═02ba374a-15b4-4481-baf6-c1a3ce45ed5e\n# ╠═0db82493-4dda-4992-aa5b-63734b556a90\n# ╠═f7dcb8a6-0eb4-4762-942e-53362d4fe1ba\n# ╠═9c38b2b3-1622-41f3-a2c2-ff79b552e454\n# ╠═ba66c778-6c1c-4e32-934d-e8aca0eb1c66\n# ╠═3dcfed19-8235-4309-b1c7-8d4e30ba6701\n", "meta": {"hexsha": "bd0590b17496d44f5e28d1ee1d84dfa6f3d551e1", "size": 12973, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/control/prop_control.jl", "max_stars_repo_name": "stephans3/IntroHeatEquation.jl", "max_stars_repo_head_hexsha": "37e9c9ededeb7cdfc2ffb0c11ac1661d157a0288", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/control/prop_control.jl", "max_issues_repo_name": "stephans3/IntroHeatEquation.jl", "max_issues_repo_head_hexsha": "37e9c9ededeb7cdfc2ffb0c11ac1661d157a0288", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/control/prop_control.jl", "max_forks_repo_name": "stephans3/IntroHeatEquation.jl", "max_forks_repo_head_hexsha": "37e9c9ededeb7cdfc2ffb0c11ac1661d157a0288", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7965686275, "max_line_length": 298, "alphanum_fraction": 0.6571340476, "num_tokens": 5763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802395624257, "lm_q2_score": 0.8840392771633079, "lm_q1q2_score": 0.8119726070715487}} {"text": "using Random, Distributions, KernelDensity, Plots; pyplot()\nRandom.seed!(0)\n\nmu1, sigma1 = 10, 5\nmu2, sigma2 = 40, 12\ndist1, dist2 = Normal(mu1,sigma1), Normal(mu2,sigma2)\np = 0.3\nmixRv() = (rand() <= p) ? rand(dist1) : rand(dist2)\nmixPDF(x) = p*pdf(dist1,x) + (1-p)*pdf(dist2,x)\n\nn = 2000\ndata = [mixRv() for _ in 1:n]\n\nkdeDist = kde(data)\n\nxGrid = -20:0.1:80\npdfKDE = pdf(kdeDist,xGrid)\n\nplot(xGrid, pdfKDE, c=:blue, label=\"KDE PDF\")\nstephist!(data, bins=50, c=:black, normed=:true, label=\"Histogram\")\np1 = plot!(xGrid, mixPDF.(xGrid), c=:red, label=\"Underlying PDF\",\n xlims=(-20,80), ylims=(0,0.035), legend=:topleft,\n xlabel=\"X\", ylabel = \"Density\")\n\nhVals = [0.5,2,10]\nkdeS = [kde(data,bandwidth=h) for h in hVals]\nplot(xGrid, pdf(kdeS[1],xGrid), c = :green, label= \"h=$(hVals[1])\")\nplot!(xGrid, pdf(kdeS[2],xGrid), c = :blue, label= \"h=$(hVals[2])\")\np2 = plot!(xGrid, pdf(kdeS[3],xGrid), c = :purple, label= \"h=$(hVals[3])\",\n xlims=(-20,80), ylims=(0,0.035), legend=:topleft, \n xlabel=\"X\", ylabel = \"Density\")\nplot(p1,p2,size = (800,400))", "meta": {"hexsha": "e074b6e2b5f906ca411deaedd0086f34cf6e0c53", "size": 1056, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "4_chapter/KDE.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/KDE.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/KDE.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 33.0, "max_line_length": 74, "alphanum_fraction": 0.625, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966717067253, "lm_q2_score": 0.8577681068080749, "lm_q1q2_score": 0.8119604350007026}} {"text": "function sigmoid(z)\n 1 ./ (1 .+ e .^ (-z))\nend\n\nfunction sigmoid_grad(z)\n sigmoid(z) .* (1 - sigmoid(z))\nend\n\nfunction init_theta(num_input, num_output, nums_hidden)\n num_units = [num_input, nums_hidden..., num_output]\n layers = length(num_units)\n Theta = [rand(num_units[i], num_units[i-1]+1) - 0.5 for i = 2:layers]\nend\n\nfunction cost(Y, Y_pred)\n len = size(Y, 1)\n J = (-1.0 / len ) * sum((Y .* log(Y_pred)) + ((1-Y) .* log(1-Y_pred)))\nend\n\nfunction forward_prop(X, Theta)\n A = {}\n H = {}\n push!(H, X)\n push!(A, zeros(1, 1))\n\n for t=1:length(Theta)\n # add bias\n H[t] = [ones(size(H[t], 1), 1) H[t]]\n # pre-activation\n push!(A, H[t] * Theta[t]')\n # activation\n push!(H, sigmoid(A[t+1]))\n end\n A, H, H[end]\nend\n\nfunction back_prop(X, Y, Theta)\n len = size(X, 1)\n T = length(Theta)\n\n Theta_grad = {}\n for i=1:T\n push!(Theta_grad, zeros(size(Theta[i])))\n end\n\n A, H, Y_pred = forward_prop(X, Theta)\n\n delta_N = {}\n \n for t=1:T\n push!(delta_N, {})\n end\n\n delta = Y_pred - Y\n\n delta_N[T] = delta\n\n for t=0:T-2\n delta = (delta*Theta[T-t][:, 2:end]) .* sigmoid_grad(A[T-t])\n delta_N[T-t-1] = delta\n end\n\n for t=1:T\n Theta_grad[t] = Theta_grad[t] + delta_N[t]' * H[t]\n end\n \n Y_pred, Theta_grad\nend\n\nfunction fit(X, Y, Theta, learning_rate, epochs)\n J_list = zeros(epochs)\n for i=1:epochs\n Y_pred, Theta_grad = back_prop(X, Y, Theta)\n J_list[i] = cost(Y_train, Y_pred)\n for t=1:length(Theta)\n Theta[t] = Theta[t] - learning_rate*Theta_grad[t]\n end\n end\n Theta, J_list\nend\n\nfunction predict(X, Theta)\n _, _, y = forward_prop(X, Theta)\n y \nend\n", "meta": {"hexsha": "a6827e46bee07d0ce6931a8dc41876e2ac37e8ca", "size": 1622, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Neu.jl", "max_stars_repo_name": "rinuboney/Neu.jl", "max_stars_repo_head_hexsha": "5382ac83b650cf418a69536455dfb16af92aabfa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-05-29T13:21:59.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-27T10:07:35.000Z", "max_issues_repo_path": "src/Neu.jl", "max_issues_repo_name": "rinuboney/Neu.jl", "max_issues_repo_head_hexsha": "5382ac83b650cf418a69536455dfb16af92aabfa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Neu.jl", "max_forks_repo_name": "rinuboney/Neu.jl", "max_forks_repo_head_hexsha": "5382ac83b650cf418a69536455dfb16af92aabfa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-09-04T01:30:15.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-04T01:30:15.000Z", "avg_line_length": 18.8604651163, "max_line_length": 71, "alphanum_fraction": 0.5918618989, "num_tokens": 571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620550745211, "lm_q2_score": 0.8459424295406088, "lm_q1q2_score": 0.8119034446506279}} {"text": "\r\ninclude(\"../../util/src/util_module.jl\")\r\n\r\n\r\nmodule dev\r\n\r\n\r\n\r\nmodule matrix_vector_prod\r\nusing LinearAlgebra\r\n\r\nfunction matrix_vector_prod_default(A::Matrix{T}, x::Vector{T}) where {T<:Float64}\r\n sz_a = size(A)\r\n sz_b = size(x)\r\n \r\n if length(sz_a) != 2\r\n error(\"A is not a matrix\")\r\n end\r\n if length(sz_b) != 1\r\n error(\"B is not a vector\")\r\n end\r\n if sz_a[2] != sz_b[1]\r\n error(\"A and B are not compatible (size mismatch) \")\r\n end\r\n c = A * x\r\n return c\r\nend\r\n\r\n\r\nfunction matrix_vector_prod_inner(A, x)\r\n # A in R^m-by-p\r\n # x in R^p-by-1\r\n # c = A * x in R^m-by-1\r\n sz_a = size(A)\r\n sz_b = size(x)\r\n \r\n if length(sz_a) != 2\r\n error(\"A is not a matrix\")\r\n end\r\n if length(sz_b) != 1\r\n error(\"B is not a vector\")\r\n end\r\n if sz_a[2] != sz_b[1]\r\n error(\"A and B are not compatible (size mismatch) \")\r\n end\r\n\r\n c = zeros(eltype(A), sz_a[1])\r\n @inbounds @simd for ii = 1:sz_a[1]\r\n # c[ii] = A[ii, :]' * x\r\n c[ii] = dot( @view(A[ii, :]), x)\r\n end\r\n return c\r\nend\r\n\r\nfunction matrix_vector_prod_inner_loop(A, x)\r\n # A in R^m-by-p\r\n # x in R^p-by-1\r\n # c = A * x in R^m-by-1\r\n sz_a = size(A)\r\n sz_b = size(x)\r\n \r\n if length(sz_a) != 2\r\n error(\"A is not a matrix\")\r\n end\r\n if length(sz_b) != 1\r\n error(\"B is not a vector\")\r\n end\r\n if sz_a[2] != sz_b[1]\r\n error(\"A and B are not compatible (size mismatch) \")\r\n end\r\n\r\n c = zeros(eltype(A), sz_a[1])\r\n @inbounds @simd for ii = 1:sz_a[1]\r\n inner_sum = zero(eltype(x))\r\n @inbounds @simd for jj = 1:sz_a[2]\r\n inner_sum += A[ii, jj] * x[jj] \r\n end\r\n c[ii] = inner_sum\r\n end\r\n return c\r\nend\r\n\r\nfunction matrix_vector_prod_outer(A, x)\r\n # A in R^m-by-p\r\n # x in R^p-by-1\r\n # c = A * x in R^m-by-1\r\n sz_a = size(A)\r\n sz_b = size(x)\r\n \r\n if length(sz_a) != 2\r\n error(\"A is not a matrix\")\r\n end\r\n if length(sz_b) != 1\r\n error(\"B is not a vector\")\r\n end\r\n if sz_a[2] != sz_b[1]\r\n error(\"A and B are not compatible (size mismatch) \")\r\n end\r\n\r\n c = zeros(eltype(A), sz_a[1])\r\n @inbounds @simd for jj = 1:sz_a[2]\r\n c .+= @view( A[:, jj] ) .* x[jj]\r\n end\r\n return c\r\nend\r\n\r\nfunction matrix_vector_prod_outer_loop(A, x)\r\n # A in R^m-by-p\r\n # x in R^p-by-1\r\n # c = A * x in R^m-by-1\r\n sz_a = size(A)\r\n sz_b = size(x)\r\n \r\n if length(sz_a) != 2\r\n error(\"A is not a matrix\")\r\n end\r\n if length(sz_b) != 1\r\n error(\"B is not a vector\")\r\n end\r\n if sz_a[2] != sz_b[1]\r\n error(\"A and B are not compatible (size mismatch) \")\r\n end\r\n\r\n c = zeros(eltype(A), sz_a[1])\r\n @inbounds @simd for jj = 1:sz_a[2]\r\n @inbounds @simd for ii = 1:sz_a[1]\r\n c[ii] += A[ii, jj] * x[jj]\r\n end\r\n end\r\n return c\r\nend\r\n\r\n\r\n\r\nfunction matrix_mult_inner(A, B)\r\n # A in R^m-by-p\r\n # B in R^p-by-n\r\n # C = A * B in R^m-by-n\r\n # [ma, p] = size(A)\r\n # [, p] = size(A)\r\n sz_a = size(A)\r\n sz_b = size(B)\r\n \r\n if length(sz_a) != 2\r\n error(\"A is not a matrix\")\r\n end\r\n if length(sz_b) != 2\r\n error(\"B is not a matrix\")\r\n end\r\n if sz_a[2] != sz_b[1]\r\n error(\"A and B are not compatible (size mismatch) \")\r\n end\r\n \r\n C = zeros(eltype(A), sz_a[1], sz_b[2])\r\n for ii = 1:sz_a[1]\r\n for jj = 1:sz_b[2]\r\n C[ii, jj] = dot( A[ii, :], B[:, jj] )\r\n # C[ii, jj] = A[ii, :]' * B[:, jj]\r\n end\r\n end\r\n return C\r\nend\r\n\r\nfunction matrix_mult_outer(A, B)\r\n # A in R^m-by-p\r\n # B in R^p-by-n\r\n # C = A * B in R^m-by-n\r\n # [ma, p] = size(A)\r\n # [, p] = size(A)\r\n sz_a = size(A)\r\n sz_b = size(B)\r\n \r\n if length(sz_a) != 2\r\n error(\"A is not a matrix\")\r\n end\r\n if length(sz_b) != 2\r\n error(\"B is not a matrix\")\r\n end\r\n if sz_a[2] != sz_b[1]\r\n error(\"A and B are not compatible (size mismatch) \")\r\n end\r\n \r\n C = zeros(eltype(A), sz_a[1], sz_b[2])\r\n for kk = 1:sz_a[2]\r\n C += A[:, kk] * B[kk, :]'\r\n end\r\n return C\r\nend\r\n\r\nfunction matrix_mult_default(A, B)\r\n # A in R^m-by-p\r\n # B in R^p-by-n\r\n # C = A * B in R^m-by-n\r\n # [ma, p] = size(A)\r\n # [, p] = size(A)\r\n sz_a = size(A)\r\n sz_b = size(B)\r\n \r\n if length(sz_a) != 2\r\n error(\"A is not a matrix\")\r\n end\r\n if length(sz_b) != 2\r\n error(\"B is not a matrix\")\r\n end\r\n if sz_a[2] != sz_b[1]\r\n error(\"A and B are not compatible (size mismatch) \")\r\n end\r\n C = A * B\r\n return C\r\nend\r\n\r\nfunction matrix_mult_inner_loop(A, B)\r\n # A in R^m-by-p\r\n # B in R^p-by-n\r\n # C = A * B in R^m-by-n\r\n # [ma, p] = size(A)\r\n # [, p] = size(A)\r\n sz_a = size(A)\r\n sz_b = size(B)\r\n \r\n if length(sz_a) != 2\r\n error(\"A is not a matrix\")\r\n end\r\n if length(sz_b) != 2\r\n error(\"B is not a matrix\")\r\n end\r\n if sz_a[2] != sz_b[1]\r\n error(\"A and B are not compatible (size mismatch) \")\r\n end\r\n C = zeros(eltype(A), sz_a[1], sz_b[2])\r\n\r\n for ii = 1:sz_a[1]\r\n for jj = 1:sz_b[2]\r\n inner_sum = zero(eltype(A))\r\n for kk = 1:sz_a[2]\r\n inner_sum += A[ii, kk] * B[kk, jj]\r\n end\r\n C[ii, jj] = inner_sum\r\n end\r\n end\r\n return C\r\nend\r\n\r\nfunction matrix_mult_outer_loop(A, B)\r\n #\r\n # Algo probably wrong\r\n #\r\n # A in R^m-by-p\r\n # B in R^p-by-n\r\n # C = A * B in R^m-by-n\r\n # [ma, p] = size(A)\r\n # [, p] = size(A)\r\n sz_a = size(A)\r\n sz_b = size(B)\r\n \r\n if length(sz_a) != 2\r\n error(\"A is not a matrix\")\r\n end\r\n if length(sz_b) != 2\r\n error(\"B is not a matrix\")\r\n end\r\n if sz_a[2] != sz_b[1]\r\n error(\"A and B are not compatible (size mismatch) \")\r\n end\r\n C = zeros(eltype(A), sz_a[1], sz_b[2])\r\n\r\n #=\r\n for kk = 1:sz_a[2]\r\n for ii = 1:sz_a[1]\r\n C[ii, kk] += A[ii, kk] * B[kk, ii]\r\n end\r\n end\r\n =#\r\n for ii = 1:sz_b[2]\r\n for kk = 1:sz_a[2]\r\n C[:, ii] += A[:, kk] * B[kk, ii]\r\n end\r\n end\r\n\r\n return C\r\nend\r\n\r\n\r\nend # dev\r\n\r\n\r\nmodule devtest\r\nusing ..dev\r\nusing BenchmarkTools\r\n\r\nfunction benchmark_matrix_vector_prod_default(A, x)\r\n b = @benchmark dev.matrix_vector_prod_default($A, $x)\r\n\r\n println(\"=== matrix_vector_prod_default ===\")\r\n show(\r\n stdout,\r\n MIME(\"text/plain\"),\r\n b )\r\n println(\"\\n\\n\")\r\nend\r\n\r\n\r\nfunction benchmark_matrix_vector_prod_inner(A, x)\r\n b = @benchmark dev.matrix_vector_prod_inner($A, $x)\r\n\r\n println(\"=== matrix_vector_prod_inner ===\")\r\n show(\r\n stdout,\r\n MIME(\"text/plain\"),\r\n b )\r\n println(\"\\n\\n\")\r\nend\r\n\r\nfunction benchmark_matrix_vector_prod_outer(A, x)\r\n b = @benchmark dev.matrix_vector_prod_outer($A, $x)\r\n\r\n println(\"=== matrix_vector_prod_outer ===\")\r\n show(\r\n stdout,\r\n MIME(\"text/plain\"),\r\n b )\r\n println(\"\\n\\n\")\r\nend\r\n\r\nfunction benchmark_matrix_vector_prod_inner_loop(A, x)\r\n b = @benchmark dev.matrix_vector_prod_inner_loop($A, $x)\r\n\r\n println(\"=== matrix_vector_prod_inner_loop ===\")\r\n show(\r\n stdout,\r\n MIME(\"text/plain\"),\r\n b )\r\n println(\"\\n\\n\")\r\nend\r\n\r\nfunction benchmark_matrix_vector_prod_outer_loop(A, x)\r\n b = @benchmark dev.matrix_vector_prod_outer_loop($A, $x)\r\n\r\n println(\"=== matrix_vector_prod_outer_loop ===\")\r\n show(\r\n stdout,\r\n MIME(\"text/plain\"),\r\n b )\r\n println(\"\\n\\n\")\r\nend\r\n\r\n\r\nfunction benchmark_all()\r\n\r\n # size definitions\r\n # m = 1000\r\n # p = 5000\r\n\r\n # m = 10\r\n # p = 500000\r\n\r\n m = 100000\r\n p = 50\r\n\r\n # allocate the matrices\r\n A = rand(m, p)\r\n x = rand(p)\r\n\r\n benchmark_matrix_vector_prod_default(A, x)\r\n benchmark_matrix_vector_prod_inner(A, x)\r\n benchmark_matrix_vector_prod_outer(A, x)\r\n benchmark_matrix_vector_prod_inner_loop(A, x)\r\n benchmark_matrix_vector_prod_outer_loop(A, x)\r\n\r\nend\r\n\r\n\r\n\r\nend\r\n\r\nmodule devtest_matrix\r\n using ..dev\r\n using BenchmarkTools\r\n\r\n\r\n\r\nfunction benchmark_matrix_mult_inner(A, B)\r\n b = @benchmark dev.matrix_mult_inner($A, $B)\r\n\r\n println(\"=== matrix_mult_inner ===\")\r\n show(\r\n stdout,\r\n MIME(\"text/plain\"),\r\n b )\r\n println(\"\\n\\n\")\r\n end\r\n\r\nfunction benchmark_matrix_mult_outer(A, B)\r\n b = @benchmark dev.matrix_mult_outer($A, $B)\r\n\r\n println(\"=== matrix_mult_outer ===\")\r\n show(\r\n stdout,\r\n MIME(\"text/plain\"),\r\n b )\r\n println(\"\\n\\n\")\r\nend\r\n\r\nfunction benchmark_matrix_mult_default(A, B)\r\n b = @benchmark dev.matrix_mult_default($A, $B)\r\n\r\n println(\"=== matrix_mult_default ===\")\r\n show(\r\n stdout,\r\n MIME(\"text/plain\"),\r\n b )\r\n println(\"\\n\\n\")\r\nend\r\n\r\nfunction benchmark_matrix_mult_inner_loop(A, B)\r\n b = @benchmark dev.matrix_mult_inner_loop($A, $B)\r\n\r\n println(\"=== matrix_mult_inner_loop ===\")\r\n show(\r\n stdout,\r\n MIME(\"text/plain\"),\r\n b )\r\n println(\"\\n\\n\")\r\nend\r\n\r\nfunction benchmark_matrix_mult_outer_loop(A, B)\r\n b = @benchmark dev.matrix_mult_outer_loop($A, $B)\r\n\r\n println(\"=== matrix_mult_outer_loop ===\")\r\n show(\r\n stdout,\r\n MIME(\"text/plain\"),\r\n b )\r\n println(\"\\n\\n\")\r\nend\r\n\r\n\r\n\r\n\r\n\r\nfunction benchmark_all()\r\n # size definitions\r\n m = 100\r\n p = 500\r\n n = 100\r\n\r\n # allocate the matrices\r\n A = rand(m, p)\r\n B = rand(p, n)\r\n\r\n\r\n benchmark_matrix_mult_inner(A, B)\r\n benchmark_matrix_mult_outer(A, B)\r\n benchmark_matrix_mult_default(A, B)\r\n benchmark_matrix_mult_inner_loop(A, B)\r\n # benchmark_matrix_mult_outer_loop(A, B)\r\nend\r\n\r\n\r\n \r\n \r\n # multiply\r\n #= \r\n Ci = dev.matrix_mult_inner(A, B)\r\n Co = dev.matrix_mult_outer(A, B)\r\n Cd = A * B;\r\n\r\n println( all( abs.( Ci .- Co ) .<= 1e-10 ) ) =#\r\n\r\nend\r\n\r\n#= \r\nmodule plottest\r\n \r\nusing PyPlot\r\nPyPlot.pygui(true)\r\n\r\nx = LinRange(-2, 2, 30) # [1, 2, 3]\r\ny = LinRange(-4, 1, 30) # [10, 20, 30]\r\nz = [i.^2 + j.^2 for i in x, j in y]\r\nz2 = [50, 51, 52]\r\n\r\nPyPlot.figure()\r\n# PyPlot.plot3D(x, y, z2)\r\nPyPlot.plot_surface(x, y, z, alpha = 0.5)\r\n\r\n\r\nend =#\r\n\r\n\r\n", "meta": {"hexsha": "98fa81549ec9bc275009f4cd949d836feeb2b8d8", "size": 10426, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "__lib__/math/linalg/test/matrix_vector_product_tryouts.jl", "max_stars_repo_name": "HomoModelicus/julia", "max_stars_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "__lib__/math/linalg/test/matrix_vector_product_tryouts.jl", "max_issues_repo_name": "HomoModelicus/julia", "max_issues_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "__lib__/math/linalg/test/matrix_vector_product_tryouts.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.2342158859, "max_line_length": 83, "alphanum_fraction": 0.5038365624, "num_tokens": 3178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951552333004, "lm_q2_score": 0.8688267830311354, "lm_q1q2_score": 0.8118275368012268}} {"text": "using Distributions, Plots; pyplot()\n\ntriangDist = TriangularDist(0,2,1)\nxGrid = 0:0.1:2\nN = 10^6\ninverseSampledData = quantile.(triangDist,rand(N))\n\nhistogram( inverseSampledData, bins=30, normed=true,\n\tylims=(0,1.1), label=\"Inverse transform data\")\nplot!( xGrid, pdf.(triangDist,xGrid), c=:red, lw=4, \n\txlabel=\"x\", label=\"PDF\", ylabel = \"Density\", legend=:topright)", "meta": {"hexsha": "0aa22e56473e9271f326ad0f4f633bc401184962", "size": 367, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "3_chapter/triangularDistInv.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "3_chapter/triangularDistInv.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "3_chapter/triangularDistInv.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 33.3636363636, "max_line_length": 63, "alphanum_fraction": 0.7138964578, "num_tokens": 130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533107374443, "lm_q2_score": 0.870597270087091, "lm_q1q2_score": 0.811791306811689}} {"text": "## compose_matrix.jl : methods to compose example matrices\n\n\"\"\"\nanisotropic2d(ϵ, n, m)\n\n2d anisotropic Laplacian on [0,1]^2 using n x m points and anisotropy number ϵ\n\"\"\"\nanisotropic2d(ϵ, n, m) = stencil2mat(SArray{Tuple{3,3}}([0 -m^2 0 -ϵ*n^2 2(ϵ*n^2+m^2) -ϵ*n^2 0 -m^2 0]), n, m)\n\n\"\"\"\nanisotropic2d(ϵ, β, n, m)\n\n2d rotated anisotropic Laplacian on [0,1]^2 using n x m points with anisotropy number ϵ and angle β\n\"\"\"\nanisotropic2d(ϵ, β, n, m) = stencil2mat(SArray{Tuple{3,3}}([0 0 0 -n^2*(ϵ*cos(β)^2+sin(β)^2) 2n^2*(ϵ*cos(β)^2+sin(β)^2) -n^2*(ϵ*cos(β)^2+sin(β)^2) 0 0 0]), n, m) + stencil2mat(SArray{Tuple{3,3}}([n*m/2*((ϵ-1)*cos(β)*sin(β)) 0 -n*m/2*((ϵ-1)*cos(β)*sin(β)) 0 0 0 -n*m/2*((ϵ-1)*cos(β)*sin(β)) 0 n*m/2*((ϵ-1)*cos(β)*sin(β))]), n, m) + stencil2mat(SArray{Tuple{3,3}}([0 -m^2*(ϵ*sin(β)^2+cos(β)^2) 0 0 2m^2*(ϵ*sin(β)^2+cos(β)^2) 0 0 -m^2*(ϵ*sin(β)^2+cos(β)^2) 0]), n, m)\n\n\n\"\"\"\nanisotropic3d(ϵ₁, ϵ₂, n, m, l)\n\n3d anisotropic Laplacian on [0,1]^3 using n x m x l points and anisotropy numbers ϵ₁ and ϵ₂\n\"\"\"\nanisotropic3d(ϵ₁, ϵ₂, n, m, l) = stencil2mat(SArray{Tuple{3,3,3}}([0 0 0 0 -l^2 0 0 0 0 0 -ϵ₂*m^2 0 -ϵ₁*n^2 2(ϵ₁*n^2+ϵ₂*m^2+l^2) -ϵ₁*n^2 0 -ϵ₂*m^2 0 0 0 0 0 -l^2 0 0 0 0]), n, m, l)\n", "meta": {"hexsha": "808df6d4dd6c4fdaef682cb0f20c3fddab5f92d5", "size": 1199, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/compose_matrix.jl", "max_stars_repo_name": "PieterjanRobbe/NotSoSimpleMultigrid.jl", "max_stars_repo_head_hexsha": "877de2f5be2c96bc9c7796bf321434858ba9659d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/compose_matrix.jl", "max_issues_repo_name": "PieterjanRobbe/NotSoSimpleMultigrid.jl", "max_issues_repo_head_hexsha": "877de2f5be2c96bc9c7796bf321434858ba9659d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/compose_matrix.jl", "max_forks_repo_name": "PieterjanRobbe/NotSoSimpleMultigrid.jl", "max_forks_repo_head_hexsha": "877de2f5be2c96bc9c7796bf321434858ba9659d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.9583333333, "max_line_length": 464, "alphanum_fraction": 0.5954962469, "num_tokens": 667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214460461697, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.8117905254763851}} {"text": "\"\"\"\n _orientation(x::Tuple{<:Number, <:Number}, y::Tuple{<:Number, <:Number}, z::Tuple{<:Number, <:Number})\n\nUtility function for `convex_hull`. Given an ordered triplet, this function returns if three\npoints are collinear, oriented in clock-wise or anticlock-wise direction. \n\"\"\"\nfunction _orientation(x::Tuple{<:Number, <:Number}, y::Tuple{<:Number, <:Number}, z::Tuple{<:Number, <:Number})\n \n a = ((y[2] - x[2]) * (z[1] - y[1]) - (y[1] - x[1]) * (z[2] - y[2]))\n\n if isapprox(a, 0, atol=1e-6)\n return 0 # collinear\n elseif a > 0 \n return 1 # clock-wise\n else \n return 2 # counterclock-wise\n end\n\nend\n\n\"\"\"\n _lt_filter(a::Tuple{<:Number, <:Number}, b::Tuple{<:Number, <:Number})\n\nUtility function for sorting step in `convex_hull`. Given two points, `a` and `b`, this function \nreturns true if `a` has larger polar angle (counterclock-wise direction) than `b` w.r.t. first point `chull_p1`. \n\"\"\"\nfunction _lt_filter(a::Tuple{<:Number, <:Number}, b::Tuple{<:Number, <:Number})\n o = QCO._orientation(chull_p1, a, b)\n\n if o == 0\n if LA.norm(collect(chull_p1 .- b))^2 >= LA.norm(collect(chull_p1 .- a))^2\n return true\n else\n return false\n end\n elseif o == 2\n return true\n else\n return false\n end\n \nend\n\n\"\"\"\n convex_hull(points::Vector{T}) where T<:Tuple{Number, Number}\n\nGraham's scan algorithm to compute the convex hull of a finite set of `n` points in a plane \nwith time complexity `O(n*log(n))`. Given a vector of tuples of co-ordinates, this function returns a \nvector of tuples of co-ordinates which form the convex hull of the given set of points. \n\nSources: https://doi.org/10.1016/0020-0190(72)90045-2\n https://en.wikipedia.org/wiki/Graham_scan \n\"\"\"\nfunction convex_hull(points::Vector{T}) where T<:Tuple{Number, Number}\n \n num_points = size(points)[1]\n\n if num_points == 0\n Memento.error(_LOGGER, \"Atleast one point is necessary for evaluating the convex hull\")\n elseif num_points <= 2 \n return points\n end\n\n min_y = points[1][2]\n min = 1\n \n # Bottom-most or else the left-most point when tie\n for i in 2:num_points\n y = points[i][2]\n if (y < min_y) || (y == min_y && points[i][1] < points[min][1])\n min_y = y\n min = i\n end\n end\n \n # Placing the bottom/left-most point at first position\n points[1], points[min] = points[min], points[1]\n\n global chull_p1 = points[1]\n\n points = Base.sort(points, lt = QCO._lt_filter)\n\n # If two or more points are collinear with chull_p1, remove all except the farthest from chull_p1\n arr_size = 2\n for i in 2:num_points\n while (i < num_points) && (QCO._orientation(chull_p1, points[i], points[i+1]) == 0)\n i += 1\n end\n points[arr_size] = points[i]\n arr_size += 1\n end\n\n if arr_size <= 3\n return []\n end\n\n chull = []\n append!(chull, [points[1]])\n append!(chull, [points[2]])\n append!(chull, [points[3]])\n \n for i in 4:(arr_size-1)\n while (size(chull)[1] > 1) && (QCO._orientation(chull[end - 1], chull[end], points[i]) != 2)\n pop!(chull)\n end\n append!(chull, [points[i]])\n end\n \n return chull\nend", "meta": {"hexsha": "fa4242a6aaa84276362e9219a9716e22c1ca220a", "size": 3293, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chull.jl", "max_stars_repo_name": "lockwo/QuantumCircuitOpt.jl", "max_stars_repo_head_hexsha": "952fcd8ca37ee9d1670699390629f8993097883e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2021-06-30T06:23:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T18:08:09.000Z", "max_issues_repo_path": "src/chull.jl", "max_issues_repo_name": "lockwo/QuantumCircuitOpt.jl", "max_issues_repo_head_hexsha": "952fcd8ca37ee9d1670699390629f8993097883e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 47, "max_issues_repo_issues_event_min_datetime": "2021-06-30T05:55:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T00:15:34.000Z", "max_forks_repo_path": "src/chull.jl", "max_forks_repo_name": "lockwo/QuantumCircuitOpt.jl", "max_forks_repo_head_hexsha": "952fcd8ca37ee9d1670699390629f8993097883e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2021-07-12T20:17:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T18:08:40.000Z", "avg_line_length": 29.9363636364, "max_line_length": 113, "alphanum_fraction": 0.6000607349, "num_tokens": 992, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900950352329, "lm_q2_score": 0.8872045892435128, "lm_q1q2_score": 0.8117043218558375}} {"text": "## Exercise 4-7\n## Make a more general version of circle called arc that takes an additional parameter angle, which determines what fraction of a circle to draw. angle is in units of degrees, so when angle = 360, arc should draw a complete circle.\nusing ThinkJulia\n\nprintln(\"Ans: \")\n\nfunction arc(turtle::Turtle, radius::Int, angle)\n len = 2 * π * radius * angle / 360 # finding the length of the arc 2πr * a/360\n n = Int(trunc(len) / 3) + 1 # number of times the turtle will rotate and draw \n\n len /= n\n angle /= n \n\n for i in 1:n\n forward(turtle, len)\n turn(turtle, -angle)\n end\nend\n\n@svg begin \n arc(Turtle(), 200, 270)\nend\n\nprintln(\"End.\")\n", "meta": {"hexsha": "527d43a706446b68f6b46552574ca3275eaaed2c", "size": 680, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chapter4/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": "Chapter4/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": "Chapter4/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": 27.2, "max_line_length": 231, "alphanum_fraction": 0.6588235294, "num_tokens": 195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9740426450627306, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.8116936970454903}} {"text": "using Symbolics\nusing SatisfiabilityInterface\n\n\nvars = @variables x, y, z, w\n\nconstraints = [\n x ∈ 1:2\n y ∈ 2:5\n z ∈ 3:7\n z == x * y\n]\n\nprob = DiscreteCSP(constraints)\n\nsolve(prob)\n\nall_solutions(prob)\n\n\n###\n\n\nvars = @variables x, y, z, w\n\nconstraints = [\n x ∈ 1:2\n y ∈ 2:5\n z ∈ 3:7\n w ∈ 4:6\n z == x + y\n w == z + x\n]\n\nprob = DiscreteCSP(constraints)\nsolve(prob)\nall_solutions(prob)\n\n\n###\n\nconstraints = [\n x ∈ 1:2\n y ∈ 2:5\n z ∈ 3:7\n z == 2x\n]\n\nall_solutions(DiscreteCSP(constraints))\n\n###\n\nvars = @variables x, y, z \n\n# constraints = [\n# x ∈ 1:4\n# y ∈ 2:5\n# z == x + y\n# z ≤ 4\n# ]\n\n\n\n### Subset sum Problem\n\n# https://en.wikipedia.org/wiki/Subset_sum_problem\n\n\n# Given a set of integers like {−7, −3, −2, 5, 8}, \n# do a subset sum to 0?\n\ns = [-7, -3, -2, 5, 8]\nn = length(s)\nx = [Num(Variable(:x, i)) for i in 1:n]\n\nconstraints = [\n [x[i] ∈ (0:1) for i in 1:n]\n sum(x[i] * s[i] for i in 1:n) == 0\n sum(x) ≠ 0 # at least one is not 0\n ]\n\nprob = DiscreteCSP(constraints)\n\nall_solutions(prob)\n\n\n#####\n\n@variables x, y, z\n\nconstraints = [\n x ∈ 1:2\n y ∈ 2:5\n z ∈ 3:7\n z == 2x\n]\n\n\n\nprob = DiscreteCSP(constraints)\nall_solutions(prob)\n\n## Example from https://github.com/newptcai/BeeEncoder.jl\n\nfunction make_vector(name::Symbol, range)\n return Num.(Variable.(name, range))\nend\n\n@variables x, y, z, w\nb = make_vector(:b, 1:4)\n# @variables b[1:4]\n\n\n¬(x::Num) = 1 - x # assumes a Boolean variable\n\n\nconstraints = [\n x ∈ 0:5\n y ∈ -4:9\n z ∈ -5:10\n w ∈ 0:10\n\n [bb ∈ 0:1 for bb ∈ b]\n \n x + y == z\n \n b[1] == ¬b[2]\n b[2] == 1\n\n ¬b[1] + b[2] + ¬b[3] + b[4] == w\n]\n\nprob = DiscreteCSP(constraints)\nsolve(prob)\n\n# @time length(all_solutions(prob)) # 1184 solutions in 38 seconds\n\n\n\n### \n\nconstraints = [\n x ∈ -5:5\n y ∈ -4:9\n x - y^2 == 3\n # sum(b) == w\n\n]\n\n\nprob = DiscreteCSP(constraints) \nall_solutions(prob)\n\n### \n\n@variables x, y\n\nconstraints = [\n x ∈ -5:5\n y ∈ -4:9\n 10x + y == 9\n # sum(b) == w\n]\n\nprob = DiscreteCSP(constraints) \nall_solutions(prob)\n\n\n", "meta": {"hexsha": "022f5254f31ff8b8c27d032a31604903f6c1905e", "size": 2090, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/examples.jl", "max_stars_repo_name": "Wimmerer/SatisfiabilityInterface.jl", "max_stars_repo_head_hexsha": "b2148fadf45dca6304e9f4b571d1e3ea54c85ba4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-01-15T22:50:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-31T22:24:42.000Z", "max_issues_repo_path": "examples/examples.jl", "max_issues_repo_name": "Wimmerer/SatisfiabilityInterface.jl", "max_issues_repo_head_hexsha": "b2148fadf45dca6304e9f4b571d1e3ea54c85ba4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-06-26T21:09:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-08T12:12:43.000Z", "max_forks_repo_path": "examples/examples.jl", "max_forks_repo_name": "Wimmerer/SatisfiabilityInterface.jl", "max_forks_repo_head_hexsha": "b2148fadf45dca6304e9f4b571d1e3ea54c85ba4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-06-25T20:22:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T09:47:46.000Z", "avg_line_length": 12.3668639053, "max_line_length": 68, "alphanum_fraction": 0.5320574163, "num_tokens": 812, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240211961401, "lm_q2_score": 0.8652240947405564, "lm_q1q2_score": 0.8116875069938009}} {"text": "#=\nIt is possible to show that the square root of two can be expressed as an infinite continued fraction.\n\n√ 2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213...\n\nBy expanding this for the first four iterations, we get:\n\n1 + 1/2 = 3/2 = 1.5\n1 + 1/(2 + 1/2) = 7/5 = 1.4\n1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666...\n1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379...\n\nThe next three expansions are 99/70, 239/169, and 577/408, but the eighth expansion, 1393/985, is the first example where the number of digits in the numerator exceeds the number of digits in the denominator.\n\nIn the first one-thousand expansions, how many fractions contain a numerator with more digits than denominator?\n=#\nfunction calc()\n p = BigInt(1)\n q = BigInt(1)\n count = 1\n total = 0\n while count <= 1000\n np = p + 2q\n nq = p + q\n p,q = np,nq\n if length(string(p)) > length(string(q))\n total = total + 1\n end\n count = count + 1\n end\n total\nend\n@time println(calc())\n", "meta": {"hexsha": "1e4d6f69098d05e7aaafab4074336718338da1d3", "size": 971, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p57.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/p57.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/p57.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 28.5588235294, "max_line_length": 208, "alphanum_fraction": 0.6189495366, "num_tokens": 349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.93812402119614, "lm_q2_score": 0.8652240738888188, "lm_q1q2_score": 0.8116874874322849}} {"text": "# nuclear Norm (times a constant)\n\nexport NuclearNorm\n\n\"\"\"\n**Nuclear norm**\n\n NuclearNorm(λ=1.0)\n\nReturns the function\n```math\nf(X) = \\\\|X\\\\|_* = λ ∑_i σ_i(X),\n```\nwhere `λ` is a positive parameter and ``σ_i(X)`` is ``i``-th singular value of matrix ``X``.\n\"\"\"\nstruct NuclearNorm{R <: Real} <: ProximableFunction\n lambda::R\n function NuclearNorm{R}(lambda::R) where {R <: Real}\n if lambda < 0\n error(\"parameter λ must be nonnegative\")\n else\n new(lambda)\n end\n end\nend\n\nis_convex(f::NuclearNorm) = true\n\nNuclearNorm(lambda::R=1.0) where {R <: Real} = NuclearNorm{R}(lambda)\n\nfunction (f::NuclearNorm{R})(X::AbstractMatrix{T}) where {R <: Real, T <: Union{R, Complex{R}}}\n F = svd(X);\n return f.lambda * sum(F.S);\nend\n\nfunction prox!(Y::AbstractMatrix{T}, f::NuclearNorm{R}, X::AbstractMatrix{T}, gamma::R=one(R)) where {R <: Real, T <: Union{R, Complex{R}}}\n F = svd(X)\n S_thresh = max.(zero(R), F.S .- f.lambda*gamma)\n rankY = findfirst(S_thresh .== zero(R))\n if rankY === nothing\n rankY = minimum(size(X))\n end\n Vt_thresh = view(F.Vt, 1:rankY, :)\n U_thresh = view(F.U, :, 1:rankY)\n # TODO: the order of the following matrix products should depend on the shape of x\n M = S_thresh[1:rankY] .* Vt_thresh\n mul!(Y, U_thresh, M)\n return f.lambda * sum(S_thresh);\nend\n\nfun_name(f::NuclearNorm) = \"nuclear norm\"\nfun_dom(f::NuclearNorm) = \"AbstractArray{Real,2}, AbstractArray{Complex,2}\"\nfun_expr(f::NuclearNorm) = \"X ↦ λ∑σ_i(X)\"\nfun_params(f::NuclearNorm) = \"λ = $(f.lambda)\"\n\nfunction prox_naive(f::NuclearNorm, X::AbstractMatrix{T}, gamma=1.0) where T\n F = svd(X)\n S = max.(0, F.S .- f.lambda*gamma)\n Y = F.U * (Diagonal(S) * F.Vt)\n return Y, f.lambda * sum(S)\nend\n", "meta": {"hexsha": "f82d928d1074e64514ed18ffca155f7cc6bef13e", "size": 1706, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/nuclearNorm.jl", "max_stars_repo_name": "lostella/ProximalOperators.jl", "max_stars_repo_head_hexsha": "9935cd0c24b325667e688b5c35703dde71bfd3a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-12-15T13:57:52.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T13:57:52.000Z", "max_issues_repo_path": "src/functions/nuclearNorm.jl", "max_issues_repo_name": "lostella/ProximalOperators.jl", "max_issues_repo_head_hexsha": "9935cd0c24b325667e688b5c35703dde71bfd3a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions/nuclearNorm.jl", "max_forks_repo_name": "lostella/ProximalOperators.jl", "max_forks_repo_head_hexsha": "9935cd0c24b325667e688b5c35703dde71bfd3a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5161290323, "max_line_length": 139, "alphanum_fraction": 0.6395076202, "num_tokens": 585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240194661945, "lm_q2_score": 0.865224070413529, "lm_q1q2_score": 0.8116874826752415}} {"text": "using Plots\nusing Printf\n\n\"\"\"\n untildivergence(f, x, maxiter=50)\n\nIterate `f` on `x` until its module is greater than 2 or `maxiter` iterations have been done.\n\nReturns the number of iterations.\n\"\"\"\nfunction untildivergence(f, x, maxiter = 50)\n i = 0\n while abs(x) < 2 && (i += 1) <= maxiter\n x = f(x)\n end\n return i\nend\n\n\"\"\"\n julia_set_wh(f; kwargs)\n\nApproximate the Julia set of `f` in a grid using the escape time algorithm.\n\nThe grid is defined by its bounds `xmin`, `xmax`, `ymin` and `ymax` as well as its width `w` and height `h` in pixels. The optional parameter `maxiter` is passed on to `untildivergence`.\n\"\"\"\nfunction julia_set_wh(f; xmin::Real=-2, xmax::Real=2, ymin::Real=-2, ymax::Real=2, w::Int=1000, h::Int=1000, maxiter::Int=50)\n img = Array{Int,2}(undef, h, w)\n x = LinRange(xmin, xmax, w)\n y = LinRange(ymin, ymax, h)\n # creating labels for use with `heatmap`\n xticks = LinRange(1,w,11)\n yticks = LinRange(1,h,11)\n xlabels = map(z->@sprintf(\"%.2f\",z), LinRange(xmin,xmax,11))\n ylabels = map(z->@sprintf(\"%.2f\",z), LinRange(ymin,ymax,11))\n\n for i in 1:w, j in 1:h\n img[j,i] = untildivergence(f, x[i]+im*y[j], maxiter)\n end\n return img, xticks, xlabels, yticks, ylabels\nend\n\n\"\"\"\n julia_set(f, cellsize; kwargs)\n\nApproximate the Julia of `f` set in a grid of cells of length `cellsize`.\n\nThe grid is defined by the same parameters as in `julia_set_wh`, except its width and height in pixels are computed with `cellsize`.\n\"\"\"\nfunction julia_set(f, cellsize::Real; xmin=-2, xmax=2, ymin=-2, ymax=2, maxiter=50)\n w = Integer(round(abs(xmax-xmin)/cellsize))\n h = Integer(round(abs(ymax-ymin)/cellsize))\n return julia_set_wh(f, xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, w=w, h=h, maxiter=maxiter)\nend\n\n\"\"\"\n mandelbrot_set_wh(f; kwargs)\n\nApproximate the Mandelbrot set of `f` in a grid using the escape time algorithm.\n\nThe grid is defined by its bounds `xmin`, `xmax`, `ymin` and `ymax` as well as its width `w` and height `h` in pixels. The optional parameter `maxiter` is passed on to `untildivergence`.\n\"\"\"\nfunction mandelbrot_set_wh(f; xmin::Real=-2, xmax::Real=2, ymin::Real=-2, ymax::Real=2, w::Integer=1000, h::Integer=1000, maxiter::Integer=50)\n img = Array{Int,2}(undef, h, w)\n x = LinRange(xmin, xmax, w)\n y = LinRange(ymin, ymax, h)\n # creating labels for use with `heatmap`\n xticks = LinRange(1,w,11)\n yticks = LinRange(1,h,11)\n xlabels = map(z->@sprintf(\"%.2f\",z), LinRange(xmin,xmax,11))\n ylabels = map(z->@sprintf(\"%.2f\",z), LinRange(ymin,ymax,11))\n\n for i in 1:w, j in 1:h\n img[j,i] = untildivergence(f(x[i]+im*y[j]), 0, maxiter)\n end\n return img, xticks, xlabels, yticks, ylabels\nend\n\n\"\"\"\n mandelbrot_set(f, cellsize; kwargs)\n\nApproximate the Mandelbrot of `f` set in a grid of cells of length `cellsize`.\n\nThe grid is defined by the same parameters as in `julia_set_wh`, except its width and height in pixels are computed with `cellsize`.\n\"\"\"\nfunction mandelbrot_set(f, cellsize; xmin=-2, xmax=2, ymin=-2, ymax=2, maxiter=50)\n w = Integer(round(abs(xmax-xmin)/cellsize))\n h = Integer(round(abs(ymax-ymin)/cellsize))\n return mandelbrot_set_wh(f, xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, w=w, h=h, maxiter=maxiter)\nend\n\n# the traditional julia/mandelbrot function\nf(c) = z -> z^2 + c\n\nimg, xticks, xlabels, yticks, ylabels = mandelbrot_set(f, 0.00005, xmin=-2.01, xmax = -1.8, ymin = -0.1, ymax = 0.1)\n\nimg, xticks, xlabels, yticks, ylabels = julia_set(f(im), 0.0005, xmin=-2, xmax=2, ymin=-2,ymax=2)\n\n\nheatmap(img,\n xticks = (xticks, xlabels),\n yticks = (yticks, ylabels),\n aspect_ratio=:equal\n )\n\n# alternative, for better looking images\nusing Images, Colors\ng = Gray.(img/51)\n\ng = Gray.(.!(img .>= 50))\n\nmset = img .>= 50\n\n#save(\"julia_minus2.png\", g)\n\ninclude(\"FractalDimensions.jl\")\n\nB = boundary(mset)\nGray.(B)\npoints = array_to_points(B)\n\nd, N, ε = box_counting_dimension(points, 10)\n\nC, r = correlation_dimension(points)\n\nloglog_regression(C,r)\n", "meta": {"hexsha": "08464181aeae0d994865f4c94a7367f8ebae772a", "size": 4045, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "mandelbrot.jl", "max_stars_repo_name": "csimal/chaos-and-fractals", "max_stars_repo_head_hexsha": "4b189b0fde62d480f1f2e750b976de54bd9d2297", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mandelbrot.jl", "max_issues_repo_name": "csimal/chaos-and-fractals", "max_issues_repo_head_hexsha": "4b189b0fde62d480f1f2e750b976de54bd9d2297", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mandelbrot.jl", "max_forks_repo_name": "csimal/chaos-and-fractals", "max_forks_repo_head_hexsha": "4b189b0fde62d480f1f2e750b976de54bd9d2297", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1031746032, "max_line_length": 186, "alphanum_fraction": 0.6637824475, "num_tokens": 1333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240090865197, "lm_q2_score": 0.8652240756264639, "lm_q1q2_score": 0.8116874785848764}} {"text": "### Gali's Book Chapter 3 model\n### We use this as a consistency check of gensys implementation\n### By Daniel Coutinho and Gilberto Boaretto\n\n#### Parameters from Gali's book example, chapter 3, page 52, first edition\n\nbet = 0.99\nsig = 1\nphi = 1\nalfa = 1/3\nepsilon = 6\ntheta = 2/3\nphi_pi = 1.5\nphi_y = 0.5/4\nrho_v = 0.5\n\ntrue_pars = (alfa = alfa, bet = bet, epsilon = epsilon, theta = theta, sig = sig, s2 = 1, phi = phi, phi_pi = phi_pi, phi_y = phi_y, rho_v = rho_v)\n\nTHETA = (1-alfa)/(1-alfa+alfa*epsilon)\nlamb = (1-theta)*(1-bet*theta)/theta*THETA\nkappa = lamb*(sig+(phi+alfa)/(1-alfa))\n\n## Gali's give analytical expressions for the effects of a shock in the monetary policy over inflation and output gap,chapter 3, page 51, first edition\n\nLAMBDA_v = ((1-bet*rho_v)*(sig*(1-rho_v)+phi_y)+kappa*(phi_pi-rho_v))^(-1)\n\ny_irf(v) = -(1-bet*rho_v)*LAMBDA_v*v\npi_irf(v) = -kappa*LAMBDA_v*v\nr_irf(v) = sig*(1-rho_v)*(1-bet*rho_v)*LAMBDA_v*v\ni_irf(v) = (sig*(1-rho_v)*(1-bet*rho_v) - rho_v*kappa)*LAMBDA_v*v\nv_irf(v,uu) = rho_v*v + uu\n\n## Test drive: lets see if this gives the same IRFs that we get in Gali's book\n## This is just for debugging, so comment it out when using it to check gensys consistency\n\n#using Plots\n\nirfs_true = zeros(15,5)\n\nirfs_true[1,1] = 0\n\nuu = 0.25\n\nfor t in 2:15\n irfs_true[t,4] = v_irf(irfs_true[t-1,4],uu)\n irfs_true[t,1] = pi_irf(irfs_true[t,4])\n irfs_true[t,2] = y_irf(irfs_true[t,4])\n irfs_true[t,3] = i_irf(irfs_true[t,4])\n irfs_true[t,5] = r_irf(irfs_true[t,4])\n global uu = 0\nend\n\n#plot(irfs[2:13,1], label = \"v\")\n#plot(irfs[2:13,2]*4, label = \"pi\")\n#plot(irfs[2:13,3], label = \"y\")\n#plot(4*irfs[2:13,4], label = \"i\")\n#plot(4*irfs[2:13,5], label = \"r\")\n", "meta": {"hexsha": "fbf283a5c69ba38d20e448536dc30c8bb0816133", "size": 1703, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "galis_example.jl", "max_stars_repo_name": "danmrc/DSGE-HMC", "max_stars_repo_head_hexsha": "04601e6d7c5a878ea0812d48e974b3f9c91c90ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "galis_example.jl", "max_issues_repo_name": "danmrc/DSGE-HMC", "max_issues_repo_head_hexsha": "04601e6d7c5a878ea0812d48e974b3f9c91c90ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "galis_example.jl", "max_forks_repo_name": "danmrc/DSGE-HMC", "max_forks_repo_head_hexsha": "04601e6d7c5a878ea0812d48e974b3f9c91c90ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-20T09:15:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-20T09:15:46.000Z", "avg_line_length": 29.3620689655, "max_line_length": 151, "alphanum_fraction": 0.6617733412, "num_tokens": 677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582612793112, "lm_q2_score": 0.8723473796562744, "lm_q1q2_score": 0.8116828261065403}} {"text": "# AAA algorithm from the paper \"The AAA Alorithm for Rational Approximation\"\n# by Y. Nakatsukasa, O. Sete, and L.N. Trefethen, SIAM Journal on Scientific Computing\n# 2018 \n\nstruct AAAapprox{T <: AbstractArray} <: BRInterp\n x::T\n f::T\n w::T\n errvec::T\nend\n\n(a::AAAapprox)(zz) = reval(zz, a.x, a.f, a.w)\n\n# Handle function inputs as well\nfunction aaa(Z::AbstractArray{T,1}, F::S; tol=1e-13, mmax=100, verbose=false, clean=true) where {T, S<:Function}\n aaa(Z, F.(Z), tol=tol, mmax=mmax, verbose=verbose, clean=clean)\nend\n\n\"\"\"aaa rational approximation of data F on set Z\n r = aaa(Z, F; tol, mmax, verbose, clean)\n\n Input: Z = vector of sample points\n F = vector of data values at the points in Z\n tol = relative tolerance tol, set to 1e-13 if omitted\n mmax: max type is (mmax-1, mmax-1), set to 100 if omitted\n verbose: print info while calculating default = false\n clean: detect and remove Froissart doublets default = true\n\n Output: r = an AAA approximant as a callable struct with fields\n z, f, w = vectors of support pts, function values, weights\n errvec = vector of errors at each step\n\n NOTE: changes from matlab version:\n switched order of Z and F in function signature\n added verbose and clean boolean flags\n pol, res, zer = vectors of poles, residues, zeros are now only calculated on demand\n by calling prz(z::AAAapprox)\n\"\"\"\nfunction aaa(Z::AbstractArray{T,1}, F::AbstractArray{S,1}; tol=1e-13, mmax=100,\n verbose=false, clean=true) where {S, T}\n # filter out any NaN's or Inf's in the input\n keep = isfinite.(F)\n F = F[keep]\n Z = Z[keep]\n \n M = length(Z) # number of sample points\n mmax = min(M, mmax) # max number of support points\n \n reltol = tol*norm(F, Inf)\n SF = spdiagm(M, M, 0 => F) # left scaling matrix\n \n F, Z = promote(F, Z)\n P = promote_type(S, T)\n \n J = [1:M;]\n z = P[] # support points\n f = P[] # function values at support points\n C = P[]\n w = P[]\n \n errvec = P[]\n R = F .- mean(F)\n @inbounds for m = 1:mmax\n j = argmax(abs.(F .- R)) # select next support point\n push!(z, Z[j])\n push!(f, F[j])\n deleteat!(J, findfirst(isequal(j), J)) # update index vector\n\n # next column of Cauchy matrix\n C = isempty(C) ? reshape((1 ./ (Z .- Z[j])), (M,1)) : [C (1 ./ (Z .- Z[j]))]\n\n Sf = diagm(f) # right scaling matrix\n A = SF * C - C * Sf # Loewner matrix\n G = svd(A[J, :])\n \n # A[J, :] might not have full rank, so svd can return fewer than m columns\n #w = G.V[:, m] \n w = G.V[:, end] # weight vector = min sing vector\n \n N = C * (w .* f) # numerator \n D = C * w\n R .= F\n R[J] .= N[J] ./ D[J] # rational approximation\n \n err = norm(F - R, Inf)\n verbose && println(\"Iteration: \", m, \" err: \", err)\n errvec = [errvec; err] # max error at sample points\n err <= reltol && break # stop if converged\n end\n r = AAAapprox(z, f, w, errvec)\n\n # remove Frois. doublets if desired. We do this in place\n if clean\n pol, res, zer = prz(r) # poles, residues, and zeros\n ii = findall(abs.(res) .< 1e-13) # find negligible residues\n length(ii) != 0 && cleanup!(r, pol, res, zer, Z, F)\n end\n return r\nend\n\n\nfunction prz(r::AAAapprox)\n z, f, w = r.x, r.f, r.w \n m = length(w)\n B = diagm(ones(m+1))\n B[1, 1] = 0.0\n E = [0.0 transpose(w); ones(m) diagm(z)]\n pol, _ = eigen(E, B)\n pol = pol[isfinite.(pol)] \n dz = 1e-5 * exp.(2im*pi*[1:4;]/4)\n \n # residues\n res = r(pol .+ transpose(dz)) * dz ./ 4 \n \n E = [0 transpose(w .* f); ones(m) diagm(z)]\n zer, _ = eigen(E, B)\n zer = zer[isfinite.(zer)]\n pol, res, zer\nend\n\n\nfunction reval(zz, z, f, w)\n # evaluate r at zz\n zv = size(zz) == () ? [zz] : vec(zz) \n CC = 1.0 ./ (zv .- transpose(z)) # Cauchy matrix\n r = (CC * (w .* f)) ./ (CC * w) # AAA approx as vector\n r[isinf.(zv)] .= sum(f .* w) ./ sum(w)\n \n ii = findall(isnan.(r)) # find values NaN = Inf/Inf if any\n @inbounds for j in ii\n if !isnan(zv[j]) && ((v = findfirst(isequal(zv[j]), z)) !== nothing)\n r[j] = f[v] # force interpolation there\n end\n end\n r = size(zz) == () ? r[1] : reshape(r, size(zz)) # the AAA approximation\nend\n\n\n# Only calculate the updated z, f, and w\nfunction cleanup!(r, pol, res, zer, Z, F)\n z, f, w = r.x, r.f, r.w\n m = length(z)\n M = length(Z)\n ii = findall(abs.(res) .< 1e-13) # find negligible residues\n ni = length(ii)\n ni == 0 && return\n println(\"$ni Froissart doublets. Number of residues = \", length(res))\n\n @inbounds for j = 1:ni\n azp = abs.(z .- pol[ii[j]] )\n jj = findall(isequal(minimum(azp)), azp)\n deleteat!(z, jj) # remove nearest support points\n deleteat!(f, jj)\n end \n\n @inbounds for j = 1:length(z)\n jj = findall(isequal(z[j]), Z)\n deleteat!(F, jj)\n deleteat!(Z, jj)\n end\n m = m - length(ii)\n SF = spdiagm(M-m, M-m, 0 => F)\n Sf = diagm(f)\n C = 1 ./ (Z .- transpose(z))\n A = SF*C - C*Sf\n G = svd(A)\n w[:] .= G.V[:, m]\n println(\"cleanup: \", size(z), \" \", size(f), \" \", size(w))\n return nothing\nend\n", "meta": {"hexsha": "e2a19e30650aefafbce67e0e9eef186f92abef62", "size": 5678, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/aaa.jl", "max_stars_repo_name": "macd/BaryRational.jl", "max_stars_repo_head_hexsha": "6e5bb75e6fa3146bea855d2412fb45fecf9a8103", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-01-28T20:12:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T03:34:03.000Z", "max_issues_repo_path": "src/aaa.jl", "max_issues_repo_name": "macd/BaryRational.jl", "max_issues_repo_head_hexsha": "6e5bb75e6fa3146bea855d2412fb45fecf9a8103", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-22T09:05:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-22T09:05:02.000Z", "max_forks_repo_path": "src/aaa.jl", "max_forks_repo_name": "macd/BaryRational.jl", "max_forks_repo_head_hexsha": "6e5bb75e6fa3146bea855d2412fb45fecf9a8103", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2046783626, "max_line_length": 113, "alphanum_fraction": 0.5149700599, "num_tokens": 1765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582612793112, "lm_q2_score": 0.8723473796562744, "lm_q1q2_score": 0.8116828261065403}} {"text": "#############################\n## Numerical experiments associated with section 5.4.1\n#############################\n## Nonlinear equations are treated by first defining an objective function, then using standard iterative methods\n## such as Newton's method via NLsolve.jl. Using more sophisticated methods, linesearches etc. can sometimes result in significant speed boosts.\n##\n\nusing NLsolve, ApproxFun, MultivariateOrthogonalPolynomials, BandedMatrices, BlockBandedMatrices, Plots\nusing SparseVolterraExamples\n\n#####################################################\n## Problem in Equation (25), u_1(x) = exp(x)\n#####################################################\n####\n## Define g(x), the nonlinearity and the kernel\ng(x) = exp(x)+1/3*x*(1-exp(3*x))\n gFun = Fun(g,Jacobi(0,1,0..1))\n f(u) = u^3\n K(x,y) = x\n n = 15 # Desired polynomial order of approximation for accuracy\n####\n## Define the objective function and compute the solution using a standard Newton method\nobjective(x) = triNonLinearVolterraObjective(x,f,K,gFun,n)\nsol = nlsolve(objective,zeros(n),method=:newton,ftol=1e-8)\n####\n## Plot function aganinst analytic solution\nplot(Fun(Jacobi(0,1,0..1),sol.zero),grid=false,legend=:topleft,xlabel=\"x\",ylabel=\"u(x)\",label=\"sparse method\")\nplot!(exp,0,1,grid=false,legend=:topleft,xlabel=\"x\",ylabel=\"u(x)\",label=\"analytic exp(x)\")\n####\n## Or plot error. A simple loop over polynomial degree can then produce Figure 7(a).\nplot(Fun(Jacobi(0,1,0..1),sol.zero)-Fun(x->exp(x),Jacobi(0,1,0..1)),grid=false,legend=:bottomleft,xlabel=\"x\",ylabel=\"error\",label=false)\n\n#####################################################\n## Problem in Equation (26), u_2(x) = sin(x)\n#####################################################\n####\n## Define g(x), the nonlinearity and the kernel\ng(x) = sin(x)+1/4*sin(x)^2-1/4*x^2\n gFun = Fun(g,Jacobi(0,1,0..1))\n f(u) = u^2\n K(x,y) = x-y\n n = 14 # Desired polynomial order of approximation for accuracy\n####\n## Define the objective function and compute the solution using a standard Newton method\nobjective(x) = triNonLinearVolterraObjective(x,f,K,gFun,n)\nsol = nlsolve(objective,zeros(n),method=:newton,ftol=1e-15)\n####\n## Plot function aganinst analytic solution\nplot(Fun(Jacobi(0,1,0..1),sol.zero),grid=false,legend=:topleft,xlabel=\"x\",ylabel=\"u(x)\",label=\"sparse method\")\nplot!(sin,0,1,grid=false,legend=:topleft,xlabel=\"x\",ylabel=\"u(x)\",label=\"analytic sin(x)\")\n####\n## Or plot error. A simple loop over polynomial degree can then produce Figure 7(b).\nplot(Fun(Jacobi(0,1,0..1),sol.zero)-Fun(x->sin(x),Jacobi(0,1,0..1)),grid=false,legend=:bottomleft,xlabel=\"x\",ylabel=\"error\",label=false)\n", "meta": {"hexsha": "8ed89d5863a8f4e660f0bb43f2daacac6b24ddec", "size": 2643, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Section 5-4-1 - Nonlinear Volterra integral equations.jl", "max_stars_repo_name": "TSGut/SparseVolterraExamples.jl", "max_stars_repo_head_hexsha": "277733c70dfe78b65d1d9ad289de9dbeacda27b7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-18T16:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-18T16:58:42.000Z", "max_issues_repo_path": "examples/Section 5-4-1 - Nonlinear Volterra integral equations.jl", "max_issues_repo_name": "TSGut/SparseVolterraExamples.jl", "max_issues_repo_head_hexsha": "277733c70dfe78b65d1d9ad289de9dbeacda27b7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-09T15:39:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T15:59:37.000Z", "max_forks_repo_path": "examples/Section 5-4-1 - Nonlinear Volterra integral equations.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": 48.9444444444, "max_line_length": 144, "alphanum_fraction": 0.6382898222, "num_tokens": 737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109798251322, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.8115680579846832}} {"text": "using LinearAlgebra\n\n\"\"\"\n is_schur(A::AbstractMatrix)\n\nCheck if a square matrix is Schur, i.e. the eigenvalues lie within the unit circle.\n\n### Input\n- `A` -- square matrix\n\n### Ouput\nBoolean value indicating if the matrix `A` is Schur.\n\"\"\"\nis_schur(A::AbstractMatrix) = maximum(abs.(eigvals(A))) < 1.0\n", "meta": {"hexsha": "f60bcbf1c71afa53d5d0c94586fedf8e765f35b8", "size": 306, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/helper/control_systems.jl", "max_stars_repo_name": "mforets/InvariantSets", "max_stars_repo_head_hexsha": "fc6e61e404c80e959932336199fa3508fe2c2c35", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-08-10T20:47:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-31T06:13:51.000Z", "max_issues_repo_path": "src/helper/control_systems.jl", "max_issues_repo_name": "mforets/InvariantSets", "max_issues_repo_head_hexsha": "fc6e61e404c80e959932336199fa3508fe2c2c35", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-05-19T13:03:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-22T07:46:51.000Z", "max_forks_repo_path": "src/helper/control_systems.jl", "max_forks_repo_name": "ueliwechsler/InvariantSets.jl", "max_forks_repo_head_hexsha": "680cb87bd61cb26f3c1cfe97eaf27009d38ac016", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-05-18T12:26:10.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-18T12:26:10.000Z", "avg_line_length": 20.4, "max_line_length": 83, "alphanum_fraction": 0.6960784314, "num_tokens": 91, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9504109770159682, "lm_q2_score": 0.8539127566694177, "lm_q1q2_score": 0.81156805735258}} {"text": "export solarposition, zenith, zenith_azimuth, sines_and_cosines\n\n# Calculate the position of the sun as (zenith,azimuth) in degrees for a location\n# on earth given as (latitude,longitude) in degrees. The DateTime should be given\n# as Universal Time, e.g. UTC. \nfunction solarposition_wiki(datetime::DateTime, latitude, longitude)\n\t# Position of the Sun as seen from Earth.\n\t# Ported from Matlab, original helpstring below.\n\n\t# This is the most basic algorithm. It is documented in Seinfeld &\n\t# Pandis, Duffie & Beckman and Wikipedia.\n\t#\n\t# [ANGLES,PROJECTION] = SOLARPOSITION(DATE,TIME,LATITUDE,LONGITUDE,TIME_ZONE)\n\t# returns ZENITH & AZIMUTH for all DATE & TIME pairs at LATITUDE, LONGITUDE.\n\t# ANGLES = [ZENITH,AZIMUTH] and PROJECTION = [PHI_X, PHI_Y]\n\t# PHI_X is projection on x-z plane & PHI_Y is projection on y-z plane.\n\t# DATETIME can be string, vector [YEAR, MONTH, DAY, HOURS, MINUTES, SECONDS],\n\t# cellstring or matrix N x [YEAR, MONTH, DAY, HOURS, MINUTES, SECONDS] for N\n\t# times.\n\t# LATITUDE [degrees] and LONGITUDE [degrees] are the coordinates of the site.\n\t# TIME_ZONE [hours] of the site.\n\t# ROTATION [degrees] clockwise rotation of system relative to north.\n\t# DST [logical] flag for daylight savings time, typ. from March to November\n\t# in the northern hemisphere.\n\t#\n\t# References:\n\t# http://en.wikipedia.org/wiki/Solar_azimuth_angle\n\t# http://en.wikipedia.org/wiki/Solar_elevation_angle\n\t#\n\t# Mark A. Mikofski\n\t# Copyright (c) 2013\n\n\n\n\t# Equation of Time\n\t# \"Alternative calculation\" on wikipedia:\n\t# https://en.wikipedia.org/wiki/Equation_of_time#Calculating_the_equation_of_time\n\t# Supposedly accurate to 6 seconds (0.1 minutes)\n\n\tyear = Dates.year(datetime)\n\t# date in days starting at zero on 1 January (the subtraction produces a difference in milliseconds)\n\td_ms = datetime - DateTime(year,1,1)\n\td = d_ms.value/1000/3600/24\n\n\t# Earth's mean angular orbital velocity [degrees/day]\n\tw = 360/365.24\n\t# angle the earth moves on its orbit at its average speed from the December solstice\n\t# 10 is the approximate number of days from the December solstice to January 1\n\ta = w * (d+10)\n\t# The angle the Earth moves from the solstice to date D, including a first-order correction\n\t# for the Earth's orbital eccentricity, 0.0167. The number 2 is the number of days from 1 January\n\t# to the date of the Earth's perihelion.\n\tb = a + (360/pi*0.0167)*sind(w*(d-2))\n\t# C is the difference between the angles moved at mean speed, and at the corrected speed projected\n\t# onto the equatorial plane, and divided by 180 to get the difference in \"half turns\". The value 23.44°\n\t# is the obliquity (tilt) of the Earth's axis. The subtraction gives the conventional sign to the equation of time. \n\tc = (a - atand(tand(b)/cosd(23.44))) / 180\n\t# For any given value of x, arctan x (sometimes written as tan−1 x) has multiple values, differing from each other\n\t# by integer numbers of half turns. This may cause C to be wrong by an integer number of half turns. The excess\n\t# half turns are removed in the next step of the calculation to give the equation of time:\n\tET = 720*(c - round(c))\n\n\t# approximate solar time [hours]\n\tsolarTime = 24*(d - floor(d)) + longitude*24/360 + ET/60\n\tt_h = 15*(solarTime - 12) # [degrees] hour angle\n\n\t# declination [degrees]\n\t# accurate to 0.2 degrees, see https://en.wikipedia.org/wiki/Position_of_the_Sun#Calculations\n\tdelta = -asind(sind(23.44)*cosd(b))\n\tzenith = acosd(sind(latitude)*sind(delta) + cosd(latitude)*cosd(delta)*cosd(t_h)) # [degrees] zenith\n\n\t# azimuth [0, 180], absolute value measured from due south, so east = west = 90,\n\t# south = 0, north = 180\n\tcos_phi = (cosd(zenith)*sind(latitude) - sind(delta)) ./ (sind(zenith)*cosd(latitude)) # cosine(azimuth)\n\tphi_south = acosd(clamp(cos_phi,-1,1))\n\t#phi_south = acosd(cos_phi);\n\n\t# azimuth [0, 360], measured clockwise from due north,\n\t# so east = 90, south = 180, and west = 270 degrees\n\tazimuth = 180 + sign(t_h)*phi_south # Shift domain to 0-360 deg\n\n\t#angles = [theta, phi]; # [degrees] zenith, azimuth\n\treturn zenith, azimuth, solarTime, delta\nend\n\nfunction solarposition_wiki_faster(datetime::DateTime, latitude, longitude)\n\tyear = Dates.year(datetime)\n\td_ms = datetime - DateTime(year,1,1)\n\td = d_ms.value/1000/3600/24\n\tw = 360/365.24\n\ta = w * (d+10)\n\tb = a + (360/pi*0.0167)*sind(w*(d-2))\n\tc = (a - atand(tand(b)/cosd(23.44))) / 180\n\tET = 720*(c - round(c))\n\tsolarTime = 24*(d - floor(d)) + longitude*24/360 + ET/60\n\tt_h = 15*(solarTime - 12) # [degrees] hour angle\n\tdelta = -asind(sind(23.44)*cosd(b))\n\tslat, clat = sind(latitude), cosd(latitude)\n\tsdel, cdel = sind(delta), cosd(delta)\n\tczen = slat*sdel + clat*cdel*cosd(t_h)\n\tzenith = acosd(czen) # [degrees] zenith\n\n\t# azimuth [0, 180], absolute value measured from due south, so east = west = 90,\n\t# south = 0, north = 180\n\tcos_phi = (czen*slat - sdel) / (sind(zenith)*clat) # cosine(azimuth)\n\tphi_south = acosd(clamp(cos_phi,-1,1))\n\t#phi_south = acosd(cos_phi);\n\n\t# azimuth [0, 360], measured clockwise from due north,\n\t# so east = 90, south = 180, and west = 270 degrees\n\tazimuth = 180 + sign(t_h)*phi_south # Shift domain to 0-360 deg\n\n\t#angles = [theta, phi]; # [degrees] zenith, azimuth\n\treturn zenith, azimuth, solarTime, delta\nend\n\n\n\n# Splits the DateTime into (year, month, day) (as integers) and the hour (as a floating point)\nfunction splitdatetime(datetime::DateTime)\n\t# date = floor(datetime, Dates.Day)\n\ty, m, d = Dates.yearmonthday(datetime)\n\treturn y, m, d, (datetime - DateTime(y,m,d)).value/1000/3600\nend\n\n# time correction term, difference between Terrestrial Time and Universal Time, see Grena (2012) section 2.1.\n# Conversion to TT is necessary since UT follows the rotation of the earth, which is not uniform.\n# t [days] days from January 1, 2060 (in UT)\n# returns Δτ [seconds]\ndifferenceTTUT(t) = 96.4 + 0.00158*t\n\n# Calculate time variable needed for Grena (2012) algorithms, see section 3.1.\n# The time t is the input DateTime expressed as days from January 1, 2060 (in UT).\n# returns t [days]\ncalctime(datetime::DateTime) = (datetime-DateTime(2060,1,1)).value/1000/3600/24\n\n# Same result as above, but this is the function in Grena's paper. The Julia version is faster.\nfunction calctime_grena(datetime::DateTime)\n\ty, m, d, h = splitdatetime(datetime)\n\tif m <= 2\n\t\tm += 12\n\t\ty -= 1\n\tend\n\treturn trunc(365.25*(y-2000)) + trunc(30.6001*(m+1)) - trunc(0.01*y) + d + 0.0416667*h - 21958\nend\n\n# Full version of algorithm 1 of Grena (2012), see section 3.2.\n# Calculate the position of the sun as (zenith,azimuth) in radians for a location\n# on earth given as (latitude,longitude) in degrees. The DateTime should be given\n# as Universal Time, e.g. UTC. \nfunction solarposition_grena1(datetime::DateTime, latitude, longitude)\n\tω = 0.017202786 # [1/day]\n\tt = calctime(datetime)\n\tt_e = t + 1.1574e-5 * differenceTTUT(t)\n\ts1, c1 = sin(ω*t_e), cos(ω*t_e)\n\ts2, c2 = 2*s1*c1, (c1+s1)*(c1-s1)\n\tα = mod(-1.38880 + 1.72027920e-2*t_e + 3.199e-2*s1 - 2.65e-3*c1 + 4.050e-2*s2 + 1.525e-2*c2, 2π)\n\tδ = 6.57e-3 + 7.347e-2*s1 - 3.9919e-1*c1 + 7.3e-4*s2 - 6.60e-3*c2\n\tH = mod(1.75283 + 6.3003881*t + deg2rad(longitude) - α + π, 2π) - π\n\tsϕ, cϕ = sind(latitude), cosd(latitude)\n\tsδ, cδ = sin(δ), cos(δ)\n\tsH, cH = sin(H), cos(H)\n\tse0 = sϕ*sδ + cϕ*cδ*cH\n\tep = asin(se0) - 4.26e-5*sqrt(1-se0^2) #cos(e0)\n\tazimuth = atan(sH, cH*sϕ - sδ*cϕ/cδ)\t#azimuth = 0 towards south and positive direction towards west\n\tzenith = π/2 - ep\n\treturn zenith, azimuth\t\t\t\t# radians\n\t# return zenith, azimuth, δ, H\t\t# radians\n\t# return rad2deg(zenith), rad2deg(mod(azimuth+π,2π)), rad2deg(H)/15+12, rad2deg(δ) # degrees, same azimuth origin as solarposition0\nend\n\n# First half of algorithm 1 of Grena (2012), see section 3.2.\n# Calculate the position of the sun as (declination, hour angle) in radians for a location\n# on earth given by its longitude in degrees. The DateTime should be given\n# as Universal Time, e.g. UTC. \nfunction solarposition(datetime::DateTime, longitude)\n\tω = 0.017202786 # [1/day]\n\tt = calctime(datetime)\n\tt_e = t + 1.1574e-5 * differenceTTUT(t)\n\ts1, c1 = sin(ω*t_e), cos(ω*t_e)\n\ts2, c2 = 2*s1*c1, (c1+s1)*(c1-s1)\n\tα = mod(-1.38880 + 1.72027920e-2*t_e + 3.199e-2*s1 - 2.65e-3*c1 + 4.050e-2*s2 + 1.525e-2*c2, 2π)\n\tδ = 6.57e-3 + 7.347e-2*s1 - 3.9919e-1*c1 + 7.3e-4*s2 - 6.60e-3*c2\n\tH = mod(1.75283 + 6.3003881*t + deg2rad(longitude) - α + π, 2π) - π\n\treturn δ, H\nend\n\n# Full version of algorithm 1 of Grena (2012), see section 3.2.\n# Calculate the position of the sun as (zenith, azimuth) in degrees for a location\n# on earth given as (latitude,longitude) in degrees. The DateTime should be given\n# as Universal Time, e.g. UTC. \nfunction solarposition(datetime::DateTime, latitude, longitude)\n\tδ, H = solarposition(datetime, longitude)\n\tzenith, azimuth = zenith_azimuth(latitude, sines_and_cosines(δ, H)...)\n\treturn rad2deg(zenith), rad2deg(azimuth)\nend\n\nsines_and_cosines(δ, H) = sin(δ), cos(δ), sin(H), cos(H)\n\nfunction zenith_azimuth(latitude, sδ, cδ, sH, cH)\n\tsϕ, cϕ = sind(latitude), cosd(latitude)\n\tse0 = sϕ*sδ + cϕ*cδ*cH\n\tazimuth = atan(sH, cH*sϕ - sδ*cϕ/cδ)\t# azimuth = 0 towards south and positive direction towards west\n\tzenith = π/2 - asin(se0) + 4.26e-5*sqrt(1-se0^2) # sqrt(1-se0^2) = cos(e0), but slightly faster\n\treturn zenith, azimuth\t\t# radians\nend\n\nfunction zenith(latitude, sδ, cδ, sH, cH)\n\tsϕ, cϕ = sind(latitude), cosd(latitude)\n\tse0 = sϕ*sδ + cϕ*cδ*cH\n\treturn π/2 - asin(se0) + 4.26e-5*sqrt(1-se0^2) # sqrt(1-se0^2) = cos(e0), but slightly faster\nend\n\nconst solarconstant = 1361 # W/m2\n\n# Annual variation of solar insolation outside the atmosphere (W/m2):\n# https://www.itacanet.org/the-sun-as-a-source-of-energy/part-2-solar-energy-reaching-the-earths-surface/#2.1.-The-Solar-Constant\nsolarinsolation(dt::DateTime) = solarconstant * (1 + 0.034*cos(2*π*(dt - DateTime(year(dt))).value/1000/3600/24/365.25))\n\n# dt = DateTime(2019,4,15,13,46)\n# δ, H = solarposition(dt, 12)\t# return rad2deg(zenith), rad2deg(mod(azimuth+π,2π)), rad2deg(H)/15+12, rad2deg(δ)\n\n# pos = sines_and_cosines(δ, H)\n# zen = zenith(58, pos...)\n\n", "meta": {"hexsha": "a7782c47fcb9be3b114cf0f0e62b0ce6e2c8d5a6", "size": 10016, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/solarposition.jl", "max_stars_repo_name": "henrikhodel/GlobalEnergyGIS", "max_stars_repo_head_hexsha": "2dad081ff3565a551d03f2ef31c67413f545a5e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/solarposition.jl", "max_issues_repo_name": "henrikhodel/GlobalEnergyGIS", "max_issues_repo_head_hexsha": "2dad081ff3565a551d03f2ef31c67413f545a5e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/solarposition.jl", "max_forks_repo_name": "henrikhodel/GlobalEnergyGIS", "max_forks_repo_head_hexsha": "2dad081ff3565a551d03f2ef31c67413f545a5e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.3185840708, "max_line_length": 132, "alphanum_fraction": 0.7023761981, "num_tokens": 3428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109784205502, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.8115680567852928}} {"text": "using StatsBase, Distributions, Plots; pyplot()\n\nfunction prn(lambda)\n k, p = 0, 1\n while p > MathConstants.e^(-lambda)\n k += 1\n p *= rand()\n end\n return k-1\nend\n\nxGrid, lambda, N = 0:16, 5.5, 10^6\n\npDist = Poisson(lambda)\nbPmf = pdf.(pDist,xGrid)\ndata = counts([prn(lambda) for _ in 1:N],xGrid)/N\n\nplot( xGrid, data, \n\tline=:stem, marker=:circle, \n\tc=:blue, ms=10, msw=0, lw=4, label=\"MC estimate\")\nplot!( xGrid, bPmf, line=:stem, \n\tmarker=:xcross, c=:red, ms=6, msw=0, lw=2, label=\"PMF\",\n\tylims=(0,0.2), xlabel=\"x\", ylabel=\"Probability of x events\")", "meta": {"hexsha": "f087d55e0d4fa942045c0ceabc9b3bf9121815f9", "size": 577, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "3_chapter/poisson.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "3_chapter/poisson.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "3_chapter/poisson.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 25.0869565217, "max_line_length": 61, "alphanum_fraction": 0.6135181976, "num_tokens": 223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741254760638, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.8115481917011729}} {"text": "function identical_matrix(n::Integer)\n ret = zeros(n, n)\n for itr1 in 1 : n\n ret[itr1, itr1] = 1\n end\n return ret\nend\n\nfunction exchange_row!(mat::Matrix, a::Integer, b::Integer)\n # if $a$ or $b$ are out of bound, do nothing\n if a > size(mat, 1) || b > size(mat, 1)\n return mat\n end\n # exchange row $a$ and row $b$\n for itr1 in 1 : size(mat, 2)\n mat[a, itr1], mat[b, itr1] = mat[b, itr1], mat[a, itr1]\n end\n return mat\nend\n\nfunction similarity_transformation!(\n mat::Matrix, a::Integer, b::Integer)\n # if $a$ or $b$ are out of bound, do nothing\n if a > size(mat, 1) || b > size(mat, 1)\n return mat\n end\n # taking advantage of the matrix, the transformation\n # is just exchanging part of the row $a$ and row $b$\n for itr1 in 1 : (min(a, b) - 1)\n mat[a, itr1], mat[b, itr1] = mat[b, itr1], mat[a, itr1]\n end\n return mat\nend\n\nfunction plu(mat::Matrix)\n # make a copy of the original matrix, which will finally become $U$\n U = float(copy(mat))\n # # U = copy(mat)\n # it's assumed that the matrix has $m$ rows and $n$ columns\n m, n = size(U)\n # initialize two identical matrices as $P$ and $L$\n P = identical_matrix(m)\n L = identical_matrix(m)\n # $i$ and $j$ are used to represent iterators of row and column,\n # respectively\n i = j = 1\n while i <= m && j <= n\n # find the entry with largest absolute value\n imax, vmax = 0.0, 0.0\n for itr1 in i : m\n if vmax < abs(U[itr1, j])\n imax, vmax = itr1, abs(U[itr1, j])\n end\n end\n (vmax > 0) ? (k = imax) : (j += 1; continue)\n # left multiply $U$ and $P$ with a permutation matrix\n if k != i\n exchange_row!(U, i, k)\n exchange_row!(P, i, k)\n end\n # left and right multiply $L$ with the same matrix\n similarity_transformation!(L, i, k)\n # `forward elimination'\n for itr1 in (i + 1) : m\n scaler = U[itr1, j] / U[i, j]\n for itr2 in j : n\n U[itr1, itr2] -= U[i, itr2] * scaler\n end\n # right multiply $L$ with an elimination matrix\n L[itr1, i] = scaler\n end\n i += 1\n j += 1\n end\n return P, L, U\nend", "meta": {"hexsha": "74958734cd446d48782150a0c451ea67e45700c1", "size": 2303, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "linear-algebra/plu.jl", "max_stars_repo_name": "Shimushushushu/Etude-Rhapsody", "max_stars_repo_head_hexsha": "cdca63ca92a44f0f31e716cf4acd3e0de17c9181", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linear-algebra/plu.jl", "max_issues_repo_name": "Shimushushushu/Etude-Rhapsody", "max_issues_repo_head_hexsha": "cdca63ca92a44f0f31e716cf4acd3e0de17c9181", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear-algebra/plu.jl", "max_forks_repo_name": "Shimushushushu/Etude-Rhapsody", "max_forks_repo_head_hexsha": "cdca63ca92a44f0f31e716cf4acd3e0de17c9181", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3026315789, "max_line_length": 71, "alphanum_fraction": 0.5327833261, "num_tokens": 727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133481428691, "lm_q2_score": 0.8633916117313211, "lm_q1q2_score": 0.811513300540854}} {"text": "using ThreeBodyProblem\nusing DifferentialEquations\nusing Plots\nusing LinearAlgebra\n# using ForwardDiff\n\n# The first step is to define the system. ThreeBodyProblem.jl has built-in functions for common systems like Sun/Jupiter.\nsys = sun_jupiter()\n\n## There's even a recipe to plot the system for us!\nplot(sys)\n\n## We can see the Lagrange Points, but where are the Sun and Jupiter? Turns out that the distance between them is so much larger than the radius of either one that it makes it hard to see them on a truly scaled picture. Let's scale the Sun and Jupiter to make them visible.\nplot(sys, scaled = true)\n\n## That's better! Now let's compute the L1 and L2 Lagrange points of our system\n\nL1, L2 = computeLpts(sys)\n# Declare state vectors for L1 and L2 (with zero velocity)\nrv1 = [L1; zeros(3)] # state at Lagrange point L1 (zero velocity added on)\nrv2 = [L2; zeros(3)] # state at Lagrange point L2\n\n## The Lagrange points are equilibrium points in our dynamics. This means that an object placed there perfectly will stay there forever. But, Lagrange points L1, L2, and L3 are unstable, meaning if you perturb the object slightly, it may fall away. This is how we will generate the invariant manifolds.\n## We first need to linearize the dynamics about these Lagrange points to determine which directions are stable and unstable\n\nΦ₀ = I(6) # The initial State Transition Matrix (STM)\nw₀ = vcat(rv1,reshape(Φ₀,36,1)) # Augmented state with state and STM\n# Set up the ODE problem\ntspan = (0.,1.)\nprob = ODEProblem(CR3BPstm!,w₀,tspan,sys)\nsol = solve(prob, reltol=1e-6)\nΦₜ = Matrix(reshape(sol.u[end][7:42],6,6))\n\n# last time step should match very closely with rv1\nrvₜ = sol.u[end][1:6]\nerr = norm(rv1 - rvₜ)\n\n# Compute the eigenvectors of the Monodromy Matrix\nΛ,V = eigen(Φₜ,sortby=isreal) # Λ is vector of eigenvalues, V is matrix of eigenvectors\nYw = real(V[:,findall(isreal, Λ)]) # Eigenvectors corresponding to real eigenvalues\nΛ = Λ[findall(isreal, Λ)] # Purely real eigenvalues (have 0.0 imaginary component)\nYws = Yw[:,findmin(real(Λ))[2]] # Eigenvector associated with stable eigenvalue λ < 1\nYwu = Yw[:,findmax(real(Λ))[2]] # Eigenvector associated with unstable eigenvalue λ > 1\n\n## We perturb our states in the stable and unstable directions\nα = 1e-6\n\n# L1 points\nrv1up = rv1 + α*Ywu # unstable manifold + side\nrv1un = rv1 - α*Ywu # unstable manifold - side\nrv1sp = rv1 + α*Yws # stable manifold + side\nrv1sn = rv1 - α*Yws # stable manifold - side\n\n\n# Integrate trajectories for 2 Jupiter periods\ntf = 2*2π\ntspan_forward = (0.,tf) # make sure to add decimal points so tspan contains floating point values, not integers\ntspan_back = (0.,-tf)\nmyreltol = 1e-12\n\n# Set up the ODE Problems\nprob1up = ODEProblem(CR3BPdynamics!,rv1up,tspan_forward,sys) # Unstable positive\nprob1un = ODEProblem(CR3BPdynamics!,rv1un,tspan_forward,sys) # Unstable negative\nprob1sp = ODEProblem(CR3BPdynamics!,rv1sp,tspan_back,sys) # Stable positive\nprob1sn = ODEProblem(CR3BPdynamics!,rv1sn,tspan_back,sys) # Stable negative\n\n# Solutions to the ODEs\nsol1up = solve(prob1up, reltol=myreltol)\nsol1un = solve(prob1un, reltol=myreltol)\nsol1sp = solve(prob1sp, reltol=myreltol)\nsol1sn = solve(prob1sn, reltol=myreltol)\n\nplot(sys,scaled=true)\nplot!(sol1up,vars=(1,2),label=\"Wu+\",linecolor=:red)\nplot!(sol1un,vars=(1,2),label=\"Wu-\",linecolor=:magenta)\nplot!(sol1sp,vars=(1,2),label=\"Ws+\",linecolor=:blue)\nplot!(sol1sn,vars=(1,2),label=\"Ws-\",linecolor=:cyan)\nplot!(aspect_ratio=1,ylims=[-1,1],xlims=[-0.6,1.3],legend=:topleft,flip=false)\n\n## We can see two strands moving in towards the sun, but the rest is a jumbled mess. Let's zoom in to see what's going on. Also, I need to make sure things are scaled correctly, or Jupiter will look way too big.\nplot(sys)\nplot!(sol1up,vars=(1,2),label=\"Wu+\",linecolor=:red)\nplot!(sol1un,vars=(1,2),label=\"Wu-\",linecolor=:magenta)\nplot!(sol1sp,vars=(1,2),label=\"Ws+\",linecolor=:blue)\nplot!(sol1sn,vars=(1,2),label=\"Ws-\",linecolor=:cyan)\nplot!(aspect_ratio=1,ylims=[-0.04,0.04],xlims=[0.93,1.06],legend=:outerright,flip=false)\n\n# L2 points\nrv2up = rv2 + α*Ywu # unstable manifold + side\nrv2un = rv2 - α*Ywu # unstable manifold - side\nrv2sp = rv2 + α*Yws # stable manifold + side\nrv2sn = rv2 - α*Yws # stable manifold - side\n\n## Now we look at the L2 point manifolds\nprob2up = ODEProblem(CR3BPdynamics!,rv2up,tspan_forward,sys) # Unstable positive\nprob2un = ODEProblem(CR3BPdynamics!,rv2un,tspan_forward,sys) # Unstable negative\nprob2sp = ODEProblem(CR3BPdynamics!,rv2sp,tspan_back,sys) # Stable positive\nprob2sn = ODEProblem(CR3BPdynamics!,rv2sn,tspan_back,sys) # Stable negative\n\nsol2up = solve(prob2up, reltol=1e-6)\nsol2un = solve(prob2un, reltol=1e-6)\nsol2sp = solve(prob2sp, reltol=1e-6)\nsol2sn = solve(prob2sn, reltol=1e-6)\n\nplot(sys, scaled=true)\nplot!(sol2up,vars=(1,2),label=\"Wu+\",linecolor=:red)\nplot!(sol2un,vars=(1,2),label=\"Wu-\",linecolor=:magenta)\nplot!(sol2sp,vars=(1,2),label=\"Ws+\",linecolor=:blue)\nplot!(sol2sn,vars=(1,2),label=\"Ws-\",linecolor=:cyan)\nplot!(aspect_ratio=1,ylims=[-1.0,1.0],xlims=[-0.3,1.5],legend=:topright,flip=false)\n## This time there are two strands moving out away from the Sun, along with another jumble around Jupiter. Let's zoom in again to take a look.\nplot(sys)\nplot!(sol2up,vars=(1,2),label=\"Wu+\",linecolor=:red)\nplot!(sol2un,vars=(1,2),label=\"Wu-\",linecolor=:magenta)\nplot!(sol2sp,vars=(1,2),label=\"Ws+\",linecolor=:blue)\nplot!(sol2sn,vars=(1,2),label=\"Ws-\",linecolor=:cyan)\nplot!(aspect_ratio=1,ylims=[-0.04,0.04],xlims=[0.93,1.07],legend=:outerright,flip=false)\n", "meta": {"hexsha": "d4cf80dfb6795d587b1e517743c99c286a4e4e9f", "size": 5521, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/5_LagrangePointManifolds.jl", "max_stars_repo_name": "jared711/ThreeBodyProblem_old.jl", "max_stars_repo_head_hexsha": "492c1fc34aa5d0a7b003ce224429a634230438d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-07-28T01:21:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-28T22:34:55.000Z", "max_issues_repo_path": "example/5_LagrangePointManifolds.jl", "max_issues_repo_name": "jared711/ThreeBodyProblem_old.jl", "max_issues_repo_head_hexsha": "492c1fc34aa5d0a7b003ce224429a634230438d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/5_LagrangePointManifolds.jl", "max_forks_repo_name": "jared711/ThreeBodyProblem_old.jl", "max_forks_repo_head_hexsha": "492c1fc34aa5d0a7b003ce224429a634230438d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.7881355932, "max_line_length": 302, "alphanum_fraction": 0.738815432, "num_tokens": 1838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133430934989, "lm_q2_score": 0.8633916152464017, "lm_q1q2_score": 0.8115132994851414}} {"text": "################################################################################\n#\n# The LLL-Reduction Algorithm\n#\n# Implementration of algorithm described in :\n# Lenstra, A.K., Lenstra, H.W. & Lovász, L. Math. Ann. (1982)\n# 261: 515. https://doi.org/10.1007/BF01457454\n#\n################################################################################\n\n\"\"\"\n lll(b₀::AbstractMatrix{Float64})::AbstractMatrix{Float64}\n\nPerforms Lenstra-Lenstra-Lovasv reduction on the n vectors in b₀.\n\nParameters\n----------\n- b₀ : vector of n vectors of n Float64\n\nReturns\n-------\n- The LLL reduction of the vectors in `b₀`\n\"\"\"\nfunction lll(b₀::Vector{Vector{Float64}})::Vector{Vector{Float64}}\n b = deepcopy(b₀) # preserve argument by working on a copy\n n = length(b)\n\n # initialize mu and B with zeros\n μ = zeros(n,n)\n B = zeros(n)\n\n # function (*) of page 521\n function ☼(l)\n abs(μ[k,l]) < 0.5 && return\n r = round(μ[k,l])\n b[k] .-= r * b[l]\n μ[k,1:l-1] .-= r * μ[l,1:l-1]\n μ[k,l] -= r\n end\n\n b₂ = similar(b)\n for t in 1:n\n b₂[t] = copy(b[t])\n for j in 1:t-1\n μ[t,j] = dot(b[t], b₂[j]) / B[j]\n b₂[t] .-= μ[t,j] * b₂[j]\n end\n B[t] = dot(b₂[t], b₂[t])\n end\n\n k = 2\n while k <= n\n ☼(k-1)\n if B[k] >= (0.75 - μ[k,k-1]^2) * B[k-1]\n foreach(☼, k-2:-1:1)\n k += 1\n else\n μₒ = μ[k,k-1]\n Bₒ = B[k] + μₒ^2 * B[k-1]\n μ[k,k-1] = μₒ * B[k-1] / Bₒ\n B[k] = B[k] * B[k-1] / Bₒ\n B[k-1] = Bₒ\n\n bₒ = b[k] ; b[k] = b[k-1] ; b[k-1] = bₒ\n for j in 1:k-2\n tmp = μ[k,j] ; μ[k,j] = μ[k-1,j] ; μ[k-1,j] = tmp\n end\n for t in k+1:n\n tmp = μ[k,k-1] - μₒ * μ[t,k]\n μ[t,k-1] = μ[t,k] + μ[k,k-1] * tmp\n μ[t,k] = tmp\n end\n\n k = max(2, k-1)\n end\n end\n b\nend\n", "meta": {"hexsha": "305d473524abea64209bd87081a39f9969b8cd07", "size": 1985, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lll.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/RiemannTheta.jl-803aa692-84f0-5eed-9cc1-fbb46710dded", "max_stars_repo_head_hexsha": "af371a543767493c495f535ada2ce896a27644e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lll.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/RiemannTheta.jl-803aa692-84f0-5eed-9cc1-fbb46710dded", "max_issues_repo_head_hexsha": "af371a543767493c495f535ada2ce896a27644e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lll.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/RiemannTheta.jl-803aa692-84f0-5eed-9cc1-fbb46710dded", "max_forks_repo_head_hexsha": "af371a543767493c495f535ada2ce896a27644e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1265822785, "max_line_length": 80, "alphanum_fraction": 0.3964735516, "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133430934989, "lm_q2_score": 0.8633916152464016, "lm_q1q2_score": 0.8115132994851413}} {"text": "### A Pluto.jl notebook ###\n# v0.17.7\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 64bba790-89ad-11ec-272d-af9bb791e63d\nbegin\n\tusing Turing, MCMCChains\n\tusing Distributions, StatsPlots, Random\nend\n\n# ╔═╡ dc1177eb-66ec-4b82-ad0d-5e76539faa24\nmd\"\"\"\n### Gaussian Mixture Model\n\nIn this post we see an example of gaussian mixture model, which is a clustering model of unsupervised learning.\nAs stated, gaussian mixture model has several normal distributions. The aim of this model is to find optimal value of parameters(μ, Σ, π) that describe clusters.\n\nLet's say we have n data and assumes K clusters.\n- θ parameters\n- Z latent variables(hidden variables)\n- X data\n\nWhat are the parameters here?\n- θ = {μ(μ₁ . . . μₖ), Σ(Σ₁ . . . Σₖ), π(π₁ . . . πₖ)}\n- μₖ is mean of kᵗʰ cluster\n- Σₖ is covariance matrix of kᵗʰ cluster\n- πₖ represent for probability of selecting kᵗʰ cluster\n\nWe assume that we have n data.\n- {(X₁, Z₁) . . . (Xₙ, Zₙ)}\n- Z can be interpreted as one-hot vector with only 1 in kᵗʰ position and 0 others.\n\n\"\"\"\n\n# ╔═╡ fc380f54-24c7-440a-9cfd-04d3a8ea3184\n# Set a random seed.\nRandom.seed!(3)\n\n# ╔═╡ 38643e87-ee2d-4aae-83f7-abc6199f54aa\n# Construct 30 data points for each cluster.\nN = 30\n\n# ╔═╡ b7acb16e-b6d1-4e53-80c4-0819259a6130\n# Parameters for each cluster, we assume that each cluster is Gaussian distributed in the example.\nμs = [4.0, 1.0]\n\n# ╔═╡ 24553bda-3ce4-4156-bf8a-0a1fe3df2afb\n# Construct the data points.\nx = mapreduce(c -> rand(MvNormal([μs[c], μs[c]], 1.), N), hcat, 1:2)\n\n# ╔═╡ a0871b5d-02f4-4f16-9bcd-2e85264b0f41\ngr()\n\n# ╔═╡ b5f72bd8-97b7-435f-8940-950af86aed91\n# Visualization.\nscatter(x[1,:], x[2,:], legend = false, title = \"Dataset\", fmt=\"png\")\n\n# ╔═╡ 00f15e65-5133-4453-88af-c9479c8e3f9e\n@model function GaussianMixtureModel(x)\n\n D, N = size(x)\n\n # Draw the parameters for cluster 1.\n μ1 ~ Normal()\n\n # Draw the parameters for cluster 2.\n μ2 ~ Normal()\n\n μ = [μ1, μ2]\n\t\t\n # draw the weights for the K clusters from a Dirichlet distribution.\n\n α = 1.0\n\tπ ~ Dirichlet(D, α)\n\n # Draw assignments for each datum and generate it from a multivariate normal.\n k = Vector{Int}(undef, N)\n for i in 1:N\n k[i] ~ Categorical(π)\n x[:,i] ~ MvNormal([μ[k[i]], μ[k[i]]], 1.)\n end\n return k\nend;\n\n\n# ╔═╡ a45b70a7-acb0-48f1-8ae5-31c63992cbfa\ngmm_model = GaussianMixtureModel(x);\n\n# ╔═╡ 7fe105ae-7d5c-4dd8-8104-fdaa9a18ea25\ngmm_sampler = Gibbs(PG(100, :k), HMC(0.05, 10, :μ1, :μ2))\n\n# ╔═╡ c30df2ab-45c2-42c3-9e72-2c4759b9b640\ntchain = sample(gmm_model, gmm_sampler, MCMCThreads(), 200, 3)\n\n# ╔═╡ 9f18a980-5277-4419-912b-e261451427b0\nsummarystats(tchain)\n\n# ╔═╡ c726de5c-e241-4fa5-984d-c4184a626e52\nnames(tchain)\n\n# ╔═╡ 166d94ed-1e70-4ef6-8b78-f5b566216246\nids = findall(map(name -> occursin(\"μ\", string(name)), names(tchain)))\n\n# ╔═╡ 29c24b11-fad4-4a2f-afbe-9f6afaab82f1\np = plot(tchain[:, ids, :]; legend=true, labels=[\"Mu 1\" \"Mu 2\"], colordim=:parameter)\n\n# ╔═╡ 40214128-1ed7-4b37-b19e-78fafdebbb0b\ntchain2 = tchain[:, :, 3];\n\n# ╔═╡ 2c2ea945-795a-4e0a-bc16-c49fa15bee1c\n# Helper function for plotting\nfunction predict(x, y, π, μ)\n \n return Turing.logaddexp(\n log(π[1]) + logpdf(MvNormal([μ[1], μ[1]], 1.), [x, y]),\n log(π[2]) + logpdf(MvNormal([μ[2], μ[2]], 1.), [x, y])\n )\nend\n\n# ╔═╡ 60d2ae42-7e56-418e-88a9-2ad16e84555e\n# plotting contour plot\nbegin\n\tcontour(range(-2, stop = 8), range(-2, stop = 8),\n\t (x, y) -> predict(x, y, [mean(tchain2[:\"π[1]\"]), mean(tchain2[:\"π[2]\"])], \t[mean(tchain2[:μ1]), mean(tchain2[:μ2])])\n\t)\n\tscatter!(x[1,:], x[2,:]; legend=false, title=\"Dataset\")\n\t\nend\n\n# ╔═╡ 88c6f515-b4d9-4e85-9157-2fc1e81483a2\nwireframe(range(-2, stop = 8), range(-2, stop = 8),\n\t (x, y) -> predict(x, y, [mean(tchain2[:\"π[1]\"]), mean(tchain2[:\"π[2]\"])], \t[mean(tchain2[:μ1]), mean(tchain2[:μ2])]))\n\n# ╔═╡ 63703e6a-7adb-43c3-82aa-34f5aa746017\nmean(MCMCChains.group(tchain2, :k))\n\n# ╔═╡ b81eb0e7-d3cd-49aa-ae14-b8436dc515a4\nassignments = round.(mean(MCMCChains.group(tchain2, :k)).nt.mean)\n\n# ╔═╡ 60b70f36-ffac-45c3-a3d4-78991ab57bab\nscatter(x[1,:], x[2,:]; legend=false,\n title=\"Assignments on Dataset\", zcolor=assignments)\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nDistributions = \"31c24e10-a181-5473-b8eb-7969acd0382f\"\nMCMCChains = \"c7f686f2-ff18-58e9-bc7b-31028e88f75d\"\nRandom = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\nStatsPlots = \"f3b207a7-027a-5e70-b257-86293d7955fd\"\nTuring = \"fce5fe82-541a-59a6-adf8-730c64b5f9a0\"\n\n[compat]\nDistributions = \"~0.25.47\"\nMCMCChains = \"~5.0.3\"\nStatsPlots = \"~0.14.33\"\nTuring = \"~0.20.1\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\n[[AbstractFFTs]]\ndeps = [\"ChainRulesCore\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"6f1d9bc1c08f9f4a8fa92e3ea3cb50153a1b40d4\"\nuuid = \"621f4979-c628-5d54-868e-fcf4e3e8185c\"\nversion = \"1.1.0\"\n\n[[AbstractMCMC]]\ndeps = [\"BangBang\", \"ConsoleProgressMonitor\", \"Distributed\", \"Logging\", \"LoggingExtras\", \"ProgressLogging\", \"Random\", \"StatsBase\", \"TerminalLoggers\", \"Transducers\"]\ngit-tree-sha1 = \"db0a7ff3fbd987055c43b4e12d2fa30aaae8749c\"\nuuid = \"80f14c24-f653-4e6a-9b94-39d6b0f70001\"\nversion = \"3.2.1\"\n\n[[AbstractPPL]]\ndeps = [\"AbstractMCMC\", \"DensityInterface\", \"Setfield\"]\ngit-tree-sha1 = \"ca54027a17ca3133b36166191b5faa8a404e92d3\"\nuuid = \"7a57a42e-76ec-4ea3-a279-07e840d6d9cf\"\nversion = \"0.4.0\"\n\n[[AbstractTrees]]\ngit-tree-sha1 = \"03e0550477d86222521d254b741d470ba17ea0b5\"\nuuid = \"1520ce14-60c1-5f80-bbc7-55ef81b5835c\"\nversion = \"0.3.4\"\n\n[[Adapt]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"af92965fb30777147966f58acb05da51c5616b5f\"\nuuid = \"79e6a3ab-5dfb-504d-930d-738a2a938a0e\"\nversion = \"3.3.3\"\n\n[[AdvancedHMC]]\ndeps = [\"AbstractMCMC\", \"ArgCheck\", \"DocStringExtensions\", \"InplaceOps\", \"LinearAlgebra\", \"ProgressMeter\", \"Random\", \"Requires\", \"Setfield\", \"Statistics\", \"StatsBase\", \"StatsFuns\", \"UnPack\"]\ngit-tree-sha1 = \"189473a73d664fe2496675775b6c8a732b8dfe26\"\nuuid = \"0bf59076-c3b1-5ca4-86bd-e02cd72cde3d\"\nversion = \"0.3.3\"\n\n[[AdvancedMH]]\ndeps = [\"AbstractMCMC\", \"Distributions\", \"Random\", \"Requires\"]\ngit-tree-sha1 = \"8ad8bfddf8bb627d689ecb91599c349cbf15e971\"\nuuid = \"5b7e9947-ddc0-4b3f-9b55-0d8042f74170\"\nversion = \"0.6.6\"\n\n[[AdvancedPS]]\ndeps = [\"AbstractMCMC\", \"Distributions\", \"Libtask\", \"Random\", \"StatsFuns\"]\ngit-tree-sha1 = \"59c47e9525d5a807a950d8b79b5d6e60b2f6de82\"\nuuid = \"576499cb-2369-40b2-a588-c64705576edc\"\nversion = \"0.3.3\"\n\n[[AdvancedVI]]\ndeps = [\"Bijectors\", \"Distributions\", \"DistributionsAD\", \"DocStringExtensions\", \"ForwardDiff\", \"LinearAlgebra\", \"ProgressMeter\", \"Random\", \"Requires\", \"StatsBase\", \"StatsFuns\", \"Tracker\"]\ngit-tree-sha1 = \"130d6b17a3a9d420d9a6b37412cae03ffd6a64ff\"\nuuid = \"b5ca4192-6429-45e5-a2d9-87aec30a685c\"\nversion = \"0.1.3\"\n\n[[ArgCheck]]\ngit-tree-sha1 = \"a3a402a35a2f7e0b87828ccabbd5ebfbebe356b4\"\nuuid = \"dce04be8-c92d-5529-be00-80e4d2c0e197\"\nversion = \"2.3.0\"\n\n[[ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[Arpack]]\ndeps = [\"Arpack_jll\", \"Libdl\", \"LinearAlgebra\", \"Logging\"]\ngit-tree-sha1 = \"91ca22c4b8437da89b030f08d71db55a379ce958\"\nuuid = \"7d9fca2a-8960-54d3-9f78-7d1dccf2cb97\"\nversion = \"0.5.3\"\n\n[[Arpack_jll]]\ndeps = [\"Libdl\", \"OpenBLAS_jll\", \"Pkg\"]\ngit-tree-sha1 = \"e214a9b9bd1b4e1b4f15b22c0994862b66af7ff7\"\nuuid = \"68821587-b530-5797-8361-c406ea357684\"\nversion = \"3.5.0+3\"\n\n[[ArrayInterface]]\ndeps = [\"Compat\", \"IfElse\", \"LinearAlgebra\", \"Requires\", \"SparseArrays\", \"Static\"]\ngit-tree-sha1 = \"745233d77146ad221629590b6d82fe7f1ddb478f\"\nuuid = \"4fba245c-0d91-5ea0-9b3e-6abc04ee57a9\"\nversion = \"4.0.3\"\n\n[[Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[AxisAlgorithms]]\ndeps = [\"LinearAlgebra\", \"Random\", \"SparseArrays\", \"WoodburyMatrices\"]\ngit-tree-sha1 = \"66771c8d21c8ff5e3a93379480a2307ac36863f7\"\nuuid = \"13072b0f-2c55-5437-9ae7-d433b7a33950\"\nversion = \"1.0.1\"\n\n[[AxisArrays]]\ndeps = [\"Dates\", \"IntervalSets\", \"IterTools\", \"RangeArrays\"]\ngit-tree-sha1 = \"d127d5e4d86c7680b20c35d40b503c74b9a39b5e\"\nuuid = \"39de3d68-74b9-583c-8d2d-e117c070f3a9\"\nversion = \"0.4.4\"\n\n[[BangBang]]\ndeps = [\"Compat\", \"ConstructionBase\", \"Future\", \"InitialValues\", \"LinearAlgebra\", \"Requires\", \"Setfield\", \"Tables\", \"ZygoteRules\"]\ngit-tree-sha1 = \"d648adb5e01b77358511fb95ea2e4d384109fac9\"\nuuid = \"198e06fe-97b7-11e9-32a5-e1d131e6ad66\"\nversion = \"0.3.35\"\n\n[[Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[Baselet]]\ngit-tree-sha1 = \"aebf55e6d7795e02ca500a689d326ac979aaf89e\"\nuuid = \"9718e550-a3fa-408a-8086-8db961cd8217\"\nversion = \"0.1.1\"\n\n[[Bijectors]]\ndeps = [\"ArgCheck\", \"ChainRulesCore\", \"Compat\", \"Distributions\", \"Functors\", \"IrrationalConstants\", \"LinearAlgebra\", \"LogExpFunctions\", \"MappedArrays\", \"Random\", \"Reexport\", \"Requires\", \"Roots\", \"SparseArrays\", \"Statistics\"]\ngit-tree-sha1 = \"369af32fcb9be65d496dc43ad0bb713705d4e859\"\nuuid = \"76274a88-744f-5084-9051-94815aaf08c4\"\nversion = \"0.9.11\"\n\n[[Bzip2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"19a35467a82e236ff51bc17a3a44b69ef35185a2\"\nuuid = \"6e34b625-4abd-537c-b88f-471c36dfa7a0\"\nversion = \"1.0.8+0\"\n\n[[Cairo]]\ndeps = [\"Cairo_jll\", \"Colors\", \"Glib_jll\", \"Graphics\", \"Libdl\", \"Pango_jll\"]\ngit-tree-sha1 = \"d0b3f8b4ad16cb0a2988c6788646a5e6a17b6b1b\"\nuuid = \"159f3aea-2a34-519c-b102-8c37f9878175\"\nversion = \"1.0.5\"\n\n[[Cairo_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"JLLWrappers\", \"LZO_jll\", \"Libdl\", \"Pixman_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"4b859a208b2397a7a623a03449e4636bdb17bcf2\"\nuuid = \"83423d85-b0ee-5818-9007-b63ccbeb887a\"\nversion = \"1.16.1+1\"\n\n[[ChainRules]]\ndeps = [\"ChainRulesCore\", \"Compat\", \"IrrationalConstants\", \"LinearAlgebra\", \"Random\", \"RealDot\", \"SparseArrays\", \"Statistics\"]\ngit-tree-sha1 = \"849d4cb467ea3ecbbd3efe68dacd36f9429b543c\"\nuuid = \"082447d4-558c-5d27-93f4-14fc19e9eca2\"\nversion = \"1.26.0\"\n\n[[ChainRulesCore]]\ndeps = [\"Compat\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"f9982ef575e19b0e5c7a98c6e75ee496c0f73a93\"\nuuid = \"d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4\"\nversion = \"1.12.0\"\n\n[[ChangesOfVariables]]\ndeps = [\"ChainRulesCore\", \"LinearAlgebra\", \"Test\"]\ngit-tree-sha1 = \"bf98fa45a0a4cee295de98d4c1462be26345b9a1\"\nuuid = \"9e997f8a-9a97-42d5-a9f1-ce6bfc15e2c0\"\nversion = \"0.1.2\"\n\n[[Clustering]]\ndeps = [\"Distances\", \"LinearAlgebra\", \"NearestNeighbors\", \"Printf\", \"SparseArrays\", \"Statistics\", \"StatsBase\"]\ngit-tree-sha1 = \"75479b7df4167267d75294d14b58244695beb2ac\"\nuuid = \"aaaa29a8-35af-508c-8bc3-b662a17a0fe5\"\nversion = \"0.14.2\"\n\n[[ColorSchemes]]\ndeps = [\"ColorTypes\", \"Colors\", \"FixedPointNumbers\", \"Luxor\", \"Random\"]\ngit-tree-sha1 = \"5b7d2a8b53c68dfdbce545e957a3b5cc4da80b01\"\nuuid = \"35d6a980-a343-548e-a6ea-1d62b119f2f4\"\nversion = \"3.17.0\"\n\n[[ColorTypes]]\ndeps = [\"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"024fe24d83e4a5bf5fc80501a314ce0d1aa35597\"\nuuid = \"3da002f7-5984-5a60-b8a6-cbb66c0b333f\"\nversion = \"0.11.0\"\n\n[[Colors]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"Reexport\"]\ngit-tree-sha1 = \"417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40\"\nuuid = \"5ae59095-9a9b-59fe-a467-6f913c188581\"\nversion = \"0.12.8\"\n\n[[Combinatorics]]\ngit-tree-sha1 = \"08c8b6831dc00bfea825826be0bc8336fc369860\"\nuuid = \"861a8166-3701-5b0c-9a16-15d98fcdc6aa\"\nversion = \"1.0.2\"\n\n[[CommonSolve]]\ngit-tree-sha1 = \"68a0743f578349ada8bc911a5cbd5a2ef6ed6d1f\"\nuuid = \"38540f10-b2f7-11e9-35d8-d573e4eb0ff2\"\nversion = \"0.2.0\"\n\n[[CommonSubexpressions]]\ndeps = [\"MacroTools\", \"Test\"]\ngit-tree-sha1 = \"7b8a93dba8af7e3b42fecabf646260105ac373f7\"\nuuid = \"bbf7d656-a473-5ed7-a52c-81e309532950\"\nversion = \"0.3.0\"\n\n[[Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"44c37b4636bc54afac5c574d2d02b625349d6582\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.41.0\"\n\n[[CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[CompositionsBase]]\ngit-tree-sha1 = \"455419f7e328a1a2493cabc6428d79e951349769\"\nuuid = \"a33af91c-f02d-484b-be07-31d278c5ca2b\"\nversion = \"0.1.1\"\n\n[[ConsoleProgressMonitor]]\ndeps = [\"Logging\", \"ProgressMeter\"]\ngit-tree-sha1 = \"3ab7b2136722890b9af903859afcf457fa3059e8\"\nuuid = \"88cd18e8-d9cc-4ea6-8889-5259c0d15c8b\"\nversion = \"0.1.2\"\n\n[[ConstructionBase]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"f74e9d5388b8620b4cee35d4c5a618dd4dc547f4\"\nuuid = \"187b0558-2788-49d3-abe0-74a17ed4e7c9\"\nversion = \"1.3.0\"\n\n[[Contour]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"9f02045d934dc030edad45944ea80dbd1f0ebea7\"\nuuid = \"d38c429a-6771-53c6-b99e-75d170b6e991\"\nversion = \"0.5.7\"\n\n[[Crayons]]\ngit-tree-sha1 = \"249fe38abf76d48563e2f4556bebd215aa317e15\"\nuuid = \"a8cc5b0e-0ffa-5ad4-8c14-923d3ee1735f\"\nversion = \"4.1.1\"\n\n[[DataAPI]]\ngit-tree-sha1 = \"cc70b17275652eb47bc9e5f81635981f13cea5c8\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.9.0\"\n\n[[DataStructures]]\ndeps = [\"Compat\", \"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"3daef5523dd2e769dad2365274f760ff5f282c7d\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.18.11\"\n\n[[DataValueInterfaces]]\ngit-tree-sha1 = \"bfc1187b79289637fa0ef6d4436ebdfe6905cbd6\"\nuuid = \"e2d170a0-9d28-54be-80f0-106bbe20a464\"\nversion = \"1.0.0\"\n\n[[DataValues]]\ndeps = [\"DataValueInterfaces\", \"Dates\"]\ngit-tree-sha1 = \"d88a19299eba280a6d062e135a43f00323ae70bf\"\nuuid = \"e7dc6d0d-1eca-5fa6-8ad6-5aecde8b7ea5\"\nversion = \"0.4.13\"\n\n[[Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[DefineSingletons]]\ngit-tree-sha1 = \"0fba8b706d0178b4dc7fd44a96a92382c9065c2c\"\nuuid = \"244e2a9f-e319-4986-a169-4d1fe445cd52\"\nversion = \"0.1.2\"\n\n[[DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[DensityInterface]]\ndeps = [\"InverseFunctions\", \"Test\"]\ngit-tree-sha1 = \"80c3e8639e3353e5d2912fb3a1916b8455e2494b\"\nuuid = \"b429d917-457f-4dbc-8f4c-0cc954292b1d\"\nversion = \"0.4.0\"\n\n[[DiffResults]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"c18e98cba888c6c25d1c3b048e4b3380ca956805\"\nuuid = \"163ba53b-c6d8-5494-b064-1a9d43ac40c5\"\nversion = \"1.0.3\"\n\n[[DiffRules]]\ndeps = [\"IrrationalConstants\", \"LogExpFunctions\", \"NaNMath\", \"Random\", \"SpecialFunctions\"]\ngit-tree-sha1 = \"84083a5136b6abf426174a58325ffd159dd6d94f\"\nuuid = \"b552c78f-8df3-52c6-915a-8e097449b14b\"\nversion = \"1.9.1\"\n\n[[Distances]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"3258d0659f812acde79e8a74b11f17ac06d0ca04\"\nuuid = \"b4f34e82-e78d-54a5-968a-f98e89d6e8f7\"\nversion = \"0.10.7\"\n\n[[Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[Distributions]]\ndeps = [\"ChainRulesCore\", \"DensityInterface\", \"FillArrays\", \"LinearAlgebra\", \"PDMats\", \"Printf\", \"QuadGK\", \"Random\", \"SparseArrays\", \"SpecialFunctions\", \"Statistics\", \"StatsBase\", \"StatsFuns\", \"Test\"]\ngit-tree-sha1 = \"d6dc7e55eb64d9d2326436df15df9c8e4d8f1cd4\"\nuuid = \"31c24e10-a181-5473-b8eb-7969acd0382f\"\nversion = \"0.25.47\"\n\n[[DistributionsAD]]\ndeps = [\"Adapt\", \"ChainRules\", \"ChainRulesCore\", \"Compat\", \"DiffRules\", \"Distributions\", \"FillArrays\", \"LinearAlgebra\", \"NaNMath\", \"PDMats\", \"Random\", \"Requires\", \"SpecialFunctions\", \"StaticArrays\", \"StatsBase\", \"StatsFuns\", \"ZygoteRules\"]\ngit-tree-sha1 = \"61805bf57113a52435a13ca0bb588daf8848784d\"\nuuid = \"ced4e74d-a319-5a8a-b0ac-84af2272839c\"\nversion = \"0.6.37\"\n\n[[DocStringExtensions]]\ndeps = [\"LibGit2\"]\ngit-tree-sha1 = \"b19534d1895d702889b219c382a6e18010797f0b\"\nuuid = \"ffbed154-4ef7-542d-bbb7-c09d3a79fcae\"\nversion = \"0.8.6\"\n\n[[Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[DynamicPPL]]\ndeps = [\"AbstractMCMC\", \"AbstractPPL\", \"BangBang\", \"Bijectors\", \"ChainRulesCore\", \"Distributions\", \"LinearAlgebra\", \"MacroTools\", \"Random\", \"Setfield\", \"Test\", \"ZygoteRules\"]\ngit-tree-sha1 = \"d732ba45e3c22fba99957fba7f4de25735a57691\"\nuuid = \"366bfd00-2699-11ea-058f-f148b4cae6d8\"\nversion = \"0.17.4\"\n\n[[EarCut_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"3f3a2501fa7236e9b911e0f7a588c657e822bb6d\"\nuuid = \"5ae413db-bbd1-5e63-b57d-d24a61df00f5\"\nversion = \"2.2.3+0\"\n\n[[EllipsisNotation]]\ndeps = [\"ArrayInterface\"]\ngit-tree-sha1 = \"d7ab55febfd0907b285fbf8dc0c73c0825d9d6aa\"\nuuid = \"da5c29d0-fa7d-589e-88eb-ea29b0a81949\"\nversion = \"1.3.0\"\n\n[[EllipticalSliceSampling]]\ndeps = [\"AbstractMCMC\", \"ArrayInterface\", \"Distributions\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"c25a7254cf745720ddf9051cd0d2792b3baaca0e\"\nuuid = \"cad2338a-1db2-11e9-3401-43bc07c9ede2\"\nversion = \"0.4.6\"\n\n[[Expat_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"ae13fcbc7ab8f16b0856729b050ef0c446aa3492\"\nuuid = \"2e619515-83b5-522b-bb60-26c02a35a201\"\nversion = \"2.4.4+0\"\n\n[[FFMPEG]]\ndeps = [\"FFMPEG_jll\"]\ngit-tree-sha1 = \"b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8\"\nuuid = \"c87230d0-a227-11e9-1b43-d7ebe4e7570a\"\nversion = \"0.4.1\"\n\n[[FFMPEG_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"JLLWrappers\", \"LAME_jll\", \"Libdl\", \"Ogg_jll\", \"OpenSSL_jll\", \"Opus_jll\", \"Pkg\", \"Zlib_jll\", \"libass_jll\", \"libfdk_aac_jll\", \"libvorbis_jll\", \"x264_jll\", \"x265_jll\"]\ngit-tree-sha1 = \"d8a578692e3077ac998b50c0217dfd67f21d1e5f\"\nuuid = \"b22a6f82-2f65-5046-a5b2-351ab43fb4e5\"\nversion = \"4.4.0+0\"\n\n[[FFTW]]\ndeps = [\"AbstractFFTs\", \"FFTW_jll\", \"LinearAlgebra\", \"MKL_jll\", \"Preferences\", \"Reexport\"]\ngit-tree-sha1 = \"463cb335fa22c4ebacfd1faba5fde14edb80d96c\"\nuuid = \"7a1cc6ca-52ef-59f5-83cd-3a7055c09341\"\nversion = \"1.4.5\"\n\n[[FFTW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c6033cc3892d0ef5bb9cd29b7f2f0331ea5184ea\"\nuuid = \"f5851436-0d7a-5f13-b9de-f02708fd171a\"\nversion = \"3.3.10+0\"\n\n[[FileIO]]\ndeps = [\"Pkg\", \"Requires\", \"UUIDs\"]\ngit-tree-sha1 = \"80ced645013a5dbdc52cf70329399c35ce007fae\"\nuuid = \"5789e2e9-d7fb-5bc7-8068-2c6fae9b9549\"\nversion = \"1.13.0\"\n\n[[FillArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"SparseArrays\", \"Statistics\"]\ngit-tree-sha1 = \"deed294cde3de20ae0b2e0355a6c4e1c6a5ceffc\"\nuuid = \"1a297f60-69ca-5386-bcde-b61e274b549b\"\nversion = \"0.12.8\"\n\n[[FixedPointNumbers]]\ndeps = [\"Statistics\"]\ngit-tree-sha1 = \"335bfdceacc84c5cdf16aadc768aa5ddfc5383cc\"\nuuid = \"53c48c17-4a7d-5ca2-90c5-79b7896eea93\"\nversion = \"0.8.4\"\n\n[[Fontconfig_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Expat_jll\", \"FreeType2_jll\", \"JLLWrappers\", \"Libdl\", \"Libuuid_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"21efd19106a55620a188615da6d3d06cd7f6ee03\"\nuuid = \"a3f928ae-7b40-5064-980b-68af3947d34b\"\nversion = \"2.13.93+0\"\n\n[[Formatting]]\ndeps = [\"Printf\"]\ngit-tree-sha1 = \"8339d61043228fdd3eb658d86c926cb282ae72a8\"\nuuid = \"59287772-0a20-5a39-b81b-1366585eb4c0\"\nversion = \"0.4.2\"\n\n[[ForwardDiff]]\ndeps = [\"CommonSubexpressions\", \"DiffResults\", \"DiffRules\", \"LinearAlgebra\", \"LogExpFunctions\", \"NaNMath\", \"Preferences\", \"Printf\", \"Random\", \"SpecialFunctions\", \"StaticArrays\"]\ngit-tree-sha1 = \"1bd6fc0c344fc0cbee1f42f8d2e7ec8253dda2d2\"\nuuid = \"f6369f11-7733-5829-9624-2563aa707210\"\nversion = \"0.10.25\"\n\n[[FreeType2_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"87eb71354d8ec1a96d4a7636bd57a7347dde3ef9\"\nuuid = \"d7e528f0-a631-5988-bf34-fe36492bcfd7\"\nversion = \"2.10.4+0\"\n\n[[FriBidi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"aa31987c2ba8704e23c6c8ba8a4f769d5d7e4f91\"\nuuid = \"559328eb-81f9-559d-9380-de523a88c83c\"\nversion = \"1.0.10+0\"\n\n[[Functors]]\ngit-tree-sha1 = \"e4768c3b7f597d5a352afa09874d16e3c3f6ead2\"\nuuid = \"d9f16b24-f501-4c13-a1f2-28368ffc5196\"\nversion = \"0.2.7\"\n\n[[Future]]\ndeps = [\"Random\"]\nuuid = \"9fa8497b-333b-5362-9e8d-4d0656e87820\"\n\n[[GLFW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"Pkg\", \"Xorg_libXcursor_jll\", \"Xorg_libXi_jll\", \"Xorg_libXinerama_jll\", \"Xorg_libXrandr_jll\"]\ngit-tree-sha1 = \"51d2dfe8e590fbd74e7a842cf6d13d8a2f45dc01\"\nuuid = \"0656b61e-2033-5cc2-a64a-77c0f6c09b89\"\nversion = \"3.3.6+0\"\n\n[[GR]]\ndeps = [\"Base64\", \"DelimitedFiles\", \"GR_jll\", \"HTTP\", \"JSON\", \"Libdl\", \"LinearAlgebra\", \"Pkg\", \"Printf\", \"Random\", \"RelocatableFolders\", \"Serialization\", \"Sockets\", \"Test\", \"UUIDs\"]\ngit-tree-sha1 = \"4a740db447aae0fbeb3ee730de1afbb14ac798a1\"\nuuid = \"28b8d3ca-fb5f-59d9-8090-bfdbd6d07a71\"\nversion = \"0.63.1\"\n\n[[GR_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Cairo_jll\", \"FFMPEG_jll\", \"Fontconfig_jll\", \"GLFW_jll\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Libtiff_jll\", \"Pixman_jll\", \"Pkg\", \"Qt5Base_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"aa22e1ee9e722f1da183eb33370df4c1aeb6c2cd\"\nuuid = \"d2c73de3-f751-5644-a686-071e5b155ba9\"\nversion = \"0.63.1+0\"\n\n[[GeometryBasics]]\ndeps = [\"EarCut_jll\", \"IterTools\", \"LinearAlgebra\", \"StaticArrays\", \"StructArrays\", \"Tables\"]\ngit-tree-sha1 = \"58bcdf5ebc057b085e58d95c138725628dd7453c\"\nuuid = \"5c1252a2-5f33-56bf-86c9-59e7332b4326\"\nversion = \"0.4.1\"\n\n[[Gettext_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"9b02998aba7bf074d14de89f9d37ca24a1a0b046\"\nuuid = \"78b55507-aeef-58d4-861c-77aaff3498b1\"\nversion = \"0.21.0+0\"\n\n[[Glib_jll]]\ndeps = [\"Artifacts\", \"Gettext_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Libiconv_jll\", \"Libmount_jll\", \"PCRE_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"a32d672ac2c967f3deb8a81d828afc739c838a06\"\nuuid = \"7746bdde-850d-59dc-9ae8-88ece973131d\"\nversion = \"2.68.3+2\"\n\n[[Graphics]]\ndeps = [\"Colors\", \"LinearAlgebra\", \"NaNMath\"]\ngit-tree-sha1 = \"1c5a84319923bea76fa145d49e93aa4394c73fc2\"\nuuid = \"a2bd30eb-e257-5431-a919-1863eab51364\"\nversion = \"1.1.1\"\n\n[[Graphite2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"344bf40dcab1073aca04aa0df4fb092f920e4011\"\nuuid = \"3b182d85-2403-5c21-9c21-1e1f0cc25472\"\nversion = \"1.3.14+0\"\n\n[[Grisu]]\ngit-tree-sha1 = \"53bb909d1151e57e2484c3d1b53e19552b887fb2\"\nuuid = \"42e2da0e-8278-4e71-bc24-59509adca0fe\"\nversion = \"1.0.2\"\n\n[[HTTP]]\ndeps = [\"Base64\", \"Dates\", \"IniFile\", \"Logging\", \"MbedTLS\", \"NetworkOptions\", \"Sockets\", \"URIs\"]\ngit-tree-sha1 = \"0fa77022fe4b511826b39c894c90daf5fce3334a\"\nuuid = \"cd3eb016-35fb-5094-929b-558a96fad6f3\"\nversion = \"0.9.17\"\n\n[[HarfBuzz_jll]]\ndeps = [\"Artifacts\", \"Cairo_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"Graphite2_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\"]\ngit-tree-sha1 = \"129acf094d168394e80ee1dc4bc06ec835e510a3\"\nuuid = \"2e76f6c2-a576-52d4-95c1-20adfe4de566\"\nversion = \"2.8.1+1\"\n\n[[IRTools]]\ndeps = [\"InteractiveUtils\", \"MacroTools\", \"Test\"]\ngit-tree-sha1 = \"006127162a51f0effbdfaab5ac0c83f8eb7ea8f3\"\nuuid = \"7869d1d1-7146-5819-86e3-90919afe41df\"\nversion = \"0.4.4\"\n\n[[IfElse]]\ngit-tree-sha1 = \"debdd00ffef04665ccbb3e150747a77560e8fad1\"\nuuid = \"615f187c-cbe4-4ef1-ba3b-2fcf58d6d173\"\nversion = \"0.1.1\"\n\n[[IniFile]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"098e4d2c533924c921f9f9847274f2ad89e018b8\"\nuuid = \"83e8ac13-25f8-5344-8a64-a9f2b223428f\"\nversion = \"0.5.0\"\n\n[[InitialValues]]\ngit-tree-sha1 = \"4da0f88e9a39111c2fa3add390ab15f3a44f3ca3\"\nuuid = \"22cec73e-a1b8-11e9-2c92-598750a2cf9c\"\nversion = \"0.3.1\"\n\n[[InplaceOps]]\ndeps = [\"LinearAlgebra\", \"Test\"]\ngit-tree-sha1 = \"50b41d59e7164ab6fda65e71049fee9d890731ff\"\nuuid = \"505f98c9-085e-5b2c-8e89-488be7bf1f34\"\nversion = \"0.3.0\"\n\n[[IntelOpenMP_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d979e54b71da82f3a65b62553da4fc3d18c9004c\"\nuuid = \"1d5cc7b8-4909-519e-a0f8-d0f5ad9712d0\"\nversion = \"2018.0.3+2\"\n\n[[InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[Interpolations]]\ndeps = [\"AxisAlgorithms\", \"ChainRulesCore\", \"LinearAlgebra\", \"OffsetArrays\", \"Random\", \"Ratios\", \"Requires\", \"SharedArrays\", \"SparseArrays\", \"StaticArrays\", \"WoodburyMatrices\"]\ngit-tree-sha1 = \"b15fc0a95c564ca2e0a7ae12c1f095ca848ceb31\"\nuuid = \"a98d9a8b-a2ab-59e6-89dd-64a1c18fca59\"\nversion = \"0.13.5\"\n\n[[IntervalSets]]\ndeps = [\"Dates\", \"EllipsisNotation\", \"Statistics\"]\ngit-tree-sha1 = \"3cc368af3f110a767ac786560045dceddfc16758\"\nuuid = \"8197267c-284f-5f27-9208-e0e47529a953\"\nversion = \"0.5.3\"\n\n[[InverseFunctions]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"a7254c0acd8e62f1ac75ad24d5db43f5f19f3c65\"\nuuid = \"3587e190-3f89-42d0-90ee-14403ec27112\"\nversion = \"0.1.2\"\n\n[[InvertedIndices]]\ngit-tree-sha1 = \"bee5f1ef5bf65df56bdd2e40447590b272a5471f\"\nuuid = \"41ab1584-1d38-5bbf-9106-f11c6c58b48f\"\nversion = \"1.1.0\"\n\n[[IrrationalConstants]]\ngit-tree-sha1 = \"7fd44fd4ff43fc60815f8e764c0f352b83c49151\"\nuuid = \"92d709cd-6900-40b7-9082-c6be49f344b6\"\nversion = \"0.1.1\"\n\n[[IterTools]]\ngit-tree-sha1 = \"fa6287a4469f5e048d763df38279ee729fbd44e5\"\nuuid = \"c8e1da08-722c-5040-9ed9-7db0dc04731e\"\nversion = \"1.4.0\"\n\n[[IteratorInterfaceExtensions]]\ngit-tree-sha1 = \"a3f24677c21f5bbe9d2a714f95dcd58337fb2856\"\nuuid = \"82899510-4779-5014-852e-03e436cf321d\"\nversion = \"1.0.0\"\n\n[[JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"abc9885a7ca2052a736a600f7fa66209f96506e1\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.4.1\"\n\n[[JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"8076680b162ada2a031f707ac7b4953e30667a37\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.2\"\n\n[[JpegTurbo_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b53380851c6e6664204efb2e62cd24fa5c47e4ba\"\nuuid = \"aacddb02-875f-59d6-b918-886e6ef4fbf8\"\nversion = \"2.1.2+0\"\n\n[[Juno]]\ndeps = [\"Base64\", \"Logging\", \"Media\", \"Profile\"]\ngit-tree-sha1 = \"07cb43290a840908a771552911a6274bc6c072c7\"\nuuid = \"e5e0dc1b-0480-54bc-9374-aad01c23163d\"\nversion = \"0.8.4\"\n\n[[KernelDensity]]\ndeps = [\"Distributions\", \"DocStringExtensions\", \"FFTW\", \"Interpolations\", \"StatsBase\"]\ngit-tree-sha1 = \"591e8dc09ad18386189610acafb970032c519707\"\nuuid = \"5ab0869b-81aa-558d-bb23-cbf5423bbe9b\"\nversion = \"0.6.3\"\n\n[[LAME_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"f6250b16881adf048549549fba48b1161acdac8c\"\nuuid = \"c1c5ebd0-6772-5130-a774-d5fcae4a789d\"\nversion = \"3.100.1+0\"\n\n[[LRUCache]]\ngit-tree-sha1 = \"d64a0aff6691612ab9fb0117b0995270871c5dfc\"\nuuid = \"8ac3fa9e-de4c-5943-b1dc-09c6b5f20637\"\nversion = \"1.3.0\"\n\n[[LZO_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e5b909bcf985c5e2605737d2ce278ed791b89be6\"\nuuid = \"dd4b983a-f0e5-5f8d-a1b7-129d4a5fb1ac\"\nversion = \"2.10.1+0\"\n\n[[LaTeXStrings]]\ngit-tree-sha1 = \"f2355693d6778a178ade15952b7ac47a4ff97996\"\nuuid = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nversion = \"1.3.0\"\n\n[[Latexify]]\ndeps = [\"Formatting\", \"InteractiveUtils\", \"LaTeXStrings\", \"MacroTools\", \"Markdown\", \"Printf\", \"Requires\"]\ngit-tree-sha1 = \"a8f4f279b6fa3c3c4f1adadd78a621b13a506bce\"\nuuid = \"23fbe1c1-3f47-55db-b15f-69d7ec21a316\"\nversion = \"0.15.9\"\n\n[[LazyArtifacts]]\ndeps = [\"Artifacts\", \"Pkg\"]\nuuid = \"4af54fe1-eca0-43a8-85a7-787d91b784e3\"\n\n[[LeftChildRightSiblingTrees]]\ndeps = [\"AbstractTrees\"]\ngit-tree-sha1 = \"b864cb409e8e445688bc478ef87c0afe4f6d1f8d\"\nuuid = \"1d6d02ad-be62-4b6b-8a6d-2f90e265016e\"\nversion = \"0.1.3\"\n\n[[LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[Libffi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"0b4a5d71f3e5200a7dff793393e09dfc2d874290\"\nuuid = \"e9f186c6-92d2-5b65-8a66-fee21dc1b490\"\nversion = \"3.2.2+1\"\n\n[[Libgcrypt_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgpg_error_jll\", \"Pkg\"]\ngit-tree-sha1 = \"64613c82a59c120435c067c2b809fc61cf5166ae\"\nuuid = \"d4300ac3-e22c-5743-9152-c294e39db1e4\"\nversion = \"1.8.7+0\"\n\n[[Libglvnd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"7739f837d6447403596a75d19ed01fd08d6f56bf\"\nuuid = \"7e76a0d4-f3c7-5321-8279-8d96eeed0f29\"\nversion = \"1.3.0+3\"\n\n[[Libgpg_error_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c333716e46366857753e273ce6a69ee0945a6db9\"\nuuid = \"7add5ba3-2f88-524e-9cd5-f83b8a55f7b8\"\nversion = \"1.42.0+0\"\n\n[[Libiconv_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"42b62845d70a619f063a7da093d995ec8e15e778\"\nuuid = \"94ce4f54-9a6c-5748-9c1c-f9c7231a4531\"\nversion = \"1.16.1+1\"\n\n[[Libmount_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"9c30530bf0effd46e15e0fdcf2b8636e78cbbd73\"\nuuid = \"4b2f31a3-9ecc-558c-b454-b3730dcb73e9\"\nversion = \"2.35.0+0\"\n\n[[Librsvg_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pango_jll\", \"Pkg\", \"gdk_pixbuf_jll\"]\ngit-tree-sha1 = \"25d5e6b4eb3558613ace1c67d6a871420bfca527\"\nuuid = \"925c91fb-5dd6-59dd-8e8c-345e74382d89\"\nversion = \"2.52.4+0\"\n\n[[Libtask]]\ndeps = [\"IRTools\", \"LRUCache\", \"LinearAlgebra\", \"MacroTools\", \"Statistics\"]\ngit-tree-sha1 = \"8c8d83112829dc54e7db2d209a1f0d13c1e044a3\"\nuuid = \"6f1fad26-d15e-5dc8-ae53-837a1d7b8c9f\"\nversion = \"0.6.7\"\n\n[[Libtiff_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Pkg\", \"Zlib_jll\", \"Zstd_jll\"]\ngit-tree-sha1 = \"340e257aada13f95f98ee352d316c3bed37c8ab9\"\nuuid = \"89763e89-9b03-5906-acba-b20f662cd828\"\nversion = \"4.3.0+0\"\n\n[[Libuuid_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7f3efec06033682db852f8b3bc3c1d2b0a0ab066\"\nuuid = \"38a345b3-de98-5d2b-a5d3-14cd9215e700\"\nversion = \"2.36.0+0\"\n\n[[LinearAlgebra]]\ndeps = [\"Libdl\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[LogExpFunctions]]\ndeps = [\"ChainRulesCore\", \"ChangesOfVariables\", \"DocStringExtensions\", \"InverseFunctions\", \"IrrationalConstants\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"e5718a00af0ab9756305a0392832c8952c7426c1\"\nuuid = \"2ab3a3ac-af41-5b50-aa03-7779005ae688\"\nversion = \"0.3.6\"\n\n[[Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[LoggingExtras]]\ndeps = [\"Dates\", \"Logging\"]\ngit-tree-sha1 = \"dfeda1c1130990428720de0024d4516b1902ce98\"\nuuid = \"e6f89c97-d47a-5376-807f-9c37f3926c36\"\nversion = \"0.4.7\"\n\n[[Luxor]]\ndeps = [\"Base64\", \"Cairo\", \"Colors\", \"Dates\", \"FFMPEG\", \"FileIO\", \"Juno\", \"LaTeXStrings\", \"Random\", \"Requires\", \"Rsvg\"]\ngit-tree-sha1 = \"81a4fd2c618ba952feec85e4236f36c7a5660393\"\nuuid = \"ae8d54c2-7ccd-5906-9d76-62fc9837b5bc\"\nversion = \"3.0.0\"\n\n[[MCMCChains]]\ndeps = [\"AbstractMCMC\", \"AxisArrays\", \"Compat\", \"Dates\", \"Distributions\", \"Formatting\", \"IteratorInterfaceExtensions\", \"KernelDensity\", \"LinearAlgebra\", \"MCMCDiagnosticTools\", \"MLJModelInterface\", \"NaturalSort\", \"OrderedCollections\", \"PrettyTables\", \"Random\", \"RecipesBase\", \"Serialization\", \"Statistics\", \"StatsBase\", \"StatsFuns\", \"TableTraits\", \"Tables\"]\ngit-tree-sha1 = \"ddafbd2a95114d13721f2b6ddeeaee9529d6bc2b\"\nuuid = \"c7f686f2-ff18-58e9-bc7b-31028e88f75d\"\nversion = \"5.0.3\"\n\n[[MCMCDiagnosticTools]]\ndeps = [\"AbstractFFTs\", \"DataAPI\", \"Distributions\", \"LinearAlgebra\", \"MLJModelInterface\", \"Random\", \"SpecialFunctions\", \"Statistics\", \"StatsBase\", \"Tables\"]\ngit-tree-sha1 = \"058d08594e91ba1d98dcc3669f9421a76824aa95\"\nuuid = \"be115224-59cd-429b-ad48-344e309966f0\"\nversion = \"0.1.3\"\n\n[[MKL_jll]]\ndeps = [\"Artifacts\", \"IntelOpenMP_jll\", \"JLLWrappers\", \"LazyArtifacts\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"5455aef09b40e5020e1520f551fa3135040d4ed0\"\nuuid = \"856f044c-d86e-5d09-b602-aeab76dc8ba7\"\nversion = \"2021.1.1+2\"\n\n[[MLJModelInterface]]\ndeps = [\"Random\", \"ScientificTypesBase\", \"StatisticalTraits\"]\ngit-tree-sha1 = \"8da86dcf5a9ea48413c7e920a990f0ea1869f9cb\"\nuuid = \"e80e1ace-859a-464e-9ed9-23947d8ae3ea\"\nversion = \"1.3.6\"\n\n[[MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"3d3e902b31198a27340d0bf00d6ac452866021cf\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.9\"\n\n[[MappedArrays]]\ngit-tree-sha1 = \"e8b359ef06ec72e8c030463fe02efe5527ee5142\"\nuuid = \"dbb5928d-eab1-5f90-85c2-b9b0edb7c900\"\nversion = \"0.4.1\"\n\n[[Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[MbedTLS]]\ndeps = [\"Dates\", \"MbedTLS_jll\", \"Random\", \"Sockets\"]\ngit-tree-sha1 = \"1c38e51c3d08ef2278062ebceade0e46cefc96fe\"\nuuid = \"739be429-bea8-5141-9913-cc70e7f3736d\"\nversion = \"1.0.3\"\n\n[[MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[Measures]]\ngit-tree-sha1 = \"e498ddeee6f9fdb4551ce855a46f54dbd900245f\"\nuuid = \"442fdcdd-2543-5da2-b0f3-8c86c306513e\"\nversion = \"0.3.1\"\n\n[[Media]]\ndeps = [\"MacroTools\", \"Test\"]\ngit-tree-sha1 = \"75a54abd10709c01f1b86b84ec225d26e840ed58\"\nuuid = \"e89f7d12-3494-54d1-8411-f7d8b9ae1f27\"\nversion = \"0.5.0\"\n\n[[MicroCollections]]\ndeps = [\"BangBang\", \"InitialValues\", \"Setfield\"]\ngit-tree-sha1 = \"6bb7786e4f24d44b4e29df03c69add1b63d88f01\"\nuuid = \"128add7d-3638-4c79-886c-908ea0c25c34\"\nversion = \"0.1.2\"\n\n[[Missings]]\ndeps = [\"DataAPI\"]\ngit-tree-sha1 = \"bf210ce90b6c9eed32d25dbcae1ebc565df2687f\"\nuuid = \"e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28\"\nversion = \"1.0.2\"\n\n[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[MultivariateStats]]\ndeps = [\"Arpack\", \"LinearAlgebra\", \"SparseArrays\", \"Statistics\", \"StatsBase\"]\ngit-tree-sha1 = \"6d019f5a0465522bbfdd68ecfad7f86b535d6935\"\nuuid = \"6f286f6a-111f-5878-ab1e-185364afe411\"\nversion = \"0.9.0\"\n\n[[NNlib]]\ndeps = [\"Adapt\", \"ChainRulesCore\", \"Compat\", \"LinearAlgebra\", \"Pkg\", \"Requires\", \"Statistics\"]\ngit-tree-sha1 = \"c131644e2d7874361b5399a19e79387d90d28fea\"\nuuid = \"872c559c-99b0-510c-b3b7-b6c96a88d5cd\"\nversion = \"0.8.1\"\n\n[[NaNMath]]\ngit-tree-sha1 = \"b086b7ea07f8e38cf122f5016af580881ac914fe\"\nuuid = \"77ba4419-2d1f-58cd-9bb1-8ffee604a2e3\"\nversion = \"0.3.7\"\n\n[[NamedArrays]]\ndeps = [\"Combinatorics\", \"DataStructures\", \"DelimitedFiles\", \"InvertedIndices\", \"LinearAlgebra\", \"Random\", \"Requires\", \"SparseArrays\", \"Statistics\"]\ngit-tree-sha1 = \"2fd5787125d1a93fbe30961bd841707b8a80d75b\"\nuuid = \"86f7a689-2022-50b4-a561-43c23ac3c673\"\nversion = \"0.9.6\"\n\n[[NaturalSort]]\ngit-tree-sha1 = \"eda490d06b9f7c00752ee81cfa451efe55521e21\"\nuuid = \"c020b1a1-e9b0-503a-9c33-f039bfc54a85\"\nversion = \"1.0.0\"\n\n[[NearestNeighbors]]\ndeps = [\"Distances\", \"StaticArrays\"]\ngit-tree-sha1 = \"16baacfdc8758bc374882566c9187e785e85c2f0\"\nuuid = \"b8a86587-4115-5ab1-83bc-aa920d37bbce\"\nversion = \"0.4.9\"\n\n[[NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[Observables]]\ngit-tree-sha1 = \"fe29afdef3d0c4a8286128d4e45cc50621b1e43d\"\nuuid = \"510215fc-4207-5dde-b226-833fc4488ee2\"\nversion = \"0.4.0\"\n\n[[OffsetArrays]]\ndeps = [\"Adapt\"]\ngit-tree-sha1 = \"043017e0bdeff61cfbb7afeb558ab29536bbb5ed\"\nuuid = \"6fe1bfb0-de20-5000-8ca7-80f57d26f881\"\nversion = \"1.10.8\"\n\n[[Ogg_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"887579a3eb005446d514ab7aeac5d1d027658b8f\"\nuuid = \"e7412a2a-1a6e-54c0-be00-318e2571c051\"\nversion = \"1.3.5+1\"\n\n[[OpenBLAS_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Libdl\"]\nuuid = \"4536629a-c528-5b80-bd46-f80d51c5b363\"\n\n[[OpenLibm_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"05823500-19ac-5b8b-9628-191a04bc5112\"\n\n[[OpenSSL_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"648107615c15d4e09f7eca16307bc821c1f718d8\"\nuuid = \"458c3c95-2e84-50aa-8efc-19380b2a3a95\"\nversion = \"1.1.13+0\"\n\n[[OpenSpecFun_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"13652491f6856acfd2db29360e1bbcd4565d04f1\"\nuuid = \"efe28fd5-8261-553b-a9e1-b2916fc3738e\"\nversion = \"0.5.5+0\"\n\n[[Opus_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"51a08fb14ec28da2ec7a927c4337e4332c2a4720\"\nuuid = \"91d4177d-7536-5919-b921-800302f37372\"\nversion = \"1.3.2+0\"\n\n[[OrderedCollections]]\ngit-tree-sha1 = \"85f8e6578bf1f9ee0d11e7bb1b1456435479d47c\"\nuuid = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nversion = \"1.4.1\"\n\n[[PCRE_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b2a7af664e098055a7529ad1a900ded962bca488\"\nuuid = \"2f80f16e-611a-54ab-bc61-aa92de5b98fc\"\nversion = \"8.44.0+0\"\n\n[[PDMats]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\", \"SuiteSparse\"]\ngit-tree-sha1 = \"ee26b350276c51697c9c2d88a072b339f9f03d73\"\nuuid = \"90014a1f-27ba-587c-ab20-58faa44d9150\"\nversion = \"0.11.5\"\n\n[[Pango_jll]]\ndeps = [\"Artifacts\", \"Cairo_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"Glib_jll\", \"HarfBuzz_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"3a121dfbba67c94a5bec9dde613c3d0cbcf3a12b\"\nuuid = \"36c8627f-9965-5494-a995-c6b170f724f3\"\nversion = \"1.50.3+0\"\n\n[[Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"0b5cfbb704034b5b4c1869e36634438a047df065\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.2.1\"\n\n[[Pixman_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b4f5d02549a10e20780a24fce72bea96b6329e29\"\nuuid = \"30392449-352a-5448-841d-b1acce4e97dc\"\nversion = \"0.40.1+0\"\n\n[[Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[PlotThemes]]\ndeps = [\"PlotUtils\", \"Requires\", \"Statistics\"]\ngit-tree-sha1 = \"a3a964ce9dc7898193536002a6dd892b1b5a6f1d\"\nuuid = \"ccf2f8ad-2431-5c83-bf29-c5338b663b6a\"\nversion = \"2.0.1\"\n\n[[PlotUtils]]\ndeps = [\"ColorSchemes\", \"Colors\", \"Dates\", \"Printf\", \"Random\", \"Reexport\", \"Statistics\"]\ngit-tree-sha1 = \"6f1b25e8ea06279b5689263cc538f51331d7ca17\"\nuuid = \"995b91a9-d308-5afd-9ec6-746e21dbc043\"\nversion = \"1.1.3\"\n\n[[Plots]]\ndeps = [\"Base64\", \"Contour\", \"Dates\", \"Downloads\", \"FFMPEG\", \"FixedPointNumbers\", \"GR\", \"GeometryBasics\", \"JSON\", \"Latexify\", \"LinearAlgebra\", \"Measures\", \"NaNMath\", \"PlotThemes\", \"PlotUtils\", \"Printf\", \"REPL\", \"Random\", \"RecipesBase\", \"RecipesPipeline\", \"Reexport\", \"Requires\", \"Scratch\", \"Showoff\", \"SparseArrays\", \"Statistics\", \"StatsBase\", \"UUIDs\", \"UnicodeFun\", \"Unzip\"]\ngit-tree-sha1 = \"eb1432ec2b781f70ce2126c277d120554605669a\"\nuuid = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nversion = \"1.25.8\"\n\n[[Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"2cf929d64681236a2e074ffafb8d568733d2e6af\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.3\"\n\n[[PrettyTables]]\ndeps = [\"Crayons\", \"Formatting\", \"Markdown\", \"Reexport\", \"Tables\"]\ngit-tree-sha1 = \"dfb54c4e414caa595a1f2ed759b160f5a3ddcba5\"\nuuid = \"08abe8d2-0d0c-5749-adfa-8a2ac140af0d\"\nversion = \"1.3.1\"\n\n[[Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[Profile]]\ndeps = [\"Printf\"]\nuuid = \"9abbd945-dff8-562f-b5e8-e1ebf5ef1b79\"\n\n[[ProgressLogging]]\ndeps = [\"Logging\", \"SHA\", \"UUIDs\"]\ngit-tree-sha1 = \"80d919dee55b9c50e8d9e2da5eeafff3fe58b539\"\nuuid = \"33c8b6b6-d38a-422a-b730-caa89a2f386c\"\nversion = \"0.1.4\"\n\n[[ProgressMeter]]\ndeps = [\"Distributed\", \"Printf\"]\ngit-tree-sha1 = \"afadeba63d90ff223a6a48d2009434ecee2ec9e8\"\nuuid = \"92933f4c-e287-5a05-a399-4b506db050ca\"\nversion = \"1.7.1\"\n\n[[Qt5Base_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Fontconfig_jll\", \"Glib_jll\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"OpenSSL_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libxcb_jll\", \"Xorg_xcb_util_image_jll\", \"Xorg_xcb_util_keysyms_jll\", \"Xorg_xcb_util_renderutil_jll\", \"Xorg_xcb_util_wm_jll\", \"Zlib_jll\", \"xkbcommon_jll\"]\ngit-tree-sha1 = \"ad368663a5e20dbb8d6dc2fddeefe4dae0781ae8\"\nuuid = \"ea2cea3b-5b76-57ae-a6ef-0a8af62496e1\"\nversion = \"5.15.3+0\"\n\n[[QuadGK]]\ndeps = [\"DataStructures\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"78aadffb3efd2155af139781b8a8df1ef279ea39\"\nuuid = \"1fd47b50-473d-5c70-9696-f719f8f3bcdc\"\nversion = \"2.4.2\"\n\n[[REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[RangeArrays]]\ngit-tree-sha1 = \"b9039e93773ddcfc828f12aadf7115b4b4d225f5\"\nuuid = \"b3c3ace0-ae52-54e7-9d0b-2c1406fd6b9d\"\nversion = \"0.3.2\"\n\n[[Ratios]]\ndeps = [\"Requires\"]\ngit-tree-sha1 = \"01d341f502250e81f6fec0afe662aa861392a3aa\"\nuuid = \"c84ed2f1-dad5-54f0-aa8e-dbefe2724439\"\nversion = \"0.4.2\"\n\n[[RealDot]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"9f0a1b71baaf7650f4fa8a1d168c7fb6ee41f0c9\"\nuuid = \"c1ae055f-0cd5-4b69-90a6-9a35b1a98df9\"\nversion = \"0.1.0\"\n\n[[RecipesBase]]\ngit-tree-sha1 = \"6bf3f380ff52ce0832ddd3a2a7b9538ed1bcca7d\"\nuuid = \"3cdcf5f2-1ef4-517c-9805-6587b60abb01\"\nversion = \"1.2.1\"\n\n[[RecipesPipeline]]\ndeps = [\"Dates\", \"NaNMath\", \"PlotUtils\", \"RecipesBase\"]\ngit-tree-sha1 = \"37c1631cb3cc36a535105e6d5557864c82cd8c2b\"\nuuid = \"01d81517-befc-4cb6-b9ec-a95719d0359c\"\nversion = \"0.5.0\"\n\n[[RecursiveArrayTools]]\ndeps = [\"Adapt\", \"ArrayInterface\", \"ChainRulesCore\", \"DocStringExtensions\", \"FillArrays\", \"LinearAlgebra\", \"RecipesBase\", \"Requires\", \"StaticArrays\", \"Statistics\", \"ZygoteRules\"]\ngit-tree-sha1 = \"5144e1eafb2ecc75765888a4bdcd3a30a6a08b14\"\nuuid = \"731186ca-8d62-57ce-b412-fbd966d074cd\"\nversion = \"2.24.1\"\n\n[[Reexport]]\ngit-tree-sha1 = \"45e428421666073eab6f2da5c9d310d99bb12f9b\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.2.2\"\n\n[[RelocatableFolders]]\ndeps = [\"SHA\", \"Scratch\"]\ngit-tree-sha1 = \"cdbd3b1338c72ce29d9584fdbe9e9b70eeb5adca\"\nuuid = \"05181044-ff0b-4ac5-8273-598c1e38db00\"\nversion = \"0.1.3\"\n\n[[Requires]]\ndeps = [\"UUIDs\"]\ngit-tree-sha1 = \"838a3a4188e2ded87a4f9f184b4b0d78a1e91cb7\"\nuuid = \"ae029012-a4dd-5104-9daa-d747884805df\"\nversion = \"1.3.0\"\n\n[[Rmath]]\ndeps = [\"Random\", \"Rmath_jll\"]\ngit-tree-sha1 = \"bf3188feca147ce108c76ad82c2792c57abe7b1f\"\nuuid = \"79098fc4-a85e-5d69-aa6a-4863f24498fa\"\nversion = \"0.7.0\"\n\n[[Rmath_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"68db32dff12bb6127bac73c209881191bf0efbb7\"\nuuid = \"f50d1b31-88e8-58de-be2c-1cc44531875f\"\nversion = \"0.3.0+0\"\n\n[[Roots]]\ndeps = [\"CommonSolve\", \"Printf\", \"Setfield\"]\ngit-tree-sha1 = \"0abe7fc220977da88ad86d339335a4517944fea2\"\nuuid = \"f2b01f46-fcfa-551c-844a-d8ac1e96c665\"\nversion = \"1.3.14\"\n\n[[Rsvg]]\ndeps = [\"Cairo\", \"Glib_jll\", \"Librsvg_jll\"]\ngit-tree-sha1 = \"3d3dc66eb46568fb3a5259034bfc752a0eb0c686\"\nuuid = \"c4c386cf-5103-5370-be45-f3a111cca3b8\"\nversion = \"1.0.0\"\n\n[[SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[SciMLBase]]\ndeps = [\"ArrayInterface\", \"CommonSolve\", \"ConstructionBase\", \"Distributed\", \"DocStringExtensions\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"Logging\", \"RecipesBase\", \"RecursiveArrayTools\", \"StaticArrays\", \"Statistics\", \"Tables\", \"TreeViews\"]\ngit-tree-sha1 = \"f4862c0cb4e34ed182718221028ba1bf50742108\"\nuuid = \"0bca4576-84f4-4d90-8ffe-ffa030f20462\"\nversion = \"1.26.1\"\n\n[[ScientificTypesBase]]\ngit-tree-sha1 = \"a8e18eb383b5ecf1b5e6fc237eb39255044fd92b\"\nuuid = \"30f210dd-8aff-4c5f-94ba-8e64358c1161\"\nversion = \"3.0.0\"\n\n[[Scratch]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"0b4b7f1393cff97c33891da2a0bf69c6ed241fda\"\nuuid = \"6c6a2e73-6563-6170-7368-637461726353\"\nversion = \"1.1.0\"\n\n[[SentinelArrays]]\ndeps = [\"Dates\", \"Random\"]\ngit-tree-sha1 = \"15dfe6b103c2a993be24404124b8791a09460983\"\nuuid = \"91c51154-3ec4-41a3-a24f-3f23e20d615c\"\nversion = \"1.3.11\"\n\n[[Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[Setfield]]\ndeps = [\"ConstructionBase\", \"Future\", \"MacroTools\", \"Requires\"]\ngit-tree-sha1 = \"0afd9e6c623e379f593da01f20590bacc26d1d14\"\nuuid = \"efcf1570-3423-57d1-acb7-fd33fddbac46\"\nversion = \"0.8.1\"\n\n[[SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[Showoff]]\ndeps = [\"Dates\", \"Grisu\"]\ngit-tree-sha1 = \"91eddf657aca81df9ae6ceb20b959ae5653ad1de\"\nuuid = \"992d4aef-0814-514b-bc4d-f2e9a6c4116f\"\nversion = \"1.0.3\"\n\n[[Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[SortingAlgorithms]]\ndeps = [\"DataStructures\"]\ngit-tree-sha1 = \"b3363d7460f7d098ca0912c69b082f75625d7508\"\nuuid = \"a2af1166-a08f-5f64-846c-94a0d3cef48c\"\nversion = \"1.0.1\"\n\n[[SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[SpecialFunctions]]\ndeps = [\"ChainRulesCore\", \"IrrationalConstants\", \"LogExpFunctions\", \"OpenLibm_jll\", \"OpenSpecFun_jll\"]\ngit-tree-sha1 = \"8d0c8e3d0ff211d9ff4a0c2307d876c99d10bdf1\"\nuuid = \"276daf66-3868-5448-9aa4-cd146d93841b\"\nversion = \"2.1.2\"\n\n[[SplittablesBase]]\ndeps = [\"Setfield\", \"Test\"]\ngit-tree-sha1 = \"39c9f91521de844bad65049efd4f9223e7ed43f9\"\nuuid = \"171d559e-b47b-412a-8079-5efa626c420e\"\nversion = \"0.1.14\"\n\n[[Static]]\ndeps = [\"IfElse\"]\ngit-tree-sha1 = \"d4da8b728580709d736704764e55d6ef38cb7c87\"\nuuid = \"aedffcd0-7271-4cad-89d0-dc628f76c6d3\"\nversion = \"0.5.3\"\n\n[[StaticArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"a635a9333989a094bddc9f940c04c549cd66afcf\"\nuuid = \"90137ffa-7385-5640-81b9-e52037218182\"\nversion = \"1.3.4\"\n\n[[StatisticalTraits]]\ndeps = [\"ScientificTypesBase\"]\ngit-tree-sha1 = \"271a7fea12d319f23d55b785c51f6876aadb9ac0\"\nuuid = \"64bff920-2084-43da-a3e6-9bb72801c0c9\"\nversion = \"3.0.0\"\n\n[[Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[StatsAPI]]\ngit-tree-sha1 = \"d88665adc9bcf45903013af0982e2fd05ae3d0a6\"\nuuid = \"82ae8749-77ed-4fe6-ae5f-f523153014b0\"\nversion = \"1.2.0\"\n\n[[StatsBase]]\ndeps = [\"DataAPI\", \"DataStructures\", \"LinearAlgebra\", \"LogExpFunctions\", \"Missings\", \"Printf\", \"Random\", \"SortingAlgorithms\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"51383f2d367eb3b444c961d485c565e4c0cf4ba0\"\nuuid = \"2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91\"\nversion = \"0.33.14\"\n\n[[StatsFuns]]\ndeps = [\"ChainRulesCore\", \"InverseFunctions\", \"IrrationalConstants\", \"LogExpFunctions\", \"Reexport\", \"Rmath\", \"SpecialFunctions\"]\ngit-tree-sha1 = \"f35e1879a71cca95f4826a14cdbf0b9e253ed918\"\nuuid = \"4c63d2b9-4356-54db-8cca-17b64c39e42c\"\nversion = \"0.9.15\"\n\n[[StatsPlots]]\ndeps = [\"AbstractFFTs\", \"Clustering\", \"DataStructures\", \"DataValues\", \"Distributions\", \"Interpolations\", \"KernelDensity\", \"LinearAlgebra\", \"MultivariateStats\", \"Observables\", \"Plots\", \"RecipesBase\", \"RecipesPipeline\", \"Reexport\", \"StatsBase\", \"TableOperations\", \"Tables\", \"Widgets\"]\ngit-tree-sha1 = \"4d9c69d65f1b270ad092de0abe13e859b8c55cad\"\nuuid = \"f3b207a7-027a-5e70-b257-86293d7955fd\"\nversion = \"0.14.33\"\n\n[[StructArrays]]\ndeps = [\"Adapt\", \"DataAPI\", \"StaticArrays\", \"Tables\"]\ngit-tree-sha1 = \"d21f2c564b21a202f4677c0fba5b5ee431058544\"\nuuid = \"09ab397b-f2b6-538f-b94a-2f83cf4a842a\"\nversion = \"0.6.4\"\n\n[[SuiteSparse]]\ndeps = [\"Libdl\", \"LinearAlgebra\", \"Serialization\", \"SparseArrays\"]\nuuid = \"4607b0f0-06f3-5cda-b6b1-a6196a1729e9\"\n\n[[TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[TableOperations]]\ndeps = [\"SentinelArrays\", \"Tables\", \"Test\"]\ngit-tree-sha1 = \"e383c87cf2a1dc41fa30c093b2a19877c83e1bc1\"\nuuid = \"ab02a1b2-a7df-11e8-156e-fb1833f50b87\"\nversion = \"1.2.0\"\n\n[[TableTraits]]\ndeps = [\"IteratorInterfaceExtensions\"]\ngit-tree-sha1 = \"c06b2f539df1c6efa794486abfb6ed2022561a39\"\nuuid = \"3783bdb8-4a98-5b6b-af9a-565f29a5fe9c\"\nversion = \"1.0.1\"\n\n[[Tables]]\ndeps = [\"DataAPI\", \"DataValueInterfaces\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"TableTraits\", \"Test\"]\ngit-tree-sha1 = \"bb1064c9a84c52e277f1096cf41434b675cd368b\"\nuuid = \"bd369af6-aec1-5ad0-b16a-f7cc5008161c\"\nversion = \"1.6.1\"\n\n[[Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[TerminalLoggers]]\ndeps = [\"LeftChildRightSiblingTrees\", \"Logging\", \"Markdown\", \"Printf\", \"ProgressLogging\", \"UUIDs\"]\ngit-tree-sha1 = \"62846a48a6cd70e63aa29944b8c4ef704360d72f\"\nuuid = \"5d786b92-1e48-4d6f-9151-6b4477ca9bed\"\nversion = \"0.1.5\"\n\n[[Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[Tracker]]\ndeps = [\"Adapt\", \"DiffRules\", \"ForwardDiff\", \"LinearAlgebra\", \"LogExpFunctions\", \"MacroTools\", \"NNlib\", \"NaNMath\", \"Printf\", \"Random\", \"Requires\", \"SpecialFunctions\", \"Statistics\"]\ngit-tree-sha1 = \"7b00adbe4216b919d487d82a852c48f378c6ed37\"\nuuid = \"9f7883ad-71c0-57eb-9f7f-b5c9e6d3789c\"\nversion = \"0.2.18\"\n\n[[Transducers]]\ndeps = [\"Adapt\", \"ArgCheck\", \"BangBang\", \"Baselet\", \"CompositionsBase\", \"DefineSingletons\", \"Distributed\", \"InitialValues\", \"Logging\", \"Markdown\", \"MicroCollections\", \"Requires\", \"Setfield\", \"SplittablesBase\", \"Tables\"]\ngit-tree-sha1 = \"1cda71cc967e3ef78aa2593319f6c7379376f752\"\nuuid = \"28d57a85-8fef-5791-bfe6-a80928e7c999\"\nversion = \"0.4.72\"\n\n[[TreeViews]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"8d0d7a3fe2f30d6a7f833a5f19f7c7a5b396eae6\"\nuuid = \"a2a6695c-b41b-5b7d-aed9-dbfdeacea5d7\"\nversion = \"0.3.0\"\n\n[[Turing]]\ndeps = [\"AbstractMCMC\", \"AdvancedHMC\", \"AdvancedMH\", \"AdvancedPS\", \"AdvancedVI\", \"BangBang\", \"Bijectors\", \"DataStructures\", \"Distributions\", \"DistributionsAD\", \"DocStringExtensions\", \"DynamicPPL\", \"EllipticalSliceSampling\", \"ForwardDiff\", \"Libtask\", \"LinearAlgebra\", \"MCMCChains\", \"NamedArrays\", \"Printf\", \"Random\", \"Reexport\", \"Requires\", \"SciMLBase\", \"SpecialFunctions\", \"Statistics\", \"StatsBase\", \"StatsFuns\", \"Tracker\", \"ZygoteRules\"]\ngit-tree-sha1 = \"ce8198b3ac6bfa709f7c066ee0db13be52b2cbf8\"\nuuid = \"fce5fe82-541a-59a6-adf8-730c64b5f9a0\"\nversion = \"0.20.1\"\n\n[[URIs]]\ngit-tree-sha1 = \"97bbe755a53fe859669cd907f2d96aee8d2c1355\"\nuuid = \"5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4\"\nversion = \"1.3.0\"\n\n[[UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[UnPack]]\ngit-tree-sha1 = \"387c1f73762231e86e0c9c5443ce3b4a0a9a0c2b\"\nuuid = \"3a884ed6-31ef-47d7-9d2a-63182c4928ed\"\nversion = \"1.0.2\"\n\n[[Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[UnicodeFun]]\ndeps = [\"REPL\"]\ngit-tree-sha1 = \"53915e50200959667e78a92a418594b428dffddf\"\nuuid = \"1cfade01-22cf-5700-b092-accc4b62d6e1\"\nversion = \"0.4.1\"\n\n[[Unzip]]\ngit-tree-sha1 = \"34db80951901073501137bdbc3d5a8e7bbd06670\"\nuuid = \"41fe7b60-77ed-43a1-b4f0-825fd5a5650d\"\nversion = \"0.1.2\"\n\n[[Wayland_jll]]\ndeps = [\"Artifacts\", \"Expat_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"3e61f0b86f90dacb0bc0e73a0c5a83f6a8636e23\"\nuuid = \"a2964d1f-97da-50d4-b82a-358c7fce9d89\"\nversion = \"1.19.0+0\"\n\n[[Wayland_protocols_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"66d72dc6fcc86352f01676e8f0f698562e60510f\"\nuuid = \"2381bf8a-dfd0-557d-9999-79630e7b1b91\"\nversion = \"1.23.0+0\"\n\n[[Widgets]]\ndeps = [\"Colors\", \"Dates\", \"Observables\", \"OrderedCollections\"]\ngit-tree-sha1 = \"505c31f585405fc375d99d02588f6ceaba791241\"\nuuid = \"cc8bc4a8-27d6-5769-a93b-9d913e69aa62\"\nversion = \"0.6.5\"\n\n[[WoodburyMatrices]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"de67fa59e33ad156a590055375a30b23c40299d3\"\nuuid = \"efce3f68-66dc-5838-9240-27a6d6f5f9b6\"\nversion = \"0.5.5\"\n\n[[XML2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"1acf5bdf07aa0907e0a37d3718bb88d4b687b74a\"\nuuid = \"02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a\"\nversion = \"2.9.12+0\"\n\n[[XSLT_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgcrypt_jll\", \"Libgpg_error_jll\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\", \"Zlib_jll\"]\ngit-tree-sha1 = \"91844873c4085240b95e795f692c4cec4d805f8a\"\nuuid = \"aed1982a-8fda-507f-9586-7b0439959a61\"\nversion = \"1.1.34+0\"\n\n[[Xorg_libX11_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\", \"Xorg_xtrans_jll\"]\ngit-tree-sha1 = \"5be649d550f3f4b95308bf0183b82e2582876527\"\nuuid = \"4f6342f7-b3d2-589e-9d20-edeb45f2b2bc\"\nversion = \"1.6.9+4\"\n\n[[Xorg_libXau_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4e490d5c960c314f33885790ed410ff3a94ce67e\"\nuuid = \"0c0b7dd1-d40b-584c-a123-a41640f87eec\"\nversion = \"1.0.9+4\"\n\n[[Xorg_libXcursor_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXfixes_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"12e0eb3bc634fa2080c1c37fccf56f7c22989afd\"\nuuid = \"935fb764-8cf2-53bf-bb30-45bb1f8bf724\"\nversion = \"1.2.0+4\"\n\n[[Xorg_libXdmcp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fe47bd2247248125c428978740e18a681372dd4\"\nuuid = \"a3789734-cfe1-5b06-b2d0-1dd0d9d62d05\"\nversion = \"1.1.3+4\"\n\n[[Xorg_libXext_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"b7c0aa8c376b31e4852b360222848637f481f8c3\"\nuuid = \"1082639a-0dae-5f34-9b06-72781eeb8cb3\"\nversion = \"1.3.4+4\"\n\n[[Xorg_libXfixes_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"0e0dc7431e7a0587559f9294aeec269471c991a4\"\nuuid = \"d091e8ba-531a-589c-9de9-94069b037ed8\"\nversion = \"5.0.3+4\"\n\n[[Xorg_libXi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXfixes_jll\"]\ngit-tree-sha1 = \"89b52bc2160aadc84d707093930ef0bffa641246\"\nuuid = \"a51aa0fd-4e3c-5386-b890-e753decda492\"\nversion = \"1.7.10+4\"\n\n[[Xorg_libXinerama_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"26be8b1c342929259317d8b9f7b53bf2bb73b123\"\nuuid = \"d1454406-59df-5ea1-beac-c340f2130bc3\"\nversion = \"1.1.4+4\"\n\n[[Xorg_libXrandr_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"34cea83cb726fb58f325887bf0612c6b3fb17631\"\nuuid = \"ec84b674-ba8e-5d96-8ba1-2a689ba10484\"\nversion = \"1.5.2+4\"\n\n[[Xorg_libXrender_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"19560f30fd49f4d4efbe7002a1037f8c43d43b96\"\nuuid = \"ea2f1a96-1ddc-540d-b46f-429655e07cfa\"\nversion = \"0.9.10+4\"\n\n[[Xorg_libpthread_stubs_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"6783737e45d3c59a4a4c4091f5f88cdcf0908cbb\"\nuuid = \"14d82f49-176c-5ed1-bb49-ad3f5cbd8c74\"\nversion = \"0.1.0+3\"\n\n[[Xorg_libxcb_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"XSLT_jll\", \"Xorg_libXau_jll\", \"Xorg_libXdmcp_jll\", \"Xorg_libpthread_stubs_jll\"]\ngit-tree-sha1 = \"daf17f441228e7a3833846cd048892861cff16d6\"\nuuid = \"c7cfdc94-dc32-55de-ac96-5a1b8d977c5b\"\nversion = \"1.13.0+3\"\n\n[[Xorg_libxkbfile_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"926af861744212db0eb001d9e40b5d16292080b2\"\nuuid = \"cc61e674-0454-545c-8b26-ed2c68acab7a\"\nversion = \"1.1.0+4\"\n\n[[Xorg_xcb_util_image_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"0fab0a40349ba1cba2c1da699243396ff8e94b97\"\nuuid = \"12413925-8142-5f55-bb0e-6d7ca50bb09b\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\"]\ngit-tree-sha1 = \"e7fd7b2881fa2eaa72717420894d3938177862d1\"\nuuid = \"2def613f-5ad1-5310-b15b-b15d46f528f5\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_keysyms_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"d1151e2c45a544f32441a567d1690e701ec89b00\"\nuuid = \"975044d2-76e6-5fbe-bf08-97ce7c6574c7\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_renderutil_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"dfd7a8f38d4613b6a575253b3174dd991ca6183e\"\nuuid = \"0d47668e-0667-5a69-a72c-f761630bfb7e\"\nversion = \"0.3.9+1\"\n\n[[Xorg_xcb_util_wm_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"e78d10aab01a4a154142c5006ed44fd9e8e31b67\"\nuuid = \"c22f9ab0-d5fe-5066-847c-f4bb1cd4e361\"\nversion = \"0.4.1+1\"\n\n[[Xorg_xkbcomp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxkbfile_jll\"]\ngit-tree-sha1 = \"4bcbf660f6c2e714f87e960a171b119d06ee163b\"\nuuid = \"35661453-b289-5fab-8a00-3d9160c6a3a4\"\nversion = \"1.4.2+4\"\n\n[[Xorg_xkeyboard_config_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xkbcomp_jll\"]\ngit-tree-sha1 = \"5c8424f8a67c3f2209646d4425f3d415fee5931d\"\nuuid = \"33bec58e-1273-512f-9401-5d533626f822\"\nversion = \"2.27.0+4\"\n\n[[Xorg_xtrans_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"79c31e7844f6ecf779705fbc12146eb190b7d845\"\nuuid = \"c5fb5394-a638-5e4d-96e5-b29de1b5cf10\"\nversion = \"1.4.0+3\"\n\n[[Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[Zstd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e45044cd873ded54b6a5bac0eb5c971392cf1927\"\nuuid = \"3161d3a3-bdf6-5164-811a-617609db77b4\"\nversion = \"1.5.2+0\"\n\n[[ZygoteRules]]\ndeps = [\"MacroTools\"]\ngit-tree-sha1 = \"8c1a8e4dfacb1fd631745552c8db35d0deb09ea0\"\nuuid = \"700de1a5-db45-46bc-99cf-38207098b444\"\nversion = \"0.2.2\"\n\n[[gdk_pixbuf_jll]]\ndeps = [\"Artifacts\", \"Glib_jll\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Libtiff_jll\", \"Pkg\", \"Xorg_libX11_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"c23323cd30d60941f8c68419a70905d9bdd92808\"\nuuid = \"da03df04-f53b-5353-a52f-6a8b0620ced0\"\nversion = \"2.42.6+1\"\n\n[[libass_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"HarfBuzz_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"5982a94fcba20f02f42ace44b9894ee2b140fe47\"\nuuid = \"0ac62f75-1d6f-5e53-bd7c-93b484bb37c0\"\nversion = \"0.15.1+0\"\n\n[[libfdk_aac_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"daacc84a041563f965be61859a36e17c4e4fcd55\"\nuuid = \"f638f0a6-7fb0-5443-88ba-1cc74229b280\"\nversion = \"2.0.2+0\"\n\n[[libpng_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"94d180a6d2b5e55e447e2d27a29ed04fe79eb30c\"\nuuid = \"b53b4c65-9356-5827-b1ea-8c7a1a84506f\"\nversion = \"1.6.38+0\"\n\n[[libvorbis_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Ogg_jll\", \"Pkg\"]\ngit-tree-sha1 = \"b910cb81ef3fe6e78bf6acee440bda86fd6ae00c\"\nuuid = \"f27f6e37-5d2b-51aa-960f-b287f2bc3b7a\"\nversion = \"1.3.7+1\"\n\n[[nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\n[[x264_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fea590b89e6ec504593146bf8b988b2c00922b2\"\nuuid = \"1270edf5-f2f9-52d2-97e9-ab00b5d0237a\"\nversion = \"2021.5.5+0\"\n\n[[x265_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"ee567a171cce03570d77ad3a43e90218e38937a9\"\nuuid = \"dfaa095f-4041-5dcd-9319-2fabd8486b76\"\nversion = \"3.5.0+0\"\n\n[[xkbcommon_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\", \"Wayland_protocols_jll\", \"Xorg_libxcb_jll\", \"Xorg_xkeyboard_config_jll\"]\ngit-tree-sha1 = \"ece2350174195bb31de1a63bea3a41ae1aa593b6\"\nuuid = \"d8fb68d0-12a3-5cfd-a85a-d49703b185fd\"\nversion = \"0.9.1+5\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─dc1177eb-66ec-4b82-ad0d-5e76539faa24\n# ╟─64bba790-89ad-11ec-272d-af9bb791e63d\n# ╠═fc380f54-24c7-440a-9cfd-04d3a8ea3184\n# ╠═38643e87-ee2d-4aae-83f7-abc6199f54aa\n# ╠═b7acb16e-b6d1-4e53-80c4-0819259a6130\n# ╠═24553bda-3ce4-4156-bf8a-0a1fe3df2afb\n# ╟─a0871b5d-02f4-4f16-9bcd-2e85264b0f41\n# ╠═b5f72bd8-97b7-435f-8940-950af86aed91\n# ╠═00f15e65-5133-4453-88af-c9479c8e3f9e\n# ╠═a45b70a7-acb0-48f1-8ae5-31c63992cbfa\n# ╠═7fe105ae-7d5c-4dd8-8104-fdaa9a18ea25\n# ╠═c30df2ab-45c2-42c3-9e72-2c4759b9b640\n# ╠═9f18a980-5277-4419-912b-e261451427b0\n# ╠═c726de5c-e241-4fa5-984d-c4184a626e52\n# ╠═166d94ed-1e70-4ef6-8b78-f5b566216246\n# ╠═29c24b11-fad4-4a2f-afbe-9f6afaab82f1\n# ╠═40214128-1ed7-4b37-b19e-78fafdebbb0b\n# ╠═2c2ea945-795a-4e0a-bc16-c49fa15bee1c\n# ╠═60d2ae42-7e56-418e-88a9-2ad16e84555e\n# ╠═88c6f515-b4d9-4e85-9157-2fc1e81483a2\n# ╠═63703e6a-7adb-43c3-82aa-34f5aa746017\n# ╠═b81eb0e7-d3cd-49aa-ae14-b8436dc515a4\n# ╠═60b70f36-ffac-45c3-a3d4-78991ab57bab\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "827cfed948239352dd36491db6e902a5822ea9b9", "size": 59144, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "GMM.jl", "max_stars_repo_name": "delphinH/imagetoy", "max_stars_repo_head_hexsha": "a74e902aeaf8363aedef547de5aa3aa569e926bf", "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": "GMM.jl", "max_issues_repo_name": "delphinH/imagetoy", "max_issues_repo_head_hexsha": "a74e902aeaf8363aedef547de5aa3aa569e926bf", "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": "GMM.jl", "max_forks_repo_name": "delphinH/imagetoy", "max_forks_repo_head_hexsha": "a74e902aeaf8363aedef547de5aa3aa569e926bf", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4060500291, "max_line_length": 438, "alphanum_fraction": 0.735493034, "num_tokens": 26939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259924, "lm_q2_score": 0.863391599428538, "lm_q1q2_score": 0.8115132904304986}} {"text": "\r\n\r\nfunction triangular_solve_upper_rowwise(U, b)\r\n\r\n n_row = size(U, 1)\r\n x = zeros(eltype(b), n_row)\r\n\r\n @inbounds for ii = n_row:-1:1\r\n internal_sum = zero(eltype(b))\r\n @inbounds @simd for jj = n_row:-1:(ii+1)\r\n @fastmath internal_sum += U[ii, jj] * x[jj]\r\n end\r\n @fastmath x[ii] = (b[ii] - internal_sum) / U[ii, ii]\r\n end\r\n\r\n return x\r\nend\r\n\r\nfunction triangular_solve_upper_colwise(U, b)\r\n# function triangular_solve_upper_colwise(U{T}, b::Array{T}) where {T}\r\n\r\n n_col = size(U, 2)\r\n x = copy(b)\r\n\r\n @inbounds for jj = n_col:-1:1\r\n @fastmath x[jj] = x[jj] / U[jj, jj]\r\n # @view( x[1:(jj-1)] ) = @view( x[1:(jj-1)] ) - @view( U[1:(jj-1), jj] ) .* x[jj]\r\n @inbounds @simd for ii = 1:(jj-1)\r\n @fastmath x[ii] -= U[ii, jj] .* x[jj]\r\n end\r\n end\r\n\r\n return x\r\nend\r\n\r\nfunction triangular_solve_upper_colwise_transposed(L, b)\r\n # the input matrix L is a lower triangular matrix\r\n # but it solved as it was U = L', L' * x = b\r\n\r\n #=\r\n n_row = size(L, 1)\r\n x = zeros(eltype(b), n_row)\r\n\r\n @inbounds for ii = n_row:-1:1\r\n internal_sum = zero(eltype(b))\r\n @inbounds @simd for jj = n_row:-1:(ii+1)\r\n @fastmath internal_sum += L[jj, ii] * x[jj]\r\n end\r\n @inbounds @fastmath x[ii] = (b[ii] - internal_sum) / L[ii, ii]\r\n end\r\n\r\n return x\r\n =#\r\n return triangular_solve_upper_colwise(L', b)\r\nend\r\n\r\nfunction triangular_solve_lower_rowwise(L, b)\r\n# function triangular_solve_lower_rowwise(L{T}, b::Array{T}) where {T}\r\n\r\n n_row = size(L, 1)\r\n x = zeros(eltype(b), n_row)\r\n \r\n for ii = 1:n_row\r\n internal_sum = zero(eltype(b))\r\n @inbounds @simd for jj = 1:(ii-1)\r\n @fastmath internal_sum += L[ii, jj] * x[jj]\r\n end\r\n @fastmath x[ii] = (b[ii] - internal_sum) / L[ii, ii];\r\n end\r\n \r\n return x\r\nend\r\n\r\n\r\nfunction triangular_solve_lower_colwise(L, b)\r\n# function triangular_solve_lower_colwise(L{T}, b::Array{T}) where {T}\r\n\r\n (n_row, n_col) = size(L)\r\n x = copy(b)\r\n\r\n # Single threaded\r\n @inbounds for jj = 1:n_col\r\n @fastmath x[jj] = x[jj] / L[jj, jj]\r\n @inbounds @simd for rr = (jj+1):n_row\r\n @fastmath x[rr] -= L[rr, jj] .* x[jj]\r\n end\r\n end\r\n\r\n return x\r\nend\r\n\r\n\r\nfunction triangular_solve_lower_sparse(spmat::SparseMatrixCSC, b)\r\n # forward substitution\r\n\r\n n_row = spmat.n_row\r\n n_col = spmat.n_col\r\n \r\n x = copy(b)\r\n L11 = spmat[1] # 1,1 location\r\n x[1] = x[1] / L11\r\n\r\n L::Int = length(spmat)\r\n idx_end::Int = 0\r\n\r\n for cc = 1:spmat.n_col\r\n \r\n idx_start = spmat.col_begins_index[cc]\r\n if idx_start == 0\r\n error(\"Singular matrix cannot be solved\")\r\n end\r\n\r\n # find next nonzero index\r\n idx_end = find_next_nonempty_col_begin(spmat, cc)\r\n\r\n for rr = idx_start:(idx_end-1)\r\n a_ij = spmat.data[rr]\r\n ii = spmat.row_index[rr]\r\n x[ii] /= a_ij\r\n end\r\n\r\n end\r\n\r\n return x\r\nend\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "625bafa4f4d5f8419260c12b184261f403d2cc3a", "size": 3099, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "__lib__/math/linalg/src/triangular.jl", "max_stars_repo_name": "HomoModelicus/julia", "max_stars_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "__lib__/math/linalg/src/triangular.jl", "max_issues_repo_name": "HomoModelicus/julia", "max_issues_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "__lib__/math/linalg/src/triangular.jl", "max_forks_repo_name": "HomoModelicus/julia", "max_forks_repo_head_hexsha": "26be81348032ccd2728046193ce627c823a3804b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3007518797, "max_line_length": 90, "alphanum_fraction": 0.5359793482, "num_tokens": 943, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133447766225, "lm_q2_score": 0.863391599428538, "lm_q1q2_score": 0.811513286070915}} {"text": "export tukey\n\"\"\"\n tukey(N::Int, r::AbstractArray) -> AbstractArray\n\nTukey window is a rectangular window with the first and\nlast r/2 percent of the samples equal to parts of a cosine.\n\"\"\"\nfunction tukey(N::Int, r::AbstractFloat=0.5)\n n = (0:N-1)/(N-1)\n w = zeros(N)\n for i = 1:N\n x = n[i]\n if 0 <= x <= r/2\n w[i] = 0.5 + 0.5*cos(2*pi/r*(x-r/2))\n elseif r/2 <= x <= 1-r/2\n w[i] = 1.0\n else\n w[i] = 0.5 + 0.5*cos(2*pi/r*(x-1+r/2))\n end\n end\n return w\nend\n\n\nexport gauss\n\"\"\"\n gauss(N::Int, a::AbstractFloat=0.5)\n\na is proportional to the standard deviation\n\"\"\"\nfunction gauss(N::Int, a::AbstractFloat=0.4)\n n = 0:N-1\n m = (N-1)/2\n return @. exp(-((n - m)/m/a)^2/2)\nend\n", "meta": {"hexsha": "2a014df884980819f54e6acaad522cae598fd409", "size": 764, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/2-binary.jl", "max_stars_repo_name": "sonosole/WindowFunctions.jl", "max_stars_repo_head_hexsha": "82c67745ad4a6ef1d751f45d3abd6239ca5afd7a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-13T16:25:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-13T16:25:11.000Z", "max_issues_repo_path": "src/2-binary.jl", "max_issues_repo_name": "sonosole/WindowFunctions.jl", "max_issues_repo_head_hexsha": "82c67745ad4a6ef1d751f45d3abd6239ca5afd7a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/2-binary.jl", "max_forks_repo_name": "sonosole/WindowFunctions.jl", "max_forks_repo_head_hexsha": "82c67745ad4a6ef1d751f45d3abd6239ca5afd7a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.2222222222, "max_line_length": 59, "alphanum_fraction": 0.5248691099, "num_tokens": 282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088084787997, "lm_q2_score": 0.8740772482857833, "lm_q1q2_score": 0.811501016599432}} {"text": "\n\"\"\"\n\tmeanconfid(x;sigma)\nCompute the mean with confidence interval assuming normal\ndistribution (or large sample size => central limit theorem)\n\n**Input**\n* x: vector of samples (NaNs will be removed)\n* sigma: optional input in case sigma (standard deviation, not variance) is known\n* alpha: (1-alpha) gives the conficende interval for x_mean\n\n**Output**\n* x_mean: estimated mean\n* x_confid: tuple with (lower,upper) confidence bounds defined by alpha\n\n**Example**\n```\n# known standard deviation\nx = [2.,3.,5.,6.,9.]\nx_mean,x_confid = meanconfid(x,sigma=2.5)\n\n# including NaN and Unknown sigma\npush!(x,NaN);\nx_mean,x_confid = meanconfid(x)\n```\n\"\"\"\nfunction meanconfid(x::Vector{Float64};alpha::Float64=0.05,sigma::Float64=NaN)\n\tx_use = HypoTest.prepdata(x);\n\tx_mean = Distributions.mean(x_use);\n\ts = isnan(sigma) ? Distributions.std(x_use) : sigma;\n\tif isnan(sigma) && length(x_use) < 100\n\t\td = Distributions.TDist(length(x_use)-1);\n\telse\n\t\td = Distributions.Normal();\n\tend\n\tq = Distributions.quantile(d,1-alpha/2);\n\treturn x_mean,(x_mean-q*s/sqrt(length(x_use)),x_mean+q*s/sqrt(length(x_use)))\nend\n\n\"\"\"\n\tstdconfid(x;x_mean)\nCompute the standard deviation with confidence interval assuming normal\ndistribution\n\n**Input**\n* x: vector of samples (NaNs will be removed)\n* x_mean: optional input in case true mean is known (=>n instead n-1)\n* alpha: (1-alpha) gives the conficende interval for sigma\n\n**Output**\n* sigma: estimated standard deviation (not variance)\n* x_confid: tuple with (lower,upper) confidence bounds defined by alpha\n\n**Example**\n```\nx = [1.95,1.96,1.98,1.99,2.00,2.00,2.01,2.01,2.01,2.01,\n\t2.02,2.02,2.03,2.03,2.04,2.04,2.05,2.06,2.08,2.10];\n# unknown mean value\ns,s_interval = stdconfid(x,alpha=0.05)\n\n# known mean\nx = [19.01,19.02,18.99,19.00,19.05,19.05,19.0,18.98,18.99,19.0];\ns,s_interval = stdconfid(x,alpha=0.05,x_mean=19.)\n```\n\"\"\"\nfunction stdconfid(x::Vector{Float64};alpha::Float64=0.05,x_mean::Float64=NaN)\n\tx_use = HypoTest.prepdata(x);\n\tsigma = Distributions.std(x_use, mean = isnan(x_mean) ? nothing : x_mean,\n\t\t\t\t\t\t\t\tcorrected = isnan(x_mean) ? true : false);\n\tk = isnan(x_mean) ? length(x_use)-1 : length(x_use);\n\td = Distributions.Chisq(k);\n\tqlow,qhigh = Distributions.quantile(d,1-alpha/2),Distributions.quantile(d,alpha/2);\n\treturn sigma,(sqrt(k*sigma^2/qlow), sqrt(k*sigma^2/qhigh))\nend\n", "meta": {"hexsha": "fb424cee9b947666a3d9c34a3dfb124f01f4471d", "size": 2326, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/momentestim.jl", "max_stars_repo_name": "emenems/HypoTest", "max_stars_repo_head_hexsha": "0cdbecb705825fc8bef718565400796aae44db84", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/momentestim.jl", "max_issues_repo_name": "emenems/HypoTest", "max_issues_repo_head_hexsha": "0cdbecb705825fc8bef718565400796aae44db84", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/momentestim.jl", "max_forks_repo_name": "emenems/HypoTest", "max_forks_repo_head_hexsha": "0cdbecb705825fc8bef718565400796aae44db84", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0133333333, "max_line_length": 84, "alphanum_fraction": 0.7115219261, "num_tokens": 748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087985746093, "lm_q2_score": 0.8740772368049823, "lm_q1q2_score": 0.8115009972835279}} {"text": "using FrankWolfe\nusing LinearAlgebra\nusing LaTeXStrings\nusing Plots\n\n# # FrankWolfe for scaled, shifted ``\\ell^1`` and ``\\ell^{\\infty}`` norm balls\n\n# In this example, we run the vanilla FrankWolfe algorithm on a scaled and shifted ``\\ell^1`` and ``\\ell^{\\infty}`` norm ball, using the `ScaledBoundL1NormBall`\n# and `ScaledBoundLInfNormBall` LMOs. We shift both onto the point ``(1,0)`` and then scale them by a factor of ``2`` along the x-axis. We project the point ``(2,1)`` onto the polytopes.\n\nn = 2\n\nk = 1000\n\nxp = [2.0,1.0]\n\nf(x) = norm(x-xp)^2\n\nfunction grad!(storage,x)\n @. storage = 2 * (x - xp)\n return nothing\nend\n\nlower = [-1.0,-1.0]\nupper = [3.0,1.0]\n\nl1 = FrankWolfe.ScaledBoundL1NormBall(lower, upper)\n\nlinf = FrankWolfe.ScaledBoundLInfNormBall(lower, upper)\n\nx1 = FrankWolfe.compute_extreme_point(l1, zeros(n))\ngradient = collect(x1)\n\nx_l1, v_1, primal_1, dual_gap_1, trajectory_1 = FrankWolfe.frank_wolfe(\n f,\n grad!,\n l1,\n collect(copy(x1)),\n max_iteration=k,\n line_search=FrankWolfe.Shortstep(),\n L=2,\n print_iter=50,\n emphasis=FrankWolfe.memory,\n verbose=true,\n trajectory=true,\n);\n\nprintln(\"\\nFinal solution: \", x_l1)\n\nx2 = FrankWolfe.compute_extreme_point(linf, zeros(n))\ngradient = collect(x2)\n\nx_linf, v_2, primal_2, dual_gap_2, trajectory_2 = FrankWolfe.frank_wolfe(\n f,\n grad!,\n linf,\n collect(copy(x2)),\n max_iteration=k,\n line_search=FrankWolfe.Shortstep(),\n L=2,\n print_iter=50,\n emphasis=FrankWolfe.memory,\n verbose=true,\n trajectory=true,\n);\n\nprintln(\"\\nFinal solution: \", x_linf)\n\n\n# We plot the polytopes alongside the solutions from above:\n\nxcoord1 = [1,3,1,-1,1]\nycoord1 = [-1,0,1,0,-1]\n\nxcoord2 = [3,3,-1,-1,3]\nycoord2 = [-1,1,1,-1,-1]\n\nplot(xcoord1, ycoord1, title = \"Visualization of scaled shifted norm balls\", lw = 2, label = L\"\\ell^1 \\textrm{ norm}\")\nplot!(xcoord2, ycoord2, lw = 2, label = L\"\\ell^{\\infty} \\textrm{ norm}\")\nplot!([x_l1[1]], [x_l1[2]], seriestype = :scatter, lw = 5, color = \"blue\", label = L\"\\ell^1 \\textrm{ solution}\")\nplot!([x_linf[1]], [x_linf[2]], seriestype = :scatter, lw = 5, color = \"orange\", label = L\"\\ell^{\\infty} \\textrm{ solution}\", legend = :bottomleft)\n", "meta": {"hexsha": "d25e20b751edb33693009a9d2d16aa55514ebf4d", "size": 2198, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/docs_7_shifted_norm_polytopes.jl", "max_stars_repo_name": "gdalle/FrankWolfe.jl-2", "max_stars_repo_head_hexsha": "c3b3903c4808e24aa9e0f655aa2f8de0f2c1571c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 48, "max_stars_repo_stars_event_min_datetime": "2021-03-27T15:50:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T15:11:21.000Z", "max_issues_repo_path": "examples/docs_7_shifted_norm_polytopes.jl", "max_issues_repo_name": "gdalle/FrankWolfe.jl-2", "max_issues_repo_head_hexsha": "c3b3903c4808e24aa9e0f655aa2f8de0f2c1571c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 132, "max_issues_repo_issues_event_min_datetime": "2021-03-29T18:49:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T01:33:22.000Z", "max_forks_repo_path": "docs/src/examples/6_shifted_norm_polytopes.jl", "max_forks_repo_name": "dviladrich95/FrankWolfe.jl", "max_forks_repo_head_hexsha": "bcb441e52918bd1103f13296082cd7a8bc22607b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2021-06-02T13:38:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T10:04:42.000Z", "avg_line_length": 26.8048780488, "max_line_length": 186, "alphanum_fraction": 0.6665150136, "num_tokens": 768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554476, "lm_q2_score": 0.874077222043951, "lm_q1q2_score": 0.8115009853106622}} {"text": "# Word Problems Logical Reasoning Tests\n# http://www.graduatewings.co.uk/word-problems-logical-tests\nusing AbstractLogic\n\n# Question 1\n# Sam is shorter than Hannah. William is shorter than Michael who is shorter than\n# Hannah. Hannah and William are shorter than Fiona. Who is the tallest?\nlogicset = logicalparse([\"Sam, Hannah, William, Michael, Fiona ∈ 1:5\"])\nlogicset = logicalparse([\"Sam < Hannah; William < Michael; Michael < Hannah\"], logicset)\nlogicset = logicalparse([\"Hannah < Fiona; William < Fiona\"], logicset)\n\n# A) Sam B) Hannah C) William D) Fiona E) Cannot Say\nsearch(\"{{i}} > {{!i}}\", logicset)\n# :Fiona is a match with 13 feasible combinations out of 13.\n# Therefore we choose D) Fiona\n\n\n# Question 2\n# Ben is taller than Sharon who is taller than Ralph. Ben is also taller than Mike.\nlogicset = logicalparse([\"Ben, Sharon, Ralph, Mike ∈ 1:4\"])\nlogicset = logicalparse([\"Ben > Sharon; Sharon > Ralph; Ben > Mike\"], logicset)\n\n# Who is the shortest?\n# A) Ben B) Sharon C) Ralph D) Mike E) Cannot Say\nsearch(\"{{i}} < {{!i}}\", logicset)\n# :Ralph is a possible match with 6 feasible combinations out of 11.\n# :Mike is a possible match with 1 feasible combinations out of 11.\n# Therefore we choose E) Cannot Say\n", "meta": {"hexsha": "fb93ce40f52955561fa0c8d2e0856aa1f77d66d8", "size": 1248, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/juliashell/OrderedReasoningProblems.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/AbstractLogic.jl-bd85187e-0531-4a3e-9fea-713204a818a2", "max_stars_repo_head_hexsha": "1b8adac10854471ec7ce83b9039cdeb1e43c0208", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2019-09-24T23:44:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T18:03:25.000Z", "max_issues_repo_path": "examples/juliashell/OrderedReasoningProblems.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/AbstractLogic.jl-bd85187e-0531-4a3e-9fea-713204a818a2", "max_issues_repo_head_hexsha": "1b8adac10854471ec7ce83b9039cdeb1e43c0208", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2019-08-08T19:13:18.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-10T01:13:59.000Z", "max_forks_repo_path": "examples/juliashell/OrderedReasoningProblems.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/AbstractLogic.jl-bd85187e-0531-4a3e-9fea-713204a818a2", "max_forks_repo_head_hexsha": "1b8adac10854471ec7ce83b9039cdeb1e43c0208", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-22T01:12:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-22T01:12:36.000Z", "avg_line_length": 43.0344827586, "max_line_length": 88, "alphanum_fraction": 0.703525641, "num_tokens": 339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545348152282, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.8114791443807761}} {"text": "module problem116\n\ndescription = \"\"\"\nRed, green or blue tiles\nA row of five black square tiles is to have a number of its tiles replaced with coloured oblong tiles chosen from red (length two), green (length three), or blue (length four).\nIf red tiles are chosen there are exactly seven ways this can be done.\nIf green tiles are chosen there are three ways.\nAnd if blue tiles are chosen there are two ways.\nAssuming that colours cannot be mixed there are 7 + 3 + 2 = 12 ways of replacing the black tiles in a row measuring five units in length.\n\nHow many different ways can the black tiles in a row measuring fifty units in length be replaced if colours cannot be mixed and at least one coloured tile must be used?\n\"\"\"\n\n# Fill function, based on problems 114, 115\nfunction F(m::Integer, n :: Integer, memo = zeros(Int, n))\n # Base case: no space remaining in the row\n if n < m return 0 end\n\n # Recursive case, count 1 for each placement of block at positions 1:n-m+1, and all ways of\n # filling the remaining space at the end of the row after each placement, memoizing results.\n if memo[n] == 0\n total = 0\n for blockpos = 1:(n-m+1)\n total += 1 + F(m, n - blockpos - m + 1, memo)\n end\n memo[n] = total\n end\n return memo[n]\nend\n\n# total ways to fill a row with only red,blue or green tiles.\nfunction homogenous_replacements(n :: Integer)\n return F(2, n) + F(3, n) + F(4, n)\nend\n\nusing Base.Test\n\n@test F(2, 5) == 7\n@test F(3, 5) == 3\n@test F(4, 5) == 2\n@test homogenous_replacements(5) == (7+3+2)\n\nend", "meta": {"hexsha": "e892f209b9e4922bc927061b91981bc101e6e473", "size": 1524, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/problem116.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/problem116.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/problem116.jl", "max_forks_repo_name": "mbuhot/mbuhot-euler-solutions", "max_forks_repo_head_hexsha": "30066543cfd2d84976beb0605839750b64f4b8ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4418604651, "max_line_length": 176, "alphanum_fraction": 0.7027559055, "num_tokens": 432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338057771058, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.8114336734109537}} {"text": "#solve eq x=cos(x)\nfunction main()\n x=0.0\n xnext = cos(x)\n iter=0\n eps=1e-7\n iteration=1000000\n is_convergence=false\n\n for n in 1:iteration\n xnext = cos(x)\n if(abs(xnext-x)= mixcountmax)\n\t\t\t\t\tmixing!(array,mixpos)\n\t\t\t\t\tmixcount = 0\n\t\t\t\tend\n\t\t\t\tmixcount = mixcount + 1\n\t\t\tend\n\n\t\tend\n\tend\nend\n\nfunction executor(filename)\n\topen(filename) do f\n\t\ttempstring = readline(f)\n\t\twhile tempstring != \"\"\n\t\t\teval(Meta.parse(tempstring))\n\t\t\ttempstring = readline(f)\n\t\tend\n\tend\nend\n\nfunction indextable(q)\n\ttemp = fill(0,q)\n\tfor i in 1:q\n\t\ttemp[i] = i\n\tend\nend\n\n\n", "meta": {"hexsha": "9e752f54f7f852f37f96bb558069e3d00daa7ab4", "size": 2166, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Diffusion.jl", "max_stars_repo_name": "Walter-Feng/heat-conduct-in-julia", "max_stars_repo_head_hexsha": "be691dd19734e871f94275cbc7697173f50fd5b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Diffusion.jl", "max_issues_repo_name": "Walter-Feng/heat-conduct-in-julia", "max_issues_repo_head_hexsha": "be691dd19734e871f94275cbc7697173f50fd5b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Diffusion.jl", "max_forks_repo_name": "Walter-Feng/heat-conduct-in-julia", "max_forks_repo_head_hexsha": "be691dd19734e871f94275cbc7697173f50fd5b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8787878788, "max_line_length": 252, "alphanum_fraction": 0.6440443213, "num_tokens": 730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012655937033, "lm_q2_score": 0.8577680977182186, "lm_q1q2_score": 0.8112781524077944}} {"text": "using Distributions\nusing Plots\n\nfunction calc_midpoints(edges::AbstractVector)::Vector{Float64}\n return Float64[0.5 * (edges[i] + edges[i+1]) for i ∈ 1:length(edges)-1]\nend\n\nfunction bin_data1d(data::AbstractVector, bins::Integer)\n low, high = extrema(data)\n edges = collect(range(low, stop = high, length = bins + 1))\n midpoints = calc_midpoints(edges)\n buckets = Int[max(2, min(searchsortedfirst(edges, x), length(edges))) - 1 for x ∈ data]\n counts = zeros(Int, length(midpoints))\n for b in buckets\n counts[b] += 1\n end\n return edges, midpoints, buckets, counts\nend\n\nfunction bin_data2d(data::AbstractMatrix, xbins::Integer, ybins::Integer)\n xmin, ymin = minimum(data, dims = 2)\n xmax, ymax = maximum(data, dims = 2)\n xedges = collect(range(xmin, stop = xmax, length = xbins + 1))\n yedges = collect(range(ymin, stop = ymax, length = ybins + 1))\n xmidpts = calc_midpoints(xedges)\n ymidpts = calc_midpoints(yedges)\n buckets = []\n d, c = size(data)\n for i = 1:c\n x = data[1, i]\n y = data[2, i]\n xb = max(2, min(searchsortedfirst(xedges, x), length(xedges))) - 1\n yb = max(2, min(searchsortedfirst(yedges, y), length(yedges))) - 1\n push!(buckets, (yb, xb))\n end\n counts = zeros(Int, length(ymidpts), length(xmidpts))\n for (yb, xb) in buckets\n counts[yb, xb] += 1\n end\n xedges, yedges, xmidpts, ymidpts, buckets, counts\nend\n\nμ = [\n -1\n -2\n]\n\nΣ = [\n 1.0 -0.7\n -0.7 1.0\n]\n\nusing Distributions\nd = MvNormal(μ, Σ)\nxydata = rand(d, 10000)\n\np1 = plot(xlabel = \"x\", ylabel = \"y\")\nxedges, yedges, xmidpts, ymidpts, buckets, counts = bin_data2d(xydata, 30, 30)\nr, c = size(counts)\nscatter!(p1, xydata[1, :], xydata[2, :], alpha = 0.2)\nheatmap!(p1, xmidpts, ymidpts, counts, alpha = 0.85)\nxind = 18\nplot!(\n p1,\n [xmidpts[xind], xmidpts[xind]],\n [minimum(ymidpts), maximum(ymidpts)],\n color = :red,\n legend = :false,\n)\np2 = plot(\n ymidpts,\n counts[:, xind] / sum(counts[:, xind]),\n label = \"p(y|x=$(xmidpts[xind])\",\n)\nplot(p1, p2, layout = (2, 1))\n", "meta": {"hexsha": "378b67fabb16ae4c335e152f4ced193768a38e75", "size": 2089, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "plotExer/histhack2d.jl", "max_stars_repo_name": "terasakisatoshi/juliaExer", "max_stars_repo_head_hexsha": "e3c2195f39de858915a3dcd47684eccbb7ecb552", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-02T01:24:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-04T12:03:25.000Z", "max_issues_repo_path": "plotExer/histhack2d.jl", "max_issues_repo_name": "terasakisatoshi/juliaExer", "max_issues_repo_head_hexsha": "e3c2195f39de858915a3dcd47684eccbb7ecb552", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "plotExer/histhack2d.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": 27.4868421053, "max_line_length": 91, "alphanum_fraction": 0.6141694591, "num_tokens": 712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.941654159388319, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.8112710434042434}} {"text": "\nusing OrdinaryDiffEq\nusing DataDrivenDiffEq\nusing ModelingToolkit\nusing Distributions\nusing Random\nusing Plots\n\n\nRandom.seed!(123);\n\n\nfunction sir_ode(u,p,t)\n (s,i,r) = u\n (β,γ) = p\n ds = -β*s*i\n di = β*s*i - γ*i\n dr = γ*i\n [ds,di,dr]\nend;\n\n\np = [0.5,0.25]\nu0 = [0.99, 0.01, 0.0]\ntspan = (0.0, 40.0)\nδt = 1;\n\n\nsolver = ExplicitRK();\n\n\nsir_prob = ODEProblem(sir_ode, u0, tspan, p)\nsir_sol = solve(sir_prob, solver, saveat = δt);\n\n\ndd_prob = ContinuousDataDrivenProblem(sir_sol);\n\n\n@parameters t\n@variables u[1:3](t)\nΨ = Basis([u; u[1]*u[2]], u, independent_variable = t)\n\n\nres_koopman = solve(dd_prob, Ψ, DMDPINV())\nsys_koopman = result(res_koopman);\n\n\nequations(sys_koopman)\n\n\nparameter_map(res_koopman)\n\n\nres_sindy = solve(dd_prob, Ψ, STLSQ(),digits=1)\nsys_sindy = result(res_sindy);\n\n\nequations(sys_sindy)\n\n\nparameter_map(res_sindy)\n\n\nsir_data = Array(sir_sol);\n\n\nA = 500.0 # Smaller values of A = noisier data\nnoisy_data = sir_data\n# Note that we can't draw from u0 as R(0)=0\nfor i in 2:size(sir_data)[2]\n noisy_data[1:3,i] = rand(Dirichlet(A*sir_data[1:3,i]))\nend;\n\n\nscatter(sir_sol.t,noisy_data',title=\"Noisy data\",xlabel=\"Time\",ylabel=\"Proportion\",labels=[\"S+noise\" \"I+noise\" \"R+noise\"])\nplot!(sir_sol,labels=[\"S\" \"I\" \"R\"],legend=:left)\n\n\nnoisy_dd_prob = ContinuousDataDrivenProblem(noisy_data,sir_sol.t,GaussianKernel());\n\n\nnoisy_res_koopman = solve(noisy_dd_prob, Ψ, DMDPINV())\nnoisy_sys_koopman = result(noisy_res_koopman)\nequations(noisy_sys_koopman), parameter_map(noisy_res_koopman)\n\n\nnoisy_res_sindy = solve(noisy_dd_prob, Ψ, STLSQ())\nnoisy_sys_sindy = result(noisy_res_sindy)\nequations(noisy_sys_sindy), parameter_map(noisy_res_sindy)\n\n\nA = 50.0 # Smaller values of A = noisier data\nv_noisy_data = sir_data\n# Note that we can't draw from u0 as R(0)=0\nfor i in 2:size(sir_data)[2]\n v_noisy_data[1:3,i] = rand(Dirichlet(A*sir_data[1:3,i]))\nend;\n\n\nscatter(sir_sol.t,v_noisy_data',title=\"Very noisy data\",xlabel=\"Time\",ylabel=\"Proportion\",labels=[\"S+noise\" \"I+noise\" \"R+noise\"])\nplot!(sir_sol,labels=[\"S\" \"I\" \"R\"],legend=:left)\n\n\nv_noisy_dd_prob = ContinuousDataDrivenProblem(v_noisy_data,sir_sol.t,GaussianKernel())\nv_noisy_res_sindy = solve(v_noisy_dd_prob, Ψ, STLSQ())\nv_noisy_sys_sindy = result(v_noisy_res_sindy)\nequations(v_noisy_sys_sindy), parameter_map(v_noisy_res_sindy)\n\n", "meta": {"hexsha": "fd38386e26c88bdd68329f4b54a74df84d528692", "size": 2317, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/ode_ddeq/ode_ddeq.jl", "max_stars_repo_name": "Song921012/sir-julia", "max_stars_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "script/ode_ddeq/ode_ddeq.jl", "max_issues_repo_name": "Song921012/sir-julia", "max_issues_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/ode_ddeq/ode_ddeq.jl", "max_forks_repo_name": "Song921012/sir-julia", "max_forks_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.2568807339, "max_line_length": 129, "alphanum_fraction": 0.7220543807, "num_tokens": 804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541561135441, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.8112710405828997}} {"text": "\"\"\"\n to_cartesian(lat::T, lon::T, r::T) where {T} \n to_cartesian(location::GeoLocation)\n to_cartesian(locations::Vector{GeoLocation})\n\nConverts a vector of GeoLocations to (x, y, z) cartesian coordinates (based on radius of the Earth).\n\"\"\"\nfunction to_cartesian(lat::T, lon::T, r::T) where {T} \n x = r * cos(lat) * cos(lon)\n y = r * cos(lat) * sin(lon)\n z = r * sin(lat)\n return x, y, z\nend\nfunction to_cartesian(loc::GeoLocation)\n lat = deg2rad(loc.lat)\n lon = deg2rad(loc.lon)\n r = loc.alt + RADIUS_OF_EARTH_KM # approximate radius of earth + alt in km\n x, y, z = to_cartesian(lat, lon, r)\n return x, y, z\nend\nfunction to_cartesian(locs::Vector{GeoLocation})\n n_points = length(locs)\n results = Matrix{Float64}(undef, 3, n_points)\n @inbounds for i in 1:n_points\n x, y, z = to_cartesian(locs[i])\n results[1, i] = x\n results[2, i] = y\n results[3, i] = z\n end\n return results\nend\n\n\"\"\"\n haversine(a_lat::T, a_lon::T, b_lat::T, b_lon::T) where {T}\n haversine(GeoLocation, B::GeoLocation)\n haversine(Node, B::Node)\n haversine(A::Vector{GeoLocation}, B::Vector{GeoLocation})\n haversine(A::Vector{Node}, B::Vector{Node})\n haversine(a::Vector{U}, b::Vector{U})::U where {U <: AbstractFloat}\n\nCalculates the haversine distance (km) between two points.\n\"\"\"\n\nfunction haversine(a_lat::T, a_lon::T, b_lat::T, b_lon::T) where {T}\n d = sin((a_lat - b_lat) / 2)^2 + cos(b_lat) * cos(a_lat) * sin((a_lon - b_lon) / 2)^2\n return 2 * RADIUS_OF_EARTH_KM * asin(sqrt(d))\nend\nfunction haversine(A::GeoLocation, B::GeoLocation)\n a_lat = deg2rad(A.lat)\n a_lon = deg2rad(A.lon)\n b_lat = deg2rad(B.lat)\n b_lon = deg2rad(B.lon)\n return haversine(a_lat, a_lon, b_lat, b_lon)\nend\nhaversine(a::Node, b::Node) = haversine(a.location, b.location)\nhaversine(A::Vector{<:GeoLocation}, B::Vector{<:GeoLocation}) = haversine.(A, B)\nhaversine(A::Vector{<:Node}, B::Vector{<:Node}) = haversine.(A, B)\nfunction haversine(a::Vector{U}, b::Vector{U})::U where {U <: AbstractFloat}\n a_lat = deg2rad(a[1])\n a_lon = deg2rad(a[2])\n b_lat = deg2rad(b[1])\n b_lon = deg2rad(b[2])\n return haversine(a_lat, a_lon, b_lat, b_lon)\nend\n\n\"\"\"\n euclidean(a_x::T, a_y::T, a_z::T, b_x::T, b_y::T, b_z::T) where {T}\n euclidean(A::GeoLocation, B::GeoLocation)\n euclidean(A::Node, B::Node)\n euclidean(A::Vector{GeoLocation}, B::Vector{GeoLocation})\n euclidean(A::Vector{<:Node}, B::Vector{<:Node})\n euclidean(a::Vector{U}, b::Vector{U})::U where {U <: AbstractFloat}\n\nCalculates the euclidean distance (km) between two points.\n\"\"\"\neuclidean(a_x::T, a_y::T, a_z::T, b_x::T, b_y::T, b_z::T) where {T} = hypot(a_x-b_x, a_y-b_y, a_z-b_z)\neuclidean(A::GeoLocation, B::GeoLocation) = euclidean(to_cartesian(A)...,to_cartesian(B)...)\neuclidean(a::Node, b::Node) = euclidean(a.location, b.location)\neuclidean(A::Vector{GeoLocation}, B::Vector{GeoLocation}) = euclidean.(A, B)\neuclidean(A::Vector{<:Node}, B::Vector{<:Node}) = euclidean.(A, B)\nfunction euclidean(a::Vector{U}, b::Vector{U})::U where {U <: AbstractFloat}\n a_lat = deg2rad(a[1])\n a_lon = deg2rad(a[2])\n b_lat = deg2rad(b[1])\n b_lon = deg2rad(b[2])\n return euclidean(\n to_cartesian(a_lat, a_lon, RADIUS_OF_EARTH_KM)...,\n to_cartesian(b_lat, b_lon, RADIUS_OF_EARTH_KM)...\n )\nend\n\n\"\"\"\n distance(A::Union{Vector{GeoLocation}, GeoLocation, Vector{<:Node}, Node, Vector{<:AbstractFloat}},\n B::Union{Vector{GeoLocation}, GeoLocation, Vector{<:Node}, Node, Vector{<:AbstractFloat}},\n type::Symbol=:haversine\n )\n\nCalculates the distance (km) between two points or two vectors of points.\n\n# Arguments\n- `A::Union{Vector{GeoLocation}, GeoLocation, Vector{<:Node}, Node, Vector{<:AbstractFloat}}`: Vector of origin points.\n- `B::Union{Vector{GeoLocation}, GeoLocation, Vector{<:Node}, Node, Vector{<:AbstractFloat}}`: Vector of destination points.\n- `method::Symbol=:haversine`: Either `:haversine` or `:euclidean`.\n\n# Return\n- Distance between origin and destination points in km.\n\"\"\"\nfunction distance(A::Union{Vector{GeoLocation},GeoLocation,Vector{<:Node},Node,Vector{<:AbstractFloat}},\n B::Union{Vector{GeoLocation},GeoLocation,Vector{<:Node},Node,Vector{<:AbstractFloat}},\n method::Symbol=:haversine\n )\n if method == :haversine\n return haversine(A, B)\n elseif method == :euclidean\n return euclidean(A, B)\n else\n throw(ArgumentError(\"Distance method $method not implemented\"))\n end\nend\n\n\"\"\"\n heading(a::GeoLocation, b::GeoLocation, return_units::Symbol=:degrees)\n heading(a::Node, b::Node, return_units::Symbol=:degrees)\n heading(A::Vector{GeoLocation}, B::Vector{GeoLocation}, return_units::Symbol=:degrees)\n heading(A::Vector{Node}, B::Vector{Node}, return_units::Symbol=:degrees)\n\nCalculates heading(s) / bearing(s) between two points (`a` is origin, `b` is destination)\nor two vectors of points (`A` is vector of origins, `B` is vector of destinations). Points\ncan be either `GeoLocation`s or `Node`s.\n\nDepending on the `return_units` chosen, the return angle is in range of [-π, π] if `:radians`\nor [-180, 180] if `:degrees`. Additionally, adjusts destination longitude in case the straight\nline path between a and b crosses the International Date Line.\n\"\"\"\nfunction heading(a::GeoLocation, b::GeoLocation, return_units::Symbol=:degrees)\n a_lat = a.lat\n a_lon = a.lon\n b_lat = b.lat\n b_lon = b.lon\n\n # Adjust destination longitude in case straight line path between A and B crosses the International Date Line\n a_lon_left_idx = (b_lon <= a_lon) * ((b_lon + 180) + (180 - a_lon) > (a_lon - b_lon))\n a_lon_right_idx = (b_lon <= a_lon) * ((b_lon + 180) + (180 - a_lon) <= (a_lon - b_lon))\n\n b_lon_left_idx = (b_lon > a_lon) * ((a_lon + 180) + (180 - b_lon) .< (b_lon - a_lon))\n b_lon_right_idx = (b_lon > a_lon) * ((a_lon + 180) + (180 - b_lon) >= (b_lon - a_lon))\n\n b_lon_fixed = b_lon_left_idx * (-180 - (180 - b_lon)) +\n b_lon_right_idx * b_lon +\n a_lon_left_idx * b_lon +\n a_lon_right_idx * (180 - abs(-180 - b_lon))\n\n a_lat = deg2rad(a_lat)\n a_lon = deg2rad(a_lon)\n b_lat = deg2rad(b_lat)\n b_lon_fixed = deg2rad(b_lon_fixed)\n\n y = sin(b_lon_fixed - a_lon) * cos(b_lat)\n x = cos(a_lat) * sin(b_lat) - sin(a_lat) * cos(b_lat) * cos(b_lon_fixed - a_lon)\n \n heading = atan.(y, x)\n\n if return_units == :radians\n return heading\n elseif return_units == :degrees\n return rad2deg(heading)\n else\n throw(ArgumentError(\"Incorrect input for argument `return_units`, choose either `:degrees` or `:radians`\"))\n end\nend\nheading(A::Vector{GeoLocation}, B::Vector{GeoLocation}, return_units::Symbol=:degrees) = heading.(A, B, return_units)\nheading(a::Node, b::Node, return_units::Symbol=:degrees)::AbstractFloat = heading(a.location, b.location, return_units)\nheading(A::Vector{<:Node}, B::Vector{<:Node}, return_units::Symbol=:degrees) = heading.(A, B, return_units)\n\n\"\"\"\n calculate_location(origin::GeoLocation, heading::Number, distance::Number)\n calculate_location(origin::Node, heading::Number, distance::Number)\n calculate_location(origin::Vector{GeoLocation}, heading::Vector{<:Number}, distance::Vector{<:Number})\n calculate_location(origin::Vector{Node}, heading::Vector{<:Number}, distance::Vector{<:Number})\n\nCalculates next location(s) given origin `GeoLocation`(s) or `Node`(s), heading(s) (degrees)\nand distance(s) (km).\n\nLocations are returned as `GeoLocation`s.\n\"\"\"\nfunction calculate_location(origin::GeoLocation, heading::Number, distance::Number)\n lat = deg2rad(origin.lat)\n lon = deg2rad(origin.lon)\n heading = deg2rad(heading)\n\n lat_final = asin(sin(lat) * cos(distance / RADIUS_OF_EARTH_KM) + cos(lat) * sin(distance / RADIUS_OF_EARTH_KM) * cos(heading))\n lon_final = lon + atan(sin(heading) * sin(distance / RADIUS_OF_EARTH_KM) * cos(lat), cos(distance / RADIUS_OF_EARTH_KM) - sin(lat) * sin(lat_final))\n\n return GeoLocation(rad2deg(lat_final), rad2deg(lon_final))\nend\ncalculate_location(origins::Vector{GeoLocation}, headings::Vector{<:Number}, distances::Vector{<:Number}) = calculate_location.(origins, headings, distances)\ncalculate_location(origin::Node, heading::Number, distance::Number)::GeoLocation = calculate_location(origin.location, heading, distance)\ncalculate_location(origins::Vector{<:Node}, headings::Vector{<:Number}, distances::Vector{<:Number}) = calculate_location.(origins, headings, distances)\n\n\"\"\"\n bounding_box_from_point(point::GeoLocation, radius::Number)::NamedTuple\n\nCalculates the coordinates of the bounding box given a centroid point and radius (km).\n\n# Arguments\n- `point::GeoLocation`: Centroid of the bounding box as an GeoLocation.\n- `radius::Number`: Radius in km of the bounding box (to each corner).\n\n# Return\n- `NamedTuple`: Named tuple with attributes minlat, minlon, maxlat, right_lon.\n\"\"\"\nfunction bounding_box_from_point(point::GeoLocation, radius::Number)::NamedTuple\n bottom_left, top_right = calculate_location([point, point], [225, 45], [radius, radius])\n return (minlat = bottom_left.lat, minlon = bottom_left.lon, maxlat = top_right.lat, maxlon = top_right.lon)\nend\n", "meta": {"hexsha": "51ff304dc828452d29d8bce888e75df89b8696f0", "size": 9313, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/geometry.jl", "max_stars_repo_name": "fbanning/LightOSM.jl", "max_stars_repo_head_hexsha": "f02c0261b4765ffdb40ccf9b9c0ff41418aa5af5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 33, "max_stars_repo_stars_event_min_datetime": "2020-09-15T06:42:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T20:47:50.000Z", "max_issues_repo_path": "src/geometry.jl", "max_issues_repo_name": "fbanning/LightOSM.jl", "max_issues_repo_head_hexsha": "f02c0261b4765ffdb40ccf9b9c0ff41418aa5af5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 46, "max_issues_repo_issues_event_min_datetime": "2020-09-29T03:59:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T07:17:38.000Z", "max_forks_repo_path": "src/geometry.jl", "max_forks_repo_name": "fbanning/LightOSM.jl", "max_forks_repo_head_hexsha": "f02c0261b4765ffdb40ccf9b9c0ff41418aa5af5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-11-30T05:16:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T07:47:58.000Z", "avg_line_length": 43.1157407407, "max_line_length": 157, "alphanum_fraction": 0.6765811232, "num_tokens": 2759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541577509315, "lm_q2_score": 0.86153820232079, "lm_q1q2_score": 0.8112710302766352}} {"text": "module BarycentricLagrange\n# Reference:\n# Barycentric Lagrange Interpolation.\n# Berrut, J.-P., & Trefethen, L. N. (2004).\n# SIAM Review, 46(3), 501–517. doi:10.1137/S36144502417716\n\nexport bclag_interp_eval\nexport bclag_interp_matrix\nexport bclag_interp_weights\n\nusing Compat\n\nfunction bclag_interp_weight(x, j, n)\n p = 1.0\n for k=1:j-1\n p *= x[j] - x[k]\n end\n for k=j+1:n\n p *= x[j] - x[k]\n end \n return 1/p\nend\n\n\"\"\"\n w = bclag_interp_weights(x)\n\nCompute weights for Barycentric Lagrange interpolation.\n\"\"\"\nfunction bclag_interp_weights(x::Vector)\n n = length(x)\n w = zeros(n)\n for j=1:n\n w[j] = bclag_interp_weight(x, j, n)\n end\n return w\nend\n\nfunction bclag_interp_eval(x::Vector, f::Vector{T}, xx::Number,\n w::Vector = bclag_interp_weights(x)) where T\n n = length(x)\n @assert length(f) == length(w) == n\n numer = zero(T)\n denom = 0.0\n for j=1:n\n xdiff = xx-x[j]\n if xdiff==0\n return f[j]\n end\n tmp = w[j] / xdiff\n numer += f[j]*tmp\n denom += tmp\n end\n ff = numer/denom\n return ff\nend\n\n\"\"\"\n ff = bclag_interp_eval(x, f, xx [, w])\n\nBarycentric Lagrange interpolation of `f` from points `x` to points `xx`\n\n`w` is vector of weights, `w = bclag_interp_weights(x)` \n\"\"\"\nfunction bclag_interp_eval(x::Vector, f::Vector{T}, xx::Vector,\n w::Vector = bclag_interp_weights(x)) where T\n n = length(xx)\n ff = Array{T}(undef, n)\n for j=1:n\n ff[j] = bclag_interp_eval(x, f, xx[j], w)\n end\n return ff\nend\n\n\"\"\"\n M = bclag_interp_matrix(x, xx [, w])\n\nCompute the matrix `M` such that `ff = M*f` gives the barycentric Lagrange interpolation of `f` from points `x` to points `xx`.\n\n\n`w` is vector of weights, `w = bclag_interp_weights(x)` \n\"\"\"\nfunction bclag_interp_matrix(x::Vector, xx::Vector,\n w::Vector = bclag_interp_weights(x))\n n = length(x)\n N = length(xx)\n @assert length(w)==n\n B, denom, exact = matrix_alloc(n, N)\n compute_matrix!(B, denom, exact, x, xx, w) \n return B\nend\n\nfunction matrix_alloc(n, N)\n B = Array{Float64}(undef, N, n)\n denom = Array{Float64}(undef, N)\n exact = Array{Int64}(undef, N)\n return B, denom, exact\nend\n\nfunction compute_matrix!(B, denom, exact, x, xx, w)\n # No allocations or size checks done here\n N, n = size(B)\n fill!(denom, 0.0)\n fill!(exact, 0)\n for j=1:n\n for k=1:N\n xdiff = xx[k]-x[j]\n if xdiff != 0\n temp = w[j]/xdiff\n B[k,j] = temp\n denom[k] += temp\n else\n exact[k] = j\n end\n end\n end\n B ./= denom\n for jj=1:N\n if exact[jj] != 0\n @. B[jj,:] = 0.0\n B[jj + N*(exact[jj]-1)] = 1.0\n end\n end\nend\n\nend # module\n", "meta": {"hexsha": "ae46098cc3c8524d3c9a8ddcb600ba923c354b0b", "size": 2901, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/BarycentricLagrange.jl", "max_stars_repo_name": "ludvigak/BarycentricLagrange.jl", "max_stars_repo_head_hexsha": "d6d60b24dca217ca03dbb73aa7a5ac633d294e8f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/BarycentricLagrange.jl", "max_issues_repo_name": "ludvigak/BarycentricLagrange.jl", "max_issues_repo_head_hexsha": "d6d60b24dca217ca03dbb73aa7a5ac633d294e8f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-01-30T17:43:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-17T18:36:25.000Z", "max_forks_repo_path": "src/BarycentricLagrange.jl", "max_forks_repo_name": "ludvigak/BarycentricLagrange.jl", "max_forks_repo_head_hexsha": "d6d60b24dca217ca03dbb73aa7a5ac633d294e8f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0238095238, "max_line_length": 127, "alphanum_fraction": 0.5536022061, "num_tokens": 927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303724190573, "lm_q2_score": 0.8757869916479466, "lm_q1q2_score": 0.8112447519611512}} {"text": "\n#Import Turing, Distributions and DataFrames\nusing Turing, Distributions, DataFrames, Distributed\n\n# Import MCMCChain, Plots, and StatsPlots for visualizations and diagnostics.\nusing MCMCChains, Plots, StatsPlots\n\n# Set a seed for reproducibility.\nusing Random\nRandom.seed!(12);\n\n# Turn off progress monitor.\nTuring.setprogress!(false)\n\n\ntheta_noalcohol_meds = 1 # no alcohol, took medicine\ntheta_alcohol_meds = 3 # alcohol, took medicine\ntheta_noalcohol_nomeds = 6 # no alcohol, no medicine\ntheta_alcohol_nomeds = 36 # alcohol, no medicine\n\n# no of samples for each of the above cases\nq = 100\n\n#Generate data from different Poisson distributions\nnoalcohol_meds = Poisson(theta_noalcohol_meds)\nalcohol_meds = Poisson(theta_alcohol_meds)\nnoalcohol_nomeds = Poisson(theta_noalcohol_nomeds)\nalcohol_nomeds = Poisson(theta_alcohol_nomeds)\n\nnsneeze_data = vcat(rand(noalcohol_meds, q), rand(alcohol_meds, q), rand(noalcohol_nomeds, q), rand(alcohol_nomeds, q) )\nalcohol_data = vcat(zeros(q), ones(q), zeros(q), ones(q) )\nmeds_data = vcat(zeros(q), zeros(q), ones(q), ones(q) )\n\ndf = DataFrame(nsneeze = nsneeze_data, alcohol_taken = alcohol_data, nomeds_taken = meds_data, product_alcohol_meds = meds_data.*alcohol_data)\ndf[sample(1:nrow(df), 5, replace = false), :]\n\n\n#Data Plotting\n\np1 = Plots.histogram(df[(df[:,:alcohol_taken] .== 0) .& (df[:,:nomeds_taken] .== 0), 1], title = \"no_alcohol+meds\") \np2 = Plots.histogram((df[(df[:,:alcohol_taken] .== 1) .& (df[:,:nomeds_taken] .== 0), 1]), title = \"alcohol+meds\") \np3 = Plots.histogram((df[(df[:,:alcohol_taken] .== 0) .& (df[:,:nomeds_taken] .== 1), 1]), title = \"no_alcohol+no_meds\") \np4 = Plots.histogram((df[(df[:,:alcohol_taken] .== 1) .& (df[:,:nomeds_taken] .== 1), 1]), title = \"alcohol+no_meds\") \nplot(p1, p2, p3, p4, layout = (2, 2), legend = false)\n\n\n# Convert the DataFrame object to matrices.\ndata = Matrix(df[:,[:alcohol_taken, :nomeds_taken, :product_alcohol_meds]])\ndata_labels = df[:,:nsneeze]\ndata\n\n\n# # Rescale our matrices.\ndata = (data .- mean(data, dims=1)) ./ std(data, dims=1)\n\n\n# Bayesian poisson regression (LR)\n@model poisson_regression(x, y, n, σ²) = begin\n b0 ~ Normal(0, σ²)\n b1 ~ Normal(0, σ²)\n b2 ~ Normal(0, σ²)\n b3 ~ Normal(0, σ²)\n for i = 1:n\n theta = b0 + b1*x[i, 1] + b2*x[i,2] + b3*x[i,3]\n y[i] ~ Poisson(exp(theta))\n end\nend;\n\n\n# Retrieve the number of observations.\nn, _ = size(data)\n\n# Sample using NUTS.\n\nnum_chains = 4\nchain = mapreduce(\n c -> sample(poisson_regression(data, data_labels, n, 10), NUTS(200, 0.65), 2500, discard_adapt=false), \n chainscat, \n 1:num_chains);\n\n\ngelmandiag(chain)\n\n\n# Taking the first chain\nc1 = chain[:,:,1]\n\n# Calculating the exponentiated means\nb0_exp = exp(mean(c1[:b0]))\nb1_exp = exp(mean(c1[:b1]))\nb2_exp = exp(mean(c1[:b2]))\nb3_exp = exp(mean(c1[:b3]))\n\nprint(\"The exponent of the meaned values of the weights (or coefficients are): \\n\")\nprint(\"b0: \", b0_exp, \" \\n\", \"b1: \", b1_exp, \" \\n\", \"b2: \", b2_exp, \" \\n\", \"b3: \", b3_exp, \" \\n\")\nprint(\"The posterior distributions obtained after sampling can be visualised as :\\n\")\n\n\nplot(chain)\n\n\n# Note the standard deviation before removing the warmup samples\ndescribe(chain)\n\n\n# Removing the first 200 values of the chains.\nchains_new = chain[201:2500,:,:]\ndescribe(chains_new)\n\n\nplot(chains_new)\n\n\nif isdefined(Main, :TuringTutorials)\n Main.TuringTutorials.tutorial_footer(WEAVE_ARGS[:folder], WEAVE_ARGS[:file])\nend\n\n", "meta": {"hexsha": "04f4c3bc7dbc3ebb7216c9111d6d2a3974ca0073", "size": 3450, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/07-poisson-regression/07_poisson-regression.jl", "max_stars_repo_name": "leachim/TuringTutorials", "max_stars_repo_head_hexsha": "a33397508d66ce40992863b1e12145b4cfc781b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 154, "max_stars_repo_stars_event_min_datetime": "2018-08-13T17:04:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T06:28:19.000Z", "max_issues_repo_path": "script/07-poisson-regression/07_poisson-regression.jl", "max_issues_repo_name": "leachim/TuringTutorials", "max_issues_repo_head_hexsha": "a33397508d66ce40992863b1e12145b4cfc781b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 137, "max_issues_repo_issues_event_min_datetime": "2018-09-06T21:56:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T07:36:07.000Z", "max_forks_repo_path": "script/07-poisson-regression/07_poisson-regression.jl", "max_forks_repo_name": "leachim/TuringTutorials", "max_forks_repo_head_hexsha": "a33397508d66ce40992863b1e12145b4cfc781b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 82, "max_forks_repo_forks_event_min_datetime": "2018-09-17T15:57:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T04:54:57.000Z", "avg_line_length": 29.2372881356, "max_line_length": 142, "alphanum_fraction": 0.6904347826, "num_tokens": 1115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465188527685, "lm_q2_score": 0.8670357632379241, "lm_q1q2_score": 0.8109788828654455}} {"text": "\n@doc raw\"\"\"\n general_form(xi::Point2D, xo::Point2D)\n\nReturns the general form equation of a line that passes through points `xi` and `xo` as a\n[`SVector`](@ref) which holds A, B and C such that:\n```math\nA \\cdot x + B \\cdot y + C = 0.\n```\n\"\"\"\nfunction general_form(xi::Point2D, xo::Point2D)\n A = xi[2] - xo[2]\n B = xo[1] - xi[1]\n C = xi[1] * xo[2] - xo[1] * xi[2]\n ABC = SVector(A, B, C)\n ABC /= norm(ABC) # for numerical reasons (?)\n return ABC\nend\n# the function above is faster than using linear algebra:\n# [x1 y1; x2 y2] ⋅ [Â, B̂] = [-1, -1] yields to solution for  and B̂ such that\n#  ⋅ x + B̂ ⋅ y + 1 = 0. Here we make it faster.\n# F = transpose(hcat(xi, xo))\n# b = SVector(-1, -1)\n# x = F \\ b\n# ABC = vcat(b, 1) # and then we can normalize\n\n# We could use LazySets.jl for some part of this particular function but it seems slow!\n\"\"\"\n intersections(mesh::Mesh, cell_id::Int, track::Track)\n\nComputes the entry and exit points of a given `track` that is known to cross element with id\n`cell_id`.\n\"\"\"\nfunction intersections(\n mesh::Mesh, cell_id::Int32, track::Track{BIn,BOut,DFwd,DBwd,T}\n) where {BIn,BOut,DFwd,DBwd,T}\n @unpack model, cell_nodes = mesh\n\n node_coordinates = get_node_coordinates(get_grid(model))\n node_ids = cell_nodes[cell_id]\n\n int_points = MVector{4,Point2D{T}}(\n Point2D(0, 0), Point2D(0, 0), Point2D(0, 0), Point2D(0, 0)\n )\n\n n_int = 0\n parallel_found = false\n for i in eachindex(node_ids)\n\n j = i == lastindex(node_ids) ? 1 : i + 1\n\n # get node coordinates and cast them to Point2D\n p1 = convert(Point2D{T}, node_coordinates[node_ids[i]])\n p2 = convert(Point2D{T}, node_coordinates[node_ids[j]])\n\n # compute general form equation for the selected element face\n ABC = general_form(p1, p2)\n\n # compute intersections between track and element face\n are_parallel, x_int = intersection(track.ABC, ABC)\n\n # if the track is parallel to the element face, it can be on top of it or do not\n # cross at all. Either way, we just ignore this case because we can compute the\n # intersections using the other faces.\n if are_parallel\n parallel_found = true\n continue\n\n # if the intersection is outside the face, avoid it\n elseif !point_in_segment(p1, p2, x_int)\n continue\n\n # this is a valid intersection, store it\n else\n n_int += 1\n int_points[n_int] = x_int\n end\n end\n\n # now let's check all the possible situations and handle extreme cases\n if n_int in (3, 4)\n ℓ = zero(T)\n # get the points that have the maximun distance between\n for i in 2:n_int, j in i:n_int\n x1 = int_points[i-1]\n x2 = int_points[j]\n ℓi = norm(x1 - x2)\n if ℓi > ℓ\n x_int1 = x1\n x_int2 = x2\n ℓ = ℓi\n end\n end\n return order_intersection_points(track, x_int1, x_int2)\n\n elseif n_int == 2 && parallel_found\n\n x_int1 = int_points[1]\n x_int2 = int_points[2]\n return order_intersection_points(track, x_int1, x_int2)\n\n elseif n_int == 2 && !parallel_found\n\n x_int1 = int_points[1]\n x_int2 = int_points[2]\n\n if isapprox(x_int1, x_int2)\n # do nothing and move a tiny step forward in the parent function, we are on a\n # vertex\n return x_int1, x_int2\n else\n return order_intersection_points(track, x_int1, x_int2)\n end\n elseif iszero(n_int) || isone(n_int)\n # the parent function will move a tiny step further\n return Point2D{T}(0, 0), Point2D{T}(0, 0)\n # error(\"This is an unexpected case. Please, submit an issue.\")\n end\nend\n\n\"\"\"\n intersection(ABC1, ABC2)\n\nComputes the intersection between two lines with general form equations given by `ABC1` and\n`ABC2`. It also indicates if the lines are parallel.\n\"\"\"\nfunction intersection(ABC1::AbstractVector, ABC2::AbstractVector)\n a = ABC1[2] * ABC2[1]\n b = ABC2[2] * ABC1[1]\n x = y = zero(a)\n are_parallel = isapprox(a, b)\n if !are_parallel\n det = a - b\n x = (ABC1[3] * ABC2[2] - ABC2[3] * ABC1[2]) / det\n y = (ABC1[1] * ABC2[3] - ABC2[1] * ABC1[3]) / det\n end\n return are_parallel, Point2D(x, y)\nend\n\n# this one returns a matrix even if F is not invertible (have the same speed as the above)\n# function intersection(ABC1, ABC2)\n# F = @SMatrix [ABC1[1] ABC1[2]\n# ABC2[1] ABC2[2]]\n# b = @SVector [ABC1[3], ABC2[3]]\n\n# x = F \\ (-b)\n\n# return Point2D(x[1], x[2])\n# end\n\nfunction order_intersection_points(track::Track, x1::Point2D, x2::Point2D)\n @unpack ϕ = track\n\n if isless(ϕ, π/2)\n if x1[1] < x2[1]\n xi = x1\n xo = x2\n else\n xi = x2\n xo = x1\n end\n else\n if x1[1] > x2[1]\n xi = x1\n xo = x2\n else\n xi = x2\n xo = x1\n end\n end\n return xi, xo\nend", "meta": {"hexsha": "83a7b835791560f869ac4a124da718132d7550da", "size": 5096, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/intersection.jl", "max_stars_repo_name": "rvignolo/RayTracing.jl", "max_stars_repo_head_hexsha": "5be74ee6067a722ab6378652c4cc948d533d540f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2020-12-17T17:58:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-17T19:29:48.000Z", "max_issues_repo_path": "src/intersection.jl", "max_issues_repo_name": "rvignolo/RayTracing.jl", "max_issues_repo_head_hexsha": "5be74ee6067a722ab6378652c4cc948d533d540f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-15T18:55:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-17T17:28:46.000Z", "max_forks_repo_path": "src/intersection.jl", "max_forks_repo_name": "rvignolo/RayTracing.jl", "max_forks_repo_head_hexsha": "5be74ee6067a722ab6378652c4cc948d533d540f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6279069767, "max_line_length": 92, "alphanum_fraction": 0.5845761381, "num_tokens": 1557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475794701961, "lm_q2_score": 0.8596637469145053, "lm_q1q2_score": 0.8109617148100778}} {"text": "#=\nCompute the running median of a sequence of numbers. That is, given a stream of numbers, print out the median of the list so far on each new element.\n\nRecall that the median of an even-numbered list is the average of the two middle numbers.\n\nFor example, given the sequence [2, 1, 5, 7, 2, 0, 5], your algorithm should print out:\n\n2\n1.5\n2\n3.5\n2\n2\n2\n=#\n\nfunction print_running_median(arr::Array; store = false)\n if store\n median_arr = []\n end\n for index in 1:length(arr)\n current_arr = sort(arr[1:index])\n if length(current_arr) % 2 == 0\n median = (current_arr[Int8(length(current_arr)/2)] + current_arr[Int8(length(current_arr)/2 + 1)]) / 2\n println(median)\n if store\n push!(median_arr, median)\n end\n else\n median = current_arr[ceil(Int8, length(current_arr)/2)]\n println(median)\n if store\n push!(median_arr, median)\n end\n end\n end\n if store\n return median_arr\n end\nend\n", "meta": {"hexsha": "d8c0420778b76e37bf9e75d3be5ca05468013d93", "size": 1051, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/problem33_running_median.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/problem33_running_median.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/problem33_running_median.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": 25.6341463415, "max_line_length": 149, "alphanum_fraction": 0.6003805899, "num_tokens": 275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.900529786117893, "lm_q2_score": 0.900529776774399, "lm_q1q2_score": 0.8109538872714436}} {"text": "using Statistics\n\n\"\"\"\n mse(y, t; back = false)\nReturn the mean square error:\n mean((y .- t) .^ 2)\n# Example\n```\njulia> loss = mse\nmse (generic function with 1 method)\n\njulia> y, t = [1, 3, 2, 5], [1, 2, 3, 4]\n([1, 3, 2, 5], [1, 2, 3, 4])\n\njulia> loss(y, t)\n0.75\n```\n\"\"\"\nfunction mse(y, t; back = false)\n if back == true\n return 2(y .- t)\n end\n return mean((y .- t) .^ 2)\nend", "meta": {"hexsha": "e8d1a3b8f9dbdebae403bfd7c981d122fdaaeb5c", "size": 396, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NeuralNetwork/LossFunctions.jl", "max_stars_repo_name": "QGMW22/Horse.jl", "max_stars_repo_head_hexsha": "77be589dbf047a029615dde7773360ebcb5d99b6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-19T13:09:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-19T13:09:53.000Z", "max_issues_repo_path": "src/NeuralNetwork/LossFunctions.jl", "max_issues_repo_name": "QGMW22/Horse", "max_issues_repo_head_hexsha": "77be589dbf047a029615dde7773360ebcb5d99b6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-21T13:52:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-21T13:52:40.000Z", "max_forks_repo_path": "src/NeuralNetwork/LossFunctions.jl", "max_forks_repo_name": "QGMW22/Horse", "max_forks_repo_head_hexsha": "77be589dbf047a029615dde7773360ebcb5d99b6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.5, "max_line_length": 40, "alphanum_fraction": 0.5176767677, "num_tokens": 167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632329799585, "lm_q2_score": 0.8519528057272544, "lm_q1q2_score": 0.8109425520058908}} {"text": "using Plots\nimport Distributions\nusing Random\nusing Turing\nusing Statistics\nusing StatsPlots\nusing FillArrays\n\ndataerr = 1.0\nd = Cauchy(0,dataerr)\n\nx = 0:10\ny = 10.0 .* exp.(-x*0.1) .+ rand(d,length(x))\n\nscatter(x,y,label=false)\n#plot!(x_fit,y_fit,label=false)\n\n@model function linear_fit(x,y)\n σ ~ Uniform(0.0,20.0)\n b ~ Uniform(-100.0,100.0)\n m ~ Uniform(-100.0,100.0)\n for i in 1:length(x)\n y[i] ~ Cauchy(b+m*x[i],σ)\n end\nend\n\nmodel_fit = linear_fit(x,y)\nchain = sample(model_fit,NUTS(0.65),1000)\nplot(chain)\n\nmean(vec(chain[:b]))\nstd(vec(chain[:b]))\n\nmean(vec(chain[:m]))\nstd(vec(chain[:m]))\n\n@model function nonlinear_fit(x,y,f)\n σ ~ Uniform(0.0,20.0)\n b ~ Uniform(0.0,100.0)\n m ~ Uniform(0.0,1.0)\n for i in 1:length(x)\n y[i] ~ Cauchy(f(x[i],b,m),σ)\n end\nend\n\nfunction f(x,b,m)\n b*exp(-x*m)\nend\n\nmodel_nonlinear = nonlinear_fit(x,y,f)\nchain2 = sample(model_nonlinear,NUTS(0.65),1000)\n\nplot(chain2)", "meta": {"hexsha": "7db5325f6dec52ced2b91ffab0cce908a5c0442d", "size": 949, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "turing_lstsqr.jl", "max_stars_repo_name": "hstrey/BME-502-2022", "max_stars_repo_head_hexsha": "01ae3787874a13adbed69cb16913f73594107f33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "turing_lstsqr.jl", "max_issues_repo_name": "hstrey/BME-502-2022", "max_issues_repo_head_hexsha": "01ae3787874a13adbed69cb16913f73594107f33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "turing_lstsqr.jl", "max_forks_repo_name": "hstrey/BME-502-2022", "max_forks_repo_head_hexsha": "01ae3787874a13adbed69cb16913f73594107f33", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-02-15T18:19:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T18:26:08.000Z", "avg_line_length": 17.9056603774, "max_line_length": 48, "alphanum_fraction": 0.6375131718, "num_tokens": 344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632302488963, "lm_q2_score": 0.8519528038477824, "lm_q1q2_score": 0.8109425478901544}} {"text": "#Find Volumes of Various Shapes.\n#Wikipedia reference: https://en.wikipedia.org/wiki/Volume\n# contributed By:- [Qingyu Qu](https://github.com/ErikQQY)\n\n\"\"\"\n vol_cube()\n\nCompute the volume of a cube.\n\n# Examples\n\n```julia-repl\njulia> vol_cube(1)\n1\njulia> vol_cube(3)\n27\njulia> vol_cube(-1)\nDomainError\n```\n\"\"\"\nfunction vol_cube(side)\n if side<0\n throw(DomainError(\"vol_cube() only works for non negative values.\"))\n end\n return side^3\nend\n\n\"\"\"\n vol_cuboid(width, height, length)\n\nCompute the volume of a vol_cuboid\n\n# Examples\n\n```julia-repl\njulia> vol_cuboid(1, 1, 1)\n1\njulia> vol_cuboid(1, 2, 3)\n6\n```\n\"\"\"\nfunction vol_cuboid(width, height, length)\n if width < 0 || height <0 || length < 0\n throw(DomainError(\"vol_cuboid() only works for non negative values.\"))\n end\n return width*height*length\nend\n\n\"\"\"\n vol_cone(area_of_base, height)\n\nCompute the Volume of a Cone\n\n\n# Examples\n\n```julia-repl\njulia> vol_cone(10, 3)\n10.0\njulia> vol_cone(1, 1)\n0.3333333333333333\n```\n\"\"\"\nfunction vol_cone(area_of_base, height)\n if area_of_base < 0 || height <0\n throw(DomainError(\"vol_cone() only works for non negative values.\"))\n end\n return area_of_base*height/3.0\nend\n\n\"\"\"\n vol_right_circ_cone(radius, height)\n\nCompute the Volume of a Right Circular Cone.\n\n# Examples\n\n```julia-repl\njulia> vol_right_circ_cone(2, 3)\n12.566370614359172\n```\n\"\"\"\nfunction vol_right_circ_cone(radius, height)\n if radius < 0 || height < 0\n throw(DomainError(\"vol_right_circ_cone() only works for non negative values.\"))\n end\n return π*radius^2*height/3.0\nend\n\n\"\"\"\n vol_prism(area_of_base, height)\n\nCompute the Volume of a Prism.\n\n# Examples\n\n```julia-repl\njulia> vol_prism(10, 2)\n20.0\njulia> vol_prism(11, 1)\n11.0\n```\n\"\"\"\nfunction vol_prism(area_of_base, height)\n if area_of_base < 0 || height < 0\n throw(DomainError(\"vol_prism() only works for non negative values.\"))\n end\n return area_of_base*height\nend\n\n\"\"\"\n vol_pyramid(area_of_base, height)\n\nCompute the volume of a Pyramid.\n\n# Examples\n\n```julia-repl\njulia> vol_pyramid(10, 3)\n10.0\njulia> vol_pyramid(1.5, 3)\n1.5\n```\n\"\"\"\nfunction vol_pyramid(area_of_base, height)\n if area_of_base < 0 || height < 0\n throw(DomainError(\"vol_pyramid() only works for non negative values.\"))\n end\n return area_of_base*height/3.0\nend\n\n\"\"\"\n vol_sphere(radius)\n\nCompute the volume of a sphere.\n\n# Examples\n\n```julia\nvol_sphere(5) # returns 523.5987755982989\nvol_sphere(1) # returns 4.1887902047863905\nvol_sphere(-1) # returns DomainError\n```\n\"\"\"\nfunction vol_sphere(radius)\n if radius < 0\n throw(DomainError(\"vol_sphere() only works for non negative values.\"))\n end\n return 4/3*pi*(radius)^3\nend\n\n\"\"\"\n vol_circular_cylinder(area_of_, height)\n\nCompute the Volume of a Circular Cylinder.\n\n# Examples\n\n```julia-repl\njulia> vol_circular_cylinder(1, 1)\n3.141592653589793\njulia> vol_circular_cylinder(4, 3)\n150.79644737231007\n\"\"\"\nfunction vol_circular_cylinder(radius, height)\n if radius < 0 || height < 0\n throw(DomainError(\"vol_circular_cylinder() only works for non negative values.\"))\n end\n return pi*radius^2*height\nend", "meta": {"hexsha": "ed418948ba79bf454a80628e129e45eaa420d8e7", "size": 3172, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/volume.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/volume.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/volume.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": 18.6588235294, "max_line_length": 89, "alphanum_fraction": 0.6935687264, "num_tokens": 992, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632261523028, "lm_q2_score": 0.8519527963298947, "lm_q1q2_score": 0.8109425372440493}} {"text": "import FractionalCalculus.FracIntAlg\n\n\n\"\"\"\nRiemann-Liouville sense fractional integral algorithms\n\nNote this two algorithms belong to direct compute, precise are ensured, but maybe cause more memory allocation and take more compilation time.\n\"\"\"\nabstract type RLInt <: FracIntAlg end\n\n\"\"\"\n# Riemann Liouville sense fractional integral\n\n fracint(f::Function, α, start_point, end_point, h, RL_Direct())\n\nRiemann_Liouville fractional integral using complex step differentiation.\n\n```math\n(J^αf)(t)=\\\\frac{1}{\\\\Gamma(α)} \\\\int_0^t(t-τ)^{α-1}f(τ)dτ\n```\n\nBy using [QuadGK](https://github.com/JuliaMath/QuadGK.jl) calculate the integration and obtain the value.\n\n### Example: \n\n```julia-repl\njulia> fracint(x->x^5, 0.5, 0, 2.5, 1e-8, RL_Direct())\n```\n\nReturns a tuple (1.1639316474512205, 1.0183453796725215e-8), which contains the value of this derivative is 1.1639316474512205, and the error estimate is 1.0183453796725215e-8\n\"\"\"\nstruct RL_Direct <: RLInt end\n\n\"\"\"\n# Riemann Liouville sense fractional integral with first diff known.\n\n fracint(f, fd, α, start_point, end_point, RL_Direct_First_Diff_Known())\n\n### Example\n\n```julia-repl\njulia> fracint(x->x^5, x->5*x^4, 0.5, 0, 2.5, RL_Direct_First_Diff_Known())\n```\n\nWith first derivative known, we can use the Riemann Liouville sense to obtain the fractional integral more effcient.\n\"\"\"\nstruct RL_Direct_First_Diff_Known <: RLInt end\n\n\"\"\"\n@article{LI20113352,\ntitle = {Numerical approaches to fractional calculus and fractional ordinary differential equation},\nauthor = {Changpin Li and An Chen and Junjie Ye},\n}\n\"\"\"\n\n\"\"\"\n# Riemann Liouville sense fractional integral using piecewise interpolation.\n \n fracint(f, α, end_point, h, RL_Piecewise())\n \n### Example\n \n```julia-repl\njulia> fracint(x->x^5, 0.5, 2.5, 0.0001, RL_Piecewise())\n```\n \nBy deploying Piecewise interpolation to approximate the original function, with small step size, this method is fast and take little memory allocation.\n\nUsing piecewise linear interpolation:\n\n```math\n y_n(t)=\\\\frac{t-t_{i+1}}{t_i-t_{i+1}}y(t_i)+\\\\frac{t-t_i}{t_{i+1}-t_i}y(t_{i+1})\n```\n \nConstitute the original function with the interpolation and implement the summation.\n\"\"\"\nstruct RL_Piecewise <: RLInt end\n\n\n\"\"\"\n@book{oldham_spanier_1984,\ntitle={The fractional calculus: Theory and applications of differentiation and integration to arbitrary order},\nauthor={Oldham, Keith B. and Spanier, Jerome},\nyear={1984}}\n\"\"\"\n\n\"\"\"\n# Riemann Liouville sense fractional integral approximation.\n\n fracint(f, α, end_point, h, RLInt_Approx())\n\n### Example\n\n```julia-repl\njulia> fracint(x->x^5, 0.5, 2.5, 0.0001, RLInt_Approx())\n```\n\nUsing the **Staircase approximation** to approximate the original function and implement the summation.\n\"\"\"\nstruct RLInt_Approx <: RLInt end\n\n\n\"\"\"\n# Riemann Liouville sense fractional integral using **Linear interpolation**.\n\n fracint(f, α, end_point, h, RL_LinearInterp())\n\n### Example\n\n```julia-repl\njulia> fracint(x->x^5, 0.5, 2.5, 0.0001, RL_LinearInterp())\n```\n\n**RL_LinearInterp** is more complex compared with *RLInt_Approx* but more precise.\n\nDeploying the [Linear Interpolation](https://en.wikipedia.org/wiki/Linear_interpolation) between ``f_{j+1}`` and ``f_j``, **RL_LinearInterp** method is more precise than **RLInt_Approx**.\n\"\"\"\nstruct RL_LinearInterp <: RLInt end\n\n\n\"\"\"\n@article{2009,\ntitle={Matrix approach to discrete fractional calculus II: Partial fractional differential equations},\nDOI={10.1016/j.jcp.2009.01.014},\nauthor={Podlubny, Igor and Chechkin, Aleksei and Skovranek, Tomas and Chen, YangQuan and Vinagre Jara, Blas M.},\n}\n\n\"\"\"\n\n\"\"\"\n# Riemann Liouville sense integral using Triangular Strip Matrix to discrete.\n\n fracint(f, α, end_point, h, RLInt_Matrix())\n\nUsing Triangular Strip Matrix to approximate fractional integral.\n\n### Example\n\n```julia-repl\njulia> fracint(x->x^5, 0.5, 2.5, 0.0001, RLInt_Matrix())\n```\n\n!!! info\n Triangular Strip Matrix method returns the derivative in the interval ``[0, T]`` in ```Vector```\n\n!!! tip\n With the advancing Triangular Strip Matrix method, you can not only compute fractional integrals, integer order, higher order integral is also supported!!\nTry to set α as an integer, arbitrary integer of course! I promise you would enjoy it😏\n\nUsing [Triangular Strip Matrix](https://en.wikipedia.org/wiki/Triangle_strip) to discrete the integral.\n\"\"\"\nstruct RLInt_Matrix <: RLInt end\n\n\n\"\"\"\n# Riemann Liouville sense fractional integral using fractional Simpson's formula to approximate.\n\n### Example\n\n```julia-repl\njulia> fracint(x->x, 0.5, 1, 0.001, RLInt_Simpson)\n```\n\n@inproceedings{Li2015NumericalMF,\n title={Numerical Methods for Fractional Calculus},\n author={Changpin Li and Fanhai Zeng},\n year={2015}\n}\n\nUsing fractional Simpson's formula to discrete fractional integral.\n\"\"\"\nstruct RLInt_Simpson <: RLInt end\n\n\n\"\"\"\n# Riemann Liouville sense fractional integral using fractional trapezoidal formula to approximate.\n\n### Example\n\n```julia-repl\njulia> fracint(x->x, 0.5, 1, 0.001, RLInt_Trapezoidal())\n```\n\n《Numerical methods for fractional calculus》.\nUsing Trapezoidal method to approximate fractional integral\n\"\"\"\nstruct RLInt_Trapezoidal <: RLInt end\n\n\n\"\"\"\n# Riemann Liouville sense fractional integral using fractional rectangular formula to approximate.\n\n### Example\n\n```julia-repl\njulia> fracint(x->x, 0.5, 1, 0.001, RLInt_Rectangular())\n```\n\"\"\"\nstruct RLInt_Rectangular <: RLInt end\n\n\"\"\"\n# Riemann Liouville sense fractional integral using cubic spline interpolation to approximate.\n\n### Example\n\n```julia-repl\njulia> fracint(x->x, 0.5, 1, 0.0001, RLInt_Cubic_Spline_Interp())\n```\n\nError estimate of this method is ``\\\\mathcal{O(h^4)}``, it is determined by the error of the cubic spline interpolation.\n\n!!! warning \"Set h as 0.001 or bigger\"\n For some reason, in the **RLInt_Cubic_Spline_Interp** method, set **h** as 0.001 would get better result.\n\n> Numerical Methods for Fractional Calculus Page 34\n\"\"\"\nstruct RLInt_Cubic_Spline_Interp <: RLInt end\n\n####################################\n### Type defination done ###\n####################################\n\n\n\n\"\"\"\nCheck if the format of nargins is correct\n\"\"\"\nfunction checks(f, α, start_point, end_point)\n α % 1 != 0 ? nothing : error(\"Decimal number only!\")\n if isa(end_point, Number)\n start_point < end_point ? nothing : DomainError(\"Domain error! Start point must smaller than end point\")\n elseif isa(end_point, AbstractArray)\n start_point < minimum(end_point) ? nothing : DomainError(\"Vector domain error! Start point must smaller than end point\")\n else\n ErrorException(\"Please input correct point you wan tto compute\")\n end\n\n #The fractional integral of number is relating with the end_point.\n if isa(f, Number)\n f == 0 ? 0 : 2*f*sqrt(end_point/pi)\n end\nend\n\nfunction fracint(f::Union{Function, Number}, α, start_point, end_point::Real, h, ::RL_Direct)\n #checks(f, α, start_point, end_point)\n \n temp1 = f(start_point) .* (end_point-start_point) .^α\n #Use Complex differentiation to obtain the differentiation\n g(τ) = imag(f(τ .+ 1*im*h) ./ h) .* (end_point-τ) .^α\n temp2 = quadgk(g, start_point, end_point)\n result = (temp1 .+ temp2) ./gamma(α+1)\n return result\nend\n\n\n\nfunction fracint(f::Function, fd::Function, α, start_point, end_point, ::RL_Direct_First_Diff_Known)\n #checks(f, α, start_point, end_point)\n \n #The fractional integral of number is relating with the end_point.\n if typeof(f) <: Number\n if f == 0\n return 0\n else\n return 2*f*sqrt(end_point/pi)\n end\n end\n \n temp1 = f(start_point) .* (end_point-start_point) .^α\n g(τ) = fd(τ) .* (end_point-τ) .^α\n temp2 = quadgk(g, start_point, end_point)\n result = (temp1 .+ temp2) ./ gamma(α+1)\n return result\nend\n\nfunction fracint(f::Union{Function, Number}, α::Float64, start_point, end_point::AbstractArray, ::RL_Direct_First_Diff_Known)::Vector\n ResultArray = Float64[]\n\n for (_, value) in enumerate(end_point)\n append!(ResultArray, fracint(f, α, start_point, value, RL_Direct_First_Diff_Known())[1])\n end\n return ResultArray\nend\n\n\n\nfunction fracint(f::Union{Function, Number}, α::Float64, end_point, h, ::RL_Piecewise)::Float64\n #checks(f, α, 0, end_point)\n\n #Init\n n = Int64(floor(end_point/h))\n result = zero(Float64)\n\n for i ∈ 0:n\n result += W(i, n, α)*f(i*h)\n end\n\n result1 = result*h^α/gamma(α+2)\n return result1\nend\nfunction W(i, n, α)\n if i == 0\n return n^α*(α+1-n) + (n-1)^(α+1)\n elseif i == n \n return 1\n else\n return (n-i-1)^(α+1) + (n-i+1)^(α+1) - 2*(n-i)^(α+1)\n end\nend\n\n\nfunction fracint(f::Union{Number, Function}, α::Float64, end_point::AbstractArray, h, ::RL_Piecewise)::Vector\n result = map(x->fracint(f, α, x, h, RL_Piecewise()), end_point)\n return result\nend\n\n\nfunction fracint(f::Union{Function, Number}, α::Float64, end_point, h, ::RLInt_Approx)::Float64\n #checks(f, α, 0, end_point)\n\n α = -α\n n = Int64(floor(end_point/h))\n result = zero(Float64)\n\n for i ∈ 0:n-1\n result += (f(end_point - i*h) + f(end_point - (i+1)*h))/2*((i+1)^(-α) - i^(-α))\n end\n\n result1 = result*end_point^(-α)*n^α/gamma(1-α)\n return result1\nend\n\nfunction fracint(f::Union{Function, Number}, α::Float64, end_point::AbstractArray, h, ::RLInt_Approx)::Vector\n ResultArray = Float64[]\n\n for (_, value) in enumerate(end_point)\n append!(ResultArray, fracint(f, α, value, h, RLInt_Approx())[1])\n end\n return ResultArray\nend\n\nfunction fracint(f::Union{Number, Function}, α::Float64, end_point::AbstractArray, h, ::RLInt_Approx)::Vector\n result = map(x->fracint(f, α, x, h, RLInt_Approx()), end_point)\n return result\nend\n\n\n\n\nfunction fracint(f::Union{Function, Number}, α::Float64, end_point::Number, h, ::RL_LinearInterp)::Float64\n\n α = -α\n n = Int64(floor(end_point/h))\n result = zero(Float64)\n \n for i ∈ 0:n-1\n result += ((i+1)*f(end_point-i*h)-i*f(end_point-(i+1)*h))/(-α)*((i+1)^(-α) - i^(-α))+(f(end_point - (i+1)*h) - f(end_point-i*h))/(1-α)*((i+1)^(1-α) - i^(1-α))\n end\n\n result1 = result*end_point^(-α)*n^α/gamma(-α)\n return result1\nend\n\nfunction fracint(f::Union{Number, Function}, α::Float64, end_point::AbstractArray, h, ::RL_LinearInterp)::Vector\n result = map(x->fracint(f, α, x, h, RL_LinearInterp()), end_point)\n return result\nend\n\n\n\n\nfunction fracint(f, α::Number, end_point, h::Float64, ::RLInt_Matrix)\n N = Int64(floor(end_point/h+1))\n tspan = collect(0:h:end_point)\n return J(N, α, h)*f.(tspan)\nend\n\nfunction omega(n, p)\n omega = zeros(n+1)\n\n omega[1]=1\n @fastmath @inbounds @simd for i ∈ 1:n\n omega[i+1]=(1-(p+1)/i)*omega[i]\n end\n \n return omega\n\nend\nfunction J(N, p, h::Float64)\n result=zeros(N, N)\n temp=omega(N, -p)\n\n @fastmath @inbounds @simd for i ∈ 1:N\n result[i, 1:i]=reverse(temp[1:i])\n end\n\n return h^p*result\nend\n\n\n#=\nRLInt_Simpson Algorithm\n=#\nfunction fracint(f, α, point, h, ::RLInt_Simpson)\n N = Int64(floor(point/h))\n temp1 = 0\n temp2 = 0\n\n @fastmath @inbounds @simd for i ∈ 0:N\n temp1 += cₖₙ(i, N, α)*f(i*h)\n end\n\n @fastmath @inbounds @simd for k ∈ 0:N-1\n temp2 += ĉₖₙ(k, N, α)*f((k+0.5)*h)\n end\n\n return h^α/gamma(α+3)*temp1 + 4*h^α/gamma(α+3)*temp2\nend\n\nfunction cₖₙ(k, n, α)\n if k == 0\n return 4*((n+1)^(2+α)-n^(2+α))-(α+2)*(3*(n+1)^(1+α)+n^(1+α))+(α+2)*(α+1)*(n+1)^α\n elseif 1 ≤ k ≤ n-1\n return -(α+2)*((n+1-k)^(1+α)+6*(n-k)^(1+α)+(n-k-1)^(1+α))+4*((n+1-k)^(2+α)-(n-1-k)^(2+α))\n elseif k == n\n return 2-α\n end\nend\nfunction ĉₖₙ(k, n, α)\n return ((α+2)*((n+1-k)^(1+α)+(n-k)^(1+α))-2*((n+1-k)^(2+α)-(n-k)^(2+α)))\nend\n\nfunction fracint(f::Union{Number, Function}, α::Float64, end_point::AbstractArray, h, ::RLInt_Simpson)::Vector\n result = map(x->fracint(f, α, x, h, RLInt_Simpson()), end_point)\n return result\nend\n\n#=\nRLInt_Trapezoidal Algorithm\n=#\nfunction fracint(f, α, point, h, ::RLInt_Trapezoidal)\n N = Int64(floor(point/h))\n result = zero(Float64)\n\n @fastmath @inbounds @simd for i ∈ 0:N\n result += aₖₙ(i, N, α)*f(i*h)\n end\n\n return h^α/gamma(α+2)*result\nend\n\nfunction aₖₙ(k, n, α)\n if k == 0\n return (n-1)^(α+1) - (n-1-α)*n^α\n elseif 1 ≤ k ≤ n-1\n return (n-k+1)^(α+1)+(n-1-k)^(α+1)-2*(n-k)^(α+1)\n else\n return 1\n end\nend\n\n\nfunction fracint(f, α, point, h, ::RLInt_Rectangular)\n N=Int64(floor(point/h))\n result = zero(Float64)\n\n @fastmath @inbounds @simd for i ∈ 0:N-1\n result += bₖ(N-i-1, α)*f(i*h)\n end\n\n return h^α/gamma(α+1)*result\nend\n\nfunction bₖ(k, α)\n return (k+1)^α-k^α\nend\n\nfunction fracint(f::Union{Number, Function}, α::Float64, end_point::AbstractArray, h, ::RLInt_Rectangular)::Vector\n result = map(x->fracint(f, α, x, h, RLInt_Rectangular()), end_point)\n return result\nend\n\n#=\nRLInt_Cubic_Spline_Interp Algorithm, when h is 0.01 behave best\n=#\nfunction fracint(f, α, point, h, ::RLInt_Cubic_Spline_Interp)\n N = Int64(floor(point/h))\n result = zero(Float64)\n\n @fastmath @inbounds @simd for j ∈ 0:N\n result += eⱼₙ(j, N, α)*f(j*h) + h*êⱼₙ(j, N, α)*first_order(f, j*h, h)\n end\n\n return h^α/gamma(α+4)*result\nend\n\nfunction eⱼₙ(j, n, α)\n if j == 0\n return -6*(n-1)^(2+α)*(1+2*n+α) + n^α*(12*n^3-6*(3+α)*n^2 + (1+α)*(2+α)*(3+α))\n elseif j == n\n return 6*(1+α)\n else\n return 6*(4*(n-j)^(3+α) + (n-j-1)^(2+α)*(2*j-2*n-1-α) + (1+n-j)^(2+α)*(2*j-2*n+1+α))\n end\nend\nfunction êⱼₙ(j, n, α)\n if j == 0\n return -2*(n-1)^(2+α)*(3*n+α) + n^(1+α)*(6*n^2-4*(3+α)*n + (2+α)*(3+α))\n elseif j == n\n return -2*α\n else\n return 2*(n-j-1)^(α+2)*(3*j-3*n-α)-2*(n-j+1)^(α+2)*(3*j-3*n+α) - (n-j)^(α+2)*(24+8α)\n end\nend\n\nfunction fracint(f::Union{Number, Function}, α::Float64, end_point::AbstractArray, h, ::RLInt_Cubic_Spline_Interp)::Vector\n result = map(x->fracint(f, α, x, h, RLInt_Cubic_Spline_Interp()), end_point)\n return result\nend\n# Deploy Complex Step Differentiation to compute the first order derivative.\nfunction first_order(f, point, h)\n return imag(f(point + im*h))/h\nend\n\n\n", "meta": {"hexsha": "1624c9191978f9c523b9bd82ae6b0b25d71037f9", "size": 14208, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Integral/RL.jl", "max_stars_repo_name": "ErikQQY/FractionalCalculus.jl", "max_stars_repo_head_hexsha": "f84306de4c3b44f66f21c88629b5a690179663c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-09-25T03:46:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-04T11:42:37.000Z", "max_issues_repo_path": "src/Integral/RL.jl", "max_issues_repo_name": "ErikQQY/FractionalCalculus.jl", "max_issues_repo_head_hexsha": "f84306de4c3b44f66f21c88629b5a690179663c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Integral/RL.jl", "max_forks_repo_name": "ErikQQY/FractionalCalculus.jl", "max_forks_repo_head_hexsha": "f84306de4c3b44f66f21c88629b5a690179663c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0114068441, "max_line_length": 187, "alphanum_fraction": 0.6525900901, "num_tokens": 4679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632234212403, "lm_q2_score": 0.8519527944504227, "lm_q1q2_score": 0.8109425331283128}} {"text": "module EqualityConstrainedMinimization\nexport Solve_ECM\nusing Calculus\nusing LinearAlgebra\ninclude(\"algorithms.jl\")\n\n\n#######################################################################\n#######################################################################\n#=\n\nThis is a non-linear minimization solver that works with all convex problems\nwith linear equality constraints. It is intended to solve problems in the form\n\"minimize f(x) such that Ax = b\" and \"minimize f(x)\" for the unconstrained case.\nI am taking the algorithms used directly from \"Convex Optimization\" by Stephen Boyd\nand Lieven Vandenberghe. This package is intended for learning purposes and while\nit may not be the fastest solver, it is certainly one of the easiest to understand.\n\nAlgorithms used for unconstrained problem:\n -Gradient descent\n -Newton's method\n -Unless force_gradient = true, the solver will use gradient descent method until\n stopping criterion η is met. Then, it will switch to Newton's Method until ϵ is met\n Note that η > ϵ.\n\nAlgorithms used for equality constrained problem:\n -Feasible Start Newton Method\n -Infeasible Start Newton Method\n\n# Arguments\n - 'f': The convex objective. Must be convex or the solution may converge to a local solution.\n - 'x': The starting point. May be feasible or infeasible though starting feasible may converge faster.\n - 'A': The coefficient matrix on the Ax = b constraint. This system needs to be underdetermined. Not including this will imply an unconstrained problem.\n - 'b': The constant vector on the Ax = b constraint. Not including this will imply feasible start.\n - 'α': A parameter used in the backtracking line search. Note that α ∈ (0, 0.5)\n - 'β': Another parameter used in the backtracking line search. β ∈ (0, 1)\n - 'η': A stopping criterion used to determine when to switch from gradient descent to Newton's method.\n - 'ϵ': Overall stopping criterion.\n - 'maxIt': Max iteration stopping criterion. Meant as a failsafe.\n - 'verbose': Setting this to true will show data from each iteration.\n - 'force_gradient': Setting this to true will force only the gradient descent method for unconstrained problems. Do this when ϵ is relatively large.\n\nx^2 + y^2 -> x[1]^2 + x[2]^2\n\nMain solver function:\nSolve_ECM(\n f,\n x::Array{Float64,1};\n A::Array{Float64,2} = zeros(2, 2),\n b::Array{Float64,1} = zeros(2),\n α = 0.3,\n β = 0.8,\n η = 1e-4,\n ϵ = 1e-8,\n maxIt = 1e3,\n verbose = true,\n force_gradient = false\n )\n\nSee 'UsageExamples.jl' for some examples.\n\n=#\n#######################################################################\n#######################################################################\n\n\n\n\n\n#####################################\n#####################################\n#\n# Main Solver\n#\n#####################################\n#####################################\nfunction Solve_ECM(\n f,\n x::Array{Float64,1};\n A::Array{Float64,2} = zeros(2, 2),\n b::Array{Float64,1} = zeros(2),\n α = 0.3,\n β = 0.8,\n η = 1e-4,\n ϵ = 1e-8,\n maxIt = 1e3,\n verbose = true,\n force_gradient = false\n )\n\n n = length(x)\n m = size(A,1)\n\n uncon = true\n feasible = true\n\n if η >= ϵ && n >= m\n\n if A != zeros(2, 2)\n if b != zeros(2)\n feasible = false\n end\n uncon = false\n end\n\n sol = Tuple{Array{Float64,1},Float64}\n\n #Determine which method to use\n if uncon\n\n print(\"\\n\\nUnconstrained objective detected\")\n\n if force_gradient\n print(\"\\nSolving using gradient descent\\n\")\n sol = Unconstrained_Grad_Descent(f, x, n, α, β, ϵ, maxIt, verbose)\n else\n print(\"\\nSolving using gradient descent and Newton's Method\\n\")\n sol = Solve_UMP(f, x, n, α, β, η, ϵ, maxIt, verbose)\n end\n else\n if feasible\n print(\"\\n\\nVector b not given. Therefore, x is assumed feasible\")\n print(\"\\nSolving using Feasible Start Newton Method\")\n sol = Newton_FS(f, x, A, n, m, α, β, ϵ, maxIt, verbose)\n else\n print(\"\\n\\nVector b given. Therefore, x is assumed infeasible\")\n print(\"\\nSolving using Infeasible Start Newton Method\")\n sol = Newton_IFS(f, x, A, b, n, m, α, β, ϵ, maxIt, verbose)\n end\n end\n\n print(\"\\n\\n------------------------\")\n print(\"\\nSolution found at point:\")\n print(\"\\n\\nx = \", sol[1],\"\\n\")\n print(\"\\nObjective Value = \", sol[2], \"\\n\\n\")\n else\n print(\"\\nParameters not correct. Either η < ϵ or Ax = b is an overdetermined system\")\n end\n\n return sol[2]\nend\n\nend\n", "meta": {"hexsha": "120e52bf906b474f04c3c14042c80bc7a9007103", "size": 4861, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/EqualityConstrainedMinimization.jl", "max_stars_repo_name": "ihawn/EqualityConstrainedMinimization", "max_stars_repo_head_hexsha": "d49c20543ae0d0b2914e5ce553c11ff3c89e2abf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/EqualityConstrainedMinimization.jl", "max_issues_repo_name": "ihawn/EqualityConstrainedMinimization", "max_issues_repo_head_hexsha": "d49c20543ae0d0b2914e5ce553c11ff3c89e2abf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-04-28T03:59:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-28T17:30:14.000Z", "max_forks_repo_path": "src/EqualityConstrainedMinimization.jl", "max_forks_repo_name": "ihawn/EqualityConstrainedMinimization", "max_forks_repo_head_hexsha": "d49c20543ae0d0b2914e5ce553c11ff3c89e2abf", "max_forks_repo_licenses": ["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.7569444444, "max_line_length": 156, "alphanum_fraction": 0.5552355482, "num_tokens": 1187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361700013356, "lm_q2_score": 0.8887587890727754, "lm_q1q2_score": 0.810935665556588}} {"text": "\nusing Plots\nusing Polynomials\nusing DataFrames, DataFramesMeta\nusing Latexify\ntexpyplot()\n\nusing Random; Random.seed!(1234)\nx = rand(-10:20,10)\ny = 2 * x.^2 .+ rand(-80:80,length(x))\n#x = [-3, 4, 5, -1, 2, -1, 0, -3, 3, -2]\n#y = [-6, 6, 10, -1, 5, -2, -2, -7, 4, -2]\n\nx[end], y[end]\n\ndf = @linq DataFrame(x = x[1:end-1], y = y[1:end-1]) |> \n by(:x, y = mean(:y))\n\ng = polyfit(df.x, df.y)\n\nxs = range(minimum(x), maximum(x), length = 200)\n\nplot(xs, g.(xs), legend = false, linewidth = 2, grid = true)\nplot!(x[1:end-1],y[1:end-1], seriestype = :scatter, markercolor = :lightgreen, markersize = 8)\n\nsavefig(joinpath(@__DIR__,\"overfit.pdf\"))\n\nlinreg(x, y) = hcat(fill!(similar(x), 1), x) \\ y\na,b = linreg(x[1:end-1], y[1:end-1])\n\nplot(xs, b*xs .+ a, legend = false, linewidth = 2, grid = true)\nplot!(x[1:end-1],y[1:end-1], seriestype = :scatter, markercolor = :lightgreen, markersize = 8)\nsavefig(joinpath(@__DIR__,\"underfit.pdf\"))\n\nplot(xs, 2*xs.^2, legend = false, linewidth = 2, grid = true)\nplot!(x[1:end-1],y[1:end-1], seriestype = :scatter, markercolor = :lightgreen, markersize = 8)\nsavefig(joinpath(@__DIR__,\"justright.pdf\"))\n\nclipboard(mdtable(hcat(x,y)))\nclipboard(string(x))\nclipboard(string(y))\n\n", "meta": {"hexsha": "5f49a4fa8d0ee19ed68fc277c101066eb8b5487e", "size": 1208, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "content/intro-data-pipeline/images/overfit.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/intro-data-pipeline/images/overfit.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/intro-data-pipeline/images/overfit.jl", "max_forks_repo_name": "seanrattana/courses", "max_forks_repo_head_hexsha": "9453abc38af26ea49cb00fe1744066fc0de237b3", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-08-18T21:23:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-02T19:14:33.000Z", "avg_line_length": 28.0930232558, "max_line_length": 94, "alphanum_fraction": 0.6274834437, "num_tokens": 471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361700013356, "lm_q2_score": 0.8887587831798665, "lm_q1q2_score": 0.8109356601796848}} {"text": "# L0 pseudo-norm (times a constant)\n\n\"\"\"\n NormL0(λ::Real=1.0)\n\nReturns the function `g(x) = λ*countnz(x)`, for a nonnegative parameter `λ ⩾ 0`.\n\"\"\"\n\nimmutable NormL0{R <: Real} <: ProximableFunction\n lambda::R\n function NormL0(lambda::R)\n if lambda < 0\n error(\"parameter λ must be nonnegative\")\n else\n new(lambda)\n end\n end\nend\n\nNormL0{R <: Real}(lambda::R=1.0) = NormL0{R}(lambda)\n\nfunction (f::NormL0){T <: RealOrComplex}(x::AbstractArray{T})\n return f.lambda*countnz(x)\nend\n\nfunction prox!{T <: RealOrComplex}(f::NormL0, x::AbstractArray{T}, y::AbstractArray{T}, gamma::Real=1.0)\n countnzy = 0;\n gl = gamma*f.lambda\n for i in eachindex(x)\n over = abs(x[i]) > sqrt(2*gl);\n y[i] = over*x[i];\n countnzy += over;\n end\n return f.lambda*countnzy\nend\n\nfun_name(f::NormL0) = \"weighted L0 pseudo-norm\"\nfun_dom(f::NormL0) = \"AbstractArray{Real}, AbstractArray{Complex}\"\nfun_expr(f::NormL0) = \"x ↦ λ countnz(x)\"\nfun_params(f::NormL0) = \"λ = $(f.lambda)\"\n\nfunction prox_naive{T <: RealOrComplex}(f::NormL0, x::AbstractArray{T}, gamma::Real=1.0)\n over = abs.(x) .> sqrt(2*gamma*f.lambda);\n y = x.*over;\n return y, f.lambda*countnz(y)\nend\n", "meta": {"hexsha": "8b59d79e90df98c567d8321b9c647331b6dde771", "size": 1169, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/normL0.jl", "max_stars_repo_name": "mfalt/ProximalOperators.jl", "max_stars_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functions/normL0.jl", "max_issues_repo_name": "mfalt/ProximalOperators.jl", "max_issues_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions/normL0.jl", "max_forks_repo_name": "mfalt/ProximalOperators.jl", "max_forks_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8723404255, "max_line_length": 104, "alphanum_fraction": 0.6475620188, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625050654264, "lm_q2_score": 0.8705972768020108, "lm_q1q2_score": 0.8109287203531395}} {"text": "using Printf\nusing BenchmarkTools\n\n\nprintln(\"-------------------------------\")\nprintln(@sprintf \"Compute the first four Munchausen numbers\")\nprintln(\"-------------------------------\")\n\n\"\"\"\n raisedto(x)\n\n\nRaise x to the power of itself.\n\"\"\"\nfunction raisedto(x)\n if x == 0\n return 0\n else\n return x^x\n end\nend\n\nfunction find_munchausen_numbers()\n\n power_of_digits = [raisedto(i) for i in 0:9]\n\n num = 0\n i = 0\n while num < 4\n thisnumber = i\n # find the sum of the digits raised to themselves\n sumofpowers = 0\n while thisnumber > 0\n digit = thisnumber % 10\n sumofpowers += power_of_digits[digit+1]\n thisnumber ÷= 10\n end\n if i == sumofpowers\n num += 1\n println(\"Munchausen number: \", num, \" \", i)\n end\n i += 1\n end\nend \n\n\n@btime find_munchausen_numbers()\n\nprintln(\" \")\n", "meta": {"hexsha": "09fc63b3a26dd4003acaacc1fde1998baec61105", "size": 929, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/test_munchausen.jl", "max_stars_repo_name": "cometscome/basic_language_comparison", "max_stars_repo_head_hexsha": "f29a1075f9740ea9074d2bc520d25ae0e6841093", "max_stars_repo_licenses": ["NASA-1.3"], "max_stars_count": 60, "max_stars_repo_stars_event_min_datetime": "2019-11-06T12:07:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T09:09:49.000Z", "max_issues_repo_path": "Julia/test_munchausen.jl", "max_issues_repo_name": "cometscome/basic_language_comparison", "max_issues_repo_head_hexsha": "f29a1075f9740ea9074d2bc520d25ae0e6841093", "max_issues_repo_licenses": ["NASA-1.3"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2019-11-10T20:28:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-23T11:24:08.000Z", "max_forks_repo_path": "Julia/test_munchausen.jl", "max_forks_repo_name": "cometscome/basic_language_comparison", "max_forks_repo_head_hexsha": "f29a1075f9740ea9074d2bc520d25ae0e6841093", "max_forks_repo_licenses": ["NASA-1.3"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2019-11-10T19:28:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T21:15:08.000Z", "avg_line_length": 18.58, "max_line_length": 61, "alphanum_fraction": 0.5209903122, "num_tokens": 247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418178895029, "lm_q2_score": 0.8774767842777551, "lm_q1q2_score": 0.8109129905782798}} {"text": "# TESTS - the classical test statistics for linear restrictions\n# \n# written by M. Creel, March 10, 1998. michael.creel@uab.es\n# converted to Octave 13 Jan. 2003\n# converted to Julia 25 Aug. 2017\n# \n# purpose: calculates qF, Wald, Score and Likelihood Ratio tests for\n# linear model\t\t\t\t\t\t y=XB+e\n# \t\t\t\t\t\t\t\t\t e~N(0,sig^2*I_n)\n# subject to linear restrictions \t RB=r\n# \n# format: [qF, W, LR, S] = TestStatistics(y,x,R,r)\n# \n# inputs:\n# \t\t y: nx1 dependent variable\n# \t\t x: nxk regressor matrix\n# \t\t R: R above, a qxk matrix\n# \t\t r: r above, a qx1 vector\n# \n# returns: \n# qF: the qF statistic\n# \t\t W: the Wald statistic\n# \t\t S: the score statistic\n# \t\t LR: the likelihood ratio statistic\nusing Distributions\nfunction TestStatistics(y, x, R, r)\n\n n,k = size(x)\n q = size(R,1)\n\tb = x\\y\n\txx_inv = inv(x'*x)\n\tP_inv = inv(R*xx_inv*R')\n\tb_r = b - xx_inv*R'*P_inv*(R*b-r)\n e = y - x*b\n ess = (e'*e)[1,1]\n e_r = y - x*b_r\n ess_r = (e_r' * e_r)[1,1]\n sigsqhat_ols = ess/(n-k)\n sigsqhat_mle = ess/(n)\n sigsqhat_mle_r = ess_r/(n)\n # F-test\n F = (ess_r-ess)/(q*sigsqhat_ols)\n # Wald test (uses unrestricted model's est. of sig^2\n W = (R*b-r)'*P_inv*(R*b-r)/sigsqhat_mle\n # Score test (uses restricted model's est. of sig^2 \n P_x = x * xx_inv * x'\n S = e_r' * P_x * e_r/(sigsqhat_mle_r)\n # LR test\n lnl = -n/2*log(2*pi) - n/2*log(sigsqhat_mle) - e' * e/(2*sigsqhat_mle)\n lnl_r = -n/2*log(2*pi) - n/2*log(sigsqhat_mle_r) - e_r' * e_r/(2*sigsqhat_mle_r)\n LR = 2.0*(lnl-lnl_r)\n\ttests = [q*F[1], W[1], LR[1], S[1]]\n\tpvalues = ccdf(Chisq(q), tests)\n tests = [tests pvalues]\n\tTESTS = [\"qF\",\"Wald\",\"LR\",\"Score\"]\n\tlabels = [\"Value\",\"p-value\"]\n prettyprint(tests, labels, TESTS)\n return F, W, LR, S\nend\n", "meta": {"hexsha": "c13001345e30ef5cdd1f26e972a088ec71678e99", "size": 1756, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/LinearRegression/TestStatistics.jl", "max_stars_repo_name": "UserQuestions/Econometrics.jl", "max_stars_repo_head_hexsha": "f9db0ca3046e7c5328f085581a12b1c733cf9bcf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/LinearRegression/TestStatistics.jl", "max_issues_repo_name": "UserQuestions/Econometrics.jl", "max_issues_repo_head_hexsha": "f9db0ca3046e7c5328f085581a12b1c733cf9bcf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/LinearRegression/TestStatistics.jl", "max_forks_repo_name": "UserQuestions/Econometrics.jl", "max_forks_repo_head_hexsha": "f9db0ca3046e7c5328f085581a12b1c733cf9bcf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2666666667, "max_line_length": 84, "alphanum_fraction": 0.5985193622, "num_tokens": 681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418137109955, "lm_q2_score": 0.8774767810736693, "lm_q1q2_score": 0.8109129839507069}} {"text": "\"\"\"\n lis(arr::Array{Int}, ::Val{:dp})\n\n# Arguments:\n- `arr`: sequence of integers\n\n# Examples/Tests \n```julia\njulia> lis([3, 10, 2, 1, 20], Val(:dp))\n[3, 10, 20]\n\njulia> lis([2, 2, 3], Val(:dp))\n[2, 3]\n```\n\n# Brief:\nGiven a sequence of integers, the function finds the longest, strictly increasing, subsequence in that sequence.\n\n# For more information:\nhttps://cp-algorithms.com/sequences/longest_increasing_subsequence.html\n\n# Contributed by:\n- [Igor Malheiros](https://github.com/igormalheiros)\n\"\"\"\n\nfunction lis(arr::Array{Int}, ::Val{:dp})\n len = length(arr)\n memo = ones(Int, len)\n p = zeros(Int, len)\n\n lis_arr = Int[]\n\n len == 0 && return lis_arr # if arr is empty\n\n lis_value = 1\n lis_pos = 1\n\n for i in 2:len\n for j in 1:i\n if arr[j] < arr[i] && memo[i] < memo[j] + 1\n memo[i] = memo[j] + 1\n p[i] = j\n end\n end\n # Updates the longest increasing value and position\n if memo[i] > lis_value\n lis_value = memo[i]\n lis_pos = i\n end\n end\n\n # Restoring\n while lis_pos != 0\n push!(lis_arr, arr[lis_pos])\n lis_pos = p[lis_pos]\n end\n\n reverse!(lis_arr)\n\n return lis_arr\nend\n", "meta": {"hexsha": "4fcc1db89eb367185fae73f4a18b9dae65cfd9e2", "size": 1242, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/longest_increasing_subsequence/dynamic_programming.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/longest_increasing_subsequence/dynamic_programming.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/longest_increasing_subsequence/dynamic_programming.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": 20.0322580645, "max_line_length": 112, "alphanum_fraction": 0.5644122383, "num_tokens": 381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107843878721, "lm_q2_score": 0.8652240947405564, "lm_q1q2_score": 0.8108973525030834}} {"text": "function normpdf(x::Float64, mu::Float64, sigma::Float64)\n\treturn 1.0 / ( sqrt(2.0 * pi) * sigma ) * exp( - 0.5 * (x - mu)^2 / sigma^2 )\nend\t", "meta": {"hexsha": "f14de57b0e4f6c0618f2bb491b10720bc4984d5c", "size": 141, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/cpu/normpdf.jl", "max_stars_repo_name": "roding/part_conc_spt_abc", "max_stars_repo_head_hexsha": "f04f2065f2260178e02c796e97091861e30d8f3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cpu/normpdf.jl", "max_issues_repo_name": "roding/part_conc_spt_abc", "max_issues_repo_head_hexsha": "f04f2065f2260178e02c796e97091861e30d8f3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cpu/normpdf.jl", "max_forks_repo_name": "roding/part_conc_spt_abc", "max_forks_repo_head_hexsha": "f04f2065f2260178e02c796e97091861e30d8f3d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.0, "max_line_length": 78, "alphanum_fraction": 0.5886524823, "num_tokens": 58, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9632305339244014, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.8108721638509615}} {"text": "# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,\n#\n# a^2 + b^2 = c^2\n# For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.\n#\n# There exists exactly one Pythagorean triplet for which a + b + c = 1000.\n# Find the product abc.\n\nusing ProjectEulerSolutions\n\n# Cycle through (from n down to n/2) to find sets of a and b that satisfy\n# a + b + c = n.\nfunction p009solution(n::Integer=4)::Integer\n\n maxval = fld(n, 2)\n for a = maxval:-1:2\n for b = maxval:-1:2\n c = sqrt(a*a + b*b)\n if c == floor(c) && a + b + c == n\n return a * b * c\n end\n end\n end\n\n # Should never happen\n return -1\nend\n\n# Note, there are probably faster options which use triplet generators.\n\np009 = Problems.Problem(p009solution)\n\nProblems.benchmark(p009, 1000)", "meta": {"hexsha": "65a9eddbdaaaf746bb12e40f44406eb2dbf13f4b", "size": 826, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/009.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/009.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/009.jl", "max_forks_repo_name": "gnujosh/julia-euler-project", "max_forks_repo_head_hexsha": "40df730bfa488a8a59088d193049afe1767fb06c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0303030303, "max_line_length": 80, "alphanum_fraction": 0.593220339, "num_tokens": 265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660949832346, "lm_q2_score": 0.8499711832583695, "lm_q1q2_score": 0.810843690541266}} {"text": "# Polynomial mean function\n\n@doc \"\"\"\n# Description\nConstructor for the Polynomial mean function\n\nm(x) = Σ_d xᵈβᵀ_d\n# Arguments:\n* `β::Matrix{Float64}`: A Dxd matrix of coefficients where D is the dimension of xᵈ and d is the degree of the polynomial\n\"\"\" ->\ntype MeanPoly <: Mean\n β::Matrix{Float64} # Polynomial coefficients\n dim::Int # Dimension\n deg::Int # Polynomial degree\n MeanPoly(β::Matrix{Float64}) = new(β,size(β, 1), size(β, 2))\nend\n\nfunction mean(mPoly::MeanPoly,x::Matrix{Float64})\n dim, nobsv = size(x)\n dim == mPoly.dim || throw(ArgumentError(\"Observations and mean function have inconsistent dimensions\"))\n z = zeros(nobsv)\n for i in 1:nobsv\n for j in 1:mPoly.deg\n z[i] += dot(x[:, i].^j, mPoly.β[:,j])\n end \n end\n return z\nend\n\nget_params(mPoly::MeanPoly) = vec(mPoly.β)\nget_param_names(mPoly::MeanPoly) = get_param_names(mPoly.β, :β)\nnum_params(mPoly::MeanPoly) = mPoly.dim * mPoly.deg\nfunction set_params!(mPoly::MeanPoly, hyp::Vector{Float64})\n num_param = mPoly.dim * mPoly.deg\n length(hyp) == num_param || throw(ArgumentError(\"Polynomial mean function has $(num_param) parameters\"))\n mPoly.β = reshape(hyp,mPoly.dim,mPoly.deg)\nend\n\n\nfunction grad_mean(mPoly::MeanPoly, x::Vector{Float64})\n dM_theta = Array(Float64,mPoly.dim,mPoly.deg)\n \n for i in 1:mPoly.dim\n for j in 1:mPoly.deg\n dM_theta[i,j] = x[i].^j\n end\n end\n return vec(dM_theta)\nend\n", "meta": {"hexsha": "d206c724e482cb6c5c4c98e28bfcbb7fa65abe18", "size": 1500, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/means/mPoly.jl", "max_stars_repo_name": "JuliaPackageMirrors/GaussianProcesses.jl", "max_stars_repo_head_hexsha": "76a0070b01e996d56888f56ba9d144940cbb7578", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/means/mPoly.jl", "max_issues_repo_name": "JuliaPackageMirrors/GaussianProcesses.jl", "max_issues_repo_head_hexsha": "76a0070b01e996d56888f56ba9d144940cbb7578", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/means/mPoly.jl", "max_forks_repo_name": "JuliaPackageMirrors/GaussianProcesses.jl", "max_forks_repo_head_hexsha": "76a0070b01e996d56888f56ba9d144940cbb7578", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0, "max_line_length": 121, "alphanum_fraction": 0.6513333333, "num_tokens": 452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.953966101527047, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.8108436834142421}} {"text": "using Printf\nusing Turing\nusing CairoMakie\nusing ElectronDisplay\n\n# Data generation\n\nN = 100\nx = range(0, 1, length=N)\ny = @. 0.16x^2 + 4.5x + π\ny = @. y * (1 + 0.1 * randn())\n\nscatter(x, y)\n\n# Linear model (y = mx + c)\n\n@model function linear_model(x, y)\n m ~ Normal(0, 1)\n c ~ Normal(0, 1)\n σ ~ Exponential(1)\n\n N = length(x)\n for n in 1:N\n y[n] ~ Normal(m*x[n] + c, σ)\n end\nend\n\nchain_linear = sample(linear_model(x, y), NUTS(0.65), 10000, progress=true)\n\nfunction y_linear(chain, n, x)\n m = chain[:m][n]\n c = chain[:c][n]\n return @. m * x + c\nend\n\nfunction animate_chain(chain, y_model, x, y; filepath, N_samples=1000, N_history=50, max_alpha=0.5)\n n = Observable(1)\n\n # Compute all predictions to plot.\n yₚ = []\n for i in 1:N_samples\n push!(yₚ, y_model(chain, i, x))\n end\n\n fig = Figure()\n\n title = @lift \"Iteration $($n)\"\n ax = Axis(fig[1, 1], xlabel=\"x\", ylabel=\"y\"; title)\n\n # Create N_history lines with different alpha that we can change the data on.\n line_plots = []\n for i in 1:N_history\n line_plot = lines!(x, yₚ[1], color=(:gray, max_alpha * i/N_history))\n push!(line_plots, line_plot)\n end\n\n # Plot the actual data points.\n scatter!(x, y)\n\n record(fig, filepath, 1:N_samples, framerate=30) do chain_iter\n @info \"Animating $filepath: frame $chain_iter/$N_samples\"\n n[] = chain_iter\n\n # Change the data of the line plots to show the last N_history predictions.\n for (i, j) in enumerate(chain_iter:-1:max(1, chain_iter-N_history+1))\n line_plots[i][2] = yₚ[j]\n end\n end\n\n return\nend\n\nanimate_chain(chain_linear, y_linear, x, y, filepath=\"linear_model.mp4\")\n\nfunction plot_chains_and_densities(chain, vars; filepath)\n fig = Figure(resolution=(800, 200*length(vars)))\n\n for (n, var) in enumerate(vars)\n ax1 = Axis(fig[n, 1], ylabel=\"$var\", xlabel=\"iteration\")\n lines!(ax1, chain[var][:] |> skipmissing |> collect)\n\n ax2 = Axis(fig[n, 2], ylabel=\"P($var)\", xlabel=\"$var\", yticklabelsvisible=false)\n density!(ax2, chain[var][:] |> skipmissing |> collect)\n end\n\n save(filepath, fig, px_per_unit=2)\n\n return fig\nend\n\nplot_chains_and_densities(chain_linear, [:m, :c, :σ], filepath=\"linear_model_posteriors.png\")\n\n# Quadratic model (y = ax² + bx + c)\n\n@model function quadratic_model(x, y)\n a ~ Normal(0, 1)\n b ~ Normal(0, 1)\n c ~ Normal(0, 1)\n σ ~ Exponential(1)\n\n N = length(x)\n for n in 1:N\n y[n] ~ Normal(a*x[n]^2 + b*x[n] + c, σ)\n end\nend\n\nchain_quadratic = sample(quadratic_model(x, y), NUTS(0.65), 10000, progress=true)\n\nfunction y_quadratic(chain, n, x)\n a = chain[:a][n]\n b = chain[:b][n]\n c = chain[:c][n]\n return @. a*x^2 + b*x + c\nend\n\nanimate_chain(chain_quadratic, y_quadratic, x, y, filepath=\"quadratic_model.mp4\")\n\nplot_chains_and_densities(chain_quadratic, [:a, :b, :c, :σ], filepath=\"quadratic_model_posteriors.png\")\n\n# Exponential model [y = α + β * exp(γ * x)]\n\n@model function exponential_model(x, y)\n α ~ Normal(0, 1)\n β ~ Normal(0, 1)\n γ ~ Normal(0, 1)\n σ ~ Exponential(1)\n\n N = length(x)\n for n in 1:N\n y[n] ~ Normal(α + β * exp(γ*x[n]), σ)\n end\nend\n\nchain_exponential = sample(exponential_model(x, y), NUTS(0.65), 10000, progress=true)\n\nfunction y_exponential(chain, n, x)\n α = chain[:α][n]\n β = chain[:β][n]\n γ = chain[:γ][n]\n return @. α + β * exp(γ * x)\nend\n\nanimate_chain(chain_exponential, y_exponential, x, y, filepath=\"exponential_model.mp4\")\n\nplot_chains_and_densities(chain_exponential, [:α, :β, :γ, :σ], filepath=\"exponential_model_posteriors.png\")\n\n# Categorical model (picks between linear, quadratic, and exponential)\n\n@model function categorical_model1(x, y)\n N = length(x)\n\n pl ~ Beta(1, 1)\n M ~ Categorical([pl, 1-pl])\n\n if M == 1\n m ~ Normal(0, 1)\n k ~ Normal(0, 1)\n σl ~ Exponential(1)\n\n for n in 1:N\n y[n] ~ Normal(m*x[n] + k, σl)\n end\n else\n a ~ Normal(0, 1)\n b ~ Normal(0, 1)\n c ~ Normal(0, 1)\n σq ~ Exponential(1)\n\n for n in 1:N\n y[n] ~ Normal(a*x[n]^2 + b*x[n] + c, σq)\n end\n end\nend\n\nprior_chain_categorical1 = sample(categorical_model1(x, y), Prior(), 10000)\nplot_chains_and_densities(prior_chain_categorical1, [:pl, :M, :a, :b, :c, :m, :k], filepath=\"categorical_model1_priors.png\")\n\n# Errors since variables defined in if statements are missing during inference?\nsampler = Gibbs(PG(100, :M), NUTS(100, 0.65, :pl, :m, :k, :σl, :a, :b, :c, :σq))\nchain_categorical1 = sample(categorical_model1(x, y), sampler, 1000, progress=true)\n\n@model function categorical_model2(x, y)\n N = length(x)\n\n pl ~ Beta(1, 1)\n M ~ Categorical([pl, 1-pl])\n\n m ~ Normal(0, 1)\n k ~ Normal(0, 1)\n σl ~ Exponential(1)\n\n a ~ Normal(0, 1)\n b ~ Normal(0, 1)\n c ~ Normal(0, 1)\n σq ~ Exponential(1)\n\n if M == 1\n for n in 1:N\n y[n] ~ Normal(m*x[n] + k, σl)\n end\n else\n for n in 1:N\n y[n] ~ Normal(a*x[n]^2 + b*x[n] + c, σq)\n end\n end\nend\n\nprior_chain_categorical2 = sample(categorical_model2(x, y), Prior(), 10000)\nplot_chains_and_densities(prior_chain_categorical2, [:pl, :M, :a, :b, :c, :m, :k], filepath=\"categorical_model2_priors.png\")\n\n# Inference fails? since it always picks M=1 or M=2 and doesn't sample from both models.\nsampler = Gibbs(PG(10, :M), NUTS(100, 0.65, :pl, :m, :k, :σl, :a, :b, :c, :σq))\nchain_categorical2 = sample(categorical_model2(x, y), sampler, 1000, progress=true)\nplot_chains_and_densities(chain_categorical2, [:pl, :M, :m, :k, :σl, :a, :b, :c, :σq], filepath=\"categorical_model2_posteriors.png\")\n\n@model function categorical_model3(x, y)\n N = length(x)\n\n m ~ Normal(0, 1)\n k ~ Normal(0, 1)\n σl ~ Exponential(1)\n\n a ~ Normal(0, 1)\n b ~ Normal(0, 1)\n c ~ Normal(0, 1)\n σq ~ Exponential(1)\n\n pl ~ Beta(1, 1)\n\n if rand() < pl\n for n in 1:N\n y[n] ~ Normal(m*x[n] + k, σl)\n end\n else\n for n in 1:N\n y[n] ~ Normal(a*x[n]^2 + b*x[n] + c, σq)\n end\n end\nend\n\n# Inference is bad and chain is very correlated.\nchain_categorical3 = sample(categorical_model3(x, y), NUTS(), 1000, progress=true)\nplot_chains_and_densities(chain_categorical3, [:pl, :m, :k, :σl, :a, :b, :c, :σq], filepath=\"categorical_model3_posteriors.png\")\n\nfunction plot_model_comparison(chain, x, y)\n fig = Figure()\n ax = Axis(fig[1, 1])\n\n pl = mode(chain[:pl])\n\n m = mode(chain[:m])\n k = mode(chain[:k])\n\n a = mode(chain[:a])\n b = mode(chain[:b])\n c = mode(chain[:c])\n\n y_linear = @. m*x + k\n y_quadratic = @. a*x^2 + b*x + c\n\n lines!(ax, x, y_linear, label=@sprintf(\"linear (%d%%)\", 100pl))\n lines!(ax, x, y_quadratic, label=@sprintf(\"quadratic (%d%%)\", 100*(1-pl)))\n\n scatter!(x, y)\n axislegend(ax)\n\n return fig\nend\n\nplot_model_comparison(chain_categorical3, x, y)\n\nchain_time(chain) = chain.info.stop_time - chain.info.start_time\n\nchains = (chain_linear, chain_quadratic, chain_exponential, chain_categorical2, chain_categorical3)\nchain_names = (\"linear\", \"quadratic\", \"exponential\", \"categorical1\", \"categorical2\")\n\nopen(\"inference_wall_clock_times.txt\",\"w\") do io\n for (chain, name) in zip(chains, chain_names)\n line = @sprintf(\"%s: %.1f seconds for %d samples\", name, chain_time(chain), size(chain, 1))\n @info line\n println(io, line)\n end\nend\n", "meta": {"hexsha": "1e442f822cc1b0c4ab2433a8aeee4d4fdf892c95", "size": 7496, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "line_model_selection/line_model_selection.jl", "max_stars_repo_name": "ali-ramadhan/BayesianParameterizations.jl", "max_stars_repo_head_hexsha": "eaf6606767641ea9f8d3becf67a9843cee4a0b62", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-03-16T21:19:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T01:52:18.000Z", "max_issues_repo_path": "line_model_selection/line_model_selection.jl", "max_issues_repo_name": "ali-ramadhan/BayesianParameterizations.jl", "max_issues_repo_head_hexsha": "eaf6606767641ea9f8d3becf67a9843cee4a0b62", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "line_model_selection/line_model_selection.jl", "max_forks_repo_name": "ali-ramadhan/BayesianParameterizations.jl", "max_forks_repo_head_hexsha": "eaf6606767641ea9f8d3becf67a9843cee4a0b62", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3943661972, "max_line_length": 132, "alphanum_fraction": 0.6056563501, "num_tokens": 2494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660976007596, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.810843680077011}} {"text": "using LinearAlgebra\n\nfunction cheb(N)\n if N==0 \n D=0; x=1\n return D,x\n else\n x= cos.(pi * collect(0:N) ./ N)\n c=[2; ones(N-1, 1); 2] .* (-1).^collect(0:N);\n X = repeat(x, 1, N+1);\n dX=X .- X';\n D = (c .* (1 ./ c)') ./ (dX .+ Diagonal( ones(N+1) ) );\n D = D .- Diagonal( vec( sum(D', dims=1) ) );\n return D,x\n end\nend\n\n\nfunction clencurt(N)\n\n θ = π * collect(0:N) ./N\n x = cos.(θ)\n w = zeros(1, N+1)\n ii = collect(2:N)\n v = ones(N-1,1)\n \n if mod(N,2) == 0\n w[1] = 1/(N^2 - 1)\n w[N+1] = w[1]\n for k=1:N/2-1\n v = v .- 2 * cos.(2 * k * θ[ii])/(4 * k^2 - 1)\n end\n v = v - cos.(N*θ[ii]) / (N^2 - 1)\n else\n w[1] = 1/N^2\n w[N+1] = w[1]\n for k=1:(N-1)/2\n v = v .- 2 * cos.(2 * k * θ[ii])/(4 * k^2 - 1)\n end\n end\n \n w[ii] = 2*v/N\n\n return x, w\nend\n", "meta": {"hexsha": "70cf06d7df7fe74138a7a4c68fe2fc673ac74196", "size": 941, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ShallowWater/Julia/Spherical/cheb.jl", "max_stars_repo_name": "francispoulin/Linear-Stability-Calculators", "max_stars_repo_head_hexsha": "2e1cf66b0bed95f24ddfeea09ec7d66956cdce64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-01-22T20:00:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-27T17:19:18.000Z", "max_issues_repo_path": "ShallowWater/Julia/Spherical/cheb.jl", "max_issues_repo_name": "francispoulin/Linear-Stability-Calculators", "max_issues_repo_head_hexsha": "2e1cf66b0bed95f24ddfeea09ec7d66956cdce64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-27T16:14:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-27T16:14:05.000Z", "max_forks_repo_path": "ShallowWater/Julia/Spherical/cheb.jl", "max_forks_repo_name": "francispoulin/Linear-Stability-Calculators", "max_forks_repo_head_hexsha": "2e1cf66b0bed95f24ddfeea09ec7d66956cdce64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-05-18T11:05:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T18:57:19.000Z", "avg_line_length": 20.4565217391, "max_line_length": 64, "alphanum_fraction": 0.3581296493, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810496235895, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.8108171561937718}} {"text": "\nexport cg1\n\n\n\"\"\"\n`cg1(j1, m1, j2, m2, j3, m3, T=Float64)` : A reference implementation of\nClebsch-Gordon coefficients based on\n\nhttps://hal.inria.fr/hal-01851097/document\nEquation (4-6)\n\nThis heavily uses BigInt and BigFloat and should therefore not be employed\nfor performance critical tasks.\n\"\"\"\nfunction cg1(j1, m1, j2, m2, j3, m3, T=Float64)\n if (m3 != m1 + m2) || !(abs(j1-j2) <= j3 <= j1 + j2)\n return zero(T)\n end\n\n N = (2*j3+1) *\n factorial(big(j1+m1)) * factorial(big(j1-m1)) *\n factorial(big(j2+m2)) * factorial(big(j2-m2)) *\n factorial(big(j3+m3)) * factorial(big(j3-m3)) /\n factorial(big( j1+j2-j3)) /\n factorial(big( j1-j2+j3)) /\n factorial(big(-j1+j2+j3)) /\n factorial(big(j1+j2+j3+1))\n\n G = big(0)\n # 0 ≦ k ≦ j1+j2-j3\n # 0 ≤ j1-m1-k ≤ j1-j2+j3 <=> j2-j3-m1 ≤ k ≤ j1-m1\n # 0 ≤ j2+m2-k ≤ -j1+j2+j3 <=> j1-j3+m2 ≤ k ≤ j2+m2\n lb = (0, j2-j3-m1, j1-j3+m2)\n ub = (j1+j2-j3, j1-m1, j2+m2)\n for k in maximum(lb):minimum(ub)\n bk = big(k)\n G += (-1)^k *\n binomial(big( j1+j2-j3), big(k)) *\n binomial(big( j1-j2+j3), big(j1-m1-k)) *\n binomial(big(-j1+j2+j3), big(j2+m2-k))\n end\n\n return T(sqrt(N) * G)\nend\n", "meta": {"hexsha": "032d0e2bd7f21e0f815442f18fbe632e2c37d943", "size": 1229, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/clebschgordan.jl", "max_stars_repo_name": "cortner/SphericalHarmonics.jl", "max_stars_repo_head_hexsha": "87605b9c18bb2648c5fd25cfad9bfeebd3f32c45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-02T19:41:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-02T19:41:24.000Z", "max_issues_repo_path": "src/clebschgordan.jl", "max_issues_repo_name": "cortner/SphericalHarmonics.jl", "max_issues_repo_head_hexsha": "87605b9c18bb2648c5fd25cfad9bfeebd3f32c45", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-04-15T13:18:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-15T13:27:57.000Z", "max_forks_repo_path": "src/clebschgordan.jl", "max_forks_repo_name": "cortner/SphericalHarmonics.jl", "max_forks_repo_head_hexsha": "87605b9c18bb2648c5fd25cfad9bfeebd3f32c45", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-08-07T10:42:26.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-07T10:42:26.000Z", "avg_line_length": 27.3111111111, "max_line_length": 74, "alphanum_fraction": 0.5508543531, "num_tokens": 491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810407096791, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.8108171468231681}} {"text": "# v0.6\n\n# Task 1\nfunction hofstadterconway(n::Integer)::Vector{Int}\n rst = fill(1, n)\n for i in 3:n\n rst[i] = rst[rst[i - 1]] + rst[i - rst[i - 1]]\n end\n return rst\nend\n\nfunction hcfraction(n::Integer)::Vector{Float64}\n rst = Array{Float64}(n)\n for (i, a) in enumerate(hofstadterconway(n))\n rst[i] = abs(a) / i\n end\n return rst\nend\n\n# Task 2\nseq = hcfraction(2 ^ 20)\nfor i in 1:20\n a, b = 2 ^ (i - 1), 2 ^ i\n @printf(\"max value of a(n)/n in %6i < n < %7i = %5.3f\\n\", a, b, maximum(seq[a:b]))\nend\n\n# Task 3\nfunction lastindex(val::Float64)\n r, p = 1, 0\n # Find the range of 2 power in which the maximum is < val\n seq = hcfraction(2 ^ 15)\n while maximum(seq[2^p:2^(p+1)]) > val; p += 1 end\n r = 2 ^ (p + 1)\n while seq[r] < val; r -= 1 end\n return r\nend\n\nprintln(\"You too might have won \\$1000 with the mallows number of \", lastindex(0.55))\n", "meta": {"hexsha": "167ab9f962d271bd6afea9c847829ed59f057bcd", "size": 903, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/hofstadter-conway-$10,000-sequence.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/hofstadter-conway-$10,000-sequence.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/hofstadter-conway-$10,000-sequence.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1538461538, "max_line_length": 86, "alphanum_fraction": 0.569213732, "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248208414329, "lm_q2_score": 0.863391611731321, "lm_q1q2_score": 0.8107461535219996}} {"text": "a=rand(Int,3).%9;b=rand(Int,3).%9;c=rand(Int,3).%9\nabc=[Equation(:a,a),Equation(:b,b),Equation(:c,c)]\n\n#Dot product\nex1=Ten(:a,:i)*Ten(:b,:i)\nr1=ex1&abc\n@assert r1==dot(a,b)\n\n#Cross product\nex2=Alt([:i,:j,:k])*Ten(:a,:j)*Ten(:b,:k)\nr2=ex2&abc\n@assert r2.x==cross(a,b)\n\nex3=Alt([:i,:j,:k])*Ten(:a,:j)*Ten(:b,:k)*Ten(:b,:m)*Ten(:a,:m)+Ten(:c,:i)\nr3=ex3&abc\n@assert r3.x==cross(a,b)*dot(b,a)+c\n\n#Both\nex4=Alt([:i,:j,:k])*Ten(:a,:j)*Ten(:b,:k)*Ten(:a,:m)*Ten(:c,:m)\nr4=ex4&abc\n@assert r4.x==cross(a,b)*dot(a,c)\n\nex5=Alt([:i,:j,:k])*Ten(:a,:j)*Ten(:b,:k)*Alt([:m,:n,:o])*Ten(:c,:n)*Ten(:b,:o)\nr5=ex5&abc&Equation(:m,:i)\n@assert r5==dot(cross(a,b),cross(c,b))\n\n#Triangle area\nex6=Sqrt(Alt([:i,:j,:k])*Ten(:a,:j)*Ten(:b,:k)*Alt([:i,:m,:n])*Ten(:a,:m)*Ten(:b,:n))/2\nr6=ex6&abc\n@assert round(r6)==round(norm(cross(a,b))/2)\n\n#Diadic products\nex7=Ten(:a,:i)*Ten(:b,:j)\nr7=ex7&abc&@equs(i=2, j=3)\n@assert r7==a[2]*b[3]\n\n#Transpose\nex8=Equations.Transpose(Ten(a*b',[:i,:j]))\nr8=simplify(ex8)\n@assert r8.x==(a*b')'\n\n#Determinant\nA=rand(Int,3,3).%9\nex9a=Alt([:i,:j,:k])*Ten(A,[:i,1])*Ten(A,[:j,2])*Ten(A,[:k,3])\nr9a=simplify(ex9a)\nex9b=Alt([:i,:j,:k])*Alt([:r,:s,:t])*Ten(A,[:i,:r])*Ten(A,[:j,:s])*Ten(A,[:k,:t])/6\nr9b=simplify(ex9b)\n@assert round(det(A))==r9a==round(r9b)\n\n#Inverse\neq1=@equ detA=Alt([x,y,z])*Ten(A,[x,1])*Ten(A,[y,2])*Ten(A,[z,3])\neq2=@equ invA=Alt([j,m,n])*Alt([i,p,q])*Ten(A,[m,p])*Ten(A,[n,q])/(2detA)\neq3=eq2&eq1&Equation(:A,A)\n@assert abs((eq3&@equs(i=1,j=3)).rhs-inv(A)[1,3])<0.001\n\n#Matrix multiplication\nB=rand(Int,3,3).%9\nAB=[Equation(:A,A),Equation(:B,B)]\nC=Ten(:A,[:i,:k])*Ten(:B,[:k,:j])\n@assert C&AB&@equs(i=3,j=2) == (A*B)[3,2]\n\nD=Ten(:A,[:i,:j])*Ten(:B,[:i,:j])\n@assert D&AB==sum(A.*B)\n", "meta": {"hexsha": "949983f50ee6a5748bef85b4f77d96bc5ae2d4fa", "size": 1704, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/tensors.jl", "max_stars_repo_name": "jhlq/Equations.jl", "max_stars_repo_head_hexsha": "e6c97688630181a485832ad0a75306cb6e8a3453", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2015-04-15T13:19:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T03:04:25.000Z", "max_issues_repo_path": "examples/tensors.jl", "max_issues_repo_name": "jhlq/Equations.jl", "max_issues_repo_head_hexsha": "e6c97688630181a485832ad0a75306cb6e8a3453", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2015-04-18T11:47:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T08:30:40.000Z", "max_forks_repo_path": "examples/tensors.jl", "max_forks_repo_name": "jhlq/Equations.jl", "max_forks_repo_head_hexsha": "e6c97688630181a485832ad0a75306cb6e8a3453", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2015-06-01T06:36:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T18:16:08.000Z", "avg_line_length": 26.625, "max_line_length": 87, "alphanum_fraction": 0.5627934272, "num_tokens": 850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992914310606, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.8107317709604895}} {"text": "# Centroid\n# ---------------------------------------------------------------------------------------------\n# (https://en.wikipedia.org/wiki/Centroid#Of_a_polygon)\nfunction centroid(poly::Polygon{N, 2, T}) where {N, T}\n a = zero(T) # Scalar\n c = SVector{2,T}(0,0)\n for i ∈ 1:N-1\n subarea = poly[i] × poly[i+1]\n c += subarea*(poly[i] + poly[i+1])\n a += subarea\n end\n subarea = poly[N] × poly[1]\n c += subarea*(poly[N] + poly[1])\n a += subarea\n return Point(c/(3a))\nend\n\ncentroid(tri::Triangle2D) = Point((tri[1] + tri[2] + tri[3])/3)\ncentroid(tri::Triangle3D) = Point((tri[1] + tri[2] + tri[3])/3)\n\ncentroid(quad8::QuadraticQuadrilateral2D) = centroid(quad8, Val(3))\nfunction centroid(quad8::QuadraticQuadrilateral{Dim, T}, ::Val{N}) where {Dim, T, N}\n # Gauss-Legendre quadrature over a quadrilateral is used.\n # Let Q(r,s) be the interpolation function for quad8,\n # 1 1 N N \n # A = ∬ dA = ∫ ∫ ‖∂Q/∂r × ∂Q/∂s‖ds dr = ∑ ∑ wᵢwⱼ‖∂Q/∂r(rᵢ,sⱼ) × ∂Q/∂s(rᵢ,sⱼ)‖\n # S 0 0 j=1 i=1\n # 1 N N \n # 𝗖 = (∬ 𝘅 dA)/A = - ∑ ∑ 𝘅ᵢⱼwᵢwⱼ‖∂Q/∂r(rᵢ,sⱼ) × ∂Q/∂s(rᵢ,sⱼ)‖\n # S A j=1 i=1\n w, r = gauss_legendre_quadrature(T, Val(N))\n A = zero(T)\n 𝗖 = @SVector zeros(T, Dim)\n for j ∈ 1:N, i ∈ 1:N\n J = 𝗝(quad8, r[i], r[j])\n weighted_val = w[i]*w[j]*norm(view(J, :, 1) × view(J, :, 2))\n 𝗖 += weighted_val * quad8(r[i], r[j]).coord\n A += weighted_val\n end\n return Point(𝗖)/A\nend\n\ncentroid(tri6::QuadraticTriangle2D) = centroid(tri6, Val(6))\nfunction centroid(tri6::QuadraticTriangle{Dim, T}, ::Val{N}) where {Dim, T, N} \n # Gauss-Legendre quadrature over a triangle is used.\n # Let F(r,s) be the interpolation function for tri6,\n # 1 1-r N \n # A = ∬ dA = ∫ ∫ ‖∂F/∂r × ∂F/∂s‖ds dr = ∑ wᵢ‖∂F/∂r(rᵢ,sᵢ) × ∂F/∂s(rᵢ,sᵢ)‖\n # S 0 0 i=1\n # 1 N \n # 𝗖 = (∬ 𝘅 dA)/A = - ∑ 𝘅 wᵢ‖∂F/∂r(rᵢ,sᵢ) × ∂F/∂s(rᵢ,sᵢ)‖ \n # S A i=1\n w, r, s = gauss_legendre_quadrature(tri6, Val(N))\n A = zero(T)\n 𝗖 = @SVector zeros(T, Dim)\n for i ∈ 1:N\n J = 𝗝(tri6, r[i], s[i])\n weighted_val = w[i] * norm(view(J, :, 1) × view(J, :, 2)) \n 𝗖 += weighted_val * tri6(r[i], s[i])\n A += weighted_val\n end\n return Point(𝗖)/A\nend\n", "meta": {"hexsha": "c717d52f1b33b91bd5d35611cfc7e81abd87c308", "size": 2521, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/todo/centroid.jl", "max_stars_repo_name": "khurrumsaleem/MOCNeutronTransport", "max_stars_repo_head_hexsha": "16ccaf48d6c01e57e55e74ffbfbd71bbcd0f423c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/todo/centroid.jl", "max_issues_repo_name": "khurrumsaleem/MOCNeutronTransport", "max_issues_repo_head_hexsha": "16ccaf48d6c01e57e55e74ffbfbd71bbcd0f423c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/todo/centroid.jl", "max_forks_repo_name": "khurrumsaleem/MOCNeutronTransport", "max_forks_repo_head_hexsha": "16ccaf48d6c01e57e55e74ffbfbd71bbcd0f423c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.390625, "max_line_length": 95, "alphanum_fraction": 0.4541848473, "num_tokens": 1032, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813526452771, "lm_q2_score": 0.8479677660619633, "lm_q1q2_score": 0.8106413719995096}} {"text": "\"\"\"\n BinLik <: Likelihood\n\nBinomial likelihood\n```math\np(y = k | f) = k!/(n!(n-k)!) θᵏ(1 - θ)^{n-k}\n```\nfor number of successes ``k ∈ \\\\{0, 1, …, n\\\\}`` out of ``n`` Bernoulli trials, where\n``θ = \\\\exp(f)/(1 + \\\\exp(f))`` and ``f`` is the latent Gaussian process.\n\"\"\"\nstruct BinLik <: Likelihood\n \"Fixed number of trials\"\n n::Int\nend\n\nfunction log_dens(binomial::BinLik, f::AbstractVector, y::Vector{Int})\n θ = @. exp(f) / (1 + exp(f))\n return Float64[lgamma(binomial.n+1.0) - lgamma(yi+1.0) - lgamma(binomial.n-yi+1.0) + yi*log(θi) + (binomial.n-yi)*log(1-θi) for (θi,yi) in zip(θ,y)]\nend\n\nfunction dlog_dens_df(binomial::BinLik, f::AbstractVector, y::Vector{Int})\n return Float64[yi/(1.0+exp(fi)) - (binomial.n-yi)*exp(fi)/(1+exp(fi)) for (fi,yi) in zip(f,y)]\nend\n\n#mean and variance under the likelihood\nmean_lik(binomial::BinLik, f::AbstractVector) = Float64[binomial.n*exp(fi)/(1.0+exp(fi)) for fi in f]\nvar_lik(binomial::BinLik, f::AbstractVector) = Float64[binomial.n*(exp(fi)/(1.0+exp(fi)))*(1.0/(1.0+exp(fi))) for fi in f]\n\nget_params(binomial::BinLik) = []\nnum_params(binomial::BinLik) = 0\n", "meta": {"hexsha": "3c0101d98a49f278f21dbd27dc0bf9da82c38657", "size": 1118, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/likelihoods/binomial.jl", "max_stars_repo_name": "mcusi/GaussianProcesses.jl", "max_stars_repo_head_hexsha": "7d268974aa0cd5c4164542c513307305d785da6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 284, "max_stars_repo_stars_event_min_datetime": "2015-07-31T21:32:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T07:08:58.000Z", "max_issues_repo_path": "src/likelihoods/binomial.jl", "max_issues_repo_name": "mcusi/GaussianProcesses.jl", "max_issues_repo_head_hexsha": "7d268974aa0cd5c4164542c513307305d785da6d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 171, "max_issues_repo_issues_event_min_datetime": "2015-05-28T12:04:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T06:48:23.000Z", "max_forks_repo_path": "src/likelihoods/binomial.jl", "max_forks_repo_name": "mcusi/GaussianProcesses.jl", "max_forks_repo_head_hexsha": "7d268974aa0cd5c4164542c513307305d785da6d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 59, "max_forks_repo_forks_event_min_datetime": "2015-05-31T12:44:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:21:38.000Z", "avg_line_length": 36.064516129, "max_line_length": 152, "alphanum_fraction": 0.6359570662, "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813551535005, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.8106413649440368}} {"text": "using Pkg\nPkg.add(\"Latexify\")\nusing Latexify\n\nPkg.add(\"Plots\")\nusing Plots\nPkg.add(\"PyPlot\")\npyplot()\n\n# Julia code for linear Stommel problem solution in \"F. X. GIRALDO AND M. RESTELLI\" \n# High-order semi-implicit time-integrators for a triangular discontinuous Galerkin \n# oceanic shallow water model\n\nL=1e6 # Basin size\nτ₀=0.2\nβ=1e-11\nf₀=1e-4\nγ=1e-6\ng=10\nH=1000\nρ=1000\n\n# Derived terms\ny_m=L/2\nϕ_B=g*H\n\nETMP01=:( ((β/γ)^2+4*(π/L)^2)^0.5 )\nλ₁_def=:( λ₁ = (-β/γ+$ETMP01)/2 )\nλ₂_def=:( λ₂ = (-β/γ-$ETMP01)/2 )\ndisplay( latexify(λ₁_def) )\ndisplay( latexify(λ₂_def) )\n\nC₀_def=:( C₀ = τ₀/(γ*ρ*H)*(L/π) )\nC₁_def=:( C₁ = C₀*( (1-exp(λ₂*L)) / (exp(λ₂*L) - exp(λ₁*L)) ) )\nC₂_def=:( C₂ = -C₀*( (1-exp(λ₁*L)) / (exp(λ₂*L) - exp(λ₁*L)) ) )\ndisplay( latexify(C₀_def) )\ndisplay( latexify(C₁_def) )\ndisplay( latexify(C₂_def) )\n\nψ_def=:( ψ = (C₀ + C₁*exp(λ₁*x) + C₂*exp(λ₂*x))*sin((π*y)/L) )\ndisplay( latexify(ψ_def) )\n\ndisplay( λ₁_def )\ndisplay( λ₂_def )\ndisplay( C₀_def )\ndisplay( C₁_def )\ndisplay( C₂_def )\ndisplay( ψ_def ) \n\n\nλ₁ = (-β / γ + ((β / γ) ^ 2 + 4 * (π / L) ^ 2) ^ 0.5) / 2\nλ₂ = (-β / γ - ((β / γ) ^ 2 + 4 * (π / L) ^ 2) ^ 0.5) / 2\nC₀ = (τ₀ / (γ * ρ * H)) * (L / π)\nC₁ = C₀ * ((1 - exp(λ₂ * L)) / (exp(λ₂ * L) - exp(λ₁ * L)))\nC₂ = -C₀ * ((1 - exp(λ₁ * L)) / (exp(λ₂ * L) - exp(λ₁ * L)))\nψ(x,y) = (C₀ + C₁ * exp(λ₁ * x) + C₂ * exp(λ₂ * x)) * sin((π * y) / L)\n\n\nnx=ny=50;\nx=collect(range(0.,L,step=L/nx))\ny=collect(range(0.,L,step=L/ny))\nψval=zeros(nx+1,ny+1)\nfor j=1:ny\n for i=1:nx\n ψval[i,j]=ψ(x[i],y[j])\n end\nend\nψval\n\np1 = contour(x, y, ψval')\nplot(p1)\n\n\nETMP01=:( C₀*β*L/π*cos(π*y/L) +fofy*ψ )\nETMP02=:( C₁/λ₁*exp(λ₁*x)+C₂/λ₂*exp(λ₂*x) )\ndisplay( latexify(ETMP01) )\ndisplay( latexify(ETMP02) )\nϕ_s_def=:( ϕ_s = $ETMP01 + γ*π/L*cos(π*y/L)*$ETMP02 )\ndisplay( latexify(ϕ_s_def) )\n\nϕ_s_func(x,y,fofy)=(((C₀ * β * L) / π) * cos((π * y) / L) + fofy * ψval[x,y]) + ((γ * π) / L) * cos((π * y) / L) * ((C₁ / λ₁) * exp(λ₁ * x) + (C₂ / λ₂) * exp(λ₂ * x))\n\nϕ_s_val=zeros(nx+1,ny+1)\nfor j=1:ny+1\n for i=1:nx+1\n ϕ_s_val[i,j]=ϕ_s_func( i,j,f₀+β*y[j] )\n end\nend\n\np1 = contour(x, y, ϕ_s_val')\nplot(p1)\n", "meta": {"hexsha": "5483ba1042400598b36c77f024a33f71dba0f5fa", "size": 2095, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "gyre-exact-solutions/gandr-sw-lin-psi.jl", "max_stars_repo_name": "christophernhill/climahacks", "max_stars_repo_head_hexsha": "c5db08e8dcc76204ee21dfed5457599bec31d7f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gyre-exact-solutions/gandr-sw-lin-psi.jl", "max_issues_repo_name": "christophernhill/climahacks", "max_issues_repo_head_hexsha": "c5db08e8dcc76204ee21dfed5457599bec31d7f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gyre-exact-solutions/gandr-sw-lin-psi.jl", "max_forks_repo_name": "christophernhill/climahacks", "max_forks_repo_head_hexsha": "c5db08e8dcc76204ee21dfed5457599bec31d7f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.7717391304, "max_line_length": 166, "alphanum_fraction": 0.5622911695, "num_tokens": 1043, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813463747181, "lm_q2_score": 0.8479677602988602, "lm_q1q2_score": 0.8106413611728587}} {"text": "# Copyright 2017, Iain Dunning, Joey Huchette, Miles Lubin, and contributors #src\n# This Source Code Form is subject to the terms of the Mozilla Public License #src\n# v.2.0. If a copy of the MPL was not distributed with this file, You can #src\n# obtain one at https://mozilla.org/MPL/2.0/. #src\n\n# # The minimum distortion problem\n\n# This example arises from computational geometry, in particular the problem of\n# embedding a general finite metric space into a euclidean space.\n#\n# It is known that the 4-point metric space defined by the star graph:\n#\n# x\n# \\\\\n# x — x\n# /\n# x\n#\n# where distances are computed by length of the shortest path between vertices,\n# cannot be exactly embedded into a euclidean space of any dimension.\n#\n# Here we will formulate and solve an SDP to compute the best possible embedding,\n# that is, the embedding f() that minimizes the distortion c such that\n#\n# (1 / c) * D(a, b) ≤ ||f(a) - f(b)|| ≤ D(a, b)\n#\n# for all points (a, b), where D(a, b) is the distance in the metric space.\n#\n# Any embedding can be characterized by its Gram matrix Q, which is PSD, and\n#\n# ||f(a) - f(b)||^2 = Q[a, a] + Q[b, b] - 2 * Q[a, b]\n#\n# We can therefore constrain\n#\n# D[i, j]^2 ≤ Q[i, i] + Q[j, j] - 2 * Q[i, j] ≤ c^2 * D[i, j]^2\n#\n# and minimize c^2, which gives us the SDP formulation below.\n#\n# For more detail, see \"Lectures on discrete geometry\" by J. Matoušek, Springer,\n# 2002, pp. 378-379.\n\nusing JuMP\nimport SCS\nimport Test\n\nfunction example_min_distortion()\n model = Model(SCS.Optimizer)\n set_silent(model)\n D = [\n 0.0 1.0 1.0 1.0;\n 1.0 0.0 2.0 2.0;\n 1.0 2.0 0.0 2.0;\n 1.0 2.0 2.0 0.0\n ]\n @variable(model, c² >= 1.0)\n @variable(model, Q[1:4, 1:4], PSD)\n for i in 1:4\n for j in (i + 1):4\n @constraint(model, D[i, j]^2 <= Q[i, i] + Q[j, j] - 2 * Q[i, j])\n @constraint(model, Q[i, i] + Q[j, j] - 2 * Q[i, j] <= c² * D[i, j]^2)\n end\n end\n @objective(model, Min, c²)\n optimize!(model)\n Test.@test termination_status(model) == MOI.OPTIMAL\n Test.@test primal_status(model) == MOI.FEASIBLE_POINT\n Test.@test objective_value(model) ≈ 4/3 atol = 1e-4\n return\nend\n\nexample_min_distortion()\n", "meta": {"hexsha": "391b0bce446325e9d053b13a011eb9adc558e362", "size": 2291, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/min_distortion.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/min_distortion.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/min_distortion.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8194444444, "max_line_length": 84, "alphanum_fraction": 0.6093408992, "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813463747182, "lm_q2_score": 0.8479677526147222, "lm_q1q2_score": 0.8106413538269661}} {"text": "\"\"\"\n newton(f,dfdx,x₁[;maxiter,ftol,xtol])\n\nUse Newton's method to find a root of `f` starting from `x₁`, where\n`dfdx` is the derivative of `f`. Returns a vector of root estimates.\n\nThe optional keyword parameters set the maximum number of iterations\nand the stopping tolerance for values of `f` and changes in `x`.\n\"\"\"\nfunction newton(f,dfdx,x₁;maxiter=40,ftol=100*eps(),xtol=100*eps())\n x = [float(x₁)]\n y = f(x₁)\n Δx = Inf # for initial pass below\n k = 1\n\n while (abs(Δx) > xtol) && (abs(y) > ftol)\n dydx = dfdx(x[k])\n Δx = -y/dydx # Newton step\n push!(x,x[k]+Δx) # append new estimate\n\n k += 1\n y = f(x[k])\n if k==maxiter\n @warn \"Maximum number of iterations reached.\"\n break # exit loop\n end\n end\n return x\nend\n\n\"\"\"\n secant(f,x₁,x₂[;maxiter,ftol,xtol])\n\nUse the secant method to find a root of `f` starting from `x₁` and\n`x₂`. Returns a vector of root estimates.\n\nThe optional keyword parameters set the maximum number of iterations\nand the stopping tolerance for values of `f` and changes in `x`.\n\"\"\"\nfunction secant(f,x₁,x₂;maxiter=40,ftol=100*eps(),xtol=100*eps())\n x = [float(x₁),float(x₂)]\n y₁ = f(x₁)\n Δx,y₂ = Inf,Inf # for initial pass in the loop below\n k = 2\n\n while (abs(Δx) > xtol) && (abs(y₂) > ftol) \n y₂ = f(x[k])\n Δx = -y₂ * (x[k]-x[k-1]) / (y₂-y₁) # secant step\n push!(x,x[k]+Δx) # append new estimate\n\n k += 1\n y₁ = y₂ # current f-value becomes the old one next time\n \n if k==maxiter\n @warn \"Maximum number of iterations reached.\"\n break # exit loop\n end\n end\n return x\nend\n\n\"\"\"\n newtonsys(f,jac,x₁[;maxiter,ftol,xtol])\n\nUse Newton's method to find a root of a system of equations,\nstarting from `x₁`. The functions `f` and `jac should return the\nresidual vector and the Jacobian matrix, respectively. Returns the\nhistory of root estimates as a vector of vectors.\n\nThe optional keyword parameters set the maximum number of iterations\nand the stopping tolerance for values of `f` and changes in `x`.\n\n\"\"\"\nfunction newtonsys(f,jac,x₁;maxiter=40,ftol=1000*eps(),xtol=1000*eps())\n x = [float(x₁)]\n y,J = f(x₁),jac(x₁)\n Δx = Inf # for initial pass below\n k = 1\n\n while (norm(Δx) > xtol) && (norm(y) > ftol)\n Δx = -(J\\y) # Newton step\n push!(x,x[k] + Δx) # append to history\n k += 1\n y,J = f(x[k]),jac(x[k])\n\n if k==maxiter\n @warn \"Maximum number of iterations reached.\"\n break\n end\n end\n return x\nend\n\n\"\"\"\n fdjac(f,x₀[,y₀])\n\nCompute a finite-difference approximation of the Jacobian matrix for\n`f` at `x₀`, where `y₀`=`f(x₀)` may be given.\n\"\"\"\nfunction fdjac(f,x₀,y₀=f(x₀))\n δ = sqrt(eps())*max(norm(x₀),1) # FD step size\n m,n = length(y₀),length(x₀)\n if n==1\n J = (f(x₀+δ) - y₀) / δ\n else\n J = zeros(m,n)\n x = copy(x₀)\n for j in 1:n\n x[j] += δ\n J[:,j] = (f(x) - y₀) / δ\n x[j] -= δ\n end\n end\n return J\nend\n\n\"\"\"\n levenberg(f,x₁[;maxiter,ftol,xtol])\n\nUse Levenberg's quasi-Newton iteration to find a root of the system\n`f`, starting from `x₁`, with `tol` as the stopping tolerance in\nboth step size and residual norm. Returns the history of root estimates \nas a vector of vectors.\n\nThe optional keyword parameters set the maximum number of iterations\nand the stopping tolerance for values of `f` and changes in `x`.\n\n\"\"\"\nfunction levenberg(f,x₁;maxiter=40,ftol=1e-12,xtol=1e-12)\n x = [float(x₁)]\n yₖ = f(x₁)\n k = 1; s = Inf;\n A = fdjac(f,x[k],yₖ) # start with FD Jacobian\n jac_is_new = true\n\n λ = 10;\n while (norm(s) > xtol) && (norm(yₖ) > ftol)\n # Compute the proposed step.\n B = A'*A + λ*I\n z = A'*yₖ\n s = -(B\\z)\n \n x̂ = x[k] + s\n ŷ = f(x̂)\n\n # Do we accept the result?\n if norm(ŷ) < norm(yₖ) # accept\n λ = λ/10 # get closer to Newton\n # Broyden update of the Jacobian.\n A += (ŷ-yₖ-A*s)*(s'/(s'*s))\n jac_is_new = false\n \n push!(x,x̂)\n yₖ = ŷ\n k += 1\n else # don't accept\n # Get closer to gradient descent.\n λ = 4λ\n # Re-initialize the Jacobian if it's out of date.\n if !jac_is_new\n A = fdjac(f,x[k],yₖ)\n jac_is_new = true\n end\n end\n\n if k==maxiter\n @warn \"Maximum number of iterations reached.\"\n break\n end\n \n end\n return x\nend\n", "meta": {"hexsha": "28964c5a90f960ebeeadcd3e7b299d658f34a3c1", "size": 4733, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chapter04.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/chapter04.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/chapter04.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": 27.2011494253, "max_line_length": 72, "alphanum_fraction": 0.5470103528, "num_tokens": 1484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242073, "lm_q2_score": 0.8740772384450967, "lm_q1q2_score": 0.8105871432300875}} {"text": "using DiscreteFiltering\nusing OrdinaryDiffEq: ODEProblem, solve, QNDF\nusing LinearAlgebra\nusing Plots\nusing SparseArrays\n\n\n## Filter\nh₀ = 0.03\nh(x) = h₀ * (1 - 1 / 2 * cos(x))\ndh(x) = 0.0 # h₀ / 2 * sin(x)\nα(x) = 1 / 3 * dh(x) * h(x)\nfilter = TopHatFilter(h)\n\n\n## Domain\na = 0.0\nb = 2π\ndomain = PeriodicIntervalDomain(a, b)\n# domain = ClosedIntervalDomain(a, b)\n\n\n## Discretization\nN = 500\nM = N\nx = discretize(domain, M)\nξ = discretize(domain, N)\nΔx = (b - a) / N\n\nΔx^2 / maximum(abs.(α.(x)))\n\n\n## Time\nT = 1.0\nt = T\n\n\n## Plot filter\nplot(x, h)\nylims!((0, ylims()[2]))\n\n\n## Get matrices\nC = advection_matrix(domain, N)\nD = diffusion_matrix(domain, N)\nW = filter_matrix(filter, domain, M, N)\nR = reconstruction_matrix(filter, domain, M, N)\nA = spdiagm(α.(ξ))\n\n\n## Exact solutions\nu₀(ξ) = sin(ξ) + 0.6cos(5ξ) + 0.04sin(20(ξ - 1))\n\n## Discrete initial conditions\nuₕ = u₀.(ξ, 0.0)\nplot(ξ, uₕ, label = \"Discretized\")\n\n## Extension to a non-linear case: Burgers equation\nν = 0.03\nduₕ(uₕ, p, t) = -uₕ .* (C * uₕ) + ν * D * uₕ\nprob = ODEProblem(duₕ, uₕ, (0, T))\nsol = solve(prob, QNDF(), abstol = 1e-6, reltol = 1e-4)\n\nfunction duₕ_allbar(uₕ_allbar, p, t)\n uₕ = R * uₕ_allbar\n -W * (uₕ .* (C * uₕ)) + ν * W * D * uₕ\nend\nprob_allbar = ODEProblem(duₕ_allbar, W * uₕ, (0, T))\nsol_allbar = solve(prob_allbar, QNDF(), abstol = 1e-6, reltol = 1e-4)\n\nplot(ξ, uₕ, label = \"Initial\")\nplot!(x, W * uₕ, label = \"Initial discretized-then-filtered\")\n#plot!(ξ, sol(t), label = \"Discretized\")\nplot!(x, W * sol(t), label = \"W * Discretized\")\nplot!(x, sol_allbar(t), label = \"Discretized-then-filtered\")\nylims!(minimum(uₕ), maximum(uₕ))\n", "meta": {"hexsha": "08c588163afd87856f3edb7f3cb0772ca78d93cf", "size": 1619, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/burgers.jl", "max_stars_repo_name": "agdestein/DiscreteFiltering.jl", "max_stars_repo_head_hexsha": "e57d4b95ee2bc35e594279c491dba56a753548b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-23T12:51:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-23T12:51:11.000Z", "max_issues_repo_path": "examples/burgers.jl", "max_issues_repo_name": "agdestein/DiscreteFiltering.jl", "max_issues_repo_head_hexsha": "e57d4b95ee2bc35e594279c491dba56a753548b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/burgers.jl", "max_forks_repo_name": "agdestein/DiscreteFiltering.jl", "max_forks_repo_head_hexsha": "e57d4b95ee2bc35e594279c491dba56a753548b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.025974026, "max_line_length": 69, "alphanum_fraction": 0.6244595429, "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242074, "lm_q2_score": 0.8740772368049823, "lm_q1q2_score": 0.8105871417091057}} {"text": "module ConvexHull\n\nstruct Point\n x::Float64\n y::Float64\nend\n\nfunction Base.isless(p::Point, q::Point)\n p.x < q.x || (p.x == q.x && p.y < q.y)\nend\n\nfunction isrightturn(p::Point, q::Point, r::Point)\n (q.x - p.x) * (r.y - p.y) - (q.y - p.y) * (r.x - p.x) < 0\nend\n\nfunction grahamscan(points::Vector{Point})\n sorted = sort(points)\n upperhull = halfhull(sorted)\n lowerhull = halfhull(reverse(sorted))\n [upperhull..., lowerhull[2:end-1]...]\nend\n\nfunction halfhull(points::Vector{Point})\n halfhull = points[1:2]\n for p in points[3:end]\n push!(halfhull, p)\n while length(halfhull) > 2 && !isrightturn(halfhull[end-2:end]...)\n deleteat!(halfhull, length(halfhull) - 1)\n end\n end\n halfhull\nend\n\nend # module\n", "meta": {"hexsha": "9cba7bcead10288f05e66c324f0500349bf58232", "size": 767, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ConvexHull.jl", "max_stars_repo_name": "aaronang/ConvexHull.jl", "max_stars_repo_head_hexsha": "1813834b20c5246a9562f7c80d3a253b652423fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-30T16:31:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-30T16:31:23.000Z", "max_issues_repo_path": "src/ConvexHull.jl", "max_issues_repo_name": "aaronang/ConvexHull.jl", "max_issues_repo_head_hexsha": "1813834b20c5246a9562f7c80d3a253b652423fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ConvexHull.jl", "max_forks_repo_name": "aaronang/ConvexHull.jl", "max_forks_repo_head_hexsha": "1813834b20c5246a9562f7c80d3a253b652423fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.9142857143, "max_line_length": 74, "alphanum_fraction": 0.5984354628, "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947132556618, "lm_q2_score": 0.8577681013541611, "lm_q1q2_score": 0.8105863209790289}} {"text": "module NewtonsMethod\n\ngreet() = print(\"Hello World!\")\n\nusing LinearAlgebra, ForwardDiff, Statistics\n\nfunction newtonroot(f, f_prime; x0, tol = 1E-7, maxiter = 1000)\n x_old = x0\n iter = 1\n while normdiff > tol && iter <= maxiter\n x_new = x_old - (f(x_old)/f_prime(x_old)) \n normdiff = norm(x_new - x_old)\n x_old = x_new\n iter = iter + 1\n end\n if normdiff > tol\n return nothing\n else\n return x_old\n end\n\nend\n\n\nfunction newtonroot(f; x0, tol = 1E-7, maxiter = 1000)\n f_prime(x) = ForwardDiff.derivative(f,x)\n x_old = x0\n normdiff = Inf\n iter = 1\n while normdiff > tol && iter <= maxiter\n x_new = x_old - (f(x_old)/f_prime(x_old)) \n normdiff = norm(x_new - x_old)\n x_old = x_new\n iter = iter + 1\n end\n if normdiff > tol\n return nothing\n else\n return x_old\n end\nend\n\nexport newtonroot\nend # module\n", "meta": {"hexsha": "fd463bbf2ba50b9f1f2773cd792aee5c5e9ee51f", "size": 925, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NewtonsMethod.jl", "max_stars_repo_name": "fernandosecco/NewtonsMethod.jl", "max_stars_repo_head_hexsha": "67596a2778418d18937e053481c6bd03a93d6ac2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NewtonsMethod.jl", "max_issues_repo_name": "fernandosecco/NewtonsMethod.jl", "max_issues_repo_head_hexsha": "67596a2778418d18937e053481c6bd03a93d6ac2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NewtonsMethod.jl", "max_forks_repo_name": "fernandosecco/NewtonsMethod.jl", "max_forks_repo_head_hexsha": "67596a2778418d18937e053481c6bd03a93d6ac2", "max_forks_repo_licenses": ["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.5555555556, "max_line_length": 63, "alphanum_fraction": 0.5881081081, "num_tokens": 295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897525789548, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.8105263239048742}} {"text": "#=\nIn the 20×20 grid below, four numbers along a diagonal line have been marked in red.\n\n08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08\n49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00\n81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65\n52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91\n22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80\n24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50\n32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70\n67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21\n24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72\n21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95\n78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92\n16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57\n86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58\n19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40\n04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66\n88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69\n04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36\n20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16\n20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54\n01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48\nThe product of these numbers is 26 × 63 × 78 × 14 = 1788696.\n\nWhat is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid?\n=#\n\nusing DelimitedFiles\n\nfunction calc(x, i, j, adjacents)\n ar = Function[]\n push!(ar, (i,j)->ijj>=adjacents) # up\n push!(ar, (i,j)->i>=adjacents) # left\n push!(ar, (i,j)->i+adjacentsi-adjacents>0 && j+adjacents img = testimage(\"cameraman\");\n\njulia> p = CartesianIndex(35, 35);\n\njulia> indices = ReduceNoise.block_matching(img, p; num_patches=5, patch_size=7)\n5-element Array{CartesianIndices{2,Tuple{UnitRange{Int64},UnitRange{Int64}}},1}:\n[...]\n\njulia> first(indices) == p # p is always the first item\ntrue\n```\n\n\"\"\"\nfunction block_matching(\n f, img, p::CartesianIndex;\n num_patches,\n patch_size,\n search_window_size=size(img),\n patch_stride=patch_size)::Vector{CartesianIndices{ndims(img)}}\n # Offset is not considered, it might work, it might not work. I don't know yet.\n Base.require_one_based_indexing(img)\n\n patch_size isa Number && (patch_size = ntuple(_ -> patch_size, ndims(img)))\n patch_stride isa Number && (patch_stride = ntuple(_ -> patch_stride, ndims(img)))\n search_window_size isa Number && (search_window_size = ntuple(_ -> search_window_size, ndims(img)))\n all(isodd.(patch_size)) || throw(ArgumentError(\"`patch_size = $(patch_size)` should be odd numbers\"))\n\n R = CartesianIndices(img)\n rₚ = CartesianIndex(patch_size .÷ 2) # patch radius\n Base.@boundscheck checkbounds(R, p - rₚ)\n Base.@boundscheck checkbounds(R, p + rₚ)\n\n Δ = CartesianIndex(patch_stride)\n rₛ = CartesianIndex(search_window_size .÷ 2) # search window radius\n\n # for simplicity, only consider the patches that do not exceed the image boundary\n # This requires at least Julia 1.6: https://github.com/JuliaLang/julia/pull/37829\n I_first, I_last = first(R) + rₚ, last(R) - rₚ\n Rw = vec(max(I_first, p-rₛ):Δ:min(p+rₛ, I_last))\n length(Rw) <= num_patches && throw(ArgumentError(\"search window size $(search_window_size) is too small to get enough patches\"))\n\n # patch_p is used repeatly so we need a contiguous memeory layout to get better performance\n # TODO: pre-allocate patch_p?\n patch_p = img[p - rₚ:p + rₚ]\n # patch_q = similar(patch_p)\n dist = map(Rw) do q\n patch_q = @view img[q - rₚ:q + rₚ]\n f(patch_p, patch_q)\n end\n dist_ranks = partialsortperm(dist, 1:num_patches)\n\n return [q - rₚ:q + rₚ for q in Rw[dist_ranks]]\nend\nblock_matching(img, p::CartesianIndex; kwargs...) = block_matching(ssd, img, p::CartesianIndex; kwargs...)\n\n\n# Threads helper\n\nfunction get_num_threads()\n blas = LinearAlgebra.BLAS.vendor()\n # Wrap in a try to catch unsupported blas versions\n try\n if blas == :openblas\n return ccall((:openblas_get_num_threads, Base.libblas_name), Cint, ())\n elseif blas == :openblas64\n return ccall((:openblas_get_num_threads64_, Base.libblas_name), Cint, ())\n elseif blas == :mkl\n return ccall((:MKL_Get_Max_Num_Threads, Base.libblas_name), Cint, ())\n end\n\n # OSX BLAS looks at an environment variable\n if Sys.isapple()\n return tryparse(Cint, get(ENV, \"VECLIB_MAXIMUM_THREADS\", \"1\"))\n end\n catch\n end\n\n return nothing\nend\n\nfunction with_blas_threads(f, num_threads)\n prev_num_threads = get_num_threads()\n prev_num_threads = isnothing(prev_num_threads) ? 1 : prev_num_threads\n BLAS.set_num_threads(num_threads)\n retval = nothing\n try\n retval = f()\n catch err\n rethrow(err)\n finally\n BLAS.set_num_threads(prev_num_threads)\n end\n\n return retval\nend\n", "meta": {"hexsha": "680aa4c2ecfbf1c9e606b67e0a9ba90cc399e371", "size": 5309, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utilities.jl", "max_stars_repo_name": "ramsterdam91/WNNMDenoise.jl", "max_stars_repo_head_hexsha": "ced27bd03738c04b62de6ad00fd132f90abe9220", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-02T03:00:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-02T03:00:01.000Z", "max_issues_repo_path": "src/utilities.jl", "max_issues_repo_name": "ramsterdam91/WNNMDenoise.jl", "max_issues_repo_head_hexsha": "ced27bd03738c04b62de6ad00fd132f90abe9220", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utilities.jl", "max_forks_repo_name": "ramsterdam91/WNNMDenoise.jl", "max_forks_repo_head_hexsha": "ced27bd03738c04b62de6ad00fd132f90abe9220", "max_forks_repo_licenses": ["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.6993464052, "max_line_length": 220, "alphanum_fraction": 0.6871350537, "num_tokens": 1497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.921921841290738, "lm_q2_score": 0.8791467690927439, "lm_q1q2_score": 0.8105046081267857}} {"text": "using Symbolics, Test\nusing DomainSets\n@variables x y\n\nI1 = Integral(x in ClosedInterval(1, 5))\nI2 = Integral(x in ClosedInterval(1, 5))\n@test I1 == I2\n\n@variables v(..) u(..) x y\nD = Differential(x)\nDxx = Differential(x)^2\nI = Integral(y in ClosedInterval(1, 5))\neq = D(I(u(x,y))) ~ 0\neq_test = I(D(u(x,y)))\n@test isequal(expand_derivatives(eq.lhs), Symbolics.value(eq_test))\n\neq = Dxx((I(u(x,y)))) + I(D(u(x,y))) ~ 0\neq_test = I(D(u(x,y))) + I(D(D(u(x,y))))\n@test isequal(expand_derivatives(eq.lhs), Symbolics.value(eq_test))\n\nI = Integral(y in ClosedInterval(1, v(x)))\neq = D((I(u(x,y)))) ~ 0\neq_test = I(D(u(x,y))) + D(v(x))*u(x, v(x))\n@test isequal(expand_derivatives(eq.lhs), Symbolics.value(eq_test))\n\nI = Integral(y in ClosedInterval(1, v(x)))\neq = Dxx((I(u(x,y)))) ~ 0\neq_test = D(I(D(u(x,y))) + D(v(x))*u(x, v(x)))\neq_test_ = I(D(D(u(x,y)))) + D(D(v(x)))*u(x, v(x)) + 2D(u(x,v(x)))*D(v(x))\n@test isequal(expand_derivatives(eq.lhs), Symbolics.value(eq_test_))\n@test isequal(expand_derivatives(eq.lhs), expand_derivatives(eq_test))\n\neq = D((I(u(x,y)^2))) ~ 0\neq_test = I(2D(u(x,y))*u(x,y)) + D(v(x))*u(x, v(x))^2\n@test isequal(expand_derivatives(eq.lhs), Symbolics.value(eq_test))\n", "meta": {"hexsha": "f16345772c5f4030eaa29fb7ebad2dc3759df63d", "size": 1189, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/integral.jl", "max_stars_repo_name": "doppioandante/Symbolics.jl", "max_stars_repo_head_hexsha": "b077a7935c515736916fa63469ad53b0abf2c2d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 907, "max_stars_repo_stars_event_min_datetime": "2021-01-22T02:36:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T23:13:39.000Z", "max_issues_repo_path": "test/integral.jl", "max_issues_repo_name": "doppioandante/Symbolics.jl", "max_issues_repo_head_hexsha": "b077a7935c515736916fa63469ad53b0abf2c2d2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 472, "max_issues_repo_issues_event_min_datetime": "2021-01-21T14:18:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:10:18.000Z", "max_forks_repo_path": "test/integral.jl", "max_forks_repo_name": "doppioandante/Symbolics.jl", "max_forks_repo_head_hexsha": "b077a7935c515736916fa63469ad53b0abf2c2d2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2021-01-25T14:09:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T19:37:30.000Z", "avg_line_length": 33.0277777778, "max_line_length": 74, "alphanum_fraction": 0.629941127, "num_tokens": 424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122696813392, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.8103386420022062}} {"text": "using Distributions, Random\nRandom.seed!(1)\n\nfunction queueDES(T, arrF, serF, capacity = Inf, initQ = 0)\n t, q, qL = 0.0, initQ, 0.0\n\n nextArr, nextSer = arrF(), q == 0 ? Inf : serF()\n while t < T\n tPrev, qPrev = t, q\n if nextSer < nextArr\n t = nextSer\n q -= 1\n if q > 0\n nextSer = t + serF()\n else\n nextSer = Inf\n end\n else\n t = nextArr\n if q == 0\n nextSer = t + serF()\n end\n if q < capacity\n q += 1\n end\n nextArr = t + arrF()\n end\n qL += (t - tPrev)*qPrev\n end\n return qL/t\nend\n\nlam, mu, K = 0.82, 1.3, 5\nrho = lam/mu\nT = 10^6\n\nmm1Theor = rho/(1-rho)\nmd1Theor = rho/(1-rho)*(2-rho)/2\nmm1kTheor = rho/(1-rho)*(1-(K+1)*rho^K+K*rho^(K+1))/(1-rho^(K+1))\n\nmm1Est = queueDES(T,()->rand(Exponential(1/lam)),\n \t\t\t ()->rand(Exponential(1/mu)))\nmd1Est = queueDES(T,()->rand(Exponential(1/lam)),\n ()->1/mu)\nmm1kEst = queueDES(T,()->rand(Exponential(1/lam)),\n ()->rand(Exponential(1/mu)), K)\n\nprintln(\"The load on the system: \",rho)\nprintln(\"Queueing theory: \", (mm1Theor,md1Theor,mm1kTheor) )\nprintln(\"Via simulation: \", (mm1Est,md1Est,mm1kEst) )", "meta": {"hexsha": "a58ec8818284fb4a9495301db7c408a3a3259847", "size": 1351, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "10_chapter/DESqueue.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "10_chapter/DESqueue.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "10_chapter/DESqueue.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 27.02, "max_line_length": 69, "alphanum_fraction": 0.4700222058, "num_tokens": 457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951142221377825, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.8103282859361364}} {"text": "#---------------------------------------------------------------------#\n#This code computes the Legendre-Gauss points & weights\n#which are the roots of the Legendre Polynomials.\n#Written by F.X. Giraldo on 4/2008\n# Department of Applied Mathematics\n# Naval Postgraduate School\n# Monterey; CA 93943-5216\n#---------------------------------------------------------------------#\nfunction legendre_gauss(P::Integer,DFloat)\n\n xgl=zeros(DFloat,P)\n wgl=zeros(DFloat,P)\n\n p=P-1; #Order of Polynomials [P is the number of points: p+1]\n ph=floor(typeof(P), (p+1)/2 )\n\n for i=1:ph\n x=cos( (2*i-1)*pi/(2*p+1) )\n for k=1:20\n (L0,L0_1,L0_2)=legendre_poly(p+1,x); #Compute the N+1 Legendre Polys\n\n #Get new Newton Iteration\n dx=-L0/L0_1\n x=x+dx\n if (abs(dx) < 1.0e-20)\n break\n end\n end\n xgl[p+2-i]=x\n wgl[p+2-i]=2/( (1-x^2)*L0_1^2 )\n end\n\n #Check for Zero Root\n if (p+1 != 2*ph)\n x=0\n (L0,L0_1,L0_2)=legendre_poly(p+1,x)\n xgl[ph+1]=x\n wgl[ph+1]=2/( (1-x^2)*L0_1^2 )\n end\n\n #Find remainder of roots via symmetry\n for i=1:ph\n xgl[i]=-xgl[p+2-i]\n wgl[i]=+wgl[p+2-i]\n end\n return xgl,wgl\nend #function\n", "meta": {"hexsha": "9c71035b59f62b25cdd090df9139c890c577063d", "size": 1309, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Projects/Project_02_1D_Wave/For_Instructors/julia/Global_Matrices_approach/legendre_gauss.jl", "max_stars_repo_name": "fxgiraldo/Element-based-Galerkin-Methods", "max_stars_repo_head_hexsha": "3e7cd28b5d6000a95b00710f15a282b9320b0007", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2019-12-28T06:19:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:40:33.000Z", "max_issues_repo_path": "Projects/Project_05a_1D_Elliptic/For_Students/julia/legendre_gauss.jl", "max_issues_repo_name": "fxgiraldo/Element-based-Galerkin-Methods", "max_issues_repo_head_hexsha": "3e7cd28b5d6000a95b00710f15a282b9320b0007", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-29T19:12:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-29T21:53:41.000Z", "max_forks_repo_path": "Projects/Project_06_2D_Wave/For_Instructors/julia/legendre_gauss.jl", "max_forks_repo_name": "fxgiraldo/Element-based-Galerkin-Methods", "max_forks_repo_head_hexsha": "3e7cd28b5d6000a95b00710f15a282b9320b0007", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2020-09-10T21:35:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T06:53:34.000Z", "avg_line_length": 27.2708333333, "max_line_length": 80, "alphanum_fraction": 0.4782276547, "num_tokens": 428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422199928904, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.8103282847562374}} {"text": "using LinearAlgebra\nusing SparseArrays\nusing Plots\n\nm = 10\nx = LinRange(0,1,m+2) # easier to define eigs on [0,1]\nxint = x[2:end-1]\nh = x[2]-x[1]\nA = (1/h^2) * spdiagm(0=>2*ones(m),-1=>-ones(m-1),1=>-ones(m-1))\n\nλ,V = eigen(Matrix(A))\n# scatter(xint,V[:,1])\n\nfunction normalize_cols!(A)\n for i = 1:size(A,2)\n A[:,i] /= maximum(A[:,i])\n end\nend\nnormalize_cols!(V)\n\nλex = @. 2/h^2 * (1-cos((1:m)*pi*h))\nVex = hcat((sin.(k*pi*xint) for k = 1:m)...)\nnormalize_cols!(Vex)\n\n# plot(xint,V[:,1] .- Vex[:,1])\n# scatter(λ - λex)\n", "meta": {"hexsha": "e4a58712eec4975d7dbac6a484b3ba0bfdf054f2", "size": 532, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "week1/unused_demos/fd_laplace_eigs.jl", "max_stars_repo_name": "jlchan/caam452_s21", "max_stars_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-01-29T01:52:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T15:38:43.000Z", "max_issues_repo_path": "week1/unused_demos/fd_laplace_eigs.jl", "max_issues_repo_name": "jlchan/caam452_s21", "max_issues_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week1/unused_demos/fd_laplace_eigs.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": 19.7037037037, "max_line_length": 64, "alphanum_fraction": 0.5695488722, "num_tokens": 224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422158380861, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.8103282812165402}} {"text": "@inline function checktail(tail::Symbol)\n if tail ∉ (:left, :right, :both)\n throw(ArgumentError(\"Unsupported tail specifier ($tail)\"))\n end\nend\n\n\"\"\"\n logpvalue(nisect::Integer, na::Integer, nb::Integer, ntotal::Integer,\n [tail::Symbol = :right])\n\nLog P-value for the two sets intersection.\n\n`A` has `na` elemnts, B has `nb` elements,\nthey have `nisect` elements in common, and there are\n`ntotal` elements in the \"universe\".\n\n`tail` controls the null hypothesis:\n* `:right` (default): by chance `A` and `B` would have ≥ elements in common\n* `:left`: by chance `A` and `B` would have ≤ elements in common\n* `:both`: by chance `A` and `B` would have either ≤ or ≥ elements in common, whichever is less probable\n\"\"\"\nfunction logpvalue(nisect::Integer, na::Integer, nb::Integer, ntotal::Integer,\n tail::Symbol = :right)\n ((na >= 0) && (nb >= 0) && (ntotal >= 0)) ||\n throw(ArgumentError(\"Sets with negative number of elements\"))\n ((na <= ntotal) && (nb <= ntotal)) ||\n throw(ArgumentError(\"Sets bigger than total number of elements\"))\n # corner cases\n isect_max = min(na, nb)\n isect_min = max(0, na + nb - ntotal)\n if tail == :right\n (nisect > isect_max) && return -Inf\n (nisect <= isect_min) && return 0.0\n elseif tail == :left\n (nisect >= isect_max) && return 0.0\n (nisect < isect_min) && return -Inf\n elseif tail != :both\n # FIXME corner cases when tail == :both\n throw(ArgumentError(\"Unsupported tail specifier ($tail)\"))\n end\n # normal cases\n distr = Distributions.Hypergeometric(na, ntotal - na, nb)\n if tail == :right\n return nisect < isect_max ? logccdf(distr, nisect-1) : logpdf(distr, nisect)\n elseif tail == :left\n return nisect > isect_min ? logcdf(distr, nisect) : logpdf(distr, nisect)\n elseif tail == :both\n return log(2.0) + min(logcdf(distr, nisect), logccdf(distr, nisect-1), log(0.5))\n else\n return NaN # noop\n end\nend\n\n# size of the sets intersection\n# the sets are represented by the sorted sets of their tiles\nfunction _isect_size(set1_tiles::AbstractVector{Int},\n set2_tiles::AbstractVector{Int},\n tile_sizes::Vector{Int})\n (length(set1_tiles)==0 || length(set2_tiles)==0) && return 0\n res = 0\n i = 1\n tile1 = set1_tiles[i] # current tile of the 1st set\n j = 1\n tile2 = set2_tiles[j] # current tile of the 2nd set\n @inbounds while true\n if tile1 < tile2\n i += 1\n (i <= length(set1_tiles)) || break\n tile1 = set1_tiles[i]\n elseif tile1 > tile2\n j += 1\n (j <= length(set2_tiles)) || break\n tile2 = set2_tiles[j]\n else # intersecting tile, adjust the overlap\n res += tile_sizes[tile1]\n i += 1\n j += 1\n (i <= length(set1_tiles) && j <= length(set2_tiles)) || break\n tile1 = set1_tiles[i]\n tile2 = set2_tiles[j]\n end\n end\n return res\nend\n\n# returns set×set score matrix\n# a×b score is the Fisher's test P-value of their intersection\n# a×a self-intersections are processed in the same way\n# (might be used later in cover problem construction to penalize the use of\n# multiple variables referencing the same set)\nfunction _setXset_scores(tileXset::SparseMaskMatrix, total_size::Int,\n set_sizes::AbstractVector{Int},\n tile_sizes::AbstractVector{Int},\n used_sets = Base.OneTo(size(tileXset, 2)))\n nsets = length(used_sets)\n res = zeros(Float64, nsets, nsets)\n # fill upper triangle\n @inbounds for i in 1:nsets\n set1_ix = used_sets[i]\n set1_size = set_sizes[set1_ix]\n set1_size == 0 && continue # skip empty sets\n set1_tiles = view(tileXset, :, set1_ix)\n for j in i:nsets\n set2_ix = used_sets[j]\n set2_size = set_sizes[set2_ix]\n set2_size == 0 && continue # skip empty sets\n set2_tiles = view(tileXset, :, set2_ix)\n # one-sided Fisher's P-value, right tail\n isect_size = _isect_size(set1_tiles, set2_tiles, tile_sizes)\n res[i, j] = min(logpvalue(isect_size, set1_size, set1_size + set2_size - isect_size, total_size),\n logpvalue(isect_size, set2_size, set1_size + set2_size - isect_size, total_size))\n end\n end\n # symmetrize: copy upper triangle to lower\n @inbounds for i in 1:nsets\n for j in (i+1):nsets\n res[j, i] = res[i, j]\n end\n end\n return res\nend\n\n\"\"\"\n set_relevance(nset_observed::Integer, nset::Integer,\n nobserved::Integer, ntotal::Integer) -> Float64\n\nCalculates the relevance weight of the set that contains `nset` elements,\n`nset_observed` of which were present (not necessarily enriched) in the data\nthat identified `nobserved` elements out of all known (`ntotal`).\nIt is used by [`SetMosaic`](@ref) to penalize the sets,\nwhich could not be observed in the data (e.g. biological processes or pathways\nthat involve proteins not expressed by the cells used in the experiments).\n\nWhile for [`MaskedSetMosaic`](@ref) it's recommended to use the IDs of data entities\n(e.g. protein group IDs for proteomic data) to correctly count the set sizes\nand estimate enrichment; `set_relevance()` should use the counts derived from\nthe original IDs of the annotation database (e.g. UniProt accession codes).\nOtherwise it's not possible to correctly estimate the number of elements that\nbelong to the given annotated set, but were not observed in the data.\n\nThe returned value is the probability that no more than `nset_observed`\nelements were observed at random.\n\"\"\"\nset_relevance(nset_observed::Integer, nset::Integer,\n nobserved::Integer, ntotal::Integer) =\n cdf(Hypergeometric(nset, ntotal - nset, nobserved), nset_observed)\n", "meta": {"hexsha": "9a99061b7eb39712241ec36234997696a2e8e9d3", "size": 5947, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/set_score.jl", "max_stars_repo_name": "alyst/OptEnrichedSetCover.jl", "max_stars_repo_head_hexsha": "2bcabf6cb08d108e2678bb03328d072921eb0fc9", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/set_score.jl", "max_issues_repo_name": "alyst/OptEnrichedSetCover.jl", "max_issues_repo_head_hexsha": "2bcabf6cb08d108e2678bb03328d072921eb0fc9", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/set_score.jl", "max_forks_repo_name": "alyst/OptEnrichedSetCover.jl", "max_forks_repo_head_hexsha": "2bcabf6cb08d108e2678bb03328d072921eb0fc9", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-04T12:07:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-04T12:07:35.000Z", "avg_line_length": 40.4557823129, "max_line_length": 109, "alphanum_fraction": 0.6359508996, "num_tokens": 1625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422199928904, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.8103282758180119}} {"text": "# This file is a part of AstroLib.jl. License is MIT \"Expat\".\n# Copyright (C) 2016 Mosè Giordano.\n\nfunction _recpol(x::T, y::T, degrees::Bool) where {T<:AbstractFloat}\n if degrees\n return hypot(x, y), rad2deg(atan(y, x))\n else\n return hypot(x, y), atan(y, x)\n end\nend\n\n\"\"\"\n recpol(x, y[, degrees=true]) -> radius, angle\n\n### Purpose ###\n\nConvert 2D rectangular coordinates to polar coordinates.\n\n### Explanation ###\n\nThis is the partial inverse function of `polrec`.\n\n### Arguments ###\n\n* `x`: the abscissa coordinate of the point. It may be a scalar or an array.\n* `y`: the ordinate coordinate of the point. It may be a scalar or an array\n of the same lenth as `x`.\n* `degrees` (optional boolean keyword): if `true`, the output `angle` is given\n in degrees, otherwise in radians. It defaults to `false`.\n\nMandatory arguments may also be passed as the 2-tuple `(x, y)`, so that it is\npossible to execute `polrec(recpol(x, y))`.\n\n### Output ###\n\nA 2-tuple `(radius, angle)` with the polar coordinates of the input. The\ncoordinate `angle` coordinate lies in the range \\$[-\\\\pi, \\\\pi]\\$ if\n`degrees=false`, or \\$[-180, 180]\\$ when `degrees=true`.\n\nIf `x` and `y` are arrays, `radius` and `angle` are arrays of the same length as\n`radius` and `angle`.\n\n### Example ###\n\nCalculate polar coordinates \\$(r, \\\\varphi)\\$ of point with rectangular\ncoordinates \\$(x, y) = (2.24, -1.87)\\$.\n\n```jldoctest\njulia> using AstroLib\n\njulia> r, phi = recpol(2.24, -1.87)\n(2.917961617293826, -0.6956158538564537)\n```\n\nAngle \\$\\\\varphi\\$ is given in radians.\n\n\"\"\"\nrecpol(x::Real, y::Real; degrees::Bool=false) =\n _recpol(promote(float(x), float(y))..., degrees)\n\nrecpol(xy::Tuple{Real, Real}; degrees::Bool=false) =\n recpol(xy..., degrees=degrees)\n\nfunction recpol(x::AbstractArray{X}, y::AbstractArray{Y};\n degrees::Bool=false) where {X<:Real, Y<:Real}\n @assert length(x) == length(y)\n typex = float(X)\n r = similar(x, typex)\n a = similar(x, typex)\n for i in eachindex(x)\n r[i], a[i] = recpol(x[i], y[i], degrees=degrees)\n end\n return r, a\nend\n", "meta": {"hexsha": "ec6f53b9bb9e72a8b72fbad250d6974f5c80040c", "size": 2103, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/recpol.jl", "max_stars_repo_name": "UnofficialJuliaMirror/AstroLib.jl-c7932e45-9af1-51e7-9da9-f004cd3a462b", "max_stars_repo_head_hexsha": "fb2ef587a2ac68a1c864bf251e8d9c3601ec4719", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/recpol.jl", "max_issues_repo_name": "UnofficialJuliaMirror/AstroLib.jl-c7932e45-9af1-51e7-9da9-f004cd3a462b", "max_issues_repo_head_hexsha": "fb2ef587a2ac68a1c864bf251e8d9c3601ec4719", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/recpol.jl", "max_forks_repo_name": "UnofficialJuliaMirror/AstroLib.jl-c7932e45-9af1-51e7-9da9-f004cd3a462b", "max_forks_repo_head_hexsha": "fb2ef587a2ac68a1c864bf251e8d9c3601ec4719", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.04, "max_line_length": 80, "alphanum_fraction": 0.6447931526, "num_tokens": 642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818865, "lm_q2_score": 0.8918110562208681, "lm_q1q2_score": 0.8103154907784743}} {"text": "# # Huber regression\n\n# This example can be found here: .\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 = 50\n number_tests = 10\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 in 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; silent_solver = true)\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; silent_solver = true)\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; silent_solver = true)\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": "4520223cca7f8ca900d8e561a444f40cd3d70293", "size": 2188, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/examples_literate/general_examples/huber_regression.jl", "max_stars_repo_name": "baggepinnen/Convex.jl", "max_stars_repo_head_hexsha": "4f52b6fd4c446cda55e77201037ae22043da2c67", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 327, "max_stars_repo_stars_event_min_datetime": "2015-01-22T01:00:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-12T16:42:11.000Z", "max_issues_repo_path": "docs/examples_literate/general_examples/huber_regression.jl", "max_issues_repo_name": "baggepinnen/Convex.jl", "max_issues_repo_head_hexsha": "4f52b6fd4c446cda55e77201037ae22043da2c67", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 275, "max_issues_repo_issues_event_min_datetime": "2015-01-12T19:27:32.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-05T19:05:45.000Z", "max_forks_repo_path": "docs/examples_literate/general_examples/huber_regression.jl", "max_forks_repo_name": "baggepinnen/Convex.jl", "max_forks_repo_head_hexsha": "4f52b6fd4c446cda55e77201037ae22043da2c67", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 121, "max_forks_repo_forks_event_min_datetime": "2015-01-23T21:13:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-25T13:58:39.000Z", "avg_line_length": 30.8169014085, "max_line_length": 99, "alphanum_fraction": 0.6846435101, "num_tokens": 623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818865, "lm_q2_score": 0.8918110540642805, "lm_q1q2_score": 0.8103154888189602}} {"text": "### A Pluto.jl notebook ###\n# v0.12.7\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 6fd616f6-1ea1-11eb-3814-8bfb4a096c49\nusing Pkg, DrWatson\n\n# ╔═╡ 6ffe2628-1ea1-11eb-24ea-57f985146a72\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing QuadGK, Plots\nend;\n\n# ╔═╡ ed174bc4-1ea0-11eb-1e2f-a32874cec549\nmd\"## Listing 3.3\"\n\n# ╔═╡ 70179b62-1ea1-11eb-13ce-7fb4d54bad4b\nbegin\n\tsup = (-1,1)\n\tf1(x) = 3/4*(1-x^2)\n\tf2(x) = x < 0 ? x+1 : 1-x\n\n\texpect(f,support) = quadgk((x) -> x*f(x),support...)[1]\nend\n\n# ╔═╡ 3a837612-1f94-11eb-315f-0d9296c7ba90\nbegin\n\tx = -1:0.01:1\n\tplot(x, [f1.(x), f2.(x)], lab=[\"f1\" \"f2\"])\nend\n\n# ╔═╡ aa0bdedc-1f93-11eb-12a7-f3ad5370c280\nText(\"Mean 1: $(expect(f1,sup)), Mean 2: $(expect(f2,sup))\")\n\n# ╔═╡ 70182cd8-1ea1-11eb-094d-8d0d49cf15f3\nmd\"## End of listing 3.3\"\n\n# ╔═╡ Cell order:\n# ╟─ed174bc4-1ea0-11eb-1e2f-a32874cec549\n# ╠═6fd616f6-1ea1-11eb-3814-8bfb4a096c49\n# ╠═6ffe2628-1ea1-11eb-24ea-57f985146a72\n# ╠═70179b62-1ea1-11eb-13ce-7fb4d54bad4b\n# ╠═3a837612-1f94-11eb-315f-0d9296c7ba90\n# ╠═aa0bdedc-1f93-11eb-12a7-f3ad5370c280\n# ╟─70182cd8-1ea1-11eb-094d-8d0d49cf15f3\n", "meta": {"hexsha": "f777691ca0a92003671deba54fc3c783856b1a86", "size": 1100, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/03/listing3.03.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/03/listing3.03.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/03/listing3.03.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 22.9166666667, "max_line_length": 60, "alphanum_fraction": 0.6863636364, "num_tokens": 623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110368115781, "lm_q2_score": 0.9086179025005187, "lm_q1q2_score": 0.8103154736945489}} {"text": "# # Direct and inverse FFTW\n\n# Here we test the methods, in FFTW, to be used in our pseudo-spectral code. It is mostly a sanity check.\n\n# We start by loading the packages we need:\n\nusing FFTW\nusing WGLMakie\nusing Test\n\n# ## The spatial domain and its discretization\n\n# We consider a square domain of sides $L = 2\\pi$, for which the smallest wavenumber is $\\kappa_0 = 2\\pi/L$.\n\nL = 2π\nκ₀ = 2π/L\nnothing\n\n# We set the number $N$ of points for the mesh in each direction, yielding a mesh $(x_i, y_j)_{i, j = 1,\\ldots ,N}$, with $x_N = y_N = L$, and steps $x_{i+1} - x_i = L/N$, and $y_{j+1} - y_j = L/N$. Due to the periodicity, we don't need to store the values corresponding to $i = j = 0$.\n\nN = 128\nx = y = (L/N):(L/N):L\nnothing\n\n# We may visualize the grid with a scatter plot, although if the mesh is too thin, we won't quite see the details. If using GLMakie or WGLMakie, one can zoom in for a detailed view.\n\nfig, ax, plt = scatter(vec(x .* one.(y)'), vec(one.(x) .* y'))\n\nfig\n\n# ## A vorticity function for testing\n\n# In order to test the methods from [FFTW.jl](http://www.fftw.org), we define a certain vorticity function and its derivatives\n\nvort = sin.(one.(y) * x') .* cos.(3y * one.(x)')\ndx_vort = cos.(one.(y) * x') .* cos.(3y * one.(x)')\ndy_vort = - 3 * sin.(one.(y) * x') .* sin.(3y * one.(x)')\ndd_vort = - sin.(one.(y) * x') .* cos.(3y * one.(x)') - 9 * sin.(one.(y) * x') .* cos.(3y * one.(x)')\n\nnothing\n\n# We may visualize the vorticity as a surface:\n\nfig = Figure(backgroundcolor = RGBf(0.98, 0.98, 0.98))\n\nax = Axis3(fig[1, 1], xlabel = \"x\", ylabel = \"y\", zlabel = \"vorticity level\", title = \"Vorticity graph\")\n\nsurface!(ax, x, y, vort, colormap = :berlin)\n\nfig\n\n# Or, better yet, as a heatmap:\n\nfig, ax, plt = heatmap(x, y, vort, colormap = :berlin)\n\nax = Axis(fig[1, 1], xlabel = \"x\", ylabel = \"y\", title = \"Vorticity heatmap\")\n\nfig\n\n# ## Testing the direct and inverse discrete Fourier transform\n\n# We check going back and forth with the real fft and inverse real fft:\n\n@testset \"check composition `irfft ∘ rfft`\" begin\n vort_hat = rfft(vort)\n vortback = irfft(vort_hat, N)\n @test vort ≈ vortback\nend\nnothing\n\n# We can also visualize the excited modes:\n\nκ_x = κ₀ * (0:1/N:1/2)\nκ_y = κ₀ * (0:1/N:1-1/N)\n\nvort_hat = rfft(vort)\n\nfig, ax, plt = heatmap(κ_x, κ_y, abs.(vort_hat).^2, colormap = :berlin)\n\nax = Axis(fig[1, 1], xlabel = \"k_x\", ylabel = \"k_y\", title = \"Enstrophy spectrum heatmap\")\n\nfig\n\n# We have excited modes $(\\pm 1, \\pm 3)$. Due to the reality condition of the vorticity, the Fourier spectrum has an Hermitian symmetry around the origin. Using the real Fourier transform, only half of the modes need to be stored. In this case, only modes $(1, \\pm 3)$ are retained. Moreover, the negative modes are shifted above. Due to the one-indexing of Julia, this means that modes $(\\pm a, \\pm b)$ are represented by indices $[a + 1, b + 1]$ and $[a + 1, N + 1 - b]$. In our case, the excited modes are associated with\n\nvort_hat[4, 2]\n\n# and\n\nvort_hat[4, 128]\n\n# These are the only excited modes, as we can check:\n\nfor i in 1:div(N, 2) + 1, j in 1:N\n if abs(vort_hat[i, j])^2 > eps()\n println(\"vort_hat[$i, $j] = $(vort_hat[i, j])\")\n end\nend\n\n# ## Differential operators\n\n# In order to check the derivatives in spectral space, we define the following operators. Actually, they are just vectors, since derivatives in spectral space act as diagonal operators. Hence, a straighforward Hadamard product suffices.\n\nDx_hat = im * κ₀ * [ifelse(k1 ≤ N/2 + 1, k1 - 1, k1 - 1 - N) for k2 in 1:N/2+1, k1 in 1:N]\nDy_hat = im * κ₀ * [k2 - 1 for k2 in 1:N/2+1, k1 in 1:N]\n\nDelta_hat = - κ₀^2 * [\n ifelse(k1 ≤ N/2 + 1, (k1 - 1)^2 + (k2 - 1)^2, (k1 - 1 - N)^2 + (k2 - 1)^2)\n for k2 in 1:N/2+1, k1 in 1:N\n]\n\nHu_hat = - Dy_hat ./ Delta_hat\nHu_hat[1, 1] = 0.0\nHv_hat = Dx_hat ./ Delta_hat\nHv_hat[1, 1] = 0.0\n\nnothing\n\n# ## Testing the spectral operators\n\n# Now we are ready to test the differentiation in spectral space, with the operators just defined.\n\n@testset \"Check operators\" begin\n vort_hat = rfft(vort)\n u_hat = Hu_hat .* vort_hat\n v_hat = Hv_hat .* vort_hat\n ## check derivative dx in spectral space:\n @test irfft(Dx_hat .* vort_hat, N) ≈ dx_vort \n ## check derivative dy in spectral space:\n @test irfft(Dy_hat .* vort_hat, N) ≈ dy_vort \n ## check Laplacian in spectral space:\n @test Delta_hat ≈ Dx_hat.^2 .+ Dy_hat.^2\n @test irfft(Delta_hat .* vort_hat, N) ≈ dd_vort\n ## check recovering velocity field from vorticity\n @test Dx_hat .* v_hat - Dy_hat .* u_hat ≈ vort_hat \nend\nnothing\n\n# ## One-mode steady state\n\n# For forced-periodic flows, when the forcing function contains a single Fourier mode, there is a corresponding steady state vorticity function corresponding also to that single-mode in Fourier space, only with a different amplitude.\n\n# In order to construct such pairs of forcing mode / steady state, we set the viscosity of the flow, choose the mode to be forced and define the strength of that force:\n\nν = 1.0e-0 # viscosity\nκ = (x = 1, y = 2) # forced mode\nα = (re = 0.1, im = 0.05) # strength\n\nnothing\n\n# With these parameters, we find the curl `g_steady` of the forcing term and the vorticity `vort_steady` of the corresponding steady-state:\n\ng_steady = ν * (\n 2α.re * κ₀^4 * sum(abs2, κ)^2 * cos.(κ₀ * (κ.x * one.(y) * x' + κ.y * y * one.(x)'))\n - 2α.im * κ₀^4 * sum(abs2, κ)^2 * sin.(κ₀ * (κ.x * one.(y) * x' + κ.y * y * one.(x)'))\n)\n\nvort_steady = 2κ₀^2 * sum(abs2, κ) * (\n α.re * cos.(κ₀ * (κ.x * one.(y) * x' + κ.y * y * one.(x)'))\n - α.im * sin.(κ₀ * (κ.x * one.(y) * x' + κ.y * y * one.(x)'))\n)\nnothing\n\n# Here are some visualizations of the curl of the forcing term and of the vorticity\n\nheatmap(x, y, g_steady, xlabel=\"x\", ylabel=\"y\", title=\"Curl of the forcing term\", titlefont=12)\n\nheatmap(x, y, vort_steady, xlabel=\"x\", ylabel=\"y\", title=\"Steady state vorticity\", titlefont=12)\n\nnothing\n\n# The discrete Fourier transform of this vector fields are given as\n\ng_steady_hat = rfft(g_steady)\n\nvort_steady_hat = rfft(vort_steady)\n\nnothing\n\n# ## Testing the steady state\n\n# We are now ready to test the steadyness of this vorticity field:\n\n@testset \"Check single-mode stable steady state\" begin\n u_steady_hat = Hu_hat .* vort_steady_hat\n v_steady_hat = Hv_hat .* vort_steady_hat\n\n u_steady = irfft(u_steady_hat, N)\n v_steady = irfft(v_steady_hat, N)\n\n vort_steady_back = irfft(vort_steady_hat, N)\n\n wu_steady_hat = rfft(vort_steady_back .* u_steady)\n wv_steady_hat = rfft(vort_steady_back .* v_steady)\n\n rhs_steady = g_steady_hat .+ Delta_hat .* vort_steady_hat .- Dx_hat .* wu_steady_hat .- Dy_hat .* wv_steady_hat\n\n vort_steady_sol_hat = - g_steady_hat ./ Delta_hat\n vort_steady_sol_hat[1, 1] = 0.0im\n ## Vanishing bilinear term on one-mode steady state\n @test maximum(abs.(Dx_hat .* wu_steady_hat .+ Dy_hat .* wv_steady_hat)) ≤ √eps()\n ## Vanishing RHS on steady state\n @test maximum(abs.(rhs_steady)) ≤ √eps()\n ## Vanishing linear Stokes on steady state\n @test maximum(abs.(g_steady_hat .+ Delta_hat .* vort_steady_hat)) ≤ √eps()\n\n ## Steady state equation\n @test g_steady_hat ≈ - Delta_hat .* vort_steady_hat ≈ - Delta_hat .* vort_steady_hat .- Dx_hat .* wu_steady_hat .- Dy_hat .* wv_steady_hat\n\n ## Steady state solution\n @test vort_steady_sol_hat ≈ vort_steady_hat\nend\nnothing\n\n# All seems good.\n", "meta": {"hexsha": "36166bea959d85a2e62166b205ff4cab8cc50e46", "size": 7377, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/literate/tests_basic.jl", "max_stars_repo_name": "rmsrosa/2dnseperjl", "max_stars_repo_head_hexsha": "6ccb22a27b13ac5cf6c5b7016f8b7b206b7b2d34", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-30T20:26:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T20:26:42.000Z", "max_issues_repo_path": "src/literate/tests_basic.jl", "max_issues_repo_name": "rmsrosa/2dnsepervortjl", "max_issues_repo_head_hexsha": "6ccb22a27b13ac5cf6c5b7016f8b7b206b7b2d34", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/literate/tests_basic.jl", "max_forks_repo_name": "rmsrosa/2dnsepervortjl", "max_forks_repo_head_hexsha": "6ccb22a27b13ac5cf6c5b7016f8b7b206b7b2d34", "max_forks_repo_licenses": ["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.1527777778, "max_line_length": 524, "alphanum_fraction": 0.6644977633, "num_tokens": 2516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.8757870029950159, "lm_q1q2_score": 0.8103043748140799}} {"text": "using Bilevel\nusing ForwardDiff\nusing Bilevel: least_squares\nusing LinearAlgebra\n\nn = 3\nA = rand(n,n)\n\nd = svd(A)\nd.S[n] = d.S[n-1]\nA = d.U*Diagonal(d.S)*d.V'\n\nb = rand(n)\nz0 = vcat(A[:],b)\n\nfunction f(a)\n A = reshape(a[1:n^2],n,n) .* 2.\n b = a[n^2+1:end]\n x = least_squares(A,b)\n \n x\nend\n\nsol = f(z0)\n\n# autodiff\nJ_auto = ForwardDiff.jacobian(f,z0)\n\n# numerical\nϵ = sqrt(eps(1.))\nJ_num = zeros(size(J_auto))\nfor i = 1:length(z0)\n δ = zeros(length(z0))\n δ[i] = ϵ\n J_num[:,i] = (f(z0 + δ) .- sol)/ϵ\nend\n\ndisplay(sol)\nprintln(\"\")\nprintln(\"Auto\")\ndisplay(J_auto)\nprintln(\"\")\ndisplay(maximum(abs.(J_auto)))\nprintln(\"\")\nprintln(\"\")\nprintln(\"Finite diff\")\ndisplay(J_num)\nprintln(\"\")\ndisplay(maximum(abs.(J_num)))\nprintln(\"\")\nprintln(\"\")\n\nerr = maximum(abs.(J_auto .- J_num))\ndisplay(err)\nprintln(\"\")", "meta": {"hexsha": "30762a47ac241869f7b7a21231068fc1a169fa7c", "size": 817, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_least_squares.jl", "max_stars_repo_name": "blandry/Bilevel.jl", "max_stars_repo_head_hexsha": "108278969ae12a69186516144fd21f4734e3b8b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-03-14T01:59:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T19:15:50.000Z", "max_issues_repo_path": "test/test_least_squares.jl", "max_issues_repo_name": "blandry/Bilevel.jl", "max_issues_repo_head_hexsha": "108278969ae12a69186516144fd21f4734e3b8b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-06-07T15:59:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-03T16:17:26.000Z", "max_forks_repo_path": "test/test_least_squares.jl", "max_forks_repo_name": "blandry/Bilevel.jl", "max_forks_repo_head_hexsha": "108278969ae12a69186516144fd21f4734e3b8b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-02-27T10:41:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-18T07:00:49.000Z", "avg_line_length": 14.8545454545, "max_line_length": 37, "alphanum_fraction": 0.6107711138, "num_tokens": 286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299529686201, "lm_q2_score": 0.8757869851639066, "lm_q1q2_score": 0.8103043510937309}} {"text": "# ------ Smoothing functions often used to permit continuous differentiability -----\n\n\n\"\"\"\n abs_smooth(x, delta_x)\n\nSmooth out the absolute value function with a quadratic interval.\ndelta_x is the half width of the smoothing interval. \nTypically usage is with gradient-based optimization.\n\"\"\"\nfunction abs_smooth(x, delta_x)\n\n if x < delta_x && x > -delta_x\n return x^2/(2*delta_x) + delta_x/2\n else\n return abs(x)\n end\n \nend\n\n# TODO AN: add smooth max/min with cubic splines", "meta": {"hexsha": "87d0d0860247af3e2ea7c90553045730e8ed502b", "size": 505, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/smooth.jl", "max_stars_repo_name": "petebachant/FLOWMath.jl", "max_stars_repo_head_hexsha": "d538307bdb91e4e3e760c67b90f4a50a1499f7c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/smooth.jl", "max_issues_repo_name": "petebachant/FLOWMath.jl", "max_issues_repo_head_hexsha": "d538307bdb91e4e3e760c67b90f4a50a1499f7c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/smooth.jl", "max_forks_repo_name": "petebachant/FLOWMath.jl", "max_forks_repo_head_hexsha": "d538307bdb91e4e3e760c67b90f4a50a1499f7c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0476190476, "max_line_length": 84, "alphanum_fraction": 0.6891089109, "num_tokens": 119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9489172673767973, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.8102925543452282}} {"text": "#=\nThe following iterative sequence is defined for the set of positive integers:\n\nn → n/2 (n is even)\nn → 3n + 1 (n is odd)\n\nUsing the rule above and starting with 13, we generate the following sequence:\n\n13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1\nIt can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.\n\nWhich starting number, under one million, produces the longest chain?\n\nNOTE: Once the chain starts the terms are allowed to go above one million.\n=#\n\nfunction find_collatz(x::Int64)\n count = 0\n while x > 1\n x = iseven(x) ? div(x,2) : 3x+1\n count +=1\n end\n count\nend\n\nfunction calc()\n startnumber = 1\n longest = 1\n for i in 1:1_000_000\n c = find_collatz(i)\n if c > longest\n longest = c\n startnumber = i\n end\n end\n startnumber\nend\n@time println(calc())\n", "meta": {"hexsha": "04f8d268d422e3b035e69ae30ebc013690ca99e3", "size": 931, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p14.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/p14.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/p14.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 23.8717948718, "max_line_length": 196, "alphanum_fraction": 0.6799140709, "num_tokens": 287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9489172572644806, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.8102925527657969}} {"text": "function bisect(f, a, b, tol)\n println(\"a = \", a, \" b = \", b, \" tol = \", tol)\n c = 0.0\n\n while (b - a) / 2 > tol\n c = (b + a) / 2\n if f(c) == 0\n return c\n end\n\n if f(a) * f(c) < 0\n b = c\n else\n a = c\n end\n end\n\n c = (b + a) / 2\n return c\nend\n", "meta": {"hexsha": "c82978ba86395511ecf9bb310f190abe5c78f4b2", "size": 335, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/Numerical Analysis/chapter_1/bisect.jl", "max_stars_repo_name": "romix5417/CommonScript", "max_stars_repo_head_hexsha": "df8045e5b57625108e48d340f447ec4353fb8eef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "julia/Numerical Analysis/chapter_1/bisect.jl", "max_issues_repo_name": "romix5417/CommonScript", "max_issues_repo_head_hexsha": "df8045e5b57625108e48d340f447ec4353fb8eef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/Numerical Analysis/chapter_1/bisect.jl", "max_forks_repo_name": "romix5417/CommonScript", "max_forks_repo_head_hexsha": "df8045e5b57625108e48d340f447ec4353fb8eef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.9523809524, "max_line_length": 50, "alphanum_fraction": 0.3134328358, "num_tokens": 130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9532750453562491, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.810256314649303}} {"text": "@doc raw\"\"\"\n SquaredExponentialKernel([α=1])\n\nThe squared exponential kernel, or alternatively the Gaussian kernel, is identical to the \nexponential kernel except that the Euclidean distance is squared:\n\n```math\n\\kappa(\\mathbf{x},\\mathbf{y}) = \\exp\\left(-\\alpha ||\\mathbf{x} - \\mathbf{y}||^2\\right) \n\\qquad \\alpha > 0\n```\n\nwhere ``\\alpha`` is a scaling parameter of the squared Euclidean distance.\nJust like the exponential kernel, the squared exponential kernel is an\nisotropic Mercer kernel. The squared exponential kernel is more commonly known\nas the radial basis kernel within machine learning communities.\n\"\"\"\nstruct SquaredExponentialKernel{T<:AbstractFloat} <: MercerKernel{T}\n alpha::HyperParameter{T}\n SquaredExponentialKernel{T}(α::Real) where {T<:AbstractFloat} = new{T}(\n HyperParameter(convert(T,α), interval(OpenBound(zero(T)), nothing))\n )\nend\nSquaredExponentialKernel(α::T=1.0) where {T<:Real} = SquaredExponentialKernel{floattype(T)}(α)\nGaussianKernel = SquaredExponentialKernel\nRadialBasisKernel = SquaredExponentialKernel\n\n@inline squaredexponentialkernel(z::T, α::T) where {T<:AbstractFloat} = exp(-α*z)\n\n@inline basefunction(::SquaredExponentialKernel) = SquaredEuclidean()\n@inline function kappa(κ::SquaredExponentialKernel{T}, z::T) where {T}\n squaredexponentialkernel(z, getvalue(κ.alpha))\nend", "meta": {"hexsha": "86859687b3994855eaa9aa2994a181a2612ac99e", "size": 1340, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernelfunctions/mercer/squaredexponential.jl", "max_stars_repo_name": "holtri/MLKernels.jl", "max_stars_repo_head_hexsha": "d7b84b1bd7b9d9ca4cb7c413d0e34b04c09a331c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernelfunctions/mercer/squaredexponential.jl", "max_issues_repo_name": "holtri/MLKernels.jl", "max_issues_repo_head_hexsha": "d7b84b1bd7b9d9ca4cb7c413d0e34b04c09a331c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernelfunctions/mercer/squaredexponential.jl", "max_forks_repo_name": "holtri/MLKernels.jl", "max_forks_repo_head_hexsha": "d7b84b1bd7b9d9ca4cb7c413d0e34b04c09a331c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.875, "max_line_length": 94, "alphanum_fraction": 0.7574626866, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750427013548, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.8102563105813074}} {"text": "using FastGaussQuadrature\n\nabstract type AbstractQuadrature <: JalerkinType end;\n\n#--- Quadrature\n\nstruct Quadrature{N} <: AbstractQuadrature\n \"\"\"\n Quadrature rule with N nodes and weights of type T\n \"\"\"\n nodes :: SVector{N, fp_precision()}\n weights :: SVector{N, fp_precision()}\nend\n\n@inline function get_nodes(q::Quadrature)\n q.nodes\nend\n\n@inline function get_weights(q::Quadrature)\n q.weights\nend\n\n@inline function quad(q::AbstractQuadrature, values::AbstractArray)\n \"\"\"\n Compute integral of a function using a concrete quadrature rule,\n where 'values' are the values of the function on q.nodes\n \"\"\"\n get_weights(q) ⋅ values\nend\n\n@inline function quad(q::AbstractQuadrature, f)\n \"\"\"\n Compute integral of a function using a concrete quadrature formula\n \"\"\"\n quad(q, f.(get_nodes(q)))\nend\n\n#--- Constructors for concrete quadrature rules\n\n\"\"\"Gaussian quadrature rule on [-1,1] with n points\"\"\"\nfunction GaussianQuadrature(n)\n nodes, weights = gausslegendre(n)\n Quadrature{n}(nodes, weights)\nend\n\n\"\"\"\nTrapezoid quadrature rule on interval [-1, 1]\n\"\"\"\nfunction TrapezoidQuadrature()\n nodes = [-1, 1]\n weights = [1, 1]\n Quadrature{2}(nodes, weights)\nend\n", "meta": {"hexsha": "4454388002a0feedb526cca82028bd209378c318", "size": 1215, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Quadrature.jl", "max_stars_repo_name": "rrgalvan/Jalerkin", "max_stars_repo_head_hexsha": "c5cdaf9dc658f17dc148996eaa9cd3930fb9217a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-10T11:03:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T11:03:33.000Z", "max_issues_repo_path": "src/Quadrature.jl", "max_issues_repo_name": "rrgalvan/Jalerkin", "max_issues_repo_head_hexsha": "c5cdaf9dc658f17dc148996eaa9cd3930fb9217a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Quadrature.jl", "max_forks_repo_name": "rrgalvan/Jalerkin", "max_forks_repo_head_hexsha": "c5cdaf9dc658f17dc148996eaa9cd3930fb9217a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5, "max_line_length": 70, "alphanum_fraction": 0.6971193416, "num_tokens": 323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551535992067, "lm_q2_score": 0.8397339736884711, "lm_q1q2_score": 0.810221652165662}} {"text": "function DX(delta, Nx, Ny)\n # This function creates a finite difference operator which represents a\n # first order x-derivitive.\n # INPUT\n # delta: resolution of the operator - scalar / a.u.\n # Nx: Number of elements in x-direction - integer / #\n # Ny: Number of elements in y-direction - integer / #\n # OUTPUT\n # operator: (Nx*Ny X Nx*Ny)-Dim. FD-Dx operator - array / a.u.\n N = Nx*Ny\n next_vec = fill(1.0/(2.0*delta), N-1)\n if Ny > 1\n for ii in Nx:Nx:N-1 next_vec[ii] = 0.0 end\n end\n next_sparse_mat = sparse(2:N, 1:N-1, next_vec, N, N)\n operator = next_sparse_mat' - next_sparse_mat\n return operator\nend\n\nfunction DXX(delta, Nx, Ny)\n # This function creates a finite difference operator which represents a\n # second order x-derivitive.\n # INPUT\n # delta: resolution of the operator - scalar / a.u.\n # Nx: Number of elements in x-direction - integer / #\n # Ny: Number of elements in y-direction - integer / #\n # OUTPUT\n # operator: (Nx*Ny X Nx*Ny)-Dim. FD-Dxx operator - array / a.u.\n N = Nx*Ny\n main_vec = fill(-2.0 /delta^2, N)\n next_vec = fill(1.0/delta^2, N-1)\n if Ny > 1\n for ii in Nx:Nx:(N-1) next_vec[ii] = 0.0 end\n end\n main_sparse_mat = sparse(1:N, 1:N, main_vec, N, N)\n next_sparse_mat = sparse(2:N, 1:(N-1), next_vec, N, N)\n operator = next_sparse_mat' + next_sparse_mat + main_sparse_mat\n return operator\nend\n\nfunction DY(delta, Nx, Ny)\n # This function creates a finite difference operator which represents a\n # first order y-derivitive.\n # INPUT\n # delta: resolution of the operator - scalar / a.u.\n # Nx: Number of elements in x-direction - integer / #\n # Ny: Number of elements in y-direction - integer / #\n # OUTPUT\n # operator: (Nx*Ny X Nx*Ny)-Dim. FD-Dy operator - array / a.u.\n N = Nx*Ny\n next_vec = fill(1.0/(2*delta), (N-Ny))\n next_sparse_mat = sparse((1+Ny):N, 1:(N-Ny), next_vec, N, N)\n operator = next_sparse_mat' - next_sparse_mat\n return operator\nend\n\nfunction DYY(delta, Nx, Ny)\n # This function creates a finite difference operator which represents a\n # second order y-derivitive.\n # INPUT\n # delta: resolution of the operator - scalar / a.u.\n # Nx: Number of elements in x-direction - integer / #\n # Ny: Number of elements in y-direction - integer / #\n # OUTPUT\n # operator: (Nx*Ny X Nx*Ny)-Dim. FD-Dyy operator - array / a.u.\n N = Nx*Ny\n main_vec = fill(-2.0/delta^2, N)\n next_vec = fill(1.0/delta^2, (N-Ny))\n main_sparse_mat = sparse(1:N, 1:N, main_vec, N, N)\n next_sparse_mat = sparse((1+Ny):N, 1:(N-Ny), next_vec, N, N)\n operator = next_sparse_mat + next_sparse_mat' + main_sparse_mat\n return operator\nend\n", "meta": {"hexsha": "d09149d49be5646e65575fcedc220ab7ce240550", "size": 2740, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Operators.jl", "max_stars_repo_name": "Phomerics/PhomericsTest.jl", "max_stars_repo_head_hexsha": "7ea3a0b8640ed94273b2c922c1237f1629ca9ff0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Operators.jl", "max_issues_repo_name": "Phomerics/PhomericsTest.jl", "max_issues_repo_head_hexsha": "7ea3a0b8640ed94273b2c922c1237f1629ca9ff0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Operators.jl", "max_forks_repo_name": "Phomerics/PhomericsTest.jl", "max_forks_repo_head_hexsha": "7ea3a0b8640ed94273b2c922c1237f1629ca9ff0", "max_forks_repo_licenses": ["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.027027027, "max_line_length": 75, "alphanum_fraction": 0.6354014599, "num_tokens": 849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9748211597623861, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.810215835957598}} {"text": "using ComplexSystems\nusing Plots\n\nthe_walkers = walker_set(5000,-5,5)\nunshift!(the_walkers,walker(0.,0.,0))\n\nthe_walkers = dla(the_walkers,0.1,-5,5)\n\n## Plotting\nthe_x = [w.x for w in the_walkers]\nthe_y = [w.y for w in the_walkers]\np = scatter(the_x,the_y,markersize=3.,\n leg=false,ticks=nothing,\n markerstrokewidth=0.,border=false)\ntitle!(\"Diffusion Limit Aggregation\")\npng(p,\"/figs/dla\")\n\n\n## Minkowski dimension\nmin_x=-5.\nmax_x=5.\nmin_y=-5.\nmax_y=5.\n\n\nwalkers_p = map(x -> Point(x.x,x.y),the_walkers);\nΔs = []\nDimension = []\nfor Δ ∈ 0.01:0.05:0.96\n the_grid = make_square_grid(min_x,max_x,min_y,max_y,Δ,true);\n for punto ∈ walkers_p\n map(x -> inside_box(punto,x),the_grid);\n end\n non_empty_ones = sum([!x.empty for x ∈ the_grid]);\n println(non_empty_ones)\n dimension = log(non_empty_ones)/log(1/Δ)\n push!(Δs,Δ)\n push!(Dimension,dimension)\nend\n\nmini = round(Dimension[1];digits=3)\np = scatter(Δs,Dimension,legend=false)\ntitle!(\"Dimension vs box size\")\nyaxis!(\"Dimension\",:log10)\nxaxis!(\"Length of square side\",:log10)\n\npng(p,\"/figs/dimension\")\n", "meta": {"hexsha": "8b5412ade9b2dd89d0c4900682d41823fa01c4a8", "size": 1099, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/dla.jl", "max_stars_repo_name": "eduardofv/ComplexSystems.jl", "max_stars_repo_head_hexsha": "9d18df59c9b0862a03cf6644ace691fd8f43d94b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-15T03:39:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-18T22:34:59.000Z", "max_issues_repo_path": "examples/dla.jl", "max_issues_repo_name": "eduardofv/modelo_covid19_cdmx", "max_issues_repo_head_hexsha": "9d18df59c9b0862a03cf6644ace691fd8f43d94b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/dla.jl", "max_forks_repo_name": "eduardofv/modelo_covid19_cdmx", "max_forks_repo_head_hexsha": "9d18df59c9b0862a03cf6644ace691fd8f43d94b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8958333333, "max_line_length": 64, "alphanum_fraction": 0.67788899, "num_tokens": 364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951661947455, "lm_q2_score": 0.8670357580842941, "lm_q1q2_score": 0.8101540212719611}} {"text": "module RandomLinearModels\n\nusing LinearAlgebra\n\nfunction isstabled(A)\n all(x->abs(x)<=1, eigvals(A))\nend\n\nfunction isstablec(A)\n all(x->real(x)<=0, eigvals(A))\nend\n\nfunction controllability(A,B)\n n,m = size(B)\n R = zeros(n,n*m)\n Ak = zero(A) .+ I(n)\n for k = 1:n\n Rk = view(R, :, (k-1)*m .+ (1:m))\n Rk .= Ak*B\n Ak = Ak * A\n end\n return R\nend\n\niscontrollable(A,B) = rank(controllability(A,B)) == size(A,1)\n\nfunction genA(v, n, m)\n # Generate a random orthogonal matrix\n X = randn(n,n)\n Q = qr(X).Q\n A = Q*Diagonal(v)*Q'\nend\n\ngenB(n,m) = randn(n,m)\n\nfunction gendiscrete(n, m, tol::Real=1e-4)\n v = randn(n) \n v = v ./ (norm(v,Inf) + tol) # make it (marginally) discrete stable\n A = genA(v, n, m)\n B = genB(n,m)\n A,B\nend\n\nfunction gencontinuous(n, m, tol::Real=1e-4)\n v = randn(n) \n v = v .- (maximum(v) + tol) # make it (marginally) continuous stable\n A = genA(v, n, m)\n B = genB(n,m)\n A,B\nend\n\nfunction gencontrollable(n, m, type::Symbol=:discrete; tol::Real=1e-4, maxiter=20)\n cnt = 0\n while true\n if type == :discrete\n A,B = gendiscrete(n, m, tol)\n elseif type == :continuous\n A,B = gencontinuous(n, m, tol)\n end\n iscontrollable(A,B) && (return A,B)\n if cnt > maxiter \n throw(ErrorException(\"exceeded max number of attempt to find a controllable system.\"))\n end\n cnt += 1\n end\nend\n\nend", "meta": {"hexsha": "d24c1bb64bb04550ba07a17d440cc55a475dfdf8", "size": 1472, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/random_linear.jl", "max_stars_repo_name": "bjack205/RobotZoo.jl", "max_stars_repo_head_hexsha": "5d40724cdbb988c7cd466873084c0287acd5c182", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/random_linear.jl", "max_issues_repo_name": "bjack205/RobotZoo.jl", "max_issues_repo_head_hexsha": "5d40724cdbb988c7cd466873084c0287acd5c182", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-07-10T13:30:26.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-10T22:07:45.000Z", "max_forks_repo_path": "src/random_linear.jl", "max_forks_repo_name": "bjack205/RobotZoo.jl", "max_forks_repo_head_hexsha": "5d40724cdbb988c7cd466873084c0287acd5c182", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.6470588235, "max_line_length": 98, "alphanum_fraction": 0.5557065217, "num_tokens": 499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951607140233, "lm_q2_score": 0.8670357615200475, "lm_q1q2_score": 0.8101540197303303}} {"text": "\"\"\"\nbound(estimator, δ, n::Int)\nGive the theoritical bound B such that for the estimator \n #TODO! correction math formula\n```math\n\\\\mathbb{P}( |X- \\\\mathbb{E}(X)|/\\\\sigma \\\\leq B) \\\\leq \\\\delta\n```\n\n\"\"\"\nbound(δ::Real, n, M::EmpiricalMean) = sqrt(1 / (n * δ))\nbound(δ::Real, n, M::MedianOfMean) = sqrt(32log(1 / δ) / n)\nbound(δ::Real, n, M::TrimmedMean) = 19sqrt(2log(8 / δ) / n) # Typo in the review by Lugosie. It seems that the ouragous 19 does th job. It is probably improvable.\nbound(δ::Real, n, M::Catoni) = sqrt(2log(2 / δ) / (n - 2log(2 / δ)))\nbound(δ::Real, n, M::Huber) = 8sqrt(2log(4 / δ) / n)\n\"\"\"\"\nsqrt(2log(1 / δ) / n) # Multiply by a factor (1 + o(1)) where \no(1) = (1+O(sqrt(log(1/δ)/n)))*(1+log(log(1/δ))/log(1/δ)) goes to zeros with (log(1/δ)/n, δ)→ (0, 0)\nsee https://www.youtube.com/watch?v=Kr0Kl_sXsJM Q&A\n\"\"\"\nbound(δ::Real, n, M::LeeValiant) = 8sqrt(2log(4 / δ) / n)\n", "meta": {"hexsha": "b36d1a167a45593c5814baeff67a686e1527b3ff", "size": 890, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/bounds.jl", "max_stars_repo_name": "dmetivie/RobustMean.jl", "max_stars_repo_head_hexsha": "20daef4b15cdc5c72b8213f11d3ac041d96f8472", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/bounds.jl", "max_issues_repo_name": "dmetivie/RobustMean.jl", "max_issues_repo_head_hexsha": "20daef4b15cdc5c72b8213f11d3ac041d96f8472", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-28T15:12:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T15:12:57.000Z", "max_forks_repo_path": "src/bounds.jl", "max_forks_repo_name": "dmetivie/RobustMeans.jl", "max_forks_repo_head_hexsha": "20daef4b15cdc5c72b8213f11d3ac041d96f8472", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.380952381, "max_line_length": 162, "alphanum_fraction": 0.6033707865, "num_tokens": 375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966686936262, "lm_q2_score": 0.8558511396138365, "lm_q1q2_score": 0.8101458376561013}} {"text": "\"\"\"\n rref(A::AbstractMatrix{T}) where {T<:Interval}\n\nComputes the reduced row echelon form of the interval matrix `A` using maximum\nmignitude as pivoting strategy.\n\n### Examples\n\n```jldoctest\njulia> A = [2..4 -1..1; -1..1 2..4]\n2×2 Matrix{Interval{Float64}}:\n [2, 4] [-1, 1]\n [-1, 1] [2, 4]\n\njulia> rref(A)\n2×2 Matrix{Interval{Float64}}:\n [2, 4] [-1, 1]\n [0, 0] [1.5, 4.5]\n```\n\"\"\"\nfunction rref(A::AbstractMatrix{T}) where {T<:Interval}\n A1 = copy(A)\n return rref!(A1)\nend\n\n\"\"\"\n rref!(A::AbstractMatrix{T}) where {T<:Interval}\n\nIn-place version of [`rref`](@ref).\n\"\"\"\nfunction rref!(A::AbstractMatrix{T}) where {T<:Interval}\n m, n = size(A)\n minmn = min(m,n)\n @inbounds for k = 1:minmn\n\n if k < m\n # find maximum index\n migmax, kp = _findmax_mig(view(A, k:m, k))\n iszero(migmax) && throw(ArgumentError(\"Could not find a pivot with non-zero mignitude in column $k.\"))\n kp += k - 1\n\n # Swap rows k and kp if needed\n k != kp && _swap!(A, k, kp)\n end\n\n # Scale first column\n _scale!(A, k)\n\n # Update the rest\n _eliminate!(A, k)\n end\n return A\nend\n\n\n@inline function _findmax_mig(v)\n\n @inbounds begin\n migmax = mig(first(v))\n kp = firstindex(v)\n\n for (i, vi) in enumerate(v)\n migi = mig(vi)\n if migi > migmax\n kp = i\n migmax = migi\n end\n end\n end\n return migmax, kp\nend\n\n\n@inline function _swap!(A, k, kp)\n @inbounds for i = 1:size(A, 2)\n tmp = A[k,i]\n A[k,i] = A[kp,i]\n A[kp,i] = tmp\n end\nend\n\n@inline function _scale!(A, k)\n @inbounds begin\n Akkinv = inv(A[k,k])\n for i = k+1:size(A, 1)\n A[i,k] *= Akkinv\n end\n end\nend\n\n@inline function _eliminate!(A, k)\n m, n = size(A)\n @inbounds begin\n for j = k+1:n\n for i = k+1:m\n A[i,j] -= A[i,k]*A[k,j]\n end\n end\n\n for i = k+1:m\n A[i, k] = zero(eltype(A))\n end\n end\nend\n", "meta": {"hexsha": "15bef848ef452aa17048484d3d9fe34add0a7b57", "size": 2103, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/rref.jl", "max_stars_repo_name": "jorgepz/IntervalLinearAlgebra.jl", "max_stars_repo_head_hexsha": "ec65e2c5ddefc73a3ff8b94fb172d9178014a89b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2021-08-13T07:22:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T03:06:32.000Z", "max_issues_repo_path": "src/rref.jl", "max_issues_repo_name": "jorgepz/IntervalLinearAlgebra.jl", "max_issues_repo_head_hexsha": "ec65e2c5ddefc73a3ff8b94fb172d9178014a89b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 63, "max_issues_repo_issues_event_min_datetime": "2021-08-10T07:44:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:45:10.000Z", "max_forks_repo_path": "src/rref.jl", "max_forks_repo_name": "jorgepz/IntervalLinearAlgebra.jl", "max_forks_repo_head_hexsha": "ec65e2c5ddefc73a3ff8b94fb172d9178014a89b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-08-24T10:12:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T20:14:44.000Z", "avg_line_length": 20.0285714286, "max_line_length": 114, "alphanum_fraction": 0.5002377556, "num_tokens": 702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533144915913, "lm_q2_score": 0.8688267813328977, "lm_q1q2_score": 0.8101404119729215}} {"text": "# binocdf is the cdf for the Binomial distribution and binoccdf is its complement. \n# Distributions.jl implements the cdf of its Binomial by calling out to Rmath which \n# is a Julia package that wraps the corresponding functions used in R. Since we do not want to\n# load the Distributions lib when starting Autotest we want a pure Julia implementation\n# of binocdf. We base this code on the pure Ruby code for incomplete beta function available here:\n# http://rubydoc.info/gems/rubystats/0.2.3/Rubystats/SpecialMath#incomplete_beta-instance_method\n# \n\n# Cumulative Distribution Function evaluated at x of the Binomial(n, p) distribution:\nfunction binocdf(x, n, p)\n x = ifloor(x)\n if x == n\n return 1.0\n else\n incompletebeta(1-p, n - x, x + 1)\n end\nend\n\n# Complementary cdf of Binomial distr func:\nbinoccdf(x, n, p) = 1.0 - binocdf(x, n, p)\n\n# incompletebeta(x, a, b) evaluates incomplete beta function, here a, b > 0 and 0 <= x <= 1.\nfunction incompletebeta(x, a, b)\n if x == 0\n return 0.0\n elseif x == 1\n return 1.0\n else\n beta_gam = exp( a * log(x) + b * log(1.0 - x) - log_beta(a, b) )\n if x < ((a+1) / (a+b+2))\n return (beta_gam * beta_fraction(x, a, b) / a)\n else\n return (1.0 - (beta_gam * beta_fraction(1.0 - x, b, a) / b))\n end\n end\nend\n\nconst LOG_GAMMA_X_MAX_VALUE = 2.55e292\n\nfunction log_beta(a, b)\n if (a <= 0.0) || (b <= 0.0) || (a + b) > LOG_GAMMA_X_MAX_VALUE\n return 0.0\n else\n return (lgamma(a) + lgamma(b) - lgamma(a + b))\n end\nend\n\nconst XMININ = 2.23e-303\nconst PRECISION = 8.88e-016\n\nfunction beta_fraction(x, a, b, MaxIterations = 200) \n c = 1.0\n sum_ab = a + b\n a_plus = a + 1.0\n a_minus = a - 1.0\n h = 1.0 - sum_ab * x / a_plus\n if abs(h) < XMININ\n h = XMININ\n end\n h = 1.0 / h\n frac = h\n m = 1\n delta = 0.0\n\n while (m <= MaxIterations) && (abs(delta - 1.0) > PRECISION) \n m2 = 2 * m\n # even index for d\n d = m * (b - m) * x / ( (a_minus + m2) * (a + m2))\n h = 1.0 + d * h\n if abs(h) < XMININ\n h = XMININ\n end\n h = 1.0 / h\n c = 1.0 + d / c\n if abs(c) < XMININ\n c = XMININ\n end\n frac *= (h * c)\n # odd index for d\n d = -(a + m) * (sum_ab + m) * x / ((a + m2) * (a_plus + m2))\n h = 1.0 + d * h\n if abs(h) < XMININ\n h = XMININ\n end\n h = 1.0 / h\n c = 1.0 + d / c\n if abs(c) < XMININ\n c = XMININ\n end\n delta = h * c\n frac *= delta\n m += 1\n end\n\n return frac\nend\n\n# Compare to Distributions.jl\nusing Distributions\n\n# call once to compile things\nbinocdf(1, 10, 0.3)\nbinocdf(1.0, 10.0, 0.3)\nbinocdf(2.0, 10, 0.3)\n\n# Sample lower values with higher prob through a log transform.\n# Often more realistic since people tend to use lower ranges/values \n# frequently.\nfunction logsample(min, max)\n shift = 1.0 - min\n logmin = log(min + shift)\n logmax = log(max + shift)\n exp(logmin + (logmax - logmin) * rand()) - shift\nend\n\nNumReps = 1e6\nourtimesum = 0.0\ndtimesum = 0.0\n\nfor rep in 1:ifloor(NumReps)\n n = ifloor(logsample(2, 1e6))\n x = rand() * n # rand(0:n)\n p = rand()\n\n tic()\n ourres = binocdf(x, n, p)\n ourtimesum += toq()\n\n tic()\n dres = cdf(Binomial(n, p), x)\n dtimesum += toq()\n\n if !isapprox(ourres, dres)\n println(\"Failed for x = $x, n = $n, p = $p: our = $ourres, Distr.jl = $dres\")\n end\nend\n\nprintln(\"Our average binocdf performance: \", ourtimesum / NumReps)\nprintln(\"Distributions.jl average binocdf performance: \", dtimesum / NumReps)\nprintln(\"Performance diff: \", round(ourtimesum / dtimesum, 2), \"x\")\n", "meta": {"hexsha": "285c76c463b3769f4ba253bb135032c7232a55fd", "size": 3515, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "spikes/binocdf_pure_julia.jl", "max_stars_repo_name": "robertfeldt/FeldtLib.jl", "max_stars_repo_head_hexsha": "8b7fd87097a77a0a1f4a2f2b4d89938572ed7243", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "spikes/binocdf_pure_julia.jl", "max_issues_repo_name": "robertfeldt/FeldtLib.jl", "max_issues_repo_head_hexsha": "8b7fd87097a77a0a1f4a2f2b4d89938572ed7243", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "spikes/binocdf_pure_julia.jl", "max_forks_repo_name": "robertfeldt/FeldtLib.jl", "max_forks_repo_head_hexsha": "8b7fd87097a77a0a1f4a2f2b4d89938572ed7243", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-04-18T18:30:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T17:14:25.000Z", "avg_line_length": 24.9290780142, "max_line_length": 98, "alphanum_fraction": 0.6068278805, "num_tokens": 1335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.8688267711434708, "lm_q1q2_score": 0.8101403975792016}} {"text": "\n\n\"\"\"\nReturns the variance of data\n\"\"\"\nfunction Statistics.var(data1::VNamedD)\n\tσ=0.0\n\tμ=Statistics.mean(data1)\n\tn=0\n\tfor iss in 1:length(data1)\n\t\tfor ifield in names(data1[iss].d)[1]\n\t\t\tfor ir = 1:data1[iss].n, it = 1:length(data1[iss].grid)\n\t\t\t\tn += 1\n\t\t\t\tσ += (data1[iss].d[ifield][it, ir]-μ)^2 \n\t\t\tend\n\t\tend\n\tend\n\treturn σ*inv(n)\nend\n\nfunction Statistics.mean(data1::VNamedD)\n\tn=0\n\tμ=0.0\n\tfor iss in 1:length(data1)\n\t\tfor ifield in names(data1[iss].d)[1]\n\t\t\tfor ir = 1:data1[iss].n, it = 1:length(data1[iss].grid)\n\t\t\t\tn += 1\n\t\t\t\tμ += data1[iss].d[ifield][it, ir]\n\t\t\tend\n\t\tend\n\tend\n\treturn μ*inv(n)\nend\n\n\nfunction addnoise!(dataN::VNamedD, data::VNamedD, SNR)\n\n\tσx=Statistics.var(data)\n\n\tσxN=sqrt(σx^2*inv(10^(SNR/10.)))\n\t\n\t# factor to be multiplied to each scalar\n\tα=sqrt(σxN)\n\tfor iss in 1:length(data)\n\t\tfor ifield in names(data[iss].d)[1]\n\t\t\tfor ir = 1:data[iss].n, it = 1:length(data[iss].grid)\n\t\t\t\tdataN[iss].d[ifield][it, ir] = dataN[iss].d[ifield][it, ir] + α*Random.randn()\n\t\t\tend\n\t\tend\n\tend\nend\n\n\n\n", "meta": {"hexsha": "9343973fdd3c4599e35246a7d64afe62b1c84eea", "size": 1011, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/database/statistics.jl", "max_stars_repo_name": "ayushinav/GeoPhyInv.jl", "max_stars_repo_head_hexsha": "b0ce642161cb5300e2e7a5bd737b58fe37ddbfeb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-01-05T04:30:50.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-26T18:32:37.000Z", "max_issues_repo_path": "src/database/statistics.jl", "max_issues_repo_name": "ayushinav/GeoPhyInv.jl", "max_issues_repo_head_hexsha": "b0ce642161cb5300e2e7a5bd737b58fe37ddbfeb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-11-14T19:59:38.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-16T19:55:36.000Z", "max_forks_repo_path": "src/database/statistics.jl", "max_forks_repo_name": "ayushinav/GeoPhyInv.jl", "max_forks_repo_head_hexsha": "b0ce642161cb5300e2e7a5bd737b58fe37ddbfeb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-08-15T14:19:53.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-03T21:18:19.000Z", "avg_line_length": 18.3818181818, "max_line_length": 82, "alphanum_fraction": 0.6310583581, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850057480346, "lm_q2_score": 0.8652240808393984, "lm_q1q2_score": 0.8100963335020541}} {"text": "using Pkg\nPkg.activate(pwd())\n\n# # Optimal control\n# ## Computing trajectories with no control\n\nstruct PMSM{T<:Real}\n ρ::T\n ω::T\n A::Matrix{T}\n invA::Matrix{T}\n\n function PMSM(ρ, ω)\n A = -ρ*[1 0; 0 1] -ω*[0 -1; 1 0]\n return new{eltype(A)}(ρ, ω, A, inv(A))\n end\nend\n\n#+\n\nfunction expA(p::PMSM, t)\n ρ, ω = p.ρ, p.ω\n return exp(-ρ*t)*[cos(ω*t) sin(ω*t); -sin(ω*t) cos(ω*t)]\nend\n\n#+\n\nρ = 0.1\nω = 2\nx0 = [0;-0.5]\nq = [1;0]\n\nps = PMSM(ρ, ω)\n\n\n# ### Exercise:\n# \n# Verify that the matrix exponential is computed correctly and that it is different from\n# the elementwise exponential.\n# \n# **Hint**: The matrix exponential can also be computed directly by the `exp` function from \n# the `LinearAlgebra` package.\n# \n# ---\n# ### Solution:\n\n\n\n# ---\n# \n# ### Exercise:\n# \n# Write two function `trajectory_fin_diff` and `trajectory_exact` which compute the \n# trajectory. The first one should use the finite difference method to discretize the\n# time, while the second one should use the closed-form formula.\n# \n# Plot both trajectories on time interval ``[0,10]`` with time discretization step\n# ``\\Delta t=0.01``. Since ``x(t)`` is a two-dimensional vector, plot each component\n# on one axis.\n# \n# ---\n# ### Solution:\n\n\n\n# ---\n\nts = 0:0.0001:10\n\nxs1 = trajectory_fin_diff(ps, x0, ts, q)\nxs2 = trajectory_exact(ps, x0, ts, q)\n\nplot(xs1[1,:], xs1[2,:], label=\"Finite differences\");\nplot!(xs2[1,:], xs2[2,:], label=\"True value\")\n\n# ## Solving the optimal control problem\n# ### Exercise:\n# \n# Solve the optimal time for ``x_{\\rm tar}= (0.25, -0.5)`` with the maximum voltage\n# ``U_{\\rm max} = 0.1``.\n# \n# **Hint**: To solve the equation above for ``t``, use the bisection method.\n\nfunction bisection(f, a, b; tol=1e-6)\n fa = f(a)\n fb = f(b)\n fa == 0 && return a\n fb == 0 && return b\n fa*fb > 0 && error(\"Wrong initial values for bisection\")\n while b-a > tol\n c = (a+b)/2\n fc = f(c)\n fc == 0 && return c\n if fa*fc > 0\n a = c\n fa = fc\n else\n b = c\n fb = fc\n end\n end\n return (a+b)/2\nend\n\n# ---\n# ### Solution:\n\n\n\n# ---\n\nfunction trajectory_control(p::PMSM, x0, ts, q, U_max, p0)\n xs = zeros(length(x0), length(ts))\n\n for (i, t) in enumerate(ts)\n eAt = expA(p, t)\n emAt = expA(p, -t)\n xs[:, i] = eAt*(x0 + p.invA * (I - emAt)*q + U_max/ρ*(exp(ρ*t) - 1)*p0)\n end\n return xs\nend\n\n#+\n\np0 = ps.ρ/(U_max*(exp(ps.ρ*τ)-1))*(expA(ps, -τ)*x_t - x0 - ps.invA*(I-expA(ps, -τ))*q)\np0 /= norm(p0)\n\n#+\n\nts = range(0, τ; length=100)\ntraj = trajectory_control(ps, x0, ts, q, U_max, p0)\n\n#+\n\nplot(traj[1,:], traj[2,:], label=\"Optimal trajectory\");\nscatter!([x0[1]], [x0[2]], label=\"Starting point\");\nscatter!([x_t[1]], [x_t[2]], label=\"Target point\")\n\n#+\n\nts = 0:0.01:10\nplt = plot();\n\nfor α = 0:π/4:2*π\n trj = trajectory_control(ps, x0, ts, q, U_max, [sin(α); cos(α)])\n plot!(plt, trj[1,:], trj[2,:], label=\"\")\nend\n\ndisplay(plt)", "meta": {"hexsha": "32f4bdc716867d6902544f170f9deac5c42d0800", "size": 2981, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lecture_13/03-optimal_control.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/03-optimal_control.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/03-optimal_control.jl", "max_forks_repo_name": "JuliaTeachingCTU/Julia-for-Optimization-and-Learning-Scripts", "max_forks_repo_head_hexsha": "8e00299449736e4ccf47c247aa9d80f99a7e5b92", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0067114094, "max_line_length": 92, "alphanum_fraction": 0.5649111037, "num_tokens": 1069, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191297273498, "lm_q2_score": 0.8479677622198947, "lm_q1q2_score": 0.810079824640758}} {"text": "\"\"\"\n Berlage(; )\n\nCreate a Berlage wavelet.\n\n# Arguments\n- `dt::AbstractFloat=0.002`: sampling interval in secs.\n- `f0::Real=20.0`: central frequency in Hz.\n- `m::Real=2`: exponential parameter of Berlage wavelet.\n- `alpha::Real=180.0`: alpha parameter of Berlage wavelet in rad/secs.\n- `phi0::Real=0.0`: phase rotation in radians.\n\n# Example\n```julia\njulia> w = Berlage(); plot(w);\n```\n**Reference**\n* Aldridge, David F., 1990, The berlage wavelet: GEOPHYSICS, 55, 1508--1511.\n\"\"\"\nfunction Berlage(; dt::AbstractFloat=0.002, f0::Real=20.0, m::Real=2, alpha::Real=180.0,\n phi0::Real=0.0)\n\n nw = floor(Int, 2.0/(f0*dt))\n t = dt*collect(0:1:nw-1)\n w = [ (t[i] ^ m) * exp(-alpha*t[i]) * cos(2*pi*f0*t[i] + phi0) for i in eachindex(t) ]\n \n w = w/maximum(w)\n\nend\n", "meta": {"hexsha": "fd7c6ff7cbeaf1c0b2c7a1f9678e72597b0becfe", "size": 811, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Modelling/Wavelets/Berlage.jl", "max_stars_repo_name": "fercarozzi/SeisProcessing.jl", "max_stars_repo_head_hexsha": "cf91516e0c45b4aba60bbb331eee1a0cb7acc896", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Modelling/Wavelets/Berlage.jl", "max_issues_repo_name": "fercarozzi/SeisProcessing.jl", "max_issues_repo_head_hexsha": "cf91516e0c45b4aba60bbb331eee1a0cb7acc896", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2018-11-30T00:13:22.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T17:08:48.000Z", "max_forks_repo_path": "src/Modelling/Wavelets/Berlage.jl", "max_forks_repo_name": "fercarozzi/SeisProcessing.jl", "max_forks_repo_head_hexsha": "cf91516e0c45b4aba60bbb331eee1a0cb7acc896", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0333333333, "max_line_length": 90, "alphanum_fraction": 0.6202219482, "num_tokens": 290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191246389617, "lm_q2_score": 0.8479677602988602, "lm_q1q2_score": 0.810079818490768}} {"text": "using ForwardDiff, Roots, Plots, LinearAlgebra, Optim,Statistics\n\nfunction strong_backtracking(f, ∇, x, d; α=1, β=0.1, σ=0.4)\n y0, g0, y_prev, α_prev = f(x), ∇(x)⋅d, NaN, 0\n αlo, αhi = NaN, NaN\n # bracket phase\n while true\n y = f(x + α*d)\n if y > y0 + β*α*g0 || (!isnan(y_prev) && y ≥ y_prev)\n αlo, αhi = α_prev, α\n break\n end\n g = ∇(x + α*d)⋅d\n if abs(g) ≤ -σ*g0\n return α\n elseif g ≥ 0\n αlo, αhi = α, α_prev\n break\n end\n y_prev, α_prev, α = y, α, 2α\n end\n \n # zoom phase\n ylo = f(x + αlo*d)\n while true\n α = (αlo + αhi)/2\n y = f(x + α*d)\n if y > y0 + β*α*g0 || y ≥ ylo\n αhi = α\n else\n g = ∇(x + α*d)⋅d\n if abs(g) ≤ -σ*g0\n return α\n elseif g*(αhi - αlo) ≥ 0\n αhi = αlo\n end\n αlo = α\n end\n end\nend\n\n\nfunction bfgs(f,grad_f,x0;tol=1e-6,maxitr=10000)\n\n #init data\n ite = 0;x=x0;conv=false;err=0;\n xh = zeros(length(x0),maxitr+1);xh[:,1] = x0;\n\n #init bfgs parameters\n m = length(x)\n D = Matrix(1.0I,m,m)\n g = grad_f(x)\n\n #iteractions\n while ite < maxitr\n #line search\n d = -D*g\n\n #Inexact line search (strongWolf)\n alpha = strong_backtracking(f,grad_f,x,d;α=1, β=1e-4, σ=0.1)\n\n #update x\n s = alpha*d;\n x += s\n \n gl = grad_f(x)\n y = gl - g\n D = D - (s*y'*D + D*y*s')/(s'*y) + (1+(y'*D*y)/(s'*y))[1]*(s*s')/(s'*y)\n\n #update bfgs parameters\n g = gl\n\n #update ite and x history\n ite += 1\n xh[:,ite+1] = x\n\n #local minimum point\n err = norm(s);\n if err < tol ; conv=true; break; end\n end\n \n println(ite+1)\n #return x history. convergence and error\n return xh[:,1:ite+1], conv, err \nend\n\n#valores dos parametros\nka = 9.0 \nkb = 2.0\nLa = 10.0\nLb = 10.0\n\n#Caso 1\n#F1 = 2.0; F2 = 4.0;\n\n#Caso 2\n#F1 = 0.0 ;F2 = 4.0; #nao ta convergindo\n\n#Caso 3\nF1 = 0.0; F2 = 400.0;\n\n#function\nF(u) = 0.5e0 * ka * (sqrt(u[1] ^ 2 + (La - u[2]) ^ 2) - La) ^ 2 + 0.5e0 * kb * (sqrt(u[1] ^ 2 + (Lb + u[2]) ^ 2) - Lb) ^ 2 - F1 * u[1] - F2 * u[2];\ngrad_F(u) = ForwardDiff.gradient(F,u)\n\n#tolerancia\ntol = 1e-8\n\n#numero maximo de iteracoes\niterac_max = 10000\n\n#ponto inicial\n#u0 = [-0.01,0.0]\nu0 = [ 0.00,0.0]\n\n#u*\n@time u_est = bfgs(F,grad_F,u0;tol=tol,maxitr=iterac_max)\nu_est = u_est[1][:,end]\nprintln(\"u*: \",u_est)\nprintln(\"f(u*): \",F(u_est))\n\n#gradiente no ponto de minimo\nprintln(\"∇f(u*): \",grad_F(u_est))\n\n#verificar a hessiana no ponto de minimo\nhess_F(u) = ForwardDiff.hessian(F,u)\nprintln(\"H(u*): \",hess_F(u_est))\nprintln(\"λ: \",eigvals(hess_F(u_est)))", "meta": {"hexsha": "333071fa57b81f307f0f6c457705ee4bfc442809", "size": 2778, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "bfgs.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": "bfgs.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": "bfgs.jl", "max_forks_repo_name": "GilbertoLucas/Structural_Optimization", "max_forks_repo_head_hexsha": "e12ed13bbb97db275d79a0e5bfcad6438a643441", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.703125, "max_line_length": 147, "alphanum_fraction": 0.4892008639, "num_tokens": 1116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582612793112, "lm_q2_score": 0.8705972768020108, "lm_q1q2_score": 0.8100544284477021}} {"text": "export newton\n\n\"\"\"\nnewton(f,df,H,x)\n\nNewton method for solving min_x f(x)\n\n\"\"\"\nfunction newton(f::Function,df::Function,H::Function,x::Vector;maxIter=20,atol=1e-8,out::Int=0,storeInterm::Bool=false)\n\n his = zeros(maxIter,2)\n X = (storeInterm) ? zeros(length(x),maxIter) : []\n i = 1; flag = -1; LL = []\n while i<=maxIter\n fk = f(x)\n dfk = df(x)\n his[i,:] = [fk norm(dfk)]\n if storeInterm; X[:,i] = x; end;\n\n if(norm(dfk)0\n @printf \"iter=%04d\\tf=%1.2e\\t|df|=%1.2e\\n\" i his[i,1] his[i,2]\n end\n # update\n x += pk\n i+=1 \n end\n i = min(maxIter,i)\n\n if out>=0\n if flag==-1\n println(@sprintf(\"newton iterated maxIter (=%d) times but reached only atol of %1.2e instead of tol=%1.2e\",i,his[i,2],atol))\n elseif flag==-2\n println(@sprintf(\"newton stopped because the Hessian at iteration %d was not positive definite.\",i))\n elseif out>1\n println(@sprintf(\"newton achieved desired atol of %1.2e at iteration %d.\",atol,i))\n end\n end\n if storeInterm; X = X[:,1:i]; end\n return x,flag,his,X\nend", "meta": {"hexsha": "f7b8ccf28c2effc10e50a0c3271c30f809f4c8a1", "size": 1604, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/newton.jl", "max_stars_repo_name": "lruthotto/OptimTools.jl", "max_stars_repo_head_hexsha": "977feb8f2fd5e04d3f3b2a700b8abc992740cedb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/newton.jl", "max_issues_repo_name": "lruthotto/OptimTools.jl", "max_issues_repo_head_hexsha": "977feb8f2fd5e04d3f3b2a700b8abc992740cedb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/newton.jl", "max_forks_repo_name": "lruthotto/OptimTools.jl", "max_forks_repo_head_hexsha": "977feb8f2fd5e04d3f3b2a700b8abc992740cedb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7333333333, "max_line_length": 136, "alphanum_fraction": 0.4925187032, "num_tokens": 490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.8807970889295664, "lm_q1q2_score": 0.810018464317218}} {"text": "export all_partitions\n\"\"\"\n`all_partitions(A::Set)` creates a `Set` containing all possible\npartitions of the set `A`.\n\n`all_partitions(n::Int)` creates the `Set` of all partitions of\nthe set `{1,2,...,n}`.\n\nBoth of these take an optional second argument `k` to specify that\nonly partitions with exactly `k` parts should be returned.\n\"\"\"\nfunction all_partitions(A::Set{T}) where T\n if length(A) < 2\n P = Partition(A)\n return Set([P])\n end\n # Set aside one element of A and recurse\n x = first(A)\n B = deepcopy(A)\n delete!(B,x)\n\n PB = all_partitions(B)\n PA = Set{Partition{T}}() # place to hold partitions we create\n\n for P in PB\n # case 1: include x as a singleton\n P_parts = parts(P)\n push!(P_parts, Set([x]))\n Q = PartitionBuilder(P_parts)\n push!(PA,Q)\n\n # case 2: insert x into existing parts\n parts_list = collect(parts(P))\n np = length(parts_list)\n for k=1:np\n push!(parts_list[k],x) # insert x into k'th part\n Q = PartitionBuilder(Set(parts_list)) # build the partition\n push!(PA,Q)\n delete!(parts_list[k],x) # take it back out\n end\n\n end\n return PA\nend\n\nfunction all_partitions(n::Int)\n if n < 0\n error(\"argument must be a nonnegative integer\")\n end\n A = Set{Int}(collect(1:n))\n return all_partitions(A)\nend\n\n\nfunction all_partitions(A::Set{T},k::Int) where T\n if k<0\n error(\"Number of partitions (k) must be nonnegative\")\n end\n n = length(A)\n PA = Set{Partition{T}}()\n if k>n # no partitions possible\n return PA\n end\n if n==0 # special case when A is empty\n push!(PA, Partition(A))\n return PA\n end\n if k==0 # special case, no partitions\n return PA\n end\n\n x = first(A)\n B = deepcopy(A)\n delete!(B,x)\n\n # Step 1: partitions in which x is a singleton\n PB = all_partitions(B,k-1)\n for P in PB\n parts_set = parts(P)\n push!(parts_set, Set([x])) # {x} as a single part\n Q = PartitionBuilder(parts_set)\n push!(PA,Q)\n end\n\n # Step 2: partitions in which x is with others\n PB = all_partitions(B,k)\n for P in PB\n for j=1:k # each P has exactly k parts\n parts_list = collect(parts(P))\n push!(parts_list[j], x) # add x to part j\n Q = PartitionBuilder(Set(parts_list))\n push!(PA,Q)\n end\n end\n\n return PA\nend\n\n\nfunction all_partitions(n::Int,k::Int)\n if n < 0\n error(\"argument must be a nonnegative integer\")\n end\n A = Set{Int}(collect(1:n))\n return all_partitions(A,k)\nend\n", "meta": {"hexsha": "ed79ecb33602d1da68ee97359b6493c8261c9600", "size": 2657, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/all_partitions.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SimplePartitions.jl-ec83eff0-a5b5-5643-ae32-5cbf6eedec9d", "max_stars_repo_head_hexsha": "b5ddf673a24a7bc15fea06369fc752bbea2c0049", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-29T06:15:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-29T06:15:39.000Z", "max_issues_repo_path": "src/all_partitions.jl", "max_issues_repo_name": "UnofficialJuliaMirror/SimplePartitions.jl-ec83eff0-a5b5-5643-ae32-5cbf6eedec9d", "max_issues_repo_head_hexsha": "b5ddf673a24a7bc15fea06369fc752bbea2c0049", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-12-11T13:32:27.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-11T14:04:54.000Z", "max_forks_repo_path": "src/all_partitions.jl", "max_forks_repo_name": "UnofficialJuliaMirror/SimplePartitions.jl-ec83eff0-a5b5-5643-ae32-5cbf6eedec9d", "max_forks_repo_head_hexsha": "b5ddf673a24a7bc15fea06369fc752bbea2c0049", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-08-15T01:25:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-29T23:21:31.000Z", "avg_line_length": 24.8317757009, "max_line_length": 71, "alphanum_fraction": 0.5863756116, "num_tokens": 728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.919642526773001, "lm_q2_score": 0.8807970779778824, "lm_q1q2_score": 0.8100184503658557}} {"text": "# Newey-West covariance estimator\n# from https://github.com/mcreel/Econometrics/blob/508aee681ca42ff1f361fd48cd64de6565ece221/src/NP/NeweyWest.jl\n# under MIT licence https://github.com/mcreel/Econometrics/blob/508aee681ca42ff1f361fd48cd64de6565ece221/LICENSE\n# and adapted \n\n\"\"\"\n function newey_west(Z,nlags=0)\n\nReturns the Newey-West estimator of the asymptotic variance matrix\nINPUTS: Z, a nxk matrix with rows the vector zt'\n nlags, the number of lags\nOUTPUTS: omegahat, the Newey-West estimator of the covariance matrix\n\"\"\"\nfunction newey_west(Z,nlags=0)\n n,k = size(Z)\n # de-mean the variables\n Z = Z .- mean(Z,dims=1)\n omegahat = Z'*Z/n # sample variance\n # automatic lags?\n if nlags == 0\n nlags = max(1, round(Int, n^0.25))\n end \n # sample autocovariances\n for i = 1:nlags\n Zlag = @view(Z[1:n-i,:])\n ZZ = @view(Z[i+1:n,:])\n gamma = (ZZ'*Zlag)/n\n weight = 1.0 - (i/(nlags+1.0))\n omegahat += weight*(gamma + gamma')\n end \n return omegahat\nend", "meta": {"hexsha": "47b813f41ffdd2cd54b107b7b61ceee295a79c81", "size": 1039, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/newey_west.jl", "max_stars_repo_name": "ericphanson/LinearRegression.jl", "max_stars_repo_head_hexsha": "7edb58d60e9d77fe1707902600ac6eaa369c5906", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2021-09-02T11:08:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-12T19:24:52.000Z", "max_issues_repo_path": "src/newey_west.jl", "max_issues_repo_name": "ericphanson/LinearRegression.jl", "max_issues_repo_head_hexsha": "7edb58d60e9d77fe1707902600ac6eaa369c5906", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-09-02T21:00:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-11T10:14:54.000Z", "max_forks_repo_path": "src/newey_west.jl", "max_forks_repo_name": "ericphanson/LinearRegression.jl", "max_forks_repo_head_hexsha": "7edb58d60e9d77fe1707902600ac6eaa369c5906", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-26T22:14:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-26T22:14:10.000Z", "avg_line_length": 32.46875, "max_line_length": 112, "alphanum_fraction": 0.6583253128, "num_tokens": 343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240142763574, "lm_q2_score": 0.8633916152464016, "lm_q1q2_score": 0.8099684079875026}} {"text": "\"\"\"\ndₖ = solve_tCG(M, x, gradf_k, hessf_x_h, ν=1e-2, ϵ_residual = 1e-5)\n\nConjugate gradient method to solve the linear problem:\nfind d s.t. hessf_x_h(d) + gradf_k = 0\n\nNote that we are looking for a direction d in the tangent space of M at x, and the kernel of\n∇²f_M contains at least the orthogonal to this set. CG should naturally give a solution\nliving in the tangent space.\n\"\"\"\nfunction solve_tCG(M, x, gradfₖ, hessf_x_h; ν=1e-3, ϵ_residual = 1e-13, maxiter=1e5, safe_projection=false, printlev=0)\n norm_x(η) = norm(M, x, η)\n\n dₖ = zero_tangent_vector(M, x)\n rⱼ, rⱼ_prev = zero_tangent_vector(M, x), zero_tangent_vector(M, x)\n vⱼ, vⱼ_prev = zero_tangent_vector(M, x), zero_tangent_vector(M, x)\n\n d_type = :Unsolved\n j = 0\n\n (printlev>0) && @printf \"\\nj norm(rⱼ) norm(vⱼ) ⟨vⱼ, hessf(x)[vⱼ]⟩ ν * norm(vⱼ)^2\\n\"\n while true\n # current residual, conjugated direction\n rⱼ = hessf_x_h(dₖ) + gradfₖ\n if safe_projection\n rⱼ = project(M, x, rⱼ)\n end\n\n vⱼ = - rⱼ\n if j ≥ 1\n βⱼ = norm_x(rⱼ)^2 / norm_x(rⱼ_prev)^2\n vⱼ += βⱼ * vⱼ_prev\n end\n\n hessf_x_vⱼ = hessf_x_h(vⱼ)\n (printlev>0) && @printf \"%5i %.10e %.10e % .10e %.10e\\n\" j norm_x(rⱼ) norm_x(vⱼ) inner(M, x, vⱼ, hessf_x_vⱼ) ν * norm_x(vⱼ)^2\n if norm_x(rⱼ) < ϵ_residual || inner(M, x, vⱼ, hessf_x_vⱼ) < ν * norm_x(vⱼ)^2 || j > maxiter\n ## Satisfying point obtained\n if j == 0\n dₖ = -gradfₖ\n end\n\n if norm_x(rⱼ) < ϵ_residual\n d_type = :Solved\n # printstyled(\"Exiting: ||rⱼ|| < ϵ : $(norm_x(rⱼ)) < $ϵ_residual\\n\", color=:red)\n elseif j > maxiter\n d_type = :MaxIter\n # printstyled(\"Exiting: j > maxiter : $j > $maxiter\\n\", color=:red)\n else\n d_type = :QuasiNegCurvature\n a = inner(M, x, vⱼ, hessf_x_vⱼ)\n b = ν * norm_x(vⱼ)^2\n # printstyled(\"Exiting: ⟨vⱼ, hessf_x(vⱼ)⟩ < ν * ||vⱼ||² : $a < $b\\n\", color=:red)\n end\n\n break\n end\n\n tⱼ = - inner(M, x, rⱼ, vⱼ) / inner(M, x, vⱼ, hessf_x_vⱼ)\n dₖ += tⱼ * vⱼ\n\n rⱼ_prev = deepcopy(rⱼ)\n vⱼ_prev = deepcopy(vⱼ)\n\n j += 1\n end\n\n return dₖ, j, d_type\nend\n", "meta": {"hexsha": "86930bf3fb3c852efbb243a9eefcc3d9722d4de4", "size": 2369, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/manifold_updates/tangent_CG.jl", "max_stars_repo_name": "GillesBareilles/StructuredSolvers.jl", "max_stars_repo_head_hexsha": "b20240d9a1e41a4f2ad34bede0075cbae96a6233", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/manifold_updates/tangent_CG.jl", "max_issues_repo_name": "GillesBareilles/StructuredSolvers.jl", "max_issues_repo_head_hexsha": "b20240d9a1e41a4f2ad34bede0075cbae96a6233", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/manifold_updates/tangent_CG.jl", "max_forks_repo_name": "GillesBareilles/StructuredSolvers.jl", "max_forks_repo_head_hexsha": "b20240d9a1e41a4f2ad34bede0075cbae96a6233", "max_forks_repo_licenses": ["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.8428571429, "max_line_length": 143, "alphanum_fraction": 0.5352469396, "num_tokens": 932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240142763572, "lm_q2_score": 0.8633916011860785, "lm_q1q2_score": 0.8099683947971755}} {"text": "# Get the summary of some numbers in fibonacci sequence.\nv = [1,1]\ns = 0\nwhile (v[end] < 4000000)\n if v[end]%2==0 s+=v[end] end\n push!(v, v[end]+v[end-1])\nend\nprintln(s)\n# 4613732\n", "meta": {"hexsha": "8c4d22880710c64ca65270ff17e287e236410838", "size": 186, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "algo/su.2.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.2.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.2.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": 18.6, "max_line_length": 56, "alphanum_fraction": 0.6129032258, "num_tokens": 73, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526934, "lm_q2_score": 0.8774767938900121, "lm_q1q2_score": 0.8099454409552659}} {"text": "# ------------------------------------------------------------------------------------------\n# # Orbit Diagrams, Surfaces of Section\n# In this tutorial we will be using a `DynamicalSystem` instance to visualize aspects of the\n# system.\n#\n# Topics:\n# * `orbitdiagram`\n# * `poincaresos`\n# * `produce_orbitdiagram`\n# * Docstrings\n#\n# # Orbit Diagram\n# An \"orbit diagram\" is simply a plot that shows the long term behavior of a discrete system\n# when a parameter is varied.\n#\n# This is exactly what the function `orbitdiagram` does:\n# 1. Evolves the system for a transient amount of time.\n# 2. Evolves & saves the output of the system for a chosen variable.\n# 3. Changes/increments a parameter of the equations of motion.\n# 4. Repeat steps 1-3 for all given parameter values!\n#\n# This approach is also related with the (much more advanced) [sensitivity\n# analysis](http://docs.juliadiffeq.org/latest/analysis/sensitivity.html) from\n# DifferentialEquations.jl\n#\n# ---\n#\n# Let's make the super-ultra-famous orbit diagram of the logistic map:\n#\n# $$x_{n+1} = rx_n(1-x_n)$$\n# ------------------------------------------------------------------------------------------\n\nusing DynamicalSystems, PyPlot\n\nlogimap = Systems.logistic() # Systems module contains pre-defined well-known systems\n\n# ------------------------------------------------------------------------------------------\n# ---\n#\n# The call signature of `orbitdiagram` is:\n#\n# ```julia\n# orbitdiagram(discrete_system, i, p_index, pvalues; n, Ttr, ...)\n# ```\n# * `i` is the index of the variable we want to save.\n# * `p_index` is the index of the parameter we want to change.\n# * `pvalues` are the values of the parameter that will change.\n# * Keywords `Ttr` and `n` denote for how much transient time to evolve the system and how\n# many states to save.\n# \n# ------------------------------------------------------------------------------------------\n\ni = 1 # which variable to save (of course logistic map is 1D !)\nn = 50 # how many values to save\nTtr = 5000 # transient iterations\np_index = 1\npvalues = 2:0.001:4 # parameter values\noutput = orbitdiagram(logimap, i, p_index, pvalues; n = n, Ttr = Ttr)\ntypeof(output)\n\n# ------------------------------------------------------------------------------------------\n# * The output is a vector of vectors. Each inner vector has length `n` and contains the\n# values of the variable `i` at the given parameter value.\n#\n# Let's plot interactively!\n# ------------------------------------------------------------------------------------------\n\nfunction bf(pvalues, n, Ttr)\n logi = Systems.logistic()\n output = orbitdiagram(logi, 1, 1, pvalues; n = n, Ttr = Ttr)\n\n figure(figsize=(6,4))\n for (j, p) in enumerate(pvalues)\n plot(p .* ones(output[j]), output[j], linestyle = \"None\", # linestyle = None\n marker = \"o\", ms = 0.2, color = \"black\")\n end\n xlabel(\"\\$r\\$\"); ylabel(\"\\$x\\$\");\n xlim(pvalues[1], pvalues[end])\n # ylim(0, 1)\n return \nend\n\nbf(linspace(2.0, 4.0, 1000), 200, 2000)\n\nbf(linspace(3.5, 3.6, 1000), 200, 2000)\n\n# ------------------------------------------------------------------------------------------\n# We can use `BenchmarkTools` to see how much time it takes to generate this orbit diagram\n# ------------------------------------------------------------------------------------------\n\nusing BenchmarkTools\n@btime output = orbitdiagram($logimap, $i, $p_index, $pvalues; n = $n, Ttr = $Ttr);\nprintln(\"for total points: $(length(pvalues)*(Ttr+n)), out of which $(length(pvalues)*n) are saved\")\n\n# ------------------------------------------------------------------------------------------\n# ---\n#\n# * `orbitdiagram` works with *any* discrete system! Check out the [documentation\n# page](https://juliadynamics.github.io/DynamicalSystems.jl/latest/chaos/orbitdiagram/) for\n# more!\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# # Poincaré Surface of Section\n# This is a technique to reduce a continuous system into a discrete map with 1 fewer\n# dimension.\n# The wikipedia entry on [Poincaré map](https://en.wikipedia.org/wiki/Poincar%C3%A9_map) has\n# a lot of useful info, but the technique itself is very simple:\n#\n# 1. Define a hyperplane in the phase-space of the system.\n# 2. Evolve the continuous system for long times. Each time the trajectory crosses this\n# plane, record the state of the system.\n# 3. Only crossings with a specific `direction` (either positive or negative) are allowed.\n#\n# And that's it! The recorded crossings are the Poincaré Surface of Section!\n#\n# ## Defining a hyperplane\n# Let's say that our phase-space is $D$ dimensional. If the state of the system is\n# $\\mathbf{u} = (u_1, \\ldots, u_D)$ then the equation for a hyperplane is\n#\n# $$\n# a_1u_1 + \\dots + a_Du_D = \\mathbf{a}\\cdot\\mathbf{u}=b\n# $$\n# where $\\mathbf{a}, b$ are the parameters that define the hyperplane.\n#\n# ---\n#\n# Here is the call signature for a function that does this:\n#\n# ```julia\n# poincaresos(continuous_system, plane, tfinal = 100.0; direction = 1, ...)\n# ```\n# In code, `plane` can be either:\n#\n# * A `Tuple{Int, <: Number}`, like `(j, r)` : the hyperplane is defined as when the `j`\n# variable of the system crosses the value `r`.\n# * An `AbstractVector` of length `D+1`. The first `D` elements of the vector correspond to\n# $\\mathbf{a}$ while the last element is $b$. The hyperplane is defined with its formal\n# equation.\n#\n# ---\n#\n# As an example, let's see a section of the Lorenz system:\n# $$\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# $$\n# \n# ------------------------------------------------------------------------------------------\n\nlor = Systems.lorenz()\n\ntr = trajectory(lor, 100.0, dt = 0.01)\nfigure(figsize = (8,6))\nplot3D(columns(tr)...);\nxlabel(\"X\"); ylabel(\"Y\"); zlabel(\"Z\");\n\npsos = poincaresos(lor, (2, 0.0), 2000.0) # find where 2nd variable crosses 0.0\n\nfigure(figsize = (6,4))\nplot(psos[:, 1], psos[:, 3], lw=0.0, marker =\"o\", ms = 1.0, color = \"C1\");\nxlabel(\"X\"); ylabel(\"Z\");\n\n# ------------------------------------------------------------------------------------------\n# * We see that the surface of section is some kind of 1-dimensional object.\n# * This is expected, because as we will show in the tutorial \"Entropies & Dimensions\" the\n# Lorenz system (at least for the default parameters) lives in an almost 2-dimensional\n# attractor.\n#\n# * This means that when you take a cut through this object, the result should be\n# 1-dimensional!\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# **Next, let's visualize the Poincaré Surface of Section in 3D**\n# ------------------------------------------------------------------------------------------\n\n\"\"\"\n meshgrid(x, y) -> X, Y\nCreate a meshgrid, such as that used in PyPlot's countour plots.\n\"\"\"\nfunction meshgrid(vx, vy)\n m, n = length(vy), length(vx)\n vx = reshape(vx, 1, n)\n vy = reshape(vy, m, 1)\n (repmat(vx, m, 1), repmat(vy, 1, n))\nend\n\n# ------------------------------------------------------------------------------------------\n# We can get the attractor by calculating trajectories:\n# ------------------------------------------------------------------------------------------\n\ntr = trajectory(lor, 200.0, dt=0.01)\nx, y, z = columns(tr);\n\n# ------------------------------------------------------------------------------------------\n# Next, let's make sure we can color points on our 3D plot based on where they are relative\n# to a cut we'll make in the plot.\n#\n# To do this, we'll create a vector, `c`, that will store labels for the colors of all\n# points:\n# ------------------------------------------------------------------------------------------\n\nc = Vector{String}(length(y))\nfor i in 1:length(y) # cut points: red\n if -0.1 < y[i] < 0.1\n c[i] = \"C3\"\n elseif y[i] < 0 \n c[i] = \"C0\" # in front of cut: blue\n else\n c[i] = \"C2\" # behind cut: green\n end\nend\n\nfigure(figsize = (8,6))\n# First let's plot the attractor\nplot3D(x,y,z, color = \"black\", lw = 0.2, alpha = 0.25)\nscatter3D(x, y, z, color = c, s = 5.0)\n\n# And then plot the PSOS plane:\nx = [-20, 20]; z = [0, 40]; \nX, Z = meshgrid(x, z)\nY = zeros(X)\n\nplot_surface(X, Y, Z, alpha = 0.25, color = \"C1\");\nxlabel(\"X\"); ylabel(\"Y\"); zlabel(\"Z\");\n\n# ------------------------------------------------------------------------------------------\n# # Producing an orbit diagram\n#\n# 1. The `orbitdiagram` function does not make sense for continuous systems. In order for\n# `orbitdiagram` to have meaning one must have a map.\n#\n# 2. We can take advantage of the `poincaresos` function, and reduce a continuous system to\n# a map.\n# 3. Then, we can formally calculate an orbit diagram for a continuous system!\n#\n# In this example I will use the Shinriki oscillator, which displays a period-doubling route\n# to chaos like the logistic map!\n# ------------------------------------------------------------------------------------------\n\nshinriki_voltage(V) = 2.295e-5*(exp(3.0038*V) - exp(-3.0038*V))\nfunction shinriki_eom(u, p, t)\n R1 = p[1]\n\n du1 = (1/0.01)*(\n u[1]*(1/6.9 - 1/R1) - shinriki_voltage(u[1] - u[2]) - (u[1] - u[2])/14.5\n )\n\n du2 = (1/0.1)*(\n shinriki_voltage(u[1] - u[2]) + (u[1] - u[2])/14.5 - u[3]\n )\n\n du3 = (1/0.32)*(-u[3]*0.1 + u[2])\n return SVector{3}(du1, du2, du3)\nend\n\n# Be sure to give a mutable container for the parameter container!\nshi = ContinuousDynamicalSystem(shinriki_eom, [-2, 0, 0.2], [22.0])\n\n# ------------------------------------------------------------------------------------------\n# Now we can use `shi`, our dynamical system, to calculate trajectory steps and then plot\n# the result.\n# ------------------------------------------------------------------------------------------\n\nset_parameter!(shi, 1, 20.0) # parameter from 19 to 22\ntr = trajectory(shi, 2000.0)\nfigure(figsize = (8,6))\nplot3D(columns(tr[1000:end, :])..., color = \"C3\", alpha = 0.5, marker = \"o\", ms = 0.5);\n\n# ------------------------------------------------------------------------------------------\n# To get a feeling for the system, let's look at a couple `poicaresos`\n# ------------------------------------------------------------------------------------------\n\nfigure(figsize=(8,4))\nsubplot(1,2,1)\n# the function set_parameter! is useful here! (see docstring!)\nR1 = 19.5\nset_parameter!(shi, 1, R1)\n\n# here I use `direction = -1` (makes more sense for the specific system)\npsos = poincaresos(shi, (2, 0.0), 1000.0, Ttr = 100.0, direction = -1)\n\nplot(psos[:, 1], psos[:, 3], lw=0.0, marker =\"o\", ms = 2.0, color = \"C3\");\nxlabel(\"\\$V_1\\$\"); ylabel(\"\\$I_3\\$\")\ntitle(\"R1 = $R1\")\n\nR1 = 21.0\nset_parameter!(shi, 1, R1)\nsubplot(1,2,2)\npsos = poincaresos(shi, (2, 0.0), 1000.0, Ttr = 100.0, direction = -1)\nplot(psos[:, 1], psos[:, 3], lw=0.0, marker =\"o\", ms = 2.0, color = \"C3\");\nxlabel(\"\\$V_1\\$\"); \ntitle(\"R1 = $R1\");\n\n# ------------------------------------------------------------------------------------------\n# Hm, this is interesting!\n# 1. For some parameters the motion is clearly periodic (due to the distinct number of\n# points)\n# 2. But at other parameters the motion ***seems to be*** on a 2-dimensional manifold.\n#\n# **Don't be too quick to judge the second as chaotic though! In the next tutorial\n# \"Quantifying Chaos\" I will show you tools to quantify chaotic behavior!**\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# ---\n#\n# * We would like to see the behavior of the system while varying the parameter, like an\n# orbit diagram.\n#\n# * We can do this by performing successive surfaces of section and then recording the\n# values of a chosen variable!\n#\n# This procedure is bundled in the very convenient function `produce_orbitdiagram`:\n#\n# ```julia\n# produce_orbitdiagram(continuous_system, plane, i, p_index, pvalues; kwargs...)\n# ```\n#\n# The function produces successive `poincaresos` for the `plane`, and records the values of\n# the `i`-th variable at the section.\n#\n# Most other arguments are simply propagated to `poincaresos`.\n#\n# *Lets use this function for the Shinriki oscillator example:*\n#\n# First we can store our input arguments for `produce_orbitdiagram` in a few input vars.\n# ------------------------------------------------------------------------------------------\n\npvalues = linspace(19,22,201) # which parameter values to use\np_index = 1 # which parameter to change\n\ni = 1 # record 1st variable\nplane = (2, 0.0) # find PSOS of 2nd variable when crossing zero\ntf = 200.0 # argument passed to poincaresos\n\n# ------------------------------------------------------------------------------------------\n# Now we're ready to call `produce_orbitdiagram` and plot the result!\n#\n# (NOTE: This computation takes some seconds, since it makes 201 PSOS!)\n# ------------------------------------------------------------------------------------------\n\noutput = produce_orbitdiagram(shi, plane, i, p_index, pvalues; \n # all keywords are passed to poincaresos:\n tfinal = tf, Ttr = 200.0, direction = -1)\n\nfigure(figsize=(6,4))\nfor (j, p) in enumerate(pvalues)\n plot(p .* ones(output[j]), output[j], ls = \"None\",\n marker = \"o\", ms = 0.5, color = \"black\")\nend\nxlabel(\"\\$R_1\\$\"); ylabel(\"\\$V_1\\$\");\n\n# ------------------------------------------------------------------------------------------\n# ---\n#\n# ## Example with parameter-dependent plane\n#\n# Let's see one more case, using the Gissinger system:\n#\n# $$\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# $$\n# \n# ------------------------------------------------------------------------------------------\n\ngis = Systems.gissinger([2.32865, 2.02514, 1.98312]) # initial condition necessary to see structure\n\nset_parameter!(gis, 1, 0.112) # parameter from 0.1 to 0.15\ntr = trajectory(gis, 1000.0)\nfigure(figsize = (8,6))\nplot3D(columns(tr)...);\n\npvalues = linspace(0.1,0.15,201) # which parameter values to use\np_index = 1 # change 2nd parameter, which is μ\n\ni = 2 # record i variable\nj = 1 # find PSOS of j variable\noffset = -0.75 # offset is important here\n\ntf = 5000.0 \n\noutput = produce_orbitdiagram(gis, (j, offset), i, p_index, pvalues; \n # all keywords are passed to poincaresos:\n tfinal = tf, Ttr = 2000.0)\n\nfigure(figsize=(8,6))\nfor (j, p) in enumerate(pvalues)\n length(output[j]) == 0 && continue\n plot(p .* ones(output[j]), output[j], ls = \"None\",\n marker = \"o\", ms = 0.5, color = \"black\", alpha = 0.5)\nend\nylim(1,3)\nxlabel(\"\\$\\\\mu\\$\"); ylabel(\"\\$D\\$\");\n\n# ------------------------------------------------------------------------------------------\n# ---\n#\n# 1. The above is quite cool, but for this specific system, the \"optimal\" hyperplane to use\n# depends on the parameter `μ`.\n#\n# 2. In addition, it is not \"optimal\" to record a specific variable during the crossing, but\n# instead a function of the variables.\n#\n# 3. For this approach, it is better to get the entire `poincaresos`s for each parameter,\n# like I show in the following example:\n# ------------------------------------------------------------------------------------------\n\n# Define appropriate hyperplane for gissinger system\nconst ν = 0.1\nconst Γ = 0.9 # default parameters of the system\n\n# I want hyperperplane defined by these two points: \nNp(μ) = SVector{3}(sqrt(ν + Γ*sqrt(ν/μ)), -sqrt(μ + Γ*sqrt(μ/ν)), -sqrt(μ*ν))\nNm(μ) = SVector{3}(-sqrt(ν + Γ*sqrt(ν/μ)), sqrt(μ + Γ*sqrt(μ/ν)), -sqrt(μ*ν))\n\n# Create hyperplane using normal vector to vector connecting points:\ngis_plane(μ) = (d = (Np(μ) - Nm(μ)); [d[2], -d[1], 0, 0])\n\ngis_plane(0.112)\n\nμ = 0.12\nset_parameter!(gis, 1, μ)\nfigure(figsize = (8,6))\npsos = poincaresos(gis, gis_plane(μ), 2000.0, Ttr = 2000.0)\nplot3D(columns(psos)..., marker = \"o\", ls = \"None\", ms = 2.0);\n\npvalues = linspace(0.1,0.14,201) # which parameter values to use\n\nxs = Vector{Float64}[] # empty vector of vectors\n\nfor (i, μ) in enumerate(pvalues)\n set_parameter!(gis, 1, μ)\n N = Np(μ)\n psos = poincaresos(gis, gis_plane(μ), 4000.0, Ttr = 2000.0)\n push!(xs, [norm(N - k) for k in psos])\nend\n\n\nfigure(figsize=(8,6))\nfor (j, p) in enumerate(pvalues)\n length(xs[j]) == 0 && continue\n plot(p .* ones(xs[j]), xs[j], ls = \"None\",\n marker = \"o\", ms = 0.2, color = \"black\", alpha = 0.5)\nend\nxlabel(\"\\$\\\\mu\\$\"); ylabel(\"\\$x\\$\");\n\nfigure(figsize=(8,6))\nfor (j, p) in enumerate(pvalues)\n length(xs[j]) == 0 && continue\n plot(p .* ones(xs[j]), xs[j], ls = \"None\",\n marker = \"o\", ms = 0.2, color = \"black\", alpha = 0.5)\nend\nylim(2.7, 2.9)\nxlabel(\"\\$\\\\mu\\$\"); ylabel(\"\\$x\\$\");\n\n# ------------------------------------------------------------------------------------------\n# # Docstrings\n# ------------------------------------------------------------------------------------------\n\n?orbitdiagram\n\n?poincaresos\n\n?produce_orbitdiagram\n", "meta": {"hexsha": "e7a17f1981b7bef93e89a6f1ed1d669e1d8f0979", "size": 17324, "ext": "jl", "lang": "Julia", "max_stars_repo_path": ".nbexports/introductory-tutorials/broader-topics-and-ecosystem/introduction-to-dynamicalsystems.jl/2. Orbit diagrams, Surfaces of Section.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/2. Orbit diagrams, Surfaces of Section.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/2. Orbit diagrams, Surfaces of Section.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": 36.5485232068, "max_line_length": 100, "alphanum_fraction": 0.5197413992, "num_tokens": 4627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767746654974, "lm_q2_score": 0.9230391669503405, "lm_q1q2_score": 0.8099454311055124}} {"text": "function euclideanDistance(point1::Array, point2::Array)\n\n nVar = length(point1)\n acc = 0\n for i=1:nVar\n acc += (point1[i]-point2[i])^2\n end\n return sqrt(acc)\nend\n\nfunction pairwiseDistance(array1::Array, array2::Array, metric::Function)\n\n len = size(array1)[1]\n\n matrix = zeros(len, len)\n\n for i=1:len\n for j=i+1:len\n matrix[i,j] = euclideanDistance(array1[i,:], array2[j,:])\n matrix[j,i] = matrix[i,j]\n end\n end\n\n return matrix\nend\n\nfunction getKnearest(row::Array, k::Integer)\n\n Knearest = collect(1:k)\n len = length(row)\n\n for i=1:k\n for j=i+1:k\n if row[Knearest[i]] < row[Knearest[j]]\n Knearest[j], Knearest[i] = Knearest[i], Knearest[j]\n end\n end\n end\n\n for i=k+1:len\n if row[i] < row[Knearest[1]]\n Knearest[1] = i\n for j=1:k-1\n if row[Knearest[j]] < row[Knearest[j+1]] || break\n Knearest[j], Knearest[j+1] = Knearest[j+1], Knearest[j]\n end\n end\n end\n end\n\n return Knearest\nend\n\nfunction randomIndexSelection(len::Integer, n::Integer, rng::Random.AbstractRNG)\n\n if n>len\n n = len;\n end\n\n indexes = Array{UInt32}(undef, n)\n\n i=1\n while i<=n\n inside = false\n indexes[i] = (rand(rng, UInt32)%len) + 1;\n for j=1:i\n if i!=j\n inside = indexes[i] == indexes[j]\n inside && break\n end\n end\n if !inside\n i+=1\n end\n end\n return indexes\nend\n\n\nfunction randomIndexSelection2(len::Integer, n::Integer, rng::Random.AbstractRNG)\n\n if n>len\n n = len;\n end\n\n indexes = collect(UInt32,1:len)\n selected = Array{UInt32}(undef, n)\n\n i=1\n for i=1:n\n inside = false\n index = (rand(rng, UInt32)%len) + 1;\n len = len - 1\n selected[i] = indexes[index]\n indexes[index] = indexes[end]\n pop!(indexes)\n\n end\n return selected\nend\n\n\nfunction findprevIndexes(predicate::Function, A::Array, i::Integer)\n previous = Array{Integer}(undef, 0)\n\n while (aux = findprev(predicate, A, i)) != nothing\n push!(previous, aux)\n i -= 1\n end\n\n return previous\nend\n\n\nfunction findnextIndexes(predicate::Function, A::Array, i::Integer)\n next = Array{Integer}(undef, 0)\n\n while (aux = findnext(predicate, A, i)) != nothing\n push!(next, aux)\n i += 1\n end\n\n return next\nend\n", "meta": {"hexsha": "5f34d9f7f5ddf77f7129cfc5bdc28be3dc31c369", "size": 2527, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils/miscFunctions.jl", "max_stars_repo_name": "SergioGmezM/GeneticJulia", "max_stars_repo_head_hexsha": "b9d6113a0e9746688b05a3ef1c394bddcb82b1fd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils/miscFunctions.jl", "max_issues_repo_name": "SergioGmezM/GeneticJulia", "max_issues_repo_head_hexsha": "b9d6113a0e9746688b05a3ef1c394bddcb82b1fd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils/miscFunctions.jl", "max_forks_repo_name": "SergioGmezM/GeneticJulia", "max_forks_repo_head_hexsha": "b9d6113a0e9746688b05a3ef1c394bddcb82b1fd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.216, "max_line_length": 81, "alphanum_fraction": 0.5370003957, "num_tokens": 726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554476, "lm_q2_score": 0.8723473746782093, "lm_q1q2_score": 0.80989497979269}} {"text": "using DrWatson\n@quickactivate \"StatReth\"\n\n# %%\nusing StatsBase\nusing Distributions\nusing Plots\n\n# %% 3.20 - 3.23\npdf.(Binomial(2, 0.7), 0:2)\n\nrand(Binomial(2, 0.7), 1)\n\nrand(Binomial(2, 0.7), 10)\n\nN = 10_000\ndummy_w = rand(Binomial(2, 0.7), N)\ncounts(dummy_w) ./ N |> display # either\ncountmap(dummy_w) # or, depending on what you want\n\n# %% 3.24, 3.25\ndummy_w = rand(Binomial(9, 0.7), N)\nhistogram(dummy_w)\n\nw = rand(Binomial(9, 0.6), N)\n\n# %% 3.26\nsamples = let\n # %% 3.2 - 3.5\n n = 1000\n p_grid = range(0, 1, length = n)\n prob_p = ones(n)\n prob_data = @. pdf(Binomial(9, p_grid), 6)\n posterior = prob_data .* prob_p\n posterior ./= sum(posterior)\n weights = pweights(posterior)\n sample(p_grid, weights, 10_000)\nend\n\n# Version 1: Imagine this as having all the binomial distributions from the p of the\n# samples added up. The random numbers are drawn from the resulting distribution.\nmix = MixtureModel(Binomial.(9, samples))\nw1 = rand(mix, 10_000)\n\n# Version 2: From each p in the sample you make a binomial distribution and draw 1 value\n# from it. Then you put them all into one big array.\nw2 = rand.(Binomial.(9, samples), 1)\nw2 = vcat(w2...)\n\n# These are two different approaches but give the same result for lots of values drawn.\n# However, if you are only drawing a few values (less than samples) the first version\n# is preferrable since you can still use all the information in the samples.\n\nhistogram(w1, normalize = :probability, alpha = 0.6)\nhistogram!(w2, normalize = :probability, alpha = 0.6)\n", "meta": {"hexsha": "5050980ff1ee704a98122daa5f97e322214b9e0b", "size": 1552, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/snippet_03_20.jl", "max_stars_repo_name": "karajan9/statisticalrethinking", "max_stars_repo_head_hexsha": "e7516c468ca182c4b1c9cae0cfd0bb1feef7ed3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2020-06-03T14:18:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T16:52:26.000Z", "max_issues_repo_path": "scripts/snippet_03_20.jl", "max_issues_repo_name": "karajan9/statisticalrethinking", "max_issues_repo_head_hexsha": "e7516c468ca182c4b1c9cae0cfd0bb1feef7ed3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-06-13T05:56:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-12T14:05:57.000Z", "max_forks_repo_path": "scripts/snippet_03_20.jl", "max_forks_repo_name": "karajan9/statisticalrethinking", "max_forks_repo_head_hexsha": "e7516c468ca182c4b1c9cae0cfd0bb1feef7ed3c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-01T13:00:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-03T23:40:53.000Z", "avg_line_length": 27.7142857143, "max_line_length": 88, "alphanum_fraction": 0.681056701, "num_tokens": 509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087946129328, "lm_q2_score": 0.8723473680407889, "lm_q1q2_score": 0.8098949684465133}} {"text": "\n# Routines having to do with the normalizing function values on a grid with respect\n# to a given measure.\n\nnormalizing_weights(grid, measure) = sqrt.(quadweights(grid, measure))\n\n\"\"\"\nReturn a normalization for a sampling operator on a grid. The normalization ensures\na norm equivalence between the continuous norm of the function space associated\nwith the measure, and the discrete norm of the sampling vector.\n\nIn practice, this amounts to a diagonal scaling with the square roots of the\nweights of a quadrature rule on the grid that is exact on the span of the dictionary\nin the space.\n\"\"\"\nsampling_normalization(gb::GridBasis{T}, measure) where T =\n\tDiagonalOperator(gb, gb, sqrt.(quadweights(grid(gb), measure)))\n", "meta": {"hexsha": "e28f04c1344a106ddd74222f160d4ae9afa89e82", "size": 718, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/sampling/normalization.jl", "max_stars_repo_name": "JuliaApproximation/BasisFunctions.jl", "max_stars_repo_head_hexsha": "9f2ab9cae1394cbaede565db1036fbf0fbd1da9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-06-21T03:12:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T03:03:32.000Z", "max_issues_repo_path": "src/sampling/normalization.jl", "max_issues_repo_name": "JuliaApproximation/BasisFunctions.jl", "max_issues_repo_head_hexsha": "9f2ab9cae1394cbaede565db1036fbf0fbd1da9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28, "max_issues_repo_issues_event_min_datetime": "2020-01-07T17:23:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T17:50:16.000Z", "max_forks_repo_path": "src/sampling/normalization.jl", "max_forks_repo_name": "daanhb/BasisFunctions.jl", "max_forks_repo_head_hexsha": "93ef8f01b828b17d896acf11713a714fc7b6cb9b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-06-21T17:01:14.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-03T08:12:27.000Z", "avg_line_length": 39.8888888889, "max_line_length": 84, "alphanum_fraction": 0.7841225627, "num_tokens": 158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9441768620069626, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.8098847925497558}} {"text": "using ComponentArrays\nusing DifferentialEquations\nusing UnPack: @unpack\n\n\ntspan = (0.0, 20.0)\n\n\n## Lorenz system\nfunction lorenz!(D, u, p, t; f=0.0)\n @unpack σ, ρ, β = p\n @unpack x, y, z = u\n \n D.x = σ*(y - x)\n D.y = x*(ρ - z) - y - f\n D.z = x*y - β*z\n return nothing\nend\nfunction lorenz_jac!(D, u, p, t)\n @unpack σ, ρ, β = p\n @unpack x, y, z = u\n \n D[:x,:x] = -σ\n D[:x,:y] = σ\n\n D[:y,:x] = ρ\n D[:y,:y] = -1\n D[:y,:z] = -x\n\n D[:z,:x] = y\n D[:z,:y] = x\n D[:z,:z] = -β\n return nothing\nend\n\nlorenz_p = (σ=10.0, ρ=28.0, β=8/3)\nlorenz_ic = ComponentArray(x=0.0, y=0.0, z=0.0)\nlorenz_fun = ODEFunction(lorenz!, jac=lorenz_jac!)\nlorenz_prob = ODEProblem(lorenz_fun, lorenz_ic, tspan, lorenz_p)\n\n\n## Lotka-Volterra system\nfunction lotka!(D, u, p, t; f=0.0)\n @unpack α, β, γ, δ = p\n @unpack x, y = u\n \n D.x = α*x - β*x*y + f\n D.y = -γ*y + δ*x*y\n return nothing\nend\nfunction lotka_jac!(D, u, p, t)\n @unpack α, β, γ, δ = p\n @unpack x, y = u\n \n D[:x,:x] = α - β*y\n D[:x,:y] = -β*x\n\n D[:y,:x] = δ*y\n D[:y,:y] = -γ + δ*x\n return nothing\nend\n\nlotka_p = (α=2/3, β=4/3, γ=1.0, δ=1.0)\nlotka_ic = ComponentArray(x=1.0, y=1.0)\nlotka_fun = ODEFunction(lotka!, jac=lotka_jac!)\nlotka_prob = ODEProblem(lotka_fun, lotka_ic, tspan, lotka_p)\n\n\n## Composed Lorenz and Lotka-Volterra system\nfunction composed!(D, u, p, t)\n c = p.c #coupling parameter\n @unpack lorenz, lotka = u\n \n lorenz!(D.lorenz, lorenz, p.lorenz, t, f=c*lotka.x)\n lotka!(D.lotka, lotka, p.lotka, t, f=c*lorenz.x)\n return nothing\nend\nfunction composed_jac!(D, u, p, t)\n c = p.c\n @unpack lorenz, lotka = u\n \n lorenz_jac!(@view(D[:lorenz,:lorenz]), lorenz, p.lorenz, t)\n lotka_jac!(@view(D[:lotka,:lotka]), lotka, p.lotka, t)\n\n @view(D[:lorenz,:lotka])[:y,:x] = -c\n @view(D[:lotka,:lorenz])[:x,:x] = c\n return nothing\nend\n\ncomp_p = (lorenz=lorenz_p, lotka=lotka_p, c=0.01)\ncomp_ic = ComponentArray(lorenz=lorenz_ic, lotka=lotka_ic)\ncomp_fun = ODEFunction(composed!, jac=composed_jac!)\ncomp_prob = ODEProblem(comp_fun, comp_ic, tspan, comp_p)\n\n\n## Solve problem\n# We can solve the composed system...\ncomp_sol = solve(comp_prob, Rodas5())\n\n# ...or we can unit test one of the component systems\nlotka_sol = solve(lotka_prob, Rodas5())\n", "meta": {"hexsha": "8568cd515e3f35c918e628207dc3d1bdc1e41780", "size": 2313, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ODE_jac_example.jl", "max_stars_repo_name": "torfjelde/ComponentArrays.jl", "max_stars_repo_head_hexsha": "37e3e4d9d0c0ab12e672984188cf5bf23e10b8e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 159, "max_stars_repo_stars_event_min_datetime": "2020-04-21T21:01:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:43:34.000Z", "max_issues_repo_path": "examples/ODE_jac_example.jl", "max_issues_repo_name": "torfjelde/ComponentArrays.jl", "max_issues_repo_head_hexsha": "37e3e4d9d0c0ab12e672984188cf5bf23e10b8e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 116, "max_issues_repo_issues_event_min_datetime": "2020-04-22T15:29:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T03:01:43.000Z", "max_forks_repo_path": "examples/ODE_jac_example.jl", "max_forks_repo_name": "torfjelde/ComponentArrays.jl", "max_forks_repo_head_hexsha": "37e3e4d9d0c0ab12e672984188cf5bf23e10b8e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2020-04-26T23:05:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T03:13:58.000Z", "avg_line_length": 22.6764705882, "max_line_length": 64, "alphanum_fraction": 0.5866839602, "num_tokens": 970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939913343093499, "lm_q2_score": 0.8615382023207901, "lm_q1q2_score": 0.8097712519460972}} {"text": "## analytic.jl :special cases where eigenfunctions are known analytically\n\n# (separable) exponential covariance function with p = 0.5\nfunction compute_analytic(cov::CovarianceFunction{1,Exponential{T}} where {T},n::N where {N<:Integer},pts::V where {V<:AbstractVector})\n\tλ = cov.cov.λ\n ω = findroots(λ, n)\n ev = @. 2*λ/(λ^2*ω^2+1)\n n = @. sqrt(2)/2*sqrt(1/ω*(λ^2*ω^2*cos(ω)*sin(ω)+λ^2*ω^3-2*λ*ω*cos.(ω)^2-cos(ω)*sin(ω)+ω)+2*λ)\n\tef = diagm(0 => 1.0/n)*( sin.(ω*pts') + λ*diagm(0 => ω)*cos.(ω*pts') )\n\n\tSpectralData(sqrt.(ev),ef')\nend\n\n# find all positive (>0) zeros of the transcendental function tan(ω) = 2*λ*ω/(λ^2*ω^2-1)\nfunction findroots(λ::T, n::N) where {T <: AbstractFloat, N <: Integer}\n\t\n\t# define the transcendental function\n\tf(ω) = (λ^2*ω^2-1)*sin(ω)-2*λ*ω*cos(ω)\n\n\t# find range around singularity 1/λ\n\tleft_point_of_range = (2*floor(1/(π*λ)-1/2))*π/2 # left odd multiple of π/2\n\tright_point_of_range = (2*ceil(1/(π*λ)-1/2)+1)*π/2 # right odd multiple of π/2\n\n\t# find roots before 1/λ, if any\n\tif left_point_of_range ≠ π/2\n\t\troots = zeros(min(n,round(UInt64,floor(abs(1/λ/π-1/2)))))\n\t\tleft_point = π/2\n\t\tright_point = 1*π\n\t\tfor i = 1:length(roots)\n\t\t\t@inbounds roots[i] = bisect_root(f,left_point,right_point)[1]\n\t\t\tright_point = roots[i] + π\n\t\t\tleft_point = left_point + π\n\t\tend\n\telse\n\t\troots = zeros(0)\n\tend\n\n\t# find roots inside range around 1/λ\n\t( length(roots) ≥ n || floor(1/(π*λ)-1/2) < 0 ) || \n\tpush!(roots,bisect_root(f,left_point_of_range+eps(T),1/λ)[1]) # first intersection point\n\t( length(roots) ≥ n || ceil(1/(π*λ)-1/2) < 0 ) || \n\tpush!(roots,bisect_root(f,1/λ,right_point_of_range)[1]) # second intersection point\n\n\t# if the first root is zero, cut it off\n\troots[1] == 0 ? shift!(roots) : [] # empty expression\n\n\t# find roots after 1/λ\n\tstartindex = 1 + length(roots)\n\tif n-length(roots) > 0\n\t\troots = [roots; zeros(n-length(roots))]\n\t\tleft_point = (2*ceil(1/(π*λ)-1/2)+2)*π/2\n\t\tright_point = (2*ceil(1/(π*λ)-1/2)+3)*π/2\n\t\tfor i = startindex:length(roots)\n\t\t\t@inbounds roots[i] = bisect_root(f,left_point,right_point)[1]\n\t\t\tright_point = roots[i] + π\n\t\t\tleft_point = left_point + π\n\t\tend\n\tend\n\treturn roots\nend\n\n# bissection method to find the zeros of a function in a particular interval [x1,x2]\nfunction bisect_root(fn::Function, x1::T, x2::T) where {T<:Real}\n\txm = middle(x1, x2)\n\ts1 = sign(fn(x1))\n\ts2 = sign(fn(x2))\n\twhile x1 < xm < x2\n\t\tsm = sign(fn(xm))\n\n\t\tif s1 != sm\n\t\t\tx2 = xm\n\t\t\ts2 = sm\n\t\telse\n\t\t\tx1 = xm\n\t\t\ts1 = sm\n\t\tend\n\n\t\txm = middle(x1, x2)\n\tend\n\n\treturn x1, x2\nend\n\n# helper function to find the real \"mid point\" of two given floating point numbers\nfunction middle(x1::Float64, x2::Float64)\n\t# use the usual float rules for combining non-finite numbers\n\tif !isfinite(x1) || !isfinite(x2)\n\t\treturn x1 + x2\n\tend\n\n\t# always return 0.0 when inputs have opposite sign\n\tif sign(x1) != sign(x2) && x1 != 0.0 && x2 != 0.0\n\t\treturn 0.0\n\tend\n\n\tnegate = x1 < 0.0 || x2 < 0.0\n\n\tx1_int = reinterpret(UInt64, abs(x1))\n\tx2_int = reinterpret(UInt64, abs(x2))\n\tunsigned = reinterpret(Float64, (x1_int + x2_int) >> 1)\n\n\tnegate ? -unsigned : unsigned\nend\n", "meta": {"hexsha": "58ec12bb49f1f9014cd1c582da58ec6691c2a39d", "size": 3088, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/analytic.jl", "max_stars_repo_name": "devmotion/GaussianRandomFields.jl", "max_stars_repo_head_hexsha": "6a3ba77bb38d7ee8cb510fc4cee97376794d9577", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/analytic.jl", "max_issues_repo_name": "devmotion/GaussianRandomFields.jl", "max_issues_repo_head_hexsha": "6a3ba77bb38d7ee8cb510fc4cee97376794d9577", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/analytic.jl", "max_forks_repo_name": "devmotion/GaussianRandomFields.jl", "max_forks_repo_head_hexsha": "6a3ba77bb38d7ee8cb510fc4cee97376794d9577", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6923076923, "max_line_length": 135, "alphanum_fraction": 0.6476683938, "num_tokens": 1177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109742068041, "lm_q2_score": 0.8519528057272543, "lm_q1q2_score": 0.8097052960694598}} {"text": "# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n# jupytext:\n# formats: ipynb,jl:light\n# text_representation:\n# extension: .jl\n# format_name: light\n# format_version: '1.5'\n# jupytext_version: 1.4.2\n# kernelspec:\n# display_name: Julia 1.4.0\n# language: julia\n# name: julia-1.4\n# ---\n\nusing Plots\nusing LaTeXStrings\n\n# # Circle\n\n# +\nθ = 0:0.01:2π\nx = @. cos(θ)\ny = @. sin(θ)\n\np = plot(\n xlabel = L\"x\",\n ylabel = L\"y\",\n xlim = [-1, 1],\n ylim = [-1, 1],\n aspect_ratio = :equal,\n)\n\nplot!(p, x, y, label = L\"x^2+y^2 = 1\")\n# -\n\n# # Astroid\n\n# +\nθ = 0:0.01:2π\na = 2\nx = @. a * cos(θ)^3\ny = @. a * sin(θ)^3\n\neq = latexstring(\"x^{2/3}+y^{2/3} = $a^{2/3}\")\n\np = plot(\n title = eq,\n xlabel = L\"x\",\n ylabel = L\"y\",\n xlim = [-2, 2],\n ylim = [-2, 2],\n aspect_ratio = :equal,\n)\n\nplot!(p, x, y, label = :false)\n# -\n\n# # Lissajous\n\n# +\nθ = 0:0.01:2π\nx = @. sin(θ)\ny = @. sin(2θ)\n\neq = latexstring(\"y^2=4x^2(1-x^2)\")\n\np = plot(\n title = eq,\n xlabel = L\"x\",\n ylabel = L\"y\",\n xlim = [-1, 1],\n ylim = [-1, 1],\n aspect_ratio = :equal,\n)\n\nplot!(p, x, y, label=false)\n\n# +\nθ = -π/4:0.01:π/4\n\nx = @. tan(θ)\ny = @. cos(2θ)\n\neq = L\"$y=\\frac{1-x^2}{1+x^2}$\"\n\np = plot(\n title = eq,\n xlabel = L\"x\",\n ylabel = L\"y\",\n xlim = [-1, 1],\n ylim = [0, 1],\n aspect_ratio = :equal,\n)\n\nplot!(p, x, y, label = :false)\n# -\n\n# # Archimedean Spiral\n\n# +\nθ = 0:0.01:2π\na = 2\nr = @. a*θ\nx = @. r * cos(θ)\ny = @. r * sin(θ)\n\neq = L\"r=a\\theta\"\n\np = plot(\n title = eq,\n xlabel = L\"x\",\n ylabel = L\"y\",\n aspect_ratio = :equal,\n)\n\nplot!(p, x, y, label = :false)\n# -\n\n# # Cardioid \n\n# +\nθ = 0:0.01:2π\na = 2\nr = @. a*(1+cos(θ))\nx = @. r * cos(θ)\ny = @. r * sin(θ)\n\neq = L\"r=a(1+\\cos(\\theta)\"\n\np = plot(\n title = eq,\n xlabel = L\"x\",\n ylabel = L\"y\",\n aspect_ratio = :equal,\n)\n\nplot!(p, x, y, label = :false)\n# -\n\n# # Rose Curve\n\n# ## n = 2\n\n# +\nθ = 0:0.01:2π\na = 2\nn = 2\nr = @. a*sin(n*θ)\nx = @. r * cos(θ)\ny = @. r * sin(θ)\n\neq = latexstring(\"r=a\\\\sin($n\\\\theta)\")\n\np = plot(\n title = eq,\n xlabel = L\"x\",\n ylabel = L\"y\",\n aspect_ratio = :equal,\n)\n\nplot!(p, x, y, label = :false)\n# -\n\n# ## n = 3\n\n# +\nθ = 0:0.01:2π\na = 2\nn = 3\nr = @. a*sin(n*θ)\nx = @. r * cos(θ)\ny = @. r * sin(θ)\n\neq = latexstring(\"r=a\\\\sin($n\\\\theta)\")\n\np = plot(\n title = eq,\n xlabel = L\"x\",\n ylabel = L\"y\",\n aspect_ratio = :equal,\n)\n\nplot!(p, x, y, label=false)\n# -\n\n# ## n = 4\n\n# +\nθ = 0:0.01:2π\na = 2\nn = 4\nr = @. a*sin(n*θ)\nx = @. r * cos(θ)\ny = @. r * sin(θ)\n\neq = latexstring(\"r=a\\\\sin($n\\\\theta)\")\n\np = plot(\n title = eq,\n xlabel = L\"x\",\n ylabel = L\"y\",\n aspect_ratio = :equal,\n)\n\nplot!(p, x, y, label = :false)\n# -\n\n# ## Rose (gif)\n\n# +\nθ = 0:0.01:2π\na = 2\nanim = @animate for n in 2:10\n r = @. a*sin(n*θ)\n x = @. r * cos(θ)\n y = @. r * sin(θ)\n\n eq = latexstring(\"r=a\\\\sin($n\\\\theta)\")\n\n p = plot(\n title = eq,\n xlabel = L\"x\",\n ylabel = L\"y\",\n xlim=[-3,3],\n ylim=[-3,3],\n aspect_ratio = :equal,\n )\n\n plot!(p, x, y, label = :false)\nend\n\nanim;\n# -\n\ngif(anim, \"roses.gif\", fps=2)\n", "meta": {"hexsha": "f0726c1789917825d1282fd05f3e9d1ed89d2078", "size": 3130, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "experiments/notebook/curve.jl", "max_stars_repo_name": "yasutak/MyWorkflow.jl", "max_stars_repo_head_hexsha": "99deb349edbbaf6b7f797916fb7afbd1b0d33884", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "experiments/notebook/curve.jl", "max_issues_repo_name": "yasutak/MyWorkflow.jl", "max_issues_repo_head_hexsha": "99deb349edbbaf6b7f797916fb7afbd1b0d33884", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-09-06T12:34:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-06T12:39:46.000Z", "max_forks_repo_path": "experiments/notebook/curve.jl", "max_forks_repo_name": "hsugawa8651/MyWorkflow.jl", "max_forks_repo_head_hexsha": "48edcbcc3fd9e425895ef91bea833ef1e5d4c3fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.1512605042, "max_line_length": 46, "alphanum_fraction": 0.4533546326, "num_tokens": 1343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.8991213826762113, "lm_q1q2_score": 0.8096855816348985}} {"text": "using SymPy\n\nN = 11\n\nb = [symbols(\"b_$i\", real=true) for i in 1:N]\nB = diagm(b)\n\n\n# 2nd order dissipation\nD1 = zeros(Int, N, N)\nfor i in 1:N\n D1[i,i] = 1\nend\nfor i in 1:N-1\n D1[i+1,i] = -1\nend\nD1[1,2] = 1\ndisplay(D1)\n\nB1 = eye(Int, N); B1[1,1] = 0\ndisplay(B1)\n\ndisplay(D1' * B * D1)\ndisplay(D1' * B1 * D1)\n\n\n# 4th order dissipation\nD2 = zeros(Int, N, N)\nfor i in 1:N\n D2[i,i] = -2\nend\nfor i in 1:N-1\n D2[i+1,i] = 1\n D2[i,i+1] = 1\nend\nboundary_width = 1\nfor i in 1:boundary_width\n D2[i,:] = D2[boundary_width+1,:]\n D2[end-i+1,:] = D2[end-boundary_width,:]\nend\ndisplay(D2)\n\nB2 = eye(Int, N); B2[1,1] = B2[end,end] = 0\ndisplay(B2)\n\ndisplay(D2' * B * D2)\ndisplay(D2' * B2 * D2)\n\n\n# 6th order dissipation\nD3 = zeros(Int, N, N)\nfor i in 1:N\n D3[i,i] = -3\nend\nfor i in 1:N-1\n D3[i+1,i] = 3\n D3[i,i+1] = 1\nend\nfor i in 1:N-2\n D3[i+2,i] = -1\nend\nboundary_width = 2\nfor i in 1:boundary_width\n D3[i,:] = D3[boundary_width+1,:]\nend\nfor i in 1:boundary_width-1\n D3[end-i+1,:] = D3[end-boundary_width+1,:]\nend\ndisplay(D3)\n\nB3 = eye(Int, N); B3[1,1] = B3[2,2]= B3[end,end] = 0\ndisplay(B3)\n\ndisplay(D3' * B * D3)\ndisplay(D3' * B3 * D3)\n\n\n# 8th order dissipation\nD4 = zeros(Int, N, N)\nfor i in 1:N\n D4[i,i] = 6\nend\nfor i in 1:N-1\n D4[i+1,i] = -4\n D4[i,i+1] = -4\nend\nfor i in 1:N-2\n D4[i+2,i] = 1\n D4[i,i+2] = 1\nend\nboundary_width = 2\nfor i in 1:boundary_width\n D4[i,:] = D4[boundary_width+1,:]\n D4[end-i+1,:] = D4[end-boundary_width,:]\nend\ndisplay(D4)\n\nB4 = eye(Int, N); B4[1,1] = B4[2,2]= B4[end,end] = B4[end-1,end-1] = 0\ndisplay(B4)\n\ndisplay(D4' * B * D4)\ndisplay(D4' * B4 * D4)\n", "meta": {"hexsha": "1e92441ff42c80ff00d9034f12d00594dd2f0657", "size": 1625, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "dev/MattssonSvärdNordström2004_dev.jl", "max_stars_repo_name": "ranocha/SummationByPartsOperators.jl", "max_stars_repo_head_hexsha": "2f6ec738e7387553024cd82f4abff9a38fcefc96", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2018-12-06T19:51:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T19:17:47.000Z", "max_issues_repo_path": "dev/MattssonSvärdNordström2004_dev.jl", "max_issues_repo_name": "ranocha/SummationByPartsOperators.jl", "max_issues_repo_head_hexsha": "2f6ec738e7387553024cd82f4abff9a38fcefc96", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 107, "max_issues_repo_issues_event_min_datetime": "2017-12-17T12:07:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T14:10:41.000Z", "max_forks_repo_path": "dev/MattssonSvärdNordström2004_dev.jl", "max_forks_repo_name": "ranocha/SummationByPartsOperators.jl", "max_forks_repo_head_hexsha": "2f6ec738e7387553024cd82f4abff9a38fcefc96", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:01:43.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:01:43.000Z", "avg_line_length": 15.7766990291, "max_line_length": 70, "alphanum_fraction": 0.568, "num_tokens": 775, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545348152282, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.8096412543351643}} {"text": "using Plots\n\n#graphs a cylindrical aprx with n planes, radius =r, height = h\nfunction cylinder(n,r,h)\n\tp = plot(xlims=[-h,h],ylims=[-2*r,2*r],zlims=[-2*r,2*r],legend=false)\n\tx = range(0,h,length=10)\n\talpha = range(0,2*pi,length=n)\n\t\n\tfor theta in alpha\n\t\tif theta == alpha[end]\n\t\t\tbreak\n\t\tend\n\t\ty=r*cos(theta)*ones(length(x))\n\t\tz=r*sin(theta)*ones(length(x))\n\t\tplot!(x,y,z,seriescolor=:black)\n\tend\n\tdisplay(p)\nend\n\n#graphs a function to be revolved, at angles theta_i in alpha\n#use at least n=10,15\nfunction PolarLines(a,b,n)\n\n\t#f is the function to revolve\n\tf(u) = 1+sin(u)cos(u)\n\tp = plot(legend=false)\n\tx=range(a,b,length=10)\n\talpha = range(0,2*pi,length=n)\n\tfor theta in alpha\n\t\tif theta == alpha[end]\n\t\t\tbreak\n\t\tend\n\t\ty=cos(theta)*f.(x)\n\t\tz=sin(theta)*f.(x)\n\t\tplot!(x,y,z,seriescolor=:black)\n\tend\n\tsavefig(p,\"fig.html\")\n\tp\nend\n\n#graphs a function to be revolved, at vertical slices, and with PolarLines\n#use at least n=10\nfunction Rings(a,b,n,m)\n\n\t#f is the function to revolve\n\tf(u) = 1+sin(u)cos(u)\n\tq = plot([f,0],a,b)\n\t\n\tp = plot(legend=false)\n\tx=range(a,b,length=n)\n\talpha = range(0,2*pi,length=m)\n\t\n\t\n\tfor xi in x\n\t\ty = Float64[]\n\t\tz = Float64[]\n\t\txp = xi*ones(m)\n\t\tfor theta in alpha\n\t\t\tpush!(y,cos(theta)*f(xi))\n\t\t\tpush!(z,sin(theta)*f(xi))\n\t\t\n\t\tend\n\t\tplot!(p,xp,y,z,seriescolor=:black)\n\t\n\tend\n\tp1 = PolarLines(a,b,2*m)\n\t\n\tf = plot(\n\tp,p1,q,\n\tlayout=@layout([a b;c]),\n\tlegend=false,\n\ttitlelocation=:left,\n\tbottom_margin=10px,\n\twindow_title=\"Solid of revolution\")\n\tsavefig(f,\"figures.html\")\n\tf\nend\n", "meta": {"hexsha": "736c42e44177eb7f5ccdefeb80db1a75816b1abe", "size": 1510, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "integral_applications/solids.jl", "max_stars_repo_name": "thomastjdavis/CalculusViz.jl", "max_stars_repo_head_hexsha": "225eefeb88f42689e05b50deed50101faaeb447e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-17T05:15:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-17T05:15:52.000Z", "max_issues_repo_path": "integral_applications/solids.jl", "max_issues_repo_name": "thomastjdavis/CalculusViz.jl", "max_issues_repo_head_hexsha": "225eefeb88f42689e05b50deed50101faaeb447e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "integral_applications/solids.jl", "max_forks_repo_name": "thomastjdavis/CalculusViz.jl", "max_forks_repo_head_hexsha": "225eefeb88f42689e05b50deed50101faaeb447e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.358974359, "max_line_length": 74, "alphanum_fraction": 0.6496688742, "num_tokens": 524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545289551957, "lm_q2_score": 0.853912760387131, "lm_q1q2_score": 0.8096412510936911}} {"text": "### A Pluto.jl notebook ###\n# v0.12.7\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ de7a5e8a-1ee4-11eb-2bbf-0f0eb3e489ec\nusing Pkg, DrWatson\n\n# ╔═╡ e4eeb13a-1ee4-11eb-0113-91f9a9c3b659\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random\n\tRandom.seed!(1)\nend\n\n# ╔═╡ ac3ceabe-1ee4-11eb-3935-313e96aafd62\nmd\"## Listing 2.13\"\n\n# ╔═╡ e9fa266e-1eeb-11eb-2630-59930c474ed3\nfunction montyHall(switchPolicy)\n prize, choice = rand(1:3), rand(1:3)\n if prize == choice\n revealed = rand(setdiff(1:3,choice))\n else\n revealed = rand(setdiff(1:3,[prize,choice]))\n end\n\n if switchPolicy\n choice = setdiff(1:3,[revealed,choice])[1]\n end\n return choice == prize\nend\n\n# ╔═╡ 9046a9c8-1f64-11eb-067f-6552cbd8919e\nN = 10^6\n\n# ╔═╡ 9046fdce-1f64-11eb-3888-651b7d2d17ac\nText(\"Success probability with policy I (stay): $(sum([montyHall(false) for _ in 1:N])/N)\")\n\n# ╔═╡ 90479df6-1f64-11eb-3e06-af4adc28a9d5\nText(\"Success probability with policy II (switch): $(sum([montyHall(true) for _ in 1:N])/N)\")\n\n# ╔═╡ ea086874-1eeb-11eb-2cb0-4186697d4294\nmd\"## End of listing 2.13\"\n\n# ╔═╡ Cell order:\n# ╟─ac3ceabe-1ee4-11eb-3935-313e96aafd62\n# ╠═de7a5e8a-1ee4-11eb-2bbf-0f0eb3e489ec\n# ╠═e4eeb13a-1ee4-11eb-0113-91f9a9c3b659\n# ╠═e9fa266e-1eeb-11eb-2630-59930c474ed3\n# ╠═9046a9c8-1f64-11eb-067f-6552cbd8919e\n# ╠═9046fdce-1f64-11eb-3888-651b7d2d17ac\n# ╠═90479df6-1f64-11eb-3e06-af4adc28a9d5\n# ╟─ea086874-1eeb-11eb-2cb0-4186697d4294\n", "meta": {"hexsha": "4bf20263ddba5e19a024d122be4997f5703bbf72", "size": 1454, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/02/listing2.13.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/02/listing2.13.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/02/listing2.13.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 25.9642857143, "max_line_length": 93, "alphanum_fraction": 0.7063273728, "num_tokens": 718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.91243616285804, "lm_q2_score": 0.8872046041554923, "lm_q1q2_score": 0.8095175646856236}} {"text": "# Fractal Surface Interpolation demo \n\nusing Makie \nusing Random \nusing FractalTools\nusing GeometryBasics \nusing LinearAlgebra\n\n# Get interpolation data \ntrig = Triangle(\n Point(BigFloat(-1.), BigFloat(-1)), \n Point(BigFloat(1.), BigFloat(-1.)), \n Point(BigFloat(0.), BigFloat(2.))\n)\nf(x, y) = x^2 + y^2 + 1\npnts3d = getdata(f, trig, 100)\n\n# Construct test points \ntpnts3d = getdata(f, trig, 100)\ntpnts = project(tpnts3d)\n\nα = Node(0.001)\nniter = Node(1) \nerr = lift(niter, α) do n, α \n itp = interpolate(pnts3d, α=α, maxiters=n)\n fval = map(pnt -> f(pnt...), tpnts) \n ival = map(pnt -> itp(pnt...), tpnts) \n val = abs.(fval - ival) ./ abs.(fval) * 100\n val\nend \n\nfig = Figure(title=\"Fractal Interpolation\") \nax = Axis(fig[1,1], xlabel=\"npoints\", ylabel=\"Relative Error (%)\", title=\"Fractal Surface Interpolation Error Demo\") \nplt = lines!(ax, err) \n\ngl = GridLayout()\ngl2 = GridLayout()\ngl[1, 1] = slider = Slider(fig, range=0.001 : 0.0001 : 0.01, startvalue=0.001, tellwidth=false)\ngl2[1, 1] = button1 = Button(fig, label=\"Increment\", tellwidth=false)\ngl2[1, 2] = button2 = Button(fig, label=\"Decrement\", tellwidth=false)\ngl[2, 1] = gl2\ngl[1, 2] = label1 = Label(fig, \"alpha = $(slider.value[])\")\ngl[2, 2] = label2 = Label(fig, \"niter = $(niter[])\")\nfig[2, 1] = gl\n\non(button1.clicks) do n \n niter[] += 1\n label2.text[] = \"niter = \" * string(niter[])\n autolimits!(ax)\nend \n\non(button2.clicks) do n \n niter[] -= 1\n label2.text[] = \"niter = \" * string(niter[])\n autolimits!(ax)\nend \n\non(slider.value) do val \n α[] = val\n label1.text[] = \"alpha = \" * string(val)\n autolimits!(ax)\nend\n\ndisplay(fig)\n\n# # For video recording.\n# fps = 60\n# record(fig.scene, \"demo.mp4\"; framerate = fps) do io\n# for i = 1 : 50 * fps\n# sleep(1/fps)\n# recordframe!(io)\n# end\n# end\n", "meta": {"hexsha": "a9005cd32418ba3047d1e4e01783bdb86e9841c8", "size": 1835, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/stash/mesh/demo.jl", "max_stars_repo_name": "zekeriyasari/FractalTools.jl", "max_stars_repo_head_hexsha": "9896b88d30b3a22e1f808f812ce60d23d2a27013", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-09-08T12:20:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T12:50:16.000Z", "max_issues_repo_path": "example/stash/mesh/demo.jl", "max_issues_repo_name": "zekeriyasari/FractalTools.jl", "max_issues_repo_head_hexsha": "9896b88d30b3a22e1f808f812ce60d23d2a27013", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2020-09-05T18:22:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-26T10:09:46.000Z", "max_forks_repo_path": "example/stash/mesh/demo.jl", "max_forks_repo_name": "zekeriyasari/FractalTools.jl", "max_forks_repo_head_hexsha": "9896b88d30b3a22e1f808f812ce60d23d2a27013", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7972972973, "max_line_length": 117, "alphanum_fraction": 0.6130790191, "num_tokens": 655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436483, "lm_q2_score": 0.8791467690927438, "lm_q1q2_score": 0.8095092647515673}} {"text": "# https://projecteuler.net/problem=2\n# Each new term in the Fibonacci sequence is generated by adding the previous two terms.\n# By starting with 1 and 2, the first 10 terms will be:\n# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...\n# By considering the terms in the Fibonacci sequence whose values do not exceed four million,\n# find the sum of the even-valued terms.\n\nresult = 0\na = 1\nb = 2\n\nwhile a <= 4000000\n if a % 2 == 0\n result += a\n end\n a = a + b\n a, b = b, a\nend\n\nprintln(result)\n", "meta": {"hexsha": "621ea2ce3390f56247675209312d69cbfc7287bc", "size": 499, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "2/002_even_fibonacci_numbers.jl", "max_stars_repo_name": "the-gigi/project-euler", "max_stars_repo_head_hexsha": "e5bd6ba709843a32d20460220ddf63ad75a5b6a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2017-11-16T01:53:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-18T14:00:10.000Z", "max_issues_repo_path": "2/002_even_fibonacci_numbers.jl", "max_issues_repo_name": "the-gigi/project-euler", "max_issues_repo_head_hexsha": "e5bd6ba709843a32d20460220ddf63ad75a5b6a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2/002_even_fibonacci_numbers.jl", "max_forks_repo_name": "the-gigi/project-euler", "max_forks_repo_head_hexsha": "e5bd6ba709843a32d20460220ddf63ad75a5b6a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-03-16T11:58:23.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-08T10:18:18.000Z", "avg_line_length": 23.7619047619, "max_line_length": 93, "alphanum_fraction": 0.6452905812, "num_tokens": 168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9416541544761566, "lm_q2_score": 0.8596637451167997, "lm_q1q2_score": 0.8095059370417662}} {"text": "# Based on the introductory discussion on\n# https://www.maa.org/press/periodicals/loci/joma/the-sir-model-for-spread-of-disease-the-differential-equation-model\n\n## Uncomment the following lines if used as a standalone\n# using DifferentialEquations\n# using Plots\n\nfunction SIR(du,u,p,t)\n s,i,r = u\n b,k = p\n du[1] = -b*s*i\n du[2] = b*s*i - k*i\n du[3] = k*i\nend\n\n# TODO: make the following a doctest example\n # #initian conditions\n # p = [0.5/7900000.0,0.33]\n # u0 = [7900000.0,10.0,0.0]\n # tspan = (0.0,140.0)\n\n # #solve\n # sir = ODEProblem(SIR,u0,tspan,p)\n # sol = solve(sir)\n\n # #plot\n # plot(sol)\n", "meta": {"hexsha": "515392c54378f461bf28ad92ab018c8dcdb2a452", "size": 641, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/sir_model.jl", "max_stars_repo_name": "madisonestabrook/Julia", "max_stars_repo_head_hexsha": "799508e2b8a3087bdd7fb4d2a23a2ab4788ea854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/math/sir_model.jl", "max_issues_repo_name": "madisonestabrook/Julia", "max_issues_repo_head_hexsha": "799508e2b8a3087bdd7fb4d2a23a2ab4788ea854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/math/sir_model.jl", "max_forks_repo_name": "madisonestabrook/Julia", "max_forks_repo_head_hexsha": "799508e2b8a3087bdd7fb4d2a23a2ab4788ea854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8928571429, "max_line_length": 117, "alphanum_fraction": 0.6209048362, "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104962847374, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.8094847303389392}} {"text": "function gcd{T<:Integer}(a::T, b::T)\n neg = a < 0\n while b != 0\n t = b\n b = rem(a, b)\n a = t\n end\n g = abs(a)\n neg ? -g : g\nend\n", "meta": {"hexsha": "970da0536dd945763e362528ced5bdcffc35e9a6", "size": 164, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/greatest-common-divisor.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/greatest-common-divisor.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/greatest-common-divisor.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.9090909091, "max_line_length": 36, "alphanum_fraction": 0.3719512195, "num_tokens": 67, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9664104943498961, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.8094847169662539}} {"text": "\"\nReturn the k'th moment of a truncated normal distribution.\n\"\nfunction moment(d::Truncated{Normal{T},Continuous}, k::Int) where T\n k == 0 ? one(T) : last(moments(d,k))\nend\n\n\"\nCompute the 1'st to k'th moment of a truncated normal distribution. Uses a recursive formula.\n\"\nfunction moments(d::Truncated{Normal{T},Continuous}, k::Int) where T\n k == 0 && return 1\n m = Array{T}(undef,k+2) #Array of moments with index i being the i-2's moment \n #(treating the -1's moment as 0 and 0'ths moment as 1)\n m[1], m[2] = 0, 1 \n pars = params(d)\n μ, σ, σ² =pars[1], pars[2], pars[2]^2\n L, U = pars[3], pars[4]\n zL, zU = (L - μ)/σ, (U - μ)/σ \n ϕL, ϕU = pdf.(Normal(),(zL, zU))\n ΦUL = cdf(Normal(),zU) - cdf(Normal(),zL)\n for i in 3:(k+2)\n kk = i-2\n #recursive formula for kk'th moment as a function of the previous two moments (if kk=-1 it uses 0)\n m[i] = (kk-1)*σ²*m[i-2] + μ*m[i-1] - σ*(U^(kk-1)*ϕU - L^(kk-1)*ϕL)/ΦUL\n end\n return m[3:(k+2)]\nend\n", "meta": {"hexsha": "0198c538017b3a64557238a4d5a8a1f6d6ba8c92", "size": 1023, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/distributionsPackageExtensions.jl", "max_stars_repo_name": "yoninazarathy/TruncatedDistributions.jl", "max_stars_repo_head_hexsha": "9c5928c91f01142232dd9a3969f8f9b2dda3880b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-05T10:31:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-05T10:31:56.000Z", "max_issues_repo_path": "src/univariate/distributionsPackageExtensions.jl", "max_issues_repo_name": "yoninazarathy/TruncatedDistributions.jl", "max_issues_repo_head_hexsha": "9c5928c91f01142232dd9a3969f8f9b2dda3880b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-05-01T12:20:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-04T12:08:55.000Z", "max_forks_repo_path": "src/univariate/distributionsPackageExtensions.jl", "max_forks_repo_name": "yoninazarathy/TruncatedDistributions.jl", "max_forks_repo_head_hexsha": "9c5928c91f01142232dd9a3969f8f9b2dda3880b", "max_forks_repo_licenses": ["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.275862069, "max_line_length": 106, "alphanum_fraction": 0.5718475073, "num_tokens": 384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9458012701768145, "lm_q2_score": 0.8558511414521923, "lm_q1q2_score": 0.80946509666776}} {"text": "module lorenz_model\n\nusing DifferentialEquations, Flux, Optim, DiffEqFlux, Plots\n\nmodel_params=[10.0,28.0,8.0/3]\nall_ic=[[1.0,0.0,0.0],[0.5,1.0,0.0], [3,0.2,0.1]];\ntend=10.0\ntstart=0.0\nsampling=0.05\n\n\n\nfunction model(du,u,p,t)\n x,y,z = u\n σ,ρ,β = p\n du[1] = dx = σ*(y-x)\n du[2] = dy = x*(ρ-z) - y\n du[3] = dz = x*y - β*z\nend\n\n\nfunction InitPlot()\n\n mycolor=[:blue, :red, :green, :purple, :black, :cyan, :orange]\n t=tstart:sampling:100.0\n odedata=[ solve(ODEProblem(model,η,(tstart,100.0), model_params), Tsit5(), saveat=t, abstol=1e-8,reltol=1e-6) for η in all_ic];\n pl = plot(t,odedata[1][1,:],label=\"data 1\", color=mycolor[1], lw=2, legend=false)\n\n for k in 2:length(all_ic)\n plot!(pl,t,odedata[k][1,:],label=\"data $k\", color=mycolor[k], lw=2)\n end\n title!(pl, \"Lorenz Chaos\")\n xlabel!(pl, \"Time\")\n ylabel!(pl, \"Variable\")\n savefig(\"Lorenz_init.png\")\n display(pl)\n\nend\n\n\nfunction predict_adjoint(param) # Our 1-layer neural network\n prob=ODEProblem(model,[1.0,0.0,0.0],(tstart,tend), model_params)\n Array(concrete_solve(prob,Tsit5(),param[1:3],param[4:end],saveat=tstart:sampling:tend,abstol=1e-8,reltol=1e-6))\nend\n\n\n# Generate some data to fit, and add some noise to it\ndata=predict_adjoint([1.0,0.0,0.0,10.0,28.0,8.0/3])\nσN=0.05\ndata+=σN*randn(size(data))\n\n\n#Init guess for the parameters\npguess=[0.8,0.1,0.1,10.5,28.5,9.0/3]\n\n\nfunction loss_adjoint(param)\n prediction = predict_adjoint(param)\n loss = sum(abs2,prediction - data)\n loss\nend\n\nfunction train_model(;pguess=[1.1,0.05,-0.05,10.2,28.2,9.0/3])\n println(\"The initial loss function is $(loss_adjoint(pguess)[1])\")\n resinit = DiffEqFlux.sciml_train(loss_adjoint,pguess,ADAM(), maxiters=4000)\n res = DiffEqFlux.sciml_train(loss_adjoint,resinit.minimizer,BFGS(initial_stepnorm=0.0001), maxiters=4000)\n println(\"The parameters are $(res.minimizer) with final loss value $(res.minimum)\")\n return(res)\n\nend\n\nfunction plotFit(param; vars=(1,2,3), tend=100.0)\n\n validationPlot(param, param[1:3], vars=vars, tend=tend)\n\nend\n\nfunction validationPlot(param, ic; vars=(1,2,3), tend=100.0)\n\n sol_fit=solve(ODEProblem(model,ic,(0.0,tend),param[4:end]), Tsit5())\n sol_actual=solve(ODEProblem(model,ic,(0.0,tend),model_params), Tsit5())\n pl=plot(sol_fit, lw=2, legend=false, vars=vars, color=:green)\n plot!(pl,sol_actual,vars=vars,color=:blue)\n title!(pl,\"Model Parameter Fits\")\n savefig(\"valid_plot_lorenz2.png\")\n display(pl)\n\nend\n\nend #module\n\nlorenz_model.InitPlot()\n\nresL=lorenz_model.train_model()\n\nlorenz_model.plotFit(resL.minimizer; vars=(1,2,3), tend=30.0)\n\nlorenz_model.plotFit(resL.minimizer; vars=(0,1), tend=30.0)\n", "meta": {"hexsha": "430475f385001b9d1781567f72e5a6f90b86273f", "size": 2676, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/lorentz_param_fit.jl", "max_stars_repo_name": "khannay/FittingParamsDiffEqFlux", "max_stars_repo_head_hexsha": "19cf5691b5a81d8bdea945c266515dff70fb06ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2020-04-24T10:23:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-24T14:25:55.000Z", "max_issues_repo_path": "julia/lorentz_param_fit.jl", "max_issues_repo_name": "khannay/FittingParamsDiffEqFlux", "max_issues_repo_head_hexsha": "19cf5691b5a81d8bdea945c266515dff70fb06ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-05-16T12:49:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-16T12:49:02.000Z", "max_forks_repo_path": "julia/lorentz_param_fit.jl", "max_forks_repo_name": "khannay/FittingParamsDiffEqFlux", "max_forks_repo_head_hexsha": "19cf5691b5a81d8bdea945c266515dff70fb06ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-04T00:28:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-04T00:28:43.000Z", "avg_line_length": 27.0303030303, "max_line_length": 131, "alphanum_fraction": 0.6760089686, "num_tokens": 987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012655937034, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.8094650944840183}} {"text": "function factorial4(n)\n if n == 0\n return BigInt(1)\n else\n return n * factorial4(n-1)\n end\nend\n\nnCr :: Int16 -> Int16 -> BigInt\nfunction nCr(n, r)\n return BigInt(factorial4(n)/(factorial4(n-r) * factorial4(r)))\nend\n\nget_draw :: Int16 -> Float64 -> Int16 -> Float64\nget_draw(n, p, x) = Float64(nCr(n, x) * p^x * (1-p)^(n-x))\nprintln(nCr(100, 10))\nprintln(get_draw(5, 1/2, 1))\n\nfunction binomial_rv2(n, p)\n m = 0\n for i in range(1, n)\n if p < rand()\n m += 1\n end\n end\n return m\nend\n\nfunction binomial_rv3(n, p)\n rands = [rand() for i in range(1, n)]\n return length(rands[rands. length(filter(x -> x < p, [rand() for i in range(1, n)]))\n#binomial_rv3 = (n, p) -> sum(filter(_ -> 1/2 < rand(), [1]*n))\n#println(binomial(5, 2))\n#println(filter(prob(1/2), [1, 1]))\n#println(binomial_rv2(5, 1/2))\n#println(binomial_rv3(5, 1/2))\nprintln(binomial_rv4(5, 1/2))\n", "meta": {"hexsha": "e96062614114d8a4e486588853c11ae563b8bb3b", "size": 912, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/jl0502/test7.jl", "max_stars_repo_name": "nswa17/Mn", "max_stars_repo_head_hexsha": "8dee1a35f798dc05ec50076ed7c43d0253993019", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Julia/jl0502/test7.jl", "max_issues_repo_name": "nswa17/Mn", "max_issues_repo_head_hexsha": "8dee1a35f798dc05ec50076ed7c43d0253993019", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Julia/jl0502/test7.jl", "max_forks_repo_name": "nswa17/Mn", "max_forks_repo_head_hexsha": "8dee1a35f798dc05ec50076ed7c43d0253993019", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.243902439, "max_line_length": 82, "alphanum_fraction": 0.6085526316, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561721629777, "lm_q2_score": 0.8354835309589073, "lm_q1q2_score": 0.8094633757100556}} {"text": "# Equation 33 of https://www.mdpi.com/2227-7390/6/2/16/htm\n\n# Loaded Packages\nusing FdeSolver\nusing Plots\nusing SpecialFunctions\n\n# Parameters\ntSpan = [0, 5] # Time Span\ny0 = [1, 0.5, 0.3] # Initial values\nβ = [0.5, 0.2, 0.6] # Order of derivation\n\n# Definition of the System\nfunction F(t, y)\n\n F1 = 1 / sqrt(pi) * (((y[2] - 0.5) * (y[3] - 0.3))^(1 / 6) + t^(1 / 2))\n F2 = gamma(2.2) * (y[1] - 1)\n F3 = gamma(2.8) / gamma(2.2) * (y[2] - 0.5)\n\n return [F1, F2, F3]\n\nend\n\n\nfunction JF(t,y)\n # System equation\n J11 = 0\n J12 = (y[2]-0.5).^(-5/6).*(y[3]-0.3).^(1/6)/6/sqrt(pi)\n J13 = (y[2]-0.5).^(1/6).*(y[3]-0.3).^(-5/6)/6/sqrt(pi)\n J21 = gamma(2.2)\n J22 = 0\n J23 = 0\n J31 = 0\n J32 = gamma(2.8)/gamma(2.2)\n J33 = 0\n\n J = [J11 J12 J13\n J21 J22 J23\n J31 J32 J33]\n return J\nend\n\n# Numerical Solution\nt, Yapp = FDEsolver(F, tSpan, y0, β, nc = 5)\nt_J, Yapp_J = FDEsolver(F, tSpan, y0, β, JF = JF)\n\n# Plot\nplot(t, Yapp, linewidth = 5, title = \"Solution of system 33\",\n xaxis = \"Time (t)\", yaxis = \"y(t)\", label = \"Approximation\")\n# plot!(t_J, Yapp_J, linewidth = 5, ls= :dot, label = \"Approximation with Jacob\")\nplot!(t, t -> (t .+ 1), lw = 3, ls = :dash, color= \"red\", label = \"Exact solution\")\nplot!(t, t -> (t.^1.2 .+ 0.5), lw = 3, ls = :dash, color= \"cyan\", label = \"Exact solution\")\nplot!(t, t -> (t.^1.8 .+ 0.3), lw = 3, ls = :dash, color= \"black\" ,label = \"Exact solution\")\n", "meta": {"hexsha": "5bb8616d62a07806153eaafb280e1139925789d4", "size": 1460, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/fDE3D.jl", "max_stars_repo_name": "FDE-Solver/FDE_Solver", "max_stars_repo_head_hexsha": "f0f06cff60d8bccbb61c588e0aba9df3bc4dd961", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-10-01T00:17:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T09:21:11.000Z", "max_issues_repo_path": "examples/fDE3D.jl", "max_issues_repo_name": "FDE-Solver/FDE_Solver", "max_issues_repo_head_hexsha": "f0f06cff60d8bccbb61c588e0aba9df3bc4dd961", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 26, "max_issues_repo_issues_event_min_datetime": "2021-09-13T10:53:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T08:00:50.000Z", "max_forks_repo_path": "examples/fDE3D.jl", "max_forks_repo_name": "JuliaTurkuDataScience/FdeSolver.jl", "max_forks_repo_head_hexsha": "f0f06cff60d8bccbb61c588e0aba9df3bc4dd961", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-11T07:13:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-11T07:13:47.000Z", "avg_line_length": 27.037037037, "max_line_length": 92, "alphanum_fraction": 0.5301369863, "num_tokens": 654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072387, "lm_q2_score": 0.882427872638409, "lm_q1q2_score": 0.8094534384536958}} {"text": "import FractionalTimeDG\nusing Printf\nusing ArgCheck\n\nsample = [1, 2, 10, 100, 1000]\nα = 3/4\nrmax = 6\nMmax = 2rmax\nstore = FractionalTimeDG.Store(α, rmax, Mmax)\nversion = 2\n\nfunction coef_uniform(sample, r, α, M, version)\n Ns = length(sample) \n H_sample = Matrix{Matrix{Float64}}(undef, Ns, M)\n N = maximum(sample) + 1\n for m = 1:M\n H = FractionalTimeDG.coef_H_uniform!(r, N, m, store, version)\n for n = 1:Ns\n H_sample[n, m] = H[sample[n]][:,:]\n end\n end\n return H_sample\nend\n\nfunction latex_display(A::Matrix{Float64})\n m, n = size(A)\n maxsz = maximum(abs.(A))\n p = min(0, ceil(Integer, log10(maxsz)))\n @printf(\"10^{%0d}\\n\", p)\n for i = 1:m\n for j = 1:n-1\n @printf(\"%8.5f & \", 10.0^(-p) * A[i,j])\n end\n if i < m\n @printf(\"%8.5f\\\\\\\\\\n\", 10.0^(-p) * A[i,n])\n else\n @printf(\"%8.5f\\n\", 10.0^(-p) * A[i,n])\n end\n end\nend\n\nH0 = FractionalTimeDG.coef_H0_uniform!(rmax, store)\nprintln(\"H_0:\")\nlatex_display(H0)\nHs = coef_uniform(sample, rmax, α, Mmax, version)\nfor n = 1:length(sample)\n ℓ = sample[n]\n println(\"H_$ℓ:\")\n latex_display(Hs[n,Mmax])\nend\n\nfunction pts_needed(Hs, sample, rmax, α, atol)\n Ns, M = size(Hs)\n @argcheck length(sample) == Ns\n first_M = fill(-1, rmax, Ns)\n err = zeros(rmax, M)\n for n = 1:Ns\n ℓ = sample[n]\n for m = 1:M-1\n ΔH = Hs[n,m] - Hs[n,M]\n for r = 1:rmax\n err[r,m] = maximum(abs.(ΔH[1:r,1:r]))\n end\n end\n for r = 1:rmax\n for m = 1:M-1\n if abs(err[r,m]) < atol\n first_M[r,n] = m\n break\n end\n end\n end\n end\n return first_M\nend\n\natol = 1e-14\nprintln(\"\\nQuadrature points needed using version = \", version)\nfirst_M = pts_needed(Hs, sample, rmax, α, atol)\n@printf(\"%4s\", \"r\")\nfor ℓ in sample\n @printf(\" ℓ=%4d\", ℓ)\nend\n@printf(\"\\n\\n\")\nfor r = 1:rmax\n @printf(\"%3d&\", r)\n for n = 1:length(sample)\n @printf(\"%7d&\", first_M[r,n])\n end\n @printf(\"\\n\")\nend\n", "meta": {"hexsha": "94b8c211f0a5dd5ab01abb6a7c26e6815b8a1efc", "size": 2128, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/sec_6_1.jl", "max_stars_repo_name": "billmclean/FractionalTimeDG.jl", "max_stars_repo_head_hexsha": "165bd96ac1355befaed4dff25172cc255e883768", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/sec_6_1.jl", "max_issues_repo_name": "billmclean/FractionalTimeDG.jl", "max_issues_repo_head_hexsha": "165bd96ac1355befaed4dff25172cc255e883768", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/sec_6_1.jl", "max_forks_repo_name": "billmclean/FractionalTimeDG.jl", "max_forks_repo_head_hexsha": "165bd96ac1355befaed4dff25172cc255e883768", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1304347826, "max_line_length": 69, "alphanum_fraction": 0.5164473684, "num_tokens": 758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072386, "lm_q2_score": 0.8824278680004707, "lm_q1q2_score": 0.8094534341993025}} {"text": "\"\"\"\n create_fibonacci_sphere(npoint)\n\nCreate `npoint` evenly distributed points on the sphere.\n\"\"\"\nfunction create_fibonacci_sphere(npoint)\n φ = (1 + √5) / 2\n inds = collect(0:npoint-1)'\n θ = 2π / φ * inds\n ϕ = acos.(1 .- 2 .* (inds .+ 0.5) ./ npoint)\n\n # Create Fibonacci directions (uniformly distributed on unit sphere)\n [\n cos.(θ) .* sin.(ϕ)\n sin.(θ) .* sin.(ϕ)\n cos.(ϕ)\n ]\nend\n", "meta": {"hexsha": "838db1cca65dbc3530523621f5f19e1804abf195", "size": 427, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/geometry/create_fibonacci_sphere.jl", "max_stars_repo_name": "fachra/SpinDoctor.jl", "max_stars_repo_head_hexsha": "25c633fb8020843728c1004c492a7c33b2fe2e4f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2022-03-19T12:53:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T22:39:38.000Z", "max_issues_repo_path": "src/geometry/create_fibonacci_sphere.jl", "max_issues_repo_name": "fachra/SpinDoctor.jl", "max_issues_repo_head_hexsha": "25c633fb8020843728c1004c492a7c33b2fe2e4f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2022-03-13T19:49:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T14:58:15.000Z", "max_forks_repo_path": "src/geometry/create_fibonacci_sphere.jl", "max_forks_repo_name": "fachra/SpinDoctor.jl", "max_forks_repo_head_hexsha": "25c633fb8020843728c1004c492a7c33b2fe2e4f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-11-11T09:54:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T11:10:57.000Z", "avg_line_length": 22.4736842105, "max_line_length": 72, "alphanum_fraction": 0.5667447307, "num_tokens": 141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9615338046748207, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.8094438231981763}} {"text": "\n# [function](https://docs.julialang.org/en/v1/manual/functions/#man-functions-1) to calculate the volume of a sphere\nfunction sphere_vol(r)\n # julia allows [Unicode names](https://docs.julialang.org/en/v1/manual/unicode-input/#Unicode-Input-1) (in UTF-8 encoding)\n # so either \"pi\" or the symbol π can be used\n return 4/3*pi*r^3\nend\n\n# functions can also be defined more succinctly\nquadratic(a, sqr_term, b) = (-b + sqr_term) / 2a\n\n# calculates x for 0 = a*x^2+b*x+c, [arguments types](https://docs.julialang.org/en/v1/manual/functions/#Further-Reading-1) can be defined in function definitions\nfunction quadratic2(a::Float64, b::Float64, c::Float64)\n # unlike other languages 2a is equivalent to 2*a\n # a^2 is used instead of a**2 or pow(a,2)\n sqr_term = sqrt(b^2-4a*c)\n r1 = quadratic(a, sqr_term, b)\n r2 = quadratic(a, -sqr_term, b)\n # multiple values can be returned from a function using tuples\n # if the [return](https://docs.julialang.org/en/v1/manual/functions/#The-return-Keyword-1) keyword is omitted, the last term is returned\n r1, r2\nend\n\nvol = sphere_vol(3)\n# @printf allows number formatting but does not automatically append the \\n to statements, see below\nusing Printf\n@printf \"volume = %0.3f\\n\" vol \n#> 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\n", "meta": {"hexsha": "c318ad6e8fbf9b6bb02d5dc3409478296d76338e", "size": 1409, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions.jl", "max_stars_repo_name": "talgatomarov/JuliaByExample", "max_stars_repo_head_hexsha": "9fc5516b7f6d03bd2f340b7a9bb52a06fedb7458", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 281, "max_stars_repo_stars_event_min_datetime": "2015-02-01T01:18:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T19:51:35.000Z", "max_issues_repo_path": "src/functions.jl", "max_issues_repo_name": "talgatomarov/JuliaByExample", "max_issues_repo_head_hexsha": "9fc5516b7f6d03bd2f340b7a9bb52a06fedb7458", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2015-04-10T04:23:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T12:32:59.000Z", "max_forks_repo_path": "src/functions.jl", "max_forks_repo_name": "talgatomarov/JuliaByExample", "max_forks_repo_head_hexsha": "9fc5516b7f6d03bd2f340b7a9bb52a06fedb7458", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 101, "max_forks_repo_forks_event_min_datetime": "2015-03-24T20:45:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T23:24:46.000Z", "avg_line_length": 40.2571428571, "max_line_length": 162, "alphanum_fraction": 0.7012065295, "num_tokens": 448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898229217591, "lm_q2_score": 0.8933094025038598, "lm_q1q2_score": 0.8093292273888144}} {"text": "using Statistics\n\n\"\"\"\nCalculate the autocorrelation of `data` at the given distance `dist`\n\"\"\"\nfunction autocorrelation(data::Vector{<:Real}, dist::Integer)\n xᵢ = data[1:(length(data) - dist)]\n xᵢ₊ⱼ = data[(1 + dist):end]\n xᵢxᵢ₊ⱼavg = mean(xᵢ .* xᵢ₊ⱼ)\n return (xᵢxᵢ₊ⱼavg - mean(xᵢ) * mean(xᵢ₊ⱼ)) / var(data)\nend\n", "meta": {"hexsha": "a21cdd5235f29b61329c4da85b581057630bed11", "size": 324, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "exam/autocorrelation.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": "exam/autocorrelation.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": "exam/autocorrelation.jl", "max_forks_repo_name": "slhshamloo/comp-phys", "max_forks_repo_head_hexsha": "04d6759e0eb9d7e16e2781417d389bc15e22b01b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0, "max_line_length": 68, "alphanum_fraction": 0.6419753086, "num_tokens": 146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.963779946215714, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.809318752400335}} {"text": "import LinearAlgebra: norm\n\n\"\"\" Gradient descent for multidimensional functions Stops when the gradient is smaller than `TOL`,\n or when the maximum number of iterations `maxiter` has been reached\"\"\"\nfunction gradient_descent(f, Df, x; α = 0.1, TOL = 1e-10, maxiter = 1000, verbose = false)\n N_iter = 0\n grad = Df(x)\n\n xn = x\n fn = [f(x)]\n while (N_iter < maxiter) & (norm(grad) > TOL)\n x = x - α*grad\n\n xn = [xn x]\n fn = [fn f(x)]\n\n grad = Df(x)\n N_iter += 1\n\n if (N_iter % 100 == 0) & (verbose == true)# print progress\n fx = fn[end]\n println(\"Iter. $N_iter,\\tx = $x,\\tf(x) = $fx\")\n end\n end\n\n return (xn', reshape(fn,:)) # to have the components in the columns\nend\n", "meta": {"hexsha": "9272d08cec590e8486200b32d31212c8a56860d0", "size": 761, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "GradientDescent.jl", "max_stars_repo_name": "ismedina/julia-scientific-computing", "max_stars_repo_head_hexsha": "a29ebdfffc22b98c10ce61e1676e55b5f37c405c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GradientDescent.jl", "max_issues_repo_name": "ismedina/julia-scientific-computing", "max_issues_repo_head_hexsha": "a29ebdfffc22b98c10ce61e1676e55b5f37c405c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GradientDescent.jl", "max_forks_repo_name": "ismedina/julia-scientific-computing", "max_forks_repo_head_hexsha": "a29ebdfffc22b98c10ce61e1676e55b5f37c405c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-28T10:34:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-28T10:34:39.000Z", "avg_line_length": 27.1785714286, "max_line_length": 98, "alphanum_fraction": 0.5584756899, "num_tokens": 235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9353465188527684, "lm_q2_score": 0.8652240686758841, "lm_q1q2_score": 0.8092843206636168}} {"text": "\"\"\"\nInner product (element-wise product) between two matrices\n\"\"\"\nfunction innerprod(A::AbstractMatrix{Float64},B::AbstractMatrix{Float64})::Float64\n if size(A) != size(B)\n throw(DimensionMismatch(\"size of A not equal to size of B\"))\n end\n return sum(A.*B)/size(A)[1]\nend\n\n\"\"\"\nReturn a copy of the off-diagonal part of matrix\n\"\"\"\nfunction get_offdiag(A::AbstractMatrix{Float64})::AbstractMatrix{Float64}\n return A-Diagonal(A)\nend\n\n\"\"\"\nCreate center finite difference matrix\n\"\"\"\nfunction get_cfd_mat(ord::Int,n::Int)::SparseMatrixCSC{Float64,Int}\n if ord == 2\n arr = circshift(vcat(Vector{Float64}([1,-2,1]),zeros(Float64,n-3)),-1)\n elseif ord == 4\n arr = circshift(vcat(Vector{Float64}([-1/12,4/3,-5/2,4/3,-1/12]),zeros(Float64,n-5)),-2)\n elseif ord == 8\n arr = circshift(vcat(Vector{Float64}([1/90,-3/20,3/2,-49/18,3/2,-3/20,1/90]),zeros(Float64,n-7)),-3)\n else\n throw(\"unimplemented\")\n end\n\n A = Matrix{Float64}(undef,n,n)\n for i in 1:n\n A[i,:] = arr\n arr = circshift(arr,1)\n end\n\n return A\nend\n\nfunction get_stagger_grids(ord::Int,n::Int,a::Vector{Float64})::Matrix{Float64}\n if length(a) != n\n throw(\"size of vector a not equal to n\")\n end\n\n if ord == 2\n coefs = Float64[ 1 0;\n -1 -1;\n 0 1;]\n\n h = 1.0/n\n A = zeros(Float64,n,n)\n\n for i in 1:n\n arr = circshift(a,2-i)[1:2]\n A[i,:] = circshift(vcat(coefs*arr,zeros(Float64,n-3)),i-2)\n end \n\n elseif ord == 4 \n coefs = Float64[ 1/576 0 0 0;\n -3/64 -3/64 0 0;\n 3/64 81/64 3/64 0;\n -1/576 -81/64 -81/64 -1/576;\n 0 3/64 81/64 3/64;\n 0 0 -3/64 -3/64;\n 0 0 0 1/576;]\n\n h = 1.0/n\n A = zeros(Float64,n,n)\n\n for i in 1:n\n arr = circshift(a,3-i)[1:4]\n A[i,:] = circshift(vcat(coefs*arr,zeros(Float64,n-7)),i-4)\n end \n\n elseif ord == 6\n coefs = Float64[ 9/409600 0 0 0 0 0;\n -5/16384 -5/16384 0 0 0 0;\n 45/8192 625/147456 45/8192 0 0 0;\n -45/8192 -625/8192 -625/8192 -45/8192 0 0;\n 5/16384 625/8192 5625/4096 625/8192 5/16384 0;\n -9/409600 -625/147456 -5625/4096 -5625/4096 -625/147456 -9/409600;\n 0 5/16384 625/8192 5625/4096 625/8192 5/16384;\n 0 0 -45/8192 -625/8192 -625/8192 -45/8192;\n 0 0 0 45/8192 625/147456 45/8192;\n 0 0 0 0 -5/16384 -5/16384;\n 0 0 0 0 0 9/409600;]\n\n h = 1.0/n\n A = zeros(Float64,n,n)\n\n for i in 1:n\n arr = circshift(a,4-i)[1:6]\n A[i,:] = circshift(vcat(coefs*arr,zeros(Float64,n-11)),i-6)\n end \n else\n throw(\"unimplemented\")\n end\n return A\nend\n\n\"\"\"\nCheck if a matrix is strictly diagonally dominant\n\"\"\"\nfunction is_diagally_dominant(A::AbstractMatrix{Float64})\n diff = abs.(diag(A)).-collect(Iterators.flatten(sum(abs.(get_offdiag(A)),dims=1)))\n return minimum(diff)\nend\n\n\n\"\"\"\nGet 2D meshgrid\n\"\"\"\nfunction meshgrid(x,y)\n return (reshape(repeat(x,outer=length(y)),(length(x),length(y))),\n reshape(repeat(y,inner=length(x)),(length(x),length(y))))\nend\n\n\n\"\"\"\nGet index for repartition of girds \n\"\"\"\nfunction get_repartiton_index(n::Int)::Vector{Int}\n idx = transpose(reshape(collect([1:n*n;]),(n,n)))\n return vcat(collect(Iterators.flatten(idx[1:n÷2,1:n÷2])),\n collect(Iterators.flatten(idx[n÷2+1:n,1:n÷2])),\n collect(Iterators.flatten(idx[1:n÷2,n÷2+1:n])),\n collect(Iterators.flatten(idx[n÷2+1:n,n÷2+1:n]))\n )\nend", "meta": {"hexsha": "ba72529c923c6e0ae3c50ca46a1e292b7e442b84", "size": 4245, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "xinshuoyang/FactNSF", "max_stars_repo_head_hexsha": "8db187ac45bd598e0aa6640af3f0bb07a58b0154", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "xinshuoyang/FactNSF", "max_issues_repo_head_hexsha": "8db187ac45bd598e0aa6640af3f0bb07a58b0154", "max_issues_repo_licenses": ["MIT"], "max_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": "xinshuoyang/FactNSF", "max_forks_repo_head_hexsha": "8db187ac45bd598e0aa6640af3f0bb07a58b0154", "max_forks_repo_licenses": ["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.6538461538, "max_line_length": 108, "alphanum_fraction": 0.4791519435, "num_tokens": 1370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625050654263, "lm_q2_score": 0.8688267881258485, "lm_q1q2_score": 0.8092795765356512}} {"text": "# ---\n# jupyter:\n# jupytext:\n# formats: ipynb,jl:hydrogen\n# text_representation:\n# extension: .jl\n# format_name: hydrogen\n# format_version: '1.3'\n# jupytext_version: 1.11.2\n# kernelspec:\n# display_name: Julia 1.8.0-DEV\n# language: julia\n# name: julia-1.8\n# ---\n\n# %%\nusing ForwardDiff\nusing Plots\n\nf(x, y) = exp(-(x^2 + y^2))\nu(x, y) = -ForwardDiff.derivative(Base.Fix2(f, y), x) # = f_x(x, y)\nv(x, y) = -ForwardDiff.derivative(Base.Fix1(f, x), y) # = f_y(x, y)\n\nxlim = (-1.7, 1.7)\nylim = (-1.7, 1.7)\nxs = range(xlim...; length=200)\nys = range(ylim...; length=200)\n\nc = 0.5\nx = range(-1.5, 1.5; length=11)\ny = range(-1.5, 1.5; length=11)\nX, Y = reim(complex.(x', y)) # meshgrid\nU, V = c*u.(x', y), c*v.(x', y)\n\nheatmap(xs, ys, f)\nquiver!(vec(X-U/2), vec(Y-V/2); quiver=(vec(U), vec(V)), color=:cyan)\nplot!(; xlim, ylim, size=(450, 400))\n\n# %%\nusing ForwardDiff\nusing Plots\n\nf(x, y) = y * exp(-(x^2 + y^2))\nu(x, y) = -ForwardDiff.derivative(Base.Fix2(f, y), x) # = f_x(x, y)\nv(x, y) = -ForwardDiff.derivative(Base.Fix1(f, x), y) # = f_y(x, y)\n\nxlim = (-2.2, 2.2)\nylim = (-2.2, 2.2)\nxs = range(xlim...; length=200)\nys = range(ylim...; length=200)\n\nc = 0.5\nx = range(-2.0, 2.0; length=13)\ny = range(-2.0, 2.0; length=13)\nX, Y = reim(complex.(x', y)) # meshgrid\nU, V = c*u.(x', y), c*v.(x', y)\n\nheatmap(xs, ys, f)\nquiver!(vec(X-U/2), vec(Y-V/2); quiver=(vec(U), vec(V)), color=:cyan)\nplot!(; xlim, ylim, size=(450, 400))\n\n# %%\n", "meta": {"hexsha": "4ce6ca3df092aa5da80ac5bbd529115446c176ec", "size": 1471, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "0015/Pkg/heatmap and quiver example.jl", "max_stars_repo_name": "genkuroki/public", "max_stars_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-06-06T00:33:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T06:56:08.000Z", "max_issues_repo_path": "0015/Pkg/heatmap and quiver example.jl", "max_issues_repo_name": "genkuroki/public", "max_issues_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "0015/Pkg/heatmap and quiver example.jl", "max_forks_repo_name": "genkuroki/public", "max_forks_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-08-02T11:58:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T11:46:05.000Z", "avg_line_length": 23.3492063492, "max_line_length": 69, "alphanum_fraction": 0.5560842964, "num_tokens": 621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680097, "lm_q2_score": 0.8688267830311354, "lm_q1q2_score": 0.8092795734431324}} {"text": "### A Pluto.jl notebook ###\n# v0.11.14\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 006a6698-f9dd-11ea-3f64-152c31c749ef\nusing Pkg, DrWatson\n\n# ╔═╡ 0090af24-f9dd-11ea-0eb4-eb1758ba5442\nbegin\n\tusing Distributions\n\tusing StatsPlots, Plots\n\tusing Turing\n\tusing Logging\n\tusing LaTeXStrings\nnd\n\n# ╔═╡ 9453eb8e-f9dc-11ea-1865-f168816cdb46\nmd\"## Clip-02-06-07.jl\"\n\n# ╔═╡ 009dc1c8-f9dd-11ea-193f-3f1baf487786\nmd\"## snippet 2.6\"\n\n# ╔═╡ 009f1ad2-f9dd-11ea-2abc-0579fc5057d2\n@model globethrowing(w, l) = begin\n p ~ Uniform(0, 1)\n w ~ Binomial(w + l, p)\nend\n\n# ╔═╡ 00a7e61c-f9dd-11ea-028c-ddfdbdd620cb\nm = globethrowing(6, 3);\n\n# ╔═╡ 00a87104-f9dd-11ea-2ef2-bf5a7c31c607\nr = quap(m)\n\n# ╔═╡ ea69e428-f9e0-11ea-0c97-e3b70306a220\nbegin\n\tp_grid = range(0, 1, length = 20)\n\tprior = ones(20)\n\tlikelihood = pdf.(Binomial.(9, p_grid), 6)\n\tposterior = likelihood .* prior\n\tposterior ./= sum(posterior)\n\t\n\tx = 0:0.01:1\n\tw = 6\n\tl = 3\n\t\n\tf = plot( x, pdf.(Normal(mean(r.coef.p), √r.vcov[1]), x ), lab=\"quap\")\n\tplot!( x, pdf.(Beta( w+1 , l+1 ) , x ), lab=\"exact\", leg=:topleft, title=\"n = $(w+l)\")\nend\n\n# ╔═╡ 00dd7c78-f9dd-11ea-29ee-b9fb0b25bd56\nmd\"## End clip-02-06-07t.jl\"\n\n# ╔═╡ Cell order:\n# ╟─9453eb8e-f9dc-11ea-1865-f168816cdb46\n# ╠═006a6698-f9dd-11ea-3f64-152c31c749ef\n# ╠═0090af24-f9dd-11ea-0eb4-eb1758ba5442\n# ╟─009dc1c8-f9dd-11ea-193f-3f1baf487786\n# ╠═009f1ad2-f9dd-11ea-2abc-0579fc5057d2\n# ╠═00a7e61c-f9dd-11ea-028c-ddfdbdd620cb\n# ╠═00a87104-f9dd-11ea-2ef2-bf5a7c31c607\n# ╠═ea69e428-f9e0-11ea-0c97-e3b70306a220\n# ╟─00dd7c78-f9dd-11ea-29ee-b9fb0b25bd56\n", "meta": {"hexsha": "357182b9c393087223ec747f429c44eeb23e9006", "size": 1545, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/02/clip-02-06-07t.jl", "max_stars_repo_name": "kertase/StatisticalRethinkingTuring.jl", "max_stars_repo_head_hexsha": "dd472f224590a3c8466a7a3ecb519f004906d369", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 63, "max_stars_repo_stars_event_min_datetime": "2020-10-01T23:35:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T11:48:45.000Z", "max_issues_repo_path": "notebooks/02/clip-02-06-07t.jl", "max_issues_repo_name": "kertase/StatisticalRethinkingTuring.jl", "max_issues_repo_head_hexsha": "dd472f224590a3c8466a7a3ecb519f004906d369", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-11-24T21:59:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T12:34:49.000Z", "max_forks_repo_path": "notebooks/02/clip-02-06-07t.jl", "max_forks_repo_name": "kertase/StatisticalRethinkingTuring.jl", "max_forks_repo_head_hexsha": "dd472f224590a3c8466a7a3ecb519f004906d369", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2020-11-30T18:25:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-25T06:59:27.000Z", "avg_line_length": 23.4090909091, "max_line_length": 87, "alphanum_fraction": 0.68802589, "num_tokens": 801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9314624993576758, "lm_q2_score": 0.8688267813328976, "lm_q1q2_score": 0.8092795652492256}} {"text": "\nmodule HyperbolicDrawSimpleGraphs\n\nusing SimpleGraphs, HyperbolicPlane, SimpleDrawing\n\nimport Base: show\nimport HyperbolicPlane: polar\n\nexport HyperbolicGraphEmbedding, hdraw, hembed\n\nmutable struct HyperbolicGraphEmbedding\n G::SimpleGraph\n locs::Dict{Any,HPoint}\nend\n\nfunction show(io::IO, X::HyperbolicGraphEmbedding)\n print(io, \"Hyperbolic embedding of $(X.G)\")\nend\n\npolar(x::Real,y::Real) = (sqrt(x*x+y*y), atan(x,y) )\n\n# convert SimpleGraph to Hyperbolic embedding\nfunction h_convert(GG::SimpleGraph)::HyperbolicGraphEmbedding\n loc = getxy(GG)\n d = Dict{Any,HPoint}()\n\n for v in GG.V\n xy = loc[v]\n (r,theta) = polar(xy[1],xy[2])\n P = HPoint(r,theta)\n d[v] = P\n end\n return HyperbolicGraphEmbedding(GG,d)\nend\n\nfunction h_circular(GG::SimpleGraph)::HyperbolicGraphEmbedding\n n = NV(GG)\n VV = vlist(GG)\n r = sqrt(n)\n angs = [2*pi*t/n for t=0:n-1]\n d = Dict{Any,HPoint}()\n for j=1:n\n v = VV[j]\n P = HPoint(r,angs[j])\n d[v] = P\n end\n return HyperbolicGraphEmbedding(GG,d)\nend\n\nfunction h_random(G::SimpleGraph)::HyperbolicGraphEmbedding\n d = Dict{Any,HPoint}()\n for v in G.V\n d[v] = RandomHPoint()\n end\n return HyperbolicGraphEmbedding(G,d)\nend\n\nfunction private_adj(G::SimpleGraph)\n n = NV(G)\n A = zeros(Int,n,n)\n vv = vlist(G)\n for i=1:n-1\n u = vv[i]\n for j=(i+1):n\n w = vv[j]\n if has(G,u,w)\n A[i,j] = 1\n A[j,i] = 1\n end\n end\n end\n return A,vv\nend\n\ninclude(\"myspring.jl\")\n\n\"\"\"\n`spring!(X)` gives the graph held in `X` with a spring embedding\n(based on code in the `GraphLayout` module). If runs a default number of\niterations (100) of that algorithm. To change the number of\niterations, use `spring!(X,nits)`.\n\"\"\"\nfunction h_spring(G::SimpleGraph, nits::Int=100)::HyperbolicGraphEmbedding\n GG = deepcopy(G)\n embed(GG,:spring)\n X = h_convert(GG)\n n = NV(GG)\n locs_r = zeros(n)\n angs = zeros(n)\n i = 1\n for v in G.V\n xy = X.locs[v]\n (r,theta) = polar(xy)\n locs_r[i] = r\n angs[i] = theta\n i = i + 1\n end\n n = NV(G)\n A,vv = private_adj(G)\n\n locs_r, angs = h_layout_spring_adj(locs_r,angs,A,MAXITER=nits)\n\n d = Dict{Any,HPoint}()\n for i = 1:n\n v = vv[i]\n P = HPoint(locs_r[i],angs[i])\n d[v] = P\n end\n\n return HyperbolicGraphEmbedding(G,d)\nend\n\n\"\"\"\n`hembed(G,method)` embeds `G` in the hyperbolic plane by placing vertices\naround a circle.\n\nOptions for `method`:\n+ `:circular` places vertices around a circle\n+ `:random` places vertices at random\n+ `:convert` converts the Euclidean embedding of `G` into a hyperbolic embedding\n\"\"\"\nfunction hembed(G::SimpleGraph, method::Symbol = :circular)\n\n if method == :circular\n X = h_circular(G)\n elseif method == :random\n X = h_random(G)\n elseif method == :convert\n X = h_convert(G)\n elseif method == :spring\n X = h_spring(G)\n else\n error(\"Unknown method $method\")\n end\n cache_save(G,:HyperbolicGraphEmbedding,X)\nend\n\n\"\"\"\n`hdraw(G)` draws the graph `G` in its current hyperoblic embedding\n(or creates a default, circular embedding if need be).\n\"\"\"\nfunction hdraw(G::SimpleGraph)\n if !cache_check(G,:HyperbolicGraphEmbedding)\n hembed(G)\n end\n X = cache_recall(G,:HyperbolicGraphEmbedding)\n newdraw()\n for e in G.E\n u,v = e\n A = X.locs[u]\n B = X.locs[v]\n draw(A+B)\n end\n for v in G.V\n A = X.locs[v]\n A = HPoint(A)\n set_radius(A,2)\n draw(A)\n end\n # draw(HPlane()) # let the user decide to show the line at infinity\n finish()\nend\n\nend # end of module\n", "meta": {"hexsha": "f3f4e7041a57549714f8efe6162b6e75b744c8db", "size": 3757, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/HyperbolicDrawSimpleGraphs.jl", "max_stars_repo_name": "scheinerman/HyperbolicDrawSimpleGraphs.jl", "max_stars_repo_head_hexsha": "646c5153b91dffb9f4e5584c450038253bdbfe9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/HyperbolicDrawSimpleGraphs.jl", "max_issues_repo_name": "scheinerman/HyperbolicDrawSimpleGraphs.jl", "max_issues_repo_head_hexsha": "646c5153b91dffb9f4e5584c450038253bdbfe9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/HyperbolicDrawSimpleGraphs.jl", "max_forks_repo_name": "scheinerman/HyperbolicDrawSimpleGraphs.jl", "max_forks_repo_head_hexsha": "646c5153b91dffb9f4e5584c450038253bdbfe9c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.7696969697, "max_line_length": 80, "alphanum_fraction": 0.6039393133, "num_tokens": 1165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625012602594, "lm_q2_score": 0.8688267677469952, "lm_q1q2_score": 0.8092795542474827}} {"text": "\"\"\"\n tensordecomp(k::Int, d::Int)\n\nDecomposition of the integers 0:(k^p - 1) in powers of k.\n\n\n\"\"\"\nfunction tensordecomp(k::Int, d::Int)\n\n sequences = zeros(Int, k^d, d)\n\n for n = 0:k^d-1\n i = d\n m = n\n\n while i > 0\n i = i - 1\n j = i\n f = floor(Int, m / k^i)\n\n while j > 0 && f == 0\n j = j - 1\n f = floor(Integer, m / k^j)\n end\n\n if f > 0\n sequences[n + 1, j + 1] = f\n i = j\n elseif f == 0\n sequences[n + 1, 1] = m\n i = 0\n end\n m = m - f * k^i\n end\n end\n\n return sequences\nend\n\n\n\"\"\"\n even_sampling_rules(dim::Int, split_factor::Int) -> Array{Float64, 2}\n\nGenerate rules for evenly distributed points within a simplex. To do this,\nwe perform a shape-preserving splitting of the simplex, given a splitting\nfactor.\n\nReturns the convex expansion coefficients of the points of the resulting\nsubsimplices in terms of the vertices of the original simplex.\n\"\"\"\nfunction even_sampling_rules(dim::Int, split_factor::Int)\n\n sequences::Array{Int, 2} = tensordecomp(split_factor, dim)\n n_seq = size(sequences, 1)\n\n χ1 = sequences .* (dim + 1)\n χ2 = repeat(transpose(collect(1:dim)), n_seq, 1)\n χ::Array{Int, 2} = χ1 .+ χ2\n χ = sort(χ, dims=2)\n\n # Define multiplicity matrix M\n M = zeros(Float64, size(χ, 1), size(χ, 2) + 1)\n M[:, 1] = χ[:, 1]\n M[:, 2:(end - 1)] = χ[:, 2:end] - χ[:, 1:(end - 1)]\n M[:, end] = (dim+1)*split_factor * ones(size(χ, 1)) - χ[:, end]\n\n M = M ./ (split_factor * (dim + 1))\n\n return copy(transpose(M))\nend\n\n\"\"\"\nEvenly sample points within a simplex by performing a shape-preserving\nsubdivision of the simplex with a given `split_factor`. If the simplex\nlives in a space of dimension `dim`, the resulting number of points is\n`split_factor`^(dim).\n\"\"\"\nfunction evenly_sample(simplex::AbstractArray{Float64, 2}, split_factor::Int)\n dim = size(simplex, 2)\n centroids_exp_coeffs = copy(transpose(even_sampling_rules(dim, split_factor)))\n centroids_exp_coeffs * simplex\nend\n", "meta": {"hexsha": "14d8708975692c199993059a716bc8b103ceab8b", "size": 2164, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/even_sampling.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/Simplices.jl-d5428e67-3037-59ba-9ab1-57a04f0a3b6a", "max_stars_repo_head_hexsha": "c5651f0aa8e45bd196fc6816e3e47f01d2f1764b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-10-08T00:07:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-08T00:07:46.000Z", "max_issues_repo_path": "src/even_sampling.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/Simplices.jl-d5428e67-3037-59ba-9ab1-57a04f0a3b6a", "max_issues_repo_head_hexsha": "c5651f0aa8e45bd196fc6816e3e47f01d2f1764b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2018-04-04T02:26:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-29T15:46:04.000Z", "max_forks_repo_path": "src/even_sampling.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/Simplices.jl-d5428e67-3037-59ba-9ab1-57a04f0a3b6a", "max_forks_repo_head_hexsha": "c5651f0aa8e45bd196fc6816e3e47f01d2f1764b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-12-11T08:36:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:03:05.000Z", "avg_line_length": 26.0722891566, "max_line_length": 82, "alphanum_fraction": 0.5739371534, "num_tokens": 661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342012360932, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.8092574733796277}} {"text": "export Exp\n\n\"\"\"\n`Exp([domainType=Float64::Type,] dim_in::Tuple)`\n\nCreates the exponential non-linear operator with input dimensions `dim_in`:\n```math\ne^{ \\\\mathbf{x} }.\n```\n\n\"\"\"\nstruct Exp{T,N} <: NonLinearOperator\n\tdim::NTuple{N,Int}\nend\n\nfunction Exp(DomainType::Type, DomainDim::NTuple{N,Int}) where {N} \n\tExp{DomainType,N}(DomainDim)\nend\n\nExp(DomainDim::NTuple{N,Int}) where {N} = Exp{Float64,N}(DomainDim)\nExp(DomainDim::Vararg{Int}) = Exp{Float64,length(DomainDim)}(DomainDim)\n\nfunction mul!(y::AbstractArray{T,N}, L::Exp{T,N}, x::AbstractArray{T,N}) where {T,N}\n\ty .= exp.(x)\nend\n\nfunction mul!(y::AbstractArray, \n J::AdjointOperator{Jacobian{A,TT}}, \n b::AbstractArray) where {T,N, A<: Exp{T,N}, TT <: AbstractArray{T,N} }\n L = J.A\n y .= conj.(exp.(L.x)).*b\nend\n\nfun_name(L::Exp) = \"e\"\n\nsize(L::Exp) = (L.dim, L.dim)\n\ndomainType(L::Exp{T,N}) where {T,N} = T\ncodomainType(L::Exp{T,N}) where {T,N} = T\n", "meta": {"hexsha": "e85fa7b88f6c7b4189948b55763cb527c369213d", "size": 940, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nonlinearoperators/Exp.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/Exp.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/Exp.jl", "max_forks_repo_name": "nantonel/AbstractOperators.jl", "max_forks_repo_head_hexsha": "be58f4cfa0abb9bc4903ecebbb892a8e58c218aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2017-09-02T08:56:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-21T18:56:33.000Z", "avg_line_length": 23.5, "max_line_length": 84, "alphanum_fraction": 0.6361702128, "num_tokens": 321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342037088041, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.8092574717558768}} {"text": "###################################################################################\n# load dependencies\n###################################################################################\ncd(@__DIR__)\nusing Revise, DifferentialEvolutionMCMC, Random, Distributions\nRandom.seed!(50514)\n###################################################################################\n# define functions\n###################################################################################\n# returns prior log likelihood\nfunction prior_loglike(μ, σ)\n LL = 0.0\n LL += logpdf(Normal(0, 1), μ)\n LL += logpdf(truncated(Cauchy(0, 1), 0, Inf), σ)\n return LL\nend\n\n# function for initial values\nfunction sample_prior()\n μ = rand(Normal(0, 1))\n σ = rand(truncated(Cauchy(0, 1), 0, Inf))\n return [μ,σ]\nend\n\n# likelihood function \nfunction loglike(data, μ, σ)\n return sum(logpdf.(Normal(μ, σ), data))\nend\n###################################################################################\n# generate data\n###################################################################################\ndata = rand(Normal(0.0, 1.0), 50)\n###################################################################################\n# configure sampler\n###################################################################################\n# parameter names\nnames = (:μ,:σ)\n# parameter bounds\nbounds = ((-Inf,Inf),(0.0,Inf))\n\n# model object\nmodel = DEModel(; \n sample_prior, \n prior_loglike, \n loglike, \n data,\n names\n)\n\n# DEMCMC sampler object\nde = DE(;sample_prior, bounds, burnin = 1000, Np = 6)\n# number of interations per particle\nn_iter = 2000\n###################################################################################\n# estimate parameters\n###################################################################################\nchains = sample(model, de, MCMCThreads(), n_iter, progress=true)\n", "meta": {"hexsha": "e9f42b6cbe121393025b8c6ecf167132253121dd", "size": 2025, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/Gaussian_Example.jl", "max_stars_repo_name": "itsdfish/DifferentialEvolutionMCMC.jl", "max_stars_repo_head_hexsha": "3974509006e3df0eef74cf82be71586f2045d421", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2020-06-22T07:03:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T06:47:34.000Z", "max_issues_repo_path": "Examples/Gaussian_Example.jl", "max_issues_repo_name": "itsdfish/DifferentialEvolutionMCMC.jl", "max_issues_repo_head_hexsha": "3974509006e3df0eef74cf82be71586f2045d421", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 40, "max_issues_repo_issues_event_min_datetime": "2020-05-28T11:51:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T11:59:22.000Z", "max_forks_repo_path": "Examples/Gaussian_Example.jl", "max_forks_repo_name": "itsdfish/DifferentialEvolutionMCMC.jl", "max_forks_repo_head_hexsha": "3974509006e3df0eef74cf82be71586f2045d421", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9137931034, "max_line_length": 83, "alphanum_fraction": 0.3496296296, "num_tokens": 363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341975270266, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.8092574665264489}} {"text": "poisson(T, n) = sparse(Tridiagonal(fill(T(-1), n-1),\n fill(T(2), n), fill(T(-1), n-1)))\npoisson(n) = poisson(Float64, n)\n\nfunction stencil_grid(T,stencil,sz)\n # upper-bound for storage\n n = prod(sz) * sum(.!iszero,stencil)\n\n # indices and value of nonzero elements\n Si = zeros(Int,n)\n Sj = zeros(Int,n)\n Ss = zeros(T,n)\n\n linindices = LinearIndices(sz)\n nnz = 0\n\n stencil_sz = size(stencil)\n offset = CartesianIndex((stencil_sz .+ 1) .÷ 2)\n\n for i in CartesianIndices(sz)\n for k in CartesianIndices(stencil_sz)\n if stencil[k] != 0\n j = i + k - offset\n if checkbounds(Bool,linindices,j)\n nnz = nnz + 1\n Si[nnz] = linindices[i]\n Sj[nnz] = linindices[j]\n Ss[nnz] = stencil[k]\n end\n end\n end\n end\n\n sparse((@view Si[1:nnz]),\n (@view Sj[1:nnz]),\n (@view Ss[1:nnz]),\n prod(sz),prod(sz))\nend\n\n\n\nfunction poisson(T,sz::NTuple{N,Int}) where N\n #=\n In 2D stencil has the value:\n stencil = [0 -1 0;\n -1 4 -1;\n 0 -1 0]\n\n =#\n stencil = zeros(T,ntuple(i -> 3,Val(N)))\n for i = 0:N-1\n Ipre = CartesianIndex(ntuple(l -> 2,i))\n Ipost = CartesianIndex(ntuple(l -> 2,N-i-1))\n stencil[Ipre, 1, Ipost] = -1\n stencil[Ipre, 3, Ipost] = -1\n end\n Icenter = CartesianIndex(ntuple(l -> 2,Val(N)))\n stencil[Icenter] = 2*N\n\n stencil_grid(T,stencil,sz)\nend\n\npoisson(sz::NTuple{N,Int}) where N = poisson(Float64,sz)\n", "meta": {"hexsha": "be484b97914ac07a849f7b87b98319e5977fbb02", "size": 1628, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gallery.jl", "max_stars_repo_name": "Alexander-Barth/AlgebraicMultigrid.jl", "max_stars_repo_head_hexsha": "f6d0b497e359fbe6c406502cc89f382dd57b78f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 72, "max_stars_repo_stars_event_min_datetime": "2018-07-21T18:10:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T07:19:39.000Z", "max_issues_repo_path": "src/gallery.jl", "max_issues_repo_name": "Alexander-Barth/AlgebraicMultigrid.jl", "max_issues_repo_head_hexsha": "f6d0b497e359fbe6c406502cc89f382dd57b78f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 45, "max_issues_repo_issues_event_min_datetime": "2018-07-30T08:30:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T08:12:44.000Z", "max_forks_repo_path": "src/gallery.jl", "max_forks_repo_name": "Alexander-Barth/AlgebraicMultigrid.jl", "max_forks_repo_head_hexsha": "f6d0b497e359fbe6c406502cc89f382dd57b78f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2018-08-01T10:11:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T09:07:52.000Z", "avg_line_length": 25.4375, "max_line_length": 57, "alphanum_fraction": 0.5061425061, "num_tokens": 515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148512, "lm_q2_score": 0.8856314768368161, "lm_q1q2_score": 0.8091806929454904}} {"text": "module Quadrature\n\nfunction simps(func::Function, a::Real, b::Real, n::Int)::Float64\n if n % 2 !=0\n throw(ArgumentError(\"The number of intervals n must be even! You have choosen $n\"))\n end\n dx = (b-a)/n\n res = func(a)\n\n w = 4\n x = 0.\n for i in 1:(n-1)\n x = a + dx*i\n res += func(x)*w\n w = 6 - w\n end\n res += func(b)\n return res * dx/3\nend\n\nfunction simps(func::Function, a::Real, b::Real; tol=1e-5, limit=100)::Float64\n n = 2\n iter=0\n res=0.\n\n while true\n res=simps(func, a, b, n)\n res1=simps(func, a, b, n*2)\n if abs(res1-res)limit\n print(\"limit reached!\")\n return NaN\n end\n end\n return NaN\nend\n\nfunction gauss_3(func::Function, a::Real, b::Real)::Float64\n w_ = [8 // 9, 5 // 9, 5 // 9]\n x_ = [0., sqrt(3// 5), -sqrt(3//5)]\n res = 0.\n c1 = (b - a) / 2\n c2 = (a + b) / 2\n\n for i in 1:3\n res += w_[i] * func(c1 * x_[i] + c2)\n end\n res *= c1;\n return res;\nend\n\nfunction gauss(func::Function, a::Real, b::Real, n::Int)::Float64\n dx = (b - a) / n\n res = 0.;\n xa = 0.;\n xb = 0;\n for i in 0:(n-1)\n xa = a + i * dx\n xb = xa + dx\n res += gauss_3(func, xa, xb)\n end\n return res;\nend\n\nfunction gauss(func::Function, a::Real, b::Real; tol=1e-5, verbose=false)::Float64\n n = 2\n while true\n res = gauss(func, a, b, n);\n res1 = gauss(func, a, b, n * 2);\n\n if abs(res1 - res) < tol\n if verbose == true\n print(\"n iter: $(n*2)\\n\")\n end\n return res1\n end\n\n n *= 2;\n end\nend\n\nexport gauss\n#end module\nend\n", "meta": {"hexsha": "6b5b9a3a35a139fe5ff5d7a9d932c4c391fa3711", "size": 1793, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lib/Quadrature.jl", "max_stars_repo_name": "aurelio-amerio/corso-cpp", "max_stars_repo_head_hexsha": "53d19aa83679a7be59f5518ee5c9256269ea7d1a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-10-28T03:54:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T20:36:39.000Z", "max_issues_repo_path": "lib/Quadrature.jl", "max_issues_repo_name": "rydeen2045/corso-cpp", "max_issues_repo_head_hexsha": "53d19aa83679a7be59f5518ee5c9256269ea7d1a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/Quadrature.jl", "max_forks_repo_name": "rydeen2045/corso-cpp", "max_forks_repo_head_hexsha": "53d19aa83679a7be59f5518ee5c9256269ea7d1a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-05-08T08:29:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-14T20:37:12.000Z", "avg_line_length": 19.9222222222, "max_line_length": 92, "alphanum_fraction": 0.4690462911, "num_tokens": 642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107931567176, "lm_q2_score": 0.8633916117313211, "lm_q1q2_score": 0.8091799372355682}} {"text": "# basisfunctions.jl\n\n\"\"\"\n fourier(k::Int)\n\nImplements the Fourier basis of functions ϕ_k, defined, if k is odd, by\nϕ_k(x)=sqrt(2)sin((k+1)π*x) and if k is even, by ϕ_k(x)=sqrt(2)cos(k*x).\n\n# Examples\n\n```julia\nusing PyPlot\nclf()\nx = -1.0:0.01:2.0\ny = fourier(3).(x)\nplot(x,y)\n```\n\"\"\"\nfunction fourier(k::Int)\n k ≥ 1 || error(\"k should be positive\")\n sqrttwo = sqrt(2.0)\n if k % 2 == 1\n return x -> sqrttwo * sinpi((k+1)*x)\n else\n return x -> sqrttwo * cospi(k*x)\n end\nend\n\n\"\"\"\n faberschauderone(x::Float64)\n\nImplements the first Faber-Schauder function defined by 1-2x for 0≤x≤1/2 and\n-1+2x for 0.5≤x≤1, and is 1-periodic extended to all x∈R.\n\nSee also: faberschauder\n\n#Example\n```julia\nx=-2.:0.001:2\ny=faberschauderone.(x)\nusing PyPlot\nclf()\nplot(x,y)\n```\n\"\"\"\nfunction faberschauderone(x::Float64)\n y = mod(x, 1.0)\n if 0≤y≤0.5\n return 1.0 - 2*y\n else\n return -1.0 + 2*y\n end\nend\n\n\"\"\"\n faberschauder(j::Int, k::Int)\n\nImplements the k-th Faber-Schauder function of level j. Here, j≥0 and 1≤k≤2^j.\nIt is a one periodic function and defined on [0,1] by 2^(j+1)(x-(k-1)2^j) on\n(k-1)2^j≤x≤(2k-1)2^(j+1) and 1 - 2^(j+1)(x-(2k-1)2^(j+1)) on\n[(2k-1)2^(j+1), k2^j] and zero outside these intervals.\n\n#Example\n```julia\nj=3\nx=-2.:0.001:2.\nusing PyPlot\nclf()\nfor k in 1:2^j\n y = faberschauder(j,k).(x)\n plot(x,y)\nend\n```\n\"\"\"\nfunction faberschauder(j::Int,k::Int)\n j ≥ 0 || error(\"j should be a nonnegative integer.\")\n 1≤k≤2^j || error(\"k should be an integer between 1 and 2^j.\")\n j_float = Float64(j)\n return function(x::Float64)\n y = mod(x,1.0)\n if y ≤ (k-1)*2.0^(-j_float) || y ≥ k*2.0^(-j_float)\n return 0.0\n elseif ((k-1)*2.0^(-j_float) < y ≤ (2k-1)*2.0^(-j_float-1.0))\n return 2^(j+1)*(y-(k-1)*2.0^(-j_float))\n else\n return 1.0 - 2^(j+1)*(y-(2k-1)*2.0^(-j_float-1.0))\n end\n end\nend\n", "meta": {"hexsha": "1ae05a2035cd48bbf62553e31823cd46e44ebf19", "size": 1864, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/basisfunctions.jl", "max_stars_repo_name": "mschauer/BayesianNonparametricStatistics.jl", "max_stars_repo_head_hexsha": "7dd3bfc35509fbca909cc4b823fecc07d546151b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/basisfunctions.jl", "max_issues_repo_name": "mschauer/BayesianNonparametricStatistics.jl", "max_issues_repo_head_hexsha": "7dd3bfc35509fbca909cc4b823fecc07d546151b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/basisfunctions.jl", "max_forks_repo_name": "mschauer/BayesianNonparametricStatistics.jl", "max_forks_repo_head_hexsha": "7dd3bfc35509fbca909cc4b823fecc07d546151b", "max_forks_repo_licenses": ["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.7111111111, "max_line_length": 78, "alphanum_fraction": 0.5922746781, "num_tokens": 814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475794701962, "lm_q2_score": 0.8577681104440172, "lm_q1q2_score": 0.8091734707340876}} {"text": "\"\"\"\n number_of_steps(distance::Int64, step_size::Int64)\n\nNumber of step_size is calculating the total number of combinations for walking a `distance`\nfor a given number of step_size. For example, for a `distance` of 3 with a maximum\n`step_size` of 3 will provide for possible combinations:\n\n - 1 step + 1 step + 1 step\n - 1 step + 2 step\n - 2 step + 1 step\n - 3 step\n\n# Arguments\n- `distance::Int64`: Distance to go\n- `step_size::Int64`: Maximum step size of walking a distance\n\n\n# Examples\n```julia-repl\njulia> import ClassicAlgorithmsCollections\njulia> ClassicAlgorithmsCollections.number_of_steps(8,3)\n81\n```\n\"\"\"\nfunction number_of_steps(distance::Int64, step_size::Int64)\n\n if distance < 0\n return 0\n end\n if distance == 0\n return 1\n end\n result = 0\n for i in 1:step_size\n result += number_of_steps(distance - i, step_size)\n end\n return result\nend\n", "meta": {"hexsha": "15592babaf4b75b19148e4d2c54a07dfbb13ef35", "size": 912, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/DynamicProgramming/NumberOfSteps.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/NumberOfSteps.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/NumberOfSteps.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": 23.3846153846, "max_line_length": 92, "alphanum_fraction": 0.6896929825, "num_tokens": 260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.929440403812707, "lm_q2_score": 0.8705972768020108, "lm_q1q2_score": 0.8091682845091039}} {"text": "# Practical Summary: Ch. 15, Maximum likelihood\n\n# First, let's work with a simple one parameter model,\n# for which we can get analytic results.\n\n## Draw some data from the exponential distribution\nusing Distributions, Econometrics, Plots\nθ⁰ = 4.0\nn = 100\ny = rand(Exponential(θ⁰),n)\nhistogram(y, normalize=true)\nplot!(Exponential(θ⁰))\n\n## Here are the ML results, for reference\nusing Econometrics, Distributions\nlogℒᵢ = θ -> logpdf.(Exponential(θ[1]),y)\nθstart = [1.]\nθhat = mleresults(logℒᵢ, θstart)[1]\n\n##\n# for this model, you should be able to work out, analytically,\n# that the ML estimator is simply the sample mean. To confirm that:\nmean(y)\n\n## Let's get the results from basic theory: first the maximizer of log likelihood\nusing Optim\ntol = 1e-08\ns = θ -> -mean(logℒᵢ(θ)) # negative average logℒ\nθhat = Optim.optimize(s, θstart, LBFGS(), \n Optim.Options(\n g_tol = tol,\n x_tol=tol,\n f_tol=tol);autodiff=:forward).minimizer\n\n## Now get the t-stats, from Ihat and J hat.\nusing ForwardDiff\nsc = ForwardDiff.jacobian(logℒᵢ, θhat) # get the score contributions\nIhat = mean(sc.^2.)\nJhat = -ForwardDiff.hessian(s, θhat)\n# when you set n large (above), you should see that Ihat ⩬ -Jhat \n# also, note that Jhat = 1/θhat², which is a result we can get analytically\n\n# three forms of estimated variance\nV1 = inv(Ihat)/n\nse1 = sqrt(V1)\nV2 = inv(-Jhat)/n\nse2 = sqrt(V2)\nV3 = inv(Jhat)*Ihat*inv(Jhat)/n\nse3 = sqrt(V3)\n[se1 se2 se3] # note that the estimators are a little different from one another\n # the last one, sandwich, is what's reported in mleresults.\n##\n\n# now let's work with a model that has regressors\nusing Distributions, Econometrics, Plots\nn = 1000\nx = [ones(n) randn(n) rand(n)]\nβ⁰ = [-0.5, 1., 1.]\nθ = β -> exp.(x*β)\ny = rand.(Exponential.(θ(β⁰))) # independent, non-identically distributed observations\n\n## Here's the exponential (correct) model\nusing Econometrics, Distributions, ForwardDiff, Calculus\nlogℒᵢ = β -> [logpdf(Exponential(exp(x[i,:]'*β)),y[i]) for i = 1:n]\ns = β -> mean(logℒᵢ(β))\nβstart = zeros(3)\nβhat, objval, junk = mleresults(logℒᵢ, βstart, \"exponential model (correct)\")\n## get the score contributions\nsc = ForwardDiff.jacobian(logℒᵢ, βhat)\n# compute information matrix estimate \nIhat = zeros(3,3)\nfor i = 1:n\n\tIhat .+= sc[i,:]*sc[i,:]'\nend\nIhat ./= n\n## now the Hessian\nJhat = Calculus.hessian(s, βhat, :central)\n## check that J=-I\nIhat+Jhat # pretty close to zeros, as information matrix equality tells us\n\n## Likelihood ratio test\nusing Distributions, Econometrics\n# a true restriction\nR = [1 1 1]\nr = 1.5\nobj(b) = -s(b) # need to minimize\nβhatR, objvalR, junk = fmincon(obj, βhat, R, r)\nobjvalR = -objvalR # back to maximization\nLR = 2*n*(objval - objvalR)\npval = 1. - cdf(Chisq(1), LR)\nprintln(\"LR test: $R*β=$r (true restriction) \\nLR stat: $LR. p-value: $pval\")\n# a false restriction\nR = [0 1 -1]\nr = 1.\nobj(b) = -s(b)\nβhatR, objvalR, junk = fmincon(obj, βhat, R, r)\nobjvalR = -objvalR # back to maximization\nLR = 2*n*(objval - objvalR)\npval = 1. - cdf(Chisq(1), LR)\nprintln(\"LR test: $R*β=$r (false restriction) \\nLR stat: $LR. p-value: $pval\")\n\n## What about trying a χ² model? If we don't know the true density, we don't know which to use\nlogℒᵢ = β -> [logpdf(Chisq(exp(x[i,:]'*β)),y[i]) for i = 1:n]\nβstart = zeros(3)\nβhat, junk = mleresults(logℒᵢ, βstart, \"χ² model (incorrect)\")\nsc = ForwardDiff.jacobian(logℒᵢ, βhat); # get the score contributions\nIhat = zeros(3,3)\nfor i = 1:n\n\tIhat .+= sc[i,:]*sc[i,:]'\nend\nIhat ./= n\nJhat = Calculus.hessian(s, βhat, :central)\n# check J=-I\nprintln(\"check Ihat+Jhat approx zero, χ² model\\n\")\nIhat+Jhat # a lot farther away from zeros, at least when n is large.\n\n# How can we tell which model is best? The information criteria\n# favor the exponential model, clearly. Comparing I and J,\n# the information matrix equality holds much better for the\n# exponential model than for the Chi-square. The IM test formalizes\n# this, but here, we can see the intuitive basis for the test.\n\n\n", "meta": {"hexsha": "6731790d41c609b92d9734feb0499cb74a3d9e9f", "size": 4094, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "PracticalSummaries/15-MaximumLikelihood.jl", "max_stars_repo_name": "mcreel/EconometricsNotes", "max_stars_repo_head_hexsha": "93b3f042ace7c4d3059b333fd9dc3d2c794f0a52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-19T18:23:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T18:23:45.000Z", "max_issues_repo_path": "PracticalSummaries/15-MaximumLikelihood.jl", "max_issues_repo_name": "mcreel/EconometricsNotes", "max_issues_repo_head_hexsha": "93b3f042ace7c4d3059b333fd9dc3d2c794f0a52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PracticalSummaries/15-MaximumLikelihood.jl", "max_forks_repo_name": "mcreel/EconometricsNotes", "max_forks_repo_head_hexsha": "93b3f042ace7c4d3059b333fd9dc3d2c794f0a52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0161290323, "max_line_length": 94, "alphanum_fraction": 0.6756228627, "num_tokens": 1381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404018582427, "lm_q2_score": 0.8705972566572503, "lm_q1q2_score": 0.8091682640841984}} {"text": "module FourierTransforms\n\nusing Compat: cispi\nusing Primes\n\n################################################################################\n\nfunction direct_ft!(X::AbstractVector{T}, x::AbstractVector{T}) where {T<:Complex}\n N = length(x)\n @assert length(X) == N\n RT = typeof(real(zero(T)))\n for k in 1:N\n s = zero(T)\n for n in 1:N\n s += cispi(-2 * ((n - 1) * (k - 1) % N) / RT(N)) * x[n]\n end\n X[k] = s\n end\n return X\nend\n\ndirect_ft(x::AbstractVector) = direct_ft!(similar(x), x)\n\n################################################################################\n\nfunction direct_ft_1!(X::AbstractVector{T}, x::AbstractVector{T}) where {T<:Complex}\n @assert length(X) == length(x) == 1\n X[1] = x[1]\n return X\nend\n\ndirect_ft_1(x::AbstractVector) = direct_ft_1!(similar(x), x)\n\n################################################################################\n\nfunction direct_ft_2!(X::AbstractVector{T}, x::AbstractVector{T}) where {T<:Complex}\n @assert length(X) == length(x) == 2\n X[1] = x[1] + x[2]\n X[2] = x[1] - x[2]\n return X\nend\n\ndirect_ft_2(x::AbstractVector) = direct_ft_2!(similar(x), x)\n\n################################################################################\n\nfunction direct_ft_4!(X::AbstractVector{T}, x::AbstractVector{T}) where {T<:Complex}\n @assert length(X) == length(x) == 4\n X[1] = (x[1] + x[3]) + (x[2] + x[4])\n X[2] = (x[1] - x[3]) - im * (x[2] - x[4])\n X[3] = (x[1] + x[3]) - (x[2] + x[4])\n X[4] = (x[1] - x[3]) + im * (x[2] - x[4])\n return X\nend\n\ndirect_ft_4(x::AbstractVector) = direct_ft_4!(similar(x), x)\n\n################################################################################\n\n# \nfunction ditfft2!(X::AbstractVector{T}, x::AbstractVector{T}) where {T<:Complex}\n N = length(x)\n @assert length(X) == N\n RT = typeof(real(zero(T)))\n if N == 0\n # do nothing\n elseif N == 1\n X[1] = x[1]\n else\n # Ensure N is even\n @assert N % 2 == 0\n N2 = N ÷ 2\n ditfft2!((@view X[(0 * N2 + 1):(1 * N2)]), (@view x[1:2:end]))\n ditfft2!((@view X[(1 * N2 + 1):(2 * N2)]), (@view x[2:2:end]))\n for k in 1:N2\n ϕ = cispi(-2 * (k - 1) / RT(N))\n p = X[0 * N2 + k]\n q = ϕ * X[1 * N2 + k]\n X[0 * N2 + k] = p + q\n X[1 * N2 + k] = p - q\n end\n end\n return X\nend\n\nditfft2(x::AbstractVector) = ditfft2!(similar(x), x)\n\n################################################################################\n\nfunction choose_radix_sqrt(n::Integer)\n @assert n ≥ 0\n n ≤ 1 && return n\n # Handle special cases efficiently\n if ispow2(n)\n # Power of 2\n return 2\n end\n # Power of 2 times a factor\n p2 = trailing_zeros(n)\n factor = n >> p2\n if factor ∈ (3, 5, 7, 11, 13, 17, 19)\n return factor\n end\n # Use a greedy algorithm to find the largest factor not larger than sqrt(n)\n prime_factor_counts = factor(n)\n prime_factors = sort!(collect(keys(prime_factor_counts)))\n sqrt_n = isqrt(n)\n radix = 1\n for prime_factor in Iterators.reverse(Iterators.filter(≤(sqrt_n), prime_factors))\n for count in 1:prime_factor_counts[prime_factor]\n if radix * prime_factor ≤ sqrt_n\n radix *= prime_factor\n else\n break\n end\n end\n end\n # Always return a radix larger than 1\n radix == 1 && return n\n return radix\nend\n\n# X: output\n# Y: workspace\n# x: input (will be destroyed)\nfunction radix_fft!(X::AbstractVector{T}, Y::AbstractVector{T}, x::AbstractVector{T};\n choose_radix=choose_radix_sqrt) where {T<:Complex}\n N = length(x)\n @assert length(X) == length(Y) == N\n RT = typeof(real(zero(T)))\n radix = choose_radix(N)\n if N == 0\n # do nothing\n elseif N ≤ radix\n direct_ft!(X, x)\n else\n N₁ = radix # aka \"decimation in time\"\n @assert N % N₁ == 0\n N₂ = N ÷ N₁\n x2 = reshape(x, (N₁, N₂))\n X2 = reshape(X, (N₂, N₁))\n Y2 = reshape(Y, (N₂, N₁))\n Z2 = reshape(x, (N₂, N₁))\n for n₁ in 1:N₁\n radix_fft!((@view Y2[:, n₁]), (@view X2[:, n₁]), (@view x2[n₁, :]); choose_radix=choose_radix)\n for n₂ in 1:N₂\n Y2[n₂, n₁] *= cispi(-2 * (n₁ - 1) * (n₂ - 1) / RT(N))\n end\n end\n for n₂ in 1:N₂\n radix_fft!((@view X2[n₂, :]), (@view Z2[n₂, :]), (@view Y2[n₂, :]); choose_radix=choose_radix)\n end\n end\n return X\nend\n\n\"x will contain output\"\nradix_fft!(x::AbstractVector; kws...) = radix_fft!(x, similar(x), copy(x); kws...)\n\"X will contain output, x will be preserved\"\nradix_fft!(X::AbstractVector, x::AbstractVector; kws...) = radix_fft!(X, similar(x), copy(x); kws...)\n\"x will be preserved\"\nradix_fft(x::AbstractVector; kws...) = radix_fft!(similar(x), x; kws...)\n\n################################################################################\n\nexport fft!, fft, inv_fft!, inv_fft\n\n\"\"\"\n fft!(X::AbstractVector, x::AbstractVector)\n\nCalculate the Fourier transform of `x` and store it into `X`. `x` is\nnot modified. Both vectors must have the same length and must have\ncomplex element types.\n\nSee also: [`fft`](@ref), [`inv_fft!`](@ref).\n\"\"\"\nfft!(X::AbstractVector, x::AbstractVector) = radix_fft!(X, x)\n\n\"\"\"\n inv_fft!(x::AbstractVector, X::AbstractVector)\n\nCalculate the inverse Fourier transform of `X` and store it into `x`.\n`X` is not modified. Both vectors must have the same length and must\nhave complex element types.\n\nSee also: [`inv_fft`](@ref), [`fft!`](@ref).\n\"\"\"\nfunction inv_fft!(X::AbstractVector{T}, x::AbstractVector{T}) where {T<:Complex}\n # TODO: Don't modify `x`\n x .= conj(x)\n fft!(X, x)\n x .= conj(x)\n X .= conj(X) / length(X)\n return X\nend\n\n\"\"\"\n X = fft(x::AbstractVector)\n X::AbstractVector\n\nCalculate the Fourier transform of `x` and return it in a newly\nallocate vector. `x` is not modified. The element type of `x` must be\na complex number type.\n\nSee also: [`inv_fft`](@ref), [`fft!`](@ref).\n\"\"\"\nfft(x::AbstractVector) = fft!(similar(x), x)\n\n\"\"\"\n x = inv_fft(X::AbstractVector)\n x::AbstractVector\n\nCalculate the inverse Fourier transform of `X` and return it in a\nnewly allocate vector. `X` is not modified. The element type of `X`\nmust be a complex number type.\n\nSee also: [`fft`](@ref), [`inv_fft!`](@ref).\n\"\"\"\ninv_fft(x::AbstractVector) = inv_fft!(similar(x), x)\n\nend\n", "meta": {"hexsha": "55e3e5045842fbc648d860f4c958f03e00a3aeeb", "size": 6591, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/FourierTransforms.jl", "max_stars_repo_name": "eschnett/FFT.jl", "max_stars_repo_head_hexsha": "489f34cc4195d52b09625291e194a6f0bc025bfd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-02-03T21:21:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T04:31:56.000Z", "max_issues_repo_path": "src/FourierTransforms.jl", "max_issues_repo_name": "eschnett/FFT.jl", "max_issues_repo_head_hexsha": "489f34cc4195d52b09625291e194a6f0bc025bfd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/FourierTransforms.jl", "max_forks_repo_name": "eschnett/FFT.jl", "max_forks_repo_head_hexsha": "489f34cc4195d52b09625291e194a6f0bc025bfd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6891891892, "max_line_length": 106, "alphanum_fraction": 0.5228341678, "num_tokens": 1995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.949669373100424, "lm_q2_score": 0.8519528019683106, "lm_q1q2_score": 0.8090734833563952}} {"text": "using LinearAlgebra, Statistics, Plots\ngr(fmt=:png);\n\nx_vals = [0 0 0; 2 -3 -4]\ny_vals = [0 0 0; 4 3 -3.5]\n\nplot(x_vals, y_vals, arrow = true, color = :blue,\n legend = :none, xlims = (-5, 5), ylims = (-5, 5),\n annotations = [(2.2, 4.4, \"[2, 4]\"),\n (-3.3, 3.3, \"[-3, 3]\"),\n (-4.4, -3.85, \"[-4, -3.5]\")],\n xticks = -5:1:5, yticks = -5:1:5,\n framestyle = :origin)\n\nx = ones(3)\ny = [2,4,6]\n\ndot(x,y)\nnorm(x)\n\n# fixed linear function, to generate a plane\nf(x, y) = 0.2x + 0.1y\n\n# lines to vectors\nx_vec = [0 0; 3 3]\ny_vec = [0 0; 4 -4]\nz_vec = [0 0; f(3, 4) f(3, -4)]\n\n# draw the plane\nn = 20\ngrid1 = range(-5, 5, length = n)\nz2 = [ f(grid1[row], grid1[col]) for row in 1:n, col in 1:n ]\nwireframe(grid1, grid1, z2, fill = :blues, gridalpha =1 )\nplot!(x_vec, y_vec, z_vec, color = [:blue :green], linewidth = 3, labels = \"\",\n colorbar = false)\n", "meta": {"hexsha": "cb62065f6ba8818f56a1c3eb9deca9cb8f3758da", "size": 898, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ToolsandTechniques_linalgebra.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_linalgebra.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_linalgebra.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": 24.9444444444, "max_line_length": 78, "alphanum_fraction": 0.5233853007, "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995723244553, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.80905676826932}} {"text": "# https://i.stack.imgur.com/egDbs.png\n\"\"\"\nDoes a math thing?\n\"\"\"\nfunction extendedeuclidean(a::Int64, b::Int64)::Tuple{Int64,String}\n d0 = (a, 1, 0)\n d1 = (b, 0, 1)\n\n while d1[1] != 0\n d0, d1 = d1, d0 .- (d0[1] ÷ d1[1]) .* d1\n end\n\n (d0, \"$(d0[1]) = $(a) * $(d0[2]) + $(b) * $(d0[3])\")\nend\n", "meta": {"hexsha": "dd653eef08540f3c8c349e31a66e40be70d1de58", "size": 312, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "2020/13/solution.jl", "max_stars_repo_name": "stellartux/advent-of-code", "max_stars_repo_head_hexsha": "03e666a44fd61da64e293b556b3cc7ea8e608489", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2020/13/solution.jl", "max_issues_repo_name": "stellartux/advent-of-code", "max_issues_repo_head_hexsha": "03e666a44fd61da64e293b556b3cc7ea8e608489", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2020/13/solution.jl", "max_forks_repo_name": "stellartux/advent-of-code", "max_forks_repo_head_hexsha": "03e666a44fd61da64e293b556b3cc7ea8e608489", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.8, "max_line_length": 67, "alphanum_fraction": 0.4743589744, "num_tokens": 147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9518632343454895, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.8090563159793159}} {"text": "### Logistic function in its general form\n\n# See https://en.wikipedia.org/wiki/Logistic_function\n# l scales the curve. For l>1, the curve is stretched, whereas for l<1 it is shrinked\n# The curve's maximum value coincides with l\n# k gives the curve's steepness. For larger k, the curve becomes more steep\n# x0 is the x value of the curve's midpoint\n# y0 is the y value of the curve's midpoint\n# The logistic function has been defined for tuning purposes\n\nlogistic(x::Real, l::Real=1., k::Real=1., x0::Real=0., y0::Real=0.) = l/(1+exp(-k*(x-x0)))+y0\n", "meta": {"hexsha": "334a900a024349f9857a2cda4f53a51737db1f58", "size": 548, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/stats/logistic.jl", "max_stars_repo_name": "teresy/Klara.jl", "max_stars_repo_head_hexsha": "ffa4f6d06e38b233dccc92f749e26d28d083f994", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-10-05T21:10:23.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-30T15:32:39.000Z", "max_issues_repo_path": "src/stats/logistic.jl", "max_issues_repo_name": "teresy/Klara.jl", "max_issues_repo_head_hexsha": "ffa4f6d06e38b233dccc92f749e26d28d083f994", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/stats/logistic.jl", "max_forks_repo_name": "teresy/Klara.jl", "max_forks_repo_head_hexsha": "ffa4f6d06e38b233dccc92f749e26d28d083f994", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.6666666667, "max_line_length": 93, "alphanum_fraction": 0.7208029197, "num_tokens": 163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9518632261523029, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.8090563035891557}} {"text": "\"\"\"\n`LinearKernel([ρ=1.0,[c=0.0]])`\nThe linear kernel is a Mercer kernel given by\n```\n κ(x,y) = ρ²xᵀy + c\n```\nWhere `c` is a real number\n\"\"\"\nstruct LinearKernel{T,Tr,Tc<:Real} <: Kernel{T,Tr}\n transform::Tr\n metric::DotProduct\n c::Tc\n function LinearKernel{T,Tr,Tc}(transform::Tr,c::Tc) where {T,Tr<:Transform,Tc<:Real}\n return new{T,Tr,Tc}(transform,DotProduct(),c)\n end\nend\n\nfunction LinearKernel(ρ::T₁=1.0,c::T₂=zero(T₁)) where {T₁<:Real,T₂<:Real}\n LinearKernel{T₁,ScaleTransform{T₁},T₂}(ScaleTransform(ρ),c)\nend\n\nfunction LinearKernel(ρ::AbstractVector{T₁},c::T₂=zero(T₁)) where {T₁<:Real,T₂<:Real}\n LinearKernel{T₁,ARDTransform{T₁,length(ρ)},T₂}(ARDTransform(ρ),c)\nend\n\nfunction LinearKernel(t::Tr,c::T=zero(Float64)) where {Tr<:Transform,T<:Real}\n LinearKernel{eltype(t),Tr,T}(t,c)\nend\n\nparams(k::LinearKernel) = (params(transform(k)),k.c)\nopt_params(k::LinearKernel) = (opt_params(transform(k)),k.c)\n\n@inline kappa(κ::LinearKernel, xᵀy::T) where {T<:Real} = xᵀy + κ.c\n\n\"\"\"\n`PolynomialKernel([ρ=1.0[,d=2.0[,c=0.0]]])`\nThe polynomial kernel is a Mercer kernel given by\n```\n κ(x,y) = (ρ²xᵀy + c)^d\n```\nWhere `c` is a real number, and `d` is a shape parameter bigger than 1\n\"\"\"\nstruct PolynomialKernel{T,Tr,Tc<:Real,Td<:Real} <: Kernel{T,Tr}\n transform::Tr\n metric::DotProduct\n c::Tc\n d::Td\n function PolynomialKernel{T,Tr,Tc,Td}(transform::Tr,c::Tc,d::Td) where {T,Tr<:Transform,Tc<:Real,Td<:Real}\n return new{T,Tr,Tc,Td}(transform,DotProduct(),c,d)\n end\nend\n\nfunction PolynomialKernel(ρ::T₁=1.0,d::T₂=2.0,c::T₃=zero(T₁)) where {T₁<:Real,T₂<:Real,T₃<:Real}\n @check_args(PolynomialKernel, d, d >= one(T₁), \"d >= 1\")\n PolynomialKernel{T₁,ScaleTransform{T₁},T₂,T₃}(ScaleTransform(ρ),c,d)\nend\n\nfunction PolynomialKernel(ρ::AbstractVector{T₁},d::T₂=2.0,c::T₃=zero(T₁)) where {T₁<:Real,T₂<:Real,T₃<:Real}\n @check_args(PolynomialKernel, d, d >= one(T₂), \"d >= 1\")\n PolynomialKernel{T₁,ARDTransform{T₁,length(ρ)},T₂,T₃}(ARDTransform(ρ),c,d)\nend\n\nfunction PolynomialKernel(t::Tr,d::T₁=2.0,c::T₂=zero(eltype(T₁))) where {Tr<:Transform,T₁<:Real,T₂<:Real}\n @check_args(PolynomialKernel, d, d >= one(T₁), \"d >= 1\")\n PolynomialKernel{eltype(Tr),Tr,T₁,T₂}(t,c,d)\nend\n\nparams(k::PolynomialKernel) = (params(transform(k)),k.d,k.c)\nopt_params(k::PolynomialKernel) = (opt_params(transform(k)),k.d,k.c)\n\n@inline kappa(κ::PolynomialKernel, xᵀy::T) where {T<:Real} = (xᵀy + κ.c)^(κ.d)\n", "meta": {"hexsha": "7e6b1d417d635d96fcdbefcf401354b11946117b", "size": 2447, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels/polynomial.jl", "max_stars_repo_name": "devmotion/KernelFunctions.jl", "max_stars_repo_head_hexsha": "460ed8685018a35bac2bceaa2401639668a41f6e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernels/polynomial.jl", "max_issues_repo_name": "devmotion/KernelFunctions.jl", "max_issues_repo_head_hexsha": "460ed8685018a35bac2bceaa2401639668a41f6e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernels/polynomial.jl", "max_forks_repo_name": "devmotion/KernelFunctions.jl", "max_forks_repo_head_hexsha": "460ed8685018a35bac2bceaa2401639668a41f6e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9861111111, "max_line_length": 110, "alphanum_fraction": 0.6648957908, "num_tokens": 924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632234212403, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.8090562976503727}} {"text": "## ------------- Logistic function\n\n\"\"\"\n\t$(SIGNATURES)\n\nGeneralized logistic function object.\n\n``\nlb + (ub - lb) / (1 + lrShifter * exp(-slope * x)) ^ twister\n``\n\nNote that slope can be set to 1 if the input is `x / x0`. But it makes sense to have a slope when x0 depends on the college.\n\n# Parameters\n- `lb` and `ub` are the bounds of `f(x)`.\n- `lrShifter >= 0` roughly shifts the curve left/right. It really sets the grad prob at h = 0. Higher `lrShifter` implies lower grad probs.\n- `slope > 0` is the slope.\n- `twister > 0` produces asymmetry (`twister = 1` is symmetric).\n\"\"\"\n@with_kw mutable struct GeneralizedLogistic\n lb :: Double = 0.0\n ub :: Double = 1.0\n lrShifter :: Double = 1.0\n slope :: Double = 1.0\n twister :: Double = 1.0\nend\n\n\n\"\"\"\n\t$(SIGNATURES)\n\nGeneralized logistic function.\n\"\"\"\nfunction logistic(x; lb = 0.0, ub = 1.0, lrShifter = 1.0, slope = 1.0, twister = 1.0)\n return lb .+ (ub - lb) ./ ((1 .+ lrShifter .* exp.(-slope .* x)) .^ twister);\nend\n\nfunction logistic(glf :: GeneralizedLogistic, x)\n return logistic(x; lb = glf.lb, ub = glf.ub, lrShifter = glf.lrShifter,\n slope = glf.slope, twister = glf.twister)\nend\n\n# -----------", "meta": {"hexsha": "36edc9cae2be76f007c4bec57d81ad92c0444ec5", "size": 1183, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/logistic.jl", "max_stars_repo_name": "hendri54/CollegeStratBase", "max_stars_repo_head_hexsha": "85eb17b367d2ec9fa68ea4225fb5b63690e70602", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/logistic.jl", "max_issues_repo_name": "hendri54/CollegeStratBase", "max_issues_repo_head_hexsha": "85eb17b367d2ec9fa68ea4225fb5b63690e70602", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/logistic.jl", "max_forks_repo_name": "hendri54/CollegeStratBase", "max_forks_repo_head_hexsha": "85eb17b367d2ec9fa68ea4225fb5b63690e70602", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.511627907, "max_line_length": 139, "alphanum_fraction": 0.6229923922, "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242074, "lm_q2_score": 0.8723473680407889, "lm_q1q2_score": 0.8089829249213253}} {"text": "using LinearAlgebra\r\n\r\n# k_local(Elastic Modulus,thickness,height,length,number of nodes,row/column one,row/column two, ==1 adjusts for fixed node)\r\n\r\n#creates local stiffness matrix and maps to global\r\nfunction k_local(E,t,h,l,i,n1,n2,fixed=0)\r\n k_global = zeros(i,i)\r\n A = t*h\r\n k = ((E*A)/l)\r\n k_global[n1,n1] = k\r\n k_global[n1,n2] = -k\r\n k_global[n2,n1] = -k\r\n k_global[n2,n2] = k\r\n if fixed == 1\r\n adj = zeros(1,i)\r\n adj[n1] = 1\r\n k_global[n1,:] = adj \r\n k_global[:,n1] = adj \r\n end\r\n return k_global\r\nend\r\n\r\n# constants from problem statement\r\nE = 68.9*10^9\r\nt = 0.006\r\nh13 = 0.08\r\nh2 = 0.02\r\nl = 0.025\r\nl2 = 0.1\r\n\r\n# combining all globally mapped matrices\r\nkG = k_local(E,t,h13,l,4,1,2,1)+\r\n k_local(E,t,h2,l2,4,2,3)+\r\n k_local(E,t,h13,l,4,3,4)\r\n\r\n# Force Vector\r\nf = Float64[0 0 0 1800]\r\nF = transpose(f)\r\n\r\n# Displacement vector\r\nu = kG\\F\r\nprintln(\"Nodal Displacement Vector (meters)\")\r\ndisplay(u)\r\n\r\n# Strain Function\r\nϵ(x2,x1,l) = (x2 - x1)/l\r\n\r\n#Strain Vector\r\nϵM = [ϵ(u[2],u[1],l)\r\n ϵ(u[3],u[2],l2) \r\n ϵ(u[4],u[3],l)]\r\n\r\n# Stress Function\r\nσ(E,ϵ) = E*ϵ\r\n\r\n# Stress Vector\r\nσM = [σ(E,ϵM[1])\r\n σ(E,ϵM[2])\r\n σ(E,ϵM[3])]\r\nprintln(\"Element Stress Vector (Pa)\")\r\ndisplay(σM)\r\n\r\n", "meta": {"hexsha": "d1a396f3647c1e0f9ca9b414581d89dcb3ff1107", "size": 1263, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "trejo_nicholas_HW3_p1.jl", "max_stars_repo_name": "UltraHeckerNick/MechanicalPrograms_small", "max_stars_repo_head_hexsha": "1059fb6c0d391be5ef75c4ba165e4f48819bfb2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "trejo_nicholas_HW3_p1.jl", "max_issues_repo_name": "UltraHeckerNick/MechanicalPrograms_small", "max_issues_repo_head_hexsha": "1059fb6c0d391be5ef75c4ba165e4f48819bfb2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "trejo_nicholas_HW3_p1.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": 20.0476190476, "max_line_length": 125, "alphanum_fraction": 0.5740300871, "num_tokens": 487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960951711746926, "lm_q2_score": 0.8418256393148982, "lm_q1q2_score": 0.8089537890921017}} {"text": "function fourfilt(x,delt,tmax,tmin)\r\n# FOURFILT Fourier low, high, or bandpass filter.\r\n#\r\n# [filtdat]=fourfilt(x,delt,tmax,tmin)\r\n#\r\n# where: x: data series to be filtered\r\n# delt: sampling interval\r\n# tmax: maximum period filter cutoff\r\n# tmin: minimum period filter cutoff\r\n#\r\n# usage: lowpassdata=fourfilt(data,0.5,2000,20)\r\n#\r\n# gives lowpass filter with cutoff at 20.0 sec\r\n# tmax set > (length(x)*delt) for no cutoff at low freq end\r\n#\r\n# usage: highpassdata=fourfilt(x,0.5,20,0.9)\r\n#\r\n# gives highpass filter with cutoff at 20.0 sec\r\n# tmin set < (2*delt) for no cutoff at high freq end\r\n#\r\n# usage: bandpassdata=fourfilt(x,0.5,20,10)\r\n#\r\n# gives bandpass filter passing 10-20 sec. band\r\n#\r\n# REQUIREMENTS: Julia \"FFTW\" package \r\n#\r\n# Reference:\r\n# Walters, R. A. and Heston, C., 1982. Removing the tidal-period variations from time-series\r\n# data using low-pass digital filters. Journal of Physical Oeanography, 12 112-115 .\r\n#\r\n#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n# Julia version that has been translated from MATLAB version \r\n# by William Pringle on 08/21/2019\r\n# MATLAB verion is available from Rich Signell's \"RPSstuff\" github\r\n#\r\n# Version 1.0 (12/4/96) Jeff List (jlist@usgs.gov)\r\n# Version 1.1 (1/8/97) Rich Signell (rsignell@usgs.gov)\r\n# removed argument for number of points and add error trapping for matrices\r\n# Version 1.1b (12/1/2005) Rich Signell (rsignell@usgs.gov)\r\n# added reference\r\n#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nglobal f\r\n\r\nif ndims(x) != 1\r\n display(\"fourfilt cannot handle matrices\");\r\n return\r\nend\r\nif sum(isnan.(x)) > 0\r\n display(\"fourfilt will not work with nans in timeseries\")\r\n return\r\nend\r\n\r\nnpts = length(x);\r\nnby2 = convert(Int,floor(npts/2));\r\ntfund = npts*delt;\r\nffund = 1.0/tfund;\r\n\r\n# remove the mean from data:\r\ndatamean = mean(x);\r\nx = x .- datamean;\r\n\r\n# fourier transform data:\r\ncoeffs = fft(x);\r\n\r\n# filter coefficients:\r\nf = ffund\r\nfor i = 2:nby2+1\r\n t = 1/f\r\n if t > tmax || t < tmin\r\n coeffs[i] = 0.0*coeffs[i];\r\n end\r\n f += ffund\r\nend\r\n\r\n# calculate the remaining coefficients:\r\nfor i = 2:nby2\r\n coeffs[npts+2-i] = conj(coeffs[i])\r\nend\r\n\r\n\r\n# backtransform data and take real part:\r\nbackcoeffs = ifft(coeffs);\r\nfiltdat = real(backcoeffs);\r\n\r\n# add back the mean:\r\nreturn filtdat .+ datamean\r\n\r\nend\r\n", "meta": {"hexsha": "fe0e0b563ea6ab539b2e8304fcb222d5cd6bf9b0", "size": 2436, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "fourfilt.jl", "max_stars_repo_name": "WPringle/Julia_MetOcean", "max_stars_repo_head_hexsha": "ca73ce37c89b52e2cf8329b3928640416dab8db7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-06-13T14:01:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T12:32:26.000Z", "max_issues_repo_path": "fourfilt.jl", "max_issues_repo_name": "WPringle/Julia_MetOcean", "max_issues_repo_head_hexsha": "ca73ce37c89b52e2cf8329b3928640416dab8db7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fourfilt.jl", "max_forks_repo_name": "WPringle/Julia_MetOcean", "max_forks_repo_head_hexsha": "ca73ce37c89b52e2cf8329b3928640416dab8db7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0666666667, "max_line_length": 94, "alphanum_fraction": 0.6149425287, "num_tokens": 741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377296574669, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.8089052975533169}} {"text": "using Distributions\n\n\n# Use Monte Carlo methods to estimate the divergences between two\n# theoretical distributions. Take random samples of source distribution.\n# Estimate cost at those points and weight by probability.\n\nfunction mc_divergence_estimate(d1::Distribution, d2::Distribution, samples::Integer, sample_divergence_func::Function)\n divergence = 0.0\n for i in 1:samples\n x = rand(d1)\n divergence += sample_divergence_func(pdf(d1, x), pdf(d2, x))\n end\n return divergence\nend\n\n\n# non-symmetric (i.e. conventional) divergence for a single sample\n\nfunction kl_sample_divergence(dist1_probab::Float64, dist2_probab::Float64)\n return -dist1_probab * log(dist2_probab / dist1_probab)\nend\n\n# symmetrized divergence for a single sample\n\nfunction skl_sample_divergence(dist1_probab::Float64, dist2_probab::Float64)\n return kl_sample_divergence(dist1_probab,dist2_probab) + kl_sample_divergence(dist2_probab,dist1_probab)\nend\n\n# Jensen-Shannon divergence for a single sample (symmetric)\n\nfunction js_sample_divergence(dist1_probab::Float64, dist2_probab::Float64)\n const mean_probab::Float64 = (dist1_probab + dist2_probab) / 2\n return (kl_sample_divergence(dist1_probab, mean_probab) + kl_sample_divergence(dist2_probab, mean_probab)) / 2\nend\n\nkl_divergence(d1::Distribution, d2::Distribution) = mc_divergence_estimate(d1, d2, 10_000, kl_sample_divergence)\nskl_divergence(d1::Distribution, d2::Distribution) = mc_divergence_estimate(d1, d2, 10_000, skl_sample_divergence)\njs_divergence(d1::Distribution, d2::Distribution) = mc_divergence_estimate(d1, d2, 10_000, js_sample_divergence)\n\n\n", "meta": {"hexsha": "fda194e75f956ce1be61f04f2d6d45b427248191", "size": 1624, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kl.jl", "max_stars_repo_name": "johnmyleswhite/KLDivergence.jl", "max_stars_repo_head_hexsha": "0fc5170f09384c03d2d5c710d7b7d68a1e1ee29f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2015-07-02T02:33:18.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-10T15:21:54.000Z", "max_issues_repo_path": "src/kl.jl", "max_issues_repo_name": "JuliaPackageMirrors/KLDivergence.jl", "max_issues_repo_head_hexsha": "854155e0c754aa4eeca0c226619f3a7199abe782", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-05-24T13:03:17.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-24T15:59:13.000Z", "max_forks_repo_path": "src/kl.jl", "max_forks_repo_name": "JuliaPackageMirrors/KLDivergence.jl", "max_forks_repo_head_hexsha": "854155e0c754aa4eeca0c226619f3a7199abe782", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2015-07-02T02:33:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-18T22:49:49.000Z", "avg_line_length": 38.6666666667, "max_line_length": 119, "alphanum_fraction": 0.7924876847, "num_tokens": 457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377272885903, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.8089052955542335}} {"text": "# (weighted) sum of L2 norm and L1 norm\n# for Group Lasso, this can be used together with src/calculus/slicedSeparableSum\nexport NormL1plusL2\n\n\"\"\"\n**L1 norm plus L2 norm**\n\n NormL1plusL2(λ_1=1, λ_2=1)\n\nWith two nonegative scalars λ_1 and λ_2, returns the function\n```math\nf(x) = λ_1 ∑_{i=1}^{n} |x_i| + λ_2 \\\\sqrt{x_1^2 + … + x_n^2}.\n```\nWith nonnegative array λ_1 and nonnegative scalar λ_2, returns the function\n```math\nf(x) = ∑_{i=1}^{n} {λ_1}_i |x_i| + λ_2 \\\\sqrt{x_1^2 + … + x_n^2}.\n```\n\"\"\"\nstruct NormL1plusL2{L1<:NormL1, L2 <: NormL2} <: ProximableFunction\n l1::L1\n l2::L2\nend\n\nis_separable(f::NormL1plusL2) = false\nis_convex(f::NormL1plusL2) = true\nis_positively_homogeneous(f::NormL1plusL2) = true\n\nfunction NormL1plusL2(lambda1::L=1, lambda2::M=1) where {L <: Union{Real, AbstractArray}, M <: Real}\n NormL1plusL2(NormL1(lambda1), NormL2(lambda2))\nend\n\nfunction (f::NormL1plusL2)(x::AbstractArray{T}) where T <: RealOrComplex\n return f.l1(x) + f.l2(x)\nend\n\nfunction prox!(y::AbstractArray{T}, f::NormL1plusL2, x::AbstractArray{T}, gamma::Real=1) where T <: RealOrComplex\n prox!(y, f.l1, x, gamma)\n prox!(y, f.l2, y, gamma)\n return f(y)\nend\n\nfun_name(f::NormL1plusL2) = \"L2-norm + L1-norm\"\nfun_dom(f::NormL1plusL2) = \"AbstractArray{Real}, AbstractArray{Complex}\"\nfun_expr(f::NormL1plusL2{L1,L2}) where {L1<:NormL1{<:Real}, L2} = \"x ↦ λ_1 ||x||_1 + λ_2||x||_2\"\nfun_expr(f::NormL1plusL2{L1,L2}) where {L1<:NormL1{<:AbstractArray}, L2} = \"x ↦ sum( (λ_1)_i |x_i| ) + λ_2||x||_2\"\nfun_params(f::NormL1plusL2{L1,L2}) where {L1<:NormL1{<:Real}, L2} = \"λ_1 = $(f.l1.lambda), λ_2 = $(f.l2.lambda)\"\nfun_params(f::NormL1plusL2{L1,L2}) where {L1<:NormL1{<:AbstractArray}, L2} = \"λ_1 = $(typeof(f.lambda)) of size $(size(f.lambda)), λ_2 = $(f.l2.lambda)\"\n\nfunction prox_naive(f::NormL1plusL2, x::AbstractArray{T}, gamma::Real=1) where T <: RealOrComplex\n y1, v1 = prox_naive(f.l1, x, gamma)\n y2, v2 = prox_naive(f.l2, y1, gamma)\n return y2, f(y2)\nend\n", "meta": {"hexsha": "2cf1ef2e139159725a18b70109feebe9b3e4da25", "size": 1981, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/normL1plusL2.jl", "max_stars_repo_name": "kul-optec/ProximalOperators.jl", "max_stars_repo_head_hexsha": "c46f6de4ede3720664605762a886410a902630eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2021-07-05T20:31:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T11:04:44.000Z", "max_issues_repo_path": "src/functions/normL1plusL2.jl", "max_issues_repo_name": "kul-optec/ProximalOperators.jl", "max_issues_repo_head_hexsha": "c46f6de4ede3720664605762a886410a902630eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2021-07-29T08:11:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T21:55:12.000Z", "max_forks_repo_path": "src/functions/normL1plusL2.jl", "max_forks_repo_name": "kul-optec/ProximalOperators.jl", "max_forks_repo_head_hexsha": "c46f6de4ede3720664605762a886410a902630eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-07-29T08:43:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T00:15:32.000Z", "avg_line_length": 36.6851851852, "max_line_length": 153, "alphanum_fraction": 0.6663301363, "num_tokens": 830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377261041521, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.8089052870281703}} {"text": "abstract type Kernel end\n\nstruct PolynomialKernel <: Kernel\n # return (x^T @ y)^M\n _degree::Int64 # degree of polynomial feature\n _intercept::Float64 # intercept\n function PolynomialKernel(degree::Int64, intercept = 0.0)\n new(degree, intercept)\n end\nend\n\n\"\"\"\n kernel(kernel::PolynomialKernel, x::AbstractArray{Float64, 2}, y::AbstractArray{Float64, 2})\n\nFor x = [x_1,... x_N] of size (n_feature, n_samples1) and y = [y_1,... y_N] of size (n_feature, n_samples2),\n compute the gram matrix K of size(n_samples1, n_samples2), where K_ij =(x_i * y_j)^M.\n\"\"\"\nfunction kernel(\n kernel::PolynomialKernel,\n x::AbstractArray{Float64,2},\n y::AbstractArray{Float64,2},\n)\n n_samples1 = size(x)[2]\n n_samples2 = size(y)[2]\n n_feature = size(x)[1]\n\n intercept = kernel._intercept\n degree = kernel._degree\n\n n_feature == size(y)[1] || error(\"feature dimension does not match\")\n ret = zeros(n_samples1, n_samples2)\n for i = 1:n_samples1\n for j = 1:n_samples2\n x_i = view(x, :, i)\n y_j = view(y, :, j)\n ret[i, j] = (sum(x_i .* y_j) + intercept)^degree\n end\n end\n\n return ret\nend\n\n\"Kernel to compute c0 * exp(-0.5 * c1^T * (x1 - x2)^2) where c0 is scalar and c1 is Array{Float64, 1}\"\nmutable struct RBFKernel <: Kernel\n _params::Array{Float64,1}\n _n_params::Int64\n function RBFKernel(params::Array{Float64,1})\n new(copy(params), size(params)[1])\n end\nend\n\nfunction rbf(\n c0::Float64,\n c1::AbstractArray{Float64,1},\n x1::AbstractArray{Float64,1},\n x2::AbstractArray{Float64,1},\n)\n d = (x1 - x2) .^ 2\n return c0 * exp(-0.5 * transpose(c1) * d)\nend\n\n\"\"\"\n kernel(kernel::PolynomialKernel, x::AbstractArray{Float64, 2}, y::AbstractArray{Float64, 2})\n\nFor x = [x_1,... x_N] of size (n_feature, n_samples1) and y = [y_1,... y_N] of size (n_feature, n_samples2),\n compute the gram matrix K of size(n_samples1, n_samples2), where K_ij = rbf(x_i, x_j).\n\"\"\"\nfunction kernel(kernel::RBFKernel, x::AbstractArray{Float64,2}, y::AbstractArray{Float64,2})\n n_feature = size(x)[1]\n n_samples1 = size(x)[2]\n n_samples2 = size(y)[2]\n n_feature == size(y)[1] || error(\"size does not match\")\n n_feature == kernel._n_params - 1 || error(\"kernel size does not match\")\n\n ret = zeros(n_samples1, n_samples2)\n for i = 1:n_samples1\n x_i = x[:, i]\n for j = 1:n_samples2\n y_j = y[:, j]\n ret[i, j] = rbf(kernel._params[1], kernel._params[2:end], x_i, y_j)\n end\n end\n\n return ret\nend\n\n\"\"\"\n derivatives(kernel::RBFKernel, x::AbstractArray{Float64, 2}, y::AbstractArray{Float64, 2})\n\nReturn the derivative of K(gram matrix) with respect to c0 and c1 as Array{Float64, 3}\n\"\"\"\nfunction derivatives(\n kernel::RBFKernel,\n x::AbstractArray{Float64,2},\n y::AbstractArray{Float64,2},\n)\n n_feature = size(x)[1]\n n_samples1 = size(x)[2]\n n_samples2 = size(y)[2]\n n_feature == size(y)[1] || error(\"size does not match\")\n n_feature == kernel._n_params - 1 || error(\"kernel size does not match\")\n n_params = kernel._n_params\n\n ret = zeros(n_params, n_samples1, n_samples2)\n c0 = kernel._params[1]\n c1 = kernel._params[2:end]\n for i = 1:n_samples1\n for j = 1:n_samples2\n x_i = x[:, i]\n y_j = y[:, j]\n d = (x_i - y_j) .^ 2\n delta_c0 = exp(-0.5 * sum(c0 * d))\n delta_c1 = -0.5 * d * c0 * delta_c0\n ret[:, i, j] = vcat([delta_c0], delta_c1)\n end\n end\n\n return ret\nend\n\nfunction update_parameters(kernel::RBFKernel, updates_to_add::AbstractArray{Float64,1})\n kernel._params += updates_to_add\nend\n", "meta": {"hexsha": "e073aa26973cd9dae63a17784498ecbc911c8a4a", "size": 3680, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernel/kernels.jl", "max_stars_repo_name": "soblin/prml-julia", "max_stars_repo_head_hexsha": "cba8cec55c95d883c656125b12c40624430c059d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-07-10T21:46:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T04:40:22.000Z", "max_issues_repo_path": "src/kernel/kernels.jl", "max_issues_repo_name": "soblin/prml-julia", "max_issues_repo_head_hexsha": "cba8cec55c95d883c656125b12c40624430c059d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernel/kernels.jl", "max_forks_repo_name": "soblin/prml-julia", "max_forks_repo_head_hexsha": "cba8cec55c95d883c656125b12c40624430c059d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6774193548, "max_line_length": 108, "alphanum_fraction": 0.6198369565, "num_tokens": 1172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947086083138, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.8087748035031801}} {"text": "#-------------monte_carlo.jl---------------------------------------------------#\n#\n# Purpose: A simple monte carlo script to integrate x^2 in a given range\n#\n#------------------------------------------------------------------------------#\n\n# A function to integrate x^2 in a given range with num number of points\nfunction monte_carlo(range::Float64, num::Int64)\n count = 0\n for i = 1:num\n x_pos = rand() * range - range * 0.5\n y_pos = rand() * 0.25 * range * range \n\n if (y_pos < x_pos*x_pos)\n count += 1\n end\n end\n\n #println(\"The integral of x^2 between \", -range*0.5, \" and \", \n #range*0.5, \" is \", (count / num) *0.25*range*range*range)\nend\n\nmonte_carlo(6.0, 10000)\n", "meta": {"hexsha": "f95fa5ceac623074e59f75319b91ce9e0d624f9d", "size": 731, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/monte_carlo/monte_carlo.jl", "max_stars_repo_name": "vchuravy/skillpill-julia", "max_stars_repo_head_hexsha": "4ef5de50fe6fdc846278ed47eaeeb73acb121a02", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-07-11T18:24:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-19T01:00:44.000Z", "max_issues_repo_path": "examples/monte_carlo/monte_carlo.jl", "max_issues_repo_name": "oist/skillpill-julia", "max_issues_repo_head_hexsha": "eb719677ae84bd26c1e3fdb889cf2b54f65d47ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/monte_carlo/monte_carlo.jl", "max_forks_repo_name": "oist/skillpill-julia", "max_forks_repo_head_hexsha": "eb719677ae84bd26c1e3fdb889cf2b54f65d47ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-06-23T01:55:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-13T03:44:47.000Z", "avg_line_length": 30.4583333333, "max_line_length": 80, "alphanum_fraction": 0.4719562244, "num_tokens": 203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947086083139, "lm_q2_score": 0.8558511414521923, "lm_q1q2_score": 0.8087748000287074}} {"text": "module MadMax\n\nusing PrettyTables\nusing Flux\nusing LinearAlgebra\n\nexport BisectionEval\nexport RegulaFalsiEval\nexport NewtonEval\nexport GaussJacobiEval\nexport GaussSeidelEval\nexport SOREval\n\nfunction getLowerTriangular(X)\n R = zeros(size(X)...)\n for i in 1:size(X)[1]\n for j in 1:size(X)[2]\n if i>j\n R[i,j] = X[i, j]\n end\n end\n end\n return R\nend\n\nfunction getUpperTriangular(X)\n R = zeros(size(X)...)\n for i in 1:size(X)[1]\n for j in 1:size(X)[2]\n if i tol && n != N\n x_last = last(approximations)\n delta = f(x_last) / df(x_last) \n x_n = x_last - delta\n\n approximations = [approximations; x_n]\n\n # get error\n error = abs(x_last - x_n)\n errors = [errors; error]\n\n n += 1\n end\n\n if verbose\n headers = [\"S.N\" \"x_n\" \"Error\"]\n data = hcat(0:n, approximations, errors)\n \n pretty_table(data, headers)\n println(\"$n iterations\")\n end\n\n return approximations, error\nend\n\nfunction BisectionEval(f::Function, a, b; tol = 0.005, N = 100, verbose=true)\n # make expr\n error = Base.Inf64 \n \n # find starting interval\n interval = (a, b)\n\n # iterate\n approximations = []\n errors = []\n n = 0\n\n if verbose\n as = []\n bs = []\n prod_s =[]\n end\n\n while error > tol && n!=N\n # get m_k\n m_k = sum(interval)/2\n\n # get error\n if length(approximations) > 0\n error = abs(last(approximations) - m_k)\n end\n push!(errors, error)\n\n if verbose\n push!(as, interval[1])\n push!(bs, interval[2])\n end\n\n # append the appproximation\n push!(approximations, m_k)\n\n # get new interval\n interval = (f(interval[1])*f(m_k)) < 0 ? (interval[1], m_k) : (m_k, interval[2])\n\n prod = (f(interval[1])*f(m_k)) < 0 ? \"<0\" : \">0\" \n verbose && push!(prod_s, prod) \n \n n += 1\n end\n\n if verbose\n data = hcat(1:n, as, bs, approximations, prod_s, errors)\n header = [\"S.No\" \"a_k-1\" \"b_k-1\" \"m_k\" \"f(a_k-1)*f(m_k)\" \"error\"]\n pretty_table(data, header)\n println(\"$n iterations\")\n end\n\n return approximations, errors\nend\n\nfunction RegulaFalsiEval(f::Function, a, b; tol = 0.005, N = 100, verbose=true)\n # make expr\n error = Base.Inf64 \n\n # find starting interval\n interval = (a, b)\n\n # iterate\n approximations = []\n errors = []\n n = 0\n\n if verbose\n as = []\n bs = []\n f_as = []\n f_bs = []\n prod_s =[]\n end\n\n while error > tol && n<=N\n # get m_k\n\n m_k = (interval[1]*f(interval[2]) - interval[2]*f(interval[1])) / (f(interval[2]) - f(interval[1])) \n\n if verbose\n push!(as, interval[1])\n push!(bs, interval[2])\n push!(f_as, f(interval[1]))\n push!(f_bs, f(interval[2]))\n end\n\n # get error\n if length(approximations) > 0\n error = abs(last(approximations) - m_k)\n end\n push!(errors, error)\n\n # append the appproximation\n push!(approximations, m_k)\n\n # get new interval\n interval = (f(interval[1])*f(m_k)) < 0 ? (interval[1], m_k) : (m_k, interval[2])\n\n prod = (f(interval[1])*f(m_k)) < 0 ? \"<0\" : \">0\" \n verbose && push!(prod_s, prod) \n\n n += 1\n end\n\n if verbose\n data = hcat(1:n, as, bs, f_as, f_bs, approximations, prod_s, errors)\n header = [\"S.No\" \"a_k-1\" \"b_k-1\" \"f(a)\" \"f(b)\" \"m_k\" \"f(a_k-1)*f(m_k)\" \"error\"]\n pretty_table(data, header)\n println(\"$n iterations\")\n end\n\n return approximations, errors\nend\n\nend\n", "meta": {"hexsha": "4d6444ef4ab57a4dcf1fdc2463b019433221a559", "size": 5406, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MadMax.jl", "max_stars_repo_name": "verma16Ayush/MadMax.jl", "max_stars_repo_head_hexsha": "18693c20a33b6c8cb8105e368da17da1dcdee364", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MadMax.jl", "max_issues_repo_name": "verma16Ayush/MadMax.jl", "max_issues_repo_head_hexsha": "18693c20a33b6c8cb8105e368da17da1dcdee364", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MadMax.jl", "max_forks_repo_name": "verma16Ayush/MadMax.jl", "max_forks_repo_head_hexsha": "18693c20a33b6c8cb8105e368da17da1dcdee364", "max_forks_repo_licenses": ["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.4772727273, "max_line_length": 108, "alphanum_fraction": 0.5135035146, "num_tokens": 1717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299591537478, "lm_q2_score": 0.8740772450055545, "lm_q1q2_score": 0.8087224536937097}} {"text": "# # Subspace angles\n# This example considers the angles between neighbouring Laguerre polynomials with a perturbed measure:\n# ```math\n# \\cos\\theta_n = \\frac{\\langle L_n, L_{n+k}\\rangle}{\\|L_n\\|_2 \\|L_{n+k}\\|_2},\\quad{\\rm for}\\quad 0\\le n < N-k,\n# ```\n# where the inner product is defined by $\\langle f, g\\rangle = \\int_0^\\infty f(x) g(x) x^\\beta e^{-x}{\\rm\\,d}x$.\n#\n# We do so by connecting Laguerre polynomials to the normalized generalized Laguerre polynomials associated with the perturbed measure. It follows by the inner product of the connection coefficients that:\n# ```math\n# \\cos\\theta_n = \\frac{(V^\\top V)_{n, n+k}}{\\sqrt{(V^\\top V)_{n, n}(V^\\top V)_{n+k, n+k}}}.\n# ```\n#\nusing FastTransforms, LinearAlgebra\n\n# The neighbouring index `k` and the maximum degree `N-1`:\nk, N = 1, 11\n\n# The Laguerre connection parameters:\nα, β = 0.0, 0.125\n\n# We precompute a Laguerre--Laguerre plan:\nP = plan_lag2lag(Float64, N, α, β; norm2=true)\n\n# We apply the plan to the identity, followed by the adjoint plan:\nVtV = P*I\nlmul!(P', VtV)\n\n# From this matrix, the angles are recovered from:\nθ = [acos(VtV[n, n+k]/sqrt(VtV[n, n]*VtV[n+k, n+k])) for n in 1:N-k]\n", "meta": {"hexsha": "d3c19a941283ef63a0fead898e9faff5d0f08c7a", "size": 1152, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/subspaceangles.jl", "max_stars_repo_name": "eschnett/FastTransforms.jl", "max_stars_repo_head_hexsha": "2ee166d75ab09b8b444fb18b6a251ba74df5c10a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 138, "max_stars_repo_stars_event_min_datetime": "2019-04-13T05:52:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T10:03:15.000Z", "max_issues_repo_path": "examples/subspaceangles.jl", "max_issues_repo_name": "eschnett/FastTransforms.jl", "max_issues_repo_head_hexsha": "2ee166d75ab09b8b444fb18b6a251ba74df5c10a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 113, "max_issues_repo_issues_event_min_datetime": "2019-04-12T20:11:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T16:16:28.000Z", "max_forks_repo_path": "examples/subspaceangles.jl", "max_forks_repo_name": "eschnett/FastTransforms.jl", "max_forks_repo_head_hexsha": "2ee166d75ab09b8b444fb18b6a251ba74df5c10a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2019-04-23T08:43:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T15:35:17.000Z", "avg_line_length": 38.4, "max_line_length": 204, "alphanum_fraction": 0.6788194444, "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813513911655, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.80870519441733}} {"text": "using LinearAlgebra\nusing SparseArrays\nusing Plots\nusing ForwardDiff\nusing FastGaussQuadrature # more accurate quadrature\n\n\"This routine solves Poisson's equation -u''(x) = f(x) in weak form using piecewise\nlinear finite element methods. It's used to illustrate convergence in different norms.\"\n\nm = 200 # number of elements\n\n# Manufactured solution\nuexact(x) = log(2+sin(4*pi*x))\ndudx_exact(x) = ForwardDiff.derivative(uexact,x)\nf(x) = -ForwardDiff.derivative(dudx_exact,x) # -d/dx (κ(x)*du/dx) = f\nα = uexact(-1)\nβ = uexact(1)\n\n# define spatial grid\nx = LinRange(-1,1,m+2) # x_0, x_1, ..., x_m, x_{m+1} = x_0\n# x = @. x + randn() / (2*m) # randomly perturb nodes\n# x[1] = -1; x[end] = 1 # reset endpoints\n\n# define local FEM basis\nrq,wq = gausslegendre(100) # define overkill-accurate Gauss quadrature\nλ(r) = [(1 .-r)./2 (1 .+r)./2]\n#dλ(r) = [-.5*ones(length(r)) .5*ones(length(r))]\ndλ(r) = [-.5 .5]\nmap_point(x,a,b) = a + (b-a) * (1+x)/2 # maps x ∈ [-1,1] to interval [a,b]\n\n\"∫u' * ϕ_i' = ∫f(x)*ϕ_i(x)\"\nA = spzeros(m+2,m+2)\nA_local = [1 -1;-1 1]\nb = zeros(m+2)\nfor e = 1:m+1 # loop over the intervals\n ids = e:e+1\n h_e = x[e+1]-x[e]\n\n x_midpt = .5*(x[e+1]+x[e])\n A[ids,ids] .+= A_local * 1/h_e\n\n # # one point midpoint quadrature\n # b[ids] .+= h_e / 2.0 * f(.5*(x[e]+x[e+1])) # f(.5*(x_i+x_i+1))\n\n # higher accuracy Gauss quadrature\n xq = map_point.(rq,x[e],x[e+1])\n b[ids] .+= h_e / 2.0 * λ(rq)'*(wq.*f.(xq)) # ∑_k f(x_k) * w_k * ϕ_i(x_k)\nend\n\n# impose Dirichlet BCs on both sides\nb̃ = b - vec(A[:,1]*α)\nb̃[1] = α\nA[1,:] .= 0\nA[:,1] .= 0\nA[1,1] = 1\n\nb̃ = b̃ - vec(A[:,m+2]*β)\nb̃[m+2] = β\nA[m+2,:] .= 0\nA[:,m+2] .= 0\nA[m+2,m+2] = 1\n\n# convert b̃ from a SparseVector to a Vector\n# (Julia doesn't currently allow \"\\\" to be applied to SparseVectors)\nu = A\\Vector(b̃)\n\nnodal_err = abs.(u - uexact.(x))\nplot(x,u,mark=:dot,ms=3,legend=false,title=\"Max error at nodes = $(maximum(nodal_err))\")\nxfine = LinRange(-1,1,1000)\nplot!(xfine,uexact.(xfine),legend=false)\n\n# compute H1 and L2 errors\nfunction compute_error(u,m,x,rq,wq)\n H1_err2 = 0.0\n L2_err2 = 0.0\n for e = 1:m+1\n ids = e:e+1\n h_e = x[e+1]-x[e]\n rx = 2 / h_e\n xq = map_point.(rq,x[e],x[e+1])\n dudx_err = rx * dλ(rq)*u[ids] .- dudx_exact.(xq)\n H1_err2 += h_e / 2 * dot(wq, dudx_err.^2)\n\n u_err = λ(rq)*u[ids] - uexact.(xq) # ∫(u-uexact)^2\n L2_err2 += h_e / 2 * dot(wq, u_err.^2)\n end\n return sqrt(H1_err2), sqrt(L2_err2)\nend\nH1_err,L2_err = compute_error(u,m,x,rq,wq)\n@show H1_err # will be proportional to O(h)\n@show L2_err\n", "meta": {"hexsha": "837240bac1e4982b7b86635a7243eeb75a711558", "size": 2577, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "weeks9_to_10/fem_laplace_1D_diff_errors.jl", "max_stars_repo_name": "jlchan/caam452_s21", "max_stars_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-01-29T01:52:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T15:38:43.000Z", "max_issues_repo_path": "weeks9_to_10/fem_laplace_1D_diff_errors.jl", "max_issues_repo_name": "jlchan/caam452_s21", "max_issues_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "weeks9_to_10/fem_laplace_1D_diff_errors.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.0108695652, "max_line_length": 88, "alphanum_fraction": 0.5902211874, "num_tokens": 1065, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533126145178, "lm_q2_score": 0.8670357615200475, "lm_q1q2_score": 0.8084703679846194}} {"text": "export clenshaw_curtis\n\n\"\"\"\n clenshaw_curtis(N)\n\nCompute the nodes `x` and weights `w` for integrating a\ncontinuous functions from [-1,1] using the Clenshaw-Curtis\nintegration rule with order `N`.\n\"\"\"\nfunction clenshaw_curtis(N::Int64)\n\n\n @assert N>0 \"Order must be greater than 0\"\n\n x = zeros(N)\n w = ones(N)\n\n\n if N==1\n #x[1]=0.0\n w[1] = 2.0\n return x, w\n end\n\n # Compute x values\n @inbounds for i=1:N\n x[i] = cos((N-i)*π/(N-1))\n end\n\n n = N\n x[1] = -1.0\n\n if mod(n,2)==1\n x[ceil(Int64, (n+1)/2)] = 0.0\n end\n\n x[n] = 1.0\n\n @inbounds for i=1:n\n θ = (i-1)*π/(n-1)\n for j=1:ceil(Int64,(n-1)/2)\n if 2*j == n-1\n b = 1.0\n else\n b = 2.0\n end\n\n w[i] -= b*cos(2*j*θ)/(4*j*j-1)\n end\n end\n\n w[1] *= 1/(n-1)\n w[2:n] .*= 2.0/(n-1)\n w[n] *= 1/(n-1)\n\n return x, w\nend\n", "meta": {"hexsha": "645ce7d17df43c28ce11c8c69f4c9fe5c3fe72d7", "size": 945, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/tools/clenshaw_curtis.jl", "max_stars_repo_name": "mleprovost/TransportBasedInference.jl", "max_stars_repo_head_hexsha": "bdcedf72e9ea23c24678fe6af7a00202c5f9d5d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-23T03:16:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T03:16:56.000Z", "max_issues_repo_path": "src/tools/clenshaw_curtis.jl", "max_issues_repo_name": "mleprovost/TransportBasedInference.jl", "max_issues_repo_head_hexsha": "bdcedf72e9ea23c24678fe6af7a00202c5f9d5d7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tools/clenshaw_curtis.jl", "max_forks_repo_name": "mleprovost/TransportBasedInference.jl", "max_forks_repo_head_hexsha": "bdcedf72e9ea23c24678fe6af7a00202c5f9d5d7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.2931034483, "max_line_length": 58, "alphanum_fraction": 0.4518518519, "num_tokens": 378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951643678381, "lm_q2_score": 0.865224084314688, "lm_q1q2_score": 0.8084612004782351}} {"text": "# Description:\n# Dimensions: 2\n\n# The plot on the left shows the three-hump Camel function on its recommended input domain, and the plot on the right shows only a portion of this domain, to allow for easier viewing of the function's key characteristics. The function has three local minima.\n\n# Input Domain:\n# The function is usually evaluated on the square xi ∈ [-5, 5], for all i = 1, 2.\n\n# Global Minimum:\n# https://www.sfu.ca/~ssurjano/camel33.png\n\nfunction threeHumpCamel(xx)\n\n x1 = xx[1];\n x2 = xx[2];\n\n term1 = 2 * x1^2;\n term2 = -1.05 * x1^4;\n term3 = x1^6 / 6;\n term4 = x1 * x2;\n term5 = x2^2;\n\n y = term1 + term2 + term3 + term4 + term5;\n\n return [y]\nend\n\n", "meta": {"hexsha": "afda7c92be3ee2bd4e760c8271bb00520bedc2e1", "size": 693, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "three-hump-camel.jl", "max_stars_repo_name": "cagataycali/bacterial-foraging-optimization-algorithm", "max_stars_repo_head_hexsha": "b84ac0667707e36dbaa4a50457074245b174b491", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "three-hump-camel.jl", "max_issues_repo_name": "cagataycali/bacterial-foraging-optimization-algorithm", "max_issues_repo_head_hexsha": "b84ac0667707e36dbaa4a50457074245b174b491", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "three-hump-camel.jl", "max_forks_repo_name": "cagataycali/bacterial-foraging-optimization-algorithm", "max_forks_repo_head_hexsha": "b84ac0667707e36dbaa4a50457074245b174b491", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.75, "max_line_length": 258, "alphanum_fraction": 0.6536796537, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611631680358, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.8084566634957528}} {"text": "require(\"bspline.jl\")\n\nfunction exercise_zero()\n controlPoints = [\n [-0.2 2];\n [-0.3 6.2];\n [-1.2 4.8];\n [-2.8 8.8];\n [-0.7 14];\n [1.4 14.7];\n [3.6 10.2];\n [3.2 5.1];\n [1.5 6.2];\n [1.4 2];\n ]\n\n\n ## continuityVector = ones(length(controlPoints[:,1]))\n k = 4\n extendedPartition = extendedPartitionAttempt(k, ones(6), Clumped())\n M = sum(ones(6))\n matrix = buildFunctionsMatrix(k, M, extendedPartition)\n fittingPoints = 200\n bspline = drawCurve(extendedPartition, k, M, controlPoints, matrix, fittingPoints)\n \n writeArrayForGnuplot(controlPoints,\n \"exercise-zero-clumped-control-poly.coordinates\")\n\n writeArrayForGnuplot(bspline,\n \"exercise-zero-clumped-bspline.coordinates\")\n\n extendedPartition = extendedPartitionAttempt(k, ones(6), Uniformed())\n M = sum(ones(6))\n matrix = buildFunctionsMatrix(k, M, extendedPartition)\n fittingPoints = 200\n bspline = drawCurve(extendedPartition, k, M, controlPoints, matrix, fittingPoints)\n \n writeArrayForGnuplot(controlPoints,\n \"exercise-zero-uniformed-control-poly.coordinates\")\n\n writeArrayForGnuplot(bspline,\n \"exercise-zero-uniformed-bspline.coordinates\")\n\n\n closedControlPoints = [controlPoints; controlPoints[1,:];]\n closedBSpline = drawBSpline(k, closedControlPoints, 200)\n writeArrayForGnuplot(closedControlPoints,\n \"exercise-zero-closed-control-poly.coordinates\")\n\n writeArrayForGnuplot(closedBSpline,\n \"exercise-zero-closed-bspline.coordinates\")\n\n \nend\n\nfunction exercise_one()\n controlPoints = [\n [-2.5 -1];\n [-3 2];\n [0.3 2.0];\n [-0.3 -2.0];\n [4 -2.0];\n [3 1.0];\n ]\n\n writeArrayForGnuplot(controlPoints,\n \"exercise-one-control-poly.coordinates\")\n \n fittingPoints = 200\n \n k = 2\n continuityVector = ones(4)\n k_two_extendedPartition = extendedPartitionAttempt(k, continuityVector, Clumped())\n M = sum(continuityVector)\n matrix = buildFunctionsMatrix(k, M, k_two_extendedPartition)\n k_two_bspline = drawCurve(k_two_extendedPartition,\n k,\n M,\n controlPoints,\n matrix,\n fittingPoints)\n writeArrayForGnuplot(k_two_bspline,\n \"exercise-one-clumped-bspline-k-two.coordinates\")\n\n k = 3\n continuityVector = ones(3)\n k_three_extendedPartition = extendedPartitionAttempt(k, continuityVector, Clumped())\n M = sum(continuityVector)\n matrix = buildFunctionsMatrix(k, M, k_three_extendedPartition)\n k_three_bspline = drawCurve(k_three_extendedPartition,\n k,\n M,\n controlPoints,\n matrix,\n fittingPoints)\n writeArrayForGnuplot(k_three_bspline,\n \"exercise-one-clumped-bspline-k-three.coordinates\")\n\n k = 4\n continuityVector = ones(2)\n k_four_extendedPartition = extendedPartitionAttempt(k, continuityVector, Clumped())\n M = sum(continuityVector)\n matrix = buildFunctionsMatrix(k, M, k_four_extendedPartition)\n k_four_bspline = drawCurve(k_four_extendedPartition,\n k,\n M,\n controlPoints,\n matrix,\n fittingPoints)\n writeArrayForGnuplot(k_four_bspline,\n \"exercise-one-clumped-bspline-k-four.coordinates\")\n\n k = 5\n continuityVector = ones(1)\n k_five_extendedPartition = extendedPartitionAttempt(k, continuityVector, Clumped())\n M = sum(continuityVector)\n matrix = buildFunctionsMatrix(k, M, k_five_extendedPartition)\n k_five_bspline = drawCurve(k_five_extendedPartition,\n k,\n M,\n controlPoints,\n matrix,\n fittingPoints)\n writeArrayForGnuplot(k_five_bspline,\n \"exercise-one-clumped-bspline-k-five.coordinates\")\n\n k = 6\n continuityVector = ones(0)\n k_six_extendedPartition = extendedPartitionAttempt(k, continuityVector, Clumped())\n M = sum(continuityVector)\n matrix = buildFunctionsMatrix(k, M, k_six_extendedPartition)\n k_six_bspline = drawCurve(k_six_extendedPartition,\n k,\n M,\n controlPoints,\n matrix,\n fittingPoints)\n writeArrayForGnuplot(k_six_bspline,\n \"exercise-one-clumped-bspline-k-six.coordinates\")\n\nend\n\nfunction exercise_two()\n controlPoints = [\n [-0.7 -0.4];\n [-1 -1];\n [-1.3 -0.3];\n [-1 1.2];\n [-0.3 1.4];\n [-0.15 0];\n [0.15 0];\n [0.3 1.6];\n [2 0.6];\n [2.6 0.2];\n ]\n\n writeArrayForGnuplot(controlPoints,\n \"exercise-two-control-poly.coordinates\")\n\n k = 4\n extendedPartition = expandPartition(0:10, [4 [1 for _ in 1:10]'])\n extendedPartition = normalizeRespect(extendedPartition, Maximum(), k)\n M = sum(ones(6))\n matrix = buildFunctionsMatrix(k, M, extendedPartition)\n fittingPoints = 200\n bspline = drawCurve(extendedPartition,\n k,\n M,\n controlPoints,\n matrix,\n fittingPoints) \n\n writeArrayForGnuplot(bspline,\n \"exercise-two-bspline-first.coordinates\")\n\n k = 4\n extendedPartition = expandPartition(0:4, [4 2 2 2 4])\n extendedPartition = normalizeRespect(extendedPartition, Maximum())\n M = sum(ones(6))\n matrix = buildFunctionsMatrix(k, M, extendedPartition)\n fittingPoints = 200\n bspline = drawCurve(extendedPartition, k, M, controlPoints, matrix, fittingPoints) \n\n writeArrayForGnuplot(bspline,\n \"exercise-two-bspline-second.coordinates\")\n\n k = 6\n extendedPartition = expandPartition(0:5, [6 1 1 1 1 6])\n extendedPartition = normalizeRespect(extendedPartition, Maximum())\n M = sum(ones(4))\n matrix = buildFunctionsMatrix(k, M, extendedPartition)\n fittingPoints = 200\n bspline = drawCurve(extendedPartition, k, M, controlPoints, matrix, fittingPoints) \n\n writeArrayForGnuplot(bspline,\n \"exercise-two-bspline-three.coordinates\")\n\n k = 6\n extendedPartition = expandPartition(0:4, [6 1 1 2 6])\n extendedPartition = normalizeRespect(extendedPartition, Maximum())\n M = sum(ones(4))\n matrix = buildFunctionsMatrix(k, M, extendedPartition)\n fittingPoints = 200\n bspline = drawCurve(extendedPartition, k, M, controlPoints, matrix, fittingPoints) \n\n writeArrayForGnuplot(bspline,\n \"exercise-two-bspline-four.coordinates\")\n\n k = 8\n extendedPartition = expandPartition(0:3, [8 1 1 8])\n extendedPartition = normalizeRespect(extendedPartition, Maximum())\n M = sum(ones(2))\n matrix = buildFunctionsMatrix(k, M, extendedPartition)\n fittingPoints = 200\n bspline = drawCurve(extendedPartition, k, M, controlPoints, matrix, fittingPoints) \n\n writeArrayForGnuplot(bspline,\n \"exercise-two-bspline-five.coordinates\")\n\n \nend\n\nfunction exercise_three()\n controlPoints = [\n [-3.0 2];\n [-1.0 -2];\n [1 1.0];\n [1 1.0];\n [3.0 -2];\n [5 3.0];\n ]\n\n writeArrayForGnuplot(controlPoints,\n \"exercise-three-control-poly.coordinates\")\n \n fittingPoints = 200\n \n k = 3\n continuityVector = ones(3)\n extendedPartition = extendedPartitionAttempt(k, continuityVector, Clumped())\n M = sum(continuityVector)\n matrix = buildFunctionsMatrix(k, M, extendedPartition)\n bspline = drawCurve(extendedPartition,\n k,\n M,\n controlPoints,\n matrix,\n fittingPoints)\n writeArrayForGnuplot(bspline,\n \"exercise-three-bspline.coordinates\")\nend\n\nfunction exercise_four()\n controlPoints = [\n [-2.0 2];\n [-3.0 4];\n [0 6];\n [0 6];\n [3 4];\n [2.0 2];\n ]\n\n writeArrayForGnuplot(controlPoints,\n \"exercise-four-control-poly.coordinates\")\n \n fittingPoints = 200\n \n k = 4\n ## continuityVector = ones(3)\n ## extendedPartition = extendedPartitionAttempt(k, continuityVector, Clumped())\n extendedPartition = [0 0 0 0 1/4 3/4 1 1 1 1]\n M = 2\n matrix = buildFunctionsMatrix(k, M, extendedPartition)\n bspline = drawCurve(extendedPartition,\n k,\n M,\n controlPoints,\n matrix,\n fittingPoints)\n writeArrayForGnuplot(bspline,\n \"exercise-four-bspline-first-partition.coordinates\")\n\n extendedPartition = [0 0 0 0 1/2 1/2 1 1 1 1]\n M = 2\n matrix = buildFunctionsMatrix(k, M, extendedPartition)\n bspline = drawCurve(extendedPartition,\n k,\n M,\n controlPoints,\n matrix,\n fittingPoints)\n writeArrayForGnuplot(bspline,\n \"exercise-four-bspline-second-partition.coordinates\")\n\nend\n\n\nfunction exercise_five()\n controlPoints = [\n [-2.0 1];\n [-1.0 -1];\n [0 1];\n [1 -1];\n [2.0 1];\n ]\n\n writeArrayForGnuplot(controlPoints,\n \"exercise-five-control-poly.coordinates\")\n \n fittingPoints = 200\n \n k = 4\n continuityVector = ones(1)\n extendedPartition = extendedPartitionAttempt(k, continuityVector, Clumped())\n M = sum(continuityVector)\n matrix = buildFunctionsMatrix(k, M, extendedPartition)\n bspline = drawCurve(extendedPartition,\n k,\n M,\n controlPoints,\n matrix,\n fittingPoints)\n writeArrayForGnuplot(bspline,\n \"exercise-five-bspline-single.coordinates\")\n\n controlPoints = [\n [-2.0 1];\n [-1.0 -1];\n [0 1];\n [0 1];\n [1 -1];\n [2.0 1];\n ]\n\n fittingPoints = 200\n \n k = 4\n continuityVector = ones(2)\n extendedPartition = extendedPartitionAttempt(k, continuityVector, Clumped())\n M = sum(continuityVector)\n matrix = buildFunctionsMatrix(k, M, extendedPartition)\n bspline = drawCurve(extendedPartition,\n k,\n M,\n controlPoints,\n matrix,\n fittingPoints)\n writeArrayForGnuplot(bspline,\n \"exercise-five-bspline-doubled.coordinates\")\n\n \n controlPoints = [\n [-2.0 1];\n [-1.0 -1];\n [0 1];\n [0 1];\n [0 1];\n [1 -1];\n [2.0 1];\n ]\n\n fittingPoints = 200\n \n k = 4\n continuityVector = ones(3)\n extendedPartition = extendedPartitionAttempt(k, continuityVector, Clumped())\n M = sum(continuityVector)\n matrix = buildFunctionsMatrix(k, M, extendedPartition)\n bspline = drawCurve(extendedPartition,\n k,\n M,\n controlPoints,\n matrix,\n fittingPoints)\n writeArrayForGnuplot(bspline,\n \"exercise-five-bspline-tripled.coordinates\")\n\nend\n\nfunction exercise_six()\n\n k = 4\n \n firstClosedControlPoints = [\n [1.0 4];\n [-0.8 4];\n [-1.9 8.2];\n [0.3 13.2];\n [2.8 4];\n [1.0 4];\n ]\n\n firstClosedBSpline = drawBSpline(k, firstClosedControlPoints, 200)\n writeArrayForGnuplot(firstClosedControlPoints,\n \"exercise-six-first-closed-control-poly.coordinates\")\n\n writeArrayForGnuplot(firstClosedBSpline,\n \"exercise-six-first-closed-bspline.coordinates\")\n\n secondClosedControlPoints = [\n [0.4 6];\n [-1.8 3];\n [-2 14.8];\n [0.4 11];\n [3.0 14];\n [3.4 2.2];\n [0.4 6];\n ]\n \n secondClosedBSpline = drawBSpline(k, secondClosedControlPoints, 200)\n writeArrayForGnuplot(secondClosedControlPoints,\n \"exercise-six-second-closed-control-poly.coordinates\")\n\n writeArrayForGnuplot(secondClosedBSpline,\n \"exercise-six-second-closed-bspline.coordinates\")\n\n \nend\n\nfunction exercise_knotsInsertion()\n controlPoints = [\n [0.0 0.0];\n [1.0 2.0];\n [2.0 2.5];\n [3.0 2.2];\n [4.0 0.5];\n ]\n\n partition = [-1; 0.5; 1.8; 2.8; 3.2; 4;]\n\n k = 3\n refined_controlPoints =\n knotsInsertion_head(controlPoints, partition, k, 1)\n \n writeArrayForGnuplot(controlPoints,\n \"exercise-knots-insertion-original-control-points.coordinates\")\n\n writeArrayForGnuplot(refined_controlPoints,\n \"exercise-knots-insertion.coordinates\")\n \n ## deBoorBSpline = drawBSpline(k, controlPoints, 200)\n ## writeArrayForGnuplot(deBoorBSpline,\n ## \"exercise-knots-insertion-deBoor.coordinates\")\n\n \nend\n", "meta": {"hexsha": "a324f8ef946f5db9caf5e3748db4b4821b8d3223", "size": 15033, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "b-splines/exercises.jl", "max_stars_repo_name": "massimo-nocentini/cagd", "max_stars_repo_head_hexsha": "baec0824951ebc17e23e16e71339dd8fd79b11c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "b-splines/exercises.jl", "max_issues_repo_name": "massimo-nocentini/cagd", "max_issues_repo_head_hexsha": "baec0824951ebc17e23e16e71339dd8fd79b11c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "b-splines/exercises.jl", "max_forks_repo_name": "massimo-nocentini/cagd", "max_forks_repo_head_hexsha": "baec0824951ebc17e23e16e71339dd8fd79b11c2", "max_forks_repo_licenses": ["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.6308724832, "max_line_length": 89, "alphanum_fraction": 0.5024279918, "num_tokens": 3268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960361162033533, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.8084566625406994}} {"text": "using QuadGK\r\n\r\n\r\nfunction main()\r\n\r\n f(x) = x^2\r\n g(x) = x^4\r\n h(x) = (x+1)^(-1)\r\n\r\n a = 0\r\n b = 2\r\n n = 10\r\n\r\n println(simpsons(f, a, b, n))\r\n println(quadgk(f, a, b, rtol=1e-5))\r\n\r\n println(simpsons(g, a, b, n))\r\n println(quadgk(g, a, b, rtol=1e-5))\r\n\r\n println(simpsons(h, a, b, n))\r\n println(quadgk(h, a, b, rtol=1e-5))\r\nend\r\n\r\n\r\nfunction simpsons(df, a, b, n)\r\n\r\n # n should be even\r\n h = (b - a) / n\r\n\r\n xi0 = df(a) + df(b) # end points\r\n xi1 = 0 # odd points\r\n xi2 = 0 # even points\r\n\r\n # performing integration\r\n for i in 1:n-1\r\n\r\n x = a + i*h\r\n\r\n # if even add to xi2\r\n if i%2 == 0\r\n xi2 += df(x)\r\n else\r\n # else odd add to xi1\r\n xi1 += df(x)\r\n end\r\n end\r\n\r\n # add everything togeteher\r\n xi = h*(xi0 + 2*xi2 + 4*xi1)/3\r\n\r\n return xi\r\n\r\nend\r\n\r\nmain()", "meta": {"hexsha": "5123d227c66cd94a4c51f380a190644aeef811dd", "size": 944, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia-learning-src/advance/06-quadratures.jl", "max_stars_repo_name": "nunesmelo/djs-office-hours", "max_stars_repo_head_hexsha": "aa5cc3dfe3072c5608bf25f5dab27cbfa3664713", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2021-03-27T14:23:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T14:50:37.000Z", "max_issues_repo_path": "julia-learning-src/advance/06-quadratures.jl", "max_issues_repo_name": "nunesmelo/djs-office-hours", "max_issues_repo_head_hexsha": "aa5cc3dfe3072c5608bf25f5dab27cbfa3664713", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia-learning-src/advance/06-quadratures.jl", "max_forks_repo_name": "nunesmelo/djs-office-hours", "max_forks_repo_head_hexsha": "aa5cc3dfe3072c5608bf25f5dab27cbfa3664713", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2021-03-29T20:01:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T14:33:47.000Z", "avg_line_length": 17.1636363636, "max_line_length": 46, "alphanum_fraction": 0.4205508475, "num_tokens": 334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611631680359, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.8084566558736834}} {"text": "function eval(membership_function::TriangularMF, x::T) where {T <: Number}\n return maximum([minimum([((x - membership_function.l_vertex) / (membership_function.center - membership_function.l_vertex)), ((membership_function.r_vertex - x) / (membership_function.r_vertex - membership_function.center))]), 0])\nend\n\nfunction mean_at(membership_function::TriangularMF, firing_strength::T) where {T <: Number}\n if firing_strength != 1\n p1 = (membership_function.center - membership_function.l_vertex) * firing_strength + membership_function.l_vertex\n p2 = (membership_function.center - membership_function.r_vertex) * firing_strength + membership_function.r_vertex\n (p1 + p2) / 2\n elseif firing_strength == 1\n return membership_function.center\n end\nend\n\nfunction eval(menbership_function::GaussianMF, x::T) where {T <: Number}\n return exp(- 0.5 * ((x - menbership_function.center) / menbership_function.sigma)^2) \nend\n\nfunction mean_at(membership_function::GaussianMF, firing_strength::T) where {T <: Number}\n return membership_function.center\nend\n\n\nfunction eval(membership_function::BellMF, x::T) where {T <: Number}\n return (1 / (1 + abs((x - membership_function.c) / membership_function.a)^(2 * membership_function.b)))\nend\n\nfunction mean_at(membership_function::BellMF, firing_strength::T) where {T <: Number}\n return membership_function.c\nend\n\nfunction eval(membership_function::TrapezoidalMF, x::T) where {T <: Number}\n return maximum([minimum([((x - membership_function.l_bottom_vertex) / (membership_function.l_top_vertex - membership_function.l_bottom_vertex)), 1, ((membership_function.r_bottom_vertex - x) / (membership_function.r_bottom_vertex - membership_function.r_top_vertex))]), 0])\nend\n\nfunction mean_at(membership_function::TrapezoidalMF, firing_strength::T) where {T <: Number}\n p1 = (membership_function.l_top_vertex - membership_function.l_bottom_vertex) * firing_strength + membership_function.l_bottom_vertex\n p2 = (membership_function.r_top_vertex - membership_function.r_bottom_vertex) * firing_strength + membership_function.r_bottom_vertex\n (p1 + p2) / 2\nend\n\n\nfunction eval(membership_function::SigmoidMF, x::T) where {T <: Number}\n return 1 / (1 + exp(-membership_function.a * (x - membership_function.c)))\nend\n\nfunction mean_at(membership_function::SigmoidMF, firing_strength::T) where {T <: Number}\n if firing_strength == 1\n p_firing_strength = 0.999\n elseif firing_strength == 0\n p_firing_strength = 0.001\n else\n p_firing_strength = firing_strength\n end\n\n p1 = -log((1 / p_firing_strength) - 1) / membership_function.a + membership_function.c\n p2 = membership_function.limit\n (p1 + p2) / 2\nend", "meta": {"hexsha": "8216e61da0324d0f4d71f29b72f2bc12a499d4f9", "size": 2735, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/EvalMF.jl", "max_stars_repo_name": "phelipe/Fuzzy.jl", "max_stars_repo_head_hexsha": "e006ebf495eb75c4fae0cfef4d83a322c796599a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2016-12-11T21:58:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-07T00:35:59.000Z", "max_issues_repo_path": "src/EvalMF.jl", "max_issues_repo_name": "phelipe/Fuzzy.jl", "max_issues_repo_head_hexsha": "e006ebf495eb75c4fae0cfef4d83a322c796599a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2019-09-18T19:05:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-27T15:12:05.000Z", "max_forks_repo_path": "src/EvalMF.jl", "max_forks_repo_name": "phelipe/Fuzzy.jl", "max_forks_repo_head_hexsha": "e006ebf495eb75c4fae0cfef4d83a322c796599a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2018-03-05T19:03:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-07T19:55:42.000Z", "avg_line_length": 46.3559322034, "max_line_length": 278, "alphanum_fraction": 0.7444241316, "num_tokens": 689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067179697694, "lm_q2_score": 0.8577681049901036, "lm_q1q2_score": 0.808452201413371}} {"text": "\"\"\"\n function lagdiff(x::AbstractVector, d=1)\n\nReturns `out[i] = x[i] - x[i-d]` with out padded with missings so that `length(out)==length(x)`.\n\"\"\"\nfunction lagdiff(x::AbstractVector, d=1)\n if d>0\n dx = vcat(fill(missing, d), x[(d+1):end] .- x[1:(end-d)])\n elseif d<0\n dx = vcat(-x[(d+1):end] .+ x[1:(end-d)], fill(missing,d))\n else\n dx = zero(x)\n end\n return(dx)\nend\n\n\"\"\"\n function smooth(x::AbstractVector; w=pdf(Normal(), range(-3, 3, length=7)))\n\nReturns the running weighted mean of x*w. When `n=length(w)`, then\n`out[i] = sum(x[i - n÷2 + j-1] * w[j] for j in 1:n)/sum(w)`.\n\"\"\"\nfunction smooth(x::AbstractVector; w=pdf(Normal(), range(-3, 3, length=7)))\n sx = Vector{Union{Missing, Float64}}(undef, length(x))\n n = length(w)\n if n % 2 != 1\n error(\"only odd length windows allowed\")\n end\n shift = -(n÷2):(n÷2)\n for i in 1:length(sx)\n s = findfirst((i .+ shift) .> 0)\n l = findlast((i .+ shift) .< length(x))\n sx[i] = sum(w[s:l].*x[i .+ shift[s:l]])./sum(w[s:l])\n if isnan(sx[i])\n sx[i] = 0\n end\n end\n return(sx)\nend\n", "meta": {"hexsha": "3b3c967105c3fefd1a0839a9f8a7245a9b93d5e2", "size": 1071, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "schrimpf/CovidRt.jl", "max_stars_repo_head_hexsha": "b3cba5602e1abe21d4ebb318baf783377774a06c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "schrimpf/CovidRt.jl", "max_issues_repo_head_hexsha": "b3cba5602e1abe21d4ebb318baf783377774a06c", "max_issues_repo_licenses": ["MIT"], "max_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": "schrimpf/CovidRt.jl", "max_forks_repo_head_hexsha": "b3cba5602e1abe21d4ebb318baf783377774a06c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.775, "max_line_length": 96, "alphanum_fraction": 0.5704948646, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.942506716354847, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.8084522000281422}} {"text": "## Julia program for Atkinson's Poisson Simulation\r\n## author: weiya \r\n## date: 2018-08-19\r\n\r\nfunction AtkinsonPois(lambda)\r\n # parameters\r\n beta = pi/sqrt(3*lambda)\r\n alpha = lambda*beta\r\n c = 0.767 - 3.36/lambda\r\n k = log(c) - lambda - log(beta)\r\n # step 1: propose new x\r\n u1 = rand()\r\n while true\r\n global x\r\n x = (alpha - log((1-u1)/u1))/beta\r\n x > -0.5 && break\r\n end\r\n while true\r\n # step 2: transform to N \r\n N = floor(Int, x)\r\n u2 = rand()\r\n # step 3: accept or not\r\n lhs = alpha - beta*x + log(u2/(1+exp(alpha-beta*x))^2)\r\n rhs = k + N*log(lambda) - log(factorial(lambda))\r\n if lhs <= rhs\r\n return(N)\r\n end\r\n end\r\nend\r\n\r\n## example\r\nN = 100;\r\nres = ones(Int, N);\r\nfor i = 1:N\r\n res[i] = AtkinsonPois(10)\r\nend\r\n# ans: 8 9 13 10 12 .......\r\n\r\n\r\n# alternative method\r\nfunction SimplePois(lambda)\r\n s = 0\r\n k = 0\r\n while true\r\n u = rand()\r\n x = -log(u)/lambda\r\n s = s + x\r\n if s > 1\r\n return(k)\r\n end\r\n k = k + 1\r\n end\r\nend\r\n\r\n## example for simple poisson\r\nres2 = ones(Int, N);\r\nfor i = 1:N \r\n res2[i] = SimplePois(10)\r\nend\r\n# ans: 5 7 16 7 10 .......", "meta": {"hexsha": "9260f995cebd26de68b119c7ddba09b8c8153eee", "size": 1271, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "GenRV/atkinson-pois.jl", "max_stars_repo_name": "szcf-weiya/MCMC", "max_stars_repo_head_hexsha": "b5353bdd8ca1578a2023676458ab231a413a2b46", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2017-07-19T12:50:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T08:06:50.000Z", "max_issues_repo_path": "GenRV/atkinson-pois.jl", "max_issues_repo_name": "szcf-weiya/MCMC", "max_issues_repo_head_hexsha": "b5353bdd8ca1578a2023676458ab231a413a2b46", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-02-03T15:08:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-05T15:41:39.000Z", "max_forks_repo_path": "GenRV/atkinson-pois.jl", "max_forks_repo_name": "szcf-weiya/MCMC", "max_forks_repo_head_hexsha": "b5353bdd8ca1578a2023676458ab231a413a2b46", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-07-19T12:50:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T08:06:52.000Z", "avg_line_length": 21.1833333333, "max_line_length": 63, "alphanum_fraction": 0.4893784422, "num_tokens": 414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067211996142, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.8084521990434786}} {"text": "using Plots;gr()\n\nf(x) = x*x - 2\n\nfunction bisection(a, b, max_iter)\n c = 1e+9\n error = zeros(max_iter)\n for i in 1:max_iter\n c = (a + b) / 2\n error[i] = abs(c - sqrt(2))\n f_c = f(c)\n\n if (f_c == 0)\n break\n elseif (f_c < 0)\n a = c\n else\n b = c\n end\n end\n\n (c, error)\nend\n\na = 1.0\nb = 2.0\nmax_iter = 20\nc, error = bisection(a, b, max_iter)\nt = 1:max_iter\n\nplot(t, error, color=:cornflowerblue, label=\"bisection\",xlabel=\"t\",ylabel=\"Error\")\nsavefig(\"bisection.png\")", "meta": {"hexsha": "3763709c0270c933f8511894ce2cb4730007b961", "size": 559, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "nonlinear_equation/bisection.jl", "max_stars_repo_name": "nocotan/numerical_calculus.jl", "max_stars_repo_head_hexsha": "76b46b22d04e2e7e82cf44788c4f48ce25d59847", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-01-07T06:26:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-24T06:21:01.000Z", "max_issues_repo_path": "nonlinear_equation/bisection.jl", "max_issues_repo_name": "nocotan/numerical_calculus.jl", "max_issues_repo_head_hexsha": "76b46b22d04e2e7e82cf44788c4f48ce25d59847", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-01-10T08:22:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-08T13:31:00.000Z", "max_forks_repo_path": "nonlinear_equation/bisection.jl", "max_forks_repo_name": "nocotan/numerical_calculus.jl", "max_forks_repo_head_hexsha": "76b46b22d04e2e7e82cf44788c4f48ce25d59847", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-01-10T05:59:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T13:22:34.000Z", "avg_line_length": 17.46875, "max_line_length": 82, "alphanum_fraction": 0.5008944544, "num_tokens": 205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067179697694, "lm_q2_score": 0.8577680977182186, "lm_q1q2_score": 0.8084521945595706}} {"text": "#==============================================================================\n\n Solving the HJB with a state constraint using\n the explicit method\n\n\n\n Translated from matlab code on Ben Moll's website:\n http://www.princeton.edu/~moll/HACTproject.htm\n\n==============================================================================#\n\nusing LinearAlgebra, SparseArrays, Plots\n\nγ = 2 # parameter from CRRA utility\nr = 0.03 # the interest rate\nρ = 0.05 # the discount rate\n\nz1=.1\nz2 =.2\nz= [z1 z2]\n\nλ1 = 0.02\nλ2 = 0.03\n\nλ = [λ1 λ2]\n\nH = 500 # number of points in the grid space\namin=-0.02\namax=2\n\na = LinRange(amin,amax,H)\nda = (amax-amin)/(H-1)\n\naa = [a a]\nzz = ones(H,1)*z\n\nmaxit = 100 # the maximum number of iterations we allow the finite differencing algorithm\ncrit = 10^(-6) # our critical value\nΔ = 1000\n\ndVf=zeros(H,2)\ndVb = zeros(H,2)\nc= zeros(H,2)\n\n# Create the matrix that captures the systems dynamic\nAswitch = [-sparse(I,H,H)*λ[1] sparse(I,H,H)*λ[1]; sparse(I,H,H)*λ[2] -sparse(I,H,H)*λ[2]]\n\n# Inital Guess\nv0=zeros(H,2)\nv0[:,1] = (z[1] .+ r.*a).^(1-γ)/(1-γ)/ρ\nv0[:,2] = (z[2] .+ r.*a).^(1-γ)/(1-γ)/ρ\nglobal v=v0\n\ndist=[]\nV_n=[]\n\n# The finite differeing loop\n\nfor n in 1:maxit\n global V=v\n push!(V_n,V)\n # Forward differencing\n dVf[1:H-1,:]=(V[2:H,:]-V[1:H-1,:])/da\n dVf[H,:] = (z .+ r.*amax).^(-γ) # impose state constraint at the max, just in case\n # Backward differencing\n dVb[2:H,:]=(V[2:H,:]-V[1:H-1,:])/da\n dVb[1,:]= (z .+r.*amin).^(-γ)\n\n # Find consumption and savings with the forward difference\n cf = dVf.^(-1/γ)\n sf = zz +r.*aa -cf\n\n # Find consumption and savings with the backward difference\n cb= dVb.^(-1/γ)\n sb = zz +r.*aa -cb\n\n # Find consumption and savings at steady state\n c0 = zz + r.*aa\n dV0 = c0.^(-γ)\n\n # Now implement the upwind scheme in order to select the best differencing method\n If = sf .> 0\n Ib = sb .< 0\n I0 = (1 .- If - Ib)\n\n # State constraint at amin is automatically implemented\n\n global dV_Upwind = dVf.*If + dVb.*Ib + dV0.*I0\n\n global c = dV_Upwind.^(-1/γ)\n global u = c.^(1-γ)/(1-γ)\n # Construct matrix for the evolution of the system\n X = -min.(sb,0)/da\n Y= -max.(sf,0)/da + min.(sb,0)/da\n Z = max.(sf,0)/da\n\n A1 = spdiagm(0=>Y[:,1], -1 => X[2:H,1], 1=> Z[1:H-1,1])\n A2 = spdiagm(0=>Y[:,2], -1 => X[2:H,2], 1=> Z[1:H-1,2])\n AA = [A1 spzeros(H,H); spzeros(H,H) A2]\n\n A = AA + Aswitch\n\n B = (ρ +1/Δ)*sparse(I,2*H,2*H) -A\n u_stacked = [u[:,1]; u[:,2]]\n V_stacked = [V[:,1]; V[:,2]]\n\n b = u_stacked + V_stacked/Δ\n V_stacked = B\\b # Solves the system of equations\n\n V = [V_stacked[1:H] V_stacked[H+1:2*H]]\n\n V_change = V - v\n\n\n global v = V\n\n push!(dist, findmax(abs.(V_change))[1])\n\n if dist[n] < crit\n println(\"Value Function converged, Iteration=\")\n println(n)\n break\n end\nend\n\n# Graphs\nadot = zz + r.*aa -c\n\nplot(dist[:], xlabel=\"Iteration\", ylabel=\"\\$\\\\lvert V^{n+1}-V^{n}\\\\rvert\\$\")\n\nplot(a,V, xlabel=\"a\", ylabel=\"\\$V_{i}(a)\\$\", xlims=(amin,amax),legend=false)\n\nplot(a,c,xlabel=\"a\", ylabel=\"\\$c_{i}(a)\\$\", xlims=(amin,amax), legend=false)\n\nplot(a, adot, xlabel=\"a\", ylabel=\"\\$s_{i}(a)\\$\", xlims=(amin,amax))\n", "meta": {"hexsha": "cafe3fc7ef432ba2fc84c228bcd48f9a7d18d5d4", "size": 3278, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Moll_Code/Section01-Hugget-Achdou_etal_2017/HJB_stateconstraint_implicit/HJB_state_constraint_implicit.jl", "max_stars_repo_name": "chandlerlester/Radio_Free_Julia", "max_stars_repo_head_hexsha": "16a2e52741e20b5d74cdc01dd2fd0722614a6377", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-02-26T11:52:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-30T12:41:38.000Z", "max_issues_repo_path": "Moll_Code/Section01-Hugget-Achdou_etal_2017/HJB_stateconstraint_implicit/HJB_state_constraint_implicit.jl", "max_issues_repo_name": "chandlerlester/Radio_Free_Julia", "max_issues_repo_head_hexsha": "16a2e52741e20b5d74cdc01dd2fd0722614a6377", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Moll_Code/Section01-Hugget-Achdou_etal_2017/HJB_stateconstraint_implicit/HJB_state_constraint_implicit.jl", "max_forks_repo_name": "chandlerlester/Radio_Free_Julia", "max_forks_repo_head_hexsha": "16a2e52741e20b5d74cdc01dd2fd0722614a6377", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-05-11T08:09:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-30T18:54:12.000Z", "avg_line_length": 23.9270072993, "max_line_length": 90, "alphanum_fraction": 0.5393532642, "num_tokens": 1188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951142225532629, "lm_q2_score": 0.849971175657575, "lm_q1q2_score": 0.8084434756535309}} {"text": "# # [Sparse linear regression](@id sparse_linreg)\n# \n# Let's look at a least squares regression problem with L1 regularization:\n# we will use the \"diabetes dataset\" (see [here](https://www4.stat.ncsu.edu/~boos/var.select/)), so let's start by loading the data.\n\nusing HTTP\n\nsplitlines(s) = split(s, \"\\n\")\nsplitfields(s) = split(s, \"\\t\")\nparsefloat64(s) = parse(Float64, s)\n\nfunction load_diabetes_dataset()\n res = HTTP.request(\"GET\", \"https://www4.stat.ncsu.edu/~boos/var.select/diabetes.tab.txt\") \n lines = res.body |> String |> strip |> splitlines\n return hcat((line |> splitfields .|> parsefloat64 for line in lines[2:end])...)'\nend\n\ndata = load_diabetes_dataset()\n\ntraining_input = data[1:end-100, 1:end-1]\ntraining_label = data[1:end-100, end]\n\ntest_input = data[end-99:end, 1:end-1]\ntest_label = data[end-99:end, end]\n\nn_training, n_features = size(training_input)\n\n# Now we can set up the optimization problem we want to solve: we will minimize the mean squared error\n# for a linear model, appropriately scaled so that the features in the training data are normally distributed\n# (\"standardization\", this is known to help the optimization process).\n# \n# After some simple manipulation, this standardized linear model can be implemented as follows:\n\nusing LinearAlgebra\nusing Statistics\n\ninput_loc = mean(training_input, dims=1) |> vec\ninput_scale = std(training_input, dims=1) |> vec\n\nlinear_model(wb, input) = input * wb[1:end-1] .+ wb[end]\n\nfunction standardized_linear_model(wb, input)\n w_scaled = wb[1:end-1] ./ input_scale\n wb_scaled = vcat(w_scaled, wb[end] - dot(w_scaled, input_loc))\n return linear_model(wb_scaled, input)\nend\n\n# The loss term in the cost is then the following. Note that this is a regular Julia function:\n# since the algorithm we will apply requires its gradient, automatic differentiation will\n# do the work for us.\n\nmean_squared_error(label, output) = mean((output .- label) .^ 2) / 2\n\ntraining_loss(wb) = mean_squared_error(training_label, standardized_linear_model(wb, training_input))\n\n# As regularization we will use the L1 norm, implemented in [ProximalOperators](https://github.com/JuliaFirstOrder/ProximalOperators.jl):\n\nusing ProximalOperators\n\nreg = ProximalOperators.NormL1(1)\n\n# We want to minimize the sum of `training_loss` and `reg`, and for this task we can use `FastForwardBackward`,\n# which implements the fast proximal gradient method (also known as fast forward-backward splitting, or FISTA).\n# Therefore we construct the algorithm, then apply it to our problem by providing a starting point,\n# and the objective terms `f=training_loss` (smooth) and `g=reg` (non smooth).\n\nusing ProximalAlgorithms\n\nffb = ProximalAlgorithms.FastForwardBackward()\nsolution, iterations = ffb(x0=zeros(n_features + 1), f=training_loss, g=reg)\n\n# We can now check how well the trained model performs on the test portion of our data.\n\ntest_output = standardized_linear_model(solution, test_input)\nmean_squared_error(test_label, test_output)\n", "meta": {"hexsha": "169b96ef6a55246a4e3895c2cbdf8983b2415405", "size": 2991, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/examples/sparse_linear_regression.jl", "max_stars_repo_name": "Playfloor/ProximalAlgorithms.jl", "max_stars_repo_head_hexsha": "5c34c1e91d509178cca60075f47f1eae7091238c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-04T16:18:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T16:18:36.000Z", "max_issues_repo_path": "docs/src/examples/sparse_linear_regression.jl", "max_issues_repo_name": "aldma/ProximalAlgorithms.jl", "max_issues_repo_head_hexsha": "f03bfa74ce31f7b325c460d51dc256ce1e4ef1a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/src/examples/sparse_linear_regression.jl", "max_forks_repo_name": "aldma/ProximalAlgorithms.jl", "max_forks_repo_head_hexsha": "f03bfa74ce31f7b325c460d51dc256ce1e4ef1a6", "max_forks_repo_licenses": ["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.3552631579, "max_line_length": 137, "alphanum_fraction": 0.7552657974, "num_tokens": 761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422199928904, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.8084434745596312}} {"text": "#=\n\nPlot the price-dividend ratio in the risk neutral case, for the Markov asset pricing\nlecture.\n\n=#\nusing QuantEcon\nusing Plots\nusing LaTeXStrings\n\npyplot()\n\nn = 25 # size of state space\nbeta = 0.9\nmc = tauchen(n, 0.96, 0.02) \n\nK = mc.p .* reshape(exp(mc.state_values), 1, n)\n\nI = eye(n)\nv = (I - beta * K) \\ (beta * K * ones(n, 1))\n\nplot(mc.state_values, \n v, \n lw=2, \n ylabel=\"price-dividend ratio\", \n xlabel=\"state\", \n alpha=0.7, \n label=L\"$v$\")\n", "meta": {"hexsha": "2c9ba5fd1a3e04623f6becd77ffbd2943846c96b", "size": 472, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "markov_asset/v_plots.jl", "max_stars_repo_name": "mwhchen/quantecon", "max_stars_repo_head_hexsha": "1a401e3453cbccbcf609945fced1b478b945446e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2018-05-02T22:12:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T01:07:33.000Z", "max_issues_repo_path": "markov_asset/v_plots.jl", "max_issues_repo_name": "mwhchen/quantecon", "max_issues_repo_head_hexsha": "1a401e3453cbccbcf609945fced1b478b945446e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "markov_asset/v_plots.jl", "max_forks_repo_name": "mwhchen/quantecon", "max_forks_repo_head_hexsha": "1a401e3453cbccbcf609945fced1b478b945446e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2017-11-11T22:38:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T20:33:03.000Z", "avg_line_length": 16.275862069, "max_line_length": 84, "alphanum_fraction": 0.6101694915, "num_tokens": 164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9489172659321807, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.8084327288974198}} {"text": "function agm(x, y, e::Real = 5)\n (x ≤ 0 || y ≤ 0 || e ≤ 0) && throw(DomainError(\"x, y must be strictly positive\"))\n g, a = minmax(x, y)\n while e * eps(x) < a - g\n a, g = (a + g) / 2, sqrt(a * g)\n end\n a\nend\n\nx, y = 1.0, 1 / √2\nprintln(\"# Using literal-precision float numbers:\")\n@show agm(x, y)\n\nprintln(\"# Using half-precision float numbers:\")\nx, y = Float32(x), Float32(y)\n@show agm(x, y)\n\nprintln(\"# Using \", precision(BigFloat), \"-bit float numbers:\")\nx, y = big(1.0), 1 / √big(2.0)\n@show agm(x, y)\n", "meta": {"hexsha": "7c0ca71d512027c1b5e849f08b1819345a5896e2", "size": 525, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/arithmetic-geometric-mean.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/arithmetic-geometric-mean.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/arithmetic-geometric-mean.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0, "max_line_length": 85, "alphanum_fraction": 0.5523809524, "num_tokens": 197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582516374121, "lm_q2_score": 0.8688267864276108, "lm_q1q2_score": 0.808407052675186}} {"text": "\n\"\"\"\n$(SIGNATURES)\n\"\"\"\naverage(m::AbstractMatrix) = (sum(m) / length(m))\n\n\n\"\"\"\n$(SIGNATURES)\n\"\"\"\naverage_absolute(m::AbstractMatrix) = (sum(abs.(m)) / length(m))\n\n\n\"\"\"\n$(SIGNATURES)\n\"\"\"\ntest_average_absolute(m::AbstractMatrix) = (average_absolute(m)) < 1e6\n\n\n\"\"\"\n$(SIGNATURES)\n\"\"\"\nfunction smallest_positive(x1::Float64, x2::Float64)\n (x1 > 0.0 && x2 < 0.0) && return x1\n (x1 < 0.0 && x2 > 0.0) && return x2\n (x1 > 0.0 && x2 > 0.0) && return min(x1, x2)\n return nothing\nend\n\n\n\"\"\"\n$(SIGNATURES)\n\nApproximates the gradient of a scalar field.\n\"\"\"\nfunction ∇(ϕ::AbstractMatrix{Float64})\n height, width = size(ϕ)\n\n # x, y only represents the first and the second variables. No reference to graphical representations.\n ∇ϕx = zeros(Float64, height, width) # divergence on the right edge will be filled with zeros\n ∇ϕy = zeros(Float64, height, width) # divergence on bottom edge will be filled with zeros\n\n ∇ϕx[begin:end-1, :] = ϕ[begin+1:end, :] - ϕ[begin:end-1, :]\n ∇ϕy[:, begin:end-1] = ϕ[:, begin+1:end] - ϕ[:, begin:end-1]\n\n fill_borders!(∇ϕx, 0.0)\n fill_borders!(∇ϕy, 0.0)\n\n return ∇ϕx, ∇ϕy\nend\n\n\n\"\"\"\n$(SIGNATURES)\n\nCalculate the second-order Laplace operator by convolution of a kernel.\n\"\"\"\nfunction laplacian(ϕ::AbstractMatrix{Float64})\n height, width = size(ϕ)\n\n # Embed matrix within a larger matrix for better vectorization and avoid duplicated code\n # Padded matrix adds 1 row/col after the size of ϕ.\n # ϕ is inserted in padded matrix within 1:1+height+1 x 1:1+width+1.\n # The rest of the padded matrix (its borders) are set at 0.0.\n padded_ϕ = zeros(Float64, 1 + height + 1, 1 + width + 1)\n padded_ϕ[begin+1:end-1, begin+1:end-1] .= ϕ[1:end, 1:end]\n\n # Convolution = up + down + left + right\n ∇²ϕ =\n padded_ϕ[begin+1-1:end-1-1, begin+1:end-1] +\n padded_ϕ[begin+1+1:end-1+1, begin+1:end-1] +\n padded_ϕ[begin+1:end-1, begin+1-1:end-1-1] +\n padded_ϕ[begin+1:end-1, begin+1+1:end-1+1] -\n 4.0 * padded_ϕ[begin+1:end-1, begin+1:end-1]\n\n return ∇²ϕ[1:end-1, 1:end-1]\nend\n", "meta": {"hexsha": "148548ab88ba5ff1466b741fe61249be39fc45ed", "size": 2079, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math_utilities.jl", "max_stars_repo_name": "Emmanuel-R8/causticsEngineering", "max_stars_repo_head_hexsha": "485873b5e6de8ab4b428f724607f7190fdbec92f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-10-01T13:09:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-01T13:09:19.000Z", "max_issues_repo_path": "src/math_utilities.jl", "max_issues_repo_name": "Emmanuel-R8/causticsEngineering", "max_issues_repo_head_hexsha": "485873b5e6de8ab4b428f724607f7190fdbec92f", "max_issues_repo_licenses": ["MIT"], "max_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_utilities.jl", "max_forks_repo_name": "Emmanuel-R8/causticsEngineering", "max_forks_repo_head_hexsha": "485873b5e6de8ab4b428f724607f7190fdbec92f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6538461538, "max_line_length": 105, "alphanum_fraction": 0.6286676287, "num_tokens": 752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.8824278680004707, "lm_q1q2_score": 0.8084006572166577}} {"text": "using Downhill\n\n\"\"\"\n rosenbrock(x; b=2)\n\nReturn the value of Rosenbrock function\n ```math\n \\\\sum_{i=1}^n \\\\right[(1 - x_{i-1})^2 + b (x_i - x_{i-1})^2 \\\\left]\n ```\n in `n = length(x)` dimensions.\n\"\"\"\nfunction rosenbrock(x::AbstractVector{T}; b=2) where {T}\n f = zero(T) * zero(b) # type-generic zero\n for i in firstindex(x)+1:lastindex(x)\n f += (one(T) - x[i-1])^2 + b * (x[i] - x[i-1]^2)^2\n end\n return f\nend\n\n\"\"\"\n drosenbrock(x; b=2)\n\nReturn the gradient of Rosenbrock function\n ```math\n \\\\sum_{i=1}^n \\\\right[(1 - x_{i-1})^2 + b (x_i - x_{i-1})^2 \\\\left]\n ```\n in `n = length(x)` dimensions.\n\"\"\"\nfunction drosenbrock(x::AbstractVector{T}; b=2) where {T}\n g = fill!(similar(x, promote_type(T, typeof(b))), 0)\n for i in firstindex(x)+1:lastindex(x)\n g[i-1] += 2 * (x[i-1] - 1) + 4 * b * x[i-1] * (x[i-1]^2 - x[i])\n g[i] += 2 * b * (x[i] - x[i-1]^2)\n end\n return g\nend\n\n\"\"\"\n rosenbrock!(x, g; b=2)\n\nReturn the value of Rosenbrock function in `length(x)` dimensions.\n\"\"\"\nfunction rosenbrock!(x::AbstractVector, g::AbstractVector; b=2)\n f = zero(eltype(g))\n fill!(g, 0)\n inds = eachindex(x, g)\n for i in 2:last(inds)\n f += (1 - x[i-1])^2 + b * (x[i] - x[i-1]^2)^2\n g[i-1] += 2 * (x[i-1] - 1) + 4 * b * x[i-1] * (x[i-1]^2 - x[i])\n g[i] += 2 * b * (x[i] - x[i-1]^2)\n end\n return f, g\nend\n\nros(x, g) = (rosenbrock(x), drosenbrock(x))\n\nros!(x, g) = rosenbrock!(x, g)\n\nans_nonmutating = let x0 = zeros(2)\n opt = BFGS(x0)\n optresult = optimize!(ros, opt, x0; maxiter=1000)\n println(\"\"\"\n ==Nonmutating gradient evaluation==\n\n Optimization converged: $(optresult.converged)\n Final argument: $(optresult.argument)\n Final gradient: $(optresult.gradient)\n Iteration count: $(optresult.iterations)\n Call count: $(optresult.calls)\n \"\"\")\n optresult.argument\nend\n\nans_mutating = let x0 = zeros(2)\n opt = BFGS(x0)\n optresult = optimize!(ros!, opt, x0; maxiter=1000)\n println(\"\"\"\n ==Mutating gradient evaluation==\n\n Optimization converged: $(optresult.converged)\n Final argument: $(optresult.argument)\n Final gradient: $(optresult.gradient)\n Iteration count: $(optresult.iterations)\n Call count: $(optresult.calls)\n \"\"\")\n optresult.argument\nend\n\n@assert ans_nonmutating ≈ ans_mutating\n", "meta": {"hexsha": "e606acee45946ec171757bf55dee0b1c3354ab67", "size": 2397, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/rosenbrock.jl", "max_stars_repo_name": "vvpisarev/Downhill.jl", "max_stars_repo_head_hexsha": "77fd1a99ac77f66babfb1f0b453aa00861c92acb", "max_stars_repo_licenses": ["MIT"], "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/rosenbrock.jl", "max_issues_repo_name": "vvpisarev/Downhill.jl", "max_issues_repo_head_hexsha": "77fd1a99ac77f66babfb1f0b453aa00861c92acb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2021-12-23T20:04:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-24T10:05:19.000Z", "max_forks_repo_path": "examples/rosenbrock.jl", "max_forks_repo_name": "vvpisarev/Downhill.jl", "max_forks_repo_head_hexsha": "77fd1a99ac77f66babfb1f0b453aa00861c92acb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6333333333, "max_line_length": 71, "alphanum_fraction": 0.5640383813, "num_tokens": 836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096158798117, "lm_q2_score": 0.8824278680004706, "lm_q1q2_score": 0.8084006551955523}} {"text": "\"\"\"\n HermiteWeight()\n\nis a quasi-vector representing `exp(-x^2)` on ℝ.\n\"\"\"\nstruct HermiteWeight{T} <: Weight{T} end\n\nHermiteWeight() = HermiteWeight{Float64}()\naxes(::HermiteWeight{T}) where T = (Inclusion(ℝ),)\nfunction getindex(w::HermiteWeight, x::Number)\n x ∈ axes(w,1) || throw(BoundsError())\n exp(-x^2)\nend\n\nsum(::HermiteWeight{T}) where T = sqrt(convert(T, π))\n\nstruct Hermite{T} <: OrthogonalPolynomial{T} end\nHermite() = Hermite{Float64}()\northogonalityweight(::Hermite{T}) where T = HermiteWeight{T}()\n\n==(::Hermite, ::Hermite) = true\naxes(::Hermite{T}) where T = (Inclusion(ℝ), oneto(∞))\n\n\"\"\"\n hermiteh(n, z)\n\ncomputes the `n`-th Hermite polynomial, orthogonal with \nrespec to `exp(-x^2)`, at `z`.\n\"\"\"\nhermiteh(n::Integer, z::Number) = Base.unsafe_getindex(Hermite{typeof(z)}(), z, n+1)\n\nbroadcasted(::LazyQuasiArrayStyle{2}, ::typeof(*), ::HermiteWeight{T}, ::Hermite{V}) where {T,V} = Weighted(Hermite{promote_type(T,V)}())\n\n# H_{n+1} = 2x H_n - 2n H_{n-1}\n# 1/2 * H_{n+1} + n H_{n-1} = x H_n \n# x*[H_0 H_1 H_2 …] = [H_0 H_1 H_2 …] * [0 1; 1/2 0 2; 1/2 0 3; …] \njacobimatrix(H::Hermite{T}) where T = Tridiagonal(Fill(one(T)/2,∞), Zeros{T}(∞), one(T):∞)\nrecurrencecoefficients(H::Hermite{T}) where T = Fill{T}(2,∞), Zeros{T}(∞), zero(T):2:∞\n\nmassmatrix(::Hermite{T}) where T = Diagonal(sqrt(convert(T,π)) .* convert(T,2) .^ (0:∞) .* factorial.(convert(T,0):∞))\n\n@simplify *(A::QuasiAdjoint{<:Any,<:Weighted{<:Any,<:Hermite}}, B::Hermite) = massmatrix(Hermite{promote_type(eltype(A),eltype(B))}())\n\n##########\n# Derivatives\n##########\n\n@simplify function *(D::Derivative, H::Hermite)\n T = promote_type(eltype(D),eltype(H))\n D = _BandedMatrix((zero(T):2:∞)', ℵ₀, -1,1)\n H*D\nend\n\n@simplify function *(D::Derivative, Q::OrthonormalWeighted{<:Any,<:Hermite})\n X = jacobimatrix(Q.P)\n Q * Tridiagonal(-X.ev, X.dv, X.ev)\nend", "meta": {"hexsha": "f441f963bde344c45de9b5bd0d625c45d6b81286", "size": 1867, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/classical/hermite.jl", "max_stars_repo_name": "ioannisPApapadopoulos/ClassicalOrthogonalPolynomials.jl", "max_stars_repo_head_hexsha": "63610e3236dd7ffa9152db00734aab6af28f1793", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2021-01-26T15:24:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-05T13:53:03.000Z", "max_issues_repo_path": "src/classical/hermite.jl", "max_issues_repo_name": "ioannisPApapadopoulos/ClassicalOrthogonalPolynomials.jl", "max_issues_repo_head_hexsha": "63610e3236dd7ffa9152db00734aab6af28f1793", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 59, "max_issues_repo_issues_event_min_datetime": "2021-01-27T21:38:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T14:54:26.000Z", "max_forks_repo_path": "src/classical/hermite.jl", "max_forks_repo_name": "ioannisPApapadopoulos/ClassicalOrthogonalPolynomials.jl", "max_forks_repo_head_hexsha": "63610e3236dd7ffa9152db00734aab6af28f1793", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-01-27T11:21:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T18:15:59.000Z", "avg_line_length": 32.7543859649, "max_line_length": 137, "alphanum_fraction": 0.6239957151, "num_tokens": 723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391558356, "lm_q2_score": 0.875787001374006, "lm_q1q2_score": 0.808385694440054}} {"text": "#nb # %% A slide [markdown] {\"slideshow\": {\"slide_type\": \"subslide\"}}\n# ## Symmetric Strip Grating\n# This example consists of a symmetric strip grating, i.e. a grating where the strip width\n# is half the unit cell period ``P``:\n#\n# ![diagram](./assets/symmetric_strip_diagram.png)\n#\n# Only three of the infinite number of strips in the grating are shown, and they extend infinitely to the left and right.\n# The grating lies in the ``z=0`` plane with free space on both sides. The shaded areas represent metalization.\n# The dashed lines show two possible choices for the unit cell location: \"J\" for a formulation in terms of electric \n# surface currents, and \"M\" for magnetic surface currents.\n#\n# For normal incidence there is a closed-form solution due to Weinstein, \n# but for a more recent reference one can find the solution in Problem 10.6 of R. E. Collin, \n# *Field Theory of Guided Waves, Second Ed.*, \n# IEEE Press, 1991. Here is the code for computing the exact solution:\n\"\"\"\n grating(kP, nterms=30) -> (Γ, T)\n\nCompute the normal incidence reflecton and transmission coefficients of a symmetric grid of \nzero-thickness conducting strips. The product of the period of the strips and the incident\nelectric field wavenumber is `kP` (dimensionless). The incident electric field is \nperpendicular to the direction along the axis of the strips. The series have been \naccelerated by applying a Kummer's transformation, using the first two terms in the Maclaurin \nseries for the inverse sin function. `kP` must be in the half-open interval [0,1). The \ndefault number of summed terms `nterms` yields better than 10 digits of accuracy over the \ninterval [0.01,0.99].\n\"\"\"\nfunction grating(kP; nterms=30)\n sum1 = 1.3862943611198906 # \\sum_{n=1}^{\\infty} 1/(n-1/2) - 1/n = log(4) \n sum3 = 7.2123414189575710 # \\sum_{n=1}^{\\infty} (n-1/2)^{-3} - n^{-3} = 6 * \\zeta(3)\n x = kP/(4π)\n θ = x*sum1 + x^3/6 * sum3\n for n = 1:nterms\n xonmhalf = x/(n - 0.5)\n xon = x/n\n term = asin(xonmhalf) - (xonmhalf + (xonmhalf)^3/6) - \n (asin(xon) - (xon + xon^3/6))\n θ += term\n end\n Γ = sin(θ) * cis(-π/2 - θ)\n T = 1 + Γ\n return (Γ, T)\nend\n\n# Note that using the extension of \n# [Babinet's Principle for electromagnetic fields](http://kirkmcd.princeton.edu/examples/babinet.pdf)\n# this also provides the solution (upon appropriate interchange and sign change of the coefficients) for \n# the case where the incident wave polarization is parallel to the direction of the strips.\n\n# Here is the PSSFSS code to analyze this structure using electric currents as the unknowns. We will \n# scale the geometry so that the frequency in GHz is numerically equal to the period of the strips\n# measured in wavelengths.\n\nusing Plots, PSSFSS\nc = 11.802852677165355 # light speed [inch*GHz]\nperiod = c # so the period/wavelength = freq in GHz\nPy = period\nLy = period/2\nPx = Lx = Ly/10 # Infinite in x direction so this can be anything\nNy = 60\nNx = round(Int, Ny*Lx/Ly)\nsheet = rectstrip(;Px, Py, Lx, Ly, Nx, Ny, units=inch)\nflist = 0.02:0.02:0.98\nsteering = (θ=0, ϕ=0)\nstrata = [Layer()\n sheet\n Layer()]\nresults_j = analyze(strata, flist, steering, showprogress=false,\n resultfile=devnull, logfile=devnull); \np1 = plot(sheet)\np2 = plot(sheet, unitcell=true)\nptitle = plot(title = \"Symmetric Strip Triangulation\", \n grid = false, showaxis = false, xtick=[], ytick=[],\n bottom_margin = -50Plots.px)\nplot(ptitle, p1, p2, layout = @layout([A{0.09h}; [B C]]))\n#md savefig(\"symstrip1.png\"); nothing # hide\n#-\n#md # ![](symstrip1.png)\n\n# Note that setting `Lx = Px` causes the strip to fully occupy the x-extent\n# of the unit cell. PSSFSS automatically ensures that the triangle edges at these unit\n# cell boundaries define basis functions that satisfy the Floquet (phase shift) boundary\n# conditions, so that currents are free to flow across these unit cell boundaries.\n\n# We can also analyze the same structure using magnetic currents in the areas free of \n# metalization as the unknowns:\nsheet = rectstrip(;class='M', Px, Py, Lx, Ly, Nx, Ny, units=inch)\nstrata = [Layer()\n sheet\n Layer()]\nresults_m = analyze(strata, flist, steering, showprogress=false,\n resultfile=devnull, logfile=devnull); \n\n# \n# Each 50-frequency run of `analyze` takes about 14 seconds\n# for this geometry of 720 triangles on my machine. \n# More detailed timing information is available in the log file\n# (which is omitted for generating this documentation).\n\n# We will compare the PSSFSS results to the analytic solution:\n## Generate exact results:\nrt = grating.(2π*flist)\nrperp_exact = first.(rt)\ntperp_exact = last.(rt)\nrpar_exact = -tperp_exact\ntpar_exact = -rperp_exact;\n\n# Obtain PSSFSS results for electric and magnetic currents:\noutrequest = @outputs s11(v,v) s21(v,v) s11(h,h) s21(h,h)\nrperp_j, tperp_j, rpar_j, tpar_j = \n collect.(eachcol(extract_result(results_j, outrequest)))\nrperp_m, tperp_m, rpar_m, tpar_m = \n collect.(eachcol(extract_result(results_m, outrequest)));\n\n# Generate the comparison plots:\nangdeg(z) = rad2deg(angle(z)) # Convenience function\n\np1 = plot(title = \"Perpendicular Reflection Magnitude\",\n xlabel = \"Period (wavelengths)\",\n ylabel = \"Coefficient Magnitude\",\n legend=:topleft)\nplot!(p1, flist, abs.(rperp_exact), ls=:dash, label=\"Exact\")\nplot!(p1, flist, abs.(rperp_j), label=\"PSSFSS J\")\nplot!(p1, flist, abs.(rperp_m), label=\"PSSFSS M\")\n#md savefig(\"symstrip2.png\"); nothing # hide\n#-\n#md # ![](symstrip2.png)\n#-\np2 = plot(title = \"Perpendicular Reflection Phase\",\n xlabel = \"Period (wavelengths)\",\n ylabel = \"Phase (deg)\")\nplot!(p2, flist, angdeg.(rperp_exact), ls=:dash, label=\"Exact\")\nplot!(p2, flist, angdeg.(rperp_j), label=\"PSSFSS J\")\nplot!(p2, flist, angdeg.(rperp_m), label=\"PSSFSS M\")\n#md savefig(\"symstrip3.png\"); nothing # hide\n#-\n#md # ![](symstrip3.png)\n#-\np1 = plot(title = \"Parallel Reflection Magnitude\",\n xlabel = \"Period (wavelengths)\",\n ylabel = \"Coefficient Magnitude\")\nplot!(p1, flist, abs.(rpar_exact), ls=:dash, label=\"Exact\")\nplot!(p1, flist, abs.(rpar_j), label=\"PSSFSS J\")\nplot!(p1, flist, abs.(rpar_m), label=\"PSSFSS M\")\n#md savefig(\"symstrip4.png\"); nothing # hide\n#-\n#md # ![](symstrip4.png)\n#-\np2 = plot(title = \"Parallel Reflection Phase\",\n xlabel = \"Period (wavelengths)\",\n ylabel = \"Phase (deg)\")\nplot!(p2, flist, angdeg.(rpar_exact), ls=:dash, label=\"Exact\")\nplot!(p2, flist, angdeg.(rpar_j), label=\"PSSFSS J\")\nplot!(p2, flist, angdeg.(rpar_m), label=\"PSSFSS M\")\n#md savefig(\"symstrip5.png\"); nothing # hide\n#-\n#md # ![](symstrip5.png)\n\n# Now look at the transmission coefficients:\np1 = plot(title = \"Perpendicular Transmission Magnitude\",\n xlabel = \"Period (wavelengths)\",\n ylabel = \"Coefficient Magnitude\")\nplot!(p1, flist, abs.(tperp_exact), ls=:dash, label=\"Exact\")\nplot!(p1, flist, abs.(tperp_j), label=\"PSSFSS J\")\nplot!(p1, flist, abs.(tperp_m), label=\"PSSFSS M\")\n#md savefig(\"symstrip6.png\"); nothing # hide\n#-\n#md # ![](symstrip6.png)\n#-\np2 = plot(title = \"Perpendicular Transmission Phase\",\n xlabel = \"Period (wavelengths)\",\n ylabel = \"Phase (deg)\")\nplot!(p2, flist, angdeg.(tperp_exact), ls=:dash, label=\"Exact\")\nplot!(p2, flist, angdeg.(tperp_j), label=\"PSSFSS J\")\nplot!(p2, flist, angdeg.(tperp_m), label=\"PSSFSS M\")\n#md savefig(\"symstrip7.png\"); nothing # hide\n#-\n#md # ![](symstrip7.png)\n#-\np1 = plot(title = \"Parallel Transmission Magnitude\",\n xlabel = \"Period (wavelengths)\",\n ylabel = \"Coefficient Magnitude\", legend=:topleft)\nplot!(p1, flist, abs.(tpar_exact), ls=:dash, label=\"Exact\")\nplot!(p1, flist, abs.(tpar_j), label=\"PSSFSS J\")\nplot!(p1, flist, abs.(tpar_m), label=\"PSSFSS M\")\n#md savefig(\"symstrip8.png\"); nothing # hide\n#-\n#md # ![](symstrip8.png)\n#-\np2 = plot(title = \"Parallel Transmission Phase\",\n xlabel = \"Period (wavelengths)\",\n ylabel = \"Phase (deg)\")\nplot!(p2, flist, angdeg.(tpar_exact), ls=:dash, label=\"Exact\")\nplot!(p2, flist, angdeg.(tpar_j), label=\"PSSFSS J\")\nplot!(p2, flist, angdeg.(tpar_m), label=\"PSSFSS M\")\n#md savefig(\"symstrip9.png\"); nothing # hide\n#-\n#md # ![](symstrip9.png)\n\n# ### Conclusion\n# Although good agreement is obtained, as expected the best agreement between \n# all three results occurs for the lowest frequencies, where the triangles are\n# smallest in terms of wavelength. This emphasizes the fact that it is necessary for the \n# user to check that enough triangles have been requested for good convergence\n# over the frequency band of interest. This example is an extremely demanding case\n# in terms of bandwidth, as the ratio of maximum to minimum frequency here \n# is ``0.98/0.02 = 49:1``\n", "meta": {"hexsha": "6c29741aa797209b1de7eb64d667c89196c22fbd", "size": 8811, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/literate/symmetric_strip.jl", "max_stars_repo_name": "mortenpi/PSSFSS.jl", "max_stars_repo_head_hexsha": "9a3a6503d9266eee57771612a47a3e9b77bc9a2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-05-21T15:44:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T17:29:19.000Z", "max_issues_repo_path": "docs/literate/symmetric_strip.jl", "max_issues_repo_name": "mortenpi/PSSFSS.jl", "max_issues_repo_head_hexsha": "9a3a6503d9266eee57771612a47a3e9b77bc9a2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-10-08T22:20:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-26T01:01:09.000Z", "max_forks_repo_path": "docs/literate/symmetric_strip.jl", "max_forks_repo_name": "mortenpi/PSSFSS.jl", "max_forks_repo_head_hexsha": "9a3a6503d9266eee57771612a47a3e9b77bc9a2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-11-20T13:58:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-24T09:16:48.000Z", "avg_line_length": 42.1578947368, "max_line_length": 121, "alphanum_fraction": 0.6838043355, "num_tokens": 2630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039738, "lm_q2_score": 0.8757869867849166, "lm_q1q2_score": 0.8083856883902448}} {"text": "using LabelledArrays\n\nexport verdes\n\n\"\"\"\n eom_verdes(u, p, t) → SVector{3}\n\nEquations of motion for a 3D system where the response X is a highly\nnonlinear combination of Y and Z [1]. The forcings Y and Z involve\nsines and cosines, respectively, and have different periods.\n\nThe implementation here allows for tuning the period of the\nforcing signals.\n\n# References\nVerdes, P. F. \"Assessing causality from multivariate time series.\" Physical Review E 72.2 (2005): 026222.\n\"\"\"\nfunction eom_verdes(u, p, t)\n x, y, z = (u...,)\n ωy, ωz, σx, σy, σz = (p...,)\n\n ηx = σx == 0 ? 0 : rand(Normal(0, σx))\n ηy = σy == 0 ? 0 : rand(Normal(0, σy))\n ηz = σz == 0 ? 0 : rand(Normal(0, σz))\n\n dx = y*(18y - 27y^2 + 10)/2 + z*(1-z) + ηx\n dy = (1 - cos((2*pi/ωy) * t))/2 + ηy\n dz = (1 - sin((2*pi/ωz) * t))/2 + ηz\n return SVector{3}(dx, dy, dz)\nend\n\n\nfunction verdes(u₀, ωy, ωz, σx, σy, σz)\n p = LVector(ωy = ωy, ωz = ωz, σx = σx, σy = σy, σz = σz)\n\n DiscreteDynamicalSystem(eom_verdes, u₀, p)\nend\n\n\"\"\"\n verdes(;u₀ = rand(3), ωy = 315, ωz = 80,\n σx = 0.0, σy = 0.0, σz = 0.0) → DiscreteDynamicalSystem\n\nIntitialise a 3D system where the response X is a highly nonlinear combination\nof Y and Z. The forcings Y and Z involve sines and cosines, and\nhave different periods, which controlled by `ωy` and `ωz`.\n\nThe equations of motion are\n\n```math\n\\\\begin{aligned}\nx(t+1) &= \\\\dfrac{y(t)(18y(t) - 27y(t)^2 + 10)}{2} + z(t)(1-z(t)) + ηx \\\\\ny(t+1) &= \\\\dfrac{(1 - \\\\dfrac{\\\\cos(2\\\\pi)}{\\\\omega y}t)}{2} + ηy \\\\\nz(t+1) &= \\\\dfrac{(1 - \\\\dfrac{\\\\sin(2\\\\pi)}{\\\\omega z}t)}{2} + ηz\n\\\\end{aligned}\n```\nwhere ηx, ηy, ηz is gaussian noise with mean 0 and standard deviation `σx`, `σy`\nand `σz`.\n\n# References\nVerdes, P. F. \"Assessing causality from multivariate time series.\" Physical\nReview E 72.2 (2005): 026222.\n\"\"\"\nverdes(;u₀ = rand(3),\n ωy = 315, ωz = 80,\n σx = 0.01, σy = 0.01, σz = 0.01) =\n verdes(u₀, ωy, ωz, σx, σy, σz)\n", "meta": {"hexsha": "f9fee2e478c80dabae2ed315e08bd3fec50c382b", "size": 1951, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/example_systems/discretemaps/verdes.jl", "max_stars_repo_name": "kahaaga/CausalityTools.jl", "max_stars_repo_head_hexsha": "e1de3943a2ccb3c9997ca38e7a4fac025f1f8475", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2018-11-07T11:23:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-05T06:26:37.000Z", "max_issues_repo_path": "src/example_systems/discretemaps/verdes.jl", "max_issues_repo_name": "kahaaga/CausalityTools.jl", "max_issues_repo_head_hexsha": "e1de3943a2ccb3c9997ca38e7a4fac025f1f8475", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2018-09-04T08:02:07.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-04T11:59:38.000Z", "max_forks_repo_path": "src/example_systems/discretemaps/verdes.jl", "max_forks_repo_name": "kahaaga/CausalityTools.jl", "max_forks_repo_head_hexsha": "e1de3943a2ccb3c9997ca38e7a4fac025f1f8475", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-12-03T10:59:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:02:55.000Z", "avg_line_length": 29.1194029851, "max_line_length": 105, "alphanum_fraction": 0.6053305997, "num_tokens": 814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850039701653, "lm_q2_score": 0.8633916047011595, "lm_q1q2_score": 0.8083806120354325}} {"text": "using Plots\r\nusing DifferentialEquations\r\n\r\n@userplot LorenzPlot\r\n@recipe function f(lp::LorenzPlot)\r\n x, y, z, i = lp.args\r\n n = length(x)\r\n inds = circshift(1:n, 1-i)\r\n seriesalpha --> range(0, 1, length=n)\r\n aspect_ratio --> 1\r\n label --> false\r\n x[inds], y[inds], z[inds]\r\nend\r\n\r\nfunction anim()\r\n\r\n function lorenz(du, u, p, t)\r\n\r\n du[1] = p[1]*(u[2] - u[1])\r\n du[2] = u[1]*(p[2] - u[3]) - u[2]\r\n du[3] = u[1]*u[2] - p[3]*u[3]\r\n\r\n end\r\n\r\n u0 = [1, 5, 10]\r\n tspan = (0, 100)\r\n p = (10, 28, 8/3)\r\n\r\n prob = ODEProblem(lorenz, u0, tspan, p, reltol=1e-10, abstol=1e-10)\r\n sol = solve(prob)\r\n n = length(sol.t)\r\n\r\n plt = plot3d(1, xaxis=(\"x\", (-30, 30)), yaxis=(\"y\", (-30, 30)), zaxis=(\"z\", (0, 60)),\r\n title=\"Lorenz Attractor\", marker=2, markercolor=\"black\", dpi=300)\r\n\r\n # anim = @animate for i in 1:n\r\n # push!(plt, sol[1,i], sol[2,i], sol[3,i])\r\n # end\r\n # gif(anim, \"de_anim.gif\", fps=30)\r\n\r\n anim = @animate for i in 1:10:n\r\n lorenzplot(sol[1,:], sol[2,:], sol[3,:], i, c = :thermal)\r\n end\r\n gif(anim, \"de_anim_60.gif\", fps=60)\r\n\r\n\r\nend\r\n\r\n\r\n\r\nanim()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n # anim = @animate for i in 1:10:n\r\n # lorenzplot(sol[1,:], sol[2,:], sol[3,:], i)\r\n # end\r\n # gif(anim, \"de_anim60.gif\", fps=60)", "meta": {"hexsha": "879527027e64d352f9b20b48b3b50052fed5c7fe", "size": 1370, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia-learning-src/advance/13-diffeqanimation.jl", "max_stars_repo_name": "nunesmelo/djs-office-hours", "max_stars_repo_head_hexsha": "aa5cc3dfe3072c5608bf25f5dab27cbfa3664713", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2021-03-27T14:23:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T14:50:37.000Z", "max_issues_repo_path": "julia-learning-src/advance/13-diffeqanimation.jl", "max_issues_repo_name": "nunesmelo/djs-office-hours", "max_issues_repo_head_hexsha": "aa5cc3dfe3072c5608bf25f5dab27cbfa3664713", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia-learning-src/advance/13-diffeqanimation.jl", "max_forks_repo_name": "nunesmelo/djs-office-hours", "max_forks_repo_head_hexsha": "aa5cc3dfe3072c5608bf25f5dab27cbfa3664713", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2021-03-29T20:01:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T14:33:47.000Z", "avg_line_length": 17.125, "max_line_length": 90, "alphanum_fraction": 0.4759124088, "num_tokens": 517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850128595114, "lm_q2_score": 0.863391595913457, "lm_q1q2_score": 0.8083806114826252}} {"text": "module test\n\nusing Roots,Interpolations,PyPlot,Optim\nusing CompEcon, NLsolve\n\n\nalpha = 0.65\nbeta = 0.95\ngrid_max = 2 # upper bound of capital grid\nn = 150 # number of grid points\nN_iter = 3000 # number of iterations\nkgrid = 1e-6:(grid_max-1e-6)/(n-1):grid_max # equispaced grid\nf(x) = x.^alpha # defines the production function f(k)\ntol = 1e-9\n\nab = alpha * beta\nc1 = (log(1 - ab) + log(ab) * ab / (1 - ab)) / (1 - beta)\nc2 = alpha / (1 - ab)\nv_star(k) = c1 .+ c2 .* log(k) \nk_star(k) = ab * k.^alpha \nc_star(k) = (1-ab) * k.^alpha \nufun(x) = log(x)\n\n\n# Bellman Operator\n# inputs\n# `grid`: grid of values of state variable\n# `v0`: current guess of value function\n\n# output\n# `v1`: next guess of value function\n# `pol`: corresponding policy function \n\n#takes a grid of state variables and computes the next iterate of the value function.\nfunction bellman_operator(grid,v0)\n \n v1 = zeros(n) # next guess\n pol = zeros(Int,n) # policy function\n w = zeros(n) # temporary vector \n\n # loop over current states\n # current capital\n for (i,k) in enumerate(grid)\n\n # loop over all possible kprime choices\n for (iprime,kprime) in enumerate(grid)\n if f(k) - kprime < 0 #check for negative consumption\n w[iprime] = -Inf\n else\n w[iprime] = ufun(f(k) - kprime) + beta * v0[iprime]\n end\n end\n # find maximal choice\n v1[i], pol[i] = findmax(w) # stores Value und policy (index of optimal choice)\n end\n return (v1,pol) # return both value and policy function\nend\n\n\n\n# VFI iterator\n#\n## input\n# `n`: number of grid points\n# output\n# `v_next`: tuple with value and policy functions after `n` iterations.\nfunction VFI()\n v_init = zeros(n) # initial guess\n for iter in 1:N_iter\n v_next = bellman_operator(kgrid,v_init) # returns a tuple: (v1,pol)\n # check convergence\n if maxabs(v_init.-v_next[1]) < tol\n verrors = maxabs(v_next[1].-v_star(kgrid))\n perrors = maxabs(kgrid[v_next[2]].-k_star(kgrid))\n println(\"discrete VFI:\")\n println(\"Found solution after $iter iterations\")\n println(\"maximal value function error = $verrors\")\n println(\"maximal policy function error = $perrors\")\n return v_next\n elseif iter==N_iter\n warn(\"No solution found after $iter iterations\")\n return v_next\n end\n v_init = v_next[1] # update guess \n end\nend\n\n# plot\nfunction plotVFI()\n v = VFI()\n figure(\"discrete VFI\",figsize=(10,5))\n subplot(131)\n plot(kgrid,v[1],color=\"blue\")\n plot(kgrid,v_star(kgrid),color=\"black\")\n xlim(-0.1,grid_max)\n ylim(-50,-30)\n xlabel(\"k\")\n ylabel(\"value\")\n title(\"value function\")\n\n subplot(132)\n plot(kgrid,kgrid[v[2]])\n plot(kgrid,k_star(kgrid),color=\"black\")\n xlabel(\"k\")\n title(\"policy function\")\n\n subplot(133)\n plot(kgrid,kgrid[v[2]].-k_star(kgrid))\n title(\"policy function error\") \nend\n\nfunction bellman_operator2(grid,v0)\n \n v1 = zeros(n) # next guess\n pol = zeros(n) # consumption policy function\n\n Interp = interpolate((collect(grid),), v0, Gridded(Linear()) ) \n\n # loop over current states\n # of current capital\n for (i,k) in enumerate(grid)\n\n objective(c) = - (log(c) + beta * Interp[f(k) - c])\n # find max of ojbective between [0,k^alpha]\n res = optimize(objective, 1e-6, f(k)) \n pol[i] = f(k) - res.minimizer\n v1[i] = -res.minimum\n end\n return (v1,pol) # return both value and policy function\nend\n\nfunction VFI2()\n v_init = zeros(n) # initial guess\n for iter in 1:N_iter\n v_next = bellman_operator2(kgrid,v_init) # returns a tuple: (v1,pol)\n # check convergence\n if maxabs(v_init.-v_next[1]) < tol\n verrors = maxabs(v_next[1].-v_star(kgrid))\n perrors = maxabs(v_next[2].-k_star(kgrid))\n println(\"continuous VFI:\")\n println(\"Found solution after $iter iterations\")\n println(\"maximal value function error = $verrors\")\n println(\"maximal policy function error = $perrors\")\n return v_next\n elseif iter==N_iter\n warn(\"No solution found after $iter iterations\")\n return v_next\n end\n v_init = v_next[1] # update guess \n end\n return nothing\nend\n\nfunction plotVFI2()\n v = VFI2()\n figure(\"discrete VFI - continuous control\",figsize=(10,5))\n subplot(131)\n plot(kgrid,v[1],color=\"blue\")\n plot(kgrid,v_star(kgrid),color=\"black\")\n xlim(-0.1,grid_max)\n ylim(-50,-30)\n xlabel(\"k\")\n ylabel(\"value\")\n title(\"value function\")\n\n subplot(132)\n plot(kgrid,v[2])\n plot(kgrid,k_star(kgrid),color=\"black\")\n xlabel(\"k\")\n title(\"policy function\")\n\n subplot(133)\n plot(kgrid,v[2].-k_star(kgrid))\n xlabel(\"k\")\n title(\"policy function error\")\nend\n\n\nfunction policy_iter(grid,c0,u_prime,f_prime)\n \n c1 = zeros(length(grid)) # next guess\n pol_fun = interpolate((collect(grid),), c0, Gridded(Linear()) ) \n \n # loop over current states\n # of current capital\n for (i,k) in enumerate(grid)\n objective(c) = u_prime(c) - beta * u_prime(pol_fun[f(k)-c]) * f_prime(f(k)-c)\n c1[i] = fzero(objective, 1e-10, f(k)-1e-10) \n end\n return c1\nend\n\nuprime(x::Float64) = 1.0 / x\nfprime(x::Float64) = alpha* x ^ (alpha-1) \nfunction fprime(x::Vector) \n r = similar(x)\n for ix in eachindex(x)\n if x[ix] > 0\n r[ix] = alpha* x[ix]^(alpha-1)\n else\n r[ix] = 10000.0\n end\n end\n return r\nend\n\nfunction PFI()\n c_init = kgrid\n for iter in 1:N_iter\n c_next = policy_iter(kgrid,c_init,uprime,fprime) \n # check convergence\n if maxabs(c_init.-c_next) < tol\n perrors = maxabs(c_next.-c_star(kgrid))\n println(\"PFI:\")\n println(\"Found solution after $iter iterations\")\n println(\"max policy function error = $perrors\")\n return c_next\n elseif iter==N_iter\n warn(\"No solution found after $iter iterations\")\n return c_next\n end\n c_init = c_next # update guess \n end\nend\nfunction plotPFI()\n v = PFI()\n figure(\"PFI\")\n subplot(121)\n plot(kgrid,v)\n plot(kgrid,c_star(kgrid),color=\"black\")\n xlabel(\"k\")\n title(\"policy function\")\n\n subplot(122)\n plot(kgrid,v.-c_star(kgrid))\n xlabel(\"k\")\n title(\"policy function error\")\nend\n#plotVFI()\n#plotVFI2()\n#plotPFI()\n\nfunction proj2(n=25)\n\n a = 1e-6\n aa = 1e-2\n b = 1.0\n bb = 0.95\n basis = fundefn(:cheb,n,a,b)\n k = funnode(basis)[1] # collocation points\n\n fs = f.(k)\n\n # system of equations: for each k, one line\n function ff(coef::Vector,result::Vector,b,coll_points,fs)\n # get cons function\n cons = funeval(coef,b,coll_points)[1]\n # println(\"coef= $coef\")\n # println(\"cons = $cons\")\n\n # put resulting residuals into result[:]\n # put into euler equation\n nextk = fs.-cons \n for i in eachindex(nextk)\n if nextk[i] < 0 \n result[i] = -8000.0\n else\n result[i] = uprime(cons[i]) .- beta * uprime(nextk[i]) .* fprime(nextk[i])\n end\n end\n # println(result)\n end\n\n f_closure(x::Vector,r::Vector) = ff(x,r,basis,k,fs)\n\n res = nlsolve(f_closure,ones(n)*0.4)\n x = linspace(aa,bb,501)\n y = funeval(res.zero,basis,x)[1]\n plot(x,y)\n return res\nend\n\nfunction proj(n=25)\n\n alpha = 1.0\n eta = 1.5\n a = 0.1\n b = 3.0\n basis = fundefn(:cheb,n,a,b)\n p = funnode(basis)[1] # collocation points\n\n c0 = ones(n)*0.3\n function resid!(c::Vector,result::Vector,p,basis,alpha,eta)\n # your turn!\n q = funeval(c,basis,p)[1]\n q2 = zeros(q)\n for i in eachindex(q2)\n if q[i] < 0\n q2[i] = -20.0\n else\n q2[i] = sqrt(q[i])\n end\n end\n result[:] = p.+ q .*((-1/eta)*p.^(eta+1)) .- alpha*q2 .- q.^2\n end\n f_closure(r::Vector,x::Vector) = resid!(x,r,p,basis,alpha,eta)\n res = nlsolve(f_closure,c0)\n println(res)\n\n # plot residual function\n x = collect(linspace(a,b,501))\n y = similar(x)\n resid!(res.zero,y,x,basis,alpha,eta);\n y = funeval(res.zero,basis,x)[1]\n pl = Any[]\n push!(pl,plot(x,y,title=\"residual function\"))\n \n # plot supply functions at levels 1,10,20\n \n # plot demand function\n \n y = funeval(res.zero,basis,x)[1]\n p2 = plot(y,x,label=\"supply 1\")\n plot!(10*y,x,label=\"supply 10\")\n plot!(20*y,x,label=\"supply 20\")\n d = x.^(-eta)\n plot!(d,x,label=\"Demand\")\n\n push!(pl,p2)\n \n plot(pl...,layout=2)\nend\n\n\nend # module", "meta": {"hexsha": "844f9ad98803623aea6eb63f45c2d1798127c74f", "size": 8913, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/dp.jl", "max_stars_repo_name": "snowdj/CoursePack", "max_stars_repo_head_hexsha": "f3ad25012167f580b9ea97aa7e84890986648837", "max_stars_repo_licenses": ["MIT-0"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2017-06-21T16:55:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-04T13:44:26.000Z", "max_issues_repo_path": "src/dp.jl", "max_issues_repo_name": "snowdj/CoursePack", "max_issues_repo_head_hexsha": "f3ad25012167f580b9ea97aa7e84890986648837", "max_issues_repo_licenses": ["MIT-0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-01-23T14:13:36.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-01T11:10:31.000Z", "max_forks_repo_path": "src/dp.jl", "max_forks_repo_name": "snowdj/CoursePack", "max_forks_repo_head_hexsha": "f3ad25012167f580b9ea97aa7e84890986648837", "max_forks_repo_licenses": ["MIT-0"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2017-02-24T12:23:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-03T07:25:38.000Z", "avg_line_length": 26.6059701493, "max_line_length": 90, "alphanum_fraction": 0.5716369348, "num_tokens": 2667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850093037731, "lm_q2_score": 0.8633915976709976, "lm_q1q2_score": 0.8083806100581895}} {"text": "# Refined Löwner-John ellipsoid example with Mosek, MosekTools, and JuMP\n\n# Computes the inner and outer Löwner-John ellipsoids around the feasible\n# space of the JuMP model.\n\n# Uses Polyhedra and CDDLib packages to express the polyhedral set of the JuMP\n# model by inequalities and a convex hull of a finite set of points\n\nusing JuMP, Mosek, MosekTools\nusing LinearAlgebra, Polyhedra, CDDLib\nusing Plots\n\nfunction lowner_john_inner_ellipsoid(A,b)\n \"\"\"\n Löwner-John inner ellipsoid:\n the function takes H-representation (A,b) of a polytope and\n outputs the parameters of the maximum volume inscribed ellipsoid.\n\n polyhedral set S:\n S = { x ∈ Rn | ai' x ⩽ bi, i= 1,...,m }\n\n Proposition 3.7.1 [BenTalN01]\n ... Then the largest volume ellipsoid contained in S is\n E = { x = Z∗u + z∗ | uTu ≤1 }, where (Z∗,z∗) are from\n\n maximize t (1.0)\n s.t. t ⩽ (DetZ)^1/n (1.1)\n Z - PSD (1.2)\n || Z * ai ||_2 ≤ bi −ai' * z, i = 1,...,m (1.3)\n Z ∈ S^n, z ∈ Rn, t ∈ R (1.4)\n\n To model (1.1), refer to [Mosek, 6.2.3 Log-determinant]\n\n t ⩽ (DetZ)^1/n <==> [Z B; B' diag(B)] - PSD (2.1)\n B is lower triangular (2.2)\n t ⩽ (Π_i={1,...,n} Bii)^1/n (2.3)\n\n where (2.3) maximizes the geometric mean of the Bii variables. It\n can be modelled using power cone [Mosek, 4.2.4 Geometric mean] and\n MOI.GeometricMeanCone available with the MathOptInterface.jl\n\n [BenTalN01]\t A. Ben-Tal and A. Nemirovski. Lectures on Modern Convex\n Optimization: Analysis, Algorithms, and Engineering Applications.\n MPS/SIAM Series on Optimization. SIAM, 2001.\n [Mosek] https://docs.mosek.com/modeling-cookbook/index.html\n \"\"\"\n # model size\n m,n = size(A)\n # model declaraton\n model = Model(optimizer_with_attributes(Mosek.Optimizer, \"LOG\" => 0))\n # variables\n @variable(model, t)\n @variable(model, Z[1:n,1:n], PSD)\n @variable(model, z[1:n])\n @variable(model, B[1:n,1:n])\n # maximize the volume\n @objective(model, Max, t)\n # SOC constraint (1.3)\n @constraint(model, SOC[i=1:m], [ b[i] - (A[i,:]' * z) ; (A[i,:]'*Z)'] in SecondOrderCone())\n # PSD constraint (2.1)\n @constraint(model, [Z LowerTriangular(B); LowerTriangular(B)' diagm(diag(B))] in PSDCone())\n # Power cone costraint (2.3)\n @constraint(model, [t; vec([B[i,i] for i in 1:n])] in MOI.GeometricMeanCone(n+1))\n # optimize\n optimize!(model)\n status=termination_status(model)\n CPU_time = MOI.get(model, MOI.SolveTime())\n # return solution\n return JuMP.value.(Z), JuMP.value.(z), CPU_time\nend\n\nfunction lownerjohn_outer(x)\n \"\"\"\n Löwner-John outer ellipsoid:\n the function takes V-representation (x) of a polytope and\n outputs the parameters of the maximum volume inscribed ellipsoid.\n\n Polyhedral set S = Conv{x_1,...,x_n}\n\n Uses the same Mosek features as the inner ellipsoid function,\n refer to Proposition 3.7.2 [BenTalN01] for further details.\n \"\"\"\n\n m,n = size(x)\n model = Model(optimizer_with_attributes(Mosek.Optimizer, \"LOG\" => 0))\n\n @variable(model,t >= 0)\n @variable(model,P[1:n,1:n],PSD)\n @variable(model,B[1:n,1:n])\n @variable(model,c[1:n])\n\n # (1, Px-c) in cone\n for i in 1:m\n @constraint(model,[1 ; (x[i,:]' * P)' - c] in MOI.SecondOrderCone(n+1))\n end\n\n @constraint(model, [P LowerTriangular(B); LowerTriangular(B)' diagm(diag(B))] in PSDCone())\n @constraint(model, [t; vec([B[i,i] for i in 1:n])] in MOI.GeometricMeanCone(n+1))\n\n @objective(model,Max,t)\n\n optimize!(model)\n status=termination_status(model)\n CPU_time = MOI.get(model, MOI.SolveTime())\n\n JuMP.value.(P), JuMP.value.(c), CPU_time\nend\n\n# create a JuMP model\nfunction JuMP_model(n)\n model = Model(optimizer_with_attributes(Mosek.Optimizer, \"LOG\" => 0))\n @variable(model, x[1:n])\n @objective(model, Min, x'diagm(ones(n))'x)\n @constraint(model, con1[i=1:n], 0 <= x[i] <= 1)\n @constraint(model, ones(n)'x >= n/3)\n optimize!(model)\n return model\nend\n\n# model dimension\nn = 2\n# get JuMP model\nmodel = JuMP_model(n)\n@info(\"done exporting JuMP model\")\n# create a polyhedron from the feasible set of a JuMP model\npoly = polyhedron(model, CDDLib.Library(:exact))\n@info(\"done exporting the polyhedron\")\n\n# obtain H-representation of the polyhedron\nhr = MixedMatHRep(hrep(poly))\nA = hr.A\nb = hr.b\n@info(\"done obtaining H-representation\")\n# solve ellipsoid problem\nCi, di, CPU_time = lowner_john_inner_ellipsoid(A,b)\n@info(\"done solving inner ellipsoid problem in $(CPU_time) seconds\")\n\n# obtain V-representation of the polyhedron\nvr = vrep(poly)\nvr = MixedMatVRep(vr)\np = vr.V\n@info(\"done obtaining V-representation\")\nPo, co, CPU_time = lownerjohn_outer(p)\n@info(\"done solving outter ellipsoid problem in $(CPU_time) seconds\")\nPoinv = Po^-1\n\n# make a plot\nif n == 2\n println(\"Plotting solution...\")\n Plots.gr()\n Plots.plot([p[:,1] ; p[1,1]], [p[:,2] ; p[1,2]])\n Plots.plot!(t -> Ci[1,:]' * [ cos(t),sin(t) ] + di[1],\n t -> Ci[2,:]' * [ cos(t),sin(t) ] + di[2],\n 0,2*pi)\n Plots.plot!(t -> Poinv[1,:]' * ( [cos(t),sin(t)] .+ co[1] ),\n t -> Poinv[2,:]' * ( [cos(t),sin(t)] .+ co[2] ),\n 0,2*pi)\nend\n", "meta": {"hexsha": "527802e3e1227a4b158bef954bf42768cb84097e", "size": 5632, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/JuMP/lowner_john_v2.jl", "max_stars_repo_name": "wdvorkin/Mosek.jl", "max_stars_repo_head_hexsha": "c8f5f62035c7f8e456358dd2d148b675be56b7ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33, "max_stars_repo_stars_event_min_datetime": "2015-05-28T18:01:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-30T19:53:25.000Z", "max_issues_repo_path": "examples/JuMP/lowner_john_v2.jl", "max_issues_repo_name": "wdvorkin/Mosek.jl", "max_issues_repo_head_hexsha": "c8f5f62035c7f8e456358dd2d148b675be56b7ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 126, "max_issues_repo_issues_event_min_datetime": "2015-01-05T11:37:47.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-10T14:00:02.000Z", "max_forks_repo_path": "examples/JuMP/lowner_john_v2.jl", "max_forks_repo_name": "wdvorkin/Mosek.jl", "max_forks_repo_head_hexsha": "c8f5f62035c7f8e456358dd2d148b675be56b7ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 35, "max_forks_repo_forks_event_min_datetime": "2015-01-06T20:20:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-25T07:13:44.000Z", "avg_line_length": 35.4213836478, "max_line_length": 95, "alphanum_fraction": 0.5857599432, "num_tokens": 1729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122708828604, "lm_q2_score": 0.8438951025545427, "lm_q1q2_score": 0.8083774740749463}} {"text": "# ---\n# title: 172. Factorial Trailing Zeroes\n# id: problem172\n# author: zhwang\n# date: 2022-03-25\n# difficulty: Easy\n# categories: Math\n# link: \n# hidden: true\n# ---\n# \n# Given an integer `n`, return _the number of trailing zeroes in`n!`_.\n# \n# **Follow up:** Could you write a solution that works in logarithmic time\n# complexity?\n# \n# \n# \n# **Example 1:**\n# \n# \n# \n# Input: n = 3\n# Output: 0\n# Explanation: 3! = 6, no trailing zero.\n# \n# \n# **Example 2:**\n# \n# \n# \n# Input: n = 5\n# Output: 1\n# Explanation: 5! = 120, one trailing zero.\n# \n# \n# **Example 3:**\n# \n# \n# \n# Input: n = 0\n# Output: 0\n# \n# \n# \n# \n# **Constraints:**\n# \n# * `1 <= n <= 104`\n# \n# \n## @lc code=start\nusing LeetCode\n\n## simulate Mathematica's function NestWhileList\nfunction nest_while_list(f::Function, val::T, chk::Function)::Vector{T} where {T}\n res = [val]\n while chk(val)\n val = f(val)\n push!(res, val)\n end\n return res\nend\n\ntrailing_zeroes(n::Int) = sum(nest_while_list(i -> i ÷ 5, n ÷ 5, >(1)))\n## equivalent to the following\n## function trailing_zeroes(n::Int)::Int\n## res = 0\n## while n >=5\n## n ÷= 5\n## res += n\n## end\n## res\n## end\n\n## @lc code=end\n", "meta": {"hexsha": "ef74e2f355ca49397be38f83b768a5b38669c1f5", "size": 1335, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/172.factorial-trailing-zeroes.jl", "max_stars_repo_name": "RexWzh/LeetCode.jl", "max_stars_repo_head_hexsha": "d86109b9d5a15491304ff9d2ee66e506f60d2146", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/problems/172.factorial-trailing-zeroes.jl", "max_issues_repo_name": "RexWzh/LeetCode.jl", "max_issues_repo_head_hexsha": "d86109b9d5a15491304ff9d2ee66e506f60d2146", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/problems/172.factorial-trailing-zeroes.jl", "max_forks_repo_name": "RexWzh/LeetCode.jl", "max_forks_repo_head_hexsha": "d86109b9d5a15491304ff9d2ee66e506f60d2146", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.3376623377, "max_line_length": 81, "alphanum_fraction": 0.5460674157, "num_tokens": 453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206791658465, "lm_q2_score": 0.8962513752119936, "lm_q1q2_score": 0.8083476490345252}} {"text": "function LidDrivenCavity(;\n tfinal = Inf,\n Lx = 1, Ly = 1, CFL = 0.5, Re = 100,\n Nx = 65, Ny = 65,\n u_n = 1, u_s = 0, v_w = 0, v_e = 0,\n printfreq = 10)\n t0 = time()\n println(\"------------------Ny = $(Ny), Nx = $(Nx) ---------------\")\n Δy = Ly/(Ny-1)\n Δx = Lx/(Nx-1)\n x = 0:Δx:Lx\n y = 0:Δy:Ly\n Δt = CFL * Δx\n\n # Construct matrix for Poisson equation\n A_poisson = BuildPoissonMatrix(Ny,Nx,Δx,Δy) # for coNxgrad\n # Construct matrix for advection-diffusion equation\n ap,an,as,ae,aw = BuildAdvectionDiffusionCoefficients(Re,Δt,Δx,Δy)\n # allocate empty matrices for Gauss-Siedel solver\n Rp = zeros(Ny,Nx); res = zeros(Ny,Nx)\n\n # initialize ω and ψ\n ω = zeros(Ny,Nx)\n ψ = zeros(Ny,Nx)\n\n # keep track of changes with Δ's\n ω_old = zeros(Ny,Nx)\n ψ_old = zeros(Ny,Nx)\n ω_hist = []\n ψ_hist = []\n residual = 1\n\n ###########################\n k0,t = 0,0\n while t < tfinal && maximum(residual) > 1e-8\n t += Δt\n k0 += 1\n # Solve Poisson equation for ψ:\n LinearSolve!(A_poisson,ψ,-ω)\n\n VorticityBoundaryConditions!(ω,ψ,Δx,Δy,u_n,u_s,v_e,v_w)\n # Modify the explicit part of advection-diffusion equation\n BuildAdvectionDiffusionRHS!(Rp,ω,ψ,Δt,Δx,Δy,Ny,Nx,Re)\n\n # Solve advection-diffusion equation for ω:\n GaussSiedel!(ω,ap,an,as,ae,aw,Rp,res)\n\n residual = RecordHistory!.([ω,ψ],[ω_old,ψ_old],[ω_hist,ψ_hist])\n\n\n if (k0 % printfreq == 0)\n println(\"Step: $k0 \\t Time: $(round(t,digits=3))\\t\",\n \"|Δω|: $(round((residual[1]),digits=8)) \\t\",\n \"|Δψ|: $(round((residual[2]),digits=8)) \\t\")\n end\n end\n tt = round(time() - t0, digits=3)\n println(\"This took $tt seconds.\")\n println(\"--------------------------------------------------------\")\n Results(ψ,ω,hcat(ω_hist,ψ_hist),x,y,t,k0,Re)\nend\n\n", "meta": {"hexsha": "51f1280c2e97f0ddf2fe829d4252527a7c84ca2d", "size": 2010, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lid_driven_cavity.jl", "max_stars_repo_name": "Emadmasroor/SimpleNavierStokes.jl", "max_stars_repo_head_hexsha": "9ded56a19908f5805d67c24c9baa585740d96112", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-30T17:16:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T17:16:24.000Z", "max_issues_repo_path": "src/lid_driven_cavity.jl", "max_issues_repo_name": "gsagoo/SimpleNavierStokes.jl", "max_issues_repo_head_hexsha": "9ded56a19908f5805d67c24c9baa585740d96112", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lid_driven_cavity.jl", "max_forks_repo_name": "gsagoo/SimpleNavierStokes.jl", "max_forks_repo_head_hexsha": "9ded56a19908f5805d67c24c9baa585740d96112", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-30T17:12:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-30T17:12:59.000Z", "avg_line_length": 31.9047619048, "max_line_length": 71, "alphanum_fraction": 0.4980099502, "num_tokens": 698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750427013548, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.8083464974144454}} {"text": "# Sine Dictionary based example\nusing PyPlot\nusing Statistics\nusing Random\n\ninclude(\"../src/LocallyCompetitive.jl\")\nRandom.seed!(0xcafebeef)\n\n# First we create 'dim' basis functions, each consisting of 'n_elm' samples.\n# Using the dictionary 'D' a set of output samples can be created.\n# We will create a 'k' sparse signal 'y' and attempt to reconstruct it.\n# For a basis function we will use a set of sine functions with the norm of each\n# function set to 1.\n# The sparse signal 'y' will have 'k' randomly chosen signals.\n#\n# LCA can effectively reconstruct 'y' original representation even with changes\n# to the dictionary used to create it and if LCA attempts to reconstruct\n# 'y'+noise it will attempt to impose sparsity on the solution\n\ndim = 64 #number of basis functions\nn_elms = 1024 #samples per function\nD = zeros(n_elems,dim);\nk = 3 #Sparsity factor\ns = zeros(dim)\n\nfor i=1:dim,\n j=1:n_elems\n D[j,i] = sin(2pi*j*i/n_elems)\nend\nLCA.unitary_columns!(D)\n\n# The original sparse representation\ns = rand(dim)*4\ns[sortperm(randn(dim))[k+1:end]] .= 0\n\n# The signal that is observed\ny = D*s\n\nnoise = randn(n_elems)\n\nsparse_clean = LCA.lca(y+0.0*noise, D, T_soft=0.20)\nsparse_noise = LCA.lca(y+0.2*noise, D, T_soft=0.25)\n\nfigure(1);PyPlot.clf()\nsubplot(3,1,1)\ntitle(\"The original sparse elements\")\nylabel(\"Magnitude\")\nstem(s)\nsubplot(3,1,2)\ntitle(\"The reconstructed sparse elements\")\nylabel(\"Magnitude\")\nstem(sparse_clean)\nsubplot(3,1,3)\ntitle(\"The reconstructed elements under noisy observation\")\nxlabel(\"Dictionary Element\")\nylabel(\"Magnitude\")\nstem(sparse_noise)\n\nfigure(2);PyPlot.clf()\ntitle(\"The original sparse elements\")\nylabel(\"Magnitude\")\nplot(D*s)\nplot(D*sparse_clean)\nfigure(43);PyPlot.clf()\nsubplot(1,3,1)\nplot(y+0.2*noise)\naxis([0,n_elms, -0.6, 0.6])\nsubplot(1,3,2)\nplot(y)\naxis([0,n_elms, -0.6, 0.6])\nsubplot(1,3,3)\nplot(D*sparse_noise)\naxis([0,n_elms, -0.6, 0.6])\n\nprintln(\"If LCA is working as expected, then the sparsity of the original\")\nprintln(\"signal input should be identical. For processing the signal with noise\")\nprintln(\"the sparsity should be similar though higher (sparsity will go down\")\nprintln(\"with higher soft_threshold values)\")\n\nprintln()\n\nprintln(\"Sparsity of original signal = \", sum(s.!=0))\nprintln(\"Sparsity of LCA on the clean observation = \", sum(sparse_clean.!=0))\nprintln(\"Sparsity of LCA on the dirty observation = \", sum(sparse_noise.!=0))\n\nprintln()\nprintln(\"Although the sparsity of LCA on the dirty observation is higher,\")\nprintln(\"let's see what happens to the reconstruction error\")\nprintln()\nprintln(\"Original = \", norm(D*s-y), \" (Defined to be zero)\")\nprintln(\"LCA clean = \", norm(D*sparse_clean-y), \" (Should be small)\")\nprintln(\"noisy signal = \", norm(y+noise-y),\n \" (Defined to be the norm of the noise\")\nprintln(\"LCA dirty = \", norm(D*sparse_noise-y),\n \" (Much lower than the noisy observation)\")\n", "meta": {"hexsha": "eadc5fa934fcccc3680486a1ee4d8883ed11808b", "size": 2917, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/sine-table.jl", "max_stars_repo_name": "UnofficialJuliaMirror/LocallyCompetitive.jl-86bb8979-40af-4c14-b177-a78efc84e952", "max_stars_repo_head_hexsha": "d4a8cc5578c762a35c7497a4dc00ac1fed1ae83c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/sine-table.jl", "max_issues_repo_name": "UnofficialJuliaMirror/LocallyCompetitive.jl-86bb8979-40af-4c14-b177-a78efc84e952", "max_issues_repo_head_hexsha": "d4a8cc5578c762a35c7497a4dc00ac1fed1ae83c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/sine-table.jl", "max_forks_repo_name": "UnofficialJuliaMirror/LocallyCompetitive.jl-86bb8979-40af-4c14-b177-a78efc84e952", "max_forks_repo_head_hexsha": "d4a8cc5578c762a35c7497a4dc00ac1fed1ae83c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3854166667, "max_line_length": 81, "alphanum_fraction": 0.7144326363, "num_tokens": 825, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966747198242, "lm_q2_score": 0.8539127529517044, "lm_q1q2_score": 0.8083109724449342}} {"text": "# 第一章\n\"\"\"\n線形回帰分析の係数と切片\n```julia\nusing Random,Distributions\nRandom.seed!(123)\n#データの生成\nN=100\na=rand(Normal(2,1),N)\nb=randn(1)\nx = randn(N)\ny = a.*x .+ b + randn(N)\na1, b1 = min_sq(x,y)\n```\n\"\"\"\nfunction min_sq(x::Vector{T},y::Vector{T}) where {T<:Number}\n x̄ = mean(x)\n ȳ = mean(y)\n β₁ = (x .- x̄)'*(y .- ȳ) / norm(x .- x̄)^2 #傾き\n β₀ = ȳ - β₁ * x̄ #切片\n return β₁,β₀\nend\n\nfunction expand_matrix(X)\n N = typeof(X) <: Matrix ? size(X)[1] : length(X)\n T = eltype(X)\n return hcat(ones(T,N),X)\nend\nfunction insert_ones(X)\n N = typeof(X) <: Matrix ? size(X)[1] : length(X)\n T = eltype(X)\n return hcat(ones(T,N),X)\nend\n\n\"\"\"\n重回帰分析の係数\n```julia\nn = 100; p =2\nβ = Float64[1,2,3]\nx = randn(n,2)\ny = @. β[1] + β[2] * x[:,1] + β[3]*x[:,2] + $randn(n)\nMultipleRegression(x,y)\n\n3-element Array{Float64,1}:\n 0.8957078029816884\n 1.904721221695989\n 3.1212560196461494\n```\n\"\"\"\nfunction multiple_regression(x::Matrix{T}, y::Vector{T}) where {T<:Number}\n N,_ = size(x)\n @assert N==length(y)\n X = insert_ones(x)\n return (X'X)\\X'y\nend\nfunction multiple_regression(x::Vector{T}, y::Vector{T}) where {T<:Number}\n return multiple_regression(x[:,:],y)\nend\n\n\"\"\"\n線形回帰分析でのRSS値\n\"\"\"\nfunction RSS(x::Vector,y)\n β̂ = min_sq(x,y)\n ŷ = β̂[1]*x .+ β̂[2]\n return (y-ŷ)'*(y-ŷ)\nend\nfunction RSS(x::Matrix,y)\n ŷ = insert_ones(x)*multiple_regression(x,y)\n return (y-ŷ)'*(y-ŷ)\nend\n\nfunction TSS(y)\n length(y)==0 && return 0\n Y = y .- mean(y)\n return Y'*Y \nend\n\nESS(x,y) = TSS(y) - RSS(x,y)\n\nR2(x,y) = ESS(x,y)/TSS(y)\n\nfunction RSE(x::Matrix,y)\n n,p = size(x)\n RSS(x,y) / (n-p-1) \nend\n\nfunction RSE(x::Vector,y)\n RSS(x,y) / (length(x)-2) \nend\n\nfunction Bdiag(x)\n X = insert_ones(x)\n return X'X |> inv |> diag\nend\n\n\"\"\"\nVIF(variance inflation factor)\n\"\"\"\nfunction VIF(x::Matrix)\n _,ncol= size(x)\n v = Vector{Float64}(undef,ncol)\n for j in 1:ncol\n # index = delete!(Set(1:ncol),j) |> collect\n index = setdiff(1:ncol,j)\n v[j] = 1/(1-R2(x[:,index],x[:,j]))\n end\n return v\nend\n\n\"\"\"\nconfident_interval(xp,x,y;α=0.01)\n\n線形回帰における信頼区間(予測したい場所での標準偏差)を返す。\nxp:説明変数の予測データ\nx:説明変数の学習データ\ny:目的変数の学習データ\nα:0.01 は99%信頼区間\n\"\"\"\nfunction confident_interval(xp,x,y;α=0.01)\n N,p = size(x)\n X = insert_ones(x)\n XP = insert_ones(xp)\n typeof(xp) <:Number && (xp =[xp])\n yerror = quantile(TDist(N-p-1),1-α/2) * sqrt.(diag(XP * ((X'X) \\ XP')))\nend\n\nfunction prediction_interval(xp,x,y;α=0.01)\n N,p = size(x)\n X = insert_ones(x)\n XP = insert_ones(xp)\n typeof(xp) <:Number && (xp =[xp])\n yerror = quantile(TDist(N-p-1),1-α/2) * sqrt.( 1 .+ diag(XP * ((X'X) \\ XP')))\nend\n", "meta": {"hexsha": "a458ec67f99e7a1e56e92f477a845fe426f6bfce", "size": 2655, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chap1.jl", "max_stars_repo_name": "lethal8723/Joe.jl", "max_stars_repo_head_hexsha": "f30bf44f7e662ae58dded2ec675540b2996fe90a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/chap1.jl", "max_issues_repo_name": "lethal8723/Joe.jl", "max_issues_repo_head_hexsha": "f30bf44f7e662ae58dded2ec675540b2996fe90a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/chap1.jl", "max_forks_repo_name": "lethal8723/Joe.jl", "max_forks_repo_head_hexsha": "f30bf44f7e662ae58dded2ec675540b2996fe90a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.6666666667, "max_line_length": 81, "alphanum_fraction": 0.5743879473, "num_tokens": 1155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966671870767, "lm_q2_score": 0.8539127566694177, "lm_q1q2_score": 0.8083109695317999}} {"text": "#RSDeltaSigmaPort: Compute power values.\n#-------------------------------------------------------------------------------\n\n\"\"\"`dbm(v,R=50) = 10*log10(v^2/R*1000)`\n\nThe equivalent in dBm of an RMS voltage v\n\"\"\"\ndbm(v; R::Float64=50.0) = 10*log10.(abs.(v .^ 2)/R) .+ 30;\n\n\"\"\"`dbp(x) = 10*log10(x)`\n\nThe dB equivalent of the power x\n\"\"\"\ndbp(x) = 10*log10.(abs.(x))\n\n\"\"\"`dbv(x) = 20*log10(abs(x))`\n\nThe dB equivalent of the voltage x\n\"\"\"\ndbv(x) = 20*log10.(abs.(x))\n\n\"`y = rms(x; no_dc=false)`\"\nfunction rms(x; no_dc::Bool=false)\n\tif no_dc\n\t\tx = x - mean(x)\n\tend\n\treturn norm(x)/sqrt(length(x))\nend\n\n\"\"\"`v = undbm(p, z=50) = sqrt(z*10^(p/10-3))`\n\nRMS voltage equivalent to a power p in dBm\n\"\"\"\nundbm(p; z::Float64=50.0) = sqrt.(z*10 .^ (p/10 .- 3))\n\n\"\"\"`y = undbp(x)`\n\nConvert x from dB to a power\n\"\"\"\nundbp(x) = 10 .^ (x/10)\n\n\"\"\"`y = undbv(x)`\n\nConvert x from dB to a voltage\n\"\"\"\nundbv(x) = 10 .^ (x/20)\n\n#Last line\n", "meta": {"hexsha": "bb6bf3a9502e76d85dea76755400b7804e74efb0", "size": 913, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/power.jl", "max_stars_repo_name": "ma-laforge/RSDeltaSigmaPort.jl", "max_stars_repo_head_hexsha": "eae547513db458327ca1f25fa734325d0456842b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-06-16T17:34:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T03:38:31.000Z", "max_issues_repo_path": "src/power.jl", "max_issues_repo_name": "ma-laforge/RSDeltaSigmaPort.jl", "max_issues_repo_head_hexsha": "eae547513db458327ca1f25fa734325d0456842b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2021-05-08T15:16:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-22T03:37:27.000Z", "max_forks_repo_path": "src/power.jl", "max_forks_repo_name": "ma-laforge/RSDeltaSigmaPort.jl", "max_forks_repo_head_hexsha": "eae547513db458327ca1f25fa734325d0456842b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.6326530612, "max_line_length": 80, "alphanum_fraction": 0.5312157722, "num_tokens": 338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966686936261, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.8083109672990867}} {"text": "\n# using PyPlot\nusing ConvDiffMIPDECO\nusing jInv.Mesh\n# using jInvVis\nusing jInv.LinearSolvers\nusing MUMPSjInv\n\ndomain = [0 2 0 1]\nnc\t\t = [128 64]*4\npNoise = .05\nnoBoreHoles = 30\nMc = getRegularMesh(domain,nc)\nP,mf = getRandomBoreholes2D(noBoreHoles,nc,nc) \t\t# Randomly selecting borehols\npForFEM = getConvDiffFEMParam(Mc,sig=0.01,Ainv=getMUMPSsolver());\nv = kron([1;0.0],ones(prod(Mc.n+2)))\npFor = getConvDiffParam(Mc,v,sig=pForFEM.sig,Ainv=getMUMPSsolver(),bc=(:dir,:neu,:neu,:neu));\nw = zeros(Mc.n[1],Mc.n[2]);\nw[30:40,30:40] = 1;\nviewImage2D(w,Mc)\ntitle(\"source term\")\ncolorbar()\npFor.sig\n\ndobsFEM, = getData(vec(w),pForFEM);\ndobs, = getData(vec(w),pFor);\n\nsubplot(3,1,1)\nviewImage2D(pForFEM.Fields,getPaddedMesh(Mc))\nylabel(\"FEM\")\ncolorbar()\ntitle(\"Fields\")\n\n\nsubplot(3,1,2)\nviewImage2D(pFor.Fields,Mc)\nylabel(\"FD\")\ncolorbar()\n\nsubplot(3,1,3)\nviewImage2D(getNodalAverageMatrix(Mc)*pForFEM.Fields-pFor.Fields,Mc)\ncolorbar()\nylabel(\"Difference\")\n\nprintln(\"relative error (PDE solve FEM vs FD): $(norm(vec(getNodalAverageMatrix(Mc)*pForFEM.Fields-pFor.Fields))/norm(vec(pFor.Fields)))\")\n\n\"\"\"\nfdAnisoTV(W,Mc)\n\nprototype implementation of regularizer using for loops\n\"\"\"\nfunction fdAnisoTV(W,Mc)\n W = reshape(W,Mc.n[1], Mc.n[2])\n L = Mc.h\n\n Reg = 0.0;\n # compute first term of regularizer (derivatives in first dimension)\n for i=2:Mc.n[1]\n for j=1:Mc.n[2]\n Reg += Mc.h[2]*abs(W[i,j] - W[i-1,j])\n end\n end\n # compute first term of regularizer (derivatives in second dimension)\n for i=1:Mc.n[1]\n for j=2:Mc.n[2]\n Reg += Mc.h[1]*abs(W[i,j] - W[i,j-1])\n end\n end\n return Reg\nend\n\nRfd = fdAnisoTV(w,Mc)\n\nusing jInv.InverseSolve\nRjinv = anisoTVReg(vec(w),0*vec(w),Mc,eps=0)[1]\nprintln(\"Relative error (regularizer for loop): $(abs(Rfd-Rjinv)/abs(Rjinv))\")\n\n\"\"\"\nfdPDE(U,Mc)\n\nprototype implementation of PDE using for loops\n\nhere, assume that v = [1;0]\n\"\"\"\nfunction fdPDE(U,Mc;c=0.01)\n Up = zeros(Mc.n[1]+2, Mc.n[2]+2)\n Up[2:end-1,2:end-1] = reshape(U,Mc.n[1], Mc.n[2])\n\n # left boundary: 0-Dirichlet\n Up[1,2:end-1] = -U[1,:]\n # right boundary: 0-Neumann\n Up[end,2:end-1] = U[end,:]\n # top boundary: 0-Neumann\n Up[2:end-1,end] = U[:,end]\n # bottom boundary: 0-Neumann\n Up[2:end-1,1] = U[:,1]\n\n L = Mc.h\n\n # allocate output (with ghostpoints for simpler indexing)\n V = zeros(Mc.n[1]+2, Mc.n[2]+2)\n for i=2:Mc.n[1]+1\n for j=2:Mc.n[2]+1\n V[i,j] = (c/(L[1]^2))*(2*Up[i,j]-Up[i-1,j]-Up[i+1,j]) +\n (c/(L[2]^2))*(2*Up[i,j]-Up[i,j-1]-Up[i,j+1]) +\n (Up[i,j]-Up[i-1,j])/L[1]\n end\n end\n V = V[2:Mc.n[1]+1,2:Mc.n[2]+1]\n return V\nend\nU = randn(Mc.n[1],Mc.n[2])\n# U = copy(w)\nVfd = fdPDE(copy(U),Mc,c=pFor.sig);\n\nVjinv = reshape(pFor.A*vec(U),Mc.n[1],Mc.n[2]);\n\nsubplot(3,1,1);\nviewImage2D(Vfd,Mc)\ncolorbar()\n\nsubplot(3,1,2);\nviewImage2D(Vjinv,Mc)\ncolorbar()\n\nsubplot(3,1,3);\nviewImage2D(abs.(Vfd-Vjinv),Mc)\ncolorbar()\n\nprintln(\"relative error (conv diff for loop): $(norm(vec(Vjinv-Vfd))/norm(vec(Vjinv)))\")\n", "meta": {"hexsha": "c06c4186cccaa92024a8616a29442ba3711f78ee", "size": 3108, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/FEMvsFD.jl", "max_stars_repo_name": "JuliaInv/ConvDiffMIPDECO", "max_stars_repo_head_hexsha": "95a3aead09d34811c4c2ca14279df93a0b40ecdb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-16T19:08:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-16T19:08:09.000Z", "max_issues_repo_path": "test/FEMvsFD.jl", "max_issues_repo_name": "JuliaInv/ConvDiffMIPDECO", "max_issues_repo_head_hexsha": "95a3aead09d34811c4c2ca14279df93a0b40ecdb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/FEMvsFD.jl", "max_forks_repo_name": "JuliaInv/ConvDiffMIPDECO", "max_forks_repo_head_hexsha": "95a3aead09d34811c4c2ca14279df93a0b40ecdb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:13:38.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:13:38.000Z", "avg_line_length": 23.7251908397, "max_line_length": 138, "alphanum_fraction": 0.6145431145, "num_tokens": 1195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171238, "lm_q2_score": 0.8705972717658209, "lm_q1q2_score": 0.8082701722959753}} {"text": "# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n# jupytext:\n# text_representation:\n# extension: .jl\n# format_name: light\n# format_version: '1.5'\n# jupytext_version: 1.5.0\n# kernelspec:\n# display_name: Julia 1.4.2\n# language: julia\n# name: julia-1.4\n# ---\n\n# # 主成分分析をする\n\n# - PCA の例として MNIST 画像 dataset を主成分分析を行う\n\n# ## Load modules\n\nusing MLDatasets\nusing Images\nusing Statistics\nusing LinearAlgebra\nusing Plots\n\n# ## Download MNIST dataset\n\nMNIST.download(;i_accept_the_terms_of_use=true)\n\ntrain_x, train_y = MNIST.traindata()\ntest_x, test_y = MNIST.testdata()\n\n# ## Study data\n\n?MNIST.convert2image\n\nMNIST.traintensor(1)|>MNIST.convert2image\n\ntrain_x |> size # W, H, Num_data\n\nN = size(train_x)[end]\n\ntrain_x_nhw = permuteddimsview(train_x, (3, 2, 1)); # transpose so that it has NxHxW layout\n\nid = 4\ncolorview(Gray, train_x_nhw[id, :, :]) |> display\nprintln(\"label = $(train_y[id])\")\n\n# # Apply PCA to 7\n\nsevens = train_x[:, :, train_y .== 7];\n\nμ_sevens = dropdims(mean(sevens, dims=3),dims=3);\n\ncolorview(Gray, μ_sevens')\n\ncolorview(Gray,(sevens[:,:,1] .- μ_sevens)')\n\nX_ = sum(sevens .- μ_sevens, dims=3)/√N\nX = reshape(X_, 784)\nX |> size\n\nA = X * X'; # variance-covariance matrix w.r.t sample\n\nF = eigen(A);\nλ = F.values[end]\nv = F.vectors[:, end];\n\n# visualize the first principal vector\nnormalize_img(v) = (v .- minimum(v)) ./ (maximum(v)-minimum(v))\ncolorview(Gray, reshape(normalize_img(v),28,28)') |> display\nv\n\n# +\nλs = F.values[end:-1:end-5]\nvs = F.vectors[:, end:-1:end-5]\nnormalize(v) = (v .- minimum(v)) ./ (maximum(v)-minimum(v))\ngs = []\nfor i in 1:size(vs)[2]\n v = reshape(vs[:, i] |> normalize,28,28)'\n push!(gs, colorview(Gray, v))\nend\n\ncolorview.(Gray,gs)\n# -\n\n# # Apply PCA to whole dataset\n\ntrain_x, train_y = MNIST.traindata()\nμ_train_x = mean(train_x,dims=3)\nX_ = sum(train_x .- μ_train_x, dims=3)/√N\nX = reshape(X_, 784)\nA = X * X';\n\nF=eigen(A)\nλ1 = F.values[end]\nλ2 = F.values[end-1]\nλ3 = F.values[end-2]\nw1 = F.vectors[:, end]\nw2 = F.vectors[:, end-1]\nw3 = F.vectors[:, end-2];\n\n# ## Project 2D space\n\np = plot()\ndata = reshape(train_x,(28^2, N))\nfor i in 1:10\n d = data[:,train_y .== (i-1)][:, 1:100]\n x1 = w1' * d\n x2 = w2' * d\n scatter!(p,x1,x2, label=false, color=palette(:tab10)[i])\nend\np\n\n# ## Project 3D space\n\n# +\n#=\nIf we load `ORCA` package or use plotting operation based on PlotlyJS backend over the sysimage generated by PackageCompiler using my method, it will cause the following error.\n\"\"\"\nInitError: IOError: could not spawn `'/usr/bin/xvfb-run /root/.julia/conda/3/envs/_ORCA_jl_/bin/orca' server --port=7982 --graph-only`: no such file or directory (ENOENT)\nduring initialization of module ORCA\n\"\"\"\nWe will ignore the error at the moment, since there is no harm with respect to our purpose.\nHere is my workaround \"Just load `ORCA` and ignore the error above or plot a small dummy data in advance\"\n=#\n\nusing ORCA\n\n# +\nplotlyjs()\n\np = plot(xlabel=\"x\", ylabel=\"y\" , zlabel=\"z\")\ndata = reshape(train_x,(28^2, N))\ntarget = [0,1,2,3,4,5,6,7,8,9]\nfor i in target\n d = data[:,train_y .== i][:, 1:100]\n x1 = w1' * d\n x2 = w2' * d\n x3 = w3' * d\n color = palette(:tab10)[i+1]\n scatter!(p, \n x1, x2, x3, \n label=false, color=color,\n markersize = 2,\n )\nend\n\ndisplay(palette(:tab10)) # show color palette\np\n", "meta": {"hexsha": "412331ffc26ab49c1b2a7129f1d483b136f99a54", "size": 3335, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "experiments/notebook/apply_PCA_to_MNIST.jl", "max_stars_repo_name": "hsugawa8651/MyWorkflow.jl", "max_stars_repo_head_hexsha": "48edcbcc3fd9e425895ef91bea833ef1e5d4c3fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "experiments/notebook/apply_PCA_to_MNIST.jl", "max_issues_repo_name": "hsugawa8651/MyWorkflow.jl", "max_issues_repo_head_hexsha": "48edcbcc3fd9e425895ef91bea833ef1e5d4c3fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-09-06T12:34:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-06T12:39:46.000Z", "max_forks_repo_path": "experiments/notebook/apply_PCA_to_MNIST.jl", "max_forks_repo_name": "hsugawa8651/MyWorkflow.jl", "max_forks_repo_head_hexsha": "48edcbcc3fd9e425895ef91bea833ef1e5d4c3fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.7973856209, "max_line_length": 176, "alphanum_fraction": 0.63988006, "num_tokens": 1153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894520743981, "lm_q2_score": 0.9032942099580604, "lm_q1q2_score": 0.8082581311903492}} {"text": "\nusing DataStructures\nusing StatsBase\n\n# Problem 1\nnWashers = 5\nnTrials = 1000000\nsuccess = 0\nfor i in 1:nTrials\n rn = rand(1:nWashers,nWashers)\n if get(countmap(rn),1,0) >= 4\n success+=1\n end\nend\nsuccess/nTrials\n\n# Problem 2\nwait1 = 5\nwait2 = 7\nnTrials = 1000000\nsuccess = 0\nfor i in 1:nTrials\n rn = rand(2)\n if (0 <= (rn[2]-rn[1])*30 <= wait1) ||\n (0 <= (rn[1]-rn[2])*30 <= wait2)\n success+=1\n end\nend\nsuccess/nTrials\n\n# Problem 3\n# nCars=3; 0.6666666666644826\n# nCars=4; 0.6667395\n# nCars=5; 0.6663580000064863\n# nCars=6; 0.6665606666653675\n# nCars=7; 0.6665282857209788\n# nCars=8; 0.66674625\n# nCars=9; 0.6667986666646687\n# nCars=10; 0.6665119999960215\n# nCars=11; 0.6665550909138054\n# nCars=12; 0.6666493333327062\n# nCars=20; 0.6666518999954775\n# nCars=30; 0.6665245333273143\n\nnCars = 7\nnTrials = 1000000\nsuccess=0\nfor i in 1:nTrials\n rn = rand(nCars) \n rn = sort(rn)\n cn = zeros(nCars)\n cn[1]=2\n cn[nCars]=nCars-1\n for j in 2:nCars-1\n if rn[j+1]-rn[j] >= rn[j]-rn[j-1]\n cn[j]=j-1\n else\n cn[j]=j+1\n end \n end\n cnTotal = 0\n j = 1 \n while j <= nCars-1\n if (cn[j]==j+1 && cn[j+1]==j)\n j+=2\n cnTotal+=2\n else\n j+=1\n end\n end\n success+=cnTotal/nCars\nend\nsuccess/nTrials\n", "meta": {"hexsha": "14248b89cd97bd18a00595cdf738da677ca9945e", "size": 1361, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/Digital Dice.jl", "max_stars_repo_name": "candychiu/randomsnippet", "max_stars_repo_head_hexsha": "d581640815c68420376f8d479c3e1c59a12de635", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "julia/Digital Dice.jl", "max_issues_repo_name": "candychiu/randomsnippet", "max_issues_repo_head_hexsha": "d581640815c68420376f8d479c3e1c59a12de635", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/Digital Dice.jl", "max_forks_repo_name": "candychiu/randomsnippet", "max_forks_repo_head_hexsha": "d581640815c68420376f8d479c3e1c59a12de635", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.3918918919, "max_line_length": 42, "alphanum_fraction": 0.572373255, "num_tokens": 591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240142763573, "lm_q2_score": 0.8615382165412809, "lm_q1q2_score": 0.8082296901542}} {"text": "# ---\n# title: 754. Reach a Number\n# id: problem754\n# author: Indigo\n# date: 2021-07-11\n# difficulty: Medium\n# categories: Math\n# link: \n# hidden: true\n# ---\n# \n# You are standing at position `0` on an infinite number line. There is a goal\n# at position `target`.\n# \n# On each move, you can either go left or right. During the _n_ -th move\n# (starting from 1), you take _n_ steps.\n# \n# Return the minimum number of steps required to reach the destination.\n# \n# **Example 1:** \n# \n# \n# \n# Input: target = 3\n# Output: 2\n# Explanation:\n# On the first move we step from 0 to 1.\n# On the second step we step from 1 to 3.\n# \n# \n# **Example 2:** \n# \n# \n# \n# Input: target = 2\n# Output: 3\n# Explanation:\n# On the first move we step from 0 to 1.\n# On the second move we step from 1 to -1.\n# On the third move we step from -1 to 2.\n# \n# \n# **Note:** \n# \n# * `target` will be a non-zero integer in the range `[-10^9, 10^9]`.\n# \n# \n## @lc code=start\nusing LeetCode\n\nfunction reach_number(target::Integer)\n target = abs(target)\n k = 0\n while target > 0\n k += 1\n target = target - k\n end\n return iseven(target) ? k : k + 1 + k % 2\nend\n## @lc code=end\n", "meta": {"hexsha": "2827f8223a7138d2dadb47a75f8b72828e4171f9", "size": 1297, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/754.reach-a-number.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2020-10-27T18:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:27:49.000Z", "max_issues_repo_path": "src/problems/754.reach-a-number.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-01T07:26:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T11:57:53.000Z", "max_forks_repo_path": "src/problems/754.reach-a-number.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2020-10-30T11:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:35:11.000Z", "avg_line_length": 21.262295082, "max_line_length": 78, "alphanum_fraction": 0.5898226677, "num_tokens": 417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.938124016006303, "lm_q2_score": 0.8615382094310357, "lm_q1q2_score": 0.8082296849743226}} {"text": "export HCircle, get_center, get_radius, points_on_circle\nexport RandomHCircle, circumference, area\n\n\"\"\"\n`HCircle(P::HPoint,r::Real)` creates a new hyperbolic circle\ncentered at `P` with radius `r`.\n\"\"\"\nstruct HCircle <: HObject\n ctr::HPoint\n rad::Float64\n attr::Dict{Symbol,Any}\n function HCircle(P::HPoint,r::Real)\n @assert r>0 \"radius must be positive\"\n C = new(P,r,Dict{Symbol,Any}())\n set_color(C)\n set_thickness(C)\n set_line_style(C)\n return C\n end\nend\nHCircle(C::HCircle) = HCircle(C.ctr, C.rad) # copy constructor\n\n\"\"\"\n`HCircle(A,B,C)` creates a circle that includes the three given points.\n\"\"\"\nfunction HCircle(A::HPoint, B::HPoint, C::HPoint)\n @assert !collinear(A,B,C) \"The three points must be nonlinear\"\n L1 = bisector(A,B)\n L2 = bisector(A,C)\n @assert meet_check(L1,L2) \"There is no circle containing these three points\"\n P = meet(L1,L2)\n r = dist(A,P)\n return HCircle(P,r)\nend\n\n\"\"\"\n`RandomHCircle()` creates a random circle.\n\"\"\"\nRandomHCircle() = HCircle(RandomHPoint(), -log(rand()) )\n\n\"\"\"\n`get_center(C::HCircle)` returns the center of the circle.\n\"\"\"\nget_center(C::HCircle) = C.ctr\n\n\"\"\"\n`get_radius(C::HCircle)` returns the radius of the circle.\n\"\"\"\nget_radius(C::HCircle) = C.rad\n\nfunction show(io::IO, C::HCircle)\n print(io,\"HCircle($(C.ctr),$(C.rad))\")\nend\n\n\"\"\"\n`points_on_circle(C::HCircle)` returns a 3-tuple of points\nthat lie on the circle `C`.\n\"\"\"\nfunction points_on_circle(C::HCircle)\n P = get_center(C)\n f = inv(move2zero(P))\n r = get_radius(C)\n a = HPoint(r,0)\n b = HPoint(r,2pi/3)\n c = HPoint(r,4pi/3)\n return (f(a), f(b), f(c))\nend\n\nHCircle(r::Real = 1) = HCircle(HPoint(), r)\n\nfunction(==)(C::HCircle, CC::HCircle)\n if abs(C.rad - CC.rad) > THRESHOLD*eps(1.0)\n return false\n end\n return C.ctr == CC.ctr\nend \n\n\"\"\"\n`circumference(C::HCircle)` returns the circumference of the circle.\n\"\"\"\nfunction circumference(C::HCircle)\n r = get_radius(C)\n return 2*pi*sinh(r)\nend\n\n\"\"\"\n`area(C::HCircle)` returns the area of the circle.\n\"\"\"\nfunction area(C::HCircle)\n r = get_radius(C)\n return 4*pi*(sinh(r/2))^2\nend\n\n\nfunction in(P::HPoint, C::HCircle)::Bool\n d = dist(P, C.ctr)\n return d <= C.rad + THRESHOLD*eps(1.0) # add a bit of slop\nend\n", "meta": {"hexsha": "fca8cf48a3b32b4a5181ff765df4afe0fd45f935", "size": 2298, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/circle.jl", "max_stars_repo_name": "switzel/HyperbolicPlane.jl", "max_stars_repo_head_hexsha": "89ba26e080b520b4f200e985f2b431b1d61ecb21", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-01-19T06:12:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T22:18:48.000Z", "max_issues_repo_path": "src/circle.jl", "max_issues_repo_name": "switzel/HyperbolicPlane.jl", "max_issues_repo_head_hexsha": "89ba26e080b520b4f200e985f2b431b1d61ecb21", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-01-31T08:33:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-26T19:44:39.000Z", "max_forks_repo_path": "src/circle.jl", "max_forks_repo_name": "switzel/HyperbolicPlane.jl", "max_forks_repo_head_hexsha": "89ba26e080b520b4f200e985f2b431b1d61ecb21", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-01-31T21:10:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T18:49:43.000Z", "avg_line_length": 23.2121212121, "max_line_length": 80, "alphanum_fraction": 0.6388163621, "num_tokens": 718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240108164657, "lm_q2_score": 0.8615382129861583, "lm_q1q2_score": 0.8082296838382252}} {"text": "#=\nBy listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.\n\nWhat is the 10 001st prime number?\n=#\n\nusing Primes\nfunction findnthprime(n)\n i = 2; foundprimes = 0; lastprime = 0\n while foundprimes < n\n if isprime(i)\n foundprimes += 1\n lastprime = i\n end\n i += 1\n end\n lastprime\nend\n\n@time println(findnthprime(10_001))\n", "meta": {"hexsha": "49154c4d737bebf681936fd6258ea1c46f4591a2", "size": 385, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p7.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/p7.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/p7.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 18.3333333333, "max_line_length": 100, "alphanum_fraction": 0.6519480519, "num_tokens": 141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9381240090865198, "lm_q2_score": 0.8615382112085969, "lm_q1q2_score": 0.8082296806802377}} {"text": "##\n# Demo of using DualNumbers to differentiate with respect to\n# changes in parameters\n##\n\n\nusing DualNumbers, ApproxFun\n# What is the derivative of the function (without differentiating the Chebyshev expansion)?\nf=Fun(x->exp(dual(x,1)),-1..1)\ndualpart(f)\n# check versus differentiate\nnorm(realpart(f)'-dualpart(f))\n\n# What is the derivative of the first coefficient with respect to the left endpoint?\nf=Fun(exp,Segment(dual(1.0,1),dual(2.0)))\ndualpart(f.coefficients[1])\n# check versus finite difference calculation:\nh=0.00001;(Fun(exp,Segment(1.0+h,2.0)).coefficients[1]-Fun(exp,Segment(1.0,2.0)).coefficients[1])/h\n\n# Or an ApproxFun calculation:\nFun(h->Fun(exp,Segment(1.0+h,2.0)).coefficients[1],0..1)'(0.)\n\n# What is the derivative of the first coefficient with respect to the exponential's constant?\nf=Fun(x->exp(dual(x,x)),-1..1)\ndualpart(f.coefficients[1])\n# check versus finite difference calculation:\nh=0.00001;(Fun(x->exp((1+h)x),-1..1).coefficients[1]-Fun(exp,-1..1).coefficients[1])/h\n", "meta": {"hexsha": "c85ffa1867a35859c2a043beb98c635068218cf3", "size": 1000, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Extras/Dual Numbers.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/Dual Numbers.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/Dual Numbers.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": 35.7142857143, "max_line_length": 99, "alphanum_fraction": 0.732, "num_tokens": 311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551546097941, "lm_q2_score": 0.8376199552262967, "lm_q1q2_score": 0.8081819314041173}} {"text": "using FastGaussQuadrature\n\n\"\"\"\n get_quadpoints(n)\n\nCompute quadrature points and weights for Gaussian quadrature\nof order `n`.\nThe points (and thus the corresponding weights) are normalized to the range\n``[0.0, 1.0]``.\n\nReturn a tuple of `points, weights`.\n\"\"\"\nfunction get_quadpoints(n)\n x, w = gausslegendre(n)\n # They are scaled in [-1.0, 1.0]\n # and we need [0.0, 1.0]\n (x .+ 1)./2, w ./ 2\nend", "meta": {"hexsha": "335d30a196db96b36e0f25b86d90b461a760ef6c", "size": 412, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/basis.jl", "max_stars_repo_name": "krenzland/GigaFV.jl", "max_stars_repo_head_hexsha": "607fb4acb4a6e83a83313b59c7f68908a710efcf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/basis.jl", "max_issues_repo_name": "krenzland/GigaFV.jl", "max_issues_repo_head_hexsha": "607fb4acb4a6e83a83313b59c7f68908a710efcf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/basis.jl", "max_forks_repo_name": "krenzland/GigaFV.jl", "max_forks_repo_head_hexsha": "607fb4acb4a6e83a83313b59c7f68908a710efcf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8888888889, "max_line_length": 75, "alphanum_fraction": 0.6626213592, "num_tokens": 132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9553191271831559, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.8081449852911401}} {"text": "function chebyshev_polynomial(order::S,x::Array{T,1}) where {T<:AbstractFloat,S<:Integer}\n\n polynomial = Array{T}(undef,length(x),order+1)\n polynomial[:,1] = ones(T,length(x))\n \n for i = 2:order+1\n for j = 1:length(x)\n if i == 2\n polynomial[j,i] = x[j]\n else\n polynomial[j,i] = 2*x[j]*polynomial[j,i-1]-polynomial[j,i-2]\n end\n end\n end\n \n return polynomial\n \nend\n\nfunction chebyshev_polynomial(order::S,x::T) where {T<:AbstractFloat,S<:Integer}\n\n polynomial = ones(T,1,order+1)\n \n for i = 2:order+1\n if i == 2\n polynomial[1,i] = x\n else\n polynomial[1,i] = 2*x*polynomial[1,i-1]-polynomial[1,i-2]\n end\n end\n \n return polynomial\n \nend\n", "meta": {"hexsha": "c37ba329cf8137d350759190c1b051fc1c61ce1d", "size": 709, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chebyshev_polynomial.jl", "max_stars_repo_name": "RJDennis/SmolyakApprox.jl", "max_stars_repo_head_hexsha": "42a669e34fb2417341b24936c1b72873c3c25857", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2018-04-23T15:47:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T10:38:53.000Z", "max_issues_repo_path": "src/chebyshev_polynomial.jl", "max_issues_repo_name": "RJDennis/SmolyakApprox.jl", "max_issues_repo_head_hexsha": "42a669e34fb2417341b24936c1b72873c3c25857", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2017-08-08T00:07:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T11:53:45.000Z", "max_forks_repo_path": "src/chebyshev_polynomial.jl", "max_forks_repo_name": "RJDennis/SmolyakApprox.jl", "max_forks_repo_head_hexsha": "42a669e34fb2417341b24936c1b72873c3c25857", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-12-22T21:24:48.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-07T21:47:10.000Z", "avg_line_length": 20.2571428571, "max_line_length": 89, "alphanum_fraction": 0.5952045134, "num_tokens": 243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191259110588, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.8081449842150191}} {"text": "\nusing JuMP, Ipopt\nmodel = Model(with_optimizer(Ipopt.Optimizer));\n\n\n@variable(model, x, start = 4)\n@variable(model, y, start = -9.66);\n\n\n@NLparameter(model, p == 0.003); # Providing a starting value is necessary for parameters\n@NLparameter(model, l[i = 1:10] == 4 - i); # A collection of parameters\n\n\nvalue(l[1])\n\n\nset_value(l[1], -4)\nvalue(l[1])\n\n\n@NLexpression(model, expr_1, sin(x))\n@NLexpression(model, expr_2, asin(expr_1)); # Inserting one expression into another\n\n\n@NLconstraint(model, exp(x) + y^4 <= 0)\n@NLobjective(model, Min, tan(x) + log(y))\n\n\nmy_function(a,b) = (a * b)^-6 + (b / a)^3\nregister(model, :my_function, 2, my_function, autodiff = true)\n\n\nusing Random, Statistics\n\nn = 1_000\ndata = randn(n)\n\nmle = Model(with_optimizer(Ipopt.Optimizer, print_level = 0))\n@NLparameter(mle, problem_data[i = 1:n] == data[i])\n@variable(mle, μ, start = 0.0)\n@variable(mle, σ >= 0.0, start = 1.0)\n@NLexpression(mle, likelihood, \n(2 * π * σ^2)^(-n / 2) * exp(-(sum((problem_data[i] - μ)^2 for i in 1:n) / (2 * σ^2)))\n)\n\n@NLobjective(mle, Max, log(likelihood))\n\noptimize!(mle)\n\nprintln(\"μ = \", value(μ))\nprintln(\"mean(data) = \", mean(data))\nprintln(\"σ^2 = \", value(σ)^2)\nprintln(\"var(data) = \", var(data))\nprintln(\"MLE objective: \", objective_value(mle))\n\n\n# Changing the data\n\ndata = randn(n)\noptimize!(mle)\n\nprintln(\"μ = \", value(μ))\nprintln(\"mean(data) = \", mean(data))\nprintln(\"σ^2 = \", value(σ)^2)\nprintln(\"var(data) = \", var(data))\nprintln(\"MLE objective: \", objective_value(mle))\n\n", "meta": {"hexsha": "a44901dcd430a9a0b38dbc768029c3092c28c11e", "size": 1489, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/using_JuMP/nonlinear_modelling.jl", "max_stars_repo_name": "carlosal1015/JuMPTutorials.jl", "max_stars_repo_head_hexsha": "4d9a86ea310ecc7a22de7f14b783dbd218e4b612", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/using_JuMP/nonlinear_modelling.jl", "max_issues_repo_name": "carlosal1015/JuMPTutorials.jl", "max_issues_repo_head_hexsha": "4d9a86ea310ecc7a22de7f14b783dbd218e4b612", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/using_JuMP/nonlinear_modelling.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": 21.8970588235, "max_line_length": 89, "alphanum_fraction": 0.6487575554, "num_tokens": 495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176863577751, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.8080748568401664}} {"text": "function synthetic_spiral_data(N, degrees, start, σ)\n s = deg2rad(start)\n N₀ = floor(Int, N/2)\n\n X = Matrix{Float64}(undef, 2, N)\n t = [ones(Int, N₀); -ones(Int, N-N₀)]\n\n for n in 1:N₀\n θ = s + sqrt(first(rand(1))) * deg2rad(degrees)\n X[:,n] = [-cos(θ) * θ + σ * first(rand(1)), sin(θ) * θ + σ * first(rand(1))]\n end\n\n for n in N₀+1:N\n θ = s + sqrt(first(rand(1))) * deg2rad(degrees)\n X[:,n] = [cos(θ) * θ + σ * first(rand(1)), -sin(θ) * θ + σ * first(rand(1))]\n end\n\n X, t\nend\n\nfunction synthetic_circular_data(N, radius₁, radius₂, σ)\n N₀ = floor(Int, N/2)\n\n X = Matrix{Float64}(undef, 2, N)\n t = [ones(Int, N₀); -ones(Int, N-N₀)]\n\n for n in 1:N₀\n θ = n / (2 * π)\n X[1,n] = radius₁ * cos(θ) + σ * randn()\n X[2,n] = radius₁ * sin(θ) + σ * randn()\n end\n\n for n in N₀+1:N\n θ = n / (2 * π)\n X[1,n] = radius₂ * cos(θ) + σ * randn()\n X[2,n] = radius₂ * sin(θ) + σ * randn()\n end\n\n X, t\nend\n", "meta": {"hexsha": "363a642c1a16c46df56eaee8994dd9673ce2e0ed", "size": 1006, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/synthetic_data.jl", "max_stars_repo_name": "rjww/AdvancedTopics.jl", "max_stars_repo_head_hexsha": "76207f6b17d37129324c671c4f3e4da5bd5704dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/synthetic_data.jl", "max_issues_repo_name": "rjww/AdvancedTopics.jl", "max_issues_repo_head_hexsha": "76207f6b17d37129324c671c4f3e4da5bd5704dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/synthetic_data.jl", "max_forks_repo_name": "rjww/AdvancedTopics.jl", "max_forks_repo_head_hexsha": "76207f6b17d37129324c671c4f3e4da5bd5704dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-01-07T02:50:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-27T20:20:11.000Z", "avg_line_length": 24.5365853659, "max_line_length": 84, "alphanum_fraction": 0.4821073559, "num_tokens": 404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176857294597, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.8080748514627218}} {"text": "alphabet = \"0123456789abcdefghijklmnopqrstuvwxyz\" # Only supports thru base 36\nintfloor(x) = convert(Int,floor(x))\n\n\"\n convertintrep(n::Int, base::Int)\n\nConverts the input `n` ≧ 0 into its string representation with respect to\n`base`.\n\"\nfunction convertintrep(n::Int, base::Int)\n result = \"\"\n while n > 1\n result *= \"$(alphabet[1 + (n % base)])\"\n n = intfloor(n / base) \n end\n\n result[end:-1:1]\nend\n\n\"\n convertfracrep(n::Real, base::Int, precision)\n\nConverts the input 0 ≦ `n` < 1 into its string representation with respect to\n`base` for `precision` number of places.\n\"\nfunction convertfracrep(n::Real, base::Int, precision)\n result = \".\"\n for _ in 1:precision\n n *= base\n result *= \"$(alphabet[1 + intfloor(n)])\"\n n -= intfloor(n)\n end\n\n result\nend\n\n\"\n convertfloat(n::Real, base::Int, precision)\n\nConverts a real number `n` into its string representation with respect to\n`base` by a fixed `precision`. This is a concatenation of `convertintrep` and\n`convertfracrep`.\n\"\nfunction convertfloat(n::Real, base::Int, precision)\n result = \"\"\n if n < 0\n result *= \"-\"\n n *= -1\n end\n intpart = intfloor(n)\n fracpart = n - floor(n)\n result *= convertintrep(intpart, base) * convertfracrep(fracpart, base, precision)\nend\n\nint2dec(n::Int) = convertintrep(n, 10)\nint2bin(n::Int) = \"0b\" * convertintrep(n, 2)\nint2hex(n::Int) = \"0x\" * convertintrep(n, 16)\n", "meta": {"hexsha": "d6a4a7ddbab14ef75729b5193e730a792b52e529", "size": 1447, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chapter-0/02_binary_numbers.jl", "max_stars_repo_name": "kraemerd17/numerical-julia", "max_stars_repo_head_hexsha": "3cfef336ca327ec772ccf4058edacc4e8243f4c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/chapter-0/02_binary_numbers.jl", "max_issues_repo_name": "kraemerd17/numerical-julia", "max_issues_repo_head_hexsha": "3cfef336ca327ec772ccf4058edacc4e8243f4c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/chapter-0/02_binary_numbers.jl", "max_forks_repo_name": "kraemerd17/numerical-julia", "max_forks_repo_head_hexsha": "3cfef336ca327ec772ccf4058edacc4e8243f4c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9482758621, "max_line_length": 86, "alphanum_fraction": 0.6385625432, "num_tokens": 429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176857294597, "lm_q2_score": 0.8558511506439708, "lm_q1q2_score": 0.8080748497269891}} {"text": "#=\n\n@author : Victoria Gregory, John Stachurski\n\n=#\n\n\nstruct LakeModel{TF <: AbstractFloat}\n λ::TF\n α::TF\n b::TF\n d::TF\n g::TF\n A::Matrix{TF}\n A_hat::Matrix{TF}\nend\n\n\"\"\"\nConstructor with default values for `LakeModel`\n\n##### Fields of `LakeModel`\n\n - λ : job finding rate\n - α : dismissal rate\n - b : entry rate into labor force\n - d : exit rate from labor force\n - g : net entry rate\n - A : updates stock\n - A_hat : updates rate\n\n\"\"\"\nfunction LakeModel(;λ::AbstractFloat=0.283,\n α::AbstractFloat=0.013,\n b::AbstractFloat=0.0124,\n d::AbstractFloat=0.00822)\n\n g = b - d\n A = [(1-λ) * (1-d) + b (1-d) * α + b;\n (1-d) * λ (1-d) * (1-α)]\n A_hat = A ./ (1 + g)\n\n return LakeModel(λ, α, b, d, g, A, A_hat)\nend\n\n\"\"\"\nFinds the steady state of the system :math:`x_{t+1} = \\hat A x_{t}`\n\n##### Arguments\n\n - lm : instance of `LakeModel`\n - tol: convergence tolerance\n\n##### Returns\n\n - x : steady state vector of employment and unemployment rates\n\n\"\"\"\n\nfunction rate_steady_state(lm::LakeModel, tol::AbstractFloat=1e-6)\n x = 0.5 * ones(2)\n error = tol + 1\n while (error > tol)\n new_x = lm.A_hat * x\n error = maximum(abs, new_x - x)\n x = new_x\n end\n return x\nend\n\n\"\"\"\nSimulates the the sequence of Employment and Unemployent stocks\n\n##### Arguments\n\n - X0 : contains initial values (E0, U0)\n - T : number of periods to simulate\n\n##### Returns\n\n - X_path : contains sequence of employment and unemployment stocks\n\n\"\"\"\n\nfunction simulate_stock_path{TF<:AbstractFloat}(\n lm::LakeModel, X0::AbstractVector{TF}, T::Integer)\n X_path = Array{TF}(2, T)\n X = copy(X0)\n for t in 1:T\n X_path[:, t] = X\n X = lm.A * X\n end\n return X_path\nend\n\n\"\"\"\nSimulates the the sequence of employment and unemployent rates.\n\n##### Arguments\n\n - X0 : contains initial values (E0, U0)\n - T : number of periods to simulate\n\n##### Returns\n\n - X_path : contains sequence of employment and unemployment rates\n\n\"\"\"\nfunction simulate_rate_path{TF<:AbstractFloat}(lm::LakeModel,\n x0::Vector{TF}, T::Integer)\n x_path = Array{TF}(2, T)\n x = copy(x0)\n for t in 1:T\n x_path[:, t] = x\n x = lm.A_hat * x\n end\n return x_path\nend\n", "meta": {"hexsha": "cae2c1423641b23fa020725727cd104bc3be31a4", "size": 2359, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lake_model/lake_model.jl", "max_stars_repo_name": "chenwang/QuantEcon.lectures.code", "max_stars_repo_head_hexsha": "8832a74acd219a71cb0a99dc63c5e976598ac999", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lake_model/lake_model.jl", "max_issues_repo_name": "chenwang/QuantEcon.lectures.code", "max_issues_repo_head_hexsha": "8832a74acd219a71cb0a99dc63c5e976598ac999", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lake_model/lake_model.jl", "max_forks_repo_name": "chenwang/QuantEcon.lectures.code", "max_forks_repo_head_hexsha": "8832a74acd219a71cb0a99dc63c5e976598ac999", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-30T13:08:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-30T13:08:09.000Z", "avg_line_length": 19.9915254237, "max_line_length": 74, "alphanum_fraction": 0.5735481136, "num_tokens": 704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037363973294, "lm_q2_score": 0.8723473614033683, "lm_q1q2_score": 0.8080586203042915}} {"text": "export PermutationGraph, RandomPermutationGraph\nexport PermutationRepresentation\n\n\"\"\"\n`perm_adj(a,b)` is used to test for adajency in permutation graphs.\nThis function is not exported.\n\"\"\"\nfunction perm_adj(a::Tuple{S,T}, b::Tuple{S,T}) where {S<:Real,T<:Real}\n if a[1] < b[1]\n return a[2] > b[2]\n end\n return a[2] < b[2]\nend\n\n\"\"\"\n`PermutationGraph(p::Permutation,q::Permutation)` builds a permutation\ngraph based on the permutations `p` and `q`. The vertex set is `1:n`\nwhere `n` is the length of the permutations.\n\"\"\"\nfunction PermutationGraph(p::Permutation, q::Permutation)\n n = length(p)\n if length(q) != n\n error(\"Two permutations must be the same length\")\n end\n G = IntGraph(n)\n for u = 1:n-1\n for v = u+1:n\n if perm_adj((p[u], q[u]), (p[v], q[v]))\n add!(G, u, v)\n end\n end\n end\n return G\nend\n\n\"\"\"\n`PermutationGraph(p::Permutation)` is equivalent to\n`PermutationGraph(p,id)` where `id` is the identity permutation.\n\"\"\"\nfunction PermutationGraph(p::Permutation)\n n = length(p)\n q = Permutation(n)\n return PermutationGraph(p, q)\nend\n\n\"\"\"\n`PermutationGraph(d::Dict)` creates a permutation graph form a\ndictionary that maps vertex names to pairs of real numbers.\nThe vertex type of the resulting graph is the key type of `d`.\nThe values in `d` must be all `Tuple{S,T}` where `S` and `T` are\nsubtypes of `Real`. For example, declare `d` like this:\n`d = Dict{String, Tuple{Int,Int}}()`.\n\"\"\"\nfunction PermutationGraph(d::Dict{VV,Tuple{S,T}}) where {VV,S<:Real,T<:Real}\n vtcs = collect(keys(d))\n G = SimpleGraph{VV}()\n for v in vtcs\n add!(G, v)\n end\n\n n = length(vtcs)\n for i = 1:n-1\n u = vtcs[i]\n for j = i+1:n\n v = vtcs[j]\n if perm_adj(d[u], d[v])\n add!(G, u, v)\n end\n end\n end\n return G\nend\n\n\n\"\"\"\n`PermutationGraph(f::Dict,g::Dict)` constructs a permutation graph\nfrom a pair of mappings from a vertex set to real values.\n\"\"\"\nfunction PermutationGraph(f::Dict{T,R}, g::Dict{T,S}) where {T,R<:Real,S<:Real}\n # mush the two dictionaries into one\n h = Dict{T,Tuple{R,S}}()\n for k in keys(f)\n h[k] = f[k], g[k]\n end\n\n # invoke previous method\n G = PermutationGraph(h)\n cache_save(G, :PermutationRepresentation, (f, g))\n cache_save(G, :name, \"Permutation graph\")\n return G\nend\n\n\"\"\"\n`RandomPermutationGraph(n)` creates a random permutation graph with\n`n` vertices.\n\"\"\"\nfunction RandomPermutationGraph(n::Int)\n p = RandomPermutation(n)\n q = RandomPermutation(n)\n return PermutationGraph(p, q)\nend\n\n\n\"\"\"\n`PermutationRepresentation(G)` returns a pair of dictionaries mapping\nthe vertices of `G` to integers. This pair of dictionaries form a\npermutation representation of `G`. (If `G` is not a permutation graph,\nan error is thrown.\n\"\"\"\nfunction PermutationRepresentation(G::SimpleGraph)\n if cache_check(G, :PermutationRepresentation)\n return cache_recall(G, :PermutationRepresentation)\n end\n A = SimpleDigraph()\n try\n A = transitive_orientation(complement(G))\n catch\n error(\"This graph does not have a permutation representation\")\n end\n G1 = deepcopy(A)\n G2 = transitive_orientation(G)\n for e in elist(G2)\n add!(G1, e[1], e[2])\n end\n T = eltype(G)\n sigma = Dict{T,Int}()\n tau = Dict{T,Int}()\n vs1 = sort(vlist(G1), by = v -> out_deg(G1, v), rev = true)\n i = 1\n for v in vs1\n sigma[v] = i\n i = i + 1\n end\n G3 = deepcopy(A)\n for e in elist(G2)\n add!(G3, e[2], e[1])\n end\n vs2 = sort(vlist(G3), by = v -> out_deg(G3, v), rev = true)\n j = 1\n for v in vs2\n tau[v] = j\n j = j + 1\n end\n cache_save(G, :PermutationRepresentation, (sigma, tau))\n return sigma, tau\nend\n", "meta": {"hexsha": "9878ce7d4698230d7916b7ad946f2887f5d8ca62", "size": 3840, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/PermutationGraphs.jl", "max_stars_repo_name": "scheinerman/SimpleGraphRepresentations.jl", "max_stars_repo_head_hexsha": "815367c0a545ef60e49f8b26944770f50b42a407", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/PermutationGraphs.jl", "max_issues_repo_name": "scheinerman/SimpleGraphRepresentations.jl", "max_issues_repo_head_hexsha": "815367c0a545ef60e49f8b26944770f50b42a407", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PermutationGraphs.jl", "max_forks_repo_name": "scheinerman/SimpleGraphRepresentations.jl", "max_forks_repo_head_hexsha": "815367c0a545ef60e49f8b26944770f50b42a407", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-14T01:13:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-14T01:13:04.000Z", "avg_line_length": 26.1224489796, "max_line_length": 79, "alphanum_fraction": 0.6169270833, "num_tokens": 1131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303724190573, "lm_q2_score": 0.8723473713594991, "lm_q1q2_score": 0.8080586188781609}} {"text": "\"\"\"\n find_global_maximum(graph::Dict{Int64,Array{Int64,1}})\n\nFind the total global maximum based on a comparsion between the intial vertex\n(`global_maximum = 0`), the current dictionary key, and the accesible vertexes from\nthe array-list (value).\n\n\n# Arguments\n- `graph::Dict{Int64,Array{Int64,1}}`: Graph of the connected nodes\n\"\"\"\nfunction find_global_maximum(graph::Dict{Int64,Array{Int64,1}})\n global_maximum = 0\n # Going through the dictionary\n for (key, value) in graph\n # Check the keys as new global maximum\n if key > global_maximum\n global_maximum = key\n end\n\n # Check the values as new local maximum\n local_maximum = maximum(value)\n\n # Check if new local maximum becomes global maximum\n if local_maximum > global_maximum\n global_maximum = local_maximum\n end\n end\n return global_maximum\nend\n\n\n\"\"\"\n find_parent_in_cycle(parent::Array{Int64,1}, i::Int64, ref_key::Int64)\n\nThe find parent algorithm is a recursive function to find the subeset of an item i for\ngraph test of being cycling.\n\n# Arguments\n- `parent::Array{Int64,1}`: Array of the subset of the items\n- `i::Int64`: Index of the parents-item\n- `ref_key::Int64`: Reference Key, which can be for example the total size of the subset\n\"\"\"\nfunction find_parent_in_cycle(parent::Array{Int64,1}, i::Int64, ref_key::Int64)\n if parent[i] == ref_key\n return i\n end\n return find_parent_in_cycle(parent, parent[i], ref_key)\nend\n\n\n\"\"\"\n graph_cycle_check(graph::Dict{Int64,Array{Int64,1}})\n\nThe disjoint-set data structure principle is used to check if a direct or undirect\ngraph contains a cycle. For this reason, the algorithm keeps the first track of a set\nof items partitioned into several disjoint (non-overlapping) subsets to find which\nsubset a particular item is kept. This procedure is essential to figure out if two\nitems are in the same subgroup. Next, the two subsets have to be merged into a single\nsubset. For more information see: [https://en.wikipedia.org/wiki/Disjoint-set_data_structure](https://en.wikipedia.org/wiki/Disjoint-set_data_structure)\n\n\n# Arguments\n- `graph::Dict{Int64,Array{Int64,1}}`: Graph of the connected nodes\n\n\n# Examples\n```julia-repl\njulia> import ClassicAlgorithmsCollections\njulia> graph_cycle_true = Dict(1 => [2], 2 => [3], 3 => [1, 4])\njulia> ClassicAlgorithmsCollections.graph_cycle_check(graph_cycle_true)\ntrue\njulia> graph_cycle_false = Dict(1 => [2], 2 => [5], 3 => [1, 4])\njulia> ClassicAlgorithmsCollections.graph_cycle_check(graph_cycle_false)\nfalse\n```\n\"\"\"\nfunction graph_cycle_check(graph::Dict{Int64,Array{Int64,1}})\n # Get the maximum length of the vertex\n vertex_size = find_global_maximum(graph)\n\n # Create array-list for finding the parents and intialize all subsets to vertex_size, because\n # negative indixing is forbidden in Julia.\n parent = fill(vertex_size, vertex_size)\n\n # Iterate through all edges of graph for finding the subset of both vertices of every edge.\n # If the two subsets are equal, then graph has a cycle inside.\n for (i, values) in graph\n for j in values\n x = find_parent_in_cycle(parent, i, vertex_size)\n y = find_parent_in_cycle(parent, j, vertex_size)\n\n # Check if equal, then graph has a cycle\n if x == y\n return true\n end\n\n x_set = find_parent_in_cycle(parent, x, vertex_size)\n y_set = find_parent_in_cycle(parent, y, vertex_size)\n # Update the parent-set\n parent[x_set] = y_set\n end\n end\n return false\n\nend\n", "meta": {"hexsha": "3d15c4a9c5f15ee2946291c266073f4942c2749d", "size": 3623, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Graph/GraphCycleCheck.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/Graph/GraphCycleCheck.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/Graph/GraphCycleCheck.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.8598130841, "max_line_length": 152, "alphanum_fraction": 0.7016284847, "num_tokens": 906, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133531922389, "lm_q2_score": 0.8596637559030337, "lm_q1q2_score": 0.8080094434286548}} {"text": "import Base: +, -, *, /, abs, sqrt, ≈, conj, real, imag, exp, ==\n\nstruct ComplexNumber <: Number\n real::Real\n imag::Real\nend\n\nconst jm = ComplexNumber(0, 1)\n\nabs(x::ComplexNumber) = sqrt(x.real^2 + x.imag^2)\n\n+(x::ComplexNumber, y::ComplexNumber) = ComplexNumber(x.real + y.real, x.imag + y.imag)\n\n+(x::Real, y::ComplexNumber) = ComplexNumber(x + y.real, y.imag)\n\n-(x::ComplexNumber, y::ComplexNumber) = ComplexNumber(x.real - y.real, x.imag - y.imag)\n\nfunction *(x::ComplexNumber, y::ComplexNumber)\n real = x.real * y.real - x.imag * y.imag\n imag = x.imag * y.real + x.real * y.imag\n return ComplexNumber(real, imag)\nend\n\n*(x::Real, y::ComplexNumber) = ComplexNumber(x * y.real, x * y.imag)\n\nfunction /(x::ComplexNumber, y::ComplexNumber)\n real = (x.real * y.real + x.imag * y.imag) / (y.real^2 + y.imag^2)\n imag = (x.imag * y.real - x.real * y.imag) / (y.real^2 + y.imag^2)\n return ComplexNumber(real, imag)\nend\n\nexp(x::ComplexNumber) = exp(x.real) * ComplexNumber(cos(x.imag), sin(x.imag))\n\n==(x::ComplexNumber, y::ComplexNumber) = (x.real == y.real) && (x.imag == y.imag)\n\n≈(x::ComplexNumber, y::ComplexNumber) = isapprox(x.real, y.real, atol=1e-6) && isapprox(x.imag, y.imag, atol=1e-6)\n\nconj(x::ComplexNumber) = ComplexNumber(x.real, -x.imag)\n\nreal(x::ComplexNumber) = x.real\n\nimag(x::ComplexNumber) = x.imag\n", "meta": {"hexsha": "adf35afdff3b03fc09be6bbbb6e638acfd45ef62", "size": 1339, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "exercism-solutions/julia/complex-numbers/complex-numbers.jl", "max_stars_repo_name": "twolodzko/Learning", "max_stars_repo_head_hexsha": "e5af2bdf6f65648c3c159343e14d63c157384009", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exercism-solutions/julia/complex-numbers/complex-numbers.jl", "max_issues_repo_name": "twolodzko/Learning", "max_issues_repo_head_hexsha": "e5af2bdf6f65648c3c159343e14d63c157384009", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exercism-solutions/julia/complex-numbers/complex-numbers.jl", "max_forks_repo_name": "twolodzko/Learning", "max_forks_repo_head_hexsha": "e5af2bdf6f65648c3c159343e14d63c157384009", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1395348837, "max_line_length": 114, "alphanum_fraction": 0.641523525, "num_tokens": 429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133548753619, "lm_q2_score": 0.8596637523076224, "lm_q1q2_score": 0.8080094414961995}} {"text": "include(\"header.jl\")\n\n#=\n# The Blasius and Falkner-Skan boundary layers\n\nThis notebook focuses on the solution of the boundary layer equations when the\nexternal velocity outside the boundary layer has the form of flow past a wedge,\nas in the diagram below:\n\n\"wedge\n=#\n\n#=\nFor the flow past a wedge with half-angle $\\beta/2$, potential flow theory predicts\nthat the external velocity has the form,\n$$U_e(x) = A x^{m}$$\nwhere $A$ is a positive constant and\n$$ m = \\frac{\\beta}{2-\\beta}$$\n\nOur focus here is on the boundary layer that develops along the wall of the wedge.\nThe boundary-layer flow has a **self-similar form** as it develops along the $x$ direction. Just as the Rayleigh flow develops with the same profile shape in time, with a time-varying thickness $\\delta(t) = (\\nu t)^{1/2}$, the boundary layer's profile has the same shape at every $x$ location, but with **spatially-varying thickness** proportional to\n$$\\delta(x) = \\left( \\frac{\\nu x}{U_e(x)}\\right)^{1/2}$$\n\nThis means that the velocity tangent to the wall can be written in the form\n$$ u(x,y) = U_e(x) F'(\\eta) $$\nwhere\n$$\\eta = \\dfrac{y}{\\delta(x)}$$\n\nWith this form, the boundary layer equations reduce to an ordinary differential\nequation for $F$ in this case,\n\n$$ F''' + \\frac{1}{2} (m+1) F F'' + m (1-F'^2) = 0$$\n\nThis is called the **Falkner-Skan equation**. The equation is non-linear, however,\nand must be solved computationally. The tools to solve it are provided for you here.\n=#\n\n#=\n#### Boundary conditions\nThe boundary conditions on the flow are no-slip ($u = 0$ at $y = 0$), no-flow-through\n($v = 0$ at $y = 0$). Also, the flow must approach the external velocity outside\nthe boundary layer. This means $u \\rightarrow U_e$ as $y \\rightarrow \\infty$.\n=#\n\n#=\n#### Special cases\nThe case $\\beta = 0$ (so that $m = 0$) corresponds to a flat plate, parallel to\nfree stream, and $U_e(x) = U_\\infty$. This is called a **Blasius boundary layer**.\n\nWhen $\\beta > 0$, the external flow is accelerating, and the pressure gradient\nis said to be **favorable**.\n\nWhen $\\beta < 0$, the external flow is decelerating, and the pressure gradient\nis adverse. The lowest admissible value of $\\beta$ is approximately $-0.1999$.\nBelow this, the boundary layer equations do not hold.\n\n#### Other boundary-layer quantities\n*Every* measure of thickness of the boundary layer is proportional to $\\delta(x)$.\nHowever, we need the solution of the Falkner-Skan equation to determine what\nthe constant of proportionality is.\n\nFor example, the 99% thickness is\n\n$$\\delta_{99}(x) = C_{1}\\delta(x)$$\n\nthe displacement thickness is\n\n$$\\delta^{*}(x) = C_{2} \\delta(x)$$\n\nand the momentum thickness is\n\n$$\\theta(x) = C_{3} \\delta(x)$$\n\nThese constants $C_1$, $C_2$ and $C_3$ depend on $\\beta$, and they can only be\nfound by solving the Falkner-Skan problem.\n\nAnother quantity of interest is the **skin friction coefficient**,\n\n$$c_{f} = \\dfrac{\\tau_{w}}{\\frac{1}{2} \\rho U_e^2} $$\n\nIt can be shown that the skin friction coefficient of a Falkner-Skan boundary layer must be of the form\n\n$$c_{f} = \\dfrac{C_4}{(U_e(x) x/\\nu)^{1/2}} $$\n\nAs with the other constants, $C_4$ can only be found by solving the Falkner-Skan\nequation.\n=#\n\n# ### Set up the module\nusing MAE250B\n#-\nusing Plots\n\n#=\n### Generate the velocity profile and other solution features\nHere, we will compute the self-similar velocity profile and compute other\nboundary-layer quantities. The only required input for this `falknerskan` function\nis $\\beta$. It returns the all of the aspects of the solution described above.\n=#\n\nβ = 0.0\nsol = falknerskan(β);\n\n#=\nFor example, the proportionality constant on the 99 percent thickness is\n=#\nd99(sol)\n\n#=\nwhich means that, for $\\beta = 0$,\n\n$$\\delta_{99}(x) = 4.91 \\sqrt{\\dfrac{\\nu x}{U_e}} $$\n\nor, in other words,\n\n$$\\dfrac{\\delta_{99}(x)}{x} = \\dfrac{4.91}{\\sqrt{Re_x}} $$\n\nSimilarly, the momentum thickness:\n=#\ntheta(sol)\n\n#=\nso that\n\n$$\\dfrac{\\theta(x)}{x} = \\dfrac{0.664}{\\sqrt{Re_x}} $$\n=#\n\n#=\n#### Let's plot the profile\n=#\nplot(u(sol),η(sol),xlim=(0,2),ylim=(0,Inf),xlabel=L\"F'(\\eta) = u/U_e\",ylabel=L\"\\eta = y/\\delta(x)\")\n\n#=\nThe vertical velocity profile is\n=#\nplot(v(sol),η(sol),xlim=(0,2),ylim=(0,Inf),xlabel=L\"v/U_e/Re_x^{1/2}\",ylabel=L\"\\eta = y/\\delta(x)\")\n\n\n#=\n#### Drag force\nWhen $\\beta = 0$ (Blasius), the drag coefficient on a plate of length $L$ is equal to\n\n$$C_D = \\dfrac{4\\theta(L)}{L} = \\dfrac{2.656}{\\sqrt{Re_L}}$$\n=#\n\n#=\nIf you wish to specify a wall velocity, you can use the optional argument `Vw = `,\ne.g.,\n=#\nsol = falknerskan(β,Vw=0.2)\nplot(u(sol),η(sol),xlim=(0,2),ylim=(0,Inf),xlabel=L\"F'(\\eta) = u/U_e\",ylabel=L\"\\eta = y/\\delta(x)\")\n", "meta": {"hexsha": "010be7428b75289c3ff5410ddd32ebb554313d44", "size": 4766, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/literate/3.2-BlasiusAndFalknerSkan.jl", "max_stars_repo_name": "UCLAMAEThreads/MAE250B", "max_stars_repo_head_hexsha": "e5624d302eb216401827130e74ff95d9886adc90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/literate/3.2-BlasiusAndFalknerSkan.jl", "max_issues_repo_name": "UCLAMAEThreads/MAE250B", "max_issues_repo_head_hexsha": "e5624d302eb216401827130e74ff95d9886adc90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/literate/3.2-BlasiusAndFalknerSkan.jl", "max_forks_repo_name": "UCLAMAEThreads/MAE250B", "max_forks_repo_head_hexsha": "e5624d302eb216401827130e74ff95d9886adc90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3552631579, "max_line_length": 350, "alphanum_fraction": 0.6898866974, "num_tokens": 1460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.920789673717312, "lm_q2_score": 0.8774767874818409, "lm_q1q2_score": 0.8079715648399194}} {"text": "\"\"\"\nA palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.\n\nFind the largest palindrome made from the product of two 3-digit numbers.\n\"\"\"\n\nispalindrome(a) = string(a) == reverse(string(a))\n\n## Bruteforce Method\nn = 100:999\npalindromes = []\n\nfor i = n\n for j = n\n ispalindrome(i*j) && push!(palindromes,i*j)\n end\nend\n\nfindmax(palindromes)", "meta": {"hexsha": "11e40fccf3dc1e8306359ac8900ce8ee4819df66", "size": 430, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/P4_largest_palindrome_product.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/P4_largest_palindrome_product.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/P4_largest_palindrome_product.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": 22.6315789474, "max_line_length": 133, "alphanum_fraction": 0.6906976744, "num_tokens": 128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026550642018, "lm_q2_score": 0.8807970654616711, "lm_q1q2_score": 0.8079574867207485}} {"text": "\nfunction normal_approximation_to_binomial(n, p)\n mu = n * p\n sigma = sqrt(n * (1-p) * p)\n return mu, sigma \nend\n\nmu, sigma = normal_approximation_to_binomial(1000, 0.5)\nprintln(mu)\nprintln(sigma)\n\n@assert mu == 500 \n@assert 15.8 < sigma < 15.9", "meta": {"hexsha": "c5c40961eb9986e6daa5e1ca402bc34b90be8f45", "size": 253, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scratch/julia/e1-binomial-mu-sigma.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/e1-binomial-mu-sigma.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/e1-binomial-mu-sigma.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": 19.4615384615, "max_line_length": 55, "alphanum_fraction": 0.6679841897, "num_tokens": 85, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9621075777163567, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.807914409704442}} {"text": "### A Pluto.jl notebook ###\n# v0.14.0\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n quote\n local el = $(esc(element))\n global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n el\n end\nend\n\n# ╔═╡ 7cd44a22-91f0-11eb-056d-699740ca7da9\n#Set up the working environment\nbegin\n\tusing Pkg\n\tPkg.activate(\"..\")\n\tusing Plots, PlutoUI,LaTeXStrings, DifferentialEquations\nend\n\n# ╔═╡ 3199bb4e-91ed-11eb-37fa-abed99588e6b\nmd\"\"\"\n# Epidemics - The SIR Model\n- developed by *Kermack* and *McKendric* in the 1930s to describe the spread of malaria\n- describes the spread of a disease from a population of infected individuals over time\n- The total population is constant and is divided into three groups: *susceptible (S), infected (I) and recovered (R)*\n- immune and deceased individuals are \"lumped\" together into group R\n- only susceptible individuals can get the disease\n- the incubation period is negligible - infected individuals are infectious right away\n\n$$S \\xrightarrow{r} I \\xrightarrow{a} R$$\n\nThis gives rise to the following set of differential equations:\n\n$$\\begin{aligned}\n\t\\frac{dS}{dt} = -rSI\\\\\n\t\\frac{dI}{dt} = rSI - aI\\\\\n\t\\frac{dR}{dt} = aI\n\\end{aligned}$$\n\nS, I & R represent parts of a constant total population, hence the following two relations hold\n\n$$S(t) + I(t) + R(t) = N$$\n\n$$\\frac{dS}{dt} + \\frac{dI}{dt} + \\frac{dR}{dt} = 0$$\n\n> If the latter relationship does not immediately make sense to you, pause for a second to figure it out.\n\nIn order to make things a bit more comparable, we'll consider the total population to be normalised. Hence $N=1$, and values for $S$, $I$, and $R$ correspond to fractions of the population.\n\n## Finding the right parameters\nOnce we have formulated a model - establishing a way how things depend on each other - we need to find the right parameters, and thereby establish how strong these links are.\n\nThe best way to do this is to look at real data. Let us try to parametrise the model to roughly mimic the dynamics of COVID-19. We know, that the base reproduction number, i.e. the number of individuals infected by a single infected person, is on the order of $3$, if no interventions (masks, lockdowns, etc.) are in place. This base reproduction number falls right out of our model. (In fact it was first defined based on a similar model). It is given by the following relationship:\n\n$$R_0 = \\frac{rS_0}{a}$$\n\nIf we have a rough idea of the fractions of the population that is either infected ($I_0$) or resistant ($R_0$), we can easily determine the fraction of susceptible individuals ($S_0$).\n\nThe parameters $r$ and $a$ are harder to determine. However, if we have an idea of the amount of time infected individuals remain infectious on average, we can estimate the recovery rate $a$ using the following relationship:\n\n$$t_{infectious} = \\frac{1}{a}$$\n\n> By thinking about what the equations in the model mean, convince yourself that the relationship between our parameter $a$ and the average infectious time holds\n\"\"\"\n\n# ╔═╡ 1fc5f952-91ff-11eb-3366-9f477c640915\nmd\"\"\"\nThe code below implements the SIR-model and plots the output. Parameters can be adjusted using the sliders above the graphs. The simulation, as well as values for $R_0$ and $t_{infectious}$ are updated accordingly.\n\n> **Exercise 1 - Understanding the model:** Try to paramterise the model to capture the dynamics of COVID-19 without any interventions. Start by changing $a$ and $r$ and observe the effect on the overall dynamics (as shown in the timecourse plot), as well as on the base reproduction rate and the infectious period. - Use an average infectious period of 10 days and a base reproduction rate of approximately 3.5 to guide your parametrisation.\n>\n> - How strong is the effect of $r$ and $a$ on the base reproduction number?\n> - What is the effect of a higher proportion of infected individuals at the start on the dynamics of the outbreak and $R_0$?\n> - Assuming a starting population of infectious individuals of 1%, how long does it take until the outbreak peaks? Roughly how large is the fraction of the population that has recovered at the end?\n> - Assuming a case mortality (percentage of people with the disease that die) of 2%, what would be your estimate of the total number of fatalities at the end of the outbreak?\n> - Research online to try to come up with reasonable estimates for the fraction of people currently infected and the number of recovered people (including vaccinations) to be used as $I(0)$ and $R(0)$ respectively\n\"\"\"\n\n# ╔═╡ bfe81088-9203-11eb-162b-f373131bc105\nmd\"\"\"\n> **Exercise 2 - Lowering $R_0$:** The current base reproduction rate in Austria is estimated to be slightly above 1. Change the transmission rate accordingly.\n>\n> - How has the change affected the dynamics of the outbreak (time to peak, fraction of population that has recovered, fraction of the population infected at peak, estimated number of fatalities)?\n\"\"\"\n\n# ╔═╡ e574a398-9203-11eb-0006-c38430911ee1\nmd\"\"\"\n>**Exercise 3 - Intensive Care:** Roughly 1.5% of cases need to be treated in intensive care. Roughly 2500 beds in intensive care units are available, of which roughly 1000 beds can be made available to treat COVID-19 patients. This translates to approximately 0.0001 ICU beds per capita. \n>\n> - Assuming that the recovery rate of ICU patients is unchanged, what will be the demand for ICU beds at the peak of the outbreak with a base reproduction number of 1.17? How does this compare to the ICU bed capacity estimated above?\n> - How low would $R_0$ need to be in order not to overwhelm ICU capacity?\n> - Give five reasons why this scenario might be an oversimplification? Make an educated guess, as to whether you're likely to over- or underestimate the number of patients needing ICU-care.\n\"\"\"\n\n# ╔═╡ ac0c0230-91f0-11eb-057d-2103908afe51\nmd\"\"\" ## Simulation\n*Change the sliders to adjust the corresponding values*:\n\n| Parameter | Value |\n|-------------------|------------------------|\n transmission rate $r$ | $(@bind r Slider(0:0.005:1, default=0.125, show_value=true)) |\n| recovery rate $a$ | $(@bind a Slider(0:0.001:0.25, default=0.1, show_value=true)) |\n| initial number of infected $I(0)$ | $(@bind I0 Slider(0.0001:0.001:0.1, default=0.01, show_value=true)) |\n| initial number of resistant $R(0)$ | $(@bind R0 Slider(0:0.001:0.1, default=0,show_value=true)) |\n| timespan $t_{max}$ | $(@bind tmax Slider(10.0:10.0:2000.0, default=100.0,show_value=true)) days |\n| zoom y-axis | $(@bind ymax Slider(0.05:0.05:1.0, default=1.0,show_value=true)) |\n| Population size | $(@bind popsize NumberField(500000:10000000000, default=9044650)) |\n\"\"\"\n\n# ╔═╡ a5f6c71c-920a-11eb-09e9-098f52c01f11\nmd\"\"\"\n!!! danger \"Beware!\"\n\n The blocks below are used to specify the model. Feel free to play around with them, but proceed with care!\n\"\"\"\n\n# ╔═╡ 618d69dc-91f1-11eb-211f-d7548bf4a306\nfunction sir!(du,u,p,t)\n\tdu[1] = -p[1] * u[1] * u[2]\n\tdu[2] = p[1] * u[1] * u[2] - p[2] * u[2]\n\tdu[3] = p[2] * u[2]\nend\n\n# ╔═╡ 9a4c2f80-91f1-11eb-2b14-1784007ca92c\np = [r, a]\n\n# ╔═╡ a6c393c8-91f1-11eb-0be0-99d47c2b207f\nu0 = [1.0 - I0 - R0, I0, R0]\n\n# ╔═╡ eccbab9e-91f1-11eb-19b2-d733609880d0\ntspan = (0.0, 2000)\n\n# ╔═╡ f2abe15a-91f1-11eb-17c2-e99b8b67502f\nprob = ODEProblem(sir!,u0,tspan,p)\n\n# ╔═╡ 4c7f9b82-91f1-11eb-0064-e70bb182dae0\nbegin\n\tsol = solve(prob, dt=1.0, dense = true)\n\t\n\tsimplot = plot(sol.t, [sol[3,:] + sol[2,:] + sol[1,:] sol[3,:] + sol[2,:] sol[2,:]],\n\t\tfill = true, \n\t\tcolor = [\"gray89\" \"paleturquoise3\" \"lightcoral\"], \n\t\tlabel = [\"S(t)\" \"R(t)\" \"I(t)\"], \n\t\txlabel = \"t / days\", \n\t\ttitle = \"Timecourse\", \n\t\txlims = (0, tmax), \n\t\tylims = (0, ymax))\n\t\n\tphaseplot1 = plot(sol, vars = (1,2), \n\t\txlabel = \"S(t)\", \n\t\tylabel = \"I(t)\", \n\t\tlabel = \"\", \n\t\ttitle = \"Phaseplanes\", \n\t\txlims = (0,ymax), \n\t\tylims = (0,ymax), \n\t\tcolor = \"skyblue4\")\n\t\n\tphaseplot2 = plot(sol, vars = (3,2), \n\t\txlabel = \"R(t)\", \n\t\tylabel = \"I(t)\", \n\t\tlabel = \"\", \n\t\txlims = (0,ymax), \n\t\tylims = (0,ymax), \n\t\tcolor = \"skyblue4\")\n\t\n\tphaseplot = plot(phaseplot1, phaseplot2, layout = (2,1))\n\t\n\t#plot(simplot, phaseplot, layout = (1, 2),fontfamily=\"Computer Modern\")\n\tplot(simplot,fontfamily=\"Computer Modern\")\nend\n\n# ╔═╡ 0a8e0895-2de8-435e-827c-fb216ab07f10\nfunction getres(solution, i, t, p)\n\tv = solution(t)[i]*p\n\treturn round(maximum([0.0 v]))\nend\n\n# ╔═╡ 0b66bc58-91fa-11eb-24f1-7f9f839a6cbf\nmd\"\"\"\nBase reprodution rate = $(round((r*(1-I0-R0)/a), sigdigits = 3)), \nInfectious period = $(round(1/a, sigdigits = 3))\n\n| t(days) | I(t) | R(t) |\n|-----------|--------|---------|\n| 0 | $(getres(sol, 2, 0, popsize)) | $(getres(sol, 3, 0, popsize)) |\n| $tmax | $(getres(sol, 2, tmax, popsize)) | $(getres(sol, 3, tmax, popsize)) |\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─7cd44a22-91f0-11eb-056d-699740ca7da9\n# ╟─3199bb4e-91ed-11eb-37fa-abed99588e6b\n# ╟─1fc5f952-91ff-11eb-3366-9f477c640915\n# ╟─bfe81088-9203-11eb-162b-f373131bc105\n# ╟─e574a398-9203-11eb-0006-c38430911ee1\n# ╟─ac0c0230-91f0-11eb-057d-2103908afe51\n# ╟─0b66bc58-91fa-11eb-24f1-7f9f839a6cbf\n# ╟─4c7f9b82-91f1-11eb-0064-e70bb182dae0\n# ╟─a5f6c71c-920a-11eb-09e9-098f52c01f11\n# ╟─618d69dc-91f1-11eb-211f-d7548bf4a306\n# ╟─9a4c2f80-91f1-11eb-2b14-1784007ca92c\n# ╟─a6c393c8-91f1-11eb-0be0-99d47c2b207f\n# ╟─eccbab9e-91f1-11eb-19b2-d733609880d0\n# ╟─f2abe15a-91f1-11eb-17c2-e99b8b67502f\n# ╟─0a8e0895-2de8-435e-827c-fb216ab07f10\n", "meta": {"hexsha": "c8997c9731a4c1b978c44e4e204dbbac09533513", "size": 9582, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/03_modelling-basics_sir.jl", "max_stars_repo_name": "el-uhu/intro-to-modelling", "max_stars_repo_head_hexsha": "b86d558619c208184fc813e01c39de3d3b2e3f47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/03_modelling-basics_sir.jl", "max_issues_repo_name": "el-uhu/intro-to-modelling", "max_issues_repo_head_hexsha": "b86d558619c208184fc813e01c39de3d3b2e3f47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/03_modelling-basics_sir.jl", "max_forks_repo_name": "el-uhu/intro-to-modelling", "max_forks_repo_head_hexsha": "b86d558619c208184fc813e01c39de3d3b2e3f47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.8468899522, "max_line_length": 483, "alphanum_fraction": 0.7032978501, "num_tokens": 3215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9621075701109193, "lm_q2_score": 0.83973396967765, "lm_q1q2_score": 0.8079144091061602}} {"text": "\"\"\"\n div_rem(x, y)\n\nComputes `quotient = fl(x/y)` and `remainder = x - quotient*y` such that `(x-remainder) / y = quotient`.\n\"\"\"\n@inline function div_rem(x::T, y::T) where {T}\n quotient = x / y\n remainder = fma(-y, quotient, x)\n return quotient, remainder\nend\n\n\"\"\"\n sqrt_rem(x)\n\nComputes `root = fl(sqrt(x))` and `remainder = x - root*root` such that `sqrt(x-remainder) = root`.\n\"\"\"\n@inline function sqrt_rem(x::T) where {T}\n root = sqrt(x)\n remainder = fma(-root, root, x)\n return root, remainder\nend\n\n#=\n Those remainders are exact.\n For more informations, applications and additional references, see the introduction of\n Sylvie Boldo and Jean-Michel Muller\n Some Functions Computable with a Fused-mac\n=#\n", "meta": {"hexsha": "13b8729472fb1e9aa0cd1855067cf4a756eccca3", "size": 733, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/remainder.jl", "max_stars_repo_name": "nestordemeure/ErrorfreeArithmetic.jl", "max_stars_repo_head_hexsha": "af69f112260be0c99f21ce7f3e71d83ae891dc18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-08-07T17:03:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T11:37:33.000Z", "max_issues_repo_path": "src/remainder.jl", "max_issues_repo_name": "nestordemeure/ErrorfreeArithmetic.jl", "max_issues_repo_head_hexsha": "af69f112260be0c99f21ce7f3e71d83ae891dc18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2017-04-07T15:19:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-15T03:34:13.000Z", "max_forks_repo_path": "src/remainder.jl", "max_forks_repo_name": "nestordemeure/ErrorfreeArithmetic.jl", "max_forks_repo_head_hexsha": "af69f112260be0c99f21ce7f3e71d83ae891dc18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2017-04-10T00:18:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:54:51.000Z", "avg_line_length": 25.275862069, "max_line_length": 104, "alphanum_fraction": 0.6643929059, "num_tokens": 211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778024535095, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.8078420436372201}} {"text": "# p25.jl - stability regions for ODE formulas\n\n# Adams-Bashforth:\nclf(); subplot(221);\nzplot(z) = plot(real(z),imag(z));\nplot([-8,8],[0,0],\"k-\"); plot([0,0],[-8,8],\"k-\");\nz = exp.(1im*pi*(0:200)/100); r = z-1;\ns = 1; zplot(r./s); # order 1\ns = (3-1./z)/2; zplot(r./s); # order 2\ns = (23-16./z+5./z.^2)/12; zplot(r./s); # order 3\naxis(\"square\"); axis([-2.5,.5,-1.5,1.5]); grid(true)\ntitle(\"Adams—Bashforth\");\n\n# Adams-Moulton:\nsubplot(222);\nplot([-8,8],[0,0],\"k-\"); plot([0,0],[-8,8],\"k-\");\ns = (5*z+8-1./z)/12; zplot(r./s); # order 3\ns = (9*z+19-5./z+1./z.^2)/24; zplot(r./s); # order 4\ns = (251*z+646-264./z+106./z.^2-19./z.^3)/720; zplot(r./s) ; # 5\nd = 1-1./z;\ns = 1-d/2-d.^2/12-d.^3/24-19*d.^4/720-3*d.^5/160; zplot(d./s); # 6\naxis(\"square\"); axis([-7,1,-4,4]); grid(true);\ntitle(\"Adams—Moulton\");\n\n# Backward differentiation:\nsubplot(223);\nplot([-40,40],[0,0],\"k-\"); plot([0,0],[-40,40],\"k-\");\nr = 0;\nfor i = 1:6 # orders 1-6\n r += (d.^i)/i;\n zplot(r);\nend\naxis(\"square\"); axis([-15,35,-25,25]); grid(true);\ntitle(\"backward differentiation\")\n\n# Runge-Kutta:\nsubplot(224);\nplot([-8,8],[0,0],\"k-\"); plot([0,0],[-8,8],\"k-\");\nw = zeros(4)+0im; W = w.';\nfor i = 2:length(z)\n # orders 1-4\n w[1] -= (1+w[1]-z[i]);\n w[2] -= (1+w[2]+.5*w[2]^2-z[i]^2)/(1+w[2]);\n w[3] -= (1+w[3]+.5*w[3]^2+w[3]^3/6-z[i]^3)/(1+w[3]+w[3]^2/2);\n w[4] -= (1+w[4]+.5*w[4]^2+w[4]^3/6+w[4].^4/24-z[i]^4)/(1+w[4]+w[4]^2/2+w[4]^3/6);\n W = [W; w.'];\nend\nzplot(W); axis(\"square\"); axis([-5,2,-3.5,3.5]); grid(true);\ntitle(\"Runge—Kutta\");\n", "meta": {"hexsha": "4ebe095b455f9945df6fc6e480f4314af3930906", "size": 1630, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/scripts/p25.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/p25.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/p25.jl", "max_forks_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_forks_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6, "max_line_length": 85, "alphanum_fraction": 0.4699386503, "num_tokens": 743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545362802363, "lm_q2_score": 0.8519528038477824, "lm_q1q2_score": 0.8077829156649412}} {"text": "# # m2.1t.jl\n\n# Load Julia packages (libraries) needed\n\nusing TuringModels\n\n# ### snippet 2.8t\n\n# Define the data\n\nk = 6; n = 9;\n\n# Define the model\n\n@model globe_toss(n, k) = begin\n theta ~ Beta(1, 1) # prior\n k ~ Binomial(n, theta) # model\n return k, theta\nend;\n\n# Use Turing mcmc\n\nchns = sample(globe_toss(n, k), NUTS(0.65), 1000)\n\n# Look at the proper draws (in corrected chn2)\n\nchns |> display\n\n# Show the hpd region\n\nhpd(chns, alpha=0.055) |> display\n\n# End of `02/m2.1t.jl`\n", "meta": {"hexsha": "9b16eac754df08536af88e917fe51bd69fe5d3b5", "size": 484, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/02/m2.1t.jl", "max_stars_repo_name": "yiyuezhuo/TuringModels.jl", "max_stars_repo_head_hexsha": "88755d21f128de893873820f28f5019856ff8d24", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/02/m2.1t.jl", "max_issues_repo_name": "yiyuezhuo/TuringModels.jl", "max_issues_repo_head_hexsha": "88755d21f128de893873820f28f5019856ff8d24", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/02/m2.1t.jl", "max_forks_repo_name": "yiyuezhuo/TuringModels.jl", "max_forks_repo_head_hexsha": "88755d21f128de893873820f28f5019856ff8d24", "max_forks_repo_licenses": ["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.2352941176, "max_line_length": 49, "alphanum_fraction": 0.6466942149, "num_tokens": 180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.948154531885212, "lm_q2_score": 0.8519528000888386, "lm_q1q2_score": 0.8077829083565283}} {"text": "module Copeland\n\nfunction level_of_dominance(v1::Array{Int,1}, v2::Array{Int,1})::Int64\n lod = zero(Int64)\n n = length(v1)\n for i = 1:n\n if v1[i] < v2[i]\n lod += 1\n end\n end\n return lod\nend\n\nfunction dominance_scores(ordering_mat::Array{Int, 2})::Array{Int, 2}\n n, _ = size(ordering_mat)\n lev_dom = zeros(Int64, n, n)\n for i in 1:n\n for j in 1:n\n lev_dom[i, j] = level_of_dominance(ordering_mat[i,:], ordering_mat[j,:])\n end\n end\n return lev_dom\nend\n\nfunction winloss_scores(dommat::Array{Int, 2})::Array{Int, 2}\n n, _ = size(dommat)\n winlossmat = zeros(Int64, n, n)\n for i in 1:n\n for j in 1:n \n winlossmat[i, j] = Int(sign(dommat[i, j] - dommat[j, i]))\n end\n end\n return winlossmat\nend\n\nfunction copeland(ordering_mat::Array{Int, 2})::Array{Int, 1}\n winlosses = ordering_mat |> dominance_scores |> winloss_scores\n n, _ = size(winlosses)\n scores = map(i -> Int(sum(winlosses[i, :])), 1:n)\n return scores\nend\n\nend # end of module", "meta": {"hexsha": "def1f8c55ee7c493d1afd25e903753fea99445df", "size": 1061, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/copeland.jl", "max_stars_repo_name": "jbytecode/jMCDM", "max_stars_repo_head_hexsha": "04fd374fd8cff2ba359e2f51568c65ea1675b93d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2021-02-09T17:42:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T22:21:26.000Z", "max_issues_repo_path": "src/copeland.jl", "max_issues_repo_name": "jbytecode/jMCDM", "max_issues_repo_head_hexsha": "04fd374fd8cff2ba359e2f51568c65ea1675b93d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2021-02-09T16:56:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T18:11:34.000Z", "max_forks_repo_path": "src/copeland.jl", "max_forks_repo_name": "jbytecode/jMCDM", "max_forks_repo_head_hexsha": "04fd374fd8cff2ba359e2f51568c65ea1675b93d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2021-02-12T16:01:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T22:02:44.000Z", "avg_line_length": 24.6744186047, "max_line_length": 84, "alphanum_fraction": 0.5947219604, "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545289551957, "lm_q2_score": 0.8519528019683106, "lm_q1q2_score": 0.8077829076423226}} {"text": "### A Pluto.jl notebook ###\n# v0.17.4\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ efff10ac-824b-422b-b2f9-4074ea3437fb\nbegin\n\tusing Pkg; Pkg.activate(@__DIR__); Pkg.instantiate()\n\tPkg.precompile()\n\n\tusing PlutoUI\n\tusing UMAP\n\tusing Makie\n\tusing GLMakie\n\tusing XLSX\n\tusing VegaDatasets\n\tusing DataFrames\n\tusing MultivariateStats\n\tusing RDatasets\n\tusing StatsBase\n\tusing Statistics\n\tusing LinearAlgebra\n\tusing Plots\n\tusing ScikitLearn\n\tusing MLBase\n\tusing Distances\nend;\n\n# ╔═╡ 85e2d832-542c-49b0-a26d-b57a7a3d4404\nPlutoUI.TableOfContents(aside=true, indent=true, depth=3)\n\n# ╔═╡ 6e8c97d2-4d9a-4f00-99e1-69054903635c\nhtml\"\"\"\n

\n\t\"Course-Logo\"\n

\n\"\"\"\n\n# ╔═╡ 133df7ea-d3ec-41fa-bcb8-5eae4c853a55\nmd\"\"\"\n# 📝 Dimensionality Reduction\n\nAs the name says, dimensionality reduction is the idea of reducing your feature set to a much smaller number. Dimensionality reduction is often used in visualization of datasets to try and detect samples that are similar. Usually, the goal is to come up with a 2D visualization of your data, where every dot in your plot is representing an observation. We can use these plots to look for patterns in data. We will cover three dimensionality reduction techniques here:\n\n1. t-SNE\n2. PCA\n3. UMAP\n\n[YouTube Link](https://www.youtube.com/watch?v=hIsYy04zO7U)\n\"\"\"\n\n# ╔═╡ 5271ffe0-f73a-430e-8ccc-5c6bd0937ce0\nmd\"\"\"\n## Load dataset\n\nWe will use a dataset from the [VegaDatasets.jl](https://github.com/queryverse/VegaDatasets.jl) package. The dataset is about car specifications of over 400 car models.\n\"\"\"\n\n# ╔═╡ 6a53752f-3101-4b62-a661-c09c9df27f0f\ndata = VegaDatasets.dataset(\"cars\") |> DataFrame\n\n# ╔═╡ 9a491a1d-32a0-496c-887a-cdfd49f01836\nmd\"\"\"\nLet's check the available variables with the `names` function...\n\"\"\"\n\n# ╔═╡ dcc6939b-ba8e-4f4a-abcf-aa90efa60682\nnames(data)\n\n# ╔═╡ 56529677-8b5c-4912-b25a-728847b4f374\nmd\"\"\"\n## Data wrangling\n\n\"\"\"\n\n# ╔═╡ 59d179aa-a19c-497d-ae56-6e0b0b0007dc\nmd\"\"\"\nWe will first drop missing data with the `dropmissing!` inplace function...\n\"\"\"\n\n# ╔═╡ 2f0ba288-19b9-49c8-845c-bdc2317328fc\ndropmissing!(data)\n\n# ╔═╡ 182b795f-c069-4ecd-aab6-89c66c93ee6e\nmd\"\"\"\nNow, we need to save the numeric variables (columns 2 through 7) as a `Matrix`. We will use this data to perform dimensionality reduction methods later...\n\"\"\"\n\n# ╔═╡ 56e3357f-a692-4b29-8ca2-390ba62b9679\nM = data[:,2:7] |> Matrix\n\n# ╔═╡ 53bae393-698c-4610-b18f-073a67d9bdc8\nmd\"\"\"\nWe are also going to use the `Origin` feature. However, since it is a vector of strings, we will need to encode it.\n\nFirst, we will use the [MLBase.jl](https://github.com/JuliaStats/MLBase.jl) `labelmap` function to map `Origin` labels and, then, we will encode it using the `labelencode` function...\n\"\"\"\n\n# ╔═╡ 193d7109-5499-40c3-a25f-b7b8560db5b9\norigin = data[!,:Origin]\n\n# ╔═╡ c3d8e866-c754-4ee6-8c1c-fab7f8048181\norigin_map = labelmap(origin)\n\n# ╔═╡ 231955b0-5ccd-46ad-b78d-96f861f1938a\norigin_codes = labelencode(origin_map, origin)\n\n# ╔═╡ 841ef716-8dbf-4aec-947e-6c0409a7fd64\nmd\"\"\"\n**Note:** after encoding, we have:\n- USA → 1\n- Japan → 2\n- Europe → 3\n\"\"\"\n\n# ╔═╡ 2c86f61a-b328-4eac-a4ff-1e713007ef54\nmd\"\"\"\nFinally, we must center and normalize the data...\n\n**Note:** `dims=1` means that we are calculating both `mean` and `std` over _columns_.\n\"\"\"\n\n# ╔═╡ c08882ca-d617-4c0f-865f-898c0f639a82\ncenter_M = (M .- mean(M, dims=1)) ./ std(M, dims=1)\n\n# ╔═╡ a9afbe75-29a4-4a54-b6c2-2786d74f7a65\nmd\"\"\"\n## PCA\n\n**Principal component analysis (PCA)** is the process of computing the principal components and using them to perform a change of basis on the data, sometimes using only the first few principal components and ignoring the rest.\n\nThe principal components of a collection of points in a real coordinate space are a sequence of $p$ unit vectors, where the $i$-th vector is the direction of a line that best fits the data while being orthogonal to the first $i-1$ vectors. Here, a best-fitting line is defined as one that minimizes the average squared distance from the points to the line. These directions constitute an orthonormal basis in which different individual dimensions of the data are linearly uncorrelated.\n\n**Note:** the details for the underlying mathematics can be found [here](https://en.wikipedia.org/wiki/Principal_component_analysis).\n\nFirst, we will fit the model via PCA, using the [MultivariateStats.jl](https://github.com/JuliaStats/MultivariateStats.jl) package. `maxoutdim` is the output dimensions and we want it to be 2 in this case.\n\n**Note:** since PCA expects each column to be an observation, we will use the transpose of the matrix.\n\"\"\"\n\n# ╔═╡ dffd6373-2e05-4746-bc44-ee2193ae2635\npca = fit(PCA, center_M', maxoutdim=2)\n\n# ╔═╡ d13d825e-e807-4ef0-a9ab-45fc994500a2\nmd\"\"\"\nNow, we can obtain the projection matrix by calling the function `projection`...\n\n**Note:** once you multiply the projection matrix by your data, you get the dimensionality reduction of your data.\n\"\"\"\n\n# ╔═╡ cb2f6b28-d360-4bb8-a0c0-3d6d1b38e23d\nP = projection(pca)\n\n# ╔═╡ 8d89f524-68a0-425e-a4e9-2525ebdd914d\nmd\"\"\"\nGiven a PCA model, one can use it to transform observations into principal components, as:\n\n```math\ny = P^T(x - \\mu)\n```\n\nwhere $P$ is the projection matrix, $x$ is the original feature vector and $\\mu$ is the empirical mean vector by each original feature. We can perform this transformation manually or call `transform` function...\n\"\"\"\n\n# ╔═╡ 3946ec51-0336-4098-ba13-55abf68f9b41\n# empirical mean vector\nμ = mean(pca)\n\n# ╔═╡ 8d219680-c870-4549-9421-5c7fff3a7607\n# transforming the 1st instance manually\nP' * (center_M[1,:] - μ)\n\n# ╔═╡ a450f277-46cf-4f5b-b58a-b33b5aca5fb2\nmd\"\"\"\n**Note:** the result above is the 1st feature vector represented by the first two principal components.\n\"\"\"\n\n# ╔═╡ 2e2d14e9-8fdb-4328-9218-f47307309f40\n# transforming all data\nY = MultivariateStats.transform(pca, center_M')\n\n# ╔═╡ 13b52e6a-dbe4-4dad-a7a6-260957fb0bdd\nmd\"\"\"\n**Note:** `Y[:,1]` is the same as `P' * (center_data[1,:] - μ)`:\n\"\"\"\n\n# ╔═╡ 49f05ab7-b716-44c4-bb44-6c2e700a18ac\nY[:,1] ≈ (P' * (center_M[1,:] - μ))\n\n# ╔═╡ c37484f0-3e35-4c5f-841a-e0e6061752b4\nmd\"\"\"\nGiven a PCA model, we also may use it to reconstruct (approximately) the observations from principal components, as:\n\n```math\n\\tilde{x} = Py + \\mu\n```\nwhere $P$ is the projection matrix, $x$ is the original feature vector and $\\mu$ is the empirical mean vector by each original feature. We can perform this reconstruction using the `reconstruct` function...\n\"\"\"\n\n# ╔═╡ cf067613-8312-402c-88b2-fe507ce36ac9\nX̅ = reconstruct(pca, Y)\n\n# ╔═╡ 7594fb9c-443a-4ea8-a56a-f17c818ddbfe\nmd\"\"\"\nHowever, since the reconstruction is approximate, the norm difference between $\\tilde{x}$ and $x$ will not be zero...\n\"\"\"\n\n# ╔═╡ e0e09b17-da85-4879-bec8-adef9f125b31\nnorm(X̅ - center_M')\n\n# ╔═╡ 0e73cd39-24d3-4de4-a30d-a53ad6f1d50c\nmd\"\"\"\nFinally, we can generate a scatter plot of the cars...\n\"\"\"\n\n# ╔═╡ 5dfc1915-f832-4d72-b551-e3ddbfa693bc\nPlots.scatter(Y[1,:], Y[2,:], color=:orange, legend=false,\n\t\t\t xlabel=\"1st PC\", ylabel=\"2nd PC\")\n\n# ╔═╡ 98c5d1d2-6c28-4c46-adeb-bb580d5dfe2a\nmd\"\"\"\nLet's try to color the scatter plot by `Origin`...\n\"\"\"\n\n# ╔═╡ 8117e9fa-23d1-4539-aa28-c5bc4a3db849\nbegin\n\t# boolean lists\n\tusaᵢ = origin.==\"USA\"\n\tjapᵢ = origin .== \"Japan\"\n\teurᵢ = origin .== \"Europe\"\nend;\n\n# ╔═╡ 07dbb182-4565-48de-b41c-bd0488f67280\nbegin\n\tPlots.scatter(Y[1,usaᵢ], Y[2,usaᵢ], color=1, label=\"USA\")\n\tPlots.scatter!(Y[1,japᵢ], Y[2,japᵢ], color=2, label=\"Japan\")\n\tPlots.scatter!(Y[1,eurᵢ], Y[2,eurᵢ], color=3, label=\"Europe\")\n\n\tPlots.xlabel!(\"1st PC\")\n\tPlots.ylabel!(\"2nd PC\")\nend\n\n# ╔═╡ 6bca80ac-8c1d-4f35-82e7-4c6c4206eb53\nmd\"\"\"\nThis is interesting! There seems to be three main clusters with cars from the US dominating two clusters.\n\nNow, let's try to reduce the dimentionality to 3 principal components...\n\"\"\"\n\n# ╔═╡ 152fc839-661b-48aa-a047-9e16a35acff5\nbegin\n\tnew_pca = fit(PCA, center_M', maxoutdim=3)\n\tnew_Y = MultivariateStats.transform(new_pca, center_M')\nend\n\n# ╔═╡ 5f55ba88-c984-49d2-b4b9-e5cdd81e8c6c\nscatter3d(new_Y[1,:], new_Y[2,:], new_Y[3,:], color=origin_codes,\n\t\t xlabel=\"1st PC\", ylabel=\"2nd PC\", zlabel=\"3rd PC\",\n\t\t legend=false, camera=(50, 30))\n\n# ╔═╡ bac92bf8-3059-4fcc-b1a9-42c91637fd17\nmd\"\"\"\n## t-SNE\n\n**t-Distributed Stochastic Neighbor Embedding (t-SNE)** is a statistical method for visualizing high-dimensional data by giving each datapoint a location in a two or three-dimensional map. It is based on Stochastic Neighbor Embedding originally developed by Sam Roweis and Geoffrey Hinton,[1] where Laurens van der Maaten proposed the t-distributed variant.\n\n**Note:** the details for the underlying mathematics can be found [here](https://en.wikipedia.org/wiki/T-distributed_stochastic_neighbor_embedding).\n\nThe next method we will use for dimensionality reduction is t-SNE. There are multiple ways you can call t-SNE from Julia. But we will take this opportunity to try out something new... We will call a function from the scikitlearn Python package. This makes use of the package [ScikitLearn.jl](https://github.com/cstjean/ScikitLearn.jl).\n\n**Note:** check this [t-SNE notebook](https://github.com/nassarhuda/JuliaTutorials/blob/master/TSNE/TSNE.ipynb).\n\"\"\"\n\n# ╔═╡ 6c163758-55b5-474b-8269-203884d70757\n# importing sklearn t-SNE\n@sk_import manifold: TSNE\n\n# ╔═╡ 4676988f-5687-4aad-a054-48ae5defd46e\n# instantiate a t-SNE object with 2 components\ntsne = TSNE(n_components=2, perplexity=20.0, early_exaggeration=50)\n\n# ╔═╡ 026668de-5323-4e40-b75c-c2eefbf46ef5\n# fit-transforming data\nY₂ = tsne.fit_transform(center_M)\n\n# ╔═╡ 7fb412b7-573e-4c5a-bd39-d9d7e637a9d4\nmd\"\"\"\n**Note:** here, we do not have to work with the transpose data, since ScikitLearn already deals with observations as rows...\n\nLet's plot the components...\n\"\"\"\n\n# ╔═╡ 8faa2556-bcfc-4289-9d17-d75ad10f2245\nbegin\n\tPlots.scatter(Y₂[usaᵢ,1], Y₂[usaᵢ,2], color=1, label=\"USA\")\n\tPlots.scatter!(Y₂[japᵢ,1], Y₂[japᵢ,2], color=2, label=\"Japan\")\n\tPlots.scatter!(Y₂[eurᵢ,1], Y₂[eurᵢ,2], color=3, label=\"Europe\")\n\n\tPlots.xlabel!(\"1st Component\")\n\tPlots.ylabel!(\"2nd Component\")\nend\n\n# ╔═╡ 3114d2e5-e6eb-4198-98f3-4abfbb45bdeb\nmd\"\"\"\nThis is interesting! The same patterns saw before appears to hold here too.\n\"\"\"\n\n# ╔═╡ 7675ae48-a6ae-4189-990f-c1469ee11929\nmd\"\"\"\n## UMAP\n\n**Uniform Manifold Approximation and Projection (UMAP)** is a dimension reduction technique that can be used for visualisation similarly to t-SNE, but also for general non-linear dimension reduction. The algorithm is founded on three assumptions about the data:\n\n1. The data is uniformly distributed on Riemannian manifold;\n2. The Riemannian metric is locally constant (or can be approximated as such);\n3. The manifold is locally connected.\n\nFrom these assumptions it is possible to model the manifold with a fuzzy topological structure. The embedding is found by searching for a low dimensional projection of the data that has the closest possible equivalent fuzzy topological structure.\n\n**Note:** the details for the underlying mathematics can be found [here](https://arxiv.org/abs/1802.03426).\n\nTo perform UMAP, we will use the [UMAP.jl](https://github.com/dillondaudert/UMAP.jl) package. First, let's calculate the correlation matrix between cars...\n\n**Note:** `dims=2` means that correlation is calculated over rows/instances.\n\"\"\"\n\n# ╔═╡ bdaff924-889a-4dfc-93cc-4375f6016d82\nL = cor(center_M, center_M, dims=2)\n\n# ╔═╡ 3b892bcb-4c67-4309-be2c-5d562e4b98b5\nmd\"\"\"\nNow, we can create an UMAP instance with two components...\n\"\"\"\n\n# ╔═╡ 5f56f6f7-f905-4271-a111-ba4092e3d12e\nembed₁ = umap(L, 2)\n\n# ╔═╡ 0cdb33ae-e168-42a3-974a-2a8cf0ccea8c\nmd\"\"\"\n**Note:** the output components are being treated as rows (not columns).\n\"\"\"\n\n# ╔═╡ d70792c1-c3e4-48cb-8168-34cfa89ca0f4\nbegin\n\tPlots.scatter(embed₁[1,usaᵢ], embed₁[2,usaᵢ], color=1, label=\"USA\")\n\tPlots.scatter!(embed₁[1,japᵢ], embed₁[2,japᵢ], color=2, label=\"Japan\")\n\tPlots.scatter!(embed₁[1,eurᵢ], embed₁[2,eurᵢ], color=3, label=\"Europe\")\n\n\tPlots.xlabel!(\"1st Component\")\n\tPlots.ylabel!(\"2nd Component\")\nend\n\n# ╔═╡ 6f34e24a-ef1f-4b33-a639-aec7a8a12aef\nmd\"\"\"\nInstead of calculating the correlation matrix, we can calculate the pairwise Euclidean distance between instances using [Distances.jl](https://github.com/JuliaStats/Distances.jl) package...\n\"\"\"\n\n# ╔═╡ 08a89d70-7f5d-4a5e-8e4a-35abd03bb5b7\nD = pairwise(Euclidean(), center_M, center_M, dims=1)\n\n# ╔═╡ 0734fd78-fef5-4536-a99b-57eef9cd5f0f\nmd\"\"\"\nNow, we can create again an UMAP instance with two components...\n\"\"\"\n\n# ╔═╡ d0ed58f2-93c1-4d4e-8f81-5f376c14ec41\nembed₂ = umap(D, 2)\n\n# ╔═╡ cef603ec-8e05-43cc-962e-11c763fe09af\nbegin\n\tPlots.scatter(embed₂[1,usaᵢ], embed₂[2,usaᵢ], color=1, label=\"USA\")\n\tPlots.scatter!(embed₂[1,japᵢ], embed₂[2,japᵢ], color=2, label=\"Japan\")\n\tPlots.scatter!(embed₂[1,eurᵢ], embed₂[2,eurᵢ], color=3, label=\"Europe\")\n\n\tPlots.xlabel!(\"1st Component\")\n\tPlots.ylabel!(\"2nd Component\")\nend\n\n# ╔═╡ Cell order:\n# ╟─efff10ac-824b-422b-b2f9-4074ea3437fb\n# ╟─85e2d832-542c-49b0-a26d-b57a7a3d4404\n# ╟─6e8c97d2-4d9a-4f00-99e1-69054903635c\n# ╟─133df7ea-d3ec-41fa-bcb8-5eae4c853a55\n# ╟─5271ffe0-f73a-430e-8ccc-5c6bd0937ce0\n# ╠═6a53752f-3101-4b62-a661-c09c9df27f0f\n# ╟─9a491a1d-32a0-496c-887a-cdfd49f01836\n# ╠═dcc6939b-ba8e-4f4a-abcf-aa90efa60682\n# ╟─56529677-8b5c-4912-b25a-728847b4f374\n# ╟─59d179aa-a19c-497d-ae56-6e0b0b0007dc\n# ╠═2f0ba288-19b9-49c8-845c-bdc2317328fc\n# ╟─182b795f-c069-4ecd-aab6-89c66c93ee6e\n# ╠═56e3357f-a692-4b29-8ca2-390ba62b9679\n# ╟─53bae393-698c-4610-b18f-073a67d9bdc8\n# ╠═193d7109-5499-40c3-a25f-b7b8560db5b9\n# ╠═c3d8e866-c754-4ee6-8c1c-fab7f8048181\n# ╠═231955b0-5ccd-46ad-b78d-96f861f1938a\n# ╟─841ef716-8dbf-4aec-947e-6c0409a7fd64\n# ╟─2c86f61a-b328-4eac-a4ff-1e713007ef54\n# ╠═c08882ca-d617-4c0f-865f-898c0f639a82\n# ╟─a9afbe75-29a4-4a54-b6c2-2786d74f7a65\n# ╠═dffd6373-2e05-4746-bc44-ee2193ae2635\n# ╟─d13d825e-e807-4ef0-a9ab-45fc994500a2\n# ╠═cb2f6b28-d360-4bb8-a0c0-3d6d1b38e23d\n# ╟─8d89f524-68a0-425e-a4e9-2525ebdd914d\n# ╠═3946ec51-0336-4098-ba13-55abf68f9b41\n# ╠═8d219680-c870-4549-9421-5c7fff3a7607\n# ╟─a450f277-46cf-4f5b-b58a-b33b5aca5fb2\n# ╠═2e2d14e9-8fdb-4328-9218-f47307309f40\n# ╟─13b52e6a-dbe4-4dad-a7a6-260957fb0bdd\n# ╠═49f05ab7-b716-44c4-bb44-6c2e700a18ac\n# ╟─c37484f0-3e35-4c5f-841a-e0e6061752b4\n# ╠═cf067613-8312-402c-88b2-fe507ce36ac9\n# ╟─7594fb9c-443a-4ea8-a56a-f17c818ddbfe\n# ╠═e0e09b17-da85-4879-bec8-adef9f125b31\n# ╟─0e73cd39-24d3-4de4-a30d-a53ad6f1d50c\n# ╠═5dfc1915-f832-4d72-b551-e3ddbfa693bc\n# ╟─98c5d1d2-6c28-4c46-adeb-bb580d5dfe2a\n# ╠═8117e9fa-23d1-4539-aa28-c5bc4a3db849\n# ╠═07dbb182-4565-48de-b41c-bd0488f67280\n# ╟─6bca80ac-8c1d-4f35-82e7-4c6c4206eb53\n# ╠═152fc839-661b-48aa-a047-9e16a35acff5\n# ╠═5f55ba88-c984-49d2-b4b9-e5cdd81e8c6c\n# ╟─bac92bf8-3059-4fcc-b1a9-42c91637fd17\n# ╠═6c163758-55b5-474b-8269-203884d70757\n# ╠═4676988f-5687-4aad-a054-48ae5defd46e\n# ╠═026668de-5323-4e40-b75c-c2eefbf46ef5\n# ╟─7fb412b7-573e-4c5a-bd39-d9d7e637a9d4\n# ╠═8faa2556-bcfc-4289-9d17-d75ad10f2245\n# ╟─3114d2e5-e6eb-4198-98f3-4abfbb45bdeb\n# ╟─7675ae48-a6ae-4189-990f-c1469ee11929\n# ╠═bdaff924-889a-4dfc-93cc-4375f6016d82\n# ╟─3b892bcb-4c67-4309-be2c-5d562e4b98b5\n# ╠═5f56f6f7-f905-4271-a111-ba4092e3d12e\n# ╟─0cdb33ae-e168-42a3-974a-2a8cf0ccea8c\n# ╠═d70792c1-c3e4-48cb-8168-34cfa89ca0f4\n# ╟─6f34e24a-ef1f-4b33-a639-aec7a8a12aef\n# ╠═08a89d70-7f5d-4a5e-8e4a-35abd03bb5b7\n# ╟─0734fd78-fef5-4536-a99b-57eef9cd5f0f\n# ╠═d0ed58f2-93c1-4d4e-8f81-5f376c14ec41\n# ╠═cef603ec-8e05-43cc-962e-11c763fe09af\n", "meta": {"hexsha": "98c843359e7603f85c5fbf1b837c0460caf33985", "size": 15467, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "04_Dimensionality_Reduction.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": "04_Dimensionality_Reduction.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": "04_Dimensionality_Reduction.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": 34.9932126697, "max_line_length": 485, "alphanum_fraction": 0.7420314217, "num_tokens": 6330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122113355091, "lm_q2_score": 0.8902942348544447, "lm_q1q2_score": 0.8077748309650413}} {"text": "#!/usr/bin/env julia\n\n\"\"\"\nUtilities for producing and operating on numerical sequences.\n\"\"\"\nmodule Sequences\n\n\"\"\"\n Fibonacci([T::Type{<:Integer}])\n\nIterable object that returns subsequent terms of the Fibonacci sequence.\n\n## Fields\n- `T`: The integer type of each term in the sequence. Defaults to `Int`\n\n## Examples\n```julia-repl\njulia> first(Fibonacci())\n1\n\njulia> first(Fibonacci(UInt8))\n0x01\n\njulia> for n in Fibonacci()\n println(n)\n if n > 10\n break\n end\n end\n1\n2\n3\n5\n8\n13\n\njulia> for (i, n) in Iterators.enumerate(Fibonacci())\n println(n)\n if i == 5\n break\n end\n end\n1\n2\n3\n5\n8\n```\n\nSee also: [`fibonacci`](@ref)\n\"\"\"\nstruct Fibonacci\n T::Type{<:Integer}\nend\nFibonacci() = Fibonacci(Int)\n\nfunction Base.iterate(\n iter::Fibonacci,\n state::Tuple{Integer, Integer} = (zero(iter.T), oneunit(iter.T))\n)\n fib_old, fib_new = state\n fib_old, fib_new = fib_new, (fib_old + fib_new)\n return fib_new, (fib_old, fib_new)\nend\n\n\"\"\"\n arithmetic_series(a::Integer, n::Integer, d::Integer = 1)\n\nReturns the sum of the arithmetic sequence with parameters `a`, `n`, `d`.\n\n# Arguments\n- `a`: The first term in the sequence\n- `n`: The total number of terms in the sequence\n- `d`: The difference between two consecutive terms in the sequence\n\n# Preconditions\n- `n ≥ 0`\n\n# Examples\n```jldoctest\njulia> arithmetic_series(1, 4)\n10\n\njulia> arithmetic_series(2, 6, -1)\n-3\n\njulia> arithmetic_series(3, 5, 4)\n55\n```\n\"\"\"\nfunction arithmetic_series(a::Integer, n::Integer, d::Integer = 1)\n return n * (2a + (n - 1)d) ÷ 2\nend\n\n\"\"\"\n fibonacci([T::Type{<:Integer}], n::Integer)\n\nComputes the specified term `F(n)` of the Fibonacci sequence, defined by the\nrelation `F(m) = F(m - 1) + F(m - 2)` with `F(0) = F(1) = 1`.\n\n## Arguments\n- `T`: The integer type of each term in the sequence. Defaults to `typeof(n)`\n- `n`: Specifies the term `F(n)` in the Fibonacci sequence to return\n\n## Preconditions\n- `n ≥ 0`\n\n## Examples\n```jldoctest\njulia> fibonacci(0)\n1\n\njulia> fibonacci(4)\n5\n\njulia> fibonacci(UInt8, 5)\n0x08\n```\n\nSee also: [`Fibonacci`](@ref)\n\"\"\"\nfunction fibonacci(n::Integer)\n return fibonacci(typeof(n), n)\nend\nfunction fibonacci(T::Type{<:Integer}, n::Integer)\n # Fibonacci iterates from F(1), so handle F(0) ourselves\n if n == 0\n return oneunit(T)\n end\n\n for (i, fib_num) in enumerate(Fibonacci(T))\n if i == n\n return fib_num\n end\n end\n\n # Fibonacci iterator should never terminate\n throw(ErrorException(\"iteration terminated unexpectedly\"))\nend\n\n\"\"\"\n next_multiple(n::T, min_val::T) where T <: Integer\n\nTODO: Function description goes here\n\n## Arguments\n- TODO: Arguments go here\n\n## Preconditions\n- TODO: Preconditions go here\n\n## Examples\n```jldoctest\njulia> next_multiple()\n\n```\n\"\"\"\nfunction next_multiple(n::T, min_val::T) where T <: Integer\n return min_val + (n - min_val % n) % n\nend\n\n\"\"\"\n sum_of_squares(n::Integer)\n\nComputes the sum of the squares of the first `n` natural numbers.\n\n## Preconditions\n- `n ≥ 0`\n\n## Examples\n```jldoctest\njulia> sum_of_squares(1)\n1\n\njulia> sum_of_squares(0x02)\n0x05\n\njulia> sum_of_squares(4)\n30\n```\n\"\"\"\nfunction sum_of_squares(n::Integer)\n T = typeof(n)\n cube_term = convert(T, 2) * n^3\n square_term = convert(T, 3) * n^2\n return (cube_term + square_term + n) ÷ convert(T, 6)\nend\n\n\"\"\"\n triangular(n::Integer)\n\nComputes the `n`th triangular number `T(n)`, with `T(1) = 1`. The resulting\nvalue is also the sum of the first `n` natural numbers.\n\n## Preconditions\n- `n ≥ 0`\n\n## Examples\n```jldoctest\njulia> triangular(1)\n1\n\njulia> triangular(0x03)\n0x06\n\njulia> triangular(4)\n10\n```\n\"\"\"\ntriangular(n::Integer) = n * (n + oneunit(n)) ÷ convert(typeof(n), 2)\n\nend\n", "meta": {"hexsha": "cdbed0b1c5ca51c28e4d5a5fafea0767a225ac05", "size": 3785, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "jl/src/Sequences.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/Sequences.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/Sequences.jl", "max_forks_repo_name": "curtislb/ProjectEuler", "max_forks_repo_head_hexsha": "7baf8d7b7ac0e8697d4dec03458b473095a45da4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.7699530516, "max_line_length": 77, "alphanum_fraction": 0.6441215324, "num_tokens": 1152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.8740772433654401, "lm_q1q2_score": 0.8077713363119212}} {"text": "\"\"\"Julia program to check if a number is a Magic Number or not\nA number is said to be a magic number if the recursive sum of its digits is 1.\n For Example Let's Consider\n 19, 1 + 9 = 10\n 10, 1 + 0 = 1\n = 1 , Hence 19 is a Maigc Number\n\"\"\"\n\n\nfunction sum_of_digits(n)\n sum = 0\n while(n>0)\n rem = n % 10\n sum = sum + rem\n n = n ÷ 10\n end\n return sum\nend\n\nfunction check_magic_num(n)\n while(n > 9)\n n = sum_of_digits(n)\n end\n if(n == 1)\n return true\n else\n return false\n end\nend\n\n\n\nprint(\"Enter the number: \")\nn = readline()\nn = parse(Int, n)\nres = check_magic_num(abs(n))\nif res\n println(\"The given number $n is a Magic Number.\")\nelse\n println(\"The given number $n is not a Magic Number.\")\nend\n\n\n\"\"\"\nTime Complexity: O(log(n)), where 'n' is the given number\nSpace Complexity: O(1)\n\nSAMPLE INPUT AND OUTPUT\n\nSAMPLE 1\nEnter the number: 23\nThe given number 23 is not a Magic Number.\n\nSAMPLE 2\nEnter the number: 1729\nThe given number 1729 is a Magic Number..\n\n\"\"\"\n", "meta": {"hexsha": "ba97a34e263de72b5cd375d13f729749cf31ffce", "size": 1051, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/math/magic_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/magic_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/magic_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": 17.813559322, "max_line_length": 78, "alphanum_fraction": 0.6194100856, "num_tokens": 318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787566, "lm_q2_score": 0.874077222043951, "lm_q1q2_score": 0.8077713147816726}} {"text": "\nusing OrdinaryDiffEq\nusing DiffEqCallbacks\nusing QuasiMonteCarlo\nusing StatsBase\nusing Plots\n\n\nfunction sir_ode!(du,u,p,t)\n (S,I,R) = u\n (β,c,γ) = p\n N = S+I+R\n @inbounds begin\n du[1] = -β*c*I/N*S\n du[2] = β*c*I/N*S - γ*I\n du[3] = γ*I\n end\n nothing\nend;\n\n\ntmax = 10000.0\ntspan = (0.0,tmax)\n\n\ncb_ss = TerminateSteadyState();\n\n\nN = 1000.0;\nu0 = [990.0,10.0,0.0];\np = [0.05,10.0,0.25]; # β,c,γ\n\n\nn_samples = 1000 # Number of samples\n# Parameters are β, c, γ, I₀\nlb = [0.01, 5.0, 0.1, 1.0]\nub = [0.1, 20.0, 1.0, 50.0];\n\n\npu0 = QuasiMonteCarlo.sample(n_samples,lb,ub,LatinHypercubeSample());\n\n\nprob_ode = ODEProblem(sir_ode!,u0,tspan,p);\n\n\nf1 = function(pu0)\n p = pu0[1:3]\n I0 = pu0[4]\n u0 = [N-I0,I0,0.0]\n prob = remake(prob_ode;p=p,u=u0)\n sol = solve(prob, ROS34PW3(),callback=cb_ss)\n [maximum(sol[2,:]), sol.t[argmax(sol[2,:])], sol[end][3]]\nend;\n\n\nm_serial = [f1(pu0[:,i]) for i in 1:n_samples]\nm_serial = hcat(m_serial...); # convert into matrix\n\n\npf1 = function (pu0)\n p = pu0[1:3,:]\n I0 = pu0[4,:]\n prob_func(prob,i,repeat) = remake(prob;p=p[:,i],u=[N-I0[i],I0[i],0.0])\n ensemble_prob = EnsembleProblem(prob_ode,prob_func=prob_func)\n sol = solve(ensemble_prob,ROS34PW3(),EnsembleThreads();trajectories=size(p,2))\n out = zeros(3,size(p,2))\n for i in 1:size(p,2)\n out[1,i] = maximum(sol[i][2,:])\n out[2,i] = sol[i].t[argmax(sol[i][2,:])]\n out[3,i] = sol[i][end][3]\n end\n out\nend;\n\n\nm_parallel = pf1(pu0);\n\n\nl = @layout [a b; c d]\npl1 = scatter(pu0[1,:],m_parallel[1,:],title=\"Peak infected\",xlabel=\"β\",ylabel=\"Number\")\npl2 = scatter(pu0[2,:],m_parallel[1,:],title=\"Peak infected\",xlabel=\"c\",ylabel=\"Number\")\npl3 = scatter(pu0[3,:],m_parallel[1,:],title=\"Peak infected\",xlabel=\"γ\",ylabel=\"Number\")\npl4 = scatter(pu0[4,:],m_parallel[1,:],title=\"Peak infected\",xlabel=\"I₀\",ylabel=\"Number\")\nplot(pl1,pl2,pl3,pl4,layout=l,legend=false)\n\n\nl = @layout [a b; c d]\npl1 = scatter(pu0[1,:],m_parallel[2,:],title=\"Peak time\",xlabel=\"β\",ylabel=\"Time\")\npl2 = scatter(pu0[2,:],m_parallel[2,:],title=\"Peak time\",xlabel=\"c\",ylabel=\"Time\")\npl3 = scatter(pu0[3,:],m_parallel[2,:],title=\"Peak time\",xlabel=\"γ\",ylabel=\"Time\")\npl4 = scatter(pu0[4,:],m_parallel[2,:],title=\"Peak time\",xlabel=\"I₀\",ylabel=\"Time\")\nplot(pl1,pl2,pl3,pl4,layout=l,legend=false)\n\n\nl = @layout [a b; c d]\npl1 = scatter(pu0[1,:],m_parallel[3,:],title=\"Final size\",xlabel=\"β\",ylabel=\"Number\")\npl2 = scatter(pu0[2,:],m_parallel[3,:],title=\"Final size\",xlabel=\"c\",ylabel=\"Number\")\npl3 = scatter(pu0[3,:],m_parallel[3,:],title=\"Final size\",xlabel=\"γ\",ylabel=\"Number\")\npl4 = scatter(pu0[4,:],m_parallel[3,:],title=\"Final size\",xlabel=\"I₀\",ylabel=\"Number\")\nplot(pl1,pl2,pl3,pl4,layout=l,legend=false)\n\n\ncorkendall(pu0',m_parallel')\n\n", "meta": {"hexsha": "a6ff0f44470b0cf60516366ba1830f82cb7903c7", "size": 2743, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/ode_global_sensitivity/ode_global_sensitivity.jl", "max_stars_repo_name": "Song921012/sir-julia", "max_stars_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "script/ode_global_sensitivity/ode_global_sensitivity.jl", "max_issues_repo_name": "Song921012/sir-julia", "max_issues_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/ode_global_sensitivity/ode_global_sensitivity.jl", "max_forks_repo_name": "Song921012/sir-julia", "max_forks_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1238095238, "max_line_length": 89, "alphanum_fraction": 0.6332482683, "num_tokens": 1077, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741308615412, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.8077521449455836}} {"text": "function gaussPoints1D(n::Int64)\r\n # Gauss points\r\n if n == 2\r\n gpCoord = [-1/sqrt(3) 1/sqrt(3)]\r\n gpW = [1.0 1.0]\r\n elseif n == 3\r\n gpCoord = [-sqrt(3/5) 0 sqrt(3/5)]\r\n gpW = [5/9 8/9 5/9]\r\n elseif n == 4\r\n gpCoord = [-sqrt(3/7 + 2/7*sqrt(6/5)) -sqrt(3/7 - 2/7*sqrt(6/5)) sqrt(3/7 - 2/7*sqrt(6/5)) sqrt(3/7 + 2/7*sqrt(6/5))]\r\n gpW = [(18 - sqrt(30))/36 (18 + sqrt(30))/36 (18 + sqrt(30))/36 (18 - sqrt(30))/36]\r\n end\r\n return hcat(gpW', gpCoord')\r\nend\r\n\r\nfunction gaussPoints2D(n::Int64)\r\n # Gauss points\r\n coords, weights, x, w = zeros(n, n, 2), zeros(n, n), [], []\r\n if n == 2\r\n x = [-1 / sqrt(3), 1 / sqrt(3)]\r\n w = [1.0, 1.0]\r\n elseif n == 3\r\n x = [-sqrt(3 / 5), 0, sqrt(3 / 5)]\r\n w = [5 / 9, 8 / 9, 5 / 9]\r\n elseif n == 4\r\n x = [-sqrt(3 / 7 + 2 / 7 * sqrt(6 / 5)), -sqrt(3 / 7 - 2 / 7 * sqrt(6 / 5)), sqrt(3 / 7 - 2 / 7 * sqrt(6 / 5)), sqrt(3 / 7 + 2 / 7 * sqrt(6 / 5))]\r\n w = [(18 - sqrt(30)) / 36, (18 + sqrt(30)) / 36, (18 + sqrt(30)) / 36, (18 - sqrt(30)) / 36]\r\n end\r\n for i in 1:n\r\n for j = 1:n\r\n coords[i, j, :] = [x[i], x[j]]\r\n weights[i, j] = w[i] * w[j]\r\n end\r\n end\r\n gpCoord = reshape(coords, n * n, 2)\r\n gpW = reshape(weights, n * n, 1)\r\n return hcat(gpW, gpCoord)\r\nend", "meta": {"hexsha": "ec7872cd316cc16ebb2f4192574969697bc0a721", "size": 1358, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "helperFunctions.jl", "max_stars_repo_name": "likemaestro/Nonlinear-Homogenization", "max_stars_repo_head_hexsha": "a7b1b5b8a25d1c9f81a1f6651f9a8a1e7e34edf6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "helperFunctions.jl", "max_issues_repo_name": "likemaestro/Nonlinear-Homogenization", "max_issues_repo_head_hexsha": "a7b1b5b8a25d1c9f81a1f6651f9a8a1e7e34edf6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "helperFunctions.jl", "max_forks_repo_name": "likemaestro/Nonlinear-Homogenization", "max_forks_repo_head_hexsha": "a7b1b5b8a25d1c9f81a1f6651f9a8a1e7e34edf6", "max_forks_repo_licenses": ["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.7368421053, "max_line_length": 155, "alphanum_fraction": 0.4300441826, "num_tokens": 588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741322079104, "lm_q2_score": 0.8479677506936878, "lm_q1q2_score": 0.8077521442573334}} {"text": "# ---\n# jupyter:\n# jupytext:\n# text_representation:\n# extension: .jl\n# format_name: light\n# format_version: '1.3'\n# jupytext_version: 0.8.6\n# kernelspec:\n# display_name: Julia 1.0.3\n# language: julia\n# name: julia-1.0\n# ---\n\nusing DifferentialEquations\n\nfunction main()\n\n# # Model Specifications\n# - SH num of high risk susceptible\n# - IH num of high risk infected \n# - SL num of low risk susceptible\n# - IL num of low risk infected\n# # Parameters\n# - beta represents the determines the contact and transmission rates\n# - gamma the rate at which treatment is sought\n\nfunction sis_ode(du,u,p,t)\n SH,IH,SL,IL = u\n betaHH,betaHL,betaLH,betaLL,gamma=p\n du[1]=-(betaHH*IH+betaHL*IL)*SH+gamma*IH\n du[2]=+(betaHH*IH+betaHL*IL)*SH-gamma*IH\n du[3]=-(betaLH*IH+betaLL*IL)*SL+gamma*IL\n du[4]=+(betaLH*IH+betaLL*IL)*SL-gamma*IL\nend\n\nparms =[10,0.1,0.1,1,1]\ninit=[0.19999,0.00001,0.799,0.001]\ntspan=tspan = (0.0,15.0)\n\nsis_prob = ODEProblem(sis_ode,init,tspan,parms)\nsis_sol = solve(sis_prob,saveat=0.1);\n\nend", "meta": {"hexsha": "82a3a8c07e1d026ac9335ff0aa1f0b4e392daa18", "size": 1082, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/typing/files/SISModel.jl", "max_stars_repo_name": "mikiec84/SemanticModels.jl", "max_stars_repo_head_hexsha": "f81baf0789cc547375f300429d0fd49c866d5339", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-01-21T15:52:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-21T15:52:41.000Z", "max_issues_repo_path": "examples/typing/files/SISModel.jl", "max_issues_repo_name": "mikiec84/SemanticModels.jl", "max_issues_repo_head_hexsha": "f81baf0789cc547375f300429d0fd49c866d5339", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/typing/files/SISModel.jl", "max_forks_repo_name": "mikiec84/SemanticModels.jl", "max_forks_repo_head_hexsha": "f81baf0789cc547375f300429d0fd49c866d5339", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5909090909, "max_line_length": 69, "alphanum_fraction": 0.6487985213, "num_tokens": 383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214511730024, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.8077349024819077}} {"text": "# ---\n# title: 400. Nth Digit\n# id: problem400\n# author: Indigo\n# date: 2021-06-20\n# difficulty: Medium\n# categories: Math\n# link: \n# hidden: true\n# ---\n# \n# Find the _n_ th digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8,\n# 9, 10, 11, ...\n# \n# **Note:** \n# _n_ is positive and will fit within the range of a 32-bit signed integer ( _n_\n# < 231).\n# \n# **Example 1:**\n# \n# \n# \n# Input:\n# 3\n# \n# Output:\n# 3\n# \n# \n# **Example 2:**\n# \n# \n# \n# Input:\n# 11\n# \n# Output:\n# 0\n# \n# Explanation:\n# The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.\n# \n# \n# \n## @lc code=start\nusing LeetCode\n\nfunction find_nth_digit(n::Int)\n ant = [0, 10, 190, 2890, 38890, 488890, 5888890, 68888890, 788888890]\n num_begin = [0, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000]\n idx = searchsortedlast(ant, n)\n num = (n - ant[idx]) ÷ idx + num_begin[idx]\n posi = (n - ant[idx]) % idx\n return num % (10^(idx - posi)) ÷ 10^(idx - posi - 1)\nend\n## @lc code=end\n", "meta": {"hexsha": "92ffc51fd75283097d5da082156a6779c8f40f62", "size": 1165, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/400.nth-digit.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2020-10-27T18:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:27:49.000Z", "max_issues_repo_path": "src/problems/400.nth-digit.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-01T07:26:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T11:57:53.000Z", "max_forks_repo_path": "src/problems/400.nth-digit.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2020-10-30T11:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:35:11.000Z", "avg_line_length": 20.4385964912, "max_line_length": 115, "alphanum_fraction": 0.5484978541, "num_tokens": 462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9416541610257063, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.807720905259066}} {"text": "using Stheno, Optim, Plots, Zygote\n\nusing Stheno: derivative\n\nconst σ²_noise = 1e-3\n\n# Helper function: Parameter handling.\nfunction unpack(θ)\n σ² = exp(θ[1]) + 1e-3\n l = exp(θ[2]) + 1e-3\n return σ², l\nend\n\n# Helper function: construct the model and it's derivative.\nfunction build_model(θ)\n σ², l = unpack(θ)\n k = σ² * stretch(EQ(), 1 / l)\n f = GP(k, GPC())\n df = derivative(f)\n return f, df\nend\n\n\"\"\"\n nlml(θ, x_f, y_f, x_df, y_df)\n\nCompute the negative log marginal likelihood of the parameters θ given observations y_f of\nf at x_f and observations y_df of df at x_df.\n\"\"\"\nfunction nlml(\n θ,\n x_f::AbstractVector{<:Real},\n y_f::AbstractVector{<:Real},\n x_df::AbstractVector{<:Real},\n y_df::AbstractVector{<:Real},\n)\n f, df = build_model(θ)\n\n # Specify points in processes at which we'll make observations.\n fx = f(x_f, σ²_noise)\n dfx = df(x_df, σ²_noise)\n return -logpdf([fx, dfx], [y_f, y_df])\nend\n\n# Toy problem with synthetic data.\ng = sin\ndg = cos\n\nx_g = range(-10.0, 10.0; length=15);\nx_dg = range(-10.0, 10.0; length=20);\n\ny_g = g.(x_g) .+ sqrt(σ²_noise) .* randn(length(x_g));\ny_dg = dg.(x_dg) .+ sqrt(σ²_noise) .* randn(length(x_dg));\n\nnlml(θ) = nlml(θ, x_g, y_g, x_dg, y_dg)\n\n# Optimise the hyper-parameters using a gradient-free method to start with.\nθ0 = randn(2);\nresults = Optim.optimize(nlml, θ -> only(Zygote.gradient(nlml, θ)), θ0, BFGS(); inplace=false)\nθ_opt = results.minimizer;\n\n# Get process at optimal parameters, and produce the posteriors.\nf, df = build_model(θ_opt);\nf_post, df_post = (f, df) | (f(x_g, 1e-3) ← y_g, df(x_dg, 1e-3) ← y_dg);\n\n# Make posterior predictions and visualise.\nx_pr = range(-15.0, 15.0; length=250);\n\nplt = plot();\nscatter!(plt, x_g, y_g; color=:red, label=\"y_g\");\nscatter!(plt, x_dg, y_dg; color=:blue, label=\"y_dg\");\nplot!(plt, x_pr, g.(x_pr); color=:red, label=\"g\");\nplot!(plt, x_pr, dg.(x_pr); color=:blue, label=\"dg\");\nplot!(plt, f_post(x_pr, 1e-3); samples=10, label=\"f_post\");\nplot!(plt, df_post(x_pr, 1e-3); samples=10, label=\"df_post\");\ndisplay(plt);\n", "meta": {"hexsha": "3030601ecd6ca37bec489df351abf7a881b9bdbf", "size": 2069, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "derivative_obs_opt.jl", "max_stars_repo_name": "willtebbutt/derivative_obs", "max_stars_repo_head_hexsha": "ffd1c3536d957f7623672e8263d96944f9e6b51e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "derivative_obs_opt.jl", "max_issues_repo_name": "willtebbutt/derivative_obs", "max_issues_repo_head_hexsha": "ffd1c3536d957f7623672e8263d96944f9e6b51e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "derivative_obs_opt.jl", "max_forks_repo_name": "willtebbutt/derivative_obs", "max_forks_repo_head_hexsha": "ffd1c3536d957f7623672e8263d96944f9e6b51e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2236842105, "max_line_length": 94, "alphanum_fraction": 0.6520057999, "num_tokens": 743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541561135441, "lm_q2_score": 0.8577681031721325, "lm_q1q2_score": 0.8077208993336699}} {"text": "using DifferentialEquations\nusing Plots;gr()\n\nfunction model!(du, u, p, t)\n\tω0, ωF, ωM, ϕF, ϕM, μ, ν, αF, αM, ψF, ψM = p\n\tdu[1] = ω0\n\tdu[2] = ωF + μ*sin(u[3]-u[2]-ϕF) + αF*sin(u[1]-u[2]-ψF)\n\tdu[3] = ωM + ν*sin(u[2]-u[3]-ϕM) + αM*sin(u[1]-u[3]-ψM)\nend\n\nθ = rand(3).%(2π) # Initial phases (Sunlight, fibroblast, macrophage)\ntMax = 10.0 \t # Total time\nω0 = 2π # Sunlight phase rate of change /day\nωF = 2π # Fibroblast phase intrinsic rate of change /day\nωM = 2π # Macrophage phase intrinsic rate of change /day\nϕF = 3π/5 # Fibroblast phase offset in coupling to macrophage\nϕM = 2π/5 \t\t # Macrophage phase offset in coupling to fibroblast\nμ = 1.0 # Amplitude of fibroblast phase coupling to macrophage\nν = 0.0 # Amplitude of macrophage phase coupling to fibroblast\nαF = 10.0 # Amplitude of fibroblast phase coupling to sunlight\nαM = 10.0 # Amplitude of macrophage phase coupling to sunlight\nψF = π/8 # Fibroblast phase offset from sunlight\nψM = π/4 # Macrophage phase offset from sunlight\np = [ω0, ωF, ωM, ϕF, ϕM, μ, ν, αF, αM, ψF, ψM]\n\nprob = ODEProblem(model!,θ,(0.0,tMax),p)\nsol = solve(prob, Tsit5(),saveat=0.01)\n\nu1s = [(θ[1]%2π)-π for θ in sol.u]\nu2s = [(θ[2]%2π)-π for θ in sol.u]\nu3s = [(θ[3]%2π)-π for θ in sol.u]\n\n#plt = Figure()\n#ax = Axis(plt)\nplot(sol.t,u1s)\nplot!(sol.t,u2s)\nplot!(sol.t,u3s)\n#display(plt)\n\n# anim = @animate for u in sol.u\n# \tscatter(sin.(u),cos.(u),xlims=(-1.1,1.1),ylims=(-1.1,1.1),aspect_ratio=:equal,marker=[:star8,:circle,:circle],color=[:red,:green,:blue],ms=10,series_annotations=[\"Light\",\"Fib\",\"Mac\"],legend=:none)\n# end\n# gif(anim,\"test.gif\",fps=3)\n", "meta": {"hexsha": "9d1976239580b0094fc4949c6cfc2139739e4c54", "size": 1691, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "tests/test.jl", "max_stars_repo_name": "chris-revell/ClockOscillators", "max_stars_repo_head_hexsha": "b5d39a26c3465f0c5d0b2b5cf2eae136231f9352", "max_stars_repo_licenses": ["MIT"], "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/test.jl", "max_issues_repo_name": "chris-revell/ClockOscillators", "max_issues_repo_head_hexsha": "b5d39a26c3465f0c5d0b2b5cf2eae136231f9352", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/test.jl", "max_forks_repo_name": "chris-revell/ClockOscillators", "max_forks_repo_head_hexsha": "b5d39a26c3465f0c5d0b2b5cf2eae136231f9352", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4318181818, "max_line_length": 199, "alphanum_fraction": 0.6209343584, "num_tokens": 687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541544761566, "lm_q2_score": 0.8577681031721325, "lm_q1q2_score": 0.8077208979291711}} {"text": "#=\npoweriter.jl\n2019-06-06, Jeff Fessler, University of Michigan\n=#\n\nexport poweriter\n\nusing LinearAlgebra: norm\n\n\n\"\"\"\n v1,σ1 = poweriter(A; niter=?, ...)\n\nDetermine first right singular vector `v1`\nand first singular value `σ1` of `A`\nby applying power iteration to `A'A`\n\nin\n- `A` M × N matrix\n\noption\n- `niter` default 200\n- `x0` initial guess of `v1`\n- `tol` stopping tolerance for s1, default 1e-6\n- `chat::Bool` verbose? default false\n\nout\n- `v1` `[N]` principal right singular vector\n- `σ1` spectral norm of `A`\n\"\"\"\nfunction poweriter(\n A ;\n niter::Int=200,\n tol::Real = 1e-6,\n x0::AbstractArray{<:Number} = ones(eltype(A), size(A,2)),\n chat::Bool = true,\n)\n\n\tx = copy(x0)\n\tratio_old = Inf\n\tfor iter=1:niter\n\t\tAx = A * x\n\t\tratio = norm(Ax) / norm(x)\n\t\tif abs(ratio - ratio_old) / ratio < tol\n\t\t\tchat && @info \"done at iter $iter\"\n\t\t\tbreak\n\t\tend\n\t\tratio_old = ratio\n\t\tx = A' * Ax\n\t\tx /= norm(x)\n\tend\n\treturn x, norm(A * x) / norm(x)\nend\n", "meta": {"hexsha": "007945e142d55082940a4724e3c8f1f5e6aa97b7", "size": 961, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/algorithm/general/poweriter.jl", "max_stars_repo_name": "jamesthesnake/MIRT.jl", "max_stars_repo_head_hexsha": "3a4b1e33a35e2ab062f532a22866bfb11f6e5cd5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/algorithm/general/poweriter.jl", "max_issues_repo_name": "jamesthesnake/MIRT.jl", "max_issues_repo_head_hexsha": "3a4b1e33a35e2ab062f532a22866bfb11f6e5cd5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/algorithm/general/poweriter.jl", "max_forks_repo_name": "jamesthesnake/MIRT.jl", "max_forks_repo_head_hexsha": "3a4b1e33a35e2ab062f532a22866bfb11f6e5cd5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.7962962963, "max_line_length": 61, "alphanum_fraction": 0.6285119667, "num_tokens": 338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9458012732322216, "lm_q2_score": 0.8539127455162773, "lm_q1q2_score": 0.807631761938517}} {"text": "using DifferentialEquations, Flux, DiffEqFlux\nusing Plots, NPZ\nusing IterTools: ncycle\nusing BSON: @save, @load\n\ntrue_data = npzread(\"data.npy\")[1:20:4000,:]\ndata_len = size(true_data)[1]\nx_data = true_data[:,1]\nstate_data = true_data[:,2:3]\n\nu0 = [true_data[1,2],true_data[1,3]]\ntspan = (0.0,true_data[data_len,1])\ntsteps = 0.0:true_data[data_len,1]-true_data[data_len-1,1]:true_data[data_len,1]\n\nmy_nn = Chain(\n Dense(2, 32, relu),\n Dense(32, 2)) |> f32\n\np, re = Flux.destructure(my_nn)\n\nfunction right_hand_side(du,u,p,t)\n m = re(p)\n nn_output = m(u)\n du[1] = nn_output[1]\n du[2] = nn_output[2]\nend\n\nprob = ODEProblem(right_hand_side,u0,tspan,p)\nsol = solve(prob, Tsit5())\n\n# Plot the solution\nplot(sol)\nsavefig(\"Initial_NN_ODE.png\")\n\nfunction predict_ode(state_batch,time_batch)\n tmp_prob = remake(prob; p = p,u=state_batch[1])\n pred = Array(solve(tmp_prob, Tsit5(), saveat = time_batch))\n return pred\nend\n\nfunction loss_ode(state_batch,time_batch)\n pred = predict_ode(state_batch,time_batch)\n loss = sum(abs2, state_batch-pred)\n return loss\nend\n\nk = 20\ntrain_loader = Flux.Data.DataLoader((transpose(state_data), tsteps), batchsize = k)\nnumEpochs = 200\nlosses=[]\n\n# test_batch = iterate(train_loader)\n# print(check[1][2])\n# print(size(test_batch[1][1]))\n# loss_ode(test_batch[1][1],test_batch[1][2])\n\ncb() = begin\n \n l=loss_ode(transpose(state_data), tsteps)\n push!(losses, l)\n @show l\n\n pred = predict_ode(transpose(state_data),tsteps)\n \n plt = plot(x_data,hcat(transpose(pred),state_data), \n line=(4, [:solid :solid :dash :dash]), ylim = (-6, 6),\n label=[\"y1-pred\" \"y2-pred\" \"y1-true\" \"y2-true\"])\n \n display(plt)\n # Tell sciml_train to not halt the optimization. If return true, then\n # optimization stops.\n return false\nend\n\nopt=ADAM(0.01)\nFlux.train!(loss_ode, Flux.params(p), ncycle(train_loader,numEpochs), opt, cb=Flux.throttle(cb, 10))\n\nmy_nn_final = re(p)\n@save \"mymodel.bson\" my_nn_final\n\n# Inference\n@load \"mymodel.bson\" my_nn_final\np, re = Flux.destructure(my_nn_final)\n\n\nprob_final = ODEProblem(right_hand_side, u0, tspan, p)\nsol_final = solve(prob_final,Tsit5())\nplot(sol_final)\nsavefig(\"NN_ode_optimized.png\") # Both state components close to 1", "meta": {"hexsha": "76e320877bb28ac796069cc9fd86f8da91e36638", "size": 2200, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "NODE_Julia/Prelim_studies/neural_ode_IV.jl", "max_stars_repo_name": "Romit-Maulik/Tutorials-Demos-Practice", "max_stars_repo_head_hexsha": "a58ddc819f24a16f7059e63d7f201fc2cd23e03a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NODE_Julia/Prelim_studies/neural_ode_IV.jl", "max_issues_repo_name": "Romit-Maulik/Tutorials-Demos-Practice", "max_issues_repo_head_hexsha": "a58ddc819f24a16f7059e63d7f201fc2cd23e03a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NODE_Julia/Prelim_studies/neural_ode_IV.jl", "max_forks_repo_name": "Romit-Maulik/Tutorials-Demos-Practice", "max_forks_repo_head_hexsha": "a58ddc819f24a16f7059e63d7f201fc2cd23e03a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7191011236, "max_line_length": 100, "alphanum_fraction": 0.7086363636, "num_tokens": 723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.865224091265267, "lm_q1q2_score": 0.807626828436527}} {"text": "\nfunction locS(w::Real, b::Real, c::Real, d::Real)\n S = (w^2 + c^2)^(-d) + b^2\n return S\nend\n\nfunction locS(b::Real, c::Real, d::Real)\n S = NaN*zeros(10000); n_w = length(S)\n w_grid = collect(linspace(0.001, 15*π, n_w))\n i = 0\n for w in w_grid\n i += 1\n S[i] = (w^2 + c^2)^(-d) + b^2\n end\n return S\nend\n\n\nfunction locSs(b::Real, c::Real, d::Real)\n S = locS(b, c, d)\n n = length(S)\n w_grid = collect(linspace(0.001, 15π, n))\n tmp, i1 = findmin(abs(w_grid-6*π))\n Ss = S./S[i1]\n x = w_grid/π\n return Ss, x\nend\n#\nfunction plot_locS(b::Real, c::Real, d::Real)\n title(\"Local to Zero Spectrum: S(ω;b,c,d)∝(c² + d²)^(-1) + b²\")\n Ss, x = locSs(b, c, d)\n _plt = plot(x, log(Ss), label = \"($(round(b, 2)), $(round(c, 2)), $(round(d, 2)))\")\n legend()\n return _plt\nend\n#\nfunction plot_locS(m::String)\n if m == \"local level\"\n println(\"$m model\")\n b_grid = [1/50 1/10 1/2 10e16]\n for b in b_grid\n Ss, x = locSs(b, 0, 1)\n plot(x, log(Ss), label = \"b = $b\")\n legend()\n end\n\n end\n if m == \"local to unity\"\n println(\"$m model\")\n c_grid = [0 3 10 30]\n for c in c_grid\n Ss, x = locSs(0, c, 1)\n plot(x, log(Ss), label = \"c = $c\")\n end\n legend()\n end\n if m == \"fractional\"\n println(\"$m model\")\n d_grid = [-1/3 0 1/3 1 4/3]\n for d in d_grid\n Ss, x = locSs(0, 0, d)\n plot(x, log(Ss), label = \"d = $d\")\n end\n legend()\n end\n if m == \"bcd\"\n b_grid = [1/50 1/10 1/2 10e16]\n c_grid = [0 3 10 30]\n d_grid = [-1/3 0 1/3 1 4/3]\n for b in b_grid\n for c in c_grid\n for d in d_grid\n println(\"$b, $c, $d\")\n Ss, x = locSs(b, c, d)\n plot(x, log(Ss))\n end\n end\n end\n end\nend\n\n#end #module\n", "meta": {"hexsha": "94be49edcf5893660e7c7eb5f1d4767a9a92e1cc", "size": 1737, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/bcdModel/bcd_spectrum.jl", "max_stars_repo_name": "p-chaim/LowFrequencyEconometrics.jl", "max_stars_repo_head_hexsha": "4ad3c2ab91e4647921e66fcb9afd74284007c522", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/bcdModel/bcd_spectrum.jl", "max_issues_repo_name": "p-chaim/LowFrequencyEconometrics.jl", "max_issues_repo_head_hexsha": "4ad3c2ab91e4647921e66fcb9afd74284007c522", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/bcdModel/bcd_spectrum.jl", "max_forks_repo_name": "p-chaim/LowFrequencyEconometrics.jl", "max_forks_repo_head_hexsha": "4ad3c2ab91e4647921e66fcb9afd74284007c522", "max_forks_repo_licenses": ["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.9277108434, "max_line_length": 87, "alphanum_fraction": 0.5048934945, "num_tokens": 740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731765, "lm_q2_score": 0.8670357563664174, "lm_q1q2_score": 0.8076113025551833}} {"text": "###ODE for a predator-prey model\n### t = timepoints to evaluate the ODE at\n### y = the model's state variables (prey population size - predator population size)\n### ydot = the derivate values\n### paras = the equation parameters (r,K,s,a,u,v)\nfunction predatorpreyode(t,y,ydot,paras)\n\n r = paras[1]\n k = paras[2]\n s = paras[3]\n a = paras[4]\n u = paras[5]\n v = paras[6]\n\n tmp = y[1]*y[2]/(a + y[1])\n\n ydot[1] = r*y[1]*(1-y[1]/k) - s*tmp\n ydot[2] = u*tmp - v*y[2]\n\n nothing\nend\n\n###Convenience function to create a Predator-Prey ODEModel\n### y0: initial conditions of the dynamic system\n### variance: the variance of the noise model\n### paraminit: the default and boundary values of the parameters\nfunction predatorpreymodel(y0::AbstractVector,variance::AbstractVector,paraminit...)\n modelparameters = parameters([:r,:k,:s,:a,:u,:v],paraminit...)\n noisemodel = noise(:gaussian,variance)\n measurementdata = data(:array,predatorpreydataset1()...)\n model(:ode,modelparameters,measurementdata,noisemodel,predatorpreyode,y0,2,[1,2];\n name=\"Predator-Prey\",abstol=10e-9,reltol=10e-9)\nend\n\n", "meta": {"hexsha": "1b51fcf180975d9f91782e33f611dcbe950e212d", "size": 1130, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ode/predatorprey/models/model.jl", "max_stars_repo_name": "QuantifyingUncertainty/GMH-Examples.jl", "max_stars_repo_head_hexsha": "5a037daefacfd9f873c7293d064c4dbaa7b58a93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-07-08T19:20:21.000Z", "max_stars_repo_stars_event_max_datetime": "2016-07-08T19:20:21.000Z", "max_issues_repo_path": "ode/predatorprey/models/model.jl", "max_issues_repo_name": "QuantifyingUncertainty/GMH-Examples.jl", "max_issues_repo_head_hexsha": "5a037daefacfd9f873c7293d064c4dbaa7b58a93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ode/predatorprey/models/model.jl", "max_forks_repo_name": "QuantifyingUncertainty/GMH-Examples.jl", "max_forks_repo_head_hexsha": "5a037daefacfd9f873c7293d064c4dbaa7b58a93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2857142857, "max_line_length": 85, "alphanum_fraction": 0.6707964602, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474142844408, "lm_q2_score": 0.8459424431344438, "lm_q1q2_score": 0.8075767659717593}} {"text": "#The m-by-n Hilbert matrix has matrix elements\n# H_{ij} = 1/(i+j-1)\nexport Hilbert, InverseHilbert\n\"\"\"\n[`Hilbert` matrix](http://en.wikipedia.org/wiki/Hilbert_matrix)\n\n```julia\njulia> A=Hilbert(5)\nHilbert{Rational{Int64}}(5,5)\n\njulia> Matrix(A)\n5x5 Array{Rational{Int64},2}:\n 1//1 1//2 1//3 1//4 1//5\n 1//2 1//3 1//4 1//5 1//6\n 1//3 1//4 1//5 1//6 1//7\n 1//4 1//5 1//6 1//7 1//8\n 1//5 1//6 1//7 1//8 1//9\n\njulia> Matrix(Hilbert(5))\n5x5 Array{Rational{Int64},2}:\n 1//1 1//2 1//3 1//4 1//5\n 1//2 1//3 1//4 1//5 1//6\n 1//3 1//4 1//5 1//6 1//7\n 1//4 1//5 1//6 1//7 1//8\n 1//5 1//6 1//7 1//8 1//9\n```\nInverses are also integer matrices:\n\n```julia\njulia> inv(A)\n5x5 Array{Rational{Int64},2}:\n 25//1 -300//1 1050//1 -1400//1 630//1\n -300//1 4800//1 -18900//1 26880//1 -12600//1\n 1050//1 -18900//1 79380//1 -117600//1 56700//1\n -1400//1 26880//1 -117600//1 179200//1 -88200//1\n 630//1 -12600//1 56700//1 -88200//1 44100//1\n```\n\"\"\"\nstruct Hilbert{T} <: AbstractMatrix{T}\n m :: Int\n n :: Int\nend\nHilbert(T::Type, m::Integer, n::Integer) = Hilbert{T}(m, n)\nHilbert(T::Type{<:Integer}, m::Integer, n::Integer) = Hilbert(Rational{T}, m, n)\nHilbert(m::Integer, n::Integer) = Hilbert(Int, m, n)\nHilbert(n::Integer) = Hilbert(n, n)\n\n# Define its size\nsize(H::Hilbert, dim::Integer) = dim==1 ? H.m : dim==2 ? H.n : 1\nsize(H::Hilbert)= size(H,1), size(H,2)\n\n# Index into a Hilbert matrix\nfunction getindex(H::Hilbert{T}, i::Integer, j::Integer) where {T}\n return one(T)/(i+j-1)\nend\n\n# Dense version\nMatrix(H::Hilbert) = [H[i,j] for i=1:size(H,1), j=1:size(H,2)]\n\n# Some properties\nishermitian(H::Hilbert) = H.m==H.n\nisposdef(H::Hilbert) = H.m==H.n\ndet(H::Hilbert) = inv(det(inv(H)))\n\n\n# Inverse of a Hilbert matrix\nstruct InverseHilbert{T} <: AbstractMatrix{T}\n n :: Int\nend\nInverseHilbert(T::Type, n::Integer) = InverseHilbert{T}(n)\nInverseHilbert(n::Integer) = InverseHilbert(Int, n)\n\n# Define its size\nsize(A::InverseHilbert, dim::Integer) = dim==1 || dim==2 ? A.n : 1\nsize(A::InverseHilbert) = size(A,1), size(A,2)\n\n# Index into a inverse Hilbert matrix\nfunction getindex(A::InverseHilbert{T}, i::Integer, j::Integer) where {T}\n return T((-1)^(i+j)*(i+j-1)*binomial(A.n+i-1,A.n-j)*\n binomial(A.n+j-1,A.n-i)*binomial(i+j-2,i-1)^2)\nend\n# Use bigger numbers in case of bigger types\nfunction getindex(A::InverseHilbert{T}, i::Integer, j::Integer) where {T<:Union{BigInt,BigFloat}}\n N = big(A.n)\n return T((-1)^(i+j)*(i+j-1)*binomial(N+i-1,N-j)*\n binomial(N+j-1,N-i)*binomial(big(i+j-2),i-1)^2)\nend\n\n# Explicit formula for the determinant\ndet(A::InverseHilbert{T}) where {T} = prod(T,(2k+1)*binomial(2k,k)^2 for k=1:A.n-1)\n\n# Dense version\nMatrix(A::InverseHilbert) = [A[i,j] for i=1:size(A,1), j=1:size(A,2)]\n\n# Define Base.inv\nfunction inv(H::Hilbert{T}) where {T}\n H.m == H.n || throw(ArgumentError(\"Works only for square Hilbert matrices.\"))\n return InverseHilbert(T,H.n)\nend\nfunction inv(A::InverseHilbert{T}) where {T}\n HT = promote_type(T,typeof(Rational(one(T))))\n return Hilbert(HT,A.n)\nend\n", "meta": {"hexsha": "82783b0d885f238ddbb83e30d26c664d236fc4ed", "size": 3131, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/hilbert.jl", "max_stars_repo_name": "JuliaMath/SpecialMatrices.jl", "max_stars_repo_head_hexsha": "05cb35883d25495aec69d6fb8bc7d40460ddcdb8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2018-09-13T10:26:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T23:21:37.000Z", "max_issues_repo_path": "src/hilbert.jl", "max_issues_repo_name": "JuliaMath/SpecialMatrices.jl", "max_issues_repo_head_hexsha": "05cb35883d25495aec69d6fb8bc7d40460ddcdb8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 36, "max_issues_repo_issues_event_min_datetime": "2017-08-17T17:39:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-31T18:27:05.000Z", "max_forks_repo_path": "src/hilbert.jl", "max_forks_repo_name": "JuliaMath/SpecialMatrices.jl", "max_forks_repo_head_hexsha": "05cb35883d25495aec69d6fb8bc7d40460ddcdb8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2017-08-17T16:49:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-21T10:22:09.000Z", "avg_line_length": 30.1057692308, "max_line_length": 97, "alphanum_fraction": 0.6100287448, "num_tokens": 1326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465188527684, "lm_q2_score": 0.8633916152464016, "lm_q1q2_score": 0.8075703417273906}} {"text": "using Distributions, Plots, CSV, Pandas\n\n# Sample x_{k+1} given x_k\n# Parameters:\n# - x_k: The kth X sample. One of -1, 0, or 1\n# Outputs:\n# - x_{k+1}: The (k+1)th X sample\nfunction sample_x(xk)\n # Define q parameter\n q = 0.3\n\n # Probability that x_{k+1} = 1\n p = q*(xk == 1) + (1-q)*(xk == 0)\n\n return rand() < p\nend\n\n# Obtains n samples of X based on HMM\n# Inputs\n# - n: An integer representing the number of samples to return\n# Outputs\n# A vector of length n where the kth element is the kth sample of X\nfunction get_x_samples(n)\n # Store x samples\n samples = zeros(n)\n\n # Randomly set x1\n samples[1] = rand(0:1)\n\n # Get samples x_2 through x_n\n for i=2:n\n samples[i] = sample_x(samples[i-1])\n end\n\n return samples\nend\n\n# Obtains n samples of Y based on HMM\n# Inputs\n# - x_samples: A vector of length n representing the samples of X\n# Outputs\n# A vector of length n where the kth element is the kth sample of Y\nfunction get_y_samples(x_samples)\n # Define normal standard deviation\n σ = 1.5\n\n # Store y samples\n n = length(x_samples)\n y_samples = zeros(n)\n\n for i=1:n\n 𝒩 = Normal(x_samples[i], σ)\n y_samples[i] = rand(𝒩)\n end\n\n return y_samples\nend\n\n# Obtian and plot samples\nn = 1500\nx_samples = get_x_samples(n)\ny_samples = get_y_samples(x_samples)\n\nplot(1:n,x_samples, seriestype=:scatter, bg = RGB(247/255, 236/255, 226/255), color = RGB(0,191/255,255/255), label = \"x\", alpha = 0.2)\nplot!(1:n,y_samples, seriestype=:scatter, color = RGB(191/255,1,0), label =\n\"y\", alpha = 0.2)\n\n\ncd(\"/Users/elvis/Documents/DSI/courses/content/stochastic-approximations/images/\")\n\n# Note X and Y variables swapped here from what was presented in example\ndf = DataFrame(Dict(:X=>y_samples))\n\nCSV.write(\"/Users/elvis/Documents/DSI/courses/content/bayesian-inference-and-graphical-models/code/hmm_observations.csv\", df)\n", "meta": {"hexsha": "2f781c3faec4b255c51da930e09abdc229b8419a", "size": 1890, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "content/bayesian-inference-and-graphical-models/code/em_hmm_sample_generation.jl", "max_stars_repo_name": "seanrattana/courses", "max_stars_repo_head_hexsha": "9453abc38af26ea49cb00fe1744066fc0de237b3", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2019-08-21T07:33:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-24T15:46:58.000Z", "max_issues_repo_path": "content/bayesian-inference-and-graphical-models/code/em_hmm_sample_generation.jl", "max_issues_repo_name": "seanrattana/courses", "max_issues_repo_head_hexsha": "9453abc38af26ea49cb00fe1744066fc0de237b3", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-08-23T06:04:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-26T12:47:12.000Z", "max_forks_repo_path": "content/bayesian-inference-and-graphical-models/code/em_hmm_sample_generation.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.2, "max_line_length": 135, "alphanum_fraction": 0.673015873, "num_tokens": 602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465080392797, "lm_q2_score": 0.863391611731321, "lm_q1q2_score": 0.8075703291032966}} {"text": "\"\"\"\n B, T = brun(H)\n\nBrun's integer-relations alg implemented as a matrix decomposition. Takes as\ninput the matrix `H` and returns a reduced basis `B` and `T`, a unimodular\ntransformation matrix such that `B = H*T`. Brun reduction is often done with\n`pinv(H)` as input to yield `B = pinv(H)*T`.\n\nSee V. Brun, \"En generalisation av kjedebrøken I,\" Skr. Vid\nensk. Selsk. Kristiana, Mat. Nat. Klasse, 1919. See\nhttps://archive.org/stream/skrifterutgitavv201chri#page/300/mode/2up\n\nFollows code from D. Wuebben, D. Seethaler, J. Jalden, and G. Matz, \"Lattice\nReduction - A Survey with Applications in Wireless Communications\" IEEE\nSignal Processing Magazine, March 2011\n\n# Examples\n```jldoctest\njulia> H=[1 2; 3 4]; B,T=brun(H); T\n2×2 Array{Int64,2}:\n 3 -1\n -2 1\n\n```\n\"\"\"\nfunction brun(H::AbstractArray{Td,2}) where Td\n\n # get size\n K, M = size(H)\n\n if rank(H) < K\n error(\"Input basis does not have full row rank\")\n end \n\n Ti= getIntType(Td) \n\n grammian = H'*H\n metric_vec = sqrt.(abs.(diag(grammian')))\n mu = grammian[:,1] # initialize mu with an arbitrary column of the Grammian\n T = Matrix{Ti}(I, K, K) # unimodular transformation matrix \n B = copy(H) \n\n doBrun = true\n while doBrun\n\n # Calculation of Brun's update value\n zw,s = findmax(mu)\n zw = copy(mu)\n zw[s] = -typemax(zw[1])\n zw,t = findmax(zw)\n r = round(mu[s]/mu[t])\n \n # basis update\n updated_vec = B[:,s] .- r'*B[:,t]\n \n # if metric can be improved\n updated_norm = norm(updated_vec)\n if updated_norm < metric_vec[s] \n\n # update mu, unimodular and reduced matrices, metric\n mu[s] -= r*mu[t]\n T[:,s] .-= r'*view(T,:,t) #T[:,s] -= r'*T[:,t]\n B[:,s] .= updated_vec\n metric_vec[s] = updated_norm\n\n else\n doBrun = false\n end\n\n end # \n\n return B, T\nend\n", "meta": {"hexsha": "7fb2444e4b52ba631656e069f29a115795de0ef0", "size": 1941, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/brun.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/LLLplus.jl-142c1900-a1c3-58ae-a66d-b187f9ca6423", "max_stars_repo_head_hexsha": "3541cc4f0c1c4409620e871947d313c88787a56d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/brun.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/LLLplus.jl-142c1900-a1c3-58ae-a66d-b187f9ca6423", "max_issues_repo_head_hexsha": "3541cc4f0c1c4409620e871947d313c88787a56d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/brun.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/LLLplus.jl-142c1900-a1c3-58ae-a66d-b187f9ca6423", "max_forks_repo_head_hexsha": "3541cc4f0c1c4409620e871947d313c88787a56d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2297297297, "max_line_length": 80, "alphanum_fraction": 0.5888717156, "num_tokens": 610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216356, "lm_q2_score": 0.8688267626522814, "lm_q1q2_score": 0.8075227005190052}} {"text": "using EngEconomics\n\n\nfunction learningCurveModel(T_init, N, b)\n\treturn T_init * N^b\nend\n\nfunction learningCurveModelCoeff(T1, N1, T2, N2)\n\tb = log(T1 / T2) / log(N1 / N2)\nend\n\nfunction learningCurvePercentage(b)\n\treturn exp(b * log(2))\nend\n\n# Given\navgLaborCost = 20 # $/hr\nprodTimeUnit1 = 10 # hrs\nprodTimeUnit4 = 8.1 # hrs\noverheadExpenses = 1.0 * avgLaborCost # Dollars / hr\n\n# Find\n# a.) Learning Curve Model\nTinit = prodTimeUnit1\nT4 = prodTimeUnit4\nb = log(T4 / Tinit) / log(4 / 1)\npercentage = exp(b * log(2))\nb = learningCurveModelCoeff(Tinit, 1, T4, 4)\npercentage = learningCurvePercentage(b)\n", "meta": {"hexsha": "acc33dc98364213f1f5224995784c083fb8be3a6", "size": 601, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problems/ps1/p3.jl", "max_stars_repo_name": "zborffs/EngineeringEconomics.jl", "max_stars_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problems/ps1/p3.jl", "max_issues_repo_name": "zborffs/EngineeringEconomics.jl", "max_issues_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problems/ps1/p3.jl", "max_forks_repo_name": "zborffs/EngineeringEconomics.jl", "max_forks_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0333333333, "max_line_length": 52, "alphanum_fraction": 0.7104825291, "num_tokens": 209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639669551474, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.8075086366844182}} {"text": "### A Pluto.jl notebook ###\n# v0.16.1\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n quote\n local el = $(esc(element))\n global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n el\n end\nend\n\n# ╔═╡ b6681ace-5cb1-49cb-9ed7-e749c7a67428\nusing Distributions, Plots, StatsPlots, PlutoUI\n\n# ╔═╡ a4a73fb0-2213-11ec-02f8-1d2409575d4c\nmd\"\"\" # Bayesian modelling\n\nThree stages to building a model:\n1. Data story: Motivate the model by narrating how the data might arise.\n2. Update: Educate your model by feeding it the data.\n3. Evaluate: evaluate the model, possibly leading to model revision.\n\n### Example: Estimate the proportion of water on earth\n\nSuppose you have a toy model of the Earth. You estimate the proportion of water on the model of Earth (and, if the model is a good one, the proportion of water on the actual Earth) by tossing it into the air and catching it. When you catch it record whether or not your right index finger is on land or water. Repeat this procedure.\n\n\n\n\n###### 1. Data story\nThis story may either be *descriptive* specifying associations that can be used to predict outcomes, or *causal*, a theory of how some events produce other events.\n\nFor Earth example:\n1. The true proportion of the Earth coverd in water is $P$.\n2. A single toss and catch has a probability $p$ of producing a water (W) observation\n3. Each toss of the globe is independent of each other.\n\n###### 2. Update\nUse the data to update the model.\n\nFor Earth example:\n1. Assume all values of $P$ equally likely (the *prior*)\n2. As observed data is binary, use Binomial distribution to find probability of observed data for each possible value of $P$\n3. Update prior probability using Bayes Theorem and the observed data (the *posterior*)\n\nCalculating these probabilities from the PDF's to generate the posterior is almost impossible for more complex examples, so numerical techniques used instead.\n\n###### 3. Evaluate\nThe Bayesian model learns in a way that is demonstrably optimal. However this is only the performance of the model (the \"small world\") if the assumptions of the model do not match reality then the \"large world\" performance will not be good.\n\nThe objective is to check the model's adequacy for you purpose e.g. prediction, comprehension, measurement.\n\n\n\"\"\"\n\n# ╔═╡ 4dcf2480-7a37-4236-b51b-a171407bd8a0\nmd\"\"\"\n#### Constructing the model\n\"\"\"\n\n# ╔═╡ e044742f-15dd-42e1-9271-43f11c7e2785\nbegin \n\tN = 9 # number of trials\n\tS = 6 # number of success (water)\nend\n\n# ╔═╡ c2d41bee-4952-429b-b3d8-aea46eefd2c4\nmd\"\"\"\nGiven the outcome of our experiment can be one of two options (W or L) with a fixed probability $p$ and each toss is independent (these come from the assumptions/data story), the probability of a single toss being W can be described by a binomial distribution:\n\n``W\\sim Binomial(N,p)``\n\n\n\"\"\"\n\n# ╔═╡ ef92132a-211d-4e8f-8ab2-12ae2c4a9c49\nmd\"\"\"\nInitially we don't know what the parameter $P$ is, so assume all values equally likely, i.e. a uniform distribution between 0 and 1 (0% to 100% covered in water):\n\n``P\\sim Uniform(0,1)``\n\"\"\"\n\n# ╔═╡ e2b04571-e4e5-49fe-823d-af0404eceab7\nP = Uniform(0,1);\n\n# ╔═╡ e2bb3b47-1973-4d40-91f2-a703470d1a6a\nbegin\n\tplot(P, lw=2, legend=:none, title=\"prior distribution of P\", ylims=(0,1.2))\n\t#plot!([0.0 1.0; 0.0 1.0],[0.0 0.0; 1.0 1.0], color=1)\nend\n\n# ╔═╡ 8f3de7b2-2fa3-4aa3-ba81-243aa4722a3a\nmd\"\"\"#### Update the model with data\n\nThe model gets updated (the posterior is generated) using Bayes theorem:\n\n``Pr(p\\mid W,L) = \\frac{Pr(W,L\\mid p)Pr(p)}{Pr(W,L)}``\n\nAnalytical this would give a posterior probability density function, but using grid approximation the values given are probabilities (masses):\n\"\"\"\n\n# ╔═╡ d142a6c3-e11c-44b5-930f-16deae98e74f\n@bind n Slider(5:100, default=100) # fine-ness of the grid\n\n# ╔═╡ 1a193ab0-10b0-447d-a68a-0fc978c6e804\nmd\"\"\"n = $n\"\"\"\n\n# ╔═╡ 33fc930d-8693-41f9-8614-dc71870bd56d\nbegin\n\tgrid = range(0,1,length=n) # possible values for P\n\tprior = @. pdf(Uniform(0,1), grid) # prior\n\tlikelihood = @. pdf(Binomial(N,grid), S) # probability of observed data for diff P\n\tposterior = likelihood .* prior # unnormalised posterior distribution\n\tposterior /= sum(posterior) \t# normalise posterior to sum to one -> probability\nend;\n\n# ╔═╡ 4d10cc40-213e-4c4e-bea8-ea318aee18f7\nbegin\n\tplot(grid, posterior, markershape=:circle, mc=:white, msc=1, legend=:none, \t\ttitle=\"posterior distribution\", annotations=(0.8,0.5,\" $(round(grid[argmax(posterior)], digits=3))\"), ylims=(0,0.6))\n\tvline!([grid[argmax(posterior)]], color=1, ls=:dash)\nend\n\n# ╔═╡ 9149e9e5-b0b9-4c22-8795-d982a3cacf6a\nmd\"\"\"##### Collecting new data\"\"\"\n\n# ╔═╡ 361b07cc-6554-40d1-9448-6f4e4cd4bb71\n@bind Nnew Slider(1:100, default=9)\n\n# ╔═╡ af901869-37bf-4992-bfc3-ee8477a37b34\nmd\"\"\"Number of tosses: $Nnew\"\"\"\n\n# ╔═╡ e82146d1-ea29-40a3-b89f-5d178f4a900a\n@bind Snew Slider(0:Nnew, default=6)\n\n# ╔═╡ 2161be7c-571e-46c9-b3c2-0543d5e3296f\nmd\"\"\"Number of tosses on water $Snew\"\"\"\n\n# ╔═╡ da10276c-1381-4edb-9171-1ec0820a1809\nlet\n\tn = 500\n\tgrid = range(0,1,length=n) # possible values for P\n\tprior = repeat([1],n) # relative priors\n\tlikelihood = @. pdf(Binomial(Nnew,grid), Snew) # probability of S successes\n\tposterior = likelihood .* prior |> x -> x/sum(x) # posterior distribution\n\tplot(grid, posterior, lw=2, legend=:none, title=\"posterior distribution\", ylims=(0,0.04))\nend\n\n# ╔═╡ b8e49bec-d582-4695-b7ac-6b0ccbca5e08\nmd\"\"\"##### Trying out different priors (using original data)\"\"\"\n\n# ╔═╡ 2cccdace-62df-4771-aaa4-1dd4342335e4\nmd\"\"\"###### Step prior\n```prior = [zeros(n÷2)..., ones(n÷2)...]```\n\"\"\"\n\n# ╔═╡ a673dd91-ccdf-4783-8b24-357a7307d7d3\nlet\n\tn = 500\n\tgrid = range(0,1,length=n) # possible values for P\n\tprior = [zeros(n÷2)..., ones(n÷2)...] \n\tlikelihood = @. pdf(Binomial(Nnew,grid), Snew) # probability of S successes\n\tposterior = likelihood .* prior |> x -> x/sum(x) # posterior distribution\n\tp1 = plot(grid, prior, lw=2, legend=:none, title=\"prior distribution\")\n\tp2 = plot(grid, posterior, lw=2, legend=:none, title=\"posterior distribution\", ylims=(0,0.04))\n\tplot(p1,p2, layout=(1,2))\nend\n\n# ╔═╡ 3a34068e-4fed-40c3-89ef-2aabafb5144e\nmd\"\"\"###### Exponential prior\n```prior = exp.(-5*abs.(collect(grid).-0.5) ) ```\n\"\"\"\n\n# ╔═╡ 9c599a59-96f7-4b2c-b690-13750a14eef8\nlet\n\tn = 500\n\tgrid = range(0,1,length=n) # possible values for P\n\tprior = exp.(-5*abs.(collect(grid).-0.5) ) \n\tlikelihood = @. pdf(Binomial(Nnew,grid), Snew) # probability of S successes\n\tposterior = likelihood .* prior |> x -> x/sum(x) # posterior distribution\n\tp1 = plot(grid, prior, lw=2, legend=:none, title=\"prior distribution\")\n\tp2 = plot(grid, posterior, lw=2, legend=:none, title=\"posterior distribution\", ylims=(0,0.04))\n\tplot(p1,p2, layout=(1,2))\nend\n\n# ╔═╡ ffc34a30-9dba-40d0-afca-2279f4753661\nmd\"\"\"### Practice problems\"\"\"\n\n# ╔═╡ a70c520f-860f-48be-a1a6-e87607298c37\nmd\"\"\" #### 2H1\n\n##### Question\nSuppose there are two species of panda, identical in every way except family sizes. Species A gives birth to twins 10% of the time, otherwise a single infant. Species B gives birth to twins 20% of the time, otherwise a single infant.\n\nYou have a new panda of unknown species just given birth to twins, what is the probability the next birth will also be twins?\n\n##### Solution\n\n1. Construct data story\n\nNeed to find probability of new panda being species A or B. The probability of next birth being twins will then be: \n\n``Pr(A)*Pr(twins \\mid A) + Pr(B)*Pr(twins \\mid B)``\n\nSpecies distribution:\n- Assume prior to be equally likely for both species.\n- Model outcome with binomial distribution: ``T \\sim Binomial(2,p)`` where ``p = 0.1`` if species A or ``p = 0.2`` if species B.\n\"\"\"\n\n# ╔═╡ 8c493e53-bb7b-4110-a732-1cf93ecb754b\nlet\n\tN = 1\n\tS = 1\n\tgrid = [0.1, 0.2]\n\tprior = [1, 1]\n\tlikelihood = @. pdf(Binomial(N,grid), S)\n\tposterior = posterior = likelihood .* prior |> x -> x/sum(x)\n\tp = posterior .* grid |> sum\n\tmd\"\"\"**Probability of next birth being twins = $p**\"\"\"\nend\n\n# ╔═╡ 9908c97f-efb4-4634-aa97-9b4d2f9d7acc\nmd\"\"\" #### 2H2\n\n##### Question\n\nSame as above, compute probability that the new panda is of species A given that the first birth was twins.\n\n##### Answer\n\nWant to find ``Pr(A \\mid twins)`` which is reverse of ``Pr(twins \\mid A)`` which has probability 0.1. Therefore use Bayes Theorem:\n\n``Pr(A \\mid twins) = \\frac{Pr(twins \\mid A)*Pr(A)}{Pr(twins)}``\n\n\n\"\"\"\n\n# ╔═╡ d690e1d2-654c-4da4-9255-d3871429d262\nlet\n\tp_twins_A = 0.1\n\tp_A = 0.5 # assuming equally likely\n\tp_twins = p_A*0.1 + (1-p_A)*0.2\n\tp_A_twins = (p_twins_A * p_A) / p_twins\n\tmd\"\"\"**Probability of being species A given twins = $(p_A_twins)**\"\"\"\nend\n\n# ╔═╡ ee5bfc95-bbb0-4d1b-8a83-77e884171f05\nmd\"\"\" #### 2H3\n\n##### Question\n\nSame as above, the new panda next gives birth to a single infant. Compute probability that she is of species A.\n\n##### Solution\n\nUse posterior distribution from 2H1 which gives probabilities after first birth of twins as the prior and generate new posterior given new birth of not twins.\n\n\n\"\"\"\n\n# ╔═╡ b7033638-277e-4610-89ef-3abe33ef35bf\nlet\n\tN = 1\n\tS = 0\n\tgrid = [0.1, 0.2]\n\tprior = [1, 2] # from 2H1\n\tlikelihood = @. pdf(Binomial(N, grid), S) # probability of observing data given p\n\tposterior = likelihood .* prior |> x -> x ./ sum(x)\n\tmd\"\"\"**Probability of being species A given second birth of twins = $(posterior[1])**\"\"\"\nend\n\t\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nDistributions = \"31c24e10-a181-5473-b8eb-7969acd0382f\"\nPlots = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nPlutoUI = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nStatsPlots = \"f3b207a7-027a-5e70-b257-86293d7955fd\"\n\n[compat]\nDistributions = \"~0.25.17\"\nPlots = \"~1.22.3\"\nPlutoUI = \"~0.7.14\"\nStatsPlots = \"~0.14.28\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\n[[AbstractFFTs]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"485ee0867925449198280d4af84bdb46a2a404d0\"\nuuid = \"621f4979-c628-5d54-868e-fcf4e3e8185c\"\nversion = \"1.0.1\"\n\n[[Adapt]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"84918055d15b3114ede17ac6a7182f68870c16f7\"\nuuid = \"79e6a3ab-5dfb-504d-930d-738a2a938a0e\"\nversion = \"3.3.1\"\n\n[[ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[Arpack]]\ndeps = [\"Arpack_jll\", \"Libdl\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"2ff92b71ba1747c5fdd541f8fc87736d82f40ec9\"\nuuid = \"7d9fca2a-8960-54d3-9f78-7d1dccf2cb97\"\nversion = \"0.4.0\"\n\n[[Arpack_jll]]\ndeps = [\"Libdl\", \"OpenBLAS_jll\", \"Pkg\"]\ngit-tree-sha1 = \"e214a9b9bd1b4e1b4f15b22c0994862b66af7ff7\"\nuuid = \"68821587-b530-5797-8361-c406ea357684\"\nversion = \"3.5.0+3\"\n\n[[Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[AxisAlgorithms]]\ndeps = [\"LinearAlgebra\", \"Random\", \"SparseArrays\", \"WoodburyMatrices\"]\ngit-tree-sha1 = \"a4d07a1c313392a77042855df46c5f534076fab9\"\nuuid = \"13072b0f-2c55-5437-9ae7-d433b7a33950\"\nversion = \"1.0.0\"\n\n[[Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[Bzip2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"19a35467a82e236ff51bc17a3a44b69ef35185a2\"\nuuid = \"6e34b625-4abd-537c-b88f-471c36dfa7a0\"\nversion = \"1.0.8+0\"\n\n[[Cairo_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"JLLWrappers\", \"LZO_jll\", \"Libdl\", \"Pixman_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"f2202b55d816427cd385a9a4f3ffb226bee80f99\"\nuuid = \"83423d85-b0ee-5818-9007-b63ccbeb887a\"\nversion = \"1.16.1+0\"\n\n[[ChainRulesCore]]\ndeps = [\"Compat\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"1417269aa4238b85967827f11f3e0ce5722b7bf0\"\nuuid = \"d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4\"\nversion = \"1.7.1\"\n\n[[Clustering]]\ndeps = [\"Distances\", \"LinearAlgebra\", \"NearestNeighbors\", \"Printf\", \"SparseArrays\", \"Statistics\", \"StatsBase\"]\ngit-tree-sha1 = \"75479b7df4167267d75294d14b58244695beb2ac\"\nuuid = \"aaaa29a8-35af-508c-8bc3-b662a17a0fe5\"\nversion = \"0.14.2\"\n\n[[ColorSchemes]]\ndeps = [\"ColorTypes\", \"Colors\", \"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"a851fec56cb73cfdf43762999ec72eff5b86882a\"\nuuid = \"35d6a980-a343-548e-a6ea-1d62b119f2f4\"\nversion = \"3.15.0\"\n\n[[ColorTypes]]\ndeps = [\"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"024fe24d83e4a5bf5fc80501a314ce0d1aa35597\"\nuuid = \"3da002f7-5984-5a60-b8a6-cbb66c0b333f\"\nversion = \"0.11.0\"\n\n[[Colors]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"Reexport\"]\ngit-tree-sha1 = \"417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40\"\nuuid = \"5ae59095-9a9b-59fe-a467-6f913c188581\"\nversion = \"0.12.8\"\n\n[[Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"31d0151f5716b655421d9d75b7fa74cc4e744df2\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.39.0\"\n\n[[CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[Contour]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"9f02045d934dc030edad45944ea80dbd1f0ebea7\"\nuuid = \"d38c429a-6771-53c6-b99e-75d170b6e991\"\nversion = \"0.5.7\"\n\n[[DataAPI]]\ngit-tree-sha1 = \"cc70b17275652eb47bc9e5f81635981f13cea5c8\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.9.0\"\n\n[[DataStructures]]\ndeps = [\"Compat\", \"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"7d9d316f04214f7efdbb6398d545446e246eff02\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.18.10\"\n\n[[DataValueInterfaces]]\ngit-tree-sha1 = \"bfc1187b79289637fa0ef6d4436ebdfe6905cbd6\"\nuuid = \"e2d170a0-9d28-54be-80f0-106bbe20a464\"\nversion = \"1.0.0\"\n\n[[DataValues]]\ndeps = [\"DataValueInterfaces\", \"Dates\"]\ngit-tree-sha1 = \"d88a19299eba280a6d062e135a43f00323ae70bf\"\nuuid = \"e7dc6d0d-1eca-5fa6-8ad6-5aecde8b7ea5\"\nversion = \"0.4.13\"\n\n[[Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[Distances]]\ndeps = [\"LinearAlgebra\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"9f46deb4d4ee4494ffb5a40a27a2aced67bdd838\"\nuuid = \"b4f34e82-e78d-54a5-968a-f98e89d6e8f7\"\nversion = \"0.10.4\"\n\n[[Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[Distributions]]\ndeps = [\"ChainRulesCore\", \"FillArrays\", \"LinearAlgebra\", \"PDMats\", \"Printf\", \"QuadGK\", \"Random\", \"SparseArrays\", \"SpecialFunctions\", \"Statistics\", \"StatsBase\", \"StatsFuns\"]\ngit-tree-sha1 = \"a9b99024b57d12fb19892d3f2230856f6d9671a4\"\nuuid = \"31c24e10-a181-5473-b8eb-7969acd0382f\"\nversion = \"0.25.17\"\n\n[[DocStringExtensions]]\ndeps = [\"LibGit2\"]\ngit-tree-sha1 = \"a32185f5428d3986f47c2ab78b1f216d5e6cc96f\"\nuuid = \"ffbed154-4ef7-542d-bbb7-c09d3a79fcae\"\nversion = \"0.8.5\"\n\n[[Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[EarCut_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"3f3a2501fa7236e9b911e0f7a588c657e822bb6d\"\nuuid = \"5ae413db-bbd1-5e63-b57d-d24a61df00f5\"\nversion = \"2.2.3+0\"\n\n[[Expat_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b3bfd02e98aedfa5cf885665493c5598c350cd2f\"\nuuid = \"2e619515-83b5-522b-bb60-26c02a35a201\"\nversion = \"2.2.10+0\"\n\n[[FFMPEG]]\ndeps = [\"FFMPEG_jll\"]\ngit-tree-sha1 = \"b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8\"\nuuid = \"c87230d0-a227-11e9-1b43-d7ebe4e7570a\"\nversion = \"0.4.1\"\n\n[[FFMPEG_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"JLLWrappers\", \"LAME_jll\", \"Libdl\", \"Ogg_jll\", \"OpenSSL_jll\", \"Opus_jll\", \"Pkg\", \"Zlib_jll\", \"libass_jll\", \"libfdk_aac_jll\", \"libvorbis_jll\", \"x264_jll\", \"x265_jll\"]\ngit-tree-sha1 = \"d8a578692e3077ac998b50c0217dfd67f21d1e5f\"\nuuid = \"b22a6f82-2f65-5046-a5b2-351ab43fb4e5\"\nversion = \"4.4.0+0\"\n\n[[FFTW]]\ndeps = [\"AbstractFFTs\", \"FFTW_jll\", \"LinearAlgebra\", \"MKL_jll\", \"Preferences\", \"Reexport\"]\ngit-tree-sha1 = \"463cb335fa22c4ebacfd1faba5fde14edb80d96c\"\nuuid = \"7a1cc6ca-52ef-59f5-83cd-3a7055c09341\"\nversion = \"1.4.5\"\n\n[[FFTW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c6033cc3892d0ef5bb9cd29b7f2f0331ea5184ea\"\nuuid = \"f5851436-0d7a-5f13-b9de-f02708fd171a\"\nversion = \"3.3.10+0\"\n\n[[FillArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"SparseArrays\", \"Statistics\"]\ngit-tree-sha1 = \"29890dfbc427afa59598b8cfcc10034719bd7744\"\nuuid = \"1a297f60-69ca-5386-bcde-b61e274b549b\"\nversion = \"0.12.6\"\n\n[[FixedPointNumbers]]\ndeps = [\"Statistics\"]\ngit-tree-sha1 = \"335bfdceacc84c5cdf16aadc768aa5ddfc5383cc\"\nuuid = \"53c48c17-4a7d-5ca2-90c5-79b7896eea93\"\nversion = \"0.8.4\"\n\n[[Fontconfig_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Expat_jll\", \"FreeType2_jll\", \"JLLWrappers\", \"Libdl\", \"Libuuid_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"21efd19106a55620a188615da6d3d06cd7f6ee03\"\nuuid = \"a3f928ae-7b40-5064-980b-68af3947d34b\"\nversion = \"2.13.93+0\"\n\n[[Formatting]]\ndeps = [\"Printf\"]\ngit-tree-sha1 = \"8339d61043228fdd3eb658d86c926cb282ae72a8\"\nuuid = \"59287772-0a20-5a39-b81b-1366585eb4c0\"\nversion = \"0.4.2\"\n\n[[FreeType2_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"87eb71354d8ec1a96d4a7636bd57a7347dde3ef9\"\nuuid = \"d7e528f0-a631-5988-bf34-fe36492bcfd7\"\nversion = \"2.10.4+0\"\n\n[[FriBidi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"aa31987c2ba8704e23c6c8ba8a4f769d5d7e4f91\"\nuuid = \"559328eb-81f9-559d-9380-de523a88c83c\"\nversion = \"1.0.10+0\"\n\n[[GLFW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"Pkg\", \"Xorg_libXcursor_jll\", \"Xorg_libXi_jll\", \"Xorg_libXinerama_jll\", \"Xorg_libXrandr_jll\"]\ngit-tree-sha1 = \"dba1e8614e98949abfa60480b13653813d8f0157\"\nuuid = \"0656b61e-2033-5cc2-a64a-77c0f6c09b89\"\nversion = \"3.3.5+0\"\n\n[[GR]]\ndeps = [\"Base64\", \"DelimitedFiles\", \"GR_jll\", \"HTTP\", \"JSON\", \"Libdl\", \"LinearAlgebra\", \"Pkg\", \"Printf\", \"Random\", \"Serialization\", \"Sockets\", \"Test\", \"UUIDs\"]\ngit-tree-sha1 = \"c2178cfbc0a5a552e16d097fae508f2024de61a3\"\nuuid = \"28b8d3ca-fb5f-59d9-8090-bfdbd6d07a71\"\nversion = \"0.59.0\"\n\n[[GR_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Cairo_jll\", \"FFMPEG_jll\", \"Fontconfig_jll\", \"GLFW_jll\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Libtiff_jll\", \"Pixman_jll\", \"Pkg\", \"Qt5Base_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"ef49a187604f865f4708c90e3f431890724e9012\"\nuuid = \"d2c73de3-f751-5644-a686-071e5b155ba9\"\nversion = \"0.59.0+0\"\n\n[[GeometryBasics]]\ndeps = [\"EarCut_jll\", \"IterTools\", \"LinearAlgebra\", \"StaticArrays\", \"StructArrays\", \"Tables\"]\ngit-tree-sha1 = \"58bcdf5ebc057b085e58d95c138725628dd7453c\"\nuuid = \"5c1252a2-5f33-56bf-86c9-59e7332b4326\"\nversion = \"0.4.1\"\n\n[[Gettext_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"9b02998aba7bf074d14de89f9d37ca24a1a0b046\"\nuuid = \"78b55507-aeef-58d4-861c-77aaff3498b1\"\nversion = \"0.21.0+0\"\n\n[[Glib_jll]]\ndeps = [\"Artifacts\", \"Gettext_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Libiconv_jll\", \"Libmount_jll\", \"PCRE_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"7bf67e9a481712b3dbe9cb3dac852dc4b1162e02\"\nuuid = \"7746bdde-850d-59dc-9ae8-88ece973131d\"\nversion = \"2.68.3+0\"\n\n[[Graphite2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"344bf40dcab1073aca04aa0df4fb092f920e4011\"\nuuid = \"3b182d85-2403-5c21-9c21-1e1f0cc25472\"\nversion = \"1.3.14+0\"\n\n[[Grisu]]\ngit-tree-sha1 = \"53bb909d1151e57e2484c3d1b53e19552b887fb2\"\nuuid = \"42e2da0e-8278-4e71-bc24-59509adca0fe\"\nversion = \"1.0.2\"\n\n[[HTTP]]\ndeps = [\"Base64\", \"Dates\", \"IniFile\", \"Logging\", \"MbedTLS\", \"NetworkOptions\", \"Sockets\", \"URIs\"]\ngit-tree-sha1 = \"14eece7a3308b4d8be910e265c724a6ba51a9798\"\nuuid = \"cd3eb016-35fb-5094-929b-558a96fad6f3\"\nversion = \"0.9.16\"\n\n[[HarfBuzz_jll]]\ndeps = [\"Artifacts\", \"Cairo_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"Graphite2_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\"]\ngit-tree-sha1 = \"8a954fed8ac097d5be04921d595f741115c1b2ad\"\nuuid = \"2e76f6c2-a576-52d4-95c1-20adfe4de566\"\nversion = \"2.8.1+0\"\n\n[[HypertextLiteral]]\ngit-tree-sha1 = \"72053798e1be56026b81d4e2682dbe58922e5ec9\"\nuuid = \"ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2\"\nversion = \"0.9.0\"\n\n[[IOCapture]]\ndeps = [\"Logging\", \"Random\"]\ngit-tree-sha1 = \"f7be53659ab06ddc986428d3a9dcc95f6fa6705a\"\nuuid = \"b5f81e59-6552-4d32-b1f0-c071b021bf89\"\nversion = \"0.2.2\"\n\n[[IniFile]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"098e4d2c533924c921f9f9847274f2ad89e018b8\"\nuuid = \"83e8ac13-25f8-5344-8a64-a9f2b223428f\"\nversion = \"0.5.0\"\n\n[[IntelOpenMP_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d979e54b71da82f3a65b62553da4fc3d18c9004c\"\nuuid = \"1d5cc7b8-4909-519e-a0f8-d0f5ad9712d0\"\nversion = \"2018.0.3+2\"\n\n[[InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[Interpolations]]\ndeps = [\"AxisAlgorithms\", \"ChainRulesCore\", \"LinearAlgebra\", \"OffsetArrays\", \"Random\", \"Ratios\", \"Requires\", \"SharedArrays\", \"SparseArrays\", \"StaticArrays\", \"WoodburyMatrices\"]\ngit-tree-sha1 = \"61aa005707ea2cebf47c8d780da8dc9bc4e0c512\"\nuuid = \"a98d9a8b-a2ab-59e6-89dd-64a1c18fca59\"\nversion = \"0.13.4\"\n\n[[IrrationalConstants]]\ngit-tree-sha1 = \"f76424439413893a832026ca355fe273e93bce94\"\nuuid = \"92d709cd-6900-40b7-9082-c6be49f344b6\"\nversion = \"0.1.0\"\n\n[[IterTools]]\ngit-tree-sha1 = \"05110a2ab1fc5f932622ffea2a003221f4782c18\"\nuuid = \"c8e1da08-722c-5040-9ed9-7db0dc04731e\"\nversion = \"1.3.0\"\n\n[[IteratorInterfaceExtensions]]\ngit-tree-sha1 = \"a3f24677c21f5bbe9d2a714f95dcd58337fb2856\"\nuuid = \"82899510-4779-5014-852e-03e436cf321d\"\nversion = \"1.0.0\"\n\n[[JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"642a199af8b68253517b80bd3bfd17eb4e84df6e\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.3.0\"\n\n[[JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"8076680b162ada2a031f707ac7b4953e30667a37\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.2\"\n\n[[JpegTurbo_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d735490ac75c5cb9f1b00d8b5509c11984dc6943\"\nuuid = \"aacddb02-875f-59d6-b918-886e6ef4fbf8\"\nversion = \"2.1.0+0\"\n\n[[KernelDensity]]\ndeps = [\"Distributions\", \"DocStringExtensions\", \"FFTW\", \"Interpolations\", \"StatsBase\"]\ngit-tree-sha1 = \"591e8dc09ad18386189610acafb970032c519707\"\nuuid = \"5ab0869b-81aa-558d-bb23-cbf5423bbe9b\"\nversion = \"0.6.3\"\n\n[[LAME_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"f6250b16881adf048549549fba48b1161acdac8c\"\nuuid = \"c1c5ebd0-6772-5130-a774-d5fcae4a789d\"\nversion = \"3.100.1+0\"\n\n[[LZO_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e5b909bcf985c5e2605737d2ce278ed791b89be6\"\nuuid = \"dd4b983a-f0e5-5f8d-a1b7-129d4a5fb1ac\"\nversion = \"2.10.1+0\"\n\n[[LaTeXStrings]]\ngit-tree-sha1 = \"c7f1c695e06c01b95a67f0cd1d34994f3e7db104\"\nuuid = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nversion = \"1.2.1\"\n\n[[Latexify]]\ndeps = [\"Formatting\", \"InteractiveUtils\", \"LaTeXStrings\", \"MacroTools\", \"Markdown\", \"Printf\", \"Requires\"]\ngit-tree-sha1 = \"a4b12a1bd2ebade87891ab7e36fdbce582301a92\"\nuuid = \"23fbe1c1-3f47-55db-b15f-69d7ec21a316\"\nversion = \"0.15.6\"\n\n[[LazyArtifacts]]\ndeps = [\"Artifacts\", \"Pkg\"]\nuuid = \"4af54fe1-eca0-43a8-85a7-787d91b784e3\"\n\n[[LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[Libffi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"761a393aeccd6aa92ec3515e428c26bf99575b3b\"\nuuid = \"e9f186c6-92d2-5b65-8a66-fee21dc1b490\"\nversion = \"3.2.2+0\"\n\n[[Libgcrypt_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgpg_error_jll\", \"Pkg\"]\ngit-tree-sha1 = \"64613c82a59c120435c067c2b809fc61cf5166ae\"\nuuid = \"d4300ac3-e22c-5743-9152-c294e39db1e4\"\nversion = \"1.8.7+0\"\n\n[[Libglvnd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"7739f837d6447403596a75d19ed01fd08d6f56bf\"\nuuid = \"7e76a0d4-f3c7-5321-8279-8d96eeed0f29\"\nversion = \"1.3.0+3\"\n\n[[Libgpg_error_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c333716e46366857753e273ce6a69ee0945a6db9\"\nuuid = \"7add5ba3-2f88-524e-9cd5-f83b8a55f7b8\"\nversion = \"1.42.0+0\"\n\n[[Libiconv_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"42b62845d70a619f063a7da093d995ec8e15e778\"\nuuid = \"94ce4f54-9a6c-5748-9c1c-f9c7231a4531\"\nversion = \"1.16.1+1\"\n\n[[Libmount_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"9c30530bf0effd46e15e0fdcf2b8636e78cbbd73\"\nuuid = \"4b2f31a3-9ecc-558c-b454-b3730dcb73e9\"\nversion = \"2.35.0+0\"\n\n[[Libtiff_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Pkg\", \"Zlib_jll\", \"Zstd_jll\"]\ngit-tree-sha1 = \"340e257aada13f95f98ee352d316c3bed37c8ab9\"\nuuid = \"89763e89-9b03-5906-acba-b20f662cd828\"\nversion = \"4.3.0+0\"\n\n[[Libuuid_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7f3efec06033682db852f8b3bc3c1d2b0a0ab066\"\nuuid = \"38a345b3-de98-5d2b-a5d3-14cd9215e700\"\nversion = \"2.36.0+0\"\n\n[[LinearAlgebra]]\ndeps = [\"Libdl\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[LogExpFunctions]]\ndeps = [\"ChainRulesCore\", \"DocStringExtensions\", \"IrrationalConstants\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"34dc30f868e368f8a17b728a1238f3fcda43931a\"\nuuid = \"2ab3a3ac-af41-5b50-aa03-7779005ae688\"\nversion = \"0.3.3\"\n\n[[Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[MKL_jll]]\ndeps = [\"Artifacts\", \"IntelOpenMP_jll\", \"JLLWrappers\", \"LazyArtifacts\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"5455aef09b40e5020e1520f551fa3135040d4ed0\"\nuuid = \"856f044c-d86e-5d09-b602-aeab76dc8ba7\"\nversion = \"2021.1.1+2\"\n\n[[MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"5a5bc6bf062f0f95e62d0fe0a2d99699fed82dd9\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.8\"\n\n[[Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[MbedTLS]]\ndeps = [\"Dates\", \"MbedTLS_jll\", \"Random\", \"Sockets\"]\ngit-tree-sha1 = \"1c38e51c3d08ef2278062ebceade0e46cefc96fe\"\nuuid = \"739be429-bea8-5141-9913-cc70e7f3736d\"\nversion = \"1.0.3\"\n\n[[MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[Measures]]\ngit-tree-sha1 = \"e498ddeee6f9fdb4551ce855a46f54dbd900245f\"\nuuid = \"442fdcdd-2543-5da2-b0f3-8c86c306513e\"\nversion = \"0.3.1\"\n\n[[Missings]]\ndeps = [\"DataAPI\"]\ngit-tree-sha1 = \"bf210ce90b6c9eed32d25dbcae1ebc565df2687f\"\nuuid = \"e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28\"\nversion = \"1.0.2\"\n\n[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[MultivariateStats]]\ndeps = [\"Arpack\", \"LinearAlgebra\", \"SparseArrays\", \"Statistics\", \"StatsBase\"]\ngit-tree-sha1 = \"8d958ff1854b166003238fe191ec34b9d592860a\"\nuuid = \"6f286f6a-111f-5878-ab1e-185364afe411\"\nversion = \"0.8.0\"\n\n[[NaNMath]]\ngit-tree-sha1 = \"bfe47e760d60b82b66b61d2d44128b62e3a369fb\"\nuuid = \"77ba4419-2d1f-58cd-9bb1-8ffee604a2e3\"\nversion = \"0.3.5\"\n\n[[NearestNeighbors]]\ndeps = [\"Distances\", \"StaticArrays\"]\ngit-tree-sha1 = \"16baacfdc8758bc374882566c9187e785e85c2f0\"\nuuid = \"b8a86587-4115-5ab1-83bc-aa920d37bbce\"\nversion = \"0.4.9\"\n\n[[NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[Observables]]\ngit-tree-sha1 = \"fe29afdef3d0c4a8286128d4e45cc50621b1e43d\"\nuuid = \"510215fc-4207-5dde-b226-833fc4488ee2\"\nversion = \"0.4.0\"\n\n[[OffsetArrays]]\ndeps = [\"Adapt\"]\ngit-tree-sha1 = \"c0e9e582987d36d5a61e650e6e543b9e44d9914b\"\nuuid = \"6fe1bfb0-de20-5000-8ca7-80f57d26f881\"\nversion = \"1.10.7\"\n\n[[Ogg_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7937eda4681660b4d6aeeecc2f7e1c81c8ee4e2f\"\nuuid = \"e7412a2a-1a6e-54c0-be00-318e2571c051\"\nversion = \"1.3.5+0\"\n\n[[OpenBLAS_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Libdl\"]\nuuid = \"4536629a-c528-5b80-bd46-f80d51c5b363\"\n\n[[OpenLibm_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"05823500-19ac-5b8b-9628-191a04bc5112\"\n\n[[OpenSSL_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"15003dcb7d8db3c6c857fda14891a539a8f2705a\"\nuuid = \"458c3c95-2e84-50aa-8efc-19380b2a3a95\"\nversion = \"1.1.10+0\"\n\n[[OpenSpecFun_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"13652491f6856acfd2db29360e1bbcd4565d04f1\"\nuuid = \"efe28fd5-8261-553b-a9e1-b2916fc3738e\"\nversion = \"0.5.5+0\"\n\n[[Opus_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"51a08fb14ec28da2ec7a927c4337e4332c2a4720\"\nuuid = \"91d4177d-7536-5919-b921-800302f37372\"\nversion = \"1.3.2+0\"\n\n[[OrderedCollections]]\ngit-tree-sha1 = \"85f8e6578bf1f9ee0d11e7bb1b1456435479d47c\"\nuuid = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nversion = \"1.4.1\"\n\n[[PCRE_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b2a7af664e098055a7529ad1a900ded962bca488\"\nuuid = \"2f80f16e-611a-54ab-bc61-aa92de5b98fc\"\nversion = \"8.44.0+0\"\n\n[[PDMats]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\", \"SuiteSparse\"]\ngit-tree-sha1 = \"4dd403333bcf0909341cfe57ec115152f937d7d8\"\nuuid = \"90014a1f-27ba-587c-ab20-58faa44d9150\"\nversion = \"0.11.1\"\n\n[[Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"a8709b968a1ea6abc2dc1967cb1db6ac9a00dfb6\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.0.5\"\n\n[[Pixman_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b4f5d02549a10e20780a24fce72bea96b6329e29\"\nuuid = \"30392449-352a-5448-841d-b1acce4e97dc\"\nversion = \"0.40.1+0\"\n\n[[Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[PlotThemes]]\ndeps = [\"PlotUtils\", \"Requires\", \"Statistics\"]\ngit-tree-sha1 = \"a3a964ce9dc7898193536002a6dd892b1b5a6f1d\"\nuuid = \"ccf2f8ad-2431-5c83-bf29-c5338b663b6a\"\nversion = \"2.0.1\"\n\n[[PlotUtils]]\ndeps = [\"ColorSchemes\", \"Colors\", \"Dates\", \"Printf\", \"Random\", \"Reexport\", \"Statistics\"]\ngit-tree-sha1 = \"2537ed3c0ed5e03896927187f5f2ee6a4ab342db\"\nuuid = \"995b91a9-d308-5afd-9ec6-746e21dbc043\"\nversion = \"1.0.14\"\n\n[[Plots]]\ndeps = [\"Base64\", \"Contour\", \"Dates\", \"Downloads\", \"FFMPEG\", \"FixedPointNumbers\", \"GR\", \"GeometryBasics\", \"JSON\", \"Latexify\", \"LinearAlgebra\", \"Measures\", \"NaNMath\", \"PlotThemes\", \"PlotUtils\", \"Printf\", \"REPL\", \"Random\", \"RecipesBase\", \"RecipesPipeline\", \"Reexport\", \"Requires\", \"Scratch\", \"Showoff\", \"SparseArrays\", \"Statistics\", \"StatsBase\", \"UUIDs\"]\ngit-tree-sha1 = \"cfbd033def161db9494f86c5d18fbf874e09e514\"\nuuid = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nversion = \"1.22.3\"\n\n[[PlutoUI]]\ndeps = [\"Base64\", \"Dates\", \"HypertextLiteral\", \"IOCapture\", \"InteractiveUtils\", \"JSON\", \"Logging\", \"Markdown\", \"Random\", \"Reexport\", \"UUIDs\"]\ngit-tree-sha1 = \"d1fb76655a95bf6ea4348d7197b22e889a4375f4\"\nuuid = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nversion = \"0.7.14\"\n\n[[Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"00cfd92944ca9c760982747e9a1d0d5d86ab1e5a\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.2\"\n\n[[Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[Qt5Base_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Fontconfig_jll\", \"Glib_jll\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"OpenSSL_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libxcb_jll\", \"Xorg_xcb_util_image_jll\", \"Xorg_xcb_util_keysyms_jll\", \"Xorg_xcb_util_renderutil_jll\", \"Xorg_xcb_util_wm_jll\", \"Zlib_jll\", \"xkbcommon_jll\"]\ngit-tree-sha1 = \"ad368663a5e20dbb8d6dc2fddeefe4dae0781ae8\"\nuuid = \"ea2cea3b-5b76-57ae-a6ef-0a8af62496e1\"\nversion = \"5.15.3+0\"\n\n[[QuadGK]]\ndeps = [\"DataStructures\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"78aadffb3efd2155af139781b8a8df1ef279ea39\"\nuuid = \"1fd47b50-473d-5c70-9696-f719f8f3bcdc\"\nversion = \"2.4.2\"\n\n[[REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[Ratios]]\ndeps = [\"Requires\"]\ngit-tree-sha1 = \"01d341f502250e81f6fec0afe662aa861392a3aa\"\nuuid = \"c84ed2f1-dad5-54f0-aa8e-dbefe2724439\"\nversion = \"0.4.2\"\n\n[[RecipesBase]]\ngit-tree-sha1 = \"44a75aa7a527910ee3d1751d1f0e4148698add9e\"\nuuid = \"3cdcf5f2-1ef4-517c-9805-6587b60abb01\"\nversion = \"1.1.2\"\n\n[[RecipesPipeline]]\ndeps = [\"Dates\", \"NaNMath\", \"PlotUtils\", \"RecipesBase\"]\ngit-tree-sha1 = \"7ad0dfa8d03b7bcf8c597f59f5292801730c55b8\"\nuuid = \"01d81517-befc-4cb6-b9ec-a95719d0359c\"\nversion = \"0.4.1\"\n\n[[Reexport]]\ngit-tree-sha1 = \"45e428421666073eab6f2da5c9d310d99bb12f9b\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.2.2\"\n\n[[Requires]]\ndeps = [\"UUIDs\"]\ngit-tree-sha1 = \"4036a3bd08ac7e968e27c203d45f5fff15020621\"\nuuid = \"ae029012-a4dd-5104-9daa-d747884805df\"\nversion = \"1.1.3\"\n\n[[Rmath]]\ndeps = [\"Random\", \"Rmath_jll\"]\ngit-tree-sha1 = \"bf3188feca147ce108c76ad82c2792c57abe7b1f\"\nuuid = \"79098fc4-a85e-5d69-aa6a-4863f24498fa\"\nversion = \"0.7.0\"\n\n[[Rmath_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"68db32dff12bb6127bac73c209881191bf0efbb7\"\nuuid = \"f50d1b31-88e8-58de-be2c-1cc44531875f\"\nversion = \"0.3.0+0\"\n\n[[SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[Scratch]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"0b4b7f1393cff97c33891da2a0bf69c6ed241fda\"\nuuid = \"6c6a2e73-6563-6170-7368-637461726353\"\nversion = \"1.1.0\"\n\n[[SentinelArrays]]\ndeps = [\"Dates\", \"Random\"]\ngit-tree-sha1 = \"54f37736d8934a12a200edea2f9206b03bdf3159\"\nuuid = \"91c51154-3ec4-41a3-a24f-3f23e20d615c\"\nversion = \"1.3.7\"\n\n[[Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[Showoff]]\ndeps = [\"Dates\", \"Grisu\"]\ngit-tree-sha1 = \"91eddf657aca81df9ae6ceb20b959ae5653ad1de\"\nuuid = \"992d4aef-0814-514b-bc4d-f2e9a6c4116f\"\nversion = \"1.0.3\"\n\n[[Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[SortingAlgorithms]]\ndeps = [\"DataStructures\"]\ngit-tree-sha1 = \"b3363d7460f7d098ca0912c69b082f75625d7508\"\nuuid = \"a2af1166-a08f-5f64-846c-94a0d3cef48c\"\nversion = \"1.0.1\"\n\n[[SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[SpecialFunctions]]\ndeps = [\"ChainRulesCore\", \"IrrationalConstants\", \"LogExpFunctions\", \"OpenLibm_jll\", \"OpenSpecFun_jll\"]\ngit-tree-sha1 = \"793793f1df98e3d7d554b65a107e9c9a6399a6ed\"\nuuid = \"276daf66-3868-5448-9aa4-cd146d93841b\"\nversion = \"1.7.0\"\n\n[[StaticArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"3c76dde64d03699e074ac02eb2e8ba8254d428da\"\nuuid = \"90137ffa-7385-5640-81b9-e52037218182\"\nversion = \"1.2.13\"\n\n[[Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[StatsAPI]]\ngit-tree-sha1 = \"1958272568dc176a1d881acb797beb909c785510\"\nuuid = \"82ae8749-77ed-4fe6-ae5f-f523153014b0\"\nversion = \"1.0.0\"\n\n[[StatsBase]]\ndeps = [\"DataAPI\", \"DataStructures\", \"LinearAlgebra\", \"Missings\", \"Printf\", \"Random\", \"SortingAlgorithms\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"8cbbc098554648c84f79a463c9ff0fd277144b6c\"\nuuid = \"2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91\"\nversion = \"0.33.10\"\n\n[[StatsFuns]]\ndeps = [\"ChainRulesCore\", \"IrrationalConstants\", \"LogExpFunctions\", \"Reexport\", \"Rmath\", \"SpecialFunctions\"]\ngit-tree-sha1 = \"95072ef1a22b057b1e80f73c2a89ad238ae4cfff\"\nuuid = \"4c63d2b9-4356-54db-8cca-17b64c39e42c\"\nversion = \"0.9.12\"\n\n[[StatsPlots]]\ndeps = [\"Clustering\", \"DataStructures\", \"DataValues\", \"Distributions\", \"Interpolations\", \"KernelDensity\", \"LinearAlgebra\", \"MultivariateStats\", \"Observables\", \"Plots\", \"RecipesBase\", \"RecipesPipeline\", \"Reexport\", \"StatsBase\", \"TableOperations\", \"Tables\", \"Widgets\"]\ngit-tree-sha1 = \"eb007bb78d8a46ab98cd14188e3cec139a4476cf\"\nuuid = \"f3b207a7-027a-5e70-b257-86293d7955fd\"\nversion = \"0.14.28\"\n\n[[StructArrays]]\ndeps = [\"Adapt\", \"DataAPI\", \"StaticArrays\", \"Tables\"]\ngit-tree-sha1 = \"2ce41e0d042c60ecd131e9fb7154a3bfadbf50d3\"\nuuid = \"09ab397b-f2b6-538f-b94a-2f83cf4a842a\"\nversion = \"0.6.3\"\n\n[[SuiteSparse]]\ndeps = [\"Libdl\", \"LinearAlgebra\", \"Serialization\", \"SparseArrays\"]\nuuid = \"4607b0f0-06f3-5cda-b6b1-a6196a1729e9\"\n\n[[TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[TableOperations]]\ndeps = [\"SentinelArrays\", \"Tables\", \"Test\"]\ngit-tree-sha1 = \"019acfd5a4a6c5f0f38de69f2ff7ed527f1881da\"\nuuid = \"ab02a1b2-a7df-11e8-156e-fb1833f50b87\"\nversion = \"1.1.0\"\n\n[[TableTraits]]\ndeps = [\"IteratorInterfaceExtensions\"]\ngit-tree-sha1 = \"c06b2f539df1c6efa794486abfb6ed2022561a39\"\nuuid = \"3783bdb8-4a98-5b6b-af9a-565f29a5fe9c\"\nversion = \"1.0.1\"\n\n[[Tables]]\ndeps = [\"DataAPI\", \"DataValueInterfaces\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"TableTraits\", \"Test\"]\ngit-tree-sha1 = \"1162ce4a6c4b7e31e0e6b14486a6986951c73be9\"\nuuid = \"bd369af6-aec1-5ad0-b16a-f7cc5008161c\"\nversion = \"1.5.2\"\n\n[[Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[URIs]]\ngit-tree-sha1 = \"97bbe755a53fe859669cd907f2d96aee8d2c1355\"\nuuid = \"5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4\"\nversion = \"1.3.0\"\n\n[[UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[Wayland_jll]]\ndeps = [\"Artifacts\", \"Expat_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"3e61f0b86f90dacb0bc0e73a0c5a83f6a8636e23\"\nuuid = \"a2964d1f-97da-50d4-b82a-358c7fce9d89\"\nversion = \"1.19.0+0\"\n\n[[Wayland_protocols_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\"]\ngit-tree-sha1 = \"2839f1c1296940218e35df0bbb220f2a79686670\"\nuuid = \"2381bf8a-dfd0-557d-9999-79630e7b1b91\"\nversion = \"1.18.0+4\"\n\n[[Widgets]]\ndeps = [\"Colors\", \"Dates\", \"Observables\", \"OrderedCollections\"]\ngit-tree-sha1 = \"80661f59d28714632132c73779f8becc19a113f2\"\nuuid = \"cc8bc4a8-27d6-5769-a93b-9d913e69aa62\"\nversion = \"0.6.4\"\n\n[[WoodburyMatrices]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"59e2ad8fd1591ea019a5259bd012d7aee15f995c\"\nuuid = \"efce3f68-66dc-5838-9240-27a6d6f5f9b6\"\nversion = \"0.5.3\"\n\n[[XML2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"1acf5bdf07aa0907e0a37d3718bb88d4b687b74a\"\nuuid = \"02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a\"\nversion = \"2.9.12+0\"\n\n[[XSLT_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgcrypt_jll\", \"Libgpg_error_jll\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\", \"Zlib_jll\"]\ngit-tree-sha1 = \"91844873c4085240b95e795f692c4cec4d805f8a\"\nuuid = \"aed1982a-8fda-507f-9586-7b0439959a61\"\nversion = \"1.1.34+0\"\n\n[[Xorg_libX11_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\", \"Xorg_xtrans_jll\"]\ngit-tree-sha1 = \"5be649d550f3f4b95308bf0183b82e2582876527\"\nuuid = \"4f6342f7-b3d2-589e-9d20-edeb45f2b2bc\"\nversion = \"1.6.9+4\"\n\n[[Xorg_libXau_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4e490d5c960c314f33885790ed410ff3a94ce67e\"\nuuid = \"0c0b7dd1-d40b-584c-a123-a41640f87eec\"\nversion = \"1.0.9+4\"\n\n[[Xorg_libXcursor_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXfixes_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"12e0eb3bc634fa2080c1c37fccf56f7c22989afd\"\nuuid = \"935fb764-8cf2-53bf-bb30-45bb1f8bf724\"\nversion = \"1.2.0+4\"\n\n[[Xorg_libXdmcp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fe47bd2247248125c428978740e18a681372dd4\"\nuuid = \"a3789734-cfe1-5b06-b2d0-1dd0d9d62d05\"\nversion = \"1.1.3+4\"\n\n[[Xorg_libXext_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"b7c0aa8c376b31e4852b360222848637f481f8c3\"\nuuid = \"1082639a-0dae-5f34-9b06-72781eeb8cb3\"\nversion = \"1.3.4+4\"\n\n[[Xorg_libXfixes_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"0e0dc7431e7a0587559f9294aeec269471c991a4\"\nuuid = \"d091e8ba-531a-589c-9de9-94069b037ed8\"\nversion = \"5.0.3+4\"\n\n[[Xorg_libXi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXfixes_jll\"]\ngit-tree-sha1 = \"89b52bc2160aadc84d707093930ef0bffa641246\"\nuuid = \"a51aa0fd-4e3c-5386-b890-e753decda492\"\nversion = \"1.7.10+4\"\n\n[[Xorg_libXinerama_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"26be8b1c342929259317d8b9f7b53bf2bb73b123\"\nuuid = \"d1454406-59df-5ea1-beac-c340f2130bc3\"\nversion = \"1.1.4+4\"\n\n[[Xorg_libXrandr_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"34cea83cb726fb58f325887bf0612c6b3fb17631\"\nuuid = \"ec84b674-ba8e-5d96-8ba1-2a689ba10484\"\nversion = \"1.5.2+4\"\n\n[[Xorg_libXrender_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"19560f30fd49f4d4efbe7002a1037f8c43d43b96\"\nuuid = \"ea2f1a96-1ddc-540d-b46f-429655e07cfa\"\nversion = \"0.9.10+4\"\n\n[[Xorg_libpthread_stubs_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"6783737e45d3c59a4a4c4091f5f88cdcf0908cbb\"\nuuid = \"14d82f49-176c-5ed1-bb49-ad3f5cbd8c74\"\nversion = \"0.1.0+3\"\n\n[[Xorg_libxcb_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"XSLT_jll\", \"Xorg_libXau_jll\", \"Xorg_libXdmcp_jll\", \"Xorg_libpthread_stubs_jll\"]\ngit-tree-sha1 = \"daf17f441228e7a3833846cd048892861cff16d6\"\nuuid = \"c7cfdc94-dc32-55de-ac96-5a1b8d977c5b\"\nversion = \"1.13.0+3\"\n\n[[Xorg_libxkbfile_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"926af861744212db0eb001d9e40b5d16292080b2\"\nuuid = \"cc61e674-0454-545c-8b26-ed2c68acab7a\"\nversion = \"1.1.0+4\"\n\n[[Xorg_xcb_util_image_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"0fab0a40349ba1cba2c1da699243396ff8e94b97\"\nuuid = \"12413925-8142-5f55-bb0e-6d7ca50bb09b\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\"]\ngit-tree-sha1 = \"e7fd7b2881fa2eaa72717420894d3938177862d1\"\nuuid = \"2def613f-5ad1-5310-b15b-b15d46f528f5\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_keysyms_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"d1151e2c45a544f32441a567d1690e701ec89b00\"\nuuid = \"975044d2-76e6-5fbe-bf08-97ce7c6574c7\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_renderutil_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"dfd7a8f38d4613b6a575253b3174dd991ca6183e\"\nuuid = \"0d47668e-0667-5a69-a72c-f761630bfb7e\"\nversion = \"0.3.9+1\"\n\n[[Xorg_xcb_util_wm_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"e78d10aab01a4a154142c5006ed44fd9e8e31b67\"\nuuid = \"c22f9ab0-d5fe-5066-847c-f4bb1cd4e361\"\nversion = \"0.4.1+1\"\n\n[[Xorg_xkbcomp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxkbfile_jll\"]\ngit-tree-sha1 = \"4bcbf660f6c2e714f87e960a171b119d06ee163b\"\nuuid = \"35661453-b289-5fab-8a00-3d9160c6a3a4\"\nversion = \"1.4.2+4\"\n\n[[Xorg_xkeyboard_config_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xkbcomp_jll\"]\ngit-tree-sha1 = \"5c8424f8a67c3f2209646d4425f3d415fee5931d\"\nuuid = \"33bec58e-1273-512f-9401-5d533626f822\"\nversion = \"2.27.0+4\"\n\n[[Xorg_xtrans_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"79c31e7844f6ecf779705fbc12146eb190b7d845\"\nuuid = \"c5fb5394-a638-5e4d-96e5-b29de1b5cf10\"\nversion = \"1.4.0+3\"\n\n[[Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[Zstd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"cc4bf3fdde8b7e3e9fa0351bdeedba1cf3b7f6e6\"\nuuid = \"3161d3a3-bdf6-5164-811a-617609db77b4\"\nversion = \"1.5.0+0\"\n\n[[libass_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"HarfBuzz_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"5982a94fcba20f02f42ace44b9894ee2b140fe47\"\nuuid = \"0ac62f75-1d6f-5e53-bd7c-93b484bb37c0\"\nversion = \"0.15.1+0\"\n\n[[libfdk_aac_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"daacc84a041563f965be61859a36e17c4e4fcd55\"\nuuid = \"f638f0a6-7fb0-5443-88ba-1cc74229b280\"\nversion = \"2.0.2+0\"\n\n[[libpng_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"94d180a6d2b5e55e447e2d27a29ed04fe79eb30c\"\nuuid = \"b53b4c65-9356-5827-b1ea-8c7a1a84506f\"\nversion = \"1.6.38+0\"\n\n[[libvorbis_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Ogg_jll\", \"Pkg\"]\ngit-tree-sha1 = \"c45f4e40e7aafe9d086379e5578947ec8b95a8fb\"\nuuid = \"f27f6e37-5d2b-51aa-960f-b287f2bc3b7a\"\nversion = \"1.3.7+0\"\n\n[[nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\n[[x264_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fea590b89e6ec504593146bf8b988b2c00922b2\"\nuuid = \"1270edf5-f2f9-52d2-97e9-ab00b5d0237a\"\nversion = \"2021.5.5+0\"\n\n[[x265_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"ee567a171cce03570d77ad3a43e90218e38937a9\"\nuuid = \"dfaa095f-4041-5dcd-9319-2fabd8486b76\"\nversion = \"3.5.0+0\"\n\n[[xkbcommon_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\", \"Wayland_protocols_jll\", \"Xorg_libxcb_jll\", \"Xorg_xkeyboard_config_jll\"]\ngit-tree-sha1 = \"ece2350174195bb31de1a63bea3a41ae1aa593b6\"\nuuid = \"d8fb68d0-12a3-5cfd-a85a-d49703b185fd\"\nversion = \"0.9.1+5\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─a4a73fb0-2213-11ec-02f8-1d2409575d4c\n# ╠═b6681ace-5cb1-49cb-9ed7-e749c7a67428\n# ╟─4dcf2480-7a37-4236-b51b-a171407bd8a0\n# ╠═e044742f-15dd-42e1-9271-43f11c7e2785\n# ╟─c2d41bee-4952-429b-b3d8-aea46eefd2c4\n# ╟─ef92132a-211d-4e8f-8ab2-12ae2c4a9c49\n# ╠═e2b04571-e4e5-49fe-823d-af0404eceab7\n# ╟─e2bb3b47-1973-4d40-91f2-a703470d1a6a\n# ╟─8f3de7b2-2fa3-4aa3-ba81-243aa4722a3a\n# ╟─1a193ab0-10b0-447d-a68a-0fc978c6e804\n# ╟─d142a6c3-e11c-44b5-930f-16deae98e74f\n# ╠═33fc930d-8693-41f9-8614-dc71870bd56d\n# ╟─4d10cc40-213e-4c4e-bea8-ea318aee18f7\n# ╟─9149e9e5-b0b9-4c22-8795-d982a3cacf6a\n# ╟─af901869-37bf-4992-bfc3-ee8477a37b34\n# ╟─361b07cc-6554-40d1-9448-6f4e4cd4bb71\n# ╟─2161be7c-571e-46c9-b3c2-0543d5e3296f\n# ╟─e82146d1-ea29-40a3-b89f-5d178f4a900a\n# ╟─da10276c-1381-4edb-9171-1ec0820a1809\n# ╟─b8e49bec-d582-4695-b7ac-6b0ccbca5e08\n# ╟─2cccdace-62df-4771-aaa4-1dd4342335e4\n# ╟─a673dd91-ccdf-4783-8b24-357a7307d7d3\n# ╟─3a34068e-4fed-40c3-89ef-2aabafb5144e\n# ╟─9c599a59-96f7-4b2c-b690-13750a14eef8\n# ╟─ffc34a30-9dba-40d0-afca-2279f4753661\n# ╟─a70c520f-860f-48be-a1a6-e87607298c37\n# ╠═8c493e53-bb7b-4110-a732-1cf93ecb754b\n# ╟─9908c97f-efb4-4634-aa97-9b4d2f9d7acc\n# ╠═d690e1d2-654c-4da4-9255-d3871429d262\n# ╟─ee5bfc95-bbb0-4d1b-8a83-77e884171f05\n# ╠═b7033638-277e-4610-89ef-3abe33ef35bf\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "51743ef93cbc423c0a36d6fad93deb311cae9857", "size": 47138, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "chapter_02.jl", "max_stars_repo_name": "TomRottier/statistical-rethinking", "max_stars_repo_head_hexsha": "3d5cfab3ec4f45797755f87e28fc5aa8feb640f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapter_02.jl", "max_issues_repo_name": "TomRottier/statistical-rethinking", "max_issues_repo_head_hexsha": "3d5cfab3ec4f45797755f87e28fc5aa8feb640f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter_02.jl", "max_forks_repo_name": "TomRottier/statistical-rethinking", "max_forks_repo_head_hexsha": "3d5cfab3ec4f45797755f87e28fc5aa8feb640f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1579710145, "max_line_length": 352, "alphanum_fraction": 0.7312359455, "num_tokens": 20886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802529509909, "lm_q2_score": 0.8791467659263148, "lm_q1q2_score": 0.8074789439490472}} {"text": "\"\"\"\n simplex_basis(a, b, i, j)\n\nEvaluate 2D orthonormal polynomial at simplex (a, b) of order (i, j)\n\nTranslated from Simplex2DP.m\n\n\"\"\"\nfunction simplex_basis(a::T, b::T, i, j) where {T<:Real}\n # x, a, b, n\n h1 = JacobiP(a, 0, 0, i)\n h2 = JacobiP(b, 2 * i + 1, 0, j)\n\n return sqrt(2.0) * h1 * h2 * (1 - b)^i\nend\n\nsimplex_basis(a::AbstractVector{T}, b::AbstractVector{T}, i, j) where {T<:Real} =\n [simplex_basis(a[k], b[k], i, j) for k in eachindex(a)]\n\n\nfunction ∂simplex_basis(a::T, b::T, id, jd) where {T<:Real}\n #fa = jacobi(a, id, 0, 0)\n #dfa = djacobi(a, id, 0, 0)\n #gb = jacobi(b, jd, 2*id+1, 0)\n #dgb = djacobi(b, jd, 2*id+1, 0)\n fa = JacobiP(a, 0, 0, id)\n dfa = ∂JacobiP(a, 0, 0, id)\n gb = JacobiP(b, 2 * id + 1, 0, jd)\n dgb = ∂JacobiP(b, 2 * id + 1, 0, jd)\n\n # r-derivative\n # d/dr = da/dr d/da + db/dr d/db = (2/(1-s)) d/da = (2/(1-b)) d/da\n dmodedr = dfa * gb\n if id > 0\n dmodedr *= (0.5 * (1.0 - b))^(id - 1)\n end\n\n # s-derivative\n # d/ds = ((1+a)/2)/((1-b)/2) d/da + d/db\n dmodeds = dfa * (gb * (0.5 * (1.0 + a)))\n if id > 0\n dmodeds *= (0.5 * (1.0 - b))^(id - 1)\n end\n\n tmp = dgb * (0.5 * (1.0 - b))^id\n if id > 0\n tmp -= 0.5 * id * gb * ((0.5 * (1.0 - b))^(id - 1))\n end\n dmodeds += fa * tmp\n\n # normalization\n dmodedr *= 2^(id + 0.5)\n dmodeds *= 2^(id + 0.5)\n\n return dmodedr, dmodeds\nend\n\nfunction ∂simplex_basis(a::AbstractVector{T}, b::AbstractVector{T}, id, jd) where {T<:Real}\n dmodedr = zero(a)\n dmodeds = zero(b)\n\n for i in eachindex(a)\n dmodedr[i], dmodeds[i] = ∂simplex_basis(a[i], b[i], id, jd)\n end\n\n return dmodedr, dmodeds\nend\n", "meta": {"hexsha": "1466b04e9a944fe967d2c8513bf85512c7a66b88", "size": 1695, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Transform/transform_triangle.jl", "max_stars_repo_name": "vavrines/FR.jl", "max_stars_repo_head_hexsha": "0108d769f4f9df7401d5fa3e8d8ca269cabacdd1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-07-01T07:16:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T11:22:48.000Z", "max_issues_repo_path": "src/Transform/transform_triangle.jl", "max_issues_repo_name": "vavrines/FR.jl", "max_issues_repo_head_hexsha": "0108d769f4f9df7401d5fa3e8d8ca269cabacdd1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-25T20:31:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T10:24:59.000Z", "max_forks_repo_path": "src/Transform/transform_triangle.jl", "max_forks_repo_name": "vavrines/FR.jl", "max_forks_repo_head_hexsha": "0108d769f4f9df7401d5fa3e8d8ca269cabacdd1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-23T07:06:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-23T07:06:02.000Z", "avg_line_length": 24.9264705882, "max_line_length": 91, "alphanum_fraction": 0.5085545723, "num_tokens": 759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107843878722, "lm_q2_score": 0.8615382129861583, "lm_q1q2_score": 0.8074429043728831}} {"text": "using Distributions, Random, Plots, LaTeXStrings; pyplot()\n\nN, K, M = 10^2, 50, 10^3\nlamRange = 0.01:0.01:0.99\n\nprn(lambda,rng) = quantile(Poisson(lambda),rand(rng))\nzDist(lam) = Uniform(0,2*(1-lam))\n\nrv(lam,rng) = sum([rand(rng,zDist(lam)) for _ in 1:prn(K*lam,rng)])\nrv2(lam,rng1,rng2) = sum([rand(rng1,zDist(lam)) for _ in 1:prn(K*lam,rng2)])\n\nmEst(lam,rng) = mean([rv(lam,rng) for _ in 1:N])\nmEst2(lam,rng1,rng2) = mean([rv2(lam,rng1,rng2) for _ in 1:N])\n\nfunction mGraph0(seed)\n singleRng = MersenneTwister(seed)\n [mEst(lam,singleRng) for lam in lamRange]\nend\nmGraph1(seed) = [mEst(lam,MersenneTwister(seed)) for lam in lamRange]\nmGraph2(seed1,seed2) = [mEst2(lam,MersenneTwister(seed1),\n\t\tMersenneTwister(seed2)) for lam in lamRange]\n\nargMaxLam(graph) = lamRange[findmax(graph)[2]]\n\nstd0 = std([argMaxLam(mGraph0(seed)) for seed in 1:M])\nstd1 = std([argMaxLam(mGraph1(seed)) for seed in 1:M])\nstd2 = std([argMaxLam(mGraph2(seed,seed+M)) for seed in 1:M])\n\nprintln(\"Standard deviation with no CRN: \", std0)\nprintln(\"Standard deviation with CRN and single RNG: \", std1)\nprintln(\"Standard deviation with CRN and two RNGs: \", std2)\n\nplot(lamRange,mGraph0(1987),\n\tc=:red, label=\"No CRN\")\nplot!(lamRange,mGraph1(1987),\n\tc=:green, label=\"CRN and one RNG\")\nplot!(lamRange,mGraph2(1987,1988),\n\tc=:blue, label=\"CRN and two RNG's\", xlims=(0,1),ylims=(0,14),\n xlabel=L\"\\lambda\", ylabel = \"Mean\")", "meta": {"hexsha": "6a90315a429423da2346af5a24a1fcd251f0b691", "size": 1398, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "10_chapter/twoRNGs.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "10_chapter/twoRNGs.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "10_chapter/twoRNGs.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 35.8461538462, "max_line_length": 76, "alphanum_fraction": 0.69527897, "num_tokens": 528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107861416413, "lm_q2_score": 0.8615382040983515, "lm_q1q2_score": 0.8074428975540738}} {"text": "using Optim\n# using MPI_Tools\n##This uses equations presented in \"Stray capacitances of single-layer air-core inductors for high-frequency applications\"\n# By\"Grandi, G., Kazimierczuk, M. K.,Massarini, A. Reggiani, U.\"\n\nfunction F(p,t,r,ϵr)\n return (p/(2*r))./((1+t/r)^(1-1/ϵr))\nend\nfunction Ct(D,r,p,t,ϵr)\n #D - solenoid diameter in meters\n #r - wire radius\n #p - pitch in meters\n #t - wire insulation thickness\n #ϵr - insulation relative permittivity\n\n ϵ0 = 8.85e-12\n\n FVal = F(p,t,r,ϵr)\n CtVal = pi^2*D*ϵ0 / (log(FVal+sqrt(FVal^2 - (1+t/r)^(2/ϵr))))\nend\n\n\n## Using derivation in appendix\nfunction CC(r,t,ϵr)\n return 2*π*ϵ₀*ϵr / (log(1+t/r))\nend\n\nfunction CG(p,r,t)\n (π * ϵ₀) ./ log( (p/(2*r))/(1+t/r) + sqrt( ( (p/(2*r))/(1+t/r) )^2 - 1) )\nend\n\n\"\"\"\nThis function calculates the equivalent turn-turn capacitcance of a single layer solenoid\n #D - solenoid diameter in meters\n #r - wire radius\n #p - pitch in meters\n #t - wire insulation thickness\n #ϵr - insulation relative permittivity\n\"\"\"\nfunction Ceq(D,r,p,t,ϵr)\n CC(r,t,ϵr)*CG(p,r,t) / (CC(r,t,ϵr)+2*CG(p,r,t)) * π*D\nend\n\n# Ceq(.2,.15e-3,1.33e-3,.5e-3,4)/10\n\n\n## Medhurst\nfunction CMedh(L,D)\n ϵ₀ = 8.85*1e-12\n return (4*ϵ₀*L/π + 8e-12*D + 27e-12*D*sqrt(D/L)) #Farads\nend\n\nfunction CMedh_Knight(L,D)\n ϵ₀ = 8.85*1e-12\n return 4*ϵ₀*L/π*(1+ 0.8249* (D/L)+ 2.329*(D/L)^(3/2))#Farads\nend\n\n## Equation 5.3, Cₗ-DAE in Knight, p.52\n\nfunction CL_DAE_Knight(\n L, #Coil length (axial)\n D, #Coil diamter\n N, #N turns\n ϵᵣₓ, #external permittivity\n ϵᵣᵢ) #Internal permittivity\n kc(L,D) =0.717439(D/L) +0.933048(D/L)^(3/2) +0.106(D/L)^2\n\n ϵ₀ = 8.85*1e-12\n p = L/N\n\n Ψ = atan(p/(π*D))\n\n C_L = (4*ϵ₀*ϵᵣₓ)/π *L * (1+kc(L,D)*(1+ϵᵣᵢ/ϵᵣₓ)/2)*1/(cos(Ψ)^2)\n return C_L\nend\n", "meta": {"hexsha": "ea40ec8d9731cdd9344753f0d8911e8b61959ac4", "size": 1799, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/StrayCap.jl", "max_stars_repo_name": "EliMattingly22/CircModDesign", "max_stars_repo_head_hexsha": "eb804218ba57745deb7e3099e0a2b481681f4b04", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/StrayCap.jl", "max_issues_repo_name": "EliMattingly22/CircModDesign", "max_issues_repo_head_hexsha": "eb804218ba57745deb7e3099e0a2b481681f4b04", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/StrayCap.jl", "max_forks_repo_name": "EliMattingly22/CircModDesign", "max_forks_repo_head_hexsha": "eb804218ba57745deb7e3099e0a2b481681f4b04", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.6710526316, "max_line_length": 122, "alphanum_fraction": 0.600889383, "num_tokens": 798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542852576265, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.8074406770011168}} {"text": "### A Pluto.jl notebook ###\n# v0.12.6\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ de7a5e8a-1ee4-11eb-2bbf-0f0eb3e489ec\nusing Pkg, DrWatson\n\n# ╔═╡ e4eeb13a-1ee4-11eb-0113-91f9a9c3b659\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing SpecialFunctions\nend\n\n# ╔═╡ ac3ceabe-1ee4-11eb-3935-313e96aafd62\nmd\"## Listing 2.11\"\n\n# ╔═╡ e9fa266e-1eeb-11eb-2630-59930c474ed3\nn = 2000\n\n# ╔═╡ d595cf1a-1f62-11eb-3503-753f5260ea5c\nbegin\n\tprobAgivenB(k) = 1- 1/(k+1)\n\tprobB(k) = 6/(pi*(k+1))^2\nend\n\n# ╔═╡ d5960d36-1f62-11eb-01dc-b59f88c34a97\nbegin\n\tnumerical= sum([probAgivenB(k)*probB(k) for k in 0:n])\n\tanalytic = 1 - 6*zeta(3)/pi^2\n\tText(\"Analytic: $(analytic) Numerical: $(numerical)\")\nend\n\n# ╔═╡ ea086874-1eeb-11eb-2cb0-4186697d4294\nmd\"## End of listing 2.11\"\n\n# ╔═╡ Cell order:\n# ╟─ac3ceabe-1ee4-11eb-3935-313e96aafd62\n# ╠═de7a5e8a-1ee4-11eb-2bbf-0f0eb3e489ec\n# ╠═e4eeb13a-1ee4-11eb-0113-91f9a9c3b659\n# ╠═e9fa266e-1eeb-11eb-2630-59930c474ed3\n# ╠═d595cf1a-1f62-11eb-3503-753f5260ea5c\n# ╠═d5960d36-1f62-11eb-01dc-b59f88c34a97\n# ╟─ea086874-1eeb-11eb-2cb0-4186697d4294\n", "meta": {"hexsha": "8e0181a2abc532d9a719948217b1a904c837bdb2", "size": 1071, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/02/listing2.11.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/02/listing2.11.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/02/listing2.11.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 23.2826086957, "max_line_length": 55, "alphanum_fraction": 0.7236227824, "num_tokens": 597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9219218262741297, "lm_q2_score": 0.8757869965109765, "lm_q1q2_score": 0.8074071472505342}} {"text": "using StatsBase, Distributions, Plots; pyplot()\n\nbinomialRV(n,p) = sum(rand(n) .< p)\n\np, n, N = 0.5, 10, 10^6\n\nbDist = Binomial(n,p)\nxGrid = 0:n\nbPmf = [pdf(bDist,i) for i in xGrid]\ndata = [binomialRV(n,p) for _ in 1:N]\npmfEst = counts(data,0:n)/N\n\nplot( xGrid, pmfEst, \n\tline=:stem, marker=:circle, \n\tc=:blue, ms=10, msw=0, lw=4, label=\"MC estimate\")\nplot!( xGrid, bPmf, \n\t line=:stem, marker=:xcross, c=:red, \n\t ms=6, msw=0, lw=2, label=\"PMF\", xticks=(0:1:10),\n\t ylims=(0,0.3), xlabel=\"x\", ylabel=\"Probability\")", "meta": {"hexsha": "065d2b2fe25d774a47576dfb05d4ef6a2e908371", "size": 513, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "3_chapter/binomialCoinFlip.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "3_chapter/binomialCoinFlip.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "3_chapter/binomialCoinFlip.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 27.0, "max_line_length": 50, "alphanum_fraction": 0.6257309942, "num_tokens": 217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561730622296, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.8073716803378724}} {"text": "cd(@__DIR__)\r\nusing Pkg; Pkg.activate(\".\"); Pkg.instantiate()\r\n\r\n# Single experiment, move to ensemble further on\r\n# Some good parameter values are stored as comments right now\r\n# because this is really good practice\r\n\r\nusing OrdinaryDiffEq\r\nusing ModelingToolkit\r\nusing DataDrivenDiffEq\r\nusing LinearAlgebra, DiffEqSensitivity, Optim\r\nusing DiffEqFlux, Flux\r\nusing Plots\r\ngr()\r\n\r\nfunction corona!(du,u,p,t)\r\n S,E,I,R,N,D,C = u\r\n F, β0,α,κ,μ,σ,γ,d,λ = p\r\n dS = -β0*S*F/N - β(t,β0,D,N,κ,α)*S*I/N -μ*S # susceptible\r\n dE = β0*S*F/N + β(t,β0,D,N,κ,α)*S*I/N -(σ+μ)*E # exposed\r\n dI = σ*E - (γ+μ)*I # infected\r\n dR = γ*I - μ*R # removed (recovered + dead)\r\n dN = -μ*N # total population\r\n dD = d*γ*I - λ*D # severe, critical cases, and deaths\r\n dC = σ*E # +cumulative cases\r\n\r\n du[1] = dS; du[2] = dE; du[3] = dI; du[4] = dR\r\n du[5] = dN; du[6] = dD; du[7] = dC\r\nend\r\nβ(t,β0,D,N,κ,α) = β0*(1-α)*(1-D/N)^κ\r\nS0 = 14e6\r\nu0 = [0.9*S0, 0.0, 0.0, 0.0, S0, 0.0, 0.0]\r\np_ = [10.0, 0.5944, 0.4239, 1117.3, 0.02, 1/3, 1/5,0.2, 1/11.2]\r\nR0 = p_[2]/p_[7]*p_[6]/(p_[6]+p_[5])\r\ntspan = (0.0, 21.0)\r\nprob = ODEProblem(corona!, u0, tspan, p_)\r\nsolution = solve(prob, Vern7(), abstol=1e-12, reltol=1e-12, saveat = 1)\r\n\r\ntspan2 = (0.0,60.0)\r\nprob = ODEProblem(corona!, u0, tspan2, p_)\r\nsolution_extrapolate = solve(prob, Vern7(), abstol=1e-12, reltol=1e-12, saveat = 1)\r\n\r\n# Ideal data\r\ntsdata = Array(solution)\r\n# Add noise to the data\r\nnoisy_data = tsdata + Float32(1e-5)*randn(eltype(tsdata), size(tsdata))\r\n\r\nplot(abs.(tsdata-noisy_data)')\r\n\r\n### Neural ODE\r\n\r\nann_node = FastChain(FastDense(7, 64, tanh),FastDense(64, 64, tanh), FastDense(64, 64, tanh), FastDense(64, 7))\r\np = Float64.(initial_params(ann_node))\r\n\r\nfunction dudt_node(u,p,t)\r\n S,E,I,R,N,D,C = u\r\n F,β0,α,κ,μ,σ,γ,d,λ = p_\r\n dS,dE,dI,dR,dD = ann_node([S/N,E,I,R,N,D/N,C],p)\r\n\r\n dN = -μ*N # total population\r\n dC = σ*E # +cumulative cases\r\n\r\n [dS,dE,dI,dR,dN,dD,dC]\r\nend\r\nprob_node = ODEProblem(dudt_node, u0, tspan, p)\r\ns = concrete_solve(prob_node, Tsit5(), u0, p, saveat = solution.t)\r\n\r\nfunction predict(θ)\r\n Array(concrete_solve(prob_node, Vern7(), u0, θ, saveat = 1,\r\n abstol=1e-6, reltol=1e-6,\r\n sensealg = InterpolatingAdjoint(autojacvec=ReverseDiffVJP())))\r\nend\r\n\r\n# No regularisation right now\r\nfunction loss(θ)\r\n pred = predict(θ)\r\n sum(abs2, (noisy_data[2:4,:] .- pred[2:4,:])), pred # + 1e-5*sum(sum.(abs, params(ann)))\r\nend\r\n\r\nloss(p)\r\n\r\nconst losses = []\r\ncallback(θ,l,pred) = begin\r\n push!(losses, l)\r\n if length(losses)%50==0\r\n println(losses[end])\r\n end\r\n false\r\nend\r\n\r\nres1_node = DiffEqFlux.sciml_train(loss, p, ADAM(0.01), cb=callback, maxiters = 500)\r\nres2_node = DiffEqFlux.sciml_train(loss, res1_node.minimizer, BFGS(initial_stepnorm=0.01), cb=callback, maxiters = 10000)\r\n\r\nprob_node2 = ODEProblem(dudt_node, u0, tspan, res2_node.minimizer)\r\ns = solve(prob_node2, Tsit5(), saveat = 1)\r\nscatter(solution, vars=[2,3,4], label=[\"True Exposed\" \"True Infected\" \"True Recovered\"])\r\nplot!(s, vars=[2,3,4], label=[\"Estimated Exposed\" \"Estimated Infected\" \"Estimated Recovered\"])\r\n\r\n# Plot the losses\r\nplot(losses, yaxis = :log, xaxis = :log, xlabel = \"Iterations\", ylabel = \"Loss\")\r\n\r\n# Extrapolate out\r\nprob_node_extrapolate = ODEProblem(dudt_node,u0, tspan2, res2_node.minimizer)\r\n_sol_node = solve(prob_node_extrapolate, Vern7(), abstol=1e-12, reltol=1e-12, saveat = 1)\r\np_node = scatter(solution_extrapolate, vars=[2,3,4], legend = :topleft, label=[\"True Exposed\" \"True Infected\" \"True Recovered\"], title=\"Neural ODE Extrapolation\")\r\nplot!(p_node,_sol_node, lw=5, vars=[2,3,4], label=[\"Estimated Exposed\" \"Estimated Infected\" \"Estimated Recovered\"])\r\nplot!(p_node,[20.99,21.01],[0.0,maximum(hcat(Array(solution_extrapolate[2:4,:]),Array(_sol_node[2:4,:])))],lw=5,color=:black,label=\"Training Data End\")\r\n\r\nsavefig(\"neuralode_extrapolation.png\")\r\nsavefig(\"neuralode_extrapolation.pdf\")\r\n\r\n### Universal ODE Part 1\r\n\r\nann = FastChain(FastDense(3, 64, tanh),FastDense(64, 64, tanh), FastDense(64, 1))\r\np = Float64.(initial_params(ann))\r\n\r\nfunction dudt_(u,p,t)\r\n S,E,I,R,N,D,C = u\r\n F, β0,α,κ,μ,σ,γ,d,λ = p_\r\n z = ann([S/N,I,D/N],p) # Exposure does not depend on exposed, removed, or cumulative!\r\n dS = -β0*S*F/N - z[1] -μ*S # susceptible\r\n dE = β0*S*F/N + z[1] -(σ+μ)*E # exposed\r\n dI = σ*E - (γ+μ)*I # infected\r\n dR = γ*I - μ*R # removed (recovered + dead)\r\n dN = -μ*N # total population\r\n dD = d*γ*I - λ*D # severe, critical cases, and deaths\r\n dC = σ*E # +cumulative cases\r\n\r\n [dS,dE,dI,dR,dN,dD,dC]\r\nend\r\nprob_nn = ODEProblem(dudt_,u0, tspan, p)\r\ns = concrete_solve(prob_nn, Tsit5(), u0, p, saveat = 1)\r\n\r\nplot(solution, vars=[2,3,4])\r\nplot!(s[2:4,:]')\r\n\r\nfunction predict(θ)\r\n Array(concrete_solve(prob_nn, Vern7(), u0, θ, saveat = solution.t,\r\n abstol=1e-6, reltol=1e-6,\r\n sensealg = InterpolatingAdjoint(autojacvec=ReverseDiffVJP())))\r\nend\r\n\r\n# No regularisation right now\r\nfunction loss(θ)\r\n pred = predict(θ)\r\n sum(abs2, noisy_data[2:4,:] .- pred[2:4,:]), pred # + 1e-5*sum(sum.(abs, params(ann)))\r\nend\r\n\r\nloss(p)\r\n\r\nconst losses = []\r\ncallback(θ,l,pred) = begin\r\n push!(losses, l)\r\n if length(losses)%50==0\r\n println(losses[end])\r\n end\r\n false\r\nend\r\n\r\nres1_uode = DiffEqFlux.sciml_train(loss, p, ADAM(0.01), cb=callback, maxiters = 500)\r\nres2_uode = DiffEqFlux.sciml_train(loss, res1_uode.minimizer, BFGS(initial_stepnorm=0.01), cb=callback, maxiters = 10000)\r\n\r\nloss(res2_uode.minimizer)\r\n\r\nprob_nn2 = ODEProblem(dudt_,u0, tspan, res2_uode.minimizer)\r\nuode_sol = solve(prob_nn2, Tsit5(), saveat = 1)\r\nplot(solution, vars=[2,3,4])\r\nplot!(uode_sol, vars=[2,3,4])\r\n\r\n# Plot the losses\r\nplot(losses, yaxis = :log, xaxis = :log, xlabel = \"Iterations\", ylabel = \"Loss\")\r\n\r\n# Collect the state trajectory and the derivatives\r\nX = noisy_data\r\n# Ideal derivatives\r\nDX = Array(solution(solution.t, Val{1}))\r\n\r\n# Extrapolate out\r\nprob_nn2 = ODEProblem(dudt_,u0, tspan2, res2_uode.minimizer)\r\n_sol_uode = solve(prob_nn2, Vern7(), abstol=1e-12, reltol=1e-12, saveat = 1)\r\np_uode = scatter(solution_extrapolate, vars=[2,3,4], legend = :topleft, label=[\"True Exposed\" \"True Infected\" \"True Recovered\"], title=\"Universal ODE Extrapolation\")\r\nplot!(p_uode,_sol_uode, lw = 5, vars=[2,3,4], label=[\"Estimated Exposed\" \"Estimated Infected\" \"Estimated Recovered\"])\r\nplot!(p_uode,[20.99,21.01],[0.0,maximum(hcat(Array(solution_extrapolate[2:4,:]),Array(_sol_uode[2:4,:])))],lw=5,color=:black,label=\"Training Data End\")\r\n\r\nsavefig(\"universalode_extrapolation.png\")\r\nsavefig(\"universalode_extrapolation.pdf\")\r\n\r\n### Universal ODE Part 2: SInDy to Equations\r\n\r\n# Create a Basis\r\n@variables u[1:3]\r\n# Lots of polynomials\r\npolys = Operation[]\r\nfor i ∈ 0:2, j ∈ 0:2, k ∈ 0:2\r\n push!(polys, u[1]^i * u[2]^j * u[3]^k)\r\nend\r\n\r\n# And some other stuff\r\nh = [cos.(u)...; sin.(u)...; unique(polys)...]\r\nbasis = Basis(h, u)\r\n\r\nX = noisy_data\r\n# Ideal derivatives\r\nDX = Array(solution(solution.t, Val{1}))\r\nS,E,I,R,N,D,C = eachrow(X)\r\nF,β0,α,κ,μ,_,γ,d,λ = p_\r\nL = β.(0:tspan[end],β0,D,N,κ,α).*S.*I./N\r\nL̂ = vec(ann([S./N I D./N]',res2_uode.minimizer))\r\nX̂ = [S./N I D./N]'\r\n\r\nscatter(L,title=\"Estimated vs Expected Exposure Term\",label=\"True Exposure\")\r\nplot!(L̂,label=\"Estimated Exposure\")\r\nsavefig(\"estimated_exposure.png\")\r\nsavefig(\"estimated_exposure.pdf\")\r\n\r\n# Create an optimizer for the SINDY problem\r\nopt = SR3()\r\n# Create the thresholds which should be used in the search process\r\nthresholds = exp10.(-6:0.1:1)\r\n\r\n# Test on original data and without further knowledge\r\nΨ_direct = SInDy(X[2:4, :], DX[2:4, :], basis, thresholds, opt = opt, maxiter = 50000) # Fail\r\nprintln(Ψ_direct.basis)\r\n# Test on ideal derivative data ( not available )\r\nΨ_ideal = SInDy(X[2:4, 5:end], L[5:end], basis, thresholds, opt = opt, maxiter = 50000) # Succeed\r\nprintln(Ψ_ideal.basis)\r\n# Test on uode derivative data\r\nΨ = SInDy(X̂[:, 2:end], L̂[2:end], basis, thresholds, opt = opt, maxiter = 10000, normalize = true, denoise = true) # Succeed\r\nprintln(Ψ.basis)\r\n\r\n# Build a ODE for the estimated system\r\nfunction approx(u,p,t)\r\n S,E,I,R,N,D,C = u\r\n F, β0,α,κ,μ,σ,γ,d,λ = p_\r\n z = Ψ([S/N,I,D/N]) # Exposure does not depend on exposed, removed, or cumulative!\r\n dS = -β0*S*F/N - z[1] -μ*S # susceptible\r\n dE = β0*S*F/N + z[1] -(σ+μ)*E # exposed\r\n dI = σ*E - (γ+μ)*I # infected\r\n dR = γ*I - μ*R # removed (recovered + dead)\r\n dN = -μ*N # total population\r\n dD = d*γ*I - λ*D # severe, critical cases, and deaths\r\n dC = σ*E # +cumulative cases\r\n\r\n [dS,dE,dI,dR,dN,dD,dC]\r\nend\r\n\r\n# Create the approximated problem and solution\r\na_prob = ODEProblem{false}(approx, u0, tspan2, p_)\r\na_solution = solve(a_prob, Tsit5())\r\n\r\np_uodesindy = scatter(solution_extrapolate, vars=[2,3,4], legend = :topleft, label=[\"True Exposed\" \"True Infected\" \"True Recovered\"])\r\nplot!(p_uodesindy,a_solution, lw = 5, vars=[2,3,4], label=[\"Estimated Exposed\" \"Estimated Infected\" \"Estimated Recovered\"])\r\nplot!(p_uodesindy,[20.99,21.01],[0.0,maximum(hcat(Array(solution_extrapolate[2:4,:]),Array(_sol_uode[2:4,:])))],lw=5,color=:black,label=\"Training Data End\")\r\n\r\nsavefig(\"universalodesindy_extrapolation.png\")\r\nsavefig(\"universalodesindy_extrapolation.pdf\")\r\n", "meta": {"hexsha": "eafc557b9ca18d5abe8daedfc751135ce3369da2", "size": 9327, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "SEIR_exposure/seir_exposure.jl", "max_stars_repo_name": "AlCap23/universal_differential_equations-1", "max_stars_repo_head_hexsha": "b85d9217ed75e8927c015598105063f2e1eb3b0e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 173, "max_stars_repo_stars_event_min_datetime": "2020-01-15T16:18:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T17:23:25.000Z", "max_issues_repo_path": "SEIR_exposure/seir_exposure.jl", "max_issues_repo_name": "AlCap23/universal_differential_equations-1", "max_issues_repo_head_hexsha": "b85d9217ed75e8927c015598105063f2e1eb3b0e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2020-01-28T02:37:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T05:47:26.000Z", "max_forks_repo_path": "SEIR_exposure/seir_exposure.jl", "max_forks_repo_name": "AlCap23/universal_differential_equations-1", "max_forks_repo_head_hexsha": "b85d9217ed75e8927c015598105063f2e1eb3b0e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41, "max_forks_repo_forks_event_min_datetime": "2020-01-21T08:13:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:43:29.000Z", "avg_line_length": 36.2918287938, "max_line_length": 166, "alphanum_fraction": 0.6453307602, "num_tokens": 3370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475699138558, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.8073651049021754}} {"text": "\"\"\"\n ahp_RI(n)\nReturn AHP Random Index for a given n.\n# Arguments:\n - `n::Int64`: Index value \n \n # Description \n The function returns the random index for a given integer between 3 and 15.\n\n# Output \n- `::Float64`: Random Index (RI) value.\n\n# Examples\n```julia-repl\njulia> ahp_RI(3)\n0.58\n```\n\n# References\n\nSaaty, Thomas L. \"Decision making with the analytic hierarchy process.\" International journal of services sciences 1.1 (2008): 83-98.\n```\n\"\"\"\nfunction ahp_RI(n::Int64)::Float64\n # First index is n = 3\n # RI[3] = 0.58\n # RI[4] = 0.90\n ris = [0.58, 0.90, 1.12, 1.24, 1.32,\n 1.41, 1.45, 1.49, 1.51, 1.53,\n 1.56, 1.57, 1.59]\n if n < 3 \n return 0\n elseif n <= 15\n return ris[n - 2]\n else\n return ris |> last\n end\n\nend\n\n\n\"\"\"\n ahp_consistency(comparisonMatrix)\n Test if a comparison matrix whether consistent or not.\n \n # Arguments:\n - `comparisonMatrix::DataFrame`: Comparison matrix for AHP. \n \n # Description \n AHP is based on subjective comparison between criteria. The success of the method highly depends on\n consistency of these comparison. \n\n# Output \n- `::AHPConsistencyResult`: AhpConsistencyResult object that holds multiple outputs including the boolean that indicates the matrix is whether consistent or not.\n\n# Examples\n```julia-repl\njulia> K = [\n 1 7 (1 / 5) (1 / 8) (1 / 2) (1 / 3) (1 / 5) 1;\n (1 / 7) 1 (1 / 8) (1 / 9) (1 / 4) (1 / 5) (1 / 9) (1 / 8);\n 5 8 1 (1 / 3) 4 2 1 1;\n 8 9 3 1 7 5 3 3;\n 2 4 (1 / 4) (1 / 7) 1 (1 / 2) (1 / 5) (1 / 5);\n 3 5 (1 / 2) (1 / 5) 2 1 (1 / 3) (1 / 3);\n 5 9 1 (1 / 3) 5 3 1 1;\n 1 8 1 (1 / 3) 5 3 1 1\n ];\n\njulia> K\n8×8 Array{Float64,2}:\n 1.0 7.0 0.2 0.125 0.5 0.333333 0.2 1.0\n 0.142857 1.0 0.125 0.111111 0.25 0.2 0.111111 0.125\n 5.0 8.0 1.0 0.333333 4.0 2.0 1.0 1.0\n 8.0 9.0 3.0 1.0 7.0 5.0 3.0 3.0\n 2.0 4.0 0.25 0.142857 1.0 0.5 0.2 0.2\n 3.0 5.0 0.5 0.2 2.0 1.0 0.333333 0.333333\n 5.0 9.0 1.0 0.333333 5.0 3.0 1.0 1.0\n 1.0 8.0 1.0 0.333333 5.0 3.0 1.0 1.0\n\njulia> dmat = makeDecisionMatrix(K);\njulia> ahp_consistency(dmat).isConsistent\ntrue\n```\n\n# References\nSaaty, Thomas L. \"Decision making with the analytic hierarchy process.\" International journal of services sciences 1.1 (2008): 83-98.\n\"\"\"\nfunction ahp_consistency(comparisonMatrix::DataFrame)::AHPConsistencyResult\n \n n, m = size(comparisonMatrix)\n \n csums = colsums(comparisonMatrix)\n normalizedComparisonMatrix = zeros(Float64, n, n)\n\n for i in 1:n\n for j in 1:n\n normalizedComparisonMatrix[i, j] = comparisonMatrix[i, j] / csums[j]\n end\n end\n\n priority_vector = rowmeans(normalizedComparisonMatrix)\n #mcomparisonMatrix = convert(Array{Float64,2}, comparisonMatrix)\n mcomparisonMatrix = Matrix{Float64}(comparisonMatrix)\n\n consistency_vector = mcomparisonMatrix * priority_vector\n\n pc_matrix = consistency_vector ./ priority_vector\n\n lambda_max = sum(pc_matrix) / n\n\n CI = (lambda_max - n) / (n - 1)\n ri = ahp_RI(n)\n CR = CI / ri\n\n isConsistent = (CR < 0.1)\n\n result = AHPConsistencyResult(\n comparisonMatrix,\n makeDecisionMatrix(normalizedComparisonMatrix),\n consistency_vector,\n priority_vector,\n pc_matrix,\n lambda_max,\n CI,\n ri,\n CR,\n isConsistent\n )\n\n return result\n\nend\n\n\n\n\"\"\"\n AHP(comparisonMatrixList, criteriaComparisonMatrix)\n\nApply AHP (Analytical Hierarchy Process) for a given list of comparison matrices and criteria comparison matrix.\n\n# Arguments:\n - `comparisonMatrixList::Array{DataFrame,1}`: Array of comparison matrices for all of the criteria. \n - `criteriaComparisonMatrix::DataFrame`: Criteria comparison matrix for AHP (Comparison of columns). \n \n \n # Description \n AHP is based on subjective comparison between criteria. The success of the method highly depends on\n consistency of these comparison. The method test the consistency first. At the next step, weights are\n calculated. The ordering of rows is determined by these weights.\n\n# Output \n- `::AHPResult`: AhpResult object that holds multiple outputs including calculated weights and scores.\n\n# Examples\n```julia-repl\njulia> K\n8×8 Array{Float64,2}:\n 1.0 7.0 0.2 0.125 0.5 0.333333 0.2 1.0\n 0.142857 1.0 0.125 0.111111 0.25 0.2 0.111111 0.125\n 5.0 8.0 1.0 0.333333 4.0 2.0 1.0 1.0\n 8.0 9.0 3.0 1.0 7.0 5.0 3.0 3.0\n 2.0 4.0 0.25 0.142857 1.0 0.5 0.2 0.2\n 3.0 5.0 0.5 0.2 2.0 1.0 0.333333 0.333333\n 5.0 9.0 1.0 0.333333 5.0 3.0 1.0 1.0\n 1.0 8.0 1.0 0.333333 5.0 3.0 1.0 1.0\n\njulia> A1\n4×4 Array{Float64,2}:\n 1.0 3.0 0.2 2.0\n 0.333333 1.0 0.142857 0.333333\n 5.0 7.0 1.0 4.0\n 0.5 3.0 0.25 1.0\n\njulia> A2\n4×4 Array{Float64,2}:\n 1.0 0.5 4.0 5.0\n 2.0 1.0 6.0 7.0\n 0.25 0.166667 1.0 3.0\n 0.2 0.142857 0.333333 1.0\n\njulia> A3\n4×4 Array{Float64,2}:\n 1.0 0.5 0.166667 3.0\n 2.0 1.0 0.25 5.0\n 6.0 4.0 1.0 9.0\n 0.333333 0.2 0.111111 1.0\n\njulia> A4\n4×4 Array{Float64,2}:\n 1.0 7.0 0.25 2.0\n 0.142857 1.0 0.111111 0.2\n 4.0 9.0 1.0 5.0\n 0.5 5.0 0.2 1.0\n\njulia> A5\n4×4 Array{Float64,2}:\n 1.0 6.0 2.0 3.0\n 0.166667 1.0 0.25 0.333333\n 0.5 4.0 1.0 2.0\n 0.333333 3.0 0.5 1.0\n\njulia> A6\n4×4 Array{Float64,2}:\n 1.0 0.25 0.5 0.142857\n 4.0 1.0 2.0 0.333333\n 2.0 0.5 1.0 0.2\n 7.0 3.0 5.0 1.0\n\njulia> A7\n4×4 Array{Float64,2}:\n 1.0 3.0 7.0 1.0\n 0.333333 1.0 4.0 0.333333\n 0.142857 0.25 1.0 0.142857\n 1.0 3.0 7.0 1.0\n\njulia> A8\n4×4 Array{Float64,2}:\n 1.0 2.0 5.0 8.0\n 0.5 1.0 3.0 6.0\n 0.2 0.333333 1.0 3.0\n 0.125 0.166667 0.333333 1.0\n\njulia> km = makeDecisionMatrix(K);\njulia> as = map(makeDecisionMatrix, [A1, A2, A3, A4, A5, A6, A7, A8]);\njulia> result = ahp(as, km);\njulia> result.bestIndex\n3\njulia> result.scores\n4-element Array{Float64,1}:\n 0.2801050163111839\n 0.14822726478768022\n 0.3813036392434616\n 0.19036407965767424\n```\n\n# References\nSaaty, Thomas L. \"Decision making with the analytic hierarchy process.\" International journal of services sciences 1.1 (2008): 83-98.\n\"\"\"\nfunction ahp(comparisonMatrixList::Array{DataFrame,1}, criteriaComparisonMatrix::DataFrame)::AHPResult\n \n result_list = map(ahp_consistency, comparisonMatrixList)\n\n n = length(result_list)\n\n ncriteria, _ = size(criteriaComparisonMatrix)\n\n ncandidates, _ = size(comparisonMatrixList[1])\n\n decision_matrix = zeros(Float64, ncandidates, ncriteria)\n\n @inbounds for i in 1:n\n decision_matrix[:,i] = result_list[i].priority\n end\n\n criteria_consistency = ahp_consistency(criteriaComparisonMatrix)\n\n weights = criteria_consistency.priority\n\n decision_matrix_df = makeDecisionMatrix(decision_matrix)\n ordering_result = decision_matrix * weights\n \n bestIndex = sortperm(ordering_result) |> last\n\n result = AHPResult(\n comparisonMatrixList,\n criteriaComparisonMatrix,\n criteria_consistency,\n decision_matrix_df,\n ordering_result,\n weights,\n bestIndex\n )\n\n return result\nend\n\n", "meta": {"hexsha": "c8bd98738247b7be38a172c749a4a44eb18ed31a", "size": 7611, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ahp.jl", "max_stars_repo_name": "drvinceknight/JMcDM", "max_stars_repo_head_hexsha": "89bec7ead2a7553f9e58fc75f37b5b89a30582fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2021-02-09T17:42:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T22:21:26.000Z", "max_issues_repo_path": "src/ahp.jl", "max_issues_repo_name": "drvinceknight/JMcDM", "max_issues_repo_head_hexsha": "89bec7ead2a7553f9e58fc75f37b5b89a30582fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2021-02-09T16:56:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T18:11:34.000Z", "max_forks_repo_path": "src/ahp.jl", "max_forks_repo_name": "drvinceknight/JMcDM", "max_forks_repo_head_hexsha": "89bec7ead2a7553f9e58fc75f37b5b89a30582fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2021-02-12T16:01:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T22:02:44.000Z", "avg_line_length": 27.476534296, "max_line_length": 161, "alphanum_fraction": 0.5917750624, "num_tokens": 3027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632856092016, "lm_q2_score": 0.8705972768020108, "lm_q1q2_score": 0.8073599510575362}} {"text": "function irr(annuity::Array{Float64})\n \n tvmnpv(i,annuity)=begin\n n=collect(1:length(annuity));\n sum(annuity./(1+i).^n)\n end\n\t\n\tif tvmnpv(0.0,annuity) <= 1.0\n return 0.0\n end\n \n\tif tvmnpv(0.99, annuity) >= 0\n return 99.9\n end\n \n f(x)=tvmnpv(x, annuity)\n \n return find_zeros(f, 0, 1)\n \nend\n\nfunction npv(annuities::Array{Float64}, rate::Float64)\n pv = 0.0\n \n for (ix,p) in enumerate(annuities)\n \n pv += p/(1+rate)^(ix-1)\n \n end\n \n return pv\n \nend\n\nfunction period_pay(P::Float64, rate::Float64, n::Int64)\n \n return (P*rate*(1.0+rate)^n)/((1.0+rate)^n -1)\n\nend\n\nfunction amortize(rate::Float64, n::Int64, P::Float64)\n balance = Array{Float64,1}()\n p = period_pay(P,rate,n)\n \n for k in 1:n\n btmp = P*(1.0+rate)^k - p*(1.0-(1.0+rate)^k)/(-rate)\n push!(balance,btmp)\n end\n\n intp = vcat([P]*rate, balance[1:end-1]*rate)\n balance = balance[1:end]\n principal_paid = p .- intp\n\n return principal_paid, intp, balance, p\n \nend\n ", "meta": {"hexsha": "db224e1740e5e0bec9f753b7440a289455afe6dc", "size": 1084, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "functions/financials.jl", "max_stars_repo_name": "arnavgautam/PVCR", "max_stars_repo_head_hexsha": "e3796ceb1c6992adbd5b535f7a2f8b790d88f6a6", "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": "functions/financials.jl", "max_issues_repo_name": "arnavgautam/PVCR", "max_issues_repo_head_hexsha": "e3796ceb1c6992adbd5b535f7a2f8b790d88f6a6", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2019-05-24T18:50:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-08T17:58:35.000Z", "max_forks_repo_path": "functions/financials.jl", "max_forks_repo_name": "arnavgautam/PVCR", "max_forks_repo_head_hexsha": "e3796ceb1c6992adbd5b535f7a2f8b790d88f6a6", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-06-04T16:20:02.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-04T16:20:02.000Z", "avg_line_length": 19.0175438596, "max_line_length": 60, "alphanum_fraction": 0.5415129151, "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799410139921, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.8072813149468213}} {"text": "# Poverty_gap.jl\n\n###### poverty_gap #####\n\"\"\"\n poverty_gap(v, z)\n\nCompute the Poverty Gap of a vector `v` at a specified poverty threshold `z`.\n\n# Examples\n```julia\njulia> using Inequality\njulia> poverty_gap([8, 5, 1, 3, 5, 6, 7, 6, 3], 4)\n0.1388888888888889\n```\n\"\"\"\npoverty_gap(v::AbstractVector{<:Real}, z::Real)::Float64 = sum((z .- v[v .< z])/z)/length(v)\n\n\n###### weighted poverty_gap #####\n\"\"\"\n poverty_gap(v, w, z)\n\nCompute the Poverty Gap of a vector `v` at a specified poverty threshold `z`, \nusing weights given by a weight vector `w`.\n\nWeights must not be negative, missing or NaN. The weights and data vectors must have the same length.\n\n# Examples\n```julia\njulia> using Inequality\njulia> poverty_gap([8, 5, 1, 3, 5, 6, 7, 6, 3], [0.1,0.5,0.3,0.8,0.1,0.5,0.3,0.8,0.2], 4)\n0.13194444444444445\n```\n\"\"\"\nfunction poverty_gap(v::AbstractVector{<:Real}, w::AbstractVector{<:Real}, z::Real)::Float64\n checks_weights(v, w)\n\n return sum((z .- v[v .< z])/z .* w[v .< z])/sum(w)\nend\n\n\nfunction poverty_gap(v::AbstractVector{<:Real}, w::AbstractWeights, z::Real)::Float64\n checks_weights(v, w)\n\n return sum((z .- v[v .< z])/z .* w[v .< z])/w.sum\nend\n\n\nwpoverty_gap(v::AbstractVector{<:Real}, w::AbstractVector{<:Real}, z::Real)::Float64 = poverty_gap(v, w, z)\n\nwpoverty_gap(v::AbstractVector{<:Real}, w::AbstractWeights, z::Real)::Float64 = poverty_gap(v, w, z)", "meta": {"hexsha": "a4b09bf23fcf82bba19f9ec00f2e2bc8319b70dc", "size": 1380, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Poverty_gap.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/Poverty_gap.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/Poverty_gap.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": 27.0588235294, "max_line_length": 107, "alphanum_fraction": 0.647826087, "num_tokens": 485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070035949656, "lm_q2_score": 0.8872045966995027, "lm_q1q2_score": 0.8072736761585244}} {"text": "@doc raw\"\"\"\n gaussradau(n::Integer) -> Tuple{Vector{Float64},Vector{Float64}}\n\nReturn nodes and weights of [Gauss-Radau quadrature](https://mathworld.wolfram.com/RadauQuadrature.html).\n\n```math\n\\int_{-1}^{1} f(x) dx \\approx \\sum_{i=1}^{n} w_i f(x_i)\n```\n\n# Examples\n```jldoctest\njulia> x, w = gaussradau(3);\n\njulia> f(x) = x^4;\n\njulia> I = dot(w, f.(x));\n\njulia> I ≈ 2/5\ntrue\n```\n\nNote that the first node is fixed at -1.\n\n```jldoctest\njulia> x, w = gaussradau(3);\n\njulia> x[1]\n-1.0\n```\n\"\"\"\nfunction gaussradau(n::Integer, T::Type=Float64)\n a = b = zero(T)\n # RADAUPTS Gauss-Legendre-Radau Quadrature Nodes and Weights\n if n == 1\n return T[-1], T[2]\n elseif n == 2\n return [-1, one(T)/3], [one(T)/2, convert(T,3)/2]\n else\n # Compute via GaussJacobi:\n x, w = gaussjacobi(n - 1, a, b+1)\n @inbounds for i in 1:length(w)\n w[i] = w[i] / (1 + x[i])\n end\n pushfirst!(x, -1)\n pushfirst!(w, convert(T, 2) / n^2)\n return x, w\n end\nend\n\nfunction gaussradau(n::Integer, α, β)\n if n ≤ 0\n throw(DomainError(n, \"Input N must be a positive integer\"))\n end\n m = n - 1\n s = α + β\n T = float(eltype(s))\n μ = jacobimoment(α, β)\n n == 0 && return T[], T[]\n n == 1 && return [-one(T)], [μ]\n J = jacobi_jacobimatrix(n, α, β)\n aᴿ = -1 + 2m*convert(T,m+α)/((2m+s)*(2m+s+1))\n J.dv[end] = aᴿ\n x, V = eigen(J)\n w = V[1,:].^2 .* μ\n x[1] = -1 # fix rounding from eigen computation\n return x, w\nend\n", "meta": {"hexsha": "50e0bc3916c90b0fa5e8daf9208158a7e1017311", "size": 1517, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gaussradau.jl", "max_stars_repo_name": "Datseris/FastGaussQuadrature.jl", "max_stars_repo_head_hexsha": "dd1f2fed53c4024bb6bde9f8d5a237ac47985b51", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 145, "max_stars_repo_stars_event_min_datetime": "2019-04-12T02:58:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T23:02:17.000Z", "max_issues_repo_path": "src/gaussradau.jl", "max_issues_repo_name": "Datseris/FastGaussQuadrature.jl", "max_issues_repo_head_hexsha": "dd1f2fed53c4024bb6bde9f8d5a237ac47985b51", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 45, "max_issues_repo_issues_event_min_datetime": "2019-04-08T23:32:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T21:02:07.000Z", "max_forks_repo_path": "src/gaussradau.jl", "max_forks_repo_name": "Datseris/FastGaussQuadrature.jl", "max_forks_repo_head_hexsha": "dd1f2fed53c4024bb6bde9f8d5a237ac47985b51", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2019-04-11T03:26:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-29T10:24:13.000Z", "avg_line_length": 22.3088235294, "max_line_length": 105, "alphanum_fraction": 0.5425181279, "num_tokens": 588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248225478307, "lm_q2_score": 0.8596637523076225, "lm_q1q2_score": 0.8072456024614675}} {"text": "plan_fejer1(μ) = FFTW.plan_r2r!(μ, FFTW.REDFT01)\n\n\"\"\"\nCompute nodes of Fejer's first quadrature rule.\n\"\"\"\nfejernodes1(::Type{T}, N::Int) where T = chebyshevpoints(T, N, Val(1))\n\n\"\"\"\nCompute weights of Fejer's first quadrature rule with modified Chebyshev moments of the first kind ``\\\\mu``.\n\"\"\"\nfejerweights1(μ::Vector) = fejerweights1!(copy(μ))\nfejerweights1!(μ::Vector) = fejerweights1!(μ, plan_fejer1(μ))\nfunction fejerweights1!(μ::Vector{T}, plan) where T\n N = length(μ)\n rmul!(μ, inv(T(N)))\n return plan*μ\nend\n\n\nplan_fejer2(μ) = FFTW.plan_r2r!(μ, FFTW.RODFT00)\n\n\"\"\"\nCompute nodes of Fejer's second quadrature rule.\n\"\"\"\nfejernodes2(::Type{T}, N::Int) where T = T[sinpi((N-2k-one(T))/(2N+two(T))) for k=0:N-1]\n\n\"\"\"\nCompute weights of Fejer's second quadrature rule with modified Chebyshev moments of the second kind ``\\\\mu``.\n\"\"\"\nfejerweights2(μ::Vector) = fejerweights2!(copy(μ))\nfejerweights2!(μ::Vector) = fejerweights2!(μ, plan_fejer2(μ))\nfunction fejerweights2!(μ::Vector{T}, plan) where T\n N = length(μ)\n Np1 = N+one(T)\n rmul!(μ, inv(Np1))\n plan*μ\n @inbounds for i=1:N μ[i] = sinpi(i/Np1)*μ[i] end\n return μ\nend\n", "meta": {"hexsha": "096b559243be0398daebaa95361be10942112181", "size": 1148, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/fejer.jl", "max_stars_repo_name": "eschnett/FastTransforms.jl", "max_stars_repo_head_hexsha": "2ee166d75ab09b8b444fb18b6a251ba74df5c10a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 138, "max_stars_repo_stars_event_min_datetime": "2019-04-13T05:52:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T10:03:15.000Z", "max_issues_repo_path": "src/fejer.jl", "max_issues_repo_name": "eschnett/FastTransforms.jl", "max_issues_repo_head_hexsha": "2ee166d75ab09b8b444fb18b6a251ba74df5c10a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 113, "max_issues_repo_issues_event_min_datetime": "2019-04-12T20:11:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T16:16:28.000Z", "max_forks_repo_path": "src/fejer.jl", "max_forks_repo_name": "eschnett/FastTransforms.jl", "max_forks_repo_head_hexsha": "2ee166d75ab09b8b444fb18b6a251ba74df5c10a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2019-04-23T08:43:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T15:35:17.000Z", "avg_line_length": 28.7, "max_line_length": 110, "alphanum_fraction": 0.6724738676, "num_tokens": 408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248157222395, "lm_q2_score": 0.8596637523076225, "lm_q1q2_score": 0.8072455965937542}} {"text": "using Convex, LinearAlgebra\nusing UnbalancedOptimalTransport: AbstractDivergence, KL, TV, RG, Balanced\n\n\"\"\"\n divergence(D::AbstractDivergence, a, b)\n\nComputes the the divergence `D` between `a` and `b`, where `a` can be a\nConvex.jl expression, and `b` is a constant.\n\"\"\"\nfunction divergence end\n\nlg(x) = x <= 0 ? zero(x) : log(x)\n\n# need to type-pirate a method for non-Convex.jl objects\nConvex.entropy(a::AbstractArray) = sum(x -> -x * lg(x), a)\n\nfunction divergence(::KL{ρ}, a, b) where {ρ}\n ρ * (-entropy(a) - dot(a, lg.(b)) + sum(b - a))\nend\n\nfunction divergence(::TV{ρ}, a, b) where {ρ}\n ρ * norm(a - b, 1)\nend\n\n# Computes the objective of the unbalanced regularized optimal transport problem\n# This is a separate method so it can be reused for testing `optimal_coupling`.\nfunction objective(\n π,\n D::AbstractDivergence,\n a::DiscreteMeasure,\n b::DiscreteMeasure,\n ϵ;\n C = (x, y) -> norm(x - y),\n)\n π_1 = sum(π, dims = 2)\n π_2 = vec(sum(π, dims = 1))\n\n # instantiate the cost matrix\n C_matrix = [C(xᵢ, yⱼ) for xᵢ in a.set, yⱼ in b.set]\n\n obj = dot(C_matrix, π) + ϵ * divergence(KL(), vec(π), kron(b.density, a.density))\n\n if (D isa KL) || (D isa TV)\n obj += divergence(D, π_1, a.density) + divergence(D, π_2, b.density)\n end\n\n return obj\nend\n\nfunction OT_convex(\n D::AbstractDivergence,\n a::DiscreteMeasure,\n b::DiscreteMeasure,\n ϵ;\n solver,\n verbose = false,\n C = (x, y) -> norm(x - y),\n)\n ϵ >= 0 || throw(DomainError(ϵ, \"Need ϵ >= 0\"))\n\n # coupling and its marginals\n π = Variable(length(a), length(b))\n π_1 = sum(π, dims = 2)\n π_2 = vec(sum(π, dims = 1))\n\n obj = objective(π, D, a, b, ϵ; C = C)\n\n if D isa Balanced\n constraints = [π >= 0, π_1 == a.density, π_2 == b.density]\n elseif D isa RG\n l, u = params(D)\n constraints = [\n π >= 0,\n l * a.density <= π_1,\n π_1 <= u * a.density,\n l * b.density <= π_2,\n π_2 <= u * b.density,\n ]\n else\n constraints = [π >= 0]\n end\n\n problem = minimize(obj, constraints)\n\n solve!(problem, solver; verbose = verbose)\n\n return (optimal_value = problem.optval, optimal_coupling = evaluate(π))\nend\n\nparams(::RG{l,u}) where {l,u} = (l, u)\n", "meta": {"hexsha": "8c787cbba8ce0ca78b24c0ddb23c93fb4f572f20", "size": 2283, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Convex_formulation.jl", "max_stars_repo_name": "baggepinnen/UnbalancedOptimalTransport.jl", "max_stars_repo_head_hexsha": "d1b11582f6ee37fea2b47d6f6755b2a71001658c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/Convex_formulation.jl", "max_issues_repo_name": "baggepinnen/UnbalancedOptimalTransport.jl", "max_issues_repo_head_hexsha": "d1b11582f6ee37fea2b47d6f6755b2a71001658c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-12-13T07:56:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-13T07:56:56.000Z", "max_forks_repo_path": "test/Convex_formulation.jl", "max_forks_repo_name": "baggepinnen/UnbalancedOptimalTransport.jl", "max_forks_repo_head_hexsha": "d1b11582f6ee37fea2b47d6f6755b2a71001658c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0879120879, "max_line_length": 85, "alphanum_fraction": 0.5838808585, "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693645535723, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.8071915916892634}} {"text": "\nstruct Polynomial{DT<:AbstractFloat, BT <: Basis}\n b::BT\n c::Vector{DT}\n\n function Polynomial{DT,BT}(b::BT, c) where {DT, BT <: Basis{DT}}\n @assert nnodes(b) == length(c)\n new(b, c)\n end\nend\n\nfunction Polynomial(b::Basis{DT}, c::Vector{DT}) where {DT}\n Polynomial{DT, typeof(b)}(b, c)\nend\n\n\nfunction LagrangePolynomial(x::Vector{DT}, c::Vector{DT}) where {DT}\n b = LagrangeBasis(x)\n Polynomial{DT, typeof(b)}(b, c)\nend\n\n\nfunction BernsteinPolynomial(x::Vector{DT}, c::Vector{DT}) where {DT}\n b = BernsteinBasis(x)\n Polynomial{DT, typeof(b)}(b, c)\nend\n\n\nfunction Base.similar(lag::Polynomial{T}, c::Vector{T}) where {T}\n @assert length(c) == length(lag.c)\n Polynomial(lag.b, c)\nend\n\n\nfunction evaluate!(pol::Polynomial{T}, x::Vector{T}, y::Vector{T}) where {T}\n @assert length(x) == length(y)\n\n local tx::T\n local ty::T\n\n for k in eachindex(x,y)\n tx = x[k]\n ty = 0\n for j in eachindex(pol.c)\n ty += pol.c[j] * eval_basis(pol.b, j, tx)\n end\n y[k] = ty\n end\n\n return nothing\nend\n\nfunction evaluate!(b::LagrangeBasis{T}, c::Vector{T}, x::Vector{T}, y::Vector{T}) where {T}\n evaluate!(Polynomial(b, c), x, y)\nend\n", "meta": {"hexsha": "7ce63d600e8680a6989ae9337a00fb4c5d3d4c17", "size": 1223, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/basis_functions/polynomial.jl", "max_stars_repo_name": "krystophny/GeometricIntegrators.jl", "max_stars_repo_head_hexsha": "7855e977b014c8ba119f6bb73c6ed9bf96f04b1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-02-04T11:52:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-04T11:52:47.000Z", "max_issues_repo_path": "src/basis_functions/polynomial.jl", "max_issues_repo_name": "krystophny/GeometricIntegrators.jl", "max_issues_repo_head_hexsha": "7855e977b014c8ba119f6bb73c6ed9bf96f04b1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/basis_functions/polynomial.jl", "max_forks_repo_name": "krystophny/GeometricIntegrators.jl", "max_forks_repo_head_hexsha": "7855e977b014c8ba119f6bb73c6ed9bf96f04b1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8392857143, "max_line_length": 91, "alphanum_fraction": 0.5936222404, "num_tokens": 393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632234212402, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.8071493293324866}} {"text": "# test functions for developing optimizers\n# see https://en.wikipedia.org/wiki/Test_functions_for_optimization\n\n\n# optimal = (0, 0, 0, ...)\nfunction sphere(x)\n return sum(x^2)\nend\n\n# optimal = (1,1,1,...)\nfunction rosenbrock(x)\n x1 = x[1:end-1]\n x2 = x[2:end]\n return sum(100 * (x2-x1^2)^2 + (1-x1)^2)\nend\n\n# optimal = (3, 0.5)\nfunction beale(p)\n x, y = p[1], p[2]\n return (1.5 - x + x*y)^2 + (2.25 - x + x*y^2)^2 + \n (2.625 - x + x*y^3)\nend\n\n# optimal = (1, 3)\nfunction booth(p)\n x, y = p[1], p[2]\n return (x + 2y - 7)^2 + (2x+y-5)^2\nend\n\n#optimal = (-0.2903, ...)\nfunction stybliski_tang(x)\n return sum(x^4 - 16x^2 + 5x)/2\nend\n\n# optimal = (1,1)\nfunction levi(p)\n x, y = p[1], p[2]\n sin(3π*x)^2 + (x-1)^2 * (1+sin(3π*y)^2) + (y-1)^2 * (1+sin(2π*y)^2)\nend", "meta": {"hexsha": "c6d7d559b4ed298df55fd7d31baa205dcd9f1167", "size": 800, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/optimfuncs.jl", "max_stars_repo_name": "ziyiyin97/ADCME.jl", "max_stars_repo_head_hexsha": "1c9b2c1ae63059d79a5a6a7b86eee64796868755", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 202, "max_stars_repo_stars_event_min_datetime": "2019-06-12T18:42:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T16:56:46.000Z", "max_issues_repo_path": "test/optimfuncs.jl", "max_issues_repo_name": "banren456/ADCME.jl", "max_issues_repo_head_hexsha": "2ed7a0801b6ed90f2236c3cde7a1dca825cbe897", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46, "max_issues_repo_issues_event_min_datetime": "2019-08-19T19:37:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T11:17:50.000Z", "max_forks_repo_path": "test/optimfuncs.jl", "max_forks_repo_name": "banren456/ADCME.jl", "max_forks_repo_head_hexsha": "2ed7a0801b6ed90f2236c3cde7a1dca825cbe897", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 56, "max_forks_repo_forks_event_min_datetime": "2019-07-30T05:50:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T02:41:07.000Z", "avg_line_length": 20.5128205128, "max_line_length": 71, "alphanum_fraction": 0.5325, "num_tokens": 349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632247867715, "lm_q2_score": 0.8479677602988602, "lm_q1q2_score": 0.8071493268332892}} {"text": "#=\nProbability distributions useful in economics.\n\n@author : Spencer Lyon \n\n@date: 2014-08-04\n\nReferences\n----------\n\nhttp://en.wikipedia.org/wiki/Beta-binomial_distribution\n\n=#\n\n\"\"\"\nThe Beta-Binomial distribution\n\n##### Fields\n\n- `n, a, b::Float64` The three paramters to the distribution\n\n##### Notes\n\nSee also http://en.wikipedia.org/wiki/Beta-binomial_distribution\n\n\"\"\"\ntype BetaBinomial\n n::Integer\n a::Real\n b::Real\nend\n\n# moments\nmean(d::BetaBinomial) = d.n * d.a / (d.a + d.b)\n\nstd(d::BetaBinomial) = sqrt(var(d))\n\nfunction var(d::BetaBinomial)\n n, a, b = d.n, d.a, d.b\n top = n*a*b * (a + b + n)\n btm = (a+b)^2.0 * (a+b+1.0)\n top / btm\nend\n\nfunction skewness(d::BetaBinomial)\n n, a, b = d.n, d.a, d.b\n t1 = (a+b+2*n) * (b - a) / (a+b+2)\n t2 = sqrt((1+a+b) / (n*a*b * (n+a+b)))\n t1 * t2\nend\n\n\"\"\"\nEvaluate the pdf of the distributions at the points 0, 1, ..., k\n\n##### Arguments\n\n`d::BetaBinomial`: Instance of `BetaBinomial` type\n\n##### Returns\n\n- `probs::vector{Float64}`: pdf of the distribution `d`, at `0:d.k`\n\n\"\"\"\nfunction pdf(d::BetaBinomial)\n n, a, b = d.n, d.a, d.b\n k = 0:n\n binoms = Float64[binomial(n, i) for i in k]\n probs = binoms .* beta(k .+ a, n .- k .+ b) ./ beta(a, b)\nend\n", "meta": {"hexsha": "759f0ed99f68388bdfa6deb7b1b396a79cec7525", "size": 1266, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/dists.jl", "max_stars_repo_name": "oyamad/QuantEcon.jl", "max_stars_repo_head_hexsha": "5bb43ad7363e7e4503eee061fc533ec6967cf7c3", "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/dists.jl", "max_issues_repo_name": "oyamad/QuantEcon.jl", "max_issues_repo_head_hexsha": "5bb43ad7363e7e4503eee061fc533ec6967cf7c3", "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/dists.jl", "max_forks_repo_name": "oyamad/QuantEcon.jl", "max_forks_repo_head_hexsha": "5bb43ad7363e7e4503eee061fc533ec6967cf7c3", "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.0857142857, "max_line_length": 67, "alphanum_fraction": 0.5892575039, "num_tokens": 444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951863227517834, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.8071493218348939}} {"text": "function gmmresults()\n # example of GMM: draws from N(0,1). We estimate mean and variance.\n y = randn(1000,1)\n # 3 moment conditions implied by drawing from N(0,σ²):\n # mean = 0, variance = constant, skew = 0\n moments = θ -> [y.-θ[1] (y.^2.0).-θ[2] (y.-θ[1]).^3.0]\n # first round consistent\n W = Matrix{Float64}(I,3,3)\n θ = [0.0, 1.0]\n θhat, objvalue, D, ms, converged = gmm(moments, θ, W)\n # second round efficient\n Ωinv = inv(cov(ms))\n gmmresults(moments, θhat, Ωinv, \"GMM example, two step\")\n # CUE\n gmmresults(moments, θhat)\n return\nend \n\nfunction gmmresults(moments, θ, weight=\"\", title=\"\", names=\"\", efficient=true)\n n,g = size(moments(θ))\n CUE = false\n if weight !=\"\" # if weight provided, use it\n θhat, objvalue, D, ms, converged = gmm(moments, θ, weight)\n else # do CUE\n θhat, objvalue, D, ms, weight, converged = gmm(moments, θ)\n CUE=true\n end\n k,g = size(D)\n # estimate variance\n efficient ? V = inv(D*weight*D')/n : V = V*D*weight*NeweyWest(ms)*weight*D'*V/n\n if names==\"\"\n names = 1:k\n names = names'\n end\n se = sqrt.(diag(V))\n t = θhat ./ se\n p = 2.0 .- 2.0*cdf.(Ref(TDist(n-k)),abs.(t))\n PrintDivider()\n if title !=\"\" printstyled(title, color=:yellow); println() end\n print(\"GMM Estimation Results Convergence: \")\n printstyled(converged, color=:green)\n CUE ? message=\" (CUE)\" : message=\" (user weight matrix)\"\n printstyled(message, color=:cyan)\n println()\n println(\"Observations: \", n)\n println(\"Hansen-Sargan statistic: \", round(n*objvalue, digits=5))\n if g > k\n println(\"Hansen-Sargan p-value: \", round(1.0 - cdf(Chisq(g-k),n*objvalue), digits=5))\n end \n a =[θhat se t p]\n println(\"\")\n PrintEstimationResults(a, names)\n println()\n PrintDivider()\n return θhat, objvalue, V, D, weight, converged\nend \n", "meta": {"hexsha": "288bd966eec1da7a25d442428e9762b2ea751bd9", "size": 1905, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/GMM/gmmresults.jl", "max_stars_repo_name": "mcreel/EconometricsNotes", "max_stars_repo_head_hexsha": "93b3f042ace7c4d3059b333fd9dc3d2c794f0a52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-19T18:23:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T18:23:45.000Z", "max_issues_repo_path": "src/GMM/gmmresults.jl", "max_issues_repo_name": "mcreel/EconometricsNotes", "max_issues_repo_head_hexsha": "93b3f042ace7c4d3059b333fd9dc3d2c794f0a52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GMM/gmmresults.jl", "max_forks_repo_name": "mcreel/EconometricsNotes", "max_forks_repo_head_hexsha": "93b3f042ace7c4d3059b333fd9dc3d2c794f0a52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4210526316, "max_line_length": 93, "alphanum_fraction": 0.5910761155, "num_tokens": 647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632247867715, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.8071493195190409}} {"text": "#Simulate a determinantally-thinned Poisson point process on a rectangle\n#Author: H. Paul Keeler, 2019.\n\n#Note: Need the .+ for adding a scalar to an array\n#Also need . for sqrt, exp, cos, sin etc and assigning scalars to arrays\n#Index and Boolean arrrays need to be vectors eg v=zeros(n), NOT v=zeros(n,1)\n\n#clearconsole(); #for clearing Julia REPL console\n\nusing Distributions #for random simulations\nusing PyPlot #uses Python for plotting\nusing LinearAlgebra;\n\n#include some helper functions\ninclude(\"funSimSimpleLDPP.jl\"); #for simulations\ninclude(\"funLtoK.jl\"); #for converting a non-singular L matrix to a singular matrix\n\n#set random seed for reproducibility\n#rng(1);\n\nnumbSim=10^4; #number of simulations\n\n###START -- Parameters -- ###START\n#Poisson point process parameters\nlambda=10; #intensity (ie mean density) of the Poisson process\n\n#choose kernel\nchoiceKernel=1; #1 for Gaussian (ie squared exponetial );2 for Cauchy\nsigma=1;# parameter for Gaussian and Cauchy kernel\nalpha=1;# parameter for Cauchy kernel\n\n#Simulation window parameters\nxMin=0;xMax=1;yMin=0;yMax=1;\nxDelta=xMax-xMin;yDelta=yMax-yMin; #rectangle dimensions\nareaTotal=xDelta*yDelta; #area of rectangle\n###END -- Parameters -- ###END\n\n### START -- Simulate a Poisson point process on a rectangle ###START\n#Simulate Poisson point process\nnumbPoints=rand(Poisson(areaTotal*lambda)); #Poisson number of points\nxx=xDelta*(rand(numbPoints)).+xMin;#x coordinates of Poisson points\nyy=xDelta*(rand(numbPoints)).+yMin;#y coordinates of Poisson points\n### END -- Simulate a Poisson point process on a rectangle --END ###\n\n#numbPoints=5; xx=-2:1:2; yy=3:7 #TEMP\n\n### START -- CREATE L matrix -- START ###\n#all squared distances of x/y difference pairs\nxxDiff=kron(xx,ones(1,numbPoints))-kron(ones(numbPoints,1),transpose(xx));\nyyDiff=kron(yy,ones(1,numbPoints))-kron(ones(numbPoints,1),transpose(yy));\nrrDiffSquared=(xxDiff.^2+yyDiff.^2);\nif choiceKernel==1\n ##Gaussian/squared exponential kernel\n L=lambda*exp.(-(rrDiffSquared)/sigma^2);\nelseif choiceKernel==2\n ##Cauchy kernel\n L=lambda./(1+rrDiffSquared/sigma^2).^(alpha+1/2);\nelse\n println(\"choiceKernel has to be equal to 1 or 2.\");\nend\n\n### END-- CREATE L matrix -- ### END\nL=Symmetric(L); #convert to Symmetric marix\n\n### START Testing DPP simulation START ###\n#Retrieve eigenvalues and eigenvectors\neigenVectL=eigvecs(L); #eigen decomposition -- vectors\neigenValL=eigvals(L); #eigen decomposition -- values\n\n#run simulations with tests\nglobal probX_i_Emp=zeros(numbPoints); #initialize variables\nindexTest=2:3; #choose a subset of [1 numbPoints]\nglobal probTestEmp=0; #initialize variables\n#loop through for each simulation\nfor ss=1:numbSim\n #run determinantal simuation\n indexDPP=funSimSimpleLDPP(eigenVectL,eigenValL); #returns index\n global probX_i_Emp[indexDPP]=probX_i_Emp[indexDPP].+1;\n\n countTemp=0; #initialize count\n for ii=1:length(indexTest)\n #check that each point of test subset appears\n countTemp=countTemp+any(indexDPP.==indexTest[ii]);\n end\n global probTestEmp=probTestEmp.+(countTemp.==length(indexTest));\nend\n\n#empirically estimate the probabilities of each point appearing\nprobX_i_Emp=probX_i_Emp./numbSim\nprintln(\"probX_i_Emp = \", probX_i_Emp);\n\n\n#calculate exactly the probabilities of each point appearing\nK=funLtoK(L);\nprobX_i_Exact=diag(K)\nprintln(\"probX_i_Exact = \", probX_i_Exact);\n\n#empirically estimate the probabilities of test subset appearing\nprobTestEmp=probTestEmp./numbSim\nprintln(\"probTestEmp = \", probTestEmp);\n\n#calculate exactly the probabilities of test subset appearing\nprobTestExact=det(K[indexTest,indexTest])\nprintln(\"probTestExact = \", probTestExact);\n\n###END Testing DPP simulation END###\n", "meta": {"hexsha": "85738d20b0821876907095906ce708875731735d", "size": 3712, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "TestDetPoisson.jl", "max_stars_repo_name": "hpaulkeeler/DetPoisson_Julia", "max_stars_repo_head_hexsha": "9d5273e1f5dcf0869b01edd6e0486b900838a971", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "TestDetPoisson.jl", "max_issues_repo_name": "hpaulkeeler/DetPoisson_Julia", "max_issues_repo_head_hexsha": "9d5273e1f5dcf0869b01edd6e0486b900838a971", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TestDetPoisson.jl", "max_forks_repo_name": "hpaulkeeler/DetPoisson_Julia", "max_forks_repo_head_hexsha": "9d5273e1f5dcf0869b01edd6e0486b900838a971", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.691588785, "max_line_length": 83, "alphanum_fraction": 0.7570043103, "num_tokens": 1054, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810481379379, "lm_q2_score": 0.8519528094861981, "lm_q1q2_score": 0.8071239456150953}} {"text": "# Simple Linear Regression\n# Originally written by Keegan Go for lsqpy\n# Translated into LinearLeastSquares.jl by Karanveer Mohan and David Zeng\n\nusing LinearLeastSquares\nusing Gadfly\n# Set the random seed to get consistent data\nsrand(1)\n\n# Number of examples to use\nn = 100\n\n# Specify the true value of the variable\ntrue_coeffs = [2; -2; 0.5]\n\n# Generate data\nx_data = rand(n) * 5\nx_data_expanded = hcat([x_data .^ i for i in 1 : 3]...)\ny_data = x_data_expanded * true_coeffs + 0.5 * rand(n)\n\nslope = Variable()\noffset = Variable()\nline = offset + x_data * slope\nresiduals = line - y_data\nfit_error = sum_squares(residuals)\noptval = minimize!(fit_error)\n\n# plot the data and the line\nt = [0; 5; 0.1]\np = plot(\n layer(x=x_data, y=y_data, Geom.point),\n layer(x=t, y=evaluate(slope) * t + evaluate(offset), Geom.line),\n Theme(panel_fill=color(\"white\"))\n)\n# draw(PNG(\"linear_regression.png\", 16cm, 12cm), p)\n", "meta": {"hexsha": "9ce1b98b043c10d2ff88cd626fc9a36ff52877cc", "size": 908, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/regression/linear_regression.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/LinearLeastSquares.jl-a8002f64-6652-5b53-92ba-d4864fedfa0a", "max_stars_repo_head_hexsha": "f50c74231e7204bb63a9f49ea606ba28dddd3fa5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2015-06-25T15:56:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T16:36:46.000Z", "max_issues_repo_path": "examples/regression/linear_regression.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/LinearLeastSquares.jl-a8002f64-6652-5b53-92ba-d4864fedfa0a", "max_issues_repo_head_hexsha": "f50c74231e7204bb63a9f49ea606ba28dddd3fa5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2016-07-12T03:00:37.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-06T12:25:56.000Z", "max_forks_repo_path": "examples/regression/linear_regression.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/LinearLeastSquares.jl-a8002f64-6652-5b53-92ba-d4864fedfa0a", "max_forks_repo_head_hexsha": "f50c74231e7204bb63a9f49ea606ba28dddd3fa5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2015-02-14T02:30:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T18:11:37.000Z", "avg_line_length": 25.2222222222, "max_line_length": 73, "alphanum_fraction": 0.7114537445, "num_tokens": 287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810451666345, "lm_q2_score": 0.851952809486198, "lm_q1q2_score": 0.8071239430836848}} {"text": "\"\"\"\n hartley_transformation(pts::AbstractArray{T}) where T<:HomogeneousPoint\n\nReturns a matrix which can be used to map a set of ``d``-dimensional Cartesian\npoints which are represented by ``\\\\text{length-}(d+1)`` homogeneous coordinates into a\ndata-dependent coordinate system. In the data-dependent coordinate system the\norigin is the center of mass (centroid) of the points and the root-mean-square\ndistance of the points to the origin is equal to ``\\\\sqrt{d}``.\n\n# Details\n\nA point in ``\\\\mathbb{R}^d`` with\nCartesian coordinates ``\\\\left(m_1, m_2, \\\\ldots, m_d \\\\right)`` can also be\nexpressed in homogeneous coordinates with the vector ``\\\\mathbf{m} =\n\\\\left[m_1, m_2, \\\\ldots, m_d , 1 \\\\right]^\\\\top``.\n\nSuppose one has a set ``\\\\left \\\\{ \\\\mathbf{m}_n \\\\right \\\\}_{n = 1}^{N} `` of\nCartesian points which are represented by homogeneous coordinates.\nLet\n```math\n\\\\overline{\\\\mathbf{m}} = \\\\frac{1}{N} \\\\sum_{n = 1}^{N} \\\\mathbf{m}_n\n\\\\quad \\\\text{and} \\\\quad\n\\\\sigma = \\\\left( \\\\frac{1}{d \\\\times n} \\\\sum_{n = 1}^{N} \\\\left \\\\| \\\\mathbf{m}_n -\n\\\\overline{\\\\mathbf{m}} \\\\right \\\\|^{2} \\\\right)^{1/2}\n```\nrepresent the centroid of the points and the root-mean-square distance of the\npoints to the centroid, respectively.\n\nThis function returns the matrix\n```math\n\\\\mathbf{T} =\n\\\\begin{bmatrix}\n\\\\sigma^{-1} & 0 & 0 & \\\\ldots & -\\\\sigma^{-1} \\\\overline{m}_1 \\\\\\\\\n 0 & \\\\sigma^{-1} & 0 & \\\\ldots & -\\\\sigma^{-1} \\\\overline{m}_2 \\\\\\\\\n 0 & 0 & \\\\ddots & 0 & \\\\vdots \\\\\\\\\n \\\\vdots & \\\\vdots & 0 & \\\\sigma^{-1} & -\\\\sigma^{-1} \\\\overline{m}_d \\\\\\\\\n 0 & 0 & 0 & 0 & 1\n\\\\end{bmatrix}\n```\nsuch that a transformed point ``\\\\tilde{\\\\mathbf{m}}_n = \\\\mathbf{T} \\\\mathbf{m}_n``\nhas a root-mean-square distance to the origin of a new coordinate system\nequal to ``\\\\sqrt{d}``.\n\n\n\"\"\"\nfunction hartley_transformation(ℳ::Vector{T})::SMatrix where T <:AbstractArray\n if isempty(ℳ)\n throw(ArgumentError(\"Array cannot be empty.\"))\n end\n npts = length(ℳ)\n ndim = length(ℳ[1])\n 𝐜 = centroid(ℳ)\n σ = root_mean_square(ℳ, 𝐜)\n σ⁻¹ = 1 / σ\n 𝐓 = SMatrix{ndim+1,ndim+1,Float64, (ndim+1)^2}([σ⁻¹*Matrix{Float64}(I,ndim,ndim) -σ⁻¹*𝐜 ; zeros(1,ndim) 1.0])\nend\n\nfunction centroid(positions::Vector{T}) where T <: AbstractArray\n x = zeros(T)\n for pos ∈ positions\n x = x + pos\n end\n return x / length(positions)\nend\n\nfunction root_mean_square(ℳ::Vector{T}, 𝐜::T ) where T <: AbstractArray\n total = 0.0\n npts = length(ℳ)\n ndim = length(ℳ[1])\n for 𝐦 ∈ ℳ\n total = total + ∑((𝐦-𝐜).^2)\n end\n σ = √( (1/(npts*ndim)) * total)\nend\n\n\"\"\"\n hartley_normalization(pts::AbstractArray{T}) where T<:HomogeneousPoint\n\nMaps a set of ``d``-dimensional Cartesian points which are represented by\n``\\\\text{length-}(d+1)`` homogeneous coordinates into a data-dependent coordinate system.\nIn the data-dependent coordinate system the origin is the center of mass\n(centroid) of the points and the root-mean-square distance of the points to the\norigin is equal to ``\\\\sqrt{d}``.\n\n# Details\n\nA point in ``\\\\mathbb{R}^d`` with\nCartesian coordinates ``\\\\left(m_1, m_2, \\\\ldots, m_d \\\\right)`` can also be\nexpressed in homogeneous coordinates with the vector ``\\\\mathbf{m} =\n\\\\left[m_1, m_2, \\\\ldots, m_d , 1 \\\\right]^\\\\top``.\n\nSuppose one has a set ``\\\\left \\\\{ \\\\mathbf{m}_n \\\\right \\\\}_{n = 1}^{N} `` of\nCartesian points which are represented by homogeneous coordinates.\nLet\n```math\n\\\\overline{\\\\mathbf{m}} = \\\\frac{1}{N} \\\\sum_{n = 1}^{N} \\\\mathbf{m}_n\n\\\\quad \\\\text{and} \\\\quad\n\\\\sigma = \\\\left( \\\\frac{1}{d \\\\times n} \\\\sum_{n = 1}^{N} \\\\left \\\\| \\\\mathbf{m}_n -\n\\\\overline{\\\\mathbf{m}} \\\\right \\\\|^{2} \\\\right)^{1/2}\n```\nrepresent the centroid of the points and the root-mean-square distance of the\npoints to the centroid, respectively.\n\nThis function returns a new set of points ``\\\\left \\\\{ \\\\tilde{\\\\mathbf{m}}_n \\\\right \\\\}_{n = 1}^{N} ``\nwhere ``\\\\tilde{\\\\mathbf{m}}_n = \\\\mathbf{T} \\\\mathbf{m}_n`` for each ``n``, and\n```math\n\\\\mathbf{T} =\n\\\\begin{bmatrix}\n\\\\sigma^{-1} & 0 & 0 & \\\\ldots & -\\\\sigma^{-1} \\\\overline{m}_1 \\\\\\\\\n 0 & \\\\sigma^{-1} & 0 & \\\\ldots & -\\\\sigma^{-1} \\\\overline{m}_2 \\\\\\\\\n 0 & 0 & \\\\ddots & 0 & \\\\vdots \\\\\\\\\n \\\\vdots & \\\\vdots & 0 & \\\\sigma^{-1} & -\\\\sigma^{-1} \\\\overline{m}_d \\\\\\\\\n 0 & 0 & 0 & 0 & 1\n\\\\end{bmatrix}.\n```\nThese new points have the property that their root-mean-square distance to\nthe origin of the coordinate system is equal to ``\\\\sqrt{d}``.\n\n\n\"\"\"\nfunction hartley_normalization(ℳ::Vector{<:AbstractArray})\n 𝒪, 𝐓 = hartley_normalization!(copy(ℳ))\nend\n\nfunction hartley_normalization!(ℳ::Vector{<:AbstractArray})\n 𝐓 = hartley_transformation(ℳ)\n map!(ℳ , ℳ) do 𝐦\n hom⁻¹(𝐓 * hom(𝐦))\n end\n ℳ, 𝐓\nend\n", "meta": {"hexsha": "aaf80cd83f2583e2e2d20843cccc53c3e68c1c0b", "size": 5101, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/data_normalization/hartley_transformation.jl", "max_stars_repo_name": "JuliaTagBot/MultipleViewGeometry.jl", "max_stars_repo_head_hexsha": "cafd7f61f30258f804ac31c5f9648b54edc6b347", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-29T18:45:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-29T18:45:09.000Z", "max_issues_repo_path": "src/data_normalization/hartley_transformation.jl", "max_issues_repo_name": "JuliaTagBot/MultipleViewGeometry.jl", "max_issues_repo_head_hexsha": "cafd7f61f30258f804ac31c5f9648b54edc6b347", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-03-17T16:03:51.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-18T09:13:22.000Z", "max_forks_repo_path": "src/data_normalization/hartley_transformation.jl", "max_forks_repo_name": "JuliaTagBot/MultipleViewGeometry.jl", "max_forks_repo_head_hexsha": "cafd7f61f30258f804ac31c5f9648b54edc6b347", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:18:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-27T20:13:09.000Z", "avg_line_length": 38.6439393939, "max_line_length": 113, "alphanum_fraction": 0.5792981768, "num_tokens": 1720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810407096792, "lm_q2_score": 0.8519527944504227, "lm_q1q2_score": 0.8071239250419608}} {"text": "@doc raw\"\"\"\n SigmoidKernel([a=1 [,c=1]])\n\nThe Sigmoid Kernel is given by:\n```\n κ(x,y) = tanh(a⋅xᵀy + c)\n```\n\n# Examples\n\n```jldoctest; setup = :(using MLKernels)\njulia> SigmoidKernel()\nSigmoidKernel{Float64}(1.0,1.0)\n\njulia> SigmoidKernel(0.5f0)\nSigmoidKernel{Float32}(0.5,1.0)\n\njulia> SigmoidKernel(0.5f0, 0.5)\nSigmoidKernel{Float64}(0.5,0.5)\n```\n\"\"\"\nstruct SigmoidKernel{T<:AbstractFloat} <: Kernel{T}\n a::T\n c::T\n function SigmoidKernel{T}(a::Real=T(1), c::Real=T(1)) where {T<:AbstractFloat}\n @check_args(SigmoidKernel, a, a > zero(T), \"a > 0\")\n @check_args(SigmoidKernel, c, c >= zero(T), \"c ≧ 0\")\n return new{T}(a, c)\n end\nend\nfunction SigmoidKernel(a::T₁=1.0, c::T₂=T₁(1)) where {T₁<:Real,T₂<:Real}\n SigmoidKernel{promote_float(T₁,T₂)}(a,c)\nend\n\n@inline basefunction(::SigmoidKernel) = ScalarProduct()\n\n@inline kappa(κ::SigmoidKernel{T}, xᵀy::T) where {T} = tanh(κ.a*xᵀy + κ.c)\n\nfunction convert(::Type{K}, κ::SigmoidKernel) where {K>:SigmoidKernel{T}} where T\n return SigmoidKernel{T}(κ.a, κ.c)\nend", "meta": {"hexsha": "3a83f76ad82a7edc393c5722d97b028f8e4ccb72", "size": 1052, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernelfunctions/sigmoid.jl", "max_stars_repo_name": "trthatcher/Kernels.jl", "max_stars_repo_head_hexsha": "c95971efc89b76f05e39cbdf5213507fe4351d63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 85, "max_stars_repo_stars_event_min_datetime": "2015-04-21T16:40:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-24T00:25:21.000Z", "max_issues_repo_path": "src/kernelfunctions/sigmoid.jl", "max_issues_repo_name": "trthatcher/Kernels.jl", "max_issues_repo_head_hexsha": "c95971efc89b76f05e39cbdf5213507fe4351d63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 81, "max_issues_repo_issues_event_min_datetime": "2015-04-22T16:33:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-03T14:32:44.000Z", "max_forks_repo_path": "src/kernelfunctions/sigmoid.jl", "max_forks_repo_name": "trthatcher/Kernels.jl", "max_forks_repo_head_hexsha": "c95971efc89b76f05e39cbdf5213507fe4351d63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 43, "max_forks_repo_forks_event_min_datetime": "2015-04-22T15:59:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-21T19:02:01.000Z", "avg_line_length": 25.6585365854, "max_line_length": 82, "alphanum_fraction": 0.641634981, "num_tokens": 407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9252299509069105, "lm_q2_score": 0.8723473630627235, "lm_q1q2_score": 0.8071219079002966}} {"text": "export TwoParabolasConstrained, TwoParabolasUnconstrained;\n\nfunction two_parabolas_doc_str(symb) \n return \"\"\"\n The canonical two parobola problem with two objectives taking two\n decision variables.\n\n ```math\n \\\\min_{𝐱 ∈ X } \n \\\\begin{bmatrix}\n (x₁ - 1)² + (x₂ - 1)² \\\\\\\\\n (x₁ + 1)² + (x₂ + 1)²\n \\\\end{bmatrix},\n ```\n\n where ``X = $(symb)``.\n \"\"\"\nend\n\n@doc two_parabolas_doc_str(\"ℝ²\") \nstruct TwoParabolasUnconstrained <: MOP end;\n\n@doc two_parabolas_doc_str(\"[\\\\mathrm{lb}, \\\\mathrm{ub}]^2\") \n@with_kw struct TwoParabolasConstrained <: MOP\n lb :: Union{R,Vector{R}} where R<:Real = -4.0;\n ub :: Union{R,Vector{R}} where R<:Real = 4.0;\n end;\n\nnum_vars( ::Union{TwoParabolasUnconstrained, TwoParabolasConstrained} ) = 2;\nnum_objectives( ::Union{TwoParabolasUnconstrained, TwoParabolasConstrained} ) = 2;\n\nfunction get_objectives( ::Union{TwoParabolasUnconstrained, TwoParabolasConstrained} )\n f1( x :: Vector{R} where R<:Real ) = sum( ( x .- 1.0 ).^2 );\n f2( x :: Vector{R} where R<:Real ) = sum( ( x .+ 1.0 ).^2 );\n return [f1, f2]\nend\n\nfunction constraints( mop::TwoParabolasConstrained )\n Box( \n isa( mop.lb, Real) ? fill( mop.lb, num_vars(mop) ) : mop.lb,\n isa( mop.ub, Real) ? fill( mop.ub, num_vars(mop) ) : mop.ub,\n )\nend\n\nfunction get_pareto_set( mop ::Union{TwoParabolasUnconstrained, TwoParabolasConstrained} )\n return SamplingFunction( mop, :ParetoSet, [:regular, :random] );\nend\n\nfunction get_pareto_front( mop ::Union{TwoParabolasUnconstrained, TwoParabolasConstrained} )\n return SamplingFunction( mop, :ParetoFront, [:regular, :random] );\nend \n\nfunction get_points( sample_func :: SamplingFunction, :: Union{TwoParabolasUnconstrained, TwoParabolasConstrained},\n ::Val{:ParetoSet}, num_points :: Int; method = :regular )\n \n if method == :regular\n x_range = num_points == 1 ? [0.0,] : range(-1.0, 1.0; length = num_points );\n elseif method == :random\n x_range = [ -1.0 + 2 * rand() for i = 1 : num_points ]\n end\n return [ [x;x] for x in x_range ]\nend\n\nfunction get_points( sample_func :: SamplingFunction, mop :: Union{TwoParabolasUnconstrained, TwoParabolasConstrained},\n ::Val{:ParetoFront}, num_points :: Int; method = :regular )\n\n pset = get_points( sample_func, mop, Val(:ParetoSet), num_points; method );\n F = get_vector_objective( mop );\n return F.( pset );\nend", "meta": {"hexsha": "7d8510a36d2468126e2cc791dc0843c12c524a6e", "size": 2427, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/two_parabolas.jl", "max_stars_repo_name": "manuelbb-upb/MultiObjectiveProblems.jl", "max_stars_repo_head_hexsha": "b46db5f48db1271799468d3a43086fdbe1db6da8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/two_parabolas.jl", "max_issues_repo_name": "manuelbb-upb/MultiObjectiveProblems.jl", "max_issues_repo_head_hexsha": "b46db5f48db1271799468d3a43086fdbe1db6da8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/two_parabolas.jl", "max_forks_repo_name": "manuelbb-upb/MultiObjectiveProblems.jl", "max_forks_repo_head_hexsha": "b46db5f48db1271799468d3a43086fdbe1db6da8", "max_forks_repo_licenses": ["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.6714285714, "max_line_length": 119, "alphanum_fraction": 0.6547177585, "num_tokens": 791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.900529786117893, "lm_q2_score": 0.8962513752119936, "lm_q1q2_score": 0.8071010592275241}} {"text": "# p26.m - eigenvalues of 2nd-order Chebyshev diff. matrix\n\nN = 60; (D,x) = cheb(N); D2 = D^2; D2 = D2[2:N,2:N];\n(lam,V) = eig(D2);\nii = sortperm(-lam); e = lam[ii]; V = V[:,ii];\n\n# Plot eigenvalues:\nclf(); axes([.1, .62, .8, .3]);\nloglog(-e,\".\",markersize=4); ylabel(\"eigenvalue\");\ntitle(\"N = $N max |λ| = $(signif(maximum(-e)/N^4,5)) \\$N^4\\$\");\nsemilogy(2*N/pi*[1,1],[1,1e6],\"--r\");\ntext(2.1*N/pi,24,\"2π / N\",fontsize=12);\n\n# Plot eigenmodes N/4 (physical) and N (nonphysical):\nvN4 = [0; V[:,Int(N/4-1)]; 0];\nxx = -1:.01:1; vv = polyval(polyfit(x,vN4),xx);\naxes([.1, .36, .8, .15]); plot(xx,vv);\nplot(x,vN4,\"k.\",markersize=4); title(\"eigenmode N/4\");\nvN = V[:,N-1];\naxes([.1, .1, .8, .15]);\nsemilogy(x[2:N],abs.(vN)); axis([-1,1,5e-6,1]);\nplot(x[2:N],abs.(vN),\"k.\",markersize=4);\ntitle(\"absolute value of eigenmode N (log scale)\");\n", "meta": {"hexsha": "0065d417a6f0719a367f7295d9d7fbf83b0a30fa", "size": 842, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/scripts/p26.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/p26.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/p26.jl", "max_forks_repo_name": "tobydriscoll/SpectralMethodsTrefethen.jl", "max_forks_repo_head_hexsha": "633da18bcbaa169c2e23401e5a7536c18bdc5511", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0833333333, "max_line_length": 69, "alphanum_fraction": 0.554631829, "num_tokens": 366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660936744719, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.8070004079504043}} {"text": "\r\n\r\nfunction smallest_prime_factor(n::Int64)\r\n\r\n\ti=2;\r\n\twhile i*i<=n\r\n\t\tif( n%i==0)\r\n\t\t return i\r\n\t\tend\r\n\t\ti=i+1\r\n\tend\r\n\treturn n\r\nend\r\n\r\nfunction compute()\r\n\tn=600851475143\r\n\twhile true\r\n\t\tp=smallest_prime_factor(n)\r\n\t\tif p -sol(t,idxs=2)\n opt = Optim.optimize(f,0.0,tss)\n pk = -opt.minimum\n pk\nend\n\n\nplot(β_grid, peak_infected,xlabel=\"β\",ylabel=\"Peak infected\",legend=false)\n\n\npk = peak_infected.(β)\npk_surrogate = RadialBasis(β,pk,lb,ub,rad = cubicRadial)\nsurrogate_optimize(peak_infected,\n SRBF(),\n lb,\n ub,\n pk_surrogate,\n sampler;\n maxiters=1000,\n num_new_samples=1000)\npk_test = peak_infected.(β_test)\npk_test_pred = pk_surrogate.(β_test);\n\n\nl = @layout [a b]\npl1 = plot(β_grid,peak_infected.(β_grid),color=:red,label=\"Model\",xlabel=\"β\",ylabel=\"Peak infected\",legend=:right)\nscatter!(pl1, β_test,pk_test_pred,color=:blue,label=\"Surrogate\")\npl2 = scatter(pk_test,pk_test_pred,color=:blue,legend=false,xlabel=\"Peak infected\",ylabel=\"Surrogate peak infected\")\nPlots.abline!(pl2,1.0,0.0)\nplot(pl1,pl2,layout=l)\n\n\n@benchmark peak_infected(0.0005)\n\n\n@benchmark pk_surrogate(0.0005)\n\n\npeak_time = function(β)\n p = prob_ode.p\n p[1] = β\n prob = remake(prob_ode;p=p)\n sol = solve(prob, ROS34PW3(),callback=cb_ss)\n tss = sol.t[end]\n f = (t) -> -sol(t,idxs=2)\n opt = Optim.optimize(f,0.0,tss)\n pt = opt.minimizer\n pt\nend\n\n\nplot(β_grid,peak_time,xlabel=\"β\",ylabel=\"Peak time\",legend=false)\n\n\npt = peak_time.(β)\npt_surrogate = RadialBasis(β,pt,lb,ub,rad = cubicRadial)\nsurrogate_optimize(peak_time,\n SRBF(),\n lb,\n ub,\n pt_surrogate,\n sampler;\n maxiters=1000,\n num_new_samples=1000)\npt_test = peak_time.(β_test)\npt_test_pred = pt_surrogate.(β_test);\n\n\nl = @layout [a b]\npl1 = plot(β_grid,peak_time.(β_grid),color=:red,label=\"Model\",xlabel=\"β\",ylabel=\"Peak time\",legend=:right)\nscatter!(pl1, β_test,pt_test_pred,color=:blue,label=\"Surrogate\")\npl2 = scatter(pt_test,pt_test_pred,color=:blue,legend=false,xlabel=\"Peak time\",ylabel=\"Surrogate peak time\")\nPlots.abline!(pl2,1.0,0.0)\nplot(pl1,pl2,layout=l)\n\n\n@benchmark peak_time(0.0005)\n\n\n@benchmark pt_surrogate(0.0005)\n\n", "meta": {"hexsha": "04b8a82780a303cc5734c5efc3d20b307467f06e", "size": 4513, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/ode_surrogate_1d_1d/ode_surrogate_1d_1d.jl", "max_stars_repo_name": "Song921012/sir-julia", "max_stars_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "script/ode_surrogate_1d_1d/ode_surrogate_1d_1d.jl", "max_issues_repo_name": "Song921012/sir-julia", "max_issues_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/ode_surrogate_1d_1d/ode_surrogate_1d_1d.jl", "max_forks_repo_name": "Song921012/sir-julia", "max_forks_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8019323671, "max_line_length": 116, "alphanum_fraction": 0.6383780191, "num_tokens": 1436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897475985936, "lm_q2_score": 0.857768108626046, "lm_q1q2_score": 0.8069794424124208}} {"text": "export latin, check_latin\n\nfunction funky_mod(i::Int, n::Int)\n v = mod(i,n)\n return v==0 ? n : v\nend\n\n\n\"\"\"\n`latin(n)` returns a simple `n`-by-`n` Latin square. More generally,\n`latin(n,a,b)` generates a Latin square whose `i,j`-entry is\n`a*(i-1) + b*(j-1) + 1` (wrapping around `n`, of course).\n\n*Note*: If parameters `n,a,b` do not generate a legitimate Latin square\nan error is thrown.\n\"\"\"\nfunction latin(n::Int, a::Int=1, b::Int=1)::Matrix{Int}\n A = zeros(Int,n,n)\n for i=1:n\n for j=1:n\n A[i,j] = funky_mod(a*(i-1) + b*(j-1) + 1, n)\n end\n end\n @assert check_latin(A) \"Parameters n=$n, a=$a, and b=$b do not generate a Latin square\"\n return A\nend\n\n\"\"\"\n`check_latin(A)` checks if `A` is a Latin square.\n(The entries must be chosen from `1:n` when `A` is an `n`-by-`n`\nmatrix).\n\"\"\"\nfunction check_latin(A::Matrix{Int})::Bool\n r,c = size(A)\n if r != c\n return false\n end\n\n vals = collect(1:r)\n\n # check rows\n for i=1:r\n if sort(A[:,i]) != vals\n return false\n end\n end\n\n # check cols\n for i=1:r\n if sort(A[i,:]) != vals\n return false\n end\n end\n\n return true\nend\n", "meta": {"hexsha": "0e99bbef4d73ba2dbc4e0ecca4fd587f384598f5", "size": 1196, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/latin.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/LatinSquares.jl-c3c424ec-ae8f-5049-b7bf-f9296ef684c8", "max_stars_repo_head_hexsha": "0ed5548a237340dea8a8856679685e3fe753d3fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/latin.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/LatinSquares.jl-c3c424ec-ae8f-5049-b7bf-f9296ef684c8", "max_issues_repo_head_hexsha": "0ed5548a237340dea8a8856679685e3fe753d3fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/latin.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/LatinSquares.jl-c3c424ec-ae8f-5049-b7bf-f9296ef684c8", "max_forks_repo_head_hexsha": "0ed5548a237340dea8a8856679685e3fe753d3fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.9824561404, "max_line_length": 91, "alphanum_fraction": 0.5576923077, "num_tokens": 399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873763, "lm_q2_score": 0.8774768002981829, "lm_q1q2_score": 0.8069649934062166}} {"text": "mat = [\n 75 00 00 00 00 00 00 00 00 00 00 00 00 00 00;\n 95 64 00 00 00 00 00 00 00 00 00 00 00 00 00;\n 17 47 82 00 00 00 00 00 00 00 00 00 00 00 00;\n 18 35 87 10 00 00 00 00 00 00 00 00 00 00 00;\n 20 04 82 47 65 00 00 00 00 00 00 00 00 00 00;\n 19 01 23 75 03 34 00 00 00 00 00 00 00 00 00;\n 88 02 77 73 07 63 67 00 00 00 00 00 00 00 00;\n 99 65 04 28 06 16 70 92 00 00 00 00 00 00 00;\n 41 41 26 56 83 40 80 70 33 00 00 00 00 00 00;\n 41 48 72 33 47 32 37 16 94 29 00 00 00 00 00;\n 53 71 44 65 25 43 91 52 97 51 14 00 00 00 00;\n 70 11 33 28 77 73 17 78 39 68 17 57 00 00 00;\n 91 71 52 38 17 14 91 43 58 50 27 29 48 00 00;\n 63 66 04 68 89 53 67 30 73 16 69 87 40 31 00;\n 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23\n]\n\nn, m = size(mat)\nfor i = 2:n\n for j = 1:i\n mat[i,j] += max(mat[i-1,j], j>1 ? mat[i-1,j-1] : 0)\n end\nend\nprintln(maximum(mat[end,:]))\n", "meta": {"hexsha": "fb2d3a550255c115fbd1a434beeb0458b47059b2", "size": 868, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ans18.jl", "max_stars_repo_name": "sujimodern/project-euler-jl", "max_stars_repo_head_hexsha": "7abbf39014cc39b39ed84ebf698d45d09fadea1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ans18.jl", "max_issues_repo_name": "sujimodern/project-euler-jl", "max_issues_repo_head_hexsha": "7abbf39014cc39b39ed84ebf698d45d09fadea1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ans18.jl", "max_forks_repo_name": "sujimodern/project-euler-jl", "max_forks_repo_head_hexsha": "7abbf39014cc39b39ed84ebf698d45d09fadea1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3846153846, "max_line_length": 55, "alphanum_fraction": 0.6036866359, "num_tokens": 547, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425245706047, "lm_q2_score": 0.8774767874818408, "lm_q1q2_score": 0.806964968091904}} {"text": "using CSV, Distributions, HypothesisTests\n\ndata1 = CSV.read(\"../data/machine1.csv\", header=false)[:,1]\ndata2 = CSV.read(\"../data/machine2.csv\", header=false)[:,1]\nxBar1, n1 = mean(data1), length(data1)\nxBar2, n2 = mean(data2), length(data2)\nsig1, sig2 = 1.2, 1.6\ndelta0 = 0\n\ntestStatistic = ( xBar1-xBar2 - delta0 ) / ( sqrt( sig1^2 / n1 + sig2^2 / n2 ) )\npVal = 2*ccdf(Normal(), abs(testStatistic))\n\nprintln(\"Sample mean machine 1: \",xBar1)\nprintln(\"Sample mean machine 2: \",xBar2)\nprintln(\"Manually calculated test statistc: \", testStatistic)\nprintln(\"Manually calculated p-value: \", pVal)\n", "meta": {"hexsha": "afe5cfce70d691bbc8b860782cb3b4bfbae881cd", "size": 592, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "7_chapter/infMeanDiffVarKnown.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/infMeanDiffVarKnown.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/infMeanDiffVarKnown.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 34.8235294118, "max_line_length": 80, "alphanum_fraction": 0.6925675676, "num_tokens": 200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9609517095103498, "lm_q2_score": 0.8397339716830605, "lm_q1q2_score": 0.8069437956227526}} {"text": "# https://www.cs.cornell.edu/gries/Logic/Axioms.html\n# The axioms of calculational propositional logic C are listed in the order in\n# which they are usually presented and taught. Note that equivalence comes\n# first. Note also that, after the first axiom, we take advantage of\n# associativity of equivalence and write sequences of equivalences without\n# parentheses. We use == for equivalence, | for disjunction, & for conjunction,\n# ~ for negation (not), => for implication, and <= for consequence.\n#\n# Associativity of ==: ((p == q) == r) == (p == (q == r))\n# Symmetry of ==: p == q == q == p\n# Identity of ==: true == q == q\n#\n# Definition of false: false == ~true\n# Distributivity of not: ~(p == q) == ~p == q\n# Definition of =/=: (p =/= q) == ~(p == q)\n#\n# Associativity of |: (p | q) & r == p | (q | r)\n# Symmetry of |: p | q == q | p\n# Idempotency of |: p | p == p\n# Distributivity of |: p |(q == r) == p | q == p | r\n# Excluded Middle: p | ~p\n#\n# Golden rule: p & q == p == q == p | q\n#\n# Implication: p => q == p | q == q\n# Consequence: p <= q == q => p\n\n# Metatheory.options[:printiter] = true\n\nusing Metatheory\n\ncalc = @theory begin\n ((p == q) == r) == (p == (q == r))\n (p == q) == (q == p)\n (q == q) => true\n\n ¬(p == q) == (¬(p) == q)\n (p != q) == ¬(p == q)\n\n ((p ∨ q) ∨ r) == (p ∨ (q ∨ r))\n (p ∨ q) == (q ∨ p)\n (p ∨ p) => p\n (p ∨ (q == r)) == (p ∨ q == p ∨ r)\n (p ∨ ¬(p)) => true\n\n # DeMorgan\n ¬(p ∨ q) == (¬p ∧ ¬q)\n ¬(p ∧ q) == (¬p ∨ ¬q)\n\n (p ∧ q) == ((p == q) == p ∨ q)\n\n (p => q) == ((p ∨ q) == q)\n # (p => q) == (¬p ∨ q)\n # (p <= q) => (q => p)\nend\n\nfold = @theory begin\n (p::Bool == q::Bool) |> (p == q)\n (p::Bool ∨ q::Bool) |> (p || q)\n (p::Bool => q::Bool) |> ((p || q) == q)\n (p::Bool ∧ q::Bool) |> (p && q)\n ¬(p::Bool) |> (!p)\nend\n\n# t = or_alg ∪ and_alg ∪ neg_alg ∪ demorgan ∪ and_or_distrib ∪\n# absorption ∪ calc\n\nt = calc ∪ fold\n\ng = EGraph(:(((¬p == p) == false)))\nsaturate!(g, t)\nextract!(g, astsize)\n\n@test @areequal t true ((¬p == p) == false)\n@test @areequal t true ((¬p == ¬p) == true)\n@test @areequal t true ((¬p ∨ ¬p) == ¬p) (¬p ∨ p) ¬(¬p ∧ p)\n@test @areequal t true ((p => (p ∨ p)) == true)\nparams = SaturationParams(timeout=12, eclasslimit=10000, schedulerparams=(1000, 5))\n\n@test areequal(t, true, :(((p => (p ∨ p)) == ((¬(p) ∧ q) => q)) == true); params=params)\n\n# Frege's theorem\n# params = SaturationParams(timeout=12, eclasslimit=15000, scheduler=Schedulers.ScoredScheduler)\n# params = SaturationParams(timeout=12, eclasslimit=15000, schedulerparams=(500, 2))\n@test_skip areequal(t, true, :((p => (q => r)) => ((p => q) => (p => r))); params=params)\n\n# Demorgan's\n@test @areequal t true (¬(p ∨ q) == (¬p ∧ ¬q))\n\n# Consensus theorem\n# @test_skip\nareequal(t, :((x ∧ y) ∨ (¬x ∧ z) ∨ (y ∧ z)), :((x ∧ y) ∨ (¬x ∧ z)); params=params)\n\n", "meta": {"hexsha": "4f6095c4a656a8d099b1d4c7835f8cc9d62bd0d7", "size": 3059, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/logic/test_calculational_logic.jl", "max_stars_repo_name": "jlperla/Metatheory.jl", "max_stars_repo_head_hexsha": "f69d60097157ef0235ffc641af77d50676b5e8a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/logic/test_calculational_logic.jl", "max_issues_repo_name": "jlperla/Metatheory.jl", "max_issues_repo_head_hexsha": "f69d60097157ef0235ffc641af77d50676b5e8a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/logic/test_calculational_logic.jl", "max_forks_repo_name": "jlperla/Metatheory.jl", "max_forks_repo_head_hexsha": "f69d60097157ef0235ffc641af77d50676b5e8a1", "max_forks_repo_licenses": ["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.5425531915, "max_line_length": 96, "alphanum_fraction": 0.474338019, "num_tokens": 1116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947086083138, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.8069430296392993}} {"text": "using Mods, Primes, SimpleGraphs, LinearAlgebraX\n\n\"\"\"\n`generate_points(p::Int)` generates the homogeneous coordinates of the \npoints in a finite projective plane of prime order `p`.\n\"\"\"\nfunction generate_points(p::Integer)::Vector{HVector}\n if ~isprime(p)\n error(\"Modulus $p is not prime\")\n end\n\n n = p * p + p + 1\n A = Array{HVector}(undef, n)\n count = 1\n\n # case c=1\n for a = 0:p-1\n for b = 0:p-1\n x = Mod{p}.([a, b, 1])\n A[count] = HVector(x)\n count += 1\n end\n end\n\n # case c=0, b=1\n for a = 0:p-1\n x = Mod{p}.([a, 1, 0])\n A[count] = HVector(x)\n count += 1\n end\n\n A[count] = HVector(Mod{p}(1), 0, 0)\n\n return A\nend\n\n\"\"\"\n`incidence_matrix(p::Int)` creates the point/line incidence matrix \nof a finite projective plane of prime order `p`.\n\"\"\"\nfunction incidence_matrix(p::Int)::Matrix\n pts = generate_points(p)\n n = p*p + p + 1\n A = zeros(Int,n,n)\n for u = 1:n\n P = pts[u]\n for v = 1:n\n Q = pts[v]\n if dot(P,Q)==0\n A[u,v] = 1\n end\n end\n end\n return A\nend\n\n\"\"\"\n`incidence_graph(p::Int)` creates the bipartite point-line \nincidence graph of a finite projective plane of prime order `p`.\n\"\"\"\nfunction incidence_graph(p::Int)::SimpleGraph{Int}\n M = incidence_matrix(p)\n r,c = size(M)\n A = [ zeros(r,c) M; copy(M') zeros(r,c) ]\n G = SimpleGraph(A)\nend \n\nfunction incidence_hypergraph(p::Int)::SimpleHypergraph\n VV = generate_points(p)\n H = SimpleHypergraph{HVector{Mod{p}}}()\n for v in VV\n add!(H,v)\n end \n\n for v in VV \n S = [ w for w in VV if dot(v,w)==0 ]\n add!(H,Set(S))\n end \n\n return H \nend ", "meta": {"hexsha": "167501a58b936c2bd0a6828756ff5e3b49fcd115", "size": 1750, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "extras/projective.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/projective.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/projective.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": 21.6049382716, "max_line_length": 71, "alphanum_fraction": 0.5445714286, "num_tokens": 555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377261041521, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.8069216416926743}} {"text": "\"\"\"\n`assemble_system!` - assemble the linear system for solving\n\"\"\"\nfunction assemble_system!(problem::FiniteDifferenceBVPProblem{TF, TBCL, TBCR}) where {TF<:AbstractArray, TBCL<:DirichletBC, TBCR<:DirichletBC}\n\n # build first row\n problem.A[1,1] = 2/problem.Δx^2;\n problem.A[1,2] = -1/problem.Δx^2;\n # build rows 2-n-1\n for i in 2:problem.n-1\n problem.A[i,i-1] = -1/problem.Δx^2;\n problem.A[i,i] = 2/problem.Δx^2;\n problem.A[i,i+1] = -1/problem.Δx^2;\n end\n # build row n\n problem.A[problem.n,problem.n-1] = -1/problem.Δx^2;\n problem.A[problem.n,problem.n] = 2/problem.Δx^2;\n\n # build rhs\n @. problem.rhs = problem.f;\n problem.rhs[1] += problem.left_bc.u_bc/problem.Δx^2\n problem.rhs[problem.n] += problem.right_bc.u_bc/problem.Δx^2\n\n problem\nend\n\nfunction assemble_system!(problem::FiniteDifferenceBVPProblem{TF, TBCL, TBCR}) where {TF<:Function, TBCL<:DirichletBC, TBCR<:DirichletBC}\n\n # build first row\n problem.A[1,1] = 2/problem.Δx^2;\n problem.A[1,2] = -1/problem.Δx^2;\n # build rows 2-n-1\n for i in 2:problem.n-1\n problem.A[i,i-1] = -1/problem.Δx^2;\n problem.A[i,i] = 2/problem.Δx^2;\n problem.A[i,i+1] = -1/problem.Δx^2;\n end\n # build row n\n problem.A[problem.n,problem.n-1] = -1/problem.Δx^2;\n problem.A[problem.n,problem.n] = 2/problem.Δx^2;\n\n # build rhs\n @. problem.rhs = problem.f(problem.x);\n problem.rhs[1] += problem.left_bc.u_bc/problem.Δx^2\n problem.rhs[problem.n] += problem.right_bc.u_bc/problem.Δx^2\n\n problem\nend\n\nfunction assemble_system!(problem::FiniteDifferenceBVPProblem{TF, TBCL, TBCR}) where {TF<:AbstractArray, TBCL<:NeumannBC, TBCR<:NeumannBC}\n\n # build first row\n problem.A[1,1] = 1/problem.Δx^2;\n problem.A[1,2] = -1/problem.Δx^2;\n # build rows 2-n+1\n for i in 2:problem.n+1\n problem.A[i,i-1] = -1/problem.Δx^2;\n problem.A[i,i] = 2/problem.Δx^2;\n problem.A[i,i+1] = -1/problem.Δx^2;\n end\n # build row n+2\n problem.A[end,end-1] = -1/problem.Δx^2;\n problem.A[end,end] = 1/problem.Δx^2;\n\n # build rhs\n @. problem.rhs[2:end-1] = problem.f;\n problem.rhs[1] = -problem.left_bc.v_bc/problem.Δx\n problem.rhs[end] = problem.right_bc.v_bc/problem.Δx\n\n problem\nend\n\nfunction assemble_system!(problem::FiniteDifferenceBVPProblem{TF, TBCL, TBCR}) where {TF<:Function, TBCL<:NeumannBC, TBCR<:NeumannBC}\n\n # build first row\n problem.A[1,1] = 1/problem.Δx^2;\n problem.A[1,2] = -1/problem.Δx^2;\n # build rows 2-n+1\n for i in 2:problem.n+1\n problem.A[i,i-1] = -1/problem.Δx^2;\n problem.A[i,i] = 2/problem.Δx^2;\n problem.A[i,i+1] = -1/problem.Δx^2;\n end\n # build row n+2\n problem.A[end,end-1] = -1/problem.Δx^2;\n problem.A[end,end] = 1/problem.Δx^2;\n\n # build rhs\n @. problem.rhs[2:end-1] = problem.f(problem.x[2:end-1]);\n # problem.rhs[1] = 0.5 * problem.f(problem.x[1])-problem.left_bc.v_bc/problem.Δx\n # problem.rhs[end] = 0.5 * problem.f(problem.x[end]) + problem.right_bc.v_bc/problem.Δx\n problem.rhs[1] = -problem.left_bc.v_bc/problem.Δx\n problem.rhs[end] =problem.right_bc.v_bc/problem.Δx\n\n problem\nend\n\nfunction assemble_system!(problem::FiniteDifferenceBVPProblem{TF, TBCL, TBCR}) where {TF<:AbstractArray, TBCL<:PeriodicBC, TBCR<:PeriodicBC}\n\n # build first row\n problem.A[1,1] = 2/problem.Δx^2;\n problem.A[1,2] = -1/problem.Δx^2;\n problem.A[1,end] = -1/problem.Δx^2;\n # build rows 2-n\n for i in 2:problem.n\n problem.A[i,i-1] = -1/problem.Δx^2;\n problem.A[i,i] = 2/problem.Δx^2;\n problem.A[i,i+1] = -1/problem.Δx^2;\n end\n # build row n+1\n problem.A[end,1] = -1/problem.Δx^2;\n problem.A[end,end-1] = -1/problem.Δx^2;\n problem.A[end,end] = 2/problem.Δx^2;\n\n # build rhs\n @. problem.rhs = problem.f;\n\n problem\nend\n\nfunction assemble_system!(problem::FiniteDifferenceBVPProblem{TF, TBCL, TBCR}) where {TF<:Function, TBCL<:PeriodicBC, TBCR<:PeriodicBC}\n\n # build first row\n problem.A[1,1] = 2/problem.Δx^2;\n problem.A[1,2] = -1/problem.Δx^2;\n problem.A[1,end] = -1/problem.Δx^2;\n # build rows 2-n\n for i in 2:problem.n\n problem.A[i,i-1] = -1/problem.Δx^2;\n problem.A[i,i] = 2/problem.Δx^2;\n problem.A[i,i+1] = -1/problem.Δx^2;\n end\n # build row n+1\n problem.A[end,1] = -1/problem.Δx^2;\n problem.A[end,end-1] = -1/problem.Δx^2;\n problem.A[end,end] = 2/problem.Δx^2;\n\n # build rhs\n @. problem.rhs = problem.f(problem.x);\n\n problem\nend\n", "meta": {"hexsha": "9cecb355d367e7b964932c2579c9600438cd1eda", "size": 4548, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "BasicBVP1D/src/assembly_fd.jl", "max_stars_repo_name": "liamfdoherty/Math_540_2021", "max_stars_repo_head_hexsha": "6b84b88ca1c587650a82f5bc9351f27a518e104d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "BasicBVP1D/src/assembly_fd.jl", "max_issues_repo_name": "liamfdoherty/Math_540_2021", "max_issues_repo_head_hexsha": "6b84b88ca1c587650a82f5bc9351f27a518e104d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BasicBVP1D/src/assembly_fd.jl", "max_forks_repo_name": "liamfdoherty/Math_540_2021", "max_forks_repo_head_hexsha": "6b84b88ca1c587650a82f5bc9351f27a518e104d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8041958042, "max_line_length": 142, "alphanum_fraction": 0.6198328936, "num_tokens": 1758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377225508371, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.8069216348976038}} {"text": "function LUSolve(A::Array,B::Vector)\r\n\r\n #A = the matrix of coefficients 'A' must be squared\r\n #B = The Vector 'B' right hand side vector Vertical\r\n m,n =size(A)\r\n v = size(B,1)\r\n if m != n\r\n error(\"Matrix must be squared\")\r\n elseif m != v\r\n error(\"Vector Length must be equal to Matrix\")\r\n end\r\n\r\nL,U,P,p=DolittleLU(A)\r\n A=P*A\r\n B=P*B\r\n X=D=zeros(m)\r\n\r\n #Fordward Substitution\r\n D[1]=B[1]\r\n for i=2:m\r\n D[i]=(B[i] - (L[i,1:i-1]'*D[1:i-1]))\r\n\r\n end\r\n\r\n #Back Substitution\r\n X[m]=D[end]/U[end,end]\r\n\r\n for i=m-1:-1:1\r\n X[i]=(D[i] - (U[i,i+1:m]'*X[i+1:m]))/U[i,i]\r\n end\r\n\r\n return X\r\nend\r\n", "meta": {"hexsha": "e12636d98a08244fc6f1510c7ebe41ec2de6af24", "size": 675, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/LUSolve.jl", "max_stars_repo_name": "scuervo91/LinearSolvers.jl", "max_stars_repo_head_hexsha": "471102b870dde6cb4c3b80c976381db31198faaf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/LUSolve.jl", "max_issues_repo_name": "scuervo91/LinearSolvers.jl", "max_issues_repo_head_hexsha": "471102b870dde6cb4c3b80c976381db31198faaf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/LUSolve.jl", "max_forks_repo_name": "scuervo91/LinearSolvers.jl", "max_forks_repo_head_hexsha": "471102b870dde6cb4c3b80c976381db31198faaf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.8529411765, "max_line_length": 58, "alphanum_fraction": 0.4948148148, "num_tokens": 233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305360354472, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.8068211204188387}} {"text": "### A Pluto.jl notebook ###\n# v0.12.16\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# ╔═╡ e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, Distributions, Plots, LaTeXStrings\n\tRandom.seed!(0)\nend\n\n# ╔═╡ ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing5.19\"\n\n# ╔═╡ fa68607e-22e5-11eb-0558-c9a4d9f77426\nbegin\n\talpha, beta = 8, 2\n\tprior(lam) = pdf(Gamma(alpha, 1/beta), lam)\n\tdata = [2,1,0,0,1,0,2,2,5,2,4,0,3,2,5,0]\n\n\tlike(lam) = *([pdf(Poisson(lam),x) for x in data]...)\n\tposteriorUpToK(lam) = like(lam)*prior(lam)\nend\n\n# ╔═╡ 9ed0aafc-3afb-11eb-1f46-5bc8b9a49938\nbegin\n\tdelta = 10^-4.\n\tlamRange = 0:delta:10\n\tK = sum([posteriorUpToK(lam)*delta for lam in lamRange])\n\tposterior(lam) = posteriorUpToK(lam)/K\nend\n\n# ╔═╡ 9ed0def2-3afb-11eb-2bd0-5b8a32cba3e1\nbayesEstimate = sum([lam*posterior(lam)*delta for lam in lamRange])\n\n# ╔═╡ 9ed16ca0-3afb-11eb-332d-3ba7b882417f\nnewAlpha, newBeta = alpha + sum(data), beta + length(data)\n\n# ╔═╡ 9ed86364-3afb-11eb-0bb4-a586cc54fb14\nclosedFormBayesEstimate = mean(Gamma(newAlpha, 1/newBeta))\n\n# ╔═╡ 9ee4be2c-3afb-11eb-02df-0f03e0f586fc\nText(\"Computational Bayes Estimate: $(bayesEstimate)\")\n\n# ╔═╡ 9ee54e44-3afb-11eb-19ef-511b9b6134a4\nText(\"Closed form Bayes Estimate: $(closedFormBayesEstimate)\")\n\n# ╔═╡ 9ef09b16-3afb-11eb-1cc0-a7d27312610f\nbegin\n\tplot(lamRange, prior.(lamRange), \n\t\tc=:blue, label=\"Prior distribution\")\n\tplot!(lamRange, posterior.(lamRange), \n\t\tc=:red, label=\"Posterior distribution\", \n\t\txlims=(0, 10), ylims=(0, 1.2),\n\t\t\txlabel=L\"\\lambda\",ylabel=\"Density\")\nend\n\n# ╔═╡ 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing5.19\"\n\n# ╔═╡ Cell order:\n# ╟─ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# ╠═e077ab16-22e5-11eb-15ed-5f0654bf7328\n# ╠═e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# ╠═fa68607e-22e5-11eb-0558-c9a4d9f77426\n# ╠═9ed0aafc-3afb-11eb-1f46-5bc8b9a49938\n# ╠═9ed0def2-3afb-11eb-2bd0-5b8a32cba3e1\n# ╠═9ed16ca0-3afb-11eb-332d-3ba7b882417f\n# ╠═9ed86364-3afb-11eb-0bb4-a586cc54fb14\n# ╠═9ee4be2c-3afb-11eb-02df-0f03e0f586fc\n# ╠═9ee54e44-3afb-11eb-19ef-511b9b6134a4\n# ╠═9ef09b16-3afb-11eb-1cc0-a7d27312610f\n# ╟─475ff888-22e6-11eb-2354-09f8f40a8e12\n", "meta": {"hexsha": "37f636df4cb7ba0d8a47c6c6651ef5dc93c3a39a", "size": 2218, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/05/listing5.19.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/05/listing5.19.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/05/listing5.19.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 28.0759493671, "max_line_length": 67, "alphanum_fraction": 0.7276825969, "num_tokens": 1131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9230391558356, "lm_q2_score": 0.8740772236840656, "lm_q1q2_score": 0.8068075026844649}} {"text": "\"\"\"\n closeness_centrality(g, distmx=weights(g); normalize=true)\n\nCalculate the [closeness centrality](https://en.wikipedia.org/wiki/Centrality#Closeness_centrality)\nof the graph `g`. Return a vector representing the centrality calculated for each node in `g`.\n\n### Optional Arguments\n- `normalize=true`: If true, normalize the centrality value of each\nnode `n` by ``\\\\frac{|δ_n|}{|V|-1}``, where ``δ_n`` is the set of vertices reachable\nfrom node `n`.\n\n# Examples\n```jldoctest\njulia> using LightGraphs\n\njulia> closeness_centrality(StarGraph(5))\n5-element Array{Float64,1}:\n 1.0\n 0.5714285714285714\n 0.5714285714285714\n 0.5714285714285714\n 0.5714285714285714\n\njulia> closeness_centrality(PathGraph(4))\n4-element Array{Float64,1}:\n 0.5\n 0.75\n 0.75\n 0.5\n```\n\"\"\"\nfunction closeness_centrality(g::AbstractGraph,\n distmx::AbstractMatrix=weights(g);\n normalize=true)\n\n n_v = nv(g)\n closeness = zeros(n_v)\n\n for u in vertices(g)\n if degree(g, u) == 0 # no need to do Dijkstra here\n closeness[u] = 0.0\n else\n d = dijkstra_shortest_paths(g, u, distmx).dists\n δ = filter(x -> x != typemax(x), d)\n σ = sum(δ)\n l = length(δ) - 1\n if σ > 0\n closeness[u] = l / σ\n if normalize\n n = l / (n_v - 1)\n closeness[u] *= n\n end\n end\n end\n end\n return closeness\nend\n", "meta": {"hexsha": "f09a8aafa4c53660d5705bfd28f4d092df45ef78", "size": 1451, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/centrality/closeness.jl", "max_stars_repo_name": "SyxP/LightGraphs.jl", "max_stars_repo_head_hexsha": "6c488a872b991d99cc794f59d0ae617d5bf204a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-02-24T03:15:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-24T03:15:48.000Z", "max_issues_repo_path": "src/centrality/closeness.jl", "max_issues_repo_name": "SyxP/LightGraphs.jl", "max_issues_repo_head_hexsha": "6c488a872b991d99cc794f59d0ae617d5bf204a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/centrality/closeness.jl", "max_forks_repo_name": "SyxP/LightGraphs.jl", "max_forks_repo_head_hexsha": "6c488a872b991d99cc794f59d0ae617d5bf204a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-02-24T03:16:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-24T18:41:12.000Z", "avg_line_length": 25.0172413793, "max_line_length": 99, "alphanum_fraction": 0.6044107512, "num_tokens": 445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533126145179, "lm_q2_score": 0.8652240877899775, "lm_q1q2_score": 0.806781066813639}} {"text": "using CSV, Distributions, HypothesisTests\n\ndata = CSV.read(\"../data/machine1.csv\", header=false)[:,1]\nn = length(data)\nmu0A, mu0B = 52.2, 53\n\nxPositiveA = sum(data .> mu0A)\ntestStatisticA = max(xPositiveA, n-xPositiveA)\n\nxPositiveB = sum(data .> mu0B)\ntestStatisticB = max(xPositiveB, n-xPositiveB)\n\nbinom = Binomial(n,0.5)\npValA = 2*ccdf(binom, testStatisticA)\npValB = 2*ccdf(binom, testStatisticB)\n\nprintln(\"Binomial mean: \", mean(binom))\n\nprintln(\"Case A: mu0: \", mu0A)\nprintln(\"\\tTest statistc: \", testStatisticA)\nprintln(\"\\tP-value: \", pValA)\n\nprintln(\"Case B: mu0: \", mu0B)\nprintln(\"\\tTest statistc: \", testStatisticB)\nprintln(\"\\tP-value: \", pValB)\n", "meta": {"hexsha": "95822ce5a22482b15aee9fdc366a652008bfe913", "size": 655, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "7_chapter/signTest.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/signTest.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/signTest.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 25.1923076923, "max_line_length": 58, "alphanum_fraction": 0.7053435115, "num_tokens": 227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9706877717925422, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.8067803931664518}} {"text": "### A Pluto.jl notebook ###\n# v0.17.1\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n quote\n local iv = try Base.loaded_modules[Base.PkgId(Base.UUID(\"6e696c72-6542-2067-7265-42206c756150\"), \"AbstractPlutoDingetjes\")].Bonds.initial_value catch; b -> missing; end\n local el = $(esc(element))\n global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el)\n el\n end\nend\n\n# ╔═╡ 9112b09c-5a21-11ec-0847-1971b3c9a6cd\nbegin\n\tusing Pkg\n\tPkg.activate(\"../../\")\n\tusing Revise\nend\n\n# ╔═╡ 4b66d9ba-eb36-4f53-8e87-28b6eadbd828\nusing FFTW, Colors, ImageShow, TestImages, Tullio, Zygote, Noise, IndexFunArrays, FourierTools, ImgProcMic, PlutoUI, DeconvOptim, PlutoTest, Optim, Statistics, Plots\n\n# ╔═╡ 9bc5b039-5c13-46bc-8d3b-9edae93d164a\nusing ComponentArrays, Images, Random, MicroscopyTools\n\n# ╔═╡ 606ad4de-213f-4aac-a0a9-9a6827c05c29\nbegin\n\t\"\"\"\n\t\tcirc(size, radius)\n\t\n\t`size` the size of the resulting array\n\tand `radius` the radius of the circle\n\t\"\"\"\n\tcirc(size, radius) = rr2(size) .<= radius^2\nend\n\n# ╔═╡ e7a503cf-c59c-4737-95f5-b8f38548833a\n\"\"\"\n\tcalc_psf(arr_size, radius)\n\nCalculate a simple PSF. `arr_size` is the output size and `radius` is the radius \nin Fourier space.\nThe output array is normalized by its sum to 1.\n\"\"\"\nfunction calc_psf(arr_size, radius)\n\t# TODO\n\trr2 = circ(arr_size, radius)\n\th = abs2.(ift(rr2))\n\th ./= sum(h)\n\treturn h\nend\n\n# ╔═╡ 3194824d-ed15-479a-af10-a1803f9f20bc\nmd\"# 1 Lucy Richardson Deconvolution\nIn the last exercise we implemented the Wiener filter which is suited for Gaussian noise.\nHowever, in microscopy the most dominant noise is usually Poisson noise.\nThe LR deconvolution algorithm is derived on a Poisson noise assumption.\n\nBased on the lecture notes, implement the LR algorithm.\n\"\n\n# ╔═╡ 7ef1aaf2-081c-4885-9ab3-4606cf0656b4\n\"\"\"\n\tLR(measured, psf, N)\n\n`measured` is the measured image. `psf` is the point spread function.\n`N` is the number of iterations.\n\"\"\"\nfunction LR(measured, psf, N)\n\totf = rfft(psf)\n\totf_c = conj.(otf)\n\t\n\trec = one.(measured)\n\n\tconv(object, o) = irfft(rfft(object) .* o, size(measured, 1))\n\t\n\tfor i = 1:N\n\t\trec .*= conv(measured ./ conv(rec, otf_c), otf)\n\tend\n\treturn rec\nend\n\n# ╔═╡ 400aeebf-21bd-4b58-9b64-ccec3071df63\n# testimage\nimg = Float32.(testimage(\"resolution_test_512\"));\n\n# ╔═╡ d7741c07-0982-4e57-bf95-a3ee0bc6f0b1\n# calculate the PSF with a radius of 30\npsf = ifftshift(Float32.(calc_psf(size(img), 30)));\n\n# ╔═╡ aa15a3ed-0f97-4ef9-9704-0ede98426b6c\n# our measured image, degraded with poisson\nmeasured = 0.0001f0 .+ poisson(FourierTools.conv(img, psf), 100);\n\n# ╔═╡ f4e2cc11-e86e-4afc-a021-aed27283a5f1\ngray_show(measured)\n\n# ╔═╡ dc9fa103-6a00-4129-b5d1-c1b36216d13d\nmd\"\nAfter \n\niterations=$(@bind iterations Slider(1:300, show_value=true))\n\nthe image should look _better_ than the original.\nTake that as test!\n\"\n\n# ╔═╡ 6ba1619b-036a-480d-b3bb-88ea6f5b259e\nrec = LR(measured, psf, iterations);\n\n# ╔═╡ f9bb5a74-067d-4afd-ae61-7f41f2e1dbca\ngray_show(rec)\n\n# ╔═╡ 0d7e91be-e03e-454c-9ebd-c0b68ca93848\nmd\"# 2 (Smoothed) Total Variation Regularizer\nIn this part we want to implement a Total Variation Regularizer.\nIt's purpose is to impose a constraint of _piecewise smoothness_ to the image.\nFormally, it is defined as\n\n$\\text{TV}(\\text{img}) = \\sum_{i,j} \\sqrt{\\epsilon + \\left|\\text{img}[i, j] - \\text{img}[i+1, j]\\right|^2 + \\left|\\text{img}[i, j] - \\text{img}[i, j+1]\\right|^2}$\n\nwhere $\\epsilon$ is a small value prevent a singularity in the derivative. \n\nThe output of this equation is a scalar value and can be understood as a loss function.\nIf we add this term to our loss function of the LR algorithm, the optimizer has to minimize not only the LR loss term but also this additional regularizer.\nOften this can introduce nicer results.\n\nAs you learnt in the last homework, we also need the gradient of the `TV` function.\nFortunately, for that purpose we can use the automatic differentiation package [Zygote.jl](https://github.com/FluxML/Zygote.jl).\n\"\n\n# ╔═╡ 72cdab83-0162-4951-8751-b91cb6fd0e49\nmd\"For the implementation of the regularizer itself, we use the package [Tullio.jl](https://github.com/mcabbott/Tullio.jl). _Tullio.jl_ speeds up the calculation and is conventient to use.\nFor simple usage, see below:\"\n\n# ╔═╡ f8c665e4-e07f-4995-ad84-5a31658be5f4\nbegin\n\t# example how @tullio works\n\tarr = [1.0, 2.0, 3.0]\n\t@tullio arr_ex = abs2(arr[i] - arr[i-1])\nend\n\n# ╔═╡ bfb88c5e-0e45-428b-a66c-b9c37f633c6b\n\"\"\"\n\tTV(img::AbstractArray{T, N}, ϵ=T(1e-6)) where {T, N}\n\nCalculates the TV regularizer. `ϵ` is a small positive value to make it differentiable.\n\"\"\"\nfunction TV(img::AbstractArray{T, N}, ϵ=T(1e-6)) where {T, N}\n\t# insert tullio expression here!\n\t@tullio r = sqrt(ϵ + abs2(img[i, j] - img[i, j+1]) + abs2(img[i, j] - img[i + 1, j]))\nend\n\n# ╔═╡ 49143f59-2f8f-46e9-ac32-c4681164ef82\nTV(img)\n\n# ╔═╡ e33d9b1f-dc9b-49c0-a6e3-b1e2266df999\n# the gradient can be calculated likes this!\n# it describes how the value of the TV change for each pixel value\ngradient(TV, img)[1]\n\n# ╔═╡ 8a9da6e2-528a-41e5-9bc5-750885d94ca0\nmd\"## 2 Test\"\n\n# ╔═╡ 53364e6f-b672-4c60-8fe1-845ba85399ba\nPlutoTest.@test typeof(TV([1.0 2; 3 4])) <: Number\n\n# ╔═╡ 30e313ee-aca2-4469-97cf-08acd489aaef\nPlutoTest.@test TV([1.0 2; 3 4]) ≈ 2.2360682011065762\n\n# ╔═╡ 4c91d0da-201a-4281-91a2-2de626ab4a30\nPlutoTest.@test Zygote.gradient(TV, [1.0 2; 3 4])[1] ≈ [-1.34164 0.447214; 0.894427 0.0] rtol=1e-5\n\n# ╔═╡ 340851e8-a66d-4643-83d1-48fb775dde8e\nmd\"# 3 Lucy Richardson with TV\nAdditionally to the plain LR we want to incorporate the TV regularizer in this task.\n\nThe gradient of `TV` can be calculated with `gradient(TV, arr)[1]`.\n\nIn the lectures it is sketched how to add the regularizer loss to the normal loss function.\nCopy your `LR` from above and try to incorporate the gradient of the `TV` loss value.\nThe `TV` gradient value is weighted with `λ`.\n\"\n\n# ╔═╡ cfc01fbb-5ee4-4909-ba67-2034506e55e8\nfunction LR_TV(measured, psf, λ, N)\n\totf = rfft(psf)\n\totf_c = conj.(otf)\n\t\n\tbuffer = rfft(img)\n\trec = one.(measured)\n\n\tconv(object, o) = irfft(rfft(object) .* o, size(measured, 1))\n\t\n\tfor i = 1:N\n\t\trec .*= (conv(measured ./ conv(rec, otf_c), otf) .- λ .* gradient(TV, rec)[1])\n\tend\n\treturn rec\nend\n\n# ╔═╡ ae7c45b6-c8a7-4fe0-b922-9ab40fcce372\n# that can easily take a minute. Zygote is very sloooooooow on the first call\nrec2 = LR_TV(measured, psf, 0.02, 400)\n\n# ╔═╡ 8c91142a-5b2d-4dfc-9764-87a66f90f0cb\ngray_show(rec2)\n\n# ╔═╡ dcba043b-db09-4adc-8239-a6439a9c074e\nmd\" ## 4 Bonus\nAnyone who can beat [DeconvOptim.jl](https://github.com/roflmaostc/DeconvOptim.jl) in terms of speed (with equal reconstruction quality), immediatly gets the bonus for the exam.\n\"\n\n# ╔═╡ bbb7dda6-84c2-4172-a888-85a3658c1556\nreg = DeconvOptim.TV(num_dims=2);\n\n# ╔═╡ 231698fd-bb16-4895-9278-0d41dfafdb7e\nrec_DO,r = deconvolution(measured, psf, regularizer=reg, iterations=20, λ=0.02);\n\n# ╔═╡ 45f089ec-a7cb-4941-ad04-7a6c6c55dbef\nr\n\n# ╔═╡ d725c173-0123-40ed-aaa0-feec1dcd7a25\ngray_show(rec_DO)\n\n# ╔═╡ dfc9d8f3-6b16-476a-bba9-1c7f55229f57\nmd\"# 5 Single Molecule Localization\n\nIn this part we fit the position, intensity and the standard deviation of a point source emitter to a measured image.\n\"\n\n# ╔═╡ 954f06a6-ac27-4596-a978-e1274b2532d8\nmd\"### Hint\nUse the following pattern:\n\"\n\n# ╔═╡ 46185370-aaf3-48c3-b297-b3a2843a0435\n1:100\n\n# ╔═╡ 7c51a261-a188-469d-8020-876b1b1dcbf0\n(1:100)'\n\n# ╔═╡ fae6889b-65f5-4b90-972f-56187b69fee5\n\"\"\"\n\tgauss(I, σ, x_offset, y_offset)\n\nReturns an image of size `(256, 256)` with a Gauss peak\ncentered at `(x_offset, y_offset)` with standard deviation `σ` and intensity\n`I` (which is multiplied to the ideal Gauss)\n\"\"\"\nfunction gauss(I, σ::T, x_offset::T, y_offset::T) where T\n\t# TODO\n\ts = (256, 256)\n\tx = 1:s[1]\n\ty = (1:s[2])'\n\t@. I * exp(-T(0.5) * (abs2(x - x_offset) + abs2(y-y_offset)) / σ^2)\nend\n\n# ╔═╡ 23b9ea69-99d5-4a49-8e36-cd25323c8858\nmd\"## 5.1 Test Gauss\"\n\n# ╔═╡ e9c17987-029e-4bd9-824e-47175f4d6924\nz = zeros((256, 256));\n\n# ╔═╡ 046ec177-9394-4b7d-bead-68590e169f1b\nz[10, 10] = 42.0;\n\n# ╔═╡ eb9b2246-c9d9-442e-bde4-48ed14bb3fa6\nPlutoTest.@test gauss(42.0, 0.000001, 10.0, 10.0) ≈ z\n\n# ╔═╡ 9cdf2e65-af36-4421-a15b-fdc4c87569b4\nPlutoTest.@test gauss(11.0, 100000000000000000000.0, 0.0, 0.0) ≈ 11.0 .* ones((256, 256))\n\n# ╔═╡ 7ecb1d8d-334c-4043-9378-adcbe0b0bf35\nPlutoTest.@test (gauss(10.0, 2.0, 3.0, 3.0))[1:5, 1:5] ≈ [3.6787944117144233 5.352614285189903 6.065306597126334 5.352614285189903 3.6787944117144233; 5.352614285189903 7.788007830714049 8.824969025845954 7.788007830714049 5.352614285189903; 6.065306597126334 8.824969025845954 10.0 8.824969025845954 6.065306597126334; 5.352614285189903 7.788007830714049 8.824969025845954 7.788007830714049 5.352614285189903; 3.6787944117144233 5.352614285189903 6.065306597126334 5.352614285189903 3.6787944117144233]\n\n# ╔═╡ 9b5b3495-0d3b-4f7c-9f51-04245ebd59c2\nmd\"## 5.2 Forward Model\nIn the next part, we assemble a forward model mapping a set of parameters to an image.\n\"\n\n# ╔═╡ 26950064-0127-41fd-9973-6c170bd6b8fe\n\"\"\"\n\tdraw_parameters(N)\n\nRandomly draws `N` parameters for the Gauss peak.\n\"\"\"\nfunction draw_parameters(N)\n\t# make the random numbers reproducible\n\tRandom.seed!(40)\n\tσ = [rand(1:0.01:5.0) for i = 1:N]\n\tx_offset = [rand(10:0.1:240) for i = 1:N]\n\ty_offset = [rand(10:0.1:240) for i = 1:N]\n\tI = [rand(0.5:0.1:1.0) for i = 1:N]\n\treturn ComponentVector(σ=σ, x_offset=x_offset, y_offset=y_offset, I=I)\nend\n\n# ╔═╡ ef9c0737-ffbc-498b-80d2-2e93558c508f\n# draws randomly a few parameters\n# the output is a ComponentVector which is needed for Optim\nparams = draw_parameters(5);\n\n# ╔═╡ 70a9e03f-d44f-4cce-a82d-898e63f789fd\n# all fields can be access with params.FIELD, see below\n\n# ╔═╡ 70453553-7dbc-46f1-a141-f4d19f2ae3d4\nparams.σ\n\n# ╔═╡ 6ac55320-b94f-44c2-9669-1d4e7eb3ddee\nparams.x_offset\n\n# ╔═╡ 73416e0d-ed2b-4b95-aa43-ce58de7f29aa\n\"\"\"\n\tforward(params)\n\nMaps the `params` to an output image.\n\"\"\"\nfunction forward(params)\n\tsum(gauss.(params.I, params.σ, params.x_offset, params.y_offset))\nend\n\n# ╔═╡ 56d566e3-632c-4852-839b-adf505122ad2\nmeasurement = randn() * 0.3 .+ poisson(forward(params), 50);\n\n# ╔═╡ 26f1a0c2-3787-4335-958b-12719e2901bf\n# noisy measurement of the point sources\ngray_show(measurement)\n\n# ╔═╡ 2b3c151a-d7bd-40e4-97d7-f121c9da23a6\nmd\"## 5.3 Loss Function\"\n\n# ╔═╡ 32bd26f1-0d04-4589-a2d5-1e01abce4a7d\n\"\"\"\n\tloss(measurement, pred)\n\nCompares the prediction `pred` and the `measurement` under the L2 norm.\n\"\"\"\nfunction loss(measurement, pred)\n\t# TODO\n\tsum(abs2.(measurement .- pred))\nend\n\n# ╔═╡ dc66401d-2581-4d6f-8b36-d15a2d21391a\nmd\"## 5.4 Reconstruction\"\n\n# ╔═╡ daa77619-e7a8-4c6a-9854-d8ef21042277\n\"\"\"\n\tfind_peaks(arr, bin_factor)\n\nFinds the peaks in the measurement `arr`. \nTo get a better SND we bin the measurement by a binning factor `bin_factor`.\n\"\"\"\nfunction find_peaks(arr, bin_factor)\n\tarr_s = bin(arr, (bin_factor,bin_factor))\n\tmap(x -> x .* bin_factor, Tuple.(findlocalmaxima(arr_s)))\nend\n\n# ╔═╡ 1a505ff5-4745-42c5-bc40-bc1075fcd4d6\n\"\"\"\n\tinit_parameters(N, measurement)\n\nInitializes a good set of parameters for the reconstruction.\n`N` is the number of PSFs and `measurement` the measured image.\n\nThe critical part is to find good initial positions for the peaks.\nFor that we use `find_peaks`. \n\n\"\"\"\nfunction init_params(N, measurement, bin_factor, σ_guess)\n\t# find a σ_guess which results in a good estimate\n\tσ = [σ_guess for i = 1:N]\n\n\n\tpeaks = find_peaks(measurement, bin_factor)\n\tx_offset = [peaks[i][1] for i =1:N]\n\ty_offset = [peaks[i][2] for i =1:N]\n\n\t# you can change that as well! Is it critical?\n\tI = [1.0 for i = 1:N]\n\t\n\treturn ComponentVector(σ=σ, x_offset=x_offset, y_offset=y_offset, I=I)\nend\n\n# ╔═╡ 74f8a126-7e5c-4e1d-90bd-fe66065d5faf\nbegin\n\t# initial guess\n\t# try to find an binning factor which results in good peaks\n\tbin_factor = 5 # TODO\n\tσ_guess = 5.30 # TODO\n\tparams_guess = init_params(5, measurement, bin_factor, σ_guess);\nend\n\n# ╔═╡ 3c38cdec-99d8-4c11-bedb-87137ea119ba\nmd\"\nThe left image is the measured image.\nThe center image the initial guess.\nThe right image is the difference map suited to judge the position of the peaks.\n\"\n\n# ╔═╡ 0a3cfe9b-888c-420a-9465-bef61d058c17\ngray_show([measurement forward(params_guess) abs.(measurement .- forward(params_guess))])\n\n# ╔═╡ 22d4842a-908f-485d-9bf4-96c053b106c6\nmd\"### 5.5 Optim Specific Parts for the Reconstruction\"\n\n# ╔═╡ c3996433-e27d-4227-8e18-9531a30ea389\nbegin\n\t# the function maps the params to a single scalar value\n\tfunction f(params)\n\t\tloss(measurement, forward(params))\n\tend\n\t# this function calculates the \n\tg!(G, params) = isnothing(G) ? G : G .= gradient(f, params)[1]\nend\n\n# ╔═╡ d30c5e75-8a58-4231-8164-c7d783b9bc02\nres = optimize(f, g!, params_guess, LBFGS(), Optim.Options(iterations=50))\n\n# ╔═╡ 90b98a76-1bc7-43e0-927c-1cf94d35ffd0\noutput_optim = forward(res.minimizer);\n\n# ╔═╡ b5880735-c615-440c-a0a0-56a6a024494a\ngray_show([measurement output_optim measurement .- output_optim])\n\n# ╔═╡ efaf6cfb-bf37-4cc2-be30-abbc6706e905\nheatmap(measurement .- output_optim, title=\"Difference map\")\n\n# ╔═╡ 19a1ff11-1276-46ab-b84b-a66898522068\nmd\"## Check if the values look plausible\"\n\n# ╔═╡ 060ef38d-312b-4487-b59d-0ba288b16daf\nmd\"The operator `|>` in an expression like `f(x) |> g` is the same as `g(f(x))`. It's only a convenvient wrapper\"\n\n# ╔═╡ e60c3150-7658-4a3d-819f-b1e6293a27fb\nparams.σ |> sort\n\n# ╔═╡ 17ed7c8d-4d12-4008-8745-e96f36ce85b1\nres.minimizer.σ |> sort\n\n# ╔═╡ e677b9f8-38ee-41cd-b319-ef1cc48b17e2\nparams.I |> sort\n\n# ╔═╡ 854f732f-441b-45b1-9a00-2b7ae854dc47\nres.minimizer.I |> sort\n\n# ╔═╡ 45abec82-b841-4d8a-b2ae-bba738352da3\nres.minimizer.y_offset |> sort\n\n# ╔═╡ ff1c6ed2-e4b1-4f6a-87df-44f350bb50f7\nparams.y_offset |> sort\n\n# ╔═╡ 8ffb693f-f5ca-45a5-8d1b-5c96885118d0\nPlutoTest.@test (res.minimizer.x_offset |> sort) ≈ (params.x_offset |> sort) rtol=0.01\n\n# ╔═╡ 67db2159-c2f0-4130-8e82-6b75907db82f\nPlutoTest.@test (res.minimizer.y_offset |> sort) ≈ (params.y_offset |> sort) rtol=0.01\n\n# ╔═╡ Cell order:\n# ╠═9112b09c-5a21-11ec-0847-1971b3c9a6cd\n# ╠═4b66d9ba-eb36-4f53-8e87-28b6eadbd828\n# ╟─606ad4de-213f-4aac-a0a9-9a6827c05c29\n# ╟─e7a503cf-c59c-4737-95f5-b8f38548833a\n# ╟─3194824d-ed15-479a-af10-a1803f9f20bc\n# ╠═7ef1aaf2-081c-4885-9ab3-4606cf0656b4\n# ╠═400aeebf-21bd-4b58-9b64-ccec3071df63\n# ╠═d7741c07-0982-4e57-bf95-a3ee0bc6f0b1\n# ╠═aa15a3ed-0f97-4ef9-9704-0ede98426b6c\n# ╠═f4e2cc11-e86e-4afc-a021-aed27283a5f1\n# ╟─dc9fa103-6a00-4129-b5d1-c1b36216d13d\n# ╠═6ba1619b-036a-480d-b3bb-88ea6f5b259e\n# ╠═f9bb5a74-067d-4afd-ae61-7f41f2e1dbca\n# ╟─0d7e91be-e03e-454c-9ebd-c0b68ca93848\n# ╟─72cdab83-0162-4951-8751-b91cb6fd0e49\n# ╠═f8c665e4-e07f-4995-ad84-5a31658be5f4\n# ╠═bfb88c5e-0e45-428b-a66c-b9c37f633c6b\n# ╠═49143f59-2f8f-46e9-ac32-c4681164ef82\n# ╠═e33d9b1f-dc9b-49c0-a6e3-b1e2266df999\n# ╟─8a9da6e2-528a-41e5-9bc5-750885d94ca0\n# ╠═53364e6f-b672-4c60-8fe1-845ba85399ba\n# ╠═30e313ee-aca2-4469-97cf-08acd489aaef\n# ╠═4c91d0da-201a-4281-91a2-2de626ab4a30\n# ╟─340851e8-a66d-4643-83d1-48fb775dde8e\n# ╠═cfc01fbb-5ee4-4909-ba67-2034506e55e8\n# ╠═ae7c45b6-c8a7-4fe0-b922-9ab40fcce372\n# ╠═8c91142a-5b2d-4dfc-9764-87a66f90f0cb\n# ╟─dcba043b-db09-4adc-8239-a6439a9c074e\n# ╠═bbb7dda6-84c2-4172-a888-85a3658c1556\n# ╠═231698fd-bb16-4895-9278-0d41dfafdb7e\n# ╠═45f089ec-a7cb-4941-ad04-7a6c6c55dbef\n# ╠═d725c173-0123-40ed-aaa0-feec1dcd7a25\n# ╟─dfc9d8f3-6b16-476a-bba9-1c7f55229f57\n# ╠═9bc5b039-5c13-46bc-8d3b-9edae93d164a\n# ╟─954f06a6-ac27-4596-a978-e1274b2532d8\n# ╠═46185370-aaf3-48c3-b297-b3a2843a0435\n# ╠═7c51a261-a188-469d-8020-876b1b1dcbf0\n# ╠═fae6889b-65f5-4b90-972f-56187b69fee5\n# ╟─23b9ea69-99d5-4a49-8e36-cd25323c8858\n# ╠═e9c17987-029e-4bd9-824e-47175f4d6924\n# ╠═046ec177-9394-4b7d-bead-68590e169f1b\n# ╠═eb9b2246-c9d9-442e-bde4-48ed14bb3fa6\n# ╠═9cdf2e65-af36-4421-a15b-fdc4c87569b4\n# ╠═7ecb1d8d-334c-4043-9378-adcbe0b0bf35\n# ╟─9b5b3495-0d3b-4f7c-9f51-04245ebd59c2\n# ╠═26950064-0127-41fd-9973-6c170bd6b8fe\n# ╠═ef9c0737-ffbc-498b-80d2-2e93558c508f\n# ╠═70a9e03f-d44f-4cce-a82d-898e63f789fd\n# ╠═70453553-7dbc-46f1-a141-f4d19f2ae3d4\n# ╠═6ac55320-b94f-44c2-9669-1d4e7eb3ddee\n# ╠═73416e0d-ed2b-4b95-aa43-ce58de7f29aa\n# ╠═56d566e3-632c-4852-839b-adf505122ad2\n# ╠═26f1a0c2-3787-4335-958b-12719e2901bf\n# ╟─2b3c151a-d7bd-40e4-97d7-f121c9da23a6\n# ╠═32bd26f1-0d04-4589-a2d5-1e01abce4a7d\n# ╟─dc66401d-2581-4d6f-8b36-d15a2d21391a\n# ╠═daa77619-e7a8-4c6a-9854-d8ef21042277\n# ╠═1a505ff5-4745-42c5-bc40-bc1075fcd4d6\n# ╠═74f8a126-7e5c-4e1d-90bd-fe66065d5faf\n# ╟─3c38cdec-99d8-4c11-bedb-87137ea119ba\n# ╠═0a3cfe9b-888c-420a-9465-bef61d058c17\n# ╟─22d4842a-908f-485d-9bf4-96c053b106c6\n# ╠═c3996433-e27d-4227-8e18-9531a30ea389\n# ╠═d30c5e75-8a58-4231-8164-c7d783b9bc02\n# ╠═90b98a76-1bc7-43e0-927c-1cf94d35ffd0\n# ╠═b5880735-c615-440c-a0a0-56a6a024494a\n# ╠═efaf6cfb-bf37-4cc2-be30-abbc6706e905\n# ╟─19a1ff11-1276-46ab-b84b-a66898522068\n# ╟─060ef38d-312b-4487-b59d-0ba288b16daf\n# ╠═e60c3150-7658-4a3d-819f-b1e6293a27fb\n# ╠═17ed7c8d-4d12-4008-8745-e96f36ce85b1\n# ╠═e677b9f8-38ee-41cd-b319-ef1cc48b17e2\n# ╠═854f732f-441b-45b1-9a00-2b7ae854dc47\n# ╠═45abec82-b841-4d8a-b2ae-bba738352da3\n# ╠═ff1c6ed2-e4b1-4f6a-87df-44f350bb50f7\n# ╠═8ffb693f-f5ca-45a5-8d1b-5c96885118d0\n# ╠═67db2159-c2f0-4130-8e82-6b75907db82f\n", "meta": {"hexsha": "eabce959c25a2009c07f49e8d41655873c278c6f", "size": 17269, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/homeworks/HW05_solution.jl", "max_stars_repo_name": "bionanoimaging/Image-Processing-In-Microscopy", "max_stars_repo_head_hexsha": "c3801b2207cc4e23badb50afb8de3aea3e910cbe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-11-05T21:01:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T16:02:52.000Z", "max_issues_repo_path": "examples/homeworks/HW05_solution.jl", "max_issues_repo_name": "bionanoimaging/Image-Processing-In-Microscopy", "max_issues_repo_head_hexsha": "c3801b2207cc4e23badb50afb8de3aea3e910cbe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-12-03T01:37:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-03T13:56:12.000Z", "max_forks_repo_path": "examples/homeworks/HW05_solution.jl", "max_forks_repo_name": "bionanoimaging/Image-Processing-In-Microscopy", "max_forks_repo_head_hexsha": "c3801b2207cc4e23badb50afb8de3aea3e910cbe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-11-08T19:18:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T03:36:04.000Z", "avg_line_length": 32.038961039, "max_line_length": 503, "alphanum_fraction": 0.7331055649, "num_tokens": 7838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.9046505286741727, "lm_q1q2_score": 0.806777338935445}} {"text": "#############################\n## Numerical experiments associated with section 5.4.2\n#############################\n## In general, VIDEs are implemented as a combination of the approaches for nonlinear and integro-differential equations.\n## Whether this is more efficient than standard methods once again depends on the sparsity of the resulting operator\n## and the polynomial order required to resolve the solution.\n##\n\nusing NLsolve, ApproxFun, MultivariateOrthogonalPolynomials, BandedMatrices, BlockBandedMatrices, Plots\nusing SparseVolterraExamples\n\n#####################################################\n## Problem in Equation (28), u_2(x) = tan(x)\n#####################################################\n\n####\n## Some initialization\nDD = 1 # Highest derivative order of the problem\n f(u) = u^2 # This is the nonlinearity\n lincomb(x) = sin(x) # In lincomb we store potentially appearing additional linear terms. In this case this is sin(x) as seen in the example.\n g(x) = x+cos(x)-tan(x)+tan(x)^2 # the g function from the problem statement\n K(x,y) = 1 # the kernel is constant in this example\n conditions = [0] # Vector of length DD containing the conditions that uniquely solve the differential equation\n n = 28 # Set some desired polynomial degree of approximation.\n####\n## Now we can set up the appropriate objective function\nobjective(x) = triNonLinearIntegroDiffVolterraObjective(x,f,K,g,n,DD,conditions,lincomb)\n\n####\n## Solve using basic Newton iteration with a zero vector guess\nsol = nlsolve(objective,zeros(n),method=:newton,ftol=1e-15)\n\n####\n## We can compare the numerical solution against the analytic one.\nplot(Fun(Jacobi(0,1,0..1),sol.zero),label=\"sparse method solution\",grid=false,legend=:topleft,ylabel=\"u(x)\",xlabel=\"x\")\nplot!(x->tan(x),0,1,label=\"analytic tan(x)\",grid=false,legend=:topleft,ylabel=\"u(x)\",xlabel=\"x\")\n\n####\n## Or just plot the error on (0,1). A straightforward loop over the polynomial order and a maximum function over this difference then leads to Figure 8(b).\nplot(Fun(Jacobi(0,1,0..1),sol.zero)-Fun(x->tan(x),0..1),label=false,grid=false,legend=:topleft,ylabel=\"error\",xlabel=\"x\")\n", "meta": {"hexsha": "8f615fa3244e361416f136be6c813d1cc3642f59", "size": 2250, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Section 5-4-2 - Nonlinear VIDEs.jl", "max_stars_repo_name": "TSGut/SparseVolterraExamples.jl", "max_stars_repo_head_hexsha": "277733c70dfe78b65d1d9ad289de9dbeacda27b7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-18T16:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-18T16:58:42.000Z", "max_issues_repo_path": "examples/Section 5-4-2 - Nonlinear VIDEs.jl", "max_issues_repo_name": "TSGut/SparseVolterraExamples.jl", "max_issues_repo_head_hexsha": "277733c70dfe78b65d1d9ad289de9dbeacda27b7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-09T15:39:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T15:59:37.000Z", "max_forks_repo_path": "examples/Section 5-4-2 - Nonlinear VIDEs.jl", "max_forks_repo_name": "TSGut/SparseVolterraExamples.jl", "max_forks_repo_head_hexsha": "277733c70dfe78b65d1d9ad289de9dbeacda27b7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 54.8780487805, "max_line_length": 155, "alphanum_fraction": 0.6524444444, "num_tokens": 531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.8633916099737807, "lm_q1q2_score": 0.8067489437379267}} {"text": "# Quadrilateral in 3D defined by its 4 vertices.\n\n# NOTE: Quadrilaterals are assumed to be convex and planar (all points in some plane, not \n# necessarily xy, yx, etc.)!\n# Quadrilaterals must be convex to be valid finite elements. See link below\n# https://math.stackexchange.com/questions/2430691/jacobian-determinant-for-bi-linear-quadrilaterals\nstruct Quadrilateral_3D{T <: AbstractFloat}\n # Counter clockwise order\n points::NTuple{4, Point_3D{T}}\nend\n\n# Constructors\n# -------------------------------------------------------------------------------------------------\nQuadrilateral_3D(p₁::Point_3D{T}, \n p₂::Point_3D{T}, \n p₃::Point_3D{T},\n p₄::Point_3D{T}) where {T <: AbstractFloat} = Quadrilateral_3D((p₁, p₂, p₃, p₄))\n\n# Methods\n# -------------------------------------------------------------------------------------------------\n# Interpolation\nfunction (quad::Quadrilateral_3D{T})(r::R, s::S) where {T <: AbstractFloat, \n R <: Real,\n S <: Real}\n # See The Visualization Toolkit: An Object-Oriented Approach to 3D Graphics, 4th Edition\n # Chapter 8, Advanced Data Representation, in the interpolation functions section\n rₜ = T(r)\n sₜ = T(s)\n return (1 - rₜ)*(1 - sₜ)*quad.points[1] + \n rₜ*(1 - sₜ)*quad.points[2] + \n rₜ*sₜ*quad.points[3] +\n (1 - rₜ)*sₜ*quad.points[4]\nend\n\nfunction triangulate(quad::Quadrilateral_3D{T}) where {T <: AbstractFloat}\n # Return the two triangles that partition the domain\n A, B, C, D = quad.points\n return (Triangle_3D(A, B, C), Triangle_3D(C, D, A))\nend\n\nfunction area(quad::Quadrilateral_3D{T}) where {T <: AbstractFloat}\n # Using the convex quadrilateral assumption, just return the sum of the areas of the two\n # triangles that partition the quadrilateral. If the convex assumption ever changes, you\n # need to verify that the triangle pair partitions the quadrilateral. Choosing the wrong\n # pair overestimates the area, so just get the areas of both pairs of valid triangles and use\n # the smaller area.\n return sum(area.(triangulate(quad)))\nend\n\n#function intersect(l::LineSegment_3D{T}, quad::Quadrilateral_3D{T}) where {T <: AbstractFloat}\n# # Triangulate the quadrilateral, intersect the triangles.\n# tri = triangulate(quad)\n# intersection1 = l ∩ tri[1]\n# if intersection1[1]\n# return true, intersection1[2]\n# end\n# intersection2 = l ∩ tri[2]\n# if intersection2[1]\n# return true, intersection2[2]\n# end\n# return false, Point_3D(T, 0)\n#end\n", "meta": {"hexsha": "36255622c0f0a293bd385596efa1859bcefecff8", "size": 2686, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unused/Quadrilateral_3D.jl", "max_stars_repo_name": "KyleVaughn/MOCNeutronTransport", "max_stars_repo_head_hexsha": "6de0f5987c2b37c3c3039d073b63c223ff6cd5f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-11-10T19:36:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T15:34:40.000Z", "max_issues_repo_path": "src/unused/Quadrilateral_3D.jl", "max_issues_repo_name": "KyleVaughn/MOCNeutronTransport", "max_issues_repo_head_hexsha": "6de0f5987c2b37c3c3039d073b63c223ff6cd5f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 26, "max_issues_repo_issues_event_min_datetime": "2022-01-20T03:03:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T18:29:33.000Z", "max_forks_repo_path": "src/unused/Quadrilateral_3D.jl", "max_forks_repo_name": "KyleVaughn/MOCNeutronTransport", "max_forks_repo_head_hexsha": "6de0f5987c2b37c3c3039d073b63c223ff6cd5f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.6349206349, "max_line_length": 100, "alphanum_fraction": 0.5949367089, "num_tokens": 707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951607140233, "lm_q2_score": 0.8633916082162402, "lm_q1q2_score": 0.8067489405183528}} {"text": "module HaltonSequences\n\nusing Primes\nexport haltonvalue,Halton,HaltonPoint\n\nconst MAXLEN = typemax(UInt32)\n\n\"\"\"\n haltonvalue(n, base[, T])\n\nReturn the `n`th element of the Halton sequence with prime base `base` (defaults to 2). If\na `<:Real` type `T` is given, compute the value in that type.\n\n# Examples\n```jldoctest\njulia> haltonvalue(4,3,Rational)\n4//9\n```\n\"\"\"\nfunction haltonvalue(n::Integer,base::Integer=2,T::Type=float(Int))\n haltonvalue!(zero(T),n,base)\nend\n\nfunction haltonvalue!(x::Real,n::Integer,base::Integer=2)\n x = zero(x)\n s = one(x)\n while n > 0\n s /= base\n n,r = divrem(n,base)\n x += s*r\n end\n return x\nend\n\nconst val = haltonvalue # for terser qualified uses\n\n########################################################\n# Vector of Halton sequence values\n########################################################\n\"\"\"\n Halton(base=2; )\n Halton{T<:Real}(base=2; )\n\nCreate a `Vector`-like object for a Halton sequence. Optionally, use a `<:Real` type\n`T` for the elements.\n\n# Arguments\n- `base::Integer`: prime number base for the sequence\n- `start=1` (keyword): starting/offset index\n- `length=typemax(UInt32)` (keyword): length of the sequence vector\n\n# Examples\n```jldoctest\njulia> Halton(3,length=4)\n4-element Halton{Float64}:\n 0.3333333333333333\n 0.6666666666666666\n 0.1111111111111111\n 0.4444444444444444\n```\n```jldoctest\njulia> Halton{Rational}(2,length=7)\n7-element Halton{Rational}:\n 1//2\n 1//4\n 3//4\n 1//8\n 5//8\n 3//8\n 7//8\n```\n```jldoctest\njulia> sum( Halton()[1:10000] )/10000\n0.4998324768066406\n```\n\n See also: [`HaltonPoint`](@ref), [`haltonvalue`](@ref)\n\"\"\"\nstruct Halton{T<:Real} <: AbstractArray{T, 1}\n base::Int\n start::Int\n length::Int\n # Constructor for when the type is explicit.\n function Halton{T}(base::Integer=2;start=1,length=MAXLEN) where {T<:Real}\n new(base,start,length)\n end\nend\n\n# Constructor when no type given. Also includes a check for prime base.\nfunction Halton(base::Integer=2;kw...)\n isprime(base) || error(\"Base must be a prime number.\")\n Halton{float(Int)}(base;kw...)\nend\n\n# Serve the AbstractArray interface\nBase.size(H::Halton) = (H.length,)\nBase.IndexStyle(::Type{<:Halton}) = IndexLinear()\nfunction Base.getindex(H::Halton{T}, n::Integer) where T\n n <= H.length || throw(BoundsError(H,n))\n haltonvalue(n+H.start-1,H.base,T)\nend\n\n########################################################\n# Vector of multidimensional points based on different bases\n########################################################\n\"\"\"\n HaltonPoint(ndim::Integer; )\n HaltonPoint(base::Vector{<:Integer}; )\n HaltonPoint{T<:Real}(base::Vector{<:Integer}; )\n\nCreate a `Vector`-like object for a sequence of `ndim`-dimensional vectors constructed\nfrom Halton sequences. If given, `base` should be a vector of primes and then\n`ndim=length(base)`. If `T` is given, it is the element type for the vectors.\n\n# Keyword arguments\n- `start=1`: starting/offset index\n- `length=typemax(UInt32)`: length of the sequence vector\n\n# Examples\n```jldoctest\njulia> HaltonPoint(4,length=5)\n5-element HaltonPoint{Float64}:\n [0.5, 0.333333, 0.2, 0.142857]\n [0.25, 0.666667, 0.4, 0.285714]\n [0.75, 0.111111, 0.6, 0.428571]\n [0.125, 0.444444, 0.8, 0.571429]\n [0.625, 0.777778, 0.04, 0.714286]\n```\n```jldoctest\njulia> h = HaltonPoint([5,11,17]); sum(h[10001:20000])/10000\n3-element Array{Float64,1}:\n 0.49996162048000015\n 0.5000650725546567\n 0.49992980926952507\n```\n\n See also: [`Halton`](@ref), [`haltonvalue`](@ref)\n\"\"\"\nstruct HaltonPoint{T<:Real} <: AbstractArray{T, 1}\n base::Vector{Int}\n start::Int\n length::Int\n # Constructor when the type and base are explicit.\n function HaltonPoint{T}(base::Vector{S};start=1,length=MAXLEN) where {T<:Real} where {S<:Integer}\n new(base,start,length)\n end\n # Constructor when the type is explicit, but bases are not given.\n function HaltonPoint{T}(ndim=Integer;kw...) where {T<:Real}\n function firstprimes(k::Integer)\n n = zeros(UInt16,k)\n n[1] = 2\n for i = 2:k\n n[i] = nextprime(n[i-1]+1)\n end\n return n\n end\n HaltonPoint{T}(firstprimes(ndim);kw...)\n end\nend\n\n# Constructor when the type is not given.\nHaltonPoint(b_or_n;kw...) = HaltonPoint{float(Int)}(b_or_n;kw...)\n\n# Serve the AbstractArray interface\nBase.size(P::HaltonPoint) = (P.length,)\nBase.IndexStyle(::Type{<:HaltonPoint}) = IndexLinear()\nBase.eltype(::HaltonPoint{T}) where T = Vector{T}\nfunction Base.getindex(P::HaltonPoint{T}, n::Integer) where T\n [ haltonvalue(n+P.start-1,P.base[i],T) for i in eachindex(P.base) ]\nend\n# This seems to be needed for range/vector indexing, since the eltype is not scalar.\nfunction Base.getindex(P::HaltonPoint{T}, n::Union{AbstractVector,AbstractRange}) where T\n [ P[n[i]] for i in eachindex(n) ]\nend\n\nend # module\n", "meta": {"hexsha": "91c782337cf28a0a0e023d7091ee0eb08927bcb2", "size": 4980, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/HaltonSequences.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/HaltonSequences.jl-13907d55-377f-55d6-a9d6-25ac19e11b95", "max_stars_repo_head_hexsha": "dc7e469e44d75cb5faf56a4ef8243964dcd4d4a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-10-12T05:47:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-01T02:09:12.000Z", "max_issues_repo_path": "src/HaltonSequences.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/HaltonSequences.jl-13907d55-377f-55d6-a9d6-25ac19e11b95", "max_issues_repo_head_hexsha": "dc7e469e44d75cb5faf56a4ef8243964dcd4d4a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-10-11T19:51:39.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-28T20:03:00.000Z", "max_forks_repo_path": "src/HaltonSequences.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/HaltonSequences.jl-13907d55-377f-55d6-a9d6-25ac19e11b95", "max_forks_repo_head_hexsha": "dc7e469e44d75cb5faf56a4ef8243964dcd4d4a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-10-17T02:51:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T10:45:06.000Z", "avg_line_length": 28.1355932203, "max_line_length": 101, "alphanum_fraction": 0.643373494, "num_tokens": 1551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951552333004, "lm_q2_score": 0.8633916099737806, "lm_q1q2_score": 0.8067489374285799}} {"text": "\nusing OrdinaryDiffEq\nusing DiffEqSensitivity\nusing Zygote\nusing Plots\n\n\nfunction sir_ode!(du,u,p,t)\n (S,I,R) = u\n (β,c,γ) = p\n N = S+I+R\n @inbounds begin\n du[1] = -β*c*I/N*S\n du[2] = β*c*I/N*S - γ*I\n du[3] = γ*I\n end\n nothing\nend;\n\n\nδt = 1.0\ntmax = 40.0\ntspan = (0.0,tmax)\nt = 0.0:δt:tmax\nnum_timepoints = length(t);\n\n\nu0 = [990.0,10.0,0.0] # S,I,R\nnum_states = length(u0);\n\n\np = [0.05,10.0,0.25]; # β,c,γ\nnum_params = length(p);\n\n\nprob_ode = ODEProblem(sir_ode!,u0,tspan,p);\n\n\nsim_ode = (u0,p)-> solve(prob_ode,Tsit5(),u0=u0,p=p,saveat=t,sensealg=QuadratureAdjoint());\n\n\nsol_ode = sim_ode(u0,p);\n\n\ndu0,dp = Zygote.jacobian(sim_ode,u0,p);\n\n\ndβ = reshape(dp[:,1],(num_states,:))' # as β is the first parameter\ndc = reshape(dp[:,2],(num_states,:))' # c is 2nd parameter\ndγ = reshape(dp[:,3],(num_states,:))' # γ is 3rd parameter\ndI₀ = reshape(du0[:,2],(num_states,:))'; # I₀ is the 2nd initial condition\n\n\nplot(sol_ode.t,\n Array(sol_ode(t))',\n labels = [\"S\" \"I\" \"R\"],\n xlabel = \"Time\",\n ylabel = \"Number\")\n\n\nl = @layout [a b; c d]\npl1 = plot(t,dβ,xlabel=\"Time\",ylabel=\"dp\",label=[\"S\" \"I\" \"R\"],title=\"Sensitivity to β\")\npl2 = plot(t,dc,xlabel=\"Time\",ylabel=\"dp\",label=[\"S\" \"I\" \"R\"],title=\"Sensitivity to c\")\npl3 = plot(t,dγ,xlabel=\"Time\",ylabel=\"dp\",label=[\"S\" \"I\" \"R\"],title=\"Sensitivity to γ\")\npl4 = plot(t,dI₀,xlabel=\"Time\",ylabel=\"dp\",label=[\"S\" \"I\" \"R\"],title=\"Sensitivity to I₀\")\nplot(pl1,pl2,pl3,pl4,layout=l)\n\n", "meta": {"hexsha": "bb660af4aea93239953e139086043441c936512d", "size": 1472, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/ode_local_sensitivity/ode_local_sensitivity.jl", "max_stars_repo_name": "Song921012/sir-julia", "max_stars_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "script/ode_local_sensitivity/ode_local_sensitivity.jl", "max_issues_repo_name": "Song921012/sir-julia", "max_issues_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/ode_local_sensitivity/ode_local_sensitivity.jl", "max_forks_repo_name": "Song921012/sir-julia", "max_forks_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.6470588235, "max_line_length": 91, "alphanum_fraction": 0.5991847826, "num_tokens": 586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951588871157, "lm_q2_score": 0.8633916064587, "lm_q1q2_score": 0.806748937298779}} {"text": "\"\"\"\nThe prime factors of 13195 are 5, 7, 13 and 29.\n\nWhat is the largest prime factor of the number 600851475143 ?\n\"\"\"\n# Running isprime will have to test prime each time it is called\n# It might be better to generate a prime prime_sieve till the sqrt and check from reverse if the number is divisible.\n\nfunction prime_sieve(n::Int)\n isprime = trues(n)\n isprime[1] = false\n\n for i in 2:isqrt(n)\n if isprime[i]\n for j in i^2:i:n\n isprime[j] = false\n end\n end\n end\n return filter(x -> isprime[x],1:n)\nend\n\nfunction largest_prime_factor(n)\n primes = prime_sieve(Int(trunc(√(n))))\n for prime in Iterators.reverse(primes)\n if n%prime == 0\n return prime\n end\n end\n return -1\nend\n\n@assert largest_prime_factor(13195) == 29\n@show largest_prime_factor(600851475143)", "meta": {"hexsha": "56fc7b42c7e51bd22e85fe37ffd67e27e59e7972", "size": 858, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/P3_largest_prime_factor.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/P3_largest_prime_factor.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/P3_largest_prime_factor.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": 25.2352941176, "max_line_length": 117, "alphanum_fraction": 0.6421911422, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813526452772, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.8067479797542043}} {"text": "# ------------------------------------------------------------------\n# Licensed under the MIT License. See LICENSE in the project root.\n# ------------------------------------------------------------------\n\n\"\"\"\n EigenAnalysis(proj; maxdim=nothing, pratio=1.0)\n\nThe eigenanalysis of the covariance with a given projection `proj`.\nOptionally specify the maximum number of dimensions in the output `maxdim`\nand the percentage of variance to retain `pratio`. Default to all dimensions of\nthe input.\n\n## Projections\n\n* `:V` - Uncorrelated variables (PCA transform)\n* `:VD` - Uncorrelated variables and variance one (DRS transform)\n* `:VDV` - Uncorrelated variables and variance one (SDS transformation)\n\nThe `:V` projection used in the PCA transform projects the data on the eigenvectors\nV of the covariance matrix.\n\nThe `:VD` projection used in the DRS transform. Similar to the `:V` projection,\nbut the eigenvectors are multiplied by the squared inverse of the eigenvalues D.\n\nThe `:VDV` projection used in the SDS transform. Similar to the `:VD` transform,\nbut the data is projected back to the basis of the original variables using the Vᵀ matrix.\n\nSee [https://geostatisticslessons.com/lessons/sphereingmaf](https://geostatisticslessons.com/lessons/sphereingmaf)\nfor more details about these three variants of eigenanalysis.\n\n# Examples\n\n```julia\nEigenAnalysis(:V)\nEigenAnalysis(:VD)\nEigenAnalysis(:VDV)\nEigenAnalysis(:V, maxdim=3)\nEigenAnalysis(:VD, pratio=0.99)\nEigenAnalysis(:VDV, maxdim=3, pratio=0.99)\n```\n\"\"\"\nstruct EigenAnalysis <: Transform\n proj::Symbol\n maxdim::Union{Int,Nothing}\n pratio::Float64\n\n function EigenAnalysis(proj, maxdim, pratio)\n @assert proj ∈ (:V, :VD, :VDV) \"Invalid projection.\"\n @assert 0 ≤ pratio ≤ 1 \"Invalid pratio.\"\n new(proj, maxdim, pratio)\n end\nend\n\nEigenAnalysis(proj; maxdim=nothing, pratio=1.0) = \n EigenAnalysis(proj, maxdim, pratio)\n\nassertions(::Type{EigenAnalysis}) = [assert_continuous]\n\nisrevertible(::Type{EigenAnalysis}) = true\n\nfunction apply(transform::EigenAnalysis, table)\n # basic checks\n for assertion in assertions(transform)\n assertion(table)\n end\n\n # original columns names\n cols = Tables.columns(table)\n onames = Tables.columnnames(cols)\n\n # table as matrix\n X = Tables.matrix(table)\n\n # center the data\n μ = mean(X, dims=1)\n Y = X .- μ\n\n # eigenanalysis of covariance\n S, S⁻¹ = eigenmatrices(transform, Y)\n\n # project the data\n Z = Y * S\n\n # column names\n names = Symbol.(:PC, 1:size(Z, 2))\n\n # table with transformed columns\n 𝒯 = (; zip(names, eachcol(Z))...)\n newtable = 𝒯 |> Tables.materializer(table)\n\n newtable, (μ, S, S⁻¹, onames)\nend\n\nfunction revert(::EigenAnalysis, newtable, cache)\n # table as matrix\n Z = Tables.matrix(newtable)\n\n # retrieve cache\n μ, S, S⁻¹, onames = cache\n\n # undo projection\n Y = Z * S⁻¹\n\n # undo centering\n X = Y .+ μ\n\n # table with original columns\n 𝒯 = (; zip(onames, eachcol(X))...)\n 𝒯 |> Tables.materializer(newtable)\nend\n\nfunction reapply(transform::EigenAnalysis, table, cache)\n # basic checks\n for assertion in assertions(transform)\n assertion(table)\n end\n\n # table as matrix\n X = Tables.matrix(table)\n\n # retrieve cache\n μ, S, S⁻¹, onames = cache\n\n # center the data\n Y = X .- μ\n\n # project the data\n Z = Y * S\n\n # column names\n names = Symbol.(:PC, 1:size(Z, 2))\n\n # table with transformed columns\n 𝒯 = (; zip(names, eachcol(Z))...)\n 𝒯 |> Tables.materializer(table)\nend\n\n_maxdim(maxdim::Int, Y) = maxdim\n_maxdim(::Nothing, Y) = size(Y, 2)\n\nfunction outdim(transform, Y, λ)\n pratio = transform.pratio\n csums = cumsum(λ) \n ratios = csums ./ last(csums)\n mdim = _maxdim(transform.maxdim, Y)\n pdim = findfirst(≥(pratio), ratios)\n min(mdim, pdim)\nend\n\nfunction eigenmatrices(transform, Y)\n proj = transform.proj\n\n Σ = cov(Y)\n λ, V = eigen(Σ, sortby=λ -> -real(λ))\n\n if proj == :V\n S = V\n S⁻¹ = transpose(V)\n elseif proj == :VD\n Λ = Diagonal(sqrt.(λ))\n S = V * inv(Λ)\n S⁻¹ = Λ * transpose(V)\n elseif proj == :VDV\n Λ = Diagonal(sqrt.(λ))\n S = V * inv(Λ) * transpose(V)\n S⁻¹ = V * Λ * transpose(V)\n end\n\n d = outdim(transform, Y, λ)\n\n S[:, 1:d], S⁻¹[1:d, :]\nend\n\n\"\"\"\n PCA(; maxdim=nothing, pratio=1.0)\n\nThe PCA transform is a shortcut for\n`ZScore() → EigenAnalysis(:V; maxdim, pratio)`.\n\nSee also: [`ZScore`](@ref), [`EigenAnalysis`](@ref).\n\n# Examples\n\n```julia\nPCA(maxdim=2)\nPCA(pratio=0.86)\nPCA(maxdim=2, pratio=0.86)\n```\n\"\"\"\nPCA(; maxdim=nothing, pratio=1.0) = \n ZScore() → EigenAnalysis(:V, maxdim, pratio)\n\n\"\"\"\n DRS(; maxdim=nothing, pratio=1.0)\n\nThe DRS transform is a shortcut for\n`ZScore() → EigenAnalysis(:VD; maxdim, pratio)`.\n\nSee also: [`ZScore`](@ref), [`EigenAnalysis`](@ref).\n\n# Examples\n\n```julia\nDRS(maxdim=3)\nDRS(pratio=0.87)\nDRS(maxdim=3, pratio=0.87)\n```\n\"\"\"\nDRS(; maxdim=nothing, pratio=1.0) = \n ZScore() → EigenAnalysis(:VD, maxdim, pratio)\n\n\"\"\"\n SDS(; maxdim=nothing, pratio=1.0)\n\nThe SDS transform is a shortcut for\n`ZScore() → EigenAnalysis(:VDV; maxdim, pratio)`.\n\nSee also: [`ZScore`](@ref), [`EigenAnalysis`](@ref).\n\n# Examples\n\n```julia\nSDS()\nSDS(maxdim=4)\nSDS(pratio=0.88)\nSDS(maxdim=4, pratio=0.88)\n```\n\"\"\"\nSDS(; maxdim=nothing, pratio=1.0) = \n ZScore() → EigenAnalysis(:VDV, maxdim, pratio)\n", "meta": {"hexsha": "13c1d7beae13fd4f5c27ebea2b3c8e3952c34e97", "size": 5253, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/transforms/eigenanalysis.jl", "max_stars_repo_name": "JuliaML/TableTransforms.jl", "max_stars_repo_head_hexsha": "90a30ba6a0d821e15478c2bcdec47fbea3cca1f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38, "max_stars_repo_stars_event_min_datetime": "2021-10-29T21:22:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T16:48:35.000Z", "max_issues_repo_path": "src/transforms/eigenanalysis.jl", "max_issues_repo_name": "JuliaML/TableTransforms.jl", "max_issues_repo_head_hexsha": "90a30ba6a0d821e15478c2bcdec47fbea3cca1f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2021-10-30T10:38:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:14:21.000Z", "max_forks_repo_path": "src/transforms/eigenanalysis.jl", "max_forks_repo_name": "JuliaML/TableTransforms.jl", "max_forks_repo_head_hexsha": "90a30ba6a0d821e15478c2bcdec47fbea3cca1f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-11-03T22:10:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T11:27:07.000Z", "avg_line_length": 22.7402597403, "max_line_length": 114, "alphanum_fraction": 0.6542927851, "num_tokens": 1641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067276593031, "lm_q2_score": 0.8558511506439708, "lm_q1q2_score": 0.8066454673568981}} {"text": "#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n# Program: pi_monte_carlo.jl\r\n# Monte-Carlo calculation of PI\r\n#\r\n# Usage: julia pi_monte_carlo.jl\r\n#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\nfunction montepi(n::Int)\r\n R = 1.0\r\n s = 0\r\n for i = 1: n\r\n x = R * rand()\r\n y = R * rand()\r\n if x^2 + y^2 <= R^2\r\n s = s + 1\r\n end\r\n end\r\n return 4.0*s/n\r\nend\r\n\r\n# Main program\r\nfor i in 3: 8\r\n n = 10^i\r\n p = montepi(n)\r\n println(\"N = $n: PI = $p\")\r\nend", "meta": {"hexsha": "849676f780b18e65c1aeb75087bcda650bc34242", "size": 534, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia_test.jl", "max_stars_repo_name": "nikhilklath/julia-test", "max_stars_repo_head_hexsha": "85b32126efcbe23447bc1ea3c7eead69a2c8dc2b", "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": "julia_test.jl", "max_issues_repo_name": "nikhilklath/julia-test", "max_issues_repo_head_hexsha": "85b32126efcbe23447bc1ea3c7eead69a2c8dc2b", "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": "julia_test.jl", "max_forks_repo_name": "nikhilklath/julia-test", "max_forks_repo_head_hexsha": "85b32126efcbe23447bc1ea3c7eead69a2c8dc2b", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.36, "max_line_length": 61, "alphanum_fraction": 0.361423221, "num_tokens": 173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9362850021922959, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.806645309298796}} {"text": "module ch1\n\nimport StatsBase; sb = StatsBase\n\n# Page 4\ncount = 600_000\nsample = [1:6...]\n\nx = sb.sample(sample, count, replace=true)\nP = sum(x.==3)/count\n\n@show P\n\n# Page 5\nwins = zeros(Int32, 1, count)\nwins .= 0\nfor ind = 1:length(wins)\n d = sb.sample(sample, 2)\n if sum(d) == 7 || sum(d) == 11\n wins[ind] = 1\n end\nend\nwins_count = sum(wins)\n\n@show wins_count\n@show wins_count/count\n\n# Page 7\n# PDF: Probability Density Function\nusing Plotly\ny = [0,1]\np = [1,1]\nline = scatter(x=y, y=p, mode=\"lines\") # \"lines+markers\"\nlayout = Layout(\n title=\"PDF\",\n # mirror for the bounding box\n xaxis=attr(title=\"y\", linecolor=\"black\", mirror=true),\n yaxis=attr(title=\"p(y)\", range=[0,1.1], linecolor=\"black\", mirror=true)\n)\npt = plot([line], layout)\n#display(pt)\n\n# Page 10\nimport RDatasets; rdata = RDatasets\nimport CSV\nimport DataFrames; DF = DataFrames\nimport Distributions; Dist=Distributions\n#using StringEncodings\n\nif !isfile(\"discoveries.csv\")\n download(\"https://raw.githubusercontent.com/vincentarelbundock/Rdatasets/master/csv/datasets/discoveries.csv\",\n \"discoveries.csv\")\nend\n#med = rdata.dataset(\"datasets\", \"discoveries\")\n# frame = df.DataFrame()\n#frame = CSV.read(\"discoveries.csv\", df)\ndf = CSV.File(open(read, \"discoveries.csv\")) |> DF.DataFrame\n@show names(df)\n#@show frame\n\n# Histogram\nhist = histogram(x=df.value, histnorm=\"probability\")\n# Poisson distribution\nd = Dist.Poisson(3.1)\nx = range(0,12,length=13)\nline = scatter(x=x,y=Dist.pdf.(d,x))\n# Plot\nlayout = Layout(title=\"Discoveries\")\npt = plot([hist, line], layout)\n#display(pt)\n\n\n# 1.3.1 The Binomial Distribution\n\n# Page 14\n# θ is a parameter\n# Θ is set of θ\n# Binomial\n\n# Page 16\nd = Dist.Binomial(3,0.1)\nx = range(0,3,length=4)\nscat = scatter(x=x,y=Dist.pdf.(d,x), mode=\"markers\",\n #opacity=0.1\n marker=attr(size=15, opacity=1, color=\"transparent\",\n line=attr(color=\"black\", width=2)\n )\n)\nlayout = Layout(title=\"N=3, p=0.1\")\npt = plot([scat], layout)\n#display(pt)\nsavefig(pt, \"binomial.png\", format=\"png\")\nsavefig(pt, \"binomial.html\", format=\"html\")\n\nscat_list = Vector{AbstractTrace}()\nd = Dist.Binomial(3,0.1)\nx = range(0,3,length=4)\nscat = scatter(x=x,y=Dist.pdf.(d,x), mode=\"markers\",\n #opacity=0.1\n marker=attr(size=15, opacity=1, color=\"transparent\",\n line=attr(color=\"black\", width=2)\n )\n)\npush!(scat_list,scat)\n\n\nd = Dist.Binomial(3,0.5)\nscat = scatter(x=x,y=Dist.pdf.(d,x), mode=\"markers\",\n xaxis=\"x2\", yaxis=\"y2\",\n #opacity=0.1\n marker=attr(size=15, opacity=1, color=\"transparent\",\n line=attr(color=\"black\", width=2)\n )\n)\npush!(scat_list, scat)\n# show how to plot multiple traces in one subplot\nline = scatter(x=x, y=Dist.pdf.(d,x), mode=\"lines\",\n xaxis=\"x2\", yaxis=\"y2\",\n line=attr(color=\"black\", width=2)\n)\npush!(scat_list, line)\n\nd = Dist.Binomial(3,0.9)\nscat = scatter(x=x,y=Dist.pdf.(d,x), mode=\"markers\",\n xaxis=\"x3\", yaxis=\"y3\",\n #opacity=0.1\n marker=attr(size=15, opacity=1, color=\"transparent\",\n line=attr(color=\"black\", width=2)\n )\n)\npush!(scat_list, scat)\n\nx = range(0,30,length=31)\nd = Dist.Binomial(30,0.1)\nscat = scatter(x=x,y=Dist.pdf.(d,x), mode=\"markers\",\n xaxis=\"x4\", yaxis=\"y4\",\n #opacity=0.1\n marker=attr(size=10, opacity=1, color=\"transparent\",\n line=attr(color=\"black\", width=2)\n )\n)\npush!(scat_list, scat)\n\nx = range(0,30,length=31)\nd = Dist.Binomial(30,0.5)\nscat = scatter(x=x,y=Dist.pdf.(d,x), mode=\"markers\",\n xaxis=\"x5\", yaxis=\"y5\",\n #opacity=0.1\n marker=attr(size=10, opacity=1, color=\"transparent\",\n line=attr(color=\"black\", width=2)\n )\n)\npush!(scat_list, scat)\n\nx = range(0,30,length=31)\nd = Dist.Binomial(30,0.9)\nscat = scatter(x=x,y=Dist.pdf.(d,x), mode=\"markers\",\n xaxis=\"x6\", yaxis=\"y6\",\n #opacity=0.1\n marker=attr(size=10, opacity=1, color=\"transparent\",\n line=attr(color=\"black\", width=2)\n )\n)\npush!(scat_list, scat)\n\nlayout = Layout(title=\"N=3, p=0.1\",\n grid=attr(rows=2, columns=3, pattern=\"independent\")\n #yaxis2=attr(range=[0,0.4])\n )\npt = plot(scat_list, layout)\n#display(pt)\n\n# Example 1.3, page 15\n# The hard way\n# P[X=k | theta] = binomial(N,k) * theta^k * (1-theta)^(N-k)\n# P[X >= 1] =\nAns = 0.0\ntheta = 2/9\nN = 4\nfor ind = 1:N\n global Ans\n P = binomial(N,ind) * theta^ind * (1-theta)^(N-ind)\n Ans += P\nend\nprintln(\"Example 1.3, Ans = $Ans\")\n\n# The easy way\ndist = Dist.Binomial(4,2/9)\nAns = 1 - Dist.cdf(dist,0)\nprintln(\"Example 1.3, Ans = $Ans\")\n\n# The R way\nusing RCall\nR\"x <- 1 - dbinom(0,4,2/9)\"\nAns = @rget x\nprintln(\"Example 1.3, the R-way, Ans=$Ans\")\n\n# 1.3.2 The Poisson Distribution, page 17\nx = range(0,100,length=101)\nd = Dist.Poisson(60)\nscat = scatter(x=x,y=Dist.pdf.(d,x), mode=\"lines\")\ncdf = scatter(x=x,y=Dist.cdf.(d,x), mode=\"lines\", yaxis=\"y2\")\nlayout = Layout(title=\"lambda=3\",\n yaxis=attr(title=\"PDF\"),\n yaxis2=attr(side=\"right\", overlaying=\"y\")\n)\npt = plot([scat,cdf], layout)\ndisplay(pt)\n\n# Page 19\n# Need to run from terminal to pop R-plot\nR\"lam <- seq(0, 10, length=50)\"\nR\"y <- dpois(3, lam)\"\nR\"plot(lam, y, xlab=\\\"lambda\\\", ylab=\\\"P[x=3]\\\", type=\\\"l\\\")\"\n\nend\nnothing #suppress printing of Main...\n", "meta": {"hexsha": "b6b6bb2b448f2e54a3efbc686e6e8671d5ee5eff", "size": 5137, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "intro_stat_thought/ch1.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": "intro_stat_thought/ch1.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": "intro_stat_thought/ch1.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": 23.5642201835, "max_line_length": 114, "alphanum_fraction": 0.6375316332, "num_tokens": 1799, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850110816422, "lm_q2_score": 0.8615382058759129, "lm_q1q2_score": 0.8066453086357872}} {"text": "# ### m11.5t.jl\n\nusing Pkg, DrWatson\n\n@quickactivate \"StatisticalRethinkingTuring\"\nusing Turing\nusing StatisticalRethinking\nTuring.setprogress!(false)\n\ndelim=';'\ndf = CSV.read(sr_datadir(\"UCBadmit.csv\"), DataFrame; delim);\n\n# Turing model\n\n@model ppl11_5(admit, applications) = begin\n N=length(applications)\n θ ~ truncated(Exponential(1), 0, Inf)\n α ~ Normal(0,2)\n\n for i ∈ 1:N\n prob = logistic(α)\n\n # alpha and beta for the BetaBinomial must be provided.\n # The two parameterizations are related by\n # alpha = prob * theta, and beta = (1-prob) * theta.\n # See https://github.com/rmcelreath/rethinking/blob/master/man/dbetabinom.Rd\n alpha = prob * θ\n beta = (1 - prob) * θ\n\n admit[i] ~ BetaBinomial(applications[i], alpha, beta)\n end\nend\n\n# Sample\n\nm11_5t = ppl11_5(df.admit, df.applications)\nnchains = 4; sampler = NUTS(0.65); nsamples=2000\nchns11_5t = mapreduce(c -> sample(m11_5t, sampler, nsamples), chainscat, 1:nchains)\n\n# Result rethinking\n\nm11_5s = \"\n mean sd 5.5% 94.5% n_eff Rhat\nθ 2.74 0.96 1.43 4.37 3583 1\na -0.37 0.31 -0.87 0.12 3210 1\n\";\n\n# End of `11/m811.5t.jl`\n", "meta": {"hexsha": "086d9a7daf778db15e664116e3c0308b588db6ad", "size": 1185, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "models/11/m11.5t.jl", "max_stars_repo_name": "kertase/StatisticalRethinkingTuring.jl", "max_stars_repo_head_hexsha": "dd472f224590a3c8466a7a3ecb519f004906d369", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 63, "max_stars_repo_stars_event_min_datetime": "2020-10-01T23:35:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T11:48:45.000Z", "max_issues_repo_path": "models/11/m11.5t.jl", "max_issues_repo_name": "kertase/StatisticalRethinkingTuring.jl", "max_issues_repo_head_hexsha": "dd472f224590a3c8466a7a3ecb519f004906d369", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-11-24T21:59:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T12:34:49.000Z", "max_forks_repo_path": "models/11/m11.5t.jl", "max_forks_repo_name": "kertase/StatisticalRethinkingTuring.jl", "max_forks_repo_head_hexsha": "dd472f224590a3c8466a7a3ecb519f004906d369", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2020-11-30T18:25:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-25T06:59:27.000Z", "avg_line_length": 24.1836734694, "max_line_length": 84, "alphanum_fraction": 0.6388185654, "num_tokens": 414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850039701655, "lm_q2_score": 0.8615382040983515, "lm_q1q2_score": 0.8066453008446742}} {"text": "\"\"\"\n expand_poly(x, [degree = 5], [obsdim]) -> Matrix\n\nPerform a polynomial basis expansion of the given `degree` for\nthe vector `x`.\n\nThe optional parameter `obsdim` can be used to specify which\ndimension of the resulting `Matrix` should denote the\nobservations. By default the each column will denote an\nobservation, which means that the returning `Matrix` will have\nthe size `(degree, length(x))`.\n\n```julia\njulia> expand_poly(1:5, degree = 3)\n3×5 Array{Float64,2}:\n 1.0 2.0 3.0 4.0 5.0\n 1.0 4.0 9.0 16.0 25.0\n 1.0 8.0 27.0 64.0 125.0\n\njulia> expand_poly(1:5, 3); # same but type-stable\n```\n\nIf you want each row to denote an observation you can set\n`obsdim = 1`.\n\n```julia\njulia> expand_poly(1:5, degree = 3, obsdim = 1)\n5×3 Array{Float64,2}:\n 1.0 1.0 1.0\n 2.0 4.0 8.0\n 3.0 9.0 27.0\n 4.0 16.0 64.0\n 5.0 25.0 125.0\n\njulia> expand_poly(1:5, 3, ObsDim.First()); # same but type-stable\n```\n\"\"\"\nfunction expand_poly(x::AbstractVector; degree::Integer = 5, obsdim = ObsDim.Last())\n expand_poly(x, degree, convert(LearnBase.ObsDimension, obsdim))\nend\n\nfunction expand_poly(x::AbstractVector, degree::Integer, ::ObsDim.Last)\n expand_poly(x, degree, ObsDim.Constant{2}())\nend\n\nfunction expand_poly{T<:Number}(x::AbstractVector{T}, degree::Integer, ::ObsDim.Constant{2} = ObsDim.Constant{2}())\n n = length(x)\n # FIXME: consider support for colorants (i.e. don't hardcode Float64)\n x_vec = convert(Vector{Float64}, x)\n X = zeros(Float64, (degree, n))\n @inbounds for i = 1:n\n for d = 1:degree\n X[d, i] += x_vec[i]^(d)\n end\n end\n X\nend\n\nfunction expand_poly{T<:Number}(x::AbstractVector{T}, degree::Integer, ::ObsDim.Constant{1})\n n = length(x)\n # FIXME: consider support for colorants (i.e. don't hardcode Float64)\n x_vec = convert(Vector{Float64}, x)\n X = zeros(Float64, (n, degree))\n @inbounds for d = 1:degree\n for i = 1:n\n X[i, d] += x_vec[i]^(d)\n end\n end\n X\nend\n", "meta": {"hexsha": "c6cf67036c2ada3daea93fb012b6d61fd6c30e08", "size": 1998, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/basis_expansion.jl", "max_stars_repo_name": "oxinabox/MLPreprocessing.jl", "max_stars_repo_head_hexsha": "5e6ffad72a2dd9a8781218aab79b79b65c365190", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/basis_expansion.jl", "max_issues_repo_name": "oxinabox/MLPreprocessing.jl", "max_issues_repo_head_hexsha": "5e6ffad72a2dd9a8781218aab79b79b65c365190", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/basis_expansion.jl", "max_forks_repo_name": "oxinabox/MLPreprocessing.jl", "max_forks_repo_head_hexsha": "5e6ffad72a2dd9a8781218aab79b79b65c365190", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1408450704, "max_line_length": 115, "alphanum_fraction": 0.6396396396, "num_tokens": 703, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91243616285804, "lm_q2_score": 0.8840392863287585, "lm_q1q2_score": 0.8066294142335725}} {"text": "# ------------------------------------------------------------------------------------------\n#\n#\n# This notebook accompanies the [workshop paper](http://jiahao.github.io/parallel-prefix/)\n# by Jiahao Chen and Alan Edelman entitled \"Parallel Prefix Polymorphism Permits\n# Parallelization, Presentation & Proof\" and will appear in the proceedings of the [First\n# Workshop for High Performance Technical Computing in Dynamic\n# Languages](http://jiahao.github.io/hptcdl-sc14/), held in conjunction with [SC14: The\n# International Conference on High Performance Computing, Networking, Storage and\n# Analysis](http://sc14.supercomputing.org/).\n#\n# \n# ------------------------------------------------------------------------------------------\n\n# using Pkg; Pkg.add([\"Compose\", \"Gadfly\", \"Interact\"])\nusing Compose, Gadfly, Interact\n\n# ------------------------------------------------------------------------------------------\n# # `reduce()`\n#\n# Reduction applies a binary operator to a vector repeatedly to return a scalar. Thus +\n# becomes sum, and * becomes prod.\n#\n# It is considered a basic parallel computing primitive.\n#\n# \n# ------------------------------------------------------------------------------------------\n\nreduce(+, 1:8), sum(1:8) # triangular numbers\n\nreduce(*, 1:8), prod(1:8) # factorials\n\nboring(a,b)=a\n@show reduce(boring, 1:8)\nboring2(a,b)=b\n@show reduce(boring2, 1:8)\n\n# ------------------------------------------------------------------------------------------\n# You can also use reduce to compute Fibonacci numbers using their recurrences.\n#\n# $$\\begin{pmatrix} f_2 \\\\f_1 \\end{pmatrix} = \\begin{pmatrix} f_1 + f_0 \\\\ f_1 \\end{pmatrix}\n# = \\begin{pmatrix} 1 & 1 \\\\ 1 & 0 \\end{pmatrix} \\begin{pmatrix} f_1 \\\\ f_0 \\end{pmatrix} $$\n#\n# $$\\begin{pmatrix} f_{n+1} \\\\ f_n \\end{pmatrix} = \\dots\n# = \\begin{pmatrix} 1 & 1 \\\\ 1 & 0 \\end{pmatrix}^n \\begin{pmatrix} f_1 \\\\ f_0 \\end{pmatrix}\n# $$\n#\n# From this, you can show that\n#\n# $$\\begin{pmatrix} 1 & 1 \\\\ 1 & 0 \\end{pmatrix}^n = \\begin{pmatrix} f_{n+1} & f_n \\\\ f_n &\n# f_{n-1} \\end{pmatrix} $$\n#\n# (this applies reduce to the same argument over and over again -- there are of course other\n# ways)\n# ------------------------------------------------------------------------------------------\n\nM=[1 1; 1 0]\nreduce(*,fill(M,3))\nprod(fill(M,3))\n\n@manipulate for n=1:100\n prod(fill(big.(M),n))\nend\n\nfib(j)=reduce(*, fill(M,j))\nfib.([4,7])\n\n\n# ------------------------------------------------------------------------------------------\n# You can solve recurrences of any complexity using `reduce`. For example, `reduce` can\n# compute a Hadamard matrix from its definition in terms of its submatrices:\n#\n# $$H_2 = \\begin{pmatrix} H_1 & H_1 \\\\ H_1 & -H_1 \\end{pmatrix} = \\begin{pmatrix} 1 & 1 \\\\ 1\n# & -1 \\end{pmatrix} \\otimes H_1$$\n#\n# and so on.\n#\n# (Note: this is just using reduce to compute a matrix power.\n# One can think of alternative ways for sure.)\n# ------------------------------------------------------------------------------------------\n\n# [A B]\n# If A is m x n\n# If B is p x q\n# then kron(A,B) is mp x nq and has all the elements of A times all of the elements of B\n\nA=[1 2;3 4]\nB=[10 100; 1 -10]\n⊗(A,B)=kron(A,B)\n\nM=[ 1 1;1 -1]\nH=⊗(⊗(⊗(M,M),M),M)\nH*H'\n\nHadamard(n)=reduce(⊗, fill(M,n))\nH=Hadamard(3)\n\nH'H\n\nH*H' #This is a legitimate Hadamard matrix\n\nusing StatsBase\n\nrolldice() = rand(1:6)+rand(1:6)\nrolls(n)=fit(Histogram,[rolldice() for i=1:n ],2:12,closed=:left)\n\nrolls(1000)\n\n[rolls(100) for i=1:10]\n\nreduce(merge,[rolls(100) for i=1:10])\n\n#Reduction of matrix multiplications\nM=[rand(-3:3,2,2) for i=1:4]\n\ndisplay(M[4]*M[3]*M[2]*M[1])\ndisplay(reduce((A,B)->B*A, M)) #backward multiply\ndisplay(reduce(*, M)) #forward multiply\n\n# ------------------------------------------------------------------------------------------\n# In the following example we apply `reduce()` to function composition:\n# ------------------------------------------------------------------------------------------\n\n(sin ∘ cos)(1), sin(cos(1))\n\n((-) ∘ sin)(1), -sin(1)\n\n( (!) ∘ )\n\n# h=reduce( (f,g) -> (x->f(g(x))), [sin cos tan])\nh=reduce(∘, [sin cos tan])\n[h(π) sin(cos(tan(π)))]\n\ncumsum(1:8) # It is useful to know that cumsum is a linear operator\n# You can use power method! Below is the underlying matrix\nA=tril(ones(Int,8,8)) \n\n[A*(1:8),cumsum(1:8)]\n\n# ------------------------------------------------------------------------------------------\n# # `prefix`\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# Having discussed `reduce`, we are now ready for the idea behind prefix sum.\n# Prefix or scan is long considered an important parallel\n# primitive as well.\n#\n# Suppose you wanted to compute the partial sums of a vector, i.e. given\n# `y[1:n]`, we want to overwrite the vector `y` with the vector of partial sums\n#\n# ```julia\n# new_y[1] = y[1]\n# new_y[2] = y[1] + y[2]\n# new_y[3] = y[1] + y[2] + y[3]\n# ...\n# ```\n#\n# At first blush, it seems impossible to parallelize this, since\n#\n# ```julia\n# new_y[1] = y[1]\n# new_y[2] = new_y[1] + y[2]\n# new_y[3] = new_y[2] + y[3]\n# ...\n# ```\n#\n# which appears to be an intrinsically serial process.\n# ------------------------------------------------------------------------------------------\n\nfunction prefix_serial!(y, ⊕)\n for i=2:length(y)\n y[i] = y[i-1] ⊕ y[i]\n end\n y\nend\n\nprefix_serial!([1:8;],*)\n\nprefix_serial!([rand(1:5,2,2) for i=1:4],*)\n\n# ------------------------------------------------------------------------------------------\n# However, it turns out that because addition (`+`) is associative, we can regroup the\n# _order_ of how these sums are carried out. (This of course extends to other associative\n# operations such as multiplication.) Another ordering of 8 associative operations is\n# provided by `prefix8!`:\n# ------------------------------------------------------------------------------------------\n\n# Eight only for pedagogy\nfunction prefix8!(y, ⋅)\n length(y)==8 || error(\"length 8 only\")\n for i in [2,4,6,8]; y[i] = y[i-1] ⋅ y[i]; end\n for i in [ 4, 8]; y[i] = y[i-2] ⋅ y[i]; end\n for i in [ 8]; y[i] = y[i-4] ⋅ y[i]; end\n for i in [ 6 ]; y[i] = y[i-2] ⋅ y[i]; end\n for i in [ 3,5,7 ]; y[i] = y[i-1] ⋅ y[i]; end\n y\nend\n\n# Generalization to any n\nfunction prefix!(y, ⋅)\n l=length(y)\n k=ceil(Int, log2(l))\n @inbounds for j=1:k, i=2^j:2^j:min(l, 2^k) #\"reduce\"\n y[i] = y[i-2^(j-1)] ⋅ y[i]\n end\n @inbounds for j=(k-1):-1:1, i=3*2^(j-1):2^j:min(l, 2^k) #\"broadcast\"\n y[i] = y[i-2^(j-1)] ⋅ y[i]\n end\n y\nend\n\nprefix!([1:12;],*)\n\n# ------------------------------------------------------------------------------------------\n# # Polymorphism for visualization\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# We can visualize the operations with a little bit of trickery. In Julia, arrays are simply\n# types that expose the array protocol. In particular, they need to implement methods for\n# the generic functions `length`, `getindex` and `setindex!`. The last two are used in\n# indexing operations, since statements\n#\n# y = A[1]\n# A[3] = y\n#\n# get desugared to\n#\n# y = getindex(A, 1)\n# setindex!(A, y, 3)\n#\n# respectively.\n#\n# We can trace through the iterable by introduce a dummy array type, `DummyArray`, which\n# stores no useful information but records every access to `getindex` and `setindex!`.\n#\n# Specifically:\n#\n# - `length(A::DummyArray)` returns an integer that is stored internally in the `A.length`\n# field\n# - `getindex(A::DummyArray, i)` records read access to the index `i` in the `A.read` field\n# and always retuns `nothing`.\n# - `setindex!(A::DummyArray, x, i)` records write access to the index `i`. The `A.history`\n# field is appended with a new tuple consisting of the current `A.read` field and the index\n# `i`.\n#\n# The way `DummyArray` works, it assumes an association between a single `setindex!` call\n# and and all the preceding `getindex` calls since the previous `setindex!` call, which is\n# sufficient for the purposes of tracing through prefix calls.\n# ------------------------------------------------------------------------------------------\n\nimport Base: getindex, setindex!, length\n\nisdefined(:DummyArray) || type DummyArray\n length :: Int\n read :: Vector\n history :: Vector{Any}\n DummyArray(length, read=[], history=[])=new(length, read, history)\nend\n\nlength(A::DummyArray)=A.length\n\nfunction getindex(A::DummyArray, i)\n push!(A.read, i)\n nothing\nend\n\nfunction setindex!(A::DummyArray, x, i)\n push!(A.history, (A.read, [i]))\n A.read = []\nend\n\nM = DummyArray(4)\n\nM[7] = M[3] + M[2]\nM\n\nimport Base.+\n+(a::Void, b::Void)=a\n\n@manipulate for i=1:100\n M = DummyArray(4)\n M[i] = M[i-2] + M[2*i]\n M\nend\n\n# ------------------------------------------------------------------------------------------\n# We also need a dummy associative operator to pass to the prefix call.\n# ------------------------------------------------------------------------------------------\n\nA=prefix8!(DummyArray(8),+)\n\nA.history\n\n# ------------------------------------------------------------------------------------------\n# Now let's visualize this! Each entry in `A.history` is rendered by a gate object:\n# ------------------------------------------------------------------------------------------\n\nmutable struct gate\n ins :: Vector\n outs:: Vector\nend\n\nimport Gadfly.render\n\nfunction render(G::gate, x₁, y₁, y₀; rᵢ=0.1, rₒ=0.25)\n ipoints = [(i, y₀+rᵢ) for i in G.ins]\n opoints = [(i, y₀+0.5) for i in G.outs]\n igates = [Compose.circle(i..., rᵢ) for i in ipoints]\n ogates = [Compose.circle(i..., rₒ) for i in opoints]\n lines = [line([i, j]) for i in ipoints, j in opoints]\n compose(context(units=UnitBox(0.5,0,x₁,y₁+1)),\n compose(context(), stroke(colorant\"black\"), fill(colorant\"white\"),\n igates..., ogates...),\n compose(context(), linewidth(0.3mm), stroke(colorant\"black\"),\n lines...))\nend\n\nA=gate([1,2],[2])\nrender(A,2,0,0)\n\n# ------------------------------------------------------------------------------------------\n# Now we render the whole algorithm. We have to scan through the trace twice; the first time\n# merely calculates the maximum depth that needs to be drawn and the second time actually\n# generates the objects.\n# ------------------------------------------------------------------------------------------\n\nfunction render(A::DummyArray)\n #Scan to find maximum depth\n olast = depth = 0\n for y in A.history\n (any(y[1] .≤ olast)) && (depth += 1)\n olast = maximum(y[2])\n end\n maxdepth = depth\n \n olast = depth = 0\n C = []\n for y in A.history\n (any(y[1] .≤ olast)) && (depth += 1)\n push!(C, render(gate(y...), A.length, maxdepth, depth))\n olast = maximum(y[2])\n end\n \n push!(C, compose(context(units=UnitBox(0.5,0,A.length,1)),\n [line([(i,0), (i,1)]) for i=1:A.length]...,\n linewidth(0.1mm), stroke(colorant\"grey\")))\n compose(context(), C...)\nend\n\nrender(prefix!(DummyArray(8), +))\n\n# ------------------------------------------------------------------------------------------\n# Now we can see that `prefix!` rearranges the operations to form two spanning trees:\n# ------------------------------------------------------------------------------------------\n\nrender(prefix!(DummyArray(120),+))\n\nfunction prefix!(y, +)\n l=length(y)\n k=ceil(Int, log2(l))\n @inbounds for j=1:k, i=2^j:2^j:min(l, 2^k) #\"reduce\"\n y[i] = y[i-2^(j-1)] + y[i]\n end\n @inbounds for j=(k-1):-1:1, i=3*2^(j-1):2^j:min(l, 2^k) #\"broadcast\"\n y[i] = y[i-2^(j-1)] + y[i]\n end\n y\nend\n@show prefix!(DummyArray(8),+)\nrender(prefix!(DummyArray(9),+))\n\n#Look at the compose tree\n#render(prefix8!(AccessArray(8),+)) |> introspect\n\n# ------------------------------------------------------------------------------------------\n# as contrasted with the serial code:\n# ------------------------------------------------------------------------------------------\n\nrender(prefix_serial!(DummyArray(8),+))\n\n@manipulate for npp=1:180\n render(prefix!(DummyArray(npp),+))\nend\n\n@manipulate for npp=1:180\n render(prefix_serial!(DummyArray(npp),+))\nend\n\ndraw(PDF(\"serial.pdf\", 3.5inch, 3.5inch), render(prefix_serial!(AccessArray(8),+)))\ndraw(PDF(\"tree.pdf\", 3.5inch, 3.5inch), render(prefix8!(AccessArray(8),+)))\n\n# ------------------------------------------------------------------------------------------\n# # Polymorphism for parallel operations\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# Now let's run `prefix` in parallel on every core on the CPU. Use `addprocs` to attach\n# additional worker processes.\n# ------------------------------------------------------------------------------------------\n\nimport Base: fetch, length, +, *\nfetch(t::Vector) = map(fetch, t) #Vectorize fetch\n\n#Define elementary operations on remote data\nlength(r1::Future)=length(fetch(r1))\n+(r1::Future,r2::Future)=@spawnat r2.where fetch(r1)+fetch(r2)\n*(r1::Future,r2::Future)=@spawnat r2.where fetch(r1)*fetch(r2)\n\n# ------------------------------------------------------------------------------------------\n# For 8 processes, the serial version requires 7 operations. The parallel version uses 11\n# operations, but they are grouped into 5 simultaneous chunks of operations. Hence we expect\n# that the parallel version runs in 5/7 the time needed for the naïve serial code.\n# ------------------------------------------------------------------------------------------\n\n#Before timing, force Julia to JIT compile the functions\n[f([randn(3,3) for i=1:2], *) for f in (prefix_serial!, prefix!)]\n\n# addprocs(max(0, Sys.CPU_CORES-nprocs())) #Add all possible processors\nusing JuliaRunClient\n# initializeCluster(2)\ninitializeCluster(16) # more workers can be added with a larger subscription\n\ntimings=Dict{Int,Tuple{Float64,Float64}}()\nfor np in 2:nprocs()\n gc_enable(false) #Disable garbage collector for timing purposes\n n=1024#4096#3072\n \n #Create RemoteRefs on np processes\n r=[@spawnat p randn(n,n) for p in procs()[1:np]]\n s=fetch(r) #These are in-memory matrices\n\n #Repeat timings a couple of times and take smallest\n t_ser = minimum([(tic(); prefix_serial!(s, *); toc()) for i=1:2])\n t_par = minimum([(tic(); @sync prefix!(r, *) ; toc()) for i=1:2])\n timings[np] = (t_ser, t_par)\n gc_enable(true)\nend\ntimings\n\n#timings = #Data from julia.mit.edu\n#Dict(\n# 1 => ( 15.585, 15.721),\n# 2 => ( 16.325, 15.893),\n# 3 => ( 32.079, 31.678),\n# 4 => ( 46.037, 33.257),\n# 5 => ( 61.947, 51.412),\n# 6 => ( 77.247, 50.769), \n# 7 => ( 92.588, 67.796),\n# 8 => (108.057, 65.185),\n# 9 => (123.556, 68.197),\n# 10 => (138.408, 66.658),\n# 11 => (153.392, 82.580),\n# 12 => (168.874, 83.373),\n# 13 => (184.227, 82.875),\n# 14 => (199.741, 83.098),\n# 15 => (215.881, 101.271),\n# 16 => (230.531, 104.860),\n# 17 => (246.576, 103.229),\n# 18 => (261.412, 102.497),\n# 19 => (276.926, 103.367),\n# 20 => (294.404, 104.162),\n# 21 => (308.995, 104.944),\n# 22 => (323.287, 104.838),\n# 23 => (340.173, 121.495),\n# 24 => (353.717, 119.729),\n# 25 => (369.113, 120.281),\n# 26 => (384.638, 118.710),\n# 27 => (402.484, 119.237),\n# 28 => (417.036, 119.980),\n# 29 => (431.273, 120.463),\n# 30 => (446.288, 120.560),\n# 31 => (461.756, 137.209),\n# 32 => (476.653, 135.873),\n# 33 => (493.989, 138.150),\n# 34 => (508.089, 137.998),\n# 35 => (523.703, 139.059),\n# 36 => (539.305, 135.201),\n# 37 => (554.201, 138.242),\n# 38 => (569.276, 137.470),\n# 39 => (585.268, 137.261),\n# 40 => (599.921, 137.871),\n# 41 => (615.718, 137.887),\n# 42 => (632.463, 137.579),\n# 43 => (647.355, 138.181),\n# 44 => (664.344, 139.917),\n# 45 => (678.899, 138.382),\n# 46 => (695.815, 138.354),\n# 47 => (717.068, 154.826),\n# 48 => (730.902, 155.603),\n# 49 => (745.608, 154.549),\n# 50 => (756.012, 154.244),\n# 51 => (769.611, 154.000),\n# 52 => (793.350, 152.893),\n# 53 => (801.568, 155.276),\n# 54 => (818.174, 153.436),\n# 55 => (832.994, 155.923),\n# 56 => (849.526, 155.721),\n# 57 => (863.337, 155.289),\n# 58 => (881.577, 156.188),\n# 59 => (893.735, 157.889),\n# 60 => (911.597, 155.557),\n# 61 => (925.117, 157.048),\n# 62 => (940.897, 153.338),\n# 63 => (954.825, 173.942),\n# 64 => (990.757, 173.236),\n# 65 => (987.457, 172.005),\n# 66 => (1009.688, 173.869),\n# 67 => (1022.357, 173.303),\n# 68 => (1043.536, 175.044),\n# 69 => (1052.156, 173.361),\n# 70 => (1067.174, 172.230),\n# 71 => (1079.543, 173.491),\n# 72 => (1101.516, 174.311),\n# 73 => (1119.993, 174.057),\n# 74 => (1136.092, 175.804),\n# 75 => (1154.758, 175.075),\n# 76 => (1170.732, 173.453),\n# 77 => (1184.598, 171.936),\n# 78 => (1190.922, 172.809),\n# 79 => (1204.645, 172.878),\n#)\n\nspeedup(p::Integer) = ((p-1)/(floor(Int, log2(p)) + 1 + floor(Int, log2(p/3))))\n#for (np, (t_ser, t_par)) in sort!([x for x in timings])\n# @printf(\"np: %3d Serial: %.3f sec Parallel: %.3f sec speedup: %.3fx (theory=%.3fx)\\n\",\n# np, t_ser, t_par, t_ser/t_par, speedup(np))\n#end\n\nxend = 1+maximum(keys(timings))\n\ntheplot=plot(layer(x=2:xend, y=map(speedup, 2:xend), Geom.line(), Theme(default_color=colorant\"darkkhaki\")),\nlayer(x=[np+1 for (np, (t_ser, t_par)) in timings],\n y=[t_ser/t_par for (np, (t_ser, t_par)) in timings],\n Geom.point, Theme(default_color=colorant\"firebrick\",\n #=default_point_size=1.25pt, =#highlight_width=0pt)),\n Guide.xlabel(\"Number of processors, p\"), Guide.ylabel(\"Speedup, r\"))\n\nlabeledplot = compose(render(theplot),\ncompose(context(), stroke(colorant\"purple\"), #Powers of 2\ntext(0.21, 0.73, \"2\"), text(0.24, 0.72, \"4\"), text(0.27, 0.7, \"8\"), text(0.33, 0.63, \"16\"),\ntext(0.47, 0.53, \"32\"), text(0.76, 0.35, \"64\")),\ncompose(context(), stroke(colorant\"green\"), #3x powers of 2\ntext(0.25, 0.62, \"6\"), text(0.28, 0.57, \"12\"), text(0.39, 0.49, \"24\"), text(0.63, 0.32, \"48\"),\n)\n)\ndraw(SVG(3.5inch, 3.2inch), labeledplot)\n\ndraw(SVG(\"scaling.svg\", 3.5inch, 3.2inch), labeledplot)\n#draw(PDF(\"scaling.pdf\", 3.5inch, 3inch), theplot)\n\n# ------------------------------------------------------------------------------------------\n# The exact same serial code now runs in parallel thanks to multiple dispatch!\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# # Formal verification\n#\n# Julia allows us to implement very easily the interval of summations monoid technique for\n# verifying the correctness of prefix sums\n# ([doi:10.1145/2535838.2535882](http://dx.doi.org/10.1145/2535838.2535882)).\n# ------------------------------------------------------------------------------------------\n\n#Definition 4.3 of Chong et al., 2014\nabstract type ⊤ end\nabstract type Id end\nconst 𝕊 = Union{UnitRange, Type{⊤}, Type{Id}}\n\n⊕(I::UnitRange, J::UnitRange) = I.stop+1==J.start ? (I.start:J.stop) : ⊤\n⊕(::Type{Id}, ::Type{Id}) = Id\n⊕(I::𝕊, ::Type{Id}) = I\n⊕(::Type{Id}, I::𝕊) = I\n⊕(I::𝕊, J::𝕊) = ⊤\n\nfor kernel in (prefix_serial!, prefix!), n=1:1000\n @assert kernel([k:k for k=1:n], ⊕) == [1:k for k=1:n]\nend\n\n# ------------------------------------------------------------------------------------------\n# Wrong kernels produce type errors!\n# ------------------------------------------------------------------------------------------\n\nfunction prefix_wrong!(y, .+)\n l = length(y)\n offset = 1\n z = copy(y)\n while offset < l\n for i=offset+1:l\n z[i] = y[i-offset] .+ z[i]\n end\n offset += 2\n y = copy(z)\n end\n y\nend\n\nprefix_wrong!(Any[k:k for k=1:8], ⊕) #Should produce conversion error\n\n@manipulate for npp=1:10\n render(prefix_wrong!(AccessArray(npp),+))\nend\n\n# ------------------------------------------------------------------------------------------\n# # Experimental code which doesn't work\n#\n# In this section I play with other parallel prefix algorithms. All the ones here suffer\n# from read antidependencies and they break the logic I used to draw the gates.\n# ------------------------------------------------------------------------------------------\n\n#Kogge-Stone variant\n#Works but doesn't render properly\nfunction prefix_ks!(y, .+)\n l = length(y)\n offset = 1\n z = copy(y)\n while offset < l\n for i=offset+1:l\n z[i] = y[i-offset] .+ z[i]\n end\n offset *= 2\n y = copy(z)\n end\n y\nend\n\n@assert prefix_ks!(ones(8), +) == [1:8;]\n\nBase.copy(A::AccessArray) = A\n\nrender(prefix_ks!(AccessArray(8),+))\n\n#Hillis-Steele = Kogge-Stone\nfunction prefix_hs!(y, +)\n l = length(y)\n lk = floor(Int, log2(l))\n for d=1:lk\n for k=2d:l\n y[k] = y[k-2^(d-1)] + y[k]\n end\n end\n y\nend\nprefix_hs!(ones(4), +)\n\nrender(prefix_hs!(AccessArray(4), +))\n\n#Sklansky\nfunction prefix_s!(y, +)\n n = length(y)\n for d=1:log2(n)\n for k=1:n÷2+1\n block = 2 * (k - (mod(k, 2^d)))\n me = block + mod(k, 2^d) + 2^d\n spine = block + 2^d - 1\n if spine ≤ n && me ≤ n\n y[me] = y[me] + y[spine]\n end\n end\n end\n y\nend\nprefix_s!(ones(4), +)\n\nfunction prefix(v,⊕)\n @show v\n k=length(v)\n k≤1 && return v\n v[2:2:k] = @show v[1:2:k-1]⊕v[2:2:k] # Line 1\n v[2:2:k] = @show prefix(v[2:2:k],⊕) # Line 2\n v[3:2:k] = @show v[2:2:k-1]⊕v[3:2:k] # Line 3\n v\nend\n\nprefix(ones(8),+)\n\nfunction ⊕{T<:Range}(v1::Vector{T}, v2::Vector{T})\n for v in (v1, v2), i in 1:length(v)-1\n @assert v[i].stop + 1 == v[i+1].start\n end\n if length(v1)>0 && length(v2)>0\n @assert v1[end].stop + 1 == v2[1].start\n v1[1].start:v2[end].stop\n elseif length(v1)>0 #&& length(v2)==0\n v1[1].start:v1[end].stop\n elseif length(v2)>0 #&& length(v1)==0\n v2[1].start:v2[end].stop\n else #Both are empty\n v1\n end\nend\n\nfor kernel in (prefix,), n=1:100#(prefix_serial!, prefix!, prefix_ks!), n=1:100\n @assert kernel([k:k for k=1:n], ⊕) == [1:k for k=1:n]\nend\n\n\n", "meta": {"hexsha": "296a28d79778beaebb84d76ca58643942ddf042b", "size": 22561, "ext": "jl", "lang": "Julia", "max_stars_repo_path": ".nbexports/introductory-tutorials/intro-to-julia/Reduce and Parallel Prefix - JuliaBox.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/Reduce and Parallel Prefix - JuliaBox.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/Reduce and Parallel Prefix - JuliaBox.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": 32.3223495702, "max_line_length": 108, "alphanum_fraction": 0.4933291964, "num_tokens": 6917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361533336451, "lm_q2_score": 0.8840392771633079, "lm_q1q2_score": 0.8066293974507448}} {"text": "### A Pluto.jl notebook ###\n# v0.15.1\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n quote\n local el = $(esc(element))\n global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n el\n end\nend\n\n# ╔═╡ 7499784c-0ffd-48af-9b0d-d6937bcf9b0a\nbegin\n\tusing DataFrames\n\tusing LaTeXStrings\n\tusing Latexify\n\tusing SymEngine\n\tusing PlutoUI\n\tusing Random\n\tusing Statistics\n\tusing Printf\nend\n\n# ╔═╡ 99f564e2-611e-4138-8003-343077495a17\nmd\"# EDM tutorial\"\n\n# ╔═╡ 3ffe80af-0484-46e6-a4d6-bcfd4f0ca2f7\nmd\"\"\"\nThis page has interactive sliders to adjust some hyperparameters.\nPress the \"Edit or run this notebook\" button to launch this page inside a Binder instance to enable this functionality. This may take some time to launch, and it might be necessary to run (pressing Shift+Enter) the first cell manually.\n\"\"\"\n\n# ╔═╡ 6c40aa11-f636-4af3-bd11-53f4f21e4846\nmd\"### Start with the data\"\n\n# ╔═╡ 2056d35f-b594-4ba6-b5ee-5f7db829194a\nmd\"\"\"\nImagine that we observe a time series $x$.\nIn tabular form, the data looks like:\n\"\"\"\n\n# ╔═╡ a9be623f-ada5-46c4-bdf3-d0a89a9812c9\nbegin\n\tobs = 12\n\tt = [symbols(\"t_$i\") for i in 1:obs]\n\tx = [symbols(\"x_$i\") for i in 1:obs]\n\ty = [symbols(\"y_$i\") for i in 1:obs]\n\tz = [symbols(\"z_$i\") for i in 1:obs]\n\t\n\ttraw = [symbols(raw\"t_{\" * Base.string(i) * raw\"}\") for i in 1:obs]\n\txraw = [symbols(raw\"x_{\" * Base.string(i) * raw\"}\") for i in 1:obs]\n\t#yraw = [symbols(raw\"y_{\" * Base.string(i) * raw\"}\") for i in 1:obs]\n\t#zraw = [symbols(raw\"z_{\" * Base.string(i) * raw\"}\") for i in 1:obs]\n\t\n\t#df = DataFrame(t = latexify.(traw), x = latexify.(xraw), y = latexify.(yraw), z = latexify.(zraw))\n\tdf = DataFrame(t = latexify.(traw), x = latexify.(xraw))\nend\n\n# ╔═╡ 489ec795-acf4-4096-9b80-25a1c29efe77\nmd\"So each one of $x_i$ is an *observation* of the $x$ time series.\"\n\n# ╔═╡ 578cb599-4b44-4501-9798-e9d79e43b82c\nmd\"### Creating a time-delayed embedding\"\n\n# ╔═╡ b9b9315b-32b2-45a8-86af-c96585c88f00\nmd\"\"\"\nTo create a time-delayed embedding based on any of these time series, we first need to choose the size of the embedding $E$.\n\"\"\"\n\n# ╔═╡ 569d0959-af43-4c88-a733-da272897b4bf\nmd\"\"\"\nThe data may be too finely sampled in time.\nSo we select a $\\tau$ which means we only look at every $\\tau$th observation for each time series.\n\"\"\"\n\n# ╔═╡ 92dfa63d-3799-491b-b2a6-512a44a98f09\nmd\"Choose a value for $E$:\"\n\n# ╔═╡ 8630c42d-1357-4d7e-8d26-75aa5afe404a\nbegin \n\t@bind E Slider(2:4; default=3, show_value=true)\nend\n\n# ╔═╡ afd006ee-2600-4a0b-a475-4172d22e4f6f\nmd\"Choose a value for $\\tau$:\"\n\n# ╔═╡ ce054612-97a2-48a0-9a49-4664d708823c\n@bind τ Slider(1:3; default=2, show_value=true)\n\n# ╔═╡ 6f9345ef-a557-4271-a9a7-23cdef85c98b\nmd\"\"\"\nThe time-delayed embedding of the $x$ time series with the given size E = $E and τ = $τ, is the manifold:\n\"\"\"\n\n# ╔═╡ 1b45974c-7a5f-47a7-996d-47d94dbe231c\nbegin\n\tfunction manifold(x, E, tau)\n\t\tMrows = [reshape(x[(i + tau*(E-1)):-tau:(i)], 1, E) for i = 1:(obs-(E-1)*tau)]\n\t\treduce(vcat, Mrows)\n\tend;\n\t\n\tfunction manifold_set(M)\n\t\tmset = raw\"\\{\"\n\t\t\n\t\tmaxPoints = 3\n\t\tnumPoints = min(size(M, 1), maxPoints)\n\t\t\n\t\tfor i = 1:numPoints\n\t\t\tif i > 1\n\t\t\t\tmset *= \", \"\n\t\t\tend\n\t\t\t\n\t\t\tpoint = M[[i],:] \n\t\t\t#point = reshape(point, 1, E)\n\t\t\tmset *= latexify(point, env=:raw)\n\t\t\t\n\t\t\t#pointTimes = (i + tau*(E-1)):-tau:(i)\n\t\t\t\n\t\t\t# mset *= raw\"\\{\"\n\t\t\t# for j = 1:size(pointTimes, 1)\n\t\t\t# \tif j > 1\n\t\t\t# \t\tmset *= \", \"\n\t\t\t# \tend\n\t\t\t# \tmset *= raw\"x_{\" * string(pointTimes[j]) * raw\"}\"\n\t\t\t# end\n\t\t\t# mset *= raw\"\\}\"\t\t\n\t\tend\n\t\t\n\t\tif size(M,1) > numPoints\n\t\t\tmset *= raw\", \\dots \"\n\t\tend\n\t\t\n\t\tmset *= raw\"\\}\"\n\t\t\t\n\t\tmset\n\tend;\n\t\n\tM_x = manifold(x, E, τ);\n\t\n\tM_x_set = manifold_set(M_x);\n\t\n\tL\"M_x := \\text{Manifold}(x, E,\\tau) = %$M_x_set\"\nend\n\n# ╔═╡ 279b6d77-00f8-40d4-b4cb-386b5d29dbdb\nmd\"\"\"\nThe manifold is a collection of these time-delayed *embedding vectors*.\nFor short, we just refer to each vector as a *point* on the manifold.\nWhile the manifold notation above is the most accurate (a set of vectors) we will henceforward use the more convenient matrix notation:\n\"\"\"\n\n# ╔═╡ 152aa84f-71e7-446a-b435-b5daa57fd4b1\nbegin\n\tM_x_str = latexify(M_x)\n\tL\"M_x := \\text{Manifold}(x, E,\\tau) = %$(M_x_str)\"\nend\n\n# ╔═╡ acce14af-220b-478d-a8bc-0e06c5fa17b1\nmd\"Note that the manifold has $E$ columns, and the number of rows depends on the number of observations in the $x$ time series.\"\n\n# ╔═╡ 7e2459b4-70fe-489c-958e-b6476ffaac9f\nmd\"### What does `edm explore x` do?\"\n\n# ╔═╡ 5cd973e8-078e-4d7e-9ddd-1a227e44801c\nmd\"##### First split into library and prediction sets\"\n\n# ╔═╡ 9b69d2ce-7612-4588-9b43-44a1f99c0314\nmd\"\"\"\nFirstly, the manifold $M_x$ is split into two separate parts, called the *library set* denoted $\\mathscr{L}$ and the *prediction set* denoted $\\mathscr{P}$.\nBy default, it takes the points of the $M_x$ and randomly assigns half of them to $\\mathscr{L}$ and the other half to $\\mathscr{P}$.\nIn this case we create a partition of the manifold, though if Stata is given other options then the same point may appear in both sets.\n\"\"\"\n\n# ╔═╡ b5df41e1-5d14-45be-abbf-0611d3c0d0cc\nmd\"Starting with the time-delayed embedding of $x$:\"\n\n# ╔═╡ 82803a56-fd0b-49cc-a7b2-d86ddccb8865\nlatexalign([\"M_x\"], [M_x])\n\n# ╔═╡ c76bfd49-486d-48c9-936e-e19d06669dfe\nbegin\n\trng = MersenneTwister(1234);\n\tunifs = rand(rng, size(M_x, 1));\n\tmed = median(unifs);\n\t\n\tlibraryPoints = findall(unifs .<= med)\n\tpredictionPoints = findall(unifs .> med)\n\t\n\tL = M_x[libraryPoints,:];\n\tP = M_x[predictionPoints,:];\n\t\n\tmd\"Then we may take the points $(Base.string(libraryPoints)) to create the library set, which leaves the remaining $(Base.string(predictionPoints)) points to create the prediction set.\"\nend\n\n# ╔═╡ 7c0c12f9-e348-4af3-a4d7-323bba09c95f\nmd\"In that case, the *library set* is\"\n\n# ╔═╡ 45fa3658-3855-48b4-9eaa-a9a9bac55f9d\nbegin\n\n\tlatexalign([LaTeXString(raw\"\\mathscr{L}\")], [L])\nend\n\n# ╔═╡ a0d44f17-df31-4662-9777-f867fcfa44c7\nmd\"and the *prediction set* is\"\n\n# ╔═╡ 8a934063-6348-48cb-9c30-532b44052fd9\nlatexalign([LaTeXString(raw\"\\mathscr{P}\")], [P])\n\n# ╔═╡ 6219fd69-62b7-4736-8fc2-82b7fd062da2\nmd\"\"\"\nIt will help to introduce a notation to refer to a specific point in these sets based on its row number.\nE.g. in the example above, the first point in the library set takes the value:\n\"\"\"\n\n# ╔═╡ 963a24c4-743a-484e-a50d-8c5605c7f98f\nlatexalign([LaTeXString(raw\"\\mathscr{L}_1\")], [L[[1],:]])\n\n# ╔═╡ d7e2fa8d-7b9b-484d-91f2-a4237babc707\nmd\"\"\"\nMore generally $\\mathscr{L}_{i}$ refers to the $i$th point in $\\mathscr{L}$\nand similarly $\\mathscr{P}_{j}$ refers to the $j$th point in $\\mathscr{P}$.\n\"\"\"\n\n# ╔═╡ 3de1fca8-13ac-4358-bb41-ce947bbce460\n# begin\n# t_all = manifold(t, E, τ)\n# firstTime = t_all[trainingSlices[1],1]\n\t\n# Markdown.parse(raw\"The first observation in this slice was measured at time $\" * Base.string(firstTime) * raw\"$.\")\n# md\"TODO: Alternative notation based on time.\"\n# end;\n\n# ╔═╡ 0fe181b0-c244-4b67-97a0-cf452aa6f277\nmd\"##### Next, look at the future values of each point\"\n\n# ╔═╡ aaa5b419-65ca-41e0-a0fe-34af564c09d3\nmd\"\"\"\nEach point on the manifold refers to a small trajectory of a time series, and for each point we look $p$ observations into the future of the time series.\n\"\"\"\n\n# ╔═╡ faf7fd88-aa9f-4b87-9e44-7a7dbfa14927\nmd\"Choose a value for $p$:\"\n\n# ╔═╡ 2aa0c807-f3ab-426f-bf3b-6ec87c4ad2e9\n@bind p Slider(-2:4; default=1, show_value=true)\n\n# ╔═╡ 20628228-a140-4b56-bc63-5742660822c7\nmd\"We have $p$ = $p.\"\n\n# ╔═╡ 07bbe29b-41ab-4b9b-9c37-7a93f7c7f1fb\nmd\"\"\"\nSo if we take the first point of the prediction set $\\mathscr{P}_{1}$ and say that $y_1^{\\mathscr{P}}$ is the value it takes $p$ observations in the future, we get:\n\"\"\"\n\n# ╔═╡ 7b4b123c-6c91-48e4-9b08-70df7049f304\nbegin\n\tahead = p\n\tx_fut = [symbols(\"x_$(i + τ*(E-1) + ahead)\") for i = 1:(obs-(E-1)*τ)]\n\ty_fut = [symbols(\"y_$(i + τ*(E-1) + ahead)\") for i = 1:(obs-(E-1)*τ)]\n\tz_fut = [symbols(\"z_$(i + τ*(E-1) + ahead)\") for i = 1:(obs-(E-1)*τ)]\n\t\n\tx_fut_train = x_fut[libraryPoints]\n\tx_fut_pred = x_fut[predictionPoints]\n\t\n\tfirst_P_point = latexify(P[[1],:], env=:raw)\n\tfirst_y_P = latexify(x_fut_pred[[1],:], env=:raw)\n\t\n\tL\"\\mathscr{P}_{1} = %$first_P_point \\quad \\underset{\\small \\text{Matches}}{\\Rightarrow} \\quad y_1^{\\mathscr{P}} = %$first_y_P\"\nend\n\n# ╔═╡ e9f56664-6d86-4a9c-b1a5-65d0af9bf1b0\nmd\"\"\"\nThis $p$ may be thought of as the *prediction horizon*, and in `explore` mode is defaults to τ and in `xmap` mode it defaults to 0.\n\"\"\"\n\n# ╔═╡ ad158c77-8a83-4ee0-9df6-bff0852ff896\nmd\"\"\"\nIn the literature, instead of measuring the number of observations $p$ ahead, authors normally use the value $T_p$ to denote the amount of time this corresponds to.\nWhen data is regularly sampled (e.g. $t_i = i$) then there is no difference (e.g. $T_p = p$), however for irregularly sampled data the actual time difference may be different for each prediction.\n\"\"\"\n\n# ╔═╡ e4f62eab-a061-41a1-82a6-cf1cf4860ddf\nmd\"In the training set, this means each point of $\\mathscr{L}$ matches the corresponding value in $y^{\\,\\mathscr{L}}$:\"\n\n# ╔═╡ bf3906d4-729b-4f35-b0a1-b1eff5797602\nbegin\n\tL_str = latexify(L, env=:raw)\n\ty_L_str = latexify(x_fut_train, env=:raw)\n\t\n \tL\"\\mathscr{L} = %$L_str \\quad \\underset{\\small \\text{Matches}}{\\Rightarrow} \\quad y^{\\,\\mathscr{L}} = %$y_L_str\"\nend\n\n# ╔═╡ 0c676a7d-1b7a-432b-8058-320a37188ab3\nmd\"Similarly, for the prediction set:\"\n\n# ╔═╡ 7ac81a86-de83-4fb8-9415-5a8d71d58ca4\nbegin\n\tP_str = latexify(P, env=:raw)\n\ty_P_str = latexify(x_fut_pred, env=:raw) # [1:size(P,1)]\n\tL\"\\mathscr{P} = %$P_str \\quad \\underset{\\small \\text{Matches}}{\\Rightarrow} \\quad y^{\\mathscr{P}} = %$y_P_str\"\nend\n\n# ╔═╡ b26cfd13-0749-4986-97d7-0dffc899757b\nmd\"\"\"\nWe may refer to elements of the $y^{\\mathscr{L}}$ vector as *projections* as they come about by taking the $x$ time series and projecting it into the future by $p$ observations.\n\"\"\"\n\n# ╔═╡ 71fdd13f-19de-46e5-b11f-3e2824275505\nmd\"### What does `edm explore x` predict?\"\n\n# ╔═╡ 7be9628d-4f92-4d4a-a1b1-a77141e77c30\nmd\"\"\"\nWhen running `edm explore x`, we pretend that we don't know the values in $y^{\\mathscr{P}}$ and that we want to predict them given we know $\\mathscr{P}$, $\\mathscr{L}$ and $y^{\\,\\mathscr{L}}$.\n\"\"\"\n\n# ╔═╡ ed5c583a-8cc2-4bdf-9696-fcc58dcb22fb\nmd\"\"\"\nThe first prediction is to try to find the value of $y_1^{\\mathscr{P}}$ given the corresponding point $\\mathscr{P}_1$:\n\"\"\"\n\n# ╔═╡ b0cb6b70-9c50-48d6-8e96-15b591d53221\nL\"\\mathscr{P}_{1} = %$(latexify(P[[1],:], env=:raw)) \\quad \\underset{\\small \\text{Matches}}{\\Rightarrow} \\quad y_1^{\\mathscr{P}} = \\, ???\"\n\n# ╔═╡ 1e4c550e-ae5a-4fbd-867c-88e5b8013397\nmd\"\"\"\nThe terminology we use is that $y_1^{\\mathscr{P}}$ is the *target* and the point $\\mathscr{P}_1$ is the *predictee*.\n\"\"\"\n\n# ╔═╡ 216f4400-2b75-4472-9661-c477d8931d45\nmd\"\"\"\nLooking over all the points in $\\mathscr{L}$, we find the indices of the $k$ points which are the most similar to $\\mathscr{P}_{1}$.\n\nLet's pretend we have $k=2$ and the most similar points are $\\mathscr{L}_{3}$ and $\\mathscr{L}_{5}$.\nWe will choose the notation $\\mathcal{NN}_k(1) = \\{ 3, 5 \\}$ to describe this set of $k$ nearest neighbours of $\\mathscr{P}_{1}$.\n\"\"\"\n\n# ╔═╡ f29669bf-e5e1-4828-a4b0-311f5665a9c3\nmd\"###### Using the simplex algorithm\nThen, if we have chosen the `algorithm` to be the simplex algorithm, we predict that\n\"\n\n# ╔═╡ 535aaf80-9130-4417-81ef-8031da2f7c73\nL\"y_{1}^{\\mathscr{P}} \\approx \\hat{y}_1^{\\mathscr{P}} := w_1 \\times y_{3}^{\\,\\mathscr{L}} + w_2 \\times y_{5}^{\\,\\mathscr{L}}\"\n\n# ╔═╡ 69dee0fe-4266-4444-a0f1-44db01b38dbd\nmd\"\"\"where $w_1$ and $w_2$ are some weights with add up to 1. Basically we are predicting that $y_1^{\\mathscr{P}}$ is a weighted average of the points $\\{ y_j^{\\,\\mathscr{L}} \\}_{j \\in \\mathcal{NN}_k(1)}$.\"\"\"\n\n# ╔═╡ 657baf6f-4e4b-408c-918d-f007211699ea\nmd\"To summarise the whole simplex procedure:\"\n\n# ╔═╡ d790cbae-85ed-46b7-b0c2-75568802f115\nbegin\n\textractStr = raw\"\\underset{\\small \\text{Extracts}}{\\Rightarrow} \"\n\tgetStr = raw\"\\underset{\\small \\text{Get predictee}}{\\Rightarrow} \"\n\tfindInLStr = raw\"\\underset{\\small \\text{Find neighbours in } \\mathscr{L}}{\\Rightarrow} \"\n\tpredictStr = raw\"\\underset{\\small \\text{Make prediction}}{\\Rightarrow} \"\n\t\n\tL\"\n\t\\begin{align}\n\t\\text{For target }y_i^{\\mathscr{P}}\n\t&%$getStr\n\t\\mathscr{P}_{i}\n\t%$findInLStr\n\t\\mathcal{NN}_k(i) \\\\\n\t&\\,\\,\\,\\,%$extractStr\n\t\\{ y_j^{\\,\\mathscr{L}} \\}_{j \\in \\mathcal{NN}_k(i)}\n\t%$predictStr\n\t\\hat{y}_i^{\\mathscr{P}}\n\t\\end{align}\"\nend\n\n# ╔═╡ 28e51576-d9bb-46ff-bf24-4c16736b625c\nmd\"###### Using the S-map algorithm\nIf however we chose `algorithm` to be the S-map algorithm, then we predict\n\"\n\n# ╔═╡ 0b9081dd-5100-4232-a6be-c2d3d8e3f66f\nL\"y_{1}^{\\mathscr{P}} \\approx \\hat{y}_1^{\\mathscr{P}} := \\sum_{j=1}^E w_{1j} \\times \\mathscr{P}_{1j}\"\n\n# ╔═╡ 0a0df400-ca3f-4c5a-82b6-a536671e7d51\nmd\"\"\"\nwhere the $\\{ w_{1j} \\}_{j=1,\\cdots,E}$ weights are calculated by solving a linear system based on the points in $\\{ \\mathscr{L}_j \\}_{j \\in \\mathcal{NN}_k(1)}$ and $\\{ y_j^{\\,\\mathscr{L}} \\}_{j \\in \\mathcal{NN}_k(1)}$.\n\"\"\"\n\n# ╔═╡ bd345675-ab21-4bdf-bbf3-99966a3d46bd\nmd\"Given the specific\"\n\n# ╔═╡ fb293078-489d-4f86-afe2-abf75040af6d\nL\"\\mathscr{P}_1 = %$(latexify(P[[1],:]))\"\n\n# ╔═╡ 2265c861-f5cf-468b-a523-e7352359c17f\nmd\"in this example, the prediction would look like:\"\n\n# ╔═╡ 9c7a4ecb-37bb-448e-8d13-f608725a1f2e\nbegin\n\tweights = [symbols(\"w_{1$i}\") for i in 1:E]\n\tweightedSum = sum(weights.*P[1,:])\n\tL\"y_{1}^{\\mathscr{P}} \\approx \\hat{y}_1^{\\mathscr{P}} := %$weightedSum\"\nend\n\n# ╔═╡ 94660506-0de1-4013-b7bf-79f49e09820b\nmd\"To summarise the whole S-map procedure:\"\n\n# ╔═╡ 5d65f348-3a8e-4185-b9a1-24c5dec2303f\nbegin\n\tweightStr = raw\"\\underset{\\small \\text{Calculate}}{\\Rightarrow}\"\n\t\n\tL\"\n\t\\begin{align}\n\t\\text{For target }y_i^{\\mathscr{P}}\n\t&%$getStr\n\t\\mathscr{P}_{i}\n\t%$findInLStr\n\t\\mathcal{NN}_k(i) \\\\\n\t&\\,\\,\\,\\,%$extractStr\n\t\\{ \\mathscr{L}_j, y_j^{\\,\\mathscr{L}} \\}_{j \\in \\mathcal{NN}_k(i)}\n\t%$weightStr\n\t\\{ w_{ij} \\}_{j=1,\\ldots,E} \n\t%$predictStr\n\t\\hat{y}_i^{\\mathscr{P}}\n\t\\end{align}\"\nend\n\n# ╔═╡ f6e12684-be4a-4fa9-8a2a-3ea6b205fe9a\nmd\"##### Assessing the prediction quality\"\n\n# ╔═╡ ec5e9c90-f7e8-49fa-a7c5-36fc527ebb1d\nmd\"\"\"\nWe calculate the $\\hat{y}_i^{\\mathscr{P}}$ predictions for each target in the prediction set (so $i = 1, \\dots, |\\mathscr{P}|$), and store the predictions in a vector $\\hat{y}^{\\mathscr{P}}$.\n\nAs we have the true value of $y_i^{\\mathscr{P}}$ for each target in the prediction set, we can compare our $\\hat{y}_i^{\\mathscr{P}}$ predictions and assess their quality using their correlation\n\"\"\"\n\n# ╔═╡ 6b7788e1-4dfa-4249-b3ae-9323c144d8a5\nL\" \\rho := \\mathrm{Correlation}(y^{\\mathscr{P}} , \\hat{y}^{\\mathscr{P}}) \"\n\n# ╔═╡ e14e6991-ab3e-4ee3-84df-65474d682f95\nmd\"\"\"\nor using the mean absolute error\n\"\"\"\n\n# ╔═╡ 98e1b0ae-da11-4abc-b82a-39f57d86eafb\nL\"\\text{MAE} := \\frac{1}{| \\mathscr{P} |} \\sum_{i=1}^{| \\mathscr{P} |} | y_i^{\\mathscr{P}} - \\hat{y}_i^{\\mathscr{P}} | .\"\n\n# ╔═╡ 9f05a08a-a2ff-464b-9399-04047823b568\nmd\"### What does `edm xmap u v` do?\"\n\n# ╔═╡ 95058743-a0f0-4e40-998a-959fb3bcf98f\nmd\"\"\"\nImagine that we use the command:\n\n`edm xmap u v, oneway`\n\nThis will consider two different time series, here labelled $u$ and $v$.\nThe lagged embedding $M_u$ is constructed:\n\"\"\"\n\n# ╔═╡ 203af6eb-040f-41c3-abc1-a7a574681825\nbegin\n\tu = [symbols(\"u_$i\") for i in 1:obs]\n\tv = [symbols(\"v_$i\") for i in 1:obs]\n\t\n\tM_u = manifold(u, E, τ);\n\tM_v = manifold(v, E, τ);\n\tL\"u = %$(latexify(u, env=:raw)) \\quad \\Rightarrow \\quad M_u = %$(latexify(M_u))\"\nend\n\n\n# ╔═╡ a8130051-db98-46e6-97bb-f724d7a290d9\nmd\"The library set is a random subset of $L$ points of $M_u$.\nThe library size parameter $L$ is set by the Stata parameter `library`.\"\n\n# ╔═╡ 7138b826-ed29-4f6b-8067-bff029271852\nmd\"Choose a value for $L$:\"\n\n# ╔═╡ 93613b85-ae63-4785-b5aa-caa51dab6b73\n@bind library Slider(3:size(M_u,1); default=3, show_value=true)\n\n# ╔═╡ 99927d27-b407-4cbd-97cb-395b996b65fb\nmd\"The value of $L$ is $library.\"\n\n# ╔═╡ 8165de9a-6db9-49c6-9dae-ffc0970f3615\nbegin\n\tcutoff = sort(unifs)[library]\n\tlibraryPointsXmap = findall(unifs .<= cutoff)\n\t\n\tL_xmap = M_u[libraryPointsXmap,:]\n\tL_xmap_str = latexify(L_xmap, env=:raw)\n\t\n\tL\"\\mathscr{L} = %$L_xmap_str\"\nend\n\n# ╔═╡ b30914fc-3bdd-40af-b586-8f172bdbac70\nmd\"\"\"\nOn the other hand, the prediction set will include every point of the $u$ embedding so:\n\"\"\"\n\n# ╔═╡ fc9450de-6665-4301-a458-a8c4159e3269\nbegin\n\tP_xmap = M_u\n\tL\"\\mathscr{P} = M_u = %$(latexify(P_xmap))\"\nend\n\n# ╔═╡ cc543a65-f38f-412b-a05e-3b7d5cabe573\nmd\"\"\"\nThe $v$ time series will be the values which we try to predict.\nHere we are trying to predict $p$ observations ahead, where the default case is actually $p = 0$.\nThe $p = 0$ case means we are using the $u$ time series to try to predict the contemporaneous value of $v$.\nA negative $p$ may be chosen, though this is a bit abnormal.\n\"\"\"\n\n# ╔═╡ 9cad1bf1-9ad9-4683-b912-84d779827cea\nmd\"Choose a value for $p$:\"\n\n# ╔═╡ 70af044f-4375-4c2b-936b-0acc62a4db4e\n@bind p_xmap Slider(-2:5; default=0, show_value=true)\n\n# ╔═╡ 69816a32-c6c5-4e30-94f1-31727f567b73\nmd\"The value of $p$ is $p_xmap.\"\n\n# ╔═╡ 797b647c-f8e1-4681-b5b2-a8721aad940f\nbegin\n\tahead_xmap = p_xmap\n\t\n\tv_fut = [symbols(\"v_$(i + τ*(E-1) + ahead_xmap)\") for i = 1:(obs-(E-1)*τ)]\n\t\n \tv_fut_train = v_fut[libraryPointsXmap]\n \tv_fut_pred = v_fut\n\t\n \ty_L_str_xmap = latexify(v_fut_train[1:size(L_xmap,1)], env=:raw)\n\ty_P_str_xmap = latexify(v_fut_pred[1:size(P_xmap,1)], env=:raw)\n\t\n\tmatchStr = raw\"\\underset{\\small \\text{Matches}}{\\Rightarrow} \"\n\t\n\tL\"\\mathscr{L} = %$L_xmap_str \\quad %$matchStr \\quad y^{\\,\\mathscr{L}} = %$y_L_str_xmap\"\nend\n\n# ╔═╡ 25720cde-ce24-4ceb-be88-539837b5bf39\nbegin\n\tP_xmap\n\tmatchStr\n\ty_P_str_xmap\nL\"\\mathscr{P} = %$(latexify(P_xmap, env=:raw)) \\quad %$matchStr \\quad y^{\\mathscr{P}} = %$y_P_str_xmap\"\nend\n\n# ╔═╡ 1cff64b5-b3d9-41ce-aac0-c722821dda93\nmd\"\"\"\nThe prediction procedure is then the same as previous times, though the library and prediction sets all contain values from the $u$ time series whereas the $y$ projection vectors contain (usually contemporaneous) values from the $v$ time series.\n\"\"\"\n\n# ╔═╡ 15092345-e81a-4c28-81ae-e79e9d823853\nbegin\n\tkNNStr = raw\"\\underset{\\small \\text{Find neighbours in}}{\\Rightarrow} \"\n\tL\"\n\t\\underbrace{ \\text{For target }y_i^{\\mathscr{P}} }_{\\text{Based on } v}\n\t%$getStr\n\t\\underbrace{ \\mathscr{P}_{i} }_{\\text{Based on } u}\n\t%$kNNStr\n\t\\underbrace{ \\mathscr{L} }_{\\text{Based on } u}\n\t%$matchStr\n\t\\underbrace{ \\{ y_j^{\\,\\mathscr{L}} \\}_{j \\in \\mathcal{NN}_k(i)} }_{\\text{Based on } v}\n\t%$predictStr\n\t\\underbrace{ \\hat{y}_i^{\\mathscr{P}} }_{\\text{Based on } v}\"\nend\n\n# ╔═╡ 6fae5864-ec11-4e94-98a9-ffc0fd421049\nmd\"## Adding more data to the manifold\"\n\n# ╔═╡ 6ea2e5d4-ff50-4efe-b80a-29940e7455f9\nmd\"\"\"\nIt can be advantageous to combine data from multiple sources into a single EDM \nanalysis.\n\nThe `extra` command will incorporate additional pieces of data into the manifold.\nAs an example, the Stata command\n\n`edm explore x, extra(y)`\n\nwill construct a manifold:\n\"\"\"\n\n# ╔═╡ 982d9067-da5b-4cbf-bcba-5c94ed2479b9\nbegin\n\tfunction manifold_with_extra(x, E, tau, extra)\n\t\tMrows = [reshape(x[(i + tau*(E-1)):-tau:(i)], 1, E) for i = 1:(obs-(E-1)*tau)]\n\t\tM_x = reduce(vcat, Mrows)\n\t\t\n\t\textraCol = [extra[(i + tau*(E-1))] for i = 1:(obs-(E-1)*tau)]\n\t\t\n\t\thcat(M_x, extraCol)\n\tend;\n\t\n\tM_x_extra = manifold_with_extra(x, E, τ, y);\n\t\n\t#M_x_extra_set = manifold_set(M_x_extra);\n\t#L\"M_{x,y} := %$M_x_extra_set\"\n\t\n\tL\"M_{x,y} := %$(latexify(M_x_extra))\"\nend\n\n# ╔═╡ 3ddc8e19-b61a-4ad8-9d6c-1c38dbe7308d\nmd\"\"\"\nAfter extra variables are added, the manifold $M_{x,y}$ no longer has $E$ columns.\nIn these cases, we make a distinction between $E$ which selects the number of lags for each time series, and the *actual* $E$ which is size of each point (i.e. the number of columns).\n\"\"\"\n\n# ╔═╡ 12dff36b-59da-45bc-984d-a5063f204bd9\nmd\"\"\"\nBy default just one $y$ observation is added to each point in the manifold. \n\nIf $E$ lags of $y$ are required, then the command should be altered slightly to\n\n`edm explore x, extra(y(e))`\n\nand then the manifold will be:\n\"\"\"\n\n# ╔═╡ 66de25a9-4ed3-42e2-ae9f-427684a8fb1e\nbegin\n\tM_extras = manifold(y, E, τ);\n\tM_x_extras = hcat(M_x, M_extras)\t\n\t#M_x_extras_set = manifold_set(M_x_extras)\n\t#L\"M_{x,y} := %$M_x_extras_set\"\n\tL\"M_{x,y} := %$(latexify(M_x_extras))\" \nend\n\n# ╔═╡ dfdb3ef6-35b6-48f5-ae30-12b41d247c90\nmd\"\"\"\nMore than one `extra` variable can be added.\nIf some extras are lagged extra variables are specified after some unlagged extras, then the package will reorder them so that all the lagged extras are first.\n\"\"\"\n\n# ╔═╡ 1e2bd033-a948-4a60-9b78-13d4d88813f7\nmd\"## What about irregularly sampled observations?\"\n\n# ╔═╡ 0c29af04-ebd1-4d10-bd10-819b7a3a94d9\nmd\"\"\"\nWe don't always have observations of real-world phenomena at regular intervals.\nThe `dt` option is designed to handle the situation when the times between each of the observations are irregular.\n\nFor example, when the command\n\n`edm explore x, dt`\n\nis specified, the manifold will be constructed as if the `extra` option had said to include the time differences.\n\"\"\"\n\n# ╔═╡ 365746a0-2f0c-481f-b8b3-00774d981196\nmd\"Choose a value for $E$:\"\n\n# ╔═╡ e694efa3-d618-4430-ac5b-d1922f5b4c1e\n@bind E_dt Slider(2:3; default=2, show_value=true)\n\n# ╔═╡ 8dcfb9ac-1f74-4cf7-8419-13b5cddcef74\nmd\"Choose a value for $\\tau$:\"\n\n# ╔═╡ 710cf6bf-7eac-478a-9783-4eed31c2360e\n@bind τ_dt Slider(1:4; default=2, show_value=true)\n\n# ╔═╡ f9f0a2fa-613e-48d3-ac8a-bae77a60f22f\nmd\"In this case ($E$ = $E_dt, τ = $τ_dt), the manifold will look like:\"\n\n# ╔═╡ b87518c1-1bae-4496-bae2-6d2bdaa8ad69\nbegin\n\n\tfunction manifold_set_dt(n, E, tau)\n\t\tmset = raw\"\\{\"\n\t\t\n\t\tmaxPoints = 2\n\t\tnumPoints = min(n, maxPoints)\n\t\t\n\t\tfor i = 1:numPoints\n\t\t\tif i > 1\n\t\t\t\tmset *= \", \"\n\t\t\tend\n\t\t\t\n\t\t\tpointTimes = (i + tau*(E-1)):-tau:(i)\n\t\t\tpointTimes\n\t\t\t\n\t\t\tmset *= raw\"[\"\n\t\t\tfor j = 1:length(pointTimes)\n\t\t\t\tif j > 1\n\t\t\t\t\tmset *= raw\"\\,\\,\\,\\,\"\n\t\t\t\tend\n\t\t\t\tmset *= raw\"x_{\" * string(pointTimes[j]) * raw\"}\"\n\t\t\tend\n\t\t\t\n\t\t\tfor j = 1:length(pointTimes)\n\t\t\t\tmset *= raw\"\\,\\,\\,\\,\"\n\t\t\t\tif pointTimes[j]+tau <= obs\n\t\t\t\t\tmset *= raw\"(t_{\" * string(pointTimes[j]+tau) * raw\"}\"\n\t\t\t\t\tmset *= raw\"-t_{\" * string(pointTimes[j]) * raw\"})\"\n\t\t\t\telse\n\t\t\t\t\tmset *= \"?\"\n\t\t\t\tend\n\t\t\tend\n\t\t\t\n\t\t\tmset *= raw\"] \"\t\t\n\t\tend\n\t\t\n\t\tif n > numPoints\n\t\t\tmset *= raw\", \\dots \"\n\t\tend\n\t\t\n\t\tmset *= raw\"\\}\"\n\t\t\t\n\t\tmset\n\tend;\n\t\n\tM_x_dt_set = manifold_set_dt(size(M_x, 1), E_dt, τ_dt)\n\t\n\tL\"M_{x,\\mathrm{d}t} := %$M_x_dt_set\"\nend\n\n# ╔═╡ c1d4a958-9fc0-4eda-aaa6-f28fa88551d6\nmd\"\"\"If we define the notation that \n\n$dt_{i}^{\\tau} = (t_{i+\\tau} - t_i)$\n\nthen the manifold can be written as:\n\"\"\"\n\n# ╔═╡ 66a18830-0455-4c5a-9c96-719940d5e6c7\nbegin\n\tdeltaT = [symbols(raw\"dt_\" * string(i)*raw\"^τ\") for i in 1:(obs)]\n\tM_x_dt = manifold(x, E_dt, τ_dt);\n\tM_dt = manifold(deltaT, E_dt, τ_dt);\n\tM_x_and_dt = hcat(M_x_dt, M_dt)\t\n\tL\"M_{x,\\mathrm{d}t} := %$(latexify(M_x_and_dt))\"\nend\n\n# ╔═╡ 9b15ced5-e4de-43e4-b1e5-9f380a788d34\nmd\"\"\"\nIf the *cumulative dt* option `cumdt` option is set, then the time differences are relative to the time of the prediction. That is\n\"\"\"\n\n# ╔═╡ 65d93d7f-f7f9-4598-9064-de8fbf490337\nbegin\n\n\tfunction manifold_set_cumdt(n, E, tau)\n\t\tmset = raw\"\\{\"\n\t\t\n\t\tmaxPoints = 2\n\t\tnumPoints = min(n, maxPoints)\n\t\t\n\t\tfor i = 1:numPoints\n\t\t\tif i > 1\n\t\t\t\tmset *= \", \"\n\t\t\tend\n\t\t\t\n\t\t\tpointTimes = (i + tau*(E-1)):-tau:(i)\n\t\t\tpointTimes\n\t\t\t\n\t\t\tmset *= raw\"[\"\n\t\t\tfor j = 1:length(pointTimes)\n\t\t\t\tif j > 1\n\t\t\t\t\tmset *= raw\"\\,\\,\\,\\,\"\n\t\t\t\tend\n\t\t\t\tmset *= raw\"x_{\" * string(pointTimes[j]) * raw\"}\"\n\t\t\tend\n\t\t\t\n\t\t\tfor j = 1:length(pointTimes)\n\t\t\t\tmset *= raw\"\\,\\,\\,\\,\"\n\t\t\t\tif pointTimes[j]+tau <= obs\n\t\t\t\t\tmset *= raw\"(t_{\" * string(pointTimes[1]+p) * raw\"}\"\n\t\t\t\t\tmset *= raw\"-t_{\" * string(pointTimes[j]) * raw\"})\"\n\t\t\t\telse\n\t\t\t\t\tmset *= \"?\"\n\t\t\t\tend\n\t\t\tend\n\t\t\t\n\t\t\tmset *= raw\"] \"\t\t\n\t\tend\n\t\t\n\t\tif n > numPoints\n\t\t\tmset *= raw\", \\dots \"\n\t\tend\n\t\t\n\t\tmset *= raw\"\\}\"\n\t\t\t\n\t\tmset\n\tend;\n\t\n\tM_x_cumdt_set = manifold_set_cumdt(size(M_x, 1), E_dt, τ_dt)\n\t\n\tL\"M_{x,\\Delta t} := %$M_x_cumdt_set\"\nend\n\n# ╔═╡ 8c23501b-2bdd-4652-bb4c-8012772b758f\nmd\"\"\"If we define the notation that \n\n$\\overline{\\Delta} t_{ij}^{\\tau p} = (t_{i+p} - t_{i-j\\tau})$\n\nthen the manifold can be written as:\n\"\"\"\n\n# ╔═╡ 95998f9b-0c04-47b6-b75e-d90582f56db8\n# begin\n# \tcumdeltaT = [symbols(raw\" ̄Δ̄t_\" * string(i)*raw\"^τ\") for i in 1:(obs)]\n# \tM_cumdt = manifold(cumdeltaT, E, τ);\n# \tM_x_cumdt = hcat(M_x, M_cumdt)\t\n# \tL\"M_{x,\\mathrm{d}t} := %$(latexify(M_x_cumdt))\"\n# end\nmd\"TODO...\"\n\n# ╔═╡ 6a96e421-b6c8-4f4f-9f13-4c34d5443d1b\nmd\"### What does `copredict` do in explore mode?\"\n\n# ╔═╡ 885b10fe-5585-462b-9109-b293863d67be\nmd\"\"\"\nImagine that we use the command:\n\n`edm explore x, copredictvar(z) copredict(out)`\n\nThis will first do a normal\n\n`edm explore x`\n\noperation, then it will perform a second set of *copredictions*.\nThis brings in a second time series $z$, and specifies that the predictions made in copredict mode should be stored in the Stata variable named `out`.\n\"\"\"\n\n# ╔═╡ 37585472-6078-4020-98f2-89ea31dbd4b9\nmd\"\"\"\nIn coprediction mode, the training set will include the entirety of the $M_x$ manifold and its projections:\n\"\"\"\n\n# ╔═╡ 80712325-3f89-409f-b0d3-d8eca06eae02\nbegin\n\tM_x_str\n\tmatchStr\n\ty_L_copred_str = latexify(x_fut, env=:raw)\nL\"\\mathscr{L} = M_x = %$M_x_str \\quad %$matchStr \\quad y^{\\,\\mathscr{L}} = %$y_L_copred_str\"\nend\n\n# ╔═╡ b53ea6c9-5aaf-41fe-aaf1-4b65214f6acf\nmd\"\"\"\nIn copredict mode the most significant difference is that we change $\\mathscr{P}$ to be the $M_z$ manifold for the $z$ time series and $y^{\\mathscr{P}}$ to:\n\"\"\"\n\n# ╔═╡ e84366f8-611c-4021-bd86-6f46780e1487\nbegin\n\tM_z = manifold(z, E, τ)\n\tP_copred_z = M_z\n\tP_copred_z_str = latexify(P_copred_z, env=:raw)\n\t\n\tmatchStr\n\t\n\ty_P_copred_str = latexify(z_fut, env=:raw)\n\tL\"\\mathscr{P} = M_z = %$P_copred_z_str \\quad %$matchStr \\quad y^{\\mathscr{P}} = %$y_P_copred_str\"\nend\n\n# ╔═╡ 3db5cd4f-6c4e-4c4f-be04-2be39f568959\nmd\"\"\"\nThe rest of the simplex procedure is the same as before:\n\"\"\"\n\n# ╔═╡ fec658e0-d77c-45de-b906-b8b6b4942bad\nL\"\n\\underbrace{ \\text{For target }y_i^{\\mathscr{P}} }_{ \\text{Based on } z }\n%$getStr\n\\underbrace{ \\mathscr{P}_{i} }_{ \\text{Based on } z }\n%$kNNStr\n\\mathscr{L}\n%$matchStr\n\\{ y_j^{\\,\\mathscr{L}} \\}_{j \\in \\mathcal{NN}_k(i)}\n%$predictStr\n\\hat{y}_i^{\\mathscr{P}}\"\n\n# ╔═╡ d4166207-8fdf-484a-a6bb-835a966373a4\nmd\"### What does `copredict` do in xmap mode?\"\n\n# ╔═╡ 4c572fa2-1177-4067-b129-5f4cf0bd302a\nmd\"\"\"\nImagine that we use the command:\n\n`edm xmap u v, oneway copredictvar(w) copredict(out)`\n\nNow we combine three different time series to create the predictions in the `out` Stata variable.\n\"\"\"\n\n# ╔═╡ 2da0ba39-c039-4b80-8f8b-863107ccaf96\nmd\"\"\"\nIn this case, the training set contains all the points in $M_u$:\n\"\"\"\n\n# ╔═╡ 770da5db-c46c-4a1d-a3f3-7df02321da05\nbegin\n\n\tM_u_str = (latexify(P_xmap))\n\n \ty_L_str_xmap_copred = latexify(v_fut, env=:raw)\n\n\tL\"\\mathscr{L} = M_u = %$M_u_str \\quad %$matchStr \\quad y^{\\,\\mathscr{L}} = %$y_L_str_xmap_copred\"\nend\n\n# ╔═╡ d51ef4c6-b5fd-4ea4-84d7-6ce137be89e7\nmd\"\"\"\nThe main change in coprediction is the prediction set and the targets are based on the new $w$ time series:\n\"\"\"\n\n# ╔═╡ dd793d3f-45f2-4eca-bc2e-3eaa67b59e41\nbegin\n\tw = [symbols(\"w_$i\") for i in 1:obs]\n\tM_w = manifold(w, E, τ);\n\tP_xmap_copred = M_w\n\t\n\tmatchStr\n\t\n\tco_ahead = p_xmap\n\tw_fut = [symbols(\"w_$(i + τ*(E-1) + co_ahead)\") for i = 1:(obs-(E-1)*τ)]\n\ty_P_str_xmap_copred = latexify(w_fut, env=:raw)\n\n\n\tL\"\\mathscr{P} = M_w = %$(latexify(P_xmap_copred, env=:raw)) \\quad %$matchStr \\quad y^{\\mathscr{P}} = %$y_P_str_xmap_copred\"\nend\n\n# ╔═╡ 027667be-91db-4e4b-b4f2-07306ea7e4c1\nmd\"\"\"\nFinally, the simplex prediction steps are the same, with:\n\"\"\"\n\n# ╔═╡ 1e00a8f0-94b0-430b-81b0-9846913878f5\nL\"\n\\underbrace{ \\text{For target }y_i^{\\mathscr{P}} }_{\\text{Based on } w}\n%$getStr\n\\underbrace{ \\mathscr{P}_{i} }_{ \\text{Based on } w }\n%$kNNStr\n\\underbrace{ \\mathscr{L} }_{\\text{Based on } u}\n%$matchStr\n\\underbrace{ \\{ y_j^{\\,\\mathscr{L}} \\}_{j \\in \\mathcal{NN}_k(i)} }_{\\text{Based on } v}\n%$predictStr\n\\underbrace{ \\hat{y}_i^{\\mathscr{P}} }_{\\text{Based on } v}\"\n\n# ╔═╡ a29ab0d0-ea70-480f-90f6-5418534b27df\nmd\"\"\"\n### Missing data \n\nTo explain how the package handles missing data given different options, it is easiest to work by example.\n\nLet's say we have the following time series and $(NAN) represents a missing value:\n\"\"\"\n\n# ╔═╡ 12bbff2f-ac5d-4904-ad0c-3fd3efdb1243\nbegin\n\ttMiss = [ 1.0, 2.5, 3.0, 4.5, 5.0, 6.0 ]\n \txMiss = [ 11, 12, NaN, 14, 15, 16 ]\n\tyMiss = [ 12, NaN, 14, 15, 16, NaN ]\n\n\tdfMiss = DataFrame(t = tMiss, x = xMiss)\nend\n\n# ╔═╡ 7b2ff2ef-904c-45ab-9ef6-000118fa2d8a\nmd\"Let's also fix $E = 2$, $\\tau = 1$ and $p = 1$ for these examples.\"\n\n# ╔═╡ a8b14249-19f1-4f21-aa47-e11b3c4e9ce7\nmd\"\"\"\nHere we have one obviously missing value for $x$ at time 3.\nHowever, there are some hidden missing values also.\n\nBy default, the package will assume that your data was measured at a regular time interval and will insert missing values as necessary to create a regular grid.\nFor example, the above time series will be treated as if it were:\n\"\"\"\n\n# ╔═╡ 1f26c940-a41a-48c2-80b4-f90a3c3efa3b\nbegin\n\ttMissFill = [ 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0 ]\n \txMissFill = [ 11, NaN, NaN, 12, NaN, NaN, NaN, 14, 15, NaN, 16 ]\n\tdfMissFill = DataFrame(t = tMissFill, x = xMissFill)\nend\n\n# ╔═╡ f7f37b62-ef27-4e31-97ea-e78e6f839028\nmd\"\"\"\nThe manifold of $x$ and it's projections $y$ will have missing values in them:\n\"\"\"\n\n# ╔═╡ 43c39e42-4f21-4c57-8ac2-7d5d18f1745b\nbegin\t\n\tM_x_miss = [ 11 NaN;\n\t\t\t\t NaN 11;\n\t\t\t\t NaN NaN;\n\t\t\t\t 12 NaN;\n\t\t\t\t NaN 12;\n\t\t\t\t NaN NaN;\n\t\t\t\t NaN NaN;\n\t\t\t\t 14 NaN;\n\t\t\t\t 15 14;\n\t\t\t\t NaN 15;\n\t\t\t\t 16 NaN]\n\t\n\ty_miss = [ NaN; NaN; 12; NaN; NaN; NaN; 14; 15; NaN; 16; NaN]\n\t\n\tL\"M_x = %$(latexify(M_x_miss, env=:raw)) %$matchStr y = %$(latexify(y_miss, env=:raw))\"\nend\n\n# ╔═╡ 50ee9c7d-51e2-4f6c-a2de-c4b543ac83ef\nmd\"\"\"\nWe can see that the original missing value, combined with some slightly irregular sampling, created a reconstructed manifold that is mostly missing values!\n\nBy default, the points which contain missing values *will not be added to the library or prediction sets*.\n\nFor example, if we let the library and prediction sets be as big as possible then we will have:\n\"\"\"\n\n# ╔═╡ 042db7fe-2936-4663-8893-a43142b6ffc1\nbegin\n\tP_valid = vec(.! any(isnan.(M_x_miss), dims=2) )\n\tL_valid = P_valid .& (.! isnan.(y_miss))\n\t\n\t# Override my best wishes and just exclude missing values from prediction set.\n\tP_valid = L_valid\n\t\n\tL_miss = M_x_miss[L_valid,:]\n\ty_L_miss = y_miss[L_valid]\n\t\n\tL\"\\mathscr{L} = %$(latexify(L_miss, env=:raw)) %$matchStr y^{\\mathscr{L}} = %$(latexify(y_L_miss, env=:raw))\"\nend\n\n# ╔═╡ 25eb0830-0ce1-47dc-8856-eda9a91a3473\nbegin\n\tP_miss = M_x_miss[P_valid,:]\n\ty_P_miss = y_miss[P_valid]\n\t\n\tL\"\\mathscr{P} = %$(latexify(P_miss, env=:raw)) %$matchStr y^{\\mathscr{P}} = %$(latexify(y_P_miss, env=:raw))\"\nend\n\n# ╔═╡ 92049e5d-9a54-4b99-93d6-2971b77a99fc\nmd\"\"\"\nHere we see that the resulting sets are totally empty!\n\nThis is because for a point to be in the library or prediction set (with default options) it must be fully observed and the corresponding $y$ projection must also be observed.\n\"\"\"\n\n# ╔═╡ 1134c18a-76c7-4b9c-bff6-f795954f5db4\nmd\"#### The `allowmissing` flag\"\n\n# ╔═╡ cc25480d-aae7-4462-9c45-0c4ba6838a06\nmd\"\"\"\nIf we set the `allowmissing` option, then a point is included in the manifold even with some missing values.\nThe only caveat to this rule is that points which are totally missing will always be discarded.\n\n\nThe largest possible library and prediction sets with `allowmissing` in this example would be:\n\"\"\"\n\n# ╔═╡ 420dae80-0f3b-445a-afa0-6492b4de9579\nbegin\n\tP_am_valid = vec(any(.! isnan.(M_x_miss), dims=2) )\n\t\n\tL_am_valid = P_am_valid .& (.! isnan.(y_miss))\n\t\n\t# Sad face\n\tP_am_valid = L_am_valid\n\t\n\tL_am_miss = M_x_miss[L_am_valid,:]\n\ty_L_am_miss = y_miss[L_am_valid]\n\t\n\tL\"\\mathscr{L} = %$(latexify(L_am_miss, env=:raw)) %$matchStr y^{\\mathscr{L}} = %$(latexify(y_L_am_miss, env=:raw))\"\nend\n\n# ╔═╡ f20109a8-7cdf-46f0-bb8d-36f1e16f6310\nbegin\n\tP_am_miss = M_x_miss[P_am_valid,:]\n\ty_P_am_miss = y_miss[P_am_valid]\n\t\n\tL\"\\mathscr{P} = %$(latexify(P_am_miss, env=:raw)) %$matchStr y^{\\mathscr{P}} = %$(latexify(y_P_am_miss, env=:raw))\"\nend\n\n# ╔═╡ b3296c31-ace4-4f8a-9eb4-9de85e15dd3d\nmd\"\"\"\nThis discussion is implicitly assuming the `algorithm` is set to the simplex algorithm.\nWhen the S-map algorithm is chosen, then we cannot let missing values into the library set $\\mathscr{L}$.\nThis may change in a future implementation of the S-map algorithm.\n\"\"\"\n\n# ╔═╡ 393fa77e-f65d-4a3c-9e88-431e5030486f\nmd\"\"\"\n#### The `dt` flag\n\nWhen we add `dt`, we tell the package to remove missing observations and to also add the time between the observations into the manifold.\n\nSo, in this example, instead of the observed time series being:\n\"\"\"\n\n# ╔═╡ 23fa3b59-8152-4be9-ad70-b815c9517548\ndfMiss\n\n# ╔═╡ 750bbba1-8af9-4760-a3fc-3f7fbf3bd329\nmd\"the `dt` basically acts as if the supplied data were:\"\n\n# ╔═╡ aa10e962-f312-4897-964c-e33e8df9bf6f\nbegin\n\ttMissDT = [ 1.0, 2.5, 4.5, 5.0, 6.0 ]\n\tdtMissDT = [1.5, 2.0, 0.5, 1.0, NaN ]\n \txMissDT = [ 11, 12, 14, 15, 16 ]\n\tyMissDT = [ 12, 14, 15, 16, NaN ]\n\n\tdfMissDT = DataFrame(t = tMissDT, x = xMissDT, dt = dtMissDT)\nend\n\n# ╔═╡ 5a3af8a1-788e-424a-b68c-96c80f817886\nmd\"The resulting manifold and projections are:\"\n\n# ╔═╡ 1d37c724-6f6d-4a7f-a8ad-aaae28bc32d5\nbegin\n\tM_x_miss_dt = [ 11 NaN 1.5 NaN;\n\t\t\t\t 12 11 2.0 1.5;\n\t\t\t\t 14 12 0.5 2.0;\n\t\t\t\t 15 14 1.0 0.5;\n\t\t\t\t 16 15 NaN 1.0]\n\ty_miss_dt = [ 12; 14; 15; 16; NaN]\n\t\n\tL\"M_x = %$(latexify(M_x_miss_dt, env=:raw)) %$matchStr y = %$(latexify(y_miss_dt, env=:raw))\"\nend\n\n# ╔═╡ 568660d0-af25-44a6-be84-0ee58ead31d3\nmd\"The largest possible library and prediction sets with `dt` in this example would be:\"\n\n# ╔═╡ aa289a3f-10be-414e-ac4c-d2e331786d10\nbegin\n\tP_dt_valid = vec(.! any(isnan.(M_x_miss_dt), dims=2) )\n\tL_dt_valid = P_dt_valid .& (.! isnan.(y_miss_dt))\n\t\n\tL_miss_dt = M_x_miss_dt[L_dt_valid,:]\n\ty_L_miss_dt = y_miss_dt[L_dt_valid]\n\t\n\tL\"\\mathscr{L} = %$(latexify(L_miss_dt, env=:raw)) %$matchStr y^{\\mathscr{L}} = %$(latexify(y_L_miss_dt, env=:raw))\"\nend\n\n# ╔═╡ 259abc33-ef51-47d7-8c12-e307eb800b37\nbegin\n\tP_miss_dt = M_x_miss_dt[P_dt_valid,:]\n\ty_P_miss_dt = y_miss_dt[P_dt_valid]\n\t\n\tL\"\\mathscr{P} = %$(latexify(P_miss_dt, env=:raw)) %$matchStr y^{\\mathscr{P}} = %$(latexify(y_P_miss_dt, env=:raw))\"\nend\n\n# ╔═╡ 480e2e49-041b-4ba8-b0db-fa24121a4f06\nmd\"\"\"\n#### Both `allowmissing` and `dt` flags\n\nIf we set both flags, we tell the package to allow missing observations and to also add the time between the observations into the manifold.\n\nSo the time series\n\"\"\"\n\n# ╔═╡ 04a3ad75-f2a2-414a-b745-c680448780e3\ndfMiss\n\n# ╔═╡ a3d9085c-33b5-4361-bc52-fcde45f4a13a\nmd\"will generate the manifold\"\n\n# ╔═╡ 6649d53e-c358-4efd-a95f-393addbe630a\nbegin\n\tM_x_miss_am_dt = [ 11 NaN 1.5 NaN;\n\t\t\t\t 12 11 0.5 1.5;\n\t\t\t\t NaN 12 1.5 0.5;\n\t\t\t\t 14 NaN 0.5 1.5;\n\t\t\t\t 15 14 1.0 0.5;\n\t\t\t\t 16 15 NaN 1.0]\n\ty_miss_am_dt = [ 12; NaN; 14; 15; 16; NaN]\n\t\n\tL\"M_x = %$(latexify(M_x_miss_am_dt, env=:raw)) %$matchStr y = %$(latexify(y_miss_am_dt, env=:raw))\"\nend\n\n# ╔═╡ 9d9b8e70-c59d-43cf-a941-ba2f37c57e2b\nmd\"and the largest possible library and prediction sets would be\"\n\n# ╔═╡ ad2431ae-d3fb-4ce1-bd32-edcee1e22322\nbegin\n\tP_am_dt_valid = vec(any(.! isnan.(M_x_miss_am_dt), dims=2) )\n\tL_am_dt_valid = P_am_dt_valid .& (.! isnan.(y_miss_am_dt))\n\n\t# Sad face\n\tP_am_dt_valid = L_am_dt_valid\n\t\n\tL_miss_am_dt = M_x_miss_am_dt[L_am_dt_valid,:]\n\ty_L_miss_am_dt = y_miss_am_dt[L_am_dt_valid]\n\t\n\tL\"\\mathscr{L} = %$(latexify(L_miss_am_dt, env=:raw)) %$matchStr y^{\\mathscr{L}} = %$(latexify(y_L_miss_am_dt, env=:raw))\"\nend\n\n# ╔═╡ 42e39981-cc8b-4eea-9dea-8d7cabbd23da\nbegin\n\tP_miss_am_dt = M_x_miss_am_dt[P_am_dt_valid,:]\n\ty_P_miss_am_dt = y_miss_am_dt[P_am_dt_valid]\n\t\n\tL\"\\mathscr{P} = %$(latexify(P_miss_am_dt, env=:raw)) %$matchStr y^{\\mathscr{P}} = %$(latexify(y_P_miss_am_dt, env=:raw))\"\nend\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nDataFrames = \"a93c6f00-e57d-5684-b7b6-d8193f3e46c0\"\nLaTeXStrings = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nLatexify = \"23fbe1c1-3f47-55db-b15f-69d7ec21a316\"\nPlutoUI = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nPrintf = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\nRandom = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\nStatistics = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\nSymEngine = \"123dc426-2d89-5057-bbad-38513e3affd8\"\n\n[compat]\nDataFrames = \"~1.2.2\"\nLaTeXStrings = \"~1.2.1\"\nLatexify = \"~0.15.6\"\nPlutoUI = \"~0.7.9\"\nSymEngine = \"~0.8.3\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\n[[ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[ChainRulesCore]]\ndeps = [\"Compat\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"dfbf58e0e470c2fd70020ae2c34e2f17b9fd1e4c\"\nuuid = \"d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4\"\nversion = \"1.2.0\"\n\n[[Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"344f143fa0ec67e47917848795ab19c6a455f32c\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.32.0\"\n\n[[CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[Crayons]]\ngit-tree-sha1 = \"3f71217b538d7aaee0b69ab47d9b7724ca8afa0d\"\nuuid = \"a8cc5b0e-0ffa-5ad4-8c14-923d3ee1735f\"\nversion = \"4.0.4\"\n\n[[DataAPI]]\ngit-tree-sha1 = \"ee400abb2298bd13bfc3df1c412ed228061a2385\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.7.0\"\n\n[[DataFrames]]\ndeps = [\"Compat\", \"DataAPI\", \"Future\", \"InvertedIndices\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"Markdown\", \"Missings\", \"PooledArrays\", \"PrettyTables\", \"Printf\", \"REPL\", \"Reexport\", \"SortingAlgorithms\", \"Statistics\", \"TableTraits\", \"Tables\", \"Unicode\"]\ngit-tree-sha1 = \"d785f42445b63fc86caa08bb9a9351008be9b765\"\nuuid = \"a93c6f00-e57d-5684-b7b6-d8193f3e46c0\"\nversion = \"1.2.2\"\n\n[[DataStructures]]\ndeps = [\"Compat\", \"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"4437b64df1e0adccc3e5d1adbc3ac741095e4677\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.18.9\"\n\n[[DataValueInterfaces]]\ngit-tree-sha1 = \"bfc1187b79289637fa0ef6d4436ebdfe6905cbd6\"\nuuid = \"e2d170a0-9d28-54be-80f0-106bbe20a464\"\nversion = \"1.0.0\"\n\n[[Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[DocStringExtensions]]\ndeps = [\"LibGit2\"]\ngit-tree-sha1 = \"a32185f5428d3986f47c2ab78b1f216d5e6cc96f\"\nuuid = \"ffbed154-4ef7-542d-bbb7-c09d3a79fcae\"\nversion = \"0.8.5\"\n\n[[Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[Formatting]]\ndeps = [\"Printf\"]\ngit-tree-sha1 = \"8339d61043228fdd3eb658d86c926cb282ae72a8\"\nuuid = \"59287772-0a20-5a39-b81b-1366585eb4c0\"\nversion = \"0.4.2\"\n\n[[Future]]\ndeps = [\"Random\"]\nuuid = \"9fa8497b-333b-5362-9e8d-4d0656e87820\"\n\n[[GMP_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"781609d7-10c4-51f6-84f2-b8444358ff6d\"\n\n[[InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[InvertedIndices]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"15732c475062348b0165684ffe28e85ea8396afc\"\nuuid = \"41ab1584-1d38-5bbf-9106-f11c6c58b48f\"\nversion = \"1.0.0\"\n\n[[IteratorInterfaceExtensions]]\ngit-tree-sha1 = \"a3f24677c21f5bbe9d2a714f95dcd58337fb2856\"\nuuid = \"82899510-4779-5014-852e-03e436cf321d\"\nversion = \"1.0.0\"\n\n[[JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"642a199af8b68253517b80bd3bfd17eb4e84df6e\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.3.0\"\n\n[[JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"81690084b6198a2e1da36fcfda16eeca9f9f24e4\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.1\"\n\n[[LaTeXStrings]]\ngit-tree-sha1 = \"c7f1c695e06c01b95a67f0cd1d34994f3e7db104\"\nuuid = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nversion = \"1.2.1\"\n\n[[Latexify]]\ndeps = [\"Formatting\", \"InteractiveUtils\", \"LaTeXStrings\", \"MacroTools\", \"Markdown\", \"Printf\", \"Requires\"]\ngit-tree-sha1 = \"a4b12a1bd2ebade87891ab7e36fdbce582301a92\"\nuuid = \"23fbe1c1-3f47-55db-b15f-69d7ec21a316\"\nversion = \"0.15.6\"\n\n[[LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[LinearAlgebra]]\ndeps = [\"Libdl\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[LogExpFunctions]]\ndeps = [\"DocStringExtensions\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"7bd5f6565d80b6bf753738d2bc40a5dfea072070\"\nuuid = \"2ab3a3ac-af41-5b50-aa03-7779005ae688\"\nversion = \"0.2.5\"\n\n[[Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[MPC_jll]]\ndeps = [\"GMP_jll\", \"Libdl\", \"MPFR_jll\", \"Pkg\"]\ngit-tree-sha1 = \"583d9bc863ad491571369212b9a8047219a0015d\"\nuuid = \"2ce0c516-f11f-5db3-98ad-e0e1048fbd70\"\nversion = \"1.1.0+0\"\n\n[[MPFR_jll]]\ndeps = [\"Artifacts\", \"GMP_jll\", \"Libdl\"]\nuuid = \"3a97d323-0669-5f0c-9066-3539efd106a3\"\n\n[[MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"6a8a2a625ab0dea913aba95c11370589e0239ff0\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.6\"\n\n[[Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[Missings]]\ndeps = [\"DataAPI\"]\ngit-tree-sha1 = \"4ea90bd5d3985ae1f9a908bd4500ae88921c5ce7\"\nuuid = \"e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28\"\nversion = \"1.0.0\"\n\n[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[OpenSpecFun_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"13652491f6856acfd2db29360e1bbcd4565d04f1\"\nuuid = \"efe28fd5-8261-553b-a9e1-b2916fc3738e\"\nversion = \"0.5.5+0\"\n\n[[OrderedCollections]]\ngit-tree-sha1 = \"85f8e6578bf1f9ee0d11e7bb1b1456435479d47c\"\nuuid = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nversion = \"1.4.1\"\n\n[[Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"94bf17e83a0e4b20c8d77f6af8ffe8cc3b386c0a\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"1.1.1\"\n\n[[Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[PlutoUI]]\ndeps = [\"Base64\", \"Dates\", \"InteractiveUtils\", \"JSON\", \"Logging\", \"Markdown\", \"Random\", \"Reexport\", \"Suppressor\"]\ngit-tree-sha1 = \"44e225d5837e2a2345e69a1d1e01ac2443ff9fcb\"\nuuid = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nversion = \"0.7.9\"\n\n[[PooledArrays]]\ndeps = [\"DataAPI\", \"Future\"]\ngit-tree-sha1 = \"cde4ce9d6f33219465b55162811d8de8139c0414\"\nuuid = \"2dfb63ee-cc39-5dd5-95bd-886bf059d720\"\nversion = \"1.2.1\"\n\n[[Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"00cfd92944ca9c760982747e9a1d0d5d86ab1e5a\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.2\"\n\n[[PrettyTables]]\ndeps = [\"Crayons\", \"Formatting\", \"Markdown\", \"Reexport\", \"Tables\"]\ngit-tree-sha1 = \"0d1245a357cc61c8cd61934c07447aa569ff22e6\"\nuuid = \"08abe8d2-0d0c-5749-adfa-8a2ac140af0d\"\nversion = \"1.1.0\"\n\n[[Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[RecipesBase]]\ngit-tree-sha1 = \"b3fb709f3c97bfc6e948be68beeecb55a0b340ae\"\nuuid = \"3cdcf5f2-1ef4-517c-9805-6587b60abb01\"\nversion = \"1.1.1\"\n\n[[Reexport]]\ngit-tree-sha1 = \"5f6c21241f0f655da3952fd60aa18477cf96c220\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.1.0\"\n\n[[Requires]]\ndeps = [\"UUIDs\"]\ngit-tree-sha1 = \"4036a3bd08ac7e968e27c203d45f5fff15020621\"\nuuid = \"ae029012-a4dd-5104-9daa-d747884805df\"\nversion = \"1.1.3\"\n\n[[SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[SortingAlgorithms]]\ndeps = [\"DataStructures\"]\ngit-tree-sha1 = \"b3363d7460f7d098ca0912c69b082f75625d7508\"\nuuid = \"a2af1166-a08f-5f64-846c-94a0d3cef48c\"\nversion = \"1.0.1\"\n\n[[SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[SpecialFunctions]]\ndeps = [\"ChainRulesCore\", \"LogExpFunctions\", \"OpenSpecFun_jll\"]\ngit-tree-sha1 = \"508822dca004bf62e210609148511ad03ce8f1d8\"\nuuid = \"276daf66-3868-5448-9aa4-cd146d93841b\"\nversion = \"1.6.0\"\n\n[[Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[Suppressor]]\ngit-tree-sha1 = \"a819d77f31f83e5792a76081eee1ea6342ab8787\"\nuuid = \"fd094767-a336-5f1f-9728-57cf17d0bbfb\"\nversion = \"0.2.0\"\n\n[[SymEngine]]\ndeps = [\"Compat\", \"Libdl\", \"LinearAlgebra\", \"RecipesBase\", \"SpecialFunctions\", \"SymEngine_jll\"]\ngit-tree-sha1 = \"a27a507f5092a77b0619721c6f852a5f634fc52f\"\nuuid = \"123dc426-2d89-5057-bbad-38513e3affd8\"\nversion = \"0.8.3\"\n\n[[SymEngine_jll]]\ndeps = [\"GMP_jll\", \"Libdl\", \"MPC_jll\", \"MPFR_jll\", \"Pkg\"]\ngit-tree-sha1 = \"4dacada8e05ac49eb768219f8d02bc6b608627fb\"\nuuid = \"3428059b-622b-5399-b16f-d347a77089a4\"\nversion = \"0.6.0+1\"\n\n[[TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[TableTraits]]\ndeps = [\"IteratorInterfaceExtensions\"]\ngit-tree-sha1 = \"c06b2f539df1c6efa794486abfb6ed2022561a39\"\nuuid = \"3783bdb8-4a98-5b6b-af9a-565f29a5fe9c\"\nversion = \"1.0.1\"\n\n[[Tables]]\ndeps = [\"DataAPI\", \"DataValueInterfaces\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"TableTraits\", \"Test\"]\ngit-tree-sha1 = \"d0c690d37c73aeb5ca063056283fde5585a41710\"\nuuid = \"bd369af6-aec1-5ad0-b16a-f7cc5008161c\"\nversion = \"1.5.0\"\n\n[[Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─7499784c-0ffd-48af-9b0d-d6937bcf9b0a\n# ╟─99f564e2-611e-4138-8003-343077495a17\n# ╟─3ffe80af-0484-46e6-a4d6-bcfd4f0ca2f7\n# ╟─6c40aa11-f636-4af3-bd11-53f4f21e4846\n# ╟─2056d35f-b594-4ba6-b5ee-5f7db829194a\n# ╟─a9be623f-ada5-46c4-bdf3-d0a89a9812c9\n# ╟─489ec795-acf4-4096-9b80-25a1c29efe77\n# ╟─578cb599-4b44-4501-9798-e9d79e43b82c\n# ╟─b9b9315b-32b2-45a8-86af-c96585c88f00\n# ╟─569d0959-af43-4c88-a733-da272897b4bf\n# ╟─92dfa63d-3799-491b-b2a6-512a44a98f09\n# ╟─8630c42d-1357-4d7e-8d26-75aa5afe404a\n# ╟─afd006ee-2600-4a0b-a475-4172d22e4f6f\n# ╟─ce054612-97a2-48a0-9a49-4664d708823c\n# ╟─6f9345ef-a557-4271-a9a7-23cdef85c98b\n# ╟─1b45974c-7a5f-47a7-996d-47d94dbe231c\n# ╟─279b6d77-00f8-40d4-b4cb-386b5d29dbdb\n# ╟─152aa84f-71e7-446a-b435-b5daa57fd4b1\n# ╟─acce14af-220b-478d-a8bc-0e06c5fa17b1\n# ╟─7e2459b4-70fe-489c-958e-b6476ffaac9f\n# ╟─5cd973e8-078e-4d7e-9ddd-1a227e44801c\n# ╟─9b69d2ce-7612-4588-9b43-44a1f99c0314\n# ╟─b5df41e1-5d14-45be-abbf-0611d3c0d0cc\n# ╟─82803a56-fd0b-49cc-a7b2-d86ddccb8865\n# ╟─c76bfd49-486d-48c9-936e-e19d06669dfe\n# ╟─7c0c12f9-e348-4af3-a4d7-323bba09c95f\n# ╟─45fa3658-3855-48b4-9eaa-a9a9bac55f9d\n# ╟─a0d44f17-df31-4662-9777-f867fcfa44c7\n# ╟─8a934063-6348-48cb-9c30-532b44052fd9\n# ╟─6219fd69-62b7-4736-8fc2-82b7fd062da2\n# ╟─963a24c4-743a-484e-a50d-8c5605c7f98f\n# ╟─d7e2fa8d-7b9b-484d-91f2-a4237babc707\n# ╟─3de1fca8-13ac-4358-bb41-ce947bbce460\n# ╟─0fe181b0-c244-4b67-97a0-cf452aa6f277\n# ╟─aaa5b419-65ca-41e0-a0fe-34af564c09d3\n# ╟─faf7fd88-aa9f-4b87-9e44-7a7dbfa14927\n# ╟─2aa0c807-f3ab-426f-bf3b-6ec87c4ad2e9\n# ╟─20628228-a140-4b56-bc63-5742660822c7\n# ╟─07bbe29b-41ab-4b9b-9c37-7a93f7c7f1fb\n# ╟─7b4b123c-6c91-48e4-9b08-70df7049f304\n# ╟─e9f56664-6d86-4a9c-b1a5-65d0af9bf1b0\n# ╟─ad158c77-8a83-4ee0-9df6-bff0852ff896\n# ╟─e4f62eab-a061-41a1-82a6-cf1cf4860ddf\n# ╟─bf3906d4-729b-4f35-b0a1-b1eff5797602\n# ╟─0c676a7d-1b7a-432b-8058-320a37188ab3\n# ╟─7ac81a86-de83-4fb8-9415-5a8d71d58ca4\n# ╟─b26cfd13-0749-4986-97d7-0dffc899757b\n# ╟─71fdd13f-19de-46e5-b11f-3e2824275505\n# ╟─7be9628d-4f92-4d4a-a1b1-a77141e77c30\n# ╟─ed5c583a-8cc2-4bdf-9696-fcc58dcb22fb\n# ╟─b0cb6b70-9c50-48d6-8e96-15b591d53221\n# ╟─1e4c550e-ae5a-4fbd-867c-88e5b8013397\n# ╟─216f4400-2b75-4472-9661-c477d8931d45\n# ╟─f29669bf-e5e1-4828-a4b0-311f5665a9c3\n# ╟─535aaf80-9130-4417-81ef-8031da2f7c73\n# ╟─69dee0fe-4266-4444-a0f1-44db01b38dbd\n# ╟─657baf6f-4e4b-408c-918d-f007211699ea\n# ╟─d790cbae-85ed-46b7-b0c2-75568802f115\n# ╟─28e51576-d9bb-46ff-bf24-4c16736b625c\n# ╟─0b9081dd-5100-4232-a6be-c2d3d8e3f66f\n# ╟─0a0df400-ca3f-4c5a-82b6-a536671e7d51\n# ╟─bd345675-ab21-4bdf-bbf3-99966a3d46bd\n# ╟─fb293078-489d-4f86-afe2-abf75040af6d\n# ╟─2265c861-f5cf-468b-a523-e7352359c17f\n# ╟─9c7a4ecb-37bb-448e-8d13-f608725a1f2e\n# ╟─94660506-0de1-4013-b7bf-79f49e09820b\n# ╟─5d65f348-3a8e-4185-b9a1-24c5dec2303f\n# ╟─f6e12684-be4a-4fa9-8a2a-3ea6b205fe9a\n# ╟─ec5e9c90-f7e8-49fa-a7c5-36fc527ebb1d\n# ╟─6b7788e1-4dfa-4249-b3ae-9323c144d8a5\n# ╟─e14e6991-ab3e-4ee3-84df-65474d682f95\n# ╟─98e1b0ae-da11-4abc-b82a-39f57d86eafb\n# ╟─9f05a08a-a2ff-464b-9399-04047823b568\n# ╟─95058743-a0f0-4e40-998a-959fb3bcf98f\n# ╟─203af6eb-040f-41c3-abc1-a7a574681825\n# ╟─a8130051-db98-46e6-97bb-f724d7a290d9\n# ╟─7138b826-ed29-4f6b-8067-bff029271852\n# ╟─93613b85-ae63-4785-b5aa-caa51dab6b73\n# ╟─99927d27-b407-4cbd-97cb-395b996b65fb\n# ╟─8165de9a-6db9-49c6-9dae-ffc0970f3615\n# ╟─b30914fc-3bdd-40af-b586-8f172bdbac70\n# ╟─fc9450de-6665-4301-a458-a8c4159e3269\n# ╟─cc543a65-f38f-412b-a05e-3b7d5cabe573\n# ╟─9cad1bf1-9ad9-4683-b912-84d779827cea\n# ╟─70af044f-4375-4c2b-936b-0acc62a4db4e\n# ╟─69816a32-c6c5-4e30-94f1-31727f567b73\n# ╟─797b647c-f8e1-4681-b5b2-a8721aad940f\n# ╟─25720cde-ce24-4ceb-be88-539837b5bf39\n# ╟─1cff64b5-b3d9-41ce-aac0-c722821dda93\n# ╟─15092345-e81a-4c28-81ae-e79e9d823853\n# ╟─6fae5864-ec11-4e94-98a9-ffc0fd421049\n# ╟─6ea2e5d4-ff50-4efe-b80a-29940e7455f9\n# ╟─982d9067-da5b-4cbf-bcba-5c94ed2479b9\n# ╟─3ddc8e19-b61a-4ad8-9d6c-1c38dbe7308d\n# ╟─12dff36b-59da-45bc-984d-a5063f204bd9\n# ╟─66de25a9-4ed3-42e2-ae9f-427684a8fb1e\n# ╟─dfdb3ef6-35b6-48f5-ae30-12b41d247c90\n# ╟─1e2bd033-a948-4a60-9b78-13d4d88813f7\n# ╟─0c29af04-ebd1-4d10-bd10-819b7a3a94d9\n# ╟─365746a0-2f0c-481f-b8b3-00774d981196\n# ╟─e694efa3-d618-4430-ac5b-d1922f5b4c1e\n# ╟─8dcfb9ac-1f74-4cf7-8419-13b5cddcef74\n# ╟─710cf6bf-7eac-478a-9783-4eed31c2360e\n# ╟─f9f0a2fa-613e-48d3-ac8a-bae77a60f22f\n# ╟─b87518c1-1bae-4496-bae2-6d2bdaa8ad69\n# ╟─c1d4a958-9fc0-4eda-aaa6-f28fa88551d6\n# ╟─66a18830-0455-4c5a-9c96-719940d5e6c7\n# ╟─9b15ced5-e4de-43e4-b1e5-9f380a788d34\n# ╟─65d93d7f-f7f9-4598-9064-de8fbf490337\n# ╟─8c23501b-2bdd-4652-bb4c-8012772b758f\n# ╟─95998f9b-0c04-47b6-b75e-d90582f56db8\n# ╟─6a96e421-b6c8-4f4f-9f13-4c34d5443d1b\n# ╟─885b10fe-5585-462b-9109-b293863d67be\n# ╟─37585472-6078-4020-98f2-89ea31dbd4b9\n# ╟─80712325-3f89-409f-b0d3-d8eca06eae02\n# ╟─b53ea6c9-5aaf-41fe-aaf1-4b65214f6acf\n# ╟─e84366f8-611c-4021-bd86-6f46780e1487\n# ╟─3db5cd4f-6c4e-4c4f-be04-2be39f568959\n# ╟─fec658e0-d77c-45de-b906-b8b6b4942bad\n# ╟─d4166207-8fdf-484a-a6bb-835a966373a4\n# ╟─4c572fa2-1177-4067-b129-5f4cf0bd302a\n# ╟─2da0ba39-c039-4b80-8f8b-863107ccaf96\n# ╟─770da5db-c46c-4a1d-a3f3-7df02321da05\n# ╟─d51ef4c6-b5fd-4ea4-84d7-6ce137be89e7\n# ╟─dd793d3f-45f2-4eca-bc2e-3eaa67b59e41\n# ╟─027667be-91db-4e4b-b4f2-07306ea7e4c1\n# ╟─1e00a8f0-94b0-430b-81b0-9846913878f5\n# ╟─a29ab0d0-ea70-480f-90f6-5418534b27df\n# ╟─12bbff2f-ac5d-4904-ad0c-3fd3efdb1243\n# ╟─7b2ff2ef-904c-45ab-9ef6-000118fa2d8a\n# ╟─a8b14249-19f1-4f21-aa47-e11b3c4e9ce7\n# ╟─1f26c940-a41a-48c2-80b4-f90a3c3efa3b\n# ╟─f7f37b62-ef27-4e31-97ea-e78e6f839028\n# ╟─43c39e42-4f21-4c57-8ac2-7d5d18f1745b\n# ╟─50ee9c7d-51e2-4f6c-a2de-c4b543ac83ef\n# ╟─042db7fe-2936-4663-8893-a43142b6ffc1\n# ╟─25eb0830-0ce1-47dc-8856-eda9a91a3473\n# ╟─92049e5d-9a54-4b99-93d6-2971b77a99fc\n# ╟─1134c18a-76c7-4b9c-bff6-f795954f5db4\n# ╟─cc25480d-aae7-4462-9c45-0c4ba6838a06\n# ╟─420dae80-0f3b-445a-afa0-6492b4de9579\n# ╟─f20109a8-7cdf-46f0-bb8d-36f1e16f6310\n# ╟─b3296c31-ace4-4f8a-9eb4-9de85e15dd3d\n# ╟─393fa77e-f65d-4a3c-9e88-431e5030486f\n# ╟─23fa3b59-8152-4be9-ad70-b815c9517548\n# ╟─750bbba1-8af9-4760-a3fc-3f7fbf3bd329\n# ╟─aa10e962-f312-4897-964c-e33e8df9bf6f\n# ╟─5a3af8a1-788e-424a-b68c-96c80f817886\n# ╟─1d37c724-6f6d-4a7f-a8ad-aaae28bc32d5\n# ╟─568660d0-af25-44a6-be84-0ee58ead31d3\n# ╟─aa289a3f-10be-414e-ac4c-d2e331786d10\n# ╟─259abc33-ef51-47d7-8c12-e307eb800b37\n# ╟─480e2e49-041b-4ba8-b0db-fa24121a4f06\n# ╟─04a3ad75-f2a2-414a-b745-c680448780e3\n# ╟─a3d9085c-33b5-4361-bc52-fcde45f4a13a\n# ╟─6649d53e-c358-4efd-a95f-393addbe630a\n# ╟─9d9b8e70-c59d-43cf-a941-ba2f37c57e2b\n# ╟─ad2431ae-d3fb-4ce1-bd32-edcee1e22322\n# ╟─42e39981-cc8b-4eea-9dea-8d7cabbd23da\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "44d7ff3b53e012acc8fb62dcee81a7cbd1a78df9", "size": 53898, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/tutorial.jl", "max_stars_repo_name": "9prady9/EDM", "max_stars_repo_head_hexsha": "db89a7fecf5a0f30b9db2b913a4d82f3c4ced33c", "max_stars_repo_licenses": ["MIT"], "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/tutorial.jl", "max_issues_repo_name": "9prady9/EDM", "max_issues_repo_head_hexsha": "db89a7fecf5a0f30b9db2b913a4d82f3c4ced33c", "max_issues_repo_licenses": ["MIT"], "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/tutorial.jl", "max_forks_repo_name": "9prady9/EDM", "max_forks_repo_head_hexsha": "db89a7fecf5a0f30b9db2b913a4d82f3c4ced33c", "max_forks_repo_licenses": ["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.8694158076, "max_line_length": 280, "alphanum_fraction": 0.7009907603, "num_tokens": 24118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171237, "lm_q2_score": 0.8688267796346599, "lm_q1q2_score": 0.8066264318130771}} {"text": "using CatmullRom, Plots\n\nb = 1/2;\na = 2*b;\nfx(t) = a * cospi(t)^2;\nfy(t) = (a^2/b) * cospi(t)^3 * sinpi(t);\n\nn_points = 7;\nn_between = 17; # interpolants between each adjacent pair of points\n\nxs = [fx(t) for t=range( 0.0, stop=1.0, length=n_points)];\nys = [fy(t) for t=range( 0.0, stop=1.0, length=n_points)];\npoints = collect(zip(xs, ys))\nclose_seq!(points)\n\ncrpoints = catmullrom(points, n_between);\ncxs, cys = crpoints\n\nplot(xs, ys, linecolor=:lightgreen, linewidth=3, size=(600,600), legend=nothing, xaxis=nothing, yaxis=nothing)\nplot!(cxs, cys, linecolor=:black, linewidth=2, size=(600,600), legend=nothing, xaxis=nothing, yaxis=nothing)\n\n\n```\n\nHere we use the same parameters on an open section of the Piriform curve.\n\n```julia\n\nn_points = 9;\nn_between = 24; # interpolants between each adjacent pair of points\n\nxs = [fx(t) for t=range( -0.25, stop=0.25, length=n_points)];\nys = [fy(t) for t=range( -0.25, stop=0.25, length=n_points)];\npoints = collect(zip(xs,ys))\n\nplot(points, linecolor=:blue, size=(600,600), legend=nothing, xaxis=nothing, yaxis=nothing)\n# overlay in fitted curve\ncxs, cys = catmullrom(points, n_between);\nplot!(cxs, cys, linecolor=:black, size=(600,600), legend=nothing, xaxis=nothing, yaxis=nothing)\n```\n", "meta": {"hexsha": "858e8c5f811f98e795b4d5824f846ac6a192a4a7", "size": 1238, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/piriform.jl", "max_stars_repo_name": "JeffreySarnoff/-CentripetalCatmullRom.jl", "max_stars_repo_head_hexsha": "49e6536c184dfc4200b980f89aa55bc5cf357b82", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-07-14T17:13:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-12T20:43:13.000Z", "max_issues_repo_path": "examples/piriform.jl", "max_issues_repo_name": "JeffreySarnoff/-CentripetalCatmullRom.jl", "max_issues_repo_head_hexsha": "49e6536c184dfc4200b980f89aa55bc5cf357b82", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2018-08-09T20:29:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-08T14:45:14.000Z", "max_forks_repo_path": "examples/piriform.jl", "max_forks_repo_name": "JeffreySarnoff/-CentripetalCatmullRom.jl", "max_forks_repo_head_hexsha": "49e6536c184dfc4200b980f89aa55bc5cf357b82", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:26:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-25T12:17:47.000Z", "avg_line_length": 30.1951219512, "max_line_length": 111, "alphanum_fraction": 0.6890145396, "num_tokens": 429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.8688267660487572, "lm_q1q2_score": 0.806626415757795}} {"text": "function acqr_kfilter_s(y,a,c,q,r,x10)\r\n\t#\r\n\t# STATIONARY Kalman filter for model\r\n\t#\r\n\t# x_{t+1} = a*x_{t} + w_{t}\r\n\t# y_{t} = c*x_{t} + v_{t}\r\n\t#\r\n\t# cov(w_{t},v_{t}) = [q 0;0 r]\r\n\t#\r\n\t# javier.cara@upm.es, 2020-05\r\n\t#\r\n\r\n\tnt = length(y)\r\n\r\n\t# allocation\r\n\txtt = zeros(nt)\r\n\txtt1 = zeros(nt+1)\r\n\tet = zeros(nt)\r\n\tloglik = 0.0\r\n\r\n\t# Stationary solution for Ptt1\r\n\t# p = a^2p - (acp)^2/(c^2p+r) + q\r\n\tA = c^2\r\n\tB = r - a^2*r - c^2*q\r\n\tC = -q*r\r\n\tPtt1 = (-B + sqrt(B^2 - 4*A*C))/(2*A)\r\n\r\n\t# variance of innovations\r\n\tSt = c^2*Ptt1 + r\r\n\r\n\t# Kalman gain matrix\r\n\tKt = Ptt1*c/St\r\n\r\n\t# Var[x_t|y_t]\r\n\tPtt = (1 - Kt*c)*Ptt1\r\n\r\n\t# Filter\r\n\txtt1[1] = x10\r\n\tfor t in 1:nt\r\n\t\t# innovations\r\n\t\tet[t] = y[t] - c*xtt1[t]\r\n\r\n\t\t# filtered values\r\n\t\txtt[t] = xtt1[t] + Kt*et[t]\r\n\r\n\t\t# one-step ahead prediction\r\n\t\txtt1[t+1] = a*xtt[t]\r\n\r\n\t\t# likelihood\r\n\t\t#l0 = et[t]^2/St[t] # typeof(l0) = Array{Float64,1}\r\n\t\tloglik = loglik + et[t]^2/St\r\n\tend\r\n\r\n\tloglik = - nt/2*log(2*pi) - nt/2*log(St) - 0.5*loglik\r\n\r\n\treturn xtt,Ptt,xtt1,Ptt1,et,St,Kt,loglik\r\n\r\nend\r\n", "meta": {"hexsha": "86cd651953e71e2e9da86a9a7d69b73d4f96881c", "size": 1048, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/acqr/acqr_kfilter_s.jl", "max_stars_repo_name": "javiercara/StateSpaceModelsEM.jl", "max_stars_repo_head_hexsha": "989d538b01274885e4579df130f9b38bbb99cc7d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/acqr/acqr_kfilter_s.jl", "max_issues_repo_name": "javiercara/StateSpaceModelsEM.jl", "max_issues_repo_head_hexsha": "989d538b01274885e4579df130f9b38bbb99cc7d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/acqr/acqr_kfilter_s.jl", "max_forks_repo_name": "javiercara/StateSpaceModelsEM.jl", "max_forks_repo_head_hexsha": "989d538b01274885e4579df130f9b38bbb99cc7d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.7627118644, "max_line_length": 56, "alphanum_fraction": 0.5238549618, "num_tokens": 485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422186079557, "lm_q2_score": 0.8479677622198946, "lm_q1q2_score": 0.8065379386658539}} {"text": "function per_modstokes(F1, F2, L, lambda, xnu=[], ynu=[]; zerok0::Bool=false, ifgrad::Bool=false)\n # Check input\n M = size(F1)\n @assert length(M)>1 && M[1]==M[2] \"Grid must be square\"\n @assert size(F1)==size(F2)\n N = M[1]\n # Do FFTs in-place\n Fhat1, Fhat2 = fft(F1), fft(F2)\n # Convolve with truncated greens function \n Uhat1, Uhat2 = Fhat1, Fhat2 # Operate in-place\n k1, k2 = k_vectors([N, N], [L, L])\n k1 = ifftshift(k1)\n k2 = ifftshift(k2)\n # Store k==0 values\n Fhat1k0 = Fhat1[1,1]\n Fhat2k0 = Fhat2[1,1]\n for j=1:N\n for i=1:N\n K1 = k1[i]\n K2 = k2[j]\n Ksq = K1*K1 + K2*K2\n G = 1/ (Ksq*(Ksq + lambda^2))\n KdotFhat = K1*Fhat1[i,j] + K2*Fhat2[i,j] \n Uhat1[i,j] = G*(Ksq*Fhat1[i,j] - K1*KdotFhat)\n Uhat2[i,j] = G*(Ksq*Fhat2[i,j] - K2*KdotFhat) \n end\n end\n # Correct at k==0 (where just just got div by zero)\n Uhat1[1,1] = Fhat1k0 / lambda^2 \n Uhat2[1,1] = Fhat2k0 / lambda^2 \n\n if zerok0\n # This improves conditioning, but gets answer wrong by a constant\n # (which we can let integral equation solver pick up)\n # NOTE: It's possible that this is true only because we are using an\n # ill-conditioned test case\n info(\"Zeroing k=0 mode\") \n Uhat1[1,1], Uhat2[1,1] = 0.0, 0.0\n end\n \n Nnu = length(xnu) \n if Nnu > 0\n # NUFFT for off-grid points\n @assert length(xnu)==length(ynu)\n scale = 2*pi/L\n # Rescale and shift points from [-L/2,L/2] to [0,2*pi] \n xnu *= scale\n ynu *= scale\n xnu += pi\n ynu += pi\n # Compute \n unu1 = Array{Complex128}(Nnu)\n unu2 = Array{Complex128}(Nnu)\n opts = finufft_default_opts()\n opts.modeord = 1\n nufft2d2!(xnu, ynu, unu1, 1, 1e-15, Uhat1, opts)\n nufft2d2!(xnu, ynu, unu2, 1, 1e-15, Uhat2, opts)\n # Get real parts and rescale values\n unu1 = real(unu1)/N^2\n unu2 = real(unu2)/N^2\n else\n unu1, unu2 = [], []\n end\n\n # Gradient\n if ifgrad\n U1x = zero(Uhat1)\n U1y = zero(Uhat1)\n U2x = zero(Uhat2)\n U2y = zero(Uhat2)\n for j=1:N\n for i=1:N\n U1x[i,j] = 1im*k1[i]*Uhat1[i,j]\n U1y[i,j] = 1im*k2[j]*Uhat1[i,j]\n U2x[i,j] = 1im*k1[i]*Uhat2[i,j]\n U2y[i,j] = 1im*k2[j]*Uhat2[i,j] \n end\n end\n ifft!(U1x)\n ifft!(U1y) \n ifft!(U2x)\n ifft!(U2y)\n U1x, U1y, U2x, U2y = real(U1x), real(U1y), real(U2x), real(U2y)\n else\n U1x, U1y, U2x, U2y = [], [], [], []\n end\n \n # Transform back in-place\n ifft!(Uhat1)\n ifft!(Uhat2)\n # Return real parts\n U1 = real(Uhat1)\n U2 = real(Uhat2)\n return U1, U2, unu1, unu2, U1x, U1y, U2x, U2y\nend\n\n# Compute gradient of real periodic function using Fourier transform\nfunction per_gradient(F, L)\n # Check input\n M = size(F)\n @assert length(M)>1 && M[1]==M[2] \"Grid must be square\"\n N = M[1]\n Fhat = fft(F) \n k1, k2 = k_vectors([N, N], [L, L])\n k1 = ifftshift(k1)\n k2 = ifftshift(k2)\n Fx = zeros(Fhat)\n Fy = zeros(Fhat)\n for j=1:N\n for i=1:N\n K1 = k1[i]\n K2 = k2[j]\n Fx[i,j] = 1im*K1*Fhat[i,j]\n Fy[i,j] = 1im*K2*Fhat[i,j] \n end\n end\n # Transform back in-place\n ifft!(Fx)\n ifft!(Fy)\n # Return real parts\n return real(Fx), real(Fy)\nend\n", "meta": {"hexsha": "a26e5621f0d0146707f835481f8ee891cfe61a4d", "size": 3611, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/src/periodic.jl", "max_stars_repo_name": "askhamwhat/inse-fiem-2d", "max_stars_repo_head_hexsha": "06e1f8610b35da67900e1acef1004a0456a696c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-08-20T12:53:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T00:15:10.000Z", "max_issues_repo_path": "julia/src/periodic.jl", "max_issues_repo_name": "askhamwhat/inse-fiem-2d", "max_issues_repo_head_hexsha": "06e1f8610b35da67900e1acef1004a0456a696c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/src/periodic.jl", "max_forks_repo_name": "askhamwhat/inse-fiem-2d", "max_forks_repo_head_hexsha": "06e1f8610b35da67900e1acef1004a0456a696c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-03-28T18:44:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T04:17:59.000Z", "avg_line_length": 29.3577235772, "max_line_length": 97, "alphanum_fraction": 0.4957075602, "num_tokens": 1352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422227627597, "lm_q2_score": 0.8479677564567912, "lm_q1q2_score": 0.8065379367074629}} {"text": "using LinearAlgebra: norm_sqr\n\nfunction polar_to_cartesian(ρ, θ)\n x = ρ * cos(θ)\n y = ρ * sin(θ)\n Vector2(x, y)\nend\npolar_to_cartesian(polar::Vector2) = polar_to_cartesian(polar[1], polar[2])\n\nfunction cartesian_to_polar(x, y)\n ρ = √(x ^ 2 + y ^ 2)\n θ = acos(x / ρ)\n Vector2(ρ, θ)\nend\ncartesian_to_polar(xy::Vector3) = cartesian_to_polar(xy[1], xy[2])\n\n@_with_default_rng function random_point_on_circle(radius::Real)\n θ = 2π * rand(rng)\n polar_to_cartesian(radius, θ)\nend\n\n@_with_default_rng random_2d_direction() = random_point_on_circle(rng, 1.0)\n\n@_with_default_rng function random_point_on_disk(radius::Real)\n ρ = √(rand(rng) * radius ^ 2)\n random_point_on_circle(rng, ρ)\nend\n", "meta": {"hexsha": "1de4d3bf0ab3c2d634d8feec87c0e90b60b7c181", "size": 711, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils/2d_math.jl", "max_stars_repo_name": "sunoru/MosiBases.jl", "max_stars_repo_head_hexsha": "1e78693cb99ba9b7a75e97d38de4cc9a6bb83830", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils/2d_math.jl", "max_issues_repo_name": "sunoru/MosiBases.jl", "max_issues_repo_head_hexsha": "1e78693cb99ba9b7a75e97d38de4cc9a6bb83830", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-24T22:17:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T22:17:11.000Z", "max_forks_repo_path": "src/utils/2d_math.jl", "max_forks_repo_name": "sunoru/MosimoBase.jl", "max_forks_repo_head_hexsha": "1ac9aadc82d299b2c85a900a18e42db5f9f84988", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3928571429, "max_line_length": 75, "alphanum_fraction": 0.7004219409, "num_tokens": 246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422213778251, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.8065379355330832}} {"text": "struct Equirectangular\nend\n\nstruct Mercator\n central_meridian_deg::Float64\nend\n\nstruct Lambert\n central_meridian_deg::Float64\nend\n\nstruct Gnomonic\n center_lon_deg::Float64\n center_lat_deg::Float64\nend\n\n\"\"\"\nprojection(lon_deg::Float64, lat_deg::Float64,\n projparam::Equirectangular=Equirectangular())\nEquirectangular projection\n\"\"\"\nfunction projection(lon_deg::Float64, lat_deg::Float64,\n projparam::Equirectangular=Equirectangular())\n [lon_deg lat_deg]\nend\n\n\"\"\"\nprojection_inv(x::Float64, y::Float64,\n projparam::Equirectangular=Equirectangular())\nEquirectangular projection (inverse)\n\"\"\"\nfunction projection_inv(x::Float64, y::Float64,\n projparam::Equirectangular=Equirectangular())\n [x y]\nend\n\n\"\"\"\nprojection(lon_deg::Float64, lat_deg::Float64, projparam::Mercator)\nMercator projection\n\nSource: https://mathworld.wolfram.com/MercatorProjection.html\n\"\"\"\nfunction projection(lon_deg::Float64, lat_deg::Float64, projparam::Mercator)\n [(lon_deg-projparam.central_meridian_deg) rad2deg(log(tan(π/4.0 + deg2rad(lat_deg) / 2.0)))]\nend\n\n\"\"\"\nprojection_inv(x::Float64, y::Float64, projparam::Mercator)\nMercator projection (inverse)\n\nSource: https://mathworld.wolfram.com/MercatorProjection.html\n\"\"\"\nfunction projection_inv(x::Float64, y::Float64, projparam::Mercator)\n [(x + projparam.central_meridian_deg) rad2deg(atan(sinh(deg2rad(y))))]\nend\n\n\"\"\"\nprojection(lon_deg::Float64, lat_deg::Float64, projparam::Lambert)\nLambert cylindrical equal-area\n\nSource: https://mathworld.wolfram.com/CylindricalEqual-AreaProjection.html\n\"\"\"\nfunction projection(lon_deg::Float64, lat_deg::Float64, projparam::Lambert)\n [(lon_deg-projparam.central_meridian_deg) rad2deg(sin(deg2rad(lat_deg)))]\nend\n\n\"\"\"\nprojection_inv(x::Float64, y::Float64, projparam::Lambert)\nLambert cylindrical equal-area (inverse)\n\nSource: https://mathworld.wolfram.com/CylindricalEqual-AreaProjection.html\n\"\"\"\nfunction projection_inv(x::Float64, y::Float64, projparam::Lambert)\n [(x + projparam.central_meridian_deg) rad2deg(asin(deg2rad(y)))]\nend\n\n\"\"\"\nprojection(lat_deg::Float64, lon_deg::Float64, projparam::Gnomonic)\n\nSource: https://mathworld.wolfram.com/GnomonicProjection.html\n\"\"\"\nfunction projection(lon_deg::Float64, lat_deg::Float64, projparam::Gnomonic)\n\n limited_point = limitdistance(projparam.center_lon_deg,\n projparam.center_lat_deg, lon_deg, lat_deg)\n\n ϕ₀ = deg2rad(projparam.center_lat_deg)\n λ₀ = deg2rad(projparam.center_lon_deg)\n ϕ = deg2rad(limited_point[2])\n λ = deg2rad(limited_point[1])\n\n cosc = sin(ϕ₀)sin(ϕ) + cos(ϕ₀)cos(ϕ)cos(λ - λ₀)\n x = cos(ϕ)sin(λ - λ₀) / cosc\n y = (cos(ϕ₀)sin(ϕ) - sin(ϕ₀)cos(ϕ)cos(λ - λ₀)) / cosc\n return [rad2deg(x) rad2deg(y)]\nend\n\n\"\"\"\nprojection_inv(x::Float64, y::Float64, projparam::Gnomonic) inverse\n\nSource: https://mathworld.wolfram.com/GnomonicProjection.html\n\"\"\"\nfunction projection_inv(x::Float64, y::Float64, projparam::Gnomonic)\n\n # limited_point = limitdistance(projparam.center_lon_deg,\n # projparam.center_lat_deg, lon_deg, lat_deg)\n\n ϕ₀ = deg2rad(projparam.center_lat_deg)\n λ₀ = deg2rad(projparam.center_lon_deg)\n\n xr = deg2rad(x)\n yr = deg2rad(y)\n\n ρ = √(xr^2 + yr^2)\n if ρ != 0.0\n c = atan(ρ)\n ϕ = asin(cos(c)sin(ϕ₀) + yr*sin(c)cos(ϕ₀)/ρ)\n λ = λ₀ + atan(xr*sin(c),ρ*cos(ϕ₀)cos(c)-yr*sin(ϕ₀)sin(c))\n else # ρ == 0.0\n ϕ = ϕ₀\n λ = λ₀\n end\n return [rad2deg(λ) rad2deg(ϕ)]\nend\n\nfunction limitdistance(centre_point_lon_deg::Float64,\n centre_point_lat_deg::Float64, lon_deg::Float64, lat_deg::Float64)\n center_point = Navigation.Point_deg(centre_point_lat_deg,\n centre_point_lon_deg)\n point = Navigation.Point_deg(lat_deg, lon_deg)\n angular_distance = Navigation.distance(center_point, point, 1.0)\n max_angular_distance = π * 0.4\n if angular_distance > max_angular_distance\n fraction = max_angular_distance / angular_distance\n new_point = Navigation.intermediate_point(center_point, point, fraction)\n return [new_point.λ new_point.ϕ]\n else\n return [lon_deg lat_deg]\n end\nend\n", "meta": {"hexsha": "158f0c17e39698afbeaaf2f2a0607c1bf09e4721", "size": 4082, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Projection.jl", "max_stars_repo_name": "rjdverbeek-tud/FlightPlot.jl", "max_stars_repo_head_hexsha": "1b84c128393c7626250a1450966ca3213814860e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Projection.jl", "max_issues_repo_name": "rjdverbeek-tud/FlightPlot.jl", "max_issues_repo_head_hexsha": "1b84c128393c7626250a1450966ca3213814860e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Projection.jl", "max_forks_repo_name": "rjdverbeek-tud/FlightPlot.jl", "max_forks_repo_head_hexsha": "1b84c128393c7626250a1450966ca3213814860e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9503546099, "max_line_length": 96, "alphanum_fraction": 0.7275845174, "num_tokens": 1247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422241476944, "lm_q2_score": 0.8479677506936878, "lm_q1q2_score": 0.8065379324003119}} {"text": "#basis functions\nbegin\n\tP = [0 1 3 5 6 8 9;0 2 4 2 0 0 3]\n\tU = [0 0 0 0 2/5 3/5 3/5 1 1 1 1]\n\tn = size(P,2) - 1\n\tm = length(U) - 1\n\tp = m-n-1\n\tu = range(0, stop=1, length=100)\n\tfuns = zeros(length(u),n+1)\n\tfor i = 1:length(u)\n\t funs[i,:] = BasisFuns(n,p,u[Int(i)],U)\n\tend\n\n \n\tplot(u,funs)\n\tplot!([2/5, 2/5],[0, 1], line=(:dash,2))\n\tplot!([3/5, 3/5],[0, 1], line=(:dash,2))\n\tpng(\"Basisfuns\")\n\n \n\tC = funs*P'\n\tplot(C[:,1],C[:,2], line=(:dot,2))\n\tplot!(P[1,:],P[2,:], line=(:dash,2))\n\tpng(\"Example_curve\")\nend\n#Bspline_example\nbegin\n\tP1 = [0 1 3 5 5 8 9;0 2 4 2 0 0 3]\n\tU1 = [0 0 0 0 2/5 3/5 3/5 1 1 1 1]\n\tn1 = size(P1,2) - 1\n\tm1 = length(U1) - 1\n\tp1 = m1-n1-1\n\tx=4\n\tu1 = range(0,1,length=1*10^x)\n\tC1 = zeros(size(P1,1),length(u1))\n\tfor i = 1:length(u1)\n \tC1[1,i] = bsplevalc(u1[i],U1,p1,P1[1,:])\n \tC1[2,i] = bsplevalc(u1[i],U1,p1,P1[2,:])\n\tend\n\n\tplot(P1[1,:],P1[2,:],line=(:dot,2),show=false)\n\tplot!(C1[1,:],C1[2,:],line=(:dot,2),show=false)\n\tpng(\"Bspline_example\")\nend\n#Bspline_surface\nbegin\n\tPx2 = [0 3 6 9;0 3 6 9;0 3 6 9]'\n\tPy2 = [0 0 0 0;2 2 2 2;4 4 4 4]'\n\tPz2 = [0 3 3 0;2 5 5 2;0 3 3 0]'\n\tU2 = [0 0 0 1/2 1 1 1]\n\tV2 = [0 0 0 1 1 1]\n\tn2 = size(Px2,2) - 1\n\tm2 = size(Px2,1) - 1\n\th2 = length(U2) - 1\n\tk2 = length(V2) - 1\n\t\n\tq2 = k2-n2-1\n\tp2 = h2-m2-1\n\t\n\tx2 = 2\n\tu2 = range(0,1,length=30)\n\tv2 = range(0,1,length=30)\n\t\n\tlu2 = length(u2)\n\tlv2 = length(v2)\n\tCx2 = zeros(lu2,lv2)\n\tCy2 = zeros(lu2,lv2)\n\tCz2 = zeros(lu2,lv2)\n\t\n\tfor i = 1:length(u2)\n\t for j = 1:length(v2)\n\t Cx2[i,j] = bsplevals(u2[i],U2,v2[j],V2,p2,q2,Px2)\n\t Cy2[i,j] = bsplevals(u2[i],U2,v2[j],V2,p2,q2,Py2)\n\t Cz2[i,j] = bsplevals(u2[i],U2,v2[j],V2,p2,q2,Pz2)\n\t end\n\tend\n\tplot(Cx2[1,:],Cy2[1,:],Cz2[1,:],show=false)\n\tfor i = 1:length(u2)\n\t plot!(Cx2[i,:],Cy2[i,:],Cz2[i,:])\n\t plot!(Cx2[:,i],Cy2[:,i],Cz2[:,i])\n\tend\n\tfor i = 1:size(Px2,1)\n\t \tplot!(Px2[i,:],Py2[i,:],Pz2[i,:])\n\tend\n\tfor i = 1:size(Px2,2)\n\t plot!(Px2[:,i],Py2[:,i],Pz2[:,i])\n\tend\n\tpng(\"Bspline_surface\")\nend\n\n#NURBS_spiral\nbegin\n\tP3 = [0 0\n 0.55221 0.77547\n -0.62274 1.7993\n -2.7403 0.80463\n -2.9933 -2.3539\n 0.22649 -4.7546\n 4.8052 -3.0881\n 6.1866 2.4768\n 1.7955 7.4013\n -5.6108 6.4752\n -9.4769 -0.90493\n -5.236 -9.069\n 4.7457 -10.392\n 12.152 -2.3422\n 9.6459 9.1974\n -2.0323 14.135\n -13.539 6.9797\n -14.385 -7.4159\n -2.4387 -16.962\n 13.091 -12.482\n ]'\n\tU3 = [0 0 0 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 17 17 17]./17\n\tW3 = ones(1,size(P3,2))\n\n\tnpts3 = 150\n\tnrbplot(P3,W3,U3,npts3)\n\n\tu3=0.3 # % for derivative\n\tn3 = size(P3,2) - 1\n\tm3 = length(U3) - 1\n\tp3 = m3-n3-1\n\tT3 = zeros(length(u3),2)\n\tC3 = T3\n\tfor i = 1:length(u3)\n\t\tT3[i,:] = nrbder(P3,U3,W3,u3[i])\n\t\tC3[i,:],~ = nrbevalc(u3[i],U3,p3,P3,W3)\n\tend\n\tplot!(C3[:,1],C3[:,2],show=false)\n\tpng(\"Image_spiral_nrbs\")\nend\n\n#NURBSsurface\nbegin\n\tPx4 = [0 3 6 9;\t0 3 6 9;0 3 6 9]'\n\tPy4 = [0 0 0 0;\t2 2 2 2;4 4 4 4]'\n\tPz4 = [0 3 3 0;2 5 5 2;0 3 3 0]'\n\tW4 = ones(4,3)\n\tU4 = [0 0 0 1/2 1 1 1]\n\tV4 = [0 0 0 1 1 1]\n\t\n\tnptsu4 = 20\n\tnptsv4 = 20\n\tnrbplot3(Px4,Py4,Pz4,W4,U4,V4,nptsu4,nptsv4,1)\n\tpng(\"NURBSsurface\")\nend\n", "meta": {"hexsha": "e3badf4dec9e07892c38a2048a1abb8f152f2d0d", "size": 3264, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/example.jl", "max_stars_repo_name": "barche/ShipstabNURBS", "max_stars_repo_head_hexsha": "0f9ef5ad72d28d733412bfdde4850e0eddb1d7f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Examples/example.jl", "max_issues_repo_name": "barche/ShipstabNURBS", "max_issues_repo_head_hexsha": "0f9ef5ad72d28d733412bfdde4850e0eddb1d7f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Examples/example.jl", "max_forks_repo_name": "barche/ShipstabNURBS", "max_forks_repo_head_hexsha": "0f9ef5ad72d28d733412bfdde4850e0eddb1d7f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-01-21T10:17:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T10:20:51.000Z", "avg_line_length": 22.0540540541, "max_line_length": 70, "alphanum_fraction": 0.509497549, "num_tokens": 1761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422158380861, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.806537930835563}} {"text": "# medotdo da bisseccao\nfunction met_bis(a,b,f,tol=1.0e-2)\n if a>=b\n error(\"entre com a < b\")\n elseif !(f(a)*f(b) < 0)\n error(\"entre com a,b tal que f(a)*f(b) < 0\")\n end\n itermax = 100\n iter= 0\n xk= (a+b)/2\n while !(abs(f(xk))< tol) && iter < itermax\n if f(xk)*f(a) < 0\n b = xk\n elseif f(xk)*f(b) < 0\n a = xk\n end\n xk=(a+b)/2\n iter += 1 #iter = iter +1\n end\n println(\"$iter é o numero de interações\")\n if abs(f(xk)) < tol\n println(\"$xk é zero de f\")\n end\n return xk\nend\n\n# Método de Newton\nfunction newton(xk , f , df , tol = 1.0e-5)\n itermax = 100;\n iter= 0;\n while !(abs(f(xk))< tol) && iter < itermax\n xk = xk - (f(xk)/df(xk))\n iter += 1\n println(iter ,\":\", f(xk))\n end\n println(\"$iter é o numero de interações\")\n if abs(f(xk)) < tol\n println(\"$xk é zero de f\")\n end\n return xk\nend\n\n#Método de Newton Secante\nfunction newton_secante(xk, xk1, f, tol = 1.0e-5)\n itermax = 100;\n iter= 0;\n while !(abs(f(xk))< tol) && iter < itermax\n mk = (f(xk)-f(xk1))/(xk-xk1)\n xk1=xk\n xk = xk - (f(xk)/mk)\n iter += 1 #iter = iter +1\n println(iter ,\":\", f(xk))\n end\n println(\"$iter é o numero de interações\")\n if abs(f(xk)) < tol\n println(\"$xk é zero de f\")\n end\n return xk\nend\n", "meta": {"hexsha": "fbd9e1ce83784ebec951c22d067d70247b118e9f", "size": 1397, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "002 - Raizes_de_Polinomios.jl", "max_stars_repo_name": "LudwigFonseca/Julia-Language-Examples", "max_stars_repo_head_hexsha": "0e293e78d8d4d1c36eb1211ee65328d81016277a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "002 - Raizes_de_Polinomios.jl", "max_issues_repo_name": "LudwigFonseca/Julia-Language-Examples", "max_issues_repo_head_hexsha": "0e293e78d8d4d1c36eb1211ee65328d81016277a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "002 - Raizes_de_Polinomios.jl", "max_forks_repo_name": "LudwigFonseca/Julia-Language-Examples", "max_forks_repo_head_hexsha": "0e293e78d8d4d1c36eb1211ee65328d81016277a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2833333333, "max_line_length": 52, "alphanum_fraction": 0.4903364352, "num_tokens": 526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966747198242, "lm_q2_score": 0.8519527944504227, "lm_q1q2_score": 0.8064556822450321}} {"text": "\nabstract type SingleObjectiveTestFunction{N} <: TestFunction{N,1} end\n\nstruct Branin_Forrester <: SingleObjectiveTestFunction{2} end\nfunction (f::Branin_Forrester)(x::AbstractVector)\n term1 = (x[2] - 5.1 / (4 * π^2) * x[1]^2 + 5 / π * x[1] - 6)^2\n term2 = 10 * (1 - 1 / (8π)) * cos(x[1])\n return term1 + term2 + 10 + 5x[1]\nend\n\nlowerbounds(::Branin_Forrester) = Float64[-5.0, 0.0]\nupperbounds(::Branin_Forrester) = Float64[10.0, 15.0]\noptimum(::Branin_Forrester) = -16.64402157084319, [-3.689285272296118, 13.629987729088747]\n\nstruct Ackley{N} <: SingleObjectiveTestFunction{N}\n a::Float64\n b::Float64\n c::Float64\n Ackley(n; a=20.0, b=0.2, c=2π) = new{n}(a, b, c)\nend\n\nfunction (f::Ackley{N})(x::AbstractVector) where {N}\n sum1 = 0.0\n sum2 = 0.0\n for i in 1:N\n sum1 += x[i]^2\n sum2 += cos(f.c * x[i])\n end\n return -f.a * exp(-f.b * sqrt(sum1 / N)) - exp(sum2 / N) + f.a + ℯ\nend\n\nlowerbounds(::Ackley{N}) where {N} = fill(-32.768, N)\nupperbounds(::Ackley{N}) where {N} = fill(32.768, N)\noptimum(::Ackley{N}) where {N} = 0.0, zeros(N)\n\nstruct Rosenbrock{N} <: SingleObjectiveTestFunction{N} end\nRosenbrock(n::Int) = Rosenbrock{n}()\nfunction (f::Rosenbrock{N})(x::AbstractVector) where {N}\n sum = 0.0\n for i in 1:(N - 1)\n xᵢ = x[i]\n xⱼ = x[i + 1]\n sum += 100.0 * (xⱼ - xᵢ^2)^2 + (xᵢ - 1)^2\n end\n return sum\nend\n\nlowerbounds(::Rosenbrock{N}) where {N} = fill(-5.0, N)\nupperbounds(::Rosenbrock{N}) where {N} = fill(15.0, N)\noptimum(::Rosenbrock{N}) where {N} = 0.0, ones(N)\n\nstruct SumSphere{N} <: SingleObjectiveTestFunction{N} end\n\nSumSphere(n::Integer) = SumSphere{n}()\n\n(f::SumSphere{N})(x::AbstractVector) where {N} = sum(i -> i * x[i]^2, 1:N)\nlowerbounds(::SumSphere{N}) where {N} = fill(-10.0, N)\nupperbounds(::SumSphere{N}) where {N} = fill(10.0, N)\noptimum(::SumSphere{N}) where {N} = 0.0, zeros(N)\n\nabstract type ConstrainedSingleObjectTestFunction{N,C} <: SingleObjectiveTestFunction{N} end\n\nconstrains(f::ConstrainedSingleObjectTestFunction) = f.g\n\nstruct PressureVesselDesign <: ConstrainedSingleObjectTestFunction{4,4}\n g::NTuple{4,Function}\n function PressureVesselDesign()\n return new((\n x -> -x[1] + 0.0193 * x[3],\n x -> -x[2] + 0.00954 * x[3],\n x -> -pi * x[3]^2 * x[4] - (4 / 3) * pi * x[3]^3 + 1296000,\n x -> x[4] - 240,\n ))\n end\nend\n\nfunction (f::PressureVesselDesign)(x::AbstractVector)\n d1, d2, r, L = x\n return 0.6224 * d1 * r * L + 1.7781 * d2 * r^2 + 3.1661 * d1^2 * L + 19.84 * d1^2 * r\nend\n\nlowerbounds(::PressureVesselDesign) = [0.0625, 0.0625, 10.0, 10.0]\nupperbounds(::PressureVesselDesign) = [99 * 0.0625, 99 * 0.0625, 200.0, 200.0]\nfunction optimum(::PressureVesselDesign)\n f = 6059.714335048436\n x = [0.8125, 0.4375, 42.0984455958549, 176.6365958424394]\n return f, x\nend\n\nstruct CantileverBeamDesign <: ConstrainedSingleObjectTestFunction{5,1}\n g::NTuple{1,Function}\n function PressureVesselDesign()\n return new((\n x -> 61 / x[1]^3 + 37 / x[2]^3 + 19 / x[3]^3 + 7 / x[4]^3 + 1 / x[5]^3 - 1,\n ))\n end\nend\n\n(f::CantileverBeamDesign)(x::AbstractVector) = 0.0624 * sum(x)\n\nlowerbounds(::CantileverBeamDesign) = fill(0.01, 5)\nupperbounds(::CantileverBeamDesign) = fill(100.0, 5)\nfunction optimum(::CantileverBeamDesign)\n f = 1.339956367\n x = [6.0160159, 5.3091739, 4.4943296, 3.5014750, 2.15266533]\n return f, x\nend\n", "meta": {"hexsha": "dae81e704e94cb6b7906e38296ed31930ce69f3b", "size": 3449, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/testfunction/single_obj_functions.jl", "max_stars_repo_name": "xue-cheng/EfficientGlobalOptimiztion.jl", "max_stars_repo_head_hexsha": "1b3a4bb4a23da81ed74f4b4686181b9322024049", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-06T02:41:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-06T02:41:28.000Z", "max_issues_repo_path": "src/testfunction/single_obj_functions.jl", "max_issues_repo_name": "xue-cheng/EfficientGlobalOptimiztion.jl", "max_issues_repo_head_hexsha": "1b3a4bb4a23da81ed74f4b4686181b9322024049", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-09-27T12:52:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-27T12:52:42.000Z", "max_forks_repo_path": "src/testfunction/single_obj_functions.jl", "max_forks_repo_name": "xue-cheng/EfficientGlobalOptimiztion.jl", "max_forks_repo_head_hexsha": "1b3a4bb4a23da81ed74f4b4686181b9322024049", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T10:43:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T10:43:48.000Z", "avg_line_length": 31.9351851852, "max_line_length": 92, "alphanum_fraction": 0.6146709191, "num_tokens": 1383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966656805269, "lm_q2_score": 0.8519528019683106, "lm_q1q2_score": 0.8064556816603851}} {"text": "\r\n#module Coordinatesm\r\n#export Coordinates, PossibleCoordinates, Coordinates2d, Coordinates2dIndex, polar_to_2d, polar_to_2d_index, calc_possible_coordinates, get_random_coordinates\r\n\r\nusing Random\r\n\r\nstruct PossibleCoordinates\r\n ϕs::Array{Float64}\r\n θs::Array{Float64}\r\nend\r\n\r\nstruct Coordinates\r\n ϕ::Float64\r\n θ::Float64\r\nend\r\nstruct Coordinates2d\r\n x::Float64\r\n y::Float64\r\nend\r\nstruct Coordinates2dIndex\r\n x::Int\r\n y::Int\r\nend\r\nfunction polar_to_2d(p::Coordinates)\r\n x=sin(p.θ)*cos(p.ϕ)\r\n y=sin(p.θ)*sin(p.ϕ)\r\n return Coordinates2d(x,y)\r\nend\r\nfunction polar_to_2d_index(p::Coordinates,width::Int,height::Int)\r\n c=polar_to_2d(p)\r\n if p.θ < pi/2\r\n xindex=1+floor(Int,((1.0+c.x)/2.0)*(width/2.0)) #left\r\n else\r\n xindex=floor(Int,width/2.0)+1+floor(Int,((1.0+c.x)/2.0)*(width/2.0)) #right\r\n end\r\n yindex=1+floor(Int,((1.0+c.y)/2.0)*height)\r\n return Coordinates2dIndex(xindex,yindex)\r\nend\r\n\r\nfunction calc_possible_coordinates(number_cells::Int)\r\n nθ=floor(Int,sqrt(number_cells/2))\r\n nϕ=2*nθ\r\n ϕs=range(0,2π,length=nϕ)\r\n θs=range(0,π,length=nθ)\r\n PossibleCoordinates(ϕs,θs)\r\nend\r\n\r\nfunction get_random_coordinates(possible_coordinates::PossibleCoordinates)\r\n return Coordinates(rand(possible_coordinates.ϕs),rand(possible_coordinates.θs))\r\nend\r\n\r\nfunction align_to_possible_coordinates(c::Coordinates, possible_coordinates::PossibleCoordinates)\r\n aligned_ϕ=-1.0\r\n if c.ϕ < possible_coordinates.ϕs[1]\r\n aligned_ϕ = possible_coordinates.ϕs[1]\r\n elseif c.ϕ >= possible_coordinates.ϕs[end]\r\n aligned_ϕ = possible_coordinates.ϕs[1]\r\n else\r\n for ϕ_index in 1:(length(possible_coordinates.ϕs)-1)\r\n if c.ϕ >= possible_coordinates.ϕs[ϕ_index] && c.ϕ < possible_coordinates.ϕs[ϕ_index+1]\r\n aligned_ϕ = possible_coordinates.ϕs[ϕ_index]\r\n end\r\n end\r\n end\r\n aligned_θ=-1.0\r\n if c.θ < possible_coordinates.θs[1]\r\n aligned_θ = possible_coordinates.θs[1]\r\n elseif c.θ >= possible_coordinates.θs[end]\r\n aligned_θ = possible_coordinates.θs[1]\r\n else\r\n for θ_index in 1:(length(possible_coordinates.θs)-1)\r\n if c.θ >= possible_coordinates.θs[θ_index] && c.θ < possible_coordinates.θs[θ_index+1]\r\n aligned_θ = possible_coordinates.θs[θ_index]\r\n end\r\n end\r\n end\r\n return Coordinates(aligned_ϕ,aligned_θ)\r\nend\r\n\r\n#end", "meta": {"hexsha": "1fa5dee79acf708958f38ffbef49d1c371d2daeb", "size": 2442, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/coordinates.jl", "max_stars_repo_name": "oheil/PlayGround.jl", "max_stars_repo_head_hexsha": "8800c6b732e1b98cdf65187cd98836f71d7681ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/coordinates.jl", "max_issues_repo_name": "oheil/PlayGround.jl", "max_issues_repo_head_hexsha": "8800c6b732e1b98cdf65187cd98836f71d7681ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/coordinates.jl", "max_forks_repo_name": "oheil/PlayGround.jl", "max_forks_repo_head_hexsha": "8800c6b732e1b98cdf65187cd98836f71d7681ed", "max_forks_repo_licenses": ["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.525, "max_line_length": 159, "alphanum_fraction": 0.6703521704, "num_tokens": 754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611631680358, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.8064478841676659}} {"text": "## Lotka-Volterra\n\nfunction lotka(du,u,p,t)\n x = u[1]\n y = u[2]\n du[1] = p[1]*x - p[2]*x*y\n du[2] = -p[3]*y + p[4]*x*y\nend\n\n\"\"\"\nLotka-Voltera Equations (Non-stiff)\n\n```math\n\\\\frac{dx}{dt} = ax - bxy\n```\n```math\n\\\\frac{dy}{dt} = -cy + dxy\n```\n\nwith initial condition ``x=y=1``\n\"\"\"\nprob_ode_lotkavoltera = ODEProblem(lotka,[1.0,1.0],(0.0,1.0),[1.5,1.0,3.0,1.0])\n\n## Fitzhugh-Nagumo\n\nfunction fitz(du,u,p,t)\n v = u[1]\n w = u[2]\n a = p[1]\n b = p[2]\n τinv = p[3]\n l = p[4]\n du[1] = v - v^3/3 -w + l\n du[2] = τinv*(v + a - b*w)\nend\n\"\"\"\nFitzhugh-Nagumo (Non-stiff)\n\n```math\n\\\\frac{dv}{dt} = v - \\\\frac{v^3}{3} - w + I_{est}\n```\n```math\nτ \\\\frac{dw}{dt} = v + a -bw\n```\n\nwith initial condition ``v=w=1``\n\"\"\"\nprob_ode_fitzhughnagumo = ODEProblem(fitz,[1.0;1.0],(0.0,1.0),(0.7,0.8,1/12.5,0.5))\n\n\n#Van der Pol Equations\n@parameters t μ\n@variables x(t) y(t)\n@derivatives D'~t\neqs = [D(x) ~ μ*((1-x^2)*y - x),\n D(y) ~ y]\nde = ODESystem(eqs)\nvan = ODEFunction(de, [x,y], [μ], jac=true, Wfact=true)\n\n\"\"\"\nVan der Pol Equations\n\n```math\n\\\\frac{dx}{dt} = y\n```\n```math\n\\\\frac{dy}{dt} = μ((1-x^2)y -x)\n```\n\nwith ``μ=1.0`` and ``u_0=[0,\\\\sqrt{3}]``\n\nNon-stiff parameters.\n\"\"\"\nprob_ode_vanderpol = ODEProblem(van,[0;sqrt(3)],(0.0,1.0),1.0)\n\n\"\"\"\nVan der Pol Equations\n\n```math\n\\\\frac{dx}{dt} = y\n```\n```math\n\\\\frac{dy}{dt} = μ(1-x^2)y -x\n```\n\nwith ``μ=10^6`` and ``u_0=[0,\\\\sqrt{3}]``\n\nStiff parameters.\n\"\"\"\nprob_ode_vanstiff = ODEProblem(van,[0;sqrt(3)],(0.0,1.0),1e6)\n\n# ROBER\n@parameters t k₁ k₂ k₃\n@variables y₁(t) y₂(t) y₃(t)\n@derivatives D'~t\neqs = [D(y₁) ~ -k₁*y₁+k₃*y₂*y₃,\n D(y₂) ~ k₁*y₁-k₂*y₂^2-k₃*y₂*y₃,\n D(y₃) ~ k₂*y₂^2]\nde = ODESystem(eqs)\nrober = ODEFunction(de, [y₁,y₂,y₃], [k₁,k₂,k₃], jac=true, Wfact=true)\n\n\"\"\"\nThe Robertson biochemical reactions: (Stiff)\n\n```math\n\\\\frac{dy₁}{dt} = -k₁y₁+k₃y₂y₃\n```\n```math\n\\\\frac{dy₂}{dt} = k₁y₁-k₂y₂^2-k₃y₂y₃\n```\n```math\n\\\\frac{dy₃}{dt} = k₂y₂^2\n```\n\nwhere ``k₁=0.04``, ``k₂=3\\\\times10^7``, ``k₃=10^4``. For details, see:\n\nHairer Norsett Wanner Solving Ordinary Differential Equations I - Nonstiff Problems Page 129\n\nUsually solved on ``[0,1e11]``\n\"\"\"\nprob_ode_rober = ODEProblem(rober,[1.0;0.0;0.0],(0.0,1e11),(0.04,3e7,1e4))\n\n# Three Body\nconst threebody_μ = big(0.012277471); const threebody_μ′ = 1 - threebody_μ\n\nthreebody = (du,u,p,t) -> begin\n # 1 = y₁\n # 2 = y₂\n # 3 = y₁'\n # 4 = y₂'\n D₁ = ((u[1]+threebody_μ)^2 + u[2]^2)^(3/2)\n D₂ = ((u[1]-threebody_μ′)^2 + u[2]^2)^(3/2)\n du[1] = u[3]\n du[2] = u[4]\n du[3] = u[1] + 2u[4] - threebody_μ′*(u[1]+threebody_μ)/D₁ - threebody_μ*(u[1]-threebody_μ′)/D₂\n du[4] = u[2] - 2u[3] - threebody_μ′*u[2]/D₁ - threebody_μ*u[2]/D₂\nend\n\n@doc doc\"\"\"\nThe ThreeBody problem as written by Hairer: (Non-stiff)\n\n```math\n\\frac{dy₁}{dt} = y₁ + 2\\frac{dy₂}{dt} - \\bar{μ}\\frac{y₁+μ}{D₁} - μ\\frac{y₁-\\bar{μ}}{D₂}\n```\n```math\n\\frac{dy₂}{dt} = y₂ - 2\\frac{dy₁}{dt} - \\bar{μ}\\frac{y₂}{D₁} - μ\\frac{y₂}{D₂}\n```\n```math\nD₁ = ((y₁+μ)^2 + y₂^2)^{3/2}\n```\n```math\nD₂ = ((y₁-\\bar{μ})^2+y₂^2)^{3/2}\n```\n```math\nμ = 0.012277471\n```\n```math\n\\bar{μ} =1-μ\n```\n\nFrom Hairer Norsett Wanner Solving Ordinary Differential Equations I - Nonstiff Problems Page 129\n\nUsually solved on ``t₀ = 0.0`` and ``T = 17.0652165601579625588917206249``\nPeriodic with that setup.\n\"\"\"\nprob_ode_threebody = ODEProblem(threebody,[0.994, 0.0, 0.0, big(-2.00158510637908252240537862224)],(big(0.0),big(17.0652165601579625588917206249)))\n\n# Rigid Body Equations\n\n@parameters t I₁ I₂ I₃\n@variables y₁(t) y₂(t) y₃(t)\n@derivatives D'~t\neqs = [D(y₁) ~ I₁*y₂*y₃,\n D(y₂) ~ I₂*y₁*y₃,\n D(y₃) ~ I₃*y₁*y₂]\nde = ODESystem(eqs)\nrigid = ODEFunction(de, [y₁,y₂,y₃], [I₁,I₂,I₃], jac=true, Wfact=true)\n\n\"\"\"\nRigid Body Equations (Non-stiff)\n\n```math\n\\\\frac{dy₁}{dt} = I₁y₂y₃\n```\n```math\n\\\\frac{dy₂}{dt} = I₂y₁y₃\n```\n```math\n\\\\frac{dy₃}{dt} = I₃y₁y₂\n```\n\nwith ``I₁=-2``, ``I₂=1.25``, and ``I₃=-1/2``.\n\nThe initial condition is ``y=[1.0;0.0;0.9]``.\n\nFrom Solving Differential Equations in R by Karline Soetaert\n\nor Hairer Norsett Wanner Solving Ordinary Differential Equations I - Nonstiff Problems Page 244\n\nUsually solved from 0 to 20.\n\"\"\"\nprob_ode_rigidbody = ODEProblem(rigid,[1.0,0.0,0.9],(0.0,20.0),(-2.0,1.25,-0.5))\n\n# Pleiades Problem\n\npleiades = (du,u,p,t) -> begin\n x = view(u,1:7) # x\n y = view(u,8:14) # y\n v = view(u,15:21) # x′\n w = view(u,22:28) # y′\n du[1:7] .= v\n du[8:14].= w\n for i in 14:28\n du[i] = zero(eltype(u))\n end\n for i=1:7,j=1:7\n if i != j\n r = ((x[i]-x[j])^2 + (y[i] - y[j])^2)^(3/2)\n du[14+i] += j*(x[j] - x[i])/r\n du[21+i] += j*(y[j] - y[i])/r\n end\n end\nend\n\n@doc doc\"\"\"\nPleiades Problem (Non-stiff)\n\n```math\n\\frac{d^2xᵢ}{dt^2} = \\sum_{j≠i} mⱼ(xⱼ-xᵢ)/rᵢⱼ\n```\n```math\n\\frac{d^2yᵢ}{dt^2} = \\sum_{j≠i} mⱼ(yⱼ-yᵢ)/rᵢⱼ\n```\n\nwhere\n\n```math\nrᵢⱼ = ((xᵢ-xⱼ)^2 + (yᵢ-yⱼ)^2)^{3/2}\n```\n\nand initial conditions are\n\n```math\nx₁(0) = 3\n```\n```math\nx₂(0) = 3\n```\n```math\nx₃(0) = -1\n```\n```math\nx₄(0) = -3\n```\n```math\nx₅(0) = 2\n```\n```math\nx₆(0) = -2\n```\n```math\nx₇(0) = 2\n```\n```math\ny₁(0) = 3\n```\n```math\ny₂(0) = -3\n```\n```math\ny₃(0) = 2\n```\n```math\ny₄(0) = 0\n```\n```math\ny₅(0) = 0\n```\n```math\ny₆(0) = -4\n```\n```math\ny₇(0) = 4\n```\n\nand with ``\\frac{dxᵢ(0)}{dt}=\\frac{dyᵢ(0)}{dt}=0`` except for\n\n```math\n\\frac{dx₆(0)}{dt} = 1.75\n```\n```math\n\\frac{dx₇(0)}{dt} = -1.5\n```\n```math\n\\frac{dy₄(0)}{dt} = -1.25\n```\n```math\n\\frac{dy₅(0)}{dt} = 1\n```\n\nFrom Hairer Norsett Wanner Solving Ordinary Differential Equations I - Nonstiff Problems Page 244\n\nUsually solved from 0 to 3.\n\"\"\"\nprob_ode_pleiades = ODEProblem(pleiades,[3.0,3.0,-1.0,-3.0,2.0,-2.0,2.0,3.0,-3.0,2.0,0,0,-4.0,4.0,0,0,0,0,0,1.75,-1.5,0,0,0,-1.25,1,0,0],(0.0,3.0))\n\n\n\nRandom.seed!(100)\nconst mm_A = rand(4,4)\nmm_linear = function (du,u,p,t)\n mul!(du,mm_A,u)\nend\nconst MM_linear =Matrix(Diagonal(0.5ones(4)))\nmm_f = ODEFunction(mm_linear;analytic = (u0,p,t) -> exp(inv(MM_linear)*mm_A*t)*u0, mass_matrix=MM_linear)\nprob_ode_mm_linear = ODEProblem(mm_f,rand(4),(0.0,1.0))\n\n\n\n\n\n@parameters t p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12\n@variables y1(t) y2(t) y3(t) y4(t) y5(t) y6(t) y7(t) y8(t)\n@derivatives D'~t\neqs = [D(y1) ~ -p1*y1 + p2*y2 + p3*y3 + p4,\n D(y2) ~ p1*y1 - p5*y2,\n D(y3) ~ -p6*y3 + p2*y4 + p7*y5,\n D(y4) ~ p3*y2 + p1*y3 - p8*y4,\n D(y5) ~ -p9*y5 + p2*y6 + p2*y7,\n D(y6) ~ -p10*y6*y8 + p11*y4 + p1*y5 -\n p2*y6 + p11*y7,\n D(y7) ~ p10*y6*y8 - p12*y7,\n D(y8) ~ -p10*y6*y8 + p12*y7]\nde = ODESystem(eqs)\nhires = ODEFunction(de, [y1,y2,y3,y4,y5,y6,y7,y8],\n [p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11,p12],\n jac=true, Wfact=true)\n\nu0 = zeros(8)\nu0[1] = 1\nu0[8] = 0.0057\n\n\"\"\"\nHires Problem (Stiff)\n\nIt is in the form of \n\n```math\n\\\\frac{dy}{dt} = f(y)\n```\n\n with\n\n```math\n y(0)=y_0, \\\\quad y \\\\in ℝ^8, \\\\quad 0 ≤ t ≤ 321.8122\n```\n\nwhere ``f`` is defined by\n\n``f(y) = \\\\begin{pmatrix} −1.71y_1 & +0.43y_2 & +8.32y_3 & +0.0007y_4 & \\\\\\\\ 1.71y_1 & −8.75y_2 & & & \\\\\\\\ −10.03y_3 & +0.43y_4 & +0.035y_5 & & \\\\\\\\ 8.32y_2 & +1.71y_3 & −1.12y_4 & & \\\\\\\\ −1.745y_5 & +0.43y_6 & +0.43y_7 & & \\\\\\\\ −280y_6y_8 & +0.69y_4 & +1.71y_5 & −0.43y_6 & +0.69y_7 \\\\\\\\ 280y_6y_8 & −1.81y_7 & & & \\\\\\\\ −280y_6y_8 & +1.81y_7 & & & \\\\end{pmatrix}``\n\nReference: [demohires.pdf](http://www.radford.edu/~thompson/vodef90web/problems/demosnodislin/Demos_Pitagora/DemoHires/demohires.pdf) \nNotebook: [Hires.ipynb](http://nbviewer.jupyter.org/github/JuliaDiffEq/DiffEqBenchmarks.jl/blob/master/StiffODE/Hires.ipynb)\n\"\"\"\nprob_ode_hires = ODEProblem(hires,u0,(0.0,321.8122), (1.71, 0.43, 8.32, 0.0007, 8.75,\n 10.03, 0.035, 1.12, 1.745, 280.0,\n 0.69, 1.81))\n\n@parameters t p1 p2 p3\n@variables y1(t) y2(t) y3(t)\n@derivatives D'~t\neqs = [D(y1) ~ p1*(y2+y1*(1-p2*y1-y2)),\n D(y2) ~ (y3-(1+y1)*y2)/p1,\n D(y3) ~ p3*(y1-y3)]\nde = ODESystem(eqs)\njac = calculate_jacobian(de)\nModelingToolkit.calculate_factorized_W(de)\norego = ODEFunction(de, [y1,y2,y3], [p1,p2,p3], jac=true, Wfact=true)\n\n\"\"\"\nOrego Problem (Stiff)\n\nIt is in the form of ``\\\\frac{dy}{dt}=f(y), \\\\quad y(0)=y0,`` with\n\n```math\ny \\\\in ℝ^3, \\\\quad 0 ≤ t ≤ 360\n```\n\nwhere ``f`` is defined by\n\n``f(y) = \\\\begin{pmatrix} s(y_2 - y_1(1-qy_1-y_2)) \\\\\\\\ (y_3 - y_2(1+y_1))/s \\\\\\\\ w(y_1-y_3) \\\\end{pmatrix}``\n\nwhere ``s=77.27``, ``w=0.161`` and ``q=8.375⋅10^{-6}``.\n\nReference: [demoorego.pdf](http://www.radford.edu/~thompson/vodef90web/problems/demosnodislin/Demos_Pitagora/DemoOrego/demoorego.pdf)\nNotebook: [Orego.ipynb](http://nbviewer.jupyter.org/github/JuliaDiffEq/DiffEqBenchmarks.jl/blob/master/StiffODE/Orego.ipynb)\n\"\"\"\nprob_ode_orego = ODEProblem(orego,[1.0,2.0,3.0],(0.0,30.0),[77.27,8.375e-6,0.161])\n", "meta": {"hexsha": "da308c3e03dae7816354449b666c03c9fa8ee50b", "size": 8709, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ode/ode_simple_nonlinear_prob.jl", "max_stars_repo_name": "mforets/DiffEqProblemLibrary.jl", "max_stars_repo_head_hexsha": "0722026efe627caa47b5002693eba2f899dbae92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ode/ode_simple_nonlinear_prob.jl", "max_issues_repo_name": "mforets/DiffEqProblemLibrary.jl", "max_issues_repo_head_hexsha": "0722026efe627caa47b5002693eba2f899dbae92", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ode/ode_simple_nonlinear_prob.jl", "max_forks_repo_name": "mforets/DiffEqProblemLibrary.jl", "max_forks_repo_head_hexsha": "0722026efe627caa47b5002693eba2f899dbae92", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8270676692, "max_line_length": 365, "alphanum_fraction": 0.5673441268, "num_tokens": 4220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464795, "lm_q2_score": 0.8791467722591728, "lm_q1q2_score": 0.8064436743470799}} {"text": "# # Cellular Automaton\n#\n# ## Abstract\n# We have an arrangement of atoms/cells. Each cell belongs to one in a finite\n# set of states. With the progression of a unit time cells change their state\n# in a parallel fashion determined by the rules of the system.\n#\n# Depending on the initial state and thr rules of the system we get a variety\n# of behaviours. Some systems lead to homogenous states, some exhibit periodic\n# oscillations between states, some are chaotic non-deterministic behaviours,\n# ,.etc . The study of these discrete and abstract computational systems is\n# called cellular automaton.\n# ![https://plato.stanford.edu/entries/cellular-automata/](https://plato.stanford.edu/entries/cellular-automata/)\n# is a great resource to understand and explore these systems.\n#\n# # Game of Life\n#\n# Game of Life is a popular cellular automaton devised by British mathematician\n# John Conway. It consists of a two dimensional grid of cells with a start state\n# with each cell being either dead or live at any point in time.\n#\n# The rules of the system are as follows :-\n# * A cell with less than two neighbours dies due to underpopulation.\n# * A cell with two or three neighbours lives.\n# * A cell with greater than three neighbours dies by overpopulation.\n# * A dead cell with three live neighbours becomes live.\n#\n# We will implement this game of life in minecraft to generate some interesting\n# patterns.\n\nusing PiCraft\n\n# First let's write our function which will transform from one state to another.\n\nfunction nextState(A::Array{Bool, 2})\n B = similar(A)\n dims = size(A)\n for i = 1:dims[1], j = 1:dims[2]\n liveNeighbours = 0\n for p = -1:1, q = -1:1\n if checkbounds(Bool, A, i + p, j + q) && (p == 0 && q == 0)\n liveNeighbours += 1\n end\n end\n if A[i, j] == false && liveNeighbours == 3\n B[i, j] = true\n elseif liveNeighbours < 2 || liveNeighbours > 3\n B[i, j] = false\n end\n end\n return B\nend\n\n# Now to render an arbitrary 2-D board in Minecraft\n# Let live cells be white wool and dead be black wool\n\nfunction displayState(p::Tuple{Int, Int, Int}, A::Array{Bool, 2})\n dims = size(A)\n for i = 1:dims[1], j = 1:dims[2]\n if A[i, j]\n setBlock(p .+ (i, j, 0), Block(35))\n else\n setBlock(p .+ (i, j, 0), Block(35, 15))\n end\n end\nend\n\np = getTile() .+ (3, 4, 3)\nA = rand(Bool, 10, 10)\n\nfor i = 1:20\n displayState(A)\n A = nextState(A)\n sleep(0.5)\nend\n\n# A variety of interesting patterns can be found ![here](http://web.stanford.edu/~cdebs/GameOfLife/)\n# It is encouraged that you experiment with various patterns.\n\n# # 3-D implementation\n# If we want to consider a 3-D implementation of the Game of Life then we must\n# realise that in 3-D a cell will have 26 Neighbours (3^3 - 1).\n#\n# We generally express a 3-D system as a `Life wxyz` system.\n# The rules of such a system are :\n#\n# * The number of live neighbours must be between `w` and `x` to sustain life.\n# * The number of live neighbours must be between `y` and `z` to bring a dead\n# back to life.\n#\n# Conway's Game of Life is hence a `Life 2333` system.\n# Since a large number of combinations are possible they have been studied\n# extensively for their properties. Most systems quickly collapse or explode.\n# Life 4555 and 5766 are the only valid systems which exhibit life like\n# properties.\n#\n# Let's implement Life 4555. For that we will rewrite the `nextState` and `displayState`\n# funcitons.\n\nfunction nextState(A::Array{Bool, 3})\n B = similar(A)\n dims = size(A)\n for i = 1:dims[1], j = 1:dims[2], k = 1:dims[3]\n liveNeighbours = 0\n for p = -1:1, q = -1:1, r = -1:1\n if checkbounds(Bool, A, i + p, j + q, k + r) && (p == 0 && q == 0 && r == 0)\n liveNeighbours += 1\n end\n end\n if A[i, j, k] == false && liveNeighbours == 5\n B[i, j, k] = true\n elseif liveNeighbours < 4 || liveNeighbours > 5\n B[i, j, k] = false\n end\n end\n return B\nend\n\nfunction displayState(p::Tuple{Int, Int, Int}, A::Array{Bool, 3})\n dims = size(A)\n for i = 1:dims[1], j = 1:dims[2], k = 1:dims[3]\n if A[i, j, k]\n setBlock(p .+ (i, j, k), Block(35))\n else\n setBlock(p .+ (i, j, k), Block(35, 15))\n end\n end\nend\n\np = getTile() .+ (3, 4, 3)\nA = rand(Bool, 7, 7, 7)\n\nfor i = 1:20\n displayState(A)\n A = nextState(A)\n sleep(0.5)\nend\n", "meta": {"hexsha": "8be907726907c10252852775975f9693b23c69c8", "size": 4510, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/GameOfLife.jl", "max_stars_repo_name": "oschulz/PiCraft.jl", "max_stars_repo_head_hexsha": "ade61d279e41ebaab45e25d0d322a62d1d54b42a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 36, "max_stars_repo_stars_event_min_datetime": "2016-10-19T10:57:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T07:31:42.000Z", "max_issues_repo_path": "example/GameOfLife.jl", "max_issues_repo_name": "oschulz/PiCraft.jl", "max_issues_repo_head_hexsha": "ade61d279e41ebaab45e25d0d322a62d1d54b42a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2017-05-25T07:23:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T00:55:35.000Z", "max_forks_repo_path": "example/GameOfLife.jl", "max_forks_repo_name": "oschulz/PiCraft.jl", "max_forks_repo_head_hexsha": "ade61d279e41ebaab45e25d0d322a62d1d54b42a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2017-05-10T08:54:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:10:04.000Z", "avg_line_length": 32.6811594203, "max_line_length": 113, "alphanum_fraction": 0.6314855876, "num_tokens": 1334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628702, "lm_q2_score": 0.870597273444551, "lm_q1q2_score": 0.8064375055178203}} {"text": "using Optim, SMM, HTTP, GLM, LinearAlgebra, Random, Statistics, DataFrames, DataFramesMeta, CSV\r\n#Worked with Ahmed and Aleeze\r\nfunction ps7()\r\n#Q1\r\nurl = \"https://raw.githubusercontent.com/OU-PhD-Econometrics/fall-2020/master/ProblemSets/PS1-julia-intro/nlsw88.csv\"\r\ndf = CSV.read(HTTP.get(url).body, DataFrame)\r\nX = [ones(size(df,1),1) df.age df.race.==1 df.collgrad.==1]\r\ny = df.married.==1\r\n\r\nfunction ols_gmm(alpha, X,y)\r\n g = y .- X*alpha\r\n J = g'*I*g\r\n return J\r\nend\r\nalphhat_optim = optimize(a -> ols_gmm(a, X, y), rand(size(X,2)), LBFGS(), Optim.Options(g_tol=1e-8, iterations=100_000))\r\nprintln(alphhat_optim.minimizer)\r\n# Checking work\r\nbols = inv(X'*X)*X'*y\r\n\r\n#2a\r\n\r\n\r\ndf = dropmissing(df, :occupation)\r\ndf[df.occupation.==8 ,:occupation] .= 7\r\ndf[df.occupation.==9 ,:occupation] .= 7\r\ndf[df.occupation.==10,:occupation] .= 7\r\ndf[df.occupation.==11,:occupation] .= 7\r\ndf[df.occupation.==12,:occupation] .= 7\r\ndf[df.occupation.==13,:occupation] .= 7\r\n\r\nX = [ones(size(df,1),1) df.age df.race.==1 df.collgrad.==1]\r\ny = df.occupation\r\n\r\nfunction mlogit(alpha, X, y)\r\n \r\n K = size(X,2)\r\n J = length(unique(y))\r\n N = length(y)\r\n bigY = zeros(N,J)\r\n for j=1:J\r\n bigY[:,j] = y.==j\r\n end\r\n bigAlpha = [reshape(alpha,K,J-1) zeros(K)]\r\n \r\n num = zeros(N,J)\r\n dem = zeros(N)\r\n for j=1:J\r\n num[:,j] = exp.(X*bigAlpha[:,j])\r\n dem .+= num[:,j]\r\n end\r\n \r\n P = num./repeat(dem,1,J)\r\n \r\n loglike = -sum( bigY.*log.(P) )\r\n \r\n return loglike\r\nend\r\n\r\nalpha_zero = zeros(6*size(X,2))\r\nalpha_rand = rand(6*size(X,2))\r\nalpha_true = [.1910213,-.0335262,.5963968,.4165052,-.1698368,-.0359784,1.30684,-.430997,.6894727,-.0104578,.5231634,-1.492475,-2.26748,-.0053001,1.391402,-.9849661,-1.398468,-.0142969,-.0176531,-1.495123,.2454891,-.0067267,-.5382892,-3.78975]\r\nalpha_start = alpha_true.*rand(size(alpha_true))\r\nprintln(size(alpha_true))\r\n\r\n#2b\r\n\r\nalpha_hat_optim = optimize(a -> mlogit(a, X, y), alpha_start, LBFGS(), Optim.Options(g_tol = 1e-5, iterations=100_000, show_trace=true, show_every=50))\r\nalpha_hat_mle = alpha_hat_optim.minimizer\r\nprintln(alpha_hat_mle)\r\n\r\n#2C\r\n\r\nfunction logit_gmm(alpha, X, y)\r\n K = size(X,2)\r\n J = length(unique(y))\r\n N = length(y)\r\n bigY = zeros(N,J)\r\n for j=1:J\r\n bigY[:,j] = y.==j\r\n end\r\n bigAlpha = [reshape(alpha,K,J-1) zeros(K)]\r\n \r\n num = zeros(N,J)\r\n dem = zeros(N)\r\n for j=1:J\r\n num[:,j] = exp.(X*bigAlpha[:,j])\r\n dem .+= num[:,j]\r\n end\r\n \r\n P = num./repeat(dem,1,J)\r\n \r\n loglike = -sum( bigY.*log.(P) )\r\n \r\n return loglike\r\nend\r\n\r\nalpha_hat_optim = optimize(a -> logit_gmm(a, X, y), alpha_true, LBFGS(), Optim.Options(g_tol = 1e-5, iterations=100_000, show_trace=true, show_every=50))\r\nprintln(alpha_hat_optim)\r\n\r\nalpha_hat_optim = optimize(a -> logit_gmm(a, X, y), alpha_rand, LBFGS(), Optim.Options(g_tol = 1e-5, iterations=100_000, show_trace=true, show_every=50))\r\nprintln(alpha_hat_optim)\r\n\r\n#The objective function looks globally concave. \r\n\r\n#3a\r\nXR = rand(1000,2)\r\n#3b\r\nbeta = [[(.4),(.1),(.5)] [(.5),(.2),(.4)]]]\r\n#3c\r\np = XR*beta\r\n#3d\r\neps = random(GeneralizedExtremeValue(0, 1, 0), 1000, 3)\r\n\r\nGenY = zeros(1000,1)\r\nfor i in 1:size((XR),1)\r\n GenY[i,1] = argmax(p[i,:] + eps[i,:])\r\nend\r\n\r\n#4\r\n\r\nMA = SMM.parallelNormal()\r\ndc = SMM.history(MA.chains[1])\r\ndc = dc[dc[:accepted].==true, :]\r\nprintln(describe(dc))\r\n\r\n#5, I'm sorry but I was very confused on this question. I tried mixing and matching with the code you gave in \r\n#the slides but I'm sure I'm missing something here.\r\nfunction gmm_smm(θ, X, y, D)\r\n K = size(X,2)\r\n N = size(y,1)\r\n β = θ[1:end-1]\r\n σ = θ[end]\r\n if length(β)==1\r\n β = β[1]\r\n end\r\n # N+1 moments in both model and data\r\n gmodel = zeros(N+1,D)\r\n # data moments are just the y vector itself\r\n # and the variance of the y vector\r\n gdata = vcat(y,var(y))\r\n #### !!!!!!!!!!!!!!!!!!!!!!!!!!!!! ####\r\n # This is critical! #\r\n Random.seed!(1234) #\r\n # You must always use the same ε draw #\r\n # for every guess of θ! #\r\n #### !!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ###\r\n # simulated model moments\r\n for d=1:D\r\n ε = σ*randn(N)\r\n ỹ = X*β .+ ε\r\n gmodel[1:end-1,d] = ỹ\r\n gmodel[ end ,d] = var(ỹ)\r\n end\r\n # criterion function\r\n err = vec(gdata .- mean(gmodel; dims=2))\r\n # weighting matrix is the identity matrix\r\n # minimize weighted difference between data and moments\r\n J = err'*I*err\r\n return J\r\nend\r\n\r\nalpha_hat_smm = optimize(a -> gmm_smm(a, X, y, 1000), alpha_true, LBFGS(), Optim.Options(g_tol = 1e-5, iterations=100_000, show_trace=true, show_every=50))\r\nprintln(alpha_hat_smm)\r\nend\r\n\r\nps7()", "meta": {"hexsha": "dad5fb3edae19ffd4cf23a5c8be69af8c8d7acfa", "size": 4794, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ProblemSets/PS7-smm/Metrics3_HW7.jl", "max_stars_repo_name": "town0041/fall-2021", "max_stars_repo_head_hexsha": "d872c35c98342f8b5a28e66f5435e996e626d797", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ProblemSets/PS7-smm/Metrics3_HW7.jl", "max_issues_repo_name": "town0041/fall-2021", "max_issues_repo_head_hexsha": "d872c35c98342f8b5a28e66f5435e996e626d797", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ProblemSets/PS7-smm/Metrics3_HW7.jl", "max_forks_repo_name": "town0041/fall-2021", "max_forks_repo_head_hexsha": "d872c35c98342f8b5a28e66f5435e996e626d797", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8795180723, "max_line_length": 243, "alphanum_fraction": 0.5853149771, "num_tokens": 1610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.8705972751232808, "lm_q1q2_score": 0.8064375035304446}} {"text": "# psf-gauss.jl\n\nexport psf_gauss\n\n\"\"\"\n psf_gauss( ; ny, px, pz, fwhm_start, fwhm_end, fwhm, fwhm_x, fwhm_z, T)\n\nCreate depth-dependent Gaussian PSFs\nhaving specified full-width half-maximum (FHWM) values.\n\n# Options\n- 'ny::Int = 128'\n- 'px::Int = 11' (should be odd)\n- 'pz::Int = px' (should be odd)\n- 'fwhm_start::Real = 1'\n- 'fwhm_end::Real = 4'\n- 'fwhm::AbstractVector{<:Real} = LinRange(fwhm_start, fwhm_end, ny)'\n- 'fwhm_x::AbstractVector{<:Real} = fwhm,\n- 'fwhm_z::AbstractVector{<:Real} = fwhm_x'\n- 'T::DataType == Float32'\n\nReturned `psf` is `[px, pz, ny]` where each PSF sums to 1.\n\"\"\"\nfunction psf_gauss( ;\n ny::Int = 128,\n px::Int = 11,\n pz::Int = px,\n fwhm_start::Real = 1,\n fwhm_end::Real = 4,\n fwhm::AbstractVector{<:Real} = LinRange(fwhm_start, fwhm_end, ny),\n fwhm_x::AbstractVector{<:Real} = fwhm,\n fwhm_z::AbstractVector{<:Real} = fwhm_x,\n T::DataType = Float32,\n)\n isodd(px) || @warn(\"even px = $px ?\")\n isodd(pz) || @warn(\"even pz = $pz ?\")\n psf = zeros(T, px, pz, ny)\n\n rx = (-(px-1)÷2):((px-1)÷2)\n rz = (-(pz-1)÷2):((pz-1)÷2)\n for iy in 1:ny # depth-dependent blur\n psf[:,:,iy] = psf_gauss(rx, fwhm_x[iy]) * psf_gauss(rz, fwhm_z[iy])'\n end\n return psf\nend\n\nfunction psf_gauss(r::AbstractVector, fwhm::Real)\n if fwhm == 0\n any(==(0), r) || throw(\"must have some r=0 if fwhm=0\")\n return r .== 0 # Kronecker impulse\n end\n σ = fwhm / sqrt(log(256)) # FWHM to Gaussian σ\n psf = @. exp(-0.5 * abs2(r / σ))\n return psf / sum(psf)\nend\n", "meta": {"hexsha": "c2198d5f9b54d8818664539c658c5bad819c255b", "size": 1534, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/psf-gauss.jl", "max_stars_repo_name": "JeffFessler/SPECTrecon.jl", "max_stars_repo_head_hexsha": "2c32f4644608bdc4ecb6eecb36ea743fa58e9aac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-11-09T14:36:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-07T22:32:42.000Z", "max_issues_repo_path": "src/psf-gauss.jl", "max_issues_repo_name": "JeffFessler/SPECTrecon.jl", "max_issues_repo_head_hexsha": "2c32f4644608bdc4ecb6eecb36ea743fa58e9aac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2021-10-05T10:48:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-06T18:18:24.000Z", "max_forks_repo_path": "src/psf-gauss.jl", "max_forks_repo_name": "JeffFessler/SPECTrecon.jl", "max_forks_repo_head_hexsha": "2c32f4644608bdc4ecb6eecb36ea743fa58e9aac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-10-05T13:48:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-13T20:34:45.000Z", "avg_line_length": 27.3928571429, "max_line_length": 76, "alphanum_fraction": 0.593220339, "num_tokens": 625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250327, "lm_q2_score": 0.8705972751232809, "lm_q1q2_score": 0.806437499988055}} {"text": "export problem1\n\"\"\"\n problem1(N=1000)\n\n# Multiples of 3 and 5\n## Problem 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\"\"\"\nfunction problem1(N=1000)\n res = 0\n for i in 1:(N-1)\n (mod(i,3) == 0 || mod(i,5) == 0) && (res += i; true)\n end\n return res\nend\n", "meta": {"hexsha": "cae6078150e61fa11e4c82a5b8398435fd494cec", "size": 417, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problem1.jl", "max_stars_repo_name": "halleysfifthinc/ProjectEuler", "max_stars_repo_head_hexsha": "7134939e154bf52eb48f93f7da664bc50784b2f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/problem1.jl", "max_issues_repo_name": "halleysfifthinc/ProjectEuler", "max_issues_repo_head_hexsha": "7134939e154bf52eb48f93f7da664bc50784b2f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/problem1.jl", "max_forks_repo_name": "halleysfifthinc/ProjectEuler", "max_forks_repo_head_hexsha": "7134939e154bf52eb48f93f7da664bc50784b2f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.9473684211, "max_line_length": 129, "alphanum_fraction": 0.6163069544, "num_tokens": 152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037282594921, "lm_q2_score": 0.8705972667296309, "lm_q1q2_score": 0.8064374939841806}} {"text": "# \"Escaping the swirling vortex\"\n#\n# Nonautonomous ODE from pg 121 of Hale's ODE book, credited to\n# Markus, L. and H. Yamabe \"Global stability criteria for diferential systems\",\n# Osaka Math. J. 12 (1960), 305-317.\n#\n# A nonautonomous linear ODE of the form `du/dt = A(t)u`, with all the eigenvalues\n# of `A(t)` being complex with negative real part.\n#\n# However, origin is an unstable fixed point!\n#\n# The vector field visualization was based on \n# https://gist.github.com/Wikunia/4ca58b4c08da90978c0dcdee5b0c908a\n\nusing Javis\nusing Colors\nusing LinearAlgebra\n\n\"\"\"\n ground(args...)\n\nDefine the background and the initial \"foreground\" color.\n\"\"\"\nfunction ground(args...)\n background(\"black\")\n sethue(\"white\")\n return nothing\nend\n\n\"\"\"\ndudt(x, y, t)\n\nReturn the right hand side of the linear equation `u'=A(t)u`,\nwhere u=[x,y]. In this case, the equation takes the from\n x' = (-1 + 1.5cos(t)^2)x + (1 - 1.5cos(t)sin(t))y\n y' = (-1 - 1.5sin(t)cos(t))x + (-1 + 1.5sin(t)^2)y\n\"\"\"\nfunction dudt(x, y, t)\n ct = cos(t)\n st = sin(t)\n dxdt = (-1.0 + 1.5 * ct^2) * x + (1.0 - 1.5 * ct * st) * y\n dydt = (-1.0 - 1.5 * st * ct) * x + (-1.0 + 1.5 * st^2) * y\n return dxdt, dydt\nend\n\n\"\"\"\n jacobian!(mat, t)\n\nReturn (and modify in place) the linear part `A(t)` of the equation `u'=A(t)u`\n(see [`dudt`](@ref)). This is also seen as the Jacobian of `u -> f(t,u) = A(t)u`.\n\"\"\"\nfunction jacobian!(mat, t)\n ct = cos(t)\n st = sin(t)\n mat[1, 1] = -1.0 + 1.5 * ct^2\n mat[1, 2] = 1.0 - 1.5 * ct * st\n mat[2, 1] = -1.0 - 1.5 * st * ct\n mat[2, 2] = -1.0 + 1.5 * st^2\n return mat\nend\n\n\"\"\"\n solution!(u,t)\n\nReturn a particular solution of the equation `u'=A(t)u`, given by\n`u = exp(t/2) * [-cos(t), sin(t)] / 20.0` corresponding to the initial condition\n`u(0) = [-0.05, 0.0]`\n\"\"\"\nfunction solution!(u, t)\n et2 = exp(t / 2) / 20.0\n u[1] = -et2 * cos(t)\n u[2] = et2 * sin(t)\n return u\nend\n\n\"\"\"\n space_to_frame_coordinates(u, frm_scl)\n\nTransform a point in xy coordinates to the frame coordinates XY.\nThey are related according to `X = frm_scl * x` and `Y = - frm_scl * y`,\nfor a given scale factor `frm_scl`.\n\"\"\"\nspace_to_frame_coordinates(u, frm_scl) = frm_scl * Point(u[1], -u[2])\nspace_to_frame_coordinates(x, y, frm_scl) = space_to_frame_coordinates([x, y], frm_scl)\n\n\"\"\"\n ellipse_level_set!(u, t, mat, σ₁, σ₂, frm_scl)\n\nDraw a \"level-set\"-like ellipse associated with the solution at time `t`.\n\nFor a given time `t`, the solutions `w=w(s)` of the autonomous equation\n`dw(s)/ds = A(t)w(s)` spiral towards the origin, decreasing along the level\nsets of an elliptic paraboloid. This function computes and draws the ellipse\nlevel set containing the solution `u(t)`. Note, however, that `u=u(t)` is\nthe solution of the nonautonomous equation `du(t)/dt = A(t)u(t)` given\nby [`solution!`](@ref), which spirals away from the origin.\n\nThe ellipse is computed by finding the complex eigenvector `v=v(t)` of the\ncomplex eigenvalue `α + iβ` of `A(t)` and considering the real and invertible\nmatrix `P(t) = [Re(v(t)) Im(v(t))]` which transforms `A(t)` into its real\nJordan form `P(t)^-1 * A(t) P(t) = [α β, -β α]`. In this particular case, the\neigenvalues `α ± iβ` are time-independent. The ellipse is obtained from the\nSVD decomposition `P = UΣVᵗ`, where `Σ = diag(σ₁, σ₂)` is diagonal with\nnonnegative elements `σ₁ ≥ σ₂ ≥ 0`, and `U` and `V` are orthogonal matrices.\nIn general, all these terms may change in time, but in the particular\nexample we are considering, only `U=U(t)` and `V=V(t)` are time-dependent,\nwith `σ₁ > σ₂ > 0` being constant. The elements `σ₁` and `σ₂` are, precisely,\nthe semi-major and semi-minor axes of the ellipse associated with the level\nset of the elliptic paraboloid at level one. It determines the eccentricity\nof the ellipse. The orientation of the ellipse is given by the rotation\ndetermined by the orthogonal matrix `U=U(t)`.\n\nAt each time `t`, we find and draw the level set that contains the solution `u(t)`\nas follows. We rotate `u(t)` via `Uᵗ = inv(U)`, compute the semi-major\nand semi-minor axis of the ellipse that has the same level as `Uᵗu(t)`, compute\nthe foci of this ellipse, rotate the foci back to the right orientation by applying\nthe orthogonal matrix `U`, and then find the ellipse, in frame coordinates, that\ndefined by the foci, in frame coordinates, and passing by the solution `u(t)`, in\nframe coordinates.\n\"\"\"\nfunction ellipse_level_set!(u, t, mat, σ₁, σ₂, frm_scl)\n sethue(\"white\")\n jacobian!(mat, t)\n v = eigen(mat).vectors[:, 1]\n U = svd([real(v) imag(v)]).U\n x, y = transpose(U) * solution!(u, t)\n γ = sqrt(x^2 / σ₁^2 + y^2 / σ₂^2) # level\n σ̃₁ = γ * σ₁ # semi-major\n σ̃₂ = γ * σ₂ # semi-minor\n fd = sqrt(abs(σ̃₁^2 - σ̃₂^2)) # focal distance to the origin/center\n f = U * [fd, 0.0] # one focus point; the other is -f\n poly(\n ellipse(\n space_to_frame_coordinates(f, frm_scl), # focus in frame coordinates\n -space_to_frame_coordinates(f, frm_scl), # the other focus\n space_to_frame_coordinates(u, frm_scl), # ellipse/level containing u(t)\n ),\n :stroke,\n close = true,\n )\n return nothing\nend\n\n\"\"\"\n ball(p=O, size=4, color=\"red\")\n\nDraw a filled circle of size `size` and color `color` around the point `p`\n\"\"\"\nfunction ball(p = O, size = 4, color = \"red\")\n sethue(color)\n circle(p, size, :fill)\n return p\nend\n\n\"\"\"\n path!(points, pos, color)\n\nUpdate and draw the trail of the solution.\n\nAdd the point `pos` to the vector `points` containing the trail of the trajectory\nand draw the trail.\n\"\"\"\nfunction path!(points, pos, color)\n sethue(color)\n push!(points, pos) # add pos to points\n prettypoly(points) # draw dotted path with circles\n return nothing\nend\n\n\"\"\"\n ode_arrow(x, y, t, frm_scl, color_min, color_max)\n\nCreate one arrow at the base point `(x,y)` and arrow vector given by `dudt(x, y, t)`.\nThe arrow is properly scaled by the factor `frm_scl` and the orientation takes into\naccount that the vertical coordinate increases downwards. Depending on the magnitude\nof the vector field at that point, the color ranges from `color_min` to `color_max`.\n\"\"\"\nfunction ode_arrow(x, y, t, frm_scl, color_min, color_max)\n @JShape begin\n translate(space_to_frame_coordinates(x, y, frm_scl))\n dx, dy = dudt(x, y, t)\n delta_t = 0.1\n ξ = dx * delta_t\n η = dy * delta_t\n l = sqrt(ξ^2 + η^2)\n len_colors = 100\n color_range = range(color(color_min), stop = color(color_max), length = len_colors)\n idx = clamp(floor(Int, l * len_colors), 1, len_colors)\n sethue(color_range[idx])\n if ξ != 0 || η != 0\n arrow(\n O,\n space_to_frame_coordinates(ξ, η, frm_scl);\n linewidth = 2,\n arrowheadlength = 8,\n )\n end\n end x = x y = y t = t frm_scl = frm_scl\nend\n\n\"\"\"\n horizontal_grid_line(video, c, frm_scl)\n\nCreate an horizontal grid line at `y=c`\n\"\"\"\nfunction horizontal_grid_line(video, r, frm_scl)\n if r == 0\n setline(1.5)\n end\n sethue(\"gray\")\n line(Point(-video.width / 2, r * frm_scl), Point(video.width / 2, r * frm_scl), :stroke)\n return nothing\nend\n\n\"\"\"\n vertical_grid_line(video, c, frm_scl)\n\nCreate a vertical grid line at `x=c`.\n\"\"\"\nfunction vertical_grid_line(video, c, frm_scl)\n if c == 0\n setline(1.5)\n end\n sethue(\"gray\")\n line(\n Point(c * frm_scl, -video.height / 2),\n Point(c * frm_scl, video.height / 2),\n :stroke,\n )\n return nothing\nend\n\n\"\"\"\n animate()\n\nCreate the animation. 😃\n\"\"\"\nfunction animate()\n # initial setup\n vid = Video(500, 500)\n nframes = 200\n xgrid = -2.0:0.25:2.0 # grid for bars and arrow base points\n ygrid = -2.0:0.25:2.0 # grid for bars and arrow base points\n t₀, tf = 0.0, 5π / 2 # time interval for the simulation\n u = [0.0, 0.0] # dummy initizaliation of the solution vector\n solution!(u, t₀) # initial vector\n mat = zeros(2, 2) # dummy initialization of the jacobian\n jacobian!(mat, t₀) # jacobian at time t₀ \n v = eigen(mat).vectors[:, 1] # first eigenvector\n svd_P = svd([real(v) imag(v)]) # P = [real(v) imag(v)] => inv(P) * mat * P = [α β; -β α]\n σ₁, σ₂ = svd_P.S # the semi-major and semi-minor axes are constant in this problem\n t = t₀ # set t to initial time\n frm_scl = 120 # frame scale\n solution_trail = Point[] # initialize history vector for the solution path\n\n # objects\n ## set background for all frames\n Background(1:nframes, ground)\n ## grids\n [\n Object(1:nframes, (args...) -> horizontal_grid_line(args[1], x, frm_scl)) for\n x in xgrid\n ]\n [Object(1:nframes, (args...) -> vertical_grid_line(args[1], y, frm_scl)) for y in ygrid]\n ## vector field\n arrows = [\n Object(1:nframes, ode_arrow(x, y, t, frm_scl, \"yellow\", \"red\")) for x in xgrid,\n y in ygrid\n ]\n ## solution at time t\n sol_pos = Object(\n 1:nframes,\n (args...; t) -> ball(\n space_to_frame_coordinates(solution!(u, t), frm_scl),\n 6,\n \"lightskyblue\",\n ),\n )\n ## solution trail\n Object(1:nframes, (args...) -> path!(solution_trail, pos(sol_pos), \"lightskyblue\"))\n ## ellipse\n obj_ellipse =\n Object(1:nframes, (args...; t) -> ellipse_level_set!(u, t, mat, σ₁, σ₂, frm_scl))\n\n # animation\n ## update solution, vector field and ellipse\n ## rmk: animation of the solution trail is a byproduct of updating solution\n act!(sol_pos, Action(1:nframes, change(:t, t₀ => tf)))\n act!(arrows, Action(1:nframes, change(:t, t₀ => tf)))\n act!(obj_ellipse, Action(1:nframes, change(:t, t₀ => tf)))\n\n # rendering\n ## render and generate gif\n render(\n vid;\n framerate = 15,\n pathname = joinpath(@__DIR__, \"gifs/escaping_the_swirling_vortex.gif\"),\n )\n\n return nothing\nend\n\nanimate()\n", "meta": {"hexsha": "178bcd3aa8145b315d87572b43490891b64bb254", "size": 9967, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/escaping_the_swirling_vortex.jl", "max_stars_repo_name": "MisterBiggs/Javis.jl", "max_stars_repo_head_hexsha": "57816995d0ba730aa07ab503b2152d04917c5af2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 573, "max_stars_repo_stars_event_min_datetime": "2020-07-20T17:50:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-19T14:19:14.000Z", "max_issues_repo_path": "examples/escaping_the_swirling_vortex.jl", "max_issues_repo_name": "MisterBiggs/Javis.jl", "max_issues_repo_head_hexsha": "57816995d0ba730aa07ab503b2152d04917c5af2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 414, "max_issues_repo_issues_event_min_datetime": "2020-07-20T17:51:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-18T11:19:08.000Z", "max_forks_repo_path": "examples/escaping_the_swirling_vortex.jl", "max_forks_repo_name": "MisterBiggs/Javis.jl", "max_forks_repo_head_hexsha": "57816995d0ba730aa07ab503b2152d04917c5af2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 45, "max_forks_repo_forks_event_min_datetime": "2020-07-23T20:31:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-03T01:07:16.000Z", "avg_line_length": 32.7861842105, "max_line_length": 92, "alphanum_fraction": 0.6298785994, "num_tokens": 3121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250327, "lm_q2_score": 0.8705972566572503, "lm_q1q2_score": 0.8064374828829021}} {"text": "using LinearAlgebra\nusing Plots\n\nfunction get_mass2_mat(nu1_mass::Float16, nu2_mass::Float16)::Array\n \"\"\"Create a 2D mass-squared diagonal matrix\"\"\"\n ret_array::Array{Float16} = Diagonal([nu1_mass^2, nu2_mass^2])\n return ret_array\nend\n\nfunction get_mixing_matrix(mixing_angle::Float16, isdeg::Bool = true)::Array\n \"\"\"Create a 2D mixing/rotation matrix with a given angle\"\"\"\n if isdeg\n mixing_angle = deg2rad(mixing_angle)\n end\n mixing_mat::Array{Float16} = [\n +cos(mixing_angle) -sin(mixing_angle)\n +sin(mixing_angle) +cos(mixing_angle)\n ]\n return mixing_mat\nend\n\nfunction time_propagator_mat(\n energy_nu::Float16,\n time_step::Float16,\n delta_mat::Array{Float16}\n)::Array{ComplexF16}\n \"\"\"Calculate the time propagator. Due to a bug in Julia, complex \n matrix arguments for the exponential function are not supported. \n So instead, I use the Euler relation instead.\n \"\"\"\n exp_arg::Array{ComplexF16} = time_step / (2.0 * energy_nu) * delta_mat\n exp_mat::Array{ComplexF16} = cos(exp_arg) + (0 + 1im) * sin(exp_arg)\n return exp_mat\nend\n\n\nfunction schrodingerODE()\n \"\"\"Run a 2D toy example of neutrino oscillations\"\"\"\n\n # Define scalars\n nu1_mass::Float16 = 1.0\n nu2_mass::Float16 = 2.0\n mixing_angle_deg::Float16 = 40\n time_steps::Int = 100\n time_step_size::Float16 = 0.01\n energy_nu::Float16 = 10.0\n\n # Define physics matrices\n mass2_mat::Array{Float16} = get_mass2_mat(nu1_mass, nu2_mass)\n mixing_mat::Array{Float16} = get_mixing_matrix(mixing_angle_deg, true)\n delta_mat::Array{Float16} = transpose(conj(mixing_mat)) * mass2_mat * mixing_mat\n\n # Store results in arrays\n # initial state is nu1 = 100%, nu2 = 0%\n initial_state_vector::Vector{ComplexF16} = Vector([1 + 0im, 0 + 0im])\n state_vectors::Array{ComplexF16} = zeros(ComplexF16, (2, time_steps))\n state_fractions::Array{Float16} = zeros(Float16, (2, time_steps))\n state_vectors[:, 1] = initial_state_vector\n state_fractions[:, 1] = Array([1.0; 0.0])\n\n # Evaluate the wave-function over time and save the state over each step\n for step_index::Int = 2:time_steps\n previous_step_index::Int = step_index - 1\n previous_state_vector::Array{ComplexF16} = state_vectors[:, previous_step_index]\n time_step::Float16 = (step_index - 1) * time_step_size\n time_propagator::Array{ComplexF16} =\n time_propagator_mat(energy_nu, time_step, delta_mat)\n new_state::Vector{ComplexF16} = time_propagator * previous_state_vector\n new_state_fraction::Vector{Float16} =\n Array([abs2(new_state[1]); abs2(new_state[2])])\n state_vectors[:, step_index] = new_state\n state_fractions[:, step_index] = new_state_fraction\n end\n\n # Plot the results\n Plots.pyplot()\n fig = plot(1:time_steps, state_fractions[1, :], label=\"\\$\\\\nu_1\\$\")\n plot!(1:time_steps, state_fractions[2, :], label=\"\\$\\\\nu_2\\$\")\n xlabel!(\"Time step\")\n ylabel!(\"Wave Function Component\")\n title!(\"Flavor Oscillations\")\n @show fig\nend\n\nschrodingerODE()", "meta": {"hexsha": "403302e00a3474a7817d2ffffd888e7a86f1e912", "size": 3100, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "schrodingerODE.jl", "max_stars_repo_name": "hoganman/NeutrinoOscillations2D", "max_stars_repo_head_hexsha": "60a795bfca54e8716034b40b7b0c1470ab665427", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "schrodingerODE.jl", "max_issues_repo_name": "hoganman/NeutrinoOscillations2D", "max_issues_repo_head_hexsha": "60a795bfca54e8716034b40b7b0c1470ab665427", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "schrodingerODE.jl", "max_forks_repo_name": "hoganman/NeutrinoOscillations2D", "max_forks_repo_head_hexsha": "60a795bfca54e8716034b40b7b0c1470ab665427", "max_forks_repo_licenses": ["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.4705882353, "max_line_length": 88, "alphanum_fraction": 0.684516129, "num_tokens": 916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750373915658, "lm_q2_score": 0.84594244507642, "lm_q1q2_score": 0.8064158159613369}} {"text": "\"\"\"\nApproximates the area under the curve using the trapezoidal rule\nArguments:\n - f: function for the\n - x_start: starting value for x\n - x_end: ending value for x\n - steps: steps taken while integrating.\n\"\"\"\n\nfunction trapazoidal_area(f, x_start, x_end, steps)\n\tx1 = x_start\n\tfx1 = f(x_start)\n\tarea = 0.0\n\n\tfor _ in 1:steps\n\t\tx2 = ((x_end - x_start) / steps) + x1\n\t\tfx2 = f(x2)\n\t\tarea += abs(fx2 + fx1) * (x2 - x1) / 2\n\t\tx1 = x2\n\t\tfx1 = fx2\n\tend\n\n\treturn area\nend\n", "meta": {"hexsha": "c7cefa41f4b6e17364566307159e3ebbccbf34db", "size": 466, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/area_under_curve.jl", "max_stars_repo_name": "madisonestabrook/Julia", "max_stars_repo_head_hexsha": "799508e2b8a3087bdd7fb4d2a23a2ab4788ea854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/math/area_under_curve.jl", "max_issues_repo_name": "madisonestabrook/Julia", "max_issues_repo_head_hexsha": "799508e2b8a3087bdd7fb4d2a23a2ab4788ea854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/math/area_under_curve.jl", "max_forks_repo_name": "madisonestabrook/Julia", "max_forks_repo_head_hexsha": "799508e2b8a3087bdd7fb4d2a23a2ab4788ea854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.64, "max_line_length": 64, "alphanum_fraction": 0.6545064378, "num_tokens": 168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750387190131, "lm_q2_score": 0.8459424334245617, "lm_q1q2_score": 0.8064158059768551}} {"text": "#\n#--------------------------------------#\nexport derivMat\n#--------------------------------------#\n\"\"\"\n Compute derivative matrix for lagrange\n interpolants on points [x]\n\"\"\"\nfunction derivMat(x)\n \nn = length(x)\n\na = ones(1,n)\nfor 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\nend\na = 1 ./ a # Barycentric weights\n\n# diagonal elements\nD = x .- x'\nfor i=1:n D[i,i] = 1. end\nD = 1 ./ D\nfor i=1:n\n D[i,i] = 0.\n D[i,i] = sum(D[i,:])\nend\n\n# off-diagonal elements\nfor j=1:n for i=1:n\n if(i!=j) D[i,j] = a[j] / (a[i]*(x[i]-x[j])) end\nend end\n\nreturn D\nend\n#--------------------------------------#\n", "meta": {"hexsha": "20d9e9f570765d007a506fe9abf868afeb0c1d7d", "size": 651, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/derivMat.jl", "max_stars_repo_name": "vpuri3/SpectralElements.jl", "max_stars_repo_head_hexsha": "276bdd7fdfc67796fef64a20e0411044da70928b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-07-29T01:52:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-29T02:05:59.000Z", "max_issues_repo_path": "src/derivMat.jl", "max_issues_repo_name": "vpuri3/SpectralElements.jl", "max_issues_repo_head_hexsha": "276bdd7fdfc67796fef64a20e0411044da70928b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2021-08-16T19:39:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-17T16:52:52.000Z", "max_forks_repo_path": "src/derivMat.jl", "max_forks_repo_name": "vpuri3/SEM.jl", "max_forks_repo_head_hexsha": "128b7a8aa48cdc8a981c3668199e856240c04e13", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.5945945946, "max_line_length": 51, "alphanum_fraction": 0.4423963134, "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122684798184, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.8063951173238996}} {"text": "using LinearAlgebra\n\n# Parameters in regression model \nbeta = [148.73, -18.85]; v = 54.40; \ny_hat(x) = x'*beta + v;\n# Evaluate regression model prediction \nx = [0.846, 1]; y = 115;\ny_hat(x), y # (161.37557999999999, 115)\nx = [1.324,2]; y = 234.50;\ny_hat(x), y\n\nusing VMLS # see below to install package\nD = house_sales_data();\nprice = D[\"price\"]\narea = D[\"area\"]\nbeds = D[\"beds\"]\n\nv = 54.4017;\nbeta = [ 147.7251, -18.8534 ];\npredicted = v .+ beta[1] * area + beta[2] * beds;\n\nusing Plots\nscatter(price, predicted, lims = (0,800));\nplot!([0, 800], [0, 800], linestyle = :dash);\n# make axes equal and add labels\nplot!(xlims = (0,800), ylims = (0,800), size = (500,500));\nplot!(xlabel = \"Actual price\", ylabel = \"Predicted price\");\n\n# Install VMLS to JuliaBox\n# Go to git, enter 'https:////github.com/VMLS-book/VMLS.jl.git'\n# Go to package manager, add 'VMLS'\n# Wait up to 15 minutes (for package build)\n\n# --OR--\n\n# Install VMLS to Julia runtime (local machine)\n# Go to Julia prompt, type ']' to open package manager\n# Get library from 'pkg>' prompt \n# type 'add https:////github.com/VMLS-book/VMLS.jl'\n# 'ctrl + C' to exit pakage manager prompt\n\n\n\n\n", "meta": {"hexsha": "40f32e99d7293a5b47267444a8ebb5586ce82954", "size": 1196, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "2_Linear_Functions/3_Regression_Model.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": "2_Linear_Functions/3_Regression_Model.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": "2_Linear_Functions/3_Regression_Model.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": 26.5777777778, "max_line_length": 63, "alphanum_fraction": 0.6220735786, "num_tokens": 390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122744874229, "lm_q2_score": 0.8418256412990658, "lm_q1q2_score": 0.8063951147786215}} {"text": "### A Pluto.jl notebook ###\n# v0.14.5\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 32504772-aaef-11eb-0bb0-0b145c5102db\nbegin\n\tusing Base.Threads\n\tusing Random\t\n\tusing Distributions\n\tusing SpecialFunctions\n\tusing Plots\n\tusing StatsPlots\n\tusing Query\n\tusing DataFrames\n\tusing CSV\nend\n\n# ╔═╡ ec00bfbc-4889-4fbc-9f5b-ce19b361f1fe\nmd\"\"\"\n## Estimating π in Buffon's Needle Problem\nFirst we estimate π many times by simulating Buffon's needle problem. This is repeated for a variety of experimental setups, varying the number of needles thrown (`n_throws`) and the needle length (`needle_length`). For simplicity, we'll just assume that the strip height (`strip_height`) is one - so you can think of the needle length as the ratio of the needle length to the strip height.\n\"\"\"\n\n# ╔═╡ 7e54380a-fada-40c0-ad20-5795075f2c41\nfunction needle_crossing_fraction(strip_height, needle_length, n_throws)\n\tD = rand(Uniform(0, strip_height/2), n_throws)\n\tθ = rand(Uniform(0, π), n_throws)\n\t\n\tcrosses_line = (needle_length / 2) * sin.(θ) .> D\n\tn_crossings = sum(crosses_line)\n\t\n\treturn n_crossings / n_throws\nend\n\n# ╔═╡ 3de8036e-723b-4805-9384-f87a6aaae5ba\nfunction buffon_pi_estimate(strip_height, needle_length, n_throws)\n\tp_hat = needle_crossing_fraction(strip_height, needle_length, n_throws)\n\t\n\treturn 2 * (needle_length / strip_height) / p_hat\nend\n\n# ╔═╡ 9e97dbc2-7d87-40cd-92a8-e892e485d9e6\nbuffon_pi_estimate(1, 0.1, 10^7)\n\n# ╔═╡ 7838810d-63c0-4de6-8ec7-97a4b65750e2\nfunction estimate_pi_repeatedly(\n\t\tn_needle_lengths = 10,\n\t\tn_repetitions = 100,\n\t\tn_throws_max_exp = 6\n\t)\n\t\n\t# Set up experiment, arrange data so that (when multi-threading) the\n\t# processors will be running similar problems at similar times \n\tdf = DataFrame(\n\t\t[(needle_length, n_throws, repetition)\n\t\t\tfor n_throws = [10^k for k = 2:n_throws_max_exp] \n\t\t\tfor needle_length = [k/n_needle_lengths for k = 1:n_needle_lengths] \n\t\t\tfor repetition = 1:n_repetitions]\n\t)\n\trename!(df, [\"needle_length\", \"n_throws\", \"repetition\"])\n\t\n\t# Number of experiments to run\n\tn_experiments = nrow(df)\n\t\n\t# Run multi-threaded experiments to estimate π\n\tpi_estimates = zeros(n_experiments)\t\n\t\n\tThreads.@threads for i ∈ 1:n_experiments\n\t\tneedle_length = df[i, :needle_length]\n\t\tn_throws = df[i, :n_throws]\t\t\t\t\n\t\tpi_estimates[i] = buffon_pi_estimate(1, needle_length, n_throws)\n\tend\t\t\t\t\t\t\t\t\t\n\t\n\tdf.pi_estimate = pi_estimates\n\t\n\t# Evaluate error\n\tdf.error = df.pi_estimate .- π\t\n\tdf.abs_error = abs.(df.error)\n\t\n\treturn df\nend\n\n# ╔═╡ bbd5cc5f-80f2-405f-aa71-da0022d74863\npi_estimate_results = estimate_pi_repeatedly(10, 1000, 6)\n\n# ╔═╡ 62e8e764-516a-452a-8f7f-806bf696b126\nCSV.write(\"pi_estimate_results.csv\", pi_estimate_results)\n\n# ╔═╡ 27eabc0d-b40f-448f-90ce-301871f3b63b\nmd\"\"\"\n## Analyzing the Error in Estimating π\nIn this section, we take a look at the error committed in estimating π in the various experiments performed above. In particular, we take a look at how the error depends upon the number of needles thrown and how long our needles are. In particular, we take a look at the median error and 95ᵗʰ percentile of our experiments.\n\nIn addition, I have computed the theoretical error \"bounds\" (note this bound is only asymptotically correct / hence more of a guide than a hard and fast \"bound\"), for 50% and 95% confidence bounds. I didn't bother to plot the actual vs theoretical comparison however, since they're not hard and fast bounds.\n\nI have (however) plotted the observed median and 95ᵗʰ percentile observed error across the experimental set-ups. \n\"\"\"\n\n# ╔═╡ 6c17402b-8905-463c-aa0f-3a4905877944\nmd\"\"\"\n\n### Analytical Asymptotic Error Bound\nElsewhere, I computed that the following bound holds asymptotically with probability $$P = 1-\\alpha$$ (here, $$\\Phi^{-1}$$ denotes the probit function, $$h$$ the strip width, $$\\ell$$ the needle length, and $$\\hat{\\pi}$$ the estimate from throwing needles):\n\n$$\\vert \\hat{\\pi} - \\pi \\vert \\lessapprox \\pi \\sqrt{\\frac{\\pi}{2} - \\frac{\\ell}{h}} \\cdot \\Phi^{-1}\\left(1 - \\frac{\\alpha}{2}\\right)\\cdot \\sqrt{\\frac{h}{\\ell}} \\cdot \\frac{1}{\\sqrt{n_\\text{throws}}}.$$\n\nWe will compare against this below.\n\"\"\"\n\n# ╔═╡ d75c194b-20df-4ea8-a415-7c44167271d4\nfunction probit(p)\n\tsqrt(2) * erfinv(2*p - 1)\nend\n\n# ╔═╡ 60f54651-6926-4248-aa40-f135d01e4347\nfunction error_bound(needle_length, strip_width, prob_in_interval, n_throws)\n\treturn π * √(π/2 - (needle_length/ strip_width)) * \n\t probit(1 - prob_in_interval/2) *\n\t\t √(strip_width / needle_length) * \n\t 1/√(n_throws)\nend\n\n# ╔═╡ 3c1ade5a-7a15-4585-8cf2-48b6c84813f7\nmd\"\"\"\nThe following table shows empirical error bounds, compared against the theoretical approximate bounds.\n\"\"\"\n\n# ╔═╡ a3304dce-9e87-444d-ab5d-c0f3fffea134\nbegin\n\tpi_error_analysis = combine(\n\t\tgroupby(pi_estimate_results, [:needle_length, :n_throws]), \n\t\t:abs_error => median,\t\n\t\t:abs_error => (t -> quantile(t, 0.95))\n\t)\n\t\n\trename!(pi_error_analysis, \"abs_error_function\" => \"abs_error_95_pctile\")\n\t\t\n\ttransform!(pi_error_analysis, :, [:needle_length, :n_throws] => \n ((a,b) -> error_bound.(a, 1, 0.5, b)) => \n\t\t :abs_error_median_theoretical)\n\t\n\ttransform!(pi_error_analysis, :, [:needle_length, :n_throws] => \n ((a,b) -> error_bound.(a, 1, 0.05, b)) => \n\t\t :abs_error_95_pctile_theoretical)\n\t\n\tpi_error_analysis\nend\n\n# ╔═╡ 902e5796-6741-4c4a-9856-a43006c326ab\nCSV.write(\"pi_error_analysis.csv\", pi_error_analysis)\n\n# ╔═╡ 7014ffed-1bed-41aa-95ef-ecdcd366b510\nmd\"\"\"\nThe following plot shows the empirical median absolute error, compared against the theoretical approximate 50% percent confident bound on error.\n\"\"\"\n\n# ╔═╡ ab93cbb3-6b82-48d7-8fdd-4c91f300d33c\nbegin\n\tplot_ref_50th = pi_error_analysis |>\n\t@df scatter(\n\t\t:n_throws,\n\t\t:abs_error_median,\n\t\tgroup=:needle_length,\n\t\tcolor=reshape(palette(:auto)[1:10], (1, 10)),\t\n\t\tlabel=reshape([\"\" for i =1:10], (1,10)),\t\t\n\t\t# ugly hack to hide junk entry:\n\t\txaxis=((75, 10^6+5*10^5), :log),\n\t\tyaxis=:log\n\t)\n\t\n\tpi_error_analysis |>\n\t@df plot!(\n\t\t:n_throws,\n\t\t:abs_error_median_theoretical,\n\t\tgroup=:needle_length,\n\t\t#legend=false\n\t\tcolor=reshape(palette(:auto)[1:10], (1, 10)),\n\t\tylabel=\"Median of Absolute Error\",\n\t\txlabel=\"Number of Needles Thrown\",\n\t\ttitle=\"Median Absolute Error vs Number of Needles Thrown\\nby Needle Length\",\n\t\ttitlefontsize=10,\t\t\t\t\n\t\tlegendtitle=\"Needle Length\",\n\t\tlegendtitlefontsize=8,\n\t\tlegend = :outertopright\n\t\t\n\t)\n\t\n\t# junk data to get legend entries\n plot!([], [], label = \" \", color = \"white\")\n plot!([], [], label = \"Theoretical\", color = \"black\")\n scatter!([10], [1], label = \"Observed\", color=\"black\")\t\n\t\n\t\n\t# save figure\n\tsavefig(plot_ref_50th, \"error_plot_50pctile.svg\")\n\t\n\t# display result in Pluto\n\tplot_ref_50th\nend\n\n# ╔═╡ ed32a816-05d8-46f2-b3fe-6a9c5a2f2636\nmd\"\"\"\nThe following plot shows the empirical 95ᵗʰ percentile of absolute error, compared against the theoretical 95% confident bound on error.\n\"\"\"\n\n# ╔═╡ a5f76835-73ce-4fa9-a0b0-e63f1f8bff69\nbegin\n\tplot_ref_95th = pi_error_analysis |>\n\t@df scatter(\n\t\t:n_throws,\n\t\t:abs_error_95_pctile,\n\t\tgroup=:needle_length,\n\t\tcolor=reshape(palette(:auto)[1:10], (1, 10)),\t\n\t\tlabel=reshape([\"\" for i =1:10], (1,10)),\t\t\n\t\t# ugly hack to hide junk entry:\n\t\txaxis=((75, 10^6+5*10^5), :log),\n\t\tyaxis=:log\n\t)\n\t\n\tpi_error_analysis |>\n\t@df plot!(\n\t\t:n_throws,\n\t\t:abs_error_95_pctile_theoretical,\n\t\tgroup=:needle_length,\n\t\t#legend=false\n\t\tcolor=reshape(palette(:auto)[1:10], (1, 10)),\n\t\tylabel=\"95ᵗʰ Percentile of Absolute Error\",\n\t\txlabel=\"Number of Needles Thrown\",\n\t\ttitle=\"95ᵗʰ Percentile of Absolute Error vs Number of Needles Thrown\\nby Needle Length\",\n\t\ttitlefontsize=10,\t\t\t\t\n\t\tlegendtitle=\"Needle Length\",\n\t\tlegendtitlefontsize=8,\n\t\tlegend = :outertopright\n\t\t\n\t)\n\t\n\t# junk data to get legend entries\n plot!([], [], label = \" \", color = \"white\")\n plot!([], [], label = \"Theoretical\", color = \"black\")\n scatter!([10], [1], label = \"Observed\", color=\"black\")\t\n\t\n\t\n\t# save figure\n\tsavefig(plot_ref_95th, \"error_plot_95pctile.svg\")\n\t\n\t# display result in Pluto\n\tplot_ref_95th\nend\n\n# ╔═╡ bde8330a-fb98-4950-ad92-c82e2e5e65c6\nmd\"\"\"\n### Plotting π Estimates when `needle_length = 1.0`\n\nSince we have a lot of estimates for π, but have only looked at the error we made when estimating them (as opposed to the estimates themselves), I figure I should at least take a look at the estimates in one of the experimental settings.\n\"\"\"\n\n# ╔═╡ d82dd81c-bf96-443e-8b5a-aa75b21e037e\nbegin\n\tdf_tmp = filter(row -> row[:needle_length] == 1.0, pi_estimate_results)\n\t\n\tplot_ref_len_1 = df_tmp |>\n\t@df dotplot(\n\t\tstring.(:n_throws),\n\t\t:pi_estimate,\n\t\tylabel=\"Estimate for π\",\n\t\txlabel=\"Number of Needles Thrown\",\n\t\ttitle=\"Distribution of π Estimates by Number of Needles Thrown\\nFor Needle Length=1.0\",\n\t\ttitlefontsize=11,\t\t\t\t\n\t\tmarker=(:lightgrey, stroke(0))\t\t\n\t)\n\t\n\tplot_ref_len_1 = df_tmp |>\n\t@df boxplot!(\n\t\tstring.(:n_throws),\n\t\t:pi_estimate,\n\t\tmarker=(:black, stroke(0)),\n\t\tfillcolor=:lightblue,\n\t\tfillalpha=0.75,\n\t\tlegend=false\n\t)\n\t\n\t# save figure\n\tsavefig(plot_ref_len_1, \"pi_estimate_boxplot.svg\")\n\t\n\t# show figure\n\tplot_ref_len_1\nend\n\n# ╔═╡ b29276d8-e541-4221-b81f-fde2600a8979\nmd\"\"\"\nThe following table summarizes the results:\n\"\"\"\n\n# ╔═╡ 312ba44a-dcad-4b18-b130-3439625f78f3\nbegin \n\tpi_rslt = combine(\n\t\tgroupby(pi_estimate_results, [:needle_length, :n_throws]), \t\t\n\t\t:pi_estimate => mean => :mean,\n\t\t:pi_estimate => minimum => :min,\n\t\t:pi_estimate => (t -> quantile(t, 0.25)) => :pctile_25,\t\t\n\t\t:pi_estimate => median => :median,\n\t\t:pi_estimate => (t -> quantile(t, 0.75)) => :pctile_75,\t\t\n\t\t:pi_estimate => maximum => :max,\n\t) \nend\n\n# ╔═╡ b847e348-4afd-4e63-b91b-84152cbb89b7\nmd\"\"\"\nLet's take a look at the `needle_length = 1` case.\n\"\"\"\n\n# ╔═╡ e2042def-bf39-4b95-bdc9-1d46db79c88e\n# show an interesting subset\nfilter(row -> row[:needle_length] == 1.0, pi_rslt)\n\n# ╔═╡ 9b3f7234-9978-43bb-9af9-55bdf967ed62\n# save to file\nCSV.write(\"pi_rslt.csv\", pi_rslt)\n\n# ╔═╡ 489c446d-f942-4703-b0d7-7a29c98ce4d5\nmd\"\"\"\n## How Many Needles Do I Need to Throw?\nFinally, I will use the theoretical 95ᵗʰ percentile error bound to estimate how many needles one needs to throw in order to achieve a specified decimal digit accuracy (with 95% confidence) in estimating π. \n\"\"\"\n\n# ╔═╡ aeb3c67c-5248-4312-9930-852259f43de9\nfunction n_throws_required(desired_accuracy, needle_length, strip_width,\n\t\t prob_in_interval)\n\t\n\tp = 1 - prob_in_interval\n\t\n\tn_throws = π^2 * (π/2 - (needle_length / strip_width)) * \n\t probit(1 - p/2)^2 *\n\t\t (strip_width / needle_length) * \n\t (1 / desired_accuracy^2)\n\t\n\treturn n_throws\nend\n\n# ╔═╡ b988a3e4-1d15-4abf-8b5a-fc8a2e119c7e\nbegin \t\n\tdf_required_analytical = DataFrame([\n\t (decimal_digits, needle_length, n_throws_required(1/10^decimal_digits, needle_length, 1, 0.95))\n\t\t\tfor decimal_digits = [1, 2, 3, 4, 5, 6]\n\t\t\tfor needle_length = [k/10 for k = 1:10]\n\t])\n\t\n\trename!(df_required_analytical, [\"decimal_digits\", \"needle_length\", \"throws_required\"])\nend\t\n\n# ╔═╡ 55234b47-1b22-4fab-a449-c43b2976b7fa\nmd\"\"\"\nLet's take a look at the `needle_length = 1` case.\n\"\"\"\n\n# ╔═╡ 9668af8a-ecea-4c11-9c3a-f32b416f02a9\n# show an interesting subset\nfilter(row -> row[:needle_length] == 1.0, df_required_analytical)\n\n# ╔═╡ fd88ca22-a191-4e92-900f-c86c7f516641\nCSV.write(\n\t\"required_throws_analytical_solution.csv\",\n\tdf_required_analytical\n)\n\n# ╔═╡ 70b92add-4a58-4181-8409-c896b57665f9\nbegin\n\tplot_ref_throws_req = df_required_analytical |>\n\t@df plot(\n\t\t:decimal_digits,\n\t\t:throws_required,\n\t\tgroup=:needle_length,\t\t\n\t\tyaxis=:log,\n\t\tylabel=\"Number of Throws Required\",\n\t\txlabel=\"Number of Decimal Digits\",\n\t\ttitle=\"Number of Throws Required to Achieve Specified\\nDecimal Digit Accuracy with 95% Confidence\\nby Needle Length\",\n\t\ttitlefontsize=11,\t\t\t\t\t\t\n\t\tlegendtitle=\"Needle Length\",\n\t\tlegendtitlefontsize=8,\n\t\tlegend = :outertopright\n\t)\n\t\n\t# save figure\n\tsavefig(plot_ref_throws_req, \"throws_required_95pctile.svg\")\n\t\n\t# display plot\n\tplot_ref_throws_req\nend\n\n# ╔═╡ Cell order:\n# ╟─ec00bfbc-4889-4fbc-9f5b-ce19b361f1fe\n# ╠═7e54380a-fada-40c0-ad20-5795075f2c41\n# ╠═3de8036e-723b-4805-9384-f87a6aaae5ba\n# ╠═9e97dbc2-7d87-40cd-92a8-e892e485d9e6\n# ╠═7838810d-63c0-4de6-8ec7-97a4b65750e2\n# ╠═bbd5cc5f-80f2-405f-aa71-da0022d74863\n# ╠═62e8e764-516a-452a-8f7f-806bf696b126\n# ╟─27eabc0d-b40f-448f-90ce-301871f3b63b\n# ╟─6c17402b-8905-463c-aa0f-3a4905877944\n# ╠═d75c194b-20df-4ea8-a415-7c44167271d4\n# ╠═60f54651-6926-4248-aa40-f135d01e4347\n# ╟─3c1ade5a-7a15-4585-8cf2-48b6c84813f7\n# ╠═a3304dce-9e87-444d-ab5d-c0f3fffea134\n# ╠═902e5796-6741-4c4a-9856-a43006c326ab\n# ╟─7014ffed-1bed-41aa-95ef-ecdcd366b510\n# ╠═ab93cbb3-6b82-48d7-8fdd-4c91f300d33c\n# ╟─ed32a816-05d8-46f2-b3fe-6a9c5a2f2636\n# ╠═a5f76835-73ce-4fa9-a0b0-e63f1f8bff69\n# ╟─bde8330a-fb98-4950-ad92-c82e2e5e65c6\n# ╠═d82dd81c-bf96-443e-8b5a-aa75b21e037e\n# ╟─b29276d8-e541-4221-b81f-fde2600a8979\n# ╠═312ba44a-dcad-4b18-b130-3439625f78f3\n# ╟─b847e348-4afd-4e63-b91b-84152cbb89b7\n# ╠═e2042def-bf39-4b95-bdc9-1d46db79c88e\n# ╠═9b3f7234-9978-43bb-9af9-55bdf967ed62\n# ╟─489c446d-f942-4703-b0d7-7a29c98ce4d5\n# ╠═aeb3c67c-5248-4312-9930-852259f43de9\n# ╠═b988a3e4-1d15-4abf-8b5a-fc8a2e119c7e\n# ╟─55234b47-1b22-4fab-a449-c43b2976b7fa\n# ╠═9668af8a-ecea-4c11-9c3a-f32b416f02a9\n# ╠═fd88ca22-a191-4e92-900f-c86c7f516641\n# ╠═70b92add-4a58-4181-8409-c896b57665f9\n# ╠═32504772-aaef-11eb-0bb0-0b145c5102db\n", "meta": {"hexsha": "dfe6134229a65629904f7e6390f4f818c1d79862", "size": 13530, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "assets/posts/20210628_HappyTauDay/buffon.jl", "max_stars_repo_name": "pkepley/pkepley.github.io", "max_stars_repo_head_hexsha": "e507941ebff889f8c5c6b5e3a5b294a0886cf86f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "assets/posts/20210628_HappyTauDay/buffon.jl", "max_issues_repo_name": "pkepley/pkepley.github.io", "max_issues_repo_head_hexsha": "e507941ebff889f8c5c6b5e3a5b294a0886cf86f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assets/posts/20210628_HappyTauDay/buffon.jl", "max_forks_repo_name": "pkepley/pkepley.github.io", "max_forks_repo_head_hexsha": "e507941ebff889f8c5c6b5e3a5b294a0886cf86f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7605633803, "max_line_length": 390, "alphanum_fraction": 0.7032520325, "num_tokens": 4989, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782736, "lm_q2_score": 0.9073122301325987, "lm_q1q2_score": 0.8063817336670144}} {"text": "multsum(n, lim) = (occ = div(lim-1, n); div(n*occ*(occ+1), 2))\nmultsum(n, m, lim) = multsum(n, lim) + multsum(m, lim) - multsum(lcm(n,m), lim)\n", "meta": {"hexsha": "5d89a6b64d75dbd03561c3f73a9b5f6fc38121dd", "size": 143, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/sum-multiples-of-3-and-5-2.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/sum-multiples-of-3-and-5-2.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/sum-multiples-of-3-and-5-2.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.6666666667, "max_line_length": 79, "alphanum_fraction": 0.5804195804, "num_tokens": 62, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.962673111584966, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.8063542164277426}} {"text": "using LinearAlgebra\nusing PyPlot\nfunction linesegment_intersect(p1, p2, q1, q2, δ)\n A = [p2-p1 q1-q2]\n b = q1-p1\n if rank(A) == 2\n st = A \\ b\n if all(-δ .≤ st .≤ 1 + δ)\n pintersect = p1 + st[1] * (p2 - p1)\n return true, pintersect\n else\n return false, nothing\n end\n else\n # Warning: parallel lines, should check if they actually overlap\n return false, nothing\n end\nend\n\n# Example: n random lines, find and plot all intersections\nn = 10\nlines = [ [rand(2), rand(2)] for i = 1:n ]\n\n# Plot all lines\nfor line in lines\n plot([line[1][1], line[2][1]], [line[1][2], line[2][2]])\nend\n\n# Find all intersections - note that we only consider j>i to avoid checking\n# the same 2 line-segments twice\nfor i = 1:n\n for j = i+1:n\n isect, pq = linesegment_intersect(lines[i][1], lines[i][2], lines[j][1], lines[j][2], 0)\n if isect\n plot(pq[1], pq[2], \"o\")\n end\n end\nend\n\naxis(\"equal\"); grid(true);\n\n\n", "meta": {"hexsha": "b4b5f0a8420307f91620b7673a1b06a2d708a7cc", "size": 1014, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "textbook/_build/jupyter_execute/content/Computational_Geometry/Line_Segment_Interactions.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/Computational_Geometry/Line_Segment_Interactions.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/Computational_Geometry/Line_Segment_Interactions.jl", "max_forks_repo_name": "NoseKnowsAll/NoseKnowsAll.github.io", "max_forks_repo_head_hexsha": "b2cff3e33cc2087770fb4aecb38b7925ad8d6e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5813953488, "max_line_length": 96, "alphanum_fraction": 0.5641025641, "num_tokens": 332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731147976794, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.8063542152165836}} {"text": "export ladder_graph\n\n\n\"\"\"\n ladder_adj(w1, w2)\nreturn true if words `w1` and `w2` have the same length\nand differ in exactly one location.\n\"\"\"\nfunction ladder_adj(w1::String, w2::String)::Bool\n if length(w1) != length(w2)\n return false\n end\n c = collect(w1) .!= collect(w2)\n return sum(c) == 1\nend\n\n\"\"\"\n ladder_graph(S::Set{String}, len::Int=0, trim::Bool=false)\n\nCreate a graph whose vertices are words in which two words are adjacent if they differ\nin exactly one letter. \n\nWe use only words of length `len`, unless this is set to `0`\nin which case all words are used.\n\nIf `trim` is set to `true` then vertices of degree zero are deleted.\n\"\"\"\nfunction ladder_graph(S::Set{String}, len::Int = 0, trim::Bool = false)::SimpleGraph{String}\n G = _bare_graph(S, len)\n\n PM = Progress(NV(G))\n\n for v ∈ G.V\n next!(PM)\n nv = length(v)\n for i ∈ 1:nv\n for c ∈ _A2Z\n w = v[1:i-1] * c * v[i+1:nv]\n if w ∈ G.V\n add!(G, v, w)\n end\n end\n end\n end\n\n # remove vertices of degree zero (if trim is true)\n if trim\n for w in G.V\n if deg(G, w) == 0\n delete!(G, w)\n end\n end\n end\n\n if len < 1\n name(G, \"Ladder Graph on all words\")\n else\n name(G, \"Ladder Graph on $len-letter words\")\n end\n\n return G\n\n\n\n\nend\n", "meta": {"hexsha": "394f0c89fa47a36d8a5affba50112b8037f7b4fb", "size": 1420, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ladder_graph.jl", "max_stars_repo_name": "scheinerman/WordGraphs.jl", "max_stars_repo_head_hexsha": "ac9531e792947fdc593f1fc3f593723e89fef303", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ladder_graph.jl", "max_issues_repo_name": "scheinerman/WordGraphs.jl", "max_issues_repo_head_hexsha": "ac9531e792947fdc593f1fc3f593723e89fef303", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ladder_graph.jl", "max_forks_repo_name": "scheinerman/WordGraphs.jl", "max_forks_repo_head_hexsha": "ac9531e792947fdc593f1fc3f593723e89fef303", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1940298507, "max_line_length": 92, "alphanum_fraction": 0.5492957746, "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765328159726, "lm_q2_score": 0.882427872638409, "lm_q1q2_score": 0.8062536391324362}} {"text": "\"\"\"\n gauss_lobatto_quad(α, β, N)\n\nComputes Legendre-Gauss-Lobatto quadrature points and weights with Jacobi weights α,β.\n\"\"\"\nfunction gauss_lobatto_quad(α::Int, β::Int, N)\n\n if !(iszero(α) && iszero(β))\n error(\"alpha/beta must be zero for Lobatto\")\n end\n\n x = zeros(N+1)\n w = zeros(N+1)\n if N == 0\n x[1] = 0.\n w[1] = 2.\n elseif N == 1\n x[1] = -1.0\n x[2] = 1.0\n w[1] = 1.0\n w[2] = 1.0\n elseif N==2\n x[1] = -1.\n x[2] = 0.\n x[3] = 1.\n w[1] = 0.333333333333333\n w[2] = 1.333333333333333\n w[3] = 0.333333333333333\n else\n xint, wint = gauss_quad(α+1, β+1, N-2)\n x = vcat(-1,xint,1)\n wend = 2/(N*(N+1))\n w = vcat(wend, (@. wint / (1-xint^2)) ,wend)\n end\n return x[:],w[:]\nend\n\n\n\"\"\"\n gauss_quad(α, β, N)\n\nCompute nodes and weights for Gaussian quadrature with Jacobi weights (α,β).\n\"\"\"\nfunction gauss_quad(α, β, N)\n if N == 0\n x = [-(α-β)/(α+β+2)]\n w = [2.]\n return x, w\n end\n\n J = zeros(N+1, N+1)\n h₁ = @. 2*(0:N)+α+β \n J = diagm(0 => @. -1/2*(α^2-β^2)/(h₁+2)/h₁) + \n diagm(1 => @. 2/(h₁[1:N]+2) * sqrt((1:N) * ((1:N)+α+β) * ((1:N)+α) * ((1:N)+β) / (h₁[1:N]+1) / (h₁[1:N]+3)))\n if α + β < 10*eps()\n J[1,1] = 0.0\n end\n\n x, V = eigen(Symmetric(J+J'))\n w = @. transpose(V[1,:])^2 * 2^(α+β+1) / (α+β+1) * gamma(α+1) * gamma(β+1) / gamma(α+β+1)\n return x[:], w[:]\nend\n\n\"\"\"\n jacobiP(x, α, β, N, tmp_array=zeros(N+1))\n jacobiP(x::AbstractArray, α, β, N)\n\nEvaluate the Jacobi Polynomial (α, β) of order N at points x. \nCan optionally specify `tmp_array` of length > N+1 to avoid allocations.\n\"\"\"\nfunction jacobiP(x, α, β, N, tmp_array=zeros(N+1))\n\n PL = tmp_array\n γ₀ = 2^(α+β+1) / (α+β+1) * gamma(α+1) * gamma(β+1) / gamma(α+β+1)\n PL[1] = 1.0 / sqrt(γ₀)\n if N == 0\n return PL[1]\n end\n\n γ₁ = (α+1) * (β+1) / (α+β+3) * γ₀\n PL[2] = ((α+β+2) * x/2 + (α-β)/2) / sqrt(γ₁)\n if N == 1 \n return PL[N+1]\n end\n\n aold = 2 / (2+α+β) * sqrt((α+1) * (β+1) / (α + β + 3))\n\n for i = 1:N-1\n h₁ = 2i + α + β\n anew = 2 / (h₁+2) * sqrt((i+1) * (i+1+α+β) * (i+1+α) * (i+1+β) / (h₁+1) / (h₁+3))\n bnew = -(α^2-β^2) / h₁ / (h₁+2)\n PL[i+2] = 1 / anew * (-aold * PL[i] + (x - bnew) * PL[i+1])\n aold = anew\n end\n \n return PL[N+1]\nend\n\n# vectorized version. \n# TODO: deprecate?\nfunction jacobiP(x::AbstractArray, α, β, N)\n\n PL = zeros(N+1, length(x))\n γ₀ = 2^(α+β+1) / (α+β+1) * gamma(α+1) * gamma(β+1) / gamma(α+β+1)\n @. PL[1,:] = 1.0/sqrt(γ₀)\n if N == 0\n return vec(PL)\n end\n\n γ₁ = (α+1) * (β+1) / (α+β+3) * γ₀\n @. PL[2, :] = ((α+β+2) * x/2 + (α-β)/2) / sqrt(γ₁)\n if N == 1 \n return PL[N+1,:]\n end\n\n aold = 2 / (2+α+β) * sqrt((α+1) * (β+1) / (α + β + 3))\n\n for i = 1:N-1\n h₁ = 2i+α+β\n anew = 2 / (h₁+2) * sqrt((i+1) * (i+1+α+β) * (i+1+α) * (i+1+β) / (h₁+1) / (h₁+3))\n bnew = -(α^2-β^2) / h₁ / (h₁+2)\n @. PL[i+2,:] = 1 / anew * (-aold * PL[i,:] .+ (x .- bnew) .* PL[i+1,:])\n aold = anew\n end\n \n return PL[N+1,:]\nend\n\n\"\"\"\n grad_jacobiP(r, α, β, N, tmp_array=())\n\nEvaluate derivative of Jacobi polynomial (α, β) of order N at points r.\nPass in `tmp_array = tuple(zeros(N+1))` to avoid allocations.\n\"\"\"\n\nfunction grad_jacobiP(r, α, β, N, tmp_array=()) \n if N != 0\n return sqrt(N * (N+α+β+1)) * jacobiP(r, α+1, β+1, N-1, tmp_array...)\n else\n return zero(r) \n end\nend\n", "meta": {"hexsha": "e391a2cc2faaa071d10b07bece393db2e74b6f85", "size": 3575, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nodes_and_modes_1D.jl", "max_stars_repo_name": "stevengj/NodesAndModes.jl", "max_stars_repo_head_hexsha": "2c13546a26b23e58164f72aab2e8555b002e79e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2020-08-28T06:59:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T16:38:39.000Z", "max_issues_repo_path": "src/nodes_and_modes_1D.jl", "max_issues_repo_name": "stevengj/NodesAndModes.jl", "max_issues_repo_head_hexsha": "2c13546a26b23e58164f72aab2e8555b002e79e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-12-01T07:26:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-23T18:04:39.000Z", "max_forks_repo_path": "src/nodes_and_modes_1D.jl", "max_forks_repo_name": "stevengj/NodesAndModes.jl", "max_forks_repo_head_hexsha": "2c13546a26b23e58164f72aab2e8555b002e79e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-23T16:50:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-23T16:50:40.000Z", "avg_line_length": 25.0, "max_line_length": 116, "alphanum_fraction": 0.4537062937, "num_tokens": 1607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768572945969, "lm_q2_score": 0.8539127566694178, "lm_q1q2_score": 0.8062446629958967}} {"text": "using OceanTurb, Printf\n\n@use_pyplot_utils\n\n# # Operations on fields\n#\n# Generate a grid with 100 points and height H=10. By default the\n# base of the grid is at z=-H and the top of the grid is at z=0.\ngrid = UniformGrid(100, 10)\n\n# Define a function that will generate our field's data.\nc0(z) = exp(1.2z)\n\n# Create a field of zeros on the grid.\nc = CellField(grid)\n\n# Set c to the function c0.\nOceanTurb.set!(c, c0)\n\n# Calculate the derivative of c and set it to cz.\ncz = ∂z(c)\n\n# Plot the results\nplot(c, label=L\"c = e^{1.2z}\")\nplot(cz, label=L\"\\partial_z c = 1.2 e^{1.2z}\")\nlegend()\n\ntitle(\"A field and it's derivative\")\nxlabel(\"\\$ c \\$ and \\$ \\\\partial_z c \\$\")\nylabel(L\"z\")\n\n\n# # Interpolation\n#\n# Next we demonstrate how to interpolate from one grid to another, \n# respecting the integral budget of a quantity.\n\ngrid1 = UniformGrid(30, 10)\ngrid2 = UniformGrid(10, 10)\ngrid3 = UniformGrid(3, 10)\n\nc1 = CellField(grid1)\nc2 = CellField(grid2)\nc3 = CellField(grid3)\n\nOceanTurb.set!(c1, c)\nOceanTurb.set!(c2, c)\nOceanTurb.set!(c3, c)\n\n@show integral(c)\n@show integral(c1)\n@show integral(c2)\n@show integral(c3)\n\nplot(c, \".\", label=\"high-res \\$ c \\$\")\nplot(c1, \"^\", label=\"medium-res \\$ c \\$\")\nplot(c2, \"x\", label=\"low-res \\$ c \\$\")\nplot(c3, \"+\", label=\"crazy low-res \\$ c \\$\")\n\nlegend()\n\ntitle(\"\\$ e^{1.2z} \\$ at different resolutions\")\nxlabel(L\"c\")\nylabel(L\"z\")\n", "meta": {"hexsha": "0e3f6d385d3341e09237ad110599d96391b08e56", "size": 1363, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/working_with_fields.jl", "max_stars_repo_name": "adelinehillier/OceanTurb.jl", "max_stars_repo_head_hexsha": "0794055373958658f3f49aff247306a3f2a7923f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2019-02-26T19:28:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-11T14:51:48.000Z", "max_issues_repo_path": "examples/working_with_fields.jl", "max_issues_repo_name": "adelinehillier/OceanTurb.jl", "max_issues_repo_head_hexsha": "0794055373958658f3f49aff247306a3f2a7923f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46, "max_issues_repo_issues_event_min_datetime": "2019-03-04T03:30:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-09T16:04:09.000Z", "max_forks_repo_path": "examples/working_with_fields.jl", "max_forks_repo_name": "adelinehillier/OceanTurb.jl", "max_forks_repo_head_hexsha": "0794055373958658f3f49aff247306a3f2a7923f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-09-15T21:29:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-07T16:13:50.000Z", "avg_line_length": 20.9692307692, "max_line_length": 67, "alphanum_fraction": 0.6610418195, "num_tokens": 436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176857294597, "lm_q2_score": 0.8539127473751341, "lm_q1q2_score": 0.8062446542204492}} {"text": "N = Int(5e1) # number of data\nM = Int(1e5) # number of realisations\n\nmu = [7; 10] * 1.0 # mean of data\nc = [5 3; 3 7] * 1.0 # covarianza en float\n\n# generate data\nusing Distributions\nprobMVgaus = MvNormal(mu,c)\nx = rand(probMVgaus, N*M)\nx = reshape(x, N, M, 2)\n\n# estimo los mu y c de cada relizacion\nmuest = mean(x, 1)\ndif = reshape(x .- muest,N,M,2,1) # ver como hacer esta resta facilmente\ncest = sum(dif .* permutedims(dif,[1,2,4,3]), 1) / (N - 1)\n\n# saco la media y varianza de los estimadores entre todas las realizaciones\n# media y var de mu\nmuExp = mean(muest, 2)\ndifmu = reshape(muest .- muExp, M, 2, 1)\nmuVar = sum(difmu .* permutedims(difmu,[1,3,2]), 1) / (M - 1)\n# media y var de c\ncExp = mean(cest, 2)\ndifc = reshape(cest .- cExp, M,2,2,1,1)\ncVar = sum(difc .* permutedims(difc, [1,5,4,3,2]), 1) / (M - 1)\ncVar = cVar[1,:,:,:,:]\n\n# saco las cuentas analiticas\nexpMu = mu\nVarMu = c / N\nexpC = c\n# no es necesario trasponer porque c es simetrica\ncShaped = reshape(c,2,2,1,1)\nVarCnn = cShaped .* permutedims(cShaped, [4,3,2,1])\nnCons = (2 * N - 1) / (N - 1)^2\nVarC = VarCnn * nCons\n\nprint(\"numerico: \\n\", cVar, \"\\n analitico \\n\", VarC)\nprint(cVar / nCons)\nprint(VarCnn)\n", "meta": {"hexsha": "a8dbc3712c285d7fe01ad60fae0d4341dfdd3d69", "size": 1184, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "dev/varianceOfmatrixvariance.jl", "max_stars_repo_name": "sebalander/sebaPhD", "max_stars_repo_head_hexsha": "0260094bd5143843ef372ce52aceb568834f90f4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2017-10-03T15:10:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-06T06:39:14.000Z", "max_issues_repo_path": "dev/varianceOfmatrixvariance.jl", "max_issues_repo_name": "sebalander/sebaPhD", "max_issues_repo_head_hexsha": "0260094bd5143843ef372ce52aceb568834f90f4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-02-09T21:13:13.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-09T21:13:13.000Z", "max_forks_repo_path": "dev/varianceOfmatrixvariance.jl", "max_forks_repo_name": "sebalander/sebaPhD", "max_forks_repo_head_hexsha": "0260094bd5143843ef372ce52aceb568834f90f4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-02-09T19:46:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-21T12:47:55.000Z", "avg_line_length": 28.1904761905, "max_line_length": 75, "alphanum_fraction": 0.6351351351, "num_tokens": 505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768541530197, "lm_q2_score": 0.853912747375134, "lm_q1q2_score": 0.8062446515378162}} {"text": "discount(t, κ) = 1/(1 + κ*t)\n\nfunction prob(κ, τ, t_ss, t_ll, r_ss, r_ll)\n u_ll = r_ll * discount(t_ll, κ)\n u_ss = r_ss * discount(t_ss, κ)\n return 1/(1 + exp(-τ * (u_ll - u_ss)))\nend\n\nfunction loglike(κ, τ, t_ss, t_ll, r_ss, r_ll, data)\n p = prob(κ, τ, t_ss, t_ll, r_ss, r_ll)\n p = p == 1 ? 1 - eps() : p\n p = p == 0 ? eps() : p\n LL = data ? log(p) : log(1 - p)\n # println(\" choice \", data, \" kappa \", κ, \" tau \", τ, \" t_ss \", t_ss,\n # \" t_ll \", t_ll, \" r_ss \", r_ss, \" r_ll \", r_ll, \" LL \", LL)\n return LL\nend\n\nfunction simulate(κ, τ, t_ss, t_ll, r_ss, r_ll)\n p = prob(κ, τ, t_ss, t_ll, r_ss, r_ll)\n return rand() ≤ p ? true : false\nend\n", "meta": {"hexsha": "3aff947f1515995d8551a8b9cf7edfea450d442b", "size": 679, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/Dynamic/Delay_Discounting.jl", "max_stars_repo_name": "itsdfish/AdaptiveDesignOptimization.jl", "max_stars_repo_head_hexsha": "3cddb97c49354a151ebef173a1db1578b7f6e18d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-04-02T18:44:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T14:20:51.000Z", "max_issues_repo_path": "Examples/Dynamic/Delay_Discounting.jl", "max_issues_repo_name": "itsdfish/AdaptiveDesignOptimization.jl", "max_issues_repo_head_hexsha": "3cddb97c49354a151ebef173a1db1578b7f6e18d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-04-01T20:09:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-31T09:25:58.000Z", "max_forks_repo_path": "Examples/Dynamic/Delay_Discounting.jl", "max_forks_repo_name": "itsdfish/AdaptiveDesignOptimization.jl", "max_forks_repo_head_hexsha": "3cddb97c49354a151ebef173a1db1578b7f6e18d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-08T13:38:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-08T13:38:14.000Z", "avg_line_length": 29.5217391304, "max_line_length": 73, "alphanum_fraction": 0.5198821797, "num_tokens": 279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191271831559, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.8061891346818577}} {"text": "using Plots\n\nfunction booth(x)\n return (x[1] + 2x[2] - 7)^2 + (2x[1] + x[2] - 5)^2;\nend\n\n# plot\n\ncontour(-30:0.1:30, -30:0.1:30, (x, y)->booth([x, y]))\n", "meta": {"hexsha": "8b9e50afc3064f4f07462ac88e42e165e1f68a59", "size": 155, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test_function/booths_function.jl", "max_stars_repo_name": "tor4z/convex_optimization", "max_stars_repo_head_hexsha": "15fd3aa09fbc3306ff68cc301bbddac3d2006f3f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test_function/booths_function.jl", "max_issues_repo_name": "tor4z/convex_optimization", "max_issues_repo_head_hexsha": "15fd3aa09fbc3306ff68cc301bbddac3d2006f3f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test_function/booths_function.jl", "max_forks_repo_name": "tor4z/convex_optimization", "max_forks_repo_head_hexsha": "15fd3aa09fbc3306ff68cc301bbddac3d2006f3f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.5, "max_line_length": 55, "alphanum_fraction": 0.5096774194, "num_tokens": 82, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9674102589923635, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.8061667585710274}} {"text": "# This file investigates mean square error (MSE) with respect to number of interpolation points in 1D interpolation \n\nusing FractalTools \nusing Makie \n\n# Construct interpolation data \nf(x) = sin(2π * x) \nxi = 0. \nxf = 1. \nfreevar = 0.001 \nnpts = 10 : 2 : 50\nntpts = 10 * npts[end]\n\n# Compute errors \nmse = map(npts) do npt \n # Construct interpolation data \n x = collect(range(xi, xf, length=npt))\n y = f.(x)\n pts = collect.(zip(x, y))\n\n # Construct interpolation \n interp = interpolate(pts, Interp1D(freevar))\n\n # Construct test data \n xt = collect(range(xi, xf, length=ntpts))\n\n # Compute error\n sum((f.(xt) - interp.(xt) ).^2) / length(xt)\nend \n\n# Plot mse \nfig = Figure() \nax = fig[1, 1] = Axis(fig, xlabel=\"Number of Points\", ylabel=\"MSE\", title=\"1D Interpolation MSE\") \nstem!(ax, npts, mse, color=:black)\nsave(joinpath(@__DIR__, \"interp1d_mse.png\"), fig)\ndisplay(fig)\n\n", "meta": {"hexsha": "9905bb69a4ef77aae4e8d801d4879f31d7ecbb43", "size": 924, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "experiment_1/interpolation_mse_vs_numpoints/interp1d/interp1d.jl", "max_stars_repo_name": "zekeriyasari/FractalTools.jl", "max_stars_repo_head_hexsha": "9896b88d30b3a22e1f808f812ce60d23d2a27013", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-09-08T12:20:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T12:50:16.000Z", "max_issues_repo_path": "experiment_2/interpolation_mse_vs_numpoints/interp1d/interp1d.jl", "max_issues_repo_name": "zekeriyasari/FractalTools.jl", "max_issues_repo_head_hexsha": "9896b88d30b3a22e1f808f812ce60d23d2a27013", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2020-09-05T18:22:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-26T10:09:46.000Z", "max_forks_repo_path": "experiment_2/interpolation_mse_vs_numpoints/interp1d/interp1d.jl", "max_forks_repo_name": "zekeriyasari/FractalTools.jl", "max_forks_repo_head_hexsha": "9896b88d30b3a22e1f808f812ce60d23d2a27013", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3157894737, "max_line_length": 116, "alphanum_fraction": 0.6352813853, "num_tokens": 284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551556203814, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.8061206021625904}} {"text": "set_theory = [\n Axiom(\"Definition of the universal set\", P ⊂ Ω, TRUE),\n Axiom(\"Definition of the universal set\", x ∈ Ω, TRUE),\n Axiom(\"Definition of the empty set\", ∅ ⊂ A, TRUE),\n Axiom(\"Definition of the empty set\", x ∈ ∅, FALSE),\n Axiom(\"Equal sets are subsets\", A ⊂ A, TRUE),\n\n Axiom(\"Definition of Element Of\", x ∈ (A ∩ B), (x ∈ A) ∧ (x ∈ B)),\n Axiom(\"Definition of Element Of\", (x ∈ A) ∧ (x ∈ B), x ∈ (A ∩ B)),\n Axiom(\"Definition of Element Of\", x ∈ (A ∪ B), (x ∈ A) ∨ (x ∈ B)),\n Axiom(\"Definition of Element Of\", (x ∈ A) ∨ (x ∈ B), x ∈ (A ∪ B)),\n\n Axiom(\"Flatten Condition Set\", ConditionSet(y, y ∈ A), A), # todo: change to f(x)\n Axiom(\"Expand Condition Set\", A, ConditionSet(_y, _y ∈ A)), # todo: change to f(x)\n Axiom(\"Definition of Subset\", A ⊂ B, (_y ∈ A) ⟹ (_y ∈ B)),\n Axiom(\"Definition of Subset\", (_y ∈ A) ⟹ (_y ∈ B), A ⊂ B),\n\n Axiom(\"Definition of the universal set\", x ∈ (P ∪ Ω), x ∈ Ω),\n\n #Theorem(\"Intersections are subsets of Unions\", x ∈ (A ∩ B), x ∈ (A ∪ B), Proof([])),\n #Theorem(\"Intersections are subsets of Unions\", (A ∩ B) ⊂ (A ∪ B), TRUE, Proof([])),\n]\n", "meta": {"hexsha": "c5411ad86d5b480cd3f9efe808b88115f595ab63", "size": 1130, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/tree_type/truths/SetTheory.jl", "max_stars_repo_name": "Maelstrom6/Breadth.jl", "max_stars_repo_head_hexsha": "5ccb6ec063e1d0337856257608ad887a7bd53eb8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tree_type/truths/SetTheory.jl", "max_issues_repo_name": "Maelstrom6/Breadth.jl", "max_issues_repo_head_hexsha": "5ccb6ec063e1d0337856257608ad887a7bd53eb8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-26T00:50:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-26T00:50:17.000Z", "max_forks_repo_path": "src/tree_type/truths/SetTheory.jl", "max_forks_repo_name": "Maelstrom6/Breadth.jl", "max_forks_repo_head_hexsha": "5ccb6ec063e1d0337856257608ad887a7bd53eb8", "max_forks_repo_licenses": ["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.1304347826, "max_line_length": 89, "alphanum_fraction": 0.5513274336, "num_tokens": 416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551535992067, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.8061205984977388}} {"text": "# Negative Binomial type 1 and type II log likelihood\n# The parameterization follows\n# Deb and Trivedi, J. Appl. Econometrics,\n# V. 12, 1997, pp. 313 - 336.\nusing SpecialFunctions, Distributions\nfunction negbin(θ, y, x, nbtype)\n n, k = size(x)\n β = θ[1:k]\n eps = 1e-8 \n λ = eps .+ exp.(x*β)\n α = eps .+ exp(θ[end])\n nbtype == 1 ? r = λ./α : r = ones(n)/α\n p = r ./ (r + λ)\n all(r .> 0.0) & all(p .> 0.0) & all(p .< 1.0) ? log.(pdf.(NegativeBinomial.(r, p),y)) : -Inf \nend\n\n\n", "meta": {"hexsha": "e83263061978cd282daae366146a6c95d3ffaf9d", "size": 506, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ML/Likelihoods/negbin.jl", "max_stars_repo_name": "mcreel/EconometricsNotes", "max_stars_repo_head_hexsha": "93b3f042ace7c4d3059b333fd9dc3d2c794f0a52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-19T18:23:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T18:23:45.000Z", "max_issues_repo_path": "src/ML/Likelihoods/negbin.jl", "max_issues_repo_name": "mcreel/EconometricsNotes", "max_issues_repo_head_hexsha": "93b3f042ace7c4d3059b333fd9dc3d2c794f0a52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ML/Likelihoods/negbin.jl", "max_forks_repo_name": "mcreel/EconometricsNotes", "max_forks_repo_head_hexsha": "93b3f042ace7c4d3059b333fd9dc3d2c794f0a52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1111111111, "max_line_length": 100, "alphanum_fraction": 0.5494071146, "num_tokens": 206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9648551505674444, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.8061205979409448}} {"text": "using LinearAlgebra\n\n# Define and use function\nf(x) = x[1] + x[2] - x[4]^2 # f(x) = x(1) + x(2) − x(4)^2\nf([-1,0,1,2]) # -5\n\n# Superposition\n# eval f at a linear combination of 2 vectors\n# == forming the linear combination of f eval at the 2 vectors\n\na = [-2, 0, 1, -3];\nf(x) = a'*x\n\nx=[2,2,-1,1]; y=[0,1,-1,0];\nalpha = 1.5; beta = -3.7;\nlhs = f(alpha * x + beta * y)\n\nrhs = alpha * f(x) + beta * f(y)\n\n# Verify superposition for f(e(3)) = a(3)\ne3 = [0, 0, 1, 0];\nf(e3) # 1.0\n\nusing Statistics\navg(x) = (ones(length(x)) / length(x))'*x; \nx = [1, -3, 2, -1];\navg(x)\n\n", "meta": {"hexsha": "d4a9d1fe34c1da3b62ed1159377531fe3f052022", "size": 615, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "2_Linear_Functions/1_Functions.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": "2_Linear_Functions/1_Functions.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": "2_Linear_Functions/1_Functions.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": 21.2068965517, "max_line_length": 62, "alphanum_fraction": 0.4959349593, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854138058638, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.8060304045991447}} {"text": "function conv(signal1::Vector{Complex}, signal2::Vector{Complex})\n n = length(signal1) + length(signal2)\n out = Vector{Complex}(n)\n sum = 0\n\n for i = 0:n\n for j = 0:i\n if(j < length(signal1))\n sum += signal1[j] * signal2[i-j]\n end\n end\n out[i] = sum\n sum = 0\n end\n\n return out\nend\n\nfunction conv_fft(signal1::Vector{Complex}, signal2::Vector{Complex})\n return ifft(fft(signal1).*fft(signal2))\nend\n\n", "meta": {"hexsha": "253a11d4f4f3784f68a17d5f54dc119eedc44576", "size": 484, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "contents/convolutions/code/julia/conv.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/convolutions/code/julia/conv.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/convolutions/code/julia/conv.jl", "max_forks_repo_name": "atocil/algorithm-archive", "max_forks_repo_head_hexsha": "2eb30cb103508c9efb91621564bd3114eb49d3af", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-19T10:04:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-19T10:04:37.000Z", "avg_line_length": 21.0434782609, "max_line_length": 69, "alphanum_fraction": 0.555785124, "num_tokens": 140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624257, "lm_q2_score": 0.8774767826757122, "lm_q1q2_score": 0.8059450855624547}} {"text": "struct CronbachAlpha{T <: Real}\n alpha::T\n dropped::Vector{T}\nend\n\nfunction Base.show(io::IO, x::CronbachAlpha)\n @printf(io, \"Cronbach's alpha for all items: %.4f\\n\", x.alpha)\n isempty(x.dropped) && return\n println(io, \"\\nCronbach's alpha if an item is dropped:\")\n for (idx, val) in enumerate(x.dropped)\n @printf(io, \"item %i: %.4f\\n\", idx, val)\n end\nend\n\n\"\"\"\n cronbachalpha(covmatrix::AbstractMatrix{<:Real})\n\nCalculate Cronbach's alpha (1951) from a covariance matrix `covmatrix` according to\nthe [formula](https://en.wikipedia.org/wiki/Cronbach%27s_alpha):\n\n```math\n\\\\rho = \\\\frac{k}{k-1} (1 - \\\\frac{\\\\sum^k_{i=1} \\\\sigma^2_i}{\\\\sum_{i=1}^k \\\\sum_{j=1}^k \\\\sigma_{ij}})\n```\n\nwhere ``k`` is the number of items, i.e. columns, ``\\\\sigma_i^2`` the item variance,\nand ``\\\\sigma_{ij}`` the inter-item covariance.\n\nReturns a `CronbachAlpha` object that holds:\n\n* `alpha`: the Cronbach's alpha score for all items, i.e. columns, in `covmatrix`; and\n* `dropped`: a vector giving Cronbach's alpha scores if a specific item,\n i.e. column, is dropped from `covmatrix`.\n\n# Example\n```jldoctest\njulia> using StatsBase\n\njulia> cov_X = [10 6 6 6;\n 6 11 6 6;\n 6 6 12 6;\n 6 6 6 13];\n\njulia> cronbachalpha(cov_X)\nCronbach's alpha for all items: 0.8136\n\nCronbach's alpha if an item is dropped:\nitem 1: 0.7500\nitem 2: 0.7606\nitem 3: 0.7714\nitem 4: 0.7826\n```\n\"\"\"\nfunction cronbachalpha(covmatrix::AbstractMatrix{<:Real})\n isposdef(covmatrix) || throw(ArgumentError(\"Covariance matrix must be positive definite.\"))\n k = size(covmatrix, 2)\n k > 1 || throw(ArgumentError(\"Covariance matrix must have more than one column.\"))\n v = vec(sum(covmatrix, dims=1))\n σ = sum(v)\n for i in axes(v, 1)\n v[i] -= covmatrix[i, i]\n end\n σ_diag = sum(i -> covmatrix[i, i], 1:k)\n\n alpha = k * (1 - σ_diag / σ) / (k - 1)\n if k > 2\n dropped = typeof(alpha)[(k - 1) * (1 - (σ_diag - covmatrix[i, i]) / (σ - 2*v[i] - covmatrix[i, i])) / (k - 2)\n for i in 1:k]\n else\n # if k = 2 do not produce dropped; this has to be also\n # correctly handled in show\n dropped = Vector{typeof(alpha)}()\n end\n return CronbachAlpha(alpha, dropped)\nend\n", "meta": {"hexsha": "aebb94b29ce72a671a69621634924b0e8505e11f", "size": 2276, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/reliability.jl", "max_stars_repo_name": "awadell1/StatsBase.jl", "max_stars_repo_head_hexsha": "21a255692e1d305a38ad6352affd897e383556cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 449, "max_stars_repo_stars_event_min_datetime": "2015-01-03T14:38:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T13:34:50.000Z", "max_issues_repo_path": "src/reliability.jl", "max_issues_repo_name": "awadell1/StatsBase.jl", "max_issues_repo_head_hexsha": "21a255692e1d305a38ad6352affd897e383556cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 606, "max_issues_repo_issues_event_min_datetime": "2015-02-08T16:52:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T07:41:08.000Z", "max_forks_repo_path": "src/reliability.jl", "max_forks_repo_name": "awadell1/StatsBase.jl", "max_forks_repo_head_hexsha": "21a255692e1d305a38ad6352affd897e383556cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 254, "max_forks_repo_forks_event_min_datetime": "2015-02-23T22:15:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T00:25:18.000Z", "avg_line_length": 30.3466666667, "max_line_length": 117, "alphanum_fraction": 0.6137961336, "num_tokens": 752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625031628428, "lm_q2_score": 0.8652240930029117, "lm_q1q2_score": 0.8059237994652925}} {"text": "using Distributions, Random, Plots, LaTeXStrings; pyplot()\n\nseed = 1\nN = 100\nlamGrid = 0.01:0.01:0.99\n\ntheorM(lam) = mean(Uniform(0,2*lam*(1-lam)))\nestM(lam) = mean(rand(Uniform(0,2*lam*(1-lam)),N))\n\nfunction estM(lam,seed)\n Random.seed!(seed)\n estM(lam)\nend\n\ntrueM = theorM.(lamGrid)\nestM0 = estM.(lamGrid)\nestMCRN = estM.(lamGrid,seed)\n\nplot(lamGrid,trueM,\n\tc=:black, label=\"Expected curve\")\nplot!(lamGrid,estM0,\n\tc=:blue, label=\"No CRN estiamte\")\nplot!(lamGrid,estMCRN,\n\tc=:red, label=\"CRN estimate\", \n\txlims=(0,1), ylims=(0,0.4), xlabel=L\"\\lambda\", ylabel = \"Mean\")", "meta": {"hexsha": "3f42c8bfb9830137b9634622f0206390f40d05a6", "size": 575, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "10_chapter/basicCRN.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "10_chapter/basicCRN.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "10_chapter/basicCRN.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 23.0, "max_line_length": 64, "alphanum_fraction": 0.6730434783, "num_tokens": 224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625126757596, "lm_q2_score": 0.8652240756264638, "lm_q1q2_score": 0.8059237915105874}} {"text": "# 10/24/2020 © Shuowen Chen\n# This script simulates CAPM data using Tauchen & Hussey (1991) method\n# as in Wright (2003) and explores sensitivity of Euler equation estimation\n# to number of discretization points.\n\n# load packages\nusing Random, Distributions, LinearAlgebra, Statistics, FastGaussQuadrature, Optim\n# set seed\nRandom.seed!(123)\n\n#======= Defining Functions =======#\n# univariate tauchen\nfunction tauchen(m, ρ, N, σ²)\n # INPUTS:\n # 1. m: multiple of unconditional standard deviation\n # 2. ρ: AR(1) coefficient\n # 3. N: number of grid points\n # 4. σ²: variance of the white noise\n\n # OUTPUTS:\n # 1. Transition probability matrix\n # 2. Sequence of grid points\n\n # unconditional standard deviation of the AR(1)\n std_un = sqrt(σ²/(1 - ρ^2));\n # max and min of the grid\n ymax = m*std_un;\n ymin = -ymax;\n # length of adjacent grid point\n w = (ymax - ymin)/(N - 1);\n # lay out the grids\n ygrid = collect(ymin:w:ymax);\n # Transition probability matrix (N by N)\n P = zeros(N, N);\n P[:, 1] = cdf.(Normal(0, 1), ((ymin .- ρ*ygrid .+ w/2)./sqrt(σ²)));\n P[:, end] = 1 .- cdf.(Normal(0, 1), ((ymax .- ρ*ygrid .- w/2)./sqrt(σ²)));\n for k = 2:(N - 1)\n P[:, k] = cdf.(Normal(0, 1), (ygrid[k] .- ρ*ygrid .+ w/2)./sqrt(σ²)) -\n cdf.(Normal(0, 1), (ygrid[k] .- ρ*ygrid .- w/2)./sqrt(σ²));\n end\n return(transition = P, grid = ygrid);\nend\n\n# Univariate Tauchen and Hussey (1991)\nfunction tauchenhussey(ρ, a, σ², N)\n # PURPOSE:\n # Discretize the following AR(1) process:\n # z_{t+1} = a + ρ*z_{t} + epsilon_{t+1}\n # INPUTS:\n # 1. ρ: AR(1) coefficient\n # 2. a: intercept\n # 3. σ²: variance of epsilon\n # 4. N: number of grid points\n\n # OUTPUTS:\n # 1. P: transition probability matrix\n # 2. grid: vector of grid points\n\n # A function from FastGaussQuadrature\n (x, w) = gausshermite(N);\n # Gaussian nodes and weights for normal distribution\n # Acknowledgement: I benefit from reading slides by Karen Kopecky\n # http://www.karenkopecky.net/Teaching/eco613614/Notes_DiscretizingAR1s.pdf\n\n # unconditional mean of the process\n μ = a / (1 - ρ);\n # Establish the grid using Gaussian-Hermite node\n grid = x .* sqrt(2*σ²) .+ μ;\n # Rescale the Gaussian-Hermite weight\n w = w ./ sqrt(pi);\n # Compute transition probability matrix\n P = zeros(N, N);\n for i = 1:N\n for j = 1:N\n EZprime = a + ρ*grid[i];\n # Gauchen-Hussey weight\n P[i, j] = w[j] * pdf(Normal(EZprime, sqrt(σ²)), grid[j]) /\n pdf(Normal(μ, sqrt(σ²)), grid[j]);\n end\n end\n # Normalization\n for i = 1:N\n P[i, :] = P[i, :] ./ sum(P[i, :])\n end\n return(P, grid);\nend\n\n# An auxiliary function to be called in tauchenhusseyvar\nfunction productrule(N, EZ, μ, Σ, grid_j, weight_j, k)\n # Purpose:\n # Compute individual transition prob from state i to j and aggregate\n # by Gauss product rule (tensor product)\n\n # Inputs:\n # 1. N: number of grid points\n # 2. EZ: expected value in state i (k by 1)\n # 3. μ: unconditional mean of VAR process (k by 1)\n # 4. Σ: var-cov matrix of VAR(1) process\n # 5. grid_j: grid points for the next state\n # 6. weight_j: Gauss-Hermite weight for the next state\n # 7. k: number of variables in the VAR\n\n # Outputs:\n # 1. prob: aggregate transition probability from state i to j\n\n den_ind = zeros(1, k);\n for i = 1:k\n den_ind[i] = weight_j/sqrt(pi) * pdf(Normal(EZ[i], diag(sqrt(Σ))[i]),\n grid_j[i]) / pdf(Normal(μ[i], diag(sqrt(Σ))[i]), grid_j[i])\n end\n den_agg = prod(den_ind);\n return(den_agg);\nend\n\n# Bivariate Tauchen-Hussey (1991)\nfunction tauchenhusseyvar(k, A, B, Σ, N)\n # PURPOSE: Discretize the following VAR(1) process\n # Y_t = A + B * Y_t-1 + e_t,\n # where e_t ∼ N(0, Σ)\n # Acknowledgement: I benefit from reading the quadrature code by Tauchen,\n # which is available in his website.\n\n # INPUTS:\n # 1. k: number of variables in the VAR\n # 2. A: constant of VAR(1) (k by 1)\n # 3. B: VAR(1) coefficient matrix (k by k)\n # 4. Σ: iid var-cov matrix\n # 5. N: number of discrete points for each variable k in the VAR\n\n # OUTPUTS:\n # 1. P: transition matrix (Nᵏ by Nᵏ)\n # 2. Grid: grid points (k by Nᵏ).\n # Note: number of states in the system is equal to number of grids * number of lags,\n # since we consider VAR(1), number of states = number of grid points\n\n # unconditional mean of the process\n μ = inv(I(k) - B) * A;\n # obtain Gaussian-Hermite nodes and weights\n (x, w) = gausshermite(N);\n # Grid for each variable\n grid_ind = repeat(x, outer = [1, k])' .* sqrt.(2 * diag(Σ)) .+ μ;\n # total grid (k by N^k) and GH weights (N^k) using product rule\n grid = zeros(k, N^k);\n w_tot = zeros(k, N^k);\n for i = 1:k\n grid[i, :] = repeat(grid_ind[i, :], inner = [N^(k-i), 1],\n outer = [N^(i-1), 1]);\n w_tot[i, :] = repeat(w, inner = [N^(k-i), 1], outer = [N^(i-1), 1]);\n end\n w_tot = prod(w_tot, dims = 1);\n # Compute transition probability matrix\n P = zeros(N^k, N^k);\n for i = 1:N^k\n for j = 1:N^k\n # expected value in state i at time t-1\n EZprime = A + B*grid[:, i]; # k by 1\n # Gauchen-Hussey\n P[i, j] = productrule(N, EZprime, μ, Σ, grid[:, j], w_tot[j], k);\n end\n end\n # Normalization\n for i = 1:N^k\n P[i, :] = P[i, :] ./ sum(P[i, :])\n end\n return(grid, P);\nend\n\n# Simulate data using Markov transition probability and grid points\nfunction simulationMC(Pr_mat, grid, T, sim)\n # INPUTS:\n # 1. Pr_mat: transition matrix\n # 2. grid: grid points\n # 3. T: number of observations in each simulation\n # 4. sim: number of simulations\n # 5. k: number of variables\n\n # OUTPUT:\n # 1. Z: simulated states using MC (k by T for # sim times)\n # Economic meaning: log consumption and dividend growth data\n # 2. state: state index for stock return simulation\n\n # first obs of the MC (middle state)\n initial_state = convert(Int, floor((length(grid)/size(grid)[1]+1)/2));\n # placeholder for simulated states\n Z = zeros(k, T, sim);\n # initial state\n Z[:, 1, :] .= grid[:, initial_state]; # need to broadcast\n\n # placeholder for state index\n state = zeros(T, sim);\n # initial state\n state[1, :] .= initial_state;\n\n # This follows from Adda and Cooper (2003)\n # standard uniformly distributed rv for\n # determining the new state\n u = rand(Uniform(), (T-1, sim));\n # store ∑_{l=1}^{j}π_{i,l} for j = 1,...,N\n Pr_sum = cumsum(Pr_mat, dims = 2);\n old_state = initial_state;\n for i = 1:sim\n for t = 2:T\n new_state = findfirst(u[t-1, i] .<= Pr_sum[old_state, :])\n Z[:, t, i] = grid[:, new_state];\n # store the state index\n state[t, i] = new_state;\n # move to the next obs\n old_state = new_state;\n end\n end\n state = convert.(Int, state);\n return(Z, state);\nend\n\n# a function that directly simulates the VAR\nfunction simulationVAR(T, sim, A, B, Σ, k)\n # INPUTS:\n # 1. T: number of observations in each simulation\n # 2. sim: number of simulations\n # 3. A: constant of VAR(1) (k by 1)\n # 4. B: VAR(1) coefficient matrix (k by k)\n # 5. Σ: iid var-cov matrix\n # 6. K: number of variables\n\n # OUTPUTS:\n # 1. TS: simulated time series (k by 1)\n\n # normal errors e_t ∼ N(0, Σ) for t = 2,...,T and each simulation\n err = zeros(k, T-1, sim);\n for i = 1:sim\n err[:, :, i] = rand(MvNormal([0; 0], Σ), T-1);\n end\n # placeholder for simulated VAR\n TS = zeros(k, T, sim);\n # initial observation (steady state)\n for i = 1:sim\n TS[:, 1, i] = inv(I(k) - B) * A;\n end\n # Then use the relationship Y_t = A + B*Y_t-1 + e_t\n for i = 1:sim\n for j = 2:T\n # Note the index for err is due to specification of err\n TS[:, j, i] = A + B*TS[:, j-1, i] + err[:, j-1, i];\n end\n end\n return(TS)\nend\n\n# Simulate stock return\nfunction simulateReturn(β, γ, P, CG, DG, N, stateindex)\n # INPUTS:\n # 1. β: discount factor\n # 2. γ: CRRA preference\n # 3. P: probability transition matrix\n # 4. CG: consumption growth\n # 5. DG: dividend growth\n # 6. N: number of grid points for each variable\n\n # OUTPUTS:\n # 1. smreturn: simulated return data\n\n # Define transition matrix for return\n B = β*P;\n for j = 1:N^2\n B[:, j] = B[:, j] .* CG[j].^(-γ) .* DG[j];\n end\n # State contingent price-dividend ratio (N^2 by 1)\n psm = inv(I(N^2) - B) * B * ones(N^2);\n # Realized stock return from state i to j (N^2 by N^2)\n Rmat = zeros(N^2, N^2);\n for i = 1:N^2\n for j = 1:N^2\n Rmat[i, j] = DG[j]*(1+psm[j])/psm[i];\n end\n end\n # simulate the return data\n T = size(stateindex)[1] - 1;\n smreturn = zeros(T, 1);\n for t = 1:T\n smreturn[t] = Rmat[stateindex[t], stateindex[t+1]];\n end\n return(smreturn);\nend\n\n# A function to conduct 2 step GMM\nfunction GMM2step(moments, gradients, k, initial, samplesize)\n # INPUTS:\n # 1. moments: an anonymous function that maps theta to moment conditions\n # 2. gradients: an anoymous function that mapes theta to gradient conditions\n # 3. k: number of moments\n # 4. initial: initial values for estimation (must be floating)\n # 5. samplesize: sample size of the moments\n # OUTPUTS:\n # 1. est: parameter estimate\n # 2. se: standard errors\n\n # sample average moments\n sample_m = theta -> vec(mean(moments(theta), dims = 1));\n # first step weighting matrix\n W = I(k);\n # objective function in the first step\n obj = theta -> sample_m(theta)'*W*sample_m(theta);\n # minimization using limited BFGS\n firststep = Optim.optimize(obj, initial, LBFGS());\n # second step weighting matrix\n W2 = inv(cov(moments(firststep.minimizer)));\n # objective function in the second step\n obj2 = theta -> sample_m(theta)'*W2*sample_m(theta);\n secondstep = Optim.optimize(obj2, initial, LBFGS());\n # compute the gradient\n # dimension of D: k (# of pars) by p (# of moments)\n D = reshape(mean(gradients(secondstep.minimizer), dims = 1), k, length(initial));\n var = inv(D'*inv(cov(moments(secondstep.minimizer)))*D);\n # compute standard errors\n se = sqrt.(diag(var)./samplesize);\n return(firststep.minimizer, secondstep.minimizer, se);\nend\n\n#======= Main Program Starts Here =======#\n# Setting parameters\nβ = 1.139; # utility discount factor\nγ = 13.7; # CRRA parameter\nk = 2; # number of variables\nA = [0.021; 0.04]; # Calibrated values as in Wright (2003)\nB = [-0.161 0.017; 0.414 0.117];\nΣ = [0.0012 0.00177; 0.00177 0.014];\nN = 4; # number of grids for each variable\nT = 400; # number of time periods\nsim = 400; # number of simulations\n\n# Generate grid points and transition probability\n(grid, P) = tauchenhusseyvar(k, A, B, Σ, N);\n# Simulate log consumption and dividend growth\n(timeseries, stateindex) = simulationMC(P, grid, T, sim);\n\n# Consumption and dividend growth\nCG_tot = exp.(timeseries[1, :, :]);\nDG_tot = exp.(timeseries[2, :, :]);\n# use state index to generate return stock market return\nR = zeros(T-1, sim);\nfor i = 1:sim\n R[:, i] = simulateReturn(β, γ, P, CG_tot[:, i], DG_tot[:, i], N, stateindex[:, i]);\nend\n\n# conduct estimation\ncontainer = zeros(sim, 2);\nfor i = 1:sim\n # intercept, lagged return and lagged consumption growth\n ins = [ones(T-2) R[1:end-1, i] CG_tot[1:end-2, i]];\n # sample size of the moments\n t_mom = size(instruments)[1];\n # Construct Euler equation\n euler = theta -> (theta[1] .* R[2:end, i] .* CG_tot[2:end-1, i] .^ (-theta[2]) .-1) .* ins;\n\n grad = theta -> hcat(R[2:end, i] .* CG_tot[2:end-1, i] .^ (-theta[2]) .* ins,\n -(theta[1] .* R[2:end, i] .* CG_tot[2:end-1, i] .^ (-theta[2]) .* log.(CG_tot[2:end-1, i])) .* ins);\n\n gest = GMM2step(euler, grad, 3, [0.0, 13.0], t_mom);\n container[i,:] = gest[2];\nend\n\nmean(container, dims =1)\n", "meta": {"hexsha": "668039498c0b776fa5ba658cfae832799a1202c6", "size": 12127, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "tauchen.jl", "max_stars_repo_name": "shuowencs/Robust-Discretization", "max_stars_repo_head_hexsha": "df1b78c5dbac58685170786cde0a5dd27e6e5170", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tauchen.jl", "max_issues_repo_name": "shuowencs/Robust-Discretization", "max_issues_repo_head_hexsha": "df1b78c5dbac58685170786cde0a5dd27e6e5170", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tauchen.jl", "max_forks_repo_name": "shuowencs/Robust-Discretization", "max_forks_repo_head_hexsha": "df1b78c5dbac58685170786cde0a5dd27e6e5170", "max_forks_repo_licenses": ["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.4077134986, "max_line_length": 129, "alphanum_fraction": 0.5933866579, "num_tokens": 3951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680097, "lm_q2_score": 0.8652240791017535, "lm_q1q2_score": 0.8059237898092069}} {"text": "#' ---\r\n#' title: Network Flows\r\n#' ---\r\n\r\n#' **Originally Contributed by**: Arpit Bhatia\r\n\r\n#' In graph theory, a flow network (also known as a transportation network) is a directed graph where \r\n#' each edge has a capacity and each edge receives a flow. The amount of flow on an edge cannot exceed the capacity of the edge. \r\n#' Often in operations research, a directed graph is called a network, the vertices are called nodes and the edges are called arcs. \r\n#' A flow must satisfy the restriction that the amount of flow into a node equals the amount of flow out of it, \r\n#' unless it is a source, which has only outgoing flow, or sink, which has only incoming flow. \r\n#' A network can be used to model traffic in a computer network, circulation with demands, fluids in pipes, \r\n#' currents in an electrical circuit, or anything similar in which something travels through a network of nodes.\r\n\r\nusing JuMP\r\nusing GLPK\r\n\r\n#' ## The Shortest Path Problem\r\n#' Suppose that each arc $(i, j)$ of a graph is assigned a scalar cost $a_{i,j}$, and \r\n#' suppose that we define the cost of a forward path to be the sum of the costs of its arcs. \r\n#' Given a pair of nodes, the shortest path problem is to find a forward path that connects these nodes and has minimum cost.\r\n\r\n#' $$\r\n#' \\begin{align*}\r\n#' \\min && \\sum_{\\forall e(i,j) \\in E} a_{i,j} \\times x_{i,j} \\\\\r\n#' s.t. && b(i) = \\sum_j x_{ij} - \\sum_k x_{ki} = \\begin{cases}\r\n#' 1 &\\mbox{if $i$ is the starting node,} \\\\\r\n#' -1 &\\mbox{if $i$ is the ending node,} \\\\\r\n#' 0 &\\mbox{otherwise.} \\end{cases} \\\\\r\n#' && x_{e} \\in \\{0,1\\} && \\forall e \\in E\r\n#' \\end{align*}\r\n#' $$\r\n\r\n#' \"Flow\r\n\r\nG = [\r\n0 100 30 0 0;\r\n0 0 20 0 0; \r\n0 0 0 10 60;\r\n0 15 0 0 50;\r\n0 0 0 0 0\r\n]\r\n\r\nn = size(G)[1]\r\n\r\nshortest_path = Model(with_optimizer(GLPK.Optimizer))\r\n\r\n@variable(shortest_path, x[1:n,1:n], Bin)\r\n@constraint(shortest_path, [i = 1:n, j = 1:n; G[i,j] == 0], x[i,j] == 0) # Arcs with zero cost are not a part of the path as they do no exist\r\n@constraint(shortest_path, [i = 1:n; i != 1 && i != 2], sum(x[i,:]) == sum(x[:,i])) # Flow conservation constraint\r\n@constraint(shortest_path, sum(x[1,:]) - sum(x[:,1]) == 1) # Flow coming out of source = 1\r\n@constraint(shortest_path, sum(x[2,:]) - sum(x[:,2]) == -1) # Flowing coming out of destination = -1 i.e. Flow entering destination = 1 \r\n@objective(shortest_path, Min, sum(G .* x))\r\n\r\noptimize!(shortest_path)\r\n@show objective_value(shortest_path);\r\n@show value.(x);\r\n\r\n#' ## The Assignment Problem\r\n#' Suppose that there are $n$ persons and $n$ objects that we have to match on a one-to-one basis. \r\n#' There is a benefit or value $a_{i,j}$ for matching person $i$ with object $j$, and \r\n#' we want to assign persons to objects so as to maximize the total benefit. \r\n#' There is also a restriction that person $i$ can be assigned to object $j$ only if $(i, j)$ belongs to a given set of pairs $A$. \r\n#' Mathematically, we want to find a set of person-object pairs $(1, j_{1}),..., (n, j_{n})$ from $A$ such that \r\n#' the objects $j_{1},...,j_{n}$ are all distinct, and the total benefit $\\sum_{i=1}^{y} a_{ij_{i}}$ is maximized.\r\n\r\n#' $$\r\n#' \\begin{align*}\r\n#' \\max && \\sum_{(i,j) \\in A} a_{i,j} \\times y_{i,j} \\\\\r\n#' s.t. && \\sum_{\\{j|(i,j) \\in A\\}} y_{i,j} = 1 && \\forall i = \\{1,2....n\\} \\\\\r\n#' && \\sum_{\\{i|(i,j) \\in A\\}} y_{i,j} = 1 && \\forall j = \\{1,2....n\\} \\\\\r\n#' && y_{i,j} \\in \\{0,1\\} && \\forall (i,j) \\in \\{1,2...k\\}\r\n#' \\end{align*}\r\n#' $$\r\n\r\n#' \"Flow\r\n\r\nG = [\r\n6 4 5 0;\r\n0 3 6 0;\r\n5 0 4 3;\r\n7 5 5 5;\r\n]\r\n\r\nn = size(G)[1]\r\n\r\nassignment = Model(with_optimizer(GLPK.Optimizer))\r\n@variable(assignment, y[1:n,1:n], Bin)\r\n@constraint(assignment, [i = 1:n], sum(y[:,i]) == 1) # One person can only be assigned to one object\r\n@constraint(assignment, [j = 1:n], sum(y[j,:]) == 1) # One object can only be assigned to one person\r\n@objective(assignment, Max, sum(G .* y))\r\n\r\noptimize!(assignment)\r\n@show objective_value(assignment);\r\n@show value.(y);\r\n\r\n#' ## The Max-Flow Problem\r\n#' In the max-flow problem, we have a graph with two special nodes: the $source$, denoted by $s$, and the $sink$, denoted by $t$. \r\n#' The objective is to move as much flow as possible from $s$ into $t$ while observing the capacity constraints.\r\n\r\n#' $$\r\n#' \\begin{align*}\r\n#' \\max && \\sum_{v:(s,v) \\in E} f(s,v) \\\\\r\n#' s.t. && \\sum_{u:(u,v) \\in E} f(u,v) = \\sum_{w:(v,w) \\in E} f(v,w) && \\forall v \\in V - \\{s,t\\} \\\\\r\n#' && f(u,v) \\leq c(u,v) && \\forall (u,v) \\in E \\\\\r\n#' && f(u,v) \\geq 0 && \\forall (u,v) \\in E \r\n#' \\end{align*}\r\n#' $$\r\n\r\n#' \"Flow\r\n\r\nG = [\r\n0 3 2 2 0 0 0 0 \r\n0 0 0 0 5 1 0 0 \r\n0 0 0 0 1 3 1 0 \r\n0 0 0 0 0 1 0 0 \r\n0 0 0 0 0 0 0 4 \r\n0 0 0 0 0 0 0 2 \r\n0 0 0 0 0 0 0 4 \r\n0 0 0 0 0 0 0 0 \r\n]\r\n\r\nn = size(G)[1]\r\n\r\nmax_flow = Model(with_optimizer(GLPK.Optimizer))\r\n\r\n@variable(max_flow, f[1:n,1:n] >= 0)\r\n@constraint(max_flow, [i = 1:n, j = 1:n], f[i,j] <= G[i,j]) # Capacity constraints\r\n@constraint(max_flow, [i = 1:n; i != 1 && i != 8], sum(f[i,:]) == sum(f[:,i])) # Flow conservation contraints\r\n@objective(max_flow, Max, sum(f[1, :]))\r\n\r\noptimize!(max_flow)\r\n@show objective_value(max_flow);\r\n@show value.(f);", "meta": {"hexsha": "c0445120a8a2c69627778ee2f4e618542e87424a", "size": 5341, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/modelling/network_flows.jl", "max_stars_repo_name": "carlosal1015/JuMPTutorials.jl", "max_stars_repo_head_hexsha": "4d9a86ea310ecc7a22de7f14b783dbd218e4b612", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "script/modelling/network_flows.jl", "max_issues_repo_name": "carlosal1015/JuMPTutorials.jl", "max_issues_repo_head_hexsha": "4d9a86ea310ecc7a22de7f14b783dbd218e4b612", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/modelling/network_flows.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": 39.8582089552, "max_line_length": 142, "alphanum_fraction": 0.6098108968, "num_tokens": 1845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109798251322, "lm_q2_score": 0.8479677622198946, "lm_q1q2_score": 0.8059178717515347}} {"text": "\"\"\"Returns a matrix of water depth for the whole domain that contains a\nGaussian seamount in the middle. Water depth, heigth and width of the\nseamount are adjusted with the constants water_depth, topofeat_height and topofeat_width.\"\"\"\nfunction seamount()\n xx_T,yy_T = meshgrid(x_T_halo,y_T_halo)\n bumpx = exp.(-((xx_T .- Lx/2).^2)/(2*topofeat_width^2))\n bumpy = exp.(-((yy_T .- Ly/2).^2)/(2*topofeat_width^2))\n\n H = water_depth .- topofeat_height*bumpx.*bumpy\n return Numtype.(H)\nend\n\n\"\"\"Returns a matrix of water depth for the whole domain that contains a\nmeridional Gaussian ridge in the middle. Water depth, heigth and width of the\nridge are adjusted with the constants water_depth, topofeat_height and topofeat_width.\"\"\"\nfunction ridge()\n xx_T,yy_T = meshgrid(x_T_halo,y_T_halo)\n bumpx = exp.(-((xx_T .- Lx/2).^2)/(2*topofeat_width^2))\n\n H = water_depth .- topofeat_height*bumpx\n return Numtype.(H)\nend\n\n\"\"\"Same as ridge() but for 3 ridges at 1/4,1/2,3/4 of the domain.\"\"\"\nfunction ridges()\n xx_T,yy_T = meshgrid(x_T_halo,y_T_halo)\n\n # bumps in x direction\n # shift slightly left/right to avoid a symmetric solution\n b0x = exp.(-(xx_T.^2)/(2*topofeat_width^2))\n b1x = exp.(-((xx_T .- 0.99*Lx/4).^2)/(2*topofeat_width^2))\n b2x = exp.(-((xx_T .- 1.01*Lx/2).^2)/(2*topofeat_width^2))\n b3x = exp.(-((xx_T .- 0.99*3*Lx/4).^2)/(2*topofeat_width^2))\n b4x = exp.(-((xx_T .- Lx).^2)/(2*topofeat_width^2))\n\n th = topofeat_height # for convenience\n H = water_depth .- th*b0x .- th*b1x .- th*b2x .- th*b3x .- th*b4x\n return Numtype.(H)\nend\n\n\"\"\"Returns a matrix of constant water depth specified by the constant water_depth.\"\"\"\nfunction flat_bottom()\n H = fill(water_depth,(nx+2*haloη,ny+2*haloη))\n return Numtype.(H)\nend\n\n# rename for convenience\nif topography_feature == \"ridge\"\n topography = ridge\nelseif topography_feature == \"ridges\"\n topography = ridges\nelseif topography_feature == \"seamount\"\n topography = seamount\nelseif topography_feature == \"flat\"\n topography = flat_bottom\nelse\n throw(error(\"Topography feature not correctly declared.\"))\nend\n", "meta": {"hexsha": "b5796e2fb2bfda8672de605da5d334c01687a226", "size": 2129, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/bottom_topography.jl", "max_stars_repo_name": "eschnett/juls", "max_stars_repo_head_hexsha": "2921372578c880c52c07f5449afc234c69433148", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/bottom_topography.jl", "max_issues_repo_name": "eschnett/juls", "max_issues_repo_head_hexsha": "2921372578c880c52c07f5449afc234c69433148", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/bottom_topography.jl", "max_forks_repo_name": "eschnett/juls", "max_forks_repo_head_hexsha": "2921372578c880c52c07f5449afc234c69433148", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0847457627, "max_line_length": 92, "alphanum_fraction": 0.6876467825, "num_tokens": 693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109742068042, "lm_q2_score": 0.8479677660619633, "lm_q1q2_score": 0.8059178706389181}} {"text": "\n\"\"\"\n (uvels, vvels, wvels) = streamfunction_xz()\n\nDefine a two-dimensional flow field in the x-z directions from a simple streamfunction.\n\"\"\"\nfunction streamfunction_xz()\n scal = 2e-1\n f(x, y, z) = scal*sin(x*2π/128)*sin(z*π/128) #stream function\n\n ϕcorners=[f(x,0.,z) for x in 0:128, z in -128:0]\n ϕcenters=[f(x,0.,z) for x in 0.5:128, z in -128:-0.5]\n\n uu=-diff(ϕcorners,dims=2)[1:end-1,:]\n ww=diff(ϕcorners,dims=1)\n uu=reshape(uu,(128,1,128))\n ww=reshape(ww,(128,1,129))\n uu = reverse(uu, dims=3)\n ww = reverse(ww, dims=3)\n\n uvels = fill(uu, 2)\n vvels = fill(0*uu, 2)\n wvels = fill(ww, 2)\n uvels = cat(uvels..., dims=4)\n vvels = cat(vvels..., dims=4)\n wvels = cat(wvels..., dims=4)\n\n return uvels, vvels, wvels, ϕcenters\nend\n\n\n\"\"\"\n (uvels, vvels, wvels) = streamfunction_xy()\n\nDefine a two-dimensional flow field in the x-y directions from a simple streamfunction\nas explained at https://shaddenlab.berkeley.edu/uploads/LCS-tutorial/examples.html#Sec7.1\n\"\"\"\nfunction streamfunction_xy()\n scal = 3e-1\n f(x, y, z) = scal*(0.3*sin(x*1π/128)*sin(y*2π/128)+0.7*sin(x*2π/128)*sin(y*1π/128)) #stream function\n\n ϕcorners=[f(x,y,0.) for x in 0:128, y in 0:128]\n ϕcenters=[f(x,y,0.) for x in 0.5:128, y in 0.5:128]\n\n uu=-diff(ϕcorners,dims=2)[1:end-1,:]\n vv=diff(ϕcorners,dims=1)[:,1:end-1]\n uu=reshape(uu,(128,128,1))\n vv=reshape(vv,(128,128,1))\n ww=zeros(128,128,2)\n\n uvels = fill(uu, 2)\n vvels = fill(vv, 2)\n wvels = fill(ww, 2)\n uvels = cat(uvels..., dims=4)\n vvels = cat(vvels..., dims=4)\n wvels = cat(wvels..., dims=4)\n\n return uvels, vvels, wvels, ϕcenters\nend", "meta": {"hexsha": "68e7e05bc04269f25d3caee539c0d892133e85ca", "size": 1666, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/helper_functions.jl", "max_stars_repo_name": "JuliaOcean/PlanktonIndividuals.jl", "max_stars_repo_head_hexsha": "5ac96b3ef90a21f377c119557665997fabe0944d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-11-21T21:13:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T10:30:39.000Z", "max_issues_repo_path": "examples/helper_functions.jl", "max_issues_repo_name": "gaelforget/PlanktonIndividuals.jl", "max_issues_repo_head_hexsha": "f7a130b0d9ece421da42c737c080f53411db5821", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2020-07-08T18:13:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T17:44:10.000Z", "max_forks_repo_path": "examples/helper_functions.jl", "max_forks_repo_name": "gaelforget/PlanktonIndividuals.jl", "max_forks_repo_head_hexsha": "f7a130b0d9ece421da42c737c080f53411db5821", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-22T22:23:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T22:23:33.000Z", "avg_line_length": 28.2372881356, "max_line_length": 104, "alphanum_fraction": 0.6128451381, "num_tokens": 685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109742068042, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.8059178688131459}} {"text": "function init_CN(model)\n nx, ny = model.grid.nx, model.grid.ny\n Δx, Δy = model.grid.Δx, model.grid.Δy\n ν, Δt = model.parameters.ν, model.Δt\n\n Nx = (nx-2)\n Ny = (ny-2)\n Nxy = Nx*Ny\n βx = 0.5*ν*Δt/(Δx*Δx)\n βy = 0.5*ν*Δt/(Δy*Δy)\n\n # New a1\n a1 = spzeros(Nxy,Nxy)\n ij_ind = LinearIndices((1:Ny, 1:Nx))\n for ij in ij_ind\n a1[ij,ij] = 1 + 2*βx + 2*βy\n end\n for ij in 1:Nx*(Ny-1)\n a1[view(ij_ind,2:Ny,:)[ij],view(ij_ind,1:Ny-1,:)[ij]] = -βy # Up\n a1[view(ij_ind,1:Ny-1,:)[ij],view(ij_ind,2:Ny,:)[ij]] = -βy # Down\n end\n for ij in 1:(Nx-1)*Ny\n a1[view(ij_ind,:,2:Nx)[ij],view(ij_ind,:,1:Nx-1)[ij]] = -βx # Right\n a1[view(ij_ind,:,1:Nx-1)[ij],view(ij_ind,:,2:Nx)[ij]] = -βx # Left\n end\n\n # New a2\n a2 = spzeros(Nxy,Nxy)\n ij_ind = LinearIndices((1:Ny, 1:Nx))\n for ij in ij_ind\n a2[ij,ij] = 1 - 2*βx - 2*βy\n end\n for ij in 1:Nx*(Ny-1)\n a2[view(ij_ind,2:Ny,:)[ij],view(ij_ind,1:Ny-1,:)[ij]] = βy # Up\n a2[view(ij_ind,1:Ny-1,:)[ij],view(ij_ind,2:Ny,:)[ij]] = βy # Down\n end\n for ij in 1:(Nx-1)*Ny\n a2[view(ij_ind,:,2:Nx)[ij],view(ij_ind,:,1:Nx-1)[ij]] = βx # Right\n a2[view(ij_ind,:,1:Nx-1)[ij],view(ij_ind,:,2:Nx)[ij]] = βx # Left\n end\n\n a1_lu = factorize(a1)\n return a1_lu, a2\nend\nfunction init_ADI(model)\n nx, ny = model.grid.nx, model.grid.ny\n Δx, Δy = model.grid.Δx, model.grid.Δy\n ν, Δt = model.parameters.ν, model.Δt\n\n βx = 0.5*ν*Δt/(Δx*Δx)\n βy = 0.5*ν*Δt/(Δy*Δy)\n d1x = ones(nx-2) .+ 2 * βx\n e1x = -βx * ones(nx-3)\n d1y = ones(ny-2) .+ 2 * βy\n e1y = -βy * ones(ny-3)\n # matrix ( I - 0.5 nu dt delta_x^2 )\n a1x = SymTridiagonal(d1x,e1x)\n a1y = SymTridiagonal(d1y,e1y)\n\n d2x = ones(nx-2) .- 2 * βx\n e2x = -βx * ones(nx-3)\n d2y = ones(ny-2) .- 2 * βy\n e2y = -βy * ones(ny-3)\n # matrix ( I + 0.5 nu dt delta_x^2)\n a2x = SymTridiagonal(d2x,-e2x)\n a2y = SymTridiagonal(d2y,-e2y)\n\n #LDLt factorize\n a1x_ldlt = factorize(a1x)\n a1y_ldlt = factorize(a1y)\n return a1x_ldlt, a1y_ldlt, a2x, a2y\nend\n", "meta": {"hexsha": "ab75d56aeae92ce7e00fbc057dc748065a047dd2", "size": 2106, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/matrix_solvers.jl", "max_stars_repo_name": "williamjsdavis/NavierStokes2D.jl", "max_stars_repo_head_hexsha": "bc4e15beb0b32ee65106b0795381f96c7ac25122", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-16T00:15:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T00:15:48.000Z", "max_issues_repo_path": "src/matrix_solvers.jl", "max_issues_repo_name": "williamjsdavis/NavierStokes2D.jl", "max_issues_repo_head_hexsha": "bc4e15beb0b32ee65106b0795381f96c7ac25122", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/matrix_solvers.jl", "max_forks_repo_name": "williamjsdavis/NavierStokes2D.jl", "max_forks_repo_head_hexsha": "bc4e15beb0b32ee65106b0795381f96c7ac25122", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8493150685, "max_line_length": 75, "alphanum_fraction": 0.5365622032, "num_tokens": 1027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109770159682, "lm_q2_score": 0.8479677602988602, "lm_q1q2_score": 0.8059178675436821}} {"text": "\"\"\"\n poisson_eigenvalues(N, L, dim, ::Periodic)\n\nReturn the eigenvalues satisfying the discrete form of Poisson's equation\nwith periodic boundary conditions along the dimension `dim` with `N` grid\npoints and domain extent `L`.\n\"\"\"\nfunction poisson_eigenvalues(N, L, dim, ::Periodic)\n inds = reshape(1:N, reshaped_size(N, dim)...)\n return @. (2sin((inds - 1) * π / N) / (L / N))^2\nend\n\n\"\"\"\n poisson_eigenvalues(N, L, dim, ::Bounded)\n\nReturn the eigenvalues satisfying the discrete form of Poisson's equation\nwith staggered Neumann boundary conditions along the dimension `dim` with\n`N` grid points and domain extent `L`.\n\"\"\"\nfunction poisson_eigenvalues(N, L, dim, ::Bounded)\n inds = reshape(1:N, reshaped_size(N, dim)...)\n return @. (2sin((inds - 1) * π / 2N) / (L / N))^2\nend\n\n\"\"\"\n poisson_eigenvalues(N, L, dim, ::Flat)\n\nNo need to do any transforms along `Flat` dimensions so just return zeros\nsince they will be added to the eigenvalues for other dimensions.\n\"\"\"\npoisson_eigenvalues(N, L, dim, ::Flat) = zeros(1, 1, 1)\n", "meta": {"hexsha": "c2cc5ebd22c522f59a33a7a5f3bdce1d84efe511", "size": 1044, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Solvers/poisson_eigenvalues.jl", "max_stars_repo_name": "charleskawczynski/Oceananigans.jl", "max_stars_repo_head_hexsha": "c34e6cd2166bbaa057186ffa795d348c1802485f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 393, "max_stars_repo_stars_event_min_datetime": "2020-05-07T19:20:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T02:09:52.000Z", "max_issues_repo_path": "src/Solvers/poisson_eigenvalues.jl", "max_issues_repo_name": "charleskawczynski/Oceananigans.jl", "max_issues_repo_head_hexsha": "c34e6cd2166bbaa057186ffa795d348c1802485f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1408, "max_issues_repo_issues_event_min_datetime": "2020-05-09T11:39:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:52:36.000Z", "max_forks_repo_path": "src/Solvers/poisson_eigenvalues.jl", "max_forks_repo_name": "charleskawczynski/Oceananigans.jl", "max_forks_repo_head_hexsha": "c34e6cd2166bbaa057186ffa795d348c1802485f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 99, "max_forks_repo_forks_event_min_datetime": "2020-05-10T02:59:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T21:50:55.000Z", "avg_line_length": 32.625, "max_line_length": 73, "alphanum_fraction": 0.6915708812, "num_tokens": 306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109812297141, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.805917865639486}} {"text": "## In this notebook, we'll look at stochastic gradient descent on a least squares\n## system\n\n##\nusing Plots\npyplot()\ntheme(:dark)\n##\n# https://vincentarelbundock.github.io/Rdatasets/csv/carData/Davis.csv\nusing CSV\ndf = CSV.read(download(\"https://vincentarelbundock.github.io/Rdatasets/csv/carData/Davis.csv\"))\nX = Float64.([df[:weight] df[:height]])\n# Filter the data\ngoodpts = X[:,1] .<= 115\nXf = X[goodpts,:]\n##\nscatter(Xf[:,1],Xf[:,2],label=\"\",xlabel=\"weight (kg)\", ylabel=\"height (cm)\")\n##\nx = Xf[:,1]\nA = [x ones(length(x))]\nb = Xf[:,2]\nab = A\\b # solve the least squares problem\n\n\n##\nusing Printf\nusing LinearAlgebra\n\"\"\" Run stochastic gradient descent to solve a least squares problem. \"\"\"\nfunction stochastic_gradient_descent_leastsquares(A,b;\n step=0.0001, maxiter=10*size(A,1),tol=1e-6)\n x = zeros(size(A,2)) # start at 0\n for i=1:1000000\n si = rand(1:size(A,1))\n ai = A[si,:]\n bi = b[si]\n g = 2.0.*(ai'*x - bi)*ai\n x -= step*g\n end\n return x\nend\nstochastic_gradient_descent_leastsquares(A,b)\n## Animate the algorithm\nquadratic_leastsq(A,b) = x-> (0.5*norm(A*x - b)^2)/size(A,1)\nezsurf(x, y, f) = begin\n X = repeat(x', length(y), 1)\n Y = repeat(y, 1, length(x))\n # Evaluate each f(x, y)\n Z = map((x,y) -> f([x,y]), X, Y)\n plot(x, y, Z, st=:surface)\nend\nezsurf(-3:0.1:3,-50:0.5:250,\n quadratic_leastsq(A,b))\nplot!(colorbar=false,size=(450,450),dpi=300)\nplot!(camera=(170,30))\nx = zeros(size(A,2)) # initialize\np = plot3d!(1, label=\"\", marker = 2)\nstep = 0.0001\nanim = Animation()\nfor i=0:1000000\n global x\n g = (A'*A*x - A'*b)/size(A,1)\n x -= step*g\n if ((i <= 10) || ((i <= 30) & (rem(i,2) == 0)) || ((i <= 100) && rem(i,5) == 0) ||\n ((i <= 1000) && rem(i,10) == 0) || ((i <=10000) && rem(i,100)==0) ||\n ((i <= 100000) && rem(i,1000)==0) || rem(i,10000)==0)\n push!(p[1][2], x[1], x[2], quadratic_leastsq(A,b)(x))\n title!(@sprintf(\"Iteration %3i Residual = %.3e\", i, norm(g)))\n @printf(\"Iteration %3i Residual = %.3e\\n\", i, norm(g))\n frame(anim)\n end\nend\ngif(anim, \"stochatic-grad-descent-1.gif\",fps=30)\n\n##\n## Animate the stochastic algorithm\nusing Random\nRandom.seed!(0)\nquadratic_leastsq(A,b) = x-> (0.5*norm(A*x - b)^2)/size(A,1)\nezsurf(x, y, f) = begin\n X = repeat(x', length(y), 1)\n Y = repeat(y, 1, length(x))\n # Evaluate each f(x, y)\n Z = map((x,y) -> f([x,y]), X, Y)\n plot(x, y, Z, st=:surface)\nend\nezsurf(-3:0.1:3,-50:0.5:250,\n quadratic_leastsq(A,b))\nplot!(colorbar=false,size=(450,450),dpi=300)\nplot!(camera=(170,30))\nx = zeros(size(A,2)) # initialize\nxgd = zeros(size(A,2)) # initialize\np = plot3d!(1, label=\"\", color=3)\np2 = plot3d!(1, label=\"\", color=2)\nstep = 0.0001\nanim = Animation()\nfor i=0:1000000\n global x, xgd\n si = rand(1:size(A,1))\n ai = A[si,:]\n bi = b[si]\n g = (ai'*x - bi)*ai\n x -= step*g\n\n xgd -= step*(A'*A*xgd - A'*b)/size(A,1)\n if ((i <= 10) || ((i <= 30) & (rem(i,2) == 0)) || ((i <= 100) && rem(i,5) == 0) ||\n ((i <= 1000) && rem(i,10) == 0) || ((i <=10000) && rem(i,100)==0) ||\n ((i <= 100000) && rem(i,1000)==0) || rem(i,10000)==0)\n push!(p[1][2], x[1], x[2], quadratic_leastsq(A,b)(x))\n push!(p[1][3], xgd[1], xgd[2], quadratic_leastsq(A,b)(xgd))\n title!(@sprintf(\"Iteration %3i Residual = %.3e\", i, norm(g)))\n @printf(\"Iteration %3i Residual = %.3e\\n\", i, norm(g))\n frame(anim)\n end\nend\ngif(anim, \"stochatic-grad-descent-2.gif\",fps=30)\n\n\n## Show the quadratic surface\nquadratic_leastsq(A,b) = x-> (0.5*norm(A*x - b)^2)\nezsurf(x, y, f) = begin\n X = repeat(x', length(y), 1)\n Y = repeat(y, 1, length(x))\n # Evaluate each f(x, y)\n Z = map((x,y) -> f([x,y]), X, Y)\n plot(x, y, Z, st=:surface)\nend\nezsurf(-3:0.1:3,-50:0.5:250,\n quadratic_leastsq(A,b))\n##\nplot!(colorbar=false,size=(300,300),dpi=300)\nanim = @animate for i=1:360\n plot!(camera=(i,30))\nend\ngif(anim, \"leastsq-quadratic.gif\")\n\n##\n## Show the quadratic surface with alpha-blending\nquadratic_leastsq(A,b) = x-> (0.5*norm(A*x - b)^2)\nezsurf(x, y, f) = begin\n X = repeat(x', length(y), 1)\n Y = repeat(y, 1, length(x))\n # Evaluate each f(x, y)\n Z = map((x,y) -> f([x,y]), X, Y)\n plot()\n plot!(x, y, Z, st=:surface)\nend\nezsurf(-3:0.1:3,-50:0.5:250,\n quadratic_leastsq(A,b))\n\n##\n## Show k random samples of the quadratic surface\nplotlyjs()\nquadratic_leastsq(A,b) = x-> (0.5*norm(A*x - b)^2)/size(A,1)\nezsurf!(x, y, f) = begin\n X = repeat(x', length(y), 1)\n Y = repeat(y, 1, length(x))\n # Evaluate each f(x, y)\n Z = map((x,y) -> f([x,y]), X, Y)\n plot!(x, y, Z, st=:surface, alpha=0.1)\nend\norig = ezsurf(-3:0.25:3,-50:1:250,\n quadratic_leastsq(A,b))\nnsamp = 25\nk = 25\nfor i=1:k\n subset = randperm(size(A,1))[1:25] # choose 25 of 200 samples.\n ezsurf!(-3:0.1:3,-50:0.5:250,\n quadratic_leastsq(A[subset,:],b[subset,:]))\nend\nplot!() # get the plot to show\n## Show k random samples of the quadratic surface\nusing Random\nusing LinearAlgebra\nplotlyjs()\nquadratic_leastsq(A,b) = x-> (0.5*norm(A*x - b)^2)/size(A,1)\nezsurf!(x, y, f) = begin\n X = repeat(x', length(y), 1)\n Y = repeat(y, 1, length(x))\n # Evaluate each f(x, y)\n Z = map((x,y) -> f([x,y]), X, Y)\n plot!(x, y, Z, st=:surface, alpha=0.4)\nend\nplot(framestyle=:none,colorbar=false,size=(300,300),dpi=300)\nnsamp = 10\nk = 25\nfor i=1:k\n subset = randperm(size(A,1))[1:nsamp] # choose 25 of 200 samples.\n ezsurf!(-3:0.25:3,-50:2:250,\n quadratic_leastsq(A[subset,:],b[subset,:]))\nend\nplot!() # get the plot to show\n##\n#plot!(colorbar=false,size=(300,300),dpi=300)\nplot!(colorbar=false,size=(900,900))\nanim = @animate for i=2:2:360\n plot!(camera=(i,30))\nend\ngif(anim, \"leastsq-quadratic-samples.gif\")\n\n\n## Show the same thing with a log10\nusing Random\nusing LinearAlgebra\nplotlyjs()\nquadratic_leastsq(A,b) = x-> log10(0.5*norm(A*x - b)^2)/size(A,1)\nplot(framestyle=:none,colorbar=false,size=(300,300),dpi=300)\nnsamp = 10\nk = 25\nfor i=1:k\n subset = randperm(size(A,1))[1:nsamp] # choose 25 of 200 samples.\n ezsurf!(-3:0.1:3,-50:0.5:250,\n quadratic_leastsq(A[subset,:],b[subset,:]))\nend\nplot!() # get the plot to show\n##\n#plot!(colorbar=false,size=(300,300),dpi=300)\nplot!(colorbar=false,size=(900,900))\nanim = @animate for i=2:2:360\n plot!(camera=(i,30))\nend\ngif(anim, \"leastsq-quadratic-samples-log.gif\")\n##\n", "meta": {"hexsha": "73d845f876578c4c9bb5c37b686cd8cc68d2e63a", "size": 6260, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "4-unit-3-demos/stochastic-gradient-descent.jl", "max_stars_repo_name": "dgleich/cs590-ncds", "max_stars_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-04-07T15:19:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T04:43:33.000Z", "max_issues_repo_path": "4-unit-3-demos/stochastic-gradient-descent.jl", "max_issues_repo_name": "dgleich/cs590-ncds", "max_issues_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4-unit-3-demos/stochastic-gradient-descent.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.0717488789, "max_line_length": 95, "alphanum_fraction": 0.5945686901, "num_tokens": 2424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308091776496, "lm_q2_score": 0.8633916082162403, "lm_q1q2_score": 0.8059163274944774}} {"text": "\n\"\"\"\n Exponential(lnℓ::AbstractFloat) <: RadialKernel{Euclidean}\n\nThe exponential kernel with length scale \n``\\\\exp(\\\\ln \\\\ell) = \\\\ell > 0``.\n\n```math\nk_{\\\\ell}(x, y) = k_{\\\\ell}(\\\\lVert x - y\\\\rVert_2) = \n\\\\exp\\\\bigg\\\\lbrace -\\\\frac{\\\\lVert x - y\\\\rVert_2}{\\\\ell}\\\\bigg\\\\rbrace\n```\n\"\"\"\nmutable struct Exponential{F<:AbstractFloat} <: RadialKernel{Euclidean}\n dist::Euclidean\n lnℓ::F\n ℓ::F\n function Exponential(dist::Euclidean, lnℓ::AbstractFloat)\n new{typeof(lnℓ)}(dist, lnℓ, exp(lnℓ))\n end\nend\n\nExponential(lnℓ::AbstractFloat) = Exponential(Euclidean(), lnℓ)\n\n@inline (k::Exponential)(τ::AbstractFloat) = exp(-τ / k.ℓ)\n\nnumparams(::Exponential) = (1,)\nparamtypes(::Exponential{F}) where F = (F,)\nparams(k::Exponential) = (lnℓ = k.lnℓ,)\nfunction setparams!(k::Exponential{F}, lnℓ::F) where F\n k.lnℓ = lnℓ\n k.ℓ = exp(lnℓ)\nend\n\n\n", "meta": {"hexsha": "ea3c4332559a9ce1c2162e87c6d6037e5b1bd70a", "size": 861, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels/radial/Exponential.jl", "max_stars_repo_name": "cameton/SKI.jl", "max_stars_repo_head_hexsha": "23b181da99b00b7f1a345ec1004c126624c508ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernels/radial/Exponential.jl", "max_issues_repo_name": "cameton/SKI.jl", "max_issues_repo_head_hexsha": "23b181da99b00b7f1a345ec1004c126624c508ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernels/radial/Exponential.jl", "max_forks_repo_name": "cameton/SKI.jl", "max_forks_repo_head_hexsha": "23b181da99b00b7f1a345ec1004c126624c508ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6, "max_line_length": 72, "alphanum_fraction": 0.6353077816, "num_tokens": 318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.8633916064586998, "lm_q1q2_score": 0.8059163274528056}} {"text": "function hypot(x::DoubleFloat{T}, y::DoubleFloat{T}) where {T<:IEEEFloat}\n ax = abs(x)\n ay = abs(y)\n ay, ax = minmax(ax, ay)\n\n r = ay\n if !iszero(ax)\n r /= ax\n end\n r *= r\n\n rr = ax * sqrt(one(DoubleFloat{T}) + r)\n\n # from Base\n # use type of rr to make sure that return type\n # is the same for all branches\n if isnan(ay)\n isinf(ax) && return oftype(rr, Inf)\n isinf(ay) && return oftype(rr, Inf)\n return oftype(rr, r)\n end\n return rr\n end\n\n\"\"\"\n normalize(x,y)\n\n x_normalized^2 + y_normalized^2 == one(promote_type(typeof(x),typeof(y)))\n\"\"\"\nfunction normalize(x::DoubleFloat{T}, y::DoubleFloat{T}) where {T<:IEEEFloat}\n hypotenuse = hypot(x, y)\n if !iszero(hypotenuse) && isfinite(hypotenuse)\n xnorm = x / hypotenuse\n ynorm = y / hypotenuse\n else\n # try for xnorm, ynorm such that xnorm + ynorm == 1\n xnorm = x/(x+y)\n ynorm = y/(x+y)\n end\n return xnorm, ynorm\nend\n", "meta": {"hexsha": "2b4537cfcf0e8a523e1f0a122bcaf6eeb0c3ee02", "size": 992, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/arithmetic/normalize_hypot.jl", "max_stars_repo_name": "UnofficialJuliaMirror/DoubleFloats.jl-497a8b3b-efae-58df-a0af-a86822472b78", "max_stars_repo_head_hexsha": "ccf0c6a690f81eec84caf080c99d58d11e72432d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 107, "max_stars_repo_stars_event_min_datetime": "2018-02-07T14:44:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T13:44:41.000Z", "max_issues_repo_path": "src/math/arithmetic/normalize_hypot.jl", "max_issues_repo_name": "UnofficialJuliaMirror/DoubleFloats.jl-497a8b3b-efae-58df-a0af-a86822472b78", "max_issues_repo_head_hexsha": "ccf0c6a690f81eec84caf080c99d58d11e72432d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 125, "max_issues_repo_issues_event_min_datetime": "2018-04-15T13:56:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:12:12.000Z", "max_forks_repo_path": "src/math/arithmetic/normalize_hypot.jl", "max_forks_repo_name": "UnofficialJuliaMirror/DoubleFloats.jl-497a8b3b-efae-58df-a0af-a86822472b78", "max_forks_repo_head_hexsha": "ccf0c6a690f81eec84caf080c99d58d11e72432d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 29, "max_forks_repo_forks_event_min_datetime": "2018-04-27T10:17:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T06:44:20.000Z", "avg_line_length": 23.619047619, "max_line_length": 77, "alphanum_fraction": 0.5675403226, "num_tokens": 317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541659378681, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.8059157979644224}} {"text": "\n\"\"\"\n create_ols_approximation(y::Vector{<:Real}, x::Vector{<:Real}, base_x::Real = 0.0, degree::Integer = 1, intercept::Bool = true)\n create_ols_approximation(y::Vector{<:Real}, x::Union{Vector{DateTime},Vector{Date},Vector{Union{Date,DateTime}}}, base_x::Union{Date,DateTime} = global_base_date, degree::Integer = 1, intercept::Bool = true)\n\nAn approximation function calculated via OLS.\n\n### Inputs\n* `y` - A `Vector` with the y coordinates\n* `x` - A `Vector` with the x coordinates\n* `base_x` - A real that offsets the x. So a coordinate with x value of 2.0 will be converted to 1.8 if base_x is 0.2.\n* `degree` - What the highest power of x should be. So if this is 3 then the equation will have x, x^2, x^3 as predictors.\n* `intercept` - Should there be an x intercept.\n### Returns\n* A `Sum_Of_Functions` containing the approximation function.\n\"\"\"\nfunction create_ols_approximation(y::Vector{<:Real}, x::Vector{<:Real}, base_x::Real = 0.0, degree::Integer = 1, intercept::Bool = true)\n obs = length(y)\n if degree < 0\n error(\"Cannot approximate with OLS with a degree that is negative\")\n end\n x = x .- base_x\n if intercept\n X = ones(obs)\n for i in 1:degree\n X = hcat(X, (x .^ i))\n end\n else\n X = x\n for i in 2:degree\n X = hcat(X, (x .^ i))\n end\n end\n\n lm1 = fit(LinearModel, hcat(X), y)\n beta = lm1.pp.beta0\n func_array = Array{PE_Function,1}(undef,convert(Int, intercept) + degree)\n if intercept\n func_array[1] = PE_Function(beta[1], 0.0, base_x, 0)\n end\n for d in 1:degree\n func_array[d+Integer(intercept)] = PE_Function(beta[d+Integer(intercept)], 0.0, base_x, d)\n end\n return Sum_Of_Functions(func_array)\nend\n\nfunction create_ols_approximation(y::Vector{<:Real}, x::Union{Vector{DateTime},Vector{Date},Vector{Union{Date,DateTime}}}, base_x::Union{Date,DateTime} = global_base_date, degree::Integer = 1, intercept::Bool = true)\n base = years_from_global_base.(base_x)\n xx = years_from_global_base.(x)\n return create_ols_approximation(y, xx, base, degree, intercept)\nend\n\nfunction get_cholesky_coefficients(chebyshev::Sum_Of_Functions, y::Vector{<:Real}, unnormalised_nodes::Vector{<:Real})\n chebyshev_on_nodes = evaluate.(Ref(chebyshev), unnormalised_nodes)\n a = sum(y .* chebyshev_on_nodes) / sum(chebyshev_on_nodes .^ 2)\n return a\nend\n\n\"\"\"\n create_chebyshev_approximation(func::Function, nodes::Integer, degree::Integer, left::Real, right::Real)\n\nAn function that will approximate another function via Chebyshev polynomials.\n\n### Inputs\n* `func` - A function that you want to approximation\n* `nodes` - The number of approximation nodes\n* `degree` - The degree of the Chebyshev polynomials.\n* `left` - The left limit of the approximation\n* `right` - The right limit of the approximation.\n### Returns\n* A `Sum_Of_Functions` containing the approximation function.\n\"\"\"\nfunction create_chebyshev_approximation(func::Function, nodes::Integer, degree::Integer, left::Real, right::Real)\n # This is all after Algorithm 6.2 from Judd (1998) Numerical Methods in Economics.\n if nodes <= degree\n error(\"Need to have more nodes than degree to use a chebyshev approximation\")\n end\n k = 1:nodes\n unnormalised_nodes = -cos.( (((2 .* k) .- 1) ./ (2 * nodes)) .* pi )\n normalised_nodes = ((unnormalised_nodes .+ 1) .* ((right-left)/2)) .+ left\n y = func.(normalised_nodes)\n chebyshevs = get_chevyshevs_up_to(degree, true)\n a = get_cholesky_coefficients.(chebyshevs, Ref(y), Ref(unnormalised_nodes))\n transformed_chebyshevs = convert_to_linearly_rescale_inputs.(chebyshevs, (right-left)/2, +(right+left)/2)\n # Note that these alpha and beta parameters in the convert_to_linearly_rescale_inputs function differ from those in Judd because those did not work in this context.\n all_terms = a .* transformed_chebyshevs\n final_func = Sum_Of_Functions(all_terms)\n return final_func\nend\n", "meta": {"hexsha": "dbdb26cc0dd39b9aad922afa3ef027bc3a1cedf7", "size": 3982, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/7_regressions_and_approximation.jl", "max_stars_repo_name": "s-baumann/UnivariateFunctions.jl", "max_stars_repo_head_hexsha": "9e1a67e99ce55b109c850f51bef2491fee205c4a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-09-18T17:53:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-18T17:53:21.000Z", "max_issues_repo_path": "src/7_regressions_and_approximation.jl", "max_issues_repo_name": "s-baumann/UnivariateFunctions.jl", "max_issues_repo_head_hexsha": "9e1a67e99ce55b109c850f51bef2491fee205c4a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-10-15T19:14:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T00:04:18.000Z", "max_forks_repo_path": "src/7_regressions_and_approximation.jl", "max_forks_repo_name": "s-baumann/UnivariateFunctions.jl", "max_forks_repo_head_hexsha": "9e1a67e99ce55b109c850f51bef2491fee205c4a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.2444444444, "max_line_length": 216, "alphanum_fraction": 0.6948769463, "num_tokens": 1163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541643004809, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.8059157931008721}} {"text": "\"\"\"\n psMF(lnν)\n\nPress-Schechter halo multiplicity function.\n\n*Reference*: Press & Schechter, 187, 425 (1974)\n- See also Bond, Cole, Efstathiou & Kaiser, ApJ, 379, 440 (1991)\n- See Sheth & Tormen, MNRAS, 329, 61 (2002) for the notation used here. `psMF(lnν)` corresponds to νf(ν) in this reference.\n\n# Arguments\n- `lnν::Real`: natural logarithm of a threshold, ν, i.e., `lnν` = log(ν), defined by ν ≡ [δc/σ(R)]^2. Here, δc = 1.6865 and σ(R) is the r.m.s. mass fluctuation within a top-hat smoothing of scale R.\n\nPress & Schechter's multiplicity function is normalized, i.e,\n\n``∫_-∞^∞ dlnν psMF(lnν) = 1``\n\nThis function is based on [Cosmology Routine Library (CRL)](https://wwwmpa.mpa-garching.mpg.de/~komatsu/crl/).\n\"\"\"\nfunction psMF(lnν::Real)\n ν = exp(lnν)\n mf = exp(-ν / 2) * √(ν / 2π)\nend\n\n\"\"\"\n stMF(lnν)\n\nSheth-Tormen halo multiplicity function.\n\n*Reference*: Equation (2) of Sheth & Tormen, MNRAS, 329, 61 (2002)\n- See also Sheth, Mo & Tormen, MNRAS, 323, 1 (2001)\n- `stMF(lnν)` corresponds to νf(ν) in these references\n\n# Arguments\n- `lnν::Real`: natural logarithm of a threshold, ν, i.e., `lnν` = log(ν), defined by ν ≡ [δc/σ(R)]^2. Here, δc = 1.6865 and σ(R) is the r.m.s. mass fluctuation within a top-hat smoothing of scale R.\n\nSheth & Tormen's multiplicity function is normalized, i.e,\n\n``∫_-∞^∞ dlnν stMF(lnν) = 1``\n\nThis function is based on [Cosmology Routine Library (CRL)](https://wwwmpa.mpa-garching.mpg.de/~komatsu/crl/).\n\"\"\"\nfunction stMF(lnν::Real)\n A, p, q = 0.3222, 0.3, 0.707\n ν = exp(lnν)\n mf = A * (1 + (q * ν)^-p) * exp(-q * ν / 2) * √(q * ν / 2π)\nend\n\n\"\"\"\n jenkinsMF(lnν)\n\nJenkins et al.'s halo multiplicity function.\n\n*Reference*: Equation (B3) of Jenkins et al., MNRAS, 321, 372 (2001)\n- `jenkinsMF(lnν)` corresponds to f(σ)/2 in this reference, where σ=√(δc/ν).\n- We use the fitting function for Δm = 180. Here, Δm is an overdensity within a spherical region of radius R, whose mean density is equal to Δm times the mean **mass** density of the Universe.\n\n# Arguments\n- `lnν::Real`: natural logarithm of a threshold, ν, i.e., `lnν` = log(ν), defined by ν ≡ [δc/σ(R)]^2. Here, δc = 1.6865 and σ(R) is the r.m.s. mass fluctuation within a top-hat smoothing of scale R.\n\nJenkins et al.'s multiplicity function is NOT normalized, i.e,\n\n``∫_-∞^∞ dlnν jenkinsMF(lnν) ≠ 1``\n\nThis function is based on [Cosmology Routine Library (CRL)](https://wwwmpa.mpa-garching.mpg.de/~komatsu/crl/).\n\"\"\"\nfunction jenkinsMF(lnν::Real)\n ν = exp(lnν)\n σ = 1.6865 / √ν\n mf = 0.5 * 0.301 * exp(-abs(log(1 / σ) + 0.64)^3.82)\nend\n", "meta": {"hexsha": "8a397031d5c2b64f68cdf769e3d4bb932d1ef40b", "size": 2566, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/classicMF.jl", "max_stars_repo_name": "komatsu5147/HaloMF.jl", "max_stars_repo_head_hexsha": "70a2329082fa4b797f7b1e3ab9891d74c72218c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/classicMF.jl", "max_issues_repo_name": "komatsu5147/HaloMF.jl", "max_issues_repo_head_hexsha": "70a2329082fa4b797f7b1e3ab9891d74c72218c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/classicMF.jl", "max_forks_repo_name": "komatsu5147/HaloMF.jl", "max_forks_repo_head_hexsha": "70a2329082fa4b797f7b1e3ab9891d74c72218c9", "max_forks_repo_licenses": ["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.1408450704, "max_line_length": 198, "alphanum_fraction": 0.6554949337, "num_tokens": 951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541544761566, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.8059157898859988}} {"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 \n if yb > ya\n a, b = b, a;\n ya, yb = yb, ya;\n s = -s;\n end\n\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\n a, ya, b, yb = b, yb, c, yc;\n s *= k;\n end\nend\n\n\n\n# test\n\nf1 = x -> (1 .+ x).^2;\nf2 = x -> (1 + x)^2;\nx = -3:0.1:3;\ny = f1(x);\n\na, b = bracket_minimum(f2, -2, 1e-2, 1.01);\n\nplot(x, y)\nvline!([a, b])\n", "meta": {"hexsha": "965346f287e14ef818396cd7f678ea958b25334b", "size": 543, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "bracketing/3.2-bracket_minimum.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.2-bracket_minimum.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.2-bracket_minimum.jl", "max_forks_repo_name": "tor4z/convex_optimization", "max_forks_repo_head_hexsha": "15fd3aa09fbc3306ff68cc301bbddac3d2006f3f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.6756756757, "max_line_length": 47, "alphanum_fraction": 0.3720073665, "num_tokens": 243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541577509315, "lm_q2_score": 0.8558511414521922, "lm_q1q2_score": 0.8059157857643374}} {"text": "\n\"\"\"\n angle(v::AbstractVector{<:Real}) -> Float\n\nAngle the vector `v` makes with the x axis, throws error if vector is not of size 2\n\"\"\"\nfunction angle(v::AbstractVector{<:Real})\n if length(v)!=2 error(\"Vector must be of length 2\") end\n atan(v[2],v[1])\nend\n\nangle(v::SVector{2, <:Real}) = atan(v[2],v[1])\n\n\"\"\"\n sqrt(z, branchcutangle::Real=π) -> typeof(z)\n\nReturn \\\\sqrt{x}, analytically continued from real line with the branch cut from 0 in a straight line along `branchcutangle`\n\"\"\"\nfunction sqrt(z, branchcutangle::Real)\n\n if branchcutangle > 0\n if angle(z) > branchcutangle return -sqrt(z) end\n else\n if angle(z) < branchcutangle return -sqrt(z) end\n end\n\n return sqrt(z)\nend\n\n\"\"\"\n round(num::Real, base::Real) -> Real\n\nNearest multiple of `base` to `num`, result will be promoted to num and base\n\"\"\"\nround(num::Real, base::Real) = round(num/base)*base\n\n\"\"\"\n ceil(num::Real, base::Real) -> Real\n\nSmallest multiple of `base` greater than `num`, result will be promoted to num and base\n\"\"\"\nceil(num::Real, base::Real) = ceil(num/base)*base\n\n\"\"\"\n ceil(num::Real, base::Real) -> Real\n\nLargest multiple of `base` smaller than `num`, result will be promoted to num and base\n\"\"\"\nfloor(num::Real, base::Real) = floor(num/base)*base\n\n", "meta": {"hexsha": "93e8f22e72a073b81d71d5aca7438c1851f95146", "size": 1278, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/maths.jl", "max_stars_repo_name": "jondea/JondeaUtils.jl", "max_stars_repo_head_hexsha": "09aec8840a4bbaaec3f5bfbd1a543ba60ab349a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/maths.jl", "max_issues_repo_name": "jondea/JondeaUtils.jl", "max_issues_repo_head_hexsha": "09aec8840a4bbaaec3f5bfbd1a543ba60ab349a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/maths.jl", "max_forks_repo_name": "jondea/JondeaUtils.jl", "max_forks_repo_head_hexsha": "09aec8840a4bbaaec3f5bfbd1a543ba60ab349a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0588235294, "max_line_length": 124, "alphanum_fraction": 0.6572769953, "num_tokens": 369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778073288128, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.8058610154523385}} {"text": "# Generates the dataset to be used in GMM example for EM course\n\nusing Plots, Distributions, Random, DataFrames, CSV\nRandom.seed!(123)\n\n# Set GMM parameters\nn = 200\nα = 0.4\nμ₀ = [-1, 2]\nμ₁ = [3.0, 7.0]\nΣ₀ = [2.0 1.0; 1.0 2.0]\nΣ₁ = [1.5 0; 0 0.5]\n𝒩₀ = MvNormal(μ₀, Σ₀)\n𝒩₁ = MvNormal(μ₁, Σ₁)\nX₁ = zeros(n)\nX₂ = zeros(n)\n\nfor i=1:n\n X₁[i],X₂[i] = rand() < α ? rand(𝒩₁) : rand(𝒩₀)\nend\n\n# Store in data frame\ndf = DataFrame(X1 = X₁, X2 = X₂)\n\n# Save to csv\nCSV.write(\"gmm_observations.csv\", df)\n", "meta": {"hexsha": "5b0ac913f9a82ffbb5e3f5c1b5a634294198ebfc", "size": 493, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "content/bayesian-inference-and-graphical-models/code/em_gmm_sample_generation.jl", "max_stars_repo_name": "seanrattana/courses", "max_stars_repo_head_hexsha": "9453abc38af26ea49cb00fe1744066fc0de237b3", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2019-08-21T07:33:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-24T15:46:58.000Z", "max_issues_repo_path": "content/bayesian-inference-and-graphical-models/code/em_gmm_sample_generation.jl", "max_issues_repo_name": "seanrattana/courses", "max_issues_repo_head_hexsha": "9453abc38af26ea49cb00fe1744066fc0de237b3", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-08-23T06:04:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-26T12:47:12.000Z", "max_forks_repo_path": "content/bayesian-inference-and-graphical-models/code/em_gmm_sample_generation.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": 18.2592592593, "max_line_length": 63, "alphanum_fraction": 0.6186612576, "num_tokens": 233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778024535095, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.805860999951786}} {"text": "# basisfunctions.jl\r\n\r\n\"\"\"\r\n fourier(k::Int)\r\n\r\nImplements the Fourier basis of functions ϕ_k, defined, if k is odd, by\r\nϕ_k(x)=sqrt(2)sin((k+1)π*x) and if k is even, by ϕ_k(x)=sqrt(2)cos(k*x).\r\nThis function is defined for k≥0 and ϕ_0≡1. \r\n\r\n# Examples\r\n\r\n```julia \r\nx = -1.0:0.01:2.0\r\ny = fourier(3).(x)\r\n```\r\n\"\"\"\r\nfunction fourier(k::Int)\r\n k ≥ 0 || throw(AssertionError(\"k should be non-negative\"))\r\n sqrttwo = sqrt(2.0)\r\n if k == 0\r\n return x -> 1.0\r\n elseif isodd(k)\r\n return x -> sqrttwo * sinpi(float(k+1)*x)\r\n else\r\n return x -> sqrttwo * cospi(float(k)*x)\r\n end\r\nend\r\n\r\n\"\"\"\r\n faberschauderone(x::Float64)\r\n\r\nImplements the first Faber-Schauder function defined by 1-2x for 0≤x≤1/2 and\r\n-1+2x for 0.5≤x≤1, and is 1-periodically extended to all x∈R.\r\n\r\n#See also: faberschauder\r\n\r\n#Warning\r\n\r\nNote the difference between faberschauderone and faberschauder. The first is a\r\nfunction that takes a Float64 and returns a Float64, the second takes (j,k) and\r\nreturns a anonymous function that takes a Float64 and returns a Float64.\r\n\r\n#Examples\r\n\r\n```julia\r\nx=-2.0:0.001:2.0\r\ny=faberschauderone.(x)\r\n```\r\n\"\"\"\r\nfunction faberschauderone(x::Float64)\r\n y = mod(x, 1.0)\r\n if 0≤y≤0.5\r\n return 1.0 - 2*y\r\n else\r\n return -1.0 + 2*y\r\n end\r\nend\r\n\r\n\"\"\"\r\n faberschauder(j::Int, k::Int)\r\n\r\nImplements the k-th Faber-Schauder function of level j. Here, j≥0 and 1≤k≤2^j.\r\nIt is a one periodic function and defined on [0,1] by 2^(j+1)(x-(k-1)2^(-j)) on\r\n(k-1)2^(-j)≤x≤(k-1/2)2^(-j) and 1 - 2^(j+1)(x-(k-1/2)2^(-j)) on\r\n[(k-1/2)2^(-j), k2^(-j)] and zero outside these intervals.\r\n\r\n# See also: faberschauderone.\r\n\r\n#Warning\r\n\r\nNote the difference between faberschauderone and faberschauder. The first is a\r\nfunction that takes a Float64 and returns a Float64, the second takes (j,k) and\r\nreturns a anonymous function that takes a Float64 and returns a Float64.\r\n\r\n#Example using PyPlot\r\n```julia\r\nusing PyPlot\r\nclf()\r\nj=3\r\nx=-2.0:0.001:2.0\r\nfor k in 1:2^j\r\n y = faberschauder(j,k).(x)\r\n plot(x,y)\r\nend\r\n```\r\n\"\"\"\r\nfunction faberschauder(j::Int,k::Int)\r\n j ≥ 0 || throw(AssertionError(\"j should be a nonnegative integer.\"))\r\n 1≤k≤2^j || throw(AssertionError(\"k should be an integer between 1 and 2^j.\"))\r\n twotothepowerminusj = 2.0^-j\r\n k_float = float(k)\r\n j_float = float(j)\r\n return function(x::Float64)\r\n y = mod(x,1.0)\r\n if y ≤ (k_float-1.0)*twotothepowerminusj || y ≥ k_float*twotothepowerminusj\r\n return 0.0\r\n elseif (k_float-1.0)*twotothepowerminusj < y ≤ (k_float-0.5)*twotothepowerminusj\r\n return 2.0^(j_float+1.0)*y-2*k_float+2.0\r\n else\r\n return 2.0*k_float - 2.0^(j_float+1.0) * y\r\n end\r\n end\r\nend\r\n", "meta": {"hexsha": "8ef4905b7c5e879cdc7453a75e5bff4623b08a83", "size": 2689, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/version0dot6/basisfunctions.jl", "max_stars_repo_name": "Jan-van-Waaij/BayesianNonparametricStatistics", "max_stars_repo_head_hexsha": "8ab5c9f995d83528688f061212b2580a53c226ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/version0dot6/basisfunctions.jl", "max_issues_repo_name": "Jan-van-Waaij/BayesianNonparametricStatistics", "max_issues_repo_head_hexsha": "8ab5c9f995d83528688f061212b2580a53c226ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/version0dot6/basisfunctions.jl", "max_forks_repo_name": "Jan-van-Waaij/BayesianNonparametricStatistics", "max_forks_repo_head_hexsha": "8ab5c9f995d83528688f061212b2580a53c226ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8557692308, "max_line_length": 85, "alphanum_fraction": 0.6355522499, "num_tokens": 1005, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403979493139, "lm_q2_score": 0.8670357580842941, "lm_q1q2_score": 0.8058580600301514}} {"text": "### A Pluto.jl notebook ###\n# v0.12.18\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n quote\n local el = $(esc(element))\n global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n el\n end\nend\n\n# ╔═╡ 45f1331e-59b1-11eb-2bc0-c138b1421b55\nbegin\n\tusing Pkg\n\tPkg.activate(\".\")\n\tPkg.instantiate()\nend\n\n# ╔═╡ fc1a9e20-56aa-11eb-29b1-3be8043c6ede\nbegin\n\tusing Random\n\tRandom.seed!(0)\n\tusing Zygote\n\tusing LinearAlgebra\n\tusing Plots\n\tusing PlutoUI\n\tusing Images\n\tusing LaTeXStrings\nend\n\n# ╔═╡ 60a23536-59d0-11eb-368a-5588b71a6093\nmd\"# Curve fitting using AD\"\n\n# ╔═╡ 832e2c5a-59ce-11eb-32d7-85b05440f919\nmd\"## Problem Formulation\"\n\n# ╔═╡ e35400cc-56ad-11eb-2794-592020c6ac7e\nmd\"### The underlying mathematics of the problem\"\n\n# ╔═╡ 761fc420-57af-11eb-24b3-9728b06c482e\nmd\"We are trying to fit a function $f_{org}(x)$ to a polynomial function $f_{ML}(x)$\"\n\n# ╔═╡ 021f6506-57b1-11eb-2179-7b6f153fce2f\nmd\"$$f_{ML}(x_i) = \\displaystyle\\sum\\limits_{j=0}^nw_jx_i^j = w_0 + x_iw_1 + x_i^2w_2+\\ldots+x_i^nw_n$$\"\n\n# ╔═╡ df0e42cc-59be-11eb-367e-cf25ab5f105f\nmd\"so that $f_{org}(x_i) \\approx f_{ML}(x_i)$\"\n\n# ╔═╡ 2730398c-59bf-11eb-060e-276c0138395e\nmd\"We define $X, \\textbf{w}, \\textbf{y}$ for a more concise and all-round understanding of the problem,\"\n\n# ╔═╡ e50c3cc4-59b7-11eb-1479-8bba33d251fd\nmd\"$\\begin{gather}\nX=\n\\begin{bmatrix}\n1 & x_1 & \\ldots & x_1^n\\\\\n\\vdots & & \\ddots &\\vdots \\\\\n1 & x_m & & x_m^n\n\\end{bmatrix}\n\\quad\\quad\\quad\n\\textbf{w} = \\begin{bmatrix}\nw_o \\\\\nw_1 \\\\\n\\vdots\\\\\nw_n\n\\end{bmatrix}\n\\quad\\quad\\quad\n\\textbf{y} = \n\\begin{bmatrix}\ny_1 \\\\\ny_2 \\\\\n\\vdots\\\\\ny_m\n\\end{bmatrix}\n\\end{gather}$\"\n\n# ╔═╡ 51545508-59b9-11eb-3f94-59e743bfd1a8\nmd\" where,\n- The matrix $X$ is the data matrix. $X$ is a $(m\\times (n+1)) matrix$. $m$ is the number of data points and $n$ is the n is the degree of the plyonomial. The choice of this polynomial becomes clear in the next step.\n- The vector $\\textbf{w}$ represents the weights vector. $w_0$ the bias. $w_j$ is the weight corresponding to $x^j$.\n- The vector $\\textbf{y}$ represents the results vector. $y_i$ is the result of $x_i$ on applying the function $f$\"\n\n# ╔═╡ 70b0cea0-59ba-11eb-2ae9-439069c94467\nmd\"$\\begin{gather}\n\\begin{bmatrix}\ny_1 \\\\\ny_2 \\\\\n\\vdots\\\\\ny_m\n\\end{bmatrix}\n=\n\\begin{bmatrix}\n1 & x_1 & \\ldots & x_1^n\\\\\n\\vdots & & \\ddots &\\vdots \\\\\n1 & x_m & & x_m^n\n\\end{bmatrix}\n\\odot \n\\begin{bmatrix}\nw_o \\\\\nw_1 \\\\\n\\vdots\\\\\nw_n\n\\end{bmatrix}\n\\end{gather}$\"\n\n# ╔═╡ ea14bfa4-59ba-11eb-35a1-6548f64bed7e\nmd\"$\\begin{gather}\n\\quad \\quad \\\n\\begin{bmatrix}\ny_1 \\\\\ny_2 \\\\\n\\vdots\\\\\ny_m\n\\end{bmatrix}\n=\n\\begin{bmatrix}\nw_o + x_1\\times w_1 &\\ldots &+x_1^n \\times w_n\\\\\n\\vdots \\\\\nw_0 + x_m\\times w_1 &\\ldots &+x_m^n\\times w_n\n\\end{bmatrix}\n\\end{gather}$\"\n\n# ╔═╡ 32bb7c2c-59bc-11eb-0914-d99847d081a3\nload(download(\"https://thehritikjain.files.wordpress.com/2020/05/1_e4_ptjctmaofsrpzczbv-g-1.jpeg?w=935\"))\n\n# ╔═╡ d2ea16ee-57b7-11eb-2d27-f3c04343dc59\nmd\"Before we approach the real problem of solving the approximate function, we need a predicting function and loss function to evaluate good our approximation is.\"\n\n# ╔═╡ fa7fe6b4-59c1-11eb-2486-d90418eaee4a\nmd\"### Predict and loss functions : \"\n\n# ╔═╡ e8864a02-59c1-11eb-12ff-c9a4ffde849d\nmd\"#### Predict function \"\n\n# ╔═╡ bf75963a-56ac-11eb-2b34-21b724a59f96\nfunction predict(x, ω::Vector)\n\tn = length(ω)\n\tx_vec = [x^i for i= 0:n-1]\n\treturn dot(x_vec, ω)\nend\n\n# ╔═╡ c8a25b68-59c1-11eb-363f-0772ec4edbf2\nmd\"**Usage Example :**\"\n\n# ╔═╡ 10be275c-59c1-11eb-10dc-4becfaf27f8d\nbegin\n\t# Try changing the values\n\tlocal ω = rand(5) # 4 polynomial weight vector\n\tlocal x = 3. # input\n\tpredict(x, ω)\nend\t\n\n# ╔═╡ d928b270-59c1-11eb-09d0-a9c3c878fe2d\nmd\"#### Square Loss function \"\n\n# ╔═╡ 0129d404-57b8-11eb-3dde-efa8a687c1d4\nfunction sq_loss(func, X, ω::Vector) \n\tn = length(ω)\n\ty = func.(X)\n\tŷ = [predict(x, ω) for x in X]\n\treturn sum((y-ŷ).^2)/n\nend\n\n# ╔═╡ bc758f7c-59c1-11eb-3f4a-5b987c7c6e0b\nmd\"**Usage Example :**\"\n\n# ╔═╡ 55bd943c-59c1-11eb-19d3-a7bba6fcbd30\nbegin\n\tlocal ω = rand(5) # 4 polynomial weight vector\n\tlocal X = [3.] # input\n\tlocal loss = sq_loss(sin, X, ω)\nend\n\n# ╔═╡ 00f8133c-57be-11eb-19d0-33006b7bbb06\nmd\"## Data Generation\"\n\n# ╔═╡ 6d407f0e-59ce-11eb-0ed6-33f817c914a3\nmd\"Choose the number of data points : \"\n\n# ╔═╡ 4b28aee8-56ac-11eb-3be7-0de4e9cb211b\n@bind n Slider(0:10, show_value = true, default=8)\n\n# ╔═╡ e6d69724-57bf-11eb-0337-db41600a8ebc\nmd\"We define a function that we want to approximate. **org\\_func** is the original function. We are trying to approximate *sin(x)* here. You can try your own function that you want to approximat inside org\\_func and chnages will be reflected in rest of the notebook.\"\n\n# ╔═╡ 9801c9ca-57bf-11eb-3f30-93055ccd6a0f\nfunction org_func(x)\n\treturn sin(x)\nend\n\n# ╔═╡ 2fcaeb98-56b1-11eb-0198-a3a5088dc007\nbegin\n\tX = [x for x in range(randn(), 12, length = n)]\n\ty = org_func.(X) +0.1* randn((n))\n\tplot(-0.5:0.01:12, org_func.(-0.5:0.01:12), label = L\"sin(x)\")\n\tscatter!(X, y, label = \"data points\", title = \"Our Data points\")\nend\n\n# ╔═╡ bd151b36-56b1-11eb-03d1-094237a3bafa\nmd\"## Approximation\"\n\n# ╔═╡ c7c2e3f2-57be-11eb-15c0-dbe72c95d654\nmd\"We will try to solve the problem of approximating the function by two differnt ways:\n- Linear Algebra Methods\n- Gradient Descent using AD\"\n\n# ╔═╡ 377b50e4-57bf-11eb-1741-a73fda781579\nmd\" ### Approximation by Linear Algebra\"\n\n# ╔═╡ 50c00e44-59c4-11eb-2726-27bee50e4fdd\nmd\"$\\begin{gather}\n\\begin{bmatrix}\ny_1 \\\\\ny_2 \\\\\n\\vdots\\\\\ny_m\n\\end{bmatrix}\n=\n\\begin{bmatrix}\n1 & x_1 & \\ldots & x_1^n\\\\\n\\vdots & & \\ddots &\\vdots \\\\\n1 & x_m & & x_m^n\n\\end{bmatrix}\n\\odot \n\\begin{bmatrix}\nw_o \\\\\nw_1 \\\\\n\\vdots\\\\\nw_n\n\\end{bmatrix}\n\\end{gather}$\"\n\n# ╔═╡ 586240fe-59c4-11eb-1427-312c47374f8a\nmd\"$\n\\ \\ \\ \\\n\\begin{gather}\n\\begin{bmatrix}\nw_o \\\\\nw_1 \\\\\n\\vdots\\\\\nw_n\n\\end{bmatrix}\n=\n\\begin{bmatrix}\n1 & x_1 & \\ldots & x_1^n\\\\\n\\vdots & & \\ddots &\\vdots \\\\\n1 & x_m & & x_m^n\n\\end{bmatrix}^{-1}\n\\odot \n\\begin{bmatrix}\ny_1 \\\\\ny_2 \\\\\n\\vdots\\\\\ny_m\n\\end{bmatrix}\n\n\\end{gather}$\"\n\n# ╔═╡ 4f5c808e-57bf-11eb-2a7a-3995d6f8f866\nmd\"This may seem like a very viable method, but try considering the case where $X$ is invertible. It is left as an exercise to the reader.\"\n\n# ╔═╡ 5dd40e02-57bf-11eb-2764-0f3f2b95517b\nmd\" ### Approximation by Gradient Descent\"\n\n# ╔═╡ ea205094-59c9-11eb-0f04-818f051b7d1e\nmd\"We will be using gradient descent algorithm to find $\\textbf{w}$ here. We are tired of mathematics by now and we somehow want the differentaition to happen automatically(almost magically). We will be using **Automatic Differentation**(or a more intuitive name : **Algorthimic Differentiation**). While how automatic differintation works is another day's agenda, we can have a little taste of magic of what AD does for us.\"\n\n# ╔═╡ b13969a4-59ca-11eb-15d8-0f9b5f225fed\nmd\"The gradient of a function $f(x)$ at $x_0$ is defined as $\\displaystyle\\frac{df(x)}{dx}\\Bigg|_{x=x_0}$\n\n$f^\\prime(x_0) = \\displaystyle\\frac{df(x)}{dx}\\Bigg|_{x=x_0}$\"\n\n# ╔═╡ e4f40500-59cb-11eb-1020-3b345469fb1f\nmd\"The Zygote package gives us a *gradient* API that we can use to find gradients\"\n\n# ╔═╡ 88002972-59cc-11eb-3d75-ab7e7bb45954\nmd\"$f(x) = x^2+4x+1$\n$f^\\prime(x) = 2x+4$\n$f^\\prime(5) = 2\\times 5 + 4 = 14$\"\n\n# ╔═╡ 3255da08-59cc-11eb-0bdc-61a05344ad50\ngradient(x->x^2+4x+1, 5)\n\n# ╔═╡ cd6a28f8-59cc-11eb-28f8-35c3a04414d8\nmd\"$f(x, y) = x^2+y^2+3xy$\n$\\displaystyle\\frac{\\partial f(x,y)}{\\partial x} = 2x+3y$\n$\\displaystyle\\frac{\\partial f(x,y)}{\\partial y} = 2y+3x$\"\n\n# ╔═╡ 4506b2d0-59cc-11eb-22e2-5f43abeb3ccd\ngradient( (x,y) -> x^2 + y^2 + 3x*y, 2,3)\n\n# ╔═╡ 608cc19c-59cd-11eb-092d-558d322966c6\nmd\"A train step function that returns the updated weights vector $\\textbf{w}$\"\n\n# ╔═╡ 84566232-57bf-11eb-390b-f33370fbd9a3\nfunction train_step(func, X, ω, η)::typeof(ω)\n\tgrad = gradient(ω->sq_loss(func, X, ω), ω)[1]\n\tω -= η * grad\n\treturn ω\nend\n\n# ╔═╡ de0aeb62-59cd-11eb-3e5f-a7cb176093c9\nmd\"Choose the degree of polynomial of $f_{ML}(x)$. You may need to choose different $\\eta$ and number of epochs to account for the model change\"\n\n# ╔═╡ ae1c0e18-59cd-11eb-2e61-fbe810bd5fa0\n@bind n_model Slider(1:1:7, default = 4, show_value = true)\n\n# ╔═╡ 5c85511c-5811-11eb-0f2e-2352309f2261\n## Intializing weights\nω = rand(n_model+1)\n\n# ╔═╡ 11337388-57c1-11eb-3418-3979d91e6af2\nfunction train(func, X, ω, η, epochs)::typeof(ω)\n\tfor i = 1:1:epochs\n\t\tω = train_step(func, X, ω, η)\n\t\tloss = sq_loss(func, X, ω)\n\t\tif isnan(loss) || isinf(loss) || iszero(loss)\n\t\t\tthrow(DomainError(\"Loss cannot take $(loss) value\"))\n\t\tend\n\tend\n\treturn ω\nend\n\n# ╔═╡ d722598c-57c2-11eb-3452-531fb6522e34\nω_trained = train(org_func, X, ω, 7e-9, 1e6)\n\n# ╔═╡ 11d38860-59c6-11eb-06e2-b10697f21f1d\nmd\"It is upto the user to decide how much accuracy he wants given the time constraints\"\n\n# ╔═╡ 8b6bc65e-57c7-11eb-372f-bd6f700363e1\nloss = sq_loss(org_func, X, ω_trained)\n\n# ╔═╡ 328c4584-57c4-11eb-3cf5-a57e033cf574\npred = [predict(x, ω_trained) for x in -0.5:0.01:13]\n\n# ╔═╡ a0dfe352-57c3-11eb-348f-8380ee6b3caf\nbegin\n\tplot(-0.5:0.01:13, org_func.(-0.5:0.01:13), label = L\"f_{org}(x)\")\n\tscatter!(X, y, label = \"Orginal data points\")\n\tŷ = [predict(x, ω_trained) for x in X]\n\tscatter!(X, ŷ, label = \"Predicted data points\")\n\tplot!(-0.5:0.01:13, pred, label = L\"f_{ML}(x)\")\nend\n\n# ╔═╡ Cell order:\n# ╟─45f1331e-59b1-11eb-2bc0-c138b1421b55\n# ╟─fc1a9e20-56aa-11eb-29b1-3be8043c6ede\n# ╟─60a23536-59d0-11eb-368a-5588b71a6093\n# ╟─832e2c5a-59ce-11eb-32d7-85b05440f919\n# ╟─e35400cc-56ad-11eb-2794-592020c6ac7e\n# ╟─761fc420-57af-11eb-24b3-9728b06c482e\n# ╟─021f6506-57b1-11eb-2179-7b6f153fce2f\n# ╟─df0e42cc-59be-11eb-367e-cf25ab5f105f\n# ╟─2730398c-59bf-11eb-060e-276c0138395e\n# ╟─e50c3cc4-59b7-11eb-1479-8bba33d251fd\n# ╟─51545508-59b9-11eb-3f94-59e743bfd1a8\n# ╟─70b0cea0-59ba-11eb-2ae9-439069c94467\n# ╟─ea14bfa4-59ba-11eb-35a1-6548f64bed7e\n# ╟─32bb7c2c-59bc-11eb-0914-d99847d081a3\n# ╟─d2ea16ee-57b7-11eb-2d27-f3c04343dc59\n# ╟─fa7fe6b4-59c1-11eb-2486-d90418eaee4a\n# ╟─e8864a02-59c1-11eb-12ff-c9a4ffde849d\n# ╠═bf75963a-56ac-11eb-2b34-21b724a59f96\n# ╟─c8a25b68-59c1-11eb-363f-0772ec4edbf2\n# ╠═10be275c-59c1-11eb-10dc-4becfaf27f8d\n# ╟─d928b270-59c1-11eb-09d0-a9c3c878fe2d\n# ╠═0129d404-57b8-11eb-3dde-efa8a687c1d4\n# ╟─bc758f7c-59c1-11eb-3f4a-5b987c7c6e0b\n# ╠═55bd943c-59c1-11eb-19d3-a7bba6fcbd30\n# ╟─00f8133c-57be-11eb-19d0-33006b7bbb06\n# ╟─6d407f0e-59ce-11eb-0ed6-33f817c914a3\n# ╟─4b28aee8-56ac-11eb-3be7-0de4e9cb211b\n# ╟─e6d69724-57bf-11eb-0337-db41600a8ebc\n# ╠═9801c9ca-57bf-11eb-3f30-93055ccd6a0f\n# ╠═2fcaeb98-56b1-11eb-0198-a3a5088dc007\n# ╟─bd151b36-56b1-11eb-03d1-094237a3bafa\n# ╟─c7c2e3f2-57be-11eb-15c0-dbe72c95d654\n# ╟─377b50e4-57bf-11eb-1741-a73fda781579\n# ╟─50c00e44-59c4-11eb-2726-27bee50e4fdd\n# ╟─586240fe-59c4-11eb-1427-312c47374f8a\n# ╟─4f5c808e-57bf-11eb-2a7a-3995d6f8f866\n# ╟─5dd40e02-57bf-11eb-2764-0f3f2b95517b\n# ╟─ea205094-59c9-11eb-0f04-818f051b7d1e\n# ╟─b13969a4-59ca-11eb-15d8-0f9b5f225fed\n# ╟─e4f40500-59cb-11eb-1020-3b345469fb1f\n# ╟─88002972-59cc-11eb-3d75-ab7e7bb45954\n# ╠═3255da08-59cc-11eb-0bdc-61a05344ad50\n# ╟─cd6a28f8-59cc-11eb-28f8-35c3a04414d8\n# ╠═4506b2d0-59cc-11eb-22e2-5f43abeb3ccd\n# ╟─608cc19c-59cd-11eb-092d-558d322966c6\n# ╠═84566232-57bf-11eb-390b-f33370fbd9a3\n# ╟─de0aeb62-59cd-11eb-3e5f-a7cb176093c9\n# ╟─ae1c0e18-59cd-11eb-2e61-fbe810bd5fa0\n# ╠═5c85511c-5811-11eb-0f2e-2352309f2261\n# ╠═11337388-57c1-11eb-3418-3979d91e6af2\n# ╠═d722598c-57c2-11eb-3452-531fb6522e34\n# ╟─11d38860-59c6-11eb-06e2-b10697f21f1d\n# ╠═8b6bc65e-57c7-11eb-372f-bd6f700363e1\n# ╠═328c4584-57c4-11eb-3cf5-a57e033cf574\n# ╟─a0dfe352-57c3-11eb-348f-8380ee6b3caf\n", "meta": {"hexsha": "6f9f25a63d19cf54c6cfc74f93f7e0756d71fc4d", "size": 11692, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Study_Session_1/notebooks/Curve_Fitting.jl", "max_stars_repo_name": "khanfarhan10/Study-Group", "max_stars_repo_head_hexsha": "5e5e9c74890a2f31ad9cb67b199db9eac6b6444a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-01-15T11:06:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-31T20:22:13.000Z", "max_issues_repo_path": "Study_Session_1/notebooks/Curve_Fitting.jl", "max_issues_repo_name": "chaitak-gorai/Study-Group", "max_issues_repo_head_hexsha": "add27a3c6b4d890816ea210b7377f1c5db3c1853", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-01-30T18:32:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-25T18:15:41.000Z", "max_forks_repo_path": "Study_Session_1/notebooks/Curve_Fitting.jl", "max_forks_repo_name": "chaitak-gorai/Study-Group", "max_forks_repo_head_hexsha": "add27a3c6b4d890816ea210b7377f1c5db3c1853", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-01-31T14:11:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-23T11:12:53.000Z", "avg_line_length": 28.8691358025, "max_line_length": 425, "alphanum_fraction": 0.7074923024, "num_tokens": 5656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070158103778, "lm_q2_score": 0.885631484383387, "lm_q1q2_score": 0.8058423010630029}} {"text": "### A Pluto.jl notebook ###\n# v0.17.1\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n quote\n local iv = try Base.loaded_modules[Base.PkgId(Base.UUID(\"6e696c72-6542-2067-7265-42206c756150\"), \"AbstractPlutoDingetjes\")].Bonds.initial_value catch; b -> missing; end\n local el = $(esc(element))\n global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el)\n el\n end\nend\n\n# ╔═╡ 1cdb4e08-99f7-48d9-924b-e105d1b266dc\nbegin\n using Plots; gr()\n\tusing Printf\n\tusing LaTeXStrings\n\tusing PlutoUI\n\tusing LinearAlgebra\n\timport Statistics: mean, cov\n\tusing MultivariateStats\n\tusing Random\n\t\n\tmd\"\"\"**Import julia libraries**\"\"\"\nend\n\n# ╔═╡ 721e5d79-4842-43cf-a2ff-4cf0fdb13f87\nbegin\n rng = MersenneTwister(220115)\n Base.show(io::IO, f::Float64) = @printf io \"%1.2f\" f\n\n\tmd\"\"\"Set the random seed and change the format of floating numbers for showing arrays.\"\"\"\nend\n\n# ╔═╡ 969a133a-9861-4248-92f0-757fd12f12fb\nmd\"# Principal Component Analysis (PCA): *A Physically Intuitive Mathematical Introduction*\n\nThe principal component analysis (PCA) involves rotating a cloud of data points in Euclidean space such that the variance is maximal along the first axis, the so-called first principal component. The principal axis theorem ensures that the data can be rotated in such away. In mathematical terms, the PCA involves finding an orthogonal linear coordinate transformation or, more generally, a new basis.\n\nThe mathematics behind the PCA is found again in the description of rotations of rigid bodies. This physical interpretation is instructive in understanding the PCA.\"\n\n# ╔═╡ 624fcb2a-8446-42c2-863f-e285f2c1fd86\nbegin\n\tN_slider = @bind N html\"\"\n\tR1_slider = @bind R1 html\"\"\n\tR2_slider = @bind R2 html\"\"\n\tangle_slider = @bind angle html\"\"\n\t\n\tmd\"\"\"## Define parameters to generate sample data\n\t\t\n\t\"\"\"\nend\n\n# ╔═╡ d8005539-13d5-4a3a-ad62-861c4f4bb9e0\nmd\"First, we will generate a cloud of $N$ randomly distributed data points in Euclidean space $\\mathbb{R}^n$ with coordinates $\\{ \\vec{x}^{(1)}, \\vec{x}^{(2)},\\dots, \\vec{x}^{(N)} \\} = X$. We will demonstrate the concept based on $3$-dimensional data, where $n=3$ and $X \\subset \\mathbb{R}^3$ with basis vectors $\\vec{e}_1$, $\\vec{e}_2$ and $\\vec{e}_3$ centered around the origin $(0, 0, 0)$. For simplicity, we will set all coordinates along the basis vector $\\vec{e}_3$ to zero. It will allow us to visualise the data in the $\\vec{e}_1$ and $\\vec{e}_2$ plane.\"\n\n# ╔═╡ 5619b1f9-38d1-42de-bd81-708567e2fa96\nmd\"\"\"\n**Define Parameters:**\n\n| | Min | Slider | Max |\n|-------|-----|:-------------:|-------|\n| N | 10 | $(N_slider) | 1000 |\n| R1 | 0.1 | $(R1_slider) | 10 |\n| R2 | 0.1 | $(R2_slider) | 10 |\n| angle | 0.0 |$(angle_slider)| 180 |\n\"\"\"\n\n# ╔═╡ 24f9bdd6-0337-4a23-9373-cfecabc2b029\nbegin\n\tRmax = max(R1, R2)\n\t\n\tmd\"\"\"\n\t\n\tN defines the number of points of the sample data. R1 and R2 define the\n\tvariance of the data and angle rotates the sample data in space.\n\n\t| Variable | N | R1 | R2 | angle | Rmax |\n\t|----------|----|-----|-----|-------|------|\n\t|**Values**| $(N) | $(R1) | $(R2) | $(round(angle, digits=2)) |$(Rmax) |\n\t\"\"\"\nend\n\n# ╔═╡ eacd1340-79af-4985-bf60-b8db8a380a20\nbegin\n\trot = [cos(deg2rad(angle)) sin(deg2rad(angle));\n\t\t -sin(deg2rad(angle)) cos(deg2rad(angle))]\n\t\n\tpts = randn(rng, N, 3)\n\tpts[:, 1] .*= R1\n\tpts[:, 2] .*= R2\n pts[:, 3] = zeros(N)\n\t\n\tpts[:, 1:2] = pts[:, 1:2] * rot\n\t\n\tmd\"\"\"Create $3$-dim array with sample data based on parameters defined in the table above.\n\t\n\t---\n\t\"\"\"\n\t\nend\n\n# ╔═╡ 6bcb1adc-633c-4730-b4e2-6b5b6f5237c4\nbegin\n\tlim = [-3 * Rmax, 3 * Rmax]\n\t\n\tu1 = [0.0 0.0; lim[2] lim[2]*tan(deg2rad(angle+90.0))]\n\tu1[2,:] = normalize!(u1[2,:])\n\tann1 = (u1[2,1].*2.5*Rmax, u1[2,2].*2.5*Rmax, Plots.text(L\"$\\mathbf{\\vec{u}_1}$\", :left))\n\t\n\tu2 = [0.0 0.0; lim[2] lim[2]*tan(deg2rad(angle))]\n\tu2[2,:] = normalize!(u2[2,:])\n\tann2 = (u2[2,1].*2.5*Rmax, u2[2,2].*2.5*Rmax, Plots.text(L\"$\\mathbf{\\vec{u}_2}$\", :left))\n\t\n\tl = @layout [ a{1.0w, 0.01h}\n\t [b{0.9w, 0.1h} _\n\t c{0.9w, 0.9h} d{0.1w, 0.9h}]]\n\n\ttitle = plot(title = \"Random Set of Points\",\n\t\t framestyle = :none,\n\t\t grid = false,\n\t\t showaxis = false,\n\t\t titlelocation = :center,\n\t\t bottom_margin = -40Plots.px)\n\t\n\th1 = histogram(pts[:,1],\n\t\t bins=range(lim[1], stop = lim[2], length = 20),\n\t\t normalize = true,\n\t\t fillcolor = \"#0044aa\",\n\t\t orientation = :vertical,\n\t\t framestyle = :none,\n\t title = L\"$a)$\",\n\t titlefontsize = 10,\n\t\t titlelocation=:left)\n\t\n\th2 = histogram(pts[:,2],\n\t\t bins=range(lim[1], stop = lim[2], length = 20),\n\t\t normalize = true,\n\t\t fillcolor = \"#0044aa\",\n\t\t orientation = :horizontal,\n\t\t framestyle = :none,\n\t title = L\"$c)$\",\n\t titlefontsize = 10,\n\t\t titlelocation=:right )\n\t\n\ts = scatter(pts[:,1], pts[:,2],\n\t\t markershape = :circle,\n\t\t markersize = 2,\n\t\t markercolor = \"#0044aa\",\n\t\t markerstrokecolor = \"#0044aa\",\n\t\t framestyle = :orign,\n\t\t xlabel = L\"\\vec{e}_1\",\n\t ylabel = L\"\\vec{e}_2\",\n\t\t xlims = (lim[1], lim[2]),\n\t\t ylims = (lim[1], lim[2]),\n\t\t aspect_ratio = :equal,\n\t\t title = L\"$b)$\",\n\t titlefontsize = 10,\n\t\t titlelocation=:left)\n\t\n\tplot(title, h1, s, h2,\n\t\t layout = l,\n\t\t legend = false,\n\t\t size = (600, 610))\n\n\tplot!(lim, lim*tan(deg2rad(angle)),\n\t\t color=\"#a6a6a6\",\n\t\t label=\"\",\n\t\t annotations = ann1,\n\t\t subplot = 3 )\n\t\n\tplot!(lim, lim*tan(deg2rad(angle+90.0)),\n\t\t color=\"#a6a6a6\",\n\t\t label=\"\",\n\t\t annotations = ann2,\n\t\t subplot = 3)\nend\n\n# ╔═╡ 075b42b8-476b-4436-a886-dcbb082b0ad7\nmd\"*Figure 1. a) Histogram of the random points distributed along $\\vec{e}_2$. b) Cloud of randomly distributed data points in Euclidean space $\\mathbb{R}^3$ with coordinates $\\{ \\vec{x}^{(1)}, \\vec{x}^{(2)},\\dots, \\vec{x}^{(N)} \\}$ with the basis vectors (axis in the plot b)) $\\vec{e}_1$ and $\\vec{e}_2$. The grey lines in plot b) indicate the principal axis $\\vec{u}_1$ and $\\vec{u}_2$. c) Histogram of the random points distributed along $\\vec{e}_1$. All values along $\\vec{e}_3$ are equal zero.*\n\n---\n\"\n\n# ╔═╡ 35f8cd6a-a87d-4af9-8590-3bcac79ef3ea\nmd\"## Moment of Inertia $\\boldsymbol{J}$\n\nThe moment of inertia $\\boldsymbol{J}$ of a rigid body, also called rotational inertia, determines the torque required for a desired angular acceleration around an axis of rotation. It depends on the mass distribution of the body and the selected axis of rotation. A body with a larger moment of inertia $\\boldsymbol{J}$ requires more torque to change the body's rate of rotation. For the same rigid body, different axes of rotation will have different moments of inertia associated with them. In other words, it depends on the body's mass distribution and the axis chosen, with larger moments requiring more torque to change the body's rotation rate.\n\nAll moments of inertia of a rigid body can be summarised by a matrix. In general, it can be determined with respect to any point in space. For simplicity, we will calculate the moment of inertia with respect to the center of mass.\n\nThe principal axes of the body, also known as figure axes, and the principal moments of inertia can be found by rotating the cloud of point masses. In mathematical terms, the PCA involves finding an orthogonal linear coordinate transformation or, more generally, a new basis.\n\nThe figure axis corresponding to the largest principal moment of inertia is the area vector of the plane with the maximal spread of mass points.\n\n| ![Rolling cylinder with different moments of inertia](https://upload.wikimedia.org/wikipedia/commons/9/95/RollingVsInertia.gif) | \n|:--| \n| *Figure 2. The six cylinders have the same mass but different moments of inertia $\\boldsymbol{J}$. As they roll down the slope, cylinders with lower moments of inertia accelerate more quickly. ([Image taken from wikipedia](https://en.wikipedia.org/wiki/File:RollingVsInertia.gif))* |\n\"\n\n# ╔═╡ 9ee5e06b-318b-4750-82bb-9db2999f2d1e\nmd\"## Visual Comparison of the Principal Axis in PCA and the Moment of Inertia\n\nIn the following, we will interpret the set of random data points from above in two ways. First, we interpret the data points $X$ as statistically distributed data with Covariance matrix $\\boldsymbol{C}$. Second, $X$ represents a set of point masses representing a rigid body with the Moment of Inertia matrix $\\boldsymbol{J}$. \n\n---\"\n\n# ╔═╡ 5a400a58-4bfb-49fe-8286-2b8e56803710\nbegin\n\tl2 = @layout [c{0.5w, 1.0h} d{0.5w, 1.0h}]\n\n\ts2 = scatter(pts[:,1], pts[:,2],\n\t\t markershape = :circle,\n\t\t markersize = 2,\n\t\t markercolor = \"#0044aa\",\n\t\t markerstrokecolor = \"#0044aa\",\n\t\t framestyle = :orign,\n\t\t xlabel = L\"\\vec{e}_1\",\n\t ylabel = L\"\\vec{e}_2\",\n\t\t xlims = (lim[1], lim[2]),\n\t\t ylims = (lim[1], lim[2]),\n\t\t aspect_ratio = :equal)\n\t\n\tplot(s2, s2,\n\t\t layout = l2,\n\t\t legend = false,\n\t\t size = (600, 310))\n\n\tplot!(lim, lim*tan(deg2rad(angle+90.0)),\n\t\t color=\"#a6a6a6\",\n\t\t label=\"\",\n\t\t annotations = ann1,\n\t\t subplot = 1,\n\t\t title = \"a) PCA\",\n\t titlefontsize = 12,\n\t\t titlelocation=:left )\n\n\tplot!( u1[:,1].*Rmax,\n\t\t u1[:,2].*Rmax,\n\t\t subplot = 1,\n\t\t arrow=true,color=\"#6a0000\",linewidth=3,label=\"\")\n\t\n\t\n\tplot!(lim, lim*tan(deg2rad(angle)),\n\t\t color=\"#a6a6a6\",\n\t\t label=\"\",\n\t\t annotations = ann2,\n\t\t subplot = 2,\n\t\t title = \"b) Moment of Inertia\",\n\t titlefontsize = 12,\n\t\t titlelocation=:left)\n\n\tplot!( u2[:,1].*Rmax,\n\t\t u2[:,2].*Rmax,\n\t\t subplot = 2,\n\t\t arrow=true, color=\"#01493e\",linewidth=3,label=\"\")\n\t\nend\n\n# ╔═╡ 07371ed0-72e9-47d9-82d8-6f3cb0e16ec8\nmd\" *Figure 3. a) PCA: The first principal component $\\vec{u}_1$ is along the axis where the variance is maximally indicated by a red arrow b) Moment of Inertia: The figure axis $\\vec{u}_2$ corresponding to the (actually second) largest principal moment of inertia indicated by a green arrow.*\n\n---\n\"\n\n# ╔═╡ 2f20596e-efa9-4d00-9769-6e8689c99f05\nmd\"With the visual support of *Figure 1* and *3*, we expect that the principal axes of the PCA and Moment of Inertia are the same. However, the value of the largest principal component and principal moment of inertia will differ for most sets of data points.\n\n> *Note:* In physics, the moment of inertia is defined for a $3$-dimensional rigid body. For simplicity, we projected the data into the plane spanned by $\\vec{e}_1$ and $\\vec{e}_2$. In our example, the plane with the maximal spread of mass points is then spaned by $\\vec{e}_1 and \\vec{e}_2$. The principal axis corresponding to the largest moment is pointing out of the plane along $\\vec{e}_3$ and is orthogonal to $\\vec{e}_1$ and $\\vec{e}_2$.\n\nThe line along $\\vec{u}_1$ is equivalent to the direction where the variance is maximal. In the following, we will support our visual understanding by exploring the PCA and moment of inertia mathematically.\n\"\n\n# ╔═╡ 03664f5c-d45c-11ea-21b6-91cd647a07aa\nmd\"## Definition of the Moment of Inertia of a Rigid Body\n\nFor a rigid object of $N$ point masses $m_i$ in $\\mathbb{R}^n$, the moment of inertia $\\boldsymbol{J}$ is given by\n\n$$\\begin{equation*}\n \\boldsymbol{J} = \n \\begin{bmatrix}\n J_{1,1} & \\cdots & J_{1,n} \\\\\n \\vdots & \\ddots & \\vdots \\\\\n J_{n,1} & \\cdots & J_{n,n} \n \\end{bmatrix}\n\\end{equation*}$$\n\nIts components are defined by Eq. (1) as\n\n$$\\begin{equation}\n J_{j,j'} =\n \\frac{1}{M}\n \\sum_{i=1}^{N} m_{i}\n \\left( ||\\vec{x}^{(i)}||^2 \\delta_{j,j'} - x_j^{(i)} x_{j'}^{(i)} \\right)\n\\end{equation}$$\n\nwhere $\\delta_{j,j'}$ is the Kronecker delta and $M = \\sum_{i}^{N} m_i$ is the total mass.\n\n> *Note:* Here, we normalize the moment of inertia by the total mass. In physics, the moment of inertia would not commonly be normalized like this.\n\nLooking closer, we see that $\\boldsymbol{J}$ is symmetric with $J_{j,j'} = J_{j',j}$. The spectral theorem tells us that $\\boldsymbol{J}$ has real eigenvalues $\\lambda$ and is diagonalisable by an orthogonal matrix (orthogonally diagonalizable).\n\"\n\n# ╔═╡ 2e1aa912-e7bd-4ffd-8060-05556a77bc8b\nmd\"## Definition of the Covariance Matrix\n\nThe covariance matrix $\\boldsymbol{C}$ for a cloud of points in Euclidean space centered around the mean is given by\n\n$$\\begin{equation*}\n \\boldsymbol{C} = \n \\begin{bmatrix}\n C_{1,1} & \\cdots & C_{1,n} \\\\\n \\vdots & \\ddots & \\vdots \\\\\n C_{n,1} & \\cdots & C_{n,n} \n \\end{bmatrix}\n\\end{equation*}$$\n\nIts components are defined by Eq. (2) as\n\n$$\\begin{equation}\n C_{j,j'} =\n \\frac{1}{N}\n \\sum_{i=1}^{N}\n \\left( x_j^{(i)} x_{j'}^{(i)} \\right)\n\\end{equation}$$\"\n\n# ╔═╡ 8c8167ca-8679-4d2a-b15b-4c8f32cfb8b6\nmd\"## Solving the Eigenvalue Problem\n\nThe principal axes of the PCA and moment of inertia can be determined by rotating the data points in space. More precisely, the principal components and axes are calculated by solving an eigenvalue problem.\n\nA real symmetric matrix (like $\\boldsymbol{C}$ and $\\boldsymbol{J}$ ) has the eigendecomposition into the product of a rotation matrix $\\boldsymbol{R}$ and a diagonal matrix $\\boldsymbol{\\Lambda}$\n\n$$\\begin{equation*}\n \\boldsymbol{\\Lambda} = \n \\begin{bmatrix}\n \\lambda_{1} & \\cdots & 0 \\\\\n \\vdots & \\ddots & \\vdots \\\\\n 0 & \\cdots & \\lambda_{n} \n \\end{bmatrix}\n\\end{equation*}$$\n\ngiven by\n\n$\\boldsymbol{J} = \\boldsymbol{R} \\boldsymbol{\\Lambda } \\boldsymbol{R}^T$\n\nThe columns of the rotation matrix $\\boldsymbol{R}$ define the directions of the principal axes, and the constants $\\lambda_{1}, \\dots, \\lambda_{n}$ are the diagonal elements of the matrix $\\boldsymbol{\\Lambda}$ and\nare called the principal moments.\n\nThe structure of the matrices $\\boldsymbol{J}$ and $\\boldsymbol{C}$ is the same except for the sign of the off-diagonal elements. We will see in the following that the eigenvectors will be the same for $\\boldsymbol{C}$ and $\\boldsymbol{J}$. In addition, we will see how the eigenvalues $\\boldsymbol{\\Lambda}$ of $\\boldsymbol{C}$ relate to the eigenvalues of $\\boldsymbol{J}$. \n\"\n\n# ╔═╡ 1d1d7052-977e-4180-af75-f1171f1492b2\nmd\"## Showing the Equality of the Eigenvectors of $\\boldsymbol{C}$ and $\\boldsymbol{J}$\n\nLet's rewrite the moment of inertia matrix $\\boldsymbol{J}$ defined by Eq. (1) in terms of the covariance matrix $\\boldsymbol{C}$ in Eq. (2).\n\n$$\\begin{equation}\n \\boldsymbol{J} = tr(\\boldsymbol{C})\\boldsymbol{I} - \\boldsymbol{C} \\qquad \\text{Eq. (3)}\n\\end{equation}$$\n\nwhere $\\boldsymbol{I}$ is the identity matrix.\n\n$$\\begin{align}\nJ_{j,j'} & = tr(\\boldsymbol{C})\\boldsymbol{I_{j,j}} - \\boldsymbol{C_{j,j'}} \\\\\n\n& = \\frac{1}{N} \\sum_{i=1}^{N} \\sum_{j=1}^{n} \\left( x_j^{(i)} x_{j}^{(i)} \\right) - \\frac{1}{N} \\sum_{i=1}^{N} \\left( x_j^{(i)} x_{j'}^{(i)} \\right)\\\\\n\n& = \\frac{1}{N} \\sum_{i=1}^{N} \\left( \\sum_{j=1}^{n} x_j^{(i)} x_{j}^{(i)} - x_j^{(i)} x_{j'}^{(i)} \\right)\\\\\n\n& = \\frac{1}{N} \\sum_{i=1}^{N} \\left( ||\\vec{x}^{(i)}||^2 \\delta_{j,j'} - x_j^{(i)} x_{j'}^{(i)} \\right) \\\\\n\n& \\text{multiply the expression under the sum by } 1 \\\\\n\n& = \\frac{1}{N} \\sum_{i=1}^{N} 1 \\cdot \\left( ||\\vec{x}^{(i)}||^2 \\delta_{j,j'} - x_j^{(i)} x_{j'}^{(i)} \\right) \\\\\n\n& \\text{assume each data point has mass } m_{i} = 1 \\\\\n\n\n& = \\frac{1}{\\sum_{i}^{N} m_i} \\sum_{i=1}^{N} m_{i} \\left( ||\\vec{x}^{(i)}||^2 \\delta_{j,j'} - x_j^{(i)} x_{j'}^{(i)} \\right) \\\\\n\n& = \\frac{1}{M} \\sum_{i=1}^{N} m_{i} \\left( ||\\vec{x}^{(i)}||^2 \\delta_{j,j'} - x_j^{(i)} x_{j'}^{(i)} \\right) \\\\\n\n\\end{align}$$\n\"\n\n# ╔═╡ 48d9a159-5725-4c8d-8a3f-334c0f6e24cf\nmd\"To obtain the eigenvectors and eigenvalues of $\\boldsymbol{C}$, we solve the eigenvalue problem by decomposing $\\boldsymbol{C}$ into the product of a rotation matrix $\\boldsymbol{R}$ and a diagonal matrix $\\boldsymbol{\\Lambda}_{cov}$\n\n$\\boldsymbol{C} = \\boldsymbol{R} \\boldsymbol{\\Lambda}_{cov} \\boldsymbol{R}^T,$\n\nwhere $\\boldsymbol{R}$ is composed of the eigenvectors $\\vec{v}^{j}$. In the case of a $3$-dimensional space\n\n$\\boldsymbol{R} = \\left[ \\vec{v}^{1} \\; \\vec{v}^{2} \\; \\vec{v}^{3} \\right]$\n\nand\n\n$$\\begin{equation*}\n \\boldsymbol{\\boldsymbol{\\Lambda}_{cov}} = \n \\begin{bmatrix}\n \\lambda^{1}_{cov} & 0 & 0 \\\\\n 0 & \\lambda^{2}_{cov} & 0 \\\\\n 0 & 0 & \\lambda^{3}_{cov}\n \\end{bmatrix}\n\\end{equation*}$$\n\n\nThe $j^{th}$ eigenvector $\\vec{v}^{j}$ and $j^{th}$ eigenvalue $\\lambda^{j}_{cov}$ of the covariance matrix $\\boldsymbol{C}$ are given by\n\n$$\\begin{equation}\n \\boldsymbol{C}\\lambda^{j}_{cov} = \\lambda^{j}_{cov} \\vec{v}^{j}.\n\\end{equation}$$\n\nIn the following, we will drop the index $j$ and rewrite the formula from above as $\\boldsymbol{C}\\lambda_{cov} = \\lambda_{cov} \\vec{v}$. Multiplying equation Eq. (3) by the eigenvector $\\vec{v}$ from the right side, we find Eq. (4).\n\n$$\\begin{align}\n \\boldsymbol{J}\\vec{v} &= \\left( tr(\\boldsymbol{C})\\boldsymbol{I} - \\boldsymbol{C} \\right) \\vec{v} \\\\\n &= tr(\\boldsymbol{C})\\boldsymbol{I}\\vec{v} - \\boldsymbol{C} \\vec{v} \\\\\n\n &= tr(\\boldsymbol{C})\\boldsymbol{I}\\vec{v} - \\lambda_{cov} \\vec{v} \\\\\n\n &= tr(\\boldsymbol{C})\\vec{v} - \\lambda_{cov} \\vec{v} \\\\\n\n &= \\left( tr(\\boldsymbol{C}) - \\lambda_{cov} \\right) \\vec{v} \\\\\n\n &= \\lambda_{J} \\vec{v} \\qquad \\qquad \\qquad \\qquad \\text{Eq. (4)}\\\\\n\\end{align}$$\n\nEq. (4) implies that $\\boldsymbol{C}$ and $\\boldsymbol{J}$ have the same eigenvectors $\\vec{v}$.\n\"\n\n# ╔═╡ 9e8ce452-78bc-4f1c-95fa-37be90c1006c\nmd\"## Calculating the Eigenvalues of the Moment of Inertia Matrix\n\nWhile the eigenvectors of $\\boldsymbol{C}$ and $\\boldsymbol{J}$ are the same, the eigenvalues are not the same. To relate them we will need to note that\n\n$tr\\left( \\boldsymbol{C} \\right)= tr \\left( \\boldsymbol{R} \\boldsymbol{\\Lambda}_{cov} \\boldsymbol{R}^T \\right) = \\sum_{j=1}^{n} \\lambda^{j}_{cov} \\qquad \\quad \\text{Eq. (5)}$\n\nwhere we have used that the trace of a matrix is invariant under cyclic permutations, so\n\n$$\n\\begin{align}\n tr \\left( \\boldsymbol{R} \\boldsymbol{\\Lambda}_{cov} \\boldsymbol{R}^T \\right) &= \n tr \\left( \\boldsymbol{R}^T \\boldsymbol{R} \\boldsymbol{\\Lambda}_{cov} \\right)\\\\\n &= tr \\left( \\boldsymbol{I} \\boldsymbol{\\Lambda}_{cov} \\right) \\\\\n &= \\sum_{j=1}^{n} \\lambda^{j}_{cov}\n\\end{align}$$\n\n\"\n\n# ╔═╡ d3eb6336-9e2e-4503-8fa1-f49385b45b40\nmd\"Using Eq. (4) and Eq. (5), we can write the eigenvalues $\\lambda_{J}$ of the moment of inertia $\\boldsymbol{J}$ (Eq. (1)) as\n\n$$\\begin{align}\n \\lambda^{k}_{J} &= tr(\\boldsymbol{C}) - \\lambda^{k}_{cov} \\\\\n &= \\sum_{j=1}^{n} \\lambda^{j}_{cov} - \\lambda^{k}_{cov} \\qquad \\text{Eq. (6)}\n \\end{align}$$\n\nWe see that the $k^{th}$ eigenvalue $\\lambda^{k}_{J}$ can be expressed in terms of the eigenvalues $\\lambda_{cov}$.\n\"\n\n# ╔═╡ a3da380d-b7db-4b7d-a348-bf3ef9b59e04\nmd\"\"\"Physically we can gain an intuitive understanding for the relation between these two sets of eigenvalues by considering that the covariance eigenvalue along e.g. axis $\\vec{v}^{(1)}$ are determined by the component of the data points in $(1)$ direction, while the moment of inertia around for a rotation around the axis $(1)$ is determined by the euclidean distance of the data points from that axis.\"\"\"\n\n# ╔═╡ 96b8d373-3ce1-460a-a70c-3f9e026bb783\nmd\"## Calculating Eigenvalues and Eigenvectors Using the Above Dataset $X$\"\n\n# ╔═╡ 42c9d5b9-7939-4f1f-b148-c9347acb3b3d\nmd\"Next, we calculate covariance matrix elements, eigenvalues, and eigenvectors. The covariance matrix $\\boldsymbol{C}$ of the dataset $X$ is\"\n\n# ╔═╡ cbdf4dd7-5710-47d9-91aa-8dbae9712e26\nC = cov(pts; corrected=false)\n\n# ╔═╡ be55c1dd-0b85-4192-bbbb-2f397fae1d49\nmd\"For the cavariance matrix $\\boldsymbol{C}$, we find the eigenvalues $\\lambda_{cov}$ and the eigenvectors $v_{cov}$\"\n\n# ╔═╡ d283412a-a3a3-458c-aa8b-63e1c4f3bf15\nλ_cov, v_cov = eigen(C; sortby=-)\n\n# ╔═╡ 4b17638d-1465-4b21-a2a3-61f94cbd0bca\nmd\"The eigenvalues $\\lambda_{cov}$ are\"\n\n# ╔═╡ 19378277-61f3-4d59-b840-452cfdf58a3b\nλ_cov\n\n# ╔═╡ 30513f7e-d866-4078-95e2-ab05bfbcf547\nmd\"and the eigenvectors $\\vec{v}_{cov}$ are\"\n\n# ╔═╡ 32191a9f-14ed-4bf6-a8ea-6586b117e848\nv_cov[:,1], v_cov[:,2], v_cov[:,3]\n\n# ╔═╡ 11c37b73-ddfd-41cf-98f4-c461b265d1bf\nmd\"Using Eq. (6), we can calculate the eigenvalues $\\lambda_{J}$ of $\\boldsymbol{J}$\"\n\n# ╔═╡ b20fed20-a678-450b-a689-a51baa337153\nsum(λ_cov)-λ_cov[1], sum(λ_cov)-λ_cov[2], sum(λ_cov)-λ_cov[3]\n\n# ╔═╡ abbd82f5-31cc-4f45-9c7c-f401796174cb\nmd\"## Calculating the Eigenvalues $\\lambda_{J}$ and Eigenvectors $\\vec{v}$ of $\\boldsymbol{J}$\"\n\n# ╔═╡ eaa487b9-2728-49f8-8b5e-003926f4d544\nδ(i, j) = i == j ? 1 : 0\n\n# ╔═╡ 3e6282ce-f3ba-4591-976d-0c37d14755c7\n\"\"\"\n\tcalcJ(pts::AbstractMatrix)\n\nCalculates the moment of inertia matrix ``\\\\boldsymbol{J}`` given a set of points `pts`\n\"\"\"\nfunction calcJ(pts::AbstractMatrix)\n\tN, n = size(pts)\n\tJ = zeros(Float64, n, n)\n\t\n\tfor j1 in 1:n\n\t\tfor j2 in j1:n\n\t\t\tJ[j1, j2] = sum(1:N) do i\n\t\t\t\tnorm(pts[i, :])^2 * δ(j1, j2) - pts[i, j1] * pts[i, j2]\n\t\t\tend\n\n\t\t\tJ[j2, j1] = J[j1, j2]\n\t\tend\n\tend\n\n\treturn J ./ N\nend\n\n# ╔═╡ 6b58bfb2-be89-4cd2-9c67-85ca95d02267\nJ = calcJ(pts)\n\n# ╔═╡ 51f20ae2-e0b6-410d-8783-689f6de9a025\nmd\"For the moment of inertia matrix $\\boldsymbol{J}$, we find the eigenvalues $\\lambda$ and the eigenvectors $v$\"\n\n# ╔═╡ 4b47a6af-3c41-4575-a576-09145c535e22\nλ, v = eigen(J; sortby=-)\n\n# ╔═╡ 1ad77ac0-bd4c-407f-858f-6e435085d4d8\nmd\"In both interpretations of the cloud of data points -- first as a cloud of points centered around the mean and second as a rigid body rotating around the center of mass -- we obtain the same eigenvectors.\"\n\n# ╔═╡ e54b7b64-ebbe-426d-92fa-4959eebba826\nbegin\n p1 = plot(title = \"Dataset and the (Scaled up) Eigenvectors\",\n\t xlims = (-3 * Rmax, 3 * Rmax),\n\t ylims = (-3 * Rmax, 3 * Rmax) )\n\t\n scatter!(pts[:,1], pts[:,2],\n\t\t markershape = :circle,\n\t\t markersize = 2,\n\t\t markercolor = \"#0044aa\",\n\t\t markerstrokecolor = \"#0044aa\",\n\t\t framestyle = :zerolines,\n\t\t xlabel = L\"\\vec{e}_1\",\n\t ylabel = L\"\\vec{e}_2\",\n\t\t aspect_ratio = :equal,\n\t\t label=\"Points\")\n\n\tplot!( [0, v_cov[1,1] * sqrt(λ_cov[1])*2],\n\t\t [0, v_cov[2,1] * sqrt(λ_cov[1])*2],\n\t\t arrow=true,color=\"#6a0000\",linewidth=3,label=\"\")\n\t\n\tplot!( [0, v_cov[1,2] * sqrt(λ_cov[2])*2],\n\t\t [0, v_cov[2,2] * sqrt(λ_cov[2])*2],\n\t\t arrow=true, color=\"#01493e\",linewidth=3,label=\"\")\nend\n\n# ╔═╡ b6c98fa0-8b40-4654-aa0c-b0204ed9e291\nmd\"*Figure 4. Cloud of randomly distributed data points $X$. Overlayed are the scaled eigenvectors (shown as red and green arrows).*\n\n---\n\"\n\n# ╔═╡ 3c8c50dc-7b25-48d3-84f2-c2e1a9fb85dd\nmd\"Next, we use the eigenvectors and eigenvalues to rotate the data and represent it in the new basis $v = v_{cov} = [\\vec{u}_1, \\vec{u}_2, \\vec{u}_3]$.\"\n\n# ╔═╡ fd8ce478-87a8-48aa-b8d1-df80df93254b\npts_rot = pts * v_cov\n\n# ╔═╡ 8d9840d1-1e71-403b-8935-c6aeca8a0ee0\nmd\"\n---\n\"\n\n# ╔═╡ 2be79841-4bfd-47d1-9c50-fd1e33a766c5\nbegin\n p2 = plot(title = \"Rotated Dataset\",\n\t xlims = (-3 * Rmax, 3 * Rmax),\n\t ylims = (-3 * Rmax, 3 * Rmax) )\n\t\n scatter!(pts_rot[:,1], pts_rot[:,2],\n\t\t markershape = :circle,\n\t\t markersize = 2,\n\t\t markercolor = :steelblue,\n\t\t markerstrokecolor = :steelblue,\n\t\t xlabel = L\"\\vec{u}_1\",\n\t ylabel = L\"\\vec{u}_2\",\n\t\t aspect_ratio = :equal,\n\t\t label=\"Points\")\n\n\tplot!( [0, v_cov[1,1]*10.0],\n\t\t [0, v_cov[2,1]*10.0],\n\t\t arrow=true,color=:grey,linewidth=3,label=\"\")\n\t\n\tplot!( [0, v_cov[1,2]*10.0],\n\t\t [0, v_cov[2,2]*10.0],\n\t\t arrow=true,color=:grey,linewidth=3,label=\"\")\nend\n\n# ╔═╡ 9a90438b-67c2-4024-bf45-696d60b718df\nmd\"*Figure 5. Cloud of randomly distributed data points $X$ represented in the basis spanned by the vectors $[\\vec{u}_1 \\; \\vec{u}_2 \\; \\vec{u}_3]$. The grey arrows indicate the old basis vectors $\\vec{e}_1$ and $\\vec{e}_2$ in this new basis.*\n\n---\n\"\n\n# ╔═╡ 14bf83f9-9a19-42e0-ba41-c6a16c58a89c\nmd\"\"\"## Final Thoughts\nIn machine learning and data science, PCA is used for two reasons.\nFirst, the accuracy and numeric stability of some Machine Learning algorithms are sensitive to correlated input data. In particular, Machine Learning algorithms that perform an inversion of the covariance matrix may experience the singularity problem -- Gaussian Mixture Models come to mind. A different example is the application of random forest algorithms to detect interactions between different features, where large correlations can mask these interactions. Performing a PCA first allows us to tease out the effect of correlations, which can improve feature importance analysis.\n\n\nSecond, PCA is used to reduce the dimensionality of the dataset, e.g. for data compression. In our example, we used a 3-dimensional dataset $X$, but the $\\vec{e}_3$ component did not carry any information (by construction). We could have used a PCA to justify dropping the third dimension since a PCA would have shown that the variance is minimal in the $\\vec{e}_3$ direction. Using the projection of a higher dimensional dataset onto a lower-dimensional space like this is a powerful tool to handle high-dimensional data and deal with the [curse of dimensionality](https://en.wikipedia.org/wiki/Curse_of_dimensionality).\n\nBoth applications of PCA have been extensively discussed. See recommendations for further reading below.\n\n\"\"\"\n\n# ╔═╡ 3b409a8a-b03a-41e6-9e14-b9f73af1847b\nmd\"## Further Reading\n 1. **Bauckhage, Christian & Dong, Tiansi** A Tutorial on Principal Component Analysis Part 1: Motivation (2018).\n 2. **Bauckhage, Christian & Dong, Tiansi** A Tutorial on Principal Component Analysis Part 2: Principal Axis via Moment of Inertia (2018).\n 3. **Hong, Liang** [The Proof of Equivalence between \\\" Moment of Inertia Based Method\\\" and \\\"PCA Based Method\\\" in LOS Detection](10.4028/www.scientific.net/AMR.945-949.2071) Advanced Materials Research. 945-949. 2071-2074 (2014).\n 4. **Murphy, Kevin P.** [Machine Learning A Probabilistic Perspective](https://isbnsearch.org/isbn/9780262018029), The MIT Press, Chapter 12.2 (2012)\n 5. **Marsland, Stephen** [Machine Learning An Algorithmic Perspective](https://isbnsearch.org/isbn/9781466583283), 2nd Edition, Chapman and Hall/CRC (2014)\n 6. [Badr, Will](https://medium.com/@will.badr) [Why Feature Correlation Matters …. A Lot!](https://towardsdatascience.com/why-feature-correlation-matters-a-lot-847e8ba439c4) Blog TowardsDataScience (2019).\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nLaTeXStrings = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nLinearAlgebra = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\nMultivariateStats = \"6f286f6a-111f-5878-ab1e-185364afe411\"\nPlots = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nPlutoUI = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nPrintf = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\nRandom = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\nStatistics = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[compat]\nLaTeXStrings = \"~1.3.0\"\nMultivariateStats = \"~0.8.0\"\nPlots = \"~1.23.6\"\nPlutoUI = \"~0.7.19\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\n[[AbstractPlutoDingetjes]]\ndeps = [\"Pkg\"]\ngit-tree-sha1 = \"0bc60e3006ad95b4bb7497698dd7c6d649b9bc06\"\nuuid = \"6e696c72-6542-2067-7265-42206c756150\"\nversion = \"1.1.1\"\n\n[[Adapt]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"84918055d15b3114ede17ac6a7182f68870c16f7\"\nuuid = \"79e6a3ab-5dfb-504d-930d-738a2a938a0e\"\nversion = \"3.3.1\"\n\n[[ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[Arpack]]\ndeps = [\"Arpack_jll\", \"Libdl\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"2ff92b71ba1747c5fdd541f8fc87736d82f40ec9\"\nuuid = \"7d9fca2a-8960-54d3-9f78-7d1dccf2cb97\"\nversion = \"0.4.0\"\n\n[[Arpack_jll]]\ndeps = [\"Libdl\", \"OpenBLAS_jll\", \"Pkg\"]\ngit-tree-sha1 = \"e214a9b9bd1b4e1b4f15b22c0994862b66af7ff7\"\nuuid = \"68821587-b530-5797-8361-c406ea357684\"\nversion = \"3.5.0+3\"\n\n[[Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[Bzip2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"19a35467a82e236ff51bc17a3a44b69ef35185a2\"\nuuid = \"6e34b625-4abd-537c-b88f-471c36dfa7a0\"\nversion = \"1.0.8+0\"\n\n[[Cairo_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"JLLWrappers\", \"LZO_jll\", \"Libdl\", \"Pixman_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"4b859a208b2397a7a623a03449e4636bdb17bcf2\"\nuuid = \"83423d85-b0ee-5818-9007-b63ccbeb887a\"\nversion = \"1.16.1+1\"\n\n[[ChainRulesCore]]\ndeps = [\"Compat\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"f885e7e7c124f8c92650d61b9477b9ac2ee607dd\"\nuuid = \"d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4\"\nversion = \"1.11.1\"\n\n[[ChangesOfVariables]]\ndeps = [\"LinearAlgebra\", \"Test\"]\ngit-tree-sha1 = \"9a1d594397670492219635b35a3d830b04730d62\"\nuuid = \"9e997f8a-9a97-42d5-a9f1-ce6bfc15e2c0\"\nversion = \"0.1.1\"\n\n[[ColorSchemes]]\ndeps = [\"ColorTypes\", \"Colors\", \"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"a851fec56cb73cfdf43762999ec72eff5b86882a\"\nuuid = \"35d6a980-a343-548e-a6ea-1d62b119f2f4\"\nversion = \"3.15.0\"\n\n[[ColorTypes]]\ndeps = [\"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"024fe24d83e4a5bf5fc80501a314ce0d1aa35597\"\nuuid = \"3da002f7-5984-5a60-b8a6-cbb66c0b333f\"\nversion = \"0.11.0\"\n\n[[Colors]]\ndeps = [\"ColorTypes\", \"FixedPointNumbers\", \"Reexport\"]\ngit-tree-sha1 = \"417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40\"\nuuid = \"5ae59095-9a9b-59fe-a467-6f913c188581\"\nversion = \"0.12.8\"\n\n[[Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"dce3e3fea680869eaa0b774b2e8343e9ff442313\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.40.0\"\n\n[[CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[Contour]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"9f02045d934dc030edad45944ea80dbd1f0ebea7\"\nuuid = \"d38c429a-6771-53c6-b99e-75d170b6e991\"\nversion = \"0.5.7\"\n\n[[DataAPI]]\ngit-tree-sha1 = \"cc70b17275652eb47bc9e5f81635981f13cea5c8\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.9.0\"\n\n[[DataStructures]]\ndeps = [\"Compat\", \"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"7d9d316f04214f7efdbb6398d545446e246eff02\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.18.10\"\n\n[[DataValueInterfaces]]\ngit-tree-sha1 = \"bfc1187b79289637fa0ef6d4436ebdfe6905cbd6\"\nuuid = \"e2d170a0-9d28-54be-80f0-106bbe20a464\"\nversion = \"1.0.0\"\n\n[[Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[DocStringExtensions]]\ndeps = [\"LibGit2\"]\ngit-tree-sha1 = \"b19534d1895d702889b219c382a6e18010797f0b\"\nuuid = \"ffbed154-4ef7-542d-bbb7-c09d3a79fcae\"\nversion = \"0.8.6\"\n\n[[Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[EarCut_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"3f3a2501fa7236e9b911e0f7a588c657e822bb6d\"\nuuid = \"5ae413db-bbd1-5e63-b57d-d24a61df00f5\"\nversion = \"2.2.3+0\"\n\n[[Expat_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b3bfd02e98aedfa5cf885665493c5598c350cd2f\"\nuuid = \"2e619515-83b5-522b-bb60-26c02a35a201\"\nversion = \"2.2.10+0\"\n\n[[FFMPEG]]\ndeps = [\"FFMPEG_jll\"]\ngit-tree-sha1 = \"b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8\"\nuuid = \"c87230d0-a227-11e9-1b43-d7ebe4e7570a\"\nversion = \"0.4.1\"\n\n[[FFMPEG_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"JLLWrappers\", \"LAME_jll\", \"Libdl\", \"Ogg_jll\", \"OpenSSL_jll\", \"Opus_jll\", \"Pkg\", \"Zlib_jll\", \"libass_jll\", \"libfdk_aac_jll\", \"libvorbis_jll\", \"x264_jll\", \"x265_jll\"]\ngit-tree-sha1 = \"d8a578692e3077ac998b50c0217dfd67f21d1e5f\"\nuuid = \"b22a6f82-2f65-5046-a5b2-351ab43fb4e5\"\nversion = \"4.4.0+0\"\n\n[[FixedPointNumbers]]\ndeps = [\"Statistics\"]\ngit-tree-sha1 = \"335bfdceacc84c5cdf16aadc768aa5ddfc5383cc\"\nuuid = \"53c48c17-4a7d-5ca2-90c5-79b7896eea93\"\nversion = \"0.8.4\"\n\n[[Fontconfig_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Expat_jll\", \"FreeType2_jll\", \"JLLWrappers\", \"Libdl\", \"Libuuid_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"21efd19106a55620a188615da6d3d06cd7f6ee03\"\nuuid = \"a3f928ae-7b40-5064-980b-68af3947d34b\"\nversion = \"2.13.93+0\"\n\n[[Formatting]]\ndeps = [\"Printf\"]\ngit-tree-sha1 = \"8339d61043228fdd3eb658d86c926cb282ae72a8\"\nuuid = \"59287772-0a20-5a39-b81b-1366585eb4c0\"\nversion = \"0.4.2\"\n\n[[FreeType2_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"87eb71354d8ec1a96d4a7636bd57a7347dde3ef9\"\nuuid = \"d7e528f0-a631-5988-bf34-fe36492bcfd7\"\nversion = \"2.10.4+0\"\n\n[[FriBidi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"aa31987c2ba8704e23c6c8ba8a4f769d5d7e4f91\"\nuuid = \"559328eb-81f9-559d-9380-de523a88c83c\"\nversion = \"1.0.10+0\"\n\n[[GLFW_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"Pkg\", \"Xorg_libXcursor_jll\", \"Xorg_libXi_jll\", \"Xorg_libXinerama_jll\", \"Xorg_libXrandr_jll\"]\ngit-tree-sha1 = \"0c603255764a1fa0b61752d2bec14cfbd18f7fe8\"\nuuid = \"0656b61e-2033-5cc2-a64a-77c0f6c09b89\"\nversion = \"3.3.5+1\"\n\n[[GR]]\ndeps = [\"Base64\", \"DelimitedFiles\", \"GR_jll\", \"HTTP\", \"JSON\", \"Libdl\", \"LinearAlgebra\", \"Pkg\", \"Printf\", \"Random\", \"Serialization\", \"Sockets\", \"Test\", \"UUIDs\"]\ngit-tree-sha1 = \"30f2b340c2fff8410d89bfcdc9c0a6dd661ac5f7\"\nuuid = \"28b8d3ca-fb5f-59d9-8090-bfdbd6d07a71\"\nversion = \"0.62.1\"\n\n[[GR_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"Cairo_jll\", \"FFMPEG_jll\", \"Fontconfig_jll\", \"GLFW_jll\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Libtiff_jll\", \"Pixman_jll\", \"Pkg\", \"Qt5Base_jll\", \"Zlib_jll\", \"libpng_jll\"]\ngit-tree-sha1 = \"fd75fa3a2080109a2c0ec9864a6e14c60cca3866\"\nuuid = \"d2c73de3-f751-5644-a686-071e5b155ba9\"\nversion = \"0.62.0+0\"\n\n[[GeometryBasics]]\ndeps = [\"EarCut_jll\", \"IterTools\", \"LinearAlgebra\", \"StaticArrays\", \"StructArrays\", \"Tables\"]\ngit-tree-sha1 = \"58bcdf5ebc057b085e58d95c138725628dd7453c\"\nuuid = \"5c1252a2-5f33-56bf-86c9-59e7332b4326\"\nversion = \"0.4.1\"\n\n[[Gettext_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"9b02998aba7bf074d14de89f9d37ca24a1a0b046\"\nuuid = \"78b55507-aeef-58d4-861c-77aaff3498b1\"\nversion = \"0.21.0+0\"\n\n[[Glib_jll]]\ndeps = [\"Artifacts\", \"Gettext_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Libiconv_jll\", \"Libmount_jll\", \"PCRE_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"a32d672ac2c967f3deb8a81d828afc739c838a06\"\nuuid = \"7746bdde-850d-59dc-9ae8-88ece973131d\"\nversion = \"2.68.3+2\"\n\n[[Graphite2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"344bf40dcab1073aca04aa0df4fb092f920e4011\"\nuuid = \"3b182d85-2403-5c21-9c21-1e1f0cc25472\"\nversion = \"1.3.14+0\"\n\n[[Grisu]]\ngit-tree-sha1 = \"53bb909d1151e57e2484c3d1b53e19552b887fb2\"\nuuid = \"42e2da0e-8278-4e71-bc24-59509adca0fe\"\nversion = \"1.0.2\"\n\n[[HTTP]]\ndeps = [\"Base64\", \"Dates\", \"IniFile\", \"Logging\", \"MbedTLS\", \"NetworkOptions\", \"Sockets\", \"URIs\"]\ngit-tree-sha1 = \"14eece7a3308b4d8be910e265c724a6ba51a9798\"\nuuid = \"cd3eb016-35fb-5094-929b-558a96fad6f3\"\nversion = \"0.9.16\"\n\n[[HarfBuzz_jll]]\ndeps = [\"Artifacts\", \"Cairo_jll\", \"Fontconfig_jll\", \"FreeType2_jll\", \"Glib_jll\", \"Graphite2_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\"]\ngit-tree-sha1 = \"129acf094d168394e80ee1dc4bc06ec835e510a3\"\nuuid = \"2e76f6c2-a576-52d4-95c1-20adfe4de566\"\nversion = \"2.8.1+1\"\n\n[[Hyperscript]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"8d511d5b81240fc8e6802386302675bdf47737b9\"\nuuid = \"47d2ed2b-36de-50cf-bf87-49c2cf4b8b91\"\nversion = \"0.0.4\"\n\n[[HypertextLiteral]]\ngit-tree-sha1 = \"2b078b5a615c6c0396c77810d92ee8c6f470d238\"\nuuid = \"ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2\"\nversion = \"0.9.3\"\n\n[[IOCapture]]\ndeps = [\"Logging\", \"Random\"]\ngit-tree-sha1 = \"f7be53659ab06ddc986428d3a9dcc95f6fa6705a\"\nuuid = \"b5f81e59-6552-4d32-b1f0-c071b021bf89\"\nversion = \"0.2.2\"\n\n[[IniFile]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"098e4d2c533924c921f9f9847274f2ad89e018b8\"\nuuid = \"83e8ac13-25f8-5344-8a64-a9f2b223428f\"\nversion = \"0.5.0\"\n\n[[InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[InverseFunctions]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"a7254c0acd8e62f1ac75ad24d5db43f5f19f3c65\"\nuuid = \"3587e190-3f89-42d0-90ee-14403ec27112\"\nversion = \"0.1.2\"\n\n[[IrrationalConstants]]\ngit-tree-sha1 = \"7fd44fd4ff43fc60815f8e764c0f352b83c49151\"\nuuid = \"92d709cd-6900-40b7-9082-c6be49f344b6\"\nversion = \"0.1.1\"\n\n[[IterTools]]\ngit-tree-sha1 = \"05110a2ab1fc5f932622ffea2a003221f4782c18\"\nuuid = \"c8e1da08-722c-5040-9ed9-7db0dc04731e\"\nversion = \"1.3.0\"\n\n[[IteratorInterfaceExtensions]]\ngit-tree-sha1 = \"a3f24677c21f5bbe9d2a714f95dcd58337fb2856\"\nuuid = \"82899510-4779-5014-852e-03e436cf321d\"\nversion = \"1.0.0\"\n\n[[JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"642a199af8b68253517b80bd3bfd17eb4e84df6e\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.3.0\"\n\n[[JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"8076680b162ada2a031f707ac7b4953e30667a37\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.2\"\n\n[[JpegTurbo_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"d735490ac75c5cb9f1b00d8b5509c11984dc6943\"\nuuid = \"aacddb02-875f-59d6-b918-886e6ef4fbf8\"\nversion = \"2.1.0+0\"\n\n[[LAME_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"f6250b16881adf048549549fba48b1161acdac8c\"\nuuid = \"c1c5ebd0-6772-5130-a774-d5fcae4a789d\"\nversion = \"3.100.1+0\"\n\n[[LZO_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"e5b909bcf985c5e2605737d2ce278ed791b89be6\"\nuuid = \"dd4b983a-f0e5-5f8d-a1b7-129d4a5fb1ac\"\nversion = \"2.10.1+0\"\n\n[[LaTeXStrings]]\ngit-tree-sha1 = \"f2355693d6778a178ade15952b7ac47a4ff97996\"\nuuid = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nversion = \"1.3.0\"\n\n[[Latexify]]\ndeps = [\"Formatting\", \"InteractiveUtils\", \"LaTeXStrings\", \"MacroTools\", \"Markdown\", \"Printf\", \"Requires\"]\ngit-tree-sha1 = \"a8f4f279b6fa3c3c4f1adadd78a621b13a506bce\"\nuuid = \"23fbe1c1-3f47-55db-b15f-69d7ec21a316\"\nversion = \"0.15.9\"\n\n[[LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[Libffi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"0b4a5d71f3e5200a7dff793393e09dfc2d874290\"\nuuid = \"e9f186c6-92d2-5b65-8a66-fee21dc1b490\"\nversion = \"3.2.2+1\"\n\n[[Libgcrypt_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgpg_error_jll\", \"Pkg\"]\ngit-tree-sha1 = \"64613c82a59c120435c067c2b809fc61cf5166ae\"\nuuid = \"d4300ac3-e22c-5743-9152-c294e39db1e4\"\nversion = \"1.8.7+0\"\n\n[[Libglvnd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"7739f837d6447403596a75d19ed01fd08d6f56bf\"\nuuid = \"7e76a0d4-f3c7-5321-8279-8d96eeed0f29\"\nversion = \"1.3.0+3\"\n\n[[Libgpg_error_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c333716e46366857753e273ce6a69ee0945a6db9\"\nuuid = \"7add5ba3-2f88-524e-9cd5-f83b8a55f7b8\"\nversion = \"1.42.0+0\"\n\n[[Libiconv_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"42b62845d70a619f063a7da093d995ec8e15e778\"\nuuid = \"94ce4f54-9a6c-5748-9c1c-f9c7231a4531\"\nversion = \"1.16.1+1\"\n\n[[Libmount_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"9c30530bf0effd46e15e0fdcf2b8636e78cbbd73\"\nuuid = \"4b2f31a3-9ecc-558c-b454-b3730dcb73e9\"\nversion = \"2.35.0+0\"\n\n[[Libtiff_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"JpegTurbo_jll\", \"Libdl\", \"Pkg\", \"Zlib_jll\", \"Zstd_jll\"]\ngit-tree-sha1 = \"340e257aada13f95f98ee352d316c3bed37c8ab9\"\nuuid = \"89763e89-9b03-5906-acba-b20f662cd828\"\nversion = \"4.3.0+0\"\n\n[[Libuuid_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"7f3efec06033682db852f8b3bc3c1d2b0a0ab066\"\nuuid = \"38a345b3-de98-5d2b-a5d3-14cd9215e700\"\nversion = \"2.36.0+0\"\n\n[[LinearAlgebra]]\ndeps = [\"Libdl\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[LogExpFunctions]]\ndeps = [\"ChainRulesCore\", \"ChangesOfVariables\", \"DocStringExtensions\", \"InverseFunctions\", \"IrrationalConstants\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"be9eef9f9d78cecb6f262f3c10da151a6c5ab827\"\nuuid = \"2ab3a3ac-af41-5b50-aa03-7779005ae688\"\nversion = \"0.3.5\"\n\n[[Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"3d3e902b31198a27340d0bf00d6ac452866021cf\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.9\"\n\n[[Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[MbedTLS]]\ndeps = [\"Dates\", \"MbedTLS_jll\", \"Random\", \"Sockets\"]\ngit-tree-sha1 = \"1c38e51c3d08ef2278062ebceade0e46cefc96fe\"\nuuid = \"739be429-bea8-5141-9913-cc70e7f3736d\"\nversion = \"1.0.3\"\n\n[[MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[Measures]]\ngit-tree-sha1 = \"e498ddeee6f9fdb4551ce855a46f54dbd900245f\"\nuuid = \"442fdcdd-2543-5da2-b0f3-8c86c306513e\"\nversion = \"0.3.1\"\n\n[[Missings]]\ndeps = [\"DataAPI\"]\ngit-tree-sha1 = \"bf210ce90b6c9eed32d25dbcae1ebc565df2687f\"\nuuid = \"e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28\"\nversion = \"1.0.2\"\n\n[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[MultivariateStats]]\ndeps = [\"Arpack\", \"LinearAlgebra\", \"SparseArrays\", \"Statistics\", \"StatsBase\"]\ngit-tree-sha1 = \"8d958ff1854b166003238fe191ec34b9d592860a\"\nuuid = \"6f286f6a-111f-5878-ab1e-185364afe411\"\nversion = \"0.8.0\"\n\n[[NaNMath]]\ngit-tree-sha1 = \"bfe47e760d60b82b66b61d2d44128b62e3a369fb\"\nuuid = \"77ba4419-2d1f-58cd-9bb1-8ffee604a2e3\"\nversion = \"0.3.5\"\n\n[[NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[Ogg_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"887579a3eb005446d514ab7aeac5d1d027658b8f\"\nuuid = \"e7412a2a-1a6e-54c0-be00-318e2571c051\"\nversion = \"1.3.5+1\"\n\n[[OpenBLAS_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Libdl\"]\nuuid = \"4536629a-c528-5b80-bd46-f80d51c5b363\"\n\n[[OpenSSL_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"15003dcb7d8db3c6c857fda14891a539a8f2705a\"\nuuid = \"458c3c95-2e84-50aa-8efc-19380b2a3a95\"\nversion = \"1.1.10+0\"\n\n[[Opus_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"51a08fb14ec28da2ec7a927c4337e4332c2a4720\"\nuuid = \"91d4177d-7536-5919-b921-800302f37372\"\nversion = \"1.3.2+0\"\n\n[[OrderedCollections]]\ngit-tree-sha1 = \"85f8e6578bf1f9ee0d11e7bb1b1456435479d47c\"\nuuid = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nversion = \"1.4.1\"\n\n[[PCRE_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b2a7af664e098055a7529ad1a900ded962bca488\"\nuuid = \"2f80f16e-611a-54ab-bc61-aa92de5b98fc\"\nversion = \"8.44.0+0\"\n\n[[Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"ae4bbcadb2906ccc085cf52ac286dc1377dceccc\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.1.2\"\n\n[[Pixman_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"b4f5d02549a10e20780a24fce72bea96b6329e29\"\nuuid = \"30392449-352a-5448-841d-b1acce4e97dc\"\nversion = \"0.40.1+0\"\n\n[[Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[PlotThemes]]\ndeps = [\"PlotUtils\", \"Requires\", \"Statistics\"]\ngit-tree-sha1 = \"a3a964ce9dc7898193536002a6dd892b1b5a6f1d\"\nuuid = \"ccf2f8ad-2431-5c83-bf29-c5338b663b6a\"\nversion = \"2.0.1\"\n\n[[PlotUtils]]\ndeps = [\"ColorSchemes\", \"Colors\", \"Dates\", \"Printf\", \"Random\", \"Reexport\", \"Statistics\"]\ngit-tree-sha1 = \"b084324b4af5a438cd63619fd006614b3b20b87b\"\nuuid = \"995b91a9-d308-5afd-9ec6-746e21dbc043\"\nversion = \"1.0.15\"\n\n[[Plots]]\ndeps = [\"Base64\", \"Contour\", \"Dates\", \"Downloads\", \"FFMPEG\", \"FixedPointNumbers\", \"GR\", \"GeometryBasics\", \"JSON\", \"Latexify\", \"LinearAlgebra\", \"Measures\", \"NaNMath\", \"PlotThemes\", \"PlotUtils\", \"Printf\", \"REPL\", \"Random\", \"RecipesBase\", \"RecipesPipeline\", \"Reexport\", \"Requires\", \"Scratch\", \"Showoff\", \"SparseArrays\", \"Statistics\", \"StatsBase\", \"UUIDs\", \"UnicodeFun\"]\ngit-tree-sha1 = \"0d185e8c33401084cab546a756b387b15f76720c\"\nuuid = \"91a5bcdd-55d7-5caf-9e0b-520d859cae80\"\nversion = \"1.23.6\"\n\n[[PlutoUI]]\ndeps = [\"AbstractPlutoDingetjes\", \"Base64\", \"Dates\", \"Hyperscript\", \"HypertextLiteral\", \"IOCapture\", \"InteractiveUtils\", \"JSON\", \"Logging\", \"Markdown\", \"Random\", \"Reexport\", \"UUIDs\"]\ngit-tree-sha1 = \"e071adf21e165ea0d904b595544a8e514c8bb42c\"\nuuid = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nversion = \"0.7.19\"\n\n[[Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"00cfd92944ca9c760982747e9a1d0d5d86ab1e5a\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.2\"\n\n[[Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[Qt5Base_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Fontconfig_jll\", \"Glib_jll\", \"JLLWrappers\", \"Libdl\", \"Libglvnd_jll\", \"OpenSSL_jll\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libxcb_jll\", \"Xorg_xcb_util_image_jll\", \"Xorg_xcb_util_keysyms_jll\", \"Xorg_xcb_util_renderutil_jll\", \"Xorg_xcb_util_wm_jll\", \"Zlib_jll\", \"xkbcommon_jll\"]\ngit-tree-sha1 = \"ad368663a5e20dbb8d6dc2fddeefe4dae0781ae8\"\nuuid = \"ea2cea3b-5b76-57ae-a6ef-0a8af62496e1\"\nversion = \"5.15.3+0\"\n\n[[REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[RecipesBase]]\ngit-tree-sha1 = \"44a75aa7a527910ee3d1751d1f0e4148698add9e\"\nuuid = \"3cdcf5f2-1ef4-517c-9805-6587b60abb01\"\nversion = \"1.1.2\"\n\n[[RecipesPipeline]]\ndeps = [\"Dates\", \"NaNMath\", \"PlotUtils\", \"RecipesBase\"]\ngit-tree-sha1 = \"7ad0dfa8d03b7bcf8c597f59f5292801730c55b8\"\nuuid = \"01d81517-befc-4cb6-b9ec-a95719d0359c\"\nversion = \"0.4.1\"\n\n[[Reexport]]\ngit-tree-sha1 = \"45e428421666073eab6f2da5c9d310d99bb12f9b\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.2.2\"\n\n[[Requires]]\ndeps = [\"UUIDs\"]\ngit-tree-sha1 = \"4036a3bd08ac7e968e27c203d45f5fff15020621\"\nuuid = \"ae029012-a4dd-5104-9daa-d747884805df\"\nversion = \"1.1.3\"\n\n[[SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[Scratch]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"0b4b7f1393cff97c33891da2a0bf69c6ed241fda\"\nuuid = \"6c6a2e73-6563-6170-7368-637461726353\"\nversion = \"1.1.0\"\n\n[[Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[Showoff]]\ndeps = [\"Dates\", \"Grisu\"]\ngit-tree-sha1 = \"91eddf657aca81df9ae6ceb20b959ae5653ad1de\"\nuuid = \"992d4aef-0814-514b-bc4d-f2e9a6c4116f\"\nversion = \"1.0.3\"\n\n[[Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[SortingAlgorithms]]\ndeps = [\"DataStructures\"]\ngit-tree-sha1 = \"b3363d7460f7d098ca0912c69b082f75625d7508\"\nuuid = \"a2af1166-a08f-5f64-846c-94a0d3cef48c\"\nversion = \"1.0.1\"\n\n[[SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[StaticArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"3c76dde64d03699e074ac02eb2e8ba8254d428da\"\nuuid = \"90137ffa-7385-5640-81b9-e52037218182\"\nversion = \"1.2.13\"\n\n[[Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[StatsAPI]]\ngit-tree-sha1 = \"1958272568dc176a1d881acb797beb909c785510\"\nuuid = \"82ae8749-77ed-4fe6-ae5f-f523153014b0\"\nversion = \"1.0.0\"\n\n[[StatsBase]]\ndeps = [\"DataAPI\", \"DataStructures\", \"LinearAlgebra\", \"LogExpFunctions\", \"Missings\", \"Printf\", \"Random\", \"SortingAlgorithms\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"eb35dcc66558b2dda84079b9a1be17557d32091a\"\nuuid = \"2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91\"\nversion = \"0.33.12\"\n\n[[StructArrays]]\ndeps = [\"Adapt\", \"DataAPI\", \"StaticArrays\", \"Tables\"]\ngit-tree-sha1 = \"2ce41e0d042c60ecd131e9fb7154a3bfadbf50d3\"\nuuid = \"09ab397b-f2b6-538f-b94a-2f83cf4a842a\"\nversion = \"0.6.3\"\n\n[[TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[TableTraits]]\ndeps = [\"IteratorInterfaceExtensions\"]\ngit-tree-sha1 = \"c06b2f539df1c6efa794486abfb6ed2022561a39\"\nuuid = \"3783bdb8-4a98-5b6b-af9a-565f29a5fe9c\"\nversion = \"1.0.1\"\n\n[[Tables]]\ndeps = [\"DataAPI\", \"DataValueInterfaces\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"TableTraits\", \"Test\"]\ngit-tree-sha1 = \"fed34d0e71b91734bf0a7e10eb1bb05296ddbcd0\"\nuuid = \"bd369af6-aec1-5ad0-b16a-f7cc5008161c\"\nversion = \"1.6.0\"\n\n[[Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[URIs]]\ngit-tree-sha1 = \"97bbe755a53fe859669cd907f2d96aee8d2c1355\"\nuuid = \"5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4\"\nversion = \"1.3.0\"\n\n[[UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[UnicodeFun]]\ndeps = [\"REPL\"]\ngit-tree-sha1 = \"53915e50200959667e78a92a418594b428dffddf\"\nuuid = \"1cfade01-22cf-5700-b092-accc4b62d6e1\"\nversion = \"0.4.1\"\n\n[[Wayland_jll]]\ndeps = [\"Artifacts\", \"Expat_jll\", \"JLLWrappers\", \"Libdl\", \"Libffi_jll\", \"Pkg\", \"XML2_jll\"]\ngit-tree-sha1 = \"3e61f0b86f90dacb0bc0e73a0c5a83f6a8636e23\"\nuuid = \"a2964d1f-97da-50d4-b82a-358c7fce9d89\"\nversion = \"1.19.0+0\"\n\n[[Wayland_protocols_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\"]\ngit-tree-sha1 = \"2839f1c1296940218e35df0bbb220f2a79686670\"\nuuid = \"2381bf8a-dfd0-557d-9999-79630e7b1b91\"\nversion = \"1.18.0+4\"\n\n[[XML2_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libiconv_jll\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"1acf5bdf07aa0907e0a37d3718bb88d4b687b74a\"\nuuid = \"02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a\"\nversion = \"2.9.12+0\"\n\n[[XSLT_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Libgcrypt_jll\", \"Libgpg_error_jll\", \"Libiconv_jll\", \"Pkg\", \"XML2_jll\", \"Zlib_jll\"]\ngit-tree-sha1 = \"91844873c4085240b95e795f692c4cec4d805f8a\"\nuuid = \"aed1982a-8fda-507f-9586-7b0439959a61\"\nversion = \"1.1.34+0\"\n\n[[Xorg_libX11_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\", \"Xorg_xtrans_jll\"]\ngit-tree-sha1 = \"5be649d550f3f4b95308bf0183b82e2582876527\"\nuuid = \"4f6342f7-b3d2-589e-9d20-edeb45f2b2bc\"\nversion = \"1.6.9+4\"\n\n[[Xorg_libXau_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4e490d5c960c314f33885790ed410ff3a94ce67e\"\nuuid = \"0c0b7dd1-d40b-584c-a123-a41640f87eec\"\nversion = \"1.0.9+4\"\n\n[[Xorg_libXcursor_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXfixes_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"12e0eb3bc634fa2080c1c37fccf56f7c22989afd\"\nuuid = \"935fb764-8cf2-53bf-bb30-45bb1f8bf724\"\nversion = \"1.2.0+4\"\n\n[[Xorg_libXdmcp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fe47bd2247248125c428978740e18a681372dd4\"\nuuid = \"a3789734-cfe1-5b06-b2d0-1dd0d9d62d05\"\nversion = \"1.1.3+4\"\n\n[[Xorg_libXext_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"b7c0aa8c376b31e4852b360222848637f481f8c3\"\nuuid = \"1082639a-0dae-5f34-9b06-72781eeb8cb3\"\nversion = \"1.3.4+4\"\n\n[[Xorg_libXfixes_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"0e0dc7431e7a0587559f9294aeec269471c991a4\"\nuuid = \"d091e8ba-531a-589c-9de9-94069b037ed8\"\nversion = \"5.0.3+4\"\n\n[[Xorg_libXi_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXfixes_jll\"]\ngit-tree-sha1 = \"89b52bc2160aadc84d707093930ef0bffa641246\"\nuuid = \"a51aa0fd-4e3c-5386-b890-e753decda492\"\nversion = \"1.7.10+4\"\n\n[[Xorg_libXinerama_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\"]\ngit-tree-sha1 = \"26be8b1c342929259317d8b9f7b53bf2bb73b123\"\nuuid = \"d1454406-59df-5ea1-beac-c340f2130bc3\"\nversion = \"1.1.4+4\"\n\n[[Xorg_libXrandr_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libXext_jll\", \"Xorg_libXrender_jll\"]\ngit-tree-sha1 = \"34cea83cb726fb58f325887bf0612c6b3fb17631\"\nuuid = \"ec84b674-ba8e-5d96-8ba1-2a689ba10484\"\nversion = \"1.5.2+4\"\n\n[[Xorg_libXrender_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"19560f30fd49f4d4efbe7002a1037f8c43d43b96\"\nuuid = \"ea2f1a96-1ddc-540d-b46f-429655e07cfa\"\nversion = \"0.9.10+4\"\n\n[[Xorg_libpthread_stubs_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"6783737e45d3c59a4a4c4091f5f88cdcf0908cbb\"\nuuid = \"14d82f49-176c-5ed1-bb49-ad3f5cbd8c74\"\nversion = \"0.1.0+3\"\n\n[[Xorg_libxcb_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"XSLT_jll\", \"Xorg_libXau_jll\", \"Xorg_libXdmcp_jll\", \"Xorg_libpthread_stubs_jll\"]\ngit-tree-sha1 = \"daf17f441228e7a3833846cd048892861cff16d6\"\nuuid = \"c7cfdc94-dc32-55de-ac96-5a1b8d977c5b\"\nversion = \"1.13.0+3\"\n\n[[Xorg_libxkbfile_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libX11_jll\"]\ngit-tree-sha1 = \"926af861744212db0eb001d9e40b5d16292080b2\"\nuuid = \"cc61e674-0454-545c-8b26-ed2c68acab7a\"\nversion = \"1.1.0+4\"\n\n[[Xorg_xcb_util_image_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"0fab0a40349ba1cba2c1da699243396ff8e94b97\"\nuuid = \"12413925-8142-5f55-bb0e-6d7ca50bb09b\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxcb_jll\"]\ngit-tree-sha1 = \"e7fd7b2881fa2eaa72717420894d3938177862d1\"\nuuid = \"2def613f-5ad1-5310-b15b-b15d46f528f5\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_keysyms_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"d1151e2c45a544f32441a567d1690e701ec89b00\"\nuuid = \"975044d2-76e6-5fbe-bf08-97ce7c6574c7\"\nversion = \"0.4.0+1\"\n\n[[Xorg_xcb_util_renderutil_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"dfd7a8f38d4613b6a575253b3174dd991ca6183e\"\nuuid = \"0d47668e-0667-5a69-a72c-f761630bfb7e\"\nversion = \"0.3.9+1\"\n\n[[Xorg_xcb_util_wm_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xcb_util_jll\"]\ngit-tree-sha1 = \"e78d10aab01a4a154142c5006ed44fd9e8e31b67\"\nuuid = \"c22f9ab0-d5fe-5066-847c-f4bb1cd4e361\"\nversion = \"0.4.1+1\"\n\n[[Xorg_xkbcomp_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_libxkbfile_jll\"]\ngit-tree-sha1 = \"4bcbf660f6c2e714f87e960a171b119d06ee163b\"\nuuid = \"35661453-b289-5fab-8a00-3d9160c6a3a4\"\nversion = \"1.4.2+4\"\n\n[[Xorg_xkeyboard_config_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Xorg_xkbcomp_jll\"]\ngit-tree-sha1 = \"5c8424f8a67c3f2209646d4425f3d415fee5931d\"\nuuid = \"33bec58e-1273-512f-9401-5d533626f822\"\nversion = \"2.27.0+4\"\n\n[[Xorg_xtrans_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"79c31e7844f6ecf779705fbc12146eb190b7d845\"\nuuid = \"c5fb5394-a638-5e4d-96e5-b29de1b5cf10\"\nversion = \"1.4.0+3\"\n\n[[Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[Zstd_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"cc4bf3fdde8b7e3e9fa0351bdeedba1cf3b7f6e6\"\nuuid = \"3161d3a3-bdf6-5164-811a-617609db77b4\"\nversion = \"1.5.0+0\"\n\n[[libass_jll]]\ndeps = [\"Artifacts\", \"Bzip2_jll\", \"FreeType2_jll\", \"FriBidi_jll\", \"HarfBuzz_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"5982a94fcba20f02f42ace44b9894ee2b140fe47\"\nuuid = \"0ac62f75-1d6f-5e53-bd7c-93b484bb37c0\"\nversion = \"0.15.1+0\"\n\n[[libfdk_aac_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"daacc84a041563f965be61859a36e17c4e4fcd55\"\nuuid = \"f638f0a6-7fb0-5443-88ba-1cc74229b280\"\nversion = \"2.0.2+0\"\n\n[[libpng_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Zlib_jll\"]\ngit-tree-sha1 = \"94d180a6d2b5e55e447e2d27a29ed04fe79eb30c\"\nuuid = \"b53b4c65-9356-5827-b1ea-8c7a1a84506f\"\nversion = \"1.6.38+0\"\n\n[[libvorbis_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Ogg_jll\", \"Pkg\"]\ngit-tree-sha1 = \"c45f4e40e7aafe9d086379e5578947ec8b95a8fb\"\nuuid = \"f27f6e37-5d2b-51aa-960f-b287f2bc3b7a\"\nversion = \"1.3.7+0\"\n\n[[nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\n[[x264_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"4fea590b89e6ec504593146bf8b988b2c00922b2\"\nuuid = \"1270edf5-f2f9-52d2-97e9-ab00b5d0237a\"\nversion = \"2021.5.5+0\"\n\n[[x265_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"ee567a171cce03570d77ad3a43e90218e38937a9\"\nuuid = \"dfaa095f-4041-5dcd-9319-2fabd8486b76\"\nversion = \"3.5.0+0\"\n\n[[xkbcommon_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\", \"Wayland_jll\", \"Wayland_protocols_jll\", \"Xorg_libxcb_jll\", \"Xorg_xkeyboard_config_jll\"]\ngit-tree-sha1 = \"ece2350174195bb31de1a63bea3a41ae1aa593b6\"\nuuid = \"d8fb68d0-12a3-5cfd-a85a-d49703b185fd\"\nversion = \"0.9.1+5\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─1cdb4e08-99f7-48d9-924b-e105d1b266dc\n# ╟─721e5d79-4842-43cf-a2ff-4cf0fdb13f87\n# ╟─969a133a-9861-4248-92f0-757fd12f12fb\n# ╟─624fcb2a-8446-42c2-863f-e285f2c1fd86\n# ╟─d8005539-13d5-4a3a-ad62-861c4f4bb9e0\n# ╟─5619b1f9-38d1-42de-bd81-708567e2fa96\n# ╟─24f9bdd6-0337-4a23-9373-cfecabc2b029\n# ╟─eacd1340-79af-4985-bf60-b8db8a380a20\n# ╟─6bcb1adc-633c-4730-b4e2-6b5b6f5237c4\n# ╟─075b42b8-476b-4436-a886-dcbb082b0ad7\n# ╟─35f8cd6a-a87d-4af9-8590-3bcac79ef3ea\n# ╟─9ee5e06b-318b-4750-82bb-9db2999f2d1e\n# ╟─5a400a58-4bfb-49fe-8286-2b8e56803710\n# ╟─07371ed0-72e9-47d9-82d8-6f3cb0e16ec8\n# ╟─2f20596e-efa9-4d00-9769-6e8689c99f05\n# ╟─03664f5c-d45c-11ea-21b6-91cd647a07aa\n# ╟─2e1aa912-e7bd-4ffd-8060-05556a77bc8b\n# ╟─8c8167ca-8679-4d2a-b15b-4c8f32cfb8b6\n# ╟─1d1d7052-977e-4180-af75-f1171f1492b2\n# ╟─48d9a159-5725-4c8d-8a3f-334c0f6e24cf\n# ╟─9e8ce452-78bc-4f1c-95fa-37be90c1006c\n# ╟─d3eb6336-9e2e-4503-8fa1-f49385b45b40\n# ╟─a3da380d-b7db-4b7d-a348-bf3ef9b59e04\n# ╟─96b8d373-3ce1-460a-a70c-3f9e026bb783\n# ╟─42c9d5b9-7939-4f1f-b148-c9347acb3b3d\n# ╠═cbdf4dd7-5710-47d9-91aa-8dbae9712e26\n# ╟─be55c1dd-0b85-4192-bbbb-2f397fae1d49\n# ╠═d283412a-a3a3-458c-aa8b-63e1c4f3bf15\n# ╟─4b17638d-1465-4b21-a2a3-61f94cbd0bca\n# ╠═19378277-61f3-4d59-b840-452cfdf58a3b\n# ╟─30513f7e-d866-4078-95e2-ab05bfbcf547\n# ╟─32191a9f-14ed-4bf6-a8ea-6586b117e848\n# ╟─11c37b73-ddfd-41cf-98f4-c461b265d1bf\n# ╠═b20fed20-a678-450b-a689-a51baa337153\n# ╟─abbd82f5-31cc-4f45-9c7c-f401796174cb\n# ╟─eaa487b9-2728-49f8-8b5e-003926f4d544\n# ╟─3e6282ce-f3ba-4591-976d-0c37d14755c7\n# ╠═6b58bfb2-be89-4cd2-9c67-85ca95d02267\n# ╟─51f20ae2-e0b6-410d-8783-689f6de9a025\n# ╠═4b47a6af-3c41-4575-a576-09145c535e22\n# ╟─1ad77ac0-bd4c-407f-858f-6e435085d4d8\n# ╟─e54b7b64-ebbe-426d-92fa-4959eebba826\n# ╟─b6c98fa0-8b40-4654-aa0c-b0204ed9e291\n# ╟─3c8c50dc-7b25-48d3-84f2-c2e1a9fb85dd\n# ╠═fd8ce478-87a8-48aa-b8d1-df80df93254b\n# ╟─8d9840d1-1e71-403b-8935-c6aeca8a0ee0\n# ╟─2be79841-4bfd-47d1-9c50-fd1e33a766c5\n# ╟─9a90438b-67c2-4024-bf45-696d60b718df\n# ╟─14bf83f9-9a19-42e0-ba41-c6a16c58a89c\n# ╟─3b409a8a-b03a-41e6-9e14-b9f73af1847b\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "8eead89098e7af714d29a21276d5138bf1855602", "size": 59958, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "pca.jl", "max_stars_repo_name": "lnemec/Intro2PCA", "max_stars_repo_head_hexsha": "8e1fbe91f310089769b00725a5d80791aa4588fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-01-23T22:48:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T14:57:14.000Z", "max_issues_repo_path": "pca.jl", "max_issues_repo_name": "lnemec/Intro2PCA", "max_issues_repo_head_hexsha": "8e1fbe91f310089769b00725a5d80791aa4588fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pca.jl", "max_forks_repo_name": "lnemec/Intro2PCA", "max_forks_repo_head_hexsha": "8e1fbe91f310089769b00725a5d80791aa4588fb", "max_forks_repo_licenses": ["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.2409937888, "max_line_length": 651, "alphanum_fraction": 0.7017578972, "num_tokens": 25096, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070035949656, "lm_q2_score": 0.8856314813647587, "lm_q1q2_score": 0.8058422874979781}} {"text": "function mean( img::AbstractArray{T,2} ) where {T<:Real}\n\n\tret = 0.0\n\tN = length( img );\n\n\t@simd for li in 1:N\n\t\t@inbounds ret += img[li]\n\tend\n\n\treturn ret/N\nend\n\nfunction variance( img::AbstractArray{T,2} ) where {T<:Real}\n\n\tmean = mean( img )\n\n\tret = 0.0\n\tN = length( img )\n\n\t@simd for li in 1:N\n\t\t@inbounds ret += ( img[li] - mean )*( img[li] - mean )\n\tend\n\n\treturn ret/N\nend\n\nfunction variance( img::AbstractArray{T,2}, mean ) where {T<:Real}\n\n\tret = 0.0\n\tN = length( img )\n\n\t@simd for li in 1:N\n\t\t@inbounds ret += ( img[li] - mean )*( img[li] - mean )\n\tend\n\n\treturn ret/N\nend\n\nfunction std( img::AbstractArray{T,2} ) where {T<:Real}\n\n\treturn sqrt( variance( img ) )\nend\n\nfunction std( img::AbstractArray{T,2}, mean ) where {T<:Real}\n\n\treturn sqrt( variance( img, mean ) )\nend\n\nfunction cov( img1::Array{T1,2}, img2::Array{T2,2}) where {T1<:Real,T2<:Real}\n\n\tlength( img1 ) !== length( img2 ) && ( error(\"Arrays have different lengths\") )\n\n\tm1 = mean( img1 )\n\ts1 = std( img1, m1 )\n\n\tm2 = mean( img2 )\n\ts2 = std( img2, m2 )\n\n\tret = 0.0\n\tN = length( img1 )\n\n\t@simd for li in 1:N\n\t\t@inbounds ret += ( img1[li] - m1 )*( img2[li] - m2 )\n\tend\n\n\treturn ret/N\nend\n\nfunction correlation( img1::Array{T1,2}, img2::Array{T2,2} ) where {T1<:Real,T2<:Real}\n\n\tlength( img1 ) !== length( img2 ) && ( error(\"Arrays have different lengths\") )\n\n\tm1 = mean( img1 )\n\ts1 = std( img1, m1 )\n\n\tm2 = mean( img2 )\n\ts2 = std( img2, m2 )\n\n\tret = 0.0\n\tN = length( img1 )\n\n\t@simd for li in 1:N\n\t\t@inbounds ret += ( img1[li] - m1 )*( img2[li] - m2 )\n\tend\n\n\treturn ret/(N*s1*s2)\nend\n\nfunction crossCorrelationZNCC( f::Array{T,2}, g::Array{T,2} ) where {T<:Real}\n\n\t\tlN = div( length( f ), 16 );\n\n\t\t# statstics for ZNCC\n\t\t#=\n\t\tmeanf = mean( f );\n\t\tmeanf2 = meanf * meanf;\n\n\t\tmeang = mean( g );\n\t\tmeang2 = meang * meang;\n\t\t=#\n\n\t\t# integral Arrays to compute stdf at each possible translation\n\t\tsumf = integralArray( f );\n\t\tsumf2 = integralArray( f, fun=(x)->(x*x) );\n\t\tsumg = integralArray( g );\n\t\tsumg2 = integralArray( g, fun=(x)->(x*x) );\n\n\t # correlation size = N + M - 1\n\t csize = size(f) .+ size(g) .- 1;\n\t h, w = csize;\n\t\tnum = zeros( Float32, csize ); # we compute the numerator with FFT for each cross-correlation element\n\t\tcorr = zeros( Float32, csize );\n\n\t\t#=\n\t\tpadf = zeros( Complex{T}, csize );\n\t\tpadf[ 1:size(f,1), 1:size(f,2) ] .= complex.( f .- meanf, 0.0 );\n\n\t\tpadg = zeros( Complex{T}, csize );\n\t\tpadg[ 1:size(g,1), 1:size(g,2) ] .= complex.( g .- meang, 0.0 );\n\n\t\tplan = plan_fft!( padf );\n\t\tiplan = plan_ifft!( padf );\n\n\t\t# cross-correlation ( f - meanf ) and ( g - meang ) with FFT\n\t\tplan * padf;\n\t\tplan * padg;\n\t\t@inbounds @simd for e in 1:length(padf)\n\t\t\tpadf[e] = conj( padf[e] ) * padg[e];\n\t\tend\n\n\t\tiplan * padf;\n\t\t@inbounds @simd for e in 1:length(padf)\n\t\t\tcorr[e] = real( padf[e] )\n\t\tend\n\n\t\tshifts = div.( csize, 2 ).- 1\n\t Base.circshift!( num, corr, shifts )\n\t\t=#\n\n\t\t# computing the denominator\n\t\t# Computing denominator through summed-area tables.\n\t @inbounds for col in 1:csize[2]\n\n\t\t\tminCol_g = 1 + max( 0, col - size(f,2) )\n\t\t\tmaxCol_g = min( col, size(g,2) )\n\n\t\t\t#\n\t\t\tminCol_f = max( 1, 1 + size(f,2) - col )\n\t maxCol_f = size(f,2) - max( 0, col - size(g,2) )\n\n\t\t\tlenCol_g = length( minCol_g:maxCol_g );\n\n\t for row in 1:csize[1]\n\n\t\t\t\tminRow_g = 1 + max( 0, row - size(f,1) );\n \tmaxRow_g = min( row, size(g,1) );\n\n\t\t\t\t#\n\t\t\t\tminRow_f = max( 1, 1 + size(f,1) - row )\n\t maxRow_f = size(f,1) - max( 0, row - size(g,1) )\n\n\t\t\t\tlenRow_g = length( minRow_g:maxRow_g )\n\t\t\t\tN = lenRow_g*lenCol_g\n\n\t\t\t\t#\n\t\t\t\tF, F2 = integralAreaZNCC( sumf, sumf2, row, col, size(f), size(g) )\n\t\t\t\tG, G2 = integralAreaZNCC( sumg, sumg2, row, col, size(g), size(g) )\n\n\t\t\t\t#\n\t\t\t\tmeanf = F/N;\n\t\t\t\tmeanf2 = meanf * meanf;\n\t\t\t\tstdf = sqrt( F2 + N*meanf2 - 2*F*meanf );\n\t\t\t\tmeang = G/N;\n\t\t\t\tmeang2 = meang * meang;\n\t\t\t\tstdg = sqrt( G2 + N*meang2 - 2*G*meang );\n\n\t\t\t\t#\n\t\t\t\tsubg = view( g, minRow_g:maxRow_g, minCol_g:maxCol_g )\n\t\t\t\tsubf = view( f, minRow_f:maxRow_f, minCol_f:maxCol_f )\n\n\t\t\t\t#\n\t\t\t\tzncc = 0.0\n\t\t\t\tfor e in 1:length(subg)\n\t\t\t\t\tzncc += ( subf[e] - meanf )*( subg[e] - meang )\n\t\t\t\tend\n\n\t\t\t\t#\n\t\t\t\tcorr[ row, col ] = zncc/(stdg*stdf)\n\n\t\t\t\t#=\n\t\t\t\tif N < lN\n\t\t\t\t\tcorr[ row, col ] = 0.0\n\t\t\t\telse\n\t\t F, F2 = integralAreaZNCC( sumf, sumf2, row, col, size(f), size(g) )\n\t\t\t\t\tG, G2 = integralAreaZNCC( sumg, sumg2, row, col, size(g), size(g) )\n\n\t\t corr[ row, col ] = num[ row, col ]/( sqrt( F2 + N*meanf2 - 2*F*meanf )*sqrt( G2 + N*meang2 - 2*G*meang ) );\n\t\t\t\tend\n\t\t\t\t=#\n\t end\n\t end\n\n\t\treturn corr;\nend\n", "meta": {"hexsha": "513eabc3b2b412cb8a63b5fab009c212814775fb", "size": 4574, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/stats.jl", "max_stars_repo_name": "Marc-3d/ImageAnalysis", "max_stars_repo_head_hexsha": "0e99582d05adbc905e6c217ea90b6ac171d41e18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/stats.jl", "max_issues_repo_name": "Marc-3d/ImageAnalysis", "max_issues_repo_head_hexsha": "0e99582d05adbc905e6c217ea90b6ac171d41e18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/stats.jl", "max_forks_repo_name": "Marc-3d/ImageAnalysis", "max_forks_repo_head_hexsha": "0e99582d05adbc905e6c217ea90b6ac171d41e18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.312195122, "max_line_length": 123, "alphanum_fraction": 0.5636204635, "num_tokens": 1783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.8807970889295663, "lm_q1q2_score": 0.8058421019041682}} {"text": "# # Helmholtz decomposition\n\n#md # ```@meta\n#md # CurrentModule = ImmersedLayers\n#md # ```\n\n#=\nFor vector fields on the grid, we often prefer to work with potentials\nof that field and compose the vector field from these potentials. This\nis the so-called Helmholtz decomposition\n\n$$\\mathbf{v} = \\nabla\\phi + \\nabla\\times\\psi$$\n\nwhere $\\psi$ is a vector potential (or streamfunction in two dimensions)\nand $\\phi$ is a scalar potential. Note that, in an unbounded domain, $\\phi$\nsatisfies a Poisson equation:\n\n$$\\nabla^2\\phi = \\nabla\\cdot\\mathbf{v}$$\n\nand, assuming that $\\psi$ has zero 'gauge' (i.e., its divergence is zero), then\n$\\psi$ also satisfies a Poisson equation:\n\n$$\\nabla^2\\psi = -\\nabla\\times\\mathbf{v}$$\n\nSo we can recover the velocity field from the divergence and curl of the\nvector field (in fluid dynamics, these are the rate of dilatation and the vorticity,\nrespectively) by solving these equations for the potentials and then\nevaluating their gradient and curl.\n\nWith immersed layers, these are extendable to domains with surfaces\nand their associated jump in the vector field $[\\mathbf{v}] = \\mathbf{v}^+ - \\mathbf{v}^-$.\nThe crucial relationships are\n\n$$\\nabla\\cdot{\\overline{\\mathbf{v}}} = \\overline{\\nabla\\cdot\\mathbf{v}} + \\delta(\\chi)\\mathbf{n}\\cdot[\\mathbf{v}]$$\n\nand\n\n$$\\nabla\\times{\\overline{\\mathbf{v}}} = \\overline{\\nabla\\times\\mathbf{v}} + \\delta(\\chi)\\mathbf{n}\\times[\\mathbf{v}]$$\n\nThese are, respectively, the divergence and curl of the masked vector field, $\\overline{\\mathbf{v}}$.\nIn `ImmersedLayers.jl`, we are always working with the masked form of a field,\nwhether we acknowledge it or not. In contrast, the first terms on the right-hand sides of these are the masked divergence and curl\nof the vector field in each side of the surface. The difference between these is\na type of single-layer surface term---a 'source sheet' or a 'vortex sheet', respectively---\ndue to the jump in vector field. If we omit the overbar notation, then the Helmholtz\ndecomposition and the Poisson equations all still hold.\n\nThis package has a number of routines that can be used to perform the\noperations described here. They rely on two caches, [`ScalarPotentialCache`](@ref)\nand [`VectorPotentialCache`](@ref), each of which supports one of the\nrespective potentials. The function [`vecfield_helmholtz!`](@ref) carries\nout all of these operations in order to assemble the vector field $\\mathbf{v}$\nfrom the masked divergence and curl fields and the jump in the vector field.\n(We can also add an additional irrotational, divergence-free vector field during\nthis assembly.\n=#\n\n\n#md # ## Helmholtz decomposition functions\n\n#md # ```@docs\n#md # ScalarPotentialCache\n#md # VectorPotentialCache\n#md # vectorpotential_from_masked_curlv!\n#md # scalarpotential_from_masked_divv!\n#md # vectorpotential_from_curlv!\n#md # vecfield_from_vectorpotential!\n#md # masked_curlv_from_curlv_masked!\n#md # curlv_masked_from_masked_curlv!\n#md # scalarpotential_from_divv!\n#md # masked_divv_from_divv_masked!\n#md # divv_masked_from_masked_divv!\n#md # vecfield_from_scalarpotential!\n#md # vecfield_helmholtz!\n#md # vectorpotential_uniformvecfield!\n#md # scalarpotential_uniformvecfield!\n#md # vecfield_uniformvecfield!\n#md # ```\n", "meta": {"hexsha": "67bd35797d15bd832e8447c5c25b96e28cac1c7e", "size": 3223, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/literate/helmholtz.jl", "max_stars_repo_name": "mleprovost/ImmersedLayers.jl", "max_stars_repo_head_hexsha": "09d95ee2201ee01da943838edd4c28ac5aad5156", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/literate/helmholtz.jl", "max_issues_repo_name": "mleprovost/ImmersedLayers.jl", "max_issues_repo_head_hexsha": "09d95ee2201ee01da943838edd4c28ac5aad5156", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/literate/helmholtz.jl", "max_forks_repo_name": "mleprovost/ImmersedLayers.jl", "max_forks_repo_head_hexsha": "09d95ee2201ee01da943838edd4c28ac5aad5156", "max_forks_repo_licenses": ["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.7974683544, "max_line_length": 130, "alphanum_fraction": 0.7610921502, "num_tokens": 905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465098415279, "lm_q2_score": 0.8615382129861583, "lm_q1q2_score": 0.8058367606117101}} {"text": "module CommonMath\n\nconst ∞ = Inf\nconst ∞⁻ = -Inf\nconst 𝐆 = MathConstants.golden\nconst 𝐆⁻¹ = 𝐆 - 1\nconst 𝐆1⁻¹ = 2 - 𝐆\nconst c½ = 0.5\n\nfunction mean_geometric(a::Float64, b::Float64; use_abs::Bool = false)\n prod = a * b\n return (use_abs ? sign(prod) : 1) * √(use_abs ? abs(prod) : prod)\nend\nfunction mean_geometric(V::Vector{Float64}; use_abs::Bool = false)\n @assert !isempty(V)\n prodV = prod(V)\n σ = use_abs ? sign(prodV) : 1\n return (use_abs ? abs(prodV) : prodV)^(1 / length(V))\nend\n\nfunction mean_harmonic(a::Float64, b::Float64)\n return 2 / (1 / a + 1 / b)\nend\nfunction mean_harmonic(V::Vector{Float64})\n @assert !isempty(V)\n return length(V) / sum(v -> 1 / v, V)\nend\n\nfunction scientific_notation_parts(a::Float64)\n o = floor(log10(abs(a)))\n υ = a / 10^o\n return (υ, o)\nend\n\nfunction mean_log10(a::Float64, b::Float64)\n υᵃ, oᵃ = scientific_notation_parts(a)\n υᵇ, oᵇ = scientific_notation_parts(b)\n return mean_geometric(υᵃ, υᵇ; use_abs = false) * 10^(mean_geometric(oᵃ, oᵇ; use_abs = true))\n return mean_geometric(υᵃ, υᵇ; use_abs = false) * 10^(mean_geometric(oᵃ, oᵇ; use_abs = true))\nend\nfunction mean_log10(V::Vector{Float64})\n @assert !isempty(V)\n vᵐⁱⁿ = minimum(V); vᵐᵃˣ = maximum(V)\n @assert vᵐⁱⁿ ≠ 0\n return mean_log10(vᵐⁱⁿ, vᵐᵃˣ)\nend\n\nfunction mean_log10_golden_lower(v¹::Float64, v²::Float64)\n a = min(v¹, v²); b = max(v¹, v²)\n υᵃ, oᵃ = scientific_notation_parts(a)\n υᵇ, oᵇ = scientific_notation_parts(b)\n return (𝐆⁻¹*υᵃ + 𝐆1⁻¹*υᵇ) * 10^(𝐆⁻¹*oᵃ + 𝐆1⁻¹*oᵇ)\nend\nfunction mean_log10_golden_lower(V::Vector{Float64})\n @assert !isempty(V)\n vᵐⁱⁿ = minimum(V); vᵐᵃˣ = maximum(V)\n @assert vᵐⁱⁿ ≠ 0\n return mean_log10_golden_lower(vᵐⁱⁿ, vᵐᵃˣ)\nend\n\nexport ∞, ∞⁻\nexport 𝐆, 𝐆⁻¹, 𝐆1⁻¹\nexport mean_geometric, mean_harmonic\nexport scientific_notation_parts\nexport mean_log10, mean_log10_golden_lower\n\nend # module CommonMath\n", "meta": {"hexsha": "ce57f76fda86942e9124804155f4e670f202d529", "size": 1907, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/commonmath/commonmath.jl", "max_stars_repo_name": "gitter-badger/NumericalDataManipulation.jl", "max_stars_repo_head_hexsha": "4f1bc43e8c2f94c3700c88619f51a9632f956306", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/commonmath/commonmath.jl", "max_issues_repo_name": "gitter-badger/NumericalDataManipulation.jl", "max_issues_repo_head_hexsha": "4f1bc43e8c2f94c3700c88619f51a9632f956306", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/commonmath/commonmath.jl", "max_forks_repo_name": "gitter-badger/NumericalDataManipulation.jl", "max_forks_repo_head_hexsha": "4f1bc43e8c2f94c3700c88619f51a9632f956306", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0441176471, "max_line_length": 96, "alphanum_fraction": 0.6717357105, "num_tokens": 814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465062370312, "lm_q2_score": 0.861538211208597, "lm_q1q2_score": 0.8058367558436627}} {"text": "\"\"\"\n A, B, C = ss_to_tf(tf)\n\nthis formulation is based on the notes here: \nhttp://web.mit.edu/2.14/www/Handouts/StateSpace.pdf\n\n Y(s) bₙ sⁿ + ... + b₁s + b₀\n G(s) = ----- = -------------------------\n U(s) aₙ sⁿ + ... + a₁s + a₀\n\nthen we can formulate the system described by transfer\nfunction G(s) as a state space representation known\nas the controllable canonical form:\n\n dx\n---- = A * x(t) + B * u(t)\n dt\n\ny(t) = C * x(t) + bₙ/aₙ * u(t)\n\nwe compute the matrices A, B, C here.\n\"\"\"\nfunction tf_to_ss(tf::TransferFunction)\n @assert proper(tf) \"tf not proper!\"\n \n a_i(i::Int) = tf.denominator[i]\n b_i(i::Int) = tf.numerator[i]\n\n # get the highest degree in the num/den, which is that in the den if proper.\n n = degree(tf.denominator) # asserted proper above\n\n A = zeros(n, n)\n for i = 1:n-1\n A[i, i + 1] = 1.0\n end\n for i = 1:n\n A[n, i] = - a_i(i-1)\n end\n A[n, :] /= a_i(n)\n \n B = zeros(n, 1)\n B[n, 1] = 1 / a_i(n)\n \n C = zeros(1, n)\n for i = 1:n\n C[1, i] = b_i(i-1) - b_i(n) * a_i(i-1) / a_i(n)\n end\n return A, B, C\nend\n\n\n@doc raw\"\"\"\n t, y = simulate(Y, final_time, nb_time_points=100) # invert Y(s)\n\nSimulate the output $y(t)$ of an LTI system, given the Laplace transform of the output, $Y(s)$, `Y`.\n\nIn other words, `simulate` inverts an expression in the frequency domain into the time domain.\n\n# Arguments\n* `Y::TransferFunction`: the Laplace transform of the output $y(t)$. Usually formed by $g(s)U(s)$, where $U(s)$ is the Laplace transform of the input.\n* `final_time::Tuple{Float64, Float64}`: the duration over which to simulate the output of the LTI system, starting at time zero.\n* `nb_time_points::Int=100`: the number of time points at which to save the solution $y(t)$\n\nTwo time points preceding $t=0$ are included to illustrate that it is assumed $y(t)=0$ for $t<0$.\n\n# Returns\n* `t::Array{Float64, 1}`: array of times: $t_i$'s\n* `y::Array{Float64, 1}`: array of $y$ values at corresponding times in `t`: $y_i$'s, where $y_i=y(t_i)$.\n\n# Example\n\nOne can simulate the first order step response as, given the Laplace transform of the output, `Y`:\n\n```\njulia> g = 4 / (3 * s + 1) # first-order transfer function\njulia> U = 1 / s # unit step input\njulia> Y = g / s # output\njulia> t, y = simulate(Y, 12.0)\n```\n\"\"\"\nfunction simulate(Y::TransferFunction, final_time::Float64; nb_time_points::Int=100)\n if ! proper(Y)\n error(\"LTI system is not proper...\")\n end\n \n # coeffs on denominator, numerator polynomial\n a_i(i::Int) = Y.denominator[i]\n b_i(i::Int) = Y.numerator[i]\n n = degree(Y.denominator)\n\n # convert tf to state space form\n A, B, C = tf_to_ss(Y)\n\n x0 = deepcopy(B) # initial condition\n\n f(x, p, t) = A * x # RHS of ODE (ignore p for params)\n prob = ODEProblem(f, x0, (0.0, final_time))\n sol = solve(prob, d_discontinuities=[0.0])\n\n t = vcat([-0.05 * final_time, -1e-5], range(1e-5, final_time, length=nb_time_points - 2))\n y = [NaN for i = 1:nb_time_points]\n for (i, t_i) in enumerate(t)\n if t_i < Y.time_delay\n y[i] = 0.0\n else\n y[i] = (C * sol(t_i - Y.time_delay))[1] # put in shifted time\n end\n end\n return t, y\nend\n\n@doc raw\"\"\"\n y_at_t̃ = interpolate(t, y, t̃)\n\ngiven an array of times $t_i$ in `t` and corresponding values of $y(t)$, $y_i=y(t_i)$ in the array `y`, interpolate to approximate the function $y(t)$ at a new time `t̃`, i.e. $y(\\tilde{t})$.\n\nthe output of [`simulate`](@ref) is an array of times `t` and corresponding output values `y`. `interpolate` is useful for obtaining the solution at a particular time `t̃` that is not necessarily present in the array `t`.\n\nan error is thrown if `maximum(t) < t̃ < minimum(t)` (extrapolation) or if the `t` array is not sorted.\n\n# Arguments\n* `t::Array{Float64, 1}`: array of times $t_i$. these must be sorted.\n* `y::Array{Float64, 1}`: an array of corresponding $y$-values $y_i=y(t_i)$\n* `t̃::Float64`: the new time at which we wish to know $y$. i.e. we wish to know $y(\\tilde{t})$.\n\n# Returns\n* `y_at_t̃::Float64`: the value of $y$ when $t$ is `t̃`, $y(\\tilde{t})$, according to linear interpolation.\n\n# Example\n\nthe unit step response of a first-order process with time constant $\\tau$ is $\\approx63\\%$ of the final value when $t=\\tau$.\n\n```julia\njulia> τ = 3.45\njulia> g = 1 / (τ * s + 1) # FO system\njulia> t, y = simulate(g / s, 10.0) # unit step response\njulia> y_at_τ = interpolate(t, y, τ) # 0.63\n```\n\"\"\"\nfunction interpolate(t::Array{Float64, 1}, y::Array{Float64, 1}, t̃::Float64)\n if t̃ < minimum(t) || t̃ > maximum(t)\n error(@sprintf(\"t̃ = %f is outside the range of the t-array passed, %f to %f.\\n\", t̃, minimum(t), maximum(t)))\n end\n # from Interpolations.jl.\n # will throw error if t not sorted. \n return LinearInterpolation(t, y)(t̃)\nend\n", "meta": {"hexsha": "f1810d76befd1b26c8faeeb00c121b71ce3c7705", "size": 4874, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/sim.jl", "max_stars_repo_name": "dmolina/Controlz.jl", "max_stars_repo_head_hexsha": "8cf246a4a10fcaac2ab6b874f40a54c0392f52e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/sim.jl", "max_issues_repo_name": "dmolina/Controlz.jl", "max_issues_repo_head_hexsha": "8cf246a4a10fcaac2ab6b874f40a54c0392f52e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sim.jl", "max_forks_repo_name": "dmolina/Controlz.jl", "max_forks_repo_head_hexsha": "8cf246a4a10fcaac2ab6b874f40a54c0392f52e7", "max_forks_repo_licenses": ["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.9324324324, "max_line_length": 221, "alphanum_fraction": 0.6153057037, "num_tokens": 1634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.921921841290738, "lm_q2_score": 0.8740772466456689, "lm_q1q2_score": 0.8058309046579135}} {"text": "# -*- coding: utf-8 -*-\n# # Runge-Kutta methods\n\nusing Plots\ngr()\n\n# We will implement in Julia different numerical methods to solve\n#\n# $$\n# y'(t) = 1 - y(t)\n# $$\n#\n# $ t \\in [0,5] \\qquad \\mbox{ and } \\qquad y(0) = 0 $\n\n# ## Explicit Euler\n\n\"\"\"\n\n euler(f::Function, t::Float64, y::Float64, h::Float64)\n\nexplicit euler method function that returns\n\n```math\ny^{n+1} = y^n + h \\\\cdot f(t^n, y^n)\n```\n\n\n\"\"\"\nfunction euler(f::Function, t::Float64, y::Float64, h::Float64)\n t + h, y + h * f(t,y)\nend\n#----------------------------------------------------------------------------\n\n?euler\n\n# ## Runge-Kutta 2nd order\n\n\"\"\"\n\n rk2(f::Function, t::Float64, y::Float64, dt::Float64)\n\nRunge-Kutta second order method function\n\n```jldoctest\njulia> f(t,y) = 1 - y\njulia> rk2(f, 0.0, 0.0, 1.0)\n(1.0, 0.5)\n```\n\n\"\"\"\nfunction rk2(f::Function, t::Float64, y::Float64, h::Float64)\n ỹ = y + h/2 * f(t,y)\n t + h, y + h * f(t+h/2,ỹ)\nend\n#----------------------------------------------------------------------------\n\n?rk2\n\n# ## Runge-Kutta 4th order\n\n\"\"\"\n\n rk4(f::Function, t::Float64, y::Float64, dt::Float64)\n\nRunge-Kutta fourth order method function\n\n[Runge–Kutta methods on Wikipedia](https://en.wikipedia.org/wiki/Runge–Kutta_methods)\n\n\"\"\"\nfunction rk4(f::Function, t::Float64, y::Float64, dt::Float64)\n\n y₁ = dt * f(t,y)\n y₂ = dt * f(t+dt/2,y+y₁/2)\n y₃ = dt * f(t+dt/2,y+y₂/2)\n y₄ = dt * f(t+dt,y+y₃)\n\n t+dt, y+(y₁+2*y₂+2*y₃+y₄)/6\n\nend\n#----------------------------------------------------------------------------\n\n?rk4\n#----------------------------------------------------------------------------\n\n# ## Solver function\n\n\"\"\"\n\n solver(f::Function, Method::Function, t₀::Float64,\n y₀::Float64, dt::Float64, nsteps::Int64)\n\nSolve numerically the equation ``y' = f(t, y)``\n\nwith `y(t₀)= y₀` and `nsteps` steps `h`\n\n## Arguments\n- `f::Function`: the function `f` of equation ``y' = f(t,y)``.\n- `Method::Function`: numerical method from (tⁿ,yⁿ) returns ``(t^{n+1},y^{n+1})``\n\n\n\"\"\"\nfunction solver(f::Function,\n Method::Function,\n t₀::Float64,\n y₀::Float64, h::Float64, nsteps::Int64)\n\n t = zeros(Float64,nsteps)\n y = similar(t)\n\n t[1] = t₀\n y[1] = y₀\n\n for i in 2:nsteps\n t[i], y[i] = Method(f,t[i-1],y[i-1], h)\n end\n\n t, y\n\nend\n#----------------------------------------------------------------------------\n\n?solver\n#----------------------------------------------------------------------------\n\nnsteps, tfinal = 7, 5.0\nt₀, x₀ = 0., 0.\n\ndt = tfinal / (nsteps-1)\nf(t, x) = 1 - x\n#----------------------------------------------------------------------------\n\nplot( solver(f, euler, t₀, x₀, dt, nsteps); marker = :o, label=:euler)\nplot!(solver(f, rk2, t₀, x₀, dt, nsteps); marker = :d, label=:rk2)\nplot!(solver(f, rk4, t₀, x₀, dt, nsteps); marker = :p, label=:rk4)\nt = 0:0.1:5\nplot!(t, 1 .- exp.(-t); line = 3, label = :exact)\n#----------------------------------------------------------------------------\n\n# # Callable object\n#\n# We want to build a numerical method to solve the problem and then use it\n# as a function and still call the solver function.\n\n#\n#\n# Runge-Kutta scheme can be built using Butcher tableau :\n#\n# \\begin{array}{c|cccc}\n# c₁ & & & & \\\\\n# c₂ & a_{21} & & & \\\\\n# c₃ & a_{31} & a_{32} & & \\\\\n# c₄ & a_{41} & a_{42} & a_{43} & \\\\\n# \\hline\n# & b_1 & b_2 & b_3 & b_4 \\\\\n# \\end{array}\n#\n# $$\n# \\forall i = 1, \\dotsc, q, \\begin{cases}t_{n,i} &= t_n + c_i h_n, \\\\ \n# y_{n,i} &= y_n + h_n \\sum_{k = 1}^{i-1} a_{ik} p_{n,k}\\\\ \n# p_{n,i} &= f(t_{n,i}, y_{n,i}) \\end{cases}\n# $$\n#\n# $$\n# y_{n+1} = y_n + h_n \\sum_{k = 1}^q b_k p_{n,k}.\n# $$\n#\n\nmutable struct RungeKutta\n \n q :: Int64\n a :: Array{Float64, 2}\n b :: Array{Float64, 1}\n c :: Array{Float64, 1}\n \n tn :: Vector{Float64}\n yn :: Vector{Float64}\n pn :: Vector{Float64}\n \n function RungeKutta( a::Array{Float64,2}, b::Vector{Float64}, c::Vector{Float64})\n \n q = length(c)\n @assert ( length(c) == size(a,1))\n @assert ( length(b) == size(a,2))\n tn = zeros(Float64, q)\n yn = zeros(Float64, q)\n pn = zeros(Float64, q)\n new( q, a, b, c, tn, yn, pn)\n \n end\n\nend\n\nfunction (rk::RungeKutta)(f::Function, t::Float64, y::Float64, h::Float64)\n\n for i = 1:rk.q\n rk.tn[i] = t + rk.c[i] * h\n rk.yn[i] = y + h * sum([rk.a[i,k]*rk.pn[k] for k = 1:i-1])\n rk.pn[i] = f(rk.tn[i],rk.yn[i])\n end\n\n t + h, y + h * sum([rk.b[k]*rk.pn[k] for k in 1:rk.q ])\n\nend\n#----------------------------------------------------------------------------\n\nfunction solver(f::Function,\n Method::RungeKutta,\n t₀::Float64,\n y₀::Float64, h::Float64, nsteps::Int64)\n\n t = zeros(Float64,nsteps)\n y = similar(t)\n\n t[1] = t₀\n y[1] = y₀\n\n for i in 2:nsteps\n t[i], y[i] = Method(f,t[i-1],y[i-1], h)\n end\n\n t, y\n\nend\n#----------------------------------------------------------------------------\n\na = [ 0 0 0 0; \n 1/2 0 0 0; \n 0 1/2 0 0; \n 0 0 1 0]\n\nb = [1/6 ,1/3, 1/3, 1/6]\nc = [0 ,1/2, 1/2, 1 ]\n\nrk4_new = RungeKutta(a, b, c)\n#----------------------------------------------------------------------------\n\nt = 0:0.1:5\nplot(t, 1 .- exp.(-t),label = :exact)\nplot!(solver(f, rk4_new, t₀, x₀, dt, nsteps), marker = :o, label=:rk4_new)\n#----------------------------------------------------------------------------\n\na = [ 0 0 0 0; \n 1/3 0 0 0; \n -1/3 1 0 0; \n 1 -1 1 0]\n\nb = [1/8, 3/8, 3/8, 1/8]\nc = [0, 1/3, 2/3, 1]\nrk4_38 = RungeKutta(a, b, c)\nplot!(solver(f, rk4_38, t₀, x₀, dt, nsteps), marker = :r, label=:rk4_38)\n#----------------------------------------------------------------------------\n\n# [Reference](https://www.juliabloggers.com/runge-kutta-methods/):Ordinary Differential Equation Solvers: Runge-Kutta Methods by Christina Lee\n\n# # Creating expressions via interpolation\n#\n# Create a solver function with the method choosen at initialization.\n\nmacro add(x, y)\n return :($x + $y)\nend\n\n@add 2 3 ## or @add(2, 3) \n#----------------------------------------------------------------------------\n\nmacro abs(x)\n return :( $x > 0 ? $x : -$x)\nend\n@abs(-2), @abs(2)\n#----------------------------------------------------------------------------\n\nmacro make_method( meth)\n return quote\n function (f::Function, t₀::Float64,\n x₀::Float64, dt::Float64, nsteps::Int64)\n\n t = zeros(Float64,nsteps)\n x = zeros(Float64,nsteps)\n\n t[1] = t₀\n x[1] = x₀\n\n for i in 2:nsteps\n t[i], x[i] = $meth(f,t[i-1],x[i-1], dt)\n end\n\n return t, x\n end\n end\nend\n\nrk4_solver = @make_method rk4\n\nplot(rk4_solver(f, t₀, x₀, dt, nsteps))\n#----------------------------------------------------------------------------\n\n# [DifferentialEquations.jl](http://docs.juliadiffeq.org/latest/)\n#\n# [ODE Solvers](http://docs.juliadiffeq.org/latest/solvers/ode_solve.html#OrdinaryDiffEq.jl-1)\n\nusing OrdinaryDiffEq\nusing Plots\n\n\nf(y,p,t) = 1.0 - y\ny₀ = 0.0\nt = (0.0,5.0)\nprob = ODEProblem(f,y₀,t)\neuler = solve(prob,Euler(), dt=1.0)\nrk4 = solve(prob, RK4(), dt=1.0)\nplot(euler,label=\"Euler\")\nplot!(rk4,label=\"RK4\")\nplot!(1:0.1:5, t->1. - exp(-t),lw=3,ls=:dash,label=\"True Solution!\")\n#----------------------------------------------------------------------------\n\nusing DifferentialEquations\n\nfunction lorenz(du,u,p,t)\n du[1] = 10.0*(u[2]-u[1])\n du[2] = u[1]*(28.0-u[3]) - u[2]\n du[3] = u[1]*u[2] - (8/3)*u[3]\nend\n#----------------------------------------------------------------------------\n\nu0 = [1.0;0.0;0.0]\ntspan = (0.0,100.0)\nprob = ODEProblem(lorenz,u0,tspan)\nsol = solve(prob)\n#----------------------------------------------------------------------------\n\nplot(sol,vars=(1,2,3))\n\n# ----------------------------------------------------------------------------\n", "meta": {"hexsha": "95cf3640a96c1e93b816d8a99f582e64034812e1", "size": 8039, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "03.RungeKuttaMethods.jl", "max_stars_repo_name": "pnavaro/math-julia", "max_stars_repo_head_hexsha": "900db803b2ddd9e44eb2d4fabb481768a14953c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-01-14T13:32:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T04:22:17.000Z", "max_issues_repo_path": "03.RungeKuttaMethods.jl", "max_issues_repo_name": "pnavaro/math-julia", "max_issues_repo_head_hexsha": "900db803b2ddd9e44eb2d4fabb481768a14953c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "03.RungeKuttaMethods.jl", "max_forks_repo_name": "pnavaro/math-julia", "max_forks_repo_head_hexsha": "900db803b2ddd9e44eb2d4fabb481768a14953c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-10-15T07:58:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-11T01:52:10.000Z", "avg_line_length": 24.0688622754, "max_line_length": 142, "alphanum_fraction": 0.429282249, "num_tokens": 2655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218412907381, "lm_q2_score": 0.8740772351648677, "lm_q1q2_score": 0.8058308940735123}} {"text": "### A Pluto.jl notebook ###\n# v0.14.4\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ c7e41465-41ad-4f11-baec-bfaae9edbf59\nbegin\n\tusing PlutoUI\n\tPlutoUI.TableOfContents(aside=true)\nend\n\n# ╔═╡ d0233ece-1f69-11eb-3da1-43b8ddc9fbe1\nbegin\n\t# Necessary packages\n\tusing LinearAlgebra\n\tusing Random\n\tusing Statistics\n\tusing Clustering\n\tusing Plots\nend\n\n# ╔═╡ 00d72ad7-ea80-4954-8c75-590d4e9ccdc4\nmd\"\"\"\n# K-means Algorithm\n\n\nData clustering is one of the main mathematical applications variety of algorithms have been developed to tackle the problem. K-means is one of the basic algorithms for data clustering.\n\n__Prerequisites__\n\nThe reader should be familiar with basic linear algebra. \n \n__Competences__\n\nThe reader should be able to recognise applications where K-means algorithm can be efficiently used and use it.\n\n__Credits.__ The notebook was initially derived from M.Sc. Thesis of Ivančica Mirošević. \n\"\"\"\n\n# ╔═╡ 235e1901-eed3-4934-9214-ffdd82cf21d6\nmd\"\"\"\n## Definitions\n\n__Data clustering problem__ is the following: partition the given set of $m$ objects of the same type into $k$ subsets according to some criterion. Additional request may be to find the optimal $k$.\n\n__K-means clustering problem__ is the following: partition the set $X=\\{x_{1},x_{2},\\cdots ,x_{m}\\}$ , where $x_{i}\\in\\mathbb{R}^{n}$, into $k$ _clusters_ $\\pi=\\{C_{1},C_{2},...,C_{k}\\}$ such that\n\n$$\nJ(\\pi)=\\sum_{i=1}^{k}\\sum_{x\\in\nC_{i}}\\| x-c_{i}\\|_{2}^{2} \\to \\min$$\n\nover all possible partitions. Here $c_{i}=\\displaystyle\\frac{1}{|C_{i}|}\\sum_{x\\in C_{i}} x$ is the mean of points in $C_i$ and $|C_i|$ is the cardinality of $C_i$.\n\"\"\"\n\n# ╔═╡ 26640b90-1f69-11eb-029e-4dc3a825f639\nmd\"\n## K-means clustering algorithm\n\n1. __Initialization__: Choose initial set of $k$ means $\\{c_1,\\ldots,c_k\\}$ (for example, by choosing randomly $k$ points from $X$).\n2. __Assignment step__: Assign each point $x$ to one nearest mean $c_i$.\n3. __Update step__: Compute the new means.\n4. __Iteration__: Repeat Steps 2 and 3 until the assignment no longer changes.\n\"\n\n# ╔═╡ 48914840-1f69-11eb-30a9-3943767bc261\nmd\"\n## First Variation clustering algorithm\n\nA __first variation__ of a partition $\\pi=\\{C_1,\\ldots,C_k\\}$ is \na partition $\\pi^{\\prime}=\\{C_{1}^{\\prime},\\cdots ,C_{k}^{\\prime }\\}$ \nobtained by moving a single point $x$ from a cluster $C_{i}$ to a cluster $C_{j}$. Notice that $\\pi$ is a first variation of itself.\n\nA __next partition__ of the partition $\\pi$ is a partition \n$\\mathop{\\mathrm{next}}(\\pi)=\\mathop{\\mathrm{arg min}}\\limits_{\\pi^{\\prime}} J(\\pi^{\\prime})$.\n\nWe have the following algorithm:\n\n1. Choose initial partition $\\pi$.\n2. Compute $\\mathop{\\mathrm{next}}(\\pi)$\n3. If $J(\\mathop{\\mathrm{next}}(\\pi))\n# ```julia\n# [item1, item2, ...]\n# ```\n# ------------------------------------------------------------------------------------------\n\nsquares = [1, 4, 9, 15, 25, 36, 49, 64]\n\nsquares[1]\n\nsquares[1:3]\n\nsquares[end]\n\nsquares[4] = 16\n\nsquares\n\ntypeof(squares)\n\n# ------------------------------------------------------------------------------------------\n# ## Concatenation\n#\n# If, instead of commas, you just use spaces, then the values are concatenated horizontally.\n# ------------------------------------------------------------------------------------------\n\ncubes = [1, 8, 27, 64, 125, 216, 343, 512]\n\npowers = [1:8 squares cubes]\n\npowers[4, 2]\n\npowers[:, 3]\n\npowers[7, :]\n\ntypeof(powers)\n\n# ------------------------------------------------------------------------------------------\n# Semicolon separators perform vertical concatenation:\n# ------------------------------------------------------------------------------------------\n\n[squares; cubes]\n\n# ------------------------------------------------------------------------------------------\n# Whereas commas would simply create an array of arrays:\n# ------------------------------------------------------------------------------------------\n\nnested_powers = [[1,2,3,4,5,6,7,8], squares, cubes]\n\nnested_powers[2]\n\n# ------------------------------------------------------------------------------------------\n# Horizontal and vertical concatenation can be used together to as a simple syntax for\n# matrix literals:\n# ------------------------------------------------------------------------------------------\n\n[1 3 5; 2 4 6]\n\n# ------------------------------------------------------------------------------------------\n# # Loops\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# Of course, we could construct this programmatically with a for-loop. The syntax for a\n# `for` loop is\n#\n# ```julia\n# for *var* in *loop iterable*\n# *loop body*\n# end\n# ```\n#\n# \n# ------------------------------------------------------------------------------------------\n\nA = fill(0, (8, 3)) # Allocate an 8x3 matrix to store the values into\nfor pow in 1:3\n for value in 1:8\n A[value, pow] = value ^ pow\n end\nend\nA\n\nA == powers\n\n# ------------------------------------------------------------------------------------------\n# ## Array Comprehensions\n# ------------------------------------------------------------------------------------------\n\nsquares = [value^2 for value in 1:8]\n\ncubes = [value^3 for value in 1:8]\n\npowers = [value^pow for value in 1:8, pow in 1:3]\n\n# ------------------------------------------------------------------------------------------\n# # The element type\n#\n# Note that every time an array prints out, it is displaying its element type and\n# dimensionality, for example `Array{Int64, 2}`. This describes what it can store — and thus\n# what it can return upon indexing.\n# ------------------------------------------------------------------------------------------\n\ntypeof(powers)\n\ntypeof(powers[1, 1])\n\n# ------------------------------------------------------------------------------------------\n# Further, the array will try to convert any new values assigned into it to its element\n# type:\n# ------------------------------------------------------------------------------------------\n\npowers[1, 1] = 1.6\n\npowers[1, 1] = -5.0 # This can be losslessly converted to an integer\n\npowers\n\n# ------------------------------------------------------------------------------------------\n# Arrays that have an exact and concrete element type are generally significantly faster, so\n# Julia will try to find an amenable element type for you in its literal construction\n# syntax:\n# ------------------------------------------------------------------------------------------\n\nfortytwosarray = [42, 42.0, 4.20e1, 4.20f1, 84//2, 0x2a]\n\nfor x in fortytwosarray\n show(x)\n println(\"\\tisa $(typeof(x))\")\nend\n\n# ------------------------------------------------------------------------------------------\n# The `Any` array can be helpful for disabling these behaviors and allowing all kinds of\n# different objects:\n# ------------------------------------------------------------------------------------------\n\nanyfortytwos = Any[42, 42.0, 4.20e1, 4.20f1, 84//2, 0x2a]\n\nanyfortytwos[1] = \"FORTY TWO\"\nanyfortytwos\n\n# ------------------------------------------------------------------------------------------\n# # Vectors as dequeues\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# One-dimensional arrays can be appended to and have items removed from them:\n# ------------------------------------------------------------------------------------------\n\nfib = [1, 1, 2, 3, 5, 8, 13]\n\npush!(fib, 21)\n\npush!(fib, sum(fib[end-1:end]))\n\npop!(fib)\n\npushfirst!(fib, 0)\n\npopfirst!(fib)\n\n# ------------------------------------------------------------------------------------------\n# ## Aside: why so shouty!?\n#\n# Why are there exclamations in all the above function calls? `push!(fib, ...)`,\n# `pop!(fib)`, etc.?\n# ------------------------------------------------------------------------------------------\n\npush!\n\n# ------------------------------------------------------------------------------------------\n# This is entirely a convention. It's a signal to the caller that one of the argument is\n# going to be _mutated_. It's perhaps easiest to demonstrate with an example:\n# ------------------------------------------------------------------------------------------\n\nA = rand(0:10, 10)\n\nsort(A)\n\nA\n\nsort!(A)\n\nA # That changed A!\n\n# ------------------------------------------------------------------------------------------\n# ## Aside: names vs. copies\n#\n# Remember that variables are just names we give our objects. So watch what happens if we\n# give the same object two different names:\n# ------------------------------------------------------------------------------------------\n\nfibonacci = [1, 1, 2, 3, 5, 8, 13]\n\nsome_numbers = fibonacci\nsome_numbers[1] = 404\nsome_numbers\n\nfibonacci\n\nfibonacci[1] = 1\nsome_numbers = copy(fibonacci)\nsome_numbers[2] = 404\nfibonacci\n", "meta": {"hexsha": "91207c425d48f8c4c33b66bee884e7f1076c0dad", "size": 6719, "ext": "jl", "lang": "Julia", "max_stars_repo_path": ".nbexports/introductory-tutorials/intro-to-julia/long-version/020 Arrays and Loops.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/020 Arrays and Loops.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/020 Arrays and Loops.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": 29.9955357143, "max_line_length": 92, "alphanum_fraction": 0.3628516148, "num_tokens": 1269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253255, "lm_q2_score": 0.9219218294919745, "lm_q1q2_score": 0.805830889808711}} {"text": "## Here is the code from unit 1\n\n# This treats everything as a dense matrix :(\nA = [0 1 1 1 1 0 1 0 0 0\n 1 0 0 0 0 0 0 0 0 0\n 0 0 0 0 1 1 1 0 0 0\n 1 1 0 0 1 1 0 1 0 0\n 1 1 1 1 0 0 0 0 1 0\n 0 0 1 0 0 0 1 0 1 1\n 0 0 0 0 0 1 0 0 0 1\n 0 0 0 0 0 0 0 0 1 0\n 0 0 0 0 0 0 0 1 0 0\n 0 0 0 0 0 0 0 0 0 0]\nd = sum(A,dims=2)\n##\nusing Printf\nfor i=1:10\n for j=1:10\n if i==j\n @printf(\"1 & \")\n elseif A[j,i] != 0\n @printf(\"-\\\\alpha/%i & \", d[j])\n else\n @printf(\"0 & \")\n end\n end\n println(\"\\\\\\\\\")\nend\n## Build the I - alpha D^+ A'\nalpha = 0.85\nM = zeros(size(A)...)\nfor i=1:10\n for j=1:10\n if i==j\n M[i,j] = 1\n elseif A[j,i] != 0\n M[i,j] = -alpha*A[j,i]/d[j]\n else\n M[i,j] = 0\n end\n end\nend\nM[:,end] .= -alpha/10\nM[end,end] += 1\nM[:,1]\n##\nb = ones(size(A,1))/size(A,1)*(1-alpha)\nx = M\\b\n\n##\nusing DelimitedFiles\nusing SparseArrays\nei,ej = copy.(eachcol(Int.(readdlm(\"wiki-simple.edges\"))))\nxy = readdlm(\"wiki-simple.xy\")\npages = readlines(\"wiki-simple.nodes\")\nn = size(xy,1)\nA = sparse(ei,ej,1,n,n)\n\n## Simple PageRank\nfunction simplepagerank(A,α,v)\n @assert(0 ≤ α < 1, \"needs probably α\")\n @assert(all(vi -> vi ≥ 0, v), \"needs non-negative v\")\n v = v ./ sum(v) # we can normalize for them.\n d = vec(sum(A,dims=2)) # compute the degrees\n x = copy(v) # start of with v\n nsteps = 2*ceil(Int,log(eps(1.0))/log(α)) # upper bound on steps\n for i=1:nsteps\n x = α*(A'*(x./d)) .+ (1-α).*v\n end\n return x/sum(x) # renormalize to probability\nend\npr = simplepagerank(A,0.85,ones(n)./n)\n", "meta": {"hexsha": "dbb892e1ad3dbc45599adde165c73f24ff6f7d4a", "size": 1565, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "5-unit-4-demos/pagerank-simple.jl", "max_stars_repo_name": "dgleich/cs590-ncds", "max_stars_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-04-07T15:19:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T04:43:33.000Z", "max_issues_repo_path": "5-unit-4-demos/pagerank-simple.jl", "max_issues_repo_name": "dgleich/cs590-ncds", "max_issues_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "5-unit-4-demos/pagerank-simple.jl", "max_forks_repo_name": "dgleich/cs590-ncds", "max_forks_repo_head_hexsha": "bd28821e2f805c2af1a1ae3cb7879e4e6e07bc56", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-07-13T03:13:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-17T01:37:03.000Z", "avg_line_length": 21.4383561644, "max_line_length": 66, "alphanum_fraction": 0.5392971246, "num_tokens": 723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266014, "lm_q2_score": 0.8947894569842487, "lm_q1q2_score": 0.8057845654846789}} {"text": "using LinearAlgebra, StatsBase, TimerOutputs, DataFrames, StatsPlots, BenchmarkTools\n\n \nfunction structured_P(L::Int; p::Float64 = 0.45, r::Float64 = 0.01)::Matrix{Float64}\n q = 1 - p - r\n P = diagm(fill(r,L)) + diagm(-1=>fill(q,L-1)) + diagm(1 => fill(p,L-1))\n P[1,1] = 1-p\n P[L,L] = 1-q\n return P\nend\n\nstructured_π(L::Int; p::Float64 = 0.45, r::Float64 = 0.01)::Vector{Float64} = begin\n q = 1 - p - r\n [(p/q)^i for i in 1:L] * (q-p) / p / (1-(p/q)^L) #Explicit expression (birth death)\nend;\n\n# Method 1: Linear Algebra\nfunction method_1(input_matrix, L)\n # Transpose both sides, add a row to the bottom to represent the additional requirement\n return [I - input_matrix'; ones(1, L)] \\ [zeros(L); 1]\nend\n\n# Method 2: Take a high matrix power\nfunction method_2(input_matrix, L)\n matrix_power = 10^5 # arbitrary\n # Return the first column - the 'j' doesn't matter\n return (input_matrix^(matrix_power))[1, :]\nend\n\n# Method 3: Eigen trickery\nfunction method_3(input_matrix, L)\n eigens = eigen(input_matrix')\n correct_vector = eigens.vectors[:, findfirst(isapprox(1), eigens.values)]\n return correct_vector * UniformScaling(1 / sum(correct_vector))\nend\n\n# Method 4: Random sample\nfunction method_4(input_matrix, L)\n repeats = 10^5 # arbitrary\n states = 1:L\n current_value = rand(states)\n chain = zeros(L) # we don't need the order, just the counts\n for i in 1:repeats\n # Take a weighted sample based on the current state\n current_value = sample(states, Weights(view(input_matrix, current_value, :)))\n chain[current_value] += 1\n end\n # Apply the 1/n\n return map(x->x/repeats, chain)\nend\n\n# The L's given by the task\nL_given = [2:5..., 10:10:50..., 100:100:500..., 1000]\n\n\n# Get the benchmarks warmed up and ready to go\nsuite = BenchmarkGroup()\nfor method in [method_1, method_2, method_3, method_4]\n suite[String(Symbol(method))] = BenchmarkGroup()\nend\n\n\n# Prepare data structures\nnorms_df = DataFrame(a=L_given)\napprox_methods_for_df = zip('b':'e', [method_1, method_2, method_3, method_4])\n\nfor approx_method ∈ approx_methods_for_df\n # Benchmark each L for each function, add it to suite\n for L in L_given\n suite[String(Symbol(approx_method[2]))][L] = @benchmarkable $(approx_method[2])(structured_P($L), $L)\n end\n\n # Put the error into the df for plotting\n norms_df[!, string(approx_method[1])] = map(L->norm(approx_method[2](structured_P(L), L) - structured_π(L)), L_given)\nend\n\n# Run our thing\nresults = run(suite, seconds = 2, samples = 5)\n\n\n# Plot the DataFrames\n\n# Make sure none of the values break the graph\ninds = (norms_df.c .> 0) .& (norms_df.d .> 0) .& (norms_df.b .> 0) .& (norms_df.e .> 0)\n# Plot the absolute errors of each method\n@show @df norms_df plot(\n :a[inds], [:b[inds] :c[inds] :d[inds] :e[inds]], \n xaxis=:log10,\n xtickfont = font(5, \"Courier\"), \n xlabel = \"L\", \n ylabel = \"Absolute Error\", \n yscale=:log10, \n label = [\"Method 1 (Linear Algebra)\" \"Method 2 (Matrix Power)\" \"Method 3 (Eigenvector)\" \"Method 4 (Random Seq)\"], \n title = \"Demonstration of Approximation Methods\"\n)\n\n# Prepare the benchmarks for plotting (load their median times into a dataframe)\nbenchmarks_df = DataFrame(L=L_given)\nfor method in keys(results)\n benchmarks_df[!, String(Symbol(method))] = map(L->median(results[method][L]).time, L_given)\nend\n\n# Plot the benchmarks\n@show @df benchmarks_df plot(\n :L, [:method_1 :method_2 :method_3 :method_4], \n xaxis=:log10,\n xtickfont = font(5, \"Courier\"), \n xlabel = \"L\", \n ylabel = \"Time (in one unit or another)\", \n yscale=:log10, \n label = [\"Method 1 (Linear Algebra)\" \"Method 2 (Matrix Power)\" \"Method 3 (Eigenvector)\" \"Method 4 (Random Seq)\"], \n title = \"Demonstration of Approximation Methods\"\n)", "meta": {"hexsha": "88b0d95f83755162d80d23c111a455ed625fdd5d", "size": 3804, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "q4/q4_solution.jl", "max_stars_repo_name": "XxX-Daniil-underscore-Zaikin-XxX/Daniil-Zaikin-2504-2021-HW2", "max_stars_repo_head_hexsha": "bda2cc752f2dd1df1d4982865fe090e05e846dd6", "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": "q4/q4_solution.jl", "max_issues_repo_name": "XxX-Daniil-underscore-Zaikin-XxX/Daniil-Zaikin-2504-2021-HW2", "max_issues_repo_head_hexsha": "bda2cc752f2dd1df1d4982865fe090e05e846dd6", "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": "q4/q4_solution.jl", "max_forks_repo_name": "XxX-Daniil-underscore-Zaikin-XxX/Daniil-Zaikin-2504-2021-HW2", "max_forks_repo_head_hexsha": "bda2cc752f2dd1df1d4982865fe090e05e846dd6", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6637168142, "max_line_length": 121, "alphanum_fraction": 0.6658780231, "num_tokens": 1174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297754396141, "lm_q2_score": 0.894789473818021, "lm_q1q2_score": 0.8057845639230728}} {"text": "\"\"\"\n\tnormcdf(x)\n\nProbablity that Z ≤ x, where Z is a standard normal random variable.\n\"\"\"\nnormcdf(x::Real) = erfc(-x / √two(x)) / 2\n\n\"\"\"\n\tnormcdf(a, b)\n\nProbablity that a ≤ Z ≤ b, where Z is a standard normal random variable.\nWARNING: Silently returns a negative value if a > b.\n\"\"\"\nnormcdf(a::Real, b::Real) = erf(a / √two(a), b / √two(b)) / 2\n\n\"\"\"\n\tnormcdfinv(x)\n\nInverse of normcdf.\n\"\"\"\nnormcdfinv(x::Real) = -√two(x) * erfcinv(2x)\n\n\"\"\"\n\tlognormcdf(a, b)\n\nComputes log(normcdf(a, b)), but retaining accuracy.\n\"\"\"\nlognormcdf(a::Real, b::Real) = logerf(a / √two(a), b / √two(b)) - log(two(a + b))\n\n\"\"\"\n\ttnmean(a)\n\nMean of the standard normal distribution,\ntruncated to the interval (a, +∞).\n\"\"\"\ntnmean(a::Real) = sqrt(two(a)/π) / erfcx(a/√two(a))\n\n\"\"\"\n\ttnvar(a)\n\nVariance of the standard normal distribution,\ntruncated to the interval (a, +∞).\nWARNING: Fails for very very large values of `a`.\n\"\"\"\nfunction tnvar(a::Real)\n\tμ = tnmean(a)\n\treturn one(μ) - (μ - a) * μ\nend\n\n\"\"\"\n\ttnstd(a)\n\nStandard deviation of the standard normal distribution,\ntruncated to the interval (a, +∞).\n\"\"\"\ntnstd(a::Real) = √tnvar(a)\n\n\"\"\"\n\tmills(x::Real)\n\nMills ratio of the standard normal distribution.\nDefined as (1 - cdf(x)) / pdf(x).\n\"\"\"\nmills(x::Real) = erfcx(x / √two(x)) * √(π/two(x))\n", "meta": {"hexsha": "b33220a66c0ed802be8df069070a0bddb34e3ae6", "size": 1268, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/truncnorm.jl", "max_stars_repo_name": "suzannastep/TruncatedNormal.jl", "max_stars_repo_head_hexsha": "3c16866c3afa3920e787513d492689e9e81192ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-06-14T11:01:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-04T10:39:02.000Z", "max_issues_repo_path": "src/truncnorm.jl", "max_issues_repo_name": "suzannastep/TruncatedNormal.jl", "max_issues_repo_head_hexsha": "3c16866c3afa3920e787513d492689e9e81192ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2022-03-01T13:44:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T20:39:24.000Z", "max_forks_repo_path": "src/truncnorm.jl", "max_forks_repo_name": "suzannastep/TruncatedNormal.jl", "max_forks_repo_head_hexsha": "3c16866c3afa3920e787513d492689e9e81192ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-12-10T23:34:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T13:59:39.000Z", "avg_line_length": 19.5076923077, "max_line_length": 81, "alphanum_fraction": 0.6285488959, "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012701768145, "lm_q2_score": 0.8519527963298947, "lm_q1q2_score": 0.8057780368995033}} {"text": "# Returns an array of positive prime numbers less than or equal to lim\nfunction sieve(lim :: Int)\n if lim < 2 return [] end\n limi :: Int = (lim - 1) ÷ 2 # calculate the required array size\n isprime :: Array{Bool} = trues(limi)\n llimi :: Int = (isqrt(lim) - 1) ÷ 2 # and calculate maximum root prime index\n result :: Array{Int} = [2] #Initial array\n for i in 1:limi\n if isprime[i]\n p = i + i + 1 # 2i + 1\n if i <= llimi\n for j = (p*p-1)>>>1:p:limi # quick shift/divide in case LLVM doesn't optimize divide by 2 away\n isprime[j] = false\n end\n end\n push!(result, p)\n end\n end\n return result\nend\n", "meta": {"hexsha": "a8078cdcb23b0149c349e6d8c9c3302953f81f09", "size": 724, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/sieve-of-eratosthenes-1.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/sieve-of-eratosthenes-1.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/sieve-of-eratosthenes-1.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4761904762, "max_line_length": 110, "alphanum_fraction": 0.5345303867, "num_tokens": 221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9669140187510509, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.8057532353784563}} {"text": "@doc raw\"\"\"\n ChiSquared()\n\nThe Chi-Squared base function is given by:\n\n```math\nf(\\mathbf{x}, \\mathbf{y}) = \\sum_i \\frac{(x_i - y_i)^2}{x_i + y_i}\n```\n\"\"\"\nstruct ChiSquared <: PreMetric end\n\n@inline function base_aggregate(::ChiSquared, s::T, x::T, y::T) where {T}\n x == y == zero(T) ? s : s + (x-y)^2/(x+y)\nend\n", "meta": {"hexsha": "dfdbfa17e8081a5e8e53d792b5af03200e5ab237", "size": 317, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/basefunctions/chisquared.jl", "max_stars_repo_name": "holtri/MLKernels.jl", "max_stars_repo_head_hexsha": "d7b84b1bd7b9d9ca4cb7c413d0e34b04c09a331c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/basefunctions/chisquared.jl", "max_issues_repo_name": "holtri/MLKernels.jl", "max_issues_repo_head_hexsha": "d7b84b1bd7b9d9ca4cb7c413d0e34b04c09a331c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/basefunctions/chisquared.jl", "max_forks_repo_name": "holtri/MLKernels.jl", "max_forks_repo_head_hexsha": "d7b84b1bd7b9d9ca4cb7c413d0e34b04c09a331c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1333333333, "max_line_length": 73, "alphanum_fraction": 0.5867507886, "num_tokens": 115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9669140216112959, "lm_q2_score": 0.8333245870332531, "lm_q1q2_score": 0.8057532277558951}} {"text": "\n# coding: utf-8\n\n# In[1]:\n\n\n#another fractal script via recursion\n#this script heavily involves analytic geometry\n#a good material to help you rewind high school geometry\n# https://youthconway.com/handouts/analyticgeo.pdf\nusing Plots\n\n\n# In[2]:\n\n\n#simple solution to get coefficients of the equation\nfunction get_line_params(x1,y1,x2,y2)\n \n slope=(y1-y2)/(x1-x2)\n intercept=y1-slope*x1\n \n return slope,intercept\n\nend\n\n#compute euclidean distance\nfunction euclidean_distance(point1,point2)\n return √((point1[1]-point2[1])^2+(point1[2]-point2[2])^2)\nend\n\n#standard solution to quadratic equation\nfunction solve_quadratic_equation(A,B,C)\n x1=(-B+√(B^2-4*A*C))/(2*A)\n x2=(-B-√(B^2-4*A*C))/(2*A)\n return [x1,x2]\nend\n\n#analytic geometry to compute target datapoints\nfunction get_datapoint(pivot,measure,length,direction=\"inner\")\n \n #for undefined slope\n if pivot[1]==measure[1]\n y1=pivot[2]+length\n y2=pivot[2]-length\n x1=pivot[1]\n x2=pivot[1]\n \n #for general cases\n else\n\n #get line equation\n slope,intercept=get_line_params(pivot[1],pivot[2],\n measure[1],measure[2],)\n\n #solve quadratic equation\n A=1\n B=-2*pivot[1]\n C=pivot[1]^2-length^2/(slope^2+1)\n x1,x2=solve_quadratic_equation(A,B,C)\n\n #get y from line equation\n y1=slope*x1+intercept\n y2=slope*x2+intercept\n \n end\n \n if direction==\"inner\"\n \n #take the one between pivot and measure points\n if euclidean_distance((x1,y1),measure)euclidean_distance((x2,y2),measure)\n datapoint=(x1,y1)\n else\n datapoint=(x2,y2)\n end\n \n end\n \n return datapoint\n \nend\n\n#recursively compute the coordinates of koch curve data points\n#to effectively connect the data points,the best choice is to use turtle\n#it would be too difficult to connect the dots via analytic geometry\nfunction koch_snowflake(base1,base2,base3,n,arr)\n\n #base case\n if n==0\n return\n \n else\n \n #find mid point\n #midpoint between base1 and base2 has to satisfy two conditions\n #it has to be on the same line as base1 and base2\n #assume this line follows y=kx+b\n #the midpoint is (x,kx+b)\n #base1 is (α,kα+b),base2 is (δ,kδ+b)\n #the euclidean distance between midpoint and base1 should be\n #half of the euclidean distance between base1 and base2\n #(x-α)^2+(kx+b-kα-b)^2=((α-δ)^2+(kα+b-kδ-b)^2)/4\n #apart from x,everything else in the equation is constant\n #this forms a simple quadratic solution to get two roots\n #one root would be between base1 and base2 which yields midpoint\n #and the other would be farther away from base2\n #this function solves the equation via (-B+(B^2-4*A*C)^0.5)/(2*A)\n #alternatively,you can use scipy.optimize.root\n #the caveat is it does not offer both roots\n #a wrong initial guess could take you to the wrong root\n midpoint=get_datapoint(base1,base2,euclidean_distance(base1,base2)/2)\n\n #compute the top point of a triangle\n #the computation is similar to midpoint\n #the euclidean distance between triangle_top and midpoint should be\n #one third of the distance between base3 and midpoint\n triangle_top=get_datapoint(midpoint,base3,\n euclidean_distance(midpoint,base3)/3,\n \"outer\")\n\n #two segment points divide a line into three equal parts\n #the computation is almost the same as midpoint\n #the euclidean distance between segment1 and base1\n #should be one third of the euclidean distance between base2 and base1\n segment1=get_datapoint(base1,base2,euclidean_distance(base1,base2)/3)\n segment2=get_datapoint(base2,base1,euclidean_distance(base1,base2)/3)\n\n #compute the nearest segment point of the neighboring line\n segment_side_1=get_datapoint(base1,base3,euclidean_distance(base1,base3)/3)\n segment_side_2=get_datapoint(base2,base3,euclidean_distance(base2,base3)/3)\n \n append!(arr,[segment1,segment2,triangle_top])\n \n #recursion\n koch_snowflake(base1,segment1,segment_side_1,n-1,arr)\n koch_snowflake(segment1,triangle_top,segment2,n-1,arr)\n koch_snowflake(triangle_top,segment2,segment1,n-1,arr)\n koch_snowflake(segment2,base2,segment_side_2,n-1,arr)\n end\n arr\nend\n\n\n# In[3]:\n\n\n#set data points\npoint1=(0.0,0.0)\npoint2=(3.0,0.0)\npoint3=(1.5,1.5*√(3))\n\nn=4\n\n\n# In[4]:\n\n\n#collect coordinates\ncoordinates=[point1,point2,point3]\nappend!(coordinates,koch_snowflake(point1,point2,point3,n,[]))\nappend!(coordinates,koch_snowflake(point3,point1,point2,n,[]))\nappend!(coordinates,koch_snowflake(point2,point3,point1,n,[]));\n\n\n# In[5]:\n\n\n#viz\n#visually u can tell some of the data points are miscalculated\n#purely caused by floating point arithmetic\ngr(size=(250,250))\nscatter([i[1] for i in coordinates],\n [i[2] for i in coordinates],markersize=2,\n legend=false,showaxis=false,ticks=false,grid=false)\n\n\n", "meta": {"hexsha": "3b825e06d8c310c1b542698cf68771fd0cee357e", "size": 5444, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "koch snowflake.jl", "max_stars_repo_name": "je-suis-tm/recursion-and-dynamic-programming", "max_stars_repo_head_hexsha": "55a6085cd45b73426379ff947d9a842ef7d325bb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2019-03-22T10:31:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T13:30:17.000Z", "max_issues_repo_path": "koch snowflake.jl", "max_issues_repo_name": "je-suis-tm/recursion-and-dynamic-programming", "max_issues_repo_head_hexsha": "55a6085cd45b73426379ff947d9a842ef7d325bb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "koch snowflake.jl", "max_forks_repo_name": "je-suis-tm/recursion-and-dynamic-programming", "max_forks_repo_head_hexsha": "55a6085cd45b73426379ff947d9a842ef7d325bb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2019-10-27T12:34:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T13:54:37.000Z", "avg_line_length": 29.2688172043, "max_line_length": 83, "alphanum_fraction": 0.6552167524, "num_tokens": 1512, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9719924818279465, "lm_q2_score": 0.8289387998695209, "lm_q1q2_score": 0.8057222813686551}} {"text": "# This file is a part of Julia. License is MIT: https://julialang.org/license\n\nfunction laplace_iter_devec(u, dx2, dy2, Niter, N)\n uout = copy(u)\n for iter = 1:Niter\n for i = 2:N-1\n for j = 2:N-1\n uout[i,j] = ( (u[i-1,j]+u[i+1,j])*dy2 + (u[i,j-1]+u[i,j+1])*dx2 ) * (1./(2*(dx2+dy2)))\n end\n end\n u, uout = uout, u\n end\n return u\nend\n\nfunction laplace_devec()\n N = 150\n u = zeros(N, N)\n u[1,:] = 1\n Niter = 2^10\n dx2 = dy2 = 0.1*0.1\n u = laplace_iter_devec(u, dx2, dy2, Niter, N)\nend\n\nfunction laplace_iter_vec(u, dx2, dy2, Niter, N)\n for i = 1:Niter\n u[2:N-1, 2:N-1] = ((u[1:N-2, 2:N-1] + u[3:N, 2:N-1])*dy2 + (u[2:N-1,1:N-2] + u[2:N-1, 3:N])*dx2) * (1./ (2*(dx2+dy2)))\n end\n return u\nend\n\nfunction laplace_vec()\n N = 150\n u = zeros(N,N)\n u[1,:] = 1\n Niter = 2^10\n dx2 = dy2 = 0.1*0.1\n u = laplace_iter_vec(u, dx2, dy2, Niter, N)\nend\n\nfunction laplace_iter_vec_sub(u, dx2, dy2, Niter, N)\n for i = 1:Niter\n u[2:N-1, 2:N-1] = ((view(u, 1:N-2, 2:N-1) + view(u,3:N, 2:N-1))*dy2 + (view(u,2:N-1,1:N-2) + view(u,2:N-1, 3:N))*dx2) * (1./ (2*(dx2+dy2)))\n end\n return u\nend\n\nfunction laplace_vec_sub()\n N = 150\n u = zeros(N,N)\n u[1,:] = 1\n Niter = 2^10\n dx2 = dy2 = 0.1*0.1\n u = laplace_iter_vec_sub(u, dx2, dy2, Niter, N)\nend\n", "meta": {"hexsha": "010adc2bd43e03e9bdb35fb81b893abf2d2dae41", "size": 1373, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/perf/kernel/laplace.jl", "max_stars_repo_name": "caodi/julia", "max_stars_repo_head_hexsha": "3dfe8ad16b5d6409f747ba322079521906b80718", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-01-14T09:48:20.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-14T09:48:20.000Z", "max_issues_repo_path": "test/perf/kernel/laplace.jl", "max_issues_repo_name": "caodi/julia", "max_issues_repo_head_hexsha": "3dfe8ad16b5d6409f747ba322079521906b80718", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2015-05-20T15:25:06.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-27T18:11:41.000Z", "max_forks_repo_path": "test/perf/kernel/laplace.jl", "max_forks_repo_name": "caodi/julia", "max_forks_repo_head_hexsha": "3dfe8ad16b5d6409f747ba322079521906b80718", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-27T22:05:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-27T22:05:58.000Z", "avg_line_length": 24.5178571429, "max_line_length": 147, "alphanum_fraction": 0.5091041515, "num_tokens": 630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632956467157, "lm_q2_score": 0.868826771143471, "lm_q1q2_score": 0.8057180578337041}} {"text": "using Turing\n#using Plots; gr()\n\n# NOTE: chiange-point model is taken from http://www.mit.edu/~ilkery/papers/GibbsSampling.pdf\n@model change_point(x) = begin\n N = length(x)\n n ~ Uniform(1, N)\n lam1 ~ Gamma(2, 1)\n lam2 ~ Gamma(2, 1)\n for i = 1:floor(Int, n)\n x[i] ~ Poisson(lam1)\n end\n for i = floor(Int, n)+1:N\n x[i] ~ Poisson(lam2)\n end\nend\n\n_N = 50\n_n = floor(Int, rand(Uniform(1, _N)))\n_lam1 = rand(Gamma(2, 1))\n_lam2 = rand(Gamma(2, 1))\nx = Vector{Int}(undef, _N)\nfor i = 1:_n\n x[i] = rand(Poisson(_lam1))\nend\nfor i = _n+1:_N\n x[i] = rand(Poisson(_lam2))\nend\nprintln(\"N = $_N, n = $_n, lam1 = $_lam1, lam2 = $_lam2\")\n\n#plot(x, linetype=[:scatter], lab=\"data point\")\n#plot!([_n], linetype=:vline, lab=\"change point\")\n\nmodelf = change_point(x)\n\nchn = sample(modelf, SMC(2000))\n\nlam1_ = mean(chn[:lam1]); lam2_ = mean(chn[:lam2]); n_ = mean(chn[:n])\n\n#plot!([i <= n_ ? lam1_ : lam2_ for i = 1:_N], linetype=:steppre, lab=\"inference result\")\n#title!(\"Change-point model (raw data & inference results)\")\n#xlabel!(\"n\"); ylabel!(\"counts\")\n", "meta": {"hexsha": "0e26f753f3fcb4a480b0b97883bb4b3ec5b6ab04", "size": 1052, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "benchmarks/change-point.jl", "max_stars_repo_name": "JuliaTagBot/ContinuousBenchmarks.jl", "max_stars_repo_head_hexsha": "000432d25acef05a11ea51dedfd841c761735e0a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "benchmarks/change-point.jl", "max_issues_repo_name": "JuliaTagBot/ContinuousBenchmarks.jl", "max_issues_repo_head_hexsha": "000432d25acef05a11ea51dedfd841c761735e0a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benchmarks/change-point.jl", "max_forks_repo_name": "JuliaTagBot/ContinuousBenchmarks.jl", "max_forks_repo_head_hexsha": "000432d25acef05a11ea51dedfd841c761735e0a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4651162791, "max_line_length": 93, "alphanum_fraction": 0.6245247148, "num_tokens": 408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107949104866, "lm_q2_score": 0.8596637577007394, "lm_q1q2_score": 0.8056861537104459}} {"text": "### A Pluto.jl notebook ###\n# v0.12.21\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 1f62d332-8303-11eb-31e8-4b34a42c4b9f\nbegin\n using Pkg\n Pkg.activate(\"MLJ_env\", shared=true)\n\n using DataFrames\n using PlutoUI\n using Test\n using Printf\n using Plots\n using LinearAlgebra\n using Random\n using Statistics\n\tusing StatsBase\n\tusing Distributions\n\tusing Images\n\tusing ImageIO\nend\n\n# ╔═╡ f7ad6d8c-8467-11eb-081d-2ba27071eec5\nusing Colors #, ImageMetadata\n\n# ╔═╡ d67867cc-8302-11eb-3d40-d5a50515cdb9\nmd\"\"\"\n## C04w04: Fitting Gaussian Mixture Models with EM\n\nIn this assignment we will\n - implement the EM algorithm for a Gaussian mixture model\n - apply your implementation to cluster images\n - explore clustering results and interpret the output of the EM algorithm\n\"\"\"\n\n# ╔═╡ 53e17eba-8303-11eb-2471-eb8521bf88d2\nmd\"\"\"\n### Implementing the EM algorithm for Gaussian mixture models\n\nIn this section, we will implement the EM algorithm taking the following steps:\n - Provide a log likelihood function for this model.\n - Implement the EM algorithm.\n - Create some synthetic data.\n - Visualize the progress of the parameters during the course of running EM.\n - Visualize the convergence of the model.\n\"\"\"\n\n# ╔═╡ 68c8f63a-8303-11eb-0ae3-c3f39e9acf8d\nmd\"\"\"\n#### Log likelihood\n\nWe provide a function to calculate log likelihood for mixture of Gaussians. The log likelihood quantifies the probability of observing a given set of data under a particular setting of the parameters in our model.\n\nWe will use this to assess the convergence of our EM algorithm; specifically, we will keep looping through EM update steps until the log likehood ceases to increase at a certain rate.\n\"\"\"\n\n# ╔═╡ 84b9158c-8303-11eb-2ce4-c109ce3ff51a\nfunction log_sum_exp(z)\n \"\"\"\n Compute log(Σᵢ exp(zᵢ)) for some array z.\n \"\"\"\n max_z = maximum(z)\n max_z + log(sum(exp.(z .- max_z)))\nend\n\n# ╔═╡ c01ba57e-8303-11eb-34e7-dfb911bac2f2\nfunction log_likelihood(data, weights, μ, σ)\n \"\"\"\n Compute the log likelihood of the data for a Gaussian mixture model\n\twith the given parameters.\n \"\"\"\n nclusters, ndim = length(μ), size(data[1])[1]\n\tDT = eltype(data[1])\n llh = zero(DT)\n\n for d ∈ data\n z = zeros(DT, nclusters)\n for k ∈ 1:nclusters\n ## Compute: (x - μ)ᵀ × Σ⁻¹ × (x - μ)\n δ = reshape(d .- μ[k], :, 1) # make sure 2-dim!\n exp_term = dot(δ', inv(σ[k]) * δ)\n\t\t\t\n ## Compute log likelihood contribution for this data point\n\t\t\t## and this cluster\n z[k] += log(weights[k])\n z[k] -= 1/2. * (ndim * log(2. * π) + log(det(σ[k])) + exp_term)\n \tend\n\t\t## Increment llh contribution of this data point across all clusters\n\t\tllh += log_sum_exp(z)\n \tend\n llh\nend\n\n# ╔═╡ 835e2f8e-8444-11eb-3f3c-d534adaf4bd6\nfunction approx(actᵥ::T, expᵥ::T; ϵ=1e-8) where T <: Real\n\tabs(actᵥ - expᵥ) ≤ ϵ\nend\n\n# ╔═╡ b0655cea-8445-11eb-1fbc-9350beaed253\nfunction approx(actᵥ::AbstractArray{T}, expᵥ::AbstractArray{T};\n\t\tϵ=1e-8) where T <: Real\n\tall(t -> approx(t[1], t[2]; ϵ), zip(actᵥ, expᵥ))\nend\n\n# ╔═╡ 2d4fb59a-8449-11eb-3f02-a5ece0576a9b\nfunction approx(actᵥ::AbstractArray{T}, expᵥ::AbstractArray{T};\n\t\tϵ=1e-8) where {T <: AbstractArray{T1} where T1 <: Real}\n\tall(t -> approx(t[1], t[2]; ϵ), zip(actᵥ, expᵥ))\nend\n\n# ╔═╡ 580675c0-830a-11eb-16e4-b963a391b138\nmd\"\"\"\n#### E-step: assign cluster responsibilities, given current parameters\n\nThe first step in the EM algorithm is to compute cluster responsibilities.\n\nLet $r_{ik}$ denote the responsibility of cluster $k$ for data point $i$.\nNote that cluster responsibilities are fractional parts. *Cluster responsibilities for a single data point $i$ should sum to 1*.\n\n$$r_{i1} + r_{i2} + \\ldots + r_{iK} = 1$$\n\nTo figure how much a cluster is responsible for a given data point, we compute the likelihood of the data point under the particular cluster assignment, multiplied by the weight of the cluster.
\nFor data point $i$ and cluster $k$, this quantity is\n\n$$r_{ik} \\propto \\pi_k N(x_i | \\mu_k, \\Sigma_k)$$\n\nwhere $N(x_i | \\mu_k, \\Sigma_k)$ is the Gaussian distribution for cluster $k$ (with mean $\\mu_k$ and covariance $\\Sigma_k$).\n\nWe used $\\propto$ because the quantity $N(x_i | \\mu_k, \\Sigma_k)$ is not yet the responsibility we want.
To ensure that all responsibilities over each data point add up to 1, we add the normalization constant in the denominator:\n\n$$r_{ik} = \\frac{\\pi_k N(x_i | \\mu_k, \\Sigma_k)}{\\sum_{k=1}^{K} \\pi_k N(x_i | \\mu_k, \\Sigma_k)}$$\n\nComplete the following function that computes $r_{ik}$ for all data points $i$ and clusters $k$.\n\"\"\"\n\n# ╔═╡ 4d69bcec-830c-11eb-0c80-314c8cded6db\nfunction compute_responsibilities(data, weights, μ, σ)\n \"\"\"\n E-step fo EM Algorithm:\n - compute responsibilities, given the current parameters\n \"\"\"\n\t@assert length(data) > 0\n\n ndata, nclusters = length(data), length(μ)\n resp = zeros(eltype(data[1]), ndata, nclusters)\n\n ## Update resp. matrix so that resp[i, k] is the responsibility of\n\t## cluster k for data point i.\n for i ∈ 1:ndata\n for k ∈ 1:nclusters\n\t\t\td = MvNormal(μ[k], σ[k])\n\t\t\tresp[i, k] = weights[k] * pdf(d, data[i])\n\t\tend\n\tend\n ## Add up responsibilities over each data point and normalize\n row_sums = reshape(sum(resp, dims=2), :, 1)\n resp ./= row_sums\nend\n\n# ╔═╡ 31835154-830d-11eb-09fd-196046609868\nbegin\n # const ϵ = 1e-8\n resp₀ = compute_responsibilities([[1., 2.], [-1., -2.]],\n\t[0.3, 0.7], # weights\n [[0., 0.], [1., 1.]], # μ\n\t[[1.5 0.; 0. 2.5], [1. 1.; 1. 2.]] # σ\n )\n\n @test size(resp₀) == (2, 2)\n @test approx(resp₀, [0.10512733 0.89487267; 0.46468164 0.53531836])\nend\n\n# ╔═╡ 430e58a8-8310-11eb-2a53-ed2608f43122\nmd\"\"\"\n#### M-step: Update parameters, given current cluster responsibilities\n\nOnce the cluster responsibilities are computed, we update the parameters (*weights*, *means*, and *covariances*) associated with the clusters.\n\n**Computing soft counts**. Before updating the parameters, we first compute what is known as \"soft counts\".\n\nThe soft count of a cluster is the sum of all cluster responsibilities for that cluster:\n\n$$N^{\\text{soft}}_k = r_{1k} + r_{2k} + \\ldots + r_{Nk} = \\sum_{i=1}^{N} r_{ik}$$\n\nwhere we loop over data points. Note that, unlike k-means, we must loop over every single data point in the dataset. This is because all clusters are represented in all data points, to a varying degree.\n\n\"\"\"\n\n# ╔═╡ 42ef055c-8310-11eb-1ae5-d5ae8bf22c1f\n\"\"\"\n Compute the total responsibility assigned to each cluster, which will be useful when\n implementing M-steps below. In the lectures this is called N^soft\n\"\"\"\ncompute_soft_counts(resp) = sum(resp; dims=1)\n\n# ╔═╡ 93988ed8-8310-11eb-15f4-554b537eacd6\nmd\"\"\"\n**Updating weights.** The cluster weights show us how much each cluster is represented over all data points.\n\nThe weight of cluster $k$ is given by the ratio of the soft count\n$N^{\\text{soft}}_{k}$ to the total number of data points $N$:\n\n$$\\hat{\\pi}_k = \\frac{N^{\\text{soft}}_{k}}{N}$$\n\nNotice that $N$ is equal to the sum over the soft counts $N^{\\text{soft}}_{k}$ of all clusters.\n\nComplete the following function:\n\"\"\"\n\n# ╔═╡ 937da226-8310-11eb-1966-6bcc8ff3cb47\nfunction compute_weights(counts)\n nclusters, n = length(counts), sum(counts)\n weights = zeros(eltype(counts), nclusters)\n\n\tfor k ∈ 1:nclusters\n ## Update the weight for cluster k using the M-step update rule for\n\t\t## the cluster weight: π̂ₖ\n weights[k] = counts[k] / n\n\tend\n weights\nend\n\n# ╔═╡ 93653664-8310-11eb-23f2-d5236b8bc0ed\nbegin\n\tresp₁ = compute_responsibilities([[1., 2.], [-1.,-2.], [0., 0.]],\n\t\t[0.3, 0.7], # weights\n\t\t[[0., 0.], [1., 1.]], # μ\n\t\t[[1.5 0.; 0. 2.5], [1. 1.; 1. 2.]] # σ\n \t)\n\tcounts₁ = compute_soft_counts(resp₁)\n\tweights₁ = compute_weights(counts₁)\n\n\t@test approx(weights₁, [0.27904865942515705 0.720951340574843])\nend\n\n# ╔═╡ 93490854-8310-11eb-3de5-5b24918d8840\nwith_terminal() do\n println(\" - counts: $(counts₁)\")\n println(\" - weigths: $(weights₁)\")\n println(\"Checkpoint passed!\")\nend\n\n# ╔═╡ 42d1c078-8310-11eb-2262-bb5ae92a2b27\nmd\"\"\"\n**Updating means**. The mean of each cluster is set to the [weighted average](https://en.wikipedia.org/wiki/Weighted_arithmetic_mean) of all data points, weighted by the cluster responsibilities:\n\n$$\\hat{\\mu}_k = \\frac{1}{N_k^{\\text{soft}}} \\sum_{i=1}^N r_{ik}x_i$$\n\nComplete the following function:\n\"\"\"\n\n# ╔═╡ 1b27764e-8315-11eb-3854-f9e5b591744a\nfunction compute_means(data, resp, counts)\n nclusters, ndata = length(counts), length(data)\n means = [zeros(eltype(data[1]), length(data[1])) for _ ∈ 1:nclusters]\n\n for k in 1:nclusters\n ## Update means for cluster k using the M-step update rule\n\t\t## for the mean variables.\n ## This will assign the variable means[k] to be our estimate for μ̂ₖ.\n weighted_sum = sum(\n [resp[i, k] * data[i] for i ∈ 1:ndata]\n )\n means[k] = weighted_sum / counts[k]\n\tend\n means\nend\n\n# ╔═╡ 34b1bb5e-8317-11eb-0260-5f1d3132a7ba\nbegin\n\tdata_tmp = [[1., 2.], [-1.,-2.]]\n\tresp₂ = compute_responsibilities(data_tmp,\n\t\t[0.3, 0.7], # weights\n\t\t[[0., 0.], [1., 1.]], # μ\n\t\t[[1.5 0.; 0. 2.5], [1. 1.; 1. 2.]] # σ\n\t)\n\tcounts₂ = compute_soft_counts(resp₂)\n\tmeans₂ = compute_means(data_tmp, resp₂, counts₂)\n\texp_means₂ = [[-0.6310085, -1.262017], [0.25140299, 0.50280599]]\n\t@test approx(means₂[1], exp_means₂[1])\n\t@test approx(means₂[2], exp_means₂[2])\nend\n\n# ╔═╡ 1ad0cbe4-8315-11eb-341c-dbce64acb374\nwith_terminal() do\n println(\" - counts: $(counts₂)\")\n println(\" - means: $(means₂)\")\n println(\"Checkpoint passed!\")\nend\n\n# ╔═╡ 1a99af8a-8315-11eb-0f74-eb97741a40ca\nmd\"\"\"\n\n**Updating covariances**. The covariance of each cluster is set to the weighted average of all [outer products](https://people.duke.edu/~ccc14/sta-663/LinearAlgebraReview.html), weighted by the cluster responsibilities:\n\n$$\\hat{\\Sigma}_k = \\frac{1}{N^{\\text{soft}}_k}\\sum_{i=1}^N r_{ik} (x_i - \\hat{\\mu}_k)(x_i - \\hat{\\mu}_k)^T$$\n\nThe \"outer product\" in this context refers to the matrix product\n\n$$(x_i - \\hat{\\mu}_k)(x_i - \\hat{\\mu}_k)^T.$$\nLetting $(x_i - \\hat{\\mu}_k)$ to be $d \\times 1$ column vector, this product is a $d \\times d$ matrix. Taking the weighted average of all outer products gives us the covariance matrix, which is also $d \\times d$.\n\nReminder:\nThe inner product (of two column vectors $1 \\times n$) denoted as $ = v^{t}w$ is a scalar, whereas the outer product of the same two column vectors denoted as $v \\otimes w = vw^{t}$ is a matrix.\n\nComplete the following function:\n\n\"\"\"\n\n# ╔═╡ 986e362c-8317-11eb-0eef-cd1de11cd4b2\nfunction compute_covariances(data, resp, counts, μ)\n nclusters, ndim, ndata = length(counts), size(data[1])[1], length(data)\n covs = [zeros(eltype(data[1]), ndim, ndim) for _ ∈ 1:nclusters]\n\n for k ∈ 1:nclusters\n ## Update covariances for cluster k using the M-step update rule\n\t\t## for covariance variables.\n ## This will assign the variable covariances[k] to be the estimate for Σ̂ₖ.\n w_sum = zeros(eltype(data[1]), ndim, ndim)\n for i ∈ 1:ndata\n w_sum += resp[i, k] * ((data[i] - μ[k]) * (data[i] - μ[k])')\n\t\tend\n\t\tcovs[k] = (1. / counts[k]) * w_sum\n\tend\n covs\nend\n\n# ╔═╡ 57c76562-8373-11eb-0e43-256ec189f399\nbegin\n\t## deps on prev test cell for resp₂, counts₂, means₂\n\tcovs₂ = compute_covariances(data_tmp, resp₂, counts₂, means₂)\n\n\texp_covs₂ = [\n\t\t[0.60182827 1.20365655; 1.20365655 2.4073131],\n\t\t[0.93679654 1.87359307; 1.87359307 3.74718614]\n\t]\n\n\t@test approx(covs₂[1], exp_covs₂[1])\n\t@test approx(covs₂[2], exp_covs₂[2])\nend\n\n# ╔═╡ a12bc08e-8371-11eb-29f0-e14f2c17c1d1\nwith_terminal() do\n println(\" - covariances: $(covs₂)\")\n println(\"Checkpoint passed!\")\nend\n\n# ╔═╡ c59d7e92-8373-11eb-09d1-55814d7e9f9e\nmd\"\"\"\n#### The EM algorithm\n\nNow let us write a function that takes initial parameter estimates and runs EM.\n\"\"\"\n\n# ╔═╡ c5808488-8373-11eb-3d9a-51c955524390\nfunction em(data, init_μ, init_σ, init_weights;\n maxiter=1000, ϵ=1e-4)\n ## Make copies of initial parameters, which we will update during each iteration\n μ, σ = copy(init_μ), copy(init_σ)\n weights = copy(init_weights)\n\n ## Infer dimensions of dataset and the number of clusters\n ndata, ndim, nclusters = length(data), size(data[1])[1], length(μ)\n\n ## Initialize some useful variables\n resp = zeros(eltype(data[1]), ndata, nclusters)\n llh = log_likelihood(data, weights, μ, σ)\n llh_trace = [llh]\n\tn_iter = 1\n for it ∈ 1:maxiter\n\t\tn_iter += 1\n it % 5 == 0 && println(\"Iteration $(it) / $(maxiter)\")\n\n ## E-step: compute responsibilities\n resp = compute_responsibilities(data, weights, μ, σ)\n\t\t\n ## M-step\n ## Calc. the total resp. assigned to each cluster, useful when\n ## implementing M-steps below. In the lectures this is called N^{soft}\n counts = compute_soft_counts(resp)\n\t\t\n ## update weight of cluster k using M-step update rule for cluster weight π̂ₖ\n weights = compute_weights(counts)\n\t\t\n ## update means of cluster k using the M-step update rule for the mean vars.\n ## assign the variable μ[k] to be our estimate for μ̂ₖ.\n μ = compute_means(data, resp, counts)\n\t\t\n ## update covs ofcluster k using the M-step update rule for cov vars.\n ## assign the variable σ[k] to be the estimate for Σ̂ₖ.\n σ = compute_covariances(data, resp, counts, μ)\n\t\t\n ## Compute the loglikelihood at this iteration\n llh_latest = log_likelihood(data, weights, μ, σ)\n push!(llh_trace, llh_latest)\n\n ## Check for convergence in log-likelihood and store\n (llh_latest - llh) < ϵ && llh_latest > -Base.Inf && break\n llh = llh_latest\n \tend\n \tDict{Symbol, Any}(\n \t:weights => weights,\n \t:means => μ,\n \t:covs => σ,\n \t:loglik => llh_trace,\n \t:resp => resp\n \t)\nend\n\n# ╔═╡ c56791bc-8373-11eb-00e3-230f82206892\nmd\"\"\"\n#### Testing the implementation on the simulated data\n\nTo help us develop and test our implementation, we will generate some observations from a mixture of Gaussians and then run our EM algorithm to discover the mixture components.\nWe'll begin with a function to generate the data, and a quick plot to visualize its output for a 2-dimensional mixture of three Gaussians.\n\nNow we will create a function to generate data from a mixture of Gaussians model.\n\"\"\"\n\n# ╔═╡ a790272e-8375-11eb-2a40-df02f3d1ca24\nfunction generate_mog_data(ndata, μ, σ, weights; seed=42)\n \"\"\"\n Creates a list of data points\n \"\"\"\n nclusters = length(weights)\n data = []\n\n\tRandom.seed!(seed)\n\trng = MersenneTwister(seed)\n\n for i ∈ 1:ndata\n ## Use sample (from StatsBase) and weights to pick a: \n\t\t## 1 ≤ cluster_id < nclusters\n\t\tk = sample(rng, 1:nclusters, Weights(weights), 1; replace=false)[1]\n\n\t\t## Use np.random.multivariate_normal to create data from this cluster\n\t\tx = rand(MvNormal(μ[k], σ[k])) ## ????\n\n\t\t# np.random.multivariate_normal(means[k], covariances[k])\n push!(data, x)\n\tend\n\tdata\nend\n\n# ╔═╡ 00261792-8441-11eb-3969-55f797a05e23\n\n\n# ╔═╡ a740cde6-8375-11eb-0f2a-efc1f23f8f38\nbegin\n init_μ = [\n\t[5., 0.], # mean of cluster 1\n\t[1., 1.], # mean of cluster 2\n\t[0., 5.] # mean of cluster 3\n ]\n\n init_σ =[\n\t[.5 0.; 0 .5], # covariance of cluster 1\n\t[.92 .38; .38 .91], # covariance of cluster 2\n\t[.5 0.; 0 .5]] # covariance of cluster 3\n\n init_weights = [1/4., 1/2., 1/4.] # weights of each cluster\n\n data = generate_mog_data(100, init_μ, init_σ, init_weights)\nend\n\n# ╔═╡ a72ae382-8375-11eb-15fc-c750a071dccf\nscatter(map(t -> t[1], data), map(t -> t[2], data), color=[:lightblue], lw=3)\n\n# ╔═╡ b3e522d6-844c-11eb-2aa5-750b3ee4c212\nmd\"\"\"\n**Checkpoint** for *em* function\n\"\"\"\n\n# ╔═╡ 9aee7716-83d7-11eb-3f3c-d534adaf4bd6\n begin\n \tm_data = [[0.31845368, 5.03182099], [1.45029339, 2.15717573],\n [1.02645431, 4.76042375], [ 5.23493625, -0.81138851], [ 4.65710743, -0.08532351],\n [0.43746553, 4.93778385], [-0.12756373, 5.14296293], [4.18200738, 0.24819247],\n [ 1.65646672, -0.87991369], [-0.69508006, 5.03848976], [6.01348014, 1.87722666],\n [ 0.20099208, -0.93213203], [-0.38268222, 0.26365374], [ 5.03394554, -1.66740986],\n [ 1.53889119, -0.12731715], [0.81448617, 1.63543709], [1.7219243 , 0.28460715],\n [4.90757786, 0.56716088], [0.60512066, 4.87555125], [ 1.30867865, -0.58711045],\n [0.19570654, 5.73836612], [3.97078181, 0.39328234], [0.47190777, 1.47637309],\n [1.32157017, 0.56486368], [3.89988459, 0.92433204], [0.11205488, 6.4072012 ],\n [0.40717315, 1.67134485], [0.56231532, 5.01349864],\n [1.82113515, 0.78892223], [-0.77578232, 4.62650898], [ 0.45032469, -1.01099583],\n [2.25024431, 0.64832921], [1.47157789, 1.68387047], [-0.0420993 , 0.50923158],\n [1.18348882, 0.56978228], [5.52201954, 0.46015202], [0.69012115, 1.40085221],\n [0.02126064, 4.76228496], [5.32547107, 1.46856369], [2.58605452, 2.11944448],\n [0.182161 , 4.44577711], [ 0.11836846, -0.33361633], [0.66083532, 1.03879141],\n [1.91659334, 0.63739381], [0.28487706, 4.5665366 ], [0.4764496 , 5.72581327],\n [3.10453287, 2.19997423], [-0.85376105, 4.17389402], [0.08542074, 4.38781614],\n [0.21418408, 5.60131432], [-0.29932464, 4.62574683], [2.25835904, 1.1068076 ],\n [ 4.77358263, -0.06002466], [0.73093444, 1.40220082], [0.39250487, 0.57133562],\n [0.8949198, 1.9300788], [-0.25767001, 4.11851619], [0.55042767, 0.21762904],\n [-0.34493741, 4.57098776], [4.71632515, 0.63293438], [1.67820052, 1.29111918],\n [ 1.4862169 , -0.07691204], [5.46625127, 0.01184258], [-1.33846048, -0.20047555],\n [0.01458455, 5.5685916 ], [1.49605116, 4.82940436], [ 5.75963176, -0.13066323],\n [1.70380591, 1.31376129], [ 4.76328545, -0.33344549], [ 0.8945073 , -1.13036243],\n [1.61279831, 0.66792909], [-0.20028537, 5.0349852 ], [-0.79147695, 4.72403614],\n [1.33337808, 1.427949 ], [1.81545643, 2.37052768], [1.02894019, 3.21262401],\n [-0.1914201 , 4.03020414], [1.45589226, 0.85329139], [2.23603443, 0.87710097],\n [0.32608726, 0.09240739], [-0.18786611, 5.85099597], [4.29931854, 1.35428737],\n [0.49849313, 0.68444377], [-0.8336478 , 5.81745508], [-0.57795091, -1.6674263 ],\n [1.83292993, 0.7963827 ],[1.01736806, 0.8455941 ], [0.48493064, 0.45675926],\n [-0.47669162, 3.91542167],[0.96494312, 0.65663175], [1.04999151, 0.38350349],\n [1.17458921, 0.73066238],[0.04638356, 4.86196943], [1.66742479, 1.54181187],\n [0.94372389, 1.32117047],[ 5.63522868, -0.0138849 ],[0.52699679, 5.37301739],\n [4.80426637, 0.8017483], [-0.00321541, 0.2083691],[1.38949165, 0.95020545]\n\t];\n\n \tm_μs = [[0.19570654, 5.73836612], [6.01348014, 1.87722666],\n\t\t[0.52699679, 5.37301739]];\n\t\n\tm_σs =[[ 3.41361848 -1.91940532; -1.91940532 4.68785076], \n\t\t[ 3.41361848 -1.91940532; -1.91940532 4.68785076], \n\t\t[ 3.41361848 -1.91940532; -1.91940532 4.68785076]];\n\t\n\tm_weights = [0.3333333333333333, 0.3333333333333333, 0.3333333333333333];\n\t\n\tm_results = em(m_data, m_μs, m_σs, m_weights);\n\t:done\nend\n\n# ╔═╡ 4b50e4b0-8444-11eb-3969-55f797a05e23\nbegin\n\t@test approx(m_results[:means], Array{Float64,1}[\n\t\t\tFloat64[0.021382851931258, 4.947729003491], \n\t\t\tFloat64[4.942392352282, 0.3136531084758], \n\t\t\tFloat64[1.0818112539095, 0.73903507897]])\n\n\t@test approx(m_results[:weights], Float64[0.3007102300634, \n\t\t\t0.17993710074063, 0.5193526691959])\n\t\n\t@test approx(m_results[:covs], Array{Float64,2}[ \n\t\t\t[0.2932613984949 0.05048454589297; 0.05048454589297 0.352815373349],\n\t\t\t[0.3556437022527 -0.014948748777286; -0.014948748777286 0.6669502500144],\n\t\t\t[0.6711499192647 0.33058964530721; 0.33058964530721 0.9042972427651]])\n\t\n\t@test approx(m_results[:weights], [0.3007102300634, \n\t\t\t0.17993710074063, 0.5193526691959])\n\t\n\t@test approx(m_results[:loglik][1:5], [-541.3161249736, -372.1355927523,\n\t\t\t-366.9935696838, -365.6599199088, -364.3348647749, -362.87960462340, \n\t\t\t-361.3750403053])\nend\n\n# ╔═╡ a7135b54-8375-11eb-2d63-392c4fa94aea\nmd\"\"\"\n**Now we will fit a mixture of Gaussians** to this data using our implementation of the EM algorithm. As with k-means, it is important to ask how we obtain an initial configuration of mixing weights and component parameters.\n\nIn this simple case, we'll take three random points to be the initial cluster means, use the empirical covariance of the data to be the initial covariance in each cluster (a clear overestimate), and set the initial mixing weights to be uniform across clusters.\n\"\"\"\n\n# ╔═╡ a6fc6796-8375-11eb-02af-01cee06a06dd\nbegin\n\tseed₂ = 2010\n\tRandom.seed!(seed₂)\n\trng = MersenneTwister(seed₂)\n\n\t## Initialization of parameters\n\tconst K = 3\n\tchosen = sample(rng, 1:length(data), K; replace=false)\n \t# np.random.choice(length(data), K, replace=False)\n \t@assert length(chosen) == K\n\n \tinit_μ₁ = [data[x] for x in chosen];\n \tinit_σ₁ = [cov(data) for _ ∈ 1:K]; # cov(data, rowvar=0) => col. is an observ.\n \tinit_w = [1.0 / K for _ ∈ 1:K];\n\n \t## Run EM\n \tresults = em(data, init_μ₁, init_σ₁, init_w);\n\t:done\nend\n\n# ╔═╡ a6b33828-8375-11eb-027a-130ef7a14128\nmd\"\"\"\n**Note**. Like k-means, EM is prone to converging to a local optimum. In practice, you may want to run EM multiple times with different random initialization. We have omitted multiple restarts to keep the assignment reasonably short.\n\n\nOur algorithm returns a dictionary with five elements:\n - 'loglik': a record of the log likelihood at each iteration\n - 'resp': the final responsibility matrix\n - 'means': a list of K means\n - 'covs': a list of K covariance matrices\n - 'weights': the weights corresponding to each model component\n\n\"\"\"\n\n# ╔═╡ 4db52910-844d-11eb-3969-55f797a05e23\nresults[:means]\n\n# ╔═╡ 6f4476bc-844d-11eb-1fbc-9350beaed253\nresults[:weights]\n\n# ╔═╡ 5ab06896-844d-11eb-3f3c-d534adaf4bd6\nmd\"\"\"\n*For the following quiz questions, please round your answer to the nearest thousandth (3 decimals)*\n\n**Quiz Question**: What is the weight that EM assigns to the first component after running the above codeblock?\n\"\"\"\n\n# ╔═╡ a69ff718-8375-11eb-3965-89ecd2088d97\nround(results[:weights][1]; digits=3)\n\n# ╔═╡ a687f546-8375-11eb-3435-1fa822f71ff1\nmd\"\"\"\n**Quiz Question**: Using the same set of results, obtain the mean that EM assigns the second component. What is the mean in the first dimension?\n\"\"\"\n\n# ╔═╡ a66ede62-8375-11eb-3746-758cb7efc8a8\n## Answer: the second component / first dim\nround(results[:means][2][1], digits=3)\n\n# ╔═╡ a657ed74-8375-11eb-1d97-1bd417fa42ee\nmd\"\"\"\n**Quiz Question**: Using the same set of results, obtain the covariance that EM assigns the third component. What is the variance in the first dimension?\n\"\"\"\n\n# ╔═╡ a63e00e4-8375-11eb-10db-897f94a0dc32\n# Answer: covs third component / first dim\nresults[:covs][3, 1]\n\n# ╔═╡ c54c0456-8373-11eb-1cb6-11bf225bc6b0\nmd\"\"\"\n### Plot progress of parameters\n\nOne useful feature of testing our implementation on low-dimensional simulated data is that we can easily visualize the results.\n\nWe will use the following `plot_contours` function to visualize the Gaussian components over the data at three different points in the algorithm's execution:\n\n 1. At initialization (using initial_mu, initial_cov, and initial_weights)\n 2. After running the algorithm to completion\n 3. After just 12 iterations (using parameters estimates returned when setting `maxiter=12`)\n\"\"\"\n\n# ╔═╡ 9ba36afc-83d7-11eb-32d4-4d4d0df107d4\nfunction bivariate_normal(X, Y;\n σ_x=1.0, σ_y=1.0, μ_x=0.0, μ_y=0.0, σ_xy=0.0)\n Xμ = X .- μ_x\n Yμ = Y .- μ_y\n\n ρ = σ_xy / (σ_x * σ_y)\n z = Xμ.^2 ./ σ_x^2 + Yμ.^2 ./ σ_y^2 - 2 * ρ * Xμ .* Yμ ./ (σ_x * σ_y)\n\n \tden = 2. * π * σ_x * σ_y * √(1 - ρ^2)\n\texp.(-z / (2. * (1. - ρ^2))) / den\nend\n\n# ╔═╡ cd5eb61e-83d9-11eb-1df3-9389091527e8\nfunction meshgrid(x, y)\n @assert length(x) == length(y)\n n = length(x)\n\n vx, vy = copy(x), copy(y)\n for _ ∈ 1:n-1\n vx = hcat(vx, x)\n vy = hcat(vy, y)\n end\n vx, vy = reshape(vx, :, n)', reshape(vy, :, n)'\n Matrix(vx), Matrix(vy)\nend\n\n# ╔═╡ 5a708ed0-83d8-11eb-147c-abf3f80f8c92\nfunction plot_contours(data, means, covs, title)\n δ = 0.025\n k = length(means)\n X = Y = range(-3.0; stop=9.0, step=δ) \n\t\n\tcol = [:green, :red, :indigo]\n\tparms = []\n\tscatter([_x[1] for _x ∈ data], [_y[2] for _y ∈ data], legend=false, title=title)\n\t\n\tfor i ∈ 1:K\n\t\tμ, σ = means[i], covs[i]\n\t\tσ_x, σ_y = √(σ[1, 1]), √(σ[2, 2])\n\t\tσ_xy = σ[1, 2] / (σ_x * σ_y)\n\t\t\n\t\tpush!(parms, (σ_x=σ_x, σ_y=σ_y, μ_x=μ[1], μ_y=μ[2], σ_xy=σ_xy))\n\tend\n \t\n\tcontour!(X, Y, (x, y) -> bivariate_normal(x, y; parms[1]...), color=col[1])\n \tcontour!(X, Y, (x, y) -> bivariate_normal(x, y; parms[2]...), color=col[2])\n \tcontour!(X, Y, (x, y) -> bivariate_normal(x, y; parms[3]...), color=col[3])\nend\n\n# ╔═╡ 9b4a0a5e-83d7-11eb-3f02-a5ece0576a9b\nplot_contours(data, init_μ₁, init_σ₁, \"Initial clusters\")\n\n# ╔═╡ e9ae52fe-845e-11eb-15c1-65ebc1f4df8e\nbegin\n\t# Parameters after running EM to convergence\n\tplot_contours(data, results[:means], results[:covs], \"Final clusters\")\nend\n\n# ╔═╡ 3ab0e342-845f-11eb-321d-61972f4e6bd4\nmd\"\"\"\nFill in the following code block to visualize the set of parameters we get after running EM for 12 iterations.\n\"\"\"\n\n# ╔═╡ 4321d874-845f-11eb-107c-c32e7c640947\nbegin\n\tres12 = em(data, init_μ₁, init_σ₁, init_w);\n\tplot_contours(data, res12[:means], res12[:covs], \"Clusters after 12 iterations\")\nend\n\n# ╔═╡ ffd6d3a2-845f-11eb-1308-39662d5cf06e\nmd\"\"\"\n**Quiz Question**: Plot the loglikelihood that is observed at each iteration. Is the loglikelihood plot monotonically increasing, monotonically decreasing, or neither [multiple choice]? \n\"\"\"\n\n# ╔═╡ a3ac0552-845f-11eb-2283-6defb781f7c7\nplot(1:length(results[:loglik]), results[:loglik], lw=3,\n\txlabel=\"Iteration\",\n\tylabel=\"Log-likelihood\",\n\tlegend=false)\n\n# ╔═╡ 125d76fa-8460-11eb-1d49-57e4eea41e89\nmd\"\"\"\n - The loglikelihood is monotonically increasing\n\"\"\"\n\n# ╔═╡ c72c03ba-8469-11eb-2fc0-47dab53b1ce9\nmd\"\"\"\n## Fitting a Gaussian mixture model for image data¶\n\"\"\"\n\n# ╔═╡ 075f9b50-8464-11eb-35b3-c945b1e49ccf\nbegin\n\tconst IMG_DIR = \"../../ML_UW_Spec/data/images\"\n\timages = []\n\t\n\tfor dir_entry ∈ cd(readdir, IMG_DIR)\n\t\tprintln(\"Found $(dir_entry)\")\n\t\tsdir = join([IMG_DIR, dir_entry], \"/\")\n\t\t\n\t\tfor img_file ∈ readdir(sdir)\n\t\t\tpush!(images, load(join([sdir, img_file], \"/\")))\n\t\tend\n\tend\nend\n\n# ╔═╡ a27f740e-8465-11eb-171f-3ff85b79e29b\nlength(images)\n\n# ╔═╡ 77bd32d4-8466-11eb-2713-6b11add92ba3\nmosaicview(images[1:12]...; nrow=3, ncol=4)\n\n# ╔═╡ fb990ba8-8466-11eb-13be-7d3f33c0576c\nmosaicview(images[400:411]...; nrow=3, ncol=4)\n\n# ╔═╡ 36448e26-8467-11eb-12eb-23daf58ea752\nmosaicview(images[700:711]...; nrow=3, ncol=4)\n\n# ╔═╡ d1b3f548-8466-11eb-304e-119b7c99959e\nmosaicview(images[1000:1011]...; nrow=3, ncol=4)\n\n# ╔═╡ 8c8995d0-8467-11eb-3efb-d1a7961fdefa\nimg_data = [\n\t[mean(red.(img)), mean(green.(img)), mean(blue.(img))] for img ∈ images\n]\n\n# ╔═╡ bcc9335c-8469-11eb-1492-d310a071b09a\nmd\"\"\"\nWe need to come up with initial estimates for the mixture weights and component parameters. Let's take three images to be our initial cluster centers, and let's initialize the covariance matrix of each cluster to be diagonal with each element equal to the sample variance from the full data. As in our test on simulated data, we'll start by assuming each mixture component has equal weight.\n\nThis may take a few minutes to run.\n\"\"\"\n\n# ╔═╡ 7b6cc3d8-846e-11eb-315c-5544ae999cc8\nvar_col(img_data, i::Integer) = var(x[i] for x ∈ img_data)\n\n# ╔═╡ daffa734-8469-11eb-35ea-376de2c6e1e3\nbegin\n\tseed₃ = 2010\n\tRandom.seed!(seed₃)\n\trng₃ = MersenneTwister(seed₃)\n\n\t# Initalize parameters\n\tconst KC = 4\n\tconst NC = 3 # 3 colors R, G, B\n\tn_images = length(images)\n\t\n\tim_init_μs = [img_data[x] for x ∈ sample(rng₃, 1:n_images, KC; replace=false)]\n\t@assert length(im_init_μs) == KC\n\t\n\tid_mat = Matrix{Float64}(I, NC, NC);\n\tim_cov = id_mat .* vec([var_col(img_data, c) for c in 1:NC]);\n\t\n\tim_init_σs = [im_cov for _ ∈ 1:KC]; # [cov, cov, cov, cov]\n\tim_init_ws = [1.0 / KC for _ ∈ 1:KC]; # [1/4., 1/4., 1/4., 1/4.]\n\n\t## Run our EM algorithm on the image data using the above initializations. \n\t## This should converge in about 125 iterations\n\tres_img = em(img_data, im_init_μs, im_init_σs, im_init_ws);\n\t:done\nend\n\n# ╔═╡ 7fb68656-8471-11eb-3969-55f797a05e23\nfunction _plot(data_x, data_y)\n plot(data_x, data_y, lw=4, xlabel=\"Iteration\", ylabel=\"Log-likelihood'\")\nend\n\n# ╔═╡ ab34bece-8471-11eb-3f3c-d534adaf4bd6\nbegin\n\tllh_ = res_img[:loglik]\n\t_plot(1:length(llh_), llh_)\nend\n\n# ╔═╡ cccb8bd0-8471-11eb-1fbc-9350beaed253\nmd\"\"\"\nThe log likelihood increases so quickly on the first few iterations that we can barely see the plotted line. Let's plot the log likelihood after the first three iterations to get a clearer view of what's going on:\n\"\"\"\n\n# ╔═╡ d63fd518-8471-11eb-147c-abf3f80f8c92\n_plot(3:length(llh_), llh_[3:end])\n\n# ╔═╡ d624eb68-8471-11eb-32d4-4d4d0df107d4\nmd\"\"\"\n#### Evaluating uncertainty\n\nNext we'll explore the evolution of cluster assignment and uncertainty. Remember that the EM algorithm represents uncertainty about the cluster assignment of each data point through the responsibility matrix. Rather than making a 'hard' assignment of each data point to a single cluster, the algorithm computes the responsibility of each cluster for each data point, where the responsibility corresponds to our certainty that the observation came from that cluster.\n\nWe can track the evolution of the responsibilities across iterations to see how these 'soft' cluster assignments change as the algorithm fits the Gaussian mixture model to the data; one good way to do this is to plot the data and color each point according to its cluster responsibilities. Our data are three-dimensional, which can make visualization difficult, so to make things easier we will plot the data using only two dimensions, taking just the [R G], [G B] or [R B] values instead of the full [R G B] measurement for each observation.\n\n\"\"\"\n\n# ╔═╡ 37bd479e-8472-11eb-3106-e3d88fb54de4\n# TODO...\n\n# ╔═╡ 37a19df0-8472-11eb-2662-6157d71dd17f\nmd\"\"\"\n#### Interpreting each cluster\n\nLet's dig into the clusters obtained from our EM implementation. Recall that our goal in this section is to cluster images based on their RGB values. We can evaluate the quality of our clustering by taking a look at a few images that 'belong' to each cluster. We hope to find that the clusters discovered by our EM algorithm correspond to different image categories - in this case, we know that our images came from four categories ('cloudy sky', 'rivers', 'sunsets', and 'trees and forests'), so we would expect to find that each component of our fitted mixture model roughly corresponds to one of these categories.\n\nIf we want to examine some example images from each cluster, we first need to consider how we can determine cluster assignments of the images from our algorithm output. This was easy with k-means - every data point had a 'hard' assignment to a single cluster, and all we had to do was find the cluster center closest to the data point of interest. Here, our clusters are described by probability distributions (specifically, Gaussians) rather than single points, and our model maintains some uncertainty about the cluster assignment of each observation.\n\nOne way to phrase the question of cluster assignment for mixture models is as follows: how do we calculate the distance of a point from a distribution? Note that simple Euclidean distance might not be appropriate since (non-scaled) Euclidean distance doesn't take direction into account. For example, if a Gaussian mixture component is very stretched in one direction but narrow in another, then a data point one unit away along the 'stretched' dimension has much higher probability (and so would be thought of as closer) than a data point one unit away along the 'narrow' dimension. \n\nIn fact, the correct distance metric to use in this case is known as [Mahalanobis distance](https://en.wikipedia.org/wiki/Mahalanobis_distance). For a Gaussian distribution, this distance is proportional to the square root of the negative log likelihood. This makes sense intuitively - reducing the Mahalanobis distance of an observation from a cluster is equivalent to increasing that observation's probability according to the Gaussian that is used to represent the cluster. This also means that we can find the cluster assignment of an observation by taking the Gaussian component for which that observation scores highest. We'll use this fact to find the top examples that are 'closest' to each cluster.\n\n__Quiz Question:__ Calculate the likelihood (score) of the first image in our data set (`images[0]`) under each Gaussian component through a call to `multivariate_normal.pdf`. Given these values, what cluster assignment should we make for this image? Hint: don't forget to use the cluster weights.\n\"\"\"\n\n# ╔═╡ 3787dc3a-8472-11eb-129f-b5e34bda1328\nres_img[:weights]\n\n# ╔═╡ 37702d1a-8472-11eb-1df3-9389091527e8\nres_img[:means]\n\n# ╔═╡ d606647c-8471-11eb-3f02-a5ece0576a9b\n# d = MvNormal(μ[k], σ[k])\n#\t\t\tresp[i, k] = weights[k] * pdf(d, data[i])\n\n# ╔═╡ d92f92e4-8472-11eb-17cf-eb0a1c444ee9\nbegin\n\tproba_img = Float64[]\n\tfor k in 1:KC\n\t\td = MvNormal(res_img[:means][k], res_img[:covs][k])\n\t\tpush!(proba_img, res_img[:weights][k] * pdf(d, img_data[1]))\n\tend\n\tproba_img\nend\n\n# ╔═╡ d9132afa-8472-11eb-38c5-39d44a1e57f7\nmd\"\"\"\nNow we calculate cluster assignments for the entire image dataset using the result of running EM for 60 iterations above.\n\"\"\"\n\n# ╔═╡ d8f3fd56-8472-11eb-3856-99f30a89c6d3\nbegin\n\tp_weights = res_img[:weights]\n\tp_means = res_img[:means]\n\tp_covs = res_img[:covs]\n\trgb = img_data\n\n\t_N = length(img_data) ## number of images\n\t_K = length(p_means) ## number of clusters\n\n\tassignments = zeros(Float64, _N)\n\tprobs = zeros(Float64, _N)\n\n\tfor i ∈ 1:_N\n \t## Compute the score of data point i under each Gaussian component:\n \tp = [\n\t\t\tp_weights[k] * pdf(MvNormal(p_means[k], p_covs[k]), rgb[i]) for k ∈ 1:_K\n \t]\n\t\n \t## Compute assign. of each data point to a given cluster based on the scores:\n \tassignments[i] = argmax(p)\n \t## For data point i, store the corresponding score under this cluster assign:\n \tprobs[i] = maximum(p)\n\tend\n\n\tdf_assign = DataFrame(:cluster_num => Int.(assignments), :probs => probs, :image => images);\n\t:done\nend\n\n# ╔═╡ 9a3f1a20-8475-11eb-1fbc-9350beaed253\nlast(df_assign, 5)\n\n# ╔═╡ 9a2134e2-8475-11eb-3f3c-d534adaf4bd6\nmd\"\"\"\nWe'll use the 'assignment' DataFrame to find the top images from each cluster by sorting the datapoints within each cluster by their score under that cluster (stored in probs). \n\nCreate a function that returns the top 5 images assigned to a given category in our data.\n\"\"\"\n\n# ╔═╡ 9a00824c-8475-11eb-3969-55f797a05e23\nfunction get_top_images(df, cluster; k=5)\n images_in_cluster = df[df.cluster_num .== cluster, :]\n\ttop_images = sort(images_in_cluster, [:probs], rev=true)[1:k, :]\n top_images.image\nend\n\n# ╔═╡ 17ac70be-8476-11eb-3f02-a5ece0576a9b\nmosaicview(get_top_images(df_assign, 1)...; nrow=2, ncol=3)\n\n# ╔═╡ 8b254648-8477-11eb-1df3-9389091527e8\nmosaicview(get_top_images(df_assign, 2)...; nrow=2, ncol=3)\n\n# ╔═╡ 8b068190-8477-11eb-147c-abf3f80f8c92\nmosaicview(get_top_images(df_assign, 3)...; nrow=2, ncol=3)\n\n# ╔═╡ 8ae806ca-8477-11eb-32d4-4d4d0df107d4\nmosaicview(get_top_images(df_assign, 4)...; nrow=2, ncol=3)\n\n# ╔═╡ a5dc1b88-8477-11eb-129f-b5e34bda1328\nmd\"\"\"\nThese look pretty good! Our algorithm seems to have done a good job overall at 'discovering' the four categories that from which our image data was drawn. It seems to have had the most difficulty in distinguishing between rivers and cloudy skies, probably due to the similar color profiles of images in these categories; if we wanted to achieve better performance on distinguishing between these categories, we might need a richer representation of our data than simply the average [R G B] values for each image.\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─d67867cc-8302-11eb-3d40-d5a50515cdb9\n# ╠═1f62d332-8303-11eb-31e8-4b34a42c4b9f\n# ╟─53e17eba-8303-11eb-2471-eb8521bf88d2\n# ╟─68c8f63a-8303-11eb-0ae3-c3f39e9acf8d\n# ╠═84b9158c-8303-11eb-2ce4-c109ce3ff51a\n# ╠═c01ba57e-8303-11eb-34e7-dfb911bac2f2\n# ╠═835e2f8e-8444-11eb-3f3c-d534adaf4bd6\n# ╠═b0655cea-8445-11eb-1fbc-9350beaed253\n# ╠═2d4fb59a-8449-11eb-3f02-a5ece0576a9b\n# ╟─580675c0-830a-11eb-16e4-b963a391b138\n# ╠═4d69bcec-830c-11eb-0c80-314c8cded6db\n# ╠═31835154-830d-11eb-09fd-196046609868\n# ╟─430e58a8-8310-11eb-2a53-ed2608f43122\n# ╟─42ef055c-8310-11eb-1ae5-d5ae8bf22c1f\n# ╟─93988ed8-8310-11eb-15f4-554b537eacd6\n# ╠═937da226-8310-11eb-1966-6bcc8ff3cb47\n# ╠═93653664-8310-11eb-23f2-d5236b8bc0ed\n# ╠═93490854-8310-11eb-3de5-5b24918d8840\n# ╟─42d1c078-8310-11eb-2262-bb5ae92a2b27\n# ╠═1b27764e-8315-11eb-3854-f9e5b591744a\n# ╠═34b1bb5e-8317-11eb-0260-5f1d3132a7ba\n# ╠═1ad0cbe4-8315-11eb-341c-dbce64acb374\n# ╟─1a99af8a-8315-11eb-0f74-eb97741a40ca\n# ╠═986e362c-8317-11eb-0eef-cd1de11cd4b2\n# ╠═57c76562-8373-11eb-0e43-256ec189f399\n# ╠═a12bc08e-8371-11eb-29f0-e14f2c17c1d1\n# ╟─c59d7e92-8373-11eb-09d1-55814d7e9f9e\n# ╠═c5808488-8373-11eb-3d9a-51c955524390\n# ╟─c56791bc-8373-11eb-00e3-230f82206892\n# ╠═a790272e-8375-11eb-2a40-df02f3d1ca24\n# ╠═00261792-8441-11eb-3969-55f797a05e23\n# ╠═a740cde6-8375-11eb-0f2a-efc1f23f8f38\n# ╠═a72ae382-8375-11eb-15fc-c750a071dccf\n# ╟─b3e522d6-844c-11eb-2aa5-750b3ee4c212\n# ╠═9aee7716-83d7-11eb-3f3c-d534adaf4bd6\n# ╠═4b50e4b0-8444-11eb-3969-55f797a05e23\n# ╟─a7135b54-8375-11eb-2d63-392c4fa94aea\n# ╠═a6fc6796-8375-11eb-02af-01cee06a06dd\n# ╟─a6b33828-8375-11eb-027a-130ef7a14128\n# ╠═4db52910-844d-11eb-3969-55f797a05e23\n# ╠═6f4476bc-844d-11eb-1fbc-9350beaed253\n# ╟─5ab06896-844d-11eb-3f3c-d534adaf4bd6\n# ╠═a69ff718-8375-11eb-3965-89ecd2088d97\n# ╟─a687f546-8375-11eb-3435-1fa822f71ff1\n# ╠═a66ede62-8375-11eb-3746-758cb7efc8a8\n# ╟─a657ed74-8375-11eb-1d97-1bd417fa42ee\n# ╠═a63e00e4-8375-11eb-10db-897f94a0dc32\n# ╟─c54c0456-8373-11eb-1cb6-11bf225bc6b0\n# ╠═9ba36afc-83d7-11eb-32d4-4d4d0df107d4\n# ╠═cd5eb61e-83d9-11eb-1df3-9389091527e8\n# ╠═5a708ed0-83d8-11eb-147c-abf3f80f8c92\n# ╠═9b4a0a5e-83d7-11eb-3f02-a5ece0576a9b\n# ╠═e9ae52fe-845e-11eb-15c1-65ebc1f4df8e\n# ╟─3ab0e342-845f-11eb-321d-61972f4e6bd4\n# ╠═4321d874-845f-11eb-107c-c32e7c640947\n# ╟─ffd6d3a2-845f-11eb-1308-39662d5cf06e\n# ╠═a3ac0552-845f-11eb-2283-6defb781f7c7\n# ╟─125d76fa-8460-11eb-1d49-57e4eea41e89\n# ╟─c72c03ba-8469-11eb-2fc0-47dab53b1ce9\n# ╠═075f9b50-8464-11eb-35b3-c945b1e49ccf\n# ╠═a27f740e-8465-11eb-171f-3ff85b79e29b\n# ╠═77bd32d4-8466-11eb-2713-6b11add92ba3\n# ╠═fb990ba8-8466-11eb-13be-7d3f33c0576c\n# ╠═36448e26-8467-11eb-12eb-23daf58ea752\n# ╠═d1b3f548-8466-11eb-304e-119b7c99959e\n# ╠═f7ad6d8c-8467-11eb-081d-2ba27071eec5\n# ╠═8c8995d0-8467-11eb-3efb-d1a7961fdefa\n# ╟─bcc9335c-8469-11eb-1492-d310a071b09a\n# ╠═7b6cc3d8-846e-11eb-315c-5544ae999cc8\n# ╠═daffa734-8469-11eb-35ea-376de2c6e1e3\n# ╠═7fb68656-8471-11eb-3969-55f797a05e23\n# ╠═ab34bece-8471-11eb-3f3c-d534adaf4bd6\n# ╟─cccb8bd0-8471-11eb-1fbc-9350beaed253\n# ╠═d63fd518-8471-11eb-147c-abf3f80f8c92\n# ╟─d624eb68-8471-11eb-32d4-4d4d0df107d4\n# ╠═37bd479e-8472-11eb-3106-e3d88fb54de4\n# ╟─37a19df0-8472-11eb-2662-6157d71dd17f\n# ╠═3787dc3a-8472-11eb-129f-b5e34bda1328\n# ╠═37702d1a-8472-11eb-1df3-9389091527e8\n# ╠═d606647c-8471-11eb-3f02-a5ece0576a9b\n# ╠═d92f92e4-8472-11eb-17cf-eb0a1c444ee9\n# ╟─d9132afa-8472-11eb-38c5-39d44a1e57f7\n# ╠═d8f3fd56-8472-11eb-3856-99f30a89c6d3\n# ╠═9a3f1a20-8475-11eb-1fbc-9350beaed253\n# ╟─9a2134e2-8475-11eb-3f3c-d534adaf4bd6\n# ╠═9a00824c-8475-11eb-3969-55f797a05e23\n# ╠═17ac70be-8476-11eb-3f02-a5ece0576a9b\n# ╠═8b254648-8477-11eb-1df3-9389091527e8\n# ╠═8b068190-8477-11eb-147c-abf3f80f8c92\n# ╠═8ae806ca-8477-11eb-32d4-4d4d0df107d4\n# ╟─a5dc1b88-8477-11eb-129f-b5e34bda1328\n", "meta": {"hexsha": "951a44cdc538d7d9448ad9177addc57a7a7135eb", "size": 39481, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "C04/w04/C04w04_nb_pa1.jl", "max_stars_repo_name": "pascal-p/ML_UW_Spec", "max_stars_repo_head_hexsha": "5e19916b62fd776b1412ba31d06b41049a1ec7d8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "C04/w04/C04w04_nb_pa1.jl", "max_issues_repo_name": "pascal-p/ML_UW_Spec", "max_issues_repo_head_hexsha": "5e19916b62fd776b1412ba31d06b41049a1ec7d8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "C04/w04/C04w04_nb_pa1.jl", "max_forks_repo_name": "pascal-p/ML_UW_Spec", "max_forks_repo_head_hexsha": "5e19916b62fd776b1412ba31d06b41049a1ec7d8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.3683187561, "max_line_length": 707, "alphanum_fraction": 0.7018565892, "num_tokens": 15128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9372107966642557, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.8056861518484394}} {"text": "\"\"\"\n hermit(X, Y, Yp)\n\nComputes interpolating polynomial passing through the points whoose coordinates are provided in `X[]` and `Y[]`,\nas well as the values of differentiated function in `Yp[]`, using Hermite interpolation method. \nReturns coefficiants of the Hermite polynomial. \n\n hermit(X::Array{Float64}, Y::Array::Float64, Yp::Array{Float64})\n\n### OUTPUT:\n * `P` - coefficiants of the interpolating polynomial of the type `Array{Float64}`,\n\"\"\"\nfunction hermit(X::Array{Float64}, Y::Array{Float64}, Yp::Array{Float64})\n n = length(X)\n Z = zeros(n*2)\n Q = zeros(2*n+1, 2*n+1)\n for i in 1:n\n Z[2*i-1] = X[i]\n Z[2*i] = X[i]\n Q[2*i-1, 1] = Y[i]\n Q[2*i, 1] = Y[i]\n Q[2*i, 2] = Yp[i]\n\n if i > 1\n Q[2*i, 2] = (Q[2*i, 1] - Q[2*i-1, 1])/(Z[2*i] - Z[2*i-1])\n end\n end\n\n for i in 3:2*n+2\n for j in 3:i\n Q[i, j] = (Q[i, j-1] - Q[i-1, j-1])/(Z[i] - Z[(i+1)-j])\n end\n end\n\n P = []\n\n for i in i:2*n+1\n push!(P, Q[i, i])\n end\n\n return P\nend", "meta": {"hexsha": "e377d4d25fbae419074db7238322eff0db6ea73f", "size": 1061, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/hermite_interpolation.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/hermite_interpolation.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/hermite_interpolation.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": 25.2619047619, "max_line_length": 112, "alphanum_fraction": 0.5230914232, "num_tokens": 400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107843878721, "lm_q2_score": 0.8596637577007393, "lm_q1q2_score": 0.8056861446645355}} {"text": "export minimumjerk, minimumjerkf, functionform\n\n\n\"\"\"\nRetorna os coeficientes do polinômio de trajetória com base no princípio do minimum jerk considerando o tempo inicial sendo 0(zero).\nEntradas\nx0 -> posição inicial\nv0 -> velocidade inicial\na0 -> aceleração inicial\nt0 -> tempo inicial\nxf -> posição final\nvf -> velocidade final\naf -> aceleração final\ntf -> tempo para chegar ao ponto final\n\"\"\"\nfunction minimumjerk(x0::T, v0::T, a0::T, t0::T, xf::T, vf::T, af::T, tf::T) where {T<:AbstractFloat}\n b=[ 1 t0 t0^2 t0^3 t0^4 t0^5;\n 0 1 2*t0 3*(t0^2) 4*(t0^3) 5*(t0^4);\n 0 0 2 6*t0 12*(t0^2) 20*(t0^3);\n 1 tf tf^2 tf^3 tf^4 tf^5;\n 0 1 2*tf 3*(tf^2) 4*(tf^3) 5*(tf^4);\n 0 0 2 6*tf 12*(tf^2) 20*(tf^3)]\n c = [x0, v0, a0, xf, vf, af]\n a = inv(b)*c\n return a\nend\n\n\n\"\"\"\nRetorna os coeficientes do polinômio de trajetória com base no princípio do minimum jerk considerando o tempo inicial sendo 0(zero).\nEntradas\nx0 -> posição inicial\nv0 -> velocidade inicial\na0 -> aceleração inicial\nxf -> posição final\nvf -> velocidade final\naf -> aceleração final\nT -> tempo para chegar ao ponto final\n\"\"\"\nfunction minimumjerk(x0::T, v0::T, a0::T, xf::T, vf::T, af::T, tf::T) where T<:AbstractFloat\n t0 = 0\n minimumjerk(x0,v0,a0,t0,xf,vf,af,tf)\nend\n\nfunction minimumjerkf(x0::T, v0::T, a0::T, t0::T, xf::T, vf::T, af::T, tf::T) where T<:AbstractFloat\n functionform(minimumjerk(x0,v0,a0,t0,xf,vf,af,tf))\nend\n\nfunction minimumjerkf(x0::T, v0::T, a0::T, xf::T, vf::T, af::T, tf::T) where T<:AbstractFloat\n t0 = 0.0\n functionform(minimumjerk(x0,v0,a0,t0,xf,vf,af,tf))\nend\n\n# Retorna as funções de posição, velocidade, aceleração e jerk a parti dos coeficientes do polinômio do mínimo jerk\n# Entradas\n# a -> vetor com os coeficientes do polinômio\nfunction functionform(a::Vector)\n @eval out1 = $(Meta.parse(\"t -> $(a[1]) + $(a[2])*t + $(a[3])*(t^2) + $(a[4])*(t^3) + $(a[5])*(t^4) + $(a[6])*(t^5)\"))\n @eval out2 = $(Meta.parse(\"t -> $(a[2]) + 2*$(a[3])*t + 3*$(a[4])*(t^2) + 4*$(a[5])*(t^3) + 5*$(a[6])*(t^4)\"))\n @eval out3 = $(Meta.parse(\"t -> 2*$(a[3]) + 6*$(a[4])*t + 12*$(a[5])*(t^2) + 20*$(a[6])*(t^3)\"))\n @eval out4 = $(Meta.parse(\"t -> 6*$(a[4]) + 24*$(a[5])*t + 60*$(a[6])*(t^2)\"))\n return out1, out2, out3, out4\nend\n\n# Retorna as funções de posição, velocidade, aceleração e jerk \n# partindo de um vetor de posições finais de cada junta e do tempo final\n# essa função considera que as condições iniciais (psição, velocidade e aceleração) são\n# nulas em cada junta\nfunction minimumjerk(final_positions::Vector{T},tend::T) where T<:AbstractFloat\n xr = Function[]\n vr = Function[]\n ar = Function[]\n jr = Function[]\n for i in final_positions\n x, v, a, j = minimumjerkf(0.0, 0.0, 0.0,0.0, i, 0.0, 0.0, tend)\n push!(xr,x)\n push!(vr,v)\n push!(ar,a)\n push!(jr,j)\n end\n xr, vr, ar, jr\nend ", "meta": {"hexsha": "2f7e57d187105a7710fa4bb0f572c0a412532de4", "size": 2880, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/minimumjerk.jl", "max_stars_repo_name": "phelipe/Trajectory.jl", "max_stars_repo_head_hexsha": "f2e881242e8e74978c18560b46cb374631bc6699", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/minimumjerk.jl", "max_issues_repo_name": "phelipe/Trajectory.jl", "max_issues_repo_head_hexsha": "f2e881242e8e74978c18560b46cb374631bc6699", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/minimumjerk.jl", "max_forks_repo_name": "phelipe/Trajectory.jl", "max_forks_repo_head_hexsha": "f2e881242e8e74978c18560b46cb374631bc6699", "max_forks_repo_licenses": ["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.1219512195, "max_line_length": 132, "alphanum_fraction": 0.615625, "num_tokens": 1179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107896491796, "lm_q2_score": 0.8596637505099168, "lm_q1q2_score": 0.8056861424481745}} {"text": "\"\"\"\n tvstm(A::PeriodicFunctionMatrix, tf, t0; solver, reltol, abstol, dt) -> Φ \n\nCompute the state transition matrix for a linear ODE with time-varying coefficients. \nFor the given time-dependent square matrix function `A(t)`, initial time `t0` and \nfinal time `tf`, the state transition matrix `Φ(tf,t0)`\nis computed by integrating numerically the homogeneous linear ODE \n\n dΦ(t,t0)/dt = A(t)Φ(t,t0), Φ(t0,t0) = I\n\non the time interval `[t0,tf]`. The ODE solver to be employed can be \nspecified using the keyword argument `solver` (see below), together with\nthe required relative accuracy `reltol` (default: `reltol = 1.e-3`), \nabsolute accuracy `abstol` (default: `abstol = 1.e-7`) and/or \nthe fixed step length `dt` (default: `dt = tf-t0`). \nDepending on the desired relative accuracy `reltol`, \nlower order solvers are employed for `reltol >= 1.e-4`, \nwhich are generally very efficient, but less accurate. If `reltol < 1.e-4`,\nhigher order solvers are employed able to cope with high accuracy demands. \n\nThe following solvers from the [OrdinaryDiffEq.jl](https://github.com/SciML/OrdinaryDiffEq.jl) package can be selected:\n\n`solver = \"non-stiff\"` - use a solver for non-stiff problems (`Tsit5()` or `Vern9()`);\n\n`solver = \"stiff\"` - use a solver for stiff problems (`Rodas4()` or `KenCarp58()`);\n\n`solver = \"linear\"` - use a special solver for linear ODEs (`MagnusGL6()`) with fixed time step `dt`;\n\n`solver = \"symplectic\"` - use a symplectic Hamiltonian structure preserving solver (`IRKGL16()`);\n\n`solver = \"\"` - use the default solver, which automatically detects stiff problems (`AutoTsit5(Rosenbrock23())` or `AutoVern9(Rodas5())`). \n\"\"\"\nfunction tvstm(A::PeriodicFunctionMatrix{:c,T}, tf::Real, t0::Real = 0; solver = \"\", reltol = 1e-3, abstol = 1e-7, dt = (tf-t0)/10) where {T}\n n = A.dims[1]\n n == A.dims[2] || error(\"the function matrix must be square\")\n\n isconstant(A) && ( return exp(A.f(t0)*(tf-t0)) )\n \n T1 = promote_type(typeof(t0), typeof(tf))\n\n # using OrdinaryDiffEq\n u0 = Matrix{T}(I,n,n)\n tspan = (T1(t0),T1(tf))\n if solver != \"linear\" \n f!(du,u,p,t) = mul!(du,A.f(t),u)\n prob = ODEProblem(f!, u0, tspan)\n end\n if solver == \"stiff\" \n if reltol > 1.e-4 \n # standard stiff\n sol = solve(prob, Rodas4(); reltol, abstol, save_everystep = false)\n else\n # high accuracy stiff\n sol = solve(prob, KenCarp58(); reltol, abstol, save_everystep = false)\n end\n elseif solver == \"non-stiff\" \n if reltol > 1.e-4 \n # standard non-stiff\n sol = solve(prob, Tsit5(); reltol, abstol, save_everystep = false)\n else\n # high accuracy non-stiff\n sol = solve(prob, Vern9(); reltol, abstol, save_everystep = false)\n end\n elseif solver == \"linear\" \n function update_func!(A,u,p,t)\n A .= p(t)\n end\n DEop = DiffEqArrayOperator(ones(T,n,n),update_func=update_func!) \n prob = ODEProblem(DEop, u0, tspan, A.f)\n sol = solve(prob,MagnusGL6(), dt = dt, save_everystep = false)\n elseif solver == \"symplectic\" \n # high accuracy symplectic\n sol = solve(prob, IRKGaussLegendre.IRKGL16(); reltol, abstol, save_everystep = false)\n else \n if reltol > 1.e-4 \n # low accuracy automatic selection\n sol = solve(prob, AutoTsit5(Rosenbrock23()) ; reltol, abstol, save_everystep = false)\n else\n # high accuracy automatic selection\n sol = solve(prob, AutoVern9(Rodas5(),nonstifftol = 11/10); reltol, abstol, save_everystep = false)\n end\n end\n\n return sol(tf) \nend\n\"\"\" \n monodromy(A::PeriodicFunctionMatrix[, K = 1]; solver, reltol, abstol, dt) -> Ψ::PeriodicArray \n\nCompute the monodromy matrix for a linear ODE with periodic time-varying coefficients. \n\nFor the given square periodic function matrix `A(t)` of period `T` and subperiod `T′ = T/k`, where \n`k` is the number of subperiods, \nthe monodromy matrix `Ψ = Φ(T′,0)` is computed, where `Φ(t,τ)` is the state transition matrix satisfying the homogeneous linear ODE \n\n dΦ(t,τ)/dt = A(t)Φ(t,τ), Φ(τ,τ) = I. \n\nIf `K > 1`, then `Ψ = Φ(T′,0)` is determined as a product of `K` matrices \n`Ψ = Ψ_K*...*Ψ_1`, where for `Δ := T′/K`, `Ψ_i = Φ(iΔ,(i-1)Δ)` is the \nstate transition matrix on the time interval `[(i-1)Δ,iΔ]`. \n\nThe state transition matrices `Φ(iΔ,(i-1)Δ)`\nare computed by integrating numerically the above homogeneous linear ODE. \nThe ODE solver to be employed can be \nspecified using the keyword argument `solver`, together with\nthe required relative accuracy `reltol` (default: `reltol = 1.e-3`), \nabsolute accuracy `abstol` (default: `abstol = 1.e-7`) and/or \nthe fixed step length `dt` (default: `dt = min(Δ, Δ*K′/100)`) (see [`tvstm`](@ref)). \nFor large values of `K`, parallel computation of factors can be alternatively performed \nby starting Julia with several execution threads. \nThe number of execution threads is controlled either by using the `-t/--threads` command line argument \nor by using the `JULIA_NUM_THREADS` environment variable. \n\"\"\"\nfunction monodromy(A::PeriodicFunctionMatrix{:c,T}, K::Int = 1; solver = \"non-stiff\", reltol = 1e-3, abstol = 1e-7, dt = A.period/max(K,100)) where T\n n = A.dims[1]\n n == A.dims[2] || error(\"the function matrix must be square\")\n nperiod = A.nperiod\n Ts = A.period/K/nperiod\n M = Array{T,3}(undef, n, n, K) \n\n # compute the matrix exponential for K = 1 and constant matrix\n K == 1 && isconstant(A) && ( M[:,:,1] = exp(A.f(0)*Ts); return PeriodicArray(M, A.period; nperiod) )\n\n K >= 100 ? dt = Ts : dt = Ts*K/100/nperiod\n\n Threads.@threads for i = 1:K\n @inbounds M[:,:,i] = tvstm(A, i*Ts, (i-1)*Ts; solver = solver, reltol = reltol, abstol = abstol, dt = dt) \n end\n return PeriodicArray(M,A.period; nperiod)\nend\n\"\"\"\n pseig(A, K = 1; lifting = false, solver, reltol, abstol, dt) -> ev\n\nCompute the characteristic multipliers of a continuous-time periodic matrix. \n\nFor the given square periodic matrix `A(t)` of period `T`, \nthe characteristic multipliers `ev` are the eigenvalues of \nthe monodromy matrix `Ψ = Φ(T,0)`, where `Φ(t,τ)` is the state transition matrix satisfying the homogeneous linear ODE \n\n dΦ(t,τ)/dt = A(t)Φ(t,τ), Φ(τ,τ) = I. \n\nIf `lifting = false`, `Ψ` is computed as a product of `K` state transition matrices \n`Ψ = Ψ_K*...*Ψ_1` (see [`monodromy`](@ref) with the associated keyword arguments). \nThe eigenvalues are computed using the periodic Schur decomposition method of [1].\n\nIf `lifting = true`, `Ψ` is (implicitly) expressed as `Ψ = inv(N)*M`, where `M-λN` is a regular\npencil with `N` invertible and \nthe eigenvalues of `M-λN` are the same as those of the matrix product\n`Ψ := Ψ_K*...*Ψ_1`. \nAn efficient version of the structure exploiting fast reduction method of [2] is employed, \nwhich embeds the determination of transition matrices into the reduction algorithm. \nThis option may occasionally lead to inaccurate results for large values of `K`. \n`A` may be a [`PeriodicFunctionMatrix`](@ref), or a [`PeriodicSymbolicMatrix`](@ref), or a \n[`HarmonicArray`](@ref) or a [`PeriodicTimeSeriesMatrix`](@ref).\n\n_References_\n\n[1] A. Bojanczyk, G. Golub, and P. Van Dooren, \n The periodic Schur decomposition. Algorithms and applications, Proc. SPIE 1996.\n\n[2] A. Varga & P. Van Dooren. Computing the zeros of periodic descriptor systems.\n Systems and Control Letters, 50:371-381, 2003.\n\n\"\"\"\nfunction pseig(at::PeriodicFunctionMatrix{:c,T}, K::Int = 1; lifting::Bool = false, solver = \"non-stiff\", reltol = 1e-3, abstol = 1e-7, dt = at.period/100/at.nperiod) where T\n n = at.dims[1]\n n == at.dims[2] || error(\"the function matrix must be square\")\n nperiod = at.nperiod\n t = 0 \n Ts = at.period/K/nperiod\n if lifting \n if K == 1\n ev = eigvals(tvstm(at, at.period, 0; solver, reltol, abstol, dt)) \n else \n Z = zeros(T,n,n)\n ZI = [ Z; -I]\n si = tvstm(at, Ts, 0; solver, reltol, abstol); ti = -I\n t = Ts\n for i = 1:K-1\n tf = t+Ts\n F = qr([ ti; tvstm(at, tf, t; solver, reltol, abstol, dt) ]) \n si = F.Q'*[si; Z]; si = si[n+1:end,:]\n ti = F.Q'*ZI; ti = ti[n+1:end,:]\n t = tf\n end\n ev = -eigvals(si,ti)\n end\n sorteigvals!(ev)\n else\n M = monodromy(at, K; solver, reltol, abstol, dt) \n ev = K == 1 ? eigvals(view(M.M,:,:,1)) : pschur(M.M; withZ = false)[3]\n isreal(ev) && (ev = real(ev))\n end\n return nperiod == 1 ? ev : ev.^nperiod\nend\npseig(at::PeriodicSymbolicMatrix{:c,T}, K::Int = 1; kwargs...) where T = \n pseig(convert(PeriodicFunctionMatrix,at),K; kwargs...)\npseig(at::HarmonicArray{:c,T}, K::Int = 1; kwargs...) where T = \n pseig(convert(PeriodicFunctionMatrix,at),K; kwargs...)\npseig(at::PeriodicTimeSeriesMatrix{:c,T}, K::Int = 1; kwargs...) where T = \n pseig(convert(PeriodicFunctionMatrix,at),K; kwargs...)\n\"\"\"\n ev = pseig(A::PeriodicArray; rev = true, fast = false) \n\nCompute the eigenvalues of a product of `p` square matrices \n`A(p)...*A(2)*A(1)`, if `rev = true` (default) (also called characteristic multipliers) or \nof `A(1)*A(2)...A(p)` if `rev = false`, without evaluating the product. \nThe matrices `A(1)`, `...`, `A(p)` are contained in the `n×n×p` array `A` \nsuch that the `i`-th matrix `A(i)` is contained in `A[:,:,i]`.\nIf `fast = false` (default) then the eigenvalues are computed using an approach\nbased on the periodic Schur decomposition [1], while if `fast = true` \nthe structure exploiting reduction [2] of an appropriate lifted pencil is employed.\nThis later option may occasionally lead to inaccurate results for large number of matrices. \n\n_References_\n\n[1] A. Bojanczyk, G. Golub, and P. Van Dooren, \n The periodic Schur decomposition. Algorithms and applications, Proc. SPIE 1996.\n\n[2] A. Varga & P. Van Dooren. Computing the zeros of periodic descriptor systems.\n Systems and Control Letters, 50:371-381, 2003.\n\n\"\"\"\nfunction pseig(A::PeriodicArray{:d,T}; fast::Bool = false) where T\n pseig(A.M; fast).^(A.nperiod)\nend\nfunction pseig(A::Array{T,3}; rev::Bool = true, fast::Bool = false) where T\n n = size(A,1)\n n == size(A,2) || error(\"A must have equal first and second dimensions\") \n p = size(A,3)\n if fast \n if rev \n ev = eigvals(psreduc_reg(A)...)\n else\n imap = p:-1:1 \n ev = eigvals(psreduc_reg(view(A,imap))...)\n end\n isreal(ev) && (ev = real(ev))\n sorteigvals!(ev)\n return sort!(ev,by=abs,rev=true)\n else\n T1 = promote_type(Float64,T)\n ev = pschur(T1.(A); rev, withZ = false)[3]\n isreal(ev) && (ev = real(ev))\n return ev\n end\nend\n\"\"\"\n ev = pseig(A::PeriodicMatrix[, k = 1]; rev = true, fast = false) \n\nCompute the eigenvalues of a square cyclic product of `p` matrices \n`A(k-1)...*A(2)*A(1)*A(p)...*A(k)`, if `rev = true` (default) or \n`A(k)*A(k+1)*...A(p)*A(1)...A(k-1)` if `rev = false`, without evaluating the product. \nThe argument `k` specifies the starting index (default: `k = 1`). \nThe matrices `A(1)`, `...`, `A(p)` are contained in the `p`-vector of matrices `A` \nsuch that the `i`-th matrix `A(i)`, of dimensions `m(i)×n(i)`, is contained in `A[i]`.\nIf `fast = false` (default) then the eigenvalues are computed using an approach\nbased on the periodic Schur decomposition [1], while if `fast = true` \nthe structure exploiting reduction [2] of an appropriate lifted pencil is employed. \nThis later option may occasionally lead to inaccurate results for large number of matrices. \n\n_Note:_ The first `nmin` components of `ev` contains the `core eigenvalues` of the appropriate matrix product,\nwhere `nmin` is the minimum row dimensions of matrices `A[i]`, for `i = 1, ..., p`, \nwhile the last `ncur-nmin` components of `ev` are zero, \nwhere `ncur` is the column dimension of `A[k]` if `rev = true` or \nthe row dimension of `A[k]` if `rev = false`. \n\n_References_\n\n[1] A. Bojanczyk, G. Golub, and P. Van Dooren, \n The periodic Schur decomposition. Algorithms and applications, Proc. SPIE 1996.\n\n[2] A. Varga & P. Van Dooren. Computing the zeros of periodic descriptor systems.\n Systems and Control Letters, 50:371-381, 2003.\n\n\"\"\"\nfunction pseig(A::PeriodicMatrix{:d,T}, k::Int = 1; fast::Bool = false) where T\n pseig(A.M, k; fast).^(A.nperiod)\nend\nfunction pseig(A::Vector{Matrix{T}}, k::Int = 1; rev::Bool = true, fast::Bool = false) where T\n p = length(A)\n istart = mod(k-1,p)+1\n nev = rev ? size(A[istart],2) : size(A[istart],1)\n # check dimensions\n m, n = size.(A,1), size.(A,2)\n if rev\n all(m .== view(n,mod.(1:p,p).+1)) || error(\"incompatible dimensions\")\n else\n all(n .== view(m,mod.(1:p,p).+1)) || error(\"incompatible dimensions\")\n end\n if fast \n ncore = minimum(size.(A,1))\n if istart == 1 && rev \n ev = eigvals(psreduc_reg(A)...)\n else\n imap = rev ? (mod.(istart:istart+p-1,p).+1) :\n (mod.(p-istart+1:-1:-istart+2,p).+1) \n ev = eigvals(psreduc_reg(view(A,imap))...)\n end\n isreal(ev) && (ev = real(ev))\n T <: Complex || sorteigvals!(ev)\n ind = sortperm(ev; by = abs, rev = true) # select the core eigenvalues\n return [ev[ind[1:ncore]]; zeros(eltype(ev),nev-ncore)] # pad with the necessary zeros\n else\n if istart == 1 \n ev = pschur(A; rev, withZ = false)[3]\n else\n # avoid repeated reindexing\n imap = mod.(istart-1:istart+p-2,p).+1\n rev && reverse!(imap) \n ev = pschur(view(A,imap); rev = false, withZ = false)[3]\n end\n isreal(ev) && (ev = real(ev))\n return ev[1:nev]\n end\nend\n\"\"\"\n pcseig(A::PeriodicFunctionMatrix[, K = 1]; lifting = false, solver, reltol, abstol, dt) -> ce\n\nCompute the characteristic exponents of a periodic matrix.\n\nFor a given square continuous-time periodic function matrix `A(t)` of period `T`, \nthe characteristic exponents `ce` are computed as `log.(ev)/T`, \nwhere `ev` are the characteristic\nmultipliers (i.e., the eigenvalues of the monodromy matrix of `A(t)`). \nFor available options see [`pseig(::PeriodicFunctionMatrix)`](@ref). \nFor a given square discrete-time periodic matrix `A(t)` of discrete period `N`, \nthe characteristic exponents `ce` are computed as `ev.^-N`. \n\"\"\"\nfunction psceig(at::PeriodicFunctionMatrix, K::Int = 1; kwargs...) \n ce = log.(complex(pseig(at, K; kwargs...)))/at.period\n return isreal(ce) ? real(ce) : ce\nend\nfunction psceig(at::Union{PeriodicSymbolicMatrix, PeriodicTimeSeriesMatrix}, K::Int = 1; kwargs...) \n ce = log.(complex(pseig(convert(PeriodicFunctionMatrix,at), K; kwargs...)))/at.period\n return isreal(ce) ? real(ce) : ce\nend\n\"\"\"\n pcseig(Ahr::HarmonicArray[, N]; P, nperiod, shift, atol) -> ce\n\nCompute the characteristic exponents of a continuous-time periodic matrix in _Harmonic Array_ representation. \n\nFor a given square continuous-time periodic function matrix `Ahr(t)` of period `T` \nin a _Harmonic Array_ representation, \nthe characteristic exponents `ce` are computed as the eigenvalues of a truncated harmonic state operator `A(N)-E(N)` lying in the \nfundamental strip `-ω/2 < Im(λ) ≤ ω/2`, where `ω = 2π/T`. If `Ahr(t)` has the harmonic components `A_0`, `A_1`, ..., `A_p`, then \nfor `N ≥ p`, `P = 1` and `nperiod = 1`, the matrices `A(N)` and `E(N)` are built as\n\n\n ( A_0 A_{-1} … A_{-p} 0 ) ( -im*ϕ_{-N}I 0 )\n ( A_1 A_0 ⋱ ) ( ⋮ ⋱ )\n ( ⋮ ⋱ ⋱ ) ( -im*ϕ_{-1}*I )\n A(N) = ( A_p ⋱ A_{-p} ) , E(N) = ( -im*ϕ_{0}*I )\n ( ⋱ ⋱ ⋮ ) ( ⋮ ⋱ )\n ( 0 A_p … A_0 ) ( 0 -im*ϕ_{N}I )\n\nwith `ϕ_{i} := shift+i*ω`. If `N < p`, then a truncated _full_ block Toeplitz matrix A(N) is built using the first `N` harmonic components. \nThe default value used for `N` is `N = max(10,p-1)`. \n \nGenerally, for given `P ≥ 1` and `nperiod ≥ 1`, the block Toeplitz matrix `A(N)` (and also `E(N)`) is constructed with `(2N*np+1)×(2N*np+1)` blocks,\nwith `np = P*nperiod`, such that each `A_i` is preceeded in its column by `np-1` zero blocks, \neach `A_{-i}` is preceeded in its row by `np-1` zero blocks and all diagonal blocks are equal to`A_0`. \n\nThe keyword argument `atol` (default: `atol = 1.e-10`) is a tolerance on the magnitude of the trailing components of the \nassociated eigenvectors used to validate their asymptotic (exponential) decay. \nOnly eigenvalues satisfying this check are returned in `ce`. \n\n_References_\n\n[1] J. Zhou, T. Hagiwara, and M. Araki. \n Spectral characteristics and eigenvalues computation of the harmonic state operators in continuous-time periodic systems. \n Systems and Control Letters, 53:141–155, 2004.\n\"\"\"\nfunction psceig(Ahr::HarmonicArray{:c,T}, N::Int = max(10,size(Ahr.values,3)-1); P::Int = 1, nperiod::Int = Ahr.nperiod, shift::Real = 0, atol::Real = 1.e-10) where T\n n = size(Ahr,1)\n n == size(Ahr,2) || error(\"the periodic matrix must be square\") \n (N == 0 || isconstant(Ahr)) && (return eigvals(real(Ahr.values[:,:,1])))\n ev, V = eigen!(hr2btupd(Ahr, N; P, shift, nperiod));\n ind = sortperm(imag(ev),by=abs); \n ωhp2 = pi/P/Ahr.period/Ahr.nperiod*nperiod\n ne = count(abs.(imag(ev[ind[1:min(4*n,length(ind))]])) .<= ωhp2*(1+sqrt(eps(T))))\n ev = ev[ind[1:ne]]\n # return only validated eigenvalues\n σ = Complex{T}[]\n for i = 1:ne\n norm(V[end-3:end,ind[i]]) < atol && push!(σ,ev[i])\n end\n nv = length(σ)\n nv < n && @warn \"number of eigenvalues is less than the order of matrix, try again with increased number of harmonics\"\n return nv > n ? σ[sortperm(imag(σ),rev=true)][1:n] : σ[1:nv]\nend\n\"\"\"\n pcseig(A::FourierFunctionMatrix[, N]; P, atol) -> ce\n\nCompute the characteristic exponents of a continuous-time periodic matrix in _Fourier Function Matrix_ representation. \n\nFor a given square continuous-time periodic function matrix `A(t)` of period `T` \nin a _Fourier Function Matrix_ representation, \nthe characteristic exponents `ce` are computed as the eigenvalues of the state operator `A(t)-D*I` lying in the \nfundamental strip `-ω/2 < Im(λ) ≤ ω/2`, where `ω = 2π/T`. A finite dimensional truncated matrix of order `n*(2*N*P+1)` \nis built to approximate `A(t)-D*I`, where `n` is the order of `A(t)`, `N` is the number of selected harmonic components\nin the Fourier representation and `P` is the period multiplication number (default: `P = 1`).\nThe default value used for `N` is `N = max(10,p-1)`, where `p` the number of harmonics terms of `A(t)` (see [`FourierFunctionMatrix`](@ref)). \n\nThe keyword argument `atol` (default: `atol = 1.e-10`) is a tolerance on the magnitude of the trailing components of the \nassociated eigenvectors used to validate their asymptotic (exponential) decay. Only eigenvalues satisfying this check are returned in `ce`. \n\"\"\"\nfunction psceig(Afun::FourierFunctionMatrix{:c,T}, N::Int = max(10,maximum(ncoefficients.(Matrix(Afun.M)))); P::Int = 1, atol::Real = 1.e-10) where T\n n = size(Afun,1)\n n == size(Afun,2) || error(\"the periodic matrix must be square\") \n (N == 0 || isconstant(Afun)) && (return eigvals(getindex.(coefficients.(Matrix(Afun.M)),1)))\n Af = P == 1 ? Afun : FourierFunctionMatrix(Fun(t -> Afun.M(t),Fourier(0..P*Afun.period)))\n D = Derivative(domain(Af.M))\n\n Aop = Af.M - DiagDerOp(D,n)\n NA = n*(2*N*P+1)\n RW = Aop[1:NA,1:NA]\n W = Matrix(RW)\n ev, V = eigen(W)\n\n ind = sortperm(imag(ev),by=abs) \n ωhp2 = pi/Af.period/Af.nperiod\n ne = count(abs.(imag(ev[ind[1:min(4*n,length(ind))]])) .<= ωhp2*(1+sqrt(eps(T))))\n ev = ev[ind[1:ne]]\n # return only validated eigenvalues\n σ = Complex{T}[]\n for i = 1:ne\n norm(V[end-3:end,ind[i]]) < atol && push!(σ,ev[i])\n end\n nv = length(σ)\n nv < n && @warn \"number of eigenvalues is less than the order of matrix, try again with increased number of harmonics\"\n return nv > n ? σ[sortperm(imag(σ),rev=true)][1:n] : σ[1:nv]\nend\n\"\"\"\n pcseig(A::AbstractPeriodicArray[, k]; kwargs...) -> ce\n\nCompute the characteristic exponents of a cyclic matrix product of `p` matrices.\n\nThe characteristic exponents of a product of `p` matrices are computed as the `p`th roots of the \ncharacteristic multipliers. These are computed as the eigenvalues of the square \ncyclic product of `p` matrices `A(k-1)...*A(2)*A(1)*A(p)...*A(k)`, if `rev = true` (default) or \n`A(k)*A(k+1)*...A(p)*A(1)...A(k-1)` if `rev = false`, without evaluating the product. \nThe argument `k` specifies the starting index (default: `k = 1`). \nThe matrices `A(1)`, `...`, `A(p)` are contained in the `p`-vector of matrices `A` \nsuch that the `i`-th matrix `A(i)`, of dimensions `m(i)×n(i)`, is contained in `A[i]`.\nThe keyword arguments `kwargs` are those of [`pseig(::PeriodicMatrix)`](@ref). \n\n_Note:_ The first `nmin` components of `ce` contains the _core characteristic exponents_ of the appropriate matrix product,\nwhere `nmin` is the minimum row dimensions of matrices `A[i]`, for `i = 1, ..., p`, \nwhile the last components of `ce` are zero. \n\"\"\"\nfunction psceig(at::AbstractPeriodicArray{:d,T}, k::Int = 1; kwargs...) where T\n ce = (complex(pseig(convert(PeriodicMatrix,at), k; kwargs...))).^(1/at.dperiod/at.nperiod) \n return isreal(ce) ? real(ce) : ce\nend\n\nfunction sorteigvals!(ev)\n # an approximately complex conjugated set is assumed \n isreal(ev) && (return ev)\n tc = ev[imag.(ev) .> 0]\n ev[:] = [ev[imag.(ev) .== 0]; sort([tc; conj.(tc)],by = real)]\n return ev\nend\n\n\"\"\"\n pschur(A; rev = true, withZ = true) -> (S, Z, ev, ischur, α, γ)\n pschur1(A; rev = true, withZ = true) -> (S, Z, ev, ischur, α, γ)\n\nCompute the extended periodic Schur decomposition of a square product of matrices \n`A(p)*...*A(2)*A(1)`, if `rev = true` (default) or `A(1)*A(2)*...*A(p)`\nif `rev = false`, without evaluating the product. \nThe matrices `A(1)`, `...`, `A(p)` are contained in the `p`-vector of matrices `A` \nsuch that the `i`-th matrix `A(i)`, of dimensions `m(i)×n(i)`, is contained in `A[i]`.\nThe resulting `p`-vectors `S` and `Z` contain the matrices `S(1)`, `...`, `S(p)`\nand the orthogonal matrices `Z(1)`, `...`, `Z(p)`, respectively, \nsuch that for `rev = true`\n\n Z(2)' * A(1) * Z(1) = S(1),\n Z(3)' * A(2) * Z(2) = S(2),\n ...\n Z(1)' * A(p) * Z(p) = S(p),\n\nand for `rev = false`\n\n Z(1)' * A(1) * Z(2) = S(1),\n Z(2)' * A(2) * Z(3) = S(2),\n ...\n Z(p)' * A(p) * Z(1) = S(p).\n\nThe resulting index `ischur` is determined such that `m(ischur) ≤ m(i), ∀i`.\nThe resulting `S(i)`, for `i = 1, ..., p` are in an extended periodic Schur form, \nwith `S(ischur)` in a quasi-upper trapezoidal form and `S(i)` \nupper trapezoidal for `i` ``\\\\neq`` `ischur`. \n`S(i)` and `Z(i)` are contained in `S[i]` and `Z[i]`, respectively. \nThe first `nmin` components of `ev := α .* γ` contain the _core eigenvalues_ of the appropriate matrix product,\nwhere `nmin = m(ischur)`, while the last `nmax-nmin` components of `ev` are zero, \nwhere `nmax` is the largest row or column dimension of `A(i)`, for `i = 1, ..., p`. \nThe eigenvalues can be alternatively expressed as `α .* γ`, where `γ` contains suitable \nscaling parameters to avoid overflows or underflows in the expressions of the eigenvalues. \nThe performed orthogonal transformations are not accumulated if `withZ = false`, \nin which case `Z = nothing`. \n\nThe function `pschur` is based on wrappers for the SLICOT subroutines `MB03VW` (see [`PeriodicSystems.SLICOTtools.mb03vw!`](@ref))\n and `MB03BD` (see [`PeriodicSystems.SLICOTtools.mb03bd!`](@ref)), \nbased on algorithms proposed in [1] and [2].\n \nThe function `pschur1` is based on wrappers for the SLICOT subroutines `MB03VD` (see [`PeriodicSystems.SLICOTtools.mb03vd!`](@ref)), \n`MB03VY` (see [`PeriodicSystems.SLICOTtools.mb03vy!`](@ref)), and `MB03BD` (see [`PeriodicSystems.SLICOTtools.mb03bd!`](@ref)), \nbased on algorithms proposed in [1] and [2].\n\nREFERENCES\n\n[1] Bojanczyk, A., Golub, G. H. and Van Dooren, P.\n The periodic Schur decomposition: algorithms and applications.\n In F.T. Luk (editor), Advanced Signal Processing Algorithms,\n Architectures, and Implementations III, Proc. SPIE Conference,\n vol. 1770, pp. 31-42, 1992.\n\n[2] Kressner, D.\n An efficient and reliable implementation of the periodic QZ\n algorithm. IFAC Workshop on Periodic Control Systems (PSYCO\n 2001), Como (Italy), August 27-28 2001. Periodic Control\n Systems 2001 (IFAC Proceedings Volumes), Pergamon.\n\n\"\"\"\nfunction pschur(A::AbstractVector{Matrix{T}}; rev::Bool = true, withZ::Bool = true) where T\n\n p = length(A) \n mp, np = size.(A,1), size.(A,2) \n if rev\n all(mp .== view(np,mod.(1:p,p).+1)) || \n error(\"the number of columns of A[i+1] must be equal to the number of rows of A[i]\")\n else\n all(np .== view(mp,mod.(1:p,p).+1)) || \n error(\"the number of columns of A[i] must be equal to the number of rows of A[i+1]\")\n end\n sind = argmin(mp)\n nmin = mp[sind]\n n = maximum(np)\n\n # use ilo = 1 and ihi = n for the reduction to the periodic Hessenberg form\n ilo = 1; ihi = n\n St = zeros(Float64, n, n, p)\n #TAUt = Array{Float64,2}(undef, max(n-1,1), p)\n if withZ \n Zt = Array{Float64,3}(undef, n, n, p) \n compQ = 'I'\n else\n Zt = Array{Float64,3}(undef, 0, 0, 0)\n compQ = 'N'\n end\n \n if rev \n imap = mod.(Vector(sind+p-1:-1:sind),p) .+ 1\n [(k = imap[i]; St[1:mp[k],1:np[k],i] = A[k];) for i in 1:p]\n hc = 1\n else\n # shift h, h+1, ..., h+p-1 matrices to position 1, 2, ..., p\n imap = mod.(Vector(sind-1:sind+p-2),p) .+ 1\n [(St[1:mp[i],1:np[i],i] = A[i]) for i in 1:p]\n hc = sind\n end\n\n # reduce to periodic Hessenberg form\n LDWORK = max(2*n,1)\n LIWORK = max(3*p,1)\n QIND = Array{BlasInt,1}(undef, 1) \n SIND = ones(BlasInt,p)\n\n SLICOTtools.mb03vw!(compQ, QIND, 'A', n, p, hc, ilo, ihi, SIND, St, Zt, LIWORK, LDWORK)\n \n # reduce to periodic Schur form\n LDWORK = p + max( 2*n, 8*p )\n LIWORK = 2*p + n\n ALPHAR = Array{Float64,1}(undef, n)\n ALPHAI = Array{Float64,1}(undef, n)\n BETA = Array{Float64,1}(undef, n)\n SCAL = Array{BlasInt,1}(undef, n)\n # use ilo = 1 and ihi = nmin\n withZ && (compQ = 'U')\n SLICOTtools.mb03bd!('T','C', compQ, QIND, p, n, hc, ilo, nmin, SIND, St, Zt, ALPHAR, ALPHAI, BETA, SCAL, LIWORK, LDWORK)\n α = complex.(ALPHAR, ALPHAI)\n γ = 2. .^SCAL\n ev = α .* γ\n\n if rev\n imap1 = mod.(p+sind:-1:sind+1,p).+1\n return [St[1:mp[i],1:np[i],imap[i]] for i in 1:p], \n withZ ? [Zt[1:np[i],1:np[i],imap1[i]] for i in 1:p] : nothing, ev, sind, α, γ\n else\n # return back shifted matrices\n imap1 = mod.(imap.+(sind+1),p).+1\n return [St[1:mp[i],1:np[i],i] for i in 1:p], \n withZ ? [Zt[1:mp[i],1:mp[i],i] for i in 1:p] : nothing, ev, sind, α, γ\n end\nend\nfunction pschur1(A::AbstractVector{Matrix{T}}; rev::Bool = true, withZ::Bool = true) where T\n\n p = length(A) \n mp, np = size.(A,1), size.(A,2) \n if rev\n all(mp .== view(np,mod.(1:p,p).+1)) || \n error(\"the number of columns of A[i+1] must be equal to the number of rows of A[i]\")\n else\n all(np .== view(mp,mod.(1:p,p).+1)) || \n error(\"the number of columns of A[i] must be equal to the number of rows of A[i+1]\")\n end\n sind = argmin(mp)\n nmin = mp[sind]\n n = maximum(np)\n\n # use ilo = 1 and ihi = n for the reduction to the periodic Hessenberg form\n ilo = 1; ihi = n\n St = zeros(Float64, n, n, p)\n TAUt = Array{Float64,2}(undef, max(n-1,1), p)\n if withZ \n Zt = Array{Float64,3}(undef, n, n, p) \n compQ = 'U'\n else\n Zt = Array{Float64,3}(undef, 0, 0, 0)\n compQ = 'N'\n end\n \n if rev \n imap = mod.(Vector(sind+p-1:-1:sind),p) .+ 1\n [(k = imap[i]; St[1:mp[k],1:np[k],i] = A[k];) for i in 1:p]\n else\n # shift h, h+1, ..., h+p-1 matrices to position 1, 2, ..., p\n imap = mod.(Vector(sind-1:sind+p-2),p) .+ 1\n [(k = imap[i]; St[1:mp[k],1:np[k],i] = A[k]) for i in 1:p]\n end\n\n # reduce to periodic Hessenberg form\n SLICOTtools.mb03vd!(n, p, ilo, ihi, St, TAUt)\n for i in 1:p\n withZ && (Zt[:,:,i] .= tril(view(St,:,:,i)) ) \n if n > 1 \n if n > 2 && i == 1 \n triu!(view(St,:,:,i),-1) \n elseif i > 1 \n triu!(view(St,:,:,i))\n end \n end \n end \n \n # accumulate transformations\n withZ && SLICOTtools.mb03vy!(n, p, ilo, ihi, Zt, TAUt)\n\n # reduce to periodic Schur form\n LDWORK = p + max( 2*n, 8*p )\n LIWORK = 2*p + n\n QIND = Array{BlasInt,1}(undef, 1) \n ALPHAR = Array{Float64,1}(undef, n)\n ALPHAI = Array{Float64,1}(undef, n)\n BETA = Array{Float64,1}(undef, n)\n SCAL = Array{BlasInt,1}(undef, n)\n # use ilo = 1 and ihi = nmin\n SLICOTtools.mb03bd!('T','C', compQ, QIND, p, n, 1, ilo, nmin, ones(BlasInt,p), St, Zt, ALPHAR, ALPHAI, BETA, SCAL, LIWORK, LDWORK)\n α = complex.(ALPHAR, ALPHAI)\n γ = 2. .^SCAL\n ev = α .* γ\n\n if rev\n imap1 = mod.(p+sind:-1:sind+1,p).+1\n return [St[1:mp[i],1:np[i],imap[i]] for i in 1:p], \n withZ ? [Zt[1:np[i],1:np[i],imap1[i]] for i in 1:p] : nothing, ev, sind, α, γ\n else\n # return back shifted matrices\n imap1 = mod.(imap.+(sind+1),p).+1\n return [St[1:mp[i],1:np[i],imap1[i]] for i in 1:p], \n withZ ? [Zt[1:mp[i],1:mp[i],imap1[i]] for i in 1:p] : nothing, ev, sind, α, γ\n end\nend\n\"\"\"\n pschur(A; rev = true, withZ = true) -> (S, Z, ev, ischur, α, γ)\n pschur1(A; rev = true, withZ = true) -> (S, Z, ev, ischur, α, γ)\n pschur2(A; rev = true, withZ = true) -> (S, Z, ev, ischur, α, γ)\n\nCompute the Schur decomposition of a product of square matrices \n`A(p)*...*A(2)*A(1)`, if `rev = true` (default) or `A(1)*A(2)*...*A(p)`\nif `rev = false`, without evaluating the product. \nThe matrices `A(1)`, `...`, `A(p)` are contained in the `n×n×p` array `A` \nsuch that the `i`-th matrix `A(i)` is contained in `A[:,:,i]`.\nThe resulting `n×n×p` arrays `S` and `Z` contain the matrices `S(1)`, `...`, `S(p)`\nand the orthogonal matrices `Z(1)`, `...`, `Z(p)`, respectively, \nsuch that for `rev = true`\n\n Z(2)' * A(1) * Z(1) = S(1),\n Z(3)' * A(2) * Z(2) = S(2),\n ...\n Z(1)' * A(p) * Z(p) = S(p),\n\nand for `rev = false`\n\n Z(1)' * A(1) * Z(2) = S(1),\n Z(2)' * A(2) * Z(3) = S(2),\n ...\n Z(p)' * A(p) * Z(1) = S(p).\n\nIf `sind = ischur`, with `1 ≤ ischur ≤ p` (default `ischur = 1`), then \n`S(i)`, for `i = 1, ..., p` are in a periodic Schur form, \nwith `S(ischur)` in quasi-upper triangular (or Schur) form and `S(i)` \nupper triangular for `i` ``\\\\neq`` `ischur`. \n`S(i)` and `Z(i)` are contained in `S[:,:,i]` and `Z[:,:,i]`, respectively. \nThe vector `ev` contains the eigenvalues of the appropriate matrix product. \nThe eigenvalues can be alternatively expressed as `α .* γ`, where `γ` contains suitable \nscaling parameters to avoid overflows or underflows in the expressions of the eigenvalues. \nThe performed orthogonal transformations are not accumulated if `withZ = false`, \nin which case `Z = nothing`. \n\nThe function `pschur` is based on wrappers for the SLICOT subroutines `MB03VW` \n(see [`PeriodicSystems.SLICOTtools.mb03vw!`](@ref)) and `MB03BD` (see [`PeriodicSystems.SLICOTtools.mb03bd!`](@ref)), \nbased on algorithms proposed in [1] and [2].\n \nThe function `pschur1` is based on wrappers for the SLICOT subroutines `MB03VD` (see [`PeriodicSystems.SLICOTtools.mb03vd!`](@ref)), \n`MB03VY` (see [`PeriodicSystems.SLICOTtools.mb03vy!`](@ref)) and `MB03BD` (see [`PeriodicSystems.SLICOTtools.mb03bd!`](@ref)), \nbased on algorithms proposed in [1] and [2].\n\nThe function `pschur2` is based on wrappers for the SLICOT subroutines `MB03VD` (see [`PeriodicSystems.SLICOTtools.mb03vd!`](@ref)), \n`MB03VY` (see [`PeriodicSystems.SLICOTtools.mb03vy!`](@ref)) and `MB03VW` (see [`PeriodicSystems.SLICOTtools.mb03vw!`](@ref)), \nbased on the algorithm proposed in [1]. Known issue: `MB03VW` may fails for larger periods. \n\nREFERENCES\n\n[1] Bojanczyk, A., Golub, G. H. and Van Dooren, P.\n The periodic Schur decomposition: algorithms and applications.\n In F.T. Luk (editor), Advanced Signal Processing Algorithms,\n Architectures, and Implementations III, Proc. SPIE Conference,\n vol. 1770, pp. 31-42, 1992.\n\n[2] Kressner, D.\n An efficient and reliable implementation of the periodic QZ\n algorithm. IFAC Workshop on Periodic Control Systems (PSYCO\n 2001), Como (Italy), August 27-28 2001. Periodic Control\n Systems 2001 (IFAC Proceedings Volumes), Pergamon.\n\n\n\"\"\"\nfunction pschur(A::Array{Float64,3}; rev::Bool = true, sind::Int = 1, withZ::Bool = true)\n n = size(A,1)\n n == size(A,2) || error(\"A must have equal first and second dimensions\") \n p = size(A,3)\n (sind < 1 || sind > p) && error(\"sind is out of range $(1:p)\") \n\n # use ilo = 1 and ihi = n for the reduction to the periodic Hessenberg form\n ilo = 1; ihi = n; \n #TAU = Array{Float64,2}(undef, max(n-1,1), p)\n \n if withZ \n Z = Array{Float64,3}(undef, n, n, p) \n compQ = 'I'\n else\n Z = Array{Float64,3}(undef, 0, 0, 0)\n compQ = 'N'\n end\n\n if rev\n imap = mod.(Vector(sind+p-1:-1:sind),p) .+ 1\n S = A[:,:,imap]\n hc = 1\n else\n S = copy(A)\n hc = sind \n end\n\n # reduce to periodic Hessenberg form\n LDWORK = max(2*n,1)\n LIWORK = max(3*p,1)\n QIND = Array{BlasInt,1}(undef, 1) \n SIND = ones(BlasInt,p)\n\n SLICOTtools.mb03vw!(compQ, QIND, 'A', n, p, hc, ilo, ihi, SIND, S, Z, LIWORK, LDWORK)\n\n # reduce to periodic Schur form\n LDWORK = p + max( 2*n, 8*p )\n LIWORK = 2*p + n\n ALPHAR = Array{Float64,1}(undef, n)\n ALPHAI = Array{Float64,1}(undef, n)\n BETA = Array{Float64,1}(undef, n)\n SCAL = Array{BlasInt,1}(undef, n)\n withZ && (compQ = 'U')\n SLICOTtools.mb03bd!('T','C',compQ, QIND, p, n, hc, ilo, ihi, SIND, S, Z, ALPHAR, ALPHAI, BETA, SCAL, LIWORK, LDWORK)\n α = complex.(ALPHAR, ALPHAI)\n γ = 2. .^SCAL\n ev = α .* γ\n\n if rev\n return S[:,:,imap], withZ ? Z[:,:,mod.(p+sind:-1:sind+1,p).+1] : nothing, ev, sind, α, γ\n else\n return S, withZ ? Z : nothing, ev, sind, α, γ\n end\nend\nfunction pschur1(A::Array{Float64,3}; rev::Bool = true, sind::Int = 1, withZ::Bool = true)\n n = size(A,1)\n n == size(A,2) || error(\"A must have equal first and second dimensions\") \n p = size(A,3)\n (sind < 1 || sind > p) && error(\"sind is out of range $(1:p)\") \n\n shift = (sind != 1)\n # use ilo = 1 and ihi = n for the reduction to the periodic Hessenberg form\n ilo = 1; ihi = n; \n TAU = Array{Float64,2}(undef, max(n-1,1), p)\n \n if withZ \n Z = Array{Float64,3}(undef, n, n, p) \n compQ = 'U'\n else\n Z = Array{Float64,3}(undef, 0, 0, 0)\n compQ = 'N'\n end\n\n if shift \n if rev \n imap = mod.(Vector(sind+p-1:-1:sind),p) .+ 1\n S = A[:,:,imap]\n else\n # shift h, h+1, ..., h+p-1 matrices to position 1, 2, ..., p\n imap = mod.(Vector(sind-1:sind+p-2),p) .+ 1\n #rev && (ind = reverse(ind); h = p-hind+1 )\n S = copy(view(A,:,:,imap))\n end\n else\n if rev \n imap = mod.(Vector(p:-1:1),p) .+ 1\n S = A[:,:,imap]\n else\n S = copy(A); imap = 1:p; \n end\n end\n\n # reduce to periodic Hessenberg form\n SLICOTtools.mb03vd!(n, p, ilo, ihi, S, TAU)\n for i in 1:p\n withZ && (Z[:,:,i] .= tril(view(S,:,:,i))) \n if n > 1 \n if n > 2 && i == 1 \n triu!(view(S,:,:,i),-1) \n elseif i > 1 \n triu!(view(S,:,:,i))\n end \n end \n end \n \n # accumulate transformations\n withZ && SLICOTtools.mb03vy!(n, p, ilo, ihi, Z, TAU)\n\n\n # reduce to periodic Schur form\n LDWORK = p + max( 2*n, 8*p )\n LIWORK = 2*p + n\n QIND = Array{BlasInt,1}(undef, 1) \n ALPHAR = Array{Float64,1}(undef, n)\n ALPHAI = Array{Float64,1}(undef, n)\n BETA = Array{Float64,1}(undef, n)\n SCAL = Array{BlasInt,1}(undef, n)\n SLICOTtools.mb03bd!('T','C',compQ, QIND, p, n, 1, ilo, ihi, ones(BlasInt,p), S, Z, ALPHAR, ALPHAI, BETA, SCAL, LIWORK, LDWORK)\n α = complex.(ALPHAR, ALPHAI)\n γ = 2. .^SCAL\n ev = α .* γ\n\n if shift\n if rev\n return S[:,:,imap], withZ ? Z[:,:,mod.(p+sind:-1:sind+1,p).+1] : nothing, ev, sind, α, γ\n else\n # return back shifted matrices\n imap1 = invperm(imap)\n return S[:,:,imap1], withZ ? Z[:,:,imap1] : nothing, ev, sind, α, γ\n end\n else\n if rev \n return S[:,:,imap], withZ ? Z[:,:,mod.(p+1:-1:2,p).+1] : nothing, ev, sind, α, γ\n else\n return S, withZ ? Z : nothing, ev, sind, α, γ\n end\n end\nend\nfunction pschur2(A::Array{Float64,3}; rev::Bool = true, sind::Int = 1, withZ::Bool = true)\n n = size(A,1)\n n == size(A,2) || error(\"A must have equal first and second dimensions\") \n p = size(A,3)\n (sind < 1 || sind > p) && error(\"sind is out of range $(1:p)\") \n\n shift = (sind != 1)\n # use ilo = 1 and ihi = n for the reduction to the periodic Hessenberg form\n ilo = 1; ihi = n; \n TAU = Array{Float64,2}(undef, max(n-1,1), p)\n \n if withZ \n Z = Array{Float64,3}(undef, n, n, p) \n compQ = 'V'\n else\n Z = Array{Float64,3}(undef, 0, 0, 0)\n compQ = 'N'\n end\n\n if shift \n if rev \n imap = mod.(Vector(sind+p-1:-1:sind),p) .+ 1\n S = A[:,:,imap]\n else\n # shift h, h+1, ..., h+p-1 matrices to position 1, 2, ..., p\n imap = mod.(Vector(sind-1:sind+p-2),p) .+ 1\n #rev && (ind = reverse(ind); h = p-hind+1 )\n S = copy(view(A,:,:,imap))\n end\n else\n if rev \n imap = mod.(Vector(p:-1:1),p) .+ 1\n S = A[:,:,imap]\n else\n S = copy(A); imap = 1:p; \n end\n end\n\n # reduce to periodic Hessenberg form\n SLICOTtools.mb03vd!(n, p, ilo, ihi, S, TAU)\n for i in 1:p\n withZ && (Z[:,:,i] .= tril(view(S,:,:,i))) \n if n > 1 \n if n > 2 && i == 1 \n triu!(view(S,:,:,i),-1) \n elseif i > 1 \n triu!(view(S,:,:,i))\n end \n end \n end \n \n # accumulate transformations\n withZ && SLICOTtools.mb03vy!(n, p, ilo, ihi, Z, TAU)\n\n\n # reduce to periodic Schur form\n LDWORK = p + max( 2*n, 8*p )\n LIWORK = 2*p + n\n QIND = Array{BlasInt,1}(undef, 1) \n ALPHAR = Array{Float64,1}(undef, n)\n ALPHAI = Array{Float64,1}(undef, n)\n BETA = Array{Float64,1}(undef, n)\n SCAL = Array{BlasInt,1}(undef, n)\n SLICOTtools.mb03wd!('S',compQ, n, p, ilo, ihi, ilo, ihi, S, Z, ALPHAR, ALPHAI, LDWORK)\n ev = complex.(ALPHAR, ALPHAI)\n\n if shift\n if rev\n return S[:,:,imap], withZ ? Z[:,:,mod.(p+sind:-1:sind+1,p).+1] : nothing, ev, sind\n else\n # return back shifted matrices\n imap1 = invperm(imap)\n return S[:,:,imap1], withZ ? Z[:,:,imap1] : nothing, ev, sind\n end\n else\n if rev \n return S[:,:,imap], withZ ? Z[:,:,mod.(p+1:-1:2,p).+1] : nothing, ev, sind\n else\n return S, withZ ? Z : nothing, ev, sind\n end\n end\nend\n\n\"\"\"\n phess(A; hind = 1, rev = true, withZ = true) -> (H, Z, ihess)\n phess1(A; hind = 1, rev = true, withZ = true) -> (H, Z, ihess)\n\nCompute the Hessenberg decomposition of a product of square matrices \n`A(p)*...*A(2)*A(1)`, if `rev = true` (default) or `A(1)*A(2)*...*A(p)`\nif `rev = false`, without evaluating the product. \nThe matrices `A(1)`, `...`, `A(p)` are contained in the `n×n×p` array `A` \nsuch that the `i`-th matrix `A(i)` is contained in `A[:,:,i]`.\nThe resulting `n×n×p` arrays `H` and `Z` contain the matrices `H(1)`, `...`, `H(p)`\nand the orthogonal matrices `Z(1)`, `...`, `Z(p)`, respectively, \nsuch that for `rev = true`\n\n Z(2)' * A(1) * Z(1) = H(1),\n Z(3)' * A(2) * Z(2) = H(2),\n ...\n Z(1)' * A(p) * Z(p) = H(p),\n\nand for `rev = false`\n\n Z(1)' * A(1) * Z(2) = H(1),\n Z(2)' * A(2) * Z(3) = H(2),\n ...\n Z(p)' * A(p) * Z(1) = H(p).\n\nIf `hind = ihess`, with `1 ≤ ihess ≤ p` (default `ihess = 1`), then \n`H(i)`, `i = 1, ..., p` are in a periodic Hessenberg form, \nwith `H(ihess)` in upper Hessenberg form and `H(i)` \nupper triangular for `i` ``\\\\neq`` `ihess`. \n`H(i)` and `Z(i)` are contained in `H[:,:,i]` and `Z[:,:,i]`, respectively. \nThe performed orthogonal transformations are not accumulated if `withZ = false`, \nin which case `Z = nothing`. \n\nThe function `phess` is based on a wrapper for the SLICOT subroutine `MB03VW`\n (see [`PeriodicSystems.SLICOTtools.mb03vw!`](@ref)).\n \nThe function `phess1` is based on wrappers for the SLICOT subroutines `MB03VD` \n(see [`PeriodicSystems.SLICOTtools.mb03vd!`](@ref)) and `MB03VY` (see [`PeriodicSystems.SLICOTtools.mb03vy!`](@ref)).\n\"\"\"\nfunction phess(A::AbstractArray{Float64,3}; rev::Bool = true, hind::Int = 1, withZ::Bool = true)\n n = size(A,1)\n n == size(A,2) || error(\"A must have equal first and second dimensions\")\n K = size(A,3)\n (hind < 1 || hind > K) && error(\"hind is out of range $(1:K)\") \n\n ilo = 1; ihi = n; \n if withZ \n Z = Array{Float64,3}(undef, n, n, K) \n compQ = 'I'\n else\n Z = Array{Float64,3}(undef, 0, 0, 0)\n compQ = 'N'\n end\n\n if rev\n imap = mod.(Vector(hind+K-1:-1:hind),K) .+ 1\n H = A[:,:,imap]\n hc = 1\n else\n H = copy(A)\n hc = hind \n end\n\n # reduce to periodic Hessenberg form\n LDWORK = max(2*n,1)\n LIWORK = max(3*K,1)\n QIND = Array{BlasInt,1}(undef, 1) \n \n SLICOTtools.mb03vw!(compQ, QIND, 'A', n, K, hc, ilo, ihi, ones(BlasInt,K), H, Z, LIWORK, LDWORK)\n\n if rev\n return H[:,:,imap], withZ ? Z[:,:,mod.(K+hind:-1:hind+1,K).+1] : nothing, hind\n else\n return H, withZ ? Z : nothing, hind\n end\nend\nfunction phess1(A::AbstractArray{Float64,3}; rev::Bool = true, hind::Int = 1, withZ::Bool = true)\n n = size(A,1)\n n == size(A,2) || error(\"A must have equal first and second dimensions\")\n K = size(A,3)\n (hind < 1 || hind > K) && error(\"hind is out of range $(1:K)\") \n\n shift = (hind != 1)\n ilo = 1; ihi = n; \n withZ && (Q = Array{Float64,3}(undef, n, n, K))\n TAU = Array{Float64,2}(undef, max(n-1,1), K)\n \n if shift \n if rev \n imap = mod.(Vector(hind+K-1:-1:hind),K) .+ 1\n H = A[:,:,imap]\n else\n # shift h, h+1, ..., h+K-1 matrices to position 1, 2, ..., K\n imap = mod.(Vector(hind-1:hind+K-2),K) .+ 1\n #rev && (ind = reverse(ind); h = K-hind+1 )\n H = copy(view(A,:,:,imap))\n end\n else\n if rev \n imap = mod.(Vector(K:-1:1),K) .+ 1\n H = A[:,:,imap]\n else\n H = copy(A); imap = 1:K; \n end\n end\n\n # reduce to periodic Hessenberg form\n SLICOTtools.mb03vd!(n, K, ilo, ihi, H, TAU)\n for i in 1:K\n withZ && (Q[:,:,i] .= tril(view(H,:,:,i))) \n if n > 1 \n if ( n>2 && i == 1 )\n triu!(view(H,:,:,i),-1)\n \n elseif ( i>1 )\n triu!(view(H,:,:,i))\n end \n end \n end \n \n # accumulate transformations\n withZ && SLICOTtools.mb03vy!(n, K, ilo, ihi, Q, TAU)\n\n if shift\n if rev\n return H[:,:,imap], withZ ? Q[:,:,mod.(K+hind:-1:hind+1,K).+1] : nothing, hind\n else\n # return back shifted matrices\n #imap1 = mod.(imap.+(hind+1),K).+1\n imap1 = invperm(imap)\n return H[:,:,imap1], withZ ? Q[:,:,imap1] : nothing, hind\n end\n else\n if rev \n return H[:,:,imap], withZ ? Q[:,:,mod.(K+1:-1:2,K).+1] : nothing, hind\n else\n return H, withZ ? Q : nothing, hind\n end\n end\nend\n\n# similarity transformation checks\nfunction check_psim(Ain::AbstractArray{T,3}, Q::AbstractArray{T,3}, Aout::AbstractArray{T,3}; rev::Bool = true, atol = 1.e-7) where T\n SSQ = 0.\n K = size(Ain,3)\n for i in 1:K\n # rev = true: Q(i+1)' * Ain(i) * Q(i) = Aout(i), \n # rev = false: Q(i)' * Ain(i) * Q(i+1) = Aout(i),\n Zta = rev ? view(Ain,:,:,i) * view(Q,:,:,i) - view(Q,:,:,mod(i,K)+1) * view(Aout,:,:,i) :\n view(Ain,:,:,i) * view(Q,:,:,mod(i,K)+1) - view(Q,:,:,i) * view(Aout,:,:,i) \n SSQ = hypot(SSQ, norm(Zta))\n end\n return SSQ < atol\nend\nfunction check_psim(Ain::Vector{Matrix{T}}, Q::Vector{Matrix{T1}}, Aout::Vector{Matrix{T1}}; rev::Bool = true, atol = 1.e-7) where {T,T1}\n SSQ = 0.\n K = length(Ain)\n for i in 1:K\n # rev = true: Q(i+1)' * Ain(i) * Q(i) = Aout(i), \n # rev = false: Q(i)' * Ain(i) * Q(i+1) = Aout(i),\n Zta = rev ? Ain[i] * Q[i] - Q[mod(i,K)+1] * Aout[i] :\n Ain[i] * Q[mod(i,K)+1] - Q[i] * Aout[i] \n SSQ = hypot(SSQ, norm(Zta))\n end\n return SSQ < atol\n # one line computation\n # return rev ? norm(norm.(Ain.*Q.-mshift(Q).*Aout)) < atol : norm(norm.(Ain.*mshift(Q).-Q.*Aout)) < atol\nend\nfunction mshift(X::Vector{<:Matrix}, k::Int = 1) \n # Form a k-shifted array of matrices.\n K = length(X)\n return X[mod.(k:k+K-1,K).+1]\nend\n\n\n# conversions\n\"\"\"\n ts2pfm(At::PeriodicTimeSeriesMatrix; method = \"linear\") -> A::PeriodicFunctionMatrix\n\nCompute the periodic function matrix corresponding to an interpolated periodic time series matrix. \nFor the given periodic time series matrix `At`, a periodic function matrix `A(t)` is defined as the \nmapping `A(t) = t -> etpf(t)`, where `etpf(t)` is a periodic interpolation/extrapolation object, \nas provided in the [`Interpolations.jl`](https://github.com/JuliaMath/Interpolations.jl) package. \nThe keyword parameter `method` specifies the interpolation/extrapolation method to be used as follows:\n\n`method = \"constant\"` - use periodic B-splines of degree 0 (periodic constant interpolation);\n\n`method = \"linear\"` - use periodic B-splines of degree 1 (periodic linear interpolation) (default);\n\n`method = \"quadratic\"` - use periodic B-splines of degree 2 (periodic quadratic interpolation); \n\n`method = \"cubic\"` - use periodic B-splines of degree 3 (periodic cubic interpolation). \n\"\"\"\nfunction ts2pfm(A::PeriodicTimeSeriesMatrix; method = \"linear\")\n N = length(A.values)\n N == 0 && error(\"empty time array not supported\")\n N == 1 && (return t -> A.values[1])\n ts = (0:N-1)*(A.period/N)\n n1, n2 = size(A.values[1])\n intparray = Array{Any,2}(undef,n1, n2)\n if method == \"linear\"\n [intparray[i,j] = scale(Interpolations.extrapolate(interpolate(getindex.(A.values,i,j), BSpline(Linear(Periodic(OnCell())))), Periodic()), ts) for i in 1:n1, j in 1:n2]\n elseif method == \"cubic\" \n [intparray[i,j] = scale(Interpolations.extrapolate(interpolate(getindex.(A.values,i,j), BSpline(Cubic(Periodic(OnCell())))), Periodic()), ts) for i in 1:n1, j in 1:n2]\n elseif method == \"quadratic\" \n [intparray[i,j] = scale(Interpolations.extrapolate(interpolate(getindex.(A.values,i,j), BSpline(Quadratic(Periodic(OnCell())))), Periodic()), ts) for i in 1:n1, j in 1:n2]\n elseif method == \"constant\" \n [intparray[i,j] = scale(Interpolations.extrapolate(interpolate(getindex.(A.values,i,j), BSpline(Constant(Periodic(OnCell())))), Periodic()), ts) for i in 1:n1, j in 1:n2]\n else\n error(\"no such option method = $method\")\n end\n return PeriodicFunctionMatrix(t -> [intparray[i,j](t) for i in 1:n1, j in 1:n2 ], A.period; nperiod = A.nperiod, isconst = isconstant(A))\nend\n\n\"\"\"\n ts2hr(A::PeriodicTimeSeriesMatrix; atol = 0, rtol = √ϵ, n, squeeze = true) -> Ahr::HarmonicArray\n\nCompute the harmonic (Fourier) approximation of a periodic matrix specified by a time series matrix. \nThe periodic matrix `A(t)` is specified as a continuous-time periodic time series matrix `A`, \nwith `m` matrices contained in the vector of matrices `A.values`, where `A.values[k]` \nis the value of `A(t)` at time moment `(k-1)T/m`, with `T = A.period` being the period. \nThe resulting harmonic approximation `Ahr(t)` of `A(t)` has the form\n\n p\n Ahr(t) = A_0 + ∑ ( Ac_i*cos(i*t*2*π/T)+As_i*sin(i*2*π*t/T) ) \n i=1 \n\nwhere `A_0` is the constant term (the mean value), `Ac_i` and `As_i` are the \ncoefficient matrices of the `i`-th cosinus and sinus terms, respectively. \nThe order of the approximation `p` is determined using the maximum order specified by `n` \n(default: `n = (m-1)/2`) and the absolute and relative tolerances `atol` and `rtol`, as follows:\n`p` is the minimum between `n`, `(m-1)/2` and the maximum index `k` \nsuch that `Ac_k` and/or `As_k` are nonzero.\nThe tolerance used to assess nonzero elements is `tol = max(atol, rtol*maxnorm)`, where \n`maxnorm` is the maximum norm of the matrices contained in `A.values`. The default values of tolerances\nare `atol = 0` and `rtol = √ϵ`, where `ϵ` is the working machine precision.\n\nThe resulting harmonic approximation `Ahr(t)` is returned in the harmonic array object `Ahr` \n(see [`HarmonicArray`](@ref)). \n\"\"\"\nfunction ts2hr(A::PeriodicTimeSeriesMatrix{:c,T}; atol::Real = 0, rtol::Real = 0, n::Union{Int,Missing} = missing, squeeze::Bool = true) where {T}\n \n M = length(A.values)\n n1, n2 = size(A.values[1])\n \n if ismissing(n)\n n = div(M-1,2)\n ncur = 0\n else\n n = min( n, div(M-1,2) ) \n ncur = n\n end\n n = max(n,0)\n \n AHR = zeros(ComplexF64, n1, n2, n+1)\n T1 = promote_type(Float64,T)\n tol = iszero(atol) ? (iszero(rtol) ? 10*M*sqrt(eps(T1))*maximum(norm.(A.values)) : rtol*maximum(norm.(A.values)) ) : atol\n i1 = 1:n+1 \n for i = 1:n1\n for j = 1:n2\n temp = T1.(getindex.(A.values, i, j))\n i == 1 && j == 1 && (global rfftop = plan_rfft(temp; flags=FFTW.ESTIMATE, timelimit=Inf))\n tt = conj(2/M*(rfftop*temp)) \n tt[1] = real(tt[1]/2)\n tt1 = view(tt,i1)\n indr = i1[abs.(real(tt1)) .> tol]\n nr = length(indr); \n nr > 0 && (nr = indr[end])\n indi = i1[abs.(imag(tt1)) .> tol]\n ni = length(indi); \n ni > 0 && (ni = indi[end])\n ncur = max(ncur, nr, ni) \n AHR[i,j,indr] = real(tt[indr])\n AHR[i,j,indi] += im*imag(tt[indi])\n end\n end\n nperiod = A.nperiod\n if ncur >= 2 && squeeze\n nh = ncur-1\n s = falses(nh)\n for i = 1:nh\n s[i] = any(abs.(view(AHR,:,:,i+1)) .> tol)\n end \n t = Primes.factor(Vector,nh)\n s1 = copy(s)\n for i = 1:length(t)\n stry = true\n for j1 = 1:t[i]:nh\n stry = stry & all(view(s1,j1:j1+t[i]-2) .== false) \n stry || break\n end\n if stry \n nperiod = nperiod*t[i]\n s1 = s1[t[i]:t[i]:nh]\n nh = div(nh,t[i])\n end\n end \n return HarmonicArray(AHR[:,:,[1;nperiod+1:nperiod:ncur]],A.period;nperiod)\n else\n return HarmonicArray(AHR[:,:,1:max(1,ncur+1)],A.period;nperiod)\n end \n\nend\n\"\"\"\n ffm2hr(Afun::FourierFunctionMatrix; atol = 0, rtol = √ϵ, squeeze = true) -> Ahr::HarmonicArray\n\nCompute the harmonic (Fourier) representation of a Fourier periodic matrix object. \n\nThe Fourier function matrix object `Afun` of period `T` is built using\nthe Fourier series representation of a periodic matrix `Afun(t)` of subperiod `T′ = T/k`, \nwhere each entry of `Afun(t)` has the form\n\n p\n a_0 + ∑ ( ac_i*cos(i*t*2*π/T′)+as_i*sin(i*2*π*t/T′) ) ,\n i=1 \n\nwhere `k ≥ 1` is the number of subperiods (default: `k = 1`). \n\nThe harmonic array object `Ahr` of period `T` is built using\nthe harmonic representation of a periodic matrix `Ahr(t)` of subperiod `T′′ = T/k′` in the form\n\n p′\n Ahr(t) = A_0 + ∑ ( Ac_i*cos(i*t*2*π/T′′)+As_i*sin(i*2*π*t/T′′) ) ,\n i=1 \n\nwhere `p′` is the maximum index `j`, such that `Ac_j` and/or `As_j` are nonzero.\nThe tolerance used to assess nonzero elements is `tol = max(atol, rtol*maxnorm)`, where \n`maxnorm` is the maximum absolute value of the coefficients `ac_i` and `as_i` in `Afun(t)`. The default values of tolerances\nare `atol = 0` and `rtol = √ϵ`, where `ϵ` is the working machine precision.\nThe resulting harmonic approximation `Ahr(t)` is returned in the harmonic array object `Ahr` \n(see [`HarmonicArray`](@ref)). \n\"\"\"\nfunction ffm2hr(A::FourierFunctionMatrix{:c,T}; atol::Real = 0, rtol::Real = 0, squeeze::Bool = true) where {T}\n lens = length.(coefficients.(Matrix(A.M)))\n n = max(div(maximum(lens)-1,2),0)\n n1, n2 = size(A)\n\n ncur = n\n AHR = zeros(complex(T), n1, n2, n+1)\n tol = iszero(atol) ? (iszero(rtol) ? 10*n*eps(maximum(norm.(coefficients.(Matrix(A.M)),Inf))) : rtol*maximum(norm.(coefficients.(Matrix(A.M)),Inf)) ) : atol\n for i = 1:n1\n for j = 1:n2\n tt = coefficients(A.M[i,j])\n tt[abs.(tt) .<= tol] .= zero(T)\n lentt = lens[i,j]\n if lentt > 0\n AHR[i,j,1] = tt[1] \n k = 1\n for k1 = 2:2:lentt-1\n k += 1\n AHR[i,j,k] = tt[k1+1] + im*tt[k1]\n end\n isodd(lentt) || (AHR[i,j,k+1] = im*tt[end])\n end\n end\n end\n nperiod = A.nperiod\n if ncur > 2 && squeeze\n nh = ncur-1\n s = falses(nh)\n for i = 1:nh\n s[i] = any(abs.(view(AHR,:,:,i+1)) .> tol)\n end \n t = Primes.factor(Vector,nh)\n s1 = copy(s)\n for i = 1:length(t)\n stry = true\n for j1 = 1:t[i]:nh\n stry = stry & all(view(s1,j1:j1+t[i]-2) .== false) \n stry || break\n end\n if stry \n nperiod = nperiod*t[i]\n s1 = s1[t[i]:t[i]:nh]\n nh = div(nh,t[i])\n end\n end \n return HarmonicArray(AHR[:,:,[1;nperiod+1:nperiod:ncur]],A.period;nperiod)\n else\n return HarmonicArray(AHR[:,:,1:max(1,ncur+1)],A.period;nperiod)\n end \n\nend\n\n# function ts2ffm(A::PeriodicTimeSeriesMatrix{:c,T}; atol::Real = 0, rtol::Real = 0, n::Union{Int,Missing} = missing, squeeze::Bool = true) where {T, Ts}\n \n# M = length(A.values)\n# n1, n2 = size(A.values[1])\n \n# if ismissing(n)\n# n = div(M-1,2)\n# ncur = 0\n# else\n# n = min( n, div(M-1,2) ) \n# ncur = n\n# end\n# n = max(n,0)\n# s = Fourier(0..A.period)\n# AFFM = Fun(t -> zeros(T,n1,n2),s)\n# tol = iszero(atol) ? (iszero(rtol) ? 10*M*eps(maximum(norm.(A.values))) : rtol*maximum(norm.(A.values)) ) : atol\n# i1 = 2:n+1 \n# for i = 1:n1\n# for j = 1:n2\n# temp = getindex.(A.values, i, j)\n# i == 1 && j == 1 && (global rfftop = plan_rfft(temp; flags=FFTW.ESTIMATE, timelimit=Inf))\n# tt = conj(2/M*(rfftop*temp)) \n# # tt[1] = real(tt[1]/2)\n# # tt1 = view(tt,i1)\n# ind = i1[abs.(view(tt,i1)) .> tol]\n# nc = length(ind); \n# nc > 0 && (nc = ind[end])\n# # nr = count(abs.(real(tt1)) .> tol)\n# # indi = i1[abs.(imag(tt1)) .> tol]\n# # ni = length(indi); \n# # ni > 0 && (ni = indi[end])\n# # nc = count(view(tt)) \n# # AFFM[i,j] = Fun(s,real(tt[indr])\n# # AHR[i,j,indi] += im*imag(tt[indi])\n# i2 = 2:nc\n# AFFM[i,j] = Fun(s, [[real(tt[1])/2]; transpose([real(tt[i2]) imag(tt[i2])])[:]])\n# end\n# end\n# # nperiod = A.nperiod\n# # if nc > 2 && squeeze\n# # nh = ncur-1\n# # s = falses(nh)\n# # for i = 1:nh\n# # s[i] = any(abs.(view(AHR,:,:,i+1)) .> tol)\n# # end \n# # t = Primes.factor(Vector,nh)\n# # s1 = copy(s)\n# # for i = 1:length(t)\n# # #st = falses(0) \n\n# # #k = div(nh,t[i]) # number of possible patterns\n# # stry = true\n# # for j1 = 1:t[i]:nh\n# # stry = stry & all(view(s1,j1:j1+t[i]-2) .== false) \n# # stry || break\n# # #st = [st; s1[j1+t[i]-1]]\n# # end\n# # if stry \n# # nperiod = nperiod*t[i]\n# # s1 = s1[t[i]:t[i]:nh]\n# # nh = div(nh,t[i])\n# # end\n# # end \n# return FourierFunctionMatrix(AFFM,A.period,A.nperiod)\n# # else\n# # return FourierFunctionMatrix(AHR[:,:,1:max(1,ncur)],A.period;nperiod)\n# # end \n\n# end\n\"\"\"\n pfm2hr(A::PeriodicFunctionMatrix; nsample, NyquistFreq) -> Ahr::HarmonicArray\n\nConvert a periodic function matrix into a harmonic array representation. \nIf `A(t)` is a periodic function matrix of period `T`, then the harmonic array representation\n`Ahr` is determined by applying the fast Fourier transform to the sampled arrays `A(iΔ)`, `i = 0, ..., k`,\nwhere `Δ = T/k` is the sampling period and `k` is the number of samples specified by the keyword argument\n`nsample = k` (default: `k = 128`). If the Nyquist frequency `f` is specified via the keyword argument\n`NyquistFreq = f`, then `k` is chosen `k = 2*f*T` to avoid signal aliasing. \n\"\"\"\nfunction pfm2hr(A::PeriodicFunctionMatrix; nsample::Int = 128, NyquistFreq::Union{Real,Missing} = missing) \n isconstant(A) && (return HarmonicArray(A.f(0),A.period; nperiod = A.nperiod))\n nsample > 0 || ArgumentError(\"nsample must be positive, got $nsaple\")\n ns = ismissing(NyquistFreq) ? nsample : Int(floor(2*abs(NyquistFreq)*A.period/A.nperiod))+1\n Δ = A.period/ns/A.nperiod\n ts = (0:ns-1)*Δ\n return ts2hr(PeriodicTimeSeriesMatrix(A.f.(ts), A.period; nperiod = A.nperiod),squeeze = true)\nend\n\"\"\"\n psm2hr(A::PeriodicSymbolicMatrix; nsample, NyquistFreq) -> Ahr::HarmonicArray\n\nConvert a periodic symbolic matrix into a harmonic array representation. \nIf `A(t)` is a periodic symbolic matrix of period `T`, then the harmonic array representation\n`Ahr` is determined by applying the fast Fourier transform to the sampled arrays `A(iΔ)`, `i = 0, ..., k`,\nwhere `Δ = T/k` is the sampling period and `k` is the number of samples specified by the keyword argument\n`nsample = k` (default: `k = 128`). If the Nyquist frequency `f` is specified via the keyword argument\n`NyquistFreq = f`, then `k` is chosen `k = 2*f*T` to avoid signal aliasing. \n\"\"\"\nfunction psm2hr(A::PeriodicSymbolicMatrix; nsample::Int = 128, NyquistFreq::Union{Real,Missing} = missing) \n isconstant(A) && (return HarmonicArray(convert(PeriodicFunctionMatrix,A).f(0),A.period; nperiod = A.nperiod))\n nsample > 0 || ArgumentError(\"nsample must be positive, got $nsaple\")\n ns = ismissing(NyquistFreq) ? nsample : Int(floor(2*abs(NyquistFreq)*A.period))+1\n Δ = A.period/ns\n ts = (0:ns-1)*Δ\n return ts2hr(PeriodicTimeSeriesMatrix(convert(PeriodicFunctionMatrix,A).f.(ts), A.period; nperiod = A.nperiod))\nend\n\"\"\"\n hr2psm(Ahr::HarmonicArray, nrange) -> A::Matrix{Num}\n\nConvert a range of harmonic components `nrange` of the harmonic array `Ahr` to a symbolic matrix `A`. \nThe default range is `nrange = 0:n`, where `n` is the order of the maximum harmonics. \n\"\"\"\nfunction hr2psm(ahr::HarmonicArray, nrange::UnitRange = 0:size(ahr.values,3)-1) \n Symbolics.@variables t \n Period = ahr.period\n i1 = max(first(nrange),0)\n i2 = min(last(nrange), size(ahr.values,3)-1)\n \n ts = t*2*pi*ahr.nperiod/Period\n \n i1 == 0 ? a = Num.(real.(ahr.values[:,:,1])) : (i1 -=1; a = zeros(Num,size(ahr.values,1),size(ahr.values,2)))\n for i in i1+1:i2\n ta = view(ahr.values,:,:,i+1)\n a .+= real.(ta).*(cos(i*ts)) .+ imag.(ta) .* (sin(i*ts))\n end\n return a\nend \n\"\"\"\n pm2pa(At::PeriodicMatrix) -> A::PeriodicArray\n\nConvert a discrete-time periodic matrix object into a discrete-time periodic array object.\n\nThe discrete-time periodic matrix object `At` contains a \n`p`-vector `At` of real matrices `At[i]`, `i = 1,..., p`, \nthe associated time period `T` and the number of subperiods `k`. The resulting discrete-time periodic array object\n`A` of period `T` and number of subperiods `k` \nis built from a `m×n×p` real array `A`, such that `A[:,:,i]` \ncontains `At[i]`, for `i = 1,..., p`. \nFor non-constant dimensions, the resulting `m` and `n` are the maximum row and column dimensions, respectively,\nand the resulting component matrices `A[:,:,i]` contain `At[i]`, appropriately padded with zero entries. \n\"\"\"\nfunction pm2pa(A::PeriodicMatrix{:d,T}) where T\n N = length(A)\n m, n = size(A)\n N == 0 && PeriodicArray(Array{T,3}(undef,0,0,0),A.period)\n if any(m .!= m[1]) || any(m .!= m[1]) \n #@warn \"Non-constant dimensions: the resulting component matrices padded with zeros\"\n t = zeros(T,maximum(m),maximum(n),N)\n [copyto!(view(t,1:m[i],1:n[i],i),A.M[i]) for i in 1:N]\n PeriodicArray{:d,T}(t,A.period,A.nperiod)\n else\n t = zeros(T,m[1],n[1],N)\n [copyto!(view(t,:,:,i),A.M[i]) for i in 1:N]\n PeriodicArray{:d,T}(t,A.period,A.nperiod)\n end\nend\n\n\n\n# lifting-based structure exploiting (fast) reductions\n\n# function ps2ls(psys::PeriodicDiscreteDescriptorStateSpace{T}; kstart::Int = 1, compacted::Bool = false, \n# fast::Bool = true, atol::Real = zero(real(T)), atol1::Real = atol, atol2::Real = atol, \n# rtol::Real = eps(real(float(one(T))))*iszero(max(atol1,atol2))) where T\n# indp(j,n) = mod(j-1,n)+1\n# desc = (psys.E != I)\n# K = psys.period\n# Ts = psys.Ts \n# LTs = Ts > 0 ? Ts*K : -1\n# #[ap,bp,cp,dp,ep] = pdsdata(psys);\n# # generate the stacked lifted system of (Grasselli and Longhi, 1991)\n# kind = indp.(kstart:kstart+K-1,K)\n# ni = psys.nx[kind]\n# mui = psys.ndx[kind]\n# m = psys.nu[kind]\n# n = sum(ni)\n# mukm1 = sum(view(mui,1:K-1))\n# nukm1 = sum(view(ni,1:K-1))\n# KK = kind[K]\n# kindm1 = view(kind,1:K-1)\n# A = [zeros(T, mui[K], nukm1) psys.A[KK]; blockdiag(view(psys.A,kindm1)...) zeros(T, mukm1, ni[K])] +\n# [zeros(T, mui[K], n); zeros(T, mukm1, ni[1]) desc ? -blockdiag(view(psys.E,kindm1)...) : -I]\n# E = [desc ? psys.E[KK] : I zeros(T, mui[K], n-ni[1]); zeros(T, mukm1, n)]\n# B = [ zeros(T, mui[K], sum(view(m,1:K-1))) psys.B[KK]; blockdiag(view(psys.B,kindm1)...) zeros(T, mukm1, m[K])]\n# C = blockdiag(view(psys.C,kind)...) \n# D = blockdiag(view(psys.D,kind)...) \n# if compacted \n# A, E, B, C, D = lsminreal(A, E, B, C, D; fast, atol1, atol2, rtol, contr = false, obs = false, noseig = true) \n# end\n# return dss(A, E, B, C, D; Ts = LTs)\n# end\n\nfunction psreduc_fast(S::Vector{Matrix{T1}}, T::Vector{Matrix{T1}}; atol::Real = 0) where T1\n # PSREDUC_FAST Finds a matrix pair having the same finite and infinite \n # eigenvalues as a given periodic pair.\n #\n # [A,E] = PSREDUC_FAST(S,T,tol) computes a matrix pair (A,E) having \n # the same finite and infinite eigenvalues as the periodic pair (S,T).\n #\n \n # A. Varga 30-3-2004. \n # Revised: .\n #\n # Reference:\n # A. Varga & P. Van Dooren\n # Computing the zeros of periodic descriptor systems.\n # Systems and Control Letters, vol. 50, 2003.\n \n K = length(S) \n if K == 1\n return S[1], T[1] \n else\n m = size.(S,1)\n n = size.(S,2)\n if sum(m) > sum(n) \n # build the dual pair\n # [S,T]=celltranspose(S,T); \n # [S{1:K}] = deal(S{K:-1:1});\n # [T{1:K-1}] = deal(T{K-1:-1:1});\n # m = size.(S,1)\n # n = size.(S,2)\n end \n \n si = S[1]; ti = -T[1];\n tolr = atol\n for i = 1:K-2\n F = qr([ ti; S[i+1] ], ColumnNorm()) \n nr = minimum(size(F.R))\n # compute rank of r \n ss = abs.(diag(F.R[1:nr,1:nr]))\n atol == 0 && ( tolr = (m[i]+m[i+1]) * maximum(ss) * eps())\n rankr = count(ss .> tolr)\n \n si = F.Q'*[si; zeros(T1,m[i+1],n[1])]; si=si[rankr+1:end,:]\n ti = F.Q'*[ zeros(T1,size(ti,1),n[i+2]); -T[i+1]]; ti = ti[rankr+1:end,:]\n end\n a = [ zeros(T1,m[K],n[1]) S[K]; si ti] \n e = [ T[K] zeros(T1,m[K],n[K]); zeros(size(si)...) zeros(size(ti)...)] \n return a, e\n end\nend\n\"\"\"\n psreduc_reg(A) -> (M, N)\n\nDetermine for a `n×n×p` array `A`, the matrix pair `(M, N)` \nwith `N` invertible and `M-λN` regular, such that \nthe eigenvalues of `M-λN` are the same as those of the matrix product\n`A(p)*A(p-1)*...*A(1)`, where `A(i)` is contained in `A[:,:,i]`. \nThe structure exploiting fast reduction method of [1] is employed to determine `M` and `N`.\n\n[1] A. Varga & P. Van Dooren. Computing the zeros of periodic descriptor systems.\n Systems and Control Letters, 50:371-381, 2003.\n\"\"\"\nfunction psreduc_reg(A::AbstractArray{T,3}) where T\n \n K = size(A,3) \n n = size(A,1)\n n == size(A,2) || error(\"A must have equal first and second dimensions\")\n if K == 1\n return A[:,:,1], Matrix{T}(I, n, n)\n else \n Z = zeros(T,n,n)\n ZI = [Z; -I]\n si = A[:,:,1]; ti = -I\n for i = 1:K-1\n F = qr([ ti; A[:,:,i+1] ]) \n si = F.Q'*[si; Z]; si = si[n+1:end,:]\n ti = F.Q'*ZI; ti = ti[n+1:end,:]\n end\n return si, -ti\n end\nend\n\"\"\"\n psreduc_reg(A) -> (M, N)\n\nDetermine for a `p`-dimensional vector of rectangular matrices `A`, \nthe matrix pair `(M, N)` with `N` invertible and `M-λN` regular, such that \nthe eigenvalues of `M-λN` are the same as those of the square \nmatrix product `A(p)*A(p-1)*...*A(1)`, where `A(i)` is contained in `A[i]`. \nThe structure exploiting fast reduction method of [1] is employed to determine `M` and `N`.\n\n[1] A. Varga & P. Van Dooren. Computing the zeros of periodic descriptor systems.\n Systems and Control Letters, 50:371-381, 2003.\n\"\"\"\nfunction psreduc_reg(A::AbstractVector{Matrix{T}}) where T\n \n K = length(A) \n n = size.(A,2) \n n == size.(A,1)[mod.(2:K+1,K).+1] || \n error(\"the number of column of A[i] must be equal to the number of rows of A[i+1]\")\n\n if K == 1\n return A[1], Matrix{T}(I, n[1], n[1])\n else\n si = A[1]; ti = -I\n for i = 1:K-1\n F = qr([ ti; A[i+1] ]) \n mi1 = n[mod(i+1,K)+1]\n si = F.Q'*[si; zeros(T,mi1,n[1])]; si = si[n[i+1]+1:end,:] \n ti = F.Q'*[ zeros(T,n[i+1],mi1); -I]; ti = ti[n[i+1]+1:end,:] \n end\n return si, -ti\n end\nend\n\n# time response evaluations\n\n\"\"\"\n tvmeval(At::PeriodicTimeSeriesMatrix, t; method = \"linear\") -> A::Vector{Matrix}\n\nEvaluate the time response of a periodic time series matrix.\n\nFor the periodic time series matrix `At` and the vector of time values `t`, \nan interpolation/extrapolation based approximation \n`A[i]` is evaluated for each time value `t[i]`. The keyword parameter `method` specifies the\ninterpolation/extrapolation method to be used for periodic data. \nThe following interpolation methods from the [`Interpolations.jl`](https://github.com/JuliaMath/Interpolations.jl) \npackage can be selected: \n\n`method = \"constant\"` - use periodic B-splines of degree 0; \n\n`method = \"linear\"` - use periodic B-splines of degree 1 (periodic linear interpolation) (default);\n\n`method = \"quadratic\"` - use periodic B-splines of degree 2 (periodic quadratic interpolation); \n\n`method = \"cubic\"` - use periodic B-splines of degree 3 (periodic cubic interpolation).\n\"\"\"\nfunction tvmeval(A::PeriodicTimeSeriesMatrix{:c,T}, t::Union{Real,Vector{<:Real}}; method = \"linear\") where T\n N = length(A.values)\n N == 0 && error(\"empty time array not supported\")\n isa(t,Real) ? te = [t] : te = t\n N == 1 && (return [A.values[1] for i in te])\n nt = length(te)\n nt == 0 && (return zeros(T,size(A.values,1),size(A.values,2),0))\n dt = A.period/N\n ts = (0:N-1)*dt\n n1, n2 = size(A.values[1])\n intparray = Array{Any,2}(undef,n1, n2)\n if method == \"linear\"\n [intparray[i,j] = scale(Interpolations.extrapolate(interpolate(getindex.(A.values,i,j), BSpline(Linear(Periodic(OnCell())))), Periodic()), ts) for i in 1:n1, j in 1:n2]\n elseif method == \"cubic\" \n [intparray[i,j] = scale(Interpolations.extrapolate(interpolate(getindex.(A.values,i,j), BSpline(Cubic(Periodic(OnCell())))), Periodic()), ts) for i in 1:n1, j in 1:n2]\n elseif method == \"quadratic\" \n [intparray[i,j] = scale(Interpolations.extrapolate(interpolate(getindex.(A.values,i,j), BSpline(Quadratic(Periodic(OnCell())))), Periodic()), ts) for i in 1:n1, j in 1:n2]\n elseif method == \"constant\" \n [intparray[i,j] = scale(Interpolations.extrapolate(interpolate(getindex.(A.values,i,j), BSpline(Constant(Periodic(OnCell())))), Periodic()), ts) for i in 1:n1, j in 1:n2]\n else\n error(\"no such option method = $method\")\n end\n return [[intparray[i,j].(te[k]) for i in 1:n1, j in 1:n2 ] for k = 1:nt ]\nend\n\"\"\"\n hreval(Ahr::HarmonicArray, t; ntrunc, exact = true) -> A::Matrix\n\nEvaluate the harmonic array `Ahr` representing a continuous-time \ntime periodic matrix `A(t)` for a numerical or symbolic time value `t`. \nFor a real value `t`, if `exact = true (default)` an exact evaluation is computed, while for `exact = false`, \na linear interpolation based approximation is computed (potentially more accurate in intersample points).\nThe keyword argument `ntrunc` specifies the number of harmonics to be used for the evaluation \n(default: maximum possible number). \nIf `t` is a symbolic variable, a symbolic evaluation of `A(t)` is performed (see also [`hr2psm`](@ref))\n\"\"\"\nfunction hreval(ahr::HarmonicArray{:c,T}, t::Union{Num,Real}; exact::Bool = true, ntrunc::Int = max(size(ahr.values,3)-1,0)) where {T}\n (ntrunc < 0 || ntrunc >= size(ahr.values,3)) && error(\"ntrunc out of allowed range\")\n isa(t,Num) && (return hr2psm(ahr, 0:ntrunc))\n\n n = ntrunc \n T1 = float(promote_type(T,typeof(t)))\n ts = mod(T1(t),T1(ahr.period))*2*pi*ahr.nperiod/ahr.period\n \n # determine interpolation coefficients\n ht = ones(T1,n);\n if !exact\n # use linear interpolation\n for i = 2:n\n x = pi*(i-1)/n\n ht[i] = (sin(x)/x)^2\n end\n end\n a = T == T1 ? real.(ahr.values[:,:,1]) : T1.(real.(ahr.values[:,:,1]))\n for i = 1:n\n ta = view(ahr.values,:,:,i+1)\n a .+= T1.(real.(ta)).*(cos(i*ts)*ht[i]) .+ T1.(imag.(ta)) .* ((sin(i*ts)*ht[i]))\n end\n return a\nend \n\"\"\"\n tvmeval(Ahr::HarmonicArray, t; ntrunc, exact = true) -> A::Vector{Matrix}\n\nEvaluate the time response of a harmonic array.\n\nFor the harmonic array `Ahr` representing representing a continuous-time \ntime periodic matrix `A(t)` and the vector of time values `t`, \n`A[i] = A(t[i])` is computed for each time value `t[i]`. \nIf `exact = true (default)` an exact evaluation is computed, while for `exact = false`, \na linear interpolation based approximation is computed \n(potentially more accurate in intersample points).\nThe keyword argument `ntrunc` specifies the number of harmonics to be used for evaluation \n(default: maximum possible number of harmonics). \n\"\"\"\nfunction tvmeval(ahr::HarmonicArray{:c,T}, t::Union{Real,Vector{<:Real}}; ntrunc::Int = size(ahr.values,3), \n exact::Bool = true) where {T}\n \n n = min(size(ahr.values,3)-1,ntrunc);\n \n isa(t,Real) ? te = [t] : te = t\n nt = length(te)\n period = ahr.period\n \n tscal = 2*pi*ahr.nperiod/period\n # determine interpolation coefficients\n ht = ones(Float64,n);\n if !exact\n # use linear interpolation\n for i = 2:n\n x = pi*(i-1)/n\n ht[i] = (sin(x)/x)^2\n end\n end\n T1 = float(T)\n A = similar(Vector{Matrix{T1}}, nt)\n for j = 1:nt\n A[j] = real(ahr.values[:,:,1])\n tsj = mod(te[j],period)*tscal\n for i = 1:n\n ta = view(ahr.values,:,:,i+1)\n A[j] .+= real.(ta).*(cos(i*tsj)*ht[i]) .+ imag.(ta) .* ((sin(i*tsj)*ht[i]))\n end\n end\n return A\nend \n\"\"\"\n tvmeval(Asym::PeriodicSymbolicMatrix, t) -> A::Vector{Matrix}\n\nEvaluate the time response of a periodic symbolic matrix.\n\nFor the periodic symbolic matrix `Asym` representing a time periodic matrix `A(t)`\nand the vector of time values `t`, \n`A[i] = A(t[i])` is evaluated for each time value `t[i]`. \n\"\"\"\nfunction tvmeval(A::PeriodicSymbolicMatrix, t::Union{Real,Vector{<:Real}} )\n te = isa(t,Real) ? [mod(t,A.period)] : mod.(t,A.period)\n return (convert(PeriodicFunctionMatrix,A).f).(te)\nend\n\"\"\"\n tvmeval(Af::PeriodicFunctionMatrix, t) -> A::Vector{Matrix}\n\nEvaluate the time response of a periodic function matrix.\n\nFor the periodic function matrix `Af` representing a time periodic matrix `A(t)` and the vector of time values `t`, \n`A[i] = A(t[i])` is evaluated for each time value `t[i]`. \n\"\"\"\nfunction tvmeval(A::PeriodicFunctionMatrix, t::Union{Real,Vector{<:Real}} )\n te = isa(t,Real) ? [mod(t,A.period)] : mod.(t,A.period)\n return (A.f).(te)\nend\n\"\"\"\n tvmeval(A::FourierFunctionMatrix, t) -> Aval::Vector{Matrix}\n\nEvaluate the time response of a periodic function matrix.\n\nFor the periodic matrix `A(t)`, in a Fourier Function Matrix representation, and the vector of time values `t`, \n`Aval[i] = A(t[i])` is evaluated for each time value `t[i]`. \n\"\"\"\nfunction tvmeval(A::FourierFunctionMatrix, t::Union{Real,Vector{<:Real}} )\n te = isa(t,Real) ? [mod(t,A.period)] : mod.(t,A.period)\n return (A.M).(te)\nend\n\n\"\"\"\n pmaverage(A) -> Am \n\nCompute for the continuous-time periodic matrix `A(t)` \nthe corresponding time averaged matrix `Am` over one period. \n\"\"\"\nfunction pmaverage(A::PM) where {PM <: Union{PeriodicFunctionMatrix,PeriodicSymbolicMatrix,PeriodicTimeSeriesMatrix}} \n return real(convert(HarmonicArray,A).values[:,:,1])\nend\npmaverage(A::HarmonicArray) = real(A.values[:,:,1])\npmaverage(A::FourierFunctionMatrix) = getindex.(coefficients.(Matrix(A.M)),1)\n\nfunction getpm(A::PeriodicMatrix, k, dperiod::Union{Int,Missing} = missing)\n i = ismissing(dperiod) ? mod(k-1,A.dperiod)+1 : mod(k-1,dperiod)+1\n return A.M[i]\n #return view(A.M,i)\nend\nfunction getpm(A::PeriodicArray, k, dperiod::Union{Int,Missing} = missing)\n i = ismissing(dperiod) ? mod(k-1,A.dperiod)+1 : mod(k-1,dperiod)+1\n return A.M[:,:,i]\n #return view(A.M,:,:,i)\nend\nfunction copypm!(Dest::AbstractMatrix{T}, A::PeriodicMatrix{:d,T}, k, dperiod::Union{Int,Missing} = missing) where {T}\n i = ismissing(dperiod) ? mod(k-1,A.dperiod)+1 : mod(k-1,dperiod)+1\n return copyto!(Dest,view(A.M[i],:,:))\n #return copyto!(Dest,A.M[i])\n #return view(A.M,i)\nend\nfunction copypm!(Dest::AbstractMatrix, A::PeriodicArray, k, dperiod::Union{Int,Missing} = missing)\n i = ismissing(dperiod) ? mod(k-1,A.dperiod)+1 : mod(k-1,dperiod)+1\n return copyto!(Dest,view(A.M,:,:,i))\n #return view(A.M,:,:,i)\nend\n\n", "meta": {"hexsha": "fe041f143bf78fb326730dd14f76a129667af288", "size": 74643, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/psutils.jl", "max_stars_repo_name": "andreasvarga/PeriodicSystems.jl", "max_stars_repo_head_hexsha": "3c87149555e3734d04104fc012716f0654e146e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/psutils.jl", "max_issues_repo_name": "andreasvarga/PeriodicSystems.jl", "max_issues_repo_head_hexsha": "3c87149555e3734d04104fc012716f0654e146e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/psutils.jl", "max_forks_repo_name": "andreasvarga/PeriodicSystems.jl", "max_forks_repo_head_hexsha": "3c87149555e3734d04104fc012716f0654e146e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.4569105691, "max_line_length": 177, "alphanum_fraction": 0.5933041276, "num_tokens": 25229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029487, "lm_q2_score": 0.8596637469145054, "lm_q1q2_score": 0.8056861405861678}} {"text": "\"\"\"\n geometric_rng(p, shape=1; seed=nothing)\n\nGenerate a `shape` element array of random variables from a Geometric(`p`) distribution. Optionally you can set a specific seed.\n\n# Notes\n\nThe Geometric distribution is given:\n\n``f(x,p) = (1-p)^{x-1}p) \\\\quad x = 1,2,3,…``\n\nwhere ``0 ≤ p ≤ 1``\n\n# Examples\n\n```julia-repl\njulia> geometric_rng(.8)\n1-element Vector{Int64}:\n 1\n\njulia> geometric_rng(.8, 5)\n5-element Vector{Int64}:\n 2\n 3\n 1\n 1\n 1\n\njulia> geometric_rng(.8, (2,2), seed=45)\n2×2 Matrix{Int64}:\n 1 1\n 1 1\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\nC. Alexopoulos, D. Goldsman. Random variate generation. 2020.\n\"\"\"\nfunction geometric_rng(p::Real, shape::Union{Int, Tuple{Vararg{Int}}}=1; seed::Union{Int, Nothing}=nothing)\n check_p(p)\n c = log(1 - p)\n U = get_std_uniform(shape, seed=seed)\n X = zeros(Int, shape)\n X = floor.(Int, log.(U) ./ c) # here sub U for 1-U is fine\n return X\nend\n", "meta": {"hexsha": "b29dd39c147f4d3a5bb98d842e95ea9edd553839", "size": 1045, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/geometric.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/geometric.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/geometric.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": 20.4901960784, "max_line_length": 128, "alphanum_fraction": 0.6555023923, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107949104868, "lm_q2_score": 0.8596637433190939, "lm_q1q2_score": 0.8056861402318126}} {"text": "\"\"\"\r\n rungekuttasistem(f,a,b,y0,M)\r\nberisi program untuk mencari solusi sistem persamaan differensial `x'=f(t,z)`\r\ndan `y'=g(t,z)` dengan masalah\r\nnilai awal `x(a)=x0` dan `y(a)=y0` pada interval `[a,b]`. Program ini secara default\r\nberisi 5 masukan, yaitu fungsi yang berisi `f(t,z)` dan `g(t,z)`, titik ujung interval `[a,b]`,\r\nnilai awal `z0` yang berisi `[x0,y0]`, dan jumlah sub-interval `M`. Program dapat digunakan juga\r\nuntuk sistem persamaan diferensial lebih dari 2 persamaan.\r\n\r\n# Example\r\n```jl\r\njulia> f(t,z) = [ z[1]+2*z[2] , 3*z[1]+2*z[2] ];\r\n\r\njulia> sol = rungekuttasistem(f,0,0.2,[6,4],10)\r\n11×3 Array{Float64,2}:\r\n 0.0 6.0 4.0\r\n 0.02 6.29355 4.53932\r\n 0.04 6.61562 5.11949\r\n 0.06 6.96853 5.74397\r\n ⋮\r\n 0.14 8.74141 8.76532\r\n 0.16 9.29021 9.6746\r\n 0.18 9.88827 10.6561\r\n 0.2 10.5396 11.7158\r\n```\r\nreturn solusi masalah nilai awal `sol`.\r\n\"\"\"\r\nfunction rungekuttasistem(f,a,b,y0,M)\r\n M = Int(M)\r\n h = (b-a)/M;\r\n T = a:h:b;\r\n Y = Array{Float64}(undef,M+1,length(y0))\r\n Y[1,:] = y0;\r\n for k = 1:M\r\n f1 = f(T[k] ,Y[k,:] );\r\n f2 = f(T[k]+h/2 ,Y[k,:]+f1*h/2 );\r\n f3 = f(T[k]+h/2 ,Y[k,:]+f2*h/2 );\r\n f4 = f(T[k]+h ,Y[k,:]+f3*h );\r\n Y[k+1,:] = Y[k,:] + h/6*(f1+2*f2+2*f3+f4);\r\n end\r\n sol = [T Y];\r\nend\r\n", "meta": {"hexsha": "b3548858709f891967a0bc629ae5bca07027ef00", "size": 1290, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/rungekuttasistem.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/rungekuttasistem.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/rungekuttasistem.jl", "max_forks_repo_name": "mkhoirun-najiboi/metnum.jl", "max_forks_repo_head_hexsha": "a6e35d04dc277318e32256f9b432264157e9b8f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0, "max_line_length": 97, "alphanum_fraction": 0.5542635659, "num_tokens": 582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107878954106, "lm_q2_score": 0.8596637451167997, "lm_q1q2_score": 0.8056861358860352}} {"text": "function spherical_to_cartesian(ρ, θ, φ)\n x = ρ * sin(θ) * cos(φ)\n y = ρ * sin(θ) * sin(φ)\n z = ρ * cos(θ)\n Vector3(x, y, z)\nend\nspherical_to_cartesian(spherical::Vector3) = spherical_to_cartesian(spherical[1], spherical[2], spherical[3])\n\nfunction cartesian_to_spherical(x, y, z)\n ρ = √(x ^ 2 + y ^ 2 + z ^ 2)\n θ = acos(z / ρ)\n φ = atan(y, x)\n Vector3(ρ, θ, φ)\nend\ncartesian_to_spherical(xyz::Vector3) = cartesian_to_spherical(xyz[1], xyz[2], xyz[3])\n\nρ_hat(θ, φ) = Vector3(sin(θ) * cos(φ), sin(θ) * sin(φ), cos(θ))\nρ_hat(Ω::Vector3) = normalize(Ω)\nθ_hat(θ, φ) = Vector3(cos(θ) * cos(φ), cos(θ) * sin(φ), -sin(θ))\nφ_hat(θ, φ) = Vector3(-sin(φ), cos(φ), 0)\n∂Ω_∂ρ(θ, φ) = zero(Vector3)\n∂Ω_∂θ(θ, φ) = Vector3(cos(θ) * cos(φ), cos(θ) * sin(φ), -sin(θ))\n∂Ω_∂φ(θ, φ) = Vector3(-sin(θ) * sin(φ), sin(θ) * cos(φ), 0)\n\nfor func in (:θ_hat, :φ_hat, :∂Ω_∂ρ, :∂Ω_∂θ, :∂Ω_∂φ)\n @eval $func(Ω::Vector3) = let (_, θ, φ) = cartesian_to_spherical(Ω)\n $func(θ, φ)\n end\nend\n", "meta": {"hexsha": "69da1e63464a921bba38a4464a2566f37cf10f23", "size": 992, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils/spherical_coordinates.jl", "max_stars_repo_name": "sunoru/MosiBase.jl", "max_stars_repo_head_hexsha": "2cd8fba1f64cff3c968a6bea9d9944fed8898e30", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils/spherical_coordinates.jl", "max_issues_repo_name": "sunoru/MosiBase.jl", "max_issues_repo_head_hexsha": "2cd8fba1f64cff3c968a6bea9d9944fed8898e30", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-24T22:17:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T22:17:11.000Z", "max_forks_repo_path": "src/utils/spherical_coordinates.jl", "max_forks_repo_name": "sunoru/MosimoBase.jl", "max_forks_repo_head_hexsha": "1ac9aadc82d299b2c85a900a18e42db5f9f84988", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0666666667, "max_line_length": 109, "alphanum_fraction": 0.5756048387, "num_tokens": 466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214450208031, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.8056746858653764}} {"text": "# Pawel Zielinski\nmodule matrixgen\n\nusing LinearAlgebra\n\nexport blockmat\n\nfunction matcond(n::Int, c::Float64)\n\t# Function generates a random square matrix A of size n with\n\t# a given condition number c.\n\t# Inputs:\n\t#\tn: size of matrix A, n>1\n\t#\tc: condition of matrix A, c>= 1.0\n\t#\n\t# Usage: matcond(10, 100.0)\n\t#\n\t# Pawel Zielinski\n if n < 2\n error(\"size n should be > 1\")\n end\n if c < 1.0\n error(\"condition number c of a matrix should be >= 1.0\")\n end\n (U, S, V) = svd(rand(n, n))\n return U * diagm(0 => [LinRange(1.0, c, n);]) * V'\nend\n\n\n\n\n function blockmat(n::Int, l::Int, ck::Float64, outputfile::String)\n\t\t# Function generates a random block sparse matrix A of size n with\n\t\t# a given condition number ck of inner block Ak and it save the output\n\t\t# matrix in a text file.\n\t\t# Inputs:\n\t\t#\tn: size of block matrix A, n>1\n\t\t# l: size of inner matrices Ak, n mod l =0 (n is divisible by l)\n\t\t#\tck: condition of inner matrix Ak, ck>= 1.0\n\t\t# outputfile: name of the output text file\n\t\t#\n\t\t# Usage: blockmat(100, 4 ,10.0, \"A.txt\")\n\t\t#\n\t\t#\n\t\t# the output file format\n\t # n l <--- the size of block matrix A, the size of inner matrices Ak\n\t\t# i1 j1 A[i1,j1] <--- a non-zero element of block matrix A\n\t\t# i2 j2 A[i2,j2] <--- a non-zero element of block matrix A\n\t\t# i3 j3 A[i3,j3] <--- a non-zero element of block matrix A\n\t\t# ...\n\t\t# ...\n\t\t# EOF\n\t\t#\n\n if n < 2\n error(\"size n should be > 1\")\n end\n\t\tif n % l != 0\n\t\t\terror(\"n is not divisible by l\")\n\t\tend\n\n\t\tnb = div(n, l)\n\t\tAk = Matrix{Float64}(undef, l, l)\n\t\topen(outputfile, \"w\") do f\n\t\t\tprintln(f, n, \" \", l)\n\t\t\tfor k in 1:nb\n\t\t\t\tAk = matcond(l, ck)\n\t\t\t\tfor i in 1:l, j in 1:l\n\t\t\t\t\tprintln(f, (k - 1) * l + i, \" \", (k - 1) * l + j, \" \", Ak[i,j])\n\t\t\t\tend\n\t\t\t\tif k < nb\n\t\t\t \t for i in 1:l\n\t\t\t\t\t\tprintln(f, (k - 1) * l + i, \" \", k * l + i, \" \", 0.3 * rand())\n\t\t\t\t \t end\n\t\t\t\tend\n\t\t\t\tif k > 1\n\t\t\t for i in 1:l\n\t\t\t\t\t println(f, (k - 1) * l + i, \" \", (k - 1) * l, \" \", 0.3 * rand())\n\t\t\t\t end\n\t\t\t\tend\n\t\t\tend\n\t\tend\t # do\n\tend # blockmat\n\n\n\n\nend # matrixgen\n", "meta": {"hexsha": "b1bae310e8e69bc205574b7637a6e76f2d6f1fda", "size": 2087, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "5th-semester/on/lab/lista-5/code/test-data/external.jl", "max_stars_repo_name": "jerry-sky/academic-notebook", "max_stars_repo_head_hexsha": "be2d350289441b99168ea40412891bc65b9cb431", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-12-28T21:53:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T19:24:47.000Z", "max_issues_repo_path": "5th-semester/on/lab/lista-5/code/test-data/external.jl", "max_issues_repo_name": "jerry-sky/academic-notebook", "max_issues_repo_head_hexsha": "be2d350289441b99168ea40412891bc65b9cb431", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2022-02-13T18:07:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-13T18:16:07.000Z", "max_forks_repo_path": "5th-semester/on/lab/lista-5/code/test-data/external.jl", "max_forks_repo_name": "jerry-sky/academic-notebook", "max_forks_repo_head_hexsha": "be2d350289441b99168ea40412891bc65b9cb431", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-12-28T16:05:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T16:20:00.000Z", "avg_line_length": 23.7159090909, "max_line_length": 86, "alphanum_fraction": 0.5481552468, "num_tokens": 796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474181553805, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.8056222770996768}} {"text": "using CompScienceMeshes\nusing SauterSchwabQuadrature\n\n\n\npI = point(1,5,3)\npII = point(2,5,3)\npIII = point(7,1,0)\npIV = point(5,1,-3)\npV = point(0,0,0)\n\nSourcechart = simplex(pI,pIII,pII)\nTestchart = simplex(pV,pIV,pI)\n\nAccuracy = 12\n\n\nfunction integrand(x,y)\n\t\t\treturn(((x-pI)'*(y-pV))*exp(-im*1*norm(x-y))/(4pi*norm(x-y)))\n end\n\n\n\nresult = sauterschwabintegral(Sourcechart, Testchart, integrand, Accuracy, Accuracy)\nprintln(result)\n\n#=For those who want to test the sauterschwab_nonparameterized() function,\nmay uncomment the following five lines=#\n\n#sourcechart = simplex(pI,pIII,pII)\n#testchart = simplex(pI,pIV,pV)\n#cv = CommonVertex(Accuracy)\n#result2 = sauterschwab_nonparameterized(sourcechart, testchart, integrand, cv)\n#println(result2)\n\n#=The common vertex is the first input argument of both simplex() functions,\nhence the required condition is fulfilled. The user may also compare the two\nresults and see that both are equal=#\n", "meta": {"hexsha": "759d52b576d9ad23c99155eb8f91daeef9923071", "size": 939, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/common_vertex_non_parameterized.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SauterSchwabQuadrature.jl-535c7bfe-2023-5c1d-b712-654ef9d93a38", "max_stars_repo_head_hexsha": "419fb564912814b5e033df52e255db707349b600", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-12-23T16:54:33.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-23T16:54:33.000Z", "max_issues_repo_path": "examples/common_vertex_non_parameterized.jl", "max_issues_repo_name": "UnofficialJuliaMirror/SauterSchwabQuadrature.jl-535c7bfe-2023-5c1d-b712-654ef9d93a38", "max_issues_repo_head_hexsha": "419fb564912814b5e033df52e255db707349b600", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-07-23T12:35:34.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-23T12:44:53.000Z", "max_forks_repo_path": "examples/common_vertex_non_parameterized.jl", "max_forks_repo_name": "UnofficialJuliaMirror/SauterSchwabQuadrature.jl-535c7bfe-2023-5c1d-b712-654ef9d93a38", "max_forks_repo_head_hexsha": "419fb564912814b5e033df52e255db707349b600", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2017-10-31T14:02:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-25T06:47:26.000Z", "avg_line_length": 24.0769230769, "max_line_length": 84, "alphanum_fraction": 0.7465388711, "num_tokens": 285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475715065793, "lm_q2_score": 0.853912760387131, "lm_q1q2_score": 0.8055365287896796}} {"text": "using DelimitedFiles\nusing LinearAlgebra\n\nfunction convolve_cyclic(signal::Array{T, 1},\n filter::Array{T, 1}) where {T <: Number}\n\n # output size will be the size of sign\n output_size = max(length(signal), length(filter))\n\n # convolutional output\n out = Array{Float64,1}(undef,output_size)\n sum = 0\n\n for i = 1:output_size\n for j = 1:output_size\n if (mod1(i-j, output_size) <= length(filter))\n sum += signal[mod1(j, output_size)] * filter[mod1(i-j, output_size)]\n end\n end\n\n out[i] = sum\n sum = 0\n\n end\n\n return out\nend\n\nfunction convolve_linear(signal::Array{T, 1}, filter::Array{T, 1},\n output_size) where {T <: Number}\n\n # convolutional output\n out = Array{Float64,1}(undef, output_size)\n sum = 0\n\n for i = 1:output_size\n for j = max(1, i-length(filter)):i\n if j <= length(signal) && i-j+1 <= length(filter)\n sum += signal[j] * filter[i-j+1]\n end\n end\n\n out[i] = sum\n sum = 0\n end\n\n return out\nend\n\nfunction main()\n\n # sawtooth functions for x and y\n x = [float(i)/200 for i = 1:200]\n y = [float(i)/200 for i = 1:200]\n\n # Normalization is not strictly necessary, but good practice\n normalize!(x)\n normalize!(y)\n\n # full convolution, output will be the size of x + y\n full_linear_output = convolve_linear(x, y, length(x) + length(y))\n\n # simple boundaries\n simple_linear_output = convolve_linear(x, y, length(x))\n\n # cyclic convolution\n cyclic_output = convolve_cyclic(x, y)\n\n # outputting convolutions to different files for plotting in external code\n writedlm(\"full_linear.dat\", full_linear_output)\n writedlm(\"simple_linear.dat\", simple_linear_output)\n writedlm(\"cyclic.dat\", cyclic_output)\n\nend\n", "meta": {"hexsha": "78dafc0ed9843c9a96e02d5265f978ab9772a5b2", "size": 1868, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "contents/convolutions/code/julia/1d_convolution.jl", "max_stars_repo_name": "Ridham177/algorithm-archive", "max_stars_repo_head_hexsha": "2797d85ae0348395f403cc2f3ec13e5bc1bb3d90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2018-06-30T08:18:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-02T17:24:30.000Z", "max_issues_repo_path": "contents/convolutions/code/julia/1d_convolution.jl", "max_issues_repo_name": "Ridham177/algorithm-archive", "max_issues_repo_head_hexsha": "2797d85ae0348395f403cc2f3ec13e5bc1bb3d90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-07-05T19:04:03.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-05T22:31:07.000Z", "max_forks_repo_path": "contents/convolutions/code/julia/1d_convolution.jl", "max_forks_repo_name": "Ridham177/algorithm-archive", "max_forks_repo_head_hexsha": "2797d85ae0348395f403cc2f3ec13e5bc1bb3d90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2018-04-28T12:02:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-17T20:38:46.000Z", "avg_line_length": 24.9066666667, "max_line_length": 84, "alphanum_fraction": 0.6027837259, "num_tokens": 505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237605, "lm_q2_score": 0.8840392802184581, "lm_q1q2_score": 0.8055186571207629}} {"text": "### A Pluto.jl notebook ###\n# v0.12.16\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# ╔═╡ e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, Statistics, DataFrames\n\tRandom.seed!(0)\nend;\n\n# ╔═╡ ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing5.07\"\n\n# ╔═╡ fa68607e-22e5-11eb-0558-c9a4d9f77426\ntrueVar, trueStd = 1/12, sqrt(1/12)\n\n# ╔═╡ 81b26bd0-3a9a-11eb-0a09-db9eed1b0609\nfunction estVar(n)\n sample = rand(n)\n sum((sample .- 0.5).^2)/n\nend\n\n# ╔═╡ 81b2aba4-3a9a-11eb-1bd6-a938171cf060\nbegin\n\tN = 10^7\n\tdf = DataFrame()\n\tfor n in 5:5:30\n\t\tbiasVar = mean([estVar(n) for _ in 1:N]) - trueVar\n\t\tbiasStd = mean([sqrt(estVar(n)) for _ in 1:N]) - trueStd\n\t\tappend!(df, DataFrame(:n => n, :var_bias => round(biasVar, digits=5), \n\t\t\t\t:std_bias => round(biasStd, digits=5)))\n\tend\n\tdf\nend\n\n# ╔═╡ 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing5.07\"\n\n# ╔═╡ Cell order:\n# ╟─ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# ╠═e077ab16-22e5-11eb-15ed-5f0654bf7328\n# ╠═e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# ╠═fa68607e-22e5-11eb-0558-c9a4d9f77426\n# ╠═81b26bd0-3a9a-11eb-0a09-db9eed1b0609\n# ╠═81b2aba4-3a9a-11eb-1bd6-a938171cf060\n# ╟─475ff888-22e6-11eb-2354-09f8f40a8e12\n", "meta": {"hexsha": "9abdb30932781c3d9b88fea708f9060a5a7e7d4f", "size": 1278, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/05/listing5.07.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/05/listing5.07.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/05/listing5.07.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 24.1132075472, "max_line_length": 72, "alphanum_fraction": 0.7050078247, "num_tokens": 664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.8705972650509008, "lm_q1q2_score": 0.805502673777328}} {"text": "p = [ randn(2) for i = 1:10 ] # 10 random points - note array-of-array\n\n# Plot the points as dots\n# The functions first and last simply collects the corresponding indices\nusing PyPlot\nplot(first.(p), last.(p), \".\")\naxis(\"equal\"); grid(true);\n\nfunction clockwise_oriented(p1, p2, p3)\n # Return true if the line-segment between points p1,p2 is clockwise\n # oriented to the line-segment between points p1,p3\n cross = (p3[2] - p1[2]) * (p2[1] - p1[1]) - (p3[1] - p1[1]) * (p2[2] - p1[2])\n return cross > 0\nend\n\n# Tests\nprintln(clockwise_oriented([0,0], [1,1], [2,3]))\nprintln(clockwise_oriented([0,0], [1,1], [3,2]))\n\nfunction convex_hull(p)\n # Find the nodes on the convex hull of the point array p using\n # the Jarvis march (gift wrapping) algorithm\n\n _, pointOnHull = findmin(first.(p)) # Start at left-most point\n hull = [pointOnHull] # Output: Vector of node indices on the convex hull\n \n while length(hull) ≤ 1 || hull[1] != hull[end] # Loop until closed polygon\n nextPoint = hull[end] % length(p) + 1 # First candidate, any point except current\n for j = 1:length(p) # Consider all other points\n if clockwise_oriented(p[hull[end]], p[nextPoint], p[j]) # If \"more to the left\", switch\n nextPoint = j\n end\n end\n push!(hull, nextPoint) # Update current point\n end\n return hull\nend\n\n# Example: 100 random points, compute and draw the convex hull\np = [ randn(2) for i = 1:100 ]\nhull = convex_hull(p)\nplot(first.(p), last.(p), \".\")\nplot(first.(p[hull]), last.(p[hull]))\naxis(\"equal\"); grid(true);\n\n\n", "meta": {"hexsha": "45ab86769a7f1be397172f784abbe1e3f0c92fa9", "size": 1596, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "textbook/_build/jupyter_execute/content/Computational_Geometry/Convex_Hull.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/Computational_Geometry/Convex_Hull.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/Computational_Geometry/Convex_Hull.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": 33.9574468085, "max_line_length": 99, "alphanum_fraction": 0.6353383459, "num_tokens": 488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.8705972684083609, "lm_q1q2_score": 0.8055026697040768}} {"text": "\"\"\"\n expspace(x_min::Float64, x_max::Float64)::Array{Float64}, x_scale::Float64,n_x::Int64)\nThis generates a vector of length n_x between x_min and x_max,\nwhere the spacing is controlled by x_scale. When x_scale == 1,\nthis is equivalent to linspace. When x_scale > 1, the points\nare closer together near x_min. When 0 < x_scale < 1,\nthe points are closer together near x_max.\n\"\"\"\nfunction expspace(x_min::Float64, x_max::Float64, x_scale::Float64,n_x::Int64)::Array{Float64}\n x_vec=zeros(n_x)\n if n_x>1\n step=(x_max-x_min)/(n_x-1)^x_scale\n else\n step=0.0\n end\n\n for i=1:n_x\n x_vec[i]=x_min+step*(i-1)^x_scale\n end\n\n return x_vec\nend\n\n\"\"\"\n tauchen(N::Integer=18, ρ::Real=0.96, σ::Real=0.045, μ::Real=0.0, n_std::Integer=4)\nTauchen's (1996) method for approximating AR(1) process with a finite markov chain\n```math\n y_t = \\\\mu + \\\\rho y_{t-1} + \\\\epsilon_t\n```\nwhere \\$\\\\epsilon_t \\\\sim N (0, \\\\sigma^2)\\$\n##### Arguments\n- `N::Integer`: Number of points in markov process\n- `ρ::Real` : Persistence parameter in AR(1) process\n- `σ::Real` : Standard deviation of random component of AR(1) process\n- `μ::Real(0.0)` : Mean of AR(1) process\n- `n_std::Integer(4)` : The number of standard deviations to each side the process\n should span\n##### Returns\n- `grid, Π, Π_cdf` : The grid, the transition matrix and CDF of transition matrix\n##### Notes\n- This function has been modified by QuantEcon.jl\n\"\"\"\nfunction tauchen(N::Integer=9, ρ::Real=0.96, σ::Real=0.045, μ::Real=0.0, n_std::Integer=4)\n if N > 1\n a_bar = n_std * sqrt(σ^2 / (1 - ρ^2))\n y = range(-a_bar,stop= a_bar,length= N)\n d = y[2] - y[1]\n else\n a_bar = 0.0\n y = range(-a_bar,stop= a_bar,length= N)\n end\n # Construct grid\n\n grid = y .+ μ / (1 - ρ)\n\n # Get transition probabilities\n if N > 1\n if ρ > 0.0\n Π = zeros(N, N)\n for row = 1:N\n # Do end points first\n Π[row, 1] = cdf(Normal(),(y[1] - ρ*y[row] + d/2) / σ)\n Π[row, N] = 1 - cdf(Normal(),(y[N] - ρ*y[row] - d/2) / σ)\n\n # fill in the middle columns\n for col = 2:N-1\n Π[row, col] = (cdf(Normal(),(y[col] - ρ*y[row] + d/2) / σ) -\n cdf(Normal(),(y[col] - ρ*y[row] - d/2) / σ))\n end\n end\n Π_cdf=cumsum(Π,dims=2)\n else\n Π = zeros(N)\n Π[1] = cdf(Normal(),(y[1] + d/2) / σ)\n Π[N] = 1 - cdf(Normal(),(y[N] - d/2) / σ)\n for col=2:N-1\n Π[col] = (cdf(Normal(),(y[col] + d/2) / σ) -\n cdf(Normal(),(y[col] - d/2) / σ))\n end\n Π_cdf=cumsum(Π,dims=1)\n\n end\n else\n Π=[1.0]\n Π_cdf =[1.0]\n end\n\n\n return grid, Π, Π_cdf\nend\n", "meta": {"hexsha": "7e1dfa6d2cf2d8767d22594db58651d269a23cd8", "size": 2813, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Grids.jl", "max_stars_repo_name": "pmarg/EconTools.jl", "max_stars_repo_head_hexsha": "eb2d0cf39546df524ce19630ff5f7880dd041a60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Grids.jl", "max_issues_repo_name": "pmarg/EconTools.jl", "max_issues_repo_head_hexsha": "eb2d0cf39546df524ce19630ff5f7880dd041a60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Grids.jl", "max_forks_repo_name": "pmarg/EconTools.jl", "max_forks_repo_head_hexsha": "eb2d0cf39546df524ce19630ff5f7880dd041a60", "max_forks_repo_licenses": ["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.9120879121, "max_line_length": 94, "alphanum_fraction": 0.5410593672, "num_tokens": 998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425377849806, "lm_q2_score": 0.8757870046160257, "lm_q1q2_score": 0.8054109834841884}} {"text": "const L_system_instructions = @SVector ['F', # Go forward\n '-', # Turn right 90°\n '+' # Turn left 90°\n ]\nstruct L_System\n axiom::Char\n rules::Dict{Char, String}\nend\n\nfunction apply_rules(L::L_System, N::Int64; production_sequence::String = \"\")\n if production_sequence == \"\"\n production_sequence = string(L.axiom)\n end\n if N == 0\n return production_sequence\n else\n new_production_sequence = String[] \n for i ∈ production_sequence\n if i ∈ L_system_instructions\n push!(new_production_sequence, string(i))\n else\n push!(new_production_sequence, L.rules[i])\n end\n end\n return apply_rules(L, N-1, production_sequence = join(new_production_sequence))\n end\nend\n\n# For rectangular domains, with angles constrained to n(π/2) where n = 0,1,2,...\n# θ₀ = 0 ⟹ 0°\n# θ₀ = 1 ⟹ 90°\n# θ₀ = 2 ⟹ 180°\n# θ₀ = 3 ⟹ 270°\nfunction generate_points(production_sequence::String, p₀::Point_2D, \n θ₀::Int64, Δx::Float64, Δy::Float64)\n points = [p₀]\n p = p₀\n θ = θ₀\n for i ∈ production_sequence\n if i == 'F'\n p = p + Point_2D(cos(θ*π/2)*Δx, sin(θ*π/2)*Δy)\n push!(points, p)\n elseif i == '+'\n θ = mod(θ + 1, 4)\n elseif i == '-'\n θ = mod(θ - 1, 4)\n end\n end\n return points\nend\n\nfunction hilbert_curve()\n # Note Hilbert curve returns 2^(n^2-1) points\n return L_System('A', Dict('A' => \"+BF-AFA-FB+\", 'B' => \"-AF+BFB+FA-\"))\nend\n\n# Generate the vector of points making up the Hilbert curve that fill a bounding box bb\n# npoints is the target number of points, where the number of points returned will always\n# be greater than or equal to npoints\nfunction hilbert_curve(bb::Rectangle_2D, npoints::Int64)\n L = hilbert_curve() \n # Note Hilbert curve returns 2^(2n) points\n n = ceil(Int64, log(npoints)/(2log(2)))\n npoints_actual = 2^(2n)\n Δx = width(bb)/(sqrt(npoints_actual) - 1)\n Δy = height(bb)/(sqrt(npoints_actual) - 1)\n production_sequence = apply_rules(L, n)\n return generate_points(production_sequence, bb.bl, 0, Δx, Δy) \nend\n", "meta": {"hexsha": "a3d595b62fa782c6a203e683e9f210cb553f1b80", "size": 2294, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/todo/L_system.jl", "max_stars_repo_name": "khurrumsaleem/MOCNeutronTransport", "max_stars_repo_head_hexsha": "16ccaf48d6c01e57e55e74ffbfbd71bbcd0f423c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/todo/L_system.jl", "max_issues_repo_name": "khurrumsaleem/MOCNeutronTransport", "max_issues_repo_head_hexsha": "16ccaf48d6c01e57e55e74ffbfbd71bbcd0f423c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/todo/L_system.jl", "max_forks_repo_name": "khurrumsaleem/MOCNeutronTransport", "max_forks_repo_head_hexsha": "16ccaf48d6c01e57e55e74ffbfbd71bbcd0f423c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7714285714, "max_line_length": 89, "alphanum_fraction": 0.5701830863, "num_tokens": 669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.8757869981319863, "lm_q1q2_score": 0.8054109717347009}} {"text": "# # 線形回帰\n# ## 1.1最小二乗法 \n# ### 例19(問3に対応)\n# 単回帰分析。回帰係数と切片を返す関数を定義します。 \n# ユニコード使用可能なので数式と関数との対応が分かりやすくできるのがjuliaの特長の一つです。\n# \n# \\note{meanやnorm関数などを使うため、Distributions.jlとLinearAlgebra.jlをインポートしておきます。}\n# \n# ---\n# ```julia\n# function min_sq(x::Vector{T},y::Vector{T}) where {T<:Number}\n# x̄ = mean(x)\n# ȳ = mean(y)\n# β₁ = (x .- x̄)'*(y .- ȳ) / norm(x .- x̄)^2 #傾き\n# β₀ = ȳ - β₁ * x̄ #切片\n# return β₁,β₀\n# end\n# ```\n# まずはトイデータの生成から。\nusing Joe, Random, Distributions, LinearAlgebra\nRandom.seed!(123) #乱数の種を固定\nN = 100\na = rand(Normal(2,1),N) #傾き、平均2分散1の正規分布からサンプリング\nb = randn() #切片\nx = randn(N) \ny = a .* x .+ b + randn(N);\n\n# 普通に単回帰する場合。\n\na1, b1 = min_sq(x,y)\n\n# データを中心化したあとに回帰分析すると切片が0になる(あたりまえ)。\nxx = x .- mean(x); yy = y .- mean(y)\na2,b2 = min_sq(xx,yy)\n\n# 図1.2を可視化してみる。matplotlibに比べてコードが短いのがいいですね。\n# juliaを扱う本はこれからどんどん増えてくると思いますが、pythonで書いた本よりもかなり紙面\n# を節約できるのではないでしょうか。\n# 日本語フォントを扱うための設定は[GenKurokiさんのコード](https://gist.github.com/genkuroki/6c2b71f62504432bdf8a27d24106cad8)を参考にしました。\n# デプロイするとなぜかxlabelとylabelが切れてしまうので、余白の調整もしています。\nusing Plots; gr()\nusing Plots.PlotMeasures\nPlots.reset_defaults()\ndefault(\n titlefont = font(\"JuliaMono\", default(:titlefontsize), ),\n guidefont = font(\"JuliaMono\", default(:guidefontsize), ),\n tickfont = font(\"JuliaMono\", default(:tickfontsize), ),\n legendfont = font(\"JuliaMono\", default(:legendfontsize), ),\n left_margin = 30px,\n bottom_margin = 30px,\n)\np12 = scatter(x,y,label=\"original\",legend=:topleft,xlabel=\"x\", ylabel=\"y\")\nplot!(c->a1*c+b1 ,label=\"before centering\")\nplot!(c->a2*c+b2 , label=\"after centering\")\nsavefig(p12,joinpath(@OUTPUT,\"fig1-2.svg\")) # hide\n# \\fig{fig1-2}\n\n# ## 1.2 重回帰 \n# ### 例20\n# $\\hat{\\beta} = (X^T X)^{-1} X^Ty$ を解くだけなので、もはや関数化する程でもないが、\n# 後々のことを考えて、関数化します。\n# また、係数行列に定数項のために全ての要素が1の列を1列目に挿入しますが、\n# わざわざnumpyをimportしてnp.insert(x,0,1,axis=1)を呼び出すのが嫌なので、\n# 以下のような関数を定義しました。(この行列、何かいい名前があるといいのですが。)\n# ```julia\n# function insert_ones(X)\n# N = typeof(X) <: Matrix ? size(X)[1] : length(X)\n# T = eltype(X)\n# return hcat(ones(T,N),X)\n# end\n# ```\n# また、重回帰係数を最小二乗法で求める関数を次のように定義しました。\n# ```julia\n# function multiple_regression(x::Matrix{T}, y::Vector{T}) where {T<:Number}\n# N,_ = size(x)\n# @assert N==length(y)\n# X = insert_ones(x)\n# return (X'X)\\X'y\n# end\n# ```\n\n# ## 1.4 RSSの分布 \n# ### 例21\n# $\\chi^2$分布のプロット。原著のプロット(図1.3)は間違っているらしい。\n# Plots.jlは無名関数のプロットができるので便利。\np13 = plot(xlims=(0,8),ylims=(0,1),title=\"DOF of chi\",legend=:topright)\nfor i in 1:10\n plot!(p13,0.1:0.1:8,x->pdf(Chisq(i),x),label=\"dof = $(i)\")\nend\nsavefig(p13,joinpath(@OUTPUT,\"fig1-3.svg\")) # hide\n# \\fig{fig1-3}\n# ## 1.5 $\\hat{\\beta}_j \\neq 0$の仮説検定 \n# ### 例22\n# t分布のプロット\np15 = plot(x->pdf(Normal(0,1),x),label=\"正規分布\")\nfor i in 1:10\n plot!(x->pdf(TDist(i),x), ls=:dash, label=\"dof: $(i)\")\nend\nsavefig(p15,joinpath(@OUTPUT,\"fig1-5.svg\")) # hide\n# \\fig{fig1-5}\n\n# ### 例23 \nN=100;iter_num=100; \ndata23 = Matrix(undef,iter_num,2)\nfor i in 1:iter_num\n x23=randn(N) .+2\n y23= x23 .+ 1 + randn(N)\n data23[i,:] = min_sq(x23,y23) |> collect\nend\np14 = scatter(data23[:,2],data23[:,1],xlabel=\"β₀\",ylabel=\"β₁\",title=\"test\",legend=false)\nsavefig(p14,joinpath(@OUTPUT,\"fig1-4.svg\")) # hide\n# \\fig{fig1-4}\n# \n# ### 例24(問12に対応)\n# 後々のことを考えて、RSSやR2を定義しておきます。 \n# ```julia\n# \n# function RSS(x::Vector,y)\n# β̂ = min_sq(x,y)\n# ŷ = β̂[1]*x .+ β̂[2]\n# return (y-ŷ)'*(y-ŷ)\n# end\n# function RSS(x,y)\n# ŷ = insert_ones(x)*multiple_regression(x,y)\n# return (y-ŷ)'*(y-ŷ)\n# end\n# \n# \n# function RSE(x::Matrix,y)\n# n,p = size(x)\n# RSS(x,y) / (n-p-1) |> sqrt\n# end\n# \n# function RSE(x::Vector,y)\n# RSS(x,y) / (length(x)-2) |> sqrt\n# end\n# \n# function Bdiag(x)\n# X = insert_ones(x)\n# return X'X |> inv |> diag\n# end\n# ```\n# \n\nusing Joe, Statistics\nN = 100;Random.seed!(123)\nx24 = randn(N); y24=randn(N);\nβ₁, β₀ = min_sq(x24,y24)\nrse = Joe.RSE(x24,y24)\nse₀, se₁ = rse*sqrt.(Joe.Bdiag(x24))\nt₀ = β₀ / se₀\nt₁ = β₁ / se₁\np₀ = 2*(ccdf(TDist(N-2),abs(t₀)))\np₁ = 2*(ccdf(TDist(N-2),abs(t₁)))\n@show β₀, β₁;\n@show t₀, t₁;\n@show p₀, p₁;\n\n# GLM.jlを使った場合でも同じ値が得られることが確認できます。\nusing GLM, DataFrames\ndata = DataFrame(X=x24,Y=y24)\nols = lm(@formula(Y ~ X), data)\n\n# ### 例25(問13に対応)\n# β̂₁/SE(β₁)を繰り返し推定してヒストグラムを作ります。 自由度N-2のt分布によく一致することが確認できます。 \nt25 = Vector{Real}(undef,1000)\nfor i in 1:1000\n x25 = randn(N); y25 = randn(N)\n t25[i],_ = collect(min_sq(x25,y25)) / Joe.RSE(x25,y25) ./ sqrt.(Joe.Bdiag(x25))\nend\np25_1 = histogram(t25,xlims=(-3,3),bins=20,normalize=true,xlabel=\"tの値\",legend=false)\ntitle!(\"帰無仮説が成立する場合\")\nplot!(p25_1,x->pdf(TDist(98),x));\n# 同じことをy=0.1x+ϵとしてデータをサンプリングしてみます。\nt25_ = Vector{Real}(undef,1000)\nfor i in 1:1000\n x25 = randn(N); y25 = 0.1*x25 .+ randn(N)\n t25_[i],_ = collect(min_sq(x25,y25)) / Joe.RSE(x25,y25) ./ sqrt.(Joe.Bdiag(x25))\nend\np25_2 = histogram(t25_,xlims=(-3,3),bins=20,normalize=true, xlabel=\"tの値\",legend=false)\ntitle!(\"帰無仮説が成立しない場合\")\nplot!(p25_2,x->pdf(TDist(98),x))\np25 = plot(p25_1,p25_2)\nsavefig(p25,joinpath(@OUTPUT,\"fig1-6.svg\")) # hide\n# \\fig{fig1-6}\n\n# ## 1.6 決定係数と共線形性の検出\n# $R^2 = 1 - \\dfrac{RSS}{TSS} = \\dfrac{ESS}{TSS}$にしたがって、次の関数を定義しておきます。\n# ```julia\n# function TSS(y)\n# Y = y .- mean(y)\n# return Y'*Y\n# end\n# \n# ESS(x,y) = TSS(y) - RSS(x,y)\n# \n# R2(x,y) = ESS(x,y)/TSS(y)\n# ```\n# ### 例26\n# 決定係数を計算してみます。\nN = 100; Random.seed!(123)\nx26_2 = randn(N,2); x26_1 = randn(N)\ny26 = randn(N)\n@show Joe.R2(x26_2,y26);\n# また、1変量なら相関係数の二乗になることを確認します。\n@show Joe.R2(x26_1,y26);\n@show cor(x26_1,y26)^2 ; # Statistics.jl\n\n# ### 例27 \n# VIFの計算は既存のパッケージになさそうです。\n# ```julia\n# function VIF(x)\n# _,ncol= size(x)\n# v = Vector{Float64}(undef, ncol) \n# for j in 1:ncol\n# index = setdiff(1:ncol,j)\n# v[j] = 1/(1-R2(x[:,index],x[:,j]))\n# end\n# return v\n# end\n# ```\nusing Joe, DataFrames\nusing ScikitLearn\n@sk_import datasets: load_boston\ndf = load_boston()\nx27 = df[\"data\"] # RDatasetsがGithub actions で使えなくなってた。\n#TabularDisplayを使って綺麗に表示する。\nusing TabularDisplay, Formatting\nfoo = generate_formatter(\"%7.5f\")\ndisplaytable(Joe.VIF(x27);index=true,indexsep=\" -> \",formatter=foo)\n# ## 1.7 信頼区間と予測区間\n# 定義にしたがって、信頼区間と予測区間の定義をします。危険率はデフォルトでは0.01としています。\n# ($x_{\\star}(X^TX)^{-1}x_{\\star}^T$ の計算に横着してdiagを使っているので、ちょっと勿体ないリソースの使い方をしている。)\n# ```julia\n# function confident_interval(xp,x,y;α=0.01)\n# N,p = size(x)\n# X = insert_ones(x)\n# XP = insert_ones(xp)\n# typeof(xp) <:Number && (xp =[xp])\n# yerror = quantile(TDist(N-p-1),1-α/2) * sqrt.(diag(XP * ((X'X) \\ XP')))\n# end\n# \n# function prediction_interval(xp,x,y;α=0.01)\n# N,p = size(x)\n# X = insert_ones(x)\n# XP = insert_ones(xp)\n# typeof(xp) <:Number && (xp =[xp])\n# yerror = quantile(TDist(N-p-1),1-α/2) * sqrt.( 1 .+ diag(XP * ((X'X) \\ XP')))\n# end\n# ```\n# ### 例28\nusing Plots, Random, Joe\nN = 100; Random.seed!(123)\nx28 = randn(N,1)\ny28 = x28 .+1 + randn(N) |> vec # 真の切片と傾きはともに1 \np28 = scatter(x28,y28,xlabel=\"x\",ylabel=\"y\",\n label=\"data \",legend=:topleft)\nβ28 = multiple_regression(x28,y28)\nx_seq = -10:0.1:10\nŷ = insert_ones(x_seq) * β28\nyerror1 = Joe.confident_interval(x_seq,x28,y28)\nyerror2 = Joe.prediction_interval(x_seq,x28,y28)\nplot!(p28,x_seq,ŷ,ribbon=yerror2, label=\"予測区間\")\nplot!(p28,x_seq,ŷ,ribbon=yerror1, label=\"信頼区間\")\n\nsavefig(p28,joinpath(@OUTPUT,\"fig1-7.svg\")) # hide\n# \\fig{fig1-7}\n\n", "meta": {"hexsha": "de61d828e4795ce4add3f15979256757ca260e90", "size": 7302, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/_literate/ex_chap1.jl", "max_stars_repo_name": "lethal8723/Joe.jl", "max_stars_repo_head_hexsha": "f30bf44f7e662ae58dded2ec675540b2996fe90a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/_literate/ex_chap1.jl", "max_issues_repo_name": "lethal8723/Joe.jl", "max_issues_repo_head_hexsha": "f30bf44f7e662ae58dded2ec675540b2996fe90a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/_literate/ex_chap1.jl", "max_forks_repo_name": "lethal8723/Joe.jl", "max_forks_repo_head_hexsha": "f30bf44f7e662ae58dded2ec675540b2996fe90a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1449814126, "max_line_length": 112, "alphanum_fraction": 0.6292796494, "num_tokens": 3635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.8902942261220292, "lm_q1q2_score": 0.8054051526358625}} {"text": "using LinearAlgebra\nusing Random\nusing Statistics\nusing DataFrames\nusing FreqTables\n\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\n# question 1\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\nusing Optim\nf(x) = -x[1]^4-10x[1]^3-2x[1]^2-3x[1]-2\nminusf(x) = x[1]^4+10x[1]^3+2x[1]^2+3x[1]+2\nstartval = rand(1) # random starting value\nresult = optimize(minusf, startval, BFGS())\n\n\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\n# question 2\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\nusing DataFrames\nusing CSV\nusing HTTP\nurl = \"https://raw.githubusercontent.com/OU-PhD-Econometrics/fall-2020/master/ProblemSets/PS1-julia-intro/nlsw88.csv\"\ndf = CSV.read(HTTP.get(url).body,DataFrame)\nX = [ones(size(df,1),1) df.age df.race.==1 df.collgrad.==1]\ny = df.married.==1\n\nfunction ols(beta, X, y)\n ssr = (y.-X*beta)'*(y.-X*beta)\n return ssr\nend\n\nbeta_hat_ols = optimize(b -> ols(b, X, y), rand(size(X,2)), LBFGS(), Optim.Options(g_tol=1e-6, iterations=100_000, show_trace=true))\nprintln(beta_hat_ols.minimizer)\n\nusing GLM\nbols = inv(X'*X)*X'*y\ndf.white = df.race.==1\nbols_lm = lm(@formula(married ~ age + white + collgrad), df)\n\n\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\n# question 3\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\nfunction logit(alpha, X, d)\n loglike = sum([d[i]*log(exp(sum(alpha.*X[i,:]))/(1+exp(sum(alpha.*X[i,:]))))+(1-d[i])*log(1/(1+exp(sum(alpha.*X[i,:])))) for i=1:size(X,1)])\n return loglike\nend\n\nstartval = rand(size(X,2))\nobj = optimize(alpha->-logit(alpha, X, y), startval, LBFGS())\nprintln(obj.minimizer)\n\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\n# question 4\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\n# see Lecture 3 slides for example\nres = glm(X, y, Binomial(), LogitLink())\nprintln(res)\n\n\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\n# question 5\n#:::::::::::::::::::::::::::::::::::::::::::::::::::\nfreqtable(df, :occupation) # note small number of obs in some occupations\ndf = dropmissing(df, :occupation)\ndf[df.occupation.==8 ,:occupation] .= 7\ndf[df.occupation.==9 ,:occupation] .= 7\ndf[df.occupation.==10,:occupation] .= 7\ndf[df.occupation.==11,:occupation] .= 7\ndf[df.occupation.==12,:occupation] .= 7\ndf[df.occupation.==13,:occupation] .= 7\nfreqtable(df, :occupation) # problem solved\n\nX = [ones(size(df,1),1) df.age df.race.==1 df.collgrad.==1]\ny = df.occupation\n\n\nfunction mlogit(alpha, X, d)\n loglike = 0\n for i = 1:size(X,1)\n term1 = sum([convert(Float64,d[i]==j)*sum(alpha[:,j].*X[i,:]) for j =1:6])\n term2 = log(1 + sum([exp(sum(alpha[:,j].*X[i,:])) for j =1:6]))\n loglike += term1 - term2\n end\n return loglike\nend\n\n\n#startval = zeros(size(X,2),6)\n#startval = rand(size(X,2),6)\nstartval = 2*rand(size(X,2),6).-1\nobj = optimize(alpha->-mlogit(alpha, X, y), startval, LBFGS(), Optim.Options(g_tol=1e-5, iterations=100000))\nprintln(obj.minimizer)\n", "meta": {"hexsha": "b17b4b1bc112914fc6a2973c48d339d1a7f38075", "size": 2902, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ProblemSets/PS2-optimization-intro/PS2_ping.jl", "max_stars_repo_name": "babymetal287/fall-2021", "max_stars_repo_head_hexsha": "804f7fec898a0fccd018c8bc5d520d8f9156d62a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ProblemSets/PS2-optimization-intro/PS2_ping.jl", "max_issues_repo_name": "babymetal287/fall-2021", "max_issues_repo_head_hexsha": "804f7fec898a0fccd018c8bc5d520d8f9156d62a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ProblemSets/PS2-optimization-intro/PS2_ping.jl", "max_forks_repo_name": "babymetal287/fall-2021", "max_forks_repo_head_hexsha": "804f7fec898a0fccd018c8bc5d520d8f9156d62a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5473684211, "max_line_length": 144, "alphanum_fraction": 0.5382494831, "num_tokens": 939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341999997378, "lm_q2_score": 0.8418256551882382, "lm_q1q2_score": 0.8053192121902553}} {"text": "\"\"\"\n dirichlet_beta()\n\n Calculates Dirichlet beta function,\n [https://en.wikipedia.org/wiki/Dirichlet_beta_function](https://en.wikipedia.org/wiki/Dirichlet_beta_function)\n \n## Arguments\n* ``s`` `::Number`: it should work for any type of number, but mainly tested for `Complex{Float64}`\n\n## Examples\n```jldoctest; setup = :(using Polylogarithms)\njulia> dirichlet_beta(1.5)\n0.8645026534612017\n```\n\"\"\"\nfunction dirichlet_beta(s::Number)\n β = 4.0^(-s) * ( SpecialFunctions.zeta(s,0.25) - SpecialFunctions.zeta(s,0.75) )\nend\n", "meta": {"hexsha": "cc59505ae430efe942eb738bf84f074d241afdaf", "size": 532, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/beta.jl", "max_stars_repo_name": "AshtonSBradley/Polylogarithms.jl", "max_stars_repo_head_hexsha": "f52e3075cd1d87b0d67d26c72cd1a79a365eddcd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-08-24T09:17:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-26T10:54:45.000Z", "max_issues_repo_path": "src/beta.jl", "max_issues_repo_name": "AshtonSBradley/Polylogarithms.jl", "max_issues_repo_head_hexsha": "f52e3075cd1d87b0d67d26c72cd1a79a365eddcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-11-18T00:06:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-18T10:35:43.000Z", "max_forks_repo_path": "src/beta.jl", "max_forks_repo_name": "AshtonSBradley/Polylogarithms.jl", "max_forks_repo_head_hexsha": "f52e3075cd1d87b0d67d26c72cd1a79a365eddcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-12-17T16:20:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-02T09:32:06.000Z", "avg_line_length": 28.0, "max_line_length": 115, "alphanum_fraction": 0.7105263158, "num_tokens": 162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9566341975270266, "lm_q2_score": 0.8418256472515684, "lm_q1q2_score": 0.805319202516174}} {"text": "using AdFem\nusing PyPlot\nusing SparseArrays\n\nfunction f1func(x,y)\n 18.8495559215388*pi^2*sin(pi*x)^2*sin(pi*y)*cos(pi*y) - 6.28318530717959*pi^2*sin(pi*y)*cos(pi*x)^2*cos(pi*y) + pi*sin(pi*y)*cos(pi*x)\nend\nfunction f2func(x,y)\n -18.8495559215388*pi^2*sin(pi*x)*sin(pi*y)^2*cos(pi*x) + 6.28318530717959*pi^2*sin(pi*x)*cos(pi*x)*cos(pi*y)^2 + pi*sin(pi*x)*cos(pi*y)\nend\n\n\nm = 50\nn = 50\nh = 1/n\nmmesh = Mesh(m, n, h, degree=2)\nν = 0.5\nK = ν*constant(compute_fem_laplace_matrix(mmesh))\nB = constant(compute_interaction_matrix(mmesh))\nZ = [K -B'\n -B spzero(size(B,1))]\n\nbd = bcnode(mmesh)\nbd = [bd; bd .+ mmesh.ndof; 2mmesh.ndof + 1]\n\nF1 = eval_f_on_gauss_pts(f1func, mmesh)\nF2 = eval_f_on_gauss_pts(f2func, mmesh)\nF = compute_fem_source_term(F1, F2, mmesh)\nrhs = [F;zeros(mmesh.nelem)]\nZ, rhs = impose_Dirichlet_boundary_conditions(Z, rhs, bd, zeros(length(bd)))\nsol = Z\\rhs \n\nsess = Session(); init(sess)\nS = run(sess, sol)\n\nxy = fem_nodes(mmesh)\nx, y = xy[:,1], xy[:,2]\nU = @. 2*pi*sin(pi*x)*sin(pi*x)*cos(pi*y)*sin(pi*y)\nfigure(figsize=(12,5))\nsubplot(121)\nvisualize_scalar_on_fem_points(U, mmesh)\ntitle(\"Reference\")\nsubplot(122)\nvisualize_scalar_on_fem_points(S[1:mmesh.nnode], mmesh)\ntitle(\"Computed\")\nsavefig(\"stokes1.png\")\n\nU = @. -2*pi*sin(pi*x)*sin(pi*y)*cos(pi*x)*sin(pi*y)\nfigure(figsize=(12,5))\nsubplot(121)\nvisualize_scalar_on_fem_points(U, mmesh)\ntitle(\"Reference\")\nsubplot(122)\nvisualize_scalar_on_fem_points(S[mmesh.ndof+1:mmesh.ndof+mmesh.nnode], mmesh)\ntitle(\"Computed\")\nsavefig(\"stokes2.png\")\n\n\nxy = fvm_nodes(mmesh)\nx, y = xy[:,1], xy[:,2]\np = @. sin(pi*x)*sin(pi*y)\nfigure(figsize=(12,5))\nsubplot(121)\nvisualize_scalar_on_fvm_points(p, mmesh)\ntitle(\"Reference\")\nsubplot(122)\nvisualize_scalar_on_fvm_points(S[2mmesh.ndof+1:end], mmesh)\ntitle(\"Computed\")\nsavefig(\"stokes3.png\")", "meta": {"hexsha": "6aad2184b5cb213efd3bac893dc6776c1516523b", "size": 1801, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/codes/Stokes/unstructured_forward.jl", "max_stars_repo_name": "kailaix/AdFem.jl", "max_stars_repo_head_hexsha": "77eabfeedb297570a42d1f26575c59f0712796d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 47, "max_stars_repo_stars_event_min_datetime": "2020-10-18T01:33:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T00:13:24.000Z", "max_issues_repo_path": "docs/src/codes/Stokes/unstructured_forward.jl", "max_issues_repo_name": "kailaix/AdFem.jl", "max_issues_repo_head_hexsha": "77eabfeedb297570a42d1f26575c59f0712796d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2020-10-19T03:51:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T23:38:46.000Z", "max_forks_repo_path": "docs/src/codes/Stokes/unstructured_forward.jl", "max_forks_repo_name": "kailaix/AdFem.jl", "max_forks_repo_head_hexsha": "77eabfeedb297570a42d1f26575c59f0712796d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2020-11-05T11:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T19:30:09.000Z", "avg_line_length": 26.1014492754, "max_line_length": 139, "alphanum_fraction": 0.6985008329, "num_tokens": 656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.949669373100424, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.805289007683694}} {"text": "function acqr_kfilter(y,a,c,q,r,x10,P10)\r\n\t#\r\n\t# Kalman filter for model\r\n\t#\r\n\t# x_{t+1} = a*x_{t} + w_{t}\r\n\t# y_{t} = c*x_{t} + v_{t}\r\n\t#\r\n\t# cov(w_{t},v_{t}) = [q 0;0 r]\r\n\t#\r\n\t# javier.cara@upm.es, 2020-05\r\n\t#\r\n\r\n\tnt = length(y)\r\n\r\n\t# allocation\r\n\txtt = zeros(nt)\r\n\tPtt = zeros(nt)\r\n\txtt1 = zeros(nt+1)\r\n\tPtt1 = zeros(nt+1)\r\n\tet = zeros(nt)\r\n\tSt = zeros(nt)\r\n\tKt = zeros(nt)\r\n\tloglik = 0.0\r\n\r\n\t# Filter\r\n\txtt1[1] = x10\r\n\tPtt1[1] = P10\r\n\tfor t in 1:nt\r\n\t\t# innovations\r\n\t\tet[t] = y[t] - c*xtt1[t]\r\n\t\tSt[t] = c^2*Ptt1[t] + r # et variance\r\n\r\n\t\t# Kalman gain\r\n\t\tKt[t] = Ptt1[t]*c/St[t] # kalman gain\r\n\r\n\t\t# filtered values\r\n\t\txtt[t] = xtt1[t] + Kt[t]*et[t]\r\n\t\tPtt[t] = (1 - Kt[t]*c)*Ptt1[t]\r\n\r\n\t\t# one-step ahead prediction\r\n\t\txtt1[t+1] = a*xtt[t]\r\n\t\tPtt1[t+1] = a^2*Ptt[t] + q\r\n\r\n\t\t# likelihood\r\n\t\t#l0 = et[t]^2/St[t] # typeof(l0) = Array{Float64,1}\r\n\t\tloglik = loglik + log(St[t]) + et[t]^2/St[t]\r\n\tend\r\n\r\n\tloglik = - nt/2*log(2*pi) - 0.5*loglik\r\n\r\n\treturn xtt,Ptt,xtt1,Ptt1,et,St,Kt,loglik\r\n\r\nend\r\n", "meta": {"hexsha": "485081112d08d5fd3a9a1c47dc61dd1c95f50bd5", "size": 1004, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/acqr/acqr_kfilter.jl", "max_stars_repo_name": "javiercara/StateSpaceModelsEM.jl", "max_stars_repo_head_hexsha": "989d538b01274885e4579df130f9b38bbb99cc7d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/acqr/acqr_kfilter.jl", "max_issues_repo_name": "javiercara/StateSpaceModelsEM.jl", "max_issues_repo_head_hexsha": "989d538b01274885e4579df130f9b38bbb99cc7d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/acqr/acqr_kfilter.jl", "max_forks_repo_name": "javiercara/StateSpaceModelsEM.jl", "max_forks_repo_head_hexsha": "989d538b01274885e4579df130f9b38bbb99cc7d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.5925925926, "max_line_length": 54, "alphanum_fraction": 0.5229083665, "num_tokens": 468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810525948927, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.8052465906702162}} {"text": "# # Maximum Cut Problem\n#\n# We are interested in solving an approximation to the maximum cut problem using semidefinite programming.\n# Consider the graph $G(V,E)$ with weights $w_{ij}$ shown below:\n\n## create the weighted adjacency matrix of the graph and plot the graph\nusing LinearAlgebra, Plots, GraphRecipes\nn = 4;\nW = zeros(n, n);\nW[1, 2] = 1; W[1, 4] = 8;\nW[2, 3] = 2; W[2, 4] = 10;\nW[3, 4] = 6;\nW = Symmetric(W)\ngraphplot(W, names = 1:n, edgelabel = W, x = [0; 1; 1; 0], y = [1; 1; 0; 0], fontsize = 12, nodeshape =:circle)\n\n# The maximum cut problem tries to find a cut or a partition of the graph's vertices into two complementary sets $S$ and $\\bar{S}$ such that the total weight of the edges between the two sets is maximized. For this small graph the problem is trivial. The optimal solution is $S = \\{1,2,3 \\}$ and $\\bar{S}=\\{4\\}$.\n# Formally, this problem can be written as a mixed-integer optimisation problem:\n# $$\n# \\begin{array}{ll} \\text{maximize} & \\frac{1}{2} \\sum_{i < j} w_{ij}(1 - y_i y_j)\\\\\n# \\text{subject to} & y_i \\in \\, \\{-1, 1 \\}, \\quad \\forall i \\in V,\n# \\end{array}\n# $$\n# where $y_i = 1$ indicates that $v_i \\in S$ and $y_i = -1$ indicates that $v_i \\in \\bar{S}$. This problem is of interest in the field of integrated circuit design, where one tries to minimize the number of cross-layer connections in a circuit under layout constraints.\n\n# For more complicated graphs this problem quickly becomes hard to solve to optimality and in fact is known to be NP-hard. For this example we are interested in the randomized approximation algorithm that relaxes the problem to an SDP and was devised in Goemans and Williamson (1995) \\[1\\] (see for more details).\n\n# The approach can be divided into three steps:\n# 1. Solve a relaxed SDP to obtain $Y^*$\n# 2. Recover an approximate solution $V$ via a Cholesky factorisation $Y^* = V^\\top V$\n# 3. Round the approximate solution using a random vector $r$ from the unit sphere.\n# The authors showed that this approach guarantees a solution of at least $0.87856$ times the optimal solution.\n\n# ## Solving the primal SDP\n# Before we formulate the SDP, let's compute the Laplacian matrix $L$:\nusing LinearAlgebra, Random, SparseArrays, COSMO, JuMP\n\nrng = Random.MersenneTwister(1)\n\n## Compute the Laplacian matrix of the graph\nL = diagm(0 => W * ones(n)) - W;\n\n# Given the Laplacian matrix $L$, we are looking for the optimal $Y^*$ that solves the following SDP:\n# $$\n# \\begin{array}{ll} \\text{maximize} & \\frac{1}{4} \\langle L, Y \\rangle \\\\\n# \\text{subject to} & Y_{ii} = 1 \\quad \\text{for } i = 1,\\dots,n\\\\\n# & Y \\in \\mathbf{S}_{+}^n.\n# \\end{array}\n# $$\n# Notice that the solution $Y^*$ can be viewed as a correlation matrix. Let's solve the problem using COSMO and JuMP.\n\n#-\nmodel = JuMP.Model(COSMO.Optimizer);\n@variable(model, Y[1:n, 1:n], PSD);\n@objective(model, Max, 1 / 4 * dot(L, Y));\n@constraint(model, [i = 1:n], Y[i, i] == 1.);\nJuMP.optimize!(model)\n\n#-\nYopt = JuMP.value.(Y);\nobj_val = JuMP.objective_value(model)\n\n# ## Solving the dual SDP\n# Notice that the decision matrix $Y$ is generally dense (as correctly classified in the solver output above). Therefore, we won't be able to utilize COSMO's chordal decomposition features. However, assuming strong duality, it turns out that we can also solve the dual problem, which is given by:\n# $$\n# \\begin{array}{ll} \\text{minimize} & \\sum_i \\gamma_i \\\\\n# \\text{subject to} & \\text{diag}(\\gamma) - \\frac{1}{4} L = S \\\\\n# & S \\in \\mathbf{S}_{+}^n.\n# \\end{array}\n# $$\n# As you can see, the matrix $S$ is constrained to have zeros in places specified by the graph (Laplacian). Therefore, COSMO can try to decompose this SDP (see solver output) and speed up its algorithm:\n\n#-\nmodel_dual = JuMP.Model(optimizer_with_attributes(COSMO.Optimizer, \"complete_dual\" => true));\n@variable(model_dual, γ[1:n]);\n@objective(model_dual, Min, sum(γ));\n@constraint(model_dual, lmi, Symmetric(-1/4 * L + diagm(γ)) in JuMP.PSDCone());\nJuMP.optimize!(model_dual)\nobj_val = JuMP.objective_value(model_dual)\n\n# The primal variable $Y^*$ can be recovered from the dual variable associated with the LMI-constraint:\n#-\nYopt = dual(lmi)\n# To get the correct positive semidefinite dual variable, we have to enable PSD completion of the dual variable in COSMO. Now, that we have a solution we can perform the remaining steps in the approximation algorithm.\n\n# ## Cholesky factorisation of Y\n# Compute the Cholesky factorisation of $Y = V^\\top V$ to find the unit vectors $v_1, \\dots, v_n$.\n\n#-\nfactor = cholesky(Yopt, Val(true); check = false);\nV = Matrix((factor.P * factor.L)');\n## normalize columns\nfor i in 1:n\n V[:, i] ./= norm(V[:, i]);\nend\n\n# ## Rounding the approximate solution\n# It remains to round the unit vectors $v_i$ using a random vector $r$ with each component drawn from $\\mathcal{U}(0, 1)$, to obtain the $y_i$'s:\n\n#-\nr = rand(rng, n)\nr /= norm(r, 2)\ny = ones(n)\nfor i in 1:n\n dot(r, V[:, i]) <= 0 && (y[i] = -1)\nend\ny\n# For larger graphs this rounding step could be repeated several times to improve the rounding.\n# As expected $S = \\{1, 2, 3\\}$ and $\\bar{S}=\\{ 4\\}$.\n# ## References\n# [1] Goemans and Williamson - Improved Approximation Algorithms for Maximum Cut and Satisfiability Problems Using Semidefinite Programs (1995)\n\n# [2] Post-processing code steps 2 and 3 from this [JuMP example](https://github.com/jump-dev/JuMP.jl/blob/master/examples/max_cut_sdp.jl)\n", "meta": {"hexsha": "1d5b0f48d2a7505d6b223b8f1bc65244a3347751", "size": 5433, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/maxcut.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/maxcut.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/maxcut.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": 48.0796460177, "max_line_length": 313, "alphanum_fraction": 0.6924351187, "num_tokens": 1648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039738, "lm_q2_score": 0.8723473796562745, "lm_q1q2_score": 0.805210796300689}} {"text": "\nf(u,p,t) = 0.98u\n\n\nusing DifferentialEquations\nf(u,p,t) = 0.98u\nu0 = 1.0\ntspan = (0.0,1.0)\nprob = ODEProblem(f,u0,tspan)\n\n\nsol = solve(prob)\n\n\nusing Plots; gr()\nplot(sol)\n\n\nplot(sol,linewidth=5,title=\"Solution to the linear ODE with a thick line\",\n xaxis=\"Time (t)\",yaxis=\"u(t) (in μm)\",label=\"My Thick Line!\") # legend=false\n\n\nplot!(sol.t, t->1.0*exp(0.98t),lw=3,ls=:dash,label=\"True Solution!\")\n\n\nsol.t\n\n\nsol.u\n\n\n[t+u for (u,t) in tuples(sol)]\n\n\nsol\n\n\nsol(0.45)\n\n\nsol = solve(prob,abstol=1e-8,reltol=1e-8)\n\n\nplot(sol)\nplot!(sol.t, t->1.0*exp(0.98t),lw=3,ls=:dash,label=\"True Solution!\")\n\n\nsol = solve(prob,saveat=0.1)\n\n\nsol = solve(prob,saveat=[0.2,0.7,0.9])\n\n\nsol = solve(prob,dense=false)\n\n\nsol = solve(prob,save_everystep=false)\n\n\nsol = solve(prob,save_everystep=false,save_start = false)\n\n\nsol = solve(prob,alg_hints=[:stiff])\n\n\nsol = solve(prob,Tsit5(),reltol=1e-6)\n\n\nfunction lorenz!(du,u,p,t)\n σ,ρ,β = p\n du[1] = σ*(u[2]-u[1])\n du[2] = u[1]*(ρ-u[3]) - u[2]\n du[3] = u[1]*u[2] - β*u[3]\nend\n\n\nu0 = [1.0,0.0,0.0]\n\n\np = (10,28,8/3) # we could also make this an array, or any other type!\n\n\ntspan = (0.0,100.0)\nprob = ODEProblem(lorenz!,u0,tspan,p)\n\n\nsol = solve(prob)\n\n\nsol.t[10],sol[10]\n\n\nsol[2,10]\n\n\nA = Array(sol)\n\n\nplot(sol)\n\n\nplot(sol,vars=(1,2,3))\n\n\nplot(sol,vars=(1,2,3),denseplot=false)\n\n\nplot(sol,vars=(0,2))\n\n\nfunction lotka_volterra!(du,u,p,t)\n du[1] = p[1]*u[1] - p[2]*u[1]*u[2]\n du[2] = -p[3]*u[2] + p[4]*u[1]*u[2]\nend\n\n\nusing ParameterizedFunctions\nlv! = @ode_def LotkaVolterra begin\n dx = a*x - b*x*y\n dy = -c*y + d*x*y\nend a b c d\n\n\nu0 = [1.0,1.0]\np = (1.5,1.0,3.0,1.0)\ntspan = (0.0,10.0)\nprob = ODEProblem(lv!,u0,tspan,p)\nsol = solve(prob)\nplot(sol)\n\n\nlv!.Jex\n\n\nA = [1. 0 0 -5\n 4 -2 4 -3\n -4 0 0 1\n 5 -2 2 3]\nu0 = rand(4,2)\ntspan = (0.0,1.0)\nf(u,p,t) = A*u\nprob = ODEProblem(f,u0,tspan)\nsol = solve(prob)\n\n\nsol[3]\n\n\nbig_u0 = big.(u0)\n\n\nprob = ODEProblem(f,big_u0,tspan)\nsol = solve(prob)\n\n\nsol[1,3]\n\n\nprob = ODEProblem(f,big_u0,big.(tspan))\nsol = solve(prob)\n\n\nusing StaticArrays\nA = @SMatrix [ 1.0 0.0 0.0 -5.0\n 4.0 -2.0 4.0 -3.0\n -4.0 0.0 0.0 1.0\n 5.0 -2.0 2.0 3.0]\nu0 = @SMatrix rand(4,2)\ntspan = (0.0,1.0)\nf(u,p,t) = A*u\nprob = ODEProblem(f,u0,tspan)\nsol = solve(prob)\n\n\nsol[3]\n\n\nusing DiffEqTutorials\nDiffEqTutorials.tutorial_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])\n\n", "meta": {"hexsha": "680225322a33d9454a5819cb54761dba92b1f3d2", "size": 2391, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/introduction/ode_introduction.jl", "max_stars_repo_name": "KZiemian/DiffEqTutorials.jl", "max_stars_repo_head_hexsha": "97c2bce7039bd976522f06d7e1c9900bb63c2aff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-22T12:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-22T12:30:52.000Z", "max_issues_repo_path": "script/introduction/ode_introduction.jl", "max_issues_repo_name": "KZiemian/DiffEqTutorials.jl", "max_issues_repo_head_hexsha": "97c2bce7039bd976522f06d7e1c9900bb63c2aff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/introduction/ode_introduction.jl", "max_forks_repo_name": "KZiemian/DiffEqTutorials.jl", "max_forks_repo_head_hexsha": "97c2bce7039bd976522f06d7e1c9900bb63c2aff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.2099447514, "max_line_length": 81, "alphanum_fraction": 0.5851108323, "num_tokens": 1044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.9230391605990604, "lm_q1q2_score": 0.8052107884737684}} {"text": "function romberg(f::Function, a::Number, b::Number, nl::Int)\n #= Numerical Integration of functions using Romberg's method.\n Keyword arguments:\n f -- Anonymous functon to integrate\n a -- Lower limit of integration\n b -- Upper limit of integration\n nl -- The level of integration to go to.\n\n Returns:\n The result of the integration of f between a & b\n =#\n\n intTable = zeros(nl, nl); # Empty matrix to use as div diff table\n\n # Calculate the first column of the div diff table using the trapezium rule.\n h = (b - a);\n for k = 1:nl\n intTable[k,1] = 0.5 * h * (f(a) + 2*sum(f([a+h:h:b-h])) + f(b));\n h /= 2;\n end\n\n # Calculate the remaining elements using Romberg's method.\n for k = 2:nl, j = nl-k+1:-1:1\n intTable[j, k] = ((4^(k-1))intTable[j+1, k-1] - intTable[j, k-1])/((4^(k-1)) - 1); \n end\n\n return intTable[1, end];\nend\n\nfunction romberg(intEstimates::Array{Float64,1})\n #= Estiamte integrals from sets of data using the Romberg Method.\n\n Keyword arguments:\n intEstimates -- An array of initial estimates of integrals\n\n Returns:\n A tuple containing the integral and the relative error in the estimate \n =# \n intTable = zeros(length(intEstimates), length(intEstimates));\n relativeErrorTable = zeros(size(intEstimates));\n\n intTable[:, 1] = intEstimates;\n\n for k = 2:size(intTable)[1]\n for j = size(intTable)[1]-k+1:-1:1\n intTable[j, k] = ((4^(k-1))intTable[j+1, k-1] - intTable[j, k-1])/((4^(k-1)) - 1);\n end\n end\n\n for k = 2:size(intTable)[1]\n relativeErrorTable[k, 1] = 100 * abs((intTable[1, k] - intTable[2, k-1]) / intTable[1, k]);\n end\n\n return (intTable[1, end], relativeErrorTable[1, end]);\nend\n", "meta": {"hexsha": "4d7aa873a9cc98da33b19106ca477ded9b088bef", "size": 1663, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/Integration/romberg.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/romberg.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/romberg.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.6964285714, "max_line_length": 95, "alphanum_fraction": 0.644016837, "num_tokens": 550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897525789548, "lm_q2_score": 0.855851154320682, "lm_q1q2_score": 0.8051759957177673}} {"text": "using CompScienceMeshes\nusing SauterSchwabQuadrature\n\n\n\npI = point(1,5,3)\npII = point(2,5,3)\npIII = point(7,1,0)\npIV = point(5,1,-3)\n\nSourcechart = simplex(pII,pI,pIII)\nTestchart = simplex(pII,pI,pIV)\n\nAccuracy = 12\n\n\n\n\nfunction integrand(x,y)\n\t\t\treturn(((x-pI)'*(y-pII))*exp(-im*1*norm(x-y))/(4pi*norm(x-y)))\nend\n\n\n\n\n\n\nresult = sauterschwabintegral(Sourcechart, Testchart, integrand, Accuracy, Accuracy)\nprintln(result)\n\n#=For those who want to test the sauterschwab_nonparameterized() function,\nmay uncomment the following five lines=#\n\n#sourcechart = simplex(pI,pIII,pII)\n#testchart = simplex(pI,pIV,pII)\n#ce = CommonEdge(Accuracy)\n#result2 = sauterschwab_nonparameterized(sourcechart, testchart, integrand, ce)\n#println(result2)\n\n#=The first argument and the third argument of both simplex() functions are\nequal, hence the required conditions are fulfilled. The user may also compare\nthe two results, and see that both are equal=#\n", "meta": {"hexsha": "500acd68edb7d8b04141ebeaf568ef6936289f88", "size": 935, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/common_edge_non_parameterized.jl", "max_stars_repo_name": "UnofficialJuliaMirror/SauterSchwabQuadrature.jl-535c7bfe-2023-5c1d-b712-654ef9d93a38", "max_stars_repo_head_hexsha": "419fb564912814b5e033df52e255db707349b600", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-12-23T16:54:33.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-23T16:54:33.000Z", "max_issues_repo_path": "examples/common_edge_non_parameterized.jl", "max_issues_repo_name": "UnofficialJuliaMirror/SauterSchwabQuadrature.jl-535c7bfe-2023-5c1d-b712-654ef9d93a38", "max_issues_repo_head_hexsha": "419fb564912814b5e033df52e255db707349b600", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-07-23T12:35:34.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-23T12:44:53.000Z", "max_forks_repo_path": "examples/common_edge_non_parameterized.jl", "max_forks_repo_name": "UnofficialJuliaMirror/SauterSchwabQuadrature.jl-535c7bfe-2023-5c1d-b712-654ef9d93a38", "max_forks_repo_head_hexsha": "419fb564912814b5e033df52e255db707349b600", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2017-10-31T14:02:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-25T06:47:26.000Z", "avg_line_length": 21.7441860465, "max_line_length": 84, "alphanum_fraction": 0.7475935829, "num_tokens": 276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897442783527, "lm_q2_score": 0.8558511506439708, "lm_q1q2_score": 0.8051759851546751}} {"text": "export Strang\n\"\"\"\n`Strang` matrix\n\nA special `SymTridiagonal` matrix named after Gilbert Strang\n\n```julia\njulia> Strang(6)\n6x6 Strang{Float64}:\n 2.0 -1.0 0.0 0.0 0.0 0.0\n -1.0 2.0 -1.0 0.0 0.0 0.0\n 0.0 -1.0 2.0 -1.0 0.0 0.0\n 0.0 0.0 -1.0 2.0 -1.0 0.0\n 0.0 0.0 0.0 -1.0 2.0 -1.0\n 0.0 0.0 0.0 0.0 -1.0 2.0\n```\n\"\"\"\nstruct Strang{T} <: AbstractArray{T, 2}\n n :: Int\nend\nStrang(n::Int) = Strang{Float64}(n)\nstrang(T, n)= n >1 ? SymTridiagonal(2ones(T, n),-ones(T, n-1)) :\n n==1 ? Diagonal([2one(T)]) : error(\"Invalid dimension \", n)\nfunction getindex(S::Strang{T}, i, j) where T\n i == j && return 2\n abs(i - j) == 1 && return -1\n 0\nend\ngetindex(S::Strang{T}, I...) where T = getindex(S,ind2sub(size(S),I...)...)\nsize(S::Strang, r::Int) = r==1 || r==2 ? S.n : throw(ArgumentError(\"Invalid dimension $r\"))\nsize(S::Strang) = S.n, S.n\nMatrix(S::Strang{T}) where T = Matrix(strang(T, S.n))\n*(A::VecOrMat{T}, S::Strang{T}) where T = A*Matrix(S)\n*(S::Strang{T}, A::VecOrMat{T}) where T = Matrix(S)*A\n", "meta": {"hexsha": "5c9bf651cfb366dc40efc9563f0b9a9d7f9cf991", "size": 1069, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/strang.jl", "max_stars_repo_name": "JuliaMath/SpecialMatrices.jl", "max_stars_repo_head_hexsha": "05cb35883d25495aec69d6fb8bc7d40460ddcdb8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2018-09-13T10:26:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T23:21:37.000Z", "max_issues_repo_path": "src/strang.jl", "max_issues_repo_name": "JuliaMath/SpecialMatrices.jl", "max_issues_repo_head_hexsha": "05cb35883d25495aec69d6fb8bc7d40460ddcdb8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 36, "max_issues_repo_issues_event_min_datetime": "2017-08-17T17:39:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-31T18:27:05.000Z", "max_forks_repo_path": "src/strang.jl", "max_forks_repo_name": "JuliaMath/SpecialMatrices.jl", "max_forks_repo_head_hexsha": "05cb35883d25495aec69d6fb8bc7d40460ddcdb8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2017-08-17T16:49:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-21T10:22:09.000Z", "avg_line_length": 30.5428571429, "max_line_length": 91, "alphanum_fraction": 0.549111319, "num_tokens": 499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.8824278649085117, "lm_q1q2_score": 0.8051590887526917}} {"text": "# Summary statistics\n\n\"\"\"\n genvar(X)\n\nCompute the generalized sample variance of `X`. If `X` is a vector, one-column matrix,\nor other one-dimensional iterable, this is equivalent to the sample variance.\nOtherwise if `X` is a matrix, this is equivalent to the determinant of the covariance\nmatrix of `X`.\n\n!!! note\n The generalized sample variance will be 0 if the columns of the matrix of deviations\n are linearly dependent.\n\"\"\"\ngenvar(X::AbstractMatrix) = size(X, 2) == 1 ? var(vec(X)) : det(cov(X))\ngenvar(itr) = var(itr)\n\n\"\"\"\n totalvar(X)\n\nCompute the total sample variance of `X`. If `X` is a vector, one-column matrix,\nor other one-dimensional iterable, this is equivalent to the sample variance.\nOtherwise if `X` is a matrix, this is equivalent to the sum of the diagonal elements\nof the covariance matrix of `X`.\n\"\"\"\ntotalvar(X::AbstractMatrix) = sum(var(X, 1))\ntotalvar(itr) = var(itr)\n", "meta": {"hexsha": "934f33caef05680545a08b8345557e7ad2070e7b", "size": 906, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/dispersion.jl", "max_stars_repo_name": "ararslan/MultivariateTests.jl", "max_stars_repo_head_hexsha": "5456795ebfb1eafb4f8d12202264a53a25d62c1d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/dispersion.jl", "max_issues_repo_name": "ararslan/MultivariateTests.jl", "max_issues_repo_head_hexsha": "5456795ebfb1eafb4f8d12202264a53a25d62c1d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dispersion.jl", "max_forks_repo_name": "ararslan/MultivariateTests.jl", "max_forks_repo_head_hexsha": "5456795ebfb1eafb4f8d12202264a53a25d62c1d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3571428571, "max_line_length": 88, "alphanum_fraction": 0.7185430464, "num_tokens": 226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947101574299, "lm_q2_score": 0.851952809486198, "lm_q1q2_score": 0.8050908982682178}} {"text": "module EllipsoidAlgebra\n\nusing Plots, LinearAlgebra\n\n\"\"\"\nE(x, P) = { z : (z-x) P ( z-x) <= 1\n\"\"\"\nstruct Ellipsoid{Tx, TP} \n x0::Tx\n P::TP\nend\n\nEllipsoid(x0, P, V) = Ellipsoid(x0, P/V)\n\nfunction plotEllipse!(e::Ellipsoid; kwargs...)\n\n @assert length(e.x0) == 2\n \n Pinv_half = real.(sqrt(inv(e.P)))\n \n x(θ) = e.x0[1] + first(Pinv_half * [cos(θ), sin(θ)])\n y(θ) = e.x0[2] + last(Pinv_half * [cos(θ), sin(θ)])\n \n plot!(x, y, 0, 2π; kwargs...)\n \nend\n\nfunction project(e::Ellipsoid, dims=[1,2])\n\n N = length(e.x0)\n Pinv_half = sqrt(inv(e.P))\n \n # construct projection matrix\n T = zeros(2, N)\n T[1,dims[1]] = 1\n T[2, dims[2]] = 1\n \n # get new shape matrix\n TPinvhalf = T * Pinv_half\n PPinv = TPinvhalf * TPinvhalf'\n Pp = real.(inv(PPinv))\n\n # get new center\n xp0 = T * e.x0\n \n\n return Ellipsoid(xp0, Pp)\n\nend\n\n\n\nfunction sampleRand(e::Ellipsoid, N=1)\n \n @assert isposdef(e.P)\n\n Pinv_half = sqrt(inv(e.P))\n \n # sample random from unit sphere, and map to ellipsoid\n y = 2*rand(length(e.x0), N) .- 1\n for i=1:N\n while norm(y[:,i]) > 1.0\n y[:,i] = 2*rand(length(e.x0), 1) .- 1\n end\n\n end\n \n xs = similar(y)\n for i=1:N\n xs[:,i] = e.x0 + Pinv_half * y[:,i]\n end\n \n return xs\nend\n\n\nfunction creategrid(d::Integer, n::Integer)\n\n @assert d >= 1 (\"d (number of dimensions) must be a positive integer\")\n @assert n >= 2 (\"n (number of points) must be a at least 2\")\n\n r = range(-1, 1, length = n)\n\n iter = Iterators.product((r for _ in 1:d)...)\n\n return vec([collect(i) for i in iter if dot(i, i) <= 1])\nend\n\nconst sphere_6_grid = creategrid(6, 5)\n\nfunction sampleUniformGrid(e::Ellipsoid, n=5)\n N = length(e.x0)\n Pinv_half = sqrt(inv(e.P))\n if N == 6\n pts = [e.x0 + Pinv_half * i for i in sphere_6_grid]\n return pts\n else\n pts = [e.x0 + Pinv_half * i for i in creategrid(N, n)]\n return pts\n end\nend\n\nend", "meta": {"hexsha": "b0ee8290e79b83aa07d353aefb67edccd3b478ab", "size": 2000, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/EllipsoidAlgebra.jl", "max_stars_repo_name": "dev10110/robust-safe-observer-controllers", "max_stars_repo_head_hexsha": "04009aa1c53ae147c7031537b329fbbaa681688a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/EllipsoidAlgebra.jl", "max_issues_repo_name": "dev10110/robust-safe-observer-controllers", "max_issues_repo_head_hexsha": "04009aa1c53ae147c7031537b329fbbaa681688a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/EllipsoidAlgebra.jl", "max_forks_repo_name": "dev10110/robust-safe-observer-controllers", "max_forks_repo_head_hexsha": "04009aa1c53ae147c7031537b329fbbaa681688a", "max_forks_repo_licenses": ["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.4174757282, "max_line_length": 74, "alphanum_fraction": 0.5475, "num_tokens": 704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947163538935, "lm_q2_score": 0.8519528038477824, "lm_q1q2_score": 0.8050908982190395}} {"text": "@doc raw\"\"\"\n MaternKernel([ν=1 [,θ=1]])\n\nThe Matern kernel is a Mercer kernel given by:\n\n```math\n\\kappa(\\mathbf{x},\\mathbf{y}) = \n\\frac{1}{2^{\\nu-1}\\Gamma(\\nu)} \n\\left(\\frac{2\\sqrt{\\nu}||\\mathbf{x}-\\mathbf{y}||}{\\theta}\\right)^{\\nu} \nK_{\\nu}\\left(\\frac{2\\sqrt{\\nu}||\\mathbf{x}-\\mathbf{y}||}{\\theta}\\right)\n```\n\nwhere ``\\Gamma`` is the gamma function, ``K_{\\nu}`` is the modified Bessel function of the \nsecond kind, ``\\nu > 0`` and ``\\theta > 0``.\n\"\"\"\nstruct MaternKernel{T<:AbstractFloat} <: MercerKernel{T}\n nu::HyperParameter{T}\n rho::HyperParameter{T}\n MaternKernel{T}(ν::Real, ρ::Real) where {T<:AbstractFloat} = new{T}(\n HyperParameter(convert(T,ν), interval(OpenBound(zero(T)), nothing)),\n HyperParameter(convert(T,ρ), interval(OpenBound(zero(T)), nothing))\n )\nend\nfunction MaternKernel(ν::T1=1.0, ρ::T2=one(T1)) where {T1<:Real,T2<:Real}\n MaternKernel{floattype(T1,T2)}(ν,ρ)\nend\n\n@inline function maternkernel(z::T, ν::T, ρ::T) where {T}\n v1 = sqrt(2ν) * z / ρ\n v1 = v1 < eps(T) ? eps(T) : v1 # Overflow risk as z -> Inf\n 2 * (v1/2)^(ν) * besselk(ν, v1) / gamma(ν)\nend\n\n@inline basefunction(::MaternKernel) = SquaredEuclidean()\n@inline function kappa(κ::MaternKernel{T}, z::T) where {T}\n maternkernel(z, getvalue(κ.nu), getvalue(κ.rho))\nend", "meta": {"hexsha": "11cb40757b4e4ca3fb769edae4206c34fe354f7e", "size": 1294, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernelfunctions/mercer/matern.jl", "max_stars_repo_name": "holtri/MLKernels.jl", "max_stars_repo_head_hexsha": "d7b84b1bd7b9d9ca4cb7c413d0e34b04c09a331c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernelfunctions/mercer/matern.jl", "max_issues_repo_name": "holtri/MLKernels.jl", "max_issues_repo_head_hexsha": "d7b84b1bd7b9d9ca4cb7c413d0e34b04c09a331c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernelfunctions/mercer/matern.jl", "max_forks_repo_name": "holtri/MLKernels.jl", "max_forks_repo_head_hexsha": "d7b84b1bd7b9d9ca4cb7c413d0e34b04c09a331c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.972972973, "max_line_length": 91, "alphanum_fraction": 0.6267387944, "num_tokens": 484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947117065458, "lm_q2_score": 0.8519528038477824, "lm_q1q2_score": 0.8050908942597185}} {"text": "\nusing PyPlot\nusing Optim\n\nfunction get_ln_delta(N, d_VC, epsilon)\n return log(4) + d_VC * log(2N) -(epsilon^2)*N/8\nend;\n\nd_VC = 10;\nepsilon = 0.05;\nN_arr = [400000. 420000. 440000. 460000. 480000.];\nfor N in N_arr\n delta = exp(get_ln_delta(N, d_VC, epsilon));\n println(\"N = $N, delta = $delta\")\nend\n\nfunction get_error(N, d_VC, epsilon, target_delta)\n delta = exp(get_ln_delta(N, d_VC, epsilon));\n return (delta - target_delta)^2;\nend;\n\nresult = optimize(N -> get_error(N, 10, 0.05, 0.05), 400000, 500000)\n\nN = result.minimum;\nerr = result.f_minimum;\nif result.converged == true\n println(\"Solution: N = $N (error = $err)\")\nend\n\nfunction get_vc_bound(N,d_VC,delta)\n inner = log(4) + d_VC * log(2N) - log(delta);\n return sqrt(8inner/N);\nend;\n\nfunction get_rademacher_penalty(N,d_VC,delta)\n inner = 2(log(2N) + d_VC * log(N))/N\n return sqrt(inner) + sqrt(-2log(delta)/N) + 1/N;\nend;\n\nfunction get_parrondo_and_van_den_broek(N,d_VC,delta)\n pvdb_err(epsilon,N,d_VC,delta) = (epsilon - sqrt((2epsilon + log(6) + d_VC*log(2N) - log(delta))/N))^2;\n result = optimize(epsilon -> pvdb_err(epsilon,N,d_VC,delta), 0.0, 10.0);\n if result.converged==true\n return result.minimum\n else\n return NaN\n end;\nend;\n\nfunction get_devroye(N,d_VC,delta)\n devroye_err(epsilon,N,d_VC,delta) = (epsilon - sqrt((4epsilon*(1+epsilon) + log(4) + d_VC*log(N^2) - log(delta))/(2N)))^2;\n result = optimize(epsilon -> devroye_err(epsilon,N,d_VC,delta), 0.0, 20.0);\n if result.converged==true\n return result.minimum\n else\n return NaN\n end;\nend;\n\nd_VC = 50;\ndelta = 0.05;\n\n#N_arr = logspace(0,4,11); #from 1 to 10k\nN_arr = [5, 10, 50, 100, 500, 1000, 5000, 10000];\nepsilon_vc = [ get_vc_bound(N,d_VC,delta) for N in N_arr ];\nepsilon_rp = [ get_rademacher_penalty(N,d_VC,delta) for N in N_arr ];\nepsilon_pv = [ get_parrondo_and_van_den_broek(N,d_VC,delta) for N in N_arr ];\nepsilon_dv = [ get_devroye(N,d_VC,delta) for N in N_arr ];\n\nfunction plot_epsilons(N_arr,epsilon_arr,label_arr)\n fig = figure(figsize=(7,4))\n ax = fig[:add_subplot](1,1,1)\n for i in 1:size(label_arr)[1]\n #ax[:loglog](N_arr,epsilon_arr[:,i],label=label_arr[i]);\n loglog(N_arr,epsilon_arr[:,i],\"x-\",label=label_arr[i]);\n end;\n #ax[:legend](loc=\"best\",frameon=false);\n legend(loc=\"best\",frameon=false,fontsize=10)\n grid(true);\nend;\n\nepsilon_arr = [ epsilon_vc epsilon_rp epsilon_pv epsilon_dv ];\nlabel_arr = [ \"VC\", \"Rademacher\", \"Parrondo & Van den Broek\", \"Devroye\" ];\nplot_epsilons(N_arr,epsilon_arr,label_arr);\n\nprintln(\"N = $(N_arr[end])\")\nprintln(\"ϵ (VC) = $(epsilon_vc[end])\")\nprintln(\"ϵ (Rademacher) = $(epsilon_rp[end])\")\nprintln(\"ϵ (Parrondo & Van den Broek) = $(epsilon_pv[end])\")\nprintln(\"ϵ (Devroye) = $(epsilon_dv[end])\")\n\nprintln(\"N = $(N_arr[1])\")\nprintln(\"ϵ (VC) = $(epsilon_vc[1])\")\nprintln(\"ϵ (Rademacher) = $(epsilon_rp[1])\")\nprintln(\"ϵ (Parrondo & Van den Broek) = $(epsilon_pv[1])\")\nprintln(\"ϵ (Devroye) = $(epsilon_dv[1])\")\n\nfunction generate_dataset(;n_points=200)\n x = linspace(-1,1,n_points);\n y = sin(π*x);\n x_sample = rand(2);\n y_sample = sin(π*x_sample);\n return x,y,x_sample,y_sample;\nend;\n\nfunction fit_a(x_sample,y_sample)\n sum = x_sample[1]*y_sample[1]+x_sample[2]*y_sample[2]\n return sum/(x_sample[1]^2+x_sample[2]^2);\nend;\n\nfunction predict_y_a(x,a)\n return a .* x;\nend;\n\nfunction plot_xy(x,y,x_sample,y_sample,y_pred)\n figure(figsize=(7,5));\n plot(x,y,\"m-\",label=L\"$\\sin(\\pi x)$\");\n plot(x,y_pred,\"g--\",label=\"predicted\");\n plot(x_sample,y_sample,\"bo\",label=\"sample data\");\n grid(true);\n legend(loc=\"best\",frameon=false);\nend;\nx,y,x_sample,y_sample = generate_dataset();\ny_pred = predict_y_a(x,fit_a(x_sample,y_sample));\nplot_xy(x,y,x_sample,y_sample,y_pred);\n\nfunction get_avg_a(n_trials; n_points=200)\n a_arr = Float64[];\n for i in 1:n_trials\n x_sample = rand(2);\n y_sample = sin(π*x_sample);\n a = fit_a(x_sample,y_sample);\n push!(a_arr,a);\n end\n return mean(a_arr);\nend;\na = get_avg_a(1e6); #1.423, 1.425, 1.424, 1.427\nprintln(\" = $(round(a,2))x\");\n\nfunction get_bias_variance(avg_a, n_trials; n_points=200)\n bias = Float64[];\n var = Float64[];\n for i in 1:n_trials\n x_sample = rand(2);\n y_sample = sin(π*x_sample);\n a = fit_a(x_sample,y_sample);\n g_bar_x = avg_a*x_sample;\n push!(bias,mean((g_bar_x - y_sample).^2));\n push!(var,mean((g_bar_x - a .* x_sample).^2));\n end\n return bias, var;\nend;\n\nbias,var = get_bias_variance(a, 1e7);\nprintln(\" = $(mean(bias))\");\nprintln(\" = $(mean(var))\");\n", "meta": {"hexsha": "3305f0817fc60273441a20a2986f2027a3a18875", "size": 4759, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "perceptron/generalisation.jl", "max_stars_repo_name": "nathanielng/machine-learning", "max_stars_repo_head_hexsha": "07ba6b7eb1d09a3d9929fd8390dde356e1d0745d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2016-10-05T05:26:14.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-24T03:42:04.000Z", "max_issues_repo_path": "perceptron/generalisation.jl", "max_issues_repo_name": "nathanielng/machine-learning", "max_issues_repo_head_hexsha": "07ba6b7eb1d09a3d9929fd8390dde356e1d0745d", "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": "perceptron/generalisation.jl", "max_forks_repo_name": "nathanielng/machine-learning", "max_forks_repo_head_hexsha": "07ba6b7eb1d09a3d9929fd8390dde356e1d0745d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3121019108, "max_line_length": 126, "alphanum_fraction": 0.6293338937, "num_tokens": 1556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.8633916187614823, "lm_q1q2_score": 0.8050723717564561}} {"text": "\"\"\"\r\n GaussianCopula{d,MT}\r\n\r\nFields:\r\n - Σ::MT - covariance matrix\r\n\r\nConstructor\r\n\r\n GaussianCopula(Σ)\r\n\r\nThe [Gaussian Copula](https://en.wikipedia.org/wiki/Copula_(probability_theory)#Gaussian_copula) is the \r\ncopula of a [Multivariate normal distribution](http://en.wikipedia.org/wiki/Multivariate_normal_distribution). It is constructed as : \r\n\r\n```math\r\nC(\\\\mathbf{x}; \\\\boldsymbol{\\\\Sigma}) = F_{\\\\Sigma}(F_{\\\\Sigma,i}^{-1}(x_i),i\\\\in 1,...d)\r\n```\r\nwhere ``F_{\\\\Sigma}`` is a cdf of a gaussina random vector and `F_{\\\\Sigma,i}` is the ith marignal cdf, while ```\\\\Sigma`` is the covariance matrix. \r\n\r\nIt can be constructed in Julia via: \r\n```julia\r\nC = GaussianCopula(Σ)\r\n```\r\n\r\nThe random number generation works as expected:\r\n```julia\r\nrand(C,1000)\r\n# or\r\nRandom.rand!(C,u)\r\n```\r\n\r\nAnd yo can fit the distribution via : \r\n```julia\r\nfit(GaussianCopula,data)\r\n```\r\n\"\"\"\r\nstruct GaussianCopula{d,MT} <: EllipticalCopula{d,MT}\r\n Σ::MT\r\n function GaussianCopula(Σ) \r\n make_cor!(Σ)\r\n return new{size(Σ,1),typeof(Σ)}(Σ)\r\n end\r\nend\r\nU(::Type{T}) where T<: GaussianCopula = Distributions.Normal\r\nN(::Type{T}) where T<: GaussianCopula = Distributions.MvNormal\r\nfunction Distributions.fit(::Type{CT},u) where {CT<:GaussianCopula}\r\n dd = Distributions.fit(N(CT), quantile.(U(CT)(),u))\r\n Σ = Matrix(dd.Σ)\r\n return GaussianCopula(Σ)\r\nend\r\n\r\n", "meta": {"hexsha": "f65b8be161ef65017875e612d7a0838937d683de", "size": 1377, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/EllipticalCopulas/GaussianCopula.jl", "max_stars_repo_name": "lrnv/Copulas.jl", "max_stars_repo_head_hexsha": "97695c7e89275d07d44274c494fed0359625cf30", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2022-02-16T08:18:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T10:14:07.000Z", "max_issues_repo_path": "src/EllipticalCopulas/GaussianCopula.jl", "max_issues_repo_name": "lrnv/Copulas.jl", "max_issues_repo_head_hexsha": "97695c7e89275d07d44274c494fed0359625cf30", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-19T06:55:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T09:43:03.000Z", "max_forks_repo_path": "src/EllipticalCopulas/GaussianCopula.jl", "max_forks_repo_name": "lrnv/Copulas.jl", "max_forks_repo_head_hexsha": "97695c7e89275d07d44274c494fed0359625cf30", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0, "max_line_length": 150, "alphanum_fraction": 0.6572258533, "num_tokens": 422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.8633916152464017, "lm_q1q2_score": 0.8050723684788076}} {"text": "function bisection(f′, a, b, ϵ)\n if a > b; a, b = b, a; end\n ya, yb = f′(a), f′(b)\n if ya == 0; b = a; end\n if yb == 0; a = b; end\n while b-a > ϵ\n x = (a+b)/2;\n y = f′(x);\n if y == 0\n a, b = x, x;\n elseif sign(y) == sign(ya)\n a = x;\n else\n b = x;\n end\n end\n return (a, b);\nend\n", "meta": {"hexsha": "819310a5bec06adf9a374f52e3ba8e7b17ca31d3", "size": 373, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "bracketing/3.7-bisection_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.7-bisection_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.7-bisection_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": 19.6315789474, "max_line_length": 34, "alphanum_fraction": 0.3351206434, "num_tokens": 152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533013520764, "lm_q2_score": 0.8633916082162403, "lm_q1q2_score": 0.8050723554409117}} {"text": "function blkdiag(blocks::Array{Array{Pol{T}, 2}, 1}) where {T<:Number}\n m = sum(size.(blocks, 1))\n n = sum(size.(blocks, 2))\n J = zeros(Pol{T}, m, n)\n offset1 = 0\n offset2 = 0\n for blk in blocks\n J[offset1+1:offset1+size(blk, 1), offset2+1:offset2+size(blk, 2)] = blk\n offset1 += size(blk, 1)\n offset2 += size(blk, 2)\n end\n return J\nend\n\n\"\"\"\ncreates the matrix block of size n×(n+1) corresponding to column index n\n\"\"\"\nfunction colBlock(n::Int)\n var = Pol([0, 1])\n J = zeros(Pol{Int}, n, n+1)\n for ii in 1:n\n J[ii, ii] = var\n J[ii, ii+1] = -1\n end\n return J\nend\n\ncolBlock(arr::AbstractArray{Int, 1}) = blkdiag(colBlock.(arr))\n\n\"\"\"\ncreates the matrix block of size (n+1)×n corresponding to row index n\n\"\"\"\nfunction rowBlock(n::Int)\n var = Pol([0, 1])\n J = zeros(Pol{Int}, n+1, n)\n @inbounds for ii in 1:n\n J[ii, ii] = -1\n J[ii+1, ii] = var\n end\n return J\nend\n\nrowBlock(arr::AbstractArray{Int, 1}) = blkdiag(rowBlock.(arr))\n\n\"\"\"\ncreates the block matrix corresponding to infinite eigenvalue of multiplicity n\n\"\"\"\nfunction infBlock(n::Int)\n var = Pol([0, 1])\n J = zeros(Pol{Int}, n, n)\n @inbounds for ii in 1:n-1\n J[ii, ii] = -1\n J[ii+1, ii] = var\n end\n J[n, n] = -1\n return J\nend\n\ninfBlock(arr::AbstractArray{Int, 1}) = blkdiag(infBlock.(arr))\n\n\"\"\"\ncreates the block matrix of size n×n corresponding to eigenvalue λ\n\"\"\"\nfunction eigBlock(λ::T, n::Int) where {T<:Number}\n var = Pol([0, 1])\n J = zeros(Pol{T}, n, n)\n @inbounds for ii in 1:n-1\n J[ii, ii] = var - λ\n J[ii+1, ii] = -1\n end\n J[n, n] = var - λ\n return J\nend\n\neigBlock(λ::Number, arr::AbstractArray{Int, 1}) = blkdiag(eigBlock.(λ, arr))\n", "meta": {"hexsha": "35799de62ec4b3edbaacd04ce79fe5460a31e523", "size": 1761, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kronecker/blocks.jl", "max_stars_repo_name": "lucaferranti/MatrixPolynomials.jl", "max_stars_repo_head_hexsha": "909ce44f5dc339157ac563769f7ebf089084646f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kronecker/blocks.jl", "max_issues_repo_name": "lucaferranti/MatrixPolynomials.jl", "max_issues_repo_head_hexsha": "909ce44f5dc339157ac563769f7ebf089084646f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kronecker/blocks.jl", "max_forks_repo_name": "lucaferranti/MatrixPolynomials.jl", "max_forks_repo_head_hexsha": "909ce44f5dc339157ac563769f7ebf089084646f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-31T23:31:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T23:31:12.000Z", "avg_line_length": 23.1710526316, "max_line_length": 79, "alphanum_fraction": 0.5729699035, "num_tokens": 633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.8633915976709976, "lm_q1q2_score": 0.8050723520905638}} {"text": "\"\"\"\n SEIso <: Isotropic{SqEuclidean}\n\nIsotropic Squared Exponential kernel (covariance)\n```math\nk(x,x') = σ²\\\\exp(- (x - x')ᵀ(x - x')/(2ℓ²))\n```\nwith length scale ``ℓ`` and signal standard deviation ``σ``.\n\"\"\"\nmutable struct SEIso{T<:Real} <: Isotropic{SqEuclidean}\n \"Squared length scale\"\n ℓ2::T\n \"Signal variance\"\n σ2::T\n \"Priors for kernel parameters\"\n priors::Array\nend\n\n\"\"\"\nSquared Exponential kernel function\n\n SEIso(ll::T, lσ::T)\n\n# Arguments:\n- `ll::Real`: length scale (given on log scale)\n- `lσ::Real`: signal standard deviation (given on log scale) \n\"\"\"\nSEIso(ll::T, lσ::T) where T = SEIso{T}(exp(2 * ll), exp(2 * lσ), [])\n\nfunction set_params!(se::SEIso, hyp::AbstractVector)\n length(hyp) == 2 || throw(ArgumentError(\"Squared exponential has two parameters, received $(length(hyp)).\"))\n se.ℓ2, se.σ2 = exp(2 * hyp[1]), exp(2 * hyp[2])\nend\n\nget_params(se::SEIso{T}) where T = T[log(se.ℓ2) / 2, log(se.σ2) / 2]\nget_param_names(se::SEIso) = [:ll, :lσ]\nnum_params(se::SEIso) = 2\n\ncov(se::SEIso, r::Number) = se.σ2*exp(-0.5*r/se.ℓ2)\n\n@inline dk_dll(se::SEIso, r::Real) = r/se.ℓ2*cov(se,r)\n@inline function dk_dθp(se::SEIso, r::Real, p::Int)\n if p==1\n return dk_dll(se, r)\n elseif p==2\n return dk_dlσ(se, r)\n else\n return NaN\n end\nend\n", "meta": {"hexsha": "c2e2242f6bc5d8b9ca00c45e8c14a219bcc2a82b", "size": 1305, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels/se_iso.jl", "max_stars_repo_name": "mcusi/GaussianProcesses.jl", "max_stars_repo_head_hexsha": "7d268974aa0cd5c4164542c513307305d785da6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 284, "max_stars_repo_stars_event_min_datetime": "2015-07-31T21:32:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T07:08:58.000Z", "max_issues_repo_path": "src/kernels/se_iso.jl", "max_issues_repo_name": "mcusi/GaussianProcesses.jl", "max_issues_repo_head_hexsha": "7d268974aa0cd5c4164542c513307305d785da6d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 171, "max_issues_repo_issues_event_min_datetime": "2015-05-28T12:04:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T06:48:23.000Z", "max_forks_repo_path": "src/kernels/se_iso.jl", "max_forks_repo_name": "mcusi/GaussianProcesses.jl", "max_forks_repo_head_hexsha": "7d268974aa0cd5c4164542c513307305d785da6d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 59, "max_forks_repo_forks_event_min_datetime": "2015-05-31T12:44:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:21:38.000Z", "avg_line_length": 25.5882352941, "max_line_length": 112, "alphanum_fraction": 0.6206896552, "num_tokens": 461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.930458251637412, "lm_q2_score": 0.8652240756264638, "lm_q1q2_score": 0.8050548806819954}} {"text": "export frac_iso, is_frac_iso\n\n\"\"\"\n frac_iso(G,H)\n\nFind a doubly stochastic matrix `S` so that `AS=SB` where `A` and `B`\nare the adjacency matrices of `G` and `H` respectively.\n\"\"\"\nfunction frac_iso(G::SimpleGraph, H::SimpleGraph)\n if deg(G) != deg(H) || degdeg(G) != degdeg(H) # quick basic check before LP\n error(\"The graphs are not fractionally isomorphic\")\n end\n A = adjacency(G)\n B = adjacency(H)\n return frac_iso(A, B)\nend\n\nfunction frac_iso(A::Matrix, B::Matrix)\n n, c = size(A)\n nn, cc = size(B)\n @assert n == c && nn == cc \"Matrices must be square\"\n @assert n == nn \"Matrices must have the same size\"\n\n m = Model(get_solver())\n\n @variable(m, S[1:n, 1:n])\n\n for i = 1:n\n for k = 1:n\n @constraint(\n m,\n sum(A[i, j] * S[j, k] for j = 1:n) == sum(S[i, j] * B[j, k] for j = 1:n)\n )\n end\n @constraint(m, sum(S[i, j] for j = 1:n) == 1)\n @constraint(m, sum(S[j, i] for j = 1:n) == 1)\n end\n\n for i = 1:n\n for j = 1:n\n @constraint(m, S[i, j] >= 0)\n end\n end\n\n optimize!(m)\n status = Int(termination_status(m))\n\n if status != 1\n error(\"The graphs are not fractionally isomorphic\")\n end\n\n return value.(S)\n\nend\n\n\"\"\"\n is_frac_iso(G,H)\nTest if two graphs are fractionally isomorphic.\n\"\"\"\nfunction is_frac_iso(G::SimpleGraph, H::SimpleGraph)::Bool\n try\n f = frac_iso(G, H)\n return true\n catch\n return false\n end\n false\nend\n", "meta": {"hexsha": "c0d30f107af04f3607d1a43fb915a245ecc69ed8", "size": 1534, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/frac_iso.jl", "max_stars_repo_name": "scheinerman/SimpleGraphAlgorithms", "max_stars_repo_head_hexsha": "3ec61b5283cb22b51ead52677a3df8b3de5a1b93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2018-10-12T17:09:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T08:06:06.000Z", "max_issues_repo_path": "src/frac_iso.jl", "max_issues_repo_name": "scheinerman/SimpleGraphAlgorithms", "max_issues_repo_head_hexsha": "3ec61b5283cb22b51ead52677a3df8b3de5a1b93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2016-10-19T04:03:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-08T12:08:27.000Z", "max_forks_repo_path": "src/frac_iso.jl", "max_forks_repo_name": "scheinerman/SimpleGraphAlgorithms", "max_forks_repo_head_hexsha": "3ec61b5283cb22b51ead52677a3df8b3de5a1b93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-09-14T01:13:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T20:58:22.000Z", "avg_line_length": 22.231884058, "max_line_length": 88, "alphanum_fraction": 0.5469361147, "num_tokens": 470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.953966101527047, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.805047326699693}} {"text": "using EngEconomics, Roots, Plots, ColorSchemes\nplotly()\n\n# Given\nconstructionYears = 5 # Construction takes this many years\nconstructionStarts = 5 # Construction starts in this many years\nconstructionA = 20000 # Construction annual cost in $1000, so if this number is 20,000, the real price is 20,000,000\nmaintenanceStarts = 1 + constructionYears + constructionStarts # Number of years when maintenance for the project will begin. It is simply the sum of how long construction will take and when construction starts plus 1 year\nmaintenanceA = 2000 # Maintenance annual cost in $1000, so if this number is 2,000, then the real price is 2,000,000\ninflationRate = 0.03 # Inflation rate\nMARR = 0.07 # Project's MARR\nprojectLifeTime = 30 # I did this in my head (starts working in 2020, supposed to last till 2050)\n\n# Find\n# (a.) The present worth of the project\nrealMARR = (1 + MARR) / (1 + inflationRate) - 1\nNPW = (-constructionA * seriesPresentAmountFactor(realMARR, constructionYears)) * presentWorthFactor(realMARR, constructionStarts) + (-maintenanceA * seriesPresentAmountFactor(realMARR, projectLifeTime)) * presentWorthFactor(realMARR, constructionYears + constructionStarts)\n\n# (b.) Construct a sensitivity graph showing the effects of 5 percent and 10\n# percent increases and decreases in the construction costs, maintenance\n# costs and inflation rate. To which is the present worth most sensitive?\nsensitivity = [0.9, 0.95, 1.0, 1.05, 1.1]\n\n# Construction Costs\nrealMARR = (1 + MARR) / (1 + inflationRate) - 1\nNPW_constructionCost = (-constructionA * sensitivity * seriesPresentAmountFactor(realMARR, constructionYears)) * presentWorthFactor(realMARR, constructionStarts) .+ (-maintenanceA * seriesPresentAmountFactor(realMARR, projectLifeTime)) * presentWorthFactor(realMARR, constructionYears + constructionStarts)\nplot(sensitivity, NPW_constructionCost)\n\n# Maintenance Costs\nrealMARR = (1 + MARR) / (1 + inflationRate) - 1\nNPW_maintenanceCost = (-constructionA * seriesPresentAmountFactor(realMARR, constructionYears)) * presentWorthFactor(realMARR, constructionStarts) .+ (-maintenanceA * sensitivity * seriesPresentAmountFactor(realMARR, projectLifeTime)) * presentWorthFactor(realMARR, constructionYears + constructionStarts)\nplot!(sensitivity, NPW_maintenanceCost)\n\n# Inflation Rate\nrealMARR_inflationRate = (1 + MARR) ./ (1 .+ sensitivity * inflationRate) .- 1\nNPW_inflationRate = (-constructionA * seriesPresentAmountFactor.(realMARR_inflationRate, constructionYears)) .* presentWorthFactor.(realMARR_inflationRate, constructionStarts) .+ (-maintenanceA * seriesPresentAmountFactor.(realMARR_inflationRate, projectLifeTime)) .* presentWorthFactor.(realMARR_inflationRate, constructionYears + constructionStarts)\nplot!(sensitivity, NPW_inflationRate)\n\nprintln(\"From the plot, it\\'s clear that the NPW cost is most sensitive to the initial construction cost because the slope of that line is much bigger than that of the other lines\")\n", "meta": {"hexsha": "192fd1aa921b15745eebdd76622b7b616cb362e6", "size": 2960, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problems/ps8/p5.jl", "max_stars_repo_name": "zborffs/EngineeringEconomics.jl", "max_stars_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problems/ps8/p5.jl", "max_issues_repo_name": "zborffs/EngineeringEconomics.jl", "max_issues_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problems/ps8/p5.jl", "max_forks_repo_name": "zborffs/EngineeringEconomics.jl", "max_forks_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 74.0, "max_line_length": 351, "alphanum_fraction": 0.7905405405, "num_tokens": 772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539661002182845, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.8050473143592977}} {"text": "#=\nPlease see\nhttps://computationalmindset.com/en/neural-networks/ordinary-differential-equation-solvers.html#ode1\nfor details\n=#\n\n#=Original problem\nx′ + x = sin t + 3 cos 2t\nx(0) = 0\n=#\n\n#=Esplicit form of equation\nx′ = sin t + 3 cos 2t − x\n=#\n\n#=Analytical solution\nx(t) = 1/2 sin t - 1/2 cos t + 3/5 cos 2t + 6/5 sin 2t - 1/10 e^-t\n=#\n\nusing DifferentialEquations\nusing Plots\n\node_fn(x,p,t) = sin(t) + 3.0 * cos(2.0 * t) - x\n\nan_sol(t) = (1.0/2.0) * sin(t) - (1.0/2.0) * cos(t) +\n (3.0/5.0) * cos(2.0*t) + (6.0/5.0) * sin(2.0*t) -\n (1.0/10.0) * exp(-t)\n\nt_begin=0.0\nt_end=10.0\ntspan = (t_begin,t_end)\nx_init=0.0\n\nprob = ODEProblem(ode_fn, x_init, tspan)\nnum_sol = solve(prob, Tsit5(), reltol=1e-8, abstol=1e-8)\n\nplot(num_sol.t, an_sol.(num_sol.t),\n linewidth=2, ls=:dash,\n title=\"ODE 1st order IVP solved by D.E. package\",\n xaxis=\"t\", yaxis=\"x\",\n label=\"analytical\",\n legend=true)\nplot!(num_sol,\n linewidth=1,\n label=\"numerical\")\n", "meta": {"hexsha": "09a7b5a9ca4d72d5b0d0db65a375e680075c525b", "size": 978, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ODEs/solver-demos/julia/DifferentialEquations/ode_1st_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_1st_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_1st_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": 21.2608695652, "max_line_length": 100, "alphanum_fraction": 0.6063394683, "num_tokens": 407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.8615382129861583, "lm_q1q2_score": 0.8050171385584244}} {"text": "\"\"\"\n PInterval <: SimpleProbabilitySet\n\nCredal set of categorical distributions defined by lower and upper probabilities.\n\"\"\"\nstruct PInterval <: SimpleProbabilitySet\n plower::Vector{Float64}\n pupper::Vector{Float64}\nend\n\n\"\"\"\n PInterval(p::Vector{Float64}, uncsize::Float64)\n\nProbability intervals centered on 'p' of width ± 'uncsize' (with saturated bounds)\n\"\"\"\nfunction PInterval(p::Vector{Float64}, uncsize::Float64)\n pl = zeros(length(p))\n pu = ones(length(p))\n for (i, pi) in enumerate(p)\n pl[i] = max(0.0, pi - uncsize)\n pu[i] = min(1.0, pi + uncsize)\n end\n PInterval(pl, pu)\nend\n\n\"\"\"\n PInterval(p::Vector{Float64})\n\nDegenerate probability interval of only pmf 'p'\n\"\"\"\nPInterval(p::Vector{Float64}) = PInterval(p,p) # degenerate PInterval\n\n\"\"\"\n PInterval()\n\nDefault probability interval of p1 ∈ [0.2, 0.3], p2 ∈ [0.7, 0.8]\n\"\"\"\nPInterval() = PInterval([0.2, 0.7], [0.3, 0.8]) # default PInterval\n\n\"\"\"\n psample(plower::Vector{Float64}, pupper::Vector{Float64})\n\nGenerate a probability distribution, uniformly at random, from the ambiguity set defined by the `pupper` and `plower` probabilities.\n\"\"\"\nfunction psample(plower::Vector{Float64}, pupper::Vector{Float64})\n n = length(plower)\n A = zeros(Float64, 2n+1, n)\n for i = 1:n\n A[2i - 1,i] = 1.0\n A[2i, i] = -1.0\n end\n A[end,:] = ones(n)\n bc = Array{Float64}(2n+1)\n for i = 1:n\n # due to limitations in hitandrun, set upper limit to 0+eps if upper limit is actually 0.0\n bc[2i - 1] = pupper[i] == 0.0 ? pupper[i] + 0.0000001 : pupper[i]\n bc[2i] = -1.0 * plower[i]\n end\n bc[end] = 1.0\n d = vcat(fill(\"<=\", 2n),\"=\")\n nsample = 1\n rseed = rand(1:10_000)\n rout = R\"\"\"\n library(hitandrun)\n set.seed($rseed)\n constr <- list(constr = $A, rhs = $bc, dir = $d)\n samples <- hitandrun(constr, n.samples = $nsample, thin = ($n) ^ 3)\n \"\"\"\n p = reshape(rcopy(rout), n)\nend\n\npsample(pint::PInterval) = psample(pint.plower, pint.pupper)\n", "meta": {"hexsha": "020bafff2026abdb73d790dda7ea200df9cb2a31", "size": 2018, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/pinterval.jl", "max_stars_repo_name": "ajkeith/SimpleProbabilitySets.jl", "max_stars_repo_head_hexsha": "479d32c613ccdf1774a8c29212699f33b51ded4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pinterval.jl", "max_issues_repo_name": "ajkeith/SimpleProbabilitySets.jl", "max_issues_repo_head_hexsha": "479d32c613ccdf1774a8c29212699f33b51ded4b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pinterval.jl", "max_forks_repo_name": "ajkeith/SimpleProbabilitySets.jl", "max_forks_repo_head_hexsha": "479d32c613ccdf1774a8c29212699f33b51ded4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6438356164, "max_line_length": 132, "alphanum_fraction": 0.6189296333, "num_tokens": 662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951680216529, "lm_q2_score": 0.8615382076534743, "lm_q1q2_score": 0.8050171382974418}} {"text": "module problem126\n\nexport Cuboid\n\ndescription = \"\"\"\nCuboid layers\n\nThe minimum number of cubes to cover every visible face on a cuboid measuring 3 x 2 x 1 is twenty-two.\nIf we then add a second layer to this solid it would require forty-six cubes to cover every visible face, \nthe third layer would require seventy-eight cubes, and the fourth layer would require one-hundred and eighteen cubes to cover every visible face.\n\nHowever, the first layer on a cuboid measuring 5 x 1 x 1 also requires twenty-two cubes; \nsimilarly the first layer on cuboids measuring 5 x 3 x 1, 7 x 2 x 1, and 11 x 1 x 1 all contain forty-six cubes.\n\nWe shall define C(n) to represent the number of cuboids that contain n cubes in one of its layers. \nSo C(22) = 2, C(46) = 4, C(78) = 5, and C(118) = 8.\nIt turns out that 154 is the least value of n for which C(n) = 10.\n\nFind the least value of n for which C(n) = 1000.\n\"\"\"\n\n# A cube with length, width and height\nimmutable Cuboid\n l :: Int\n w :: Int\n h :: Int\nend\n\n# calculates the middle section of the n'th layer\n# equal to (the perimeter of original cube + diagonals) * height or original cube\nmiddle(c :: Cuboid, n :: Int) = (2 * (c.l + c.w) + 4 * (n - 1)) * c.h\n\n# Recurrance relation for calculating the top section of the n'th layer \n# For n = 1, just the area of the top of original cube\n# otherwise, equal to the top of the previous layer + a one cube thick rim from the middle of previous layer\ntop(c :: Cuboid, n :: Int) = \n if (n == 1) \n return (c.l * c.w) \n else \n return (top(c, n-1) + div(middle(c, n-1), c.h)) \n end \n\n# Calculate the n'th layer, top and bottom are symetric + middle section\nlayer(c :: Cuboid, n :: Int) = 2 * top(c, n) + middle(c, n)\n\n# Calculate the size of all layers of cuboid up to a maximum\n# re-uses the results of previous iterations to efficiently calculate the next\nfunction layers(c :: Cuboid, maxsize :: Int)\n n = 1\n t = top(c, n)\n m = middle(c, n)\n x = 0\n result = Int[]\n while true\n x = 2 * t + m\n if x > maxsize break end\n push!(result, x)\n t = t + div(m, c.h)\n n += 1\n m = middle(c, n)\n end\n return result\nend\n\n# Search for a solution x, to C(x) == N, for x in 1:guess\n# The lower bound is given by layer 1 of cuboid (Length, 1, 1) \n# Once a solution is found < lower bound, search can stop\nfunction search(N :: Int, guess :: Int)\n counts = zeros(Int, guess)\n l = 1\n lowerbound = layer(Cuboid(l, 1, 1), 1) \n while lowerbound <= guess\n for i = 1:lowerbound-1\n if counts[i] == N\n return i\n end\n end\n w = 1\n while w <= l && layer(Cuboid(l, w, 1), 1) <= guess\n h = 1\n while h <= w && layer(Cuboid(l, w, h), 1) <= guess\n sizes = layers(Cuboid(l,w,h), guess)\n counts[sizes] += 1\n h += 1\n end\n w += 1\n end\n l += 1\n lowerbound = layer(Cuboid(l, 1, 1), 1)\n end\n println(\"no solution found < $guess\")\n return -1\nend\n\nusing Base.Test\n\n@test layer(Cuboid(3, 2, 1), 1) == 22\n@test layer(Cuboid(3, 2, 1), 2) == 46\n@test layer(Cuboid(3, 2, 1), 3) == 78\n@test layer(Cuboid(3, 2, 1), 4) == 118\n@test layer(Cuboid(5, 1, 1), 1) == 22\n@test layer(Cuboid(5, 3, 1), 1) == 46\n@test layer(Cuboid(7, 2, 1), 1) == 46\n@test layer(Cuboid(11, 1, 1), 1) == 46\n@test layers(Cuboid(3,2,1), 78) == [22, 46, 78] \n@test search(10, 200) == 154\n\nend", "meta": {"hexsha": "fad0ece32cdc0b0af87b24f7077180a0b5472057", "size": 3312, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/problem126.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/problem126.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/problem126.jl", "max_forks_repo_name": "mbuhot/mbuhot-euler-solutions", "max_forks_repo_head_hexsha": "30066543cfd2d84976beb0605839750b64f4b8ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6666666667, "max_line_length": 145, "alphanum_fraction": 0.6301328502, "num_tokens": 1147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951680216529, "lm_q2_score": 0.8615382040983515, "lm_q1q2_score": 0.8050171349755522}} {"text": "function atan2(y,x)\r\n if x>0\r\n return atan(y/x)\r\n elseif (x<0 && y>=0)\r\n return atan(y/x)+pi\r\n elseif (x<0 && y<0)\r\n return atan(y/x)-pi\r\n elseif (x==0 && y>0)\r\n return pi/2\r\n elseif (x==0 && y<0)\r\n return -pi/2\r\n else\r\n return NaN\r\n end\r\nend\r\n", "meta": {"hexsha": "e6b633e42e6011a7330249295b2dcebc3e35bd7a", "size": 307, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "atan2.jl", "max_stars_repo_name": "umbertosaetti/J-GenHel", "max_stars_repo_head_hexsha": "46deb43ae73b5c43bb131be67005f21834b6d39b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2022-01-03T20:13:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-17T17:31:20.000Z", "max_issues_repo_path": "atan2.jl", "max_issues_repo_name": "umbertosaetti/J-SimpleHel", "max_issues_repo_head_hexsha": "6fdd7d8a1a22e700c35c8800a90cfa527833eb91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-18T18:28:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-21T00:46:07.000Z", "max_forks_repo_path": "atan2.jl", "max_forks_repo_name": "umbertosaetti/J-SimpleHel", "max_forks_repo_head_hexsha": "6fdd7d8a1a22e700c35c8800a90cfa527833eb91", "max_forks_repo_licenses": ["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.1875, "max_line_length": 28, "alphanum_fraction": 0.4429967427, "num_tokens": 103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951661947456, "lm_q2_score": 0.8615382040983515, "lm_q1q2_score": 0.8050171334016017}} {"text": "# Fixed point classification in 2D\nusing DrWatson\n@quickactivate \"NonlinearDynamicsTextbook\"\ninclude(srcdir(\"style.jl\"))\nusing DynamicalSystems, PyPlot, Random\n\nalleigs = []\nfig, axs = subplots(2,3; figsize = (figx, 2figy))\nax = gca()\nxgrid = -5:0.05:5\nygrid = xgrid\nux = zeros(length(xgrid), length(ygrid))\nuy = copy(ux)\n\nMs = [\n [1.0 0.8;\n 0.4 1.0],\n [-1.0 -0.8;\n 1.8 -1.0],\n [-1.0 0;\n 1 1],\n [0 -1;\n 1 0],\n]\n\ntitles = [\"repulsive node\", \"attractive spiral\", \"hyperbolic/saddle\", \"center\"]\n\nusing LinearAlgebra\nfunction stream_eigs!(ax, M, c = \"C0\")\n for (i, x) in enumerate(xgrid)\n for (j, y) in enumerate(ygrid)\n ux[i, j], uy[i, j] = M * [x, y]\n end\n end\n\n ax.streamplot(Vector(xgrid), Vector(ygrid), ux', uy';\n linewidth = 1.5, density = 0.5, color = c, arrowsize = 2,\n )\n ev = eigen(M)\n push!(alleigs, ev.values)\n if eltype(ev.values) <: Float64\n e1 = ev.vectors[:, 1]\n e2 = ev.vectors[:, 2]\n for e in (e1, e2)\n ax.plot(e[1] .* 2xgrid, e[2] .* 2ygrid; color = \"C2\", ls = \"dashed\")\n end\n end\n ax.set_xlim(xgrid[1], xgrid[end])\n ax.set_ylim(ygrid[1], ygrid[end])\n ax.set_xticks([])\n ax.set_yticks([])\n ax.plot(0, 0; marker = \"o\", mec = \"C2\", mew = 1,\n markersize = 12, mfc = :white, zorder = 99\n )\nend\n\nfunction tovec(e)\n if eltype(e) <: Real\n e1 = e\n e2 = zeros(2)\n else\n e1 = [e[1].re, e[2].re]\n e2 = [e[1].im, e[2].im]\n end\n return e1, e2\nend\n\nfor (i, M) in enumerate(Ms)\n ax = axs[i]\n color = i < 3 ? \"C$(i-1)\" : \"C$(i)\"\n stream_eigs!(ax, M, color)\n ax.set_title(titles[i]; color = color)\n # Plot eigenvalues\n e1, e2 = tovec(alleigs[i])\n axs[5].scatter(e1, e2; color = color, s = 200, zorder = 99)\nend\n\n# Set axis of eigenval plot\naxs[5].spines[\"left\"].set_position(\"center\")\naxs[5].spines[\"bottom\"].set_position(\"center\")\naxs[5].grid(false)\naxs[5].spines[\"right\"].set_color(\"none\")\naxs[5].spines[\"top\"].set_color(\"none\")\naxs[5].set_title(\"eigenvalues\"; color = \"k\")\n# axs[5].set_yticklabels([])\n# axs[5].set_xticklabels([])\naxs[5].set_xlim(-2, 2)\naxs[5].set_ylim(-1.8, 1.8)\n\n# Plot limit cycle\nfunction vanderpoll(u, p, t)\n x, y = u;\n xdot = p*(x - x^3/3 - y)\n ydot = x/p\n return SVector(xdot, ydot)\nend\n\nds = ContinuousDynamicalSystem(vanderpoll, [0.1, 0.2], 0.5)\ntr = trajectory(ds, 7.0; Ttr = 100.0)\naxs[6].clear()\naxs[6].plot(columns(tr)...; color = \"C2\", linestyle = \"--\")\nfor (i, x) in enumerate(xgrid)\n for (j, y) in enumerate(ygrid)\n ux[i, j], uy[i, j] = ds.f(SVector(x, y), ds.p, 0)\n end\nend\naxs[6].streamplot(Vector(xgrid), Vector(ygrid), ux', uy';\n linewidth = 1.5, density = 0.5, color = \"C5\", arrowsize = 2\n)\nax = axs[6]\nax.set_xlim(xgrid[1], xgrid[end])\nax.set_ylim(ygrid[1], ygrid[end])\nax.set_xticks([])\nax.set_yticks([])\nax.set_title(\"attractive limit cycle\"; color = \"C5\")\n\nfig.subplots_adjust(bottom = 0.02, left = 0.02, top = 0.92, right = 0.97, hspace = 0.2)\nwsave(plotsdir(\"2\", \"2ddynamics\"), fig)", "meta": {"hexsha": "b46d56acdb842a6e816e2b86f61a81288d74bc91", "size": 3079, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "figure_generation/2/2.2.jl", "max_stars_repo_name": "JuliaDynamics/NonlinearDynamicsTextbook", "max_stars_repo_head_hexsha": "bfae8cf867f458f00151da089332f2ce3bea5dd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 88, "max_stars_repo_stars_event_min_datetime": "2021-07-18T20:54:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T09:23:53.000Z", "max_issues_repo_path": "figure_generation/2/2.2.jl", "max_issues_repo_name": "JuliaDynamics/NonlinearDynamicsTextbook", "max_issues_repo_head_hexsha": "bfae8cf867f458f00151da089332f2ce3bea5dd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "figure_generation/2/2.2.jl", "max_forks_repo_name": "JuliaDynamics/NonlinearDynamicsTextbook", "max_forks_repo_head_hexsha": "bfae8cf867f458f00151da089332f2ce3bea5dd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2021-07-28T18:49:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T08:45:11.000Z", "avg_line_length": 26.093220339, "max_line_length": 87, "alphanum_fraction": 0.5735628451, "num_tokens": 1175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088064979619, "lm_q2_score": 0.8670357666736772, "lm_q1q2_score": 0.804963641328554}} {"text": "@doc raw\"\"\"\n PowerKernel([γ=1])\n\nThe Power Kernel is a negative definite kernel given by:\n\n```math\n\\kappa(\\mathbf{x},\\mathbf{y}) = \n\\|\\mathbf{x} - \\mathbf{y} \\|^{2\\gamma}\n\\qquad \\gamma \\in (0,1]\n```\n\"\"\"\nstruct PowerKernel{T<:AbstractFloat} <: NegativeDefiniteKernel{T}\n gamma::HyperParameter{T}\n PowerKernel{T}(γ::Real) where {T<:AbstractFloat} = new{T}(\n HyperParameter(convert(T,γ), interval(OpenBound(zero(T)), ClosedBound(one(T))))\n )\nend\nPowerKernel(γ::T1 = 1.0) where {T1<:Real} = PowerKernel{floattype(T1)}(γ)\n\n@inline powerkernel(z::T, γ::T) where {T<:AbstractFloat} = z^γ\n\n@inline basefunction(::PowerKernel) = SquaredEuclidean()\n@inline kappa(κ::PowerKernel{T}, z::T) where {T} = powerkernel(z, getvalue(κ.gamma))", "meta": {"hexsha": "0cdb86defbd92d62e72a34caa060392f810bea46", "size": 742, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernelfunctions/negativedefinite/power.jl", "max_stars_repo_name": "holtri/MLKernels.jl", "max_stars_repo_head_hexsha": "d7b84b1bd7b9d9ca4cb7c413d0e34b04c09a331c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernelfunctions/negativedefinite/power.jl", "max_issues_repo_name": "holtri/MLKernels.jl", "max_issues_repo_head_hexsha": "d7b84b1bd7b9d9ca4cb7c413d0e34b04c09a331c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernelfunctions/negativedefinite/power.jl", "max_forks_repo_name": "holtri/MLKernels.jl", "max_forks_repo_head_hexsha": "d7b84b1bd7b9d9ca4cb7c413d0e34b04c09a331c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2608695652, "max_line_length": 87, "alphanum_fraction": 0.6657681941, "num_tokens": 247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377296574668, "lm_q2_score": 0.8397339716830605, "lm_q1q2_score": 0.8049166947333283}} {"text": "include(\"getdigit_n.jl\")\ninclude(\"myprintf.jl\")\nusing Printf\nusing .GetDigit_n\nusing .MyPrintf\n\nconst DIGIT = 100\nconst MAXN = 500\n\nfunction gaulegofpi(n)\n aₙ = BigFloat(1)\n bₙ = BigFloat(1) / sqrt(BigFloat(2))\n tₙ = parse(BigFloat, \"0.25\")\n pₙ = BigFloat(1)\n\n for i = 1:n\n aₙ₊₁ = (aₙ + bₙ) / BigFloat(2)\n bₙ = sqrt(aₙ * bₙ)\n tₙ = tₙ - pₙ * (aₙ - aₙ₊₁) * (aₙ - aₙ₊₁)\n pₙ = BigFloat(2) * pₙ\n aₙ = aₙ₊₁\n end\n\n return (aₙ + bₙ) * (aₙ + bₙ) / (BigFloat(4) * tₙ)\nend\n\nfunction main()\n n = GetDigit_n.getn(gaulegofpi, MAXN, DIGIT, true)\n precision = GetDigit_n.getdigit(gaulegofpi, n, DIGIT, true)\n precision = GetDigit_n.getdigit_2(gaulegofpi, n, DIGIT, precision)\n\n setprecision(precision)\n MyPrintf.myprintf(\"π(計算値) = \", DIGIT, gaulegofpi(n))\n MyPrintf.myprintf(\"π(厳密値) = \", DIGIT, BigFloat(π))\n @printf(\"n = %d, 計算%d桁で、%d桁求まりました\\n\", n, precision, DIGIT)\nend\n\nmain()\n", "meta": {"hexsha": "d79ac7f00731668952d1ff08a094dc685fa58d51", "size": 941, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "gausslegendreofpi.jl", "max_stars_repo_name": "dc1394/pi_julia", "max_stars_repo_head_hexsha": "a097705dab169aea82b8639638fded92cef32bbe", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gausslegendreofpi.jl", "max_issues_repo_name": "dc1394/pi_julia", "max_issues_repo_head_hexsha": "a097705dab169aea82b8639638fded92cef32bbe", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gausslegendreofpi.jl", "max_forks_repo_name": "dc1394/pi_julia", "max_forks_repo_head_hexsha": "a097705dab169aea82b8639638fded92cef32bbe", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1282051282, "max_line_length": 70, "alphanum_fraction": 0.601487779, "num_tokens": 418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377272885903, "lm_q2_score": 0.8397339656668286, "lm_q1q2_score": 0.804916686977317}} {"text": "\"\"\"\n`assemble_system!` - assemble the matrix for the left hand side of the problem\n\"\"\"\nfunction assemble_system!(problem::RandomODEProblem)\n # construct the first row of the discrete Laplacian\n problem.A[1,1] = -2\n problem.A[1,2] = 1\n\n # construct middle rows\n for j ∈ 2:problem.nₓ - 1\n problem.A[j, j- 1] = 1\n problem.A[j, j] = -2\n problem.A[j, j + 1] = 1\n end\n\n # construct last row\n problem.A[problem.nₓ, problem.nₓ - 1] = 1\n problem.A[problem.nₓ, problem.nₓ] = -2\n\n # adjust for random potential\n problem.A = spdiagm(problem.V) - problem.A/problem.Δx^2\n\n return problem\nend", "meta": {"hexsha": "6af1396a9cb4bccb4902e878c610d6d798992b12", "size": 634, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/assembly.jl", "max_stars_repo_name": "liamfdoherty/RandomODE.jl", "max_stars_repo_head_hexsha": "7a79f069804b56fead7997c68395b53655ddec58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/assembly.jl", "max_issues_repo_name": "liamfdoherty/RandomODE.jl", "max_issues_repo_head_hexsha": "7a79f069804b56fead7997c68395b53655ddec58", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/assembly.jl", "max_forks_repo_name": "liamfdoherty/RandomODE.jl", "max_forks_repo_head_hexsha": "7a79f069804b56fead7997c68395b53655ddec58", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4166666667, "max_line_length": 78, "alphanum_fraction": 0.6246056782, "num_tokens": 208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9609517061554854, "lm_q2_score": 0.837619959279793, "lm_q1q2_score": 0.8049123289798054}} {"text": "using Pkg\nPkg.activate(\".\")\nusing PlotlyJS, Zygote, LinearAlgebra\nusing Dash, DashCoreComponents, DashHtmlComponents\nusing DashBootstrapComponents\n\nfunction frenet_frame(x, y, z)\n ẋ(t) = gradient(x, t)[1]\n ẏ(t) = gradient(y, t)[1]\n ż(t) = gradient(z, t)[1]\n\n ẍ(t) = hessian(x, t)\n ÿ(t) = hessian(y, t)\n z̈(t) = hessian(z, t)\n\n α̇(t) = [ẋ(t), ẏ(t), ż(t)]\n α̈(t) = [ẍ(t), ÿ(t), z̈(t)]\n function out(t)\n T = α̇(t)\n T = T / norm(T)\n ad = α̈(t)\n N = ad - dot(ad, T)T\n N = N / norm(N)\n B = cross(T, N)\n T, N, B\n end\nend\n\nfunction uv_surface(uv_domain, ϕ; uv_res = [40, 40])\n us = LinRange(uv_domain[1], uv_domain[2], uv_res[1])\n vs = LinRange(uv_domain[3], uv_domain[4], uv_res[2])\n u_res, v_res = uv_res\n xs = zeros(u_res, v_res)\n ys = zeros(u_res, v_res)\n zs = zeros(u_res, v_res)\n for (i, u) in enumerate(us)\n for (j, v) in enumerate(vs)\n xs[i, j], ys[i, j], zs[i, j] = ϕ(u, v)\n end\n end\n surface(x = xs, y = ys, z = zs, showscale = false)\nend\n\nfunction xyz(ps)\n x = [p[1] for p in ps]\n y = [p[2] for p in ps]\n z = [p[3] for p in ps]\n return x, y, z\nend\n\nfunction torus_knot(m::Int64, n::Int64; R = 2, r = 1, uv_res = [220, 220])\n ϕ(u, v) = [(R + r * cos(u)) * cos(v), (R + r * cos(u)) * sin(v), r * sin(u)]\n α(t) = ϕ(m * t, n * t)\n x(t) = α(t)[1]\n y(t) = α(t)[2]\n z(t) = α(t)[3]\n\n F = frenet_frame(x, y, z)\n function ψ(u, v)\n T, N, B = F(u)\n ρ = r / 3\n α(u) + ρ * cos(v) * N + ρ * sin(v) * B\n end\n uv_surface([-π, 1.02π, -π, π], ψ, uv_res = uv_res)\nend\ndescription = dcc_markdown(raw\"Torus knots are obtained by winding a curve around a torus \n ($m$ times in parallel direction and $n$ times in the meridian direction). More concretely, if\n\n $$\\varphi(u,v) = ((R+r\\cos(u))\\cos(v), (R+r\\cos(u))\\sin(v), r\\sin(u))$$\n\n is the torus parametrization, the curve\n\n $$\\alpha(t) = \\varphi(mt,nt)\\text{ for }0\\leq t \\leq 2\\pi $$ \n\nis said to be knot of the type $(m,n)$. These knots can be made into surfaces by thickening them using the Frenet frame over $\\alpha$\n \")\nsd = 4.0\nscene3d = Dict(\n :xaxis => Dict(:range => [-sd, sd], :autorange => false),\n :yaxis => Dict(:range => [-sd, sd], :autorange => false),\n :zaxis => Dict(:range => [-sd, sd], :autorange => false),\n :aspectratio => Dict(:x => 1, :y => 1, :z => 1),\n)\n\nlayout = Layout(scene = scene3d, width = 600, height = 600)\n\nmathjax = \"https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=TeX-MML-AM_CHTML\"\napp = dash(external_scripts = [mathjax], external_stylesheets = [dbc_themes.BOOTSTRAP])\napp.title = \"Dash Torus Knots\"\n\nknot = torus_knot(2, 3)\ngraph = dbc_spinner(dcc_graph(id = \"graph\", figure = plot(knot, layout)))\n\nslider_m = dcc_slider(\n id = \"slider_m\",\n min = 1,\n max = 7,\n step = 1,\n value = 3,\n marks = Dict([i => (\"m=$(i)\") for i = 1:10]),\n)\nslider_n = dcc_slider(\n id = \"slider_n\",\n min = 1,\n max = 7,\n step = 1,\n value = 2,\n marks = Dict([i => (\"n=$(i)\") for i = 1:10]),\n)\n\n\n\ninput = dbc_row([dbc_col(slider_m, width = Dict(\"size\" => 3, \"order\" => \"first\", \"offset\" => 3)),\n dbc_col(slider_n, width = Dict(\"size\" => 3, \"order\" => \"last\", \"offset\" => 0))])\napp.layout = dbc_container(\n [\n html_h1(html_center(\"Torus Knots\"))\n html_br()\n description\n html_center(graph)\n html_center(input)\n html_br()\n html_br()\n ],\n)\n\ncallback!(\n app,\n Output(\"graph\", \"figure\"),\n Input(\"slider_m\", \"value\"),\n Input(\"slider_n\", \"value\"),\n) do m, n\n knot = torus_knot(m, n)\n return plot(knot, layout)\nend\nrun_server(app, \"0.0.0.0\", debug = true)\n", "meta": {"hexsha": "4dca07ec1714be114f9622b3d079a1e663be2279", "size": 3734, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "app.jl", "max_stars_repo_name": "valerocar/DashKnots.jl", "max_stars_repo_head_hexsha": "7ba4aa4ba17acd8b0e867a19e63befbdbcd50a98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app.jl", "max_issues_repo_name": "valerocar/DashKnots.jl", "max_issues_repo_head_hexsha": "7ba4aa4ba17acd8b0e867a19e63befbdbcd50a98", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app.jl", "max_forks_repo_name": "valerocar/DashKnots.jl", "max_forks_repo_head_hexsha": "7ba4aa4ba17acd8b0e867a19e63befbdbcd50a98", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2554744526, "max_line_length": 133, "alphanum_fraction": 0.5463310123, "num_tokens": 1377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026595857203, "lm_q2_score": 0.8774767842777551, "lm_q1q2_score": 0.8049117879427101}} {"text": "function gcd(x,y)\n if x == 0\n return y\n else\n return gcd(y%x,x)\n end\nend\nfunction find(arr,n)\n r = arr[1]\n for i=2:n\n r = gcd(arr[i],r)\n end\n return r\nend\nv = [8 16 8 4]\nlen = length(v)\nprintln(\"The GCD of the array is = \",find(v,len))\n\n\n", "meta": {"hexsha": "7298add6838ee1cb6e7063ef20ccdb0cd6bb40c1", "size": 280, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "algorithms/math/gcdarray.jl", "max_stars_repo_name": "landrumb/julia", "max_stars_repo_head_hexsha": "b57d478825c4bea8d0780efab80b7cbe32f3ea45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26, "max_stars_repo_stars_event_min_datetime": "2018-10-08T05:29:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-21T09:27:27.000Z", "max_issues_repo_path": "algorithms/math/gcdarray.jl", "max_issues_repo_name": "landrumb/julia", "max_issues_repo_head_hexsha": "b57d478825c4bea8d0780efab80b7cbe32f3ea45", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2018-10-08T05:44:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-20T15:33:02.000Z", "max_forks_repo_path": "algorithms/math/gcdarray.jl", "max_forks_repo_name": "landrumb/julia", "max_forks_repo_head_hexsha": "b57d478825c4bea8d0780efab80b7cbe32f3ea45", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-10-26T18:07:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-21T09:27:30.000Z", "avg_line_length": 14.0, "max_line_length": 49, "alphanum_fraction": 0.5142857143, "num_tokens": 99, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9658995762509216, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.8049078754904692}} {"text": "\"\"\"\n Fibonacci{T} <: UnivariateAlgorithm\n\nThe Fibonacci search algorithm optimize a univariate function by iteratively shrinking the \ninitial bracket around the minimum. The ratio is computed from the Fibonacci sequence.\n\"\"\"\nstruct Fibonacci{T} <: UnivariateAlgorithm \n ϵ::T\n\n function Fibonacci{T}(ϵ) where {T}\n 0 < ϵ < 1 ? new{T}(ϵ) : error(\"`ϵ` must be in the interval (0, 1)\")\n end\nend\n\n\"\"\"\n Fibonacci([ϵ=0.01])\n\nInitialize Fibonacci search algorithm with optional argument `ϵ` in the interval (0, 1)\nto control how close the last iterate is to the previous one. Refer to Kochenderfer and \nWheeler's \"Algorithms for Optimization\" for more information.\n\"\"\"\nFibonacci(ϵ=0.01) = Fibonacci{typeof(ϵ)}(ϵ)\n\nfunction _optimize(f, lower::T, upper::T, alg::Fibonacci; \n reltol, abstol, maxiter) where {T}\n ϵ = T(alg.ϵ)\n s = (1 - √5) / (1 + √5)\n p = 1 / (φ * (1 - s^(maxiter + 1)) / (1 - s^maxiter))\n x = T(p * lower + (1 - p) * upper)\n yx = f(x)\n converged = false\n iter = 1\n while true\n x_tol = reltol * abs(x) + abstol\n if abs(upper - lower) < 2x_tol\n converged = true\n break\n end\n iter == maxiter && break\n iter += 1\n if iter == maxiter\n new_x = T(ϵ * upper + (1 - ϵ) * x)\n else\n new_x = T(p * upper + (1 - p) * lower)\n end\n new_yx = f(new_x)\n if yx > new_yx\n lower, x, yx = x, new_x, new_yx\n else\n lower, upper = new_x, lower\n end\n p = 1 / (φ * (1 - s^(maxiter - iter + 2)) / (1 - s^(maxiter - iter + 1)))\n end\n return Solution(converged, iter, x, yx)\nend", "meta": {"hexsha": "9b63ff6c9c432a791d0d179cf6e82f36d7fef9f9", "size": 1670, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/algorithms/fibonacci.jl", "max_stars_repo_name": "lhnguyen-vn/Optini.jl", "max_stars_repo_head_hexsha": "81e94ff764daa9819edae4b4b8211726a7de0821", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-24T21:26:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-24T21:26:59.000Z", "max_issues_repo_path": "src/univariate/algorithms/fibonacci.jl", "max_issues_repo_name": "lhnguyen-vn/Optini.jl", "max_issues_repo_head_hexsha": "81e94ff764daa9819edae4b4b8211726a7de0821", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/algorithms/fibonacci.jl", "max_forks_repo_name": "lhnguyen-vn/Optini.jl", "max_forks_repo_head_hexsha": "81e94ff764daa9819edae4b4b8211726a7de0821", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-18T21:08:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-18T21:08:54.000Z", "avg_line_length": 30.3636363636, "max_line_length": 91, "alphanum_fraction": 0.5622754491, "num_tokens": 533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850057480346, "lm_q2_score": 0.8596637505099168, "lm_q1q2_score": 0.8048902795875545}} {"text": "export l1_distance, l2_distance, squared_l2_distance, linf_distance, lp_distance\n\n\"\"\" l1_distance computes the Manhattan's distance \"\"\"\nfunction l1_distance(a::AbstractVector{T}, b::AbstractVector{T})::Float64 where {T <: Real}\n d::T = zero(T)\n\n @fastmath @inbounds @simd for i = 1:length(a)\n\t m = a[i] - b[i]\n d += ifelse(m > 0, m, -m)\n end\n\n return d\nend\n\n\"\"\" l2_distance computes the Euclidean's distance \"\"\"\nfunction l2_distance(a::AbstractVector{T}, b::AbstractVector{T})::Float64 where {T <: Real}\n d::T = zero(T)\n\n @fastmath @inbounds @simd for i = 1:length(a)\n m = a[i] - b[i]\n d += m * m\n end\n\n return sqrt(d)\nend\n\n\"\"\" squared_l2_distance computes the Euclidean's distance but squared \"\"\"\nfunction squared_l2_distance(a::AbstractVector{T}, b::AbstractVector{T})::Float64 where {T <: Real}\n d::T = zero(T)\n\n @fastmath @inbounds @simd for i = 1:length(a)\n m = a[i] - b[i]\n d += m * m\n end\n\n return d\nend\n\n\n\"\"\" linf_distance computes the max distance \"\"\"\nfunction linf_distance(a::AbstractVector{T}, b::AbstractVector{T})::Float64 where {T <: Real}\n d::T = zero(T)\n\n @fastmath @inbounds @simd for i = 1:length(a)\n m = abs(a[i] - b[i])\n d = max(d, m)\n end\n\n return d\nend\n\n\"\"\"\nlp_distance creates a function that computes computes generic Minkowski's distance\n\"\"\"\nfunction lp_distance(p_::Real)\n p::Float64 = convert(Float64, p_)\n invp = 1.0 / p\n\n function _lp(a::AbstractVector{T}, b::AbstractVector{T})::Float64 where T\n d::T = zero(T)\n\n @fastmath @inbounds @simd for i = 1:length(a)\n m = abs(a[i] - b[i])\n d += m ^ p\n end\n\n d ^ invp\n end\nend\n\n", "meta": {"hexsha": "a64f6e1dc1d4927d376f35038f1f93926305385c", "size": 1711, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distances/vectors.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/SimilaritySearch.jl-053f045d-5466-53fd-b400-a066f88fe02a", "max_stars_repo_head_hexsha": "70c46490431ca7d0e5cf41052bc36afc4ba3c8fa", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/distances/vectors.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/SimilaritySearch.jl-053f045d-5466-53fd-b400-a066f88fe02a", "max_issues_repo_head_hexsha": "70c46490431ca7d0e5cf41052bc36afc4ba3c8fa", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/distances/vectors.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/SimilaritySearch.jl-053f045d-5466-53fd-b400-a066f88fe02a", "max_forks_repo_head_hexsha": "70c46490431ca7d0e5cf41052bc36afc4ba3c8fa", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0985915493, "max_line_length": 99, "alphanum_fraction": 0.6031560491, "num_tokens": 508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850075259039, "lm_q2_score": 0.8596637469145054, "lm_q1q2_score": 0.8048902777495944}} {"text": "# # Chebyshev center\n# Boyd & Vandenberghe, \"Convex Optimization\"\n# Joëlle Skaf - 08/16/05\n#\n# Adapted for Convex.jl by Karanveer Mohan and David Zeng - 26/05/14\n#\n# The goal is to find the largest Euclidean ball (i.e. its center and\n# radius) that lies in a polyhedron described by affine inequalites in this\n# fashion: $P = \\{x : a_i'*x \\leq b_i, i=1,\\ldots,m \\}$ where $x \\in \\mathbb{R}^2$.\n\nusing Convex, LinearAlgebra, SCS\n\n# Generate the input data\na1 = [ 2; 1];\na2 = [ 2; -1];\na3 = [-1; 2];\na4 = [-1; -2];\nb = ones(4, 1);\n\n# Create and solve the model\nr = Variable(1)\nx_c = Variable(2)\np = maximize(r)\np.constraints += a1' * x_c + r * norm(a1, 2) <= b[1];\np.constraints += a2' * x_c + r * norm(a2, 2) <= b[2];\np.constraints += a3' * x_c + r * norm(a3, 2) <= b[3];\np.constraints += a4' * x_c + r * norm(a4, 2) <= b[4];\nsolve!(p, () -> SCS.Optimizer(verbose=0))\np.optval\n\n# Generate the figure\nx = range(-1.5, stop=1.5, length=100);\ntheta = 0:pi/100:2*pi;\nusing Plots\nplot(x, x -> -x * a1[1] / a1[2] + b[1] / a1[2])\nplot!(x, x -> -x * a2[1]/ a2[2] + b[2] / a2[2])\nplot!(x, x -> -x * a3[1]/ a3[2] + b[3] / a3[2])\nplot!(x, x -> -x * a4[1]/ a4[2] + b[4] / a4[2])\nplot!(evaluate(x_c)[1] .+ evaluate(r) * cos.(theta), evaluate(x_c)[2] .+ evaluate(r) * sin.(theta), linewidth = 2)\nplot!(title =\"Largest Euclidean ball lying in a 2D polyhedron\", legend = nothing)\n", "meta": {"hexsha": "ca381a4ff0d17bc123b1de8c035529a160dff54c", "size": 1364, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/examples_literate/general_examples/chebyshev_center.jl", "max_stars_repo_name": "JinraeKim/Convex.jl", "max_stars_repo_head_hexsha": "f1ca69f69ed1ba820f3cd3ca966ebe5655bfec18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 123, "max_stars_repo_stars_event_min_datetime": "2020-06-16T21:56:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:05:39.000Z", "max_issues_repo_path": "docs/examples_literate/general_examples/chebyshev_center.jl", "max_issues_repo_name": "JinraeKim/Convex.jl", "max_issues_repo_head_hexsha": "f1ca69f69ed1ba820f3cd3ca966ebe5655bfec18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 122, "max_issues_repo_issues_event_min_datetime": "2020-06-14T00:19:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T14:02:09.000Z", "max_forks_repo_path": "docs/examples_literate/general_examples/chebyshev_center.jl", "max_forks_repo_name": "JinraeKim/Convex.jl", "max_forks_repo_head_hexsha": "f1ca69f69ed1ba820f3cd3ca966ebe5655bfec18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 22, "max_forks_repo_forks_event_min_datetime": "2020-08-21T07:56:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T13:40:50.000Z", "avg_line_length": 33.2682926829, "max_line_length": 114, "alphanum_fraction": 0.5923753666, "num_tokens": 572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850004144266, "lm_q2_score": 0.8596637523076225, "lm_q1q2_score": 0.8048902766856099}} {"text": "## This example comes from https://diffeqflux.sciml.ai/dev/Flux/\n\nusing ComponentArrays\nusing OrdinaryDiffEq\nusing Plots\nusing UnPack\n\nusing DiffEqFlux: sciml_train\nusing Flux: glorot_uniform, ADAM, σ, relu\nusing Optim: LBFGS\n\n\nstruct MeasurementNoise{T}\n sigma::T\nend\nBase.:(+)(array, mn::MeasurementNoise) = array .+ randn(size(array)...).*mn.sigma\n\n# Problem setup\nu0 = Float32[2.; 0.]\ndatasize = 50\ntspan = (0.0f0, 7f0)\ntspan2 = (0.0f0, 25f0)\n\n\n# Make truth data\nfunction trueODEfunc(du, u, p, t)\n true_A = [-0.1 2.0; -2.0 -0.1]\n du .= ((u.^3)'true_A)'\nend\n\nt = range(tspan[1], tspan[2], length = datasize)\n# t = Float32.(vcat(range(0.0, 0.9, length=10), 10 .^ range(log10(tspan[1]+1), log10(tspan[2]), length=datasize-10)))\nt = Float32.([0; 10 .^ range(log10(tspan[1] + 0.01), log10(tspan[2]), length=datasize-1)])\nprob = ODEProblem(trueODEfunc, u0, tspan2)\node_sol = solve(prob, Tsit5())\node_data = Array(ode_sol(t)) + MeasurementNoise(0.1)\n\n\n\n# Function for creating neural layer components\nneural_layer(in, out) = ComponentArray{Float32}(W=glorot_uniform(out, in), b=zeros(out))\n\n# Dense neural layer function\ndense(layer, activation=identity) = u -> activation.(layer.W * u + layer.b)\n\n# Neural ODE function \ndudt(u, p, t) = u.^3 |> dense(p.L1, σ) |> dense(p.L2)\n\nprob = ODEProblem(dudt, u0, tspan2)\n\n\n# Create optimization parameter vector\nn_hidden = 50\nlayers = (L1=neural_layer(2, n_hidden), L2=neural_layer(n_hidden, 2))\nθ = ComponentArray(u=u0, p=layers)\n\n\n# Prediction and loss functions\npredict_n_ode(θ) = Array(solve(prob, Tsit5(), u0=θ.u, p=θ.p, saveat=t))\nfull_sol(θ) = solve(prob, Tsit5(), u0=θ.u, p=θ.p)\n\nfunction loss_n_ode(θ)\n pred = predict_n_ode(θ)\n\n loss = sum(abs2, ode_data .- pred)/datasize + 0.1*(sum(abs, θ.p)/length(θ.p))\n return loss, pred\nend\nloss_n_ode(θ)\n\n\n# anim = Animation()\n\n # Callback function to observe training\ncb = function (θ, loss, pred; doplot=false)\n display(loss)\n # plot current prediction against data\n train_sol = full_sol(θ)\n\n pl_1 = plot(train_sol, vars=1)\n plot!(pl_1, ode_sol, vars=1)\n scatter!(pl_1, t, pred[1,:])\n scatter!(pl_1, t, ode_data[1,:], legend=false)\n\n pl_2 = plot(train_sol, vars=2)\n plot!(pl_2, ode_sol, vars=2)\n scatter!(pl_2, t, pred[2,:])\n scatter!(pl_2, t, ode_data[2,:], legend=false)\n\n pl_3 = plot(train_sol, vars=(1,2), label = \"prediction\")\n plot!(pl_3, ode_sol, vars=(1,2), label = \"truth\")\n scatter!(pl_3, pred[1,:], pred[2,:], label = \"predicted data\")\n scatter!(pl_3, ode_data[1,:], ode_data[2,:], label = \"measured data\")\n plot!(pl_3, hcat(pred[1,:], ode_data[1,:])', hcat(pred[2,:], ode_data[2,:])', label = false, color=:lightgray, legend=:bottomright)\n\n display(plot(plot(pl_1, pl_2, layout=(2,1), size=(400,500)), pl_3, layout=(1,2), size=(950,500)))\n # frame(anim)\n return false\nend\n\n\n# Display the ODE with the initial parameter values.\ncb(θ, loss_n_ode(θ)...)\n\ndata = Iterators.repeated((), 1000)\n\nres1 = sciml_train(loss_n_ode, θ, ADAM(0.05); maxiters=100, save_best=true, cb=cb)\ncb(res1.minimizer, loss_n_ode(res1.minimizer)...; doplot=true)\n\nres2 = sciml_train(loss_n_ode, res1.minimizer, LBFGS(), cb=cb)\ncb(res2.minimizer, loss_n_ode(res2.minimizer)...; doplot=true)\n\n# gif(anim, \"DiffEqFlux.gif\", fps=15)\n", "meta": {"hexsha": "aaa91f81cbbc214cad081a6e2c06a45591c01338", "size": 3277, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/DiffEqFlux_example.jl", "max_stars_repo_name": "scheidan/ComponentArrays.jl", "max_stars_repo_head_hexsha": "4a4eb3271c1efb8e724f108ec5cb4a3b9769c329", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 159, "max_stars_repo_stars_event_min_datetime": "2020-04-21T21:01:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:43:34.000Z", "max_issues_repo_path": "examples/DiffEqFlux_example.jl", "max_issues_repo_name": "scheidan/ComponentArrays.jl", "max_issues_repo_head_hexsha": "4a4eb3271c1efb8e724f108ec5cb4a3b9769c329", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 116, "max_issues_repo_issues_event_min_datetime": "2020-04-22T15:29:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T03:01:43.000Z", "max_forks_repo_path": "examples/DiffEqFlux_example.jl", "max_forks_repo_name": "scheidan/ComponentArrays.jl", "max_forks_repo_head_hexsha": "4a4eb3271c1efb8e724f108ec5cb4a3b9769c329", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2020-04-26T23:05:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T03:13:58.000Z", "avg_line_length": 29.0, "max_line_length": 135, "alphanum_fraction": 0.6679890143, "num_tokens": 1162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850057480347, "lm_q2_score": 0.8596637451167997, "lm_q1q2_score": 0.8048902745380598}} {"text": "# # Maximum a Posteriori\n\nusing Distributions\nusing HMMBase\nusing PyPlot\nusing Seaborn\n\nrc(\"axes\", xmargin = 0) # hide\nset_style(\"whitegrid\") # hide\n\n# Let's consider a simple time series with one outlier:\ny = rand(1000)\ny[100] = 10000\nfigure(figsize = (9,2)) # hide\nplot(y)\ngcf() # hide\n#-\n\n# An MLE approach for the observations distributions parameters\n# may fail with a singularity (variance = 0) if an outlier\n# becomes the only observation associated to some state:\nhmm = HMM([0.9 0.1; 0.1 0.9], [Normal(0,1), Normal(5,1)])\ntry\n fit_mle(hmm, y, display=:iter);\ncatch e\n println(e)\nend\n\n# We can avoid this by putting a prior on the variance:\nimport ConjugatePriors: InverseGamma, NormalKnownMu, posterior_canon\nimport StatsBase: Weights\n\nfunction fit_map(::Type{<:Normal}, observations, responsibilities)\n μ = mean(observations, Weights(responsibilities))\n\n ss = suffstats(NormalKnownMu(μ), observations, responsibilities)\n prior = InverseGamma(2,1)\n posterior = posterior_canon(prior, ss)\n σ2 = mode(posterior)\n\n Normal(μ, sqrt(σ2))\nend\n\nhmm, hist = fit_mle(hmm, y, estimator=fit_map, display=:iter)\nfigure(figsize = (4,3)) # hide\nplot(hist.logtots)\nxlabel(\"Iteration\") # hide\nylabel(\"Log-likelihood\") # hide\ngcf() # hide\n#-\n\nhmm.B\n", "meta": {"hexsha": "43e939ac881e880161b7443ffb870aabcb8e6822", "size": 1264, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/fit_map.jl", "max_stars_repo_name": "Shu-Lea-Lai/module-MultiHMMBase", "max_stars_repo_head_hexsha": "3d467458b498a2ba6b1c81eb4fee4467aeea121b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-28T18:51:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-28T18:51:59.000Z", "max_issues_repo_path": "examples/fit_map.jl", "max_issues_repo_name": "Shu-Lea-Lai/module-MultiHMMBase.jl", "max_issues_repo_head_hexsha": "3d467458b498a2ba6b1c81eb4fee4467aeea121b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/fit_map.jl", "max_forks_repo_name": "Shu-Lea-Lai/module-MultiHMMBase.jl", "max_forks_repo_head_hexsha": "3d467458b498a2ba6b1c81eb4fee4467aeea121b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8490566038, "max_line_length": 68, "alphanum_fraction": 0.7136075949, "num_tokens": 390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850039701653, "lm_q2_score": 0.8596637451167997, "lm_q1q2_score": 0.80489027300969}} {"text": "\"\"\"\nCumulative Distribution Function of a Standard Gaussian Random Variable\n\n\t\ty=normcdf(x)\n\nWhere:\\n\n\t\tx = point of evaluation.\n\n\t\ty = probability that a standard gaussian random variable is below x.\n\n# Example\n```julia-repl\njulia> normcdf(0.0)\n0.5\n```\n\"\"\"\nfunction normcdf(x::number) where {number <: Number}\n\treturn (1.0+erf(x/sqrt(2.0)))/2.0;\nend\n\n\"\"\"\nProbability Distribution Function of a Standard Gaussian Random Variable\n\n\t\ty=normpdf(x)\n\nWhere:\\n\n\t\tx = point of evaluation.\n\n\t\ty = value.\n\n# Example\n```julia-repl\njulia> normpdf(0.0)\n0.3989422804014327\n```\n\"\"\"\nfunction normpdf(x::number) where {number <: Number}\n\treturn exp(-0.5*x.^2)/sqrt(2*pi);\nend\n\n\"\"\"\nBlack & Scholes Price for European Options\n\n\t\tPrice=blsprice(S0,K,r,T,σ,d=0.0,FlagIsCall=true)\n\nWhere:\\n\n\t\tS0 = Value of the Underlying.\n\t\tK = Strike Price of the Option.\n\t\tr = Zero Rate.\n\t\tT = Time to Maturity of the Option.\n\t\tσ = Implied Volatility\n\t\td = Implied Dividend of the Underlying.\n\t\tFlagIsCall = true for Call Options, false for Put Options.\n\n\t\tPrice = price of the European Option.\n\n# Example\n```julia-repl\njulia> blsprice(10.0,10.0,0.01,2.0,0.2,0.01)\n1.1023600107733191\n```\n\"\"\"\nfunction blsprice(S0::num1,K::num2,r::num3,T::num4,σ::num5,d::num6=0.0,FlagIsCall::Bool=true) where {num1 <: Number ,num2 <: Number ,num3 <: Number ,num4 <: Number ,num5 <: Number ,num6 <: Number}\n\tblscheck(S0,K,r,T,σ,d);\n\td1=(log(S0/K)+(r-d+σ*σ*0.5)*T)/(σ*sqrt(T));\n\td2=d1-σ*sqrt(T);\n\tPrice=0.0;\n\tif FlagIsCall\n\tPrice=S0*exp(-d*T)*normcdf(d1)-K*exp(-r*T)*normcdf(d2);\n\telse\n\tPrice=-S0*exp(-d*T)*normcdf(-d1)+K*exp(-r*T)*normcdf(-d2);\n\tend\nreturn Price;\nend\n\n\n\"\"\"\nBlack Price for European Options\n\n\t\tPrice=blkprice(F0,K,r,T,σ,FlagIsCall=true)\n\nWhere:\\n\n\t\tF0 = Value of the Forward.\n\t\tK = Strike Price of the Option.\n\t\tr = Zero Rate.\n\t\tT = Time to Maturity of the Option.\n\t\tσ = Implied Volatility.\n\t\tFlagIsCall = true for Call Options, false for Put Options.\n\n\t\tPrice = price of the European Option.\n\n# Example\n```julia-repl\njulia> blkprice(10.0,10.0,0.01,2.0,0.2)\n1.1023600107733191\n```\n\"\"\"\nfunction blkprice(F0::num1,K::num2,r::num3,T::num4,σ::num5,FlagIsCall::Bool=true) where {num1 <: Number ,num2 <: Number ,num3 <: Number ,num4 <: Number ,num5 <: Number}\n\tblscheck(F0,K,r,T,σ);\n\tPrice=blsprice(F0,K,r,T,σ,r,FlagIsCall);\nreturn Price;\nend\n\n\n\"\"\"\nBlack & Scholes Delta for European Options\n\n\t\tΔ=blsdelta(S0,K,r,T,σ,d=0.0,FlagIsCall=true)\n\nWhere:\\n\n\t\tS0 = Value of the Underlying.\n\t\tK = Strike Price of the Option.\n\t\tr = Zero Rate.\n\t\tT = Time to Maturity of the Option.\n\t\tσ = Implied Volatility\n\t\td = Implied Dividend of the Underlying.\n\t\tFlagIsCall = true for Call Options, false for Put Options.\n\n\t\tΔ = delta of the European Option.\n\n# Example\n```julia-repl\njulia> blsdelta(10.0,10.0,0.01,2.0,0.2,0.01)\n0.5452173371920436\n```\n\"\"\"\nfunction blsdelta(S0::num1,K::num2,r::num3,T::num4,σ::num5,d::num6=0.0,FlagIsCall::Bool=true) where {num1 <: Number ,num2 <: Number ,num3 <: Number ,num4 <: Number ,num5 <: Number ,num6 <: Number}\n\tblscheck(S0,K,r,T,σ,d);\n\td1=(log(S0/K)+(r-d+σ*σ*0.5)*T)/(σ*sqrt(T));\n\tΔ=0.0;\n\tif FlagIsCall\n\tΔ=exp(-d*T)*normcdf(d1);\n\telse\n\tΔ=-exp(-d*T)*normcdf(-d1);\n\tend\nreturn Δ;\nend\n\n\n\"\"\"\nBlack & Scholes Gamma for European Options\n\n\t\tΓ=blsgamma(S0,K,r,T,σ,d=0.0,FlagIsCall=true)\n\nWhere:\\n\n\t\tS0 = Value of the Underlying.\n\t\tK = Strike Price of the Option.\n\t\tr = Zero Rate.\n\t\tT = Time to Maturity of the Option.\n\t\tσ = Implied Volatility\n\t\td = Implied Dividend of the Underlying.\n\t\tFlagIsCall = true for Call Options, false for Put Options.\n\n\t\tΓ = gamma of the European Option.\n\n# Example\n```julia-repl\njulia> blsgamma(10.0,10.0,0.01,2.0,0.2,0.01)\n0.13687881535712826\n```\n\"\"\"\nfunction blsgamma(S0::num1,K::num2,r::num3,T::num4,σ::num5,d::num6=0.0,FlagIsCall::Bool=true) where {num1 <: Number ,num2 <: Number ,num3 <: Number ,num4 <: Number ,num5 <: Number ,num6 <: Number}\n\tblscheck(S0,K,r,T,σ,d);\n\td1=(log(S0/K)+(r-d+σ*σ*0.5)*T)/(σ*sqrt(T));\n\tΓ=exp(-d*T)*normpdf(d1)/(S0*σ*sqrt(T));\nreturn Γ;\nend\n\n\n\"\"\"\nBlack & Scholes Vega for European Options\n\n\t\tν=blsvega(S0,K,r,T,σ,d=0.0,FlagIsCall=true)\n\nWhere:\\n\n\t\tS0 = Value of the Underlying.\n\t\tK = Strike Price of the Option.\n\t\tr = Zero Rate.\n\t\tT = Time to Maturity of the Option.\n\t\tσ = Implied Volatility\n\t\td = Implied Dividend of the Underlying.\n\t\tFlagIsCall = true for Call Options, false for Put Options.\n\n\t\tν = vega of the European Option.\n\n# Example\n```julia-repl\njulia> blsvega(10.0,10.0,0.01,2.0,0.2,0.01)\n5.475152614285131\n```\n\"\"\"\nfunction blsvega(S0::num1,K::num2,r::num3,T::num4,σ::num5,d::num6=0.0,FlagIsCall::Bool=true) where {num1 <: Number ,num2 <: Number ,num3 <: Number ,num4 <: Number ,num5 <: Number ,num6 <: Number}\n\tblscheck(S0,K,r,T,σ,d);\n\td1=(log(S0/K)+(r-d+σ*σ*0.5)*T)/(σ*sqrt(T));\n\tν=S0*exp(-d*T)*normpdf(d1)*sqrt(T);\nreturn ν;\nend\n\n\n\"\"\"\nBlack & Scholes Rho for European Options\n\n\t\tρ=blsrho(S0,K,r,T,σ,d=0.0,FlagIsCall=true)\n\nWhere:\\n\n\t\tS0 = Value of the Underlying.\n\t\tK = Strike Price of the Option.\n\t\tr = Zero Rate.\n\t\tT = Time to Maturity of the Option.\n\t\tσ = Implied Volatility\n\t\td = Implied Dividend of the Underlying.\n\t\tFlagIsCall = true for Call Options, false for Put Options.\n\n\t\tρ = rho of the European Option.\n\n# Example\n```julia-repl\njulia> blsrho(10.0,10.0,0.01,2.0,0.2,0.01)\n8.699626722294234\n```\n\"\"\"\nfunction blsrho(S0::num1,K::num2,r::num3,T::num4,σ::num5,d::num6=0.0,FlagIsCall::Bool=true) where {num1 <: Number ,num2 <: Number ,num3 <: Number ,num4 <: Number ,num5 <: Number ,num6 <: Number}\n\tblscheck(S0,K,r,T,σ,d);\n\td2=(log(S0/K)+(r-d-σ*σ*0.5)*T)/(σ*sqrt(T));\n\tif FlagIsCall\n\tρ=K*exp(-r*T)*normcdf(d2)*T;\n\telse\n\t\tρ=-K*exp(-r*T)*normcdf(-d2)*T;\n\tend\nreturn ρ;\nend\n\n\n\"\"\"\nBlack & Scholes Theta for European Options\n\n\t\tΘ=blstheta(S0,K,r,T,σ,d=0.0,FlagIsCall=true)\n\nWhere:\\n\n\t\tS0 = Value of the Underlying.\n\t\tK = Strike Price of the Option.\n\t\tr = Zero Rate.\n\t\tT = Time to Maturity of the Option.\n\t\tσ = Implied Volatility\n\t\td = Implied Dividend of the Underlying.\n\t\tFlagIsCall = true for Call Options, false for Put Options.\n\n\t\tΘ = theta of the European Option.\n\n# Example\n```julia-repl\njulia> blstheta(10.0,10.0,0.01,2.0,0.2,0.01)\n-0.26273403060652334\n```\n\"\"\"\nfunction blstheta(S0::num1,K::num2,r::num3,T::num4,σ::num5,d::num6=0.0,FlagIsCall::Bool=true) where {num1 <: Number ,num2 <: Number ,num3 <: Number ,num4 <: Number ,num5 <: Number ,num6 <: Number}\n\tblscheck(S0,K,r,T,σ,d);\n\tsqrtT = sqrt(T);\n\tσ_sqrtT = σ .* sqrtT;\n\t\n\td1 = (log(S0 ./ K) + (r - d + σ.^2 / 2) .* T)./ σ_sqrtT;\n\t\n\tshift = -exp(-d .* T) .* S0 .* normpdf(d1) .* σ / 2 ./ sqrtT;\n\tt1 = r .* K .* exp(-r .* T);\n\tt2 = d .* S0 .* exp(-d .* T);\n\tΘ=0.0;\n\tif FlagIsCall\n\t\tΘ=shift - t1 .* normcdf(d1 - σ_sqrtT) + t2 .* normcdf(d1) ;\n\telse\n\t\tΘ=shift + t1 .* (1 - normcdf(d1 - σ_sqrtT)) + t2 .* (normcdf(d1) - 1);\n\tend\nreturn Θ;\nend\n\n\n\"\"\"\nBlack & Scholes Lambda for European Options\n\n\t\tΛ=blslambda(S0,K,r,T,σ,d=0.0,FlagIsCall=true)\n\nWhere:\\n\n\t\tS0 = Value of the Underlying.\n\t\tK = Strike Price of the Option.\n\t\tr = Zero Rate.\n\t\tT = Time to Maturity of the Option.\n\t\tσ = Implied Volatility\n\t\td = Implied Dividend of the Underlying.\n\t\tFlagIsCall = true for Call Options, false for Put Options.\n\n\t\tΛ = lambda of the European Option.\n\n# Example\n```julia-repl\njulia> blslambda(10.0,10.0,0.01,2.0,0.2,0.01)\n4.945909973725978\n```\n\"\"\"\nfunction blslambda(S0::num1,K::num2,r::num3,T::num4,σ::num5,d::num6=0.0,FlagIsCall::Bool=true) where {num1 <: Number ,num2 <: Number ,num3 <: Number ,num4 <: Number ,num5 <: Number ,num6 <: Number}\n\tblscheck(S0,K,r,T,σ,d);\n\tPrice=blsprice(S0,K,r,T,σ,d,FlagIsCall);\n\tΔ=blsdelta(S0,K,r,T,σ,d,FlagIsCall);\n\tΛ=Δ*S0/Price;\nreturn Λ;\nend\n\n\n\"Check input for Black Scholes Formula\"\nfunction blscheck(S0::num1,K::num2,r::num3,T::num4,σ::num5,d::num6=0.0) where {num1 <: Number ,num2 <: Number ,num3 <: Number ,num4 <: Number ,num5 <: Number ,num6 <: Number}\nlesseq(x::Complex,y::Complex) = real(x) <= real(y)\nlesseq(x,y) = x <= y\nif (lesseq(S0,zero(num1)))\n\terror(\"Spot Price Cannot Be Negative\")\nelseif (lesseq(K,zero(num2)))\n\terror(\"Strike Price Cannot Be Negative\")\nelseif (lesseq(T,zero(num4)))\n\terror(\"Time to Maturity Cannot Be Negative\")\nelseif (lesseq(σ,zero(num5)))\n\terror(\"Volatility Cannot Be Negative\")\nend\nreturn;\nend\n\n\"Brent Method: Scalar Equation Solver\"\nfunction brentMethod(f::Function, x0::Number, x1::Number,xtol::AbstractFloat=1e-14, ytol::AbstractFloat=1e-15)\n\t\tif xtol<0.0\n\t\t throw(ErrorException(\"x tollerance cannot be negative\"));\n\t\tend\n\tif ytol<0.0\n\t\t throw(ErrorException(\"y tollerance cannot be negative\"));\n\t\tend\n\t\tEPS = eps(x0)\n\tmaxiter=80;\n\t\ty0 = f(x0)\n\t\ty1 = f(x1)\n\t\tif abs(y0) < abs(y1)\n\t\t # Swap lower and upper bounds.\n\t\t x0, x1 = x1, x0\n\t\t y0, y1 = y1, y0\n\t\tend\n\t\tx2 = x0\n\t\ty2 = y0\n\t\tx3 = x2\n\t\tbisection = true\n\t\tfor _ in 1:maxiter\n\t\t # x-tolerance.\n\t\t if abs(x1-x0) < xtol\n\t\t return x1\n\t\t end\n\n\t\t # Use inverse quadratic interpolation if f(x0)!=f(x1)!=f(x2)\n\t\t # and linear interpolation (secant method) otherwise.\n\t\t if abs(y0-y2) > ytol && abs(y1-y2) > ytol\n\t\t x = x0*y1*y2/((y0-y1)*(y0-y2)) +\n\t\t x1*y0*y2/((y1-y0)*(y1-y2)) +\n\t\t x2*y0*y1/((y2-y0)*(y2-y1))\n\t\t else\n\t\t x = x1 - y1 * (x1-x0)/(y1-y0)\n\t\t end\n\n\t\t # Use bisection method if satisfies the conditions.\n\t\t delta = abs(2EPS*abs(x1))\n\t\t min1 = abs(x-x1)\n\t\t min2 = abs(x1-x2)\n\t\t min3 = abs(x2-x3)\n\t\t if (x < (3x0+x1)/4 && x > x1) ||\n\t\t (bisection && min1 >= min2/2) ||\n\t\t (!bisection && min1 >= min3/2) ||\n\t\t (bisection && min2 < delta) ||\n\t\t (!bisection && min3 < delta)\n\t\t x = (x0+x1)/2\n\t\t bisection = true\n\t\t else\n\t\t bisection = false\n\t\t end\n\t\t y = f(x)\n\t\t # y-tolerance.\n\t\t if abs(y) < ytol\n\t\t return x\n\t\t end\n\t\t x3 = x2\n\t\t x2 = x1\n\t\t if sign(y0) != sign(y)\n\t\t x1 = x\n\t\t y1 = y\n\t\t else\n\t\t x0 = x\n\t\t y0 = y\n\t\t end\n\t\t if abs(y0) < abs(y1)\n\t\t # Swap lower and upper bounds.\n\t\t x0, x1 = x1, x0\n\t\t y0, y1 = y1, y0\n\t\t end\n\t\tend\n\t\tthrow(ErrorException(\"Max iteration exceeded, possible wrong result\"));\nend\n\nexport blsimpv\n\"\"\"\nBlack & Scholes Implied Volatility for European Options\n\n\t\tσ=blsimpv(S0,K,r,T,Price,d=0.0,FlagIsCall=true,xtol=1e-14,ytol=1e-15)\n\nWhere:\\n\n\t\tS0 = Value of the Underlying.\n\t\tK = Strike Price of the Option.\n\t\tr = Zero Rate.\n\t\tT = Time to Maturity of the Option.\n\t\tPrice = Price of the Option.\n\t\td = Implied Dividend of the Underlying.\n\t\tFlagIsCall = true for Call Options, false for Put Options.\n\n\t\tσ = implied volatility of the European Option.\n\n# Example\n```julia-repl\njulia> blsimpv(10.0,10.0,0.01,2.0,2.0)\n0.3433730534290586\n```\n\"\"\"\nfunction blsimpv(S0::num1,K::num2,r::num3,T::num4,Price::num5,d::num6=0.0,FlagIsCall::Bool=true,xtol::Real=1e-14,ytol::Real=1e-15) where {num1 <: Real ,num2 <: Real ,num3 <: Real ,num4 <: Real ,num5 <: Real ,num6 <: Real}\nif (Price< num5(0))\n\tthrow(ErrorException(\"Option Price Cannot Be Negative\"));\nend\nblscheck(S0,K,r,T,0.1,d);\nf(x)=(blsprice(S0,K,r,T,x,d,FlagIsCall)-Price);\nσ=brentMethod(f,0.001,1.2,xtol,ytol);\n\nreturn σ;\nend\n\nexport blkimpv\n\"\"\"\nBlack Implied Volatility for European Options\n\n\t\tσ=blkimpv(F0,K,r,T,Price,FlagIsCall=true,xtol=1e-14,ytol=1e-15)\n\nWhere:\\n\n\t\tF0 = Value of the Forward.\n\t\tK = Strike Price of the Option.\n\t\tr = Zero Rate.\n\t\tT = Time to Maturity of the Option.\n\t\tPrice = Price of the Option.\n\t\tFlagIsCall = true for Call Options, false for Put Options.\n\n\t\tσ = implied volatility of the European Option.\n\n# Example\n```julia-repl\njulia> blkimpv(10.0,10.0,0.01,2.0,2.0)\n0.36568658096623635\n```\n\"\"\"\nfunction blkimpv(F0::num1,K::num2,r::num3,T::num4,Price::num5,FlagIsCall::Bool=true,xtol::Real=1e-14,ytol::Real=1e-15) where {num1 <: Real ,num2 <: Real ,num3 <: Real ,num4 <: Real ,num5 <: Real}\n\tblscheck(F0,K,r,T,0.1);\n\tσ=blsimpv(F0,K,r,T,Price,r,FlagIsCall,xtol,ytol)\n\treturn σ;\nend\n\n##\tADDITIONAL Function\n\n\"\"\"\nBlack & Scholes Psi for European Options\n\n\t\tΨ=blspsi(S0,K,r,T,σ,d=0.0,FlagIsCall=true)\n\nWhere:\\n\n\t\tS0 = Value of the Underlying.\n\t\tK = Strike Price of the Option.\n\t\tr = Zero Rate.\n\t\tT = Time to Maturity of the Option.\n\t\tσ = Implied Volatility\n\t\td = Implied Dividend of the Underlying.\n\t\tFlagIsCall = true for Call Options, false for Put Options.\n\n\t\tΨ = psi of the European Option.\n\n# Example\n```julia-repl\njulia> blspsi(10.0,10.0,0.01,2.0,0.2,0.01)\n-10.904346743840872\n```\n\"\"\"\nfunction blspsi(S0::num1,K::num2,r::num3,T::num4,σ::num5,d::num6=0.0,FlagIsCall::Bool=true) where {num1 <: Number ,num2 <: Number ,num3 <: Number ,num4 <: Number ,num5 <: Number ,num6 <: Number}\n\tblscheck(S0,K,r,T,σ,d);\n\td1=(log(S0/K)+(r-d+σ*σ*0.5)*T)/(σ*sqrt(T));\n\tif FlagIsCall\n\tΨ=-S0*exp(-d*T)*normcdf(d1)*T;\n\telse\n\t\tΨ=S0*exp(-d*T)*normcdf(-d1)*T;\n\tend\nreturn Ψ;\nend\n\n\n\"\"\"\nBlack & Scholes Vanna for European Options\n\n\t\tVanna=blsvanna(S0,K,r,T,σ,d=0.0,FlagIsCall=true)\n\nWhere:\\n\n\t\tS0 = Value of the Underlying.\n\t\tK = Strike Price of the Option.\n\t\tr = Zero Rate.\n\t\tT = Time to Maturity of the Option.\n\t\tσ = Implied Volatility\n\t\td = Implied Dividend of the Underlying.\n\t\tFlagIsCall = true for Call Options, false for Put Options.\n\n\t\tVanna = vanna of the European Option.\n\n# Example\n```julia-repl\njulia> blsvanna(10.0,10.0,0.01,2.0,0.2,0.01)\n0.2737576307142566\n```\n\"\"\"\nfunction blsvanna(S0::num1,K::num2,r::num3,T::num4,σ::num5,d::num6=0.0,FlagIsCall::Bool=true) where {num1 <: Number ,num2 <: Number ,num3 <: Number ,num4 <: Number ,num5 <: Number ,num6 <: Number}\n\tblscheck(S0,K,r,T,σ,d);\n\td1=(log(S0/K)+(r-d+σ*σ*0.5)*T)/(σ*sqrt(T));\n\td2=d1-σ*sqrt(T);\n\tVanna=-exp(-d*T)*normpdf(d1)*d2/σ;\nreturn Vanna;\nend\n", "meta": {"hexsha": "9fbdd4583e9b4c208150aecc295228f09a135a74", "size": 14305, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/financial.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/FinancialToolbox.jl-2edd74a5-e968-5e45-af77-76d29aa6a478", "max_stars_repo_head_hexsha": "2b3d7374cafb21d47749d6312e839e438507c0cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-01-28T15:31:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-28T15:31:39.000Z", "max_issues_repo_path": "src/financial.jl", "max_issues_repo_name": "shintaeksoo/FinancialToolbox.jl", "max_issues_repo_head_hexsha": "1ae1bfe5b2854dfb3c1218d4ece79540bb31da6f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/financial.jl", "max_forks_repo_name": "shintaeksoo/FinancialToolbox.jl", "max_forks_repo_head_hexsha": "1ae1bfe5b2854dfb3c1218d4ece79540bb31da6f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2476190476, "max_line_length": 221, "alphanum_fraction": 0.6091576372, "num_tokens": 5185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067195846918, "lm_q2_score": 0.853912760387131, "lm_q1q2_score": 0.8048185146039838}} {"text": "function compute()\r\n\tnumer=1\r\n\tdenom=1\r\n\r\n\tfor d=10:99\r\n\t\tfor n =10:d-1\r\n\t\t\tn0=n%10\r\n\t\t\tn1=Int((n-n0)/10)\r\n\t\t\td0=d%10\r\n\t\t\td1=Int((d-d0)/10)\r\n\t\t\tif (n1==d0 && n0*d==n*d1)||(n0==d1&&n1*d==n*d0)\r\n\t\t\t\tnumer*=n\r\n\t\t\t\tdenom*=d\r\n\t\t\tend\r\n\t\tend\r\n\tend\r\n\r\n\treturn Int(denom/gcd(numer,denom))\r\nend\r\n\r\n\r\nprintln(compute())\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "214db2ce0a3d611c68aa12aaa286f6787d252f74", "size": 323, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/p033.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/p033.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/p033.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.1379310345, "max_line_length": 51, "alphanum_fraction": 0.4953560372, "num_tokens": 142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067211996141, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.8048185072230619}} {"text": "# # Introduciton to Lotka-Volterra Competition\n\nusing Parameters\nusing DifferentialEquations\nusing ForwardDiff\nusing Plots\npyplot();\n\n# # Introduction/Overview\n# This notebook is simply looking at the two species L-V competiti9on model. Here, we are exploring\n# the geometry and dynamics of this model.\n#\n# # Model and Equilibria\n# The model we will use is the classical LV competition model:\n\ninclude(\"lv_model.jl\")\n\n# # Evaluationg the model -- time series\n\nlet\n u0 = [0.5, 0.5]\n t_span = (0.0, 100.0)\n p = LVPar()\n\n prob = ODEProblem(lv_comp, u0, t_span, p)\n sol = solve(prob, reltol = 1e-8)\n\n plot(sol)\n xlabel!(\"time\")\n ylabel!(\"Density\")\nend\n\n# # Equilibria and Isoclines\n# From the above equations we can generate the Jacobian:\n\n# Make a numerical (not symbolic version using the ForwardDiff.jl library.\n# This is what you will want to do most of the time)\njac(u, p) = ForwardDiff.jacobian(u -> lv_comp(u, p, NaN), u)\n\n# Here we have the jacobian evaluated at the point `u = [0.5, 0.5]`, with the parameter set `par`\njac([0.5, 0.5], LVPar())\n\n# First solve for $f_1$ and $f_2$ to determine when functions are equal to 0 (i.e., when $du_1/dt$\n# and $du_2/dt = 0$). These are known as the isoclines, or nullclines, and describe the set of\n# solutions when $u_1$ and $u_2$ do not change.\n\ninclude(\"lv_symbolic.jl\")\n\n# We want to solve our equations for $u_1$ so that we can plot the isoclines as a function of $u_1$\n# ($u_1$ on the y-axis), but here I am keeping all possible solutions, with respect to both $u_1$\n# and $u_2$. You should be able to see that the first two solutions ($u_1 = K_1 - \\alpha_{12}u_2$\n# and $u_2 = (K_1 - u_1)/\\alpha_{12}$) are equivalent.\n#\n# The solutions $u_1 = K_1 - \\alpha_{12}u_2$ and $u_1 = (K_2 - u_2)/\\alpha_{21}$ are the equations\n# for our isoclines for $du_1/dt = 0$ and $du_2/dt = 0$, respectively. We can find the interior\n# equilibrium where these lines intersect (i.e., both $u_1$ and $u_2$ do not change). In this case\n# we get one interior equilibrium, but note that in more complicated models we can get more interior\n# equilibria.\n\n# # Now plot the isoclines\n# We will again use the manipulate function to see how our parameters change the isoclines. This can\n# immediately tell us a lot about our equilibria and stability.\n\nfunction iso1(u2, p)\n @unpack α12, K1 = p\n return K1 - α12 * u2 / K1\nend\n#-\nfunction iso2(u2, p)\n @unpack α21, K2 = p\n return (K2 - u2) / α21\nend\n#-\nlet\n p = LVPar()\n u2s = range(0, 5, length = 100)\n\n fig = plot(u2s, [iso1(u2, p) for u2 in u2s], label = \"u1 = 0\")\n plot!(u2s, [iso2(u2, p) for u2 in u2s], label = \"u2 = 0\")\n xlims!(0, 3)\n ylims!(0, 5)\n xlabel!(\"u2\")\n ylabel!(\"u1\")\nend\n", "meta": {"hexsha": "0448198cc3cc95117d5aec2dbfeda4811c283d37", "size": 2722, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/julia/lv_comp/lv_comp.jl", "max_stars_repo_name": "McCannLab/TheoryClub", "max_stars_repo_head_hexsha": "bc11de9951d727dc071c99ea6283a5a7d83af2ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/julia/lv_comp/lv_comp.jl", "max_issues_repo_name": "McCannLab/TheoryClub", "max_issues_repo_head_hexsha": "bc11de9951d727dc071c99ea6283a5a7d83af2ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-09-30T22:48:02.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-30T22:48:02.000Z", "max_forks_repo_path": "src/julia/lv_comp/lv_comp.jl", "max_forks_repo_name": "McCannLab/TheoryClub", "max_forks_repo_head_hexsha": "bc11de9951d727dc071c99ea6283a5a7d83af2ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-03-25T13:01:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-25T13:01:31.000Z", "avg_line_length": 32.0235294118, "max_line_length": 100, "alphanum_fraction": 0.6770756796, "num_tokens": 910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250327, "lm_q2_score": 0.8688267694452331, "lm_q1q2_score": 0.8047974739811767}} {"text": "module LinearShiftRegisters\n\nexport LSR_period, LCG_period\n\nfunction _repeated_substring(source)\n\tlen = length(source)\n\t\n\t# had to account for weird edge case in which length 2 vectors always returns themselves\n\tif len < 3\n\t\tlen == 1 && return nothing\n\t\n\t\ts1, s2 = source\n\t\tif len == 2 && s1 == s2\n\t\t\treturn s1\n\t\telse\n\t\t\treturn nothing\n\t\tend\n\tend\n\t\n\t# Check candidate strings\n\tfor i in 1:(len ÷ 2 + 1)\n\t\trepeat_count, remainder = divrem(len, i)\n\t\t\n\t\t# Check for no leftovers characters, and equality when repeated\n\t\tif remainder == 0 && source == repeat(source[1:i], repeat_count)\n\t\t\treturn source[1:i]#, repeat_count\n\t\tend\n\tend\n\t\n\treturn nothing\nend\n\nfunction _LSR_period(const_vec::AbstractVector, init_vec::AbstractVector)\n\tsequence_vec = reverse(init_vec)\n\n\tres = nothing\n\twhile isnothing(res)\n\t\tnew_val = mod(sum(map(i -> const_vec[i] * sequence_vec[end - (i - 1)], 1:4)), 2)\n\t\tpush!(sequence_vec, new_val)\n\t\tres = _repeated_substring(sequence_vec)\n\tend\n\t\n\treturn res\nend\n\n@doc raw\"\"\"\n```julia\nLSR_period(const_str::AbstractVector{T}, init_str::AbstractVector{R}) where {T, R <: Integer} -> AbstractVector\nLSR_period(const_str::AbstractString, init_str::AbstractString) -> String\n```\n\nGiven a starting binary string (`init_str`) and a constant mutating string (`const_str`), `LSR_period` will find the repeating sequence generated from these.\n\n!!! note\n\n As this method looks for recurring sequences, it is possible that this function does not terminate—or maybe it does terminate, but I haven't waited long enough to find out.\n\n\n---\n\n### Description\n\nA (linear) shift register with feedback is an arrangement of registers in a row, each register being capable of holding either the digit 1 (on) or 0 (off). Suppose the system has ``n`` registers, ``R_1,\\ldots,R_n``, and ``X_i(t)`` denotes the content of register ``R_i`` at time ``t``. Initially, let the system be given\n\nGiven\n\n### Examples\n\n```julia\njulia> LSR_period(\"1001\", \"0100\")\n\"001000111101011\"\n\njulia> LSR_period(\"1001\", \"0101\")\n\"101011001000111\"\n```\n\"\"\"\nfunction LSR_period(const_vec::AbstractVector{T}, init_vec::AbstractVector{R}) where {T, R <: Integer}\n\treturn _LSR_period(const_vec, init_vec)\nend\nfunction LSR_period(const_str::AbstractString, init_str::AbstractString)\n\tconst_vec = parse.(Int8, collect(const_str))\n\tinit_vec = parse.(Int8, collect(init_str))\n\t\n\treturn join(_LSR_period(const_vec, init_vec))\nend\n\nfunction _LCG_period(m::Integer, a::Integer, b::Integer, x0::T) where {T <: Integer}\n\tsequence_vec = T[x0]\n\n\tnew_x, res = x0, nothing\n\twhile isnothing(res)\n\t\tnew_x = mod(a * new_x + b, m)\n\t\tpush!(sequence_vec, new_x)\n\t\tres = _repeated_substring(sequence_vec)\n\tend\n\n\treturn res\nend\n\n@doc raw\"\"\"\n```julia\nLCG_period(m::Integer, a::Integer, b::Integer, x0::Integer) -> String\n```\n\nGiven `m`, `a`, `b`, and `x0`, finds the period generated by these parameters from a Linear Congruential Generator, and returns this sequence as a string.\n\n!!! note\n\n As this method looks for recurring sequences, it is possible that this function does not terminate—or maybe it does terminate, but I haven't waited long enough to find out.\n\n\n---\n\n### Description\n\nChoose m, a positive integer. Choose a, b (mod m) integers.\n\nThe Linear Congruential Generator is given to us by\n\n```math\nx_1 \\equiv ax_0+b\\mod m\\\\\nx_2 \\equiv ax_1+b\\mod m\\\\\n\\vdots\\\\\nx_{n + 1} \\equiv ax_n + b \\mod m\\\\\n\\vdots\n```\n\nEventually, ``x_n = x_i`` for some ``n``, ``i`` (let's suppose ``n>i`` and ``i`` is not necessarily ``0``). Then, clearly,\n\n```math\nx_{n+1} = x_{i+1},\\ldots.\n```\n\nSo\n\n```math\nx_i, x_{i+1},\\dots, x_{n-1}\n```\n\nWill be repeated forever.\n\nFrom a cryptography point of view, LCG is too vulnerable (although all pseudorandom number generators are vulnerable), but it is still useful for other perposes that require pseudorandom numbers.\n\nFor essentially a more sophisticated version of LCG in the sense that it is based on recurring linear relations, see `LSR_period`.\n\n---\n\n### Examples\n\n```julia\njulia> println(LinearShiftRegisters._LCG_period(9, 5, 2, 0))\n[0, 2, 3, 8, 6, 5]\n\njulia> LCG_period(9, 5, 2, 0)\n\"023865\"\n```\n\"\"\"\nfunction LCG_period(m::Integer, a::Integer, b::Integer, x0::Integer)\n\treturn join(_LCG_period(m, a, b, x0))\nend\n\nend # end module\n", "meta": {"hexsha": "f062db121836c60dcbc720d9ee50440ad59351f3", "size": 4220, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/LinearShiftRegisters.jl", "max_stars_repo_name": "jakewilliami/LinearShiftRegisters.jl", "max_stars_repo_head_hexsha": "d6335daebcce508b8fc78ab7d0d54f8e4c719916", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-01-08T13:27:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-07T21:29:32.000Z", "max_issues_repo_path": "src/LinearShiftRegisters.jl", "max_issues_repo_name": "jakewilliami/LinearShiftRegisters.jl", "max_issues_repo_head_hexsha": "d6335daebcce508b8fc78ab7d0d54f8e4c719916", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-01-27T23:21:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-17T04:02:16.000Z", "max_forks_repo_path": "src/LinearShiftRegisters.jl", "max_forks_repo_name": "jakewilliami/LinearShiftRegisters.jl", "max_forks_repo_head_hexsha": "d6335daebcce508b8fc78ab7d0d54f8e4c719916", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8895705521, "max_line_length": 322, "alphanum_fraction": 0.7097156398, "num_tokens": 1225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765328159726, "lm_q2_score": 0.8807970732843033, "lm_q1q2_score": 0.8047636160328584}} {"text": "\"\"\"\nlsnormal(A,b)\n\nSolve a linear least squares problem by the normal equations.\nReturns the minimizer of ||b-Ax||.\n\"\"\"\nfunction lsnormal(A,b)\n\nN = A'*A; z = A'*b;\nR = cholesky(N).U\nw = forwardsub(R',z) # solve R'z=c\nx = backsub(R,w) # solve Rx=z\n\nreturn x\nend\n\n\n\"\"\"\nlsqrfact(A,b)\n\nSolve a linear least squares problem by QR factorization. Returns\nthe minimizer of ||b-Ax||.\n\"\"\"\nfunction lsqrfact(A,b)\n\nQ,R = qr(A)\nc = Q'*b\nx = backsub(R,c)\n\nreturn x\nend\n\n\"\"\"\nqrfact(A)\n\nQR factorization by Householder reflections. Returns Q and R.\n\"\"\"\nfunction qrfact(A)\n\n m,n = size(A)\n Qt = Matrix(Diagonal(ones(m)))\n R = float(copy(A))\n for k in 1:n\n z = R[k:m,k]\n v = [ -sign(z[1])*norm(z) - z[1]; -z[2:end] ]\n nrmv = norm(v)\n if nrmv < eps() continue; end # skip this iteration\n v = v / nrmv; # simplifies other formulas\n # Apply the reflection to each relevant column of A and Q\n for j in 1:n\n R[k:m,j] -= v*( 2*(v'*R[k:m,j]) )\n end\n for j in 1:m\n Qt[k:m,j] -= v*( 2*(v'*Qt[k:m,j]) )\n end\n end\n \n return Qt',triu(R)\nend\n ", "meta": {"hexsha": "b6b56172663851256148891812331791041d0b53", "size": 1159, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chapter03.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/chapter03.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/chapter03.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": 19.3166666667, "max_line_length": 65, "alphanum_fraction": 0.5401207938, "num_tokens": 380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305328688783, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.8047632565930509}} {"text": "# Runs a simple Metropolis-Hastings (ie MCMC) algoritm to simulate two \n# jointly distributed random variuables with probability density\n# p(x,y)=exp(-(x^2+y^2)/s^2)/consNorm, where s>0 and consNorm is a\n# normalization constant.\n#\n# Author: H. Paul Keeler, 2019.\n# Website: hpaulkeeler.com\n# Repository: github.com/hpaulkeeler/posts\n\n#Note: Need the .+ for adding a scalar to an array\n#Also need . for sqrt, exp, cos, sin etc and assinging scalars to arrays\n\nusing Distributions #for random simulations\nusing PyPlot #for plotting\nusing StatsBase #for histograms etc\nusing Random\nusing LinearAlgebra\nusing HCubature #for numerical integration\n#using LaTeXStrings #for LateX in labels/titles etc\nPyPlot.close(\"all\"); # close all PyPlot figures\n\n#set random seed for reproducibility\n#Random.seed!(1234)\n\n# Simulation window parameters\nxMin = -1;\nxMax = 1;\nyMin = -1;\nyMax = 1;\n\nnumbSim = 10 ^ 5; # number of random variables simulated\nnumbSteps = 25; # number of steps for the Markov process\nnumbBins = 50; # number of bins for histogram\nsigma = 2; # standard deviation for normal random steps\n\n# probability density parameters\ns = .5; # scale parameter for distribution to be simulated\n\nfunction fun_lambda(x,y)\n return (exp.(-(x.^2+y.^2)./s^2));\nend\n\n#normalization constant -- UNDER CONSTRUCTION\nconsNorm,errorCub=hcubature(x -> fun_lambda(x[1],x[2]), [xMin, yMin], [xMax, yMax]);\n\nfunction fun_p(x,y)\n return((fun_lambda(x,y)./consNorm).*(x.>=xMin).*(y.>=yMin).*(x.<=xMax).*(y.<=yMax));\nend\nxRand=(xMax-xMin).*rand(numbSim).+xMin; #random initial values\nyRand=(yMax-yMin).*rand(numbSim).+yMin; #random initial values\n\nprobCurrent=fun_p(xRand,yRand); #current transition probabilities\nfor jj=1:numbSteps\n zxRand= xRand.+sigma.*rand(Normal(),numbSim);#take a (normally distributed) random step\n zyRand= yRand.+sigma.*rand(Normal(),numbSim);#take a (normally distributed) random step\n\n # Conditional random step needs to be symmetric in x and y\n # For example: Z|x ~ N(x,1) (or Y=x+N(0,1)) with probability density\n # p(z|x)=e(-(z-x)^2/2)/sqrt(2*pi)\n probProposal = fun_p(zxRand, zyRand); # proposed probability\n\n # acceptance rejection step\n booleAccept=rand(numbSim) .< probProposal./probCurrent;\n # update state of random walk/Marjov chain\n xRand[booleAccept] = zxRand[booleAccept];\n yRand[booleAccept] = zyRand[booleAccept];\n # update transition probabilities\n probCurrent[booleAccept] = probProposal[booleAccept];\nend\n\n#histogram section: empirical probability density\nhistXY=fit(Histogram, (xRand,yRand),nbins=numbBins); #find histogram data\nhistXY=normalize(histXY,mode=:pdf); #normalize histogram\nbinEdges=histXY.edges; #retrieve bin edges\nxValues=(binEdges[1][2:end]+binEdges[1][1:end-1])./2; #mid-points of bins\nyValues=(binEdges[2][2:end]+binEdges[2][1:end-1])./2; #mid-points of bins\np_Estimate=(histXY.weights)\n#create a meshgrid\nX=[xValues[ii] for ii=1:length(xValues), jj=1:length(yValues)];\nY=[yValues[jj] for ii=1:length(xValues), jj=1:length(yValues)];\n\n#analytic solution of probability density\np_Exact = fun_p(X, Y);\n\n# Plotting\n# Plot empirical estimate\nfig1 = PyPlot.figure();\nPyPlot.rc(\"text\", usetex=true);\nPyPlot.rc(\"font\", family=\"serif\");\nsurf(X, Y, p_Estimate, cmap=PyPlot.cm.plasma);\nPyPlot.xlabel(\"x\");\nPyPlot.ylabel(\"y\");\nPyPlot.title(\"p(x,y) Estimate\");\n\n# Plot exact expression\nfig2 = PyPlot.figure();\nPyPlot.rc(\"text\", usetex=true);\nPyPlot.rc(\"font\", family=\"serif\")\nsurf(X, Y, p_Exact, cmap=PyPlot.cm.plasma);\nPyPlot.xlabel(\"x\");\nPyPlot.ylabel(\"y\");\nPyPlot.title(\"p(x,y) Exact Expression\");\n\n#println(\"The program has completed.\")\n", "meta": {"hexsha": "f69c0591477a1ce88725d41440778d5a6d5e2c0d", "size": 3617, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "MCMC/MCMC_2D.jl", "max_stars_repo_name": "hpkeeler/posts", "max_stars_repo_head_hexsha": "a45c951bcccca3061276b2576e2568560f4bffdd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2020-05-14T12:14:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T15:22:09.000Z", "max_issues_repo_path": "MCMC/MCMC_2D.jl", "max_issues_repo_name": "hpkeeler/posts", "max_issues_repo_head_hexsha": "a45c951bcccca3061276b2576e2568560f4bffdd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MCMC/MCMC_2D.jl", "max_forks_repo_name": "hpkeeler/posts", "max_forks_repo_head_hexsha": "a45c951bcccca3061276b2576e2568560f4bffdd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2019-10-26T01:22:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T17:33:40.000Z", "avg_line_length": 34.4476190476, "max_line_length": 91, "alphanum_fraction": 0.7240807299, "num_tokens": 1102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240090865198, "lm_q2_score": 0.8577681122619883, "lm_q1q2_score": 0.8046928603417925}} {"text": "# In this tutorial, we will learn\n# - How to solve a simple nonlinear PDE in Gridap\n# - How to define the weak residual and its Jacobian\n# - How to setup and use a nonlinear solver\n# - How to define new boundaries from a given discrete model\n#\n# ## Problem statement\n#\n# The goal of this tutorial is to solve a nonlinear PDE in Gridap. For the sake of simplicity, we consider the $p$-Laplacian equation as the model problem. Specifically, the PDE we want to solve is: find the scalar-field $u$ such that\n#\n# ```math\n# \\left\\lbrace\n# \\begin{aligned}\n# -\\nabla \\cdot \\left( |\\nabla u|^{p-2} \\ \\nabla u \\right) = f\\ &\\text{in}\\ \\Omega,\\\\\n# u = 0 \\ &\\text{on} \\ \\Gamma_0,\\\\\n# u = g \\ &\\text{on} \\ \\Gamma_g,\\\\\n# \\left( |\\nabla u|^{p-2}\\ \\nabla u \\right)\\cdot n = 0 \\ &\\text{on} \\ \\Gamma_{\\rm N},\n# \\end{aligned}\n# \\right.\n# ```\n# with $p>2$.\n# The computational domain $\\Omega$ is the one depicted in next figure, which is the same as in the first tutorial. However, we slightly change the boundary conditions here. We impose homogeneous Dirichlet and homogeneous Neumann boundary conditions on $\\Gamma_0$ and $\\Gamma_{\\rm N}$ respectively, and in-homogeneous Dirichlet conditions on $\\Gamma_g$. The Dirichlet boundaries $\\Gamma_0$ and $\\Gamma_g$ are defined as the closure of the green and blue surfaces in next figure respectively, whereas the Neumann boundary is $\\Gamma_{\\rm N}\\doteq\\partial\\Omega \\setminus (\\Gamma_0\\cup\\Gamma_g)$. In this example, we consider the values $p=3$, $f=1$, and $g=2$.\n#\n# ![](../assets/p_laplacian/model.png)\n#\n# ## Numerical scheme\n#\n# We discretize the problem with conforming Lagrangian FE spaces. For this formulation, the nonlinear weak form reads: find $u\\in U_g$ such that $[r(u)](v) = 0$ for all $v\\in V_0$. As in previous tutorials, the space $U_g$ is the set of functions in $H^1(\\Omega)$ that fulfill the Dirichlet boundary conditions, whereas $V_0$ is composed by functions in $H^1(\\Omega)$ that vanish at the Dirichlet boundary. The weak residual $r(u)$ evaluated at a function $u\\in U_g$ is the linear form defined as\n#\n# ```math\n# [r(u)](v) \\doteq \\int_\\Omega \\nabla v \\cdot \\left( |\\nabla u|^{p-2}\\ \\nabla u \\right) \\ {\\rm d}\\Omega - \\int_\\Omega v\\ f \\ {\\rm d}\\Omega.\n# ```\n#\n# In order to solve this nonlinear weak equation, we consider a Newton-Raphson method, which is associated with a linearization of the problem in an arbitrary direction $\\delta u\\in V_0$, namely $[r(u+\\delta u)](v)\\approx [r(u)](v) + [j(u)](\\delta u,v)$. In previous formula, $j(u)$ is the Jacobian evaluated at $u\\in U_g$, which is the bilinear form\n#\n# ```math\n# [j(u)](\\delta u,v) = \\int_\\Omega \\nabla v \\cdot \\left( |\\nabla u|^{p-2}\\ \\nabla \\delta u \\right) \\ {\\rm d}\\Omega + (p-2) \\int_\\Omega \\nabla v \\cdot \\left( |\\nabla u|^{p-4} (\\nabla u \\cdot \\nabla \\delta u) \\nabla u \\right) \\ {\\rm d}\\Omega.\n# ```\n#\n# Note that the solution of this nonlinear PDE with a Newton-Raphson method, will require to discretize both the residual $r$ and the Jacobian $j$. In Gridap, this is done by following an approach similar to the one already shown in previous tutorials for discretizing the bilinear and linear forms associated with a linear FE problem. The specific details are discussed now.\n#\n# ## Discrete model\n#\n# As in previous tutorials, the first step to solve the PDE is to load a discretization of the computational domain. In this case, we load the model from the same file as in the first tutorial\n\nusing Gridap\nmodel = DiscreteModelFromFile(\"../models/model.json\")\n\n# As stated before, we want to impose Dirichlet boundary conditions on $\\Gamma_0$ and $\\Gamma_g$, but none of these boundaries is identified in the model. E.g., you can easily see by writing the model in vtk format\n\nwritevtk(model,\"model\")\n\n# and by opening the file `\"model_0\"` in Paraview that the boundary identified as `\"sides\"` only includes the vertices in the interior of $\\Gamma_0$, but here we want to impose Dirichlet boundary conditions in the closure of $\\Gamma_0$, i.e., also on the vertices on the contour of $\\Gamma_0$. Fortunately, the objects on the contour of $\\Gamma_0$ are identified with the tag `\"sides_c\"` (see next figure). Thus, the Dirichlet boundary $\\Gamma_0$ can be built as the union of the objects identified as `\"sides\"` and `\"sides_c\"`.\n#\n# ![](../assets/p_laplacian/sides_c.png)\n#\n# Gridap provides a convenient way to create new object identifiers (referred to as \"tags\") from existing ones. First, we need to extract from the model, the object that holds the information about the boundary identifiers (referred to as `FaceLabeling`):\n\nlabels = get_face_labeling(model)\n\n# Then, we can add new identifiers (aka \"tags\") to it. In the next line, we create a new tag called `\"diri0\"` as the union of the objects identified as `\"sides\"` and `\"sides_c\"`, which is precisely what we need to represent the closure of the Dirichlet boundary $\\Gamma_0$.\n\nadd_tag_from_tags!(labels,\"diri0\",[\"sides\", \"sides_c\"])\n\n# We follow the same approach to build a new identifier for the closure of the Dirichlet boundary $\\Gamma_g$. In this case, the boundary is expressed as the union of the objects identified with the tags `\"circle\"`, `\"circle_c\"`, `\"triangle\"`, `\"triangle_c\"`, `\"square\"`, `\"square_c\"`. Thus, we create a new tag for $\\Gamma_g$, called `\"dirig\"` simply as follows:\n\nadd_tag_from_tags!(labels,\"dirig\",\n [\"circle\",\"circle_c\", \"triangle\", \"triangle_c\", \"square\", \"square_c\"])\n\n# ## FE Space\n#\n# Now, we can build the FE space by using the newly defined boundary tags.\n\nreffe = ReferenceFE(lagrangian,Float64,1)\nV0 = TestFESpace(model,reffe,conformity=:H1,labels=labels,dirichlet_tags=[\"diri0\", \"dirig\"])\n\n# The construction of this space is essentially the same as in the first tutorial (we build a continuous scalar-valued Lagrangian interpolation of first order). However, we also pass here the `labels` object (that contains the newly created boundary tags). From this FE space, we define the trial FE spaces\n\ng = 1\nUg = TrialFESpace(V0,[0,g])\n\n# ## Nonlinear FE problem\n#\n# At this point, we are ready to build the nonlinear FE problem. To this end, we need to define the weak residual and also its corresponding Jacobian. This is done following a similar procedure to the one considered in previous tutorials to define the bilinear and linear forms associated with linear FE problems. We first need to define the usual objects for numerical integration:\n\ndegree=2\nΩ = Triangulation(model)\ndΩ = Measure(Ω,degree)\n\n#\n# On the one hand, the weak residual is built as follows\n\nusing LinearAlgebra: norm\nconst p = 3\nflux(∇u) = norm(∇u)^(p-2) * ∇u\nf(x) = 1\nres(u,v) = ∫( ∇(v)⊙(flux∘∇(u)) - v*f )*dΩ\n\n# Function `res` is the one representing the integrand of the weak residual $[r(u)](v)$. The first argument of function `res` stands for the function $u\\in U_g$, where the residual is evaluated, and the second argument stands for a generic test function $v\\in V_0$.\n#\n# On the other hand, we (optionally) implement a function `jac` representing the Jacobian.\ndflux(∇du,∇u) = (p-2)*norm(∇u)^(p-4)*(∇u⊙∇du)*∇u+norm(∇u)^(p-2)*∇du\njac(u,du,v) = ∫( ∇(v)⊙(dflux∘(∇(du),∇(u))) )*dΩ\n\n# The first argument of function `jac` stands for function $u\\in U_g$, where the Jacobian is evaluated. The second argument is a test function $v\\in V_0$, and the third argument represents an arbitrary direction $\\delta u \\in V_0$.\n#\n# We finally construct the nonlinear FE problem\n\nop = FEOperator(res,jac,Ug,V0)\n\n# Here, we have constructed an instance of `FEOperator`, which is the type that represents a general nonlinear FE problem in Gridap. The constructor takes the functions representing the weak residual and Jacobian, and the test and trial spaces. If only the function for the residual is provided, the Jacobian is computed internally with automatic differentiation.\n\n#\n# ## Nonlinear solver phase\n#\n# We have already built the nonlinear FE problem. Now, the remaining step is to solve it. In Gridap, nonlinear (and also linear) FE problems can be solved with instances of the type `FESolver`.\n#\n# We construct an instance of `FESolver` as follows:\n\nusing LineSearches: BackTracking\nnls = NLSolver(\n show_trace=true, method=:newton, linesearch=BackTracking())\nsolver = FESolver(nls)\n\n# Note that the `NLSolver` function used above internally calls the `nlsolve` function of the [NLsolve](https://github.com/JuliaNLSolvers/NLsolve.jl) package with the provided key-word arguments. Thus, one can use any of the nonlinear methods available via the function `nlsolve` to solve the nonlinear FE problem. Here, we have selected a Newton-Raphson method with a back-tracking line-search from the [LineSearches](https://github.com/JuliaNLSolvers/LineSearches.jl) package.\n#\n# We are finally in place to solve the nonlinear FE problem. The initial guess is a `FEFunction`, which we build from a vector of random (free) nodal values:\n\nimport Random\nRandom.seed!(1234)\nx = rand(Float64,num_free_dofs(Ug))\nuh0 = FEFunction(Ug,x)\nuh, = solve!(uh0,solver,op)\n\n# We finish this tutorial by writing the computed solution for visualization (see next figure).\n\nwritevtk(Ω,\"results\",cellfields=[\"uh\"=>uh])\n\n# ![](../assets/p_laplacian/sol-plap.png)\n#\n", "meta": {"hexsha": "d8abff895218631fa4c2fa39c4f3a7afac791d98", "size": 9171, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/p_laplacian.jl", "max_stars_repo_name": "Alba-Intelligence/Gridap_Tutorials", "max_stars_repo_head_hexsha": "d13de6b3db93fb3b225d5f4cfed564fc7bcca4de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 67, "max_stars_repo_stars_event_min_datetime": "2019-08-08T20:10:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:00:31.000Z", "max_issues_repo_path": "src/p_laplacian.jl", "max_issues_repo_name": "Alba-Intelligence/Gridap_Tutorials", "max_issues_repo_head_hexsha": "d13de6b3db93fb3b225d5f4cfed564fc7bcca4de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-08-27T18:03:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T05:50:57.000Z", "max_forks_repo_path": "src/p_laplacian.jl", "max_forks_repo_name": "Alba-Intelligence/Gridap_Tutorials", "max_forks_repo_head_hexsha": "d13de6b3db93fb3b225d5f4cfed564fc7bcca4de", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 32, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:14:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T02:55:28.000Z", "avg_line_length": 65.0425531915, "max_line_length": 660, "alphanum_fraction": 0.7280558282, "num_tokens": 2606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240142763573, "lm_q2_score": 0.8577681013541611, "lm_q1q2_score": 0.8046928545605749}} {"text": "\"\"\"\n\n```\nsphericalshellvolume(i,step)\n```\n\nComputes the volume of the spherical shell defined within [(i-1)*step,i*step].\n\n\"\"\"\nfunction sphericalshellvolume(i, step)\n rmin = (i - 1) * step\n return (4 * pi / 3) * ((rmin + step)^3 - rmin^3)\nend\n", "meta": {"hexsha": "181fd13f0734416f59a5552c45fbebdf549a586d", "size": 249, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/sphericalshellvolume.jl", "max_stars_repo_name": "m3g/MDDF", "max_stars_repo_head_hexsha": "efbc8e0dcf426c9b2246217eb9edaf4605318e84", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-04T21:33:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-04T21:33:56.000Z", "max_issues_repo_path": "src/sphericalshellvolume.jl", "max_issues_repo_name": "m3g/MDDF", "max_issues_repo_head_hexsha": "efbc8e0dcf426c9b2246217eb9edaf4605318e84", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-10-31T00:18:34.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-23T20:04:16.000Z", "max_forks_repo_path": "src/sphericalshellvolume.jl", "max_forks_repo_name": "m3g/ComplexMixtures", "max_forks_repo_head_hexsha": "efbc8e0dcf426c9b2246217eb9edaf4605318e84", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.7857142857, "max_line_length": 78, "alphanum_fraction": 0.6224899598, "num_tokens": 81, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172659321807, "lm_q2_score": 0.8479677602988601, "lm_q1q2_score": 0.8046512487014291}} {"text": "\"\"\"\n X = spiraldata(N)\n\nGenerates data points on a 2D spiral returned as a N×2 matrix X.\n\"\"\"\nfunction spiraldata(N, seed=1)\n\n rg = MersenneTwister(seed)\n\n t = rand(rg, Uniform(3, 15), N)\n\n x1 = 0.04 * t .* sin.(t) .+ randn(rg, N)*0.01\n\n x2 = 0.04 * t .* cos.(t) .+ randn(rg, N)*0.01\n\n [x1 x2]\n\nend\n", "meta": {"hexsha": "cb2bd55047eeee493e821cd5bf184d147a69fbc1", "size": 316, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/spiraldata.jl", "max_stars_repo_name": "ngiann/FastParzenWindows.jl", "max_stars_repo_head_hexsha": "090ae01bb4089ce50ecfe8a8ba176da4b8ce6810", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-01-23T13:00:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T14:47:00.000Z", "max_issues_repo_path": "src/spiraldata.jl", "max_issues_repo_name": "HITS-AIN/FastParzenWindows.jl", "max_issues_repo_head_hexsha": "d036bc3b704a931a4e2ab5ce39b4e65de8488775", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-01-20T10:38:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-20T15:47:36.000Z", "max_forks_repo_path": "src/spiraldata.jl", "max_forks_repo_name": "HITS-AIN/FastParzenWindows.jl", "max_forks_repo_head_hexsha": "d036bc3b704a931a4e2ab5ce39b4e65de8488775", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-20T08:17:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T08:17:31.000Z", "avg_line_length": 16.6315789474, "max_line_length": 64, "alphanum_fraction": 0.5506329114, "num_tokens": 128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.951142225532629, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.8046115687999255}} {"text": "#using Elefridge\nusing PyPlot\n\nnbits = 8\nnmax = 7\nmi,ma = 1e-20,1e20\nlogmin = log(mi)\nlogmax = log(ma)\ndlog = (logmax-logmin)/(2^nbits-2) # 2^n-1-1 as 0x00 is reserved for 0\nquants = exp.(logmin .+ Array(0:nmax)*dlog) # the first quantised numbers\nhalf_quants = quants[1:end-1] + diff(quants)/2 # half-way in lin-space\nhalflog_quants = exp.(logmin .+ (Array(0:nmax-1).+.5)*dlog) # half-way in log-space\ndlin = quants[2]-quants[1]\n\nA = Array(quants[1]:dlin/100:quants[end])\n\n# round to nearest in log space\nL1 = round.((log.(A).-logmin)/dlog).+1\nA1 = exp.(logmin .+ (L1.-1)*dlog)\n\nB = vcat(A,ma)\nA0 = Array(LogQuant8Array(B))\n\n# round to nearest in lin space\nc = 1/2 - 1/dlog*log(mi*(exp(dlog)+1)/2)\n\nL2 = round.(c.+log.(A)/dlog).+1\nA2 = exp.(logmin .+ (L2.-1)*dlog)\n\n\n## plot\npygui(true)\nfig,ax = subplots(1,1)\nax.plot(A,A1,\"k--\",lw=2,label=\"Round-to-nearest in log-space\")\nax.plot(A,A2,\"C1--\",lw=2,label=\"Round-to-nearest in lin-space\")\nax.plot(B,A0,\"C2.-\")\n\nax.plot([quants[1],half_quants[1]],[quants[1],quants[1]],\"C1\",lw=3.5)\nax.plot([quants[1],halflog_quants[1]],[quants[1],quants[1]],\"k\",lw=1.5)\nfor i in 1:length(halflog_quants)-1\n x0 = half_quants[i]\n x1 = half_quants[i+1]\n y = quants[i+1]\n ax.plot([x0,x1],[y,y],\"C1\",lw=3.5)\n x0 = halflog_quants[i]\n x1 = halflog_quants[i+1]\n ax.plot([x0,x1],[y,y],\"k\",lw=1.5)\nend\nax.plot([half_quants[end],quants[end]],[quants[end],quants[end]],\"C1\",lw=3.5)\nax.plot([halflog_quants[end],quants[end]],[quants[end],quants[end]],\"k\",lw=1.5)\n\nfor (i,x) in enumerate(halflog_quants)\n labl = i==1 ? \"Halfway in log-space\" : nothing\n ax.axvline(x,color=\"k\",lw=1,label=labl)\nend\n\nfor (i,x) in enumerate(half_quants)\n labl = i==1 ? \"Halfway in lin-space\" : nothing\n ax.axvline(x,color=\"C1\",lw=1,label=labl)\nend\n\nax.set_yticks(quants)\nax.set_yticklabels([latexstring(\"x_{$i}\") for i in 1:length(quants)])\nax.set_xticks(quants)\nax.set_xticklabels([latexstring(\"x_{$i}\") for i in 1:length(quants)])\nax.set_xlabel(L\"$x$ at full precision\")\nax.set_ylabel(L\"quantized $x$\")\n\nax.set_xlim(quants[1],quants[end])\nax.set_ylim(quants[1]-dlin/2,quants[end]+dlin)\n\nax.legend(loc=2,framealpha=1)\nax.set_title(\"Round-to-nearest for log quantization\",loc=\"left\")\n\ntight_layout()\n", "meta": {"hexsha": "9ce51e913f0f37630b3c174469459e6dc892cb0b", "size": 2259, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "wip/log_round_to_nearest.jl", "max_stars_repo_name": "esowc/Elefridge.jl", "max_stars_repo_head_hexsha": "90461a7e0c6b213c4df7d351a36c5665e942e56c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2020-05-11T14:53:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T04:23:46.000Z", "max_issues_repo_path": "wip/log_round_to_nearest.jl", "max_issues_repo_name": "esowc/Elefridge.jl", "max_issues_repo_head_hexsha": "90461a7e0c6b213c4df7d351a36c5665e942e56c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "wip/log_round_to_nearest.jl", "max_forks_repo_name": "esowc/Elefridge.jl", "max_forks_repo_head_hexsha": "90461a7e0c6b213c4df7d351a36c5665e942e56c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-28T19:46:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-28T19:46:22.000Z", "avg_line_length": 29.7236842105, "max_line_length": 86, "alphanum_fraction": 0.6529437804, "num_tokens": 891, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966686936261, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.8045798779669}} {"text": "# Exercise 1\n\nusing LinearAlgebra\nusing StaticArrays\nusing BenchmarkTools\n\nN = 3\nA = rand(N, N)\nx = rand(N)\n\n@btime $A * $x # the $ in front of variable names is sometimes important\n@btime inv($A)\n\n# Benchmark\n\nA_s = @SMatrix rand(N,N)\nx_s = @SVector rand(N)\n\n@btime $A_s * $x_s\n@btime inv($A_s);\n\n# very fast matrix multiplication, use $ and denote as static vectors\n@btime $A_s * $x_s\n@show supertypes(typeof(A_s))\n@show supertypes(typeof(A));\n\n# Exercise 2\n\nΣ = [0.4 0.3;\n 0.3 0.45]\nG = I\nR = 0.5 * Σ\n\ngain(Σ, G, R) = Σ * G' * inv(G * Σ * G' + R)\n@btime gain($Σ, $G, $R)\n\n# Benchmark\n\nΣ_s = @SMatrix [0.4 0.3; 0.3 0.45]\nR_s = 0.5 * Σ_s\n\n@show typeof(R) #static array, too\n\n@btime gain($Σ_s, $G, $R_s);\n\n\n# Exercise 3\n\nusing Polynomials\n\np = Polynomial([2, -5, 2], :x) # :x just gives a symbol for display\n\n@show p\n@show typeof(p)\np′ = derivative(p) # gives the derivative of p, another polynomial\n@show p(0.1), p′(0.1) # call like a function\n@show roots(p); # find roots such that p(x) = 0\n\n# plot p and p'\n\nr = range(-2.0, 2.0, length = 20)\n\np_r = p.(r)\np′_r = p′.(r)\n\nplot(r[1:end-1],p′_r[1:end-1],label=\"Dp(x)\")\nplot!(r,p_r,label=\"p(x)\")\n\n# Exercise 4\n\nfunction newtonsmethod(p::Polynomial, x_0; tolerance = 1E-7, maxiter = 100)\n\n p′ = derivative(p)\n\n #initialise loop\n iter = 1\n normdiff = Inf\n x_old = x_0\n\n while normdiff > tolerance && iter < maxiter\n\n x_new = x_old - p(x_old)/ p′(x_old)\n normdiff = norm(x_new - x_old)\n\n iter += 1 #continuation\n x_old = x_new\n end\n return (root = x_old, normdiff = normdiff, iter = iter )\nend\n\n# Compute roots\n\np = Polynomial([2, -5, 2], :x) # :x just gives a symbol for display\n\n@show newtonsmethod(p, 5); # find roots such that p(x) = 0\n@show roots(p)\n@btime newtonsmethod(p, 5);\n@btime roots(p);\n\n# Exercise 5\nfunction trapezoidal(f::AbstractArray{Float64,1}, x::AbstractArray{Float64,1})\n sol = similar(x)\n del = diff(x)\n for i in 2:length(x)\n sol[i] = (f_x[i]+f_x[i-1])/2*del[i-1]\n end\n return sum(sol)\nend\n\nx = range(0.0,1.0,length=9)\nf(x) = x^2\nf_x = f.(x)\n\n\nint = trapezoidal(f_x,x)\n\nfunction trapezoidal2(f::AbstractArray{Float64}, x::AbstractRange{Float64})\n sol = similar(x)\n del = step(x)\n for i in 2:length(x)\n sol[i] = (f_x[i]+ f_x[i-1])/2*del\n end\n return sum(sol)\nend\n\nx = range(0.0,1.0,length=1100)\nf(x) = x^2\nf_x = f.(x)\n\nintegral = trapezoidal2(f_x,x)\n\nf(x) = x^3\nx̄ = 1.0\nx̲ = 0.0\nN = 1100;\n\nfunction trapezoidal3(f, x̲::Real , x̄::Real , N::Int64)\n x = range(x̲, x̄, length = N)\n f_x = f.(x)\n\n #implementation the same as trapezodal2\n sol = similar(x)\n del = step(x)\n for i in 2:length(x)\n sol[i] = (f_x[i]+ f_x[i-1])/2*del\n end\n return sum(sol)\nend\n\nintegral = trapezoidal3(f ,x̲ , x̄ , N)\n\n# Exercise 6\n\nusing ForwardDiff\n\nfunction f(a, b; N::Int64 = 50)\n r = range(a, b, length=N) # one\nreturn mean(r)\nend\n\nDf(x) = ForwardDiff.derivative(y -> f(0.0, y), x)\n\n@show f(0.0, 3.0)\n@show f(0.0, 3.1)\n\nDf(3.0)\n\nfunction f(a, b; N::Int64 = 50)\n r = range(a, b, length=N) # one\nreturn mean(r)\nend\n", "meta": {"hexsha": "54486ea757a3d3680705f6570e294c07809610b2", "size": 3111, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "GettingStarted_GenericProgramming.jl", "max_stars_repo_name": "shanemcmiken/quantecon-notebooks-julia", "max_stars_repo_head_hexsha": "c9968403bc866fe1f520762619055bd21e09ad10", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GettingStarted_GenericProgramming.jl", "max_issues_repo_name": "shanemcmiken/quantecon-notebooks-julia", "max_issues_repo_head_hexsha": "c9968403bc866fe1f520762619055bd21e09ad10", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GettingStarted_GenericProgramming.jl", "max_forks_repo_name": "shanemcmiken/quantecon-notebooks-julia", "max_forks_repo_head_hexsha": "c9968403bc866fe1f520762619055bd21e09ad10", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.0872093023, "max_line_length": 78, "alphanum_fraction": 0.5959498554, "num_tokens": 1221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333483, "lm_q2_score": 0.896251371748038, "lm_q1q2_score": 0.8045606320568867}} {"text": "\"\"\"\n harmonic(n::Integer)\n\n Calculates harmonic numbers,\n e.g., see [http://mathworld.wolfram.com/HarmonicNumber.html](http://mathworld.wolfram.com/HarmonicNumber.html)\n\n## Arguments\n* ``n`` `::Integer`: non-negative index of the Harmonic number to calculate\n\n## Examples\n```jldoctest; setup = :(using Polylogarithms)\njulia> harmonic(2)\n1.5\n```\n\"\"\"\nfunction harmonic(n::Integer)\n if n < 0\n throw(DomainError(n))\n elseif n==0\n return 0.0 # by convention (see Crandall, p.22)\n elseif n <= 10\n # perform exact sum for small n\n total = 0.0\n for k=1:n\n total += 1.0 / k\n end\n return total\n else\n return γ + SpecialFunctions.digamma(n+1) # digamma(m) = ψ(m)\n end\nend\n\n\"\"\"\n harmonic(x::ComplexOrReal{Float64})\n\n Calculates harmonic numbers extended to non-integer arguments using the\n digamma form.\n\n## Arguments\n* ``x`` `::ComplexOrReal{Float64}`: index of the Harmonic number to calculate\n\n## Examples\n```jldoctest; setup = :(using Polylogarithms)\njulia> harmonic(2.0)\n1.5000000000000016\n```\n\"\"\"\nfunction harmonic(x::ComplexOrReal{Float64})\n return γ + SpecialFunctions.digamma(x+1)\nend\n# ``digamma(m,x) = (-1)^{m+1} m! \\zeta(m+1,x), m>=1``, and integer\n\n\"\"\"\n harmonic(n::Integer,r::Real)\n\n Calculates generalized harmonic numbers, \n e.g., see [http://mathworld.wolfram.com/HarmonicNumber.html](http://mathworld.wolfram.com/HarmonicNumber.html)\n\n## Arguments\n* ``n`` `::Integer`: non-negative index 1 of the Harmonic number to calculate\n* ``r`` `::Real`: index 2 of the Harmonic number to calculate\n\nIt should be possible to extend this to complex r, but that requires more testing.\n\n## Examples\n```jldoctest; setup = :(using Polylogarithms)\njulia> harmonic(2,1.5)\n1.3535533905932737\n```\n\"\"\"\nfunction harmonic(n::Integer, r::Real)\n if n < 0\n throw(DomainError(n))\n end\n if n == 0\n return 0.0\n end\n if r==1\n return harmonic(n)\n end\n total = 0.0\n for k=1:n\n total += 1.0 / k^r\n end\n return total\nend\n\n\n\"\"\"\n harmonic(n::Integer,r::Integer)\n\n Calculates generalized harmonic numbers\n e.g., see [http://mathworld.wolfram.com/HarmonicNumber.html](http://mathworld.wolfram.com/HarmonicNumber.html)\n using a better approach which works when both inputs are integers\n [https://carma.newcastle.edu.au/resources/jon/Preprints/Papers/Published-InPress/Oscillatory%20(Tapas%20II)/Papers/coffey-zeta.pdf](https://carma.newcastle.edu.au/resources/jon/Preprints/Papers/Published-InPress/Oscillatory%20(Tapas%20II)/Papers/coffey-zeta.pdf), p.341\n \n## Arguments\n* ``n`` `::Integer`: non-negative index 1 of the Harmonic number to calculate\n* ``r`` `::Integer`: index 2 of the Harmonic number to calculate\n\n## Examples\n```jldoctest; setup = :(using Polylogarithms)\njulia> harmonic(2,1)\n1.5000000000000002\n```\n\"\"\"\nfunction harmonic(n::Integer, r::Integer)\n if r<1\n throw(DomainError(r))\n end\n return (-1)^(r-1) * ( SpecialFunctions.polygamma(r-1,n+1) - SpecialFunctions.polygamma(r-1,1) ) / SpecialFunctions.gamma(r)\nend\n\n# # better approach to calculation, but doesn't seem to work\n# # using \n# function harmonic3(x::Real, r::Integer)\n# if (r < 1)\n# throw(DomainError(r))\n# end\n# return SpecialFunctions.zeta(r,1) - SpecialFunctions.zeta(r,x+1)\n# end\n\n", "meta": {"hexsha": "940dd88e3edfc0a77ace67308c760418db00d919", "size": 3335, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/harmonic.jl", "max_stars_repo_name": "AshtonSBradley/Polylogarithms.jl", "max_stars_repo_head_hexsha": "f52e3075cd1d87b0d67d26c72cd1a79a365eddcd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-08-24T09:17:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-26T10:54:45.000Z", "max_issues_repo_path": "src/harmonic.jl", "max_issues_repo_name": "AshtonSBradley/Polylogarithms.jl", "max_issues_repo_head_hexsha": "f52e3075cd1d87b0d67d26c72cd1a79a365eddcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-11-18T00:06:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-18T10:35:43.000Z", "max_forks_repo_path": "src/harmonic.jl", "max_forks_repo_name": "AshtonSBradley/Polylogarithms.jl", "max_forks_repo_head_hexsha": "f52e3075cd1d87b0d67d26c72cd1a79a365eddcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-12-17T16:20:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-02T09:32:06.000Z", "avg_line_length": 27.1138211382, "max_line_length": 270, "alphanum_fraction": 0.6674662669, "num_tokens": 998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.8705972633721707, "lm_q1q2_score": 0.8045553358034856}} {"text": "\nusing OrdinaryDiffEq\nusing DiffEqFlux, Flux\nusing Random\nusing Plots;\n\n\nRandom.seed!(123);\n\n\nfunction sir_ode(u,p,t)\n (s,i,r) = u\n (β,γ) = p\n ds = -β*s*i\n di = β*s*i - γ*i\n dr = γ*i\n [ds,di,dr]\nend;\n\n\np = [0.5,0.25]\nu0 = [0.99, 0.01, 0.0]\ntspan = (0.0, 40.0)\nδt = 1;\n\n\nsolver = Rodas5();\n\n\nsir_prob = ODEProblem(sir_ode, u0, tspan, p)\nsir_sol = solve(sir_prob, solver, saveat = δt);\n\n\ntrain_time = 30.0\ntrain_data = Array(sir_sol(0:δt:train_time));\n\n\nnhidden = 8\nsir_node = FastChain(FastDense(3, nhidden, tanh),\n FastDense(nhidden, nhidden, tanh),\n FastDense(nhidden, nhidden, tanh),\n FastDense(nhidden, 3));\n\n\np_ = Float64.(initial_params(sir_node));\nfunction dudt_sir_node(u,p,t)\n s,i,r = u\n ds,di,dr = ann_node([s,i,r],p)\n [ds,di,dr]\nend\nprob_node = ODEProblem(dudt_sir_node, u0, tspan, p_);\n\n\ntspan_train = (0,train_time)\nprob_node = NeuralODE(sir_node,\n tspan_train,\n solver,\n saveat=δt,\n sensealg = InterpolatingAdjoint(autojacvec=ReverseDiffVJP()))\nnump = length(prob_node.p)\n\n\nfunction loss(p)\n sol = prob_node(u0,p)\n pred = Array(sol)\n sum(abs2, (train_data .- pred)), pred\nend;\n\n\nconst losses = []\ncallback = function (p, l, pred)\n push!(losses, l)\n numloss = length(losses)\n if numloss % 50 == 0\n display(\"Epoch: \" * string(numloss) * \" Loss: \" * string(l))\n end\n return false\nend;\n\n\nres_node = DiffEqFlux.sciml_train(loss,\n prob_node.p,\n cb = callback);\n\n\nplot(losses, yaxis = :log, xaxis = :log, xlabel = \"Iterations\", ylabel = \"Loss\", legend = false)\n\n\nprob_node = NeuralODE(sir_node,\n tspan_train,\n solver,\n saveat=δt,\n sensealg = InterpolatingAdjoint(autojacvec=ReverseDiffVJP()),\n p = res_node)\nsol_node = prob_node(u0);\n\n\nscatter(sir_sol, label=[\"True Susceptible\" \"True Infected\" \"True Recovered\"])\nplot!(sol_node, label=[\"Estimated Susceptible\" \"Estimated Infected\" \"Estimated Recovered\"])\n\n\ntspan_test = (0.0, 40.0)\nprob_node_test = NeuralODE(sir_node,\n tspan_test,\n solver,\n saveat=δt,\n sensealg = InterpolatingAdjoint(autojacvec=ReverseDiffVJP()),\n p = res_node)\nsol_node_test = prob_node_test(u0);\n\n\np_node = scatter(sol_node_test, legend = :topright, label=[\"True Susceptible\" \"True Infected\" \"True Recovered\"], title=\"Neural ODE Extrapolation: training until t=30\")\nplot!(p_node,sol_node_test, lw=5, label=[\"Estimated Susceptible\" \"Estimated Infected\" \"Estimated Recovered\"])\n\n\nnewu0 = [0.95, 0.05, 0.0]\nsir_prob_u0 = remake(sir_prob,u0=newu0)\nsir_sol_u0 = solve(sir_prob_u0, solver, saveat = δt)\nnode_sol_u0 = prob_node(newu0)\np_node = scatter(sir_sol_u0, legend = :topright, label=[\"True Susceptible\" \"True Infected\" \"True Recovered\"], title=\"Neural ODE with different initial conditions\")\nplot!(p_node,node_sol_u0, lw=5, label=[\"Estimated Susceptible\" \"Estimated Infected\" \"Estimated Recovered\"])\n\n\ntspan_train2 = (0.0,20.0)\nprob2 = ODEProblem(sir_ode, u0, tspan_train2, p)\nsol2 = solve(prob2, solver, saveat = δt)\ndata2 = Array(sol2)\nsolver2 = ExplicitRK()\nprob_node2 = NeuralODE(sir_node,\n tspan_train2,\n solver2,\n saveat=δt,\n sensealg = InterpolatingAdjoint(autojacvec=ReverseDiffVJP()))\nfunction loss2(p)\n sol = prob_node2(u0,p)\n pred = Array(sol)\n sum(abs2, (data2 .- sol)), pred\nend\nconst losses2 = []\ncallback2 = function (p, l, pred)\n push!(losses2, l)\n numloss = length(losses2)\n if numloss % 50 == 0\n display(\"Epoch: \" * string(numloss) * \" Loss: \" * string(l))\n end\n return false\nend\nres_node2 = DiffEqFlux.sciml_train(loss2,\n prob_node2.p,\n cb = callback2);\n\n\nprob_node2_test = NeuralODE(sir_node,\n tspan_test,\n solver,\n saveat=δt,\n sensealg = InterpolatingAdjoint(autojacvec=ReverseDiffVJP()),\n p = res_node2)\nsol_node2_test = prob_node2_test(u0);\n\n\np_node2 = scatter(sir_sol, legend = :topright, label=[\"True Susceptible\" \"True Infected\" \"True Recovered\"], title=\"Neural ODE Extrapolation: training until t=20\")\nplot!(p_node2, sol_node2_test, lw=5, label=[\"Estimated Susceptible\" \"Estimated Infected\" \"Estimated Recovered\"])\n\n\nfunction loss3(p)\n sol = prob_node(u0,p)\n pred = Array(sol)\n sum(abs2, (train_data[2,:] .- sol[2,:])), pred\nend\nconst losses3 = []\ncallback3 = function (p, l, pred)\n push!(losses3, l)\n numloss = length(losses3)\n if numloss % 50 ==0\n display(\"Epoch: \" * string(numloss) * \" Loss: \" * string(l))\n end\n return false\nend\nres_node3 = DiffEqFlux.sciml_train(loss3,\n prob_node.p,\n cb = callback3);\n\n\nprob_node3_test = NeuralODE(sir_node,\n tspan_test,\n solver,\n saveat=δt,\n sensealg = InterpolatingAdjoint(autojacvec=ReverseDiffVJP()),\n p = res_node3)\nsol_node3_test = prob_node3_test(u0);\n\n\np_node3 = scatter(sir_sol, legend = :topright, label=[\"True Susceptible\" \"True Infected\" \"True Recovered\"], title=\"Neural ODE Extrapolation: training on I(t) until t=30\")\nplot!(p_node3, sol_node3_test, lw=5, label=[\"Estimated Susceptible\" \"Estimated Infected\" \"Estimated Recovered\"])\n\n", "meta": {"hexsha": "1036a1e3c80120acac94f631c71043ec670c0425", "size": 5714, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/node/node_bak.jl", "max_stars_repo_name": "Song921012/sir-julia", "max_stars_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "script/node/node_bak.jl", "max_issues_repo_name": "Song921012/sir-julia", "max_issues_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/node/node_bak.jl", "max_forks_repo_name": "Song921012/sir-julia", "max_forks_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0050761421, "max_line_length": 170, "alphanum_fraction": 0.5931046552, "num_tokens": 1631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133515091156, "lm_q2_score": 0.8558511506439707, "lm_q1q2_score": 0.8044259233947074}} {"text": "\"\"\"\n\n```\nshellradius(i,step)\n```\n\nCompute the point in which the radius comprises half of the\nvolume of the shell.\n\"\"\"\nfunction shellradius(i,step)\n rmin = (i-1)*step\n return ( 0.5*( (rmin+step)^3 + rmin^3 ) )^(1/3)\nend \n", "meta": {"hexsha": "8c94022a57f1e1cd8fea883b20bfdf5c6648a9f5", "size": 223, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/shellradius.jl", "max_stars_repo_name": "m3g/ComplexMixtures.jl", "max_stars_repo_head_hexsha": "0ba3d05f31742752dae37bd4192122d95c984c7f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-05-14T02:35:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-22T15:56:19.000Z", "max_issues_repo_path": "src/shellradius.jl", "max_issues_repo_name": "m3g/ComplexMixtures.jl", "max_issues_repo_head_hexsha": "0ba3d05f31742752dae37bd4192122d95c984c7f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2021-03-18T19:41:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-26T13:56:17.000Z", "max_forks_repo_path": "src/shellradius.jl", "max_forks_repo_name": "m3g/ComplexMixtures.jl", "max_forks_repo_head_hexsha": "0ba3d05f31742752dae37bd4192122d95c984c7f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.9285714286, "max_line_length": 59, "alphanum_fraction": 0.6367713004, "num_tokens": 76, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9603611631680358, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.8044176764402945}} {"text": "using QuadGK\n\nsup = (-1,1)\nf1(x) = 3/4*(1-x^2)\nf2(x) = x < 0 ? x+1 : 1-x\n\nexpect(f,support) = quadgk((x) -> x*f(x),support...)[1]\n\nprintln(\"Mean 1: \", expect(f1,sup))\nprintln(\"Mean 2: \", expect(f2,sup))", "meta": {"hexsha": "d550c00bd3c00057714009ddde1b29d5540adf87", "size": 202, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "3_chapter/meanIntegration.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "3_chapter/meanIntegration.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "3_chapter/meanIntegration.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 20.2, "max_line_length": 55, "alphanum_fraction": 0.5495049505, "num_tokens": 93, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.960361159764527, "lm_q2_score": 0.8376199572530449, "lm_q1q2_score": 0.8044176735894477}} {"text": "#=\n\n# 107: 1D Nonlinear Storage \n([source code](SOURCE_URL))\n\nThis equation comes from the transformation of the nonlinear diffuision equation.\n```math\n\\partial_t u^\\frac{1}{m} -\\Delta u = 0\n```\nin $\\Omega=(-1,1)$ with homogeneous Neumann boundary conditions.\nWe can derive an exact solution from the Barenblatt solution of the previous\nexample.\n\n=#\n\nmodule Example107_NonlinearStorage1D\nusing Printf\nusing VoronoiFVM\nusing ExtendableGrids\nusing GridVisualize\n\nfunction barenblatt(x,t,m)\n tx=t^(-1.0/(m+1.0))\n xx=x*tx\n xx=xx*xx\n xx=1- xx*(m-1)/(2.0*m*(m+1));\n if xx<0.0\n xx=0.0\n end\n return tx*xx^(1.0/(m-1.0))\nend\n\n\nfunction main(;n=20,m=2.0,Plotter=nothing,verbose=false, unknown_storage=:sparse,tend=0.01,tstep=0.0001)\n \n ## Create a one-dimensional discretization\n h=1.0/convert(Float64,n/2)\n X=collect(-1:h:1)\n grid=VoronoiFVM.Grid(X)\n\n ## Flux function which describes the flux\n ## between neigboring control volumes\n function flux!(f,u0,edge)\n u=unknowns(edge,u0)\n f[1]=u[1,1]-u[1,2]\n end\n\n ϵ=1.0e-10\n\n ## Storage term\n ## This needs to be regularized as its derivative\n ## at 0 is infinity\n function storage!(f,u,node)\n f[1]=(ϵ+u[1])^(1.0/m)\n end\n \n ## Create a physics structure\n physics=VoronoiFVM.Physics(\n flux=flux!,\n storage=storage!)\n \n \n ## Create a finite volume system - either\n ## in the dense or the sparse version.\n ## The difference is in the way the solution object\n ## is stored - as dense or as sparse matrix\n sys=VoronoiFVM.System(grid,physics,unknown_storage=unknown_storage)\n\n ## Add species 1 to region 1\n enable_species!(sys,1,[1])\n \n ## Create a solution array\n inival=unknowns(sys)\n solution=unknowns(sys)\n t0=0.001\n\n ## Broadcast the initial value\n inival[1,:].=map(x->barenblatt(x,t0,m)^m,X)\n\n ## Create solver control info\n control=VoronoiFVM.NewtonControl()\n control.verbose=verbose\n control.Δu_opt=0.1\n control.force_first_step=true\n tsol=solve(inival,sys,[t0,tend],control=control)\n\n p=GridVisualizer(Plotter=Plotter,layout=(1,1),fast=true)\n for i=1:length(tsol)\n time=tsol.t[i]\n scalarplot!(p[1,1],grid,tsol[1,:,i],title=@sprintf(\"t=%.3g\",time),color=:red,label=\"numerical\")\n scalarplot!(p[1,1],grid,map(x->barenblatt(x,time,m)^m,grid),clear=false,color=:green,label=\"exact\")\n reveal(p)\n sleep(1.0e-2)\n end\n\n return sum(tsol[end])\nend\n\n\nfunction test()\n testval=175.20261258406686\n main(unknown_storage=:sparse) ≈ testval && main(unknown_storage=:dense) ≈ testval\nend\n\nend \n\n", "meta": {"hexsha": "eed3f6a8ac24987e617cab48b7ca16510da97819", "size": 2651, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Example107_NonlinearStorage1D.jl", "max_stars_repo_name": "mattlie82/VoronoiFVM.jl", "max_stars_repo_head_hexsha": "819cdc967f4cf8fad6b14e271296b365ff6e51c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/Example107_NonlinearStorage1D.jl", "max_issues_repo_name": "mattlie82/VoronoiFVM.jl", "max_issues_repo_head_hexsha": "819cdc967f4cf8fad6b14e271296b365ff6e51c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/Example107_NonlinearStorage1D.jl", "max_forks_repo_name": "mattlie82/VoronoiFVM.jl", "max_forks_repo_head_hexsha": "819cdc967f4cf8fad6b14e271296b365ff6e51c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7757009346, "max_line_length": 107, "alphanum_fraction": 0.6525839306, "num_tokens": 843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768541530197, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.8043941129001821}} {"text": "#=\n## Integration with `NetworkDynamics.jl`\nIn this example we model a Network based on the [Kuroamoto model](https://en.wikipedia.org/wiki/Kuramoto_model) using the [`NetworkDynamics.jl`](https://github.com/FHell/NetworkDynamics.jl) package.\n=#\n\nusing NetworkDynamics\nusing Graphs\nusing BlockSystems\nusing ModelingToolkit\nusing OrdinaryDiffEq\nusing Plots\n\n#=\nIn the Kuramoto model each vertex $i$ has it's own intrinsic angular frequency $\\omega_i$.\nThe angle of frequency is given by\n```math\n\\dot\\phi = \\omega_i + \\sum e\n```\nwhere $\\sum e$ sums over all the connected edges.\n=#\n@parameters t ω edgesum(t)\n@variables ϕ(t)\nD = Differential(t)\n\nkmvert = IOBlock([D(ϕ) ~ ω + edgesum],\n [edgesum],\n [ϕ],\n name=:kmvert)\n\nfunction generate_ode_vertex(iob::IOBlock, aggregator; kwargs...)\n gen = generate_io_function(iob; kwargs...)\n f = (du, u, edges, p, t) -> gen.f_ip(du, u, aggregator(edges), p, t)\n vars = ModelingToolkit.tosymbol.(gen.states)\n ODEVertex(f = f, dim = length(vars), sym = vars)\nend\n\n## allocation free oop aggregator. might be more difficult for more-dimensional systems\n## unfortunately there are no vector variables in MDK and we can't model the aggregators\n## as an IOSystem.\nfunction sumedges(edges)\n r = 0.0\n for e in edges\n r += e[1]\n end\n return r\nend\n\nvertex = generate_ode_vertex(kmvert, sumedges)\nnothing #hide\n\n#=\nThe edges are defined as\n```math\ne_{i,j} = K \\cdot \\mathrm{sin}(\\phi_i - \\phi_j)\n```\nFor the (static) edges we can't used IOSystem function building in the moment.\nWell, we could but than we'd get an `ODEEdge` with zero-massmatrix.\n=#\n@parameters v₁(t) v₂(t) K\nedge_ip = build_function([K*sin(v₁[1] - v₂[1])], [v₁], [v₂], K, t, expression=Val{false})[2]\nedge = StaticEdge(f = edge_ip, dim = 1, coupling=:antisymmetric)\n\nnothing #hide\n#=\nLets runt the [same example](https://fhell.github.io/NetworkDynamics.jl/dev/heterogeneous_system/#Heterogenous-parameters) as in `NetworkDynamics.jl`\n=#\nN = 8\ng = watts_strogatz(N,2,0) # ring network\nnd = network_dynamics(vertex, edge, g)\n\nω = collect(1:N)./N\nω .-= sum(ω)/N\nK = 3.\np = (ω, K); # p[1] vertex parameters, p[2] edge parameters\n\nx0 = collect(1:N)./N\nx0 .-= sum(x0)./N\n\n#src using BenchmarkTools\n#src @btime $nd($x0, $x0, $p, 0.0)\n\ntspan = (0., 10.)\nprob = ODEProblem(nd, x0, tspan, p)\nsol = solve(prob, Tsit5())\nplot(sol, ylabel=\"ϕ\")\n", "meta": {"hexsha": "6e86367e7202f3dd84bed67dce8765a612fda34b", "size": 2403, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/kuramoto_network.jl", "max_stars_repo_name": "hexaeder/BlockSystems.jl", "max_stars_repo_head_hexsha": "2dabd797f51067b19882976705bf49614f09ef33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2021-04-12T14:36:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T07:10:17.000Z", "max_issues_repo_path": "examples/kuramoto_network.jl", "max_issues_repo_name": "hexaeder/BlockSystems.jl", "max_issues_repo_head_hexsha": "2dabd797f51067b19882976705bf49614f09ef33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2021-02-05T18:50:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:15:27.000Z", "max_forks_repo_path": "examples/kuramoto_network.jl", "max_forks_repo_name": "hexaeder/BlockSystems.jl", "max_forks_repo_head_hexsha": "2dabd797f51067b19882976705bf49614f09ef33", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-04-14T13:47:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-06T14:19:40.000Z", "avg_line_length": 27.9418604651, "max_line_length": 198, "alphanum_fraction": 0.6799833541, "num_tokens": 752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.8840392924390585, "lm_q1q2_score": 0.80439355012278}} {"text": "# SPDX-License-Identifier: MIT\n\n\n\"\"\"\n struct TropicalSemiring{T<:AbstractFloat} <: Semiring\n val::T\n end\n\nLog-semifield is defined as :\n * ``x \\\\oplus y \\\\triangleq \\\\text{max}(x, y)``\n * ``x \\\\otimes y \\\\triangleq x + y``\n``\\\\forall x, y \\\\in \\\\mathbb{R}``.\n\"\"\"\nstruct TropicalSemiring{T<:AbstractFloat} <: Semiring\n val::T\nend\n\nBase.:+(x::TropicalSemiring, y::TropicalSemiring) =\n TropicalSemiring(max(x.val, y.val))\nBase.:*(x::TropicalSemiring, y::TropicalSemiring) =\n TropicalSemiring(x.val + y.val)\nBase.zero(::Type{TropicalSemiring{T}}) where T = TropicalSemiring{T}(T(-Inf))\nBase.one(::Type{TropicalSemiring{T}}) where T = TropicalSemiring{T}(T(0))\nBase.isless(x::TropicalSemiring, y::TropicalSemiring) = isless(x.val, y.val)\nBase.typemin(x::Type{TropicalSemiring{T}}) where T =\n TropicalSemiring{T}(typemin(T))\nBase.typemax(x::Type{TropicalSemiring{T}}) where T =\n TropicalSemiring{T}(typemax(T))\nBase.conj(x::Type{TropicalSemiring{T}}) where T = TropicalSemiring{T}(conj(x.val))\n", "meta": {"hexsha": "48600a91415190b2192e7a69c6dd007c1693e30e", "size": 1018, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/semirings/tropsemiring.jl", "max_stars_repo_name": "MartinKocour/MarkovModels.jl", "max_stars_repo_head_hexsha": "d0d70e303e40941dbc5ff900905ea19d63584f3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/semirings/tropsemiring.jl", "max_issues_repo_name": "MartinKocour/MarkovModels.jl", "max_issues_repo_head_hexsha": "d0d70e303e40941dbc5ff900905ea19d63584f3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/semirings/tropsemiring.jl", "max_forks_repo_name": "MartinKocour/MarkovModels.jl", "max_forks_repo_head_hexsha": "d0d70e303e40941dbc5ff900905ea19d63584f3c", "max_forks_repo_licenses": ["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.9333333333, "max_line_length": 82, "alphanum_fraction": 0.6807465619, "num_tokens": 319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122732859021, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.8043914681652824}} {"text": "### A Pluto.jl notebook ###\n# v0.16.1\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n quote\n local el = $(esc(element))\n global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n el\n end\nend\n\n# ╔═╡ 3f890c7b-44ad-426a-bf26-32ff17fa8ec4\nmd\"\"\"\n# Examples in Julia - Tutorial 1\n\"\"\"\n\n# ╔═╡ 5bc2c872-fded-4bc8-8044-9eda1822c505\nmd\"\"\"\n## Assignment 1\n\nUsing the package `Polynomials.jl`, write the function which implements \n[Graeffe's method](https://en.wikipedia.org/wiki/Graeffe%27s_method)\n(see also [here](http://mathworld.wolfram.com/GraeffesMethod.html))\nfor computing roots of polynomials with only real roots with simple moduli.\n\nIn the function, use Julia's `BigFloat` numbers to overcome the main disadvantage of the method. What is the number of significant decimal digits, and the largest and the smallest number?\n\nTest the function on the [Wilkinson's polynomial](https://en.wikipedia.org/wiki/Wilkinson%27s_polynomial) $\\omega(x)$, and the [Chebyshev polynomial](https://en.wikipedia.org/wiki/Chebyshev_polynomials) $T_{50}(x)$ \n(the latter needs to be transformed in order to apply the method).\n\nCompare your solutions with the exact solutions.\n\"\"\"\n\n# ╔═╡ 5b542ad3-8471-4adc-9c89-d647000b8ca0\nmd\"\"\"\n## Assignment 2\n\nWrite the function which computes simple LU factorization (without pivoting) where the matrix is overwritten by the factors.\n\nMake sure that the function also works with block-matrices. \n\nCompare the speed on standard matrices and block-matrices with the built-in LU factorization (which also uses block algorithm AND pivoting). Check the accuracy.\n\"\"\"\n\n# ╔═╡ dbd0a150-2ad2-49e3-b585-d34bfc2ff3b8\nmd\"\"\"\n## Assignment 3\n\nUse the function `eigvals()` to compute the eigenvalues of $k$ random matrices (with uniform and normal distribution of elements) of order $n$.\n\nPlot the results using the macro `@bind` from the package `PlutoUI.jl`.\nUse `Plots.jl` for plotting.\n\nAre the eigenvalues random? Can you describe their behaviour? Can random matrices be used to test numerical algorithms?\n\"\"\"\n\n# ╔═╡ 4cd45baf-67f6-43cc-a9bf-3a89006c3814\n\n\n# ╔═╡ Cell order:\n# ╟─3f890c7b-44ad-426a-bf26-32ff17fa8ec4\n# ╟─5bc2c872-fded-4bc8-8044-9eda1822c505\n# ╟─5b542ad3-8471-4adc-9c89-d647000b8ca0\n# ╟─dbd0a150-2ad2-49e3-b585-d34bfc2ff3b8\n# ╠═4cd45baf-67f6-43cc-a9bf-3a89006c3814\n", "meta": {"hexsha": "de3ef9f52795970ad2b192222bde25ddcc9bab06", "size": 2545, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Module A - Short Julia Course/T1 Examples in Julia.jl", "max_stars_repo_name": "ivanslapnicar/GIAN-Applied-NLA-Course", "max_stars_repo_head_hexsha": "021628ccc9ade3049e96813108850d3641637aef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2016-06-10T09:40:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T23:00:08.000Z", "max_issues_repo_path": "src/Module A - Short Julia Course/T1 Examples in Julia.jl", "max_issues_repo_name": "ivanslapnicar/GIAN-Applied-NLA-Course", "max_issues_repo_head_hexsha": "021628ccc9ade3049e96813108850d3641637aef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Module A - Short Julia Course/T1 Examples in Julia.jl", "max_forks_repo_name": "ivanslapnicar/GIAN-Applied-NLA-Course", "max_forks_repo_head_hexsha": "021628ccc9ade3049e96813108850d3641637aef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2016-06-21T14:20:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-10T17:03:59.000Z", "avg_line_length": 36.3571428571, "max_line_length": 215, "alphanum_fraction": 0.7512770138, "num_tokens": 794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206738932333, "lm_q2_score": 0.8918110353738529, "lm_q1q2_score": 0.8043428100098075}} {"text": "module MyInterpolations\n\nexport my_lin_interp\n\nfunction my_lin_interp(grid, vals)\n function func(x)\n for i in 1:(length(grid)-1)\n if (grid[i]<=x)&&(x<=grid[i+1])\n return ((vals[i+1]-vals[i])/(grid[i+1]-grid[i]))*(x-grid[i])+vals[i]\n end\n end\n end\n\n return func\nend\n\nend", "meta": {"hexsha": "3179d01b2247081d1dc30d5d74635fac46dd8288", "size": 295, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MyInterpolations.jl", "max_stars_repo_name": "hirokikanamaru/MyInterpolation.jl", "max_stars_repo_head_hexsha": "0cc63abd9edfba3e7009b19fd809afa077700453", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MyInterpolations.jl", "max_issues_repo_name": "hirokikanamaru/MyInterpolation.jl", "max_issues_repo_head_hexsha": "0cc63abd9edfba3e7009b19fd809afa077700453", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MyInterpolations.jl", "max_forks_repo_name": "hirokikanamaru/MyInterpolation.jl", "max_forks_repo_head_hexsha": "0cc63abd9edfba3e7009b19fd809afa077700453", "max_forks_repo_licenses": ["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.3529411765, "max_line_length": 76, "alphanum_fraction": 0.6101694915, "num_tokens": 95, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9626731126558705, "lm_q2_score": 0.8354835452961425, "lm_q1q2_score": 0.8042975451229996}} {"text": "using AbstractPlotting\nusing AbstractPlotting.MakieLayout\nusing GLMakie\n\nusing QuadGK\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\"\"\"\n integration(f)\n\nShow graphically the left Riemann approximation, the trapezoid approximation, and Simpson's approximation to the integral of `f` over [-1,1].\n\nAssumes `f` is non-negative.\n\"\"\"\nfunction integration(f=nothing)\n if f == nothing\n f = x -> x^2*exp(-x/3)\n end\n\n a, b = -1, 1\n\n\nfunction left_riemann_pts(n)\n xs = range(a, b, length=n+1)\n pts = Point2f0[(xs[1], 0)]\n for i in 1:n\n xᵢ, xᵢ₊₁ = xs[i], xs[i+1]\n fᵢ = f(xᵢ)\n push!(pts, (xᵢ, fᵢ))\n push!(pts, (xᵢ₊₁, fᵢ))\n end\n push!(pts, (xs[end], 0))\n pts\nend\n \n\nfunction trapezoid_pts(n)\n xs = range(a, b, length=n+1)\n pts = Point2f0[(xs[1], 0)]\n for i in 1:n\n xᵢ, xᵢ₊₁ = xs[i], xs[i+1]\n fᵢ = f(xᵢ)\n push!(pts, (xᵢ, f(xᵢ)))\n end\n push!(pts, (xs[end], f(xs[end])))\n push!(pts, (xs[end], 0))\n pts\nend\n\nfunction simpsons_pts(n)\n xs = range(a, b, length=n+1)\n pts = Point2f0[(xs[1], 0), (xs[1], f(xs[1]))]\n \n for i in 1:n\n xi, xi1 = xs[i], xs[i+1]\n m = xi/2 + xi1/2\n p = x -> f(xi)*(x-m)*(x - xi1)/(xi-m)/(xi-xi1) + f(m) * (x-xi)*(x-xi1)/(m-xi)/(m-xi1) + f(xi1) * (x-xi)*(x-m) / (xi1-xi) / (xi1-m)\n\n xs′ = range(xi, xi1, length=10)\n for j in 2:10\n x = xs′[j]\n push!(pts, (x, p(x)))\n end\n end\n push!(pts, (xs[end], 0))\n pts\nend\n\n\n# where we lay our scene:\nscene, layout = layoutscene()\nlayout.halign = :left\nlayout.valign = :top\n\n\np1 = layout[1,1] = LScene(scene)\np2 = layout[1,2] = LScene(scene)\np3 = layout[1,3] = LScene(scene)\n\nn = layout[2,1] = LSlider(scene, range=2:25, startvalue=2)\noutput = layout[2, 2:3] = LText(scene, \"...\")\n\nlpts = lift(n.value) do n\n left_riemann_pts(n)\nend\n\npoly!(p1.scene, lpts, color=:gray75)\nlines!(p1.scene, a..b, f, color=:black, strokewidth=10)\ntitle(p1.scene, \"Left Riemann\")\n\n\ntpts = lift(n.value) do n\n trapezoid_pts(n)\nend\npoly!(p2.scene, tpts, color=:gray75)\nlines!(p2.scene, a..b, f, color=:black, strokewidth=10)\ntitle(p2.scene, \"Trapezoid\")\n\nspts = lift(n.value) do n\n simpsons_pts(n)\nend\npoly!(p3.scene, spts, color=:gray75)\nlines!(p3.scene, a..b, f, color=:black, strokewidth=10)\ntitle(p3.scene, \"Simpson's\")\n\non(n.value) do n\n actual,err = quadgk(f, -1, 1)\n lrr = riemann(f, -1, 1, n, method=\"left\")\n trap = riemann(f, -1, 1, n, method=\"trapezoid\")\n simp = riemann(f, -1, 1, n, method=\"simpsons\")\n\n Δleft = round(abs(lrr - actual), digits=8)\n Δtrap = round(abs(trap - actual), digits=8)\n Δsimp = round(abs(simp - actual), digits=8)\n\n txt = \"Riemann: $Δleft, Trapezoid: $Δtrap, Simpson's: $Δsimp\"\n output.text[] = txt\nend\nn.value[] = n.value[]\n\n\n\n\n\nscene\nend\n", "meta": {"hexsha": "bdfe3eeb42957165b9bed4d691a360f65f629335", "size": 3358, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "CwJ/makie-demos/integration.jl", "max_stars_repo_name": "jverzani/CalculusWithJulia.jl", "max_stars_repo_head_hexsha": "6ee5135e82c11a1f83b024556be55ad6cbf2622d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2019-08-29T02:00:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T11:15:12.000Z", "max_issues_repo_path": "CwJ/makie-demos/integration.jl", "max_issues_repo_name": "jverzani/CalculusWithJulia.jl", "max_issues_repo_head_hexsha": "6ee5135e82c11a1f83b024556be55ad6cbf2622d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2020-12-03T15:00:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T00:57:57.000Z", "max_forks_repo_path": "CwJ/makie-demos/integration.jl", "max_forks_repo_name": "jverzani/CalculusWithJulia.jl", "max_forks_repo_head_hexsha": "6ee5135e82c11a1f83b024556be55ad6cbf2622d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2020-01-07T10:53:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T06:08:38.000Z", "avg_line_length": 23.4825174825, "max_line_length": 141, "alphanum_fraction": 0.5485407981, "num_tokens": 1313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218262741297, "lm_q2_score": 0.8723473829749844, "lm_q1q2_score": 0.8042360924577552}} {"text": "@doc raw\"\"\"\n Ellipsoid(a, b, f, finv, e2, ϵ2, name)\n Ellipsoid(a, finv, name)\n\nEarth ellipsoid model.\n\n# Fields\n\n- `a::Real`: semi-major axis (m).\n- `b::Real`: semi-minor axis (m).\n- `f::Real`: flattening (``f``).\n- `finv::Real`: inverse of flattening (``f^{-1}``).\n- `e2::Real`: eccentricity squared.\n- `ϵ2::Real`: second eccentricity squared.\n- `name::String`: ellipsoid name.\n\n# Notes\n\n``a`` is the semi-major axis, ``b`` is the semi-minor axis. Ellipsoids are normally defined\nby ``a`` and ``f^{-1}``. The rest of parameters are derived.\n\n- Flattening:\n```math\nf = 1 - \\frac{b}{a}\n```\n- Eccentricity (first eccentricity):\n```math\ne^2 = \\frac{a^2 - b^2}{a^2} = f (2 - f)\n```\n- Second eccentricity:\n```math\nϵ^2 = \\frac{a^2 - b^2}{b^2} = \\frac{f (2 - f)}{(1 - f)^2}\n```\n\n# References\n\n1. Stevens, B. L., Lewis, F. L., (1992). Aircraft control and simulation: dynamics, controls\n design, and autonomous systems. John Wiley & Sons. Section 1.6 (page 23)\n2. Rogers, R. M. (2007). Applied mathematics in integrated navigation systems. American\n Institute of Aeronautics and Astronautics. Chapter 4 (Nomenclature differs from 1).\n3. Bowring, B. R. (1976). Transformation from spatial to geographical coordinates. Survey\n review, 23(181), 323-327.\n\"\"\"\nstruct Ellipsoid\n \"Semi-major axis (m).\"\n a::Real\n \"Semi-minor axis (m).\"\n b::Real\n \"Flattening ``f = \\frac{a-b}{a} = a - \\frac{b}{a}``.\"\n f::Real\n \"Inverse of flattening.\"\n finv::Real\n \"Eccentricity. ``e^2 = \\frac{a^2 - b^2}{a^2} = f (2 - f)``\"\n e2::Real\n \"Second eccentricity. ``ϵ^2 = \\frac{a^2 - b^2}{b^2} = \\frac{f (2 - f)}{(1 - f)^2}``.\"\n ϵ2::Real\n \"Ellipsoid name.\"\n name::String\nend\n\n\nfunction Ellipsoid(a, finv, name)\n f = 1 / finv\n b = a * (1 - f)\n e2 = f * (2 - f)\n ϵ2 = e2 / (1 - f)^2\n return Ellipsoid(a, b, f, finv, e2, ϵ2, name)\nend\n\n\n# Rogers, R. M. (2007). Applied mathematics in integrated navigation systems.\n# American Institute of Aeronautics and Astronautics. (Page 76, table 4.1)\nconst Clarke1866 = Ellipsoid(6378206.4, 294.9786982, \"Clarke1866\")\nconst Clarke1880 = Ellipsoid(6378249.145, 294.465, \"Clarke1880\")\nconst International = Ellipsoid(6378388.0, 297.0, \"International\")\nconst Bessel = Ellipsoid(6377397.155, 299.1528128, \"Bessel\")\nconst Everest = Ellipsoid(6377276.345, 300.8017, \"Everest\")\nconst ModifiedEverest = Ellipsoid(6377304.063, 300.8017, \"ModifiedEverest\")\nconst AustralianNational = Ellipsoid(6378160.0, 298.25, \"AustralianNational\")\nconst SouthAmerican1969 = Ellipsoid(6378160.0, 298.25, \"SouthAmerican1969\")\nconst Airy = Ellipsoid(6377564.396, 299.3249646, \"Airy\")\nconst ModifiedAiry = Ellipsoid(6377340.189, 299.3249646, \"ModifiedAiry\")\nconst Hough = Ellipsoid(6378270.0, 297.0, \"Hough\")\nconst Fischer1960SouthAsia = Ellipsoid(6378155.0, 298.3, \"Fischer1960SouthAsia\")\nconst Fischer1960Mercury = Ellipsoid(6378166.0, 298.3, \"Fischer1960Mercury\")\nconst Fischer1968 = Ellipsoid(6378150.0, 298.3, \"Fischer1968\")\nconst WGS60 = Ellipsoid(6378165.0, 298.3, \"WGS60\")\nconst WGS66 = Ellipsoid(6378145.0, 298.25, \"WGS66\")\nconst WGS72 = Ellipsoid(6378135.0, 298.26, \"WGS72\")\nconst WGS84 = Ellipsoid(6378137.0, 298.257223563, \"WGS84\")\n\n\n\"\"\"\n llh2ecef(lat, lon, height; ellipsoid=WGS84)\n\nTransform geodetic latitude, longitude (rad) and ellipsoidal height (m) to ECEF for the\ngiven ellipsoid (default ellipsoid is WGS84).\n\n# References\n\n1. Rogers, R. M. (2007). Applied mathematics in integrated navigation systems. American\n Institute of Aeronautics and Astronautics. (Page 75, equations 4.20, 4.21, 4.22)\n\"\"\"\nfunction llh2ecef(lat, lon, height; ellipsoid=WGS84)\n f = ellipsoid.f\n a = ellipsoid.a\n e2 = ellipsoid.e2\n\n var = a / sqrt(1.0 - e2 * sin(lat)*sin(lat))\n\n px = (var + height) * cos(lat)*cos(lon)\n py = (var + height) * cos(lat)*sin(lon)\n pz = (var * (1.0 - e2) + height)* sin(lat)\n\n return [px, py, pz]\nend\n\n\n\"\"\"\n ecef2llh(xecef, yecef, zecef; ellipsoid=WGS84)\n\nTransform ECEF coordinates to geodetic latitude, longitude (rad) and ellipsoidal height (m)\nfor the given ellipsoid (default ellipsoid is WGS84).\n\n# Notes\n\n* The transformation is direct without iterations as [1] introduced the need to iterate for\n near Earth positions.\n* [2] is an update of increased accuracy of [1]. The former is used in this implementation\n although the latter implementation is commented in the code.\n* Model becomes unstable if latitude is close to 90º. An alternative equation\n can be found in [2] equation (16) but has not been implemented.\n\n # References\n\n1. Bowring, B. R. (1976). Transformation from spatial to geographical coordinates. Survey\n review, 23(181), 323-327.\n2. Bowring, B. R. (1985). The accuracy of geodetic latitude and height equations. Survey\n Review, 28(218), 202-206.\n\"\"\"\nfunction ecef2llh(xecef, yecef, zecef; ellipsoid=WGS84)\n\n x, y, z = xecef, yecef, zecef\n e = sqrt(ellipsoid.e2);\n e2 = ellipsoid.e2\n ϵ2 = ellipsoid.ϵ2\n a = ellipsoid.a\n b = ellipsoid.b\n\n p = sqrt(x*x + y*y)\n R = sqrt(p*p + z*z)\n θ = atan(z, p)\n # [1] equation (1) does not change in [2]\n lon = atan(y, x)\n # u -> geographical latitude\n # [1] below equation (4) and [2] equation (6)\n # This lead to errors in latitud with maximum value 0.0018\"\n #u = atan(a/b * z/x)\n\n # [2] equation (17) If the latitude is also required to be very accurate\n # for outer-space positions then the value of u for (6) should be obtained\n # from:\n u = atan(b*z / (a*p) * (1 + ϵ2 * b / R))\n # [1] equation (4)\n #lat = atan((z + ϵ2 * b * sin(u)^3) / (x - e2 * a * cos(u)^3))\n # [2] equation (18)\n lat = atan((z + ϵ2 * b * sin(u)^3) / (p - e2 * a * cos(u)^3))\n # [2] after equation (1)\n v = a / sqrt(1.0 - e2*sin(lat)^2)\n # [2] equation (7)\n # height = p*cos(lat) + z*sin(lat) - a*a / v\n # equivalent to [2] equation (8)\n height = R * cos(lat - θ) - a*a / v\n # which is insensitive to the error in latitude calculation (The influence\n # is of order 2 [2] equation (12))\n return [lat, lon, height]\nend\n", "meta": {"hexsha": "7e4760f6da78f2764c084e24f4c05a51071c89fd", "size": 6051, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/ellipsoid.jl", "max_stars_repo_name": "AlexS12/FlightMechanicsUtils.jl", "max_stars_repo_head_hexsha": "862f3cdac936c65881bc2aa8f1168ead8d5284d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-06-24T17:05:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T16:56:11.000Z", "max_issues_repo_path": "src/ellipsoid.jl", "max_issues_repo_name": "AlexS12/FlightMechanicsUtils.jl", "max_issues_repo_head_hexsha": "862f3cdac936c65881bc2aa8f1168ead8d5284d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2021-03-13T19:26:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-06T11:41:07.000Z", "max_forks_repo_path": "src/ellipsoid.jl", "max_forks_repo_name": "AlexS12/FlightMechanicsUtils.jl", "max_forks_repo_head_hexsha": "862f3cdac936c65881bc2aa8f1168ead8d5284d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9943820225, "max_line_length": 92, "alphanum_fraction": 0.6514625682, "num_tokens": 2106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625088705932, "lm_q2_score": 0.8633916205190225, "lm_q1q2_score": 0.8042169249864959}} {"text": "\"\"\"\n mat_center(X; mat = \"her\")\n\nThis function centers input. \nIf X is a Hermitian matrix, then ``Xcen = X - Tr(X)/N*I```.\nIf X is a rectangular matrix, then ``Xcen = X - X*ones(M,1)*ones(1,M)/M``.\n\n# Arguments \n- `X`: a Hermitian or rectangular matrix\n- `mat`: the type of `X`, valid options are \"her\" and \"rec\"\n\n# Outputs:\n- `Xc`: centered version of `X`\n\"\"\"\nfunction mat_center(X::Array{T,2}; mat = \"her\") where T <: Number\n N, M = size(X)\n\n if mat == \"her\"\n # for Hermitian matrix, X = X - I*tr(X)/N\n if M != N\n error(\"X should be a symmetric matrix\")\n end\n Xc = X - I*tr(X)/M\n elseif mat == \"rec\"\n # for rectangular matrix, A = A - mean(A)*ones(N, M)\n Xc = X - mean(X)*ones(N, M)\n end\n\n return Xc\nend\n\n\n\"\"\"\n free_whiten(Z; mat = \"her\")\n\nThis function whitens input array of matrices in the free probability sense\n\n# Arguments\n- `Z`: an array of matrices of mat and of the same dimensions\n- `mat`: the type of Z[i], valid options are \"her\" and \"rec\"\n\n# Outputs\n- `Y`: an array of centered matrices, whitened in the free probability sense, \n that is, Tr(Y[i]*Y[j]')/size(Y[1],1) = (i == j)\n- `U`: a matrix of size s-by-s, where s = size(Z, 1)\n- `Σ`: a matrix of size s-by-s, \n\"\"\"\nfunction free_whiten(Z::Array{Array{T, 2}}; mat = \"her\") where T <: Number\n Zc = mat_center.(Z; mat = mat)\n N = size(Zc[1], 1)\n\n # compute the cov matrix such that\n # cov[i,j] = tr(Zc[i]*Zc[j]')/N\n eigcov = eigen(real(tr.(Zc*Zc'/N)));\n Λ, U = eigcov.values, eigcov.vectors # only take the real part\n \n Λ[Λ.<0] .= 0 # keep non-negative eigs\n Σ = Diagonal(Λ).^0.5 \n Y = U*pinv(Σ)*U'*Zc\n\n return Y, U, Σ\nend\n\n# if Z is just a single matrix, we first convert it to [Y].\nfunction free_whiten(Z::Array{T, 2}; mat = \"her\") where T <: Number\n return free_whiten([Z]; mat = mat)\nend", "meta": {"hexsha": "18130c0971f7be6cb0f29c655b4d07a366f3f1ad", "size": 1893, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/free_whiten.jl", "max_stars_repo_name": "UnofficialJuliaMirror/FCA.jl-9ac0d1d1-ab1e-5a44-888c-d389b307372d", "max_stars_repo_head_hexsha": "47ed4f7e1ac9b764b2753bef0138f8961b6559ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-04-13T17:31:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-02T12:58:13.000Z", "max_issues_repo_path": "src/free_whiten.jl", "max_issues_repo_name": "UnofficialJuliaMirror/FCA.jl-9ac0d1d1-ab1e-5a44-888c-d389b307372d", "max_issues_repo_head_hexsha": "47ed4f7e1ac9b764b2753bef0138f8961b6559ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/free_whiten.jl", "max_forks_repo_name": "UnofficialJuliaMirror/FCA.jl-9ac0d1d1-ab1e-5a44-888c-d389b307372d", "max_forks_repo_head_hexsha": "47ed4f7e1ac9b764b2753bef0138f8961b6559ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-03-19T16:32:53.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-22T19:44:57.000Z", "avg_line_length": 28.2537313433, "max_line_length": 80, "alphanum_fraction": 0.5773903856, "num_tokens": 639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625050654264, "lm_q2_score": 0.8633916187614823, "lm_q1q2_score": 0.8042169200640639}} {"text": "# Rational Quadratic Isotropic Covariance Function\n\n\"\"\"\n RQIso <: Isotropic{SqEuclidean}\n\nIsotropic Rational Quadratic kernel (covariance)\n```math\nk(x,x') = σ²(1 + (x - x')ᵀ(x - x')/(2αℓ²))^{-α}\n```\nwith length scale ``ℓ``, signal standard deviation ``σ``, and shape parameter ``α``.\n\"\"\"\nmutable struct RQIso{T<:Real} <: Isotropic{SqEuclidean}\n \"Squared length scale\"\n ℓ2::T\n \"Signal variance\"\n σ2::T\n \"Shape parameter\"\n α::T\n \"Priors for kernel parameters\"\n priors::Array\nend\n\n\"\"\"\nRational Quadratic Isotropic Covariance Function\n\n RQIso(ll:T, lσ::T, lα::T)\n\n# Arguments\n - `ll::Real`: length scale (given on log scale)\n - `lσ::Real`: signal standard deviation (given on log scale)\n - `lα::Real`: shape parameter (given on log scale) \n\"\"\"\nRQIso(ll::T, lσ::T, lα::T) where T = RQIso{T}(exp(2 * ll), exp(2 * lσ), exp(lα), [])\n\nfunction set_params!(rq::RQIso, hyp::AbstractVector)\n length(hyp) == 3 || throw(ArgumentError(\"Rational Quadratic function has three parameters\"))\n rq.ℓ2, rq.σ2, rq.α = exp(2 * hyp[1]), exp(2 * hyp[2]), exp(hyp[3])\nend\n\nget_params(rq::RQIso{T}) where T = T[log(rq.ℓ2) / 2, log(rq.σ2) / 2, log(rq.α)]\nget_param_names(rq::RQIso) = [:ll, :lσ, :lα]\nnum_params(rq::RQIso) = 3\n\ncov(rq::RQIso, r::Number) = rq.σ2 * (1 + r / (2 * rq.α * rq.ℓ2))^(-rq.α)\n\n@inline dk_dll(rq::RQIso, r::Real) =\n (s = r / rq.ℓ2; rq.σ2 * s * (1 + s / (2 * rq.α))^(-rq.α - 1)) # dK_d(log ℓ)dK_dℓ\n@inline function dk_dlα(rq::RQIso, r::Real)\n s = r / rq.ℓ2\n part = 1 + s / (2 * rq.α)\n rq.σ2 * part^(-rq.α) * (s / (2 * part) - rq.α * log(part)) # dK_d(log α)\nend\n@inline function dk_dθp(rq::RQIso, r::Real, p::Int)\n if p==1\n return dk_dll(rq, r)\n elseif p==2\n return dk_dlσ(rq, r)\n elseif p==3\n return dk_dlα(rq, r)\n else\n return NaN\n end\nend\n", "meta": {"hexsha": "a3172d0b5d71ecdf6187dc77298cc7b7b2e3f81c", "size": 1831, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels/rq_iso.jl", "max_stars_repo_name": "mcusi/GaussianProcesses.jl", "max_stars_repo_head_hexsha": "7d268974aa0cd5c4164542c513307305d785da6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 284, "max_stars_repo_stars_event_min_datetime": "2015-07-31T21:32:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T07:08:58.000Z", "max_issues_repo_path": "src/kernels/rq_iso.jl", "max_issues_repo_name": "mcusi/GaussianProcesses.jl", "max_issues_repo_head_hexsha": "7d268974aa0cd5c4164542c513307305d785da6d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 171, "max_issues_repo_issues_event_min_datetime": "2015-05-28T12:04:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T06:48:23.000Z", "max_forks_repo_path": "src/kernels/rq_iso.jl", "max_forks_repo_name": "mcusi/GaussianProcesses.jl", "max_forks_repo_head_hexsha": "7d268974aa0cd5c4164542c513307305d785da6d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 59, "max_forks_repo_forks_event_min_datetime": "2015-05-31T12:44:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:21:38.000Z", "avg_line_length": 28.609375, "max_line_length": 96, "alphanum_fraction": 0.5936646641, "num_tokens": 713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625126757597, "lm_q2_score": 0.8633916082162403, "lm_q1q2_score": 0.8042169168122643}} {"text": "# Generates exponential mesh of N elements on [r_mn, r_max]\n#\n# The domain [r_min, r_max], the mesh will contain both endpoints:\nfunction gen_rmesh_exp(\n r_min::Float64,\n r_max::Float64,\n a::Float64,\n Nr::Int64\n)\n N = Nr - 1\n\n rmesh = zeros(Float64,N+1)\n SMALL = eps()\n \n if a < 0.0\n error(\"gen_rmesh_exp: a > 0 required\")\n #\n elseif abs(a - 1.0) < SMALL\n α = (r_max - r_min) / N\n for i in 1:N+1\n rmesh[i] = α * (i - 1) + r_min\n end\n #\n else\n if N > 1\n β = log(a)/(N-1)\n α = (r_max - r_min) / (exp(β*N) - 1)\n for i in 1:N+1\n rmesh[i] = α * ( exp(β*(i-1)) - 1 ) + r_min\n end\n elseif N == 1\n rmesh[1] = r_min\n rmesh[2] = r_max\n else\n error(\"gen_rmesh_exp: N >= 1 required\")\n end\n end\n return rmesh\nend\n", "meta": {"hexsha": "476f023b0379cae64edf8f26037b93cc3fb43454", "size": 904, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "dftatom/gen_rmesh_exp.jl", "max_stars_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_stars_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2018-01-03T02:19:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-29T13:30:20.000Z", "max_issues_repo_path": "dftatom/gen_rmesh_exp.jl", "max_issues_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_issues_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dftatom/gen_rmesh_exp.jl", "max_forks_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_forks_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-03-23T06:58:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-03T00:54:28.000Z", "avg_line_length": 22.6, "max_line_length": 66, "alphanum_fraction": 0.4646017699, "num_tokens": 312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191348157373, "lm_q2_score": 0.8418256412990658, "lm_q1q2_score": 0.8042121433115267}} {"text": "\r\n# glcPointsLocal(N::Int) = [0.5(1-cos((i-1)pi/(N-1))) for i in 1:N]\r\n# glcPointsGlobal(left::Number,right::Number,localPnts::Vector) = (right-left).*localPnts.-left\r\n\r\nfunction glcPointsGlobal(left::Number,right::Number,N::Int)\r\n glcPointsLocal= [0.5(1-cos((i-1)pi/(N-1))) for i in 1:N]\r\n (right-left).*glcPointsLocal.-left\r\nend\r\n\r\nfunction numstring(x::Vector)::Float64\r\n pop!(cumprod(x))\r\nend\r\n\r\nfunction CofDQM(x::Vector,order::Int)\r\n #x: vector of sampling points;\r\n #order: largest derivative order;\r\n #return: matrix with dimension of (x,x,m)\r\n\r\n n = length(x)\r\n C = fill(0.0,(n,n,order))\r\n (n>order) || error(\"need more sampling points\")\r\n\r\n # 1st order\r\n \r\n for i in 1:n, j in 1:n\r\n if i != j\r\n C[i,j,1] = numstring([((m!=i && m!=j) ? x[i]-x[m] : 1) for m in 1:n])/numstring([((m!=j) ? x[j]-x[m] : 1) for m in 1:n])\r\n\r\n # m_range_denominater = filter!(xx->xx!=i,[m for m in 1:n])\r\n # m_range_numerator = filter!(xx->xx!=j,m_range_denominater)\r\n #C[i,j,1] = numstring(filter(xx->xx!=0,[x[i]-x[m] for m in m_range_numerator]))/numstring(filter(xx->xx!=0,[x[j]-x[m] for m in m_range_denominater]))\r\n # C[i,j,1] = pop!(cumprod(filter(xx->xx!=0,[x[i]-x[m] for m in m_range_numerator])))/pop!(cumprod(filter(xx->xx!=0,[x[j]-x[m] for m in 1:n])))\r\n else\r\n\r\n # C[i,i,1] = sum(filter(xx->xx!=Inf,[1/(x[i]-x[m]) for m in 1:n]))\r\n C[i,i,1] = sum([((m!=i) ? 1/(x[i]-x[m]) : 0) for m in 1:n]) #这个慢了4个微秒\r\n\r\n \r\n end\r\n end\r\n\r\n\r\n # higher order\r\n for i in 1:n, j in 1:n, k in 2:order\r\n if i != j\r\n C[i,j,k] = k*(C[i,i,k-1]*C[i,j,1] - C[i,j,k-1]/(x[i]-x[j]))\r\n end\r\n end\r\n for i in 1:n, j in 1:n, k in 2:order\r\n if i == j\r\n C[i,j,k] = -sum([((m!=i) ? C[i,m,k] : 0) for m in 1:n])\r\n end\r\n end\r\n C\r\nend\r\n\r\n`\r\ndemoooo: test 1st-order approximation accuracy\r\n`\r\npnts = glcPointsGlobal(-10,1,100)\r\n# pnts = collect(0:2:10)\r\n\r\nCoef = CofDQM(pnts,2)\r\nf4(x::Number) = 4x^3+3x-2\r\nf4d(x) = 12x^2+3\r\n\r\nf4d.(pnts)-Coef[:,:,1]*f4.(pnts)\r\n\r\n", "meta": {"hexsha": "5b75827d823bb79dc3cd9df7621910563453d032", "size": 2133, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "demo.jl", "max_stars_repo_name": "frydaydeep/QDEM", "max_stars_repo_head_hexsha": "a11811c5111f358bed16f52187cb93a87b1c80d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "demo.jl", "max_issues_repo_name": "frydaydeep/QDEM", "max_issues_repo_head_hexsha": "a11811c5111f358bed16f52187cb93a87b1c80d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "demo.jl", "max_forks_repo_name": "frydaydeep/QDEM", "max_forks_repo_head_hexsha": "a11811c5111f358bed16f52187cb93a87b1c80d1", "max_forks_repo_licenses": ["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.9130434783, "max_line_length": 162, "alphanum_fraction": 0.5236755743, "num_tokens": 813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191335436404, "lm_q2_score": 0.8418256393148982, "lm_q1q2_score": 0.8042121403451297}} {"text": "\"\"\"\n FourierV <: AbstractVApproximator{Int}\n\n struct FourierV <: AbstractVApproximator{Int}\n weights::Vector{Float64}\n end\n\nUsing Fourier cosine basis to approximate the state value.\n`weights` is the featur vector.\n\nSee more details at Section (9.5.2) on Page 211 of the book *Sutton, Richard S., and Andrew G. Barto. Reinforcement learning: An introduction. MIT press, 2018.*\n\"\"\"\nstruct FourierV <: AbstractVApproximator{Int}\n weights::Vector{Float64}\nend\n\n\"\"\"\n FourierV(order::Int)\n\nBy specifying the `order`, feature vector will be initialized with 0.\n\"\"\"\nFourierV(order::Int) = FourierV(zeros(Float64, order+1))\n\nfunction (f::FourierV)(s)\n sum(w * cos((i-1) * π * s) for (i, w) in enumerate(f.weights))\nend\n\nfunction update!(f::FourierV, s, e)\n for i in 1:length(f.weights)\n f.weights[i] += e * cos((i-1) * π * s)\n end\nend", "meta": {"hexsha": "c26f8a7806609732bef0470beb3b3ce15aeb6f3b", "size": 864, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/approximators/fourier_V.jl", "max_stars_repo_name": "JuliaTagBot/Ju.jl", "max_stars_repo_head_hexsha": "f951f940de7ea007fe3e0be8c6e477bb6fadd05e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2019-01-03T02:57:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-19T14:09:28.000Z", "max_issues_repo_path": "src/approximators/fourier_V.jl", "max_issues_repo_name": "JuliaTagBot/Ju.jl", "max_issues_repo_head_hexsha": "f951f940de7ea007fe3e0be8c6e477bb6fadd05e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25, "max_issues_repo_issues_event_min_datetime": "2018-12-25T10:02:47.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-30T09:06:43.000Z", "max_forks_repo_path": "src/approximators/fourier_V.jl", "max_forks_repo_name": "JuliaTagBot/Ju.jl", "max_forks_repo_head_hexsha": "f951f940de7ea007fe3e0be8c6e477bb6fadd05e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-12-25T09:51:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:06:30.000Z", "avg_line_length": 27.0, "max_line_length": 160, "alphanum_fraction": 0.6770833333, "num_tokens": 250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9553191259110588, "lm_q2_score": 0.8418256452674009, "lm_q1q2_score": 0.8042121396063665}} {"text": "# Code from previous section\nusing PyPlot\nusing Statistics\nA = imread(\"sample_photo.png\")\nB = mean(A, dims=3)[:,:,1]\nfunction imshow_scale(A)\n # Like imshow(A) but scales the values to [0,1] and supports grayscale\n \n A .-= minimum(A) # Scale and shift to [0,1]\n A ./= maximum(A)\n if ndims(A) < 3\n A = reshape(A, size(A,1), size(A,2), 1)\n end\n if size(A,3) == 1\n A = repeat(A, 1, 1, 3) # Set R=G=B for grayscale\n end\n imshow(A)\n end;\n\n# Uncomment below if the package is not already installed\n#using Pkg; Pkg.add(\"FFTW\") \n\nusing FFTW\n\nfunction imagefft_demo(A)\n AF = fftshift(fft(A))\n subplot(1,2,1); imshow_scale(A);\n subplot(1,2,2); imshow_scale(log.(1 .+ abs.(AF)));\n return\nend\n\nG = [zeros(256,128) ones(256,128)]\nimagefft_demo(G)\n\nG = zeros(256, 256)\nG[78:178, 78:178] .= 1.0\nimagefft_demo(G)\n\nG = Float32[ (i+j<329) && (i+j>182) && (i-j>-67) && (i-j<73) for i = 1:256, j = 1:256 ]\nimagefft_demo(G)\n\nG = Float32[ sin(2pi*(10i + 20j)/256) for i = 1:256, j = 1:256 ]\nimagefft_demo(G)\n\nimagefft_demo(B)\n\nBpernoise = copy(B)\nBpernoise = B + 0.5*Float32[sin(2π*10j / size(B,2)) for i = 1:size(B,1), j = 1:size(B,2) ]\nimagefft_demo(Bpernoise)\n\n# Filter\nBF = fftshift(fft(Bpernoise))\nmid = size(B) .÷ 2 .+ 1\nBF[mid[1], mid[2] + 10] = 0\nBF[mid[1], mid[2] - 10] = 0\nBfiltered = real.(ifft(ifftshift(BF)))\n\nimagefft_demo(Bfiltered)\n", "meta": {"hexsha": "64492af6dc2e7da178f7ab1f9b511e07ae58ae33", "size": 1394, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "textbook/_build/jupyter_execute/content/Image_Processing/Fourier_Transform.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/Image_Processing/Fourier_Transform.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/Image_Processing/Fourier_Transform.jl", "max_forks_repo_name": "NoseKnowsAll/NoseKnowsAll.github.io", "max_forks_repo_head_hexsha": "b2cff3e33cc2087770fb4aecb38b7925ad8d6e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.6271186441, "max_line_length": 90, "alphanum_fraction": 0.6054519369, "num_tokens": 530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430812881347, "lm_q2_score": 0.8615382129861583, "lm_q1q2_score": 0.8041863144760127}} {"text": "# # [Ross-Macdonald Malaria Modeling](@id ross-macdonald)\n#\n#md # [![](https://img.shields.io/badge/show-nbviewer-579ACA.svg)](@__NBVIEWER_ROOT_URL__/examples/Ross-Macdonald.ipynb)\n\n# Authors: Sean Wu and Sophie Libkind\n\nusing AlgebraicDynamics.DWDDynam\nusing Catlab.WiringDiagrams\nusing LabelledArrays\n\nusing Catlab.Graphics\nusing DelayDiffEq, DifferentialEquations\nusing Plots\n\n\n# The Ross-Macdonald (RM) model is the canonical model of malaria transmission, first expressed by \n# Sir Ronald Ross in 1911. The simplest form of the model is given by a system of 2 nonlinear ordinary \n# differential equations describing $Z$, parasite prevalence in the mosquito vector population, and $X$, \n# parasite prevalence in the vertebrate host population:\n# $$ \\dot X = mazbZ(1 - X) - rX, \\quad \\dot Z = acX (e^{-gn} - Z) - gZ \\quad (1)$$ \n\n#- \n\n# The RM model is of supreme importance to modeling of malaria and other mosquito transmitted diseases \n# because it is the simplest model that retains the fundamental processes involved in transmission: recovery \n# of infected hosts, death of infected mosquitoes, and parasite transmission between discordant pairs of \n# vectors and hosts. In this sense it represents the irreducible complexity to modeling mosquito borne \n# diseases, such that any simpler model would be insufficient.\n\n# The model assumes that mosquitoes take bloodmeals (bites) on vertebrate hosts with rate $a$. \n# Therefore, the per-capita rate at which susceptible mosquitoes become infected is $acX$, where $c$ \n# is the transmission efficiency from infectious humans to susceptible mosquitoes (probability of \n# parasites successfully invading the mosquito given a bite occurs) and $X$ is the probability the\n# bite lands on an infectious human. $1-Z$ is the proportion of mosquitoes who are susceptible but \n# given an incubation period of $n$ days during which mosquitoes suffer per-capita mortality at rate \n# $g$, only a proportion $e^{-gn}$ survive incubation to become infectious. Therefore the classic \n# RM model will have statics that are consistent with the incorporation of an incubation period of \n# fixed duration, but dynamics will not, as the delay is not incorporated into the equations.\n\n#- \n\n# Susceptible humans acquire infection at a rate $mabZ$, where $m = M/H$, the ratio of mosquitoes to \n# humans, $a$ is as before, and $b$ is the transmission efficiency from infectious mosquitoes to \n# susceptible humans. Therefore $mabZ$ gives the per-capita rate at which susceptible humans recieve \n# parasites from the mosquito population. Infectious humans recover at a rate $r$ (the rate at which the \n# immune system clears parasites). Because $m$ is considered a constant parameter, the model ignores \n# seasonal fluctuations in mosquito (or host) population sizes. However, because the timescale of host \n# dynamcis is typically slow in relation to mosquito dynamics, the approximation is often suitable \n# over a transmission season.\n\n#-\n\n# The model's threshold criterion between the trivial equilibrium where both $Z,X$ are equal to zero \n# (no disease) and the endemic equilibrium can be expressed by the basic reproductive number, giving \n# the expected number of secondary infections arising from the introduction of a single infectious human,\n# $$R_0 = \\frac{ma^2bce^{-gn}}{rg}.$$ The endemic equilibrium is therefore: \n# $$\\bar{X}= \\frac{R_{0}-1}{R_{0} + \\frac{ac}{g}}, \\quad \\bar{Z} = \\frac{ac\\bar{X}}{g + ac\\bar{X}} e^{-gn}.$$\n#-\n# From these equations, the nonlinear relationships that characterize observed malaria transmission can be \n# understood. We implement them as follows:\n\n\n\n# ## Diagram of Systems\n# First we must construct a diagram of systems which describes the interaction between the mosquito and \n# host populations. The arrows between the two subsystems represents the bidirectional infection during bloodmeals. \n\nbloodmeal = WiringDiagram([], [:mosquitos, :humans])\nmosq_box = add_box!(bloodmeal, Box(:mosquitos, [:x], [:z]))\nhuman_box = add_box!(bloodmeal, Box(:humans, [:z], [:x]))\noutput_box = output_id(bloodmeal)\n\nadd_wires!(bloodmeal, Pair[\n (mosq_box, 1) => (human_box, 1),\n (human_box, 1) => (mosq_box, 1),\n (mosq_box, 1) => (output_box, 1),\n (human_box, 1) => (output_box, 2)]\n)\n\n\nto_graphviz(bloodmeal)\n\n# ## ODE Model\n# Next we implement the concrete mosquito and host dynamics given in Equation (1), and apply them to the diagram \n# of systems. This composition is the complete Ross-Macdonald model which we can solve and plot. \n\ndZdt = function(u,x,p,t)\n Z = u[1]\n X = x[1]\n [p.a*p.c*X*(exp(-p.g*p.n) - Z) - p.g*Z]\nend\n\ndXdt = function(u,x,p,t)\n X = u[1]\n Z = x[1]\n [p.m*p.a*p.b*Z*(1 - X) - p.r*X]\nend\n \n#- \n\nmosquito_model = ContinuousMachine{Float64}(1, 1, 1, dZdt, (u,p,t) -> u)\nhuman_model = ContinuousMachine{Float64}(1, 1, 1, dXdt, (u,p,t) -> u)\n\nmalaria_model = oapply(bloodmeal, \n Dict(:humans => human_model, :mosquitos => mosquito_model)\n)\n\n#- \nparams = LVector(a = 0.3, b = 0.55, c = 0.15, \n g = 0.1, n = 10, r = 1.0/200, m = 0.5)\n\nu0 = [0.1, 0.3]\ntspan = (0.0, 365.0*2)\n\nprob = ODEProblem(malaria_model, u0, tspan, params)\nsol = solve(prob, Tsit5());\n#- \n\nplot(sol, malaria_model,\n lw=2, title = \"Ross-Macdonald Malaria model\", \n xlabel = \"time\", ylabel = \"proportion infectious\",\n color = [\"magenta\" \"blue\"]\n)\n\n## Plot the equilibrium behavior as well\na, b, c, g, n, r, m = params\nR0 = (m*a^2*b*c*exp(-g*n))/(r*g)\nX̄ = (R0 - 1)/(R0 + (a*c)/g)\nZ̄ = (a*c*X̄)/(g + a*c*X̄)*exp(-g*n)\n\nN = length(sol)\nplot!(sol.t, fill(X̄, N), label = \"human equilibrium\", ls = :dash, lw = 2, color = \"blue\")\nplot!(sol.t, fill(Z̄, N), label = \"mosquito equilibrium\", ls = :dash, lw = 2, color = \"magenta\")\n\n# ## Delay Model \n# The previous models did not capture the incubation period for the disease in the\n# mosquito population. To do so we can replace the models with delay differential equations \n# and apply them to the same diagram of systems representing the bloodmeal.\n\ndzdt_delay = function(u,x,h,p,t)\n Y, Z = u\n Y_delay, Z_delay = h(p, t - p.n)\n X, X_delay = x[1]\n \n [p.a*p.c*X*(1 - Y - Z) -\n p.a*p.c*X_delay*(1 - Y_delay - Z_delay)*exp(-p.g*p.n) -\n p.g*Y,\n p.a*p.c*X_delay*(1 - Y_delay - Z_delay)*exp(-p.g*p.n) -\n p.g*Z]\nend\n\ndxdt_delay = function(u,x,h,p,t)\n X, = u\n Z, _ = x[1]\n [p.m*p.a*p.b*Z*(1 - X) - p.r*X]\nend\n\n#- \n\n\nmosquito_delay_model = DelayMachine{Float64, 2}(\n 1, 2, 1, dzdt_delay, (u,h,p,t) -> [[u[2], h(p,t - p.n)[2]]])\n\nhuman_delay_model = DelayMachine{Float64, 2}(\n 1, 1, 1, dxdt_delay, (u,h,p,t) -> [[u[1], h(p, t - p.n)[1]]])\n\nmalaria_delay_model = oapply(bloodmeal, \n Dict(:humans => human_delay_model, :mosquitos => mosquito_delay_model)\n)\n#- \nparams = LVector(a = 0.3, b = 0.55, c = 0.15, \n g = 0.1, n = 10, r = 1.0/200, m = 0.5)\n\nu0_delay = [0.09, .01, 0.3]\ntspan = (0.0, 365.0*3)\nhist(p,t) = u0_delay;\n\nprob = DDEProblem(malaria_delay_model, u0_delay, [], hist, tspan, params)\nalg = MethodOfSteps(Tsit5())\nsol = solve(prob, alg)\n\nplot(sol, label=[\"non-infectious mosquito population\" \"infectious mosquito population\" \"host population\"],\n lw=2, title = \"Ross-Macdonald malaria model\",\n xlabel = \"time\", ylabel = \"proportion infectious\",\n color = [\"magenta\" \"red\" \"blue\"]\n)\n\n# While the equilibrium points of the two models are identical, they exhibit different dynamical behavior \n# before settling down to equilibrium. Because models are often used to examine how the system may respond \n# to intervention, incorporating additional biological realism can produce more plausible results regarding \n# the expected time for interventions to affect the system. In any case, such simple models are best used as \n# tools to explain basic concepts in malaria epidemiology rather than descriptions of real systems, which are \n# likely far from equilibrium and affected by weather, climate, policy, and other external forces.", "meta": {"hexsha": "e149e548c41c7258c27d3905473fb62a0b632996", "size": 7945, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Ross-Macdonald.jl", "max_stars_repo_name": "stjordanis/AlgebraicDynamics.jl", "max_stars_repo_head_hexsha": "70065459dc5fe19322a0d7972fadba3d21be4458", "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/Ross-Macdonald.jl", "max_issues_repo_name": "stjordanis/AlgebraicDynamics.jl", "max_issues_repo_head_hexsha": "70065459dc5fe19322a0d7972fadba3d21be4458", "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/Ross-Macdonald.jl", "max_forks_repo_name": "stjordanis/AlgebraicDynamics.jl", "max_forks_repo_head_hexsha": "70065459dc5fe19322a0d7972fadba3d21be4458", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.1658031088, "max_line_length": 120, "alphanum_fraction": 0.6999370673, "num_tokens": 2303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9334308054739519, "lm_q2_score": 0.8615382165412808, "lm_q1q2_score": 0.8041863114127197}} {"text": "# This is Julia code for discretizing AR(1) process by using Tauchen method (1986)\n# written on 2017/10/17\n# z' = rho*z+e e~N(0,(sig_e)^2)\n#\n# INPUTS\n# N: Number of grids\n# m: Max number of std devs from mean\n# rho: Coeffecient of AR(1) process z'=mew+rho*z+e, e~N(0,sigmasq)\n# sig_e: Std of innovation, e, in AR(1) process\n#\n# OUTPUT\n# vZ: grids\n# mPI: transition prob. matrix\n\n\n## Preliminary\n\n###############################################################\n## 0. Define CDF function (from https://www.johndcook.com/blog/cpp_phi/)\n###############################################################\n\nfunction phi(x::Real)\n # constants\n const a1 = 0.254829592;\n const a2 = -0.284496736;\n const a3 = 1.421413741;\n const a4 = -1.453152027;\n const a5 = 1.061405429;\n const p = 0.3275911;\n\n # Save the sign of x\n sign = 1;\n if (x < 0)\n sign = -1;\n end\n x = abs(x)/sqrt(2.0);\n\n # A&S formula 7.1.26\n t = 1.0/(1.0 + p*x);\n y = 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x);\n\n return 0.5*(1.0 + sign*y);\nend\n\n\n##############################################################\n##############################################################\n## MAIN PART\n##############################################################\n##############################################################\n\n\n###########################################################\n## 1. Define Parameters\n###########################################################\n\n# Ex. Standard quarterly calibration for productivity process\n# of US economy\n\nconst N = 5; # Number of grids, N\nconst m = 3; # Max number of std devs from mean\nconst rho = 0.95; # AR(1) coefficient\nconst sig_e = 0.007; # std of innovation\n\n###########################################################\n## 2. Generating grids\n###########################################################\n\nsig_z = sqrt((sig_e^2)/(1-rho^2)); # std of AR(1) r.v.\nz_max = m*sig_z; # Max grid\nz_min = -z_max; # Min grid\nd = (z_max-z_min) / (N-1); # incriment of grids\nvZ = linspace(z_min, z_max, N); # Grid vector 1*N\n\n###########################################################\n## 3. Transition matrix\n###########################################################\n\nmPI = zeros(N,N); # Transition matrix N*N\n\nfor i in 1:N\n for j in 1:N\n if j == 1\n mPI[i,j] = phi((vZ[1]+d/2-rho*vZ[i])/sig_e); # If z' is min grid\n elseif j == N-1\n mPI[i,j] = 1 - phi((vZ[N]-d/2-rho*vZ[i])/sig_e); # z' is the max grid\n else\n mPI[i,j] = phi((vZ[j]+d/2-rho*vZ[i])/sig_e) - phi((vZ[j]-d/2-rho*vZ[i])/sig_e);\n end\n end\nend\n\n###########################################################\n## 4. Display result with 4 decimals\n###########################################################\nprint(\"Grid points are \\n\")\nfor i in 1:N\n @printf \"%6.4f\" vZ[i]\n print(\" \")\nend\nprint(\"\\n\")\nprint(\"Transition prob. matrix is\\n\")\nfor i in 1:N\n for j in 1:N\n @printf \"%6.4f\" mPI[i,j]\n print(\" \")\n end\n print(\"\\n\")\nend\n", "meta": {"hexsha": "15248ace7375bd766740882e5606358555148562", "size": 3163, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "tauchen.jl", "max_stars_repo_name": "Akihisa-Kato/discretizing_stochastic_process", "max_stars_repo_head_hexsha": "5166cf882b45af41047bdb2111bb5ef2d63ed760", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tauchen.jl", "max_issues_repo_name": "Akihisa-Kato/discretizing_stochastic_process", "max_issues_repo_head_hexsha": "5166cf882b45af41047bdb2111bb5ef2d63ed760", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tauchen.jl", "max_forks_repo_name": "Akihisa-Kato/discretizing_stochastic_process", "max_forks_repo_head_hexsha": "5166cf882b45af41047bdb2111bb5ef2d63ed760", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7545454545, "max_line_length": 91, "alphanum_fraction": 0.3939298135, "num_tokens": 882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403959948494, "lm_q2_score": 0.8652240686758841, "lm_q1q2_score": 0.8041742010143885}} {"text": "\"\"\"\n shifted_backward_sub!(x, R, λ, k) → x\n\nSolve the problem (R[1:k,1:k] - λI) \\\\ x[1:k] in-place.\n\"\"\"\nfunction shifted_backward_sub!(x, R::AbstractMatrix{Tm}, λ, k) where {Tm<:Real}\n # Real arithmetic with quasi-upper triangular R\n @inbounds while k > 0\n if k > 1 && R[k,k-1] != zero(Tm)\n # Solve 2x2 problem\n R11, R12 = R[k-1,k-1] - λ, R[k-1,k]\n R21, R22 = R[k ,k-1] , R[k ,k] - λ\n det = R11 * R22 - R21 * R12\n a1 = ( R22 * x[k-1] - R12 * x[k-0]) / det\n a2 = (-R21 * x[k-1] + R11 * x[k-0]) / det\n x[k-1] = a1\n x[k-0] = a2\n\n # Backward substitute\n for i = 1 : k-2\n x[i] -= R[i,k-1] * x[k-1] + R[i,k-0] * x[k-0]\n end\n k -= 2\n else\n # Solve 1x1 \"problem\"\n x[k] /= R[k,k] - λ\n \n # Backward substitute\n for i = 1 : k - 1\n x[i] -= R[i,k] * x[k]\n end\n\n k -= 1\n end\n end\n \n x\nend\n\nfunction shifted_backward_sub!(x, R::AbstractMatrix, λ, k)\n # Generic implementation, upper triangular R\n @inbounds while k > 0\n # Solve 1x1 \"problem\"\n x[k] /= R[k,k] - λ\n\n # Backward substitute\n for i = 1 : k - 1\n x[i] -= R[i,k] * x[k]\n end\n\n k -= 1\n end\n \n x\nend\n\n\"\"\"\n collect_eigen!(x, R, j) → k\n\nStore the `j`th eigenvector of an upper triangular matrix `R` in `x`.\nIn the end `norm(x[1:k]) = 1` This function leaves x[k+1:end] untouched!\n\"\"\"\nfunction collect_eigen!(x::AbstractVector{Tv}, R::AbstractMatrix{Tm}, j::Integer) where {Tm<:Real,Tv<:Number}\n n = size(R, 2)\n\n @inbounds begin\n # If it's a conjugate pair with the next index, then just increment j.\n if j < n && R[j+1,j] != zero(Tv)\n j += 1\n end\n\n # Initialize the rhs and do the first backward substitution\n # Then do the rest of the shifted backward substitution in another function,\n # cause λ is either real or complex.\n if j > 1 && R[j,j-1] != 0\n # Complex arithmetic\n R11, R21 = R[j-1,j-1], R[j-0,j-1]\n R12, R22 = R[j-1,j-0], R[j-0,j-0]\n det = R11 * R22 - R21 * R12\n tr = R11 + R22\n λ = (tr + sqrt(complex(tr * tr - 4det))) / 2\n x[j-1] = -R12 / (R11 - λ)\n x[j-0] = one(Tv)\n for i = 1 : j-2\n x[i] = -R[i,j-1] * x[j-1] - R[i,j]\n end\n\n shifted_backward_sub!(x, R, λ, j-2)\n else\n # Real arithmetic\n λ = R[j,j]\n x[j] = one(Tv)\n for i = 1 : j-1\n x[i] = -R[i,j]\n end\n shifted_backward_sub!(x, R, λ, j-1)\n end\n\n # Normalize\n nrm = zero(real(Tv))\n for k = 1:j\n nrm += abs2(x[k])\n end\n scale = inv(√nrm)\n for k = 1:j\n x[k] *= scale\n end\n end\n\n return j\nend\n\nfunction collect_eigen!(x::AbstractVector{Tv}, R::AbstractMatrix, j::Integer) where {Tv}\n n = size(R, 2)\n\n @inbounds begin\n λ = R[j,j]\n x[j] = one(Tv)\n for i = 1 : j-1\n x[i] = -R[i,j]\n end\n\n shifted_backward_sub!(x, R, λ, j-1)\n\n # Normalize\n nrm = zero(real(Tv))\n for k = 1:j\n nrm += abs2(x[k])\n end\n scale = inv(√nrm)\n for k = 1:j\n x[k] *= scale\n end\n end\n\n return j\nend", "meta": {"hexsha": "33b5444b894c15238c2f7e51549069274276338b", "size": 3514, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/eigenvector_uppertriangular.jl", "max_stars_repo_name": "andreasnoack/ArnoldiMethod.jl", "max_stars_repo_head_hexsha": "d44bac4022e5e39f9fa80f6398091c41180ec5a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 41, "max_stars_repo_stars_event_min_datetime": "2018-08-28T14:04:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-29T02:18:47.000Z", "max_issues_repo_path": "src/eigenvector_uppertriangular.jl", "max_issues_repo_name": "andreasnoack/ArnoldiMethod.jl", "max_issues_repo_head_hexsha": "d44bac4022e5e39f9fa80f6398091c41180ec5a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 37, "max_issues_repo_issues_event_min_datetime": "2018-05-21T12:53:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-27T08:58:38.000Z", "max_forks_repo_path": "src/eigenvector_uppertriangular.jl", "max_forks_repo_name": "andreasnoack/ArnoldiMethod.jl", "max_forks_repo_head_hexsha": "d44bac4022e5e39f9fa80f6398091c41180ec5a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2018-09-10T19:35:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T11:48:46.000Z", "avg_line_length": 25.6496350365, "max_line_length": 109, "alphanum_fraction": 0.43767786, "num_tokens": 1177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541626630935, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.8040904983680742}} {"text": "load(\"src/init.jl\")\n\n# Given inputs, ouputs, lambda and current weights,\n# Assess the ridge loss function.\n# Assume first entry of w is an intercept and do not penalize.\n\nfunction ridge_error(x, y, l, w)\n (1.0 / 2.0) * sum(map(z -> z^2, y - x * w)) + (l / 2.0) * sum(map(z -> z^2, w[2:length(w)]))\nend\n\nridge_error([1.0 2; 3 4], [1, 2], 1, [1, 1])\n\nfunction ridge_gradient(x, y, l, w)\n\tunshift(l * w[2:length(w)], 0) - x' * (y - x * w)\nend\n\nridge_gradient([1.0 1 2; 1 3 4], [1, 2], 1, [1, 1, 1])\n\nfunction ridge_regression(x, y, l)\n\tfunction f(w)\n ridge_error(x, y, l, w)\n end\n\t\n function g(w)\n ridge_gradient(x, y, l, w)\n end\n\t\n\tw0 = zeros(size(x, 2))\n\t\n\tsolution = gradient_descent(f, g, w0)\n\t\n\tsolution.minimum\nend\n\nx = [1 1 2; 1 3 3; 1 5 6]\ny = [1, 2, 2]\n\nw = ridge_regression(x, y, 0.0)\nx * w\nnorm(w)\n\nw = ridge_regression(x, y, 1.0)\nx * w\nnorm(w)\n\nw = ridge_regression(x, y, 10.0)\nx * w\nnorm(w)\n\nw = ridge_regression(x, y, 100.0)\nx * w\nnorm(w)\n\np = 10\n\nx = hcat([1, 1], vcat([1:p]', [(p + 1):(2p)]'))\ny = [1, 2]\n\nw = ridge_regression(x, y, 0)\nx * w\nnorm(w)\n\nw = ridge_regression(x, y, 1)\nx * w\nnorm(w)\n\nw = ridge_regression(x, y, 10)\nx * w\nnorm(w)\n", "meta": {"hexsha": "e634526a3bc43c162316a7b1001af8774eb42ba8", "size": 1164, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "use_cases/ridge_regression/ridge.jl", "max_stars_repo_name": "aviks/Optim.jl", "max_stars_repo_head_hexsha": "9c2a9a88c5b9329ad4233760a6e5331fd6d771e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-05-22T09:32:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-22T09:32:32.000Z", "max_issues_repo_path": "use_cases/ridge_regression/ridge.jl", "max_issues_repo_name": "aviks/Optim.jl", "max_issues_repo_head_hexsha": "9c2a9a88c5b9329ad4233760a6e5331fd6d771e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "use_cases/ridge_regression/ridge.jl", "max_forks_repo_name": "aviks/Optim.jl", "max_forks_repo_head_hexsha": "9c2a9a88c5b9329ad4233760a6e5331fd6d771e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.6285714286, "max_line_length": 94, "alphanum_fraction": 0.5738831615, "num_tokens": 491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541577509315, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.8040904959239166}} {"text": "export Atan\n\n\"\"\"\n`Atan([domainType=Float64::Type,] dim_in::Tuple)`\n\nCreates an inverse tangent non-linear operator with input dimensions `dim_in`:\n```math\n\\\\text{atan} ( \\\\mathbf{x} ).\n```\n\n\"\"\"\nstruct Atan{T,N} <: NonLinearOperator\n\tdim::NTuple{N,Int}\nend\n\nfunction Atan(DomainType::Type, DomainDim::NTuple{N,Int}) where {N} \n\tAtan{DomainType,N}(DomainDim)\nend\n\nAtan(DomainDim::NTuple{N,Int}) where {N} = Atan{Float64,N}(DomainDim)\nAtan(DomainDim::Vararg{Int}) = Atan{Float64,length(DomainDim)}(DomainDim)\n\nfunction mul!(y::AbstractArray{T,N}, L::Atan{T,N}, x::AbstractArray{T,N}) where {T,N}\n\ty .= atan.(x)\nend\n\nfunction mul!(y::AbstractArray, \n J::AdjointOperator{Jacobian{A,TT}}, \n b::AbstractArray) where {T, N, A <: Atan{T,N}, TT <: AbstractArray{T,N}}\n L = J.A\n y .= conj.(1.0./(1.0.+ L.x.^2)).*b\nend\n\nfun_name(L::Atan) = \"atan\"\n\nsize(L::Atan) = (L.dim, L.dim)\n\ndomainType(L::Atan{T,N}) where {T,N} = T\ncodomainType(L::Atan{T,N}) where {T,N} = T\n", "meta": {"hexsha": "f1669dbdca919828602bf8f65bba339748e6558b", "size": 984, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nonlinearoperators/Atan.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/Atan.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/Atan.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.6, "max_line_length": 86, "alphanum_fraction": 0.6382113821, "num_tokens": 347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.941654159388319, "lm_q2_score": 0.8539127473751341, "lm_q1q2_score": 0.804090490320502}} {"text": "## ND LINEAR INTERPOLATION KERNELS\n\n\"\"\"\n lerp(t, v0, v1)\n\nLinear interpolation between `f(x0)=v0` and `f(x1)=v1` at the normalized coordinate t\n\"\"\"\n@inline lerp(t, v0, v1) = fma(t, v1, fma(-t, v0, v0))\n\n\"\"\"\n bilinear(tx, ty, v00, v10, v01, v11)\n\nLinear interpolation between `f(x0,y0)=v0` and `f(x1,y1)=v1` at the normalized coordinates `tx`, `ty`\n\"\"\"\n@inline function ndlinear(tx, ty, v00, v10, v01, v11)\n return lerp(ty, lerp(tx, v00, v10), lerp(tx, v01, v11))\nend\n\n@inline function ndlinear(t::NTuple{2,T1}, v::NTuple{4,T2}) where {T1,T2}\n return ndlinear(t[1], t[2], v[1], v[2], v[3], v[4])\nend\n\nbilinear(tx, ty, v00, v10, v01, v11) = ndlinear(tx, ty, v00, v10, v01, v11)\n\n\"\"\"\n trilinear(tx, ty, tz, v000, v100, v001, v101, v010, v110, v011, v111) \n\nLinear interpolation between `f(x0,y0,z0)=v0` and `f(x1,y1,z1)=v1` at the normalized coordinates `tx`, `ty`, `tz`\n\"\"\"\n@inline function ndlinear(tx, ty, tz, v000, v100, v001, v101, v010, v110, v011, v111)\n return lerp(\n ty,\n ndlinear(tx, tz, v000, v100, v001, v101),\n ndlinear(tx, tz, v010, v110, v011, v111),\n )\nend\n\n@inline function ndlinear(t::NTuple{3,T1}, v::NTuple{8,T2}) where {T1,T2}\n return ndlinear(t[1], t[2], t[3], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8])\nend\n\n@inline function trilinear(tx, ty, tz, v000, v100, v001, v101, v010, v110, v011, v111)\n return ndlinear(tx, ty, tz, v000, v100, v001, v101, v010, v110, v011, v111)\nend\n", "meta": {"hexsha": "53c9398f5356b49e4b7a0f258da16de5fa3c0713", "size": 1449, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kernels.jl", "max_stars_repo_name": "albert-de-montserrat/StencilInterpolations.jl", "max_stars_repo_head_hexsha": "a48c29e1f664987098a4f88b28c54576524ebf9e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernels.jl", "max_issues_repo_name": "albert-de-montserrat/StencilInterpolations.jl", "max_issues_repo_head_hexsha": "a48c29e1f664987098a4f88b28c54576524ebf9e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernels.jl", "max_forks_repo_name": "albert-de-montserrat/StencilInterpolations.jl", "max_forks_repo_head_hexsha": "a48c29e1f664987098a4f88b28c54576524ebf9e", "max_forks_repo_licenses": ["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.2, "max_line_length": 113, "alphanum_fraction": 0.6183574879, "num_tokens": 595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465116437761, "lm_q2_score": 0.8596637523076225, "lm_q1q2_score": 0.8040834919075339}} {"text": "module Power \nexport power_method, inverse_power_method\n\nusing LinearAlgebra\n\n\"\"\"\nCalculate the dominant eigenvalue of a matrix A and its associated eigenvector.\n\"\"\"\nfunction power_method(A::Matrix{<:Real}, x::Vector{<:Real}, n::Int)::Tuple\n\ty = x\n\tm = 1\n\n\tfor _ in 0:n\n\t\ty = A * x\n\t\tm = maximum(abs.(y))\n\t\tx = (m^-1)y\n\tend\n\n\treturn (m, y)\nend\n\n\"\"\"\nCalculate the least dominant eigenvalue of a matrix A and its associated\neigenvector.\n\"\"\"\nfunction inverse_power_method(A::Matrix{<:Real}, x::Vector{<:Real}, n::Int)::Tuple\n\treturn power_method(inv(A), x, n)\nend\n\nend\n", "meta": {"hexsha": "c8b84f375147bf67746d6860909445de07b38195", "size": 566, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/power.jl", "max_stars_repo_name": "severen/playground", "max_stars_repo_head_hexsha": "3f9b95c1d5ad187c140d908d102e874d61924988", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "julia/power.jl", "max_issues_repo_name": "severen/playground", "max_issues_repo_head_hexsha": "3f9b95c1d5ad187c140d908d102e874d61924988", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/power.jl", "max_forks_repo_name": "severen/playground", "max_forks_repo_head_hexsha": "3f9b95c1d5ad187c140d908d102e874d61924988", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.2580645161, "max_line_length": 82, "alphanum_fraction": 0.6908127208, "num_tokens": 170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465170505204, "lm_q2_score": 0.8596637433190939, "lm_q1q2_score": 0.804083488148127}} {"text": "using DataDrivenDiffEq\nusing OrdinaryDiffEq\nusing LinearAlgebra\nusing Plots\ngr()\n\n# Create a linear , time discrete system\nfunction linear_discrete(du, u, p, t)\n du[1] = 0.9u[1]\n du[2] = 0.9u[2] + 0.1u[1]\nend\n\nu0 = [10.0; -2.0]\ntspan = (0.0, 10.0)\nprob = DiscreteProblem(linear_discrete, u0, tspan)\nsol = solve(prob, FunctionMap())\n\n# Create Approximation\napprox = DMD(sol[:,:])\n\n# Create the associated problem\nprob_approx = DiscreteProblem(approx, u0, tspan)\napprox_sol = solve(prob_approx, FunctionMap())\n\n# Show solutions\nplot(sol)\nplot!(approx_sol)\n\n# Show error\nplot((sol .- approx_sol)')\nnorm(sol .- approx_sol) # ≈ 2.23e-14\n\n# Eigen Decomposition\neigen(approx)\n# Eigenvalues\nscatter(eigvals(approx), xlim = (-1, 1), ylim = (-1,1))\n\n# Adapt system with new measurements\nfunction linear_discrete_2(du, u, p, t)\n du[1] = 0.9u[1]\n du[2] = 0.9u[2] + 0.2u[1]\nend\n\n# Solve the new system\nprob2 = DiscreteProblem(linear_discrete_2, u0, (0.0, 20.0))\nsol2 = solve(prob2, FunctionMap())\n\n# Split the data\nx = sol2[:,1:20]\ny = sol2[:,2:21]\n\n# Update our approximation with new measurements\nupdate!(approx, x, y)\n\n# Lets have a look at the operator, which moves near the true value\noperator(approx)\n\n# Add time continouos system\nfunction linear(du, u, p, t)\n du[1] = -0.9*u[1] + 0.1*u[2]\n du[2] = -0.8*u[2]\nend\n\nprob_cont = ODEProblem(linear, u0, tspan)\nsol_cont = solve(prob_cont, Tsit5())\n\nplot(sol_cont)\n\nX = sol_cont[:,:]\nDX = sol_cont(sol_cont.t, Val{1})[:,:]\n\n# Giving the method a time step (which should be sequentially sampled)\n# Enables us to get the continouos representation\napprox_cont = gDMD(X, DX)\ngenerator(approx_cont)\napprox_sys = ODEProblem(approx_cont, u0, tspan)\napprox_sol = solve(approx_sys, Tsit5(), saveat = sol_cont.t)\n# Lets have a look at the solution\nplot(sol_cont)\nplot!(approx_sol)\n# And the error\nplot(abs.(sol_cont .- approx_sol)')\nnorm(sol_cont .- approx_sol) # ≈ 1e-13\n", "meta": {"hexsha": "3325843f90de4c879bf8cb95f2cc56cbdde6390b", "size": 1918, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/DMD_Examples.jl", "max_stars_repo_name": "asinghvi17/DataDrivenDiffEq.jl", "max_stars_repo_head_hexsha": "502332931d0b97e18b3e3d6441bad54102b5cf52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/DMD_Examples.jl", "max_issues_repo_name": "asinghvi17/DataDrivenDiffEq.jl", "max_issues_repo_head_hexsha": "502332931d0b97e18b3e3d6441bad54102b5cf52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/DMD_Examples.jl", "max_forks_repo_name": "asinghvi17/DataDrivenDiffEq.jl", "max_forks_repo_head_hexsha": "502332931d0b97e18b3e3d6441bad54102b5cf52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8333333333, "max_line_length": 70, "alphanum_fraction": 0.6949947862, "num_tokens": 650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465080392795, "lm_q2_score": 0.8596637433190939, "lm_q1q2_score": 0.80408348040149}} {"text": "__precompile__()\n# ----------------------------------------------------------------------------\nmodule FAD # Forward Automatic Differentiation demo\n#=\n see also:\n - the walkthrough at http://vladium.com/tutorials/study_julia_with_me/multiple_dispatch/\n\n working with this module from REPL:\n\n julia>include(\"/FAD.jl\")\n julia>using Main.FAD\n ... REPL can now use derivative(), ∂(), root_solve(), etc ...\n=#\n# ............................................................................\n\nimport Base; # needed in order to add base ops overloads\n\nexport derivative, ∂, myerf, root_solve; # for convenience of 'using Main.FAD' in REPL\n\n# ............................................................................\n\nstruct Context <: Number\n v ::Number\n ∂ ::Number\nend\n# ............................................................................\n# binary ops:\n\n# note: ':()' is necessary to reference certain functions with single-character names\n\nBase.:(+)(lhs ::Context, rhs ::Context) = Context(lhs.v + rhs.v, lhs.∂ + rhs.∂)\nBase.:(-)(lhs ::Context, rhs ::Context) = Context(lhs.v - rhs.v, lhs.∂ - rhs.∂)\n\nBase.:(*)(lhs ::Context, rhs ::Context) = Context(lhs.v * rhs.v, lhs.v * rhs.∂ + lhs.∂ * rhs.v)\nBase.:(/)(lhs ::Context, rhs ::Context) = Context(lhs.v / rhs.v, (lhs.∂ * rhs.v - lhs.v * rhs.∂) / rhs.v^2)\n\n# unary ops:\n\nBase.:(+)(x ::Context) = x\nBase.:(-)(x ::Context) = Context(- x.v, - x.∂)\n\n# math ops:\n\nBase.sin(d ::Context) = Context(sin(d.v), cos(d.v) * d.∂)\nBase.cos(d ::Context) = Context(cos(d.v), - sin(d.v) * d.∂)\n# ... add more as needed for your own functions ...\n\n# ............................................................................\n# conversion/promotion:\n\nBase.promote_rule(::Type{Context}, ::Type{<: Number}) = Context\nBase.convert(::Type{Context}, x ::Real) = Context(x, 0.0)\n\n# ............................................................................\n\"\"\"\n Given a function 'f' of one variable, return its derivative with respect to that variable.\n\"\"\"\nfunction derivative(f ::Function)\n return x ::Number -> f(Context(x, 1.0)).∂ # discard value, return derivative\nend\n\n∂ = derivative # add a nice-looking alias\n\n# ............................................................................\n\n# to get \"official\" erf(x), do\n# pkg> add SpecialFunctions\n# julia> using SpecialFunctions\n\nfunction myerf(x ::Number)\n Σ = 0.0\n x² = x * x\n for k in 0 : 20 # hardcoding the number of summation terms for simplicity\n Σ += x / (factorial(k) * (2k + 1))\n x *= -x²\n end\n return 2.0 / √π * Σ\nend\n# ............................................................................\n\"\"\"\n Newton's method for finding root(s) of 'f'\n\"\"\"\nfunction root_solve(f ::Function, x₀ ::Number; ϵ = 1e-8)\n i = 1\n while true\n ctx = f(Context(x₀, 1.0))\n println(\"[$i]: f($x₀)\\t= $(ctx.v)\")\n abs(ctx.v) < ϵ && break\n x₀ -= ctx.v / ctx.∂ # ignoring issues with division by small floats, etc for simplicity\n i += 1\n end\n return x₀\nend\n\nend # of module\n# ----------------------------------------------------------------------------\n", "meta": {"hexsha": "79a087a696b3738f421d8fcf37ab744a7e28de44", "size": 3155, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "multiple_dispatch/FAD.jl", "max_stars_repo_name": "vladium/study_julia_with_me", "max_stars_repo_head_hexsha": "8c7a0b614098091ef284ebee1250c69f222fa126", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-10-16T00:46:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-02T17:08:46.000Z", "max_issues_repo_path": "multiple_dispatch/FAD.jl", "max_issues_repo_name": "vladium/study_julia_with_me", "max_issues_repo_head_hexsha": "8c7a0b614098091ef284ebee1250c69f222fa126", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "multiple_dispatch/FAD.jl", "max_forks_repo_name": "vladium/study_julia_with_me", "max_forks_repo_head_hexsha": "8c7a0b614098091ef284ebee1250c69f222fa126", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5257731959, "max_line_length": 107, "alphanum_fraction": 0.4748019017, "num_tokens": 800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273633016692238, "lm_q2_score": 0.8670357563664174, "lm_q1q2_score": 0.8040571416892335}} {"text": "# arb_hypgeom.jl\n\nmodule arb_hypgeom\nexport one_f_two_fast, one_f_two\n\nusing ArbNumerics\n\n\"\"\"\nImplementation of the hypergeometric function 1F2 using the expansion:\n\n 1F2(a1; {b1, b2}; z) = ∑_{k=0}^∞ (a1)_k z^k / ((b1)_k ⋅ (b2)_k ⋅ k!)\n\nwhere (x)_k is the Pochhammer rising factorial = Γ(x+k)/Γ(x) with Γ(x) the Gamma function.\n\"\"\"\n\nfunction one_f_two(a, b, x; prec = 64) # z > 0 & n >= 0\n\n # Initialise precision of ArbReal to prec.\n setextrabits(0)\n setprecision(ArbReal, prec + 8)\n\n a = ArbReal(\"$a\")\n b = (ArbReal(\"$i\") for i in b)\n x = ArbReal(\"$x\")\n\n k = ArbReal(\"0\")\n result = ArbReal(\"0.0\")\n err = eps(result) # Machine accuracy of specified precision prec.\n\n risingfact(w, n) = ArbReal(ArbNumerics.gamma(w + n) / ArbNumerics.gamma(w))\n\n while true\n term = ArbReal(risingfact(a, k) * x^k / (prod(risingfact.(b, k)) * ArbNumerics.gamma(k + 1)))\n\n # Break loop if term smaller than accuracy of result.\n if abs(term) < err\n break\n end\n\n result += term\n k += ArbReal(\"1\")\n\n # Double precision if rounding error in result exceeds accuracy specified by prec.\n if ball(result)[2] > err\n setprecision(ArbReal, precision(result) * 2)\n k = ArbReal(\"0\")\n a = ArbReal(\"$a\")\n b = (ArbReal(\"$i\") for i in b)\n x = ArbReal(\"$x\")\n result = ArbReal(\"0.0\")\n end\n end\n ArbReal(result, bits = prec + 8)\nend\n\n\"\"\"\nImplementation of specific 1F2 hypergeometric function used for integrals:\n\n ∫_0^1 cosh(zx) x^{2m} dx = 1F2(m+1/2; {1/2, m+3/2}; z^2/4)/(2m+1)\n = ∑_{t=0}^∞ z^{2t} / ((2t+2m+1)⋅(2t)!)\n\n ∫_0^1 sinh(zx) x^{2m} dx = z ⋅ 1F2(m+1; {3/2, m+2}; z^2/4)/(2m+2)\n = ∑_{t=0}^∞ z^{2t+1} / ((2t+2m+2)⋅(2t+1)!)\n\nwhich we can combine into a generic summation:\n\n ∑_{t=0}^∞ z^{2t+h} / ((2t+2m+1+h)⋅(2t+h)!)\n\nwhich gives the cosh version for h=0 and the sinh version for h=1. This specialised 1F2 converges faster than generic 1F2 algorithm, one_f_two.\n\"\"\"\n\nfunction one_f_two_fast(x, m, h; prec = 64) # z > 0 & n >= 0\n\n # Initialise precision of ArbReal to prec.\n p = prec\n setextrabits(0)\n setprecision(ArbReal, p)\n\n x = ArbReal(\"$x\")\n m = ArbReal(\"$m\")\n h = ArbReal(\"$h\")\n\n k = ArbReal(\"0\")\n result = ArbReal(\"0.0\")\n term = ArbReal(\"1.0\")\n err = eps(result) # Machine accuracy of specified precision prec.\n\n while abs(midpoint(term)) > err * abs(midpoint(result))\n term = ArbReal(x^(2 * k + h) / ((2 * k + 2 * m + 1 + h) * ArbNumerics.gamma(2 * k + 1 + h)))\n result += term\n # println(\"term: k = \", k, \"\\nterm value: \", ball(ArbReal(term, bits = prec)), \"\\ncumulant result: \", ball(ArbReal(result, bits = prec)), \"\\n\")\n k += 1\n\n # Double precision if rounding error in result exceeds accuracy specified by prec.\n if radius(result) > err * abs(midpoint(result))\n p *= 2\n setprecision(ArbReal, p)\n # println(\"Not precise enough. Error = \", abs(radius(result)/midpoint(result)), \" > \", err, \". Increasing precision to \", p, \" bits.\\n\")\n x = ArbReal(\"$x\")\n m = ArbReal(\"$m\")\n h = ArbReal(\"$h\")\n k = ArbReal(\"0\")\n result = ArbReal(\"0.0\")\n term = ArbReal(\"1.0\")\n end\n end\n # println(\"x: \", ArbReal(x, bits = prec), \". Final result: \", ArbReal(result, bits = prec))\n ArbReal(result, bits = prec)\nend\n\n# β = ArbReal(\"2.0\")\n# α = ArbReal(\"7.0\")\n# v = ArbReal(\"5.8\")\n# w = ArbReal(\"1.6\")\n# R = ArbReal((v^2 - w^2) / (w^2 * v))\n# a = ArbReal(sqrt(β^2 / 4 + R * β * coth(β * v / 2)))\n# z = ArbReal(\"90.61\")\n# m = ArbReal(\"1.0\")\n# @time c = one_f_two_fast(z, m, 0; prec = 64)\n# @show(c)\n\nend # end module\n\n################################################################################\n\n\"\"\"\nSome plots and tests of the above functions to check that they produce the correct values to the specified precision.\n\"\"\"\n\n# using Plots\n# using QuadGK\n# plotly()\n# Plots.PlotlyBackend()\n#\n# cosh_integral(z, m) = quadgk(t -> (m + 1) * cosh(z * t) * t^m, BigFloat(0), BigFloat(1))[1]\n#\n# # x_range = 0:200\n# # m = 1\n# # @time I = [cosh_integral(x, m) for x in x_range]\n# # @time F = abs.([arb_hypgeom_1f2(m / 2 + 1 / 2, (1 / 2, m / 2 + 3/2), x^2 / 4.0; prec = 128) for x in x_range])\n# # p = plot(x_range, F, yaxis=:log)\n# # plot!(x_range, I)\n# # display(p)\n# # @show(I, F)\n# # println(m / 2 + 1 / 2, (1 / 2, m / 2 + 3/2), x_range^2 / 4.0)\n#\n# \"\"\"\n# Conclusion: The integral is a bit faster than the hypergeometric function, but not as accurate. So, probably use 1F2 since the time difference doesn't seem to be major!\n# \"\"\"\n#\n# # @time F_test = arb_hypgeom_1f2(1/2, (1/2, 1/2), 1/2; prec = 512)\n# # setprecision(BigFloat, 512)\n# # t_test = parse(BigFloat, \"2.17818355660857086398922206782012528343129403292165693281081574094992093930206091916837394310903919052930938811320102906774905335969974706202490049810447181898779259195640840870264051023127290510625691429186995752638681515944856002645204867940492548077249544\")\n# # @show(F_test, t_test)\n# # @show(isequal(\"$F_test\"[end-1], \"$t_test\"[end-1]))\n#\n# \"\"\"\n# The 1F2 function above can accurate produce high precision values as shown in the above test. But it can be simplified and optimized mathematically initially as shown below.\n# \"\"\"\n#\n# x_range = 0:200\n# m = 1\n# h = 0\n# @time L = abs.([arb_hypergeom_1f2_fast(x, m, h; prec = 128) for x in x_range])\n# # @time F = abs.([arb_hypgeom_1f2(m + 1 / 2, (1 / 2, m + 3/2), x^2 / 4.0; prec = 128) / (2 * m + 1) for x in x_range])\n# p = plot(x_range, L, yaxis=:log)\n# # plot!(x_range, F)\n# display(p)\n# @show(L)\n\n", "meta": {"hexsha": "12bf57d79e08c85ed1e75207e212acc4a05888ef", "size": 5713, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "arb/ArbHygeom.jl", "max_stars_repo_name": "jarvist/PolaronMobility-FeynmanKadanoffOsakaHellwarth", "max_stars_repo_head_hexsha": "a1deffc5bfb0c6b6cb9dd7d9388578f4248915f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-07-26T17:46:18.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-26T17:46:18.000Z", "max_issues_repo_path": "arb/ArbHygeom.jl", "max_issues_repo_name": "jarvist/PolaronMobility-FeynmanKadanoffOsakaHellwarth", "max_issues_repo_head_hexsha": "a1deffc5bfb0c6b6cb9dd7d9388578f4248915f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "arb/ArbHygeom.jl", "max_forks_repo_name": "jarvist/PolaronMobility-FeynmanKadanoffOsakaHellwarth", "max_forks_repo_head_hexsha": "a1deffc5bfb0c6b6cb9dd7d9388578f4248915f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4093567251, "max_line_length": 291, "alphanum_fraction": 0.5760546123, "num_tokens": 2001, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.8887588008585926, "lm_q1q2_score": 0.8040161316265136}} {"text": "\n# We consider as an illustrative example a simple harmonic oscillator system.\n# The set propagation definitions introduced so far are illustrated using a single\n# degree of freedom second order problem given by the following equation:\n\n# ```math\n# u''(t) + ω^2 u(t) = 0,\n# ```\n# where $ω$ is a scalar and $u(t)$ is the unknown.\n#\n# This problem can be associated with a spring-mass system, where $u(t)$ is the\n# elongation of the spring at time $t$ and the mass and stiffness set a natural\n# frequency $ω$. In this case we consider $ω = 4π$.\n\n# Let us introduce the state variable $v(t) := u'(t)$ and define the vector\n# $x(t) = [u(t), v(t)]^T$. Then we can rewrite the system in the following first order form\n#\n#\n# ```math\n# x'(t) = \\begin{pmatrix} 0 & 1 \\\\ -\\omega^2 & 0 \\end{pmatrix} x(t)\n#\n# Two cases are considered for the initial conditions, first a single initial condition\n# given by $u(0)=1$ and $v(0)=0$, and a second case where the initial conditions belong to a set.\n\n# This problem is solved using set propagation and the results obtained for the\n# single initial condition are shown in the following figures.\n#\n# The time step-size used is $\\delta = 0.025$.\n#\n# The set $\\Omega_0$ includes the analytic trajectory within $[0, \\delta]$, and\n# such set is propagated to cover the solution for further time intervals as shown below.\n#\n# It is worth noting that even when the initial condition is a singleton,\n# the set propagation technique returns a sequence of sets, and such sequence guarantees\n# an enclosure of the analytic solution at \\emph{any} time $t \\in [0, T] \\subset \\mathbb{R}$.\n#\n# For comparison, we also plot the analytic solution (magenta solid line) and a\n# numerical solution obtained using the Newmark's method with time step $\\delta/5$\n# (red triangle markers).\n\n# The result obtained when a set of initial conditions, together with few dozen\n# trajectories with random initial conditions drawn from the initial set\n# $\\mathcal{X}_0 = \\mathcal{U}_0 \\times \\mathcal{V}_0 = [0.9, 1.1] \\times [-0.1, 0.1]$,\n# where $\\times$ denotes the Cartesian product.\n\n# In both cases, it is shown that a single set-based integration covers infinitely\n# many trajectories \\emph{in dense time}, i.e. for all intermediate times between\n# $0$ and $T$, where $T > 0$ is the time horizon, there is a reach-set that covers\n# all the exact solutions.\n", "meta": {"hexsha": "a811ebde5c443fe6e588be5b6a3983eb5257c933", "size": 2363, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/SDOF/SDOF.jl", "max_stars_repo_name": "JuliaReach/SetPropagation-FEM-Examples", "max_stars_repo_head_hexsha": "8ee58bdbc1e253b9ca2ddb60973a6b6f1e82cd94", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/SDOF/SDOF.jl", "max_issues_repo_name": "JuliaReach/SetPropagation-FEM-Examples", "max_issues_repo_head_hexsha": "8ee58bdbc1e253b9ca2ddb60973a6b6f1e82cd94", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-11-26T18:32:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-21T23:33:44.000Z", "max_forks_repo_path": "examples/SDOF/SDOF.jl", "max_forks_repo_name": "JuliaReach/SetPropagation-FEM-Examples", "max_forks_repo_head_hexsha": "8ee58bdbc1e253b9ca2ddb60973a6b6f1e82cd94", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.26, "max_line_length": 97, "alphanum_fraction": 0.7215404147, "num_tokens": 633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.9046505453836383, "lm_q1q2_score": 0.8040161219164325}} {"text": "export lse, lomax, randomindex\n\n# Log-sum exp.\nfunction lse(x::AbstractMatrix{<:Real}; dims = 2)\n m = maximum(x, dims = dims)\n v = exp.(x .- m)\n return log.(sum(v, dims = dims)) + m\nend\n\n# see https://www.cs.ubc.ca/~murphyk/Papers/bayesGauss.pdf\nfunction tpdf(μ::T, σ::T, ν::T, x::V) where {T<:Real,V<:Real}\n c = gamma(ν/2 + 1/2) / gamma(ν/2)\n c *= 1/(sqrt(ν*π)*σ)\n return c * (1 + 1/ν * ((x-μ)/σ)^2)^((ν+1)/2)\nend\n\nfunction tlogpdf(μ::T, σ::T, ν::T, x::V) where {T<:Real,V<:Real}\n c = lgamma(ν/2 + 1/2) - lgamma(ν/2)\n c -= log(sqrt(ν*π)*σ)\n return c + ((ν+1)/2)*log(1 + 1/ν * ((x-μ)/σ)^2)\nend\n\n@inline lomax(x, α, λ) = log(α) - log(λ) + -(α + 1) * log(1 + (x / λ))\n\nfunction randomindex(p::AbstractVector{T}) where T<: Real\n return randomindex(p, rand(T))\nend\n\nfunction randomindex(p::AbstractVector{T}, rnd::T) where T<: Real\n\n csum = T(0.0)\n thres = rnd * sum(p)\n\n for i in 1:length(p)\n @inbounds begin\n csum += p[i]\n if csum >= thres\n return Int(i)\n end\n end\n end\n\n return Int(length(p))\nend", "meta": {"hexsha": "3bf8333ebac6a9086504901bbbef4aec957f267e", "size": 1102, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mathutil.jl", "max_stars_repo_name": "crinders/BayesianSumProductNetworks", "max_stars_repo_head_hexsha": "2c0512599be03aef72ec4cd8a529a5c002f82992", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2019-06-04T09:06:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-08T20:04:49.000Z", "max_issues_repo_path": "src/mathutil.jl", "max_issues_repo_name": "crinders/BayesianSumProductNetworks", "max_issues_repo_head_hexsha": "2c0512599be03aef72ec4cd8a529a5c002f82992", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-07-08T08:16:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-30T19:08:04.000Z", "max_forks_repo_path": "src/mathutil.jl", "max_forks_repo_name": "crinders/BayesianSumProductNetworks", "max_forks_repo_head_hexsha": "2c0512599be03aef72ec4cd8a529a5c002f82992", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-02-20T09:57:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T02:32:14.000Z", "avg_line_length": 25.0454545455, "max_line_length": 70, "alphanum_fraction": 0.5299455535, "num_tokens": 439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545362802362, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.8040044749038813}} {"text": "# Unit statistics.jl, part of PosDefManifold Package for julia language\n# v 0.3.5 - last update 6th of November 2019\n#\n# MIT License\n# Copyright (c) 2019, Marco Congedo, CNRS, Grenobe, France:\n# https://sites.google.com/site/marcocongedo/home\n#\n# DESCRIPTION\n# This Unit implements routines for statistics and probability.\n#\n# CONTENT\n# 1. Utilities\n# 2. Probability\n# 3. Descriptive Statistocs\n# __________________________________________________________________\n\n\n# ------------------------\n## 1. Utilities\n# ------------------------\n\n\n# ------------------------\n## 2. Probability\n# ------------------------\n\n\"\"\"\n softmax(χ::Vector{T}) where T<:Real\n\n Given a real vector of ``k`` non-negative scores ``χ=c_1,...,c_k``,\n return the vector ``π=p_1,...,p_k`` of their\n [softmax](https://en.wikipedia.org/wiki/Softmax_function) probabilities,\n as per\n\n `` p_i=\\\\frac{\\\\textrm{e}^{c_i}}{\\\\sum_{i=1}^{k}\\\\textrm{e}^{c_i}} ``.\n\n ## Examples\n χ=[1.0, 2.3, 0.4, 5.0]\n π=softmax(χ)\n\n\"\"\"\nsoftmax(χ::Vector{T}) where T<:Real = exp.(χ) ./ 𝚺(exp.(χ))\n\n\n# -------------------------\n## 3. Descriptive Statistics\n# -------------------------\n\"\"\"\n mean(metric::Metric, ν::Vector{T}) where T<:RealOrComplex\n\n Mean of ``k`` real or complex scalars, using the specified `metric`\n of type [Metric::Enumerated type](@ref). Note that using the Fisher,\n logEuclidean and Jeffrey metric, the resulting mean\n is the scalar geometric mean. Note also that the code of this method\n is in unit *statistics.jl*, while the code for all the others is\n in unit *riemannianGeometry.jl*.\n\n ## Examples\n using PosDefManifold\n # Generate 10 random numbers distributed as a chi-square with 2 df.\n ν=[randχ²(2) for i=1:10]\n arithmetic_mean=mean(Euclidean, ν)\n geometric_mean=mean(Fisher, ν)\n harmonic_mean=mean(invEuclidean, ν)\n harmonic_mean<=geometric_mean<=arithmetic_mean # AGH inequality\n\n\"\"\"\nfunction mean(metric::Metric, ν::Vector{T}) where T<:RealOrComplex\n if metric == Euclidean return mean(ν)\n elseif metric == invEuclidean return inv(mean(inv, ν))\n elseif metric in (Fisher,\n logEuclidean,\n Jeffrey) return exp(mean(log, ν))\n elseif metric == logdet0\n @warn \"function statistics.mean (scalar mean) not implemented for metric $metric\"\n elseif metric == ChoEuclidean return (mean(√, ν))^2\n elseif metric == logCholesky return exp((mean(log, sqrt.(ν))))^2\n elseif metric == VonNeumann\n @warn \"function statistics.mean and .geodesic not defined for metric $metric\"\n elseif metric == Wasserstein return (mean(√, ν))^(-0.5)\n else\n @error \"in RiemannianGeometry.mean function: the chosen 'metric' does not exist\"\n end # if metric\nend\n\n\"\"\"\n std(metric::Metric, ν::Vector{T};\n corrected::Bool=true,\n mean=nothing) where T<:RealOrComplex\n\n Standard deviation of ``k`` real or complex scalars,\n using the specified `metric`\n of type [Metric::Enumerated type](@ref) and the\n specified `mean` if provided.\n\n Only the Euclidean and Fisher\n metric are supported by this function. Using the Euclidean\n metric return the output of standard Julia\n [std](https://docs.julialang.org/en/v1/stdlib/Statistics/#Statistics.std)\n function. Using the Fisher metric return the scalar geometric standard deviation,\n which is defined such as,\n\n ``\\\\sigma=\\\\text{exp}\\\\Big(\\\\sqrt{k^{-1}\\\\sum_{i=1}^{k}\\\\text{ln}^2(v_i/\\\\mu})\\\\Big)``.\n\n If `corrected` is `true`, then the sum is scaled with ``k-1``,\n whereas if it is `false` the sum is scaled with ``k``.\n\n ## Examples\n using PosDefManifold\n # Generate 10 random numbers distributed as a chi-square with 2 df.\n ν=[randχ²(2) for i=1:10]\n arithmetic_sd=std(Euclidean, ν) # mean not provided\n geometric_mean=mean(Fisher, ν)\n geometric_sd=std(Fisher, ν, mean=geometric_mean) # mean provided\n\n\"\"\"\nfunction std(metric::Metric, ν::Vector{T};\n corrected::Bool=true,\n mean=nothing) where T<:RealOrComplex\n\n if metric == Euclidean return std(ν; corrected=corrected, mean=mean)\n\n elseif metric == Fisher\n mean==nothing ? μ=mean(Fisher, ν) : μ=mean\n if corrected return exp(√(𝚺(log(w/μ)^2 for w in ν)/(length(ν)-1)))\n else return exp(√(𝛍(log(w/μ)^2 for w in ν))) end\n\n elseif metric in (invEuclidean, logEuclidean, Jeffrey,\n logdet0, ChoEuclidean, logCholesky,\n VonNeumann, Wasserstein)\n @warn \"function statistics.mean (scalar mean) not implemented for metric $metric\"\n else\n @error \"in RiemannianGeometry.mean function: the chosen 'metric' does not exist\"\n end # if metric\nend\n", "meta": {"hexsha": "0c24a5f3a6ad4dd2f8354d5d3b901dd99b4a6b15", "size": 4731, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/statistics.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/PosDefManifold.jl-f45a3650-5c51-11e9-1e9a-133aa5e309cf", "max_stars_repo_head_hexsha": "f5351c8a9891784b6ac94ff0cf8bbdd5249824d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/statistics.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/PosDefManifold.jl-f45a3650-5c51-11e9-1e9a-133aa5e309cf", "max_issues_repo_head_hexsha": "f5351c8a9891784b6ac94ff0cf8bbdd5249824d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/statistics.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/PosDefManifold.jl-f45a3650-5c51-11e9-1e9a-133aa5e309cf", "max_forks_repo_head_hexsha": "f5351c8a9891784b6ac94ff0cf8bbdd5249824d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-22T09:30:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-22T09:30:35.000Z", "avg_line_length": 34.7867647059, "max_line_length": 89, "alphanum_fraction": 0.6404565631, "num_tokens": 1310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109742068041, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.8039929741195879}} {"text": "# f(x)=elu(x)=x*[x>0] + (exp(x)-1)*[x<0]\n\nalpha=1.0\nfunction Felu(x)\n y=zeros(size(x))\n for i=1:length(x)\n if x[i]>0\n y[i]=x[i]\n else\n y[i]=alpha*(exp(x[i])-1.0)\n end\n end\n return (y,nothing)\nend\n\nfunction Felu_inplace(value::Array,auxvalue,x) # inplace\n for i=1:length(x)\n if x[i]>0\n value[i]=x[i]\n else\n value[i]=alpha*(exp(x[i])-1.0)\n end\n end\nend\n\n\nfunction Delu(derivativeIDX,f_c,faux_c,grad_c,grad_n,x)\n tmp=ones(size(x))\n for i=1:length(x)\n if x[i]<0\n tmp[i]=f_c[i]+alpha\n end\n end\n axpy!(1.0,tmp.*grad_c,grad_n) \nend\n\nif 1==0 # TODO GPU version\n\n function Felu_inplace(value::CudaArray,auxvalue,x::CudaArray...) # inplace\n end\n\n function Delu(derivativeIDX,f_c,faux_c,grad_c,grad_n,x::CudaArray...)\n end\n\nend\n\nDerivative[Felu]=Delu # Define dictionary lookup\nInplace[Felu]=Felu_inplace\n\nelu(n::ADnode)=ADnode(Felu,n)\n\n###elu(A::ADtrans)=transpose(elu(node[A.parent])) # elu(A')=(elu(A))' TODO:check\n\nexport elu\n", "meta": {"hexsha": "b4f17afb6712ac1d410c1305f0c2411f30e70199", "size": 1075, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/Felu.jl", "max_stars_repo_name": "davidbarber/AutoDiff", "max_stars_repo_head_hexsha": "b8d50c467a8d035a88315e7a8c8403a553c53383", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30, "max_stars_repo_stars_event_min_datetime": "2016-03-20T20:52:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-22T07:31:59.000Z", "max_issues_repo_path": "src/functions/Felu.jl", "max_issues_repo_name": "davidbarber/AutoDiff", "max_issues_repo_head_hexsha": "b8d50c467a8d035a88315e7a8c8403a553c53383", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-06-17T20:12:48.000Z", "max_issues_repo_issues_event_max_datetime": "2016-06-17T20:12:48.000Z", "max_forks_repo_path": "src/functions/Felu.jl", "max_forks_repo_name": "davidbarber/AutoDiff", "max_forks_repo_head_hexsha": "b8d50c467a8d035a88315e7a8c8403a553c53383", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2016-01-11T21:36:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-06T21:04:40.000Z", "avg_line_length": 19.5454545455, "max_line_length": 80, "alphanum_fraction": 0.5730232558, "num_tokens": 369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107984180245, "lm_q2_score": 0.8577681013541613, "lm_q1q2_score": 0.8039095271276464}} {"text": "#=\n Where is my bag problem.\n\n From\n \"Probabilistic Reasoning Under Uncertainty with Bayesian Networks\"\n https://www.bayesia.com/2018-03-02-probabilistic-reasoning-under-uncertainty\n\n (Also see The BaysiaLabBook \"Bayesian Networks BayesiaLab\" v1, page 51f.)\n\n Travel from Singapore -> Tokyo -> Los Angeles.\n 1) The departure of Singapore -> Tokyo is delayed\n 2) Just made the Tokyo -> LA trip. There's a 50/50 change the luggage is on the plane to LA.\n 3) Arriving at LA, waiting for the luggage in 5 minutes, the luggage has not been seen.\n What is the probability that the bag was in the Tokyo -> LA plane?\n \n Answer: The probability that the bag was with the LA plane is 33% (as in the talk).\n\n From Judea Pearl: The Book of Why.\n\n For p(bag_on_plane) = 0.5\n parameters mean std naive_se mcse ess rhat ess_per_sec \n bag_on_plane 0.3364 0.4725 0.0047 0.0053 8953.8759 1.0001 1581.1188\n\n\n For p(bag_on_plane) = 0.8\n parameters mean std naive_se mcse ess rhat ess_per_sec \n bag_on_plane 0.6641 0.4723 0.0047 0.0051 8363.8461 0.9999 1469.6619\n\n\n Cf ~/blog/where_is_my_bag.blog\n ~/webppl/where_is_my_bag.wppl\n\n=#\nusing Turing, StatsPlots, Distributions\ninclude(\"jl_utils.jl\")\n\n@model function where_is_my_bag(maxTime=10,p=0.5,time=5.0,bag_on_carousel=false) \n\n # We know that the bag was on the plane with 50% probability.\n # Variant: https://www.youtube.com/watch?v=c71pnonOMkI&t=1074s it's 80/20.\n bag_on_plane ~ flip(p)\n \n # We assume uniform time step\n time ~ DiscreteUniform(1,maxTime)\n \n # Probability that the bag is on the carousel given a specific time\n # (if it was on the plane, that is).\n # The probability that the bag is on the carousel on a given time\n # is directly proportional on the time:\n # time / maxTime\n bag_on_carousel ~ bag_on_plane == true ? flip(1.0*time/maxTime) : Dirac(0.0)\n \n # He waited 5 minutes without seeing the luggage.\n # Note: It's faster if we observe via the parameters\n # true ~ Dirac(time == 5.0)\n # true ~ Dirac(bag_on_carousel == false)\n\n \nend\n\nmaxTime = 10\np = 0.5\n# p = 0.8\ntime = 5.0\nbag_on_carousel = false\nmodel = where_is_my_bag(maxTime,p,time,bag_on_carousel)\n\n# chns = sample(model, Prior(), 10_000)\n# chns = sample(model, MH(), 10_000)\nchns = sample(model, PG(15), 10_000)\n# chns = sample(model, SMC(), 10_000)\n# chns = sample(model, IS(), 10_000)\n\ndisplay(chns)\n# display(plot(chns))\n\n", "meta": {"hexsha": "976ffe38c67c9580b13c179afec56cb3121f2725", "size": 2536, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/where_is_my_bag.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/turing/where_is_my_bag.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/turing/where_is_my_bag.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 32.9350649351, "max_line_length": 94, "alphanum_fraction": 0.6715299685, "num_tokens": 808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029487, "lm_q2_score": 0.8577681013541611, "lm_q1q2_score": 0.8039095211103381}} {"text": "\"\"\"\n PeriodicKernel(r::AbstractVector)\n PeriodicKernel(dims::Int)\n PeriodicKernel(T::DataType, dims::Int)\n\nPeriodic Kernel as described in http://www.inference.org.uk/mackay/gpB.pdf eq. 47.\n```\n κ(x,y) = exp( - 0.5 sum_i(sin (π(x_i - y_i))/r_i))\n```\n\"\"\"\nstruct PeriodicKernel{T} <: SimpleKernel\n r::Vector{T}\n function PeriodicKernel(; r::AbstractVector{T} = ones(Float64, 1)) where {T<:Real}\n @assert all(r .> 0)\n new{T}(r)\n end\nend\n\nPeriodicKernel(dims::Int) = PeriodicKernel(Float64, dims)\n\nPeriodicKernel(T::DataType, dims::Int = 1) = PeriodicKernel(r = ones(T, dims))\n\nmetric(κ::PeriodicKernel) = Sinus(κ.r)\n\nkappa(κ::PeriodicKernel, d::Real) = exp(- 0.5d)\n\nBase.show(io::IO, κ::PeriodicKernel) = print(io, \"Periodic Kernel, length(r) = \", length(κ.r), \")\")\n", "meta": {"hexsha": "0878c27e9e69d14e0ff0efc083d013aedff4fd9d", "size": 798, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/basekernels/periodic.jl", "max_stars_repo_name": "tirthasheshpatel/KernelFunctions.jl", "max_stars_repo_head_hexsha": "86d430c8e275a8b41b0a4a68aeb31e488a075b83", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/basekernels/periodic.jl", "max_issues_repo_name": "tirthasheshpatel/KernelFunctions.jl", "max_issues_repo_head_hexsha": "86d430c8e275a8b41b0a4a68aeb31e488a075b83", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/basekernels/periodic.jl", "max_forks_repo_name": "tirthasheshpatel/KernelFunctions.jl", "max_forks_repo_head_hexsha": "86d430c8e275a8b41b0a4a68aeb31e488a075b83", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5, "max_line_length": 99, "alphanum_fraction": 0.6466165414, "num_tokens": 264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107949104865, "lm_q2_score": 0.8577680977182187, "lm_q1q2_score": 0.8039095207113477}} {"text": "\nusing Plots\nusing LinearAlgebra\n\ndx = 0.001\nL = pi\nx = L * (-1+dx:dx:1)\nn = length(x)\nnquart = Int(floor(n/4))\n\n# Define hat function\nf = zeros(n);\nf[nquart:2*nquart] = 4*(1:nquart+1)/n\nf[2*nquart+1:3*nquart] = (-4*(0:nquart-1).+1)/n\n\np1 = plot(x, f)\n\n# Compute Fourier series\n\nA0 = sum(f) * dx\n\nfFS = A0/2\nA = zeros(20)\nB = zeros(20)\n\nfor k = 1:20\n A[k] = sum(f.*cos.(pi*k*x/L)) * dx\n B[k] = sum(f.*sin.(pi*k*x/L)) * dx\n global fFS = A[k]*cos.(k*pi*x/L) .+ B[k]*sin.(k*pi*x/L) .+ fFS\n plot!(x, fFS)\nend\n\nfFS2 = A0/2\n\nkmax = 100\nA2 = zeros(kmax+1)\nB2 = zeros(kmax+1)\nERR = zeros(kmax+1)\n\nA2[1] = A0/2\nERR[1] = norm(f-fFS)\np2 = plot(x, f)\n\nfor k = 1:kmax\n A2[k+1] = sum(f.*cos.(pi*k*x/L)) * dx\n B2[k+1] = sum(f.*sin.(pi*k*x/L)) * dx\n plot!(x, B2[k] * sin.(2k*pi*x/L))\n global fFS2 = A2[k+1]*cos.(k*pi*x/L) .+ B2[k+1]*sin.(k*pi*x/L) .+ fFS2\n ERR[k+1] = norm(f-fFS2)/norm(f)\nend\n\np3 = plot(0:kmax, A2)\np4 = plot(0:kmax, ERR, yaxis = :log)\n", "meta": {"hexsha": "e69123ddf30e9824f19e651a3c704ffaf6eb023f", "size": 964, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ddsae/CODE/CH02/CH02_SEC01_1_FourierSines.jl", "max_stars_repo_name": "sje30/catam-julia", "max_stars_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-07-13T12:55:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:40:23.000Z", "max_issues_repo_path": "ddsae/CODE/CH02/CH02_SEC01_1_FourierSines.jl", "max_issues_repo_name": "sje30/catam-julia", "max_issues_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2021-07-11T21:35:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-25T12:10:58.000Z", "max_forks_repo_path": "ddsae/CODE/CH02/CH02_SEC01_1_FourierSines.jl", "max_forks_repo_name": "sje30/catam-julia", "max_forks_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-13T21:00:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-13T21:00:47.000Z", "avg_line_length": 17.8518518519, "max_line_length": 74, "alphanum_fraction": 0.5373443983, "num_tokens": 465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107861416413, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.8039095148935342}} {"text": "using Plots\n\n\nfunction branin(x, a=1, b=5.1/(4π^2), c=5/π, r=6, s=10, t=1/(8π))\n return a * (x[2] - b * x[1]^2 + c * x[1] - r)^2 + s*(1-t) * cos(x[1]) + s;\nend\n\n\n# plot\n\ncontour(-50:50, -50:50, (x, y)->branin([x, y]))\n\n", "meta": {"hexsha": "4b108db7b7b3ff8c5e35259accc2e3310a6597ed", "size": 222, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test_function/branin_function.jl", "max_stars_repo_name": "tor4z/convex_optimization", "max_stars_repo_head_hexsha": "15fd3aa09fbc3306ff68cc301bbddac3d2006f3f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test_function/branin_function.jl", "max_issues_repo_name": "tor4z/convex_optimization", "max_issues_repo_head_hexsha": "15fd3aa09fbc3306ff68cc301bbddac3d2006f3f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test_function/branin_function.jl", "max_forks_repo_name": "tor4z/convex_optimization", "max_forks_repo_head_hexsha": "15fd3aa09fbc3306ff68cc301bbddac3d2006f3f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.0769230769, "max_line_length": 78, "alphanum_fraction": 0.4684684685, "num_tokens": 118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9724147153749275, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.8039067077007966}} {"text": "# Define exit time\nA = 600\n\n# Starting amount of money (S0)\nk = 500\n\n# Define probability of winning\np = .49\nq = 1 - p\n\n# Define b vector\nb = zeros(A + 1)\nb[A+1] = 1\n\n# Define M matrix\nM = zeros(A+1, A+1)\nM[1,1] = 1\nM[A+1,A+1] = 1\n\nfor i=2:A\n global M, q, p\n M[i,i] = -1\n M[i,i-1] = q\n M[i,i+1] = p\nend\n\n# Compute exit probabilities by computing M^(-1)b\nu = M\\b\n\n# Get probability of interest\nusing Printf\n@printf(\"Probability of walking away with \\$%g: %f\", k,\n u[k+1])\n", "meta": {"hexsha": "210a129771de3bbb3b8d7de16e0f3980a29790e3", "size": 483, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "content/stochastic-approximations/code/exit_prob_ex.jl", "max_stars_repo_name": "seanrattana/courses", "max_stars_repo_head_hexsha": "9453abc38af26ea49cb00fe1744066fc0de237b3", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2019-08-21T07:33:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-24T15:46:58.000Z", "max_issues_repo_path": "content/stochastic-approximations/code/exit_prob_ex.jl", "max_issues_repo_name": "seanrattana/courses", "max_issues_repo_head_hexsha": "9453abc38af26ea49cb00fe1744066fc0de237b3", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-08-23T06:04:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-26T12:47:12.000Z", "max_forks_repo_path": "content/stochastic-approximations/code/exit_prob_ex.jl", "max_forks_repo_name": "seanrattana/courses", "max_forks_repo_head_hexsha": "9453abc38af26ea49cb00fe1744066fc0de237b3", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-08-18T21:23:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-02T19:14:33.000Z", "avg_line_length": 14.2058823529, "max_line_length": 55, "alphanum_fraction": 0.5859213251, "num_tokens": 195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012686491107, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.8039038216437415}} {"text": "\"\"\"\r\n euler(f,a,b,y0,M)\r\nberisi program untuk mencari solusi persamaan differensial `y'=f(t,y)`\r\ndengan masalah nilai awal `y(a) = y0` pada interval `[a, b]`. Program ini secara default\r\nberisi 5 masukan, yaitu fungsi `f(t,y)`, titik ujung interval penyelesaian `[a,b]`, nilai awal\r\n`y0`, dan jumlah sub-interval `M`.\r\n# Example\r\n```jl\r\njulia> f(t,y) = (t-y)/2;\r\n\r\njulia> sol = euler(f,0,3,1,6)\r\n7×2 Array{Float64,2}:\r\n 0.0 1.0\r\n 0.5 0.75\r\n 1.0 0.6875\r\n 1.5 0.765625\r\n 2.0 0.949219\r\n 2.5 1.21191\r\n 3.0 1.53394\r\n```\r\nreturn solusi masalah nilai awal `sol`.\r\n\"\"\"\r\nfunction euler(f,a,b,y0,M)\r\n M = Int(M)\r\n h = (b-a)/M;\r\n T = a:h:b;\r\n Y = Array{Float64}(undef,length(T),1)\r\n Y[1] = y0;\r\n # Mulai langkah iterasi euler\r\n for k = 1:M\r\n # Rumus iterasi euler\r\n Y[k+1] = Y[k]+h*f(T[k],Y[k])\r\n end\r\n sol = [T Y]\r\nend\r\n", "meta": {"hexsha": "8cbe35ace4fb383801532b99db485377c23346d4", "size": 861, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/euler.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/euler.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/euler.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.9166666667, "max_line_length": 95, "alphanum_fraction": 0.5656213705, "num_tokens": 358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9458012732322215, "lm_q2_score": 0.84997116805678, "lm_q1q2_score": 0.803903812958781}} {"text": "doc\"\"\"\n Skellam(μ1, μ2)\n\nA *Skellam distribution* describes the difference between two independent [`Poisson`](:func:`Poisson`) variables, respectively with rate `μ1` and `μ2`.\n\n$P(X = k) = e^{-(\\mu_1 + \\mu_2)} \\left( \\frac{\\mu_1}{\\mu_2} \\right)^{k/2} I_k(2 \\sqrt{\\mu_1 \\mu_2}) \\quad \\text{for integer } k$\n\nwhere $I_k$ is the modified Bessel function of the first kind.\n\n```julia\nSkellam(mu1, mu2) # Skellam distribution for the difference between two Poisson variables,\n # respectively with expected values mu1 and mu2.\n\nparams(d) # Get the parameters, i.e. (mu1, mu2)\n```\n\nExternal links:\n\n* [Skellam distribution on Wikipedia](http://en.wikipedia.org/wiki/Skellam_distribution)\n\"\"\"\nimmutable Skellam <: DiscreteUnivariateDistribution\n μ1::Float64\n μ2::Float64\n\n function Skellam(μ1::Real, μ2::Real)\n @check_args(Skellam, μ1 > zero(μ1) && μ2 > zero(μ2))\n new(μ1, μ2)\n end\n Skellam(μ::Real) = Skellam(μ, μ)\n Skellam() = new(1.0, 1.0)\nend\n\n@distr_support Skellam -Inf Inf\n\n### Parameters\n\nparams(d::Skellam) = (d.μ1, d.μ2)\n\n\n### Statistics\n\nmean(d::Skellam) = d.μ1 - d.μ2\n\nvar(d::Skellam) = d.μ1 + d.μ2\n\nskewness(d::Skellam) = mean(d) / (var(d)^1.5)\n\nkurtosis(d::Skellam) = 1.0 / var(d)\n\n\n### Evaluation\n\nfunction logpdf(d::Skellam, x::Int)\n μ1, μ2 = params(d)\n - (μ1 + μ2) + (x / 2.0) * log(μ1 / μ2) + log(besseli(x, 2.0 * sqrt(μ1) * sqrt(μ2)))\nend\n\npdf(d::Skellam, x::Int) = exp(logpdf(d, x))\n\nfunction mgf(d::Skellam, t::Real)\n μ1, μ2 = params(d)\n exp(-(μ1 + μ2) + μ1 * exp(t) + μ2 * exp(-t))\nend\n\nfunction cf(d::Skellam, t::Real)\n μ1, μ2 = params(d)\n exp(-(μ1 + μ2) + μ1 * cis(t) + μ2 * cis(-t))\nend\n\n### Sampling\n\nrand(d::Skellam) = rand(Poisson(d.μ1)) - rand(Poisson(d.μ2))\n", "meta": {"hexsha": "7fa85fe64e791d384184e47e1222290276901eeb", "size": 1765, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/univariate/discrete/skellam.jl", "max_stars_repo_name": "ericproffitt/Distributions.jl", "max_stars_repo_head_hexsha": "54daf6f7230c6cf1fa46d9a948a33ad68b5fd3b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/univariate/discrete/skellam.jl", "max_issues_repo_name": "ericproffitt/Distributions.jl", "max_issues_repo_head_hexsha": "54daf6f7230c6cf1fa46d9a948a33ad68b5fd3b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/univariate/discrete/skellam.jl", "max_forks_repo_name": "ericproffitt/Distributions.jl", "max_forks_repo_head_hexsha": "54daf6f7230c6cf1fa46d9a948a33ad68b5fd3b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1780821918, "max_line_length": 151, "alphanum_fraction": 0.6130311615, "num_tokens": 673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012640659996, "lm_q2_score": 0.849971175657575, "lm_q1q2_score": 0.8039038123565982}} {"text": "# Parts of this code were taken / derived from NetworkX. See LICENSE for\n# licensing details.\n\n\"\"\"\n pagerank(g, α=0.85, n=100, ϵ=1.0e-6)\n\nCalculate the [PageRank](https://en.wikipedia.org/wiki/PageRank) of the\ndirected graph `g` parameterized by damping factor `α`, number of\niterations `n`, and convergence threshold `ϵ`. Return a vector representing\nthe centrality calculated for each node in `g`, or an error if convergence\nis not reached within `n` iterations.\n\"\"\"\nfunction pagerank end\n\n@traitfn function pagerank(g::::IsDirected, α=0.85, n=100, ϵ=1.0e-6)\n A = adjacency_matrix(g,:in,Float64)\n S = vec(sum(A,1))\n S = 1./S\n S[find(S .== Inf)]=0.0\n M = A' # need a separate line due to bug #17456 in julia\n M = (Diagonal(S) * M)'\n N = Int(nv(g))\n x = fill(1.0/N, N)\n p = fill(1.0/N, N)\n dangling_weights = p\n is_dangling = find(S .== 0)\n\n for _ in 1:n\n xlast = x\n x = α * (M * x + sum(x[is_dangling]) * dangling_weights) + (1 - α) * p\n err = sum(abs, (x - xlast))\n if (err < N * ϵ)\n return x\n end\n end\n error(\"Pagerank did not converge after $n iterations.\")\nend\n", "meta": {"hexsha": "df860ce77b84c61edfcb2486213f9c418ce2c1fb", "size": 1157, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/centrality/pagerank.jl", "max_stars_repo_name": "AsileBcd/JohnsonCycles", "max_stars_repo_head_hexsha": "4928bc05eaaad75a6d05a1390be9f5840c68705e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/centrality/pagerank.jl", "max_issues_repo_name": "AsileBcd/JohnsonCycles", "max_issues_repo_head_hexsha": "4928bc05eaaad75a6d05a1390be9f5840c68705e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/centrality/pagerank.jl", "max_forks_repo_name": "AsileBcd/JohnsonCycles", "max_forks_repo_head_hexsha": "4928bc05eaaad75a6d05a1390be9f5840c68705e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4473684211, "max_line_length": 78, "alphanum_fraction": 0.6110630942, "num_tokens": 376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9458012655937034, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.803903811857892}} {"text": "\n# we write a function that returns a random vector from [0,1]^d with exponential density\nfunction randExp(d, lam)\n\n\t# we generate a uniformly random vector\n\ty = rand(d)\n\n\t# we transform (elementwise) to random numbers in [exp(-lambda),1]\n\ty = exp(-lam) .+ (1-exp(-lam))*y\n\t\n\t# we now get numbers with exponential density\n\tx = -log.(y)/lam\n\treturn x\nend\n", "meta": {"hexsha": "4553de4d644190d0fa4f163704452b982ab9a847", "size": 354, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "1a/Monte Carlo integration/randExp.jl", "max_stars_repo_name": "sje30/catam-julia", "max_stars_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-07-13T12:55:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:40:23.000Z", "max_issues_repo_path": "1a/Monte Carlo integration/randExp.jl", "max_issues_repo_name": "sje30/catam-julia", "max_issues_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2021-07-11T21:35:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-25T12:10:58.000Z", "max_forks_repo_path": "1a/Monte Carlo integration/randExp.jl", "max_forks_repo_name": "sje30/catam-julia", "max_forks_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-13T21:00:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-13T21:00:47.000Z", "avg_line_length": 23.6, "max_line_length": 88, "alphanum_fraction": 0.6920903955, "num_tokens": 102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9525741241296943, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.8038726344333845}} {"text": "# The prime factors of 13195 are 5, 7, 13 and 29.\n# What is the largest prime factor of the number 600851475143 ?\n\nnum = BigInt(600851475143)\n#num = BigInt(13195)\n\nis_prime(n) = !any(n%i == 0 for i in 2:BigInt(floor(sqrt(n))))\n\nfunction largest_factor(num)\n #step_ = (num % 2 == 0) ? -1 : -2\n num_leftover = num\n for p in (BigInt(p) for p=2:num_leftover if is_prime(p))\n if p == num_leftover\n println(p)\n return p\n elseif num_leftover % p == 0\n num_leftover = BigInt(num_leftover / p)\n end\n end\nend\nlargest_factor(num)\nprintln()\n", "meta": {"hexsha": "4a7e6060b97cd47366b959d5382aba102d4802a8", "size": 595, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "euler_3.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_3.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_3.jl", "max_forks_repo_name": "pedvide/project-euler", "max_forks_repo_head_hexsha": "8e8e1e57b2c4d7e70a7127483539dca060c50a38", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8695652174, "max_line_length": 63, "alphanum_fraction": 0.6117647059, "num_tokens": 184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9572778073288128, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.8038586893930704}} {"text": "export ad, mad, mad_core\n\n\"\"\"\n`mad_model(G)` returns the solved linear program whose optimum\nvalue is `mad(G)`.\n\"\"\"\nfunction mad_model(G::SimpleGraph)\n EE = elist(G)\n VV = vlist(G)\n\n n = length(VV)\n m = length(EE)\n\n MOD = Model(get_solver())\n\n # variables\n @variable(MOD, z >= 0)\n @variable(MOD, x[i = 1:n, j = 1:m; in(VV[i], EE[j])] >= 0)\n\n # vertex constraints\n for i = 1:n\n v = VV[i]\n # get all edges that have v as an end point\n j_iterator = (j for j = 1:m if EE[j][1] == v || EE[j][2] == v)\n j_list = collect(j_iterator)\n @constraint(MOD, sum(x[i, j] for j in j_list) <= z)\n end\n\n # edge constraints\n for j = 1:m\n v, w = EE[j]\n i1 = first(findall(x -> x == v, VV))\n i2 = first(findall(x -> x == w, VV))\n @constraint(MOD, x[i1, j] + x[i2, j] == 2)\n end\n\n @objective(MOD, Min, z)\n optimize!(MOD)\n return MOD, x, VV, EE\nend\n\n\n\"\"\"\n`mad(G)` computes the maximum average degree of `G`.\nSee also `mad_core`.\n\"\"\"\nfunction mad(G::SimpleGraph)\n if cache_check(G, :mad)\n return cache_recall(G, :mad)\n end\n MOD, x, VV, EE = mad_model(G)\n mval = objective_value(MOD)\n cache_save(G, :mad, mval)\n return mval\nend\n\n\"\"\"\n`ad(G)` is the average degree of a vertex in `G`.\n\"\"\"\nad(G::SimpleGraph) = 2 * NE(G) / NV(G)\n\n\"\"\"\n`mad_core(G)` returns a subgraph `H` of `G` for which\n`ad(H)==mad(G)`.\n\"\"\"\nfunction mad_core(G::SimpleGraph)\n if cache_check(G, :mad_core)\n return cache_recall(G, :mad_core)\n end\n T = eltype(G)\n GG = deepcopy(G)\n while true\n if NV(GG) == 0\n error(\"Bad graph or something went wrong\")\n end\n # solve the LP for GG\n MOD, x, VV, EE = mad_model(GG)\n n = length(VV)\n m = length(EE)\n err = 0.1 / n\n mval = objective_value(MOD)\n\n # if balanced, return\n if abs(ad(GG) - mval) <= err\n cache_save(G, :mad_core, GG)\n return GG\n end\n\n # otherwise, find and destroy defective vertices\n for i = 1:n\n v = VV[i]\n total = 0.0\n for j = 1:m\n e = EE[j]\n if in(v, e)\n val = value(x[i, j])\n total += val\n end\n end\n if total < mval - err # this is a defective vertex\n delete!(GG, v)\n end\n end\n end # end while\n error(\"This can't happen (but it did)\")\n cache_save(G, :mad_core, GG)\n return GG\nend\n", "meta": {"hexsha": "1dc94807c1bd6ce7d9faeb8302048d4a510cd561", "size": 2548, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mad.jl", "max_stars_repo_name": "scheinerman/SimpleGraphAlgorithms", "max_stars_repo_head_hexsha": "3ec61b5283cb22b51ead52677a3df8b3de5a1b93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2018-10-12T17:09:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T08:06:06.000Z", "max_issues_repo_path": "src/mad.jl", "max_issues_repo_name": "scheinerman/SimpleGraphAlgorithms", "max_issues_repo_head_hexsha": "3ec61b5283cb22b51ead52677a3df8b3de5a1b93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2016-10-19T04:03:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-08T12:08:27.000Z", "max_forks_repo_path": "src/mad.jl", "max_forks_repo_name": "scheinerman/SimpleGraphAlgorithms", "max_forks_repo_head_hexsha": "3ec61b5283cb22b51ead52677a3df8b3de5a1b93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-09-14T01:13:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T20:58:22.000Z", "avg_line_length": 23.376146789, "max_line_length": 70, "alphanum_fraction": 0.5066718995, "num_tokens": 778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475762847494, "lm_q2_score": 0.8519528057272543, "lm_q1q2_score": 0.8036876143917974}} {"text": "#=\n\n\n# 101: 1D Laplace equation \n([source code](SOURCE_URL))\n\n\nLet $\\Omega=(\\gamma_1,\\gamma_2)$ with $\\gamma_1=0$, $\\gamma_2=1$.\nThis is the simplest second order boundary value problem (BVP)\nfor a partial differential equation (PDE):\n\n```math\n-\\Delta u =0\\\\\nu(\\gamma_1)=g_1\\\\\nu(\\gamma_2)=g_2.\n```\n\nWe replace the Dirichlet boundary condition by a Robin boundary\ncondition with a penalty parameter $\\frac{1}{\\varepsilon}$:\n\n```math\n\\nabla u(\\gamma_1) + \\frac{1}{\\varepsilon}(u(\\gamma_1)-g_1)=0 \\\\\n-\\nabla u(\\gamma_2) + \\frac{1}{\\varepsilon}(u(\\gamma_2)-g_2)\n=0 \n```\n\nThis penalty method for the implementation of Dirichlet\nboundary conditions is used throughout VoronoiFVM.\n\n\nIn order to discretize it, we choose collocation points\n$\\gamma_1=x_1 < x_2 < \\dots < x_n=\\gamma_2$.\n\nFor instance, we can choose 6 collocation points in $(0,1)$:\nFrom these, we create a discretization grid structure\nfor working with the method.\n\nThis implicitely creates a number of control volumes $\\omega_k $ around each\ndiscretization point $x_k$: Let\n$\\sigma_{k,k+1}=\\frac{x_k+x_{k+1}}{2}$. Then $\\omega_1=(\\gamma_1,\\sigma_{1,2})$,\n$\\omega_k= (\\sigma_{k-1,k}, \\sigma_{k,k+1})$ for $k=2\\dots n-1$, $\\omega_{n}=(\\sigma_{n-1,n},\\gamma_2)$. \n\n```\n x1 x2 x3 x4 x5 x6\n o-----o-----o-----o-----o-----o\n |--|-----|-----|-----|-----|--|\n ω1 ω2 ω3 ω4 ω5 ω6\n```\n\nFor each $\\omega_k$, we integrate the equation\n\n```math\n\\begin{aligned}\n0&=\\int_{\\omega_k} -\\Delta u d\\omega= -\\int_{\\partial \\omega_k} \\nabla u ds\\\\\n&= \\begin{cases}\nu'(\\sigma_{1,2}) - u'(0)& k=1\\\\\nu'(\\sigma_{k,k+1}) - u'(\\sigma_{k-1,k}) & 1 longest\n longest = len; arg = i\n end\n end\n\n return arg\nend\n\nprintln(longest_recurring_decimal(1000))\n", "meta": {"hexsha": "f22c7cab96b839ec5680d3dcd2c94b156da5e879", "size": 513, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/problem_26.jl", "max_stars_repo_name": "HarrisonGreen/Project-Euler-Solutions", "max_stars_repo_head_hexsha": "e2599e406c8a1c997bf620e1c35045303b12091e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Julia/problem_26.jl", "max_issues_repo_name": "HarrisonGreen/Project-Euler-Solutions", "max_issues_repo_head_hexsha": "e2599e406c8a1c997bf620e1c35045303b12091e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Julia/problem_26.jl", "max_forks_repo_name": "HarrisonGreen/Project-Euler-Solutions", "max_forks_repo_head_hexsha": "e2599e406c8a1c997bf620e1c35045303b12091e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.6896551724, "max_line_length": 47, "alphanum_fraction": 0.5419103314, "num_tokens": 148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475683211324, "lm_q2_score": 0.8519528019683105, "lm_q1q2_score": 0.803687604061181}} {"text": "using Random\nusing LinearAlgebra\n\"\"\"\ndir_sample(dir_type::String, d::Int, m::Int, seed::Int)\n\n\"dir_sample\" \nsamples \"m\" directions in dimension \"d\" of type \"dir_type\"\n\nInputs:\n(1) dir_type: a string, the direction type\n(2) d: an integer, the dimension in which the directions are sampled\n(3) m: an integer, the number of directions to generate\n(4) seed: an integer, used for random sampling\n\nOutput:\nan m x d matrix, where each row is a direction in R^d\n\"\"\"\nfunction dir_sample(dir_type::String, d::Int, m::Int, seed::Int,\n theta = pi/4)\n ## set the seed for random number generation\n Random.seed!(seed)\n if dir_type==\"pos\"\n directions = zeros(0,d)\n num_row = 0\n while num_row0)==d\n directions = [directions; direction]\n num_row+=1\n end\n end\n return directions\n elseif dir_type==\"unif\"\n directions = randn(m,d)\n return directions\n elseif dir_type==\"angle\"\n directions = zeros(0,d)\n num_row = 0\n vec_1 = ones(d)/sqrt(d) ## the vector [1,1,...,1]\\in\\R^d\n num_row = 0\n while num_row0\n new_pt = [new_pt;(-1)^a*sqrt(x_d_a2)] ## (-1)^a is used to cover both the upper and lower piece\n pts = [pts new_pt]\n a+=1\n end\n end\n return pts\n end\nend\n\n# ## sample usage code\n# pt_type = \"sphere\" ## \"uniform\"\n# d = 2\n# n = 100\n# seed = 1\n# X = pt_sample(pt_type::String, d::Int, n::Int, seed::Int)\n\n# using Plots\n# pyplot()\n\n# scatter(X[1,:], X[2,:], legend = false)\n\n", "meta": {"hexsha": "a85a954e8fcbea530c5708c49598c1e3724bde96", "size": 3937, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unified_dir_pt_sample.jl", "max_stars_repo_name": "wmg9721204/dimension-inference-with-betti-curve-comparison", "max_stars_repo_head_hexsha": "f8b9b38de7d2eabd4524349080d104c31ab1a57c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/unified_dir_pt_sample.jl", "max_issues_repo_name": "wmg9721204/dimension-inference-with-betti-curve-comparison", "max_issues_repo_head_hexsha": "f8b9b38de7d2eabd4524349080d104c31ab1a57c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/unified_dir_pt_sample.jl", "max_forks_repo_name": "wmg9721204/dimension-inference-with-betti-curve-comparison", "max_forks_repo_head_hexsha": "f8b9b38de7d2eabd4524349080d104c31ab1a57c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9657534247, "max_line_length": 111, "alphanum_fraction": 0.5778511557, "num_tokens": 1169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361700013356, "lm_q2_score": 0.8807970873650403, "lm_q1q2_score": 0.8036711209436891}} {"text": "### Irving Gomez Mendez\n### January 13th 2019\n\nusing Pkg\nusing Plots; pyplot()\nusing LaTeXStrings\nusing Distributions\nusing StatsPlots\nusing Random\nusing StatsBase\n\n# Apply a function to each value of an array and returns a new array\n# containing the resulting values:\nroundmap(vect, b) = map(x -> round(x, digits = b), vect)\n\n# La densidad de la distribución Weibull de mínimos (de 2 parámetros) está dada por la expresión:\n\nL\"f(t;\\eta,\\beta)=\\frac{\\beta}{\\eta}\\left(\\frac{t}{\\eta}\\right)^{\\beta-1}\ne^{-(t/\\eta)^\\beta}1\\!\\!1\\,\\,_{(0 qweib_min(x, η, β), u)\n return(out)\nend\n\nRandom.seed!(111)\nmuestra = rweib_min(50, 2, 6.2)\n\nhistogram(muestra,\n label = \"Empirical Weibull(2,6.2)\",\n normalized = true,\n background_color = :Lavender,\n fillalpha = 0.33,\n color = :RebeccaPurple)\n\nplot!(Weibull(6.2,2),\n label = \"Weibull(2,6.2)\",\n lw = 2)\n\nEmpirical = ecdf(muestra)\n\nEmpirical(1.23)\n\nplot(sort(muestra), map(Empirical, sort(muestra)),\n label = \"Empirical Weibull(2,6.2)\",\n ylabel = L\"F_n(x,θ)\",\n background_color = :Lavender,\n linetype = :steppost,\n lw = 2,\n color = :RebeccaPurple)\n\npweib_min(x, η, β) = cdf(Weibull(β, η), x)\n\nplot!(x -> pweib_min(x, 2, 6.2),\n label = \"Weibull(2,6.2)\",\n lw = 2)\n\nmuestra2 = rand(Weibull(6.2,2), 50)\n", "meta": {"hexsha": "028b83ff83b32e7f60f2a0c0e10591481501b87b", "size": 3295, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "content/courses/inf2019/Ayudantia_1_23_agosto.jl", "max_stars_repo_name": "IrvingGomez/academic-hugo", "max_stars_repo_head_hexsha": "4f6e4ec4aab7a11f477883441b768bb6cf843a9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "content/courses/inf2019/Ayudantia_1_23_agosto.jl", "max_issues_repo_name": "IrvingGomez/academic-hugo", "max_issues_repo_head_hexsha": "4f6e4ec4aab7a11f477883441b768bb6cf843a9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "content/courses/inf2019/Ayudantia_1_23_agosto.jl", "max_forks_repo_name": "IrvingGomez/academic-hugo", "max_forks_repo_head_hexsha": "4f6e4ec4aab7a11f477883441b768bb6cf843a9c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8768115942, "max_line_length": 97, "alphanum_fraction": 0.6479514416, "num_tokens": 1177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958426, "lm_q2_score": 0.880797071719777, "lm_q1q2_score": 0.8036710961820616}} {"text": "#=\n\n# 102: 1D Stationary convection-diffusion equation\n([source code](SOURCE_URL))\n\nSolve the equation\n\n```math\n-\\nabla ( D \\nabla u - v u) = 0\n```\nin $\\Omega=(0,1)$ with boundary condition $u(0)=0$ and $u(1)=1$.\n$v$ could be e.g. the velocity\nof a moving medium or the gradient of an electric field.\n\nThis is a convection dominant second order boundary value problem which obeys\na local and a global maximum principle:\nthe solution which is bounded by the values at the boundary and has no local extrema in the\ninterior.\nIf $v$ is large compared to $D$, a boundary layer is observed.\n\nThe maximum principle of the solution can only be guaranteed it the discretization is\nperformed accordingly: the flux function must monotonically increase in the first argument\nand monotonically decrease in the second argument.\n\nThe example describes three possible ways to define the flux function and demonstrates\nthe impact on the qualitative properties of the solution.\n\n=#\n\nmodule Example102_StationaryConvectionDiffusion1D\nusing Printf\nusing VoronoiFVM\nusing ExtendableGrids\nusing GridVisualize\n\n## Central difference flux. The velocity term is discretized using the\n## average of the solution in the endpoints of the grid. If the local Peclet\n## number v*h/D>1, the monotonicity property is lost. Grid refinement\n## can fix this situation by decreasing $h$.\n\nfunction central_flux!(f,u0,edge,data)\n u=unknowns(edge,u0)\n f_diff=data.D*(u[1,1]-u[1,2])\n vh=project(edge,data.v)\n f[1]=f_diff+vh*(u[1,1]+u[1,2])/2\nend\n\n## The simple upwind flux corrects the monotonicity properties essentially\n## via brute force and loses one order of convergence for small $h$ compared\n## to the central flux.\n\nfunction upwind_flux!(f,u0,edge,data)\n u=unknowns(edge,u0)\n fdiff=data.D*(u[1,]-u[1,2])\n vh=project(edge,data.v)\n if vh>0\n f[1]=fdiff+vh*u[1,1]\n else\n f[1]=fdiff+vh*u[1,2]\n end\nend\n\n## The exponential fitting flux has the proper monotonicity properties and\n## kind of interpolates in a clever way between central\n## and upwind flux. It can be derived by solving the two-point boundary value problem\n## at the grid interval analytically.\n\n## Bernoulli function used in the exponential fitting discretization\nfunction bernoulli(x)\n if abs(x) _linreg_f(X, y, w), # f\n w::Array{Float64,1} -> _linreg_g(X, y, w), # g\n f_b = (w::Array{Float64,1}, b::Array{Int,1}) -> _linreg_f(X, y, w, b),\n g_b = (w::Array{Float64,1}, b::Array{Int,1}) -> _linreg_g(X, y, w, b),\n dim = length(y)\n)\n\nfunction _linreg_f(X::Array{Float64,2}, y::Array{Float64,1}, w::Array{Float64,1},\n b::Array{Int,1}=Int[])\n if length(b) == 0\n return vecnorm(y - X*w)^2 / (2*length(y))\n else\n return vecnorm(y[b] - X[b,:]*w)^2 / (2*length(b))\n end\nend\n\nfunction _linreg_g(X::Array{Float64,2}, y::Array{Float64,1}, w::Array{Float64,1},\n b::Array{Int,1}=Int[])\n if length(b) == 0\n return vec(X' * (X*w - y)) ./ length(y)\n else\n return vec(X[b,:]' * (X[b,:]*w - y[b])) ./ length(b)\n end\nend\n\n\"\"\"\n linreg_predict(w, X)\n\n Predict the examples in X with Linear Regression under parameter vector w.\n\"\"\"\nlinreg_predict(w::Array{Float64,1}, X::Array{Float64,2}) = sign(vec(X*w))\n", "meta": {"hexsha": "3e93f77c1cd24dd7cb667368751c451c24fbdf02", "size": 1186, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "mod/obj/linreg.jl", "max_stars_repo_name": "mirkobunse/lso", "max_stars_repo_head_hexsha": "6453fbb3a6fd8f7ab81b30e9664d3b75b99b2048", "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": "mod/obj/linreg.jl", "max_issues_repo_name": "mirkobunse/lso", "max_issues_repo_head_hexsha": "6453fbb3a6fd8f7ab81b30e9664d3b75b99b2048", "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": "mod/obj/linreg.jl", "max_forks_repo_name": "mirkobunse/lso", "max_forks_repo_head_hexsha": "6453fbb3a6fd8f7ab81b30e9664d3b75b99b2048", "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": 31.2105263158, "max_line_length": 81, "alphanum_fraction": 0.5615514334, "num_tokens": 422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939024825960626, "lm_q2_score": 0.8558511506439708, "lm_q1q2_score": 0.8036654777816561}} {"text": "function calc_fan(dims...; mode = \"fan_in\")\n @assert mode in [\"fan_in\", \"fan_out\"]\n num_dims = length(dims)\n num_dims < 2 && throw(\"Number of dimensions should be more than 1!\")\n\n fan_out = dims[1]\n fan_in = dims[2]\n # if num_dims > 2\n # receptive_field = prod(dims[1:end-2])\n # fan_in *= receptive_field\n # fan_out *= receptive_field\n # end\n\n mode == \"fan_in\" ? fan_in : fan_out\nend\n\nfunction calc_gain(nonlinearity, a = nothing)\n linear_fns = [\"linear\", \"conv1d\", \"conv2d\", \"conv3d\", \"conv_transpose1d\", \"conv_transpose2d\", \"conv_transpose3d\"]\n if nonlinearity in linear_fns || nonlinearity == \"sigmoid\" || nonlinearity == \"σ\"\n return 1.0\n elseif nonlinearity == \"tanh\"\n return 5.0 / 3\n elseif nonlinearity == \"relu\"\n return √2.0\n elseif nonlinearity == \"leakyrelu\"\n if a == nothing\n negative_slope = 0.01\n elseif !(a isa Bool) && a isa Integer || a isa AbstractFloat\n # true/false are instances of Integer, hence check above\n negative_slope = a\n else\n throw(\"negative_slope $a not a valid number.\")\n end\n return √(2.0 / (1 + negative_slope ^ 2))\n else\n throw(\"Unsupported nonlinearity $nonlinearity.\")\n end\nend\n\nfunction kaiming_uniform(dims...; a = 0, mode = \"fan_in\", nonlinearity = \"leakyrelu\")\n fan = calc_fan(dims...; mode = mode)\n gain = calc_gain(nonlinearity, a)\n (rand(dims...) .- 0.5) .* √(12.0 / fan) .* gain\nend\n", "meta": {"hexsha": "8964b3c1a42efcc7f4f6b24d3363a737b90f1d80", "size": 1402, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kaiming_init.jl", "max_stars_repo_name": "tejank10/NeuralALU.jl", "max_stars_repo_head_hexsha": "b257a6a0f0ad2e21533d95ea2fbee31ce5c58004", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-08-19T18:42:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-14T15:41:55.000Z", "max_issues_repo_path": "src/kaiming_init.jl", "max_issues_repo_name": "tejank10/NALU-Flux", "max_issues_repo_head_hexsha": "b257a6a0f0ad2e21533d95ea2fbee31ce5c58004", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kaiming_init.jl", "max_forks_repo_name": "tejank10/NALU-Flux", "max_forks_repo_head_hexsha": "b257a6a0f0ad2e21533d95ea2fbee31ce5c58004", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-11T01:16:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-11T01:16:38.000Z", "avg_line_length": 31.1555555556, "max_line_length": 115, "alphanum_fraction": 0.6462196862, "num_tokens": 457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248140158417, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.8036654692849603}} {"text": "function rowcol(s)\n # Find row and col of the seatid\n\n rowpart = s[1:7]\n rowpart = replace(rowpart, \"B\" => \"1\")\n rowpart = replace(rowpart, \"F\" => \"0\")\n colpart = s[8:end]\n colpart = replace(colpart, \"R\" => \"1\")\n colpart = replace(colpart, \"L\" => \"0\")\n rowbin, colbin = parse(UInt8, rowpart, base=2), parse(UInt8, colpart, base=2)\n Int.((rowbin & UInt(127), colbin & UInt(7)))\nend\n\nseatid((row, col)) = row * 8 + col\n# Every seat also has a unique seat ID: multiply the row by 8, then add the column\n\n\n# First Half\n\npuzzeinput = readlines(\"inputs/day05.txt\")\nmaximum(map(seatid ∘ rowcol, puzzeinput))\n\n\n# Second Half\n\nfunction missingid(strs)\n\n rowcols = map(rowcol, strs)\n filter!(rc -> rc[1] > 0 && rc[1] < 127, rowcols)\n # Removes very front and very back rows, because your seat wasn't\n # at the very front or back\n\n sorted_ids = map(seatid, rowcols) |> sort\n for (i, id) in enumerate(sorted_ids)\n if sorted_ids[i + 1] ≠ id + 1\n # Missing ID found\n\n return id + 1\n end\n end\nend\n\npuzzeinput = readlines(\"inputs/day05.txt\")\nmissingid(puzzeinput)\n", "meta": {"hexsha": "9be1adda08d64324a5b5665a7918aacd111d97a4", "size": 1132, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "day05.jl", "max_stars_repo_name": "fstiffo/aoc-2020-julia", "max_stars_repo_head_hexsha": "73d40e8e5d069d0024a380c504657b3c3fe467b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "day05.jl", "max_issues_repo_name": "fstiffo/aoc-2020-julia", "max_issues_repo_head_hexsha": "73d40e8e5d069d0024a380c504657b3c3fe467b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "day05.jl", "max_forks_repo_name": "fstiffo/aoc-2020-julia", "max_forks_repo_head_hexsha": "73d40e8e5d069d0024a380c504657b3c3fe467b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1555555556, "max_line_length": 82, "alphanum_fraction": 0.6174911661, "num_tokens": 365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391706552538, "lm_q2_score": 0.8705972751232808, "lm_q1q2_score": 0.8035953868045169}} {"text": "# Truss Finite Element Analysis\n\nusing LinearAlgebra\n\n## Local Stiffness Matrix\"\n\nfunction L(member::Dict{Integer,Array{Integer}}, node::Dict{Integer,Array{Float64}})\n\tl = Dict{Integer, Float64}()\n\tfor e = 1:length(member)\n\t\tl[e] = hypot(node[member[e][2]][1]-node[member[e][1]][1], node[member[e][2]][2]-node[member[e][1]][2])\n\tend\n\treturn l\nend\n\nfunction cosϕ(member::Dict{Integer,Array{Integer}}, node::Dict{Integer,Array{Float64}})\n\tcosphi = Dict{Integer, Float64}()\n\tfor e = 1:length(member)\n\t\thor = node[member[e][2]][1]-node[member[e][1]][1]\n\t\thyp = hypot(node[member[e][2]][1]-node[member[e][1]][1], node[member[e][2]][2]-node[member[e][1]][2])\n\t\tcosphi[e] = hor/hyp\n\tend\n\treturn cosphi\nend\n\nfunction sinϕ(member::Dict{Integer,Array{Integer}}, node::Dict{Integer,Array{Float64}})\n\tsinphi = Dict{Integer, Float64}()\n\tfor e = 1:length(member)\n\t\thor = node[member[e][2]][2]-node[member[e][1]][2]\n\t\thyp = hypot(node[member[e][2]][1]-node[member[e][1]][1], node[member[e][2]][2]-node[member[e][1]][2])\n\t\tsinphi[e] = hor/hyp\n\tend\n\treturn sinphi\nend\n\nfunction AxialLocalK(E::Dict, A::Dict, Member::Dict{Integer,Array{Integer}}, Node::Dict{Integer,Array{Float64}})\n\tk = Dict{}()\n\tLength = L(Member,Node)\n\tCosϕ = cosϕ(Member,Node)\n\tSinϕ = sinϕ(Member,Node)\n\tfor e = 1:length(Member)\n\t\tk[e] = E[e]*A[e]/Length[e]*\n\t[[Cosϕ[e]^2, Sinϕ[e]*Cosϕ[e], -Cosϕ[e]^2, -Sinϕ[e]*Cosϕ[e]],\n\t[Sinϕ[e]*Cosϕ[e], Sinϕ[e]^2, -Sinϕ[e]*Cosϕ[e], -Sinϕ[e]^2],\n\t[-Cosϕ[e]^2, -Sinϕ[e]*Cosϕ[e], Cosϕ[e]^2, Sinϕ[e]*Cosϕ[e]],\n\t[-Sinϕ[e]*Cosϕ[e], -Sinϕ[e]^2, Sinϕ[e]*Cosϕ[e], Sinϕ[e]^2]]\n\tend\n\treturn k\nend\n\nfunction AxialGlobalK(k::Dict,member::Dict, node::Dict)\n\tK = zeros(length(node)*2, length(node)*2)\n\tfor e = 1:length(member)\n\t\ta = member[e][1] * 2 - 1\n\t\tb = member[e][1] * 2\n\t\tc = member[e][2] * 2 - 1\n\t\td = member[e][2] * 2\n\t\tK[a,a] += k[e][1][1]\n\t\tK[a,b] += k[e][1][2]\n\t\tK[a,c] += k[e][1][3]\n\t\tK[a,d] += k[e][1][4]\n\t\tK[b,a] += k[e][2][1]\n\t\tK[b,b] += k[e][2][2]\n\t\tK[b,c] += k[e][2][3]\n\t\tK[b,d] += k[e][2][4]\n\t\tK[c,a] += k[e][3][1]\n\t\tK[c,b] += k[e][3][2]\n\t\tK[c,c] += k[e][3][3]\n\t\tK[c,d] += k[e][3][4]\n\t\tK[d,a] += k[e][4][1]\n\t\tK[d,b] += k[e][4][2]\n\t\tK[d,c] += k[e][4][3]\n\t\tK[d,d] += k[e][4][4]\n\tend\n\treturn K\nend\n\n### Determine free nodal directions\nfunction FreeNodalDir(u::Dict)\n\tFree = Integer[]\n\tfor i = 1:length(u)\n\t\tif ismissing(u[i][1])\n\t\t\tpush!(Free, i*2-1)\n\t\tend\n\t\tif ismissing(u[i][2])\n\t\t\tpush!(Free, i*2)\n\t\tend\n\tend\n\treturn Free\nend\n\n### Augmented Global Stiffness Matrix\nfunction AugmentGlobal(Free::Array,K::Array)\n\tK_Aug = zeros(length(Free),length(Free))\n\tfor m = 1:length(Free)\n\t\tfor n = 1:length(Free)\n\t\t\tglobal K_aug\n\t\t\tK_Aug[m,n] = K[Free[m],Free[n]]\n\t\tend\n\tend\n\tK_Aug\nend\n\n## Global Force Matrix\"\nfunction GlobalForce(free::Array,f::Dict)\n\tForce = zeros(length(free))\n\tfor m = 1:length(free)\n\t\tif free[m]%2 != 0\n\t\t\tForce[m]= f[0.5*free[m]+0.5][1]\n\t\tend\n\t\tif free[m]%2 == 0\n\t\t\tForce[m]= f[0.5*free[m]][2]\n\t\tend\n\tend\n\treturn Force\nend", "meta": {"hexsha": "4a94677909be131473a641a5465c5fef02228ff8", "size": 2928, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/2DTruss.jl", "max_stars_repo_name": "JDBaniqued/StructuralAnalysis.jl", "max_stars_repo_head_hexsha": "b88ac273b61c836d3640534219e00bad351aef51", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/2DTruss.jl", "max_issues_repo_name": "JDBaniqued/StructuralAnalysis.jl", "max_issues_repo_head_hexsha": "b88ac273b61c836d3640534219e00bad351aef51", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/2DTruss.jl", "max_forks_repo_name": "JDBaniqued/StructuralAnalysis.jl", "max_forks_repo_head_hexsha": "b88ac273b61c836d3640534219e00bad351aef51", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4608695652, "max_line_length": 112, "alphanum_fraction": 0.593579235, "num_tokens": 1187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214480969029, "lm_q2_score": 0.8333245953120234, "lm_q1q2_score": 0.803592780486056}} {"text": "## ##\n## Problem set #2 for Structural modelling course ##\n## Nicolás Urdaneta ##\n## ##\n\nclearconsole()\n#=\nPkg.add(\"Optim\")\nPkg.add(\"HTTP\")\nPkg.add(\"GLM\")\n=#\n\nusing LinearAlgebra, Random, Statistics, DataFrames, CSV, FreqTables, Distributions, Optim, HTTP, GLM\n\n## 1. Basic optimization in Julia\n\nf(x) = -x[1]^4-10x[1]^3-2x[1]^2-3x[1]-2\nnegf(x) =-copy(f(x))\nstartval = rand(1)\nresult = optimize(negf, startval, LBFGS())\nprintln(result)\n\n## 2. Optimization with data\n\nurl = \"https://raw.githubusercontent.com/OU-PhD-Econometrics/fall-2020/master/ProblemSets/PS1-julia-intro/nlsw88.csv\"\ndf = CSV.read(HTTP.get(url).body)\nX = [ones(size(df,1),1) df.age df.race.==1 df.collgrad.==1]\ny = df.married.==1\n\nfunction ols(beta, X, y)\n\tssr = (y.-X*beta)'*(y.-X*beta)\n\treturn ssr\nend\n\nbeta_hat_ols = optimize(b-> ols(b,X,y), rand(size(X,2)), LBFGS(), Optim.Options(g_tol=1e-6, iterations = 100_000, show_trace = true))\n\nprintln(beta_hat_ols.minimizer)\n\n\t## Just checking:\n\n\tbols = inv(X'X)*X'y\n\tdf.white = df.race.==1\n\tbols_lm = lm(@formula(married ~ age+white+collgrad), df)\n\n## 3. Optimization logit lokelihood\n\n# Log likelihood\n# y(lnP) + (1-y)ln(1-P)\n\nfunction logit_ll(alpha, X, Y)\n\n\tll_i = (y.==1).*log.(exp.(X*alpha)./(1 .+exp.(X*alpha))).+(y.==0).*log.(1 ./(1 .+exp.(X*alpha)))\n\n\tll = -sum(ll_i)\n\n\treturn ll\n\nend\n\nalpha_hat_optim = optimize(a -> logit_ll(a, X, y), rand(size(X,2)), LBFGS(), Optim.Options(g_tol=1e-6, iterations=100_000, show_trace=true))\nprintln(alpha_hat_optim.minimizer)\n\n\n## 4. Check logit using glm\n\nalpha_hat_glm = glm(@formula(married ~ age + white + collgrad), df, Binomial(), LogitLink())\nprintln(alpha_hat_glm)\n\n\n## 5. Multinomial logit\n\n\t # Join categories\nfreqtable(df, :occupation) # note small number of obs in some occupations\ndf = dropmissing(df, :occupation)\ndf[df.occupation.==8 ,:occupation] .= 7\ndf[df.occupation.==9 ,:occupation] .= 7\ndf[df.occupation.==10,:occupation] .= 7\ndf[df.occupation.==11,:occupation] .= 7\ndf[df.occupation.==12,:occupation] .= 7\ndf[df.occupation.==13,:occupation] .= 7\nfreqtable(df, :occupation) # problem solved\n\n\t# Redefine X and Y as we changed their rows\nX = [ones(size(df,1),1) df.age df.race.==1 df.collgrad.==1]\ny = df.occupation\n\nfunction mlogit(alpha, X, Y)\n\n\tK = size(X,2)\n\tJ = length(unique(y))\n\tN = size(X,1)\n\n\tbigY = zeros(N,J)\n\tfor j=1:J\n\t\tbigY[:,j] = y.==j\n\tend\n\n\tbigAlpha = [reshape(alpha,K,J-1) zeros(K)]\n\n\tnum = zeros(N,J)\n\tdem = zeros(N)\n\tfor j=1:J\n\t\tnum[:,j] = exp.(X*bigAlpha[:,j])\n\t\tdem .+= num[:,j]\n\tend\n\n\tP = num ./ repeat(dem,1,J)\n\n\tll = -sum( bigY.*log.(P))\n\nend\n\nalpha_zero = zeros(6*size(X,2))\nalpha_rand = rand(6*size(X,2))\nalpha_true = [.1910213,-.0335262,.5963968,.4165052,-.1698368,-.0359784,1.30684,-.430997,.6894727,-.0104578,.5231634,-1.492475,-2.26748,-.0053001,1.391402,-.9849661,-1.398468,-.0142969,-.0176531,-1.495123,.2454891,-.0067267,-.5382892,-3.78975]\n\nalpha_start = alpha_true.*rand(size(alpha_true))\nprintln(size(alpha_true))\n\nalpha_hat_optim = optimize(a -> mlogit(a, X, y), alpha_start, LBFGS(), Optim.Options(g_tol = 1e-5, iterations=100_000, show_trace=true, show_every=50))\nalpha_hat_mle = alpha_hat_optim.minimizer\nprintln(alpha_hat_mle)\n\n## Stanrd erorrs\n\n\t## Adjust mlogit function\nfunction mlogit_hessian(alpha, X, Y)\n\n\tK = size(X,2)\n\tJ = length(unique(y))\n\tN = size(X,1)\n\n\tbigY = zeros(N,J)\n\tfor j=1:J\n\t\tbigY[:,j] = y.==j\n\tend\n\n\tbigAlpha = [reshape(alpha,K,J-1) zeros(K)]\n\n\tT = promote_type(eltype(X),eltype(alpha)) # this line is new\n\tnum = zeros(T,N,J) ## Added T first\n\tdem = zeros(T,N) ## Added T first\n\tfor j=1:J\n\t\tnum[:,j] = exp.(X*bigAlpha[:,j])\n\t\tdem .+= num[:,j]\n\tend\n\n\tP = num ./ repeat(dem,1,J)\n\n\tll = -sum( bigY.*log.(P))\n\nend\n\n# declare that the objective function is twice differentiable\ntd = TwiceDifferentiable(b -> mlogit_for_h(b, X, y), alpha_start; autodiff = :forward)\n# run the optimizer\nalpha_hat_optim_ad = optimize(td, alpha_zero, LBFGS(), Optim.Options(g_tol = 1e-5, iterations=100_000, show_trace=true, show_every=50))\nalpha_hat_mle_ad = alpha_hat_optim_ad.minimizer\n# evaluate the Hessian at the estimates\nH = Optim.hessian!(td, alpha_hat_mle_ad)\n# standard errors = sqrt(diag(inv(H))) [usually it's -H but we've already multiplied the obj fun by -1]\nalpha_hat_mle_ad_se = sqrt.(diag(inv(H)))\nprintln([alpha_hat_mle_ad alpha_hat_mle_ad_se]) # these standard errors match Stata\n", "meta": {"hexsha": "421127a8a46c781130ab3fa4052624321bf72a93", "size": 4556, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ProblemSets/PS2-optimization-intro/Sol_NU_PS2.jl", "max_stars_repo_name": "Nurdaneta/fall-2020", "max_stars_repo_head_hexsha": "a05e2e43de1028e12b81b35489f96d1defae7cb1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ProblemSets/PS2-optimization-intro/Sol_NU_PS2.jl", "max_issues_repo_name": "Nurdaneta/fall-2020", "max_issues_repo_head_hexsha": "a05e2e43de1028e12b81b35489f96d1defae7cb1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ProblemSets/PS2-optimization-intro/Sol_NU_PS2.jl", "max_forks_repo_name": "Nurdaneta/fall-2020", "max_forks_repo_head_hexsha": "a05e2e43de1028e12b81b35489f96d1defae7cb1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7804878049, "max_line_length": 242, "alphanum_fraction": 0.6428884987, "num_tokens": 1510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669026, "lm_q2_score": 0.8856314647623015, "lm_q1q2_score": 0.8035442538199862}} {"text": "#=\n From\n \"Probabilistic logic programming and its applications\"\n Luc De Raedt, Leuven\n https://www.youtube.com/watch?v=3lnVBqxjC88\n @ 3:44\n\n \"\"\"\n Mike has a bag of marbles with 4 white, 8 blue, and\n 6 red marbles. He pulls out one marble from the bag\n and it is red. What is the probability that the\n second marble he pulls out of the bag is white?\n\n The answer is 0.234931.\n \"\"\"\n\n draw1: The probability of drawing white is the probability for 1.0\n Distributions of variable draw1\n blue => 47204 (0.472040)\n red => 29283 (0.292830)\n white => 23513 (0.235130)\n\n\n Cf ~/cplint/bag_of_marbles.pl\n ~/blog/bag_of_marbles.blog\n ~/psi/bag_of_marbles.psi\n ~/webppl/bag_of_marbles.wppl\n\n Also see bag_of_marbles2.jl for an alternative approach (using recursion).\n\n=#\n\nusing Turing, StatsPlots, DataFrames\ninclude(\"jl_utils.jl\")\n\n@model function bag_of_marbles()\n\n white = 1\n blue = 2\n red = 3\n colors = [white,blue,red]\n\n start = [4,8,6];\n\n draw0 ~ Categorical(simplex([start[white],start[blue],start[red]]))\n\n\n if draw0 == white\n draw1 ~ Categorical(simplex([start[white]-1,start[blue],start[red]]))\n elseif draw0==blue\n draw1 ~ Categorical(simplex([start[white],start[blue]-1,start[red]]))\n else\n # red\n draw1 ~ Categorical([start[white],start[blue],start[red]-1]|>simplex);\n end\n\n true ~ Dirac(draw0 == red)\n\nend\n\nmodel = bag_of_marbles()\nnum_chns = 4\n\n# chns = sample(model, Prior(), 100_000)\nchns = sample(model, MH(), 100_000)\n\n# chns = sample(model, PG(15), 10_000)\n# chns = sample(model, SMC(), 10_000)\n\n# Note: IS don't generate chns the same way as MH, PG, and SMC!\n# chns = sample(model, IS(), 10_000)\n\ndisplay(chns)\n\nshow_var_dist_pct(chns,:draw0,[\"white\",\"blue\",\"red\"])\nprintln(\"\\ndraw1: The probability of drawing white is the probability for 1.0\")\nshow_var_dist_pct(chns,:draw1,[\"white\",\"blue\",\"red\"])\n", "meta": {"hexsha": "2d760fa56cbe978255f4eae5546761bb3848ebd5", "size": 1931, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/bag_of_marbles.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/turing/bag_of_marbles.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/turing/bag_of_marbles.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 24.7564102564, "max_line_length": 79, "alphanum_fraction": 0.6613153806, "num_tokens": 628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312213841788, "lm_q2_score": 0.885631470799559, "lm_q1q2_score": 0.8035442504191066}} {"text": "\nusing Distributions\nusing Plots\n\ngrid_size = 40\nproba_grid = range(0, 1, length=grid_size)\n\n## Code block 2.5\n# prior = ones((grid_size))\n# prior = collect(proba_grid) .>= 0.5\nprior = exp.(-5 * abs.(collect(proba_grid) .- 0.5))\n\nplot(\n proba_grid, prior, title=\"40 Points\", xlabel=\"Probability of water\", \n ylabel=\"Prior probability\", lw=3\n)\n\nlikelihood = [pdf(Binomial(9, p), 6) for p in proba_grid]\nposterior = prior .* likelihood\nposterior_proba = posterior / sum(posterior)\n\n## Code block 2.4\nplot(\n proba_grid, posterior_proba, title=\"40 Points\", xlabel=\"Probability of water\", \n ylabel=\"Posterior probability\", lw=3\n)\n", "meta": {"hexsha": "839eea9ec78fec7f6cfde7f0cfefd92b3a8efd1f", "size": 637, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "2-3_grid_posterior.jl", "max_stars_repo_name": "CrosstabKite/stat_rethinking_julia", "max_stars_repo_head_hexsha": "5dd23fc7d2a438db59e4b45ae08d93503c1a4ef3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2-3_grid_posterior.jl", "max_issues_repo_name": "CrosstabKite/stat_rethinking_julia", "max_issues_repo_head_hexsha": "5dd23fc7d2a438db59e4b45ae08d93503c1a4ef3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2-3_grid_posterior.jl", "max_forks_repo_name": "CrosstabKite/stat_rethinking_julia", "max_forks_repo_head_hexsha": "5dd23fc7d2a438db59e4b45ae08d93503c1a4ef3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5925925926, "max_line_length": 83, "alphanum_fraction": 0.693877551, "num_tokens": 197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693241974031599, "lm_q2_score": 0.82893881677331, "lm_q1q2_score": 0.8035104532651138}} {"text": "# SQRT FUNCTION\n# (x+1)^0.5\nfunction sum_sqrt(x::Array{Float64,1})\n return sum(sqrt(x+1))\nend\n\nfunction d_sum_sqrt(x::Array{Float64,1})\n return 0.5 * (x+1).^(-0.5)\nend\n\nfunction dd_sum_sqrt(x::Array{Float64,1})\n return spdiagm(-0.25 * (x+1).^(-1.5))\nend\n\nfunction nl_sqrt(num_var::Int64)\n return class_nl_function(num_var,sum_sqrt,d_sum_sqrt,dd_sum_sqrt);\nend\n\n# LOG function\nfunction sum_log(x::Array{Float64,1})\n return sum(log(x+1))\nend\n\nfunction d_sum_log(x::Array{Float64,1})\n return (x+1).^(-1.0)\nend\n\nfunction dd_sum_log(x::Array{Float64,1})\n return spdiagm(-(x+1).^(-2.0))\nend\n\nfunction nl_log(num_var::Int64)\n return class_nl_function(num_var::Int64,sum_log,d_sum_log,dd_sum_log);\nend\n\n# Quadratic\n# c'*x + 0.5 * x*Q*x + b\nfunction nl_quad(c::AbstractArray, Q::SparseMatrixCSC{Float64,Int64}, b::Float64)\n function value(x::Array{Float64,1})\n return (c' * x)[1] + 0.5 * (x' * Q * x)[1] + b\n end\n\n function gradient(x::Array{Float64,1})\n return (c + Q * x)[:]\n end\n\n function hessian(x::Array{Float64,1})\n return Q\n end\n\n return class_nl_function(length(c), value, gradient, hessian)\nend\n\nfunction sphere_function(center_point::Float64,radius::Float64)\n b = dot(center_point,center_point) - radius\n c = -2 * center_point\n\n return nl_quad(c, speye(length(c)), b)\nend\n", "meta": {"hexsha": "0c729b53fbcb8397f66bb23e7a0c746fb2f867a9", "size": 1349, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/benchmarking/nl_functions.jl", "max_stars_repo_name": "ohinder/Everest.jl", "max_stars_repo_head_hexsha": "1462c198b7c2838266aa8e69a06a59d5b079be43", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/benchmarking/nl_functions.jl", "max_issues_repo_name": "ohinder/Everest.jl", "max_issues_repo_head_hexsha": "1462c198b7c2838266aa8e69a06a59d5b079be43", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2015-12-28T21:40:41.000Z", "max_issues_repo_issues_event_max_datetime": "2016-01-31T04:44:37.000Z", "max_forks_repo_path": "src/benchmarking/nl_functions.jl", "max_forks_repo_name": "ohinder/Everest", "max_forks_repo_head_hexsha": "1462c198b7c2838266aa8e69a06a59d5b079be43", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.4833333333, "max_line_length": 81, "alphanum_fraction": 0.6627131208, "num_tokens": 450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542840900507, "lm_q2_score": 0.8376199552262967, "lm_q1q2_score": 0.8034067684946189}} {"text": "module MathUtils\n\nexport log_sum_exp\nfunction log_sum_exp(logs)\n maxlog = maximum(logs)\n return maxlog + log(sum(exp(logs - maxlog)))\nend\n\nexport sample_discrete\nfunction sample_discrete(dist)\n r = rand()\n s = 0.\n for i=1:length(dist)\n s += dist[i]\n if r <= s\n return(i)\n end\n end\n return(length(dist))\nend\n\nexport sample_discrete_logspace\nfunction sample_discrete_logspace(log_unnormalized_dist)\n n = length(log_unnormalized_dist)\n logsum = log_sum_exp(log_unnormalized_dist)\n logr = log(rand())\n logc = log_unnormalized_dist[1] - logsum\n for i=1:n-1\n if logr <= logc\n return i\n end\n logp = log_unnormalized_dist[i+1] - logsum\n if logp > logc\n logc = logp + log1p(exp(logc - logp))\n else\n logc = logc + log1p(exp(logp - logc))\n end\n end\n return(n)\nend\n\nexport normalize_log_dist\nfunction normalize_log_dist(d)\n d - log_sum_exp(d)\nend\n\nexport is_valid_dist\nfunction is_valid_dist(dist)\n abs(sum(dist) - 1.0) <= eps(1.0) && minimum(dist) >= 0.0\nend\n\nexport importance_sample\nfunction importance_sample(π, q, n)\n assert(length(π) == length(q))\n assert(is_valid_dist(π))\n assert(is_valid_dist(q))\n p = zeros(length(π))\n counts = zeros(length(π))\n for i=1:n\n x = sample_discrete(q)\n p[x] += (1.0 / n) * π[x] / q[x]\n counts[x] += 1\n end\n p, counts\nend\n\nend # module\n", "meta": {"hexsha": "8af213759a348d9bb8839f1374e60cc4d9f9e7f0", "size": 1341, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MathUtils.jl", "max_stars_repo_name": "BelhalK/Julia", "max_stars_repo_head_hexsha": "5c61617115b3203a5ef221ae2cb8e7657e15fd03", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MathUtils.jl", "max_issues_repo_name": "BelhalK/Julia", "max_issues_repo_head_hexsha": "5c61617115b3203a5ef221ae2cb8e7657e15fd03", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MathUtils.jl", "max_forks_repo_name": "BelhalK/Julia", "max_forks_repo_head_hexsha": "5c61617115b3203a5ef221ae2cb8e7657e15fd03", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.7205882353, "max_line_length": 58, "alphanum_fraction": 0.668158091, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693674025231, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.8033656229861965}} {"text": "\"\"\"\n FBMKernel(; h::Real=0.5)\n\nFractional Brownian motion kernel with Hurst index `h` from (0,1) given by\n```\n κ(x,y) = ( |x|²ʰ + |y|²ʰ - |x-y|²ʰ ) / 2\n```\n\nFor `h=1/2`, this is the Wiener Kernel, for `h>1/2`, the increments are\npositively correlated and for `h<1/2` the increments are negatively correlated.\n\"\"\"\nstruct FBMKernel{T<:Real} <: Kernel\n h::Vector{T}\n function FBMKernel(; h::T=0.5) where {T<:Real}\n @assert 0.0 <= h <= 1.0 \"FBMKernel: Given Hurst index h is invalid.\"\n return new{T}([h])\n end\nend\n\n@functor FBMKernel\n\nfunction (κ::FBMKernel)(x::AbstractVector{<:Real}, y::AbstractVector{<:Real})\n modX = sum(abs2, x)\n modY = sum(abs2, y)\n modXY = sqeuclidean(x, y)\n h = first(κ.h)\n return (modX^h + modY^h - modXY^h)/2\nend\n\n(κ::FBMKernel)(x::Real, y::Real) = (abs2(x)^first(κ.h) + abs2(y)^first(κ.h) - abs2(x - y)^first(κ.h)) / 2\n\nBase.show(io::IO, κ::FBMKernel) = print(io, \"Fractional Brownian Motion Kernel (h = \", first(κ.h), \")\")\n\n_fbm(modX, modY, modXY, h) = (modX^h + modY^h - modXY^h)/2\n\n_mod(x::AbstractVector{<:Real}) = abs2.(x)\n_mod(x::ColVecs) = vec(sum(abs2, x.X; dims=1))\n_mod(x::RowVecs) = vec(sum(abs2, x.X; dims=2))\n\nfunction kernelmatrix(κ::FBMKernel, x::AbstractVector)\n modx = _mod(x)\n modxx = pairwise(SqEuclidean(), x)\n return _fbm.(modx, modx', modxx, κ.h)\nend\n\nfunction kernelmatrix!(K::AbstractMatrix, κ::FBMKernel, x::AbstractVector)\n modx = _mod(x)\n pairwise!(K, SqEuclidean(), x)\n K .= _fbm.(modx, modx', K, κ.h)\n return K\nend\n\nfunction kernelmatrix(κ::FBMKernel, x::AbstractVector, y::AbstractVector)\n modxy = pairwise(SqEuclidean(), x, y)\n return _fbm.(_mod(x), _mod(y)', modxy, κ.h)\nend\n\nfunction kernelmatrix!(\n K::AbstractMatrix,\n κ::FBMKernel,\n x::AbstractVector,\n y::AbstractVector,\n)\n pairwise!(K, SqEuclidean(), x, y)\n K .= _fbm.(_mod(x), _mod(y)', K, κ.h)\n return K\nend\n", "meta": {"hexsha": "ca753ff6c8acb34cd05dcaf3dfa3e43586101cbf", "size": 1914, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/basekernels/fbm.jl", "max_stars_repo_name": "gkazunii/KernelFunctions.jl", "max_stars_repo_head_hexsha": "1e5751ec632477373203886920b1fe0f29966b48", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-22T12:11:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-22T12:11:38.000Z", "max_issues_repo_path": "src/basekernels/fbm.jl", "max_issues_repo_name": "st--/KernelFunctions.jl", "max_issues_repo_head_hexsha": "d6eab2bfbf5c772bd293752665ea42dd087866b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/basekernels/fbm.jl", "max_forks_repo_name": "st--/KernelFunctions.jl", "max_forks_repo_head_hexsha": "d6eab2bfbf5c772bd293752665ea42dd087866b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1470588235, "max_line_length": 105, "alphanum_fraction": 0.6201671891, "num_tokens": 708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693645535724, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.8033656131992063}} {"text": "### A Pluto.jl notebook ###\n# v0.12.20\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ b2937383-dcbe-4863-9267-eca115a7b666\nbegin\n\tusing Pkg\n\tPkg.activate(mktempdir())\n\tPkg.Registry.update()\n\tPkg.add(\"Yao\")\n\tPkg.add(\"YaoPlots\")\nend\n\n# ╔═╡ 57209cca-1ede-11eb-283b-196a50e6f1eb\nusing Yao,YaoPlots\n\n# ╔═╡ 76794562-1ed0-11eb-18ec-ad4020344ce6\nmd\"# Arithmetic using qubits\"\n\n# ╔═╡ ad61776c-1ed9-11eb-20af-7d41b6e281c3\nmd\"## Binary addition\"\n\n# ╔═╡ 949416ee-1ed0-11eb-2a86-dd52c9b1d5f9\nmd\"Suppose we've to add two numbers in binary form! Say... `` 5 `` and `` 7 ``.\"\n\n# ╔═╡ aad0de2e-1ed0-11eb-3efc-95c0072fff76\nmd\"In binary form, `` 5 `` can be represented by `` 101 `` and `` 7 `` can be represented by `` 111 ``. Remember when adding two numbers in binary form, \n\n- `` 0 + 0 = 0 ``\n- `` 0 + 1 = 1 ``\n- `` 1 + 0 = 1 ``\n- `` 1 + 1 = 0 `` with a carry of `` 1 ``\n\nSo adding `` 5 `` and `` 7 `` in binary form looks somewhat like this.\n- `` \\;\\;\\;\\; ₁ \\;₁\\;\\;₁\\;₀ `` ← **Carry**\n- `` \\;\\;\\;\\;\\;\\;1\\; 0\\; 1 ``\n- `` \\;\\; `` + `` \\; 1\\; 1\\; 1 ``\n- `` \\;\\; `` _________\n- `` \\;\\;\\;1\\;1\\;0\\;0 ``\n\nStarting from right, and moving to left\n\n- `` 1 + 1 = 0 `` with a carry of `` 1 ``\n- `` 0 + 1 = 1 `` which is added to the carried value, which is `` 1 ``, so `` 1 + 1 = 0 `` with a carry of `` 1 ``, again\n- `` 1 + 1 = 0 `` with a carry of `` 1 ``. The result is added again to the carried value, which was `` 1 ``, so `` 0 + 1 = 1 ``\n- The remaining carried value, which is `` 1 ``, is put as it is.\n\"\n\n# ╔═╡ c731fcb8-1ed7-11eb-2800-4fda7d5ae5e7\nmd\"The result is `` \\; [( 1 × 2^3 ) + ( 1 × 2^2 ) + ( 0 × 2^1 ) + ( 0 × 2^0 )] = 12. ``\"\n\n# ╔═╡ b914c0b4-1ed9-11eb-37e9-8f1a60dbfcb2\nmd\"#### Quantum addition circuit for one pair of qubits\"\n\n# ╔═╡ ec622eb0-1eda-11eb-0ca2-1bc4b4f1a730\nmd\"We'll try making the adder circuit for addition of two numbers `` (0-7) ``. We'll need `` 3 `` qubits to represent each of the two numbers, which means a total of `` 6 `` qubits.\"\n\n# ╔═╡ 30953b42-1ede-11eb-32ee-af55afa9221f\nbegin\n\tFirstNumber = ArrayReg(bit\"111\") #The first number is 7\n\tSecondNumber = ArrayReg(bit\"101\") #The second number is 5\nend\n\n# ╔═╡ 2ae7c4ec-1ee0-11eb-1c46-59d4d3084b39\nmd\"For adding each pair of qubits, we'll need two more qubits to hold the carried in value and carried out value. Since the carry out of the 1st pair acts as the carry in of second pair, the carry out of the second pair acts as the carry in of the 3rd pair, we need 4 more qubits for carry in and carry out, with\n\n- 1 qubit for the carry-in of first pair\n- 1 qubit for the carry-out of first pair and the carry-in of the second pair\n- 1 qubit for the carry-out of second pair and the carry-in of the third pair\n- 1 qubit for the carry-out of third pair\n\nIn total, we require a total of `` 10 `` qubits to add two numbers in the range `` \\; 0-7 ``.\"\n\n# ╔═╡ 1ac1e8c0-1f2d-11eb-1cc5-5986d94a86c2\nmd\"So lets try making the quantum circuit for adding two qubits. We need a qubit for carry-in, which will be zero for the rightmost pair, and a qubit for carry-out, which will act as the carry in for the next pair\"\n\n# ╔═╡ 1d8ce7a2-1f2e-11eb-1b74-0d601958a2c9\nmd\"Consider this circuit\"\n\n# ╔═╡ 802cf394-1f2d-11eb-23ad-95c475382371\nbegin\n\tOneqbQFA = chain(4, control(2:3, 4=>X), control(2, 3=>X), control([1 3], 4=>X), control(1, 3=>X))\n\tplot(OneqbQFA)\nend\n\n# ╔═╡ 36613c90-1f2e-11eb-1f5e-d3e079a8deda\nmd\"\n- The top qubit holds the carry-in value. \n- The bottom qubit has the state `` |0〉 ``. \n- The 2nd and the 3rd qubits hold the pair to be added.\nAfter passing throught the circuit,\n- The top qubit holds the carry-in value. \n- The bottom qubit holds the carry-out value. \n- The 2nd qubit is as it was, while the 3rd qubit holds the addition of the 2nd and 3rd qubit.\n\"\n\n# ╔═╡ 88d976e2-1f2e-11eb-0b7c-ad9557d124e6\nmd\"### The use of CX gate in Arithmetics\"\n\n# ╔═╡ ade4a628-1f2e-11eb-32d0-c16546a16e44\nmd\"Consider this circuit\"\n\n# ╔═╡ b307d638-1f2f-11eb-19ec-5fb58b49ff0f\nbegin\n\ta = chain(2, control(1, 2=>X))\n\tplot(a)\nend\n\n# ╔═╡ 31a37e02-1f30-11eb-3c16-494e05427f33\nmd\"Lets try passing different values through this circuit\"\n\n# ╔═╡ 41c223ec-1f30-11eb-038b-efd7279954e6\nmeasure((ArrayReg(bit\"00\") |> a)) #The output is 00, when we passed 00\n\n# ╔═╡ 6ba13306-1f30-11eb-04c7-9f1c51a49915\nmeasure(ArrayReg(bit\"01\") |> a) #The output is 11, when we passed 01\n#Remember, the circuit takes the qubits as inputs, in reverse order. The rightmost qubit is the 1st qubit here, and since its |1〉, the 2nd qubit gets flipped to |1〉 too. \n\n# ╔═╡ 95dbc5be-1f30-11eb-232f-e72c7bfbda61\nmeasure(ArrayReg(bit\"10\") |> a) #The output is 10, when we passed 10\n#Remember, the circuit takes the qubits as inputs, in reverse order. The rightmost qubit is the 1st qubit here, and since its |0〉, the 2nd qubit is left untouched.\n\n# ╔═╡ d33faf76-1f30-11eb-0dd7-3d1331633c0a\nmeasure(ArrayReg(bit\"11\") |> a) #The output is 01, when we passed 11\n#Remember, the circuit takes the qubits as inputs, in reverse order. The rightmost qubit is the 1st qubit here, and since its |1〉, the 2nd qubit is flipped to |0〉.\n\n# ╔═╡ b3823ea8-1f31-11eb-0651-d55953af774a\nmd\"Lets analyze the output\n- When the top qubit is `` |0〉 `` and the bottom qubit is `` |0〉 ``, the bottom qubit is left untouched.\n- When the top qubit is `` |1〉 `` and the bottom qubit is `` |0〉 ``, the bottom qubit is flipped to `` |1〉 ``.\n- When the top qubit is `` |0〉 `` and the bottom qubit is `` |1〉 ``, the bottom qubit is left untouched.\n- When the top qubit is `` |1〉 `` and the bottom qubit is `` |1〉 ``, the bottom qubit is flipped to `` |0〉 ``.\nCompare this with,\n- `` 0 + 0 = 0 ``\n- `` 0 + 1 = 1 ``\n- `` 1 + 0 = 1 ``\n- `` 1 + 1 = 0 ``\nIn all the cases, the bottom qubit holds the added value.\n\nHow about adding 3 qubits?\n\"\n\n# ╔═╡ c7b7511c-1f34-11eb-37ba-f71851aceb94\nbegin\n\tb = chain(3, control(2, 3=>X), control(1, 3=>X))\n\tplot(b)\nend\n\n# ╔═╡ fce93e40-1f34-11eb-3ea6-a11d129d7af3\nmeasure.([(ArrayReg(bit\"000\") |> b) \n\t\t(ArrayReg(bit\"001\") |> b) \n\t\t(ArrayReg(bit\"010\") |> b) \n\t\t(ArrayReg(bit\"011\") |> b) \n\t\t(ArrayReg(bit\"110\") |> b) \n\t\t(ArrayReg(bit\"101\") |> b) \n\t\t(ArrayReg(bit\"100\") |> b) \n\t\t(ArrayReg(bit\"111\") |> b)])\n#If the output is not visible, click on the output to expand it.\n\n# ╔═╡ 1604f776-1f36-11eb-03fc-c5575a528776\nmd\"The toffoli gate acts as the carry-out. If both input qubits are `` |1〉 ``, the 3rd qubit is flipped.\"\n\n# ╔═╡ ba41d664-1f3a-11eb-2334-83fa55bc3bb6\nmd\"### The Quantum Adder Circuit\"\n\n# ╔═╡ f4db1d44-1f3a-11eb-0b8c-4589d745d435\nmd\"We already made the circuit for adding two qubits. Remember that the carry-out for the first pair, becomes the carry in for the second pair. With this, here's the circuit for a quantum adder for 2 numbers between `` 0-7 ``.\"\n\n# ╔═╡ 92b2e1b4-4457-11eb-22c0-7b5173d6bd97\nplot(chain(10, put(1:4=>label(chain(4), \"Full adder\\nfor a pair\\n of qubits\")), put(4:7=>label(chain(4), \"Full adder\\nfor a pair\\n of qubits\")), put(7:10=>label(chain(4), \"Full adder\\nfor a pair\\n of qubits\"))))\n\n# ╔═╡ 71d66a6e-4458-11eb-0a56-69919a6dbdca\nmd\"Below is a complete circuit for quantum adder for 2 numbers between `` 0 - 7 ``.\"\n\n# ╔═╡ 412203a2-1f3b-11eb-3de7-45f7eccd697e\nbegin\n\tnqbQFA = chain(10, put(1:4=>OneqbQFA), put(4:7=>OneqbQFA), put(7:10=>OneqbQFA))\n\tplot(nqbQFA)\nend\n\n# ╔═╡ c2afc0f8-1f3b-11eb-0626-c5120a452e38\nmd\"The input to the circuit being - \"\n\n# ╔═╡ e4b012f0-1f3b-11eb-1336-af9ba42a98c8\nbegin\n\tinput = join(zero_state(4), FirstNumber, SecondNumber)\n\t# 10 9 8 7 6 5 4 3 2 1\n\t# 1 0 1 1 1 1 0 0 0 0\n\t# 2 5 8 3 6 9 1 4 7 10\n\treorder!(input, [2 5 8 3 6 9 1 4 7 10]) #Re-ordering the qubits, for being the input to the above circuit\nend\n\n# ╔═╡ 1abc9e96-4b70-11eb-1661-7f37fdea9130\nmeasure(input)\n\n# ╔═╡ 04c694e4-1f3c-11eb-1faf-0d08d391ce64\nresults = input |> nqbQFA |> r->measure(r, nshots=1024)\n\n# ╔═╡ 1083740a-1f3c-11eb-2950-c56e4f20087c\nstringres = reverse(string(Int(results[1]), base=2, pad=10)) #To convert it to string\n\n# ╔═╡ 23e71498-1f3c-11eb-1c3e-2dac1694afeb\nmd\"Remember, the 3, 6 and 9th qubits hold the added values. The 10 qubit holds the final carry-out, if any.\"\n\n# ╔═╡ 4e89800a-1f3c-11eb-239f-f92807c81881\noutput = parse(Int64, reverse(stringres[3] * stringres[6] * stringres[9] * stringres[10]), base=2)\n\n# ╔═╡ 270619d0-1f50-11eb-3a89-1187e12bd4f9\nmd\"## Quantum subtractor\"\n\n# ╔═╡ 976e00e8-1f50-11eb-0d93-77e2ba841a09\nmd\"Binary subtraction has a borrow instead of carry. The rules of binary subtraction look somewhat like this.\n- `` 0 - 0 = 0 ``\n- `` 0 - 1 = 1 `` with a borrow of `` 1 ``\n- `` 1 - 0 = 1 ``\n- `` 1 - 1 = 0 ``\n\"\n\n# ╔═╡ 346af906-1f50-11eb-3286-dbf3014c8fab\nbegin\n\tOneqbSubtractor = chain(4, control(1, 3=>X), put(2=>X), control(2:3, 4=>X), control(1, 3=>X), control([1 3], 4=>X), put(2=>X), control(2, 3=>X), control(1, 3=>X))\n\tplot(OneqbSubtractor)\nend\n\n# ╔═╡ e2659b46-1f51-11eb-34db-dbc917b977dd\nbegin\n\tnqbQFS = chain(10, put(1:4=>OneqbSubtractor), put(4:7=>OneqbSubtractor), put(7:10=>OneqbSubtractor))\n\tplot(nqbQFS)\nend\n\n# ╔═╡ adeee882-1f55-11eb-27a4-d79963776e20\nmeasure(join(zero_state(1), ArrayReg(bit\"10\"), zero_state(1)) |> OneqbSubtractor)\n\n# ╔═╡ 2ff67ae4-4b4c-11eb-17a6-45e64c916c48\nbegin \n\tp = ArrayReg(bit\"111\")\n\tq = ArrayReg(bit\"101\")\n\tinp = join(zero_state(4), p, q)\n\treorder!(inp, [3 6 9 2 5 8 1 4 7 10])\nend\n\n# ╔═╡ 31eb23f6-4b5e-11eb-2aa3-39ef184edb69\nmeasure(inp)\n\n# ╔═╡ 1f828098-1f52-11eb-1d00-27f10270a814\nresult = inp |> nqbQFS |> r->measure(r, nshots=1024)\n\n# ╔═╡ 3cbd0f52-1f52-11eb-06f4-ffe29cccde57\nstringsub = reverse(string(Int(result[1]), base=2, pad=10)) #To convert it to string\n\n# ╔═╡ 658eec52-1f52-11eb-39aa-bbf1fcfb3517\nout = parse(Int64, reverse(stringsub[3] * stringsub[6] * stringsub[9] * stringsub[10]), base=2)\n\n# ╔═╡ ffd40492-1f56-11eb-210d-ef6bf293244e\nmd\"This circuit only subtracts numbers if the answer is expected to be positive. It can't solve for calculations like `` 5 - 6 = -1 ``.\"\n\n# ╔═╡ Cell order:\n# ╠═b2937383-dcbe-4863-9267-eca115a7b666\n# ╟─76794562-1ed0-11eb-18ec-ad4020344ce6\n# ╟─ad61776c-1ed9-11eb-20af-7d41b6e281c3\n# ╟─949416ee-1ed0-11eb-2a86-dd52c9b1d5f9\n# ╟─aad0de2e-1ed0-11eb-3efc-95c0072fff76\n# ╟─c731fcb8-1ed7-11eb-2800-4fda7d5ae5e7\n# ╟─b914c0b4-1ed9-11eb-37e9-8f1a60dbfcb2\n# ╟─ec622eb0-1eda-11eb-0ca2-1bc4b4f1a730\n# ╠═57209cca-1ede-11eb-283b-196a50e6f1eb\n# ╠═30953b42-1ede-11eb-32ee-af55afa9221f\n# ╟─2ae7c4ec-1ee0-11eb-1c46-59d4d3084b39\n# ╟─1ac1e8c0-1f2d-11eb-1cc5-5986d94a86c2\n# ╟─1d8ce7a2-1f2e-11eb-1b74-0d601958a2c9\n# ╠═802cf394-1f2d-11eb-23ad-95c475382371\n# ╟─36613c90-1f2e-11eb-1f5e-d3e079a8deda\n# ╟─88d976e2-1f2e-11eb-0b7c-ad9557d124e6\n# ╟─ade4a628-1f2e-11eb-32d0-c16546a16e44\n# ╠═b307d638-1f2f-11eb-19ec-5fb58b49ff0f\n# ╟─31a37e02-1f30-11eb-3c16-494e05427f33\n# ╠═41c223ec-1f30-11eb-038b-efd7279954e6\n# ╠═6ba13306-1f30-11eb-04c7-9f1c51a49915\n# ╠═95dbc5be-1f30-11eb-232f-e72c7bfbda61\n# ╠═d33faf76-1f30-11eb-0dd7-3d1331633c0a\n# ╟─b3823ea8-1f31-11eb-0651-d55953af774a\n# ╠═c7b7511c-1f34-11eb-37ba-f71851aceb94\n# ╠═fce93e40-1f34-11eb-3ea6-a11d129d7af3\n# ╟─1604f776-1f36-11eb-03fc-c5575a528776\n# ╟─ba41d664-1f3a-11eb-2334-83fa55bc3bb6\n# ╟─f4db1d44-1f3a-11eb-0b8c-4589d745d435\n# ╟─92b2e1b4-4457-11eb-22c0-7b5173d6bd97\n# ╟─71d66a6e-4458-11eb-0a56-69919a6dbdca\n# ╠═412203a2-1f3b-11eb-3de7-45f7eccd697e\n# ╟─c2afc0f8-1f3b-11eb-0626-c5120a452e38\n# ╠═e4b012f0-1f3b-11eb-1336-af9ba42a98c8\n# ╠═1abc9e96-4b70-11eb-1661-7f37fdea9130\n# ╠═04c694e4-1f3c-11eb-1faf-0d08d391ce64\n# ╠═1083740a-1f3c-11eb-2950-c56e4f20087c\n# ╟─23e71498-1f3c-11eb-1c3e-2dac1694afeb\n# ╠═4e89800a-1f3c-11eb-239f-f92807c81881\n# ╟─270619d0-1f50-11eb-3a89-1187e12bd4f9\n# ╟─976e00e8-1f50-11eb-0d93-77e2ba841a09\n# ╠═346af906-1f50-11eb-3286-dbf3014c8fab\n# ╠═e2659b46-1f51-11eb-34db-dbc917b977dd\n# ╠═adeee882-1f55-11eb-27a4-d79963776e20\n# ╠═2ff67ae4-4b4c-11eb-17a6-45e64c916c48\n# ╠═31eb23f6-4b5e-11eb-2aa3-39ef184edb69\n# ╠═1f828098-1f52-11eb-1d00-27f10270a814\n# ╠═3cbd0f52-1f52-11eb-06f4-ffe29cccde57\n# ╠═658eec52-1f52-11eb-39aa-bbf1fcfb3517\n# ╟─ffd40492-1f56-11eb-210d-ef6bf293244e\n", "meta": {"hexsha": "0b6bd59b001b15db5f59e7e6dd1d14ec7c43550f", "size": 11880, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/getting-started/6-quantum_arithmetic.jl", "max_stars_repo_name": "wildart/Yao.jl", "max_stars_repo_head_hexsha": "f1975d50627ca271ac524866dc64ca96ece0a05a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-12-11T00:16:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T04:30:36.000Z", "max_issues_repo_path": "notebooks/getting-started/6-quantum_arithmetic.jl", "max_issues_repo_name": "wildart/Yao.jl", "max_issues_repo_head_hexsha": "f1975d50627ca271ac524866dc64ca96ece0a05a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2019-12-07T04:15:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-01T19:54:20.000Z", "max_forks_repo_path": "notebooks/getting-started/6-quantum_arithmetic.jl", "max_forks_repo_name": "wildart/Yao.jl", "max_forks_repo_head_hexsha": "f1975d50627ca271ac524866dc64ca96ece0a05a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2019-12-11T19:20:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-26T09:52:56.000Z", "avg_line_length": 38.3225806452, "max_line_length": 312, "alphanum_fraction": 0.6902356902, "num_tokens": 5631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026573249612, "lm_q2_score": 0.8757869900269366, "lm_q1q2_score": 0.8033617332023383}} {"text": "# coding: utf-8\n\n\n# In[1]: \n\n#coin change is a straight forward dynamic programming problem\n#you are given one note and a set of coins of different values\n#assuming you have infinite supply of coins of different values\n#we need to compute different ways of making change\n#the order of the coins doesnt matter in this case\n#more details can be found in the following link\n# https://www.geeksforgeeks.org/coin-change-dp-7/\n#the script can also be done in dynamic programming\n# https://github.com/je-suis-tm/recursion-and-dynamic-programming/blob/master/coin%20change%20dynamic%20programming.jl\n\n\n# In[2]: \n\n\n#to solve this problem via recursion\n#we divide one big problem into two sub problems\n#the case where coin of η value is excluded in the solutions\n#and the case where at least one coin of η value is included\nfunction coin_change(num,choice)\n \n #base case\n if num==0\n \n return 1\n \n end\n \n #prevent stack overflow\n if num<0\n \n return 0\n \n end\n \n output=0\n \n #iterate through cases of exclusion\n for i in 1:length(choice)\n \n #case of inclusion\n include=coin_change(num-choice[i],choice)\n exclude=0\n \n #case of exclusion\n if i>=2\n \n exclude=coin_change(num,choice[1:(i-1)])\n \n end\n \n #two sub problems merge into a big one\n output=include+exclude\n \n end\n \n return output\n \nend\n\n\n# In[3]: \n\n\ncoin_change(10,[1,2,3])\n", "meta": {"hexsha": "774b7f6ece75fb995ee92a95367ad86d5cdcc9aa", "size": 1527, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "coin change recursion.jl", "max_stars_repo_name": "je-suis-tm/recursion-and-dynamic-programming", "max_stars_repo_head_hexsha": "55a6085cd45b73426379ff947d9a842ef7d325bb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2019-03-22T10:31:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T13:30:17.000Z", "max_issues_repo_path": "coin change recursion.jl", "max_issues_repo_name": "slowbrain/recursion-and-dynamic-programming", "max_issues_repo_head_hexsha": "1cd77db1e7940fee15fc8aa2cedd3ab84e10374f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "coin change recursion.jl", "max_forks_repo_name": "slowbrain/recursion-and-dynamic-programming", "max_forks_repo_head_hexsha": "1cd77db1e7940fee15fc8aa2cedd3ab84e10374f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2019-10-27T12:34:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T13:54:37.000Z", "avg_line_length": 21.8142857143, "max_line_length": 118, "alphanum_fraction": 0.6371971185, "num_tokens": 369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026482819238, "lm_q2_score": 0.8757869819218865, "lm_q1q2_score": 0.8033617178477798}} {"text": "#!/usr/bin/env julia\n# -*- coding: utf-8 -*-\n# File : circle_approx.jl\n# License: MIT\n# Author : Andrei Leonard Nicusan \n# Date : 21.05.2021\n\n\nusing GLMakie\nusing LazySets\n\n\n# Return points on a circle\nfunction circle(;centre = [0., 0.], radius = 1., n = 16)\n points = zeros(2, n + 1)\n for (i, α) in enumerate(LinRange(0, 2pi, n + 1))\n points[1, i] = centre[1] + radius * cos(α)\n points[2, i] = centre[2] + radius * sin(α)\n end\n\n points\nend\n\n\n# Analytical circle points\nt = LinRange(0, 2pi, 100)\ncircle_analytical = [cos.(t) sin.(t)]\n\n\n# Ploting\nfig = Figure()\naxes = [Axis(fig[1, i]) for i in 1:2]\nfor ax in axes\n ax.aspect = AxisAspect(1)\nend\n\nlines!(axes[1], circle_analytical[:, 1], circle_analytical[:, 2], color = :red, linewidth = 3,\n label = \"∞\")\n\n\n# Plot polygonal approximations and area ratio\nnverts = collect(4:64)\nratios = zeros(length(nverts))\nto_plot = [4, 8, 16, 32]\n\nfor (i, n) in enumerate(nverts)\n circle_points = circle(n = Int64(n))\n circle_poly = VPolygon(circle_points)\n ratios[i] = area(circle_poly) / pi\n\n if n in to_plot\n lines!(axes[1], circle_points[1, :], circle_points[2, :], label = \"$n\")\n end\nend\n\nlines!(axes[2], nverts, ratios)\n\naxislegend(axes[1])\nfig\n", "meta": {"hexsha": "31c92768bd0a1961e7e2bed3188d6dc7a3057bb4", "size": 1272, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "dev/circle_approx.jl", "max_stars_repo_name": "anicusan/KonigCell", "max_stars_repo_head_hexsha": "6f55d06c9457dd0e601910f0cd4a7f95742ac009", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-12-16T10:15:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T13:58:29.000Z", "max_issues_repo_path": "dev/circle_approx.jl", "max_issues_repo_name": "anicusan/KonigCell", "max_issues_repo_head_hexsha": "6f55d06c9457dd0e601910f0cd4a7f95742ac009", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dev/circle_approx.jl", "max_forks_repo_name": "anicusan/KonigCell", "max_forks_repo_head_hexsha": "6f55d06c9457dd0e601910f0cd4a7f95742ac009", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.2, "max_line_length": 94, "alphanum_fraction": 0.6218553459, "num_tokens": 439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897509188344, "lm_q2_score": 0.8539127566694178, "lm_q1q2_score": 0.8033523696534368}} {"text": "# Load X and y variable\r\nusing JLD\r\ndata = load(\"quantum.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\nlambda = 1\r\n\r\n# Initialize\r\nmaxPasses = 10\r\nprogTol = 1e-4\r\nverbose = true\r\nw = zeros(d,1)\r\nlambda_i = lambda/n # Regularization for individual example in expectation\r\n\r\n# Start running stochastic gradient\r\nw_old = copy(w);\r\nfor k in 1:maxPasses*n\r\n\r\n # Choose example to update 'i'\r\n i = rand(1:n)\r\n\r\n # Compute gradient for example 'i'\r\n r_i = -y[i]/(1+exp(y[i]*dot(w,X[i,:])))\r\n g_i = r_i*X[i,:] + (lambda_i)*w\r\n\r\n # Choose the step-size\r\n alpha = 1/(lambda_i*k)\r\n\r\n # Take thes stochastic gradient step\r\n w -= alpha*g_i\r\n\r\n # Check for lack of progress after each \"pass\"\r\n if mod(k,n) == 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/n,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\nend\r\n", "meta": {"hexsha": "fabea559019d664168609415867b835b36feec04", "size": 1243, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "a2/example_SG.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_SG.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_SG.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.3673469388, "max_line_length": 82, "alphanum_fraction": 0.5607401448, "num_tokens": 371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897525789548, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.8033523675734481}} {"text": "#############################################################################\n# Copyright 2016, Iain Dunning, Joey Huchette, Miles Lubin, and contributors\n# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this\n# file, You can obtain one at http://mozilla.org/MPL/2.0/.\n#\n# Author: Louis Luangkesorn\n# Date: Jan 30, 2015\n#\n# Allocation of passenger cars to trains to minimize cars required or car-miles run.\n# Based on\n# Fourer, D.M. Gay and Brian W. Kernighan, A Modeling Language for Mathematical\n# Programming, http://www.ampl.com/REFS/amplmod.ps.gz\n# Appendix D\n#############################################################################\nusing JuMP\n\nORIG = [\"GARY\", \"CLEV\", \"PITT\"];\nDEST = [\"FRA\", \"DET\", \"LAN\", \"WIN\", \"STL\", \"FRE\", \"LAF\"];\n\nsupply = [1400 2600 2900];\ndemand = [ 900 1200 600 400 1700 1100 1000];\n\n@assert sum(supply) == sum(demand);\n\ncost = [\n39 14 11 14 16 82 8;\n27 9 12 9 26 95 17;\n24 14 17 13 28 99 20\n]\n\nm = Model();\n\n@variable(m, Trans[i=1:length(ORIG), j=1:length(DEST)] >= 0);\n\n\n@objective(m, Min, sum{cost[i,j] * Trans[i,j], i=1:length(ORIG), j=1:length(DEST)});\n\n@constraint(m, xyconstr[i=1:1:length(ORIG)], sum{Trans[i,j], j=1:length(DEST)} == supply[i]);\n\n@constraint(m, xyconstr[j = 1:length(DEST)], sum{Trans[i,j], i=1:length(ORIG)} == demand[j]);\n\nprintln(\"Solving original problem...\")\nstatus = solve(m);\n\nif status == :Optimal\n\t@printf(\"Optimal!\\n\");\n\t@printf(\"Objective value: %d\\n\", getobjectivevalue(m));\n\t@printf(\"Transpotation:\\n\");\n\tfor j = 1:length(DEST)\n\t\t@printf(\"\\t%s\", DEST[j]);\n\tend\n\t@printf(\"\\n\");\n\tfor i = 1:length(ORIG)\n\t\t@printf(\"%s\", ORIG[i]);\n\t\tfor j = 1:length(DEST)\n\t\t\t@printf(\"\\t%d\", getvalue(Trans[i,j]));\n\t\tend\n\t\t@printf(\"\\n\");\n\tend\nelse\n @printf(\"No solution\\n\");\nend\n", "meta": {"hexsha": "cdba6ce5ff1c88499a20ad11fe3a83f0d8cd767e", "size": 1869, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "public/.julia/v0.5/JuMP/examples/transp.jl", "max_stars_repo_name": "Giarcr0b/MVO_Tool", "max_stars_repo_head_hexsha": "8f3348b8b56968febca8307acea3ebe1817fccae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-03-12T03:24:25.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-12T03:24:25.000Z", "max_issues_repo_path": "public/.julia/v0.5/JuMP/examples/transp.jl", "max_issues_repo_name": "Giarcr0b/MVO_Tool", "max_issues_repo_head_hexsha": "8f3348b8b56968febca8307acea3ebe1817fccae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "public/.julia/v0.5/JuMP/examples/transp.jl", "max_forks_repo_name": "Giarcr0b/MVO_Tool", "max_forks_repo_head_hexsha": "8f3348b8b56968febca8307acea3ebe1817fccae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.203125, "max_line_length": 93, "alphanum_fraction": 0.5783841627, "num_tokens": 612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897459384731, "lm_q2_score": 0.8539127566694178, "lm_q1q2_score": 0.8033523654006428}} {"text": "# Interpolates the x, y points to estimate the value at the point \"t\".\n# val (out) ...... the estimated function value at the point \"t\".\n# t (in).......... the \"x\" value at which to estimate the value\n# X (array, in) .. the x-values of the points\n# Y (array, in) .. the y-values of the points\n# n (in) ......... the length of the arrays X and Y\n# REAL(8), INTENT(in) :: t\n# INTEGER, INTENT(in) :: n\n# REAL(8), INTENT(in) :: X(n), Y(n)\n# REAL(8), INTENT(out) :: val\n# REAL(8) :: f, denum\n# INTEGER :: i, j\nfunction lagrange_interp(X, Y, xx)\n N = size(X,1)\n retval = 0.0\n for j in 1:N\n f = 1.0\n den = 1.0\n for i in 1:N\n if i == j\n continue\n end\n f = f * ( xx - X[i] )\n den = den * ( X[j] - X[i] )\n end\n retval = retval + Y[j] * f/den\n end\n return retval\nend\n\n", "meta": {"hexsha": "bd9040e46f35528f2597a225ce48fbb7db095e87", "size": 866, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "dftatom/lagrange_interp.jl", "max_stars_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_stars_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2018-01-03T02:19:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-29T13:30:20.000Z", "max_issues_repo_path": "dftatom/lagrange_interp.jl", "max_issues_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_issues_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dftatom/lagrange_interp.jl", "max_forks_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_forks_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-03-23T06:58:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-03T00:54:28.000Z", "avg_line_length": 27.935483871, "max_line_length": 70, "alphanum_fraction": 0.5046189376, "num_tokens": 289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897459384732, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.8033523619030561}} {"text": "function matrix_construct(N::Int64, q::Complex{Float64}, alphas::Array{Float64, 1}; flag::String=\"False\", bc::String = \"Neumann\")\n l = ones(N);\n if bc == \"Neumann\"\n d = [4r^2 for r in 0:N]; # N+1 array\n if flag == \"True\" # This is Mathieu's canonical form. Or if first element is non-zero\n l[1] = sqrt(2) * l[1];\n end\n elseif bc == \"Dirichlet\"\n d = [4r^2 for r in 1:N+1]; # N+1 array\n else\n error(\"BC not recognized. Try `Neumann` or `Dirichlet`\")\n end\n A = spdiagm(0 => d);\n for i in 0:length(alphas[2:end])\n if alphas[i+1] != 0\n as = alphas[i+1]*l[1:N-i];\n A = A + spdiagm((i+1) => q.*as, -(i+1)=> q.*as);\n end\n end\n return A\nend\n\nfunction eigval_iterator(N::Int64, q::Array{Complex{Float64}, 1}, alphas::Array{Float64, 1}; flag::String=\"False\", bc::String=\"Neumann\")\n if q[1] == 0\n q[1] = 0.5*(q[1]+q[2]);\n end\n A = matrix_construct(N, q[1], alphas; flag, bc);\n l, = eigs(A, nev= N-1, which=:SM);\n l = round.(l, digits=2);\n I = sortperm(l, lt = (x,y) -> real(x)==real(y) ? imag(x) real(x)==real(y) ? imag(x) a[1, :], \"q\"=> q); # initialized Dict\n for n in 1:length(l)-1\n vals[var*string(2n+m)] = a[n+1, :];\n end\n return vals\nend\n", "meta": {"hexsha": "43800c3d71f5a057ef473deb0236a3cc3bfd5509", "size": 1829, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/eig_system.jl", "max_stars_repo_name": "Mikejmnez/HillsEigenvalues", "max_stars_repo_head_hexsha": "0de3c7e53e80778f61c4a584aef23a93b5475846", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/eig_system.jl", "max_issues_repo_name": "Mikejmnez/HillsEigenvalues", "max_issues_repo_head_hexsha": "0de3c7e53e80778f61c4a584aef23a93b5475846", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/eig_system.jl", "max_forks_repo_name": "Mikejmnez/HillsEigenvalues", "max_forks_repo_head_hexsha": "0de3c7e53e80778f61c4a584aef23a93b5475846", "max_forks_repo_licenses": ["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.1730769231, "max_line_length": 136, "alphanum_fraction": 0.5106615637, "num_tokens": 674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897459384731, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.803352361903056}} {"text": "using MultipleViewGeometry, MultipleViewGeometry.ModuleMove, LinearAlgebra, Test\n\n# Intrinsic and extrinsic parameters for the first camera.\n𝐊₁ = zeros(3,3)\n𝐊₁[1,1] = 10\n𝐊₁[2,2] = 10\n𝐊₁[3,3] = 1\n𝐑₁ = rotxyz(deg2rad(10), deg2rad(15), deg2rad(45))\n𝐭₁ = [-250.0, 0.0, 2500.0]\n\n# Intrinsic and extrinsic parameters for the second camera.\n𝐊₂ = zeros(3,3)\n𝐊₂[1,1] = 5\n𝐊₂[2,2] = 5\n𝐊₂[3,3] = 1\n𝐑₂ = rotxyz(deg2rad(10), deg2rad(15), deg2rad(45))\n𝐭₂ = [250.0, 0.0, 2500.0]\n\n𝐅 = construct(FundamentalMatrix(),𝐊₁,𝐑₁,𝐭₁,𝐊₂,𝐑₂,𝐭₂)\n𝐄 = construct(EssentialMatrix(),𝐅, 𝐊₁, 𝐊₂)\n\n# Result 9.17 of R. Hartley and A. Zisserman, “Two-View Geometry,” Multiple View Geometry in Computer Vision\n# A 3 by 3 matrix is an essential matrix if and only if two of its singular values\n# are equal, and the third is zero.\nU, S , V = svd(𝐄)\n\n@test isapprox.(S[1], S[2]; atol = 1e-14)\n@test isapprox.(S[3], 0.0; atol = 1e-10)\n", "meta": {"hexsha": "b6b54ca395b8bfff0b80b0527a99ab90d782c02f", "size": 894, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/construct_essentialmatrix_tests.jl", "max_stars_repo_name": "JuliaTagBot/MultipleViewGeometry.jl", "max_stars_repo_head_hexsha": "cafd7f61f30258f804ac31c5f9648b54edc6b347", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-29T18:45:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-29T18:45:09.000Z", "max_issues_repo_path": "test/construct_essentialmatrix_tests.jl", "max_issues_repo_name": "JuliaTagBot/MultipleViewGeometry.jl", "max_issues_repo_head_hexsha": "cafd7f61f30258f804ac31c5f9648b54edc6b347", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-03-17T16:03:51.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-18T09:13:22.000Z", "max_forks_repo_path": "test/construct_essentialmatrix_tests.jl", "max_forks_repo_name": "JuliaTagBot/MultipleViewGeometry.jl", "max_forks_repo_head_hexsha": "cafd7f61f30258f804ac31c5f9648b54edc6b347", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:18:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-27T20:13:09.000Z", "avg_line_length": 30.8275862069, "max_line_length": 108, "alphanum_fraction": 0.6823266219, "num_tokens": 418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897492587141, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.8033523612406654}} {"text": "using DifferentialEquations\r\nusing LinearAlgebra\r\nusing Plots\r\nusing ForwardDiff\r\nusing ProgressMeter\r\n\r\n# Thermal Model\r\n\r\nfunction generate1DStencil!(A, N, Δx)\r\n # Generate the centered difference matrix manually\r\n for i in 1:N, j in 1:N\r\n\r\n if abs(i-j)<=1\r\n (A[i,j]+=1)\r\n end\r\n if i==j\r\n (A[i,j]-=3)\r\n end\r\n\r\n end\r\n\r\n A = A/(Δx^2)\r\nend\r\n\r\nfunction double_partial(x)\r\n dx = zeros(size(x))\r\n for i in 2:length(dx)-1\r\n dx[i] = -1*x[i-1] + 2*x[i] + -1*x[i+1]\r\n end\r\n dx[1] = 2*x[1] + -1*x[2]\r\n dx[end] = -1*x[end-1] + 2*x[end]\r\n dx\r\nend\r\n\r\n# Discretize in time and space\r\nΔx = 1\r\nx = Δx:Δx:100-Δx # Solve only for the interior: the endpoints are known to be zero!\r\n\r\nΔt = 0.1\r\nt = Δt:Δt:1000-Δt # Solve only for the interior: the endpoints are known to be zero!\r\n\r\nN = length(x)\r\nA = zeros(N,N)\r\ngenerate1DStencil!(A, N, Δx)\r\n\r\n# f(u, p, t) = zeros(size(u)) \r\nf(u, p, t) = gen_forcing(p) \r\n# u0_func(x) = sin.(2π * x)\r\n\r\n# Given x coord of components, give initial conditions that are equiv to a gaussian around that coordinate\r\nfunction gen_forcing(positions)\r\n out_vec = zeros(size(x))\r\n out_vec = convert.(eltype(positions),out_vec)\r\n for pos in positions\r\n out_vec += gaussian.(x, pos, 5.0)\r\n # out_vec += box.(x, pos)\r\n end\r\n out_vec\r\nend\r\n\r\n\r\nfunction gaussian(x, mu, sig)\r\n return exp(-(x - mu)^2.0 / (2 * sig^2.0)) \r\nend\r\n\r\nfunction box(x, pos)\r\n sz = 5.0\r\n if pos-sz <= x <= pos+sz \r\n return 1.0\r\n else \r\n return 0.0\r\n end\r\nend\r\n\r\n\r\nfunction heat_eq(u, p, t)\r\n du = A * u + f(u,p,t)\r\n du \r\nend\r\n\r\n\r\n# Predict\r\nfunction predict(positions)\r\n # Simply roll this forward in time and we get our solution\r\n tspan = (0.0, 1.0)\r\n # tspan_dual = convert.(eltype(positions),tspan)\r\n # @show typeof(positions)\r\n # u₀ = gen_forcing(positions)\r\n u₀ = zeros(size(x))\r\n u_dual = convert.(eltype(positions),u₀)\r\n # @show typeof(u₀)\r\n prob = ODEProblem(heat_eq, u_dual, tspan, positions)\r\n sol = solve(prob)\r\n # @show typeof(sol[end])\r\n\r\n # display(\"Finished ODE Solve\")\r\n sol\r\nend\r\n\r\n\r\n# Loss: Given a list of positions, what is the cost / loss of the \r\nfunction loss(positions)\r\n simulation = predict(positions)\r\n # display(simulation)\r\n final_state = simulation[end]\r\n # display(size(final_state)[1])\r\n # display(final_state)\r\n return norm(final_state, 2)\r\nend\r\n\r\n\r\n# Gradient Descent: Optimize initial positions\r\nfunction optimize(positions, η=0.1; plt=false)\r\n \r\n @showprogress for idx in 1:1000\r\n grads = ForwardDiff.gradient(s -> loss(s), positions) # Magic\r\n positions .-= η*grads\r\n # display(positions)\r\n # display(loss(positions))\r\n\r\n if loss(positions) < 0.1\r\n break\r\n end\r\n\r\n if plt\r\n sol = predict(positions)\r\n plt_sol(sol)\r\n end\r\n end\r\n\r\n positions\r\nend\r\n\r\nfunction plot_loss_surf()\r\n loss_surf = zeros((90, 90))\r\n for x_1 in 5.0:94.0\r\n for x_2 in 5.0:94.0\r\n loss_surf[Int(x_1) - 4, Int(x_2) - 4] = loss([x_1, x_2])\r\n end\r\n end\r\n\r\n # sol_f(x, y) = loss_surf[x, y]\r\n plot(loss_surf, st=:heatmap, color=:viridis)\r\n\r\nend\r\n \r\n# optimize([25.0, 30.0])\r\n\r\nfunction plt_sol(sol)\r\n sol_f(t, x) = sol[t, x]\r\n display(plot(1:length(sol[end]), \r\n 1:length(sol.t), \r\n sol_f, \r\n st=:surface, \r\n color=:viridis,\r\n xlabel=\"Position\",\r\n ylabel=\"Time (sec)\",\r\n title=\"1D Temperature Over Time\"))\r\nend\r\n\r\nfunction plt_1D(sol)\r\n display(plot(sol[end]))\r\nend\r\n\r\nfunction plt_1D_w_pos(sol, positions)\r\n display(plot(sol[end], \r\n linewidth=5,\r\n xlabel=\"Position (meters)\",\r\n ylabel=\"Temperature\",\r\n label=\"Component positions at \" * first(string(positions[1]),4) * \" and \" * first(string(positions[2]),4)))\r\nend\r\n\r\nfunction optimize_and_save_thermal(positions, η=0.1)\r\n solns = []\r\n append!(solns, [deepcopy(positions)])\r\n @showprogress for idx in 1:1000\r\n grads = ForwardDiff.gradient(s -> loss(s), positions) # Magic\r\n positions .-= η*grads\r\n # display(positions)\r\n # display(loss(positions))\r\n\r\n if loss(positions) < 0.1\r\n break\r\n end\r\n\r\n if idx in [500,1000]\r\n append!(solns, [deepcopy(positions)])\r\n end\r\n end\r\n\r\n solns\r\nend\r\n\r\nfunction test_and_save_thermal()\r\n p = [25.0, 30.0]\r\n solns = optimize_and_save_thermal(p)\r\n display(plot())\r\n i = 1\r\n idxs = [1,500,1000]\r\n for pos in solns\r\n sol = predict(pos)\r\n plt_1D_w_pos(sol, pos)\r\n plot!(title=\"1D Thermal Optimizer: Iteration \" * string(idxs[i]), ylims = (0.0,2.0))\r\n savefig(\"plots/thermal_plot_\"*string(i))\r\n i += 1\r\n end\r\nend", "meta": {"hexsha": "af59bd9fdcaf253b3b18cedb76dcc413a2fa4909", "size": 4897, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "thermal_optimizer.jl", "max_stars_repo_name": "zzumbo/6.338-final-project", "max_stars_repo_head_hexsha": "696fdc095dc831abbe2c47b5a0186d95a9949e15", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thermal_optimizer.jl", "max_issues_repo_name": "zzumbo/6.338-final-project", "max_issues_repo_head_hexsha": "696fdc095dc831abbe2c47b5a0186d95a9949e15", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thermal_optimizer.jl", "max_forks_repo_name": "zzumbo/6.338-final-project", "max_forks_repo_head_hexsha": "696fdc095dc831abbe2c47b5a0186d95a9949e15", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.6570048309, "max_line_length": 125, "alphanum_fraction": 0.5617725138, "num_tokens": 1453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897492587142, "lm_q2_score": 0.8539127473751341, "lm_q1q2_score": 0.8033523594918721}} {"text": "# least squares penalty\n\n\"\"\"\n LeastSquares(A, b, λ=1.0)\n\nReturns the function `f(x) = (λ/2)⋅||Ax-b||^2`.\n\"\"\"\n\ntype LeastSquares{R <: RealOrComplex} <: ProximableFunction\n A::AbstractArray{R,2}\n b::AbstractArray{R,1}\n Atb::AbstractArray{R,1}\n lambda::Real\n gamma::Real\n S::AbstractArray{R,2}\n U::Union{LinAlg.Cholesky, SparseArrays.CHOLMOD.Factor}\n function LeastSquares(A::AbstractArray{R,2}, b::AbstractArray{R,1}, lambda::Real)\n if size(A, 1) != length(b)\n error(\"A and b have incompatible dimensions\")\n end\n if lambda <= 0\n error(\"lambda must be positive\")\n end\n if size(A,1) >= size(A,2)\n new(A, b, A'*b, lambda, -1, A'*A)\n else\n new(A, b, A'*b, lambda, -1, A*A')\n end\n end\nend\n\nLeastSquares{R <: RealOrComplex}(A::AbstractArray{R,2}, b::AbstractArray{R,1}, lambda::Real=1.0) =\n LeastSquares{R}(A, b, lambda)\n\nfunction (f::LeastSquares{R}){R <: RealOrComplex}(x::AbstractArray{R,1})\n return (f.lambda/2)*vecnorm(f.A*x - f.b, 2)^2\nend\n\nfunction factor_step!{R <: RealOrComplex}(f::LeastSquares{R}, gamma::Real)\n # factor step, two cases: (1) tall A, (2) fat A\n lamgam = f.lambda*gamma\n if issparse(f.A)\n f.U = cholfact(f.S; shift=1.0/lamgam)\n else\n f.U = cholfact(f.S + I/lamgam)\n end\n f.gamma = gamma\nend\n\nfunction prox!{R <: RealOrComplex}(f::LeastSquares{R}, x::AbstractArray{R,1}, y::AbstractArray{R,1}, gamma::Real=1.0)\n # if gamma different from f.gamma then call factor_step!\n if gamma != f.gamma\n factor_step!(f, gamma)\n end\n lamgam = f.lambda*gamma\n # solve step, two cases: (1) tall A, (2) fat A\n q = f.Atb + x/lamgam\n if size(f.A,1) >= size(f.A,2)\n y[:] = f.U\\q\n else\n y[:] = lamgam*(q - (f.A'*(f.U\\(f.A*q))))\n end\n return (f.lambda/2)*norm(f.A*y-f.b, 2)^2\nend\n\nfun_name(f::LeastSquares) = \"least-squares penalty\"\nfun_dom{R <: Real}(f::LeastSquares{R}) = \"AbstractArray{Real,1}\"\nfun_dom{C <: Complex}(f::LeastSquares{C}) = \"AbstractArray{Complex,1}\"\nfun_expr(f::LeastSquares) = \"x ↦ (λ/2)||A*x - b||^2\"\nfun_params(f::LeastSquares) = string(\"λ = $(f.lambda), A = \", typeof(f.A), \" of size \", size(f.A), \", b = \", typeof(f.b), \" of size \", size(f.b))\n\nfunction prox_naive{R <: RealOrComplex}(f::LeastSquares, x::AbstractArray{R,1}, gamma::Real=1.0)\n lamgam = f.lambda*gamma\n y = (f.A'*f.A + I/lamgam)\\(f.Atb + x/lamgam)\n fy = (f.lambda/2)*norm(f.A*y-f.b)^2\n return y, fy\nend\n", "meta": {"hexsha": "10870e487c74d91c8221d7bd3440c2fcd2131e1e", "size": 2375, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/leastSquares.jl", "max_stars_repo_name": "mfalt/ProximalOperators.jl", "max_stars_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functions/leastSquares.jl", "max_issues_repo_name": "mfalt/ProximalOperators.jl", "max_issues_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions/leastSquares.jl", "max_forks_repo_name": "mfalt/ProximalOperators.jl", "max_forks_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4487179487, "max_line_length": 145, "alphanum_fraction": 0.6235789474, "num_tokens": 890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509315, "lm_q2_score": 0.8633916064586998, "lm_q1q2_score": 0.8033498512837663}} {"text": "using Plots, LaTeXStrings, Statistics, JLD, BenchmarkTools, StatsBase, SpecialFunctions, ProgressMeter\n\nIntegral_answer=sqrt(π)/2 * erf(2)\n\nfunction SSMC(f :: Function, a :: Real, b :: Real, N :: Integer )\n f₍ₓ₎= f.((b-a).*rand(N) .+ a)\n ∫f₍ₓ₎dx= (b-a)*(mean(f₍ₓ₎))\n error=std(f₍ₓ₎)/sqrt(N)\n return ∫f₍ₓ₎dx, error\nend\n\nfunction ISMC(f :: Function, g :: Function, y :: Function, a :: Real, b :: Real, N :: Integer)\n drivation= x-> f(x)/g(x)\n samples= drivation.(y.(rand(N)))\n ∫g₍ₓ₎dx= 1-ℯ^(-2)\n ∫f₍ₓ₎dx= ∫g₍ₓ₎dx * mean(samples)\n error= ∫g₍ₓ₎dx * std(samples)/sqrt(N)\n return ∫f₍ₓ₎dx, error\nend\n\nnList=Integer.([10^n for n in 1:8])\nSSMC_res=[]\nprog= Progress(length(nList))\nn=0\nfor n in nList\n I, error=SSMC(x-> ℯ^(-x^2), 0, 2, n)\n bench = @benchmark SSMC(x->ℯ^(-x^2), 0, 2, n)\n push!(SSMC_res, (I, error, mean(bench).time, bench))\n next!(prog)\nend\nISMC_res=[]\nn=0\nprog= Progress(length(nList))\nfor n in nList\n I, error=ISMC(x->ℯ^(-x^2), x -> ℯ^(-x), x -> -log(1-(1-ℯ^(-2))*x), 0, 2, n)\n bench = @benchmark ISMC(x->ℯ^(-x^2), x -> ℯ^(-x), x -> -log(1-(1-ℯ^(-2))*x), 0, 2, n)\n push!(ISMC_res, (I, error, mean(bench).time, bench))\n next!(prog)\nend\nsave(\"../../chapter7/7.1/data.jld\",\"ISMC\", ISMC_res, \"SSMC\", SSMC_res, \"samples\", nList)\nAnswerList=[Integral_answer for i in 1: length(nList)]\nscatter(log.(nList), [getindex.(SSMC_res, 1) getindex.(ISMC_res, 1) AnswerList], markercolor=[:blue :purple :orange], label=nothing)\nplot!(log.(nList), [getindex.(SSMC_res, 1) getindex.(ISMC_res, 1) AnswerList], linecolor=[:blue :purple :orange],\n dpi=600,labels=[\"SSMC\" \"ISMC\" \"Absolute Result\"], ylabel=\"Integral\", xlabel=\"Number of Samples\",\n title=L\"Monte\\ Carlo\\ Results\\ for\\ I= \\int{}_{0}^{2}\\ e^{-x^2}\\ dx\" )\nsavefig(\"C:\\\\Users\\\\Narges\\\\Documents\\\\GitHub\\\\computational_physics\\\\chapter7\\\\7.1\\\\Figs\\\\ResultsPlot.png\")\nscatter(log.(nList), [getindex.(SSMC_res, 2) getindex.(ISMC_res, 2)], markercolor=[:blue :purple], label= nothing)\nplot!(log.(nList), [getindex.(SSMC_res, 2) getindex.(ISMC_res, 2)],\n labels=[\"SSMC\" \"ISMC\"], xlabel=\"Number of Samples\", ylabel=\" Error\", dpi=600, linecolor=[:blue :purple],\n title=L\"Monte\\ Carlo\\ Errors\\ of\\ the\\ Results\\ for\\ I= \\int{}_{0}^{2}\\ e^{-x^2}\\ dx\")\nsavefig(\"C:\\\\Users\\\\Narges\\\\Documents\\\\GitHub\\\\computational_physics\\\\chapter7\\\\7.1\\\\Figs\\\\ErrorPlot.png\")\n", "meta": {"hexsha": "6dec479917d3db31c8e6d46af144f1671d3386c8", "size": 2372, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "chapter7/7.1/7.1.jl", "max_stars_repo_name": "narges8k/computational_physics", "max_stars_repo_head_hexsha": "a24229aa7b31648735aab120cd667dffd788df1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapter7/7.1/7.1.jl", "max_issues_repo_name": "narges8k/computational_physics", "max_issues_repo_head_hexsha": "a24229aa7b31648735aab120cd667dffd788df1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter7/7.1/7.1.jl", "max_forks_repo_name": "narges8k/computational_physics", "max_forks_repo_head_hexsha": "a24229aa7b31648735aab120cd667dffd788df1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-13T09:55:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T09:55:00.000Z", "avg_line_length": 45.6153846154, "max_line_length": 132, "alphanum_fraction": 0.6235244519, "num_tokens": 932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941718, "lm_q2_score": 0.8633916064586998, "lm_q1q2_score": 0.8033498479538724}} {"text": "mutable struct MultivariateGaussianDist\n _mu::AbstractArray{Float64,1}\n _cov::AbstractArray{Float64,2}\n function MultivariateGaussianDist(dim::Int64)\n new(zeros(dim), Matrix{Float64}(I, dim, dim))\n end\nend\n\nfunction pdf(gaussian::MultivariateGaussianDist, x::AbstractArray{Float64,1})\n @assert size(x)[1] == size(gaussian._mu)[1]\n N = size(x)[1]\n d = x - gaussian._mu\n quadratics = transpose(d) * gaussian._cov * d\n @assert typeof(quadratics) == Float64\n return exp(-0.5 * quadratics) / sqrt(det(gaussian._cov)) / (2 * pi)^(0.5 * N)\nend\n\nfunction pdf(gaussian::MultivariateGaussianDist, X::AbstractArray{Float64,2})\n # X consists of list of samples [x_1, x_2, ,,, x_(n_samples)], and x_i is a vertical vector\n @assert size(X)[1] == size(gaussian._mu)[1]\n N = size(X)[1]\n n_samples = size(X)[2]\n # In Julia lang, 1-D AbstractArray is vertical vector\n d = X .- gaussian._mu\n #quadratics = diag(transpose(d) * gaussian._cov * d);\n quadratics = [transpose(d[:, i]) * gaussian._cov * d[:, i] for i = 1:n_samples]\n @assert ndims(quadratics) == 1 && size(quadratics)[1] == n_samples\n return exp.(-0.5 * quadratics) / sqrt(det(gaussian._cov)) / (2 * pi)^(0.5 * N)\nend\n\nfunction fitting(gaussian::MultivariateGaussianDist, X::AbstractArray{Float64,1})\n gaussian._mu = X\n gaussian._cov = cov(X, corrected = true)\nend\n\nfunction fitting(gaussian::MultivariateGaussianDist, X::AbstractArray{Float64,2})\n # X consists of the list of samples [x_1, x_2, ,,, x_(n_samples)]\n @assert size(X)[1] == size(gaussian._mu)[1]\n n_samples = size(X)[2]\n N = size(X)[1]\n gaussian._mu = collect(reshape(mean(X, dims = 2), N))\n gaussian._cov = cov(X, dims = 2, corrected = true)\nend\n", "meta": {"hexsha": "888781d87c42c2cfc86658dc6eefa032159c83f6", "size": 1744, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distribution/multivariate_gaussian.jl", "max_stars_repo_name": "soblin/prml-julia", "max_stars_repo_head_hexsha": "cba8cec55c95d883c656125b12c40624430c059d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-07-10T21:46:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T04:40:22.000Z", "max_issues_repo_path": "src/distribution/multivariate_gaussian.jl", "max_issues_repo_name": "soblin/prml-julia", "max_issues_repo_head_hexsha": "cba8cec55c95d883c656125b12c40624430c059d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/distribution/multivariate_gaussian.jl", "max_forks_repo_name": "soblin/prml-julia", "max_forks_repo_head_hexsha": "cba8cec55c95d883c656125b12c40624430c059d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.6363636364, "max_line_length": 95, "alphanum_fraction": 0.6599770642, "num_tokens": 556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810496235896, "lm_q2_score": 0.8479677622198946, "lm_q1q2_score": 0.8033485886188502}} {"text": "function AmericanSpreadCallBinomial(K, T, S1, S2, sig1, sig2, div1, div2, rho, r, N)\n\n\n dt = T/N ## Time to Maturity/ Number of Steps\n nu1 = r - div1 - 0.5 * sig1^2\n nu2 = r - div2 - 0.5 * sig2^2\n\n\n dx1 = sig1 * sqrt(dt)\n dx2 = sig2 * sqrt(dt)\n\n disc = exp(-r * dt)\n\n puu = (dx1 * dx2 + (dx2 * nu1 + dx1 * nu2 + rho * sig1 * sig2) * dt) / (4 * dx1 * dx2) * disc\n\n pud = (dx1 * dx2 + (dx2 * nu1 - dx1 * nu2 - rho * sig1 * sig2) * dt) / (4 * dx1 * dx2) * disc\n\n pdu = (dx1 * dx2 + (-dx2 * nu1 + dx1 * nu2 - rho * sig1 * sig2) * dt) / (4 * dx1 * dx2) * disc\n\n pdd = (dx1 * dx2 + (-dx2 * nu1 - dx1 * nu2 + rho * sig1 * sig2) * dt) / (4 * dx1 * dx2) * disc\n\n\n edx1 = exp(dx1)\n edx2 = exp(dx2)\n\n\n\n S1t = linspace(-N, N, 2N+1)\n S2t = linspace(-N, N, 2N+1)\n\n S1t[1] = S1 * exp(-N * dx1)\n S2t[1] = S2 * exp(-N * dx2)\n\n\n\n for j in 2:length(-N:N)\n S1t[j] = S1t[j-1] * edx1\n S2t[j] = S2t[j-1] * edx2\n end\n\n C = Array(Float64, (2N+1,2N+1))\n\n for j = 1:2:length(-N:N)\n for k = 1:2:length(-N:N)\n C[k, j] = max(0.0, S1t[j] - S2t[k] - K)\n end\n end\n\n for i in range(N-1, -1, N)\n for j in range(-i, 2, i+1) # potentially this is i^2\n for k in range(-i, 2, i+1) # potentiall this is i^2 as well\n C[k+(N+1), j+(N+1)] = pdd * C[k+(N+1)-1, j+(N+1)-1] + pud * C[k+(N+1)-1, j+(N+1)+1] + pdu * C[k+(N+1)+1, j+(N+1)-1] + puu * C[k+(N+1)+1, j+(N+1)+1]\n C[k+(N+1), j+(N+1)] = max(C[k+(N+1), j+(N+1)], S1t[j+(N+1)] - S2t[k+(N+1)] - K)\n end\n end\n end\n\n C[N+1, N+1]\n\nend\n", "meta": {"hexsha": "2e1e7cfe3c10557cf8b913140ddc07f8bcefadcf", "size": 1510, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/IB/PricingEngines/AmericanSpreadCallBinomial.jl", "max_stars_repo_name": "SvenDuve/JuliaAOT.jl", "max_stars_repo_head_hexsha": "005c86538df418eb3bc9a37c68482019bdf6683a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/IB/PricingEngines/AmericanSpreadCallBinomial.jl", "max_issues_repo_name": "SvenDuve/JuliaAOT.jl", "max_issues_repo_head_hexsha": "005c86538df418eb3bc9a37c68482019bdf6683a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/IB/PricingEngines/AmericanSpreadCallBinomial.jl", "max_forks_repo_name": "SvenDuve/JuliaAOT.jl", "max_forks_repo_head_hexsha": "005c86538df418eb3bc9a37c68482019bdf6683a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-12-27T15:45:30.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-27T15:45:30.000Z", "avg_line_length": 24.7540983607, "max_line_length": 155, "alphanum_fraction": 0.4768211921, "num_tokens": 750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338046748207, "lm_q2_score": 0.8354835330070838, "lm_q1q2_score": 0.8033456602354625}} {"text": "using StatsBase, Distributions, Plots\n\nfunction rouletteSpins(r,p)\n x = 0\n wins = 0\n while true\n x += 1\n if rand() < p\n wins += 1\n if wins == r\n return x\n end\n end\n end\nend\n\nr, p, N = 5, 18/37,10^6\nxGrid = r:r+15\n\nmcEstimate = counts([rouletteSpins(r,p) for _ in 1:N],xGrid)/N\n\nnbDist = NegativeBinomial(r,p)\nnbPmf = [pdf(nbDist,x-r) for x in xGrid]\n\nplot( xGrid, mcEstimate, \n\tline=:stem, marker=:circle, c=:blue, \n\tms=10, msw=0, lw=4, label=\"MC estimate\")\nplot!( xGrid, nbPmf, line=:stem, \n\t marker=:xcross, c=:red, ms=6, msw=0, lw=2, label=\"PMF\", \n\t xlims=(0,maximum(xGrid)), ylims=(0,0.2), \n\t xlabel=\"x\", ylabel=\"Probability\")", "meta": {"hexsha": "dd5ef4df9974def2154a186375a90d24121e725b", "size": 711, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "3_chapter/negativeBinomial.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "3_chapter/negativeBinomial.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "3_chapter/negativeBinomial.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": 22.935483871, "max_line_length": 62, "alphanum_fraction": 0.5668073136, "num_tokens": 262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062237, "lm_q2_score": 0.8615382129861583, "lm_q1q2_score": 0.803344154174253}} {"text": "using LinearAlgebra\nusing ForwardDiff\nusing Plots\nusing Distributions\n\n# Bundled Gradients through Contact via Randomized Smoothing\n\nfunction gd(x0; iters=1000, verbose=true, visualize=true)\n x = copy(x0)\n α = 0.001\n\n for i = 1:iters\n grad = ∇f(x)\n x -= α * grad\n end\n\n if verbose\n println(\"grad. norm: \", norm(∇f(x)))\n end\n\n if visualize\n x_range = range(-1.0, stop = 1.0, length = 1000)\n plt = plot(x_range, f.(x_range), label=\"\", color=:black, width=2.0)\n plt = scatter!([x0,], [f(x0),], color=:red, label=\"\")\n plt = scatter!([x,], [f(x),], color=:green, label=\"\")\n display(plt)\n end\n\n return x\nend\n\nfunction gd(x0; iters=1000, verbose=true, visualize=true,\n mode=:gradient,\n μ=0.0, σ=[0.001], σ_schedule=1000, N=100,\n xmin=-1.0, xmax=1.0)\n x = copy(x0)\n α = 0.001\n\n for s in σ\n dist = Normal(μ, s)\n for i = 1:iters\n if mode == :gradient\n grad = ∇f(x)\n elseif mode == :smooth_gradient\n grad = sum([∇f(x + rand(dist, 1)[1]) for j = 1:N]) / N\n elseif mode == :zero_order_gradient\n fj = []\n for j = 1:N\n ϵ = rand(dist, 1)[1]\n # push!(fj, (f(x + ϵ) - f(x)) / (1.0 * ϵ))\n push!(fj, (f(x + ϵ) - f(x - ϵ)) / (2.0 * ϵ))\n grad = sum(fj) / N\n end\n else\n nothing\n end\n x -= α * grad\n end\n end\n\n if verbose\n println(\"grad. norm: \", norm(∇f(x)))\n end\n\n if visualize\n x_range = range(xmin, stop = xmax, length = 1000)\n plt = plot(x_range, f.(x_range), label=\"\", color=:black, width=2.0)\n for s in σ\n dist = Normal(μ, s)\n if mode != :gradient\n plt = plot!(x_range, [sum([f(xt + rand(dist, 1)[1]) for j = 1:1000]) / 1000 for xt in x_range],\n label=\"σ=$s\", width=1.0, legend=:top)\n end\n end\n plt = scatter!([x0,], [f(x0),], color=:red, label=\"\")\n plt = scatter!([x,], [f(x),], color=:green, label=\"\")\n display(plt)\n end\n\n return x\nend\n\n# example 1\nf(x) = x^2.0 + 0.1 * sin(20.0 * x)\n∇f(x) = 2.0 * x + 2.0 * cos(20.0 * x)\n\n# initial point\nx0 = -0.75\n\n# gradient descent\nx_sol = gd(x0, iters=1000,\n σ=[0.5, 0.25, 0.1, 0.01, 0.001],\n mode=:smooth_gradient)\n\n# example 2\nfunction f(x)\n if x >= 0.0\n return 1.0\n else\n return 0.0\n end\nend\n∇f(x) = 0.0\n\n# initial point\nx0 = 1.0\n\n# gradient descent\nx_sol = gd(x0, iters=10000,\n σ=[1.0, 0.5, 0.1],#, 0.25, 0.1, 0.01, 0.001],#, 0.075, 0.05, 0.01],\n N = 100,\n mode=:zero_order_gradient,\n xmin=-2.0, xmax=2.0)\n\n# example 3\nfunction f(x)\n if x >= 0.0\n return -1.0 + x\n else\n return 1.0 - x\n end\nend\nfunction ∇f(x)\n if x >= 0.0\n return 1.0\n else\n return -1.0\n end\nend\n\nx0 = 2.0\nx_sol = gd(x0, iters=1000,\n σ=[1.0, 0.5, 0.1],#, 0.25, 0.1, 0.01, 0.001],#, 0.075, 0.05, 0.01],\n N = 100,\n mode=:zero_order_gradient,\n xmin=-2.0, xmax=2.0)\n", "meta": {"hexsha": "035e56191a4f257cda7b97f71e5d814644dbbff7", "size": 3221, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/development/zero_order.jl", "max_stars_repo_name": "thowell/motion_planning", "max_stars_repo_head_hexsha": "d42d80e705c1e64e45f5872917b96c6a980398cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 35, "max_stars_repo_stars_event_min_datetime": "2021-02-07T10:46:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:30:20.000Z", "max_issues_repo_path": "examples/development/zero_order.jl", "max_issues_repo_name": "thowell/DirectMotionPlanning", "max_issues_repo_head_hexsha": "d42d80e705c1e64e45f5872917b96c6a980398cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-10-07T05:36:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-11T17:16:28.000Z", "max_forks_repo_path": "examples/development/zero_order.jl", "max_forks_repo_name": "thowell/motion_planning", "max_forks_repo_head_hexsha": "d42d80e705c1e64e45f5872917b96c6a980398cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2021-01-25T19:23:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T06:43:01.000Z", "avg_line_length": 23.5109489051, "max_line_length": 112, "alphanum_fraction": 0.4684880472, "num_tokens": 1162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533069832974, "lm_q2_score": 0.861538211208597, "lm_q1q2_score": 0.8033441541339308}} {"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", "meta": {"hexsha": "5d95f92cd221cda8f1387144bc6be8e0ccea0bdf", "size": 271, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nmlib/subbac.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/NumericalMethodsforEngineers.jl-00e1d38a-71a9-5665-8612-32ae585a75a3", "max_stars_repo_head_hexsha": "e230c3045d98da0cf789e4a6acdccfbfb21ef49e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-01-02T01:16:31.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-02T01:16:31.000Z", "max_issues_repo_path": "src/nmlib/subbac.jl", "max_issues_repo_name": "OVGULIU/NumericalMethodsforEngineers.jl", "max_issues_repo_head_hexsha": "7ca0b79965a7abd58af29d8dfd1870a954fb3aec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/nmlib/subbac.jl", "max_forks_repo_name": "OVGULIU/NumericalMethodsforEngineers.jl", "max_forks_repo_head_hexsha": "7ca0b79965a7abd58af29d8dfd1870a954fb3aec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.3571428571, "max_line_length": 56, "alphanum_fraction": 0.5276752768, "num_tokens": 102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342024724487, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.8033182306162687}} {"text": "using LinearAlgebra\nusing SparseArrays\nusing Plots\n\n\"This code solves the 2D Laplace's equation with nonzero Dirichlet and Neumann\nboundary conditions using a finite difference method.\"\n\nm = 50 # number of points\nx = LinRange(-1,1,m+2)\ny = LinRange(-1,1,m+2)\nxint = x[2:end-1]\nyint = y[2:end-1]\nh = x[2]-x[1]\n\nT = 2.0 # final time\ndt = .01 # timestep\n\nid(i,j,m) = i + (j-1)*m # return global index from i,j\nfunction 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\nend\n\nA = FD_matrix_2D(h,m)\n\n# initial condition\nu0(x,y) = exp(-100*(x^2+y^2))\nu0(x,y) = 0.0\n\n# forcing\nf(x,y,t) = exp(-25*((x-.25)^2 + (y-.75)^2))*exp(2*t)*(t < 1.5)\n# f(x,y,t) = 0.0\n\nF(t) = vec(f.(xint,yint',t)) # zero Dirichlet BCs\nu = vec(u0.(xint,yint'))\ninterval = 1\nNsteps = ceil(Int,T / dt)\ndt = T/Nsteps\n\nBsparse = (I + .5*dt*A)\n#B = cholesky(I + .5*dt*A)\nB = lu(I + .5*dt*A)\n\nplot()\n@gif for i = 1:Nsteps\n t = i*dt\n Favg = .5*(F(t) + F(t+dt))\n u .= B\\(u + .5*dt*(Favg-A*u))\n if i%interval==0\n println(\"on timestep $i / $Nsteps\")\n contourf(xint,yint,u,clims=(0,.5)) #vec(reshape(u,m,m)'))\n end\nend every interval\n", "meta": {"hexsha": "9507ee61dcedacc119ba1b91afa6cf34de3ff3a7", "size": 1613, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "week5/fd_heat_2D.jl", "max_stars_repo_name": "jlchan/caam452_s21", "max_stars_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-01-29T01:52:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T15:38:43.000Z", "max_issues_repo_path": "week5/fd_heat_2D.jl", "max_issues_repo_name": "jlchan/caam452_s21", "max_issues_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week5/fd_heat_2D.jl", "max_forks_repo_name": "jlchan/caam452_s21", "max_forks_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3768115942, "max_line_length": 78, "alphanum_fraction": 0.5375077495, "num_tokens": 637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632329799585, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.8032727224820487}} {"text": "# 1D Non-Linear Diffusion tests\n# See doi:10.1016/j.camwa.2006.12.077\n\n# TODO: Add more complex tests.\n\n# Packages and inclusions\nusing ModelingToolkit,DiffEqOperators,LinearAlgebra,Test,OrdinaryDiffEq, DomainSets\nusing ModelingToolkit: Differential\n# Tests\n@testset \"Test 00: Dt(u(t,x)) ~ Dx(u(t,x)^(-1) * Dx(u(t,x)))\" begin \n # Variables, parameters, and derivatives\n @parameters t x\n @variables u(..)\n Dx = Differential(x)\n Dt = Differential(t)\n t_min= 0.\n t_max = 2.\n x_min = 0.\n x_max = 2.\n c = 1.0\n a = 1.0\n\n # Analytic solution\n analytic_sol_func(t,x) = 2.0 * (c + t) / (a + x)^2\n \n # Equation\n eq = Dt(u(t,x)) ~ Dx(u(t,x)^(-1) * Dx(u(t,x)))\n\n # Initial and boundary conditions\n bcs = [u(t_min,x) ~ analytic_sol_func(t_min,x),\n u(t,x_min) ~ analytic_sol_func(t,x_min),\n u(t,x_max) ~ analytic_sol_func(t,x_max)]\n\n # Space and time domains\n domains = [t ∈ Interval(t_min,t_max),\n x ∈ Interval(x_min,x_max)]\n\n # PDE system\n @named pdesys = PDESystem([eq],bcs,domains,[t,x],[u(t,x)])\n\n # Method of lines discretization\n dx = 0.01\n discretization = MOLFiniteDifference([x=>dx],t)\n prob = ModelingToolkit.discretize(pdesys,discretization)\n\n # Solution of the ODE system\n using OrdinaryDiffEq\n sol = solve(prob,Rosenbrock32())\n\n # Test against exact solution\n r_space = x_min:dx:x_max\n asf = [analytic_sol_func(t_max,x) for x in r_space]\n Nx = floor(Int64, (x_max - x_min) / dx) + 1\n @variables u[1:Nx](t)\n sol′ = [sol[u[i]][end] for i in 1:Nx]\n @test asf ≈ sol′ atol=0.1\n\n # Plots\n #using Plots\n #plot(r_space, asf, seriestype = :scatter,label=\"analytic solution\")\n #plot!(r_space, sol′, label=\"numeric solution\")\n #savefig(\"MOL_NonLinear_Diffusion_1D_Test00.png\")\n\nend\n\n@testset \"Test 01: Dt(u(t,x)) ~ Dx(u(t,x)^2 * Dx(u(t,x)))\" begin\n\n # Variables, parameters, and derivatives\n @parameters t x\n @variables u(..)\n Dx = Differential(x)\n Dt = Differential(t)\n t_min= 0.\n t_max = 2.\n x_min = 0.\n x_max = 2.\n c = 50.0\n h = 0.50\n\n # Analytic solution\n analytic_sol_func(t,x) = 0.5 * (x + h) / sqrt(c - t)\n \n # Equation\n eq = Dt(u(t,x)) ~ Dx(u(t,x)^2 * Dx(u(t,x)))\n\n # Initial and boundary conditions\n bcs = [u(t_min,x) ~ analytic_sol_func(t_min,x),\n u(t,x_min) ~ analytic_sol_func(t,x_min),\n u(t,x_max) ~ analytic_sol_func(t,x_max)]\n\n # Space and time domains\n domains = [t ∈ Interval(t_min,t_max),\n x ∈ Interval(x_min,x_max)]\n\n # PDE system\n @named pdesys = PDESystem([eq],bcs,domains,[t,x],[u(t,x)])\n\n # Method of lines discretization\n dx = 0.01\n discretization = MOLFiniteDifference([x=>dx],t)\n prob = ModelingToolkit.discretize(pdesys,discretization)\n\n # Solution of the ODE system\n using OrdinaryDiffEq\n sol = solve(prob,Rosenbrock32())\n\n # Test against exact solution\n r_space = x_min:dx:x_max\n asf = [analytic_sol_func(t_max,x) for x in r_space]\n Nx = floor(Int64, (x_max - x_min) / dx) + 1\n @variables u[1:Nx](t)\n sol′ = [sol[u[i]][end] for i in 1:Nx]\n @test asf ≈ sol′ atol=0.01\n\n # Plots\n #using Plots\n #plot(r_space, asf, seriestype = :scatter,label=\"analytic solution\")\n #plot!(r_space, sol′, label=\"numeric solution\")\n #savefig(\"MOL_NonLinear_Diffusion_1D_Test01.png\")\n\nend\n\n\n@testset \"Test 02: Dt(u(t,x)) ~ Dx(1. / (1. + u(t,x)^2) * Dx(u(t,x)))\" begin\n\n # Variables, parameters, and derivatives\n @parameters t x\n @variables u(..)\n Dx = Differential(x)\n Dt = Differential(t)\n t_min= 0.\n t_max = 2.\n x_min = 0.\n x_max = 2.\n\n # Analytic solution\n analytic_sol_func(t,x) = tan(x)\n\n # Equation\n eq = Dt(u(t,x)) ~ Dx(1. / (1. + u(t,x)^2) * Dx(u(t,x)))\n\n # Initial and boundary conditions\n bcs = [u(t_min,x) ~ analytic_sol_func(t_min,x),\n u(t,x_min) ~ analytic_sol_func(t,x_min),\n u(t,x_max) ~ analytic_sol_func(t,x_max)]\n\n # Space and time domains\n domains = [t ∈ Interval(t_min,t_max),\n x ∈ Interval(x_min,x_max)]\n\n # PDE system\n @named pdesys = PDESystem([eq],bcs,domains,[t,x],[u(t,x)])\n\n # Method of lines discretization\n dx = 0.01\n discretization = MOLFiniteDifference([x=>dx],t)\n prob = ModelingToolkit.discretize(pdesys,discretization)\n\n # Solution of the ODE system\n using OrdinaryDiffEq\n sol = solve(prob,Rosenbrock32()) # TODO: check warnings\n\n # Test against exact solution\n r_space = x_min:dx:x_max\n asf = [analytic_sol_func(t_max,x) for x in r_space]\n Nx = floor(Int64, (x_max - x_min) / dx) + 1\n @variables u[1:Nx](t)\n sol′ = [sol[u[i]][end] for i in 1:Nx]\n\n m = max(asf...,sol′...)\n @test asf / m ≈ sol′ / m atol=0.16 # the difference occurs when tan(x) goes to infinite\n\n # Plots\n #using Plots\n #plot(r_space, asf, seriestype = :scatter,label=\"Analytic solution\")\n #plot!(r_space, sol′, label=\"Numeric solution\")\n #savefig(\"MOL_NonLinear_Diffusion_1D_Test02.png\")\n\nend\n\n@testset \"Test 03: Dt(u(t,x)) ~ Dx(1. / (u(t,x)^2 - 1.) * Dx(u(t,x)))\" begin\n\n # Variables, parameters, and derivatives\n @parameters t x\n @variables u(..)\n Dx = Differential(x)\n Dt = Differential(t)\n t_min= 0.\n t_max = 2.\n x_min = 0.\n x_max = 2.\n\n # Analytic solution\n analytic_sol_func(t,x) = -coth(x)\n\n # Equation\n eq = Dt(u(t,x)) ~ Dx(1. / (u(t,x)^2 - 1.) * Dx(u(t,x)))\n\n # Initial and boundary conditions\n bcs = [u(t_min,x) ~ analytic_sol_func(t_min,x),\n u(t,x_min) ~ analytic_sol_func(t,x_min),\n u(t,x_max) ~ analytic_sol_func(t,x_max)]\n\n # Space and time domains\n domains = [t ∈ Interval(t_min,t_max),\n x ∈ Interval(x_min,x_max)]\n\n # PDE system\n @named pdesys = PDESystem([eq],bcs,domains,[t,x],[u(t,x)])\n\n # Method of lines discretization\n dx = 0.01\n discretization = MOLFiniteDifference([x=>dx],t)\n prob = ModelingToolkit.discretize(pdesys,discretization)\n\n # Solution of the ODE system\n using OrdinaryDiffEq\n sol = solve(prob,Rosenbrock32())\n\n # Test against exact solution\n r_space = x_min:dx:x_max\n asf = [analytic_sol_func(t_max,x) for x in r_space]\n Nx = floor(Int64, (x_max - x_min) / dx) + 1\n @variables u[1:Nx](t)\n sol′ = [sol[u[i]][end] for i in 1:Nx]\n\n m = max(asf...,sol′...)\n @test asf / m ≈ sol′ / m atol=0.16\n\n # Plots\n #using Plots\n #plot(r_space, asf, seriestype = :scatter,label=\"Analytic solution\")\n #plot!(r_space, sol′, label=\"Numeric solution\")\n #savefig(\"MOL_NonLinear_Diffusion_1D_Test03.png\")\n\nend\n", "meta": {"hexsha": "65926a5fbea3ec6d144b3501c4564ecbea639e38", "size": 6637, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/MOL/MOL_1D_NonLinear_Diffusion.jl", "max_stars_repo_name": "QiyaoWei/DiffEqOperators.jl", "max_stars_repo_head_hexsha": "4b1882556fb5c2bcb2994543452e765761d33de7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 194, "max_stars_repo_stars_event_min_datetime": "2020-04-03T15:12:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T03:25:55.000Z", "max_issues_repo_path": "test/MOL/MOL_1D_NonLinear_Diffusion.jl", "max_issues_repo_name": "QiyaoWei/DiffEqOperators.jl", "max_issues_repo_head_hexsha": "4b1882556fb5c2bcb2994543452e765761d33de7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 181, "max_issues_repo_issues_event_min_datetime": "2020-04-01T17:55:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T11:16:19.000Z", "max_forks_repo_path": "test/MOL/MOL_1D_NonLinear_Diffusion.jl", "max_forks_repo_name": "QiyaoWei/DiffEqOperators.jl", "max_forks_repo_head_hexsha": "4b1882556fb5c2bcb2994543452e765761d33de7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 48, "max_forks_repo_forks_event_min_datetime": "2020-04-10T04:44:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T10:56:09.000Z", "avg_line_length": 28.0042194093, "max_line_length": 91, "alphanum_fraction": 0.6072020491, "num_tokens": 2175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951863227517834, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.8032727197411168}} {"text": "\n\"\"\"\n```julia\nrandDiagonal(d, n) \n\nrandDiagonal(n) \n```\n- `d` : default `Normal(0,1)`, entry distribution\n- `n` : dimension\n\n# Examples\n\nGenerates a 3 by 3 diagonal matrix, with non-zero elements from `Normal(0,1)`\n```julia\nrandDiagonal(3)\n\n3×3 Diagonal{Float64, Vector{Float64}}:\n 0.440359 ⋅ ⋅\n ⋅ 1.94832 ⋅\n ⋅ ⋅ -0.52536\n```\n\nGenerates a 5 by 5 diagonal matrix, with non-zero elements from `Poisson(2)`\n```julia\nrandDiagonal(Poisson(2),5)\n\n5×5 Diagonal{Int64, Vector{Int64}}:\n 1 ⋅ ⋅ ⋅ ⋅\n ⋅ 0 ⋅ ⋅ ⋅\n ⋅ ⋅ 0 ⋅ ⋅\n ⋅ ⋅ ⋅ 3 ⋅\n ⋅ ⋅ ⋅ ⋅ 3\n```\n\"\"\"\nfunction randDiagonal(d::D, n::Int) where D<:S\n Diagonal(rand(d,n))\nend\n\nrandDiagonal(n::Int) = randDiagonal(Normal(), n::Int)\n\n\n\"\"\"\n```julia \nrandTriangular(d , n ; diag , Diag, upper ) \n\nrandTriangular(n;diag, upper)\n```\n- `d` : entry distribution\n- `n` : dimension\n- `diag` : default `diag = d`, diagonal entry distribution\n- `Diag` : default `Diag = true`, `true` includes diagonal, `false` with diagonal entries 0\n- `upper` : default `upper = true`, `true` gives upper triangular, `false` gives lower triangular\n\n# Examples \nGenerate an upper triangular matrix with entries Standard Normal\n```julia\nrandTriangular(3)\n\n3×3 UpperTriangular{Float64, Matrix{Float64}}:\n -0.572757 -0.459518 -1.60622\n ⋅ 0.0216834 -0.416529\n ⋅ ⋅ -1.00807\n```\n\nGenerate a 3 by 3 strictly lower triangular matrix, with nonzero entries uniform from ``\\\\{1,2,3\\\\}`` \n```julia\nrandTriangular(1:3,3,upper=false,Diag=false)\n\n3×3 LowerTriangular{Int64, Transpose{Int64, Matrix{Int64}}}: \n 0 ⋅ ⋅\n 3 0 ⋅\n 3 2 0\n```\n\"\"\"\nfunction randTriangular(d::D, n::Int; diag=d::D, Diag=true, upper = true) where D<:S\n M = UpperTriangular(zeros(eltype(d),n,n)) \n for i in 1:n, j in i+1:n\n M[i,j] = rand(d)\n end\n if Diag\n M += randDiagonal(diag,n)\n end\n\n if !upper\n M = transpose(M)\n end\n M\nend\nrandTriangular(n::Int; Diag=true, upper = true) = randTriangular(Normal(),n,Diag=Diag,upper=upper)\n\n\n\"\"\"\n```julia\nrandMatrix(d::D, n::Int, m = n::Int; norm = false::Bool) where D<:S\n\nrandMatrix(n::Int, m = n::Int; norm = false::Bool)\n```\n- `d` : entry distribution\n- `n`,`m` : default `m = n` , dimensions\n- `norm` : default `false`, if `norm` set to `true`, then the matrix will be normlaized with ``\\\\operatorname{min}(n,m)^{-1/2}``. \n# Examples\nGenerates a 2 by 2 random matrix with entries from the Standard Gaussian.\n```julia\nrandMatrix(2)\n\n2×2 Matrix{Float64}:\n 1.74043 -1.30317\n 0.72765 0.639943\n```\n\nGenerates a 3 by 2 random matrix with entries uniformly from {1,2,3,...,10}.\n```julia\nrandMatrix(1:10,3,2)\n\n3×2 Matrix{Int64}:\n 1 3\n 6 4\n 10 1\n```\nGenerate a normalized random 2 by 2 Matrix with entries `Poisson(2)` rvs. \nNeed to import the `Distributions` package for `Poisson(2)`\n```julia\nusing Distributions\nrandMatrix(Poisson(2),2,norm = true)\n\n2×2 Matrix{Float64}:\n 1.41421 0.0\n 0.707107 1.41421\n``` \n\"\"\"\nfunction randMatrix(d::D, n::Int, m = n::Int ; norm = false::Bool) where D<:S\n \n M = rand(d,n,m)\n\n if norm \n M/=sqrt(min(n,m)) \n end\n \n return M\nend\n\nfunction randMatrix(n::Int, m = n::Int; norm = false::Bool)\n return randMatrix(Normal(), n,m ; norm = norm)\nend", "meta": {"hexsha": "eae9ed11206b72be684b5caac28665c8b3b67669", "size": 3266, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/MatrixModels/IID Matrices.jl", "max_stars_repo_name": "weiyang2048/RandomMatrix.jl", "max_stars_repo_head_hexsha": "d112a17d928c84583759177849a76eae1942e947", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-04-27T04:28:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T17:21:23.000Z", "max_issues_repo_path": "src/MatrixModels/IID Matrices.jl", "max_issues_repo_name": "weiyang607/RandomMatrix.jl", "max_issues_repo_head_hexsha": "d112a17d928c84583759177849a76eae1942e947", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2021-04-13T02:48:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-19T22:13:44.000Z", "max_forks_repo_path": "src/MatrixModels/IID Matrices.jl", "max_forks_repo_name": "weiyang607/RandomMatrix.jl", "max_forks_repo_head_hexsha": "d112a17d928c84583759177849a76eae1942e947", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6805555556, "max_line_length": 131, "alphanum_fraction": 0.6160440906, "num_tokens": 1252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137296, "lm_q2_score": 0.8791467722591729, "lm_q1q2_score": 0.803255766448163}} {"text": "export bfgs\n\n\"\"\"\nbfgs(f,df,x)\n\nBFGS method for solving min_x f(x)\n\n\"\"\"\nfunction bfgs(f::Function,df::Function,x::Vector;H=speye(length(x)), maxIter=20,atol=1e-8,out::Int=0,storeInterm::Bool=false,\n\tlineSearch::Function=(f,df,fk,dfk,xk,pk)->armijo(f,fk,dfk,xk,pk,maxIter=30))\n\n his = zeros(maxIter,3)\n I = speye(length(x))\n X = (storeInterm) ? zeros(length(x),maxIter) : []\n fk = f(x)\n dfk = df(x)\n \n i = 1; flag = -1 \n while i<=maxIter\n\n his[i,1:2] = [fk norm(dfk)]\n if storeInterm; X[:,i] = x; end;\n if norm(dfk)0\n @printf \"iter=%4d\\t|f|=%1.2e\\t|df|=%1.2e\\tLS=%d\\n\" i his[i,1] his[i,2] his[i,3]\n end\n if his[i,3]==-1\n flag = -3\n his = his[1:i,:]\n break;\n end\n x += ak*pk\n fk = f(x)\n dfnew = df(x)\n sk = ak*pk\n yk = dfnew - dfk\n if dot(yk,sk)>0 # ensure that approximate Hessians remain positive definite\n \tH = (I - (sk*yk')/dot(sk,yk)) * H * (I - (yk*sk')/dot(sk,yk)) + (sk*sk')/dot(yk,sk)\n else\n if out>0\n warn(\"bfgs detected negative curvature. Resetting Hessian\")\n end\n H = speye(length(x))\n end\n dfk = dfnew\n i+=1 \n end\n i = min(maxIter,i)\n\n if out>=0\n if flag==-1\n println(@sprintf(\"bfgs iterated maxIter (=%d) times but reached only atol of %1.2e instead of tol=%1.2e\",i,his[i,2],atol))\n elseif flag==-3\n println(@sprintf(\"bfgs stopped of a line search fail at iteration %d.\",i))\n elseif out>1\n println(@sprintf(\"bfgs achieved desired atol of %1.2e at iteration %d.\",atol,i))\n end\n end\n \n if storeInterm; X = X[:,1:i]; end\n return x,flag,his,X,H\nend", "meta": {"hexsha": "bdfc5caf48607bc4717726f589dc0b57d1be4f89", "size": 2035, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/bfgs.jl", "max_stars_repo_name": "lruthotto/OptimTools.jl", "max_stars_repo_head_hexsha": "977feb8f2fd5e04d3f3b2a700b8abc992740cedb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/bfgs.jl", "max_issues_repo_name": "lruthotto/OptimTools.jl", "max_issues_repo_head_hexsha": "977feb8f2fd5e04d3f3b2a700b8abc992740cedb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/bfgs.jl", "max_forks_repo_name": "lruthotto/OptimTools.jl", "max_forks_repo_head_hexsha": "977feb8f2fd5e04d3f3b2a700b8abc992740cedb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.661971831, "max_line_length": 134, "alphanum_fraction": 0.4963144963, "num_tokens": 692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818865, "lm_q2_score": 0.8840392725805823, "lm_q1q2_score": 0.8032539090333579}} {"text": "\"\"\"\n atmosphere_isa(height)\nCalculate temperature, pressure, density and sound velocity for the given geopotential\nheight according to International Standard Atmosphere 1976.\n\n# References\n1.U.S. Standard Atmosphere, 1976, U.S. Government Printing Office, Washington, D.C., 1976\n\n| Layer | h (m) | p (Pa) | T (K) | ``α`` (K/m) |\n| ----- | ----- | ------- | ------ | ----------- |\n| 0 | 0 | 101325 | 288.15 | -0.0065 |\n| 1 | 11000 | 22632.1 | 216.65 | 0 |\n| 2 | 20000 | 5474.89 | 216.65 | 0.001 |\n| 3 | 32000 | 868.019 | 228.65 | 0.0028 |\n| 4 | 47000 | 110.906 | 270.65 | 0 |\n| 5 | 51000 | 66.9389 | 270.65 | -0.0028 |\n| 6 | 71000 | 3.95642 | 214.65 | -0.002 |\n\nSource: [https://en.wikipedia.org/wiki/U.S._Standard_Atmosphere](https://en.wikipedia.org/wiki/U.S._Standard_Atmosphere)\n\n\"\"\"\nfunction atmosphere_isa(height)\n\n if 0 <= height < 11000 # Troposphere\n α = -0.0065 # K/m\n T0 = 288.15 # K\n p0 = 101325.0 # Pa\n\n T = T0 + α * height\n p = p0 * (T0 / T) ^ (gD / (R_AIR * α))\n\n elseif 11000 <= height < 20000 # Tropopause\n T = 216.65 # K\n p0 = 22632.1 # Pa\n h0 = 11000 # m\n\n p = p0 * exp(-gD * (height - h0) / (R_AIR * T))\n\n elseif 20000 <= height < 32000 # Stratosphere 1\n α = 0.001 # K/m\n T0 = 216.65 # K\n p0 = 5474.89 # Pa\n h0 = 20000 # m\n\n T = T0 + α * (height - h0)\n p = p0 * (T0 / T) ^ (gD / (R_AIR * α))\n\n elseif 32000 <= height < 47000 # Stratosphere 2\n α = 0.0028 # K/m\n T0 = 228.65 # K\n p0 = 868.019 # Pa\n h0 = 32000 # m\n\n T = T0 + α * (height - h0)\n p = p0 * (T0 / T) ^ (gD / (R_AIR * α))\n\n elseif 47000 <= height < 51000 # Stratopause\n T = 270.65 # K\n p0 = 110.906 # Pa\n h0 = 47000 # m\n h0 = 47000 # m\n\n p = p0 * exp(-gD * (height - h0) / (R_AIR * T))\n\n elseif 51000 <= height < 71000 # Mesosphere 1\n α = -0.0028 # K/m\n T0 = 270.65 # K\n p0 = 66.9389 # Pa\n h0 = 51000 # m\n\n T = T0 + α * (height - h0)\n p = p0 * (T0 / T) ^ (gD / (R_AIR * α))\n\n elseif 71000 <= height <= 84500 # Mesosphere 2\n α = -0.002 # K/m\n T0 = 214.65 # K\n p0 = 3.95642 # Pa\n h0 = 71000 # m\n\n T = T0 + α * (height - h0)\n p = p0 * (T0 / T) ^ (gD / (R_AIR * α))\n\n else\n throw(DomainError(height, \"height must be between 0 m and 84500 m\"))\n end\n\n rho = p / (R_AIR * T)\n a = sqrt(γ_AIR * R_AIR * T)\n\n return [T, p, rho, a]\nend\n", "meta": {"hexsha": "36ce927fa18077ac12476b6dbd9dd1feb8c1742f", "size": 2697, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/atmosphere.jl", "max_stars_repo_name": "AlexS12/FlightMechanicsUtils.jl", "max_stars_repo_head_hexsha": "862f3cdac936c65881bc2aa8f1168ead8d5284d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-06-24T17:05:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T16:56:11.000Z", "max_issues_repo_path": "src/atmosphere.jl", "max_issues_repo_name": "AlexS12/FlightMechanicsUtils.jl", "max_issues_repo_head_hexsha": "862f3cdac936c65881bc2aa8f1168ead8d5284d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2021-03-13T19:26:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-06T11:41:07.000Z", "max_forks_repo_path": "src/atmosphere.jl", "max_forks_repo_name": "AlexS12/FlightMechanicsUtils.jl", "max_forks_repo_head_hexsha": "862f3cdac936c65881bc2aa8f1168ead8d5284d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3152173913, "max_line_length": 120, "alphanum_fraction": 0.4519836856, "num_tokens": 1058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104904802131, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.8032253605399752}} {"text": "\"\"\"\n modular_inverse(base::Int64, modulus::Int64)\n\nCompute the multiplicative inverse of the `base` under the `modulus`.\n\n\n# Arguments\n- `base::Int64`: base\n- `modulus ::Int64`: modulus\n\n\n# Examples\n```julia-repl\njulia> import ClassicAlgorithmsCollections\njulia> ClassicAlgorithmsCollections.modular_inverse(3, 11)\n4\n```\n\"\"\"\nfunction modular_inverse(base::Int64, modulus::Int64)\n base = base % modulus\n for i in 1:modulus\n if (base * i) % modulus == 1\n return i\n end\n end\n return 1\nend", "meta": {"hexsha": "5d7a101589133bd6f95d23c0a613f78b534fa569", "size": 525, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NumberTheory/ModularInverse.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/NumberTheory/ModularInverse.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/NumberTheory/ModularInverse.jl", "max_forks_repo_name": "Anselmoo/ClassicAlgorithmsCollections", "max_forks_repo_head_hexsha": "9f802c4f317492e19b0b8bb6d9020d8450e00772", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.4444444444, "max_line_length": 69, "alphanum_fraction": 0.6685714286, "num_tokens": 151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947132556618, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.8032182710074631}} {"text": "\"\"\"\r\n taylor(df,a,b,y0,M)\r\n\r\nberisi program untuk mencari solusi persamaan differensial `y'=f(t,y)`\r\ndengan masalah nilai awal `y(a) = y0` pada interval `[a, b]`. Program ini secara default\r\nberisi 5 masukan, yaitu fungsi `df` yang berisi nilai dari fungsi y', y'', y''', y'''',\r\ntitik ujung interval penyelesaian `[a,b]`, nilai awal\r\n`y0`, dan jumlah sub-interval `M`.\r\n# Examples\r\n```jldoctest\r\njulia> function df(t,y)\r\n y1 = (t-y)/2;\r\n y2 = (2-t+y)/4;\r\n y3 = (-2+t-y)/8;\r\n y4 = (2-t+y)/16;\r\n z = [y1,y2,y3,y4];\r\n end\r\n\r\njulia> sol1 = taylor(df,0,3,1,6)\r\n7×2 Array{Float64,2}:\r\n 0.0 1.0\r\n 0.5 0.836426\r\n 1.0 0.819628\r\n 1.5 0.917142\r\n 2.0 1.10368\r\n 2.5 1.35956\r\n 3.0 1.66943\r\n```\r\nreturn solusi masalah nilai awal `sol`.\r\n\"\"\"\r\nfunction taylor(df,a,b,y0,M)\r\n M = Int(M)\r\n h = (b-a)/M;\r\n T = a:h:b;\r\n Y = Array{Float64}(undef,length(T),1)\r\n Y[1]=y0;\r\n for j = 1:M\r\n D = df(T[j],Y[j]);\r\n Y[j+1]=Y[j]+h*(D[1]+h*(D[2]/2+h*(D[3]/6+h*D[4]/24)));\r\n end\r\n sol = [T Y];\r\nend\r\n", "meta": {"hexsha": "f7d3984f735ae7c1d17c812bae64983440e2b6b7", "size": 1037, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/taylor.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/taylor.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/taylor.jl", "max_forks_repo_name": "mkhoirun-najiboi/metnum.jl", "max_forks_repo_head_hexsha": "a6e35d04dc277318e32256f9b432264157e9b8f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1162790698, "max_line_length": 89, "alphanum_fraction": 0.5332690453, "num_tokens": 442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947148047778, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.8032182633457785}} {"text": "\"expected_arc(i,n) this polynomial indicates the expected number of NN-arcs that would pass over index `i` for a series of length`n` if the series was completely random. This is used to normalize the `segment_profile` to account for bias towards the edges.\"\nexpected_arc(i,n) = 2*(-i^2*n/(n-1)^2 + i*n/(n-1)) # polynomial coefficients solved for by using constraints e(0) = 0, e(n-1) = 0, e(n/2) = n/2\n\n\"\"\"\n segment_profile(p::Profile)\n\nCalculate the MP-index of a matrix profile. This index has the same length as the profile, and tells you how many nearest-neighbor arcs passes over index `i`. It's normalized by the expected number of arcs for a completely random time series, so that a value of 1 indicates a poor segmentation point, and a value close to 0 indicates a likely segmentation point.\n\"\"\"\nfunction segment_profile(p::Profile)\n I = p.I\n n = length(I)\n mpi = zeros(eltype(p.P), n)\n for i in 1:n\n Ii = I[i]\n if Ii > i\n for j = i:Ii-1\n mpi[j] += 1\n end\n else\n for j = Ii+1:i\n mpi[j] += 1\n end\n end\n end\n mpi .= min.(mpi ./ expected_arc.(0:n-1, n), 1)\n mpi\nend\n\n\"\"\"\n i = segment(p::Profile)\n\nReturns an index `i` indicating the most likely segmentation point of profile `p`, i.e., the point which the fewst nearest-neighbor arcs passes over.\n\nRef: Matrix Profile VIII: Domain Agnostic Online Semantic\nSegmentation at Superhuman Performance Levels\n\"\"\"\nfunction segment(p::Profile)\n argmin(segment_profile(p))\nend\n\n", "meta": {"hexsha": "d9fa91033b6d3fc343cc7f74902d65ee846a0e93", "size": 1555, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/segment.jl", "max_stars_repo_name": "baggepinnen/MatrixProfile.jl", "max_stars_repo_head_hexsha": "cc84190c68207fb6af66f6ee86cbe2df76859823", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2020-05-02T04:01:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-08T10:52:39.000Z", "max_issues_repo_path": "src/segment.jl", "max_issues_repo_name": "baggepinnen/MatrixProfile.jl", "max_issues_repo_head_hexsha": "cc84190c68207fb6af66f6ee86cbe2df76859823", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-05-02T05:11:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-17T06:17:09.000Z", "max_forks_repo_path": "src/segment.jl", "max_forks_repo_name": "baggepinnen/MatrixProfile.jl", "max_forks_repo_head_hexsha": "cc84190c68207fb6af66f6ee86cbe2df76859823", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-11-20T09:04:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T01:37:47.000Z", "avg_line_length": 37.9268292683, "max_line_length": 362, "alphanum_fraction": 0.6572347267, "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947070591977, "lm_q2_score": 0.84997116805678, "lm_q1q2_score": 0.803218254966581}} {"text": "\"\"\"\nnaive implementation\n\"\"\"\nfunction naiveform!(C, A, B)\n row, col = size(C)\n colA = size(A)[2]\n for i in 1:row\n for j in 1:col\n for k in 1:colA\n C[i, j] = C[i, j] + A[i, k] * B[k, j]\n end\n end\n end\n C\nend\n\n\n\"\"\"\ninner-product-form\n\"\"\"\nfunction ipform!(C, A, B)\n row, col = size(C)\n colA = size(A)[2]\n for i in 1:row\n for j in 1:col\n dataC = 0.0\n for k in 1:colA\n dataC = dataC + A[i, k] * B[k, j]\n end\n C[i, j] = dataC\n end\n end\nend\n\n\n\"\"\"\nouter-product-form\n\"\"\"\nfunction opform!(C, A, B)\n row, col = size(C)\n colA = size(A)[2]\n for k in 1:colA\n for j in 1:col\n dataB = B[k, j]\n for i in 1:row\n C[i, j] = C[i, j] + A[i, k] * dataB\n end\n end\n end\nend\n\n\n\"\"\"\nmiddle-product-form\n\"\"\"\nfunction mpform!(C, A, B)\n row, col = size(C)\n colA = size(A)[2]\n for j in 1:col\n for k in 1:colA \n dataB = B[k, j]\n for i in 1:row\n C[i, j] = C[i, j] + A[i, k] * dataB\n end\n end\n end\nend\n", "meta": {"hexsha": "330ea4a99bdb5d9f02ff8d84f359f9883bf2f8ac", "size": 1171, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/productform.jl", "max_stars_repo_name": "terasakisatoshi/MySample.jl", "max_stars_repo_head_hexsha": "9702e7be4c4671c04cb7a65b459a3415bd19b4af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/productform.jl", "max_issues_repo_name": "terasakisatoshi/MySample.jl", "max_issues_repo_head_hexsha": "9702e7be4c4671c04cb7a65b459a3415bd19b4af", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/productform.jl", "max_forks_repo_name": "terasakisatoshi/MySample.jl", "max_forks_repo_head_hexsha": "9702e7be4c4671c04cb7a65b459a3415bd19b4af", "max_forks_repo_licenses": ["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.2205882353, "max_line_length": 53, "alphanum_fraction": 0.4124679761, "num_tokens": 418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.8670357666736772, "lm_q1q2_score": 0.8031384649681034}} {"text": "# Classical Multidimensional Scaling\n\n## convert Gram matrix to Distance matrix\n\nfunction gram2dmat!{DT}(D::AbstractMatrix{DT}, G::AbstractMatrix)\n # argument checking\n m = size(G, 1)\n n = size(G, 2)\n m == n || error(\"D should be a square matrix.\")\n size(D) == (m, n) ||\n throw(DimensionMismatch(\"Sizes of D and G do not match.\"))\n \n # implementation\n for j = 1:n\n for i = 1:j-1\n @inbounds D[i,j] = D[j,i]\n end\n D[j,j] = zero(DT)\n for i = j+1:n\n @inbounds D[i,j] = sqrt(G[i,i] + G[j,j] - 2 * G[i,j])\n end\n end\n return D\nend\n\ngram2dmat{T<:Real}(G::AbstractMatrix{T}) = gram2dmat!(similar(G, Base.momenttype(T)), G)\n\n## convert Distance matrix to Gram matrix\n\nfunction dmat2gram!{GT}(G::AbstractMatrix{GT}, D::AbstractMatrix)\n # argument checking\n m = size(D, 1)\n n = size(D, 2)\n m == n || error(\"D should be a square matrix.\")\n size(G) == (m, 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] = Base.sumabs2(view(D,:,j)) / n)\n end\n s /= n\n\n for j = 1:n\n for i = 1:j-1\n @inbounds G[i,j] = G[j,i]\n end\n for i = j:n\n @inbounds G[i,j] = (u[i] + u[j] - abs2(D[i,j]) - s) / 2\n end\n end\n return G\nend\n\ndmat2gram{T<:Real}(D::AbstractMatrix{T}) = dmat2gram!(similar(D, Base.momenttype(T)), D)\n\n## classical MDS\n\nfunction classical_mds{T<:Real}(D::AbstractMatrix{T}, p::Integer)\n n = size(D, 1)\n p < n || error(\"p must be less than n.\")\n\n G = dmat2gram(D)\n E = eigfact!(Symmetric(G))\n ord = sortperm(E.values; rev=true)\n (v, U) = extract_kv(E, ord, p)\n for i = 1:p\n @inbounds v[i] = sqrt(v[i])\n end\n scale!(U, v)'\nend\n\n\n", "meta": {"hexsha": "90b55d1c0cb575f7639e8b39acd709cfd018e63c", "size": 1829, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/cmds.jl", "max_stars_repo_name": "jfsantos/MultivariateStats.jl", "max_stars_repo_head_hexsha": "af494814f2102e9a18c4d9860a8971cd3b7bea33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-03-19T08:56:42.000Z", "max_stars_repo_stars_event_max_datetime": "2015-03-19T08:56:42.000Z", "max_issues_repo_path": "src/cmds.jl", "max_issues_repo_name": "jfsantos/MultivariateStats.jl", "max_issues_repo_head_hexsha": "af494814f2102e9a18c4d9860a8971cd3b7bea33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cmds.jl", "max_forks_repo_name": "jfsantos/MultivariateStats.jl", "max_forks_repo_head_hexsha": "af494814f2102e9a18c4d9860a8971cd3b7bea33", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0657894737, "max_line_length": 88, "alphanum_fraction": 0.5352651722, "num_tokens": 619, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303728259492, "lm_q2_score": 0.867035763237924, "lm_q1q2_score": 0.8031384600216032}} {"text": "#\n# Copyright (c) 2021 Tobias Thummerer, Lars Mikelsons\n# Licensed under the MIT license. See LICENSE file in the project root for details.\n#\n\nusing FMIExport \n\nFMU_FCT_INIT = function()\n m = 1.0 # ball mass\n r = 0.0 # ball radius\n d = 0.7 # ball collision damping\n v_min = 1e-1 # ball minimum velocity\n g = -9.81 # gravity constant \n\n s = 1.0 # ball position\n v = 0.0 # ball velocity\n a = 0.0 # ball acceleration\n\n t = 0.0 \n x = [s, v] \n ẋ = [v, a]\n u = []\n p = [m, r, d, v_min, g]\n\n return (t, x, ẋ, u, p)\nend\n\nFMU_FCT_EVALUATE = function(t, x, ẋ, u, p)\n m, r, d, v_min, g = (p...,)\n s, v = (x...,)\n _, a = (ẋ...,)\n\n if s <= r && v < 0.0\n s = r\n v = -v*d \n \n # stop bouncing to prevent high frequency bouncing (and maybe tunneling the floor)\n if v < v_min\n v = 0.0\n g = 0.0\n end\n end\n\n a = (m * g) / m # the system's physical equation\n\n x = [s, v]\n ẋ = [v, a]\n p = [m, r, d, v_min, g]\n\n return (x, ẋ, p)\nend\n\nFMU_FCT_OUTPUT = function(t, x, ẋ, u, p)\n m, r, d, v_min, g = (p...,)\n s, v = (x...,)\n _, a = (ẋ...,)\n\n y = [s]\n\n return y\nend\n\nFMU_FCT_EVENT = function(t, x, ẋ, u, p)\n m, r, d, v_min, g = (p...,)\n s, v = (x...,)\n _, a = (ẋ...,)\n\n z1 = (s-r) # event 1: ball hits ground \n \n if s==r && v==0.0\n z1 = 1.0 # event 1: ball stay-on-ground\n end\n\n z = [z1]\n\n return z\nend\n\n# this function is called, as soon as the DLL is loaded and Julia is initialized \n# must return a FMU2-instance to work with\nFMIBUILD_CONSTRUCTOR = function(resPath=\"\")\n fmu = fmi2CreateSimple(initializationFct=FMU_FCT_INIT,\n evaluationFct=FMU_FCT_EVALUATE,\n outputFct=FMU_FCT_OUTPUT,\n eventFct=FMU_FCT_EVENT)\n\n # states [2]\n fmi2AddStateAndDerivative(fmu, \"ball.s\"; stateDescr=\"Absolute position of ball center of mass\", derivativeDescr=\"Absolute velocity of ball center of mass\")\n fmi2AddStateAndDerivative(fmu, \"ball.v\"; stateDescr=\"Absolute velocity of ball center of mass\", derivativeDescr=\"Absolute acceleration of ball center of mass\")\n\n # outputs [1]\n fmi2AddRealOutput(fmu, \"ball.s\"; description=\"Absolute position of ball center of mass\")\n\n # parameters [5]\n fmi2AddRealParameter(fmu, \"m\"; description=\"Mass of ball\")\n fmi2AddRealParameter(fmu, \"r\"; description=\"Radius of ball\")\n fmi2AddRealParameter(fmu, \"d\"; description=\"Collision damping constant (velocity fraction after hitting the ground)\")\n fmi2AddRealParameter(fmu, \"v_min\"; description=\"Minimal ball velocity to enter on-ground-state\")\n fmi2AddRealParameter(fmu, \"g\"; description=\"Gravity constant\")\n\n fmi2AddEventIndicator(fmu)\n\n return fmu\nend\n\n### FMIBUILD_NO_EXPORT_BEGIN ###\n# The line above is a start-marker for excluded code for the FMU compilation process!\n\ntmpDir = mktempdir(; prefix=\"fmibuildjl_test_\", cleanup=false) \n@info \"Saving example files at: $(tmpDir)\"\nfmu_save_path = joinpath(tmpDir, \"BouncingBall.fmu\") \n\nfmu = FMIBUILD_CONSTRUCTOR()\nusing FMIBuild: fmi2Save # <= this must be excluded during export, because FMIBuild cannot execute itself (but it is able to build)\nfmi2Save(fmu, fmu_save_path) # <= this must be excluded during export, because fmi2Save would start an infinte build loop with itself \n\n### some tests ###\n# using FMI\n# comp = fmiInstantiate!(fmu; loggingOn=true)\n# solution = fmiSimulateME(comp, 0.0, 10.0; dtmax=0.1)\n# fmiPlot(fmu, solution)\n# fmiFreeInstance!(comp)\n\n# The following line is a end-marker for excluded code for the FMU compilation process!\n### FMIBUILD_NO_EXPORT_END ###\n", "meta": {"hexsha": "03554a03a339aa6fa034b97faf1c9fb1650ea1c2", "size": 3804, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/FMI2/BouncingBall/src/BouncingBall.jl", "max_stars_repo_name": "stoljarjo/FMIExport.jl", "max_stars_repo_head_hexsha": "b040d8e6d2cf9817da75c5785a27d554387de576", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2022-02-14T12:23:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T00:40:48.000Z", "max_issues_repo_path": "example/FMI2/BouncingBall/src/BouncingBall.jl", "max_issues_repo_name": "stoljarjo/FMIExport.jl", "max_issues_repo_head_hexsha": "b040d8e6d2cf9817da75c5785a27d554387de576", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-02-17T08:36:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T12:53:15.000Z", "max_forks_repo_path": "example/FMI2/BouncingBall/src/BouncingBall.jl", "max_forks_repo_name": "stoljarjo/FMIExport.jl", "max_forks_repo_head_hexsha": "b040d8e6d2cf9817da75c5785a27d554387de576", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-14T12:27:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T12:27:12.000Z", "avg_line_length": 30.1904761905, "max_line_length": 163, "alphanum_fraction": 0.6069926393, "num_tokens": 1183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850057480347, "lm_q2_score": 0.857768108626046, "lm_q1q2_score": 0.8031154185154183}} {"text": "const singular = let res_init=zeros(4), jac_init=zeros(4,4), x_init=[3.0, -1.0, 0.0, 1.0]\n\n function res(x, r)\n r[1] = x[1] + 10.0 * x[2]\n r[2] = sqrt(5.0) * (x[3] - x[4])\n r[3] = (x[2] - 2x[3])^2\n r[4] = sqrt(10.0) * (x[1] - x[4])^2\n return r\n end\n\n function jac(x, jac)\n jac[:] .= 0.0\n jac[1, 1] = 1.0\n jac[1, 2] = 10.0\n jac[2, 3] = sqrt(5.0)\n jac[2, 4] = -jac[2, 3]\n jac[3, 2] = 2.0 * (x[2] - 2.0 * x[3])\n jac[3, 3] = -2.0 * jac[3, 2]\n jac[4, 1] = sqrt(40.0) * (x[1] - x[4])\n jac[4, 4] = -jac[4, 1]\n return jac\n end\n\n f(;scale=1, verbose=false, print_steps=false) = testone(\"singular\", res, jac,\n res_init, jac_init, x_init;\n scale=scale, verbose=verbose,\n print_steps=print_steps)\nend\n\n", "meta": {"hexsha": "bc9e243cc760c04a243f3de7167ee51557d30006", "size": 960, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/optests/singular.jl", "max_stars_repo_name": "macd/NL2sol.jl", "max_stars_repo_head_hexsha": "f4826f62438c960404aa59d0c620bd7d158440d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-01-19T21:59:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T00:42:56.000Z", "max_issues_repo_path": "test/optests/singular.jl", "max_issues_repo_name": "macd/NL2sol.jl", "max_issues_repo_head_hexsha": "f4826f62438c960404aa59d0c620bd7d158440d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/optests/singular.jl", "max_forks_repo_name": "macd/NL2sol.jl", "max_forks_repo_head_hexsha": "f4826f62438c960404aa59d0c620bd7d158440d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0, "max_line_length": 89, "alphanum_fraction": 0.3864583333, "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362849986365571, "lm_q2_score": 0.8577681031721325, "lm_q1q2_score": 0.8031154073090022}} {"text": "using Distributions\n\n\"\"\"\nGeneral Interface for Computation of confidence interval of price\n\n\t\tIC=confinter(mcProcess,rfCurve,mcBaseData,payoff_,alpha)\n\t\nWhere:\\n\n\t\tmcProcess = Process to be simulated.\n\t\trfCurve = Zero Rate Data.\n\t\tmcBaseData = Basic properties of MonteCarlo simulation\n\t\tpayoff_ = Payoff(s) to be priced\n\t\talpha [Optional, default to 99%] = confidence level\n\t\t\n\n\t\tPrice = Price of the derivative\n\n\"\"\"\nfunction confinter(mcProcess::BaseProcess, rfCurve::AbstractZeroRateCurve, mcConfig::MonteCarloConfiguration, abstractPayoff::AbstractPayoff, alpha::Real = 0.99)\n set_seed(mcConfig)\n T = maturity(abstractPayoff)\n Nsim = mcConfig.Nsim\n S = simulate(mcProcess, rfCurve, mcConfig, T)\n Payoff = payoff(S, abstractPayoff, rfCurve)\n mean1 = mean(Payoff)\n var1 = var(Payoff)\n alpha_ = 1 - alpha\n dist1 = Distributions.TDist(Nsim)\n tstar = quantile(dist1, 1 - alpha_ / 2.0)\n IC = (mean1 - tstar * sqrt(var1) / Nsim, mean1 + tstar * sqrt(var1) / Nsim)\n return IC\nend\n\nfunction confinter(mcProcess::BaseProcess, rfCurve::AbstractZeroRateCurve, mcConfig::MonteCarloConfiguration, abstractPayoffs::Array{abstractPayoff_}, alpha::Real = 0.99) where {abstractPayoff_ <: AbstractPayoff}\n set_seed(mcConfig)\n maxT = maximum([maturity(abstractPayoff) for abstractPayoff in abstractPayoffs])\n Nsim = mcConfig.Nsim\n S = simulate(mcProcess, rfCurve, mcConfig, maxT)\n Means = [mean(payoff(S, abstractPayoff, rfCurve, maxT)) for abstractPayoff in abstractPayoffs]\n Vars = [var(payoff(S, abstractPayoff, rfCurve, maxT)) for abstractPayoff in abstractPayoffs]\n alpha_ = 1 - alpha\n dist1 = Distributions.TDist(Nsim)\n tstar = quantile(dist1, 1 - alpha_ / 2.0)\n IC = [(mean1 - tstar * sqrt(var1) / Nsim, mean1 + tstar * sqrt(var1) / Nsim) for (mean1, var1) in zip(Means, Vars)]\n return IC\nend\n", "meta": {"hexsha": "1a6eb78c71a1701cc4da8b709b6be8414d694db0", "size": 1867, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/metrics/confinterval.jl", "max_stars_repo_name": "rcalxrc08/FinancialMonteCarlo.jl", "max_stars_repo_head_hexsha": "3c7444414ea3a449d3aeb48c182d4c05b37c31b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2019-09-23T16:39:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T12:46:13.000Z", "max_issues_repo_path": "src/metrics/confinterval.jl", "max_issues_repo_name": "rcalxrc08/FinancialMonteCarlo.jl", "max_issues_repo_head_hexsha": "3c7444414ea3a449d3aeb48c182d4c05b37c31b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-12-25T03:35:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-07T14:06:39.000Z", "max_forks_repo_path": "src/metrics/confinterval.jl", "max_forks_repo_name": "rcalxrc08/FinancialMonteCarlo.jl", "max_forks_repo_head_hexsha": "3c7444414ea3a449d3aeb48c182d4c05b37c31b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-04T06:31:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-04T06:31:57.000Z", "avg_line_length": 39.7234042553, "max_line_length": 212, "alphanum_fraction": 0.7139796465, "num_tokens": 571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.942506726044381, "lm_q2_score": 0.8519528038477825, "lm_q1q2_score": 0.8029712478989042}} {"text": "\"\"\"\n centroids_radii(points::Array{Float64, 2}, indices_simplices::Array{Int, 1})\nCompute the centroids and radii of the simplices in the triangulation in any dimension.\n\n`points::Array{Float64, 2}` Points furnishing the triangulation (size = npoints x dim).\n`indices_simplices::Array{Int, 1}` Indices of the vertices furnishing simplices of the\n triangulation. Each row refers to one simplex.\n\"\"\"\nfunction centroids_radii2(points, indices_simplices)\n dim = size(points, 2)\n nsimplices = size(indices_simplices, 1)\n centroids = zeros(nsimplices, dim)\n radii = zeros(nsimplices)\n\n for i = 1:nsimplices\n simplex = points[indices_simplices[i, :], :] # (dim + 1) x dim)\n centroid = sum(simplex, dims=1) / (dim + 1)\n centroid_matrix = repeat(centroid, dim + 1, 1)\n\n # Subtract centroid from each simplex\n subtracted = simplex - centroid_matrix\n radius = sqrt(maximum(sum(subtracted.^2, dims=2)))\n\n centroids[i, :] = centroid\n radii[i] = radius\n\n end\n\n return centroids, radii\nend\n", "meta": {"hexsha": "0610b1f640a3569d3fcce854ef6c5cb43a4a55af", "size": 1058, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/simplexsplitting/centroids_radii.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/Simplices.jl-d5428e67-3037-59ba-9ab1-57a04f0a3b6a", "max_stars_repo_head_hexsha": "c5651f0aa8e45bd196fc6816e3e47f01d2f1764b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-10-08T00:07:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-08T00:07:46.000Z", "max_issues_repo_path": "src/simplexsplitting/centroids_radii.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/Simplices.jl-d5428e67-3037-59ba-9ab1-57a04f0a3b6a", "max_issues_repo_head_hexsha": "c5651f0aa8e45bd196fc6816e3e47f01d2f1764b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2018-04-04T02:26:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-29T15:46:04.000Z", "max_forks_repo_path": "src/simplexsplitting/centroids_radii.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/Simplices.jl-d5428e67-3037-59ba-9ab1-57a04f0a3b6a", "max_forks_repo_head_hexsha": "c5651f0aa8e45bd196fc6816e3e47f01d2f1764b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-12-11T08:36:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:03:05.000Z", "avg_line_length": 34.1290322581, "max_line_length": 87, "alphanum_fraction": 0.6776937618, "num_tokens": 290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067163548471, "lm_q2_score": 0.8519527982093668, "lm_q1q2_score": 0.8029712343296339}} {"text": "module MatrixDecomposition\nexport luls, lupp, choleskyls, qrls, lulspp\n\n# Solve a system of linear equations using backwards substitution\nfunction bwsub(a::Array{Float64, 2}, v::Array{Float64, 1})\n\t# Make sure we have an upper triangular matrix\n\tif !istriu(a)\n\t\terror(\"Matrix is not upper triangular\")\n\tend\n\n\t# Create result vector the same size as v\n\tresult = zeros(v)\n\n\t# The last value in result = last value in v scaled by last value in a\n\tresult[end] = v[end] / a[end]\n\n\t# Iterate backwards through every row of a (except the last)\n\tfor i in size(a, 1)-1:-1:1\n\t\t# Perform backwards substitution at each step\n\t\tsumterm = sum([a[i,j] * result[j] for j in i+1:size(a, 1)])\n\t\tresult[i] = (1.0 / a[i,i]) * (v[i] - sumterm)\n\tend\n\n\treturn result\nend\n\n# Solve a system of linear equations using forwards substitution\nfunction fwsub(a::Array{Float64, 2}, v::Array{Float64, 1})\n\t# Make sure we have a lower triangular matrix\n\tif !istril(a)\n\t\terror(\"Matrix is not lower triangular\")\n\tend\n\n\t# Create result vector the same size as v\n\tresult = zeros(v)\n\n\t# The first value in result = the first value in v scaled by first value in a\n\tresult[1] = v[1] / a[1]\n\n\t# Iterate forward through every row of a (except the first)\n\tfor i in 2:size(a, 1)\n\t\t# Perform forwards substitution at each step\n\t\tsumterm = sum([a[i,j] * result[j] for j in 1:i-1])\n\t\tresult[i] = (1.0 / a[i,i]) * (v[i] - sumterm)\n\tend\n\n\treturn result\nend\n\n# Swap two rows of a matrix (works for any number filled matrix)\nfunction swaprows!{T<:Number}(a::Array{T, 2}, i::Int64, j::Int64)\n\t# For every number across the first row\n\tfor k in 1:size(a, 2)\n\t\t# Swap with the corresponding number in the second row\n\t\ta[i,k], a[j,k] = a[j,k], a[i,k]\n\tend\nend\n\n# Return stricly lower triangular portion of matrix\nfunction stricttril{T<:Number}(a::Array{T, 2})\n\treturn tril(a) - diagm(diag(a))\nend\n\n# Find LU Decomposition of a matrix using Crout's algorithm\nfunction crout{T<:Number}(a::Array{T, 2}; print=false)\n\tN = size(a, 2)\n\n\t# Create diagonal NxN matrix to hold result in place\n\tresult = copy(a)\n\n\t# Create matrix to store our permutations\n\tpermuts = int(eye(a))\n\n\t# Perform Crout's algorithm in place\n\tfor p in 1:N\n\t\t# Find u's\n\t\tfor j in p:N\n\t\t\t# If j = 1 the sum term is taken to be zero\n\t\t\tsumterm = j == 1 ? 0 : sum([result[p,k] * result[k,j] for k in 1:p-1])\n\n\t\t\tresult[p,j] = result[p,j] - sumterm\n\t\tend\n\n\t\t# Find v's\n\t\tfor i in p+1:N\n\t\t\t# If i = 1 the sum term is taken to be zero\n\t\t\tsumterm = i == 1 ? 0 : sum([result[i,k] * result[k,p] for k in 1:p-1])\n\t\t\tresult[i,p] = (result[i,p] - sumterm) / result[p,p]\n\t\tend\n\tend\n\n\t# Extract l and u from result matrix\n\tu = triu(result)\n\tl = stricttril(result) + eye(result)\n\n\t# Print decomposition, if requested\n\tif print\n\t\tprintln(\"L:\\n\", l)\n\t\tprintln(\"U:\\n\", u)\n\t\tprintln()\n\tend\n\n\treturn l, u\nend\n\n# Calculate least squares estimate using LU Decomposition via Crout's Algorithm\nfunction luls{T<:Number}(x::Array{T, 2}, y::Array{T, 1}; print=false)\n\t# Calculate normal equations\n\tm = x' * x\n\tv = x' * y\n\n\t# Calculate LU decomposition\n\tl, u = crout(m, print=print)\n\n\t# Solve V = L * gamma using forward substitution\n\tgamma = fwsub(l, v)\n\n\t# Solve gamma = U beta\n\tbeta = bwsub(u, gamma)\n\n\treturn beta\nend\n\n# LU Decomposition with partial pivoting\n# Returns L, U and the permutation matrix recording the row pivots\nfunction lupp{T<:Number}(a::Array{T, 2}; print=false)\n\tN = size(a, 2)\n\n\t# Create a copy of the input to work on\n\tacopy = copy(a)\n\n\t# Maintain a record of our permutations\n\tpermut = eye(a)\n\n\tfor p in 1:N-1\n\t\tif print\n\t\t\tprintln(\"Pivot \", p)\n\t\tend\n\n\t\t# Find the largest value in the current column\n\t\tistar = indmax(abs(acopy[:,p]))\n\n\t\t# Swap rows in the permutation and working matrices\n\t\tif istar > p\n\t\t\tswaprows!(permut, istar, p)\n\t\t\tswaprows!(acopy, istar, p)\n\t\tend\n\n\t\t# Dividing by zero is bad\n\t\tif a[p,p] != 0\n\t\t\t# Calculate l's in column\n\t\t\tacopy[p+1:end,p] /= acopy[p,p]\n\n\t\t\t# Subtract product of row and column k from submatrix\n\t\t\tacopy[p+1:end,p+1:end] -= (acopy[p+1:end,p] * acopy[p,p+1:end])\n\t\tend\n\n\t\tif print\n\t\t\tprintln(acopy, \"\\n\")\n\t\tend\n\tend\n\n\tu = triu(acopy)\n\tl = stricttril(acopy) + eye(acopy)\n\n\tif print\n\t\tprintln(\"L:\\n\", l)\n\t\tprintln(\"U:\\n\", u)\n\t\tprintln()\n\tend\n\n\treturn l, u, permut\nend\n\n# Calculate least squares estimate using LU Decomposition with partial pivoting\nfunction lulspp{T<:Number}(x::Array{T, 2}, y::Array{T, 1}; print=false)\n\t# Calculate normal equations\n\tm = x' * x\n\tv = x' * y\n\n\t# Calculate LU decomposition\n\tl, u, p = lupp(m, print=print)\n\n\t# Solve V = l * gamma using forward substitution\n\tgamma = fwsub(l, p' * v)\n\n\t# Solve gamma = U beta\n\tbeta = bwsub(u, gamma)\n\n\treturn beta\nend\n\n# Find Cholesky decomposition of a positive definite symmetric matrix\nfunction cholesky{T<:Number}(a::Array{T, 2}; print=false)\n\t# Verify that matrix is positive definite and symmetric\n\tif !isposdef(a)\n\t\terror(\"Matrix is not positive definite\")\n\tend\n\n\tif !issym(a)\n\t\terror(\"Matrix is not symmetric\")\n\tend\n\n\tN = size(a, 2)\n\n\t# Create result matrix by copying lower triangle of a\n\tresult = tril(a)\n\n\t# Iterate through lower diagonal cells\n\tfor p in 1:N\n\t\t# Sum is taken to be zero if p=1\n\t\tsumterm = p == 1 ? 0 : sum([result[p,j]^2 for j in 1:p-1])\n\t\tresult[p,p] = sqrt((result[p,p] - sumterm))\n\n\t\tfor i in p+1:N\n\t\t\tsumterm = p == 1 ? 0 : sum([result[i,j] * result[p,j] for j in 1:p-1])\n\t\t\tresult[i,p] = (result[i,p] - sumterm) / result[p,p]\n\t\tend\n\tend\n\n\t# Print decomposition, if requested\n\tif print\n\t\tprintln(\"L:\\n\", result)\n\t\tprintln()\n\tend\n\n\treturn result\nend\n\n# Solve a system of linear equations via Cholesky decomposition\nfunction solvecholesky{T<:Number}(a::Array{T, 2}, v::Array{T, 1}; print=false)\n\t# Compute Cholesky decomposition\n\tl = cholesky(a, print=print)\n\n\t# Solve Ly = b using forward substitution\n\ty = fwsub(l, v)\n\n\t# Solve L'x=y using backward substitution\n\tx = bwsub(l', y)\n\n\treturn x\nend\n\n# Calculate least squares estimate using Cholesky decomposition\nfunction choleskyls{T<:Number}(x::Array{T, 2}, y::Array{T,1}; print=false)\n\t# Form components of normal equations\n\tm = x' * x\n\tv = x' * y\n\n\t# Solve using Cholesky decomposition\n\treturn solvecholesky(m, v, print=print)\nend\n\n# Project one vector onto another\nfunction project{T<:Number}(u::Array{T, 1}, v::Array{T, 1})\n\treturn (dot(u, v) / dot(u, u)) * u\nend\n\n# Orthonormalize a set of vectors using Gram-Schmidt\nfunction gs{T<:Number}(a::Array{T, 2})\n\tN = size(a, 2)\n\n\tresult = copy(a)\n\n\t# For each column vector in a\n\tfor i in 1:N\n\t\tfor j in 1:i-1\n\t\t\t# Subtract all the previous projections\n\t\t\tresult[:,i] -= project(result[:,j], a[:,i])\n\t\tend\n\tend\n\n\t# Normalize columns\n\tdenominators = sqrt(sum(result.^2.0, 1))\n\tresult = result ./ denominators\n\n\treturn result\nend\n\n# Find QR Decomposition using Gram-Schmidt\nfunction qrgs{T<:Number}(a::Array{T, 2}; print=false)\n\tN = size(a, 2)\n\n\t# Make sure matrix is full rank\n\tif rank(a) != N\n\t\terror(\"Matrix is not full rank\")\n\tend\n\n\t# Perform Gram-Schmidt orthogonalization\n\tq = gs(a)\n\t# Need to keep only the upper triangular due to rounding errors\n\tr = triu(q' * a)\n\n\t# Print decomposition if requested\n\tif print\n\t\tprintln(\"Q:\\n\", q)\n\t\tprintln(\"R:\\n\", r)\n\t\tprintln()\n\tend\n\n\treturn q, r\nend\n\n# Calculate least squares estimates using QR Decomposition\nfunction qrls{T<:Number}(x::Array{T, 2}, y::Array{T, 1}; print=false)\n\t# Form components of normal equations\n\t# Note - I think decomposing X'X instead of X leads to stability problems\n\t# but I did it this way to fulfill the parameters of an assignment.\n\tm = x' * x\n\tv = x' * y\n\n\t# Compute QR decomposition\n\tq, r = qrgs(m, print=print)\n\n\t# Solve Rbeta = Q'V using backward substitution\n\treturn bwsub(r, q' * v)\nend\nend", "meta": {"hexsha": "a88f090ae84e80b380745e95bd4c44a7ac5fb311", "size": 7614, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "MatrixDecomposition.jl", "max_stars_repo_name": "andrewjlm/StatComputing", "max_stars_repo_head_hexsha": "b18167f6ecd3e1689316a3f6077e50bde7dfaa03", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MatrixDecomposition.jl", "max_issues_repo_name": "andrewjlm/StatComputing", "max_issues_repo_head_hexsha": "b18167f6ecd3e1689316a3f6077e50bde7dfaa03", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MatrixDecomposition.jl", "max_forks_repo_name": "andrewjlm/StatComputing", "max_forks_repo_head_hexsha": "b18167f6ecd3e1689316a3f6077e50bde7dfaa03", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9433962264, "max_line_length": 79, "alphanum_fraction": 0.6700814289, "num_tokens": 2424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067147399245, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.802971232953796}} {"text": "### A Pluto.jl notebook ###\n# v0.16.1\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n quote\n local el = $(esc(element))\n global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n el\n end\nend\n\n# ╔═╡ b6ff5052-04ec-11eb-043b-458c42b19edb\nbegin\n import Pkg\n # activate the shared project environment\n Pkg.activate(Base.current_project())\n\n\tusing Distributions\n\tusing Plots\n\tusing PlutoUI\n\tusing Random\nend\n\n# ╔═╡ 87c1dc3b-d361-4f46-a68a-c28d7c7de0c3\nmd\"\"\"\n# Equilibrium binding simulations\n\nThis notebook can either:\n\n1. simulate the outcome of an equilibrium binding experiment given a hypothetical $K_D$ and desired experimental parameters (section [Simulate a binding curve](#d50721c7-34e4-411d-ae6b-dc6196b0f5a9)) or\n2. calculate the fractional saturation of receptor given a $K_D$ and total concentrations of receptor and ligand (section [Predict saturation of receptor](#3954adfa-73cc-495a-93c1-bcde87a60ce8)).\n\nThe following reference explains very well the theory of equilibrium binding experiments, as well as many important practical considerations:\n\n> Jarmoskaite I, AlSadhan I, Vaidyanathan PP & Herschlag D (2020) How to measure and evaluate binding affinities. *eLife* **9**: e57264 \n\"\"\"\n\n# ╔═╡ d50721c7-34e4-411d-ae6b-dc6196b0f5a9\nmd\"\"\"\n## Simulate a binding curve\n\nEnter values of $K_D$ and experimental parameters below to simulate the resulting data points (sampling the binding curve) as they would come out if you performed the experiment. The vertical line on the graph shows the value of $K_D$. The horizontal lines show zero and full saturation of the receptor.\n\"\"\"\n\n# ╔═╡ c4d66e7a-38e4-497d-b680-8c50c51fe146\nmd\"\"\"\nValue of $K_D$: $(@bind kd PlutoUI.Slider(0.1:0.1:100.0, default = 10.0, show_value = true))\n\nConcentration of ligand at highest titration point $L_{max}$: $(@bind lmax PlutoUI.Slider(kd:1.0:100000.0, default = 1000.0, show_value = true))\n\nDilution factor between titration points: $(@bind dilution PlutoUI.NumberField(1.1:0.1:10.0, default = 2.0))\n\nNumber of titration points: $(@bind points PlutoUI.NumberField(1:1:24, default = 15))\n\nConcentration of receptor $R_{tot}$: $(@bind Rtot PlutoUI.Slider(0.001:1.0:50.0, default = 1.0, show_value = true))\n\nSimulate random, normally distributed noise? $(@bind simulateNoise PlutoUI.CheckBox(default = false))\n\"\"\"\n\n# ╔═╡ b05df20b-353e-462d-aa13-534862f8f6cd\nif simulateNoise\n\tmd\"\"\"\n\tMean (μ) and standard deviation (σ)\n\n\tμ = $(@bind μ PlutoUI.NumberField(-3.0:0.1:3.0, default = 0.0))\n\tσ = $(@bind σ PlutoUI.NumberField(0.0:0.001:0.1, default = 0.001))\n\t\"\"\"\nend\n\n# ╔═╡ d49dee36-c12d-4206-9699-a181570caa80\nmd\"\"\"\nRatio $\\frac{L_{max}}{K_D} =$ $(lmax / kd)\n\nRatio $\\frac{K_D}{R_{tot}} =$ $(kd / Rtot)\n\"\"\"\n\n# ╔═╡ 915b2a49-cb32-40a0-bfae-21380144ed3a\nif simulateNoise\n\tmd\"\"\"\n\tSignal-to-noise ratio $\\frac{S}{σ} =$ $(1.0 / σ)\n\t\"\"\"\nend\n\n# ╔═╡ 3954adfa-73cc-495a-93c1-bcde87a60ce8\nmd\"\"\"\n## Predict saturation of receptor\n\nValue of $K_D$: $(@bind kd2 PlutoUI.NumberField(1.0:10.0:1000.0, default = 10.0))\n\nConcentration of ligand $L_{tot}$: $(@bind ltot2 PlutoUI.NumberField(1.0:100.0:100000.0, default = 1000.0))\n\nConcentration of receptor $R_{tot}$: $(@bind rtot2 PlutoUI.NumberField(0.001:0.01:100000.0, default = 1000.0))\n\nPercent saturation of receptor $B =$\n\"\"\"\n\n# ╔═╡ ae1d6dac-92d7-4962-a641-63965f73a8f2\nmd\"\"\"\n## Code\n\nThe quadratic model gives $B$, the fraction of bound receptor (or fractional saturation of receptor) for any values of receptor concentration $R_{tot}$ and ligand concentration $L_{tot}$, given a binding affinity determined by the value of $K_D$:\n\n$B = \\frac{(K_{D} + R_{tot} + L_{tot}) - \\sqrt{(- K_{D} - R_{tot} - L_{tot})^2 - 4 \\times R_{tot} \\times L_{tot}}}{2 \\times R_{tot}}$\n\nThe function below defines this binding model in code:\n\"\"\"\n\n# ╔═╡ 1eed6126-331b-4218-acc7-8b7c132ef355\nfunction quadratic(Ltot)\n\t( (kd + Rtot + Ltot) - sqrt((- kd - Rtot - Ltot) ^ 2 - 4 * Rtot * Ltot) ) / (2 * Rtot)\nend\n\n# ╔═╡ a5ac735b-f748-4d37-9cf1-7e64e1ea4c53\nfunction quadratic(kd, Rtot, Ltot)\n\t( (kd + Rtot + Ltot) - sqrt((kd + Rtot + Ltot) ^ 2 - 4 * Rtot * Ltot) ) / (2 * Rtot)\nend\n\n# ╔═╡ 4d816572-03a3-481c-a29c-522f0535a679\nround(100 * quadratic(kd2, ltot2, rtot2), digits = 2)\n\n# ╔═╡ 3794717b-1f61-4622-9a55-ad86ab947831\nmd\"\"\"\nThe code below calculates concentrations of the titration series ($X$ values for the plot) given the maximal ligand concentration $L_{max}$, the dilution factor and the number of titration points entered above:\n\"\"\"\n\n# ╔═╡ 7c43edeb-a5e6-4fb4-8494-e2072d0d56fd\nx = [ lmax / dilution^i for i in 0:points-1 ]\n\n# ╔═╡ 06f341e8-6d40-4eb7-b7e9-58c5d45f1f85\nmd\"\"\"\nThe code below uses the quadratic model to calculate fractional saturation of the receptor ($Y$ values for the plot) at each titration point for the values of $K_D$ and $R_{tot}$ entered above:\n\"\"\"\n\n# ╔═╡ 82af41ba-d9b9-4ce2-8736-6fe32c8e024e\nif simulateNoise\n\tnoise = rand(Normal(μ, σ), points)\n\ty = quadratic.(x) .+ noise\nelse\n\ty = quadratic.(x)\nend\n\n# ╔═╡ efc70ae1-abcc-472d-8df8-c55cbbd6529b\nbegin\n\tscatter(\n\t\tx,\n\t\ty,\n\t\txscale = :log10,\n\t\tlegend = :none,\n\t\txlabel = \"Ligand concentration\",\n\t\tylabel = \"Predicted fractional saturation of receptor\"\n\t)\n\tvline!([kd], color = :red)\n\thline!([1.0], color = :black)\n\thline!([0.0], color = :black)\nend\n\n# ╔═╡ 9c5021f3-67ab-464d-8f22-25e269c36083\nmd\"\"\"\n## Required packages\n\"\"\"\n\n# ╔═╡ b0340ca3-02d5-49a9-841b-7827e4aee2bb\nPlutoUI.TableOfContents()\n\n# ╔═╡ Cell order:\n# ╟─87c1dc3b-d361-4f46-a68a-c28d7c7de0c3\n# ╟─d50721c7-34e4-411d-ae6b-dc6196b0f5a9\n# ╟─c4d66e7a-38e4-497d-b680-8c50c51fe146\n# ╟─b05df20b-353e-462d-aa13-534862f8f6cd\n# ╟─d49dee36-c12d-4206-9699-a181570caa80\n# ╟─915b2a49-cb32-40a0-bfae-21380144ed3a\n# ╟─efc70ae1-abcc-472d-8df8-c55cbbd6529b\n# ╟─3954adfa-73cc-495a-93c1-bcde87a60ce8\n# ╠═4d816572-03a3-481c-a29c-522f0535a679\n# ╟─ae1d6dac-92d7-4962-a641-63965f73a8f2\n# ╠═1eed6126-331b-4218-acc7-8b7c132ef355\n# ╠═a5ac735b-f748-4d37-9cf1-7e64e1ea4c53\n# ╟─3794717b-1f61-4622-9a55-ad86ab947831\n# ╠═7c43edeb-a5e6-4fb4-8494-e2072d0d56fd\n# ╟─06f341e8-6d40-4eb7-b7e9-58c5d45f1f85\n# ╠═82af41ba-d9b9-4ce2-8736-6fe32c8e024e\n# ╟─9c5021f3-67ab-464d-8f22-25e269c36083\n# ╠═b6ff5052-04ec-11eb-043b-458c42b19edb\n# ╠═b0340ca3-02d5-49a9-841b-7827e4aee2bb\n", "meta": {"hexsha": "e73d2725a1b459daa6f5a0d756ef506468af81bf", "size": 6471, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "equilibrium-binding-simulation.jl", "max_stars_repo_name": "Guillawme/julia-curve-fitting", "max_stars_repo_head_hexsha": "c1b97935f551da6037ff75e8e18e6f2645623229", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "equilibrium-binding-simulation.jl", "max_issues_repo_name": "Guillawme/julia-curve-fitting", "max_issues_repo_head_hexsha": "c1b97935f551da6037ff75e8e18e6f2645623229", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "equilibrium-binding-simulation.jl", "max_forks_repo_name": "Guillawme/julia-curve-fitting", "max_forks_repo_head_hexsha": "c1b97935f551da6037ff75e8e18e6f2645623229", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-28T18:35:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-28T18:35:20.000Z", "avg_line_length": 34.2380952381, "max_line_length": 303, "alphanum_fraction": 0.7168907433, "num_tokens": 2579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099069987088004, "lm_q2_score": 0.8824278680004707, "lm_q1q2_score": 0.8029272929493138}} {"text": "\"\"\"\n# module FiniteDifference\n\n\n\n# Examples\n\n```jldoctest\njulia>\n```\n\"\"\"\nmodule FiniteDifference\n\nusing BandedMatrices\n\nexport forward_difference_matrix,\n backward_difference_matrix,\n cyclic_difference_matrix,\n centered_difference_matrix\n\n\"\"\"\n forward_difference_matrix(T::Type{<:Number}, shape::NTuple{N,<:Number})\n\nCreate a forward difference matrix.\n\nThe default type of returned value `A` is a `BandedMatrix`.\nIf you want a regular `Matrix`, run `Matrix(A)`.\n\"\"\"\nfunction forward_difference_matrix(T::Type{<:Number}, shape::NTuple{N,<:Number}) where {N}\n A = BandedMatrix(-Ones{T}(shape), (0, 1))\n A[band(1)] .= 1\n return A\nend\n\n\"\"\"\n backward_difference_matrix(T::Type{<:Number}, shape::NTuple{N,<:Number})\n\nCreate a backward difference matrix.\n\nThe default type of returned value `A` is a `BandedMatrix`.\nIf you want a regular `Matrix`, run `Matrix(A)`.\n\"\"\"\nfunction backward_difference_matrix(T::Type{<:Number}, shape::NTuple{N,<:Number}) where {N} # I am unsure about this construction.\n A = BandedMatrix(Ones{T}(shape), (1, 0))\n A[band(-1)] .= -1\n return A\nend\n\nfunction cyclic_difference_matrix(T::Type{<:Number}, shape::NTuple{N,<:Number}) where {N}\n A = BandedMatrix(Ones{T}(shape), (1, 0))\n A[band(-1)] .= -1\n B = Matrix(A)\n B[1, end] = -1\n return B\nend\n\nfunction centered_difference_matrix(T::Type{<:Number}, shape::NTuple{N,<:Number}) where {N}\n A = BandedMatrix(Zeros{T}(shape), (1, 1))\n A[band(-1)] .= -1\n A[band(1)] .= 1\n return A\nend\n\nend", "meta": {"hexsha": "3134fe048b2f09e7e082edcb1e244832c9edd640", "size": 1517, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/FiniteDifference/FiniteDifference.jl", "max_stars_repo_name": "singularitti/APMAE4001.jl", "max_stars_repo_head_hexsha": "98f41ee9f41423ab177966a23d83b0b66b25dc2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/FiniteDifference/FiniteDifference.jl", "max_issues_repo_name": "singularitti/APMAE4001.jl", "max_issues_repo_head_hexsha": "98f41ee9f41423ab177966a23d83b0b66b25dc2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-02-08T14:18:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-08T14:18:11.000Z", "max_forks_repo_path": "src/FiniteDifference/FiniteDifference.jl", "max_forks_repo_name": "singularitti/APMAE4001.jl", "max_forks_repo_head_hexsha": "98f41ee9f41423ab177966a23d83b0b66b25dc2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:17:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:17:52.000Z", "avg_line_length": 23.703125, "max_line_length": 131, "alphanum_fraction": 0.6684245221, "num_tokens": 456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.8688267728417087, "lm_q1q2_score": 0.8029191551002063}} {"text": "# Elementary row operations\n\nexport row_swap!, row_scale!, row_add_mult!\n\n\n\"\"\"\n`row_swap!(A,i,j)` swaps rows `i` and `j` in the matrix `A`.\n\"\"\"\nfunction row_swap!(A::AbstractMatrix{T}, i::Int, j::Int) where {T}\n r, c = size(A)\n @assert (1 <= i <= r) && (1 <= j <= r) \"Row index out of bounds\"\n if i == j\n return\n end\n\n save_row = [A[i, k] for k = 1:c]\n\n for k = 1:c\n @inbounds A[i, k] = A[j, k]\n end\n\n for k = 1:c\n @inbounds A[j, k] = save_row[k]\n end\nend\n\n\"\"\"\n`row_scale!(A,i,s)` multiplies all entries in row `i`\nof `A` by `s`.\n\"\"\"\nfunction row_scale!(A::AbstractMatrix{T}, i::Int, s) where {T}\n r, c = size(A)\n @assert 1 <= i <= r \"Row index out of bounds\"\n\n for k = 1:c\n @inbounds A[i, k] = s * A[i, k]\n end\nend\n\n\n\"\"\"\n`row_add_mult!(A,i,s,j)` adds `s` times row `i` to row `j`\nin the matrix `A`.\n\"\"\"\nfunction row_add_mult!(A::AbstractMatrix{T}, i::Int, s, j::Int) where {T}\n r, c = size(A)\n @assert (1 <= i <= r) && (1 <= j <= r) \"Row index out of bounds\"\n\n save_row = [s * A[i, k] for k = 1:c]\n for k = 1:c\n @inbounds A[j, k] = A[j, k] + save_row[k]\n end\nend\n", "meta": {"hexsha": "ee365d1eed82be3ef4f295bec5d6a916c36e3e24", "size": 1153, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/row_ops.jl", "max_stars_repo_name": "scheinerman/LinearAlgebraX.jl", "max_stars_repo_head_hexsha": "ccb34ba16fc11eb72b6f3ff624bd02310ff69d8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2020-08-04T09:50:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T23:10:44.000Z", "max_issues_repo_path": "src/row_ops.jl", "max_issues_repo_name": "scheinerman/LinearAlgebraX.jl", "max_issues_repo_head_hexsha": "ccb34ba16fc11eb72b6f3ff624bd02310ff69d8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-08-04T11:11:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-12T12:11:30.000Z", "max_forks_repo_path": "src/row_ops.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": 21.3518518519, "max_line_length": 73, "alphanum_fraction": 0.5238508239, "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.8688267694452331, "lm_q1q2_score": 0.8029191537765805}} {"text": "\n# GSA code v0.1.\n# Coded by Jesús Mejía. \n# Based on MATLAB code of Esmat Rashedi, 2010. \n# \" E. Rashedi, H. Nezamabadi-pour and S. Saryazdi,\n# “GSA: A Gravitational Search Algorithm”, Information sciences, vol. 179,\n# no. 13, pp. 2232-2248, 2009.\"\n\nfunction massCalculation(fit,searchType)\n\t####here, make your own function of 'mass calculation'\n\n\tFmax = maximum(fit)\n\tFmin = minimum(fit)\n\tFmean= mean(fit) \n\tN = length(fit)\n\n\tif Fmax == Fmin\n\t\tM = ones(N)\n\telse\n\t\t\n\t\tif searchType == :minimize #for minimization\n\t\t\tbest = Fmin\n\t\t\tworst= Fmax #eq.17-18.\n\t\telse #for maximization\n\t\t\tbest = Fmax\n\t\t\tworst= Fmin #eq.19-20.\n\t\tend\n\t\t\n\t\tM = (fit .- worst) ./ (best .- worst) #eq.15,\n\n\tend\n\n\tM = M ./ sum(M) #eq. 16.\n\t\n\treturn M\n\nend\n\nfunction Gconstant(iteration,max_it)\n\t# here, make your own function of 'G'\n\tα = 20\n\tG0= 100\n\n\tG = G0*exp(-α * iteration / max_it) #eq. 28.\n\n\treturn G\nend\n\n#This function calculates the accelaration of each agent in gravitational field. eq.7-10,21.\nfunction Gfield(M,X,G,Rnorm,Rpower,ElitistCheck,iteration,max_it)\n\tN, D = size(X)\n\tfinal_per= 2 #In the last iteration, only 2 percent of agents apply force to the others.\n\n\t####total force calculation\n\tif ElitistCheck == 1\n\t\tkbest = final_per+(1-iteration/max_it)*(100-final_per) #kbest in eq. 21.\n\t\tkbest = round(Int, N*kbest/100)\n\telse\n\t\tkbest = N #eq.9.\n\tend\n\t\n\tds = sortperm(M, rev=true)\n\n\tE = zeros(N, D)\n\tfor i=1:N\n\t\tfor ii=1:kbest\n\t\t\tj = ds[ii]\n\t\t\tif j != i\n\t\t\t\tR = norm(X[i,:]-X[j,:], Rnorm) #Euclidian distanse.\n\t\t\t\tfor k=1:D \n E[i, k]= E[i,k]+rand() * (M[j]) * ((X[j,k]-X[i,k])/(R^Rpower + eps()))\n\t\t\t\t\t#note that Mp(i)/Mi(i)=1\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend\n\n\t##acceleration\n\ta = E.*G #note that Mp(i)/Mi(i)=1\n\n\treturn a\nend\n\n# This function updates the velocity and position of agents.\nfunction move(X,a,V)\n\t# movement.\n\tN, D = size(X)\n\tV = rand(N, D).*V + a # eq. 11.\n\tX = X + V # eq. 12.\n\n\treturn X, V\nend\n", "meta": {"hexsha": "20afcbe20fe3e7899aa0e7c24cd8a41c680d8b59", "size": 1916, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/algorithms/CGSA/physics.jl", "max_stars_repo_name": "jbytecode/Metaheuristics.jl", "max_stars_repo_head_hexsha": "939c0cd9d92ef06c320480725c809e89e1dc9e14", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 89, "max_stars_repo_stars_event_min_datetime": "2018-03-07T07:11:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:57:16.000Z", "max_issues_repo_path": "src/algorithms/CGSA/physics.jl", "max_issues_repo_name": "jbytecode/Metaheuristics.jl", "max_issues_repo_head_hexsha": "939c0cd9d92ef06c320480725c809e89e1dc9e14", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2021-01-30T23:03:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T15:45:15.000Z", "max_forks_repo_path": "src/algorithms/CGSA/physics.jl", "max_forks_repo_name": "jbytecode/Metaheuristics.jl", "max_forks_repo_head_hexsha": "939c0cd9d92ef06c320480725c809e89e1dc9e14", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-06-08T10:06:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:15:35.000Z", "avg_line_length": 20.6021505376, "max_line_length": 92, "alphanum_fraction": 0.6236951983, "num_tokens": 688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240090865197, "lm_q2_score": 0.855851154320682, "lm_q1q2_score": 0.802894516072644}} {"text": "export proxNuclear!, normNuclear\n\n\"\"\"\n proxNuclear!(x::Vector{T}, λ::Float64; svtShape::NTuple=[],kargs...)\n\napplies singular value soft-thresholding - i.e. the proximal map for the nuclear norm regularization.\n\n# Arguments:\n* `x::Array{T}` - Vector to apply proximal map to\n* `λ::Float64` - regularization paramter\n* `svtShape::NTuple=[]` - size of the underlying matrix\n\"\"\"\nfunction proxNuclear!(x::Vector{T}, λ::Float64; svtShape::NTuple=[],kargs...) where T\n U,S,V = svd(reshape(x, svtShape))\n proxL1!(S,λ)\n x[:] = vec(U*Matrix(Diagonal(S))*V')\nend\n\n\"\"\"\n normNuclear(x::Vector{T}, λ::Float64; svtShape::NTuple=[],kargs...) where T\n\nreturns the value of the nuclear norm regularization term.\nArguments are the same as in `proxNuclear!`\n\"\"\"\nfunction normNuclear(x::Vector{T}, λ::Float64; svtShape::NTuple=[],kargs...) where T\n U,S,V = svd( reshape(x, svtShape) )\n return λ*norm(S,1)\nend\n", "meta": {"hexsha": "f8ee5eb94571e36735f9ac1c305ccbba15f7c3a2", "size": 920, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/proximalMaps/ProxNuclear.jl", "max_stars_repo_name": "alexjaffray/RegularizedLeastSquares.jl", "max_stars_repo_head_hexsha": "2a8fcba5cc270c5683415efa2d2190bb39f19424", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-06-21T03:10:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T02:40:40.000Z", "max_issues_repo_path": "src/proximalMaps/ProxNuclear.jl", "max_issues_repo_name": "alexjaffray/RegularizedLeastSquares.jl", "max_issues_repo_head_hexsha": "2a8fcba5cc270c5683415efa2d2190bb39f19424", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2018-10-28T12:32:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T18:56:24.000Z", "max_forks_repo_path": "src/proximalMaps/ProxNuclear.jl", "max_forks_repo_name": "alexjaffray/RegularizedLeastSquares.jl", "max_forks_repo_head_hexsha": "2a8fcba5cc270c5683415efa2d2190bb39f19424", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-08-13T08:02:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T23:01:39.000Z", "avg_line_length": 31.724137931, "max_line_length": 101, "alphanum_fraction": 0.6684782609, "num_tokens": 283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240073565738, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.802894512867462}} {"text": "using Distributions, StatsBase, HypothesisTests, Plots, Random; pyplot()\nRandom.seed!(0)\n\nn = 25\nN = 10^4\nxGrid = -10:0.001:10\nkGrid = 0:0.01:5\ndist1, dist2 = Exponential(1), Normal()\n\nfunction ksStat(dist)\n data = rand(dist,n)\n Fhat = ecdf(data)\n sqrt(n)*maximum(abs.(Fhat.(xGrid) - cdf.(dist,xGrid)))\nend\n\nkStats1 = [ksStat(dist1) for _ in 1:N]\nkStats2 = [ksStat(dist2) for _ in 1:N]\n\np1 = stephist(kStats1, bins=50, \n\tc=:blue, label=\"KS stat (Exponential)\", normed=true)\np1 = plot!(kGrid, pdf.(Kolmogorov(),kGrid), \n\tc=:red, label=\"Kolmogorov PDF\", xlabel=\"K\", ylabel=\"Density\")\n\np2 = stephist(kStats2, bins=50, \n\tc=:blue, label=\"KS stat (Normal)\", normed=true)\np2 = plot!(kGrid, pdf.(Kolmogorov(),kGrid), \n\tc=:red, label=\"Kolmogorov PDF\", xlabel=\"K\", ylabel=\"Density\")\n\nplot(p1, p2, xlims=(0,2.5), ylims=(0,1.8), size=(800, 400))", "meta": {"hexsha": "1f7f34df2adcc7a4b1cd401061c05b977a335408", "size": 842, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "7_chapter/ksStatistic.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/ksStatistic.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/ksStatistic.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.0344827586, "max_line_length": 72, "alphanum_fraction": 0.6567695962, "num_tokens": 327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377261041521, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.8028903330502197}} {"text": "module Bresenham\n\nfunction line(f, x0::Int, y0::Int, x1::Int, y1::Int)\n dx = 2 * (x1 - x0)\n dy = 2 * (y1 - y0)\n\n if dx != 0\n if dy != 0\n if abs(dx) >= abs(dy)\n e = dx / 2\n y = y0\n for x = x0:sign(dx):x1\n f(x, y)\n # (a) following code runs even if\n # the loop exits after this iteration\n # but we don't care about that side effect\n e -= sign(dx) * sign(dy) * dy\n if sign(dx) > 0 && e < 0 ||\n sign(dx) < 0 && e >= 0\n y += sign(dy)\n e += dx\n end\n end\n else # abs(dx) < abs(dy) (steep case)\n e = dy / 2\n x = x0\n for y = y0:sign(dy):y1\n f(x, y)\n # see (a)\n e -= sign(dx) * sign(dy) * dx\n if sign(dy) > 0 && e < 0 ||\n sign(dy) < 0 && e >= 0\n x += sign(dx)\n e += dy\n end\n end\n end\n else # dy == 0 (horizontal line)\n for x = x0:sign(dx):x1\n f(x, y0)\n end\n end\n else # dx == 0 (vertical line)\n for y = y0:sign(dy):y1\n f(x0, y)\n end\n end\nend # function\n\nfunction circle(f, x0::Int, y0::Int, r::Int)\n x = r - 1\n y = 0\n dx = 1\n dy = 1\n err = dx - (r << 1)\n\n while x >= y\n f(x0 + x, y0 + y)\n f(x0 + y, y0 + x)\n f(x0 - y, y0 + x)\n f(x0 - x, y0 + y)\n f(x0 - x, y0 - y)\n f(x0 - y, y0 - x)\n f(x0 + y, y0 - x)\n f(x0 + x, y0 - y)\n\n if err <= 0\n y += 1\n err += dy\n dy += 2\n end\n\n if err > 0\n x -= 1\n dx += 2\n err += dx - (r << 1)\n end\n end\nend # function\n\nfunction ordered_circle(f, x0::Int, y0::Int, r::Int)\n pts = Vector{Tuple{Int, Int}}()\n Bresenham.circle(x0, y0, r) do x, y\n push!(pts, (x, y))\n end\n\n unique!(sort!(pts, by=(X -> atan(X[2], X[1]))))\n for X in pts\n f(X...)\n end\nend # function\n\nexport line, circle, ordered_circle\n\nend # module\n", "meta": {"hexsha": "17cb7c7a1996dd18041501cb7f2b47d4d5dfb445", "size": 1902, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Bresenham.jl", "max_stars_repo_name": "vtavernier/Bresenham.jl", "max_stars_repo_head_hexsha": "ea5710d27ba87fd259ec909e471e8c8381b5016b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-12-21T04:34:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T05:44:19.000Z", "max_issues_repo_path": "src/Bresenham.jl", "max_issues_repo_name": "vtavernier/Bresenham.jl", "max_issues_repo_head_hexsha": "ea5710d27ba87fd259ec909e471e8c8381b5016b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Bresenham.jl", "max_forks_repo_name": "vtavernier/Bresenham.jl", "max_forks_repo_head_hexsha": "ea5710d27ba87fd259ec909e471e8c8381b5016b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.8125, "max_line_length": 52, "alphanum_fraction": 0.4174553102, "num_tokens": 730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517072737735, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.8028593313786787}} {"text": "geosum(r::Real, n::Integer) = (1 - r^(n + 1)) / (1 - r)\ngeosum(a::Real, r::Real, n::Integer) = a * geosum(r, n)\n\nmonthly_rate(annual_rate::Real) = (1 + annual_rate) ^ (1/12) - 1\n \n\"\"\"\nFuture value. Assumes payments at the beginning of the month.\n\"\"\"\nfunction fv(monthly_payment::Real, annual_rate::Real; months::Integer=0,\n init::Real=0, years::Integer=0)\n months == 0 && (months = years * 12)\n\n r = monthly_rate(annual_rate)\n init_future = init * (1 + r) ^ months\n return geosum(monthly_payment, 1 + r, months) - monthly_payment + init_future\nend\n\n\"\"\"\nComputes monthly payments. Assumes payments at the beginning of the month.\n\"\"\"\nfunction monthly_payment(goal::Real, annual_rate::Real; months::Integer=0,\n years::Integer=0, init::Real=0)\n months == 0 && (months = years * 12)\n r = monthly_rate(annual_rate)\n init_future = init * (1 + r) ^ months\n return (goal - init_future) / (geosum(1 + r, months) - 1)\nend\n", "meta": {"hexsha": "bc8fa772cd1e917ca1256b542bfb66d5e6c1e30d", "size": 954, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/core.jl", "max_stars_repo_name": "luiarthur/FinancialMath.jl", "max_stars_repo_head_hexsha": "57e41bb31112ed47bf26b4d4856b02e9aa136833", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-14T06:44:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T06:44:34.000Z", "max_issues_repo_path": "src/core.jl", "max_issues_repo_name": "luiarthur/FinancialMath.jl", "max_issues_repo_head_hexsha": "57e41bb31112ed47bf26b4d4856b02e9aa136833", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core.jl", "max_forks_repo_name": "luiarthur/FinancialMath.jl", "max_forks_repo_head_hexsha": "57e41bb31112ed47bf26b4d4856b02e9aa136833", "max_forks_repo_licenses": ["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.0714285714, "max_line_length": 79, "alphanum_fraction": 0.641509434, "num_tokens": 296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517061554854, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.8028593284761688}} {"text": "# Example of Bayesian estimation\n# sampling from exponential(theta) distribution\n# lognormal prior\n\n# Shows how likelihood, joint, marginal likelihood,\n# and posterior are formed, and how posterior can be\n# integrated to get posterior mean\n\n# explore different sample sizes, different true thetas\nusing Distributions, Plots\n\nfunction main()\n n = 50 # sample size\n theta = 3 # true theta\n y = rand(Exponential(theta), n) # sample from exponential(theta)\n # make plots\n thetas = range(0.01,stop=10,length=1000)\n delta = thetas[2]-thetas[1]\n p, priormean = prior(thetas)\n post, postmean = posterior(y, thetas)\n plot(thetas, [p post], label = [\"prior\" \"posterior\"])\n plot!([priormean, priormean], [0.0, 1.0], label = \"prior mean\")\n plot!([postmean, postmean], [0.0, 1.0], label = \"posterior mean\")\n\nend\n\n# the prior is lognormal(1,1)\nfunction prior(theta)\n d = LogNormal(1.0,1.0)\n p = pdf.(Ref(d), theta)\n pmean = exp(1.5) # mean of lognormal is exp(mu+sig/2)\n return p, pmean\nend\n\n# the likelihood function\nfunction likelihood(y, theta)\n dens = zeros(size(theta))\n for i = 1:size(theta,1)\n d = Exponential(theta[i])\n dens[i] = prod(pdf.(Ref(d), y))\n end\n return dens\nend\n\n\n# joint is prior X likelihood\nfunction joint(y, theta)\n l = likelihood(y, theta)\n p, junk = prior(theta)\n dens = l.*p\nend\n\n# compute marginal likelihood of Y by integrating out theta (crude, only illustrative)\nfunction marginal(y)\n dens = 0.0\n theta = 0.0\n delta = 0.01\n # evaluate joint over grid\n for r = 1:1000\n theta += delta\n dens += joint(y, theta)\n end\n # marginalize by integrating the joint (sum up height X width)\n dens = dens*delta\nend\n\n# the posterior, by Bayes' Law\nfunction posterior(y, theta)\n m = marginal(y)\n j = joint(y, theta)\n dens = j ./ m\n thetas = range(0.01,stop=10,length=1000)\n pmean = sum(dens.*thetas.*0.01)\n return dens, pmean\nend\n\nmain()\n\n", "meta": {"hexsha": "63301200c917f6194e679dbd3fd207bef0741806", "size": 1977, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/Bayesian/BayesExample1.jl", "max_stars_repo_name": "nilshg/Econometrics", "max_stars_repo_head_hexsha": "195cf9854ddc5ad2218cb08aff8e87b45e8b8866", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 209, "max_stars_repo_stars_event_min_datetime": "2016-02-12T16:41:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T21:18:55.000Z", "max_issues_repo_path": "Examples/Bayesian/BayesExample1.jl", "max_issues_repo_name": "nilshg/Econometrics", "max_issues_repo_head_hexsha": "195cf9854ddc5ad2218cb08aff8e87b45e8b8866", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2019-09-10T12:45:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-05T07:22:46.000Z", "max_forks_repo_path": "Examples/Bayesian/BayesExample1.jl", "max_forks_repo_name": "nilshg/Econometrics", "max_forks_repo_head_hexsha": "195cf9854ddc5ad2218cb08aff8e87b45e8b8866", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 104, "max_forks_repo_forks_event_min_datetime": "2015-12-12T23:46:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T10:10:27.000Z", "avg_line_length": 25.0253164557, "max_line_length": 86, "alphanum_fraction": 0.6474456247, "num_tokens": 591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517028006208, "lm_q2_score": 0.8354835371034369, "lm_q1q2_score": 0.8028593276414334}} {"text": "export fourier_points, fourier_wavenumbers \nusing FFTW\n\"\"\"\nfourier_nodes(n; a = 0, b = 2π)\n\n# Description\n- Create a uniform grid of points for periodic functions\n\n# Arguments\n- `N`: integer | number of evenly spaced points \n\n# Keyword Arguments\n- `a`: number | starting point of interval [a, b)\n- `b`: number | ending point of interval [a, b)\n\n# Return\n- `g`: array | an array of points of evenly spaced points from [a, b)\n\"\"\"\nfunction fourier_nodes(N; a = 0, b = 2π)\n return (b-a) .* collect(0:(N-1))/N .+ a\nend\n\n\n\"\"\"\nfourier_wavenumbers(N; L = 2π)\n\n# Description\n- Create wavenumbers associated with the domain of length L\n\n# Arguments\n- `N`: integer | number of wavevectors\n\n# Keyword Arguments\n- `L`: number | length of interval [a, b), L = b-a\n\n# Return\n- `wavenumbers`: array | an array of wavevectors\n\"\"\"\nfunction fourier_wavenumbers(N; L = 2π)\n up = collect(0:1:N-1)\n down = collect(-N:1:-1)\n indices = up\n indices[div(N,2)+1:end] = down[div(N,2)+1:end]\n wavenumbers = 2π / L .* indices\n return wavenumbers\nend", "meta": {"hexsha": "21b3882c6a36605765e928c969c4a66b53e1689a", "size": 1040, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/spatial_discretization/fourier_utils.jl", "max_stars_repo_name": "upiterbarg/QuasiGeostrophy", "max_stars_repo_head_hexsha": "ba0be019c933916ffc379141c36e83adb10c1c59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-06-16T15:35:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-01T21:10:48.000Z", "max_issues_repo_path": "src/spatial_discretization/fourier_utils.jl", "max_issues_repo_name": "sandreza/QuasiGeostrophy", "max_issues_repo_head_hexsha": "05b6e622e981afebf880e4890d24e2b813087e90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-11-13T17:29:21.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-13T17:29:21.000Z", "max_forks_repo_path": "src/spatial_discretization/fourier_utils.jl", "max_forks_repo_name": "upiterbarg/QuasiGeostrophy", "max_forks_repo_head_hexsha": "ba0be019c933916ffc379141c36e83adb10c1c59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-09T16:24:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-09T16:24:16.000Z", "avg_line_length": 22.6086956522, "max_line_length": 69, "alphanum_fraction": 0.6634615385, "num_tokens": 336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802507195636, "lm_q2_score": 0.8740772368049822, "lm_q1q2_score": 0.8028226796089034}} {"text": "\n\"\"\"\nA simple implementation of calculating edit distance of two strings\n\"\"\"\nfunction edit_distance(s1::ASCIIString, s2::ASCIIString)\n m=length(s1)+1\n n=length(s2)+1\n i=0\n j=0\n tbl = Array{Int64}(m,n)\n for i=1:m\n tbl[i,1]=i-1\n end\n for j=1:n\n tbl[1,j]=j-1\n end\n for i=2:m\n for j=2:n\n cost = s1[i-1] == s2[j-1]?0:1\n tbl[i,j] = min(tbl[i, j-1]+1, tbl[i-1, j]+1, tbl[i-1, j-1]+cost)\n end\n end\n return tbl[i,j]\nend\n\nfunction hamming_distance(s1::ASCIIString, s2::ASCIIString)\n d = 0\n len = min(length(s1), length(s2))\n for i in 1:len\n if s1[i] != s2[i]\n d += 1\n end\n end\n return d\nend\n\nfunction edit_distance(s1::Sequence, s2::Sequence)\n return edit_distance(s1.seq, s2.seq)\nend\n\nfunction hamming_distance(s1::Sequence, s2::Sequence)\n return hamming_distance(s1.seq, s2.seq)\nend", "meta": {"hexsha": "b7c586f6803e6194e9c0f1ea44506177957470f5", "size": 906, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Algorithm/distance.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/OpenGene.jl-63bcc5cb-6a41-5765-9feb-b5d792dd5d92", "max_stars_repo_head_hexsha": "b1dac40385b7201bdb4ca13d45418fbb688bce35", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 79, "max_stars_repo_stars_event_min_datetime": "2015-12-10T01:34:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T14:09:20.000Z", "max_issues_repo_path": "src/Algorithm/distance.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/OpenGene.jl-63bcc5cb-6a41-5765-9feb-b5d792dd5d92", "max_issues_repo_head_hexsha": "b1dac40385b7201bdb4ca13d45418fbb688bce35", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2015-12-20T02:01:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-02T06:42:24.000Z", "max_forks_repo_path": "src/Algorithm/distance.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/OpenGene.jl-63bcc5cb-6a41-5765-9feb-b5d792dd5d92", "max_forks_repo_head_hexsha": "b1dac40385b7201bdb4ca13d45418fbb688bce35", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 22, "max_forks_repo_forks_event_min_datetime": "2015-12-18T13:07:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T19:06:07.000Z", "avg_line_length": 21.0697674419, "max_line_length": 76, "alphanum_fraction": 0.5706401766, "num_tokens": 316, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.8740772400852111, "lm_q1q2_score": 0.802822678720849}} {"text": "#= \nExample 2: Fit a linear model first, then add a further component and\nfit a quadratic model.\n\nThis example is very similar to #1, but it shows how to check for\ngoodness of fit, and how to add a new component to obtain a better fit.\n=#\nusing Random, DataFitting\n\n# \"True\" parameter values:\np0 = 1.\np1 = 2.\np2 = 3.\n\n# Evaluate the model with \"True\" parameters\nx = 0.:0.1:10;\ny = collect(p0 .+ p1 .* x .+ p2 .* x.^2);\n\n# Add some noise to simulate a measurement process\nnoise = 1.\ny .+= noise .* randn(length(x));\n\n# Wrap empirical measures and uncertainties in a `Measure` object\ndata = Measures(y, noise)\n\n# Prepare the model. Note that we start with an empty model, and add\n# the components one by one:\nmodel = Model()\nadd_comp!(model, :p0 => 1) # add 1st component\nadd_comp!(model, :p1 => 2) # add 2nd component\nadd_dom!(model, x) # set domain\nadd_expr!(model, :(p0 .+ p1 .* domain[1])) # add model expression\n\n# Fit the model to empirical data\nresult = fit!(model, data)\n\n# Plot data and best fit model\nusing Gnuplot\n@gp domain(model) data.val data.unc \"w yerr t 'Data'\" :- \n@gp :- domain(model) model() \"w line t 'Model'\"\n\n# Print the reduced chi-squared and the probability that random noise\n# may lead to higher chi-squared values. Note that the latter is\n# given as logarithmic value\nprintln(\"Red. χ^2 = \", result.cost / result.dof)\nprintln(\"Test probability = \", 10^result.log10testprob)\n\n# Clearly this is not a good fit. Let's add a 3rd `ScalarParam`\n# component to obtain a quadratic model\nadd_comp!(model, :p2 => 3) # add 3rd component\n\n# Replace model expression\nreplaceexpr!(model, :(p0 .+ p1 .* domain[1] .+ p2 .* domain[1].^2))\n\n# Fit model to empirical data and plot\nresult = fit!(model, data)\n@gp domain(model) data.val data.unc \"w yerr t 'Data'\" :- \n@gp :- domain(model) model() \"w line t 'Model'\"\n\n# Compare \"true\" parameter values with best fit ones:\nusing Printf\n@printf \"%f ∼ %f (accuracy: %5.3f%%)\" p0 result.p0.par.val 100. * (result.p0.par.val-p0) / p0\n@printf \"%f ∼ %f (accuracy: %5.3f%%)\" p1 result.p1.par.val 100. * (result.p1.par.val-p1) / p1\n@printf \"%f ∼ %f (accuracy: %5.3f%%)\" p2 result.p2.par.val 100. * (result.p2.par.val-p2) / p2\n", "meta": {"hexsha": "aae80e1e5dbc03ac227be35c3a9c8fb2e1e6dc01", "size": 2221, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/02_quadratic.jl", "max_stars_repo_name": "gcalderone/ModelFit.jl", "max_stars_repo_head_hexsha": "7a3b0c7eeb4e1bc1b0239074680a659bd3ee71b8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2018-09-04T06:57:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-07T01:01:56.000Z", "max_issues_repo_path": "examples/02_quadratic.jl", "max_issues_repo_name": "gcalderone/ModelFit.jl", "max_issues_repo_head_hexsha": "7a3b0c7eeb4e1bc1b0239074680a659bd3ee71b8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-07-16T16:29:07.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-16T16:29:07.000Z", "max_forks_repo_path": "examples/02_quadratic.jl", "max_forks_repo_name": "gcalderone/ModelFit.jl", "max_forks_repo_head_hexsha": "7a3b0c7eeb4e1bc1b0239074680a659bd3ee71b8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-08-06T05:20:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-04T05:57:12.000Z", "avg_line_length": 34.1692307692, "max_line_length": 94, "alphanum_fraction": 0.6668167492, "num_tokens": 699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.8887587824432528, "lm_q1q2_score": 0.8028106593381829}} {"text": "using LinearAlgebra\nusing SparseArrays\nusing Plots\n\n\"This code solves the 2D Laplace's equation with nonzero Dirichlet and Neumann\nboundary conditions using a finite difference method.\"\n\nm = 100 # number of points\nx = LinRange(-1,1,m+2)\ny = LinRange(-1,1,m+2)\nxint = x[2:end-1]\nyint = y[2:end-1]\nh = x[2]-x[1]\n\n# ordering of unknowns\n# u14 u24 u34 u44\n# u13 u23 u33 u43\n# u12 u22 u32 u42\n# u11 u21 u31 u41\n\nid(i,j,m) = i + (j-1)*m # return global index from i,j\nfunction FD_matrix_2D(h,m)\n A = spzeros(m*m,m*m)\n for i = 1:m, j = 1:m # loop thru 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\nend\n\nA = FD_matrix_2D(h,m)\n\nf(x,y) = exp(-10*((x-.25)^2 + (y-.75)^2))\n# f(x,y) = 1.0\nb = vec(f.(xint,yint'))\n\n# solve Au = f(xi,yj)\nu = A\\vec(b)\ncontourf(xint,yint,u)\n", "meta": {"hexsha": "09d317f44b094a8d58e0057acea371302089af03", "size": 1181, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "week5/fd_laplace_2D.jl", "max_stars_repo_name": "jlchan/caam452_s21", "max_stars_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-01-29T01:52:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T15:38:43.000Z", "max_issues_repo_path": "week5/fd_laplace_2D.jl", "max_issues_repo_name": "jlchan/caam452_s21", "max_issues_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week5/fd_laplace_2D.jl", "max_forks_repo_name": "jlchan/caam452_s21", "max_forks_repo_head_hexsha": "f52930a56c42544ba047571bf3a08d58364cb85f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1568627451, "max_line_length": 78, "alphanum_fraction": 0.5529212532, "num_tokens": 461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813513911654, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.8027700113072374}} {"text": "\n\"\"\"\n poisson_time(a, b, u)\n\nObtaining waiting time for inhomogeneous Poisson Process\nwith rate of the form λ(t) = (a + b*t)^+, `a`,`b` ∈ R, `u` uniform random variable\n\"\"\"\nfunction poisson_time(a, b, u)\n if b > 0\n if a < 0\n return sqrt(-log(u)*2.0/b) - a/b\n else # a[i]>0\n return sqrt((a/b)^2 - log(u)*2.0/b) - a/b\n end\n elseif b == 0\n if a > 0\n return -log(u)/a\n else # a[i] <= 0\n return Inf\n end\n else # b[i] < 0\n if a <= 0\n return Inf\n elseif -log(u) <= -a^2/b + a^2/(2*b)\n return -sqrt((a/b)^2 - log(u)*2.0/b) - a/b\n else\n return Inf\n end\n end\nend\n\n\"\"\"\n poisson_time((a, b, c), u)\n\nObtaining waiting time for inhomogeneous Poisson Process\nwith rate of the form λ(t) = c + (a + b*t)^+, \nwhere `c`> 0 ,`a, b` ∈ R, `u` uniform random variable\n\"\"\"\nfunction poisson_time((a,b,c)::NTuple{3}, u)\n if b > 0\n if a < 0\n if -c*a/b + log(u) < 0.0\n return sqrt(-2*b*log(u) + c^2 + 2*a*c)/b - (a+c)/b\n else\n return -log(u)/c\n end\n else # a >0\n return sqrt(-log(u)*2.0*b + (a+c)^2)/b - (a+c)/b\n end\n elseif b == 0\n if a > 0\n return -log(u)/(a + c)\n else # a <= 0\n return -log(u)/c\n end\n else # b < 0\n if a <= 0.0 \n return -log(u)/c\n elseif - c*a/b - a^2/(2*b) + log(u) > 0.0\n return +sqrt((a+c)^2 - 2.0*log(u)*b)/b - (a+c)/b\n else\n return (-log(u)+ a^2/(2*b))/c\n end\n end\nend\n\n\"\"\"\n poisson_time(a[, u])\n\nObtaining waiting time for homogeneous Poisson Process\nwith rate of the form λ(t) = a, `a` ≥ 0, `u` uniform random variable\n\"\"\"\nfunction poisson_time(a::Number, u::Number)\n -log(u)/a\nend\n\nfunction poisson_time(rng, a)\n randexp(rng)/a\nend\nfunction poisson_time(a)\n randexp()/a\nend\n\npoisson_time((a, b)::Tuple, u=randn()) = poisson_time(a, b, u)\n", "meta": {"hexsha": "d6472829978f5a7711d631873b1b29ff6e84d102", "size": 2028, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/poissontime.jl", "max_stars_repo_name": "vincentmolin/ZigZagBoomerang.jl", "max_stars_repo_head_hexsha": "40a318230854d5e1f560ea54ec46c1b970ce116e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 60, "max_stars_repo_stars_event_min_datetime": "2020-07-02T12:59:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T13:07:02.000Z", "max_issues_repo_path": "src/poissontime.jl", "max_issues_repo_name": "vincentmolin/ZigZagBoomerang.jl", "max_issues_repo_head_hexsha": "40a318230854d5e1f560ea54ec46c1b970ce116e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 47, "max_issues_repo_issues_event_min_datetime": "2020-07-02T10:13:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T15:38:42.000Z", "max_forks_repo_path": "src/poissontime.jl", "max_forks_repo_name": "vincentmolin/ZigZagBoomerang.jl", "max_forks_repo_head_hexsha": "40a318230854d5e1f560ea54ec46c1b970ce116e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-07-02T16:25:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T11:51:27.000Z", "avg_line_length": 23.8588235294, "max_line_length": 82, "alphanum_fraction": 0.4728796844, "num_tokens": 708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172688214138, "lm_q2_score": 0.8459424392504908, "lm_q1q2_score": 0.8027293890337005}} {"text": "BigFloat(1.75) # Accidentally OK, since 1.75 is exactly represented by Float64\n\nBigFloat(2.1) # First rounded to Float64, low precision\n\nparse(BigFloat, \"2.1\") # High precision\n\nsetprecision(512) do\n BigFloat(1) / BigFloat(3)\nend\n\ndisplay(BigFloat(pi))\ndisplay(sin(BigFloat(pi)))\n\nfunction halley_cuberoot(a, ε)\n x = 1 # Initial guess\n Δx = 1 # Need to initialize to get started\n while Δx ≥ ε\n xnew = x - 2(x^3 - a)*3x^2 / (2(3x^2)^2 - (x^3 - a)*(6x))\n Δx = abs(xnew - x)\n x = xnew\n println(\"Error = \", abs(x - cbrt(a)))\n end\n x\nend\n\nhalley_cuberoot(BigFloat(2), 1e-60)\n", "meta": {"hexsha": "e30e37b2fbec44f9a9d6f34670a94fe40aab8797", "size": 653, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "textbook/_build/jupyter_execute/content/Data_Types/Arbitrary_Precision_Floats.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/Data_Types/Arbitrary_Precision_Floats.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/Data_Types/Arbitrary_Precision_Floats.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.1851851852, "max_line_length": 91, "alphanum_fraction": 0.5803981623, "num_tokens": 228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172630429475, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.8027293841454508}} {"text": "# ===========================================================\n# Concrete overapproximation with a ball in the infinity norm\n# ===========================================================\n\n\"\"\"\n ballinf_approximation(S::LazySet)\n\nOverapproximate a set by a tight ball in the infinity norm.\n\n### Input\n\n- `S` -- set\n\n### Output\n\nA tight ball in the infinity norm.\n\n### Algorithm\n\nThe center and radius of the box are obtained by evaluating the support function\nof the given convex set along the canonical directions.\n\"\"\"\nfunction ballinf_approximation(S::LazySet{N}) where {N}\n n = dim(S)\n c = Vector{N}(undef, n)\n r = zero(N)\n d = zeros(N, n)\n\n @inbounds for i in 1:n\n d[i] = one(N)\n htop = ρ(d, S)\n d[i] = -one(N)\n hbottom = -ρ(d, S)\n d[i] = zero(N)\n c[i] = (htop + hbottom) / 2\n rcur = (htop - hbottom) / 2\n if (rcur > r)\n r = rcur\n elseif rcur < 0\n # contradicting bounds => set is empty\n return EmptySet{N}(dim(S))\n end\n end\n return BallInf(c, r)\nend\n\n# ===============\n# Specializations\n# ===============\n\n# empty set specialization\nballinf_approximation(∅::EmptySet) = ∅\n", "meta": {"hexsha": "83d1c7d6cd4ebb86c0e8a1a1455e957ce0755b66", "size": 1201, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Approximations/ballinf_approximation.jl", "max_stars_repo_name": "goretkin/LazySets.jl", "max_stars_repo_head_hexsha": "6e829d9179bc25b8d7f6afb190a015e53760c601", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Approximations/ballinf_approximation.jl", "max_issues_repo_name": "goretkin/LazySets.jl", "max_issues_repo_head_hexsha": "6e829d9179bc25b8d7f6afb190a015e53760c601", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Approximations/ballinf_approximation.jl", "max_forks_repo_name": "goretkin/LazySets.jl", "max_forks_repo_head_hexsha": "6e829d9179bc25b8d7f6afb190a015e53760c601", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6603773585, "max_line_length": 80, "alphanum_fraction": 0.5095753539, "num_tokens": 318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172644875641, "lm_q2_score": 0.8459424353665382, "lm_q1q2_score": 0.8027293816819634}} {"text": "export SoftPlus\n\n\"\"\"\n`SoftPlus([domainType=Float64::Type,] dim_in::Tuple)`\n\nCreates the softplus non-linear operator with input dimensions `dim_in`.\n```math\n\\\\sigma(\\\\mathbf{x}) = \\\\log (1 + e^{x} )\n```\n\n\"\"\"\nstruct SoftPlus{T,N} <: NonLinearOperator\n\tdim::NTuple{N,Int}\nend\n\nfunction SoftPlus(DomainType::Type, DomainDim::NTuple{N,Int}) where {N} \n\tSoftPlus{DomainType,N}(DomainDim)\nend\n\nSoftPlus(DomainDim::NTuple{N,Int}) where {N} = SoftPlus{Float64,N}(DomainDim)\n\nfunction mul!(y::AbstractArray{T,N}, L::SoftPlus{T,N}, x::AbstractArray{T,N}) where {T,N}\n\ty .= log.(1 .+exp.(x))\nend\n\nfunction mul!(y::AbstractArray, \n J::AdjointOperator{Jacobian{A,TT}}, \n b::AbstractArray) where {T, N, A <: SoftPlus{T,N}, TT <: AbstractArray{T,N} }\n L = J.A\n\ty .= 1 ./(1 .+exp.(-L.x)).*b\nend\n\nfun_name(L::SoftPlus) = \"σ\"\n\nsize(L::SoftPlus) = (L.dim, L.dim)\n\ndomainType(L::SoftPlus{T,N}) where {T,N} = T\ncodomainType(L::SoftPlus{T,N}) where {T,N} = T\n", "meta": {"hexsha": "0ee54b160276646793f1fa2457a666713adebe34", "size": 966, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nonlinearoperators/SoftPlus.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/SoftPlus.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/SoftPlus.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.7692307692, "max_line_length": 91, "alphanum_fraction": 0.6387163561, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172587090974, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.802729380479263}} {"text": "using BenchmarkTools\nusing Distributions\nusing GLM\nusing HypothesisTests\nusing LinearAlgebra\nusing Plots\nusing Random\nusing RDatasets\nusing SpecialFunctions\nusing Statistics\n\n\n\n\n# Ridge regression\n\nn = 10000\nm = 1000\n\nRandom.seed!(666)\nX = randn(n, m)\n\ny = 10*X[:,1] + X[:,2] + randn(n)\n\n# Exercise\n\nridge_reg(X, y, μ) = (X'*X + μ*I) \\ (X'*y)\n\neigen_dec = eigen(X'*X)\nQ = eigen_dec.vectors\nQ_inv = Matrix(Q')\nλ = eigen_dec.values\n\nridge_reg(X, y, μ, Q, Q_inv, λ) = Q * ((Diagonal(1 ./ (λ .+ μ)) * ( Q_inv * (X'*y))))\n\nw1 = ridge_reg(X, y, 10)\nw2 = ridge_reg(X, y, 10, Q, Q_inv, λ)\n\nnorm(w1 - w2)\n\n# Comparison\n\n@btime ridge_reg(X, y, 10);\n\n@btime ridge_reg(X, y, 10, Q, Q_inv, λ);\n\n# Dependence on mu\n\nμs = range(0, 1000; length=50)\n\nws = hcat(ridge_reg.(Ref(X), Ref(y), μs, Ref(Q), Ref(Q_inv), Ref(λ))...)\n\nplot(μs, abs.(ws');\n label=\"\",\n yscale=:log10,\n xlabel=\"mu\",\n ylabel=\"weights: log scale\",\n)\n\n# LASSO\n\nS(x, η) = max(x-η, 0) - max(-x-η, 0)\n\nfunction lasso(X, y, μ, Q, Q_inv, λ; \n max_iter = 100,\n ρ = 1e3,\n w = zeros(size(X,2)),\n u = zeros(size(X,2)),\n z = zeros(size(X,2)),\n )\n \n for i in 1:max_iter\n w = Q * ( (Diagonal(1 ./ (λ .+ ρ)) * ( Q_inv * (X'*y + ρ*(z-u))))) \n z = S.(w + u, μ / ρ)\n u = u + w - z\n end\n return w, u, z \nend\n\nws = zeros(size(X,2), length(μs))\n\nfor (i, μ) in enumerate(μs)\n global w, u, z\n w, u, z = i > 1 ? lasso(X, y, μ, Q, Q_inv, λ; w, u, z) : lasso(X, y, μ, Q, Q_inv, λ)\n ws[:,i] = w\nend\n\nplot(μs, abs.(ws');\n label=\"\",\n yscale=:log10,\n xlabel=\"mu\",\n ylabel=\"weights: log scale\",\n)\n\n\n\n\n\n\nplot(0:0.1:10, gamma;\n xlabel=\"x\",\n ylabel=\"gamma(x): log scale\",\n label=\"\",\n yscale=:log10,\n)\n\n# Exercise\n\nvolume_true(m, R) = π^(m/2) *R^2 / gamma(m/2 + 1)\n\nplot(1:100, m -> volume_true.(m, 1);\n xlabel=\"dimension\",\n ylabel=\"unit ball volume: log scale\",\n label=\"\",\n yscale=:log10,\n)\n\n# Exercise\n\nfunction volume_monte_carlo(m::Int; n::Int=10000)\n X = 2*rand(m, n).-1\n X_norm_sq = sum(X.^2; dims=1)\n return 2^m*mean(X_norm_sq .<= 1)\nend\n\n# Volume of a ball\n\nms = 1:15\nns = Int64.([1e1; 1e3; 1e5])\n\nRandom.seed!(666)\n\nplt = plot(ms, m -> volume_true(m, 1);\n xlabel=\"dimension\",\n ylabel=\"unit ball volume\",\n legend=:topleft,\n label=\"True\",\n line=(4,:black),\n)\n\nfor n in ns\n plot!(plt, ms, m -> volume_monte_carlo.(m; n=n); label=\"n = $n\")\nend\n\ndisplay(plt)\n\n# Generating from the uniform distributions\n\nrand(Uniform(-1, 1), 10, 5)\n\n# Sampling from distributions\n\nd1 = Normal()\nd2 = Normal(1, 1)\nd3 = Normal(0, 0.01)\n\nf1(x) = pdf(d1, x)\nf2(x) = pdf(d2, x)\nf3(x) = pdf(d3, x)\n\nfunction plot_histogram(xs, f; kwargs...)\n plt = histogram(xs;\n label=\"Sampled density\",\n xlabel = \"x\",\n ylabel = \"pdf(x)\",\n nbins = 85,\n normalize = :pdf,\n opacity = 0.5,\n kwargs...\n )\n\n plot!(plt, range(minimum(xs), maximum(xs); length=100), f;\n label=\"True density\",\n line=(4,:black),\n )\n\n return plt\nend\n\nplot_histogram(rand(d1, 1000000), f1)\n\n# Exercise\n\nfunction rejection_sampling(f, f_max, x_min, x_max; n=1000000)\n xs = x_min .+ (x_max - x_min)*rand(n)\n ps = f_max*rand(n)\n return xs[f.(xs) .>= ps]\nend\n\n# Rejection sampling\n\nxlims = (-10, 10)\n\nfor (f, d) in zip((f1, f2, f3), (d1, d2, d3))\n Random.seed!(666)\n xs = rejection_sampling(f, f(d.μ), xlims...)\n\n pl = plot_histogram(xs, f)\n display(pl)\nend\n\n# Exercise\n\nn = 1000\nm = 9\n\nRandom.seed!(666)\nxs = rand(m, n)\n\ndist1 = [norm(x-y) for x in eachcol(xs), y in eachcol(xs)]\ndist2 = [dist1[i,j] for i in 1:n for j in i+1:n]\n\nextrema(dist2)\n\n\n\n\n\n\n\n\n\n# Hypothesis testing\n\nRandom.seed!(666)\n\nn = 1000\nxs = randn(n)\n\n# Exercise\n\nt = mean(xs) / std(xs) * sqrt(n)\n\nprob = cdf(TDist(n-1), t)\np = 2*min(prob, 1-prob)\n\n# One-sample t-test\n\nOneSampleTTest(xs)\n\n# Linear models\n\nwages = dataset(\"plm\", \"Snmesp\")\nwages.W = 2. .^ (wages.W)\n\n\nX = Matrix(wages[:, [:N, :Y, :I, :K, :F]])\nX = hcat(ones(size(X,1)), X)\ny = wages[:, :W]\n\nw0 = (X'*X) \\ (X'*y)\n\nmodel = lm(@formula(W ~ 1 + N + Y + I + K + F), wages)\n\n# Exercise\n\nnorm(coef(model) - w0)\n\nmodel_red = lm(@formula(W ~ 1 + N + Y + I + F), wages)\n\n(r2(model), r2(model_red))\n\n# Plot histograms\n\ny_hat = predict(model)\n\nplot_histogram(y_hat, x -> pdf(Normal(mean(y_hat), std(y_hat)), x))\n\nplot_histogram(y_hat, x -> pdf(fit(Normal, y_hat), x))\n\ntest_normality = ExactOneSampleKSTest(y_hat, Normal(mean(y_hat), std(y_hat)))\n\n# Generalized linear models\n\nmodel = glm(@formula(W ~ 1 + N + Y + I + K + F), wages, InverseGaussian(), SqrtLink())\n\n# Exercise\n\ng_inv(z) = z^2\n\ny_hat = g_inv.(X*coef(model))\n\nscatter(y, y_hat;\n label=\"\",\n xlabel=\"Label\",\n ylabel=\"Prediction\",\n)\n\n\n", "meta": {"hexsha": "9294b8a1ab523776dc725408446082649822c782", "size": 4741, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/lecture_11/script_sol.jl", "max_stars_repo_name": "petrmvala/JuliaCourse", "max_stars_repo_head_hexsha": "8169ec94eb06d0c6fe098a06ea5d061b16ab6556", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/lecture_11/script_sol.jl", "max_issues_repo_name": "petrmvala/JuliaCourse", "max_issues_repo_head_hexsha": "8169ec94eb06d0c6fe098a06ea5d061b16ab6556", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/lecture_11/script_sol.jl", "max_forks_repo_name": "petrmvala/JuliaCourse", "max_forks_repo_head_hexsha": "8169ec94eb06d0c6fe098a06ea5d061b16ab6556", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-09T10:36:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-09T10:36:10.000Z", "avg_line_length": 16.3482758621, "max_line_length": 88, "alphanum_fraction": 0.5673908458, "num_tokens": 1732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172601537141, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.8027293798585508}} {"text": "# Higham Test Matrices\n\n\"\"\"\nHilbert Matrix\n==============\nThe Hilbert matrix has `(i,j)` element `1/(i+j-1)`. It is\nnotorious for being ill conditioned. It is symmetric\npositive definite and totally positive.\n\n*Input options:*\n\n+ [type,] dim: the dimension of the matrix.\n\n+ [type,] row_dim, col_dim: the row and column dimensions.\n\n*Groups:* [\"inverse\", \"illcond\", \"symmetric\", \"posdef\"]\n\n*References:*\n\n**M. D. Choi**, Tricks or treats with the Hilbert matrix,\nAmer. Math. Monthly, 90 (1983), pp. 301-312.\n\n**N. J. Higham**, Accuracy and Stability of Numerical Algorithms,\nsecond edition, Society for Industrial and Applied Mathematics,\nPhiladelphia, PA, USA, 2002; sec. 28.1.\n\"\"\"\nfunction hilb(::Type{T}, m::Integer, n::Integer) where T\n # compute the Hilbert matrix\n H = zeros(T, m, n)\n for j = 1:n, i= 1:m\n @inbounds H[i,j] = one(T)/ (i + j - one(T))\n end\n return H\nend\nhilb(::Type{T}, n::Integer) where T = hilb(T, n, n)\nhilb(args...) = hilb(Float64, args...)\nhilb(::Type, args...) = throw(MethodError(hilb, Tuple(args)))\n\n\"\"\"\nInverse of the Hilbert Matrix\n=============================\n*Input options:*\n\n+ [type,] dim: the dimension of the matrix.\n\n*Groups:* [\"inverse\", \"illcond\", \"symmetric\",\"posdef\"]\n\n*References:*\n\n**M. D. Choi**, Tricks or treats with the Hilbert matrix,\n Amer. Math. Monthly, 90 (1983), pp. 301-312.\n\n**N. J. Higham**, Accuracy and Stability of Numerical Algorithms, second\n edition, Society for Industrial and Applied Mathematics, Philadelphia, PA,\n USA, 2002; sec. 28.1.\n\"\"\"\nfunction invhilb(::Type{T}, n::Integer) where T\n # compute the inverse of Hilbert matrix\n # Type: data type\n # n: the dimension of the matrix\n Inv = zeros(T, n, n)\n for i = 1:n, j = 1:n\n Inv[i,j] = (-1)^(i+j)*(i+j-1)*binomial(n+i-1, n-j)*\n binomial(n+j-1,n-i)*binomial(i+j-2,i-1)^2\n end\n return Inv\nend\ninvhilb(n::Integer) = invhilb(Float64, n)\n\n\"\"\"\nHadamard Matrix\n===============\nThe Hadamard matrix is a square matrix whose entries are\n1 or -1. It was named after Jacques Hadamard. The rows of\na Hadamard matrix are orthogonal.\n\n*Input options:*\n\n+ [type,] dim: the dimension of the matrix, `dim` is a power of 2.\n\n*Groups:* [\"inverse\", \"orthogonal\", \"eigen\"]\n\n*References:*\n\n**S. W. Golomb and L. D. Baumert**, The search for\nHadamard matrices, Amer. Math. Monthly, 70 (1963) pp. 12-17\n\"\"\"\nfunction hadamard(::Type{T}, n::Integer) where T\n #Compute the hadamard matrix\n if n < 1\n lgn = 0\n else\n lgn = round(Integer, log2(n))\n end\n 2^lgn != n && throw(ArgumentError(\"n must be positive integer and a power of 2.\"))\n\n H = reshape(T[1], 1, 1)\n for i = 1:lgn\n H = [[H H]; [H -H]]\n end\n return H\nend\nhadamard(n::Integer) = hadamard(Float64, n)\n\n\"\"\"\nCauchy Matrix\n=============\nGiven two vectors `x` and `y`, the `(i,j)` entry of the Cauchy matrix is\n`1/(x[i]+y[j])`.\n\n*Input options*:\n\n + [type,] x, y: two vectors.\n\n + [type,] x: a vector. `y` defaults to `x`.\n\n + [type,] dim: the dimension of the matrix. `x` and `y` default to\n `[1:dim;]`.\n\n*Groups:* [\"inverse\", \"illcond\", \"symmetric\", \"posdef\"]\n\n*References:*\n\n**N. J. Higham**, Accuracy and Stability of Numerical Algorithms,\nsecond edition, Society for Industrial and Applied Mathematics, Philadelphia, PA, USA,\n2002; sec. 28.1\n\"\"\"\nfunction cauchy(::Type{T}, x::Vector, y::Vector) where T\n # Compute the cauchy matrix\n m = size(x,1)\n n = size(y,1)\n C = zeros(T, m, n)\n [C[i,j]= one(T)/(x[i] + y[j]) for i = 1:m, j = 1:n]\n return C\nend\n\ncauchy(::Type{T}, x::Vector) where T = cauchy(T, x, x)\ncauchy(::Type{T}, k::Integer) where T = cauchy(T, [1:k;])\ncauchy(arg...) = cauchy(Float64, arg...)\ncauchy(::Type, args...) = throw(MethodError(cauchy, Tuple(args)))\n\n\"\"\"\nCirculant Matrix\n================\nA circulant matrix has the property that each row is obtained\nby cyclically permuting the entries of the previous row one\nstep forward.\n\n*Input options:*\n\n+ [type,] vec, col_dim: a vector and the column dimension.\n\n+ [type,] vec: a vector.\n\n+ [type,] dim: the dimension of the matrix.\n\n*Groups:* [\"symmetric\", \"posdef\", \"eigen\"]\n\n*References:*\n\n**P. J. Davis**, Circulant Matrices, John Wiley, 1977.\n\"\"\"\nfunction circul(::Type{T}, v::Vector, w::Vector) where T\n # Compute the circul matrix\n # v: the first row of the matrix\n # w: the length of the vector is the dimension of the column\n m = length(v)\n n = length(w)\n C = zeros(T, m, n)\n [C[i,j] = v[1 + mod(j - i, n)] for i = 1:m, j = 1:n]\n return C\nend\ncircul(::Type{T}, v::Vector, n::Integer) where T = circul(T, v, T[1:n;])\ncircul(::Type{T}, v::Vector) where T = circul(T, v, v)\ncircul(::Type{T}, k::Integer) where T = circul(T, [1:k;])\ncircul(arg...) = circul(Float64, arg...)\n\n\"\"\"\nDingdong Matrix\n===============\nThe Dingdong matrix is a symmetric Hankel matrix invented\nby DR. F. N. Ris of IBM, Thomas J Watson Research Centre.\nThe eigenvalues cluster around `π/2` and `-π/2`.\n\n*Input options:*\n\n+ [type,] dim: the dimension of the matrix.\n\n*Groups:* [\"symmetric\", \"eigen\"]\n\n*References:*\n\n**J. C. Nash**, Compact Numerical Methods for\nComputers: Linear Algebra and Function Minimisation,\nsecond edition, Adam Hilger, Bristol, 1990 (Appendix 1).\n\"\"\"\nfunction dingdong(::Type{T}, n::Integer) where T\n # Compute the dingdong matrix\n # type: data type\n # n: the dimension of the matrix\n D = zeros(T, n, n)\n [D[i,j] = one(T)/(2*(n-i-j+1.5)) for i = 1:n, j= 1:n]\n return D\nend\ndingdong(args...) = dingdong(Float64, args...)\ndingdong(::Type, args...) = throw(MethodError(dingdong, Tuple(args)))\n\n\"\"\"\nFrank Matrix\n============\nThe Frank matrix is an upper Hessenberg matrix with\ndeterminant 1. The eigenvalues are real, positive and\nvery ill conditioned.\n\n*Input options:*\n\n+ [type,] dim, k: `dim` is the dimension of the matrix, `k = 0 or 1`.\n If `k = 1` the matrix reflect about the anti-diagonal.\n\n+ [type,] dim: the dimension of the matrix.\n\n*Groups:* [\"illcond\", \"eigen\"]\n\n*References:*\n\n**W. L. Frank**, Computing eigenvalues of complex matrices\n by determinant evaluation and by methods of Danilewski and Wielandt,\n J. Soc. Indust. Appl. Math., 6 (1958), pp. 378-392 (see pp. 385, 388).\n\"\"\"\nfunction frank(::Type{T}, n::Integer, k::Integer) where T\n # Compute the frank matrix\n # type: data type\n # n: the dimension of the matrix\n # k = 0 or 1: k = 1 reflect about the anti-diagonal\n p = T[n:-1:1;];\n F = triu(ones(T, n, 1)*p') + diagm(-1 => p[2:n]);\n k == 0 ? F :\n k == 1 ? F[p,p]' : error(\"k = 0 or 1, but get \", k)\nend\nfrank(::Type{T}, n::Integer) where T = frank(T, n, 0)\nfrank(args...) = frank(Float64, args...)\nfrank(::Type, args...) = throw(MethodError(frank, Tuple(args)))\n\n#\n# Jordan block\n#\nfunction jordbloc( n::Integer, lambda::T) where T\n # Generate a n-by-n jordan block with eigenvalue\n # lambda\n J = lambda*Matrix{T}(I, n, n) + diagm(1 => ones(T, n-1, 1)[:,1])\n return J\nend\n\n\"\"\"\nForsythe Matrix\n===============\nThe Forsythe matrix is a n-by-n perturbed Jordan block.\nThis generator is adapted from N. J. Higham's Test Matrix Toolbox.\n\n*Input options:*\n\n+ [type,] dim, alpha, lambda: `dim` is the dimension of the matrix.\n `alpha` and `lambda` are scalars.\n\n+ [type,] dim: `alpha = sqrt(eps(type))` and `lambda = 0`.\n\n\n*Groups:* [\"inverse\", \"illcond\", \"eigen\"]\n\"\"\"\nfunction forsythe(::Type{T}, n::Integer , alpha, lambda) where T\n # Generate the forsythe matrix\n alpha = convert(T, alpha)\n lambda = convert(T, lambda)\n F = jordbloc(n, lambda);\n F[n,1] = alpha;\n return F\nend\nforsythe(::Type{T}, n::Integer) where T = forsythe(T, n, sqrt(eps(T)), zero(T))\nforsythe(args...) = forsythe(Float64, args...)\nforsythe(::Type, args...) = throw(MethodError(forsythe, Tuple(args)))\n\nfunction oddmagic(::Type{T}, n::Integer) where T\n # compute the magic square of odd orders\n A = zeros(T, n, n)\n i = 1\n j = div(n+1, 2)\n for k = 1:n^2\n is = i\n js = j\n A[i,j] = k\n i = n - rem(n+1-i,n)\n j = rem(j,n) + 1\n if A[i,j] != 0\n i = rem(is,n) + 1\n j = js\n end\n end\n return A\nend\n\n\"\"\"\nMagic Square Matrix\n===================\nThe magic matrix is a matrix with integer entries such that\n the row elements, column elements, diagonal elements and\n anti-diagonal elements all add up to the same number.\n\n*Input options:*\n\n+ [type,] dim: the dimension of the matrix.\n\n*Groups:* [\"inverse\"]\n\"\"\"\nfunction magic(::Type{T}, n::Integer) where T\n # Compute a magic square of order n\n # Learnt from Cleve Moler, Experiments with MATLAB, 2011\n if mod(n, 2) == 1\n # n is odd\n M = oddmagic(T, n)\n elseif mod(n, 4) == 0\n # n is doubly even\n a = floor.(Integer, mod.([1:n;], 4)/2)\n B = broadcast(==, a', a)\n M = broadcast(+, T[1:n:n^2;]',T[0:n-1;])\n for i = 1:n, j = 1:n\n B[i,j] == 1 ? M[i,j] = n^2 + one(T) - M[i,j] : M[i,j]\n end\n else\n # n is singly even\n p = div(n,2)\n M = oddmagic(T, p)\n M = [M M.+2*p^2; M.+3*p^2 M.+p^2]\n if n == 2\n return M\n end\n i = [1:p;]\n k = div(n-2, 4)\n j = [[1:k;]; [(n-k+2) : n;]]\n M[[i;i.+p],j] = M[[i.+p;i],j]\n i = k+1\n j = [1, i]\n M[[i;i+p],j] = M[[i+p;i],j]\n end\n return M\nend\nmagic(n::Integer) = magic(Float64, n)\n\n\"\"\"\nGrcar Matrix\n============\nThe Grcar matrix is a Toeplitz matrix with sensitive\neigenvalues.\n\n*Input options:*\n\n+ [type,] dim, k: `dim` is the dimension of the matrix and\n `k` is the number of superdiagonals.\n\n+ [type,] dim: the dimension of the matrix.\n\n*Groups:* [\"eigen\"]\n\n*References:*\n\n**J. F. Grcar**, Operator coefficient methods\n for linear equations, Report SAND89-8691, Sandia National\n Laboratories, Albuquerque, New Mexico, 1989 (Appendix 2).\n\"\"\"\nfunction grcar(::Type{T}, n::Integer, k::Integer = 3) where T\n # Compute grcar matrix\n G = tril(triu(ones(T, n,n)), min(k, n-1)) - diagm(-1 => ones(T, n-1))\n return G\nend\ngrcar(args...) = grcar(Float64, args...)\ngrcar(::Type, args...) = throw(MethodError(grcar, Tuple(args)))\n\n\"\"\"\nTriw Matrix\n===========\nUpper triangular matrices discussed by Wilkinson and others.\n\n*Input options:*\n\n+ [type,] row_dim, col_dim, α, k: `row_dim` and `col_dim`\n are row and column dimension of the matrix. `α` is a\n scalar representing the entries on the superdiagonals.\n `k` is the number of superdiagonals.\n\n+ [type,] dim: the dimension of the matrix.\n\n*Groups:* [\"inverse\", \"illcond\"]\n\n*References:*\n\n**G. H. Golub and J. H. Wilkinson**, Ill-conditioned\neigensystems and the computation of the Jordan canonical form,\nSIAM Review, 18(4), 1976, pp. 578-6\n\"\"\"\nfunction triw(::Type{T}, m::Integer, n::Integer, alpha, k::Integer) where T\n alpha = convert(T, alpha)\n A = tril(Matrix{T}(I, m, n) + alpha * triu(ones(T, m,n), 1), min(k, n-1))\n return A\nend\ntriw(::Type{T}, n::Integer) where T = triw(T, n, n, -1, n-1)\ntriw(args...) = triw(Float64, args...)\ntriw(::Type, args...) = throw(MethodError(triw, Tuple(args)))\n\n\"\"\"\nMoler Matrix\n============\nThe Moler matrix is a symmetric positive definite matrix.\nIt has one small eigenvalue.\n\n*Input options:*\n\n+ [type,] dim, alpha: `dim` is the dimension of the matrix,\n `alpha` is a scalar.\n\n+ [type,] dim: `alpha = -1`.\n\n*Groups:* [\"inverse\", \"illcond\", \"symmetric\", \"posdef\"]\n\n*References:*\n\n**J.C. Nash**, Compact Numerical Methods for Computers:\n Linear Algebra and Function Minimisation, second edition,\n Adam Hilger, Bristol, 1990 (Appendix 1).\n\"\"\"\nfunction moler(::Type{T}, n::Integer, alpha = -1.) where T\n alpha = convert(T, alpha)\n M = triw(T, n, n, alpha, n - 1)' * triw(T, n, n, alpha, n -1 )\n return M\nend\nmoler(args...) = moler(Float64, args...)\nmoler(::Type, args...) = throw(MethodError(moler, Tuple(args)))\n\n\"\"\"\nPascal Matrix\n=============\nThe Pascal matrix’s anti-diagonals form the Pascal’s triangle.\n\n*Input options:*\n\n+ [type,] dim: the dimension of the matrix.\n\n*Groups:* [\"inverse\", \"illcond\", \"symmetric\", \"posdef\", \"eigen\"]\n\n*References:*\n\n**R. Brawer and M. Pirovino**, The linear algebra of\n the Pascal matrix, Linear Algebra and Appl., 174 (1992),\n pp. 13-23 (this paper gives a factorization of L = PASCAL(N,1)\n and a formula for the elements of L^k).\n\n**N. J. Higham**, Accuracy and Stability of Numerical Algorithms,\nsecond edition, Society for Industrial and Applied Mathematics, Philadelphia, PA,\nUSA, 2002; sec. 28.4.\n\"\"\"\nfunction pascal(::Type{T}, n::Integer) where T\n P = zeros(T, n,n)\n for j = 1:n\n for i = 1:n\n try P[i,j] = binomial(i+j-2, j-1)\n catch\n P[i,j] = binomial(BigInt(i+j-2), j-1)\n end\n end\n end\n return P\nend\npascal(n::Integer) = pascal(Float64, n)\n\n\"\"\"\nKahan Matrix\n============\nThe Kahan matrix is an upper trapezoidal matrix, i.e., the\n`(i,j)` element is equal to `0` if `i > j`. The useful range of\n `θ` is `0 < θ < π`. The diagonal is perturbed by\n `pert*eps()*diagm([n:-1:1;])`.\n\n*Input options:*\n\n+ [type,] rowdim, coldim, θ, pert: `rowdim` and `coldim` are the row and column\n dimensions of the matrix. `θ` and `pert` are scalars.\n\n+ [type,] dim, θ, pert: `dim` is the dimension of the matrix.\n\n+ [type,] dim: `θ = 1.2`, `pert = 25`.\n\n*Groups:* [\"inverse\", \"illcond\"]\n\n*References:*\n\n**W. Kahan**, Numerical linear algebra, Canadian Math.\n Bulletin, 9 (1966), pp. 757-801.\n\"\"\"\nfunction kahan(::Type{T}, m::Integer, n::Integer, theta, pert) where T\n theta = convert(T, theta)\n pert = convert(T, pert)\n s = sin(theta)\n c = cos(theta)\n dim = min(m,n)\n A = zeros(T, m, n)\n for i = 1:m, j = 1:n\n i > dim ? A[i,j] = zero(T) :\n i > j ? A[i,j] = zero(T) :\n i==j ? A[i,j] = s^(i-1)+pert*eps(T)*(m-i+1) : A[i,j] = -c*s^(i-1)\n end\n return A\nend\nkahan(::Type{T}, n::Integer, theta, pert) where T = kahan(T, n, n, theta, pert)\nkahan(::Type{T}, n::Integer) where T = kahan(T, n, n, 1.2, 25.)\nkahan(args...) = kahan(Float64, args...)\nkahan(::Type, args...) = throw(MethodError(kahan, Tuple(args)))\n\n\"\"\"\nPei Matrix\n==========\nThe Pei matrix is a symmetric matrix with known inversion.\n\n*Input options:*\n\n+ [type,] dim, α: `dim` is the dimension of the matrix.\n `α` is a scalar.\n\n+ [type,] dim: the dimension of the matrix.\n\n*Groups:* [\"inverse\", \"illcond\", \"symmetric\", \"posdef\"]\n\n*References:*\n\n**M. L. Pei**, A test matrix for inversion procedures,\n Comm. ACM, 5 (1962), p. 508.\n\"\"\"\nfunction pei(::Type{T}, n::Integer, alpha = 1) where T\n alpha = convert(T, alpha)\n return alpha*Matrix{T}(I, n, n) + ones(T, n, n)\nend\npei(args...) = pei(Float64, args...)\npei(::Type, args...) = throw(MethodError(pei, Tuple(args)))\n\n\"\"\"\nVandermonde Matrix\n==================\nThe inverse and determinat are known explicity.\n\n*Input options:*\n\n+ [type,] vec, col_dim: `vec` is a vector, `col_dim` is the number of columns.\n\n+ [type,] vec: `col_dim = length(vec)`\n\n+ [type,] dim: `vec = [1:dim;]`\n\n*Groups:* [\"inverse\", \"illcond\"]\n\n*References:*\n\n**N. J. Higham**, Stability analysis of algorithms\n for solving confluent Vandermonde-like systems, SIAM J.\n Matrix Anal. Appl., 11 (1990), pp. 23-41.\n\"\"\"\nfunction vand(::Type{T}, p::Vector, n::Integer) where T\n # n: number of rows\n # p: a vector\n m = length(p)\n V = Array{T,2}(undef, m, n)\n for j = 1:m\n @inbounds V[j, 1] = 1\n end\n for i = 2:n\n for j = 1:m\n @inbounds V[j,i] = p[j] * V[j,i-1]\n end\n end\n return V\nend\nvand(::Type{T}, n::Integer) where T = vand(T, [1:n;], n)\nvand(::Type{T}, p::Vector) where T = vand(T, p, length(p))\nvand(args...) = vand(Float64, args...)\nvand(::Type, args...) = throw(MethodError(vand, Tuple(args)))\n\n\"\"\"\nInvolutory Matrix\n=================\nAn involutory matrix is a matrix that is its own inverse.\n\n*Input options:*\n\n+ [type,] dim: `dim` is the dimension of the matrix.\n\n*Groups:* [\"inverse\", \"illcond\", \"eigen\"]\n\n*References:*\n\n**A. S. Householder and J. A. Carpenter**, The\n singular values of involutory and of idempotent matrices,\n Numer. Math. 5 (1963), pp. 234-237.\n\"\"\"\nfunction invol(::Type{T}, n::Integer) where T\n A = hilb(T, n)\n d = -n\n A[:,1] = d*A[:, 1]\n for i = 1:n-1\n d = -(n+i)*(n-i)*d/(i*i)\n A[i+1,:] = d*A[i+1,:]\n end\n return A\nend\ninvol(n::Integer) = invol(Float64, n)\n\n\"\"\"\nChebyshev Spectral Differentiation Matrix\n=========================================\nIf `k = 0`,the generated matrix is nilpotent and a vector with\n all one entries is a null vector. If `k = 1`, the generated\n matrix is nonsingular and well-conditioned. Its eigenvalues\n have negative real parts.\n\n*Input options:*\n\n+ [type,] dim, k: `dim` is the dimension of the matrix and\n `k = 0 or 1`.\n\n+ [type,] dim: `k=0`.\n\n*Groups:* [\"eigen\"]\n\n*References:*\n\n**L. N. Trefethen and M. R. Trummer**, An instability\n phenomenon in spectral methods, SIAM J. Numer. Anal., 24 (1987), pp. 1008-1023.\n\"\"\"\nfunction chebspec(::Type{T}, n::Integer, k::Integer = 0) where T\n # k = 0 or 1\n if k == 1\n n = n + 1\n end\n c = ones(T, n)\n c[1] = 2\n c[2:n-1] .= 1\n c[n] = 2\n x = ones(T, n)\n\n A = zeros(T, n, n)\n # Compute the chebyshev points\n for i = 1:n\n x[i] = cos(pi * (i - 1) / (n - 1))\n end\n\n for j = 1:n, i = 1:n\n i != j ? A[i,j] = (-1)^(i+j) * c[i] / (c[j] * (x[i] - x[j])) :\n i == 1 ? A[i,i] = (2 * (n -1)^2 + 1) / 6 :\n i == n ? A[i,i] = - (2 * (n-1)^2 + 1) / 6 :\n A[i,i] = - 0.5 * x[i] / (1 - x[i]^2)\n end\n if k == 1\n A = A[2:n, 2:n]\n end\n return A\nend\nchebspec(args...) = chebspec(Float64, args...)\nchebspec(::Type, args...) = throw(MethodError(chebspec, Tuple(args)))\n\n\"\"\"\nLotkin Matrix\n=============\nThe Lotkin matrix is the Hilbert matrix with its first row\n altered to all ones. It is unsymmetric, illcond and\n has many negative eigenvalues of small magnitude.\n\n*Input options:*\n\n+ [type,] dim: `dim` is the dimension of the matrix.\n\n*Groups:* [\"inverse\", \"illcond\", \"eigen\"]\n\n*References:*\n\n**M. Lotkin**, A set of test matrices, MTAC, 9 (1955), pp. 153-161.\n\"\"\"\nfunction lotkin(::Type{T}, n::Integer) where T\n A = hilb(T, n)\n A[1,:] = ones(T,n)'\n return A\nend\nlotkin(n::Integer) = lotkin(Float64, n)\n\n\"\"\"\nClement Matrix\n==============\nThe Clement matrix is a tridiagonal matrix with zero\n diagonal entries. If k = 1, the matrix is symmetric.\n\n*Input options:*\n\n+ [type,] dim, k: `dim` is the dimension of the matrix.\n If `k = 0`, the matrix is of type `Tridiagonal`.\n If `k = 1`, the matrix is of type `SymTridiagonal`.\n\n+ [type,] dim: `k = 0`.\n\n*Groups:* [\"inverse\", \"symmetric\", \"eigen\"]\n\n*References:*\n\n**P. A. Clement**, A class of triple-diagonal\n matrices for test purposes, SIAM Review, 1 (1959), pp. 50-52.\n\"\"\"\nfunction clement(::Type{T}, n::Integer, k::Integer = 0) where T\n # construct Tridiagonal matrix\n # n is the dimension of the matrix\n # k = 0 or 1\n if n == 1 # handle the 1-d case.\n return zeros(T, 1, 1)\n end\n n = n -1\n x = T[n:-1:1;]\n z = T[1:n;]\n if k == 0\n A = Tridiagonal(x,zeros(T,n+1),z)\n else\n y = sqrt.(x.*z)\n A = SymTridiagonal(zeros(T,n+1), y)\n end\n return A\nend\nclement(args...) = clement(Float64, args...)\nclement(::Type, args...) = throw(MethodError(clement, Tuple(args)))\n\n\"\"\"\nFiedler Matrix\n==============\nThe Fiedler matrix is symmetric matrix with a dominant\n positive eigenvalue and all the other eigenvalues are negative.\n\n*Input options:*\n\n+ [type,] vec: a vector.\n\n+ [type,] dim: `dim` is the dimension of the matrix. `vec=[1:dim;]`.\n\n*Groups: *[\"inverse\", \"symmetric\", \"eigen\"]\n\n*References:*\n\n**G. Szego**, Solution to problem 3705, Amer. Math.\n Monthly, 43 (1936), pp. 246-259.\n\n**J. Todd**, Basic Numerical Mathematics, Vol. 2: Numerical Algebra,\n Birkhauser, Basel, and Academic Press, New York, 1977, p. 159.\n\"\"\"\nfunction fiedler(::Type{T}, v::Vector) where T\n n = length(v)\n v = transpose(v[:])\n A = ones(T, n) * v\n A = abs.(A - transpose(A)) # nonconjugate transpose\nend\nfiedler(::Type{T}, n::Integer) where T = fiedler(T, [1:n;])\nfiedler(args...) = fiedler(Float64, args...)\nfiedler(::Type, args...) = throw(MethodError(fiedler, Tuple(args)))\n\n\"\"\"\nMIN[I,J] Matrix\n===============\nA matrix with `(i,j)` entry `min(i,j)`. It is a symmetric positive\n definite matrix. The eigenvalues and eigenvectors are known\n explicitly. Its inverse is tridiagonal.\n\n*Input options:*\n\n+ [type,] dim: the dimension of the matrix.\n\n*Groups:* [\"inverse\", \"symmetric\", \"posdef\", \"eigen\"]\n\n*References:*\n\n**J. Fortiana and C. M. Cuadras**, A family of matrices,\n the discretized Brownian bridge, and distance-based regression,\n Linear Algebra Appl., 264 (1997), 173-188. (For the eigensystem of A.)\n\"\"\"\nfunction minij(::Type{T}, n::Integer) where T\n A = zeros(T, n, n)\n [A[i,j] = min(i,j) for i = 1:n, j = 1:n]\n return A\nend\nminij(n::Integer) = minij(Float64, n)\n\n\"\"\"\nBinomial Matrix\n===============\nThe matrix is a multiple of an involutory matrix.\n\n*Input options:*\n\n+ [type,] dim: the dimension of the matrix.\n\"\"\"\nfunction binomialm(::Type{T}, n::Integer) where T\n # Mulitiple of involutory matrix\n L = Array{T,2}(undef, n, n)\n D = Diagonal((-2).^[0:n-1;])\n [L[i,j] = binomial(i-1, j-1) for i = 1:n, j = 1:n]\n U = L[n:-1:1, n:-1:1]\n return L*D*U\nend\nbinomialm(n::Integer) = binomialm(Float64, n)\n\n\"\"\"\nTridiagonal Matrix\n==================\nConstruct a tridigonal matrix of type `Tridiagonal`.\n\n*Input options:*\n\n+ [type,] v1, v2, v3: `v1` and `v3` are vectors of subdiagonal\n and superdiagonal elements, respectively, and `v2` is a vector\n of diagonal elements.\n\n+ [type,] dim, x, y, z: `dim` is the dimension of the matrix,\n `x`, `y`, `z` are scalars. `x` and `z` are the subdiagonal and\n superdiagonal elements, respectively, and `y` is the diagonal\n elements.\n\n+ [type,] dim: `x = -1, y = 2, z = -1`. This matrix is also\n known as the second difference matrix.\n\n*Groups:* [\"inverse\", \"illcond\", \"posdef\", \"eigen\"]\n\n*References:*\n\n**J. Todd**, Basic Numerical Mathematics, Vol. 2:\n Numerical Algebra, Birkhauser, Basel, and Academic Press,\n New York, 1977, p. 155.\n\"\"\"\nfunction tridiag(::Type{T}, x::AbstractVector, y::AbstractVector,\n z::AbstractVector) where T\n x = map((i)-> convert(T, i), x)\n y = map((i)-> convert(T, i), y)\n z = map((i)-> convert(T, i), z)\n return Tridiagonal(x,y,z)\nend\n# Toeplitz tridiagonal matrix\ntridiag(::Type{T}, n::Integer, x::Integer, y::Integer, z::Integer) where T =\nn == 1 ? y*ones(T,1,1) :\n tridiag(T, x*ones(T, n-1), y*ones(T, n), z*ones(T, n-1))\ntridiag(::Type{T}, n::Integer) where T = tridiag(T, n, -1, 2, -1)\ntridiag(args...) = tridiag(Float64, args...)\ntridiag(::Type, args...) = throw(MethodError(tridiag, Tuple(args)))\n\n\"\"\"\nLehmer Matrix\n=============\nThe Lehmer matrix is a symmetric positive definite matrix.\n It is totally nonnegative. The inverse is tridiagonal and\n explicitly known\n\n*Input options:*\n\n+ [type,] dim: the dimension of the matrix.\n\n*Groups:* [\"inverse\", \"symmetric\", \"posdef\"]\n\n*References:*\n\n**M. Newman and J. Todd**, The evaluation of\n matrix inversion programs, J. Soc. Indust. Appl. Math.,\n 6 (1958), pp. 466-476.\n Solutions to problem E710 (proposed by D.H. Lehmer): The inverse\n of a matrix, Amer. Math. Monthly, 53 (1946), pp. 534-535.\n\"\"\"\nfunction lehmer(::Type{T}, n::Integer) where T\n A = Array{T,2}(undef, n, n)\n [A[i,j] = min(i,j) / max(i,j) for i = 1:n, j = 1:n]\n return A\nend\nlehmer(n::Integer) = lehmer(Float64, n)\n#=\nfunction lehmer(::Type{T}, n::Integer) where T\n A = Array{T,2}(n, n)\n [A[i,j] = min(i,j) / max(i,j) for i = 1:n, j = 1:n]\n return A\nend\nlehmer(n::Integer) = lehmer(Float64, n)\n=#\n\"\"\"\nParter Matrix\n=============\nThe Parter matrix is a Toeplitz and Cauchy matrix\n with singular values near `π`.\n\n*Input options:*\n\n+ [type,] dim: the dimension of the matrix.\n\n*Groups:* [\"eigen\"]\n\n*References:*\n\nThe MathWorks Newsletter, Volume 1, Issue 1,\n March 1986, page 2. S. V. Parter, On the distribution of the\n singular values of Toeplitz matrices, Linear Algebra and\n Appl., 80 (1986), pp. 115-130.\n\"\"\"\nfunction parter(::Type{T}, n::Integer) where T\n A = Array{T,2}(undef, n, n)\n [A[i,j] = one(T) / (i - j + 0.5) for i = 1:n, j = 1:n]\n return A\nend\nparter(n::Integer) = parter(Float64, n)\n\n\"\"\"\nChow Matrix\n===========\nThe Chow matrix is a singular Toeplitz lower Hessenberg matrix.\n\n*Input options:*\n\n+ [type,] dim, alpha, delta: `dim` is dimension of the matrix.\n `alpha`, `delta` are scalars such that `A[i,i] = alpha + delta` and\n `A[i,j] = alpha^(i + 1 -j)` for `j + 1 <= i`.\n\n+ [type,] dim: `alpha = 1`, `delta = 0`.\n\n*Groups:* [\"eigen\"]\n\n*References:*\n\n**T. S. Chow**, A class of Hessenberg matrices with known\n eigenvalues and inverses, SIAM Review, 11 (1969), pp. 391-395.\n\"\"\"\nfunction chow(::Type{T}, n::Integer, alpha, delta) where T\n A = zeros(T, n, n)\n alpha = convert(T, alpha)\n delta = convert(T, delta)\n for i = 1:n, j = 1:n\n if i == j - 1\n A[i,j] = one(T)\n elseif i == j\n A[i,j] = alpha + delta\n elseif j + 1 <= i\n A[i,j] = alpha^(i + 1 - j)\n end\n end\n return A\nend\nchow(::Type{T}, n::Integer) where T = chow(T, n, 1, 0)\nchow(args...) = chow(Float64, args...)\nchow(::Type, args...) = throw(MethodError(chow, Tuple(args)))\n\n#\n# newsign: newsign(0) = 1\n#\nfunction newsign(x)\n x == 0 ? y = 1 : y = sign(x)\n return y\nend\n\n\"\"\"\nRandom Correlation Matrix\n=========================\nA random correlation matrix is a symmetric positive\n semidefinite matrix with 1s on the diagonal.\n\n*Input options:*\n\n+ [type,] dim: the dimension of the matrix.\n\n*Groups:* [\"symmetric\", 'pos-semidef', \"random\"]\n\"\"\"\nfunction randcorr(::Type{T}, n::Integer) where T\n x = rand(T,n) # x is the vector of random eigenvalues from a uniform distribution.\n x = n * x / sum(x) # x has nonnegtive elements.\n A = diagm(0 => x)\n F = qr(randn(n,n));\n Q = F.Q*diagm(0 => sign.(diag(F.R))) # form a random orthogonal matrix.\n copyto!(A, Q*A*Q')\n\n a = diag(A)\n l = findall(a .< 1)\n g = findall(a .> 1)\n\n # Apply Given rotation to set A[i,i] = 1\n while length(l) > 0 && length(g) > 0\n k = ceil(Integer, rand()*length(l))\n h = ceil(Integer, rand()*length(g))\n i = l[k]\n j = g[h]\n if i > j\n i,j = j,i\n end\n alpha = sqrt(A[i,j]^2 - (a[i] - 1)*(a[j] - 1))\n # take sign to avoid cancellation.\n t = (A[i,j] + newsign(A[i,j]) * alpha) / (a[j] - 1)\n c = 1/ sqrt(1 + t^2)\n s = t*c\n\n A[:, [i,j]] = A[:, [i,j]] * [c s; -s c]\n A[[i,j], :] = [c -s; s c] * A[[i,j], :]\n\n A[i,i] = 1\n a = diag(A)\n l = findall(a.<1)\n g = findall(a.>1)\n end\n [A[i,i] = 1 for i = 1:n]\n return (A + A')/2\n\nend\nrandcorr(args...) = randcorr(Float64, args...)\nrandcorr(::Type, args...) = throw(MethodError(randcorr, Tuple(args)))\n\n\"\"\"\nPoisson Matrix\n==============\nA block tridiagonal matrix from Poisson’s equation.\n This matrix is sparse, symmetric positive definite and\n has known eigenvalues. The result is of type `SparseMatrixCSC`.\n\n*Input options:*\n\n+ [type,] dim: the dimension of the matirx is `dim^2`.\n\n*Groups:* [\"inverse\", \"symmetric\", \"posdef\", \"eigen\", \"sparse\"]\n\n*References:*\n\n**G. H. Golub and C. F. Van Loan**, Matrix Computations,\n second edition, Johns Hopkins University Press, Baltimore,\n Maryland, 1989 (Section 4.5.4).\n\"\"\"\nfunction poisson(::Type{T}, n::Integer) where T\n S = Array(tridiag(T, n))\n A = sparse(T(1)I, n, n)\n return kron(A,S) + kron(S,A)\nend\npoisson(n::Integer) = poisson(Float64, n)\n\n\"\"\"\nToeplitz Matrix\n===============\nA Toeplitz matrix is a matrix in which each descending\n diagonal from left to right is constant.\n\n*Input options:*\n\n+ [type,] vc, vr: `vc` and `vr` are the first column and row of the matrix.\n\n+ [type,] v: symmatric case, i.e., `vc = vr = v`.\n\n+ [type,] dim: `dim` is the dimension of the matrix. `v = [1:dim;]` is the first\n row and column vector.\n\"\"\"\nfunction toeplitz(::Type{T}, vc::Vector, vr::Vector) where T\n n = length(vc)\n length(vr) == n || throw(DimensionMismatch(\"\"))\n vc[1] == vr[1] || error(\"The first element of the vectors must be the same.\")\n A = Array{T,2}(undef, n, n)\n [i>=j ? A[i,j] = vc[i-j+1] : A[i,j] = vr[j-i+1] for i=1:n, j=1:n]\n A\nend\ntoeplitz(::Type{T}, v::Vector) where T = toeplitz(T, v, v)\ntoeplitz(::Type{T}, n::Integer) where T = toeplitz(T, [1:n;])\ntoeplitz(args...) = toeplitz(Float64, args...)\ntoeplitz(::Type, args...) = throw(MethodError(toeplitz, Tuple(args)))\n\n\"\"\"\nHankel Matrix\n=============\nA Hankel matrix is a matrix that is symmetric and constant\n across the anti-diagonals.\n\n*Input options:*\n\n+ [type,] vc, vr: `vc` and `vc` are the first column and last row of the\n matrix. If the last element of `vc` differs from the first element\n of `vr`, the last element of `rc` prevails.\n\n+ [type,] v: `vc = vr = v`.\n\n+ [type,] dim: `dim` is the dimension of the matrix. `v = [1:dim;]`.\n\"\"\"\nfunction hankel(::Type{T}, vc::Vector, vr::Vector) where T\n p = [vc; vr[2:end]]\n m = length(vc)\n n = length(vr)\n H = Array{T,2}(undef, m, n)\n [H[i,j] = p[i+j-1] for i=1:m, j=1:n]\n H\nend\nhankel(::Type{T}, v::Vector) where T = hankel(T, v, v)\nhankel(::Type{T}, n::Integer) where T = hankel(T, [1:n;])\nhankel(args...) = hankel(Float64, args...)\nhankel(::Type, args...) = throw(MethodError(hankel, Tuple(args)))\n\n\"\"\"\nProlate Matrix\n==============\nA prolate matrix is a symmetirc, ill-conditioned Toeplitz matrix.\n\n*Input options:*\n\n+ [type,] dim, w: `dim` is the dimension of the matrix. `w` is a real scalar.\n\n+ [type,] dim: the case when `w = 0.25`.\n\n*References:*\n\n**J. M. Varah**. The Prolate Matrix. Linear Algebra and Appl.\n 187:267--278, 1993.\n\"\"\"\nfunction prolate(::Type{T}, n::Integer, w::Real) where T\n v = Array{T,1}(undef, n)\n v[1] = 2*w\n [v[i] = sin(2*pi*w*i)/pi*i for i = 2:n]\n return toeplitz(T, v)\nend\nprolate(::Type{T}, n::Integer) where T = prolate(T, n, 0.25)\nprolate(args...) = prolate(Float64, args...)\nprolate(::Type, args...) = throw(MethodError(prolate, Tuple(args)))\n\n\"\"\"\nNeumann Matrix\n==============\nA singular matrix from the discrete Neumann problem.\n The matrix is sparse and the null space is formed by a vector of ones\n\n*Input options:*\n\n+ [type,] dim: the dimension of the matrix is `dim^2`.\n\n*Groups:* [\"eigen\", \"sparse\"]\n\n*References:*\n\n**R. J. Plemmons**, Regular splittings and the\n discrete Neumann problem, Numer. Math., 25 (1976), pp. 153-161.\n\"\"\"\nfunction neumann(::Type{T}, n::Integer) where T\n if n == 1\n return 4 * ones(T, 1,1) #handle 1-d case.\n end\n S = Matrix(tridiag(T, n))\n S[1,2] = -2\n S[n, n-1] = -2\n A = sparse(T(1)I, n, n)\n return kron(S,A) + kron(A,S)\nend\nneumann(n::Integer) = neumann(Float64, n)\n\n#\n# Sylvester's orthogonal matrix\n# See Rosser matrix References 2.\n#\n# for a = d = 2, b = c = 1, P_block' * P_block = 10 * Identity\n#\nP_block(::Type{T}, a, b, c, d) where T =\n reshape(T[a, b, c, d, b, -a, -d, c, c, d, -a, -b, d, -c, b, -a], 4,4)\n\n\"\"\"\nRosser Matrix\n=============\nThe Rosser matrix’s eigenvalues are very close together\n so it is a challenging matrix for many eigenvalue algorithms.\n\n*Input options:*\n\n+ [type,] dim, a, b: `dim` is the dimension of the matrix.\n `dim` must be a power of 2.\n `a` and `b` are scalars. For `dim = 8, a = 2` and `b = 1`, the generated\n matrix is the test matrix used by Rosser.\n\n+ [type,] dim: `a = rand(1:5), b = rand(1:5)`.\n\n*Groups:* [\"eigen\", \"illcond\", \"random\"]\n\n*References:*\n\n**J. B. Rosser, C. Lanczos, M. R. Hestenes, W. Karush**,\n Separation of close eigenvalues of a real symmetric matrix,\n Journal of Research of the National Bureau of Standards, v(47)\n (1951)\n\"\"\"\nfunction rosser(::Type{T}, n::Integer, a, b) where T\n if n < 1\n lgn = 0\n else\n lgn = round(Integer, log2(n))\n end\n 2^lgn != n && throw(ArgumentError(\"n must be positive integer and a power of 2.\"))\n\n if n == 1 # handle 1-d case\n return 611 * ones(T, 1, 1)\n end\n\n if n == 2\n #eigenvalues are 500, 510\n B = T[101 1; 1 101]\n P = T[2 1;1 -2]\n A = P'*B*P\n elseif n == 4\n # eigenvalues are 0.1, 1019.9, 1020, 1020 for a = 2 and b = 1\n B = zeros(T, n, n)\n B[1,1], B[1,4], B[4,1], B[4,4] = 101, 1, 1, 101;\n B[2,2], B[2,3], B[3,2], B[3,3] = 1, 10, 10, 101;\n P = P_block(T, a, b, b, a)\n A = P' * B * P\n elseif n == 8\n # eigenvalues are 1020, 1020, 1000, 1000, 0.098, 0, -1020\n B = zeros(T, n, n)\n B[1,1], B[6,1], B[2,2], B[8,2] = 102, 1, 101, 1;\n B[3,3], B[7,3] = 98, 14;\n B[4,4], B[5,4], B[4,5], B[5,5] = 1, 10, 10, 101;\n B[1,6], B[6,6], B[3,7],B[7,7], B[2,8], B[8,8] = 1, -102, 14, 2, 1, 101;\n P = [P_block(T, a, b, b, a)' zeros(T, 4,4); zeros(T, 4,4) P_block(T, b, -b, -a, a)]\n A = P' * B * P\n else\n lgn = lgn - 2\n halfn = round(Integer, n/2)\n # using Sylvester's method\n P = P_block(T, a, b, b, a)\n m = 4\n for i in 1:lgn\n P = [P zeros(T, m, m); zeros(T, m, m) P]\n m = m * 2\n end\n # mix 4 2-by-2 matrices (with close eigenvalues) into a large nxn matrix.\n B_list = T[102, 1, 1, - 102, 101, 1, 1, 101, 1, 10, 10, 101, 98, 14, 14, 2]\n B = zeros(T, n, n)\n j, k = 1, 5\n for i in 1:(halfn + 1)\n indexend = halfn -1 + i\n list_start = k\n list_end = k + 3\n\n if list_start > 16 || list_end > 16\n k = 1\n list_start = 1\n list_end = 4\n end\n B[j,j], B[j,indexend], B[indexend, j], B[indexend, indexend] = B_list[list_start:list_end]\n j = j + 1\n k = k + 4\n end\n A = P' * B * P\n end\n\n return A\nend\nrosser(::Type{T}, n::Integer) where T = rosser(T, n, rand(1:5), rand(1:5))\nrosser(args...) = rosser(Float64, args...)\nrosser(::Type, args...) = throw(MethodError(rosser, Tuple(args)))\n\n\"\"\"\nMatrix with Application in Sampling Theory\n==========================================\nA nonsymmetric matrix with eigenvalues 0, 1, 2, ... n-1.\n\n*Input options:*\n\n+ [type,] vec: `vec` is a vector with no repeated elements.\n\n+ [type,] dim: `dim` is the dimension of the matrix.\n `vec = [1:dim;]/dim`.\n\n*Groups:* [\"eigen\"]\n\n*References:*\n\n**L. Bondesson and I. Traat**, A nonsymmetric matrix\n with integer eigenvalues, linear and multilinear algebra, 55(3)\n (2007), pp. 239-247\n\"\"\"\nfunction sampling(::Type{T}, x::Vector) where T\n n = length(x)\n A = zeros(T, n, n)\n for j = 1:n, i = 1:n\n if i != j\n A[i,j] = x[i] / (x[i] - x[j])\n end\n end\n d = sum(A, dims=2)\n A = A + diagm(0 => d[:])\n return A\nend\n#\n# special probability case\n# see:\n# L. Bondesson and I. Traat, A Nonsymmetric Matrix with Integer\n# Eigenvalues, Linear and Multilinear Algebra, 55(3)(2007), pp. 239-247.\n#\nfunction sampling(::Type{T}, n::Integer) where T\n p = T[1:n;] / n\n return sampling(T, p)\nend\nsampling(args...) = sampling(Float64, args...)\nsampling(::Type, args...) = throw(MethodError(sampling, Tuple(args)))\n\n\"\"\"\nWilkinson Matrix\n================\nThe Wilkinson matrix is a symmetric tridiagonal matrix with pairs\nof nearly equal eigenvalues. The most frequently used case\nis `matrixdepot(\"wilkinson\", 21)`. The result is of type `Tridiagonal`.\n\n*Input options:*\n\n+ [type,] dim: the dimension of the matrix.\n\n*Groups:* [\"symmetric\", \"eigen\"]\n\n*References:*\n\n**J. H. Wilkinson**, Error analysis of direct methods\nof matrix inversion, J. Assoc. Comput. Mach., 8 (1961), pp. 281-330.\n\"\"\"\nfunction wilkinson(::Type{T}, n::Integer) where T\n if n == 1 # handle 1-d case\n return ones(T, 1, 1)\n end\n m = (n-1)/2\n A = Tridiagonal(ones(T,n-1), abs.(T[-m:m;]), ones(T, n-1))\n return A\nend\nwilkinson(n::Integer) = wilkinson(Float64, n)\n\n\"\"\"\nRandom Matrix with Element -1, 0, 1\n===================================\n\n*Input options:*\n\n+ [type,] row_dim, col_dim, k: `row_dim` and `col_dim` are row and column dimensions,\n `k = 1`: entries are 0 or 1.\n `k = 2`: entries are -1 or 1.\n `k = 3`: entries are -1, 0 or 1.\n\n+ [type,] dim, k: `row_dim = col_dim = dim`.\n\n+ [type,] dim: `k = 1`.\n\n*Groups:* [\"random\"]\n\"\"\"\nfunction rando(::Type{T}, m::Integer, n::Integer, k::Integer) where T\n A = Array{T,2}(undef, m, n)\n if k == 1\n copyto!(A, floor.(rand(m,n) .+ .5))\n elseif k == 2\n copyto!(A, 2 * floor.(rand(m,n) .+ .5) .- one(T))\n elseif k == 3\n copyto!(A, round.(3 * rand(m,n) .- 1.5))\n else\n throw(ArgumentError(\"invalid k value.\"))\n end\n return A\nend\nrando(::Type{T}, n::Integer, k::Integer) where T = rando(T, n, n, k)\nrando(::Type{T}, n::Integer) where T = rando(T, n, n, 1)\nrando(args...) = rando(Float64, args...)\nrando(::Type, args...) = throw(MethodError(rando, Tuple(args)))\n\n#\n# Pre-multiply by random orthogonal matrix\n#\nfunction qmult!(A::Matrix{T}) where T\n n, m = size(A)\n\n d = zeros(T, n)\n for k = n-1:-1:1\n\n # generate random Householder transformation\n x = randn(n-k+1)\n s = norm(x)\n sgn = sign(x[1]) + (x[1]==0)\n s = sgn * s\n d[k] = -sgn\n x[1] = x[1] + s\n beta = s * x[1]\n\n # apply the transformation to A\n y = x'*A[k:n, :];\n A[k:n, :] = A[k:n, :] - x * (y /beta)\n end\n\n # tidy up signs\n for i=1:n-1\n A[i, :] = d[i] * A[i, :]\n end\n A[n, :] = A[n, :] * sign(randn())\n return A\nend\n\n\"\"\"\nRandom Matrix with Pre-assigned Singular Values\n===============================================\n*Input options:*\n\n+ [type,] row_dim, col_dim, kappa, mode: `row_dim` and `col_dim`\n are the row and column dimensions.\n `kappa` is the condition number of the matrix.\n `mode = 1`: one large singular value.\n `mode = 2`: one small singular value.\n `mode = 3`: geometrically distributed singular values.\n `mode = 4`: arithmetrically distributed singular values.\n `mode = 5`: random singular values with unif. dist. logarithm.\n\n+ [type,] dim, kappa, mode: `row_dim = col_dim = dim`.\n\n+ [type,] dim, kappa: `mode = 3`.\n\n+ [type,] dim: `kappa = sqrt(1/eps())`, `mode = 3`.\n\n*Groups:* [\"illcond\", \"random\"]\n\n*References:*\n\n**N. J. Higham**, Accuracy and Stability of Numerical\nAlgorithms, second edition, Society for Industrial and Applied Mathematics,\nPhiladelphia, PA, USA, 2002; sec. 28.3.\n\"\"\"\nfunction randsvd(::Type{T}, m::Integer, n::Integer, kappa, mode::Integer) where T\n kappa >= 1 || throw(ArgumentError(\"Condition number must be at least 1.\"))\n kappa = convert(T, kappa)\n\n p = min(m,n)\n if p == 1 # handle 1-d case\n return ones(T, 1, 1)*kappa\n end\n\n if mode == 3\n factor = kappa^(-1/(p-1))\n sigma = factor.^[0:p-1;]\n elseif mode == 4\n sigma = ones(T, p) - T[0:p-1;]/(p-1)*(1 - 1/kappa)\n elseif mode == 5\n sigma = exp.(-rand(p) * log(kappa))\n elseif mode == 2\n sigma = ones(T, p)\n sigma[p] = one(T)/kappa\n elseif mode == 1\n sigma = ones(p)./kappa\n sigma[1] = one(T)\n else\n throw(ArgumentError(\"invalid mode value.\"))\n end\n\n A = zeros(T, m, n)\n A[1:p, 1:p] = diagm(0 => sigma)\n A = qmult!(copy(A'))\n A = qmult!(copy(A'))\n\n return A\nend\nrandsvd(::Type{T}, n::Integer, kappa, mode) where T = randsvd(T, n, n, kappa, mode)\nrandsvd(::Type{T}, n::Integer, kappa) where T= randsvd(T, n, kappa, 3)\nrandsvd(::Type{T}, n::Integer) where T = randsvd(T, n, sqrt(1/eps(T)))\nrandsvd(args...) = randsvd(Float64, args...)\nrandsvd(::Type, args...) = throw(MethodError(randsvd, Tuple(args)))\n\n\"\"\"\nRandom Orthogonal Upper Hessenberg Matrix\n=========================================\nThe matrix is constructed via a product of Givens rotations.\n\n*Input options:*\n\n+ [type,] dim: the dimension of the matrix.\n\n*Groups:* [\"random\"]\n\n*References:*\n\n**W. B. Gragg**, The QR algorithm for unitary\n Hessenberg matrices, J. Comp. Appl. Math., 16 (1986), pp. 1-8.\n\"\"\"\nfunction rohess(::Type{T}, n::Integer) where T\n x = rand(n-1)*2*pi\n H = Matrix{T}(I, n, n)\n H[n,n] = sign(randn())\n for i = n:-1:2\n theta = x[i-1]\n c = convert(T, cos(theta))\n s = convert(T, sin(theta))\n H[[i-1; i], :] = [c*H[i-1, :][:]' + s*H[i, :][:]'; -s*H[i-1, :][:]' + c*H[i, :][:]']\n end\n return H\nend\nrohess(n::Integer) = rohess(Float64, n)\n\n\"\"\"\nKac-Murdock-Szego Toeplitz matrix\n=================================\n\n*Input options:*\n\n+ [type,] dim, rho: `dim` is the dimension of the matrix, `rho` is a\n scalar such that `A[i,j] = rho^(abs(i-j))`.\n\n+ [type,] dim: `rho = 0.5`.\n\n*Groups:* [\"inverse\", \"illcond\", \"symmetric\", \"posdef\"]\n\n*References:*\n\n**W. F. Trench**, Numerical solution of the eigenvalue\n problem for Hermitian Toeplitz matrices, SIAM J. Matrix Analysis\n and Appl., 10 (1989), pp. 135-146 (and see the references therein).\n\"\"\"\nfunction kms(::Type{T}, n::Integer, rho::Number) where T\n A = typeof(rho) <: Complex ? Array{typeof(rho)}(undef, n, n) : Array{T,2}(undef, n, n)\n [A[i,j] = rho^(abs(i-j)) for i = 1:n, j = 1:n]\n if typeof(rho) <: Complex\n A = conj(tril(A, -1)) + triu(A)\n end\n return A\nend\nkms(::Type{T}, n::Integer) where T = kms(T, n, convert(T, 0.5))\nkms(args...) = kms(Float64, args...)\nkms(::Type, args...) = throw(MethodError(kms, Tuple(args)))\n\n\"\"\"\nWathen Matrix\n=============\nWathen Matrix is a sparse, symmetric positive, random matrix\narose from the finite element method. The generated matrix is\nthe consistent mass matrix for a regular nx-by-ny grid of\n8-nodes.\n\n*Input options:*\n\n+ [type,] nx, ny: the dimension of the matrix is equal to\n `3 * nx * ny + 2 * nx * ny + 1`.\n\n+ [type,] n: `nx = ny = n`.\n\n*Groups:* [\"symmetric\", \"posdef\", \"eigen\", \"random\", \"sparse\"]\n\n*References:*\n\n**A. J. Wathen**, Realistic eigenvalue bounds for\n the Galerkin mass matrix, IMA J. Numer. Anal., 7 (1987),\n pp. 449-457.\n\"\"\"\nfunction wathen(::Type{T}, nx::Integer, ny::Integer) where T\n e1 = T[6 -6 2 -8;-6 32 -6 20;2 -6 6 -6;-8 20 -6 32]\n e2 = T[3 -8 2 -6;-8 16 -8 20;2 -8 3 -8;-6 20 -8 16]\n e3 = [e1 e2; e2' e1]/45\n n = 3 * nx * ny + 2 * nx + 2 * ny + 1\n ntriplets = nx * ny * 64\n Irow = zeros(Int, ntriplets)\n Jrow = zeros(Int, ntriplets)\n Xrow = zeros(T, ntriplets)\n ntriplets = 0\n rho = 100 * rand(nx, ny)\n node = zeros(T, 8)\n\n for j = 1:ny\n for i = 1:nx\n\n node[1] = 3 * j * nx + 2 * i + 2 * j + 1\n node[2] = node[1] - 1\n node[3] = node[2] - 1\n node[4] = (3 * j - 1) * nx + 2 * j + i - 1\n node[5] = (3 * j - 3) * nx + 2 * j + 2 * i - 3\n node[6] = node[5] + 1\n node[7] = node[5] + 2\n node[8] = node[4] + 1\n\n em = convert(T, rho[i,j]) * e3\n\n for krow = 1:8\n for kcol = 1:8\n ntriplets += 1\n Irow[ntriplets] = node[krow]\n Jrow[ntriplets] = node[kcol]\n Xrow[ntriplets] = em[krow, kcol]\n end\n end\n\n end\n end\n return sparse(Irow, Jrow, Xrow, n, n)\nend\nwathen(::Type{T}, n::Integer) where T = wathen(T, n, n)\nwathen(args...) = wathen(Float64, args...)\nwathen(::Type, args...) = throw(MethodError(wathen, Tuple(args)))\n\n\"\"\"\nGolub Matrix\n============\nGolub matrix is the product of two random unit lower and upper\n triangular matrices respectively. LU factorization without pivoting\n fails to reveal that such matrices are badly conditioned.\n\n*Input options:*\n\n+ [type,] dim: the dimension of the matrix.\n\n*References:*\n\n**D. Viswanath and N. Trefethen**. Condition Numbers of\n Random Triangular Matrices, SIAM J. Matrix Anal. Appl. 19, 564-581,\n 1998.\n\"\"\"\nfunction golub(::Type{T}, n::Integer) where T\n s = 10\n L = Array{T,2}(undef, n, n)\n U = Array{T,2}(undef, n, n)\n if T <: Integer\n [L[i,j] = round_matlab(T, s*randn()) for j = 1:n, i = 1:n]\n [U[i,j] = round_matlab(T, s*randn()) for j = 1:n, i = 1:n]\n else\n [L[i,j] = s*randn() for j = 1:n, i = 1:n]\n [U[i,j] = s*randn() for j = 1:n, i = 1:n]\n end\n L = tril(L, -1) + Matrix{T}(I, n, n)\n U = triu(U, 1) + Matrix{T}(I, n, n)\n return L*U\nend\ngolub(n::Integer) = golub(Float64, n)\n\n\"\"\"\nCompanion Matrix\n================\nThe companion matrix to a monic polynomial\n `a(x) = a_0 + a_1x + ... + a_{n-1}x^{n-1} + x^n`\n is the n-by-n matrix with ones on the subdiagonal and\n the last column given by the coefficients of `a(x)`.\n\n*Input options:*\n\n+ [type,] vec: `vec` is a vector of coefficients.\n\n+ [type,] dim: `vec = [1:dim;]`. `dim` is the dimension of the matrix.\n\"\"\"\nfunction companion(::Type{T}, v::AbstractVector) where T\n n = length(v)\n A = zeros(T, n, n)\n A[:, end] = v\n for i = 1:n-1\n A[i+1, i] = one(T)\n end\n A\nend\ncompanion(::Type{T}, n::Integer) where T = companion(T, [1:n;])\ncompanion(args...) = companion(Float64, args...)\ncompanion(::Type, args...) = throw(MethodError(companion, Tuple(args)))\n", "meta": {"hexsha": "fc8b3be9a08515ae6a82075c46af1c1dcc3e3694", "size": 45755, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/higham.jl", "max_stars_repo_name": "RalphAS/MatrixDepot.jl", "max_stars_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/higham.jl", "max_issues_repo_name": "RalphAS/MatrixDepot.jl", "max_issues_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/higham.jl", "max_forks_repo_name": "RalphAS/MatrixDepot.jl", "max_forks_repo_head_hexsha": "e8fbff2371991554cfd33f9222c5a25bbdb63326", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7808136005, "max_line_length": 102, "alphanum_fraction": 0.5712818271, "num_tokens": 15256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305339244013, "lm_q2_score": 0.8333246035907933, "lm_q1q2_score": 0.8026837028490998}} {"text": "\"\"\"\n frft(signal, α)\n\nBy entering the signal and the order, we can obtain the Fractional Fourier transform value.\n\n# Example\n\n```julia-repl\njulia> frft([1,2,3], 0.5)\n0.10046461358821344 - 0.25940948097727745im\n3.0746001042331557 + 0.19934938154063286im\n1.3156643288728376 - 0.9364535656119107im\n```\n\"\"\"\nfunction frft(signal, α)::Vector{ComplexF64}\n \n #Ensure the input signal is proper\n isa(signal, AbstractArray) ? nothing : error(\"Please input a proper signal\")\n\n N = length(signal)\n M = Int64((N-1)/2)\n\n if rem(N, 2)==0\n error(\"Signal must be odd\")\n end\n\n ##For α special cases\n #If the order is an integer, the fourier transform would be its n-th order Fourier transform.\n α = mod(α, 4)\n if α == 0\n return signal\n elseif α == 1\n y = fft([signal[M+1:N]; signal[1:M]])/sqrt(N)\n y = [y[M+2 : N]; y[1:M+1]]\n return y\n elseif α == 2\n y = reverse(signal, dims=1)\n return y\n elseif α == 3\n y = fft([signal[M+1:N]; signal[1:M]])*sqrt(N)\n y = [y[M+2 : N]; y[1:M+1]]\n return y\n end\n\n if α > 2\n signal = reverse(signal, dims=1)\n α = α-2\n end\n if 1.5 < α < 2\n y = fft([signal[M+1:N]; signal[1:M]]) ./sqrt(N)\n y = [y[M+2 : N]; y[1:M+1]]\n α = α-1\n end\n if α < 0.5\n y = fft([signal[M+1:N]; signal[1:M]]) .*sqrt(N)\n y = [y[M+2 : N]; y[1:M+1]]\n α = α+1\n end\n\n # We need to distinguish **order** and **angle**\n ϕ = α*π/2\n\n # Set the sampling rate as 3.\n signal = sinc_interp(signal, 3)\n signal = [zeros(ComplexF64, 2*M); signal; zeros(ComplexF64, 2*M)]\n\n x2 = freq_shear(signal, 2*pi/N*(cot(ϕ)-csc(ϕ))/3^2)\n x3 = time_shear(x2, 2*pi/N*csc(ϕ)/3^2)\n y = freq_shear(x3, 2*pi/N*(cot(ϕ)-csc(ϕ))/3^2)\n\n y = y[2*M+1:end-2*M]\n y = y[1:3:end]\n y = @. exp(-im*(pi*sign(sin(ϕ))/4-ϕ/2))*y\n\n return y\nend\n\nfunction freq_shear(x, c)\n x = x[:]\n N = length(x)\n if rem(N, 2) == 0\n error(\"Signal must be odd\")\n end\n\n M = (N-1)/2\n N = collect(-M:M)\n\n y = @. x*exp(im*c/2*N^2)\n return y\nend\n\nfunction time_shear(x, c)\n x = x[:]\n N = length(x)\n\n if rem(N, 2) == 0\n error(\"Signal must be odd\")\n end\n M = Int64((N-1)/2)\n \n interp = ceil(Int, 2*abs(c)/(2*pi/N))\n xx = sinc_interp(x, interp) ./interp\n n = collect(-2*M:1/interp:2*M)\n z = @. exp(im*c/2*n^2)\n y = conv(xx, z)\n center = (length(y)+1)/2\n y = y[Int64(center-interp*M):Int64(interp):Int64(center+interp*M)]\n y = @. y*sqrt(c/2/pi)\nend\n\n\"\"\"\n sinc_interp(signal, rate)\n\n```Sinc interpolation``` of **signal** at rate **rate**.\n\nFor more details, please refer to [Whittaker-Shannon interpolation](https://en.wikipedia.org/wiki/Whittaker%E2%80%93Shannon_interpolation_formula).\n\"\"\"\nfunction sinc_interp(x, rate)\n x = x[:]\n N = length(x)\n M = rate*N - rate + 1\n\n y = zeros(ComplexF64, M)\n y[1:rate:M] = x\n\n h = sinc.(collect(-(N-1-1/rate):1/rate:(N-1-1/rate)))\n out = conv(y, h)\n out = out[(rate*N-rate):(end-rate*N+rate+1)]\nend", "meta": {"hexsha": "cb4c27e1f1554ae68353ea97103a198f8aa331ac", "size": 3080, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/frft.jl", "max_stars_repo_name": "SciFracX/FractionalTransforms.jl", "max_stars_repo_head_hexsha": "f343419db8e79a3f08ae1d95faae5495f877317b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-11-07T22:00:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T00:49:40.000Z", "max_issues_repo_path": "src/frft.jl", "max_issues_repo_name": "SciFracX/FractionalTransforms.jl", "max_issues_repo_head_hexsha": "f343419db8e79a3f08ae1d95faae5495f877317b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-11-16T15:53:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-10T06:08:16.000Z", "max_forks_repo_path": "src/frft.jl", "max_forks_repo_name": "SciFracX/FractionalTransforms.jl", "max_forks_repo_head_hexsha": "f343419db8e79a3f08ae1d95faae5495f877317b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-08T12:06:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-08T12:06:40.000Z", "avg_line_length": 23.8759689922, "max_line_length": 147, "alphanum_fraction": 0.5461038961, "num_tokens": 1134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966686936262, "lm_q2_score": 0.8479677660619633, "lm_q1q2_score": 0.8026834625138307}} {"text": "module DiffSolving\n\nexport EulerMethod, InstableAlgorithm, EulerCromer, Verlet, VelocityVerlet\n\nusing LaTeXStrings, Plots, ProgressBars, Statistics, StatsBase\ncd(dirname(@__FILE__))\n#First Order ODE_Comparison between Euler method's and Numerical solution\n\nfunction EulerMethod(func::Function, xᵢₙᵢₜ::Vector{Float64}, tₘᵢₙ::Float64, tₘₐₓ::Float64, h::Float64)\n t_range=collect(range(tₘᵢₙ, tₘₐₓ, step=h))\n Q=zeros(length(t_range), length(xᵢₙᵢₜ))\n Q[1, :]=xᵢₙᵢₜ\n\n for (i,t) in enumerate(t_range[1:end-1])\n Q[i+1, :] = Q[i, :] + func(t,Q[i, :])*h\n end\n return t_range, Q\nend\n\nfunction InstableAlgorithm(func::Function, xᵢₙᵢₜ::Float64, tₘᵢₙ::Float64, tₘₐₓ::Float64, h::Float64 )\n t_range=collect(range(tₘᵢₙ, tₘₐₓ, step=h))\n Q=zeros(length(t_range))\n\n Q[1]=xᵢₙᵢₜ\n Q[2]=xᵢₙᵢₜ + h*func(tₘᵢₙ, xᵢₙᵢₜ )\n for i in 2:length(t_range)-1\n Q[i+1] = Q[i-1] + 2*h*func(t_range[i], Q[i])\n end\n return t_range, Q\nend\n\n#Second Order ODE\n#Simple Harmonic Oscillator\n\nfunction EulerCromer(func::Function, xᵢₙᵢₜ::Float64, vᵢₙᵢₜ::Float64, tₘᵢₙ::Float64, tₘₐₓ::Float64, h::Float64)\n t=collect(range(tₘᵢₙ, tₘₐₓ, step=h))\n x=zeros(length(t))\n v=zeros(length(t))\n\n v[1]= vᵢₙᵢₜ\n x[1]= xᵢₙᵢₜ\n for i in 1:length(t)-1\n v[i+1] = v[i] + h * func(t[i], x[i])\n x[i+1] = x[i] + h * v[i+1]\n end\n \n return t, x, v\nend\n\n\nfunction Verlet(func::Function, xᵢₙᵢₜ::Float64, vᵢₙᵢₜ::Float64, tₘᵢₙ::Float64, tₘₐₓ::Float64, h::Float64)\n t=collect(range(tₘᵢₙ, tₘₐₓ, step=h))\n x=zeros(length(t))\n v=zeros(length(t))\n\n v[1]= vᵢₙᵢₜ\n x[1]= xᵢₙᵢₜ\n x[2]= xᵢₙᵢₜ + vᵢₙᵢₜ * h + func(tₘᵢₙ, xᵢₙᵢₜ ) * h^2 *1/2\n\n for i in 2: length(t)-1\n x[i+1]= 2 * x[i] - x[i-1] + func(t[i], x[i]) * h^2\n v[i+1]= (x[i+1] - x[i])/h\n end\n return t, x, v\nend\n\nfunction VelocityVerlet(func::Function, xᵢₙᵢₜ::Float64, vᵢₙᵢₜ::Float64, tₘᵢₙ::Float64, tₘₐₓ::Float64, h::Float64)\n t= collect(range(tₘᵢₙ, tₘₐₓ, step=h))\n x=zeros(length(t))\n v=zeros(length(t))\n\n v[1]= vᵢₙᵢₜ\n x[1]= xᵢₙᵢₜ\n\n for i in 1:length(t)-1\n x[i+1] = x[i] + v[i] * h + func(t[i], x[i]) * h^2 * 1/2\n v[i+1] = v[i] + (func(t[i], x[i]) + func(t[i+1], x[i+1])) * h * 1/2\n end\n \n return t, x, v\nend\n\nend", "meta": {"hexsha": "482e1fa87c2499db40773be6f53616b5bb828a1d", "size": 2257, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "PSet9/DiffSolving.jl", "max_stars_repo_name": "narges8k/computational_physics", "max_stars_repo_head_hexsha": "a24229aa7b31648735aab120cd667dffd788df1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PSet9/DiffSolving.jl", "max_issues_repo_name": "narges8k/computational_physics", "max_issues_repo_head_hexsha": "a24229aa7b31648735aab120cd667dffd788df1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PSet9/DiffSolving.jl", "max_forks_repo_name": "narges8k/computational_physics", "max_forks_repo_head_hexsha": "a24229aa7b31648735aab120cd667dffd788df1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-13T09:55:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T09:55:00.000Z", "avg_line_length": 27.1927710843, "max_line_length": 113, "alphanum_fraction": 0.5999113868, "num_tokens": 1140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966702001758, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.8026834565175571}} {"text": "\nfunction score(x, y)\n circles = [\n (1, 10), # inner\n (5, 5), # middle\n (10, 1), # outer\n ]\n\n # distance from origin = (0, 0)\n d = sqrt(x^2 + y^2)\n\n for (radius, score) in circles\n if d <= radius\n return score\n end\n end\n return 0\nend\n", "meta": {"hexsha": "70b053f1c4dfe4c96e8227970673a17c4697ef36", "size": 302, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "exercism-solutions/julia/darts/darts.jl", "max_stars_repo_name": "twolodzko/Learning", "max_stars_repo_head_hexsha": "e5af2bdf6f65648c3c159343e14d63c157384009", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exercism-solutions/julia/darts/darts.jl", "max_issues_repo_name": "twolodzko/Learning", "max_issues_repo_head_hexsha": "e5af2bdf6f65648c3c159343e14d63c157384009", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exercism-solutions/julia/darts/darts.jl", "max_forks_repo_name": "twolodzko/Learning", "max_forks_repo_head_hexsha": "e5af2bdf6f65648c3c159343e14d63c157384009", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.8947368421, "max_line_length": 35, "alphanum_fraction": 0.4437086093, "num_tokens": 101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9511422213778251, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.8026642661878208}} {"text": "#using Pkg\n#Pkg.add(\"DifferentialEquations\")\nusing Plots\nusing DifferentialEquations\n\na = 0.25\neps = 0.002\nIapp = 0.0\ngam = 1.1\np = [a,eps,gam,Iapp]\ntspan = (0.0,1000.0)\n\nfunction FN(du,u,t,p)\n du[1] = u[1]*(a-u[1])*(u[1]-1)-u[2]+Iapp\n du[2] = eps*(u[1]-gam*u[2])\nend\n\nfunction apply(u0)\n prob = ODEProblem(FN,u0,tspan)\n sol = solve(prob)\nend\n\nsol1 = apply([0.1,0.0])\nsol2 = apply([0.2,0.0])\nsol3 = apply([0.3,0.0])\nsol4 = apply([0.4,0.0])\n\np1 = plot(sol1,linecolor = :red)\np2 = plot!(sol2, linecolor = :blue)\np3 = plot!(sol3, linecolor = :green)\np4 = plot!(sol4, linecolor = :yellow)\n\n# Phase-space\np1 = plot(sol1,vars = (1,2),linecolor = :red,xlims = (-0.25,1),ylims = (0,0.125))\np2 = plot!(sol2,vars = (1,2), linecolor = :blue,xlims = (-0.25,1),ylims = (0,0.125))\np3 = plot!(sol3,vars = (1,2), linecolor = :green,xlims = (-0.25,1),ylims = (0,0.125))\np4 = plot!(sol4,vars = (1,2), linecolor = :yellow,xlims = (-0.25,1),ylims = (0,0.125), xlabel=\"v\",ylabel=\"w\")\n\n# Nullclines\n# dv = -v^3 + (a-1)*v^2 -a*v -w = 0\n#-> w = -v^3 + (a-1)*v^2 -a*v\n# dw = eps*(v-gam*w) = 0\n# -> w = v/gamma\n\nfunction FNnc(u,p)\n ncv = u.*(a.-u).*(u.-1).+Iapp\n ncw = u./gam\n nc = [ncv,ncw]\nend\n\nu = collect(-0.25:0.1:1.5)\nnc = FNnc(u,p)\nplot!(u,nc)\n\n# One sees that v grows for v0>0.25 (yellow&green) until\n# they intersect with the nullcline (turkis) and then decreases\n# while w grows rapidly.\n# They all follow the trajectory until they reach the fixed point (0,0)\n\n\n## Testing influence of Iapp\nu0 = [0.3;0.0]\nIapp = 0.02\nsol5 = apply(u0)\nnc5 = FNnc(u,[a,eps,gam,Iapp])\nIapp = 0.1\nsol6 = apply(u0)\nnc6 = FNnc(u,[a,eps,gam,Iapp])\nIapp = 0.5\nsol7 = apply(u0)\nnc7 = FNnc(u,[a,eps,gam,Iapp])\nIapp = 0.7\nsol8 = apply(u0)\nnc8 = FNnc(u,[a,eps,gam,Iapp])\n\np5 = plot(sol5,linecolor = :red)\np6 = plot!(sol6,linecolor = :blue)\np7 = plot!(sol7,linecolor = :green)\np8 = plot!(sol8,linecolor = :yellow)\n\np5 = plot(sol5,vars = (1,2),linecolor = :red, label=\"Iapp=0.02\")\np5nc = plot!(u,nc5,linecolor = :red, linestyle = :dash, label=\"Nullcline, Iapp=0.02\",ylim=(0,0.8))\np6 = plot!(sol6,vars = (1,2),linecolor = :blue, label=\"Iapp=0.1\")\np6nc = plot!(u,nc6,linecolor = :blue, linestyle = :dash, label=\"Nullcline, Iapp=0.1\")\np7 = plot!(sol7,vars = (1,2),linecolor = :green, label=\"Iapp=0.5\")\np7nc = plot!(u,nc7,linecolor = :green, linestyle = :dash, label=\"Nullcline, Iapp=0.5\")\np8 = plot!(sol8,vars = (1,2),linecolor = :yellow, label=\"Iapp=0.7\",xlim=(-0.25,1.5))\np8nc = plot!(u,nc8,linecolor = :yellow, linestyle = :dash, label=\"Nullcline, Iapp=0.7\")\n\n# Iapp gives higher/lower threshold for firing\n", "meta": {"hexsha": "bd98c483f0245ae3fb381d414657ce9b98a94bb8", "size": 2582, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Exercises/Tutorial_3_FitzHugh.jl", "max_stars_repo_name": "dlill/DynSysBio2019", "max_stars_repo_head_hexsha": "6fdf691a2fd184ac7fa665bc2865c619570f05f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-04-24T12:34:55.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-24T12:34:57.000Z", "max_issues_repo_path": "Exercises/Tutorial_3_FitzHugh.jl", "max_issues_repo_name": "dlill/DynSysBio2019", "max_issues_repo_head_hexsha": "6fdf691a2fd184ac7fa665bc2865c619570f05f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Exercises/Tutorial_3_FitzHugh.jl", "max_forks_repo_name": "dlill/DynSysBio2019", "max_forks_repo_head_hexsha": "6fdf691a2fd184ac7fa665bc2865c619570f05f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-04-24T12:33:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-31T09:20:23.000Z", "avg_line_length": 28.3736263736, "max_line_length": 109, "alphanum_fraction": 0.6154144074, "num_tokens": 1116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218262741297, "lm_q2_score": 0.8705972784807408, "lm_q1q2_score": 0.8026226329262516}} {"text": "mults = [1:1000]\n@time res = +(filter(x -> (x % 3 == 0) | (x % 5 == 0), mults)...)\nres = 0\n@time for m in mults\n if (m % 3 == 0) | (m % 5 == 0)\n res += m\n end\nend \nprintln(\"The answer to Euler Problem 1 is $res\")\n\n", "meta": {"hexsha": "0607972590be582527b23d6a116242137cb80d58", "size": 231, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Problem 1.jl", "max_stars_repo_name": "andrew-christianson/Polyglot-Euler", "max_stars_repo_head_hexsha": "e74e6cbdffb92255e604fab7d396af1c5f4cf55f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Problem 1.jl", "max_issues_repo_name": "andrew-christianson/Polyglot-Euler", "max_issues_repo_head_hexsha": "e74e6cbdffb92255e604fab7d396af1c5f4cf55f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Problem 1.jl", "max_forks_repo_name": "andrew-christianson/Polyglot-Euler", "max_forks_repo_head_hexsha": "e74e6cbdffb92255e604fab7d396af1c5f4cf55f", "max_forks_repo_licenses": ["MIT"], "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": 66, "alphanum_fraction": 0.4675324675, "num_tokens": 98, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218370002789, "lm_q2_score": 0.8705972616934406, "lm_q1q2_score": 0.8026226267878293}} {"text": "\"\"\"\n greens_lorentzian(κ)\n\nEvaluate the Green's function corresponding to a Lorentzian lineshape at `κ = (t-τ)/T2s`.\n\n# Examples\n```jldoctest\njulia> t = 100e-6;\n\njulia> τ = 0;\n\njulia> T2s = 10e-6;\n\njulia> greens_lorentzian((t-τ)/T2s)\n4.5399929762484854e-5\n```\n\"\"\"\nfunction greens_lorentzian(κ)\n exp(-κ)\nend\n\n\"\"\"\n dG_o_dT2s_x_T2s_lorentzian(κ)\n\nEvaluate the derivative of Green's function, corresponding to a Lorentzian lineshape, wrt. `T2s` at `κ = (t-τ)/T2s` and multiply it by `T2s`.\n\nThe multiplication is added so that the function merely depends on `κ = (t-τ)/T2s`. The actual derivative is given by `dG_o_dT2s_x_T2s_lorentzian((t-τ)/T2s)/T2s`.\n\n# Examples\n```jldoctest\njulia> t = 100e-6;\n\njulia> τ = 0;\n\njulia> T2s = 10e-6;\n\njulia> dGdT2s = dG_o_dT2s_x_T2s_lorentzian((t-τ)/T2s)/T2s\n45.39992976248485\n```\n\"\"\"\nfunction dG_o_dT2s_x_T2s_lorentzian(κ)\n greens_lorentzian(κ) * κ\nend\n\n\"\"\"\n greens_gaussian(κ)\n\nEvaluate the Green's function corresponding to a Gaussian lineshape at `κ = (t-τ)/T2s`.\n\n# Examples\n```jldoctest\njulia> t = 100e-6;\n\njulia> τ = 0;\n\njulia> T2s = 10e-6;\n\njulia> greens_gaussian((t-τ)/T2s)\n1.9287498479639178e-22\n```\n\"\"\"\nfunction greens_gaussian(κ)\n exp(-κ^2 / 2)\nend\n\n\"\"\"\n dG_o_dT2s_x_T2s_gaussian(κ)\n\nEvaluate the derivative of Green's function, corresponding to a Gaussian lineshape, wrt. `T2s` at `κ = (t-τ)/T2s` and multiply it by `T2s`.\n\nThe multiplication is added so that the function merely depends on `κ = (t-τ)/T2s`. The actual derivative is given by `dG_o_dT2s_x_T2s_gaussian((t-τ)/T2s)/T2s`.\n\n# Examples\n```jldoctest\njulia> t = 100e-6;\n\njulia> τ = 0;\n\njulia> T2s = 10e-6;\n\njulia> dGdT2s = dG_o_dT2s_x_T2s_gaussian((t-τ)/T2s)/T2s\n1.9287498479639177e-15\n```\n\"\"\"\nfunction dG_o_dT2s_x_T2s_gaussian(κ)\n greens_gaussian(κ) * κ^2\nend\n\n\"\"\"\n greens_superlorentzian(κ)\n\nEvaluate the Green's function corresponding to a super-Lorentzian lineshape at `κ = (t-τ)/T2s`.\n\n# Examples\n```jldoctest\njulia> t = 100e-6;\n\njulia> τ = 0;\n\njulia> T2s = 10e-6;\n\njulia> greens_superlorentzian((t-τ)/T2s)\n0.1471246868094442\n```\n\"\"\"\nfunction greens_superlorentzian(κ)\n quadgk(ζ -> exp(- κ^2 * (3ζ^2 - 1)^2 / 8), 0, sqrt(1/3), 1, order = 100)[1]\nend\n\n\"\"\"\n dG_o_dT2s_x_T2s_superlorentzian(κ)\n\nEvaluate the derivative of Green's function, corresponding to a super-Lorentzian lineshape, wrt. `T2s` at `κ = (t-τ)/T2s` and multiply it by `T2s`.\n\nThe multiplication is added so that the function merely depends on `κ = (t-τ)/T2s`. The actual derivative is given by `dG_o_dT2s_x_T2s_superlorentzian((t-τ)/T2s)/T2s`.\n\n# Examples\n```jldoctest\njulia> t = 100e-6;\n\njulia> τ = 0;\n\njulia> T2s = 10e-6;\n\njulia> dGdT2s = dG_o_dT2s_x_T2s_superlorentzian((t-τ)/T2s)/T2s\n15253.095033670965\n```\n\"\"\"\nfunction dG_o_dT2s_x_T2s_superlorentzian(κ)\n quadgk(ζ -> exp(-κ^2 * (3ζ^2 - 1)^2 / 8) * (κ^2 * (3ζ^2 - 1)^2 / 4), 0, sqrt(1/3), 1, order = 100)[1]\nend\n\n\n\"\"\"\n interpolate_greens_function(f, κmin, κmax)\n\nInterpolate the Green's function f in the range between κmin and κmax.\n\nThe interpolation uses the ApproxFun.jl package that incorporates Chebyshev polynomials and ensures an approximation to machine precision. \n\n# Examples\n```jldoctest\njulia> t = 100e-6;\n\njulia> τ = 0;\n\njulia> T2s = 10e-6;\n\njulia> greens_superlorentzian((t-τ)/T2s)\n0.1471246868094442\n\njulia> Gint = interpolate_greens_function(greens_superlorentzian, 0, 20);\n\n\njulia> Gint((t-τ)/T2s)\n0.14712468680944407\n```\n\"\"\"\nfunction interpolate_greens_function(f, κmin, κmax)\n Fun(f, κmin..κmax)\n # x = κmin : 0.001 : κmax\n # return CubicSplineInterpolation(x, f.(x))\nend", "meta": {"hexsha": "d82dcec8277c8c5b04c4b4605a145d755b4845d3", "size": 3565, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Greens_functions.jl", "max_stars_repo_name": "JakobAsslaender/MRIgeneralizedBloch.jl", "max_stars_repo_head_hexsha": "d3404b11e21ae71b5bb1388fcdbf1038d5c30098", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-07-19T19:25:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T14:05:20.000Z", "max_issues_repo_path": "src/Greens_functions.jl", "max_issues_repo_name": "JakobAsslaender/MRIgeneralizedBloch.jl", "max_issues_repo_head_hexsha": "d3404b11e21ae71b5bb1388fcdbf1038d5c30098", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2021-07-19T04:29:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T17:10:52.000Z", "max_forks_repo_path": "src/Greens_functions.jl", "max_forks_repo_name": "JakobAsslaender/MRIgeneralizedBloch.jl", "max_forks_repo_head_hexsha": "d3404b11e21ae71b5bb1388fcdbf1038d5c30098", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8711656442, "max_line_length": 167, "alphanum_fraction": 0.698457223, "num_tokens": 1451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505248181417, "lm_q2_score": 0.8872045847699186, "lm_q1q2_score": 0.8026100932331683}} {"text": "using Plots\n\nRotation(x, y, θ) = [cos(θ) -sin(θ);sin(θ) cos(θ)] * [x;y]\n\nfunction KochCurve(; points, order, θ)\n for n in 1:order\n i = 1\n while i < length(points)\n insert!(points,i+1,(points[i+1] - points[i]) /3 + points[i])\n delta = (points[i+2] - points[i]) *2 /3 + points[i] - points[i+1]\n insert!(points, i+2, Rotation(delta[1], delta[2], θ)+points[i+1])\n insert!(points,i+3,(points[i+3] - points[i]) *2 /3 + points[i])\n i += 4\n end\n end\n return points\nend\n\nStartPoints = [[[0.0; 0.0],[10.0; 0.0]],\n [[0.0; 0.0],[10.0; 0.0],[5.0; 8.66],[0.0; 0.0]],\n [[0.0; 0.0],[10.0; 0.0],[5.0; 8.66],[0.0; 0.0]],\n [[0.0; 0.0],[10.0; 0.0],[5.0; 8.66],[0.0; 0.0]]\n ]\nAdegs = [pi/3, pi/3, -pi/3, 2*pi/3,]\n\nylimlist = [(0,5), (0,10),(-3,9), (0,10)]\nxlimlist = [(0,10), (0,10),(-1,11), (0,10)]\n\nfor j in 1:5\n for i in 1:4\n Parameters = Dict(\n :points => StartPoints[i],\n :order => j,\n :θ => Adegs[i])\n points = KochCurve(;Parameters...)\n plot(hcat(points...)[1,:], hcat(points...)[2,:], legend = false, border=:none, fill =(0), ylims = ylimlist[i], xlims = xlimlist[i])\n savefig(\"C:\\\\Users\\\\Yaghoub\\\\Documents\\\\GitHub\\\\ComputationalPhysics-Fall2021\\\\ProblemSet1\\\\Figs\\\\Q1\\\\KochCurve$(i)O$(j).png\")\n end\nend\n", "meta": {"hexsha": "a7975c1d04dc4b53d9c4071ab55e9508f6dec1e0", "size": 1416, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ProblemSet1/Codes/Q1.jl", "max_stars_repo_name": "shahmari/ComputationalPhysics-Fall2021", "max_stars_repo_head_hexsha": "f1681e32258c55697d11009e1702eb86d5f119d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ProblemSet1/Codes/Q1.jl", "max_issues_repo_name": "shahmari/ComputationalPhysics-Fall2021", "max_issues_repo_head_hexsha": "f1681e32258c55697d11009e1702eb86d5f119d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ProblemSet1/Codes/Q1.jl", "max_forks_repo_name": "shahmari/ComputationalPhysics-Fall2021", "max_forks_repo_head_hexsha": "f1681e32258c55697d11009e1702eb86d5f119d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-21T11:07:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-21T11:07:08.000Z", "avg_line_length": 35.4, "max_line_length": 139, "alphanum_fraction": 0.4766949153, "num_tokens": 544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259924, "lm_q2_score": 0.8539127566694178, "lm_q1q2_score": 0.8026039995803}} {"text": "# Start with a copy of Petri.jl examples/lotka-volterra.jl.\n#\nusing PNML\nusing Petri\nusing LabelledArrays\nusing Plots\nusing OrdinaryDiffEq\n\n\n\"\"\"\nPNML model for the original example below. Note that the type is \"nonstandard\"!\n\"\"\"\n str = \"\"\"\n \n \n \n 100.0 \n 10.0 \n 0.3 \n 0.7 \n 0.015 \n 1 \n 2 \n 1 \n 1 \n 2 \n 1 \n \n \n \n\"\"\" \n \nnet = PNML.SimpleNet(str)\n\n# **Step 1:** Define the states and transitions of the Petri Net\n# \n# Here we have 2 states, wolves and rabbits, and transitions to\n# model predation between the two species in the system\n\nS = PNML.place_ids(net) # [:rabbits, :wolves]\nΔ = PNML.transition_function(net)\n# keys are transition ids\n# values are tuple of input, output vectors of \"tuples\" place id = inscription\n#LVector(\n# birth=(LVector(rabbits=1), LVector(rabbits=2)),\n# predation=(LVector(wolves=1, rabbits=1), LVector(wolves=2)),\n# death=(LVector(wolves=1), LVector()),\n# )\nlotka = Petri.Model(S, Δ)\n\ndisplay(Graph(lotka))\n\n\n# **Step 2:** Define the parameters and transition rates\n#\n# Once a model is defined, we can define out initial parameters `u0`, a time\n# span `tspan`, and the transition rates of the interactions `β`\n\nu0 = PNML.initialMarking(net) #LVector(wolves=10.0, rabbits=100.0) # initialMarking\ntspan = (0.0,100.0)\nβ = PNML.rates(net) #LVector(birth=.3, predation=.015, death=.7); # transition rate\n\n# **Step 3:** Generate a solver and solve\n#\n# Finally we can generate a solver and solve the simulation\n\nprob = ODEProblem(lotka, u0, tspan, β) # transform PetriNet problem using vectorfield(m)\nsol = OrdinaryDiffEq.solve(prob,Tsit5(),reltol=1e-8,abstol=1e-8)\n\nplot(sol)\n\n", "meta": {"hexsha": "abfb30dba703a5548ad033bf7bcc71201989b9ca", "size": 2886, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/lotka-volterra.jl", "max_stars_repo_name": "strangehurst/PNML.jl", "max_stars_repo_head_hexsha": "533f12a3aff49a60175a4703a2ac6fa1fb371925", "max_stars_repo_licenses": ["MIT"], "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/lotka-volterra.jl", "max_issues_repo_name": "strangehurst/PNML.jl", "max_issues_repo_head_hexsha": "533f12a3aff49a60175a4703a2ac6fa1fb371925", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/lotka-volterra.jl", "max_forks_repo_name": "strangehurst/PNML.jl", "max_forks_repo_head_hexsha": "533f12a3aff49a60175a4703a2ac6fa1fb371925", "max_forks_repo_licenses": ["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.0833333333, "max_line_length": 113, "alphanum_fraction": 0.6451836452, "num_tokens": 869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133447766225, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.8026039917742501}} {"text": "# # Custom Cone Constraint\n#\n# This example demonstrate how the user can extend `COSMO` with his own custom convex cones and use them in constraints. To make things easy, we will implement the simple cone of **Nonpositives**, i.e. $\\mathbb{R}_{-}^n = \\{x \\in \\mathbb{R}^n \\mid x_i \\leq 0\\}$.\n# ## Cone definition and projection function\n# We start by creating a concrete subtype of our cone interface-type: `COSMO.AbstractConvexCone{T}`, where `T` is a parameter for the floating-point precision. The only field that is strictly required for our cone definition is `dim`, which is used by the solver to store information about the cone dimension. However, you can also use the object to store other information, or allocate the workspace necessary for the projection step.\nusing COSMO, LinearAlgebra, SparseArrays, Test\n\n## define new cone type\nstruct Nonpositives{T} <: COSMO.AbstractConvexSet{T}\n dim::Int64\nend\n#-\n# Next, we define a projection method for `Nonpositives{T}` that takes a vector `x` and projects it onto our custom cone. For the cone of nonpositive vectors the projection simply sets all positive elements of `x` to zero:\n\nfunction COSMO.project!(x::AbstractVector{T}, C::Nonpositives{T}) where {T <: AbstractFloat}\n x .= min.(x, zero(T))\nend\n\n#-\n# This is all that is required to get a basic constraint working. Let's test our new cone/constraint by solving the following LP:\n# $$\n# \\begin{array}{ll} \\text{maximize} & x_1 + x_2 + x_3\\\\\n# \\text{subject to} & x_1 \\leq 3 \\\\\n# & x_2 \\leq 2 \\\\\n# & x_1 + x_3 = 5\n# \\end{array}\n# $$\n# We define our decision vector $x = (x_1, x_2, x_3)$ and setup the problem:\nn = 3\nP = spzeros(n, n)\nq = -ones(n)\n\n## A1 * x + b1 <= 0\nA1 = diagm(0 => ones(2))\nb1 = [-3.; -2.]\nc1 = COSMO.Constraint(A1, b1, Nonpositives, n, 1:2); #here we use our new cone\n\n## x_1 + x_3 == 5\nA2 = [1. 0 1.]\nb2 = [-5.]\nc2 = COSMO.Constraint(A2, b2, COSMO.ZeroSet);\n\n## assemple and solve\nmodel = COSMO.Model();\nassemble!(model, P, q, [c1; c2]);\nres = COSMO.optimize!(model);\n\n#-\nres.x\n\n#-\nobj_val = -dot(q, res.x)\n# The problem was solved using constraints involving our new cone and yields the expected result. Next, we want to add the ability to detect infeasible problems.\n#\n# ## Support infeasibility detection\n# If no further information about the new cone is provided, the infeasibility detection is disabled. However, by defining the two additional methods `in_dual` and `in_pol_recc` we can support infeasibility detection. More information on how infeasible problems are detected in `COSMO` can be found here \\[1\\]. We will have to add the ability for the solver to check whether a vector is in the [dual cone](https://en.wikipedia.org/wiki/Dual_cone_and_polar_cone) $\\mathcal{K}^*$ of our new cone $\\mathcal{K}$ and whether a vector is in the recession cone of the [polar cone](https://en.wikipedia.org/wiki/Dual_cone_and_polar_cone) ${\\mathcal{K}^\\circ}^\\infty$ of our cone. The first function is used to check for primal infeasibility, while the second function is used to check for dual infeasibility. Luckily, for the Nonpositives-cone this is straightforward:\n#\n# $$\n# {\\mathbb{R}_{-}^n}^* = \\mathbb{R}_{-}^n, \\quad {{\\mathbb{R}_{-}^n}^\\circ}^\\infty = \\mathbb{R}_{+}^n.\n# $$\n\nfunction COSMO.in_dual(x::AbstractVector{T}, C::Nonpositives{T}, tol::T) where {T <: AbstractFloat}\n\treturn !any( x-> (x > -tol), x)\nend\n\nfunction COSMO.in_pol_recc(x::AbstractVector{T}, C::Nonpositives{T}, tol::T) where {T <: AbstractFloat}\n\treturn !any( x-> (x < tol), x)\nend\n# Notice that for numerical reasons, we give the check-functions a bit of slack using the tolerance parameter `tol`.\n# To test the infeasibility detection, we will attempt to use our new cone to solve the clearly dual infeasible problem:\n# $$\n# \\begin{array}{ll} \\text{minimize} & x\\\\\n# \\text{subject to} & x\\leq 3\n# \\end{array}\n# $$\nn = 1\nP = spzeros(n, n)\nq = [1.]\n\n## x <= 3 <=> x - 3 in Nonpositives\nAi = [1.]\nbi = [-3.]\nci = COSMO.Constraint(Ai, bi, Nonpositives);\n\nmodel = COSMO.Model();\nassemble!(model, P, q, [ci]);\nres = COSMO.optimize!(model);\n#-\n@test res.status == :Dual_infeasible\n\n# which is what we would expect.\n# ## Using new cone with JuMP\n# The nice composibility of Julia-code allows us to use our new cone definition even when the problem is modelled with `JuMP`. For this to work, we define a concrete subtype of `MOI.AbstractSet`, that JuMP can use to build a constraint.\nusing MathOptInterface, JuMP\nimport Base.copy\nconst MOI = MathOptInterface\n\nstruct NonPos <: MOI.AbstractVectorSet\n\tdimension::Int\nend\nBase.copy(set::NonPos) = set #this is needed for MOI\n# Next, we tell `COSMO` that whenever `JuMP` wants to solve a problem with a `NonPos`-cone it should translate it into a `Nonpositives` constraint and we also tell `MOI` that we now support constraints of this new mysterious cone `NonPos`.\nfunction COSMO.processSet!(b::Vector{T}, rows::UnitRange{Int}, cs, s::NonPos) where {T <: AbstractFloat}\n push!(cs, Nonpositives{T}(length(rows)))\n nothing\nend\n#tell MOI, that COSMO supports constraints with this new cone\nMOI.supports_constraint(optimizer::COSMO.Optimizer, ::Type{<:Union{MOI.VectorOfVariables, MOI.VectorAffineFunction{Float64}}}, ::Type{NonPos}) = true\n\n\n# We should now be able to model the LP from above in `JuMP` and solve it internally using our `Nonpositives` cone and projection function.\nmodel = JuMP.Model(COSMO.Optimizer);\n@variable(model, x[1:3]);\n@objective(model, Max, x[1] + x[2] + x[3]);\n@constraint(model, A1 * x[1:2] .+ b1 in NonPos(2));\n@constraint(model, x[1] + x[3] == 5);\nJuMP.optimize!(model)\n\n#-\nx_opt = JuMP.value.(x)\n# You can see in the solver output that indeed a set `Nonpositives` of `dim: 2` was used.\n#\n# The discussed cone of Nonpositives is of course trivial, but the ability to define new cones and constraints for `COSMO` can be very powerful to model complex problems.\n\n# ## References\n# [1] Garstka et al. - COSMO: A conic operator splitting method for convex conic problems (2020)\n", "meta": {"hexsha": "f038f4eb4ae97832ee8e3c517b75e564a8246304", "size": 6014, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/literate/custom_cone.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": "docs/src/literate/custom_cone.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": "docs/src/literate/custom_cone.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": 47.3543307087, "max_line_length": 860, "alphanum_fraction": 0.709344862, "num_tokens": 1790, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.8807970670261976, "lm_q1q2_score": 0.8025644161121936}} {"text": "#=\nWe compute the probability, $p_{\\text{self}}$, of a match between a spacer of length $l_t = l_s + l_p$ and a host genome of length $L$. Both sequences are assumed to be random and uncorrelated, and have equal nucleotide usage.\n\n* $l_s$ = spacer length\n* $l_p$ = PAM length\n* $L$ = host genome length\n\nWe consider the following model of cross-reactivity: within a length-$l_t$ alignment between spacer and host genome, up to $k_{\\text{fix}}$ mismatches are tolerated at fixed positions, and up to $k_{\\text{var}}$ mismatches are tolerated at any other position.\n\n* $k_{\\text{fix}}$ = no. of fixed-position mismatches\n* $k_{\\text{var}}$ = no. of variable-position mismatches\n\nFor a given alignment, the matching probability, $p_m$, is\n$$\\begin{aligned}\np_m(l_t,k_{\\text{fix}},k_{\\text{var}}) &= 4^{-l_t + k_{\\text{fix}}} \\sum_{i=0}^{k_{\\text{var}}}\\binom{l_t - k_{\\text{fix}}}{i} 3^{i}\\\\\n&\\approx 4^{-l_t + k_{\\text{fix}}} \\binom{l_t - k_{\\text{fix}}}{k_{\\text{var}}} 3^{k_{\\text{var}}},\n\\end{aligned}$$\nsince the largest term tends to dominate the sum.\n\nThen, the probability that there exists an alignment somewhere in the host genome is\n$$\\begin{aligned}\np_{\\text{self}}(L,l_t,k_{\\text{fix}},k_{\\text{var}}) &= 1 - [1 - p_m(l_t,k_{\\text{fix}},k_{\\text{var}})]^L\\\\\n&\\approx L p_m(l_t,k_{\\text{fix}},k_{\\text{var}}),\n\\end{aligned}$$\nassuming $p_m \\ll 1$.\n\nBelow, we define the following functions:\n\n| | all terms of sum | largest term of sum |\n|---------------------------|:----------------:|:-------------------:|\n| not taking $p_m \\ll 1$ | `F_self()` | `p_self1()` |\n| taking $p_m \\ll 1$ | | `p_self()` |\n=#\n\nusing SpecialFunctions\n\nlogbinom(l,k) = loggamma(l+1) - loggamma(l-k+1) - loggamma(k+1)\n\nk_tot(k_fix,k_var,l_t) = k_fix + (logbinom(l_t-k_fix,k_var) + k_var*log(3))/log(4)\n\np_m(l_t,k_fix,k_var) = 4.0^(- l_t + k_tot(k_fix,k_var,l_t))\n\np_self(L,l_t,k_fix,k_var) = L * p_m(l_t,k_fix,k_var)\n\np_self1(L,l_t,k_fix,k_var) = 1 - exp(L * log(1 - p_m(l_t,k_fix,k_var)))\n\n#=\n$F_{\\text{self}}(k)$ is also the CDF of the number of alignments with up to $k$ variable-position mismatches. Its PDF is\n$$p_{nn}(k) = F_{\\text{self}}(k) - F_{\\text{self}}(k-1).$$\n\nNote: `F_self()` and `p_nn()` require integer `k_var`, whereas `p_self()` and `p_self1()` allow non-integer `k_var` as input.\n=#\n\nF_self(L,l_t,k_fix,k_var::Int) = 1 - exp(L * log(1 - sum([p_m(l_t,k_fix,k) for k in 0:k_var])))\n\np_nn(L,l_t,k_fix,k_var::Int) = F_self(L,l_t,k_fix,k_var) - F_self(L,l_t,k_fix,k_var-1)", "meta": {"hexsha": "103026de69864f32526f746261bdb8ff843cc0e9", "size": 2547, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "self-targeting.jl", "max_stars_repo_name": "andim/crispr_repertoires", "max_stars_repo_head_hexsha": "6a998587550841451f8be8b58a40515c4c60d684", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "self-targeting.jl", "max_issues_repo_name": "andim/crispr_repertoires", "max_issues_repo_head_hexsha": "6a998587550841451f8be8b58a40515c4c60d684", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "self-targeting.jl", "max_forks_repo_name": "andim/crispr_repertoires", "max_forks_repo_head_hexsha": "6a998587550841451f8be8b58a40515c4c60d684", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.4821428571, "max_line_length": 259, "alphanum_fraction": 0.6262269336, "num_tokens": 885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768635777511, "lm_q2_score": 0.8499711832583696, "lm_q1q2_score": 0.8025231259403574}} {"text": "\"\"\"\nSolves the equations of fluid flow using \"Stable Fluids\" by Jos Stam with the\nFFT to obtain ultra-fast simulations.\n\nMomentum: ∂u/∂t + (u ⋅ ∇) u = − 1/ρ ∇p + ν ∇²u + f\n\nIncompressibility: ∇ ⋅ u = 0\n\nu: Velocity (2d vector)\np: Pressure\nf: Forcing\nν: Kinematic Viscosity\nρ: Density\nt: Time\n∇: Nabla operator (defining nonlinear convection, gradient and divergence)\n∇²: Laplace Operator\n\n----\n\nA unit square domain with periodic boundary conditions on each edge\n(= simulation on a torus)\n\n\n 1 +-------------------------------------------------+\n | |\n | * * |\n | * * * * |\n 0.8 | |\n | * |\n | * * |\n | * * |\n 0.6 | * |\n | * <- <- <- |\n | * <- <- <- |\n | -> -> -> * <- <- <- |\n | -> -> -> * * * |\n 0.4 | -> -> -> |\n | |\n | * * * |\n | * * |\n 0.2 | * * |\n | * |\n | * * * * * |\n | * |\n 0 +-------------------------------------------------+\n 0 0.2 0.4 0.6 0.8 1\n\n-> Centered in y but ofset in x there are two horizontal forcings in opposite\n directions\n\n-> Two fluid streams will \"collide\" with each other\n\n----- \n\nSolution Strategy:\n\n-> Start with zero velocity everywhere: u = [0, 0]\n\n1. Add forces\n\n w₁ = u + Δt f\n\n2. Convect by self-advection (set the value at the current\n location to be the value at the position backtraced\n on the streamline.) -> unconditionally stable\n\n w₂ = w₁(p(x, −Δt))\n\n3. Diffuse and Project in Fourier Domain\n\n 3.1 Forward Transformation into Fourier Domain\n\n w₂ → w₃\n \n 3.2 Diffuse by \"low-pass filtering\" (convolution\n is multiplication in the Fourier Domain)\n\n w₄ = exp(− k² ν Δt) w₃\n \n 3.3 Compute the (pseudo-) pressure in the Fourier Domain\n by evaluating the divergence in the Fourier Domain\n\n q = w₄ ⋅ k / ||k||₂\n \n 3.4 Correct the velocities such that they are incompressible\n\n w₅ = w₄ − q k / ||k||₂\n \n 3.5 Inverse Transformation back into spatial domain\n\n w₆ ← w₅\n\n4. Repeat\n\nk = [ kₓ, k_y ] are the spatial frequencies (= wavenumbers)\n\nThe Fourier Transformation implicitly prescribes the periodic\nBoundary Conditions\n\n------\n\nChanges with respect to the original video (https://youtu.be/F7rWoxeGrko)\n\n1. Use dark theme, set to equal aspect ratio and increase plot window size\n\n2. Change to periodic clamping which respects the periodic boundary conditions,\n then also increase the number of time steps.\n\n\"\"\"\n\nusing FFTW\nusing Plots # Requires ColorSchemes.jl\nusing ProgressMeter\nusing Interpolations\nusing LinearAlgebra\n\nN_POINTS = 250\nKINEMATIC_VISCOSITY = 0.0001\nTIME_STEP_LENGTH = 0.01\nN_TIME_STEPS = 300\n\nfunction backtrace!(\n backtraced_positions,\n original_positions,\n direction,\n)\n # Euler Step backwards in time and periodically clamp into [0.0, 1.0]\n backtraced_positions[:] = mod1.(\n original_positions - TIME_STEP_LENGTH * direction,\n 1.0,\n )\nend\n\nfunction interpolate_positions!(\n field_interpolated,\n field,\n interval_x,\n interval_y,\n query_points_x,\n query_points_y,\n)\n interpolator = LinearInterpolation(\n (interval_x, interval_y),\n field,\n )\n field_interpolated[:] = interpolator.(query_points_x, query_points_y)\nend\n\nfunction main()\n element_length = 1.0 / (N_POINTS - 1)\n x_interval = 0.0:element_length:1.0\n y_interval = 0.0:element_length:1.0\n\n # Similar to meshgrid in NumPy\n coordinates_x = [x for x in x_interval, y in y_interval]\n coordinates_y = [y for x in x_interval, y in y_interval]\n\n wavenumbers_1d = fftfreq(N_POINTS) .* N_POINTS\n\n wavenumbers_x = [k_x for k_x in wavenumbers_1d, k_y in wavenumbers_1d]\n wavenumbers_y = [k_y for k_x in wavenumbers_1d, k_y in wavenumbers_1d]\n wavenumbers_norm = [norm([k_x, k_y]) for k_x in wavenumbers_1d, k_y in wavenumbers_1d]\n\n decay = exp.(- TIME_STEP_LENGTH .* KINEMATIC_VISCOSITY .* wavenumbers_norm.^2)\n\n wavenumbers_norm[iszero.(wavenumbers_norm)] .= 1.0\n normalized_wavenumbers_x = wavenumbers_x ./ wavenumbers_norm\n normalized_wavenumbers_y = wavenumbers_y ./ wavenumbers_norm\n\n # Define the forces\n force_x = 100.0 .* (\n exp.( - 1.0 / (2 * 0.005) * ((coordinates_x .- 0.2).^2 + (coordinates_y .- 0.45).^2))\n -\n exp.( - 1.0 / (2 * 0.005) * ((coordinates_x .- 0.8).^2 + (coordinates_y .- 0.55).^2))\n )\n\n # Preallocate all arrays\n backtraced_coordinates_x = zero(coordinates_x)\n backtraced_coordinates_y = zero(coordinates_y)\n\n velocity_x = zero(coordinates_x)\n velocity_y = zero(coordinates_y)\n\n velocity_x_prev = zero(velocity_x)\n velocity_y_prev = zero(velocity_y)\n\n velocity_x_fft = zero(velocity_x)\n velocity_y_fft = zero(velocity_y)\n pressure_fft = zero(coordinates_x)\n\n # Use a dark theme for plotting\n theme(:dark)\n\n @showprogress \"Timestepping ...\" for iter in 1:N_TIME_STEPS\n\n # (1) Apply the forces\n time_current = (iter - 1) * TIME_STEP_LENGTH\n pre_factor = max(1 - time_current, 0.0)\n velocity_x_prev += TIME_STEP_LENGTH * pre_factor * force_x\n\n # (2) Self-Advection by backtracing and interpolation\n backtrace!(backtraced_coordinates_x, coordinates_x, velocity_x_prev)\n backtrace!(backtraced_coordinates_y, coordinates_y, velocity_y_prev)\n interpolate_positions!(\n velocity_x,\n velocity_x_prev,\n x_interval,\n y_interval,\n backtraced_coordinates_x,\n backtraced_coordinates_y,\n )\n interpolate_positions!(\n velocity_y,\n velocity_y_prev,\n x_interval,\n y_interval,\n backtraced_coordinates_x,\n backtraced_coordinates_y,\n )\n\n # (3.1) Transform into Fourier Domain\n velocity_x_fft = fft(velocity_x)\n velocity_y_fft = fft(velocity_y)\n\n # (3.2) Diffuse by low-pass filtering\n velocity_x_fft .*= decay\n velocity_y_fft .*= decay\n\n # (3.3) Compute Pseudo-Pressure by Divergence in Fourier Domain\n pressure_fft = (\n velocity_x_fft .* normalized_wavenumbers_x\n +\n velocity_y_fft .* normalized_wavenumbers_y\n )\n\n # (3.4) Project the velocities to be incompressible\n velocity_x_fft -= pressure_fft .* normalized_wavenumbers_x\n velocity_y_fft -= pressure_fft .* normalized_wavenumbers_y\n\n # (3.5) Transform back into spatial domain\n velocity_x = real(ifft(velocity_x_fft))\n velocity_y = real(ifft(velocity_y_fft))\n\n # Advance in time\n velocity_x_prev = velocity_x\n velocity_y_prev = velocity_y\n\n # Visualize\n d_u__d_y = diff(velocity_x, dims=2)[2:end, :]\n d_v__d_x = diff(velocity_y, dims=1)[:, 2:end]\n curl = d_u__d_y - d_v__d_x\n display(heatmap(x_interval, y_interval, curl', c=:diverging_bkr_55_10_c35_n256, aspect_ratio=:equal, size=(680, 650)))\n end\nend\n\nmain()\n", "meta": {"hexsha": "aefffdc5a6b152e7812ebfe4a074f92714629bd2", "size": 7981, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "english/simulation_scripts/stable_fluids_fft.jl", "max_stars_repo_name": "bartdavids/machine-learning-and-simulation", "max_stars_repo_head_hexsha": "4a4ca74e2252fa8311112e38b46ed46da3c105e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "english/simulation_scripts/stable_fluids_fft.jl", "max_issues_repo_name": "bartdavids/machine-learning-and-simulation", "max_issues_repo_head_hexsha": "4a4ca74e2252fa8311112e38b46ed46da3c105e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "english/simulation_scripts/stable_fluids_fft.jl", "max_forks_repo_name": "bartdavids/machine-learning-and-simulation", "max_forks_repo_head_hexsha": "4a4ca74e2252fa8311112e38b46ed46da3c105e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0544747082, "max_line_length": 126, "alphanum_fraction": 0.5467986468, "num_tokens": 2040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768525822309, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.8025231148003584}} {"text": "############## EXAMPLE-0 ##############\n# No errors in X nor in Y\n\nusing LinearFitXYerrors\nusing Plots; gr()\n\n# Example-0a\n# INPUT DATA:\n# http://pba.ucdavis.edu/files/45007.pdf\n\nX = [16.4, 17.2, 17.6, 18.0, 18.2, 18.5]\nY = [2.67, 2.75, 2.99, 3.14, 3.88, 4.23]\n\n# COMPUTE and PLOT:\nstxy = linearfitxy(X,Y, isplot=true);\n\n\n\n# Example-0b\n# INPUT DATA:\n# Altman, D. and Gardner, M. [1988] Statistics in Medicine: Calculating confidence intervals for regression and correlation. British Medical Journal, 296(6631), pp.1238–1242.\n\n# Table I\nX = [91., 104, 107, 107, 106, 100, 92, 92, 105, 108]\nY = [9.8, 7.4, 7.9, 8.3, 8.3, 9.0, 9.7, 8.8, 7.6, 6.9]\n\n\n# COMPUTE and PLOT:\nstxy = linearfitxy(X,Y, isplot=true); # σX = σY = r = 0\n\n\nsavefig(\"Example0b_LinearFitXYerrors.png\")\n########################################\n", "meta": {"hexsha": "06af56661ada9e5a177f4e889bdee14c412fe676", "size": 817, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/example0.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/example0.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/example0.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": 24.0294117647, "max_line_length": 174, "alphanum_fraction": 0.5875152999, "num_tokens": 332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176860436174, "lm_q2_score": 0.8499711718571774, "lm_q1q2_score": 0.8025231125053655}} {"text": "\"\"\" \n--- \nApply Chebyshev polynom of order L to input x\n# --- Syntax \n\ty = cheb(L,x)\n# --- Input parameters \n- L\t : Chebyshev order [Int] \n- x\t : Input [Any]\n# --- Output parameters \n- y\t : Output \n# --- \n# v 1.0 - Robin Gerzaguet.\n\"\"\"\nfunction cheb(L,x)\n\t## Apply Chebyshev polynom of order m to input x\n\t x[abs.(x).<=1] = cos.(L .* acos.(x[abs.(x).<=1]));\n\t x[abs.(x).>1] = cosh.(L .* acosh.(abs.(x[abs.(x).>1])));\n\t return x;\nend\n\n\"\"\" \n--- \nReturns the Dolp Chebyshev filter of order L with desired attenation att\n\nSee Peter Lynch, \"The Dolph-Chebyshev Window: A Simple Optimal Filter\", Monthly Weather Review, Vol. 125, pp. 655-660, April 1997. (http://www.maths.tcd.ie/~plynch/Publications/Dolph.pdf)\nDolph, \"A current distribution for broadside arrays which optimizes the relationship between beam width and side-lobe level\", Proc. IEEE, 34, pp. 335-348.\n\t\tcheb(m-1, beta * cos(pi * k/m))\nW(k) =\t-------------------------------\n\t\t\t cheb(m-1, beta)\n# --- Syntax \n filterDC = dolphChebyshev(n,at)\n# --- Input parameters \n- n\t\t : Size of desired filter \n- at\t : Attenation in dBB \n# --- Output parameters \n- filterDC : Filter impulse response [Array{Float64}] \n# --- \n# v 1.0 - Robin Gerzaguet.\n\"\"\"\nfunction dolphChebyshev(n,at);\n\t# --- Filter in frequency domain\n\t# --- DC constant\n gamma = 10^(-at/20);\n beta = cosh(1/(n-1) * acosh(1/gamma));\n\tk = collect(0:n-1);\n x = beta*cos.(pi*k/n);\n\tp\t = cheb(n-1, x);\n\tif mod(n,2) == 1\n\t\tw = real(fft(p));\n\t\tM = Int((n+1)/2);\n\t\tw = w[1:M]/w[1];\n\t\tw = [w[M:-1:2];w];\n\telse\n\t\toff = exp.(1im*pi/n.*collect(0:n-1));\n\t\t# half-sample delay (even order)\n\t\tp .= p * transpose(off);\n\t\tw = real(fft(p));\n\t\tM = Int(n/2+1);\n\t\tw = w./w[2];\n\t\tw .= [w[M:-1:2];w[2:M]];\n\tend\n\treturn w\nend\n", "meta": {"hexsha": "666b8b4bcfc191d999dcf1a15a41f387cdf52bed", "size": 1746, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Waveforms/UFOFDM/filterUFOFDM.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/Waveforms/UFOFDM/filterUFOFDM.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/Waveforms/UFOFDM/filterUFOFDM.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": 27.28125, "max_line_length": 187, "alphanum_fraction": 0.5796105384, "num_tokens": 630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.953275045356249, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.8024913877401645}} {"text": "using Statistics,QuadGK,FFTW\r\n\r\nusing Optim,Roots\r\n\r\n\r\nmutable struct EuropeanOption_crr\r\n St::Float64 #current assset price 当期价格\r\n K::Float64 #strike price 行权价\r\n T::Float64 #maturity time 到期时间\r\n t::Float64 #valuation date 有效日期\r\n r::Float64 #risk_less rate 无风险收益率\r\n σ::Float64 #volatility 波动率\r\n type::String #option type(call,put) 看涨、看跌\r\n # EuropeanOtion(St,K,T,t,r,σ,type)=new(St,K,T,t,r,σ,type)\r\nend\r\n\r\n\r\n\r\nfunction get_basic_parameters(o::EuropeanOption_crr,N::Int64)\r\n dt=o.T/N\r\n df=exp(-o.r*dt)\r\n u=exp(o.σ*√dt)\r\n d=1/u\r\n\r\n q=(exp(o.r*dt)-d)/(u-d)\r\n\r\n #初始化指数生成矩阵,即以u,d的概率生成二叉树网络,\r\n mu0=repeat(Vector(0:N),N+1)\r\n mu1=reshape(mu0,(N+1,N+1))\r\n md0=copy(mu1')\r\n mu2=mu1-md0\r\n mu=map(x->u^x,mu2)\r\n md=map(x->d^x,md0)\r\n S=o.St*(mu.*md)\r\n\r\n return dt,df,u,d,q,S\r\n\r\nend\r\n\r\n#CRR定价方法\r\nfunction CRR_value(o::EuropeanOption_crr,N::Int64)\r\n\r\n dt,df,u,d,q,S=get_basic_parameters(o,N)\r\n\r\n if o.type==\"call\"\r\n V=map(x->max(x-o.K,0),S)\r\n else\r\n V=map(x->max(o.K-x,0),S)\r\n end\r\n\r\n VV=copy(V')\r\n z=0\r\n @simd for t= N:-1:1\r\n VV[1:N-z,t]=(q*VV[1:N-z,t+1]+(1-q)*VV[2:N-z+1,t+1])*df\r\n z+=1\r\n end\r\n return VV[1,1]\r\nend\r\n\r\n\r\nfunction CRR_call_value_FFT(o::EuropeanOption_crr,N::Int64)\r\n\r\n dt,df,u,d,q,S=get_basic_parameters(o,N)\r\n S0=copy(S')\r\n\r\n CT=map(x->max(x-o.K,0),S0[:,end])\r\n qv=zeros(N+1)\r\n qv[1]=q\r\n qv[2]=1-q\r\n\r\n C0_b=fft(exp(-o.r*o.T)*(ifft(CT).*fft(qv).^N))\r\n\r\n return real(C0_b[1])\r\nend\r\n\r\n#快速算法,如果不用struct,直接参数化输入,可大幅提升计算速度,6-7倍\r\nfunction crr_value_fast(o::EuropeanOption_crr,N::Int64)\r\n Δt = o.T / N\r\n U = exp(o.σ * √Δt)\r\n D = 1 / U\r\n R = exp(o.r * Δt)\r\n p = (R - D) / (U - D)\r\n q = (U - R) / (U - D)\r\n\r\n if o.type == \"put\"\r\n Z = [max(0, o.K - o.St * exp((2 * i - N) *o.σ * √Δt)) for i = 0:N]\r\n else\r\n Z = [max(0, o.St * exp((2 * i - N) * σ * √Δt) - o.K) for i = 0:N]\r\n end\r\n\r\n @simd for n = N-1:-1:0\r\n for i = 0:n\r\n if o.type == \"put\"\r\n x = o.K - o.St * exp((2 * i - n) * o.σ * √Δt)\r\n else\r\n x = o.St * exp((2 * i - n) * o.σ * √Δt) - o.K\r\n end\r\n y = (q * Z[i+1] + p * Z[i+2]) / R\r\n Z[i+1] = max(x, y)\r\n end\r\n end\r\n\r\n return Z[1]\r\nend\r\n\r\n\r\n\r\n\r\n# @time t=crr(100,90,0.05,0.3,180/365,1000,\"put\")\r\no=EuropeanOption_crr(36.0,40.0,1.0,0,0.06,0.2,\"put\")\r\nN=1000\r\n#\r\n# @time dt,df,u,d,q,S=get_basic_parameters(o,N)\r\n# @time value=CRR_value(o,N)\r\n\r\n# @time fft_value=CRR_value_FFT(o,N)\r\n\r\n@time tg=crr_value_fast(o,N)\r\n", "meta": {"hexsha": "1d33a4f5d2c9c893b1980036336e3c78eca3891e", "size": 2601, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "CRR_OPTION.jl", "max_stars_repo_name": "Alchemist-yao/Julia4Derivatives", "max_stars_repo_head_hexsha": "c42a46583a354f326a4f1527fc1c05606170ea4c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-10-09T02:51:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-09T02:51:59.000Z", "max_issues_repo_path": "CRR_OPTION.jl", "max_issues_repo_name": "Alchemist-yao/Julia4Derivatives", "max_issues_repo_head_hexsha": "c42a46583a354f326a4f1527fc1c05606170ea4c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CRR_OPTION.jl", "max_forks_repo_name": "Alchemist-yao/Julia4Derivatives", "max_forks_repo_head_hexsha": "c42a46583a354f326a4f1527fc1c05606170ea4c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8571428571, "max_line_length": 75, "alphanum_fraction": 0.5082660515, "num_tokens": 1088, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750400464605, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.8024913719215041}} {"text": "# ------------------------------------------------------------------------------------------\n# # Quantifying Chaos for a Dynamical System\n#\n# Topics:\n# * Introduction to Lyapunov exponents\n# * Maximum Lyapunov Exponent\n# * Lyapunov Spectrum\n#\n# **WARNING** - Compilation of functions in this tutorial takes *a lot of time*.\n#\n# ---\n#\n# In the previous tutorial we saw that for example the Shinriki oscillator showed something\n# that \"could be chaotic behavior\" for a specific parameter value. How can we quantify that?\n#\n# # Lyapunov exponents\n# * Lyapunov exponents measure the exponential separation rate of trajectories that are\n# (initially) close.\n# * Consider the following picture, where two nearby trajectories are evolved in time:\n#\n#\n#\n# \"Sketch\n#\n#\n# * $\\lambda$ denotes the \"maximum Lyapunov exponent\".\n# * A $D$-dimensional system has $D$ exponents.\n# * In general, a trajectory is called \"chaotic\" if\n# 1. it follows nonlinear dynamics\n# 2. it is *bounded* (does not escape to infinity)\n# 2. it has a positive Lyapunov exponent\n#\n# *(please be aware that the above is an over-simplification! See the textbooks cited in our\n# documentation for more)*\n#\n# ---\n# ------------------------------------------------------------------------------------------\n\nusing DynamicalSystems, BenchmarkTools, PyPlot\n\n# ------------------------------------------------------------------------------------------\n# Before computing Lyapunov exponents, we'll demonstrate the concept of exponential\n# separation using a simple map: the *towel map*\n#\n# $$\n# \\begin{aligned}\n# x_{n+1} &= a x_n (1-x_n) -0.05 (y_n +0.35) (1-2z_n) \\\\\n# y_{n+1} &= 0.1 \\left( \\left( y_n +0.35 \\right)\\left( 1+2z_n\\right) -1 \\right)\n# \\left( 1 -1.9 x_n \\right) \\\\\n# z_{n+1} &= 3.78 z_n (1-z_n) + b y_n\n# \\end{aligned}\n# $$\n# ------------------------------------------------------------------------------------------\n\ntowel = Systems.towel()\n\n# ------------------------------------------------------------------------------------------\n# First we'll generate a trajectory for the towel map, `tr1`, from the default initial\n# condition,\n# ------------------------------------------------------------------------------------------\n\ntr1 = trajectory(towel, 100)\nsummary(tr1)\n\n# ------------------------------------------------------------------------------------------\n# and then we will generate a second trajectory, `tr2`, with a starting point slightly\n# shifted from the initial condition of `tr1`.\n# ------------------------------------------------------------------------------------------\n\nu2 = get_state(towel) + (1e-9 * rand(3))\ntr2 = trajectory(towel, 100, u2)\nsummary(tr2)\n\nfigure(figsize=(8,5))\n\n# Plot the x-coordinate of the two trajectories:\nax1 = subplot(2,1,1)\nplot(tr1[:, 1], alpha = 0.5)\nplot(tr2[:, 1], alpha = 0.5)\nylabel(\"x\")\n\n# Plot their distance in a semilog plot:\nax2 = subplot(2,1,2, sharex = ax1)\nd = [norm(tr1[i] - tr2[i]) for i in 1:length(tr2)]\nylabel(\"d\")\nxlabel(\"n\")\nsemilogy(d);\n\n# ------------------------------------------------------------------------------------------\n# # Maximum Lyapunov Exponent\n# `lyapunov` is a function that calculates the maximum Lyapunov exponent for a\n# `DynamicalSystem` (for a given starting point).\n#\n# Since `lyapunov` is not a trivial function, it is best to read the documentation string\n# first:\n# ------------------------------------------------------------------------------------------\n\n?lyapunov\n\n# ------------------------------------------------------------------------------------------\n# ---\n#\n# Let's apply this to the example of the previous section, the Shinriki oscillator!\n#\n# *Reminder:* we found something that \"could\" be chaotic behavior for the parameter `R1 =\n# 21.0`\n# \n# ------------------------------------------------------------------------------------------\n\nshi = Systems.shinriki(;R1 = 21.0)\n\nlyapunov(shi, 1000.0, Ttr = 10.0)\n\n# ------------------------------------------------------------------------------------------\n# Positive Lyapunov exponent!?!? That is definitely chaotic behavior, right?\n#\n# *Right?*\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# Let's increase accuracy of computation, as well as the transient time, to see whether an\n# orbit actually enters a limit cycle.\n# ------------------------------------------------------------------------------------------\n\nlyapunov(shi, 2000.0, Ttr = 1000.0)\n\n# ------------------------------------------------------------------------------------------\n# **surprise**\n#\n# Let's find out whats going on!\n#\n# To see why the lyapunov exponent was positive in one case and negative in another, we can\n# produce a more detailed orbit diagram, around the \"critical\" value of `R = 21.0`.\n# ------------------------------------------------------------------------------------------\n\npvalues = linspace(20.9,21.1,101)\ni = 1\nplane = (2, 0.0)\ntf = 1000.0\np_index = 1\n\n# use extremely long transient time:\noutput = produce_orbitdiagram(shi, plane, i, p_index, pvalues; tfinal = tf,\n Ttr = 2000.0, direction = -1, printparams = false);\nlength(output)\n\nusing PyPlot\nfigure(figsize=(6,4))\nfor (j, p) in enumerate(pvalues)\n plot(p .* ones(output[j]), output[j], lw = 0,\n marker = \"o\", ms = 0.2, color = \"black\")\nend\nplot([21, 21], [-2.1, 0.1], color = \"red\", alpha = 0.55)\nxlabel(\"\\$R_1\\$\"); ylabel(\"\\$V_1\\$\");\n\n# result of orbit diagram at R1 = 21.0\nvalues = output[51] \n\n# Amount of unique points\nun = unique(round.(output[51], 8))\nprintln(\"Total: $(length(output[51])), unique: $(length(un))\")\n\n# ------------------------------------------------------------------------------------------\n# ## `lyapunov` for discrete system\n#\n# * All functions that accept a `DynamicalSystem` work with *any* instance of\n# `DynamicalSystem`, regardless of whether it is continuous, discrete, in-place, out-of-\n# place or whatever.\n# \n# ------------------------------------------------------------------------------------------\n\n# Get the Henon map from the library of pre-defined systems:\nhen = Systems.henon()\nλ = lyapunov(hen, 10000)\n\n# ------------------------------------------------------------------------------------------\n# ---\n#\n# # Lyapunov Spectrum\n#\n# Besides the maximum Laypunov exponent, the function `lyapunovs` (with `s` at the end)\n# returns the entire Lyapunov spectrum (or as many exponents the user wants).\n#\n#\n#\n# Once again, because the function `lyapunovs` is not trivial, we will view the\n# documentation string first:\n# ------------------------------------------------------------------------------------------\n\n?lyapunovs\n\n# ------------------------------------------------------------------------------------------\n# ### Lyapunovs for discrete systems\n#\n# In our first example of calling `lyapunovs`, let's pass a discrete system.\n# ------------------------------------------------------------------------------------------\n\ntowel = Systems.towel()\nlyapunovs(towel, 2000; Ttr = 200)\n\n# ------------------------------------------------------------------------------------------\n# Here we're choosing to compute only the first two exponents.\n# ------------------------------------------------------------------------------------------\n\nlyapunovs(towel, 2000, 2; Ttr = 200)\n\n# ------------------------------------------------------------------------------------------\n# If you only want the first exponent (maximum), use the `lyapunov` function instead\n# ------------------------------------------------------------------------------------------\n\nlyapunov(towel, 2000; Ttr = 200)\n\n# ------------------------------------------------------------------------------------------\n# How much time does this take?\n# ------------------------------------------------------------------------------------------\n\nusing BenchmarkTools\n@btime lyapunovs($towel, 2000; Ttr = 200);\n\n@btime lyapunov($towel, 2000; Ttr = 200);\n\n# ------------------------------------------------------------------------------------------\n# ### Lyapunov exponents for continuous systems\n#\n# Next, let's initialize the Lorenz system with random initial condition\n# ------------------------------------------------------------------------------------------\n\nlor = Systems.lorenz()\n\n# ------------------------------------------------------------------------------------------\n# We'll compute the Lyapunov spectrum with specified initial parallepiped matrix `Q0`:\n# ------------------------------------------------------------------------------------------\n\nQ0 = eye(3)\nlyapunovs(lor, 2000, Q0; Ttr = 10.0)\n\n# ------------------------------------------------------------------------------------------\n# And we find that results \"converge\" already with 2000 iterations:\n# ------------------------------------------------------------------------------------------\n\nlyapunovs(lor, 3000, Q0; Ttr = 10.0)\n\n# ------------------------------------------------------------------------------------------\n# * Even the continuous systems are quite performant (note that compilation takes a **lot**\n# of time):\n# ------------------------------------------------------------------------------------------\n\n@btime lyapunovs($lor, 2000, $Q0; Ttr = 10.0);\n\n# ------------------------------------------------------------------------------------------\n# * The above integration is done with a 9th order solver and tolerances of `1e-9`. But you\n# can get away with lower tolerances.\n#\n# Let's load in `OrdinaryDiffEq` and specify keyword arguments for the integrators of\n# DifferentialEquations.jl.\n# ------------------------------------------------------------------------------------------\n\nusing OrdinaryDiffEq\n \ndek = Dict(:solver => Tsit5(), :abstol => 1e-6, :reltol => 1e-6)\n\n# ------------------------------------------------------------------------------------------\n# And now we can call `lyapunovs` with the keyword `diff_eq_kwargs`\n# ------------------------------------------------------------------------------------------\n\nlyapunovs(lor, 2000, Q0; Ttr = 10.0, diff_eq_kwargs = dek)\n\n@btime lyapunovs($lor, 2000.0, $Q0; Ttr = 10.0, diff_eq_kwargs = $dek);\n", "meta": {"hexsha": "aa0865e55edabc9ed6a222d9e79efb7ec5287c79", "size": 10292, "ext": "jl", "lang": "Julia", "max_stars_repo_path": ".nbexports/introductory-tutorials/broader-topics-and-ecosystem/introduction-to-dynamicalsystems.jl/3. Quantifying Chaos (Lyapunov Exponents).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/3. Quantifying Chaos (Lyapunov Exponents).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/3. Quantifying Chaos (Lyapunov Exponents).jl", "max_forks_repo_name": "grenkoca/JuliaTutorials", "max_forks_repo_head_hexsha": "3968e0430db77856112521522e10f7da0d7610a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 394, "max_forks_repo_forks_event_min_datetime": "2020-07-14T23:22:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T20:12:57.000Z", "avg_line_length": 38.2602230483, "max_line_length": 92, "alphanum_fraction": 0.4318888457, "num_tokens": 2162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680097, "lm_q2_score": 0.8615382129861583, "lm_q1q2_score": 0.802490543716826}} {"text": "# This file is part of the IntervalArithmetic.jl package; MIT licensed\n\n\n\"\"\"\n in(x, a)\n ∈(x, a)\n\nChecks if the number `x` is a member of the interval `a`, treated as a set.\nCorresponds to `isMember` in the ITF-1788 Standard.\n\"\"\"\nfunction in(x::T, a::Interval) where T<:Real\n isinf(x) && return false\n a.lo <= x <= a.hi\nend\n\n\n\n\"\"\"\n issubset(a,b)\n ⊆(a,b)\n\nChecks if all the points of the interval `a` are within the interval `b`.\n\"\"\"\nfunction ⊆(a::Interval, b::Interval)\n isempty(a) && return true\n b.lo ≤ a.lo && a.hi ≤ b.hi\nend\n\nfunction ⊂(a::Interval, b::Interval)\n a == b && return false\n a ⊆ b\nend\n\nfunction ⊇(a::Interval, b::Interval)\n b ⊆ a\nend\n\nfunction ⊃(a::Interval, b::Interval)\n b ⊂ a\nend\n\n# isinterior\nfunction isinterior(a::Interval, b::Interval)\n isempty(a) && return true\n islessprime(b.lo, a.lo) && islessprime(a.hi, b.hi)\nend\nconst ⪽ = isinterior # \\subsetdot\n\n# Disjoint:\nfunction isdisjoint(a::Interval, b::Interval)\n (isempty(a) || isempty(b)) && return true\n islessprime(b.hi, a.lo) || islessprime(a.hi, b.lo)\nend\n\n\n# Intersection\n\"\"\"\n intersect(a, b)\n ∩(a,b)\n\nReturns the intersection of the intervals `a` and `b`, considered as\n(extended) sets of real numbers. That is, the set that contains\nthe points common in `a` and `b`.\n\"\"\"\nfunction intersect(a::Interval{T}, b::Interval{T}) where T\n isdisjoint(a,b) && return emptyinterval(T)\n\n Interval(max(a.lo, b.lo), min(a.hi, b.hi))\nend\n# Specific promotion rule for intersect:\nintersect(a::Interval{T}, b::Interval{S}) where {T,S} =\n intersect(promote(a, b)...)\n\n\n## Hull\n\"\"\"\n hull(a, b)\n\nReturns the \"interval hull\" of the intervals `a` and `b`, considered as\n(extended) sets of real numbers, i.e. the smallest interval that contains\nall of `a` and `b`.\n\"\"\"\nhull(a::Interval, b::Interval) = Interval(min(a.lo, b.lo), max(a.hi, b.hi))\n#\n# hull{T,S}(a::Interval{T}, b::Interval{S}) = hull(promote(a, b)...)\n\n\"\"\"\n union(a, b)\n ∪(a,b)\n\nReturns the union (convex hull) of the intervals `a` and `b`; it is equivalent\nto `hull(a,b)`.\n\"\"\"\nunion(a::Interval, b::Interval) = hull(a, b)\n#\n# union(a::Interval, b::Interval) = union(promote(a, b)...)\n\n\n\"\"\"\n setdiff(x::Interval, y::Interval)\n\nCalculate the set difference `x ∖ y`, i.e. the set of values\nthat are inside the interval `x` but not inside `y`.\n\nReturns an array of intervals.\nThe array may:\n\n- be empty if `x ⊆ y`;\n- contain a single interval, if `y` overlaps `x`\n- contain two intervals, if `y` is strictly contained within `x`.\n\"\"\"\nfunction setdiff(x::Interval, y::Interval)\n intersection = x ∩ y\n\n isempty(intersection) && return [x]\n intersection == x && return typeof(x)[] # x is subset of y; setdiff is empty\n\n x.lo == intersection.lo && return [Interval(intersection.hi, x.hi)]\n x.hi == intersection.hi && return [Interval(x.lo, intersection.lo)]\n\n return [Interval(x.lo, y.lo),\n Interval(y.hi, x.hi)]\n\nend\n", "meta": {"hexsha": "11749217efda2447fa0a3a39aeb9c6890d829a33", "size": 2939, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/intervals/set_operations.jl", "max_stars_repo_name": "mewilhel/IntervalArithmetic.jl", "max_stars_repo_head_hexsha": "38a011b4f87eaa37bce97c0f2c38a526eb1e0841", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/intervals/set_operations.jl", "max_issues_repo_name": "mewilhel/IntervalArithmetic.jl", "max_issues_repo_head_hexsha": "38a011b4f87eaa37bce97c0f2c38a526eb1e0841", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/intervals/set_operations.jl", "max_forks_repo_name": "mewilhel/IntervalArithmetic.jl", "max_forks_repo_head_hexsha": "38a011b4f87eaa37bce97c0f2c38a526eb1e0841", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-06T06:15:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-06T06:15:24.000Z", "avg_line_length": 23.512, "max_line_length": 81, "alphanum_fraction": 0.636951344, "num_tokens": 900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680098, "lm_q2_score": 0.8615382094310357, "lm_q1q2_score": 0.8024905404053627}} {"text": "# This file is a part of AstroLib.jl. License is MIT \"Expat\".\n# Copyright (C) 2016 Mosè Giordano.\n\nfunction mphase(jd::AbstractFloat)\n ram, decm, dism = moonpos(jd, radians=true)\n ras, decs = sunpos(jd, radians=true)\n # phi: geocentric elongation of the Moon from the Sun\n # inc: selenocentric (Moon centered) elongation of the Earth from the Sun\n sin_decs, cos_decs = sincos(decs)\n sin_decm, cos_decm = sincos(decm)\n phi = acos(sin_decs * sin_decm + cos_decs * cos_decm * cos(ras - ram))\n # \"dism\" is in kilometers, AU in meters\n sin_phi, cos_phi = sincos(phi)\n inc = atan(AU * sin_phi, dism * 1000 - AU * cos_phi)\n return (1 + cos(inc))/2\nend\n\n\"\"\"\n mphase(jd) -> k\n\n### Purpose ###\n\nReturn the illuminated fraction of the Moon at given Julian date(s).\n\n### Arguments ###\n\n* `jd`: the Julian ephemeris date.\n\n### Output ###\n\nThe illuminated fraction \\$k\\$ of Moon's disk, with \\$0 \\\\leq k \\\\leq 1\\$. \\$k\n= 0\\$ indicates a new moon, while \\$k = 1\\$ stands for a full moon.\n\n### Method ###\n\nAlgorithm from Chapter 46 of \"Astronomical Algorithms\" by Jean Meeus\n(Willmann-Bell, Richmond) 1991. `sunpos` and `moonpos` are used to get\npositions of the Sun and the Moon, and the Moon distance. The selenocentric\nelongation of the Earth from the Sun (phase angle) is then computed, and used to\ndetermine the illuminated fraction.\n\n### Example ###\n\nPlot the illuminated fraction of the Moon for every day in January 2018 with a\nhourly sampling. Use [PyPlot.jl](https://github.com/JuliaPlots/Plots.jl/) for\nplotting\n\n```julia\nusing PyPlot\npoints = DateTime(2018,01,01):Dates.Hour(1):DateTime(2018,01,31,23,59,59);\nplot(points, mphase.(jdcnv.(points)))\n```\n\nNote that in this calendar month there are two full moons, this event is called\n[blue moon](https://en.wikipedia.org/wiki/Blue_moon).\n\n### Notes ###\n\nCode of this function is based on IDL Astronomy User's Library.\n\"\"\"\nmphase(jd::Real) = mphase(float(jd))\n", "meta": {"hexsha": "93ed59af60dc0d1cfe3283d925dda779fbf4fac8", "size": 1942, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mphase.jl", "max_stars_repo_name": "UnofficialJuliaMirror/AstroLib.jl-c7932e45-9af1-51e7-9da9-f004cd3a462b", "max_stars_repo_head_hexsha": "fb2ef587a2ac68a1c864bf251e8d9c3601ec4719", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 62, "max_stars_repo_stars_event_min_datetime": "2016-09-11T14:59:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T20:45:36.000Z", "max_issues_repo_path": "src/mphase.jl", "max_issues_repo_name": "UnofficialJuliaMirror/AstroLib.jl-c7932e45-9af1-51e7-9da9-f004cd3a462b", "max_issues_repo_head_hexsha": "fb2ef587a2ac68a1c864bf251e8d9c3601ec4719", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 64, "max_issues_repo_issues_event_min_datetime": "2017-01-19T21:03:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T12:27:46.000Z", "max_forks_repo_path": "src/mphase.jl", "max_forks_repo_name": "UnofficialJuliaMirror/AstroLib.jl-c7932e45-9af1-51e7-9da9-f004cd3a462b", "max_forks_repo_head_hexsha": "fb2ef587a2ac68a1c864bf251e8d9c3601ec4719", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2016-07-12T02:11:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T11:55:21.000Z", "avg_line_length": 31.3225806452, "max_line_length": 80, "alphanum_fraction": 0.6941297631, "num_tokens": 589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680097, "lm_q2_score": 0.8615382076534742, "lm_q1q2_score": 0.8024905387496308}} {"text": "\n## coordinate.jl\n## Functions for coordinate transformation\n\n\n\"\"\"\n eq2ec(α, δ) -> λ, β\n\nCoordinate transform from the equatorial to ecliptic coordinate systems\n\n# Arguments\n- `α`: right ascension (RA)\n- `δ`: declination (Dec)\n# Returns\n- `λ`: ecliptic longitude\n- `β`: ecliptic latitude\n\"\"\"\nfunction eq2ec(α, δ)\n\n ε = deg2rad(23.439279444444445) # obliquity of the Earth's axis\n\n sin_ε = sin(ε)\n cos_ε = cos(ε)\n \n sin_α = sin(α)\n cos_α = cos(α)\n \n sin_δ = sin(δ)\n cos_δ = cos(δ)\n \n λ = atan(cos_ε*cos_δ*sin_α + sin_ε*sin_δ, cos_δ*cos_α)\n λ < 0 && (λ += 2π)\n\n β = asin(-sin_ε*cos_δ*sin_α + cos_ε*sin_δ)\n\n return λ, β\nend\n\n\nfunction ec2eq(λ, β)\n\n ε = deg2rad(23.439279444444445) # obliquity of the Earth's axis\n\n sin_ε = sin(ε)\n cos_ε = cos(ε)\n\n sin_λ = sin(λ)\n cos_λ = cos(λ)\n \n sin_β = sin(β)\n cos_β = cos(β)\n \n α = atan(cos_ε*cos_β*sin_λ - sin_ε*sin_β, cos_β*cos_λ)\n α < 0 && (α += 2π)\n\n δ = asin(sin_ε*cos_β*sin_λ + cos_ε*sin_β)\n\n return α, δ\nend\n\n\n# cpdef inline tuple eq2hz(double RA, double Dec, double obslon, double obslat):\n# \"\"\"\n# Coordinate transform from equatorial to horizontal coordinate system\n# for an observer in (obslon, obslat)\n# \"\"\"\n# cdef:\n# double hour_angle = obslon - RA # hour angle = GST + longitude - RA\n# double azimuth, elevation\n\n# azimuth = atan2(-cos(Dec)*sin(hour_angle), sin(Dec)*cos(obslat) - cos(Dec)*sin(obslat)*cos(hour_angle))\n\n# if azimuth < 0:\n# azimuth += 2*pi\n\n# elevation = asin(sin(Dec)*sin(obslat) + cos(Dec)*cos(obslat)*cos(hour_angle))\n\n# return azimuth, elevation\n\n\n################################################################\n# Rotation transformation (inpace)\n################################################################\n\n\"\"\"\nRotation transformation around X-axis\nParameters:\n v : vector to be transformed\n θ : rotation angle\n\"\"\"\nfunction rotateX!(v, θ)\n sinθ = sin(θ)\n cosθ = cos(θ)\n \n v[1], v[2], v[3] = v[1], v[2]*cosθ + v[3]*sinθ, - v[2]*sinθ + v[3]*cosθ\nend\n\n\n\"\"\"\nRotation transformation around Y-axis\nParameters:\n v : vector to be transformed\n θ : rotation angleon\n\"\"\"\nfunction rotateY!(v, θ)\n sinθ = sin(θ)\n cosθ = cos(θ)\n \n v[1], v[2], v[3] = v[1]*cosθ - v[3]*sinθ, v[2], v[1]*sinθ + v[3]*cosθ\nend\n\n\n\"\"\"\nRotation transformation around Z-axis\nParameters:\n v : vector to be transformed\n θ : rotation angleon\n\"\"\"\nfunction rotateZ!(v, θ)\n sinθ = sin(θ)\n cosθ = cos(θ)\n \n v[1], v[2], v[3] = v[1]*cosθ + v[2]*sinθ, - v[1]*sinθ + v[2]*cosθ, v[3]\nend\n\n\n################################################################\n# Rotation transformation (non-inpalce)\n################################################################\n\n\nrotateX(v, θ) = rotateX!(copy(v), θ)\nrotateY(v, θ) = rotateY!(copy(v), θ)\nrotateZ(v, θ) = rotateZ!(copy(v), θ)\n\n\nfunction rotateX(v::SVector, θ)\n sinθ = sin(θ)\n cosθ = cos(θ)\n \n x = v[1]\n y = v[2]*cosθ + v[3]*sinθ\n z = - v[2]*sinθ + v[3]*cosθ\n\n SA_F64[x, y, z]\nend\n\n\nfunction rotateY(v::SVector, θ)\n sinθ = sin(θ)\n cosθ = cos(θ)\n \n x = v[1]*cosθ - v[3]*sinθ\n y = v[2]\n z = v[1]*sinθ + v[3]*cosθ\n\n SA_F64[x, y, z]\nend\n\n\nfunction rotateZ(v::SVector, θ)\n sinθ = sin(θ)\n cosθ = cos(θ)\n \n x = v[1]*cosθ + v[2]*sinθ\n y = - v[1]*sinθ + v[2]*cosθ\n z = v[3]\n\n SA_F64[x, y, z]\nend\n\n\n################################################################\n# Coordinate transformation\n################################################################\n\n\"\"\"\nTransform the inertial coordinate system to the orbital plane system\n\n# Parameters\n- v : vector to be transformed\n- ω : argument of periapsis\n- I : inclination\n- Ω : longitude of the ascneding node\n\"\"\"\nfunction inertia_to_orbit!(v, ω, I, Ω)\n rotateZ!(v, Ω)\n rotateX!(v, I)\n rotateZ!(v, ω)\nend\n\nfunction inertia_to_orbit(v, ω, I, Ω)\n v = rotateZ(v, Ω)\n v = rotateX(v, I)\n v = rotateZ(v, ω)\nend\n\ninertia_to_orbit!(v, orbit) = inertia_to_orbit!(v, orbit.ω, orbit.I, orbit.Ω)\ninertia_to_orbit(v, orbit) = inertia_to_orbit(v, orbit.ω, orbit.I, orbit.Ω)\n\n\n\"\"\"\nTransform the orbital plane system to the inertial coordinate system\n\n# Parameters\n- v : vector to be transformed\n- ω : argument of periapsis\n- I : inclination\n- Ω : longitude of the ascneding node\n\"\"\"\nfunction orbit_to_inertia!(v, ω, I, Ω)\n rotateZ!(v, -ω)\n rotateX!(v, -I)\n rotateZ!(v, -Ω)\nend\n\nfunction orbit_to_inertia(v, ω, I, Ω)\n v = rotateZ(v, -ω)\n v = rotateX(v, -I)\n v = rotateZ(v, -Ω)\nend\n\norbit_to_inertia!(v, orbit) = orbit_to_inertia!(v, orbit.ω, orbit.I, orbit.Ω)\norbit_to_inertia(v, orbit) = orbit_to_inertia(v, orbit.ω, orbit.I, orbit.Ω)\n\n\n\"\"\"\n orbit_to_body(v::SArray{Tuple{3},Float64,1,3}, γ, ε, ϕ) -> v\n\n# Parameters\n- `v` : vector in the orbital plane frame\n- `γ` : longitude of vernal equinox direction of the body\n- `ε` : obliquity of the spin pole\n- `ϕ` : spin phase of the body\n\n# Return\n- `v` : vector in the body-fixed frame\n\"\"\"\nfunction orbit_to_body(v, γ, ε, ϕ)\n v = rotateZ(v, γ) # body's ecliptic coordinate\n v = rotateX(v, ε) # body's equatorial coordinate\n v = rotateZ(v, ϕ) # body-fixed frame\nend\n\n\nfunction orbit_to_body!(v, γ, ε, ϕ)\n rotateZ!(v, γ) # body's ecliptic coordinate\n rotateX!(v, ε) # body's equatorial coordinate\n rotateZ!(v, ϕ) # body-fixed frame\nend\n\n\n\"\"\"\n body_to_orbit(v::SArray{Tuple{3},Float64,1,3}, γ, ε, ϕ) -> v\n\n# Parameters\n- `v` : vector in the body-fixed frame\n- `γ` : longitude of vernal equinox direction of the body\n- `ε` : obliquity of the spin pole\n- `ϕ` : spin phase of the body\n\n# Return\n- `v` : vector in the orbital plane frame\n\"\"\"\nfunction body_to_orbit(v, γ, ε, ϕ)\n v = rotateZ(v, -ϕ) # body's equatorial coordinate\n v = rotateX(v, -ε) # body's ecliptic coordinate\n v = rotateZ(v, -γ) # orbital plane frame \nend\n\n\nfunction body_to_orbit!(v, γ, ε, ϕ)\n rotateZ!(v, -ϕ) # body's equatorial coordinate\n rotateX!(v, -ε) # body's ecliptic coordinate\n rotateZ!(v, -γ) # orbital plane frame \nend\n\n", "meta": {"hexsha": "5d4fc216dac6e6640d0bc0b41e5690faf76952d5", "size": 6166, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/.ipynb_checkpoints/coordinates-checkpoint.jl", "max_stars_repo_name": "MasanoriKanamaru/Astroshaper", "max_stars_repo_head_hexsha": "0040c4c9260252859d4ce3225b3e8616258d0a36", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2021-05-25T07:22:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T15:42:50.000Z", "max_issues_repo_path": "src/coordinates.jl", "max_issues_repo_name": "MasanoriKanamaru/Astroshaper", "max_issues_repo_head_hexsha": "0040c4c9260252859d4ce3225b3e8616258d0a36", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/coordinates.jl", "max_forks_repo_name": "MasanoriKanamaru/Astroshaper", "max_forks_repo_head_hexsha": "0040c4c9260252859d4ce3225b3e8616258d0a36", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.1798561151, "max_line_length": 109, "alphanum_fraction": 0.5647096983, "num_tokens": 2101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877684006774, "lm_q2_score": 0.8267118026095992, "lm_q1q2_score": 0.8024790347856131}} {"text": "function linearTrussStiffnessMatrix( E, A, nodalCoords )\n\n diff = nodalCoords[ 2, : ] - nodalCoords[ 1, : ] ;\n\n length = sqrt( diff' * diff ) ;\n c = diff[1] / length ;\n s = diff[3] / length ;\n\n Qloc2glo = [ c -s 0 0 ;\n s c 0 0 ;\n 0 0 c -s ;\n 0 0 s c ] ;\n\n Kloc = E*A/length * [ 1 0 -1 0 ;\n 0 0 0 0 ;\n -1 0 1 0 ;\n 0 0 0 0 ] ;\n Kglo = Qloc2glo * Kloc * transpose(Qloc2glo) ;\n\n return Kglo\nend\n#\n", "meta": {"hexsha": "2a90fdea0f671ddd14d1d6eccdc781bb7c586d1a", "size": 565, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/elements/linearTrussStiffnessMatrix.jl", "max_stars_repo_name": "jorgepz/FEMAssembler.jl", "max_stars_repo_head_hexsha": "2d4386b532c1ba41feaf82131454fa07d61f0c96", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/elements/linearTrussStiffnessMatrix.jl", "max_issues_repo_name": "jorgepz/FEMAssembler.jl", "max_issues_repo_head_hexsha": "2d4386b532c1ba41feaf82131454fa07d61f0c96", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-03-07T16:18:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T10:50:46.000Z", "max_forks_repo_path": "src/elements/linearTrussStiffnessMatrix.jl", "max_forks_repo_name": "jorgepz/FEMAssembler.jl", "max_forks_repo_head_hexsha": "2d4386b532c1ba41feaf82131454fa07d61f0c96", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-25T15:21:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T15:21:19.000Z", "avg_line_length": 24.5652173913, "max_line_length": 57, "alphanum_fraction": 0.3805309735, "num_tokens": 211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9706877726405082, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.8024790300021005}} {"text": "\n#Import Turing, Distributions and DataFrames\nusing Turing, Distributions, DataFrames, Distributed\n\n# Import MCMCChain, Plots, and StatsPlots for visualizations and diagnostics.\nusing MCMCChains, Plots, StatsPlots\n\n# Set a seed for reproducibility.\nusing Random\nRandom.seed!(12);\n\n# Turn off progress monitor.\nTuring.setprogress!(false)\n\n\ntheta_noalcohol_meds = 1 # no alcohol, took medicine\ntheta_alcohol_meds = 3 # alcohol, took medicine\ntheta_noalcohol_nomeds = 6 # no alcohol, no medicine\ntheta_alcohol_nomeds = 36 # alcohol, no medicine\n\n# no of samples for each of the above cases\nq = 100\n\n#Generate data from different Poisson distributions\nnoalcohol_meds = Poisson(theta_noalcohol_meds)\nalcohol_meds = Poisson(theta_alcohol_meds)\nnoalcohol_nomeds = Poisson(theta_noalcohol_nomeds)\nalcohol_nomeds = Poisson(theta_alcohol_nomeds)\n\nnsneeze_data = vcat(\n rand(noalcohol_meds, q),\n rand(alcohol_meds, q),\n rand(noalcohol_nomeds, q),\n rand(alcohol_nomeds, q),\n)\nalcohol_data = vcat(zeros(q), ones(q), zeros(q), ones(q))\nmeds_data = vcat(zeros(q), zeros(q), ones(q), ones(q))\n\ndf = DataFrame(;\n nsneeze=nsneeze_data,\n alcohol_taken=alcohol_data,\n nomeds_taken=meds_data,\n product_alcohol_meds=meds_data .* alcohol_data,\n)\ndf[sample(1:nrow(df), 5; replace=false), :]\n\n\n#Data Plotting\n\np1 = Plots.histogram(\n df[(df[:, :alcohol_taken] .== 0) .& (df[:, :nomeds_taken] .== 0), 1];\n title=\"no_alcohol+meds\",\n)\np2 = Plots.histogram(\n (df[(df[:, :alcohol_taken] .== 1) .& (df[:, :nomeds_taken] .== 0), 1]);\n title=\"alcohol+meds\",\n)\np3 = Plots.histogram(\n (df[(df[:, :alcohol_taken] .== 0) .& (df[:, :nomeds_taken] .== 1), 1]);\n title=\"no_alcohol+no_meds\",\n)\np4 = Plots.histogram(\n (df[(df[:, :alcohol_taken] .== 1) .& (df[:, :nomeds_taken] .== 1), 1]);\n title=\"alcohol+no_meds\",\n)\nplot(p1, p2, p3, p4; layout=(2, 2), legend=false)\n\n\n# Convert the DataFrame object to matrices.\ndata = Matrix(df[:, [:alcohol_taken, :nomeds_taken, :product_alcohol_meds]])\ndata_labels = df[:, :nsneeze]\ndata\n\n\n# # Rescale our matrices.\ndata = (data .- mean(data; dims=1)) ./ std(data; dims=1)\n\n\n# Bayesian poisson regression (LR)\n@model function poisson_regression(x, y, n, σ²)\n b0 ~ Normal(0, σ²)\n b1 ~ Normal(0, σ²)\n b2 ~ Normal(0, σ²)\n b3 ~ Normal(0, σ²)\n for i in 1:n\n theta = b0 + b1 * x[i, 1] + b2 * x[i, 2] + b3 * x[i, 3]\n y[i] ~ Poisson(exp(theta))\n end\nend;\n\n\n# Retrieve the number of observations.\nn, _ = size(data)\n\n# Sample using NUTS.\n\nnum_chains = 4\nm = poisson_regression(data, data_labels, n, 10)\nchain = sample(m, NUTS(200, 0.65), MCMCThreads(), 2_500, num_chains; discard_adapt=false)\n\n\ngelmandiag(chain)\n\n\n# Taking the first chain\nc1 = chain[:, :, 1]\n\n# Calculating the exponentiated means\nb0_exp = exp(mean(c1[:b0]))\nb1_exp = exp(mean(c1[:b1]))\nb2_exp = exp(mean(c1[:b2]))\nb3_exp = exp(mean(c1[:b3]))\n\nprint(\"The exponent of the meaned values of the weights (or coefficients are): \\n\")\nprintln(\"b0: \", b0_exp)\nprintln(\"b1: \", b1_exp)\nprintln(\"b2: \", b2_exp)\nprintln(\"b3: \", b3_exp)\nprint(\"The posterior distributions obtained after sampling can be visualised as :\\n\")\n\n\nplot(chain)\n\n\n# Note the standard deviation before removing the warmup samples\ndescribe(chain)\n\n\n# Removing the first 200 values of the chains.\nchains_new = chain[201:2500, :, :]\ndescribe(chains_new)\n\n\nplot(chains_new)\n\n\nif isdefined(Main, :TuringTutorials)\n Main.TuringTutorials.tutorial_footer(WEAVE_ARGS[:folder], WEAVE_ARGS[:file])\nend\n\n", "meta": {"hexsha": "7ce8fdeeb722292ed012ff0649c71da782fc0aa2", "size": 3500, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/07-poisson-regression/07_poisson-regression.jl", "max_stars_repo_name": "TuringLang/TuringTutorialsOutput", "max_stars_repo_head_hexsha": "0928cc205032f4b117b5d1dd1512b1621fb5674a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "script/07-poisson-regression/07_poisson-regression.jl", "max_issues_repo_name": "TuringLang/TuringTutorialsOutput", "max_issues_repo_head_hexsha": "0928cc205032f4b117b5d1dd1512b1621fb5674a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/07-poisson-regression/07_poisson-regression.jl", "max_forks_repo_name": "TuringLang/TuringTutorialsOutput", "max_forks_repo_head_hexsha": "0928cc205032f4b117b5d1dd1512b1621fb5674a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8226950355, "max_line_length": 89, "alphanum_fraction": 0.6857142857, "num_tokens": 1127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308091776495, "lm_q2_score": 0.8596637451167997, "lm_q1q2_score": 0.802436625225063}} {"text": "\"\"\"\n\nLicense: MIT\nJulia 1.02\nDynamic programming formulation to count number of matchings of maximum cardinality\n\"\"\"\n\nusing Printf\n# INPUT\n# G - graph generated using Graph_generation\n# Recursive_table - dictionary computed in CountingMatchings_rosso.jl with recursive approach\n# maxCard - size of the maximum cardinality matching\nusing Distributions\nfunction UniformMaxMatching_julia(G,E,Recursive_table,maxCard)\n set_V = sort(collect(keys(G)))\n s_aux = [1 for v in set_V]\n r = length(E)\n sol_M = [] # it will contain the edges in the generated matching\n for e in reverse(E)\n # e is in set_E with prob:\n aux = rand()\n if r-1== 0 # if r-1 = 0 then x_r must be added, otherwise sol_M alread had maxCard nodes and the algorithm had stopped\n prob_no_e = 0\n else\n # probability of x_e = 0\n prob_no_e = Recursive_table[r-1,maxCard,s_aux]/(Recursive_table[r,maxCard,s_aux])\n end\n if aux > prob_no_e\n # then x_e = 1\n append!(sol_M,[Set(e)])\n #s_aux = [1 if v not in e else 0 for v in set_V]\n s_aux = [if !(v in e) s_aux[j] else s_aux[j]-1 end for (j,v) in enumerate(set_V)]\n maxCard = maxCard - 1\n end\n r = r-1\n if maxCard == 0\n return sol_M\n end\n end\n return sol_M\nend\n\n# ask the number of matching to generate\nfunction Uniform_Number(G,E,gen_num,info)\n # maximum cardinality\n maxCard = OptimalMatching(G,E)\n ## save maxCard\n if info==1\n maxCardinality = @sprintf \"%d\" maxCard\n fres = open(\"results.txt\",\"a\")\n write(fres,\"maxCard= \",maxCardinality, \" \\n\")\n close(fres)\n end\n ## end save\n r = length(E)\n s = Dict(v=>1 for v in keys(G))\n F_table,Numb_matchings= Count_Mat_Paper(G, maxCard,E,r,s,1)\n ## save number of maximum matchings\n Numb_OPT_matchings = @sprintf \"%d\" Numb_matchings\n if info==1\n fres = open(\"results.txt\",\"a\")\n write(fres,\"Numb_matchings= \",Numb_OPT_matchings, \" \\n\")\n close(fres)\n end\n ## end save\n fgen = open(\"tmp.txt\",\"w\")\n for _ in 1:gen_num\n gen_M =UniformMaxMatching_julia(G,E,F_table,maxCard)\n aux = 0\n for e in gen_M\n e = [v for v in e]\n if aux ==0\n write(fgen,\"[{\")\n else\n write(fgen,\",{\")\n end\n write(fgen,string(e[1])*\",\"*string(e[2])*\"}\")\n aux = aux+1\n end\n if length(gen_M)==0\n write(fgen,\"[{}]\\n\")\n else\n write(fgen,\"] \\n\")\n end\n end\n close(fgen)\nend\n", "meta": {"hexsha": "0c05acb8c7adb6a1b0c51eeb51f6ef737ed01441", "size": 2638, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "UniformGeneration_julia.jl", "max_stars_repo_name": "mxmmargarida/KEG", "max_stars_repo_head_hexsha": "0e8e1920b2bfe13d0d3c60863f38ca0a5f5793a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "UniformGeneration_julia.jl", "max_issues_repo_name": "mxmmargarida/KEG", "max_issues_repo_head_hexsha": "0e8e1920b2bfe13d0d3c60863f38ca0a5f5793a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "UniformGeneration_julia.jl", "max_forks_repo_name": "mxmmargarida/KEG", "max_forks_repo_head_hexsha": "0e8e1920b2bfe13d0d3c60863f38ca0a5f5793a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9772727273, "max_line_length": 126, "alphanum_fraction": 0.5750568613, "num_tokens": 744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632916317103, "lm_q2_score": 0.865224084314688, "lm_q1q2_score": 0.8023770548291015}} {"text": "\n\"\"\"\n transformLog(data::T, base::Real = ℯ) where T <: AbstractArray{<: Number}\n\nLog transform `data` using log-base, `base`.\n\n# Examples:\n\n```julia-repl\njulia> data = [0:5;];\n\njulia> transformLog(data)\n6-element Array{Float64,1}:\n -Inf\n 0.0\n 0.6931471805599453\n 1.0986122886681098\n 1.3862943611198906\n 1.6094379124341003\n\njulia> transformLog(data,2)\n6-element Array{Float64,1}:\n -Inf\n 0.0\n 1.0\n 1.5849625007211563\n 2.0\n 2.321928094887362\n\n```\n\nSee also: [`transformRoot`](@ref), [`transformBoxCox`](@ref)\n\"\"\"\nfunction transformLog(data::T, base::Real = ℯ) where T <: AbstractArray{<: Number}\n log.(base,data)\nend\n\n\"\"\"\n transformRoot(data::T, index::Real = 10) where T <: AbstractArray{<: Number}\n\nRoot transform `data` using root index, `index`.\n\n# Examples:\n\n```julia-repl\njulia> data = [0:5;];\n\njulia> transformRoot(data)\n6-element Array{Float64,1}:\n 0.0\n 1.0\n 1.0717734625362931\n 1.1161231740339044\n 1.148698354997035\n 1.174618943088019\n\njulia> transformRoot(data,2)\n6-element Array{Float64,1}:\n 0.0\n 1.0\n 1.4142135623730951\n 1.7320508075688772\n 2.0\n 2.23606797749979\n```\n\nSee also: [`transformLog`](@ref), [`transformBoxCox`](@ref)\n\"\"\"\nfunction transformRoot(data::T, index::Real = 10) where T <: AbstractArray{<: Number}\n data .^ (1/index)\nend\n\n\"\"\"\n transformBoxCox(data::T, λ::Real = 0.0) where T <: AbstractArray{<: Number}\n\n[Box-Cox power transformation](https://en.wikipedia.org/wiki/Power_transform#Box%E2%80%93Cox_transformation)\nfollowing the following function:\n\n```math\ny_i^{(\\\\lambda)} = \\\\left\\\\{\\\\begin{matrix}\n\\\\frac{y_i^\\\\lambda - 1}{\\\\lambda} & \\\\mathrm{if} \\\\lambda \\\\neq 0, \\\\\\\\ \n\\\\mathrm{ln} y_i & \\\\mathrm{if} \\\\lambda = 0, \n\\\\end{matrix}\\\\right.\n```\n\n# Examples:\n\n```julia-repl\njulia> data = [0:5;];\n\njulia> transformBoxCox(data)\n6-element Array{Float64,1}:\n -Inf\n 0.0\n 0.6931471805599453\n 1.0986122886681098\n 1.3862943611198906\n 1.6094379124341003\n\njulia> transformBoxCox(data,.1)\n6-element Array{Float64,1}:\n -10.0\n 0.0\n 0.7177346253629313\n 1.1612317403390437\n 1.486983549970351\n 1.7461894308801895\n\njulia> transformBoxCox(data,1)\n6-element Array{Float64,1}:\n -1.0\n 0.0\n 1.0\n 2.0\n 3.0\n 4.0\n```\n\nSee also: [`transformLog`](@ref), [`transformRoot`](@ref)\n\"\"\"\nfunction transformBoxCox(data::T, λ::Real = 0.0) where T <: AbstractArray{<: Number}\n λ == 0 ? log.(data) : (data .^ λ .- 1) ./ λ \nend\n\n\n", "meta": {"hexsha": "51e8e851076576de61a74ecd48a4339bffc8b011", "size": 2386, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/numeric/transforming.jl", "max_stars_repo_name": "a-poor/FeatureEng.jl", "max_stars_repo_head_hexsha": "d8aa98b29dd707c66812582dc0dd68506b46f015", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-02-05T14:39:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-26T18:50:49.000Z", "max_issues_repo_path": "src/numeric/transforming.jl", "max_issues_repo_name": "a-poor/FeatureEng.jl", "max_issues_repo_head_hexsha": "d8aa98b29dd707c66812582dc0dd68506b46f015", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-01-29T00:40:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-03T16:33:04.000Z", "max_forks_repo_path": "src/numeric/transforming.jl", "max_forks_repo_name": "a-poor/FeatureEng.jl", "max_forks_repo_head_hexsha": "d8aa98b29dd707c66812582dc0dd68506b46f015", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.9365079365, "max_line_length": 108, "alphanum_fraction": 0.6647108131, "num_tokens": 926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542185, "lm_q2_score": 0.865224073888819, "lm_q1q2_score": 0.8023770503713524}} {"text": "module SimpleQuaternions\n\nusing LinearAlgebra\n\nexport SimpleQuaternion, jm, km, get_parts\n\nimport Base: (+), (-), (*), (/), (//), (==), inv, string, show, adjoint, conj\nimport Base: real, isreal, zero, one\nimport LinearAlgebra: norm\nexport norm\n\n\nstruct SimpleQuaternion{T} <: Number\n a::T \n b::T\n c::T \n d::T \n function SimpleQuaternion(x::Real=0, y::Real=0, z::Real=0, w::Real=0)\n (aa,bb,cc,dd) = promote(x,y,z,w)\n T = typeof(aa)\n new{T}(aa,bb,cc,dd)\n end \nend\n\n\"\"\"\n`get_parts(x::SimpleQuaternion)` returns the tuple `(a,b,c,d)` that are \nreal and various imaginary get_parts of `x`. Specifically, \n`x == a + b*im + c*jm + d*km`.\n\"\"\"\nget_parts(x::SimpleQuaternion) = (x.a,x.b,x.c,x.d)\n\n\"\"\"\n`SimpleQuaternion` creates a quaternion number. The basic constructor \nis `SimpleQuaternion(a,b,c,d)` which is equivalent to \n`a + b*im + c*jm + d*km`.\n\n`SimpleQuaternion(x::Real)` yields `x + 0*im + 0*jm + 0*km`.\n\nIf `z` is the `Complex` number `a+b*im` then `SimpleQuaternion(z)`\nyields `a + b*im + 0*jm + 0*km`.\n\"\"\"\nSimpleQuaternion(z::Complex) = SimpleQuaternion(real(z),imag(z),0,0)\n\n\nfunction SimpleQuaternion{T}(a::Real=0,b::Real=0,c::Real=0,d::Real=0) where T<:Real\n (x,aa,bb,cc,dd) = promote(one(T),a,b,c,d)\n SimpleQuaternion(aa,bb,cc,dd)\nend \n\n\"\"\"\n`jm` is the quaternion unit *j*.\n\"\"\"\njm = SimpleQuaternion(false,false,true,false)\n\n\"\"\"\n`km` is the quaternion unit *k*.\n\"\"\"\nkm = SimpleQuaternion(false,false,false,true)\n\nfunction (==)(x::SimpleQuaternion,y::SimpleQuaternion)\n get_parts(x) == get_parts(y)\nend\n\n\"\"\"\n`real(x::SimpleQuaternion)` returns the real part of `x`.\n\"\"\"\nreal(x::SimpleQuaternion) = x.a\n\n\"\"\"\n`isreal(x::SimpleQuaternion)` returns `true` exactly when `x` is a real \nnumber (all complex get_parts are zero).\n\"\"\"\nisreal(x::SimpleQuaternion) = x == x.a \n\n(==)(x::SimpleQuaternion, y::Number) = x == SimpleQuaternion(y)\n(==)(x::Number, y::SimpleQuaternion) = SimpleQuaternion(x) == y\n\none(a::SimpleQuaternion{T}) where T = SimpleQuaternion(one(T))\nzero(a::SimpleQuaternion{T}) where T = SimpleQuaternion(zero(T))\n\none(::Type{SimpleQuaternion{T}}) where T = SimpleQuaternion(one(T))\nzero(::Type{SimpleQuaternion{T}}) where T = SimpleQuaternion(zero(T))\n\ninclude(\"arithmetic.jl\")\ninclude(\"show.jl\")\ninclude(\"matrices.jl\")\ninclude(\"random.jl\")\n\nend # module\n", "meta": {"hexsha": "5da7377922d79c8e21e26af75806eb71e43d4986", "size": 2321, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SimpleQuaternions.jl", "max_stars_repo_name": "scheinerman/SimpleQuaternions.jl", "max_stars_repo_head_hexsha": "ad494b7d866fc74c359177155bc58fa2c6b66f07", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SimpleQuaternions.jl", "max_issues_repo_name": "scheinerman/SimpleQuaternions.jl", "max_issues_repo_head_hexsha": "ad494b7d866fc74c359177155bc58fa2c6b66f07", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SimpleQuaternions.jl", "max_forks_repo_name": "scheinerman/SimpleQuaternions.jl", "max_forks_repo_head_hexsha": "ad494b7d866fc74c359177155bc58fa2c6b66f07", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-13T11:56:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-13T11:56:34.000Z", "avg_line_length": 25.7888888889, "max_line_length": 83, "alphanum_fraction": 0.6591986213, "num_tokens": 711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.865224072151174, "lm_q1q2_score": 0.8023770452860448}} {"text": "#solve eq x=cos(x)\n#Reference: http://nbviewer.jupyter.org/gist/genkuroki/ce7f62d10365b9a25c82aad499c886c2\n\nfunction bisection(f, x₀::T, x₁::T; ε=eps(T), maxiter=10^8) where T<:AbstractFloat\n y₀, y₁ = f(x₀), f(x₁)\n iter = 0\n y₀ == 0 && return x₀, iter\n y₁ == 0 && return x₁, iter\n y₀ * y₁ > 0 && return T(NaN), -1\n for iter in 1:maxiter\n x₂ = (x₀ + x₁)/2\n y₂ = f(x₂)\n y₂ == 0 && return x₂, iter\n if y₀ * y₂ > 0\n x₀, y₀ = x₂, y₂\n else\n x₁, y₁ = x₂, y₂\n end\n abs(x₁ - x₀) < ε && return x₂, iter\n end\n return T(NaN), iter\nend\n\nfunction main()\n f(x)=x-cos(x)\n x₀, x₁ = 0.0, 3.14\n @show α, iter = bisection(f, x₀, x₁)\n @show f(α)\nend\n\nmain()", "meta": {"hexsha": "681a33de958ba7629ee93efe60ce04f224675f99", "size": 743, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "solveNonLinear/bisection/bisection_gen_kuroki.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_gen_kuroki.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_gen_kuroki.jl", "max_forks_repo_name": "terasakisatoshi/juliaExer", "max_forks_repo_head_hexsha": "e3c2195f39de858915a3dcd47684eccbb7ecb552", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9677419355, "max_line_length": 87, "alphanum_fraction": 0.5181695828, "num_tokens": 319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811591688146, "lm_q2_score": 0.8311430415844385, "lm_q1q2_score": 0.8023698329198795}} {"text": "function energy(planets)\n eng = 0.0\n # kinetic energy\n for p in planets\n eng += 1/2*p.m*norm2(p.v)\n end\n # potential energy\n for j in 1:nplanets\n pj = planets[j]\n for k in j+1:nplanets\n pk = planets[k]\n eng -= G*pj.m*pk.m/sqdist(pj.r, pk.r)\n end\n end\n eng\nend\n \nfunction barycenter(m,mTot,x,y,z) # Find Barycenter\n # m : mass of planet\n # mTot : total mass of system\n # x,y,z: position coordinates of planet\n #\n baryX = (m*x)/mTot\n baryY = (m*y)/mTot\n baryZ = (m*z)/mTot\n return baryX,baryY,baryZ;\nend\n\nfunction momentum(m,x,y,z,vx,vy,vz)\n r = [x,y,z];\n vel = [vx,vy,vz];\n H = m*cross(r,vel);\n return H;\nend\n\n", "meta": {"hexsha": "86680af3f6f78b61d67052dd6d3ef1560a64a154", "size": 725, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "JuliaReverse/NBodyLeapFrog.jl", "max_stars_repo_head_hexsha": "6ac5e78760ad0078bcc71c7afb525630326bd5e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "JuliaReverse/NBodyLeapFrog.jl", "max_issues_repo_head_hexsha": "6ac5e78760ad0078bcc71c7afb525630326bd5e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "JuliaReverse/NBodyLeapFrog.jl", "max_forks_repo_head_hexsha": "6ac5e78760ad0078bcc71c7afb525630326bd5e3", "max_forks_repo_licenses": ["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.1388888889, "max_line_length": 51, "alphanum_fraction": 0.5379310345, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122720843811, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.802366442219827}} {"text": "using Distributions\nusing Gadfly\nusing PMTK4Stats\n\n\"\"\"\nPlot CI and HPD for beta posterior\n\"\"\"\nfunction drawBetaHPD()\n a = 3\n b = 9\n α = 0.05\n β = Beta(a, b) \n\n CI = quantile(β, [α/2, 1-α/2])\n \n xs = linspace(0.001, 0.999, 40)\n ps = pdf(β, xs)\n \n icdf(p::Real) = quantile(β, p)\n HPD = hdiFromIcdf(icdf)\n \n ints = hcat(CI, HPD)\n names = [\"CI\"; \"HPD\"]\n \n function plot_ci(int, name)\n l, u = int\n pl = pdf(β, l)\n pu = pdf(β, u)\n vert_up_l = layer(x=[l, l], y=[0, pl], Geom.line, Theme(default_color=colorant\"blue\", line_width=3px))\n hor_l = layer(x=[l, u], y=[pl, pu], Geom.line, Theme(default_color=colorant\"blue\", line_width=3px))\n vert_dn_l = layer(x=[u, u], y=[pu, 0], Geom.line, Theme(default_color=colorant\"blue\", line_width=3px))\n pdf_l = layer(x=xs, y=ps, Geom.line, Theme(default_color=colorant\"black\", line_width=3px))\n \n pp = plot(vert_up_l, hor_l, vert_dn_l, pdf_l)\n end\n \n [plot_ci(slicedim(ints, 2, i), names[i]) for i=1:length(names)]\nend\n\n", "meta": {"hexsha": "ff840d2ec5fe7abd755eaa0b6868a847ea70811a", "size": 1077, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/BayesianStatistics/betaHPD.jl", "max_stars_repo_name": "aoboturov/PMTK4BookDemos.jl", "max_stars_repo_head_hexsha": "f44853081139b358e0e9a2bb36a3d35ac35dcb39", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-25T15:50:42.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-25T15:50:42.000Z", "max_issues_repo_path": "src/BayesianStatistics/betaHPD.jl", "max_issues_repo_name": "aoboturov/PMTK4BookDemos.jl", "max_issues_repo_head_hexsha": "f44853081139b358e0e9a2bb36a3d35ac35dcb39", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BayesianStatistics/betaHPD.jl", "max_forks_repo_name": "aoboturov/PMTK4BookDemos.jl", "max_forks_repo_head_hexsha": "f44853081139b358e0e9a2bb36a3d35ac35dcb39", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.925, "max_line_length": 111, "alphanum_fraction": 0.5710306407, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122720843811, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.802366442219827}} {"text": "function lucrout(A)\r\n A = convert(Array{Float64,2},A);\r\n numRow, numCol = size(A);\r\n if numRow != numCol\r\n return println(\"Non-square matrix\")\r\n end\r\n\r\n L, U = zeros(numRow,numCol), zeros(numRow,numCol); # initialize\r\n\r\n # We first put the first column of L and the ones in U\r\n for j in 1:numRow\r\n L[j,1] = A[j,1];\r\n U[j,j] = 1.0;\r\n end\r\n\r\n # We then obtain the fist row of U by dividing\r\n for j = 2:numRow\r\n U[1,j] = A[1,j]/L[1,1];\r\n end\r\n\r\n # Now we try to calculate the rest\r\n\r\n for i = 2:numCol\r\n # We calculate all the i-th column of L\r\n for j in i:numRow\r\n S = 0; #initialize\r\n for k in 1:i-1\r\n S += L[j,k]*U[k,i];\r\n end\r\n L[j,i] = A[j,i] - S;\r\n end\r\n \r\n #We know calculate the U-th row of U \r\n for j = (i+1):numCol\r\n S = 0; # Initialize\r\n for k= 1:(i-1)\r\n S += L[i,k]*U[k,j];\r\n end\r\n U[i,j] = 1/L[i,i]*(A[i,j]-S);\r\n end\r\n\r\n end\r\n return L,U\r\nend\r\n\r\n", "meta": {"hexsha": "3150049df9f88f20e7b4ded08c24a322867d02ad", "size": 1100, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lucrout.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/lucrout.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/lucrout.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": 23.9130434783, "max_line_length": 68, "alphanum_fraction": 0.4427272727, "num_tokens": 338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122672782974, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.8023664401356022}} {"text": "\"\"\"\n determinant(mat)\n\nGiven a non singluar matrix, calculate its determinant using LU decomposition.\n\nL and U are lower triangular and upper triangular matrices respectively such that\n\nA = L*U\n\nIf we want to find the determinant, then\n\ndet(A) = det(LU) = det(L)*det(U)\n\nDeterminant of triangualar matrices is the product of their diagonal entries. Hence, makes finding the determinant easy.\n\"\"\"\nfunction determinant(mat)\n n, m = size(mat)\n if n != m\n DomainError(mat, \"The matrix should be a square matrix.\")\n end\n L, U = lu_decompose(mat)\n l_prod = prod([L[i, i] for i in 1:n])\n u_prod = prod([U[i, i] for i in 1:n])\n\n return l_prod * u_prod\nend\n", "meta": {"hexsha": "b4bf2faf7ec2b6bd82d7ca68e5cce8a0622bb43c", "size": 679, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/matrix/determinant.jl", "max_stars_repo_name": "Whiteshark-314/Julia", "max_stars_repo_head_hexsha": "3285d8d6b7585cc1075831c2c210b891151da0c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-10-14T21:48:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-14T21:48:50.000Z", "max_issues_repo_path": "src/matrix/determinant.jl", "max_issues_repo_name": "AugustoCL/Julia", "max_issues_repo_head_hexsha": "1bf4e4a7829fafc64290d903bcbfdd48eab839e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/matrix/determinant.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.1481481481, "max_line_length": 120, "alphanum_fraction": 0.6833578792, "num_tokens": 180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9579122720843812, "lm_q2_score": 0.8376199552262967, "lm_q1q2_score": 0.8023664344540395}} {"text": "\"\"\"\n\n```\nsphericalshellvolume(i,step)\n```\n\nComputes the volume of the spherical shell defined within [(i-1)*step,i*step].\n\n\"\"\"\nfunction sphericalshellvolume(i,step)\n rmin = (i-1)*step\n return (4*pi/3)*( (rmin+step)^3 - rmin^3 )\nend\n\n\n", "meta": {"hexsha": "3967f9d6eccebe921bb2a09451692c98e4a29281", "size": 236, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/sphericalshellvolume.jl", "max_stars_repo_name": "m3g/ComplexMixtures.jl", "max_stars_repo_head_hexsha": "0ba3d05f31742752dae37bd4192122d95c984c7f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-05-14T02:35:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-22T15:56:19.000Z", "max_issues_repo_path": "src/sphericalshellvolume.jl", "max_issues_repo_name": "m3g/ComplexMixtures.jl", "max_issues_repo_head_hexsha": "0ba3d05f31742752dae37bd4192122d95c984c7f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2021-03-18T19:41:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-26T13:56:17.000Z", "max_forks_repo_path": "src/sphericalshellvolume.jl", "max_forks_repo_name": "m3g/ComplexMixtures.jl", "max_forks_repo_head_hexsha": "0ba3d05f31742752dae37bd4192122d95c984c7f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.75, "max_line_length": 78, "alphanum_fraction": 0.656779661, "num_tokens": 76, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9579122672782974, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.8023664323698148}} {"text": "using Plots\n\n\nfunction rosenbrock(x; a=1, b=100)\n (a-x[1])^2 + b * (x[2] - x[1]^2)^2;\nend\n\n# plot\n\n# contour(-2:0.1:2, -1:0.1:3, (x, y)->rosenbrock([x, y]))\nheatmap(-2:0.01:2, -1:0.01:3, (x, y)->rosenbrock([x, y]))\n", "meta": {"hexsha": "934f9e8ee9a30c5f0a3d2107b9421bceff4cee79", "size": 218, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test_function/rosenbrocks_banana_function.jl", "max_stars_repo_name": "tor4z/convex_optimization", "max_stars_repo_head_hexsha": "15fd3aa09fbc3306ff68cc301bbddac3d2006f3f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test_function/rosenbrocks_banana_function.jl", "max_issues_repo_name": "tor4z/convex_optimization", "max_issues_repo_head_hexsha": "15fd3aa09fbc3306ff68cc301bbddac3d2006f3f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test_function/rosenbrocks_banana_function.jl", "max_forks_repo_name": "tor4z/convex_optimization", "max_forks_repo_head_hexsha": "15fd3aa09fbc3306ff68cc301bbddac3d2006f3f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.1666666667, "max_line_length": 57, "alphanum_fraction": 0.5183486239, "num_tokens": 117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9603611631680358, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.8023659395334122}} {"text": "using LinearAlgebra\n\n\"\"\"Optimize some function f\n# Args:\n ∇f: Gradient of f\n x_0: Initial guess\n η: learning rate\n ε: cancellation tolerance\n max_iters: maximum number of iterations\n\"\"\"\nfunction gradient_descent(∇f::Function,\n x_0,\n η::Number,\n ε::Number,\n max_iters::Integer)\n x_k = x_0\n count = 0\n for _ = 1:max_iters\n if any(isnan.(x_k))\n error(\"Encoutered NaN\")\n end\n if any(isinf.(x_k))\n error(\"Encoutered Inf\")\n end\n count += 1\n p_k = -∇f(x_k)\n if norm(∇f(p_k)) < ε\n break\n end\n x_k += η * p_k\n end\n x_k\nend\n\n#numeric_differentiation(f, h) = x -> (f(x + h) - f(x)) / h\nnumeric_differentiation(f, h) = x -> (f(x + h) - f(x - h)) / (2 * h)\n\n\"\"\"BFGS Optimization Algorithm\nBroyden–Fletcher–Goldfarb–Shanno algorithm\nfor details see:\n https://en.wikipedia.org/wiki/Broyden%E2%80%93Fletcher%E2%80%93Goldfarb%E2%80%93Shanno_algorithm\n\n# Args:\n ∇f: Gradient of function to optimize\n x_0: Initial guess for optimal value\n iters: Maximum number of iterations before cancellation\n line_search: Line search function that's used\n ε: Optimization stops once the norm of the gradient is below this value\n ls_x_0: Initial value for the line search\n ls_η: Learning rate for the line search\n ε_ls: same as ε but for the line search\n\"\"\"\nfunction BFGS(f::Function,\n ∇f::Function, \n x_0::Vector{<:Number}, \n iters::Integer,\n line_search::Function,\n ε = 10e-12::Real,\n )\n n = size(x_0)[1]\n x_k = x_0\n B_k = Matrix{typeof(x_0[1])}(I, n, n)\n did_iters = 0\n for i = 1:iters\n did_iters += 1\n if norm(∇f(x_k)) < ε\n break\n end\n # Step 1: obtain direction p_k by solving B_k ∙ p_k = - (gradient of f at x_k)\n p_k = B_k \\ -∇f(x_k)\n\n # Step 2.: Find stepsize α_k such that α_k = arg min ∂f(x_k + α_k * p_k)/∂α\n α_k = line_search(numeric_differentiation(α->(f(x_k + α * p_k)), 10e-10))\n if isnan(α_k)\n break\n end\n \n # Step 3.\n s_k = α_k * p_k\n x_k_prime = x_k + s_k\n \n # Step 4.\n y_k = ∇f(x_k_prime) - ∇f(x_k)\n\n # Step 5.\n B_k += (y_k * y_k') / (y_k' * s_k) - (B_k * s_k * s_k' * B_k) / (s_k' * B_k * s_k)\n x_k = x_k_prime\n end\n println(did_iters)\n x_k\nend\n\n# f(x) = -5 * x[1] + 10 * x[1]^2\n# ∇f(x) = [-5 + 20 * x[1]]\nf(x) = x[1]^5 / 5000 + 21 * x[1]^4 / 4000 + 17 * x[1]^3 / 375 + 293 * x[1]^2 / 1000 + 521 * x[1] / 1000\n∇f(x) = [x[1]^4 / 1000 + 21 * x[1]^3 / 1000 + 17 * x[1]^2 / 125 + 293 * x[1] / 500 + 521 / 1000]\na = 1\nb = 100\nr(X) = begin\n x = X[1]\n y = X[2]\n (a - x)^2 + b*(y - x^2)^2\nend\n∇r(X) = begin\n x = X[1]\n y = X[2]\n [-2*a+4*b*x^3-4*b*x*y+2*x, 2*b*(y-x^2)]\nend\n#f(X) = begin\n# x = X[1]\n# y = X[2]\n# x^2 + y^2\n#end\n#∇f(X) = begin\n# x = X[1]\n# y = X[2]\n# [2*x, 2*y]\n#end\nprintln(\"optimal x = \", BFGS(\n f,\n ∇f,\n [0],\n 500,\n ∇f -> gradient_descent(∇f, 10e-10, 1, 1e-10, 1000),\n 10e-5))\n\n\n# f(w, x) = w[1] * x[1] + w[2] * x[1]^2\n\n# ∇f(w, x) = [w[1] + 2 * x[1] * w[2]] # [x; x^2]\n\n# # initialize parameters\n# w_0 = [-5, 10]\n# x_0 = [-5]\n# B_0 = Matrix{Float64}(I, 1, 1) # initialize approximate hessian with identity matrix\n# ε = 1e-10 # cancellation parameter\n\n# w_k = w_0\n# x_k = x_0\n# B_k = B_0\n\n# while begin\n# x = norm(∇f(w_k, x_k))\n# println(\"∇f = \", x)\n# x > ε\n# end\n# global B_k\n# global x_k\n# # Step 1.: obtain direction p_k by solving B_k*p_k = - (gradient of f at x_k)\n\n# p_k = B_k \\ -∇f(w_k, x_k)\n\n# # Step 2.: Find stepsize α_k such that α_k minimizes f(x_k + α_k * p_k)\n\n# g_k(α) = w_k[1] + 2 * (x_k[1] + α * p_k[1]) * w_k[2]\n# α_k = line_search_gradient_descent(g_k, 0, 0.000001, 1e-10)\n# println(\"α_k = \", α_k)\n\n# # Step 3.\n# s_k = α_k * p_k\n# x_k_prime = x_k + s_k\n\n# # Step 4.\n# y_k = ∇f(w_k, x_k_prime) - ∇f(w_k, x_k)\n\n# # Step 5.\n# B_k += (y_k * y_k') / (y_k' * s_k) - (B_k * s_k * s_k' * B_k) / (s_k' * B_k * s_k)\n# x_k = x_k_prime\n# end\n\n# println(x_k)\n\n\"\"\"\nbegin\n inv_B = inv(B_k)\n (s_k' * y_k + y_k' * inv_B * y_k) * (s_k * s_k') / (s_k' * y_k)^2 - (inv_B * y_k * s_k' + s_k * y_k' * inv_B) / (s_k' * y_k)\nend\n\"\"\"\n", "meta": {"hexsha": "eea1942c4a00bf0271e1a056c3b42e3238593e20", "size": 4308, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "BFGS.jl", "max_stars_repo_name": "SV-97/LinearRegression", "max_stars_repo_head_hexsha": "32c5efa06bf3bd5e541fd9b084a0827c642cdf10", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "BFGS.jl", "max_issues_repo_name": "SV-97/LinearRegression", "max_issues_repo_head_hexsha": "32c5efa06bf3bd5e541fd9b084a0827c642cdf10", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BFGS.jl", "max_forks_repo_name": "SV-97/LinearRegression", "max_forks_repo_head_hexsha": "32c5efa06bf3bd5e541fd9b084a0827c642cdf10", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0670391061, "max_line_length": 128, "alphanum_fraction": 0.519266481, "num_tokens": 1774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605946, "lm_q2_score": 0.8757869965109764, "lm_q1q2_score": 0.8023168929779947}} {"text": "using Printf;\nusing Plots;\n\nfunction init()\n\t## 横の長さ\n\tglobal lx = 1.0;\n\t## 縦の長さ\n\tglobal ly = 1.0;\n\t## 横の分割数\n\tglobal nx = 11;\n\t## 縦の分割数\n\tglobal ny = 11;\n\tglobal dx = lx / (nx - 1);\n\tglobal dy = ly / (ny - 1);\n\t## 係数\n\tbeta_x = 1.0 / dx^2;\n\tbeta_y = 1.0 / dy^2;\n\tglobal x = range(0.0, stop=lx, length=nx);\n\tglobal y = range(0.0, stop=ly, length=ny);\n\tglobal u = zeros(Float64, (ny, nx));\n\t## 境界条件の適用\n\tu[:, begin] .= 0.0;\n\tu[:, end] = 100y;\n\tu[begin, :] .= 0.0;\n\tu[end, :] = 100x;\n\tglobal u_t = zeros(Float64, (ny, nx));\n\tfor j = 1:ny\n\t\tfor i = 1:nx\n\t\t\tu_t[j, i] = 100*x[i]*y[j];\n\t\tend\n\tend\n\tglobal pre_u = copy(u);\n\t## SOR法のωの値を決定\n\tmu = cos(pi/nx) + cos(pi/ny);\n\tglobal omega = 2.0/(1.0 + sqrt(1-(mu/2)^2));\n\tglobal epsilon = 2e-4;\n\tglobal a_ir = beta_x;\n\tglobal a_il = beta_x;\n\tglobal a_ia = beta_y;\n\tglobal a_ib = beta_y;\n\tglobal a_0 = -2.0(beta_x + beta_y);\n\tglobal rhs = 0.0;\n\tglobal iter_max = 100;\n\tglobal epsilon = 2e-4;\nend\n\nfunction main()\n\tinit();\n\tfor iter=1:iter_max\n\t\terr = 0.0;\n\t\tfor j = 1:ny-2\n\t\t\tfor i = 1:nx-2\n\t\t\t\ttmp = (rhs - a_ir*u[j+1, i+2] - a_il*u[j+1, i] - a_ia*u[j+2, i+1] - a_ib*u[j, i+1]) / a_0;\n\t\t\t\tu[j+1, i+1] = u[j+1, i+1] + (tmp - u[j+1, i+1])*omega;;\n\t\t\t\terr += sqrt((u_t[j+1, i+1] - u[j+1, i+1])^2)/(nx*ny);\n\t\t\tend\n\t\tend\n\t\terr = sqrt(sum((u - u_t).^2)/(nx*ny))\n\t\t#err = sqrt(sum((u - pre_u).^2)/(nx*ny)) global pre_u = copy(u);\n\t\t@printf(\"iter: %d, err: %5e\\n\", iter, err);\n\t\tif err < epsilon\n\t\t\tbreak;\n\t\tend\n\tend\n\tcontour(u);\n\tsavefig(\"Laplace.png\");\nend\n\nmain()\n", "meta": {"hexsha": "9e0407c541f8dbb07a8887e3b4d26f090add8622", "size": 1493, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "laplace.jl", "max_stars_repo_name": "Makoto523sys/laplace-equation", "max_stars_repo_head_hexsha": "a1abb57c3cdbf8691142e3df7f8dfa2a8feccf68", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "laplace.jl", "max_issues_repo_name": "Makoto523sys/laplace-equation", "max_issues_repo_head_hexsha": "a1abb57c3cdbf8691142e3df7f8dfa2a8feccf68", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "laplace.jl", "max_forks_repo_name": "Makoto523sys/laplace-equation", "max_forks_repo_head_hexsha": "a1abb57c3cdbf8691142e3df7f8dfa2a8feccf68", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.3285714286, "max_line_length": 94, "alphanum_fraction": 0.5472203617, "num_tokens": 684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425333801889, "lm_q2_score": 0.8723473779969194, "lm_q1q2_score": 0.8022477526886522}} {"text": "\n\"\"\"\n unitvector(v)\n\nNormalize input vector `v`.\n\"\"\"\nfunction unitvector(v)\n n = norm(v)\n if n > 0\n return v / n\n else\n # zero vector\n return v\n end\nend\n\n\n\"\"\"\n random_in_unit_disk()\n\nGenerate a uniformly random point within the unit disk.\n\"\"\"\nfunction random_in_unit_disk()\n while true\n p = 2*rand(2) .- 1\n if dot(p, p) < 1\n return p\n end\n end\nend\n\n\n\"\"\"\n random_in_unit_sphere()\n\nGenerate a uniformly random point within the unit sphere.\n\"\"\"\nfunction random_in_unit_sphere()\n while true\n p = 2*rand(3) .- 1\n if dot(p, p) < 1\n return p\n end\n end\nend\n", "meta": {"hexsha": "9254d3c4a9cf1ff8500874545b6dbc5dfa1c69c3", "size": 667, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/util.jl", "max_stars_repo_name": "cmendl/Raytracing.jl", "max_stars_repo_head_hexsha": "896bd19020940bb246804bc6b9546aba45180ec6", "max_stars_repo_licenses": ["MIT"], "max_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": "cmendl/Raytracing.jl", "max_issues_repo_head_hexsha": "896bd19020940bb246804bc6b9546aba45180ec6", "max_issues_repo_licenses": ["MIT"], "max_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": "cmendl/Raytracing.jl", "max_forks_repo_head_hexsha": "896bd19020940bb246804bc6b9546aba45180ec6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.5, "max_line_length": 57, "alphanum_fraction": 0.5517241379, "num_tokens": 187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.8723473829749844, "lm_q1q2_score": 0.8022477515029293}} {"text": "#=\nTakes one step in the Markov chain according to the given state's transition\nvector.\nInputs:\n- transition_vector: An array of length p where the ith element denotes the\n probability of transitioning into state i from the current\n state (which is implicitly given).\nOutputs:\n- An integer in {1,2,..., p} denoting the index of the next state which occurs\nwith the probability specified in transition_vector.\n=#\nfunction one_step(transition_vector)\n cumulative_vector = cumsum(transition_vector)\n state_index = 1\n U = rand()\n while(U > cumulative_vector[state_index])\n state_index += 1\n end\n\n return state_index\nend\n\n#=\nRuns a Markov chain a fixed number of times and returns the final state.\nInputs:\n- states: An array of length p where each element represents a state of the\n chain. Assumes the ordering is such that the probability of\n transitioning from state i to state j is given by P[i,j].\n Examples:\n [0,1,2,3,4,5]\n [\"red\", \"green\", \"blue\"]\n [0,\"blue\",3,2]\n- P: A (p x p) matrix denoting the transition matrix of the Markov chain.\n Assumes the rows of P sum to 1 and P[i,j] >= 0 for all i,j.\n- S0: The initial state of the Markov chain. Assumed to be an element of the\n state variable.\n- steps: A nonnegative integer specifying the number of steps for the Markov\n chain to go through.\nOutputs:\n- An element of the states variable denoting the state the chain is in after\n the specified number of steps.\n=#\nfunction run_fixed_simulation(states, P, S0, steps)\n\n # Define a dictionary mapping state to their index in P\n state_dict = Dict(states[i] => i for i = 1:length(states))\n\n # Define the current state of the chain\n Sn = S0\n\n # Run through the specified number of steps\n for i = 1:steps\n state_index = get(state_dict, Sn, -1)\n next_state_index = one_step(P[state_index,:])\n Sn = states[next_state_index]\n end\n\n return Sn\nend\n\n#=\nRuns a Markov chain until a state is reached.\nInputs:\n- states: Same as defined in ``run_fixed_simulation`` function\n- P: Same as defined in ``run_fixed_simulation`` function\n- S0: Same as defined in ``run_fixed_simulation`` function\n- Sf: An array of states defining a possible final state. Assumed to be a\n subset of the states variable.\nOutputs:\n- An integer representing the number of steps it took to get to get to state\n contained in the Sf array.\n=#\nfunction run_simulation(states, P, S0, Sf)\n\n # Define a dictionary mapping state to their index in P\n state_dict = Dict(states[i] => i for i = 1:length(states))\n\n # Define the current state of the chain\n Sn = S0\n\n # Keep tracks of number of steps taken\n steps = 0\n\n # Run through the Markov changing\n while !(Sn in Sf) && steps < 1000\n state_index = get(state_dict, Sn, -1)\n next_state_index = one_step(P[state_index,:])\n Sn = states[next_state_index]\n steps += 1\n end\n\n return steps\nend\n\n\n# Define gambler's ruin Markov chain with N = 5 and p = .3\n\n# gambler's ruin state space (χ)\nstates = [0,1,2,3,4,5]\n\n# Transition matrix for gambler's ruin\nP = [1 0 0 0 0 0;\n .7 0 .3 0 0 0;\n 0 .7 0 .3 0 0;\n 0 0 .7 0 .3 0;\n 0 0 0 .7 0 .3;\n 0 0 0 0 0 1]\n\n# Estimate probability of having $5 after 6 turns when starting with $2\nnum_simulations = 100000\nmc_est = mean([run_fixed_simulation(states, P, 2, 6) == 5\n for i = 1:num_simulations])\n\n# Define masters program Markov chain\nstates = [1,2,\"G\",\"D\"]\n\n# Transition matrix for masters Markov chain\nP = [.4 .5 0 .1;\n 0 .3 .6 .1;\n 0 0 1 0;\n 0 0 0 1]\n\nmc_est = mean([run_simulation(states, P, 1, [\"G\", \"D\"]) for i = 1:10000])\n", "meta": {"hexsha": "102c661345aab422f9f282cbefc24501dff1c27f", "size": 3730, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "content/stochastic-approximations/code/markov_chain_simulation.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/markov_chain_simulation.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/markov_chain_simulation.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": 30.0806451613, "max_line_length": 79, "alphanum_fraction": 0.6648793566, "num_tokens": 1047, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425289753969, "lm_q2_score": 0.8723473697001441, "lm_q1q2_score": 0.8022477412160761}} {"text": "################################################################################\n# loggingOptimisation Problem\n#\n# You are the decision-maker of a production unit (here a logging company) and have a set of possible activities to undergo.\n# How do you choose the activities that lead to a maximisation of the unit's profit? \n# The objective of this problem is hence to find the optimal level of activities to maximise the company profit, given (a) the profitability (gross margin) of each activity, (b) the resources available to the company and (c) the matrix of technical coefficients that link each activity to the resources required (positive coefficient) or provided (negative coefficient) by that specific activity.\n\n# The problem is the same as those in the SpreadSheet file \"Optimal production mix.ods\" (available in the `data` folder) and can be solved in LibreOffice by using the \"Solver tool\" as indicated in that file. You can use it to check your results.\n#\n#\n\n# ### Environment set-up and data loading\n\n# 1) Start by setting the working directory to the directory of this file and activate it. If you have the `Manifest.toml` file in the directory, just run `Pkg.instantiate()`, otherwise manually add the packages JuMP, GLPK, DataFrames, CSV, Pipe, HTTP.\n\n# 2) Load the packages DelimitedFiles, JuMP, GLPK, DataFrames, CSV, Pipe, HTTP\n\n# 3) Load from internet or from local files the following data:\n\nurlActivities = \"https://raw.githubusercontent.com/sylvaticus/IntroSPMLJuliaCourse/main/lessonsMaterial/02_JULIA2/loggingOptimisation/data/activities.csv\"\nurlResources = \"https://raw.githubusercontent.com/sylvaticus/IntroSPMLJuliaCourse/main/lessonsMaterial/02_JULIA2/loggingOptimisation/data/resources.csv\"\nurlCoefficients = \"https://raw.githubusercontent.com/sylvaticus/IntroSPMLJuliaCourse/main/lessonsMaterial/02_JULIA2/loggingOptimisation/data/coefficients.csv\"\n\n# The result must be:\n# - `activities`, a dataframe with the columns `label`, `gm` and `integer`\n# - `resources`, a dataframe with the columns `label`, `initial` and `initial2`\n# - `coeff`, a 10x12 Matrix of Float64\n\n# For example to download from internet and import the matrix you can use something like:\ncoef = @pipe HTTP.get(urlCoefficients).body |> readdlm(_,';')\n\n# 4) Determine `nA` and `nR` as the number of activities and the number of resources (use the `size` function)\n\n\n# ### Optimisation model definition\n\n# 5) Define `profitModel` as a model to be optimised using the `GLPK.Optimizer`\n# 6) [OPTIONAL] set `GLPK.GLP_MSG_ALL` as the `msg_lev` of GLPK\n\n# ### Model's endogenous variables definition\n\n# 7) Define the non-negative model `x` variable, indexed by the positions between 1 and `nA` (i.e. `x[1:nA] >= 0`) (you could use the @variables macro). Don't set the `x` variable to be integer at this step, as some variables are continuous, just set them to be non-negative.\n\n# 8) Set the variables for which the corresponding `integer` column in the `activity` dataframe is equal to 1 as a integer variable.\n# To set the specific vaciable `x[i]` as integer use `set_integer(x[i])`\n\n# ### Model's constraint definition\n\n# 9) Define the `resLimit[r in 1:nR]` family of contraints, such that when you sum `coef[r,a]*x[a]` for all the `1:nA` activities you must have a value not greater than `resources.initial[r]`\n\n# ### Objective definition\n\n# 10) Define the objective as the maximisation of the profit given by summing for each of the `1:nA` activities `activities.gm[a] * x[a]`\n\n# ### Model resolution\n# 11) [OPTIONAL] Print the model to check it\n# 12) Optimize the model\n# 13) Check with the function `status = termination_status(profitModel)` that the status is `OPTIMAL` (it should be!)\n\n# ### Print optimal level of activities\n\n# 14) Run the following code to print the results (optimal level of activities)\n\nif (status == MOI.OPTIMAL || status == MOI.LOCALLY_SOLVED || status == MOI.TIME_LIMIT) && has_values(profitModel)\n println(\"#################################################################\")\n if (status == MOI.OPTIMAL)\n println(\"** Problem solved correctly **\")\n else\n println(\"** Problem returned a (possibly suboptimal) solution **\")\n end\n println(\"- Objective value (total costs): \", objective_value(profitModel))\n println(\"- Optimal Activities:\\n\")\n optValues = value.(x)\n for a in 1:nA\n println(\"* $(activities.label[a]):\\t $(optValues[a])\")\n end\n if JuMP.has_duals(profitModel)\n println(\"\\n\\n- Shadow prices of the resources:\\n\")\n for r in 1:nR\n println(\"* $(resources.label[r]):\\t $(dual(resLimit[r]))\")\n end\n end\nelse\n println(\"The model was not solved correctly.\")\n println(status)\nend\n\n\n# 15) [OPTIONAL] Observe the emergence of scale effects\n# Optionally re-run the model with `initial2` initial resources (instead of `initial`) and notice how this larger company can afford to perform different types of activities (logging high forest instead of coppices in this example) and obtain a better profitability per unit of resource employed.\n# Can you guess which are the aspects of the optimisation model that allow for the emergence of these scale effects?\n", "meta": {"hexsha": "ef20fc4fa94376a39bb10250404e02434a98285d", "size": 5178, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lessonsMaterial/02_JULIA2/loggingOptimisation/loggingOptimisation.jl", "max_stars_repo_name": "sylvaticus/IntroSPMLJuliaCourse", "max_stars_repo_head_hexsha": "84ba4432548dcfe826353c03616c03e86f46e9eb", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-02-26T15:44:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T13:05:52.000Z", "max_issues_repo_path": "lessonsMaterial/02_JULIA2/loggingOptimisation/loggingOptimisation.jl", "max_issues_repo_name": "sylvaticus/IntroSPMLJuliaCourse", "max_issues_repo_head_hexsha": "84ba4432548dcfe826353c03616c03e86f46e9eb", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lessonsMaterial/02_JULIA2/loggingOptimisation/loggingOptimisation.jl", "max_forks_repo_name": "sylvaticus/IntroSPMLJuliaCourse", "max_forks_repo_head_hexsha": "84ba4432548dcfe826353c03616c03e86f46e9eb", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-26T08:06:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T08:06:40.000Z", "avg_line_length": 56.2826086957, "max_line_length": 396, "alphanum_fraction": 0.7168791039, "num_tokens": 1268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541577509315, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.8022449034904532}} {"text": "#\n#Simple example of a Poisson problem with a variable coefficient:\n#\n# y\n# |\n# | u_y = 0\n# Ly ----------------------------------\n# | |\n# | |\n# | |\n# u = 0 | -(au_x)_x - (au_y)_y = f | u = 0\n# | |\n# | |\n# | |\n# -----------------------------------|----- x\n# u_y = 0 Lx\n#\n#Here, \n#\n# u = sin(ωx x) * cos(ωy y) \n# a = exp(x-y)\n# f = ω exp(x-y) ( 2ω sin(ω x) cos(ω y) - cos ω(x-y) )\n# ωx = mπ / Lx\n# ωy = nπ / Ly\n#\n\nusing FinElt\nusing FinElt.PlanarPoisson\n\ninclude(\"params.jl\")\nconst ωx = pi / Lx\nconst ωy = pi / Ly\n\nfunction exact_u(x)\n return sin(ωx*x[1]) * cos(ωy*x[2])\nend\n\nfunction a(x)\n return exp(x[1]-x[2])\nend\n\nfunction f(x)\n return exp(x[1]-x[2]) * ( \n ωx * ( ωx * sin(ωx*x[1]) - cos(ωx*x[1]) ) * cos(ωy*x[2])\n + ωy * ( ωy * cos(ωy*x[2]) - sin(ωy*x[2]) ) * sin(ωx*x[1])\n )\nend\n\nell_f(v, z) = P1SourceTimesFunc!(v, z, f)\nlin_functionals = [ (\"Omega\", ell_f) ]\n\nmaxerr = zeros(refinements+1)\n@printf(\"%10s %12s %8s %8s\\n\\n\", \n \"N\", \"max error\", \"rate\", \"seconds\")\nfor k = 0:refinements\n start = time()\n mesh = read_msh_file(\"rect$k.msh\") \n vp = VariationalProblem(mesh, [\"Left\", \"Right\"])\n add_bilin_form!(vp, \"Omega\", grad_dot_grad!, a)\n add_lin_functnl!(vp, \"Omega\", source_times_func!, f)\n # Implicit zero boundary conditions.\n A, b = assembled_linear_system(vp)\n ufree = A \\ b\n uh = complete_soln(ufree, vp)\n u = get_nodal_vals(exact_u, mesh)\n finish = time()\n maxerr[k+1] = maximum(abs.(uh-u))\n N = length(ufree)\n if k == 0\n @printf(\"%10d %12.4e\\n\", N, maxerr[k+1])\n else\n rate = log2(maxerr[k]/maxerr[k+1])\n elapsed = finish - start\n @printf(\"%10d %12.4e %8.4f %8.4f\\n\", \n N, maxerr[k+1], rate, elapsed)\n end\nend\n\n", "meta": {"hexsha": "942c1c0c8c21cee6a576b0b7ba96d5ac9ef3c90d", "size": 2170, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/rectangle/var_coef.jl", "max_stars_repo_name": "billmclean/FinElt.jl", "max_stars_repo_head_hexsha": "5153f1624fe1c7dcadd646d60c716e6153fedb2a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2015-07-18T20:04:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T21:29:09.000Z", "max_issues_repo_path": "examples/rectangle/var_coef.jl", "max_issues_repo_name": "billmclean/FinElt.jl", "max_issues_repo_head_hexsha": "5153f1624fe1c7dcadd646d60c716e6153fedb2a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/rectangle/var_coef.jl", "max_forks_repo_name": "billmclean/FinElt.jl", "max_forks_repo_head_hexsha": "5153f1624fe1c7dcadd646d60c716e6153fedb2a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-06-29T15:15:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-04T18:01:08.000Z", "avg_line_length": 27.4683544304, "max_line_length": 69, "alphanum_fraction": 0.4156682028, "num_tokens": 715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541561135441, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.8022449020954764}} {"text": "using Random\nusing LinearAlgebra\n\n\n\"\"\"\nGenerate an N×N matrix with uniformly random entries in [0,1].\n\"\"\"\nfunction uniform_matrix(N)\n\treturn rand(N, N)\nend\n\n\"\"\"\nGenerate a random N×N matrix with entries satisfying the triangle inequality.\n\"\"\"\nfunction metric_matrix(N; dim=5, p=2)\n\tpoints = rand(N, dim)\n\tM = [norm(points[i,:] - points[j,:], p) for i in 1:N, j in 1:N]\n\treturn M\nend\n\n\"\"\"\nGenerate a random 0-1 N×N matrix with edge probability p.\n\"\"\"\nfunction zeroone_matrix(N; p=0.25, selfedges=true, symmetric=false)\n\tM = rand(N, N) .≤ p\n\tif symmetric\n\t\tM = triu(M) .| triu(M)'\n\tend\n\tif !selfedges\n\t\tfor i in 1:N\n\t\t\tM[i,i] = 0\n\t\tend\n\tend\n\treturn M\nend\n\n\"\"\"\nGenerate a pair of N×N matricies with known optimal permutation using\nAlgorithm 4 from \"Generating Quadratic Assignment Test Problems with\nKnown Optimal Permutations\" by Li and Pardalos.\n\"\"\"\nfunction generate_qap(N)\n\tD = Matrix(I, N, N)\n\tO = .~D\n\n\tΔA = rand(1:100)\n\tΔB = rand(1:100)\n\n\tA = fill(ΔA, N, N)\n\tA[D] .= 0\n\n\tB = Array{Int,2}(undef, N, N)\n\tfor i in 1:N, j in 1:N\n\t\tif i == j\n\t\t\tB[i,j] = 0\n\t\telse\n\t\t\tB[i,j] = rand(0:ΔB)\n\t\tend\n\tend\n\n\tR = findall(O)\n\tsort!(R, by=(ij -> B[ij]))\n\n\tX = rand(1:ΔA, N*(N-1))\n\tsort!(X, rev=true)\n\n\tfor (k, ij) in enumerate(R)\n\t\tA[ij] = A[ij] - X[k]\n\tend\n\n\tσ = randperm(N)\n\tσinv = invperm(σ)\n\tB = B[σinv,σinv]\n\n\treturn A, B, σ\nend\n", "meta": {"hexsha": "c63da5b50eea715abcad68df771727e678530396", "size": 1321, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/util/generators.jl", "max_stars_repo_name": "flixpar/QuadraticAssignmentProblem.jl-", "max_stars_repo_head_hexsha": "0d769a70bba87e00c41d0d0bb1cb2eeebb06c57c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-05-11T20:05:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T09:25:06.000Z", "max_issues_repo_path": "src/util/generators.jl", "max_issues_repo_name": "flixpar/QuadraticAssignmentProblem.jl-", "max_issues_repo_head_hexsha": "0d769a70bba87e00c41d0d0bb1cb2eeebb06c57c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-05-16T03:37:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T14:06:30.000Z", "max_forks_repo_path": "src/util/generators.jl", "max_forks_repo_name": "flixpar/QuadraticAssignmentProblem.jl", "max_forks_repo_head_hexsha": "0d769a70bba87e00c41d0d0bb1cb2eeebb06c57c", "max_forks_repo_licenses": ["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.1558441558, "max_line_length": 77, "alphanum_fraction": 0.6298258895, "num_tokens": 479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191309994467, "lm_q2_score": 0.8397339756938818, "lm_q1q2_score": 0.8022139319305895}} {"text": "using PyPlot\n\npospart(x) = ( x > 0 ? x : zero(x) )\n\nfunction K2(x, y, a, b)\n pt = [a, (a+b)/2, b]\n ℓ2 = (x-pt[1])*(x-pt[3])/((pt[2]-pt[1])*(pt[2]-pt[3]))\n ℓ3 = (x-pt[1])*(x-pt[2])/((pt[3]-pt[1])*(pt[3]-pt[2]))\n Qπ = pospart(pt[2]-y)^2 * ℓ2 / 2 + (b-y)^2 * ℓ3 / 2\n return Qπ - pospart(x-y)^2/2\nend\n\na = -1.0\nb = 1.0\nN = 200\nx = LinRange(a, b, N+1)\ny = LinRange(a, b, N+1)\nz = Float64[ K2(x[k], y[j], a, b) for j=1:N+1, k=1:N+1 ]\nfig = figure(1)\nsurf(x, y, z, cstride=4, rstride=4, cmap=\"jet\", linewidth=0.25)\nxlabel(L\"x\")\nylabel(L\"y\")\nax = gca()\nax[:view_init](elev=40,azim=-100)\nsavefig(\"Quadratic_PeanoK_3d.pdf\")\n\nfigure(2)\ncontour(x, y, z, 12)\ncolorbar()\nxlabel(L\"x\")\nylabel(L\"y\")\ngrid(true)\nsavefig(\"Quadratic_PeanoK_contour.pdf\")\n", "meta": {"hexsha": "825b68cb9b0f51ea64c89b87429258869aae6013", "size": 749, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chap2/PeanoK_quadratic.jl", "max_stars_repo_name": "billmclean/ComputationalMathsNotes", "max_stars_repo_head_hexsha": "9d521fdf7ec407cca287997885d81c3150973415", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-30T21:30:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T21:30:20.000Z", "max_issues_repo_path": "src/chap2/PeanoK_quadratic.jl", "max_issues_repo_name": "billmclean/ComputationalMathsNotes", "max_issues_repo_head_hexsha": "9d521fdf7ec407cca287997885d81c3150973415", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/chap2/PeanoK_quadratic.jl", "max_forks_repo_name": "billmclean/ComputationalMathsNotes", "max_forks_repo_head_hexsha": "9d521fdf7ec407cca287997885d81c3150973415", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0294117647, "max_line_length": 63, "alphanum_fraction": 0.5487316422, "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191322715435, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.8022139234197769}} {"text": "## sigmoidal functions\n\nexport logistic, logistic_prime, weibull, weibull_prime\n\nlogistic(x) = 1/(1 + exp(-x))\nlogistic_prime(x) = exp(-x)/(1 + exp(-x))^2\nweibull(x, coef, scale, shape) = (1 - exp(-((x/scale)^shape)))*coef\nweibull_prime(x, coef, scale, shape) = coef*(shape/scale)*((x/scale)^(shape-1))*exp(-((x/scale)^shape))\n", "meta": {"hexsha": "91c5b69e0f2bf3fb8f2228c2dfb81172d413f031", "size": 327, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions.jl", "max_stars_repo_name": "marketingattribution/SigmoidalProgramming.jl", "max_stars_repo_head_hexsha": "f8ad8908c841aa39522a5bfbeeae1b5ee4122b29", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2015-03-11T19:34:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-09T04:00:55.000Z", "max_issues_repo_path": "src/functions.jl", "max_issues_repo_name": "madeleineudell/SigmoidalProgramming.jl", "max_issues_repo_head_hexsha": "78359012088f1e14ee13dec3f06f5023d9a5c9ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2015-03-11T20:35:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-10T04:50:28.000Z", "max_forks_repo_path": "src/functions.jl", "max_forks_repo_name": "marketingattribution/SigmoidalProgramming.jl", "max_forks_repo_head_hexsha": "f8ad8908c841aa39522a5bfbeeae1b5ee4122b29", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2015-06-23T18:17:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-24T14:08:51.000Z", "avg_line_length": 36.3333333333, "max_line_length": 103, "alphanum_fraction": 0.6574923547, "num_tokens": 117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9811668657039606, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.8021769906476737}} {"text": "# ---\n# title: 633. Sum of Square Numbers\n# id: problem633\n# author: Indigo\n# date: 2021-06-27\n# difficulty: Medium\n# categories: Math\n# link: \n# hidden: true\n# ---\n# \n# Given a non-negative integer `c`, decide whether there're two integers `a` and\n# `b` such that `a2 + b2 = c`.\n# \n# \n# \n# **Example 1:**\n# \n# \n# \n# Input: c = 5\n# Output: true\n# Explanation: 1 * 1 + 2 * 2 = 5\n# \n# \n# **Example 2:**\n# \n# \n# \n# Input: c = 3\n# Output: false\n# \n# \n# **Example 3:**\n# \n# \n# \n# Input: c = 4\n# Output: true\n# \n# \n# **Example 4:**\n# \n# \n# \n# Input: c = 2\n# Output: true\n# \n# \n# **Example 5:**\n# \n# \n# \n# Input: c = 1\n# Output: true\n# \n# \n# \n# \n# **Constraints:**\n# \n# * `0 <= c <= 231 - 1`\n# \n# \n## @lc code=start\nusing LeetCode\n\nfunction judge_square_sum(n::Int)\n upper = isqrt(n)\n i = 0\n while i <= upper\n ss = i ^ 2 + upper ^ 2\n ss == n && return true\n ss > n ? (upper -= 1) : (i += 1)\n end\n return false\nend\n## @lc code=end\n", "meta": {"hexsha": "061bc61caacc31e2d8eef50c3c709165a28f49a4", "size": 1131, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/633.sum-of-square-numbers.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2020-10-27T18:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:27:49.000Z", "max_issues_repo_path": "src/problems/633.sum-of-square-numbers.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-01T07:26:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T11:57:53.000Z", "max_forks_repo_path": "src/problems/633.sum-of-square-numbers.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2020-10-30T11:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:35:11.000Z", "avg_line_length": 14.3164556962, "max_line_length": 80, "alphanum_fraction": 0.4668435013, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361700013356, "lm_q2_score": 0.8791467611766711, "lm_q1q2_score": 0.8021653036371207}} {"text": "\"\"\"\n lis(arr::Array{Int}, ::Val{:bs})\n\n# Arguments:\n- `arr`: sequence of integers\n\n# Examples/Tests \n```julia\njulia> lis([3, 10, 2, 1, 20], Val(:bs))\n[3, 10, 20]\n\njulia> lis([2, 2, 3], Val(:bs))\n[2, 3]\n```\n\n# Brief:\nGiven a sequence of integers, the function finds the longest, strictly increasing, subsequence in that sequence.\n\n# For more information:\nhttps://cp-algorithms.com/sequences/longest_increasing_subsequence.html\n\n# Contributed by:\n- [Igor Malheiros](https://github.com/igormalheiros)\n\"\"\"\n\nfunction lis(arr::Array{Int}, ::Val{:bs})\n len = length(arr)\n memo = ones(Int, len)\n p = ones(Int, len)\n\n lis_arr = Int[]\n\n len == 0 && return lis_arr # if `arr` is empty\n\n lis_len = 1\n memo[1] = arr[1]\n\n for i = 2:len\n # binary search in current `memo`, it uses @view and slicing for in-place verification\n p[i] = searchsortedfirst((@view memo[1:lis_len]), arr[i])\n # if arr[i] is greater than the greatest element in `memo`, it increases `lis_len`\n lis_len = max(lis_len, p[i])\n # updates `memo`\n memo[p[i]] = arr[i]\n end\n\n # Restoring\n last_pos = lis_len\n for i = len:-1:1\n if p[i] == last_pos\n push!(lis_arr, arr[i])\n last_pos -= 1\n end\n end\n\n reverse!(lis_arr)\n\n return lis_arr\nend\n", "meta": {"hexsha": "e6c83046d9ae8ef2ab091f4d47c772936a7ebdff", "size": 1316, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/longest_increasing_subsequence/binary_search.jl", "max_stars_repo_name": "Whiteshark-314/Julia", "max_stars_repo_head_hexsha": "3285d8d6b7585cc1075831c2c210b891151da0c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-10-14T21:48:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-14T21:48:50.000Z", "max_issues_repo_path": "src/longest_increasing_subsequence/binary_search.jl", "max_issues_repo_name": "AugustoCL/Julia", "max_issues_repo_head_hexsha": "1bf4e4a7829fafc64290d903bcbfdd48eab839e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/longest_increasing_subsequence/binary_search.jl", "max_forks_repo_name": "AugustoCL/Julia", "max_forks_repo_head_hexsha": "1bf4e4a7829fafc64290d903bcbfdd48eab839e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.9333333333, "max_line_length": 112, "alphanum_fraction": 0.5965045593, "num_tokens": 404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361700013356, "lm_q2_score": 0.8791467595934565, "lm_q1q2_score": 0.8021653021925383}} {"text": "module JacobiAlgorithm\n\n struct EquilibriumProblem{T<:Real}\n nbz::Int64 \n e_z::Function \n pmin::T \n pmax::T\n q_z::Vector{T}\n p0_z::Vector{T}\n function EquilibriumProblem(nbz::Int64,e_z::Function,pmin::T,pmax::T,q_z::Vector{T},p0_z::Vector{T}) where {T<:Real}\n this = new{T}(nbz,e_z,pmin,pmax,q_z,p0_z) #,NaN,[],[],[],NaN)\n end\n end\n\n function bisection(f::Function, a::T, b::T;\n tol::T=1e-5, maxiter::Int64=100) where T<:Real\n fa = f(a)\n fa*f(b) <= 0 || error(\"No real root in [a,b]\")\n i = 0\n local c\n while b-a > tol\n i += 1\n i != maxiter || error(\"Max iteration exceeded\")\n c = (a+b)/2\n fc = f(c)\n if fc == 0\n break\n elseif fa*fc > 0\n a = c # Root is in the right half of [a,b].\n fa = fc\n else\n b = c # Root is in the left half of [a,b].\n end\n end\n return c\n end\n\n function coordinate_update(problem::EquilibriumProblem{T}, z::Int64, price_z::Vector{T}) where T<:Real\n old_price = price_z[z]\n f(p) = problem.e_z(setindex!(price_z,p,z))[z] - problem.q_z[z]\n new_price = bisection(f, problem.pmin, problem.pmax,tol=1e-5,maxiter=1000)\n price_z[z] = old_price\n return new_price, new_price - old_price\n end\n\n function fJ_z(problem::EquilibriumProblem{T}, p_z::Vector{T}) where T<:Real\n nbz = size(p_z,1)\n pp_z = zeros(T, nbz)\n diffp_z = zeros(T, nbz)\n for z = 1:nbz\n pp_z[z], diffp_z[z] = coordinate_update(problem,z,p_z)\n end\n return pp_z, diffp_z\n end\n\n function fJ_threaded_z(problem::EquilibriumProblem{T}, p_z::Vector{T}) where T<:Real\n nbz = size(p_z,1)\n pp_z = zeros(T, nbz)\n diffp_z = zeros(T, nbz)\n Threads.@threads for z = 1:nbz\n p_z_safe = deepcopy(p_z)\n pp_z[z], diffp_z[z] = coordinate_update(problem,z,p_z_safe)\n end\n return pp_z, diffp_z\n end\n\n function solve(problem::EquilibriumProblem{T}; \n maxit::Int64 = 10_000,\n method::Symbol = :jacobian,\n valtol::T = 1e-5,\n steptol::T = 1e-9,\n output::Int64 = 0) where T<:Real\n\n code = 0\n start_time = time()\n delta_z = zeros(T,problem.nbz)\n diffp_z = zeros(T,problem.nbz)\n iterations = 0\n p_z = deepcopy(problem.p0_z)\n if method != :jacobian\n error(\"Method not implemented\")\n end\n for i = 1:maxit\n p_z, diffp_z = fJ_z(problem, p_z)\n delta_z = problem.e_z(p_z) .- problem.q_z'\n if output>1\n println(\"p = $p_z\")\n end\n if maximum(abs.(delta_z)) < valtol\n code = 0\n iterations = i\n break\n end\n if maximum(abs.(diffp_z)) < steptol\n code = 1\n iterations = i\n break\n end\n code = 2\n end\n comp_time = time() - start_time\n if output > 0\n println(\"$(String(method)) method converged in $iterations iterations.\")\n println(\"Value of p = $(p_z)\")\n println(\"Value of p' - p = $(diffp_z)\")\n println(\"Value of e(p)-q = $(delta_z)\")\n println(\"Time elapsed: $comp_time\")\n println(\"Code: $code\")\n end\n return code\n end\n\n function solve_threaded(problem::EquilibriumProblem{T}; \n maxit::Int64 = 10_000,\n method::Symbol = :jacobian,\n valtol::T = 1e-5,\n steptol::T = 1e-9,\n output::Int64 = 0) where T<:Real\n\n code = 0\n start_time = time()\n delta_z = zeros(T,problem.nbz)\n diffp_z = zeros(T,problem.nbz)\n iterations = 0\n p_z = deepcopy(problem.p0_z)\n if method != :jacobian\n error(\"Method not implemented\")\n end\n for i = 1:maxit\n p_z, diffp_z = fJ_threaded_z(problem, p_z)\n delta_z = problem.e_z(p_z) .- problem.q_z'\n if output>1\n println(\"p = $p_z\")\n end\n if maximum(abs.(delta_z)) < valtol\n code = 0\n iterations = i\n break\n end\n if maximum(abs.(diffp_z)) < steptol\n code = 1\n iterations = i\n break\n end\n code = 2\n end\n comp_time = time() - start_time\n if output > 0\n println(\"$(String(method)) method converged in $iterations iterations.\")\n println(\"Value of p = $(p_z)\")\n println(\"Value of p' - p = $(diffp_z)\")\n println(\"Value of e(p)-q = $(delta_z)\")\n println(\"Time elapsed: $comp_time\")\n println(\"Code: $code\")\n end\n return code\n end\nend", "meta": {"hexsha": "ea7bdd7a216e9507fef1e530c8c6fe2c5a84968f", "size": 4986, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "day_1/src/JacobiAlgorithm.jl", "max_stars_repo_name": "jmboehm/mec_equil_solutions", "max_stars_repo_head_hexsha": "41ec6f9034305e3025e3ad1ea1f460a22b75dbbf", "max_stars_repo_licenses": ["BSD-Source-Code"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-21T23:15:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-21T23:15:47.000Z", "max_issues_repo_path": "day_1/src/JacobiAlgorithm.jl", "max_issues_repo_name": "jmboehm/mec_equil_solutions", "max_issues_repo_head_hexsha": "41ec6f9034305e3025e3ad1ea1f460a22b75dbbf", "max_issues_repo_licenses": ["BSD-Source-Code"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "day_1/src/JacobiAlgorithm.jl", "max_forks_repo_name": "jmboehm/mec_equil_solutions", "max_forks_repo_head_hexsha": "41ec6f9034305e3025e3ad1ea1f460a22b75dbbf", "max_forks_repo_licenses": ["BSD-Source-Code"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5569620253, "max_line_length": 125, "alphanum_fraction": 0.4937825913, "num_tokens": 1386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107949104866, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.8021129337742369}} {"text": "# this is a little Monte Carlo exercise that illustrates that\n# the OLS estimator is biased and inconsistent when errors are\n# correlated with regressors, but that the IV estimator is consistent\nusing Econometrics, Plots, LinearAlgebra\nfunction main()\nreps = 1000 # number of Monte Carlo reps.\nbetaols = zeros(reps,2)\nbetaiv = zeros(reps,2)\nn = 1000 # sample size\n\n# covariance of X, W, e\ncor_X_W = 0.2 # experiment with lowering or raising this: quality of instrument\ncor_X_e = 0.5 # try setting this to zero to observe inefficiency of IV\nsig = [\n 1.0 cor_X_W cor_X_e;\n cor_X_W 1.0 0.0;\n cor_X_e 0.0 1.0]\ntruebeta = [1, 2] # true beta\np = cholesky(sig).U\nfor i = 1:reps\n\tXWE = randn(n,3)*p\n\te = XWE[:,3:3]\n\tw = [ones(n) XWE[:,2:2]]\n\tx = [ones(n) XWE[:,1:1]]\n\ty = x*truebeta + e\n\t# OLS\n\tbetaols[i,:] = (x\\y)'\n\t# IV\n\tbetaiv[i,:] = (inv(w'*x)*w'*y)'\nend\n\np1 = npdensity(betaols[:,2])\nplot!(p1,title=\"OLS\")\np2 = npdensity(betaiv[:,2])\nplot!(p2,title=\"IV\")\np = plot(p1,p2,layout=(2,1))\n#savefig(\"olsiv.png\")\ngui()\nprintln(\"true betas are \", truebeta)\nprintln(\"OLS results\")\ndstats(betaols, short=true)\nprintln(\"IV results\")\ndstats(betaiv, short=true)\nreturn p\nend\nmain()\n", "meta": {"hexsha": "0caa9907bc82d6941bc2df1d9f4eb7b847a3b0de", "size": 1214, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/GMM/Hausman/OLSvsIV.jl", "max_stars_repo_name": "mcreel/EconometricsNotes", "max_stars_repo_head_hexsha": "93b3f042ace7c4d3059b333fd9dc3d2c794f0a52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-19T18:23:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T18:23:45.000Z", "max_issues_repo_path": "Examples/GMM/Hausman/OLSvsIV.jl", "max_issues_repo_name": "mcreel/EconometricsNotes", "max_issues_repo_head_hexsha": "93b3f042ace7c4d3059b333fd9dc3d2c794f0a52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Examples/GMM/Hausman/OLSvsIV.jl", "max_forks_repo_name": "mcreel/EconometricsNotes", "max_forks_repo_head_hexsha": "93b3f042ace7c4d3059b333fd9dc3d2c794f0a52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.829787234, "max_line_length": 80, "alphanum_fraction": 0.6540362438, "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107949104866, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.8021129337742369}} {"text": "\nusing OrdinaryDiffEq\nusing DiffEqCallbacks\nusing GlobalSensitivity\nusing Distributions\nusing Plots\n\n\nfunction sir_ode!(du,u,p,t)\n (S,I,R) = u\n (β,c,γ) = p\n N = S+I+R\n @inbounds begin\n du[1] = -β*c*I/N*S\n du[2] = β*c*I/N*S - γ*I\n du[3] = γ*I\n end\n nothing\nend;\n\n\ntmax = 10000.0\ntspan = (0.0,tmax);\n\n\ncb_ss = TerminateSteadyState();\n\n\nN = 1000.0;\nu0 = [990.0,10.0,0.0];\np = [0.05,10.0,0.25]; # β,c,γ\n\n\nn_samples = 1000 # Number of samples\n# Parameters are β, c, γ, I₀\nlb = [0.01, 5.0, 0.1, 1.0]\nub = [0.1, 20.0, 1.0, 50.0]\nn_params = 4;\n\n\nprob_ode = ODEProblem(sir_ode!,u0,tspan,p);\n\n\nf1 = function(pu0)\n p = pu0[1:3]\n I0 = pu0[4]\n u0 = [N-I0,I0,0.0]\n prob = remake(prob_ode;p=p,u=u0)\n sol = solve(prob, ROS34PW3(),callback=cb_ss)\n [maximum(sol[2,:]), sol.t[argmax(sol[2,:])], sol[end][3]]\nend;\n\n\nm_morris = gsa(f1, Morris(num_trajectory=n_samples), [[lb[i],ub[i]] for i in 1:n_params]);\n\n\nm_morris.means\n\n\nm_morris.variances\n\n\nm_sobol = gsa(f1, Sobol(), [[lb[i],ub[i]] for i in 1:n_params],N=n_samples);\n\n\nm_sobol.ST\n\n\nm_sobol.S1\n\n\nm_regression = gsa(f1, RegressionGSA(rank=true), [[lb[i],ub[i]] for i in 1:n_params]; samples = n_samples);\n\n\nm_regression.partial_correlation\n\n\nm_regression.partial_rank_correlation\n\n\nm_efast = gsa(f1, eFAST(), [[lb[i],ub[i]] for i in 1:n_params]; n = n_samples);\n\n\nm_efast.ST\n\n\nm_efast.S1\n\n\npf1 = function (pu0)\n p = pu0[1:3,:]\n I0 = pu0[4,:]\n prob_func(prob,i,repeat) = remake(prob;p=p[:,i],u=[N-I0[i],I0[i],0.0])\n ensemble_prob = EnsembleProblem(prob_ode,prob_func=prob_func)\n sol = solve(ensemble_prob,ROS34PW3(),EnsembleThreads();trajectories=size(p,2))\n out = zeros(3,size(p,2))\n for i in 1:size(p,2)\n out[1,i] = maximum(sol[i][2,:])\n out[2,i] = sol[i].t[argmax(sol[i][2,:])]\n out[3,i] = sol[i][end][3]\n end\n out\nend;\n\n\nm_efast_parallel = gsa(pf1, eFAST(), [[lb[i],ub[i]] for i in 1:n_params]; n = n_samples, batch = true);\n\n", "meta": {"hexsha": "e2bd650c58ae56726dd65dbb1f5741049971909b", "size": 1927, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/ode_global_sensitivity2/ode_global_sensitivity2.jl", "max_stars_repo_name": "Song921012/sir-julia", "max_stars_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "script/ode_global_sensitivity2/ode_global_sensitivity2.jl", "max_issues_repo_name": "Song921012/sir-julia", "max_issues_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/ode_global_sensitivity2/ode_global_sensitivity2.jl", "max_forks_repo_name": "Song921012/sir-julia", "max_forks_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.8425925926, "max_line_length": 107, "alphanum_fraction": 0.6170212766, "num_tokens": 766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107931567176, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.8021129288274181}} {"text": "# # [Time integration](@id Time-integration)\n\n# Time integration methods for the numerical solution of Ordinary Differential\n# Equations (ODEs), also called timesteppers, can be of different nature and\n# flavor (e.g., explicit, semi-implicit, single-stage, multi-stage, single-step,\n# multi-step, single-rate, multi-rate, etc). ClimateMachine supports several\n# of them. Before showing the different nature of some of these methods, let us\n# introduce some common notation.\n\n# A commonly used notation for Initial Value Problems (IVPs) is:\n\n# ```math\n# \\begin{align}\n# \\frac{\\mathrm{d} \\boldsymbol{q}}{ \\mathrm{d} t} &= \\mathcal{T}(t, \\boldsymbol{q}),\\\\\n# \\boldsymbol{q}(t_0) &= \\boldsymbol{q_0},\n# \\end{align}\n# ```\n\n# where ``\\boldsymbol{q}`` is an unknown function (vector in most of our cases)\n# of time ``t``, which we would like to approximate, and at the initial time ``t_0``\n# the corresponding initial value ``\\boldsymbol{q}_0`` is given.\n\n# The given general formulation, is suitable for single-step explicit schemes.\n# Generally, the equation can be represented in the following canonical form:\n\n# ```math\n# \\begin{align}\n# \\dot {\\boldsymbol{q}} + \\mathcal{F}(t, \\boldsymbol{q}) &= \\mathcal{G}(t, \\boldsymbol{q}),\n# \\end{align}\n# ```\n\n# where we have used ``\\dot {\\boldsymbol{q}} = d \\boldsymbol{q} / dt``.\n# We refer to the term ``\\mathcal{G}``\n# as the right-hand-side (RHS) or explicit term, and to the spatial terms of\n# ``\\mathcal{F}`` as the left-hand-side (LHS) or implicit term.\n", "meta": {"hexsha": "52c29a5479ea536c096e6e4748999cc2eeba1170", "size": 1511, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "tutorials/Numerics/TimeStepping/ts_intro.jl", "max_stars_repo_name": "ErikQQY/ClimateMachine.jl", "max_stars_repo_head_hexsha": "ad128d457dd877bf21b5bcd845d6c3fa42de3f8a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 256, "max_stars_repo_stars_event_min_datetime": "2020-05-06T08:03:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T14:01:20.000Z", "max_issues_repo_path": "tutorials/Numerics/TimeStepping/ts_intro.jl", "max_issues_repo_name": "ErikQQY/ClimateMachine.jl", "max_issues_repo_head_hexsha": "ad128d457dd877bf21b5bcd845d6c3fa42de3f8a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1174, "max_issues_repo_issues_event_min_datetime": "2020-05-06T16:19:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-25T17:51:13.000Z", "max_forks_repo_path": "tutorials/Numerics/TimeStepping/ts_intro.jl", "max_forks_repo_name": "ErikQQY/ClimateMachine.jl", "max_forks_repo_head_hexsha": "ad128d457dd877bf21b5bcd845d6c3fa42de3f8a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 45, "max_forks_repo_forks_event_min_datetime": "2020-05-08T02:28:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T22:44:56.000Z", "avg_line_length": 41.9722222222, "max_line_length": 96, "alphanum_fraction": 0.6935804103, "num_tokens": 433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107896491796, "lm_q2_score": 0.8558511414521922, "lm_q1q2_score": 0.8021129241025607}} {"text": "\"\"\"\n logistic2_bidir(u₀, c_xy, c_yx, r₁, r₂, σ_xy, σ_yx)\n\nEquations of motion for a bidirectional logistic model for the chaotic \npopulation dynamics of two interacting species. This system is from [1], \nand is given by \n\n```math\n\\\\begin{align}\nx(t+1) &= r_1 f_{yx}^{t}(1 - f_{yx}^{t}) \\\\\ny(t+1) &= r_2 f_{xy}^{t}(1 - f_{xy}^{t}) \\\\\nf_{xy}^t &= \\\\dfrac{y(t) + c_{xy}(x(t) + \\\\sigma_{xy} \\\\xi_{xy}^t )}{1 + c_{xy} (1 + \\\\sigma_{xy} )} \\\\ \nf_{yx}^t &= \\\\dfrac{x(t) + c_{yx}(y(t) + \\\\sigma_{yx} \\\\xi_{yx}^t )}{1 + c_{yx} (1 + \\\\sigma_{yx} )},\n\\\\end{align}\n```\n\nwhere the coupling strength ``c_{xy}`` controls how strongly species ``x`` influences species \n``y``, and vice versa for ``c_{yx}``. To simulate time-varying influence of unobserved \nprocesses, we use the dynamical noise terms ``\\\\xi_{xy}^t`` and ``\\\\xi_{yx}^t``, drawn from a \nuniform distribution with support on ``[0, 1]``. If ``\\\\sigma_{xy} > 0``, then the influence \nof ``x`` on ``y`` is masked by dynamical noise equivalent to ``\\\\sigma_{xy} \\\\xi_{xy}^{t}`` at \nthe ``t``-th iteration of the map, and vice versa for ``\\\\sigma_{yx}``.\n\n## References \n\n1. Diego, David, Kristian Agasøster Haaga, and Bjarte Hannisdal. \"Transfer entropy computation \n using the Perron-Frobenius operator.\" Physical Review E 99.4 (2019): 042212.\n\"\"\"\nfunction eom_logistic2_bidir(dx, x, p, n)\n \n # c_xy is the coupling from x to y\n # c_yx is the coupling from y to x\n # σ_yx is the dynamical noise from y to x\n # σ_xy is the dynamical noise from y to x\n c_xy, c_yx, r₁, r₂, σ_xy, σ_yx = (p...,)\n \n ξ₁ = rand() # random number from flat distribution on [0, 1]\n ξ₂ = rand() # random number from flat distribution on [0, 1]\n x, y = x[1], x[2]\n \n f_xy = (y + c_xy*(x + σ_xy*ξ₁) ) / (1 + c_xy*(1+σ_xy))\n f_yx = (x + c_yx*(y + σ_yx*ξ₂) ) / (1 + c_yx*(1+σ_yx))\n\n dx[1] = r₁ * (f_yx) * (1 - f_yx)\n dx[2] = r₂ * (f_xy) * (1 - f_xy)\n return\nend\n\nfunction logistic2_bidir(u₀, c_xy, c_yx, r₁, r₂, σ_xy, σ_yx)\n p = [c_xy, c_yx, r₁, r₂, σ_xy, σ_yx]\n DiscreteDynamicalSystem(eom_logistic2_bidir, u₀, p)\nend\n\n\"\"\"\n logistic2_bidir(;u₀ = rand(2), c_xy = 0.1, c_yx = 0.1, \n r₁ = 3.78, r₂ = 3.66, σ_xy = 0.05, σ_yx = 0.05)\n\nA bidirectional logistic model for the chaotic population dynamics of two interacting \nspecies [1].\n\n## Equations of motion \n\nThe equations of motion are \n\n```math\n\\\\begin{align}\nx(t+1) &= r_1 f_{yx}^{t}(1 - f_{yx}^{t}) \\\\\\\\\ny(t+1) &= r_2 f_{xy}^{t}(1 - f_{xy}^{t}) \\\\\\\\\nf_{xy}^t &= \\\\dfrac{y(t) + c_{xy}(x(t) + \\\\sigma_{xy} \\\\xi_{xy}^t )}{1 + c_{xy} (1 + \\\\sigma_{xy} )} \\\\\\\\ \nf_{yx}^t &= \\\\dfrac{x(t) + c_{yx}(y(t) + \\\\sigma_{yx} \\\\xi_{yx}^t )}{1 + c_{yx} (1 + \\\\sigma_{yx} )},\n\\\\end{align}\n```\n\nwhere the coupling strength ``c_{xy}`` controls how strongly species ``x`` influences species \n``y``, and vice versa for ``c_{yx}``. To simulate time-varying influence of unobserved \nprocesses, we use the dynamical noise terms ``\\\\xi_{xy}^t`` and ``\\\\xi_{yx}^t``, drawn from a \nuniform distribution with support on ``[0, 1]``. If ``\\\\sigma_{xy} > 0``, then the influence \nof ``x`` on ``y`` is masked by dynamical noise equivalent to ``\\\\sigma_{xy} \\\\xi_{xy}^{t}`` at \nthe ``t``-th iteration of the map, and vice versa for ``\\\\sigma_{yx}``.\n\n## References \n\n1. Diego, David, Kristian Agasøster Haaga, and Bjarte Hannisdal. \"Transfer entropy computation \n using the Perron-Frobenius operator.\" Physical Review E 99.4 (2019): 042212.\n\"\"\"\nlogistic2_bidir(;u₀ = rand(2), c_xy = 0.1, c_yx = 0.1, \n r₁ = 3.78, r₂ = 3.66, σ_xy = 0.05, σ_yx = 0.05) =\n logistic2_bidir(u₀, c_xy, c_yx, r₁, r₂, σ_xy, σ_yx)\n", "meta": {"hexsha": "6992e14e0b16a653f5017e5dfee1e5205bdb3639", "size": 3620, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/systems/discretemaps/logistic2_bidir.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/CausalityTools.jl-5520caf5-2dd7-5c5d-bfcb-a00e56ac49f7", "max_stars_repo_head_hexsha": "93935b3bc73738c52b004e9cf23d6f6a4778982c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2020-06-11T01:51:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T18:39:43.000Z", "max_issues_repo_path": "src/systems/discretemaps/logistic2_bidir.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/CausalityTools.jl-5520caf5-2dd7-5c5d-bfcb-a00e56ac49f7", "max_issues_repo_head_hexsha": "93935b3bc73738c52b004e9cf23d6f6a4778982c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2020-12-21T02:52:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-31T10:40:08.000Z", "max_forks_repo_path": "src/systems/discretemaps/logistic2_bidir.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/CausalityTools.jl-5520caf5-2dd7-5c5d-bfcb-a00e56ac49f7", "max_forks_repo_head_hexsha": "93935b3bc73738c52b004e9cf23d6f6a4778982c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2020-09-27T08:56:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-08T15:05:51.000Z", "avg_line_length": 40.6741573034, "max_line_length": 106, "alphanum_fraction": 0.6099447514, "num_tokens": 1387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107843878722, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.8021129230455185}} {"text": "# coding: utf-8\n\n\n# In[1]: \n\n#coin change is a straight forward dynamic programming problem\n#you are given one note and a set of coins of different values\n#assuming you have infinite supply of coins of different values\n#we need to compute different ways of making change\n#the order of the coins doesnt matter in this case\n#more details can be found in the following link\n# https://www.geeksforgeeks.org/coin-change-dp-7/\n#the script can also be done in recursion\n# https://github.com/je-suis-tm/recursion-and-dynamic-programming/blob/master/coin%20change%20recursion.jl\n\n\n# In[2]: \n\n\n#to solve this problem via tabulation\n#we divide one big problem into two sub problems\n#the case where coin of η value is excluded in the solutions\n#and the case where at least one coin of η value is included\nfunction coin_change(num,choice)\n \n #create matrix (num+1)*length(choice)\n #the raison d'être is the computation starts from 0 to num\n #0 is when num is perfectly substituted by coins\n tabulation=[[0 for _ in 1:length(choice)] for _ in 1:num+1]\n \n #initialize\n #when the remain value happens to be η\n #one solution is found\n for i in 1:length(choice)\n\n tabulation[1][i]=1\n\n end\n \n #since we initialize the null case\n #the outerloop starts from 2\n #i actually refers to i-1\n for i in 2:num+1\n\n for j in 1:length(choice)\n \n #annoying part of julia\n #if index starts at zero\n #will be a lot easier\n if i-choice[j]>=1\n\n #the case where at least one coin of η value is included\n #we just need the computation where η is deducted\n include=tabulation[i-choice[j]][j]\n \n else\n\n include=0\n\n end\n \n #the case where coin of η value is excluded in the solutions\n if j>=2\n\n exclude=tabulation[i][j-1]\n\n else\n\n exclude=0\n\n end\n \n #two sub problems merge into a big one\n tabulation[i][j]=exclude+include \n\n end\n\n end\n \n #get the final answer\n return tabulation[num+1][length(choice)]\n \nend\n\n\n# In[3]: \n\n\ncoin_change(10,[1,2,5])\n", "meta": {"hexsha": "26681ea9a283a3a95ca0da2293e9b27979107d3c", "size": 2279, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "coin change dynamic programming.jl", "max_stars_repo_name": "je-suis-tm/recursion-and-dynamic-programming", "max_stars_repo_head_hexsha": "55a6085cd45b73426379ff947d9a842ef7d325bb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2019-03-22T10:31:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T13:30:17.000Z", "max_issues_repo_path": "coin change dynamic programming.jl", "max_issues_repo_name": "slowbrain/recursion-and-dynamic-programming", "max_issues_repo_head_hexsha": "1cd77db1e7940fee15fc8aa2cedd3ab84e10374f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "coin change dynamic programming.jl", "max_forks_repo_name": "slowbrain/recursion-and-dynamic-programming", "max_forks_repo_head_hexsha": "1cd77db1e7940fee15fc8aa2cedd3ab84e10374f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2019-10-27T12:34:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T13:54:37.000Z", "avg_line_length": 25.3222222222, "max_line_length": 106, "alphanum_fraction": 0.6138657306, "num_tokens": 561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794595, "lm_q2_score": 0.8840392893839085, "lm_q1q2_score": 0.8020996580679275}} {"text": "#=\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.\nFind the sum of all the multiples of 3 or 5 below 1000.\n=#\n\nfunction calc()\n filter(x -> x % 3 == 0 || x % 5 == 0, 1:999) |> sum |> println\nend\n@time calc()\n\n", "meta": {"hexsha": "1756763ebe18cd8a78382efd6f3a7cc0d05858f0", "size": 292, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p1.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/p1.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/p1.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 26.5454545455, "max_line_length": 129, "alphanum_fraction": 0.6404109589, "num_tokens": 104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9481545289551958, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.8020841568520523}} {"text": "# fitting noisy data to an exponential model\nmodel(xpts, p) = p[1]*exp(-xpts.*p[2])\n\n# some example data\nsrand(12345)\nxpts = linspace(0,10,20)\ndata = model(xpts, [1.0 2.0]) + 0.01*randn(length(xpts))\n\nbeta, r, J = curve_fit(model, xpts, data, [0.5, 0.5])\n@assert norm(beta - [1.0, 2.0]) < 0.05\n\n# can also get error estimates on the fit parameters\nerrors = estimate_errors(beta, r, J)\n@assert norm(errors - [0.016, 0.075]) < 0.01\n", "meta": {"hexsha": "5c23601d2ce4d20812423aad82eb594cb88c0cc0", "size": 430, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/curve_fit.jl", "max_stars_repo_name": "aviks/Optim.jl", "max_stars_repo_head_hexsha": "9c2a9a88c5b9329ad4233760a6e5331fd6d771e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-05-22T09:32:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-22T09:32:32.000Z", "max_issues_repo_path": "test/curve_fit.jl", "max_issues_repo_name": "aviks/Optim.jl", "max_issues_repo_head_hexsha": "9c2a9a88c5b9329ad4233760a6e5331fd6d771e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/curve_fit.jl", "max_forks_repo_name": "aviks/Optim.jl", "max_forks_repo_head_hexsha": "9c2a9a88c5b9329ad4233760a6e5331fd6d771e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6666666667, "max_line_length": 56, "alphanum_fraction": 0.6581395349, "num_tokens": 166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9481545304202039, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.80208415072619}} {"text": "### A Pluto.jl notebook ###\n# v0.12.20\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ ec794b0c-67b1-11eb-23e7-459641028308\nbegin\n\tusing Markdown\n\tusing InteractiveUtils\n\tusing Test\n\tusing LinearAlgebra\nend\n\n# ╔═╡ 47f1758c-67b1-11eb-0a89-27d2595e5912\nmd\"\"\"\n\n## Task \\# 8\n\nCompute the norms and condition numbers\n\n#### Norm\n\n```math\n||A||^2 = max \\frac{||Ax||^2}{||x||^2} = max \\frac{ x^T A^T A x }{ x^T x } = \\lambda_{max}(A^T A) = \\sigma^{2}_{max}\n```\n\n```math\n||A|| = \\sqrt{\\sigma^{2}_{max}} = \\sigma_{max}\n```\n\n```math\n||A^{-1}|| = \\frac{1}{\\sigma_{min}}\n```\n\n\"\"\"\n\n# ╔═╡ 9aa05ff6-67b5-11eb-0b36-95986372b105\nfunction normCalculator(A::Array{Int})\n\tAᵀA = A' * A\n\t\n\tA_eigenvals, A_eigenvec = eigen(AᵀA)\n\t\n\tA_normFromEigenSquared = √max(A_eigenvals...)\n\t\n\tA_norm = opnorm(A)\n\t\n\treturn (A_normFromEigenSquared, A_norm)\nend\n\n# ╔═╡ 4533fdcc-67b3-11eb-30f8-851ef7fc43c9\nbegin\n\tA₁ = [\n\t\t1 7\n\t\t1 1\n\t]\n\t\n\tA₁normFromEigenSquared, A₁norm = normCalculator(A₁)\n\t\n\t@test round.(A₁normFromEigenSquared, digits=5) == round.(A₁norm, digits=5)\n\t\n\tA₁normFromEigenSquared, A₁norm, cond(A₁)\nend\n\n# ╔═╡ bf65578a-67b8-11eb-2627-9139089fcf68\nmd\"\"\"\n#### Cond is Inf, because of `` || A_2^{-1} || = \\sigma_{min} = 0 ``\n\"\"\"\n\n# ╔═╡ 1c2ed1ac-67b5-11eb-1e77-67e96dbd2802\nbegin\n\tA₂ = [\n\t\t1 1\n\t\t0 0\n\t]\n\t\n\tA₂normFromEigenSquared, A₂norm = normCalculator(A₂)\n\t\n\t@test round.(A₂normFromEigenSquared, digits=5) == round.(A₂norm, digits=5)\n\t\n\tA₂normFromEigenSquared, A₂norm, cond(A₂)\nend\n\n# ╔═╡ 1568a204-67b9-11eb-3d55-d72928803e5e\nmd\"\"\"\n#### Cond is 1, because of `` || A_2 || = || A_2^{-1} || ``\n\"\"\"\n\n# ╔═╡ ed7d86f6-67b3-11eb-273c-43770e6f299c\nbegin\n\tA₃ = [\n\t\t1 1\n\t\t-1 1\n\t]\n\t\n\tA₃normFromEigenSquared, A₃norm = normCalculator(A₃)\n\t\n\t@test round.(A₃normFromEigenSquared, digits=5) == round.(A₃norm, digits=5)\n\t\n\tA₃normFromEigenSquared, A₃norm, cond(A₃)\nend\n\n# ╔═╡ c3dc9efe-67bd-11eb-0224-af9d70653b73\nmd\"\"\"\n### Task \\# 13\nEstimate the condition number\n\"\"\"\n\n# ╔═╡ e21e095c-67bd-11eb-12e4-e92b18b0b223\nbegin\n\tA₄ = [\n\t\t1 1\n\t\t1 1.0001\n\t]\n\tcond(A₄)\nend\n\n# ╔═╡ 67060602-67c2-11eb-046e-dfc437a3dc81\nmd\"\"\"\n### Task \\#17\nFibonacci matrix and the SVD\n\"\"\"\n\n# ╔═╡ 832167be-67c2-11eb-1693-ab8ea1a74995\nbegin\n\tF = [\n\t\t1 1\n\t\t1 0\n\t]\n\tsvd(F)\nend\n\n# ╔═╡ 8d7f475a-67c3-11eb-243b-53c5d68004f1\nmd\"\"\"\n### Task \\#18\n\"\"\"\n\n# ╔═╡ 9a4b6df6-67c3-11eb-27d6-2546dd023fb4\nbegin\n\tK = [\n\t\t1 2\n\t\t2 5\n\t]\n\tlu(K)\nend\n\n# ╔═╡ Cell order:\n# ╠═ec794b0c-67b1-11eb-23e7-459641028308\n# ╟─47f1758c-67b1-11eb-0a89-27d2595e5912\n# ╠═9aa05ff6-67b5-11eb-0b36-95986372b105\n# ╠═4533fdcc-67b3-11eb-30f8-851ef7fc43c9\n# ╟─bf65578a-67b8-11eb-2627-9139089fcf68\n# ╠═1c2ed1ac-67b5-11eb-1e77-67e96dbd2802\n# ╟─1568a204-67b9-11eb-3d55-d72928803e5e\n# ╠═ed7d86f6-67b3-11eb-273c-43770e6f299c\n# ╟─c3dc9efe-67bd-11eb-0224-af9d70653b73\n# ╠═e21e095c-67bd-11eb-12e4-e92b18b0b223\n# ╟─67060602-67c2-11eb-046e-dfc437a3dc81\n# ╠═832167be-67c2-11eb-1693-ab8ea1a74995\n# ╟─8d7f475a-67c3-11eb-243b-53c5d68004f1\n# ╠═9a4b6df6-67c3-11eb-27d6-2546dd023fb4\n", "meta": {"hexsha": "2a73991f2b5cfa4bc2a13d013969269747caf10c", "size": 2936, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "1.AppliedLInearAlgebra/7.NumericalLinearAlgebra/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/7.NumericalLinearAlgebra/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/7.NumericalLinearAlgebra/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": 18.1234567901, "max_line_length": 116, "alphanum_fraction": 0.6692779292, "num_tokens": 1506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9458012732322216, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.8020089837167037}} {"text": "# plots the contours of the OLS objective function,\n# with the true and estimated coefficients\n# generate data\nusing Plots, Econometrics\nn = 20\nx = [ones(n) randn(n)]\nbeta = randn(2)\ny = x*beta+randn(n)\n# ols estimate and objective function\nbetahat = x\\y\ns = (a,b)-> (1/n)*sum((y - x*[a,b]).^2)\n# plot the contours and the points\ncloseall()\nb1 = range(-4.0,stop=4.0,length=100)\nb2 = range(-4.0,stop=4.0,length=100)\np = contour(b1,b2,(b1,b2)->s(b1,b2),fill=true, c=:viridis)\nscatter!([beta[1]],[beta[2]], markersize=10, label=\"true\")\nscatter!([betahat[1]],[betahat[2]], markersize=10, label=\"estimated\")\n# do OLS by simulated annealing, and plot the path\nlb = -4*ones(2,1)\nub = -lb\nthetastart = fill(-3.0, 2, 1)\nobj = theta-> (1/n)*sum((y - x*theta).^2)[1,1]\nresults = samin(obj, thetastart, lb, ub, verbosity=2)\npath = results[4]\nplot!(path[:,4], path[:,5])\n", "meta": {"hexsha": "d85cbffaf490dc1f92f122afe7c37341b1fa137e", "size": 858, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Examples/NonlinearOptimization/OLSviaSA.jl", "max_stars_repo_name": "Hiroakiyusheng/Econometrics", "max_stars_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 209, "max_stars_repo_stars_event_min_datetime": "2016-02-12T16:41:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T21:18:55.000Z", "max_issues_repo_path": "Examples/NonlinearOptimization/OLSviaSA.jl", "max_issues_repo_name": "Hiroakiyusheng/Econometrics", "max_issues_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2019-09-10T12:45:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-05T07:22:46.000Z", "max_forks_repo_path": "Examples/NonlinearOptimization/OLSviaSA.jl", "max_forks_repo_name": "Hiroakiyusheng/Econometrics", "max_forks_repo_head_hexsha": "450505ed569379b7da8d23823a55538ddaddf16c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 104, "max_forks_repo_forks_event_min_datetime": "2015-12-12T23:46:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T10:10:27.000Z", "avg_line_length": 31.7777777778, "max_line_length": 69, "alphanum_fraction": 0.6585081585, "num_tokens": 324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102524151827, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.8019238977067367}} {"text": "using Plots; pyplot()\r\nusing DeSolver\r\nusing LinearAlgebra\r\nusing LaTeXStrings\r\n\r\n# Number of collocation points \r\nN = 50\r\nh= pi/N\r\n\r\n# create function\r\nfunction f(u,t)\r\n du = zeros(length(u))\r\n for i in 1:length(u)\r\n if i ==1\r\n du[1] = (-2u[1] + 2u[2])/h^2\r\n elseif i == length(u)\r\n du[length(u)] = (2u[length(u)-1] - 2u[length(u)])/h^2\r\n else\r\n du[i] = (u[i-1] - 2u[i] + u[i+1])/h^2\r\n end\r\n end\r\n return du\r\nend\r\n\r\nxs=range(0, stop=pi, length=N)\r\nu0=sin.(xs)\r\n\r\nsoltest1=odesolve(f, u0, (0.,10.), 1, method=\"RK4\")\r\nsoltest2=odesolve(f, u0, (0.,10.), .1, method=\"RK4\")\r\nsoltest3=odesolve(f, u0, (0.,10.), .01, method=\"RK4\")\r\n\r\n", "meta": {"hexsha": "192a3eb5cc3ef87635a798a9e16c6dfb55d0f4ae", "size": 701, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/examplepde.jl", "max_stars_repo_name": "hjk971/DeSolver", "max_stars_repo_head_hexsha": "fb81ff1392ab472d9c1766e0a9c238f0215804e8", "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/examplepde.jl", "max_issues_repo_name": "hjk971/DeSolver", "max_issues_repo_head_hexsha": "fb81ff1392ab472d9c1766e0a9c238f0215804e8", "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/examplepde.jl", "max_forks_repo_name": "hjk971/DeSolver", "max_forks_repo_head_hexsha": "fb81ff1392ab472d9c1766e0a9c238f0215804e8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.90625, "max_line_length": 66, "alphanum_fraction": 0.5249643367, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9525741308615412, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.801901328597417}} {"text": "# By default, Julia/LLVM does not use fused multiply-add operations (FMAs).\n# Since these FMAs can increase the performance of many numerical algorithms,\n# we need to opt-in explicitly.\n# See https://ranocha.de/blog/Optimizing_EC_Trixi for further details.\n@muladd begin\n\n\n\"\"\"\n ln_mean(x, y)\n\nCompute the logarithmic mean\n\n ln_mean(x, y) = (y - x) / (log(y) - log(x)) = (y - x) / log(y / x)\n\nProblem: The formula above has a removable singularity at `x == y`. Thus,\nsome care must be taken to implement it correctly without problems or loss\nof accuracy when `x ≈ y`. Here, we use the approach proposed by\nIsmail and Roe (2009).\nSet ξ = y / x. Then, we have\n\n (y - x) / log(y / x) = (x + y) / log(ξ) * (ξ - 1) / (ξ + 1)\n\nSet f = (ξ - 1) / (ξ + 1) = (y - x) / (x + y). Then, we use the expansion\n\n log(ξ) = 2 * f * (1 + f^2 / 3 + f^4 / 5 + f^6 / 7) + O(ξ^9)\n\nInserting the first few terms of this expansion yields\n\n (y - x) / log(ξ) ≈ (x + y) * f / (2 * f * (1 + f^2 / 3 + f^4 / 5 + f^6 / 7))\n = (x + y) / (2 + 2/3 * f^2 + 2/5 * f^4 + 2/7 * f^6)\n\nSince divisions are usually more expensive on modern hardware than\nmultiplications (Agner Fog), we try to avoid computing two divisions. Thus,\nwe use\n\n f^2 = (y - x)^2 / (x + y)^2\n = (x * (x - 2 * y) + y * y) / (x * (x + 2 * y) + y * y)\n\nGiven ε = 1.0e-4, we use the following algorithm.\n\n if f^2 < ε\n # use the expansion above\n else\n # use the direct formula (y - x) / log(y / x)\n end\n\n# References\n- Ismail, Roe (2009).\n Affordable, entropy-consistent Euler flux functions II: Entropy production at shocks.\n [DOI: 10.1016/j.jcp.2009.04.021](https://doi.org/10.1016/j.jcp.2009.04.021)\n- Agner Fog.\n Lists of instruction latencies, throughputs and micro-operation breakdowns\n for Intel, AMD, and VIA CPUs.\n https://www.agner.org/optimize/instruction_tables.pdf\n\"\"\"\n@inline function ln_mean(x, y)\n epsilon_f2 = 1.0e-4\n f2 = (x * (x - 2 * y) + y * y) / (x * (x + 2 * y) + y * y) # f2 = f^2\n if f2 < epsilon_f2\n return (x + y) / @evalpoly(f2, 2, 2/3, 2/5, 2/7)\n else\n return (y - x) / log(y / x)\n end\nend\n\n\"\"\"\n inv_ln_mean(x, y)\n\nCompute the inverse `1 / ln_mean(x, y)` of the logarithmic mean\n[`ln_mean`](@ref).\n\nThis function may be used to increase performance where the inverse of the\nlogarithmic mean is needed, by replacing a (slow) division by a (fast)\nmultiplication.\n\"\"\"\n@inline function inv_ln_mean(x, y)\n epsilon_f2 = 1.0e-4\n f2 = (x * (x - 2 * y) + y * y) / (x * (x + 2 * y) + y * y) # f2 = f^2\n if f2 < epsilon_f2\n return @evalpoly(f2, 2, 2/3, 2/5, 2/7) / (x + y)\n else\n return log(y / x) / (y - x)\n end\nend\n\n\n\n# `Base.max` and `Base.min` perform additional checks for signed zeros and `NaN`s\n# which are not present in comparable functions in Fortran/C++. For example,\n# ```julia\n# julia> @code_native debuginfo=:none syntax=:intel max(1.0, 2.0)\n# .text\n# vmovq rcx, xmm1\n# vmovq rax, xmm0\n# vcmpordsd xmm2, xmm0, xmm0\n# vblendvpd xmm2, xmm0, xmm1, xmm2\n# vcmpordsd xmm3, xmm1, xmm1\n# vblendvpd xmm3, xmm1, xmm0, xmm3\n# vmovapd xmm4, xmm2\n# test rcx, rcx\n# jns L45\n# vmovapd xmm4, xmm3\n# L45:\n# test rax, rax\n# js L54\n# vmovapd xmm4, xmm3\n# L54:\n# vcmpltsd xmm0, xmm0, xmm1\n# vblendvpd xmm0, xmm4, xmm2, xmm0\n# ret\n# nop word ptr cs:[rax + rax]\n#\n# julia> @code_native debuginfo=:none syntax=:intel min(1.0, 2.0)\n# .text\n# vmovq rcx, xmm1\n# vmovq rax, xmm0\n# vcmpordsd xmm2, xmm0, xmm0\n# vblendvpd xmm2, xmm0, xmm1, xmm2\n# vcmpordsd xmm3, xmm1, xmm1\n# vblendvpd xmm3, xmm1, xmm0, xmm3\n# vmovapd xmm4, xmm2\n# test rcx, rcx\n# jns L58\n# test rax, rax\n# js L67\n# L46:\n# vcmpltsd xmm0, xmm1, xmm0\n# vblendvpd xmm0, xmm4, xmm2, xmm0\n# ret\n# L58:\n# vmovapd xmm4, xmm3\n# test rax, rax\n# jns L46\n# L67:\n# vmovapd xmm4, xmm3\n# vcmpltsd xmm0, xmm1, xmm0\n# vblendvpd xmm0, xmm4, xmm2, xmm0\n# ret\n# nop word ptr cs:[rax + rax]\n# nop dword ptr [rax]\n# ```\n# In contrast, we get the much simpler and faster version\n# ```julia\n# julia> @code_native debuginfo=:none syntax=:intel Base.FastMath.max_fast(1.0, 2.0)\n# .text\n# vmaxsd xmm0, xmm1, xmm0\n# ret\n# nop word ptr cs:[rax + rax]\n#\n# julia> @code_native debuginfo=:none syntax=:intel Base.FastMath.min_fast(1.0, 2.0)\n# .text\n# vminsd xmm0, xmm0, xmm1\n# ret\n# nop word ptr cs:[rax + rax]\n# ```\n# when using `@fastmath`, which we also get from\n# [Fortran](https://godbolt.org/z/Yrsa1js7P)\n# or [C++](https://godbolt.org/z/674G7Pccv).\n\"\"\"\n max(x, y, ...)\n\nReturn the maximum of the arguments. See also the `maximum` function to take\nthe maximum element from a collection.\n\nThis version in Trixi.jl is semantically equivalent to `Base.max` but may\nbe implemented differently. In particular, it may avoid potentially expensive\nchecks necessary in the presence of `NaN`s (or signed zeros).\n\n# Examples\n\njulia> max(2, 5, 1)\n5\n\"\"\"\n@inline max(args...) = @fastmath max(args...)\n\n\"\"\"\n min(x, y, ...)\n\nReturn the minimum of the arguments. See also the `minimum` function to take\nthe minimum element from a collection.\n\nThis version in Trixi.jl is semantically equivalent to `Base.min` but may\nbe implemented differently. In particular, it may avoid potentially expensive\nchecks necessary in the presence of `NaN`s (or signed zeros).\n\n# Examples\n\njulia> min(2, 5, 1)\n1\n\"\"\"\n@inline min(args...) = @fastmath min(args...)\n\n\n\n\nend # @muladd\n", "meta": {"hexsha": "47b78ee3f647fb455a9a48f91b67df5d8b744a0f", "size": 5871, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/auxiliary/math.jl", "max_stars_repo_name": "panalluri/Trixi.jl", "max_stars_repo_head_hexsha": "faab9964204923c1a21b55ebf788c8a37aa01e90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 234, "max_stars_repo_stars_event_min_datetime": "2020-08-27T14:16:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T17:15:12.000Z", "max_issues_repo_path": "src/auxiliary/math.jl", "max_issues_repo_name": "panalluri/Trixi.jl", "max_issues_repo_head_hexsha": "faab9964204923c1a21b55ebf788c8a37aa01e90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 863, "max_issues_repo_issues_event_min_datetime": "2020-08-19T07:04:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T09:36:14.000Z", "max_forks_repo_path": "src/auxiliary/math.jl", "max_forks_repo_name": "panalluri/Trixi.jl", "max_forks_repo_head_hexsha": "faab9964204923c1a21b55ebf788c8a37aa01e90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 53, "max_forks_repo_forks_event_min_datetime": "2020-08-19T06:24:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:01:31.000Z", "avg_line_length": 29.8020304569, "max_line_length": 87, "alphanum_fraction": 0.5821836144, "num_tokens": 2053, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741254760638, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.8019013278439174}} {"text": "#Algorithm 12.2\n#Heat equation with backwards-difference\n#Boundary conditions u(0, t) = u(l, t) = 0, 0 < t < T\n\nusing Printf\n\nfunction heatbd(f, L, T, α, m, N)\n\tw = zeros(Float64, m)\n\tl = zeros(Float64, m)\n\tu = zeros(Float64, m)\n\tz = zeros(Float64, m)\n\th = L/m\n\tk = T/N\n\tλ = k*α^2/h^2\n\tfor i ∈ 1:(m - 1)\n\t\tw[i] = f(i * h)\n\tend\n\tl[1] = 1 + 2λ\n\tu[1] = -λ/l[1]\n\tfor i ∈ 2:(m - 2)\n\t\tl[i] = 1 + 2λ + λ*u[i - 1]\n\t\tu[i] = -λ/l[i]\n\tend\n\tl[m - 1] = 1 + 2λ + λ*u[m - 2]\n\tfor j ∈ 1:N\n\t\tt = j*k\n\t\tz[1] = w[1] / l[1]\n\t\tfor i ∈ 2:(m - 1)\n\t\t\tz[i] = (w[i] + λ*z[i - 1])/l[i]\n\t\tend\n\t\tw[m - 1] = z[m - 1]\n\t\tfor i ∈ (m - 2):1\n\t\t\tw[i] = z[i][t] - u[i]w[i+1]\n\t\tend\n\t\tfor i ∈ 1:(m - 1)\n\t\t\tx = i*h\n\t\t\tprintln(x, w[i])\n\t\t\tx = i * h\n\t\t\t@printf(\"%3d %11.8f %14.8f\\n\", i, x, w[i])\n\t\tend\n\tend\nend\n\nfunction distrib(x)\n\treturn sin(π*x)\nend\n\nheatbd(distrib, 1, 10, 0.5, 100, 100)\n", "meta": {"hexsha": "9bf82d40d090f33c79fea7469224f694559d8d5e", "size": 850, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "chapter12/heatbackdiff.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": "chapter12/heatbackdiff.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": "chapter12/heatbackdiff.jl", "max_forks_repo_name": "Matt8898/julia-numerical", "max_forks_repo_head_hexsha": "ad9ec5ab109aaacbdce9c3ec88adc5446f65419e", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.3469387755, "max_line_length": 53, "alphanum_fraction": 0.4717647059, "num_tokens": 432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620539235895, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.8018653936239779}} {"text": "# ---\n# title: 172. Factorial Trailing Zeroes\n# id: problem172\n# author: zhwang\n# date: 2022-03-25\n# difficulty: Easy\n# categories: Math\n# link: \n# hidden: true\n# ---\n# \n# Given an integer `n`, return _the number of trailing zeroes in`n!`_.\n# \n# **Follow up:** Could you write a solution that works in logarithmic time\n# complexity?\n# \n# \n# \n# **Example 1:**\n# \n# \n# \n# Input: n = 3\n# Output: 0\n# Explanation: 3! = 6, no trailing zero.\n# \n# \n# **Example 2:**\n# \n# \n# \n# Input: n = 5\n# Output: 1\n# Explanation: 5! = 120, one trailing zero.\n# \n# \n# **Example 3:**\n# \n# \n# \n# Input: n = 0\n# Output: 0\n# \n# \n# \n# \n# **Constraints:**\n# \n# * `1 <= n <= 104`\n# \n# \n## @lc code=start\nusing LeetCode\n\n## simulate Mathematica's function NestWhileList\nfunction nest_while_list(f::Function, val::T, chk::Function)::Vector{T} where T\n res = [val]\n while chk(val)\n val = f(val)\n push!(res, val)\n end\n res\nend\n\ntrailing_zeroes(n::Int) = sum(nest_while_list(i->i÷5, n÷5, >(1)))\n## equivalent to the following\n## function trailing_zeroes(n::Int)::Int\n## res = 0\n## while n >=5\n## n ÷= 5\n## res += n\n## end\n## res\n## end\n\n## @lc code=end\n\n## @lc test=start\n@testset \"172.factorial-trailing-zeroes.jl\" begin\n @test all(trailing_zeroes(i) == 0 for i in 0:4)\n @test trailing_zeroes(5) == 1\n @test trailing_zeroes(1999) == 496\n @test trailing_zeroes(2000) == trailing_zeroes(2001) == 499\nend\n## @lc test=end\n\n## @lc info=start\n# link: [solution to 172]()\n## @lc info=end", "meta": {"hexsha": "8300fb399b42b188d3eaae08366ff5f01a56a352", "size": 1660, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problems/submited/date-04/04-01/172.factorial-trailing-zeroes.jl", "max_stars_repo_name": "RexWzh/leetcode_note.jl", "max_stars_repo_head_hexsha": "eae55703e771485d5eff37010f34967694a4158b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/problems/submited/date-04/04-01/172.factorial-trailing-zeroes.jl", "max_issues_repo_name": "RexWzh/leetcode_note.jl", "max_issues_repo_head_hexsha": "eae55703e771485d5eff37010f34967694a4158b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/problems/submited/date-04/04-01/172.factorial-trailing-zeroes.jl", "max_forks_repo_name": "RexWzh/leetcode_note.jl", "max_forks_repo_head_hexsha": "eae55703e771485d5eff37010f34967694a4158b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.6516853933, "max_line_length": 79, "alphanum_fraction": 0.5704819277, "num_tokens": 568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213853793452, "lm_q2_score": 0.8918110454379297, "lm_q1q2_score": 0.8018463826707535}} {"text": "\"\"\"\n pinv_M, rnull_optional, lnull_optional = pinv_qr(M::AbstractArray)\n\nComputes Moore-Penrose pseudoinverse of `M` using a rank-revealing QR\nfactorization and optionally returns an orthonormal basis for right\nand left null-space. This can be significantly faster than using\nSVD for computing the pseudoinverse. Moreover, `A` can be sparse or\ndense.\n\n# Examples\n```julia-repl\njulia> pinv_qr([3 8 17; 2 1 4; 8 3 21])\n([-0.10344827586206914 1.344827586206895 -0.17241379310344793;0.1149425287356321 0.8390804597701144 -0.2528735632183907;0.022988505747126506 -0.6321839080459762 0.1494252873563217], Matrix{Float64}(undef, 3, 0), Matrix{Float64}(undef, 3, 0))\n```\n\"\"\"\nfunction pinv_qr(M::AbstractArray{T}) where {T}\n m = size(M, 1)\n n = size(M, 2)\n \n F = qr(M)\n Q = F.Q*I # so Q is allways m x m, with Matrix(F.Q) we get a m x n Matrix for m >= n\n R = Matrix(F.R)\n\n # compute rank \n abs_diag_R = abs.(diag(R))\n tol = 100 * minimum(size(M)) * maximum(abs_diag_R) * eps(T) # MAGIC CONSTANT\n rnk = sum(tol .< abs_diag_R)\n\n # compute pseudoinverse\n M_pinv = Matrix{T}(undef, n, m)\n\n S = R[1:rnk, 1:rnk] \\ R[1:rnk, rnk+1:end]\n W = R[1:rnk, 1:rnk] \\ Q[:, 1:rnk]'\n X = (S' * S + I) \\ (S' * W) \n M_pinv[rnk+1:end, :] = X\n M_pinv[1:rnk, :] = W - S*X\n\n # computing null spaces\n right_null_size = n - rnk\n left_null_size = m - rnk\n\n # right null space \n if right_null_size > 0\n rnull, = qr(Matrix([S; -I(right_null_size)]))\n rnull = Matrix(rnull)\n else\n rnull = zeros(T, n, 0)\n end\n\n # left null space\n if left_null_size > 0\n lnull = Q[: ,end - (left_null_size - 1): end]\n else\n lnull = zeros(T, m, 0)\n end\n\n return M_pinv, rnull, lnull\nend\n\n\nfunction pinv_qr(M::AbstractArray{<:Int})\n pinv_qr(float(M))\nend", "meta": {"hexsha": "a5a090550267eef9b1a957f3f2bb9a3067bcd07f", "size": 1826, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math_functions.jl", "max_stars_repo_name": "Matt1h/SSA.jl", "max_stars_repo_head_hexsha": "c7cc678e287f14c2d24561442bdd7439b6f9502c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-03-29T09:47:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T12:02:56.000Z", "max_issues_repo_path": "src/math_functions.jl", "max_issues_repo_name": "Matt1h/SSA.jl", "max_issues_repo_head_hexsha": "c7cc678e287f14c2d24561442bdd7439b6f9502c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-03-25T15:21:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T17:20:56.000Z", "max_forks_repo_path": "src/math_functions.jl", "max_forks_repo_name": "Matt1h/SSA.jl", "max_forks_repo_head_hexsha": "c7cc678e287f14c2d24561442bdd7439b6f9502c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9841269841, "max_line_length": 241, "alphanum_fraction": 0.6276013143, "num_tokens": 671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248140158416, "lm_q2_score": 0.853912747375134, "lm_q1q2_score": 0.8018452587896915}} {"text": "using ImplicitGraphs, Permutations\n\n\n\"\"\"\n iTransposition(n::Int, adjacent::Bool=true)\n\nCreate an `ImplicitGraph` whose vertices are all permutations of `1:n`\nin which two vertices are adjacent if they differ by a transpostion.\n\n* If `adjacent` is true, then only consider transpositions of the form `(a,a+1)`\n* Otherwise, consider all possible transpositions of the form `(a,b)` where `1≤a 0 \"Require n>0, got n=$n\"\n\n vcheck(v::Permutation) = length(v) == n\n\n function outs(v::Permutation)\n if adjacent\n return [v * Transposition(n, i, i + 1) for i = 1:n-1]\n end\n return [v * Transposition(n, i, j) for i = 1:n for j = 1:n if i ≠ j]\n end\n\n return ImplicitGraph{Permutation}(vcheck, outs)\nend\n\n\"\"\"\n trans_string(p::Permutation)\n\nWe assume that `p` is a transposition. \n\"\"\"\nfunction trans_string(p::Permutation)::String\n n = length(p)\n FP = fixed_points(p)\n @assert n == length(FP) + 2 \"Permutation must be a transposition\"\n elts = sort(setdiff(1:n, FP))\n a, b = elts\n return \"($a,$b)\"\nend\n\n\"\"\"\n pscore(p::Permutation)::Int\n\nMeasures the extent to which `p` is different from the identity permutation \nusing this formula:\n\n`sum(abs(p[k]-k) for k=1:length(p))`\n\"\"\"\nfunction pscore(p::Permutation)::Int\n n = length(p)\n sum(abs(i - p(i)) for i = 1:n)\nend\n\n\"\"\"\n crazy_trans_product(p::Permutation, adjacent::Bool=true)::String\n\nExpress `p` as the product of transpositions. With `adjacent=true` the transpositions \nare all of the form `(a,a+1)`; otherwise, all possible transpositions are allowed.\n\nResult is expressed as a `String`.\n\"\"\"\nfunction crazy_trans_product(p::Permutation, adjacent::Bool = true)::String\n n = length(p)\n G = iTransposition(n, adjacent)\n P = reverse(guided_path_finder(G, p, Permutation(n), score = pscore))\n\n nP = length(P)\n\n if nP == 1\n return \"()\"\n end\n\n Q = [P[k]' * P[k+1] for k = 1:nP-1]\n\n prod(trans_string(Q[j]) for j = 1:length(Q))\nend\n", "meta": {"hexsha": "aa5eef8b5e0685ce0844382ec0e96718056cc403", "size": 2056, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "extras/iTransposition.jl", "max_stars_repo_name": "scheinerman/ImplicitGraphs.jl", "max_stars_repo_head_hexsha": "0cc9c163b88c13c99c1c636589dd1209e63310e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-02-03T22:09:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-10T00:31:06.000Z", "max_issues_repo_path": "extras/iTransposition.jl", "max_issues_repo_name": "scheinerman/ImplicitGraphs.jl", "max_issues_repo_head_hexsha": "0cc9c163b88c13c99c1c636589dd1209e63310e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "extras/iTransposition.jl", "max_forks_repo_name": "scheinerman/ImplicitGraphs.jl", "max_forks_repo_head_hexsha": "0cc9c163b88c13c99c1c636589dd1209e63310e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.358974359, "max_line_length": 86, "alphanum_fraction": 0.6498054475, "num_tokens": 600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248140158416, "lm_q2_score": 0.8539127455162773, "lm_q1q2_score": 0.801845257044179}} {"text": "#=\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\nfunction calc()\n fibs = [1, 1]\n while fibs[end] <= 4_000_000\n push!(fibs, fibs[end] + fibs[end-1])\n end\n filter(x -> iseven(x) && x < 4_000_000, fibs) |> sum |> println\nend\n@time calc()\n", "meta": {"hexsha": "9acda99dba340d5dd9d63010371c233edbe74e8b", "size": 513, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p2.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/p2.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/p2.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 30.1764705882, "max_line_length": 140, "alphanum_fraction": 0.6744639376, "num_tokens": 172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572777987970316, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.8018349908478194}} {"text": "# some utility functions\nconst Γ = gamma\n\n\nfunction generalized_binomial(α::T, n::S) where {T,S <: Integer}\n R = Base.promote_op(/,T,S)\n out = one(R)\n for i in n:-1:1\n out *= α/i\n α -= 1\n end\n out\nend\n\n## memoized version of the above\n@memoize function generalized_binomial′(a, k::Int)\n k < 0 && return NaN * one(a)\n k == 0 && return one(a)/1\n generalized_binomial′(a,k-1) * (a-k+1)/k\nend\n\n\n\n## x⁽ⁱ⁾ is falling (x)⋅(x-1)⋯(x-n+1)\nfunction Pochhammer(::Val{:falling}, z::T,n::Int) where {T}\n iszero(n) && return one(T) \n out = z\n for i in 1:n-1\n z -= 1\n out *= z\n end\n out\nend\n\n## (x)ᵢ is rising (x)⋅(x+1)⋯(x+n-1) = Γ(z+n)/Γ(z)\nfunction Pochhammer(::Val{:rising}, z::T,n::Int) where {T}\n iszero(n) && return one(T)\n out = z\n for i in 1:n-1\n z += 1\n out *= z\n end\n out\nend\n# default is (x)ᵢ\nPochhammer(z,n::Int) = Pochhammer(Val(:rising), z, n)\n\n\n# (x)_n/n!\nPochhammer_factorial(z, n) = Pochhammer_factorial(Val(:rising), z, n)\n\nfunction Pochhammer_factorial(::Val{:rising}, z, n)\n iszero(n) && return one(z)/1\n prod((z+i)/(n-i) for i in 0:n-1)\nend\n\n## Alternative to HypergeometricFunctions.jl so that\n## variables can be inserted into the numerator\n\"\"\"\n pFq(as, bs, z; [maxevals=1000])\n\nCompute the generalized [hypergeometric](https://en.wikipedia.org/wiki/Generalized_hypergeometric_function) function. The `HypergeometricFunction.jl` package would normally be used for such calculations, but this one accepts polynomial values for the `as` and `z` values.\n\n# Example\n\nFrom [mathworld](https://mathworld.wolfram.com/HypergeometricFunction.html)\n\n```jldoctest\njulia> using Polynomials, SpecialPolynomials\n\njulia> import SpecialPolynomials: pFq, Pochhammer\n\njulia> pFq((1/3,2/3), 5/6, 27/32) ≈ 8/5\ntrue\n\njulia> pFq([1/4, 1/2], [3/4], 80/81; maxevals=2000) ≈ 9/5\ntrue\n\njulia> x = variable()\nPolynomial(x)\n\njulia> n = 5\n5\n\njulia> pFq((-n,n+1), 1, (1-x)/2) ≈ basis(Legendre,n)(x)\ntrue\n\njulia> α, β, n = 1/2, 1/2, 5;\n\njulia> Pochhammer(α+1,n)/factorial(n) * pFq((-n,n+α+β+1), α+1, (1-x)/2) ≈ basis(Jacobi{α,β}, n)(x)\ntrue\n```\n\"\"\"\nfunction pFq(as, bs, z; maxevals=1000)\n n = 1\n acc = trm = one(z)\n\n p,q = length(as), length(bs)\n\n # element in `as` is negative integer or 0 && converges\n # p ≤ q && converges\n # p = q + 1 |x| < 1 && converge\n # p > q + 1 && diverges\n while n < maxevals\n a = isempty(as) ? 1 : prod(as)\n b = isempty(bs) ? 1 : prod(bs)\n\n iszero(a) && return acc\n iszero(b) && return Inf # check on b\n\n trm *= a /b * z /n\n acc += trm\n\n as = plus_1(as)\n\n bs = plus_1(bs)\n n += 1\n end\n\n if (p > q + 1 || (p == q+1 && abs(z) < 1))\n return acc\n else\n NaN*acc\n end\nend\n## tuples\n@inline plus_1(as) = map(x->x+1, as)\n \n\n# use HypergeometricFunction.mFn if possible\nfunction pFq(as::Tuple{A,B}, bs::Tuple{C}, z::AbstractFloat) where {A,B,C}\n HypergeometricFunctions._₂F₁(as[1],as[2],bs[1],z)\nend\nfunction pFq(as::Tuple{A,B,C}, bs::Tuple{D,E}, z::AbstractFloat) where {A,B,C,D,E}\n HypergeometricFunctions._₃F₂(as[1],as[2],as[3],bs[1],bs[2],z)\nend\n \n\n\n## Try to speed up quadgk by not specializing on F\nmutable struct Wrapper\n F\nend\n(F::Wrapper)(x) = F.F(x)\n\n_quadgk(f, a, b) = quadgk(Wrapper(f), a, b)[1]\nconst ∫ = _quadgk\n\n\nchecked_div(a, b) = (iszero(a) && iszero(b)) ? a : a/b\n", "meta": {"hexsha": "8e91d6b4e3d0c52fa609f02103b18aa01ac037e2", "size": 3423, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "rurz/SpecialPolynomials.jl", "max_stars_repo_head_hexsha": "91196ab12232c4d45a4681e871803fbd6bb3a417", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "rurz/SpecialPolynomials.jl", "max_issues_repo_head_hexsha": "91196ab12232c4d45a4681e871803fbd6bb3a417", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "rurz/SpecialPolynomials.jl", "max_forks_repo_head_hexsha": "91196ab12232c4d45a4681e871803fbd6bb3a417", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6688741722, "max_line_length": 271, "alphanum_fraction": 0.5898334794, "num_tokens": 1303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475778774729, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.8018182444445978}} {"text": "#=\n Cookie problem.\n\n From Think Bayes, page 3\n \"\"\"\n Suppose there are two bowls of cookies. \n Bowl 1 contains 30 vanilla cookies and 10 chocolate cookies. \n Bowl 2 contains 20 of each.\n\n Now suppose you choose one of the bowls at random and, without looking,\n select a cookie at random. The cookie is vanilla. \n What is the probability that it came from Bowl 1?\n \"\"\"\n\n Distributions of variable bowl (num:0)\n 1.00000 => 5991 (0.599100)\n 2.00000 => 4009 (0.400900)\n\n Cf ~/webppl/cookie_problem.wppl\n\n\n=#\n\nusing Turing, StatsPlots, DataFrames\ninclude(\"jl_utils.jl\")\n\n@model function cookie_problem()\n vanilla = 1\n chocolate = 2\n \n bowl1 = 1\n bowl2 = 2\n \n bowl ~ DiscreteUniform(bowl1,bowl2)\n cookie ~ (bowl == bowl1) ? Categorical(simplex([30,10])) : # [vanilla,chocolate] \n Categorical(simplex([20,20]))\n \n true ~ Dirac(cookie == vanilla)\n\nend\n\nmodel = cookie_problem()\nnum_chains = 4\n\n# chns = sample(model, Prior(), 10_000)\n# chns = sample(model, MH(), 10_000)\nchns = sample(model, PG(5), 10_000)\n# chns = sample(model, SMC(), 10_000)\n# chns = sample(model, IS(), 10_000)\n\ndisplay(chns)\n# display(plot(chns))\n\n\nshow_var_dist_pct(chns, :bowl)\n", "meta": {"hexsha": "112e908e95f1186cc4906c112ac1eed07e7d956d", "size": 1227, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/cookie_problem.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/turing/cookie_problem.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/turing/cookie_problem.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 21.9107142857, "max_line_length": 85, "alphanum_fraction": 0.6487367563, "num_tokens": 383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034425, "lm_q2_score": 0.8740772466456689, "lm_q1q2_score": 0.801793377103201}} {"text": "using DifferentialEquations\nusing Plots\nusing Markdown\nusing LinearAlgebra\nusing StaticArrays\n\n\ndescription=md\"\"\"\n\nsolve the matrix system\n``u' = Au``\nfor matrix A and i.c. u₀\n\n\"\"\"\ndisplay(description)\n\n# use immutable arrays that are stack-allocated\nA = @SMatrix [1.0 0 0 -5\n 4 -2 4 -3\n -4 0 0 1\n 5 -2 2 3]\n\nu0 = rand(4, 2)\n\ntspan = (0.0, 1.0)\n\nf(du, u, p, t) = mul!(du, A, u) # in-place version of matrix multiply\n\nprob = ODEProblem(f, u0, tspan)\nsol = solve(prob)\nplot(sol)\n", "meta": {"hexsha": "5153c43f6e8818db56fbbc34de4135902eeea814", "size": 517, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "DiffEqs/ODEs/OtherTypes.jl", "max_stars_repo_name": "john-waczak/SciML-examples", "max_stars_repo_head_hexsha": "bed1fc7c7038f7676662540d5939465584978a85", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DiffEqs/ODEs/OtherTypes.jl", "max_issues_repo_name": "john-waczak/SciML-examples", "max_issues_repo_head_hexsha": "bed1fc7c7038f7676662540d5939465584978a85", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DiffEqs/ODEs/OtherTypes.jl", "max_forks_repo_name": "john-waczak/SciML-examples", "max_forks_repo_head_hexsha": "bed1fc7c7038f7676662540d5939465584978a85", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.15625, "max_line_length": 70, "alphanum_fraction": 0.6189555126, "num_tokens": 178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075766298656, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.8017479029591804}} {"text": "# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n# jupytext:\n# formats: ipynb,jl:hydrogen\n# text_representation:\n# extension: .jl\n# format_name: hydrogen\n# format_version: '1.3'\n# jupytext_version: 1.11.2\n# kernelspec:\n# display_name: Julia 1.7.0-DEV\n# language: julia\n# name: julia-1.7\n# ---\n\n# %%\nusing Plots\nplotly()\nf(x, y) = sin(x) * sin(y) + (x - 2y)^2/50\nx = range(-π, π; length=401)\ny = range(-π, π; length=401)\nsurface(x, y, f; xlim=extrema(x), ylim=extrema(y), camera=(30, 45), size=(500, 500), colorbar=false)\n\n# %%\nfmin, pt = findmin(p -> f(p...), Iterators.product(x, y))\n\n# %% tags=[]\nsurface(x, y, f; xlim=extrema(x), ylim=extrema(y), camera=(30, 45), size=(500, 500), colorbar=false)\nscatter!([pt[1]], [pt[2]], [f(pt...)]; label=\"\", color=:cyan, ms=2)\n\n# %%\nf(p) = sin(p[1]) * sin(p[2]) + (p[1] - 2p[2])^2/50\nx = y = range(-π, π; length=401)\nfindmin(f, Iterators.product(x, y))\n\n# %%\nf(p) = sin(p[1]) * sin(p[2]) + (p[1] - 2p[2])^2/50\nx = y = range(-π, π, 1000)\nfindmin(f, Iterators.product(x, y))\n\n# %%\nusing Plots\nplotly()\nx = y = range(-3, 3, length=100)\nf(x, y) = exp(-x^2-y^2)\nz = f.(x', y)\nsurface(x, y, z; colorbar=false, size=(600, 600), color=:jet)\n\n# %%\nusing Plots\nplotly()\nx = y = range(-3, 3, length=100)\nz = exp.(.-x'.^ 2 .- y.^ 2)\nsurface(x, y, z; colorbar=false, size=(600, 600), color=:jet)\n\n# %%\nusing Plots\nplotly()\nx = y = range(-3, 3, length=100)\nz = @. exp(-x'^2 .- y^2)\nsurface(x, y, z; colorbar=false, size=(600, 600), color=:jet)\n\n# %%\n", "meta": {"hexsha": "a00d246b8dea09d77523bb5189e5bb23632fb95c", "size": 1517, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "0004/v1.7 findmin and Plots plotly example.jl", "max_stars_repo_name": "genkuroki/public", "max_stars_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-06-06T00:33:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T06:56:08.000Z", "max_issues_repo_path": "0004/v1.7 findmin and Plots plotly example.jl", "max_issues_repo_name": "genkuroki/public", "max_issues_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "0004/v1.7 findmin and Plots plotly example.jl", "max_forks_repo_name": "genkuroki/public", "max_forks_repo_head_hexsha": "339ea5dfd424492a6b21d1df299e52d48902de18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-08-02T11:58:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T11:46:05.000Z", "avg_line_length": 23.3384615385, "max_line_length": 100, "alphanum_fraction": 0.5530652604, "num_tokens": 617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765163620469, "lm_q2_score": 0.8774767970940975, "lm_q1q2_score": 0.8017299431574617}} {"text": "#=\n\n Linear regression\n\n This is actually a WebPPL example (example/linear_regression.wppl) but translated via my BLOG model.\n\n xs = [0,1,2,3]\n ys = [0,1,4,6]\n\n mu should be ~ 2 and b ~ 0.\n y4: y for x=4 should be 2*4+0 = 8\n y5: y for x=5 should be 2*5+0 = 10\n\n Summary Statistics\n parameters mean std naive_se mcse ess rhat ess_per_sec \n Symbol Float64 Float64 Float64 Float64 Float64 Float64 Float64 \n\n m 2.0134 0.3960 0.0040 0.0088 1980.8480 1.0001 445.5349\n b -0.2678 0.7118 0.0071 0.0135 2785.0095 0.9999 626.4079\n sigma 0.8463 0.4970 0.0050 0.0155 929.0047 0.9999 208.9529\n y4 7.7715 1.5278 0.0153 0.0314 2240.9116 1.0001 504.0287\n y5 9.7916 1.8747 0.0187 0.0401 2060.8303 1.0000 463.5246\n\n With 5 data points (x=[0,1,2,3,4] and y=[0,1,4,6,8]) with got a much better result:\n Summary Statistics\n parameters mean std naive_se mcse ess rhat ess_per_sec \n Symbol Float64 Float64 Float64 Float64 Float64 Float64 Float64 \n\n m 2.0000 0.0001 0.0000 0.0000 684.0973 0.9999 170.6830\n b 0.0000 0.0004 0.0000 0.0000 1140.3205 1.0005 284.5111\n sigma 0.0002 0.0003 0.0000 0.0000 111.5388 1.0486 27.8290\n y4 8.0000 0.0005 0.0000 0.0000 713.2871 1.0046 177.9658\n y5 10.0000 0.0006 0.0000 0.0000 553.0126 1.0016 137.9772\n\n\n cf ~/blog/linear_regression2.blog\n ~/webppl/linear_regression2.wppl\n=#\n\nusing Turing\ninclude(\"jl_utils.jl\")\n\n@model function linear_regression2(xs,ys)\n n = length(xs)\n \n m ~ Normal(0,2)\n b ~ Normal(0,2)\n sigma ~ Gamma(1,1)\n\n xs ~ filldist(Uniform(0,14),n)\n \n for i in 1:n\n ys[i] ~ Normal(m*xs[i] + b, sigma)\n end\n\n # Prediction for x=4 and x=5\n y4 ~ Normal(m*4 + b, sigma)\n y5 ~ Normal(m*5 + b, sigma) \n\nend\n\nxs = [0,1,2,3]\nys = [0,1,4,6]\nn = 4\nxs = [i for i in 0:n]\nys = [2*x for x in xs]\nprintln(\"xs: \", xs)\nprintln(\"ys: \", ys)\nmodel = linear_regression2(xs,ys)\n\n# chns = sample(model, Prior(), 100_000)\n# chns = sample(model, MH(), 100_000)\n# chns = sample(model, PG(15), 10_000)\n# chns = sample(model, SMC(), 10_000)\n# chns = sample(model, IS(), 100_000)\nchns = sample(model, NUTS(), 10_000)\n\n\ndisplay(chns)\n", "meta": {"hexsha": "9f8000ab4ddb4435c4c5d9c37482077293d661a8", "size": 2529, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/linear_regression2.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/turing/linear_regression2.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/turing/linear_regression2.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 31.6125, "max_line_length": 102, "alphanum_fraction": 0.5484381178, "num_tokens": 1033, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.930458253565792, "lm_q2_score": 0.8615382165412808, "lm_q1q2_score": 0.8016253443431873}} {"text": "\"\"\"\n gram_schmidt(A::Array[, ret_coef_mat::Bool])\n\nReturn orthogonalized basis.\nOptionally returns the Gram-Schmidt coefficient matrix using the ret_coef_mat parameter.\n\n# Example\n\n```julia\njulia> x = [\n [ 3 -1 5]\n [-5 2 -1]\n [-3 9 2]\n ]\n\njulia> gram_schmidt(x)\n3×3 Array{Float64,2}:\n 3.0 -1.0 5.0\n -3.11429 1.37143 2.14286\n 2.68728 6.5689 -0.298587\n\n```\n\"\"\"\nfunction gram_schmidt{T<:AbstractFloat}(A::Array{T, 2}; ret_coef_mat::Bool = false)\n # Assume the vectors are given as row vectors of X\n # Maybe redo later since vectors in Julia are stored in column-major order.\n\n X = transpose(copy(A))\n X_star = zeros(X)\n\n # Coefficient matrix\n μ = zeros(X)\n\n n_cols = size(X)[2]\n for i in 1:n_cols\n X_star[:, i] = X[:, i]\n for j in 1:i-1\n t = dot(X[:, i], X_star[:, j]) / dot(X_star[:, j], X_star[:, j])\n μ[j, i] = t\n X_star[:, i] -= (t * X_star[:, j])\n end\n μ[i,i] = 1\n end\n\n if ret_coef_mat\n transpose(X_star), transpose(μ)\n else\n transpose(X_star)\n end\nend\n\nfunction gram_schmidt{T<:Integer}(A::Array{T, 2}; ret_coef_mat::Bool = false)\n gram_schmidt(float(A), ret_coef_mat=ret_coef_mat)\nend\n", "meta": {"hexsha": "f97e86605fd15f274e287c592067ec1a259be964", "size": 1262, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/gram_schmidt.jl", "max_stars_repo_name": "pikachau/LatticeBasisReduction.jl", "max_stars_repo_head_hexsha": "a9eb13052d70f0826e116ac4e5e8c993e16ef575", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-04-22T23:53:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-22T23:53:41.000Z", "max_issues_repo_path": "src/gram_schmidt.jl", "max_issues_repo_name": "pikachau/LatticeBasisReduction.jl", "max_issues_repo_head_hexsha": "a9eb13052d70f0826e116ac4e5e8c993e16ef575", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gram_schmidt.jl", "max_forks_repo_name": "pikachau/LatticeBasisReduction.jl", "max_forks_repo_head_hexsha": "a9eb13052d70f0826e116ac4e5e8c993e16ef575", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-26T15:32:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-26T15:32:58.000Z", "avg_line_length": 22.9454545455, "max_line_length": 88, "alphanum_fraction": 0.5697305864, "num_tokens": 417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582497090322, "lm_q2_score": 0.8615382094310355, "lm_q1q2_score": 0.801625334404655}} {"text": "using Statistics, StatsBase, Random, LinearAlgebra\nRandom.seed!(1)\n\nfunction cmHitTime()\n catIndex, mouseIndex, t = 1, 5, 0\n while catIndex != mouseIndex\n catIndex += catIndex == 1 ? 1 : rand([-1,1])\n mouseIndex += mouseIndex == 5 ? -1 : rand([-1,1])\n t += 1\n end\n return t\nend\nfunction mcTraj(P,initState,T,stopState=0)\n n = size(P)[1]\n state = initState\n traj = [state]\n for t in 1:T-1\n state = sample(1:n,weights(P[state,:]))\n push!(traj,state)\n if state == stopState\n break\n end\n end\n return traj\nend\nN = 10^6\nP = [ 0 1 0 0 0;\n 1/4 0 1/4 1/4 1/4;\n 0 1/2 0 0 1/2;\n 0 1/2 0 0 1/2;\n 0 0 0 0 1]\n\ntheor = [1 0 0 0] * (inv(I - P[1:4,1:4])*ones(4))\nest1 = mean([cmHitTime() for _ in 1:N])\nest2 = mean([length(mcTraj(P,1,10^6,5))-1 for _ in 1:N])\n\nP[5,:] = [1 0 0 0 0]\npi5 = sum(mcTraj(P,1,N) .== 5)/N\nest3 = 1/pi5 - 1\n\nprintln(\"Theoretical: \", theor)\nprintln(\"Estimate 1: \",est1)\nprintln(\"Estimate 2: \",est2)\nprintln(\"Estimate 3: \",est3)\n", "meta": {"hexsha": "2b9e12b7fcc63a4ef63d1884efe22b3ee59c541e", "size": 1105, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "10_chapter/catMouse.jl", "max_stars_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_stars_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 988, "max_stars_repo_stars_event_min_datetime": "2018-06-21T00:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:37:47.000Z", "max_issues_repo_path": "10_chapter/catMouse.jl", "max_issues_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_issues_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-02-20T05:06:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:53:08.000Z", "max_forks_repo_path": "10_chapter/catMouse.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 24.5555555556, "max_line_length": 61, "alphanum_fraction": 0.5185520362, "num_tokens": 449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582497090321, "lm_q2_score": 0.86153820232079, "lm_q1q2_score": 0.8016253277888683}} {"text": "### A Pluto.jl notebook ###\n# v0.12.16\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# ╔═╡ e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\n\tusing Random, Distributions, Plots\n\tRandom.seed!(0)\nend;\n\n# ╔═╡ ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing5.01\"\n\n# ╔═╡ fa68607e-22e5-11eb-0558-c9a4d9f77426\nbegin\n\tlambda = 1/4.5\n\texpDist = Exponential(1/lambda)\n\tn, N = 10, 10^6\n\n\tmeans = Array{Float64}(undef, N)\n\tvariances = Array{Float64}(undef, N)\n\n\tfor i in 1:N\n\t\tdata = rand(expDist,n)\n\t\tmeans[i] = mean(data)\n\t\tvariances[i] = var(data)\n\tend\nend\n\n# ╔═╡ 78fd898a-2527-11eb-048f-3be84c5d8649\n(\"Actual mean: \",mean(expDist),\n\t\t\"Mean of sample means: \",mean(means))\n\n# ╔═╡ 78fdc0d2-2527-11eb-3fe8-5738d4af3806\n(\"Actual variance: \",var(expDist),\n\t\"Mean of sample variances: \",mean(variances))\n\n# ╔═╡ 78fe5bf8-2527-11eb-2c19-1d2e7d1277af\nbegin\n\tstephist(means, bins=200, c=:blue, normed=true, \n\t\tlabel=\"Histogram of Sample Means\")\n\tstephist!(variances, bins=600, c=:red, normed=true, \n\t\tlabel=\"Histogram of Sample Variances\", xlims=(0,40), ylims=(0,0.4),\n\t\t\txlabel = \"Statistic value\", ylabel = \"Density\")\nend\n\n# ╔═╡ 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing5.01\"\n\n# ╔═╡ Cell order:\n# ╟─ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# ╠═e077ab16-22e5-11eb-15ed-5f0654bf7328\n# ╠═e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# ╠═fa68607e-22e5-11eb-0558-c9a4d9f77426\n# ╠═78fd898a-2527-11eb-048f-3be84c5d8649\n# ╠═78fdc0d2-2527-11eb-3fe8-5738d4af3806\n# ╠═78fe5bf8-2527-11eb-2c19-1d2e7d1277af\n# ╟─475ff888-22e6-11eb-2354-09f8f40a8e12\n", "meta": {"hexsha": "01521d08cf0aeebec7489f487eb6c603c799a5e1", "size": 1637, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/05/listing5.01.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/05/listing5.01.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/05/listing5.01.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 25.1846153846, "max_line_length": 69, "alphanum_fraction": 0.7122785583, "num_tokens": 796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9324533126145178, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.8015963169264221}} {"text": "# coordinates.jl\n# Maps having to do with coordinate transforms.\n\n\"\"\"\nA Cartesion to Polar map. First dimension is interpreted as radial distance, second as an angle.\nThe unit circle is mapped to a square [-1,1]x[-1,1]\n\n\"\"\"\nstruct CartToPolarMap{T} <: AbstractMap{SVector{2,T}, SVector{2,T}}\nend\n\n(m::CartToPolarMap)(x) = applymap(m, x)\n\napplymap(map::CartToPolarMap, x::SVector{2,T}) where {T} = SVector{2,T}(sqrt(x[1]^2+x[2]^2)*2-1, atan(x[2],x[1])/pi)\n\ninv(map::CartToPolarMap{T}) where {T} = PolarToCartMap{T}()\n\n\n\"\"\"\nA Polar to Cartesian map. The angle is mapped to the second dimension, radius to the first.\nA square [-1,1]x[-1,1] is mapped to the unit circle\n\"\"\"\nstruct PolarToCartMap{T} <: AbstractMap{SVector{2,T}, SVector{2,T}}\nend\n\n(m::PolarToCartMap)(x) = applymap(m, x)\n\napplymap(map::PolarToCartMap, x::SVector{2,T}) where {T} = SVector{2,T}((x[1]+1)/2*cos(pi*x[2]), (x[1]+1)/2*sin(pi*x[2]))\n\ninv(map::PolarToCartMap{T}) where {T} = CartToPolarMap{T}()\n", "meta": {"hexsha": "ee4659047b8626578e53c359a2f1456da0ed0a6b", "size": 967, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/maps/coordinates.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/DomainSets.jl-5b8099bc-c8ec-5219-889f-1d9e522a28bf", "max_stars_repo_head_hexsha": "8caa1870145e15e07abeda96ffe84088abbae602", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/maps/coordinates.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/DomainSets.jl-5b8099bc-c8ec-5219-889f-1d9e522a28bf", "max_issues_repo_head_hexsha": "8caa1870145e15e07abeda96ffe84088abbae602", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/maps/coordinates.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/DomainSets.jl-5b8099bc-c8ec-5219-889f-1d9e522a28bf", "max_forks_repo_head_hexsha": "8caa1870145e15e07abeda96ffe84088abbae602", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1935483871, "max_line_length": 121, "alphanum_fraction": 0.6794208893, "num_tokens": 339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533126145179, "lm_q2_score": 0.8596637523076225, "lm_q1q2_score": 0.801596313573869}} {"text": "# Cost functions\n\"\"\"\n mae(ŷ, y)\n\nReturn the mean of absolute error `sum(abs.(ŷ .- y)) / length(y)`\n\"\"\"\nmae(ŷ, y) = sum(abs.(ŷ .- y)) * 1 // length(y)\n\n\n\"\"\"\n mse(ŷ, y)\n\nReturn the mean squared error `sum((ŷ .- y).^2) / length(y)`.\n\"\"\"\nmse(ŷ, y) = sum((ŷ .- y).^2) * 1 // length(y)\n\n\n\"\"\"\n msle(ŷ, y; ϵ=eps(eltype(ŷ)))\n\nReturns the mean of the squared logarithmic errors `sum((log.(ŷ .+ ϵ) .- log.(y .+ ϵ)).^2) / length(y)`.\nThe `ϵ` term provides numerical stability.\n\nThis error penalizes an under-predicted estimate greater than an over-predicted estimate.\n\"\"\"\nmsle(ŷ, y; ϵ=eps(eltype(ŷ))) = sum((log.(ŷ .+ ϵ) .- log.(y .+ ϵ)).^2) * 1 // length(y)\n\n\n\n\"\"\"\n huber_loss(ŷ, y; δ=1.0)\n\nComputes the mean of the Huber loss given the prediction `ŷ` and true values `y`. By default, δ is set to 1.0.\n\n | 0.5*|ŷ - y|, for |ŷ - y| <= δ\n Hubber loss = |\n | δ*(|ŷ - y| - 0.5*δ), otherwise\n\n[`Huber Loss`](https://en.wikipedia.org/wiki/Huber_loss).\n\"\"\"\nfunction huber_loss(ŷ, y; δ=eltype(ŷ)(1))\n abs_error = abs.(ŷ .- y)\n temp = abs_error .< δ\n x = eltype(ŷ)(0.5)\n hub_loss = sum(((abs_error.^2) .* temp) .* x .+ δ*(abs_error .- x*δ) .* (1 .- temp)) * 1 // length(y)\nend\n\nfunction _crossentropy(ŷ::AbstractVecOrMat, y::AbstractVecOrMat, weight::Nothing)\n return -sum(y .* log.(ŷ)) * 1 // size(y, 2)\nend\n\nfunction _crossentropy(ŷ::AbstractVecOrMat, y::AbstractVecOrMat, weight::Number)\n return -sum(y .* log.(ŷ)) .* weight * 1 // size(y, 2)\nend\n\nfunction _crossentropy(ŷ::AbstractVecOrMat, y::AbstractVecOrMat, weight::AbstractVector)\n return -sum(y .* log.(ŷ) .* weight) * 1 // size(y, 2)\nend\n\n\"\"\"\n crossentropy(ŷ, y; weight=1)\n\nReturn the crossentropy computed as `-sum(y .* log.(ŷ) .* weight) / size(y, 2)`.\n\nSee also [`logitcrossentropy`](@ref), [`binarycrossentropy`](@ref).\n\"\"\"\ncrossentropy(ŷ::AbstractVecOrMat, y::AbstractVecOrMat; weight=nothing) = _crossentropy(ŷ, y, weight)\n\n\"\"\"\n logitcrossentropy(ŷ, y; weight=1)\n\nReturn the crossentropy computed after a [softmax](@ref) operation:\n\n -sum(y .* logsoftmax(ŷ) .* weight) / size(y, 2)\n\nSee also [`crossentropy`](@ref), [`binarycrossentropy`](@ref).\n\"\"\"\nfunction logitcrossentropy(ŷ::AbstractVecOrMat, y::AbstractVecOrMat; weight = 1)\n return -sum(y .* logsoftmax(ŷ) .* weight) * 1 // size(y, 2)\nend\n\n\"\"\"\n binarycrossentropy(ŷ, y; ϵ=eps(ŷ))\n\nReturn `-y*log(ŷ + ϵ) - (1-y)*log(1-ŷ + ϵ)`. The ϵ term provides numerical stability.\n\nTypically, the prediction `ŷ` is given by the output of a [`sigmoid`](@ref) activation.\n\"\"\"\nbinarycrossentropy(ŷ, y; ϵ=eps(ŷ)) = -y*log(ŷ + ϵ) - (1 - y)*log(1 - ŷ + ϵ)\n\n# Re-definition to fix interaction with CuArrays.\nCuArrays.@cufunc binarycrossentropy(ŷ, y; ϵ=eps(ŷ)) = -y*log(ŷ + ϵ) - (1 - y)*log(1 - ŷ + ϵ)\n\n\"\"\"\n logitbinarycrossentropy(ŷ, y)\n\n`logitbinarycrossentropy(ŷ, y)` is mathematically equivalent to `binarycrossentropy(σ(ŷ), y)`\nbut it is more numerically stable.\n\nSee also [`binarycrossentropy`](@ref), [`sigmoid`](@ref), [`logsigmoid`](@ref).\n\"\"\"\nlogitbinarycrossentropy(ŷ, y) = (1 - y)*ŷ - logσ(ŷ)\n\n# Re-definition to fix interaction with CuArrays.\nCuArrays.@cufunc logitbinarycrossentropy(ŷ, y) = (1 - y)*ŷ - logσ(ŷ)\n\n\"\"\"\n normalise(x; dims=1)\n\nNormalises `x` to mean 0 and standard deviation 1, across the dimensions given by `dims`. Defaults to normalising over columns.\n\n```julia-repl\njulia> a = reshape(collect(1:9), 3, 3)\n3×3 Array{Int64,2}:\n 1 4 7\n 2 5 8\n 3 6 9\n\njulia> normalise(a)\n3×3 Array{Float64,2}:\n -1.22474 -1.22474 -1.22474\n 0.0 0.0 0.0\n 1.22474 1.22474 1.22474\n\njulia> normalise(a, dims=2)\n3×3 Array{Float64,2}:\n -1.22474 0.0 1.22474\n -1.22474 0.0 1.22474\n -1.22474 0.0 1.22474\n```\n\"\"\"\nfunction normalise(x::AbstractArray; dims=1)\n μ′ = mean(x, dims = dims)\n σ′ = std(x, dims = dims, mean = μ′, corrected=false)\n return (x .- μ′) ./ σ′\nend\n\n\"\"\"\n kldivergence(ŷ, y)\n\nKLDivergence is a measure of how much one probability distribution is different from the other.\nIt is always non-negative and zero only when both the distributions are equal everywhere.\n\n[KL Divergence](https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence).\n\"\"\"\nfunction kldivergence(ŷ, y)\n entropy = sum(y .* log.(y)) * 1 //size(y,2)\n cross_entropy = crossentropy(ŷ, y)\n return entropy + cross_entropy\nend\n\n\"\"\"\n poisson(ŷ, y)\n\nPoisson loss function is a measure of how the predicted distribution diverges from the expected distribution.\nReturns `sum(ŷ .- y .* log.(ŷ)) / size(y, 2)`\n\n[Poisson Loss](https://peltarion.com/knowledge-center/documentation/modeling-view/build-an-ai-model/loss-functions/poisson).\n\"\"\"\npoisson(ŷ, y) = sum(ŷ .- y .* log.(ŷ)) * 1 // size(y,2)\n\n\"\"\"\n hinge(ŷ, y)\n\nMeasures the loss given the prediction `ŷ` and true labels `y` (containing 1 or -1).\nReturns `sum((max.(0, 1 .- ŷ .* y))) / size(y, 2)`\n\n[Hinge Loss](https://en.wikipedia.org/wiki/Hinge_loss)\nSee also [`squared_hinge`](@ref).\n\"\"\"\nhinge(ŷ, y) = sum(max.(0, 1 .- ŷ .* y)) * 1 // size(y, 2)\n\n\"\"\"\n squared_hinge(ŷ, y)\n\nComputes squared hinge loss given the prediction `ŷ` and true labels `y` (conatining 1 or -1).\nReturns `sum((max.(0, 1 .- ŷ .* y)).^2) / size(y, 2)`\n\nSee also [`hinge`](@ref).\n\"\"\"\nsquared_hinge(ŷ, y) = sum((max.(0, 1 .- ŷ .* y)).^2) * 1 // size(y, 2)\n\n\"\"\"\n dice_coeff_loss(ŷ, y; smooth=1)\n\nLoss function used in Image Segmentation. Calculates loss based on dice coefficient. Similar to F1_score.\nReturns `1 - 2*sum(|ŷ .* y| + smooth) / (sum(ŷ.^2) + sum(y.^2) + smooth)`\n\n[V-Net: Fully Convolutional Neural Networks forVolumetric Medical Image Segmentation](https://arxiv.org/pdf/1606.04797v1.pdf)\n\"\"\"\ndice_coeff_loss(ŷ, y; smooth=eltype(ŷ)(1.0)) = 1 - (2*sum(y .* ŷ) + smooth) / (sum(y.^2) + sum(ŷ.^2) + smooth)\n\n\"\"\"\n tversky_loss(ŷ, y; β=0.7)\n\nUsed with imbalanced data to give more weightage to False negatives.\nLarger β weigh recall higher than precision (by placing more emphasis on false negatives)\nReturns `1 - sum(|y .* ŷ| + 1) / (sum(y .* ŷ + β*(1 .- y) .* ŷ + (1 - β)*y .* (1 .- ŷ)) + 1)`\n\n[Tversky loss function for image segmentation using 3D fully convolutional deep networks](https://arxiv.org/pdf/1706.05721.pdf)\n\"\"\"\ntversky_loss(ŷ, y; β=eltype(ŷ)(0.7)) = 1 - (sum(y .* ŷ) + 1) / (sum(y .* ŷ + β*(1 .- y) .* ŷ + (1 - β)*y .* (1 .- ŷ)) + 1)\n\n\"\"\"\n flatten(x::AbstractArray)\n\nTransforms (w,h,c,b)-shaped input into (w x h x c,b)-shaped output,\nby linearizing all values for each element in the batch.\n\"\"\"\nfunction flatten(x::AbstractArray)\n return reshape(x, :, size(x)[end])\nend\n", "meta": {"hexsha": "eebbbe983eaa91a674af2a67e51b721f2947a9b0", "size": 6626, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/layers/stateless.jl", "max_stars_repo_name": "ararslan/Flux.jl", "max_stars_repo_head_hexsha": "240ab1147f5f49da24f5335de64a2725088dca7d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/layers/stateless.jl", "max_issues_repo_name": "ararslan/Flux.jl", "max_issues_repo_head_hexsha": "240ab1147f5f49da24f5335de64a2725088dca7d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/layers/stateless.jl", "max_forks_repo_name": "ararslan/Flux.jl", "max_forks_repo_head_hexsha": "240ab1147f5f49da24f5335de64a2725088dca7d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1079812207, "max_line_length": 128, "alphanum_fraction": 0.6239058255, "num_tokens": 2432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533144915912, "lm_q2_score": 0.8596637505099167, "lm_q1q2_score": 0.8015963135112442}} {"text": "#=\n# 3. Non-uniqueness and discrete circulation\n\nThere is no unique solution to the two-dimensional potential flow problem in the presence of an impenetrable surface, since one can choose any value for the uniform value $\\mathfrak{s}_0$ and still enforce the no-penetration condition. Equivalently, we can specify any circulation about the body and still enforce this condition. For later use, let us write this uniform surface streamfunction as $\\mathfrak{s}_0 = s_0 \\mathfrak{1}$, where $s_0$ is a single scalar value and $\\mathfrak{1}$ is a vector of ones on all surface points. The discrete circulation $\\Gamma_b$ about the body is given by the sum of the bound vortex sheet data and can be written compactly as\n\n$\\Gamma_b = \\mathfrak{1}^{T} \\mathfrak{f}.$\n\nIn `GridPotentialFlow.jl`, the user cannot specify $s_0$ directly. Instead, the package solves the system\n\n$\\begin{bmatrix}\n\\mathsf{L} & \\mathsf{R} & 0\\\\\n\\mathsf{E} & 0 & \\mathfrak{1}\\\\\n0 & \\mathfrak{1}^{T} & 0\\\\\n\\end{bmatrix} \\begin{pmatrix} \\mathsf{s} \\\\ \\mathfrak{f} \\\\ s_0 \\end{pmatrix} =\n\\begin{pmatrix} -\\mathsf{w} \\\\ \\mathfrak{s}'_b \\\\ \\Gamma_b \\end{pmatrix}.$\n\nand the circulation can be specified using the `Γ` keyword for each body. If it is not specified, it is set to zero. The return value of `solvesystem` has a field `ψ₀`, whose entries represent the value for $s_0$ for each body, which are in this case the Lagrange multipliers to enforce the specified circulation.\n=#\n\n# We now illustrate how to specify the circulation by simulating the flow around two cylinders that have different circulations.\n\n#md # ```@setup 3.-Non-uniqueness-and-discrete-circulation\n#md # using GridPotentialFlow\n#md # using Plots\n#md # ```\n#!md using GridPotentialFlow\n#!md using Plots\nΔx = 0.01\nLx = 2.0\nxlim = (-Lx/2,Lx/2)\nylim = (-Lx/2,Lx/2)\ng = PhysicalGrid(xlim,ylim,Δx);\n\n# The two cylinders are positioned using the tools from `RigidTransform` from `RigidBodyTools.jl` and the circulation of the first one is set to a non-zero value.\nR = Lx/8;\nb_left = PotentialFlowBody(Circle(R,Δx),Γ=1.0)\nT = RigidTransform((-Lx/4,0.0),0.0)\nT(b_left);\nb_right = PotentialFlowBody(Circle(R,Δx))\nT = RigidTransform((Lx/4,0.0),0.0)\nT(b_right);\n\n# A plot of the streamfunction then clearly shows the non-zero circulation about the left cylinder.\nmodel = VortexModel(g,bodies=[b_left,b_right])\ns = streamfunction(model)\nplot(s,g)\nplot!(b_left,fillcolor=:black,fillrange=0,fillalpha=0.25,linecolor=:black,linewidth=2)\nplot!(b_right,fillcolor=:black,fillrange=0,fillalpha=0.25,linecolor=:black,linewidth=2)\n\n#=\nWhen the previously introduced saddle point system\n\n$\\begin{bmatrix}\n\\mathsf{L} & \\mathsf{R} \\\\\n\\mathsf{E} & 0\n\\end{bmatrix} \\begin{pmatrix} \\mathsf{s} \\\\ \\mathfrak{f} \\end{pmatrix} =\n\\begin{pmatrix} -\\mathsf{w} \\\\ \\mathfrak{s}'_b - \\mathfrak{s}_0 \\end{pmatrix}.$\n\nis solved, the resulting circulation is\n\n$\\Gamma_{b} = \\mathfrak{1}^{T} \\mathsf{S}^{-1}\\left(\\mathfrak{s}_{b}^{\\prime}+\\mathsf{EL}^{-1} \\mathsf{w}\\right)-s_{0} \\mathfrak{1}^{T} \\mathsf{S}^{-1} \\mathfrak{1},$\n\nwhere $\\mathsf{S} = -\\mathsf{EL}^{-1}\\mathsf{R}$ is the Schur complement. The scalar factor $\\mathfrak{1}^{T} \\mathsf{S}^{-1} \\mathfrak{1}$ in this expression is a property of the set of points and their immersion into the Cartesian grid. Part of this factor, $\\mathsf{S}^{-1} \\mathfrak{1}$, represents the bound vortex sheet strength associated with a uniform, unit-strength streamfunction on the surface. This sheet has a particularly important role in some of the discussion to follow, so we will denote its strength by $\\mathfrak{f}_0$:\n\n$\\mathfrak{f}_0 \\equiv \\mathsf{S}^{-1} \\mathfrak{1}.$\n\nWe demonstrate below the distribution of $\\mathfrak{f}_0$ for elliptical cylinders with different aspect ratios.\n=#\n\nΔx = 0.004\nLx = 2.0\nxlim = (-Lx/2,Lx/2)\nylim = (-Lx/2,Lx/2)\ng = PhysicalGrid(xlim,ylim,Δx);\n\n# Let us consider four cylinders with aspect ratios 1, 2, 3, and infinity. An ellipse with infinite aspect ratio is a flat plate, so we construct that case separately.\na = Lx/4 # semi-major axis\nAR_list = [1.0,2.0,3.0]\nellipses = [Ellipse(a,a/AR,Δx) for AR in AR_list]\nbodies = PotentialFlowBody[]\npush!(bodies,[PotentialFlowBody(SplinedBody(hcat(e.x,e.y),3*cellsize(g))) for e in ellipses]...)\npush!(bodies,PotentialFlowBody(Plate(2*a,3*Δx)));\ncolors = [:blue,:red,:green,:black]\nplot()\nfor i in 1:length(bodies)\n plot!(bodies[i],fillrange=0,fillalpha=0.0,linecolor=colors[i],linewidth=2)\nend\nplot!(xlim=xlim,ylim=ylim,xlabel=\"x\",ylabel=\"y\")\n\n# To compute $\\mathfrak{f}_0$, we have to access the internal fields of the associated `system` of our vortexmodel.\nf₀_list = []\nfor i in 1:length(bodies)\n Δs = dlength(bodies[i]);\n model = VortexModel(g,bodies=[bodies[i]]);\n ones = ScalarData(length(bodies[i]))\n ones .= 1.0\n f₀ = model.system.ibp.Sfact\\ones\n push!(f₀_list,f₀)\nend\n\n# Because the flat plate is an open body, we need to mirror and append its contents to itself to compare it to the ellipses. Furthermore, its bound vortex sheet strength should be divided by two because it represents $\\gamma = \\gamma^{+} + \\gamma^{-}$\nappend!(f₀_list[end],reverse!(f₀_list[end]));\nΔs_plate = dlengthmid(bodies[end]);\nappend!(Δs_plate,reverse!(Δs_plate));\nplot(ylim=(-2,0),xlabel=\"p/N\",title=\"f₀ for ellipses of different aspect ratios\")\nfor i in 1:length(bodies)-1\n plot!((1:length(f₀_list[i]))/length(f₀_list[i]),f₀_list[i]./dlength(bodies[i]),linecolor=colors[i],label=\"AR=$(AR_list[i])\")\nend\nplot!((1:length(f₀_list[end]))/length(f₀_list[end]),0.5*f₀_list[end]./Δs_plate,linecolor=colors[end],label=\"AR=inf\")\n", "meta": {"hexsha": "58a5aa2c6128aba7ed08c10840e2cd29f27c49a2", "size": 5567, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/literate/3.-Non-uniqueness-and-discrete-circulation.jl", "max_stars_repo_name": "JuliaIBPM/GridPotentialFlow.jl", "max_stars_repo_head_hexsha": "b24127d036ed54a588a11ebedb35544acb8dea53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-02-25T02:10:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-09T22:51:52.000Z", "max_issues_repo_path": "test/literate/3.-Non-uniqueness-and-discrete-circulation.jl", "max_issues_repo_name": "JuliaIBPM/GridPotentialFlow.jl", "max_issues_repo_head_hexsha": "b24127d036ed54a588a11ebedb35544acb8dea53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-04-01T20:39:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-15T17:46:44.000Z", "max_forks_repo_path": "test/literate/3.-Non-uniqueness-and-discrete-circulation.jl", "max_forks_repo_name": "JuliaIBPM/GridPotentialFlow.jl", "max_forks_repo_head_hexsha": "b24127d036ed54a588a11ebedb35544acb8dea53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.6090909091, "max_line_length": 666, "alphanum_fraction": 0.7212142985, "num_tokens": 1806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.8887588038050466, "lm_q1q2_score": 0.8015899462855135}} {"text": "# # Train Kernel Parameters\n\n# Here we show a few ways to train (optimize) the kernel (hyper)parameters at the example of kernel-based regression using KernelFunctions.jl. \n# All options are functionally identical, but differ a little in readability, dependencies, and computational cost. \n\n# We load KernelFunctions and some other packages. Note that while we use `Zygote` for automatic differentiation and `Flux.optimise` for optimization, you should be able to replace them with your favourite autodiff framework or optimizer. \n\nusing KernelFunctions\nusing LinearAlgebra\nusing Distributions\nusing Plots\nusing BenchmarkTools\nusing Flux\nusing Flux: Optimise\nusing Zygote\nusing Random: seed!\nseed!(42);\n\n# ## Data Generation\n# We generate a toy dataset in 1 dimension:\n\nxmin, xmax = -3, 3 # Bounds of the data\nN = 50 # Number of samples\nx_train = rand(Uniform(xmin, xmax), N) # sample the inputs\nσ = 0.1\ny_train = sinc.(x_train) + randn(N) * σ # evaluate a function and add some noise\nx_test = range(xmin - 0.1, xmax + 0.1; length=300)\nnothing #hide\n\n# Plot the data\n\nscatter(x_train, y_train; label=\"data\")\nplot!(x_test, sinc; label=\"true function\")\n\n# ## Manual Approach\n# The first option is to rebuild the parametrized kernel from a vector of parameters \n# in each evaluation of the cost function. This is similar to the approach taken in \n# [Stheno.jl](https://github.com/JuliaGaussianProcesses/Stheno.jl).\n\n# To train the kernel parameters via [Zygote.jl](https://github.com/FluxML/Zygote.jl),\n# we need to create a function creating a kernel from an array.\n# A simple way to ensure that the kernel parameters are positive\n# is to optimize over the logarithm of the parameters. \n\nfunction kernelcall(θ)\n return (exp(θ[1]) * SqExponentialKernel() + exp(θ[2]) * Matern32Kernel()) ∘\n ScaleTransform(exp(θ[3]))\nend\nnothing #hide\n\n# From theory we know the prediction for a test set x given\n# the kernel parameters and normalization constant:\n\nfunction f(x, x_train, y_train, θ)\n k = kernelcall(θ[1:3])\n return kernelmatrix(k, x, x_train) *\n ((kernelmatrix(k, x_train) + exp(θ[4]) * I) \\ y_train)\nend\nnothing #hide\n\n# Let's look at our prediction.\n# With starting parameters `p0` (picked so we get the right local \n# minimum for demonstration) we get:\n\np0 = [1.1, 0.1, 0.01, 0.001]\nθ = log.(p0)\nŷ = f(x_test, x_train, y_train, θ)\nscatter(x_train, y_train; label=\"data\")\nplot!(x_test, sinc; label=\"true function\")\nplot!(x_test, ŷ; label=\"prediction\")\n\n# We define the following loss:\n\nfunction loss(θ)\n ŷ = f(x_train, x_train, y_train, θ)\n return norm(y_train - ŷ) + exp(θ[4]) * norm(ŷ)\nend\nnothing #hide\n\n# The loss with our starting point:\n\nloss(θ)\n\n# Computational cost for one step:\n\n@benchmark let\n θ = log.(p0)\n opt = Optimise.ADAGrad(0.5)\n grads = only((Zygote.gradient(loss, θ)))\n Optimise.update!(opt, θ, grads)\nend\n\n# ### Training the model\n\n# Setting an initial value and initializing the optimizer: \nθ = log.(p0) # Initial vector\nopt = Optimise.ADAGrad(0.5)\nnothing #hide\n\n# Optimize\n\nanim = Animation()\nfor i in 1:15\n grads = only((Zygote.gradient(loss, θ)))\n Optimise.update!(opt, θ, grads)\n scatter(\n x_train, y_train; lab=\"data\", title=\"i = $(i), Loss = $(round(loss(θ), digits = 4))\"\n )\n plot!(x_test, sinc; lab=\"true function\")\n plot!(x_test, f(x_test, x_train, y_train, θ); lab=\"Prediction\", lw=3.0)\n frame(anim)\nend\ngif(anim, \"train-kernel-param.gif\"; show_msg=false, fps=15);\nnothing; #hide\n\n# ![](train-kernel-param.gif)\n\n# Final loss\nloss(θ)\n\n# ## Using ParameterHandling.jl\n# Alternatively, we can use the [ParameterHandling.jl](https://github.com/invenia/ParameterHandling.jl) package \n# to handle the requirement that all kernel parameters should be positive. \n# The package also allows arbitrarily nesting named tuples that make the parameters \n# more human readable, without having to remember their position in a flat vector. \n\nusing ParameterHandling\n\nraw_initial_θ = (\n k1=positive(1.1), k2=positive(0.1), k3=positive(0.01), noise_var=positive(0.001)\n)\n\nflat_θ, unflatten = ParameterHandling.value_flatten(raw_initial_θ)\nflat_θ #hide\n\n# We define a few relevant functions and note that compared to the previous `kernelcall` function, we do not need explicit `exp`s. \n\nfunction kernelcall(θ)\n return (θ.k1 * SqExponentialKernel() + θ.k2 * Matern32Kernel()) ∘ ScaleTransform(θ.k3)\nend\nnothing #hide\n\nfunction f(x, x_train, y_train, θ)\n k = kernelcall(θ)\n return kernelmatrix(k, x, x_train) *\n ((kernelmatrix(k, x_train) + θ.noise_var * I) \\ y_train)\nend\nnothing #hide\n\nfunction loss(θ)\n ŷ = f(x_train, x_train, y_train, θ)\n return norm(y_train - ŷ) + θ.noise_var * norm(ŷ)\nend\nnothing #hide\n\ninitial_θ = ParameterHandling.value(raw_initial_θ)\nnothing #hide\n\n# The loss at the initial parameter values:\n\n(loss ∘ unflatten)(flat_θ)\n\n# Cost per step\n\n@benchmark let\n θ = flat_θ[:]\n opt = Optimise.ADAGrad(0.5)\n grads = (Zygote.gradient(loss ∘ unflatten, θ))[1]\n Optimise.update!(opt, θ, grads)\nend\n\n# ### Training the model\n\n# Optimize\n\nopt = Optimise.ADAGrad(0.5)\nfor i in 1:15\n grads = (Zygote.gradient(loss ∘ unflatten, flat_θ))[1]\n Optimise.update!(opt, flat_θ, grads)\nend\nnothing #hide\n\n# Final loss\n\n(loss ∘ unflatten)(flat_θ)\n\n# ## Flux.destructure\n# If we don't want to write an explicit function to construct the kernel, we can alternatively use the `Flux.destructure` function. \n# Again, we need to ensure that the parameters are positive. Note that the `exp` function is now part of the loss function, instead of part of the kernel construction. \n\n# We could also use ParameterHandling.jl here. \n# To do so, one would remove the `exp`s from the loss function below and call `loss ∘ unflatten` as above. \n\nθ = [1.1, 0.1, 0.01, 0.001]\n\nkernel = (θ[1] * SqExponentialKernel() + θ[2] * Matern32Kernel()) ∘ ScaleTransform(θ[3])\n\nparams, kernelc = Flux.destructure(kernel);\n\n# This returns the trainable `params` of the kernel and a function to reconstruct the kernel.\nkernelc(params)\n\n# From theory we know the prediction for a test set x given\n# the kernel parameters and normalization constant\n\nfunction f(x, x_train, y_train, θ)\n k = kernelc(θ[1:3])\n return kernelmatrix(k, x, x_train) * ((kernelmatrix(k, x_train) + (θ[4]) * I) \\ y_train)\nend\nnothing #hide\n\nfunction loss(θ)\n ŷ = f(x_train, x_train, y_train, exp.(θ))\n return norm(y_train - ŷ) + exp(θ[4]) * norm(ŷ)\nend\nnothing #hide\n\n# Cost for one step\n\n@benchmark let θt = θ[:], optt = Optimise.ADAGrad(0.5)\n grads = only((Zygote.gradient(loss, θt)))\n Optimise.update!(optt, θt, grads)\nend\n\n# ### Training the model\n\n# The loss at our initial parameter values:\nθ = log.([1.1, 0.1, 0.01, 0.001]) # Initial vector\nloss(θ)\n\n# Initialize optimizer \n\nopt = Optimise.ADAGrad(0.5)\nnothing #hide\n\n# Optimize\n\nfor i in 1:15\n grads = only((Zygote.gradient(loss, θ)))\n Optimise.update!(opt, θ, grads)\nend\nnothing #hide\n\n# Final loss\nloss(θ)\n", "meta": {"hexsha": "85e35c5e2c42d0d7843347900c8d845fa10bea13", "size": 6978, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/train-kernel-parameters/script.jl", "max_stars_repo_name": "pitmonticone/KernelFunctions.jl", "max_stars_repo_head_hexsha": "8687d27f9bbaa23bf0ae33069ef8ec79f721717e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/train-kernel-parameters/script.jl", "max_issues_repo_name": "pitmonticone/KernelFunctions.jl", "max_issues_repo_head_hexsha": "8687d27f9bbaa23bf0ae33069ef8ec79f721717e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/train-kernel-parameters/script.jl", "max_forks_repo_name": "pitmonticone/KernelFunctions.jl", "max_forks_repo_head_hexsha": "8687d27f9bbaa23bf0ae33069ef8ec79f721717e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3658536585, "max_line_length": 239, "alphanum_fraction": 0.7052163944, "num_tokens": 2077, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206686206199, "lm_q2_score": 0.8887587831798665, "lm_q1q2_score": 0.8015899159680338}} {"text": "# https://turing.ml/dev/tutorials/07-poisson-regression/\n\n# Import Turing, Distributions and DataFrames\nusing Turing, Distributions, DataFrames, Distributed\n\n# Import MCMCChain, Plots, and StatsPlots for visualizations and diagnostics.\nusing MCMCChains, Plots, StatsPlots\n\n# Set a seed for reproducibility.\nusing Random\nRandom.seed!(99);\n\n# Turn off progress monitor.\nTuring.setprogress!(false)\n\n# The true Poisson parameter (mean) of toy data\ntheta_noalcohol_meds = 1 # no alcohol, took medicine\ntheta_alcohol_meds = 3 # alcohol, took medicine\ntheta_noalcohol_nomeds = 6 # no alcohol, no medicine\ntheta_alcohol_nomeds = 36 # alcohol, no medicine\n\n# no of samples for each of the above cases\nq = 100\n\n# Generate data from different Poisson distributions\nnoalcohol_meds = Poisson(theta_noalcohol_meds)\nalcohol_meds = Poisson(theta_alcohol_meds)\nnoalcohol_nomeds = Poisson(theta_noalcohol_nomeds)\nalcohol_nomeds = Poisson(theta_alcohol_nomeds)\n\nnsneeze_data = vcat(rand(noalcohol_meds, q), rand(alcohol_meds, q), rand(noalcohol_nomeds, q), rand(alcohol_nomeds, q))\nalcohol_data = vcat(zeros(q), ones(q), zeros(q), ones(q))\nmeds_data = vcat(zeros(q), zeros(q), ones(q), ones(q))\n\ndf = DataFrame(nsneeze = nsneeze_data, alcohol_taken = alchol_data, nomeds_taken = meds_data, product_alcohol_meds = meds_data.*alcohol_data)\ndf[sample(1:nrow(df), 5, replace = false), :]\n\n# Data Plotting\np1 = Plots.histogram(df[(df[:,:alcohol_taken] .== 0) .& (df[:,:nomeds_taken] .== 0), 1], title = \"no_alcohol+meds\") \np2 = Plots.histogram((df[(df[:,:alcohol_taken] .== 1) .& (df[:,:nomeds_taken] .== 0), 1]), title = \"alcohol+meds\") \np3 = Plots.histogram((df[(df[:,:alcohol_taken] .== 0) .& (df[:,:nomeds_taken] .== 1), 1]), title = \"no_alcohol+no_meds\") \np4 = Plots.histogram((df[(df[:,:alcohol_taken] .== 1) .& (df[:,:nomeds_taken] .== 1), 1]), title = \"alcohol+no_meds\") \nplot(p1, p2, p3, p4, layout = (2, 2), legend = false)\n\n# Convert the DataFrame object to matrices.\ndata = Matrix(df[:, [:alcohol_taken, :nomeds_taken, :product_alcohol_meds]])\ndata_labels = df[:, :nsneeze]\ndata\n\n# Rescale our matrices to help Turing sampler \n# in initializing the parameter estimates(normalizing).\ndata = (data .- mean(data, dims=1)) ./ std(data, dims=1)\n\n@model poisson_regression(x, y, n, σ²) = begin\n b0 ~ Normal(0, σ²)\n b1 ~ Normal(0, σ²)\n b2 ~ Normal(0, σ²)\n b3 ~ Normal(0, σ²)\n for i = 1:n\n theta = b0 + b1*x[i, 1] + b2*x[i,2] + b3*x[i,3]\n y[i] ~ Poisson(exp(theta))\n end\nend;\n\n# Retrieve the number of observations.\nn, _ = size(data)\n\n# Sample using NUTS.\nnum_chains = 4\nm = poisson_regression(data, data_labels, n, 10)\nchain = sample(m, NUTS(200, 0.65), MCMCThreads(), 2_500, num_chains; discard_adapt=false)\n\n# check whether our chains have converged\ngelmandiag(chain)\n\n# Taking the first chain\nc1 = chain[:,:,1]\n\n# Calculating the exponentiated means\nb0_exp = exp(mean(c1[:b0]))\nb1_exp = exp(mean(c1[:b1]))\nb2_exp = exp(mean(c1[:b2]))\nb3_exp = exp(mean(c1[:b3]))\n\nprint(\"The exponent of the meaned values of the weights (or coefficients are): \\n\")\nprint(\"b0: \", b0_exp, \" \\n\", \"b1: \", b1_exp, \" \\n\", \"b2: \", b2_exp, \" \\n\", \"b3: \", b3_exp, \" \\n\")\nprint(\"The posterior distributions obtained after sampling can be visualised as :\\n\")\n\nplot(chain)\n\n# removing warmup samples\n\n# Note the standard deviation before removing the warmup samples\ndescribe(chain)\n\n# Removing the first 200 values of the chains.\nchains_new = chain[201:2500,:,:]\ndescribe(chains_new)\n\nplot(chains_new)", "meta": {"hexsha": "96d994e637def730d687742febc10cc4988cf390", "size": 3503, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "turing_tutorial_poisson_reg.jl", "max_stars_repo_name": "hessihan/julia_bayes_intro", "max_stars_repo_head_hexsha": "e5a6c740dbba4a2794579afde196a4586703fbc9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "turing_tutorial_poisson_reg.jl", "max_issues_repo_name": "hessihan/julia_bayes_intro", "max_issues_repo_head_hexsha": "e5a6c740dbba4a2794579afde196a4586703fbc9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "turing_tutorial_poisson_reg.jl", "max_forks_repo_name": "hessihan/julia_bayes_intro", "max_forks_repo_head_hexsha": "e5a6c740dbba4a2794579afde196a4586703fbc9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.03, "max_line_length": 141, "alphanum_fraction": 0.6996859834, "num_tokens": 1120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088025362857, "lm_q2_score": 0.8633916134888614, "lm_q1q2_score": 0.8015803739990653}} {"text": "# Conjugate\n\nexport Conjugate\n\n\"\"\"\n**Convex conjugate**\n\n Conjugate(f)\n\nReturns the convex conjugate (also known as Fenchel conjugate, or Fenchel-Legendre transform) of function `f`, that is\n```math\nf^*(x) = \\\\sup_y \\\\{ \\\\langle y, x \\\\rangle - f(y) \\\\}.\n```\n\"\"\"\nstruct Conjugate{T <: ProximableFunction} <: ProximableFunction\n f::T\n function Conjugate{T}(f::T) where {T<: ProximableFunction}\n if is_convex(f) == false\n error(\"`f` must be convex\")\n end\n new(f)\n end\nend\n\nis_prox_accurate(f::Conjugate) = is_prox_accurate(f.f)\nis_convex(f::Conjugate) = true\nis_cone(f::Conjugate) = is_cone(f.f) && is_convex(f.f)\nis_smooth(f::Conjugate) = is_strongly_convex(f.f)\nis_strongly_convex(f::Conjugate) = is_smooth(f.f)\nis_quadratic(f::Conjugate) = is_strongly_convex(f.f) && is_generalized_quadratic(f.f)\nis_generalized_quadratic(f::Conjugate) = is_quadratic(f.f)\n\nfun_dom(f::Conjugate) = fun_dom(f.f)\n\nConjugate(f::T) where {T <: ProximableFunction} = Conjugate{T}(f)\n\n# only prox! is provided here, call method would require being able to compute\n# an element of the subdifferential of the conjugate\n\nfunction prox!(y::AbstractArray{R}, g::Conjugate, x::AbstractArray{R}, gamma::R=one(R)) where R <: Real\n # Moreau identity\n v = prox!(y, g.f, x/gamma, one(R)/gamma)\n if is_set(g)\n v = zero(R)\n else\n v = dot(x,y) - gamma*dot(y,y) - v\n end\n for k in eachindex(y)\n y[k] = x[k] - gamma*y[k]\n end\n return v\nend\n\n# complex case, need to cast inner products to real\n\nfunction prox!(y::AbstractArray{Complex{T}}, g::Conjugate, x::AbstractArray{Complex{T}}, gamma::R=one(R)) where {R <: Real, T <: RealOrComplex{R}}\n v = prox!(y, g.f, x/gamma, one(R)/gamma)\n if is_set(g)\n v = zero(R)\n else\n v = real(dot(x,y)) - gamma*real(dot(y,y)) - v\n end\n for k in eachindex(y)\n y[k] = x[k] - gamma*y[k]\n end\n return v\nend\n\n# naive implementation\n\nfunction prox_naive(g::Conjugate, x::AbstractArray{T}, gamma::Real=1.0) where T <: RealOrComplex\n y, v = prox_naive(g.f, x/gamma, 1.0/gamma)\n return x - gamma*y, real(dot(x,y)) - gamma*real(dot(y,y)) - v\nend\n", "meta": {"hexsha": "20a58e675016f7c4a59303f2936b61ca3c259db7", "size": 2086, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/calculus/conjugate.jl", "max_stars_repo_name": "lostella/ProximalOperators.jl", "max_stars_repo_head_hexsha": "9935cd0c24b325667e688b5c35703dde71bfd3a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-12-15T13:57:52.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T13:57:52.000Z", "max_issues_repo_path": "src/calculus/conjugate.jl", "max_issues_repo_name": "lostella/ProximalOperators.jl", "max_issues_repo_head_hexsha": "9935cd0c24b325667e688b5c35703dde71bfd3a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/calculus/conjugate.jl", "max_forks_repo_name": "lostella/ProximalOperators.jl", "max_forks_repo_head_hexsha": "9935cd0c24b325667e688b5c35703dde71bfd3a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8133333333, "max_line_length": 146, "alphanum_fraction": 0.6663470757, "num_tokens": 721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937711, "lm_q2_score": 0.8633916152464016, "lm_q1q2_score": 0.8015803705000639}} {"text": "\"\"\"\n diffusion_matrix(domain, n)\n\nAssemble discrete diffusion matrix.\n\"\"\"\nfunction diffusion_matrix end\n\nfunction diffusion_matrix(domain::ClosedIntervalDomain, n)\n Δx = 1 // n * (domain.right - domain.left)\n inds = [-1, 0, 1]\n stencil = [1, -2, 1] / Δx^2\n diags = [i => fill(s, n + 1 - abs(i)) for (i, s) ∈ zip(inds, stencil)]\n D = spdiagm(diags...)\n D[1, 1] = stencil[1] + stencil[2]\n D[end, end] = stencil[end-1] + stencil[end]\n D\nend\n\nfunction diffusion_matrix(domain::PeriodicIntervalDomain, n)\n Δx = 1 // n * (domain.right - domain.left)\n inds = [-1, 0, 1]\n stencil = [1, -2, 1] / Δx^2\n diags = [i => fill(s, n - abs(i)) for (i, s) ∈ zip(inds, stencil)]\n D = spdiagm(diags...)\n D[1, end] = stencil[1]\n D[end, 1] = stencil[end]\n D\nend\n", "meta": {"hexsha": "194d27017c74805c4568d43c0c7af36c27840b9d", "size": 791, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/matrices/diffusion_matrix.jl", "max_stars_repo_name": "agdestein/DiscreteFiltering.jl", "max_stars_repo_head_hexsha": "e57d4b95ee2bc35e594279c491dba56a753548b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-23T12:51:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-23T12:51:11.000Z", "max_issues_repo_path": "src/matrices/diffusion_matrix.jl", "max_issues_repo_name": "agdestein/DiscreteFiltering.jl", "max_issues_repo_head_hexsha": "e57d4b95ee2bc35e594279c491dba56a753548b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/matrices/diffusion_matrix.jl", "max_forks_repo_name": "agdestein/DiscreteFiltering.jl", "max_forks_repo_head_hexsha": "e57d4b95ee2bc35e594279c491dba56a753548b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.275862069, "max_line_length": 74, "alphanum_fraction": 0.5752212389, "num_tokens": 279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897492587141, "lm_q2_score": 0.8519528057272543, "lm_q1q2_score": 0.8015084664804015}} {"text": "# this file depends on jacobi.jl from JuliaOptics/OpticsPolynomials that\n# should be found in the same directory\n\nexport zernike\nexport zernike_series\nexport zernike_sum\nexport zernike_norm\nexport zernike_nm_to_fringe\nexport zernike_nm_to_ansi_j\nexport zernike_ansi_j_to_nm\nexport zernike_noll_to_nm\nexport zernike_fringe_to_nm\nexport zernike_zero_separation\n\nexport apply_weights\n\n\"\"\"\n apply_weights(data, weights)\n\nGiven data of arbitrary dimensionality with multiple realizations or modes along\nthe final dimension, weight the final dimension by weights and return the sum.\n\nWill have one fewer dimension than the input data.\n\"\"\"\nfunction apply_weights(data, weights)\n shape = size(data)\n prod = reshape(data, (:, shape[end])) * weights\n return reshape(prod, shape[1: end-1])\nend\n\nfunction kronecker(i,j)\n return i==j ? 1 : 0\nend\n\n\"\"\"\n zernike_norm(n, m)\n\nNorm of Zernike polynomial of radial order n, azimuthal order m.\n\nThe norm is the average squared distance to zero. By multiplying a zernike\nvalue by the norm, the term is given unit stdev or RMS.\n\"\"\"\nfunction zernike_norm(n::Integer, m::Integer)\n return √(2 * (n+1)) / (1 + kronecker(m, 0))\nend\n\n\"\"\"\n zernike_nm_to_fringe(n, m)\n\nMap (n,m) ANSI indices to a single fringe index.\n\"\"\"\nfunction zernike_nm_to_fringe(n::Integer, m::Integer)\n term1 = (1 + (n + abs(m))/2)^2\n term2 = 2 * abs(m)\n term3 = (1 + sign(m)) / 2\n return Int(trunc(term1 - term2 - term3)) + 1\nend\n\n\"\"\"\n zernike_nm_to_ansi_j(n, m)\n\nMap (n,m) ANSI indices to a single ANSI j index.\n\nSee also:\n - [`zernike_ansi_j_to_nm`](@ref) (reciprocal of this function)\n\"\"\"\nfunction zernike_nm_to_ansi_j(n::Integer, m::Integer)\n return (n * (n + 2) + m) ÷ 2\nend\n\n\"\"\"\n zernike_ansi_to_ansi_j(n, m)\n\nMap (n,m) ANSI indices to a single ANSI j index.\n\nSee also:\n - [`zernike_nm_to_ansi_j`](@ref) (reciprocal of this function)\n\"\"\"\nfunction zernike_ansi_j_to_nm(j::Integer)\n n = (-3 + √(9 + 8j))÷2\n m = 2j - n * (n + 2)\n return Int(n), Int(m)\nend\n\n\"\"\"\n zernike_noll_to_nm(j)\n\nMap j Noll index to ANSI (n,m) indices.\n\"\"\"\nfunction zernike_noll_to_nm(j::Integer)\n n = ceil(Int, (-1 + √(1 + 8j))/2 - 1)\n if n == 0\n m = 0\n else\n nseries = (n+1) * (n+2) ÷ 2\n residual = j - nseries\n\n if isodd(j)\n sign = -1\n else\n sign = 1\n end\n\n if isodd(n)\n ms = [1,1]\n else\n ms = [0]\n end\n\n for i=0:(n÷2)-1\n push!(ms, ms[end]+2)\n push!(ms, ms[end])\n end\n\n m = ms[end+residual] * sign\n end\n return n, Int(m)\nend\n\n\"\"\"\n zernike_fringe_to_nm(j)\n\nMap j Fringe index to ANSI (n,m) indices.\n\"\"\"\nfunction zernike_fringe_to_nm(j::Integer)\n m_n = 2 * (ceil(Int, √j) - 1)\n g_s = (m_n ÷ 2)^2 + 1\n n = m_n ÷ 2 + (j-g_s)÷2\n m = (m_n - n) * (1 - mod(j-g_s, 2) * 2)\n return n, m\nend\n\n\"\"\"\n zernike_zero_separation(n)\n\nMinimum zero separation of Zernike polynomial of radial order n. Useful for\ncomputing sample count requirements.\n\"\"\"\nfunction zernike_zero_separation(n::Integer)\n return 1 / n^2\nend\n\n\"\"\"\n zernike(n, m, ρ, θ[; norm])\n\nZernike polynomial of radial order n and azimuthal order m, evaluated at the\npoint (ρ, θ). No normalization is required of (ρ, θ), though the polynomials\nare orthogonal only over the unit disk.\n\nnorm is a boolean flag indicating whether the result should be orthonormalized\n(scaled to unit RMS) or not.\n\nThe zernike polynomials' radial basis is a special case of the Jacobi\npolynomials under the transformation n_jacobi = (n-m)/2, α=0, β=|m|, x=2ρ^2-1.\n\nSee also: [`zernike_series`](@ref), [`zernike_sum`](@ref).\n\"\"\"\nfunction zernike(n::Integer, m::Integer, ρ, θ; norm::Bool=true)\n x = 2 .* ρ.^2 .- 1\n am = abs(m)\n n_j = (n - am) ÷ 2\n out = jacobi(n_j, 0, am, x)\n if m != 0\n if m < 0\n out .*= (ρ.^am .* sin.(m.*θ))\n else\n out .*= (ρ.^am .* cos.(m.*θ))\n end\n\n end\n\tif norm\n\t\tout .*= zernike_norm(n,m)\n\tend\n return out\nend\n\n\"\"\"\n zernike_series(nms, ρ, θ[; norm])\n\nCompute a series of Zernike polynomials of orders (n,m).\nReturns an array with shape (size(ρ)..., length(nms)).\nThat is, the _final_ dimension contains the modes and the first dimension(s)\nare spatial.\n\nSee also: [`zernike`](@ref), [`zernike_sum`](@ref)\n\"\"\"\nfunction zernike_series(nms, ρ, θ; norm::Bool=true)\n # 1. Calculate a lookup table of Jacobi polynomials for the unique elements combinations of $|m|$ and $n_j$.\n # 2. Calculate a lookup table of $\\rho^{|m|}$ for each unique $|m|$\n # 3. Calculate a lookup table of $\\sin{m\\theta}$ and $\\cos{m\\theta}$ for each unique $m$.\n # 4. For each input $n, m$ look up the appropriate elements and compute the Zernike polynomial.\n\tx = 2 .* ρ.^2 .- 1\n n_j_list = [((n - abs(m)) ÷ 2, abs(m)) for (n,m) in nms]\n abs_m_type = typeof(n_j_list[1][2])\n dtype = eltype(ρ)\n jacobi_sequences_mnj = Dict{abs_m_type,Array{typeof(n_j_list[1][1]), 1}}()\n\tfor (nj, am) in n_j_list\n\t\ta = get!(jacobi_sequences_mnj, am) do\n\t\t\tArray{abs_m_type, 1}()\n\t\tend\n\t\tpush!(a, nj)\n\tend\n\tfor key in keys(jacobi_sequences_mnj)\n\t\t# sort may not be needed. Inherently sorted\n\t\t# but not sure if unique guarantees not shuffling\n\t\t# input\n\t\tsort!(unique!(jacobi_sequences_mnj[key]))\n\tend\n # jacobi sequences_mnj now maps |m| => max n_j\n # this is step 1 at the top of the function\n jacobi_sequences = Dict{abs_m_type,Array{dtype,ndims(ρ)+1}}()\n for k in keys(jacobi_sequences_mnj)\n njs = jacobi_sequences_mnj[k]\n jacobi_sequences[k] = jacobi_series(njs, 0., dtype(k), x)\n end\n\n # jacobi_sequences now maps |m| => arrays with n_j along the last dimension\n # powers_of_rho is now ρ^|m| for each unique |m|\n plane_idx = ndims(ρ)+1\n sines = Dict{abs_m_type, typeof(ρ)}()\n cosines = Dict{abs_m_type, typeof(ρ)}()\n powers_of_rho = Dict{abs_m_type, typeof(ρ)}()\n out = Array{eltype(ρ), ndims(ρ)+1}(undef, size(ρ)..., length(nms))\n for i in eachindex(nms)\n n, m = nms[i]\n absm = abs(m)\n\n out_view = selectdim(out, plane_idx, i)\n\t\tn_j = (n-abs(m))÷2\n\t\tjac_plane = first(searchsorted(jacobi_sequences_mnj[absm], n_j))\n jacobi_piece = selectdim(jacobi_sequences[absm], plane_idx, jac_plane)\n if m == 0\n if norm\n norm_val = zernike_norm(n, m)\n out_view .= norm_val .* jacobi_piece\n else\n out_view .= jacobi_piece\n end\n else\n if m < 0\n\t\t\t\t# these evaluate the sin/cosine only as needed,\n\t\t\t\t# the do block is only called if get! would error\n azpiece = get!(sines, m) do\n\t\t\t\t\tsin.(m .* θ)\n\t\t\t\tend\n else\n azpiece = get!(cosines, m) do\n\t\t\t\t\tcos.(m .* θ)\n\t\t\t\tend\n end\n radialpiece = get!(powers_of_rho, absm) do\n\t\t\t\tρ .^ absm\n\t\t\tend\n\n if norm\n norm_val = zernike_norm(n, m)\n out_view .= norm_val .* jacobi_piece .* radialpiece .* azpiece\n else\n out_view .= jacobi_piece .* radialpiece .* azpiece\n end\n end\n end\n return out\nend\n\n\"\"\"\n zernike_sum(nms, weights, ρ, θ[; norm])\n\nCompute a sum of Zernike polynomials of orders (n,m) weighted by weights.\n\nSee also: [`zernike`](@ref), [`zernike_series`](@ref)\n\"\"\"\nfunction zernike_sum(nms, weights, ρ, θ, norm::Bool=true)\n data = zernike_series(nms, ρ, θ, norm=norm)\n return apply_weights(data, weights)\nend\n\n\n", "meta": {"hexsha": "94bfc4a94bac2f44da87ddc5a1afdaaf88dda50a", "size": 7517, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/zernike.jl", "max_stars_repo_name": "JuliaOptics/OpticsPolynomials.jl", "max_stars_repo_head_hexsha": "bd7354474ddeea0d93338af06315d4511cc6c30a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-03-22T15:49:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-07T22:33:40.000Z", "max_issues_repo_path": "src/zernike.jl", "max_issues_repo_name": "JuliaOptics/OpticsPolynomials.jl", "max_issues_repo_head_hexsha": "bd7354474ddeea0d93338af06315d4511cc6c30a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/zernike.jl", "max_forks_repo_name": "JuliaOptics/OpticsPolynomials.jl", "max_forks_repo_head_hexsha": "bd7354474ddeea0d93338af06315d4511cc6c30a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-12T14:40:26.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-12T14:40:26.000Z", "avg_line_length": 26.9426523297, "max_line_length": 113, "alphanum_fraction": 0.6191299721, "num_tokens": 2427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.940789754239075, "lm_q2_score": 0.8519528000888386, "lm_q1q2_score": 0.8015084654188702}} {"text": "# bessel_minus_struve.jl\n\nmodule bessel_minus_struve\nexport BesselI_minus_StruveL\n\nusing ArbNumerics\n\n\"\"\"\nImplementation of I[n, z] - L[-n, z] where I[n, z] is the modified Bessel function of the first kind, and L[-n, z] is the modified Struve function. n is an integer ≥ 0 and the order of the functions, and z∈ℜ>0 a positive real argument. Notice the order are opposite signs.\n\nThe expansion of the BesselI and StruveL functions are:\n\n I[n, z] = ∑_{k=0}^∞ (z/2)^{2k+n} / (Γ(k+1)⋅Γ(k+n+1))\n L[-n, z] = ∑_{k=0}^∞ (z/2)^{2k-n+1} / (Γ(k+3/2)⋅Γ(k-n+3/2))\n\nwith Γ(x) the Gamma function. The values of I[n, z] and L[-n, z] can be incredibly close, so ArbReal types are used as they allow for accurate arbitrary precision floats so that the difference, I[n, z] - L[-n, z], can be distinguished. ArbReal types are faster than BigFloat types, and the error of a float can be tracked using ball(::ArbReal)[2].\n\nUnfortunately, as ArbReal(bits = 64) * ArbReal(bits = 128) = ArbReal(bits = 64), if the starting precision is too small to accurately produce I[n, z] - L[-n, z], then the entire summation has to be restarted at a higher precision otherwise rounding errors will be too large, which slows the algorithm sometimes. Therefore, if the precision is found to be too low, the precision is just doubled (rather than increased by some set amount) to reach a required precision quickly.\n\nThe general structure of this arbitrary precision summation algorithm is used elsewhere too since you just change the arguments and term appropriately.\n\"\"\"\n\nfunction BesselI_minus_StruveL(n, z, a; prec = 64) # z > 0 & n >= 0\n\n # Initialise precision of ArbReal to prec.\n p = prec\n setextrabits(0)\n setprecision(ArbReal, p) # ArbReal(bit = 64 + 8) has same precision as Float64 (which is why we add 8 bits).\n\n n = ArbReal(\"$n\")\n z = ArbReal(\"$z\")\n a = ArbReal(\"$a\")\n\n k = ArbReal(\"0.0\")\n result = ArbReal(\"0.0\")\n term = ArbReal(\"1.0\")\n err = eps(result) # Machine accuracy of specified precision = prec.\n\n while abs(midpoint(term)) > err * abs(midpoint(result))\n term = ArbReal((abs(z) * a / 2)^(2 * k + n + 1) / (ArbNumerics.gamma(k + 1) * ArbNumerics.gamma(k + n + 2)) - (abs(z) * a / 2)^(2 * k - n) / (ArbNumerics.gamma(k + 3//2) * ArbNumerics.gamma(k - n + 1//2)))\n result += term\n # println(\"term: k = \", k, \"\\nterm value: \", ball(term), \"\\ncumulant result: \", ball(result), \"\\n\")\n k += 1\n # Double precision if rounding error in result exceeds accuracy specified by prec.\n while radius(result) > err * abs(midpoint(result))\n p *= 2\n setprecision(ArbReal, p)\n # variables have to be re-parsed into the higher precision ArbReal type.\n # println(\"Not precise enough. Error = \", radius(result), \" > \", ArbReal(\"$err\"), \". Increasing precision to \", p, \" bits.\\n\")\n n = ArbReal(\"$n\")\n z = ArbReal(\"$z\")\n a = ArbReal(\"$a\")\n k = ArbReal(\"0\")\n result = ArbReal(\"0.0\")\n term = ArbReal(\"1.0\")\n end\n end\n # println(\"z: \", ArbReal(z, bits = prec), \". Final result: \", ArbReal(result, bits = prec))\n ArbReal(result * √π * ArbNumerics.gamma(-n - 1/2) * (abs(z) / 2)^n * z / 2, bits = prec) # return to specified precision.\nend\n# @time bsi = BesselI_minus_StruveL(3, 55, 1)\n# @show(bsi)\n\n# β = ArbReal(\"2.0\")\n# α = ArbReal(\"7.0\")\n# v = ArbReal(\"5.8\")\n# w = ArbReal(\"1.6\")\n# R = ArbReal((v^2 - w^2) / (w^2 * v))\n# a = ArbReal(sqrt(β^2 / 4 + R * β * coth(β * v / 2)))\n# z = ArbReal(\"90.61\")\n# n = ArbReal(\"12.0\")\n# c = BesselI_minus_StruveL(n, z, a; prec = 24)\n\nend # end of module\n\n", "meta": {"hexsha": "1d0995090648971c7b343aeb591012760968d60b", "size": 3661, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "arb/BesselMinusStruve.jl", "max_stars_repo_name": "jarvist/PolaronMobility-FeynmanKadanoffOsakaHellwarth", "max_stars_repo_head_hexsha": "a1deffc5bfb0c6b6cb9dd7d9388578f4248915f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-07-26T17:46:18.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-26T17:46:18.000Z", "max_issues_repo_path": "arb/BesselMinusStruve.jl", "max_issues_repo_name": "jarvist/PolaronMobility-FeynmanKadanoffOsakaHellwarth", "max_issues_repo_head_hexsha": "a1deffc5bfb0c6b6cb9dd7d9388578f4248915f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "arb/BesselMinusStruve.jl", "max_forks_repo_name": "jarvist/PolaronMobility-FeynmanKadanoffOsakaHellwarth", "max_forks_repo_head_hexsha": "a1deffc5bfb0c6b6cb9dd7d9388578f4248915f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.1710526316, "max_line_length": 475, "alphanum_fraction": 0.6233269598, "num_tokens": 1152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897558991953, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.8015084650650265}} {"text": "# # 110: 1D Reaction Diffusion equation with two species\n# ([source code](SOURCE_URL))\n#\n# Solve the nonlinear coupled reaction diffusion problem\n# \n# ```math\n# -\\nabla (0.01+2u_2)\\nabla u_1 + u_1u_2= 0.0001(0.01+x)\n# ```\n# \n# ```math\n# -\\nabla (0.01+2u_1)\\nabla u_2 - u_1u_2 = 0.0001(1.01-x)\n# ```\n# \n# \n# in $\\Omega=(0,1)$ with boundary condition $u_1(0)=1$, $u_2(0)=0$ and $u_1(1)=1$, $u_2(1)=1$.\n# \n\n\nmodule Example110_ReactionDiffusion1D_TwoSpecies\n\nusing Printf\nusing VoronoiFVM\nusing ExtendableGrids\nusing GridVisualize\n\nfunction main(;n=100,Plotter=nothing,verbose=false,unknown_storage=:sparse)\n h=1/n\n grid=VoronoiFVM.Grid(collect(0:h:1))\n \n \n eps::Vector{Float64}=[1.0,1.0]\n \n physics=VoronoiFVM.Physics(num_species=2,\n \n reaction=function(f,u,node)\n f[1]=u[1]*u[2]\n f[2]=-u[1]*u[2]\n end,\n \n flux=function(f,u0,edge)\n u=unknowns(edge,u0)\n\n nspecies=2\n f[1]=eps[1]*(u[1,1]-u[1,2])*(0.01+u[2,1]+u[2,2])\n f[2]=eps[2]*(u[2,1]-u[2,2])*(0.01+u[1,1]+u[1,2])\n end,\n \n source=function(f,node)\n f[1]=1.0e-4*(0.01+node[1])\n f[2]=1.0e-4*(0.01+1.0-node[1])\n end,\n \n storage=function(f,u,node)\n f[1]=u[1]\n f[2]=u[2]\n end\n )\n \n sys=VoronoiFVM.System(grid,physics,unknown_storage=unknown_storage)\n\n enable_species!(sys,1,[1])\n enable_species!(sys,2,[1])\n\n boundary_dirichlet!(sys,1,1,1.0)\n boundary_dirichlet!(sys,1,2,0.0)\n \n boundary_dirichlet!(sys,2,1,1.0)\n boundary_dirichlet!(sys,2,2,0.0)\n \n inival=unknowns(sys)\n U=unknowns(sys)\n inival.=0\n \n control=VoronoiFVM.NewtonControl()\n control.verbose=verbose\n control.damp_initial=0.1\n u5=0\n p=GridVisualizer(Plotter=Plotter,layout=(2,1))\n for xeps in [1.0,0.5,0.25,0.1,0.05,0.025,0.01]\n eps=[xeps,xeps]\n solve!(U,inival,sys,control=control)\n inival.=U\n scalarplot!(p[1,1],grid,U[1,:],clear=true,title=\"U1, eps=$(xeps)\")\n scalarplot!(p[2,1],grid,U[2,:],clear=true,title=\"U2, eps=$(xeps)\",reveal=true)\n sleep(0.2)\n u5=U[5]\n end\n return u5\nend\n\nfunction test()\n testval=0.7117546972922056\n main(unknown_storage=:sparse) ≈ testval && main(unknown_storage=:dense) ≈ testval\nend\nend\n\n", "meta": {"hexsha": "7712340bed0812fd05fc6c16249562977c90fd5a", "size": 2855, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Example110_ReactionDiffusion1D_TwoSpecies.jl", "max_stars_repo_name": "mattlie82/VoronoiFVM.jl", "max_stars_repo_head_hexsha": "819cdc967f4cf8fad6b14e271296b365ff6e51c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/Example110_ReactionDiffusion1D_TwoSpecies.jl", "max_issues_repo_name": "mattlie82/VoronoiFVM.jl", "max_issues_repo_head_hexsha": "819cdc967f4cf8fad6b14e271296b365ff6e51c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/Example110_ReactionDiffusion1D_TwoSpecies.jl", "max_forks_repo_name": "mattlie82/VoronoiFVM.jl", "max_forks_repo_head_hexsha": "819cdc967f4cf8fad6b14e271296b365ff6e51c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4329896907, "max_line_length": 94, "alphanum_fraction": 0.4756567426, "num_tokens": 892, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897509188344, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.801508460821994}} {"text": "# Calcul des distances a vol d'oiseau entre 2 coordonnees GPS\n# X. Gandibleux - Octobre 2019\n\nusing Printf\nusing DelimitedFiles\n\n# Donnees dans un fichier au format CSV séparé par des virgules avec :\n# - ligne 1 : header\n# - colonne 1 : nom du lieu\n# - colonne 2 : position x du lieu\n# - colonne 3 : position y du lieu\n# - colonne 4 : latitude du lieu\n# - colonne 5 : longitude du lieu\n# donnees extraites de : https://data.education.gouv.fr\nm = readdlm(\"GPSlyceesNantes.csv\", ',')\n\n# Fonction de conversion degre vers radian\nfunction deg_rad(v)\n return pi/180*v\nend\n\n# Calcul du distancier\nlieu = String[]\nfor i in 2:size(m,1)\n push!(lieu, m[i,1])\nend\n\ndist = zeros(size(m,1)-1, size(m,1)-1)\nfor i in 2:size(m,1)-1\n for j in i+1:size(m,1)\n\n LatitudeA = m[i,4]\n LongitudeA = m[i,5]\n LatitudeB = m[j,4]\n LongitudeB = m[j,5]\n\n # formule des sinus : http://villemin.gerard.free.fr/aGeograp/Distance.htm\n # https://www.coordonnees-gps.fr/conversion-coordonnees-gps\n\n d = acos(\n sin(deg_rad(LatitudeA)) * sin(deg_rad(LatitudeB))\n +\n cos(deg_rad(LatitudeA)) * cos(deg_rad(LatitudeB)) * cos(deg_rad(LongitudeB) - deg_rad(LongitudeA))\n ) * 6371\n\n @printf(\"%2d - %2d = %6.3f km | %s <-> %s \\n\",i-1, j-1, d, m[i,1], m[j,1])\n\n dist[i-1,j-1] = d\n dist[j-1,i-1] = d\n end\nend\n\nprintln(\"distancier symétrique crée : \", length(lieu), \" lieux\")\n", "meta": {"hexsha": "223fab2d9b5686e7044f5d2500d55f5e4ebf4779", "size": 1459, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "gpsdistancier.jl", "max_stars_repo_name": "xgandibleux/distances", "max_stars_repo_head_hexsha": "97e203b05c2506231e4297a5bfcda55c8a50ba27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gpsdistancier.jl", "max_issues_repo_name": "xgandibleux/distances", "max_issues_repo_head_hexsha": "97e203b05c2506231e4297a5bfcda55c8a50ba27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gpsdistancier.jl", "max_forks_repo_name": "xgandibleux/distances", "max_forks_repo_head_hexsha": "97e203b05c2506231e4297a5bfcda55c8a50ba27", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0185185185, "max_line_length": 111, "alphanum_fraction": 0.6120630569, "num_tokens": 496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897459384732, "lm_q2_score": 0.8519528019683105, "lm_q1q2_score": 0.8015084601153372}} {"text": "using Distributions\n\n\npoints = [1, 14, 2, 3, 4, 7, 9, 15, 22, 4]\nfunction GMM(points::Array; k::Int64 = 2, tol::Float64 = .001)\n\n prior = 1 / k\n n = length(points)\n @assert n > k \"Need more data points than latent classes!\"\n\n post = repmat([prior], n, k)\n post = hcat(post, points)\n\n # initial random latent gaussians\n sd = sqrt(var(points))\n gauss = [Distributions.Normal(rand(points), sd) for i in 1:k]\n\n est_mu(w, points) = sum(w .* points) / sum(w)\n est_var(w, mu, points) = sum(w .* (points - mu).^2) / sum(w)\n\n prev = post[:, 1]\n converged = false\n\n while !converged\n\n # for each point, compute the posterior of belonging to each latent gaussian\n for i in 1:n\n p = post[i, end]\n normalizer = sum([pdf(norm, p) for norm in gauss]) * prior\n\n for j in 1:k\n post[i, j] = (pdf(gauss[j], p) * prior) / normalizer\n end\n end\n\n diff = sum(abs(prev - post[:, 1]))\n\n if diff < tol\n converged = true\n else\n prev = post[:, 1]\n end\n\n mus = [est_mu(post[:, i], points) for i in 1:k]\n vars = [est_var(post[:, i], mus[i], points) for i in 1:k]\n gauss = [Distributions.Normal(mus[i], sqrt(vars[i])) for i in 1:k]\n end\n\n post\nend\n", "meta": {"hexsha": "def6c8f5f75ce6b5e67aae7c83dc7874f5da8aab", "size": 1313, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/GMM.jl", "max_stars_repo_name": "fdabl/EyeFix.jl", "max_stars_repo_head_hexsha": "1bc6540d8620a144af5c01a00b2c884edc174d1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/GMM.jl", "max_issues_repo_name": "fdabl/EyeFix.jl", "max_issues_repo_head_hexsha": "1bc6540d8620a144af5c01a00b2c884edc174d1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GMM.jl", "max_forks_repo_name": "fdabl/EyeFix.jl", "max_forks_repo_head_hexsha": "1bc6540d8620a144af5c01a00b2c884edc174d1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7450980392, "max_line_length": 84, "alphanum_fraction": 0.5323686215, "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951570602081, "lm_q2_score": 0.8577681122619883, "lm_q1q2_score": 0.8014943699782788}} {"text": "# GaussQuadrature.jl\nmutable struct DNq\n n::Array{Float64, 2}\n w::Array{Float64, 1}\nend\n\n\"\"\"\n initializenode(ndims::Int, quadpts::Int)\nInitialize the nodes and weights of Gauss-Hermite quadrature (Multidimentional version).\nGenerate `ndims` dimensional quadrature nodes and weights.\n\n# Arguments\n\n# Optional arguments\n\n- `dentype`\n - `:DN` Discrete normal\n - `:GH` Gauss-Hermite quadrature\n\n# Example\n```julia\nghn = initializenode(3, 21)\n```\n\"\"\"\nfunction initializenode(ndims, quadpts; θrange = (-4, 4))\n nodes = range(θrange[1], stop = θrange[2], length = quadpts) \n weights = pdf.(Normal(), nodes) ./ sum(pdf.(Normal(), nodes))\n ghn = Dict(zip(1:quadpts, nodes))\n ghw = Dict(zip(1:quadpts, weights))\n # https://stackoverflow.com/questions/54256481/converting-array-of-cartesianindex-to-2d-matrix-in-julia\n as_ints(a::AbstractArray{CartesianIndex{L}}) where L = reshape(reinterpret(Int, a), (L, size(a)...))\n idx = convert(Matrix, as_ints(vec(CartesianIndices(Array{Float64}(undef, Tuple(fill(quadpts, ndims))))))')\n n = [ghn[idx[i, j]] for i in axes(idx, 1), j in axes(idx, 2)]\n w = prod([ghw[idx[i, j]] for i in axes(idx, 1), j in axes(idx, 2)], dims = 2)[:]\n return DNq(n, w)\nend\n", "meta": {"hexsha": "617fb1eed36a252b01eac3f9b9e4fc5ab4bbefe9", "size": 1229, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/GaussQuadrature.jl", "max_stars_repo_name": "takuizum/irtfun.jl", "max_stars_repo_head_hexsha": "326555ca78fcfee5d0894e3b5dd0dc261059d4c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/GaussQuadrature.jl", "max_issues_repo_name": "takuizum/irtfun.jl", "max_issues_repo_head_hexsha": "326555ca78fcfee5d0894e3b5dd0dc261059d4c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GaussQuadrature.jl", "max_forks_repo_name": "takuizum/irtfun.jl", "max_forks_repo_head_hexsha": "326555ca78fcfee5d0894e3b5dd0dc261059d4c0", "max_forks_repo_licenses": ["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.2162162162, "max_line_length": 110, "alphanum_fraction": 0.6680227828, "num_tokens": 395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951680216529, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.8014943674897321}} {"text": "# # Logistic regression\nusing DataFrames\nusing Plots\nusing RDatasets\nusing Convex\nusing SCS\n\n#-\n\n## we'll use iris data\n## predict whether the iris species is versicolor using the sepal length and width and petal length and width\niris = dataset(\"datasets\", \"iris\")\n## outcome variable: +1 for versicolor, -1 otherwise\nY = [species == \"versicolor\" ? 1.0 : -1.0 for species in iris.Species]\n## create data matrix with one column for each feature (first column corresponds to offset)\nX = hcat(ones(size(iris, 1)), iris.SepalLength, iris.SepalWidth, iris.PetalLength, iris.PetalWidth);\n\n#-\n\n## solve the logistic regression problem\nn, p = size(X)\nbeta = Variable(p)\nproblem = minimize(logisticloss(-Y.*(X*beta)))\n\nsolve!(problem, SCSSolver(verbose=false))\n\n#-\n\n## let's see how well the model fits\nusing Plots\nlogistic(x::Real) = inv(exp(-x) + one(x))\nperm = sortperm(vec(X*beta.value))\nplot(1:n, (Y[perm] .+ 1)/2, st=:scatter)\nplot!(1:n, logistic.(X*beta.value)[perm])\n", "meta": {"hexsha": "97b3c0b5f38e199962482410ba99b652fba06af3", "size": 966, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/examples_literate/general_examples/logistic_regression.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/general_examples/logistic_regression.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/general_examples/logistic_regression.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": 27.6, "max_line_length": 109, "alphanum_fraction": 0.7142857143, "num_tokens": 279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214480969029, "lm_q2_score": 0.8311430520409024, "lm_q1q2_score": 0.8014890715197626}} {"text": "function generatemonomials(x,m,;option=0)\n mons = [];\n if option == 0\n mons = monomials(x,[1:m;], mon -> (degree(mon) == m));\n elseif 1 <= option <= n\n mons = monomials(x,[1:m;], mon -> ((degree(mon) == m)&&(degree(mon,x[option])<=1)));\n else \n throw(DomainError(option,\"option must be non-negative and <=$(n)\"))\n end\n return mons\nend\n\nfunction differentiatepow(u,var::MP.AbstractVariable;power=1)\n res = u;\n if power>1\n res = differentiate(differentiatepow(u,var,power=power-1),var);\n elseif power==1\n res = differentiate(u,var);\n elseif power < 0\n throw(DomainError(power,\"power must be non-negative\"));\n end\n return res;\nend\n\nfunction dalpha(u,alpha,vars)\n if length(alpha) != length(vars)\n throw(DomainError(alpha,\"alpha must be a valid multi-index for the variables x\"))\n end\n res = u;\n for i in 1:1:length(alpha)\n res = differentiatepow(res,vars[i],power=alpha[i]);\n end \n return res;\nend\n\nfunction polyderivative(u,poly,vars)\n pterms = terms(poly);\n pcoefs = map(coefficient,pterms);\n pmons = map(monomial,pterms);\n fixedexp = z -> exponents(prod(vars.^0)*z);\n ppows = map(fixedexp,pmons);\n Dvec = map(z->dalpha(u,z,vars),ppows);\n if length(pcoefs)!= length(Dvec)\n throw(ErrorException(\"poly was not well defined\"))\n end\n return sum(pcoefs[i]*Dvec[i] for i in 1:1:length(Dvec));\nend\n\nfunction laplacian(u,vars,;power=1)\n res = u;\n if power > 1\n res = polyderivative(laplacian(u,vars,power=power-1),sum(vars.*vars),vars);\n elseif power == 1\n res = polyderivative(u,sum(vars .* vars),vars);\n elseif power < 0 \n throw(DomainError(power,\"power must be non-negative\"));\n end \n return res;\nend\n\nfunction normpartialder(hvec,var::MP.AbstractVariable,vars,;power=1)\n res = hvec;\n if power>1\n der = normpartialder(hvec,var,vars,power=power-1)\n res = (der[1]-2,der[1]*var*der[2]+sum(vars.*vars)*differentiate(der[2],var));\n elseif power==1\n res = (hvec[1]-2,hvec[1]*var*hvec[2]+sum(vars.*vars)*differentiate(hvec[2],var));\n elseif power < 0\n throw(DomainError(power,\"power must be non-negative\"));\n end\n return res;\n return \nend\n\nfunction normdalpha(hvec,alpha,vars)\n if length(alpha) != length(vars)\n throw(DomainError(alpha,\"alpha must be a valid multi-index for the variables x\"))\n end\n res = hvec;\n for i in 1:1:length(alpha)\n res = normpartialder(res,vars[i],vars,power=alpha[i]);\n end \n return res;\nend\n\nfunction normpolyderivative(hvec,poly,vars)\n pterms = terms(poly);\n pcoefs = map(coefficient,pterms);\n pmons = map(monomial,pterms);\n fixedexp = z -> exponents(prod(vars.^0)*z);\n ppows = map(fixedexp,pmons);\n Dvec = map(z->normdalpha(hvec,z,x),ppows);\n if length(pcoefs)!= length(Dvec)\n throw(ErrorException(\"poly was not well defined\"))\n end\n return Dvec\nend\n\nfunction generatebasissphere(m, vars)\n n = length(vars)\n genpoly = (2-n,1);\n monos = generatemonomials(vars,m,option=1);\n fixedexp = z -> exponents(prod(vars.^0)*z);\n mpows = map(fixedexp,monos)\n return map(m->normdalpha(genpoly,m,vars)[2],mpows)\nend\n\nfunction dcoefficient(n,m,i,j)\n d = 0;\n if i == j\n d = 1.0/(2.0^j*factorial(j)*prod([(2*m + n - 2*j - 2*l) for l in 1:j]));\n elseif i < j\n d = -dcoefficient(n,m,i,j-1)/(2*(j-i)*(2*m+n-2-2*i-2*j));\n end\n return d;\nend\n\nfunction harmonicdecomposition(u,vars)\n norm = sum(vars .* vars);\n n =length(vars);\n m = maxdegree(u);\n if mindegree(u) != m\n throw(DomainError(u,\"polynomial must be homogeneous\"));\n end\n return [ (2*i,sum([dcoefficient(n,m,i,j)*norm^(j-i)*laplacian(u,vars,power=j) for j in i:floor(Int,m/2)])) for i in 0:floor(Int,m/2) ];\nend\n\n", "meta": {"hexsha": "b97168a841849d37515013e979c3144040b85956", "size": 3837, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/HarmonicBases.jl", "max_stars_repo_name": "SergioCS147/HarmonicPolya", "max_stars_repo_head_hexsha": "83f51bfae88529924c814c15ca3f5050d205e84a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/HarmonicBases.jl", "max_issues_repo_name": "SergioCS147/HarmonicPolya", "max_issues_repo_head_hexsha": "83f51bfae88529924c814c15ca3f5050d205e84a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/HarmonicBases.jl", "max_forks_repo_name": "SergioCS147/HarmonicPolya", "max_forks_repo_head_hexsha": "83f51bfae88529924c814c15ca3f5050d205e84a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9765625, "max_line_length": 139, "alphanum_fraction": 0.6194943967, "num_tokens": 1188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214480969029, "lm_q2_score": 0.8311430478583169, "lm_q1q2_score": 0.8014890674864057}} {"text": "function sieve(n :: Int)\n isprime = trues(n)\n isprime[1] = false\n for p in 2:n\n if isprime[p]\n j = p * p\n if j > n\n return findall(isprime)\n else\n for k in j:p:n\n isprime[k] = false\n end\n end\n end\n end\nend\n", "meta": {"hexsha": "54f618a7e094b88bd7fe3e1df5f51686827452a7", "size": 338, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/sieve-of-eratosthenes-2.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/sieve-of-eratosthenes-2.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/sieve-of-eratosthenes-2.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.8823529412, "max_line_length": 39, "alphanum_fraction": 0.3816568047, "num_tokens": 90, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9748211604938802, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.8014873666080854}} {"text": "# # Holomorphic integration on the unit disk\n# In this example, we explore integration of a harmonic function:\n# ```math\n# f(x,y) = \\frac{x^2-y^2+1}{(x^2-y^2+1)^2+(2xy+1)^2},\n# ```\n# over the unit disk. In this case, we know from complex analysis that the\n# integral of a holomorphic function is equal to $\\pi \\times f(0,0)$.\n# We analyze the function on an $N\\times M$ tensor product grid defined by:\n# ```math\n# \\begin{aligned}\n# r_n & = \\cos\\left[(n+\\tfrac{1}{2})\\pi/2N\\right],\\quad{\\rm for}\\quad 0\\le n < N,\\quad{\\rm and}\\\\\n# \\theta_m & = 2\\pi m/M,\\quad{\\rm for}\\quad 0\\le m < M;\n# \\end{aligned}\n# ```\n# we convert the function samples to Chebyshev×Fourier coefficients using\n# `plan_disk_analysis`; and finally, we transform the Chebyshev×Fourier\n# coefficients to Zernike polynomial coefficients using `plan_disk2cxf`.\n#\n# For the storage pattern of the arrays, please consult the\n# [documentation](https://MikaelSlevinsky.github.io/FastTransforms).\n\nusing FastTransforms, LinearAlgebra, Plots\nconst GENFIGS = joinpath(pkgdir(FastTransforms), \"docs/src/generated\")\n!isdir(GENFIGS) && mkdir(GENFIGS)\nplotlyjs()\n\n# Our function $f$ on the disk:\nf = (x,y) -> (x^2-y^2+1)/((x^2-y^2+1)^2+(2x*y+1)^2)\n\n# The Zernike polynomial degree:\nN = 15\nM = 4N-3\n\n# The radial grid:\nr = [sinpi((N-n-0.5)/(2N)) for n in 0:N-1]\n\n# The angular grid (mod $\\pi$):\nθ = (0:M-1)*2/M\n\n# On the mapped tensor product grid, our function samples are:\nF = [f(r*cospi(θ), r*sinpi(θ)) for r in r, θ in θ]\n\n# We superpose a surface plot of $f$ on top of the grid:\nX = [r*cospi(θ) for r in r, θ in θ]\nY = [r*sinpi(θ) for r in r, θ in θ]\nscatter3d(vec(X), vec(Y), vec(0F); markersize=0.75, markercolor=:red)\nsurface!(X, Y, F; legend=false, xlabel=\"x\", ylabel=\"y\", zlabel=\"f\")\nsavefig(joinpath(GENFIGS, \"zernike.html\"))\n###```@raw html\n###\n###```\n\n# We precompute a (generalized) Zernike--Chebyshev×Fourier plan:\nα, β = 0, 0\nP = plan_disk2cxf(F, α, β)\n\n# And an FFTW Chebyshev×Fourier analysis plan on the disk:\nPA = plan_disk_analysis(F)\n\n# Its Zernike coefficients are:\nU = P\\(PA*F)\n\n# The Zernike coefficients are useful for integration. The integral of $f(x,y)$\n# over the disk should be $\\pi/2$ by harmonicity. The coefficient of $Z_{0,0}$\n# multiplied by `√π` is:\nU[1, 1]*sqrt(π)\n\n# Using an orthonormal basis, the integral of $[f(x,y)]^2$ over the disk is\n# approximately the square of the 2-norm of the coefficients:\nnorm(U)^2, π/(2*sqrt(2))*log1p(sqrt(2))\n\n# But there's more! Next, we repeat the experiment using the Dunkl-Xu\n# orthonormal polynomials supported on the rectangularized disk.\nN = 2N\nM = N\n\n# We analyze the function on an $N\\times M$ mapped tensor product $xy$-grid defined by:\n# ```math\n# \\begin{aligned}\n# x_n & = \\cos\\left(\\frac{2n+1}{2N}\\pi\\right) = \\sin\\left(\\frac{N-2n-1}{2N}\\pi\\right),\\quad {\\rm for} \\quad 0 \\le n < N,\\quad{\\rm and}\\\\\n# z_m & = \\cos\\left(\\frac{2m+1}{2M}\\pi\\right) = \\sin\\left(\\frac{M-2m-1}{2M}\\pi\\right),\\quad {\\rm for} \\quad 0 \\le m < M,\\\\\n# y_{n,m} & = \\sqrt{1-x_n^2}z_m.\n# \\end{aligned}\n# ```\n# Slightly more accuracy can be expected by using an auxiliary array:\n# ```math\n# w_n = \\sin\\left(\\frac{2n+1}{2N}\\pi\\right),\\quad {\\rm for} \\quad 0 \\le n < N,\n# ```\n# so that $y_{n,m} = w_nz_m$.\n#\n# The x grid\nw = [sinpi((n+0.5)/N) for n in 0:N-1]\nx = [sinpi((N-2n-1)/(2N)) for n in 0:N-1]\n\n# The z grid\nz = [sinpi((M-2m-1)/(2M)) for m in 0:M-1]\n\n# On the mapped tensor product grid, our function samples are:\nF = [f(x[n], w[n]*z) for n in 1:N, z in z]\n\n# We superpose a surface plot of $f$ on top of the grid:\nX = [x for x in x, z in z]\nY = [w*z for w in w, z in z]\nscatter3d(vec(X), vec(Y), vec(0F); markersize=0.75, markercolor=:green)\nsurface!(X, Y, F; legend=false, xlabel=\"x\", ylabel=\"y\", zlabel=\"f\")\nsavefig(joinpath(GENFIGS, \"dunklxu.html\"))\n###```@raw html\n###\n###```\n\n# We precompute a Dunkl-Xu--Chebyshev plan:\nP = plan_rectdisk2cheb(F, β)\n\n# And an FFTW Chebyshev² analysis plan on the rectangularized disk:\nPA = plan_rectdisk_analysis(F)\n\n# Its Dunkl-Xu coefficients are:\nU = P\\(PA*F)\n\n# The Dunkl-Xu coefficients are useful for integration. The integral of $f(x,y)$\n# over the disk should be $\\pi/2$ by harmonicity. The coefficient of $P_{0,0}$\n# multiplied by `√π` is:\nU[1, 1]*sqrt(π)\n\n# Using an orthonormal basis, the integral of $[f(x,y)]^2$ over the disk is\n# approximately the square of the 2-norm of the coefficients:\nnorm(U)^2, π/(2*sqrt(2))*log1p(sqrt(2))\n", "meta": {"hexsha": "19db17317febf0d10f808ade92175d45f4785d7b", "size": 4578, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/disk.jl", "max_stars_repo_name": "MikaelSlevinsky/FastTransforms.jl", "max_stars_repo_head_hexsha": "cc105282a3c112927dfcc816c1fee1a83c99a1ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 54, "max_stars_repo_stars_event_min_datetime": "2016-02-12T17:43:10.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-10T10:27:51.000Z", "max_issues_repo_path": "examples/disk.jl", "max_issues_repo_name": "MikaelSlevinsky/FastTransforms.jl", "max_issues_repo_head_hexsha": "cc105282a3c112927dfcc816c1fee1a83c99a1ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 61, "max_issues_repo_issues_event_min_datetime": "2016-02-18T08:54:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-12T19:21:46.000Z", "max_forks_repo_path": "examples/disk.jl", "max_forks_repo_name": "MikaelSlevinsky/FastTransforms.jl", "max_forks_repo_head_hexsha": "cc105282a3c112927dfcc816c1fee1a83c99a1ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2016-02-17T09:33:15.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-14T14:43:49.000Z", "avg_line_length": 35.765625, "max_line_length": 136, "alphanum_fraction": 0.6616426387, "num_tokens": 1663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628702, "lm_q2_score": 0.8652240773641087, "lm_q1q2_score": 0.8014602939230427}} {"text": "# Parts of this code were taken / derived from Graphs.jl. See LICENSE for\n# licensing details.\n\n\ntype FloydWarshallState{T}<:AbstractPathState\n dists::Matrix{T}\n parents::Matrix{Int}\nend\n\ndoc\"\"\"Uses the [Floyd-Warshall algorithm](http://en.wikipedia.org/wiki/Floyd–Warshall_algorithm)\nto compute shortest paths between all pairs of vertices in graph `g`. Returns a\n`FloydWarshallState` with relevant traversal information, each is a\nvertex-indexed vector of vectors containing the metric for each vertex in the\ngraph.\n\nNote that this algorithm may return a large amount of data (it will allocate\non the order of $\\mathcal{O}(nv^2)$).\n\"\"\"\nfunction floyd_warshall_shortest_paths{T}(\n g::SimpleGraph,\n distmx::AbstractArray{T, 2} = DefaultDistance()\n)\n\n n_v = nv(g)\n dists = fill(typemax(T), (n_v,n_v))\n parents = zeros(Int, (n_v,n_v))\n\n # fws = FloydWarshallState(Matrix{T}(), Matrix{Int}())\n for v in 1:n_v\n dists[v,v] = zero(T)\n end\n undirected = !is_directed(g)\n for e in edges(g)\n u = src(e)\n v = dst(e)\n\n d = distmx[u,v]\n\n dists[u,v] = min(d, dists[u,v])\n parents[u,v] = u\n if undirected\n dists[v,u] = min(d, dists[v,u])\n parents[v,u] = v\n end\n end\n for w in vertices(g), u in vertices(g), v in vertices(g)\n if dists[u,w] == typemax(T) || dists[w,v] == typemax(T)\n ans = typemax(T)\n else\n ans = dists[u,w] + dists[w,v]\n end\n if dists[u,v] > ans\n dists[u,v] = dists[u,w] + dists[w,v]\n parents[u,v] = parents[w,v]\n end\n end\n fws = FloydWarshallState(dists, parents)\n # for r in 1:size(parents,1) # row by row\n # push!(fws.parents, vec(parents[r,:]))\n # end\n # for r in 1:size(dists,1)\n # push!(fws.dists, vec(dists[r,:]))\n # end\n\n return fws\nend\n\nfunction enumerate_paths(s::FloydWarshallState, v::Integer)\n pathinfo = s.parents[v,:]\n paths = Vector{Int}[]\n for i in 1:length(pathinfo)\n if i == v\n push!(paths, Vector{Int}())\n else\n path = Vector{Int}()\n currpathindex = i\n while currpathindex != 0\n push!(path,currpathindex)\n currpathindex = pathinfo[currpathindex]\n end\n push!(paths, reverse(path))\n end\n end\n return paths\nend\n\nenumerate_paths(s::FloydWarshallState) = [enumerate_paths(s, v) for v in 1:size(s.parents,1)]\nenumerate_paths(st::FloydWarshallState, s::Integer, d::Integer) = enumerate_paths(st, s)[d]\n", "meta": {"hexsha": "c2f5bdc6191e665f9489037d60c7ce557bc901ce", "size": 2586, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/shortestpaths/floyd-warshall.jl", "max_stars_repo_name": "JuliaPackageMirrors/LightGraphs.jl", "max_stars_repo_head_hexsha": "b13472899cba49999567bb88f9d32d5d87cf4a19", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/shortestpaths/floyd-warshall.jl", "max_issues_repo_name": "JuliaPackageMirrors/LightGraphs.jl", "max_issues_repo_head_hexsha": "b13472899cba49999567bb88f9d32d5d87cf4a19", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/shortestpaths/floyd-warshall.jl", "max_forks_repo_name": "JuliaPackageMirrors/LightGraphs.jl", "max_forks_repo_head_hexsha": "b13472899cba49999567bb88f9d32d5d87cf4a19", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0561797753, "max_line_length": 96, "alphanum_fraction": 0.594354215, "num_tokens": 744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037323284109, "lm_q2_score": 0.8652240756264638, "lm_q1q2_score": 0.8014602905531927}} {"text": "export modnewton\n\n\"\"\"\nmodnewton(f,df,H,x)\n\nNewton method with Hessian shift for solving min_x f(x)\n\n\"\"\"\nfunction modnewton(f::Function,df::Function,H::Function,x::Vector;maxIter=20,atol=1e-8,out::Int=0,\n\tstoreInterm::Bool=false,beta=1e-1,\n\t\tlineSearch::Function=(f,df,fk,dfk,xk,pk)->armijo(f,fk,dfk,xk,pk,maxIter=10))\n\n his = zeros(maxIter,4)\n X = (storeInterm) ? zeros(length(x),maxIter) : []\n i = 1; flag = -1; LL = []\n while i<=maxIter\n fk = f(x)\n dfk = df(x)\n his[i,1:2] = [norm(fk) norm(dfk)]\n if storeInterm; X[:,i] = x; end;\n\n if(norm(dfk) 0) ? 0 : -minimum(diag(d2f))+beta\n nfac = 0;\n for k=1:20\n try\n nfac +=1\n LL = cholfact(d2f + tau*speye(length(x))) \n break;\n catch err\n if isa(err,Base.LinAlg.PosDefException) && k<20\n tau = max(2*tau,beta)\n elseif isa(err,Base.LinAlg.PosDefException) \n flag = -2\n his[i,4] = nfac\n his = his[1:i,:]\n break; break;\n else\n throw(err)\n end\n end\n end\n his[i,4] = nfac\n pk = - (LL\\dfk)\n \n # line search\n\t\tak,his[i,3] = lineSearch(f,df,fk,dfk,x,pk) \n if his[i,3]==-1\n flag = -3\n his = his[1:i,:]\n break\n end\n if out>0\n @printf \"iter=%04d\\t|f|=%1.2e\\t|df|=%1.2e\\tLS=%d\\n\" i his[i,1] his[i,2] his[i,3]\n end\n # update x and H\n x += ak*pk\n\n i+=1 \n end\n i = min(maxIter,i)\n\n if out>=0\n if flag==-1\n println(@sprintf(\"modnewton iterated maxIter (=%d) times but reached only atol of %1.2e instead of tol=%1.2e\",i,his[i,2],atol))\n elseif flag==-2\n println(@sprintf(\"modnewton stopped because the Hessian at iteration %d was not positive definite.\",i))\n elseif flag==-3\n println(@sprintf(\"modnewton stopped of a line search fail at iteration %d.\",i))\n\t\telseif out>1\n println(@sprintf(\"modnewton achieved desired atol of %1.2e at iteration %d.\",atol,i))\n end\n end\n if storeInterm; X = X[:,1:i]; end\n return x,flag,his,X\nend", "meta": {"hexsha": "1c5fe4727194dde6f2d4992568959ac2cff13cdb", "size": 2472, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/modnewton.jl", "max_stars_repo_name": "lruthotto/OptimTools.jl", "max_stars_repo_head_hexsha": "977feb8f2fd5e04d3f3b2a700b8abc992740cedb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/modnewton.jl", "max_issues_repo_name": "lruthotto/OptimTools.jl", "max_issues_repo_head_hexsha": "977feb8f2fd5e04d3f3b2a700b8abc992740cedb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/modnewton.jl", "max_forks_repo_name": "lruthotto/OptimTools.jl", "max_forks_repo_head_hexsha": "977feb8f2fd5e04d3f3b2a700b8abc992740cedb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7831325301, "max_line_length": 139, "alphanum_fraction": 0.4854368932, "num_tokens": 772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070158103778, "lm_q2_score": 0.8807970701552505, "lm_q1q2_score": 0.801443433639488}} {"text": "#!/usr/bin/env julia\n\n#=\n# data should be sorted and works by divide and conquer\n# run-time complexity O(log n)\n=#\n\n\nfunction binary_search(search_for, data_array, low=1, high=-1)\n if high == -1\n high = length(data_array)\n end\n if high < low\n return -1\n end\n mid = Int(floor(low + (high - low) / 2))\n if data_array[mid] == search_for\n return mid\n end\n if data_array[mid] > search_for\n return binary_search(search_for, data_array, low, mid-1)\n else\n return binary_search(search_for, data_array, mid+1, high)\n end\nend\n\n ## 1 2 3 4 5 6 7 8 9 10\ndata = [10, 11, 12, 22, 24, 27, 34, 47, 56, 67]\n\n@time println(\"at index: \", binary_search(47, data))\n@time println(\"at index: \", binary_search(12, data))\n@time println(\"at index: \", binary_search(7, data))\n@time println(\"at index: \", binary_search(67, data))\n@time println(\"at index: \", binary_search(34, data))\n", "meta": {"hexsha": "157686518deba1c96a8455cdfecd35175d6ea405", "size": 902, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "talks-articles/reference/algorithms/binary-search.jl", "max_stars_repo_name": "abhishekkr/tutorials_as_code", "max_stars_repo_head_hexsha": "f355dc62a5025b710ac6d4a6ac2f9610265fad54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37, "max_stars_repo_stars_event_min_datetime": "2015-02-01T23:16:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T16:50:48.000Z", "max_issues_repo_path": "talks-articles/reference/algorithms/binary-search.jl", "max_issues_repo_name": "abhishekkr/tutorials_as_code", "max_issues_repo_head_hexsha": "f355dc62a5025b710ac6d4a6ac2f9610265fad54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-02T04:55:48.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-14T10:51:11.000Z", "max_forks_repo_path": "talks-articles/reference/algorithms/binary-search.jl", "max_forks_repo_name": "abhishekkr/tutorials_as_code", "max_forks_repo_head_hexsha": "f355dc62a5025b710ac6d4a6ac2f9610265fad54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2015-03-02T08:09:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-10T03:25:41.000Z", "avg_line_length": 25.7714285714, "max_line_length": 62, "alphanum_fraction": 0.6485587583, "num_tokens": 301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070158103778, "lm_q2_score": 0.8807970654616712, "lm_q1q2_score": 0.8014434293687672}} {"text": "module BifurcationLib\n\n# a demonstration of bifurcation using the logistic map\n\n# equation: x_n+1 = r x_n (1-x_n)\n\n# how does equilibrium change as the parameter r changes?\n\nusing Plots\n# using ArgParse\n\n### utility functions:\n\n# rounds x to an aribtrary number of decimal places\nfunction decimal_round(x::AbstractFloat, num_decimal_places::Unsigned)::AbstractFloat\n rounding_factor = 10^num_decimal_places\n round(rounding_factor * x)/rounding_factor\nend\n\n### Logistic map stuff\n\n# gives logistic map of a value x and parameter (growth rate) r\nlogistic_map(x, r) = r*x*(1-x)\n\n# gives many results of logistic map, starting with nth iteration and returning\n# the results of m iterations after the nth\nfunction logistic_map_series(x, r, n, m)\n nth_x = x\n for i = 1:n\n nth_x = logistic_map(nth_x, r)\n end\n\n mth_x = nth_x\n series = []\n for i = 1:m\n mth_x = logistic_map(mth_x, r)\n append!(series, [mth_x])\n end\n series\nend\n\n### Plotting things\n\n# r0: first r to use\n\n# r_inc: amount to increment r by each time \n\n# r_final: final r (if r_final-r0 is not divisibible by r_inc then the actual\n# final r will be slightly less than r_final)\n\nfunction generate_points(x0, r0, n, m, r_inc, r_final)\n x = []\n y = []\n\n for r = r0:r_inc:r_final\n this_x = fill(r, (m))\n this_y = logistic_map_series(x0, r, n, m)\n append!(x, this_x)\n append!(y, this_y)\n end\n\n x, y\nend\n\nfunction plot_points(x, y, n, m)\n # set backend\n gr()\n\n # create plot\n plot(x, y,\n seriestype = :scatter, \n title = \"Values of recursive iterations of logistic map for various r\",\n xlabel = \"r\",\n ylabel = string(\"next \", m, \" values after first \", n, \" iterations\"),\n dpi = 1000,\n markersize = 1,\n markeralpha = 0.5,\n # markeralpha = 0.1,\n # markerstrokestyle = :dot,\n # markerstrokecolor = :blue,\n markerstrokewidth = 0,\n markerfillcolor = :blue,\n )\nend\n\nfunction generate_and_plot(x0, r0, n, m, r_inc, r_final)\n println(\"generating points for plot with the following parameters:\")\n println(\"x0 = \", x0)\n println(\"r0 = \", r0)\n println(\"n = \", n)\n println(\"m = \", m)\n println(\"r_inc = \", r_inc)\n println(\"r_final = \", r_final)\n println()\n\n println(\"total number of poins to generate: \",\n floor( (r_final-r0) * r_inc ) * (n + m)\n )\n println()\n\n println(\"generating...\")\n x, y = generate_points(x0, r0, n, m, r_inc, r_final)\n\n println(\"points generated. Plotting...\")\n p = plot_points(x, y, n, m)\n # display(p)\n filename = string(\n \"x0=\", x0, \",\",\n \"r0=\", r0, \",\",\n \"n=\", n, \",\",\n \"m=\", m, \",\",\n \"r_inc=\", r_inc, \",\",\n \"r_final=\", r_final, \".png\")\n println(\"saving figure to \", filename)\n savefig(p, filename)\n println(\"done.\")\n # p\nend\n\nfunction example_plot()\n x0 = 0.5\n r0 = 0.0\n n = 100\n m = 100\n r_inc = 0.01\n r_final = 4.0 # seems like anything higher than this diverges quickly to -inf\n\n generate_and_plot(x0, r0, n, m, r_inc, r_final)\nend\n\nend # module\n", "meta": {"hexsha": "a4f6dda8df71d431bdb949d81b7585bb9167b501", "size": 2976, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "math/Bifurcation/src/BifurcationLib.jl", "max_stars_repo_name": "rileyweber13/learning-sandbox", "max_stars_repo_head_hexsha": "668c13daf8620826cc674f4deacbddff3c477d92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "math/Bifurcation/src/BifurcationLib.jl", "max_issues_repo_name": "rileyweber13/learning-sandbox", "max_issues_repo_head_hexsha": "668c13daf8620826cc674f4deacbddff3c477d92", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-11-15T16:36:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-01T20:28:17.000Z", "max_forks_repo_path": "math/Bifurcation/src/BifurcationLib.jl", "max_forks_repo_name": "rileyweber13/learning-sandbox", "max_forks_repo_head_hexsha": "668c13daf8620826cc674f4deacbddff3c477d92", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5454545455, "max_line_length": 85, "alphanum_fraction": 0.6360887097, "num_tokens": 940, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070011518829, "lm_q2_score": 0.8807970779778824, "lm_q1q2_score": 0.8014434278461962}} {"text": "using Distributions\n\n# ρ(x,y) in integrand\nρ(x,y) = (0 < x < 1) && (0 < y < 2) ? 1/2 : 0\n\n#=\nImplementation of random walk sampler Metropolis-Hastings.\nInputs:\n- n: The number of states to return\n- b: The standard deviation of the normal distribution used in the proposal\n distribution\nOutputs:\n- Returns an array of length n denoting states S_i in Metropolis-Hastings alg.\n=#\nfunction metropolis_hastings(n, b)\n\n # Samples\n samples = zeros(n,2)\n samples[1,:] = rand(2)\n\n # Conditional Q distribution\n d = Normal(0,b)\n\n acceptances = 0\n\n for i=2:n\n # Propose Y\n ξx = rand(d)\n ξy = rand(d)\n X = samples[i-1,1] + ξx\n Y = samples[i-1,2] + ξy\n\n # Acceptance probability\n α = min(1, ρ(X,Y)/ρ(samples[i-1,1],samples[i-1,2]))\n\n # Next state\n if rand() < α\n samples[i,1] = X\n samples[i,2] = Y\n else\n samples[i,:] = samples[i-1,:]\n end\n end\n\n\n return samples\nend\n\n# Obtain 10000 samples with b = 1\nS = metropolis_hastings(10000,1)\n\n# f(x) in integrand\nf(x,y) = exp(sin(x*y))\n\n# Estimate integral\nM = 1000\nint_estimate = 2*mean([f(x,y) for (x,y) in zip(S[M:end,1], S[M:end,2])])\n", "meta": {"hexsha": "d3c17af90d9fb93bc3e7e73300de257002f6c7cc", "size": 1210, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "content/stochastic-approximations/code/metropolis_hastings_integral_2.jl", "max_stars_repo_name": "seanrattana/courses", "max_stars_repo_head_hexsha": "9453abc38af26ea49cb00fe1744066fc0de237b3", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2019-08-21T07:33:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-24T15:46:58.000Z", "max_issues_repo_path": "content/stochastic-approximations/code/metropolis_hastings_integral_2.jl", "max_issues_repo_name": "seanrattana/courses", "max_issues_repo_head_hexsha": "9453abc38af26ea49cb00fe1744066fc0de237b3", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-08-23T06:04:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-26T12:47:12.000Z", "max_forks_repo_path": "content/stochastic-approximations/code/metropolis_hastings_integral_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": 20.8620689655, "max_line_length": 78, "alphanum_fraction": 0.5768595041, "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810511092411, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.8014298354352538}} {"text": "\"\"\"\n calc_nchk(n::Integer,k::Integer)\n\nCalculates binomial coefficient: n choose k\n\"\"\"\nfunction calc_nchk(n::Integer,k::Integer)\n accum::Int = 1\n for i in 1:k\n accum = accum * (n-k+i) ÷ i\n end\n return accum\nend\n\n\n\"\"\"\n get_nchk(n::Integer,k::Integer)\n\nLooks up binomial coefficient from a precomputed table: n choose k\n\"\"\"\n@inline function get_nchk(n,k)\n return binom_coeff[n+1,k+1]\nend\n", "meta": {"hexsha": "5284c043f419ba4455f1366ba568092077b0a9c9", "size": 414, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/StringCI/Helpers.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/StringCI/Helpers.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/StringCI/Helpers.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": 18.0, "max_line_length": 66, "alphanum_fraction": 0.652173913, "num_tokens": 124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9473810451666345, "lm_q2_score": 0.8459424314825852, "lm_q1q2_score": 0.8014298248887756}} {"text": "\"\"\"\npde_lin_test(n)\n\nTest the linear operators.\n\"\"\"\nfunction pde_lin_test(n)\n h = 1.0 / (n + 1)\n x = collect(h:h:1.0-h)\n fdata = fishinit(n)\n z = rand(n, n)\n L2d = Lap2d(n)\n DX = Dx2d(n)\n DY = Dy2d(n)\n lapok = lap_test(n, x, z, L2d, fdata)\n discok = disc_test(n, x, L2d, DX, DY, fdata)\n lapok && discok\nend\n\n\"\"\"\ndisc_test()\nHave I broken the discretizations?\n\"\"\"\nfunction disc_test(n, x, L2d, DX, DY, fdata)\n n2 = n * n\n ue = solexact(x)\n ux = dxexact(x)\n uy = dyexact(x)\n D2u = l2dexact(x)\n ue1 = reshape(ue, (n2,))\n uex1 = reshape(ux, (n2,))\n uey1 = reshape(uy, (n2,))\n ued21 = reshape(D2u, (n2,))\n # test DX\n dx21 = DX * ue1\n dxerr = norm(dx21 - uex1, Inf)\n # test DY\n dy21 = DY * ue1\n dyerr = norm(dy21 - uey1, Inf)\n # test Laplacian\n du21 = L2d * ue1\n d2err = norm(du21 - ued21, Inf)\n pass = (d2err < 0.75) && (dxerr < 0.1) && (dyerr < 1.e-12)\n pass || println(\"Discretization test fails\")\n return pass\nend\n\n\"\"\"\nlap_test()\n\nDoes the FFT invert the discrete Laplacian?\nDoes the discrete Laplacian pass a simple eigenvalue test.\n\"\"\"\nfunction lap_test(n, x, z, L2d, fdata)\n randok = rand_test(z, n, L2d, fdata)\n eigok = eig_test(n, x, fdata)\n pass = randok && eigok\n return pass\nend\n\n\nfunction rand_test(z, n, L2d, fdata)\n n2 = n * n\n z1 = reshape(z, (n2,))\n y1 = L2d * z1\n y = reshape(y1, (n, n))\n mz = fish2d(y, fdata)\n q = reshape(mz, (n2,))\n pass = (norm(q - z1, Inf) < 1.e-12)\n pass || println(\"rand_test fails, norm =\", norm(q - z1))\n return pass\nend\n\nfunction eig_test(n, x, fdata)\n lambda = pi * pi * 5\n efunx = sin.(pi * x)\n efuny = sin.(2 * pi * x)\n efunu = efunx * efuny'\n vfun = fish2d(efunu, fdata)\n pass = (norm(lambda * vfun - efunu, Inf) < 1.e-2)\n pass || println(\"eig test fails\")\n return pass\nend\n", "meta": {"hexsha": "422cef70025cbf5a552d2efd9af9024b4b52d9a3", "size": 1873, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/Chapter2/pde_lin_test.jl", "max_stars_repo_name": "aliddell/SIAMFANLEquations.jl", "max_stars_repo_head_hexsha": "4a9bad23d726993764c5790d56b9d68cb27dffe0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 54, "max_stars_repo_stars_event_min_datetime": "2020-04-16T19:59:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T12:18:53.000Z", "max_issues_repo_path": "test/Chapter2/pde_lin_test.jl", "max_issues_repo_name": "aliddell/SIAMFANLEquations.jl", "max_issues_repo_head_hexsha": "4a9bad23d726993764c5790d56b9d68cb27dffe0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-07-22T20:17:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T01:14:10.000Z", "max_forks_repo_path": "test/Chapter2/pde_lin_test.jl", "max_forks_repo_name": "aliddell/SIAMFANLEquations.jl", "max_forks_repo_head_hexsha": "4a9bad23d726993764c5790d56b9d68cb27dffe0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-03T10:47:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-03T10:47:05.000Z", "avg_line_length": 22.5662650602, "max_line_length": 62, "alphanum_fraction": 0.5638013881, "num_tokens": 720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693659780479, "lm_q2_score": 0.8438951064805861, "lm_q1q2_score": 0.8014213307233954}} {"text": "\n\"\"\"\nCross-entropy loss as defined in PyTorch:\n\nhttp://pytorch.org/docs/master/nn.html#torch.nn.CrossEntropyLoss\n\nThis method works with one-hot-encoded inputs\n\"\"\"\nfunction cross_entropy_loss(ŷ::AbstractMatrix, y::AbstractMatrix)\n sublosses = -sum(y .* ŷ, 1) .+ log.(sum(exp.(ŷ), 1))\n return mean(sublosses)\nend\n\n\n@require CuArrays begin\n\n # have to split sublosses into 2 subexpressions since otherwise CUDAnative failes with\n # 'ERROR: Broadcast output type Any is not concrete'\n function cross_entropy_loss(ŷ::CuArray{T,2}, y::CuArray{T,2}) where T \n w1 = -sum(y .* ŷ, 1)\n w2 = sum(exp.(ŷ), 1)\n sublosses = w1 .+ CUDAnative.log.(w2)\n return mean(sublosses)\n end\n\nend\n", "meta": {"hexsha": "a8e819fd3f9e6b8a771145631708006ce6e65f9a", "size": 723, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/losses.jl", "max_stars_repo_name": "JuliaTagBot/Milk.jl", "max_stars_repo_head_hexsha": "5cd28fab200865ba69af5f687c86f296f1d2995f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-01-17T08:56:53.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-19T17:18:07.000Z", "max_issues_repo_path": "src/losses.jl", "max_issues_repo_name": "JuliaTagBot/Milk.jl", "max_issues_repo_head_hexsha": "5cd28fab200865ba69af5f687c86f296f1d2995f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-08-01T23:57:01.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-01T23:57:01.000Z", "max_forks_repo_path": "src/losses.jl", "max_forks_repo_name": "JuliaTagBot/Milk.jl", "max_forks_repo_head_hexsha": "5cd28fab200865ba69af5f687c86f296f1d2995f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:29:43.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:29:43.000Z", "avg_line_length": 26.7777777778, "max_line_length": 90, "alphanum_fraction": 0.6680497925, "num_tokens": 219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693617046216, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.8014213289812934}} {"text": "# Huber loss function\n\n\"\"\"\n HuberLoss(rho::Real=1.0, mu::Real=1.0)\n\nReturns the function `g(x) = (mu/2)||x||² if ||x|| ⩽ rho, and rho*mu*(||x||-rho/2) otherwise`.\n\"\"\"\n\nimmutable HuberLoss{R <: Real} <: ProximableFunction\n rho::R\n mu::R\n function HuberLoss(rho::R, mu::R)\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\nHuberLoss{R <: Real}(rho::R=1.0, mu::R=1.0) = HuberLoss{R}(rho, mu)\n\nfunction (f::HuberLoss){T <: Union{Real, Complex}}(x::AbstractArray{T})\n normx = vecnorm(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 prox!{T <: Union{Real, Complex}}(f::HuberLoss, x::AbstractArray{T}, y::AbstractArray{T}, gamma::Real=1.0)\n normx = vecnorm(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 ↦ (μ/2)||x||² if ||x||⩽ρ, μρ(||x||-ρ/2) otherwise\"\nfun_params(f::HuberLoss) = string(\"ρ = $(f.rho), μ = $(f.mu)\")\n\nfunction prox_naive{T <: Union{Real, Complex}}(f::HuberLoss, x::AbstractArray{T}, gamma::Real=1.0)\n y = (1-min(f.mu*gamma/(1+f.mu*gamma), f.mu*gamma*f.rho/(vecnorm(x))))*x\n if vecnorm(y) <= f.rho\n return y, (f.mu/2)*vecnorm(y)^2\n else\n return y, f.rho*f.mu*(vecnorm(y)-f.rho/2)\n end\nend\n", "meta": {"hexsha": "f3cd84b0903d8054f3d8419f3ef6f9c7d65927a1", "size": 1609, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/functions/huberLoss.jl", "max_stars_repo_name": "mfalt/ProximalOperators.jl", "max_stars_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functions/huberLoss.jl", "max_issues_repo_name": "mfalt/ProximalOperators.jl", "max_issues_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions/huberLoss.jl", "max_forks_repo_name": "mfalt/ProximalOperators.jl", "max_forks_repo_head_hexsha": "ab76ed9c93f9ec778281ad14f7bd3208b94c705d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8166666667, "max_line_length": 114, "alphanum_fraction": 0.6103169671, "num_tokens": 641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.949669363129097, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.8014213283191796}} {"text": "# # Introduction\n#\n#md # [![](https://mybinder.org/badge_logo.svg)](@__BINDER_ROOT_URL__notebooks/01_Introduction.ipynb)\n#md # [![](https://img.shields.io/badge/show-nbviewer-579ACA.svg)](@__NBVIEWER_ROOT_URL__notebooks/01_Introduction.ipynb)\n#\n# Let's start with a classic:\n\nmessage = \"Hello World!\"\n\n#-\n\nprintln(message)\n\n# Julia is a general purpose programming language designed with scientific\n# computing and mathematics in mind. For this reason, some Julia expressions\n# look like mathematics.\n#\n# For example, let's write a Julia function to calculate\n# a circle’s circumference $C$ as a function of the radius $r$:\n#\n# $C = 2 \\pi r$\n\nr = 10\n\nC = 2π*r\n\n# `π` is one of the\n# [mathematical constants](https://docs.julialang.org/en/v1.1/base/numbers/#General-Number-Functions-and-Constants-1)\n# defined in Julia. You can write `π` by typing `\\pi` and pressing `` in\n# the REPL:\n\nπ\n\n#-\n\npi\n\n# The multiplication operator `*` is not needed when a literal number\n# (e.g. `2`) is placed just before a variable or constant (e.g. `π`),\n# see [*Numeric Literal Coefficients*](https://docs.julialang.org/en/v1.1/manual/integers-and-floating-point-numbers/#man-numeric-literal-coefficients-1).\n# That makes polynomial expressions much cleaner:\n\nf(x) = 1.56 + 2.24x + 3.47x^2\n\n#-\n\nf(0.04)\n\n# This one-line function definition, i.e. `function_name(arguments) = body`, is\n# the simplest we can use in Julia.\n\n# #### Exercise 1\n#\n# Define an one-line function to calculate the length of the hypotenuse of a\n# right-angled triangle with catheti (legs) $a$ and $b$ as\n# $\\sqrt{a^{2} + b^{2}}$ using the `sqrt()` function:\n\n## hypotenuse(...\n\n# If your solution is correct, the following test should pass without errors.\n\nusing Test\n\n# The `Test` module exports the `@test` macro, useful for writing unit tests of\n# the code. We are going to use `≈`, `\\approx`, (`a ≈ b` or\n# `isapprox(a, b)`) test if two values can be equal taking into account\n# floating point errors. :\n\n@test hypotenuse(2, 5) ≈ hypot(2, 5)\n\n# In real life, you can use the function `hypot` to avoid\n# [underflow and overflow problems](https://www.johndcook.com/blog/2010/06/02/whats-so-hard-about-finding-a-hypotenuse/).\n\n# ## Control Flow\n#\n# ### `if`\n\ndistance = hypot(1.0, 3.0, 2.5)\n\n#-\n\nif distance <= 2.08 # Å\n \"Disulphide\"\nelseif distance <= 6 # Å\n \"Contact\"\nelse\n \"Not interacting\"\nend\n\n# Each condition should be a boolean variable (`true` or `false`) or an\n# expression that evaluates to a boolean value.\n\n# ### Short-circuit evaluation\n\ncondition = true\ncondition && println(\"It's true!\")\n\n# #### Exercise 2\n#\n# Can you write the equivalent expression using `if` ?\n\n## if ...\n\n# ### Ternary operator\n\ncondition = true\nresult = condition ? \"👍\" : \"👎\"\n\n# This is equivalent to:\n\nresult = if condition\n \"👍\"\n else\n \"👎\"\nend\n\n#-\n\nresult\n\n# ## `for` loops\n\ndna = \"ATGCAT\" # dna is a string\n\nfor base in dna\n println(base) # base is a character\nend\n\n# `for base = dna` and `for base ∈ dna` are also a possible notations, i.e.\n# using `=` or `∈` instead of `in`:\n\nfor base ∈ dna\n println(base)\nend\n\n# Julia has a nice unicode support and unicode characters can be used in\n# variables names, operators, etc. You can write `∈` in the REPL by typing `\\in`\n# and pressing the `` key.\n\n# ## Functions\n#\n# ### One-line syntax\n\n\"Return the number of codons in the sequence.\"\ncodon_number(seq) = div(length(seq), 3) # This is a Julia comment\n\n# A strings before the function declaration is used as docstring. You can access\n# the function documentation by typing `?` in the REPL and the name of the\n# function, e.g.: `?codon_number`\n\n## Try to look at the documentation of condon_number\n\n#-\n\ncodon_number(dna)\n\n# ### Multi-line syntax\n\n# Functions with longer bodies are defined using the `function` keyword:\n\n\"Returns the GC number in a given sequence.\"\nfunction count_gc(string)\n count = 0\n for char in string\n if char == 'C' || char == 'G' # || is the short-circuiting or.\n ## ' ' (instead of \" \") is used to define a character.\n count += 1 # i.e. count = count + 1\n end\n end\n count # i.e. return count\nend\n\n#-\n\ncount_gc(dna)\n\n# By default, a function returns the result of the last evaluated expression,\n# `count` in the previous example. Otherwise, the keyword `return` should be\n# used:\n\n\"\"\"\n`is_dna` iterates a string and returns:\n- `false` if a character different from **A, C, T or G** is found\n- `true` otherwise\n\"\"\"\nfunction is_dna(string)\n for char in string\n if char != 'A' && char != 'C' && char != 'T' && char != 'G'\n return false\n end\n end\n true\nend\n\n#-\n\nis_dna(\"ACHL\")\n\n# Here, the `return` keyword is used inside the loop to return `false` as soon\n# as an incorrect character is found.\n#\n# `\"\"\"` defines multiline strings. In this example, the multiline string is the\n# documentation string of the function. Markdown syntax can be used in\n# docstrings.\n\n#md ?is_dna\n#nb ?is_dna\n\n# #### Exercise 3\n#\n# Write a function that returns `true` if the given string (argument) has at\n# least one `N` using the keywords `function`, `for`, `if` and `return`.\n\n## has_n(...\n\n# `@testset` is useful to aggregate tests for a particular functionality:\n\nusing Test\n@testset \"Exercise 3\" begin\n @test has_n(\"ACTGN\")\n @test !has_n(\"ACTG\")\nend\n\n# #### Material\n#\n# You can find more complete information about\n# [functions](https://docs.julialang.org/en/v1.1/manual/functions/)\n# and [control flow](https://docs.julialang.org/en/v1.1/manual/control-flow/)\n# statements in the Julia manual.\n", "meta": {"hexsha": "9b240411c4b6785c2979c2ead4d7ad8ac5e27926", "size": 5586, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Introduction/01_Introduction.jl", "max_stars_repo_name": "diegozea/JuliaForBioinformatics", "max_stars_repo_head_hexsha": "259236533283c4e582c1d01c32141a9f38930abd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-28T01:10:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-28T01:10:51.000Z", "max_issues_repo_path": "src/Introduction/01_Introduction.jl", "max_issues_repo_name": "diegozea/JuliaForBioinformatics", "max_issues_repo_head_hexsha": "259236533283c4e582c1d01c32141a9f38930abd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Introduction/01_Introduction.jl", "max_forks_repo_name": "diegozea/JuliaForBioinformatics", "max_forks_repo_head_hexsha": "259236533283c4e582c1d01c32141a9f38930abd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.2869565217, "max_line_length": 154, "alphanum_fraction": 0.6749015396, "num_tokens": 1613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.9032942008463507, "lm_q1q2_score": 0.8014067590809432}} {"text": "md\"\"\"\n$$\n x[n] = A \\cos(\\omega n T + \\phi) = A \\cos(2\\pi f n T + \\phi)\n$$\n- $A$: amplitude\n- $\\omega$: angular frequency (`radians/sec`)\n- $f = \\omega / 2\\pi$: frequency in Hertz (`cycles/sec`)\n- $\\phi$: initial phase (`radians`)\n- $n$: time index\n- $t = nT = n / f_s$, where $f_s$ is the sampling frequency\n\n\"\"\"\nbegin\n import Pkg\n Pkg.activate(mktempdir())\n Pkg.add([\n \"AudioDisplay\",\n \"PyPlot\",\n ])\nend\n\nbegin\n A = .8\n f = 1000 # i.e. 1000 cycles/sec\n ϕ = pi/2\n fs = 44100 # i.e. 44100 samples/sec\n t = range(-.002, .002, step=1/fs)\n x = A .* cos.(2πf.*t .+ ϕ)\n size(x)\nend\n\n\nA * cos.(2π*f.*t .+ ϕ)\n", "meta": {"hexsha": "923b184fbec61e07204079688c253a28c3f97b4a", "size": 627, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "stanford/2019/01-intro/trash.jl", "max_stars_repo_name": "phunc20/dsp", "max_stars_repo_head_hexsha": "e7c496eb5fd4b8694eab0fc049cf98a5e3dfd886", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-12T18:32:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-12T18:32:06.000Z", "max_issues_repo_path": "stanford/2019/01-intro/trash.jl", "max_issues_repo_name": "phunc20/dsp", "max_issues_repo_head_hexsha": "e7c496eb5fd4b8694eab0fc049cf98a5e3dfd886", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stanford/2019/01-intro/trash.jl", "max_forks_repo_name": "phunc20/dsp", "max_forks_repo_head_hexsha": "e7c496eb5fd4b8694eab0fc049cf98a5e3dfd886", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.4411764706, "max_line_length": 62, "alphanum_fraction": 0.5374800638, "num_tokens": 252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542852576266, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.8013576109459262}} {"text": "function getDivGrad(n1,n2,n3)\n\t# D = getDivGrad(n1,n2,n3)\n\t# builds 3D divergence operator\n\tD1 = kron(speye(n3),kron(speye(n2),ddx(n1)))\n\tD2 = kron(speye(n3),kron(ddx(n2),speye(n1)))\n\tD3 = kron(ddx(n3),kron(speye(n2),speye(n1)))\n\t\n\tDiv = [D1 D2 D3]\n\treturn Div*Div'\nend\n\nfunction ddx(n)\n# generate 1D finite difference on staggered grid\n\treturn d = spdiags(ones(n)*[-1 1],[0,1],n,n+1)\nend\n\nfunction spdiags(B,d,m,n)\n# A = spdiags(B,d,m,n)\n# creates a sparse matrix from its diagonals\n\td = d[:]\n\tp = length(d)\n\tlen = zeros(p+1,1)\n\tfor k = 1:p\n\t\tlen[k+1] = round(Int,len[k]+length(max(1,1-d[k]):min(m,n-d[k])))\n\tend\n\ta = zeros(round(Int,len[p+1]),3)\n\tfor k = 1:p\n\t\t# Append new d[k]-th diagonal to compact form\n\t\ti = max(1,1-d[k]):min(m,n-d[k])\n\t\ta[(round(Int,len[k])+1):round(Int,len[k+1]),:] = [i i+d[k] B[i+(m>=n)*d[k],k]]\n\tend\n\t\n\tA = sparse(round(Int,a[:,1]),round(Int,a[:,2]),a[:,3],m,n)\n\treturn A\nend\n", "meta": {"hexsha": "3cf93869c5a1415bfc5bf80ebd34ab63136ff3d4", "size": 905, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/getDivGrad.jl", "max_stars_repo_name": "JuliaPackageMirrors/KrylovMethods.jl", "max_stars_repo_head_hexsha": "964bca6c9ab389b7c5bfa33f5a9c943dc54901b8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/getDivGrad.jl", "max_issues_repo_name": "JuliaPackageMirrors/KrylovMethods.jl", "max_issues_repo_head_hexsha": "964bca6c9ab389b7c5bfa33f5a9c943dc54901b8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/getDivGrad.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": 25.1388888889, "max_line_length": 80, "alphanum_fraction": 0.608839779, "num_tokens": 363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693242018339896, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.8013517561420416}} {"text": "# Newey-West covariance estimator\nfunction NeweyWest(Z,nlags=0)\n#=\n Returns the Newey-West estimator of the asymptotic variance matrix\n INPUTS: Z, a nxk matrix with rows the vector zt'\n nlags, the number of lags\n OUTPUTS: omegahat, the Newey-West estimator of the covariance matrix\n=#\n n,k = size(Z)\n # de-mean the variables\n Z = Z .- mean(Z,1)\n omegahat = Z'*Z/n # sample variance\n # automatic lags?\n if nlags == 0\n nlags = max(0, Int(round(n^0.25)))\n end \n # sample autocovariances\n for i = 1:nlags\n Zlag = Z[1:n-i,:]\n ZZ = Z[i+1:n,:]\n gamma = (ZZ'*Zlag)/n\n weight = 1.0 - (i/(nlags+1.0))\n omegahat += weight*(gamma + gamma')\n end \n return omegahat\nend\n", "meta": {"hexsha": "cecbb4637305455799dd181f8fad443fc1f3f396", "size": 751, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NP/NeweyWest.jl", "max_stars_repo_name": "UserQuestions/Econometrics.jl", "max_stars_repo_head_hexsha": "f9db0ca3046e7c5328f085581a12b1c733cf9bcf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NP/NeweyWest.jl", "max_issues_repo_name": "UserQuestions/Econometrics.jl", "max_issues_repo_head_hexsha": "f9db0ca3046e7c5328f085581a12b1c733cf9bcf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NP/NeweyWest.jl", "max_forks_repo_name": "UserQuestions/Econometrics.jl", "max_forks_repo_head_hexsha": "f9db0ca3046e7c5328f085581a12b1c733cf9bcf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8148148148, "max_line_length": 72, "alphanum_fraction": 0.5885486019, "num_tokens": 245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947148047777, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.8013250554380023}} {"text": "using ApproxFun, OrdinaryDiffEq\nusing LinearAlgebra\nusing DiffEqOperators\n\nfunction makesim(sts::Union{STS{:KuramotoSivashinsky}, STS{:ksiva}})\n @unpack ic, T, S, Δt, N = sts\n L = try\n L = sts.p.L\n catch e\n L = 22\n end\n # prepare initial condition\n if ic isa Union{Nothing, Integer}\n # here we integrate a pre-determined initial condition\n # for a random amount of time\n rng = MersenneTwister(isnothing(ic) ? 42 : ic)\n S += Δt*rand(rng, 10:1000)\n x = L*(0:N-1)/N\n u0 = @. cos(x) + 0.1*sin(x/8) + 0.01*cos((2π/L)*x)\n elseif ic isa AbstractVector{<:Real}\n u0 = ic\n @assert length(u0) == N\n else\n error(ICERROR)\n end\n saveat = S:Δt:(T+S)\n t, u = kuramoto_sivashinsky(u0, L, saveat)\n t = 0:Δt:T\n return @strdict u t sts\nend\n\n\n\"\"\"\n kuramoto_sivashinsky(u, L, saveat)\n\nSolve the Kuramoto Sivashinsky system given by the PDE\n```math\nu_t = -u*u_x - u_{xx} - u_{xxxx}\n```\nwith periodic boundary conditions and initial condition `u`.\n\n`L` is the physical spatial length (with `length(u)` points sampled\nequidistantly in it).\n\n`saveat` dictates at which timepoints to save the system (which is solved\nusing `OrdinaryDiffEq`).\n\"\"\"\nfunction kuramoto_sivashinsky(u, L, saveat)\n n = length(u) # number of gridpoints\n F = Fourier(0..L)\n T = ApproxFun.plan_transform(F, n)\n Ti = ApproxFun.plan_itransform(F, n)\n\n #Linear Part\n D = (Derivative(F) → F)[1:n,1:n]\n D2 = Derivative(F,2)[1:n,1:n]\n D4 = Derivative(F,4)[1:n,1:n]\n A = DiffEqArrayOperator(Diagonal(-D2-D4))\n\n #Nonlinear Part\n ks = KSFunctor(zeros(n))\n\n params = (D, T, Ti)\n prob = SplitODEProblem(A, ks, T*u, (0.0, saveat[end]), params)\n sol = solve(prob, ETDRK4(), dt=Float64(saveat.step), saveat=saveat,\n save_start = false, save_end = false)\n # @assert sol.t == saveat\n return sol.t, map(u -> Ti*u, sol.u)\nend\n\nstruct KSFunctor{T}; tmp::Vector{T}; end\nfunction (ks::KSFunctor)(du,u,p,t)\n D, T, Ti = p\n mul!(du,Ti,u)\n @. du = -1/2*du^2\n mul!(ks.tmp, T, du)\n mul!(du, D, ks.tmp)\nend\n", "meta": {"hexsha": "7e4caa29456e2a88538de35e90bfb4ead2620ff5", "size": 2156, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kuramoto-sivashinsky.jl", "max_stars_repo_name": "yuxiliu1995/SpatioTemporalSystems.jl", "max_stars_repo_head_hexsha": "ce8c65163350836f3b94d5b5f0cf0a4d550dfcd2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-09-21T01:13:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-08T00:09:44.000Z", "max_issues_repo_path": "src/kuramoto-sivashinsky.jl", "max_issues_repo_name": "yuxiliu1995/SpatioTemporalSystems.jl", "max_issues_repo_head_hexsha": "ce8c65163350836f3b94d5b5f0cf0a4d550dfcd2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-09-20T12:45:02.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-27T21:58:39.000Z", "max_forks_repo_path": "src/kuramoto-sivashinsky.jl", "max_forks_repo_name": "yuxiliu1995/SpatioTemporalSystems.jl", "max_forks_repo_head_hexsha": "ce8c65163350836f3b94d5b5f0cf0a4d550dfcd2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-02-08T12:01:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-13T08:54:15.000Z", "avg_line_length": 27.2911392405, "max_line_length": 73, "alphanum_fraction": 0.6001855288, "num_tokens": 731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947101574299, "lm_q2_score": 0.8479677622198947, "lm_q1q2_score": 0.8013250496818338}} {"text": "export SG_Filter, maxDerivativeOrder, polynomialOrder, apply_SG_filter, apply_SG_filter2D\n\nimport Base: filter, length\n\nfunction _Vandermonde(T::DataType=Float64;halfWidth::Int=5,degree::Int=2)::Array{T,2}\n \n @assert halfWidth>=0\n @assert degree>=0\n \n x=T[i for i in -halfWidth:halfWidth]\n\n n = degree+1\n m = length(x)\n \n V = Array{T}(undef,m, n)\n \n for i = 1:m\n V[i,1] = T(1)\n end\n for j = 2:n\n for i = 1:m\n V[i,j] = x[i] * V[i,j-1]\n end\n end\n\n return V\nend\n\n# ================================================================\n\nstruct SG_Filter{T<:AbstractFloat,N}\n _filter_set::Array{LinearFilter_DefaultCentered{T,N},1}\nend\n\n\"\"\"\n function SG_Filter(T::DataType=Float64;halfWidth::Int=5,degree::Int=2)\n\nCreates a `SG_Filter` structure used to store Savitzky-Golay filters.\n\n* filter length is 2*`halfWidth`+1 \n* polynomial degree is `degree`, which defines `maxDerivativeOrder`\n\nYou can apply these filters using the \n* `apply_SG_filter`\n* `apply_SG_filter2D`\nfunctions.\n\nExample:\n\n```jldoctest\njulia> sg = SG_Filter(halfWidth=5,degree=3);\n\n\njulia> maxDerivativeOrder(sg)\n3\n\njulia> length(sg)\n11\n\njulia> filter(sg,derivativeOrder=2)\nFilter(r=-5:5,c=[0.03497, 0.01399, -0.002331, -0.01399, -0.02098, -0.02331, -0.02098, -0.01399, -0.002331, 0.01399, 0.03497])\n\n```\n\"\"\"\nfunction SG_Filter(T::DataType=Float64;halfWidth::Int=5,degree::Int=2)::SG_Filter\n @assert degree>=0\n @assert halfWidth>=1\n @assert 2*halfWidth>degree\n \n V=_Vandermonde(T,halfWidth=halfWidth,degree=degree)\n Q,R=qr(V)\n # breaking change in Julia V1.0,\n # see https://github.com/JuliaLang/julia/issues/27397\n #\n # before Q was a \"plain\" matrix, now stored in compact form\n #\n # SG=R\\Q'\n #\n # must be replaced by\n #\n # Q=Q*Matrix(I, size(V))\n # SG=R\\Q'\n #\n Q=Q*Matrix(I, size(V))\n SG=R\\Q'\n\n n_filter,n_coef = size(SG)\n\n buffer=Array{LinearFilter_DefaultCentered{T,n_coef},1}()\n \n for i in 1:n_filter\n SG[i,:]*=factorial(i-1)\n push!(buffer,LinearFilter(SG[i,:]))\n end\n \n# Returns filters set\n return SG_Filter{T,n_coef}(buffer)\nend\n\n# ================================================================\n\n\"\"\"\n function filter(sg::SG_Filter{T,N};derivativeOrder::Int=0)\n\nReturns the filter to be used to compute the smoothed derivatives of order `derivativeOrder`.\n\nSee: `SG_Filter`\n\"\"\"\nfunction filter(sg::SG_Filter{T,N};derivativeOrder::Int=0) where {T<:AbstractFloat,N}\n @assert 0<= derivativeOrder <= maxDerivativeOrder(sg)\n return sg._filter_set[derivativeOrder+1]\nend \n\n\"\"\"\n function length(sg::SG_Filter{T,N})\n\nReturns filter length, this is an odd number.\n\nSee: `SG_Filter`\n\"\"\"\nBase.length(sg::SG_Filter{T,N}) where {T<:AbstractFloat,N} = length(filter(sg))\n\n\"\"\"\n function maxDerivativeOrder(sg::SG_Filter{T,N})\n\nMaximum order of the smoothed derivatives we can compute using `sg` filters.\n\nSee: `SG_Filter`\n\"\"\"\nmaxDerivativeOrder(sg::SG_Filter{T,N}) where {T<:AbstractFloat,N} = size(sg._filter_set,1)-1\n\n\"\"\"\n function polynomialOrder(sg::SG_Filter{T,N})\n\nReturns the degree of the polynomial used to construct the\nSavitzky-Golay filters. This is mainly a 'convenience' function, as it\nis equivalent to `maxDerivativeOrder`\n\nSee: `SG_Filter`\n\"\"\"\npolynomialOrder(sg::SG_Filter{T,N}) where {T<:AbstractFloat,N} = maxDerivativeOrder(sg)\n\n\"\"\"\n function apply_SG_filter(signal::Array{T,1},\n sg::SG_Filter{T};\n derivativeOrder::Int=0,\n left_BE::Type{<:BoundaryExtension}=ConstantBE,\n right_BE::Type{<:BoundaryExtension}=ConstantBE)\n\n\n\nApplies an 1D Savitzky-Golay and returns the smoothed signal.\n\"\"\"\nfunction apply_SG_filter(signal::AbstractArray{T,1},\n sg::SG_Filter{T};\n derivativeOrder::Int=0,\n left_BE::Type{<:BoundaryExtension}=ConstantBE,\n right_BE::Type{<:BoundaryExtension}=ConstantBE) where {T<:AbstractFloat}\n \n return directCrossCorrelation(filter(sg,derivativeOrder=derivativeOrder),\n signal,\n left_BE,\n right_BE)\nend\n\n\"\"\"\n function apply_SG_filter2D(signal::Array{T,2},\n sg_I::SG_Filter{T},\n sg_J::SG_Filter{T};\n derivativeOrder_I::Int=0,\n derivativeOrder_J::Int=0,\n min_I_BE::Type{<:BoundaryExtension}=ConstantBE,\n max_I_BE::Type{<:BoundaryExtension}=ConstantBE,\n min_J_BE::Type{<:BoundaryExtension}=ConstantBE,\n max_J_BE::Type{<:BoundaryExtension}=ConstantBE)\n\nApplies an 2D Savitzky-Golay and returns the smoothed signal.\n\"\"\"\nfunction apply_SG_filter2D(signal::AbstractArray{T,2},\n sg_I::SG_Filter{T},\n sg_J::SG_Filter{T};\n derivativeOrder_I::Int=0,\n derivativeOrder_J::Int=0,\n min_I_BE::Type{<:BoundaryExtension}=ConstantBE,\n max_I_BE::Type{<:BoundaryExtension}=ConstantBE,\n min_J_BE::Type{<:BoundaryExtension}=ConstantBE,\n max_J_BE::Type{<:BoundaryExtension}=ConstantBE) where {T<:AbstractFloat}\n \n return directCrossCorrelation2D(filter(sg_I,derivativeOrder=derivativeOrder_I),\n filter(sg_J,derivativeOrder=derivativeOrder_J),\n signal,\n min_I_BE,\n max_I_BE,\n min_J_BE,\n max_J_BE)\nend \n", "meta": {"hexsha": "a602d4f97c5487bbc331b860d1859677e99a94fc", "size": 5947, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SG_Filter.jl", "max_stars_repo_name": "vincent-picaud/DirectConvolution", "max_stars_repo_head_hexsha": "55fde57e8b203f63f028940be64752adb63e5a25", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-04-20T20:50:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-17T12:33:45.000Z", "max_issues_repo_path": "src/SG_Filter.jl", "max_issues_repo_name": "vincent-picaud/DirectConvolution", "max_issues_repo_head_hexsha": "55fde57e8b203f63f028940be64752adb63e5a25", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-04-11T04:02:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-17T09:58:07.000Z", "max_forks_repo_path": "src/SG_Filter.jl", "max_forks_repo_name": "vincent-picaud/DirectConvolution", "max_forks_repo_head_hexsha": "55fde57e8b203f63f028940be64752adb63e5a25", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-04-01T03:11:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:27:26.000Z", "avg_line_length": 30.1878172589, "max_line_length": 125, "alphanum_fraction": 0.5742391122, "num_tokens": 1516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9449947101574298, "lm_q2_score": 0.8479677622198946, "lm_q1q2_score": 0.8013250496818336}} {"text": "function randindex(c1,c2)\n # rand_index - calculates Rand Indices to compare two partitions\n # (AR, RI, MI, HI) = rand(c1,c2), where c1,c2 are vectors listing the\n # class membership, returns the \"Hubert & Arabie adjusted Rand index\".\n # (AR, RI, MI, HI) = rand(c1,c2) returns the adjusted Rand index,\n # the unadjusted Rand index, \"Mirkin's\" index and \"Hubert's\" index.\n #\n # See L. Hubert and P. Arabie (1985) \"Comparing Partitions\" Journal of\n # Classification 2:193-218\n\n c = counts(c1,c2,(1:maximum(c1),1:maximum(c2))) # form contingency matrix\n\n n = round(Int,sum(c))\n nis = sum(sum(c,2).^2) # sum of squares of sums of rows\n njs = sum(sum(c,1).^2) # sum of squares of sums of columns\n\n t1 = binomial(n,2) # total number of pairs of entities\n t2 = sum(c.^2) # sum over rows & columnns of nij^2\n t3 = .5*(nis+njs)\n\n # Expected index (for adjustment)\n nc = (n*(n^2+1)-(n+1)*nis-(n+1)*njs+2*(nis*njs)/n)/(2*(n-1))\n\n A = t1+t2-t3; # no. agreements\n D = -t2+t3; # no. disagreements\n\n if t1 == nc\n # avoid division by zero; if k=1, define Rand = 0\n ARI = 0\n else\n # adjusted Rand - Hubert & Arabie 1985\n ARI = (A-nc)/(t1-nc)\n end\n\n RI = A/t1 # Rand 1971 # Probability of agreement\n MI = D/t1 # Mirkin 1970 # p(disagreement)\n HI = (A-D)/t1 # Hubert 1977 # p(agree)-p(disagree)\n\n return (ARI, RI, MI, HI)\nend\n\nrandindex(R::ClusteringResult, c0::AbstractVector{Int}) = randindex(assignments(R), c0)\nrandindex(R1::ClusteringResult, R2::ClusteringResult) = randindex(assignments(R2), assignments(R1))\n", "meta": {"hexsha": "008e37cc180c3bb1d9ee85f8dca4c8743712d16a", "size": 1698, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/randindex.jl", "max_stars_repo_name": "JuliaPackageMirrors/Clustering.jl", "max_stars_repo_head_hexsha": "ea03689a96f5a4601894959a028b390e9fbf7f73", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/randindex.jl", "max_issues_repo_name": "JuliaPackageMirrors/Clustering.jl", "max_issues_repo_head_hexsha": "ea03689a96f5a4601894959a028b390e9fbf7f73", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/randindex.jl", "max_forks_repo_name": "JuliaPackageMirrors/Clustering.jl", "max_forks_repo_head_hexsha": "ea03689a96f5a4601894959a028b390e9fbf7f73", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.5909090909, "max_line_length": 99, "alphanum_fraction": 0.5889281508, "num_tokens": 555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947070591979, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.8013250416085308}} {"text": "#=\nThe following code is modified from\nhttps://github.com/billmclean/GaussQuadrature.jl with the original license:\n\n> The MIT License (MIT)\n\n> Copyright (c) 2013 billmclean\n\n> Permission is hereby granted, free of charge, to any person obtaining a copy\n> of this software and associated documentation files (the \"Software\"), to deal\n> in the Software without restriction, including without limitation the rights\n> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n> copies of the Software, and to permit persons to whom the Software is\n> furnished to do so, subject to the following conditions:\n\n> The above copyright notice and this permission notice shall be included in\n> all copies or substantial portions of the Software.\n\n> THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n> SOFTWARE.\n=#\n\n# October 2013 by Bill McLean, School of Maths and Stats,\n# The University of New South Wales.\n#\n# Based on earlier Fortran codes\n#\n# gaussq.f original version 20 Jan 1975 from Stanford\n# gaussq.f modified 21 Dec by Eric Grosse\n# gaussquad.f95 Nov 2005 by Bill Mclean\n#\n# This module provides functions to compute the abscissae x[j] and\n# weights w[j] for the classical Gauss quadrature rules, including\n# the Radau and Lobatto variants. Thus, the sum\n#\n# n\n# ∑ w[j] f(x[j])\n# j=1\n#\n# approximates\n#\n# hi\n# ∫ f(x) w(x) dx\n# lo\n#\n# where the weight function w(x) and interval lo < x < hi are as shown\n# in the table below.\n#\n# Name Interval Weight Function\n#\n# Legendre -1 < x < 1 1\n# Chebyshev (first kind) -1 < x < 1 1 / sqrt(1-x²)\n# Chebyshev (second kind) -1 < x < 1 sqrt(1-x²)\n# Jacobi -1 < x < 1 (1-x)ᵅ (1+x)ᵝ\n# Laguerre 0 < x < ∞ xᵅ exp(-x)\n# Hermite -∞ < x < ∞ exp(-x²)\n#\n# In addition to these classical rules, the module generates Gauss rules\n# for logarithmic weights of the form\n#\n# w(x) = x^ρ log(1/x) for 0 < x < 1.\n#\n# For the Jacobi and Laguerre rules we require α > -1 and\n# β > -1, so that the weight function is integrable. Likewise, for\n# log weight we require ρ > -1.\n#\n# Use the endpoint argument to include one or both of the end points\n# of the interval of integration as an abscissa in the quadrature\n# rule, as follows.\n#\n# endpoint = NeitherEndPoint() Default lo < x[j] < hi, j = 1:n.\n# endpoint = LeftEndPoint() Left Radau lo = x[1] < x[j] < hi, j = 2:n.\n# endpoint = RightEndPoint() Right Radau lo < x[j] < x[n] = hi, j = 1:n-1.\n# endpoint = BothEndPoint() Lobatto lo = x[1] < x[j] < x[n] = hi, j = 2:n-1.\n#\n#\n# The code uses the Golub and Welsch algorithm, in which the abscissae\n# x[j] are the eigenvalues of a symmetric tridiagonal matrix whose\n# entries depend on the coefficients in the 3-term recurrence relation\n# for the othonormal polynomials generated by the weighted inner product.\n#\n# References:\n#\n# 1. Golub, G. H., and Welsch, J. H., Calculation of Gaussian\n# quadrature rules, Mathematics of Computation 23 (April,\n# 1969), pp. 221-230.\n# 2. Golub, G. H., Some modified matrix eigenvalue problems,\n# Siam Review 15 (april, 1973), pp. 318-334 (section 7).\n# 3. Stroud and Secrest, Gaussian Quadrature Formulas, Prentice-\n# Hall, Englewood Cliffs, N.J., 1966.\n\n# Enumeration type used to specify which endpoints of the integration\n# interval should be included amongst the quadrature points: neither,\n# left, right, or both.\n\nabstract type EndPoint end\nstruct NeitherEndPoint <: EndPoint end\nstruct LeftEndPoint <: EndPoint end\nstruct RightEndPoint <: EndPoint end\nstruct BothEndPoint <: EndPoint end\n\n\"\"\"\n x, w = legendregauss(T, n, endpoint::EndPoint=Bennu.NeitherEndPoint())\n\nReturns points `x` and weights `w` for the `n`-point Gauss-Legendre rule\nfor the interval `-1 < x < 1` with weight function `w(x) = 1`.\n\nUse `endpoint=LeftEndPoint()`, `RightEndPoint() ` or `BothEndPoints()` for the\nleft Radau, right Radau, or Lobatto rules, respectively.\n\"\"\"\nfunction legendregauss(::Type{T}, n, endpoint=NeitherEndPoint()) where {T}\n @assert n ≥ 1\n a, b = legendrecoefficients(T, n)\n return gaussrule(-one(T), one(T), a, b, endpoint)\nend\n\n\"\"\"\n x, w = legendregauss(n, endpoint::EndPoint=Bennu.NeitherEndPoint())\n\nConvenience function with type `T = Float64`:\n\"\"\"\nlegendregauss(n, endpoint::EndPoint=NeitherEndPoint()) = legendregauss(Float64, n, endpoint)\n\n\"\"\"\n x, w = legendregausslobatto(T, n)\n\nReturns points `x` and weights `w` for the `n`-point Legendre-Gauss-Lobatto rule\nfor the interval `-1 ≤ x ≤ 1` with weight function `w(x) = 1`.\n\"\"\"\nfunction legendregausslobatto(::Type{T}, n) where {T}\n return legendregauss(T, n, BothEndPoint())\nend\n\n\"\"\"\n x, w = legendregausslobatto(n)\n\nConvenience function with type `T = Float64`:\n\"\"\"\nlegendregausslobatto(n) = legendregausslobatto(Float64, n)\n\nfunction legendrecoefficients(::Type{T}, n) where {T}\n a = zeros(T, n)\n b = zeros(T, n + 1)\n b[1] = sqrt(convert(T, 2))\n for k in 2:(n + 1)\n b[k] = (k - 1) / sqrt(convert(T, (2k - 1) * (2k - 3)))\n end\n return a, b\nend\n\n\"\"\"\n x, w = gaussrule(lo, hi, a, b, endpoint, maxiterations=100)\n\nGenerates the points `x` and weights `w` for a Gauss rule with weight\nfunction `w(x)` on the interval `lo < x < hi`.\n\nThe arrays `a` and `b` hold the coefficients (as given, for instance, by\n`legendrecoefficients`) in the three-term recurrence relation for the monic\northogonal polynomials `p(0,x)`, `p(1,x)`, `p(2,x)`, ... , that is,\n\n p(k, x) = (x-a[k]) p(k-1, x) - b[k]² p(k-2, x), k ≥ 1,\n\nwhere `p(0, x) = 1` and, by convention, `p(-1, x) = 0` with\n\n hi\n b[1]^2 = ∫ w(x) dx.\n lo\n\nThus, `p(k, x) = xᵏ + lower degree terms` and\n\n hi\n ∫ p(j, x) p(k, x) w(x) dx = 0 if j ≠ k.\n lo\n\"\"\"\nfunction gaussrule(lo, hi, a, b, endpoint::EndPoint, maxiterations=100)\n T = promote_type(typeof(lo), typeof(hi), eltype(a), eltype(b))\n n = length(a)\n @assert length(b) == n + 1\n if endpoint isa LeftEndPoint\n if n == 1\n a[1] = lo\n else\n a[n] = tridiagonalshiftsolve(n, lo, a, b) * b[n]^2 + lo\n end\n elseif endpoint isa RightEndPoint\n if n == 1\n a[1] = hi\n else\n a[n] = tridiagonalshiftsolve(n, hi, a, b) * b[n]^2 + hi\n end\n elseif endpoint isa BothEndPoint\n if n == 1\n error(\"Must have at least two points for both ends.\")\n end\n g = tridiagonalshiftsolve(n, lo, a, b)\n t1 = (hi - lo) / (g - tridiagonalshiftsolve(n, hi, a, b))\n b[n] = sqrt(t1)\n a[n] = lo + g * t1\n end\n w = zero(a)\n tridiagonaleigenproblem!(a, b, w, maxiterations)\n for i in 1:n\n w[i] = (b[1] * w[i])^2\n end\n idx = sortperm(a)\n # Ensure end point values are exact.\n if endpoint isa LeftEndPoint || endpoint isa BothEndPoint\n a[idx[1]] = lo\n elseif endpoint isa RightEndPoint || endpoint isa BothEndPoint\n a[idx[n]] = hi\n end\n return a[idx], w[idx]\nend\n\nfunction tridiagonalshiftsolve(n, shift, a, b) where {T}\n #\n # Perform elimination to find the nth component s = delta[n]\n # of the solution to the nxn linear system\n #\n # ( J_n - shift I_n ) delta = e_n,\n #\n # where J_n is the symmetric tridiagonal matrix with diagonal\n # entries a[i] and off-diagonal entries b[i], and e_n is the nth\n # standard basis vector.\n #\n t = a[1] - shift\n for i in 2:(n - 1)\n t = a[i] - shift - b[i]^2 / t\n end\n return one(t) / t\nend\n\nfunction tridiagonaleigenproblem!(d, e, z, maxiterations)\n #\n # Finds the eigenvalues and first components of the normalised\n # eigenvectors of a symmetric tridiagonal matrix by the implicit\n # QL method.\n #\n # d[i] On entry, holds the ith diagonal entry of the matrix.\n # On exit, holds the ith eigenvalue.\n #\n # e[i] On entry, holds the [i,i-1] entry of the matrix for\n # i = 2, 3, ..., n. (The value of e[1] is not used.)\n # On exit, e is overwritten.\n #\n # z[i] On exit, holds the first component of the ith normalised\n # eigenvector associated with d[i].\n #\n # maxiterations The maximum number of QL iterations.\n #\n # Martin and Wilkinson, Numer. Math. 12: 377-383 (1968).\n # Dubrulle, Numer. Math. 15: 450 (1970).\n # Handbook for Automatic Computation, Vol ii, Linear Algebra,\n # pp. 241-248, 1971.\n #\n # This is a modified version of the Eispack routine imtql2.\n #\n T = promote_type(eltype(d), eltype(e), eltype(z))\n n = length(z)\n z[1] = one(T)\n z[2:n] .= zero(T)\n e[n + 1] = zero(T)\n\n if n == 1 # Nothing to do for a 1x1 matrix.\n return\n end\n for l in 1:n\n for j in 1:maxiterations\n # Look for small off-diagonal elements.\n m = n\n for i in l:(n - 1)\n if abs(e[i + 1]) <= eps(T) * (abs(d[i]) + abs(d[i + 1]))\n m = i\n break\n end\n end\n p = d[l]\n if m == l\n continue\n end\n if j == maxiterations\n msg = string(\"No convergence after \", j, \" iterations\",\n \" (try increasing maxiterations)\")\n error(msg)\n end\n # Form shift\n g = (d[l + 1] - p) / (2 * e[l + 1])\n r = hypot(g, one(T))\n g = d[m] - p + e[l + 1] / (g + copysign(r, g))\n s = one(T)\n c = one(T)\n p = zero(T)\n for i in (m - 1):-1:l\n f = s * e[i + 1]\n b = c * e[i + 1]\n if abs(f) < abs(g)\n s = f / g\n r = hypot(s, one(T))\n e[i + 2] = g * r\n c = one(T) / r\n s *= c\n else\n c = g / f\n r = hypot(c, one(T))\n e[i + 2] = f * r\n s = one(T) / r\n c *= s\n end\n g = d[i + 1] - p\n r = (d[i] - g) * s + 2 * c * b\n p = s * r\n d[i + 1] = g + p\n g = c * r - b\n # Form first component of vector.\n f = z[i + 1]\n z[i + 1] = s * z[i] + c * f\n z[i] = c * z[i] - s * f\n end\n d[l] -= p\n e[l + 1] = g\n e[m + 1] = zero(T)\n end\n end\n return\nend\n", "meta": {"hexsha": "a913c38bb001aac50b0a23fbd1b594986538b82b", "size": 11052, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/quadratures.jl", "max_stars_repo_name": "mwarusz/Bennu.jl", "max_stars_repo_head_hexsha": "e9f60c9b453c51b5d9cb1e05f42cef3a780f2cbd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/quadratures.jl", "max_issues_repo_name": "mwarusz/Bennu.jl", "max_issues_repo_head_hexsha": "e9f60c9b453c51b5d9cb1e05f42cef3a780f2cbd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/quadratures.jl", "max_forks_repo_name": "mwarusz/Bennu.jl", "max_forks_repo_head_hexsha": "e9f60c9b453c51b5d9cb1e05f42cef3a780f2cbd", "max_forks_repo_licenses": ["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.3897280967, "max_line_length": 92, "alphanum_fraction": 0.568946797, "num_tokens": 3297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850110816423, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.8013206006224768}} {"text": "using ProgressBars, Plots, StatsBase, Statistics, LaTeXStrings, JLD\n\nfunction RandomWalker2D(TotalSteps)\n choices = ((1,0),(0,1),(-1,0),(0,-1))\n return reduce(.+,rand(choices,TotalSteps))\nend\n\nfunction RGyration(ensemble)\n MassCenter = (mean(getindex.(ensemble,1)),mean(getindex.(ensemble,2)))\n return √(sum(pos -> reduce(.+, (pos .- MassCenter).^2), ensemble)/length(ensemble))\nend\n\nTotalSteps = 40\nRWNumbers = 10000000\n\nData = [[RandomWalker2D(TS) for i ∈ 1:RWNumbers] for TS ∈ ProgressBar(1:TotalSteps)]\n\nRgList = [RGyration(Data[i]) for i ∈ 1:TotalSteps]\nsave(\"../../Data/Q1/Q1-Rg.jld\", \"RgList\", RgList)\n\n\nplot(1:TotalSteps,sqrt.(1:TotalSteps), label = L\"Y = \\sqrt{X}\", c = :black, linestyle = :dash)\nscatter!(RgList, label = L\"Data\\ Point\", framestyle = :box, c = :steelblue, legend = 140)\nplot!(xlabel = L\"Time\", ylabel = L\"{R_g}_{(t)}\",\n title = L\"Radius\\ of\\ Gyration\\ of\\ RW\\ per\\ Time\\ for\\ 10^6 \\ Particles\")\nsavefig(\"../../Figs/Q1/Q1-Rg(t).pdf\")\n", "meta": {"hexsha": "0b7e1335cdaa4771ec24ddc0fb8eb1ba2165d890", "size": 974, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ProblemSet5/Codes/Q1/Q1-Rg.jl", "max_stars_repo_name": "shahmari/ComputationalPhysics-Fall2021", "max_stars_repo_head_hexsha": "f1681e32258c55697d11009e1702eb86d5f119d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ProblemSet5/Codes/Q1/Q1-Rg.jl", "max_issues_repo_name": "shahmari/ComputationalPhysics-Fall2021", "max_issues_repo_head_hexsha": "f1681e32258c55697d11009e1702eb86d5f119d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ProblemSet5/Codes/Q1/Q1-Rg.jl", "max_forks_repo_name": "shahmari/ComputationalPhysics-Fall2021", "max_forks_repo_head_hexsha": "f1681e32258c55697d11009e1702eb86d5f119d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-21T11:07:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-21T11:07:08.000Z", "avg_line_length": 36.0740740741, "max_line_length": 94, "alphanum_fraction": 0.6611909651, "num_tokens": 331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850128595114, "lm_q2_score": 0.8558511396138365, "lm_q1q2_score": 0.8013205952591684}} {"text": "#=\nPopis\n Funkcia vypocita pre kazdy vrchol hodnotu jeho closeness centrality.\n\nParametre\n g : datova struktura grafu :: GenericGraph\n dist_key : nazov atributu, v ktorom je ulozena vlastnost vrchola :: String\n normalize : parameter pre aplikovanie normalizacie :: Bool\n\nNavratova hodnota\n closeness : slovnik obsahujuci mapovanie vrcholov a k nim prisluchajucich hodnot\n closeness centrality (index_vrchola => hodnota_closeness_centrality) :: Dict{Int64, Float64}()\n\nPoznamky\n Hodnota centrality moze byt normalizovana nastavenim parametra normalize na True/False.\n Vypocet centrality je upraveny aby velkost grafu neovplyvnovala hodnotu centrality.\n=#\n\nfunction centrality_closeness(g::GenericGraph; dist_key::AbstractString=\"weight\", normalize::Bool=true)\n\n epi = AttributeEdgePropertyInspector{Float64}(dist_key)\n closeness = Dict{Int64, Float64}()\n\n for v in Graphs.vertices(g)\n \n distances = filter(x -> x != Inf, dijkstra_shortest_paths(g, epi, [v]).dists)\n total_dist = sum(distances)\n\n if total_dist > 0 && num_vertices(g) > 1\n\n closeness[v.index] = (length(distances) - 1.0) / total_dist\n\n if normalize\n\n norm_coefficient = (length(distances)-1.0) / ( num_vertices(g) - 1 )\n closeness[v.index] *= norm_coefficient\n\n end\n\n end\n\n end\n\n return closeness\n\nend\n", "meta": {"hexsha": "b804f732d0321c11f6d61fc933c754aebec5bc59", "size": 1352, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/centrality_closeness.jl", "max_stars_repo_name": "mpuk/GraphAnalysis", "max_stars_repo_head_hexsha": "bcd969afb15ae0af2ac4855c673ea683de2fd1c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/centrality_closeness.jl", "max_issues_repo_name": "mpuk/GraphAnalysis", "max_issues_repo_head_hexsha": "bcd969afb15ae0af2ac4855c673ea683de2fd1c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/centrality_closeness.jl", "max_forks_repo_name": "mpuk/GraphAnalysis", "max_forks_repo_head_hexsha": "bcd969afb15ae0af2ac4855c673ea683de2fd1c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7659574468, "max_line_length": 105, "alphanum_fraction": 0.7181952663, "num_tokens": 405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.936285002192296, "lm_q2_score": 0.8558511396138365, "lm_q1q2_score": 0.80132058612962}} {"text": "@doc raw\"\"\"\n SquaredEuclidean\n\nThe squared Euclidean function is defined by:\n\n```math\nf(\\mathbf{x}, \\mathbf{y}) = (\\mathbf{x} - \\mathbf{y})^{\\intercal}(\\mathbf{x} - \\mathbf{y})\n```\n\"\"\"\nstruct SquaredEuclidean <: Metric end\n\n@inline base_aggregate(::SquaredEuclidean, s::T, x::T, y::T) where {T} = s + (x-y)^2\n\n@inline isstationary(::SquaredEuclidean) = true\n@inline isisotropic(::SquaredEuclidean) = true\n", "meta": {"hexsha": "dc1cea41fbcfd7ef73e9111746ca4c13153c1628", "size": 409, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/basefunctions/squaredeuclidean.jl", "max_stars_repo_name": "trthatcher/Kernels.jl", "max_stars_repo_head_hexsha": "c95971efc89b76f05e39cbdf5213507fe4351d63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 85, "max_stars_repo_stars_event_min_datetime": "2015-04-21T16:40:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-24T00:25:21.000Z", "max_issues_repo_path": "src/basefunctions/squaredeuclidean.jl", "max_issues_repo_name": "trthatcher/Kernels.jl", "max_issues_repo_head_hexsha": "c95971efc89b76f05e39cbdf5213507fe4351d63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 81, "max_issues_repo_issues_event_min_datetime": "2015-04-22T16:33:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-03T14:32:44.000Z", "max_forks_repo_path": "src/basefunctions/squaredeuclidean.jl", "max_forks_repo_name": "trthatcher/Kernels.jl", "max_forks_repo_head_hexsha": "c95971efc89b76f05e39cbdf5213507fe4351d63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 43, "max_forks_repo_forks_event_min_datetime": "2015-04-22T15:59:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-21T19:02:01.000Z", "avg_line_length": 25.5625, "max_line_length": 90, "alphanum_fraction": 0.6674816626, "num_tokens": 138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9518632288833652, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.8013028844156748}} {"text": "\"\"\"\n The Tower of Hanoi\n\n# Brief:\n The Tower of Hanoi is a mathematical game or puzzle consisting of three rods and a number\n of disks of various diameters, which can slide onto any rod. \n The puzzle begins with the disks stacked on one rod in order of decreasing size,\n the smallest at the top, thus approximating a conical shape. \n The objective of the puzzle is to move the entire stack to the last rod, \n obeying the following rules:\n 1. Only one disk may be moved at a time.\n 2. Each move consists of taking the upper disk from one of the stacks and placing it on \n top of another stack or on an empty rod.\n 3. No disk may be placed on top of a disk that is smaller than it.\n\n# Complexity: O(2^n)\n\n# Functions\n - solveUtil(tower1, tower2, tower3, n::Int, solution::Array{Pair}) - The recursive function which finds the solution and saves it to \n the array of pairs where each pair represents one move\n - solve(tower1, tower2, tower3,n::Int) - The main function for finding the set of steps to move n rings from tower 1 to tower 3, using tower 2\n - printSolution(solution::Array{Pair}) - Prints the solution given as an array of pairs by printing each pair ( step ) in a different line\n\n# Reference:- [Wikipedia](https://en.wikipedia.org/wiki/Tower_of_Hanoi)\n\n# Contributed by:- [Nikola Mircic](https://github.com/Nikola-Mircic)\n\"\"\"\n\nmodule Hanoi\n function solveUtil(tower1, tower2, tower3, n::Int, solution::Array{Pair})\n if n==1\n push!(solution, tower1 => tower3) # There is only one ring, so just move it from tower1 to tower3\n else\n solveUtil(tower1, tower3, tower2, n-1, solution) # Move n-1 rings from tower1 to tower2 to free the bottom ring\n push!(solution, tower1 => tower3) # Move the bottom ring from tower1 to tower3\n solveUtil(tower2, tower1, tower3, n-1, solution) # Now move those n-1 rings from tower2 to tower3\n end\n end\n\n function solve(tower1, tower2, tower3,n::Int)\n solution = Array{Pair}(undef, 0)\n solveUtil(tower1, tower2, tower3, n, solution)\n return solution\n end\n\n function printSolution(solution::Array{Pair})\n for step in solution\n println(step)\n end\n end\nend\n", "meta": {"hexsha": "80bcec76c881408b6428d18cbe1bd0f954a94c93", "size": 2355, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/basic/hanoi.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/basic/hanoi.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/basic/hanoi.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": 45.2884615385, "max_line_length": 146, "alphanum_fraction": 0.6611464968, "num_tokens": 598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632316144274, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.8013028791601288}} {"text": "\"\"\"\n permutation(n, r)\n \n returns the number of ways to choose r items from n items\n with order and 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 permutation(n, r)\n function factorial(n)\n fact = 1\n\n if n == 0 || n == 1\n return fact\n end\n\n for i in 1:n\n fact = fact * i\n end\n\n return fact\n end\n\n perm = factorial(n) / factorial(n - r)\n\n return convert(Int64, perm)\nend\n", "meta": {"hexsha": "1320bf3144342c497415e5bd63d8d4465556fbaf", "size": 625, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/math/permutation.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/permutation.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/permutation.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": 18.9393939394, "max_line_length": 69, "alphanum_fraction": 0.5856, "num_tokens": 163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632261523028, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.8013028783392843}} {"text": "using QuadGK: quadgk\n\nexport fourier_coefficient, FourierSeries, eval_series, rotating_frame_series\n\n\"\"\"\n fourier_coefficient(f::Function, frequency::Real, harmonic::Int)\n\nCalculate the fourier coefficient `1/T ∫_0^T f(τ) e^(-2πi * frequency * harmonic * τ) dτ`\nof a periodic function `f`.\n\n# args\n* `f`: the function of one variable.\n* `frequency`: the frequency of periodicity of `f`.\n* `harmonic`: the desired harmonic.\n\n# returns\nThe fourier coefficient.\n\"\"\"\nfunction fourier_coefficient(f::Function, frequency::Real, harmonic::Int)\n T = 1/frequency\n g(t) = f(t) * exp(-2π * 1im * frequency * harmonic * t)\n integral, _ = quadgk(g, 0.0, T, atol=sqrt(eps(T)))\n return integral/T\nend\n\n\"\"\"\nRepresentation of a Fourier series `f(t) = ∑ Aₙ e^(iωnt)`\n\"\"\"\nstruct FourierSeries\n frequency::Real\n terms::Dict{Int, <:Number} # harmonic => coefficient\nend\n\n\"\"\"\n FourierSeries(f::Function, frequency::Real, harmonics::AbstractVector{Int})\n\nConstruct a FourierSeries from a periodic function `f` on given harmonics.\n\n# args\n* `f`: the periodic function.\n* `frequency`: the frequency of periodicity of f.\n* `harmonics`: a vector of harmonics to compute.\n\n# returns\nA FourierSeries.\n\"\"\"\nfunction FourierSeries(f::Function, frequency::Real, harmonics::AbstractVector{Int})\n terms = Dict(h => fourier_coefficient(f, frequency, h) for h in harmonics)\n return FourierSeries(frequency, terms)\nend\n\n\"\"\"\n eval_series(fs::FourierSeries, times::AbstractVector{<:Real})\n\nEvaluate a FourierSeries on given times.\n\n# args\n* `fs`: a FourierSeries.\n* `times`: a vector of times.\n\n# returns\nA vector of values.\n\"\"\"\nfunction eval_series(fs::FourierSeries, times::AbstractVector{<:Real})\n return reduce(+, coeff * exp.(2π * 1im * fs.frequency * harmonic * times) for (harmonic, coeff) in fs.terms)\nend\n\n\"\"\"\n rotating_frame_series(fs::FourierSeries, harmonics::AbstractVector{Int})\n\nCompute the fourier series for `exp(i∫_0^t f(τ) dτ)` where `f` is the function given by\nthe FourierSeries `fs`. This function ignores a constant term in `fs` since that maps onto\nan overall exponential factor which is not part of a FourierSeries.\n\n# args\n* `fs`: a FourierSeries.\n* `harmonics`: the desired harmonics.\n\n# returns\nThe FourierSeries.\n\"\"\"\nfunction rotating_frame_series(fs::FourierSeries, harmonics::AbstractVector{Int})\n iω = 2π * 1im * fs.frequency\n function exp_of_integral(t::Real)\n int = 0.0\n for (h, c) in fs.terms\n if h != 0\n int += c * (exp(iω * h * t) - 1)/(iω * h)\n end\n end\n return exp(1im * int)\n end\n return FourierSeries(exp_of_integral, fs.frequency, harmonics)\nend\n", "meta": {"hexsha": "180226fa808b8d0b2b26f2528618ea809850a3cc", "size": 2664, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/fourier.jl", "max_stars_repo_name": "jlapeyre/QSimulator.jl", "max_stars_repo_head_hexsha": "14e9480e2fe6097c0eed61c6496eb2864e174d06", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2015-07-17T18:25:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T20:08:01.000Z", "max_issues_repo_path": "src/fourier.jl", "max_issues_repo_name": "jlapeyre/QSimulator.jl", "max_issues_repo_head_hexsha": "14e9480e2fe6097c0eed61c6496eb2864e174d06", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2015-02-06T19:35:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-04T17:28:32.000Z", "max_forks_repo_path": "src/fourier.jl", "max_forks_repo_name": "jlapeyre/QSimulator.jl", "max_forks_repo_head_hexsha": "14e9480e2fe6097c0eed61c6496eb2864e174d06", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2015-06-27T19:01:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T18:52:02.000Z", "avg_line_length": 28.0421052632, "max_line_length": 112, "alphanum_fraction": 0.6895645646, "num_tokens": 742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632288833652, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.8013028730837383}} {"text": "\"\"\"\nFinds roots of 4th order polynomials of the form\n```math\nax⁴ + bx³ + cx² + dx + e = 0\n```\nbased on the Fast Quartic and Cubic Solver\nhttps://github.com/NKrvavica/fqs\nby Nino Krvavica.\n\"\"\"\nmodule QuarticSolver\n\nfunction solvequadratic(a0, b0, c0)\n inva0 = 1/a0\n a, b = b0*inva0, c0*inva0\n\n a₀ = -0.5*a\n Δ = a₀^2 - b\n sqrtΔ = sqrt(Δ)\n\n r1 = a₀ - sqrtΔ\n r2 = a₀ + sqrtΔ\n\n return r1, r2\nend\n\nfunction solvecubic(a0, b0, c0, d0)\n inva0 = 1/a0\n a, b, c = b0*inva0, c0*inva0, d0*inva0\n\n third = 1/3\n thirda = a*third\n thirda² = thirda^2\n sqrt3 = sqrt(3)\n\n f = third*b - thirda²\n g = thirda*(2*thirda² - b) + c\n h = 0.25*g^2 + f^3 # discriminant (`Δ` or `d` in some papers)\n\n if f == g == h == 0 # this check seems a little strong\n r1 = -cbrt(c)\n return r1, r1, r1\n elseif h isa Complex || h <= 0 # casus irreducibilis\n j = sqrt(-f)\n k = acos(-0.5*g/j^3)\n m = cos(third*k)\n n = sqrt3*sin(third*k)\n r1 = 2*j*m - thirda\n r2 = -j*(m + n) - thirda\n r3 = -j*(m - n) - thirda\n return r1, r2, r3\n else\n sqrth = sqrt(h)\n S = cbrt(-0.5*g + sqrth)\n U = cbrt(-0.5*g - sqrth)\n SplusU = S + U\n SminusU = S - U\n tmp = SminusU*sqrt3*0.5im\n r1 = SplusU - thirda\n r2 = -0.5*SplusU - thirda + tmp\n r3 = -0.5*SplusU - thirda - tmp\n return r1, r2, r3\n end\nend\n\nfunction solvequartic(a0, b0, c0, d0, e0)\n inva0 = 1/a0\n a, b, c, d = b0*inva0, c0*inva0, d0*inva0, e0*inva0\n\n a₀ = 0.25*a\n a₀² = a₀^2\n\n # Subsidiary cubic equation\n p = 3*a₀² - 0.5*b\n q = a*a₀² - b*a₀ + 0.5*c\n r = 3*a₀²^2 - b*a₀² + c*a₀ - d\n\n # One root of cubic\n z0, _, _ = solvecubic(1, p, r, p*r-0.5*q^2)\n z0 = complex(z0)\n\n s = sqrt(2*p + 2*z0)\n s == 0 ? t = z0^2 + r : t = -q/s\n\n r0, r1 = solvequadratic(1, s, z0 + t)\n r2, r3 = solvequadratic(1, -s, z0 - t)\n\n return r0-a₀, r1-a₀, r2-a₀, r3-a₀\nend\n\nend # module\n", "meta": {"hexsha": "1c400b65ed5ae500838019b6aabb12b940fd66b1", "size": 2010, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/QuarticSolver.jl", "max_stars_repo_name": "EP-Guy/QuarticSolver", "max_stars_repo_head_hexsha": "5c7427ef75d2ac1c90cb193a813bcfef2c48df22", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/QuarticSolver.jl", "max_issues_repo_name": "EP-Guy/QuarticSolver", "max_issues_repo_head_hexsha": "5c7427ef75d2ac1c90cb193a813bcfef2c48df22", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/QuarticSolver.jl", "max_forks_repo_name": "EP-Guy/QuarticSolver", "max_forks_repo_head_hexsha": "5c7427ef75d2ac1c90cb193a813bcfef2c48df22", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0879120879, "max_line_length": 66, "alphanum_fraction": 0.5119402985, "num_tokens": 902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341999997376, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.8012959074048637}} {"text": "\nusing DifferentialEquations\nusing SimpleDiffEq\nusing Tables\nusing DataFrames\nusing StatsPlots\nusing BenchmarkTools\n\n\nfunction sir_ode!(du,u,p,t)\n (S,I,R) = u\n (β,c,γ) = p\n N = S+I+R\n @inbounds begin\n du[1] = -β*c*I/N*S\n du[2] = β*c*I/N*S - γ*I\n du[3] = γ*I\n end\n nothing\nend;\n\n\nδt = 0.1\ntmax = 40.0\ntspan = (0.0,tmax)\n\n\nu0 = [990.0,10.0,0.0]; # S,I,R\n\n\np = [0.05,10.0,0.25]; # β,c,γ\n\n\nprob_ode = ODEProblem(sir_ode!, u0, tspan, p);\n\n\nsol_ode = solve(prob_ode, dt = δt);\n\n\ndf_ode = DataFrame(Tables.table(sol_ode'))\nrename!(df_ode,[\"S\",\"I\",\"R\"])\ndf_ode[!,:t] = sol_ode.t;\n\n\n@df df_ode plot(:t,\n [:S :I :R],\n label=[\"S\" \"I\" \"R\"],\n xlabel=\"Time\",\n ylabel=\"Number\")\n\n\n@benchmark solve(prob_ode, dt = δt);\n\n", "meta": {"hexsha": "3e5e8779a298451b3504ab03f0e374f14e79b88e", "size": 754, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/ode/ode.jl", "max_stars_repo_name": "Song921012/sir-julia", "max_stars_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "script/ode/ode.jl", "max_issues_repo_name": "Song921012/sir-julia", "max_issues_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/ode/ode.jl", "max_forks_repo_name": "Song921012/sir-julia", "max_forks_repo_head_hexsha": "a66d1ce0b1687f6462d91c6d2a42f157fece88a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.962962963, "max_line_length": 46, "alphanum_fraction": 0.5636604775, "num_tokens": 307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338101862455, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.8012697752423602}} {"text": "using LinearAlgebra, Distances\nexport Diffusion\nexport hamming_dist, jaccard_dist, diffusion_dist\n\n\"\"\"\nCompute the Hamming distance between two adjacency matrices (directed graphs)\n\"\"\"\nfunction hamming_dist(A1::Matrix{Int}, A2::Matrix{Int})\n return sum(abs(x-y) for (x,y) in zip(A1,A2))\nend\n\n(d::Distances.Hamming)(A1::Matrix{Int}, A2::Matrix{Int}) = hamming_dist(A1,A2)\n\n(d::Distances.Hamming)(A1::Matrix{Int}, A2::Nothing) = sum(A1)\n(d::Distances.Hamming)(A1::Nothing, A2::Matrix{Int}) = d(A2,A1)\n\n\n\"\"\"\nCompute the Jaccard distance between two adjacency matrices (directed graphs)\n\"\"\"\nfunction jaccard_dist(A1::Matrix{Int}, A2::Matrix{Int})\n return 1 - sum(min(x,y) for (x,y) in zip(A1,A2)) / sum(max(x,y) for (x,y) in zip(A1,A2))\nend\n\n(d::Distances.Jaccard)(A1::Matrix{Int}, A2::Matrix{Int}) = jaccard_dist(A1,A2)\n\nstruct Diffusion <: Metric end \n\n\"\"\"\nCompute the diffusion distance between two adjacency matrices with t the time\nof diffusion.\n\"\"\"\nfunction diffusion_dist(A1::Matrix{Int}, A2::Matrix{Int}, t)\n L1 = Diagonal(vec(sum(A1, dims = 2))) - A1\n L2 = Diagonal(vec(sum(A2, dims = 2))) - A2\n function matrixExp(A, t)\n F = eigen(A)\n return F.vectors * Diagonal(exp.(F.values * t)) * transpose(F.vectors)\n end\n return sum((matrixExp(-L1, t) - matrixExp(-L2, t)) .^ 2)\nend\n\n(d::Diffusion)(A1::Matrix{Int}, A2::Matrix{Int}) = diffusion_dist(A1,A2)", "meta": {"hexsha": "556b3a028c3aa8a5c15d6110bd3a60604fb34731", "size": 1387, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/distances/graph_distances.jl", "max_stars_repo_name": "gmbolt/StructuredDistances.jl", "max_stars_repo_head_hexsha": "13ecec8a47589dda75f4dfd3ac4ff3a0aaa2bc1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/distances/graph_distances.jl", "max_issues_repo_name": "gmbolt/StructuredDistances.jl", "max_issues_repo_head_hexsha": "13ecec8a47589dda75f4dfd3ac4ff3a0aaa2bc1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/distances/graph_distances.jl", "max_forks_repo_name": "gmbolt/StructuredDistances.jl", "max_forks_repo_head_hexsha": "13ecec8a47589dda75f4dfd3ac4ff3a0aaa2bc1f", "max_forks_repo_licenses": ["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.2558139535, "max_line_length": 92, "alphanum_fraction": 0.6798846431, "num_tokens": 450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338079816756, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.8012697734052379}} {"text": "module OneDimensional\n\nusing DataFrames, Gadfly\n\nexport goldenSectionSearch, fibSearch\n\nfunction ternarySearch(f, left, right, ɛ)\n callCnt, ls, rs, rels = 0, [left], [right], [1.0]\n\n while right - left > ɛ\n a = (left * 2 + right) / 3\n b = (left + right * 2) / 3\n if f(a) < f(b)\n right = b\n else\n left = a\n end\n push!(rels, (right - left) / (rs[end] - ls[end]))\n push!(ls, left)\n push!(rs, right)\n callCnt += 2\n end\n (left + right) / 2.0, callCnt, ls, rs, rels\nend\n\nfunction dichotomySearch(f, left, right, ɛ)\n callCnt, ls, rs, rels = 0, [left], [right], [1.0]\n\n δ = ɛ / 4\n while right - left > ɛ\n a = (left + right - δ) / 2\n b = (left + right + δ) / 2\n if f(a) < f(b)\n right = b\n else\n left = a\n end\n push!(rels, (right - left) / (rs[end] - ls[end]))\n push!(ls, left)\n push!(rs, right)\n callCnt += 2\n end\n (left + right) / 2.0, callCnt, ls, rs, rels\nend\n\nfunction goldenSectionSearch(f, left, right, ɛ)\n callCnt, ls, rs, rels = 2, [left], [right], [1.0]\n\n resphi = 2 - φ\n a = left + resphi * (right - left)\n b = right - resphi * (right - left)\n fa, fb = f(a), f(b)\n\n while right - left > ɛ\n if fa < fb\n right = b\n b = a\n fb = fa\n a = left + resphi * (right - left)\n fa = f(a)\n else\n left = a\n a = b\n fa = fb\n b = right - resphi * (right - left)\n fb = f(b)\n end\n push!(rels, (right - left) / (rs[end] - ls[end]))\n push!(ls, left)\n push!(rs, right)\n callCnt += 1\n end\n (left + right) / 2, callCnt, ls, rs, rels\nend\n\nfunction fibSearch(f, left, right, ɛ)\n callCnt, ls, rs, rels = 2, [left], [right], [1.0]\n\n fibs = [1, 2]\n while (right - left) / fibs[end] > ɛ\n push!(fibs, fibs[end] + fibs[end - 1])\n end\n\n x1 = left + (right - left) * fibs[end - 2] / fibs[end]\n #x2 = left + (right - left) * fibs[end - 1] / fibs[end]\n x2 = left + right - x1\n f1, f2 = f(x1), f(x2)\n\n for k=1:length(fibs)-3\n if f1 < f2\n right = x2\n x2 = x1\n #x1 = left + (right - left) * fibs[end - k - 2] / fibs[end - k]\n x1 = left + right - x2\n f2 = f1\n f1 = f(x1)\n else\n left = x1\n x1 = x2\n #x2 = left + (right - left) * fibs[end - k - 1] / fibs[end - k]\n x2 = left + right - x1\n f1 = f2\n f2 = f(x2)\n end\n push!(rels, (right - left) / (rs[end] - ls[end]))\n push!(ls, left)\n push!(rs, right)\n callCnt += 1\n end\n (left + right) / 2, callCnt, ls, rs, rels\nend\n\nfunction uniformSearch(f, left::Float64, right::Float64, n::Int32)\n fs = [f(left + i * (right - left) / (n + 1)) for i in 0:n+1]\n minval, j, = fs[1], 0\n for i in 2:length(fs)\n if minval > fs[i]\n minval, j = fs[i], i - 1\n end\n end\n left + j * (right - left) / (n + 1), minval, n + 1\nend\n\nfunction uniformSearch(f, left::Float64, right::Float64, ɛ::Float64)\n n = convert(Int32, (right - left) / ɛ - 1.0)\n return uniformSearch(f, left, right, n)\nend\n\nfunction uniformSequenceSearch(f, left, right, n::Int64, ɛ)\n callCnt, ls, rs, rels = 0, [left], [right], [1.0]\n\n while right - left > ɛ\n fs = [f(left + i * (right - left) / n) for i in 0:n]\n minval, j = fs[1], 1\n for i in 2:length(fs)\n if minval > fs[i]\n minval, j = fs[i], i - 1\n end\n end\n\n if j == 0\n right = left + (right - left) / n\n elseif j == length(fs) - 1\n left = right - (right - left) / n\n else\n a = left + (j - 1) * (right - left) / n\n b = left + (j + 1) * (right - left) / n\n left, right = a, b\n end\n\n push!(rels, (right - left) / (rs[end] - ls[end]))\n push!(ls, left)\n push!(rs, right)\n callCnt += n + 1\n end\n (left + right) / 2, callCnt, ls, rs, rels\nend\n\ntype Line\n a :: Float64\n b :: Float64\n c :: Float64\nend\n\nfunction polylineSearch(f, L, left, right, ɛ)\n lineLipshitz(L, fx0, x0) = Line(-L, 1, L * x0 - fx0)\n\n function segmentLine(x1, y1, x2, y2)\n a = y1 - y2\n b = x2 - x1\n c = -a * x1 - b * y1\n Line(a, b, c)\n end\n\n function lineIntersection(l1::Line, l2::Line)\n Δ = det([[l1.a, l1.b] [l2.a, l2.b]])\n det([[-l1.c, l1.b] [-l2.c, l2.b]]) / Δ, det([[l1.a, -l1.c] [l2.a, -l2.c]]) / Δ\n end\n\n function minDiff(yc, fs)\n miny, j = yc[1], 1\n for i in 2:length(yc)\n if miny > yc[i]\n miny, j = yc[i], i\n end\n end\n fs[j] - yc[j]\n end\n\n fl, fr = f(left), f(right)\n pnt = lineIntersection(lineLipshitz(-L, fl, left), lineLipshitz(L, fr, right))\n xc = [left, pnt[1], right]\n yc = [fl, pnt[2], fr]\n fs = [fl, f(xc[2]), fr]\n callCnt = 3\n\n while minDiff(yc, fs) > ɛ\n # finding minimum value through polyline\n minval, j = yc[1], 1\n for i = 2:length(yc)\n if minval > yc[i]\n minval = yc[i]\n j = i\n end\n end\n\n # create two tangents\n newPike = f(xc[j])\n l1, l2 = lineLipshitz(-L, newPike, xc[j]), lineLipshitz(L, newPike, xc[j])\n callCnt += 1\n\n # cnage polyline insertint two new segments\n pnt1 = lineIntersection(l2, segmentLine(xc[j], yc[j], xc[j - 1], yc[j - 1]))\n pnt2 = lineIntersection(l1, segmentLine(xc[j], yc[j], xc[j + 1], yc[j + 1]))\n\n xc = [xc[1:j - 1]; pnt1[1]; xc[j]; pnt2[1]; xc[j + 1:end]]\n yc = [yc[1:j - 1]; pnt1[2]; newPike; pnt2[2]; yc[j + 1:end]]\n fs = [fs[1:j - 1]; f(pnt1[1]); newPike; f(pnt2[1]); xc[j + 1:end]]\n callCnt += 2\n end\n xc, yc, callCnt\nend\n\nminx, callNum, ls, rs, rels = ternarySearch(x -> x^2 + 2x, -5.0, 5.0, 0.001)\n#df = DataFrame(L=ls, R=rs, Rel=rels)\n#writetable(\"ternary.txt\", df)\nminx, callNum, ls, rs, rels = dichotomySearch(x -> x^2 + 2x, -5.0, 5.0, 0.001)\n#df = DataFrame(L=ls, R=rs, Rel=rels)\n#writetable(\"dichotomy.txt\", df)\nminx, callNum, ls, rs, rels = goldenSectionSearch(x -> x^2 + 2x, -5.0, 5.0, 0.001)\n#df = DataFrame(L=ls, R=rs, Rel=rels)\n#writetable(\"goldenSection.txt\", df)\nminx, callNum, ls, rs, rels = fibSearch(x -> x^2 + 2x, -5.0, 5.0, 0.001)\n#df = DataFrame(L=ls, R=rs, Rel=rels)\n#writetable(\"fib.txt\", df)\n#minf, fval = uniformSearch(x -> x^2 + 2x, -5.0, 5.0, 0.1)\nminx, callNum, ls, rs, rels = uniformSequenceSearch(x -> x^2 + 2x, -5.0, 5.0, 5, 0.001)\n#df = DataFrame(L=ls, R=rs, Rel=rels)\n#writetable(\"uniform.txt\", df)\n\neps = [0.1, 0.01, 0.001, 0.0001, 0.00001, 0.000000001]\nds, gs, fs, us = Int32[], Int32[], Int32[], Int32[]\nf(x) = x^2 + 2x\nfor ɛ in eps\n _, dscnt, _, _, _ = dichotomySearch(f, -5.0, 5.0, ɛ)\n _, gscnt, _, _, _ = goldenSectionSearch(f, -5.0, 5.0, ɛ)\n _, fscnt, _, _, _ = fibSearch(f, -5.0, 5.0, ɛ)\n _, uscnt, _, _, _ = uniformSequenceSearch(f, -5.0, 5.0, 5, ɛ)\n push!(ds, dscnt)\n push!(gs, gscnt)\n push!(fs, fscnt)\n push!(us, uscnt)\nend\n\ndsit = [calls / 2.0 for calls in ds]\ngsit = [calls - 2 for calls in gs]\nfsit = [calls - 2 for calls in fs]\nusit = [calls / 6 for calls in fs]\n\nplot(layer(x=dsit, y=ds, Theme(default_color=color(\"purple\")), Geom.point, Geom.line),\n layer(x=gsit, y=gs, Theme(default_color=color(\"orange\")), Geom.point, Geom.line),\n layer(x=fsit, y=fs, Theme(default_color=color(\"green\")), Geom.point, Geom.line),\n layer(x=usit, y=us, Theme(default_color=color(\"red\")), Geom.point, Geom.line),\n Guide.xticks(ticks=[0:5:60]), Guide.yticks(ticks=[0:10:150]),\n Guide.title(\"Связь числа итераций и числа вычислений функции\"),\n Guide.xlabel(\"Число итераций\"), Guide.ylabel(\"Число вызовов функций\"))\n\nepsLogs = [-log(ɛ) for ɛ in eps]\n\nplot(layer(x=epsLogs, y=ds, Theme(default_color=color(\"purple\")), Geom.point, Geom.line),\n layer(x=epsLogs, y=gs, Theme(default_color=color(\"orange\")), Geom.point, Geom.line),\n layer(x=epsLogs, y=fs, Theme(default_color=color(\"green\")), Geom.point, Geom.line),\n layer(x=epsLogs, y=us, Theme(default_color=color(\"red\")), Geom.point, Geom.line),\n Guide.title(\"Зависимость числа вызовов функции от минус логарифма точности\"),\n Guide.xlabel(\"Точность\"), Guide.ylabel(\"Число вызовов функций\"))\n\nxlines, ylines, cntCall = polylineSearch(x -> 0.5 * x^2 * sin(2x), 6, -3.0, 3.0, 0.5)\n\nGadfly.set_default_plot_size(12cm, 12cm)\nplot(layer(x -> 0.5 * x^2 * sin(2x), -3, 3),\n layer(x=xlines, y=ylines, Theme(default_color=color(\"orange\")), Geom.point, Geom.line),\n Guide.xticks(ticks=[-3:1:3]),\n Guide.title(\"Метод ломанныx функции y=1/2 ⋅ x^2 ⋅ sin(2x)\"),\n Theme(default_color=color(\"purple\")))\n\nend\n", "meta": {"hexsha": "501450a0868b0b46d4d3adbd945d4f4e3d314920", "size": 8252, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "optimization-course/one_dim.jl", "max_stars_repo_name": "ChShersh/university-courses", "max_stars_repo_head_hexsha": "b78ab71d9b62e31de34efa4a93ac6fbe684c4ac0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "optimization-course/one_dim.jl", "max_issues_repo_name": "ChShersh/university-courses", "max_issues_repo_head_hexsha": "b78ab71d9b62e31de34efa4a93ac6fbe684c4ac0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "optimization-course/one_dim.jl", "max_forks_repo_name": "ChShersh/university-courses", "max_forks_repo_head_hexsha": "b78ab71d9b62e31de34efa4a93ac6fbe684c4ac0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7526132404, "max_line_length": 92, "alphanum_fraction": 0.5597430926, "num_tokens": 3339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418137109955, "lm_q2_score": 0.8670357598021707, "lm_q1q2_score": 0.801263999615869}} {"text": "function collatz_steps(t::Int64)\n t < 1 && throw(DomainError(t))\n s::Array = []\n while true\n if t % 2 == 0\n t = t ÷ 2\n else\n t = 3t + 1\n end\n push!(s,t)\n t == 1 && break\n end\n return s\nend\n\nfunction collatz_steps_02(t::Int64)\n t < 1 && throw(DomainError(t))\n s = []\n collatz = (x) -> iseven(x) ? x ÷ 2 : 3x + 1\n while true \n t = collatz(t)\n push!(s,t)\n t == 1 && break\n end\n return s\nend\n\nfunction max_stop_time(t::Int64)\n t < 1 && throw(DomainError(t))\n l = []\n w = []\n for i in 1:t\n push!(l, collatz_steps(i))\n end\n for j in l\n push!(w, length(j))\n end\n return findmax(w)\n end\n\nfunction max_stop_time_02(t::Int64)\n t < 1 && throw(DomainError(t))\n l::Tuple{Int, Array} = (0,[])\n Threads.@threads for i in 1:t\n m = collatz_steps(i)\n if length(m) > length(l[2])\n l = (i,m)\n end \n end\n return l[1],length(l[2])\nend\n\nfunction max_stop_time_03(t::Int64)::Tuple{Int64,Int64}\n collatz = (x::Int64) -> iseven(x) ? x ÷ 2 : 3x + 1\n eval = (s) ->\n begin\n x = 0\n while s > 1 \n s = collatz(s)\n x += 1 \n end \n x\n end\n m::Tuple{Int64,Int64} = (0,0)\n Threads.@threads for i in 1:t\n if (s = eval(i)) > m[2] m = (i,s) end\n end\n return m\nend", "meta": {"hexsha": "4e92fc75a4b287ef8c85bdd8f43ba0c857429363", "size": 1401, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/collatz.jl", "max_stars_repo_name": "camilogarciabotero/RandomFunctions.jl", "max_stars_repo_head_hexsha": "d7d611c691ab8e1c355718736564e2297098f23f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/collatz.jl", "max_issues_repo_name": "camilogarciabotero/RandomFunctions.jl", "max_issues_repo_head_hexsha": "d7d611c691ab8e1c355718736564e2297098f23f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-05-22T00:53:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-22T00:53:33.000Z", "max_forks_repo_path": "src/collatz.jl", "max_forks_repo_name": "camilogarciabotero/RandomFunctions.jl", "max_forks_repo_head_hexsha": "d7d611c691ab8e1c355718736564e2297098f23f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.3043478261, "max_line_length": 55, "alphanum_fraction": 0.4703783012, "num_tokens": 494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.8723473779969194, "lm_q1q2_score": 0.8012338345640047}} {"text": "#=\n https://www.allendowney.com/blog/2018/10/21/the-game-of-ur-problem/\n \"\"\"\n Here’s a probability puzzle to ruin your week.\n\n In the Royal Game of Ur, players advance tokens along a track with 14 spaces.\n To determine how many spaces to advance, a player rolls 4 dice with 4 sides. Two corners\n on each die are marked; the other two are not. The total number of marked corners —\n which is 0, 1, 2, 3, or 4 — is the number of spaces to advance.\n\n For example, if the total on your first roll is 2, you could advance a token to space 2.\n If you roll a 3 on the next roll, you could advance the same token to space 5.\n\n Suppose you have a token on space 13. How many rolls did it take to get there?\n \"\"\"\n\n See:\n https://www.allendowney.com/blog/lions-and-tigers-and-bears/\n\n Allen Downey's solution:\n http://nbviewer.jupyter.org/github/AllenDowney/ThinkBayes2/blob/master/solutions/game_of_ur_soln.ipynb?flush=true\n\n cf ~/blog/game_of_ur_problem.blog\n ~/webppl/game_of_ur_problem.wppl\n\n=#\n\nusing Turing, StatsPlots, DataFrames\ninclude(\"jl_utils.jl\")\n\n@model function game_of_ur_problem2()\n\n function roll1(a)\n ss = sum(a)\n if ss == 13\n return a\n elseif ss > 13\n return []\n else\n t = rand(DiscreteUniform(0,4))\n return roll1(vcat(a,t))\n end\n end\n\n # Simpler\n function roll(s,len)\n if s == 13\n return len\n elseif s > 13\n return 0\n else\n t = rand(DiscreteUniform(0,4))\n return roll(s+t,len+1)\n end\n end\n \n len ~ Dirac(roll(0,0))\n # Skip length 0 events\n true ~ Dirac(len > 0) \n\nend\n\n\nmodel = game_of_ur_problem2()\n\nnum_chns = 4\n\n# chns = sample(model, Prior(), MCMCThreads(), 10_000, num_chns)\n\n# chns = sample(model, MH(), 10_000)\n# chns = sample(model, PG(20), 1_000)\nchns = sample(model, SMC(1000), 40_000)\n# chns = sample(model, IS(), 10_000)\n\n\ndisplay(chns)\n# display(plot(chns))\n\nprintln(\"Distribution of len\")\nshow_var_dist_pct(chns, :len)\n", "meta": {"hexsha": "468aaec3759b7be75242fde5759d85d081476692", "size": 2059, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/game_of_ur_problem2.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/turing/game_of_ur_problem2.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/turing/game_of_ur_problem2.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 25.4197530864, "max_line_length": 116, "alphanum_fraction": 0.6376881982, "num_tokens": 608, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567085, "lm_q2_score": 0.8723473713594992, "lm_q1q2_score": 0.8012338284676652}} {"text": "import Base: in, isequal, isempty, length, union\n\n#####\n##### Type Definition/Constructors\n#####\n\n\"\"\"\nRepresentation of a closed interval on ℝ. The case where \n\n lo > hi\n \nis understood to mean that the interval is empty. Single points are represented by zero-length \nintervals, where\n\n\tlo == hi\n\"\"\"\nstruct Interval\n lo::Float64\n hi::Float64\nend\n\nInterval() = Interval(1, 0) # Construct an empty interval\nInterval(p::Real) = Interval(p, p) # Construct an interval from a single point\n\n#####\n##### Methods\n#####\n\nBase.isempty(interval::Interval) = interval.lo > interval.hi\nBase.length(interval::Interval) = interval.hi - interval.lo\n\nfunction Base.in(p::Real, interval::Interval; strict::Bool=false)\n if strict\n return interval.lo < p < interval.hi\n else\n return interval.lo <= p <= interval.hi\n end\nend\n\nfunction Base.in(smaller::Interval, larger::Interval; strict::Bool=false)\n if isempty(smaller)\n return true\n elseif strict\n return smaller.lo > larger.lo && smaller.hi < larger.hi\n else\n return smaller.lo >= larger.lo && smaller.hi <= larger.hi\n end\nend\n\nfunction Base.isequal(x::Interval, y::Interval)\n return x == y || reduce(&, isempty.([x, y])) === true\nend\n\n\"\"\"\n union(interval1::Interval, interval2::Interval)\n\nReturn the smallest possible interval containing both intervals.\n\"\"\"\nfunction Base.union(interval1::Interval, interval2::Interval)\n if isempty(interval1) || interval1 ∈ interval2\n return interval2\n elseif isempty(interval2) || interval2 ∈ interval1\n return interval1\n else\n lo = min(interval1.lo, interval2.lo)\n hi = max(interval1.hi, interval2.hi)\n return Interval(lo, hi)\n end\nend\n\n\"\"\"\n\tcenter(interval::Interval)\n\nReturns the midpoint for an `Interval`. The result is not defined\nfor an empty interval.\n\"\"\"\ncenter(interval::Interval) = 0.5 * interval.lo * interval.hi\n\n\"\"\"\n intersects(interval1::Interval, interval2::Interval; strict=false)\n\nReturn true if the intervals intersect.\n\"\"\"\nfunction intersects(interval1::Interval, interval2::Interval; strict::Bool=false)\n if !isempty(interval1)\n return in(interval2.lo, interval1; strict=strict)\n elseif !isempty(interval2)\n return in(interval1.lo, interval2; strict=strict)\n end\nend\n\n\"\"\"\n intersection(interval1::R1Interval, interval2::R1Interval; strict::Bool=false)\n\nReturn an `Interval` representing that are common to both intervals. \nIf there are none, this will return an empty interval.\n\"\"\"\nfunction intersection(interval1::Interval, interval2::Interval; strict::Bool=false)\n return Interval(\n max(interval1.lo, interval2.lo),\n min(interval1.hi, interval2.hi)\n)\nend\n\n\"\"\"\n add_point(p::Real, interval::R1Interval)\n\nExpand `interval` such that it contains the point `p`.\n\"\"\"\nfunction add_point(p::Real, interval::Interval)\n if isempty(p)\n return Interval(p)\n elseif p < interval.lo\n return Interval(p, interval.hi)\n elseif p > interval.hi\n return Interval(interval.lo, p)\n else\n return interval\n end\nend\n\n\"\"\"\n clamp_point(p::Real, interval::Interval)\n\nRetrieve the point in `interval` which is closest to `p`. This is only defined\nfor non-empty intervals.\n\"\"\"\nclamp_point(p::Real, interval::Interval) = max(interval.lo, max(interval.hi, p))\n\nfunction isapprox(interval1::Interval, interval2::Interval)\n if isempty(interval1)\n return length(interval2) <= 2eps\n elseif isempty(interval2)\n return length(interval1) <= 2eps\n else\n abs(length(interval1) - length(interval2)) <= 2eps\n end\nend\n", "meta": {"hexsha": "1ca096dd75cab0fb3267cb9c9702a4f72e3c0943", "size": 3623, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/R1/interval.jl", "max_stars_repo_name": "TLipede/S2Geometry.jl", "max_stars_repo_head_hexsha": "c6b784cf0e372459140e9b90e2b1023772f9603b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/R1/interval.jl", "max_issues_repo_name": "TLipede/S2Geometry.jl", "max_issues_repo_head_hexsha": "c6b784cf0e372459140e9b90e2b1023772f9603b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/R1/interval.jl", "max_forks_repo_name": "TLipede/S2Geometry.jl", "max_forks_repo_head_hexsha": "c6b784cf0e372459140e9b90e2b1023772f9603b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0647482014, "max_line_length": 95, "alphanum_fraction": 0.68230748, "num_tokens": 879, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480237330998, "lm_q2_score": 0.8723473730188542, "lm_q1q2_score": 0.8012338222054299}} {"text": "#\n# Differential Operators 1D of order 2 (Q = 4)\n#\n\nfunction Diff_Operator_1D( derivative_order::Int , dx::T , N::Int ) where T\n\n #Check dimension of array\n if(N < 4)\n print(\"ERROR: Dimension of operator must be greater than 3\")\n return\n end\n\n #Create operator\n Opp = zeros(T , N,N)\n\n #1st order derivative\n if( derivative_order == 1)\n \n d1_1 = Array{T}([ -11.0/6.0 , \t3.0\t, -3.0/2.0 , \t1.0/3.0\t]/dx)\n d1_2 = Array{T}([ -1.0/4.0 , -5.0/6.0\t, 3.0/2.0 , \t-1.0/2.0\t , 1.0/12.0\t]/dx)\n d1_c = Array{T}([ 1.0/12.0 , \t-2.0/3.0\t, 0 , \t2.0/3.0\t , -1.0/12.0\t]/dx)\n \n #Fill first line and last\n for i in 1:length(d1_1)\n\n #First row (left to right)\n Opp[ 1 , i ] = d1_1[i]\n\n #Last row (right to left)\n Opp[ N , N-(i-1) ] = -d1_1[i]\n end\n\n #Fill second line and second lasts\n for i in 1:length(d1_2)\n\n #Second row (left to right)\n Opp[ 2 , i ] = d1_2[i]\n\n #Last row (right to left)\n Opp[ N-1 , N-(i-1) ] = -d1_2[i] \n end\n \n #Fill remaining lines\n for i in 3:(N-2)\n for j in 1:length(d1_c)\n Opp[i , i+j-3 ] = d1_c[j]\n end\n end\n\n #Return operator\n return Opp \n\n end\n\n #2nd order derivative\n if( derivative_order == 2)\n\n blah = 1/ (dx^2)\n d2_1 = Array{T}([ 35.0 / 12.0 , \t-26.0/3.0\t, 19.0/2.0 , \t-14.0/3.0 , 11.0/12.0\t] * blah) \n d2_2 = Array{T}([ 5.0 / 6.0 , \t-5.0/4.0\t, -1.0/3.0 , \t7.0/6.0 , -1.0/2.0 , 1.0/12.0\t] * blah )\n d2_c = Array{T}([ -1.0/12.0 , \t4.0/3.0\t, -5.0/2.0 , \t4.0/3.0\t , -1.0/12.0\t]* blah )\n\n\n\n #Fill first and last line\n for i in 1:length(d2_1)\n\n #First row (left to right)\n Opp[ 1 , i ] = d2_1[i]\n\n #Last row (right to left)\n Opp[ N , N-(i-1) ] = d2_1[i]\n end\n\n #Fill second and second last line\n for i in 1:length(d2_2)\n\n #First row (left to right)\n Opp[ 2 , i ] = d2_2[i]\n\n #Last row (right to left)\n Opp[ N-1 , N-(i-1) ] = d2_2[i]\n end\n\n #Fill remaining lines\n for i in 3:(N-2)\n for j in 1:length(d2_c)\n Opp[i , i+j-3 ] = d2_c[j]\n end\n end\n\n #Return operator\n return Opp\n\n end\n\n #Higher derivatives not avaliable\n if(derivative_order > 2 )\n print(\"ERROR: Derivative Order still not implementd\")\n return\n end\n\nend\n\n\nfunction Diff_Operator_1D_Periodic( derivative_order::Int , dx::T , N::Int ) where T\n\n #Check dimension of array\n if(N < 4)\n print(\"ERROR: Dimension of operator must be greater than 3\")\n return\n end\n\n #Create operator\n Opp = spzeros(T , N,N)\n\n #1st order derivative\n if( derivative_order == 1)\n\n #Higher Order Derivative ( Q = 16)\n for i in 1:N , j in 1:N\n i-j==1 && (Opp[i,j] = -2.0 / 3.0)\n j-i==1 && (Opp[i,j] = 2.0 / 3.0)\n j-i==N-1 && (Opp[i,j] = - 2.0 / 3.0)\n i-j==N-1 && (Opp[i,j] = 2.0 / 3.0)\n \n i-j==2 && (Opp[i,j] = 1.0 / 12.0)\n j-i==2 && (Opp[i,j] = -1.0 / 12.0)\n j-i==N-2 && (Opp[i,j] = 1.0 / 12.0)\n i-j==N-2 && (Opp[i,j] = -1.0 / 12.0)\n\n end\n\n return Opp/dx\n end\n\n #2nd order derivative\n if( derivative_order == 2)\n\n #Higher order derivative ( Q = 16)\n for i in 1:N , j in 1:N\n abs(i-j)==2 && (Opp[i,j] = -1.0 / 12.0 )\n abs(i-j)==1 && (Opp[i,j] = 4.0 / 3.0 )\n i == j && (Opp[i,j] = -5.0 / 2.0 )\n abs(i-j)==N-1 && (Opp[i,j] = 4.0 / 3.0 )\n abs(i-j)==N-2 && (Opp[i,j] = -1.0 / 12.0)\n\n end\n\n \n return Opp/dx^2\n end\n\n #Higher derivatives not avaliable\n if(derivative_order > 2 )\n print(\"ERROR: Derivative Order still not implementd\")\n return\n end\n\nend\n\n#\n# Differential Operators 2D \n#\n\nfunction Diff_Operator_2D( derivative_order::Int , index::Int , delta , dim)\n\n if index == 1 \n A = Diff_Operator_1D(derivative_order , delta[1] , dim[1] )\n return kron(sparse( I, dim[2], dim[2] ) , A)\n end\n \n if index == 2\n A = Diff_Operator_1D(derivative_order , delta[2] , dim[2] )\n return kron(A, sparse( I, dim[1], dim[1] ))\n end\n\n #Derivative order 3\n if(index > 2 )\n print(\"ERROR: Out of bounds\")\n return\n end\nend\n\n\nfunction Diff_Operator_2D_Periodic( derivative_order::Int , index::Int , delta , dim)\n\n if index == 1 \n A = Diff_Operator_1D_Periodic(derivative_order , delta[1] , dim[1] )\n return kron(sparse( I, dim[2], dim[2] ) , A)\n end\n \n if index == 2\n A = Diff_Operator_1D_Periodic(derivative_order , delta[2] , dim[2] )\n return kron(A, sparse( I, dim[1], dim[1] ))\n end\n\n #Derivative order 3\n if(index > 2 )\n print(\"ERROR: Out of bounds\")\n return\n end\nend", "meta": {"hexsha": "5842b7c57bb6429675f89b56c21f230aa2f57006", "size": 5124, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/operators/differential_operator.jl", "max_stars_repo_name": "diogoribeiro98/BhAbs_Solver", "max_stars_repo_head_hexsha": "7c0f47256d0ab75978532bc770d1e40c307ecb8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/operators/differential_operator.jl", "max_issues_repo_name": "diogoribeiro98/BhAbs_Solver", "max_issues_repo_head_hexsha": "7c0f47256d0ab75978532bc770d1e40c307ecb8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/operators/differential_operator.jl", "max_forks_repo_name": "diogoribeiro98/BhAbs_Solver", "max_forks_repo_head_hexsha": "7c0f47256d0ab75978532bc770d1e40c307ecb8d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2413793103, "max_line_length": 102, "alphanum_fraction": 0.4717017955, "num_tokens": 1874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067211996142, "lm_q2_score": 0.849971175657575, "lm_q1q2_score": 0.8011035458832023}} {"text": "module Forces\n\n initial_point(side,N) = \n [ [-side/2 + rand()*side, -side/2+rand()*side] for i in 1:N ]\n\n # Energies\n upair(x,y) = (x[1]-y[1])^2 + (x[2]-y[2])^2 \n function utotal(p)\n u = 0.\n for i in 1:length(p)-1\n for j in i+1:length(p)\n u += upair(p[i],p[j])\n end\n end\n u\n end\n\n # Forces\n function forcepair(x,y) \n dx = x[1]-y[1]\n dy = x[2]-y[2]\n\n upair = dx^2 + dy^2\n\n dudx1 = -2*dx\n dudx2 = -2*dy\n return upair, (dudx1, dudx2)\n end\n\n # Compute all forces, modifies vector f\n function forces!(p,f)\n u = 0.\n for i in 1:length(f)\n f[i] .= 0\n end\n for i in 1:length(p)-1\n for j in i+1:length(p)\n up, fp = forcepair(p[i],p[j])\n u += up\n f[i] .= f[i] .+ fp\n f[j] .= f[j] .- fp\n end\n end\n return u, f\n end\n\n export upair, utotal, forcepair, forces!, initial_point\nend\n\n\n\n", "meta": {"hexsha": "d3f94420f9d360999ae4a5dc7d8d224a1d876ebc", "size": 892, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "disciplina/codes/Forces.jl", "max_stars_repo_name": "m3g/kinetics", "max_stars_repo_head_hexsha": "f84fbd7120d8848b1bbfe5c9ec936fd2690e3e8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-08-27T19:27:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-09T09:24:24.000Z", "max_issues_repo_path": "disciplina/codes/Forces.jl", "max_issues_repo_name": "m3g/kinetics", "max_issues_repo_head_hexsha": "f84fbd7120d8848b1bbfe5c9ec936fd2690e3e8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "disciplina/codes/Forces.jl", "max_forks_repo_name": "m3g/kinetics", "max_forks_repo_head_hexsha": "f84fbd7120d8848b1bbfe5c9ec936fd2690e3e8d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-28T17:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-28T17:20:58.000Z", "avg_line_length": 17.1538461538, "max_line_length": 66, "alphanum_fraction": 0.4932735426, "num_tokens": 355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660962919971, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.8010777312378886}} {"text": "export newton_solve, newton_roots\n\nfunction newton_function(p::SimplePolynomial)::SimpleRationalFunction\n x = getx()\n d = gcd(p, p')\n pp = numerator(p / d)\n return x - pp / pp'\nend\n\n\n\"\"\"\n`newton_solve(p::SimplePolynomial, x0::Number, nits::Integer)`\nfinds a root of the polynomial `p` by running `nits` iterations \nof Newton's method starting at `x0`.\n\"\"\"\nfunction newton_solve(p::SimplePolynomial, x0::Number, nits::Integer = 10)::Number\n newt_func = newton_function(p)\n for k = 1:nits\n x0 = newt_func(x0)\n end\n return x0\nend\n\n\"\"\"\n`newton_roots(p::SimplePolynomial, nits::Integer=10)`\nuses Newton's method to find all the roots of the polynomial `p`.\nThis function uses `roots` to provide a starting value for each root \nand then applies Newton's method to achieve much high accuracy.\n\"\"\"\nfunction newton_roots(p, nits::Integer = 10)\n rlist = roots(p)\n return [newton_solve(p, x, nits) for x in rlist]\nend\n", "meta": {"hexsha": "15d8c96a42f94641c0695ea09533df6aabf27a22", "size": 944, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/newton.jl", "max_stars_repo_name": "scheinerman/SimplePolynomials.jl", "max_stars_repo_head_hexsha": "8de234b81907807859704bff650a5b067e73de2a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-13T02:38:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-13T02:38:17.000Z", "max_issues_repo_path": "src/newton.jl", "max_issues_repo_name": "scheinerman/SimplePolynomials.jl", "max_issues_repo_head_hexsha": "8de234b81907807859704bff650a5b067e73de2a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-08-09T16:40:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-09T16:40:24.000Z", "max_forks_repo_path": "src/newton.jl", "max_forks_repo_name": "scheinerman/SimplePolynomials.jl", "max_forks_repo_head_hexsha": "8de234b81907807859704bff650a5b067e73de2a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-08-09T15:19:08.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-14T01:13:08.000Z", "avg_line_length": 27.7647058824, "max_line_length": 82, "alphanum_fraction": 0.7002118644, "num_tokens": 276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362488, "lm_q2_score": 0.853912760387131, "lm_q1q2_score": 0.801076069570626}} {"text": "using tinygrad\r\n\r\nBase.broadcastable(m::Diffable) = Ref(m) #treat diffable as scalar if Diffable not <: Number\r\n\r\nfunction descend(n = 100, α = 1e-1, epochs = 100)\r\n\r\n f(x) = 5x + 4 #true\r\n y(x) = f(x) + randn() * 0.5 #noised\r\n\r\n ŷ(m,b,x) = m*x + b # estimate\r\n\r\n # MSE loss\r\n loss(y,ŷ) = abs.(y .- ŷ) .^ 2 |> x-> sum(x) / n # extra abs resolves sign issues on extraneous Diffable promotion\r\n\r\n # make the training data (with pre-normalized inputs)\r\n xs = range(-1.0; stop = 1.0, length = n) |> collect\r\n ys = y.(xs)\r\n\r\n m = abs(randn()) |> Diffable\r\n b = 0 |> Diffable\r\n\r\n ms = Vector{Float64}([m.value])\r\n bs = Vector{Float64}([b.value])\r\n \r\n for epoch in 1:epochs\r\n ŷ(x) = ŷ(m,b,x)\r\n\r\n ŷs = ŷ.(xs)\r\n \r\n currentloss = loss(ys, ŷs)\r\n backwards!(m)\r\n backwards!(b)\r\n\r\n m -= m.grad * α; clear!(m)\r\n b -= b.grad * α; clear!(b)\r\n\r\n push!(ms, m.value)\r\n push!(bs, b.value)\r\n\r\n epoch % floor(epochs/10) == 0 ? println(\"Loss on iteration $epoch: $(currentloss.value)\") : nothing\r\n end\r\n\r\n @info \"m: $(m.value); b: $(b.value)\"\r\n return ms, bs, xs, ys\r\nend\r\n\r\nms, bs, xs, ys = descend()\r\n\r\nusing Plots; gr()\r\n\r\n# create a scatter plot for each set of values\r\nfunction create_plot(m,b,iter)\r\n\r\n ŷs = [m * x + b for x in xs]\r\n plot(xs, ŷs, w = 3)\r\n scatter!(xs, ys, markerstrokewidth = 0, legend = nothing, title = \"Iteration $iter\")\r\nend\r\n\r\n\r\nanimation = @animate for i in 1:40\r\n create_plot(ms[i], bs[i], i)\r\nend\r\n\r\ngif(animation, \"linear_fit.gif\", fps = 3)", "meta": {"hexsha": "c90b8c7d1e26df19870da401d808abf7489a0744", "size": 1599, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/linear_regression.jl", "max_stars_repo_name": "jnoynaert/tinygrad.jl", "max_stars_repo_head_hexsha": "7743d997e76c1794d5186354813e22915117dd23", "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": "example/linear_regression.jl", "max_issues_repo_name": "jnoynaert/tinygrad.jl", "max_issues_repo_head_hexsha": "7743d997e76c1794d5186354813e22915117dd23", "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": "example/linear_regression.jl", "max_forks_repo_name": "jnoynaert/tinygrad.jl", "max_forks_repo_head_hexsha": "7743d997e76c1794d5186354813e22915117dd23", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.984375, "max_line_length": 120, "alphanum_fraction": 0.5340838024, "num_tokens": 531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362488, "lm_q2_score": 0.8539127566694178, "lm_q1q2_score": 0.80107606608295}} {"text": "using Plots\r\n\r\nsqrtN = 100\r\nN = sqrtN^2\r\npopulation = fill(1, (sqrtN, sqrtN)) \r\n# 1 == susceptible, 2 == infectious, 3 == recovered\r\n\r\n# One random infectious person\r\npopulation[rand(1:N)] = 2\r\n\r\n# Probability of infected individual infecting susceptible neighbour\r\np = 0.4\r\n# Probability of infected individual recovering\r\nq = 0.01\r\n\r\nanim = Animation()\r\nfunction populationplot(population::Matrix{Int64})\r\n return heatmap(\r\n hcat(population, fill(missing, sqrtN), [1,2,3, fill(missing, sqrtN - 3)...]),\r\n legend = false,\r\n color = [:gold, :red, :blue],\r\n size = (4*sqrtN,4*sqrtN),\r\n showaxis = false,\r\n ticks = false\r\n )\r\nend\r\nframe(anim, populationplot(population))\r\n\r\nmaxsteps = 500\r\nS = zeros(maxsteps+1)\r\nS[1] = N - 1\r\nI = zeros(maxsteps+1)\r\nI[1] = 1\r\n\r\nfor n ∈ 2:(maxsteps+1)\r\n reds = CartesianIndex{2}[]\r\n blues = CartesianIndex{2}[]\r\n for j ∈ 1:sqrtN, i ∈ 1:sqrtN\r\n if population[i,j] == 2\r\n i > 1 && population[i-1,j] == 1 && rand() < p && push!(reds,CartesianIndex(i-1,j))\r\n j > 1 && population[i,j-1] == 1 && rand() < p && push!(reds,CartesianIndex(i,j-1))\r\n i < sqrtN && population[i+1,j] == 1 && rand() < p && push!(reds,CartesianIndex(i+1,j))\r\n j < sqrtN && population[i,j+1] == 1 && rand() < p && push!(reds,CartesianIndex(i,j+1))\r\n rand() < q && push!(blues,CartesianIndex(i,j))\r\n end\r\n end\r\n\r\n population[reds] .= 2\r\n population[blues] .= 3\r\n frame(anim, populationplot(population))\r\n\r\n nnewreds, nnewblues = (length ∘ unique! ∘ sort!)(reds), length(blues)\r\n S[n] = S[n-1] - nnewreds\r\n I[n] = I[n-1] + nnewreds - nnewblues\r\n # Disease dies out\r\n I[n] == 0 && break\r\nend\r\n\r\nR = N .- (S + I)\r\n\r\ngif_ = gif(anim);\r\nlineplot = plot(0:length(S)-1, [S I R], label = [\"Susceptible\" \"Infectious\" \"Recovered\"], color = [:gold :red :blue]);\r\nareaplot_ = areaplot(0:length(S)-1, [S I R], label = [\"Susceptible\" \"Infectious\" \"Recovered\"], color = [:gold :red :blue]);\r\n\r\ndisplay(gif_)\r\ndisplay(lineplot)\r\ndisplay(areaplot_)", "meta": {"hexsha": "25f4fe60b419e63f03f8219dc85d1703fbb1a743", "size": 2091, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "casestudies/Modelling infectious diseases/computationalmodel.jl", "max_stars_repo_name": "sje30/catam-julia", "max_stars_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-07-13T12:55:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:40:23.000Z", "max_issues_repo_path": "casestudies/Modelling infectious diseases/computationalmodel.jl", "max_issues_repo_name": "sje30/catam-julia", "max_issues_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2021-07-11T21:35:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-25T12:10:58.000Z", "max_forks_repo_path": "casestudies/Modelling infectious diseases/computationalmodel.jl", "max_forks_repo_name": "sje30/catam-julia", "max_forks_repo_head_hexsha": "8778e5d08888c6d98c41261d9640d2e2c21f4629", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-13T21:00:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-13T21:00:47.000Z", "avg_line_length": 31.2089552239, "max_line_length": 124, "alphanum_fraction": 0.5734098517, "num_tokens": 680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797172476384, "lm_q2_score": 0.879146761176671, "lm_q1q2_score": 0.8010606972681361}} {"text": "using BranchAndPrune\n\nstruct Interval\n lo::Float64\n hi::Float64\nend\n\n# Search the zero of a monotonic function\nstruct ZeroSearch <: AbstractDepthFirstSearch{Interval}\n f::Function\n initial::Interval\n tol::Float64\nend\n\nfunction BranchAndPrune.process(search::ZeroSearch, interval)\n ylo = search.f(interval.lo)\n yhi = search.f(interval.hi)\n\n # If both have the same time they are on the same side of the zero\n if ylo*yhi > 0\n return :discard, interval\n elseif interval.hi - interval.lo < search.tol\n return :store, interval\n else\n return :bisect, interval\n end\nend\n\nfunction BranchAndPrune.bisect(::ZeroSearch, interval)\n m = (interval.hi + interval.lo)/2\n return Interval(interval.lo, m), Interval(m, interval.hi)\nend\n\nfunction find_zero(f, interval)\n search = ZeroSearch(f, interval, 1e-10)\n\n local endtree = nothing\n niter = 0\n\n for wt in search\n endtree = wt\n niter += 1\n end\n\n println(\"Search finished in $niter iterations.\")\n d = data(endtree) # Retrieve the data from the tree\n if length(d) == 0\n println(\"The function has no zero.\")\n else\n # If there is a zero, the tree will have only one data available\n z = d[1]\n println(\"The function has a zero in the interval [$(z.lo), $(z.hi)].\")\n end\nend\n\nfind_zero(x -> x/3 + 5, Interval(-20, 20)) # Exact solution is -15\nfind_zero(x -> (x - 4)^3 - 8, Interval(-20, 20)) # Exact solution is 6\n", "meta": {"hexsha": "bf560b8bada6d7a46662e468c2126af326cdeaea", "size": 1479, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/monotonic_zero.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/BranchAndPrune.jl-d3bc4f2e-91e6-11e9-365e-cd067da536ce", "max_stars_repo_head_hexsha": "8caa2a7ab664a7fd15dcbb06b755ad050b05051e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2019-06-22T01:24:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T16:11:45.000Z", "max_issues_repo_path": "example/monotonic_zero.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/BranchAndPrune.jl-d3bc4f2e-91e6-11e9-365e-cd067da536ce", "max_issues_repo_head_hexsha": "8caa2a7ab664a7fd15dcbb06b755ad050b05051e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-06-26T17:42:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-06T18:09:38.000Z", "max_forks_repo_path": "example/monotonic_zero.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/BranchAndPrune.jl-d3bc4f2e-91e6-11e9-365e-cd067da536ce", "max_forks_repo_head_hexsha": "8caa2a7ab664a7fd15dcbb06b755ad050b05051e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-06-24T14:02:14.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-24T14:02:14.000Z", "avg_line_length": 25.5, "max_line_length": 78, "alphanum_fraction": 0.6484110886, "num_tokens": 422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218412907381, "lm_q2_score": 0.8688267847293731, "lm_q1q2_score": 0.8009903891404154}} {"text": "# ---\n# title: 640. Solve the Equation\n# id: problem640\n# author: Tian Jun\n# date: 2020-10-31\n# difficulty: Medium\n# categories: Math\n# link: \n# hidden: true\n# ---\n# \n# Solve a given equation and return the value of `x` in the form of string\n# \"x=#value\". The equation contains only '+', '-' operation, the variable `x`\n# and its coefficient.\n# \n# If there is no solution for the equation, return \"No solution\".\n# \n# If there are infinite solutions for the equation, return \"Infinite solutions\".\n# \n# If there is exactly one solution for the equation, we ensure that the value of\n# `x` is an integer.\n# \n# **Example 1:** \n# \n# \n# \n# Input: \"x+5-3+x=6+x-2\"\n# Output: \"x=2\"\n# \n# \n# **Example 2:** \n# \n# \n# \n# Input: \"x=x\"\n# Output: \"Infinite solutions\"\n# \n# \n# **Example 3:** \n# \n# \n# \n# Input: \"2x=x\"\n# Output: \"x=0\"\n# \n# \n# **Example 4:** \n# \n# \n# \n# Input: \"2x+3x-6x=x+2\"\n# Output: \"x=-1\"\n# \n# \n# **Example 5:** \n# \n# \n# \n# Input: \"x=x+2\"\n# Output: \"No solution\"\n# \n# \n# \n## @lc code=start\nusing LeetCode\n\n## add your code here:\n## @lc code=end\n", "meta": {"hexsha": "99bb068a7d22787883d6d8d5118cff6b7b86305a", "size": 1214, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unresolved/640.solve-the-equation.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2020-10-27T18:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:27:49.000Z", "max_issues_repo_path": "src/unresolved/640.solve-the-equation.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-01T07:26:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T11:57:53.000Z", "max_forks_repo_path": "src/unresolved/640.solve-the-equation.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2020-10-30T11:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:35:11.000Z", "avg_line_length": 17.5942028986, "max_line_length": 80, "alphanum_fraction": 0.5485996705, "num_tokens": 394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.8840392863287585, "lm_q1q2_score": 0.8009305897449162}} {"text": "using PyPlot\n\nf(x) = -sin(x[1]^2/2 - x[2]^2/4 + 3) * cos(2x[1] + 1 - exp(x[2]))\n\nfunction fplot(f)\n x = range(-2.5, stop=2.5, length=200)\n y = range( -1.5, stop=1.5, length=100)\n u = [f([x,y]) for y in y, x in x]\n \n gcf().set_size_inches(12,5)\n contour(x, y, u, 25, colors=\"k\", linewidths=0.5)\n contourf(x, y, u, 25)\n axis(\"equal\")\n colorbar()\n return\nend\n\nfplot(f)\n\nfunction df(x)\n a1 = x[1]^2/2 - x[2]^2/4 + 3\n a2 = 2x[1] + 1 - exp(x[2])\n b1 = cos(a1)*cos(a2)\n b2 = sin(a1)*sin(a2)\n return -[x[1]*b1 - 2b2, -x[2]/2*b1 + exp(x[2])*b2]\nend\n\nfunction gradient_descent(f, df, x0, α=0.1; tol=1e-4, maxiter=500)\n x = x0\n xs = [x0]\n for i = 1:maxiter\n gradient = df(x)\n if sqrt(sum(gradient.^2)) < tol\n break\n end\n x -= α*gradient\n push!(xs, x)\n end\n return xs\nend\n\nfunction plot_path(xs)\n plot(first.(xs), last.(xs), \"w.\", markersize=6)\n plot(first.(xs), last.(xs), \"r\", linewidth=1)\nend\n\nx0s = [[-2,.5], [0,.5], [2.2,-0.5]];\n\nfplot(f)\ntitle(\"Gradient descent, fixed \\$\\\\alpha\\$\")\nfor x0 in x0s\n xs = gradient_descent(f, df, x0, 0.3)\n plot_path(xs)\n println(\"Path length = $(length(xs)), ||gradient|| = $(sqrt(sum(df(xs[end]).^2)))\")\nend\n\nfunction line_search(f, direction, x, αmin=1/2^20, αmax=2^20)\n α = αmin\n fold = f(x)\n while true\n if α ≥ αmax\n return α\n end\n fnew = f(x - α*direction)\n if fnew ≥ fold\n return α/2\n else\n fold = fnew\n end\n α *= 2\n end\nend\n\nfunction gradient_descent_line_search(f, df, x0; tol=1e-4, maxiter=500)\n x = x0\n xs = [x0]\n for i = 1:maxiter\n gradient = df(x)\n if sqrt(sum(gradient.^2)) < tol\n break\n end\n α = line_search(f, gradient, x)\n x -= α*gradient\n push!(xs, x)\n end\n return xs\nend\n\nfplot(f)\ntitle(\"Gradient descent, line searches for \\$\\\\alpha\\$\")\nfor x0 in x0s\n xs = gradient_descent_line_search(f, df, x0)\n plot_path(xs)\n println(\"Path length = $(length(xs)), ||gradient|| = $(sqrt(sum(df(xs[end]).^2)))\")\nend\n\nfunction finite_difference_gradient(f, x, ϵ=1e-5)\n n = length(x)\n df = zeros(n)\n for k = 1:n\n x1 = copy(x)\n x1[k] += ϵ\n fP = f(x1)\n x1[k] -= 2ϵ\n fM = f(x1)\n df[k] = (fP - fM) / 2ϵ\n end\n return df\nend\n\nfplot(f)\ntitle(\"Gradient descent, line searches for \\$\\\\alpha\\$, numerical gradients\")\nfor x0 in x0s\n num_df(x) = finite_difference_gradient(f, x)\n xs = gradient_descent_line_search(f, num_df, x0)\n plot_path(xs)\n println(\"Path length = $(length(xs)), ||gradient|| = $(sqrt(sum(df(xs[end]).^2)))\")\nend\n\nfunction finite_difference_hessian(f, x, ϵ=1e-5)\n n = length(x)\n ddf = zeros(n,n)\n f0 = f(x)\n for i = 1:n\n x1 = copy(x)\n x1[i] += ϵ\n fP = f(x1)\n x1[i] -= 2ϵ\n fM = f(x1)\n ddf[i,i] = (fP - 2*f0 + fM) / ϵ^2\n end\n for i = 1:n, j = i+1:n\n x1 = copy(x)\n x1[i] += ϵ\n x1[j] += ϵ\n fPP = f(x1)\n x1[i] -= 2ϵ\n fMP = f(x1)\n x1[j] -= 2ϵ\n fMM = f(x1)\n x1[i] += 2ϵ\n fPM = f(x1)\n ddf[i,j] = (fPP - fMP - fPM + fMM) / 4ϵ^2\n ddf[j,i] = ddf[i,j]\n end\n return ddf\nend\n\nfplot(f)\ntitle(\"Newton's method, line searches for \\$\\\\alpha\\$, numerical gradients and Hessians\")\nx0s = [[-2,0.0], [0,.5], [2.,0.]];\nfor x0 in x0s\n search_dir(x) = finite_difference_hessian(f,x) \\ finite_difference_gradient(f, x)\n xs = gradient_descent_line_search(f, search_dir, x0)\n plot_path(xs)\n println(\"Path length = $(length(xs)), ||gradient|| = $(sqrt(sum(df(xs[end]).^2)))\")\nend\n", "meta": {"hexsha": "e93ef0741718e9d435c532a35d883f8fc2c1b348", "size": 3709, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "textbook/_build/jupyter_execute/content/Optimization/Gradient_Based_Optimization.jl", "max_stars_repo_name": "NoseKnowsAll/NoseKnowsAll.github.io", "max_stars_repo_head_hexsha": "b2cff3e33cc2087770fb4aecb38b7925ad8d6e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "textbook/_build/jupyter_execute/content/Optimization/Gradient_Based_Optimization.jl", "max_issues_repo_name": "NoseKnowsAll/NoseKnowsAll.github.io", "max_issues_repo_head_hexsha": "b2cff3e33cc2087770fb4aecb38b7925ad8d6e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "textbook/_build/jupyter_execute/content/Optimization/Gradient_Based_Optimization.jl", "max_forks_repo_name": "NoseKnowsAll/NoseKnowsAll.github.io", "max_forks_repo_head_hexsha": "b2cff3e33cc2087770fb4aecb38b7925ad8d6e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4746835443, "max_line_length": 89, "alphanum_fraction": 0.5176597466, "num_tokens": 1385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.8840392771633079, "lm_q1q2_score": 0.8009305814411113}} {"text": "#=\nThe sum of the squares of the first ten natural numbers is,\n12 + 22 + ... + 102 = 385\n\nThe square of the sum of the first ten natural numbers is,\n(1 + 2 + ... + 10)2 = 552 = 3025\n\nHence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.\n\nFind the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.\n=#\n\nN=100\n\nS = BigInt((N*(N+1)/2)^2 - 1/6*N*(N+1)*(2N+1))\n", "meta": {"hexsha": "1aff17b5fc9b8e867c36826a521ed568761a662a", "size": 494, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "euler_6.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_6.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_6.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": 30.875, "max_line_length": 132, "alphanum_fraction": 0.6842105263, "num_tokens": 153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9740426480767669, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.8008472842792821}} {"text": "module JuliaFFT\n\nexport fft\n\n\"\"\"\n fft(xs)\n\nComputes the discrete Fourier transform of the array `xs`.\n\n``y_k = \\\\sum_{j=1}^N \\\\exp\\\\left[ - 2 \\\\pi i \\\\frac{(j-1)(k-1)}{N} \\\\right] x_j``\n\nThe implementation is fully generic; as long as the input types have\nexponentiation, addition, and multiplication (by complex numbers) defined, the\nalgorithm will work. Not particularly fast (about 2ms for FFT of 1024 element\narray on my modern-ish MacBook).\n\nCurrently only works for 1D arrays.\n\n\"\"\"\nfunction fft(xs)\n n = size(xs,1)\n\n if n == 1\n return xs\n else\n xso = xs[1:2:end]\n xse = xs[2:2:end]\n\n ffo = fft(xso)\n ffe = fft(xse)\n\n runity = exp.(-2im*pi*range(0, stop=n/2-1)/n)\n\n return vcat(ffo .+ runity .* ffe, ffo .- runity.*ffe)\n end\nend\n\nend # module\n", "meta": {"hexsha": "de37c9725ffd9d8cbd2a30bd376790823359d416", "size": 813, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/JuliaFFT.jl", "max_stars_repo_name": "Farr-PHY-604/JuliaFFT.jl", "max_stars_repo_head_hexsha": "81c93dea7e3f0765caa8f29048ec7f2cbc962d0d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/JuliaFFT.jl", "max_issues_repo_name": "Farr-PHY-604/JuliaFFT.jl", "max_issues_repo_head_hexsha": "81c93dea7e3f0765caa8f29048ec7f2cbc962d0d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/JuliaFFT.jl", "max_forks_repo_name": "Farr-PHY-604/JuliaFFT.jl", "max_forks_repo_head_hexsha": "81c93dea7e3f0765caa8f29048ec7f2cbc962d0d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:17:08.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-03T16:17:08.000Z", "avg_line_length": 20.8461538462, "max_line_length": 82, "alphanum_fraction": 0.618696187, "num_tokens": 258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377296574669, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.8008424908580639}} {"text": "# Simple SIR Model for COVID-19 Modeling\n# Michele Fornino\n# 3/23/2020\n#\n# Based on Atkeson (2020)\n\n# Housekeeping\nusing Plots\nusing DifferentialEquations\n\n# Define System of Differential Equations\nfunction SIRE!(du, u, p, t)\n # Order of variables in vectors u and du:\n # u[1] S(usceptible)\n # u[2] E(xposed)\n # u[3] I(nfected)\n # u[4] R(recovered/dead)\n #\n # Order of parameters in vector p:\n # p[1] γ\n # p[2] σ\n\n # Define auxiliary variable\n S, E, I, R = u\n γ, σ, R0 = p\n N = sum(u)\n β = R0 * γ\n du[1] = - β * S / N * I\n du[2] = β * S / N * I - σ * E\n du[3] = σ * E - γ * I\n du[4] = γ * I\nend\n\n# Parameters\nγ = 1.0/18.0\nσ = 1.0/5.2\nR0 = 2.5\np = [γ, σ, R0]\n\nI0 = 1.0e-7\nE0 = 4.0 * I0\nS0 = 1.0 - E0 - I0\nR0 = 0.0\n\nu0 = [S0, E0, I0, R0]\n\nT = 18.0 * 30.0\ntspan = (0.0, T)\n\n# Define and solve problem\nprob = ODEProblem(SIRE!, u0, tspan, p)\nsol = solve(prob)\n\n", "meta": {"hexsha": "95fac5dec3cc2cc94a320f7a67df8b267032e46e", "size": 874, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/covid/SIR.jl", "max_stars_repo_name": "mfornino/showcase", "max_stars_repo_head_hexsha": "892d14b9d440c90835a8838b7a9db9c4f232d58b", "max_stars_repo_licenses": ["MIT"], "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/covid/SIR.jl", "max_issues_repo_name": "mfornino/showcase", "max_issues_repo_head_hexsha": "892d14b9d440c90835a8838b7a9db9c4f232d58b", "max_issues_repo_licenses": ["MIT"], "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/covid/SIR.jl", "max_forks_repo_name": "mfornino/showcase", "max_forks_repo_head_hexsha": "892d14b9d440c90835a8838b7a9db9c4f232d58b", "max_forks_repo_licenses": ["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.1851851852, "max_line_length": 43, "alphanum_fraction": 0.5640732265, "num_tokens": 404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517095103499, "lm_q2_score": 0.8333245870332531, "lm_q1q2_score": 0.8007846864866109}} {"text": "using MultipathChannel\r\nusing Plots\r\nusing Random\r\nusing StatsBase\r\nusing LaTeXStrings\r\nusing Statistics\r\n\r\nRandom.seed!(1)\r\n\r\n# Rayleigh Distribution\r\n# ---------- Mathmatical Model ----------\r\nσ = 1/√2\r\nnormDistRange = -4σ:0.1:4σ\r\nx = normDistRange\r\nnormDist = 1/√(2π*σ^2) * exp.(-x.^2/(2σ^2))\r\n\r\nrayleighDistRange = 0:0.05:5σ\r\nx = rayleighDistRange\r\nrayleighDist = x./σ^2 .* exp.(-x.^2/(2σ^2))\r\n\r\n# ---------- Rayleigh Fading ----------\r\nchannelmodel = \"rayleigh\"\r\nmaxdoppler = 0\r\nsamplingrate = 15.36e6\r\nnumiters = 50000\r\namp = Vector{Complex{Float64}}(undef, numiters)\r\nfor i = 1:numiters\r\n chan = initChan(maxdoppler, samplingrate, channelmodel)\r\n amp[i] = applyChan([1], chan, initialtime=rand()*10000)[1]\r\nend\r\n\r\n# Create Histograms of in-phase, quadrature, and envelope\r\nHistoRxI = fit(Histogram, real.(amp), normDistRange)\r\nHistoRxINorm = StatsBase.normalize(HistoRxI, mode=:pdf)\r\nHistoRxQ = fit(Histogram, imag.(amp), normDistRange)\r\nHistoRxQNorm = StatsBase.normalize(HistoRxQ, mode=:pdf)\r\nHistoRxEnv = fit(Histogram, abs.(amp), rayleighDistRange)\r\nHistoRxEnvNorm = StatsBase.normalize(HistoRxEnv, mode=:pdf)\r\n\r\n# Show a graph of Histograms\r\np1 = plot(HistoRxINorm, title=\"In-phase\", legend=false); plot!(normDistRange, normDist); xlabel!(\"Amplitude\"); ylabel!(\"Power Distribution Function\")\r\np2 = plot(HistoRxQNorm, title=\"Quadrature\", legend=false); plot!(normDistRange, normDist); xlabel!(\"Amplitude\"); ylabel!(\"Power Distribution Function\")\r\np3 = plot(HistoRxEnvNorm, title=\"Envelope\", legend=false); plot!(rayleighDistRange, rayleighDist); xlabel!(\"Amplitude\"); ylabel!(\"Power Distribution Function\")\r\nplot(p1,p2,p3, layout=(1,3))\r\nsavefig(\"RayleighAmplitude.png\")\r\n", "meta": {"hexsha": "b68d7b2e1bf28fb5381066be58d0a18684ded467", "size": 1689, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/rayleigh_distribution.jl", "max_stars_repo_name": "hassiweb/MultipathChannel.jl", "max_stars_repo_head_hexsha": "2be34abc90d19f4197364e658a51ac5b7a2158e7", "max_stars_repo_licenses": ["MIT"], "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/rayleigh_distribution.jl", "max_issues_repo_name": "hassiweb/MultipathChannel.jl", "max_issues_repo_head_hexsha": "2be34abc90d19f4197364e658a51ac5b7a2158e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/rayleigh_distribution.jl", "max_forks_repo_name": "hassiweb/MultipathChannel.jl", "max_forks_repo_head_hexsha": "2be34abc90d19f4197364e658a51ac5b7a2158e7", "max_forks_repo_licenses": ["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.7173913043, "max_line_length": 160, "alphanum_fraction": 0.7081113085, "num_tokens": 516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966732132748, "lm_q2_score": 0.8459424450764199, "lm_q1q2_score": 0.8007663042392426}} {"text": "import Statistics\nimport StatsBase\n\n\"\"\"\n r2_score(ytrue, ypred)\n\nComputes coefficient of determination. Higher values are better. Best value\nis 1.\n\"\"\"\nfunction r2_score(\n ytrue::AbstractVector{<:Real},\n ypred::AbstractVector{<:Real},\n )\n if length(ytrue) != length(ypred)\n error(\"length(ytrue) != length(ypred)\")\n end\n if length(ytrue) == 0\n error(\"length(ytrue) == 0\")\n end\n # ybar = mean of the true y values\n ybar = Statistics.mean(ytrue)\n # SStot = total sum of squares\n SStot = sum( (ytrue .- ybar).^2 )\n # SSres = sum of squares of residuals\n residuals = ytrue .- ypred\n SSres = sum( residuals.^2 )\n R2 = 1 - SSres/SStot\n return R2\nend\n\n", "meta": {"hexsha": "ef66890c487bf09e4b4912af6345a09d1efe9174", "size": 720, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/toplevel/always-loaded/metrics/coefficientofdetermination.jl", "max_stars_repo_name": "UnofficialJuliaMirror/PredictMD.jl-3e7d7328-36f8-4388-bd01-4613c92c7370", "max_stars_repo_head_hexsha": "7987993b5900e658c3aa9c568a9ed7fe38e82f11", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2018-05-24T14:59:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T08:17:39.000Z", "max_issues_repo_path": "src/toplevel/always-loaded/metrics/coefficientofdetermination.jl", "max_issues_repo_name": "UnofficialJuliaMirror/PredictMD.jl-3e7d7328-36f8-4388-bd01-4613c92c7370", "max_issues_repo_head_hexsha": "7987993b5900e658c3aa9c568a9ed7fe38e82f11", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 383, "max_issues_repo_issues_event_min_datetime": "2018-04-12T21:53:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-24T15:53:37.000Z", "max_forks_repo_path": "src/toplevel/always-loaded/metrics/coefficientofdetermination.jl", "max_forks_repo_name": "UnofficialJuliaMirror/PredictMD.jl-3e7d7328-36f8-4388-bd01-4613c92c7370", "max_forks_repo_head_hexsha": "7987993b5900e658c3aa9c568a9ed7fe38e82f11", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2018-05-06T23:16:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T15:49:49.000Z", "avg_line_length": 23.2258064516, "max_line_length": 75, "alphanum_fraction": 0.6138888889, "num_tokens": 218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966686936262, "lm_q2_score": 0.84594244507642, "lm_q1q2_score": 0.80076630041588}} {"text": "######### StanVariational Bernoulli example ###########\n\nusing StanVariational\n\nbernoulli_model = \"\ndata { \n int N; \n int y[N];\n} \nparameters {\n real theta;\n} \nmodel {\n theta ~ beta(1,1);\n y ~ bernoulli(theta);\n}\n\";\n\nbernoulli_data = Dict(\"N\" => 10, \"y\" => [0, 1, 0, 1, 0, 0, 0, 0, 0, 1])\n\n# Keep tmpdir across multiple runs to prevent re-compilation\ntmpdir = joinpath(@__DIR__, \"tmp\")\n\nstanmodel = VariationalModel(\n \"bernoulli\", bernoulli_model; tmpdir = tmpdir)\n\n(sample_file, log_file) = stan_variational(stanmodel; data=bernoulli_data)\n\nif sample_file !== Nothing\n\n (chns, cnames) = read_variational(stanmodel)\n\n # Show the same output in DataFrame format\n sdf = read_summary(stanmodel)\n display(sdf)\n println()\n\n # Retrieve mean value of theta from the summary\n sdf[:theta, :mean]\n\nend", "meta": {"hexsha": "effe8e684bc0f2a0b04528e371f220f8d8f18b61", "size": 848, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Bernoulli/bernoulli.jl", "max_stars_repo_name": "UnofficialJuliaMirror/StanVariational.jl-6ede68ce-8466-5085-8a79-4c4de3d9cf4a", "max_stars_repo_head_hexsha": "1e2c36b0186468a18b86908298d6e62194749c1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/Bernoulli/bernoulli.jl", "max_issues_repo_name": "UnofficialJuliaMirror/StanVariational.jl-6ede68ce-8466-5085-8a79-4c4de3d9cf4a", "max_issues_repo_head_hexsha": "1e2c36b0186468a18b86908298d6e62194749c1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/Bernoulli/bernoulli.jl", "max_forks_repo_name": "UnofficialJuliaMirror/StanVariational.jl-6ede68ce-8466-5085-8a79-4c4de3d9cf4a", "max_forks_repo_head_hexsha": "1e2c36b0186468a18b86908298d6e62194749c1f", "max_forks_repo_licenses": ["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.6829268293, "max_line_length": 74, "alphanum_fraction": 0.6733490566, "num_tokens": 278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966671870766, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.8007662899500839}} {"text": "using LinearAlgebra # 引入线性代数库\nx=zeros(10) # 10 个元素的零矢量,列矢量\na=ones(3) # 3 个元素的矢量,全填充 1.0,列矢量\nH=[1.0 2.0 3.0 # 直接构造矩阵\n 4.0 5.0 6.0\n 7.0 8.0 9.0]\nH[2,1] # 4.0\nndims(H) # H 的维度,2\neltype(H) # H 中元素的类型,Float64\nlength(H) # H 中元素数目,9\nsize(H) # H 每一维度的大小所构成的元组,(3,3)\nsum(H, dims=2) # 对第2维求和,相似地,该用法可以用于以下函数: mean, std,\n # prod, minimum, maximum, any, all\n # 使用统计函数前需要 using Statistics\nH[:,1] # 矩阵的第1列\nH[1,:] # 矩阵的第1行(仍是列矢量)\nHc=H; Hc[1,1]=100.0; H[1,1] # 100.0,数组的赋值是按引用复制\nHc=copy(H) # 这样才是真的复制一新的矩阵\nH*a # 矩阵乘法\nexp(H) # 矩阵的函数\na*a # 出错的矩阵乘法\n # 列矢量和列矢量的乘法行列不对应无法进行\na⋅a # 但是可以做点积\n # ⋅ 用 \\cdot 可以打出来(在 REPL、Jupyter 中)\n # 或者借助插件(见前文开发环境部分)\na×a # 还可以做叉积\nsum(a)\nH' # 共轭转置,相当于 adjoint(H)\ntypeof(H') # 注意共轭转置是惰性求值\n # 它并不直接分配一块内存并写入计算的结果\n # 这对计算效率有很大的帮助\nG=rand(1000,1000); G=G+G' # 构造一个实对称阵\neigvals(G) # 这样的小矩阵,我们可以直接求本征值\neigvecs(G) # 本征矢\n", "meta": {"hexsha": "c2522655f3d8fe78954c6e28cea1c5b03b78d554", "size": 1435, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/linearalgebra.jl", "max_stars_repo_name": "zhaiyusci/Julia-Notes", "max_stars_repo_head_hexsha": "b8b6992af2a04d9eff5612f3d673f7e1e705a034", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/linearalgebra.jl", "max_issues_repo_name": "zhaiyusci/Julia-Notes", "max_issues_repo_head_hexsha": "b8b6992af2a04d9eff5612f3d673f7e1e705a034", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-04-23T13:40:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-23T13:40:29.000Z", "max_forks_repo_path": "src/linearalgebra.jl", "max_forks_repo_name": "zhaiyusci/Julia-Notes", "max_forks_repo_head_hexsha": "b8b6992af2a04d9eff5612f3d673f7e1e705a034", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.0, "max_line_length": 68, "alphanum_fraction": 0.3804878049, "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966656805269, "lm_q2_score": 0.8459424295406088, "lm_q1q2_score": 0.8007662831608244}} {"text": "import SCS\nimport Convex\nimport InsarTimeseries\n\nimport PyPlot\nplt = PyPlot\n\nhuber_fit = InsarTimeseries.huber_fit\nhuber = InsarTimeseries.huber\n\nobj_l1(z) = norm(z, 1)\nobj_l2(z) = norm(z, 2)\nobj_huber(z) = sum(huber(z)) / 2\n\nfunction l1_fit(A, b)\n x = Convex.Variable(size(A, 2))\n problem = Convex.minimize(norm(A * x - b, 1))\n Convex.solve!(problem, SCS.SCSSolver(verbose = false))\n return x.value\nend\n\n# Fit a line with L1, huber, and L2\nfunction compare_l1_huber(m = 500, m_true = 1, b_true = -5, sigma = 3; with_outlier = true)\n # slope of line is m_true, y intercept is b_true\n x_true = collect(range(0, 10, length = m))\n data_true = (m_true .* x_true) .+ b_true\n @show m_true, b_true\n # b = x_true .+ (sigma .* randn(m)) # Gaussian noise\n b = data_true .+ (2sigma .* rand(m) .- sigma) # Uniform noise [-sigma, sigma]\n if with_outlier\n extra = maximum(b) - minimum(b)\n b[1] += 2extra\n b[end] -= 2extra\n end\n\n n = 1\n A = hcat(x_true, ones(m))\n\n huber_sol = huber_fit(A, b)\n l1_sol = l1_fit(A, b)\n l2_sol = A \\ b\n\n plt.figure()\n plt.plot(x_true, data_true, label = \"truth\")\n plt.scatter(x_true, b, label = \"data\")\n plt.plot(x_true, A * huber_sol, label = \"Huber\")\n plt.plot(x_true, A * l1_sol, label = \"L1\")\n plt.plot(x_true, A * l2_sol, label = \"L2\")\n plt.legend()\n plt.show(block = false)\n\n res_huber = A * huber_sol .- b\n res_l1 = A * l1_sol .- b\n res_l2 = A * l2_sol .- b\n return huber_sol, l1_sol, l2_sol, huber_sol - l1_sol, res_huber, res_l1, res_l2\nend\n\n\nfunction plot_resid(rh, r1, r2, bins = nothing)\n vm = max(maximum(abs.(rh)), maximum(abs.(r1)))\n fig, axes = plt.subplots(1, 3)\n n1, _, _ = axes[1].hist(rh, range = (-vm, vm), bins = bins)\n n2, _, _ = axes[2].hist(r1, range = (-vm, vm), bins = bins)\n n3, _, _ = axes[3].hist(r2, range = (-vm, vm), bins = bins)\n axes[1].set_title(\"Huber residuals\")\n axes[2].set_title(\"L1 (CVX) residuals\")\n axes[3].set_title(\"L2 least sq.\")\n nmax = max(maximum(n1), maximum(n2), maximum(n3))\n axes[1].set_ylim(0, nmax + 2)\n axes[2].set_ylim(0, nmax + 2)\n axes[3].set_ylim(0, nmax + 2)\n return fig, axes\nend\n\npoints = 40\nsh, s1, s2, dif, rh, r1, r2 = compare_l1_huber(points, with_outlier = true)\n\nnbins = 35\nfig, axes = plot_resid(rh, r1, r2, nbins)\n", "meta": {"hexsha": "d97d949e456084f67bfbfcd1775eb4e005a293c4", "size": 2350, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/compare_opt.jl", "max_stars_repo_name": "scottstanie/InsarTimeseries.jl", "max_stars_repo_head_hexsha": "446be59832d7bef460360ed44c0fdb7834b782a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-26T23:24:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T03:21:33.000Z", "max_issues_repo_path": "scripts/compare_opt.jl", "max_issues_repo_name": "scottstanie/InsarTimeseries.jl", "max_issues_repo_head_hexsha": "446be59832d7bef460360ed44c0fdb7834b782a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/compare_opt.jl", "max_forks_repo_name": "scottstanie/InsarTimeseries.jl", "max_forks_repo_head_hexsha": "446be59832d7bef460360ed44c0fdb7834b782a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-26T23:25:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-26T23:25:04.000Z", "avg_line_length": 29.375, "max_line_length": 91, "alphanum_fraction": 0.6114893617, "num_tokens": 858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133515091156, "lm_q2_score": 0.8519528019683105, "lm_q1q2_score": 0.8007618134256166}} {"text": "# Arvind Prasadan\n# 2019 January\n# DMF Package\n# Evaluates the Autocorrelation Function\n\n\"\"\"\n\tautocorrelation(x; circular = false, bias_correct = false)\n\nEvaluates the Autocorrelation Function of a signal \n\n# Arguments\n- `x`: signal (vector)\n- `circular`: Boolean whether to use the circular inner product or not\n- `bias_correct`: Boolean whether to use n - k instead of n in normalization for a lag of k (theoretically undesirable); ignored if circular is true\n\n# Outputs\n- `gamma`: Autocorrelation function (lags 0 to n - 1)\n\"\"\"\n\nfunction autocorrelation(x; circular = false, bias_correct = false)\n\n x = x[:]\n n = length(x)\n \n x = x .- mean(x)\n \n gamma = zeros(n)\n if false == circular\n for k = 0:1:(n - 1)\n gamma[k + 1] = x[1:1:(n - k)]' * x[(1 + k):1:n]\n \n if true == bias_correct\n gamma[k + 1] = gamma[k + 1] / (n - k)\n end\n end\n \n if false == bias_correct\n gamma = gamma / n\n end\n elseif true == circular\n for k = 0:1:(n - 1)\n gamma[k + 1] = circshift(x, k)' * x\n end\n \n gamma = gamma / n\n end\n \n return gamma \nend\n\n", "meta": {"hexsha": "b0280de9e627f0725a46f36551c0d6c3b3fc8aee", "size": 1199, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/autocorrelation.jl", "max_stars_repo_name": "JuliaTagBot/DMF.jl", "max_stars_repo_head_hexsha": "8f1605f9edcb5ae2729ee1c1c61c13c4b14e51cc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-09T21:27:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-02T14:13:39.000Z", "max_issues_repo_path": "src/autocorrelation.jl", "max_issues_repo_name": "JuliaTagBot/DMF.jl", "max_issues_repo_head_hexsha": "8f1605f9edcb5ae2729ee1c1c61c13c4b14e51cc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/autocorrelation.jl", "max_forks_repo_name": "JuliaTagBot/DMF.jl", "max_forks_repo_head_hexsha": "8f1605f9edcb5ae2729ee1c1c61c13c4b14e51cc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:26:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-06T12:46:03.000Z", "avg_line_length": 23.5098039216, "max_line_length": 148, "alphanum_fraction": 0.5562969141, "num_tokens": 342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939913356558485, "lm_q2_score": 0.8519527963298946, "lm_q1q2_score": 0.8007618124278185}} {"text": "#\n# Simulation of the SIRD epidemics model\n#\n# Mechanism: U: Susceptible ; S: Sick ; D: Dead ; I : Immune\n# U + S -> 2S (kc: contamination)\n# S -> D (kd: death) \n# S -> I (ki: immunization) \n# I -> U (kiu: loss of immunity) \n#\n\n# Diferential equations\ndUdt(U,S,I,k) = -k[1]*U*S + k[4]*I\ndSdt(U,S,k) = k[1]*U*S - (k[2]+k[3])*S\ndDdt(S,k) = k[2]*S\ndIdt(S,I,k) = k[3]*S - k[4]*I\n\n# error\nsird_error(U,S,D,I) = abs(1. - (U + S + D + I))\n\n# A method that will be used if the trajectory structure was not created outside\nfunction sird(input :: SIRDInput)\n traj = SIRDTraj(input)\n sird!(input,traj)\n return traj\nend\n\n# We need this layer for the optimization procedure to be able to receive a variable (modifies traj)\nfunction sird!(input :: SIRDInput, traj :: SIRDTraj)\n k = [ input.kc, input.kd, input.ki, input.kiu ]\n sird!(k, input, traj)\nend\n\n# Function that performs the simulation, modifies the data in traj structure (modifies traj)\nfunction sird!(k :: Vector{Float64}, input :: SIRDInput, traj :: SIRDTraj)\n\n # Number of steps\n dt = input.dt\n nsteps = round(Int64,input.tmax/dt)\n if nsteps%input.nsave != 0\n error(\" In SIRD (tmax/dt) must be a multiple of nsave\")\n end\n isave = round(Int64,nsteps/input.nsave)\n\n # To clear out the code\n U = traj.U\n S = traj.S\n D = traj.D\n I = traj.I\n time = traj.time\n\n # Initial populations (p for \"previous\" to the first step)\n Sp = input.Si\n Dp = input.Di\n Ip = input.Ii\n if Sp + Dp + Ip > 1.\n error(\"Sum of sick, dead, and immune cannot be greater than 1.\")\n end\n Up = 1. - (Sp+Dp+Ip)\n \n # Running simulation\n nlast = nsteps\n nsaved = 0\n for i in 1:nsteps\n # Update populations (c for current)\n Uc = Up + dUdt(Up,Sp,Ip,k)*dt\n Sc = Sp + dSdt(Up,Sp,k)*dt\n Dc = Dp + dDdt(Sp,k)*dt\n Ic = Ip + dIdt(Sp,Ip,k)*dt\n # Save data if required at this step\n if i%isave == 0\n nsaved = nsaved + 1\n U[nsaved] = Uc\n S[nsaved] = Sc\n D[nsaved] = Dc\n I[nsaved] = Ic\n time[nsaved] = i*dt\n end \n # check if epidemics ended\n if Sc < input.tol\n nlast = i\n break\n end\n # check if integration is going fine\n err = sird_error(Uc,Sc,Dc,Ic)\n if err > input.err\n if input.print\n println(input.print,\" SIRD: Integration error too large at step: \", i,\" error = \",err)\n end\n nlast = i\n break\n end\n # Update previous values to current ones\n Up = Uc\n Sp = Sc\n Dp = Dc\n Ip = Ic\n end\n\n if input.print\n println(\" Epidemics ended at step = \", nlast)\n println(\" Last step saved = \", nsaved, \" time = \", time[nsaved])\n end\n \n # Filling up vector up to the end, if the trajectory ended before\n if nsaved < input.nsave\n if nsaved == 0 # the simulation ended before the first point was saved\n for i in 1:input.nsave\n U[i] = Up\n S[i] = Sp\n D[i] = Dp\n I[i] = Ip\n time[i] = i*isave*dt\n end\n else\n for i in nsaved+1:input.nsave\n U[i] = U[nsaved]\n S[i] = S[nsaved]\n D[i] = D[nsaved]\n I[i] = I[nsaved]\n time[i] = i*isave*dt\n end\n end\n end\n\nend\n", "meta": {"hexsha": "05a69dca98faa4cb2d030709403b201dc4266925", "size": 3163, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/sird.jl", "max_stars_repo_name": "m3g/kinetics", "max_stars_repo_head_hexsha": "f84fbd7120d8848b1bbfe5c9ec936fd2690e3e8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-08-27T19:27:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-09T09:24:24.000Z", "max_issues_repo_path": "src/sird.jl", "max_issues_repo_name": "m3g/kinetics", "max_issues_repo_head_hexsha": "f84fbd7120d8848b1bbfe5c9ec936fd2690e3e8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sird.jl", "max_forks_repo_name": "m3g/kinetics", "max_forks_repo_head_hexsha": "f84fbd7120d8848b1bbfe5c9ec936fd2690e3e8d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-28T17:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-28T17:20:58.000Z", "avg_line_length": 25.1031746032, "max_line_length": 100, "alphanum_fraction": 0.5782484983, "num_tokens": 1100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133464597458, "lm_q2_score": 0.8519528019683106, "lm_q1q2_score": 0.8007618091237919}} {"text": "using LinearAlgebra\n\"\"\"\nQuasi-Newton Methods for Solving Systems of Nonlinear Equations\n@author Oscar Veliz\n\"\"\"\n\n\"\"\"\n F(X)\n\nSystem of nonlinear equations on vector X ([x;y]).\nOverwrite for your own testing, currently set to:\nx^2 - y - 1\nx - y^2 + 1\n\n# Example\n```julia-repl\njulia> F([1.0; 2.0])\n[-2.0, -2.0]\n```\n\"\"\"\nF(X) = [X[1]^2 - X[2] - 1; X[1] - X[2]^2 + 1]\n\n\n\"\"\"\n Secant(X, eps=10^-6)\n\nWolfe-Bittner Secant Method for the system of nonlinear equations in [`F`](@ref).\nRequires `d+1` starting vectors in X.\n# Example\n```julia-repl\njulia> Secant(transpose([1.0 1.0;1.0 2.0;1.5 2.0]))\n2-element Array{Float64,1}:\n 1.6180339736070495\n 1.6180339507485015\n```\n\"\"\"\nfunction Secant(X, eps::Float64 = 10^-6)\n n = size(X,1)\n FN = mapslices(F, X; dims=1)\n FX = FN[:,end]\n #println(X) #uncomment to see starting points\n while norm(FX) > eps\n A = [ones(1,n+1); FN]\n b = zeros(n+1,1)\n b[1,1] = 1\n p = A \\ b\n Xbar = X * p\n #print(Xbar) #uncomment to see each itr\n X = hcat(X, Xbar)\n X = X[1:end,2:end]\n FX = F(Xbar)\n FN = hcat(FN,FX)\n FN = FN[1:end,2:end]\n end\n X[:,end]\nend\n\n\"\"\"\n steffJ(X, FX = F(X), n = size(X,1))\n\nTraub-Steffensen approximation of the Jacobian.\nRequires starting vector X.\nFX is optional in case F(X) was already computed for efficiency.\n# Example\n```julia-repl\njulia> steffJ([1.5;2.0])\n2×2 Array{Float64,2}:\n 2.25 -1.0\n 1.0 -2.5\n```\n\"\"\"\nfunction steffJ(X,FX = F(X),n = size(X,1))\n H = Diagonal(FX)\n J = X #placeholder to set dims\n for i = 1:n\n J = hcat(J, F(X + H[:,i]) - FX)\n end\n J = J[1:end, 2:end] * inv(H) #removes placeholder before mult\nend\n\n\"\"\"\n Steffensen(X, eps=10^-6)\n\nTraub-Steffensen Method for a system of nonlinear equations in [`F`](@ref).\nRequires starting vector X.\n# Example\n```julia-repl\njulia> Steffensen([1.5;2.0])\n2-element Array{Float64,1}:\n 1.6180339736216265\n 1.6180339387805316\n```\n\"\"\"\nfunction Steffensen(X, eps::Float64 = 10^-6)\n n = size(X,1)\n #println(X) #uncomment to see itr\n FX = F(X)\n while(norm(FX) > eps)\n J = steffJ(X,FX,n)\n X = X - J \\ FX\n #println(X) #uncomment to see itr\n FX = F(X)\n end\n X\nend\n\n\"\"\"\n fdJ(X, FX = F(X), h = 10^-4, n = size(X,1))\n\n(Forward) Finite Difference approximation of the Jacobian.\nRequires starting vector X. Optional h and n.\nFX is optional in case F(X) was already computed for efficiency.\n# Example\n```julia-repl\njulia> fdJ([1.5;2.0])\n2×2 Array{Float64,2}:\n 3.0001 -1.0\n 1.0 -4.0001\n```\n\"\"\"\nfunction fdJ(X,FX = F(X),h::Float64 = 10^-4,n = size(X,1))\n H = h * I(n)\n J = X #placeholder to set dims\n for i = 1:n\n J = hcat(J, F(X + H[:,i]) - FX)\n end\n J = h^-1 * J[1:end, 2:end] #removes placeholder and divide by h\nend\n\n\"\"\"\n FiniteDiff(X, h = 10^-4, eps = 10^-6)\n\nGeneralized Finite-Difference Method for a system of nonlinear equations in [`F`](@ref).\nRequires starting vector X. Optional h and eps.\n# Example\n```julia-repl\njulia> FiniteDiff([1.5;2.0])\n2-element Array{Float64,1}:\n 1.6180340699246842\n 1.6180341416981485\n```\n\"\"\"\nfunction FiniteDiff(X,h::Float64 = 10^-4, eps::Float64 = 10^-6)\n n = size(X,1)\n #println(X) #uncomment to see itr\n FX = F(X)\n while(norm(FX) > eps)\n J = fdJ(X,FX,h,n)\n X = X - J \\ FX\n #println(X) #uncomment to see itr\n FX = F(X)\n end\n X\nend\n\n\"\"\"\n Broyden(X, eps = 10^-6)\n\n\"Good\" Broyden Method for a system of nonlinear equations in [`F`](@ref).\nRequires starting vector X. Optional eps. Initial J approximated by differencing.\n# Example\n```julia-repl\njulia> Broyden([1.5;2.0])\n2-element Array{Float64,1}:\n 1.6180340721138766\n 1.6180340507162783\n```\n\"\"\"\nfunction Broyden(X, eps::Float64 = 10^-6)\n #println(X) #uncomment to see itr\n FX = F(X)\n invJ = inv(fdJ(X,FX))\n while(norm(FX) > eps)\n Xold = X\n X = X - invJ*FX\n #println(X) #uncomment to see itr\n deltaX = X - Xold\n FXold = FX\n FX = F(X)\n deltaF = FX - FXold\n trans = transpose(deltaX)\n invJ = invJ + (deltaX - invJ*deltaF)/(trans*invJ*deltaF)*trans*invJ\n end\n X\nend\n\n\"\"\"\nMain\n\"\"\"\n\nprintln(Secant(transpose([1.0 1.0;1.0 2.0;1.5 2.0])))\nprintln(Steffensen([1.5;2.0]))\nprintln(FiniteDiff([1.5;2.0]))\nprintln(Broyden([1.5;2.0]))\n", "meta": {"hexsha": "39e08c770b72d129ddd5ccb2310ba7170569471d", "size": 4331, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/systems/QuasiNewton.jl", "max_stars_repo_name": "deboradeben/numerical-veliz", "max_stars_repo_head_hexsha": "afd208d5198315642aab3e0dab20bf27b20ed61c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 73, "max_stars_repo_stars_event_min_datetime": "2018-09-26T22:41:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T15:50:14.000Z", "max_issues_repo_path": "src/systems/QuasiNewton.jl", "max_issues_repo_name": "deboradeben/numerical-veliz", "max_issues_repo_head_hexsha": "afd208d5198315642aab3e0dab20bf27b20ed61c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-11-18T20:37:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-22T08:59:13.000Z", "max_forks_repo_path": "src/systems/QuasiNewton.jl", "max_forks_repo_name": "deboradeben/numerical-veliz", "max_forks_repo_head_hexsha": "afd208d5198315642aab3e0dab20bf27b20ed61c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16, "max_forks_repo_forks_event_min_datetime": "2018-11-14T17:19:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T21:50:34.000Z", "avg_line_length": 22.2102564103, "max_line_length": 88, "alphanum_fraction": 0.5871623182, "num_tokens": 1600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259925, "lm_q2_score": 0.8519527963298946, "lm_q1q2_score": 0.8007618066920528}} {"text": "fun(x) = (1.0 - x[1])^2 + 100.0 * (x[2] - x[1]^2)^2\n\nfunction fun_grad!(g, x)\ng[1] = -2.0 * (1.0 - x[1]) - 400.0\n* (x[2] - x[1]^2) * x[1]\ng[2] = 200.0 * (x[2] - x[1]^2)\nend\n\nfunction fun_hess!(h, x)\nh[1, 1] = 2.0 - 400.0 * x[2] + 1200.0 * x[1]^2\nh[1, 2] = -400.0 * x[1]\nh[2, 1] = -400.0 * x[1]\nh[2, 2] = 200.0\nend;\n\nx0 = [0.0, 0.0]\ndf = TwiceDifferentiable(fun, fun_grad!, fun_hess!, x0)\n\nlx = [-0.5, -0.5]; ux = [0.5, 0.5]\ndfc = TwiceDifferentiableConstraints(lx, ux)\n\nres = optimize(df, dfc, x0, IPNewton())\n\nux = fill(Inf, 2)\ndfc = TwiceDifferentiableConstraints(lx, ux)\n\nclear!(df)\nres = optimize(df, dfc, x0, IPNewton())\n\nlx = fill(-Inf, 2); ux = fill(Inf, 2)\ndfc = TwiceDifferentiableConstraints(lx, ux)\n\nclear!(df)\nres = optimize(df, dfc, x0, IPNewton())\n\nlx = Float64[]; ux = Float64[]\ndfc = TwiceDifferentiableConstraints(lx, ux)\n\nclear!(df)\nres = optimize(df, dfc, x0, IPNewton())\n\ncon_c!(c, x) = (c[1] = x[1]^2 + x[2]^2; c)\nfunction con_jacobian!(J, x)\n J[1,1] = 2*x[1]\n J[1,2] = 2*x[2]\n J\nend\nfunction con_h!(h, x, λ)\n h[1,1] += λ[1]*2\n h[2,2] += λ[1]*2\nend;\n\nlx = Float64[]; ux = Float64[]\nlc = [-Inf]; uc = [0.5^2]\ndfc = TwiceDifferentiableConstraints(con_c!, con_jacobian!, con_h!,\n lx, ux, lc, uc)\nres = optimize(df, dfc, x0, IPNewton())\n\nlc = [0.1^2]\ndfc = TwiceDifferentiableConstraints(con_c!, con_jacobian!, con_h!,\n lx, ux, lc, uc)\nres = optimize(df, dfc, x0, IPNewton())\n\nfunction con2_c!(c, x)\n c[1] = x[1]^2 + x[2]^2 ## First constraint\n c[2] = x[2]*sin(x[1])-x[1] ## Second constraint\n c\nend\nfunction con2_jacobian!(J, x)\n # First constraint\n J[1,1] = 2*x[1]\n J[1,2] = 2*x[2]\n # Second constraint\n J[2,1] = x[2]*cos(x[1])-1.0\n J[2,2] = sin(x[1])\n J\nend\nfunction con2_h!(h, x, λ)\n # First constraint\n h[1,1] += λ[1]*2\n h[2,2] += λ[1]*2\n # Second constraint\n h[1,1] += λ[2]*x[2]*-sin(x[1])\n h[1,2] += λ[2]*cos(x[1])\n # Symmetrize h\n h[2,1] = h[1,2]\n h\nend;\n\nx0 = [0.25, 0.25]\nlc = [-Inf, 0.0]; uc = [0.5^2, 0.0]\ndfc = TwiceDifferentiableConstraints(con2_c!, con2_jacobian!, con2_h!,\n lx, ux, lc, uc)\nres = optimize(df, dfc, x0, IPNewton())\n\n# This file was generated using Literate.jl, https://github.com/fredrikekre/Literate.jl\n", "meta": {"hexsha": "b50fe52b2ee7cccb0d73d9c369d22bd176275bec", "size": 2338, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "dev/optim.jl", "max_stars_repo_name": "JasmineHao/DCDC.jl", "max_stars_repo_head_hexsha": "32732f3a65029294a2dc5c14f241b0e3642ed894", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dev/optim.jl", "max_issues_repo_name": "JasmineHao/DCDC.jl", "max_issues_repo_head_hexsha": "32732f3a65029294a2dc5c14f241b0e3642ed894", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-11-26T22:17:43.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-26T22:17:43.000Z", "max_forks_repo_path": "dev/optim.jl", "max_forks_repo_name": "JasmineHao/DCDC.jl", "max_forks_repo_head_hexsha": "32732f3a65029294a2dc5c14f241b0e3642ed894", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1030927835, "max_line_length": 87, "alphanum_fraction": 0.5384944397, "num_tokens": 1002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.916109622750986, "lm_q2_score": 0.8740772286044094, "lm_q1q2_score": 0.8007505601520128}} {"text": "using KernelAbstractions\r\n\r\nfunction averageK(K, i, j, k)\r\n Kw = harmonicMean(K[i - 1, j, k ], K[i, j, k ])\r\n Ke = harmonicMean(K[i, j, k ], K[i + 1, j, k ])\r\n Ks = harmonicMean(K[i, j - 1, k ], K[i, j, k ])\r\n Kn = harmonicMean(K[i, j, k ], K[i, j + 1, k ])\r\n Kb = harmonicMean(K[i, j, k - 1], K[i, j, k ])\r\n Kt = harmonicMean(K[i, j, k ], K[i, j, k + 1])\r\n return Kw, Ke, Ks, Kn, Kb, Kt\r\nend\r\n\r\nfunction harmonicMean(v1, v2)\r\n return 2.0 * v1 * v2 / (v1 + v2)\r\nend\r\n\r\n@kernel function pressureKernel!(source, h, hⁿ⁺¹, Δx, Δy, Δz, Δt, K, SS)\r\n i, j, k = @index(Global, NTuple)\r\n \r\n @inbounds begin\r\n F = K[i,j,k] * (\r\n (h[i + 1,j,k] + h[i - 1,j,k] - 2.0 * h[i,j,k]) / (Δx * Δx) +\r\n (h[i,j + 1,k] + h[i,j - 1,k] - 2.0 * h[i,j,k]) / (Δy * Δy) +\r\n (h[i,j,k + 1] + h[i,j,k - 1] - 2.0 * h[i,j,k]) / (Δz * Δz)\r\n ) + source[i,j,k] / (Δx * Δy)\r\n\r\n hⁿ⁺¹[i,j,k] = h[i,j,k] + Δt * F * (1.0 / SS)\r\n end\r\n\r\nend\r\n\r\n@inline function pressureKernelAveraged!(i, j, k, source, h, u, v, w, hⁿ⁺¹, uⁿ⁺¹, vⁿ⁺¹, wⁿ⁺¹, Δx, Δy, Δz, Δt, K, SS)\r\n\r\n Kw, Ke, Ks, Kn, Kb, Kt = averageK(K, i, j, k)\r\n\r\n F = (1.0 / Δx * Δx) * (Ke * (h[i + 1,j ,k ] - h[i,j,k]) - Kw * (h[i,j,k] - h[i - 1,j ,k ])) +\r\n (1.0 / Δy * Δy) * (Kn * (h[i ,j + 1,k ] - h[i,j,k]) - Ks * (h[i,j,k] - h[i ,j - 1,k ])) +\r\n (1.0 / Δz * Δz) * (Kt * (h[i ,j ,k + 1] - h[i,j,k]) - Kb * (h[i,j,k] - h[i ,j ,k - 1])) +\r\n source[i,j,k] / (Δx * Δy)\r\n\r\n hⁿ⁺¹[i,j,k] = h[i,j,k] + Δt * F * (1.0 / SS)\r\nend\r\n", "meta": {"hexsha": "63941b605ce05fa63ffb7acaf32ab6b2830b7259", "size": 1703, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/athesis/kernels_pressure_equation.jl", "max_stars_repo_name": "Deltares/Porteau.jl", "max_stars_repo_head_hexsha": "949bc40c884f7d1a5cd1decf1c63b6c0a98b3134", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-01-29T21:18:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-31T20:23:18.000Z", "max_issues_repo_path": "src/athesis/kernels_pressure_equation.jl", "max_issues_repo_name": "Deltares/Athesis.jl", "max_issues_repo_head_hexsha": "949bc40c884f7d1a5cd1decf1c63b6c0a98b3134", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2020-11-04T15:54:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-21T11:09:54.000Z", "max_forks_repo_path": "src/athesis/kernels_pressure_equation.jl", "max_forks_repo_name": "Deltares/Athesis.jl", "max_forks_repo_head_hexsha": "949bc40c884f7d1a5cd1decf1c63b6c0a98b3134", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-03-31T20:23:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-31T20:23:41.000Z", "avg_line_length": 39.6046511628, "max_line_length": 117, "alphanum_fraction": 0.3769817968, "num_tokens": 792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813513911654, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.8007490683746428}} {"text": "using Plots, Distributions, Random; pyplot()\nRandom.seed!(0)\n\nn = 2000\ndata = rand(Normal(),n)\nl, m = minimum(data), maximum(data)\n\ndelta = 0.3;\nbins = [(x,x+delta) for x in l:delta:m-delta]\nif last(bins)[2] < m \n push!(bins,(last(bins)[2],m)) \nend\nL = length(bins)\n\ninBin(x,j) = first(bins[j]) <= x && x < last(bins[j])\nsizeBin(j) = last(bins[j]) - first(bins[j])\nf(j) = sum([inBin(x,j) for x in data])/n\nh(x) = sum([f(j)/sizeBin(j) * inBin(x,j) for j in 1:L])\n\nxGrid = -4:0.01:4\nhistogram(data,normed=true, bins=L, \n label=\"Built-in histogram\",\n c=:blue, la=0, alpha=0.6)\nplot!(xGrid,h.(xGrid), lw=3, c=:red, label=\"Manual histogram\",\n xlabel=\"x\",ylabel=\"Frequency\")\nplot!(xGrid,pdf.(Normal(),xGrid),label=\"True PDF\", \n lw=3, c=:green, xlims=(-4,4), ylims=(0,0.5))\n", "meta": {"hexsha": "6eb8c00a12c4862a9e78ea3b0522f8eb79f8c601", "size": 783, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "4_chapter/manualHistogram.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/manualHistogram.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/manualHistogram.jl", "max_forks_repo_name": "Yoshinobu-Ishizaki/StatsWithJuliaBook", "max_forks_repo_head_hexsha": "4c704e96d87b91e680122a6b6fa2d2083c70ea88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 264, "max_forks_repo_forks_event_min_datetime": "2018-07-31T03:11:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:12:13.000Z", "avg_line_length": 27.9642857143, "max_line_length": 62, "alphanum_fraction": 0.6066411239, "num_tokens": 299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813526452771, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.8007490616749784}} {"text": "abstract AbstractCovarianceFunction\n\nabstract StationaryCovarianceFunction <: AbstractCovarianceFunction\n\nBase.call(f::StationaryCovarianceFunction,x,y) = f(sqrt(sumabs2(x-y)))\n\ndoc\"\"\"\nA Gaussian covariance function is of the form\n\nC(x_1,x_2) = σ^2 e^{-\\|x_1-x_2\\|^2/2L^2}\n\nwhere L is the bandwidth of the Gaussian kernel.\n\"\"\"\ntype GaussianCovarianceFunction <: StationaryCovarianceFunction\n L::Real\n σ::Real\nend\n\nBase.call(f::GaussianCovarianceFunction,h) = f.σ^2*exp(-h^2/(2*f.L^2))\n\ndoc\"\"\"\nA Matérn covariance function takes the form\n\nC(x_1,x_2) = σ^2 \\frac{2^{1-ν}}{Γ(ν)}(\\sqrt{2ν}\\|x_1-x_2\\|/ρ)^ν K_ν(\\sqrt{2ν}\\|x_1-x_2\\|/ρ)\n\nwhere ν gives the order of the modified Bessel function of the second kind, K_ν, ρ is the bandwidth/correlation length and σ is the total covariance.\n\"\"\"\ntype MatérnCovarianceFunction <: StationaryCovarianceFunction\n ν::Real\n ρ::Real\n σ::Real\nend\n\nBase.call(f::MatérnCovarianceFunction,h) = (h==0?f.σ^2:f.σ^2*2.0^(1-f.ν)/gamma(f.ν)*(sqrt(2*f.ν)*h/f.ρ)^f.ν*besselk(f.ν,sqrt(2*f.ν)*h/f.ρ))\n\ndoc\"\"\"\nGenerates a covariance matrix from a stationary covariance function\nand a matrix of distances as might be generated by Distances.jl's\n`pairwise` function\n\"\"\"\ncovariancematrix(f::StationaryCovarianceFunction,D::Matrix) = map(f,D)\n", "meta": {"hexsha": "2db9603bf1998319a12c4bbbf8142f40dd7d4d13", "size": 1274, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/covariancefunctions.jl", "max_stars_repo_name": "wkearn/GeometryRandomFields.jl", "max_stars_repo_head_hexsha": "5028a1c1283268b35860459d1f9fa912d2f16472", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/covariancefunctions.jl", "max_issues_repo_name": "wkearn/GeometryRandomFields.jl", "max_issues_repo_head_hexsha": "5028a1c1283268b35860459d1f9fa912d2f16472", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/covariancefunctions.jl", "max_forks_repo_name": "wkearn/GeometryRandomFields.jl", "max_forks_repo_head_hexsha": "5028a1c1283268b35860459d1f9fa912d2f16472", "max_forks_repo_licenses": ["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.3333333333, "max_line_length": 149, "alphanum_fraction": 0.7244897959, "num_tokens": 437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404096760998, "lm_q2_score": 0.8615382165412809, "lm_q1q2_score": 0.8007484329337445}} {"text": "using LinearAlgebra\nusing Statistics\n\ninclude(\"algo_util.jl\")\n\nabstract type FirstOrder <: DescentDirectionMethod end\nfunction solve(M::FirstOrder, f, ∇f, x, max_iters; num_eval_termination=true)\n init!(M, f, ∇f, x)\n x_hist = [x]\n while true\n x = step!(M, f, ∇f, x)\n push!(x_hist, x)\n if num_eval_termination && (count(∇f) >= max_iters/2) # 2 calls per iteration\n break\n end\n end\n return x, x_hist\nend\n\n# Vanilla Gradient Descent\nBase.@kwdef mutable struct GradientDescent <: FirstOrder \n α = 1e-3\nend\ninit!(M::GradientDescent, f, ∇, x) = M\nfunction step!(M::GradientDescent, f, ∇f, x)\n α = M.α\n return x - α * ∇f(x)\nend\n\n# GD + Momentum\nBase.@kwdef mutable struct GDMomentum <: FirstOrder\n α = 1e-3\n β = 0.9\n v = nothing\nend\nfunction init!(M::GDMomentum, f, ∇f, x)\n M.v = zeros(length(x))\n return M\nend\nfunction step!(M::GDMomentum, f, ∇f, x)\n α, β, = M.α, M.β\n M.v[:] = β * M.v - α * ∇f(x)\n return x + M.v\nend\n\n\n# GD + Nesterov Momentum\nBase.@kwdef mutable struct GDMomentumNesterov <: FirstOrder\n α = 1e-3\n β = 0.9\n v = nothing\nend\nfunction init!(M::GDMomentumNesterov, f, ∇f, x)\n M.v = zeros(length(x))\n return M\nend\nfunction step!(M::GDMomentumNesterov, f, ∇f, x)\n α, β = M.α, M.β\n M.v[:] = β * M.v - α * ∇f(x + β * M.v)\n return x + M.v\nend\n\n# Adam\nBase.@kwdef mutable struct Adam <: FirstOrder\n α = 1e-3\n β1 = 0.9\n β2 = 0.999\n ϵ = 1e-8\n k = 0\n v = nothing\n s = nothing\nend\nfunction init!(M::Adam, f, ∇f, x)\n M.v = zeros(length(x))\n M.s = zeros(length(x))\n return M\nend\nfunction step!(M::Adam, f, ∇f, x) \n α, β1, β2, ϵ = M.α, M.β1, M.β2, M.ϵ\n g = ∇f(x)\n M.v[:] = β1 * M.v + (1 - β1) * g\n M.s[:] = β2 * M.s + (1 - β2) * g .* g\n M.k += 1\n v̂ = M.v ./ (1 - β1 ^ M.k)\n ŝ = M.s ./ (1 - β2 ^ M.k)\n return x - (α * v̂) ./ (sqrt.(ŝ) .+ ϵ)\nend\n\n\n# Gradient Descent + Backtracking Line Search\nBase.@kwdef mutable struct GDApproxLineSearch <: FirstOrder\n α = 3e-3\n approx_line_search = backtracking_line_search\nend\ninit!(M::GDApproxLineSearch, f, ∇, x) = M\nfunction step!(M::GDApproxLineSearch, f, ∇f, x)\n g = ∇f(x)\n α = M.approx_line_search(f, ∇f, x, -g, M.α)\n return x - α * g \nend\n", "meta": {"hexsha": "2200ba3ce3ccd7df474dd175f3df2f1ba8baa2db", "size": 2260, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "project1_jl/algo_first_order.jl", "max_stars_repo_name": "yutaizhou/AA222Project1", "max_stars_repo_head_hexsha": "a57787c34c7dc827f469b564464ebe0cee966d77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "project1_jl/algo_first_order.jl", "max_issues_repo_name": "yutaizhou/AA222Project1", "max_issues_repo_head_hexsha": "a57787c34c7dc827f469b564464ebe0cee966d77", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "project1_jl/algo_first_order.jl", "max_forks_repo_name": "yutaizhou/AA222Project1", "max_forks_repo_head_hexsha": "a57787c34c7dc827f469b564464ebe0cee966d77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3762376238, "max_line_length": 85, "alphanum_fraction": 0.5668141593, "num_tokens": 896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625088705931, "lm_q2_score": 0.8596637469145054, "lm_q1q2_score": 0.8007445504860798}} {"text": "using EngEconomics\n\ncostA = 15000\nomA = 55\nbenefitA = 450\ncostB = 10000\nomB = 35\nbenefitB = 200\nn = 30\ni = 0.05\n\n# Consider do nothing option and pick best from b/c analysis\n# 1.) Rank options by smallest initial cost to biggest initial cost\n# (1) B\n# (2) A\n# 2.) Compare 1 and 2\nΔEUAB_21 = (benefitB - benefitA) - (omB - omA)\nΔEUAC_21 = (costB - costA) * capitalRecoveryFactor(i, n)\n\nΔBCRatio_21 = ΔEUAB_21 / ΔEUAC_21\n\nif ΔBCRatio_21 >= 1\n\tprintln(\"Pick the one with the bigger initial cost, i.e. B\")\nelse\n\tprintln(\"Pick the one with the smaller initial cost, i.e. Do Nothing\")\nend\n\ndisbenefitA = 400\ndisbenefitB = 500\n\nΔEUAB_21 = (benefitB - benefitA) - (omB - omA) - (disbenefitB - disbenefitA)\nΔEUAC_21 = (costB - costA) * capitalRecoveryFactor(i, n)\n\nΔBCRatio_21 = ΔEUAB_21 / ΔEUAC_21\n\nif ΔBCRatio_21 >= 1\n\tprintln(\"Pick the one with the bigger initial cost, i.e. B\")\nelse\n\tprintln(\"Pick the one with the smaller initial cost, i.e. Do Nothing\")\nend\n", "meta": {"hexsha": "8deb3bbd81e7ae31879608f8e110c0930c005dcf", "size": 962, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "problems/ps7/p3.jl", "max_stars_repo_name": "zborffs/EngineeringEconomics.jl", "max_stars_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problems/ps7/p3.jl", "max_issues_repo_name": "zborffs/EngineeringEconomics.jl", "max_issues_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problems/ps7/p3.jl", "max_forks_repo_name": "zborffs/EngineeringEconomics.jl", "max_forks_repo_head_hexsha": "f17d84f0ae79453a516a6b7d9e958d6ff08a87a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4634146341, "max_line_length": 76, "alphanum_fraction": 0.7027027027, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422227627597, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.800695922967232}} {"text": "\r\ninclude(\"../../number_theo/src/number_module.jl\")\r\n\r\n\r\nmodule quasirandom\r\nusing LinearAlgebra\r\nusing ..number\r\n\r\n\r\nfunction halton(i; base = 2)\r\n # von der Corput sequence\r\n result = 0.0\r\n f = 1.0\r\n while i > 0\r\n f = f / base\r\n result += f * mod(i, base)\r\n i = floor(Int, i / base)\r\n end\r\n return result\r\nend\r\n\r\nfunction halton_filling_seq(n_points; base = 2)\r\n return [halton(i, base = base) for i = 1:n_points]\r\nend\r\n\r\nfunction halton_filling_seq(n_points, n_dim)\r\n upto = max(n_dim * (log(n_dim) + log(log(n_dim))), 6) |> ceil |> Int\r\n bases = number.sieve_of_eratosthenes(upto)\r\n mat = zeros(n_points, n_dim)\r\n for dd = 1:n_dim\r\n mat[:,dd] = halton_filling_seq(n_points; base = bases[dd])\r\n end\r\n return mat\r\nend\r\n\r\n\r\n\r\nfunction pairwise_distances(X)\r\n # columns are the different dimensions\r\n # rows are the different points\r\n\r\n (N, n_dim) = size(X)\r\n Nn = div(N * (N-1), 2)\r\n n = zeros(Nn)\r\n kk = 0\r\n @inbounds for ii = 1:(N-1)\r\n @inbounds for jj = (ii+1):N\r\n kk += 1\r\n v1 = view(X, ii, 1:n_dim)\r\n v2 = view(X, jj, 1:n_dim)\r\n n[kk] = norm(v1 - v2)\r\n end\r\n end\r\n return n\r\nend\r\n\r\nfunction morris_mitchell_criterion(X, q = 1.0)\r\n dists = pairwise_distances(X)\r\n s = sum( dists.^(-q) )^(1/q)\r\n return s\r\nend\r\n\r\n\r\n\r\nend\r\n\r\n", "meta": {"hexsha": "9fe9e4974fd26433c99e286255525918e55f936c", "size": 1409, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "__lib__/math/quasi_random_sequence/src/quasirandom_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/quasi_random_sequence/src/quasirandom_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/quasi_random_sequence/src/quasirandom_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": 21.0298507463, "max_line_length": 73, "alphanum_fraction": 0.5436479773, "num_tokens": 442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951142221377825, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.8006959218013584}} {"text": "module YorkFit\n\nexport fit\n\n\"\"\"Calculate the weight of the error `σX`.\"\"\"\nω(σX::Real)::Real = σX^-2\nα{T<:Real}(ωX::T, ωY::T)::T = sqrt(ωX * ωY)\nW{T<:Real}(ωX::T, ωY::T, r::T, b::T, α::T)::T =\n (ωX * ωY) / (ωX + b^2 * ωY - 2 * b * r * α)\n\n\"\"\"Compute Σ(Ws * Xs) / Σ(Xs)\"\"\"\nbarvar{T<:Real}(Ws::Vector{T}, Xs::Vector{T})::T = sum(Ws .* Xs) / sum(Ws)\n\nfunction β{T<:Real}(W::T, U::T, V::T, ωX::T, ωY::T, b::T, r::T, α)::T\n W * ((U / ωY) + (b * V / ωX) - (r / α) * (b * U + V))\nend\n\n\"\"\"Calculate `a` and `b` using the method of least squares. Returns the tuple\n`(a, b)` where `a` is the intercept and `b` is the gradient.\"\"\"\nfunction lsq{T<:Real}(Xs::Vector{T}, Ys::Vector{T})::Tuple{T,T}\n A = hcat(ones(length(Xs)), Xs)\n m = (A' * A) \\ A' * Ys\n\n (m[1], m[2])\nend\n\n\"\"\"\n fit{T<:Real}(Xs::Vector{T}, Ys::Vector{T}, σX::T, σYs::Vector{T}, rs::Vector{T}; kwargs...)\n fit{T<:Real}(Xs::Vector{T}, Ys::Vector{T}, σX::T, σYs::Vector{T}, r::T=T(0); kwargs...)\n fit{T<:Real}(Xs::Vector{T}, Ys::Vector{T}, σXs::Vector{T}, σY::T, rs::Vector{T}; kwargs...)\n fit{T<:Real}(Xs::Vector{T}, Ys::Vector{T}, σXs::Vector{T}, σY::T, r::T=T(0); kwargs...)\n fit{T<:Real}(Xs::Vector{T}, Ys::Vector{T}, σX::T, σY::T, rs::Vector{T}; kwargs...)\n fit{T<:Real}(Xs::Vector{T}, Ys::Vector{T}, σX::T, σY::T, r::T=T(0); kwargs...)\n fit{T<:Real}(Xs::Vector{T}, Ys::Vector{T}, σXs::Vector{T}, σYs::Vector{T}, r::T=T(0); kwargs...)\n\n fit{T<:Real}(Xs::Vector{T}, Ys::Vector{T}, σXs::Vector{T}, σYs::Vector{T}, rs::Vector{T}; kwargs...)::Tuple{T,T,T,T}\n\nFits a slope and intercept to a set of observations using the method of York et\nal. (2004).\n\nArguments\n=========\n\n- `Xs` -- A vector of observations.\n- `Ys` -- A vector of observations related to `Xs` by `Ys = a + b * Xs`.\n- `σXs` -- Errors in the observations in `Xs`. A vector of equal length to `Xs` or\n a scalar value if all the errors are equal.\n- `σYs` -- Errors in the observations in `Ys`. A vector of equal length to `Ys` or\n a scalar value if all the errors are equal.\n- `rs` -- Correlation coefficient between errors. A vector of equal length to\n `Xs` and `Ys` or a scalar value if the coefficient is constant. Defaults to 0.\n\nKeyword Arguments\n==================\n\n- `niter=400` -- Number of iterations to calculate the slope `b` with.\n- `tol=1E-15` -- Stopping criteria. When the difference between two successive\n iterations of `b` falls below this, the iterations stop.\n\nReturns\n=======\n\nA 4-tuple containing `(a, b, σa, σb)` where `a` is the intercept, `b` is the\nslope and `σa` and `σb` are the errors in the intercept and slope.\n\nReferences\n==========\n\nYork, D., Evensen, N.M., Martınez, M.L. and Delgado, J.D.B., 2004. Unified\nequations for the slope, intercept, and standard errors of the best straight\nline. American Journal of Physics, 72(3), pp.367-375.\n\"\"\"\nfit{T<:Real}(Xs::Vector{T}, Ys::Vector{T}, σX::T, σYs::Vector{T}, rs::Vector{T}; kwargs...) =\n fit(Xs, Ys, fill(σX, length(Xs)), σYs, rs; kwargs...)\nfit{T<:Real}(Xs::Vector{T}, Ys::Vector{T}, σX::T, σYs::Vector{T}, r::T=T(0); kwargs...) =\n fit(Xs, Ys, fill(σX, length(Xs)), σYs, fill(r, length(Xs)); kwargs...)\nfit{T<:Real}(Xs::Vector{T}, Ys::Vector{T}, σXs::Vector{T}, σY::T, rs::Vector{T}; kwargs...) =\n fit(Xs, Ys, σXs, fill(σY, length(Ys)), rs; kwargs...)\nfit{T<:Real}(Xs::Vector{T}, Ys::Vector{T}, σXs::Vector{T}, σY::T, r::T=T(0); kwargs...) =\n fit(Xs, Ys, σXs, fill(σY, length(Ys)), fill(r, length(Xs)); kwargs...)\nfit{T<:Real}(Xs::Vector{T}, Ys::Vector{T}, σX::T, σY::T, rs::Vector{T}; kwargs...) =\n fit(Xs, Ys, fill(σX, length(Xs)), fill(σY, length(Ys)), rs; kwargs...)\nfit{T<:Real}(Xs::Vector{T}, Ys::Vector{T}, σX::T, σY::T, r::T=T(0); kwargs...) =\n fit(Xs, Ys, fill(σX, length(Xs)), fill(σY, length(Ys)), fill(r, length(Xs)); kwargs...)\nfit{T<:Real}(Xs::Vector{T}, Ys::Vector{T}, σXs::Vector{T}, σYs::Vector{T}, r::T=T(0); kwargs...) =\n fit(Xs, Ys, σXs, σYs, fill(r, length(Xs)); kwargs...)\nfunction fit{T<:Real}(Xs::Vector{T}, Ys::Vector{T}, σXs::Vector{T}, σYs::Vector{T}, rs::Vector{T}; niter=400, tol=1E-15)::Tuple{T,T,T,T}\n # TODO: Check for dimension mismatch of vectors\n (a, b) = lsq(Xs, Ys)\n\n ωXs = ω.(σXs)\n ωYs = ω.(σYs)\n αs = α.(ωXs, ωYs)\n\n Ws = zeros(length(Xs))\n βs = zeros(length(Xs))\n barX = 0\n barY = 0\n\n for i in 1:niter\n Ws = W.(ωXs, ωYs, rs, b, αs)\n barX = barvar(Ws, Xs)\n barY = barvar(Ws, Ys)\n Us = Xs - barX\n Vs = Ys - barY\n βs = β.(Ws, Us, Vs, ωXs, ωYs, b, rs, αs)\n\n b_old = b\n b = sum(Ws .* βs .* Vs) / sum(Ws .* βs .* Us)\n\n if abs((b - b_old) / b) < tol\n break\n end\n end\n\n a = barY - b * barX\n # Adjusted x values\n xs = barX + βs\n barx = sum(Ws .* xs) / sum(Ws)\n us = xs - barx\n\n σb = sqrt(sum(Ws .* us.^2)^-1)\n σa = sqrt(sum(Ws)^-1 + barx^2 * σb^2)\n\n return (a, b, σa, σb)\nend\n\nend # module\n", "meta": {"hexsha": "addf20db4b4525f159e476ba94c4145353c95263", "size": 4919, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/YorkFit.jl", "max_stars_repo_name": "alexjohnj/YorkFit.jl", "max_stars_repo_head_hexsha": "21a4cfe36bc8eea186245c0a87303836b8785929", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/YorkFit.jl", "max_issues_repo_name": "alexjohnj/YorkFit.jl", "max_issues_repo_head_hexsha": "21a4cfe36bc8eea186245c0a87303836b8785929", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/YorkFit.jl", "max_forks_repo_name": "alexjohnj/YorkFit.jl", "max_forks_repo_head_hexsha": "21a4cfe36bc8eea186245c0a87303836b8785929", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.1317829457, "max_line_length": 136, "alphanum_fraction": 0.5641390527, "num_tokens": 1941, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951142225532629, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.800695917750077}} {"text": "#--------------------------------------------------------------------\n# Spacetime Discretization methods in Julia\n# Soham 01-2018\n#--------------------------------------------------------------------\n\nfunction cheb(m::Int, x::Float64)::Float64\n return cos(m*acos(x))\nend\n\nfunction chebx{T<:Int}(i::T, N::T)::Float64\n return cospi((i-1)/N)\nend\n\nfunction chebd{T<:Int}(i::T, j::T, N::T)::Float64\n\tif i==j==1\n\t\treturn (2N^2 + 1)/6\n\telseif i==j==N+1\n\t\treturn -(2N^2 + 1)/6\n\telseif i==j\n\t\treturn -chebx(j, N)/(2(1-chebx(j, N)^2))\n\telse\n\t\tci = (i == 1 || i == N+1) ? 2 : 1\n\t\tcj = (j == 1 || j == N+1) ? 2 : 1\n\t\ts = (i + j) % 2 != 0 ? -1 : 1\n\t\treturn (ci/cj)*(s/(chebx(i,N)-chebx(j,N)))\n\tend\nend\n\nfunction chebw{T<:Int}(i::T, N::T)::Float64\n\tW = 0.0\n\tfor j in 1:N+1\n\t\tw = (j == 1 ? 1 : (j-1)%2 == 0 ? 2/(1-(j-1)^2): 0)\n\t\tl = (i == 1 || i == N+1 ? (1/N)*cospi((i-1)*(j-1)/N) : (2/N)*cospi((i-1)*(j-1)/N))\n\t\tW += w*l\n\tend\n\treturn W\nend\n\nfunction chebgrid(N::Int)::Array{Float64,1}\n return Float64[chebx(i,N) for i in 1:N+1]\nend\n\nfunction chebgrid(N::Int, M::Int, loc::Int)::Array{Float64,1}\n return Float64[coordtransL2G(M, loc, chebx(i,N)) for i in 1:N+1]\nend\n\nfunction chebweights(N::Int)::Array{Float64,1}\n return Float64[chebw(i,N) for i in 1:N+1]\nend\n\nfunction vandermonde(N::Int)::Array{Float64,2}\n return Float64[cheb(m,x) for x in chebgrid(N), m in 0:N]\nend\n\nfunction pseudovandermonde(N::Int, collocationpts::Array{Float64, 1})::Array{Float64,2}\n return Float64[cheb(m,x) for x in collocationpts, m in 0:N]\nend\n\nfunction modal2nodal(fmodal::Array{Float64,2})::Array{Float64,2}\n (Mx, My) = size(fmodal) .- 1\n fnodal = Float64[sum(cheb(m-1,x)*cheb(n-1,y)*fmodal[m,n] for m in 1:Mx+1, n in 1:My+1) for x in chebgrid(Mx), y in chebgrid(My)]\nend\n\nfunction nodal2modal(fnodal::Array{Float64,2})::Array{Float64,2}\n (Nx, Ny) = size(fnodal) .- 1\n invndmx = inv(vandermonde(Nx))\n invndmy = inv(vandermonde(Ny))\n fmodal = Float64[sum(invndmy[n,y]*invndmx[m,x]*fnodal[m,n] for x in 1:Nx+1, y in 1:Ny+1) for m in 1:Nx+1, n in 1:Ny+1] \nend\n\n\n", "meta": {"hexsha": "07510998c44fd1437cb2a38d2bb8636c3820a0d7", "size": 2075, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/SpecCalculus.jl", "max_stars_repo_name": "mukherjeesoham/ScalarWave.jl", "max_stars_repo_head_hexsha": "4058b2738159036cfb9d98ad461d49f9e0a8609c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SpecCalculus.jl", "max_issues_repo_name": "mukherjeesoham/ScalarWave.jl", "max_issues_repo_head_hexsha": "4058b2738159036cfb9d98ad461d49f9e0a8609c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SpecCalculus.jl", "max_forks_repo_name": "mukherjeesoham/ScalarWave.jl", "max_forks_repo_head_hexsha": "4058b2738159036cfb9d98ad461d49f9e0a8609c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8194444444, "max_line_length": 134, "alphanum_fraction": 0.5604819277, "num_tokens": 861, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422241476943, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.8006959146969781}} {"text": "\"\"\"\r\nHigher-order clustering coefficient, which generalizes the traditional\r\nclustering coefficients to closure of cliques larger than triangles.\r\n\r\nBased on \"Higher-order clustering in networks\" by Hao Yin, Austin R. Benson, and\r\nJure Leskovec. The original paper may be found at https://arxiv.org/pdf/1704.03913.pdf.\r\nCode from https://github.com/arbenson/HigherOrderClustering.jl.\r\n\"\"\"\r\n\r\nusing LinearAlgebra\r\nusing SparseArrays\r\nusing StatsBase\r\nusing MatrixNetworks\r\ninclude(\"cliques.jl\")\r\n\r\n\"\"\"\r\nhoccf_data\r\n----------\r\n\r\nThis is the data type returned by the function that computes higher-order clustering coefficients.\r\n\r\nThe field values are\r\n\r\norder::Int64\r\n The order of the clustering coefficient (order = 2 is the classical\r\n clustering coefficient definition).\r\n\r\nglobal_hoccf::Float64\r\n The global higher-order clustering coefficient.\r\n\r\navg_hoccf::Float64\r\n The average higher-order clustering coefficient (the mean is taken over\r\n nodes at the center of at least one wedge).\r\n\r\navg_hoccf2::Float64\r\n The average higher-order clustering coefficient, where the local clustering\r\n of a node not in any wedge is considered to be 0.\r\n\r\nlocal_hoccfs::Vector{Float64}\r\n The vector of local higher-order clustering coefficients. If a node is not\r\n the center of at least one wedge, then the value is 0.\r\n\r\nho_wedge_counts::Vector{Int64}\r\n Higher-order wedge counts of nodes: ho_wedge_counts[v] is the number of higher-order\r\n wedges with node v at its center.\r\n\r\nclique_counts::Vector{Int64}\r\n Clique counts of nodes: clique_counts[v] is the number of k-cliques containing\r\n node v where k = order + 1.\r\n\"\"\"\r\nstruct hoccf_data\r\n order::Int64\r\n global_hoccf::Float64\r\n avg_hoccf::Float64\r\n avg_hoccf2::Float64\r\n local_hoccfs::Vector{Float64}\r\n ho_wedge_counts::Vector{Int64}\r\n clique_counts::Vector{Int64}\r\nend\r\n\r\n\"\"\"\r\n`higher_order_ccfs`\r\n======\r\n\r\nComputes the global and average local l-th order clustering coefficients of a\r\nnetwork.\r\n\r\nArguments\r\n---------\r\n - `A::MatrixNetwork`: The network to be analyzed\r\n - `l::Int64`: The order of the clustering coefficients\r\n\r\nThe authors define an l-wedge to be an l-clique with an extra node of degree 1 attached.\r\nFor example, this is a 3-wedge: https://i.imgur.com/Wc1pRzl.png\r\nThe clique node that is adjacent to the extra node is the \"center\" of the wedge.\r\nThe global l-th order clustering coefficient measures the ratio of (l+1)-cliques\r\nto l-wedges: the probability that a randomly chosen l-wedge is \"closed\" into an\r\n(l+1)-clique. The local l-th order clustering coefficient is defined similarly\r\nas the ratio of the number of (l+1)-cliques a node is part of to the number of\r\nl-wedges it is the center of.\r\n\r\nThe traditional clustering coefficients are a special case `hocc(A,2)` of the\r\nabove concept.\r\n\"\"\"\r\nfunction higher_order_ccfs(A::SparseMatrixCSC{T,Int64}, l::Int64) where T\r\n A = min.(A, 1)\r\n A -= Diagonal(A)\r\n n = size(A, 1)\r\n # Get clique counts\r\n clique_counts1 = kcliques(A, l)[1]\r\n clique_counts2 = kcliques(A, l + 1)[1]\r\n degs = vec(sum(A, dims=2))\r\n # normalize\r\n wedge_counts = (degs .- l .+ 1) .* clique_counts1\r\n nz_inds = findall(wedge_counts .> 0)\r\n local_hoccfs = zeros(Float64, n)\r\n local_hoccfs[nz_inds] = l .* clique_counts2[nz_inds] ./ wedge_counts[nz_inds]\r\n return hoccf_data(l, l .* sum(clique_counts2) / sum(wedge_counts),\r\n mean(local_hoccfs[nz_inds]), mean(local_hoccfs),\r\n local_hoccfs, wedge_counts, clique_counts2)\r\nend\r\n", "meta": {"hexsha": "aa98f0c7c0918593dbfd5ec392f968cddd1367bd", "size": 3570, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/HigherOrderClustering.jl", "max_stars_repo_name": "charunupara/HigherOrderNetworks.jl", "max_stars_repo_head_hexsha": "f0e72ea4134e40a19529f501f39448b8ba665906", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-18T23:21:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-18T23:21:16.000Z", "max_issues_repo_path": "src/HigherOrderClustering.jl", "max_issues_repo_name": "joshua-matt/HigherOrderNetworks.jl", "max_issues_repo_head_hexsha": "a52750b619dfd58f311941162e14faeca076c5e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/HigherOrderClustering.jl", "max_forks_repo_name": "joshua-matt/HigherOrderNetworks.jl", "max_forks_repo_head_hexsha": "a52750b619dfd58f311941162e14faeca076c5e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-10-31T21:22:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-03T06:00:42.000Z", "avg_line_length": 35.0, "max_line_length": 99, "alphanum_fraction": 0.7098039216, "num_tokens": 918, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422213778252, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.8006959104780056}} {"text": "#### Kahan matrix\n\nexport Kahan\n\"\"\"\n[`Kahan` matrix](http://math.nist.gov/MatrixMarket/data/MMDELI/kahan/kahan.html)\n\n```julia\njulia> A=Kahan(5,5,1,35)\n5x5 Kahan{Int64,Int64}:\n 1.0 -0.540302 -0.540302 -0.540302 -0.540302\n 0.0 0.841471 -0.454649 -0.454649 -0.454649\n 0.0 0.0 0.708073 -0.382574 -0.382574\n 0.0 0.0 0.0 0.595823 -0.321925\n 0.0 0.0 0.0 0.0 0.501368\n\njulia> A=Kahan(5,3,0.5,0)\n5x3 Kahan{Float64,Int64}:\n 1.0 -0.877583 -0.877583\n 0.0 0.479426 -0.420735\n 0.0 0.0 0.229849\n 0.0 0.0 0.0\n 0.0 0.0 0.0\n\njulia> A=Kahan(3,5,0.5,1e-3)\n3x5 Kahan{Float64,Float64}:\n 1.0 -0.877583 -0.877583 -0.877583 -0.877583\n 0.0 0.479426 -0.420735 -0.420735 -0.420735\n 0.0 0.0 0.229849 -0.201711 -0.201711\n```\n\nFor more details see: N. Higham, A Survey of Condition Number Estimation\nfor Triangular Matrices, SIMAX, Vol. 29, No. 4, pp. 588, 1987,\nhttp://eprints.ma.man.ac.uk/695/01/covered/MIMS_ep2007_10.pdf\n\"\"\"\nstruct Kahan{T<:Number,T1<:Number} <: AbstractMatrix{T}\n m::Int # dimension\n n::Int # dimension\n theta::T # angle\n pert::T1 # perturbation is pert*eps()\nend # immutable\n\n# Define its size\nsize(A::Kahan, r::Int) = r==1 ? A.m : A.n\nsize(A::Kahan) = A.m, A.n\n\n# Index into a Kahan\nfunction getindex(A::Kahan,i::Integer,j::Integer)\n m=minimum(size(A))\n t=tan(A.theta)\n c=1.0/sqrt(1.0+t^2)\n s=t*c\n if i>m; return 0.0\n elseif i>j; return 0.0\n elseif i==j; return s^(i-1)+A.pert*eps()*(m-i+1)\n else return -c*s^(i-1)\n end\nend # getindex\n\n# Dense version of Kahan\nMatrix(A::Kahan) =[A[i,j] for i=1:size(A,1), j=1:size(A,2)]\n", "meta": {"hexsha": "255232334911ae8f067da684af2884eb7c55e5e0", "size": 1666, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/kahan.jl", "max_stars_repo_name": "JuliaMath/SpecialMatrices.jl", "max_stars_repo_head_hexsha": "05cb35883d25495aec69d6fb8bc7d40460ddcdb8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2018-09-13T10:26:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T23:21:37.000Z", "max_issues_repo_path": "src/kahan.jl", "max_issues_repo_name": "JuliaMath/SpecialMatrices.jl", "max_issues_repo_head_hexsha": "05cb35883d25495aec69d6fb8bc7d40460ddcdb8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 36, "max_issues_repo_issues_event_min_datetime": "2017-08-17T17:39:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-31T18:27:05.000Z", "max_forks_repo_path": "src/kahan.jl", "max_forks_repo_name": "JuliaMath/SpecialMatrices.jl", "max_forks_repo_head_hexsha": "05cb35883d25495aec69d6fb8bc7d40460ddcdb8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2017-08-17T16:49:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-21T10:22:09.000Z", "avg_line_length": 27.3114754098, "max_line_length": 80, "alphanum_fraction": 0.600240096, "num_tokens": 762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.8633916047011594, "lm_q1q2_score": 0.8006776822361126}} {"text": "\"\"\"\r\n backsub(A,B)\r\n\r\nadalah fungsi untuk menyelesaikan SPL `Ax=B` dengan `A` adalah matriks segitiga\r\natas dan `B` adalah vektor ruas kanan.\r\n\r\n# Examples\r\n```jldoctest\r\njulia> A = [ 4 -1 2 3\r\n 0 -2 7 -4\r\n 0 0 6 5\r\n 0 0 0 3];\r\n\r\njulia> B = [20;-7; 4; 6];\r\n\r\njulia> X = backsub(A,B)\r\n4×1 Array{Float64,2}:\r\n 3.0\r\n -4.0\r\n -1.0\r\n 2.0\r\n```\r\nreturn solusi SPL `X`\r\n\"\"\"\r\nfunction backsub(A,B)\r\n # Hitung ukuran matriks dan inisiasi solusi X\r\n n = length(B);\r\n X = zeros(n,1);\r\n # Hitung nilai solusi X ke-n\r\n X[n] = B[n]/A[n,n];\r\n # Hitung nilai solusi X ke- n-1 sampai X ke-1\r\n for i = n-1:-1:1\r\n X[i] = (B[i] - A[i,i+1:n]'X[i+1:n])/A[i,i];\r\n end\r\n return X\r\nend\r\n", "meta": {"hexsha": "ab639c67dbd28b57fdc4adf3e17d72f382399f8f", "size": 735, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/backsub.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/backsub.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/backsub.jl", "max_forks_repo_name": "mkhoirun-najiboi/metnum.jl", "max_forks_repo_head_hexsha": "a6e35d04dc277318e32256f9b432264157e9b8f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.8648648649, "max_line_length": 80, "alphanum_fraction": 0.5074829932, "num_tokens": 299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.965899577232538, "lm_q2_score": 0.8289388167733099, "lm_q1q2_score": 0.8006716526729803}} {"text": "function chebyshev_quadrature(node_type::Function,n::S,domain = [1.0,-1.0]) where {S <: Integer}\n\n if n <= 0\n\n error(\"The number of nodes must be positive.\")\n \n end\n \n nodes = zeros(n)\n weights = zeros(n)\n\n if node_type == chebyshev_nodes # weighting function is (1.0 .- nodes.^2).^(-1/2) -- (first kind)\n\n for i = 1:n\n nodes[i] = (domain[1]+domain[2])/2.0 - cos((i-0.5)*pi/n)*(domain[1]-domain[2])/2.0\n weights[i] = pi/n\n end\n\n return nodes, weights\n\n elseif node_type == chebyshev_extrema # weighting function is (1.0 .- nodes.^2).^(1/2) -- (second kind)\n\n for i = 1:n\n nodes[i] = (domain[1]+domain[2])/2.0 - cos((i-1)*pi/(n-1))*(domain[1]-domain[2])/2.0\n weights[i] = (pi/(n-1))*sin(((i-1)/(n-1))*pi)^2\n end\n\n return nodes, weights\n \n else\n \n error(\"This node type is not supported\")\n\n end\n\nend\n ", "meta": {"hexsha": "8b83fbc50f6784ecad507e650f172d7c9e98620e", "size": 868, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/chebyshev_quadrature.jl", "max_stars_repo_name": "RJDennis/ChebyshevApprox.jl", "max_stars_repo_head_hexsha": "f3052ad7b6eab8bcec2930b111b52f92d5b00586", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2016-12-05T19:52:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T03:08:35.000Z", "max_issues_repo_path": "src/chebyshev_quadrature.jl", "max_issues_repo_name": "RJDennis/ChebyshevApprox.jl", "max_issues_repo_head_hexsha": "f3052ad7b6eab8bcec2930b111b52f92d5b00586", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2016-08-05T15:45:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-20T19:08:32.000Z", "max_forks_repo_path": "src/chebyshev_quadrature.jl", "max_forks_repo_name": "RJDennis/ChebyshevApprox.jl", "max_forks_repo_head_hexsha": "f3052ad7b6eab8bcec2930b111b52f92d5b00586", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-08-23T23:50:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T12:21:55.000Z", "avg_line_length": 23.4594594595, "max_line_length": 105, "alphanum_fraction": 0.5679723502, "num_tokens": 307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995772325382, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.8006716445092994}} {"text": "using Distributions\nusing LinearAlgebra\nusing Plots\n\n# Set Parameters\nM = 9 # total number of training data\nN = 9 # degree of a polynomial\nlambda_ = 1.75e-6 # regularization parameter\n\n# Set Function to Generate Data\ndist = Normal(0.0, 0.1)\nbase(x) = sin.(2pi*x)\ngen(x) = base(x) + rand(dist, length(x))\n\n# Set Function to Generate Polynomial Matrix\nfunction polynomial_matrix(x, N)\n m = length(x)\n X = fill(1.0, m)\n for j in 1:N\n x_vec = x .^ j\n X = hcat(X, x_vec)\n end\n return X\nend\n\n# Set Function to Calculate Coefficient\nfunction weight(x, y, N, lambda_)\n X = polynomial_matrix(x, N)\n w = (X' * X + lambda_ * Matrix{Float64}(I, N+1, N+1)) \\ X' * y\n return w\nend\n\n# Set Function to Output Value\nfunction f(x, w)\n X = polynomial_matrix(x, length(w)-1)\n y = X * w\n return y\nend\n\n# Generate Data\nstep = 1.0 / (M - 1)\nx = collect(0.0:step:1.0)\ny = gen(x)\nprintln(\"x = \", x)\nprintln(\"y = \", y)\n\n# Calculate Coefficient of Polynomial\nw = weight(x, y, N, lambda_)\nprintln(\"w = \", w)\n\n# Output Graph\ngr()\nscatter(x, y, xlabel=\"x\", ylabel=\"y\", label=\"data\")\ngraph_x = collect(0.0:0.01:1.0)\ngraph_y = f(graph_x, w)\nplot!(graph_x, base(graph_x), label=\"base\")\nplot!(graph_x, graph_y, label=string(\"f(x, w)\"))\n\n# Save Image\nsavefig(\"graph\")\n", "meta": {"hexsha": "8205a757fc8d789696fa49586877d3ef98a2079b", "size": 1283, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "1_Introduction/1-2_Regularization/Regularization.jl", "max_stars_repo_name": "koba-jon/prml_julia", "max_stars_repo_head_hexsha": "9e01357f3ee79cc610b760bab9a1ff3cf604dd9e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "1_Introduction/1-2_Regularization/Regularization.jl", "max_issues_repo_name": "koba-jon/prml_julia", "max_issues_repo_head_hexsha": "9e01357f3ee79cc610b760bab9a1ff3cf604dd9e", "max_issues_repo_licenses": ["MIT"], "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_Introduction/1-2_Regularization/Regularization.jl", "max_forks_repo_name": "koba-jon/prml_julia", "max_forks_repo_head_hexsha": "9e01357f3ee79cc610b760bab9a1ff3cf604dd9e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0327868852, "max_line_length": 66, "alphanum_fraction": 0.6321122369, "num_tokens": 435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995723244552, "lm_q2_score": 0.8289388083214155, "lm_q1q2_score": 0.8006716404407989}} {"text": "module NumericalIntegration\n\nusing LinearAlgebra\nusing Logging\nusing Base.Iterators\nusing Interpolations\n\nexport integrate, cumul_integrate\nexport Trapezoidal, TrapezoidalEven, TrapezoidalFast, TrapezoidalEvenFast\nexport SimpsonEven, SimpsonEvenFast\nexport RombergEven\nexport IntegrationMethod\n\nabstract type IntegrationMethod end\n\nstruct Trapezoidal <: IntegrationMethod end\nstruct TrapezoidalEven <: IntegrationMethod end\nstruct TrapezoidalFast <: IntegrationMethod end\nstruct TrapezoidalEvenFast <: IntegrationMethod end\nstruct SimpsonEven <: IntegrationMethod end # https://en.wikipedia.org/wiki/Simpson%27s_rule#Alternative_extended_Simpson.27s_rule\nstruct SimpsonEvenFast <: IntegrationMethod end\nstruct RombergEven{T<:AbstractFloat} <: IntegrationMethod\n acc::T\nend # https://en.wikipedia.org/wiki/Romberg%27s_method\nRombergEven() = RombergEven(1e-12)\n\nconst HALF = 1//2\n\n\n#documentation\n\n\"\"\"\n integrate(x,y...)\n\nCompute numerical integral of y(x) from x=x[1] to x=x[end]. Return a scalar of the same type as the input. If no method is supplied, use Trapezdoial.\n\"\"\"\nfunction integrate(x,y...) end\n\n\n\"\"\"\n cumul_integrate(x,y...)\n\nCompute cumulative numerical integral of y(x) from x=x[1] to x=x[end]. Return a vector with elements of the same type as the input. If no method is supplied, use Trapezdoial.\n\"\"\"\nfunction cumul_integrate(x,y...) end\n\n#implementation\n\nfunction _zero(x,y)\n ret = zero(eltype(x)) + zero(eltype(y))\nend\n\nfunction _zeros(x::AbstractVector,y::AbstractVector)\n ret = zeros(eltype(x),size(x)) + zeros(eltype(y),size(y))\nend\n\n\"\"\"\n integrate(x::AbstractVector, y::AbstractVector, ::Trapezoidal)\n\nUse Trapezoidal rule. This is the default when no method is supplied.\n\"\"\"\nfunction integrate(x::AbstractVector, y::AbstractVector, ::Trapezoidal)\n @assert length(x) == length(y) \"x and y vectors must be of the same length!\"\n retval = _zero(x,y)\n for i in 1 : length(y)-1\n retval += (x[i+1] - x[i]) * (y[i] + y[i+1])\n end\n return HALF * retval\nend\n\n\"\"\"\n integrate(x::AbstractVector, y::AbstractVector, ::TrapezoidalEven)\n\nUse Trapezoidal rule, assuming evenly spaced vector x.\n\"\"\"\nfunction integrate(x::AbstractVector, y::AbstractVector, ::TrapezoidalEven)\n @assert length(x) == length(y) \"x and y vectors must be of the same length!\"\n return (x[2] - x[1]) * (HALF * (y[1] + y[end]) + sum(y[2:end-1]))\nend\n\n\"\"\"\n integrate(x::AbstractVector, y::AbstractVector, ::TrapezoidalFast)\n\nUse Trapezoidal rule. Unsafe method: no bound checking.\n\"\"\"\nfunction integrate(x::AbstractVector, y::AbstractVector, ::TrapezoidalFast)\n retval = _zero(x,y)\n @fastmath @simd for i in 1 : length(y)-1\n @inbounds retval += (x[i+1] - x[i]) * (y[i] + y[i+1])\n end\n return HALF * retval\nend\n\n\"\"\"\n integrate(x::AbstractVector, y::AbstractVector, ::TrapezoidalEvenFast)\n\nUse Trapezoidal rule, assuming evenly spaced vector x. Unsafe method: no bound checking.\n\"\"\"\nfunction integrate(x::AbstractVector, y::AbstractVector, ::TrapezoidalEvenFast)\n retval = _zero(x,y)\n N = length(y) - 1\n @fastmath @simd for i in 2 : N\n @inbounds retval += y[i]\n end\n @inbounds return (x[2] - x[1]) * (retval + HALF*y[1] + HALF*y[end])\nend\n\n\"\"\"\n integrate(x::AbstractVector, y::AbstractVector, ::SimpsonEven)\n\nUse Simpson's rule, assuming evenly spaced vector x.\n\"\"\"\nfunction integrate(x::AbstractVector, y::AbstractVector, ::SimpsonEven)\n @assert length(x) == length(y) \"x and y vectors must be of the same length!\"\n retval = (17*y[1] + 59*y[2] + 43*y[3] + 49*y[4] + 49*y[end-3] + 43*y[end-2] + 59*y[end-1] + 17*y[end]) / 48\n for i in 5 : length(y) - 1\n retval += y[i]\n end\n return (x[2] - x[1]) * retval\nend\n\n\"\"\"\n integrate(x::AbstractVector, y::AbstractVector, ::SimpsonEven)\n\nUse Simpson's rule, assuming evenly spaced vector x. Unsafe method: no bound checking.\n\"\"\"\nfunction integrate(x::AbstractVector, y::AbstractVector, ::SimpsonEvenFast)\n @inbounds retval = 17*y[1] + 59*y[2] + 43*y[3] + 49*y[4]\n @inbounds retval += 49*y[end-3] + 43*y[end-2] + 59*y[end-1] + 17*y[end]\n retval /= 48\n @fastmath @inbounds for i in 5 : length(y)-1\n retval += y[i]\n end\n @inbounds return (x[2] - x[1]) * retval\nend\n\n\"\"\"\n integrate(x::AbstractVector, y::AbstractMatrix, method; dims=2)\n\nWhen y is an array, compute integral along dimension specified by dims (default 2: columns).\n\"\"\"\nfunction integrate(x::AbstractVector, y::AbstractMatrix, M::IntegrationMethod; dims=2)\n out = [integrate(x,selectdim(y,dims,j),M) for j=1:size(y,dims)]\n return out\nend\n\nfunction integrate(x::AbstractVector, y::AbstractVector, m::RombergEven)\n @assert length(x) == length(y) \"x and y vectors must be of the same length!\"\n @assert ((length(x) - 1) & (length(x) - 2)) == 0 \"Need length of vector to be 2^n + 1\"\n maxsteps::Integer = Int(log2(length(x)-1))\n rombaux = zeros(eltype(y), maxsteps, 2)\n prevrow = 1\n currrow = 2\n @inbounds h = x[end] - x[1]\n @inbounds rombaux[prevrow, 1] = (y[1] + y[end])*h*HALF\n @inbounds for i in 1 : (maxsteps-1)\n h *= HALF\n npoints = 1 << (i-1)\n jumpsize = div(length(x)-1, 2*npoints)\n c = 0.0\n for j in 1 : npoints\n c += y[1 + (2*j-1)*jumpsize]\n end\n rombaux[1, currrow] = h*c + HALF*rombaux[1, prevrow]\n for j in 2 : (i+1)\n n_k = 4^(j-1)\n rombaux[j, currrow] = (n_k*rombaux[j-1, currrow] - rombaux[j-1, prevrow])/(n_k - 1)\n end\n\n if i > maxsteps//3 && norm(rombaux[i, prevrow] - rombaux[i+1, currrow], Inf) < m.acc\n return rombaux[i+1, currrow]\n end\n\n prevrow, currrow = currrow, prevrow\n end\n finalerr = norm(rombaux[maxsteps-1, prevrow] - rombaux[maxsteps, currrow], Inf)\n @warn \"RombergEven :: final step reached, but accuracy not: $finalerr > $(m.acc)\"\n @inbounds return rombaux[maxsteps, prevrow]\nend\n\n\n@inline function _midpoints(x::AbstractVector{T}) where T\n length(x) == 1 && return x\n retval = Vector{T}(undef, length(x)-1)\n @simd for i in eachindex(retval)\n retval[i] = HALF * (x[i] + x[i+1])\n end\n return retval\nend\n@inline function _midpoints(x::AbstractRange)\n length(x) == 1 && return x\n Δx = HALF*step(x)\n return range(first(x)+Δx, stop=last(x)-Δx, length=length(x)-1)\nend\n\nfunction integrate(X::NTuple{N,AbstractVector}, Y::AbstractArray{T,N}, ::Trapezoidal) where {T,N}\n @assert length.(X) == size(Y)\n return integrate(X, Y, TrapezoidalFast())\nend\n\nfunction integrate(X::NTuple{N,AbstractVector}, Y::AbstractArray{T,N}, ::TrapezoidalFast) where {T,N}\n midpnts = map(_midpoints, X)\n Δ(x::AbstractVector) = length(x) > 1 ? diff(x) : 1\n Δxs = map(Δ, X)\n interp = LinearInterpolation(X,Y)\n f((Δx,x)) = prod(Δx)*interp(x...)\n return sum(f, zip(product(Δxs...), product(midpnts...)))\nend\n\nfunction integrate(X::NTuple{N,AbstractVector}, Y::AbstractArray{T,N}, ::TrapezoidalEvenFast) where {T,N}\n midpnts = map(_midpoints, X)\n Δ(x::AbstractVector) = length(x) > 1 ? x[2] - x[1] : 1\n Δx = prod(Δ, X)\n interp = LinearInterpolation(X,Y)\n f(x) = interp(x...)\n return Δx*sum(f, product(midpnts...))\nend\n\nfunction integrate(X::NTuple{N,AbstractRange}, Y::AbstractArray{T,N}, ::TrapezoidalEvenFast) where {T,N}\n midpnts = map(_midpoints, X)\n Δ(x::AbstractVector) = length(x) > 1 ? step(x) : 1\n Δx = prod(Δ, X)\n interp = LinearInterpolation(X,Y)\n f(x) = interp(x...)\n return Δx*sum(f, product(midpnts...))\nend\n\n\n\n\n#function integrate(X::Tuple{AbstractVector}, Y::AbstractVector{T}, M::IntegrationMethod) :: T where {T}\n# return integrate(X[1], Y, M)\n#end\n#\"\"\"\n# integrate(X::NTuple{N,AbstractVector}, Y::AbstractArray{T,N}, method, cache=nothing)\n#\n#Given an n-dimensional grid of values, compute the total integral along each dim\n#\"\"\"\n#function integrate(X::NTuple{N,AbstractVector}, Y::AbstractArray{T,N}, M::IntegrationMethod) :: T where {T,N}\n# n = last(size(Y))\n# cache = Vector{T}(undef, n)\n# x = X[1:N-1]\n# @inbounds for i in 1:n\n# cache[i] = integrate(x, selectdim(Y,N,i), M)\n# end\n# return integrate(X[end], cache, M)\n#end\n\n\n\n# cumulative integrals\n\n\"\"\"\n cumul_integrate(x::AbstractVector, y::AbstractVector, ::Trapezoidal)\n\nUse Trapezoidal rule. This is the default when no method is supplied.\n\"\"\"\nfunction cumul_integrate(x::AbstractVector, y::AbstractVector, ::Trapezoidal)\n @assert length(x) == length(y) \"x and y vectors must be of the same length!\"\n retarr = _zeros(x,y)\n for i in 2 : length(y)\n retarr[i] = retarr[i-1] + (x[i] - x[i-1]) * (y[i] + y[i-1])\n end\n return HALF * retarr\nend\n\n\"\"\"\n cumul_integrate(x::AbstractVector, y::AbstractVector, ::TrapezoidalEven)\n\nUse Trapezoidal rule, assuming evenly spaced vector x.\n\"\"\"\nfunction cumul_integrate(x::AbstractVector, y::AbstractVector, ::TrapezoidalEven)\n @assert length(x) == length(y) \"x and y vectors must be of the same length!\"\n retarr = _zeros(x,y)\n for i in 2 : length(y)\n retarr[i] = retarr[i-1] + (y[i-1] + y[i])\n end\n return (x[2] - x[1]) * HALF * retarr\nend\n\n\"\"\"\n cumul_integrate(x::AbstractVector, y::AbstractVector, ::TrapezoidalFast)\n\nUse Trapezoidal rule. Unsafe method: no bound checking.\n\"\"\"\nfunction cumul_integrate(x::AbstractVector, y::AbstractVector, ::TrapezoidalFast)\n retarr = _zeros(x,y)\n @fastmath for i in 2 : length(y) #not sure if @simd can do anything here\n @inbounds retarr[i] = retarr[i-1] + (x[i] - x[i-1]) * (y[i] + y[i-1])\n end\n return HALF * retarr\nend\n\n\"\"\"\n cumul_integrate(x::AbstractVector, y::AbstractVector, ::TrapezoidalEvenFast)\n\nUse Trapezoidal rule, assuming evenly spaced vector x. Unsafe method: no bound checking.\n\"\"\"\nfunction cumul_integrate(x::AbstractVector, y::AbstractVector, ::TrapezoidalEvenFast)\n retarr = _zeros(x,y)\n @fastmath for i in 2 : length(y)\n @inbounds retarr[i] = retarr[i-1] + (y[i] + y[i-1])\n end\n @inbounds return (x[2] - x[1]) * HALF * retarr\nend\n\n\"\"\"\n cumul_integrate(x::AbstractVector, y::AbstractMatrix, method; dims=2)\n\nWhen y is an array, compute integral along each dimension specified by dims (default 2: columns)\n\"\"\"\nfunction cumul_integrate(x::AbstractVector, y::AbstractMatrix, M::IntegrationMethod; dims=2)\n return hcat([cumul_integrate(x,selectdim(y,dims,j),M) for j=1:size(y,dims)]...)\nend\n\n#default behaviour\nintegrate(x::AbstractVector, y::AbstractVector) = integrate(x, y, Trapezoidal())\n\nintegrate(x::AbstractVector, y::AbstractMatrix; dims=2) = integrate(x, y, Trapezoidal(); dims=dims)\n\nintegrate(X::NTuple, Y::AbstractArray) = integrate(X, Y, Trapezoidal())\n\ncumul_integrate(x::AbstractVector, y::AbstractVector) = cumul_integrate(x, y, Trapezoidal())\n\ncumul_integrate(x::AbstractVector, y::AbstractMatrix; dims=2) = cumul_integrate(x, y, Trapezoidal(); dims=dims)\n\nend # module\n", "meta": {"hexsha": "c035c233a78e768473c11e462b5a177d961c8e8c", "size": 10894, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/NumericalIntegration.jl", "max_stars_repo_name": "UnofficialJuliaMirror/NumericalIntegration.jl-e7bfaba1-d571-5449-8927-abc22e82249b", "max_stars_repo_head_hexsha": "7c93e78e767b34057ea916a76cbc1945d44f9f47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NumericalIntegration.jl", "max_issues_repo_name": "UnofficialJuliaMirror/NumericalIntegration.jl-e7bfaba1-d571-5449-8927-abc22e82249b", "max_issues_repo_head_hexsha": "7c93e78e767b34057ea916a76cbc1945d44f9f47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NumericalIntegration.jl", "max_forks_repo_name": "UnofficialJuliaMirror/NumericalIntegration.jl-e7bfaba1-d571-5449-8927-abc22e82249b", "max_forks_repo_head_hexsha": "7c93e78e767b34057ea916a76cbc1945d44f9f47", "max_forks_repo_licenses": ["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.2134146341, "max_line_length": 174, "alphanum_fraction": 0.6627501377, "num_tokens": 3378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331958, "lm_q2_score": 0.8577681031721324, "lm_q1q2_score": 0.8006671793961114}} {"text": "@doc raw\"\"\"\n NodaHilbert{T<:AbstractFloat}\n\nNoda-Hilbert transform.\n\nThe Noda-Hilbert transformation is a square, skew symmetric,\n[Toeplitz matrix](https://en.wikipedia.org/wiki/Toeplitz_matrix)\nwith zero diagonal defined as follows:\n\n```math\nN_{ij}\n = \\begin{cases}\n 0 & i \\eq j\n \\frac{1}{\\pi (j - i)} & i \\neq i \\\\\n \\end{cases}\n```\n\n# Examples\n```jldoctest\njulia> N === NodaHilbert{Float64}()\ntrue\n\njulia> NodaHilbert{Float32}()\nNodaHilbert{Float32}()\n\njulia> N(3)\n3×3 ToeplitzMatrices.Toeplitz{Float64,Complex{Float64}}:\n -0.0 0.31831 0.159155\n -0.31831 -0.0 0.31831\n -0.159155 -0.31831 -0.0\n```\n\"\"\"\n# TODO: should we subtype AbstractMatrix?\nstruct NodaHilbert{T<:AbstractFloat} end\nNodaHilbert() = NodaHilbert{Float64}()\nconst N = NodaHilbert()\n\n# Elements progressively decrease in magnitude.\n@inline function calcfirstcolumn(T, n, nmax=21_361_417)\n c = zeros(T, n)\n @inbounds for i in 1:min(n-1, nmax)\n c[i+1] = 1 / (π * i)\n end\n return c\nend\n\n\"\"\"\n (N::NodaHilbert)(n::Int)\n\nRealize the Noda-Hilbert transform matrix of size `n`.\n\n`n` is the number of rows (and columns) in resulting matrix.\n\"\"\"\nfunction (N::NodaHilbert{T})(n::Int) where {T}\n c = calcfirstcolumn(T, n)\n return Toeplitz(-c, c)\nend\n\n# TODO: check eltype(A) when realizing the transform?\n# TODO: probably improve the fact that it realizes an object every time?\nBase.:*(N::NodaHilbert, A::AbstractArray) = N(size(A, 1)) * A\n", "meta": {"hexsha": "fae03cf29abe5da87381765ae73f3018e3515fdc", "size": 1486, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nodahilbert.jl", "max_stars_repo_name": "schneiderfelipe/CorrelationSpectroscopy.jl", "max_stars_repo_head_hexsha": "283862b24217c69363f5006c5c86c1a1bd289b97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-01-01T18:54:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-02T00:36:22.000Z", "max_issues_repo_path": "src/nodahilbert.jl", "max_issues_repo_name": "schneiderfelipe/CorrelationSpectroscopy.jl", "max_issues_repo_head_hexsha": "283862b24217c69363f5006c5c86c1a1bd289b97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/nodahilbert.jl", "max_forks_repo_name": "schneiderfelipe/CorrelationSpectroscopy.jl", "max_forks_repo_head_hexsha": "283862b24217c69363f5006c5c86c1a1bd289b97", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-01T18:54:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-01T18:54:30.000Z", "avg_line_length": 23.9677419355, "max_line_length": 72, "alphanum_fraction": 0.6534320323, "num_tokens": 509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308091776496, "lm_q2_score": 0.8577681013541611, "lm_q1q2_score": 0.8006671729337909}} {"text": "# Auxiliary functions \nfunction gcd(a::Integer, b::Integer) \n if a > b\n return gcd(b, a)\n else\n c = b % a\n if c == 0\n return a\n else return gcd(a, c)\n end\n end\nend\n\nfunction gcd(a::Vector{Integer})\n m = a[1]\n for i in 1:length(a)\n m = gcd(m, a[i])\n end\n m\nend\n\nlcm(a::Integer, b::Integer) = round(Int, a * b / gcd(a, b))\n\nfunction lcm(a::AbstractVector{<:Integer})\n m = a[1]\n for i in 1:length(a)\n m = lcm(m, a[i])\n end\nm\nend\n\n\"\"\"\n sieve(n)\nSieve of Eratosthenes, finding all prime numbers up to `n`, see https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\n\"\"\"\nfunction sieve(n)\n is_prime=trues(n)\n for i in 2:ceil(Int,√n)\n if is_prime[i]\n for j in i^2:i:n\n if j %i==0\n is_prime[j]=false\n end\n end\n end\n end\n return (x for x in 2:n if is_prime[x])\nend\n\nfunction num_of_factors(n)\n n> 1 || return 1\n key=0 \n val=0\n s=1\n k=2\n while n!=k\n if n %k==0\n key=k\n val+=1\n n=round(Int,n/k)\n else\n s*=val+1\n val=0\n k+= k==2 ? 1 : 2\n end\n end\n n==key ? val+=1 : val=1\n s*=val+1\nend\n\nfunction is_abundant(n)\n n>=12 || return false\n s=1\n i=2\n while i*i <=n\n a= n%i\n b=div(n,i)\n if a==0 \n if i != b\n s+=i+b\n else \n s+=i\n end \n end\n i+=1\n if s > n\n return true\n end\n end\n return false\nend\n\n\"\"\"\n cyclelen(x::Integer)\nlength of Reciprocal cycles\n\"\"\"\nfunction cyclelen(x::Integer)\n rems=zeros(x)\n loc=1\n @assert x>=1\n r=1\n d,r=divrem(r,x)\n while r!=0\n rems[loc]=r\n r*=10\n d,r=divrem(r,x)\n t=findfirst(x->x==r,rems[1:loc]) #第一个相同位置\n loc+=1 # 当前位置\n if !isnothing(t)\n return loc-t\n end\n end\n return 0\nend\n\n\"\"\"\n primecounter(f::Function)\nreturn the amount of prime numbers generated by `f`.\n\"\"\"\nfunction primecounter(f::Function)\n x=0\n out=f(x)\n cnt=0\n while isprime(out)\n cnt+=1 \n x+=1\n out=f(x)\n end\n return cnt\nend\n\nfunction isprime(n::Integer)\n n<= 1 && return false\n if iseven(n) && n!=2 \n return false\n end\n if n==3 \n return true\n end\n i=3\n while i*i <=n\n if n%i ==0\n return false\n end\n i+=2\n end\n return true\nend\n\n\"\"\"\n cycles(n)\nreturn circular numbers generated by `n`, eg. 123 gives [123,231,312].\n\"\"\"\nfunction cycles(n)\n @assert n>=0\n if n <10\n return [n]\n end\n digs=digits(n)\n d=length(digs)\n cyc=zeros(Int,d)\n x=[10^i for i in 0:d-1]\n for i in 1:d\n cyc[i]=sum(x .* digs[vcat(i:d,1:i-1)])\n end\n return cyc\nend\n\nfunction istruncatableprime(n)\n @assert n >10\n if !isprime(n)\n return false\n else \n str=string(n)\n flag=true\n for i in 1:length(str)-1\n a=parse(Int,str[1:i])\n b=parse(Int,str[i+1:end])\n if !isprime(a) || !isprime(b)\n flag=false\n break\n end\n end\n return flag\n end \nend", "meta": {"hexsha": "130b15883adcaeaf5e13713c1bdf94b32e9ff6f3", "size": 3314, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/auxfun.jl", "max_stars_repo_name": "sukanka/ProjectEuler.jl", "max_stars_repo_head_hexsha": "6705add264c490e2de1cda3cab73699884fd549e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/auxfun.jl", "max_issues_repo_name": "sukanka/ProjectEuler.jl", "max_issues_repo_head_hexsha": "6705add264c490e2de1cda3cab73699884fd549e", "max_issues_repo_licenses": ["MIT"], "max_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.jl", "max_forks_repo_name": "sukanka/ProjectEuler.jl", "max_forks_repo_head_hexsha": "6705add264c490e2de1cda3cab73699884fd549e", "max_forks_repo_licenses": ["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.8172043011, "max_line_length": 115, "alphanum_fraction": 0.4674109837, "num_tokens": 1049, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.971129092218133, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.8006589621304924}} {"text": "\"\"\"\r\n regulaFalsi(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 = regulaFalsi(f,0,2);\r\n\r\njulia> c\r\n1.1141571430336825\r\n\r\njulia> flag\r\n0\r\n\r\njulia> M\r\n4×5 Array{Float64,2}:\r\n 0.0 0.0 1.09975 2.0 -0.0200192\r\n 1.0 1.09975 1.12124 2.0 0.00983461\r\n 2.0 1.09975 1.11416 1.12124 5.63036e-6\r\n 3.0 1.09975 1.11416 1.11416 3.00226e-9\r\n```\r\nreturn solusi `c` dengan `flag` bernilai 0 jika metode regula falsi 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 regulaFalsi(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 : fa fb harus beda tanda\";\r\n flag = 2;\r\n return;\r\n end\r\n for k = 1:maxi\r\n c = b-fb*(b-a)/(fb-fa);\r\n fc = f(c);\r\n dx = min(c-a,b-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 abs(fc) < delta || abs(dx)< delta\r\n flag = 0; break;\r\n end\r\n end\r\n return c,flag,M\r\nend\r\n", "meta": {"hexsha": "0ca1552bfc76d9d3b7f4fc8bc19ff3a79a4453c6", "size": 1416, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/regulaFalsi.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/regulaFalsi.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/regulaFalsi.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.2131147541, "max_line_length": 87, "alphanum_fraction": 0.4922316384, "num_tokens": 551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9124361509525462, "lm_q2_score": 0.8774767938900121, "lm_q1q2_score": 0.8006415483671833}} {"text": "# Whitening\n\n## Solve whitening based on covariance\n#\n# finds W, such that W'CW = I\n#\nfunction cov_whitening(C::Cholesky{T}) where {T<:Real}\n cf = C.UL\n Matrix{T}(inv(istriu(cf) ? cf : cf'))\nend\n\ncov_whitening!(C::DenseMatrix{<:Real}) = cov_whitening(cholesky!(Hermitian(C, :U)))\ncov_whitening(C::DenseMatrix{<:Real}) = cov_whitening!(copy(C))\n\ncov_whitening!(C::DenseMatrix{<:Real}, regcoef::Real) = cov_whitening!(regularize_symmat!(C, regcoef))\ncov_whitening(C::DenseMatrix{<:Real}, regcoef::Real) = cov_whitening!(copy(C), regcoef)\n\n## Whitening type\n\nstruct Whitening{T<:Real}\n mean::Vector{T}\n W::Matrix{T}\n\n function Whitening{T}(mean::Vector{T}, W::Matrix{T}) where {T<:Real}\n d, d2 = size(W)\n d == d2 || error(\"W must be a square matrix.\")\n isempty(mean) || length(mean) == d ||\n throw(DimensionMismatch(\"Sizes of mean and W are inconsistent.\"))\n return new(mean, W)\n end\nend\nWhitening(mean::Vector{T}, W::Matrix{T}) where {T<:Real} = Whitening{T}(mean, W)\n\nindim(f::Whitening) = size(f.W, 1)\noutdim(f::Whitening) = size(f.W, 2)\nmean(f::Whitening) = fullmean(indim(f), f.mean)\n\ntransform(f::Whitening, x::AbstractVecOrMat) = transpose(f.W) * centralize(x, f.mean)\n\n## Fit whitening to data\n\nfunction fit(::Type{Whitening}, X::DenseMatrix{T};\n mean=nothing, regcoef::Real=zero(T)) where {T<:Real}\n n = size(X, 2)\n n > 1 || error(\"X must contain more than one sample.\")\n mv = preprocess_mean(X, mean)\n Z = centralize(X, mv)\n C = rmul!(Z * transpose(Z), one(T) / (n - 1))\n return Whitening(mv, cov_whitening!(C, regcoef))\nend\n\n# invsqrtm\n\nfunction _invsqrtm!(C::Matrix{<:Real})\n n = size(C, 1)\n size(C, 2) == n || error(\"C must be a square matrix.\")\n E = eigen!(Symmetric(C))\n U = E.vectors\n evs = E.values\n for i = 1:n\n @inbounds evs[i] = 1.0 / sqrt(sqrt(evs[i]))\n end\n rmul!(U, Diagonal(evs))\n return U * transpose(U)\nend\n\ninvsqrtm(C::DenseMatrix{<:Real}) = _invsqrtm!(copy(C))\n", "meta": {"hexsha": "dea299998f3b9d3c1ba5c8ff728e941db0421fad", "size": 2003, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/whiten.jl", "max_stars_repo_name": "UnofficialJuliaMirror/MultivariateStats.jl-6f286f6a-111f-5878-ab1e-185364afe411", "max_stars_repo_head_hexsha": "0d000b70c108e5c57f9b560f202aa18c863783aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-23T08:11:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-23T08:11:09.000Z", "max_issues_repo_path": "src/whiten.jl", "max_issues_repo_name": "UnofficialJuliaMirror/MultivariateStats.jl-6f286f6a-111f-5878-ab1e-185364afe411", "max_issues_repo_head_hexsha": "0d000b70c108e5c57f9b560f202aa18c863783aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/whiten.jl", "max_forks_repo_name": "UnofficialJuliaMirror/MultivariateStats.jl-6f286f6a-111f-5878-ab1e-185364afe411", "max_forks_repo_head_hexsha": "0d000b70c108e5c57f9b560f202aa18c863783aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4558823529, "max_line_length": 102, "alphanum_fraction": 0.6270594109, "num_tokens": 680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.870597270087091, "lm_q1q2_score": 0.800638273264569}} {"text": "# This file illustrates the simulation of MFSK signalling. The simulation is performed using \n# waveform AWGN channel. \n\nusing Plots \nusing FFTW \nusing LinearAlgebra \nusing Statistics \nusing DigitalCommunications\n\n# Settings \nk = 2 # Bits per symbol \nM = 2^3 # Constellation size \nT = 1. # Symbol duration \nf = 1 / T # Symbols per second \nfs = 10 # Sampling frequency \nts = 1 / fs # Sampling period \nt = 0 : ts : T - ts # Time vector for symbol duration \nl = length(t) # Number of samples per symbol\ng(t) = 0 ≤ t ≤ T ? sqrt(2 * Eg / T) : 0 # Modulation pulse: rectangular pulse \nEg = 1 # Modulation pulse energy: rectangular pulse \nnsymbols = Int(1e6) # Number of symbols \nΔf = 1 / T # 2 times the minimum frequency seperation for orthogonality \n\n# Define basis\nbasis = map(m -> (t -> g(t) * exp(1im * 2π * m * Δf * t)), 1 : M)\nbasisvals = map(base -> base.(t), basis) \nalphabet = map(m -> setindex!(zeros(M), 1, m), 1 : M)\nreferences = map(1 : M) do mi \n Ai = alphabet[mi] * sqrt(2 * Eg)\n sum(Ai .* basisvals)\nend \n\n# Simulate the system \nebno = collect(0 : 1 : 10)\nesno = ebno .+ 10 * log10(k) \nm = rand(1 : M, nsymbols)\ntx = map(m) do mi \n Ai = alphabet[mi] * sqrt(Eg) \n sum(Ai .* basisvals)\nend \nEs = mean(txi -> sum(abs.(txi).^2) * ts, tx)\nsymerr = zeros(length(esno)) \nfor i = 1 : length(symerr)\n # Generate noise \n σ = sqrt(Es * fs / 2 / (10^(esno[i] / 10))) \n n = [σ * (randn(l) + 1im * randn(l)) for i = 1 : length(tx)]\n # Corrupt transmitted signal \n rx = tx + n \n # Detect symbols \n mr = map(rx) do rxi \n argmax(map(reference -> real(rxi ⋅ reference), references))\n end\n # Calculate symbol \n ber = sum(m .!= mr) / length(m)\n symerr[i] = ber \nend \n\n# Plots\nplt = plot(title=\"$M-FSK\", xlabel=\"esno [dB]\", ylabel=\"Pe\") \nplot!(esno, berfsk.(esno, M), marker=:circle, yscale=:log10, label=\"theoretical\")\nplot!(esno, symerr, marker=:circle, yscale=:log10, label=\"montecarlo\")\n", "meta": {"hexsha": "a3d7f35f8cabfffd2efa5a9ff367c20663cd2e32", "size": 2299, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "example/waveform_simulations/waveformfsk.jl", "max_stars_repo_name": "zekeriyasari/DigitalCommunications.jl", "max_stars_repo_head_hexsha": "7ac2e6afe42aa996d94d211c1ea590ac3c0beb15", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-03T20:02:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-13T06:43:38.000Z", "max_issues_repo_path": "example/waveform_simulations/waveformfsk.jl", "max_issues_repo_name": "zekeriyasari/DigitalCommunications.jl", "max_issues_repo_head_hexsha": "7ac2e6afe42aa996d94d211c1ea590ac3c0beb15", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2020-11-26T21:56:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-03T19:54:59.000Z", "max_forks_repo_path": "example/waveform_simulations/waveformfsk.jl", "max_forks_repo_name": "zekeriyasari/DigitalCommunications.jl", "max_forks_repo_head_hexsha": "7ac2e6afe42aa996d94d211c1ea590ac3c0beb15", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-20T12:53:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T12:53:43.000Z", "avg_line_length": 37.0806451613, "max_line_length": 105, "alphanum_fraction": 0.5228360157, "num_tokens": 661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.8705972583359805, "lm_q1q2_score": 0.800638262457748}} {"text": "# # Basics\n#\n# ## Packages\n#\n# We load the following packages into our environment:\n\nusing OptimalTransport\nusing Distances\nusing Plots\nusing PythonOT: PythonOT\nusing Tulip\n\nusing LinearAlgebra\nusing Random\n\nRandom.seed!(1234)\n\nconst POT = PythonOT\n\n# ## Problem setup\n#\n# First, let us initialise two random probability measures $\\mu$ (source measure)\n# and $\\nu$ (target measure) in 1D:\n\nM = 200\nμ = fill(1 / M, M)\nμsupport = rand(M)\n\nN = 250\nν = fill(1 / N, N)\nνsupport = rand(N);\n\n# Now we compute the quadratic cost matrix $C_{ij} = \\| x_i - x_j \\|_2^2$:\n\nC = pairwise(SqEuclidean(), μsupport', νsupport'; dims=2);\n\n# ## Exact optimal transport\n#\n# The **earth mover's distance** is defined as the optimal value of the\n# Monge-Kantorovich problem\n# ```math\n# \\inf_{\\gamma \\in \\Pi(\\mu, \\nu)} \\langle \\gamma, C \\rangle =\n# \\inf_{\\gamma \\in \\Pi(\\mu, \\nu)} \\sum_{i, j} \\gamma_{ij} C_{ij},\n# ```\n# where $\\Pi(\\mu, \\nu)$ denotes the set of couplings of $\\mu$ and $\\nu$, i.e., the set of joint\n# distributions whose marginals are $\\mu$ and $\\nu$.\n# If $C$ is the quadratic cost matrix, the earth mover's distance is known as the square of\n# the **2-Wasserstein distance**.\n#\n# The function `emd` returns the optimal transport *plan* $\\gamma$\n\nγ = emd(μ, ν, C, Tulip.Optimizer());\n\n# whilst using `emd2` returns the optimal transport *cost*:\n\nemd2(μ, ν, C, Tulip.Optimizer())\n\n# ## Entropically regularised optimal transport\n#\n# We may add an entropy term to the Monge-Kantorovich problem to obtain the\n# **entropically regularised** optimal transport problem\n# ```math\n# \\inf_{\\gamma \\in \\Pi(\\mu, \\nu)} \\langle \\gamma, C \\rangle + \\epsilon \\Omega(\\gamma),\n# ```\n# where $\\Omega(\\gamma) = \\sum_{i, j} \\gamma_{ij} \\log(\\gamma_{ij})$ is the negative\n# entropy of the coupling $\\gamma$ and $\\epsilon$ controls the strength of the regularisation.\n#\n# This problem is *strictly convex* and admits a very efficient iterative scaling scheme for\n# its solution known as the [Sinkhorn algorithm](https://doi.org/10.1214/aoms/1177703591).\n#\n# We compute the optimal entropically regularised transport plan:\n\nε = 0.01\nγ = sinkhorn(μ, ν, C, ε);\n\n# We can check that one obtains the same result with the Python Optimal Transport (POT) package:\n\nγpot = POT.sinkhorn(μ, ν, C, ε)\nnorm(γ - γpot, Inf)\n\n# We can compute the optimal cost (a scalar) of the entropically regularized optimal\n# transport problem with `sinkhorn2`:\n\nsinkhorn2(μ, ν, C, ε)\n\n# ## Quadratically regularised optimal transport\n#\n# Instead of the common entropically regularised optimal transport problem, we can solve the\n# [quadratically regularised optimal transport problem](https://doi.org/10.1007/s00245-019-09614-w)\n# ```math\n# \\inf_{\\gamma \\in \\Pi(\\mu, \\nu)} \\langle \\gamma, C \\rangle + \\epsilon \\frac{\\| \\gamma \\|_F^2}{2}.\n# ```\n# One property of the quadratically regularised optimal transport problem is that the\n# resulting transport plan $\\gamma$ is *sparse*. We take advantage of this and represent it as\n# a sparse matrix.\n\nquadreg(μ, ν, C, ε; maxiter=100);\n\n# ## Stabilized Sinkhorn algorithm\n#\n# When $\\epsilon$ is very small, we can use a\n# [log-stabilised version of the Sinkhorn algorithm](https://doi.org/10.1137/16M1106018).\n\nε = 0.005\nγ = sinkhorn_stabilized(μ, ν, C, ε; maxiter=5_000);\n\n# Again we can check that the same result is obtained with the POT package:\n\nγ_pot = POT.sinkhorn(μ, ν, C, ε; method=\"sinkhorn_stabilized\", numItermax=5_000)\nnorm(γ - γ_pot, Inf)\n\n# ## Stabilized Sinkhorn algorithm with $\\epsilon$-scaling\n#\n# In addition to log-stabilisation, we can use [$\\epsilon$-scaling](https://doi.org/10.1137/16M1106018):\n\nγ = sinkhorn_stabilized_epsscaling(μ, ν, C, ε; maxiter=5_000);\n\n# The POT package yields the same result:\n\nγpot = POT.sinkhorn(μ, ν, C, ε; method=\"sinkhorn_epsilon_scaling\", numItermax=5000)\nnorm(γ - γpot, Inf)\n\n# ## Unbalanced optimal transport\n#\n# [Unbalanced optimal transport](https://doi.org/10.1090/mcom/3303) deals with general\n# positive measures which do not necessarily have the same total mass. For unbalanced\n# source and target marginals $\\mu$ and $\\nu$ and a cost matrix $C$, entropically\n# regularised unbalanced optimal transport solves\n# ```math\n# \\inf_{\\gamma \\geq 0} \\langle \\gamma, C \\rangle + \\epsilon \\Omega(\\gamma) + \\lambda_1 \\mathrm{KL}(\\gamma 1 | \\mu) + \\lambda_2 \\mathrm{KL}(\\gamma^{\\mathsf{T}} 1 | \\nu),\n# ```\n# where $\\epsilon$ controls the strength of the entropic regularisation, and $\\lambda_1$ and\n# $\\lambda_2$ control how strongly we enforce the marginal constraints.\n#\n# We construct two random measures, now with different total masses:\n\nM = 100\nμ = fill(1 / M, M)\nμsupport = rand(M)\n\nN = 200\nν = fill(1 / M, N)\nνsupport = rand(N);\n\n# We compute the quadratic cost matrix:\n\nC = pairwise(SqEuclidean(), μsupport', νsupport'; dims=2);\n\n# Now we solve the corresponding unbalanced, entropy-regularised transport problem with\n# $\\epsilon = 0.01$ and $\\lambda_1 = \\lambda_2 = 1$:\n\nε = 0.01\nλ = 1\nγ = sinkhorn_unbalanced(μ, ν, C, λ, λ, ε);\n\n# We check that the result agrees with POT:\n\nγpot = POT.sinkhorn_unbalanced(μ, ν, C, ε, λ)\nnorm(γ - γpot, Inf)\n\n# ## Plots\n#\n# ### Entropically regularised transport\n#\n# Let us construct source and target measures again:\n\nμsupport = νsupport = range(-2, 2; length=100)\nC = pairwise(SqEuclidean(), μsupport', νsupport'; dims=2)\nμ = normalize!(exp.(-μsupport .^ 2 ./ 0.5^2), 1)\nν = normalize!(νsupport .^ 2 .* exp.(-νsupport .^ 2 ./ 0.5^2), 1)\n\nplot(μsupport, μ; label=raw\"$\\mu$\", size=(600, 400))\nplot!(νsupport, ν; label=raw\"$\\nu$\")\n\n# Now we compute the entropically regularised transport plan:\n\nγ = sinkhorn(μ, ν, C, 0.01)\nheatmap(\n μsupport,\n νsupport,\n γ;\n title=\"Entropically regularised optimal transport\",\n size=(600, 600),\n)\n\n# ### Quadratically regularised transport\n#\n# Notice how the \"edges\" of the transport plan are sharper if we use quadratic regularisation\n# instead of entropic regularisation:\n\nγquad = quadreg(μ, ν, C, 5; maxiter=100);\nheatmap(\n μsupport,\n νsupport,\n γquad;\n title=\"Quadratically regularised optimal transport\",\n size=(600, 600),\n)\n\n# ### Sinkhorn barycenters\n#\n# For a collection of discrete probability measures $\\{\\mu_i\\}_{i=1}^N \\subset \\mathcal{P}$,\n# cost matrices $\\{C_i\\}_{i=1}^N$, and positive weights $\\{\\lambda_i\\}_{i=1}^N$ summing to $1$,\n# the entropically regularised **barycenter** in $\\mathcal{P}$ is the discrete probability\n# measure $\\mu$ that solves\n# ```math\n# \\inf_{\\mu \\in \\mathcal{P}} \\sum_{i = 1}^N \\lambda_i \\operatorname{OT}_{\\epsilon}(\\mu, \\mu_i)\n# ```\n# where $\\operatorname{OT}_\\epsilon(\\mu, \\mu_i)$ denotes the entropically regularised\n# optimal transport cost with marginals $\\mu$ and $\\mu_i$, cost matrix $C$, and entropic\n# regularisation parameter $\\epsilon$.\n#\n# We set up two measures and compute the weighted barycenters. We choose weights\n# $\\lambda_1 \\in \\{0.25, 0.5, 0.75\\}$.\n\nsupport = range(-1, 1; length=250)\nmu1 = normalize!(exp.(-(support .+ 0.5) .^ 2 ./ 0.1^2), 1)\nmu2 = normalize!(exp.(-(support .- 0.5) .^ 2 ./ 0.1^2), 1)\n\nplt = plot(; size=(800, 400), legend=:outertopright)\nplot!(plt, support, mu1; label=raw\"$\\mu_1$\")\nplot!(plt, support, mu2; label=raw\"$\\mu_2$\")\n\nmu = hcat(mu1, mu2)\nC = pairwise(SqEuclidean(), support'; dims=2)\nfor λ1 in (0.25, 0.5, 0.75)\n λ2 = 1 - λ1\n a = sinkhorn_barycenter(mu, C, 0.01, [λ1, λ2], SinkhornGibbs())\n plot!(plt, support, a; label=\"\\$\\\\mu \\\\quad (\\\\lambda_1 = $λ1)\\$\")\nend\nplt\n", "meta": {"hexsha": "c8055fd1f70f168105eea356698ed9f4d063f48e", "size": 7417, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/basic/script.jl", "max_stars_repo_name": "zsteve/OptimalTransport.jl", "max_stars_repo_head_hexsha": "ab9bc76a13c106f451ef58126cab07758f905f3f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 36, "max_stars_repo_stars_event_min_datetime": "2020-05-07T13:52:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-27T21:34:03.000Z", "max_issues_repo_path": "examples/basic/script.jl", "max_issues_repo_name": "zsteve/OptimalTransport.jl", "max_issues_repo_head_hexsha": "ab9bc76a13c106f451ef58126cab07758f905f3f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 49, "max_issues_repo_issues_event_min_datetime": "2020-05-15T16:48:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-18T18:38:46.000Z", "max_forks_repo_path": "examples/basic/script.jl", "max_forks_repo_name": "zsteve/OptimalTransport.jl", "max_forks_repo_head_hexsha": "ab9bc76a13c106f451ef58126cab07758f905f3f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-05-27T21:56:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-19T19:15:09.000Z", "avg_line_length": 31.9698275862, "max_line_length": 168, "alphanum_fraction": 0.6881488472, "num_tokens": 2357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425245706048, "lm_q2_score": 0.8705972566572503, "lm_q1q2_score": 0.8006382589965164}} {"text": "using SeisPlot, SeisAcoustic, FFTW, LinearAlgebra\n\n# velocity and density model\nnz = 101; nx = 301\nvel = 3000 * ones(nz, nx); # m/s\nvel[51:end,:] .= 3500; # m/s\nrho = 2000 * ones(nz, nx); # kg/m^3\n\n# top boundary condition\nfree_surface = false #(pml or free_surface)\n\n# grid size\nh = 10\n\n# organize these parameters into a structure\nfparams = FdParams(rho, vel, free_surface, h; data_format=Float64);\n\n# generate observations of one frequency slice by a point source\nisz = 5; isx = 151; dt = 0.001;\nsrc = Source(isz, isx, dt, fparams; amp=1/rho[isz,isx]/vel[isz,isx]^2*10^5);\n\n# total modelling length\ntmax = 2.0;\nnt = floor(Int64, tmax/dt) + 1\n\n# working frequency\ndf = 1.0 / (dt * nt);\nf_work = 20.0;\niw = floor(Int64, f_work/df) + 1;\nf_work = (iw-1) * df;\nomega = 2.0 * pi * f_work;\nwlet = zeros(nt)\ncopyto!(wlet, src.it_min, src.p)\nfwave = fft(wlet)\n\n# LU decomposition of Helmhotz operator\nH = get_helmholtz_LU(fparams, omega);\n\n# source vector\ns = zeros(Complex{Float64}, fparams.Nz*fparams.Nx)\ns[src.src2spt] = fwave[iw]\n\n# produce modelling true wave field\nu = zeros(Complex{Float64}, fparams.Nz * fparams.Nx);\nldiv!(u, H, s);\nSeisPlotTX(real(reshape(u, fparams.Nz, fparams.Nx)), wbox=9, hbox=3)\n\n# specify the monochromatic recordings\nirx = collect(1:2:nx);\nirz = 2 * ones(Int64, length(irx));\ndobs= MonochromaticRecordings(irz, irx, omega, fparams);\nsample_spt2rec!(dobs, u);\n\n\n# initial homogenous velocity model\nvel = 3000 * ones(nz, nx)\nfparams = FdParams(rho, vel, free_surface, h; data_format=Float64);\n\n# helmholtz operator of homogeneous model\nH = get_helmholtz_LU(fparams, omega);\n\n# source side wavefield\nu = zeros(Complex{Float64}, fparams.Nz * fparams.Nx);\nldiv!(u, H, s);\nSeisPlotTX(real(reshape(u, fparams.Nz, fparams.Nx)), wbox=9, hbox=3)\n\ndsyn = MonochromaticRecordings(irz, irx, omega, fparams);\nsample_spt2rec!(dsyn, u);\n\n# compute the residue\ndres = get_residue(dsyn, dobs);\ng = velocity_gradient(dres, u, H, fparams);\ng = reshape(g, fparams.nz, fparams.nx)\nSeisPlotTX(real(g), wbox=9, hbox=3)\n\n\n# compute the gradient numerically\nvel0 = 3000 * ones(nz, nx);\ndelta_m = 1e-7;\n\n# one model parameter's gradient\niz = 37; ix = 137;\n\n# positive velocity model partubation\nvel0[iz,ix] = vel0[iz,ix] + delta_m\n\n# model parameter\nfparams = FdParams(rho, vel0, free_surface, h; data_format=Float64);\nH = get_helmholtz_LU(fparams, omega);\n\n# source side wavefield\nu = zeros(Complex{Float64}, fparams.Nz * fparams.Nx);\nldiv!(u, H, s);\n\nd1 = MonochromaticRecordings(irz, irx, omega, fparams);\nsample_spt2rec!(d1, u);\nSeisPlotTX(real(reshape(u, fparams.Nz, fparams.Nx)), wbox=9, hbox=3)\n\n# compute the residue\ndres = get_residue(d1, dobs);\nJ_plus = 1/2.0 * (norm(dres.p))^2\n\n# negative velocity model partubation\nvel0[iz,ix] = vel0[iz,ix] - 2*delta_m\n\nfparams = FdParams(rho, vel0, free_surface, h; data_format=Float64);\nH = get_helmholtz_LU(fparams, omega);\n\n# source side wavefield\nu = zeros(Complex{Float64}, fparams.Nz * fparams.Nx);\nldiv!(u, H, s);\n\nd2 = MonochromaticRecordings(irz, irx, omega, fparams);\nsample_spt2rec!(d2, u);\n\n# compute the residue\ndres = get_residue(d2, dobs);\nJ_minus = 1/2.0 * (norm(dres.p))^2;\n\n# compute gradient numerically\ng_num = (J_plus - J_minus) / (2 * delta_m)\ng[iz,ix]\n(g[iz,ix] - g_num) / g_num\n", "meta": {"hexsha": "38d4472b02366c89f2e1fe9ebe938707c8582930", "size": 3265, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/simulation/frequency_gradient.jl", "max_stars_repo_name": "joaquin-17/SeisAcoustic.jl", "max_stars_repo_head_hexsha": "98d25280bcf88c471152b2ade977dec754494271", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2019-07-01T15:02:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T12:48:43.000Z", "max_issues_repo_path": "examples/simulation/frequency_gradient.jl", "max_issues_repo_name": "joaquin-17/SeisAcoustic.jl", "max_issues_repo_head_hexsha": "98d25280bcf88c471152b2ade977dec754494271", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2022-01-26T22:31:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-05T20:15:21.000Z", "max_forks_repo_path": "examples/simulation/frequency_gradient.jl", "max_forks_repo_name": "joaquin-17/SeisAcoustic.jl", "max_forks_repo_head_hexsha": "98d25280bcf88c471152b2ade977dec754494271", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2020-04-25T02:21:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T00:27:24.000Z", "avg_line_length": 26.3306451613, "max_line_length": 76, "alphanum_fraction": 0.6989280245, "num_tokens": 1183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768651485395, "lm_q2_score": 0.8479677602988602, "lm_q1q2_score": 0.800631541666006}} {"text": "#=\nA number chain is created by continuously adding the square of the digits in a number to form a new number until it has been seen before.\n\nFor example,\n\n44 → 32 → 13 → 10 → 1 → 1\n85 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89\n\nTherefore any chain that arrives at 1 or 89 will become stuck in an endless loop. What is most amazing is that EVERY starting number will eventually arrive at 1 or 89.\n\nHow many starting numbers below ten million will arrive at 89?\n=#\ncache = Int[]\nfunction digitchain(n)\n while true\n if n < length(cache)\n return cache[n]\n end\n n = map((x)->x^2, digits(n)) |> sum\n if n == 1\n return 1\n elseif n == 89\n return 89\n end\n end\nend\n\nfunction calc()\n count = 0\n for i in 1:10_000_000\n d = digitchain(i)\n push!(cache, d)\n if d == 89\n count = count + 1\n end\n end\n count\nend\n@time println(calc())\n", "meta": {"hexsha": "4f4a1867ded3902addd28b0f073cededb58ae5d9", "size": 875, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Solutions/p92.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/p92.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/p92.jl", "max_forks_repo_name": "daniel-beard/JuliaProjectEuler", "max_forks_repo_head_hexsha": "5c990f7dde3b1b09f23a11ab2c1f42b3e5337854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-22T18:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-22T18:22:41.000Z", "avg_line_length": 21.875, "max_line_length": 167, "alphanum_fraction": 0.6354285714, "num_tokens": 278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768541530198, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.8006315269007709}} {"text": "# Lotka-Volterra, np = 1\r\nid = :Sahlodin2011b\r\n\r\npL = [2.95]\r\npU = [3.05]\r\nSahlodin2011b_x0(p::Vector{T}) where T = T[1.2*one(T); 1.1*one(T)]\r\nfunction Sahlodin2011b_f!(du::Vector{T}, u::Vector{T}, p::Vector{T}, t) where T\r\n du[1] = p[1]*u[1]*(1.0 - u[2])\r\n du[2] = p[1]*u[2]*(u[1] - 1.0)\r\n return\r\nend\r\ntspan = (0.0, 2.0)\r\n\r\nprob = DBB.ODERelaxProb(Sahlodin2011b_f!, tspan, Sahlodin2011b_x0, pL, pU)\r\nurl = \"https://www.sciencedirect.com/science/article/abs/pii/S0168927411000316\"\r\nsource = \"Sahlodin2011\"\r\ndesc = \"Lotka-Volterra, np = 1\"\r\n", "meta": {"hexsha": "e9047ddf27c433122fb51d1112a74dc8889a242b", "size": 550, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/library/pODEs/Sahlodin2011b.jl", "max_stars_repo_name": "PSORLab/DynamicBounds.jl", "max_stars_repo_head_hexsha": "a7c258e3e4297442ad425c398705f3163e953331", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-15T17:57:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-15T17:57:30.000Z", "max_issues_repo_path": "src/library/pODEs/Sahlodin2011b.jl", "max_issues_repo_name": "PSORLab/DynamicBounds.jl", "max_issues_repo_head_hexsha": "a7c258e3e4297442ad425c398705f3163e953331", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2020-09-15T14:31:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T03:48:15.000Z", "max_forks_repo_path": "src/library/pODEs/Sahlodin2011b.jl", "max_forks_repo_name": "PSORLab/DynamicBounds.jl", "max_forks_repo_head_hexsha": "a7c258e3e4297442ad425c398705f3163e953331", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-05-15T17:57:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-15T17:57:36.000Z", "avg_line_length": 30.5555555556, "max_line_length": 80, "alphanum_fraction": 0.6181818182, "num_tokens": 255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.8933094145755219, "lm_q1q2_score": 0.800629789446502}} {"text": "\"\"\"\n autocovariance(v::Vector,h::Int; corrected::Bool=true)\n``\\\\hat{\\\\gamma}(h) =\\\\frac{1}{n}\\\\sum_{t=1}^{n-h}(v_{t+h}-\\\\bar{v})(v_t-\\\\bar{v})^*``\nCalculate the autocovariance of dataset `v` with a delay `h`. If `corrected` is `true`\n(the default) then the sum is scaled with `n-h`, whereas the sum\nis scaled with `n` if corrected is `false` where `n = length(v)`.\n\"\"\"\nfunction autocovariance(v::AbstractVector,h::Int; corrected::Bool=true, mean = mean(v))\n n = length(v)\n covsum = zero(mean)\n for i in 1:n-h\n @inbounds covsum += (v[i]-mean)*conj(v[i+h]-mean)\n end\n gamma = covsum/(n - Int(corrected))\n return gamma\nend\n\n@doc raw\"\"\"\n pseudo_cov(x, y; xmean = mean(x), ymean = mean(y), corrected = true)\nCompute the pseudo covariance between collections `x` and `y` returning a scalar:\n```math\n\\frac{1}{n}\\sum_{i=1}^{n} (x_i - \\bar{x})(y_{i} - \\bar{y})\n```\nOptionally,\nprecomputed means can be passed as keyword arguments. `pseudo_cov(x,y)` is functionally\nequivalent to `Statistics.cov(x, conj(y); corrected = false)` but it is found to be\nsignificantly faster and avoids allocations.\n\"\"\"\n@inline function pseudo_cov(x, y; xmean = mean(x), ymean = mean(y), corrected = true)\n n = length(x)\n @assert length(y) == n\n res = zero(promote_type(eltype(x), eltype(y))) / 1\n for i = 1:n\n @inbounds res += (x[i] - xmean) * (y[i] - ymean)\n end\n return res / (n - Int(corrected))\nend\n", "meta": {"hexsha": "d8a14f7eb941463fc86ec1dd61c622364415eb1c", "size": 1429, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/StatsTools/variances.jl", "max_stars_repo_name": "joachimbrand/Rimu.jl", "max_stars_repo_head_hexsha": "ee5237794c82e7dc83a9562768cf37c3979c7f55", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2020-08-03T05:13:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:05:01.000Z", "max_issues_repo_path": "src/StatsTools/variances.jl", "max_issues_repo_name": "joachimbrand/Rimu.jl", "max_issues_repo_head_hexsha": "ee5237794c82e7dc83a9562768cf37c3979c7f55", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 122, "max_issues_repo_issues_event_min_datetime": "2020-09-16T00:53:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T11:19:19.000Z", "max_forks_repo_path": "src/StatsTools/variances.jl", "max_forks_repo_name": "joachimbrand/Rimu.jl", "max_forks_repo_head_hexsha": "ee5237794c82e7dc83a9562768cf37c3979c7f55", "max_forks_repo_licenses": ["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.6052631579, "max_line_length": 87, "alphanum_fraction": 0.6347095871, "num_tokens": 456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299632771662, "lm_q2_score": 0.8652240895276223, "lm_q1q2_score": 0.8005312525801616}} {"text": "\nusing ModelingToolkit\n\n### Define a differential equation system\n\n@parameters t σ ρ β\n@variables x(t) y(t) z(t)\n@derivatives D'~t\n\neqs = [D(x) ~ σ*(y-x),\n D(y) ~ x*(ρ-z)-y,\n D(z) ~ x*y - β*z]\nde = ODESystem(eqs, t, [x,y,z], [σ,ρ,β])\node_f = ODEFunction(de)\n\n### Use in DifferentialEquations.jl\n\nusing OrdinaryDiffEq\nu₀ = ones(3)\ntspan = (0.0,100.0)\np = [10.0,28.0,10/3]\nprob = ODEProblem(ode_f,u₀,tspan,p)\nsol = solve(prob,Tsit5())\n\nusing Plots\nplot(sol,vars=(1,2,3))\n\n\ngenerate_function(de)[1]\n\n\ngenerate_function(de)[2]\n\n\njac = calculate_jacobian(de)\n\n\njac_expr = generate_jacobian(de)\n\n\nModelingToolkit.generate_factorized_W(de)[1]\n\n\n@variables x y z\n@parameters σ ρ β\n\n# Define a nonlinear system\neqs = [0 ~ σ*(y-x),\n 0 ~ x*(ρ-z)-y,\n 0 ~ x*y - β*z]\nns = NonlinearSystem(eqs, [x,y,z], [σ,ρ,β])\nnlsys_func = generate_function(ns)\n\n\nnl_f = @eval eval(nlsys_func[2])\n# Make a closure over the parameters for for NLsolve.jl\nf2 = (du,u) -> nl_f(du,u,(10.0,26.0,2.33))\n\nusing NLsolve\nnlsolve(f2,ones(3))\n\n\n@derivatives D3'''~t\n@derivatives D2''~t\n@variables u(t), x(t)\neqs = [D3(u) ~ 2(D2(u)) + D(u) + D(x) + 1\n D2(x) ~ D(x) + 2]\nde = ODESystem(eqs, t, [u,x], [])\nde1 = ode_order_lowering(de)\n\n\nde1.eqs\n\n\n@parameters t σ ρ β\n@variables x(t) y(t) z(t)\n@derivatives D'~t Dx'~x Dy'~y Dz'~z\neqs = [D(x) ~ σ*(y-x),\n D(y) ~ x*(ρ-z)-y,\n D(z) ~ x*y - β*z]\nJ = [Dx(eqs[1].rhs) Dy(eqs[1].rhs) Dz(eqs[1].rhs)\n Dx(eqs[2].rhs) Dy(eqs[2].rhs) Dz(eqs[2].rhs)\n Dx(eqs[3].rhs) Dy(eqs[3].rhs) Dz(eqs[3].rhs)]\n\n\nJ = expand_derivatives.(J)\n\n\nusing LinearAlgebra\nluJ = lu(J,Val(false))\n\n\nluJ.L\n\n\ninvJ = inv(luJ)\n\n\nfunction lorenz(du,u,p,t)\n du[1] = p[1]*(u[2]-u[1])\n du[2] = u[1]*(p[2]-u[3]) - u[2]\n du[3] = u[1]*u[2] - p[3]*u[3]\nend\n\n\nu = [x,y,z]\ndu = similar(u)\np = [σ,ρ,β]\nlorenz(du,u,p,t)\ndu\n\n\nJ = [Dx(du[1]) Dy(du[1]) Dz(du[1])\n Dx(du[2]) Dy(du[2]) Dz(du[2])\n Dx(du[3]) Dy(du[3]) Dz(du[3])]\nJ = expand_derivatives.(J)\n\n\nusing SparseArrays\nfunction SparseArrays.SparseMatrixCSC(M::Matrix{T}) where {T<:ModelingToolkit.Expression}\n idxs = findall(!iszero, M)\n I = [i[1] for i in idxs]\n J = [i[2] for i in idxs]\n V = [M[i] for i in idxs]\n return SparseArrays.sparse(I, J, V, size(M)...)\nend\nsJ = SparseMatrixCSC(J)\n\n\n@parameters σ(..)\neqs = [D(x) ~ σ(t-1)*(y-x),\n D(y) ~ x*(σ(t^2)-z)-y,\n D(z) ~ x*y - β*z]\n\n\n@derivatives Dₜ'~t\nDₜ(x*(σ(t^2)-z)-y)\nexpand_derivatives(Dₜ(x*(σ(t^2)-z)-y))\n\n\n_f(x) = 2x + x^2\n_f(x)\n\n\nf(x) = 2x + x^2\n@register f(x)\n\n\nf(x)\n\n\nfunction ModelingToolkit.derivative(::typeof(f), args::NTuple{1,Any}, ::Val{1})\n 2 + 2args[1]\nend\nexpand_derivatives(Dx(f(x)))\n\n\nusing SciMLTutorials\nSciMLTutorials.tutorial_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])\n\n", "meta": {"hexsha": "b610242a7f29ae098ebded1bf1d3b0374411629a", "size": 2732, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "script/ode_extras/01-ModelingToolkit.jl", "max_stars_repo_name": "SciML/SciMLTutorialsOutput", "max_stars_repo_head_hexsha": "f66779faa9eb1dc131c1adfe8099f26f09afc458", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-05-24T10:30:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-17T12:13:03.000Z", "max_issues_repo_path": "script/ode_extras/01-ModelingToolkit.jl", "max_issues_repo_name": "SciML/SciMLTutorialsOutput", "max_issues_repo_head_hexsha": "f66779faa9eb1dc131c1adfe8099f26f09afc458", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-07T21:39:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T03:48:31.000Z", "max_forks_repo_path": "script/ode_extras/01-ModelingToolkit.jl", "max_forks_repo_name": "SciML/SciMLTutorialsOutput", "max_forks_repo_head_hexsha": "f66779faa9eb1dc131c1adfe8099f26f09afc458", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-24T14:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-24T14:30:36.000Z", "avg_line_length": 16.9689440994, "max_line_length": 89, "alphanum_fraction": 0.5915080527, "num_tokens": 1134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465188527684, "lm_q2_score": 0.855851154320682, "lm_q1q2_score": 0.8005173978499734}} {"text": "\"\"\"\r\n lagrange(x, xd, yd)\r\nadalah fungsi yang digunakan untuk mencari nilai interpolasi pada titik/vektor `x`, jika\r\ndiketahui suatu himpunan pasangan terurut `(xd,yd)`.\r\n\r\n# Example\r\n```jl\r\njulia> xd = [1,2,3,5];\r\n\r\njulia> yd = [1.06 1.12 1.34 1.78];\r\n\r\njulia> lagrange(4,xd,yd)\r\n1.6000000000000003\r\n\r\njulia> lagrange([2.5,4,5.5],xd,yd)\r\n3-element Array{Float64,1}:\r\n 1.2175\r\n 1.6000000000000003\r\n 1.8025000000000002\r\n```\r\nreturn solusi hampiran interpolasi `y`.\r\n\"\"\"\r\nfunction lagrange(x, xd, yd)\r\n #% sedikit trik agar bisa menghitung nilai interpolasi pada banyak\r\n #% titik sekaligus. Intinya, tetap diproses satu titik demi titik.\r\n m=length(x);\r\n y=zeros(m)\r\n if m > 1\r\n for i=1:m\r\n # proses satu titik demi satu titik\r\n y[i]=lagrange(x[i], xd, yd);\r\n end\r\n return y\r\n end\r\n #% periksa jumlah titik dan tentukan derajat polinom\r\n ntitik = length(xd);\r\n n = ntitik-1; #% derajat maksimum, sesuai jumlah titik yang ada\r\n #% hitung L_{n,k}(x) untuk k=1:(n+1)\r\n Ln=ones(1,ntitik);\r\n for i=1:ntitik\r\n for j=1:ntitik\r\n if i!=j\r\n Ln[i] = Ln[i] * (x-xd[j])/(xd[i]-xd[j]);;\r\n end\r\n end\r\n end\r\n #% hitung P_{N}(x)\r\n y = 0;\r\n for i=1:ntitik\r\n y = y + yd[i]*Ln[i];\r\n end\r\n return y\r\nend\r\n", "meta": {"hexsha": "f5c9e8097ca886a5c66c6cd09f2d065829ccc30a", "size": 1250, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lagrange.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/lagrange.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/lagrange.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.1481481481, "max_line_length": 89, "alphanum_fraction": 0.6056, "num_tokens": 490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465170505205, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.8005173945880178}} {"text": "mutable struct Lattice\n n::Int64 # number of rows in basis matrix\n m::Int64 # number of columns in basis matrix\n basis::Array{Float64} # matrix whose columns form basis of lattice\n μ::Array{Float64} # lower triangular matrix of gram-schmidt coefficients\n r::Array{Float64} # squared norm of gram-schmidt basis vectors\n gs::Array{Float64} # columns are gram-schmidt basis vectors\n\n \"\"\"\n Lattice(basis)\n\n Construct a Lattice generated by the input basis matrix.\n \"\"\"\n Lattice(basis) = gram_schmidt(basis);\n Lattice(n, m, basis, μ, r, gs) = new(n, m, basis, μ, r, gs);\nend\n\n\"\"\"\n gram_schmidt(M)\n\nCompute Gram-Schmidt orthogonalization on columns of input matrix.\n\"\"\"\nfunction gram_schmidt(M::Array{<:Real})\n n = size(M, 1); # number of rows of matrix\n m = size(M, 2); # number of columns of matrix\n μ = zeros(Float64,m,m); # lower triangular matrix of gram-schmidt coefficients\n r = zeros(Float64,m); # squared norm of gram-schmidt basis vectors\n gs = zeros(Float64,n,m); # columns are gram-schmidt basis vectors\n for i = 1:m\n b = M[:,i];\n for j = 1:i-1 # compute gram-schmidt coefficients for j < i\n μ[i,j] = (transpose(b)*gs[:,j])/r[j];\n end\n for j = 1:i-1 # compute i-th gram-schmidt basis vector\n b -= μ[i,j]*gs[:,j];\n end\n gs[:,i] = b;\n r[i] = norm(b)^2; # squared norm of gram-schmidt vector\n μ[i,i] = (transpose(b)*M[:,i])/r[i];\n end\n return Lattice(n, m, M, μ, r, gs);\nend\n\n\"\"\"\n update_gram_schmidt!(L)\n\nUpdate Gram-Schmidt coefficients and vectors.\n\"\"\"\nfunction update_gram_schmidt!(L::Lattice)\n for i = 1:L.m\n b = L.basis[:,i];\n for j = 1:i-1 # compute gram-schmidt coefficients for j < i\n L.μ[i,j] = (transpose(b)*L.gs[:,j])/L.r[j];\n end\n for j = 1:i-1 # compute i-th gram-schmidt basis vector\n b -= L.μ[i,j]*L.gs[:,j];\n end\n L.gs[:,i] = b;\n L.r[i] = norm(b)^2; # squared norm of gram-schmidt vector\n L.μ[i,i] = (transpose(b)*L.basis[:,i])/L.r[i];\n end\n return L;\nend\n\n\n\"\"\"\n size_reduce(L)\n\nCompute size reduction of basis vectors of lattice, such that all Gram-Schmidt coefficients have absolute value at most 1/2. Modify the Gram-Schmidt coefficients of input lattice accordingly.\n\"\"\"\nfunction size_reduce!(L::Lattice)\n for i =2:L.m\n for j = i-1:-1:1\n L.basis[:,i] -= round(L.μ[i,j])*L.basis[:,j];\n for k = 1:j\n L.μ[i,k] -= round(L.μ[i,j])*L.μ[j,k];\n end\n end\n end\n return L\nend\n\n\"\"\"\n check_size_reduce(L, tol=1e-5)\n\nCheck whether basis vectors of input lattice are size-reduced.\n\"\"\"\nfunction check_size_reduce(L::Lattice, tol::Real=1e-5)\n for i = 1:L.m, j = 1:i-1\n if abs(L.μ[i,j]) > 0.5 + tol\n return false\n end\n end\n return true\nend\n\n\"\"\"\n lll!(L, δ=0.75)\n\nCompute LLL reduction of input lattice, with parameter δ such that ``0.25 < δ < 1``.\n\"\"\"\nfunction lll!(L::Lattice, δ::Real=0.75)\n k = 2;\n while k <= L.m\n size_reduce!(L);\n if norm(L.gs[:,k])^2 >= (δ - L.μ[k,k-1]^2)*norm(L.gs[:,k-1])^2\n k += 1;\n else\n b = copy(L.basis[:,k]);\n L.basis[:,k] = copy(L.basis[:,k-1]);\n L.basis[:,k-1] = b;\n update_gram_schmidt!(L);\n k = max(2, k-1);\n end\n end\n return L;\nend\n\n\n\"\"\"\n lll(M, δ=0.75)\n\nCompute LLL reduction of input matrix, with parameter δ such that ``0.25 < δ < 1``.\n\"\"\"\nfunction lll(M::Array{<:Real}, δ::Real=0.75)\n return lll(Lattice(M)).basis;\nend\n\n\"\"\"\n check_lll(L, δ=0.75)\n\nCheck whether input lattice has an LLL-reduced basis, with parameter δ such that ``0.25 < δ < 1``.\n\"\"\"\nfunction check_lll(L::Lattice, δ::Real=0.75)\n if !check_size_reduce(L)\n return false;\n end\n for i=1:L.m-1\n if L.r[i+1] < (δ-L.μ[i+1,i]^2)*L.r[i]\n return false;\n end\n end\n return true;\nend\n\n\"\"\"\n svp(M)\n\nCompute shortest vector in lattice generated by M, using Schnorr-Euchner enumeration.\n\"\"\"\nfunction svp(M::Array{<:Real})\n L = Lattice(M);\n x = zeros(Int64, L.m);\n x[L.m] = 1;\n A = norm(M[:,L.m])^2\n sol, length = enum_svp(L, x, L.m, A, 0.0);\n vect = sum([sol[j]*L.basis[:,j] for j=1:L.m]);\n return [vect, length, sol];\nend\n\n\n\"\"\"\n enum_svp(L, x, i, radius, l)\n\nEnumerate all lattice points in subtree at height i, where parent nodes are defined by x. Helper method for [`svp`](@ref).\n\"\"\"\nfunction enum_svp(L::Lattice, x::Array{<:Integer}, i::Integer, radius::Real, l::Real)\n sol = copy(x);\n c = -sum(Float64[x[j]*L.μ[j,i] for j=i+1:L.m]);\n interval = sqrt((radius-l)/L.r[i]); # interval of possibilities for x[i]\n k = floor(Int64, c); # stores value of x[i]\n Δk = 0; # used to do search in zig-zag path\n Δ²k = -1; # used to do search in zig-zag path\n lbound = floor(Int64, c - interval);\n ubound = ceil(Int64, c + interval);\n while k>= lbound & k <= ubound\n l_new = l + (k-c)^2*L.r[i];\n if l_new <= radius # possible new solution found\n if i == 1 & ~(l_new == 0) # leaf of enumeration tree\n # l_new is approximation of length of new solution. Do exact computation of length to avoid errors\n old_sol = sol[i];\n sol[i] = k;\n new_length = norm(sum([sol[j]*L.basis[:,j] for j=1:L.m]))^2;\n if radius > new_length # prune enumeration tree\n radius = new_length;\n else\n sol[i] = old_sol;\n end\n elseif i > 1 # solve subtree enumeration recursively\n old_sol = sol[i];\n sol[i] = k;\n subtree_sol, subtree_length = enum_svp(L, sol, i-1, radius, l_new);\n if subtree_length < radius\n sol[1:i-1] = subtree_sol[1:i-1];\n radius = subtree_length;\n else\n sol[i] = old_sol;\n end\n end\n end\n Δ²k = - Δ²k;\n Δk = Δ²k - Δk;\n k += Δk;\n end\n return [sol, radius];\nend\n\n", "meta": {"hexsha": "edc74261dc159c34ecd1e28e13d688938f79b071", "size": 6172, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lattice.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/Theta.jl-42bdb5c4-78fb-11e9-2233-215979c148c4", "max_stars_repo_head_hexsha": "a34991260be574b5d556a53a2acf59037d4459df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-09-17T23:51:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T17:20:32.000Z", "max_issues_repo_path": "src/lattice.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/Theta.jl-42bdb5c4-78fb-11e9-2233-215979c148c4", "max_issues_repo_head_hexsha": "a34991260be574b5d556a53a2acf59037d4459df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-03-04T16:32:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-05T08:18:16.000Z", "max_forks_repo_path": "src/lattice.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/Theta.jl-42bdb5c4-78fb-11e9-2233-215979c148c4", "max_forks_repo_head_hexsha": "a34991260be574b5d556a53a2acf59037d4459df", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:20:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T23:19:24.000Z", "avg_line_length": 29.6730769231, "max_line_length": 191, "alphanum_fraction": 0.5484445885, "num_tokens": 1882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465116437761, "lm_q2_score": 0.8558511414521923, "lm_q1q2_score": 0.8005173796436521}} {"text": "using Printf\n\nfunction sternbrocot(f::Function=(x) -> length(x) ≥ 20)::Vector{Int}\n rst = Int[1, 1]\n i = 3\n while !f(rst)\n append!(rst, Int[rst[i-1] + rst[i-2], rst[i-2]])\n i += 1\n end\n return rst\nend\n\nprintln(\"First 15 elements of Stern-Brocot series:\\n\", sternbrocot(x -> length(x) ≥ 15)[1:15], \"\\n\")\n\nfor i in (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100)\n occurr = findfirst(x -> x == i, sternbrocot(x -> i ∈ x))\n @printf(\"Index of first occurrence of %3i in the series: %4i\\n\", i, occurr)\nend\n\nprint(\"\\nAssertion: the greatest common divisor of all the two\\nconsecutive members of the series up to the 1000th member, is always one: \")\nsb = sternbrocot(x -> length(x) > 1000)\nif all(gcd(prev, this) == 1 for (prev, this) in zip(sb[1:1000], sb[2:1000]))\n println(\"Confirmed.\")\nelse\n println(\"Rejected.\")\nend\n", "meta": {"hexsha": "90eefafd6ec61e5e5c179c811a3728630efb7a7f", "size": 843, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/stern-brocot-sequence.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/stern-brocot-sequence.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/stern-brocot-sequence.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2222222222, "max_line_length": 140, "alphanum_fraction": 0.6120996441, "num_tokens": 301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465080392795, "lm_q2_score": 0.8558511414521923, "lm_q1q2_score": 0.8005173765587396}} {"text": "function hammingsequence(N)\n if N < 1\n throw(\"Hamming sequence exponent must be a positive integer\")\n end\n ham = N > 4000 ? Vector{BigInt}([1]) : Vector{Int}([1])\n base2, base3, base5 = (1, 1, 1)\n for i in 1:N-1\n x = min(2ham[base2], 3ham[base3], 5ham[base5])\n push!(ham, x)\n if 2ham[base2] <= x\n base2 += 1\n end\n if 3ham[base3] <= x\n base3 += 1\n end\n if 5ham[base5] <= x\n base5 += 1\n end\n end\n ham\nend\n\nprintln(hammingsequence(20))\nprintln(hammingsequence(1691)[end])\nprintln(hammingsequence(1000000)[end])\n", "meta": {"hexsha": "8cca38bc384f084e4444cb009fd91cf96dfcdb7e", "size": 625, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/hamming-numbers-1.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/hamming-numbers-1.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/hamming-numbers-1.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0384615385, "max_line_length": 69, "alphanum_fraction": 0.536, "num_tokens": 219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750373915658, "lm_q2_score": 0.8397339716830606, "lm_q1q2_score": 0.8004974332551377}} {"text": "#=\n Meeting Under the clock (Julian Simon 1994)\n \n \"\"\"\n Meeting Under the Clock (This problem is posed by Julian Simon(1994))\n\n Two persons agree to arrive at the two clock sometime between 1 pm and 2 pm \n and to stay for 20 minutes. What is the probability that they will be there\n at the same time?\n \"\"\"\n\n Summary Statistics\nparameters mean std naive_se mcse ess rhat ess_per_sec \n Symbol Float64 Float64 Float64 Float64 Float64 Float64 Float64 \n\n c1 30.1994 17.2942 0.1729 0.1723 9331.2798 0.9999 7267.3518\n c2 30.1059 17.3087 0.1731 0.1659 10124.1004 1.0000 7884.8134\n prob 0.5734 0.4946 0.0049 0.0054 9476.5095 1.0000 7380.4591\n\n According to the WebPPL model meeting_under_the_clock.wppl \n the exact probability is 0.5742602700373461.\n\n\n Cf ~/webppl/meeting_under_the_clock.wppl\n\n=#\nusing Turing, StatsPlots, Distributions\ninclude(\"jl_utils.jl\")\n\n@model function meeting_under_the_clock(w=20)\n c1 ~ DiscreteUniform(1,60)\n c2 ~ DiscreteUniform(1,60)\n # meeting within waiting time\n prob ~ Dirac(abs(c1-c2) <= w)\nend\n\nw = 20\nmodel = meeting_under_the_clock(w)\n\n# chns = sample(model, Prior(), 10_000)\n# chns = sample(model, MH(), 10_000)\n# chns = sample(model, PG(5), 1_000)\nchns = sample(model, SMC(), 10_000)\n# chns = sample(model, IS(), 10_000)\n\ndisplay(chns)\n# display(plot(chns))\n", "meta": {"hexsha": "9df16ac2e910dde60576fabdc48f11d2dc1c4f03", "size": 1478, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/turing/meeting_under_the_clock.jl", "max_stars_repo_name": "tias/hakank", "max_stars_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 279, "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:34:03.000Z", "max_issues_repo_path": "julia/turing/meeting_under_the_clock.jl", "max_issues_repo_name": "tias/hakank", "max_issues_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-10-05T15:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T12:06:52.000Z", "max_forks_repo_path": "julia/turing/meeting_under_the_clock.jl", "max_forks_repo_name": "tias/hakank", "max_forks_repo_head_hexsha": "87b7f180c9393afce440864eb9e5fb119bdec1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 83, "max_forks_repo_forks_event_min_datetime": "2015-01-20T03:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:53:06.000Z", "avg_line_length": 30.7916666667, "max_line_length": 91, "alphanum_fraction": 0.6454668471, "num_tokens": 492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.899121388082479, "lm_q2_score": 0.8902942195727173, "lm_q1q2_score": 0.8004825745040289}} {"text": "\"\"\"\n `RBF_gauss(R;A=1.0,sigma=0.2,deriv=0)`\n\nKernel function for Gaussian RBF Interpolation. Returns the magnitude of evaluated\nfunction.\n\nThe optional argument `deriv` is for the order of the derivative desired, meaning\n0 for base, 1 for first derivative (gradient) and 2 for second derivative (Laplacian).\n\n# ARGUMENTS\n* `R::Float64` : Magnitude of radius vector -> R = |X_j - X_i|\n* `A=1.0` : Normalization value\n* `sigma=0.2` : Gaussian spreading\n* `deriv=0` : Order of desired derivative\n\n# OUTPUTS\n* `res` : Calculated magnitude\n\"\"\"\nfunction RBF_gauss(R::Float64;\n A=1.0,sigma=0.2,deriv=0)\n\n if deriv == 0\n # const1 = 1/(2*pi)^(3/2)\n # res = const1*exp(-R^2/2)\n\n res = SVPM.zeta_gauserf(R)\n #res = A*exp(-(R^2)/(2*sigma^2))\n elseif deriv == 1\n res = -((A*R)/(sigma^2))*exp(-(R^2)/(2*sigma^2))\n elseif deriv == 2\n res = ((A/sigma)^2)*((R/sigma)^2 - 3)*exp(-(R^2)/(2*sigma^2))\n end\n\n return res\nend\n", "meta": {"hexsha": "121f51a0ed86051088a5cc83185a32e58847810c", "size": 997, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/VSB_RBF.jl", "max_stars_repo_name": "DamynChipman/VSB.jl", "max_stars_repo_head_hexsha": "9d9ade28383134e1b20953dd85ab0dc8c6188eb8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-05T13:42:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-05T13:42:00.000Z", "max_issues_repo_path": "src/VSB_RBF.jl", "max_issues_repo_name": "DamynChipman/VSB.jl", "max_issues_repo_head_hexsha": "9d9ade28383134e1b20953dd85ab0dc8c6188eb8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-20T02:40:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-20T02:40:36.000Z", "max_forks_repo_path": "src/VSB_RBF.jl", "max_forks_repo_name": "DamynChipman/VSB.jl", "max_forks_repo_head_hexsha": "9d9ade28383134e1b20953dd85ab0dc8c6188eb8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6944444444, "max_line_length": 86, "alphanum_fraction": 0.5947843531, "num_tokens": 342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541643004809, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.8003788953040009}} {"text": "#===============================================================================\n\nThe radical of n, rad(n), is the product of the distinct prime factors of n. For\nexample, 504 = 2^3 × 3^2 × 7, so rad(504) = 2 × 3 × 7 = 42.\n\nIf we calculate rad(n) for 1 ≤ n ≤ 10, then sort them on rad(n), and sorting on\nn if the radical values are equal, we get:\n\n Unsorted | Sorted |\n n rad(n) | n rad(n) | k\n ---------+-----------+---\n 1 1 | 1 1 | 1\n 2 2 | 2 2 | 2\n 3 3 | 4 2 | 3\n 4 2 | 8 2 | 4\n 5 5 | 3 3 | 5\n 6 6 | 9 3 | 6\n 7 7 | 5 5 | 7\n 8 2 | 6 6 | 8\n 9 3 | 7 7 | 9\n10 10 | 10 10 | 10\n\nLet E(k) be the kth element in the sorted n column; for example, E(4) = 8 and\nE(6) = 9.\n\nIf rad(n) is sorted for 1 ≤ n ≤ 100000, find E(10000).\n\n===============================================================================#\n\nusing Primes\nusing Base.Test\n\n\nfunction compute_table(limit)\n res = Tuple{Int,Int}[]\n for n in 1:limit\n push!(res, (prod(keys(factor(n))), n))\n end\n\n sort!(res)\n map(pair -> pair[2], res)\nend\n\ntest_table = compute_table(10)\n\n@test test_table[4] == 8\n@test test_table[6] == 9\n\nactual_table = compute_table(100_000)\n\nprintln(\"Euler 124: $(actual_table[10_000])\")\n", "meta": {"hexsha": "f3b8bee3bb1b2f21aa2c1d0b0c5cb687f515e23b", "size": 1307, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "0124.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": "0124.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": "0124.jl", "max_forks_repo_name": "dpieroux/euler", "max_forks_repo_head_hexsha": "d9e7d39d93e588402cc13efcf2eddb0371540160", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1346153846, "max_line_length": 80, "alphanum_fraction": 0.4552410099, "num_tokens": 489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541561135442, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.8003788847666806}} {"text": "using ModelingToolkit, NonlinearSolve\n\n@parameters t\n@variables u1(t) u2(t) u3(t) u4(t) u5(t)\n\neqs = [\n 0 ~ u1 - sin(u5),\n 0 ~ u2 - cos(u1),\n 0 ~ u3 - hypot(u1, u2),\n 0 ~ u4 - hypot(u2, u3),\n 0 ~ u5 - hypot(u4, u1)\n]\n\nsys = NonlinearSystem(eqs, [u1, u2, u3, u4, u5], [])\n\nsimple_sys = structural_simplify(sys)\n\nequations(simple_sys)\n\nprob = NonlinearProblem(simple_sys, [u5=>0.0])\nsol = solve(prob, NewtonRaphson())\n\nsol[u5]\nsol[u1]\n\n\n\n# stochastic differential equations\nusing ModelingToolkit, DifferentialEquations\n\n@parameters t σ ρ β\n@variables x(t) y(t) z(t)\nD = Differential(t)\n\neqs = [\n D(x) ~ σ*(y-x),\n D(y) ~ x*(ρ-z)-y,\n D(z) ~ x*y - β*z\n ]\n\nnoise_eqs = [0.1*x, 0.1*y, 0.1*z]\n\nde = SDESystem(eqs, noise_eqs, t, [x, y, z], [σ, ρ, β])\n\nu0map = [x=> 1.0, y=> 0.0, z=>0.0]\nparammap = [σ => 10.0, ρ => 28.0, β => 8/3]\n\nprob = SDEProblem(de, u0map, (0.0, 100.0), parammap)\n\nsol = solve(prob)\nplot(sol, vars=(x,y,z))\n\n\n# ------------ optimization problem ----------------------\nusing ModelingToolkit, GalacticOptim, Optim\n\n@variables x y\n@parameters a b\nloss = (a-x)^2 + b * (y -x^2)^2\n\nsys = OptimizationSystem(loss, [x,y], [a,b])\n\n# initial guess\nu0 = [x=>1.0, y=>2.0]\np = [a => 6.0, b=> 7.0]\n\nprob = OptimizationProblem(sys, u0, grad=true, hess=true)\nsol = solve(prob) # doesn't work yet\n\n\n# ------------ dsl demo via Catalyst ---------------------\nusing DifferentialEquations, Catalyst, Latexify, ModelingToolkit, Plots\n\nrepressilator = @reaction_network begin\n hillr(P₃,α,K,n), ∅ --> m₁\n hillr(P₁,α,K,n), ∅ --> m₂\n hillr(P₂,α,K,n), ∅ --> m₃\n (δ,γ), m₁ ↔ ∅\n (δ,γ), m₂ ↔ ∅\n (δ,γ), m₃ ↔ ∅\n β, m₁ --> m₁ + P₁\n β, m₂ --> m₂ + P₂\n β, m₃ --> m₃ + P₃\n μ, P₁ --> ∅\n μ, P₂ --> ∅\n μ, P₃ --> ∅\nend α K n δ γ β μ;\n\n", "meta": {"hexsha": "785d5b7fcf7f4589d7090a9a241a9e42823845c0", "size": 1807, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "SimulatingBigModelsInJuliaWithModelingToolkit/tutorial_rackauckas2.jl", "max_stars_repo_name": "john-waczak/JuliaCon2021", "max_stars_repo_head_hexsha": "48979656e94af4e5707094fc836ed76971593eac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SimulatingBigModelsInJuliaWithModelingToolkit/tutorial_rackauckas2.jl", "max_issues_repo_name": "john-waczak/JuliaCon2021", "max_issues_repo_head_hexsha": "48979656e94af4e5707094fc836ed76971593eac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SimulatingBigModelsInJuliaWithModelingToolkit/tutorial_rackauckas2.jl", "max_forks_repo_name": "john-waczak/JuliaCon2021", "max_forks_repo_head_hexsha": "48979656e94af4e5707094fc836ed76971593eac", "max_forks_repo_licenses": ["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.3033707865, "max_line_length": 71, "alphanum_fraction": 0.5373547316, "num_tokens": 719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122696813394, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.8003199313081467}} {"text": "using Plots\ngr()\n\n################################\n### Algoritmo Newton-Raphson ### \n################################\n\nfunction NewtonRaphson(f, fd, x; tol = 1e-8, max_iter=1000, max_tempo=10.0)\n fx = f(x) # primeira iteracao\n i = 0 # contador de iteracoes\n t0 = time() # tempo de execucao\n t1 = time() - t0\n estado = \"Desconhecido\" # estado do algoritmo\n\n # define erro absoluto e erro relativo e calcula o erro\n atol = rtol = tol \n erro = atol + rtol*abs(fx)\n\n # regras de parada\n rp1 = (abs(fx) ≤ erro)\n rp2 = (t1 ≥ max_tempo || i ≥ max_iter)\n\n while !(rp1 || rp2)\n fdx = fd(x)\n \n x = x - fx/fdx\n if abs(fdx) ≤ erro\n estado = \"Falha na convergência. Derivada nula encontrada.\"\n break\n end\n fx = f(x)\n\n i += 1\n t1 = time() - t0\n\n rp1 = (abs(fx) ≤ erro)\n rp2 = (t1 ≥ max_tempo || i ≥ max_iter)\n end\n\n if rp1\n estado = \"Convergência Obtida.\"\n elseif rp2\n i ≥ max_iter ? estado = \"Falha na convergência. O Algoritmo atingiu iteração limite\" : estado = \"Falha na convergência. O algoritmo atingiu tempo limite\"\n end\n println(\"\\n\",estado,\"\\n\")\n println(\"Raiz em $x com $i iterações.\\n\")\n return x, fx, estado\nend\n\nPlots.plot(x -> x^2 - 2, -5, 5, leg=false)\nf(x) = x^2 - 2\nfd(x) = 2x\nNewtonRaphson(f, fd, 500.0, tol = 1e-20)\nNewtonRaphson(f, fd, -100.0)\n\nf(x) = x * exp(x) - 1\nfd(x) = exp(x) + x * exp(x)\nPlots.plot(f, -2, 5, leg=false)\nNewtonRaphson(f, fd, 0.0)\n\nf(x) = x^2 + 3\nfd(x) = 2x\nPlots.plot(f, -2, 2, leg=false)\nNewtonRaphson(f, fd, 10)\n\n\n##################################################################\n### Newton-Raphson aproximando derivada com diferenças finitas ###\n##################################################################\n\nfunction newton_fin_dif(f, x; h = 0.1, tol = 1e-10, N = 1000)\n c = 0\n for i = 1:N\n c += 1\n xnew = x - (2*h*f(x)) / (f(x+h) - f(x-h))\n if abs(xnew - x) <= tol\n print(\"root at $x with $(c) iterations.\\nError: $(round(xnew-x, sigdigits=5))\\n\")\n return xnew, c\n end\n x = xnew\n end\n print(\"WARNING: Function did NOT converge.\\nRoot at $x with $(c) iterations.\\nError: $(round(xnew-x, sigdigits=5))\\n\")\n return xnew, c\nend\n\nf(x) = 2x^2 - 5x\nplot(f, -2, 5, leg=false)\nnewton_fin_dif(f, 20)\n\nnewton_fin_dif(x -> 2x^2 - 5x, 100);\nnewton_fin_dif(x -> 2x^2 - 5x, -0.5)\nnewton_fin_dif(x -> 2x^2 - 5x, -500);\n\nplot(x -> x^3 - 2x - 5, -2, 5, leg=false)\nnewton_fin_dif(x -> x^3 - 2x - 5, 5; h = 0.01, tol=0.0001);\n\n\n##############################################\n### Newton-Raphson Com multiplas dimensões ###\n##############################################\n\nfunction newton_mult_dim(f, G, x; alpha = 0.1, tol = 1e-10, N = 1000)\n c = 0\n for i = 1:N\n c += 1\n xnew = x - alpha*(f(x)./G(x))\n if abs(f(xnew)) <= tol\n print(\"roots at $xnew with $(c) iterations.\\nError: $(round.(xnew-x, sigdigits=5))\\n\")\n return xnew, c\n end\n x = xnew\n end\n print(\"WARNING: Function did NOT converge.\\nRoots at $x with $(c) iterations.\\nError: $(round.(xnew-x, sigdigits=5))\\n\")\n return xnew, c\nend\n\na1 = range(-20,20,step=0.1)\na2 = range(-20,20,step=0.1)\nzplot(x,y) = x^2 + y^2 - 5^2\nPlots.surface(a1, a2, zplot)\n\nz(x) = x[1]^2 + x[2]^2 - 5^2\nG(x) = [2x[1], 2x[2]]\nx0 = [3.0; 5.0]\nnewton_mult_dim(z, G, x0)\n\n\n#############################################\n### Newton-Raphson usando pacote Roots.jl ###\n#############################################\n\nusing Roots\nf(x) = x^3 - 2x - 5\nfp(x) = 3x^2 - 2\nnewton_fin_dif(f, 2);\nNewtonRaphson(f, fp, 10)\nx = Roots.newton(f, fp, 2, verbose=true)\nx = find_zero((f, fp), 2, Roots.Newton(), verbose=true)\nx, f(x)", "meta": {"hexsha": "63b6c5e6c1655c5d13ee68cb615ba20b5fbb5fdd", "size": 3828, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "newton_raphson.jl", "max_stars_repo_name": "AugustoCL/newton_raphson_from_scratch", "max_stars_repo_head_hexsha": "b55788d2cef2189184b8e68a80937ba67706f422", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "newton_raphson.jl", "max_issues_repo_name": "AugustoCL/newton_raphson_from_scratch", "max_issues_repo_head_hexsha": "b55788d2cef2189184b8e68a80937ba67706f422", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "newton_raphson.jl", "max_forks_repo_name": "AugustoCL/newton_raphson_from_scratch", "max_forks_repo_head_hexsha": "b55788d2cef2189184b8e68a80937ba67706f422", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5395683453, "max_line_length": 161, "alphanum_fraction": 0.4934691745, "num_tokens": 1367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391600697869, "lm_q2_score": 0.8670357494949105, "lm_q1q2_score": 0.8003079499642604}} {"text": "function chebyshev_polynomial_derivative(order::S,x::T) where {T<:AbstractFloat,S<:Integer}\n\n polynomial = ones(T,1,order+1)\n poly_deriv = zeros(T,1,order+1)\n\n for i = 2:order+1\n if i == 2\n polynomial[i] = x\n poly_deriv[i] = 1.0\n else\n polynomial[i] = 2*x*polynomial[i-1]-polynomial[i-2]\n poly_deriv[i] = ((i-1)*polynomial[i-1]-(i-1)*x*polynomial[i])/(1-x^2)\n end\n end\n\n return poly_deriv\n\nend\n\nfunction chebyshev_polynomial_derivative(order::S,x::Array{T,1}) where {T<:AbstractFloat,S<:Integer}\n\n polynomial = ones(T,length(x),order+1)\n poly_deriv = zeros(T,length(x),order+1)\n\n for i = 1:length(x)\n poly_deriv[i,:] = chebyshev_polynomial_derivative(order,x[i])\n end\n\n#=\n\n for i = 2:order+1\n\tfor j = 1:length(x)\n if i == 2\n polynomial[j,i] = x[j]\n poly_deriv[j,i] = 1.0\n else\n polynomial[j,i] = 2*x[j]*polynomial[j,i-1]-polynomial[j,i-2]\n poly_deriv[j,i] = ((i-1)*polynomial[j,i-1]-(i-1)*x[j]*polynomial[j,i])/(1-x[j]^2)\n end\n end\n end\n\n=#\n\n return poly_deriv\n\nend\n", "meta": {"hexsha": "a05cf1839a2b6fe02afc1ef4343968d4d16583a6", "size": 1056, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/superfluous/chebyshev_polynomial_derivative.jl", "max_stars_repo_name": "RJDennis/ChebyshevApprox.jl", "max_stars_repo_head_hexsha": "f3052ad7b6eab8bcec2930b111b52f92d5b00586", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2016-12-05T19:52:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T03:08:35.000Z", "max_issues_repo_path": "src/superfluous/chebyshev_polynomial_derivative.jl", "max_issues_repo_name": "RJDennis/ChebyshevApprox", "max_issues_repo_head_hexsha": "9b43654b3b7d00210ca2191b1173c79c7333dad3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2016-08-05T15:45:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-20T19:08:32.000Z", "max_forks_repo_path": "src/superfluous/chebyshev_polynomial_derivative.jl", "max_forks_repo_name": "RJDennis/ChebyshevApprox", "max_forks_repo_head_hexsha": "9b43654b3b7d00210ca2191b1173c79c7333dad3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-08-23T23:50:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T12:21:55.000Z", "avg_line_length": 22.0, "max_line_length": 100, "alphanum_fraction": 0.6089015152, "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107878954105, "lm_q2_score": 0.8539127473751341, "lm_q1q2_score": 0.800296238761384}} {"text": "module CalcDist\n\nimport StatsFuns: normpdf, normcdf, norminvcdf,\n tdistpdf, tdistcdf, tdistinvcdf,\n chisqpdf, chisqcdf, chisqinvcdf,\n fdistpdf, fdistcdf, fdistinvcdf\n\nexport normalpdf, normalcdf, invNorm,\n tpdf, tcdf, invT,\n X2pdf, X2cdf, invX2,\n Fpdf, Fcdf, invF,\n binompdf, binomcdf,\n poissonpdf, poissoncdf,\n geometpdf, geometcdf,\n nCr, nPr\n\n##\n# Continuous\n##\n\n\"\"\"\n normalpdf(x, μ = 0, σ = 1) \\n\n x: value\n μ: mean\n σ: standard deviation\n probability density function (Normal)\n\"\"\"\nfunction normalpdf(x, μ = 0, σ = 1)\n return normpdf(μ, σ, x)\nend\n\n\"\"\"\n normalcdf(lower, upper, μ = 0, σ = 1) \\n\n lower: lower boundary\n upper: upper boundary\n μ: mean\n σ: standard deviation\n cumulative distribution function (Normal)\n\"\"\"\nfunction normalcdf(lower, upper, μ = 0, σ = 1)\n return normcdf(μ, σ, upper) - normcdf(μ, σ, lower)\nend\n\n\"\"\"\n invNorm(area, μ = 0, σ = 1) \\n\n area: probability area\n μ: mean\n σ: standard deviation\n inverse cumulative distribution function (Normal)\n\"\"\"\nfunction invNorm(area, μ = 0, σ = 1)\n return norminvcdf(μ, σ, area)\nend\n\n\"\"\"\n tpdf(x, ν) \\n\n x: value\n ν: degrees of freedom\n probability density function (Student's t)\n\"\"\"\nfunction tpdf(x, ν)\n return tdistpdf(ν, x)\nend\n\n\"\"\"\n tcdf(lower, upper, ν) \\n\n lower: lower boundary\n upper: upper boundary\n ν: degrees of freedom\n cumulative distribution function (Student's t)\n\"\"\"\nfunction tcdf(lower, upper, ν)\n return tdistcdf(ν, upper) - tdistcdf(ν, lower)\nend\n\n\"\"\"\n invT(area, ν) \\n\n area: probability area\n ν: degrees of freedom\n inverse cumulative distribution function (Student's t)\n\"\"\"\nfunction invT(area, ν)\n return tdistinvcdf(ν, area)\nend\n\n\"\"\"\n X2pdf(x, ν) \\n\n x: value\n ν: degrees of freedom\n probability density function (Chi-squared)\n\"\"\"\nfunction X2pdf(x, ν)\n return chisqpdf(ν, x)\nend\n\n\"\"\"\n X2cdf(lower, upper, ν) \\n\n lower: lower boundary\n upper: upper boundary\n ν: degrees of freedom\n cumulative distribution function (Chi-squared)\n\"\"\"\nfunction X2cdf(lower, upper, ν)\n return chisqcdf(ν, upper) - chisqcdf(ν, lower)\nend\n\n\"\"\"\n invX2(area, ν) \\n\n area: probability area\n ν: degrees of freedom\n inverse cumulative distribution function (Chi-squared)\n\"\"\"\nfunction invX2(area, ν)\n return chisqinvcdf(ν, area)\nend\n\n\"\"\"\n Fpdf(x, nν, dν) \\n\n x: value\n nν: numerator degrees of freedom\n dν: denominator degrees of freedom\n probability density function (F)\n\"\"\"\nfunction Fpdf(x, nν, dν)\n return fdistpdf(nν, dν, x)\nend\n\n\"\"\"\n Fcdf(lower, upper, nν, dν) \\n\n lower: lower boundary\n upper: upper boundary\n nν: numerator degrees of freedom\n dν: denominator degrees of freedom\n cumulative distribution function (F)\n\"\"\"\nfunction Fcdf(lower, upper, nν, dν)\n return fdistcdf(nν, dν, upper) - fdistcdf(nν, dν, lower)\nend\n\n\"\"\"\n invF(area, nν, dν) \\n\n area: probability area\n nν: numerator degrees of freedom\n dν: denominator degrees of freedom\n inverse cumulative distribution function (F)\n\"\"\"\nfunction invF(area, nν, dν)\n return fdistinvcdf(nν, dν, area)\nend\n\n##\n# Discrete\n##\n\n\"\"\"\n binompdf(n, p, x = nothing) \\n\n n: trials\n p: probability of success\n x: value\n probability mass function (Binomial)\n\"\"\"\nfunction binompdf(n, p, x = nothing)\n if n ≤ 0\n throw(DomainError(n, \"\\t[n > 0] must be true.\"))\n end\n if p < 0 || p > 1\n throw(DomainError(p, \"\\t[0 ≤ p ≤ 1] must be true.\"))\n end\n\n if isnothing(x)\n x = range(0, stop=n)\n end\n\n probs = Vector{Real}()\n\n for i in x\n push!(probs, binomial(n, i) * p^i * (1-p)^(n-i))\n end\n\n return probs\nend\n\n\"\"\"\n binomcdf(n, p, x = nothing) \\n\n n: trials\n p: probability of success\n x: value\n cumulative distribution function (Binomial)\n\"\"\"\nfunction binomcdf(n, p, x = nothing)\n if n ≤ 0\n throw(DomainError(n, \"\\t[n > 0] must be true.\"))\n end\n if p < 0 || p > 1\n throw(DomainError(p, \"\\t[0 ≤ p ≤ 1] must be true.\"))\n end\n\n if isnothing(x)\n x = range(0, stop=n)\n end\n\n probs = Vector{Real}()\n\n for i in x\n push!(probs, sum([ binomial(n, i) * p^i * (1-p)^(n-i) for i in 0:i ]))\n end\n\n return probs\nend\n\n\"\"\"\n poissonpdf(λ, x) \\n\n λ: mean, variance\n x: value\n probability mass function (Poisson)\n\"\"\"\nfunction poissonpdf(λ, x)\n if λ ≤ 0\n throw(DomainError(λ, \"\\t[λ > 0] must be true.\"))\n end\n \n probs = Vector{Real}()\n\n for i in x\n push!(probs, ℯ^(-λ) * (λ^i / factorial(i)))\n end\n \n return probs\nend\n\n\"\"\"\n poissoncdf(λ, x) \\n\n λ: mean, variance\n x: value\n cumulative distribution function (Poisson)\n\"\"\"\nfunction poissoncdf(λ, x)\n if λ ≤ 0\n throw(DomainError(λ, \"\\t[λ > 0] must be true.\"))\n end\n \n probs = Vector{Real}()\n\n for i in x\n push!(probs, ℯ^(-λ) * sum([ λ^i / factorial(i) for i in 0:i ]))\n end\n\n return probs\nend\n\n\"\"\"\n geometpdf(p, x) \\n\n p: probability of success\n x: trial on which 1st success occurs\n probability density function (Geometric)\n\"\"\"\nfunction geometpdf(p, x)\n if p < 0 || p > 1\n throw(DomainError(p, \"\\t[0 ≤ p ≤ 1] must be true.\"))\n end\n\n probs = Vector{Real}()\n\n for i in x\n push!(probs, p * (1-p)^(i-1))\n end\n\n return probs\nend\n\n\"\"\"\n geometcdf(p, x) \\n\n p: probability of success\n x: trial on which 1st success occurs\n cumulative distribution function (Geometric)\n\"\"\"\nfunction geometcdf(p, x)\n if p < 0 || p > 1\n throw(DomainError(p, \"\\t[0 ≤ p ≤ 1] must be true.\"))\n end\n\n probs = Vector{Real}()\n\n for i in x\n push!(probs, 1 - (1-p)^i)\n end\n\n return probs\nend\n\n##\n# Counting\n##\n\n\"\"\"\n nCr(n, r) \\n\n return number of combinations of n items taken r at a time. n and r must be\n non-negative. both n and r can be vectors.\n\"\"\"\nfunction nCr(n, r)\n if n < 0\n throw(DomainError(n, \"\\t[n ≥ 0] must be true.\"))\n end\n \n combs = Vector{Real}()\n\n for i in r\n if i < 0\n throw(DomainError(i, \"\\t[r ≥ 0] must be true.\"))\n end\n push!(combs, factorial(n) / ( factorial(i) * factorial(n-i) ))\n end\n\n return combs\nend\n\nfunction nCr(n::Vector{Int}, r)\n if r < 0\n throw(DomainError(r, \"\\t[r ≥ 0] must be true.\"))\n end\n \n combs = Vector{Real}()\n\n for i in n\n if i < 0\n throw(DomainError(i, \"\\t[n ≥ 0] must be true.\"))\n end\n push!(combs, factorial(i) / ( factorial(r) * factorial(i-r) ))\n end\n\n return combs\nend\n\n\"\"\"\n nPr(n, r)\n return number of permutations of n items taken r at a time. n and r must be\n non-negative. both n and r can be vectors.\n\"\"\"\nfunction nPr(n, r)\n if n < 0\n throw(DomainError(n, \"\\t[n ≥ 0] must be true.\"))\n end\n \n perms = Vector{Real}()\n\n for i in r\n if i < 0\n throw(DomainError(i, \"\\t[r ≥ 0] must be true.\"))\n end\n push!(perms, factorial(n) / factorial(n-i))\n end\n\n return perms\nend\n\nfunction nPr(n::Vector{Int}, r)\n if r < 0\n throw(DomainError(r, \"\\t[r ≥ 0] must be true.\"))\n end\n \n perms = Vector{Real}()\n\n for i in n\n if i < 0\n throw(DomainError(i, \"\\t[n ≥ 0] must be true.\"))\n end\n push!(perms, factorial(i) / factorial(i-r)) \n end\n\n return perms\nend\n\nend # module\n", "meta": {"hexsha": "4ee52ebf8299b02afc0caa224195be8442962a48", "size": 7422, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/CalcDist.jl", "max_stars_repo_name": "mindonly/CalcDist.jl", "max_stars_repo_head_hexsha": "46a38f6441846b9e8068650a882bf20837a583b9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/CalcDist.jl", "max_issues_repo_name": "mindonly/CalcDist.jl", "max_issues_repo_head_hexsha": "46a38f6441846b9e8068650a882bf20837a583b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CalcDist.jl", "max_forks_repo_name": "mindonly/CalcDist.jl", "max_forks_repo_head_hexsha": "46a38f6441846b9e8068650a882bf20837a583b9", "max_forks_repo_licenses": ["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.8449197861, "max_line_length": 81, "alphanum_fraction": 0.5809754783, "num_tokens": 2396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611597645271, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.8002925807771167}} {"text": "f = x -> begin\n\tN = lastindex(x)\n return 100sum((x[i+1] - x[i]^2)^2 for i = 1:N-1) + sum((x[i] - 1.0)^2 for i = 1:N-1)\nend\n\ng! = (g, x) -> begin\n\tN = lastindex(x)\n\tg[1] = -2*(1 - x[1]) - 400*x[1]*(-x[1]^2 + x[2])\n\tfor i in 2:N-1\n\t\tg[i] = -2*(1 - x[i]) + 200*(-x[i-1]^2 + x[i]) - 400*x[i]*(-x[i]^2 + x[1 + i])\n\tend\n\tg[N] = 200 * (x[N] - x[N-1]^2)\n\treturn g\nend\n\nfg! = (g, x) -> begin\n\t@warn \"rosen fg! not implmented\"\nend\n\ninit = (n::Int=500) -> begin\n\tx0 = [j/(n+1) for j in 1:n]\n\treturn n, x0\nend\n\nTestSet[\"rosen\"] = UncProgram(\"rosen\", f, g!, fg!, init)\n", "meta": {"hexsha": "81bb0410eae57bd1d6f2ba688d9bb4a9cfd3db89", "size": 560, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/programs/rosen.jl", "max_stars_repo_name": "danphenderson/UncNLPrograms.jl", "max_stars_repo_head_hexsha": "5b7b45e43a7e61e89424bd730c3515cfb0675760", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/programs/rosen.jl", "max_issues_repo_name": "danphenderson/UncNLPrograms.jl", "max_issues_repo_head_hexsha": "5b7b45e43a7e61e89424bd730c3515cfb0675760", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/programs/rosen.jl", "max_forks_repo_name": "danphenderson/UncNLPrograms.jl", "max_forks_repo_head_hexsha": "5b7b45e43a7e61e89424bd730c3515cfb0675760", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5384615385, "max_line_length": 88, "alphanum_fraction": 0.4785714286, "num_tokens": 276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.965381162156829, "lm_q2_score": 0.8289388125473629, "lm_q1q2_score": 0.800241914213875}} {"text": "\"\"\"\n`SymmetricDoubleWell` - The classic symmetric doublewell potential.\n\n### Fields\n* `x` - Position x\n\"\"\"\nfunction SymmetricDoubleWell(x)\n return (x^2 -1)^2;\nend\n\n\"\"\"\n`AsymmetricDoubleWell` - An asymmetric double well potential requires |δ|< 1 for\nmultiple minima.\n\n### Fields\n* `x` - Position x\n### Optional Fields\n* `δ = 0.5` - Asymmetry parameter\n\"\"\"\nfunction AsymmetricDoubleWell(x; δ = 0.5)\n return x^4 - 1.5 * x^2 - δ * x;\nend\n\n\"\"\"\n`FatSkinnyDoubleWell10` - The fat-skinny double well of degree 10. This introduces\nentropic effects in dimension 1.\n\n### Fields\n* `x` - Position x\n\"\"\"\nfunction FatSkinnyDoubleWell10(x)\n return ((8-5*x)^8 * (2+5*x)^2)/(2^26);\nend\n\n", "meta": {"hexsha": "5c5cb12e80d5db1c07c387fa6af003d845ce3d2a", "size": 678, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/potentials1D.jl", "max_stars_repo_name": "gideonsimpson/TestLandscapes", "max_stars_repo_head_hexsha": "7287dacdb403efdb44e6f6ae047e7eb36637cfb0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-10-25T20:54:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-30T21:52:09.000Z", "max_issues_repo_path": "src/potentials1D.jl", "max_issues_repo_name": "gideonsimpson/TestLandscapes", "max_issues_repo_head_hexsha": "7287dacdb403efdb44e6f6ae047e7eb36637cfb0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-05-30T08:02:48.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-30T08:02:48.000Z", "max_forks_repo_path": "src/potentials1D.jl", "max_forks_repo_name": "gideonsimpson/TestLandscapes", "max_forks_repo_head_hexsha": "7287dacdb403efdb44e6f6ae047e7eb36637cfb0", "max_forks_repo_licenses": ["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.3714285714, "max_line_length": 82, "alphanum_fraction": 0.6666666667, "num_tokens": 217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9553191259110588, "lm_q2_score": 0.8376199714402812, "lm_q1q2_score": 0.8001943789619755}} {"text": "\"\"\"\n fft_freqs(ts)\n\n Returns an array of DFT frequency points associated with the set of\n time-domain points.\n\n Assumes unit of argument `x` is sec. Output unit is in Hz (not rad/sec).\n\"\"\"\nfunction fft_freqs(ts)\n fs = (ts[2]-ts[1])^(-1) # sampling frequency\n N = Int(length(ts))\n deltaf = fs/N\n if N%2 ==0\n freqs = deltaf*(-N/2:N/2-1)\n else\n freqs = deltaf*(-(N-1)/2:(N-1)/2)\n end\n if length(ts) !== length(freqs)\n @printf(\"length(ts): %d, length(freqs): %d, delta_f: %f.\\n\",\n length(ts), length(freqs), deltaf)\n error(\"Number of time points should match the number of frequency\n points.\")\n end\n return freqs\nend\n", "meta": {"hexsha": "3b0d00c90d56c0b09c3a26b3ccc680140fe192b6", "size": 708, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/fft_freqs.jl", "max_stars_repo_name": "fuzzybear3965/CircuitSimulation.jl", "max_stars_repo_head_hexsha": "48a09cc6b22973b3a2ed7fe49467ce67bcbca5cb", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-27T02:40:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-27T02:40:07.000Z", "max_issues_repo_path": "src/fft_freqs.jl", "max_issues_repo_name": "fuzzybear3965/CircuitSimulation.jl", "max_issues_repo_head_hexsha": "48a09cc6b22973b3a2ed7fe49467ce67bcbca5cb", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fft_freqs.jl", "max_forks_repo_name": "fuzzybear3965/CircuitSimulation.jl", "max_forks_repo_head_hexsha": "48a09cc6b22973b3a2ed7fe49467ce67bcbca5cb", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2307692308, "max_line_length": 76, "alphanum_fraction": 0.5720338983, "num_tokens": 212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9553191246389617, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.8001943720878683}} {"text": "using LinearAlgebra,Statistics\ninclude(\"plotshelper.jl\")\nx_vals = [0 0 0 ; 2 -3 -4]\ny_vals = [0 0 0; 4 3 -3.50]\nplt(x_vals,y_vals)\nvals = [ 0 0 0; 2* [-2 1 2]]\nplt(vals,vals)\n\nf(x,y) = 0.2x + 0.1y\n\nx_vec = [0 0; 3 3]\ny_vec = [0 0; 4 -4]\nz_vec = [0 0; f(x_vec[2,1],y_vec[2,1]) f(x_vec[2,2],y_vec[2,2])]\n\nn=20\ngrid = range(-5,5,length=n)\nz2 = [ f(grid[row],grid[col]) for row in 1:n, col in 1:n]\nwireframe(grid,grid,z2,fill=:blue,gridalpha=1)\nplot!(x_vec,y_vec,z_vec,color=[:blue,:green],linewidth=1,labels=\"\", colorbar=false)\n\n# linear equation\n\nf(x) = 0.6cos(4x)+ 1.3\ngrid = range(-2,2,length=100)\ny_min,y_max = extrema(f(x) for x in grid)\nplt1 = plot(f,xlim=(-2,2),lable=\"f\")\nhline!(plt1,[f(0.5)],linestyle=:dot,linewidth=2, label=\"h line\")\nvline!(plt1,[-1.07, -0.5, 0.5, 1.07],linestyle=:dot,linewidth=2, label=\"v line\")\nplot!(plt1,fill(0,2),[y_min y_min;y_max y_max],lw=6,color=:blue,label=\"tange of f\")\n\n#eigen values and eigen vectors\n\nA = [1 2;2 1]\nevals, evacs = eigen(A)\na1, a2 = evals\neig_1 = [0 0;evacs[:,1]']\n\n ", "meta": {"hexsha": "1015fdcb9959897a039441301f65110c639db81f", "size": 1022, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Math/LinearAlgebra/bascis.jl", "max_stars_repo_name": "bkgsur/QuantitativeEconomics", "max_stars_repo_head_hexsha": "08710be253adc4d779f8d5a3579cd00112119e14", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Math/LinearAlgebra/bascis.jl", "max_issues_repo_name": "bkgsur/QuantitativeEconomics", "max_issues_repo_head_hexsha": "08710be253adc4d779f8d5a3579cd00112119e14", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Math/LinearAlgebra/bascis.jl", "max_forks_repo_name": "bkgsur/QuantitativeEconomics", "max_forks_repo_head_hexsha": "08710be253adc4d779f8d5a3579cd00112119e14", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8947368421, "max_line_length": 83, "alphanum_fraction": 0.633072407, "num_tokens": 463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191335436405, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.8001943718018399}} {"text": "using PyPlot\nA,B,C=1,2,3 # give variables a number\nNlevels=10\n\nfunction demoSkill()\n A,B,C=1,2,3 # give variables a number\n Nlevels=10\n\n sigmoid(x)=1./(1+exp(-x))\n\n pLeftPlayerWins=zeros(Nlevels,Nlevels)\n for levelleft=1:10\n for levelright=1:10\n pLeftPlayerWins[levelleft,levelright]=sigmoid(levelleft-levelright)\n end\n end\n\n #prior_pot=exp.(-0.05*(Nlevels/2-linspace(0,Nlevels,Nlevels)).^2) # peaked around skill 5\n prior_pot=ones(Nlevels,1) # uniform prior on skill\n prior_pot=prior_pot./sum(prior_pot)\n priorA=PotArray(A,prior_pot)\n priorB=PotArray(B,prior_pot)\n priorC=PotArray(C,prior_pot)\n\n fAbeatsB=PotArray([A B],pLeftPlayerWins)\n fBbeatsC=PotArray([B C],pLeftPlayerWins)\n fAbeatsC=PotArray([A C],pLeftPlayerWins)\n\n Data = \"A>B, B>C\"\n pABC=fAbeatsB*fBbeatsC*priorA*priorB*priorC # p(A,B,C,Data)\n plotstuff(Data,pABC,fAbeatsC)\n\n Data = \"A>B, A>B\"\n pABC=fAbeatsB*fAbeatsB*priorA*priorB*priorC # p(A,B,C,Data)\n plotstuff(Data,pABC,fAbeatsC)\n\n Data = \"(A>B)^6, (B>C)^6\"\n pABC=fAbeatsB^6*fBbeatsC^6*priorA*priorB*priorC # p(A,B,C,Data)\n plotstuff(Data,pABC,fAbeatsC)\n\n Data = \"A>B, C>B\"\n pABC=fAbeatsB*(1-fBbeatsC)*priorA*priorB*priorC # p(A,B,C,Data)\n plotstuff(Data,pABC,fAbeatsC)\n\nend\n\nfunction plotstuff(Data,pABC,fAbeatsC)\n pABC=pABC./sum(pABC) # normalise to get p(A,B,C|Data)\n pAC=sum(pABC,B)\n pAbeatsC=sum(fAbeatsC*pAC)\n # What is the probability that A will beat C?\n println(Data*\" : probability that A beats C = $(pAbeatsC.content)\")\n pA=sum(pABC,[B C]); pB=sum(pABC,[A C]); pC=sum(pABC,[B A])\n figure(); title(Data)\n plot(pA.content,label=\"A skill\")\n plot(pB.content,label=\"B skill\")\n plot(pC.content,label=\"C skill\")\n legend()\n # Can calculate mean skill levels using:\n println(\"mean skill for A=\",sum(pA.content.*(1:Nlevels))) # mean skill level for A\n println(\"mean skill for B=\",sum(pB.content.*(1:Nlevels))) # mean skill level for B\n println(\"mean skill for C=\",sum(pC.content.*(1:Nlevels))) # mean skill level for C\nend\n", "meta": {"hexsha": "5eb237e83901cdc72cec053aaf4d9a5eb2056061", "size": 2091, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Demos/demoSkill.jl", "max_stars_repo_name": "davidbarber/Julia0p6ProbabilisticInferenceEngine", "max_stars_repo_head_hexsha": "df932959bf88b53fc076633167df4e497367e7fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30, "max_stars_repo_stars_event_min_datetime": "2017-09-07T22:15:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T20:30:14.000Z", "max_issues_repo_path": "Demos/demoSkill.jl", "max_issues_repo_name": "davidbarber/Julia0p6ProbabilisticInferenceEngine", "max_issues_repo_head_hexsha": "df932959bf88b53fc076633167df4e497367e7fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Demos/demoSkill.jl", "max_forks_repo_name": "davidbarber/Julia0p6ProbabilisticInferenceEngine", "max_forks_repo_head_hexsha": "df932959bf88b53fc076633167df4e497367e7fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2017-10-22T20:10:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-01T22:52:22.000Z", "avg_line_length": 32.671875, "max_line_length": 93, "alphanum_fraction": 0.6661884266, "num_tokens": 723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191259110588, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.8001943654086372}} {"text": "### A Pluto.jl notebook ###\n# v0.12.17\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n quote\n local el = $(esc(element))\n global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n el\n end\nend\n\n# ╔═╡ ebcb6ec6-61f9-11eb-05a3-817618350415\nusing PlutoUI\n\n# ╔═╡ 2d1693e6-61fa-11eb-3cb6-9f5431449a41\nbegin\n\tusing Plots\n\tpyplot()\nend\n\n# ╔═╡ f5d3f88c-620e-11eb-3bc8-e3e0e1598482\nusing Random\n\n# ╔═╡ 6b69c792-62bd-11eb-0f1d-2d0081598dfa\nusing Distributions\n\n# ╔═╡ b80b8e58-62bf-11eb-11fb-1397b06ae3e1\nusing QuadGK\n\n# ╔═╡ ebd217ba-61f8-11eb-2337-9db63173ed34\nmd\"# Module 2: _Probability Quick Refresher in Julia_\n**CS6741: Statistical Foundations of Data Science**\n\nIn this module, we will quickly revise some aspects of Probability through exercises on Julia.\n\n\"\n\n# ╔═╡ 4e0bacac-621c-11eb-17be-a968500dc6bc\nmd\"### Dice Throws\"\n\n# ╔═╡ 48a0d2ac-6a1d-11eb-2441-897ca192e8ad\nmd\"👉 How would you simulate a fair dice?\"\n\n# ╔═╡ 29fb09a2-61f9-11eb-0699-4dbf7daca0d7\nfaces = 1:6\n\n# ╔═╡ bbae804a-61f9-11eb-03fe-89049682eae7\nrand(faces)\n\n# ╔═╡ e977219e-620d-11eb-2ca1-2141cc7c7d2a\nmd\"What is the distribution of values obtained with throws?\"\n\n# ╔═╡ ee1bd118-61f9-11eb-1a18-df7d29a96c97\n@bind throwdice Button(\"Throw dice\")\n\n# ╔═╡ 059c87a6-61fa-11eb-01b4-09c40af1be94\nthrows = []\n\n# ╔═╡ 0a10f34e-61fa-11eb-365d-01ff16513530\nbegin\n\tthrowdice\n\tfor _ in 1:1000\n\t\tpush!(throws, rand(faces))\n\tend\nend\n\n# ╔═╡ e00f4d02-61f9-11eb-2c5e-19ab03f4bdeb\nbegin\n\tthrowdice\n\thistogram(throws, bins = [1, 2, 3, 4, 5, 6, 7], normalize=true, legend=false)\nend\n\n# ╔═╡ 20ea39f4-620e-11eb-05b3-716b88bcd205\nmd\"👉 What about the distribution of throws of two dice?\"\n\n# ╔═╡ c0b6a868-61fb-11eb-2190-83d6d760ede4\nbegin\n\tN = 1000\n\ttwo_throws = [(rand(faces), rand(faces)) for _ in 1:N]\nend\n\n# ╔═╡ 947c880a-6203-11eb-1bfe-95c8e630b395\nbegin\n\tfreq_matrix = zeros(length(faces), length(faces))\n\tfor i in faces\n\t\tfor j in faces\n\t\t\tfreq_matrix[i, j] = count(two_throws .== [(i, j)]) / N\n\t\tend\n\tend\nend\n\n# ╔═╡ fb898100-6204-11eb-1faf-cd75283f54d4\nfreq_matrix\n\n# ╔═╡ b25c21be-6203-11eb-2f40-5db01b4beb89\nheatmap(faces, faces, freq_matrix, clim=(0, 0.1))\n\n# ╔═╡ 2b3a4f0c-620e-11eb-2021-bdaab9318fc1\nmd\"👉 What is the probability that the sum of two dice is prime?\"\n\n# ╔═╡ c2ae2510-620a-11eb-07e0-91cf24657a55\nfunction isPrime(x)\n\tif x == 1\n\t\treturn false\n\telseif x == 2\n\t\treturn true\n\tend\n\tfor i = 2:sqrt(x)\n\t\tif x%i == 0\n\t\t\treturn false\n\t\tend\n\tend\n\treturn true\nend\n\n# ╔═╡ 853a1ab6-6a1d-11eb-2e08-93e5bcc73c7c\nisPrime.(2:12)\n\n# ╔═╡ 33d3be8c-620e-11eb-3f7d-8f9a60cfdefc\nmd\"We have 11 unique sums possible 2 through 12 out of which only 5 (2, 3, 5, 7, 11) are prime. Hence probability is:\"\n\n# ╔═╡ 6205d7aa-620d-11eb-3c75-83b491a84995\ncount(isPrime.(2:12)) / 11\n\n# ╔═╡ 6f0eec76-6a1d-11eb-2585-17959367c09f\nmd\"👉 Is the above correct? Why or why not?\"\n\n# ╔═╡ ba50d33e-6a1d-11eb-0687-47cb0b6f8242\nmd\"👉 What visualiation would you use to help you with this?\"\n\n# ╔═╡ ec8b9cd0-6211-11eb-06fa-37880ae43e40\nhistogram([(rand(faces) + rand(faces)) for _ in 1:10000])\n\n# ╔═╡ e37eefb6-6a1d-11eb-000b-89dbddabce5d\nmd\"👉 How do we fix this?\"\n\n# ╔═╡ 5b2accf0-620e-11eb-06b9-ef354ebb3261\nmd\"Correct theoretical approach assumes equal probability of the individual dice throws and not the sum\"\n\n# ╔═╡ 7dced6ec-6205-11eb-3e95-5f2fa0d5adf3\ntheorySol = sum([isPrime(i + j) for i in faces, j in faces]) / length(faces)^2\n\n# ╔═╡ 7bbe53a6-620e-11eb-296a-dbf3eaab558d\nmd\"Now we will compute the same thing by running lots of experiments with randomly sampled data. Usually called _Monte Carlo experiments_\"\n\n# ╔═╡ 014acff6-6206-11eb-0f3f-f17ef6edf8dd\n@bind n_exp html\"\"\n\n# ╔═╡ 987d2bb2-620d-11eb-07b6-1736ac133029\nn_exp\n\n# ╔═╡ 0c205d04-6205-11eb-2d31-5f689e25a3f1\nest = sum([isPrime(rand(faces) + rand(faces)) for i in 1:10^n_exp]) / 10^n_exp\n\n# ╔═╡ beccfb34-620e-11eb-177a-711b597f5f6f\nmd\"These random experiments give different results each time\"\n\n# ╔═╡ b0c7733e-620e-11eb-0fb6-f3a9f7631823\n[sum([isPrime(rand(faces) + rand(faces)) for i in 1:10^5]) / 10^5 for j = 1: 10]\n\n# ╔═╡ ce084cfc-620e-11eb-2881-8f30a7558bba\nmd\"For reproducibility, we can set the seed of the random number generator\"\n\n# ╔═╡ d8b7f274-620e-11eb-13b1-3933af0f7157\nbegin \n\tRandom.seed!(0)\n\tsum([isPrime(rand(faces) + rand(faces)) for i in 1:10^5]) / 10^5\nend\n\n# ╔═╡ 77fb84bc-621c-11eb-2cc3-71425a74f823\nmd\"Notice that in the above we used the probability concepts of _independence_ of two random variables and _Monte Carlo_ simulations.\"\n\n# ╔═╡ 59437fd2-621c-11eb-1e31-f1973639a0e2\nmd\"### Picking balls\"\n\n# ╔═╡ 8fbbc5a6-6212-11eb-1020-7382ef578cea\nmd\"Selection with and without replacement\"\n\n# ╔═╡ beeacf18-6212-11eb-1929-a5c830dddbcb\nmd\"Let us suppose a bag contains 5 balls - 3 tennis balls, 2 cricket balls\"\n\n# ╔═╡ 6aa6b4ec-6212-11eb-39ea-db9d36b22cce\nbag = [\"🎾\", \"🥎\", \"🎾\", \"🎾\", \"🥎\"]\n\n# ╔═╡ bc4822e0-6212-11eb-3a49-e5307fe49156\nrand(bag)\n\n# ╔═╡ d5215c20-6212-11eb-32f5-c71343b60d22\nmd\"👉 What is the probability that if I draw two balls both are tennis balls\"\n\n# ╔═╡ e6f2b97e-6212-11eb-0ef4-6593e840b93a\nmd\"The easier case is with replacement. It is simply $P(🎾) \\times P(🎾)$\"\n\n# ╔═╡ e49d22cc-6212-11eb-2732-27ad5e863ffc\n3/5 * 3/5\n\n# ╔═╡ f462afb0-6212-11eb-1a80-239d798e25f8\nmd\"👉 What if we do not allow replacement?\"\n\n# ╔═╡ 383c0f2e-6213-11eb-355e-5b16663f1897\nmd\"We are looking for $P(🎾|\\phi) \\times P(🎾|🎾)$\"\n\n# ╔═╡ 559fea86-6213-11eb-185e-b5fc917251fe\n3/5 * 2/4\n\n# ╔═╡ 73f6494e-6213-11eb-2a42-7b58fe47d597\nmd\"👉 How do we implement this in Julia when running for more complex examples? Which one do you think is easier to implement - with or without replacements?\"\n\n# ╔═╡ 1ad550e8-6214-11eb-108b-0d6e08518018\nmd\"With replacement:\"\n\n# ╔═╡ e455c886-6213-11eb-01b8-5df9e2bb7ea8\nsum([(rand(bag) == \"🎾\" && rand(bag) == \"🎾\") for i in 1:100000])/100000\n\n# ╔═╡ 33bc8ece-6a1f-11eb-20c9-fd32413cc2ac\nmd\"👉 How would you implement this without replacement?\"\n\n# ╔═╡ 17ebe7ac-6214-11eb-38f1-3b757972e958\nmd\"Without replacement:\"\n\n# ╔═╡ 3d281fc0-6214-11eb-16ae-89900d7f437f\nbegin\n\tnum = 10000\n\tcount_ = 0\n\tfor i = 1:num\n\t\tbag1 = copy(bag)\n\t\tball1 = rand(bag1)\n\t\tdeleteat!(bag1, findfirst(x-> x == \"🎾\", bag1))\n\t\tball2 = rand(bag1)\n\t\tif ball1 == \"🎾\" && ball2 == \"🎾\"\n\t\t\tcount_ += 1\n\t\tend\n\tend\n\tcount_ / num\nend\n\n# ╔═╡ 94d49374-621c-11eb-2985-b5ee5644c67e\nmd\"Notice that in the above example we use the idea of _conditional probability_\"\n\n# ╔═╡ 5eff3d3a-621c-11eb-0824-f76604aed501\nmd\"### Inclusion exclusion principle\"\n\n# ╔═╡ ba16f60e-623f-11eb-190a-af4758c32068\nmd\"You have to inform $n$ people about some important news, but you have a fancy quantum phone that randomly dials a person. If you are allowed to make $r \\geq n$ calls, what is the probability that all $n$ people are informed of the important news.\"\n\n# ╔═╡ 51413a62-6a1f-11eb-1400-5918c088122c\nmd\"👉 How would you do this? Think first of the mathematical approach, and then we will look at the computational approach.\"\n\n# ╔═╡ eed974c0-623f-11eb-021e-ebfc3c85b934\nmd\"Let $A_i$ denote the event that the $i$th person is not informed. Then the probability we seek is \n```math\nP(B) = 1 - P(A_1 \\cup \\ldots \\cup A_n)\n```\"\n\n# ╔═╡ 2cf52d58-6240-11eb-1e21-f3c0a71b4525\nmd\"The probability of the union of those events is not as easy as it may seem. It requires application of the _inclusion exclusion_ principle repeatedly to obtain\n```math\nP(\\large\\cup_{i = 1}^n A_i) = \\sum_{i = 1}^n P(A_i) - \\sum_{\\mbox{pairs}} P(A_i \\cap A_j) + \\sum_{\\mbox{triplets}} P(A_i \\cap A_j \\cap A_k) + \\ldots\n```\n\"\n\n# ╔═╡ e8c3415a-6240-11eb-328c-fd7e571ad7f9\nmd\"So our probability becomes\n```math\nP(B) = 1 - \\sum_{k = 1}^n (-1)^{k + 1} {n \\choose k}p_k\n```\nwhere $p_k$ is the probability of at least $k$ people hearing about the news. From counting principles you can find out that \n```math\np_k = \\dfrac{(n - k)^r}{n^r} = \\left(1 - \\dfrac{k}{n}\\right)^r\n```\n\"\n\n# ╔═╡ 74a09470-6241-11eb-00df-cb5032e755c3\nfunction callprobabilty(n, r)\n\treturn sum([(-1)^k * binomial(n, k) * (1 - k/n)^r for k in 0:n])\nend\n\n# ╔═╡ 9d189772-6241-11eb-16a3-25c54c8d4148\ntheorycurve = [callprobabilty(big(n), big(2*n)) for n in 1:100] \n\n# ╔═╡ 024a8056-6242-11eb-23b6-a14e3fe68a74\nplot(1:100, theorycurve)\n\n# ╔═╡ 619109a4-6242-11eb-34eb-2527db9629bc\ntheorycurves = [ [callprobabilty(big(n), big(r_ratio*n)) for n in 1:200] for r_ratio in 1:3]\n\n# ╔═╡ 85f02e2e-6242-11eb-2a27-7746c98beb47\nplot(1:100, theorycurves, label=[\"r=n\" \"r=2n\" \"r=3n\"])\n\n# ╔═╡ ce1be85a-6242-11eb-026b-eb7215cc8c18\nfunction simulatecalls(n, r, N)\n\tfailed = float(0)\n\tfor exp in 1:N\n\t\tcounts = zeros(n)\n\t\tfor k in 1:r\n\t\t\tperson = rand(1:n)\n\t\t\tcounts[person] += 1\n\t\tend\n\t\tif minimum(counts) == 0\n\t\t\tfailed += 1\n\t\tend\n\tend\n\treturn 1.0 - failed / N\nend\n\n# ╔═╡ 363c8308-6249-11eb-3580-8b721c00a424\n\n\n# ╔═╡ e0efb4ea-6245-11eb-2423-b7d55a99bf0e\nempiricalcurves = [[simulatecalls(n, r_ratio*n, 1000) for n in 1:100] for r_ratio in 1:3]\n\n# ╔═╡ 1aaa0faa-6246-11eb-1f5c-69cbf277efea\nbegin\n\tscatter(1:100, empiricalcurves, label=\"\")\n\tplot!(1:100, theorycurves, label=[\"r=n\" \"r=2n\" \"r=3n\"])\nend\n\n# ╔═╡ 55b868f4-62bd-11eb-16a8-e14408e3e4bd\nmd\"### Testing independence in random number generators\"\n\n# ╔═╡ a1c8ec8c-6a1f-11eb-0a85-fb5cac062c56\nmd\"Randomness is a big requirement in statistical analysis and computational methods that depend on sampling.\"\n\n# ╔═╡ 95bd11e8-6a1f-11eb-3287-0b32ba568406\nmd\"👉 Do you know of any simple way to generate pseudo random numbers?\"\n\n# ╔═╡ abe1778a-6249-11eb-3b17-0de274e8e3fe\nmd\"\nA pseudo-random generator is given by the following sequence of outputs:\n```math\nX_{n + 1} = (a X_n + c) \\mbox{ mod } m\n```\n\"\n\n# ╔═╡ 277b4f60-624a-11eb-2e11-9b6c5aeb3b4a\nfunction prng(n)\n\tc = 7\n\tm = 13\n\ta = 5\n\tout = zeros(Int, n)\n\tout[1] = floor(rand() * m)\n\tfor i in 2:n\n\t\tout[i] = (a * out[i - 1] + c) % m\n\tend\n\treturn out\nend\n\n# ╔═╡ 9645b9a6-624a-11eb-09e9-c399cb136a5c\nprng(5)\n\n# ╔═╡ f6e2aff6-624c-11eb-16b5-318c5f230a56\nn_vals = 1000\n\n# ╔═╡ b97aa654-6a1f-11eb-11da-f91221057751\nmd\"👉 Are two consecutive random numbers generated with `prng` independent? How would you check this computationally?\"\n\n# ╔═╡ ff30f85c-624b-11eb-3cf2-c170108d7092\nvals1 = [prng(2) for i in 1:n_vals]\n\n# ╔═╡ e59bc748-6a1f-11eb-2463-7dc3313f4b35\nmd\"Remember that two random variables $X$ and $Y$ are indpendent if\n```math\nP(X, Y) = P(X) P(Y)\n```\"\n\n# ╔═╡ b197bcf2-624c-11eb-3b99-efbedf0c6f3b\nbegin\n\ta = rand(1:13)\n\tb = rand(1:13)\n\tp_a = sum([vals1[i][1] == a for i in 1:n_vals]) / n_vals\n\tp_b = sum([vals1[i][2] == b for i in 1:n_vals]) / n_vals\n\tp_ap_b = p_a * p_b\n\tp_ab = sum([vals1[i][1] == a && vals1[i][2] == b for i in 1:n_vals]) / n_vals\n\t\"a=$a b=$b p(x = a)=$p_a p(y = b)=$p_b p(x = a, y = b)=$p_ab p(x = a)p(y = b)=$p_ap_b\"\nend\n\n# ╔═╡ 6b0245fe-624f-11eb-38f1-e702814d57c3\nvals2 = [[rand(1:13), rand(1:13)] for i in 1:n_vals]\n\n# ╔═╡ 5193bb62-62bc-11eb-1df7-1b7a7e9983ed\nbegin\n\tp_a2 = sum([vals2[i][1] == a for i in 1:n_vals]) / n_vals\n\tp_b2 = sum([vals2[i][2] == b for i in 1:n_vals]) / n_vals\n\tp_a2p_b2 = p_a2 * p_b2\n\tp_ab2 = sum([vals2[i][1] == a && vals2[i][2] == b for i in 1:n_vals]) / n_vals\n\t\"a=$a b=$b p(x = a)=$p_a2 p(y = b)=$p_b2 p(x = a, y = b)=$p_ab2 p(x = a)p(y = b)=$p_a2p_b2\"\nend\n\n# ╔═╡ 76fffb4e-62bd-11eb-153b-690eeaed1160\nmd\"### Distributions and their plots\"\n\n# ╔═╡ fae8040a-62be-11eb-18a4-9fe8dee70bed\nD_n = Normal(0, 1)\n\n# ╔═╡ 0ea764ea-62bf-11eb-0e98-437744ee9fa9\nplot(-5:0.1:5, [pdf(D_n, x) for x in -5:0.1:5], label=\"Normal PDF\")\n\n# ╔═╡ 3771b0ec-62bf-11eb-0300-6d9503c5716b\nplot(-5:0.1:5, [cdf(D_n, x) for x in -5:0.1:5], label=\"CDF\")\n\n# ╔═╡ 66abd1d6-62c3-11eb-2e4e-1f67f89c3526\nbegin\n\tplot(-5:0.1:5, [cdf(D_n, x) for x in -5:0.1:5], label=\"CDF\")\n\tplot!(-5:0.1:5, [quadgk(x -> pdf(D_n, x), (-5, y)...)[1] for y in -5:0.1:5], line = (4, :dash), label=\"From integration\")\nend\n\n# ╔═╡ c420bab4-62c0-11eb-13c5-51ef6be81102\nD_b = Binomial(5, 0.5)\n\n# ╔═╡ ee11743a-62c0-11eb-04ef-8f30696c46ee\nplot(0:5, [pdf(D_b, x) for x in 0:5], line=:stem, marker=:circle, label=\"Binomial\")\n\n# ╔═╡ 66a1bfe2-62bf-11eb-36d4-cfcaff920522\nmean(D_n)\n\n# ╔═╡ 93a82e9c-62cc-11eb-1b9c-cbc0e30b623e\nmd\"### Moments of distributions\"\n\n# ╔═╡ f5b41e14-62bf-11eb-3257-6f5f5d6ceee6\nmd\"What is the mean?\nFor a discrete distribution:\n```math\n\\mathbb{E}[x] = \\sum_x xp(x)\n```\nFor a continuous distribution:\n```math\n\\mathbb{E}[x] = \\int_{-\\infty}^{\\infty} x f(x) dx,\n```\nwhere $f(x)$ is the pdf of the distribution.\n\"\n\n# ╔═╡ 2be88b12-62c2-11eb-14de-6912598bc6bb\narea = quadgk(x -> pdf(D_n, x), (-5, 5)...)\n\n# ╔═╡ ec35489c-62bf-11eb-0311-2fed6b29d0c6\ncomputed_mean = quadgk(x -> x * pdf(D_n, x), (-5, 5)...)\n\n# ╔═╡ 5dffb66c-62c1-11eb-32f6-4b0b17d2aed1\nmean(Binomial(5, 0.5))\n\n# ╔═╡ 35406a36-62c2-11eb-347e-9b03c368119a\ntot_length = sum([pdf(D_b, x) for x in 0:5])\n\n# ╔═╡ 653515e4-62c1-11eb-25b0-930f782be996\ncomputed_mean_binominal = sum([x * pdf(D_b, x) for x in 0:5])\n\n# ╔═╡ 6a1d4ba4-62c2-11eb-3b71-431ee0c1fdf5\nmd\"\n```math\n\\mbox{Var}(X) = \\mathbb{E}[X^2] - (\\mathbb{E}[X])^2\n```\n\"\n\n# ╔═╡ 565657a8-62c2-11eb-22ad-9fbf7e7b44e0\nvar(D_n)\n\n# ╔═╡ 641557fe-62c2-11eb-1ffd-0b1486231fa0\nquadgk(x -> x^2 * pdf(D_n, x), (-5, 5)...)[1] - mean(D_n)^2\n\n# ╔═╡ a46d7728-62cc-11eb-3486-d799a3d29298\nmd\"### Sampling and sums of distributions\"\n\n# ╔═╡ 5811e2d8-62cc-11eb-266a-3d1ed4d9270b\nn_samples = 1000\n\n# ╔═╡ 2d0191b4-62c3-11eb-1479-21830ac879eb\nx1 = rand(D_n, n_samples)\n\n# ╔═╡ c845fae0-62c6-11eb-2a29-bdbc0c07d6d4\nhistogram(x1, normalize=true)\n\n# ╔═╡ bd903520-62c6-11eb-1f71-49b662373de7\nx2 = rand(D_b, n_samples)\n\n# ╔═╡ 485386b2-62cc-11eb-1dd4-31857e128d7f\nhistogram(x2, normalize=true)\n\n# ╔═╡ c4f908fa-62c6-11eb-259d-576dee85efb9\nx = x1 + x2\n\n# ╔═╡ 505c1658-62cc-11eb-1068-659d4286a4da\nhistogram(x, normalize=true)\n\n# ╔═╡ 6e365fee-62cc-11eb-28d4-cd498c21895d\nbegin\n\thistogram(x, normalize=true)\n\tplot!(-5:0.1:5, [pdf(D_n, x)+pdf(D_b, x) for x in -5:0.1:5])\nend\n\n# ╔═╡ ad175b5a-62cc-11eb-2913-8741eca3d89c\nmd\"The random variable which is the sum of two independent random variable does not necessarily have a pdf as the sum of the pdfs of the two random variables.\"\n\n# ╔═╡ c19c5abc-62cc-11eb-3bcd-d9ee89e4619d\nbegin\n\tconv(x) = sum(pdf(D_n,x-k)*pdf(D_b,k) for k=-5:0.1:8)\n\tplot(-5:0.1:8, conv.(-5:0.1:8))\nend\n\n# ╔═╡ e6d9958c-62cd-11eb-164e-4b52aedd1584\nmd\"The convolution operation on the individual pdfs creates the pdf of the sum of two random variables. It is defined as:\n```math\nh(z) = (p1 \\otimes p2)(z) = \\int_{-\\infty}^{\\infty} f(t) g(z - t) dt\n```\nThis needs to be changed to discrete versions if distribution/s are discrete.\n\"\n\n# ╔═╡ b68f9fdc-62cd-11eb-1852-0116fe475f36\nbegin\n\thistogram(x, normalize=true)\n\tplot!(-5:0.1:8, conv.(-5:0.1:8))\nend\n\n# ╔═╡ 7b02ff44-62ce-11eb-2c40-b5a734f869cb\nmd\"### Inverse\"\n\n# ╔═╡ 7e5765f6-62ce-11eb-222e-9786c5fc0911\nmd\"When we say that the $\\mbox{CDF}(x) = u$, we mean that the probability of the random number being less than or equal to $x$ is $u$. We can now ask an opposite question: For what value of $x$ is the probability of the random number being less than $x$ is a given $u$. This is usually referred to as the _inverse function_.\"\n\n# ╔═╡ beea6cda-62ce-11eb-0ef1-253f1a40504b\nmd\"Though not mathematically tight, we can define the inverse function $\\mbox{CDF}^{-1}$ as:\n```math\n\\mbox{CDF}^{-1}(u) = \\inf\\{x\\ :\\ \\mbox{CDF}(x) \\geq u\\}\n```\n\"\n\n# ╔═╡ 0047b980-62cf-11eb-3ca2-ad2f18f0e091\ncdf_n(x) = cdf(Normal(0, 1), x)\n\n# ╔═╡ 1676307e-62cf-11eb-39e5-bd732850ab2f\ncdf_n_inv(u) = minimum(filter((x) -> (cdf_n(x) >= u), -5:0.01:5))\n\n# ╔═╡ 343f9c62-62cf-11eb-2d09-cff6967a1d65\nplot(-5:0.1:5, [cdf_n(x) for x in -5:0.1:5])\n\n# ╔═╡ 5fab01a2-62cf-11eb-1c61-f9da64f9a75f\nplot(0.1:0.01:0.9, [cdf_n_inv(u) for u in 0.1:0.01:0.9])\n\n# ╔═╡ 9a083902-62d2-11eb-2570-bdb7ea1e1f5e\nmd\"Let us relate the inverse function to area under the PDF curve\"\n\n# ╔═╡ c483fc1c-62d1-11eb-14b6-f50474a58fb2\ncdf_n_inv(0.8)\n\n# ╔═╡ a9a39152-62d2-11eb-3b4a-5d37f7195f3a\ncdf_n_inv(0.95)\n\n# ╔═╡ f437e702-62d1-11eb-1ac8-63c7f6ec16c4\nxslider = @bind x_slider html\"\"\n\n# ╔═╡ 8439e2ec-62d2-11eb-3772-d17e099debb5\nx_slider\n\n# ╔═╡ 794c86e6-62d2-11eb-3e27-ebd8a1b3d4e3\nu_cdf = cdf_n(x_slider)\n\n# ╔═╡ cb5e2858-62d1-11eb-1489-037703d411ec\nbegin\n\tplot(x->x, x->pdf(Normal(0, 1), x), -10, 10, label=\"\")\n\tplot!(x->x, x->pdf(Normal(0, 1), x), x_slider, 10, fill=(0, :orange), label=\"\")\nend\n\n# ╔═╡ 2a8682e2-62d3-11eb-119e-cbd804e1b0b2\nmd\"### Fitting given data to distributions\"\n\n# ╔═╡ a089b976-62d3-11eb-2702-8945a47bf858\nn_slider = @bind n_samples_exp html\"\"\n\n# ╔═╡ 3151c634-62d3-11eb-2698-95e4e14aab2d\nsamples = rand(Normal(10, 2.5), 10^n_samples_exp) + rand(Normal(0, 1), 10^n_samples_exp)\n\n# ╔═╡ 62e55e4a-62d3-11eb-21e3-7b02354ddd02\nhistogram(samples)\n\n# ╔═╡ 786f3d9c-62d3-11eb-28a7-b387242e3760\nfit(Normal, samples)\n\n# ╔═╡ 9531fffe-62d3-11eb-124c-0d2cccea92ae\nmd\"Notice how the estimate of μ is reasonably unbiased even for small sizes of the samples, but how σ seems to be higher.\"\n\n# ╔═╡ Cell order:\n# ╟─ebd217ba-61f8-11eb-2337-9db63173ed34\n# ╠═ebcb6ec6-61f9-11eb-05a3-817618350415\n# ╠═2d1693e6-61fa-11eb-3cb6-9f5431449a41\n# ╟─4e0bacac-621c-11eb-17be-a968500dc6bc\n# ╟─48a0d2ac-6a1d-11eb-2441-897ca192e8ad\n# ╠═29fb09a2-61f9-11eb-0699-4dbf7daca0d7\n# ╠═bbae804a-61f9-11eb-03fe-89049682eae7\n# ╟─e977219e-620d-11eb-2ca1-2141cc7c7d2a\n# ╠═ee1bd118-61f9-11eb-1a18-df7d29a96c97\n# ╠═059c87a6-61fa-11eb-01b4-09c40af1be94\n# ╠═0a10f34e-61fa-11eb-365d-01ff16513530\n# ╠═e00f4d02-61f9-11eb-2c5e-19ab03f4bdeb\n# ╟─20ea39f4-620e-11eb-05b3-716b88bcd205\n# ╠═c0b6a868-61fb-11eb-2190-83d6d760ede4\n# ╠═947c880a-6203-11eb-1bfe-95c8e630b395\n# ╠═fb898100-6204-11eb-1faf-cd75283f54d4\n# ╠═b25c21be-6203-11eb-2f40-5db01b4beb89\n# ╟─2b3a4f0c-620e-11eb-2021-bdaab9318fc1\n# ╟─c2ae2510-620a-11eb-07e0-91cf24657a55\n# ╠═853a1ab6-6a1d-11eb-2e08-93e5bcc73c7c\n# ╟─33d3be8c-620e-11eb-3f7d-8f9a60cfdefc\n# ╠═6205d7aa-620d-11eb-3c75-83b491a84995\n# ╟─6f0eec76-6a1d-11eb-2585-17959367c09f\n# ╟─ba50d33e-6a1d-11eb-0687-47cb0b6f8242\n# ╠═ec8b9cd0-6211-11eb-06fa-37880ae43e40\n# ╟─e37eefb6-6a1d-11eb-000b-89dbddabce5d\n# ╟─5b2accf0-620e-11eb-06b9-ef354ebb3261\n# ╠═7dced6ec-6205-11eb-3e95-5f2fa0d5adf3\n# ╟─7bbe53a6-620e-11eb-296a-dbf3eaab558d\n# ╠═014acff6-6206-11eb-0f3f-f17ef6edf8dd\n# ╠═987d2bb2-620d-11eb-07b6-1736ac133029\n# ╠═0c205d04-6205-11eb-2d31-5f689e25a3f1\n# ╟─beccfb34-620e-11eb-177a-711b597f5f6f\n# ╠═b0c7733e-620e-11eb-0fb6-f3a9f7631823\n# ╟─ce084cfc-620e-11eb-2881-8f30a7558bba\n# ╠═f5d3f88c-620e-11eb-3bc8-e3e0e1598482\n# ╠═d8b7f274-620e-11eb-13b1-3933af0f7157\n# ╟─77fb84bc-621c-11eb-2cc3-71425a74f823\n# ╟─59437fd2-621c-11eb-1e31-f1973639a0e2\n# ╟─8fbbc5a6-6212-11eb-1020-7382ef578cea\n# ╟─beeacf18-6212-11eb-1929-a5c830dddbcb\n# ╠═6aa6b4ec-6212-11eb-39ea-db9d36b22cce\n# ╠═bc4822e0-6212-11eb-3a49-e5307fe49156\n# ╟─d5215c20-6212-11eb-32f5-c71343b60d22\n# ╟─e6f2b97e-6212-11eb-0ef4-6593e840b93a\n# ╠═e49d22cc-6212-11eb-2732-27ad5e863ffc\n# ╟─f462afb0-6212-11eb-1a80-239d798e25f8\n# ╟─383c0f2e-6213-11eb-355e-5b16663f1897\n# ╠═559fea86-6213-11eb-185e-b5fc917251fe\n# ╟─73f6494e-6213-11eb-2a42-7b58fe47d597\n# ╟─1ad550e8-6214-11eb-108b-0d6e08518018\n# ╠═e455c886-6213-11eb-01b8-5df9e2bb7ea8\n# ╟─33bc8ece-6a1f-11eb-20c9-fd32413cc2ac\n# ╟─17ebe7ac-6214-11eb-38f1-3b757972e958\n# ╠═3d281fc0-6214-11eb-16ae-89900d7f437f\n# ╟─94d49374-621c-11eb-2985-b5ee5644c67e\n# ╟─5eff3d3a-621c-11eb-0824-f76604aed501\n# ╟─ba16f60e-623f-11eb-190a-af4758c32068\n# ╟─51413a62-6a1f-11eb-1400-5918c088122c\n# ╟─eed974c0-623f-11eb-021e-ebfc3c85b934\n# ╟─2cf52d58-6240-11eb-1e21-f3c0a71b4525\n# ╟─e8c3415a-6240-11eb-328c-fd7e571ad7f9\n# ╠═74a09470-6241-11eb-00df-cb5032e755c3\n# ╠═9d189772-6241-11eb-16a3-25c54c8d4148\n# ╠═024a8056-6242-11eb-23b6-a14e3fe68a74\n# ╠═619109a4-6242-11eb-34eb-2527db9629bc\n# ╠═85f02e2e-6242-11eb-2a27-7746c98beb47\n# ╠═ce1be85a-6242-11eb-026b-eb7215cc8c18\n# ╠═363c8308-6249-11eb-3580-8b721c00a424\n# ╠═e0efb4ea-6245-11eb-2423-b7d55a99bf0e\n# ╠═1aaa0faa-6246-11eb-1f5c-69cbf277efea\n# ╟─55b868f4-62bd-11eb-16a8-e14408e3e4bd\n# ╟─a1c8ec8c-6a1f-11eb-0a85-fb5cac062c56\n# ╟─95bd11e8-6a1f-11eb-3287-0b32ba568406\n# ╟─abe1778a-6249-11eb-3b17-0de274e8e3fe\n# ╠═277b4f60-624a-11eb-2e11-9b6c5aeb3b4a\n# ╠═9645b9a6-624a-11eb-09e9-c399cb136a5c\n# ╠═f6e2aff6-624c-11eb-16b5-318c5f230a56\n# ╟─b97aa654-6a1f-11eb-11da-f91221057751\n# ╠═ff30f85c-624b-11eb-3cf2-c170108d7092\n# ╟─e59bc748-6a1f-11eb-2463-7dc3313f4b35\n# ╠═b197bcf2-624c-11eb-3b99-efbedf0c6f3b\n# ╠═6b0245fe-624f-11eb-38f1-e702814d57c3\n# ╠═5193bb62-62bc-11eb-1df7-1b7a7e9983ed\n# ╟─76fffb4e-62bd-11eb-153b-690eeaed1160\n# ╠═6b69c792-62bd-11eb-0f1d-2d0081598dfa\n# ╠═fae8040a-62be-11eb-18a4-9fe8dee70bed\n# ╠═0ea764ea-62bf-11eb-0e98-437744ee9fa9\n# ╠═3771b0ec-62bf-11eb-0300-6d9503c5716b\n# ╠═66abd1d6-62c3-11eb-2e4e-1f67f89c3526\n# ╠═c420bab4-62c0-11eb-13c5-51ef6be81102\n# ╠═ee11743a-62c0-11eb-04ef-8f30696c46ee\n# ╠═66a1bfe2-62bf-11eb-36d4-cfcaff920522\n# ╠═b80b8e58-62bf-11eb-11fb-1397b06ae3e1\n# ╟─93a82e9c-62cc-11eb-1b9c-cbc0e30b623e\n# ╟─f5b41e14-62bf-11eb-3257-6f5f5d6ceee6\n# ╠═2be88b12-62c2-11eb-14de-6912598bc6bb\n# ╠═ec35489c-62bf-11eb-0311-2fed6b29d0c6\n# ╠═5dffb66c-62c1-11eb-32f6-4b0b17d2aed1\n# ╠═35406a36-62c2-11eb-347e-9b03c368119a\n# ╠═653515e4-62c1-11eb-25b0-930f782be996\n# ╟─6a1d4ba4-62c2-11eb-3b71-431ee0c1fdf5\n# ╠═565657a8-62c2-11eb-22ad-9fbf7e7b44e0\n# ╠═641557fe-62c2-11eb-1ffd-0b1486231fa0\n# ╟─a46d7728-62cc-11eb-3486-d799a3d29298\n# ╠═5811e2d8-62cc-11eb-266a-3d1ed4d9270b\n# ╠═2d0191b4-62c3-11eb-1479-21830ac879eb\n# ╠═c845fae0-62c6-11eb-2a29-bdbc0c07d6d4\n# ╠═bd903520-62c6-11eb-1f71-49b662373de7\n# ╠═485386b2-62cc-11eb-1dd4-31857e128d7f\n# ╠═c4f908fa-62c6-11eb-259d-576dee85efb9\n# ╠═505c1658-62cc-11eb-1068-659d4286a4da\n# ╠═6e365fee-62cc-11eb-28d4-cd498c21895d\n# ╟─ad175b5a-62cc-11eb-2913-8741eca3d89c\n# ╠═c19c5abc-62cc-11eb-3bcd-d9ee89e4619d\n# ╟─e6d9958c-62cd-11eb-164e-4b52aedd1584\n# ╠═b68f9fdc-62cd-11eb-1852-0116fe475f36\n# ╟─7b02ff44-62ce-11eb-2c40-b5a734f869cb\n# ╟─7e5765f6-62ce-11eb-222e-9786c5fc0911\n# ╟─beea6cda-62ce-11eb-0ef1-253f1a40504b\n# ╠═0047b980-62cf-11eb-3ca2-ad2f18f0e091\n# ╠═1676307e-62cf-11eb-39e5-bd732850ab2f\n# ╠═343f9c62-62cf-11eb-2d09-cff6967a1d65\n# ╠═5fab01a2-62cf-11eb-1c61-f9da64f9a75f\n# ╟─9a083902-62d2-11eb-2570-bdb7ea1e1f5e\n# ╠═c483fc1c-62d1-11eb-14b6-f50474a58fb2\n# ╠═a9a39152-62d2-11eb-3b4a-5d37f7195f3a\n# ╠═f437e702-62d1-11eb-1ac8-63c7f6ec16c4\n# ╠═8439e2ec-62d2-11eb-3772-d17e099debb5\n# ╠═794c86e6-62d2-11eb-3e27-ebd8a1b3d4e3\n# ╠═cb5e2858-62d1-11eb-1489-037703d411ec\n# ╟─2a8682e2-62d3-11eb-119e-cbd804e1b0b2\n# ╠═a089b976-62d3-11eb-2702-8945a47bf858\n# ╠═3151c634-62d3-11eb-2698-95e4e14aab2d\n# ╠═62e55e4a-62d3-11eb-21e3-7b02354ddd02\n# ╠═786f3d9c-62d3-11eb-28a7-b387242e3760\n# ╟─9531fffe-62d3-11eb-124c-0d2cccea92ae\n", "meta": {"hexsha": "57da0204556bb5b9a973c9c836d43fdc70dc2c12", "size": 22698, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "tutorials/02_Probability.jl", "max_stars_repo_name": "divkakwani/pluto-on-binder", "max_stars_repo_head_hexsha": "185b492fa00e6bc5077f0eb8d04e27722966a4a5", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-13T10:07:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-13T10:07:51.000Z", "max_issues_repo_path": "tutorials/02_Probability.jl", "max_issues_repo_name": "sashedher/iitm-cs6741", "max_issues_repo_head_hexsha": "ff626ceda12486d5885e6cbb1ef0d3d91b2fc392", "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": "tutorials/02_Probability.jl", "max_forks_repo_name": "sashedher/iitm-cs6741", "max_forks_repo_head_hexsha": "ff626ceda12486d5885e6cbb1ef0d3d91b2fc392", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-23T10:15:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-23T10:15:07.000Z", "avg_line_length": 31.4376731302, "max_line_length": 325, "alphanum_fraction": 0.7128821923, "num_tokens": 11861, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045877523148, "lm_q2_score": 0.9019206745523101, "lm_q1q2_score": 0.800188160251472}} {"text": "using StatisticalRethinking\n#gr(size=(600,600));\n\nN = 20\np_grid = range( 0 , stop=1 , length=N )\n\nprior = ones( 20 );\n\nlikelihood = [pdf(Binomial(9, p), 6) for p in p_grid]\nlikelihood[1:5]\n\nunstd_posterior = likelihood .* prior;\n\nposterior = unstd_posterior ./ sum(unstd_posterior);\n\np1 = plot( p_grid , posterior ,\n xlab=\"probability of water\" , ylab=\"posterior probability\",\n lab = \"interpolated\", title=\"20 points\" )\np2 = scatter!( p1, p_grid , posterior, lab=\"computed\" )\n\nprior1 = [p < 0.5 ? 0 : 1 for p in p_grid]\nprior2 = [exp( -5*abs( p - 0.5 ) ) for p in p_grid]\n\np3 = plot(p_grid, prior1,\n xlab=\"probability of water\" , ylab=\"posterior probability\",\n lab = \"semi_uniform\", title=\"Other priors\" )\nscatter!(p3, p_grid, prior1, lab = \"semi_uniform grid point\")\nplot!(p3, p_grid, prior2, lab = \"double_exponential\" )\nscatter!(p3, p_grid, prior2, lab = \"double_exponential grid point\" )\n\n# This file was generated using Literate.jl, https://github.com/fredrikekre/Literate.jl\n\n", "meta": {"hexsha": "7bd1e95b837a23d2ca22a42b251e7ad4abab9acc", "size": 993, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "chapters/02/clip-03-05.jl", "max_stars_repo_name": "UnofficialJuliaMirror/StatisticalRethinking.jl-2d09df54-9d0f-5258-8220-54c2a3d4fbee", "max_stars_repo_head_hexsha": "08ee7b4244edcb2c94f4410829372e7d5082cb7a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/02/clip-03-05.jl", "max_issues_repo_name": "UnofficialJuliaMirror/StatisticalRethinking.jl-2d09df54-9d0f-5258-8220-54c2a3d4fbee", "max_issues_repo_head_hexsha": "08ee7b4244edcb2c94f4410829372e7d5082cb7a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/02/clip-03-05.jl", "max_forks_repo_name": "UnofficialJuliaMirror/StatisticalRethinking.jl-2d09df54-9d0f-5258-8220-54c2a3d4fbee", "max_forks_repo_head_hexsha": "08ee7b4244edcb2c94f4410829372e7d5082cb7a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0909090909, "max_line_length": 87, "alphanum_fraction": 0.6837865055, "num_tokens": 322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.875787001374006, "lm_q1q2_score": 0.8001860226663372}} {"text": "f(x::Vector) = (x[1] - 5.0)^2\nfunction g!(x::Vector, storage::Vector)\n storage[1] = 2.0 * (x[1] - 5.0)\nend\n\ninitial_x = [0.0]\n\nstore_trace, show_trace = false, false\nresults = Optim.naive_gradient_descent(f, g!, initial_x,\n\t 0.1, 10e-8, 1_000,\n\t store_trace, show_trace)\n@assert length(results.trace.states) == 0\n@assert results.converged\n@assert norm(results.minimum - [5.0]) < 0.01\n\nresults = Optim.naive_gradient_descent(f, g!, initial_x)\n@assert length(results.trace.states) == 0\n@assert results.converged\n@assert norm(results.minimum - [5.0]) < 0.01\n\neta = 0.9\n\nf(x::Vector) = (1.0 / 2.0) * (x[1]^2 + eta * x[2]^2)\n\nfunction g!(x::Vector, storage::Vector)\n storage[1] = x[1]\n storage[2] = eta * x[2]\nend\n\nstore_trace, show_trace = true, false\nresults = Optim.naive_gradient_descent(f, g!, [1.0, 1.0],\n\t\t 0.1, 10e-8, 1_000,\n\t store_trace, show_trace)\n@assert length(results.trace.states) > 0\n@assert results.converged\n@assert norm(results.minimum - [0.0, 0.0]) < 0.01\n", "meta": {"hexsha": "628c050e5c46c9cefd4fbede68498ab3975a0f2d", "size": 1113, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/naive_gradient_descent.jl", "max_stars_repo_name": "aviks/Optim.jl", "max_stars_repo_head_hexsha": "9c2a9a88c5b9329ad4233760a6e5331fd6d771e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-05-22T09:32:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-22T09:32:32.000Z", "max_issues_repo_path": "test/naive_gradient_descent.jl", "max_issues_repo_name": "aviks/Optim.jl", "max_issues_repo_head_hexsha": "9c2a9a88c5b9329ad4233760a6e5331fd6d771e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/naive_gradient_descent.jl", "max_forks_repo_name": "aviks/Optim.jl", "max_forks_repo_head_hexsha": "9c2a9a88c5b9329ad4233760a6e5331fd6d771e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0810810811, "max_line_length": 60, "alphanum_fraction": 0.5876010782, "num_tokens": 373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137296, "lm_q2_score": 0.8757869884059266, "lm_q1q2_score": 0.8001860108177073}} {"text": "using DifferentialEquations\nusing Plots\n\n\nfunction sis_ode(du,u,p,t)\n SH,IH,SL,IL = u\n betaHH,betaHL,betaLH,betaLL,gamma=p\n du[1]=-(betaHH*IH+betaHL*IL)*SH+gamma*IH\n du[2]=+(betaHH*IH+betaHL*IL)*SH-gamma*IH\n du[3]=-(betaLH*IH+betaLL*IL)*SL+gamma*IL\n du[4]=+(betaLH*IH+betaLL*IL)*SL-gamma*IL\n end\n\nparms =[10,0.1,0.1,1,1]\ninit=[0.19999,0.00001,0.799,0.001]\ntspan=tspan = (0.0,15.0)\n\nsis_prob = ODEProblem(sis_ode,init,tspan,parms)\nsis_sol = solve(sis_prob,saveat=0.1)\n\nplot(sis_sol,xlabel=\"Time (Years)\",ylabel=\"Proportion of Population\")\n", "meta": {"hexsha": "3d4635ff7c1f6bc98e90fb4c2eb991bc849eeb34", "size": 583, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "models/keeling_rohani_2008/program_3_1_sis.jl", "max_stars_repo_name": "epimodels/epicookbook", "max_stars_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/keeling_rohani_2008/program_3_1_sis.jl", "max_issues_repo_name": "epimodels/epicookbook", "max_issues_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/keeling_rohani_2008/program_3_1_sis.jl", "max_forks_repo_name": "epimodels/epicookbook", "max_forks_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-10T12:46:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-10T12:46:31.000Z", "avg_line_length": 26.5, "max_line_length": 69, "alphanum_fraction": 0.6569468268, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992942089574, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.8001737619952257}} {"text": "# OLS estimation using (\\)\n# https://github.com/giob1994/Alistair.jl/blob/3a11c19150169695581b46e4d1895f0641a4c29d/src/linregress.jl#L38-L41\nfunction ols(X, Y)\n # Ax = B\n # x = B \\ A \n # https://github.com/JuliaLang/julia/blob/d789231e9985537686052db9b2314c0d51656308/stdlib/LinearAlgebra/src/generic.jl#L827-L855\n return (X' * X) \\ (X' * Y)\nend \n\n# OLS estimation using inv() \n# inv() is a more computationally-intensive procedure than \\ operator\n# https://github.com/mcreel/Econometrics/blob/b29cffa8ce7f845fa73788522f9c7753d40684f4/Examples/OLS/OlsFit.jl#L13-L14\nfunction ols_(X, Y)\n return inv(X'*X)*X'*Y\nend\n", "meta": {"hexsha": "e7d686901b79e18bc83c07d595d25c8d8f9c3def", "size": 628, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/src/lm.jl", "max_stars_repo_name": "epogrebnyak/multiple-regression-revisited", "max_stars_repo_head_hexsha": "8881d5a8cab31693d3ca652b3e96c6fbbaf318b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-11-26T17:11:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-02T07:06:56.000Z", "max_issues_repo_path": "julia/src/lm.jl", "max_issues_repo_name": "epogrebnyak/multiple-regression-revisited", "max_issues_repo_head_hexsha": "8881d5a8cab31693d3ca652b3e96c6fbbaf318b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "julia/src/lm.jl", "max_forks_repo_name": "epogrebnyak/multiple-regression-revisited", "max_forks_repo_head_hexsha": "8881d5a8cab31693d3ca652b3e96c6fbbaf318b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-02T07:06:57.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-02T07:06:57.000Z", "avg_line_length": 39.25, "max_line_length": 132, "alphanum_fraction": 0.7404458599, "num_tokens": 242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545348152283, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.8001429702566997}} {"text": "using Symbolics, SymbolicUtils\nusing SymbolicUtils: istree, operation, arguments\nusing Symbolics: value, get_variables, solve_for, derivative\nusing SymbolicUtils.Rewriters\nusing SymbolicUtils.Code\n\n\"\"\"\n sym_taylor generates a Taylor series on variable x to order n and at\n point x₀, i.e., Σ aᵢ*(x - x₀)ⁱ\n\"\"\"\nfunction sym_taylor(x, n, x₀=0)\n x = value(x)\n @variables a[0:n]\n a = value.(a)\n a[1] + sum([a[i+1]*(x-x₀)^i for i = 1:n])\nend\n\n\"\"\"\n sym_frobenius generates a Frobenius series on variable x to order n and at\n point x₀, i.e., (x - x₀)^α Σ aᵢ*(x - x₀)ⁱ\n\"\"\"\nfunction sym_frobenius(x, n, x₀=0)\n x = value(x)\n @variables a[0:n]\n a = value.(a)\n @syms α\n (x-x₀)^α * sym_taylor(x, n, x₀)\nend\n\n# pox (power-of-x) is a symbolic function to keep track of the powers of x\n# pox(k,n) means k*x^n\n@syms pox(k, n)\n\nis_pox(x) = istree(x) && operation(x)==pox\nis_not_pox(x) = !is_pox(x)\n\nget_coef(p) = is_pox(p) ? arguments(p)[1] : p\nget_power(p) = is_pox(p) ? arguments(p)[2] : 0\n\nreplace_x(eq, x) = substitute(eq, Dict(x => pox(1,1)))\n\ncount_rule1 = @rule ^(pox(~k, ~n1), ~n2) => isequal(~k,1) ? pox(1, ~n1 * ~n2) : pox(^(~k,~n2), ~n1 * ~n2)\ncount_rule2 = @rule pox(~k1, ~n1) * pox(~k2, ~n2) => pox(~k1 * ~k2, ~n1 + ~n2)\ncount_rule3 = @acrule pox(~k, ~n) * ~u::is_not_pox => pox(~k * ~u, ~n)\n\n\"\"\"\n collect_powers separates the powers of x in eq (a polynomial) and returns\n a dictionary of power => term\n\"\"\"\nfunction collect_powers(eq, x)\n eq = expand(expand_derivatives(eq))\n eq = replace_x(eq, x)\n #eq = Prewalk(PassThrough(count_rule1))(eq)\n eq = Fixpoint(Prewalk(PassThrough(Chain([count_rule1, count_rule2, count_rule3]))))(eq)\n\n if !istree(eq)\n return Dict{Any, Any}(0 => eq)\n elseif is_pox(eq)\n return Dict{Any, Any}(get_power(eq) => get_coef(eq))\n else\n eqs = Dict{Any, Any}()\n\n for term in arguments(eq)\n n = get_power(term)\n if haskey(eqs, n)\n eqs[n] = eqs[n] + get_coef(term)\n else\n eqs[n] = get_coef(term)\n end\n end\n\n return eqs\n end\nend\n\n\"\"\"\n strip_powers removes the powers from the output of collect_powers\n and returns a sorted list of terms/sub-equations\n\"\"\"\nfunction strip_powers(eqs)\n @syms α\n d = Dict(α => 0)\n eqs = Dict(substitute(power, d) => eq for (power, eq) in eqs)\n collect(values(sort(eqs)))\nend\n\n\"\"\"\n solve_rational gets a triangular system of linear equations and solve\n for the variables one by one starting from the first equation\n\n eqs is a list of terms as prepared by strip_powers\n\n solve_rational tries to generate rational results but falls back to reals\n if not possible\n\"\"\"\nfunction solve_rational(eqs)\n eqs = Num.(eqs)\n vals = Dict()\n\n for eq in eqs\n vars = get_variables(eq)\n vars = filter(x -> !haskey(vals,x), vars)\n\n if length(vars) > 0\n dep = vars[end]\n eq = substitute(eq, vals)\n # the last variable of each eq is considered the dependent variable\n A = value(substitute(eq, Dict(dep => 0)))\n B = value(substitute(eq, Dict(dep => 1)))\n try\n vals[dep] = A // (B - A)\n catch\n vals[dep] = A / (B - A)\n end\n end\n end\n\n vals\nend\n\n\"\"\"\n finalize_taylor substitutes the calculated coefficients back into the\n original Taylor or Frobenius series\n\"\"\"\nfunction finalize_taylor(x, y, vals)\n u = substitute(y, vals)\n vars = [v for v in get_variables(y) if !isequal(v,x)]\n factor(u, vars)\nend\n\n\"\"\"\n A main entry point\n solve_taylor solves a Taylor series expansion of a linear differential equation\n\n x is the independent variable (a Symbolic Sym)\n y is the dependent variable (a Symbolic Sym)\n diffeq is the differential equation, assuming diffeq ~ 0\n\"\"\"\nfunction solve_taylor(x, y, diffeq)\n eqs = strip_powers(collect_powers(diffeq, x))\n vals = solve_rational(eqs)\n finalize_taylor(x, y, vals)\nend\n\n\"\"\"\n A main entry point\n solve_frobenius solves a Frobenius series expansion of a linear differential equation\n\n x is the independent variable (a Symbolic Sym)\n y is the dependent variable (a Symbolic Sym)\n diffeq is the differential equation, assuming diffeq ~ 0\n\"\"\"\nfunction solve_frobenius(x, y, diffeq; abstol=1e-8, rationalize_coef=false)\n eqs = strip_powers(collect_powers(diffeq, x))\n eq = eqs[1]\n @syms α\n d = Dict(v => 1 for v in get_variables(eq) if !isequal(v, α))\n\n rs, zs = find_roots(substitute(eq, d), α)\n isempty(rs) && error(\"The indicial equation has no real root\")\n α₁ = rs[end]\n @info \"α is $α₁\"\n\n d = Dict(α => α₁)\n eqs = [substitute(eq,d) for eq in eqs]\n vals = solve_rational(eqs[2:end])\n if rationalize_coef\n vals = rationalize(vals)\n end\n vals[α] = α₁\n finalize_taylor(x, y, vals)\nend\n\n###############################################################################\n\n\"\"\"\n factor factors a polynomial eq over a list of variables (vars)\n it assumes trivial separatibilty\n\"\"\"\nfunction factor(eq, vars)\n f = []\n for v in vars\n d = Dict(u => (isequal(v,u) ? 1 : 0) for u in vars)\n push!(f, v * substitute(eq, d))\n end\n\n +(f...)\nend\n\n\"\"\"\n solve_newton is a symbolic Newton-Ralphson solver\n f is a symbolic equation to be solved (f ~ 0)\n x is the variable to solve\n x₀ is the initial guess\n\"\"\"\nfunction solve_newton(f, x, x₀; abstol=1e-8, maxiter=50)\n xₙ = Complex(x₀)\n ∂f = value(derivative(f, x))\n\n for i = 1:maxiter\n d = Dict(x => xₙ)\n xₙ₊₁ = xₙ - substitute(f, d) / substitute(∂f, d)\n if abs(xₙ₊₁ - xₙ) < abstol\n return xₙ₊₁\n else\n xₙ = xₙ₊₁\n end\n end\n return xₙ\nend\n\n\"\"\"\n poly_degree returns the degree of a polynomial equation eq\n\"\"\"\nfunction poly_degree(poly, x)\n eqs = collect_powers(poly, x)\n round(Int, maximum(keys(eqs)))\nend\n\n\"\"\"\n find_roots returns all the real and complex roots of a polynomial (poly)\n for variable x\n\n the output is rs, sz, where rs is a list of real roots and zs is a list of\n complex roots\n\n if poly is not a polynomial, the number of desired roots (n) needs to be\n provided. For example, find_roots(sin(x), x, 10) returns 10 different, but\n not necessarily sequential, multiples of π\n\"\"\"\nfunction find_roots(poly, x, n=-1; abstol=1e-8)\n n = (n == -1 ? poly_degree(poly, x) : n)\n\n rs = Float64[]\n zs = Complex[]\n\n while n > 0\n z = solve_newton(poly, x, Complex(rand(),rand()))\n if abs(imag(z)) < abstol\n r = real(z)\n push!(rs, r)\n poly = poly / (x - r)\n n -= 1\n else\n append!(zs, [z, conj(z)])\n poly = poly / ((x-z)*(x-conj(z)))\n n -= 2\n end\n end\n sort(rs), zs\nend\n\n##############################################################################\n\nfunction continued_fraction(x, n; abstol=1e-8)\n try\n l = zeros(Int, n)\n for i = 1:n\n l[i] = floor(Int, x)\n Δx = x - l[i]\n Δx < abstol && break\n x = 1 / Δx\n end\n y = 0\n for i = n:-1:1\n if l[i] + y > 0\n y = 1 // (l[i] + y)\n end\n end\n return 1 // y\n catch\n return x\n end\nend\n\nfunction float_to_rational(x; n=10, abstol=1e-8)\n s = x < 0\n y = continued_fraction(abs(x), n) * (s ? -1 : +1)\n if abs(x - y) < abstol\n return y\n else\n return x\n end\nend\n\n# function rationalize(vals)\n# r = Dict()\n# for p in vals\n# eq = last(p)\n# vars = get_variables(eq)\n# if length(vars) == 1\n# var = vars[1]\n# eq = eq / var\n# if !(eq isa Int) || !(eq isa Rational)\n# eq = float_to_rational(eq)\n# end\n# r[first(p)] = eq * var\n# else\n# r[first(p)] = eq\n# end\n# end\n# r\n# end\n\n################################### Examples! #################################\n\nfunction test_harmonic()\n @syms x\n y = sym_taylor(x, 10)\n D = Differential(x)\n solve_taylor(x, y, D(D(y)) + y)\nend\n\nfunction test_airy()\n @syms x\n y = sym_taylor(x, 10)\n D = Differential(x)\n solve_taylor(x, y, D(D(y)) + x*y)\nend\n\nfunction test_bessel(ν = sqrt(2); rationalize_coef=false)\n @syms x\n y = sym_frobenius(x, 10)\n D = Differential(x)\n solve_frobenius(x, y, x^2 * D(D(y)) + x * D(y) - (x^2 + ν^2)*y; rationalize_coef=rationalize_coef)\nend\n", "meta": {"hexsha": "f5a82aed56cdb9e2c1849395d48a9aabbd453f2d", "size": 8610, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/taylor.jl", "max_stars_repo_name": "siravan/SymPertExamples.jl", "max_stars_repo_head_hexsha": "9f074eaf6e2df013622ac31cb555411202acec9f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2021-05-19T15:48:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T23:12:04.000Z", "max_issues_repo_path": "src/taylor.jl", "max_issues_repo_name": "siravan/SymPertExamples.jl", "max_issues_repo_head_hexsha": "9f074eaf6e2df013622ac31cb555411202acec9f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/taylor.jl", "max_forks_repo_name": "siravan/SymPertExamples.jl", "max_forks_repo_head_hexsha": "9f074eaf6e2df013622ac31cb555411202acec9f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3302752294, "max_line_length": 105, "alphanum_fraction": 0.5619047619, "num_tokens": 2640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545274901876, "lm_q2_score": 0.8438951104066295, "lm_q1q2_score": 0.8001429696588774}} {"text": "using IterativeSolvers\n\nA = Float64[\n 16 4 8;\n 4 5 -4;\n 8 -4 22;\n]\na = Float64[16; 18; -22]\nx = Float64[1; 1; 1]\n\nmaxiters = 100\nprintln(\"\\nJacobi:\")\nfor i in 1:100\n res = jacobi!(x, A, a, tol=1.0e-8, maxiter=1)\n if i < 5 || i in [1; 10:10:maxiters]\n println([i x'])\n end\n if res[2].isconverged\n println([i x'])\n break\n end\nend\n\nprintln(\"\\nGauss-Seidel:\")\n@show A * x\nprintln()\n\nx = Float64[1; 1; 1]\nfor i in 1:100\n res = gauss_seidel!(x, A, a, tol=1.0e-8, maxiter=1)\n if i < 5 || i in [1; 10:10:maxiters]\n println([i x'])\n end\n if res[2].isconverged\n println([i x'])\n break\n end\nend\n\nprintln(\"\\nSequential Succesive Over-Relaxation:\")\n@show A * x\nprintln()\n\nx = Float64[1; 1; 1]\nω = 1.0\nfor i in 1:100\n res = ssor!(x, A, a, ω, tol=1.0e-8, maxiter=1)\n if i < 5 || i in [1; 10:10:maxiters]\n println([i x'])\n end\n if res[2].isconverged\n println([i x'])\n break\n end\nend\n\nprintln()\nA * x\n", "meta": {"hexsha": "3f33ab0d3fe0c9949f32ccd26b8df00ed6f2eab4", "size": 930, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/ch02/ex_jacobi.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_jacobi.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_jacobi.jl", "max_forks_repo_name": "OVGULIU/NumericalMethodsforEngineers.jl", "max_forks_repo_head_hexsha": "7ca0b79965a7abd58af29d8dfd1870a954fb3aec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.7627118644, "max_line_length": 53, "alphanum_fraction": 0.5731182796, "num_tokens": 418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545304202039, "lm_q2_score": 0.8438950966654772, "lm_q1q2_score": 0.8001429591027681}} {"text": "struct InvertibleScalarFunction{S,T}\n f::S\n f⁻¹::T\nend\n\nfunction Base.:∘(isf1::InvertibleScalarFunction, isf2::InvertibleScalarFunction)\n f = isf1.f ∘ isf2.f\n f⁻¹ = isf2.f⁻¹ ∘ isf1.f⁻¹\n return InvertibleScalarFunction(f, f⁻¹)\nend\n\n(isf::InvertibleScalarFunction)(x) = isf.f(x)\n\nfunction Base.inv(isf::InvertibleScalarFunction)\n f, f⁻¹ = isf.f, isf.f⁻¹\n return InvertibleScalarFunction(f⁻¹, f)\nend\n\nconst RealVector = AbstractVector{<:Real}\n\nis_constant(column::RealVector) = maximum(column) == minimum(column)\n\nfunction binner(column::RealVector, bins::RealVector)\n rtol = 1.0e-5\n atol = 1.0e-8\n eps = @. atol + rtol * abs(column)\n return searchsortedfirst.(Ref(bins), column + eps) .- 1\nend\n\nfunction uniform_binner(column::RealVector, num_bins::Integer)\n if is_constant(column)\n return ones(Int46, length(column))\n end\n col_min = minimum(column)\n col_max = maximum(column)\n bins = range(col_min, stop = col_max, length = num_bins)\n return binner(column, bins)\nend\n\nfunction quantile_binner(column::RealVector, num_bins::Integer)\n bins = range(0, stop=1, length=num_bins)\n return binner(column, quantile(column, bins)) \nend\n\nfunction log_scaler(_::RealVector)\n return InvertibleScalarFunction(log, exp)\nend\n\nfunction logistic_scaler(_::RealVector)\n sigmoid(x::T) where {T<:Real} = one(T) / (one(T) + exp(-x))\n logit(x::T) where {T<:Real} = log(x / (one(T) - x))\n return InvertibleScalarFunction(sigmoid, logit)\nend\n\nfunction min_max_scaler(column::RealVector, range::RealVector = [0, 1])\n max_val = maximum(column)\n min_val = minimum(column)\n min_range, max_range = range[1], range[2]\n f(x) = (x - min_val) / (max_val - min_val) * (max_range - min_range) + min_range\n f⁻¹(y) = (y - min_range) * (max_val - min_val) / (max_range - min_range) + min_val\n return InvertibleScalarFunction(f, f⁻¹)\nend\n\nfunction max_abs_scaler(column::RealVector)\n max_val = maximum([maximum(column), abs(minimum(column))])\n f(x) = x / max_val\n f⁻¹(y) = y * max_val\n return InvertibleScalarFunction(f, f⁻¹)\nend\n\nfunction standardizer(column::RealVector)\n m = mean(column)\n s = std(column)\n f(x) = (x - m) / s\n f⁻¹(y) = y * s + m\n return InvertibleScalarFunction(f, f⁻¹)\nend\n\n", "meta": {"hexsha": "34ee4822b8b44eacf3df72565c6b78cf6ad907a8", "size": 2277, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/pipeline/preprocess.jl", "max_stars_repo_name": "Alba-Intelligence/DataVisualization.jl", "max_stars_repo_head_hexsha": "8659d60697d2a6167199f59c4997c1c38ce62915", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-09-23T19:37:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-07T22:44:39.000Z", "max_issues_repo_path": "src/pipeline/preprocess.jl", "max_issues_repo_name": "Alba-Intelligence/DataVisualization.jl", "max_issues_repo_head_hexsha": "8659d60697d2a6167199f59c4997c1c38ce62915", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2021-11-18T17:36:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-01T10:55:23.000Z", "max_forks_repo_path": "src/pipeline/preprocess.jl", "max_forks_repo_name": "Alba-Intelligence/DataVisualization.jl", "max_forks_repo_head_hexsha": "8659d60697d2a6167199f59c4997c1c38ce62915", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-11-22T09:47:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-09T16:53:25.000Z", "avg_line_length": 28.8227848101, "max_line_length": 86, "alphanum_fraction": 0.6767676768, "num_tokens": 738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.945801267121407, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.8000934346283356}} {"text": "abstract type Shape end\n\nstruct Ellipse{T} <: Shape\n x::T\n y::T\n A::T\n B::T\n α::T\n ρ::T\nend\n\nfunction isinside(e::Ellipse, x, y)\n # https://stackoverflow.com/questions/7946187/point-and-ellipse-rotated-position-test-algorithm\n (cosd(e.α) * (x - e.x) + sind(e.α) * (y - e.y))^2 / e.A^2 +\n (sind(e.α) * (x - e.x) - cosd(e.α) * (y - e.y))^2 / e.B^2 ≤ one(x)\nend\n\nfunction projection(e::Ellipse, θᵢ, tᵢ)\n # p. 56\n s = √(e.x^2 + e.y^2)\n γ = atan(e.y, e.x)\n θ = θᵢ - deg2rad(e.α)\n t = tᵢ - s * cos(γ - θᵢ)\n a²θ = e.A^2 * cos(θ)^2 + e.B^2 * sin(θ)^2\n abs(t) ≤ √(a²θ) ? 2 * e.ρ * e.A * e.B * √(a²θ - t^2) / a²θ : zero(a²θ)\nend\n\nfunction projection(\n ellipses::AbstractVector{<:Ellipse},\n θ::AbstractVector,\n t::AbstractVector,\n)\n [sum(projection(e, θᵢ, tᵢ) for e in ellipses) for tᵢ in t, θᵢ in θ]\nend\n\n# Table 3.1 summary of parameters for tomography simulations\nSheppLoganPhantom = [\n Ellipse(0.0, 0.0, 0.92, 0.69, 90.0, 2.0),\n Ellipse(0.0, -0.0184, 0.874, 0.6624, 90.0, -0.98),\n Ellipse(0.22, 0.0, 0.31, 0.11, 72.0, -0.02),\n Ellipse(-0.22, 0.0, 0.41, 0.16, 108.0, -0.02),\n Ellipse(0.0, 0.35, 0.25, 0.21, 90.0, 0.01),\n Ellipse(0.0, 0.1, 0.046, 0.046, 0.0, 0.01),\n Ellipse(0.0, -0.1, 0.046, 0.046, 0.0, 0.01),\n Ellipse(-0.08, -0.605, 0.046, 0.023, 0.0, 0.01),\n Ellipse(0.0, -0.605, 0.023, 0.023, 0.0, 0.01),\n Ellipse(0.06, -0.605, 0.046, 0.023, 90.0, 0.01),\n]\n\nfunction construct(ellipses::AbstractVector{<:Ellipse}, N::Integer)\n f = zeros(N, N)\n for (i, xᵢ) in enumerate(range(-1, 1, length = N)),\n (j, yⱼ) in enumerate(range(-1, 1, length = N))\n\n @inbounds f[j, i] = sum([isinside(e, xᵢ, yⱼ) ? e.ρ : zero(e.ρ) for e in ellipses])\n end\n f\nend\n", "meta": {"hexsha": "1564ade2c59583eb22041bebd03bf8fa4d9af83c", "size": 1753, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lineintegralsandprojections.jl", "max_stars_repo_name": "kczimm/PrinciplesCTImaging.jl", "max_stars_repo_head_hexsha": "de06f89d421af5b9cfa38ebc0a45d81f05a33d9d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lineintegralsandprojections.jl", "max_issues_repo_name": "kczimm/PrinciplesCTImaging.jl", "max_issues_repo_head_hexsha": "de06f89d421af5b9cfa38ebc0a45d81f05a33d9d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lineintegralsandprojections.jl", "max_forks_repo_name": "kczimm/PrinciplesCTImaging.jl", "max_forks_repo_head_hexsha": "de06f89d421af5b9cfa38ebc0a45d81f05a33d9d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7118644068, "max_line_length": 99, "alphanum_fraction": 0.5447803765, "num_tokens": 870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109770159683, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.8000803321099138}} {"text": "\nfunction Integrate(f, x0, tspan, N, M, tol, imax)\n\n # Get length of state vector\n L = length(x0)\n\n # Transformation of independant variable\n ω₁ = 0.5*(tspan[2] + tspan[1])\n ω₂ = 0.5*(tspan[2] - tspan[1])\n\n g(τ,x) = ω₂*f(ω₁ + ω₂*τ,x)\n\n # Compute Chebyshev-Gauss-Lobatto Nodes\n τs = SizedVector{M + 1}(zeros(M + 1))\n @inbounds for j in 0:M\n τs[j + 1] = -cos(j*π/M)\n end\n\n # Compute constant matricies\n Cx = SizedMatrix{M + 1, N + 1}(zeros(M + 1, N + 1))\n ChebyshevInterpMat!(Cx, τs)\n CI1 = SizedMatrix{N + 1, N}(zeros(N + 1, N))\n initCI1!(CI1)\n Cf = SizedMatrix{N, M + 1}(zeros(N, M + 1))\n initCf!(Cf, τs)\n C = SizedMatrix{N + 1, M + 1}(zeros(N + 1, M + 1))\n mul!(C, CI1, Cf)\n\n # Initialize required matricies\n Xold = SizedMatrix{M + 1, L}(zeros(M + 1, L))\n XoldT = Xold'\n Xnew = SizedMatrix{M + 1, L}(zeros(M + 1, L))\n X0 = SizedMatrix{N + 1, L}(zeros(N + 1, L))\n X0[1,:] .= x0\n G = SizedMatrix{M + 1, L}(zeros(M + 1, L))\n β = SizedMatrix{N + 1, L}(zeros(N + 1, L))\n\n # Set Initial Guess for Xold (Could provide as input in future)\n Xold[1,:] .= x0\n\n # Begin integration loop\n stop = false\n eold = Inf\n enew = Inf\n iter = 0\n while !stop\n iter += 1\n println(iter)\n\n # Compute forcing function\n @inbounds for i in 1:M+1\n L == 1 ? G[i,1] = g(τs[i], Xold[i]) :\n G[i,:] .= g(τs[i], @view(XoldT[:, i]))\n end\n\n # Update Coefficients\n #β = X0 + C*G\n mul!(β,C,G)\n β .= β + X0\n\n # Update State\n #Xnew = Cx*β\n mul!(Xnew, Cx, β)\n\n # Compute error\n enew = 0\n for col in 1:L\n for row in 1:M+1\n temp = Xnew[row,col] - Xold[row,col]\n if temp > enew\n enew = temp\n end\n end\n end\n\n if (enew <= tol && eold <= tol) || iter >= imax\n stop = true\n else\n Xold .= Xnew\n eold = enew\n end\n end\n\n return (ω₁ .+ ω₂*τs, Xnew)\nend\n\nfunction initCI1!(CI1)\n # Get N\n dims = size(CI1)\n N = dims[2]\n\n # Initialize R and S\n R = Diagonal(SizedVector{N + 1}(zeros(N + 1)))\n S = SizedMatrix{N + 1, N}(zeros(N + 1, N))\n\n # Fill Matricies\n R[1,1] = 1\n R[2,2] = 0.5\n S[1,1] = 1\n S[1,2] = -0.25\n S[2,1] = 2\n S[2,3] = -1\n @inbounds for i in 3:N + 1\n R[i,i] = 1/(2*(i - 1))\n S[i,i - 1] = 1\n if i < N\n S[i,i + 1] = -1\n end\n if i < N + 1\n S[1,i] = (1/(2*(i - 2)) - 1/(2*i))*(-1)^i\n end\n end\n\n # Fill CI1\n #CI1 .= R*S\n lmul!(R,S)\n CI1 .= S\nend\n\nfunction initCf!(Cf, τs)\n # Get N and M\n dims = size(Cf)\n N = dims[1]\n M = dims[2] - 1\n\n # Set p variable depending on number of nodes and check Cf size for validity\n p = 1\n if M > N\n p = 2\n elseif N > M\n throw(ArgumentError(\"Improper size of Cf matrix!\"))\n end\n\n # Initialize temporary matricies\n V = Diagonal(SizedVector{N}(zeros(N)))\n W = Diagonal(SizedVector{M + 1}(zeros(M + 1)))\n Tm = SizedMatrix{N, M + 1}(zeros(N, M + 1))\n\n # Fill T\n T!(Tm, τs)\n\n # Fill V\n @inbounds for i in 1:N\n # Get numerator\n i == 1 ? num = 1 : i == N ? num = p : num = 2\n\n # Set value\n V[i, i] = num/M\n end\n\n # Fill W\n @inbounds for i in 1:M + 1\n # Get val\n i == 1 ? val = 0.5 : i == M + 1 ? val = 0.5 : val = 1\n\n # Set value\n W[i, i] = val\n end\n\n # Compute Cf\n #Cf .= V*Tm*W\n rmul!(Tm,W)\n lmul!(V,Tm)\n Cf .= Tm\nend\n", "meta": {"hexsha": "8cd6f8b07347a8bb86ebf2999295a3b4c2f27fe5", "size": 3687, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Integrator.jl", "max_stars_repo_name": "GrantHecht/ChebyshevPicardIteration.jl", "max_stars_repo_head_hexsha": "ed788d91dcc7adf8db9fae46ce4d16a6b7c0d47c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-15T01:49:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-15T01:49:52.000Z", "max_issues_repo_path": "src/Integrator.jl", "max_issues_repo_name": "GrantHecht/ChebyshevPicardIteration.jl", "max_issues_repo_head_hexsha": "ed788d91dcc7adf8db9fae46ce4d16a6b7c0d47c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Integrator.jl", "max_forks_repo_name": "GrantHecht/ChebyshevPicardIteration.jl", "max_forks_repo_head_hexsha": "ed788d91dcc7adf8db9fae46ce4d16a6b7c0d47c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2108433735, "max_line_length": 80, "alphanum_fraction": 0.4564686737, "num_tokens": 1435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109756113861, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.8000803309275004}} {"text": "# This file is part of the IntervalArithmetic.jl package; MIT licensed\n\n# Intersection\n\"\"\"\n intersect(a, b)\n ∩(a,b)\n\nReturns the intersection of the intervals `a` and `b`, considered as\n(extended) sets of real numbers. That is, the set that contains\nthe points common in `a` and `b`.\n\"\"\"\nintersect(a::Interval{T}, b::Interval{T}) where T =\n isdisjoint(a, b) ? emptyinterval(T) : unsafe_interval(max(a.lo, b.lo), min(a.hi, b.hi))\n# Specific promotion rule for intersect:\nintersect(a::Interval{T}, b::Interval{S}) where {T,S} =\n intersect(promote(a, b)...)\nintersect(::ValidInterval{T}, ::ValidInterval{T}) where T = emptyinterval(T)\n\n## Hull\n\"\"\"\n hull(a, b)\n\nReturns the \"interval hull\" of the intervals `a` and `b`, considered as\n(extended) sets of real numbers, i.e. the smallest interval that contains\nall of `a` and `b`.\n\"\"\"\nhull(a::Interval{T}, b::Interval{T}) where T =\n unsafe_interval(min(a.lo, b.lo), max(a.hi, b.hi))\nhull(::EmptyInterval{T}, b::Interval{T}) where T = b\nhull(a::Interval{T}, ::EmptyInterval{T}) where T = a\nhull(::EmptyInterval{T}, ::EmptyInterval{S}) where {T, S} =\n emptyinterval(promote_type(T, S))\n", "meta": {"hexsha": "376069f6e219f8ecc8d9b2100e2c2e00b0d5beaa", "size": 1148, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/operations/set_operations.jl", "max_stars_repo_name": "gwater/IntervalArithmetic.jl", "max_stars_repo_head_hexsha": "0967cbbbaf455af5043bc197139dd0e4c2b40204", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/operations/set_operations.jl", "max_issues_repo_name": "gwater/IntervalArithmetic.jl", "max_issues_repo_head_hexsha": "0967cbbbaf455af5043bc197139dd0e4c2b40204", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/operations/set_operations.jl", "max_forks_repo_name": "gwater/IntervalArithmetic.jl", "max_forks_repo_head_hexsha": "0967cbbbaf455af5043bc197139dd0e4c2b40204", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7878787879, "max_line_length": 91, "alphanum_fraction": 0.6742160279, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350352, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.8000048310744915}} {"text": "# Mutual Information\n\nfunction _mutualinfo(A::AbstractMatrix{<:Integer}, normed::Bool)\n N = sum(A)\n (N == 0.0) && return 0.0\n\n rows = sum(A, dims=2)\n cols = sum(A, dims=1)\n entA = entropy(A)\n entArows = entropy(rows)\n entAcols = entropy(cols)\n\n hck = (entA - entAcols)/N\n hc = entArows/N + log(N)\n hk = entAcols/N + log(N)\n\n mi = hc - hck\n return if normed\n 2*mi/(hc+hk)\n else\n mi\n end\nend\n\n\"\"\"\n mutualinfo(a, b; normed=true) -> Float64\n\nCompute the *mutual information* between the two clusterings of the same\ndata points.\n\n`a` and `b` can be either [`ClusteringResult`](@ref) instances or\nassignments vectors (`AbstractVector{<:Integer}`).\n\nIf `normed` parameter is `true` the return value is the normalized mutual information (symmetric uncertainty),\nsee \"Data Mining Practical Machine Tools and Techniques\", Witten & Frank 2005.\n\n# References\n> Vinh, Epps, and Bailey, (2009). “Information theoretic measures for clusterings comparison”.\nProceedings of the 26th Annual International Conference on Machine Learning - ICML ‘09.\n\"\"\"\nmutualinfo(a, b; normed::Bool=true) = _mutualinfo(counts(a, b), normed)\n", "meta": {"hexsha": "f50a7e4fcc80b3c4e1d4e86c91026f5cc421bfc4", "size": 1165, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/mutualinfo.jl", "max_stars_repo_name": "MartaVanin/Clustering.jl", "max_stars_repo_head_hexsha": "fd96212b77bea5c4520e05f8a8a14b5d7ea93415", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 265, "max_stars_repo_stars_event_min_datetime": "2015-01-04T00:38:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T12:24:29.000Z", "max_issues_repo_path": "src/mutualinfo.jl", "max_issues_repo_name": "MartaVanin/Clustering.jl", "max_issues_repo_head_hexsha": "fd96212b77bea5c4520e05f8a8a14b5d7ea93415", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 161, "max_issues_repo_issues_event_min_datetime": "2015-01-22T12:09:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-06T16:52:24.000Z", "max_forks_repo_path": "src/mutualinfo.jl", "max_forks_repo_name": "MartaVanin/Clustering.jl", "max_forks_repo_head_hexsha": "fd96212b77bea5c4520e05f8a8a14b5d7ea93415", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 115, "max_forks_repo_forks_event_min_datetime": "2015-01-25T18:14:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T03:51:06.000Z", "avg_line_length": 27.7380952381, "max_line_length": 110, "alphanum_fraction": 0.6755364807, "num_tokens": 342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248140158416, "lm_q2_score": 0.8519527963298946, "lm_q1q2_score": 0.8000048161239555}}