AutoMathText / data /code /julia /0.10-0.15.jsonl
March07's picture
add batch 4/5 (200 files)
5697766 verified
Raw
History Blame Contribute Delete
498 kB
{"text": "### A Pluto.jl notebook ###\n# v0.14.2\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n quote\n local el = $(esc(element))\n global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n el\n end\nend\n\n# ╔═╡ a4937996-f314-11ea-2ff9-615c888afaa8\nbegin\n import Pkg\n Pkg.activate(mktempdir())\n Pkg.add([\n Pkg.PackageSpec(name=\"Images\", version=\"0.23\"),\n Pkg.PackageSpec(name=\"ImageMagick\", version=\"1\"),\n Pkg.PackageSpec(name=\"TestImages\", version=\"1\"),\n Pkg.PackageSpec(name=\"ImageFiltering\", version=\"0.6\"),\n Pkg.PackageSpec(name=\"PlutoUI\", version=\"0.7\"),\n Pkg.PackageSpec(name=\"BenchmarkTools\", version=\"0.6\"),\n ])\n using Images, TestImages, ImageFiltering, Statistics, PlutoUI, BenchmarkTools\nend\n\n# ╔═╡ e6b6760a-f37f-11ea-3ae1-65443ef5a81a\nmd\"_homework 3, version 3_\"\n\n# ╔═╡ 85cfbd10-f384-11ea-31dc-b5693630a4c5\nmd\"\"\"\n\n# **Homework 4**: _Dynamic programming_\n`18.S191`, Spring 2021\n\nThis notebook contains _built-in, live answer checks_! In some exercises you will see a coloured box, which runs a test case on your code, and provides feedback based on the result. Simply edit the code, run it, and the check runs again.\n\n_For MIT students:_ there will also be some additional (secret) test cases that will be run as part of the grading process, and we will look at your notebook and write comments.\n\nFeel free to ask questions!\n\"\"\"\n\n# ╔═╡ 33e43c7c-f381-11ea-3abc-c942327456b1\n# edit the code below to set your name and kerberos ID (i.e. email without @mit.edu)\n\nstudent = (name = \"Vidhi Katkoria\", kerberos_id = \"vidhi\")\n\n# you might need to wait until all other cells in this notebook have completed running. \n# scroll around the page to see what's up\n\n# ╔═╡ ec66314e-f37f-11ea-0af4-31da0584e881\nmd\"\"\"\n\nSubmission by: **_$(student.name)_** ($(student.kerberos_id)@mit.edu)\n\"\"\"\n\n# ╔═╡ 938185ec-f384-11ea-21dc-b56b7469f798\nmd\"\"\"\n#### Intializing packages\n_When running this notebook for the first time, this could take up to 15 minutes. Hang in there!_\n\"\"\"\n\n# ╔═╡ 0f271e1d-ae16-4eeb-a8a8-37951c70ba31\nall_image_urls = [\n\t\"https://wisetoast.com/wp-content/uploads/2015/10/The-Persistence-of-Memory-salvador-deli-painting.jpg\" => \"Salvador Dali — The Persistence of Memory (replica)\",\n\t\"https://i.imgur.com/4SRnmkj.png\" => \"Frida Kahlo — The Bride Frightened at Seeing Life Opened\",\n\t\"https://upload.wikimedia.org/wikipedia/commons/thumb/5/5b/Hilma_af_Klint_-_Group_IX_SUW%2C_The_Swan_No._1_%2813947%29.jpg/477px-Hilma_af_Klint_-_Group_IX_SUW%2C_The_Swan_No._1_%2813947%29.jpg\" => \"Hilma Klint - The Swan No. 1\",\n\t\"https://upload.wikimedia.org/wikipedia/commons/thumb/a/a4/Piet_Mondriaan%2C_1930_-_Mondrian_Composition_II_in_Red%2C_Blue%2C_and_Yellow.jpg/300px-Piet_Mondriaan%2C_1930_-_Mondrian_Composition_II_in_Red%2C_Blue%2C_and_Yellow.jpg\" => \"Piet Mondriaan - Composition with Red, Blue and Yellow\",\n\t\"https://user-images.githubusercontent.com/6933510/110993432-950df980-8377-11eb-82e7-b7ce4a0d04bc.png\" => \"Mario\",\n]\n\n# ╔═╡ 6dabe5e2-c851-4a2e-8b07-aded451d8058\nmd\"\"\"\n### Choose your image\n\n $(@bind image_url Select(all_image_urls))\n\nMaximum image size: $(@bind max_height_str Select(string.([50,100,200,500]))) pixels. _(Using a large image might lead to long runtimes in the later exercises.)_\n\"\"\"\n\n# ╔═╡ 0d144802-f319-11ea-0028-cd97a776a3d0\nimg_original = load(download(image_url));\n\n# ╔═╡ a5271c38-ba45-416b-94a4-ba608c25b897\nmax_height = parse(Int, max_height_str)\n\n# ╔═╡ 365349c7-458b-4a6d-b067-5112cb3d091f\n\"Decimate an image such that its new height is at most `height`.\"\nfunction decimate_to_height(img, height)\n\tfactor = max(1, 1 + size(img, 1) ÷ height)\n\timg[1:factor:end, 1:factor:end]\nend\n\n# ╔═╡ ab276048-f34b-42dd-b6bf-0b83c6d99e6a\nimg = decimate_to_height(img_original, max_height)\n\n# ╔═╡ b49e8cc8-f381-11ea-1056-91668ac6ae4e\nmd\"\"\"\n## Cutting a seam\n\nBelow is a function called `remove_in_each_row(img, pixels)`. It takes a matrix `img` and a vector of integers, `pixels`, and shrinks the image by 1 pixel in width by removing the element `img[i, pixels[i]]` in every row. This function is one of the building blocks of the Image Seam algorithm we saw in the lecture.\n\nRead it and convince yourself that it is correct.\n\"\"\"\n\n# ╔═╡ 90a22cc6-f327-11ea-1484-7fda90283797\nfunction remove_in_each_row(img::Matrix, column_numbers::Vector)\n\tm, n = size(img)\n\t@assert m == length(column_numbers) # same as the number of rows\n\n\tlocal img′ = similar(img, m, n-1) # create a similar image with one column less\n\n\tfor (i, j) in enumerate(column_numbers)\n\t\timg′[i, 1:j-1] .= @view img[i, 1:(j-1)]\n\t\timg′[i, j:end] .= @view img[i, (j+1):end]\n\tend\n\timg′\nend\n\n# ╔═╡ 5370bf57-1341-4926-b012-ba58780217b1\nremoval_test_image = Gray.(rand(4,4))\n\n# ╔═╡ c075a8e6-f382-11ea-2263-cd9507324f4f\nmd\"Let's use our function to remove the _diagonal_ from our image. Take a close look at the images to verify that we removed the diagonal. \"\n\n# ╔═╡ 52425e53-0583-45ab-b82b-ffba77d444c8\nlet\n\tseam = [3,2,3,4]\n\tremove_in_each_row(removal_test_image, seam)\nend\n\n# ╔═╡ a09aa706-6e35-4536-a16b-494b972e2c03\nmd\"\"\"\nRemoving the seam `[1,1,1,1]` is equivalent to removing the first column:\n\"\"\"\n\n# ╔═╡ 268546b2-c4d5-4aa5-a57f-275c7da1450c\nlet\n\tseam = [1,1,1,1]\n\tremove_in_each_row(removal_test_image, seam)\nend\n\n# ╔═╡ 6aeb2d1c-8585-4397-a05f-0b1e91baaf67\nmd\"\"\"\nIf we remove the same seam twice, we remove the first two rows:\n\"\"\"\n\n# ╔═╡ 2f945ca3-e7c5-4b14-b618-1f9da019cffd\nlet\n\tseam = [1,1,1,1]\n\t\n\tresult1 = remove_in_each_row(removal_test_image, seam)\n\tresult2 = remove_in_each_row(result1, seam)\n\tresult2\nend\n\n# ╔═╡ 318a2256-f369-11ea-23a9-2f74c566549b\nmd\"\"\"\n## _Brightness and Energy_\n\"\"\"\n\n# ╔═╡ 7a44ba52-f318-11ea-0406-4731c80c1007\nmd\"\"\"\nFirst, we will define a `brightness` function for a pixel (a color) as the mean of the red, green and blue values.\n\nYou should use this function whenever the problem set asks you to deal with _brightness_ of a pixel.\n\"\"\"\n\n# ╔═╡ 6c7e4b54-f318-11ea-2055-d9f9c0199341\nbegin\n\tbrightness(c::RGB) = mean((c.r, c.g, c.b))\n\tbrightness(c::RGBA) = mean((c.r, c.g, c.b))\n\tbrightness(c::Gray) = gray(c)\nend\n\n# ╔═╡ 74059d04-f319-11ea-29b4-85f5f8f5c610\nGray.(brightness.(img))\n\n# ╔═╡ 0b9ead92-f318-11ea-3744-37150d649d43\nmd\"\"\"We provide you with a convolve function below.\n\"\"\"\n\n# ╔═╡ d184e9cc-f318-11ea-1a1e-994ab1330c1a\nconvolve(img, k) = imfilter(img, reflect(k)) # uses ImageFiltering.jl package\n# behaves the same way as the `convolve` function used in our lectures and homeworks\n\n# ╔═╡ cdfb3508-f319-11ea-1486-c5c58a0b9177\nfloat_to_color(x) = RGB(max(0, -x), max(0, x), 0)\n\n# ╔═╡ 5fccc7cc-f369-11ea-3b9e-2f0eca7f0f0e\nmd\"\"\"\nfinally we define the `energy` function which takes the Sobel gradients along x and y directions and computes the norm of the gradient for each pixel.\n\"\"\"\n\n# ╔═╡ e9402079-713e-4cfd-9b23-279bd1d540f6\nenergy(∇x, ∇y) = sqrt.(∇x.^2 .+ ∇y.^2)\n\n# ╔═╡ 6f37b34c-f31a-11ea-2909-4f2079bf66ec\nfunction energy(img)\n\t∇y = convolve(brightness.(img), Kernel.sobel()[1])\n\t∇x = convolve(brightness.(img), Kernel.sobel()[2])\n\tenergy(∇x, ∇y)\nend\n\n# ╔═╡ 9fa0cd3a-f3e1-11ea-2f7e-bd73b8e3f302\nfloat_to_color.(energy(img))\n\n# ╔═╡ 87afabf8-f317-11ea-3cb3-29dced8e265a\nmd\"\"\"\n## **Exercise 1** - _Building up to dynamic programming_\n\nIn this exercise and the following ones, we will use the computational problem of Seam carving. We will think through all the \"gut reaction\" solutions, and then finally end up with the dynamic programming solution that we saw in the lecture.\n\nIn the process we will understand the performance and accuracy of each iteration of our solution.\n\n### How to implement the solutions:\n\nFor every variation of the algorithm, your job is to write a function which takes a matrix of energies, and an index for a pixel on the first row, and computes a \"seam\" starting at that pixel.\n\nThe function should return a vector of as many integers as there are rows in the input matrix where each number points out a pixel to delete from the corresponding row. (it acts as the input to `remove_in_each_row`).\n\"\"\"\n\n# ╔═╡ 8ba9f5fc-f31b-11ea-00fe-79ecece09c25\nmd\"\"\"\n#### Exercise 1.1 - _The greedy approach_\n\nThe first approach discussed in the lecture (included below) is the _greedy approach_: you start from your top pixel, and at each step you just look at the three neighbors below. The next pixel in the seam is the neighbor with the lowest energy.\n\n\"\"\"\n\n# ╔═╡ f5a74dfc-f388-11ea-2577-b543d31576c6\nhtml\"\"\"\n<iframe width=\"100%\" height=\"450px\" src=\"https://www.youtube.com/embed/rpB6zQNsbQU?start=777&end=833\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen></iframe>\n\"\"\"\n\n# ╔═╡ 2f9cbea8-f3a1-11ea-20c6-01fd1464a592\nrandom_seam(m, n, i) = reduce((a, b) -> [a..., clamp(last(a) + rand(-1:1), 1, n)], 1:m-1; init=[i])\n\n# ╔═╡ c3543ea4-f393-11ea-39c8-37747f113b96\nmd\"\"\"\n👉 Implement the greedy approach.\n\"\"\"\n\n# ╔═╡ a4e8e45c-9455-11eb-2f8d-c1cf300290c9\nfunction getIndexOfMinimum(v)\n\t(value, idx) = findmin(v)\n\treturn idx\nend\n\n# ╔═╡ 1342aff4-945a-11eb-3e71-e36d9a405a1f\nfunction extend(v::AbstractVector, i)\n\tprintln(i)\n\tif i<1\n\t\treturn v[1]\n\tend\n\tif i>length(v)\n\t\treturn v[length(v)]\n\tend\n\treturn v[i]\nend\n\n# ╔═╡ abf20aa0-f31b-11ea-2548-9bea4fab4c37\nfunction greedy_seam(energies, starting_pixel::Int)\n\tm,n = size(energies)\n\tseam = zeros(Int, m)\n\tleast_neighbour = 1\n\tleast_neighbour_index = -1\n\tseam[1] = starting_pixel\n\tj = starting_pixel\n\tfor i ∈ 2:m\n\t\tleast_neighbour = 1\n\t\tfor x ∈ -1:1\n\t\t\tif j+x>=1 && j+x<=n && energies[i, j+x]<least_neighbour\n\t\t\t\tleast_neighbour = energies[i, j+x]\n\t\t\t\tleast_neighbour_index = j+x\n\t\t\tend\n\t\tend\n\t\tj = least_neighbour_index\n\t\tseam[i] = least_neighbour_index\n\tend\n\tvec(seam)\nend\n\n# ╔═╡ 5430d772-f397-11ea-2ed8-03ee06d02a22\nmd\"Before we apply your function to our test image, let's try it out on a small matrix of energies (displayed here in grayscale), just like in the lecture snippet above (clicking on the video will take you to the right part of the video). Light pixels have high energy, dark pixels signify low energy.\"\n\n# ╔═╡ a4d14606-7e58-4770-8532-66b875c97b70\ngrant_example = [\n\t1 8 8 3 5 4\n\t7 8 1 0 8 4\n\t8 0 4 7 2 9\n\t9 0 0 5 9 4\n\t2 4 0 2 4 5\n\t2 4 2 5 3 0\n] ./ 10\n\n# ╔═╡ 6f52c1a2-f395-11ea-0c8a-138a77f03803\nmd\"Starting pixel: $(@bind greedy_starting_pixel Slider(1:size(grant_example, 2); show_value=true, default=5))\"\n\n# ╔═╡ 5057652e-2f88-40f1-82f0-55b1b5bca6f6\ngreedy_seam_result = greedy_seam(grant_example, greedy_starting_pixel)\n\n# ╔═╡ 2643b00d-2bac-4868-a832-5fb8ad7f173f\nlet\n\ts = sum(grant_example[i,j] for (i,j) in enumerate(greedy_seam_result))\n\tmd\"\"\"\n\t**Total energy:** $(round(s,digits=1))\n\t\"\"\"\nend\n\n# ╔═╡ 38f70c35-2609-4599-879d-e032cd7dc49d\nGray.(grant_example)\n\n# ╔═╡ 9945ae78-f395-11ea-1d78-cf6ad19606c8\nmd\"_Let's try it on the bigger image!_\"\n\n# ╔═╡ 6bac615e-9463-11eb-2210-afa3f2307aa4\ngreedy_seam, img, grant_example\n\n# ╔═╡ 87efe4c2-f38d-11ea-39cc-bdfa11298317\nbegin\n\t# reactive references to uncheck the checkbox when the functions are updated\n\tgreedy_seam, img, grant_example\n\t\n\tmd\"Compute shrunk image: $(@bind shrink_greedy CheckBox())\"\nend\n\n# ╔═╡ 52452d26-f36c-11ea-01a6-313114b4445d\nmd\"\"\"\n#### Exercise 1.2 - _Recursion_\n\nA common pattern in algorithm design is the idea of solving a problem as the combination of solutions to subproblems.\n\nThe classic example, is a [Fibonacci number](https://en.wikipedia.org/wiki/Fibonacci_number) generator.\n\nThe recursive implementation of Fibonacci looks something like this\n\"\"\"\n\n# ╔═╡ 2a98f268-f3b6-11ea-1eea-81c28256a19e\nfunction fib(n)\n # base case (basis)\n\tif n == 0 || n == 1 # `||` means \"or\"\n\t\treturn 1\n\tend\n\n # recursion (induction)\n\treturn fib(n-1) + fib(n-2)\nend\n\n# ╔═╡ 32e9a944-f3b6-11ea-0e82-1dff6c2eef8d\nmd\"\"\"\nNotice that you can call a function from within itself which may call itself and so on until a base case is reached. Then the program will combine the result from the base case up to the final result.\n\nIn the case of the Fibonacci function, we added the solutions to the subproblems `fib(n-1)`, `fib(n-2)` to produce `fib(n)`.\n\nAn analogy can be drawn to the process of mathematical induction in mathematics. And as with mathematical induction there are parts to constructing such a recursive algorithm:\n\n- Defining a base case\n- Defining an recursion i.e. finding a solution to the problem as a combination of solutions to smaller problems.\n\n\"\"\"\n\n# ╔═╡ 9101d5a0-f371-11ea-1c04-f3f43b96ca4a\nmd\"\"\"\n👉 Define a `least_energy` function which returns:\n1. the lowest possible total energy for a seam starting at the pixel at $(i, j)$;\n2. the column to jump to on the next move (in row $i + 1$),\nwhich is one of $j-1$, $j$ or $j+1$, up to boundary conditions.\n\nReturn these two values in a tuple.\n\"\"\"\n\n# ╔═╡ 8ec27ef8-f320-11ea-2573-c97b7b908cb7\n## returns lowest possible sum energy at pixel (i, j), and the column to jump to in row i+1.\nfunction least_energy(energies, i, j)\n\tm, n = size(energies)\n\t\n\tif i == m\n\t\treturn (energies[i,j], j)\n\tend\n\t\n\tlowest_energy = 1\n\tlowest_energy_route = j\n\t\n\tfor x in max(1,j-1):min(n,j+1)\n\t\ty = least_energy(energies, i+1, x)[1]\n\t\tif lowest_energy > y\n\t\t\tlowest_energy = y\n\t\t\tlowest_energy_route = x\n\t\tend\n\tend\n\treturn (lowest_energy + energies[i,j], lowest_energy_route)\nend\n\n# ╔═╡ ad524df7-29e2-4f0d-ad72-8ecdd57e4f02\nleast_energy(grant_example, 3, 2)\n\n# ╔═╡ 1add9afd-5ff5-451d-ad81-57b0e929dfe8\ngrant_example\n\n# ╔═╡ 9c5d5f94-9468-11eb-3cf2-3301537c7025\nGray.(grant_example)\n\n# ╔═╡ 447e54f8-d3db-4970-84ee-0708ab8a9244\nmd\"\"\"\n#### Expected output\nAs shown in the lecture, the optimal seam from the point (1,4) should be:\n\"\"\"\n\n# ╔═╡ 8b8da8e7-d3b5-410e-b100-5538826c0fde\ngrant_example_optimal_seam = [4, 3, 2, 2, 3, 3]\n\n# ╔═╡ e1074d35-58c4-43c0-a6cb-1413ed194e25\nmd\"\"\"\nSo we expect the output of `least_energy(grant_example, 1, 4)` to be:\n\"\"\"\n\n# ╔═╡ 281b950f-2331-4666-9e45-8fd117813f45\n(\n\tsum(grant_example[i, grant_example_optimal_seam[i]] for i in 1:6),\n\tgrant_example_optimal_seam[2]\n)\n\n# ╔═╡ a7f3d9f8-f3bb-11ea-0c1a-55bbb8408f09\nmd\"\"\"\nThis is elegant and correct, but inefficient! Let's look at the number of accesses made to the energies array needed to compute the least energy seam of a 10x10 image:\n\"\"\"\n\n# ╔═╡ 18e0fd8a-f3bc-11ea-0713-fbf74d5fa41a\nmd\"Whoa! We will need to optimize this later!\"\n\n# ╔═╡ cbf29020-f3ba-11ea-2cb0-b92836f3d04b\nbegin\n\tstruct AccessTrackerArray{T,N} <: AbstractArray{T, N}\n\t\tdata::Array{T,N}\n\t\taccesses::Ref{Int}\n\tend\n\t\n\tBase.IndexStyle(::Type{AccessTrackerArray}) = IndexLinear()\n\t\n\tBase.size(x::AccessTrackerArray) = size(x.data)\n\tBase.getindex(x::AccessTrackerArray, i::Int...) = (x.accesses[] += 1; x.data[i...])\n\tBase.setindex!(x::AccessTrackerArray, v, i...) = (x.accesses[] += 1; x.data[i...] = v;)\n\t\n\t\n\ttrack_access(x) = AccessTrackerArray(x, Ref(0))\n\tfunction track_access(f::Function, x::Array)\n\t\ttracked = track_access(x)\n\t\tf(tracked)\n\t\ttracked.accesses[]\n\tend\nend\n\n# ╔═╡ fa8e2772-f3b6-11ea-30f7-699717693164\ntrack_access(rand(10,10)) do tracked\n\tleast_energy(tracked, 1, 5)\nend\n\n# ╔═╡ 8bc930f0-f372-11ea-06cb-79ced2834720\nmd\"\"\"\n#### Exercise 1.3 - _Exhaustive search with recursion_\n\nNow use the `least_energy` function you defined above to define the `recursive_seam` function which takes the energies matrix and a starting pixel, and computes the seam with the lowest energy from that starting pixel.\n\nThis will give you the method used in the lecture to perform [exhaustive search of all possible paths](https://youtu.be/rpB6zQNsbQU?t=839).\n\"\"\"\n\n# ╔═╡ 85033040-f372-11ea-2c31-bb3147de3c0d\nfunction recursive_seam(energies, starting_pixel)\n\tm, n = size(energies)\n\t# Replace the following line with your code.\n\tseam = similar(1:m, 1, m)\n\tseam[1] = starting_pixel\n\tfor i in 2:m\n\t\tseam[i] = least_energy(energies, i-1, seam[i-1])[2]\n\tend\n\treturn vec(seam)\nend\n\n# ╔═╡ f92ac3e4-fa70-4bcf-bc50-a36792a8baaa\nmd\"\"\"\nWe won't use this function to shrink our larger image, because it is too inefficient. (Your notebook might get stuck!) But let's try it on the small example matrix from the lecture, to verify that we have found the optimal seam.\n\"\"\"\n\n# ╔═╡ 7ac5eb8d-9dba-4700-8f3a-1e0b2addc740\nrecursive_seam_test = recursive_seam(grant_example, 4)\n\n# ╔═╡ c572f6ce-f372-11ea-3c9a-e3a21384edca\nmd\"\"\"\n#### Exercise 1.4\n\n- State clearly why this algorithm does an exhaustive search of all possible paths.\n- How does the number of possible seam grow as n increases for a `m×n` image? (Big O notation is fine, or an approximation is fine).\n\"\"\"\n\n# ╔═╡ 6d993a5c-f373-11ea-0dde-c94e3bbd1552\nexhaustive_observation = md\"\"\"\n• The algorithm does an exhaustive search of all possible paths because at every step, the algorithm looks for a path in 3 bottom directions and computes the total cost of the entire path and then chooses the least energy path. It does not make a local minima choice while determining the seam of the image and hence, all the paths possible will be explored while calculating the least energy path for the image.\n\n• The number of possible seam grow as O($3^n$) as n increases in the image with dimensions mxn.\n\"\"\"\n\n# ╔═╡ ea417c2a-f373-11ea-3bb0-b1b5754f2fac\nmd\"\"\"\n## **Exercise 2** - _Memoization_\n\n**Memoization** is the name given to the technique of storing results to expensive function calls that will be accessed more than once.\n\nAs stated in the video, the function `least_energy` is called repeatedly with the same arguments. In fact, we call it on the order of $3^n$ times, when there are only really $m \\times n$ unique ways to call it!\n\nLets implement memoization on this function with first a [dictionary](https://docs.julialang.org/en/v1/base/collections/#Dictionaries) for storage.\n\"\"\"\n\n# ╔═╡ 56a7f954-f374-11ea-0391-f79b75195f4d\nmd\"\"\"\n#### Exercise 2.1 - _Dictionary as storage_\n\nLet's make a memoized version of least_energy function which takes a dictionary and\nfirst checks to see if the dictionary contains the key (i,j) if it does, returns the value stored in that place, if not, will compute it, and store it in the dictionary at key (i, j) and return the value it computed.\n\n\n`memoized_least_energy(energies, starting_pixel, memory)`\n\nThis function must recursively call itself, and pass the same `memory` object it received as an argument.\n\nYou are expected to read and understand the [documentation on dictionaries](https://docs.julialang.org/en/v1/base/collections/#Dictionaries) to find out how to:\n\n1. Create a dictionary\n2. Check if a key is stored in the dictionary\n3. Access contents of the dictionary by a key.\n\"\"\"\n\n# ╔═╡ b1d09bc8-f320-11ea-26bb-0101c9a204e2\nfunction memoized_least_energy(energies, i, j, memory::Dict)\n\tm, n = size(energies)\n\t\n\tif i == m\n\t\tmemory[(i,j)] = (energies[i,j], j)\n\t\treturn memory[(i, j)]\n\tend\n\t\n\tlowest_energy = 1\n\tlowest_energy_route = j\n\t\n\tfor x in max(1,j-1):min(n,j+1)\n\t\tif (haskey(memory, (i+1, x)))\n\t\t\ty = get(memory, (i+1, x), -1)[1]\n\t\telse\n\t\t\ty = memoized_least_energy(energies, i+1, x, memory)[1]\n\t\tend\n\t\tif lowest_energy > y\n\t\t\tlowest_energy = y\n\t\t\tlowest_energy_route = x\n\t\tend\n\tend\n\tmemory[(i, j)] = (lowest_energy + energies[i,j], lowest_energy_route)\n\treturn memory[(i, j)]\nend\n\n# ╔═╡ 1947f304-fa2c-4019-8584-01ef44ef2859\nmemoized_least_energy_test = memoized_least_energy(grant_example, 1, 4, Dict())\n\n# ╔═╡ 8992172e-c5b6-463e-a06e-5fe42fb9b16b\nmd\"\"\"\nLet's see how many matrix access we have now:\n\"\"\"\n\n# ╔═╡ b387f8e8-dced-473a-9434-5334829ecfd1\ntrack_access(rand(10,10)) do tracked\n\tmemoized_least_energy(tracked, 1, 5, Dict())\nend\n\n# ╔═╡ 3e8b0868-f3bd-11ea-0c15-011bbd6ac051\nfunction memoized_recursive_seam(energies, starting_pixel)\n\t# we set up the the _memory_: note the key type (Tuple{Int,Int}) and\n\t# the value type (Tuple{Float64,Int}). \n\t# If you need to memoize something else, you can just use Dict() without types.\n\tmemory = Dict{Tuple{Int,Int},Tuple{Float64,Int}}()\n\t\n\tm, n = size(energies)\n\tseam = similar(1:m, 1, m)\n\tseam[1] = starting_pixel\n\tfor i in 2:m\n\t\tseam[i] = memoized_least_energy(energies, i-1, seam[i-1], memory)[2]\n\tend\n\treturn vec(seam)\nend\n\n# ╔═╡ d941c199-ed77-47dd-8b5a-e34b864f9a79\nmemoized_recursive_seam(grant_example, 4)\n\n# ╔═╡ 726280f0-682f-4b05-bf5a-688554a96287\ngrant_example_optimal_seam\n\n# ╔═╡ cf39fa2a-f374-11ea-0680-55817de1b837\nmd\"\"\"\n### Exercise 2.2 - _Matrix as storage_ (optional)\n\nThe dictionary-based memoization we tried above works well in general as there is no restriction on what type of keys can be used.\n\nBut in our particular case, we can use a matrix as a storage, since a matrix is naturally keyed by two integers.\n\n👉 Write a variant of `matrix_memoized_least_energy` and `matrix_memoized_seam` which use a matrix as storage. \n\"\"\"\n\n# ╔═╡ c8724b5e-f3bd-11ea-0034-b92af21ca12d\nfunction matrix_memoized_least_energy(energies, i, j, memory::Matrix)\n\tm, n = size(energies)\n\t\n\tif i == m\n\t\tmemory[i,j] = (energies[i,j], j)\n\t\treturn memory[i, j]\n\tend\n\t\n\tlowest_energy = 1\n\tlowest_energy_route = j\n\t\n\tfor x in max(1,j-1):min(n,j+1)\n\t\tif (memory[i+1, x] != nothing)\n\t\t\ty = memory[i+1, x][1]\n\t\telse\n\t\t\ty = matrix_memoized_least_energy(energies, i+1, x, memory)[1]\n\t\tend\n\t\tif lowest_energy > y\n\t\t\tlowest_energy = y\n\t\t\tlowest_energy_route = x\n\t\tend\n\tend\n\tmemory[i, j] = (lowest_energy + energies[i,j], lowest_energy_route)\n\treturn memory[i, j]\nend\n\n# ╔═╡ be7d40e2-f320-11ea-1b56-dff2a0a16e8d\nfunction matrix_memoized_seam(energies, starting_pixel)\n\tmemory = Matrix{Union{Nothing, Tuple{Float64,Int}}}(nothing, size(energies))\n\n\t# use me instead of you use a different element type:\n\t# memory = Matrix{Any}(nothing, size(energies))\n\t\n\t\n\tm, n = size(energies)\n\t\n# \t# Replace the following line with your code.\n# \t[starting_pixel for i=1:m]\n\t\n\tseam = similar(1:m, 1, m)\n\tseam[1] = starting_pixel\n\tfor i in 2:m\n\t\tseam[i] = matrix_memoized_least_energy(energies, i-1, seam[i-1], memory)[2]\n\tend\n\treturn vec(seam)\n\t\n\t\nend\n\n# ╔═╡ 507f3870-f3c5-11ea-11f6-ada3bb087634\nbegin\n\tmatrix_memoized_seam, img\n\t\n\tmd\"Compute shrunk image: $(@bind shrink_matrix CheckBox())\"\nend\n\n# ╔═╡ 24792456-f37b-11ea-07b2-4f4c8caea633\nmd\"\"\"\n## **Exercise 3** - _Dynamic programming without recursion_ \n\nNow it's easy to see that the above algorithm is equivalent to one that populates the memory matrix in a for loop.\n\n#### Exercise 3.1\n\n👉 Write a function which takes the energies and returns the least energy matrix which has the least possible seam energy for each pixel. This was shown in the lecture, but attempt to write it on your own.\n\"\"\"\n\n# ╔═╡ ff055726-f320-11ea-32f6-2bf38d7dd310\nfunction least_energy_matrix(energies)\n\tmemory = Matrix{Union{Nothing, Tuple{Float64,Int}}}(nothing, size(energies))\n\tresult = copy(energies)\n\tm,n = size(energies)\n\t\n\tfor i ∈ 1:m\n\t\tfor j ∈ 1:n\n\t\t\tresult[i,j] = matrix_memoized_least_energy(energies, i, j, memory)[1]\n\t\tend\n\tend\n\t\n\treturn result\nend\n\n# ╔═╡ d3e69cf6-61b1-42fc-9abd-42d1ae7d61b2\nimg_brightness = brightness.(img);\n\n# ╔═╡ 51731519-1831-46a3-a599-d6fc2f7e4224\nle_test = least_energy_matrix(img_brightness)\n\n# ╔═╡ e06d4e4a-146c-4dbd-b742-317f638a3bd8\nspooky(A::Matrix{<:Real}) = map(sqrt.(A ./ maximum(A))) do x\n\tRGB(.8x, x, .8x)\nend\n\n# ╔═╡ 99efaf6a-0109-4b16-89b8-f8149b6b69c2\nspooky(le_test)\n\n# ╔═╡ 92e19f22-f37b-11ea-25f7-e321337e375e\nmd\"\"\"\n#### Exercise 3.2\n\n👉 Write a function which, when given the matrix returned by `least_energy_matrix` and a starting pixel (on the first row), computes the least energy seam from that pixel.\n\"\"\"\n\n# ╔═╡ 795eb2c4-f37b-11ea-01e1-1dbac3c80c13\nfunction seam_from_precomputed_least_energy(energies, starting_pixel::Int)\n\tleast_energies = least_energy_matrix(energies)\n\tm, n = size(least_energies)\n\t\n\t# # Replace the following line with your code.\n\t# [starting_pixel for i=1:m]\n\t\n\tseam = zeros(Int, m)\n\tseam[1] = starting_pixel\n\tj=starting_pixel\n\tleast_neighbour_index = starting_pixel\n\tfor i ∈ 2:m\n\t\tleast_neighbour = 1\n\t\tfor x ∈ -1:1\n\t\t\tif j+x>=1 && j+x<=n && least_energies[i, j+x]<least_neighbour\n\t\t\t\tleast_neighbour = least_energies[i, j+x]\n\t\t\t\tleast_neighbour_index = j+x\n\t\t\tend\n\t\tend\n\t\tj = least_neighbour_index\n\t\tseam[i] = least_neighbour_index\n\tend\n\tvec(seam)\n\t\t\n\t\nend\n\n# ╔═╡ 51df0c98-f3c5-11ea-25b8-af41dc182bac\nbegin\n\timg, seam_from_precomputed_least_energy\n\tmd\"Compute shrunk image: $(@bind shrink_bottomup CheckBox())\"\nend\n\n# ╔═╡ 0fbe2af6-f381-11ea-2f41-23cd1cf930d9\nif student.kerberos_id === \"jazz\"\n\tmd\"\"\"\n!!! danger \"Oops!\"\n **Before you submit**, remember to fill in your name and kerberos ID at the top of this notebook!\n\t\"\"\"\nend\n\n# ╔═╡ 6b4d6584-f3be-11ea-131d-e5bdefcc791b\nmd\"## Function library\n\nJust some helper functions used in the notebook.\"\n\n# ╔═╡ ef88c388-f388-11ea-3828-ff4db4d1874e\nfunction mark_path(img, path)\n\timg′ = RGB.(img) # also makes a copy\n\tm = size(img, 2)\n\tfor (i, j) in enumerate(path)\n\t\tif size(img, 2) > 50\n\t\t\t# To make it easier to see, we'll color not just\n\t\t\t# the pixels of the seam, but also those adjacent to it\n\t\t\tfor j′ in j-1:j+1\n\t\t\t\timg′[i, clamp(j′, 1, m)] = RGB(1,0,1)\n\t\t\tend\n\t\telse\n\t\t\timg′[i, j] = RGB(1,0,1)\n\t\tend\n\tend\n\timg′\nend\n\n# ╔═╡ 437ba6ce-f37d-11ea-1010-5f6a6e282f9b\nfunction shrink_n(min_seam::Function, img::Matrix{<:Colorant}, n, imgs=[];\n\t\tshow_lightning=true,\n\t)\n\t\n\tn==0 && return push!(imgs, img)\n\t\n\te = energy(img)\n\tseam_energy(seam) = sum(e[i, seam[i]] for i in 1:size(img, 1))\n\t_, min_j = findmin(map(j->seam_energy(min_seam(e, j)), 1:size(e, 2)))\n\tmin_seam_vec = min_seam(e, min_j)\n\timg′ = remove_in_each_row(img, min_seam_vec)\n\tif show_lightning\n\t\tpush!(imgs, mark_path(img, min_seam_vec))\n\telse\n\t\tpush!(imgs, img′)\n\tend\n\tshrink_n(min_seam, img′, n-1, imgs; show_lightning=show_lightning)\nend\n\n# ╔═╡ f6571d86-f388-11ea-0390-05592acb9195\nif shrink_greedy\n\tlocal n = min(200, size(img, 2))\n\tgreedy_carved = shrink_n(greedy_seam, img, n)\n\tmd\"Shrink by: $(@bind greedy_n Slider(1:n; show_value=true))\"\nend\n\n# ╔═╡ f626b222-f388-11ea-0d94-1736759b5f52\nif shrink_greedy\n\tgreedy_carved[greedy_n]\nend\n\n# ╔═╡ 4e3bcf88-f3c5-11ea-3ada-2ff9213647b7\nbegin\n\t# reactive references to uncheck the checkbox when the functions are updated\n\timg, memoized_recursive_seam, shrink_n\n\t\n\tmd\"Compute shrunk image: $(@bind shrink_dict CheckBox())\"\nend\n\n# ╔═╡ 4e3ef866-f3c5-11ea-3fb0-27d1ca9a9a3f\nif shrink_dict\n\tlocal n = min(50, size(img, 2))\n\tdict_carved = shrink_n(memoized_recursive_seam, img, n)\n\tmd\"Shrink by: $(@bind dict_n Slider(1:n, show_value=true))\"\nend\n\n# ╔═╡ 6e73b1da-f3c5-11ea-145f-6383effe8a89\nif shrink_dict\n\tdict_carved[dict_n]\nend\n\n# ╔═╡ 50829af6-f3c5-11ea-04a8-0535edd3b0aa\nif shrink_matrix\n\tlocal n = min(40, size(img, 2))\n\tmatrix_carved = shrink_n(matrix_memoized_seam, img, n)\n\tmd\"Shrink by: $(@bind matrix_n Slider(1:n, show_value=true))\"\nend\n\n# ╔═╡ 9e56ecfa-f3c5-11ea-2e90-3b1839d12038\nif shrink_matrix\n\tmatrix_carved[matrix_n]\nend\n\n# ╔═╡ 51e28596-f3c5-11ea-2237-2b72bbfaa001\nif shrink_bottomup\n\tlocal n = min(40, size(img, 2))\n\tbottomup_carved = shrink_n(seam_from_precomputed_least_energy, img, n)\n\tmd\"Shrink by: $(@bind bottomup_n Slider(1:n, show_value=true))\"\nend\n\n# ╔═╡ 0a10acd8-f3c6-11ea-3e2f-7530a0af8c7f\nif shrink_bottomup\n\tbottomup_carved[bottomup_n]\nend\n\n# ╔═╡ ef26374a-f388-11ea-0b4e-67314a9a9094\nfunction pencil(X)\n\tf(x) = RGB(1-x,1-x,1-x)\n\tmap(f, X ./ maximum(X))\nend\n\n# ╔═╡ 6bdbcf4c-f321-11ea-0288-fb16ff1ec526\nfunction decimate(img, n)\n\timg[1:n:end, 1:n:end]\nend\n\n# ╔═╡ ffc17f40-f380-11ea-30ee-0fe8563c0eb1\nhint(text) = Markdown.MD(Markdown.Admonition(\"hint\", \"Hint\", [text]))\n\n# ╔═╡ 9f18efe2-f38e-11ea-0871-6d7760d0b2f6\nhint(md\"You can call the `least_energy` function recursively within itself to obtain the least energy of the adjacent cells and add the energy at the current cell to get the total energy.\")\n\n# ╔═╡ 6435994e-d470-4cf3-9f9d-d00df183873e\nhint(md\"We recommend using a matrix with element type `Union{Nothing, Tuple{Float64,Int}}`, initialized to all `nothing`s. You can check whether the value at `(i,j)` has been computed before using `memory[i,j] != nothing`.\")\n\n# ╔═╡ ffc40ab2-f380-11ea-2136-63542ff0f386\nalmost(text) = Markdown.MD(Markdown.Admonition(\"warning\", \"Almost there!\", [text]))\n\n# ╔═╡ ffceaed6-f380-11ea-3c63-8132d270b83f\nstill_missing(text=md\"Replace `missing` with your answer.\") = Markdown.MD(Markdown.Admonition(\"warning\", \"Here we go!\", [text]))\n\n# ╔═╡ ffde44ae-f380-11ea-29fb-2dfcc9cda8b4\nkeep_working(text=md\"The answer is not quite right.\") = Markdown.MD(Markdown.Admonition(\"danger\", \"Keep working on it!\", [text]))\n\n# ╔═╡ 1413d047-099f-48c9-bbb0-ff0a3ddb4888\nbegin\n\tfunction visualize_seam_algorithm(test_energies, algorithm::Function, starting_pixel::Integer)\n\t\tseam = algorithm(test_energies, starting_pixel)\n\t\tvisualize_seam_algorithm(test_energies, seam)\n\tend\n\tfunction visualize_seam_algorithm(test_energies, seam::Vector)\n\tdisplay_img = RGB.(test_energies)\n\t\tfor (i, j) in enumerate(seam)\n\t\t\ttry\n\t\t\t\tdisplay_img[i, j] = RGB(0.9, 0.3, 0.6)\n\t\t\tcatch ex\n\t\t\t\tif ex isa BoundsError\n\t\t\t\t\treturn keep_working(\"\")\n\t\t\t\tend\n\t\t\t\t# the solution might give an illegal index\n\t\t\tend\n\t\tend\n\t\tdisplay_img\n\tend\nend\n\n# ╔═╡ 2a7e49b8-f395-11ea-0058-013e51baa554\nvisualize_seam_algorithm(grant_example, greedy_seam_result)\n\n# ╔═╡ ffe326e0-f380-11ea-3619-61dd0592d409\nyays = [md\"Great!\", md\"Yay ❤\", md\"Great! 🎉\", md\"Well done!\", md\"Keep it up!\", md\"Good job!\", md\"Awesome!\", md\"You got the right answer!\", md\"Let's move on to the next section.\"]\n\n# ╔═╡ fff5aedc-f380-11ea-2a08-99c230f8fa32\ncorrect(text=rand(yays)) = Markdown.MD(Markdown.Admonition(\"correct\", \"Got it!\", [text]))\n\n# ╔═╡ 9ff0ce41-327f-4bf0-958d-309cd0c0b6e5\nif recursive_seam_test == grant_example_optimal_seam\n\tcorrect()\nelse\n\tkeep_working()\nend\n\n# ╔═╡ 344964a8-7c6b-4720-a624-47b03483263b\nlet\n\tresult = track_access(rand(10,10)) do tracked\n\t\tmemoized_least_energy(tracked, 1, 5, Dict())\n\t\tend\n\tif result == 0\n\t\tnothing\n\telseif result < 200\n\t\tcorrect()\n\telse\n\t\tkeep_working(md\"That's still too many accesses! Did you forget to add a result to the `memory`?\")\n\tend\nend\n\n# ╔═╡ c1ab3d5f-8e6c-4702-ad40-6c7f787f1c43\nlet\n\taresult = track_access(rand(10,10)) do tracked\n\t\tmemoized_recursive_seam(tracked, 5)\n\tend\n\tif aresult < 200\n\t\tif memoized_recursive_seam(grant_example, 4) == grant_example_optimal_seam\n\t\t\tcorrect()\n\t\telse\n\t\t\tkeep_working(md\"The returned seam is not correct. Did you implement the non-memoized version correctly?\")\n\t\tend\n\telse\n\t\tkeep_working(md\"Careful! Your `memoized_recursive_seam` is still making too many memory accesses, you may not want to run the visualization below.\")\n\tend\nend\n\n# ╔═╡ 00026442-f381-11ea-2b41-bde1fff66011\nnot_defined(variable_name) = Markdown.MD(Markdown.Admonition(\"danger\", \"Oopsie!\", [md\"Make sure that you define a variable called **$(Markdown.Code(string(variable_name)))**\"]))\n\n# ╔═╡ 414dd91b-8d05-44f0-8bbd-b15981ce1210\nif !@isdefined(least_energy)\n\tnot_defined(:least_energy)\nelse\n\tlet\n\t\tresult1 = least_energy(grant_example, 6, 4)\n\t\t\n\t\tif !(result1 isa Tuple)\n\t\t\tkeep_working(md\"Your function should return a _tuple_, like `(1.2, 5)`.\")\n\t\telseif !(result1 isa Tuple{Float64,Int})\n\t\t\tkeep_working(md\"Your function should return a _tuple_, like `(1.2, 5)`.\")\n\t\telse\n\t\t\tresult = least_energy(grant_example, 1, 4)\n\t\t\tif !(result isa Tuple{Float64,Int})\n\t\t\t\tkeep_working(md\"Your function should return a _tuple_, like `(1.2, 5)`.\")\n\t\t\telse\n\t\t\t\ta,b = result\n\n\t\t\t\tif a ≈ 0.3 && b == 4\n\t\t\t\t\talmost(md\"Only search the (at most) three cells that are within reach.\")\n\t\t\t\telseif a ≈ 0.6 && b == 3\n\t\t\t\t\tcorrect()\n\t\t\t\telse\n\t\t\t\t\tkeep_working()\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend\nend\n\n# ╔═╡ e0622780-f3b4-11ea-1f44-59fb9c5d2ebd\nif !@isdefined(least_energy_matrix)\n\tnot_defined(:least_energy_matrix)\nelseif !(le_test isa Matrix{<:Real})\n\tkeep_working(md\"`least_energy_matrix` should return a 2D array of Float64 values.\")\nend\n\n# ╔═╡ 946b69a0-f3a2-11ea-2670-819a5dafe891\nif !@isdefined(seam_from_precomputed_least_energy)\n\tnot_defined(:seam_from_precomputed_least_energy)\nend\n\n# ╔═╡ fbf6b0fa-f3e0-11ea-2009-573a218e2460\nfunction hbox(x, y, gap=16; sy=size(y), sx=size(x))\n\tw,h = (max(sx[1], sy[1]),\n\t\t gap + sx[2] + sy[2])\n\t\n\tslate = fill(RGB(1,1,1), w,h)\n\tslate[1:size(x,1), 1:size(x,2)] .= RGB.(x)\n\tslate[1:size(y,1), size(x,2) + gap .+ (1:size(y,2))] .= RGB.(y)\n\tslate\nend\n\n# ╔═╡ f010933c-f318-11ea-22c5-4d2e64cd9629\nhbox(\n\tfloat_to_color.(convolve(brightness.(img), Kernel.sobel()[1])),\n\tfloat_to_color.(convolve(brightness.(img), Kernel.sobel()[2])),\n)\n\n# ╔═╡ 256edf66-f3e1-11ea-206e-4f9b4f6d3a3d\nvbox(x,y, gap=16) = hbox(x', y')'\n\n# ╔═╡ 00115b6e-f381-11ea-0bc6-61ca119cb628\nbigbreak = html\"<br><br><br><br><br>\";\n\n# ╔═╡ c086bd1e-f384-11ea-3b26-2da9e24360ca\nbigbreak\n\n# ╔═╡ f7eba2b6-f388-11ea-06ad-0b861c764d61\nbigbreak\n\n# ╔═╡ 4f48c8b8-f39d-11ea-25d2-1fab031a514f\nbigbreak\n\n# ╔═╡ 48089a00-f321-11ea-1479-e74ba71df067\nbigbreak\n\n# ╔═╡ Cell order:\n# ╟─e6b6760a-f37f-11ea-3ae1-65443ef5a81a\n# ╟─ec66314e-f37f-11ea-0af4-31da0584e881\n# ╟─85cfbd10-f384-11ea-31dc-b5693630a4c5\n# ╠═33e43c7c-f381-11ea-3abc-c942327456b1\n# ╟─938185ec-f384-11ea-21dc-b56b7469f798\n# ╠═a4937996-f314-11ea-2ff9-615c888afaa8\n# ╟─0f271e1d-ae16-4eeb-a8a8-37951c70ba31\n# ╠═6dabe5e2-c851-4a2e-8b07-aded451d8058\n# ╠═ab276048-f34b-42dd-b6bf-0b83c6d99e6a\n# ╠═0d144802-f319-11ea-0028-cd97a776a3d0\n# ╟─a5271c38-ba45-416b-94a4-ba608c25b897\n# ╟─365349c7-458b-4a6d-b067-5112cb3d091f\n# ╟─b49e8cc8-f381-11ea-1056-91668ac6ae4e\n# ╠═90a22cc6-f327-11ea-1484-7fda90283797\n# ╠═5370bf57-1341-4926-b012-ba58780217b1\n# ╟─c075a8e6-f382-11ea-2263-cd9507324f4f\n# ╠═52425e53-0583-45ab-b82b-ffba77d444c8\n# ╟─a09aa706-6e35-4536-a16b-494b972e2c03\n# ╠═268546b2-c4d5-4aa5-a57f-275c7da1450c\n# ╟─6aeb2d1c-8585-4397-a05f-0b1e91baaf67\n# ╠═2f945ca3-e7c5-4b14-b618-1f9da019cffd\n# ╟─c086bd1e-f384-11ea-3b26-2da9e24360ca\n# ╟─318a2256-f369-11ea-23a9-2f74c566549b\n# ╟─7a44ba52-f318-11ea-0406-4731c80c1007\n# ╠═6c7e4b54-f318-11ea-2055-d9f9c0199341\n# ╠═74059d04-f319-11ea-29b4-85f5f8f5c610\n# ╟─0b9ead92-f318-11ea-3744-37150d649d43\n# ╠═d184e9cc-f318-11ea-1a1e-994ab1330c1a\n# ╠═cdfb3508-f319-11ea-1486-c5c58a0b9177\n# ╠═f010933c-f318-11ea-22c5-4d2e64cd9629\n# ╟─5fccc7cc-f369-11ea-3b9e-2f0eca7f0f0e\n# ╠═e9402079-713e-4cfd-9b23-279bd1d540f6\n# ╠═6f37b34c-f31a-11ea-2909-4f2079bf66ec\n# ╠═9fa0cd3a-f3e1-11ea-2f7e-bd73b8e3f302\n# ╟─f7eba2b6-f388-11ea-06ad-0b861c764d61\n# ╟─87afabf8-f317-11ea-3cb3-29dced8e265a\n# ╟─8ba9f5fc-f31b-11ea-00fe-79ecece09c25\n# ╟─f5a74dfc-f388-11ea-2577-b543d31576c6\n# ╟─2f9cbea8-f3a1-11ea-20c6-01fd1464a592\n# ╟─c3543ea4-f393-11ea-39c8-37747f113b96\n# ╠═a4e8e45c-9455-11eb-2f8d-c1cf300290c9\n# ╠═1342aff4-945a-11eb-3e71-e36d9a405a1f\n# ╠═abf20aa0-f31b-11ea-2548-9bea4fab4c37\n# ╟─5430d772-f397-11ea-2ed8-03ee06d02a22\n# ╟─6f52c1a2-f395-11ea-0c8a-138a77f03803\n# ╠═5057652e-2f88-40f1-82f0-55b1b5bca6f6\n# ╠═2a7e49b8-f395-11ea-0058-013e51baa554\n# ╟─2643b00d-2bac-4868-a832-5fb8ad7f173f\n# ╟─a4d14606-7e58-4770-8532-66b875c97b70\n# ╠═38f70c35-2609-4599-879d-e032cd7dc49d\n# ╟─1413d047-099f-48c9-bbb0-ff0a3ddb4888\n# ╟─9945ae78-f395-11ea-1d78-cf6ad19606c8\n# ╠═6bac615e-9463-11eb-2210-afa3f2307aa4\n# ╟─87efe4c2-f38d-11ea-39cc-bdfa11298317\n# ╟─f6571d86-f388-11ea-0390-05592acb9195\n# ╟─f626b222-f388-11ea-0d94-1736759b5f52\n# ╟─52452d26-f36c-11ea-01a6-313114b4445d\n# ╠═2a98f268-f3b6-11ea-1eea-81c28256a19e\n# ╟─32e9a944-f3b6-11ea-0e82-1dff6c2eef8d\n# ╟─9101d5a0-f371-11ea-1c04-f3f43b96ca4a\n# ╠═8ec27ef8-f320-11ea-2573-c97b7b908cb7\n# ╠═ad524df7-29e2-4f0d-ad72-8ecdd57e4f02\n# ╠═1add9afd-5ff5-451d-ad81-57b0e929dfe8\n# ╠═9c5d5f94-9468-11eb-3cf2-3301537c7025\n# ╟─414dd91b-8d05-44f0-8bbd-b15981ce1210\n# ╟─447e54f8-d3db-4970-84ee-0708ab8a9244\n# ╠═8b8da8e7-d3b5-410e-b100-5538826c0fde\n# ╟─e1074d35-58c4-43c0-a6cb-1413ed194e25\n# ╠═281b950f-2331-4666-9e45-8fd117813f45\n# ╟─9f18efe2-f38e-11ea-0871-6d7760d0b2f6\n# ╟─a7f3d9f8-f3bb-11ea-0c1a-55bbb8408f09\n# ╠═fa8e2772-f3b6-11ea-30f7-699717693164\n# ╟─18e0fd8a-f3bc-11ea-0713-fbf74d5fa41a\n# ╟─cbf29020-f3ba-11ea-2cb0-b92836f3d04b\n# ╟─8bc930f0-f372-11ea-06cb-79ced2834720\n# ╠═85033040-f372-11ea-2c31-bb3147de3c0d\n# ╟─f92ac3e4-fa70-4bcf-bc50-a36792a8baaa\n# ╠═7ac5eb8d-9dba-4700-8f3a-1e0b2addc740\n# ╠═9ff0ce41-327f-4bf0-958d-309cd0c0b6e5\n# ╟─c572f6ce-f372-11ea-3c9a-e3a21384edca\n# ╠═6d993a5c-f373-11ea-0dde-c94e3bbd1552\n# ╟─ea417c2a-f373-11ea-3bb0-b1b5754f2fac\n# ╟─56a7f954-f374-11ea-0391-f79b75195f4d\n# ╠═b1d09bc8-f320-11ea-26bb-0101c9a204e2\n# ╠═1947f304-fa2c-4019-8584-01ef44ef2859\n# ╟─8992172e-c5b6-463e-a06e-5fe42fb9b16b\n# ╠═b387f8e8-dced-473a-9434-5334829ecfd1\n# ╟─344964a8-7c6b-4720-a624-47b03483263b\n# ╠═3e8b0868-f3bd-11ea-0c15-011bbd6ac051\n# ╠═d941c199-ed77-47dd-8b5a-e34b864f9a79\n# ╠═726280f0-682f-4b05-bf5a-688554a96287\n# ╟─c1ab3d5f-8e6c-4702-ad40-6c7f787f1c43\n# ╟─4e3bcf88-f3c5-11ea-3ada-2ff9213647b7\n# ╟─4e3ef866-f3c5-11ea-3fb0-27d1ca9a9a3f\n# ╟─6e73b1da-f3c5-11ea-145f-6383effe8a89\n# ╟─cf39fa2a-f374-11ea-0680-55817de1b837\n# ╠═c8724b5e-f3bd-11ea-0034-b92af21ca12d\n# ╟─6435994e-d470-4cf3-9f9d-d00df183873e\n# ╠═be7d40e2-f320-11ea-1b56-dff2a0a16e8d\n# ╟─507f3870-f3c5-11ea-11f6-ada3bb087634\n# ╟─50829af6-f3c5-11ea-04a8-0535edd3b0aa\n# ╟─9e56ecfa-f3c5-11ea-2e90-3b1839d12038\n# ╟─4f48c8b8-f39d-11ea-25d2-1fab031a514f\n# ╟─24792456-f37b-11ea-07b2-4f4c8caea633\n# ╠═ff055726-f320-11ea-32f6-2bf38d7dd310\n# ╟─e0622780-f3b4-11ea-1f44-59fb9c5d2ebd\n# ╠═51731519-1831-46a3-a599-d6fc2f7e4224\n# ╠═99efaf6a-0109-4b16-89b8-f8149b6b69c2\n# ╠═d3e69cf6-61b1-42fc-9abd-42d1ae7d61b2\n# ╟─e06d4e4a-146c-4dbd-b742-317f638a3bd8\n# ╟─92e19f22-f37b-11ea-25f7-e321337e375e\n# ╠═795eb2c4-f37b-11ea-01e1-1dbac3c80c13\n# ╟─51df0c98-f3c5-11ea-25b8-af41dc182bac\n# ╟─51e28596-f3c5-11ea-2237-2b72bbfaa001\n# ╟─0a10acd8-f3c6-11ea-3e2f-7530a0af8c7f\n# ╟─946b69a0-f3a2-11ea-2670-819a5dafe891\n# ╟─0fbe2af6-f381-11ea-2f41-23cd1cf930d9\n# ╟─48089a00-f321-11ea-1479-e74ba71df067\n# ╟─6b4d6584-f3be-11ea-131d-e5bdefcc791b\n# ╟─437ba6ce-f37d-11ea-1010-5f6a6e282f9b\n# ╟─ef88c388-f388-11ea-3828-ff4db4d1874e\n# ╟─ef26374a-f388-11ea-0b4e-67314a9a9094\n# ╟─6bdbcf4c-f321-11ea-0288-fb16ff1ec526\n# ╟─ffc17f40-f380-11ea-30ee-0fe8563c0eb1\n# ╟─ffc40ab2-f380-11ea-2136-63542ff0f386\n# ╟─ffceaed6-f380-11ea-3c63-8132d270b83f\n# ╟─ffde44ae-f380-11ea-29fb-2dfcc9cda8b4\n# ╟─ffe326e0-f380-11ea-3619-61dd0592d409\n# ╟─fff5aedc-f380-11ea-2a08-99c230f8fa32\n# ╟─00026442-f381-11ea-2b41-bde1fff66011\n# ╟─fbf6b0fa-f3e0-11ea-2009-573a218e2460\n# ╟─256edf66-f3e1-11ea-206e-4f9b4f6d3a3d\n# ╟─00115b6e-f381-11ea-0bc6-61ca119cb628\n", "meta": {"hexsha": "054263eb642937cd0fabcfdb7faddfee9b4329d1", "size": 38203, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Spring21_notebooks/homeworks/hw4.jl", "max_stars_repo_name": "elixir-1/Introduction-to-Computational-Thinking", "max_stars_repo_head_hexsha": "de05dc13acfa3d6998f0882f40062d8858f9ebb6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Spring21_notebooks/homeworks/hw4.jl", "max_issues_repo_name": "elixir-1/Introduction-to-Computational-Thinking", "max_issues_repo_head_hexsha": "de05dc13acfa3d6998f0882f40062d8858f9ebb6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Spring21_notebooks/homeworks/hw4.jl", "max_forks_repo_name": "elixir-1/Introduction-to-Computational-Thinking", "max_forks_repo_head_hexsha": "de05dc13acfa3d6998f0882f40062d8858f9ebb6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7641509434, "max_line_length": 412, "alphanum_fraction": 0.7323246865, "num_tokens": 15437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926492132671, "lm_q2_score": 0.3311197330283893, "lm_q1q2_score": 0.14880277403241762}}
{"text": "\n\"\"\"\n`module JAC.Dielectronic` \n ... a submodel of JAC that contains all methods for computing dielectronic recombination properties between \n some initial, intermediate and final-state multiplets.\n\"\"\"\nmodule Dielectronic\n\n using Printf, ..AngularMomentum, ..AutoIonization, ..Basics, ..Continuum, ..Defaults, ..ManyElectron, ..Nuclear, \n ..PhotoEmission, ..Radial, ..TableStrings\n\n \"\"\"\n `struct Dielectronic.Settings` \n ... defines a type for the details and parameters of computing dielectronic recombination pathways.\n\n + multipoles ::Array{EmMultipoles} ... Multipoles of the radiation field that are to be included.\n + gauges ::Array{UseGauge} ... Specifies the gauges to be included into the computations.\n + printBefore ::Bool ... True, if all energies and pathways are printed before their eval.\n + pathwaySelection ::PathwaySelection ... Specifies the selected levels/pathways, if any.\n + electronEnergyShift ::Float64 ... An overall energy shift for all electron energies (i.e. from the \n initial to the resonance levels.\n + photonEnergyShift ::Float64 ... An overall energy shift for all photon energies (i.e. from the \n resonance to the final levels.\n + mimimumPhotonEnergy ::Float64 ... minimum transition energy for which photon transitions are \n included into the evaluation.\n + augerOperator ::AbstractEeInteraction ... Auger operator that is to be used for evaluating the Auger ampl's: \n allowed values are: CoulombInteraction(), BreitInteration(), CoulombBreit()\n \"\"\"\n struct Settings \n multipoles ::Array{EmMultipole,1}\n gauges ::Array{UseGauge}\n printBefore ::Bool \n pathwaySelection ::PathwaySelection\n electronEnergyShift ::Float64\n photonEnergyShift ::Float64\n mimimumPhotonEnergy ::Float64\n augerOperator ::AbstractEeInteraction\n end \n\n\n \"\"\"\n `Dielectronic.Settings()` \n ... constructor for the default values of dielectronic recombination pathway computations.\n \"\"\"\n function Settings()\n Settings([E1], UseGauge[], false, PathwaySelection(), 0., 0., 0., \"Coulomb\")\n end\n\n\n \"\"\"\n ` (set::Dielectronic.Settings;`\n \n multipoles=.., gauges=.., printBefore=.., pathwaySelection=.., \n electronEnergyShift=.., photonEnergyShift=.., mimimumPhotonEnergy=.., augerOperator=..)\n \n ... constructor for modifying the given Dielectronic.Settings by 'overwriting' the previously selected parameters.\n \"\"\"\n function Settings(set::Dielectronic.Settings; \n multipoles::Union{Nothing,Array{EmMultipole,1}}=nothing, gauges::Union{Nothing,Array{UseGauge,1}}=nothing, \n printBefore::Union{Nothing,Bool}=nothing, pathwaySelection::Union{Nothing,PathwaySelection}=nothing, \n electronEnergyShift::Union{Nothing,Float64}=nothing,\n photonEnergyShift::Union{Nothing,Float64}=nothing, mimimumPhotonEnergy::Union{Nothing,Float64}=nothing,\n augerOperator::Union{Nothing,AbstractEeInteraction}=nothing)\n \n if multipoles == nothing multipolesx = set.multipoles else multipolesx = multipoles end \n if gauges == nothing gaugesx = set.gauges else gaugesx = gauges end \n if printBefore == nothing printBeforex = set.printBefore else printBeforex = printBefore end \n if pathwaySelection == nothing pathwaySelectionx = set.pathwaySelection else pathwaySelectionx = pathwaySelection end \n if electronEnergyShift == nothing electronEnergyShiftx = set.electronEnergyShift else electronEnergyShiftx = electronEnergyShift end \n if photonEnergyShift == nothing photonEnergyShiftx = set.photonEnergyShift else photonEnergyShiftx = photonEnergyShift end \n if mimimumPhotonEnergy == nothing mimimumPhotonEnergyx = set.mimimumPhotonEnergy else mimimumPhotonEnergyx = mimimumPhotonEnergy end \n if augerOperator == nothing augerOperatorx = set.augerOperator else augerOperatorx = augerOperator end \n\n Settings( multipolesx, gaugesx, printBeforex, pathwaySelectionx, electronEnergyShiftx, photonEnergyShiftx, \n mimimumPhotonEnergyx, augerOperatorx )\n end\n\n\n # `Base.show(io::IO, settings::Dielectronic.Settings)` ... prepares a proper printout of the variable settings::Dielectronic.Settings.\n function Base.show(io::IO, settings::Dielectronic.Settings) \n println(io, \"multipoles: $(settings.multipoles) \")\n println(io, \"use-gauges: $(settings.gauges) \")\n println(io, \"printBefore: $(settings.printBefore) \")\n println(io, \"pathwaySelection: $(settings.pathwaySelection) \")\n println(io, \"electronEnergyShift: $(settings.electronEnergyShift) \")\n println(io, \"photonEnergyShift: $(settings.photonEnergyShift) \")\n println(io, \"mimimumPhotonEnergy: $(settings.mimimumPhotonEnergy) \")\n println(io, \"augerOperator: $(settings.augerOperator) \")\n end\n\n\n \"\"\"\n `struct Dielectronic.Pathway` \n ... defines a type for a dielectronic recombination pathways that may include the definition of channels and \n their corresponding amplitudes.\n\n + initialLevel ::Level ... initial-(state) level\n + intermediateLevel ::Level ... intermediate-(state) level\n + finalLevel ::Level ... final-(state) level\n + electronEnergy ::Float64 ... energy of the (incoming, captured) electron\n + photonEnergy ::Float64 ... energy of the (emitted) photon\n + captureRate ::Float64 ... rate for the electron capture (Auger rate)\n + photonRate ::EmProperty ... rate for the photon emission\n + angularBeta ::EmProperty ... beta parameter of the photon emission\n + reducedStrength ::EmProperty ... reduced resonance strength S(i -> d -> f) * Gamma_d of this pathway;\n this reduced strength does not require the knowledge of Gamma_d for each pathway.\n + hasChannels ::Bool ... Determines whether the individual channels are defined in terms of their possible\n Auger and radiative channels, or not.\n + captureChannels ::Array{AutoIonization.Channel,1} ... List of |i> --> |n> dielectronic (Auger) capture channels.\n + photonChannels ::Array{PhotoEmission.Channel,1} ... List of |n> --> |f> radiative stabilization channels.\n \"\"\"\n struct Pathway\n initialLevel ::Level\n intermediateLevel ::Level\n finalLevel ::Level\n electronEnergy ::Float64\n photonEnergy ::Float64 \n captureRate ::Float64\n photonRate ::EmProperty\n angularBeta ::EmProperty\n reducedStrength ::EmProperty\n hasChannels ::Bool\n captureChannels ::Array{AutoIonization.Channel,1} \n photonChannels ::Array{PhotoEmission.Channel,1} \n end \n\n\n \"\"\"\n `Dielectronic.Pathway()` \n ... constructor for an 'empty' instance of a dielectronic recombination pathway between a specified \n initial, intermediate and final level.\n \"\"\"\n function Pathway()\n em = EmProperty(0., 0.)\n Pathway(initialLevel, intermediateLevel, finalLevel, 0., 0., 0., em, em, em, false, AutoIonization.Channel[], PhotoEmission.Channel[])\n end\n\n\n # `Base.show(io::IO, pathway::Dielectronic.Pathway)` ... prepares a proper printout of the variable pathway::Dielectronic.Pathway.\n function Base.show(io::IO, pathway::Dielectronic.Pathway) \n println(io, \"initialLevel: $(pathway.initialLevel) \")\n println(io, \"intermediateLevel: $(pathway.intermediateLevel) \")\n println(io, \"finalLevel: $(pathway.finalLevel) \")\n println(io, \"electronEnergy: $(pathway.electronEnergy) \")\n println(io, \"photonEnergy: $(pathway.photonEnergy) \")\n println(io, \"captureRate: $(pathway.captureRate) \")\n println(io, \"photonRate: $(pathway.photonRate) \")\n println(io, \"angularBeta: $(pathway.angularBeta) \")\n println(io, \"reducedStrength: $(pathway.reducedStrength) \")\n println(io, \"hasChannels: $(pathway.hasChannels) \")\n println(io, \"captureChannels: $(pathway.captureChannels) \")\n println(io, \"photonChannels: $(pathway.photonChannels) \")\n end\n\n\n \"\"\"\n `struct Dielectronic.Resonance` \n ... defines a type for a dielectronic resonance as defined by a given initial and resonance level but by summing over all final levels\n\n + initialLevel ::Level ... initial-(state) level\n + intermediateLevel ::Level ... intermediate-(state) level\n + resonanceEnergy ::Float64 ... energy of the resonance w.r.t. the inital-state\n + resonanceStrength ::EmProperty ... strength of this resonance due to the stabilization into any of the allowed final levels.\n + captureRate ::Float64 ... capture (Auger) rate to form the intermediate resonance, starting from the initial level.\n + augerRate ::Float64 ... total (Auger) rate for an electron emission of the intermediate resonance\n + photonRate ::EmProperty ... total photon rate for a photon emission, i.e. for stabilization.\n \"\"\"\n struct Resonance\n initialLevel ::Level\n intermediateLevel ::Level\n resonanceEnergy ::Float64 \n resonanceStrength ::EmProperty\n captureRate ::Float64\n augerRate ::Float64\n photonRate ::EmProperty\n end \n\n\n \"\"\"\n `Dielectronic.Resonance()` \n ... constructor for an 'empty' instance of a dielectronic resonance as defined by a given initial and resonance \n level but by summing over all final levels.\n \"\"\"\n function Resonance()\n em = EmProperty(0., 0.)\n Resonance(initialLevel, intermediateLevel, 0., em, 0., 0., em)\n end\n\n\n # `Base.show(io::IO, resonance::Dielectronic.Resonance)` ... prepares a proper printout of the variable resonance::Dielectronic.Resonance.\n function Base.show(io::IO, resonance::Dielectronic.Resonance) \n println(io, \"initialLevel: $(resonance.initialLevel) \")\n println(io, \"intermediateLevel: $(resonance.intermediateLevel) \")\n println(io, \"resonanceEnergy: $(resonance.resonanceEnergy) \")\n println(io, \"resonanceStrength: $(resonance.resonanceStrength) \")\n println(io, \"captureRate: $(resonance.captureRate) \")\n println(io, \"augerRate: $(resonance.augerRate) \")\n println(io, \"photonRate: $(resonance.photonRate) \")\n end\n\n\n \"\"\"\n `Dielectronic.checkConsistentMultiplets(finalMultiplet::Multiplet, intermediateMultiplet::Multiplet, initialMultiplet::Multiplet)` \n ... to check that the given initial-, intermediate- and final-state levels and multiplets are consistent to each other and\n to avoid later problems with the computations. An error message is issued if an inconsistency occurs,\n and nothing is returned otherwise.\n \"\"\"\n function checkConsistentMultiplets(finalMultiplet::Multiplet, intermediateMultiplet::Multiplet, initialMultiplet::Multiplet)\n initialSubshells = initialMultiplet.levels[1].basis.subshells; ni = length(initialSubshells)\n intermediateSubshells = intermediateMultiplet.levels[1].basis.subshells\n finalSubshells = finalMultiplet.levels[1].basis.subshells\n \n if initialSubshells[1:end] == intermediateSubshells[1:ni] &&\n intermediateSubshells == finalSubshells\n else\n @show initialSubshells\n @show intermediateSubshells\n @show finalSubshells\n error(\"\\nThe order of subshells must be equal for the initial-, intermediate and final states, \\n\" *\n \"and the same subshells must occur in the definition of the intermediate and final states. \\n\" *\n \"Only the initial states can have less subshells; this limitation arises from the angular coefficients.\")\n end\n \n return( nothing )\n end\n\n \n\n \"\"\"\n `Dielectronic.computeAmplitudesProperties(pathway::Dielectronic.Pathway, nm::Nuclear.Model, grid::Radial.Grid, \n nrContinuum::Int64, settings::Dielectronic.Settings, hasCaptureChannels::Bool, lastCaptureChannels::Array{AutoIonization.Channel,1})` \n ... to compute all amplitudes and properties of the given line; a line::Dielectronic.Pathway is returned for which the amplitudes and \n properties have now been evaluated.\n \"\"\"\n function computeAmplitudesProperties(pathway::Dielectronic.Pathway, nm::Nuclear.Model, grid::Radial.Grid, nrContinuum::Int64, \n settings::Dielectronic.Settings, hasCaptureChannels::Bool, \n lastCaptureChannels::Array{AutoIonization.Channel,1})\n rateA = 0.\n println(\">> pathway: $(pathway.initialLevel.index)--$(pathway.intermediateLevel.index)--$(pathway.finalLevel.index) ...\")\n \n if hasCaptureChannels\n # Simply copy the results from previous computation of the same channels\n newcChannels = deepcopy(lastCaptureChannels)\n for cChannel in newcChannels\n rateA = rateA + conj(cChannel.amplitude) * cChannel.amplitude\n end\n else\n newcChannels = AutoIonization.Channel[]; contSettings = Continuum.Settings(false, nrContinuum) \n initialLevel = deepcopy(pathway.initialLevel)\n intermediateLevel = deepcopy(pathway.intermediateLevel)\n Defaults.setDefaults(\"relativistic subshell list\", intermediateLevel.basis.subshells; printout=false)\n for cChannel in pathway.captureChannels\n newnLevel = Basics.generateLevelWithSymmetryReducedBasis(intermediateLevel, intermediateLevel.basis.subshells)\n newiLevel = Basics.generateLevelWithSymmetryReducedBasis(initialLevel, newnLevel.basis.subshells)\n newnLevel = Basics.generateLevelWithExtraSubshell(Subshell(101, cChannel.kappa), newnLevel)\n cOrbital, phase = Continuum.generateOrbitalForLevel(pathway.electronEnergy, Subshell(101, cChannel.kappa), newiLevel, nm, grid, contSettings)\n newcLevel = Basics.generateLevelWithExtraElectron(cOrbital, cChannel.symmetry, newiLevel)\n newcChannel = AutoIonization.Channel( cChannel.kappa, cChannel.symmetry, phase, Complex(0.))\n amplitude = AutoIonization.amplitude(settings.augerOperator, cChannel, newnLevel, newcLevel, grid)\n rateA = rateA + conj(amplitude) * amplitude\n newcChannel = AutoIonization.Channel( cChannel.kappa, cChannel.symmetry, phase, amplitude)\n push!( newcChannels, newcChannel)\n end\n end\n #\n finalLevel = deepcopy(pathway.finalLevel)\n intermediateLevel = deepcopy(pathway.intermediateLevel)\n Defaults.setDefaults(\"relativistic subshell list\", intermediateLevel.basis.subshells; printout=false)\n \n newpChannels = PhotoEmission.Channel[]; rateC = 0.; rateB = 0.\n for pChannel in pathway.photonChannels\n amplitude = PhotoEmission.amplitude(\"emission\", pChannel.multipole, pChannel.gauge, pathway.photonEnergy, \n finalLevel, intermediateLevel, grid, display=false, printout=false)\n newpChannel = PhotoEmission.Channel( pChannel.multipole, pChannel.gauge, amplitude)\n push!( newpChannels, newpChannel)\n if newpChannel.gauge == Basics.Coulomb rateC = rateC + abs(amplitude)^2\n elseif newpChannel.gauge == Basics.Babushkin rateB = rateB + abs(amplitude)^2\n elseif newpChannel.gauge == Basics.Magnetic rateB = rateB + abs(amplitude)^2; rateC = rateC + abs(amplitude)^2\n end\n end\n captureRate = 2pi * rateA\n wa = 8.0pi * Defaults.getDefaults(\"alpha\") * pathway.photonEnergy / (Basics.twice(pathway.intermediateLevel.J) + 1) * \n (Basics.twice(pathway.finalLevel.J) + 1)\n photonRate = EmProperty(wa * rateC, wa * rateB) \n angularBeta = EmProperty(-9., -9.)\n # Factor due to UserGuide\n wa = Defaults.convertUnits(\"kinetic energy to wave number: atomic units\", pathway.electronEnergy)\n wa = pi*pi / (wa*wa) * captureRate * # 2 *\n (Basics.twice(pathway.intermediateLevel.J) + 1) / (Basics.twice(pathway.initialLevel.J) + 1)\n # Factor due to Tu et al. (Plasma Phys., 2016)\n ## wa = pi*pi / 2. / pathway.electronEnergy * captureRate * \n ## (Basics.twice(pathway.intermediateLevel.J) + 1) / (Basics.twice(pathway.initialLevel.J) + 1)\n reducedStrength = EmProperty(wa * photonRate.Coulomb, wa * photonRate.Babushkin)\n pathway = Dielectronic.Pathway( pathway.initialLevel, pathway.intermediateLevel, pathway.finalLevel, pathway.electronEnergy, \n pathway.photonEnergy, captureRate, photonRate, angularBeta, reducedStrength, true, newcChannels, newpChannels)\n return( pathway )\n end\n\n\n \"\"\"\n `Dielectronic.computePathways(finalMultiplet::Multiplet, intermediateMultiplet::Multiplet, initialMultiplet::Multiplet, nm::Nuclear.Model, \n grid::Radial.Grid, settings::Dielectronic.Settings; output=true)` \n ... to compute the dielectronic recombination amplitudes and all properties as requested by the given settings. \n A list of pathways::Array{Dielectronic.Pathway,1} is returned.\n \"\"\"\n function computePathways(finalMultiplet::Multiplet, intermediateMultiplet::Multiplet, initialMultiplet::Multiplet, nm::Nuclear.Model, \n grid::Radial.Grid, settings::Dielectronic.Settings; output=true)\n println(\"\")\n printstyled(\"Dielectronic.computePathways(): The computation of dielectronic resonance strength, etc. starts now ... \\n\", color=:light_green)\n printstyled(\"------------------------------------------------------------------------------------------------------- \\n\", color=:light_green)\n println(\"\")\n # First check that the initial, intermediate and final-state multiplets are consistent with each other to allow all requested computations\n Dielectronic.checkConsistentMultiplets(finalMultiplet, intermediateMultiplet, initialMultiplet)\n #\n pathways = Dielectronic.determinePathways(finalMultiplet, intermediateMultiplet, initialMultiplet, settings)\n # Display all selected pathways before the computations start\n if settings.printBefore Dielectronic.displayPathways(pathways) end\n # Determine maximum (electron) energy and check for consistency of the grid\n maxEnergy = 0.; for pathway in pathways maxEnergy = max(maxEnergy, pathway.electronEnergy) end\n nrContinuum = Continuum.gridConsistency(maxEnergy, grid)\n #\n # Calculate all amplitudes and requested properties; simply copy if the captureChannels have been computed before\n newPathways = Dielectronic.Pathway[]; \n hasCaptureChannels = false; lastCaptureIndices = (0,0); lastCaptureChannels = AutoIonization.Channel[]\n for pathway in pathways\n if (pathway.initialLevel.index, pathway.intermediateLevel.index) == lastCaptureIndices hasCaptureChannels = true\n else hasCaptureChannels = false\n end\n newPathway = Dielectronic.computeAmplitudesProperties(pathway, nm, grid, nrContinuum, settings, hasCaptureChannels, lastCaptureChannels) \n push!( newPathways, newPathway)\n #\n lastCaptureIndices = (newPathway.initialLevel.index, newPathway.intermediateLevel.index)\n lastCaptureChannels = newPathway.captureChannels\n end\n # \n # Calculate all corresponding resonance\n resonances = Dielectronic.computeResonances(newPathways, settings)\n # Print all results to screen\n Dielectronic.displayResults(stdout, newPathways, settings)\n Dielectronic.displayResults(stdout, resonances, settings)\n printSummary, iostream = Defaults.getDefaults(\"summary flag/stream\")\n if printSummary Dielectronic.displayResults(iostream, newPathways, settings)\n Dielectronic.displayResults(iostream, resonances, settings) end\n #\n if output return( newPathways )\n else return( nothing )\n end\n end\n\n\n \"\"\"\n `Dielectronic.computeResonances(pathways::Array{Dielectronic.Pathway,1}, settings::Dielectronic.Settings)` \n ... to compute the data for all resonances (resonance lines) as defined by the given pathways and and settings. \n A list of resonances::Array{Dielectronic.Resonance,1} is returned.\n \"\"\"\n function computeResonances(pathways::Array{Dielectronic.Pathway,1}, settings::Dielectronic.Settings)\n # Determine all pre-defined resonances in pathways\n resonances = Dielectronic.Resonance[]; idxTuples = Tuple{Int64,Int64}[]\n for pathway in pathways idxTuples = union(idxTuples, [(pathway.initialLevel.index, pathway.intermediateLevel.index)] ) end\n # Determine the capture rate for each idxTuple\n captureRates = zeros( length(idxTuples) )\n for (idx, idxTuple) in enumerate(idxTuples)\n for pathway in pathways \n if idxTuple == (pathway.initialLevel.index, pathway.intermediateLevel.index)\n captureRates[idx] = pathway.captureRate\n end\n end\n end\n #\n # Determine the resonances\n electronEnergyShift = Defaults.convertUnits(\"energy: to atomic\", settings.electronEnergyShift)\n for idxTuple in idxTuples\n iLevel = Level(); nLevel = Level(); resonanceEnergy = 0.; reducedStrength = EmProperty(0., 0.)\n captureRate = 0.; augerRate = 0.; photonRate = EmProperty(0., 0.)\n for pathway in pathways \n if idxTuple == (pathway.initialLevel.index, pathway.intermediateLevel.index)\n iLevel = pathway.initialLevel\n nLevel = pathway.intermediateLevel\n resonanceEnergy = pathway.intermediateLevel.energy - pathway.initialLevel.energy + electronEnergyShift\n captureRate = pathway.captureRate \n photonRate = photonRate + pathway.photonRate\n reducedStrength = reducedStrength + pathway.reducedStrength\n end\n end\n # Determine total Auger rates by summation over all idxTupels with the same m\n for (idx, idxxTuple) in enumerate(idxTuples)\n if idxTuple[2] == idxxTuple[2] augerRate = captureRates[idx] end\n end\n \n resonanceStrength = reducedStrength / (augerRate + photonRate)\n push!( resonances, Dielectronic.Resonance( iLevel, nLevel, resonanceEnergy, resonanceStrength, captureRate, augerRate, photonRate) )\n end\n \n return( resonances )\n end\n\n\n \"\"\"\n `Dielectronic.determineCaptureChannels(intermediateLevel::Level, initialLevel::Level, settings::Dielectronic.Settings)` \n ... to determine a list of AutoIonization.Channel for a (Auger) capture transitions from the initial to an intermediate level, and by \n taking into account the particular settings of for this computation; an Array{AutoIonization.Channel,1} is returned.\n \"\"\"\n function determineCaptureChannels(intermediateLevel::Level, initialLevel::Level, settings::Dielectronic.Settings)\n channels = AutoIonization.Channel[]; \n symi = LevelSymmetry(initialLevel.J, initialLevel.parity); symn = LevelSymmetry(intermediateLevel.J, intermediateLevel.parity)\n kappaList = AngularMomentum.allowedKappaSymmetries(symi, symn)\n for kappa in kappaList\n push!( channels, AutoIonization.Channel(kappa, symn, 0., Complex(0.)) )\n end\n\n return( channels ) \n end\n\n\n \"\"\"\n `Dielectronic.determinePhotonChannels(finalLevel::Level, intermediateLevel::Level, settings::Dielectronic.Settings)` \n ... to determine a list of PhotoEmission.Channel for the photon transitions from the intermediate and to a final level, and by \n taking into account the particular settings of for this computation; an Array{PhotoEmission.Channel,1} is returned.\n \"\"\"\n function determinePhotonChannels(finalLevel::Level, intermediateLevel::Level, settings::Dielectronic.Settings)\n channels = PhotoEmission.Channel[]; \n symn = LevelSymmetry(intermediateLevel.J, intermediateLevel.parity); symf = LevelSymmetry(finalLevel.J, finalLevel.parity) \n for mp in settings.multipoles\n if AngularMomentum.isAllowedMultipole(symn, mp, symf)\n hasMagnetic = false\n for gauge in settings.gauges\n # Include further restrictions if appropriate\n if string(mp)[1] == 'E' && gauge == UseCoulomb push!(channels, PhotoEmission.Channel(mp, Basics.Coulomb, 0.) )\n elseif string(mp)[1] == 'E' && gauge == UseBabushkin push!(channels, PhotoEmission.Channel(mp, Basics.Babushkin, 0.) ) \n elseif string(mp)[1] == 'M' && !(hasMagnetic) push!(channels, PhotoEmission.Channel(mp, Basics.Magnetic, 0.) );\n hasMagnetic = true; \n end \n end\n end\n end\n\n return( channels ) \n end\n\n\n \"\"\"\n `Dielectronic.determinePathways(finalMultiplet::Multiplet, intermediateMultiplet::Multiplet, initialMultiplet::Multiplet, \n settings::Dielectronic.Settings)` \n ... to determine a list of dielectronic-recombination pathways between the levels from the given initial-, intermediate- and \n final-state multiplets and by taking into account the particular selections and settings for this computation; \n an Array{Dielectronic.Pathway,1} is returned. Apart from the level specification, all physical properties are set to zero \n during the initialization process. \n \"\"\"\n function determinePathways(finalMultiplet::Multiplet, intermediateMultiplet::Multiplet, initialMultiplet::Multiplet, settings::Dielectronic.Settings)\n pathways = Dielectronic.Pathway[]\n electronEnergyShift = Defaults.convertUnits(\"energy: to atomic\", settings.electronEnergyShift)\n photonEnergyShift = Defaults.convertUnits(\"energy: to atomic\", settings.photonEnergyShift)\n for iLevel in initialMultiplet.levels\n for nLevel in intermediateMultiplet.levels\n for fLevel in finalMultiplet.levels\n if Basics.selectLevelTriple(iLevel, nLevel, fLevel, settings.pathwaySelection)\n eEnergy = nLevel.energy - iLevel.energy + electronEnergyShift\n pEnergy = nLevel.energy - fLevel.energy + photonEnergyShift\n if pEnergy < 0. || eEnergy < 0. continue end\n cChannels = Dielectronic.determineCaptureChannels(nLevel, iLevel, settings) \n pChannels = Dielectronic.determinePhotonChannels( fLevel, nLevel, settings) \n push!( pathways, Dielectronic.Pathway(iLevel, nLevel, fLevel, eEnergy, pEnergy, 0., EmProperty(0., 0.), \n EmProperty(0., 0.), EmProperty(0., 0.), true, cChannels, pChannels) )\n end\n end\n end\n end\n return( pathways )\n end\n\n\n \"\"\"\n `Dielectronic.displayPathways(pathways::Array{Dielectronic.Pathway,1})` \n ... to display a list of pathways and channels that have been selected due to the prior settings. A neat table of all selected \n transitions and energies is printed but nothing is returned otherwise.\n \"\"\"\n function displayPathways(pathways::Array{Dielectronic.Pathway,1})\n nx = 180\n println(\" \")\n println(\" Selected dielectronic-recombination pathways:\")\n println(\" \")\n println(\" \", TableStrings.hLine(nx))\n sa = \" \"; sb = \" \"\n sa = sa * TableStrings.center(23, \"Levels\"; na=4); sb = sb * TableStrings.center(23, \"i -- m -- f\"; na=4); \n sa = sa * TableStrings.center(23, \"J^P symmetries\"; na=3); sb = sb * TableStrings.center(23, \"i -- m -- f\"; na=3);\n sa = sa * TableStrings.center(26, \"Energies \" * TableStrings.inUnits(\"energy\"); na=5); \n sb = sb * TableStrings.center(26, \"electron photon \"; na=5)\n sa = sa * TableStrings.flushleft(57, \"List of multipoles, gauges, kappas and total symmetries\"; na=4) \n sb = sb * TableStrings.flushleft(57, \"partial (multipole, gauge, total J^P) \"; na=4)\n println(sa); println(sb); println(\" \", TableStrings.hLine(nx)) \n # \n for pathway in pathways\n sa = \" \"; isym = LevelSymmetry( pathway.initialLevel.J, pathway.initialLevel.parity)\n msym = LevelSymmetry( pathway.intermediateLevel.J, pathway.intermediateLevel.parity)\n fsym = LevelSymmetry( pathway.finalLevel.J, pathway.finalLevel.parity)\n sa = sa * TableStrings.center(23, TableStrings.levels_imf(pathway.initialLevel.index, pathway.intermediateLevel.index, \n pathway.finalLevel.index); na=5)\n sa = sa * TableStrings.center(23, TableStrings.symmetries_imf(isym, msym, fsym); na=4)\n sa = sa * @sprintf(\"%.6e\", Defaults.convertUnits(\"energy: from atomic\", pathway.electronEnergy)) * \" \"\n sa = sa * @sprintf(\"%.6e\", Defaults.convertUnits(\"energy: from atomic\", pathway.photonEnergy)) * \" \"\n kappaMultipoleSymmetryList = Tuple{Int64,EmMultipole,EmGauge,LevelSymmetry}[]\n for cChannel in pathway.captureChannels\n for pChannel in pathway.photonChannels\n push!( kappaMultipoleSymmetryList, (cChannel.kappa, pChannel.multipole, pChannel.gauge, cChannel.symmetry) )\n end\n end\n wa = TableStrings.kappaMultipoleSymmetryTupels(85, kappaMultipoleSymmetryList)\n if length(wa) > 0 sb = sa * wa[1]; println( sb ) end \n for i = 2:length(wa)\n sb = TableStrings.hBlank( length(sa) ) * wa[i]; println( sb )\n end\n end\n println(\" \", TableStrings.hLine(nx))\n #\n return( nothing )\n end\n\n\n \"\"\"\n `Dielectronic.displayResults(stream::IO, pathways::Array{Dielectronic.Pathway,1}, settings::Dielectronic.Settings)` \n ... to list all results, energies, cross sections, etc. of the selected lines. A neat table is printed but nothing is returned otherwise.\n \"\"\"\n function displayResults(stream::IO, pathways::Array{Dielectronic.Pathway,1}, settings::Dielectronic.Settings)\n nx = 150\n println(stream, \" \")\n println(stream, \" Partial (Auger) capture and radiative decay rates:\")\n println(stream, \" \")\n println(stream, \" \", TableStrings.hLine(nx))\n sa = \" \"; sb = \" \"\n sa = sa * TableStrings.center(23, \"Levels\"; na=2); sb = sb * TableStrings.center(23, \"i -- m -- f\"; na=2); \n sa = sa * TableStrings.center(23, \"J^P symmetries\"; na=0); sb = sb * TableStrings.center(23, \"i -- m -- f\"; na=2);\n sa = sa * TableStrings.center(38, \"Energies \" * TableStrings.inUnits(\"energy\"); na=4); \n sb = sb * TableStrings.center(38, \"electron m--i photon \"; na=1)\n sa = sa * TableStrings.center(10, \"Multipoles\"; na=6); sb = sb * TableStrings.hBlank(17)\n sa = sa * TableStrings.center(36, \"Rates \" * TableStrings.inUnits(\"rate\"); na=2); \n sb = sb * TableStrings.center(36, \"(Auger) capture Cou--photon--Bab\"; na=2)\n println(stream, sa); println(stream, sb); println(stream, \" \", TableStrings.hLine(nx)) \n # \n for pathway in pathways\n sa = \" \"; isym = LevelSymmetry( pathway.initialLevel.J, pathway.initialLevel.parity)\n msym = LevelSymmetry( pathway.intermediateLevel.J, pathway.intermediateLevel.parity)\n fsym = LevelSymmetry( pathway.finalLevel.J, pathway.finalLevel.parity)\n sa = sa * TableStrings.center(23, TableStrings.levels_imf(pathway.initialLevel.index, pathway.intermediateLevel.index, \n pathway.finalLevel.index); na=3)\n sa = sa * TableStrings.center(23, TableStrings.symmetries_imf(isym, msym, fsym); na=4)\n en_mi = pathway.intermediateLevel.energy - pathway.initialLevel.energy\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"energy: from atomic\", pathway.electronEnergy)) * \" \"\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"energy: from atomic\", en_mi)) * \" \"\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"energy: from atomic\", pathway.photonEnergy)) * \" \"\n multipoles = EmMultipole[]\n for pch in pathway.photonChannels\n multipoles = push!( multipoles, pch.multipole)\n end\n multipoles = unique(multipoles); mpString = TableStrings.multipoleList(multipoles) * \" \"\n sa = sa * TableStrings.flushleft(16, mpString[1:15]; na=0)\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"rate: from atomic\", pathway.captureRate)) * \" \"\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"rate: from atomic\", pathway.photonRate.Coulomb)) * \" \"\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"rate: from atomic\", pathway.photonRate.Babushkin)) * \" \"\n println(stream, sa)\n end\n println(stream, \" \", TableStrings.hLine(nx))\n #\n #\n #\n nx = 137\n println(stream, \" \")\n println(stream, \" Partial resonance strength:\")\n println(stream, \" \")\n println(stream, \" \", TableStrings.hLine(nx))\n sa = \" \"; sb = \" \"\n sa = sa * TableStrings.center(23, \"Levels\"; na=2); sb = sb * TableStrings.center(23, \"i -- m -- f\"; na=2); \n sa = sa * TableStrings.center(23, \"J^P symmetries\"; na=0); sb = sb * TableStrings.center(23, \"i -- m -- f\"; na=2);\n sa = sa * TableStrings.center(38, \"Energies \" * TableStrings.inUnits(\"energy\"); na=4); \n sb = sb * TableStrings.center(38, \"electron m--i photon \"; na=1)\n sa = sa * TableStrings.center(10, \"Multipoles\"; na=5); sb = sb * TableStrings.hBlank(16)\n sa = sa * TableStrings.center(26, \"S * Gamma_m \" * TableStrings.inUnits(\"reduced strength\"); na=2); \n sb = sb * TableStrings.center(26, \" Cou -- photon -- Bab\"; na=2)\n println(stream, sa); println(stream, sb); println(stream, \" \", TableStrings.hLine(nx)) \n # \n for pathway in pathways\n sa = \" \"; isym = LevelSymmetry( pathway.initialLevel.J, pathway.initialLevel.parity)\n msym = LevelSymmetry( pathway.intermediateLevel.J, pathway.intermediateLevel.parity)\n fsym = LevelSymmetry( pathway.finalLevel.J, pathway.finalLevel.parity)\n sa = sa * TableStrings.center(23, TableStrings.levels_imf(pathway.initialLevel.index, pathway.intermediateLevel.index, \n pathway.finalLevel.index); na=3)\n sa = sa * TableStrings.center(23, TableStrings.symmetries_imf(isym, msym, fsym); na=4)\n en_mi = pathway.intermediateLevel.energy - pathway.initialLevel.energy\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"energy: from atomic\", pathway.electronEnergy)) * \" \"\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"energy: from atomic\", en_mi)) * \" \"\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"energy: from atomic\", pathway.photonEnergy)) * \" \"\n multipoles = EmMultipole[]\n for pch in pathway.photonChannels\n multipoles = push!( multipoles, pch.multipole)\n end\n multipoles = unique(multipoles); mpString = TableStrings.multipoleList(multipoles) * \" \"\n sa = sa * TableStrings.flushleft(16, mpString[1:15]; na=0)\n wa = Defaults.convertUnits(\"strength: from atomic\", 1.0) * Defaults.convertUnits(\"energy: from atomic\", 1.0)\n sa = sa * @sprintf(\"%.4e\", wa * pathway.reducedStrength.Coulomb) * \" \"\n sa = sa * @sprintf(\"%.4e\", wa * pathway.reducedStrength.Babushkin) * \" \"\n println(stream, sa)\n end\n println(stream, \" \", TableStrings.hLine(nx))\n #\n return( nothing )\n end\n\n\n \"\"\"\n + (stream::IO, resonances::Array{Dielectronic.Resonance,1}, settings::Dielectronic.Settings)` \n ... to list all results for the resonances. A neat table is printed but nothing is returned otherwise.\n \"\"\"\n function displayResults(stream::IO, resonances::Array{Dielectronic.Resonance,1}, settings::Dielectronic.Settings)\n nx = 160\n println(stream, \" \")\n println(stream, \" Total Auger rates, radiative rates and resonance strengths:\")\n println(stream, \" \")\n println(stream, \" \", TableStrings.hLine(nx))\n sa = \" \"; sb = \" \"\n sa = sa * TableStrings.center(18, \"i-level-m\"; na=2); sb = sb * TableStrings.hBlank(20)\n sa = sa * TableStrings.center(18, \"i--J^P--m\"; na=2); sb = sb * TableStrings.hBlank(20)\n sa = sa * TableStrings.center(14, \"Energy\" ; na=2); \n sb = sb * TableStrings.center(14,TableStrings.inUnits(\"energy\"); na=2)\n sa = sa * TableStrings.center(42, \"Auger rate Cou -- rad. rates -- Bab\"; na=1); \n sb = sb * TableStrings.center(16, TableStrings.inUnits(\"rate\"); na=1)\n sb = sb * TableStrings.center(12, TableStrings.inUnits(\"rate\"); na=0)\n sb = sb * TableStrings.center(12, TableStrings.inUnits(\"rate\"); na=6)\n sa = sa * TableStrings.center(30, \"Cou -- res. strength -- Bab\"; na=3); \n sb = sb * TableStrings.center(12, TableStrings.inUnits(\"strength\"); na=0)\n sb = sb * TableStrings.center(12, TableStrings.inUnits(\"strength\"); na=2)\n sa = sa * TableStrings.center(18, \"Widths Gamma_m\"; na=2); \n sb = sb * TableStrings.center(16, TableStrings.inUnits(\"energy\"); na=6)\n println(stream, sa); println(stream, sb); println(stream, \" \", TableStrings.hLine(nx)) \n # \n for resonance in resonances\n sa = \"\"; isym = LevelSymmetry( resonance.initialLevel.J, resonance.initialLevel.parity)\n msym = LevelSymmetry( resonance.intermediateLevel.J, resonance.intermediateLevel.parity)\n sa = sa * TableStrings.center(18, TableStrings.levels_if(resonance.initialLevel.index, resonance.intermediateLevel.index); na=4)\n sa = sa * TableStrings.center(18, TableStrings.symmetries_if(isym, msym); na=4)\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"energy: from atomic\", resonance.resonanceEnergy)) * \" \"\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"rate: from atomic\", resonance.augerRate)) * \" \"\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"rate: from atomic\", resonance.photonRate.Coulomb)) * \" \"\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"rate: from atomic\", resonance.photonRate.Babushkin)) * \" \"\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"strength: from atomic\", resonance.resonanceStrength.Coulomb)) * \" \"\n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"strength: from atomic\", resonance.resonanceStrength.Babushkin)) * \" \"\n wa = resonance.augerRate + resonance.photonRate.Coulomb \n sa = sa * @sprintf(\"%.4e\", Defaults.convertUnits(\"energy: from atomic\", wa)) * \" \"\n wa = resonance.augerRate + resonance.photonRate.Babushkin \n sa = sa * \"(\" * @sprintf(\"%.4e\", Defaults.convertUnits(\"energy: from atomic\", wa)) * \")\" * \" \"\n println(stream, sa)\n end\n println(stream, \" \", TableStrings.hLine(nx))\n #\n return( nothing )\n end\n\nend # module\n", "meta": {"hexsha": "33eb7ebd17d1571d9e25d8af32498da5763cb5e2", "size": 43194, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/module-Dielectronic.jl", "max_stars_repo_name": "mfherbst/JAC.jl", "max_stars_repo_head_hexsha": "43563c049a995817ada86ce82908714d4e1a034b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/module-Dielectronic.jl", "max_issues_repo_name": "mfherbst/JAC.jl", "max_issues_repo_head_hexsha": "43563c049a995817ada86ce82908714d4e1a034b", "max_issues_repo_licenses": ["MIT"], "max_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-Dielectronic.jl", "max_forks_repo_name": "mfherbst/JAC.jl", "max_forks_repo_head_hexsha": "43563c049a995817ada86ce82908714d4e1a034b", "max_forks_repo_licenses": ["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.7442922374, "max_line_length": 158, "alphanum_fraction": 0.6013335185, "num_tokens": 9884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.28776780354463427, "lm_q1q2_score": 0.14725556337303553}}
{"text": "export\n AbstractDisturbance,\n DisturbanceSequence\n\nabstract type AbstractDisturbance end\nconst DisturbanceSequence = Vector{Pair{Int,AbstractDisturbance}}\n\n\nexport\n StochasticProblem,\n stochastic_problem\n\n\"\"\"\n StochasticProblem{P<:AbstractPC_TAPF}\n\nDefines a stochastic version of PC_TAPF, wherein different disturbances can\ncause unexpected problems in the factory.\n\"\"\"\nstruct StochasticProblem{P<:AbstractPC_TAPF}\n prob::P\n disturbances::DisturbanceSequence\nend\nCRCBS.get_env(spc_tapf::StochasticProblem) = get_env(spc_tapf.prob)\n\nfunction stochastic_problem(ptype::Type{P},solver,prob,clean_up_bot_ICS,disturbances) where {P<:AbstractPC_MAPF}\n env = get_env(deepcopy(prob))\n env_graph = get_graph(env)\n sched = get_schedule(env)\n cache = get_cache(env)\n for pred in clean_up_bot_ICS\n add_new_robot_to_schedule!(sched,pred,get_problem_spec(env))\n end\n robot_ICs = get_robot_ICs(sched)\n prob_spec = get_problem_spec(env)\n # populate_environment_dict_layers!(env.env_layers,sched,env_graph,prob_spec)\n new_prob = P(prob,construct_search_env(solver,sched,prob_spec,env_graph,cache))\n StochasticProblem(new_prob,disturbances)\nend\n\nexport OilSpill\n\"\"\"\n OilSpill\n\nAn obstruction that affects vertices `vtxs` and edges `edges`.\n\"\"\"\nstruct OilSpill <: AbstractDisturbance\n vtxs::Set{Int}\n edges::Set{Edge}\nend\nfunction OilSpill(G::AbstractGraph,vtxs::Vector{Int})\n OilSpill(Set(vtxs),edge_cover(G,vtxs))\nend\n\nexport Intruder\n\"\"\"\n Intruder\n\nAn intruder that begins at location `start_vtx` and follows policy `policy`\n\"\"\"\nstruct Intruder{P} <: AbstractDisturbance\n policy::P\n start_vtx::Int # start vtx\nend\n\nexport DeadRobot\n\"\"\"\n DeadRobot\n\nRobot `id` is frozen.\n\nEffect:\n- Freeze robot\n- Add \"no-go\" constraint to CBS/PIBT (how to do consistently? Perhaps place in\n SearchEnv and add directly to PCCBSEnv) OR temporarily remove vertex from\n graph\n- Set robot state to NULL state? How to avoid having CBS complain about\n conflicts? Maybe set State to NULL State and place DeadRobotObject at the\n collection site?\n- Dispatch CleanUpBot to collect frozen robot\n- When CleanUpBot returns to \"garage\", regenerate frozen Robot's ROBOT_AT node\n and valid state.\n\"\"\"\nstruct DeadRobot <: AbstractDisturbance\n id::Int\nend\n\nexport DelayedRobot\n\"\"\"\n DelayedRobot\n\nRobot `id` is delayed by `dt` timesteps.\n\"\"\"\nstruct DelayedRobot <: AbstractDisturbance\n id::Int\n dt::Int\nend\n\nexport DroppedObject\n\"\"\"\n DroppedObject\n\nObject `id` dropped.\n\"\"\"\nstruct DroppedObject <: AbstractDisturbance\n id::Int\nend\n\n\nexport handle_disturbance!\n\nfunction remove_vtxs(sched,remove_set::Set{A}) where {A<:AbstractID}\n remove_vtxs(sched,Set{Int}(get_vtx(sched,id) for id in remove_set))\nend\nfunction remove_vtxs!(sched,remove_set)\n new_sched = sched\n rem_nodes!(new_sched,remove_set)\n set_leaf_operation_vtxs!(new_sched)\n process_schedule!(new_sched)\n new_sched\nend\nfunction remove_vtxs(sched,remove_set)\n # Construct new graph\n # new_sched = sched\n # rem_nodes!(new_sched,remove_set)\n # set_leaf_operation_vtxs!(new_sched)\n # process_schedule!(new_sched)\n\n new_sched = OperatingSchedule()\n keep_vtxs = setdiff(Set{Int}(collect(vertices(sched))), remove_set)\n # add all non-deleted nodes to new project schedule\n for v in keep_vtxs\n # node_id = get_vtx_id(sched,v)\n # node = get_node_from_id(sched, node_id)\n # path_spec = get_path_spec(sched,v)\n # add_to_schedule!(new_sched,path_spec,node,node_id)\n add_to_schedule!(new_sched,get_node(sched,v))\n end\n # add all edges between nodes that still exist\n for e in edges(get_graph(sched))\n add_edge!(new_sched, get_vtx_id(sched, e.src), get_vtx_id(sched, e.dst))\n end\n set_leaf_operation_vtxs!(new_sched)\n process_schedule!(new_sched)\n # @assert sanity_check(new_sched)\n new_sched\nend\n\n\"\"\"\n get_delivery_task_vtxs(sched::OperatingSchedule,o::ObjectID)\n\nReturn all vertices that correspond to the delivery task\n(`COLLECT` → `CARRY` → `DEPOSIT`) of object `o`.\n\"\"\"\nfunction get_delivery_task_vtxs(sched::OperatingSchedule,o::ObjectID)\n v = get_vtx(sched,o)\n vtxs = collect(capture_connected_nodes(sched,v,\n v->check_object_id(get_node_from_vtx(sched,v),o)))\n setdiff!(vtxs,v)\n return vtxs\nend\n\"\"\"\n isolate_delivery_task_vtxs(sched,o,vtxs=get_delivery_task_vtxs(sched,o))\n\nReturns:\n- incoming: a set of all incoming Action ScheduleNodes\n- outgoing: a set of all outgoing Action ScheduleNodes\n- op: the target Operation\n\"\"\"\nfunction isolate_delivery_task_vtxs(sched::OperatingSchedule,o::ObjectID,\n vtxs=get_delivery_task_vtxs(sched,o)\n )\n node_ids = Set{AbstractID}(get_vtx_id(sched,v) for v in vtxs)\n # incoming and outgoing robot nodes -- for single and team robot tasks\n in_edges = exclusive_edge_cover(sched,vtxs,:in)\n incoming = filter(node->matches_template(AbstractRobotAction,node),\n map(e->get_node(sched,e.src),collect(in_edges)))\n out_edges = exclusive_edge_cover(sched,vtxs,:out)\n outgoing = filter(node->matches_template(AbstractRobotAction,node),\n map(e->get_node(sched,e.dst),collect(out_edges)))\n # target operation node\n op = filter(node->matches_template(Operation,node),\n map(e->get_node(sched,e.dst),collect(out_edges)))[1]\n return incoming, outgoing, op\nend\n\n\"\"\"\n stitch_disjoint_node_sets!(sched,incoming,outgoing)\n\nFinds and adds the appropriate edges between two sets of nodes. It is assumed\nthat `size(incoming) == size(outgoing)`, that each node in `incoming` has\nexactly one feasible successor in `outgoing`, and that each node in `outgoing`\nhas exactly one feasible predecessor in `incoming`.\n\"\"\"\nfunction stitch_disjoint_node_sets!(sched,incoming,outgoing,env_state)\n @assert length(incoming) == length(outgoing)\n out_idxs = collect(1:length(outgoing))\n for node1 in incoming\n r = get_robot_id(node1)\n for i in 1:length(outgoing)\n idx = out_idxs[i]\n node2 = outgoing[idx]\n node2 = outgoing[i]\n if get_robot_id(node2) == r\n x = get_location_id(robot_positions(env_state)[r])\n add_edge!(sched,node1,node2)\n n1 = BOT_GO(r,get_initial_location_id(node1),x)\n n2 = BOT_GO(r,x,get_destination_location_id(node2))\n @log_info(-1,0,\"connecting \",string(n1),\"\",string(n2))\n replace_in_schedule!(sched,n1,node1.id)\n replace_in_schedule!(sched,n2,node2.id)\n deleteat!(out_idxs,i)\n # deleteat!(outgoing,i)\n break\n end\n end\n end\n @assert length(out_idxs) == 0\n # @assert length(outgoing) == 0\n return sched\nend\n\n\"\"\"\n handle_disturbance!(solver,prob,env,d::DroppedObject,t,env_state=get_env_state(env,t))\n\nReturns a new `SearchEnv` with a modified `OperatingSchedule`. The new schedule\nreplaces the previous delivery task (`OBJECT_AT(o,old_x)` → `COLLECT` → `CARRY`\n→ `DEPOSIT`) with a new `CleanUpBot` delivery task (`OBJECT_AT(o,new_x)` →\n`CUB_COLLECT` → `CUB_CARRY` → `CUB_DEPOSIT`).\nIt is assumed that the time `t` corresponds to a moment when the object referred\nto by `d.id` is being `CARRIED`.\n\"\"\"\nfunction handle_disturbance!(solver,prob,env::SearchEnv,d::DroppedObject,t,\n env_state = get_env_state(env,t),\n )\n # Schedule surgery\n # - remove Delivery Task: OBJECT_AT(o,old_x) -> COLLECT -> CARRY -> DEPOSIT\n # - replace with equivalent CleanUpBot Delivery Task: OBJECT_AT(o,new_x) -> BOT_COLLECT{CleanUpBot} -> CARRY -> DEPOSIT\n sched = get_schedule(env)\n o = ObjectID(d.id)\n vtxs = get_delivery_task_vtxs(sched,o)\n # incoming and outgoing robot nodes -- for single and team robot tasks\n incoming, outgoing, op = isolate_delivery_task_vtxs(sched,o,vtxs)\n # Add GO->GO edges for affected robot(s), as if they were never assigned\n stitch_disjoint_node_sets!(sched,incoming,outgoing,env_state)\n # remove old nodes\n new_sched = remove_vtxs(sched,vtxs)\n # new_sched = remove_vtxs!(sched,vtxs)\n # add new CleanUpBot task nodes\n x = get_location_ids(object_position(env_state,o))\n replace_in_schedule!(new_sched,OBJECT_AT(o,x),o)\n set_t0!(new_sched,o,t)\n add_headless_delivery_task!(\n new_sched,get_problem_spec(env,:CleanUpBot),o,op.id,CleanUpBot;\n t0=t\n )\n process_schedule!(new_sched)\n construct_search_env(\n solver,\n new_sched,\n env,\n initialize_planning_cache(new_sched)\n )\nend\n\n\nfunction apply_disturbance!(env_graph::GridFactoryEnvironment,d::OilSpill)\n remove_edges!(env_graph,d.edges)\n return env_graph\nend\nfunction remove_disturbance!(env_graph::GridFactoryEnvironment,d::OilSpill)\n add_edges!(env_graph,d.edges)\n return env_graph\nend\n\n\"\"\"\n regenerate_path_specs!(solver,env)\n\nRecompute all paths specs (to account for changes in the env_graphs that will\nbe propagated to the ProblemSpec's distance function as well.)\n\"\"\"\nfunction regenerate_path_specs!(solver,env)\n sched = get_schedule(env)\n for v in vertices(sched)\n node = get_node_from_vtx(sched,v)\n prob_spec = get_problem_spec(env,graph_key(node))\n set_path_spec!(sched,v,generate_path_spec(sched,prob_spec,node))\n end\n update_planning_cache!(solver,env)\n return env\nend\n\nfunction add_headless_cleanup_task!(\n sched::OperatingSchedule,\n spec::ProblemSpec,\n d::OilSpill,\n return_vtx::LocationID=LocationID(-1)\n ;\n t0=0,\n )\n\n robot_id = CleanUpBotID(-1)\n action_id = get_unique_action_id()\n add_to_sched!(sched, spec, CLEAN_UP(robot_id, d.vtxs), action_id)\n set_t0!(sched,action_id,t0)\n\n prev_action_id = action_id\n action_id = get_unique_action_id()\n add_to_sched!(sched, spec, CUB_GO(robot_id, d.vtxs[1], return_vtx), action_id)\n set_t0!(sched,action_id,t0)\n add_edge!(sched, prev_action_id, action_id)\n\n return\nend\n\nfunction remove_robot!(env::SearchEnv,id::BotID,t::Int)\n sched = get_schedule(env)\n G = get_graph(sched)\n # schedule\n to_remove = Set{AbstractID}(id)\n v = get_vtx(sched,id)\n for vp in edges(bfs_tree(G,v))\n node_id = get_vtx_id(sched,vp)\n if isa(node_id,ActionID)\n node = get_node_from_id(sched,node_id)\n if isa(node,BOT_GO)\n push!(to_remove,node_id)\n else\n new_node = replace_robot_id(node,-1)\n replace_in_schedule!(sched,get_problem_spec(env),new_node,node_id)\n end\n end\n end\n for node_id in to_remove\n delete_node!(sched,node_id)\n end\n # Verify that the robot is no longer in schedule\n for v in vertices(G)\n node_id = get_vtx_id(sched,v)\n if isa(node_id,ActionID)\n node = get_node_from_id(sched,node_id)\n @assert !(get_id(id) in get_valid_robot_ids(node)) \"Robot id $(string(id)) should be wiped from schedule, but is present in $(string(node))\"\n end\n end\n # Remap other robots' IDs? TODO refactor OperatinSchedule and RoutePlan so that I don't have to remap ids? i.e., have both uids and idxs?\n # - remove BOT_AT node\n # set assignment ids to -1 with replace_robot_id()\n # if in the middle of CARRY, another robot needs to get the object\nend\n", "meta": {"hexsha": "80ec84393f1d9ccc7e7dbd3fe7d9441844c57c8b", "size": 11374, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/disturbances.jl", "max_stars_repo_name": "Multi-Agent-Research-Group/TaskGraphs.jl", "max_stars_repo_head_hexsha": "72f481c7fd8dfdc30f6ffc5bc996ecec23e4b7c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-04-18T10:42:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-26T12:59:55.000Z", "max_issues_repo_path": "src/disturbances.jl", "max_issues_repo_name": "Multi-Agent-Research-Group/TaskGraphs.jl", "max_issues_repo_head_hexsha": "72f481c7fd8dfdc30f6ffc5bc996ecec23e4b7c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-15T19:43:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-16T22:45:52.000Z", "max_forks_repo_path": "src/disturbances.jl", "max_forks_repo_name": "Multi-Agent-Research-Group/TaskGraphs.jl", "max_forks_repo_head_hexsha": "72f481c7fd8dfdc30f6ffc5bc996ecec23e4b7c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-22T15:00:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-22T15:00:59.000Z", "avg_line_length": 32.5902578797, "max_line_length": 152, "alphanum_fraction": 0.7022155794, "num_tokens": 2988, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.290980853917813, "lm_q1q2_score": 0.14662704779500693}}
{"text": "using DistributedFactorGraphs\n\nimport DistributedFactorGraphs: compare\n\n\nmutable struct SASDebug\n beams::Vector{Vector{Float64}}\n azi_smpls::Vector{Float64}\n SASDebug() = new()\nend\n\nmutable struct SASREUSE\n CBFFull::Array{Complex{Float64}}\n CBFLIE::Array{Complex{Float64}}\n BFOutFull::Array{Complex{Float64}}\n BFOutLIE::Array{Complex{Float64}}\n BFOutLIETemp::Array{Complex{Float64}}\n phaseshiftLOO::Array{Complex{Float64}}\n arrayPos::Array{Float64}\n arrayPosLIE::Array{Float64}\n hackazi::Tuple{Vector{Int}, Vector{Float64}} # [idx], [azi]\n oncebackidx::Vector{Int} # [idx]\n\n workvarlist::Vector{Symbol}\n looelement::Int\n elementset::Vector{Int}\n waveformsLIE::Array{Complex{Float64},2}\n waveformsLOOc::Array{Complex{Float64},1}\n\n BFtemp::Array{Complex{Float64}}\n\n LIEtemp::Array{Complex{Float64}}\n temp1::Array{Complex{Float64},1}\n temp2::Array{Complex{Float64},2}\n\n temp::Array{Complex{Float64}}\n sourceXY::Vector{Float64}\n\n dbg::SASDebug\n SASREUSE() = new()\nend\n\n\nmutable struct SASBearing2D <: AbstractRelativeMinimize\n cfgTotal::CBFFilterConfig\n cfgLIE::CBFFilterConfig\n waveformsIn::Array{Complex{Float64}}\n\n # to allow multithreaded behaviour\n threadreuse::Vector{SASREUSE}\n\n rangemodel::Union{Distributions.Rayleigh, Vector{IIF.AliasingScalarSampler}} # , Vector{<:StatsBase.AbstractWeights}\n ranget::Vector{Float64}\n cfg::Dict\n waveformsRaw::Array{Float64,2}\n debugging::Bool\n\n SASBearing2D() = new()\n # SASBearing2D(z1) = new(z1){Float64,2}\nend\n\n# untested manifold use\ngetManifold(::SASBearing2D) = BearingRange_Manifold\n\nfunction getSample(cfo::CalcFactor{<:SASBearing2D}, N::Int=1)\n sas2d = cfo.factor\n # TODO bring the solvefor index tp getSample function\n if isa(sas2d.rangemodel, Distributions.Rayleigh)\n return (reshape(rand(sas2d.rangemodel, N),1,N), )\n else\n # TODO have to use the first waveform, since we do not know who is being solved for\n return (reshape(rand(sas2d.rangemodel[1], N), 1,N), )\n end\nend\n\n\nfunction forwardsas(sas2d::SASBearing2D,\n thread_data::SASREUSE,\n res::AbstractVector{<:Real},\n idx::Int,\n meas,\n L1,\n XX...)\n # dx, dy, azi = 0.0, 0.0, 0.0\n # thread_data = sas2d.threadreuse[Threads.threadid()]\n\n if thread_data.hackazi[1][1] != idx\n for i in 1:length(XX)\n thread_data.arrayPos[i,1:2] = XX[i][1:2]-XX[1][1:2]\n end\n constructCBFFilter2D!(sas2d.cfgTotal, thread_data.arrayPos, thread_data.CBFFull,thread_data.sourceXY, thread_data.BFtemp)\n\n #fill!(thread_data.temp1,0)\n #fill!(thread_data.temp2,0)\n\n CBF2D_DelaySum!(sas2d.cfgTotal, sas2d.waveformsIn, thread_data.BFOutFull,thread_data.temp1,thread_data.temp2,thread_data.CBFFull)\n\n thread_data.hackazi[1][1] = idx\n\n azi_weights = (repeat(norm.(thread_data.BFOutFull), 1,8)')[:]\n azi_domain = collect(LinRange(0,2pi-1e-10,length(azi_weights)))\n bss = AliasingScalarSampler(azi_domain, azi_weights, SNRfloor=sas2d.cfg[\"azi_snr_floor\"])\n\n thread_data.hackazi[2][1] = wrapRad(rand(bss)[1])\n\n if sas2d.debugging\n push!(thread_data.dbg.beams, deepcopy(thread_data.BFOutFull))\n push!(thread_data.dbg.azi_smpls, thread_data.hackazi[2][1])\n end\n end\n\n dx, dy = L1[1]-XX[1][1] , L1[2]-XX[1][2]\n res[1] = (thread_data.hackazi[2][1] - atan(dy, dx))^2 +\n (meas[1] - norm([dx; dy]))^2\n nothing\nend\n\nfunction (cfo::CalcFactor{<:SASBearing2D})( meas,\n L1,\n XX... )\n #\n sas2d = cfo.factor\n userdata = cfo.metadata\n idx = cfo._sampleIdx\n #\n dx, dy, azi = 0.0, 0.0, 0.0\n thread_data = sas2d.threadreuse[Threads.threadid()]\n res = [0.0;]\n\n if string(userdata.solvefor)[1] == 'l'\n # Solving all poses to Landmark\n # Reference the filter positions locally (first element)\n\n # looks like res is ignored later, but used in this function??\n forwardsas(sas2d, thread_data, res, idx,meas,L1,XX...)\n\n else\n\n if thread_data.oncebackidx[1] != idx\n # ccall(:jl_, Void, (Any,), \"idx=$(idx)\\n\")\n thread_data.oncebackidx[1] = idx\n #run for eacn new idx\n thread_data.workvarlist = userdata.variablelist[2:end] # skip landmark element\n thread_data.looelement = findfirst(thread_data.workvarlist .== userdata.solvefor)\n thread_data.elementset = setdiff(Int[1:length(thread_data.workvarlist);], [thread_data.looelement;])\n\n # Reference first or second element\n for i in 1:length(XX)\n if thread_data.looelement==1\n thread_data.arrayPos[i,1:2] = XX[i][1:2]-XX[2][1:2]\n dx, dy = L1[1]-XX[2][1] , L1[2]-XX[2][2]\n else\n thread_data.arrayPos[i,1:2] = XX[i][1:2]-XX[1][1:2]\n dx, dy = L1[1]-XX[1][1] , L1[2]-XX[1][2]\n end\n end\n\n for i in 1:sas2d.cfgLIE.dataLen\n for j in 1:length(thread_data.elementset)\n thread_data.waveformsLIE[i,j] = sas2d.waveformsIn[i,thread_data.elementset[j]]\n end\n thread_data.waveformsLOOc[i] = sas2d.waveformsIn[i,thread_data.looelement]\n end\n\n\n\n end #end of idx\n\n # Reference first or second element\n for i in 1:length(XX)\n if thread_data.looelement==1\n thread_data.arrayPos[i,1:2] = XX[i][1:2]-XX[2][1:2]\n dx, dy = L1[1]-XX[2][1] , L1[2]-XX[2][2]\n else\n thread_data.arrayPos[i,1:2] = XX[i][1:2]-XX[1][1:2]\n dx, dy = L1[1]-XX[1][1] , L1[2]-XX[1][2]\n end\n end\n\n for i in 1:length(thread_data.elementset), j in 1:2\n elem = thread_data.elementset[i]\n thread_data.arrayPosLIE[i,j] = thread_data.arrayPos[elem,j]\n end\n azi = atan(dy,dx)\n sas2d.cfgLIE.azimuths = [azi;]\n\n\n constructCBFFilter2D!(sas2d.cfgLIE, thread_data.arrayPosLIE, thread_data.CBFLIE,thread_data.sourceXY,thread_data.LIEtemp)\n\n liebf!(thread_data.BFOutLIE, thread_data.waveformsLIE, thread_data.CBFLIE, 1, thread_data.temp, normalize=true)\n\n copy!(thread_data.phaseshiftLOO,thread_data.waveformsLOOc)\n phaseShiftSingle!(thread_data.sourceXY, sas2d.cfgLIE, azi, thread_data.arrayPos[thread_data.looelement,1:2], thread_data.phaseshiftLOO)\n\n res[1] = 0.0\n copy!(thread_data.BFOutLIETemp,thread_data.BFOutLIE)\n @fastmath @inbounds @simd for i in 1:length(thread_data.phaseshiftLOO)\n thread_data.BFOutLIETemp[i] += thread_data.phaseshiftLOO[i]\n res[1] -= norm(thread_data.BFOutLIETemp[i])\n end\n end\n res[1]\nend\n\nfunction reset!(dbg::SASDebug)\n dbg.beams = [Float64[];]\n dbg.azi_smpls = Float64[]\n nothing\nend\n\nfunction DFG.compare(a::SASDebug,b::SASDebug)\n TP = true\n TP = TP && a.beams == b.beams\n TP = TP && a.azi_smpls == b.azi_smpls\n return TP\nend\n\n\nmutable struct PackedSASBearing2D <: DFG.AbstractPackedFactor\n rangemodel::String\n totalPhones::Int\n wavedataRawV::Vector{Float64}\n wavedataRawV_dim::Int\n cfgJson::String\n cfgTotal::String\n cfgLIE::String\n waveformsInReal::Vector{Float64}\n waveformsInIm::Vector{Float64}\n PackedSASBearing2D() = new()\n PackedSASBearing2D(rangemodel::String, tp::Int, wavedataRawV::Vector{Float64}, wavedataRawV_dim::Int, cfgJson::String, cfgTotal::String, cfgLIE::String, waveformsInReal::Vector{Float64}, waveformsInIm::Vector{Float64}) = new(rangemodel, tp, wavedataRawV, wavedataRawV_dim, cfgJson, cfgTotal, cfgLIE, waveformsInReal, waveformsInIm)\n PackedSASBearing2D(rangemodel::String, tp::Int, wd::Array{Float64,2}, cf::Dict, cfgTotal::String, cfgLIE::String, waveformsInReal::Vector{Float64}, waveformsInIm::Vector{Float64}) = new(rangemodel, tp, wd[:], size(wd,1), JSON2.write(cf), cfgTotal, cfgLIE, waveformsInReal, waveformsInIm)\nend\n\n# Note: Need this otherwise it uses a default converter and causes type conversion issues.\n# Safest to just do it here to guarantee it's done.\nimport Base.convert\n\nfunction convert(::Type{<:PackedSASBearing2D}, d::SASBearing2D)\n # range model is vector, packing it cleanly\n rangeString = \"\"\n if typeof(d.rangemodel) == Vector{AliasingScalarSampler}\n rangeString = JSON.json(map(rm -> string(rm), d.rangemodel))\n else\n error(\"Can't pack range model of type $(typeof(d.rangemodel)) yet.\")\n end\n\n cfgTotalJson = JSON2.write(d.cfgTotal)\n cfgLIEJson = JSON2.write(d.cfgLIE)\n waveformsInReal = map(r -> real(r), d.waveformsIn[:])\n waveformsInIm = map(r -> imag(r), d.waveformsIn[:])\n totalPhones = size(d.waveformsRaw,2)\n pPacked = PackedSASBearing2D(rangeString, totalPhones, d.waveformsRaw, d.cfg, cfgTotalJson, cfgLIEJson, waveformsInReal, waveformsInIm)\n return pPacked\nend\n\nfunction convert(::Type{SASBearing2D}, d::PackedSASBearing2D)::SASBearing2D\n rangePacked = JSON2.read(d.rangemodel)\n rangeModel = map(r -> extractdistribution(r), rangePacked)\n cfgJson = JSON2.read(d.cfgJson, Dict)\n cfgTotal = JSON2.read(d.cfgTotal, CBFFilterConfig)\n cfgLIE = JSON2.read(d.cfgLIE, CBFFilterConfig)\n waveformsIn = map(i -> Complex{Float64}(d.waveformsInReal[i], d.waveformsInIm[i]), 1:(length(d.waveformsInReal)))\n waveformsIn = reshape(waveformsIn, Int(length(waveformsIn)/d.totalPhones), :)\n\n sas2d = SASBearing2D()\n sas2d.rangemodel = rangeModel\n sas2d.cfg = cfgJson\n sas2d.cfgTotal = cfgTotal\n sas2d.cfgLIE = cfgLIE\n sas2d.waveformsIn = waveformsIn\n sas2d.debugging = false\n sas2d.waveformsRaw = reshape(d.wavedataRawV, d.wavedataRawV_dim, :)\n prepareSASMemory(sas2d)\n\n return sas2d\nend\n\n\nfunction DFG.compare(a::SASBearing2D, b::SASBearing2D)\n TP = true\n TP &= compare(a.cfgTotal, b.cfgTotal) # CBFFilterConfig\n @debug \"cfgTotal: $(compare(a.cfgTotal, b.cfgTotal))\"\n TP &= compare(a.cfgLIE, b.cfgLIE) # CBFFilterConfig\n @debug \"cfgLIE: $(compare(a.cfgLIE, b.cfgLIE))\"\n TP &= a.waveformsIn == b.waveformsIn # Array{Complex{Float64}}\n @debug \"waveformsIn: $(a.waveformsIn == b.waveformsIn)\"\n\n # Rangemodel\n # Utility dist formula\n calcArrayDist = (a,b, percAcceptable=1) -> begin\n sum(a) == 0 && sum(b) == 0 && return false\n sum(a) == 0 && return false\n sum(abs.(a-b))/sum(abs.(a)) * 100.0 < percAcceptable && return true\n return false\n end\n TP &= typeof(a.rangemodel) == typeof(b.rangemodel)\n @debug \"typeof(rangemodel): $((typeof(a.rangemodel) == typeof(b.rangemodel)))\"\n if typeof(a.rangemodel) == typeof(b.rangemodel) == Array{AliasingScalarSampler,1}\n TP &= length(a.rangemodel) == length(b.rangemodel)\n @debug \"rangemodel (length): $(length(a.rangemodel) == length(b.rangemodel))\"\n\n if length(a.rangemodel) == length(b.rangemodel)\n for i in 1:length(a.rangemodel)\n # Domain\n TP &= calcArrayDist(a.rangemodel[i].domain, b.rangemodel[i].domain)\n @debug \"rangemodel (model[$i].domain): $(calcArrayDist(a.rangemodel[i].domain, b.rangemodel[i].domain))\"\n # Weights\n TP &= calcArrayDist(a.rangemodel[i].weights, b.rangemodel[i].weights)\n @debug \"rangemodel (model[$i].weights): $(calcArrayDist(a.rangemodel[i].weights, b.rangemodel[i].weights))\"\n end\n end\n elseif typeof(a.rangemodel) == typeof(b.rangemodel) == Rayleigh\n TP &= a.rangemodel == b.rangemodel\n @debug \"rangemodel (Raleigh): $(a.rangemodel == b.rangemodel)\"\n end\n\n TP &= a.cfg == b.cfg # Dict\n @debug \"cfg: $(a.cfg == b.cfg)\"\n TP &= a.waveformsRaw == b.waveformsRaw # Array{Float64,2}\n @debug \"waveformsRaw: $(a.waveformsRaw == b.waveformsRaw)\"\n TP &= a.debugging == b.debugging # SASDebug\n @debug \"debugging: $(a.debugging == b.debugging)\"\n return TP\nend\n", "meta": {"hexsha": "0d0350cce5470cee16f0f73e62149fdd83cccc18", "size": 11591, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/beamforming/SASBearing2D.jl", "max_stars_repo_name": "nkhedekar/Caesar.jl", "max_stars_repo_head_hexsha": "647ab1a9a068e9eb9ff2de36e12e86b7b77878bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 122, "max_stars_repo_stars_event_min_datetime": "2018-07-02T19:05:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T14:18:07.000Z", "max_issues_repo_path": "src/beamforming/SASBearing2D.jl", "max_issues_repo_name": "nkhedekar/Caesar.jl", "max_issues_repo_head_hexsha": "647ab1a9a068e9eb9ff2de36e12e86b7b77878bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 245, "max_issues_repo_issues_event_min_datetime": "2018-06-01T15:04:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T05:53:32.000Z", "max_forks_repo_path": "src/beamforming/SASBearing2D.jl", "max_forks_repo_name": "nkhedekar/Caesar.jl", "max_forks_repo_head_hexsha": "647ab1a9a068e9eb9ff2de36e12e86b7b77878bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2018-06-01T13:22:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T12:00:59.000Z", "avg_line_length": 35.6646153846, "max_line_length": 335, "alphanum_fraction": 0.6719006125, "num_tokens": 3783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.2877678157610531, "lm_q1q2_score": 0.146131911001175}}
{"text": "using Parameters\nimport Base: length\n\nusing SparseArrays\n\nabstract type AbstractPhase end\nexport AbstractPhase\n\nabstract type IdealPhase <: AbstractPhase end\nexport IdealPhase\n\nstruct EmptyPhase <: AbstractPhase end\nexport EmptyPhase\n\ninclude(\"Calculators/Ratevec.jl\")\ninclude(\"Calculators/Thermovec.jl\")\ninclude(\"Reaction.jl\")\n\n@with_kw struct IdealGas{W<:Tuple,W2,W3} <: IdealPhase\n name::String = \"\"\n species::Array{Species,1}\n reactions::Array{ElementaryReaction,1}\n spcdict::Dict{String,Int64}\n stoichmatrix::W2\n Nrp::Array{Float64,1}\n rxnarray::Array{Int64,2}\n veckinetics::W\n veckineticsinds::Array{Int64,1}\n vecthermo::NASAvec\n otherreactions::Array{ElementaryReaction,1}\n electronchange::W3\n reversibility::Array{Bool,1}\n diffusionlimited::Bool = false\nend\n\nfunction IdealGas(species,reactions; name=\"\",diffusionlimited=false)\n vectuple,vecinds,otherrxns,otherrxninds,posinds = getveckinetics(reactions)\n rxns = vcat(reactions[vecinds],reactions[otherrxninds])\n rxns = [ElementaryReaction(index=i,reactants=rxn.reactants,reactantinds=rxn.reactantinds,products=rxn.products,\n productinds=rxn.productinds,kinetics=rxn.kinetics,radicalchange=rxn.radicalchange,reversible=rxn.reversible,pairs=rxn.pairs) for (i,rxn) in enumerate(rxns)]\n therm = getvecthermo(species)\n rxnarray = getreactionindices(species,rxns)\n M,Nrp = getstoichmatrix(rxnarray,species)\n echangevec = getfield.(rxns,:electronchange)\n if all(echangevec .== 0)\n electronchange = nothing\n else \n electronchange = convert(echangevec,Array{Float64,1})\n end\n reversibility = getfield.(rxns,:reversible)\n return IdealGas(species=species,reactions=rxns,name=name,\n spcdict=Dict([sp.name=>i for (i,sp) in enumerate(species)]),stoichmatrix=M,Nrp=Nrp,rxnarray=rxnarray,veckinetics=vectuple, \n veckineticsinds=posinds, vecthermo=therm, otherreactions=otherrxns, electronchange=electronchange, \n reversibility=reversibility,diffusionlimited=diffusionlimited,)\nend\nexport IdealGas\n\n@with_kw struct IdealDiluteSolution{W<:Tuple,W2,W3} <: IdealPhase\n name::String = \"\"\n species::Array{Species,1}\n reactions::Array{ElementaryReaction,1}\n solvent::Solvent\n stoichmatrix::W2\n Nrp::Array{Float64,1}\n rxnarray::Array{Int64,2}\n veckinetics::W\n veckineticsinds::Array{Int64,1}\n vecthermo::NASAvec\n otherreactions::Array{ElementaryReaction,1}\n electronchange::W3\n spcdict::Dict{String,Int64}\n reversibility::Array{Bool,1}\n diffusionlimited::Bool = true\nend\n\nfunction IdealDiluteSolution(species,reactions,solvent; name=\"\",diffusionlimited=true)\n vectuple,vecinds,otherrxns,otherrxninds,posinds = getveckinetics(reactions)\n rxns = vcat(reactions[vecinds],reactions[otherrxninds])\n rxns = [ElementaryReaction(index=i,reactants=rxn.reactants,reactantinds=rxn.reactantinds,products=rxn.products,\n productinds=rxn.productinds,kinetics=rxn.kinetics,radicalchange=rxn.radicalchange,reversible=rxn.reversible,pairs=rxn.pairs) for (i,rxn) in enumerate(rxns)]\n therm = getvecthermo(species)\n rxnarray = getreactionindices(species,rxns)\n M,Nrp = getstoichmatrix(rxnarray,species)\n echangevec = getfield.(rxns,:electronchange)\n if all(echangevec .== 0)\n electronchange = nothing\n else \n electronchange = convert(echangevec,Array{Float64,1})\n end\n reversibility = getfield.(rxns,:reversible)\n\n return IdealDiluteSolution(species=species,reactions=rxns,solvent=solvent,name=name,\n spcdict=Dict([sp.name=>i for (i,sp) in enumerate(species)]),stoichmatrix=M,Nrp=Nrp,rxnarray=rxnarray,veckinetics=vectuple,\n veckineticsinds=posinds,vecthermo=therm,otherreactions=otherrxns,electronchange=electronchange,\n reversibility=reversibility,diffusionlimited=diffusionlimited)\nend\nexport IdealDiluteSolution\n\n@with_kw struct IdealSurface{W<:Tuple,W2,W3,W4,W5} <: IdealPhase\n name::String = \"\"\n species::Array{Species,1}\n reactions::Array{ElementaryReaction,1}\n stoichmatrix::W2\n Nrp::W5\n rxnarray::Array{Int64,2}\n veckinetics::W\n veckineticsinds::Array{Int64,1}\n vecthermo::W4\n otherreactions::Array{ElementaryReaction,1}\n electronchange::W3\n spcdict::Dict{String,Int64}\n reversibility::Array{Bool,1}\n sitedensity::Float64\n diffusionlimited::Bool = false\nend\nfunction IdealSurface(species,reactions,sitedensity;name=\"\",diffusionlimited=false)\n @assert diffusionlimited==false \"diffusionlimited=true not supported for IdealSurface\"\n vectuple,vecinds,otherrxns,otherrxninds,posinds = getveckinetics(reactions)\n rxns = vcat(reactions[vecinds],reactions[otherrxninds])\n rxns = [ElementaryReaction(index=i,reactants=rxn.reactants,reactantinds=rxn.reactantinds,products=rxn.products,\n productinds=rxn.productinds,kinetics=rxn.kinetics,radicalchange=rxn.radicalchange,electronchange=rxn.electronchange,reversible=rxn.reversible,pairs=rxn.pairs) for (i,rxn) in enumerate(rxns)]\n therm = getvecthermo(species)\n rxnarray = getreactionindices(species,rxns)\n M,Nrp = getstoichmatrix(rxnarray,species)\n echangevec = getfield.(rxns,:electronchange).*F\n if all(echangevec .== 0)\n electronchange = nothing\n else \n electronchange = convert(typeof(Nrp),echangevec)\n end\n reversibility = getfield.(rxns,:reversible)\n return IdealSurface(species=species,reactions=rxns,name=name,\n spcdict=Dict([sp.name=>i for (i,sp) in enumerate(species)]),stoichmatrix=M,Nrp=Nrp,rxnarray=rxnarray,veckinetics=vectuple,\n veckineticsinds=posinds,vecthermo=therm,otherreactions=otherrxns,electronchange=electronchange,\n reversibility=reversibility,sitedensity=sitedensity,diffusionlimited=diffusionlimited)\nend\nexport IdealSurface\n\n\"\"\"\nconstruct the stochiometric matrix for the reactions and the reaction molecule # change\n\"\"\"\nfunction getstoichmatrix(rxnarray,spcs)\n M = spzeros(size(rxnarray)[2],length(spcs))\n Nrp = zeros(size(rxnarray)[2])\n for i in 1:size(rxnarray)[2]\n n = 0.0\n for (j,ind) in enumerate(rxnarray[:,i])\n if ind == 0\n continue\n elseif j > 3\n M[i,ind] -= 1.0\n n += 1.0\n else\n M[i,ind] += 1.0\n n -= 1.0\n end\n end\n Nrp[i] = n\n end\n return M,Nrp\nend\n\n\"\"\"\nSplit the reactions into groups with the same kinetics\n\"\"\"\nfunction splitreactionsbykinetics(rxns)\n tps = []\n rxnlists = []\n for (i,rxn) in enumerate(rxns)\n typ = getkineticstype(rxn.kinetics)\n tind = findfirst(x->x==typ,tps)\n if tind == nothing\n push!(rxnlists,[])\n push!(tps,typ)\n push!(rxnlists[end],rxn)\n else\n push!(rxnlists[tind],rxn)\n end\n end\n return (tps,rxnlists)\nend\nexport splitreactionsbykinetics\n\n\"\"\"\ncreate vectorized kinetics calculators for the reactions\n\"\"\"\nfunction getveckinetics(rxns)\n tps,rxnlists = splitreactionsbykinetics(rxns)\n posinds = Array{Int64,1}()\n fs = []\n otherrxns = Array{ElementaryReaction,1}()\n vecinds = Array{Int64,1}()\n otherrxninds = Array{Int64,1}()\n for (i,tp) in enumerate(tps)\n if typeof(tp)<:Tuple\n typ = split(tp[1],\".\")[end] #this split needs done because in pyrms the type names come as ReactionMechanismSimulator.Arrhenius instead of Arrhenius in RMS proper\n else\n typ = split(tp,\".\")[end]\n end\n rinds = [findfirst(isequal(rxn),rxns) for rxn in rxnlists[i]]\n fcn = Symbol(typ * \"vec\")\n if !(fcn in allowedfcnlist) || occursin(\"Troe\",typ) #no vectorized kinetics or for the moment stuff with efficiencies\n append!(otherrxns,rxnlists[i])\n append!(otherrxninds,rinds)\n else\n append!(vecinds,rinds)\n fcn = eval(fcn)\n x = fcn([x.kinetics for x in rxnlists[i]])\n push!(fs,x)\n if posinds == Array{Int64,1}()\n push!(posinds,length(rinds))\n else \n push!(posinds,length(rinds)+posinds[end])\n end\n end\n end\n vectuple = tuple(fs...)\n return (vectuple,vecinds,otherrxns,otherrxninds,posinds)\nend\nexport getveckinetics\n\n\"\"\"\ncreate vectorized thermo calculator for species\n\"\"\"\nfunction getvecthermo(spcs)\n thermo = [sp.thermo for sp in spcs]\n if isa(thermo[1],NASA)\n typeassert.(thermo,NASA)\n return NASAvec([sp.thermo for sp in spcs])\n elseif isa(thermo[1],ConstantG)\n typeassert.(thermo,ConstantG)\n return ConstantGvec([th.G for th in thermo],thermo[1].T)\n else\n t = typeof(thermo[1])\n error(\"Thermo type $t unsupported!\")\n end\nend\nexport getvecthermo\n\nfunction getC0(ph::X,T) where {X<:Union{IdealDiluteSolution,IdealGas}}\n return 1.0e5/(R*T)\nend\n\nfunction getC0(ph::X,T) where {X<:IdealSurface}\n return ph.sitedensity\nend\n\nexport getC0\n\nlength(p::T) where {T<:AbstractPhase} = 1\nexport length\n\niterate(p::T) where {T<:AbstractPhase} = p\nexport iterate\n\nBroadcast.broadcastable(p::T) where {T<:AbstractPhase} = Ref(p)\nexport broadcastable\n\nfunction getreactionindices(spcs,rxns) where {Q<:AbstractPhase}\n arr = zeros(Int64,(6,length(rxns)))\n names = [spc.name for spc in spcs]\n for (i,rxn) in enumerate(rxns)\n inds = [findfirst(isequal(spc),spcs) for spc in rxn.reactants]\n for (j,spc) in enumerate(rxn.reactants)\n ind = findfirst(isequal(spc),spcs)\n arr[j,i] = ind\n rxn.reactantinds[j] = ind\n end\n for (j,spc) in enumerate(rxn.products)\n ind = findfirst(isequal(spc),spcs)\n arr[j+3,i] = ind\n rxn.productinds[j] = ind\n end\n if hasproperty(rxn.kinetics,:efficiencies) && length(rxn.kinetics.nameefficiencies) > 0\n while length(rxn.kinetics.efficiencies) > 0\n pop!(rxn.kinetics.efficiencies)\n end\n for (key,val) in rxn.kinetics.nameefficiencies\n ind = findfirst(isequal(key),names)\n rxn.kinetics.efficiencies[ind] = val\n end\n end\n end\n return arr\nend\nexport getreactionindices\n", "meta": {"hexsha": "510fb98c39fa7f1593a278fa9e9fe2005c3ae5c2", "size": 10216, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Phase.jl", "max_stars_repo_name": "MechGen3SO/ReactionMechanismSimulator.jl", "max_stars_repo_head_hexsha": "09ef14046b786dea6b53a0517016b9b154386d3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 35, "max_stars_repo_stars_event_min_datetime": "2020-05-19T17:27:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T10:22:07.000Z", "max_issues_repo_path": "src/Phase.jl", "max_issues_repo_name": "MechGen3SO/ReactionMechanismSimulator.jl", "max_issues_repo_head_hexsha": "09ef14046b786dea6b53a0517016b9b154386d3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 108, "max_issues_repo_issues_event_min_datetime": "2019-09-05T17:24:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T18:29:41.000Z", "max_forks_repo_path": "src/Phase.jl", "max_forks_repo_name": "MechGen3SO/ReactionMechanismSimulator.jl", "max_forks_repo_head_hexsha": "09ef14046b786dea6b53a0517016b9b154386d3d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 22, "max_forks_repo_forks_event_min_datetime": "2019-06-23T21:00:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T04:19:51.000Z", "avg_line_length": 35.5958188153, "max_line_length": 198, "alphanum_fraction": 0.6854933438, "num_tokens": 3029, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.2509127812837603, "lm_q1q2_score": 0.14490096825725285}}
{"text": "## Exercise 6-1\n## Write a compare function takes two values, x and y, and returns 1 if x > y, 0 if x == y, and -1 if x < y.\nprintln(\"Ans: \")\n\nfunction compare(x, y)\n if x > y\n return 1\n elseif x < y\n return -1\n else\n return 0\n end \nend\n\nprintln(compare(4, 6))\nprintln(compare(90, 56))\n\nprintln(\"End.\")\n", "meta": {"hexsha": "f52eb426ada9f9f02402e8fc79cec7d0ebcbb51d", "size": 336, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chapter6/ex1.jl", "max_stars_repo_name": "yashppawar/ThinkJuliaExercises.jl", "max_stars_repo_head_hexsha": "72145b969dc51ebcac413a10004175ebc63cd5c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-13T14:11:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T14:11:30.000Z", "max_issues_repo_path": "Chapter6/ex1.jl", "max_issues_repo_name": "yashppawar/ThinkJuliaExercises.jl", "max_issues_repo_head_hexsha": "72145b969dc51ebcac413a10004175ebc63cd5c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter6/ex1.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": 17.6842105263, "max_line_length": 108, "alphanum_fraction": 0.5714285714, "num_tokens": 110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.5, "lm_q2_score": 0.28776780965284365, "lm_q1q2_score": 0.14388390482642183}}
{"text": "\n\"\"\"\n`module JAC.ElectronCapture` \n ... a submodel of JAC that contains all methods for computing electron-capture properties between some initial and final-state \n multiplets.\n\"\"\"\nmodule ElectronCapture\n\n using Printf, ..AngularMomentum, ..Basics, ..Continuum, ..Defaults, ..InteractionStrength, ..ManyElectron, ..Nuclear, \n ..Radial, ..TableStrings\n \n \"\"\"\n `struct ElectronCapture.Settings` ... defines a type for the details and parameters of computing electron-capture lines.\n\n + printBefore ::Bool ... True, if all energies and lines are printed before their evaluation.\n + lineSelection ::LineSelection ... Specifies the selected levels, if any.\n + minCaptureEnergy ::Float64 ... Minimum energy of free (Auger) electrons to be captured.\n + maxCaptureEnergy ::Float64 ... Maximum energy of free (Auger) electrons to be captured.\n + maxKappa ::Int64 ... Maximum kappa value of partial waves to be included.\n + operator ::AbstractEeInteraction ... Auger/capture operator that is to be used for evaluating the capture amplitudes: \n allowed values are: CoulombInteraction(), BreitInteraction(), ...\n \"\"\"\n struct Settings\n printBefore ::Bool \n lineSelection ::LineSelection \n minCaptureEnergy ::Float64\n maxCaptureEnergy ::Float64\n maxKappa ::Int64\n operator ::AbstractEeInteraction \n end \n\n\n \"\"\"\n `ElectronCapture.Settings()` ... constructor for the default values of ElectronCapture line computations\n \"\"\"\n function Settings()\n Settings(false, LineSelection(), 0., 1.0e5, 2, CoulombInteraction())\n end\n\n\n \"\"\"\n `ElectronCapture.Settings(set::ElectronCapture.Settings;`\n \n printBefore=.., minCaptureEnergy=.., maxCaptureEnergy=.., maxKappa=.., operator=..)\n \n ... constructor for modifying the given ElectronCapture.Settings by 'overwriting' the previously selected parameters.\n \"\"\"\n function Settings(set::ElectronCapture.Settings; \n printBefore::Union{Nothing,Bool}=nothing, lineSelection::Union{Nothing,LineSelection}=nothing, \n minCaptureEnergy::Union{Nothing,Float64}=nothing, maxCaptureEnergy::Union{Nothing,Float64}=nothing,\n maxKappa::Union{Nothing,Int64}=nothing, operator::Union{Nothing,String}=nothing) \n \n if printBefore == nothing printBeforex = set.printBefore else printBeforex = printBefore end \n if lineSelection == nothing lineSelectionx = set.lineSelection else lineSelectionx = lineSelection end \n if minCaptureEnergy == nothing minCaptureEnergyx = set.minCaptureEnergy else minCaptureEnergyx = minCaptureEnergy end \n if maxCaptureEnergy == nothing maxCaptureEnergyx = set.maxCaptureEnergy else maxCaptureEnergyx = maxCaptureEnergy end \n if maxKappa == nothing maxKappax = set.maxKappa else maxKappax = maxKappa end \n if operator == nothing operatorx = set.operator else operatorx = operator end \n\n Settings( printBeforex, lineSelectionx, minCaptureEnergyx, maxCaptureEnergyx, maxKappax, operatorx)\n end\n\n\n # `Base.show(io::IO, settings::ElectronCapture.Settings)` ... prepares a proper printout of the variable settings::ElectronCapture.Settings.\n function Base.show(io::IO, settings::ElectronCapture.Settings) \n println(io, \"printBefore: $(settings.printBefore) \")\n println(io, \"lineSelection: $(settings.lineSelection) \")\n println(io, \"minCaptureEnergy: $(settings.minCaptureEnergy) \")\n println(io, \"maxCaptureEnergy: $(settings.maxCaptureEnergy) \")\n println(io, \"maxKappa: $(settings.maxKappa) \")\n println(io, \"operator: $(settings.operator) \")\n end\n\n\n \"\"\"\n `struct Channel` \n ... defines a type for a ElectronCapture channel to help characterize a scattering (continuum) state of many \n electron-states with a single free electron.\n\n + kappa ::Int64 ... partial-wave of the free electron\n + symmetry ::LevelSymmetry ... total angular momentum and parity of the scattering state\n + phase ::Float64 ... phase of the partial wave\n + amplitude ::Complex{Float64} ... electron-capture amplitude associated with the given channel.\n \"\"\"\n struct Channel\n kappa ::Int64\n symmetry ::LevelSymmetry\n phase ::Float64\n amplitude ::Complex{Float64}\n end\n\n\n \"\"\"\n `struct Line` \n ... defines a type for a ElectronCapture line that may include the definition of sublines and their \n corresponding amplitudes.\n\n + initialLevel ::Level ... initial-(state) level\n + finalLevel ::Level ... final-(state) level\n + electronEnergy ::Float64 ... Energy of the (incoming free) electron.\n + totalRate ::Float64 ... Total rate of this line.\n + hasChannels ::Bool \n ... Determines whether the individual scattering (sub-) channels are defined in terms of their free-electron energy, kappa \n and the total angular momentum/parity as well as the amplitude, or not.\n + channels ::Array{ElectronCapture.Channel,1} ... List of ElectronCapture channels of this line.\n \"\"\"\n struct Line\n initialLevel ::Level\n finalLevel ::Level\n electronEnergy ::Float64\n totalRate ::Float64\n hasChannels ::Bool\n channels ::Array{ElectronCapture.Channel,1}\n end \n\n\n \"\"\"\n `ElectronCapture.Line(initialLevel::Level, finalLevel::Level, totalRate::Float64)` \n ... constructor for an ElectronCapture line between a specified initial and final level.\n \"\"\"\n function Line(initialLevel::Level, finalLevel::Level, totalRate::Float64)\n Line(initialLevel, finalLevel, 0., totalRate, false, ElectronCapture.Channel[])\n end\n\n\n # `Base.show(io::IO, line::ElectronCapture.Line)` ... prepares a proper printout of the variable line::ElectronCapture.Line.\n function Base.show(io::IO, line::ElectronCapture.Line) \n println(io, \"initialLevel: $(line.initialLevel) \")\n println(io, \"finalLevel: $(line.finalLevel) \")\n println(io, \"electronEnergy: $(line.electronEnergy) \")\n println(io, \"totalRate: $(line.totalRate) \")\n println(io, \"hasChannels: $(line.hasChannels) \")\n println(io, \"channels: $(line.channels) \")\n end\n\n\n \"\"\"\n `ElectronCapture.amplitude(kind::String, channel::ElectronCapture.Channel, finalLevel::Level, continuumLevel::Level,\n grid::Radial.Grid; printout::Bool=true)` \n ... to compute the kind in CoulombInteraction(), BreitInteraction(), CoulombBreit() ElectronCapture amplitude \n <alpha_f J_f || O^(capture, kind) || (alpha_i J_i, kappa) J_f> = <(alpha_i J_i, kappa) J_f || O^(Auger, kind) || alpha_f J_f>^*\n due to the interelectronic interaction for the given final and initial level. A value::ComplexF64 is returned.\n \"\"\"\n function amplitude(kind::String, channel::ElectronCapture.Channel, finalLevel::Level, continuumLevel::Level, grid::Radial.Grid; printout::Bool=true)\n aChannel = AutoIonization.Channel(channel.kappa, channel.symmetry, channel.phase, 0.)\n amplitude = conj(AutoIonization.amplitude(kind, aChannel, continuumLevel::Level, finalLevel::Level, grid; printout=printout))\n \n return( amplitude )\n end\n\n\n \"\"\"\n `ElectronCapture.computeAmplitudesProperties(line::ElectronCapture.Line, nm::Nuclear.Model, grid::Radial.Grid, nrContinuum::Int64, \n settings::ElectronCapture.Settings; printout::Bool=true)` \n ... to compute all amplitudes and properties of the given line; a line::ElectronCapture.Line is returned for which the amplitudes \n and properties are now evaluated.\n \"\"\"\n function computeAmplitudesProperties(line::ElectronCapture.Line, nm::Nuclear.Model, grid::Radial.Grid, nrContinuum::Int64, \n settings::ElectronCapture.Settings; printout::Bool=true) \n newChannels = ElectronCapture.Channel[]; contSettings = Continuum.Settings(false, nrContinuum); rate = 0.\n for channel in line.channels\n newfLevel = Basics.generateLevelWithSymmetryReducedBasis(line.finalLevel, line.finalLevel.basis.subshells)\n newiLevel = Basics.generateLevelWithSymmetryReducedBasis(line.initialLevel, newfLevel.basis.subshells)\n newfLevel = Basics.generateLevelWithExtraSubshell(Subshell(101, channel.kappa), newfLevel)\n cOrbital, phase = Continuum.generateOrbitalForLevel(line.electronEnergy, Subshell(101, channel.kappa), newiLevel, nm, grid, contSettings)\n newcLevel = Basics.generateLevelWithExtraElectron(cOrbital, channel.symmetry, newiLevel)\n newChannel = ElectronCapture.Channel(channel.kappa, channel.symmetry, phase, 0.)\n amplitude = ElectronCapture.amplitude(settings.operator, newChannel, newcLevel, newfLevel, grid, printout=printout)\n rate = rate + conj(amplitude) * amplitude\n push!( newChannels, ElectronCapture.Channel(newChannel.kappa, newChannel.symmetry, newChannel.phase, amplitude) )\n end\n totalRate = 2pi* rate\n newLine = ElectronCapture.Line(line.initialLevel, line.finalLevel, line.electronEnergy, totalRate, true, newChannels)\n \n return( newLine )\n end\n\n\n \"\"\"\n `ElectronCapture.displayRates(stream::IO, lines::Array{ElectronCapture.Line,1}, settings::ElectronCapture.Settings)` \n ... to list all results, energies, rates, etc. of the selected lines. A neat table is printed but nothing is returned \n otherwise.\n \"\"\"\n function displayRates(stream::IO, lines::Array{ElectronCapture.Line,1}, settings::ElectronCapture.Settings)\n nx = 96\n println(stream, \" \")\n println(stream, \" Auger rates: \\n\")\n println(stream, \" \", TableStrings.hLine(nx))\n sa = \" \"; sb = \" \"\n sa = sa * TableStrings.center(18, \"i-level-f\"; na=2); sb = sb * TableStrings.hBlank(20)\n sa = sa * TableStrings.center(18, \"i--J^P--f\"; na=4); sb = sb * TableStrings.hBlank(22)\n sa = sa * TableStrings.center(12, \"Energy\" ; na=2); \n sb = sb * TableStrings.center(12,TableStrings.inUnits(\"energy\"); na=4)\n sa = sa * TableStrings.center(14, \"Electron energy\" ; na=2); \n sb = sb * TableStrings.center(14,TableStrings.inUnits(\"energy\"); na=2)\n sa = sa * TableStrings.center(14, \"Capture rate\"; na=2); \n sb = sb * TableStrings.center(14, TableStrings.inUnits(\"rate\"); na=2)\n println(stream, sa); println(stream, sb); println(stream, \" \", TableStrings.hLine(nx)) \n # \n for line in lines\n sa = \" \"; isym = LevelSymmetry( line.initialLevel.J, line.initialLevel.parity)\n fsym = LevelSymmetry( line.finalLevel.J, line.finalLevel.parity)\n sa = sa * TableStrings.center(18, TableStrings.levels_if(line.initialLevel.index, line.finalLevel.index); na=2)\n sa = sa * TableStrings.center(18, TableStrings.symmetries_if(isym, fsym); na=4)\n sa = sa * @sprintf(\"%.6e\", Defaults.convertUnits(\"energy: from atomic\", line.initialLevel.energy)) * \" \"\n sa = sa * @sprintf(\"%.6e\", Defaults.convertUnits(\"energy: from atomic\", line.electronEnergy)) * \" \"\n sa = sa * @sprintf(\"%.6e\", Defaults.convertUnits(\"rate: from atomic\", line.totalRate)) * \" \"\n println(stream, sa)\n end\n println(stream, \" \", TableStrings.hLine(nx))\n #\n return( nothing )\n end\n\nend # module\n", "meta": {"hexsha": "d02a308c0e2ffe368003b3ebb0afa9551d7e1fb3", "size": 12697, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/module-ElectronCapture.jl", "max_stars_repo_name": "mfherbst/JAC.jl", "max_stars_repo_head_hexsha": "43563c049a995817ada86ce82908714d4e1a034b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 115, "max_stars_repo_stars_event_min_datetime": "2019-03-11T11:24:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T22:33:28.000Z", "max_issues_repo_path": "src/module-ElectronCapture.jl", "max_issues_repo_name": "mfherbst/JAC.jl", "max_issues_repo_head_hexsha": "43563c049a995817ada86ce82908714d4e1a034b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2019-04-02T22:04:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-06T06:21:57.000Z", "max_forks_repo_path": "src/module-ElectronCapture.jl", "max_forks_repo_name": "mfherbst/JAC.jl", "max_forks_repo_head_hexsha": "43563c049a995817ada86ce82908714d4e1a034b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2019-03-20T10:28:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T12:51:19.000Z", "avg_line_length": 58.7824074074, "max_line_length": 152, "alphanum_fraction": 0.6090415059, "num_tokens": 2859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5234203638047914, "lm_q2_score": 0.2720245569956929, "lm_q1q2_score": 0.1423831925865228}}
{"text": "# ------------------------------------------------------------------------------------------\n# # Iterators\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# `for` loops \"lower\" to `while` loops plus calls to the `iterate` function:\n#\n# ```jl\n# for i in iter # or \"for i = iter\" or \"for i ∈ iter\"\n# # body\n# end\n# ```\n#\n# internally works the same as:\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# ```jl\n# next = iterate(iter)\n# while next !== nothing\n# (i, state) = next\n# # body\n# next = iterate(iter, state)\n# end\n# ```\n#\n# The same applies to comprehensions and generators.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# Note `nothing` is a singleton value (the only value of its type `Nothing`) used by\n# convention when there is no value to return (a bit like `void` in C). For example\n# ------------------------------------------------------------------------------------------\n\ntypeof(print(\"hello\"))\n\nA = ['a','b','c'];\n\niterate(A)\n\niterate(A, 2)\n\niterate(A, 3)\n\niterate(A, 4)\n\n# ------------------------------------------------------------------------------------------\n# Iteration is also used by \"destructuring\" assignment:\n# ------------------------------------------------------------------------------------------\n\nx, y = A\n\nx\n\ny\n\n# ------------------------------------------------------------------------------------------\n# Yet another user of this \"iteration protocol\" is so-called argument \"splatting\":\n# ------------------------------------------------------------------------------------------\n\nstring(A)\n\nstring('a','b','c')\n\nstring(A...)\n\n# ------------------------------------------------------------------------------------------\n# ## Iteration utilities\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# `collect` gives you all elements of an iterator as an array.\n# Comprehensions are actually equivalent to calling `collect` on a generator.\n# ------------------------------------------------------------------------------------------\n\ncollect(pairs(A))\n\ncollect(zip(100:102,A))\n\n# ------------------------------------------------------------------------------------------\n# Some other favorites to experiment with. These are in the built-in `Iterators` module:\n# - `enumerate`\n# - `rest`\n# - `take`\n# - `drop`\n# - `product`\n# - `flatten`\n# - `partition`\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# Some iterators are infinite!\n# - `countfrom`\n# - `repeated`\n# - `cycle`\n# ------------------------------------------------------------------------------------------\n\nI = zip(Iterators.cycle(0:1), Iterators.flatten([[2,3],[4,5]]))\n\ncollect(I)\n\ncollect(Iterators.product(I,A))\n\nstring(I...)\n\n# ------------------------------------------------------------------------------------------\n# ## Defining iterators\n# ------------------------------------------------------------------------------------------\n\nstruct SimpleRange\n lo::Int\n hi::Int\nend\n\nBase.iterate(r::SimpleRange, state = r.lo) = state > r.hi ? nothing : (state, state+1)\n\nBase.length(r::SimpleRange) = r.hi-r.lo+1\n\ncollect(SimpleRange(2,8))\n\n# ------------------------------------------------------------------------------------------\n# ## Iterator traits\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# For many algorithms, it's useful to know certain properties of an iterator up front.\n#\n# The most useful is whether an iterator has a fixed, known length.\n# ------------------------------------------------------------------------------------------\n\nBase.IteratorSize([1])\n\nBase.IteratorSize(Iterators.repeated(1))\n\nBase.IteratorSize(eachline(open(\"/dev/null\")))\n\n# ------------------------------------------------------------------------------------------\n# ## Exercise\n#\n# Define an iterator giving the first N fibonacci numbers.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# ## Index iterators\n# ------------------------------------------------------------------------------------------\n\nA = rand(3,5)\n\neachindex(A)\n\nkeys(A)\n\nAv = view(A, [1,3], [1,2,5])\n\nA[[1,3],[1,2,5]]\n\neachindex(Av)\n\n# ------------------------------------------------------------------------------------------\n# ### Example: $3\\times 3\\times \\dots \\times3$ boxcar filter (from a blog post by Tim Holy)\n# ------------------------------------------------------------------------------------------\n\nfunction boxcar3(A::AbstractArray)\n out = similar(A)\n R = CartesianIndices(size(A))\n I1, Iend = first(R), last(R)\n for I in R\n n, s = 0, zero(eltype(out))\n for J in CartesianIndices(map(:, max(I1, I-I1).I, min(Iend, I+I1).I))\n s += A[J]\n n += 1\n end\n out[I] = s/n\n end\n out\nend\n\nusing Images\n\nA = rand(256,256);\n\nGray.(A)\n\nGray.(boxcar3(A))\n\nfunction sumalongdims!(B, A)\n # It's assumed that B has size 1 along any dimension that we're summing\n fill!(B, 0)\n Bmax = CartesianIndex(size(B))\n for I in CartesianIndices(size(A))\n B[min(Bmax,I)] += A[I]\n end\n B\nend\n\nB = zeros(1, 256)\n\nsumalongdims!(B, A)\n\nreduce(+,A,dims=(1,))\n\n# ------------------------------------------------------------------------------------------\n# `CartesianIndices` and other \"N-d\" iterators have a shape that propagates through\n# generators.\n# ------------------------------------------------------------------------------------------\n\n[1 for i in CartesianIndices((2,3))]\n\nB = rand(5,5)\n\nview(B,CartesianIndices((2,3)))\n\n# ------------------------------------------------------------------------------------------\n# ## Exercise: CartesianIndex life!\n#\n# - Write a function `neighborhood(A::Array, I::CartesianIndex)` that returns a view of the\n# 3x3 neighborhood around a location\n# - Write a function `liferule(A, I)` that implements the evolution rule of Conway's life\n# cellular automaton:\n# - 2 live neighbors $\\rightarrow$ stay the same\n# - 3 live neighbors $\\rightarrow$ 1\n# - otherwise $\\rightarrow$ 0\n# - Write a function `life(A)` that maps A to the next life step using these\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# Some famous initial conditions:\n# ------------------------------------------------------------------------------------------\n\nA = fill(0, 128,128);\n\nA[61:63,61:63] = [1 1 0\n 0 1 1\n 0 1 0]\n\nA = life(A)\n# `repeat` can be used to get chunky pixels to make the output easier to see\nGray.(repeat(A,inner=(4,4)))\n\n\n", "meta": {"hexsha": "08b6d4b030ea4fbe78e976e4bbac2ba1ca7693e6", "size": 7467, "ext": "jl", "lang": "Julia", "max_stars_repo_path": ".nbexports/introductory-tutorials/intro-to-julia/long-version/150 Iterators.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/150 Iterators.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/150 Iterators.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": 30.9834024896, "max_line_length": 92, "alphanum_fraction": 0.3368153207, "num_tokens": 1297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207955, "lm_q2_score": 0.2814056014026228, "lm_q1q2_score": 0.13850449833574618}}
{"text": "const combine = 2\n\nconst EnableSlide = [0, # MW_KOMA_FU = 1, // 歩兵\n 1, # MW_KOMA_KY = 2, // 香車\n 0, # MW_KOMA_KE = 3, // 桂馬\n 0, # MW_KOMA_GI = 4, // 銀将\n 0, # MW_KOMA_KI = 5, // 金将\n 1, # MW_KOMA_KA = 6, // 角行\n 1, # MW_KOMA_HI = 7, // 飛車\n 0, # MW_KOMA_OU = 8, // 玉将/王将\n 0, # MW_KOMA_TO = 9, // と\n 0, # MW_KOMA_NY = 10, // 成香\n 0, # MW_KOMA_NK = 11, // 成桂\n 0, # MW_KOMA_NG = 12, // 成銀\n 0, # MW_KOMA_NARI_KIN_IS_ABSENT = 13, // 金は成らない\n combine, # MW_KOMA_UM = 14, // 馬\n combine]::Array{Int,1} # MW_KOMA_RY = 15, // 龍\n\n# 各駒ごとの効きの数\n# スライドする駒の場合はその方向の数\n# UM/RYが4なのは、1つづつ動ける方向が4つの意味\nconst koma_num_of_moves = [1, # MW_KOMA_FU = 1, // 歩兵\n 1, # MW_KOMA_KY = 2, // 香車\n 2, # MW_KOMA_KE = 3, // 桂馬\n 5, # MW_KOMA_GI = 4, // 銀将\n 6, # MW_KOMA_KI = 5, // 金将\n 4, # MW_KOMA_KA = 6, // 角行\n 4, # MW_KOMA_HI = 7, // 飛車\n 8, # MW_KOMA_OU = 8, // 玉将/王将\n 6, # MW_KOMA_TO = 9, // と\n 6, # MW_KOMA_NY = 10, // 成香\n 6, # MW_KOMA_NK = 11, // 成桂\n 6, # MW_KOMA_NG = 12, // 成銀\n 0, # MW_KOMA_NARI_KIN_IS_ABSENT = 13, // 金は成らない\n 4, # MW_KOMA_UM = 14, // 馬(角行のslideの効きを付加する)\n 4]::Array{Int,1} # MW_KOMA_RY = 15, // 龍(飛車のslideの効きを付加する)\n\n\nconst koma_moves_offset = [-11 0 0 0 0 0 0 0 0; # fu\n -11 0 0 0 0 0 0 0 0; # ky\n -23 -21 0 0 0 0 0 0 0; # ke\n -12 -11 -10 10 12 0 0 0 0; # gi\n -12 -11 -10 -1 1 11 0 0 0; # ki\n -12 -10 10 12 0 0 0 0 0; # ka\n -11 -1 1 11 0 0 0 0 0; # hi\n -12 -11 -10 -1 1 10 11 12 0; # ou\n -12 -11 -10 -1 1 11 0 0 0; # to\n -12 -11 -10 -1 1 11 0 0 0; # ny\n -12 -11 -10 -1 1 11 0 0 0; # nk\n -12 -11 -10 -1 1 11 0 0 0; # ng\n 0 0 0 0 0 0 0 0 0; # nari_kin (none)\n -11 -1 1 11 0 0 0 0 0; # um(non slide directions)\n -12 -10 10 12 0 0 0 0 0]::Array{Int,2} # ry(non slide directions)\n\n# mailbox81と一緒に使う。\n# たとえばmailbox81[SQ91]=23で、\n# mailbox[23] = 0となっている。\n# つまりSQ = mailbox[mailbox81[SQ]]\n# この辺Tom Kerrigan Simple Chessという\n# 小さいチェスプログラムからアイデアを貰って\n# 将棋向けに拡張しています。いわゆるmailbox方式\nconst mailbox = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, -1,\n -1, 9, 10, 11, 12, 13, 14, 15, 16, 17, -1,\n -1, 18, 19, 20, 21, 22, 23, 24, 25, 26, -1,\n -1, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1,\n -1, 36, 37, 38, 39, 40, 41, 42, 43, 44, -1,\n -1, 45, 46, 47, 48, 49, 50, 51, 52, 53, -1,\n -1, 54, 55, 56, 57, 58, 59, 60, 61, 62, -1,\n -1, 63, 64, 65, 66, 67, 68, 69, 70, 71, -1,\n -1, 72, 73, 74, 75, 76, 77, 78, 79, 80, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1]::Array{Int,1}\n\n# mailboxの逆関数\nconst mailbox81 = [23, 24, 25, 26, 27, 28, 29, 30, 31,\n 34, 35, 36, 37, 38, 39, 40, 41, 42,\n 45, 46, 47, 48, 49, 50, 51, 52, 53,\n 56, 57, 58, 59, 60, 61, 62, 63, 64,\n 67, 68, 69, 70, 71, 72, 73, 74, 75,\n 78, 79, 80, 81, 82, 83, 84, 85, 86,\n 89, 90, 91, 92, 93, 94, 95, 96, 97,\n 100,101,102,103,104,105,106,107,108,\n 111,112,113,114,115,116,117,118,119]::Array{Int,1}\n\nfunction CanMoveTo( teban::Int, from::Int, to::Int, koma::Int)\n ret::Int = true\n categ::Int = koma & 0x0f;\n\n if (MJFU <= categ <= MJKE)\n else\n return ret\n end\n\n if teban == SENTE\n if (categ == MJFU)&&(to < A8)\n ret = false\n elseif (categ == MJKY)&&(to < A8)\n ret = false\n elseif (categ == MJKE)&&(to < A7)\n ret = false\n end\n elseif teban == GOTE\n if (categ == MJFU)&&(to > I2)\n ret = false\n elseif (categ == MJKY)&&(to > I2)\n ret = false\n elseif (categ == MJKE)&&(to > I3)\n ret = false\n end\n end\n\n ret\nend\n\nconst canpromA = [ 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]::Array{Int,1}\n# FU,KY,KE,GI,KI,KA,HI,OU,TO,NY,NK,NG,nk,UM,RY\n\nfunction CanIPromote( teban::Int, from::Int, to::Int, koma::Int)\n flag::Int = false\n f_y::Int = 0\n t_y::Int = 0\n\n if (koma != MJNONE)&&(teban == (koma>>>4))\n else\n return flag # 相手の駒は成れない\n end\n koma_plain::Int = koma & 0x0f\n\n enableProm = canpromA[koma_plain]\n if enableProm == 1\n koma_plain += MJNARI\n else\n return flag;\n end\n\n f_y = int(floor(from / 9))\n t_y = int(floor(to / 9))\n\n if teban == SENTE\n if (((f_y<=8)&&(f_y>=0))&&((t_y<=2)))\n flag = true\n end\n if (((t_y<=8)&&(t_y>=0))&&((f_y<=2)))\n flag = true\n end\n elseif teban == GOTE\n if ((f_y<=8)&&(t_y>=6))\n flag = true\n end\n if ((t_y<= 8)&&(f_y>=6))\n flag = true\n end\n end\n return flag\nend\n\n#@iprofile begin\nfunction recycleMove(fu_bit_array::Uint,\n\t teban::Int,\n koma::Int,\n\t p::Board,\n\t out::Array{Move,1},\n\t count::Int32,\n\t gs::GameStatus)\n # 基本、盤面情報を元に「打ち」となる可能手を生成すればよい\n # 香車、桂馬の場合は手番ごと禁じ手となる盤面の隅への着手をチェックする\n # 歩の場合は盤面のハジへの着手とともに、2歩のチェックを行う\n komadai::Int = (teban == SENTE) ? MO_MOVE_SENTE: MO_MOVE_GOTE\n from::Int = 0\n to::Int = 0\n i::Int = 0\n j::Int = 0\n value::Int= 0\n enable_move::Uint = 0\n fubi = uint32(fu_bit_array)\n co::Int32 = count\n\n if teban == SENTE\n from = A8 # 二段より手前\n to = NumSQ # 九段まで\n elseif teban == GOTE\n from = A9 # 一段から\n to = I2 # 八段まで\n end\n\n if koma == MJFU # ここに本当は打ち歩詰めの判定処理が入る\n # とりあえず王の前に打てないようにすれば反則は防げるが、貴重な着手を無駄にするかも\n elseif koma == MJKY\n fu_bit_array = 0x1ff;\n elseif koma == MJKE\n fu_bit_array = 0x1ff;\n if teban == SENTE\n from = A7 # 三段より手前\n to = NumSQ # 九段まで\n else\n from = A9 # 一段から\n to = I3 # 七段まで\n end\n else # おそらく制限なし\n fu_bit_array = 0x1ff;\n from = A9\n to = NumSQ # 基本どこでも打てる\n end\n fubit::Uint32 = 0\n komaval::Int = koma|(teban<<4)\n\n for i = from:to\n if koma == MJFU\n j = (i-1) % 9\n #println(\"fubit=\",hex(fu_bit_array), \", sq=\", p.square[i], \", koma=\", koma)\n fubit = uint32(1) << j\n enable_move = fubi & fubit\n #println(\"[\",i,\"][j=\",j,\"]: enable_move = 0x\", hex(enable_move))\n if enable_move == 0\n continue\n end\n if (p.square[i] == MJNONE)&&(enable_move != 0)\n # 可能手生成\n # value = (komadai << 24) | (i << 16) | MW_FLAG_UCHI | teban | (koma&0x0f);\n # value = (komadai << 24) | (i << 16) | koma | teban | MW_FLAG_UCHI;\n # out[count].move = value;\n co += 0x00000001\n out[co] = Move(komaval,komadai,i-1,FLAG_UCHI,0,0)::Move # value = 0 \n end\n else\n if p.square[i] == MJNONE\n # 可能手生成\n # value = (komadai << 24) | (i << 16) | MW_FLAG_UCHI | teban | (koma&0x0f);\n # value = (komadai << 24) | (i << 16) | koma | teban | MW_FLAG_UCHI;\n # out[count].move = value;\n co += 0x00000001\n out[co] = Move(komaval,komadai,i-1,FLAG_UCHI,0,0)::Move # value = 0 \n end\n end\n end\n co\nend\n#end # @iprofile\n\nfunction in_check( s::Int, p::Board)\n i::Int = 0\n\n for i = 0:(NumSQ-1)\n banpos::Int = p.square[i+1]\n pos_koma::Int = banpos & 0x0f\n\tif banpos == MJOU|(s<<4)\n\t return NewAttack( s$1, i, p)\n end\n end\n return true # shouldn't get here\nend\n\nfunction NewAttack(teban::Int, # 効きを調べる駒の種類\n pos::Int, # 効きを調べる升目(0 origin)\n p::Board)\n i::Int = 0\n n::Int = 0\n for x = 0:(NumSQ-1)\n banpos::Int = p.square[x+1] # 動かす駒\n pos_koma::Int = banpos & 0x0f # 動かす駒の種類\n pos_sengo::Int = (banpos & 0x10) >>> 4\n if (pos_koma != MJNONE)&&(pos_sengo == teban)\n bo::Bool = NewAttackSub( teban, pos, x, p)\n if bo\n return true\n end\n end\n end\n false\nend\n\nfunction NewAttackSub(teban::Int,\n\t pos::Int,\n\t from::Int,\n\t p::Board)\n i::Int = 0\n n::Int = 0\n banfrom::Int = p.square[from+1] # 動かす駒\n from_koma::Int = banfrom & 0x0f # 動かす駒の種類\n num_of_moves::Int = koma_num_of_moves[from_koma]# 駒の動かせる方向数\n enable_s::Int = EnableSlide[from_koma] # slide pieceか否か\n teban_flag = (teban == SENTE) ? 1: -1 # 先手なら1、後手ならー1\n nari::Bool = false # 成りフラグ\n canMove::Bool = false # 動かすことが可能なら1\n koma_teban::Int = 0 # 駒(移動先)の手番\n\n while true # UM,RY用のループ\n for i = 1:num_of_moves\n n = from\n while true\n n = mailbox[mailbox81[n+1] + (teban_flag*koma_moves_offset[from_koma,i])+1]\n if n == -1\n break\n else\n\t # make a move\n\t nari = CanIPromote( teban, from, n, banfrom);\n\t canMove = CanMoveTo(teban, from, n, banfrom);\n newkoma = p.square[n+1]\n\t koma_teban = (newkoma & 0x10) >>> 4;\n\t if (newkoma != MJNONE) && (koma_teban == teban)\n # 同じ種類の駒\n if n == pos\n return true\n end\n\t break\n\t elseif (newkoma != MJNONE)&&(koma_teban == (teban$1))\n\t # 駒取り\n\t if nari\n if n == pos\n return true\n end\n end\n if canMove\n if n == pos\n return true\n end\n end\n\t break\n else\n\t if nari\n if n == pos\n return true\n end\n end\n\t if canMove\n if n == pos\n return true\n end\n end\n end\n end\n if enable_s == 1\n else\n break\n end\n end\n end\n if enable_s == combine\n from_koma -= MJNARI # UM -> KA, RY -> HI\n enable_s = 1\n else\n break\n end\n end\n false\nend\n\n# function attack(teban::Int,\n# \t pos::Int,\n# \t p::Board)\n# i::Int = 0\n# n::Int = 0\n\n# nari::Bool = false # 成りフラグ\n# canMove::Bool = false # 動かすことが可能なら1\n# value::Int = 0 # 可能手の値\n# koma_teban::Int = 0 # 駒(移動先)の手番\n\n# plus1pos = pos+1\n\n# for x = 0:(NumSQ-1)\n# banpos::Int = p.square[x+1] # 動かす駒\n# pos_koma::Int = banpos & 0x0f # 動かす駒の種類\n# num_of_moves::Int = (pos_koma == 0)?0:koma_num_of_moves[pos_koma] # 駒の動かせる方向数\n# enable_s::Int = (pos_koma == 0)?0:EnableSlide[pos_koma] # slide pieceか否か\n# teban_flag = (teban == SENTE) ? 1: -1 # 先手なら1、後手ならー1\n# while true # UM,RY用のループ\n# for i = 1:num_of_moves\n# n = x\n# while true\n# n = mailbox[mailbox81[n+1] + (teban_flag*koma_moves_offset[pos_koma,i])+1]\n# \t nari = CanIPromote( teban, x, n, banpos);\n# \t canMove = CanMoveTo(teban, x, n, banpos);\n# if n == -1\n# break\n# else\n# newkoma::Int = p.square[n+1]\n# \t koma_teban = (newkoma & 0x10) >>> 4;\n\n# \t if (newkoma != MJNONE) && (koma_teban == teban)\n# \t break\n# \t elseif (newkoma != MJNONE)&&(koma_teban == ((teban==SENTE)?GOTE:SENTE))\n# # 取り\n# \t if nari\n# if n == pos\n# return true\n# end\n# end\n# if canMove\n# if n == pos\n# return true\n# end\n# end\n# break\n# else\n# # 空白のマスに進む\n# \t if nari\n# if n == pos\n# return true\n# end\n# end\n# if canMove\n# if n == pos\n# return true\n# end\n# end\n# end\n# end\n# if enable_s == 1\n# else\n# break\n# end\n# end\n# end\n# if enable_s == combine\n# pos_koma -= MJNARI # UM -> KA, RY -> HI\n# #println(\"combine,koma=\",pos_koma)\n# enable_s = 1\n# #continue\n# else\n# break\n# end\n# end\n# end\n\n# false\n# end\n\n\n#println(\"AA offset = \", koma_moves_offset[6,2])\nfunction mailbox0x88(teban::Int,\n\t pos::Int,\n\t p::Board,\n\t out::Array{Move,1}, # outは可能手バッファの先頭\n\t count::Int32, # countは既に見つけた可能手の個数\n\t gs::GameStatus)\n i::Int = 0\n n::Int = 0\n banpos::Int = p.square[pos+1] # 動かす駒\n pos_koma::Int = banpos & 0x0f # 動かす駒の種類\n num_of_moves::Int = koma_num_of_moves[pos_koma] # 駒の動かせる方向数\n enable_s::Int = EnableSlide[pos_koma] # slide pieceか否か\n teban_flag = (teban == SENTE) ? 1: -1 # 先手なら1、後手ならー1\n nari::Bool = false # 成りフラグ\n canMove::Bool = false # 動かすことが可能なら1\n value::Int = 0 # 可能手の値\n koma_teban::Int = 0 # 駒(移動先)の手番\n\n while true # UM,RY用のループ\n for i = 1:num_of_moves\n n = pos\n while true\n #println(\"A pos=\",pos,\", n=\",n, \", koma = \", pos_koma, \", i = \", i, \", numofmoves= \", num_of_moves)\n #println(\"A mailbox81 = \", mailbox81[n+1])\n #println(\"A offset = \", koma_moves_offset[pos_koma,i])\n n = mailbox[mailbox81[n+1] + (teban_flag*koma_moves_offset[pos_koma,i])+1]\n #println(\"B pos=\",pos,\", n=\",n)\n if n == -1\n break\n else\n\t # make a move\n\t nari = CanIPromote( teban, pos, n, banpos);\n\t canMove = CanMoveTo(teban, pos, n, banpos);\n\t # value = (pos << 24) | (n << 16);\n newkoma = p.square[n+1]\n\t koma_teban = (newkoma & 0x10) >>> 4;\n\t if (newkoma != MJNONE) && (koma_teban == teban)\n\t break\n\t elseif (newkoma != MJNONE)&&(koma_teban == ((teban==SENTE)?GOTE:SENTE))\n\t # 駒取り\n\t if nari\n\t count += 1\n out[count] = Move(banpos+MJNARI,pos,n,FLAG_NARI|FLAG_TORI,p.square[n+1]&0x0f,0)::Move # value = 0\n InsertMoveAB(count,out,gs)\n end\n if canMove\n count += 1\n out[count] = Move(banpos,pos,n,FLAG_TORI,p.square[n+1]&0x0f,0)::Move # value = 0\n InsertMoveAB(count,out,gs)\n end\n\t break\n else\n\t if nari\n count += 1\n out[count] = Move(banpos+MJNARI,pos,n,FLAG_NARI,0,0)::Move # value = 0\n InsertMoveAB(count,out,gs)\n end\n\t if canMove\n\t count += 1\n\t out[count] = Move(banpos,pos,n,0,0,0)::Move # value = 0\n InsertMoveAB(count,out,gs)\n end\n end\n end\n if enable_s == 1\n else\n break\n end\n end\n end\n # println(\"count = \", count)\n if enable_s == combine\n pos_koma -= MJNARI # UM -> KA, RY -> HI\n #println(\"combine,koma=\",pos_koma)\n enable_s = 1\n #continue\n else\n break\n end\n end\n count\nend\n\nfunction mailboxQ0x88(teban::Int,\n\t pos::Int,\n\t p::Board,\n\t out::Array{Move,1}, # outは可能手バッファの先頭\n\t count::Int32, # countは既に見つけた可能手の個数\n\t gs::GameStatus)\n i::Int = 0\n n::Int = 0\n banpos::Int = p.square[pos+1] # 動かす駒\n pos_koma::Int = banpos & 0x0f # 動かす駒の種類\n num_of_moves::Int = koma_num_of_moves[pos_koma] # 駒の動かせる方向数\n enable_s::Int = EnableSlide[pos_koma] # slide pieceか否か\n teban_flag = (teban == SENTE) ? 1: -1 # 先手なら1、後手ならー1\n nari::Bool = false # 成りフラグ\n canMove::Bool = false # 動かすことが可能なら1\n value::Int = 0 # 可能手の値\n koma_teban::Int = 0 # 駒(移動先)の手番\n\n while true # UM,RY用のループ\n for i = 1:num_of_moves\n n = pos\n while true\n #println(\"A pos=\",pos,\", n=\",n, \", koma = \", pos_koma, \", i = \", i, \", numofmoves= \", num_of_moves)\n #println(\"A mailbox81 = \", mailbox81[n+1])\n #println(\"A offset = \", koma_moves_offset[pos_koma,i])\n n = mailbox[mailbox81[n+1] + (teban_flag*koma_moves_offset[pos_koma,i])+1]\n #println(\"B pos=\",pos,\", n=\",n)\n if n == -1\n break\n else\n\t # make a move\n\t nari = CanIPromote( teban, pos, n, banpos);\n\t canMove = CanMoveTo(teban, pos, n, banpos);\n\t # value = (pos << 24) | (n << 16);\n newkoma = p.square[n+1]\n\t koma_teban = (newkoma & 0x10) >>> 4;\n\t if (newkoma != MJNONE) && (koma_teban == teban)\n\t break\n\t elseif (newkoma != MJNONE)&&(koma_teban == ((teban==SENTE)?GOTE:SENTE))\n\t # 駒取り\n\t if nari\n\t count += 1\n out[count] = Move(banpos+MJNARI,pos,n,FLAG_NARI|FLAG_TORI,p.square[n+1]&0x0f,0)::Move # value = 0\n InsertMove(count,out,gs)\n end\n if canMove\n count += 1\n out[count] = Move(banpos,pos,n,FLAG_TORI,p.square[n+1]&0x0f,0)::Move # value = 0\n InsertMove(count,out,gs)\n end\n\t break\n else\n\t if nari\n count += 1\n out[count] = Move(banpos+MJNARI,pos,n,FLAG_NARI,0,0)::Move # value = 0\n InsertMove(count,out,gs)\n end\n end\n end\n if enable_s == 1\n else\n break\n end\n end\n end\n # println(\"count = \", count)\n if enable_s == combine\n pos_koma -= MJNARI # UM -> KA, RY -> HI\n #println(\"combine,koma=\",pos_koma)\n enable_s = 1\n #continue\n else\n break\n end\n end\n count\nend\n\n# 可能手生成(first draft)\n# 昔あった持ち駒bit arrayは盤面を参照すればいらないはず\n# 盤面を進める・戻すのはmakeMove/takeBackが行う\n# 一手詰めを検出していない、非合法手を含んだ配列を返す\n#@iprofile begin\nfunction generateMoves(p::Board, # /* IN:盤面 */\n\t out::Array{Move,1}, # /* IN/OUT: 可能手を格納する配列*/\n\t teban::Int, # /* 可能手を生成する手番 */\n co::Int,\n\t gs::GameStatus)\n\n i::Int = 0\n j::Int = 0\n count::Int32 = int32(co)\n fu_bit_array::Uint = 0x1ff # 歩を打てない筋に対応するbitが0になる\n # MW_u08t *k = &(p->ban[0]);\n\n # 歩のある筋をfu_bit_arrayにセット: 2歩の検出のため\n for i = 0:(NumSQ-1)\n j = i % 9\n val::Int = p.square[i+1]\n if val & 0x0f == MJFU\n if (val & 0x10) >>> 4 == teban\n\t fu_bit_array &= ~(1<<j) # jは(9-段+1): 左から何列目か\n end\n end \n end\n #println(\"fu_bit_array = 0x\", hex(fu_bit_array))\n\n # ここから可能手生成部\n # まず駒を動かすことで生成できる手を生成する\n # k = &(p->ban[0]);\n for i = 0:(NumSQ-1)\n koma::Int = p.square[i+1]\n komateban::Int = (koma&0x10)>>>4\n if (koma != MJNONE)&&(komateban == teban) # 自分の駒をまず拾い出して可能手生成\n count = mailbox0x88( teban, i, p, out, count, gs)\n end\n end\n\n # 打つ手を生成する\n # k = &(p->ban[0]);\n ##println(\"uchu!(count = \", count, \")\")\n # MW_u08t fromIdx = (teban == SENTE) ? MO_HI_SENTE: MO_HI_GOTE;\n # MW_u08t toIdx = (teban == SENTE) ? MO_SENTE_OFFSET: MO_GOTE_OFFSET;\n fromIdx::Int = MJHI\n toIdx::Int = MJFU\n for j = fromIdx:-1:toIdx\n uchiGoma = j\n if teban == SENTE\n if p.WhitePiecesInHands[j] == 0\n else\n count = recycleMove( fu_bit_array, teban, uchiGoma, p, out, count, gs)\n end\n else\n if p.BlackPiecesInHands[j] == 0\n else\n count = recycleMove( fu_bit_array, teban, uchiGoma, p, out, count, gs)\n end\n end\n end\n #println(\"return value of generate move = \", count)\n count # 可能手の通算の数を返す\nend\n#end # @iprofile begin\n\nfunction generateQMoves(p::Board, # /* IN:盤面 */\n\t out::Array{Move,1}, # /* IN/OUT: 可能手を格納する配列*/\n\t teban::Int, # /* 可能手を生成する手番 */\n co::Int,\n\t gs::GameStatus)\n\n i::Int = 0\n j::Int = 0\n count::Int32 = int32(co)\n\n # ここから可能手生成部\n # まず駒を動かすことで生成できる手を生成する\n # k = &(p->ban[0]);\n for i = 0:(NumSQ-1)\n koma::Int = p.square[i+1]\n komateban::Int = (koma&0x10)>>>4\n if (koma != MJNONE)&&(komateban == teban) # 自分の駒をまず拾い出して可能手生成\n count = mailboxQ0x88( teban, i, p, out, count, gs)\n end\n end\n\n count # 可能手の通算の数を返す\nend\n\nfunction SujiDanFrom(from::Int)\n s1::UTF8String = \"\"\n if from == MO_MOVE_SENTE\n s1 = \"駒台\"\n elseif from == MO_MOVE_GOTE\n s1 = \"駒台\"\n else\n s1 = string(SUJISTR[9- (from%9)],DANSTR[int(floor(from/9)) + 1])\n end\n s1\nend\n\nfunction SujiDanTo(to::Int)\n #println(\"to=\",to,\"suji=\",9-(to%9),\", dan=\",int(to/9)+1)\n s1::UTF8String = string(SUJISTR[9- (to%9)],DANSTR[int(floor(to/9)) + 1])\n s1\nend\n\nfunction Move2String(m::Move)\n from::Int = seeMoveFrom(m)\n to::Int = seeMoveTo(m)\n capt::Int = seeMoveCapt(m)\n flag::Int = seeMoveFlag(m)\n piece::Int = seeMovePiece(m)\n sengo::Int = (piece & 0x10) >>> 4\n\n captstr::UTF8String = \"\"\n naristr::UTF8String = \"\"\n uchistr::UTF8String = \"\"\n\n if capt != 0\n captstr = string(KOMASTR[capt],\"取り\")\n end\n if flag & FLAG_NARI != 0\n naristr = \"成り\"\n end\n if flag & FLAG_UCHI != 0\n uchistr = \"打ち\"\n end\n\n s::String = string(TEBANSTR[sengo+1],SujiDanTo(to),\"(\",SujiDanFrom(from),\")\",KOMASTR[piece&0x0f],captstr,naristr,uchistr)\n s\nend\n\nfunction makeMoveOld(q::Board,\n\t\t moveIdx::Int,\n\t\t out::Array{Move,1},\n\t\t teban::Int)\n #println(\"moveIdx=\",moveIdx)\n m::Move = out[moveIdx]\n from::Int = seeMoveFrom(m)\n to::Int = seeMoveTo(m)\n koma::Int = seeMovePiece(m) & 0x0f\n komadai::Int = (teban == SENTE) ? MO_MOVE_SENTE: MO_MOVE_GOTE\n komavalTo = q.square[to+1]\n # seeMoveCapt(m)\n # seeMoveFlag(m)\n if komavalTo == MJNONE\n # そのまま置く、打ちも含む\n q.square[to+1] = (teban << 4)|int(koma)\n if q.square[to+1] == MJOU\n q.kingposW = to+1\n elseif q.square[to+1] == MJGOOU\n q.kingposB = to+1\n end\n if from > NumSQ # 駒台から一つ駒を取り除く\n if from == MO_MOVE_SENTE\n q.WhitePiecesInHands[koma] -= 1\n #println(\"mochiWR(\",koma,\") = \", q.WhitePiecesInHands[koma])\n if q.WhitePiecesInHands[koma] < 0\n println(\"Shotage of Mochigoma array (koma = ,\",koma,\")\")\n end\n else\n q.BlackPiecesInHands[koma] -= 1\n #println(\"mochiBR(\",koma,\") = \", q.BlackPiecesInHands[koma])\n if q.BlackPiecesInHands[koma] < 0\n println(\"Shotage of Mochigoma array (koma = ,\",koma,\")\")\n end\n end\n else\n q.square[from+1] = MJNONE\n end\n else\n # 駒を取る\n if (komavalTo & 0x10) == (teban << 4)\n # illegal move!\n println(\"Illegal move! (\",Move2String(out[moveIdx]),\")\")\n else\n q.square[to+1] = (teban << 4)|koma\n komavalTo::Int = komavalTo & 0x0f\n normalKoma = (komavalTo > MJOU) ? komavalTo - MJNARI: komavalTo\n if teban == SENTE\n q.WhitePiecesInHands[normalKoma] += 1\n #println(\"mochiW(\",normalKoma,\") = \", q.WhitePiecesInHands[normalKoma])\n else\n q.BlackPiecesInHands[normalKoma] += 1\n #println(\"mochiB(\",normalKoma,\") = \", q.BlackPiecesInHands[normalKoma])\n end\n q.square[from+1] = MJNONE\n end\n end\n q.nextMove $= 1\nend\n\n# レジスタ使いすぎ。。。\nfunction takeBackOld(q::Board,\n\t\t moveIdx::Int,\n\t\t out::Array{Move,1},\n\t\t teban::Int)\n m::Move = out[moveIdx]\n from::Int = seeMoveFrom(m)\n to::Int = seeMoveTo(m)\n koma::Int = seeMovePiece(m) & 0x0f\n komadai::Int = (teban == SENTE) ? MO_MOVE_SENTE: MO_MOVE_GOTE\n removed::Int = seeMoveCapt(m)\n removedOmote = (removed > MJOU) ? removed - MJNARI : removed\n flag::Int = seeMoveFlag(m)\n nari::Int = flag & FLAG_NARI\n tori::Int = flag & FLAG_TORI\n uchi::Int = flag & FLAG_UCHI\n komatmp::Int = MJNONE\n\n if (uchi == FLAG_UCHI) # case 1: 打ち。toの駒を駒台に戻す\n uchiGoma = q.square[to+1] & 0x0f\n q.square[to+1] = MJNONE\n if teban == SENTE\n q.WhitePiecesInHands[uchiGoma] += 1\n else\n q.BlackPiecesInHands[uchiGoma] += 1\n end\n elseif tori == FLAG_TORI\n # toの駒をfromに戻す(case 3と同じ)\n # その上で駒台の駒をtoに戻す\n komatmp = q.square[to+1]\n # 成っていた場合は表に戻す\n q.square[from+1] = (nari == FLAG_NARI) ? komatmp - MJNARI: komatmp\n if q.square[from+1] == MJOU\n q.kingposW = from+1\n elseif q.square[from+1] == MJGOOU\n q.kingposB = from+1\n end\n # 駒台の駒を元のtoに戻す。\n q.square[to+1] = removed | ((teban$1)<< 4) # 相手の駒に\n if teban == SENTE\n q.WhitePiecesInHands[removedOmote] -= 1\n if q.WhitePiecesInHands[removedOmote] < 0\n println(\"Illegal Move (takeBack,TORI,White)\")\n end\n else\n q.BlackPiecesInHands[removedOmote] -= 1\n if q.BlackPiecesInHands[removedOmote] < 0\n println(\"Illegal Move (takeBack,TORI,Black)\")\n end\n end\n else # case 3: 駒台の絡まない普通の指し手。toをfromに戻すだけ\n komatmp = q.square[to+1]\n q.square[to+1] = MJNONE\n # 成っていた場合は表に戻す\n q.square[from+1] = (nari == FLAG_NARI) ? komatmp - MJNARI: komatmp\n if q.square[from+1] == MJOU\n q.kingposW = from+1\n elseif q.square[from+1] == MJGOOU\n q.kingposB = from+1\n end\n end\n q.nextMove $= 1\nend\n\nfunction findPosition(st::ASCIIString) # 0 origin\n fromSuji::Int = int(st[1] - '0')\n fromDan::Int = int(st[2] - '`')\n #println(\"(suji,dan) = \",fromSuji, \",\",fromDan)\n return (fromDan-1)*NumFile + (9-fromSuji)\n # return BOARDINDEX[fromSuji,fromDan] - 1\nend\n\nfunction findIndex(out::Array{Move,1},move::ASCIIString,sengo::Int,\n Start::Int,End::Int)\n index::Int = -1\n nari::Int = 0\n uchiKoma::Int = 0\n uchi::Int = 0\n i::Int = 0\n\n if '1' <= move[1] <= '9' # normal move\n from = findPosition(move[1:2])\n to = findPosition(move[3:4])\n if length(move) == 5\n if move[5] == '+'\n #println(\"NARI!\")\n nari = FLAG_NARI\n end\n end\n else # Uchi\n uchi = FLAG_UCHI\n if sengo == SENTE\n from = MO_MOVE_SENTE\n else\n from = MO_MOVE_GOTE\n end\n uchiKoma = get(usiDict,move[1:1],0)|(sengo<<4)\n to = findPosition(move[3:4])\n end\n #println(\"from=\", from, \", to=\", to)\n mm::Move = Move(sengo<<4,from,to,nari|uchi,0,0)::Move\n lhs::Int = mm.move & 0xffff05f0\n lhs2::Int = mm.move & 0xfffff000\n #println(\"start,end = \", Start, \", \", End)\n for i = Start:End\n # println(\"# lhs = \", hex(lhs), \", out[i].move = \", hex(out[i].move & 0xfffff5f0))\n if (out[i].move & 0xffff0000) == (mm.move & 0xffff0000)\n #println(\"move[\",i,\"(\",Start,\",\",End,\")] = \", hex(out[i].move),\",lhs=\",hex(lhs),\",move=\",move)\n end\n if lhs == (out[i].move & 0xffff05f0)\n if uchi > 0\n if (out[i].move & 0x1f) == uchiKoma\n index = i\n break\n end\n else \n index = i\n break\n end\n end\n if lhs2 == (out[i].move & 0xffff0f00)\n #println(\"lhs2=\",hex(lhs2),\"move=\",hex(out[i].move))\n end\n end\n return index\nend\n\nfunction move2USIString(m::Move)\n ret::String = \"\"\n nari::Int = 0\n capt::String = \"\"\n from::String = \"\"\n to::String = \"\"\n\n if (m.move & 0x00000400) == 0x00000400 # UCHI\n capt = num2usiDict[int(m.move & 0x1f)]\n to = USISQNAME[seeMoveTo(m)+1]\n ret = string(capt,\"*\",to)\n else # 普通の手\n to = USISQNAME[seeMoveTo(m)+1]\n from = USISQNAME[seeMoveFrom(m)+1]\n if (m.move & 0x00000100) == 0x00000100\n nari = FLAG_NARI\n ret = string(from,to,\"+\")\n else\n ret = string(from,to)\n end\n end\n return ret\nend\n\nfunction IndexTest()\n count::Int = 0\n for j = 'a':'i'\n for i = '9':-1:'1'\n sq = string(i,j)\n println(\"sq=\",sq)\n idx::Int = findPosition(sq)\n println(\"index=\",idx)\n println(\"USI[\",idx+1,\"] = \", USISQNAME[idx+1])\n if (sq == USISQNAME[idx+1])\n count += 1\n end\n end\n end\n println(count,\" matched.\")\nend\n\n#IndexTest()\n\nfunction GenMoveTest(gs::GameStatus)\n bo = Board()\n #board = SquareInit(HIRATE,[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],SENTE,bo)\n sfenHirate = \"lnsgkgsnl/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1\"\n board = InitSFEN(sfenHirate, bo)\n DisplayBoard(board)\n sfen = \"8l/1l+R2P3/p2pBG1pp/kps1p4/Nn1P2G2/P1P1P2PP/1PS6/1KSG3+r1/LN2+p3L w Sbgn3p 124\"::String\n bo2 = Board()\n board2 = InitSFEN(sfen, bo2)\n DisplayBoard(board2)\n out = [Move(0,0,0,0,0,0) for n = 1:1000]\n #history = [0 for x = 1:NumSQ, y = 1:NumSQ]\n println(\"generate moves!\")\n num::Int32 = 0\n tic()\n for x = 1:100000 # 10000\n num = generateMoves(board2,#board,\n\t out, # /* IN/OUT: 可能手を格納する配列*/\n\t SENTE, #board.nextMove, # /* 可能手を生成する手番 */\n\t #(board2.nextMove == SENTE)? GOTE:SENTE, #board.nextMove, # /* 可能手を生成する手番 */\n 0,\n\t gs)\n end\n toc()\n println(\"return value of generate move = \", num)\n for i = 1:num\n println(hex(out[i].move),\":\",Move2String(out[i]))\n end\n #@iprofile report\n\n v::Int = Eval( SENTE, board2)\n println(\"eval = \",v)\n\n num = generateMoves(board, out, SENTE, 0, gs)\n for i = 1:num\n makeMove(board,\n\t\t i,\n\t\t out,\n\t\t SENTE)\n takeBack(board,\n\t\t i,\n\t\t out,\n\t\t SENTE)\n end\n num = generateMoves(board, out, GOTE, 0, gs)\n for i = 1:num\n makeMove(board,\n\t\t i,\n\t\t out,\n\t\t GOTE)\n takeBack(board,\n\t\t i,\n\t\t out,\n\t\t GOTE)\n end\n DisplayBoard(board)\n v = Eval( SENTE, board)\n println(\"eval = \",v)\n for i = 0:(NumSQ-1)\n print(\"[\")\n if NewAttack(SENTE, i, board)\n #println(\"SQ[\",SQUARENAME[i+1],\"](SENTE) is attacked!\")\n print(\"S\")\n else\n print(\"_\")\n end\n if NewAttack(GOTE, i, board)\n #println(\"SQ[\",SQUARENAME[i+1],\"](GOTE ) is attacked!\")\n print(\"G\")\n else\n print(\"_\")\n end\n print(\"]\")\n if (i % 9) == 8\n println()\n end\n end\nend\n\n#GenMoveTest()\n", "meta": {"hexsha": "dc3725998dc420647abe9d139d26b1aa4a8bbacc", "size": 34826, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia/OldGenMove.jl", "max_stars_repo_name": "kimrin/JapaneseChess", "max_stars_repo_head_hexsha": "6a213a45c104bd4004d4db31080efbc80d389c2d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-01-27T12:34:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-05T18:05:38.000Z", "max_issues_repo_path": "Julia/OldGenMove.jl", "max_issues_repo_name": "kimrin/JapaneseChess", "max_issues_repo_head_hexsha": "6a213a45c104bd4004d4db31080efbc80d389c2d", "max_issues_repo_licenses": ["MIT"], "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/OldGenMove.jl", "max_forks_repo_name": "kimrin/JapaneseChess", "max_forks_repo_head_hexsha": "6a213a45c104bd4004d4db31080efbc80d389c2d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2015-12-19T12:38:00.000Z", "max_forks_repo_forks_event_max_datetime": "2015-12-19T12:38:00.000Z", "avg_line_length": 33.5510597303, "max_line_length": 125, "alphanum_fraction": 0.4336415322, "num_tokens": 12116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.24798742068237778, "lm_q1q2_score": 0.13845807122257403}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.7\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n quote\n local el = $(esc(element))\n global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n el\n end\nend\n\n# ╔═╡ 86e1ee96-f314-11ea-03f6-0f549b79e7c9\nbegin\n\tusing Pkg\n\tPkg.activate(mktempdir())\nend\n\n# ╔═╡ a4937996-f314-11ea-2ff9-615c888afaa8\nbegin\n\tPkg.add([\n\t\t\t\"Compose\",\n\t\t\t\"Colors\",\n\t\t\t\"PlutoUI\",\n\t\t\t])\n\n\tusing Colors\n\tusing PlutoUI\n\tusing Compose\n\tusing LinearAlgebra\nend\n\n# ╔═╡ e6b6760a-f37f-11ea-3ae1-65443ef5a81a\nmd\"_homework 3, version 3_\"\n\n# ╔═╡ 85cfbd10-f384-11ea-31dc-b5693630a4c5\nmd\"\"\"\n\n# **Homework 3**: _Structure and Language_\n`18.S191`, fall 2020\n\nThis notebook contains _built-in, live answer checks_! In some exercises you will see a coloured box, which runs a test case on your code, and provides feedback based on the result. Simply edit the code, run it, and the check runs again.\n\n_For MIT students:_ there will also be some additional (secret) test cases that will be run as part of the grading process, and we will look at your notebook and write comments.\n\nFeel free to ask questions!\n\"\"\"\n\n# ╔═╡ 33e43c7c-f381-11ea-3abc-c942327456b1\n# edit the code below to set your name and kerberos ID (i.e. email without @mit.edu)\n\nstudent = (name = \"Panagiotis Georgakopoulos\", kerberos_id = \"jazz\")\n\n# you might need to wait until all other cells in this notebook have completed running. \n# scroll around the page to see what's up\n\n# ╔═╡ ec66314e-f37f-11ea-0af4-31da0584e881\nmd\"\"\"\n\nSubmission by: **_$(student.name)_** ($(student.kerberos_id)@mit.edu)\n\"\"\"\n\n# ╔═╡ 938185ec-f384-11ea-21dc-b56b7469f798\nmd\"_Let's create a package environment:_\"\n\n# ╔═╡ b49a21a6-f381-11ea-1a98-7f144c55c9b7\nhtml\"\"\"\n<iframe width=\"100%\" height=\"450px\" src=\"https://www.youtube.com/embed/ConoBmjlivs?rel=0\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen></iframe>\n\"\"\"\n\n# ╔═╡ 6f9df800-f92d-11ea-2d49-c1aaabd2d012\nmd\"\"\"\n## **Exercise 1:** _Language detection_\n\nIn this exercise, we are going to create some super simple _Artificial Intelligence_. Natural language can be quite messy, but hidden in this mess is _structure_, which we are going to look for today.\n\nLet's start with some obvious structure in English text: the set of characters that we write the language in. If we generate random text by sampling _random Unicode characters_, it does not look like English:\n\"\"\"\n\n# ╔═╡ b61722cc-f98f-11ea-22ae-d755f61f78c3\nString(rand(Char, 40))\n\n# ╔═╡ f457ad44-f990-11ea-0e2d-2bb7627716a8\nmd\"\"\"\nInstead, let's define an _alphabet_, and only use those letters to sample from. To keep things simple, we ignore punctuation, capitalization, etc, and only use these 27 characters:\n\"\"\"\n\n# ╔═╡ 4efc051e-f92e-11ea-080e-bde6b8f9295a\nalphabet = ['a':'z' ; ' '] # includes the space character\n\n# ╔═╡ 38d1ace8-f991-11ea-0b5f-ed7bd08edde5\nmd\"\"\"\nLet's sample random characters from our alphabet:\n\"\"\"\n\n# ╔═╡ ddf272c8-f990-11ea-2135-7bf1a6dca0b7\nString(rand(alphabet, 40)) |> Text\n\n# ╔═╡ 3cc688d2-f996-11ea-2a6f-0b4c7a5b74c2\nmd\"\"\"\nThat already looks a lot better than our first attempt! But still, this does not look like English text -- we can do better. \n\n$(html\"<br>\")\n\nEnglish words are not well modelled by this random-Latin-characters model. Our first observation is that **some letters are more common than others**. To put this observation into practice, we would like to have the **frequency table** of the Latin alphabet. We could search for it online, but it is actually very simple to calculate ourselves! The only thing we need is a _representative sample_ of English text.\n\nThe following samples are from Wikipedia, but feel free to type in your own sample! You can also enter a sample of a different language, if that language can be expressed in the Latin alphabet.\n\nRemember that the $(html\"<img src='https://cdn.jsdelivr.net/gh/ionic-team/ionicons@5.0.0/src/svg/eye-outline.svg' style='width: 1em; height: 1em; margin-bottom: -.2em;'>\") button on the left of a cell will show or hide the code.\n\nWe also include a sample of Spanish, which we'll use later!\n\"\"\"\n\n# ╔═╡ a094e2ac-f92d-11ea-141a-3566552dd839\nmd\"\"\"\n#### Exercise 1.1 - _Data cleaning_\nLooking at the sample, we see that it is quite _messy_: it contains punctuation, accented letters and numbers. For our analysis, we are only interested in our 27-character alphabet (i.e. `'a'` through `'z'` plus `' '`). We are going to clean the data using the Julia function `filter`. \n\"\"\"\n\n# ╔═╡ 27c9a7f4-f996-11ea-1e46-19e3fc840ad9\nfilter(isodd, [6, 7, 8, 9, -5])\n\n# ╔═╡ f2a4edfa-f996-11ea-1a24-1ba78fd92233\nmd\"\"\"\n`filter` takes two arguments: a **function** and a **collection**. The function is applied to each element of the collection, and it returns either `true` or `false`. If the result is `true`, then that element is included in the final collection.\n\nDid you notice something cool? Functions are also just _objects_ in Julia, and you can use them as arguments to other functions! _(Fons thinks this is super cool.)_\n\n$(html\"<br>\")\n\nWe have written a function `isinalphabet`, which takes a character and returns a boolean:\n\"\"\"\n\n# ╔═╡ 5c74a052-f92e-11ea-2c5b-0f1a3a14e313\nfunction isinalphabet(character)\n\tcharacter ∈ alphabet\nend\n\n# ╔═╡ dcc4156c-f997-11ea-3e6f-057cd080d9db\nisinalphabet('a'), isinalphabet('+')\n\n# ╔═╡ 129fbcfe-f998-11ea-1c96-0fd3ccd2dcf8\nmd\"👉 Use `filter` to extract just the characters from our alphabet out of `messy_sentence_1`:\"\n\n# ╔═╡ 3a5ee698-f998-11ea-0452-19b70ed11a1d\nmessy_sentence_1 = \"#wow 2020 ¥500 (blingbling!)\"\n\n# ╔═╡ 75694166-f998-11ea-0428-c96e1113e2a0\ncleaned_sentence_1 = filter(isinalphabet, messy_sentence_1)\n\n# ╔═╡ 05f0182c-f999-11ea-0a52-3d46c65a049e\nmd\"\"\"\n$(html\"<br>\")\n\nWe are not interested in the case of letters (i.e. `'A'` vs `'a'`), so we want to map these to lower case _before_ we apply our filter. If we don't, all upper case letters would get deleted.\n\"\"\"\n\n# ╔═╡ 98266882-f998-11ea-3270-4339fb502bc7\nmd\"👉 Use the function `lowercase` to convert `messy_sentence_2` into a lower case string, and then use `filter` to extract only the characters from our alphabet.\"\n\n# ╔═╡ d3c98450-f998-11ea-3caf-895183af926b\nmessy_sentence_2 = \"Awesome! 😍\"\n\n# ╔═╡ d3a4820e-f998-11ea-2a5c-1f37e2a6dd0a\ncleaned_sentence_2 = filter(isinalphabet, lowercase.(messy_sentence_2))\n\n# ╔═╡ aad659b8-f998-11ea-153e-3dae9514bfeb\nmd\"\"\"\n$(html\"<br>\")\n\nFinally, we need to deal with **accents**: simply deleting accented characters from the source text might deform it too much. We can add accented letters to our alphabet, but a simpler solution is to *replace* accented letters with the corresponding unaccented base character. We have written a function `unaccent` that does just that.\n\"\"\"\n\n# ╔═╡ d236b51e-f997-11ea-0c55-abb11eb35f4d\nfrench_word = \"Égalité!\"\n\n# ╔═╡ 24860970-fc48-11ea-0009-cddee695772c\nimport Unicode\n\n# ╔═╡ 734851c6-f92d-11ea-130d-bf2a69e89255\n\"\"\"\nTurn `\"áéíóúüñ asdf\"` into `\"aeiouun asdf\"`.\n\"\"\"\nunaccent(str) = Unicode.normalize(str, stripmark=true)\n\n# ╔═╡ d67034d0-f92d-11ea-31c2-f7a38ebb412f\nsamples = (\n\tEnglish = \"\"\"\nAlthough the word forest is commonly used, there is no universally recognised precise definition, with more than 800 definitions of forest used around the world.[4] Although a forest is usually defined by the presence of trees, under many definitions an area completely lacking trees may still be considered a forest if it grew trees in the past, will grow trees in the future,[9] or was legally designated as a forest regardless of vegetation type.[10][11]\n\t\nThe word forest derives from the Old French forest (also forès), denoting \"forest, vast expanse covered by trees\"; forest was first introduced into English as the word denoting wild land set aside for hunting[14] without the necessity in definition of having trees on the land.[15] Possibly a borrowing, probably via Frankish or Old High German, of the Medieval Latin foresta, denoting \"open wood\", Carolingian scribes first used foresta in the Capitularies of Charlemagne specifically to denote the royal hunting grounds of the King. The word was not endemic to Romance languages, e. g. native words for forest in the Romance languages derived from the Latin silva, which denoted \"forest\" and \"wood(land)\" (confer the English sylva and sylvan); confer the Italian, Spanish, and Portuguese selva; the Romanian silvă; and the Old French selve, and cognates in Romance languages, e. g. the Italian foresta, Spanish and Portuguese floresta, etc., are all ultimately derivations of the French word. \n\"\"\",\n\tSpanish = \"\"\"\nUn bosque es un ecosistema donde la vegetación predominante la constituyen los árboles y matas.1​ Estas comunidades de plantas cubren grandes áreas del globo terráqueo y funcionan como hábitats para los animales, moduladores de flujos hidrológicos y conservadores del suelo, constituyendo uno de los aspectos más importantes de la biosfera de la Tierra. Aunque a menudo se han considerado como consumidores de dióxido de carbono atmosférico, los bosques maduros son prácticamente neutros en cuanto al carbono, y son solamente los alterados y los jóvenes los que actúan como dichos consumidores.2​3​ De cualquier manera, los bosques maduros juegan un importante papel en el ciclo global del carbono, como reservorios estables de carbono y su eliminación conlleva un incremento de los niveles de dióxido de carbono atmosférico.\n\nLos bosques pueden hallarse en todas las regiones capaces de mantener el crecimiento de árboles, hasta la línea de árboles, excepto donde la frecuencia de fuego natural es demasiado alta, o donde el ambiente ha sido perjudicado por procesos naturales o por actividades humanas. Los bosques a veces contienen muchas especies de árboles dentro de una pequeña área (como la selva lluviosa tropical y el bosque templado caducifolio), o relativamente pocas especies en áreas grandes (por ejemplo, la taiga y bosques áridos montañosos de coníferas). Los bosques son a menudo hogar de muchos animales y especies de plantas, y la biomasa por área de unidad es alta comparada a otras comunidades de vegetación. La mayor parte de esta biomasa se halla en el subsuelo en los sistemas de raíces y como detritos de plantas parcialmente descompuestos. El componente leñoso de un bosque contiene lignina, cuya descomposición es relativamente lenta comparado con otros materiales orgánicos como la celulosa y otros carbohidratos. Los bosques son áreas naturales y silvestre \n\"\"\" |> unaccent,\n)\n\n# ╔═╡ a56724b6-f9a0-11ea-18f2-991e0382eccf\nunaccent(french_word)\n\n# ╔═╡ 8d3bc9ea-f9a1-11ea-1508-8da4b7674629\nmd\"\"\"\n$(html\"<br>\")\n\n👉 Let's put everything together. Write a function `clean` that takes a string, and returns a _cleaned_ version, where:\n- accented letters are replaced by their base characters;\n- upper-case letters are converted to lower case;\n- it is filtered to only contain characters from `alphabet`\n\"\"\"\n\n# ╔═╡ 4affa858-f92e-11ea-3ece-258897c37e51\nfunction clean(text)\n\t# we turn everything to lowercase to keep the number of letters small\n\tfilter(isinalphabet, unaccent(lowercase.(text)))\nend\n\n# ╔═╡ e00d521a-f992-11ea-11e0-e9da8255b23b\nclean(\"Crème brûlée est mon plat préféré.\")\n\n# ╔═╡ 2680b506-f9a3-11ea-0849-3989de27dd9f\nfirst_sample = clean(first(samples))\n\n# ╔═╡ 571d28d6-f960-11ea-1b2e-d5977ecbbb11\nfunction letter_frequencies(txt)\n\tismissing(txt) && return missing\n\tf = count.(string.(alphabet), txt)\n\tf ./ sum(f)\nend\n\n# ╔═╡ 6a64ab12-f960-11ea-0d92-5b88943cdb1a\nsample_freqs = letter_frequencies(first_sample)\n\n# ╔═╡ 603741c2-f9a4-11ea-37ce-1b36ecc83f45\nmd\"\"\"\nThe result is a 27-element array, with values between `0.0` and `1.0`. These values correspond to the _frequency_ of each letter. \n\n`sample_freqs[i] == 0.0` means that the $i$th letter did not occur in your sample, and \n`sample_freqs[i] == 0.1` means that 10% of the letters in the sample are the $i$th letter.\n\nTo make it easier to convert between a character from the alphabet and its index, we have the following function:\n\"\"\"\n\n# ╔═╡ b3de6260-f9a4-11ea-1bae-9153a92c3fe5\nindex_of_letter(letter) = findfirst(isequal(letter), alphabet)\n\n# ╔═╡ a6c36bd6-f9a4-11ea-1aba-f75cecc90320\nindex_of_letter('a'), index_of_letter('b'), index_of_letter(' ')\n\n# ╔═╡ 6d3f9dae-f9a5-11ea-3228-d147435e266d\nmd\"\"\"\n$(html\"<br>\")\n\n👉 Which letters from the alphabet did not occur in the sample?\n\"\"\"\n\n# ╔═╡ 92bf9fd2-f9a5-11ea-25c7-5966e44db6c6\nunused_letters = let\n\t[l for l ∈ alphabet if sample_freqs[index_of_letter(l)] === 0.0]\nend\n\n# ╔═╡ 01215e9a-f9a9-11ea-363b-67392741c8d4\nmd\"\"\"\n**Random letters at the correct frequencies:**\n\"\"\"\n\n# ╔═╡ 8ae13cf0-f9a8-11ea-3919-a735c4ed9e7f\nmd\"\"\"\nBy considering the _frequencies_ of letters in English, we see that our model is already a lot better!\n\nOur next observation is that **some letter _combinations_ are more common than others**. Our current model thinks that `potato` is just as 'English' as `ooaptt`. In the next section, we will quantify these _transition frequencies_, and use it to improve our model.\n\"\"\"\n\n# ╔═╡ 343d63c2-fb58-11ea-0cce-efe1afe070c2\n\n\n# ╔═╡ b5b8dd18-f938-11ea-157b-53b145357fd1\nfunction rand_sample(frequencies)\n\tx = rand()\n\tfindfirst(z -> z >= x, cumsum(frequencies ./ sum(frequencies)))\nend\n\n# ╔═╡ 0e872a6c-f937-11ea-125e-37958713a495\nfunction rand_sample_letter(frequencies)\n\talphabet[rand_sample(frequencies)]\nend\n\n# ╔═╡ fbb7c04e-f92d-11ea-0b81-0be20da242c8\nfunction transition_counts(cleaned_sample)\n\t[count(string(a, b), cleaned_sample)\n\t\tfor a in alphabet,\n\t\t\tb in alphabet]\nend\n\n# ╔═╡ 80118bf8-f931-11ea-34f3-b7828113ffd8\nnormalize_array(x) = x ./ sum(x)\n\n# ╔═╡ 7f4f6ce4-f931-11ea-15a4-b3bec6a7e8b6\ntransition_frequencies = normalize_array ∘ transition_counts;\n\n# ╔═╡ d40034f6-f9ab-11ea-3f65-7ffd1256ae9d\ntransition_frequencies(first_sample)\n\n# ╔═╡ 689ed82a-f9ae-11ea-159c-331ff6660a75\nmd\"What we get is a **27 by 27 matrix**. Each entry corresponds to a character pair. The _row_ corresponds to the first character, the _column_ is the second character. Let's visualize this:\"\n\n# ╔═╡ 0b67789c-f931-11ea-113c-35e5edafcbbf\nmd\"\"\"\nAnswer the following questions with respect to the **cleaned English sample text**, which we called `first_sample`. Let's also give the transition matrix a name:\n\"\"\"\n\n# ╔═╡ 6896fef8-f9af-11ea-0065-816a70ba9670\nsample_freq_matrix = transition_frequencies(first_sample);\n\n# ╔═╡ 39152104-fc49-11ea-04dd-bb34e3600f2f\nif first_sample === missing\n\tmd\"\"\"\n\t!!! danger \"Don't worry!\"\n\t 👆 These errors will disappear automatically once you have completed the earlier exercises!\n\t\"\"\"\nend\n\n# ╔═╡ e91c6fd8-f930-11ea-01ac-476bbde79079\nmd\"\"\"👉 What is the frequency of the combination `\"th\"`?\"\"\"\n\n# ╔═╡ 1b4c0c28-f9ab-11ea-03a6-69f69f7f90ed\nth_frequency = sample_freq_matrix[index_of_letter('t'), index_of_letter('h')]\n\n# ╔═╡ 1f94e0a2-f9ab-11ea-1347-7dd906ebb09d\nmd\"\"\"👉 What about `\"ht\"`?\"\"\"\n\n# ╔═╡ 41b2df7c-f931-11ea-112e-ede3b16f357a\nht_frequency = sample_freq_matrix[index_of_letter('h'), index_of_letter('t')]\n\n# ╔═╡ 1dd1e2f4-f930-11ea-312c-5ff9e109c7f6\nmd\"\"\"\n👉 Which le**tt**ers appeared double in our sample?\n\"\"\"\n\n# ╔═╡ 65c92cac-f930-11ea-20b1-6b8f45b3f262\ndouble_letters = [l for l ∈ 'a':'z' if sample_freq_matrix[index_of_letter(l), index_of_letter(l)] > 0]\n\n# ╔═╡ 4582ebf4-f930-11ea-03b2-bf4da1a8f8df\nmd\"\"\"\n👉 Which letter is most likely to follow a **W**?\n\"\"\"\n\n# ╔═╡ 6d8f47d2-2108-11eb-105e-63c5f7d74c6e\ngetfreq = (p, n) -> sample_freq_matrix[index_of_letter(p), index_of_letter(n)]\n\n# ╔═╡ b5fcd572-2108-11eb-3581-b18f259b42f6\nindex_of_max = a -> begin\n\tm = max(a...)\n\treturn findfirst(i -> i == m, a)\nend\n\n# ╔═╡ 7898b76a-f930-11ea-2b7e-8126ec2b8ffd\nmost_likely_to_follow_w = alphabet[index_of_max([getfreq('w', l) for l ∈ alphabet])]\n\n# ╔═╡ 458cd100-f930-11ea-24b8-41a49f6596a0\nmd\"\"\"\n👉 Which letter is most likely to precede a **W**?\n\"\"\"\n\n# ╔═╡ bc401bee-f931-11ea-09cc-c5efe2f11194\nmost_likely_to_precede_w = alphabet[index_of_max([getfreq(l, 'w') for l ∈ alphabet])]\n\n# ╔═╡ 45c20988-f930-11ea-1d12-b782d2c01c11\nmd\"\"\"\n👉 What is the sum of each row? What is the sum of each column? How can we interpret these values?\"\n\"\"\"\n\n# ╔═╡ 432276c6-2109-11eb-04e8-0bb0716eb660\nsum(sample_freq_matrix, dims=2)[:, 1]\n\n# ╔═╡ cc62929e-f9af-11ea-06b9-439ac08dcb52\nrow_col_answer = md\"\"\"\n\n\"\"\"\n\n# ╔═╡ 2f8dedfc-fb98-11ea-23d7-2159bdb6a299\nmd\"\"\"\nWe can use the measured transition frequencies to generate text in a way that it has **the same transition frequencies** as our original sample. Our generated text is starting to look like real language!\n\"\"\"\n\n# ╔═╡ b7446f34-f9b1-11ea-0f39-a3c17ba740e5\n@bind ex23_sample Select([v => String(k) for (k,v) in zip(fieldnames(typeof(samples)), samples)])\n\n# ╔═╡ 4f97b572-f9b0-11ea-0a99-87af0797bf28\nmd\"\"\"\n**Random letters from the alphabet:**\n\"\"\"\n\n# ╔═╡ 4e8d327e-f9b0-11ea-3f16-c178d96d07d9\nmd\"\"\"\n**Random letters at the correct frequencies:**\n\"\"\"\n\n# ╔═╡ d83f8bbc-f9af-11ea-2392-c90e28e96c65\nmd\"\"\"\n**Random letters at the correct transition frequencies:**\n\"\"\"\n\n# ╔═╡ 0e465160-f937-11ea-0ebb-b7e02d71e8a8\nfunction sample_text(A, n)\n\t\n\tfirst_index = rand_sample(vec(sum(A, dims=1)))\n\t\n\tindices = reduce(1:n; init=[first_index]) do word, _\n\t\tprev = last(word)\n\t\tfreq = normalize_array(A[prev, :])\n\t\tnext = rand_sample(freq)\n\t\t[word..., next]\n\tend\n\t\n\tString(alphabet[indices])\nend\n\n# ╔═╡ 141af892-f933-11ea-1e5f-154167642809\nmd\"\"\"\nIt looks like we have a decent language model, in the sense that it understands _transition frequencies_ in the language. In the demo above, try switching the language between $(join(string.(fieldnames(typeof(samples))), \" and \")) -- the generated text clearly looks more like one or the other, demonstrating that the model can capture differences between the two languages. What's remarkable is that our \"training data\" was just a single paragraph per language.\n\nIn this exercise, we will use our model to write a **classifier**: a program that automatically classifies a text as either $(join(string.(fieldnames(typeof(samples))), \" or \")). \n\nThis is not a difficult task - you can get dictionaries for both languages, and count matches - but we are doing something much more cool: we only use a single paragraph of each language, and we use a _language model_ as classifier.\n\"\"\"\n\n# ╔═╡ 7eed9dde-f931-11ea-38b0-db6bfcc1b558\nhtml\"<h4 id='mystery-detect'>Mystery sample</h4>\n<p>Enter some text here -- we will detect in which language it is written!</p>\" # dont delete me\n\n# ╔═╡ 7e3282e2-f931-11ea-272f-d90779264456\n@bind mystery_sample TextField((70,8), default=\"\"\"\nSmall boats are typically found on inland waterways such as rivers and lakes, or in protected coastal areas. However, some boats, such as the whaleboat, were intended for use in an offshore environment. In modern naval terms, a boat is a vessel small enough to be carried aboard a ship. Anomalous definitions exist, as lake freighters 1,000 feet (300 m) long on the Great Lakes are called \"boats\". \n\"\"\")\n\n# ╔═╡ 7df55e6c-f931-11ea-33b8-fdc3be0b6cfa\nmystery_sample\n\n# ╔═╡ 292e0384-fb57-11ea-0238-0fbe416fc976\nmd\"\"\"\nLet's compute the transition frequencies of our mystery sample! Type some text in the box below, and check whether the frequency matrix updates.\n\"\"\"\n\n# ╔═╡ 7dabee08-f931-11ea-0cb2-c7d5afd21551\ntransition_frequencies(mystery_sample)\n\n# ╔═╡ 3736a094-fb57-11ea-1d39-e551aae62b1d\nmd\"\"\"\nOur model will **compare the transition frequencies of our mystery sample** to those of our two language sample. The closest match will be our detected language.\n\nThe only question left is: How do we compare two matrices? When two matrices are almost equal, but not exactly, we want to quantify their _distance_.\n\n👉 Write a function called `matrix_distance` which takes 2 matrices of the same size and finds the distance between them by:\n\n1. Subtracting corresponding elements\n2. Finding the absolute value of the difference\n3. Summing the differences\n\"\"\"\n\n# ╔═╡ 13c89272-f934-11ea-07fe-91b5d56dedf8\nfunction matrix_distance(A, B)\n\tsum(abs.(A .- B))\nend\n\n# ╔═╡ 7d60f056-f931-11ea-39ae-5fa18a955a77\ndistances = map(samples) do sample\n\tmatrix_distance(transition_frequencies(mystery_sample), transition_frequencies(sample))\nend\n\n# ╔═╡ 7d1439e6-f931-11ea-2dab-41c66a779262\ntry\n\t@assert !ismissing(distances.English)\n\t\"\"\"<h2>It looks like this text is **$(argmin(distances))**!</h2>\"\"\" |> HTML\ncatch\nend\n\n# ╔═╡ 8c7606f0-fb93-11ea-0c9c-45364892cbb8\nmd\"\"\"\nWe have written a cell that selects the language with the _smallest distance_ to the mystery language. Make sure sure that `matrix_distance` is working correctly, and [scroll up](#mystery-detect) to the mystery text to see it in action!\n\n#### Further reading\nIt turns out that the SVD of the transition matrix can mysteriously group the alphabet into vowels and consonants, without any extra information. See [this paper](http://languagelog.ldc.upenn.edu/myl/Moler1983.pdf) if you want to try it yourself! We found that removing the space from `alphabet` (to match the paper) gave better results.\n\"\"\"\n\n# ╔═╡ 82e0df62-fb54-11ea-3fff-b16c87a7d45b\nmd\"\"\"\n## **Exercise 2** - _Language generation_\n\nOur model from Exercise 1 has the property that it can easily be 'reversed' to _generate_ text. While this is useful to demonstrate its structure, the produced text is mostly meaningless: it fails to model words, let alone sentence structure.\n\nTo take our model one step further, we are going to _generalize_ what we have done so far. Instead of looking at _letter combinations_, we will model _word combinations_. And instead of analyzing the frequencies of bigrams (combinations of two letters), we are going to analyze _$n$-grams_.\n\n#### Dataset\nThis also means that we are going to need a larger dataset to train our model on: the number of English words (and their combinations) is much higher than the number of letters.\n\nWe will train our model on the novel [_Emma_ (1815), by Jane Austen](https://en.wikipedia.org/wiki/Emma_(novel)). This work is in the public domain, which means that we can download the whole book as a text file from `archive.org`. We've done the process of downloading and cleaning already, and we have split the text into word and punctuation tokens.\n\"\"\"\n\n# ╔═╡ b7601048-fb57-11ea-0754-97dc4e0623a1\nemma = let\n\traw_text = read(download(\"https://ia800303.us.archive.org/24/items/EmmaJaneAusten_753/emma_pdf_djvu.txt\"), String)\n\t\n\tfirst_words = \"Emma Woodhouse\"\n\tlast_words = \"THE END\"\n\tstart_index = findfirst(first_words, raw_text)[1]\n\tstop_index = findlast(last_words, raw_text)[end]\n\t\n\traw_text[start_index:stop_index]\nend;\n\n# ╔═╡ cc42de82-fb5a-11ea-3614-25ef961729ab\nfunction splitwords(text)\n\t# clean up whitespace\n\tcleantext = replace(text, r\"\\s+\" => \" \")\n\t\n\t# split on whitespace or other word boundaries\n\ttokens = split(cleantext, r\"(\\s|\\b)\")\nend\n\n# ╔═╡ d66fe2b2-fb5a-11ea-280f-cfb12b8296ac\nemma_words = splitwords(emma)\n\n# ╔═╡ 4ca8e04a-fb75-11ea-08cc-2fdef5b31944\nforest_words = splitwords(samples.English)\n\n# ╔═╡ 6f613cd2-fb5b-11ea-1669-cbd355677649\nmd\"\"\"\n#### Exercise 2.1 - _bigrams revisited_\n\nThe goal of the upcoming exercises is to **generalize** what we have done in Exercise 1. To keep things simple, we _split up our problem_ into smaller problems. (The solution to any computational problem.)\n\nFirst, here is a function that takes an array, and returns the array of all **neighbour pairs** from the original. For example,\n\n```julia\nbigrams([1, 2, 3, 42])\n```\ngives\n\n```julia\n[[1,2], [2,3], [3,42]]\n```\n\n(We used integers as \"words\" in this example, but our function works with any type of word.)\n\"\"\"\n\n# ╔═╡ 91e87974-fb78-11ea-3ce4-5f64e506b9d2\nfunction bigrams(words)\n\tmap(1:length(words)-1) do i\n\t\twords[i:i+1]\n\tend\nend\n\n# ╔═╡ 9f98e00e-fb78-11ea-0f6c-01206e7221d6\nbigrams([1, 2, 3, 42])\n\n# ╔═╡ d7d8cd0c-fb6a-11ea-12bf-2d1448b38162\nmd\"\"\"\n👉 Next, it's your turn to write a more general function `ngrams` that takes an array and a number $n$, and returns all **subsequences of length $n$**. For example:\n\n```julia\nngrams([1, 2, 3, 42], 3)\n```\nshould give\n\n```julia\n[[1,2,3], [2,3,42]]\n```\n\nand\n\n```julia\nngrams([1, 2, 3, 42], 2) == bigrams([1, 2, 3, 42])\n```\n\"\"\"\n\n# ╔═╡ 7be98e04-fb6b-11ea-111d-51c48f39a4e9\nfunction ngrams(words, n)\n\tmap(1:length(words) - n + 1) do i\n\t\twords[i: (i + n - 1)]\n\tend\nend\n\n# ╔═╡ c560ec86-211c-11eb-06e9-b3cc1c80e46d\n\n\n# ╔═╡ 052f822c-fb7b-11ea-382f-af4d6c2b4fdb\nngrams([1, 2, 3, 42], 3)\n\n# ╔═╡ 067f33fc-fb7b-11ea-352e-956c8727c79f\nngrams(forest_words, 4)\n\n# ╔═╡ 7b10f074-fb7c-11ea-20f0-034ddff41bc3\nmd\"\"\"\nIf you are stuck, you can write `ngrams(words, n) = bigrams(words)` (ignoring the true value of $n$), and continue with the other exercises.\n\n#### Exercise 2.2 - _frequency matrix revisisted_\nIn Exercise 1, we use a 2D array to store the bigram frequencies, where each column or row corresponds to a character from the alphabet. If we use trigrams, we could store the frequencies in a 3D array, and so on. \n\nHowever, when counting words instead of letters, we run into a problem. A 3D array with one row, column and layer per word has too many elements to store on our computer.\n\"\"\"\n\n# ╔═╡ 24ae5da0-fb7e-11ea-3480-8bb7b649abd5\nmd\"\"\"\n_Emma_ consists of $(\n\tlength(Set(emma_words))\n) unique words. This means that there are $(\n\tInt(floor(length(Set(emma_words))^3 / 10^9))\n) billion possible trigrams - that's too much!\n\"\"\"\n\n# ╔═╡ 47836744-fb7e-11ea-2305-3fa5819dc154\nmd\"\"\"\n$(html\"<br>\")\n\nAlthough the frequency array would be very large, most entries are zero. For example, _\"Emma\"_ is a common word, but _\"Emma Emma Emma\"_ does not occur in the novel. This _sparsity_ of non-zero entries can be used to **store the same information in a more efficient structure**. \n\nJulia's [`SparseArrays.jl` package](https://docs.julialang.org/en/v1/stdlib/SparseArrays/index.html) might sound like a logical choice, but these arrays only support 1D and 2D types, and we also want to directly index using strings, not just integers. So instead, we will use `Dict`, the dictionary type.\n\"\"\"\n\n# ╔═╡ df4fc31c-fb81-11ea-37b3-db282b36f5ef\nhealthy = Dict(\"fruits\" => [\"🍎\", \"🍊\"], \"vegetables\" => [\"🌽\", \"🎃\", \"🍕\"])\n\n# ╔═╡ c83b1770-fb82-11ea-20a6-3d3a09606c62\nhealthy[\"fruits\"]\n\n# ╔═╡ 52970ac4-fb82-11ea-3040-8bd0590348d2\nmd\"\"\"\n(Did you notice something funny? The dictionary is _unordered_, this is why the entries were printed in reverse from the definition.)\n\nYou can dynamically add or change values of a `Dict` by assigning to `my_dict[key]`. You can check whether a key already exists using `haskey(my_dict, key)`.\n\n👉 Use these two techniques to write a function `word_counts` that takes an array of words, and returns a `Dict` with entries `word => number_of_occurences`.\n\nFor example:\n```julia\nword_counts([\"to\", \"be\", \"or\", \"not\", \"to\", \"be\"])\n```\nshould return\n```julia\nDict(\n\t\"to\" => 2, \n\t\"be\" => 2, \n\t\"or\" => 1, \n\t\"not\" => 1\n)\n```\n\"\"\"\n\n# ╔═╡ 8ce3b312-fb82-11ea-200c-8d5b12f03eea\nfunction word_counts(words::Vector)\n\tcounts = Dict()\n\tfor word ∈ words\n\t\tif haskey(counts, word)\n\t\t\tcounts[word] = counts[word] + 1\n\t\telse\n\t\t\tcounts[word] = 1\n\t\tend\n\tend\n\treturn counts\nend\n\n# ╔═╡ a2214e50-fb83-11ea-3580-210f12d44182\nword_counts([\"to\", \"be\", \"or\", \"not\", \"to\", \"be\"])\n\n# ╔═╡ 808abf6e-fb84-11ea-0785-2fc3f1c4a09f\nmd\"\"\"\nHow many times does `\"Emma\"` occur in the book?\n\"\"\"\n\n# ╔═╡ 953363dc-fb84-11ea-1128-ebdfaf5160ee\nemma_count = word_counts(emma_words)[\"Emma\"]\n\n# ╔═╡ 294b6f50-fb84-11ea-1382-03e9ab029a2d\nmd\"\"\"\nGreat! Let's get back to our ngrams. For the purpose of generating text, we are going to store a _completions cache_. This is a dictionary where the keys are $(n-1)$-grams, and the values are all found words that complete it to an $n$-gram. Let's look at an example:\n\n```julia\nlet\n\ttrigrams = ngrams(split(\"to be or not to be that is the question\", \" \"), 3)\n\tcache = completions_cache(trigrams)\n\tcache == Dict(\n\t\t[\"to\", \"be\"] => [\"or\", \"that\"],\n\t\t[\"be\", \"or\"] => [\"not\"],\n\t\t[\"or\", \"not\"] => [\"to\"],\n\t\t...\n\t)\nend\n```\n\nSo for trigrams, our keys are the first $2$ words of each trigram, and the values are arrays containing every third word of those trigrams.\n\nIf the same ngram occurs multiple times (e.g. \"said Emma laughing\"), then the last word (\"laughing\") should also be stored multiple times. This will allow us to generate trigrams with the same frequencies as the original text.\n\n👉 Write the function `completions_cache`, which takes an array of ngrams (i.e. an array of arrays of words, like the result of your `ngram` function), and returns a dictionary like described above.\n\"\"\"\n\n# ╔═╡ b726f824-fb5e-11ea-328e-03a30544037f\nfunction completions_cache(grams)\n\tcache = Dict()\n\tfor gram ∈ grams\n \tL = length(gram)\n\t\tkey = gram[1:L-1]\n\t\tval = gram[L]\n\t\tif haskey(cache, key)\n\t\t\tpush!(cache[key], val)\n\t\telse\n\t\t\tcache[key] = [val]\n\t\tend\n\tend\n\tcache\nend\n\n# ╔═╡ 18355314-fb86-11ea-0738-3544e2e3e816\nlet\n\ttrigrams = ngrams(split(\"to be or not to be or is the question\", \" \"), 3)\n\tcompletions_cache(trigrams)\nend\n\n# ╔═╡ 3d105742-fb8d-11ea-09b0-cd2e77efd15c\nmd\"\"\"\n#### Exercise 2.4 - _write a novel_\n\nWe have everything we need to generate our own novel! The final step is to sample random ngrams, in a way that each next ngram overlaps with the previous one. We've done this in the function `generate_from_ngrams` below - feel free to look through the code, or to implement your own version.\n\"\"\"\n\n# ╔═╡ a72fcf5a-fb62-11ea-1dcc-11451d23c085\n\"\"\"\n\tgenerate_from_ngrams(grams, num_words)\n\nGiven an array of ngrams (i.e. an array of arrays of words), generate a sequence of `num_words` words by sampling random ngrams.\n\"\"\"\nfunction generate_from_ngrams(grams, num_words)\n\tn = length(first(grams))\n\tcache = completions_cache(grams)\n\t\n\t# we need to start the sequence with at least n-1 words.\n\t# a simple way to do so is to pick a random ngram!\n\tsequence = [rand(grams)...]\n\t\n\t# we iteratively add one more word at a time\n\tfor i ∈ n+1:num_words\n\t\t# the previous n-1 words\n\t\ttail = sequence[end-(n-2):end]\n\t\t\n\t\t# possible next words\n\t\tcompletions = cache[tail]\n\t\t\n\t\tchoice = rand(completions)\n\t\tpush!(sequence, choice)\n\tend\n\tsequence\nend\n\n# ╔═╡ f83991c0-fb7c-11ea-0e6f-1f80709d00c1\n\"Compute the ngrams of an array of words, but add the first n-1 at the end, to ensure that every ngram ends in the the beginning of another ngram.\"\nfunction ngrams_circular(words, n)\n\tngrams([words..., words[1:n-1]...], n)\nend\n\n# ╔═╡ abe2b862-fb69-11ea-08d9-ebd4ba3437d5\ncompletions_cache(ngrams_circular(forest_words, 3))\n\n# ╔═╡ 4b27a89a-fb8d-11ea-010b-671eba69364e\n\"\"\"\n\tgenerate(source_text::AbstractString, num_token; n=3, use_words=true)\n\nGiven a source text, generate a `String` that \"looks like\" the original text by satisfying the same ngram frequency distribution as the original.\n\"\"\"\nfunction generate(source_text::AbstractString, s; n=3, use_words=true)\n\tpreprocess = if use_words\n\t\tsplitwords\n\telse\n\t\tcollect\n\tend\n\t\n\twords = preprocess(source_text)\n\tif length(words) < n\n\t\t\"\"\n\telse\n\t\tgrams = ngrams_circular(words, n)\n\t\tresult = generate_from_ngrams(grams, s)\n\t\tif use_words\n\t\t\tjoin(result, \" \")\n\t\telse\n\t\t\tString(result)\n\t\tend\n\tend\nend\n\n# ╔═╡ d7b7a14a-fb90-11ea-3e2b-2fd8f379b4d8\nmd\"\n#### Interactive demo\n\nEnter your own text in the box below, and use that as training data to generate anything!\n\"\n\n# ╔═╡ 1939dbea-fb63-11ea-0bc2-2d06b2d4b26c\n@bind generate_demo_sample TextField((50,5), default=samples.English)\n\n# ╔═╡ 70169682-fb8c-11ea-27c0-2dad2ff3080f\nmd\"\"\"Using $(@bind generate_sample_n_letters NumberField(1:5))grams for characters\"\"\"\n\n# ╔═╡ 402562b0-fb63-11ea-0769-375572cc47a8\nmd\"\"\"Using $(@bind generate_sample_n_words NumberField(1:5))grams for words\"\"\"\n\n# ╔═╡ 2521bac8-fb8f-11ea-04a4-0b077d77529e\nmd\"\"\"\n### Automatic Jane Austen\n\nUncomment the cell below to generate some Jane Austen text:\n\"\"\"\n\n# ╔═╡ cc07f576-fbf3-11ea-2c6f-0be63b9356fc\nif student.name == \"Jazzy Doe\"\n\tmd\"\"\"\n\t!!! danger \"Before you submit\"\n\t Remember to fill in your **name** and **Kerberos ID** at the top of this notebook.\n\t\"\"\"\nend\n\n# ╔═╡ 6b4d6584-f3be-11ea-131d-e5bdefcc791b\nmd\"## Function library\n\nJust some helper functions used in the notebook.\"\n\n# ╔═╡ 54b1e236-fb53-11ea-3769-b382ef8b25d6\nfunction Quote(text::AbstractString)\n\ttext |> Markdown.Paragraph |> Markdown.BlockQuote |> Markdown.MD\nend\n\n# ╔═╡ b3dad856-f9a7-11ea-1552-f7435f1cb605\nString(rand(alphabet, 400)) |> Quote\n\n# ╔═╡ be55507c-f9a7-11ea-189c-4ffe8377212e\nif sample_freqs !== missing\n\tString([rand_sample_letter(sample_freqs) for _ in 1:400]) |> Quote\nend\n\n# ╔═╡ 46c905d8-f9b0-11ea-36ed-0515e8ed2621\nString(rand(alphabet, 400)) |> Quote\n\n# ╔═╡ 489b03d4-f9b0-11ea-1de0-11d4fe4e7c69\nString([rand_sample_letter(letter_frequencies(ex23_sample)) for _ in 1:400]) |> Quote\n\n# ╔═╡ fd202410-f936-11ea-1ad6-b3629556b3e0\nsample_text(transition_frequencies(clean(ex23_sample)), 400) |> Quote\n\n# ╔═╡ b5dff8b8-fb6c-11ea-10fc-37d2a9adae8c\ngenerate(\n\tgenerate_demo_sample, 400; \n\tn=generate_sample_n_letters, \n\tuse_words=false\n) |> Quote\n\n# ╔═╡ ee8c5808-fb5f-11ea-19a1-3d58217f34dc\ngenerate(\n\tgenerate_demo_sample, 100; \n\tn=generate_sample_n_words, \n\tuse_words=true\n) |> Quote\n\n# ╔═╡ 49b69dc2-fb8f-11ea-39af-030b5c5053c3\ngenerate(emma, 100; n=4) |> Quote\n\n# ╔═╡ ddef9c94-fb96-11ea-1f17-f173a4ff4d89\nfunction compimg(img, labels=[c*d for c in replace(alphabet, ' ' => \"_\"), d in replace(alphabet, ' ' => \"_\")])\n\txmax, ymax = size(img)\n\txmin, ymin = 0, 0\n\tarr = [(j-1, i-1) for i=1:ymax, j=1:xmax]\n\n\tcompose(context(units=UnitBox(xmin, ymin, xmax, ymax)),\n\t\tfill(vec(img)),\n\t\tcompose(context(),\n\t\t\tfill(\"white\"), font(\"monospace\"), \n\t\t\ttext(first.(arr) .+ .1, last.(arr) .+ 0.6, labels)),\n\t\trectangle(\n\t\t\tfirst.(arr),\n\t\t\tlast.(arr),\n\t\t\tfill(1.0, length(arr)),\n\t\t\tfill(1.0, length(arr))))\nend\n\n# ╔═╡ b7803a28-fb96-11ea-3e30-d98eb322d19a\nfunction show_pair_frequencies(A)\n\timshow = let\n\t\tto_rgb(x) = RGB(0.36x, 0.82x, 0.8x)\n\t\tto_rgb.(A ./ maximum(abs.(A)))\n\tend\n\tcompimg(imshow)\nend\n\n# ╔═╡ ace3dc76-f9ae-11ea-2bee-3d0bfa57cfbc\nshow_pair_frequencies(transition_frequencies(first_sample))\n\n# ╔═╡ ffc17f40-f380-11ea-30ee-0fe8563c0eb1\nhint(text) = Markdown.MD(Markdown.Admonition(\"hint\", \"Hint\", [text]))\n\n# ╔═╡ 7df7ab82-f9ad-11ea-2243-21685d660d71\nhint(md\"You can answer this question without writing any code: have a look at the values of `sample_freqs`.\")\n\n# ╔═╡ e467c1c6-fbf2-11ea-0d20-f5798237c0a6\nhint(md\"Start out with the same code as `bigrams`, and use the Julia documentation to learn how it works. How can we generalize the `bigram` function into the `ngram` function? It might help to do this on paper first.\")\n\n# ╔═╡ ffc40ab2-f380-11ea-2136-63542ff0f386\nalmost(text) = Markdown.MD(Markdown.Admonition(\"warning\", \"Almost there!\", [text]))\n\n# ╔═╡ ffceaed6-f380-11ea-3c63-8132d270b83f\nstill_missing(text=md\"Replace `missing` with your answer.\") = Markdown.MD(Markdown.Admonition(\"warning\", \"Here we go!\", [text]))\n\n# ╔═╡ ffde44ae-f380-11ea-29fb-2dfcc9cda8b4\nkeep_working(text=md\"The answer is not quite right.\") = Markdown.MD(Markdown.Admonition(\"danger\", \"Keep working on it!\", [text]))\n\n# ╔═╡ ffe326e0-f380-11ea-3619-61dd0592d409\nyays = [md\"Fantastic!\", md\"Splendid!\", md\"Great!\", md\"Yay ❤\", md\"Great! 🎉\", md\"Well done!\", md\"Keep it up!\", md\"Good job!\", md\"Awesome!\", md\"You got the right answer!\", md\"Let's move on to the next section.\"]\n\n# ╔═╡ fff5aedc-f380-11ea-2a08-99c230f8fa32\ncorrect(text=rand(yays)) = Markdown.MD(Markdown.Admonition(\"correct\", \"Got it!\", [text]))\n\n# ╔═╡ 954fc466-fb7b-11ea-2724-1f938c6b93c6\nlet\n\toutput = ngrams([1, 2, 3, 42], 2)\n\n\tif output isa Missing\n\t\tstill_missing()\n\telseif !(output isa Vector{<:Vector})\n\t\tkeep_working(md\"Make sure that `ngrams` returns an array of arrays.\")\n\telseif output == [[1,2], [2,3], [3,42]]\n\t\tif ngrams([1,2,3], 1) == [[1],[2],[3]]\n\t\t\tif ngrams([1,2,3], 3) == [[1,2,3]]\n\t\t\t\tif ngrams([\"a\"],1) == [[\"a\"]]\n\t\t\t\t\tcorrect()\n\t\t\t\telse\n\t\t\t\t\tkeep_working(md\"`ngrams` should work with any type, not just integers!\")\n\t\t\t\tend\n\t\t\telse\n\t\t\t\tkeep_working(md\"`ngrams(x, 3)` did not give a correct result.\")\n\t\t\tend\n\t\telse\n\t\t\tkeep_working(md\"`ngrams(x, 1)` did not give a correct result.\")\t\t\t\n\t\tend\n\telse\n\t\tkeep_working(md\"`ngrams(x, 2)` did not give the correct bigrams. Start out with the same code as `bigrams`.\")\n\tend\nend\n\n# ╔═╡ a9ffff9a-fb83-11ea-1efd-2fc15538e52f\nlet\n\toutput = word_counts([\"to\", \"be\", \"or\", \"not\", \"to\", \"be\"])\n\n\tif output === nothing\n\t\tkeep_working(md\"Did you forget to write `return`?\")\n\telseif output == Dict()\n\t\tstill_missing(md\"Write your function `word_counts` above.\")\n\telseif !(output isa Dict)\n\t\tkeep_working(md\"Make sure that `word_counts` returns a `Dict`.\")\n\telseif output == Dict(\"to\" => 2, \"be\" => 2, \"or\" => 1, \"not\" => 1)\n\t\tcorrect()\n\telse\n\t\tkeep_working()\n\tend\nend\n\n# ╔═╡ 00026442-f381-11ea-2b41-bde1fff66011\nnot_defined(variable_name) = Markdown.MD(Markdown.Admonition(\"danger\", \"Oopsie!\", [md\"Make sure that you define a variable called **$(Markdown.Code(string(variable_name)))**\"]))\n\n# ╔═╡ 6fe693c8-f9a1-11ea-1983-f159131880e9\nif !@isdefined(messy_sentence_1)\n\tnot_defined(:messy_sentence_1)\nelseif !@isdefined(cleaned_sentence_1)\n\tnot_defined(:cleaned_sentence_1)\nelse\n\tif cleaned_sentence_1 isa Missing\n\t\tstill_missing()\n\telseif cleaned_sentence_1 isa Vector{Char}\n\t\tkeep_working(md\"Use `String(x)` to turn an array of characters `x` into a `String`.\")\n\telseif cleaned_sentence_1 == filter(isinalphabet, messy_sentence_1)\n\t\tcorrect()\n\telse\n\t\tkeep_working()\n\tend\nend\n\n# ╔═╡ cee0f984-f9a0-11ea-2c3c-53fe26156ea4\nif !@isdefined(messy_sentence_2)\n\tnot_defined(:messy_sentence_2)\nelseif !@isdefined(cleaned_sentence_2)\n\tnot_defined(:cleaned_sentence_2)\nelse\n\tif cleaned_sentence_2 isa Missing\n\t\tstill_missing()\n\telseif cleaned_sentence_2 isa Vector{Char}\n\t\tkeep_working(md\"Use `String(x)` to turn an array of characters `x` into a `String`.\")\n\telseif cleaned_sentence_2 == filter(isinalphabet, lowercase(messy_sentence_2))\n\t\tcorrect()\n\telse\n\t\tkeep_working()\n\tend\nend\n\n# ╔═╡ ddfb1e1c-f9a1-11ea-3625-f1170272e96a\nif !@isdefined(clean)\n\tnot_defined(:clean)\nelse\n\tlet\n\t\tinput = \"Aè !!! x1\"\n\t\toutput = clean(input)\n\t\t\n\t\t\n\t\tif output isa Missing\n\t\t\tstill_missing()\n\t\telseif output isa Vector{Char}\n\t\t\tkeep_working(md\"Use `String(x)` to turn an array of characters `x` into a `String`.\")\n\t\telseif output == \"ae x\"\n\t\t\tcorrect()\n\t\telse\n\t\t\tkeep_working()\n\t\tend\n\tend\nend\n\n# ╔═╡ 95b81778-f9a5-11ea-3f51-019430bc8fa8\nif !@isdefined(unused_letters)\n\tnot_defined(:unused_letters)\nelse\n\tif sample_freqs === missing\n\t\tmd\"\"\"\n\t\t!!! warning \"Oopsie!\"\n\t\t You need to complete the previous exercises first.\n\t\t\"\"\"\n\telseif unused_letters isa Missing\n\t\tstill_missing()\n\telseif unused_letters isa String\n\t\tkeep_working(md\"Use `collect` to turn a string into an array of characters.\")\n\telseif Set(index_of_letter.(unused_letters)) == Set(findall(isequal(0.0), sample_freqs))\n\t\tcorrect()\n\telse\n\t\tkeep_working()\n\tend\nend\n\n# ╔═╡ 489fe282-f931-11ea-3dcb-35d4f2ac8b40\nif !@isdefined(th_frequency)\n\tnot_defined(:th_frequency)\nelseif !@isdefined(ht_frequency)\n\tnot_defined(:ht_frequency)\nelse\n\tif th_frequency isa Missing || ht_frequency isa Missing\n\t\tstill_missing()\n\telseif th_frequency < ht_frequency\n\t\tkeep_working(md\"Looks like your answers should be flipped. Which combination is more frequent in English?\")\n\telseif th_frequency == sample_freq_matrix[index_of_letter('t'), index_of_letter('h')] && ht_frequency == sample_freq_matrix[index_of_letter('h'), index_of_letter('t')] \n\t\tcorrect()\n\telse\n\t\tkeep_working()\n\tend\nend\n\n# ╔═╡ 671525cc-f930-11ea-0e71-df9d4aae1c05\nif !@isdefined(double_letters)\n\tnot_defined(:double_letters)\nend\n\n# ╔═╡ a5fbba46-f931-11ea-33e1-054be53d986c\nif !@isdefined(most_likely_to_follow_w)\n\tnot_defined(:most_likely_to_follow_w)\nend\n\n# ╔═╡ ba695f6a-f931-11ea-0fbb-c3ef1374270e\nif !@isdefined(most_likely_to_precede_w)\n\tnot_defined(:most_likely_to_precede_w)\nend\n\n# ╔═╡ b09f5512-fb58-11ea-2527-31bea4cee823\nif !@isdefined(matrix_distance)\n\tnot_defined(:matrix_distance)\nelse\n\ttry\n\tlet\n\t\tA = rand(Float64, (5,4))\n\t\tB = rand(Float64, (5,4))\n\t\t\n\t\toutput = matrix_distance(A,B)\n\t\t\n\t\tif output isa Missing\n\t\t\tstill_missing()\n\t\telseif !(output isa Number)\n\t\t\tkeep_working(md\"Make sure that `matrix_distance` returns a nunmber.\")\n\t\telseif output == 0.0\n\t\t\tkeep_working(md\"Two different matrices should have non-zero distance.\")\n\t\telse\n\t\t\tif matrix_distance(A,B) < 0 || matrix_distance(B,A) < 0\n\t\t\t\tkeep_working(md\"The distance between two matrices should always be positive.\")\n\t\t\telseif matrix_distance(A,A) != 0\n\t\t\t\talmost(md\"The distance between two identical matrices should be zero.\")\n\t\t\telseif matrix_distance([1 -1], [0 0]) == 0.0\n\t\t\t\talmost(md\"`matrix_distance([1 -1], [0 0])` should not be zero.\")\n\t\t\telse\n\t\t\t\tcorrect()\n\t\t\tend\n\t\tend\n\tend\n\tcatch\n\t\tkeep_working(md\"The function errored.\")\n\tend\nend\n\n# ╔═╡ 00115b6e-f381-11ea-0bc6-61ca119cb628\nbigbreak = html\"<br><br><br><br><br>\";\n\n# ╔═╡ c086bd1e-f384-11ea-3b26-2da9e24360ca\nbigbreak\n\n# ╔═╡ eaa8c79e-f9a2-11ea-323f-8bb2bd36e11c\nmd\"\"\"\n$(bigbreak)\n#### Exercise 1.2 - _Letter frequencies_\n\nWe are going to count the _frequency_ of each letter in this sample, after applying your `clean` function. Can you guess which character is most frequent?\n\"\"\"\n\n# ╔═╡ dcffd7d2-f9a6-11ea-2230-b1afaecfdd54\nmd\"\"\"\n$(bigbreak)\nNow that we know the frequencies of letters in English, we can generate random text that already looks closer to English!\n\n**Random letters from the alphabet:**\n\"\"\"\n\n# ╔═╡ 77623f3e-f9a9-11ea-2f46-ff07bd27cd5f\nmd\"\"\"\n$(bigbreak)\n#### Exercise 1.3 - _Transition frequencies_\nIn the previous exercise we computed the frequency of each letter in the sample by _counting_ their occurences, and then dividing by the total number of counts.\n\nIn this exercise, we are going to count _letter transitions_, such as `aa`, `as`, `rt`, `yy`. Two letters might both be common, like `a` and `e`, but their combination, `ae`, is uncommon in English. \n\nTo quantify this observation, we will do the same as in our last exercise: we count occurences in a _sample text_, to create the **transition frequency matrix**.\n\"\"\"\n\n# ╔═╡ d3d7bd9c-f9af-11ea-1570-75856615eb5d\nbigbreak\n\n# ╔═╡ 6718d26c-f9b0-11ea-1f5a-0f22f7ddffe9\nmd\"\"\"\n$(bigbreak)\n\n#### Exercise 1.4 - _Language detection_\n\"\"\"\n\n# ╔═╡ 568f0d3a-fb54-11ea-0f77-171718ef12a5\nbigbreak\n\n# ╔═╡ 7f341c4e-fb54-11ea-1919-d5421d7a2c75\nbigbreak\n\n# ╔═╡ Cell order:\n# ╟─e6b6760a-f37f-11ea-3ae1-65443ef5a81a\n# ╟─ec66314e-f37f-11ea-0af4-31da0584e881\n# ╟─85cfbd10-f384-11ea-31dc-b5693630a4c5\n# ╠═33e43c7c-f381-11ea-3abc-c942327456b1\n# ╟─938185ec-f384-11ea-21dc-b56b7469f798\n# ╠═86e1ee96-f314-11ea-03f6-0f549b79e7c9\n# ╠═a4937996-f314-11ea-2ff9-615c888afaa8\n# ╟─b49a21a6-f381-11ea-1a98-7f144c55c9b7\n# ╟─c086bd1e-f384-11ea-3b26-2da9e24360ca\n# ╟─6f9df800-f92d-11ea-2d49-c1aaabd2d012\n# ╠═b61722cc-f98f-11ea-22ae-d755f61f78c3\n# ╟─f457ad44-f990-11ea-0e2d-2bb7627716a8\n# ╠═4efc051e-f92e-11ea-080e-bde6b8f9295a\n# ╟─38d1ace8-f991-11ea-0b5f-ed7bd08edde5\n# ╠═ddf272c8-f990-11ea-2135-7bf1a6dca0b7\n# ╟─3cc688d2-f996-11ea-2a6f-0b4c7a5b74c2\n# ╟─d67034d0-f92d-11ea-31c2-f7a38ebb412f\n# ╟─a094e2ac-f92d-11ea-141a-3566552dd839\n# ╠═27c9a7f4-f996-11ea-1e46-19e3fc840ad9\n# ╟─f2a4edfa-f996-11ea-1a24-1ba78fd92233\n# ╟─5c74a052-f92e-11ea-2c5b-0f1a3a14e313\n# ╠═dcc4156c-f997-11ea-3e6f-057cd080d9db\n# ╟─129fbcfe-f998-11ea-1c96-0fd3ccd2dcf8\n# ╠═3a5ee698-f998-11ea-0452-19b70ed11a1d\n# ╠═75694166-f998-11ea-0428-c96e1113e2a0\n# ╟─6fe693c8-f9a1-11ea-1983-f159131880e9\n# ╟─05f0182c-f999-11ea-0a52-3d46c65a049e\n# ╟─98266882-f998-11ea-3270-4339fb502bc7\n# ╠═d3c98450-f998-11ea-3caf-895183af926b\n# ╠═d3a4820e-f998-11ea-2a5c-1f37e2a6dd0a\n# ╟─cee0f984-f9a0-11ea-2c3c-53fe26156ea4\n# ╟─aad659b8-f998-11ea-153e-3dae9514bfeb\n# ╠═d236b51e-f997-11ea-0c55-abb11eb35f4d\n# ╠═a56724b6-f9a0-11ea-18f2-991e0382eccf\n# ╟─24860970-fc48-11ea-0009-cddee695772c\n# ╟─734851c6-f92d-11ea-130d-bf2a69e89255\n# ╟─8d3bc9ea-f9a1-11ea-1508-8da4b7674629\n# ╠═4affa858-f92e-11ea-3ece-258897c37e51\n# ╠═e00d521a-f992-11ea-11e0-e9da8255b23b\n# ╟─ddfb1e1c-f9a1-11ea-3625-f1170272e96a\n# ╟─eaa8c79e-f9a2-11ea-323f-8bb2bd36e11c\n# ╠═2680b506-f9a3-11ea-0849-3989de27dd9f\n# ╟─571d28d6-f960-11ea-1b2e-d5977ecbbb11\n# ╠═6a64ab12-f960-11ea-0d92-5b88943cdb1a\n# ╟─603741c2-f9a4-11ea-37ce-1b36ecc83f45\n# ╟─b3de6260-f9a4-11ea-1bae-9153a92c3fe5\n# ╠═a6c36bd6-f9a4-11ea-1aba-f75cecc90320\n# ╟─6d3f9dae-f9a5-11ea-3228-d147435e266d\n# ╠═92bf9fd2-f9a5-11ea-25c7-5966e44db6c6\n# ╟─95b81778-f9a5-11ea-3f51-019430bc8fa8\n# ╟─7df7ab82-f9ad-11ea-2243-21685d660d71\n# ╟─dcffd7d2-f9a6-11ea-2230-b1afaecfdd54\n# ╟─b3dad856-f9a7-11ea-1552-f7435f1cb605\n# ╟─01215e9a-f9a9-11ea-363b-67392741c8d4\n# ╟─be55507c-f9a7-11ea-189c-4ffe8377212e\n# ╟─8ae13cf0-f9a8-11ea-3919-a735c4ed9e7f\n# ╟─343d63c2-fb58-11ea-0cce-efe1afe070c2\n# ╟─b5b8dd18-f938-11ea-157b-53b145357fd1\n# ╟─0e872a6c-f937-11ea-125e-37958713a495\n# ╟─77623f3e-f9a9-11ea-2f46-ff07bd27cd5f\n# ╠═fbb7c04e-f92d-11ea-0b81-0be20da242c8\n# ╠═80118bf8-f931-11ea-34f3-b7828113ffd8\n# ╠═7f4f6ce4-f931-11ea-15a4-b3bec6a7e8b6\n# ╠═d40034f6-f9ab-11ea-3f65-7ffd1256ae9d\n# ╟─689ed82a-f9ae-11ea-159c-331ff6660a75\n# ╠═ace3dc76-f9ae-11ea-2bee-3d0bfa57cfbc\n# ╟─0b67789c-f931-11ea-113c-35e5edafcbbf\n# ╠═6896fef8-f9af-11ea-0065-816a70ba9670\n# ╟─39152104-fc49-11ea-04dd-bb34e3600f2f\n# ╟─e91c6fd8-f930-11ea-01ac-476bbde79079\n# ╠═1b4c0c28-f9ab-11ea-03a6-69f69f7f90ed\n# ╟─1f94e0a2-f9ab-11ea-1347-7dd906ebb09d\n# ╠═41b2df7c-f931-11ea-112e-ede3b16f357a\n# ╟─489fe282-f931-11ea-3dcb-35d4f2ac8b40\n# ╟─1dd1e2f4-f930-11ea-312c-5ff9e109c7f6\n# ╠═65c92cac-f930-11ea-20b1-6b8f45b3f262\n# ╟─671525cc-f930-11ea-0e71-df9d4aae1c05\n# ╟─4582ebf4-f930-11ea-03b2-bf4da1a8f8df\n# ╠═6d8f47d2-2108-11eb-105e-63c5f7d74c6e\n# ╠═b5fcd572-2108-11eb-3581-b18f259b42f6\n# ╠═7898b76a-f930-11ea-2b7e-8126ec2b8ffd\n# ╟─a5fbba46-f931-11ea-33e1-054be53d986c\n# ╟─458cd100-f930-11ea-24b8-41a49f6596a0\n# ╠═bc401bee-f931-11ea-09cc-c5efe2f11194\n# ╟─ba695f6a-f931-11ea-0fbb-c3ef1374270e\n# ╠═45c20988-f930-11ea-1d12-b782d2c01c11\n# ╠═432276c6-2109-11eb-04e8-0bb0716eb660\n# ╠═cc62929e-f9af-11ea-06b9-439ac08dcb52\n# ╟─d3d7bd9c-f9af-11ea-1570-75856615eb5d\n# ╟─2f8dedfc-fb98-11ea-23d7-2159bdb6a299\n# ╟─b7446f34-f9b1-11ea-0f39-a3c17ba740e5\n# ╟─4f97b572-f9b0-11ea-0a99-87af0797bf28\n# ╟─46c905d8-f9b0-11ea-36ed-0515e8ed2621\n# ╟─4e8d327e-f9b0-11ea-3f16-c178d96d07d9\n# ╟─489b03d4-f9b0-11ea-1de0-11d4fe4e7c69\n# ╟─d83f8bbc-f9af-11ea-2392-c90e28e96c65\n# ╟─fd202410-f936-11ea-1ad6-b3629556b3e0\n# ╟─0e465160-f937-11ea-0ebb-b7e02d71e8a8\n# ╟─6718d26c-f9b0-11ea-1f5a-0f22f7ddffe9\n# ╟─141af892-f933-11ea-1e5f-154167642809\n# ╟─7eed9dde-f931-11ea-38b0-db6bfcc1b558\n# ╟─7e3282e2-f931-11ea-272f-d90779264456\n# ╟─7d1439e6-f931-11ea-2dab-41c66a779262\n# ╠═7df55e6c-f931-11ea-33b8-fdc3be0b6cfa\n# ╟─292e0384-fb57-11ea-0238-0fbe416fc976\n# ╠═7dabee08-f931-11ea-0cb2-c7d5afd21551\n# ╟─3736a094-fb57-11ea-1d39-e551aae62b1d\n# ╠═13c89272-f934-11ea-07fe-91b5d56dedf8\n# ╟─7d60f056-f931-11ea-39ae-5fa18a955a77\n# ╟─b09f5512-fb58-11ea-2527-31bea4cee823\n# ╟─8c7606f0-fb93-11ea-0c9c-45364892cbb8\n# ╟─568f0d3a-fb54-11ea-0f77-171718ef12a5\n# ╟─82e0df62-fb54-11ea-3fff-b16c87a7d45b\n# ╠═b7601048-fb57-11ea-0754-97dc4e0623a1\n# ╟─cc42de82-fb5a-11ea-3614-25ef961729ab\n# ╠═d66fe2b2-fb5a-11ea-280f-cfb12b8296ac\n# ╠═4ca8e04a-fb75-11ea-08cc-2fdef5b31944\n# ╟─6f613cd2-fb5b-11ea-1669-cbd355677649\n# ╠═91e87974-fb78-11ea-3ce4-5f64e506b9d2\n# ╠═9f98e00e-fb78-11ea-0f6c-01206e7221d6\n# ╟─d7d8cd0c-fb6a-11ea-12bf-2d1448b38162\n# ╠═7be98e04-fb6b-11ea-111d-51c48f39a4e9\n# ╠═c560ec86-211c-11eb-06e9-b3cc1c80e46d\n# ╠═052f822c-fb7b-11ea-382f-af4d6c2b4fdb\n# ╠═067f33fc-fb7b-11ea-352e-956c8727c79f\n# ╟─954fc466-fb7b-11ea-2724-1f938c6b93c6\n# ╟─e467c1c6-fbf2-11ea-0d20-f5798237c0a6\n# ╟─7b10f074-fb7c-11ea-20f0-034ddff41bc3\n# ╟─24ae5da0-fb7e-11ea-3480-8bb7b649abd5\n# ╟─47836744-fb7e-11ea-2305-3fa5819dc154\n# ╠═df4fc31c-fb81-11ea-37b3-db282b36f5ef\n# ╠═c83b1770-fb82-11ea-20a6-3d3a09606c62\n# ╟─52970ac4-fb82-11ea-3040-8bd0590348d2\n# ╠═8ce3b312-fb82-11ea-200c-8d5b12f03eea\n# ╠═a2214e50-fb83-11ea-3580-210f12d44182\n# ╟─a9ffff9a-fb83-11ea-1efd-2fc15538e52f\n# ╟─808abf6e-fb84-11ea-0785-2fc3f1c4a09f\n# ╠═953363dc-fb84-11ea-1128-ebdfaf5160ee\n# ╟─294b6f50-fb84-11ea-1382-03e9ab029a2d\n# ╠═b726f824-fb5e-11ea-328e-03a30544037f\n# ╠═18355314-fb86-11ea-0738-3544e2e3e816\n# ╠═abe2b862-fb69-11ea-08d9-ebd4ba3437d5\n# ╟─3d105742-fb8d-11ea-09b0-cd2e77efd15c\n# ╟─a72fcf5a-fb62-11ea-1dcc-11451d23c085\n# ╟─f83991c0-fb7c-11ea-0e6f-1f80709d00c1\n# ╟─4b27a89a-fb8d-11ea-010b-671eba69364e\n# ╟─d7b7a14a-fb90-11ea-3e2b-2fd8f379b4d8\n# ╟─1939dbea-fb63-11ea-0bc2-2d06b2d4b26c\n# ╟─70169682-fb8c-11ea-27c0-2dad2ff3080f\n# ╟─b5dff8b8-fb6c-11ea-10fc-37d2a9adae8c\n# ╟─402562b0-fb63-11ea-0769-375572cc47a8\n# ╟─ee8c5808-fb5f-11ea-19a1-3d58217f34dc\n# ╟─2521bac8-fb8f-11ea-04a4-0b077d77529e\n# ╠═49b69dc2-fb8f-11ea-39af-030b5c5053c3\n# ╟─7f341c4e-fb54-11ea-1919-d5421d7a2c75\n# ╟─cc07f576-fbf3-11ea-2c6f-0be63b9356fc\n# ╟─6b4d6584-f3be-11ea-131d-e5bdefcc791b\n# ╟─54b1e236-fb53-11ea-3769-b382ef8b25d6\n# ╟─b7803a28-fb96-11ea-3e30-d98eb322d19a\n# ╟─ddef9c94-fb96-11ea-1f17-f173a4ff4d89\n# ╟─ffc17f40-f380-11ea-30ee-0fe8563c0eb1\n# ╟─ffc40ab2-f380-11ea-2136-63542ff0f386\n# ╟─ffceaed6-f380-11ea-3c63-8132d270b83f\n# ╟─ffde44ae-f380-11ea-29fb-2dfcc9cda8b4\n# ╟─ffe326e0-f380-11ea-3619-61dd0592d409\n# ╟─fff5aedc-f380-11ea-2a08-99c230f8fa32\n# ╟─00026442-f381-11ea-2b41-bde1fff66011\n# ╟─00115b6e-f381-11ea-0bc6-61ca119cb628\n", "meta": {"hexsha": "7cde479175e6238d6d062e857851fc12941c3463", "size": 49147, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "18s191/h3v3.jl", "max_stars_repo_name": "pankgeorg/learning", "max_stars_repo_head_hexsha": "fb1544539f7eeef441110a0e72abc4fb2e1b4321", "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": "18s191/h3v3.jl", "max_issues_repo_name": "pankgeorg/learning", "max_issues_repo_head_hexsha": "fb1544539f7eeef441110a0e72abc4fb2e1b4321", "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": "18s191/h3v3.jl", "max_forks_repo_name": "pankgeorg/learning", "max_forks_repo_head_hexsha": "fb1544539f7eeef441110a0e72abc4fb2e1b4321", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.9526315789, "max_line_length": 1058, "alphanum_fraction": 0.7406352371, "num_tokens": 18767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4225046348141882, "lm_q2_score": 0.32766829425520916, "lm_q1q2_score": 0.1384413730044851}}
{"text": "const vertex_codes = [\n \"\\x15\\x45\\x51\\x54\\x55\\x56\\x59\\x5A\\x65\\x66\\x69\\x6A\\x95\\x96\\x99\\x9A\\xA5\\xA6\\xA9\\xAA\",\n \"\\x15\\x45\\x51\\x55\\x56\\x59\\x5A\\x65\\x66\\x6A\\x95\\x96\\x9A\\xA6\\xAA\",\n \"\\x01\\x05\\x11\\x15\\x41\\x45\\x51\\x55\\x56\\x5A\\x66\\x6A\\x96\\x9A\\xA6\\xAA\",\n \"\\x01\\x15\\x16\\x45\\x46\\x51\\x52\\x55\\x56\\x5A\\x66\\x6A\\x96\\x9A\\xA6\\xAA\\xAB\",\n \"\\x15\\x45\\x54\\x55\\x56\\x59\\x5A\\x65\\x69\\x6A\\x95\\x99\\x9A\\xA9\\xAA\",\n \"\\x05\\x15\\x45\\x55\\x56\\x59\\x5A\\x65\\x66\\x69\\x6A\\x95\\x96\\x99\\x9A\\xAA\",\n \"\\x05\\x15\\x45\\x55\\x56\\x59\\x5A\\x66\\x6A\\x96\\x9A\\xAA\",\n \"\\x05\\x15\\x16\\x45\\x46\\x55\\x56\\x59\\x5A\\x66\\x6A\\x96\\x9A\\xAA\\xAB\",\n \"\\x04\\x05\\x14\\x15\\x44\\x45\\x54\\x55\\x59\\x5A\\x69\\x6A\\x99\\x9A\\xA9\\xAA\",\n \"\\x05\\x15\\x45\\x55\\x56\\x59\\x5A\\x69\\x6A\\x99\\x9A\\xAA\",\n \"\\x05\\x15\\x45\\x55\\x56\\x59\\x5A\\x6A\\x9A\\xAA\",\n \"\\x05\\x15\\x16\\x45\\x46\\x55\\x56\\x59\\x5A\\x5B\\x6A\\x9A\\xAA\\xAB\",\n \"\\x04\\x15\\x19\\x45\\x49\\x54\\x55\\x58\\x59\\x5A\\x69\\x6A\\x99\\x9A\\xA9\\xAA\\xAE\",\n \"\\x05\\x15\\x19\\x45\\x49\\x55\\x56\\x59\\x5A\\x69\\x6A\\x99\\x9A\\xAA\\xAE\",\n \"\\x05\\x15\\x19\\x45\\x49\\x55\\x56\\x59\\x5A\\x5E\\x6A\\x9A\\xAA\\xAE\",\n \"\\x05\\x15\\x1A\\x45\\x4A\\x55\\x56\\x59\\x5A\\x5B\\x5E\\x6A\\x9A\\xAA\\xAB\\xAE\\xAF\",\n \"\\x15\\x51\\x54\\x55\\x56\\x59\\x65\\x66\\x69\\x6A\\x95\\xA5\\xA6\\xA9\\xAA\",\n \"\\x11\\x15\\x51\\x55\\x56\\x59\\x5A\\x65\\x66\\x69\\x6A\\x95\\x96\\xA5\\xA6\\xAA\",\n \"\\x11\\x15\\x51\\x55\\x56\\x5A\\x65\\x66\\x6A\\x96\\xA6\\xAA\",\n \"\\x11\\x15\\x16\\x51\\x52\\x55\\x56\\x5A\\x65\\x66\\x6A\\x96\\xA6\\xAA\\xAB\",\n \"\\x14\\x15\\x54\\x55\\x56\\x59\\x5A\\x65\\x66\\x69\\x6A\\x95\\x99\\xA5\\xA9\\xAA\",\n \"\\x15\\x55\\x56\\x59\\x5A\\x65\\x66\\x69\\x6A\\x95\\x9A\\xA6\\xA9\\xAA\",\n \"\\x15\\x55\\x56\\x59\\x5A\\x65\\x66\\x69\\x6A\\x96\\x9A\\xA6\\xAA\\xAB\",\n \"\\x15\\x16\\x55\\x56\\x5A\\x66\\x6A\\x6B\\x96\\x9A\\xA6\\xAA\\xAB\",\n \"\\x14\\x15\\x54\\x55\\x59\\x5A\\x65\\x69\\x6A\\x99\\xA9\\xAA\",\n \"\\x15\\x55\\x56\\x59\\x5A\\x65\\x66\\x69\\x6A\\x99\\x9A\\xA9\\xAA\\xAE\",\n \"\\x15\\x55\\x56\\x59\\x5A\\x65\\x66\\x69\\x6A\\x9A\\xAA\",\n \"\\x15\\x16\\x55\\x56\\x59\\x5A\\x66\\x6A\\x6B\\x9A\\xAA\\xAB\",\n \"\\x14\\x15\\x19\\x54\\x55\\x58\\x59\\x5A\\x65\\x69\\x6A\\x99\\xA9\\xAA\\xAE\",\n \"\\x15\\x19\\x55\\x59\\x5A\\x69\\x6A\\x6E\\x99\\x9A\\xA9\\xAA\\xAE\",\n \"\\x15\\x19\\x55\\x56\\x59\\x5A\\x69\\x6A\\x6E\\x9A\\xAA\\xAE\",\n \"\\x15\\x1A\\x55\\x56\\x59\\x5A\\x6A\\x6B\\x6E\\x9A\\xAA\\xAB\\xAE\\xAF\",\n \"\\x10\\x11\\x14\\x15\\x50\\x51\\x54\\x55\\x65\\x66\\x69\\x6A\\xA5\\xA6\\xA9\\xAA\",\n \"\\x11\\x15\\x51\\x55\\x56\\x65\\x66\\x69\\x6A\\xA5\\xA6\\xAA\",\n \"\\x11\\x15\\x51\\x55\\x56\\x65\\x66\\x6A\\xA6\\xAA\",\n \"\\x11\\x15\\x16\\x51\\x52\\x55\\x56\\x65\\x66\\x67\\x6A\\xA6\\xAA\\xAB\",\n \"\\x14\\x15\\x54\\x55\\x59\\x65\\x66\\x69\\x6A\\xA5\\xA9\\xAA\",\n \"\\x15\\x55\\x56\\x59\\x5A\\x65\\x66\\x69\\x6A\\xA5\\xA6\\xA9\\xAA\\xBA\",\n \"\\x15\\x55\\x56\\x59\\x5A\\x65\\x66\\x69\\x6A\\xA6\\xAA\",\n \"\\x15\\x16\\x55\\x56\\x5A\\x65\\x66\\x6A\\x6B\\xA6\\xAA\\xAB\",\n \"\\x14\\x15\\x54\\x55\\x59\\x65\\x69\\x6A\\xA9\\xAA\",\n \"\\x15\\x55\\x56\\x59\\x5A\\x65\\x66\\x69\\x6A\\xA9\\xAA\",\n \"\\x15\\x55\\x56\\x59\\x5A\\x65\\x66\\x69\\x6A\\xAA\",\n \"\\x15\\x16\\x55\\x56\\x59\\x5A\\x65\\x66\\x69\\x6A\\x6B\\xAA\\xAB\",\n \"\\x14\\x15\\x19\\x54\\x55\\x58\\x59\\x65\\x69\\x6A\\x6D\\xA9\\xAA\\xAE\",\n \"\\x15\\x19\\x55\\x59\\x5A\\x65\\x69\\x6A\\x6E\\xA9\\xAA\\xAE\",\n \"\\x15\\x19\\x55\\x56\\x59\\x5A\\x65\\x66\\x69\\x6A\\x6E\\xAA\\xAE\",\n \"\\x15\\x55\\x56\\x59\\x5A\\x66\\x69\\x6A\\x6B\\x6E\\x9A\\xAA\\xAB\\xAE\\xAF\",\n \"\\x10\\x15\\x25\\x51\\x54\\x55\\x61\\x64\\x65\\x66\\x69\\x6A\\xA5\\xA6\\xA9\\xAA\\xBA\",\n \"\\x11\\x15\\x25\\x51\\x55\\x56\\x61\\x65\\x66\\x69\\x6A\\xA5\\xA6\\xAA\\xBA\",\n \"\\x11\\x15\\x25\\x51\\x55\\x56\\x61\\x65\\x66\\x6A\\x76\\xA6\\xAA\\xBA\",\n \"\\x11\\x15\\x26\\x51\\x55\\x56\\x62\\x65\\x66\\x67\\x6A\\x76\\xA6\\xAA\\xAB\\xBA\\xBB\",\n \"\\x14\\x15\\x25\\x54\\x55\\x59\\x64\\x65\\x66\\x69\\x6A\\xA5\\xA9\\xAA\\xBA\",\n \"\\x15\\x25\\x55\\x65\\x66\\x69\\x6A\\x7A\\xA5\\xA6\\xA9\\xAA\\xBA\",\n \"\\x15\\x25\\x55\\x56\\x65\\x66\\x69\\x6A\\x7A\\xA6\\xAA\\xBA\",\n \"\\x15\\x26\\x55\\x56\\x65\\x66\\x6A\\x6B\\x7A\\xA6\\xAA\\xAB\\xBA\\xBB\",\n \"\\x14\\x15\\x25\\x54\\x55\\x59\\x64\\x65\\x69\\x6A\\x79\\xA9\\xAA\\xBA\",\n \"\\x15\\x25\\x55\\x59\\x65\\x66\\x69\\x6A\\x7A\\xA9\\xAA\\xBA\",\n \"\\x15\\x25\\x55\\x56\\x59\\x5A\\x65\\x66\\x69\\x6A\\x7A\\xAA\\xBA\",\n \"\\x15\\x55\\x56\\x5A\\x65\\x66\\x69\\x6A\\x6B\\x7A\\xA6\\xAA\\xAB\\xBA\\xBB\",\n \"\\x14\\x15\\x29\\x54\\x55\\x59\\x65\\x68\\x69\\x6A\\x6D\\x79\\xA9\\xAA\\xAE\\xBA\\xBE\",\n \"\\x15\\x29\\x55\\x59\\x65\\x69\\x6A\\x6E\\x7A\\xA9\\xAA\\xAE\\xBA\\xBE\",\n \"\\x15\\x55\\x59\\x5A\\x65\\x66\\x69\\x6A\\x6E\\x7A\\xA9\\xAA\\xAE\\xBA\\xBE\",\n \"\\x15\\x55\\x56\\x59\\x5A\\x65\\x66\\x69\\x6A\\x6B\\x6E\\x7A\\xAA\\xAB\\xAE\\xBA\\xBF\",\n \"\\x45\\x51\\x54\\x55\\x56\\x59\\x65\\x95\\x96\\x99\\x9A\\xA5\\xA6\\xA9\\xAA\",\n \"\\x41\\x45\\x51\\x55\\x56\\x59\\x5A\\x65\\x66\\x95\\x96\\x99\\x9A\\xA5\\xA6\\xAA\",\n \"\\x41\\x45\\x51\\x55\\x56\\x5A\\x66\\x95\\x96\\x9A\\xA6\\xAA\",\n \"\\x41\\x45\\x46\\x51\\x52\\x55\\x56\\x5A\\x66\\x95\\x96\\x9A\\xA6\\xAA\\xAB\",\n \"\\x44\\x45\\x54\\x55\\x56\\x59\\x5A\\x65\\x69\\x95\\x96\\x99\\x9A\\xA5\\xA9\\xAA\",\n \"\\x45\\x55\\x56\\x59\\x5A\\x65\\x6A\\x95\\x96\\x99\\x9A\\xA6\\xA9\\xAA\",\n \"\\x45\\x55\\x56\\x59\\x5A\\x66\\x6A\\x95\\x96\\x99\\x9A\\xA6\\xAA\\xAB\",\n \"\\x45\\x46\\x55\\x56\\x5A\\x66\\x6A\\x96\\x9A\\x9B\\xA6\\xAA\\xAB\",\n \"\\x44\\x45\\x54\\x55\\x59\\x5A\\x69\\x95\\x99\\x9A\\xA9\\xAA\",\n \"\\x45\\x55\\x56\\x59\\x5A\\x69\\x6A\\x95\\x96\\x99\\x9A\\xA9\\xAA\\xAE\",\n \"\\x45\\x55\\x56\\x59\\x5A\\x6A\\x95\\x96\\x99\\x9A\\xAA\",\n \"\\x45\\x46\\x55\\x56\\x59\\x5A\\x6A\\x96\\x9A\\x9B\\xAA\\xAB\",\n \"\\x44\\x45\\x49\\x54\\x55\\x58\\x59\\x5A\\x69\\x95\\x99\\x9A\\xA9\\xAA\\xAE\",\n \"\\x45\\x49\\x55\\x59\\x5A\\x69\\x6A\\x99\\x9A\\x9E\\xA9\\xAA\\xAE\",\n \"\\x45\\x49\\x55\\x56\\x59\\x5A\\x6A\\x99\\x9A\\x9E\\xAA\\xAE\",\n \"\\x45\\x4A\\x55\\x56\\x59\\x5A\\x6A\\x9A\\x9B\\x9E\\xAA\\xAB\\xAE\\xAF\",\n \"\\x50\\x51\\x54\\x55\\x56\\x59\\x65\\x66\\x69\\x95\\x96\\x99\\xA5\\xA6\\xA9\\xAA\",\n \"\\x51\\x55\\x56\\x59\\x65\\x66\\x6A\\x95\\x96\\x9A\\xA5\\xA6\\xA9\\xAA\",\n \"\\x51\\x55\\x56\\x5A\\x65\\x66\\x6A\\x95\\x96\\x9A\\xA5\\xA6\\xAA\\xAB\",\n \"\\x51\\x52\\x55\\x56\\x5A\\x66\\x6A\\x96\\x9A\\xA6\\xA7\\xAA\\xAB\",\n \"\\x54\\x55\\x56\\x59\\x65\\x69\\x6A\\x95\\x99\\x9A\\xA5\\xA6\\xA9\\xAA\",\n \"\\x55\\x56\\x59\\x5A\\x65\\x66\\x69\\x6A\\x95\\x96\\x99\\x9A\\xA5\\xA6\\xA9\\xAA\",\n \"\\x15\\x45\\x51\\x55\\x56\\x59\\x5A\\x65\\x66\\x6A\\x95\\x96\\x9A\\xA6\\xAA\\xAB\",\n \"\\x55\\x56\\x5A\\x66\\x6A\\x96\\x9A\\xA6\\xAA\\xAB\",\n \"\\x54\\x55\\x59\\x5A\\x65\\x69\\x6A\\x95\\x99\\x9A\\xA5\\xA9\\xAA\\xAE\",\n \"\\x15\\x45\\x54\\x55\\x56\\x59\\x5A\\x65\\x69\\x6A\\x95\\x99\\x9A\\xA9\\xAA\\xAE\",\n \"\\x15\\x45\\x55\\x56\\x59\\x5A\\x65\\x66\\x69\\x6A\\x95\\x96\\x99\\x9A\\xA6\\xA9\\xAA\\xAB\\xAE\",\n \"\\x55\\x56\\x59\\x5A\\x66\\x6A\\x96\\x9A\\xA6\\xAA\\xAB\",\n \"\\x54\\x55\\x58\\x59\\x5A\\x69\\x6A\\x99\\x9A\\xA9\\xAA\\xAD\\xAE\",\n \"\\x55\\x59\\x5A\\x69\\x6A\\x99\\x9A\\xA9\\xAA\\xAE\",\n \"\\x55\\x56\\x59\\x5A\\x69\\x6A\\x99\\x9A\\xA9\\xAA\\xAE\",\n \"\\x55\\x56\\x59\\x5A\\x6A\\x9A\\xAA\\xAB\\xAE\\xAF\",\n \"\\x50\\x51\\x54\\x55\\x65\\x66\\x69\\x95\\xA5\\xA6\\xA9\\xAA\",\n \"\\x51\\x55\\x56\\x65\\x66\\x69\\x6A\\x95\\x96\\xA5\\xA6\\xA9\\xAA\\xBA\",\n \"\\x51\\x55\\x56\\x65\\x66\\x6A\\x95\\x96\\xA5\\xA6\\xAA\",\n \"\\x51\\x52\\x55\\x56\\x65\\x66\\x6A\\x96\\xA6\\xA7\\xAA\\xAB\",\n \"\\x54\\x55\\x59\\x65\\x66\\x69\\x6A\\x95\\x99\\xA5\\xA6\\xA9\\xAA\\xBA\",\n \"\\x15\\x51\\x54\\x55\\x56\\x59\\x65\\x66\\x69\\x6A\\x95\\xA5\\xA6\\xA9\\xAA\\xBA\",\n \"\\x15\\x51\\x55\\x56\\x59\\x5A\\x65\\x66\\x69\\x6A\\x95\\x96\\x9A\\xA5\\xA6\\xA9\\xAA\\xAB\\xBA\",\n \"\\x55\\x56\\x5A\\x65\\x66\\x6A\\x96\\x9A\\xA6\\xAA\\xAB\",\n \"\\x54\\x55\\x59\\x65\\x69\\x6A\\x95\\x99\\xA5\\xA9\\xAA\",\n \"\\x15\\x54\\x55\\x56\\x59\\x5A\\x65\\x66\\x69\\x6A\\x95\\x99\\x9A\\xA5\\xA6\\xA9\\xAA\\xAE\\xBA\",\n \"\\x15\\x55\\x56\\x59\\x5A\\x65\\x66\\x69\\x6A\\x9A\\xA6\\xA9\\xAA\",\n \"\\x15\\x55\\x56\\x59\\x5A\\x65\\x66\\x69\\x6A\\x96\\x9A\\xA6\\xAA\\xAB\",\n \"\\x54\\x55\\x58\\x59\\x65\\x69\\x6A\\x99\\xA9\\xAA\\xAD\\xAE\",\n \"\\x55\\x59\\x5A\\x65\\x69\\x6A\\x99\\x9A\\xA9\\xAA\\xAE\",\n \"\\x15\\x55\\x56\\x59\\x5A\\x65\\x66\\x69\\x6A\\x99\\x9A\\xA9\\xAA\\xAE\",\n \"\\x15\\x55\\x56\\x59\\x5A\\x66\\x69\\x6A\\x9A\\xAA\\xAB\\xAE\\xAF\",\n \"\\x50\\x51\\x54\\x55\\x61\\x64\\x65\\x66\\x69\\x95\\xA5\\xA6\\xA9\\xAA\\xBA\",\n \"\\x51\\x55\\x61\\x65\\x66\\x69\\x6A\\xA5\\xA6\\xA9\\xAA\\xB6\\xBA\",\n \"\\x51\\x55\\x56\\x61\\x65\\x66\\x6A\\xA5\\xA6\\xAA\\xB6\\xBA\",\n \"\\x51\\x55\\x56\\x62\\x65\\x66\\x6A\\xA6\\xA7\\xAA\\xAB\\xB6\\xBA\\xBB\",\n \"\\x54\\x55\\x64\\x65\\x66\\x69\\x6A\\xA5\\xA6\\xA9\\xAA\\xB9\\xBA\",\n \"\\x55\\x65\\x66\\x69\\x6A\\xA5\\xA6\\xA9\\xAA\\xBA\",\n \"\\x55\\x56\\x65\\x66\\x69\\x6A\\xA5\\xA6\\xA9\\xAA\\xBA\",\n \"\\x55\\x56\\x65\\x66\\x6A\\xA6\\xAA\\xAB\\xBA\\xBB\",\n \"\\x54\\x55\\x59\\x64\\x65\\x69\\x6A\\xA5\\xA9\\xAA\\xB9\\xBA\",\n \"\\x55\\x59\\x65\\x66\\x69\\x6A\\xA5\\xA6\\xA9\\xAA\\xBA\",\n \"\\x15\\x55\\x56\\x59\\x5A\\x65\\x66\\x69\\x6A\\xA5\\xA6\\xA9\\xAA\\xBA\",\n \"\\x15\\x55\\x56\\x5A\\x65\\x66\\x69\\x6A\\xA6\\xAA\\xAB\\xBA\\xBB\",\n \"\\x54\\x55\\x59\\x65\\x68\\x69\\x6A\\xA9\\xAA\\xAD\\xAE\\xB9\\xBA\\xBE\",\n \"\\x55\\x59\\x65\\x69\\x6A\\xA9\\xAA\\xAE\\xBA\\xBE\",\n \"\\x15\\x55\\x59\\x5A\\x65\\x66\\x69\\x6A\\xA9\\xAA\\xAE\\xBA\\xBE\",\n \"\\x55\\x56\\x59\\x5A\\x65\\x66\\x69\\x6A\\xAA\\xAB\\xAE\\xBA\\xBF\",\n \"\\x40\\x41\\x44\\x45\\x50\\x51\\x54\\x55\\x95\\x96\\x99\\x9A\\xA5\\xA6\\xA9\\xAA\",\n \"\\x41\\x45\\x51\\x55\\x56\\x95\\x96\\x99\\x9A\\xA5\\xA6\\xAA\",\n \"\\x41\\x45\\x51\\x55\\x56\\x95\\x96\\x9A\\xA6\\xAA\",\n \"\\x41\\x45\\x46\\x51\\x52\\x55\\x56\\x95\\x96\\x97\\x9A\\xA6\\xAA\\xAB\",\n \"\\x44\\x45\\x54\\x55\\x59\\x95\\x96\\x99\\x9A\\xA5\\xA9\\xAA\",\n \"\\x45\\x55\\x56\\x59\\x5A\\x95\\x96\\x99\\x9A\\xA5\\xA6\\xA9\\xAA\\xEA\",\n \"\\x45\\x55\\x56\\x59\\x5A\\x95\\x96\\x99\\x9A\\xA6\\xAA\",\n \"\\x45\\x46\\x55\\x56\\x5A\\x95\\x96\\x9A\\x9B\\xA6\\xAA\\xAB\",\n \"\\x44\\x45\\x54\\x55\\x59\\x95\\x99\\x9A\\xA9\\xAA\",\n \"\\x45\\x55\\x56\\x59\\x5A\\x95\\x96\\x99\\x9A\\xA9\\xAA\",\n \"\\x45\\x55\\x56\\x59\\x5A\\x95\\x96\\x99\\x9A\\xAA\",\n \"\\x45\\x46\\x55\\x56\\x59\\x5A\\x95\\x96\\x99\\x9A\\x9B\\xAA\\xAB\",\n \"\\x44\\x45\\x49\\x54\\x55\\x58\\x59\\x95\\x99\\x9A\\x9D\\xA9\\xAA\\xAE\",\n \"\\x45\\x49\\x55\\x59\\x5A\\x95\\x99\\x9A\\x9E\\xA9\\xAA\\xAE\",\n \"\\x45\\x49\\x55\\x56\\x59\\x5A\\x95\\x96\\x99\\x9A\\x9E\\xAA\\xAE\",\n \"\\x45\\x55\\x56\\x59\\x5A\\x6A\\x96\\x99\\x9A\\x9B\\x9E\\xAA\\xAB\\xAE\\xAF\",\n \"\\x50\\x51\\x54\\x55\\x65\\x95\\x96\\x99\\xA5\\xA6\\xA9\\xAA\",\n \"\\x51\\x55\\x56\\x65\\x66\\x95\\x96\\x99\\x9A\\xA5\\xA6\\xA9\\xAA\\xEA\",\n \"\\x51\\x55\\x56\\x65\\x66\\x95\\x96\\x9A\\xA5\\xA6\\xAA\",\n \"\\x51\\x52\\x55\\x56\\x66\\x95\\x96\\x9A\\xA6\\xA7\\xAA\\xAB\",\n \"\\x54\\x55\\x59\\x65\\x69\\x95\\x96\\x99\\x9A\\xA5\\xA6\\xA9\\xAA\\xEA\",\n \"\\x45\\x51\\x54\\x55\\x56\\x59\\x65\\x95\\x96\\x99\\x9A\\xA5\\xA6\\xA9\\xAA\\xEA\",\n \"\\x45\\x51\\x55\\x56\\x59\\x5A\\x65\\x66\\x6A\\x95\\x96\\x99\\x9A\\xA5\\xA6\\xA9\\xAA\\xAB\\xEA\",\n \"\\x55\\x56\\x5A\\x66\\x6A\\x95\\x96\\x9A\\xA6\\xAA\\xAB\",\n \"\\x54\\x55\\x59\\x65\\x69\\x95\\x99\\x9A\\xA5\\xA9\\xAA\",\n \"\\x45\\x54\\x55\\x56\\x59\\x5A\\x65\\x69\\x6A\\x95\\x96\\x99\\x9A\\xA5\\xA6\\xA9\\xAA\\xAE\\xEA\",\n \"\\x45\\x55\\x56\\x59\\x5A\\x6A\\x95\\x96\\x99\\x9A\\xA6\\xA9\\xAA\",\n \"\\x45\\x55\\x56\\x59\\x5A\\x66\\x6A\\x95\\x96\\x99\\x9A\\xA6\\xAA\\xAB\",\n \"\\x54\\x55\\x58\\x59\\x69\\x95\\x99\\x9A\\xA9\\xAA\\xAD\\xAE\",\n \"\\x55\\x59\\x5A\\x69\\x6A\\x95\\x99\\x9A\\xA9\\xAA\\xAE\",\n \"\\x45\\x55\\x56\\x59\\x5A\\x69\\x6A\\x95\\x96\\x99\\x9A\\xA9\\xAA\\xAE\",\n \"\\x45\\x55\\x56\\x59\\x5A\\x6A\\x96\\x99\\x9A\\xAA\\xAB\\xAE\\xAF\",\n \"\\x50\\x51\\x54\\x55\\x65\\x95\\xA5\\xA6\\xA9\\xAA\",\n \"\\x51\\x55\\x56\\x65\\x66\\x95\\x96\\xA5\\xA6\\xA9\\xAA\",\n \"\\x51\\x55\\x56\\x65\\x66\\x95\\x96\\xA5\\xA6\\xAA\",\n \"\\x51\\x52\\x55\\x56\\x65\\x66\\x95\\x96\\xA5\\xA6\\xA7\\xAA\\xAB\",\n \"\\x54\\x55\\x59\\x65\\x69\\x95\\x99\\xA5\\xA6\\xA9\\xAA\",\n \"\\x51\\x54\\x55\\x56\\x59\\x65\\x66\\x69\\x6A\\x95\\x96\\x99\\x9A\\xA5\\xA6\\xA9\\xAA\\xBA\\xEA\",\n \"\\x51\\x55\\x56\\x65\\x66\\x6A\\x95\\x96\\x9A\\xA5\\xA6\\xA9\\xAA\",\n \"\\x51\\x55\\x56\\x5A\\x65\\x66\\x6A\\x95\\x96\\x9A\\xA5\\xA6\\xAA\\xAB\",\n \"\\x54\\x55\\x59\\x65\\x69\\x95\\x99\\xA5\\xA9\\xAA\",\n \"\\x54\\x55\\x59\\x65\\x69\\x6A\\x95\\x99\\x9A\\xA5\\xA6\\xA9\\xAA\",\n \"\\x55\\x56\\x59\\x5A\\x65\\x66\\x69\\x6A\\x95\\x96\\x99\\x9A\\xA5\\xA6\\xA9\\xAA\",\n \"\\x55\\x56\\x59\\x5A\\x65\\x66\\x6A\\x95\\x96\\x9A\\xA6\\xA9\\xAA\\xAB\",\n \"\\x54\\x55\\x58\\x59\\x65\\x69\\x95\\x99\\xA5\\xA9\\xAA\\xAD\\xAE\",\n \"\\x54\\x55\\x59\\x5A\\x65\\x69\\x6A\\x95\\x99\\x9A\\xA5\\xA9\\xAA\\xAE\",\n \"\\x55\\x56\\x59\\x5A\\x65\\x69\\x6A\\x95\\x99\\x9A\\xA6\\xA9\\xAA\\xAE\",\n \"\\x55\\x56\\x59\\x5A\\x66\\x69\\x6A\\x96\\x99\\x9A\\xA6\\xA9\\xAA\\xAB\\xAE\\xAF\",\n \"\\x50\\x51\\x54\\x55\\x61\\x64\\x65\\x95\\xA5\\xA6\\xA9\\xAA\\xB5\\xBA\",\n \"\\x51\\x55\\x61\\x65\\x66\\x95\\xA5\\xA6\\xA9\\xAA\\xB6\\xBA\",\n \"\\x51\\x55\\x56\\x61\\x65\\x66\\x95\\x96\\xA5\\xA6\\xAA\\xB6\\xBA\",\n \"\\x51\\x55\\x56\\x65\\x66\\x6A\\x96\\xA5\\xA6\\xA7\\xAA\\xAB\\xB6\\xBA\\xBB\",\n \"\\x54\\x55\\x64\\x65\\x69\\x95\\xA5\\xA6\\xA9\\xAA\\xB9\\xBA\",\n \"\\x55\\x65\\x66\\x69\\x6A\\x95\\xA5\\xA6\\xA9\\xAA\\xBA\",\n \"\\x51\\x55\\x56\\x65\\x66\\x69\\x6A\\x95\\x96\\xA5\\xA6\\xA9\\xAA\\xBA\",\n \"\\x51\\x55\\x56\\x65\\x66\\x6A\\x96\\xA5\\xA6\\xAA\\xAB\\xBA\\xBB\",\n \"\\x54\\x55\\x59\\x64\\x65\\x69\\x95\\x99\\xA5\\xA9\\xAA\\xB9\\xBA\",\n \"\\x54\\x55\\x59\\x65\\x66\\x69\\x6A\\x95\\x99\\xA5\\xA6\\xA9\\xAA\\xBA\",\n \"\\x55\\x56\\x59\\x65\\x66\\x69\\x6A\\x95\\x9A\\xA5\\xA6\\xA9\\xAA\\xBA\",\n \"\\x55\\x56\\x5A\\x65\\x66\\x69\\x6A\\x96\\x9A\\xA5\\xA6\\xA9\\xAA\\xAB\\xBA\\xBB\",\n \"\\x54\\x55\\x59\\x65\\x69\\x6A\\x99\\xA5\\xA9\\xAA\\xAD\\xAE\\xB9\\xBA\\xBE\",\n \"\\x54\\x55\\x59\\x65\\x69\\x6A\\x99\\xA5\\xA9\\xAA\\xAE\\xBA\\xBE\",\n \"\\x55\\x59\\x5A\\x65\\x66\\x69\\x6A\\x99\\x9A\\xA5\\xA6\\xA9\\xAA\\xAE\\xBA\\xBE\",\n \"\\x55\\x56\\x59\\x5A\\x65\\x66\\x69\\x6A\\x9A\\xA6\\xA9\\xAA\\xAB\\xAE\\xBA\",\n \"\\x40\\x45\\x51\\x54\\x55\\x85\\x91\\x94\\x95\\x96\\x99\\x9A\\xA5\\xA6\\xA9\\xAA\\xEA\",\n \"\\x41\\x45\\x51\\x55\\x56\\x85\\x91\\x95\\x96\\x99\\x9A\\xA5\\xA6\\xAA\\xEA\",\n \"\\x41\\x45\\x51\\x55\\x56\\x85\\x91\\x95\\x96\\x9A\\xA6\\xAA\\xD6\\xEA\",\n \"\\x41\\x45\\x51\\x55\\x56\\x86\\x92\\x95\\x96\\x97\\x9A\\xA6\\xAA\\xAB\\xD6\\xEA\\xEB\",\n \"\\x44\\x45\\x54\\x55\\x59\\x85\\x94\\x95\\x96\\x99\\x9A\\xA5\\xA9\\xAA\\xEA\",\n \"\\x45\\x55\\x85\\x95\\x96\\x99\\x9A\\xA5\\xA6\\xA9\\xAA\\xDA\\xEA\",\n \"\\x45\\x55\\x56\\x85\\x95\\x96\\x99\\x9A\\xA6\\xAA\\xDA\\xEA\",\n \"\\x45\\x55\\x56\\x86\\x95\\x96\\x9A\\x9B\\xA6\\xAA\\xAB\\xDA\\xEA\\xEB\",\n \"\\x44\\x45\\x54\\x55\\x59\\x85\\x94\\x95\\x99\\x9A\\xA9\\xAA\\xD9\\xEA\",\n \"\\x45\\x55\\x59\\x85\\x95\\x96\\x99\\x9A\\xA9\\xAA\\xDA\\xEA\",\n \"\\x45\\x55\\x56\\x59\\x5A\\x85\\x95\\x96\\x99\\x9A\\xAA\\xDA\\xEA\",\n \"\\x45\\x55\\x56\\x5A\\x95\\x96\\x99\\x9A\\x9B\\xA6\\xAA\\xAB\\xDA\\xEA\\xEB\",\n \"\\x44\\x45\\x54\\x55\\x59\\x89\\x95\\x98\\x99\\x9A\\x9D\\xA9\\xAA\\xAE\\xD9\\xEA\\xEE\",\n \"\\x45\\x55\\x59\\x89\\x95\\x99\\x9A\\x9E\\xA9\\xAA\\xAE\\xDA\\xEA\\xEE\",\n \"\\x45\\x55\\x59\\x5A\\x95\\x96\\x99\\x9A\\x9E\\xA9\\xAA\\xAE\\xDA\\xEA\\xEE\",\n \"\\x45\\x55\\x56\\x59\\x5A\\x95\\x96\\x99\\x9A\\x9B\\x9E\\xAA\\xAB\\xAE\\xDA\\xEA\\xEF\",\n \"\\x50\\x51\\x54\\x55\\x65\\x91\\x94\\x95\\x96\\x99\\xA5\\xA6\\xA9\\xAA\\xEA\",\n \"\\x51\\x55\\x91\\x95\\x96\\x99\\x9A\\xA5\\xA6\\xA9\\xAA\\xE6\\xEA\",\n \"\\x51\\x55\\x56\\x91\\x95\\x96\\x9A\\xA5\\xA6\\xAA\\xE6\\xEA\",\n \"\\x51\\x55\\x56\\x92\\x95\\x96\\x9A\\xA6\\xA7\\xAA\\xAB\\xE6\\xEA\\xEB\",\n \"\\x54\\x55\\x94\\x95\\x96\\x99\\x9A\\xA5\\xA6\\xA9\\xAA\\xE9\\xEA\",\n \"\\x55\\x95\\x96\\x99\\x9A\\xA5\\xA6\\xA9\\xAA\\xEA\",\n \"\\x55\\x56\\x95\\x96\\x99\\x9A\\xA5\\xA6\\xA9\\xAA\\xEA\",\n \"\\x55\\x56\\x95\\x96\\x9A\\xA6\\xAA\\xAB\\xEA\\xEB\",\n \"\\x54\\x55\\x59\\x94\\x95\\x99\\x9A\\xA5\\xA9\\xAA\\xE9\\xEA\",\n \"\\x55\\x59\\x95\\x96\\x99\\x9A\\xA5\\xA6\\xA9\\xAA\\xEA\",\n \"\\x45\\x55\\x56\\x59\\x5A\\x95\\x96\\x99\\x9A\\xA5\\xA6\\xA9\\xAA\\xEA\",\n \"\\x45\\x55\\x56\\x5A\\x95\\x96\\x99\\x9A\\xA6\\xAA\\xAB\\xEA\\xEB\",\n \"\\x54\\x55\\x59\\x95\\x98\\x99\\x9A\\xA9\\xAA\\xAD\\xAE\\xE9\\xEA\\xEE\",\n \"\\x55\\x59\\x95\\x99\\x9A\\xA9\\xAA\\xAE\\xEA\\xEE\",\n \"\\x45\\x55\\x59\\x5A\\x95\\x96\\x99\\x9A\\xA9\\xAA\\xAE\\xEA\\xEE\",\n \"\\x55\\x56\\x59\\x5A\\x95\\x96\\x99\\x9A\\xAA\\xAB\\xAE\\xEA\\xEF\",\n \"\\x50\\x51\\x54\\x55\\x65\\x91\\x94\\x95\\xA5\\xA6\\xA9\\xAA\\xE5\\xEA\",\n \"\\x51\\x55\\x65\\x91\\x95\\x96\\xA5\\xA6\\xA9\\xAA\\xE6\\xEA\",\n \"\\x51\\x55\\x56\\x65\\x66\\x91\\x95\\x96\\xA5\\xA6\\xAA\\xE6\\xEA\",\n \"\\x51\\x55\\x56\\x66\\x95\\x96\\x9A\\xA5\\xA6\\xA7\\xAA\\xAB\\xE6\\xEA\\xEB\",\n \"\\x54\\x55\\x65\\x94\\x95\\x99\\xA5\\xA6\\xA9\\xAA\\xE9\\xEA\",\n \"\\x55\\x65\\x95\\x96\\x99\\x9A\\xA5\\xA6\\xA9\\xAA\\xEA\",\n \"\\x51\\x55\\x56\\x65\\x66\\x95\\x96\\x99\\x9A\\xA5\\xA6\\xA9\\xAA\\xEA\",\n \"\\x51\\x55\\x56\\x66\\x95\\x96\\x9A\\xA5\\xA6\\xAA\\xAB\\xEA\\xEB\",\n \"\\x54\\x55\\x59\\x65\\x69\\x94\\x95\\x99\\xA5\\xA9\\xAA\\xE9\\xEA\",\n \"\\x54\\x55\\x59\\x65\\x69\\x95\\x96\\x99\\x9A\\xA5\\xA6\\xA9\\xAA\\xEA\",\n \"\\x55\\x56\\x59\\x65\\x6A\\x95\\x96\\x99\\x9A\\xA5\\xA6\\xA9\\xAA\\xEA\",\n \"\\x55\\x56\\x5A\\x66\\x6A\\x95\\x96\\x99\\x9A\\xA5\\xA6\\xA9\\xAA\\xAB\\xEA\\xEB\",\n \"\\x54\\x55\\x59\\x69\\x95\\x99\\x9A\\xA5\\xA9\\xAA\\xAD\\xAE\\xE9\\xEA\\xEE\",\n \"\\x54\\x55\\x59\\x69\\x95\\x99\\x9A\\xA5\\xA9\\xAA\\xAE\\xEA\\xEE\",\n \"\\x55\\x59\\x5A\\x69\\x6A\\x95\\x96\\x99\\x9A\\xA5\\xA6\\xA9\\xAA\\xAE\\xEA\\xEE\",\n \"\\x55\\x56\\x59\\x5A\\x6A\\x95\\x96\\x99\\x9A\\xA6\\xA9\\xAA\\xAB\\xAE\\xEA\",\n \"\\x50\\x51\\x54\\x55\\x65\\x95\\xA1\\xA4\\xA5\\xA6\\xA9\\xAA\\xB5\\xBA\\xE5\\xEA\\xFA\",\n \"\\x51\\x55\\x65\\x95\\xA1\\xA5\\xA6\\xA9\\xAA\\xB6\\xBA\\xE6\\xEA\\xFA\",\n \"\\x51\\x55\\x65\\x66\\x95\\x96\\xA5\\xA6\\xA9\\xAA\\xB6\\xBA\\xE6\\xEA\\xFA\",\n \"\\x51\\x55\\x56\\x65\\x66\\x95\\x96\\xA5\\xA6\\xA7\\xAA\\xAB\\xB6\\xBA\\xE6\\xEA\\xFB\",\n \"\\x54\\x55\\x65\\x95\\xA4\\xA5\\xA6\\xA9\\xAA\\xB9\\xBA\\xE9\\xEA\\xFA\",\n \"\\x55\\x65\\x95\\xA5\\xA6\\xA9\\xAA\\xBA\\xEA\\xFA\",\n \"\\x51\\x55\\x65\\x66\\x95\\x96\\xA5\\xA6\\xA9\\xAA\\xBA\\xEA\\xFA\",\n \"\\x55\\x56\\x65\\x66\\x95\\x96\\xA5\\xA6\\xAA\\xAB\\xBA\\xEA\\xFB\",\n \"\\x54\\x55\\x65\\x69\\x95\\x99\\xA5\\xA6\\xA9\\xAA\\xB9\\xBA\\xE9\\xEA\\xFA\",\n \"\\x54\\x55\\x65\\x69\\x95\\x99\\xA5\\xA6\\xA9\\xAA\\xBA\\xEA\\xFA\",\n \"\\x55\\x65\\x66\\x69\\x6A\\x95\\x96\\x99\\x9A\\xA5\\xA6\\xA9\\xAA\\xBA\\xEA\\xFA\",\n \"\\x55\\x56\\x65\\x66\\x6A\\x95\\x96\\x9A\\xA5\\xA6\\xA9\\xAA\\xAB\\xBA\\xEA\",\n \"\\x54\\x55\\x59\\x65\\x69\\x95\\x99\\xA5\\xA9\\xAA\\xAD\\xAE\\xB9\\xBA\\xE9\\xEA\\xFE\",\n \"\\x55\\x59\\x65\\x69\\x95\\x99\\xA5\\xA9\\xAA\\xAE\\xBA\\xEA\\xFE\",\n \"\\x55\\x59\\x65\\x69\\x6A\\x95\\x99\\x9A\\xA5\\xA6\\xA9\\xAA\\xAE\\xBA\\xEA\",\n \"\\x55\\x56\\x59\\x5A\\x65\\x66\\x69\\x6A\\x95\\x96\\x99\\x9A\\xA5\\xA6\\xA9\\xAA\\xAB\\xAE\\xBA\\xEA\",\n]\n\n# Lookup Tables & Gradients\n\nstruct Vertex4D\n dx::Float32\n dy::Float32\n dz::Float32\n dw::Float32\n xsvp::Int64\n ysvp::Int64\n zsvp::Int64\n wsvp::Int64\n\n function Vertex4D(xsv::Int, ysv::Int, zsv::Int, wsv::Int)\n ssv = Float32((xsv + ysv + zsv + wsv) * UNSKEW_4D)\n new(-xsv - ssv, -ysv - ssv, -zsv - ssv, -wsv - ssv,\n (xsv * PRIME_X)%Int64,\n (ysv * PRIME_Y)%Int64,\n (zsv * PRIME_Z)%Int64,\n (wsv * PRIME_W)%Int64)\n end\nend\nVertex4D(v) = Vertex4D(((v >> 0) & 3) - 1, ((v >> 2) & 3) - 1,\n ((v >> 4) & 3) - 1, ((v >> 6) & 3) - 1)\n\nconst offsets_4D = Vector{UInt16}(undef, 256)\n\nfunction create_lattice_map()\n num_vertices = 0\n tab = falses(256)\n for i = 1:256\n codes = vertex_codes[i]\n num_vertices += sizeof(codes)\n offsets_4D[i] = num_vertices\n for v in codeunits(codes)\n tab[v+1] = true\n end\n end\n siz = count(tab)\n inv_map = zeros(UInt8, 256)\n vertices = Vector{UInt8}(undef, siz)\n vertex_map = Vector{Vertex4D}(undef, siz)\n r = findfirst(tab)\n i = 1\n while r !== nothing\n inv_map[r] = i\n vertices[i] = r-1\n vertex_map[i] = Vertex4D(r-1)\n i += 1\n r = findnext(tab, r+1)\n end\n io = IOBuffer()\n println(io, \"const vertex_ind = [\")\n for codes in vertex_codes\n print(io, \" \")\n for v in codeunits(codes)\n i = inv_map[v+1]\n print(io, i<10 ? \" \" : \"\", i, ',')\n end\n println(io)\n end\n println(io, \"]\")\n String(take!(io)), vertex_map, vertices, inv_map\nend\n", "meta": {"hexsha": "ca5d147bde8e0549b19e13e0299416500952fb50", "size": 17621, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/makecodes.jl", "max_stars_repo_name": "ScottPJones/OpenSimplex.jl", "max_stars_repo_head_hexsha": "c71dd53a0499a46f00d0cbee9d2e87d176c1f428", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2022-02-22T01:14:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T14:28:16.000Z", "max_issues_repo_path": "src/makecodes.jl", "max_issues_repo_name": "ScottPJones/OpenSimplex.jl", "max_issues_repo_head_hexsha": "c71dd53a0499a46f00d0cbee9d2e87d176c1f428", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/makecodes.jl", "max_forks_repo_name": "ScottPJones/OpenSimplex.jl", "max_forks_repo_head_hexsha": "c71dd53a0499a46f00d0cbee9d2e87d176c1f428", "max_forks_repo_licenses": ["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.5541795666, "max_line_length": 87, "alphanum_fraction": 0.6405992849, "num_tokens": 9275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.23934934189686402, "lm_q1q2_score": 0.13547616039620977}}
{"text": "### A Pluto.jl notebook ###\n# v0.12.21\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ e00967d0-89b4-11eb-031d-c128221e86e1\nbegin\n\tusing PlutoUI\n\tusing NativeSVG\nend\n\n# ╔═╡ f2f3ba34-89b3-11eb-2577-83e1dcfdc1fc\nmd\"\"\"# Case Study: Data Structure Selection\n\nAt this point you have learned about Julia’s core data structures, and you have seen some of the algorithms that use them.\n\nThis chapter presents a case study with exercises that let you think about choosing data structures and practice using them.\n\"\"\"\n\n# ╔═╡ def6b6fc-89b4-11eb-2e66-b5cc3e72779d\nmd\"\"\"## Word Frequency Analysis\n\nAs usual, you should at least attempt the exercises before you read my solutions.\n\n#### Exercise 13-1\n\nWrite a program that reads a file, breaks each line into words, strips whitespace and punctuation from the words, and converts them to lowercase.\n\n!!! tip\n The function isletter tests whether a character is alphabetic.\n\n#### Exercise 13-2\n\nGo to [Project Gutenberg](https://www.gutenberg.org/) and download your favorite out-of-copyright book in plain text format.\n\nModify your program from the previous exercise to read the book you downloaded, skip over the header information at the beginning of the file, and process the rest of the words as before.\n\nThen modify the program to count the total number of words in the book, and the number of times each word is used.\n\nPrint the number of different words used in the book. Compare different books by different authors, written in different eras. Which author uses the most extensive vocabulary?\n\n#### Exercise 13-3\n\nModify the program from the previous exercise to print the 20 most frequently used words in the book.\n\n#### Exercise 13-4\n\nModify the previous program to read a word list and then print all the words in the book that are not in the word list. How many of them are typos? How many of them are common words that should be in the word list, and how many of them are really obscure?\n\"\"\"\n\n# ╔═╡ 9016b5ea-89b5-11eb-062f-b59a784f61da\nmd\"\"\"## Random Numbers\n\nGiven the same inputs, most computer programs generate the same outputs every time, so they are said to be deterministic. Determinism is usually a good thing, since we expect the same calculation to yield the same result. For some applications, though, we want the computer to be unpredictable. Games are an obvious example, but there are more.\n\nMaking a program truly nondeterministic turns out to be difficult, but there are ways to make it at least seem nondeterministic. One of them is to use algorithms that gen‐ erate *pseudorandom* numbers. Pseudorandom numbers are not truly random because they are generated by a deterministic computation, but just by looking at the numbers it is all but impossible to distinguish them from random.\n\nThe function `rand` returns a random float between `0.0` and `1.0` (including `0.0` but not `1.0`). Each time you call rand, you get the next number in a long series. To see a sample, run this loop:\n\n```julia\nfor i in 1:10 \n\tx = rand() \n\tprintln(x)\nend\n```\n\nThe function `rand` can take an iterator or array as an argument and return a random element:\n\n```julia\nfor i in 1:10\n\tx = rand(1:6)\n\tprint(x, \" \") \nend\n```\n\n#### Exercise 13-5\n\nWrite a function named choosefromhist that takes a histogram as defined in “Dic‐ tionaries as Collections of Counters” and returns a random value from the histogram, chosen with probability in proportion to frequency. For example, for this histogram:\n\n```julia\njulia> t = ['a', 'a', 'b'];\n\njulia> histogram(t) \nDict{Any,Any} with 2 entries:\n 'a' => 2\n 'b' => 1\n```\n\nyour function should return `'a'` with probability `32` and `'b'` with probability `13`.\n\"\"\"\n\n# ╔═╡ 86793ed0-89b6-11eb-1759-cfa1ea349a6b\nmd\"\"\"## Word Histogram\n\nYou should attempt the previous exercises before you go on. You will also need the *emma.txt* file available from this book’s GitHub repository.\n\nHere is a program that reads a file and builds a histogram of the words in the file:\n\n```julia\nfunction processfile(filename) \n\thist = Dict()\n\tfor line in eachline(filename) \n\t\tprocessline(line, hist)\n\tend\n\thist\nend\n\nfunction processline(line, hist) \n\tline = replace(line, '-' => ' ') \n\tfor word in split(line)\n \tword = string(filter(isletter, [word...])...)\n word = lowercase(word)\n hist[word] = get(hist, word, 0) + 1\n\tend \nend\n\nhist = processfile(\"emma.txt\");\n```\n\nThis program reads *emma.txt*, which contains the text of *Emma* by Jane Austen.\n\n`processfile` loops through the lines of the file, passing them one at a time to `processline`. The histogram `hist` is being used as an accumulator.\n\n`processline` uses the function `replace` to replace hyphens with spaces before using `split` to break the line into an array of strings. It traverses the array of words and uses `filter`, `isletter`, and `lowercase` to remove punctuation and convert to lower case. (It is shorthand to say that strings are “converted”; remember that strings are immutable, so a function like `lowercase` returns new strings.)\n\n\nFinally, `processline` updates the histogram by creating a new item or incrementing an existing one.\n\nTo count the total number of words in the file, we can add up the frequencies in the histogram:\n\n```julia\ntotalwords(hist) = sum(values(hist))\n```\n\nThe number of different words is just the number of items in the dictionary:\n\n```julia\ndifferentwords(hist) = length(hist)\n```\n\nHere is some code to print the results:\n\n```julia\njulia> println(\"Total number of words: \", totalwords(hist))\nTotal number of words: 162742\njulia> println(\"Number of different words: \", differentwords(hist)) Number of different words: 7380\n```\n\"\"\"\n\n# ╔═╡ 00bea97c-89b8-11eb-23a1-db0c7d6c7bd1\nmd\"\"\"## Most Common Words\n\nTo find the most common words, we can make an array of tuples, where each tuple contains a word and its frequency, and sort it. The following function takes a histogram and returns an array of word-frequency tuples:\n\n```julia\nfunction mostcommon(hist) \n\tt = []\n\tfor (key, value) in hist \n\t\tpush!(t, (value, key))\n\tend\n\treverse(sort(t)) \nend\n```\n\nIn each tuple, the frequency appears first, so the resulting array is sorted by frequency. Here is a loop that prints the 10 most common words:\n\n```julia\nt = mostcommon(hist)\nprintln(\"The most common words are:\") \nfor (freq, word) in t[1:10]\n\tprintln(word, \"\\t\", freq) \nend\n```\n\nI use a tab character (`'\\t'`) as a “separator,” rather than a space, so the second column is lined up. Here are the results from *Emma*:\n\n```\nThe most common words are:\nto 5295\nthe 5266\nand 4931\nof 4339\ni 3191\na 3155\nit 2546\nher 2483\nwas 2400\nshe 2364\n```\n\n!!! tip\n This code can be simplified using the `rev` keyword argument of the `sort` function. You can read about it in the documentation.\n\"\"\"\n\n# ╔═╡ 87a74886-89b8-11eb-29aa-a9c5075a1f95\nmd\"\"\"## Optional Parameters\n\nWe have seen built-in functions that take optional arguments. It is possible to write programmer-defined functions with optional arguments, too. For example, here is a function that prints the most common words in a histogram:\n\n```julia\nfunction printmostcommon(hist, num=10)\n\tt = mostcommon(hist)\n\tprintln(\"The most common words are: \") \n\tfor (freq, word) in t[1:num]\n\t\tprintln(word, \"\\t\", freq) \n\tend\nend\n```\n\nThe first parameter is required; the second is optional. The *default value* of `num` is `10`. If you only provide one argument:\n\n```julia\nprintmostcommon(hist)\n```\n\n`num` gets the default value. If you provide two arguments:\n\n```julia\nprintmostcommon(hist, 20)\n```\n\n`num` gets the value of the argument instead. In other words, the optional argument\noverrides the default value.\n\nIf a function has both required and optional parameters, all the required parameters have to come first, followed by the optional ones.\n\"\"\"\n\n# ╔═╡ d5579180-89b8-11eb-27ec-d1b4e811c3cb\nmd\"\"\"## Dictionary Subtraction\n\nFinding the words from a book that are not in the word list from *words.txt* is a problem you might recognize as set subtraction; that is, we want to find all the words from one set (the words in the book) that are not in the other (the words in the list).\n\n`subtract` takes dictionaries `d1` and `d2` and returns a new dictionary that contains all the keys from `d1` that are not in `d2`. Since we don’t really care about the values, we set them all to `nothing`:\n\n```julia\nfunction subtract(d1, d2) res = Dict()\n\tfor key in keys(d1) \n\t\tif key ∉ keys(d2)\n\t\t\tres[key] = nothing \n\t\tend\n\tend\n\tres\nend\n```\n\nTo find the words in the book you downloaded that are not in *words.txt*, you can use `processfile` to build a histogram for *words.txt*, and then `subtract`:\n\n```julia\nwords = processfile(\"words.txt\")\ndiff = subtract(hist, words)\nprintln(\"Words in the book that aren't in the word list:\") \nfor word in keys(diff)\n\tprint(word, \" \") \nend\n```\n\nHere are some of the results from *Emma*:\n\n```\nWords in the book that aren't in the word list:\noutree quicksighted outwardly adelaide rencontre jeffereys unreserved dixons \nbetweens ...\n```\n\nSome of these words are names and possessives. Others, like “rencontre,” are no longer in common use. But a few are common words that should really be in the list!\n\n#### Exercise 13-6\n\nJulia provides a data structure called `Set` that provides many common set operations. You can read about them in “Collections and Data Structures”, or read the documentation.\n\nWrite a program that uses set subtraction to find words in the book that are not in the word list.\n\"\"\"\n\n# ╔═╡ 4ee3d86e-89ba-11eb-1dd8-99e9a315b304\nmd\"\"\"## Random Words\n\nTo choose a random word from the histogram, the simplest algorithm is to build an array with multiple copies of each word, according to the observed frequency, and then choose from the array:\n\n```julia\nfunction randomword(h) \n\tt=[]\n\tfor (word, freq) in h \n\t\tfor i in 1:freq\n\t\t\tpush!(t, word) \n\t\tend\n\tend\n\trand(t) \nend\n```\n\nThis algorithm works, but it is not very efficient; each time you choose a random word it rebuilds the array, which is as big as the original book. An obvious improvement is to build the array once and then make multiple selections, but the array is still big.\n\nAn alternative is:\n\n1. Use `keys` to get an array of the words in the book.\n2. Build an array that contains the cumulative sum of the word frequencies (see “Exercise 10-2”). The last item in this array is the total number of words in the book, *n*.\n3. Choose a random number from 1 to *n*. Use a bisection search (see “Exercise 10-10”) to find the index where the random number would be inserted in the cumulative sum.\n4. Use the index to find the corresponding word in the word array.\n\n\n#### Exercise 13-7\n\nWrite a program that uses this algorithm to choose a random word from the book.\n\"\"\"\n\n# ╔═╡ e697de38-89ba-11eb-0e7c-cb53a52eb709\nmd\"\"\"## Markov Analysis\n\nIf you choose words from the book at random, you can get a sense of the vocabulary, but you probably won’t get a sentence:\n\n```\nthis the small regard harriet which knightley's it most things\n```\n\nA series of random words seldom makes sense because there is no relationship between successive words. For example, in a real sentence you would expect an article like “the” to be followed by an adjective or a noun, and probably not a verb or adverb.\n\nOne way to measure these kinds of relationships is Markov analysis, which character‐ izes, for a given sequence of words, the probability of the words that might come next. For example, the song “Eric, the Half a Bee” (by Monty Python) begins:\n\n> Half a bee, philosophically, \n> \n> Must, ipso facto, half not be. \n> \n> But half the bee has got to be \n> \n> Vis a vis, its entity. D’you see?\n> \n> But can a bee be said to be\n> \n> Or not to be an entire bee \n> \n> When half the bee is not a bee \n> \n> Due to some ancient injury?\n\nIn this text, the phrase “half the” is always followed by the word “bee,” but the phrase “the bee” might be followed by either “has” or “is.”\n\nThe result of Markov analysis is a mapping from each prefix (like “half the” and “the bee”) to all possible suffixes (like “has” and “is”).\n\nGiven this mapping, you can generate random text by starting with any prefix and choosing at random from the possible suffixes. Next, you can combine the end of the prefix and the new suffix to form the next prefix, and repeat.\n\nFor example, if you start with the prefix “Half a,” then the next word has to be “bee,” because the prefix only appears once in the text. The next prefix is “a bee,” so the next suffix might be “philosophically,” “be,” or “due.”\n\nIn this example the length of the prefix is always 2, but you can do Markov analysis with any prefix length.\n\n#### Exercise 13-8\n\nGive Markov analysis a try.\n\n1. Write a program to read text from a file and perform Markov analysis. The result should be a dictionary that maps from prefixes to a collection of possible suffixes. The collection might be an array, tuple, or dictionary; it is up to you to make an appropriate choice. You can test your program with prefix length 2, but you should write the program in a way that makes it easy to try other lengths.\n2. Add a function to the previous program to generate random text based on the Markov analysis. Here is an example from *Emma* with prefix length 2:\n > “He was very clever, be it sweetness or be angry, ashamed or only amused, at such a stroke. She had never thought of Hannah till you were never meant for me?” “I cannot make speeches, Emma:” he soon cut it all himself.”\n For this example, I left the punctuation attached to the words. The result is almost syntactically correct, but not quite. Semantically, it almost makes sense, but not quite.\n What happens if you increase the prefix length? Does the random text make more sense?\n3. Once your program is working, you might want to try a mash-up: if you combine text from two or more books, the random text you generate will blend the vocabulary and phrases from the sources in interesting ways.\n\n*Credit*: This case study is based on an example from The Practice of Programming by Brian Kernighan and Rob Pike (Addison-Wesley).\n\n!!! tip\n You should attempt this exercise before you go on.\n\"\"\"\n\n# ╔═╡ aa416bf8-89bb-11eb-00ce-1dadb76ecfc1\nmd\"\"\"## Data Structures\n\nUsing Markov analysis to generate random text is fun, but there is also a point to this exercise: data structure selection. In completing the previous exercise, you had to choose:\n\n* How to represent the prefixes\n* How to represent the collection of possible suffixes\n* How to represent the mapping from each prefix to the collection of possible suffixes\n\nThe last one is easy: a dictionary is the obvious choice for a mapping from keys to corresponding values.\n\nFor the prefixes, the most obvious options are a string, array of strings, or tuple of strings.\n\nFor the suffixes, one option is an array; another is a histogram (dictionary).\n\nHow should you choose? The first step is to think about the operations you will need to implement for each data structure. For the prefixes, you need to be able to remove words from the beginning and add to the end. For example, if the current prefix is “Half a,” and the next word is “bee,” you need to be able to form the next prefix, “a bee.”\n\nYour first choice might be an array, since it is easy to add and remove elements.\n\nFor the collection of suffixes, the operations you need to perform include adding a new suffix (or increasing the frequency of an existing one) and choosing a random suffix.\n\nAdding a new suffix is equally easy for the array implementation or the histogram. Choosing a random element from an array is easy; choosing from a histogram is harder to do efficiently (see “Exercise 13-7”).\n\nSo far we have been talking mostly about ease of implementation, but there are other factors to consider in choosing data structures. One is runtime. Sometimes there is a theoretical reason to expect one data structure to be faster than another; for example, I mentioned that the in operator is faster for dictionaries than for arrays, at least when the number of elements is large.\n\nBut often you don’t know ahead of time which implementation will be faster. One option is to implement both of them and see which is better. This approach is called benchmarking. A practical alternative is to choose the data structure that is easiest to implement, and then see if it is fast enough for the intended application. If so, there is no need to go on. If not, there are tools, like the Profile module, that can identify the places in a program that take the most time.\n\nThe other factor to consider is storage space. For example, using a histogram for the collection of suffixes might take less space because you only have to store each word once, no matter how many times it appears in the text. In some cases, saving space can also make your program run faster, and in the extreme, your program might not run at all if you run out of memory. But for many applications, space is a secondary consideration after runtime.\n\nOne final thought: in this discussion, I have implied that you should use one data structure for both analysis and generation. But since these are separate phases, it would also be possible to use one structure for analysis and then convert to another structure for generation. This would be a net win if the time saved during generation exceeded the time spent in conversion.\n\n!!! tip\n The Julia package `DataStructures` implements a variety of data structures that are tailored to specific problems, such as an ordered dictionary whose entries can be iterated over deterministically.\n\"\"\"\n\n# ╔═╡ 34c48de6-89bc-11eb-2f60-0de81d83b233\nmd\"\"\"## Debugging\nWhen you are debugging a program, and especially if you are working on a hard bug, there are five things to try:\n\n*Reading*:\nExamine your code, read it back to yourself, and check that it says what you meant to say.\n\n*Running*:\nExperiment by making changes and running different versions. Often if you dis‐ play the right thing at the right place in the program, the problem becomes obvi‐ ous, but sometimes you have to build scaffolding.\n\n*Ruminating*:\nTake some time to think! What kind of error is it: syntax, runtime, or semantic? What information can you get from the error messages, or from the output of the program? What kind of error could cause the problem you’re seeing? What did you change last, before the problem appeared?\n\n*Rubberducking*:\nIf you explain the problem to someone else, you sometimes find the answer before you finish asking the question. Often you don’t need the other person; you could just talk to a rubber duck. And that’s the origin of the well-known strategy called rubber duck debugging. I’m not making this up!\n\n*Retreating*:\nAt some point, the best thing to do is back off, undoing recent changes, until you get back to a program that works and that you understand. Then you can start rebuilding.\n\nBeginning programmers sometimes get stuck on one of these activities and forget the others. Each activity comes with its own failure mode.\n\nFor example, reading your code might help if the problem is a typographical error, but not if the problem is a conceptual misunderstanding. If you don’t understand what your program does, you can read it 100 times and never see the error, because the error is in your head.\n\nRunning experiments can help, especially if you run small, simple tests. But if you run experiments without thinking or reading your code, you might fall into a pattern I call “random walk programming,” which is the process of making random changes until the program does the right thing. Needless to say, random walk programming can take a long time.\n\nYou have to take time to think. As I’ve said already, debugging is like an experimental science. You should have at least one hypothesis about what the problem is. If there are two or more possibilities, try to think of a test that would eliminate one of them.\n\nBut even the best debugging techniques will fail if there are too many errors, or if the code you are trying to fix is too big and complicated. Sometimes the best option is to retreat, simplifying the program until you get to something that works and that you understand.\n\nBeginning programmers are often reluctant to retreat because they can’t stand to delete a line of code (even if it’s wrong). If it makes you feel better, copy your program into another file before you start stripping it down. Then you can copy the pieces back one at a time.\n\nFinding a hard bug requires reading, running, ruminating, and sometimes retreating. If you get stuck on one of these activities, try the others.\n\"\"\"\n\n# ╔═╡ 6a8e4a20-89bc-11eb-149c-ed4f0c5d3697\nmd\"\"\"## Glossary\n\n*deterministic*:\nPertaining to a program that does the same thing each time it runs, given the same inputs.\n\n*pseudorandom*:\nPertaining to a sequence of numbers that appears to be random, but is generated by a deterministic program.\n\n*default value*:\nThe value given to an optional parameter if no argument is provided.\n\n*override*:\nTo replace a default value with an argument.\n\n*benchmarking*:\nThe process of choosing between data structures by implementing alternatives and testing them on a sample of the possible inputs.\n\n*rubberducking*:\nDebugging by explaining your problem to an inanimate object such as a rubber duck. Articulating the problem can help you solve it, even if the rubber duck doesn’t know Julia.\n\"\"\"\n\n# ╔═╡ 97b91802-89bc-11eb-1adc-856eeae921ab\nmd\"\"\"## Exercises Exercise 13-9\n\nThe “rank” of a word is its position in an array of words sorted by frequency: the most common word has rank 1, the second most common has rank 2, etc.\n\n[Zipf’s law](https://en.wikipedia.org/wiki/Zipf%27s_law) describes a relationship between the ranks and frequencies of words in natural languages. Specifically, it predicts that the frequency, ``f`` , of the word with rank ``r`` is:\n\n```math\nf = cr^{−s}\n```\n\nwhere ``s`` and ``c`` are parameters that depend on the language and the text. If you take the logarithm of both sides of this equation, you get: \n\n```math\n\\log f = \\log c − s \\log r\n```\n\nSo if you plot ``\\log f`` versus ``\\log r``, you should get a straight line with slope −``s`` and intercept ``\\log c``.\n\nWrite a program that reads a text from a file, counts word frequencies, and prints one line for each word, in descending order of frequency, with ``\\log f`` and ``\\log r``.\n\nInstall a plotting library:\n\n```julia\njulia> using Pkg\n\njulia> pkg\"add Plots\"\n```\n\nIts usage is very easy:\n```julia\n\njulia> using Plots \n\njulia> x = 1:10; \n\njulia> y = x.^2; \n\njulia> plot(x, y)\n```\n\nUse the Plots library to plot the results and check whether they form a straight line.\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─e00967d0-89b4-11eb-031d-c128221e86e1\n# ╟─f2f3ba34-89b3-11eb-2577-83e1dcfdc1fc\n# ╟─def6b6fc-89b4-11eb-2e66-b5cc3e72779d\n# ╟─9016b5ea-89b5-11eb-062f-b59a784f61da\n# ╟─86793ed0-89b6-11eb-1759-cfa1ea349a6b\n# ╟─00bea97c-89b8-11eb-23a1-db0c7d6c7bd1\n# ╟─87a74886-89b8-11eb-29aa-a9c5075a1f95\n# ╟─d5579180-89b8-11eb-27ec-d1b4e811c3cb\n# ╟─4ee3d86e-89ba-11eb-1dd8-99e9a315b304\n# ╟─e697de38-89ba-11eb-0e7c-cb53a52eb709\n# ╟─aa416bf8-89bb-11eb-00ce-1dadb76ecfc1\n# ╟─34c48de6-89bc-11eb-2f60-0de81d83b233\n# ╟─6a8e4a20-89bc-11eb-149c-ed4f0c5d3697\n# ╟─97b91802-89bc-11eb-1adc-856eeae921ab\n", "meta": {"hexsha": "cfe8959f70ae22b13f87fac58392c4e2b3d640d1", "size": 23156, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Lectures/Lecture13.jl", "max_stars_repo_name": "BenLauwens/ES123", "max_stars_repo_head_hexsha": "8531db895a8d4555e63219d79d4dcc527a685458", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2018-03-07T18:04:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-10T15:07:23.000Z", "max_issues_repo_path": "Lectures/Lecture13.jl", "max_issues_repo_name": "BenLauwens/ES123", "max_issues_repo_head_hexsha": "8531db895a8d4555e63219d79d4dcc527a685458", "max_issues_repo_licenses": ["MIT"], "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/Lecture13.jl", "max_forks_repo_name": "BenLauwens/ES123", "max_forks_repo_head_hexsha": "8531db895a8d4555e63219d79d4dcc527a685458", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-08-12T05:29:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-02T21:38:27.000Z", "avg_line_length": 45.1384015595, "max_line_length": 479, "alphanum_fraction": 0.7548367594, "num_tokens": 5969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.5, "lm_q2_score": 0.2689414213699951, "lm_q1q2_score": 0.13447071068499755}}
{"text": "# Basic properties and constants related to molecular models\n\nmodule Properties\n\nusing ..Dorothy\nusing ..Dorothy.Utils\n\nexport\n\t\tstandard_atomic_weights, covalent_radii, vertebrate_aa_frequencies,\n\n\t\twrapid, unwrapids!, unwrapnames!,\n\n\t\tnamematcher, isvsite, iswater, isprotein, isacidresidue, isbasicresidue,\n\t\tischargedresidue, ispolarresidue, ishydrophobicresidue, isbackbone,\n\t\tismainchain, issidechain, isnuclacid, islipid, ision, ismonatomicion,\n\t\tispolyatomicion, isalphahelix, ishelix310, ispihelix, isturn, isstrand,\n\t\tisbridge, iscoil, isbend, ishelix, issheet, isloop\n\n# J. Meija et al. Pure Appl. Chem., 88(3):265-91, 2016.\n# doi:10.1515/pac-2015-0305\nconst standard_atomic_weights = Dict(\n\t\t\"H\" => 1.008,\n\t\t\"He\" => 4.002,\n\t\t\"Li\" => 6.94,\n\t\t\"Be\" => 9.012,\n\t\t\"B\" => 10.81,\n\t\t\"C\" => 12.01,\n\t\t\"N\" => 14.00,\n\t\t\"O\" => 15.99,\n\t\t\"F\" => 18.99,\n\t\t\"Ne\" => 20.18,\n\t\t\"Na\" => 22.99,\n\t\t\"Mg\" => 24.30,\n\t\t\"Al\" => 26.98,\n\t\t\"Si\" => 28.08,\n\t\t\"P\" => 30.97,\n\t\t\"S\" => 32.06,\n\t\t\"Cl\" => 35.45,\n\t\t\"Ar\" => 39.94,\n\t\t\"K\" => 39.09,\n\t\t\"Ca\" => 40.07,\n\t\t\"Sc\" => 44.95,\n\t\t\"Ti\" => 47.86,\n\t\t\"V\" => 50.94,\n\t\t\"Cr\" => 51.99,\n\t\t\"Mn\" => 54.93,\n\t\t\"Fe\" => 55.84,\n\t\t\"Co\" => 58.93,\n\t\t\"Ni\" => 58.69,\n\t\t\"Cu\" => 63.54,\n\t\t\"Zn\" => 65.38,\n\t\t\"Ga\" => 69.72,\n\t\t\"Ge\" => 72.63,\n\t\t\"As\" => 74.92,\n\t\t\"Se\" => 78.97,\n\t\t\"Br\" => 79.90,\n\t\t\"Kr\" => 83.79,\n\t\t\"Rb\" => 85.46,\n\t\t\"Sr\" => 87.62,\n\t\t\"Y\" => 88.90,\n\t\t\"Zr\" => 91.22,\n\t\t\"Nb\" => 92.90,\n\t\t\"Mo\" => 95.95,\n\t\t\"Ru\" => 101.0,\n\t\t\"Rh\" => 102.9,\n\t\t\"Pd\" => 106.4,\n\t\t\"Ag\" => 107.8,\n\t\t\"Cd\" => 112.4,\n\t\t\"In\" => 114.8,\n\t\t\"Sn\" => 118.7,\n\t\t\"Sb\" => 121.7,\n\t\t\"Te\" => 127.6,\n\t\t\"I\" => 126.9,\n\t\t\"Xe\" => 131.2,\n\t\t\"Cs\" => 132.9,\n\t\t\"Ba\" => 137.3,\n\t\t\"La\" => 138.9,\n\t\t\"Ce\" => 140.1,\n\t\t\"Pr\" => 140.9,\n\t\t\"Nd\" => 144.2,\n\t\t\"Sm\" => 150.3,\n\t\t\"Eu\" => 151.9,\n\t\t\"Gd\" => 157.2,\n\t\t\"Tb\" => 158.9,\n\t\t\"Dy\" => 162.5,\n\t\t\"Ho\" => 164.9,\n\t\t\"Er\" => 167.2,\n\t\t\"Tm\" => 168.9,\n\t\t\"Yb\" => 173.0,\n\t\t\"Lu\" => 174.9,\n\t\t\"Hf\" => 178.4,\n\t\t\"Ta\" => 180.9,\n\t\t\"W\" => 183.8,\n\t\t\"Re\" => 186.2,\n\t\t\"Os\" => 190.2,\n\t\t\"Ir\" => 192.2,\n\t\t\"Pt\" => 195.0,\n\t\t\"Au\" => 196.9,\n\t\t\"Hg\" => 200.5,\n\t\t\"Tl\" => 204.3,\n\t\t\"Pb\" => 207.2,\n\t\t\"Bi\" => 208.9,\n\t\t\"Th\" => 232.0,\n\t\t\"Pa\" => 231.0,\n\t\t\"U\" => 238.03)\n\n# B. Cordero et al. Dalton Trans., (21):2832-8, 2008. doi:0.1039/b801115j\nconst covalent_radii = Dict(\n\t\"H\" => 0.31,\n\t\"He\" => 0.28,\n\t\"Li\" => 1.28,\n\t\"Be\" => 0.96,\n\t\"B\" => 0.84,\n\t\"C\" => 0.76,\n\t\"N\" => 0.71,\n\t\"O\" => 0.66,\n\t\"F\" => 0.57,\n\t\"Ne\" => 0.58,\n\t\"Na\" => 1.66,\n\t\"Mg\" => 1.41,\n\t\"Al\" => 1.21,\n\t\"Si\" => 1.11,\n\t\"P\" => 1.07,\n\t\"S\" => 1.05,\n\t\"Cl\" => 1.02,\n\t\"Ar\" => 1.06,\n\t\"K\" => 2.03,\n\t\"Ca\" => 1.76,\n\t\"Sc\" => 1.70,\n\t\"Ti\" => 1.60,\n\t\"V\" => 1.53,\n\t\"Cr\" => 1.39,\n\t\"Mn\" => 1.39,\n\t\"Fe\" => 1.32,\n\t\"Co\" => 1.26,\n\t\"Ni\" => 1.24,\n\t\"Cu\" => 1.32,\n\t\"Zn\" => 1.22,\n\t\"Ga\" => 1.22,\n\t\"Ge\" => 1.20,\n\t\"As\" => 1.19,\n\t\"Se\" => 1.20,\n\t\"Br\" => 1.20,\n\t\"Kr\" => 1.16,\n\t\"Rb\" => 2.20,\n\t\"Sr\" => 1.95,\n\t\"Y\" => 1.90,\n\t\"Zr\" => 1.75,\n\t\"Nb\" => 1.64,\n\t\"Mo\" => 1.54,\n\t\"Tc\" => 1.47,\n\t\"Ru\" => 1.46,\n\t\"Rh\" => 1.42,\n\t\"Pd\" => 1.39,\n\t\"Ag\" => 1.45,\n\t\"Cd\" => 1.44,\n\t\"In\" => 1.42,\n\t\"Sn\" => 1.39,\n\t\"Sb\" => 1.39,\n\t\"Te\" => 1.38,\n\t\"I\" => 1.39,\n\t\"Xe\" => 1.40,\n\t\"Cs\" => 2.44,\n\t\"Ba\" => 2.15,\n\t\"La\" => 2.07,\n\t\"Ce\" => 2.04,\n\t\"Pr\" => 2.03,\n\t\"Nd\" => 2.01,\n\t\"Pm\" => 1.99,\n\t\"Sm\" => 1.98,\n\t\"Eu\" => 1.98,\n\t\"Gd\" => 1.96,\n\t\"Tb\" => 1.94,\n\t\"Dy\" => 1.92,\n\t\"Ho\" => 1.92,\n\t\"Er\" => 1.89,\n\t\"Tm\" => 1.90,\n\t\"Yb\" => 1.87,\n\t\"Lu\" => 1.87,\n\t\"Hf\" => 1.75,\n\t\"Ta\" => 1.70,\n\t\"W\" => 1.62,\n\t\"Re\" => 1.51,\n\t\"Os\" => 1.44,\n\t\"Ir\" => 1.41,\n\t\"Pt\" => 1.36,\n\t\"Au\" => 1.36,\n\t\"Hg\" => 1.32,\n\t\"Tl\" => 1.45,\n\t\"Pb\" => 1.46,\n\t\"Bi\" => 1.48,\n\t\"Po\" => 1.40,\n\t\"At\" => 1.50,\n\t\"Rn\" => 1.50,\n\t\"Fr\" => 2.60,\n\t\"Ra\" => 2.21,\n\t\"Ac\" => 2.15,\n\t\"Th\" => 2.06,\n\t\"Pa\" => 2.00,\n\t\"U\" => 1.96,\n\t\"Np\" => 1.90,\n\t\"Pu\" => 1.87,\n\t\"Am\" => 1.80,\n\t\"Cm\" => 1.69)\n\n# J.L. King, T.H. Jukes. Science, 164(3881):788-98, 1969.\n# doi:10.1126/science.164.3881.788\nconst vertebrate_aa_frequencies = Dict(\n\t\t\"ALA\" => 0.74,\n\t\t\"ARG\" => 0.42,\n\t\t\"ASN\" => 0.44,\n\t\t\"ASP\" => 0.59,\n\t\t\"CYS\" => 0.33,\n\t\t\"GLU\" => 0.58,\n\t\t\"GLN\" => 0.37,\n\t\t\"GLY\" => 0.74,\n\t\t\"HIS\" => 0.29,\n\t\t\"ILE\" => 0.38,\n\t\t\"LEU\" => 0.76,\n\t\t\"LYS\" => 0.72,\n\t\t\"MET\" => 0.18,\n\t\t\"PHE\" => 0.40,\n\t\t\"PRO\" => 0.50,\n\t\t\"SER\" => 0.81,\n\t\t\"THR\" => 0.62,\n\t\t\"TRP\" => 0.13,\n\t\t\"TYR\" => 0.33,\n\t\t\"VAL\" => 0.68)\n\nfunction wrapid(id::Integer, max::Integer)\n\twhile id > max\n\t\tid -= max + 1\n\tend\n\tid\nend\n\nfunction unwrapids!(ids::AbstractVector{<:Integer}, max::Integer)\n\toffset = 0\n\tatzero = false\n\tfor i in eachindex(ids)\n\t\tif ids[i] == 0\n\t\t\tif ! atzero\n\t\t\t\toffset += max + 1\n\t\t\tend\n\t\t\tatzero = true\n\t\telse\n\t\t\tatzero = false\n\t\tend\n\t\tids[i] += offset\n\tend\n\tids\nend\n\nfunction unwrapnames!(names::AbstractVector{<:AbstractString})\n\tfor i in eachindex(names)\n\t\tname = names[i]\n\t\tif length(name) > 0 && isdigit(first(name))\n\t\t\tnames[i] = chop(name, head=1, tail=0) * first(name)\n\t\tend\n\tend\n\tnames\nend\n\nfunction namematcher(pattern::AbstractString)\n\tIstar = findall(==('*'), pattern)\n\tnstars = length(Istar)\n\tif nstars == 0\n\t\t==(pattern)\n\telseif nstars == 1\n\t\tif length(pattern) == 1\n\t\t\tname -> true\n\t\telse\n\t\t\tif Istar[1] == 1\n\t\t\t\tsuffix = chop(pattern, head=1, tail=0)\n\t\t\t\tname -> endswith(name, suffix)\n\t\t\telseif Istar[1] == length(pattern)\n\t\t\t\tprefix = chop(pattern)\n\t\t\t\tname -> startswith(name, prefix)\n\t\t\telse\n\t\t\t\terror(\"wildcard * may only appear at start or end\")\n\t\t\tend\n\t\tend\n\telseif nstars == 2\n\t\tif Istar[1] != 1 || Istar[2] != length(pattern)\n\t\t\terror(\"wildcard * may only appear at start or end\")\n\t\telse\n\t\t\tname -> occursin(name, pattern)\n\t\tend\n\telse\n\t\terror(\"wildcard * may only appear at start or end\")\n\tend\nend\n\nfunction namematcher(S::AbstractVector{<:AbstractString})\n\tF = [namematcher(s) for s in S]\n\tfunction (name)\n\t\tfor f in F\n\t\t\tif f(name)\n\t\t\t\treturn true\n\t\t\tend\n\t\tend\n\t\tfalse\n\tend\nend\n\nconst vsite_name_pattern = [\"MC*\", \"MN*\", \"MTRP*\", \"MW\", \"LP\"]\n\nconst water_resname_pattern = [\"HOH\", \"SOL\", \"TIP*\", \"WAT*\"]\n\nconst acid_protein_resname_pattern = [\"ASP\", \"GLU\"]\n\nconst basic_protein_resname_pattern = [\"ARG\", \"LYS\"]\n\nconst charged_protein_resname_pattern =\n\t\t[acid_protein_resname_pattern..., basic_protein_resname_pattern...]\n\nconst polar_protein_resname_pattern =\n\t\t[\"ASN\", \"CYS\", \"GLN\", \"HIS\", \"SER\", \"THR\", \"TRP\", \"TYR\"]\n\nconst hydrophobic_protein_resname_pattern =\n\t\t[\"ALA\", \"GLY\", \"ILE\", \"LEU\", \"MET\", \"PHE\", \"PRO\", \"VAL\"]\n\nconst protein_resname_pattern =\n\t\t[charged_protein_resname_pattern...,\n\t\t polar_protein_resname_pattern...,\n\t\t hydrophobic_protein_resname_pattern...]\n\nconst backbone_name_pattern = [\"N\", \"CA\", \"C\"]\n\nconst mainchain_name_pattern =\n\t\t[\"H1\", \"H2\", \"H3\", \"N\", \"H\", \"CA\", \"C\", \"O\", \"OC1\", \"OC2\", \"OXT\"]\n\nconst nuclacid_resname_pattern = [\"A\", \"C\", \"G\", \"U\", \"DA\", \"DC\", \"DG\", \"DT\"]\n\nconst lipid_resname_pattern = [\"D3PC\", \"DLPC\", \"DLPE\", \"DLPG\", \"DMPA\", \"DMPC\",\n\t\t\"DMPG\", \"DOPC\", \"DOPE\", \"DOPG\", \"DOPS\", \"DPPC\", \"DPPE\", \"DPPG\", \"DPPS\",\n\t\t\"DSPG\", \"POPC\", \"POPE\", \"POPG\", \"POPS\"]\n\nconst monatomic_ion_resname_pattern = [\"NA\", \"CL\", \"CA\", \"MG\", \"K\", \"RB\", \"CS\",\n\t\t\"LI\", \"ZN\", \"H\", \"SR\", \"BA\", \"AL\", \"AG\", \"FE\", \"CU\", \"F\", \"BR\", \"I\",\n\t\t\"O\", \"S\", \"N\", \"P\"]\n\nconst polyatomic_ion_resname_pattern =\n\t\t[\"CN\", \"CO3\", \"NO2\", \"NO3\", \"O2\", \"OH\", \"PO3\", \"PO4\", \"SO3\", \"SO4\"]\n\nconst ion_resname_pattern =\n\t\t[monatomic_ion_resname_pattern..., polyatomic_ion_resname_pattern...]\n\nconst helix_ss_pattern = [\"H\", \"G\", \"I\", \"T\"]\nconst sheet_ss_pattern = [\"E\", \"B\"]\nconst loop_ss_pattern = [\"C\", \"S\"]\n\nconst isvsite = namematcher(vsite_name_pattern)\n\nconst iswater = namematcher(water_resname_pattern)\n\nconst isprotein = namematcher(sort(protein_resname_pattern,\n\t\tby=(resname -> vertebrate_aa_frequencies[resname])))\n\nconst isacidresidue = namematcher(sort(acid_protein_resname_pattern,\n\t\tby=(resname -> vertebrate_aa_frequencies[resname])))\n\nconst isbasicresidue = namematcher(sort(basic_protein_resname_pattern,\n\t\tby=(resname -> vertebrate_aa_frequencies[resname])))\n\nconst ischargedresidue = namematcher(sort(charged_protein_resname_pattern,\n\t\tby=(resname -> vertebrate_aa_frequencies[resname])))\n\nconst ispolarresidue = namematcher(sort(polar_protein_resname_pattern,\n\t\tby=(resname -> vertebrate_aa_frequencies[resname])))\n\nconst ishydrophobicresidue =\n\t\tnamematcher(sort(hydrophobic_protein_resname_pattern,\n\t\tby=(resname -> vertebrate_aa_frequencies[resname])))\n\nconst isbackbonename = namematcher(backbone_name_pattern)\n\nisbackbone(name, resname) = isbackbonename(name) && isprotein(resname)\n\nconst ismainchainname = namematcher(mainchain_name_pattern)\n\nismainchain(name, resname) = ismainchainname(name) && isprotein(resname)\n\nissidechain(name, resname) = !ismainchainname(name) && isprotein(resname)\n\nconst isnuclacid = namematcher(nuclacid_resname_pattern)\n\nconst islipid = namematcher(lipid_resname_pattern)\n\nconst ision = namematcher(ion_resname_pattern)\n\nconst ismonatomicion = namematcher(monatomic_ion_resname_pattern)\n\nconst ispolyatomicion = namematcher(polyatomic_ion_resname_pattern)\n\nconst ishelix = namematcher(helix_ss_pattern)\n\nconst isalphahelix = namematcher(\"H\")\n\nconst ishelix310 = namematcher(\"G\")\n\nconst ispihelix = namematcher(\"I\")\n\nconst isturn = namematcher(\"T\")\n\nconst issheet = namematcher(sheet_ss_pattern)\n\nconst isstrand = namematcher(\"E\")\n\nconst isbridge = namematcher(\"B\")\n\nconst isloop = namematcher(loop_ss_pattern)\n\nconst iscoil = namematcher(\"C\")\n\nconst isbend = namematcher(\"S\")\n\nend # module\n", "meta": {"hexsha": "d08db2dccd1a8c44a6ee98444e2439e082e98dae", "size": 9198, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/properties.jl", "max_stars_repo_name": "ofisette/Dorothy.jl", "max_stars_repo_head_hexsha": "5dab0596434423137e9bce01c2e9648826770d0c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/properties.jl", "max_issues_repo_name": "ofisette/Dorothy.jl", "max_issues_repo_head_hexsha": "5dab0596434423137e9bce01c2e9648826770d0c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/properties.jl", "max_forks_repo_name": "ofisette/Dorothy.jl", "max_forks_repo_head_hexsha": "5dab0596434423137e9bce01c2e9648826770d0c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.9522673031, "max_line_length": 79, "alphanum_fraction": 0.5790389215, "num_tokens": 4060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.24508502416032485, "lm_q1q2_score": 0.13304766087208672}}
{"text": "### A Pluto.jl notebook ###\n# v0.16.0\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 4109a39c-00b7-4954-bb73-35407f82a6f7\nusing Pkg; Pkg.activate(\"..\")\n\n# ╔═╡ 24b76a7c-63dd-11eb-1b78-d5a20557e5cd\n# edit the code below to set your name and UGent username\n\nstudent = (name = \"Jim Janssen\", email = \"Jim.Janssen@UGent.be\");\n\n# press the ▶ button in the bottom right of this cell to run your edits\n# or use Shift+Enter\n\n# you might need to wait until all other cells in this notebook have completed running. \n# scroll down the page to see what's up\n\n# ╔═╡ 446c3e4e-63dd-11eb-3300-fb006008ff1f\nbegin \n\tusing DSJulia;\n\tusing PlutoUI;\n\ttracker = ProgressTracker(student.name, student.email);\n\tmd\"\"\"\n\n\tSubmission by: **_$(student.name)_**\n\t\"\"\"\nend\n\n# ╔═╡ 5368424c-63dd-11eb-3a1b-05a61e266d2b\nmd\"\"\"\n# Additional exercises for basics\n\nFirst of all, welcome to these additional exercises, **$(student[:name])**!\n\nThis exercise is based on [the advent of code](https://adventofcode.com/), a yearly programming challenge during the advent period.\n\"\"\"\n\n# ╔═╡ 6c0f2d10-63dd-11eb-2c17-fddf9cd51bfe\nmd\"\"\"## 1. Trajecting trajectories\n\nSuppose you find yourself on top of a snowy mountain, sparsely covered with trees. You want to reach the bottom of the mountain using your sled, but the situation you find yourself in is certainly not safe: there's very minimal steering and the area is covered in trees. You'll need to see which angles will take you near the fewest trees.\n\nDue to the local geology, trees in this area only grow on exact integer coordinates in a grid. You make a map (this will serve as the input later) of the open squares (.) and trees (#) you can see. For example:\n\n```\n..##.......\n#...#...#..\n.#....#..#.\n..#.#...#.#\n.#...##..#.\n..#.##.....\n.#.#.#....#\n.#........#\n#.##...#...\n#...##....#\n.#..#...#.#\n```\n\nThese aren't the only trees, though; due to something you read about once involving arboreal genetics and biome stability, the same pattern repeats to the right many times 🤯️:\n\n```\n..##.........##.........##.........##.........##.........##....... --->\n#...#...#..#...#...#..#...#...#..#...#...#..#...#...#..#...#...#..\n.#....#..#..#....#..#..#....#..#..#....#..#..#....#..#..#....#..#.\n..#.#...#.#..#.#...#.#..#.#...#.#..#.#...#.#..#.#...#.#..#.#...#.#\n.#...##..#..#...##..#..#...##..#..#...##..#..#...##..#..#...##..#.\n..#.##.......#.##.......#.##.......#.##.......#.##.......#.##..... --->\n.#.#.#....#.#.#.#....#.#.#.#....#.#.#.#....#.#.#.#....#.#.#.#....#\n.#........#.#........#.#........#.#........#.#........#.#........#\n#.##...#...#.##...#...#.##...#...#.##...#...#.##...#...#.##...#...\n#...##....##...##....##...##....##...##....##...##....##...##....#\n.#..#...#.#.#..#...#.#.#..#...#.#.#..#...#.#.#..#...#.#.#..#...#.# --->\n```\n\nYou start on the open square `(.)` in the top-left corner and need to reach the bottom (below the bottom-most row on your map).\n\nYour sled can only follow a few specific slopes (you opted for a cheaper model that prefers rational numbers); start by counting all the trees you would encounter for the slope right 3, down 1:\n\nFrom your starting position at the top-left, check the position that is right 3 and down 1. Then, check the position that is right 3 and down 1 from there, and so on until you go past the bottom of the map.\n\nThe locations you would check in the above example are marked here with `O` where there was an open square and `X` where there was a tree:\n\n```\n..##.........##.........##.........##.........##.........##....... --->\n#..O#...#..#...#...#..#...#...#..#...#...#..#...#...#..#...#...#..\n.#....X..#..#....#..#..#....#..#..#....#..#..#....#..#..#....#..#.\n..#.#...#O#..#.#...#.#..#.#...#.#..#.#...#.#..#.#...#.#..#.#...#.#\n.#...##..#..X...##..#..#...##..#..#...##..#..#...##..#..#...##..#.\n..#.##.......#.X#.......#.##.......#.##.......#.##.......#.##..... --->\n.#.#.#....#.#.#.#.O..#.#.#.#....#.#.#.#....#.#.#.#....#.#.#.#....#\n.#........#.#........X.#........#.#........#.#........#.#........#\n#.##...#...#.##...#...#.X#...#...#.##...#...#.##...#...#.##...#...\n#...##....##...##....##...#X....##...##....##...##....##...##....#\n.#..#...#.#.#..#...#.#.#..#...X.#.#..#...#.#.#..#...#.#.#..#...#.# --->\n```\n\nIn this example, traversing the map using this slope would cause you to encounter 7 trees.\n\n\"\"\"\n\n# ╔═╡ e1259736-63df-11eb-0010-3f2fc5719596\nmd\"\"\"\nLet us first give you a hand with the data input:\n\"\"\"\n\n# ╔═╡ 36e51b02-63df-11eb-34a5-39e6e0650541\nbegin\n\tdownload(\"https://gist.githubusercontent.com/DaanVanHauwermeiren/2b02f275eef08643acfbf8fa9e9e4097/raw/e4e68d69d9c54a9b33a319d7b56dc8daf83fea5b/data.txt\", \"map.txt\")\n\t\n\tfunction parse_input(input)\n\t\tlines = split(input, \"\\n\")\n\t\tm = length(first(lines))\n\t\t#return [l[j]=='#' for l in lines, j in 1:m]\n\t\treturn [l[j] for l in lines, j in 1:m]\n\tend\n\t\n\tmap = read(\"map.txt\", String) |> rstrip |> parse_input;\nend\n\n# ╔═╡ e677ca7e-63df-11eb-186b-8d20826ec916\nmap\n\n# ╔═╡ c34af248-63e3-11eb-2bfd-898ef2cfbea5\nmd\"## Questions\"\n\n# ╔═╡ 4b4bbeb8-63e2-11eb-0ea2-6de494f61dc1\nbegin\n\t# this is where you start\n\tx, y = 1, 1\n\t# how big is the mountain?\n\tn, m = size(map)\n\t# you start your tree hitting counter at zero of course!\n \tn_trees = 0\n\t\n\t# go over the mountain and count the trees!\n\t\n\tn_trees = missing\nend\n\n# ╔═╡ dcac803a-648d-11eb-21f2-d72e56528e92\n\n\n# ╔═╡ fb39928c-63e2-11eb-2b85-15044c04fbe6\nproduct_all_trees = missing\n\n# ╔═╡ ede6342c-648d-11eb-0712-836637408e53\n\n\n# ╔═╡ b9e97832-63e3-11eb-0e39-b5c9129eabbe\nmd\"## Overly engineered solution to these questions showcasing the 💪️ of Julia\"\n\n# ╔═╡ 9c015578-648e-11eb-0768-d1e5edb4f65f\nmd\"This is already some advanced use of Julia, so do not worry if this is not yet fully clear. You will learn about this later in this course.\"\n\n# ╔═╡ f0f0da0a-63e3-11eb-2065-838c77fc57a6\nbegin\n\tqalt = Question(;\n\t\t\tdescription=md\"\"\"\n\t\tThe alternative solutions makes use of the fact that the boundaries are circular. As an example, this would be valid:\n\t\t```julia\n\t\tA = ['a', 'b', 'c']\n\t\tA[1] == A[4] == A[7]\n\t\t```\n\t\tSo we need some datastructure that behaves like a normal array, but with wonky out-of-bounds behaviour!\n\n\t\tIn julia, a custom datatype can be defined as:\n\t\t```\n\t\tstruct CircularArray \n\t\t\tdata\n\t\tend\n\t\t```\n\t\tNow we have our data type `CircularArray`, which has a field `data`.\n\t\tUsing our knowledge from the simple example above, let us define a function which takes an index and the length of the array and returns the correct index using circular bounds. We will also create a function that takes an array of indices and returns an array of correct indices. Take a moment to think about how you would do this, and afterwards check a possible implementation in hint 1.\n\t\t\n\t\tSo now we know how the compute the **normal** indices from the circular ones. \n\t\tWe now need to define some things for our new datatype `CircularArray`. \n\t\t1. We need the `size` of `CircularArray` and \n\t\t2. we need to define how `A[1]` works on our datatype (this is the `getindex` function in julia).\n\t\tFor the first problem, note that the size of a `CircularArray` is actually the size of the underlying array! So how do you think the function `Base.size(A::CircularArray) = ...` looks like? \n\t\tFor the second problem we need a definition of `Base.getindex(A::CircularArray, i::Int)`. How can we define this using the `circindex` function? \n\t\tIf you have given this some thought, check out hint no 2 for the answer!.\n\t\t\t\t\"\"\")\n\t\n QuestionBlock(;\n\ttitle=md\"**Alternative answer: defining a new data type**\",\n\tquestions = [qalt],\n\thints=[hint(md\"\n```julia\ncircindex(i::Int, N::Int) = 1 + mod(i-1,N)\ncircindex(I, N::Int) = [circindex(i,N)::Int for i in I]\n```\"),\n\t\t\thint(md\"\nNote that I use `length`. This is because I already know that `data` will be a `string`, as you will see below.\n```julia\nBase.size(A::CircularArray) = length(A.data)\n\nBase.getindex(A::CircularArray, i::Int) = getindex(A.data, circindex(i, size(A)))\nBase.getindex(A::CircularArray, I) = getindex(A.data, circindex(I, size(A)))\n```\")\n\t\t\t],\n\t)\nend\n\n# ╔═╡ ec0aa2c6-63ea-11eb-062a-cdd3e81a743a\nmd\"\"\"\nLet us defined what we talked about before:\n\"\"\"\n\n# ╔═╡ de9cf7b0-63ea-11eb-12fb-773d79c2463b\nbegin \n\tstruct CircularArray \n\t\tdata\n\tend\n\n\tcircindex(i::Int,N::Int) = 1 + mod(i-1,N)\n\tcircindex(I,N::Int) = [circindex(i,N)::Int for i in I]\n\n\tBase.size(A::CircularArray) = length(A.data)\n\n\tBase.getindex(A::CircularArray, i::Int) = getindex(A.data, circindex(i, size(A)))\n\tBase.getindex(A::CircularArray, I) = getindex(A.data, circindex(I, size(A)))\nend\n\n# ╔═╡ 424c1470-63e0-11eb-323f-454ac8ad273e\nbegin\n\tq1 = Question(validators = @safe[n_trees == Solutions.n_trees], \n\t\t\tdescription=md\"\"\"\n\t\t\tStarting at the top-left corner of your map and following a slope of right 3 and down 1, how many trees would you encounter?\n\t\t\t\"\"\")\n\t\n qb1 = QuestionBlock(;\n\ttitle=md\"**Question 1: counting trees**\",\n\tquestions = [q1],\n\thints=[hint(md\"This question can be answered without defining your own datatypes and using all that is available from the `Julia.Base` module. This can also be completed without knowing a lot about collections. Since this is only explained in the next part of the course. \"),\n\t\t\thint(md\"An alterative solution showcasing the power of Julia will be shown below, it includes some teasers of what is yet to come in this course\")\n\t\t\t],\n\t)\n\tvalidate(qb1, tracker)\nend\n\n# ╔═╡ c1206434-63e2-11eb-16c1-d7fafb48bbbe\nbegin\n\tq2 = Question(validators = @safe[product_all_trees == Solutions.product_all_trees], \n\t\t\tdescription=md\"\"\"\nTime to check the rest of the slopes - you need to minimize the probability of a sudden arboreal stop, after all.\n\nDetermine the number of trees you would encounter if, for each of the following slopes, you start at the top-left corner and traverse the map all the way to the bottom:\n\n Right 1, down 1.\n Right 3, down 1. (This is the slope you already checked.)\n Right 5, down 1.\n Right 7, down 1.\n Right 1, down 2.\n\nIn the above example, these slopes would find 2, 7, 3, 4, and 2 tree(s) respectively; multiplied together, these produce the answer 336.\n\nWhat do you get if you multiply together the number of trees encountered on each of the listed slopes?\"\"\")\n\t\n qb2 = QuestionBlock(;\n\ttitle=md\"**Question 2: counting trees**\",\n\tquestions = [q2],\n\t)\n\tvalidate(qb2, tracker)\nend\n\n# ╔═╡ f752b934-63ea-11eb-09cc-99172ed4870d\nmd\"\"\"\nNow, let us read in the data, but this time each horizontal line is a `CircularArray`! (Try to understand what each line does in the code below)\n\"\"\"\n\n# ╔═╡ 5c2438ce-63eb-11eb-0892-272fb362a2e8\nbegin\n\t# init 1D array of data type CircularArrays with len=number of lines \n\t# in the file and leave it undefined for now\n\t# Note that the number of lines is hardcoded (323).\n\t# This could be done more elegantly in an other way, but we will leave that\n\t# exercise for the user.\n\tslope = Array{CircularArray, 1}(undef, 323)\n\n\timport Base.Iterators.enumerate\n\t\n\t# open the file\n\topen(\"map.txt\") do file\n\t\t# if you have some programming experience, you can probably guess \n\t\t# what enumerate does.\n\t\t# the eachline function speaks for itself: iterate over each line in the file!\n\t\tfor (idx, ln) in enumerate(eachline(file))\n\t\t\tslope[idx] = CircularArray(ln)\n\t\tend\n\tend\nend\n\n# ╔═╡ 9cafdef2-63eb-11eb-326a-5d51766d17d5\nmd\"This is how the data now looks like: (Click to expand and have a nicer view of the circular mountain)\"\n\n# ╔═╡ 9371b694-63eb-11eb-30a5-d3542ca8f4e5\nslope\n\n# ╔═╡ 18054676-63f0-11eb-1a53-5b65f8477882\nslope[1]\n\n# ╔═╡ 73f03a14-63f0-11eb-1a14-17e4e69745af\nmd\"Let us look at one horizontal line of the mountain. Check the output below of data at index 1, 32 and 63. Does this match your intuition?\"\n\n# ╔═╡ 2164576e-63f0-11eb-3e57-4fad123c494b\nfirstline = slope[1]\n\n# ╔═╡ 8eda596a-63f0-11eb-03ba-abd147192428\nsize(firstline)\n\n# ╔═╡ 62dfc3ae-63f0-11eb-350c-b3040f8a6d9b\nfirstline[1], firstline[32], firstline[63]\n\n# ╔═╡ 224c26ce-63ec-11eb-0744-e97f5196972a\nmd\"\"\"\nIf we want to go down the slope using our sled in the configuration of 1 down + 3 right, we can write down the *mountain coordinates* like this:\n\n```julia\n(1, 1)\n(2, 4)\n(3, 7)\n(4, 10)\n(5, 13)\n...\n```\nWe have not talked about collections and ranges, yet so this will be a sneak peak. You can define a range in julia like this: `1:5`. This will give you the values `[1,2,3,4,5]`. On the other hand, `1:2:5` will give you `[1,3,5]`. Do you see the difference? \nchange some values in the two cells below to check if you understand the basics on this concept. Then, think about how you would write up the list of x-coordinates and y-coordinates if you go down the slope 1 down, 3 right.\n\"\"\"\n\n# ╔═╡ 9ec3845e-63ec-11eb-1a81-c141b4ff37d8\ncollect(1:5)\n\n# ╔═╡ b590457a-63ec-11eb-3b3b-5d5b0de1f98c\ncollect(1:2:5)\n\n# ╔═╡ a0f50fee-63ed-11eb-0208-0b5f7036a7b1\nmd\"Moving on, let us define our function to go down the slope. Does this match your intuition of before?\"\n\n# ╔═╡ ae58f724-63eb-11eb-0541-3584d99d9fc5\nfunction goingdowntheslope(right, down, slope)\n xvals = 1:right:right*323\n yvals = 1:down:323\n thingsyoufind = [slope[yval][xval] for (xval, yval) in zip(xvals, yvals)]\n return sum(thingsyoufind .== '#')\nend \n\n# ╔═╡ 44885292-63ee-11eb-048b-2b7481a83ae8\nmd\"\"\"Now that you possess all this new knowledge, can find the answers to the two slope-questions in this notebook?\"\"\"\n\n# ╔═╡ 10e183ca-63ec-11eb-3d4b-57ed0543cda1\ngoingdowntheslope(3, 1, slope)\n\n# ╔═╡ dd716abc-63ed-11eb-36e9-fdbd1187146e\nslopestyles = (\n (1, 1), \n (3, 1), \n (5, 1), \n (7, 1), \n (1, 2), \n)\n\n# ╔═╡ e0569568-63ed-11eb-33b9-51a8b179292c\nprod([goingdowntheslope(direction..., slope) for direction in slopestyles])\n\n# ╔═╡ Cell order:\n# ╠═24b76a7c-63dd-11eb-1b78-d5a20557e5cd\n# ╟─4109a39c-00b7-4954-bb73-35407f82a6f7\n# ╠═446c3e4e-63dd-11eb-3300-fb006008ff1f\n# ╟─5368424c-63dd-11eb-3a1b-05a61e266d2b\n# ╟─6c0f2d10-63dd-11eb-2c17-fddf9cd51bfe\n# ╟─e1259736-63df-11eb-0010-3f2fc5719596\n# ╠═36e51b02-63df-11eb-34a5-39e6e0650541\n# ╠═e677ca7e-63df-11eb-186b-8d20826ec916\n# ╟─c34af248-63e3-11eb-2bfd-898ef2cfbea5\n# ╟─424c1470-63e0-11eb-323f-454ac8ad273e\n# ╠═4b4bbeb8-63e2-11eb-0ea2-6de494f61dc1\n# ╟─dcac803a-648d-11eb-21f2-d72e56528e92\n# ╟─c1206434-63e2-11eb-16c1-d7fafb48bbbe\n# ╠═fb39928c-63e2-11eb-2b85-15044c04fbe6\n# ╟─ede6342c-648d-11eb-0712-836637408e53\n# ╟─b9e97832-63e3-11eb-0e39-b5c9129eabbe\n# ╟─9c015578-648e-11eb-0768-d1e5edb4f65f\n# ╟─f0f0da0a-63e3-11eb-2065-838c77fc57a6\n# ╟─ec0aa2c6-63ea-11eb-062a-cdd3e81a743a\n# ╠═de9cf7b0-63ea-11eb-12fb-773d79c2463b\n# ╟─f752b934-63ea-11eb-09cc-99172ed4870d\n# ╠═5c2438ce-63eb-11eb-0892-272fb362a2e8\n# ╟─9cafdef2-63eb-11eb-326a-5d51766d17d5\n# ╠═9371b694-63eb-11eb-30a5-d3542ca8f4e5\n# ╠═18054676-63f0-11eb-1a53-5b65f8477882\n# ╟─73f03a14-63f0-11eb-1a14-17e4e69745af\n# ╠═2164576e-63f0-11eb-3e57-4fad123c494b\n# ╠═8eda596a-63f0-11eb-03ba-abd147192428\n# ╠═62dfc3ae-63f0-11eb-350c-b3040f8a6d9b\n# ╟─224c26ce-63ec-11eb-0744-e97f5196972a\n# ╠═9ec3845e-63ec-11eb-1a81-c141b4ff37d8\n# ╠═b590457a-63ec-11eb-3b3b-5d5b0de1f98c\n# ╟─a0f50fee-63ed-11eb-0208-0b5f7036a7b1\n# ╠═ae58f724-63eb-11eb-0541-3584d99d9fc5\n# ╟─44885292-63ee-11eb-048b-2b7481a83ae8\n# ╠═10e183ca-63ec-11eb-3d4b-57ed0543cda1\n# ╠═dd716abc-63ed-11eb-36e9-fdbd1187146e\n# ╠═e0569568-63ed-11eb-33b9-51a8b179292c\n", "meta": {"hexsha": "3517d37ab32033df839a6ca40c8972fdb6cf3865", "size": 15152, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/day1/01-basics-extra.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": "notebooks/day1/01-basics-extra.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": "notebooks/day1/01-basics-extra.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": 37.2285012285, "max_line_length": 392, "alphanum_fraction": 0.6488252376, "num_tokens": 5695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713671682749485, "lm_q2_score": 0.28140560140262283, "lm_q1q2_score": 0.12864083272206167}}
{"text": "### A Pluto.jl notebook ###\n# v0.14.2\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 794a5356-6e05-44b4-ad9d-375a1fa3613b\nbegin\n\tusing PlutoUI\n\tusing DataFrames\n\tusing CSV\n\t\n\tusing Arrow\n\tusing Serialization\n\tusing JLSO\n\tusing JSONTables\n\tusing CodecZlib\n\tusing ZipFile\n\tusing JDF\n\t\n\tusing StatsPlots # for charts\n\tusing Mmap # for compression\n\tusing Test\nend\n\n# ╔═╡ b3dcf3f4-9d68-11eb-01a6-317fe0e0cd7e\nmd\"\"\"\n## Introduction DataFrames / 4 - Load and Save\n\nref. [Introduction to DataFrames, Bogumił Kamiński](https://github.com/bkamins/Julia-DataFrames-Tutorial/blob/master/04_loadsave.ipynb)\n\nWe do not cover all features of the packages. Please refer to their documentation to learn them.\n\nHere we will load `CSV.jl` to read and write CSV files and `Arrow.jl`, `JLSO.jl`, and `serialization`, which allow us to work with a binary format and `JSONTables.jl` for JSON interaction. Finally we consider a custom `JDF.jl` format.\n\n$(html\"<div><sub>&copy; Pascal, April 2021</sub></div>\")\n\"\"\"\n\n# ╔═╡ d6993a5b-8158-4ce3-accb-8e8c514229b3\nPlutoUI.TableOfContents(indent=true, depth=4, aside=true)\n\n# ╔═╡ de97ded0-3952-4188-9a43-a8f383e1ae65\nmd\"\"\"\n### Load and save DataFrames\n\nLet us create a simple DataFrame for testing purpose :\n\"\"\"\n\n# ╔═╡ 887ea560-b824-44bd-96ba-7756271993e7\nx₀ = DataFrame(A=[true, false, true], B=[1, 2, missing], \n\tC=[missing, \"b\", \"c\"], D=['a', missing, 'c'])\n\n# ╔═╡ 327fae3b-f00a-4bb4-ba95-a003e0740c58\nmd\"\"\"\nand use `eltypes` to look at the columnwise types.\n\"\"\"\n\n# ╔═╡ b18bb84d-99f2-454e-b8bd-7c5e52b94141\neltype.(eachcol(x₀))\n\n# ╔═╡ ca9927e5-3ff2-4c73-8206-4d7495668312\nmd\"\"\"\n### CSV.jl\n\nLet's use `CSV.jl` to save x₀ to disk; make sure `x0.csv` does not conflict with some file in your working directory.\n\"\"\"\n\n# ╔═╡ 696d306e-c000-47af-a904-eff748b317f3\nCSV.write(\"./Data/x0.csv\", x₀)\n\n# ╔═╡ 157caf96-53ad-4ae6-aa1f-5d3fef0b178f\nmd\"\"\"\nNow we can see how it was saved by reading `x0.csv`.\n\"\"\"\n\n# ╔═╡ c04fb113-c95f-4a23-8884-147cdc62ac5c\nwith_terminal() do\n\tprint(read(\"./Data/x0.csv\", String))\nend\n\n# ╔═╡ 06ee8941-57ef-4dfa-8385-861146755d53\nmd\"\"\"\nWe can also load it back, as usual running:\n\"\"\"\n\n# ╔═╡ ae8ac551-ea7f-4a9f-bfb4-e1b86677a6a8\ny₀ = CSV.read(\"./Data/x0.csv\", DataFrame)\n\n# ╔═╡ 86253acd-78a2-44c2-931e-f2322ed67dc2\neltype.(eachcol(y₀))\n\n# ╔═╡ 069ea341-4097-42f5-83ff-18548bd34de2\nmd\"\"\"\n*Remark:* Note that when loading in a DataFrame from a CSV the column type for column :D has changed!\n\"\"\"\n\n# ╔═╡ a4615e9b-d3d9-443a-9146-e411f9bbd749\nmd\"\"\"\n### Serialization, JDF.jl, and JLSO.j\n\n#### Serialization\n\nNow we use serialization to save x₀.\n\nThere are two ways to perform serialization. \n - The first way is to use the Serialization.serialize as below:\n **Note** *that in general, this process will not work if the reading and writing are done by different versions of Julia, or an instance of Julia with a different system image*.\n\"\"\"\n\n# ╔═╡ 8cc8ae4d-44df-495b-9469-6b467abd6add\nopen(\"./Data/x₀.bin\", \"w\") do io\n serialize(io, x₀)\nend\n\n# ╔═╡ 8c7e6303-0d09-4993-943f-d9bd3a9c316b\nmd\"\"\"\nNow we load back the saved file to `y₁` variable. Again `y₁` is identical to `x₀`. However, please beware that if you session does not have `DataFrames.jl` loaded, then it may not recognise the content as `DataFrames.jl`.\n\"\"\"\n\n# ╔═╡ aa8ffd59-e791-4dca-bce7-05a18dfda955\ny₁ = open(deserialize, \"./Data/x₀.bin\")\n\n# ╔═╡ b67f1614-90e2-4e4f-9890-9fd66d24cf5b\neltype.(eachcol(y₁))\n\n# ╔═╡ 3d64997f-bfed-4c48-b962-d0bd6c7aa1ef\nmd\"\"\"\n#### JDF.jl\n\n\n[`JDF.jl`](https://github.com/xiaodaigh/JDF) is a relatively new package designed to serialize DataFrames. You can save a DataFrame with the `savejdf` function.\n\"\"\"\n\n# ╔═╡ 9be83f87-de31-4403-b567-4f488f88645e\nsavejdf(\"./Data/x₀.jdf\", x₀);\n\n# ╔═╡ 2717467d-c2c5-4006-bc6f-f5c5de3c6304\nmd\"\"\"\nTo load the saved JDF file, we use the `loadjdf` function\n\"\"\"\n\n# ╔═╡ 1f9c7d56-3471-4679-aa17-c5ba3b7c31c6\nx₀_loaded = loadjdf(\"./Data/x₀.jdf\") |> DataFrame\n\n# ╔═╡ 332e66fe-5a54-4741-a09c-465afef318b7\n@assert isequal(x₀_loaded, x₀)\n\n# ╔═╡ 494e54f6-f29c-457a-9aba-0b7a3cd143b9\nmd\"\"\"\n`JDF.jl` offers the ability to load only certain columns from disk to help with working with large files\n\"\"\"\n\n# ╔═╡ 2909e4a4-5355-4ca9-aca2-efc43d938b29\n# set up a JDFFile which is a on disk representation of `x₀` backed by JDF.jl\nx₀_ondisk = jdf\"./Data/x₀.jdf\"\n\n# ╔═╡ 8beffe4b-051a-41e9-af93-10329564355f\nmd\"\"\"\nWe can see all the names of `x` without loading it into memory\n\"\"\"\n\n# ╔═╡ 43b9a909-dd99-4bf0-bf41-8a21c5127e24\nnames(x₀_ondisk)\n\n# ╔═╡ 424dc5a0-f64d-4563-a8be-99ffbb1b211d\nmd\"\"\"\nThe below is an example of how to load only columns `:A` and `:D`\n\"\"\"\n\n# ╔═╡ 6109fe95-9cd4-47b7-a79d-387e7aac78db\nxd = sloadjdf(x₀_ondisk; cols = [\"A\", \"D\"]) |> DataFrame\n\n# ╔═╡ 7211a7cc-3ab1-4c4e-a858-60ee8d910054\neltype.(eachcol(xd))\n\n# ╔═╡ c7ea6a2b-8719-4a1a-b2ce-34237bbbc625\nmd\"\"\"\n#### JDF.jl vs others\n\n`JDF.jl` is specialized to `DataFrames.jl` and only supports a restricted list of columns, so it cannot save dataframes with arbitrary column types. However, this also means that `JDF.jl` has specialised algorithms to serailize the type it supports to optimize speed, minimize disk usage, and reduce the chance of errors\n\nThe list support columns for `JDF` include\n\n```Julia\nWeakRefStrings.StringVector\nVector{T}, Vector{Union{Mising, T}}, Vector{Union{Nothing, T}}\nCategoricalArrays.CategoricalVetors{T}\n```\n\nwhere `T` can be `String`, `Bool`, `Symbol`, `Char`, `TimeZones.ZonedDateTime` (experimental) and `isbits` types i.e. `UInt*`, `Int*`, `Float*`, and `Date*` types etc.\n\"\"\"\n\n# ╔═╡ 2516d88a-9141-4a25-90b3-fc212e6299f9\nmd\"\"\"\n#### JLSO.jl\n\n\nJLSO.jl\n\nAnother way to perform serialization is by using the [JLSO.jl](https://github.com/invenia/JLSO.jl) library:\n\"\"\"\n\n# ╔═╡ 381916dc-3610-4df4-9911-c822d28d3956\nJLSO.save(\"./Data/x₀.jlso\", :data => x₀)\n\n# ╔═╡ db07eb7e-2fa7-44e7-adb6-c0254a83e0e3\nmd\"\"\"\nNow we can load back the file to y₂.\n\"\"\"\n\n# ╔═╡ 4f63f693-8392-4e8e-a04e-00f45ba016a3\ny₂ = JLSO.load(\"./Data/x₀.jlso\")[:data]\n\n# ╔═╡ a3203a29-33f5-457a-9a90-80c5e14422a6\neltype.(eachcol(y₂))\n\n# ╔═╡ f12dc3e2-167d-4cad-a999-53c67d55af07\nmd\"\"\"\n#### JSONTables.jl\n\nOften you might need to read and write data stored in JSON format. `JSONTables.jl` provides a way to process them in row-oriented or column-oriented layout. We present both options below.\n\"\"\"\n\n# ╔═╡ 23b96b56-709f-4f5b-8bb9-961764f61faf\nopen(io -> arraytable(io, x₀), \"./Data/x₁.json\", \"w\")\n\n# ╔═╡ 6223627b-7541-42f7-892a-80c86e3a95ec\nopen(io -> objecttable(io, x₀), \"./Data/x₂.json\", \"w\")\n\n# ╔═╡ f9281efb-e8aa-4267-9d63-7094e6010315\nwith_terminal() do\n\tprint(read(\"./Data/x₁.json\", String))\nend\n\n# ╔═╡ f215042e-5dec-4e2f-940f-02467c0b3d94\nwith_terminal() do\n\tprint(read(\"./Data/x₂.json\", String))\nend\n\n# ╔═╡ ef097417-b572-4110-b943-7b2500c81838\nyj₁ = open(jsontable, \"./Data/x₁.json\") |> DataFrame\n\n# ╔═╡ 1aca803a-197a-47ac-8eb3-73ab3c40de47\neltype.(eachcol(yj₁))\n\n# ╔═╡ 0e193005-cd0b-4c1c-aa1e-42cee639238c\nyj₂ = open(jsontable, \"./Data/x₁.json\") |> DataFrame\n\n# ╔═╡ 6dd53b4a-a936-40c3-873d-42abe4421189\neltype.(eachcol(yj₂))\n\n# ╔═╡ dc97e056-2d8d-442e-90d2-b75931cecb33\nmd\"\"\"\n#### Arrow.jl\n\nFinally we use `Apache Arrow` format that allows, in particular, for data interchange with `R` or `Python`.\n\"\"\"\n\n# ╔═╡ d1a0d653-ac96-4712-bc26-430ba4436544\nArrow.write(\"./Data/x₀.arrow\", x₀)\n\n# ╔═╡ 2244a140-ec46-4ec5-84c6-fc40511953ad\nyₐ = Arrow.Table(\"./Data/x₀.arrow\") |> DataFrame\n\n# ╔═╡ e392701a-75a4-465b-9547-a8d6a3bdc059\neltype.(eachcol(yₐ))\n\n# ╔═╡ 2bf8f141-c809-4599-ace3-3fabd1bbc1d6\nyₐ.A[1] = false ## can be changed - used to be immutable\n\n# ╔═╡ f00b7857-6393-4501-b0a8-bfd7d50667c4\nyₐ.A\n\n# ╔═╡ 613569c5-20f4-4463-a039-12fecab721eb\nyₐ.B\n\n# ╔═╡ edd10614-b548-4148-acf5-33e16ab0a8be\nmd\"\"\"\n### Basic benchmarking\n\nNext, we'll create some files, so be careful that you don't already have these files in your working directory!\n\nIn particular, we'll time how long it takes us to write a DataFrame with 10^3 rows and 10^5 columns.\n\n\"\"\"\n\n# ╔═╡ 3d478ed4-cf5a-44a1-9441-6da73f7986d2\nbegin\n\tbigdf = DataFrame(rand(Bool, 10^5, 500), :auto)\n\tbigdf[!, 1] = Int.(bigdf[!, 1])\n\tbigdf[!, 2] = bigdf[!, 2] .+ 0.5\n\tbigdf[!, 3] = string.(bigdf[!, 3], \", as string\")\n\t\n\tbigdf = DataFrame(rand(Bool, 10^5, 500), :auto)\n\tbigdf[!, 1] = Int.(bigdf[!, 1])\n\tbigdf[!, 2] = bigdf[!, 2] .+ 0.5\n\tbigdf[!, 3] = string.(bigdf[!, 3], \", as string\")\n\t\n\twith_terminal() do\n\t\tprintln(\"First run\")\n\t\tprintln(\"CSV.jl\")\n\t\tglobal csvwrite1 = @elapsed @time CSV.write(\"./Data/bigdf1.csv\", bigdf)\n\t\n\t\tprintln(\"Serialization\")\n\t\tglobal serializewrite1 = @elapsed @time open(io -> serialize(io, bigdf), \n\t\t\t\"./Data/bigdf.bin\", \"w\")\n\t\t\n\t\tprintln(\"JDF.jl\")\n\t\tglobal jdfwrite1 = @elapsed @time savejdf(\"./Data/bigdf.jdf\", bigdf)\n\t\t\n\t\tprintln(\"JLSO.jl\")\n\t\tglobal jlsowrite1 = @elapsed @time JLSO.save(\"./Data/bigdf.jlso\", :data => bigdf)\n\t\t\n\t\tprintln(\"Arrow.jl\")\n\t\tglobal arrowwrite1 = @elapsed @time Arrow.write(\"./Data/bigdf.arrow\", bigdf)\n\t\t\n\t\tprintln(\"JSONTables.jl arraytable\")\n\t\tglobal jsontablesawrite1 = @elapsed @time open(io -> arraytable(io, bigdf), \n\t\t\t\"./Data/bigdf1.json\", \"w\")\n\t\t\n\t\tprintln(\"JSONTables.jl objecttable\")\n\t\tglobal jsontablesowrite1 = @elapsed @time open(io -> objecttable(io, bigdf), \n\t\t\t\"./Data/bigdf2.json\", \"w\")\n\t\t\n\t\tprintln(\"Second run\")\n\t\tprintln(\"CSV.jl\")\n\t\tglobal csvwrite2 = @elapsed @time CSV.write(\"./Data/bigdf1.csv\", bigdf)\n\t\t\n\t\tprintln(\"Serialization\")\n\t\tglobal serializewrite2 = @elapsed @time open(io -> serialize(io, bigdf), \n\t\t\t\t\"./Data/bigdf.bin\", \"w\")\n\t\t\n\t\tprintln(\"JDF.jl\")\n\t\tglobal jdfwrite2 = @elapsed @time savejdf(\"./Data/bigdf.jdf\", bigdf)\n\t\t\n\t\tprintln(\"JLSO.jl\")\n\t\tglobal jlsowrite2 = @elapsed @time JLSO.save(\"./Data/bigdf.jlso\", :data => bigdf)\n\t\t\n\t\tprintln(\"Arrow.jl\")\n\t\tglobal arrowwrite2 = @elapsed @time Arrow.write(\"./Data/bigdf.arrow\", bigdf)\n\t\t\n\t\tprintln(\"JSONTables.jl arraytable\")\n\t\tglobal jsontablesawrite2 = @elapsed @time open(io -> arraytable(io, bigdf), \n\t\t\t\"./Data/bigdf1.json\", \"w\")\n\t\t\n\t\tprintln(\"JSONTables.jl objecttable\")\n\t\tglobal jsontablesowrite2 = @elapsed @time open(io -> objecttable(io, bigdf), \n\t\t\t\"./Data/bigdf2.json\", \"w\")\n\tend\nend\n\n# ╔═╡ 782f560a-9fd5-498b-9ff8-0215736b240e\ngroupedbar(\n # Exclude JSONTables.jl arraytable due to timing\n\trepeat([\"CSV.jl\", \"Serialization\", \"JDF.jl\", \"JLSO.jl\", \n\t\t\t\"Arrow.jl\", \"JSONTables.jl\\nobjecttable\"], inner = 2),\n\n\t[csvwrite1, csvwrite2, serializewrite1, serializewrite1, jdfwrite1, jdfwrite2,\n jlsowrite1, jlsowrite2, arrowwrite1, arrowwrite2, jsontablesowrite2, jsontablesowrite2],\n\n\tgroup = repeat([\"1st\", \"2nd\"], outer = 6),\n\tylab = \"Second\",\n\ttitle = \"Write Performance\\nDataFrame: bigdf\\nSize: $(size(bigdf))\"\n)\n\n# ╔═╡ 5ab7852b-ea4e-42de-829f-a101e58a0b93\nbegin\n\tdata_files = [\"./Data/bigdf1.csv\", \"./Data/bigdf.bin\", \"./Data/bigdf.arrow\", \n\t\t\"./Data/bigdf1.json\", \"./Data/bigdf2.json\"]\n\tdf = DataFrame(file = data_files, size = getfield.(stat.(data_files), :size))\n\tappend!(df, \n\t\t\tDataFrame(file = \"./Data/bigdf.jdf\", \n\t\t\tsize=reduce((x,y) -> x + y.size, stat.(joinpath.(\"./Data/bigdf.jdf\", readdir(\"./Data/bigdf.jdf\"))), \n\t\t\t\tinit=0)))\n\tsort!(df, :size)\nend\n\n# ╔═╡ 175391bb-3cdc-409f-8963-8aa3d613b601\n@df df plot(:file, :size/1024^2, seriestype=:bar, title = \"Format File Size (MB)\", label=\"Size\", ylab=\"MB\", legend=:topleft, xrotation=45)\n\n# ╔═╡ 5e475f09-3177-45b5-a9a1-f25c1cfeef37\nbegin\n\t\n\twith_terminal() do\n\t\tprintln(\"First run\")\n\t\tprintln(\"CSV.jl\")\n\t\tglobal csvread1 = @elapsed @time CSV.read(\"./Data/bigdf1.csv\", DataFrame)\n\t\t\n\t\tprintln(\"Serialization\")\n\t\tglobal serializeread1 = @elapsed @time open(deserialize, \"./Data/bigdf.bin\")\n\t\t\n\t\tprintln(\"JDF.jl\")\n\t\tglobal jdfread1 = @elapsed @time loadjdf(\"./Data/bigdf.jdf\")\n\t\t\n\t\tprintln(\"JLSO.jl\")\n\t\tglobal jlsoread1 = @elapsed @time JLSO.load(\"./Data/bigdf.jlso\")\n\t\t\n\t\tprintln(\"Arrow.jl\")\n\t\tglobal arrowread1 = @elapsed @time df_tmp = Arrow.Table(\"./Data/bigdf.arrow\") |> DataFrame\n\t\tglobal arrowread1copy = @elapsed @time copy(df_tmp)\n\t\t\n\t\tprintln(\"JSONTables.jl arraytable\")\n\t\tglobal jsontablesaread1 = @elapsed @time open(jsontable, \"./Data/bigdf1.json\")\n\t\t\n\t\tprintln(\"JSONTables.jl objecttable\")\n\t\tglobal jsontablesoread1 = @elapsed @time open(jsontable, \"./Data/bigdf2.json\")\n\t\t\n\t\tprintln(\"Second run\")\n\t\tglobal csvread2 = @elapsed @time CSV.read(\"./Data/bigdf1.csv\", DataFrame)\n\t\t\n\t\tprintln(\"Serialization\")\n\t\tglobal serializeread2 = @elapsed @time open(deserialize, \"./Data/bigdf.bin\")\n\t\t\n\t\tprintln(\"JDF.jl\")\n\t\tglobal jdfread2 = @elapsed @time loadjdf(\"./Data/bigdf.jdf\")\n\t\t\n\t\tprintln(\"JLSO.jl\")\n\t\tglobal jlsoread2 = @elapsed @time JLSO.load(\"./Data/bigdf.jlso\")\n\t\t\n\t\tprintln(\"Arrow.jl\")\n\t\tglobal arrowread2 = @elapsed @time df_tmp = Arrow.Table(\"./Data/bigdf.arrow\") |> DataFrame\n\t\tglobal arrowread2copy = @elapsed @time copy(df_tmp)\n\t\t\n\t\tprintln(\"JSONTables.jl arraytable\")\n\t\tglobal jsontablesaread2 = @elapsed @time open(jsontable, \"./Data/bigdf1.json\")\n\t\t\n\t\tprintln(\"JSONTables.jl objecttable\")\n\t\tglobal jsontablesoread2 = @elapsed @time open(jsontable, \"./Data/bigdf2.json\");\n\tend\nend\n\n# ╔═╡ 2fac7472-ddf7-477e-9142-0640bda99890\ngroupedbar(\n repeat([\"CSV.jl\", \".Serialization\", \"JDF.jl\", \"JLSO.jl\", \"Arrow.jl\", \n\t\t\t\"Arrow.jl\\ncopy\", \"JSON\\narraytable\", \"JSON\\nobjecttable\"], inner = 2),\n\t\n [csvread1, csvread2, serializeread1, serializeread2, jdfread1, jdfread2, jlsoread1, jlsoread2,\n arrowread1, arrowread2, arrowread1+arrowread1copy, arrowread2+arrowread2copy,\n jsontablesaread1, jsontablesaread2, jsontablesoread1, jsontablesoread2], \n \n\tgroup = repeat([\"1st\", \"2nd\"], outer = 8),\n ylab = \"Second\",\n title = \"Read Performance\\nDataFrame: bigdf\\nSize: $(size(bigdf))\",\n\tlegend=:topleft\n)\n\n# ╔═╡ d2df242d-259c-4935-b71b-e1d444ac6f07\nmd\"\"\"\n#### Using gzip compression\n\nA common user requirement is to be able to load and save CSV that are compressed using `gzip`. Below we show how this can be accomplished using `CodecZlib.jl`. The same pattern is applicable to `JSONTables.jl` compression/decompression.\n\nAgain make sure that you do not have file named df_compress_test.csv.gz in your working directory\n\nWe first generate a random data frame\n\n\"\"\"\n\n# ╔═╡ b7b657d6-0723-4209-9ecb-efcc72be402f\ndfₓ = DataFrame(rand(1:10, 10, 1000), :auto)\n\n# ╔═╡ 8357bef1-d31c-4fa5-992f-f2a6eb6d9573\n# GzipCompressorStream comes from CodecZlib\n\nopen(\"./Data/df_compress_test.csv.gz\", \"w\") do io\n stream = GzipCompressorStream(io)\n CSV.write(stream, dfₓ)\n close(stream)\nend\n\n# ╔═╡ c33160d1-b12e-42ab-a3c3-b8d6bc58bd9d\ndf₂ = CSV.File(transcode(GzipDecompressor, \n\t\tMmap.mmap(\"./Data/df_compress_test.csv.gz\"))) |> DataFrame\n\n# ╔═╡ 544fbeae-ca73-487d-92b5-8d619d9b8db7\n@assert dfₓ == df₂\n\n# ╔═╡ bcee6550-63e7-4ff2-a324-37bef45a28b9\nmd\"\"\"\n#### Using zip files\n\nSometimes you may have files compressed inside a zip file.\n\nIn such a situation you may use `ZipFile.jl` in conjunction an an appropriate reader to read the files.\n\nHere we first create a ZIP file and then read back its contents into a DataFrame.\n\"\"\"\n\n# ╔═╡ 50eee498-9548-4ee7-8375-90c17b376c0a\nzdf₁ = DataFrame(rand(1:10, 3, 4), :auto)\n\n# ╔═╡ 90eb146e-9dbf-45ef-a093-437fb938b10d\nzdf₂ = DataFrame(rand(1:10, 3, 4), :auto)\n\n# ╔═╡ f5cb08ba-814e-4a7b-b676-5967a352d2a7\nmd\"\"\"\nAnd we show yet another way to write a DataFrame into a CSV file\n\"\"\"\n\n# ╔═╡ 223e5415-0ab4-4016-b506-658adc75c57b\nbegin\n\t# write a CSV file into the zip file\n\tw = ZipFile.Writer(\"./Data/x.zip\")\n\n\tf₁ = ZipFile.addfile(w, \"x₁.csv\")\n\twrite(f₁, sprint(show, \"text/csv\", zdf₁))\n\n\t# write a second CSV file into zip file\n\tf₂ = ZipFile.addfile(w, \"x₂.csv\", method=ZipFile.Deflate)\n\twrite(f₂, sprint(show, \"text/csv\", zdf₂))\n\n\tclose(w)\nend\n\n# ╔═╡ dd26958e-55f1-4b2e-b557-1bd24eb43fa0\nmd\"\"\"\nNow we read the CSV we have written.\n\"\"\"\n\n# ╔═╡ 8b87edb5-d8a7-4234-ac8d-f9e0c8f5f8a0\nz = ZipFile.Reader(\"./Data/x.zip\");\n\n# ╔═╡ f257c2c9-6cdf-4df8-8b53-7a8d3794b7c3\nbegin\n\t# find the index index of file called x₁.csv\n\tix_xcsv₁ = findfirst(x -> x.name == \"x₁.csv\", z.files);\n\n\t# to read the x₁.csv file in the zip file\n\trzdf₁ = read(z.files[ix_xcsv₁]) |> f -> CSV.read(f, DataFrame);\nend\n\n# ╔═╡ ec462215-2451-4e8e-b440-58503378faae\n@assert rzdf₁ == zdf₁\n\n# ╔═╡ 4fb9645f-ee4d-410a-aec3-06f13fdec761\nbegin\n\t# find the index index of file called x₂.csv\n\tix_xcsv₂ = findfirst(x->x.name == \"x₂.csv\", z.files)\n\n\t# to read the x2.csv file in the zip file\n\trzdf₂ = read(z.files[ix_xcsv₂]) |> f -> CSV.read(f, DataFrame);\nend\n\n# ╔═╡ cc833913-383f-46ac-8ff2-5b6c8c8cbff4\n@assert rzdf₂ == zdf₂\n\n# ╔═╡ c3f1fae0-4422-4023-b43f-de1651a89983\nmd\"\"\"\nNote that once you read a given file from z object its stream is all used-up (it is at its end). Therefore to read it again you need to close z and open it again.\n\nAlso do not forget to close the zip file once done.\n\"\"\"\n\n# ╔═╡ 5a1bd5be-9329-44e8-848e-efb7bac1e5f4\nclose(z)\n\n# ╔═╡ 1d8e3b27-8af6-4541-923a-a7744b271464\nmd\"\"\"\nFinally, let's clean up. Do not run the next cell unless you are sure that it will not erase your important files.\n\"\"\"\n\n# ╔═╡ d775d1a6-906c-4013-8ab7-5951cb5fe071\nforeach(f -> rm(string(\"./Data/\", f), force=true),\n\t[\"x0.csv\", \"x₀.bin\", \"x₀.jlso\", \"x₁.json\", \"x₂.json\", \"bigdf1.csv\", \"bigdf.bin\", \n\t\t\"bigdf.jlso\", \"bigdf1.json\", \"bigdf2.json\", \"x.zip\"])\n\n# ╔═╡ 2ad38587-5e55-4e24-9c23-a3180dd1bf99\nbegin\n\trm(\"bigdf.jdf\", recursive=true, force=true)\n\trm(\"x₀.jdf\", recursive=true, force=true)\nend\n\n# ╔═╡ e0fa8b35-19fd-4155-959d-51c2817199e6\nmd\"\"\"\nNote that we did not remove `x₀.arrow`, `bigdf.arrow` and `df_compress_test.csv.gz` - you have to do it manually, as these files are memory mapped.\n\"\"\"\n\n# ╔═╡ c54cdbf1-7787-4f0f-b9ff-d4389f4a7c5e\nhtml\"\"\"\n<style>\n main {\n max-width: calc(800px + 25px + 6px);\n }\n\n .plutoui-toc.aside {\n background: linen;\n }\n\n h3, h4, h5 {\n background: wheat;\n }\n</style>\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─b3dcf3f4-9d68-11eb-01a6-317fe0e0cd7e\n# ╠═794a5356-6e05-44b4-ad9d-375a1fa3613b\n# ╟─d6993a5b-8158-4ce3-accb-8e8c514229b3\n# ╟─de97ded0-3952-4188-9a43-a8f383e1ae65\n# ╠═887ea560-b824-44bd-96ba-7756271993e7\n# ╟─327fae3b-f00a-4bb4-ba95-a003e0740c58\n# ╠═b18bb84d-99f2-454e-b8bd-7c5e52b94141\n# ╟─ca9927e5-3ff2-4c73-8206-4d7495668312\n# ╠═696d306e-c000-47af-a904-eff748b317f3\n# ╟─157caf96-53ad-4ae6-aa1f-5d3fef0b178f\n# ╠═c04fb113-c95f-4a23-8884-147cdc62ac5c\n# ╟─06ee8941-57ef-4dfa-8385-861146755d53\n# ╠═ae8ac551-ea7f-4a9f-bfb4-e1b86677a6a8\n# ╠═86253acd-78a2-44c2-931e-f2322ed67dc2\n# ╟─069ea341-4097-42f5-83ff-18548bd34de2\n# ╟─a4615e9b-d3d9-443a-9146-e411f9bbd749\n# ╠═8cc8ae4d-44df-495b-9469-6b467abd6add\n# ╟─8c7e6303-0d09-4993-943f-d9bd3a9c316b\n# ╠═aa8ffd59-e791-4dca-bce7-05a18dfda955\n# ╠═b67f1614-90e2-4e4f-9890-9fd66d24cf5b\n# ╟─3d64997f-bfed-4c48-b962-d0bd6c7aa1ef\n# ╠═9be83f87-de31-4403-b567-4f488f88645e\n# ╟─2717467d-c2c5-4006-bc6f-f5c5de3c6304\n# ╠═1f9c7d56-3471-4679-aa17-c5ba3b7c31c6\n# ╠═332e66fe-5a54-4741-a09c-465afef318b7\n# ╟─494e54f6-f29c-457a-9aba-0b7a3cd143b9\n# ╠═2909e4a4-5355-4ca9-aca2-efc43d938b29\n# ╟─8beffe4b-051a-41e9-af93-10329564355f\n# ╠═43b9a909-dd99-4bf0-bf41-8a21c5127e24\n# ╟─424dc5a0-f64d-4563-a8be-99ffbb1b211d\n# ╠═6109fe95-9cd4-47b7-a79d-387e7aac78db\n# ╠═7211a7cc-3ab1-4c4e-a858-60ee8d910054\n# ╟─c7ea6a2b-8719-4a1a-b2ce-34237bbbc625\n# ╟─2516d88a-9141-4a25-90b3-fc212e6299f9\n# ╠═381916dc-3610-4df4-9911-c822d28d3956\n# ╟─db07eb7e-2fa7-44e7-adb6-c0254a83e0e3\n# ╠═4f63f693-8392-4e8e-a04e-00f45ba016a3\n# ╠═a3203a29-33f5-457a-9a90-80c5e14422a6\n# ╟─f12dc3e2-167d-4cad-a999-53c67d55af07\n# ╠═23b96b56-709f-4f5b-8bb9-961764f61faf\n# ╠═6223627b-7541-42f7-892a-80c86e3a95ec\n# ╠═f9281efb-e8aa-4267-9d63-7094e6010315\n# ╠═f215042e-5dec-4e2f-940f-02467c0b3d94\n# ╠═ef097417-b572-4110-b943-7b2500c81838\n# ╠═1aca803a-197a-47ac-8eb3-73ab3c40de47\n# ╠═0e193005-cd0b-4c1c-aa1e-42cee639238c\n# ╠═6dd53b4a-a936-40c3-873d-42abe4421189\n# ╟─dc97e056-2d8d-442e-90d2-b75931cecb33\n# ╠═d1a0d653-ac96-4712-bc26-430ba4436544\n# ╠═2244a140-ec46-4ec5-84c6-fc40511953ad\n# ╠═e392701a-75a4-465b-9547-a8d6a3bdc059\n# ╠═2bf8f141-c809-4599-ace3-3fabd1bbc1d6\n# ╠═f00b7857-6393-4501-b0a8-bfd7d50667c4\n# ╠═613569c5-20f4-4463-a039-12fecab721eb\n# ╟─edd10614-b548-4148-acf5-33e16ab0a8be\n# ╠═3d478ed4-cf5a-44a1-9441-6da73f7986d2\n# ╠═782f560a-9fd5-498b-9ff8-0215736b240e\n# ╠═5ab7852b-ea4e-42de-829f-a101e58a0b93\n# ╠═175391bb-3cdc-409f-8963-8aa3d613b601\n# ╠═5e475f09-3177-45b5-a9a1-f25c1cfeef37\n# ╠═2fac7472-ddf7-477e-9142-0640bda99890\n# ╟─d2df242d-259c-4935-b71b-e1d444ac6f07\n# ╠═b7b657d6-0723-4209-9ecb-efcc72be402f\n# ╠═8357bef1-d31c-4fa5-992f-f2a6eb6d9573\n# ╠═c33160d1-b12e-42ab-a3c3-b8d6bc58bd9d\n# ╠═544fbeae-ca73-487d-92b5-8d619d9b8db7\n# ╟─bcee6550-63e7-4ff2-a324-37bef45a28b9\n# ╠═50eee498-9548-4ee7-8375-90c17b376c0a\n# ╠═90eb146e-9dbf-45ef-a093-437fb938b10d\n# ╟─f5cb08ba-814e-4a7b-b676-5967a352d2a7\n# ╠═223e5415-0ab4-4016-b506-658adc75c57b\n# ╟─dd26958e-55f1-4b2e-b557-1bd24eb43fa0\n# ╠═8b87edb5-d8a7-4234-ac8d-f9e0c8f5f8a0\n# ╠═f257c2c9-6cdf-4df8-8b53-7a8d3794b7c3\n# ╠═ec462215-2451-4e8e-b440-58503378faae\n# ╠═4fb9645f-ee4d-410a-aec3-06f13fdec761\n# ╠═cc833913-383f-46ac-8ff2-5b6c8c8cbff4\n# ╟─c3f1fae0-4422-4023-b43f-de1651a89983\n# ╠═5a1bd5be-9329-44e8-848e-efb7bac1e5f4\n# ╟─1d8e3b27-8af6-4541-923a-a7744b271464\n# ╠═d775d1a6-906c-4013-8ab7-5951cb5fe071\n# ╠═2ad38587-5e55-4e24-9c23-a3180dd1bf99\n# ╟─e0fa8b35-19fd-4155-959d-51c2817199e6\n# ╟─c54cdbf1-7787-4f0f-b9ff-d4389f4a7c5e\n", "meta": {"hexsha": "f072f0b7688d8a8950b311429def981a7a7b5b75", "size": 21129, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "06-DataFrames/04_load_and_save.jl", "max_stars_repo_name": "pascal-p/julia-notebooks", "max_stars_repo_head_hexsha": "568c884c8b0de8ce34a84e8d1ce5fb6994cf32b8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-01T20:34:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-01T20:34:56.000Z", "max_issues_repo_path": "06-DataFrames/04_load_and_save.jl", "max_issues_repo_name": "pascal-p/julia-notebooks", "max_issues_repo_head_hexsha": "568c884c8b0de8ce34a84e8d1ce5fb6994cf32b8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "06-DataFrames/04_load_and_save.jl", "max_forks_repo_name": "pascal-p/julia-notebooks", "max_forks_repo_head_hexsha": "568c884c8b0de8ce34a84e8d1ce5fb6994cf32b8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-10T09:03:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-10T09:03:18.000Z", "avg_line_length": 31.0720588235, "max_line_length": 320, "alphanum_fraction": 0.7103033745, "num_tokens": 9126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.2782567877172032, "lm_q1q2_score": 0.1282810480951758}}
{"text": "module unifac\n\ninclude(\"general.jl\")\n\nimport Base: *\nmutable struct bonito\n frecuencia::Int\n nombre::String\nend\n\n*(x::Number, y::String) = bonito(x*1,y)\nusing Unitful\nusing NLsolve\n\n∑(x)=sum(x)\n\naₙₘ=[0\t86.02\t61.13\t76.5\t986.5\t697.2\t1318\t1333\t476.4\t677\t232.1\t507\t251.5\t391.5\t255.7\t206.6\t920.7\t287.77\t597\t663.5\t35.93\t53.76\t24.9\t104.3\t11.44\t661.5\t543\t153.6\t184.4\t354.55\t3025\t335.8\t479.5\t298.9\t526.5\t689\t-4.189\t125.8\t485.3\t-2.859\t387.1\t-450.4\t252.7\t220.3\t-5.869\t390.9\t553.3\t187\t216.1\t92.99\t699.13\t0\t0\t0\t808.59\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t-1243\t637.65;\n-35.36\t0\t38.81\t74.15\t524.1\t787.6\t270.6\t526.1\t182.6\t448.75\t37.85\t333.5\t214.5\t240.9\t163.9\t61.11\t749.3\t280.5\t336.9\t318.9\t-36.87\t58.55\t-13.99\t-109.7\t100.1\t357.5\t0\t76.3\t0\t262.9\t0\t0\t183.8\t31.14\t179\t-52.87\t-66.46\t359.3\t-70.45\t449.4\t48.33\t0\t0\t86.46\t0\t200.2\t268.1\t-617\t62.56\t0\t0\t0\t0\t0\t200.94\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t-861.46\t424.93;\n-11.12\t3.446\t0\t167\t636.1\t637.35\t903.8\t1329\t25.77\t347.3\t5.994\t287.1\t32.14\t161.7\t122.8\t90.49\t648.2\t-4.449\t212.5\t537.4\t-18.81\t-144.4\t-231.9\t3\t187\t168.04\t194.9\t52.068\t-10.43\t-64.69\t210.366\t113.3\t261.3\t154.26\t169.9\t383.9\t-259.1\t389.3\t245.6\t22.67\t103.5\t-432.3\t238.9\t30.04\t-88.11\t0\t333.3\t0\t-59.58\t-39.16\t0\t0\t0\t0\t360.82\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n-69.7\t-113.6\t-146.8\t0\t803.2\t603.25\t5695\t884.9\t-52.1\t586.8\t5688\t197.8\t213.1\t19.02\t-49.29\t23.5\t664.2\t52.8\t6096\t872.3\t-114.14\t-111\t-80.25\t-141.3\t-211\t3629\t4448\t-9.451\t393.6\t48.49\t4975\t259\t210\t-152.55\t4284\t-119.2\t-282.5\t101.4\t5629\t-245.39\t69.26\t0\t0\t46.38\t0\t0\t421.9\t0\t-203.6\t184.9\t0\t0\t0\t0\t233.51\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n156.4\t457\t89.6\t25.82\t0\t-137.1\t353.5\t-259.7\t84\t-203.6\t101.1\t267.8\t28.06\t8.642\t42.7\t-323\t-52.39\t170.029\t6.712\t199\t75.62\t65.28\t-98.12\t143.1\t123.5\t256.5\t157.1\t488.9\t147.5\t-120.46\t-318.93\t313.5\t202.1\t727.8\t-202.1\t74.27\t225.8\t44.78\t-143.9\t0\t190.3\t-817.7\t-1712.8\t-504.2\t72.96\t-382.7\t-248.3\t0\t104.7\t57.65\t0\t0\t0\t0\t215.81\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t-1840.8\t56.298;\n16.51\t-12.52\t-50\t-44.5\t249.1\t0\t-180.95\t-101.7\t23.39\t306.42\t-10.72\t179.7\t-128.6\t359.3\t-20.98\t53.9\t489.7\t580.48\t53.28\t-202\t-38.32\t-102.54\t-139.35\t-44.76\t-28.25\t75.14\t457.88\t-31.09\t17.5\t-61.76\t-119.2\t212.1\t106.3\t-119.1\t-399.3\t-5.224\t33.47\t-48.25\t-172.4\t0\t165.7\t0\t0\t0\t-52.1\t0\t0\t37.63\t-59.4\t-46.01\t0\t0\t0\t0\t150.02\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n300\t496.1\t362.3\t377.6\t-229.1\t289.6\t0\t324.5\t-195.4\t-116\t72.87\t233.87\t540.5\t48.89\t168\t304\t243.2\t459\t112.6\t-14.09\t325.44\t370.4\t353.68\t497.54\t133.9\t220.6\t399.5\t887.1\t0\t188.026\t12.72\t0\t777.1\t0\t-139\t160.8\t0\t0\t319\t0\t-197.5\t-363.8\t0\t-452.2\t0\t835.6\t139.6\t0\t407.9\t0\t0\t0\t0\t0\t-255.63\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n275.8\t217.5\t25.34\t244.2\t-451.6\t-265.2\t-601.8\t0\t-356.1\t-271.1\t-449.4\t-32.52\t-162.8742\t-832.97\t0\t0\t119.9\t-305.5\t0\t408.9\t0\t517.27\t0\t1827\t6915\t0\t-413.48\t8483.5\t0\t0\t-687.1\t0\t0\t0\t0\t0\t0\t0\t0\t0\t-494.2\t0\t0\t-659\t0\t0\t0\t0\t0\t1005\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n26.76\t42.92\t140.1\t365.8\t164.5\t108.65\t472.5\t-133.1\t0\t-37.36\t-213.7\t-190.4\t-103.6\t0\t-174.2\t-169\t6201\t7.341\t481.7\t669.4\t-191.69\t-130.3\t-354.55\t-39.2\t-119.8\t137.5\t548.5\t216.138\t-46.28\t-163.7\t71.46\t53.59\t245.2\t-246.6\t-44.58\t-63.5\t-34.57\t0\t-61.7\t0\t-18.8\t-588.9\t0\t0\t0\t0\t37.54\t0\t0\t-162.6\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n505.7\t56.3\t23.39\t106\t529\t-340.18\t480.8\t-155.6\t128\t0\t-110.3\t766\t304.1\t0\t0\t0\t0\t0\t-106.4\t497.5\t751.9\t67.52\t-483.7\t0\t0\t0\t0\t0\t0\t0\t0\t117\t0\t2.21\t0\t-339.2\t172.4\t0\t-268.8\t0\t-275.5\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n114.8\t132.1\t85.84\t-170\t245.4\t249.63\t200.8\t-36.72\t372.2\t185.1\t0\t-241.8\t-235.7\t0\t-73.5\t-196.7\t475.5\t-0.13\t494.6\t660.2\t-34.74\t108.85\t-209.66\t54.57\t442.4\t-81.13\t0\t183.046\t0\t202.25\t-101.7\t148.3\t18.88\t71.48\t52.08\t-28.61\t-275.2\t0\t85.33\t0\t560.2\t0\t0\t0\t0\t0\t151.8\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n329.3\t110.4\t18.12\t428\t139.4\t227.8\t124.63\t-234.25\t385.4\t-236.5\t1167\t0\t-234\t0\t0\t0\t0\t-233.4\t-47.25\t-268.1\t0\t31\t-126.2\t179.7\t24.28\t0\t0\t0\t103.9\t0\t0\t0\t298.13\t0\t0\t0\t-11.4\t0\t308.9\t0\t-122.3\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n83.36\t26.51\t52.13\t65.69\t237.7\t238.4\t-314.7\t-178.5461\t191.1\t-7.838\t461.3\t457.3\t0\t-78.36\t251.5\t5422.2998\t-46.39\t213.2\t-18.51\t664.6\t301.14\t137.77\t-154.3\t47.67\t134.8\t95.18\t155.11\t140.896\t-8.538\t170.1\t-20.11\t-149.5\t-202.3\t-156.57\t128.8\t0\t240.2\t-273.95\t254.8\t-172.51\t417\t1338\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n-30.48\t1.163\t-44.85\t296.4\t-242.8\t-481.65\t-330.4\t-870.8\t0\t0\t0\t0\t222.1\t0\t-107.2\t-41.11\t-200.7\t0\t358.9\t0\t-82.92\t0\t0\t-99.81\t30.05\t0\t0\t0\t-70.14\t0\t0\t0\t0\t0\t874.19\t0\t0\t0\t-164\t0\t0\t-664.4\t275.9\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n65.33\t-28.7\t-22.31\t223\t-150\t-370.3\t-448.2\t0\t394.6\t0\t136\t0\t-56.08\t127.4\t0\t-189.2\t138.54\t431.49\t147.1\t0\t0\t0\t0\t71.23\t-18.93\t0\t0\t0\t0\t0\t939.07\t0\t0\t0\t0\t0\t0\t570.9\t-255.22\t0\t-38.77\t448.1\t-1327\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n-83.98\t-25.38\t-223.9\t109.9\t28.6\t-406.8\t-598.8\t0\t225.3\t0\t2888.6001\t0\t-194.1\t38.89\t865.9\t0\t287.43\t0\t1255.1\t0\t-182.91\t-73.85\t-352.9\t-262\t-181.9\t0\t0\t0\t0\t0\t0\t0\t0\t0\t243.1\t0\t0\t-196.312\t22.05\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n1139\t2000\t247.5\t762.8\t-17.4\t-118.1\t-341.6\t-253.1\t-450.3\t0\t-294.8\t0\t285.36\t-15.07\t64.3\t-24.46\t0\t89.7\t-281.6\t-396\t287\t-111\t0\t882\t617.5\t0\t-139.3\t0\t0\t0\t0.1004\t0\t0\t0\t0\t0\t0\t0\t-334.4\t0\t-89.42\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n-101.56\t-47.63\t31.87\t49.8\t-132.3\t-378.24\t-332.9\t-341.6\t29.1\t0\t8.87\t554.4\t-156.1\t0\t-207.66\t0\t117.4\t0\t-169.67\t-153.7\t0\t-351.6\t-114.73\t-205.3\t-2.17\t0\t2845\t0\t0\t0\t0\t0\t-60.78\t0\t0\t0\t160.7\t-158.8\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t-136.6\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n24.82\t-40.62\t-22.97\t-138.4\t185.4\t162.6\t242.8\t0\t-287.5\t224.66\t-266.6\t99.37\t38.81\t-157.3\t-108.5\t-446.86\t777.4\t134.28\t0\t205.27\t4.933\t-152.7\t-15.62\t-54.86\t-4.624\t-0.515\t0\t230.852\t0.4604\t0\t177.5\t0\t-62.17\t-203.02\t0\t81.57\t-55.77\t0\t-151.5\t0\t120.3\t0\t0\t0\t0\t0\t16.23\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n315.3\t1264\t62.32\t89.86\t-151\t339.8\t-66.17\t-11\t-297.8\t-165.5\t-256.3\t193.9\t-338.5\t0\t0\t0\t493.8\t-313.5\t92.07\t0\t13.41\t-44.7\t39.63\t183.4\t-79.08\t0\t0\t0\t0\t-208.9\t0\t228.4\t-95\t0\t-463.6\t0\t-11.16\t0\t-228\t0\t-337\t0\t0\t0\t0\t-322.3\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n91.46\t40.25\t4.68\t122.91\t562.2\t529\t698.24\t0\t286.28\t-47.51\t35.38\t0\t225.39\t131.2\t0\t151.38\t429.7\t0\t54.32\t519.1\t0\t108.31\t249.15\t62.42\t153\t32.73\t86.2\t450.088\t59.02\t65.56\t0\t2.22\t344.4\t0\t0\t0\t-168.2\t0\t6.57\t0\t63.67\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n34.01\t-23.5\t121.3\t140.78\t527.6\t669.9\t708.69\t1633.5\t82.86\t190.6\t-132.95\t80.99\t-197.71\t0\t0\t-141.4\t140.8\t587.3\t258.6\t543.3\t-84.53\t0\t0\t56.33\t223.1\t108.9\t0\t0\t0\t149.56\t0\t177.6\t315.9\t0\t215\t0\t-91.8\t0\t-160.28\t0\t-96.87\t0\t0\t0\t0\t0\t361.1\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n36.7\t51.06\t288.5\t69.9\t742.1\t649.1\t826.76\t0\t552.1\t242.8\t176.45\t235.6\t-20.93\t0\t0\t-293.7\t0\t18.98\t74.04\t504.2\t-157.1\t0\t0\t-30.1\t192.1\t0\t0\t116.612\t0\t-64.38\t0\t86.4\t168.8\t0\t363.7\t0\t111.2\t0\t0\t0\t255.8\t0\t0\t-35.68\t0\t0\t0\t565.9\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n-78.45\t160.9\t-4.7\t134.7\t856.3\t709.6\t1201\t10000\t372\t0\t129.49\t351.9\t113.9\t261.1\t91.13\t316.9\t898.2\t368.5\t491.95\t631\t11.8\t17.97\t51.9\t0\t-75.97\t490.88\t534.7\t132.2\t0\t546.68\t0\t247.8\t146.6\t0\t337.7\t369.49\t187.1\t215.2\t498.6\t0\t256.5\t0\t233.1\t0\t0\t0\t423.1\t63.95\t0\t108.5\t0\t0\t0\t0\t585.19\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n106.8\t70.32\t-97.27\t402.5\t325.7\t612.8\t-274.5\t622.3\t518.4\t0\t-171.1\t383.3\t-25.15\t108.5\t102.2\t2951\t334.9\t20.18\t363.5\t993.4\t-129.7\t-8.309\t-0.2266\t248.4\t0\t132.7\t2213\t0\t0\t0\t0\t0\t593.4\t0\t1337.37\t0\t0\t0\t5143.1401\t309.58\t-71.18\t0\t0\t-209.7\t0\t0\t434.1\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n-32.69\t-1.996\t10.38\t-97.05\t261.6\t252.56\t417.9\t0\t-142.61\t0\t129.3\t0\t-94.49\t0\t0\t0\t0\t0\t0.283\t0\t113\t-9.639\t0\t-34.68\t132.9\t0\t533.2\t320.2\t0\t0\t139.822\t304.3\t10.17\t-27.701\t0\t0\t10.76\t0\t-223.1\t0\t248.4\t0\t0\t0\t-218.9\t0\t0\t0\t0\t-4.565\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n5541\t0\t1824\t-127.8\t561.6\t511.29\t360.7\t815.12\t-101.5\t0\t0\t0\t220.66\t0\t0\t0\t134.9\t2475\t0\t0\t1971\t0\t0\t514.6\t-123.1\t-85.12\t0\t0\t0\t0\t0\t2990\t-124\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n-52.65\t16.623\t21.497\t40.675\t609.8\t914.2\t1081\t1421.3\t303.657\t0\t243.775\t0\t112.382\t0\t0\t0\t0\t0\t335.743\t0\t-73.092\t0\t-26.058\t-60.71\t0\t277.8\t0\t0\t0\t0\t0\t292.7\t0\t0\t0\t0\t-47.37\t0\t0\t0\t469.8\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n-7.481\t0\t28.41\t19.56\t461.6\t448.6\t0\t0\t160.6\t0\t0\t201.5\t63.71\t106.7\t0\t0\t0\t0\t161\t0\t-27.94\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t31.66\t0\t0\t0\t78.92\t0\t0\t0\t0\t1004.2\t0\t0\t0\t-18.27\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n-25.31\t82.64\t157.29\t128.8\t521.63\t287\t23.484\t0\t317.5\t0\t-146.31\t0\t-87.31\t0\t0\t0\t0\t0\t0\t570.6\t-39.46\t-116.21\t48.484\t-133.16\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t43.37\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n139.93\t0\t221.4\t150.64\t267.6\t240.8\t-137.4\t838.4\t135.4\t0\t152\t0\t9.207\t0\t-213.74\t0\t192.3\t0\t169.6\t0\t0\t0\t0\t0\t0\t481.348\t0\t0\t0\t0\t0\t0\t0\t0\t-417.2\t0\t0\t0\t302.2\t0\t347.8\t0\t0\t-262\t0\t0\t-353.5\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n128\t0\t58.68\t26.41\t501.3\t431.3\t0\t0\t138\t245.9\t21.92\t0\t476.6\t0\t0\t0\t0\t0\t0\t616.6\t179.25\t-40.82\t21.76\t48.49\t0\t64.28\t2448\t-27.45\t0\t0\t0\t0\t6.37\t0\t0\t0\t0\t0\t0\t0\t68.55\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n-31.52\t174.6\t-154.2\t1112\t524.9\t494.7\t79.18\t0\t-142.6\t0\t24.37\t-92.26\t736.4\t0\t0\t0\t0\t-42.71\t136.9\t5256\t-262.3\t-174.5\t-46.8\t77.55\t-185.3\t125.3\t4288\t0\t0\t0\t0\t37.1\t0\t0\t32.9\t0\t-48.33\t0\t336.25\t0\t-195.1\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n-72.88\t41.38\t-101.12\t614.52\t68.95\t967.71\t0\t0\t443.615\t-55.87\t-111.45\t0\t173.77\t0\t0\t0\t0\t0\t329.12\t0\t0\t0\t0\t0\t0\t174.433\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t2073.2\t0\t-119.8\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n50.49\t64.07\t-2.504\t-143.2\t-25.87\t695\t-240\t0\t110.4\t0\t41.57\t0\t-93.51\t-366.51\t0\t-257.2\t0\t0\t0\t-180.2\t0\t-215\t-343.6\t-58.43\t-334.12\t0\t0\t0\t85.7\t0\t535.8\t0\t-111.2\t0\t0\t0\t0\t0\t-97.71\t0\t153.7\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n-165.9\t573\t-123.6\t397.4\t389.3\t218.8\t386.6\t0\t114.55\t354\t175.53\t0\t0\t0\t0\t0\t0\t0\t-42.31\t0\t0\t0\t0\t-85.148\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t-208.8\t0\t-8.804\t0\t423.4\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n47.41\t124.2\t395.8\t419.1\t738.9\t528\t0\t0\t-40.9\t183.8\t611.3\t134.5\t-217.9\t0\t0\t0\t0\t281.6\t335.2\t898.2\t383.2\t301.9\t-149.8\t-134.2\t0\t379.4\t0\t167.9\t0\t0\t0\t0\t322.42\t631.5\t0\t837.2\t0\t0\t255\t0\t730.8\t0\t0\t26.35\t0\t0\t0\t2429\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n-5.132\t-131.7\t-237.2\t-157.3\t649.7\t645.9\t0\t0\t0\t0\t0\t0\t167.3\t0\t-198.8\t116.478\t0\t159.8\t0\t0\t0\t0\t0\t-124.6\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t-110.65\t-117.17\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n-31.95\t249\t-133.9\t-240.2\t64.16\t172.2\t-287.1\t0\t97.04\t13.89\t-82.12\t-116.7\t-158.2\t49.7\t10.03\t-185.2\t343.7\t0\t150.6\t-97.77\t-55.21\t397.24\t0\t-186.7\t-374.16\t223.6\t0\t0\t-71\t0\t-191.7\t0\t-176.26\t6.699\t136.6\t5.15\t-137.7\t50.06\t0\t-5.579\t72.31\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n147.3\t62.4\t140.6\t839.83\t0\t0\t0\t0\t0\t0\t0\t0\t278.15\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t33.95\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t185.6\t55.8\t0\t0\t0\t0\t0\t111.8\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n529\t1397\t317.6\t615.8\t88.63\t171\t284.4\t-167.3\t123.4\t577.5\t-234.9\t145.4\t-247.8\t0\t284.5\t0\t-22.1\t0\t-61.6\t1179\t182.2\t305.4\t-193\t335.7\t956.1\t-124.7\t0\t885.5\t0\t-64.28\t-264.3\t288.1\t627.7\t0\t-29.34\t-53.91\t-198\t0\t-28.65\t0\t0\t0\t0\t0\t0\t0\t122.4\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n-34.36\t0\t787.9\t0\t1913\t0\t180.2\t0\t992.4\t0\t0\t0\t448.5\t961.8\t1464.2\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t-2166\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n110.2\t0\t234.4\t0\t430.06\t0\t0\t0\t0\t0\t0\t0\t0\t-125.2\t1603.8\t0\t0\t0\t0\t0\t0\t0\t0\t70.81\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t745.3\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n13.89\t-16.11\t-23.88\t6.214\t796.9\t0\t832.2\t-234.7\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t-196.2\t0\t161.5\t0\t0\t0\t-274.1\t0\t262\t0\t0\t0\t0\t0\t-66.31\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n30.74\t0\t167.9\t0\t794.4\t762.7\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t844\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t-32.17\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n27.97\t9.755\t0\t0\t394.8\t0\t-509.3\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t-70.25\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n-11.92\t132.4\t-86.88\t-19.45\t517.5\t0\t-205.7\t0\t156.4\t0\t-3.444\t0\t0\t0\t0\t0\t0\t0\t119.2\t0\t0\t-194.7\t0\t3.163\t7.082\t0\t0\t0\t0\t0\t515.8\t0\t0\t0\t0\t0\t0\t0\t0\t0\t101.2\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n39.93\t543.6\t0\t0\t0\t420\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t-363.1\t-11.3\t0\t0\t0\t0\t6.971\t0\t0\t0\t0\t0\t0\t0\t148.9\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n-23.61\t161.1\t142.9\t274.1\t-61.2\t-89.24\t-384.3\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n-8.479\t0\t23.93\t2.845\t682.5\t597.8\t0\t810.5\t278.8\t0\t0\t0\t0\t0\t0\t0\t0\t221.4\t0\t0\t0\t0\t0\t-79.34\t0\t176.3\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n456.19\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n245.21\t384.45\t47.05\t347.13\t72.19\t265.75\t627.39\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t75.04\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n125.36\t-391.81\t0\t0\t111.65\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t1517.5;\n221.56\t629.96\t0\t0\t122.19\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t-1869.9\t0]\n\naₙₘ=aₙₘ*u\"K\"\n\nno_sub=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,\n53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,\n103,104,105,106,107,108,109,118,119,178,179]\nR=[0.9011,0.6744,0.4469,0.2195,1.3454,1.1167,1.1173,0.8886,0.5313,0.3652,1.2663,1.0396,0.8121,1,1.4311,0.92,0.8952,1.6724,1.4457,0.998,1.9031,1.6764,1.242,\n1.145,0.9183,0.6908,0.9183,1.5959,1.3692,1.1417,1.4337,1.207,0.9795,1.1865,0.9597,1.06,2.9993,2.8332,2.667,1.8701,1.6434,1.3013,1.528,1.4654,1.238,1.0106,\n2.2564,2.0606,1.8016,2.87,2.6401,3.39,1.1562,2.0086,1.7818,1.5544,1.4199,2.057,1.877,1.651,3.168,2.4088,1.264,0.9492,1.292,1.0613,2.8266,2.3144,0.791,\n0.6605,0.6948,3.0856,2.6322,1.406,1.0105,0.615,1.38,1.6035,1.4443,1.2853,1.047,1.4838,1.303,1.1044,3.981,3.0356,2.2287,2.406,1.6493,1.8174,1.967,2.1721,\n2.6243,1.4515,2.1905,1.9637,2.8589,2.6322,2.4054,2.1226,1.8952,1.613,1.3863,1.1589,3.474,2.8569,2.6908,2.5247,1.0567,2.6869,2.4595,2.026,5.774]\nQ=[0.848,0.54,0.228,0,1.176,0.867,0.988,0.676,0.4,0.12,0.968,0.66,0.348,1.2,1.432,1.4,0.68,1.488,1.18,0.948,1.728,1.42,1.188,1.088,0.78,0.468,1.1,1.544,\n1.236,0.924,1.244,0.936,0.624,0.94,0.632,0.816,2.113,1.833,1.553,1.724,1.416,1.224,1.532,1.264,0.952,0.724,1.988,1.684,1.448,2.41,2.184,2.91,0.844,\n1.868,1.56,1.248,1.104,1.65,1.676,1.368,2.484,2.248,0.992,0.832,1.088,0.784,2.472,2.052,0.724,0.485,0.524,2.736,2.12,1.38,0.92,0.46,1.2,1.2632,1.0063,\n0.7494,0.4099,1.0621,0.7639,0.4657,3.2,2.644,1.916,2.116,1.416,1.648,1.828,2.1,2.376,1.248,1.796,1.488,2.428,2.12,1.812,1.904,1.592,1.368,1.06,0.748,\n2.796,2.14,1.86,1.58,0.732,2.12,1.808,0.868,4.932]\ngrupos=[1,1,1,1,2,2,2,2,3,3,4,4,4,5,6,7,8,9,9,10,11,11,12,13,13,13,13,14,14,14,15,15,15,16,16,17,18,18,18,19,19,20,20,21,21,21,22,22,22,23,23,24,25,26,\n26,26,27,28,29,29,30,31,32,33,34,34,35,36,37,2,38,39,39,40,40,40,41,42,42,42,42,43,43,43,44,45,45,45,45,45,45,45,45,46,46,46,46,46,46,47,47,48,48,48,\n49,50,50,50,51,55,55,84,85]\nsubgrupos=[\"CH3\",\"CH2\",\"CH\",\"C\",\"CH2=CH\",\"CH=CH\",\"CH2=C\",\"CH=C\",\"ACH\",\"AC\",\"ACCH3\",\"ACCH2\",\"ACCH\",\"OH\",\"CH3OH\",\"H2O\",\"ACOH\",\"CH3CO\",\"CH2CO\",\"CHO\",\"CH3COO\",\n\"CH2COO\",\"HCOO\",\"CH3O\",\"CH2O\",\"CHO\",\"THF\",\"CH3NH2\",\"CH2NH2\",\"CHNH2\",\"CH3NH\",\"CH2NH\",\"CHNH\",\"CH3N\",\"CH2N\",\"ACNH2\",\"C5H5N\",\"C5H4N\",\"C5H3N\",\"CH3CN\",\n\"CH2CN\",\"COOH\",\"HCOOH\",\"CH2CL\",\"CHCL\",\"CCL\",\"CH2CL2\",\"CHCL2\",\"CCL2\",\"CHCL3\",\"CCL3\",\"CCL4\",\"ACCL\",\"CH3NO2\",\"CH2NO2\",\n\"CHNO2\",\"ACNO2\",\"CS2\",\"CH3SH\",\"CH2SH\",\"FURFURAL\",\"DOH\",\"I\",\"BR\",\"CH≡C\",\"C≡C\",\"DMSO\",\"ACRY\",\"CL-(C=C)\",\"C=C\",\"ACF\",\"DMF\",\n\"HCON(..\",\"CF3\",\"CF2\",\"CF\",\"COO\",\"SIH3\",\"SIH2\",\"SIH\",\"SI\",\"SIH2O\",\"SIHO\",\"SIO\",\"NMP\",\"CCL3F\",\"CCL2F\",\"HCCL2F\",\"HCCLF\",\"CCLF2\",\"HCCLF2\",\"CCLF3\",\"CCL2F2\",\n\"AMH2\",\"AMHCH3\",\"AMHCH2\",\"AM(CH3)2\",\"AMCH3CH2\",\"AM(CH2)2\",\"C2H5O2\",\"C2H4O2\",\"CH3S\",\"CH2S\",\"CHS\",\"MORPH\",\"C4H4S\",\"C4H3S\",\"C4H2S\",\n\"NCO\",\"(CH2)2SU\",\"CH2CHSU\",\"IMIDAZOL\",\"BTI\"]\n#=aₙₘ=zeros(85,85)\nii=[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2\n,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4\n,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5\n,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8\n,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11\n,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13\n,13,13,13,13,13,13,13,13,13,13,13,13,14,14,14,14,14,14,14,14,14,14,14,14,15,15,15,15,15,15,15,15,15,15,15,15,16,16,16,16,16,16,16,16,16,16,17,17,17,17,17\n,17,17,17,17,17,17,18,18,18,18,18,18,18,18,18,18,18,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,20,20,20,20,20,20,20,20,20,20,20,20,20,21,21,21,21\n,21,21,21,21,21,21,21,21,21,21,22,22,22,22,22,22,22,22,22,22,22,22,23,23,23,23,23,23,23,23,23,23,23,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24\n,25,25,25,25,25,25,25,25,25,26,26,26,26,26,26,26,26,26,26,26,27,27,28,28,28,29,29,29,29,30,31,31,31,31,31,32,32,33,33,33,33,34,34,35,35,36,36,36,37,37,37\n,37,38,38,39,39,40,41,42,84]\njj=[2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,55,84,\n85,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,28,30,33,34,35,36,37,38,39,40,41,44,46,47,48,49,55,84,85,4,5,6,7,8,9,10,11,12,13,14,\n15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,47,49,50,55,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,\n23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,44,47,49,50,55,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,\n35,36,37,38,39,41,42,43,44,45,46,47,49,50,55,84,85,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,41,45,\n48,49,50,55,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,30,31,33,35,36,39,41,42,44,46,47,49,55,9,10,11,12,13,14,17,18,20,22,24,25,27,28,\n31,41,44,50,10,11,12,13,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,39,41,42,47,50,11,12,13,19,20,21,22,23,32,34,36,37,39,41,12,\n13,15,16,17,18,19,20,21,22,23,24,25,26,28,30,31,32,33,34,35,36,37,39,41,47,13,18,19,20,22,23,24,25,29,33,37,39,41,14,15,16,17,18,19,20,21,22,23,24,25,26,\n27,28,29,30,31,32,33,34,35,37,38,39,40,41,42,15,16,17,19,21,24,25,29,35,39,42,43,16,17,18,19,24,25,31,38,39,41,42,43,17,19,21,22,23,24,25,35,38,39,18,19,\n20,21,22,24,25,27,31,39,41,19,20,22,23,24,25,27,33,37,38,50,20,21,22,23,24,25,26,28,29,31,33,34,36,37,39,41,47,21,22,23,24,25,30,32,33,35,37,39,41,46,22,\n23,24,25,26,27,28,29,30,32,33,37,39,41,23,24,25,26,30,32,33,35,37,39,41,47,24,25,28,30,32,33,35,37,41,44,48,25,26,27,28,30,32,33,35,36,37,38,39,41,43,47,\n48,50,55,26,27,33,35,39,40,41,44,47,27,28,31,32,33,34,37,39,41,45,50,32,33,32,37,41,35,39,44,48,41,35,39,41,44,47,33,41,35,37,39,41,37,39,39,41,37,39,41,\n39,41,44,48,39,40,40,41,45,47,43,85]\na1=[86.02,61.13,76.5,986.5,697.2,1318,1333,476.4,677,232.1,507,251.5,391.5,255.7,206.6,920.7,287.77,597,663.5,35.93,53.76,24.9,104.3,11.44,661.5,543,153.6,184.4,354.55,3025,335.8,479.5,298.9,526.5,689,-4.189,125.8,485.3,-2.859,387.1,-450.4,252.7,220.3,-5.869,390.9,553.3,187,216.1,92.99,699.13,808.59,-1243,637.65,38.81,74.15,524.1,787.6,270.6,526.1,182.6,448.75,37.85,333.5,214.5,240.9,163.9,61.11,749.3,280.5,336.9,318.9,-36.87,58.55,-13.99,-109.7,100.1,357.5,76.3,262.9,183.8,31.14,179,-52.87,-66.46,359.3,-70.45,449.4,48.33,86.46,200.2,268.1,-617,62.56,200.94,-861.46,424.93,167,636.1,637.35,903.8,1329,25.77,347.3,5.994,287.1,32.14,161.7,122.8,90.49,648.2,-4.449,212.5,537.4,-18.81,-144.4,-231.9,3,187,168.04,194.9,52.068,-10.43,-64.69,210.366,113.3,261.3,154.26,169.9,383.9,-259.1,389.3,245.6,22.67,103.5,-432.3,238.9,30.04,-88.11,333.3,-59.58,-39.16,360.82,803.2,603.25,5695,884.9,-52.1,586.8,5688,197.8,213.1,19.02,-49.29,23.5,664.2,52.8,6096,872.3,-114.14,-111,-80.25,-141.3,-211,3629,4448,-9.451,393.6,48.49,4975,259,210,-152.55,4284,-119.2,-282.5,101.4,5629,-245.39,69.26,46.38,421.9,-203.6,184.9,233.51,-137.1,353.5,-259.7,84,-203.6,101.1,267.8,28.06,8.642,42.7,-323,-52.39,170.029,6.712,199,75.62,65.28,-98.12,143.1,123.5,256.5,157.1,488.9,147.5,-120.46,-318.93,313.5,202.1,727.8,-202.1,74.27,225.8,44.78,-143.9,190.3,-817.7,-1712.8,-504.2,72.96,-382.7,-248.3,104.7,57.65,215.81,-1840.8,56.298,-180.95,-101.7,23.39,306.42,-10.72,179.7,-128.6,359.3,-20.98,53.9,489.7,580.48,53.28,-202,-38.32,-102.54,-139.35,-44.76,-28.25,75.14,457.88,-31.09,17.5,-61.76,-119.2,212.1,106.3,-119.1,-399.3,-5.224,33.47,-48.25,-172.4,165.7,-52.1,37.63,-59.4,-46.01,150.02,324.5,-195.4,-116,72.87,233.87,540.5,48.89,168,304,243.2,459,112.6,-14.09,325.44,370.4,353.68,497.54,133.9,220.6,399.5,887.1,188.026,12.72,777.1,-139,160.8,319,-197.5,-363.8,-452.2,835.6,139.6,407.9,-255.63,-356.1,-271.1,-449.4,-32.52,-162.8742,-832.97,119.9,-305.5,408.9,517.27,1827,6915,-413.48,8483.5,-687.1,-494.2,-659,1005,-37.36,-213.7,-190.4,-103.6,-174.2,-169,6201,7.341,481.7,669.4,-191.69,-130.3,-354.55,-39.2,-119.8,137.5,548.5,216.138,-46.28,-163.7,71.46,53.59,245.2,-246.6,-44.58,-63.5,-34.57,-61.7,-18.8,-588.9,37.54,-162.6,-110.3,766,304.1,-106.4,497.5,751.9,67.52,-483.7,117,2.21,-339.2,172.4,-268.8,-275.5,-241.8,-235.7,-73.5,-196.7,475.5,-0.13,494.6,660.2,-34.74,108.85,-209.66,54.57,442.4,-81.13,183.046,202.25,-101.7,148.3,18.88,71.48,52.08,-28.61,-275.2,85.33,560.2,151.8,-234,-233.4,-47.25,-268.1,31,-126.2,179.7,24.28,103.9,298.13,-11.4,308.9,-122.3,-78.36,251.5,5422.2998,-46.39,213.2,-18.51,664.6,301.14,137.77,-154.3,47.67,134.8,95.18,155.11,140.896,-8.538,170.1,-20.11,-149.5,-202.3,-156.57,128.8,240.2,-273.95,254.8,-172.51,417,1338,-107.2,-41.11,-200.7,358.9,-82.92,-99.81,30.05,-70.14,874.19,-164,-664.4,275.9,-189.2,138.54,431.49,147.1,71.23,-18.93,939.07,570.9,-255.22,-38.77,448.1,-1327,287.43,1255.1,-182.91,-73.85,-352.9,-262,-181.9,243.1,-196.312,22.05,89.7,-281.6,-396,287,-111,882,617.5,-139.3,0.1004,-334.4,-89.42,-169.67,-153.7,-351.6,-114.73,-205.3,-2.17,2845,-60.78,160.7,-158.8,-136.6,205.27,4.933,-152.7,-15.62,-54.86,-4.624,-0.515,230.852,0.4604,177.5,-62.17,-203.02,81.57,-55.77,-151.5,120.3,16.23,13.41,-44.7,39.63,183.4,-79.08,-208.9,228.4,-95,-463.6,-11.16,-228,-337,-322.3,108.31,249.15,62.42,153,32.73,86.2,450.088,59.02,65.56,2.22,344.4,-168.2,6.57,63.67,0,56.33,223.1,108.9,149.56,177.6,315.9,215,-91.8,-160.28,-96.87,361.1,-30.1,192.1,116.612,-64.38,86.4,168.8,363.7,111.2,255.8,-35.68,565.9,-75.97,490.88,534.7,132.2,546.68,247.8,146.6,337.7,369.49,187.1,215.2,498.6,256.5,233.1,423.1,63.95,108.5,585.19,132.7,2213,593.4,1337.37,5143.1401,309.58,-71.18,-209.7,434.1,533.2,320.2,139.822,304.3,10.17,-27.701,10.76,-223.1,248.4,-218.9,-4.565,2990,-124,292.7,-47.37,469.8,31.66,78.92,1004.2,-18.27,43.37,-417.2,302.2,347.8,-262,-353.5,6.37,68.55,32.9,-48.33,336.25,-195.1,2073.2,-119.8,-97.71,153.7,-208.8,-8.804,423.4,255,730.8,26.35,2429,-110.65,-117.17,-5.579,72.31,111.8,122.4,-2166,1517.5]\na2=[-35.36,-11.12,-69.7,156.4,16.51,300,275.8,26.76,505.7,114.8,329.3,83.36,-30.48,65.33,-83.98,1139,-101.56,24.82,315.3,91.46,34.01,36.7,-78.45,106.8,-32.69,5541,-52.65,-7.481,-25.31,139.93,128,-31.52,-72.88,50.49,-165.9,47.41,-5.132,-31.95,147.3,529,-34.36,110.2,13.89,30.74,27.97,-11.92,39.93,-23.61,-8.479,456.19,245.21,125.36,221.56,3.446,-113.6,457,-12.52,496.1,217.5,42.92,56.3,132.1,110.4,26.51,1.163,-28.7,-25.38,2000,-47.63,-40.62,1264,40.25,-23.5,51.06,160.9,70.32,-1.996,16.623,82.64,174.6,41.38,64.07,573,124.2,-131.7,249,62.4,1397,-16.11,9.755,132.4,543.6,161.1,384.45,-391.81,629.96,-146.8,89.6,-50,362.3,25.34,140.1,23.39,85.84,18.12,52.13,-44.85,-22.31,-223.9,247.5,31.87,-22.97,62.32,4.68,121.3,288.5,-4.7,-97.27,10.38,1824,21.497,28.41,157.29,221.4,58.68,-154.2,-101.12,-2.504,-123.6,395.8,-237.2,-133.9,140.6,317.6,787.9,234.4,-23.88,167.9,-86.88,142.9,23.93,47.05,25.82,-44.5,377.6,244.2,365.8,106,-170,428,65.69,296.4,223,109.9,762.8,49.8,-138.4,89.86,122.91,140.78,69.9,134.7,402.5,-97.05,-127.8,40.675,19.56,128.8,150.64,26.41,1112,614.52,-143.2,397.4,419.1,-157.3,-240.2,839.83,615.8,6.214,-19.45,274.1,2.845,347.13,249.1,-229.1,-451.6,164.5,529,245.4,139.4,237.7,-242.8,-150,28.6,-17.4,-132.3,185.4,-151,562.2,527.6,742.1,856.3,325.7,261.6,561.6,609.8,461.6,521.63,267.6,501.3,524.9,68.95,-25.87,389.3,738.9,649.7,64.16,88.63,1913,430.06,796.9,794.4,394.8,517.5,-61.2,682.5,72.19,111.65,122.19,289.6,-265.2,108.65,-340.18,249.63,227.8,238.4,-481.65,-370.3,-406.8,-118.1,-378.24,162.6,339.8,529,669.9,649.1,709.6,612.8,252.56,511.29,914.2,448.6,287,240.8,431.3,494.7,967.71,695,218.8,528,645.9,172.2,171,762.7,420,-89.24,597.8,265.75,-601.8,472.5,480.8,200.8,124.63,-314.7,-330.4,-448.2,-598.8,-341.6,-332.9,242.8,-66.17,698.24,708.69,826.76,1201,-274.5,417.9,360.7,1081,23.484,-137.4,79.18,-240,386.6,-287.1,284.4,180.2,832.2,-509.3,-205.7,-384.3,627.39,-133.1,-155.6,-36.72,-234.25,-178.5461,-870.8,-253.1,-341.6,-11,1633.5,10000,622.3,815.12,1421.3,838.4,-167.3,-234.7,810.5,128,372.2,385.4,191.1,394.6,225.3,-450.3,29.1,-287.5,-297.8,286.28,82.86,552.1,372,518.4,-142.61,-101.5,303.657,160.6,317.5,135.4,138,-142.6,443.615,110.4,114.55,-40.9,97.04,123.4,992.4,156.4,278.8,185.1,-236.5,-7.838,224.66,-165.5,-47.51,190.6,242.8,245.9,-55.87,354,183.8,13.89,577.5,1167,461.3,136,2888.6001,-294.8,8.87,-266.6,-256.3,35.38,-132.95,176.45,129.49,-171.1,129.3,243.775,-146.31,152,21.92,24.37,-111.45,41.57,175.53,611.3,-82.12,-234.9,-3.444,457.3,554.4,99.37,193.9,80.99,235.6,351.9,383.3,201.5,-92.26,134.5,-116.7,145.4,222.1,-56.08,-194.1,285.36,-156.1,38.81,-338.5,225.39,-197.71,-20.93,113.9,-25.15,-94.49,220.66,112.382,63.71,-87.31,9.207,476.6,736.4,173.77,-93.51,-217.9,167.3,-158.2,278.15,-247.8,448.5,127.4,38.89,-15.07,-157.3,131.2,261.1,108.5,106.7,-366.51,49.7,961.8,-125.2,865.9,64.3,-207.66,-108.5,91.13,102.2,-213.74,-198.8,10.03,284.5,1464.2,1603.8,-24.46,-446.86,151.38,-141.4,-293.7,316.9,2951,-257.2,116.478,-185.2,117.4,777.4,493.8,429.7,140.8,898.2,334.9,134.9,192.3,343.7,-22.1,134.28,-313.5,587.3,18.98,368.5,20.18,2475,-42.71,281.6,159.8,221.4,92.07,54.32,258.6,74.04,491.95,363.5,0.283,335.743,161,169.6,136.9,329.12,-42.31,335.2,150.6,-61.6,119.2,519.1,543.3,504.2,631,993.4,570.6,616.6,5256,-180.2,898.2,-97.77,1179,-70.25,-84.53,-157.1,11.8,-129.7,113,1971,-73.092,-27.94,-39.46,179.25,-262.3,383.2,-55.21,182.2,0,17.97,-8.309,-9.639,-116.21,-40.82,-174.5,-215,301.9,397.24,305.4,-194.7,51.9,-0.2266,-26.058,48.484,21.76,-46.8,-343.6,-149.8,-193,-196.2,-363.1,248.4,-34.68,514.6,-60.71,-133.16,48.49,77.55,-58.43,-85.148,-134.2,-124.6,-186.7,335.7,70.81,3.163,-11.3,-79.34,75.04,132.9,-123.1,-185.3,-334.12,-374.16,33.95,956.1,161.5,7.082,-85.12,277.8,481.348,64.28,125.3,174.433,379.4,223.6,-124.7,844,176.3,2448,4288,-27.45,167.9,885.5,85.7,-71,-274.1,6.971,-64.28,535.8,-191.7,-264.3,262,515.8,37.1,288.1,-111.2,322.42,-176.26,627.7,631.5,6.699,136.6,-29.34,837.2,5.15,-53.91,-137.7,-198,-66.31,148.9,50.06,185.6,55.8,-28.65,-32.17,101.2,745.3,-1869.9]\nfor i=1:length(ii)\n aₙₘ[ii[i],jj[i]] = a1[i]\n aₙₘ[jj[i],ii[i]] = a2[i]\nend\nDataFrame(aₙₘ)\nCSV.write(\"a.csv\", DataFrame(aₙₘ))=#\n\ndic=Dict{String,Vector{Int}}(subgrupos[i]=>[grupos[i],no_sub[i]] for i=1:length(grupos))\ndic1=Dict{String,Vector{Float64}}(subgrupos[i]=>[R[i],Q[i]] for i=1:length(subgrupos))\n\nr(v,R,i,nn) = ∑(v[i,k]*R[k] for k=1:nn)\nq(v,Q,i,nn) = ∑(v[i,k]*Q[k] for k=1:nn)\nV(v,R,x,i::Int,n::Int,nn) = r(v,R,i,nn)/∑(r(v,R,j,nn)*x[j] for j=1:n)\nF(v,Q,x,i::Int,n::Int,nn) = q(v,Q,i,nn)/∑(q(v,Q,j,nn)*x[j] for j=1:n)\ne(v,Q,k,i,nn) = v[i,k]*Q[k]/q(v,Q,i,nn)\nτ(aₙₘ,T::Quantity,mm,k) = exp(-aₙₘ[mm,k]/T)\nτ(aₙₘ,T::Number,mm,k) = exp(-ustrip(aₙₘ[mm,k])/T)\nβ(v,Q,aₙₘ,T,i,k,nn) = ∑(e(v,Q,mm,i,nn)*τ(aₙₘ,T,k,mm) for mm=1:nn)\nθ(v,Q,x,k,n,nn) = ∑(x[i]*q(v,Q,i,nn)*e(v,Q,k,i,nn) for i=1:n)/∑(x[j]*q(v,Q,j,nn) for j=1:n)\ns(v,Q,x,aₙₘ,T,k,n,nn) = ∑(θ(v,Q,x,mm,n,nn)*τ(aₙₘ,T,k,mm) for mm=1:nn)\nγᶜ(v,Q,R,x,i::Int,n::Int,nn) = 1-V(v,R,x,i,n,nn)+log(V(v,R,x,i,n,nn))-5*q(v,Q,i,nn)*(1-V(v,R,x,i,n,nn)/F(v,Q,x,i,n,nn) +log(V(v,R,x,i,n,nn)/F(v,Q,x,i,n,nn)))\nγᴿ(v,Q,x,aₙₘ,T,i,n,nn) = q(v,Q,i,nn)*(1-∑(θ(v,Q,x,k,n,nn)*β(v,Q,aₙₘ,T,i,k,nn)/s(v,Q,x,aₙₘ,T,k,n,nn)-e(v,Q,k,i,nn)*log(β(v,Q,aₙₘ,T,i,k,nn)/s(v,Q,x,aₙₘ,T,k,n,nn)) for k=1:nn))\nγ(v,Q,R,x,aₙₘ,T,i,n,nn) = exp(γᶜ(v,Q,R,x,i,n,nn)+γᴿ(v,Q,x,aₙₘ,T,i,n,nn))\nPo(v,Q,R,x,aₙₘ,CA,T,i,n,nn) = x[i]*γ(v,Q,R,x,aₙₘ,T,i,n,nn)*general.P_Antoine(CA,T,i)\nPₜₒₜ(v,Q,R,x,aₙₘ,CA,T,n,nn) = ∑(Po(v,Q,R,x,aₙₘ,CA,T,i,n,nn) for i=1:n)\ny_calc(v,Q,R,x,aₙₘ,CA,T,i,n,nn)=Po(v,Q,R,x,aₙₘ,CA,T,i,n,nn)/Pₜₒₜ(v,Q,R,x,aₙₘ,CA,T,n,nn)\n\n\"\"\"\n pxy(n,T,CA,com,xx;uni=u\"Torr\")\n\n**Los campos de entrada son:**\n- `n :: Int` Es el numero de componentes\n- `T :: Float` Es la temperatura del sistema\n- `CA :: n×3 Array{Float,2}` Constantes de Antoine para los `n` componentes\n- `com :: `\n- `xx :: StepRange ó Vector` Son los puntos en el liquido donde se buscara el equilibrio con el vapor\n- `uni` Son las unidades en las que se desea el resultado, por defecto esta en Torr\n\n**Salida:**\n\nRegresa las fracciones de liquido `x`,\nlas fracciones del vapor `y` y la presión `P` en Torr (`m` es la longitud de `xx`).\n\n- `x :: n×m Array{Float64,2}` liquido\n- `y :: n×m Array{Float64,2}` vapor\n- `P :: m-element Array{Float64,1}` presión\n\"\"\"\nfunction pxy(n::Int,T,CA::Array,com,fre,xx;uni=u\"Torr\")\n T = T|> u\"K\"\n xx = general.nc(xx...)\n m = size(xx,2)\n n2 = length(com)\n v = zeros(n,n2)\n R = Vector{Float64}(undef,n2)\n Q = Vector{Float64}(undef,n2)\n gru = Vector{Int8}(undef,n2)\n for i=1:n2\n R[i],Q[i] = dic1[com[i]]\n gru[i] = dic[com[i]][1]\n end\n v = fre\n a = Array{Float64}(undef,n2,n2)*u\"K\"\n for i=1:n2, j=1:n2\n a[j,i] = aₙₘ[gru[i],gru[j]]\n end\n\n y = Array{Float64}(undef,n,m)\n P = Vector{Float64}(undef,m)*uni\n for i=1:m\n x = xx[:,i]\n for j=1:n\n y[j,i] = y_calc(v,Q,R,x,a,CA,T,j,n,n2)\n end\n P[i] = Pₜₒₜ(v,Q,R,x,a,CA,T,n,n2) |> uni\n end\n \n return xx,y,P\nend\n\n\"\"\"\n txy(n,Pobj,CA,com,xx;uni=u\"K\")\n\n**Los campos de entrada son:**\n- `n :: Int` Es el numero de componentes\n- `Pobj :: Float` Es la presión del sistema\n- `CA :: n×3 Array{Float,2}` Constantes de Antoine para los `n` componentes\n- `com :: `\n- `xx :: StepRange ó Vector` Son los puntos en el liquido donde se buscara el equilibrio con el vapor\n- `uni` Son las unidades en las que se desea el resultado, por defecto esta en grados kelvin\n\n**Salida:**\n\nRegresa las fracciones de liquido `x`,\nlas fracciones del vapor `y` y la temperatura `T` en grados kelvin (`m` es la longitud de `xx`).\n\n- `x :: n×m Array{Float64,2}` liquido\n- `y :: n×m Array{Float64,2}` vapor\n- `T :: m-element Array{Float64,1}` temperatura\n\"\"\"\nfunction txy(n::Int,Pobj,CA::Array,com,fre,xx;uni=u\"K\")\n Pobj = Pobj |> u\"Torr\"\n xx = general.nc(xx...)\n m = size(xx,2)\n n2 = length(com)\n v = zeros(n,n2)\n R = Vector{Float64}(undef,n2)\n Q = Vector{Float64}(undef,n2)\n gru = Vector{Int8}(undef,n2)\n for i=1:n2\n R[i],Q[i] = dic1[com[i]]\n gru[i] = dic[com[i]][1]\n end\n v = fre\n a = Array{Float64}(undef,n2,n2)*u\"K\"\n for i=1:n2, j=1:n2\n a[j,i] = aₙₘ[gru[i],gru[j]]\n end\n y = Array{Float64}(undef,n,m)\n T = Vector{Float64}(undef,m)*u\"K\"\n Tᵢ = 300.0\n #temperatura inicial\n for i=1:n\n if xx[i,1]==1\n T[1] = general.T_Antoine(CA,Pobj,i)\n Tᵢ = ustrip(u\"K\",T[1])\n end\n end\n for i = 1:m\n x = xx[:,i]\n P2ₜₒₜ(T) = Pₜₒₜ(v,Q,R,x,a,CA,T,n,n2) - ustrip(u\"Torr\",Pobj)\n #println(i)\n Pₛₒₗ = nlsolve(n_ary(P2ₜₒₜ),[Tᵢ])\n Tᵢ = Pₛₒₗ.zero[1]\n T[i] = Tᵢ*u\"K\"\n for j = 1:n\n y[j,i] = y_calc(v,Q,R,x,a,CA,T[i],j,n,n2)\n end\n end\n\n return xx,y,T .|> uni\nend\n\nend # module\n\n\n\n#=\n\n\nabstract type Temperature end\n\nstruct Celsius <: Temperature\n value::Float64\nend\n\nstruct Kelvin <: Temperature\n value::Float64\nend\n\nstruct Fahrenheit <: Temperature\n value::Float64\nend\n\nconst °C = Celsius(1)\nconst °F = Fahrenheit(1)\nconst K = Kelvin(1)\nK\n1.5K\nCelsius(10)\nType{Kelvin}\ntypeof(1K)\ntypeof(Celsius)\n# Handle converson and promotion of temperature\nconvert(::Type{Kelvin}, celsius::Celsius) = Kelvin(celsius.value + 273.15)\nconvert(::Type{Kelvin}, fahrenheit::Fahrenheit) = Kelvin(Celsius(fahrenheit))\nconvert(::Type{Celsius}, kelvin::Kelvin) = Celsius(kelvin.value - 273.15)\nconvert(::Type{Celsius}, fahrenheit::Fahrenheit) = Celsius((fahrenheit.value - 32)*5/9)\nconvert(::Type{Fahrenheit}, celsius::Celsius) = Fahrenheit(celsius.value*9/5 + 32)\nconvert(::Type{Fahrenheit}, kelvin::Kelvin) = Fahrenheit(Celsius(kelvin))\n\npromote_rule(::Type{Kelvin}, ::Type{Celsius}) = Kelvin\npromote_rule(::Type{Fahrenheit}, ::Type{Celsius}) = Celsius\npromote_rule(::Type{Fahrenheit}, ::Type{Kelvin}) = Kelvin\n\nKelvin(t::Temperature) = convert(Kelvin, t)\nCelsius(t::Temperature) = convert(Celsius, t)\nFahrenheit(t::Temperature) = convert(Fahrenheit, t)\n\n+(x::Temperature, y::Temperature) = +(promote(x,y)...)\n-(x::Temperature, y::Temperature) = -(promote(x,y)...)\nisapprox(x::Temperature, y::Temperature) = isapprox(promote(x,y)...)\n\n+(x::T, y::T) where {T <: Temperature} = T(x.value + y.value)\n-(x::T, y::T) where {T <: Temperature} = T(x.value - y.value)\nisapprox(x::T, y::T) where {T <: Temperature} = isapprox(x.value, y.value)\n\n*(x::Number, y::T) where {T <: Temperature} = T(x * y.value)\n@which *(1.,1K)\n\"\"\"\n#eliminar un metodo\n\njulia> f(x::Integer) = 2\nf (generic function with 1 method)\n\njulia> f(x::Int) = 3\nf (generic function with 2 methods)\n\njulia> f(1)\n3\n\njulia> m = @which f(1)\nf(x::Int64) in Main at REPL[2]:1\n\njulia> typeof(m)\nMethod\n\njulia> Base.delete_method(m)\n\njulia> f(1)\n2\n\"\"\"\n@which *(1.,1.)\n=#\n", "meta": {"hexsha": "cd13c15c53fbfc07e0d68723702c7c20222cccb0", "size": 41422, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/unifac.jl", "max_stars_repo_name": "EmilioAlvizo/TermoQuimica", "max_stars_repo_head_hexsha": "15cb020d79e32e6f21ec1277d19cb4de23fa9ee4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-01-29T01:01:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-29T01:07:33.000Z", "max_issues_repo_path": "src/unifac.jl", "max_issues_repo_name": "EmilioAlvizo/TermoQuimica", "max_issues_repo_head_hexsha": "15cb020d79e32e6f21ec1277d19cb4de23fa9ee4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-02-25T21:53:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-28T03:23:01.000Z", "max_forks_repo_path": "src/unifac.jl", "max_forks_repo_name": "EmilioAlvizo/TermoQuimica", "max_forks_repo_head_hexsha": "15cb020d79e32e6f21ec1277d19cb4de23fa9ee4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 109.582010582, "max_line_length": 4009, "alphanum_fraction": 0.5901936169, "num_tokens": 29476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.22815649166448124, "lm_q1q2_score": 0.12826421479109448}}
{"text": "################################################################################\n### Introduction to Scientific Programming and Machine Learning with Julia ###\n### ###\n### Run each script on a new clean Julia session ###\n### GitHub: https://github.com/sylvaticus/IntroSPMLJuliaCourse ###\n### Licence (apply to all material of the course: scripts, videos, quizes,..)###\n### Creative Commons By Attribution (CC BY 4.0), Antonello Lobianco ###\n################################################################################\n\n\n# # 0201 - Data Wrangling \n\n# ## Some stuff to set-up the environment..\n\ncd(@__DIR__) \nusing Pkg \nPkg.activate(\".\") \n## If using a Julia version different than 1.7 please uncomment and run the following line (reproductibility guarantee will hower be lost)\n## Pkg.resolve() \nPkg.instantiate()\nusing Random\nRandom.seed!(123)\n\n\n# ## Introduction\n\n# This segment will be mostly based on [DataFrames](https://github.com/JuliaData/DataFrames.jl) and related packages\n\n# !!! info DataFrames vs Matrix \n# DataFrames are popular format for **in-memory tabular data**. Their main advantages over Arrays are that they can efficiently store different types of data on each column (indeed each column is a wrapper over an `Array{T,1}` where `T` is specific to each column) and, thanks also to their named columns, provide convenient API for data operations, like indexing, querying , joining, split-apply-combine, etc. \n\n# !!! info\n# In most circunstances we can refer to dataframe columns either by using their name as a string, e.g. `\"Region\"`, or as symbol, e.g. `:Region`. In the rest of the segment we will use the strings approach.\n\n\n# ## Data import\n\n# Our example: Forest volumes and area by country and year\n# Source: Eurostat; units: forarea: Milion hectars, forvol: Milion cubic metres\n\n# ### Built-in solution: CSV --> Matrix\nusing DelimitedFiles # in the stdlib\ndata = convert(Array{Float64,2},readdlm(\"data.csv\",';')[2:end,3:end]) # Skip the first 1 row and the first 2 columns - out is a Matrix\n\n# ### CSV.jl: {CSV file, hardwritten data} --> DataFrame\nusing CSV, DataFrames\ndata = CSV.read(\"data.csv\",DataFrame) # source, sink, kword options\ndata = CSV.read(\"data.csv\",NamedTuple)\n\ndata = CSV.read(IOBuffer(\"\"\"\nCountry\tYear\tforarea\tforvol\nGermany\t2000\t11.354\t3381\nFrance\t2000\t15.288\t2254.28\nItaly\t2000\t8.36925\t1058.71\nSweden\t2000\t28.163\t3184.67\nGermany\t2020\t11.419\t3663\nFrance\t2020\t17.253\t3055.83\nItaly\t2020\t9.56613\t1424.4\nSweden\t2020\t27.98\t3653.91\n\"\"\"), DataFrame, copycols=true)\n\n# Some common CSV.jl options: `delim` (use `'\\t'` for tab delimited files), `quotechar`, `openquotechar`, `closequotechar`, `escapechar`, `missingstring`, `dateformat`, `append`, `writeheader`, `header`, `newline`, `quotestrings`, `decimal`, `header`, `normalizenames`, `datarow`, `skipto`, `footerskip`, `limit`, `transpose`, `comment`, `use_mmap`, `type`, `types` (e.g. `types=Dict(\"fieldFoo\" => Union{Missing,Int64})`), `typemap`, `pool`, `categorical`, `strict`, `silencewarnings`, `ignorerepeated`\n\n# ### XLSX.jl: xlsx -> {Matrix, DataFrame}\nusing XLSX\nsheetNames = XLSX.sheetnames(XLSX.readxlsx(\"data.xlsx\"))\ndata = XLSX.readxlsx(\"data.xlsx\")[\"Sheet1\"][\"A1:D9\"]\ndata = XLSX.readxlsx(\"data.xlsx\")[\"Sheet1\"][:]\ndata = XLSX.readdata(\"data.xlsx\", \"Sheet1\", \"A1:D9\")\nXLSX.readtable(\"data.xlsx\", \"Sheet1\") # tuple vector of (data) vectors, vector of symbols, usable as DF constructor\ndata = DataFrame(XLSX.readtable(\"data.xlsx\", \"Sheet1\")...) \n\n# ### OdsIO.jl: ods -> {Matrix, DataFrame}\nusing OdsIO\nods_read(\"data.ods\";sheetName=\"Sheet1\",retType=\"DataFrame\")\nods_read(\"data.ods\";sheetName=\"Sheet1\",retType=\"Matrix\",range=[(2,3),(9,4)]) # [(tlr,tlc),(brr,brc)]\n\n# ### HTTP.jl: from internet\nimport HTTP\nusing Pipe, ZipFile, Tar\nurlData = \"https://github.com/sylvaticus/IntroSPMLJuliaCourse/raw/main/lessonsSources/02_-_JULIA2_-_Scientific_programming_with_Julia/data.csv\"\nurlDataZ = \"https://github.com/sylvaticus/IntroSPMLJuliaCourse/raw/main/lessonsSources/02_-_JULIA2_-_Scientific_programming_with_Julia/data.zip\"\n\n\ndata = @pipe HTTP.get(urlData).body |>\n replace!(_, UInt8(';') => UInt8(' ')) |> # if we need to do modifications to the file before importing \n CSV.File(_, delim=' ') |>\n DataFrame;\n\n# ### ZipFile.jl : from a single zipped csv file..\n# ...on disk... \ndata = @pipe ZipFile.Reader(\"data.zip\").files[1] |>\n CSV.File(read(_), delim=';') |>\n DataFrame \n\n# ...or on internet:\ndata = @pipe HTTP.get(urlDataZ).body |>\n IOBuffer(_) |>\n ZipFile.Reader(_).files[1] |>\n CSV.File(read(_), delim=';') |>\n DataFrame \n\n \n# ### DataFrame constructor\n## named tuple of (colName,colData)..\ndata = DataFrame(\n country = [\"Germany\", \"France\", \"Italy\", \"Sweden\", \"Germany\", \"France\", \"Italy\", \"Sweden\"],\n year = [2000,2000,2000,2000,2020,2020,2020,2020],\n forarea = [11.354, 15.288, 8.36925, 28.163, 11.419, 17.253, 9.56613, 27.98],\n forvol = [3381, 2254.28, 1058.71, 3184.67, 3663, 3055.83, 1424.4, 3653.91]\n)\n\n# ### Matrix -> DataFrame\n\n# Headers and data separated:\n\nM = [\"Germany\"\t2000\t11.354\t3381\n \"France\"\t2000\t15.288\t2254.28\n \"Italy\"\t2000\t8.36925\t1058.71\n \"Sweden\"\t2000\t28.163\t3184.67\n \"Germany\"\t2020\t11.419\t3663\n \"France\"\t2020\t17.253\t3055.83\n \"Italy\"\t2020\t9.56613\t1424.4\n \"Sweden\"\t2020\t27.98\t3653.91]\nheaders = [\"Country\", \"Year\", \"forarea\", \"forvol\"]\n## array of colData arrays, array of headers\ndata = DataFrame([[M[:,i]...] for i in 1:size(M,2)], Symbol.(headers))\n\n# Headers on the first row of the matrix:\nM = [\"Country\"\t\"Year\"\t\"forarea\" \"forvol\"\n \"Germany\"\t2000\t11.354\t 3381\n \"France\"\t2000\t15.288\t 2254.28\n \"Italy\"\t2000\t8.36925\t 1058.71\n \"Sweden\"\t2000\t28.163\t 3184.67\n \"Germany\"\t2020\t11.419\t 3663\n \"France\"\t2020\t17.253\t 3055.83\n \"Italy\"\t2020\t9.56613\t 1424.4\n \"Sweden\"\t2020\t27.98\t 3653.91]\ndata = DataFrame([[M[2:end,i]...] for i in 1:size(M,2)], Symbol.(M[1,:])) # note the autorecognision of col types\n\n\n# ## Getting insights on the data\n\n# In VSCode, we can also use the workpanel for a nice sortable tabular view of a df\n\nshow(data,allrows=true,allcols=true)\nfirst(data,6)\nlast(data, 6)\ndescribe(data)\nnR,nC = size(data)\nnames(data)\nfor r in eachrow(data)\n println(r) # note is it a \"DataFrameRow\"\nend\nfor c in eachcol(data)\n println(c) # an array\n println(nonmissingtype(eltype(c)))\nend\n\n# ## Selection and querying data\n\n# ### Column(s) selection\n# In general we can select: (a) by name (strings or symbols) or by position; (b) a single or a vector of columns, (c) copying or making a view (a reference without copying) of the underlying data \ndata[:,[\"Country\",\"Year\"]] # copy, using strings\ndata[!,[:Country,:Year]] # view, using symbols\ndata.Year # equiv. to `data[!,Year]`\ndata[:,1] # also `data[!,1]`\ndata[:,Not([\"Year\"])]\n\n# ### Row(s) selection\ndata[1,:] # DataFrameRow\ndata[1:3,:] # DataFrame\n# Note rows have no title names as colums do.\n\n# ### Cell(s) selection\ndata[2,[2,4]]\ndata[2,\"forarea\"]\n\n# Note that the returned selection is:\n# * an `Array{T,1}` if it is a single column;\n# * a `DataFrameRow` (similar in behaviour to a `DataFrame`) if a single row;\n# * `T` if a single cell;\n# * an other `DataFrame` otherwise.\n\n# ### Boolean selection\n# Both rows and column of a DataFrame (but also of an Matrix) can be selected by passing an array of booleans as column or row mask (and, only for Matrices, also a matrix of booleans)\n\nmask = [false, false, false, false, true, true, true, true]\ndata[mask,:]\nmask = fill(false,nR,nC)\nmask[2:end,2:3] .= true\nmask\n## data[mask] # error !\nMatrix(data)[mask] \n\n# Boolean selection can be used to filter on conditions, e.g.:\ndata[data.Year .>= 2020,:]\ndata[[i in [\"France\", \"Italy\"] for i in data.Country] .&& (data.Year .== 2000),:] # note the parhenthesis\n\n# ### Filtering using the @subset macro from the `DataFramesMacro` package\nusing DataFramesMeta\n@subset(data, :Year .> 2010 )\ncolToFilter = :Country\n@subset(data, :Year .> 2010, cols(colToFilter) .== \"France\" ) # Conditions are \"end\" by default. If the column name is embedded in a varaible we eed to use `cols(varname)`\n\n# ### Filtering using the `Query` package\nusing Query \ndfOut = @from i in data begin # `i` is a single row\n @where i.Country == \"France\" .&& i.Year >= 2000\n ## Select a group of columns, eventually changing their name:\n @select {i.Year, FranceForArea=i.forarea} # or just `i` for the whole row\n @collect DataFrame\nend\n# long but flexible\n\n# ### Managing missing values\n\n# !!! tip\n# See also the section [`Missingness implementations`](@ref) for a general discussion on missing values\n\ndf = copy(data)\n## df[3,\"forarea\"] = missing # Error, type is Flat64, not Union{Float64,Missing}\ndf.forarea = allowmissing(df.forarea) # also disallowmissing\nallowmissing!(df)\ndf[3,\"forarea\"] = missing\ndf[6,\"forarea\"] = missing\ndf[6,\"Country\"] = missing\nnMissings = length(findall(x -> ismissing(x), df.forarea)) # Count `missing` values in a column.\ndropmissing(df)\ndropmissing(df[:,[\"forarea\",\"forvol\"]])\ncollect(skipmissing(df.forarea))\ncompletecases(df)\ncompletecases(df[!,[\"forarea\",\"forvol\"]])\n[df[ismissing.(df[!,col]), col] .= 0 for col in names(df) if nonmissingtype(eltype(df[!,col])) <: Number] # Replace `missing` with `0` values in all numeric columns, like `Float64` and `Int64`;\n[df[ismissing.(df[!,col]), col] .= \"\" for col in names(df) if nonmissingtype(eltype(df[!,col])) <: AbstractString] # Replace `missing` with `\"\"` values in all string columns;\ndf\n\n# ## Editing data\ndf = copy(data)\ndf[1,\"forarea\"] = 11.3\ndf[[2,4],\"forarea\"] .= 10\ndf\npush!(df,[\"UK\",2020,5.0,800.0]) # add row\nsort!(df,[\"Country\",\"Year\"], rev=false)\ndf2 = similar(df) # rubish inside\ndf = similar(df,0) # empty a dataframe. The second parameter is the number of rows desired\n\n# ## Work on dataframe structure\n\ndf = copy(data)\ndf.foo = [1,2,3,4,5,6,7,8] # existing or new column\ndf.volHa = data.forvol ./ data.forarea\ndf.goo = Array{Union{Missing,Float64},1}(missing,size(data,1))\nselect!(df,Not([\"foo\",\"volHa\",\"goo\"])) # remove cols by name\nrename!(df, [\"Country2\", \"Year2\", \"forarea2\", \"forvol2\"])\nrename!(df, Dict(\"Country2\" => \"Country\"))\ndf = df[:,[\"Year2\", \"Country\",\"forarea2\",\"forvol2\"] ] # change column order\ninsertcols!(df, 2, :foo => [1,2,3,4,5,6,7,8] ) # insert a column at position 2\n\ndf.namedYear = map(string,df.Year2)\nstringToInt(str) = try parse(Int64, str) catch; return(missing) end; df.Year3 = map(stringToInt, df.namedYear)\n\ndf2 = hcat(df,data,makeunique=true) \ndf3 = copy(data)\ndf4 = vcat(data,df3)\n\n# ### Categorical data\nusing CategoricalArrays # You may want to consider also PooledArrays\ndf.Year2 = categorical(df.Year2)\ntransform!(df, names(df, AbstractString) .=> categorical, renamecols=false) # transform to categorical all string columns\n\n# !!! warning\n# Attention that while the memory to store the data decreases, and grouping is way more efficient, filtering with categorical values is not necessarily quicker (indeed it can be a bit slower)\n\nlevels(df.Year2)\nlevels!(df.Country,[\"Sweden\",\"Germany\",\"France\",\"Italy\"]) # Let you define a personalised order, useful for ordered data\nsort(df.Country)\nsort!(df,\"Country\")\ndf.Years2 = unwrap.(df.Year2) # convert a categorical array into a normal one.\n\n# ### Joining dataframes\ndf1,df2 = copy(data),copy(data)\npush!(df1,[\"US\",2020,5.0,1000.0])\npush!(df2,[\"China\",2020,50.0,1000.0])\nrename!(df2,\"Year\"=>\"year\")\ninnerjoin(df1,df2,on=[\"Country\",\"Year\"=>\"year\"],makeunique=true) # common records only \n# Also available: `leftjoin` (all records on left df), `rightjoin` (all on right df), `outerjoin`(all records returned), `semijoin` (like inner join by only with columns from the right df), `antijoin` (left not on right df) and `crossjoin` (like the cartesian product, each on the right by each on the left)\n\n# ## Pivoting data\n\n# _long_ and _wide_ are two kind of layout for equivalent representation of tabled data.\n# In a _long_ layout we have each row being an observation of a single variable, and each record is represented as dim1, dim2, ..., value. As the name implies, \"long\" layouts tend to be relativelly long and hard to analyse by an human, but are very easity to handle.\n# At the opposite, A _wide_ layout represents multiple observations on the same row, eventually using multiple horizontal axis as in the next figure (but Julia dataframes handle only a single horizzontal axis):\n\n# | | | | | |\n# | -------- | ------------ | ----- | ---------------- | ---- |\n# | | Forest Area | | Forest Volumes | |\n# | | 2000 | 2020 | 2000 | 2020 |\n# | Germany | 11.35 | 11.42 | 3381 | 3663 |\n# | France | 15.29 | 17.25 | 2254 | 3056 |\n\n# _wide layout is easier to visually analise for a human mind but much more hard to analyse in a sistermatic way. We will learn now how to move from one type of layout to the other.\n\n# ### Stacking columns: from _wide_ to _long_\nlongDf = stack(data,[\"forarea\",\"forvol\"]) # we specify the variable to stack (the \"measured\" variables)\nlongDf2 = stack(data,Not([\"Country\",\"Year\"])) # we specify the variables _not_ to stack (the id variables)\nlongDf3 = stack(data) # automatically stack all numerical variables\nlongDf == longDf2 == longDf3\n# Note how the columns `variable` and `value` have been added automatically to host the stachked data\n\n# ### Unstacking columns: from _wide_ to _long_\nwideDf = unstack(longDf,[\"Country\",\"Year\"],\"variable\",\"value\") # args: df, [cols to remains cols also in the wide layout], column with the ids to expand horizontally and column with the relative values\nwideDf2 = unstack(longDf,\"variable\",\"value\") # cols to remains cols also in the wide layout omitted: all cols not to expand and relative value col remains as col\nwideDf == wideDf2 == data\n\n# While the DataFrames package doesn't support multiple axis we can still arrive to the table below with a little bit of work by unstacking different columns in separate wide dataframes and then joining or horizontally concatenating them:\nwideArea = unstack(data,\"Country\",\"Year\",\"forarea\")\nwideVols = unstack(data,\"Country\",\"Year\",\"forvol\")\nrename!(wideArea,[\"Country\",\"area_2000\",\"area_2020\"])\nrename!(wideVols,[\"Country\",\"vol_2000\",\"vol_2020\"])\nwideWideDf = outerjoin(wideArea,wideVols,on=\"Country\") \n\n# ## The Split-Apply-Combine strategy\n\n# Aka \"divide and conquer\". Rather than try to modify the dataset direclty, we first split it in subparts, we work on each subpart and then we recombine them in a target dataset\n\nusing Statistics # for `mean`\ngroupby(data,[\"Country\",\"Year\"]) # The \"split\" part\n\n# Aggregation:\ncombine(groupby(data,[\"Year\"]) , \"forarea\" => sum => \"sum_area\", \"forvol\" => sum => \"sum_vol\", nrow)\n# ...or...\ncombine(groupby(data,[\"Year\"])) do subdf # slower\n (sumarea = sum(subdf.forarea), sumvol = sum(subdf.forvol), nCountries = size(subdf,1))\nend\n# Cumulative computation:\na = combine(groupby(data,[\"Year\"])) do subdf # slower\n (country = subdf.Country, area = subdf.forarea, cumArea = cumsum(subdf.forarea))\nend\n\n# Note in these examples that while in the aggregation we was returning a _single record_ for each subgroup (hence we did some dimensionality reduction) in the cumulative compuation we still output the whole subgroup, so the combined dataframe in output has the same number of rows as the original dataframe.\n\n# An alternative approach is to use the `@linq` macro from the `DatAFrameMEta` package that provide a R's `dplyr`-like query language using piped data: \nusing DataFramesMeta\ndfCum = @linq data |>\n groupby([:Year]) |>\n transform(:cumArea = cumsum(:forarea))\n\n# ## Export and saving \n\n# ### DataFrame to Matrix\n\nM = Matrix(data)\n# !!! warning\n# Attention that if the dataframe contains different types across columns, the inner type of the matrix will be `Any`\n\nM = Matrix{Union{Float64,Int64,String}}(data)\n\n# ### DataFrame to Dictionary\n\nfunction toDict(df, dimCols, valueCol)\n toReturn = Dict()\n for r in eachrow(df)\n keyValues = []\n [push!(keyValues,r[d]) for d in dimCols]\n toReturn[(keyValues...,)] = r[valueCol]\n end\n return toReturn\nend\ndict = toDict(data,[\"Country\",\"Year\"],[\"forarea\",\"forvol\"])\ndict[\"Germany\",2000][1]\ndict[\"Germany\",2000][\"forvol\"]\ntoDict(data,[\"Country\",\"Year\"],\"forarea\")\n\n# ### DataFrame to NamedTuple\n\nnT = NamedTuple(Dict([Symbol(c) => data[:,c] for c in names(data)])) # order not necessarily preserved\nusing DataStructures\nnT = NamedTuple(OrderedDict([Symbol(c) => data[:,c] for c in names(data)])) # order preserved\n\n# ### Saving as CSV file\n\nCSV.write(\"outdata.csv\",data) # see options at the beginning of segment in the import section and `? CSV.write` for specific export options\n\n# ### Saving as OpenDocument spreadsheet\n\nods_write(\"outdata.ods\",Dict((\"myData\",3,2) => data)) # exported starting on cell B3 of sheet \"myData\"\n\n# ### Saving as Excel spreadsheet\nXLSX.writetable(\"outdata.xlsx\",myData = (collect(eachcol(data)),names(data)))\n\n", "meta": {"hexsha": "a1063ad10d028efe4dfe3a9f44d08fa5ee528b8c", "size": 17418, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lessonsSources/02_-_JULIA2_-_Scientific_programming_with_Julia/0201_-_Wranging_data.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": "lessonsSources/02_-_JULIA2_-_Scientific_programming_with_Julia/0201_-_Wranging_data.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": "lessonsSources/02_-_JULIA2_-_Scientific_programming_with_Julia/0201_-_Wranging_data.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": 44.4336734694, "max_line_length": 502, "alphanum_fraction": 0.6678149041, "num_tokens": 5007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.2720245392906821, "lm_q1q2_score": 0.12646463576836017}}
{"text": "# Automatically generated by gen_gm.jl, do not edit!\n\ngrav_param(::Float64, ::SolarSystemBarycenter) = 1.3271244004193938e11\ngrav_param(::SolarSystemBarycenter) = grav_param(Float64, SolarSystemBarycenter())\ngrav_param(::Type{Float64}, ::MercuryBarycenter) = 22031.78000000002\ngrav_param(::MercuryBarycenter) = grav_param(Float64, MercuryBarycenter())\ngrav_param(::Type{Float64}, ::VenusBarycenter) = 324858.59200000006\ngrav_param(::VenusBarycenter) = grav_param(Float64, VenusBarycenter())\ngrav_param(::Type{Float64}, ::EarthBarycenter) = 403503.2355022598\ngrav_param(::EarthBarycenter) = grav_param(Float64, EarthBarycenter())\ngrav_param(::Type{Float64}, ::MarsBarycenter) = 42828.37521400002\ngrav_param(::MarsBarycenter) = grav_param(Float64, MarsBarycenter())\ngrav_param(::Type{Float64}, ::JupiterBarycenter) = 1.267127648000002e8\ngrav_param(::JupiterBarycenter) = grav_param(Float64, JupiterBarycenter())\ngrav_param(::Type{Float64}, ::SaturnBarycenter) = 3.79405852e7\ngrav_param(::SaturnBarycenter) = grav_param(Float64, SaturnBarycenter())\ngrav_param(::Type{Float64}, ::UranusBarycenter) = 5.794548600000008e6\ngrav_param(::UranusBarycenter) = grav_param(Float64, UranusBarycenter())\ngrav_param(::Type{Float64}, ::NeptuneBarycenter) = 6.836527100580024e6\ngrav_param(::NeptuneBarycenter) = grav_param(Float64, NeptuneBarycenter())\ngrav_param(::Type{Float64}, ::PlutoBarycenter) = 977.0000000000007\ngrav_param(::PlutoBarycenter) = grav_param(Float64, PlutoBarycenter())\ngrav_param(::Type{Float64}, ::Sun) = 1.3271244004193938e11\ngrav_param(::Sun) = grav_param(Float64, Sun())\ngrav_param(::Type{Float64}, ::Mercury) = 22031.78000000002\ngrav_param(::Mercury) = grav_param(Float64, Mercury())\ngrav_param(::Type{Float64}, ::Venus) = 324858.59200000006\ngrav_param(::Venus) = grav_param(Float64, Venus())\ngrav_param(::Type{Float64}, ::Earth) = 398600.435436096\ngrav_param(::Earth) = grav_param(Float64, Earth())\ngrav_param(::Type{Float64}, ::Mars) = 42828.37362069909\ngrav_param(::Mars) = grav_param(Float64, Mars())\ngrav_param(::Type{Float64}, ::Jupiter) = 1.266865349218008e8\ngrav_param(::Jupiter) = grav_param(Float64, Jupiter())\ngrav_param(::Type{Float64}, ::Saturn) = 3.793120749865224e7\ngrav_param(::Saturn) = grav_param(Float64, Saturn())\ngrav_param(::Type{Float64}, ::Uranus) = 5.793951322279009e6\ngrav_param(::Uranus) = grav_param(Float64, Uranus())\ngrav_param(::Type{Float64}, ::Neptune) = 6.835099502439672e6\ngrav_param(::Neptune) = grav_param(Float64, Neptune())\ngrav_param(::Type{Float64}, ::Pluto) = 869.6138177608748\ngrav_param(::Pluto) = grav_param(Float64, Pluto())\ngrav_param(::Type{Float64}, ::Luna) = 4902.800066163796\ngrav_param(::Luna) = grav_param(Float64, Luna())\ngrav_param(::Type{Float64}, ::Phobos) = 0.0007087546066894452\ngrav_param(::Phobos) = grav_param(Float64, Phobos())\ngrav_param(::Type{Float64}, ::Deimos) = 9.615569648120313e-5\ngrav_param(::Deimos) = grav_param(Float64, Deimos())\ngrav_param(::Type{Float64}, ::Io) = 5959.916033410404\ngrav_param(::Io) = grav_param(Float64, Io())\ngrav_param(::Type{Float64}, ::Europa) = 3202.738774922892\ngrav_param(::Europa) = grav_param(Float64, Europa())\ngrav_param(::Type{Float64}, ::Ganymede) = 9887.834453334144\ngrav_param(::Ganymede) = grav_param(Float64, Ganymede())\ngrav_param(::Type{Float64}, ::Callisto) = 7179.28936139727\ngrav_param(::Callisto) = grav_param(Float64, Callisto())\ngrav_param(::Type{Float64}, ::Amalthea) = 0.1378480571202615\ngrav_param(::Amalthea) = grav_param(Float64, Amalthea())\ngrav_param(::Type{Float64}, ::Mimas) = 2.503522884661795\ngrav_param(::Mimas) = grav_param(Float64, Mimas())\ngrav_param(::Type{Float64}, ::Enceladus) = 7.211292085479989\ngrav_param(::Enceladus) = grav_param(Float64, Enceladus())\ngrav_param(::Type{Float64}, ::Tethys) = 41.21117207701302\ngrav_param(::Tethys) = grav_param(Float64, Tethys())\ngrav_param(::Type{Float64}, ::Dione) = 73.11635322923193\ngrav_param(::Dione) = grav_param(Float64, Dione())\ngrav_param(::Type{Float64}, ::Rhea) = 153.9422045545342\ngrav_param(::Rhea) = grav_param(Float64, Rhea())\ngrav_param(::Type{Float64}, ::Titan) = 8978.138845307376\ngrav_param(::Titan) = grav_param(Float64, Titan())\ngrav_param(::Type{Float64}, ::Hyperion) = 0.3718791714191668\ngrav_param(::Hyperion) = grav_param(Float64, Hyperion())\ngrav_param(::Type{Float64}, ::Iapetus) = 120.5134781724041\ngrav_param(::Iapetus) = grav_param(Float64, Iapetus())\ngrav_param(::Type{Float64}, ::Phoebe) = 0.5531110414633374\ngrav_param(::Phoebe) = grav_param(Float64, Phoebe())\ngrav_param(::Type{Float64}, ::Janus) = 0.1266231296945636\ngrav_param(::Janus) = grav_param(Float64, Janus())\ngrav_param(::Type{Float64}, ::Epimetheus) = 0.03513977490568457\ngrav_param(::Epimetheus) = grav_param(Float64, Epimetheus())\ngrav_param(::Type{Float64}, ::Atlas) = 0.0003759718886965353\ngrav_param(::Atlas) = grav_param(Float64, Atlas())\ngrav_param(::Type{Float64}, ::Prometheus) = 0.01066368426666134\ngrav_param(::Prometheus) = grav_param(Float64, Prometheus())\ngrav_param(::Type{Float64}, ::Pandora) = 0.0091037683110543\ngrav_param(::Pandora) = grav_param(Float64, Pandora())\ngrav_param(::Type{Float64}, ::Ariel) = 83.46344431770477\ngrav_param(::Ariel) = grav_param(Float64, Ariel())\ngrav_param(::Type{Float64}, ::Umbriel) = 85.09338094489388\ngrav_param(::Umbriel) = grav_param(Float64, Umbriel())\ngrav_param(::Type{Float64}, ::Titania) = 226.9437003741248\ngrav_param(::Titania) = grav_param(Float64, Titania())\ngrav_param(::Type{Float64}, ::Oberon) = 205.3234302535623\ngrav_param(::Oberon) = grav_param(Float64, Oberon())\ngrav_param(::Type{Float64}, ::Miranda) = 4.3195168992321\ngrav_param(::Miranda) = grav_param(Float64, Miranda())\ngrav_param(::Type{Float64}, ::Triton) = 1427.598140725034\ngrav_param(::Triton) = grav_param(Float64, Triton())\ngrav_param(::Type{Float64}, ::Charon) = 105.8799888601881\ngrav_param(::Charon) = grav_param(Float64, Charon())\ngrav_param(::Type{Float64}, ::Nix) = 0.00304817564816976\ngrav_param(::Nix) = grav_param(Float64, Nix())\ngrav_param(::Type{Float64}, ::Hydra) = 0.003211039206155255\ngrav_param(::Hydra) = grav_param(Float64, Hydra())\ngrav_param(::Type{Float64}, ::Kerberos) = 0.001110040850536676\ngrav_param(::Kerberos) = grav_param(Float64, Kerberos())\ngrav_param(::Type{Float64}, ::Ceres) = 63.13\ngrav_param(::Ceres) = grav_param(Float64, Ceres())\ngrav_param(::Type{Float64}, ::Pallas) = 13.73\ngrav_param(::Pallas) = grav_param(Float64, Pallas())\ngrav_param(::Type{Float64}, ::Vesta) = 17.29\ngrav_param(::Vesta) = grav_param(Float64, Vesta())\ngrav_param(::Type{Float64}, ::Psyche) = 1.81\ngrav_param(::Psyche) = grav_param(Float64, Psyche())\ngrav_param(::Type{Float64}, ::Eros) = 0.0004463\ngrav_param(::Eros) = grav_param(Float64, Eros())\ngrav_param(::Type{Float64}, ::Davida) = 2.26\ngrav_param(::Davida) = grav_param(Float64, Davida())\n", "meta": {"hexsha": "c8ecd17507dd3ba11948e99805804a28e100d464", "size": 6765, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "gen/gm.jl", "max_stars_repo_name": "matzipan/AstroBase.jl", "max_stars_repo_head_hexsha": "977061f1b5201c0cfb90e4e4e90826ac2ae6c7b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-26T19:15:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-26T19:15:00.000Z", "max_issues_repo_path": "gen/gm.jl", "max_issues_repo_name": "ravising-h/AstroBase.jl", "max_issues_repo_head_hexsha": "f67976b0635741aa3965ebf325fd372636bec92f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gen/gm.jl", "max_forks_repo_name": "ravising-h/AstroBase.jl", "max_forks_repo_head_hexsha": "f67976b0635741aa3965ebf325fd372636bec92f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.8487394958, "max_line_length": 82, "alphanum_fraction": 0.7495934959, "num_tokens": 2271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.24220562325537975, "lm_q1q2_score": 0.1248860430505794}}
{"text": "# ------------------------------------------------------------------------------------------\n# # Despacho múltiple / multiple dispatch\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# En este notebook vamos a explorar **multiple dispatch**, un concepto fundamental en Julia.\n#\n# Multiple dispatch permite software:\n# - rápido\n# - extendible\n# - programable\n# - divertido para experimentar\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# Para entender el despacho múltiple en Julia, observemos el operador `+`. <br>\n#\n# Si llamamos `methods()` sobre `+`, podemos ver todas las definiciones de `+`\n# ------------------------------------------------------------------------------------------\n\nmethods(+)\n\n# ------------------------------------------------------------------------------------------\n# Podemos usar el macro de `@which` para saber qué método en particular estamos usando de\n# `+`.<br>\n#\n# Distintos métodos se usan en cada uno de estos ejemplos.\n# ------------------------------------------------------------------------------------------\n\n@which 3 + 3\n\n@which 3.0 + 3.0 \n\n@which 3 + 3.0\n\n# ------------------------------------------------------------------------------------------\n# Aún más, pues podemos definir nuevos métodos de `+`. <br>\n#\n# Primero tenemos que importar `+` de Base.\n# ------------------------------------------------------------------------------------------\n\nimport Base: +\n\n# ------------------------------------------------------------------------------------------\n# Digamos que queremos concatenar elementos con `+`. Sin extender el método, no funciona\n# ------------------------------------------------------------------------------------------\n\n\"hello \" + \"world!\"\n\n@which \"hello \" + \"world!\"\n\n# ------------------------------------------------------------------------------------------\n# Entonces agregamos a `+` un método que toma dos cadenas y las concatena\n# ------------------------------------------------------------------------------------------\n\n+(x::String, y::String) = string(x, y)\n\n\"hello \" + \"world!\"\n\n# ------------------------------------------------------------------------------------------\n# ¡Funciona! Y si queremos más, podemos comprobarnos que Julia ha despachado sobre los tipos\n# de \"hello\" y \"world!\", sobre el método que acabamos de definir\n# ------------------------------------------------------------------------------------------\n\n@which \"hello \" + \"world!\"\n\n# ------------------------------------------------------------------------------------------\n# Vamos por un ejemplo más\n# ------------------------------------------------------------------------------------------\n\nfoo(x, y) = println(\"duck-typed foo!\")\nfoo(x::Int, y::Float64) = println(\"foo con entero y flotante!\")\nfoo(x::Float64, y::Float64) = println(\"foo con dos flotantes!\")\nfoo(x::Int, y::Int) = println(\"foo con dos enteros!\")\n\nfoo(1, 1)\n\nfoo(1., 1.)\n\nfoo(1, 1.0)\n\nfoo(true, false)\n\n# ------------------------------------------------------------------------------------------\n# Nota que el último ejemplo aplica por default el caso de 'duck-typed foo' porque no había\n# un método definido exclusivamente para dos booleanos.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# ### Ejercicios\n#\n# #### 9.1\n#\n# Agrega un método para `+` que aplique un cifrado de César a una cadena (cómo en el\n# notebook 6) tal que\n#\n# ```julia\n# \"hello\" + 4 == \"lipps\"\n# ```\n# ------------------------------------------------------------------------------------------\n\n\n\n# ------------------------------------------------------------------------------------------\n# #### 9.2\n#\n# Checa que has extendido propiamente `+` recorriendo la próxima cadena para atrás por 3\n# letras:\n#\n# \"Gr#qrw#phggoh#lq#wkh#diidluv#ri#gudjrqv#iru#|rx#duh#fuxqfk|#dqg#wdvwh#jrrg#zlwk#nhwfkxs1\"\n# ------------------------------------------------------------------------------------------\n\n\n", "meta": {"hexsha": "7a97093b35e4852fa8fbfbc8b5fd75ae4b28e7ed", "size": 4304, "ext": "jl", "lang": "Julia", "max_stars_repo_path": ".nbexports/introductory-tutorials/intro-to-julia-ES/ 9. Despacho multiple.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/ 9. Despacho multiple.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/ 9. Despacho multiple.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": 37.7543859649, "max_line_length": 92, "alphanum_fraction": 0.3278345725, "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.2509127924867847, "lm_q1q2_score": 0.1244762880880112}}
{"text": "### A Pluto.jl notebook ###\n# v0.16.4\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ d794dbb2-0254-4808-80ea-75f184586ad8\nbegin\n\tusing PlutoUI\n\tPlutoUI.TableOfContents()\nend\n\n# ╔═╡ 32785fd3-0adb-4b61-a8dc-c920904d66ea\nusing OrderedCollections\n\n# ╔═╡ 3a242ea0-a518-11eb-0c88-d541f2d52fb8\nmd\"\"\"\n# Dictionaries\n\"\"\"\n\n# ╔═╡ ea932952-cb4c-4876-9dc4-3a2b56cf4761\nmd\"\"\"\nA dictionary is an **unordered collection** of key-value pairs of elements.\n\n## Declaration\n\nThe best way to understand what it means is by looking at one:\n\"\"\"\n\n# ╔═╡ 61cb5c19-2c9b-4484-b95b-c54c2bc4066e\ndict = Dict(\"🍌\" => 4, \"🍓\" => 15)\n\n# ╔═╡ 94d9dbe3-4042-4bdf-9d14-7acc165514cc\nmd\"\"\"\nAs we can see a dictionary is declared using the `Dict` function, and then elements are declared using the `key => value` pair syntax. The keys and values can be of any type, and their type can differ between one key or value and another (although it is not recommanded for performance reasons). For example we can use symbols and strings for the keys, and integer and string for the values:\n\"\"\"\n\n# ╔═╡ 874a6524-8f3c-4bc0-bc6e-9e8fec402e56\nDict(:🍌 => 4, \"🍓\" => \"this is not the season\", 12 => 12.0)\n\n# ╔═╡ 45835257-6034-4d64-be18-68c966d96603\nmd\"\"\"\nAnd here's an example with integers:\n\"\"\"\n\n# ╔═╡ a0be3db2-a1a0-4405-b453-87b933d76ce2\nDict(1234 => 4, 999 => 15)\n\n# ╔═╡ 9f81f1e8-f3c2-4fa4-8469-2d605a418481\nmd\"\"\"\nBecause it is used to retreive a value, each key in a dictionary must be unique. You couldn't retreive a value if it shared the same index as one another.\n\nPlease note also that a dictionary is unordered, meaning we can't index into a dictionary by using the order we used to declare our `key=>value` pairs.\n\"\"\"\n\n# ╔═╡ de10d9d7-3669-4999-8309-f6c0452f5f10\nmd\"\"\"\nWe can also declare a dictionary in two steps using the zip function:\n\n- first we declare our keys and values separately:\n\"\"\"\n\n# ╔═╡ 349fbaf2-1d6e-41c8-a05e-49a1f2d12ac1\nmykeys = (:🍌, :🍓)\n\n# ╔═╡ 449eb41a-b5ac-422e-95c7-8baf36bb21f0\nmyvalues = (4, 15)\n\n# ╔═╡ ae9376e7-3fc0-4668-a495-4338e139385d\nmd\"\"\"\nAnd then we use the zip function to create a `key=>value` pair for each pair of element inside our dictionary:\n\"\"\"\n\n# ╔═╡ bb28ae8d-5bc2-4056-9c75-9983362c6716\nDict(zip(mykeys,myvalues))\n\n# ╔═╡ 602bc23f-1acc-44a5-8986-cadea9c7f461\nmd\"\"\"\n#### Empty dictionary\n\"\"\"\n\n# ╔═╡ 73dac266-f783-4406-91c7-27a08c4e4e60\nmd\"\"\"\nWe can declare an empty dictionary using `Dict()`, and even constrain the types of the keys and the values that will be added as follows:\n\"\"\"\n\n# ╔═╡ 14ac3d30-c0bc-4543-8e61-ccb1bfcd9287\nconstrained_dict = Dict{String, Float64}()\n\n# ╔═╡ e1856197-b467-465c-ba4c-032282c989eb\nconstrained_dict[\"a\"] = 2\n\n# ╔═╡ 83c526bb-5db2-4a30-bcfa-7476faaf9f55\nconstrained_dict[\"a\"]\n\n# ╔═╡ 7e1dbf59-df69-417a-8578-b34bb403848d\nconstrained_dict[\"b\"] = \"test\"\n\n# ╔═╡ 73055842-a630-4403-8233-f0a774258323\nmd\"\"\"\n## Indexing\n\"\"\"\n\n# ╔═╡ 70339c78-0e43-404b-a7f3-b5e837915ebb\nmd\"\"\"Indexing a dictionary is made using `[` along with the key of choice. For example we would type `dict[key]` to get the value in `dict` stored in `key`:\"\"\"\n\n# ╔═╡ 9ea3f3db-2421-4e43-a706-7b7f7c0b1959\ndict[\"🍓\"]\n\n# ╔═╡ 7a00c43e-d7a8-40c0-bcfa-594b3f4e7161\nmd\"\"\"\nRemember that dictionaries are not ordered, but we can still reproduce the behavior of an array just for fun using integers as keys:\n\"\"\"\n\n# ╔═╡ 26e9f223-690d-4063-8185-ef3ce0b5e622\narray_dict = Dict(1 => \"first value\", 2 => \"second value\")\n\n# ╔═╡ cca40559-57dd-4827-a334-cd437b6a475d\narray_dict[2]\n\n# ╔═╡ 18fc5ca7-febe-40a4-bfa8-ef5a8c0b547c\nmd\"\"\"\nIf we want to index a value that does not exist yet in the dictionary, it returns an error:\n\"\"\"\n\n# ╔═╡ ae2b5a5e-9a3a-49e4-8fff-cc5ef26ed173\narray_dict[3]\n\n# ╔═╡ 37c1ceae-e993-4b36-96df-c088d3ab006b\nmd\"\"\"\nWe can check if a key exists using `haskey`:\n\"\"\"\n\n# ╔═╡ a609fc58-3ade-41ac-8325-56a7a66e2a3b\nhaskey(array_dict,2)\n\n# ╔═╡ 6e36762d-e0d6-45b1-958d-f0602bdd11a5\nmd\"\"\"\nAnd if we're not sure if a key exist and want to return a default value if not, there's `get`:\n\"\"\"\n\n# ╔═╡ bee06854-8bbd-4c92-953d-46c18520707c\nget(array_dict,1,\"default value\") # The key exists, so it returns its value\n\n# ╔═╡ ddb11f15-b000-4276-9c06-30b9d1e9936c\nget(array_dict,3,\"default value\") # The key does not exist, it returns the default one\n\n# ╔═╡ 693fac53-b2b6-489b-a7aa-93ea5eab8165\nmd\"\"\"\nIf you want to get all values or all keys at once, use `keys` and `values` like for arrays:\n\"\"\"\n\n# ╔═╡ de829c74-37f4-4fe8-8e81-da3c729e2019\nkeys(dict)\n\n# ╔═╡ b08a7e04-6106-4ff6-baa3-b153eb627eba\nvalues(dict)\n\n# ╔═╡ 296be6bc-0ee2-4d2b-b8e5-8b730a974162\nmd\"\"\"\n!!! note\n\tAs we can see `keys` and `values` return a `KeySet` and a `ValueIterator` respectively. But we can use `collect` to get them as arrays.\n\"\"\"\n\n# ╔═╡ 9f0b1f62-f9f2-45b8-8fda-fe02a99fa602\ncollect(values(dict))\n\n# ╔═╡ f106e0b7-7b17-4564-8ba8-a9ba0c4c413a\nmd\"\"\"\n## Filter\n\"\"\"\n\n# ╔═╡ 6a22a2b0-8c8d-4f52-99ae-d37bc2f1ef87\nmd\"\"\"\nFiltering values is rather simple, just use the filer function 🙂. It works by providing a filtering function as the first argument:\n\"\"\"\n\n# ╔═╡ 4751e962-d173-4047-aeee-7c562d15ca8d\nfilter(x -> iseven(x.second), dict)\n\n# ╔═╡ fae3a4ab-222a-4b4e-a617-9f8199194dc7\nmd\"\"\"\n!!! note\n\t`x -> iseven(x.second)` is an anonymous function, we'll get into that in the future. What it does here is testing if the value of a `key=>value` pair is even or not, and returns `true` if so, and `false` if not. `filter` then filters out the values that are not even, *i.e.* the ones that return `false`.\n\"\"\"\n\n# ╔═╡ 6bbe9f7c-17b1-4566-89b4-6247fd937256\nmd\"\"\"\n## Mutate\n\"\"\"\n\n# ╔═╡ d0371dc1-5f08-4f1d-a79f-f4bd954eb974\nmd\"\"\"\nDictionaries are easy to work with. We can add new elements using `push!`, merge two dictionaries using `merge` and delete elements using either `pop!` or `delete!`.\n\nLet's see an example using the dict we previously declared. Here's a reminder of which elements it holds:\n\"\"\"\n\n# ╔═╡ 28ff01f9-681c-400b-b62b-e3524dcfe2c1\ndict\n\n# ╔═╡ b19e99d0-3729-4255-808b-4261fd68145a\nmd\"\"\"\n#### Add elements\n\"\"\"\n\n# ╔═╡ c895188a-8b24-45d7-a862-18110c8b7fd1\nmd\"\"\"\nNow let's add a new element:\n\"\"\"\n\n# ╔═╡ f7dbbd52-a2da-478f-89b0-e712f945103c\nbegin\n\tdict_tmp = copy(dict)\n\tpush!(dict_tmp, \"🍒\" => 30)\nend\n\n# ╔═╡ 15ac5ad1-8843-4be6-9337-5c41fe8589cf\nmd\"\"\"\n\n!!! note\n\n\tIf we were outside of Pluto, we would simply use `push!(dict, \"🍒\" => 30)`. Pluto is designed around reactivity, so it is generally bad practice to mutate a variable inside a Pluto notebook. We would normally prefer assigning the results to a new variable. I use a trick here to still be able to show you an example with a mutating function (i.e. one that change the value of its input argument directly). The trick is to put the code in a `begin ... end` statement to make it as a single statement, and apply `push!` on a copy of `dict` (here `dict_tmp`) so `dict` is never changed. If it is too complicated, no worries, just consider this big blob of code just as if it was only written `push!(dict, \"🍒\" => 30)`.\n\"\"\"\n\n# ╔═╡ 9c7974c3-6e50-44d5-b5ec-cb535280e610\nmd\"\"\"\n#### Merge dictionaries\n\"\"\"\n\n# ╔═╡ e04a56ef-7d7a-47da-9380-28e3fe9e4720\nmd\"\"\"\nWe can merge two dictionaries into a single one using `merge`:\n\"\"\"\n\n# ╔═╡ 8e132c33-2d5a-48d2-a6d7-c2d7fdc5b2b5\ndict2 = Dict(\"🍆\" => 2, \"🍅\" => 4)\n\n# ╔═╡ 85fac12d-02f4-4598-884f-82a93b29dae0\nmerge(dict,dict2)\n\n# ╔═╡ 8e27d819-d58a-42b9-bf63-e9ab6c01576e\nmd\"\"\"\n#### Delete elements\n\"\"\"\n\n# ╔═╡ 93732551-1730-41da-ab86-dbaa3732dfa0\nmd\"\"\"\nTo delete an element from a dictionary, you can either use `pop!`:\n\"\"\"\n\n# ╔═╡ fda3a3b9-7e06-422c-9b46-668c923c53e7\nbegin\n\tdict_tmp2 = copy(dict)\n\tpop!(dict_tmp2, \"🍌\")\nend\n\n# ╔═╡ e6e1515d-a893-44e9-a5e3-c6e191dfaa2d\nmd\"\"\"\nYou can see it returns 4 here. That is because `pop!` returns the value of the element it just removed, and it is very useful sometimes! We can check the newly created `dict_tmp2` and see if there still is the banana element:\n\"\"\"\n\n# ╔═╡ 1d68302e-0fbf-4e60-8bd4-97d90c5ee0b1\ndict_tmp2\n\n# ╔═╡ 2b0361ec-b65b-426c-80a5-b5bfa95a6730\nmd\"\"\"\nNope, it was removed as expected.\n\"\"\"\n\n# ╔═╡ bab7580c-228e-4bd1-91c5-e476f1c97ad5\nmd\"\"\"\nIf you prefer to get the remaining elements instead of the one removed, you can use `delete!`:\n\"\"\"\n\n# ╔═╡ f62a1379-8afe-48a6-9466-a9235199cfdb\nbegin\n\tdict_tmp3 = copy(dict)\n\tdelete!(dict_tmp3, \"🍌\")\nend\n\n# ╔═╡ cdd99268-f499-40ff-b9ad-f29bef3c05ed\ndict_tmp3\n\n# ╔═╡ a6a378c0-f3bc-4ce9-8e3d-29b3caf43ab5\nmd\"\"\"\n## Ordered dictionaries\n\"\"\"\n\n# ╔═╡ 77496c2f-4e8f-44b6-bddb-1763ac179398\nmd\"\"\"\nWe saw earlier that dictionaries are unordered. But if you think unordered collections are too chaotic and you want to put an end to this madness, you can use ordered dictionaries from the `OrderedCollections.jl` package instead.\n\nSo what is an ordered dictionary? The only difference with a standard dictionary is that elements are ordered, meaning we assign them a position in the dictionary, and they stick to it. And if you add an element, it is added as the last element, as things should be. Think of it like an array with names for each element. \n\"\"\"\n\n# ╔═╡ ee62f664-1e9d-4d0d-bd89-c46210d0bf5e\nbegin\n\torder_dict = OrderedDict(dict_tmp)\n\tpush!(order_dict, \"🌲\" => 1)\nend\n\n# ╔═╡ a75a0cee-1a9e-4186-a39b-6f7e1e3a9f89\nmd\"\"\"\n!!! note\n\tIf you have an error on the code above, it is certainly because you didn't activate the project before opening the pluto notebook, so the `OrderedCollections` package is not available to you. There's two solutions to this issue: \n\t\n\t1/ activate the environment before opening this notebook. To do so, enter the following command in Julia `] activate .`. Then instantiate the environment by entering `] instantiate`. This will work assuming you are working from the whole [julia_course](https://github.com/VEZY/julia_course) project.\n\t\n\t2/ Or add a new cell below with the following code: `import Pkg; Pkg.add(\"OrderedCollections\")`.\n\"\"\"\n\n# ╔═╡ b3a97c75-07a8-404a-ae42-01a3e865af16\nmd\"\"\"\n## Useful functions\n\"\"\"\n\n# ╔═╡ a43f99bc-9ead-40ab-8743-31923537b953\nmd\"\"\"\nUnion of two dictionaries:\n\"\"\"\n\n# ╔═╡ 603cd2c3-1437-437a-a931-caa893b5c05a\nunion(dict2, dict_tmp)\n\n# ╔═╡ ab10a88a-8542-479b-8452-9612d25ef26e\nmd\"\"\"\nIntersection of two dictionaries:\n\"\"\"\n\n# ╔═╡ 95aba192-6027-46d2-8cf8-6222ddbed0d7\nintersect(dict, dict_tmp)\n\n# ╔═╡ b0d12465-c1ba-4520-a0d4-321b86219845\nmd\"\"\"\nDifference between two dictionaries:\n\"\"\"\n\n# ╔═╡ 11c0414b-ef75-4211-ad69-9e402f6061c9\nsetdiff(dict2, dict_tmp)\n\n# ╔═╡ c3a5e91d-d7d0-4abe-b7e6-e0c08780657c\nmd\"\"\"\nThese functions are related to mathematical sets.\n\n![](https://upload.wikimedia.org/wikipedia/commons/8/86/A_union_B.svg)[^1]\n\nThe inclusion-exclusion principle is used to calculate the size of the union of sets: the size of the union is the size of the two sets, minus the size of their intersection.\n\n[^1]: See markdown link for source. \"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nOrderedCollections = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nPlutoUI = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\n\n[compat]\nOrderedCollections = \"~1.4.1\"\nPlutoUI = \"~0.7.18\"\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 = \"0ec322186e078db08ea3e7da5b8b2885c099b393\"\nuuid = \"6e696c72-6542-2067-7265-42206c756150\"\nversion = \"1.1.0\"\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[[Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\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 = \"5efcf53d798efede8fee5b2c8b09284be359bf24\"\nuuid = \"ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2\"\nversion = \"0.9.2\"\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[[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[[Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[OrderedCollections]]\ngit-tree-sha1 = \"85f8e6578bf1f9ee0d11e7bb1b1456435479d47c\"\nuuid = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nversion = \"1.4.1\"\n\n[[Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"ae4bbcadb2906ccc085cf52ac286dc1377dceccc\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.1.2\"\n\n[[Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[PlutoUI]]\ndeps = [\"AbstractPlutoDingetjes\", \"Base64\", \"Dates\", \"Hyperscript\", \"HypertextLiteral\", \"IOCapture\", \"InteractiveUtils\", \"JSON\", \"Logging\", \"Markdown\", \"Random\", \"Reexport\", \"UUIDs\"]\ngit-tree-sha1 = \"57312c7ecad39566319ccf5aa717a20788eb8c1f\"\nuuid = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nversion = \"0.7.18\"\n\n[[Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[Reexport]]\ngit-tree-sha1 = \"45e428421666073eab6f2da5c9d310d99bb12f9b\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.2.2\"\n\n[[SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─d794dbb2-0254-4808-80ea-75f184586ad8\n# ╟─3a242ea0-a518-11eb-0c88-d541f2d52fb8\n# ╟─ea932952-cb4c-4876-9dc4-3a2b56cf4761\n# ╠═61cb5c19-2c9b-4484-b95b-c54c2bc4066e\n# ╟─94d9dbe3-4042-4bdf-9d14-7acc165514cc\n# ╠═874a6524-8f3c-4bc0-bc6e-9e8fec402e56\n# ╟─45835257-6034-4d64-be18-68c966d96603\n# ╠═a0be3db2-a1a0-4405-b453-87b933d76ce2\n# ╟─9f81f1e8-f3c2-4fa4-8469-2d605a418481\n# ╟─de10d9d7-3669-4999-8309-f6c0452f5f10\n# ╠═349fbaf2-1d6e-41c8-a05e-49a1f2d12ac1\n# ╠═449eb41a-b5ac-422e-95c7-8baf36bb21f0\n# ╟─ae9376e7-3fc0-4668-a495-4338e139385d\n# ╠═bb28ae8d-5bc2-4056-9c75-9983362c6716\n# ╟─602bc23f-1acc-44a5-8986-cadea9c7f461\n# ╟─73dac266-f783-4406-91c7-27a08c4e4e60\n# ╠═14ac3d30-c0bc-4543-8e61-ccb1bfcd9287\n# ╠═e1856197-b467-465c-ba4c-032282c989eb\n# ╠═83c526bb-5db2-4a30-bcfa-7476faaf9f55\n# ╠═7e1dbf59-df69-417a-8578-b34bb403848d\n# ╟─73055842-a630-4403-8233-f0a774258323\n# ╟─70339c78-0e43-404b-a7f3-b5e837915ebb\n# ╠═9ea3f3db-2421-4e43-a706-7b7f7c0b1959\n# ╟─7a00c43e-d7a8-40c0-bcfa-594b3f4e7161\n# ╠═26e9f223-690d-4063-8185-ef3ce0b5e622\n# ╠═cca40559-57dd-4827-a334-cd437b6a475d\n# ╟─18fc5ca7-febe-40a4-bfa8-ef5a8c0b547c\n# ╠═ae2b5a5e-9a3a-49e4-8fff-cc5ef26ed173\n# ╟─37c1ceae-e993-4b36-96df-c088d3ab006b\n# ╠═a609fc58-3ade-41ac-8325-56a7a66e2a3b\n# ╟─6e36762d-e0d6-45b1-958d-f0602bdd11a5\n# ╠═bee06854-8bbd-4c92-953d-46c18520707c\n# ╠═ddb11f15-b000-4276-9c06-30b9d1e9936c\n# ╟─693fac53-b2b6-489b-a7aa-93ea5eab8165\n# ╠═de829c74-37f4-4fe8-8e81-da3c729e2019\n# ╠═b08a7e04-6106-4ff6-baa3-b153eb627eba\n# ╟─296be6bc-0ee2-4d2b-b8e5-8b730a974162\n# ╠═9f0b1f62-f9f2-45b8-8fda-fe02a99fa602\n# ╟─f106e0b7-7b17-4564-8ba8-a9ba0c4c413a\n# ╟─6a22a2b0-8c8d-4f52-99ae-d37bc2f1ef87\n# ╠═4751e962-d173-4047-aeee-7c562d15ca8d\n# ╟─fae3a4ab-222a-4b4e-a617-9f8199194dc7\n# ╟─6bbe9f7c-17b1-4566-89b4-6247fd937256\n# ╟─d0371dc1-5f08-4f1d-a79f-f4bd954eb974\n# ╠═28ff01f9-681c-400b-b62b-e3524dcfe2c1\n# ╟─b19e99d0-3729-4255-808b-4261fd68145a\n# ╟─c895188a-8b24-45d7-a862-18110c8b7fd1\n# ╠═f7dbbd52-a2da-478f-89b0-e712f945103c\n# ╟─15ac5ad1-8843-4be6-9337-5c41fe8589cf\n# ╟─9c7974c3-6e50-44d5-b5ec-cb535280e610\n# ╟─e04a56ef-7d7a-47da-9380-28e3fe9e4720\n# ╠═8e132c33-2d5a-48d2-a6d7-c2d7fdc5b2b5\n# ╠═85fac12d-02f4-4598-884f-82a93b29dae0\n# ╟─8e27d819-d58a-42b9-bf63-e9ab6c01576e\n# ╟─93732551-1730-41da-ab86-dbaa3732dfa0\n# ╠═fda3a3b9-7e06-422c-9b46-668c923c53e7\n# ╟─e6e1515d-a893-44e9-a5e3-c6e191dfaa2d\n# ╠═1d68302e-0fbf-4e60-8bd4-97d90c5ee0b1\n# ╟─2b0361ec-b65b-426c-80a5-b5bfa95a6730\n# ╟─bab7580c-228e-4bd1-91c5-e476f1c97ad5\n# ╠═f62a1379-8afe-48a6-9466-a9235199cfdb\n# ╠═cdd99268-f499-40ff-b9ad-f29bef3c05ed\n# ╟─a6a378c0-f3bc-4ce9-8e3d-29b3caf43ab5\n# ╟─77496c2f-4e8f-44b6-bddb-1763ac179398\n# ╠═32785fd3-0adb-4b61-a8dc-c920904d66ea\n# ╠═ee62f664-1e9d-4d0d-bd89-c46210d0bf5e\n# ╟─a75a0cee-1a9e-4186-a39b-6f7e1e3a9f89\n# ╟─b3a97c75-07a8-404a-ae42-01a3e865af16\n# ╟─a43f99bc-9ead-40ab-8743-31923537b953\n# ╠═603cd2c3-1437-437a-a931-caa893b5c05a\n# ╟─ab10a88a-8542-479b-8452-9612d25ef26e\n# ╠═95aba192-6027-46d2-8cf8-6222ddbed0d7\n# ╟─b0d12465-c1ba-4520-a0d4-321b86219845\n# ╠═11c0414b-ef75-4211-ad69-9e402f6061c9\n# ╟─c3a5e91d-d7d0-4abe-b7e6-e0c08780657c\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "14afe22a7bf09c7c50369b184d94b9b5ca6aefca", "size": 18644, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "4-dictionnaries.jl", "max_stars_repo_name": "VEZY/julia_course", "max_stars_repo_head_hexsha": "e85f9dbe122168c3b1063ae86fec542303f40d61", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-02-24T13:18:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T22:50:18.000Z", "max_issues_repo_path": "4-dictionnaries.jl", "max_issues_repo_name": "VEZY/julia_course", "max_issues_repo_head_hexsha": "e85f9dbe122168c3b1063ae86fec542303f40d61", "max_issues_repo_licenses": ["MIT"], "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-dictionnaries.jl", "max_forks_repo_name": "VEZY/julia_course", "max_forks_repo_head_hexsha": "e85f9dbe122168c3b1063ae86fec542303f40d61", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-02-24T21:05:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-02T16:50:19.000Z", "avg_line_length": 30.4143556281, "max_line_length": 714, "alphanum_fraction": 0.7307444754, "num_tokens": 8486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.24798742068237778, "lm_q1q2_score": 0.1210881397614479}}
{"text": "\n#\nprintln(\"Df) Test of the Dielectronic module with ASF from an internally generated initial-, intermediate and final-state multiplets.\")\n#\nsetDefaults(\"print summary: open\", \"zzz-Dielectronic.sum\")\nsetDefaults(\"method: continuum, Galerkin\") ## setDefaults(\"method: continuum, Galerkin\") setDefaults(\"method: continuum, asymptotic Coulomb\") \nsetDefaults(\"method: normalization, pure sine\") ## setDefaults(\"method: normalization, pure Coulomb\") setDefaults(\"method: normalization, pure sine\")\n\nif false\n # K-LL DR into initially He-like tungsten; comparison with Tu et al. (PP, 2016)\n asfSettings = AsfSettings(AsfSettings(), scField=Basics.HSField()) # not used\n drSettings = Dielectronic.Settings([E1], [JAC.UseCoulomb, JAC.UseBabushkin], true, PathwaySelection(), -230., 0., 0., CoulombInteraction())\n grid = Radial.Grid(Radial.Grid(false), rnt = 4.0e-6, h = 5.0e-2, hp = 0.6e-2, rbox = 10.0)\n setDefaults(\"unit: rate\", \"1/s\"); setDefaults(\"unit: strength\", \"cm^2 eV\") \n\n wa = Atomic.Computation(Atomic.Computation(), name=\"xx\", grid=grid, nuclearModel=Nuclear.Model(74.), \n initialConfigs = [Configuration(\"1s^2\")],\n intermediateConfigs = [Configuration(\"1s 2s^2\"), Configuration(\"1s 2s 2p\"), Configuration(\"1s 2p^2\")], \n finalConfigs = [Configuration(\"1s^2 2s\"), Configuration(\"1s^2 2p\")], \n process = Dierec(), processSettings = drSettings )\n\n wb = perform(wa)\n\nelseif false\n # K-LL DR into initially Be-like tungsten; comparison with Tu et al. (PP, 2016)\n asfSettings = AsfSettings(AsfSettings(), scField=Basics.HSField()) # not used\n drSettings = Dielectronic.Settings([E1], [JAC.UseCoulomb, JAC.UseBabushkin], true, PathwaySelection(), -230., 0., 0., CoulombInteraction())\n grid = Radial.Grid(Radial.Grid(false), rnt = 4.0e-6, h = 5.0e-2, hp = 0.6e-2, rbox = 10.0)\n setDefaults(\"unit: rate\", \"1/s\"); setDefaults(\"unit: strength\", \"cm^2 eV\") \n\n wa = Atomic.Computation(Atomic.Computation(), name=\"xx\", grid=grid, nuclearModel=Nuclear.Model(74.), \n initialConfigs = [Configuration(\"1s^2 2s^2\")],\n intermediateConfigs = [Configuration(\"1s 2s^2 2p^2\")], \n finalConfigs = [Configuration(\"1s^2 2s^2 2p\")], \n process = Dierec(), processSettings = drSettings )\n\n wb = perform(wa)\n\nelseif false\n # K-LL DR into initially O-like tungsten; comparison with Tu et al. (PP, 2016)\n asfSettings = AsfSettings(AsfSettings(), scField=Basics.HSField()) # not used\n drSettings = Dielectronic.Settings([E1], [JAC.UseCoulomb, JAC.UseBabushkin], true, PathwaySelection(true, indexTriples=[(1,1,0)]), \n -300., 0., 0., CoulombInteraction())\n grid = Radial.Grid(Radial.Grid(false), rnt = 4.0e-6, h = 5.0e-2, hp = 0.6e-2, rbox = 10.0)\n setDefaults(\"unit: rate\", \"1/s\"); setDefaults(\"unit: strength\", \"cm^2 eV\") \n\n wa = Atomic.Computation(Atomic.Computation(), name=\"xx\", grid=grid, nuclearModel=Nuclear.Model(74.), \n initialConfigs = [Configuration(\"1s^2 2s^2 2p^4\")],\n intermediateConfigs = [Configuration(\"1s 2s^2 2p^6\")], \n finalConfigs = [Configuration(\"1s^2 2s^2 2p^5\")], \n process = Dierec(), processSettings = drSettings )\n\n wb = perform(wa)\n\nelseif true\n # K-LL DR into initially He-like carbon; comparison with Xu et al. (PRA, 2016)\n asfSettings = AsfSettings(AsfSettings(), scField=Basics.HSField()) # not used\n drSettings = Dielectronic.Settings([E1, M1], [JAC.UseCoulomb, JAC.UseBabushkin], true, \n PathwaySelection(true, indexTriples=[(1,1,0), (1,5,0), (1,6,0), (1,10,0), (1,11,0)]), \n 0., 0., 0., CoulombInteraction())\n grid = Radial.Grid(Radial.Grid(false), rnt = 4.0e-6, h = 5.0e-2, hp = 0.6e-2, rbox = 12.0)\n setDefaults(\"unit: rate\", \"1/s\"); setDefaults(\"unit: strength\", \"cm^2 eV\") \n\n wa = Atomic.Computation(Atomic.Computation(), name=\"xx\", grid=grid, nuclearModel=Nuclear.Model(6.), \n initialConfigs = [Configuration(\"1s^2\")],\n intermediateConfigs = [Configuration(\"1s 2s^2\"), Configuration(\"1s 2s 2p\"), Configuration(\"1s 2p^2\"), Configuration(\"1s 2s 3s\"),\n Configuration(\"1s 2s 3p\"), Configuration(\"1s 2s 3d\"), Configuration(\"1s 2p 3s\"), Configuration(\"1s 2p 3p\"),\n Configuration(\"1s 2p 3d\")], \n finalConfigs = [Configuration(\"1s^2 2s\"), Configuration(\"1s^2 2p\"), Configuration(\"1s^2 3s\"), Configuration(\"1s^2 3p\"),\n Configuration(\"1s^2 3d\"), Configuration(\"1s 2s 2p\"), Configuration(\"1s 2p^2\")], \n initialAsfSettings = asfSettings, finalAsfSettings=asfSettings,\n process = Dierec(), processSettings = drSettings)\n\n wb = perform(wa)\n\nelseif false\n # DR if initially Li-like Beryllium; comparison with Mohamed et al. (PRA, 2002) ... however difficult and the identification of resonances and\n # rates does not work at present\n asfSettings = AsfSettings(AsfSettings(), scField=Basics.HSField()) # not used\n drSettings = Dielectronic.Settings([E1, M1], [JAC.UseCoulomb, JAC.UseBabushkin], true, PathwaySelection(), 0., 0., 0., CoulombInteraction())\n grid = Radial.Grid(Radial.Grid(false), rnt = 4.0e-6, h = 5.0e-2, hp = 0.8e-2, rbox = 10.0)\n setDefaults(\"unit: rate\", \"1/s\") \n\n wa = Atomic.Computation(Atomic.Computation(), name=\"xx\", grid=grid, nuclearModel=Nuclear.Model(4.), \n initialConfigs=[Configuration(\"1s^2 2s\")],\n intermediateConfigs=[Configuration(\"1s^2 2s^2\"), Configuration(\"1s^2 2s 2p\"), Configuration(\"1s^2 2p^2\"),\n Configuration(\"1s^2 2p 3s\"), Configuration(\"1s^2 2p 3p\"), Configuration(\"1s^2 2p 3d\") ], \n finalConfigs =[Configuration(\"1s^2 2s^2\"), Configuration(\"1s^2 2s 2p\"), Configuration(\"1s^2 2p^2\"),\n Configuration(\"1s^2 2s 3s\"), Configuration(\"1s^2 2s 3p\"), Configuration(\"1s^2 2s 3d\")], \n process = Dierec(), processSettings = drSettings )\n\n wb = perform(wa)\n\nelseif false\n # DR strength for sodium-like silicon: Comparison with Schmidt et al. (PRA, 2007) ... need to be adapted\n drSettings = Dielectronic.Settings([E1, M1], [JAC.UseCoulomb, JAC.UseBabushkin], true, \n PathwaySelection(false, indexTriples=[(1,5,0), (1,6,0)]), 0., 0., 0., CoulombInteraction())\n\ngrid = Radial.Grid(Radial.Grid(true), rnt = 2.0e-5,h = 5.0e-2, hp = 5.0e-2, NoPoints = 1500)\nwa = Atomic.Computation(Atomic.Computation(), name=\"xx\", grid=grid, nuclearModel=Nuclear.Model(14.0), \n initialConfigs=[Configuration(\"[Ne] 3s\")],\n intermediateConfigs=[Configuration(\"[Ne] 3s^2\"), Configuration(\"[Ne] 3s 3p\"), Configuration(\"[Ne] 3s 3d\"),\n Configuration(\"[Ne] 3p 4d\"), Configuration(\"[Ne] 3p 4f\") ], \n finalConfigs =[Configuration(\"[Ne] 3s^2\"),\n Configuration(\"[Ne] 3s 3p\"), Configuration(\"[Ne] 3s 3d\"), Configuration(\"[Ne] 3s 4d\"), Configuration(\"[Ne] 3s 4f\") ],\n process = Dierec(), \n processSettings=Dielectronic.Settings([E1, M1, M2, E2], [JAC.UseCoulomb, JAC.UseBabushkin], true, \n false, Tuple{Int64,Int64,Int64}[(1,10,1), (1,10,7)], 0., 0., 0., CoulombInteraction()) )\n\n wb = perform(wa)\n\nelseif false\n # Need to be adapted !!!\n refConfigs = [Configuration(\"[Ne] 3s\")]\n fromShells = [Shell(\"3s\")]\n toShells = [Shell(\"3s\"), Shell(\"3p\"), Shell(\"3d\"), Shell(\"4s\"), Shell(\"4p\"), Shell(\"4d\"), Shell(\"4f\"), Shell(\"5s\")]\n intermediateConfigs = Basics.generateConfigurations(refConfigs, fromShells, toShells)\n grid=JAC.Radial.Grid(true)\n #== grid = Radial.Grid(Radial.Grid(true), rnt = 2.0e-5,h = 5.0e-2, hp = 5.0e-2, NoPoints = 2000)\n wa = Atomic.Computation(Atomic.Computation(), name=\"xx\", grid=grid, nuclearModel=Nuclear.Model(74.0, \"Fermi\"), \n configs=[Configuration(\"1s^2 2s^2\"), Configuration(\"1s^2 2s 2p\"), Configuration(\"1s^2 2p^2\"), Configuration(\"1s^2 2s 3s\"), \n Configuration(\"1s^2 2s 3p\"), Configuration(\"1s^2 2s 3d\"), Configuration(\"1s^2 2p 3s\"), Configuration(\"1s^2 2p 3p\"), \n Configuration(\"1s^2 2p 3d\")],\n ## configs=[Configuration(\"1s^2 2s\"), Configuration(\"1s^2 2p\"), \n ## Configuration(\"1s^2 7s\"), Configuration(\"1s^2 7p\"), Configuration(\"1s^2 7d\"), Configuration(\"1s^2 7f\")], \n asfSettings=AsfSettings(AsfSettings(), scField=Basics.DFSField()) ) ==#\n\n grid = Radial.Grid(Radial.Grid(true), rnt = 2.0e-5,h = 5.0e-2, hp = 5.0e-2, NoPoints = 1500)\n wa = Atomic.Computation(Atomic.Computation(), name=\"xx\", grid=grid, nuclearModel=Nuclear.Model(74.0), \n initialConfigs=[Configuration(\"1s^2 2s\"), Configuration(\"1s^2 2p\"), \n Configuration(\"1s^2 7s\"), Configuration(\"1s^2 7p\"), Configuration(\"1s^2 7d\"), Configuration(\"1s^2 7f\")],\n intermediateConfigs=[Configuration(\"1s^2 2s^2\"), Configuration(\"1s^2 2s 2p\"), Configuration(\"1s^2 2p 7s\"), Configuration(\"1s^2 2p 7p\"), \n Configuration(\"1s^2 2p 7d\"), Configuration(\"1s^2 2p 7f\")], \n finalConfigs =[Configuration(\"1s^2 2s^2\"), Configuration(\"1s^2 2s 2p\"), Configuration(\"1s^2 2s 7s\"), Configuration(\"1s^2 2s 7p\"), \n Configuration(\"1s^2 2s 7d\"), Configuration(\"1s^2 2s 7f\")],\n process = Dierec(), \n processSettings=Dielectronic.Settings([E1], [JAC.UseCoulomb, JAC.UseBabushkin], true, \n false, Tuple{Int64,Int64,Int64}[(1,10,1), (1,10,7)], 0., 0., 0., CoulombInteraction()) )\n\n wb = perform(wa)\n\nend\nsetDefaults(\"print summary: close\", \"\")\n\n\n", "meta": {"hexsha": "4db500d969ace117d9b00dced5c4a31199fd5537", "size": 10813, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/example-Df.jl", "max_stars_repo_name": "mfherbst/JAC.jl", "max_stars_repo_head_hexsha": "43563c049a995817ada86ce82908714d4e1a034b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 115, "max_stars_repo_stars_event_min_datetime": "2019-03-11T11:24:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T22:33:28.000Z", "max_issues_repo_path": "examples/example-Df.jl", "max_issues_repo_name": "mfherbst/JAC.jl", "max_issues_repo_head_hexsha": "43563c049a995817ada86ce82908714d4e1a034b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2019-04-02T22:04:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-06T06:21:57.000Z", "max_forks_repo_path": "examples/example-Df.jl", "max_forks_repo_name": "mfherbst/JAC.jl", "max_forks_repo_head_hexsha": "43563c049a995817ada86ce82908714d4e1a034b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2019-03-20T10:28:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T12:51:19.000Z", "avg_line_length": 74.0616438356, "max_line_length": 165, "alphanum_fraction": 0.5582169611, "num_tokens": 3236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.2309197576365038, "lm_q1q2_score": 0.11816547433686048}}
{"text": "# ------------------------------------------------------------------------------------------\n# ### Notebook 1\n# #### 1.1\n# Buscar `convert` y `parse` en la documentación.\n# ------------------------------------------------------------------------------------------\n\n?convert;\n# ?parse\n\n# ------------------------------------------------------------------------------------------\n# #### 1.2\n# Asignar `365` a una variable llamada `days`. Convierte `days` a flotante.\n# ------------------------------------------------------------------------------------------\n\ndays = 365\nconvert(Float64, days)\n\n# ------------------------------------------------------------------------------------------\n# #### 1.3\n# Ver que sucede ejectuando\n#\n# ```julia\n# convert(Int64, '1')\n# ```\n# and\n#\n# ```julia\n# parse(Int64, '1')\n# ```\n# ------------------------------------------------------------------------------------------\n\n# Esto regresa el código ascii (un entero) asociado con el caracter '1'\nconvert(Int64, '1')\n\n# Esto regresa un entero encapsulado entre comillas\nparse(Int64, '1')\n\n# ------------------------------------------------------------------------------------------\n# ### Notebook 2\n# #### 2.1\n# Crea una cadena que dice \"hola\" 1000 veces\n# ------------------------------------------------------------------------------------------\n\n\"hola\"^1000\n\n# ------------------------------------------------------------------------------------------\n# #### 2.2\n# Agrega dos números dentro de una cadena\n# ------------------------------------------------------------------------------------------\n\nm, n = 1, 1\n\"$m + $n = $(m + n)\"\n\n# ------------------------------------------------------------------------------------------\n# ### Notebook 3\n#\n# #### 3.1\n# Crea un arreglo, `arreglo`, que es un arreglo en 1D de 2 elementos, cada uno conteniendo\n# el número 0.\n# Agrega a `arreglo` para agregar un segundo número, `1`, a cada arreglo.\n# ------------------------------------------------------------------------------------------\n\na_ray = [[0], [0]]\npush!(a_ray[1], 1)\npush!(a_ray[2], 1)\na_ray\n\n# ------------------------------------------------------------------------------------------\n# ### 3.2\n# Trata de agregar \"Emergencia\" a `miagenda` con el valor `911`. Trata de agregar `911` como\n# un entero y no como cadena. ¿Porqué no funciona?\n# ------------------------------------------------------------------------------------------\n\nmiagenda = Dict(\"Jenny\" => \"867-5309\", \"Ghostbusters\" => \"555-2368\")\n\nmiagenda[\"Emergency\"] = 911\n#= \n\nJulia infiere que \"miagenda\" toma ambos llaves\ny valores del tipo \"String\". Podemos ver que miagenda\nes un Dict{String,String} con 2 entradas. Esto significa que\nJulia no va a aceptar enteros como valores en miagenda.\n\n=#\n\n# ------------------------------------------------------------------------------------------\n# #### 3.3\n# Crea un nuevo diccionario que se llame `agenda_flexible` que tenga el número de Jenny\n# guardado como cadena y el de los Cazafantasmas como entero.\n# ------------------------------------------------------------------------------------------\n\nagenda_flexible = Dict(\"Jenny\" => \"867-5309\", \"Ghostbusters\" => 5552368)\n\n# ------------------------------------------------------------------------------------------\n# #### 3.4\n# Add the key \"Emergency\" with the value `911` (an integer) to `flexible_phonebook`.\n# ------------------------------------------------------------------------------------------\n\nflexible_phonebook[\"Emergency\"] = 911\n\n# ------------------------------------------------------------------------------------------\n# ##### 3.5\n# 3.5 ¿Porqué podemos agregar un entero como valor a `agenda_flexible` pero no a\n# `miagenda`? ¿Cómo pudimos haber inicializado `miagenda` para que aceptara enteros como\n# valores?\n# ------------------------------------------------------------------------------------------\n\n#= \n\nJulia infiere que miagenda_flexible toma valores del tipo\nAny. A diferencia de miagenda, miagenda_flexible es un\nDict{String,Any} con 2 entradas.\n\nPara evitar esto, podemos inicializar miagenda a un\ndiccionario vacío y agregamos entradas después. O podemos\ndecirle a Julia explícitamente que queremos un diccionario\nque acepte objectos del tipo Any como valores.\n\n¡Ve los ejemplos!\n\n=#\n\nmiagenda = Dict()\n\nmiagenda = Dict{String, Any}(\"Jenny\" => \"867-5309\", \"Ghostbusters\" => \"555-2368\")\n\n# ------------------------------------------------------------------------------------------\n# ### Notebook 4\n#\n# #### 4.1\n#\n# 4.1 Crea un diccionario `squares`, que tiene llaves de valores de 1 a 100. El valor\n# asociado a cada llave es el cuadrado de la llave. Guarda los valores asociados a las\n# llaves pares como enteros y las impares como cadenas. Por ejemplo,\n#\n# ```julia\n# squares[10] == 100\n# squares[11] == \"121\"\n# ```\n#\n# (¡No necesitas condicionales para esto!)\n# ------------------------------------------------------------------------------------------\n\nsquares = Dict()\niterable = range(1, 2, 50)\n# Otra opción \n# iterable = 1:2:99\nfor key in iterable\n squares[key] = \"$(key^2)\"\n squares[key + 1] = (key + 1)^2\nend\n\n@show squares[10]\n@show squares[11]\n\n# ------------------------------------------------------------------------------------------\n# #### 4.2\n#\n# 4.2 Usa `fill` para crea una matriz de `10x10` de solo `0`'s. Pobla las primeras 10\n# entradas con el índice de esa entrada. ¿Julia usa el orden de primero columna o primero\n# renglón? (O sea, ¿el \"segundo\" elemento es el de la primera columna en el primer renglón,\n# ó es el de el primer renglón en la segunda columna?)\n# ------------------------------------------------------------------------------------------\n\nA = fill(0, (10, 10))\nfor i in 1:10\n A[i] = i\nend\nA\n# ¡Julia usa order columnar! Los primeros 10 elementos van a poblar la primera columna.\n\n# ------------------------------------------------------------------------------------------\n# ### Notebook 5\n#\n# #### 5.1\n#\n# 5.1 Reescribe FizzBuzz sin usar `elseif`.\n# ------------------------------------------------------------------------------------------\n\nN = 16\nif (N % 3 == 0) & (N % 5 == 0)\n println(\"FizzBuzz\")\nelse\n if (N % 3 == 0)\n println(\"Fizz\")\n else\n if (N % 5 == 0)\n println(\"Buzz\")\n else\n println(N)\n end\n end\nend\n\n# ------------------------------------------------------------------------------------------\n# #### 5.2\n#\n# Reescribe FizzBuzz usando el operador ternario.\n# ------------------------------------------------------------------------------------------\n\n((N % 3 == 0) & (N % 5 == 0)) ? println(\"FizzBuzz\") : ((N % 3 == 0) ? println(\"Fizz\") : ((N % 5 == 0) ? println(\"Buzz\") : println(N)))\n\n# ------------------------------------------------------------------------------------------\n# ### Notebook 6\n#\n# #### 6.1\n#\n# 6.1 En vez de broadcastear `f` sobre `v`, pudimos haber hecho `v .^ 2`.\n#\n# Sin declarar una nueva funcion, agrega 1 a cada elemento de una matriz de `3x3` llena de\n# `0`'s.\n# ------------------------------------------------------------------------------------------\n\nfill(0, (3, 3)) .+ 1\n\n# ------------------------------------------------------------------------------------------\n# #### 6.2\n#\n# 6.2 En vez de broadcastear `f` sobre el vector `v` con la sintaxis de punto, aplica `f` a\n# todos los elementos de`v` usando `map` como función.\n# ------------------------------------------------------------------------------------------\n\nf(x) = x^2\nv = [1, 2, 3]\nmap(f, v)\n\n# ------------------------------------------------------------------------------------------\n# #### 6.3\n#\n# Una cifra de César recorre cada letra un número determinado de plazas más adelante en el\n# abecedario. Un corrimiento, o shift, de 1 manda \"A\" a \"B\". Escribe una función llamada\n# `cesar` que toma una cadena como input y un corrimiento y regresa una cadena desencriptada\n# tal que obtengas\n#\n# ```julia\n# cesar(\"abc\", 1)\n# \"bcd\"\n#\n# cesar(\"hello\", 4)\n# \"lipps\"\n# ```\n# ------------------------------------------------------------------------------------------\n\ncaesar(input_string, shift) = map(x -> x + shift, input_string)\n\n# ------------------------------------------------------------------------------------------\n# ### Notebook 7\n#\n# #### 7.1\n#\n# 7.1 Usa el paquete de (código fuente en https://github.com/JuliaMath/Primes.jl) para\n# encontrar el número primer más grande menor a 1,000,000\n# ------------------------------------------------------------------------------------------\n\n#Pkg.add(\"Primes\")\nusing Primes\nmaximum(primes(1000000))\n\n# ------------------------------------------------------------------------------------------\n# ### Notebook 8\n#\n# #### 8.1\n#\n# 8.1 Grafica y vs x para `y = x^2` usando el backend de PyPlot.\n# ------------------------------------------------------------------------------------------\n\nusing Plots\npyplot()\nx = 1:10\ny = x .^ 2\nplot(x, y)\n\n# ------------------------------------------------------------------------------------------\n# ### Notebook 9\n#\n# #### 9.1\n#\n# Agrega un método para `+` que aplique un cifrado de César a una cadena (cómo en el\n# notebook 6) tal que\n#\n# ```julia\n# \"hello\" + 4 == \"lipps\"\n# ```\n# ------------------------------------------------------------------------------------------\n\nimport Base: +\n+(x::String, y::Int) = map(x -> x + y, x)\n\n# ------------------------------------------------------------------------------------------\n# #### 9.2\n#\n# Checa que has extendido propiamente `+` recorriendo la próxima cadena para atrás por 3\n# letras:\n#\n# \"Gr#qrw#phggoh#lq#wkh#diidluv#ri#gudjrqv#iru#|rx#duh#fuxqfk|#dqg#wdvwh#jrrg#zlwk#nhwfkxs1\"\n# ------------------------------------------------------------------------------------------\n\n\"Gr#qrw#phggoh#lq#wkh#diidluv#ri#gudjrqv#iru#|rx#duh#fuxqfk|#dqg#wdvwh#jrrg#zlwk#nhwfkxs1\" + -3\n\n# ------------------------------------------------------------------------------------------\n# ### Notebook 10\n#\n# #### 10.1\n#\n# 10.1 Usa `circshift` para obtener una matriz con las columnas de A cíclicamente recorridas\n# a la derecha por 3 columnas.\n#\n# Empezando con\n#\n# ```\n# A = [\n# 1 2 3 4 5 6 7 8 9 10\n# 1 2 3 4 5 6 7 8 9 10\n# 1 2 3 4 5 6 7 8 9 10\n# 1 2 3 4 5 6 7 8 9 10\n# 1 2 3 4 5 6 7 8 9 10\n# 1 2 3 4 5 6 7 8 9 10\n# 1 2 3 4 5 6 7 8 9 10\n# 1 2 3 4 5 6 7 8 9 10\n# 1 2 3 4 5 6 7 8 9 10\n# 1 2 3 4 5 6 7 8 9 10\n# ]\n# ```\n#\n# Quieres obtener\n#\n# ```\n# A = [\n# 7 8 9 10 1 2 3 4 5 6\n# 7 8 9 10 1 2 3 4 5 6\n# 7 8 9 10 1 2 3 4 5 6\n# 7 8 9 10 1 2 3 4 5 6\n# 7 8 9 10 1 2 3 4 5 6\n# 7 8 9 10 1 2 3 4 5 6\n# 7 8 9 10 1 2 3 4 5 6\n# 7 8 9 10 1 2 3 4 5 6\n# 7 8 9 10 1 2 3 4 5 6\n# 7 8 9 10 1 2 3 4 5 6\n# ]\n# ```\n# ------------------------------------------------------------------------------------------\n\ncircshift(A, (0, 4))\n\n# ------------------------------------------------------------------------------------------\n# #### 10.2\n#\n# 10.2 Toma el producto de un vector `v` con sí mismo.\n# ------------------------------------------------------------------------------------------\n\nv = [1, 2, 3]\nv * v'\n\n# ------------------------------------------------------------------------------------------\n# #### 10.3\n# 10.3 Toma el producto de un vector `v` con sí mismo.\n# ------------------------------------------------------------------------------------------\n\nv' * v\n\n# ------------------------------------------------------------------------------------------\n# ### Notebook 11\n#\n# #### 11.1\n#\n# ¿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\nA =\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\neigdec = eigfact(A)\neigdec[:values]\n\n# ------------------------------------------------------------------------------------------\n# #### 11.2\n#\n# Crea una matriz diagonal de los eigenvalores de A\n# ------------------------------------------------------------------------------------------\n\nDiagonal(eigdec[:values])\n\n# ------------------------------------------------------------------------------------------\n# #### 11.3\n#\n# Realiza un factorización de Hessenberg sobre la matriz A. Verifica que `A = QHQ'`.\n# ------------------------------------------------------------------------------------------\n\nF = hessfact(A)\n\nisapprox(A, F[:Q] * F[:H] * F[:Q]')\n\n\n", "meta": {"hexsha": "19a3e03a4978081f26ff2b071eadf3de41f61c85", "size": 12684, "ext": "jl", "lang": "Julia", "max_stars_repo_path": ".nbexports/introductory-tutorials/intro-to-julia-ES/Soluciones a ejercicios.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/Soluciones a ejercicios.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/Soluciones a ejercicios.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": 30.8613138686, "max_line_length": 134, "alphanum_fraction": 0.3657363608, "num_tokens": 3426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073333856566001, "lm_q2_score": 0.2782567877172032, "lm_q1q2_score": 0.11334327942277823}}
{"text": "## Exercise 2-1\n## To check your understanding, type the following statements in the Julia REPL and see what they do:\n## in repl\n# 5 # >> 5\n# x = 5 # >> 5\n# x + 1 # >> 6\n\n# Now put the same statements in a script and run it. What is the output? Modify the script by transforming each expression into a print statement and then run it again.\nprintln(\"Ans: \")\n5\nx = 5\nx + 1\n# no output, lets try using print.\n\nprintln(5)\n# println(x = 5) # error, LoadError: MethodError\nx = 5\nprintln(x)\nprintln(x + 1)\n\nprintln(\"End.\")\n", "meta": {"hexsha": "7df4dae82296fff019728ec6eae3eb9420b221ab", "size": 521, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chapter2/ex1.jl", "max_stars_repo_name": "yashppawar/ThinkJuliaExercises.jl", "max_stars_repo_head_hexsha": "72145b969dc51ebcac413a10004175ebc63cd5c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-13T14:11:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T14:11:30.000Z", "max_issues_repo_path": "Chapter2/ex1.jl", "max_issues_repo_name": "yashppawar/ThinkJuliaExercises.jl", "max_issues_repo_head_hexsha": "72145b969dc51ebcac413a10004175ebc63cd5c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter2/ex1.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": 23.6818181818, "max_line_length": 169, "alphanum_fraction": 0.669865643, "num_tokens": 162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3276683008207139, "lm_q2_score": 0.33458945452352534, "lm_q1q2_score": 0.10963435803625309}}
{"text": "# # Data Structures\n#\n#md # [![](https://mybinder.org/badge_logo.svg)](@__BINDER_ROOT_URL__notebooks/02_DataStructures.ipynb)\n#md # [![](https://img.shields.io/badge/show-nbviewer-579ACA.svg)](@__NBVIEWER_ROOT_URL__notebooks/02_DataStructures.ipynb)\n#\n# ## Arrays\n#\n# Julia has a nice and flexible array interface. Arrays can have an arbitrary\n# number of dimensions. Let's define a one-dimetional array (i.e. a vector):\n\nvector = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]\n\n# The first index of an array in Julia is `1`:\n\nvector[1]\n\n# You can use `end` to access the last element of an array:\n\nvector[end]\n\n# Use ranges (`start:end`) to get a slice of the array:\n\nvector[2:4]\n\n# Ranges in Julia are iterable objects:\n\nindexes = 2:4\n\n#-\n\nfor i in indexes\n\t@show i\nend\n\n# Julia arrays, like the strings and ranges, are also iterables:\n\nfor element in vector\n\tprintln(element)\nend\n\n# #### Exercise 1\n#\n# Write a function to return the distance between two three dimensional points,\n# i.e. two vector of three elements. You should use a `for` loop over a range\n# and index the vectors.\n\n## function distance(a, b...\n\n#-\n\nusing Test\nA = [1.25, 2.0, 3.6]\nB = [-3.5, 4.7, 5.0]\n@test distance(A, B) ≈ hypot((A - B)...)\n\n# `...` \"splats\" the values contained in an iterable collection into a\n# function call as individual arguments, e.g:\n\nvector = [1, 2, 3]\nhypot(vector...) # hypot(1, 2, 3)\n\n# You can use `push!` to add one element to the end of an array\n\nvector = [1,2,3]\n\n#-\npush!(vector, 4)\n\n# There are other useful\n# [dequeues functions](https://docs.julialang.org/en/v1/base/collections/#Dequeues-1)\n# defined in Julia, e.g. `pop!`, `append!`.\n#\n# In Julia, by convention, all the functions that modify their arguments\n# should end with a bang or exclamation mark, `!`, see the\n# [style guide](https://docs.julialang.org/en/v1/manual/style-guide/index.html#Append-!-to-names-of-functions-that-modify-their-arguments-1).\n\n# ### Vectorized operations\n#\n# You can use a dot, `.`, to indicate that a function, e.g. `log.(x)`, or\n# operator, e.g. `x .^ y`, should be applied element by element, see\n# [dot syntax](https://docs.julialang.org/en/v1/manual/functions/#man-vectorized-1):\n\na = [1, -2, -3]\nb = [-2, -4, 0]\na .* b\n\n# This notation allows vectorizing any function, even element-wise functions\n# defined by the user:\n\nf(x) = 3.45x + 4.76\n\nf.(sin.(a))\n\n# Multiple vectorized operations get\n# [fused in a single loop](https://julialang.org/blog/2017/01/moredots)\n# without temporal arrays.\n\n# ### Comprehensions\n#\n# You can use [comprehensions](https://docs.julialang.org/en/v1/manual/arrays/#Comprehensions-1)\n# to create arrays and perform some operation\n\n[ 2x for x in 1:10 ]\n\n#-\n\nresult = [ 2x for x in 1:10 if x % 2 == 0 ]\n\n# #### Exercise 3\n#\n# Write the equivalent of the previous expression using a `for` loop and `push!`.\n\n## result = []\n## for ...\n\n# ### Matrices\n#\n# Matrices, bidimentional arrays, can be defined with the following notation:\n\nmatrix = [ 1.0 4.0 7.0\n 2.0 5.0 8.0\n\t\t 3.0 6.0 9.0 ]\n\n# You can use linear indexing (Julia arrays are stored in column major order)\n# to access an element\n\nmatrix[2]\n\n# Or using one index by dimension, i.e. `matrix[row_index, col_index]` :\n\nmatrix[2, 1]\n\n# You can also use ranges and `end`. The colon, `:`, means that all the indices\n# from that dimension should be used:\n\nmatrix[2:end, :]\n\n# #### Comprehensions\n#\n# You can also use comprehensions to create matrices. In fact, you can create\n# array of any desired dimension:\n\n[ x + y for x in 1:5, y in 1:10 ]\n\n# ## Dictionaries and pairs\n#\n# Dictionaries (hash tables) stores key => values pairs:\n\ndictionary = Dict('A' => 'T', 'C' => 'G', 'T' => 'A', 'G' => 'C')\n\n# You can get a value by indexing with the key:\n\ndictionary['A'] # get(dictionary, 'A')\n\n# If the key is not present in the dictionary, an error is raised:\n\ndictionary['N'] # get(dictionary, 'N')\n\n# The function `get` allows to specify a default value that is returned if\n# the key is absent in the dictionary:\n\nget(dictionary, 'N', '-')\n\n# A nice thing about hash tables (dictionary keys, sets) is that test\n# membership is $O(1)$ while it is $O(N)$ in lists/vectors/arrays:\n\n'N' in keys(dictionary)\n\n# A dictionary gives pairs when it is iterated:\n\nfor pair in dictionary\n\tprintln(\"pair: \", pair) # each pair is key => value\n\tprintln(\"key: \", pair.first) # pair.first == pair[1]\n\tprintln(\"value: \", pair.second) # pair.second == pair[2]\nend\n\n# ## Tuples\n#\n# Tuples are immutable collections, while arrays are mutable:\n\npoint = [1.0, 2.0, 3.0] # vector\npoint[1] = 10.0\npoint\n\n#-\n\npoint = (1.0, 2.0, 3.0) # tuple\n\n#-\n\npoint[1] = 10.0\n\n# You can index a tuple, like a vector, to get the stored element(s):\n\npoint[1:2]\n\n# Tuples, vectors, pairs and other iterables can be easily unpacked using an\n# assignation:\n\nx, y, z = point\ny\n\n# You can use this unpacking when iterating a dictionary:\n\nfor (key, value) in dictionary\n\tprintln(\"key: \", key, \" value: \", value)\nend\n\n# #### Exercise 3\n#\n# Write a function to return the reverse complement of a DNA sequence (string)\n# using a dictionary, the `join` function and the `Base.Iterators.reverse`\n# iterator. It should use a 'N' as complementary of any base different from\n# 'A', 'C', 'T' or 'G':\n\n## function reverse_complement(...\n \n#-\n\nusing Test\n@test reverse_complement(\"ACTGGTCCCNT\") == \"ANGGGACCAGT\"\n\n# ### Named tuples\n#\n# They can be an easy and fast way to store data:\n\npoint = (x=1.0, y=2.0, z=3.0) # named tuple\n\n# You can use `namedtuple.name` to access a particular element:\n\npoint.y\n\n# ## Sets\n#\n# You can use `Set` to represent a set of unique elements:\n\nset = Set([1, 2, 2, 3, 3, 3, 4, 4, 4, 4])\n\n# Test membership is $O(1)$\n\n4 in set\n\n# You can get the intersection of two sets using `intersect` or\n# `∩` (`\\cap<TAB>`)\n\nset_a = Set([1, 2, 3])\nset_b = Set([2, 3, 4])\nset_a ∩ set_b # intersect(set, set_b)\n\n# And the unioin of to sets using `union` or `∪` (`\\cup<TAB>`)\n\nset_a ∪ set_b # union(set, set_b)\n\n# The symmetric difference, i.e. disjunctive union, of two sets\n\nsymdiff(set_a, set_b)\n", "meta": {"hexsha": "6fba41b3479d8d7d87392a79b87f535a10fec10f", "size": 6039, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Introduction/02_DataStructures.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/02_DataStructures.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/02_DataStructures.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": 23.4980544747, "max_line_length": 141, "alphanum_fraction": 0.6711376056, "num_tokens": 1903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073333856566001, "lm_q2_score": 0.2568319970758679, "lm_q1q2_score": 0.10461624691385929}}