{"text": "# ------------------------------------------------------------------------------------------\n# # Multiple dispatch\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# In this notebook we'll explore **multiple dispatch**, which is a key feature of Julia.\n#\n# Multiple dispatch makes software *generic* and *fast*!\n#\n# #### Starting with the familiar\n#\n# To understand multiple dispatch in Julia, let's start with what we've already seen.\n#\n# We can declare functions in Julia without giving Julia any information about the types of\n# the input arguments that function will receive:\n# ------------------------------------------------------------------------------------------\n\nf(x) = x^2\n\n# ------------------------------------------------------------------------------------------\n# and then Julia will determine on its own which input argument types make sense and which\n# do not:\n# ------------------------------------------------------------------------------------------\n\nf(10)\n\nf([1, 2, 3])\n\n# ------------------------------------------------------------------------------------------\n# #### Specifying the types of our input arguments\n#\n# However, we also have the *option* to tell Julia explicitly what types our input arguments\n# are allowed to have.\n#\n# For example, let's write a function `foo` that only takes strings as inputs.\n# ------------------------------------------------------------------------------------------\n\nfoo(x::String, y::String) = println(\"My inputs x and y are both strings!\")\n\n# ------------------------------------------------------------------------------------------\n# We see here that in order to restrict the type of `x` and `y` to `String`s, we just follow\n# the input argument name by a double colon and the keyword `String`.\n#\n# Now we'll see that `foo` works on `String`s and doesn't work on other input argument\n# types.\n# ------------------------------------------------------------------------------------------\n\nfoo(\"hello\", \"hi!\")\n\nfoo(3, 4)\n\n# ------------------------------------------------------------------------------------------\n# To get `foo` to work on integer (`Int`) inputs, let's tack `::Int` onto our input\n# arguments when we declare `foo`.\n# ------------------------------------------------------------------------------------------\n\nfoo(x::Int, y::Int) = println(\"My inputs x and y are both integers!\")\n\nfoo(3, 4)\n\n# ------------------------------------------------------------------------------------------\n# Now `foo` works on integers! But look, `foo` also still works when `x` and `y` are\n# strings!\n# ------------------------------------------------------------------------------------------\n\nfoo(\"hello\", \"hi!\")\n\n# ------------------------------------------------------------------------------------------\n# This is starting to get to the heart of multiple dispatch. When we declared\n#\n# ```julia\n# foo(x::Int, y::Int) = println(\"My inputs x and y are both integers!\")\n# ```\n# we didn't overwrite or replace\n# ```julia\n# foo(y::String, y::String)```\n#\n# Instead, we just added an additional ***method*** to the ***generic function*** called\n# `foo`.\n#\n# A ***generic function*** is the abstract concept associated with a particular operation.\n#\n# For example, the generic function `+` represents the concept of addition.\n#\n# A ***method*** is a specific implementation of a generic function for *particular argument\n# types*.\n#\n# For example, `+` has methods that accept floating point numbers, integers, matrices, etc.\n#\n# We can use the `methods` to see how many methods there are for `foo`.\n# ------------------------------------------------------------------------------------------\n\nmethods(foo)\n\nmethods(+)\n\n# ------------------------------------------------------------------------------------------\n# So, we now can call `foo` on integers or strings. When you call `foo` on a particular set\n# of arguments, Julia will infer the types of the inputs and dispatch the appropriate\n# method. *This* is multiple dispatch.\n#\n# Multiple dispatch makes our code generic and fast. Our code can be generic and flexible\n# because we can write code in terms of abstract operations such as addition and\n# multiplication, rather than in terms of specific implementations. At the same time, our\n# code runs quickly because Julia is able to call efficient methods for the relevant types.\n#\n# To see which method is being dispatched when we call a generic function, we can use the\n# @which macro:\n# ------------------------------------------------------------------------------------------\n\n@which foo(3, 4)\n\n@which 3.0 + 3.0\n\n# ------------------------------------------------------------------------------------------\n# Given that a method written specifically for floating point numbers is dispatched on `3.0\n# + 3.0`, the LLVM code generated is extremely terse:\n# ------------------------------------------------------------------------------------------\n\n@code_llvm 3.0 + 3.0\n\n# ------------------------------------------------------------------------------------------\n# Note that Julia is fast even when we write generic function definitions because, at the\n# end of the day, specific/tailored methods are called under the hood.\n#\n# For example, note that we can declare the adding function `myadd` without providing any\n# type annotations -\n# ------------------------------------------------------------------------------------------\n\nmyadd(x, y) = x + y\n\n# ------------------------------------------------------------------------------------------\n# and though we haven't constrained the types of `x` and `y`, we'll see that the LLVM code\n# generated for `myadd(3.0, 3.0)` looks like that of `3.0 + 3.0`\n# ------------------------------------------------------------------------------------------\n\n@code_llvm myadd(3.0, 3.0)\n", "meta": {"hexsha": "bbd3b8e278c9a68a5fe32c4cb9090b049bf6aa32", "size": 5929, "ext": "jl", "lang": "Julia", "max_stars_repo_path": ".nbexports/introductory-tutorials/intro-to-julia/short-version/06.Multiple_dispatch.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/short-version/06.Multiple_dispatch.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/short-version/06.Multiple_dispatch.jl", "max_forks_repo_name": "grenkoca/JuliaTutorials", "max_forks_repo_head_hexsha": "3968e0430db77856112521522e10f7da0d7610a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 394, "max_forks_repo_forks_event_min_datetime": "2020-07-14T23:22:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T20:12:57.000Z", "avg_line_length": 42.9637681159, "max_line_length": 92, "alphanum_fraction": 0.4456063417, "num_tokens": 1033, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.21469142916152645, "lm_q1q2_score": 0.09981038277759216}} {"text": "### A Pluto.jl notebook ###\n# v0.17.4\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ bbe90636-9d1f-4ee0-8e35-c285f7b922d0\nbegin\n\timport CSV, DataFrames\n\tusing EvoTrees\n \tusing MLJ \n \tusing MLJLinearModels\n\tusing MLJBase\n \tusing MLJMultivariateStatsInterface\n \tusing UrlDownload\n\tusing PlutoUI\nend\n\n\n# ╔═╡ 83a7b4d7-6442-44b2-9388-8330b19cd537\nhtml\"\"\"\n
\n\n
\n\n \n\n

Tutorial - Part 3

\n

\nMachine Learning in Julia\n

\n\"\"\"\n\n# ╔═╡ 24abafc3-0e26-4cd2-9bca-7c69b794f8ce\nPlutoUI.TableOfContents(title = \"MLJ Tutorial - Part 3\")\n\n# ╔═╡ b67c62c2-15ab-4328-b795-033f6f2a0674\nmd\"\"\"\nAn introduction to the\n[MLJ](https://alan-turing-institute.github.io/MLJ.jl/stable/)\ntoolbox.\n\"\"\"\n\n# ╔═╡ bc689638-fd19-4c9f-935f-ddf6a6bfbbdd\nmd\"## Set-up\"\n\n# ╔═╡ 197fd00e-9068-46ea-af2a-25235e544a31\nmd\"Inspect Julia version:\"\n\n# ╔═╡ f6d4f8c4-e441-45c4-8af5-148d95ea2900\nVERSION\n\n# ╔═╡ 45740c4d-b789-45dc-a6bf-47194d7e8e12\nmd\"The following instantiates a package environment.\"\n\n# ╔═╡ 42b0f1e1-16c9-4238-828a-4cc485149963\nmd\"\"\"\nThe package environment has been created using **Julia 1.6** and may not\ninstantiate properly for other Julia versions.\n\"\"\"\n\n# ╔═╡ 499cbc31-83ba-4583-ba1f-6363f43ec697\nmd\"## General resources\"\n\n# ╔═╡ db5821e8-956a-4a46-95ea-2955abd45275\nmd\"\"\"\n- [MLJ Cheatsheet](https://alan-turing-institute.github.io/MLJ.jl/dev/mlj_cheatsheet/)\n- [Common MLJ Workflows](https://alan-turing-institute.github.io/MLJ.jl/dev/common_mlj_workflows/)\n- [MLJ manual](https://alan-turing-institute.github.io/MLJ.jl/dev/)\n- [Data Science Tutorials in Julia](https://juliaai.github.io/DataScienceTutorials.jl/)\n\"\"\"\n\n# ╔═╡ 1e248249-5629-412f-b1b3-dd47e367ba54\nmd\"# Part 3 - Transformers and Pipelines\"\n\n# ╔═╡ d055d24f-1b2d-48a6-8d7e-8e449afd1c48\nmd\"## Transformers\"\n\n# ╔═╡ 0dc40881-6163-4948-a949-7f3bd292fe31\nmd\"\"\"\nUnsupervised models, which receive no target `y` during training,\nalways have a `transform` operation. They sometimes also support an\n`inverse_transform` operation, with obvious meaning, and sometimes\nsupport a `predict` operation (see the clustering example discussed\n[here](https://alan-turing-institute.github.io/MLJ.jl/dev/transformers/#Transformers-that-also-predict-1)).\nOtherwise, they are handled much like supervised models.\n\"\"\"\n\n# ╔═╡ 0d066909-c9bf-4ae3-8514-99938a2932db\nmd\"Here's a simple standardization example:\"\n\n# ╔═╡ 29ea6531-1337-4527-92bd-6ebccf75659a\n x = rand(100)\n\n# ╔═╡ ad63ad4b-04c0-491b-a0de-1721c1bc2df2\n(mean(x), std(x))\n\n# ╔═╡ f86b62eb-6853-482a-bca8-7eec7950fd82\nbegin\n model = Standardizer() # a built-in model\n mach1 = machine(model, x)\n fit!(mach1)\n xhat = MLJ.transform(mach1, x);\n (mean(xhat), std(xhat))\nend\n\n# ╔═╡ 58686fe6-088a-4751-9873-1b1430e635cc\nmd\"This particular model has an `inverse_transform`:\"\n\n# ╔═╡ 8b90b209-cb98-4116-b43e-d0ebe87da176\ninverse_transform(mach1, xhat) ≈ x\n\n# ╔═╡ f1b47e75-0ce3-4e90-9009-4cfb2012998f\nmd\"## Re-encoding the King County House data as continuous\"\n\n# ╔═╡ e904fcb3-7603-40d2-abd3-cb77d7a79683\nmd\"\"\"\nFor further illustrations of transformers, let's re-encode *all* of the\nKing County House input features (see [Ex\n3](#exercise-3-fixing-scitypes-in-a-table)) into a set of `Continuous`\nfeatures. We do this with the `ContinuousEncoder` model, which, by\ndefault, will:\n\"\"\"\n\n# ╔═╡ e93966db-0dab-42ca-879e-dc128f3db7b3\nmd\"\"\"\n- one-hot encode all `Multiclass` features\n- coerce all `OrderedFactor` features to `Continuous` ones\n- coerce all `Count` features to `Continuous` ones (there aren't any)\n- drop any remaining non-Continuous features (none of these either)\n\"\"\"\n\n# ╔═╡ 2564f31e-4704-4820-a367-9aa3c6cf34d0\nmd\"First, we reload the data and fix the scitypes (Exercise 3):\"\n\n# ╔═╡ 7e23f8f6-1634-45c8-bf32-94657e65284e\nbegin\n \n house_csv = urldownload(\"https://raw.githubusercontent.com/ablaom/\"*\n \"MachineLearningInJulia2020/for-MLJ-version-0.16/\"*\n \"data/house.csv\");\n house = DataFrames.DataFrame(house_csv)\n coerce!(house, autotype(house_csv));\n coerce!(house, Count => Continuous, :zipcode => Multiclass);\n schema(house)\nend\n\n# ╔═╡ 348ff9a2-89ab-434a-9afd-65a5b5facac9\nyHouse, XHouse = unpack(house, ==(:price), rng=123);\n\n# ╔═╡ c7e83ce7-f067-4049-b6c8-54f5ed90a964\nmd\"Instantiate the unsupervised model (transformer):\"\n\n# ╔═╡ a6106065-1baf-4720-9292-fe822525fc77\nencoder = ContinuousEncoder() # a built-in model; no need to @load it\n\n# ╔═╡ 703d4ac3-116e-4e05-ae5e-4b83dcbc9675\nmd\"Bind the model to the data and fit!\"\n\n# ╔═╡ 5d976f7e-45ee-4cbb-8a29-32f11452654a\nmach2 = machine(encoder, XHouse) |> fit!\n\n# ╔═╡ aad55579-14f3-439a-a5f1-151fcbe229a2\nmd\"Transform and inspect the result:\"\n\n# ╔═╡ a6c1d3ea-6f43-42c7-8950-2f4327f23c1f\nXHouseCont = MLJ.transform(mach2, XHouse)\n\n# ╔═╡ 9f2f583a-e90a-43f6-81bc-2d5603785a09\nschema(XHouseCont)\n\n# ╔═╡ 828460a7-7d4e-444e-9d87-1d1fbb0e3997\nmd\"## More transformers\"\n\n# ╔═╡ 12631f23-8262-475d-b950-fddef2a1fb10\nmd\"Here's how to list all of MLJ's unsupervised models:\"\n\n# ╔═╡ d9069be8-d8c5-43ab-951b-64cb2a36c8e3\nmodels(m->!m.is_supervised)\n\n# ╔═╡ 4dee7ef6-b472-4b9c-b0e6-441461cc8770\nmd\"Some commonly used ones are built-in (do not require `@load`ing):\"\n\n# ╔═╡ 7a6df9e6-89f1-4117-8cb0-de601961bc02\nmd\"\"\"\nmodel type | does what?\n:----------------------------|:----------------------------------------------\nContinuousEncoder | transform input table to a table of `Continuous` features (see above)\nFeatureSelector | retain or dump selected features\nFillImputer | impute missing values\nOneHotEncoder | one-hot encoder `Multiclass` (and optionally `OrderedFactor`) features\nStandardizer | standardize (whiten) a vector or all `Continuous` features of a table\nUnivariateBoxCoxTransformer | apply a learned Box-Cox transformation to a vector\nUnivariateDiscretizer | discretize a `Continuous` vector, and hence render its elscitypw `OrderedFactor`\n\"\"\"\n\n# ╔═╡ 8ff17b93-2830-41e2-a87d-950c50fb2955\nmd\"\"\"\nIn addition to \"dynamic\" transformers (ones that learn something\nfrom the data and must be `fit!`) users can wrap ordinary functions\nas transformers, and such *static* transformers can depend on\nparameters, like the dynamic ones. See\n[here](https://alan-turing-institute.github.io/MLJ.jl/dev/transformers/#Static-transformers-1)\nfor how to define your own static transformers.\n\"\"\"\n\n# ╔═╡ d45a81ec-f978-4483-8448-4bcb089096cd\nmd\"## Pipelines\"\n\n# ╔═╡ b454845b-3b3b-4c46-a012-a84240254fb6\nlength(schema(XHouseCont).names)\n\n# ╔═╡ 28cf44d4-3f4b-485f-bbdd-9799f7bb2e60\nmd\"\"\"\nLet's suppose that additionally we'd like to reduce the dimension of\nour data. A model that will do this is `PCA` from\n`MultivariateStats.jl`:\n\"\"\"\n\n# ╔═╡ 1e780939-abf0-4203-97a7-88e3af4f10ee\nPCA = @load PCA\n\n# ╔═╡ 09ece795-72e1-4240-a833-1b098ab27d3f\nreducer = PCA()\n\n# ╔═╡ 8e76b5a5-7c80-4684-b372-8c9866e51852\nmd\"\"\"\nNow, rather simply repeating the work-flow above, applying the new\ntransformation to `XHouseCont`, we can combine both the encoding and the\ndimension-reducing models into a single model, known as a\n*pipeline*. While MLJ offers a powerful interface for composing\nmodels in a variety of ways, we'll stick to these simplest class of\ncomposite models for now. The simplest way to construct a pipeline is using the Julia's `|>` syntax:\n\"\"\"\n\n# ╔═╡ 5ed77309-afa6-4c94-88c0-761fe6b5a5d4\npipe1 = encoder |> reducer\n\n# ╔═╡ d45ff6ec-2dd6-4a9c-a97e-79337b0be5c8\nmd\"\"\"\nNotice that the model `pipe` has other models as hyperparameters (with names automatically generated based on the mode type name). The hyperparameters of the component models are are now nested, but we can still access them:\n\"\"\"\n\n# ╔═╡ 4a0b7419-d9ae-4570-b9b6-029e155045c0\npipe1.pca.pratio\n\n# ╔═╡ 3958b3df-51cd-4920-8f28-382c4a088a8f\npipe1.pca.pratio = 0.85\n\n# ╔═╡ e68044d8-42b4-49cd-86cf-35420d9e6995\nmd\"The pipeline model behaves like any other transformer:\"\n\n# ╔═╡ 26d649a8-3d96-4479-a29a-8d0445351914\nbegin\n mach3 = machine(pipe1, XHouse)\n fit!(mach3)\n XHouseSmall = transform(mach3, XHouse)\n schema(XHouseSmall)\nend\n\n# ╔═╡ 7f60c74e-b708-46f4-be65-28d0fcca50a8\nmd\"Want to combine this pre-processing with ridge regression?\"\n\n# ╔═╡ c8c960f0-2a46-42c2-8754-8bd531c8db8e\nRidgeRegressor = @load RidgeRegressor pkg=MLJLinearModels\n\n# ╔═╡ 4e327bb5-8abc-4e68-9832-d4c16415df30\nrgs = RidgeRegressor()\n\n# ╔═╡ f96a84ec-1cc0-400c-9493-9c2a2e3c5b51\npipe2 = pipe1 |> rgs\n\n# ╔═╡ fbb24be1-fe01-4489-b5fa-cb79ebf595ef\nmd\"\"\"\nNow our pipeline is a supervised model, instead of a transformer,\nwhose performance we can evaluate:\n\"\"\"\n\n# ╔═╡ 958f9a9a-23d5-446b-aa54-f7a086cb0264\nmach4 = machine(pipe2, XHouse, yHouse)\n\n# ╔═╡ ea64dbb5-963a-4da4-91c5-524da38aa391\nevaluate!(mach4, measure=mae, resampling=Holdout()) # CV(nfolds=6) is default\n\n# ╔═╡ 1ce36a90-ea25-48d6-ad90-b4405b216771\nmd\"## Training of composite models is \\\"smart\\\"\"\n\n# ╔═╡ 4270976f-1207-4086-895b-997a92b731e0\nmd\"\"\"\nNow notice what happens if we train on all the data, then change a\nregressor hyper-parameter and retrain:\n\"\"\"\n\n# ╔═╡ 1d0bce6b-ffff-4f30-a525-e9b04a4bd246\nfit!(mach4)\n\n# ╔═╡ 64a648e0-d5c9-4c3d-80f0-ba7781e173cf\nwith_terminal() do\n pipe2.ridge_regressor.lambda = 0.1\n fit!(mach4)\nend\n\n# ╔═╡ 5dcd0d55-bb5d-459a-9cbc-9a2c39793333\nmd\"Second time only the ridge regressor is retrained!\"\n\n# ╔═╡ 234c586e-862f-4216-b887-2b16710e5502\nmd\"\"\"\nMutate a hyper-parameter of the `PCA` model and every model except\nthe `ContinuousEncoder` (which comes before it will be retrained):\n\"\"\"\n\n# ╔═╡ b8e84a2c-2c7f-41f5-9452-5298a8a4a401\nwith_terminal() do\n pipe2.pca.pratio = 0.9999\n fit!(mach4)\nend\n\n# ╔═╡ 95b75a71-47b5-49b1-b017-96f1602f2cad\nmd\"## Inspecting composite models\"\n\n# ╔═╡ 5de9f9a0-ad8f-47de-8be2-2a4017c45345\nmd\"\"\"\nThe dot syntax used above to change the values of *nested*\nhyper-parameters is also useful when inspecting the learned\nparameters and report generated when training a composite model:\n\"\"\"\n\n# ╔═╡ aa7bdff7-7d1b-43b1-a7ad-80d84f5b0070\nfitted_params(mach4).ridge_regressor\n\n# ╔═╡ 92c5bc62-b430-41b8-8378-5aa686f0b407\nreport(mach4).pca\n\n# ╔═╡ adcb0506-e89d-43b0-9f43-49763e8691a1\nmd\"## Incorporating target transformations\"\n\n# ╔═╡ 667917e3-25d2-435c-bb0e-3a45761c733a\nmd\"\"\"\nNext, suppose that instead of using the raw `:price` as the\ntraining target, we want to use the log-price (a common practice in\ndealing with house price data). However, suppose that we still want\nto report final *predictions* on the original linear scale (and use\nthese for evaluation purposes). Then we wrap our unsupervised model using `TransformedTargetModel`, which has\nthe key-word arguments `target` and `inverse`.\n\"\"\"\n\n# ╔═╡ f71e4957-b6aa-480f-8acf-0c1d237fe9f9\nmd\"\"\"\nFirst we'll overload `log` and `exp` for broadcasting:\n\"\"\"\n\n# ╔═╡ dc119abd-72a1-4781-811d-5998beb56406\nbegin\n\tBase.log(v::AbstractArray) = log.(v)\n\tBase.exp(v::AbstractArray) = exp.(v)\nend\n\n# ╔═╡ 0398adfe-721a-4b97-910b-f8a9a217eff2\nmd\"Now for the new pipeline:\"\n\n# ╔═╡ 85f71232-0ec4-40a8-81b7-e11a56b42313\nrgs_log = TransformedTargetModel(rgs, target = log, inverse = exp)\n\n# ╔═╡ d1af0582-9074-4355-9d03-7ceec3db5d7f\npipe3 = pipe1 |> rgs_log\n\n# ╔═╡ 06fac83d-ec17-4503-b3b1-670e16d4251a\nmach5 = machine(pipe3, XHouse, yHouse)\n\n# ╔═╡ 9335bbb6-7169-47a2-8ccb-85c839a68433\nevaluate!(mach5, measure = mae)\n\n# ╔═╡ fbe0163a-ed06-49ea-8faa-017fa7aeca69\nmd\"\"\"\nMLJ will also allow you to insert *learned* target\ntransformations. For example, we might want to apply\n`Standardizer()` to the target, to standardize it, or\n`UnivariateBoxCoxTransformer()` to make it look Gaussian. Then\ninstead of specifying a *function* for `target`, we specify a\nunsupervised *model* (or model type). One does not specify `inverse`\nbecause only models implementing `inverse_transform` are\nallowed.\n\"\"\"\n\n# ╔═╡ 4fd0807d-61e5-4b4b-a1cb-54e34396a855\nmd\"Let's see which of these two options results in a better outcome:\"\n\n# ╔═╡ 1957f387-aee4-4c08-9838-327b915082f8\nbox = UnivariateBoxCoxTransformer(n=20)\n\n# ╔═╡ 7b59b396-daac-4dea-bc51-54fafe346cd8\nstand = Standardizer()\n\n# ╔═╡ 2efdfa9c-8e70-4c09-b9f9-85c873edc16a\nrgs_box = TransformedTargetModel(rgs, target=box)\n\n# ╔═╡ dcf51860-a300-453e-87fc-345e741f94d0\npipe4 = pipe1 |> rgs_box\n\n# ╔═╡ c54f41ee-75e6-4181-8de7-d194004c9700\nmach6 = machine(pipe4, XHouse, yHouse)\n\n# ╔═╡ cb026565-6c5c-4f7a-91b6-417cfea74d41\nevaluate!(mach6, measure = mae)\n\n# ╔═╡ e073f936-f2a0-4609-83fe-bd8afb87cfc1\npipe4.transformed_target_model_deterministic.target = stand\n\n# ╔═╡ 91cca9cb-db5f-4d9f-983b-3f2b20444662\nevaluate!(mach6, measure = mae)\n\n# ╔═╡ a0488295-9642-4156-b7cc-46f4ef988c68\nmd\"# Resources for Part 3\"\n\n# ╔═╡ d59d9e91-b26d-4342-90fb-7f2721f6fcc7\nmd\"\"\"\n- From the MLJ manual:\n - [Transformers and other unsupervised models](https://alan-turing-institute.github.io/MLJ.jl/dev/transformers/)\n - [Linear pipelines](https://alan-turing-institute.github.io/MLJ.jl/dev/linear_pipelines/#Linear-Pipelines)\n- From Data Science Tutorials:\n - [Composing models](https://juliaai.github.io/DataScienceTutorials.jl/getting-started/composing-models/)\n\"\"\"\n\n# ╔═╡ c4f30527-c9b4-44e9-af65-ccd25ecb9818\nmd\"# Exercises for Part 3\"\n\n# ╔═╡ 25a6fd3c-60d1-44dd-8890-979691212d9b\nmd\"#### Exercise 7\"\n\n# ╔═╡ aed2b274-cc0c-42f2-a6fa-eaf14df5d44b\nmd\"\"\"\nConsider again the Horse Colic classification problem considered in\nExercise 6, but with all features, `Finite` and `Infinite`:\n\"\"\"\n\n# ╔═╡ 0df6be04-24fe-4417-8025-5084804a9f6c\nbegin\n csv_file = urldownload(\"https://raw.githubusercontent.com/ablaom/\"*\n \"MachineLearningInJulia2020/\"*\n \"for-MLJ-version-0.16/data/horse.csv\");\n horse = DataFrames.DataFrame(csv_file); # convert to data frame\n coerce!(horse, autotype(horse));\n coerce!(horse, Count => Continuous);\n coerce!(horse,\n :surgery => Multiclass,\n :age => Multiclass,\n :mucous_membranes => Multiclass,\n :capillary_refill_time => Multiclass,\n :outcome => Multiclass,\n :cp_data => Multiclass);\n \n yHorse, XHorse = unpack(horse, ==(:outcome));\n schema(XHorse)\nend\n\n# ╔═╡ 9abf25a8-7231-43f5-9e90-09023d201062\nmd\"\"\"\n(a) Define a pipeline that:\n- uses `Standardizer` to ensure that features that are already\n continuous are centered at zero and have unit variance\n- re-encodes the full set of features as `Continuous`, using\n `ContinuousEncoder`\n- uses the `KMeans` clustering model from `Clustering.jl`\n to reduce the dimension of the feature space to `k=10`.\n- trains a `EvoTreeClassifier` (a gradient tree boosting\n algorithm in `EvoTrees.jl`) on the reduced data, using\n `nrounds=50` and default values for the other\n hyper-parameters\n\n(b) Evaluate the pipeline on all data, using 6-fold cross-validation\nand `cross_entropy` loss.\n\n $\\star$ (c) Plot a learning curve which examines the effect on this loss\nas the tree booster parameter `max_depth` varies from 2 to 10.\n\"\"\"\n\n# ╔═╡ 6cce6530-0d12-4862-af4f-11c7de9e21dd\nhtml\"\"\n\n# ╔═╡ 135dac9b-0bd9-4e1d-8dba-241d9b744683\nmd\"\"\"\n---\n\n*This notebook was generated using [Literate.jl](https://github.com/fredrikekre/Literate.jl).*\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nCSV = \"336ed68f-0bac-5ca0-87d4-7b16caf5d00b\"\nDataFrames = \"a93c6f00-e57d-5684-b7b6-d8193f3e46c0\"\nEvoTrees = \"f6006082-12f8-11e9-0c9c-0d5d367ab1e5\"\nMLJ = \"add582a8-e3ab-11e8-2d5e-e98b27df1bc7\"\nMLJBase = \"a7f614a8-145f-11e9-1d2a-a57a1082229d\"\nMLJLinearModels = \"6ee0df7b-362f-4a72-a706-9e79364fb692\"\nMLJMultivariateStatsInterface = \"1b6a4a23-ba22-4f51-9698-8599985d3728\"\nPlutoUI = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nUrlDownload = \"856ac37a-3032-4c1c-9122-f86d88358c8b\"\n\n[compat]\nCSV = \"~0.9.11\"\nDataFrames = \"~1.3.1\"\nEvoTrees = \"~0.9.1\"\nMLJ = \"~0.17.0\"\nMLJBase = \"~0.19.2\"\nMLJLinearModels = \"~0.5.7\"\nMLJMultivariateStatsInterface = \"~0.2.2\"\nPlutoUI = \"~0.7.27\"\nUrlDownload = \"~1.0.0\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\n[[ARFFFiles]]\ndeps = [\"CategoricalArrays\", \"Dates\", \"Parsers\", \"Tables\"]\ngit-tree-sha1 = \"e8c8e0a2be6eb4f56b1672e46004463033daa409\"\nuuid = \"da404889-ca92-49ff-9e8b-0aa6b4d38dc8\"\nversion = \"1.4.1\"\n\n[[AbstractFFTs]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"485ee0867925449198280d4af84bdb46a2a404d0\"\nuuid = \"621f4979-c628-5d54-868e-fcf4e3e8185c\"\nversion = \"1.0.1\"\n\n[[AbstractPlutoDingetjes]]\ndeps = [\"Pkg\"]\ngit-tree-sha1 = \"8eaf9f1b4921132a4cff3f36a1d9ba923b14a481\"\nuuid = \"6e696c72-6542-2067-7265-42206c756150\"\nversion = \"1.1.4\"\n\n[[Adapt]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"af92965fb30777147966f58acb05da51c5616b5f\"\nuuid = \"79e6a3ab-5dfb-504d-930d-738a2a938a0e\"\nversion = \"3.3.3\"\n\n[[ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[Arpack]]\ndeps = [\"Arpack_jll\", \"Libdl\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"2ff92b71ba1747c5fdd541f8fc87736d82f40ec9\"\nuuid = \"7d9fca2a-8960-54d3-9f78-7d1dccf2cb97\"\nversion = \"0.4.0\"\n\n[[Arpack_jll]]\ndeps = [\"Libdl\", \"OpenBLAS_jll\", \"Pkg\"]\ngit-tree-sha1 = \"e214a9b9bd1b4e1b4f15b22c0994862b66af7ff7\"\nuuid = \"68821587-b530-5797-8361-c406ea357684\"\nversion = \"3.5.0+3\"\n\n[[ArrayInterface]]\ndeps = [\"Compat\", \"IfElse\", \"LinearAlgebra\", \"Requires\", \"SparseArrays\", \"Static\"]\ngit-tree-sha1 = \"1ee88c4c76caa995a885dc2f22a5d548dfbbc0ba\"\nuuid = \"4fba245c-0d91-5ea0-9b3e-6abc04ee57a9\"\nversion = \"3.2.2\"\n\n[[Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[BFloat16s]]\ndeps = [\"LinearAlgebra\", \"Printf\", \"Random\", \"Test\"]\ngit-tree-sha1 = \"a598ecb0d717092b5539dbbe890c98bac842b072\"\nuuid = \"ab4f0b2a-ad5b-11e8-123f-65d77653426b\"\nversion = \"0.2.0\"\n\n[[BSON]]\ngit-tree-sha1 = \"ebcd6e22d69f21249b7b8668351ebf42d6dc87a1\"\nuuid = \"fbb218c0-5317-5bc6-957e-2ee96dd4b1f0\"\nversion = \"0.3.4\"\n\n[[Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[CEnum]]\ngit-tree-sha1 = \"215a9aa4a1f23fbd05b92769fdd62559488d70e9\"\nuuid = \"fa961155-64e5-5f13-b03f-caf6b980ea82\"\nversion = \"0.4.1\"\n\n[[CSV]]\ndeps = [\"CodecZlib\", \"Dates\", \"FilePathsBase\", \"InlineStrings\", \"Mmap\", \"Parsers\", \"PooledArrays\", \"SentinelArrays\", \"Tables\", \"Unicode\", \"WeakRefStrings\"]\ngit-tree-sha1 = \"49f14b6c56a2da47608fe30aed711b5882264d7a\"\nuuid = \"336ed68f-0bac-5ca0-87d4-7b16caf5d00b\"\nversion = \"0.9.11\"\n\n[[CUDA]]\ndeps = [\"AbstractFFTs\", \"Adapt\", \"BFloat16s\", \"CEnum\", \"CompilerSupportLibraries_jll\", \"ExprTools\", \"GPUArrays\", \"GPUCompiler\", \"LLVM\", \"LazyArtifacts\", \"Libdl\", \"LinearAlgebra\", \"Logging\", \"Printf\", \"Random\", \"Random123\", \"RandomNumbers\", \"Reexport\", \"Requires\", \"SparseArrays\", \"SpecialFunctions\", \"TimerOutputs\"]\ngit-tree-sha1 = \"429a1a05348ce948a96adbdd873fbe6d9e5e052f\"\nuuid = \"052768ef-5323-5732-b1bb-66c8b64840ba\"\nversion = \"3.6.2\"\n\n[[CategoricalArrays]]\ndeps = [\"DataAPI\", \"Future\", \"Missings\", \"Printf\", \"Requires\", \"Statistics\", \"Unicode\"]\ngit-tree-sha1 = \"c308f209870fdbd84cb20332b6dfaf14bf3387f8\"\nuuid = \"324d7699-5711-5eae-9e2f-1d82baa6b597\"\nversion = \"0.10.2\"\n\n[[CategoricalDistributions]]\ndeps = [\"CategoricalArrays\", \"Distributions\", \"Missings\", \"OrderedCollections\", \"Random\", \"ScientificTypesBase\", \"UnicodePlots\"]\ngit-tree-sha1 = \"a5734a58e5dc8c749b5507d03ba5e457d077181b\"\nuuid = \"af321ab8-2d2e-40a6-b165-3d674595d28e\"\nversion = \"0.1.4\"\n\n[[ChainRulesCore]]\ndeps = [\"Compat\", \"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"926870acb6cbcf029396f2f2de030282b6bc1941\"\nuuid = \"d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4\"\nversion = \"1.11.4\"\n\n[[ChangesOfVariables]]\ndeps = [\"ChainRulesCore\", \"LinearAlgebra\", \"Test\"]\ngit-tree-sha1 = \"bf98fa45a0a4cee295de98d4c1462be26345b9a1\"\nuuid = \"9e997f8a-9a97-42d5-a9f1-ce6bfc15e2c0\"\nversion = \"0.1.2\"\n\n[[CodecZlib]]\ndeps = [\"TranscodingStreams\", \"Zlib_jll\"]\ngit-tree-sha1 = \"ded953804d019afa9a3f98981d99b33e3db7b6da\"\nuuid = \"944b1d66-785c-5afd-91f1-9de20f533193\"\nversion = \"0.7.0\"\n\n[[ColorTypes]]\ndeps = [\"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"024fe24d83e4a5bf5fc80501a314ce0d1aa35597\"\nuuid = \"3da002f7-5984-5a60-b8a6-cbb66c0b333f\"\nversion = \"0.11.0\"\n\n[[CommonSubexpressions]]\ndeps = [\"MacroTools\", \"Test\"]\ngit-tree-sha1 = \"7b8a93dba8af7e3b42fecabf646260105ac373f7\"\nuuid = \"bbf7d656-a473-5ed7-a52c-81e309532950\"\nversion = \"0.3.0\"\n\n[[Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"44c37b4636bc54afac5c574d2d02b625349d6582\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.41.0\"\n\n[[CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[ComputationalResources]]\ngit-tree-sha1 = \"52cb3ec90e8a8bea0e62e275ba577ad0f74821f7\"\nuuid = \"ed09eef8-17a6-5b46-8889-db040fac31e3\"\nversion = \"0.3.2\"\n\n[[Crayons]]\ngit-tree-sha1 = \"b618084b49e78985ffa8422f32b9838e397b9fc2\"\nuuid = \"a8cc5b0e-0ffa-5ad4-8c14-923d3ee1735f\"\nversion = \"4.1.0\"\n\n[[DataAPI]]\ngit-tree-sha1 = \"cc70b17275652eb47bc9e5f81635981f13cea5c8\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.9.0\"\n\n[[DataFrames]]\ndeps = [\"Compat\", \"DataAPI\", \"Future\", \"InvertedIndices\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"Markdown\", \"Missings\", \"PooledArrays\", \"PrettyTables\", \"Printf\", \"REPL\", \"Reexport\", \"SortingAlgorithms\", \"Statistics\", \"TableTraits\", \"Tables\", \"Unicode\"]\ngit-tree-sha1 = \"cfdfef912b7f93e4b848e80b9befdf9e331bc05a\"\nuuid = \"a93c6f00-e57d-5684-b7b6-d8193f3e46c0\"\nversion = \"1.3.1\"\n\n[[DataStructures]]\ndeps = [\"Compat\", \"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"3daef5523dd2e769dad2365274f760ff5f282c7d\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.18.11\"\n\n[[DataValueInterfaces]]\ngit-tree-sha1 = \"bfc1187b79289637fa0ef6d4436ebdfe6905cbd6\"\nuuid = \"e2d170a0-9d28-54be-80f0-106bbe20a464\"\nversion = \"1.0.0\"\n\n[[Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[DensityInterface]]\ndeps = [\"InverseFunctions\", \"Test\"]\ngit-tree-sha1 = \"80c3e8639e3353e5d2912fb3a1916b8455e2494b\"\nuuid = \"b429d917-457f-4dbc-8f4c-0cc954292b1d\"\nversion = \"0.4.0\"\n\n[[DiffResults]]\ndeps = [\"StaticArrays\"]\ngit-tree-sha1 = \"c18e98cba888c6c25d1c3b048e4b3380ca956805\"\nuuid = \"163ba53b-c6d8-5494-b064-1a9d43ac40c5\"\nversion = \"1.0.3\"\n\n[[DiffRules]]\ndeps = [\"LogExpFunctions\", \"NaNMath\", \"Random\", \"SpecialFunctions\"]\ngit-tree-sha1 = \"9bc5dac3c8b6706b58ad5ce24cffd9861f07c94f\"\nuuid = \"b552c78f-8df3-52c6-915a-8e097449b14b\"\nversion = \"1.9.0\"\n\n[[Distances]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"3258d0659f812acde79e8a74b11f17ac06d0ca04\"\nuuid = \"b4f34e82-e78d-54a5-968a-f98e89d6e8f7\"\nversion = \"0.10.7\"\n\n[[Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[Distributions]]\ndeps = [\"ChainRulesCore\", \"DensityInterface\", \"FillArrays\", \"LinearAlgebra\", \"PDMats\", \"Printf\", \"QuadGK\", \"Random\", \"SparseArrays\", \"SpecialFunctions\", \"Statistics\", \"StatsBase\", \"StatsFuns\", \"Test\"]\ngit-tree-sha1 = \"6a8dc9f82e5ce28279b6e3e2cea9421154f5bd0d\"\nuuid = \"31c24e10-a181-5473-b8eb-7969acd0382f\"\nversion = \"0.25.37\"\n\n[[DocStringExtensions]]\ndeps = [\"LibGit2\"]\ngit-tree-sha1 = \"b19534d1895d702889b219c382a6e18010797f0b\"\nuuid = \"ffbed154-4ef7-542d-bbb7-c09d3a79fcae\"\nversion = \"0.8.6\"\n\n[[Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[EarCut_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"3f3a2501fa7236e9b911e0f7a588c657e822bb6d\"\nuuid = \"5ae413db-bbd1-5e63-b57d-d24a61df00f5\"\nversion = \"2.2.3+0\"\n\n[[EarlyStopping]]\ndeps = [\"Dates\", \"Statistics\"]\ngit-tree-sha1 = \"98fdf08b707aaf69f524a6cd0a67858cefe0cfb6\"\nuuid = \"792122b4-ca99-40de-a6bc-6742525f08b6\"\nversion = \"0.3.0\"\n\n[[EvoTrees]]\ndeps = [\"BSON\", \"CUDA\", \"CategoricalArrays\", \"Distributions\", \"MLJModelInterface\", \"NetworkLayout\", \"Random\", \"RecipesBase\", \"SpecialFunctions\", \"StaticArrays\", \"Statistics\", \"StatsBase\"]\ngit-tree-sha1 = \"d1d91fd0643d6eb7946c15115b625b0b1e1a5393\"\nuuid = \"f6006082-12f8-11e9-0c9c-0d5d367ab1e5\"\nversion = \"0.9.1\"\n\n[[ExprTools]]\ngit-tree-sha1 = \"b7e3d17636b348f005f11040025ae8c6f645fe92\"\nuuid = \"e2ba6199-217a-4e67-a87a-7c52f15ade04\"\nversion = \"0.1.6\"\n\n[[FilePathsBase]]\ndeps = [\"Compat\", \"Dates\", \"Mmap\", \"Printf\", \"Test\", \"UUIDs\"]\ngit-tree-sha1 = \"04d13bfa8ef11720c24e4d840c0033d145537df7\"\nuuid = \"48062228-2e41-5def-b9a4-89aafe57970f\"\nversion = \"0.9.17\"\n\n[[FillArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"SparseArrays\", \"Statistics\"]\ngit-tree-sha1 = \"8756f9935b7ccc9064c6eef0bff0ad643df733a3\"\nuuid = \"1a297f60-69ca-5386-bcde-b61e274b549b\"\nversion = \"0.12.7\"\n\n[[FiniteDiff]]\ndeps = [\"ArrayInterface\", \"LinearAlgebra\", \"Requires\", \"SparseArrays\", \"StaticArrays\"]\ngit-tree-sha1 = \"8b3c09b56acaf3c0e581c66638b85c8650ee9dca\"\nuuid = \"6a86dc24-6348-571c-b903-95158fe2bd41\"\nversion = \"2.8.1\"\n\n[[FixedPointNumbers]]\ndeps = [\"Statistics\"]\ngit-tree-sha1 = \"335bfdceacc84c5cdf16aadc768aa5ddfc5383cc\"\nuuid = \"53c48c17-4a7d-5ca2-90c5-79b7896eea93\"\nversion = \"0.8.4\"\n\n[[Formatting]]\ndeps = [\"Printf\"]\ngit-tree-sha1 = \"8339d61043228fdd3eb658d86c926cb282ae72a8\"\nuuid = \"59287772-0a20-5a39-b81b-1366585eb4c0\"\nversion = \"0.4.2\"\n\n[[ForwardDiff]]\ndeps = [\"CommonSubexpressions\", \"DiffResults\", \"DiffRules\", \"LinearAlgebra\", \"LogExpFunctions\", \"NaNMath\", \"Preferences\", \"Printf\", \"Random\", \"SpecialFunctions\", \"StaticArrays\"]\ngit-tree-sha1 = \"2b72a5624e289ee18256111657663721d59c143e\"\nuuid = \"f6369f11-7733-5829-9624-2563aa707210\"\nversion = \"0.10.24\"\n\n[[Future]]\ndeps = [\"Random\"]\nuuid = \"9fa8497b-333b-5362-9e8d-4d0656e87820\"\n\n[[GPUArrays]]\ndeps = [\"Adapt\", \"LinearAlgebra\", \"Printf\", \"Random\", \"Serialization\", \"Statistics\"]\ngit-tree-sha1 = \"d9681e61fbce7dde48684b40bdb1a319c4083be7\"\nuuid = \"0c68f7d7-f131-5f86-a1c3-88cf8149b2d7\"\nversion = \"8.1.3\"\n\n[[GPUCompiler]]\ndeps = [\"ExprTools\", \"InteractiveUtils\", \"LLVM\", \"Libdl\", \"Logging\", \"TimerOutputs\", \"UUIDs\"]\ngit-tree-sha1 = \"2cac236070c2c4b36de54ae9146b55ee2c34ac7a\"\nuuid = \"61eb1bfa-7361-4325-ad38-22787b887f55\"\nversion = \"0.13.10\"\n\n[[GeometryBasics]]\ndeps = [\"EarCut_jll\", \"IterTools\", \"LinearAlgebra\", \"StaticArrays\", \"StructArrays\", \"Tables\"]\ngit-tree-sha1 = \"58bcdf5ebc057b085e58d95c138725628dd7453c\"\nuuid = \"5c1252a2-5f33-56bf-86c9-59e7332b4326\"\nversion = \"0.4.1\"\n\n[[HTTP]]\ndeps = [\"Base64\", \"Dates\", \"IniFile\", \"Logging\", \"MbedTLS\", \"NetworkOptions\", \"Sockets\", \"URIs\"]\ngit-tree-sha1 = \"0fa77022fe4b511826b39c894c90daf5fce3334a\"\nuuid = \"cd3eb016-35fb-5094-929b-558a96fad6f3\"\nversion = \"0.9.17\"\n\n[[Hyperscript]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"8d511d5b81240fc8e6802386302675bdf47737b9\"\nuuid = \"47d2ed2b-36de-50cf-bf87-49c2cf4b8b91\"\nversion = \"0.0.4\"\n\n[[HypertextLiteral]]\ngit-tree-sha1 = \"2b078b5a615c6c0396c77810d92ee8c6f470d238\"\nuuid = \"ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2\"\nversion = \"0.9.3\"\n\n[[IOCapture]]\ndeps = [\"Logging\", \"Random\"]\ngit-tree-sha1 = \"f7be53659ab06ddc986428d3a9dcc95f6fa6705a\"\nuuid = \"b5f81e59-6552-4d32-b1f0-c071b021bf89\"\nversion = \"0.2.2\"\n\n[[IfElse]]\ngit-tree-sha1 = \"debdd00ffef04665ccbb3e150747a77560e8fad1\"\nuuid = \"615f187c-cbe4-4ef1-ba3b-2fcf58d6d173\"\nversion = \"0.1.1\"\n\n[[IniFile]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"098e4d2c533924c921f9f9847274f2ad89e018b8\"\nuuid = \"83e8ac13-25f8-5344-8a64-a9f2b223428f\"\nversion = \"0.5.0\"\n\n[[InlineStrings]]\ndeps = [\"Parsers\"]\ngit-tree-sha1 = \"8d70835a3759cdd75881426fced1508bb7b7e1b6\"\nuuid = \"842dd82b-1e85-43dc-bf29-5d0ee9dffc48\"\nversion = \"1.1.1\"\n\n[[InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[InverseFunctions]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"a7254c0acd8e62f1ac75ad24d5db43f5f19f3c65\"\nuuid = \"3587e190-3f89-42d0-90ee-14403ec27112\"\nversion = \"0.1.2\"\n\n[[InvertedIndices]]\ngit-tree-sha1 = \"bee5f1ef5bf65df56bdd2e40447590b272a5471f\"\nuuid = \"41ab1584-1d38-5bbf-9106-f11c6c58b48f\"\nversion = \"1.1.0\"\n\n[[IrrationalConstants]]\ngit-tree-sha1 = \"7fd44fd4ff43fc60815f8e764c0f352b83c49151\"\nuuid = \"92d709cd-6900-40b7-9082-c6be49f344b6\"\nversion = \"0.1.1\"\n\n[[IterTools]]\ngit-tree-sha1 = \"fa6287a4469f5e048d763df38279ee729fbd44e5\"\nuuid = \"c8e1da08-722c-5040-9ed9-7db0dc04731e\"\nversion = \"1.4.0\"\n\n[[IterationControl]]\ndeps = [\"EarlyStopping\", \"InteractiveUtils\"]\ngit-tree-sha1 = \"83c84b7b87d3063e48a909a86c3c5bf4c3521962\"\nuuid = \"b3c1a2ee-3fec-4384-bf48-272ea71de57c\"\nversion = \"0.5.2\"\n\n[[IterativeSolvers]]\ndeps = [\"LinearAlgebra\", \"Printf\", \"Random\", \"RecipesBase\", \"SparseArrays\"]\ngit-tree-sha1 = \"1169632f425f79429f245113b775a0e3d121457c\"\nuuid = \"42fd0dbc-a981-5370-80f2-aaf504508153\"\nversion = \"0.9.2\"\n\n[[IteratorInterfaceExtensions]]\ngit-tree-sha1 = \"a3f24677c21f5bbe9d2a714f95dcd58337fb2856\"\nuuid = \"82899510-4779-5014-852e-03e436cf321d\"\nversion = \"1.0.0\"\n\n[[JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"642a199af8b68253517b80bd3bfd17eb4e84df6e\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.3.0\"\n\n[[JLSO]]\ndeps = [\"BSON\", \"CodecZlib\", \"FilePathsBase\", \"Memento\", \"Pkg\", \"Serialization\"]\ngit-tree-sha1 = \"e00feb9d56e9e8518e0d60eef4d1040b282771e2\"\nuuid = \"9da8a3cd-07a3-59c0-a743-3fdc52c30d11\"\nversion = \"2.6.0\"\n\n[[JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"8076680b162ada2a031f707ac7b4953e30667a37\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.2\"\n\n[[LLVM]]\ndeps = [\"CEnum\", \"LLVMExtra_jll\", \"Libdl\", \"Printf\", \"Unicode\"]\ngit-tree-sha1 = \"7cc22e69995e2329cc047a879395b2b74647ab5f\"\nuuid = \"929cbde3-209d-540e-8aea-75f648917ca0\"\nversion = \"4.7.0\"\n\n[[LLVMExtra_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"c5fc4bef251ecd37685bea1c4068a9cfa41e8b9a\"\nuuid = \"dad2f222-ce93-54a1-a47d-0025e8a3acab\"\nversion = \"0.0.13+0\"\n\n[[LatinHypercubeSampling]]\ndeps = [\"Random\", \"StableRNGs\", \"StatsBase\", \"Test\"]\ngit-tree-sha1 = \"42938ab65e9ed3c3029a8d2c58382ca75bdab243\"\nuuid = \"a5e1c1ea-c99a-51d3-a14d-a9a37257b02d\"\nversion = \"1.8.0\"\n\n[[LazyArtifacts]]\ndeps = [\"Artifacts\", \"Pkg\"]\nuuid = \"4af54fe1-eca0-43a8-85a7-787d91b784e3\"\n\n[[LearnBase]]\ngit-tree-sha1 = \"a0d90569edd490b82fdc4dc078ea54a5a800d30a\"\nuuid = \"7f8f8fb0-2700-5f03-b4bd-41f8cfc144b6\"\nversion = \"0.4.1\"\n\n[[LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[LineSearches]]\ndeps = [\"LinearAlgebra\", \"NLSolversBase\", \"NaNMath\", \"Parameters\", \"Printf\"]\ngit-tree-sha1 = \"f27132e551e959b3667d8c93eae90973225032dd\"\nuuid = \"d3d80556-e9d4-5f37-9878-2ab0fcc64255\"\nversion = \"7.1.1\"\n\n[[LinearAlgebra]]\ndeps = [\"Libdl\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[LinearMaps]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\ngit-tree-sha1 = \"dbb14c604fc47aa4f2e19d0ebb7b6416f3cfa5f5\"\nuuid = \"7a12625a-238d-50fd-b39a-03d52299707e\"\nversion = \"3.5.1\"\n\n[[LogExpFunctions]]\ndeps = [\"ChainRulesCore\", \"ChangesOfVariables\", \"DocStringExtensions\", \"InverseFunctions\", \"IrrationalConstants\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"e5718a00af0ab9756305a0392832c8952c7426c1\"\nuuid = \"2ab3a3ac-af41-5b50-aa03-7779005ae688\"\nversion = \"0.3.6\"\n\n[[Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[LossFunctions]]\ndeps = [\"InteractiveUtils\", \"LearnBase\", \"Markdown\", \"RecipesBase\", \"StatsBase\"]\ngit-tree-sha1 = \"0f057f6ea90a84e73a8ef6eebb4dc7b5c330020f\"\nuuid = \"30fc2ffe-d236-52d8-8643-a9d8f7c094a7\"\nversion = \"0.7.2\"\n\n[[MLJ]]\ndeps = [\"CategoricalArrays\", \"ComputationalResources\", \"Distributed\", \"Distributions\", \"LinearAlgebra\", \"MLJBase\", \"MLJEnsembles\", \"MLJIteration\", \"MLJModels\", \"MLJSerialization\", \"MLJTuning\", \"OpenML\", \"Pkg\", \"ProgressMeter\", \"Random\", \"ScientificTypes\", \"Statistics\", \"StatsBase\", \"Tables\"]\ngit-tree-sha1 = \"3b4ebc5023cc039c65a1089e6d8c248a9b96dfd1\"\nuuid = \"add582a8-e3ab-11e8-2d5e-e98b27df1bc7\"\nversion = \"0.17.0\"\n\n[[MLJBase]]\ndeps = [\"CategoricalArrays\", \"CategoricalDistributions\", \"ComputationalResources\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"Distributions\", \"InteractiveUtils\", \"InvertedIndices\", \"LinearAlgebra\", \"LossFunctions\", \"MLJModelInterface\", \"Missings\", \"OrderedCollections\", \"Parameters\", \"PrettyTables\", \"ProgressMeter\", \"Random\", \"ScientificTypes\", \"StatisticalTraits\", \"Statistics\", \"StatsBase\", \"Tables\"]\ngit-tree-sha1 = \"54cae1f0bde7bbc72fe7ff42353b7880347bd0d5\"\nuuid = \"a7f614a8-145f-11e9-1d2a-a57a1082229d\"\nversion = \"0.19.2\"\n\n[[MLJEnsembles]]\ndeps = [\"CategoricalArrays\", \"CategoricalDistributions\", \"ComputationalResources\", \"Distributed\", \"Distributions\", \"MLJBase\", \"MLJModelInterface\", \"ProgressMeter\", \"Random\", \"ScientificTypesBase\", \"StatsBase\"]\ngit-tree-sha1 = \"4279437ccc8ece8f478ded5139334b888dcce631\"\nuuid = \"50ed68f4-41fd-4504-931a-ed422449fee0\"\nversion = \"0.2.0\"\n\n[[MLJIteration]]\ndeps = [\"IterationControl\", \"MLJBase\", \"Random\"]\ngit-tree-sha1 = \"5f32c3d281904d6e5fc64250f55732d4b24014de\"\nuuid = \"614be32b-d00c-4edb-bd02-1eb411ab5e55\"\nversion = \"0.4.1\"\n\n[[MLJLinearModels]]\ndeps = [\"DocStringExtensions\", \"IterativeSolvers\", \"LinearAlgebra\", \"LinearMaps\", \"MLJModelInterface\", \"Optim\", \"Parameters\"]\ngit-tree-sha1 = \"dfbf4a5a8454034d21b6cfd9fd5a7960c8f7fb88\"\nuuid = \"6ee0df7b-362f-4a72-a706-9e79364fb692\"\nversion = \"0.5.7\"\n\n[[MLJModelInterface]]\ndeps = [\"Random\", \"ScientificTypesBase\", \"StatisticalTraits\"]\ngit-tree-sha1 = \"7ffdd75b2b13d1ec8640bfe80ab81bb158910a1d\"\nuuid = \"e80e1ace-859a-464e-9ed9-23947d8ae3ea\"\nversion = \"1.3.5\"\n\n[[MLJModels]]\ndeps = [\"CategoricalArrays\", \"CategoricalDistributions\", \"Dates\", \"Distances\", \"Distributions\", \"InteractiveUtils\", \"LinearAlgebra\", \"MLJModelInterface\", \"OrderedCollections\", \"Parameters\", \"Pkg\", \"PrettyPrinting\", \"REPL\", \"Random\", \"Requires\", \"ScientificTypes\", \"StatisticalTraits\", \"Statistics\", \"StatsBase\", \"Tables\"]\ngit-tree-sha1 = \"cecd98731368f1eb46634d1476f49332560f886f\"\nuuid = \"d491faf4-2d78-11e9-2867-c94bc002c0b7\"\nversion = \"0.15.1\"\n\n[[MLJMultivariateStatsInterface]]\ndeps = [\"Distances\", \"LinearAlgebra\", \"MLJModelInterface\", \"MultivariateStats\", \"StatsBase\"]\ngit-tree-sha1 = \"0cfc81ff677ea13ed72894992ee9e5f8ae4dbb9d\"\nuuid = \"1b6a4a23-ba22-4f51-9698-8599985d3728\"\nversion = \"0.2.2\"\n\n[[MLJSerialization]]\ndeps = [\"IterationControl\", \"JLSO\", \"MLJBase\", \"MLJModelInterface\"]\ngit-tree-sha1 = \"cc5877ad02ef02e273d2622f0d259d628fa61cd0\"\nuuid = \"17bed46d-0ab5-4cd4-b792-a5c4b8547c6d\"\nversion = \"1.1.3\"\n\n[[MLJTuning]]\ndeps = [\"ComputationalResources\", \"Distributed\", \"Distributions\", \"LatinHypercubeSampling\", \"MLJBase\", \"ProgressMeter\", \"Random\", \"RecipesBase\"]\ngit-tree-sha1 = \"a443cc088158b949876d7038a1aa37cfc8c5509b\"\nuuid = \"03970b2e-30c4-11ea-3135-d1576263f10f\"\nversion = \"0.6.16\"\n\n[[MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"3d3e902b31198a27340d0bf00d6ac452866021cf\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.9\"\n\n[[Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[MbedTLS]]\ndeps = [\"Dates\", \"MbedTLS_jll\", \"Random\", \"Sockets\"]\ngit-tree-sha1 = \"1c38e51c3d08ef2278062ebceade0e46cefc96fe\"\nuuid = \"739be429-bea8-5141-9913-cc70e7f3736d\"\nversion = \"1.0.3\"\n\n[[MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[Memento]]\ndeps = [\"Dates\", \"Distributed\", \"Requires\", \"Serialization\", \"Sockets\", \"Test\", \"UUIDs\"]\ngit-tree-sha1 = \"9b0b0dbf419fbda7b383dc12d108621d26eeb89f\"\nuuid = \"f28f55f0-a522-5efc-85c2-fe41dfb9b2d9\"\nversion = \"1.3.0\"\n\n[[Missings]]\ndeps = [\"DataAPI\"]\ngit-tree-sha1 = \"bf210ce90b6c9eed32d25dbcae1ebc565df2687f\"\nuuid = \"e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28\"\nversion = \"1.0.2\"\n\n[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[MultivariateStats]]\ndeps = [\"Arpack\", \"LinearAlgebra\", \"SparseArrays\", \"Statistics\", \"StatsBase\"]\ngit-tree-sha1 = \"8d958ff1854b166003238fe191ec34b9d592860a\"\nuuid = \"6f286f6a-111f-5878-ab1e-185364afe411\"\nversion = \"0.8.0\"\n\n[[NLSolversBase]]\ndeps = [\"DiffResults\", \"Distributed\", \"FiniteDiff\", \"ForwardDiff\"]\ngit-tree-sha1 = \"50310f934e55e5ca3912fb941dec199b49ca9b68\"\nuuid = \"d41bc354-129a-5804-8e4c-c37616107c6c\"\nversion = \"7.8.2\"\n\n[[NaNMath]]\ngit-tree-sha1 = \"f755f36b19a5116bb580de457cda0c140153f283\"\nuuid = \"77ba4419-2d1f-58cd-9bb1-8ffee604a2e3\"\nversion = \"0.3.6\"\n\n[[NetworkLayout]]\ndeps = [\"GeometryBasics\", \"LinearAlgebra\", \"Random\", \"Requires\", \"SparseArrays\"]\ngit-tree-sha1 = \"cac8fc7ba64b699c678094fa630f49b80618f625\"\nuuid = \"46757867-2c16-5918-afeb-47bfcb05e46a\"\nversion = \"0.4.4\"\n\n[[NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[OpenBLAS_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Libdl\"]\nuuid = \"4536629a-c528-5b80-bd46-f80d51c5b363\"\n\n[[OpenLibm_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"05823500-19ac-5b8b-9628-191a04bc5112\"\n\n[[OpenML]]\ndeps = [\"ARFFFiles\", \"HTTP\", \"JSON\", \"Markdown\", \"Pkg\"]\ngit-tree-sha1 = \"06080992e86a93957bfe2e12d3181443cedf2400\"\nuuid = \"8b6db2d4-7670-4922-a472-f9537c81ab66\"\nversion = \"0.2.0\"\n\n[[OpenSpecFun_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"13652491f6856acfd2db29360e1bbcd4565d04f1\"\nuuid = \"efe28fd5-8261-553b-a9e1-b2916fc3738e\"\nversion = \"0.5.5+0\"\n\n[[Optim]]\ndeps = [\"Compat\", \"FillArrays\", \"ForwardDiff\", \"LineSearches\", \"LinearAlgebra\", \"NLSolversBase\", \"NaNMath\", \"Parameters\", \"PositiveFactorizations\", \"Printf\", \"SparseArrays\", \"StatsBase\"]\ngit-tree-sha1 = \"916077e0f0f8966eb0dc98a5c39921fdb8f49eb4\"\nuuid = \"429524aa-4258-5aef-a3af-852621145aeb\"\nversion = \"1.6.0\"\n\n[[OrderedCollections]]\ngit-tree-sha1 = \"85f8e6578bf1f9ee0d11e7bb1b1456435479d47c\"\nuuid = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nversion = \"1.4.1\"\n\n[[PDMats]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\", \"SuiteSparse\"]\ngit-tree-sha1 = \"ee26b350276c51697c9c2d88a072b339f9f03d73\"\nuuid = \"90014a1f-27ba-587c-ab20-58faa44d9150\"\nversion = \"0.11.5\"\n\n[[Parameters]]\ndeps = [\"OrderedCollections\", \"UnPack\"]\ngit-tree-sha1 = \"34c0e9ad262e5f7fc75b10a9952ca7692cfc5fbe\"\nuuid = \"d96e819e-fc66-5662-9728-84c9c7592b0a\"\nversion = \"0.12.3\"\n\n[[Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"d7fa6237da8004be601e19bd6666083056649918\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.1.3\"\n\n[[Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[PlutoUI]]\ndeps = [\"AbstractPlutoDingetjes\", \"Base64\", \"ColorTypes\", \"Dates\", \"Hyperscript\", \"HypertextLiteral\", \"IOCapture\", \"InteractiveUtils\", \"JSON\", \"Logging\", \"Markdown\", \"Random\", \"Reexport\", \"UUIDs\"]\ngit-tree-sha1 = \"fed057115644d04fba7f4d768faeeeff6ad11a60\"\nuuid = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nversion = \"0.7.27\"\n\n[[PooledArrays]]\ndeps = [\"DataAPI\", \"Future\"]\ngit-tree-sha1 = \"db3a23166af8aebf4db5ef87ac5b00d36eb771e2\"\nuuid = \"2dfb63ee-cc39-5dd5-95bd-886bf059d720\"\nversion = \"1.4.0\"\n\n[[PositiveFactorizations]]\ndeps = [\"LinearAlgebra\"]\ngit-tree-sha1 = \"17275485f373e6673f7e7f97051f703ed5b15b20\"\nuuid = \"85a6dd25-e78a-55b7-8502-1745935b8125\"\nversion = \"0.2.4\"\n\n[[Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"2cf929d64681236a2e074ffafb8d568733d2e6af\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.3\"\n\n[[PrettyPrinting]]\ngit-tree-sha1 = \"a5db8a42938bc65c2679406c51a8f5fe9597c6e7\"\nuuid = \"54e16d92-306c-5ea0-a30b-337be88ac337\"\nversion = \"0.3.2\"\n\n[[PrettyTables]]\ndeps = [\"Crayons\", \"Formatting\", \"Markdown\", \"Reexport\", \"Tables\"]\ngit-tree-sha1 = \"dfb54c4e414caa595a1f2ed759b160f5a3ddcba5\"\nuuid = \"08abe8d2-0d0c-5749-adfa-8a2ac140af0d\"\nversion = \"1.3.1\"\n\n[[Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[ProgressMeter]]\ndeps = [\"Distributed\", \"Printf\"]\ngit-tree-sha1 = \"afadeba63d90ff223a6a48d2009434ecee2ec9e8\"\nuuid = \"92933f4c-e287-5a05-a399-4b506db050ca\"\nversion = \"1.7.1\"\n\n[[QuadGK]]\ndeps = [\"DataStructures\", \"LinearAlgebra\"]\ngit-tree-sha1 = \"78aadffb3efd2155af139781b8a8df1ef279ea39\"\nuuid = \"1fd47b50-473d-5c70-9696-f719f8f3bcdc\"\nversion = \"2.4.2\"\n\n[[REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[Random123]]\ndeps = [\"Libdl\", \"Random\", \"RandomNumbers\"]\ngit-tree-sha1 = \"0e8b146557ad1c6deb1367655e052276690e71a3\"\nuuid = \"74087812-796a-5b5d-8853-05524746bad3\"\nversion = \"1.4.2\"\n\n[[RandomNumbers]]\ndeps = [\"Random\", \"Requires\"]\ngit-tree-sha1 = \"043da614cc7e95c703498a491e2c21f58a2b8111\"\nuuid = \"e6cf234a-135c-5ec9-84dd-332b85af5143\"\nversion = \"1.5.3\"\n\n[[RecipesBase]]\ngit-tree-sha1 = \"6bf3f380ff52ce0832ddd3a2a7b9538ed1bcca7d\"\nuuid = \"3cdcf5f2-1ef4-517c-9805-6587b60abb01\"\nversion = \"1.2.1\"\n\n[[Reexport]]\ngit-tree-sha1 = \"45e428421666073eab6f2da5c9d310d99bb12f9b\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.2.2\"\n\n[[Requires]]\ndeps = [\"UUIDs\"]\ngit-tree-sha1 = \"8f82019e525f4d5c669692772a6f4b0a58b06a6a\"\nuuid = \"ae029012-a4dd-5104-9daa-d747884805df\"\nversion = \"1.2.0\"\n\n[[Rmath]]\ndeps = [\"Random\", \"Rmath_jll\"]\ngit-tree-sha1 = \"bf3188feca147ce108c76ad82c2792c57abe7b1f\"\nuuid = \"79098fc4-a85e-5d69-aa6a-4863f24498fa\"\nversion = \"0.7.0\"\n\n[[Rmath_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"68db32dff12bb6127bac73c209881191bf0efbb7\"\nuuid = \"f50d1b31-88e8-58de-be2c-1cc44531875f\"\nversion = \"0.3.0+0\"\n\n[[SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[ScientificTypes]]\ndeps = [\"CategoricalArrays\", \"ColorTypes\", \"Dates\", \"Distributions\", \"PrettyTables\", \"Reexport\", \"ScientificTypesBase\", \"StatisticalTraits\", \"Tables\"]\ngit-tree-sha1 = \"ba70c9a6e4c81cc3634e3e80bb8163ab5ef57eb8\"\nuuid = \"321657f4-b219-11e9-178b-2701a2544e81\"\nversion = \"3.0.0\"\n\n[[ScientificTypesBase]]\ngit-tree-sha1 = \"a8e18eb383b5ecf1b5e6fc237eb39255044fd92b\"\nuuid = \"30f210dd-8aff-4c5f-94ba-8e64358c1161\"\nversion = \"3.0.0\"\n\n[[SentinelArrays]]\ndeps = [\"Dates\", \"Random\"]\ngit-tree-sha1 = \"244586bc07462d22aed0113af9c731f2a518c93e\"\nuuid = \"91c51154-3ec4-41a3-a24f-3f23e20d615c\"\nversion = \"1.3.10\"\n\n[[Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[SortingAlgorithms]]\ndeps = [\"DataStructures\"]\ngit-tree-sha1 = \"b3363d7460f7d098ca0912c69b082f75625d7508\"\nuuid = \"a2af1166-a08f-5f64-846c-94a0d3cef48c\"\nversion = \"1.0.1\"\n\n[[SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[SpecialFunctions]]\ndeps = [\"ChainRulesCore\", \"IrrationalConstants\", \"LogExpFunctions\", \"OpenLibm_jll\", \"OpenSpecFun_jll\"]\ngit-tree-sha1 = \"e08890d19787ec25029113e88c34ec20cac1c91e\"\nuuid = \"276daf66-3868-5448-9aa4-cd146d93841b\"\nversion = \"2.0.0\"\n\n[[StableRNGs]]\ndeps = [\"Random\", \"Test\"]\ngit-tree-sha1 = \"3be7d49667040add7ee151fefaf1f8c04c8c8276\"\nuuid = \"860ef19b-820b-49d6-a774-d7a799459cd3\"\nversion = \"1.0.0\"\n\n[[Static]]\ndeps = [\"IfElse\"]\ngit-tree-sha1 = \"7f5a513baec6f122401abfc8e9c074fdac54f6c1\"\nuuid = \"aedffcd0-7271-4cad-89d0-dc628f76c6d3\"\nversion = \"0.4.1\"\n\n[[StaticArrays]]\ndeps = [\"LinearAlgebra\", \"Random\", \"Statistics\"]\ngit-tree-sha1 = \"de9e88179b584ba9cf3cc5edbb7a41f26ce42cda\"\nuuid = \"90137ffa-7385-5640-81b9-e52037218182\"\nversion = \"1.3.0\"\n\n[[StatisticalTraits]]\ndeps = [\"ScientificTypesBase\"]\ngit-tree-sha1 = \"271a7fea12d319f23d55b785c51f6876aadb9ac0\"\nuuid = \"64bff920-2084-43da-a3e6-9bb72801c0c9\"\nversion = \"3.0.0\"\n\n[[Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[StatsAPI]]\ngit-tree-sha1 = \"d88665adc9bcf45903013af0982e2fd05ae3d0a6\"\nuuid = \"82ae8749-77ed-4fe6-ae5f-f523153014b0\"\nversion = \"1.2.0\"\n\n[[StatsBase]]\ndeps = [\"DataAPI\", \"DataStructures\", \"LinearAlgebra\", \"LogExpFunctions\", \"Missings\", \"Printf\", \"Random\", \"SortingAlgorithms\", \"SparseArrays\", \"Statistics\", \"StatsAPI\"]\ngit-tree-sha1 = \"51383f2d367eb3b444c961d485c565e4c0cf4ba0\"\nuuid = \"2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91\"\nversion = \"0.33.14\"\n\n[[StatsFuns]]\ndeps = [\"ChainRulesCore\", \"InverseFunctions\", \"IrrationalConstants\", \"LogExpFunctions\", \"Reexport\", \"Rmath\", \"SpecialFunctions\"]\ngit-tree-sha1 = \"bedb3e17cc1d94ce0e6e66d3afa47157978ba404\"\nuuid = \"4c63d2b9-4356-54db-8cca-17b64c39e42c\"\nversion = \"0.9.14\"\n\n[[StructArrays]]\ndeps = [\"Adapt\", \"DataAPI\", \"StaticArrays\", \"Tables\"]\ngit-tree-sha1 = \"2ce41e0d042c60ecd131e9fb7154a3bfadbf50d3\"\nuuid = \"09ab397b-f2b6-538f-b94a-2f83cf4a842a\"\nversion = \"0.6.3\"\n\n[[SuiteSparse]]\ndeps = [\"Libdl\", \"LinearAlgebra\", \"Serialization\", \"SparseArrays\"]\nuuid = \"4607b0f0-06f3-5cda-b6b1-a6196a1729e9\"\n\n[[TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[TableTraits]]\ndeps = [\"IteratorInterfaceExtensions\"]\ngit-tree-sha1 = \"c06b2f539df1c6efa794486abfb6ed2022561a39\"\nuuid = \"3783bdb8-4a98-5b6b-af9a-565f29a5fe9c\"\nversion = \"1.0.1\"\n\n[[Tables]]\ndeps = [\"DataAPI\", \"DataValueInterfaces\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"TableTraits\", \"Test\"]\ngit-tree-sha1 = \"bb1064c9a84c52e277f1096cf41434b675cd368b\"\nuuid = \"bd369af6-aec1-5ad0-b16a-f7cc5008161c\"\nversion = \"1.6.1\"\n\n[[Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[TimerOutputs]]\ndeps = [\"ExprTools\", \"Printf\"]\ngit-tree-sha1 = \"7cb456f358e8f9d102a8b25e8dfedf58fa5689bc\"\nuuid = \"a759f4b9-e2f1-59dc-863e-4aeb61b1ea8f\"\nversion = \"0.5.13\"\n\n[[TranscodingStreams]]\ndeps = [\"Random\", \"Test\"]\ngit-tree-sha1 = \"216b95ea110b5972db65aa90f88d8d89dcb8851c\"\nuuid = \"3bb67fe8-82b1-5028-8e26-92a6c54297fa\"\nversion = \"0.9.6\"\n\n[[URIs]]\ngit-tree-sha1 = \"97bbe755a53fe859669cd907f2d96aee8d2c1355\"\nuuid = \"5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4\"\nversion = \"1.3.0\"\n\n[[UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[UnPack]]\ngit-tree-sha1 = \"387c1f73762231e86e0c9c5443ce3b4a0a9a0c2b\"\nuuid = \"3a884ed6-31ef-47d7-9d2a-63182c4928ed\"\nversion = \"1.0.2\"\n\n[[Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[UnicodePlots]]\ndeps = [\"Crayons\", \"Dates\", \"SparseArrays\", \"StatsBase\"]\ngit-tree-sha1 = \"3cb994143aba28cfe66615702505b2d294cebd3e\"\nuuid = \"b8865327-cd53-5732-bb35-84acbb429228\"\nversion = \"2.5.1\"\n\n[[UrlDownload]]\ndeps = [\"HTTP\", \"ProgressMeter\"]\ngit-tree-sha1 = \"05f86730c7a53c9da603bd506a4fc9ad0851171c\"\nuuid = \"856ac37a-3032-4c1c-9122-f86d88358c8b\"\nversion = \"1.0.0\"\n\n[[WeakRefStrings]]\ndeps = [\"DataAPI\", \"InlineStrings\", \"Parsers\"]\ngit-tree-sha1 = \"c69f9da3ff2f4f02e811c3323c22e5dfcb584cfa\"\nuuid = \"ea10d353-3f73-51f8-a26c-33c1cb351aa5\"\nversion = \"1.4.1\"\n\n[[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# ╟─83a7b4d7-6442-44b2-9388-8330b19cd537\n# ╟─24abafc3-0e26-4cd2-9bca-7c69b794f8ce\n# ╟─b67c62c2-15ab-4328-b795-033f6f2a0674\n# ╟─bc689638-fd19-4c9f-935f-ddf6a6bfbbdd\n# ╟─197fd00e-9068-46ea-af2a-25235e544a31\n# ╠═f6d4f8c4-e441-45c4-8af5-148d95ea2900\n# ╟─45740c4d-b789-45dc-a6bf-47194d7e8e12\n# ╟─42b0f1e1-16c9-4238-828a-4cc485149963\n# ╠═bbe90636-9d1f-4ee0-8e35-c285f7b922d0\n# ╟─499cbc31-83ba-4583-ba1f-6363f43ec697\n# ╟─db5821e8-956a-4a46-95ea-2955abd45275\n# ╟─1e248249-5629-412f-b1b3-dd47e367ba54\n# ╟─d055d24f-1b2d-48a6-8d7e-8e449afd1c48\n# ╟─0dc40881-6163-4948-a949-7f3bd292fe31\n# ╟─0d066909-c9bf-4ae3-8514-99938a2932db\n# ╠═29ea6531-1337-4527-92bd-6ebccf75659a\n# ╠═ad63ad4b-04c0-491b-a0de-1721c1bc2df2\n# ╠═f86b62eb-6853-482a-bca8-7eec7950fd82\n# ╟─58686fe6-088a-4751-9873-1b1430e635cc\n# ╠═8b90b209-cb98-4116-b43e-d0ebe87da176\n# ╟─f1b47e75-0ce3-4e90-9009-4cfb2012998f\n# ╟─e904fcb3-7603-40d2-abd3-cb77d7a79683\n# ╟─e93966db-0dab-42ca-879e-dc128f3db7b3\n# ╟─2564f31e-4704-4820-a367-9aa3c6cf34d0\n# ╠═7e23f8f6-1634-45c8-bf32-94657e65284e\n# ╠═348ff9a2-89ab-434a-9afd-65a5b5facac9\n# ╟─c7e83ce7-f067-4049-b6c8-54f5ed90a964\n# ╠═a6106065-1baf-4720-9292-fe822525fc77\n# ╟─703d4ac3-116e-4e05-ae5e-4b83dcbc9675\n# ╠═5d976f7e-45ee-4cbb-8a29-32f11452654a\n# ╟─aad55579-14f3-439a-a5f1-151fcbe229a2\n# ╠═a6c1d3ea-6f43-42c7-8950-2f4327f23c1f\n# ╠═9f2f583a-e90a-43f6-81bc-2d5603785a09\n# ╟─828460a7-7d4e-444e-9d87-1d1fbb0e3997\n# ╟─12631f23-8262-475d-b950-fddef2a1fb10\n# ╠═d9069be8-d8c5-43ab-951b-64cb2a36c8e3\n# ╟─4dee7ef6-b472-4b9c-b0e6-441461cc8770\n# ╟─7a6df9e6-89f1-4117-8cb0-de601961bc02\n# ╟─8ff17b93-2830-41e2-a87d-950c50fb2955\n# ╟─d45a81ec-f978-4483-8448-4bcb089096cd\n# ╠═b454845b-3b3b-4c46-a012-a84240254fb6\n# ╟─28cf44d4-3f4b-485f-bbdd-9799f7bb2e60\n# ╠═1e780939-abf0-4203-97a7-88e3af4f10ee\n# ╠═09ece795-72e1-4240-a833-1b098ab27d3f\n# ╟─8e76b5a5-7c80-4684-b372-8c9866e51852\n# ╠═5ed77309-afa6-4c94-88c0-761fe6b5a5d4\n# ╟─d45ff6ec-2dd6-4a9c-a97e-79337b0be5c8\n# ╠═4a0b7419-d9ae-4570-b9b6-029e155045c0\n# ╠═3958b3df-51cd-4920-8f28-382c4a088a8f\n# ╟─e68044d8-42b4-49cd-86cf-35420d9e6995\n# ╠═26d649a8-3d96-4479-a29a-8d0445351914\n# ╟─7f60c74e-b708-46f4-be65-28d0fcca50a8\n# ╠═c8c960f0-2a46-42c2-8754-8bd531c8db8e\n# ╠═4e327bb5-8abc-4e68-9832-d4c16415df30\n# ╠═f96a84ec-1cc0-400c-9493-9c2a2e3c5b51\n# ╟─fbb24be1-fe01-4489-b5fa-cb79ebf595ef\n# ╠═958f9a9a-23d5-446b-aa54-f7a086cb0264\n# ╠═ea64dbb5-963a-4da4-91c5-524da38aa391\n# ╟─1ce36a90-ea25-48d6-ad90-b4405b216771\n# ╟─4270976f-1207-4086-895b-997a92b731e0\n# ╠═1d0bce6b-ffff-4f30-a525-e9b04a4bd246\n# ╠═64a648e0-d5c9-4c3d-80f0-ba7781e173cf\n# ╟─5dcd0d55-bb5d-459a-9cbc-9a2c39793333\n# ╟─234c586e-862f-4216-b887-2b16710e5502\n# ╠═b8e84a2c-2c7f-41f5-9452-5298a8a4a401\n# ╟─95b75a71-47b5-49b1-b017-96f1602f2cad\n# ╟─5de9f9a0-ad8f-47de-8be2-2a4017c45345\n# ╠═aa7bdff7-7d1b-43b1-a7ad-80d84f5b0070\n# ╠═92c5bc62-b430-41b8-8378-5aa686f0b407\n# ╟─adcb0506-e89d-43b0-9f43-49763e8691a1\n# ╟─667917e3-25d2-435c-bb0e-3a45761c733a\n# ╟─f71e4957-b6aa-480f-8acf-0c1d237fe9f9\n# ╠═dc119abd-72a1-4781-811d-5998beb56406\n# ╟─0398adfe-721a-4b97-910b-f8a9a217eff2\n# ╠═85f71232-0ec4-40a8-81b7-e11a56b42313\n# ╠═d1af0582-9074-4355-9d03-7ceec3db5d7f\n# ╠═06fac83d-ec17-4503-b3b1-670e16d4251a\n# ╠═9335bbb6-7169-47a2-8ccb-85c839a68433\n# ╟─fbe0163a-ed06-49ea-8faa-017fa7aeca69\n# ╟─4fd0807d-61e5-4b4b-a1cb-54e34396a855\n# ╠═1957f387-aee4-4c08-9838-327b915082f8\n# ╠═7b59b396-daac-4dea-bc51-54fafe346cd8\n# ╠═2efdfa9c-8e70-4c09-b9f9-85c873edc16a\n# ╠═dcf51860-a300-453e-87fc-345e741f94d0\n# ╠═c54f41ee-75e6-4181-8de7-d194004c9700\n# ╠═cb026565-6c5c-4f7a-91b6-417cfea74d41\n# ╠═e073f936-f2a0-4609-83fe-bd8afb87cfc1\n# ╠═91cca9cb-db5f-4d9f-983b-3f2b20444662\n# ╟─a0488295-9642-4156-b7cc-46f4ef988c68\n# ╟─d59d9e91-b26d-4342-90fb-7f2721f6fcc7\n# ╟─c4f30527-c9b4-44e9-af65-ccd25ecb9818\n# ╟─25a6fd3c-60d1-44dd-8890-979691212d9b\n# ╟─aed2b274-cc0c-42f2-a6fa-eaf14df5d44b\n# ╠═0df6be04-24fe-4417-8025-5084804a9f6c\n# ╟─9abf25a8-7231-43f5-9e90-09023d201062\n# ╟─6cce6530-0d12-4862-af4f-11c7de9e21dd\n# ╟─135dac9b-0bd9-4e1d-8dba-241d9b744683\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "d59159be7a9a67ac535d279bbba945fe1b8d33ed", "size": 51801, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/03_pipelines/notebook.pluto.jl", "max_stars_repo_name": "roland-KA/MLJTutorial.jl", "max_stars_repo_head_hexsha": "00d2294dbe458504f7e2d200b1ed84097b9ff3e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2021-11-02T10:46:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T23:36:21.000Z", "max_issues_repo_path": "notebooks/03_pipelines/notebook.pluto.jl", "max_issues_repo_name": "roland-KA/MLJTutorial.jl", "max_issues_repo_head_hexsha": "00d2294dbe458504f7e2d200b1ed84097b9ff3e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2021-11-11T14:36:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T04:31:54.000Z", "max_forks_repo_path": "notebooks/03_pipelines/notebook.pluto.jl", "max_forks_repo_name": "roland-KA/MLJTutorial.jl", "max_forks_repo_head_hexsha": "00d2294dbe458504f7e2d200b1ed84097b9ff3e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2021-11-11T12:08:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-30T14:27:30.000Z", "avg_line_length": 32.8269961977, "max_line_length": 403, "alphanum_fraction": 0.7415880002, "num_tokens": 22818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.2018132174596823, "lm_q1q2_score": 0.0985420430367903}} {"text": "\n # Functions and methods for cascade computation\n\n\n \"\"\"\n `Cascade.computeSteps(scheme::Cascade.PhotonIonizationScheme, comp::Cascade.Computation, stepList::Array{Cascade.Step,1})` \n ... computes in turn all the requested transition amplitudes as well as PhotoIonization.Line's, etc. for all pre-specified \n (photo-) ionizing steps of the cascade. When compared with standard computations of these atomic processes, however, \n the amount of output is largely reduced and often just printed into the summary file. A set of \n data::Cascade.PhotoIonData is returned.\n \"\"\"\n function computeSteps(scheme::Cascade.PhotonIonizationScheme, comp::Cascade.Computation, stepList::Array{Cascade.Step,1})\n data = Cascade.PhotoIonData[]\n printSummary, iostream = Defaults.getDefaults(\"summary flag/stream\")\n \n # Perform computations in turn for all photon energies\n for photonEnergy in scheme.photonEnergies\n nt = 0; st = 0; linesP = PhotoIonization.Line[] \n settings = PhotoIonization.Settings(PhotoIonization.Settings(), photonEnergies=[Defaults.convertUnits(\"energy: from atomic\", photonEnergy)])\n println(\"\\n\\n* Perform ionizing computations for the photon energy $photonEnergy [a.u.]\")\n if printSummary println(iostream, \"\\n\\n* Perform ionizing computations for the photon energy $photonEnergy [a.u.]\") end \n #\n for step in stepList\n st = st + 1\n nc = length(step.initialMultiplet.levels) * length(step.finalMultiplet.levels)\n println(\"\\n $st) Perform $(string(step.process)) amplitude computations for up to $nc ionizing lines (without selection rules): \")\n if printSummary println(iostream, \"\\n* $st) Perform $(string(step.process)) amplitude computations for \" *\n \"up to $nc ionizing lines (without selection rules): \") end \n \n if step.process == Basics.Photo()\n newLines = PhotoIonization.computeLinesCascade(step.finalMultiplet, step.initialMultiplet, comp.nuclearModel, comp.grid, \n settings, output=true, printout=true) \n append!(linesP, newLines); nt = length(linesP)\n else error(\"Unsupported atomic process for cascade computations.\")\n end\n println(\" Step $st:: A total of $(length(newLines)) $(string(step.process)) lines are calculated, giving now rise \" *\n \"to a total of $nt $(string(step.process)) ionizing lines.\" )\n if printSummary println(iostream, \"\\n* Step $st:: A total of $(length(newLines)) $(string(step.process)) lines are calculated, \" *\n \"giving now rise to a total of $nt $(string(step.process)) ionizing lines.\" ) end \n end\n #\n push!(data, Cascade.PhotoIonData(photonEnergy, linesP))\n end\n \n return( data )\n end\n\n\n \"\"\"\n `Cascade.determineSteps(scheme::Cascade.PhotonIonizationScheme, comp::Cascade.Computation, \n initialList::Array{Cascade.Block,1}, ionizedList::Array{Cascade.Block,1})` \n ... determines all steps::Cascade.Step's that need to be computed for this ionizing cascade. It cycles through all processes \n of the given ionizing scheme and selects all pairs of initial and ionized blocks due to the selected photon energies and \n cascade approaches. It also checks that the (averaged) energies of the configuration support a photoionization \n energetically. A stepList::Array{Cascade.Step,1} is returned\n \"\"\"\n function determineSteps(scheme::Cascade.PhotonIonizationScheme, comp::Cascade.Computation, \n initialList::Array{Cascade.Block,1}, ionizedList::Array{Cascade.Block,1})\n stepList = Cascade.Step[]\n if comp.approach in [Cascade.AverageSCA(), Cascade.SCA()]\n for initialBlock in initialList\n for ionizedBlock in ionizedList\n for process in comp.scheme.processes\n if process == Basics.Photo() \n if initialBlock.NoElectrons == ionizedBlock.NoElectrons + 1\n settings = PhotoIonization.Settings() ##x settings, photonEnergies=[1.0], printBefore=false)\n push!( stepList, Cascade.Step(process, settings, initialBlock.confs, ionizedBlock.confs, \n initialBlock.multiplet, ionizedBlock.multiplet) )\n end\n else error(\"stop a\")\n end\n end\n end\n end\n #\n else error(\"Unsupported cascade approach.\")\n end\n return( stepList )\n end\n\n\n \"\"\"\n `Cascade.generateConfigurationsForPhotoionization(multiplets::Array{Multiplet,1}, maxPhotoElectrons::Int64, \n maxPhotonEnergy::Float64, nm::Nuclear.Model)` \n ... generates all possible (photoionized) configurations with upto maxPhotoElectrons less electrons and whose averaged energy\n is NOT higher than maxPhotoEnergy above of the given configuration. In the present version, no shake contributions are taken\n into account. A Tuple(initialConfList::Array{Configuration,1}, confList::Array{Configuration,1}) is returned.\n \"\"\"\n function generateConfigurationsForPhotoionization(multiplets::Array{Multiplet,1}, maxPhotoElectrons::Int64, maxPhotonEnergy::Float64, \n nm::Nuclear.Model)\n # Determine all (different) configurations from multiplets\n newconfList = Configuration[]\n for mp in multiplets \n confList = Basics.extractNonrelativisticConfigurations(mp.levels[1].basis)\n for conf in confList if conf in newconfList nothing else push!(newconfList, conf) end end\n end\n en = Float64[]; for conf in confList push!(en, -Semiempirical.estimate(\"binding energy\", round(Int64, nm.Z), conf)) end\n maxen = maximum(en)\n shList = Basics.generate(\"shells: ordered list for NR configurations\", newconfList)\n \n # Collect all configuration with up to maxPhotoElectrons less electrons\n initialConfList = deepcopy(newconfList); \n allnewconfList = Configuration[]; confList = deepcopy(newconfList); newconfList = Configuration[]\n for ne = 1:maxPhotoElectrons\n for sh in shList\n for conf in confList\n shells = deepcopy(conf.shells); \n if shells[sh] > 0 shells[sh] = shells[sh] - 1; push!(newconfList, Configuration(shells, conf.NoElectrons - 1)) end\n end\n end\n append!(allnewconfList, newconfList)\n confList = deepcopy(newconfList); newconfList = Configuration[]\n end\n \n # Exclude double configurations as well as those with too high average energy\n ##x confList = Basics.excludeDoubles(allnewconfList)\n confList = unique(allnewconfList)\n newconfList = Configuration[]\n for conf in confList \n enconf = -Semiempirical.estimate(\"binding energy\", round(Int64, nm.Z), conf)\n if enconf - maxen < maxPhotonEnergy push!(newconfList, conf) end\n end\n\n return( (initialConfList, newconfList) )\n end\n\n\n \"\"\"\n `Cascade.perform(scheme::PhotonIonizationScheme, comp::Cascade.Computation)` \n ... to set-up and perform a cascade computation that starts from a given set of initial configurations xor initial multiplets\n and proceeds via photoionizing processes to configurations with a given No of photoelectrons. The results of all individual \n photoionization steps are comprised into (output) data::PhotoIonData, although all data are only printed and nothing \n is returned.\n\n `Cascade.perform(scheme::PhotonIonizationScheme, comp::Cascade.Computation; output=true, outputToFile::Bool=true)` \n ... to perform the same but to return the complete output in a dictionary that is written to disk and can be used in subsequent\n cascade simulation. The particular output also depends on the specifications of the cascade.\n \"\"\"\n function perform(scheme::PhotonIonizationScheme, comp::Cascade.Computation; output::Bool=false, outputToFile::Bool=true)\n if output results = Dict{String, Any}() else results = nothing end\n printSummary, iostream = Defaults.getDefaults(\"summary flag/stream\")\n #\n # Perform the SCF and CI computation for the intial-state multiplets if initial configurations are given\n if comp.initialConfigs != Configuration[]\n basis = Basics.performSCF(comp.initialConfigs, comp.nuclearModel, comp.grid, comp.asfSettings; printout=false)\n multiplet = Basics.performCI(basis, comp.nuclearModel, comp.grid, comp.asfSettings; printout=false)\n multiplets = [Multiplet(\"initial states\", multiplet.levels)]\n else\n multiplets = comp.initialMultiplets\n end\n # Print out initial configurations and levels \n Cascade.displayLevels(stdout, multiplets, sa=\"initial \")\n if printSummary Cascade.displayLevels(iostream, multiplets, sa=\"initial \") end\n #\n # Generate subsequent cascade configurations as well as display and group them together\n maxen = maximum(comp.scheme.photonEnergies) + 20\n wa = Cascade.generateConfigurationsForPhotoionization(multiplets, comp.scheme.maxPhotoElectrons, maxen, comp.nuclearModel)\n wb1 = Cascade.groupDisplayConfigurationList(comp.nuclearModel.Z, wa[1], sa=\"(initial part of the) ionizing \")\n wb2 = Cascade.groupDisplayConfigurationList(comp.nuclearModel.Z, wa[2], sa=\"(generated part of the) ionizing \")\n #\n # Determine first all configuration 'blocks' and from them the individual steps of the cascade\n wc1 = Cascade.generateBlocks(comp, wb1, basis.orbitals, sa=\"for the ionizing cascade \")\n wc2 = Cascade.generateBlocks(comp, wb2, basis.orbitals, sa=\"for the ionizing cascade \", printout=false)\n Cascade.displayBlocks(stdout, wc1, sa=\"for the (initial part of the) ionizing cascade \"); \n Cascade.displayBlocks(stdout, wc2, sa=\"for the (generated part of the) ionizing cascade \")\n if printSummary Cascade.displayBlocks(iostream, wc1, sa=\"for the (initial part of the) ionizing cascade \")\n Cascade.displayBlocks(iostream, wc2, sa=\"for the (generated part of the) ionizing cascade \") end \n # Determine, modify and compute the transition data for all steps, ie. the PhotoIonization.Line's, etc.\n gMultiplets = Multiplet[]; for block in wc2 push!(gMultiplets, block.multiplet) end\n we = Cascade.determineSteps(scheme, comp, wc1, wc2)\n Cascade.displaySteps(stdout, we, sa=\"ionizing \")\n if printSummary Cascade.displaySteps(iostream, we, sa=\"ionizing \") end \n wf = Cascade.modifySteps(we)\n data = Cascade.computeSteps(scheme, comp, wf)\n if output \n results = Base.merge( results, Dict(\"name\" => comp.name) ) \n results = Base.merge( results, Dict(\"cascade scheme\" => comp.scheme) ) \n results = Base.merge( results, Dict(\"initial multiplets:\" => multiplets) ) \n results = Base.merge( results, Dict(\"generated multiplets:\" => gMultiplets) ) \n results = Base.merge( results, Dict(\"photo-ionizing line data:\" => data) )\n #\n # Write out the result to file to later continue with simulations on the cascade data\n filename = \"zzz-cascade-ionizing-computations-\" * string(Dates.now())[1:13] * \".jld\"\n println(\"\\n* Write all results to disk; use:\\n JLD.save(''$filename'', results) \\n using JLD \" *\n \"\\n results = JLD.load(''$filename'') ... to load the results back from file.\")\n if printSummary println(iostream, \"\\n* Write all results to disk; use:\\n JLD.save(''$filename'', results) \\n using JLD \" *\n \"\\n results = JLD.load(''$filename'') ... to load the results back from file.\" ) end \n JLD2.@save filename results\n end\n ## return( results )\n return( results )\n end\n", "meta": {"hexsha": "ea8e49837c5b7ca0d98763770f52939492428a19", "size": 12982, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/module-Cascade-inc-photoionization.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-Cascade-inc-photoionization.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-Cascade-inc-photoionization.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": 67.2642487047, "max_line_length": 152, "alphanum_fraction": 0.6188568788, "num_tokens": 2805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.17781086512112404, "lm_q1q2_score": 0.09583707275624684}} {"text": "import Flatten: flattenable\n@metadata initial_value nothing\nimport FieldMetadata: @units, units\nimport FieldMetadata: @limits, limits\nimport FieldMetadata: @prior, prior\nimport FieldMetadata: @description, description\n@metadata bounds nothing\nimport FieldMetadata: @logscaled, logscaled\n@metadata reference nothing\n\n\n\"\"\"\n AbstractParameters{T} <: AbstractVector{T}\n\nAn abstract type for AIBECS model parameters.\n\nParameters in AIBECS use the following convenience packages:\n\n- Parameters\n- FieldMetadata\n- FieldDefaults\n- Flatten\n- Unitful\n- DataFrames\n- Distributions\n\nThese aim to allow for some nice features, which include\n\n- nice syntax for unpacking parameters in functions via the `@unpack` macro (fron UnPack.jl)\n- additional metadata on parameters\n- easy conversion to and from vectors\n- use of units and automatic conversions if necessary\n- pretty table-format displays\n- loading and saving to and from CSV files\n- prior estimates for bayesian inference and optimization\n\nSee the list of examples to get an idea of how to generate parameters for your model.\n\n# Examples\n\nGenerate a simple parameter type via\n\n```jldoctest\njulia> struct SimpleParams{T} <: AbstractParameters{T}\n α::T\n β::T\n γ::T\n end\nSimpleParams\n```\n\nTo create an instance of the `SimpleParams(Float64)` type, you can do\n\n```jldoctest\njulia> p = SimpleParams(1.0, 2.0, 3.0)\nSimpleParams{Float64}\n│ Row │ Symbol │ Value │\n│ │ Symbol │ Float64 │\n├─────┼────────┼─────────┤\n│ 1 │ α │ 1.0 │\n│ 2 │ β │ 2.0 │\n│ 3 │ γ │ 3.0 │\n```\n\nOne of the core features from Parameters is unpacking in functions, e.g.,\n\n```jldoctest\njulia> function simplef(p)\n @unpack α, γ = p\n return α + γ\n end\nsimplef (generic function with 1 method)\n\njulia> simplef(p) # 1.0 + 3.0\n4.0\n```\n\nMore complex examples are permitted by adding metadata (thanks to FieldMetadata.jl).\nYou can add units\n\n```jldoctest\njulia> @units struct UnitParams{T} <: AbstractParameters{T}\n α::T | u\"km\"\n β::T | u\"hr\"\n γ::T | u\"m/s\"\n end ;\n\njulia> p = UnitParams(1.0, 2.0, 3.0)\nUnitParams{Float64}\n│ Row │ Symbol │ Value │ Unit │\n│ │ Symbol │ Float64 │ Unitful… │\n├─────┼────────┼─────────┼──────────┤\n│ 1 │ α │ 1.0 │ km │\n│ 2 │ β │ 2.0 │ hr │\n│ 3 │ γ │ 3.0 │ m s^-1 │\n```\n\nNote that when adding units to your parameters, they will be converted to SI\nwhen unpacked, as in, e.g.,\n\n```jldoctest\njulia> function speed(p)\n @unpack α, β, γ = p\n return α / β + γ\n end\nspeed (generic function with 1 method)\n\njulia> speed(p) # (1.0 km / 2.0 hr + 3 m/s) in m/s\n3.138888888888889\n```\n\nAnother example for optimizable/flattenable parameters\n\n```jldoctest\njulia> @initial_value @units @flattenable struct OptParams{T} <: AbstractParameters{T}\n α::T | 3.6 | u\"km\" | true\n β::T | 1.0 | u\"hr\" | false\n γ::T | 1.0 | u\"m/s\" | true\n end ;\n\njulia> p = OptParams(initial_value(OptParams)...)\nOptParams{Float64}\n│ Row │ Symbol │ Value │ Initial value │ Unit │ Optimizable │\n│ │ Symbol │ Float64 │ Float64 │ Unitful… │ Bool │\n├─────┼────────┼─────────┼───────────────┼──────────┼─────────────┤\n│ 1 │ α │ 3.6 │ 3.6 │ km │ 1 │\n│ 2 │ β │ 1.0 │ 1.0 │ hr │ 0 │\n│ 3 │ γ │ 1.0 │ 1.0 │ m s^-1 │ 1 │\n```\n\nThanks to the FieldMetaData interface, you can chain the following preloaded metadata:\n\n- initial_value\n- units (from Unitful.jl)\n- prior (from Distributions.jl)\n- description (`String`)\n- bounds (2-element `Tuple`)\n- logscaled (`Bool`)\n- flattenable (to convert to vectors of optimizable parameters only)\n- reference (`String`)\n\nHere is an example of parameter with all the possible metadata available in AIBECS:\n\n```jldoctest\njulia> @initial_value @units @prior @description @bounds @logscaled @flattenable @reference struct FullParams{T} <: AbstractParameters{T}\n α::T | 1.0 | u\"km\" | Normal(0,1) | \"The distance\" | (-Inf, Inf) | false | false | \"Jean et al., 2042\"\n β::T | 2.0 | u\"hr\" | LogNormal(0,1) | \"The time\" | ( 0, Inf) | true | true | \"Claude et al. 1983\"\n γ::T | 3.0 | u\"mol\" | Normal(1,2) | \"The # of moles\" | ( -1, 1) | false | true | \"Dusse et al. 2000\"\n end ;\n\njulia> FullParams(4.0, 5.0, 6.0)\nFullParams{Float64}\n│ Row │ Symbol │ Value │ Initial value │ Unit │ Prior │ Description │ Bounds │ Logscaled │ Optimizable │ Reference │\n│ │ Symbol │ Float64 │ Float64 │ Unitful… │ Distribu… │ String │ Tuple… │ Bool │ Bool │ String │\n├─────┼────────┼─────────┼───────────────┼──────────┼──────────────────────────────────┼────────────────┼─────────────┼───────────┼─────────────┼────────────────────┤\n│ 1 │ α │ 4.0 │ 1.0 │ km │ Normal{Float64}(μ=0.0, σ=1.0) │ The distance │ (-Inf, Inf) │ 0 │ 0 │ Jean et al., 2042 │\n│ 2 │ β │ 5.0 │ 2.0 │ hr │ LogNormal{Float64}(μ=0.0, σ=1.0) │ The time │ (0, Inf) │ 1 │ 1 │ Claude et al. 1983 │\n│ 3 │ γ │ 6.0 │ 3.0 │ mol │ Normal{Float64}(μ=1.0, σ=2.0) │ The # of moles │ (-1, 1) │ 0 │ 1 │ Dusse et al. 2000 │\n```\n\nNote that there is no check that the metadata you give is consistent.\nThese metadata will hopefully be useful for advanced usage of AIBECS, e.g., using prior information and/or bounds for optimization.\n\"\"\"\nabstract type AbstractParameters{T} <: AbstractVector{T} end\n\n\"\"\"\n symbols(p)\n\nReturns the symbols in `p`.\n\nCan also be used directly on the type of `p`\n(because the symbols of `p::T` are contained in the type `T`).\n\"\"\"\nsymbols(::Type{T}) where {T <: AbstractParameters} = fieldnames(T)\nsymbols(::T) where {T <: AbstractParameters} = symbols(T)\n\n\"\"\"\n flattenable_symbols(p)\n\nReturns the flattenable symbols in `p`.\n\nThe flattenable symbols are those symbols that are kepth when using `p` as a vector,\ne.g., when doing `vec(p)`.\n(Useful when passing parameters to an optimization routine expeting a vector of optimizable parameters.)\n\nCan also be used directly on the type of `p`\n(because the flattenable symbols of `p::T` are contained in the type `T`).\n\"\"\"\nflattenable_symbols(::T) where {T <: AbstractParameters} = flattenable_symbols(T)\nflattenable_symbols(::Type{T}) where {T <: AbstractParameters} = fieldnames(T)[collect(flattenable(T))]\n\n\"\"\"\n values(p::T) where {T <: AbstractParameters}\n\nReturns a vector of **all** the values of `p`.\n\nNote that `values(p)` is different from `vec(p)`.\n\"\"\"\nBase.values(p::T) where {T <: AbstractParameters} = [getfield(p, s) for s in symbols(T)]\n\n\"\"\"\n flattenable_values(p::T) where {T <: AbstractParameters}\n\nReturns a vector of the **flattenable** values of `p`.\n\nNote that `vec(p)` is different from `values(p)`.\n\"\"\"\nflattenable_values(p::T) where {T <: AbstractParameters} = [getfield(p, s) for s in flattenable_symbols(T)]\n\n\"\"\"\n vec(p::T) where {T <: AbstractParameters}\n\nReturns a **SI-unit-converted** vector of flattenable values of `p`.\n\nNote that `vec(p) ≠ flattenable_values(p)` if `p` has units.\n\"\"\"\nBase.vec(p::T) where {T <: AbstractParameters} = [UnPack.unpack(p, Val(s)) for s in flattenable_symbols(T)]\n\n\n\"\"\"\n length(p::AbstractParameter)\n\nReturns the length of the **flattened/optimzable** vector of `p`.\n\nMay be different from the number of parameters.\nCan also be used directly on the type of `p`.\n\"\"\"\nBase.length(::T) where {T <: AbstractParameters} = sum(flattenable(T))\nBase.length(::Type{T}) where {T <: AbstractParameters} = sum(flattenable(T))\n\n\"\"\"\n size(p::AbstractParameter)\n\nReturns the size of the **flattened/optimzable** vector of `p`.\n\nMay be different from the number of parameters.\nCan also be used directly on the type of `p`.\n\"\"\"\nBase.size(::T) where {T <: AbstractParameters} = (length(T),)\nBase.size(::Type{T}) where {T <: AbstractParameters} = (length(T),)\n\nfunction Base.show(io::IO, p::T) where T <: AbstractParameters\n print(T)\n t = table(p)\n show(io, t; summary=false)\nend\nfunction Base.show(io::IO, m::MIME\"text/plain\", p::T) where T <: AbstractParameters\n print(T)\n t = table(p)\n show(io, m, t; summary=false)\nend\n\nfunction table(p::T, nf::NamedTuple) where {T <: AbstractParameters}\n t = DataFrame(Symbol = collect(symbols(p)), Value = values(p))\n for (n,f) in zip(keys(nf), nf)\n setproperty!(t, n, collect(f(p)))\n end\n return t\nend\n\n\"\"\"\n table(p)\n\nReturns a `DataFrame` (a table) of `p`.\nUseful for printing and saving into an actual text/latex table.\n\"\"\"\nfunction table(p::AbstractParameters)\n ks, vs = Symbol[], Function[]\n all(isnothing, initial_value(p)) || (push!(ks, Symbol(\"Initial value\")); push!(vs, initial_value))\n all(isequal(1), units(p)) || (push!(ks, :Unit); push!(vs, units))\n all(isnothing, prior(p)) || (push!(ks, Symbol(\"Prior\")); push!(vs, prior))\n all(isempty, description(p)) || (push!(ks, Symbol(\"Description\")); push!(vs, description))\n all(isnothing, bounds(p)) || (push!(ks, Symbol(\"Bounds\")); push!(vs, bounds))\n any(logscaled(p)) && (push!(ks, Symbol(\"Logscaled\")); push!(vs, logscaled))\n all(flattenable(p)) || (push!(ks, Symbol(\"Optimizable\")); push!(vs, flattenable))\n all(isnothing, reference(p)) || (push!(ks, Symbol(\"Reference\")); push!(vs, reference))\n nf = (; zip(ks, vs)...)\n t = table(p, nf)\nend\n\n\n\"\"\"\n latex(p)\n\nReturns a LaTeX-formatted table of the parameters.\n\"\"\"\nlatex(p::AbstractParameters) = show(stdout, MIME(\"text/latex\"), table(p))\n\n\"\"\"\n unpack(p <: AbstractParameters, s)\n\nUnpacks the parameter `s` from `p`.\n\nNote this is specialized and will convert the parameter value to SI units.\n\"\"\"\n@inline UnPack.unpack(p::T, ::Val{f}) where {T<:AbstractParameters,f} = ustrip(upreferred(getproperty(p, f) * units(T, f)))\n\n\"\"\"\n +(p::T, v::Vector) where {T <: AbstractParameters}\n\nAdds the flattened vector `v` to `p`.\n\n**Warning:** This method for `+` is implemented only for differentiation\nusing dual and hyperdual numbers.\nIf you want to change the values of `p`, you should do so explicitly\nrather than use this `+` method.\n\"\"\"\nBase.:+(p::T, v::Vector) where {T <: AbstractParameters} = reconstruct(T, vec(p) + v)\n\n\"\"\"\n reconstruct(T, v)\n\nReconstructs the parameter of type `T` from flattenable vector `v`.\n\"\"\"\nfunction reconstruct(::Type{T}, v::Tv) where {T <: AbstractParameters, Tv <: Vector}\n all(isnothing, initial_value(T)) && error(\"Can't reconstruct without initial values\")\n vunits = units(T)[[flattenable(T)...]]\n v = @. v * upreferred(vunits) |> vunits |> ustrip\n reconstructed_v = convert(Tv, collect(initial_value(T)))\n reconstructed_v[collect(flattenable(T))] .= v\n return T.name.wrapper(reconstructed_v...)\nend\n\n\"\"\"\n getindex(p::T, i) where {T <: AbstractParameters}\n\nReturns the i-th element of vec(p).\n\nThis is not efficient and only used for testing the derivatives with ForwardDiff.\n\"\"\"\nBase.getindex(p::T, i) where {T <: AbstractParameters} = getindex(vec(p), i)\n\n\nfunction (::Type{T})(args::Quantity...) where {T <: AbstractParameters}\n all(isequal(1), units(T)) && error(\"$T needs `units` for this construction to work\")\n return T([ustrip(x |> units(T, f)) for (x,f) in zip(args, fieldnames(T))]...)\nend\n\nfunction (::Type{T})(;kwargs...) where {T <: AbstractParameters}\n all(isnothing, initial_value(T)) && length(kwargs) ≠ length(symbols(T)) && error(\"$T needs `initial_value` if one of the parameters is not supplied\")\n value(f::Symbol, v::Quantity) = ustrip(v |> units(T, f))\n value(f::Symbol, v) = v\n return T([f ∈ keys(kwargs) ? value(f, kwargs[f]) : initial_value(T, f) for f in fieldnames(T)]...)\nend\n\n#===============================\nWriting to savable formats\n===============================#\n\nfunction Base.Dict(p::T, s=symbols(p)) where {T<:AbstractParameters}\n v = [getfield(p,s) for s in s]\n u = [units(p,s) for s in s]\n return Dict([(s,v*u) for (s,v,u) in zip(s,v,u)])\nend\nfunction Base.NamedTuple(p::T, s=symbols(p)) where {T<:AbstractParameters}\n v = [getfield(p,s) for s in s]\n u = [units(p,s) for s in s]\n return (; zip(s, v .* u)...)\nend\n\n#=====================\nmismatch of parameters\n=====================#\n\"\"\"\n mismatch(p::AbstractParameters)\n\nReturns the sum of the negative log-likelihood of each flattenable parameter.\n\"\"\"\nfunction mismatch(p::AbstractParameters)\n return sum(-logpdf(prior(p,k), UnPack.unpack(p,Val(k))) for k in flattenable_symbols(p))\nend\nfunction ∇mismatch(p::AbstractParameters)\n return transpose([-gradlogpdf(prior(p,k), UnPack.unpack(p,Val(k))) for k in flattenable_symbols(p)])\nend\n\n# The functions below is just for ForwardDiff to work with vectors instead of p\n# which requires `mismatch` to know about the priors, which are containted in `T`\nfunction generate_objective(ωs, μx, σ²x, v, ωp, ::Type{T}) where {T<:AbstractParameters}\n nt, nb = length(ωs), length(v)\n tracers(x) = state_to_tracers(x, nb, nt)\n f(x, p) = ωp * mismatch(T, p) +\n sum([ωⱼ * mismatch(xⱼ, μⱼ, σⱼ², v) for (ωⱼ, xⱼ, μⱼ, σⱼ²) in zip(ωs, tracers(x), μx, σ²x)])\n return f\nend\nfunction mismatch(::Type{T}, v) where {T<:AbstractParameters}\n return sum(-logpdf(prior(T,k), v[i]) for (i,k) in enumerate(flattenable_symbols(T)))\nend\n\n#==================\nChange of variables\n==================#\n\"\"\"\n subfun\n\nReturns the substitution function for the change of variables of parameters.\n\nIf the prior of parameter `pᵢ` is `LogNormal`, then the substitution function is `exp`.\nIf the prior is `Uniform`, then the change of variables is the logit function.\nOtherwise, it's `identity`.\n\"\"\"\nfunction subfun(::Type{T}) where {T<:AbstractParameters}\n return λ -> reconstruct(T, [subfun(T, s)(λᵢ) for (λᵢ,s) in zip(λ, flattenable_symbols(T))])\nend\nfunction ∇subfun(::Type{T}) where {T<:AbstractParameters}\n return λ -> reconstruct(T, [∇subfun(T, s)(λᵢ) for (λᵢ,s) in zip(λ, flattenable_symbols(T))])\nend\nfunction ∇²subfun(::Type{T}) where {T<:AbstractParameters}\n return λ -> reconstruct(T, [∇²subfun(T, s)(λᵢ) for (λᵢ,s) in zip(λ, flattenable_symbols(T))])\nend\nfunction invsubfun(::Type{T}) where {T<:AbstractParameters}\n return p -> [invsubfun(T, s)(pᵢ) for (pᵢ,s) in zip(vec(p), flattenable_symbols(T))]\nend\n# substitution function (change of variables) is determined from prior distribution\nsubfun(::Type{T}, s::Symbol) where {T<:AbstractParameters} = subfun(prior(T,s))\n∇subfun(::Type{T}, s::Symbol) where {T<:AbstractParameters} = ∇subfun(prior(T,s))\n∇²subfun(::Type{T}, s::Symbol) where {T<:AbstractParameters} = ∇²subfun(prior(T,s))\ninvsubfun(::Type{T}, s::Symbol) where {T<:AbstractParameters} = invsubfun(prior(T,s))\n# Fallback rule for change of variables is identity\nsubfun(::Distribution) = identity\n∇subfun(::Distribution) = x -> one(x)\n∇²subfun(::Distribution) = x -> zero(x)\ninvsubfun(::Distribution) = identity\n# p = exp(λ) for LogNormal\nsubfun(::LogNormal) = exp\n∇subfun(::LogNormal) = exp\n∇²subfun(::LogNormal) = exp\ninvsubfun(::LogNormal) = log\n# p = logistic(λ) for Uniform\nsubfun(d::Uniform) = λ -> d.a + (d.b - d.a) / (exp(-λ) + 1)\n∇subfun(d::Uniform) = λ -> (d.b - d.a) * exp(-λ) / (exp(-λ) + 1)^2\n∇²subfun(d::Uniform) = λ -> (d.a - d.b) * exp(-λ) / (exp(-λ) + 1)^2 + 2(d.b - d.a) * exp(-2λ) / (exp(-λ) + 1)^3\ninvsubfun(d::Uniform) = p -> -log((d.b - d.a) / (p - d.a) - 1)\n\nexport subfun, ∇subfun, ∇²subfun, invsubfun\n\n\nexport AbstractParameters, latex\n\n", "meta": {"hexsha": "481fac812d70b9460d04e9336910f15128cc0216", "size": 15637, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Parameters.jl", "max_stars_repo_name": "seamanticscience/AIBECS.jl", "max_stars_repo_head_hexsha": "ff64544aa637a7324f513be697897384efbec4e6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Parameters.jl", "max_issues_repo_name": "seamanticscience/AIBECS.jl", "max_issues_repo_head_hexsha": "ff64544aa637a7324f513be697897384efbec4e6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Parameters.jl", "max_forks_repo_name": "seamanticscience/AIBECS.jl", "max_forks_repo_head_hexsha": "ff64544aa637a7324f513be697897384efbec4e6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6195899772, "max_line_length": 166, "alphanum_fraction": 0.6213468057, "num_tokens": 4680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.18713268669577832, "lm_q1q2_score": 0.09356634334788916}} {"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# # 0105 Custom Types\n\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 however be lost)\n## Pkg.resolve() \n## Pkg.instantiate() # run this if you didn't in Segment 01.01\nusing Random\nRandom.seed!(123)\nusing InteractiveUtils # loaded automatically when working... interactively\n\n# ## \"Type\" of types\n\n# In Julia primitive, composite and abstract types can all be defined by the user\n\nprimitive type APrimitiveType 819200 end # name and size in bit - multiple of 8 and below 8388608 (1MB)\nprimitive type APrimitiveType2 819200 end\n819200/(8*1024)\nstruct ACompositeType end # fields, constructors.. we'll see this later in details\nabstract type AnAbstractType end # no objects, no instantialisation of objects\n\n\n# ## Composite types\nmutable struct Foo # starting with a capital letter\n field1\n field2::String\n field3::ACompositeType\nend\n\n# mutable struct Foo # error! can't change a struct after I defined it\n# end\n\nfieldnames(Foo)\n\no = Foo(123,\"aaa\",ACompositeType()) # call the default constructor (available automatically) - order matters!\ntypeof(o)\n\n\n# Outer constructor\nfunction Foo(f2,f3=ACompositeType()) # \"normal\" functions just happens it has the name of the object to create\n if startswith(f2,\"Booo\") # put whatever logic you wish\n return nothing\n end\n return Foo(123,f2,f3) # call the default constructor\nend\n\no = Foo(123,\"aaa\", ACompositeType()) # call the default constructor\no = Foo(\"blaaaaa\") # call the outer constructor we defined\n\no.field1 # access fields\no.field1 = 321 # modify field (because type defined as \"mutable\" !!!)\no\n\n\nfunction Base.show(io::IO, x::Foo) # function(o) rather than o.function() \n println(io,\"My custom representation for Foo objects\")\n println(io,\"Field1: $(o.field1)\")\n println(io,\"Field2: $(o.field2)\")\nend\no\n\n# Inner constructor\nmutable struct Foo2\n field1::Int64\n field2::String\n function Foo2(f1,f2,f3)\n ## ... logic\n return new(f1+f2,f3)\n end\nend\nFoo2(1,2,\"aaa\")\n\n# !!! tip\n# If any inner constructor method is defined, no default constructor method is provided.\n\n## Foo2(1,\"aaa\") # Error, no default constructor !\n\n# ## Parametric types\n\nstruct Point{T<:Number} # T must be a child of type \"Number\"\n x::T\n y::T\nend\n\no = Point(1,2)\nPoint(1.0,2.)\n## Point(1,2.0) # error !\n\nfunction Point(x::T, y::T=zero(T)) where {T}\n return Point(x,y)\nend\nPoint(2)\nPoint(1.5)\n\nabstract type Figure{T<:Number} end\n\na = Array{Int64,2}(undef,2,2) # Array is nothing else than a parametric type with 2 parameters\ntypeof(a)\neltype(a)\n\n# As we see for arrays, parameters doesn't need to be _types_, but can be any value of a bits type (in practice an integer value) :\n\nstruct MyType{T,N}\n data::Array{T,N}\nend\n\nintMatrixInside = MyType([1 2 3; 4 5 6])\nfloatVectorInside = MyType([1 2 3])\n\nfunction getPlane(o::MyType{T,N},dim,pos) where {T,N}\nsizes = size(o.data)\nif length(sizes) > N\n error(\"Dim over the dimensions of the data\")\nelseif sizes[dim] < pos\n error(\"Non enought elements in dimension $dim to cut at $pos\")\nend\nreturn selectdim(o.data,dim,pos)\nend\n\ngetPlane(intMatrixInside,1,2)\n\n# A package where non-type parameters are emploied to boost speed is [StaticArray.jl](https://github.com/JuliaArrays/StaticArrays.jl) where one parameter is the _size_ of the array that hence become known at compile time\n\n\n# ## Inheritance\n\nabstract type MyOwnGenericAbstractType end # the highest-level\nabstract type MyOwnAbstractType1 <: MyOwnGenericAbstractType end # child of MyOwnGenericAbstractType \nabstract type MyOwnAbstractType2 <: MyOwnGenericAbstractType end # also child of MyOwnGenericAbstractType\nmutable struct AConcreteTypeA <: MyOwnAbstractType1\n f1::Int64\n f2::Int64\nend\nmutable struct AConcreteTypeB <: MyOwnAbstractType1\n f1::Float64\nend\nmutable struct AConcreteTypeZ <: MyOwnAbstractType2\n f1::String\nend\noA = AConcreteTypeA(2,10)\noB = AConcreteTypeB(1.5)\noZ = AConcreteTypeZ(\"aa\")\n\nsupertype(AConcreteTypeA)\nsubtypes(MyOwnAbstractType1)\n\n\n# !!! tip\n# When multiple methods are available for an object, function calls are dispatched to the most stricter method, i.e. the one defined over the exact parameter's type or their immediate parents\n\nfunction foo(a :: MyOwnGenericAbstractType) # good for everyone \n println(\"Default implementation: $(a.f1)\")\nend\nfoo(oA) # Default implementation: 2\nfoo(oB) # Default implementation: 1.5\nfoo(oZ) # Default implementation: aa\nfunction foo(a :: MyOwnAbstractType1) # specialisation for MyOwnAbstractType1\n println(\"A more specialised implementation: $(a.f1*4)\")\nend\nfoo(oA) # A more specialised implementation: 8\nfoo(oB) # A more specialised implementation: 6.0\nfoo(oZ) # Default implementation: aa # doesn't match the specialisation, default to foo(a :: MyOwnGenericAbstractType)\nfunction foo(a :: AConcreteTypeA)\n println(\"A even more specialised implementation: $(a.f1 + a.f2)\")\nend\nfoo(oA) # A even more specialised implementation: 12\nfoo(oB) # A more specialised implementation: 6.0\nfoo(oZ) # Default implementation: aa\n\n# !!! warning \n# Attention to the inheritance for parametric types. If it is true that `Vector{Int64} <: AbstractVector{Int64}` and `Int64 <: Number`, it is FALSE that `AbstractVector{Int64} <: AbstractVector{Number}`. If you want to allow a function parameter to be a vector of numbers, use instead templates explicitly, e.g. `foo(x::AbstractVector{T}) where {T<:Number} = return sum(x)`\n\nVector{Int64} <: AbstractVector{Int64}\nInt64 <: Number\nVector{Int64} <: Vector{Number}\nAbstractVector{Int64} <: AbstractVector{Number}\n\n\n# ## Object-oriented model\n\n# OO model based on _composition_ \n\nstruct Shoes\n shoesType::String\n colour::String\nend\nstruct Person\n myname::String\n age::Int64\nend\nstruct Student\n p::Person # by referencing a `Person`` object, we do not need to repeat its fields\n school::String\n shoes::Shoes # same for `shoes`\nend\nstruct Employee\n p::Person\n monthlyIncomes::Float64\n company::String\n shoes::Shoes\nend\ngymShoes = Shoes(\"gym\",\"white\")\nproShoes = Shoes(\"classical\",\"brown\")\nMarc = Student(Person(\"Marc\",15),\"Divine School\",gymShoes)\nMrBrown = Employee(Person(\"Brown\",45),3200.0,\"ABC Corporation Inc.\", proShoes)\n\nfunction printMyActivity(self::Student)\n println(\"Hi! I am $(self.p.myname), I study at $(self.school) school, and I wear $(self.shoes.colour) shoes\") # I can use the dot operator chained...\nend\nfunction printMyActivity(self::Employee)\n println(\"Good day. My name is $(self.p.myname), I work at $(self.company) company and I wear $(self.shoes.colour) shoes\")\nend\n\nprintMyActivity(Marc) # Hi! I am Marc, ...\nprintMyActivity(MrBrown) # Good day. My name is MrBrown, ...\n\n# OO models based on Specialisation (Person → Student) or Weack Relation (Person → Shoes) instead of Composition (Person → Arm) can be implemented using third party packages, like e.g. [SimpleTraits.jl](https://github.com/mauro3/SimpleTraits.jl) or [OOPMacro.jl](https://github.com/ipod825/OOPMacro.jl)\n", "meta": {"hexsha": "747b1b34f5c65b272b430a69702a7e19bf8bc3ab", "size": 7968, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lessonsSources/01_-_JULIA1_-_Basic_Julia_programming/0105_-_Custom_types.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/01_-_JULIA1_-_Basic_Julia_programming/0105_-_Custom_types.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/01_-_JULIA1_-_Basic_Julia_programming/0105_-_Custom_types.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": 34.4935064935, "max_line_length": 377, "alphanum_fraction": 0.6848644578, "num_tokens": 2066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33807711081162, "lm_q2_score": 0.2720245510940225, "lm_q1q2_score": 0.09196527430369504}} {"text": "## Exercise 6-6\n## A palindrome is a word that is spelled the same backward and forward, like “noon” and “redivider”. Recursively, a word is a palindrome if the first and last letters are the same and the middle is a palindrome.\n\n## The following are functions that take a string argument and return the first, last, and middle letters:\n\nfunction first(word)\n first = firstindex(word)\n word[first]\nend\n\nfunction last(word)\n last = lastindex(word)\n word[last]\nend\n\nfunction middle(word)\n first = firstindex(word)\n last = lastindex(word)\n word[nextind(word, first) : prevind(word, last)]\nend\n\n## We’ll see how they work in Strings\n\n## 1. Test these functions out. What happens if you call middle with a string with two letters? One letter? What about the empty string, which is written \"\" and contains no letters?\nprintln(\"Ans 1: \")\n\nprintln(first(\"first\")) # returns 'f'\nprintln(last(\"last\")) # returns 't'\nprintln(middle(\"middle\")) # returns \"iddl\"\n\nprintln(middle(\"as\")) # returns ''\nprintln(middle(\"A\")) # returns ''\n# println(middle(\"\")) # error, empty string\n\n## 2. Write a function called ispalindrome that takes a string argument and returns true if it is a palindrome and false otherwise. Remember that you can use the built-in function length to check the length of a string.\nprintln(\"Ans 2: \")\n\nfunction ispalindrome(word)\n if length(word) == 0\n return true\n end\n\n if first(word) == last(word)\n return ispalindrome(middle(word))\n else\n return false\n end\nend\n\nprintln(ispalindrome(\"noon\"))\nprintln(ispalindrome(\"redivider\"))\nprintln(ispalindrome(\"name\"))\n\nprintln(\"End.\")\n", "meta": {"hexsha": "b72d4e22099b0f281db1187a6c0a552962e5daa5", "size": 1637, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chapter6/ex6.jl", "max_stars_repo_name": "yashppawar/ThinkJuliaExercises.jl", "max_stars_repo_head_hexsha": "72145b969dc51ebcac413a10004175ebc63cd5c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-13T14:11:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T14:11:30.000Z", "max_issues_repo_path": "Chapter6/ex6.jl", "max_issues_repo_name": "yashppawar/ThinkJuliaExercises.jl", "max_issues_repo_head_hexsha": "72145b969dc51ebcac413a10004175ebc63cd5c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter6/ex6.jl", "max_forks_repo_name": "yashppawar/ThinkJuliaExercises.jl", "max_forks_repo_head_hexsha": "72145b969dc51ebcac413a10004175ebc63cd5c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7636363636, "max_line_length": 219, "alphanum_fraction": 0.7067806964, "num_tokens": 394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.19930800503802076, "lm_q1q2_score": 0.09188433457379117}} {"text": "### A Pluto.jl notebook ###\n# v0.18.4\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 49a44e94-29c0-4004-8d0b-e37008eafc1c\nusing BenchmarkTools, PlutoUI, Wordlegames\n\n# ╔═╡ f9816eb0-078e-41f2-bf7c-29ed5c663fd0\n# hideall\ntitle = \"Scoring guesses in Wordle\";\n\n# ╔═╡ a9678ae8-48c0-4bb9-920d-7de176105bd0\n\"\"\"\n+++\ntitle = \"$title\"\n+++\n\"\"\" |> Base.Text\n\n# ╔═╡ 4eabf46e-f75c-4b15-8583-6abe17c0fd85\nmd\"\"\"\n# $title\n\n[Wordle](https://en.wikipedia.org/wiki/Wordle) is a recently developed, extremely popular word game that has already spawned many imitators such as [Primel](https://converged.yt/primel/).\n\nThese tutorials illustrate some [Julia](https://julialang.org) programming concepts using functions in the [Wordlegames](https://github.com/dmbates/Wordlegames.jl) package for illustration.\nPart of the purpose is to illustrate the unique nature of Julia as a dynamically-typed language with a just-in-time (JIT) compiler.\nIt allows you to write \"generic\", both in the common meaning of \"general purpose\" and in the technical meaning of generic functions, and performative code.\n\nThis posting originated from a conversation on the Julia [discourse channel](https://discourse.julialang.org/t/rust-julia-comparison-post/75403) referring to a case where Julia code to perform a certain Wordle-related task - determine the \"best\" initial guess in a Wordle game - was horribly slow.\nJulia code described in a [Hacker News](https://news.ycombinator.com/) posting took several hours to do this.\n\nIn situations like this the Julia community inevitably responds with suggested modifications to make the code run faster.\nSomeone joked that we wouldn't be satisfied until we could do that task in less than 1 second, and we did.\n\nThe code in these postings can be used to solve a Wordle game very rapidly, as well as related games like Primel.\n\nBefore beginning we attach some packages that will be used in this notebook.\n\"\"\"\n\n# ╔═╡ 03b41118-5756-447b-9900-15af37667529\nmd\"\"\"\n## Target pools\n\nIf you are not familiar with the rules of Wordle, please check the [Wikipedia page](https://en.wikipedia.org/wiki/Wordle).\nIt is a word game with the objective of guessing a 5-letter English word, which we will call the \"target\".\nThe target word is changed every day but it is always chosen from a set of 2315 words, which we will call the \"target pool\".\n\nThe original target pool is available with the `Wordlegames` package. (Apparently the New York Times removed a few of these words after they purchased the rights to Wordle.)\n\"\"\"\n\n# ╔═╡ 73e3e38b-0935-4ef9-97b1-8a8cdfa2feb7\ndatadir = joinpath(pkgdir(Wordlegames), \"data\");\n\n# ╔═╡ 4c5e781c-fd10-425f-95d2-1fec5bf1015f\nwordlestrings = collect(readlines(joinpath(datadir, \"Wordletargets.txt\")))\n\n# ╔═╡ 2046a4ca-c4d3-4804-9373-930d9cbb58fd\nmd\"We call this pool `wordlestrings` because it is stored as a vector of `String`s\"\n\n# ╔═╡ 560ad4d4-945c-4d21-8947-cac68c1880a1\ntypeof(wordlestrings)\n\n# ╔═╡ ddd7f90c-7cad-4279-a275-b1800b4ae83b\nmd\"\"\"\nThe `Wordlegames` package defines a `GamePool` struct for playing Wordle or related games.\nIn that `struct` the `String`s are converted to a more efficient storage mode as a vector of `NTuple{5,Char}`, which takes advantage of the fact that each string is exactly 5 characters long.\n\nSpeaking of which, it would be a good idea to check that this collection has the properties we were told it had.\nIt should be a vector of 2315 strings, each of which is 5 characters.\n\"\"\"\n\n# ╔═╡ 49500976-7ab8-43cc-9902-b25ad73ff42e\nlength(wordlestrings)\n\n# ╔═╡ f6681018-f729-48de-9342-a5bcb151aca2\nall(w -> length(w) == 5, wordlestrings)\n\n# ╔═╡ 22f7e1ad-3a2b-4a88-8f81-91feada88621\nmd\"\"\"\nThat last expression may look, well, \"interesting\".\nIt is a way of checking that a function, in this case an anonymous function expressed using the [stabby lambda](https://dev.to/keithrbennett/why-i-prefer-stabby-lambda-notation-5gcj) notation, returns `true` for each element of an iterator, in this case the vector `wordlestrings`.\nYou can read the whole expression as \"is `length(w)` equal to `5` for each word `w` in `wordlestrings`\".\n\nThese words are supposed to be exactly 5 letters long but it never hurts to check.\nI've been a data scientist for several decades and one of the first lessons in the field is to [trust, but verify](https://en.wikipedia.org/wiki/Trust%2C_but_verify) any claims about the data you are provided.\n\nIt turns out this check is redundant because the property is checked when creating a `GamePool`.\n\"\"\"\n\n# ╔═╡ 5787eef2-7a2c-46ad-8fa0-7313c07be84b\nwordle = GamePool(wordlestrings);\n\n# ╔═╡ 8df0e0c0-cdae-450c-abc1-5cea1d520ec9\npropertynames(wordle)\n\n# ╔═╡ 8580bdcf-24ce-4eb6-ac5a-4c77b729b38b\ntypeof(wordle.guesspool)\n\n# ╔═╡ 9ed9e8ab-3ebc-4c6e-b2c3-46ad1987561e\nfirst(wordle.guesspool, 3)\n\n# ╔═╡ fdd6631e-8b3a-4b4f-b8a7-11135f13cc23\nmd\"\"\"\n## Game play\n\nA Wordle game is a dialog between the player and an \"oracle\", which, for the official game, is the web site.\nThe player submits a question to the oracle and the oracle responds, using information to which the player does not have access.\nIn this case the information is the target word.\nThe question is the player's guess - a 5-letter word - and the response is a score for that word.\nThe score indicates, for each character, whether it matches the character in the same position in the target or it is in the target in another position or it is not in the target at all.\n\nUsing the sample game for Wordle #196 from the Wikipedia page for illustration\n\"\"\"\n\n# ╔═╡ 9b911b3c-17d5-42d5-b7e5-a4187ce5787c\nPlutoUI.Resource(\n \"https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Wordle_196_example.svg/440px-Wordle_196_example.svg.png\",\n)\n\n# ╔═╡ 4d5681f9-56a5-4f83-9b31-810bdef26d98\nmd\"\"\"\nThe target is \"rebus\".\n\nThe player's first guess is \"arise\" and the response, or score, from the oracle is coded as 🟫🟨🟫🟨🟨 where 🟫 indicates that the letter is not in the target (neither `a` nor `i` occur in \"rebus\") and 🟨 indicates that the letter is in the target but not at that position.\n(I'm using 🟫 instead of a gray square because I can't find a gray square Unicode character.)\n\nThe second guess is \"route\" for which the response is 🟩🟫🟨🟫🟨 indicating that the first letter in the guess occurs as the first letter in the target.\nNotice that this guess does not include an \"s\", which is known from the score of the first guess to be one of the characters in the target.\nThis guess would not be allowed if playing the game under the \"Hard Mode\" setting.\n\nOf course, the colors are just one way of summarizing the response to a guess.\nWithin a computer program it is easier to use an integer to represent each of the 243 = 3⁵ possible scores.\nAn obvious way of mapping the result to an integer in the (decimal) range 0:242 is by mapping the response for each character to 2 (in target at that position), 1 (in target not at that position), or 0 (not in target) and regarding the pattern as a base-3 number.\n\nIn this coding the response for the first guess, \"arise\", is 01011 in base-3 or 31 in decimal.\nThe response for the second guess, \"route\", is 20101 in base-3 or 172 in decimal.\n\nA function to evaluate this score can be written as\n\"\"\"\n\n# ╔═╡ db787d98-d2a4-4d4a-8e13-8b61e80e48dd\nfunction score(guess, target)\n s = 0\n for (g, t) in zip(guess, target)\n s *= 3\n s += (g == t) ? 2 : Int(g ∈ target)\n end\n return s\nend\n\n# ╔═╡ e9e23c37-e4d8-4b77-ab6f-264bcba4ebec\nmd\"\"\"\nThese numeric scores are not on a scale where \"smaller is better\" or \"larger is better\".\n(It happens that the best score is 242, corresponding to a perfect match, or five green tiles, but that's incidental.)\n\nThe score is just a way of representing each of the 243 patterns that can be produced.\n\nWe can convert back to colored tiles if desired using the `tiles` function from the `Wordlegames` package, defined as \n```julia\nfunction tiles(sc, ntiles)\n result = Char[] # initialize to an empty array of Char\n for _ in 1:ntiles # _ indicates the value of the iterator is not used\n sc, r = divrem(sc, 3)\n push!(result, iszero(r) ? '🟫' : (isone(r) ? '🟨' : '🟩'))\n end\n return String(reverse(result))\nend\n```\n\"\"\"\n\n# ╔═╡ b0970feb-103d-4560-b577-f611171e8da6\ntiles(31, 5)\n\n# ╔═╡ 39ae1224-9cdf-4d4b-b543-985a5667a601\nmd\"\"\"\n## Examining the score function\n\nIn the Sherlock Holmes story [The Adventure of Silver Blaze](thttps://en.wikipedia.org/wiki/The_Adventure_of_Silver_Blaze) there is a famous exchange where Holmes remarks on \"the curious incident of the dog in the night-time\" (see the link).\nThe critical clue in the case is not what happened but what didn't happen - the dog didn't bark.\n\nJust as Holmes found it interesting that the dog didn't bark, we should find some of the functions in this notebook interesting for what they don't include.\nIn many of the functions shown here the arguments aren't given explicit types.\n\nKnowing the concrete types of arguments is very important when compiling functions, as is done in Julia, but these functions are written without explicit types.\n\nConsider the `score` function which we reproduce here\n\n```julia\nfunction score(guess, target)\n s = 0\n for (g, t) in zip(guess, target)\n s *= 3\n s += (g == t) ? 2 : Int(g ∈ target)\n end\n return s\nend\n```\n\nThe arguments to `score` can be any type.\nIn fact, formally they are of an abstract type called `Any`.\n\nSo how do we make sure that the actual arguments make sense for this function?\nWell, the first thing that is done with the arguments is to pass them to `zip(guess, target)` to produce pairs of values, `g` and `t`, that can be compared for equality, `g == t`.\nIn a sense `score` delegates the task of checking that the arguments are sensible to the `zip` function.\n\nFor those unfamiliar with zipping two or more iterators, we can check what the result is.\n\"\"\"\n\n# ╔═╡ 8a1cc31b-f747-49b4-9860-a2c381d98c44\ncollect(zip(\"arise\", \"rebus\"))\n\n# ╔═╡ 6830dbd6-edc9-4193-8d73-becf3be3855a\nmd\"\"\"\nOne of the great advantages of dynamically-typed languages with a REPL (read-eval-print-loop) like Julia is that we can easily check what `zip` produces in a couple of examples (or even read the documentation returned by `?zip`, if we are desperate).\n\nThe rest of the function is a common pattern - initialize `s`, which will be the result, modify `s` in a loop, and return it.\nThe Julia expression\n```julia\ns *= 3\n```\nindicates, as in several other languages, that `s` is to be multiplied by 3 in-place.\n\nAn expression like\n```julia\n(g == t) ? 2 : Int(g ∈ target)\n```\nis a *ternary operator* expression (the name comes from the operator taking three operands).\nIt evaluates the condition, `g == t`, and returns `2` if the condition is `true`.\nIf `g == t` is `false` the operator returns the value of the Boolean expression `g ∈ target`, converted to an `Int`.\n(The expression could also be written `g in target`.\nIn the Julia REPL the `∈` character is created by typing `\\in`.)\nThe Boolean expression will return `false` or `true`, which is promoted to `0` or `1` for the `+=` operation.\n\nThe operation of multiplying by 3 and adding 2 or 1 or 0 is an implementation of [Horner's method](https://en.wikipedia.org/wiki/Horner%27s_method) for evaluating a polynomial.\n\nThe function is remarkable because it is both general and compact.\nEven more remarkable is that it will be very, very fast after its first usage triggers compilation.\nThat's important because this function will be in a \"hot loop\".\nIt will be called many, many times when evaluating the next guess.\n\n(Unfortunately, this version doesn't properly account for cases where a character is repeated in the guess - an example of [Kernighan and Plauger's](https://en.wikipedia.org/wiki/The_Elements_of_Programming_Style) aphorism, \"Efficiency often means getting the wrong answer quickly.\"\nWe will return to this issue later.)\n\nWe won't go into detail about the Julia compiler except to note that compilation is performed for specific *method signatures* (or \"method instances\") not for general method definitions.\n\nThere are several functions and macros in Julia that allow for inspection at different stages of compilation.\nOne of the most useful is the macro `@code_warntype` which is used to check for situations where type inference has not been successful.\nApplying it as\n```julia\njulia> @code_warntype score(\"arise\", \"rebus\")\nMethodInstance for score(::String, ::String)\n from score(guess, target) in Main at REPL[1]:1\nArguments\n #self#::Core.Const(score)\n guess::String\n target::String\nLocals\n @_4::Union{Nothing, Tuple{Tuple{Char, Char}, Tuple{Int64, Int64}}}\n s::Int64\n @_6::Int64\n t::Char\n g::Char\n @_9::Int64\nBody::Int64\n...\n```\nshows that type inference is based on concrete types (`String`) for the arguments.\n\nSome argument types are handled more efficiently than others.\nWithout going in to details we note that we can take advantage of the fact that we have exactly 5 characters and convert the elements of `words` from `String` to `NTuple{5,Char}`, which is an ordered, fixed-length homogeneous collection.\n\nUsing the `@benchmark` macro from the `BenchmarkTools` package gives run times of a few tens of nanoseconds for these arguments, and shows that the function applied to the fixed-length collections is faster.\n\"\"\"\n\n# ╔═╡ e4410d39-6680-4eac-9f70-a425df352998\nmd\"\"\"\nNew methods can be defined for a generic function like `score`.\nA reason for this could be, for example, that the method can more effectively use information from the type.\n\nFor example, the `NTuple{N,Char}` type has exactly `N` characters - information that can be used in a loop where we can turn off bounds checking.\n\"\"\"\n\n# ╔═╡ a031c3db-6630-4deb-a90d-d2b13202dec6\nfunction score(guess::NTuple{N,Char}, target::NTuple{N,Char}) where {N}\n s = 0\n @inbounds for i = 1:N\n s *= 3\n gi = guess[i]\n s += (gi == target[i]) ? 2 : Int(gi ∈ target)\n end\n return s\nend\n\n# ╔═╡ 9e1d6017-f79e-49b5-916e-8e3a9e49ab1d\nscore(\"arise\", \"rebus\")\n\n# ╔═╡ a69f62bd-ed6d-42e7-8405-9321d13a52d1\n@benchmark score(guess, target) setup = (guess = \"arise\"; target = \"rebus\")\n\n# ╔═╡ 1b9261b3-c90c-4db1-9e70-51bf364072b8\nmd\"\"\"\nThis method returns the same result as the other method, only faster.\n\"\"\"\n\n# ╔═╡ 1887c091-46a0-4e8c-9a66-2ab17968729c\nscore(('a', 'r', 'i', 's', 'e'), ('r', 'e', 'b', 'u', 's'))\n\n# ╔═╡ 39202f1a-e7d6-4961-9776-ec67c3fd9743\n@benchmark score(guess1, target1) setup =\n (guess1 = ('a', 'r', 'i', 's', 'e'); target1 = ('r', 'e', 'b', 'u', 's'))\n\n# ╔═╡ 2b73c7f4-0203-4e2b-b634-eb310152834b\nmd\"\"\"\n## Repeated characters in the guess\n\nThe simple `score` methods shown above don't give the correct score (meaning the score that would be returned on the web site) when there are repeated characters in the guess.\nFor example, a guess of `\"sheer\"` for the target `\"super\"` is scored as\n\"\"\"\n\n# ╔═╡ 79f0ceab-0c9f-42f7-b3ec-a58b5ac1c083\ntiles(score(\"sheer\", \"super\"), 5)\n\n# ╔═╡ b92abc9c-2a86-47ab-a6e8-127c4d7de52e\nmd\"\"\"\nbut the score should be `\"🟩🟫🟫🟩🟩\"` because there is only one `e` in the target `\"super\"`.\nIn a case like this where a character occurs multiple times in a guess but only once in the target the rules about which position in the guess is marked are that \"correct position\" takes precedence over \"in the word\" and, if none of the guess positions are correct, then leftmost takes precedence.\n\nThis makes for a considerably more complex score evaluation.\nEssentially there have to be two passes over the score and target - the first to check for correct position and the second to check for \"in the target, not in the correct position\".\n\nHowever, the simple algorithm in the current `score` methods works if there are no duplicate characters in the guess.\nThus it is probably worthwhile checking for duplicates, using the simple function\n\n```julia\nfunction hasdups(guess::NTuple{N,Char}) where {N}\n @inbounds for i in 1:(N - 1)\n gi = guess[i]\n for j in (i + 1):N\n gi == guess[j] && return true\n end\n end\n return false\nend\n```\n\nand choose the simple scoring algorithm when there are no duplicates.\n\nIn the [Wordlegames](https://github.com/dmbates/Wordlegames.jl) package these operations are combined in a `scorecolumn!` function that updates a vector of scores on a single guess against a vector of targets.\n\n```julia\nfunction scorecolumn!(\n col::AbstractVector{<:Integer},\n guess::NTuple{N,Char},\n targets::AbstractVector{NTuple{N,Char}},\n) where {N}\n if axes(col) ≠ axes(targets)\n throw(\n DimensionMismatch(\n \"axes(col) = $(axes(col)) ≠ $(axes(targets)) = axes(targets)\",\n )\n )\n end\n if hasdups(guess)\n onetoN = (1:N...,) # 1:N as a Tuple\n svec = zeros(Int, N) # scores for characters in guess\n unused = trues(N) # unused positions in targets[i]\n @inbounds for i in axes(targets, 1)\n targeti = targets[i]\n fill!(unused, true) # reset to all unused\n fill!(svec, 0) # reset to all guess characters not in target\n for j = 1:N # first pass for target in same position\n if guess[j] == targeti[j]\n unused[j] = false\n svec[j] = 2\n end\n end\n for j = 1:N # second pass for match in unused position\n if iszero(svec[j])\n for k in onetoN[unused]\n if guess[j] == targeti[k]\n svec[j] = 1\n unused[k] = false\n break\n end\n end\n end\n end\n sc = 0 # Horner's method to evaluate the score\n for s in svec\n sc *= 3\n sc += s\n end\n col[i] = sc\n end\n else # simplified alg. for guess w/o duplicates\n @inbounds for i in axes(targets, 1)\n sc = 0\n targeti = targets[i]\n for j = 1:N\n sc *= 3\n gj = guess[j]\n sc += (gj == targeti[j]) ? 2 : Int(gj ∈ targeti)\n end\n col[i] = sc\n end\n end\n return col\nend\n```\n\nThis is \"production code\" which has gone through several refinement steps so it may seem a bit daunting at first.\nHowever, we can break it down.\n\nFirst, does it give the desired result?\n\"\"\"\n\n# ╔═╡ 2f32604f-b64c-47f5-bf14-a3cbde36cc13\nscores1 = zeros(Int, 1) # initialize a vector of 1 integer to zero \n\n# ╔═╡ f899d69c-ee68-47e3-963f-90bc401558b2\nscorecolumn!(scores1, ('s', 'h', 'e', 'e', 'r'), [('s', 'u', 'p', 'e', 'r')])\n\n# ╔═╡ 643bb3f5-c8e7-446c-b7d4-ea40952c4f59\ntiles(first(scores1), 5)\n\n# ╔═╡ 4742dec1-1a46-4095-bc49-467182beb163\nmd\"\"\"\nWe see that the call to `scorecolumn!` overwrites the contents of the `scores1` vector with the score for the guess on the first (and only) target.\n\nThus `scorecolumn!` is a \"mutating function\", meaning that it changes the contents of one or more of its arguments.\nBy convention we give such functions names ending in `\"!\"`, as a warning to the user that the function may mutate its arguments.\n(This is merely a convention; the `\"!\"` has no syntactic significance.)\nFurthermore, the convention is to list any arguments that may be modified first.\n\nThe reason this function is called `scorecolumn!` is because the scores for all possible guesses on all possible targets are evaluated and cached as a matrix in a `GamePool` object.\nThis may seem extravagant but most methods for determining an initial guess algorithmically will end up evaluating all these scores so it makes sense to save them in an array.\nIn this case the rows correspond to targets and the columns to guesses and evaluating the scores for a single guess against all possible targets updates a column of this matrix.\n\nA section from the upper left corner of this matrix\n\"\"\"\n\n# ╔═╡ 225c813a-e63e-44fc-bc08-caf4cf36e21b\nview(wordle.allscores, 1:7, 1:10)\n\n# ╔═╡ 875f7d47-b71f-4f67-90ae-755b00e2b464\nmd\"\"\"\nshows that the scores, which are in the range `0:242`, are stored as unsigned, 8-bit integers to conserve storage.\nEven so, the storage required is (2315)² bytes, or over 5 megabytes.\n\"\"\"\n\n# ╔═╡ 7c6e0762-de57-4041-a683-7ed6f0715057\nBase.summarysize(wordle.allscores)\n\n# ╔═╡ 178cfcd4-e198-4e44-b5bd-7da6c8b21456\nmd\"\"\"\nFive megabytes is not a large amount of memory by today's standards, but for games with larger pools of guesses or targets the storage may start to mount up.\nIn those cases there is provision for [memory-mapping](https://en.wikipedia.org/wiki/Memory-mapped_file) the array.\nThe evaluation of the array is multi-threaded when Julia is running with multiple threads.\n\nThe scores in the first column,\n\"\"\"\n\n# ╔═╡ 90f09143-4046-4e2f-967e-1df115411b32\ntiles.(view(wordle.allscores, 1:7, 1), 5)\n\n# ╔═╡ 628fb954-e44f-4c6d-af03-c41e9e2894d5\nmd\"\"\"\nare for the first guess, \"aback\", against the first 7 targets\n\"\"\"\n\n# ╔═╡ c976042e-2e91-401b-acfa-88199c22326c\n[String(collect(t)) for t in view(wordle.targetpool, 1:7)]\n\n# ╔═╡ 197e3fbe-6172-47b8-99c5-c8293223747c\nmd\"\"\"\nThe `scorecolumn!` function itself uses the `axes` function in several places.\nBy default Julia uses 1-based indexing but other forms of indexing are allowed.\n(I am obligated at this point to mention [StarWarsArrays](https://github.com/giordano/StarWarsArrays.jl) which begins indexing at 4, 5, 6 then 1, 2, 3 then 7, 8, and 9.)\n\nThe call to `axes(targets, 1)` returns the indices in the first (and only) axis of the `target` vector.\nThe `col` and `targets` arguments are typed as `AbstractVector`, not `Vector`, because `Vector` is a concrete, specific type and we wish to allow for \"vector-like\" objects such as a one-dimensional view in a multi-dimensional array.\n\nThe call to `scorecolumn!` in the constructor for a `GamePool` is in the code segment\n\n```julia\n S = scoretype(N)\n vtargs = view(guesspool, validtargets)\n allscores = Array{S}(undef, length(vtargs), length(guesspool))\n Threads.@threads for j in axes(allscores, 2)\n scorecolumn!(view(allscores, :, j), guesspool[j], vtargs)\n end\n```\n\nThere are two arrays, `svec` and `unused` allocated within the `scorecolumn!` function when guesses have repeated characters.\nThese are very small arrays but nonetheless we would want to minimize the number of allocations if feasible.\nThis is why the check for duplicate characters is carried out and the allocation of these arrays is done only once per column of `allscores`.\nThe allocation is done within the function so that it can be called from multiple threads simultaneously without the threads interfering with each other.\n\nThe branch for a guess without duplicates is still much faster than for a guess with duplicate characters but neither case is horribly slow.\n\"\"\"\n\n# ╔═╡ de2cac98-2ca9-4d27-8b02-ff152a73df7e\n@benchmark scorecolumn!(col, ('a', 'r', 'i', 's', 'e'), $(wordle.guesspool)) setup =\n (col = zeros(UInt8, length(wordle.guesspool)))\n\n# ╔═╡ 04cbc640-70be-402b-8a7e-3e9fc8e2cb00\nmd\"\"\"\nNotice that there are no allocations of memory when there are no duplicated characters in the guess.\nThere are allocations, and consequently some garbage collection (GC), when the guess has duplicated characters.\n\"\"\"\n\n# ╔═╡ 01d24948-480d-4eb5-9cc4-7c1e806f22fd\n@benchmark scorecolumn!(col1, ('a', 'b', 'a', 'c', 'k'), $(wordle.guesspool)) setup =\n (col1 = zeros(UInt8, length(wordle.guesspool)))\n\n# ╔═╡ 2c6d5aa5-7a23-4c67-8ff0-27b95ef58375\nmd\"\"\"\n## Conclusion\n\nThese few examples have introduced, at least in passing, several advanced programming concepts - multi-threading, memory-mapping, control of storage allocation and garbage collection - that one typically would not associate with a dynamically-typed, REPL-based language like Julia.\n\nOf course, all of these facilities are available in compiled languages like C/C++ or Rust but usually without the \"rapid development and testing\" capability of a language like Julia.\n\nJulia provides a wide range of tools so that a programmer can start at a very simple level, like the original `score` method and refine as needed to reach speeds previously only achievable with compiled, statically-typed languages.\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nBenchmarkTools = \"6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf\"\nPlutoUI = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nWordlegames = \"1cb69566-e1cf-455f-a587-fd79a2e00f5a\"\n\n[compat]\nBenchmarkTools = \"~1.3.1\"\nPlutoUI = \"~0.7.38\"\nWordlegames = \"~0.3.0\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\njulia_version = \"1.8.0-beta3\"\nmanifest_format = \"2.0\"\nproject_hash = \"045a6e2c86e27f8d763b85c40450eb9e85eed07e\"\n\n[[deps.AbstractPlutoDingetjes]]\ndeps = [\"Pkg\"]\ngit-tree-sha1 = \"8eaf9f1b4921132a4cff3f36a1d9ba923b14a481\"\nuuid = \"6e696c72-6542-2067-7265-42206c756150\"\nversion = \"1.1.4\"\n\n[[deps.AbstractTrees]]\ngit-tree-sha1 = \"03e0550477d86222521d254b741d470ba17ea0b5\"\nuuid = \"1520ce14-60c1-5f80-bbc7-55ef81b5835c\"\nversion = \"0.3.4\"\n\n[[deps.ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\nversion = \"1.1.1\"\n\n[[deps.Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[deps.Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[deps.BenchmarkTools]]\ndeps = [\"JSON\", \"Logging\", \"Printf\", \"Profile\", \"Statistics\", \"UUIDs\"]\ngit-tree-sha1 = \"4c10eee4af024676200bc7752e536f858c6b8f93\"\nuuid = \"6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf\"\nversion = \"1.3.1\"\n\n[[deps.ColorTypes]]\ndeps = [\"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"024fe24d83e4a5bf5fc80501a314ce0d1aa35597\"\nuuid = \"3da002f7-5984-5a60-b8a6-cbb66c0b333f\"\nversion = \"0.11.0\"\n\n[[deps.Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"96b0bc6c52df76506efc8a441c6cf1adcb1babc4\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.42.0\"\n\n[[deps.CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\nversion = \"0.5.2+0\"\n\n[[deps.Crayons]]\ngit-tree-sha1 = \"249fe38abf76d48563e2f4556bebd215aa317e15\"\nuuid = \"a8cc5b0e-0ffa-5ad4-8c14-923d3ee1735f\"\nversion = \"4.1.1\"\n\n[[deps.DataAPI]]\ngit-tree-sha1 = \"cc70b17275652eb47bc9e5f81635981f13cea5c8\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.9.0\"\n\n[[deps.DataFrames]]\ndeps = [\"Compat\", \"DataAPI\", \"Future\", \"InvertedIndices\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"Markdown\", \"Missings\", \"PooledArrays\", \"PrettyTables\", \"Printf\", \"REPL\", \"Reexport\", \"SortingAlgorithms\", \"Statistics\", \"TableTraits\", \"Tables\", \"Unicode\"]\ngit-tree-sha1 = \"ae02104e835f219b8930c7664b8012c93475c340\"\nuuid = \"a93c6f00-e57d-5684-b7b6-d8193f3e46c0\"\nversion = \"1.3.2\"\n\n[[deps.DataStructures]]\ndeps = [\"Compat\", \"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"3daef5523dd2e769dad2365274f760ff5f282c7d\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.18.11\"\n\n[[deps.DataValueInterfaces]]\ngit-tree-sha1 = \"bfc1187b79289637fa0ef6d4436ebdfe6905cbd6\"\nuuid = \"e2d170a0-9d28-54be-80f0-106bbe20a464\"\nversion = \"1.0.0\"\n\n[[deps.Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[deps.DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[deps.Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[deps.Downloads]]\ndeps = [\"ArgTools\", \"FileWatching\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\nversion = \"1.6.0\"\n\n[[deps.FileWatching]]\nuuid = \"7b1f6079-737a-58dc-b8bc-7a2ca5c1b5ee\"\n\n[[deps.FixedPointNumbers]]\ndeps = [\"Statistics\"]\ngit-tree-sha1 = \"335bfdceacc84c5cdf16aadc768aa5ddfc5383cc\"\nuuid = \"53c48c17-4a7d-5ca2-90c5-79b7896eea93\"\nversion = \"0.8.4\"\n\n[[deps.Formatting]]\ndeps = [\"Printf\"]\ngit-tree-sha1 = \"8339d61043228fdd3eb658d86c926cb282ae72a8\"\nuuid = \"59287772-0a20-5a39-b81b-1366585eb4c0\"\nversion = \"0.4.2\"\n\n[[deps.Future]]\ndeps = [\"Random\"]\nuuid = \"9fa8497b-333b-5362-9e8d-4d0656e87820\"\n\n[[deps.Hyperscript]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"8d511d5b81240fc8e6802386302675bdf47737b9\"\nuuid = \"47d2ed2b-36de-50cf-bf87-49c2cf4b8b91\"\nversion = \"0.0.4\"\n\n[[deps.HypertextLiteral]]\ngit-tree-sha1 = \"2b078b5a615c6c0396c77810d92ee8c6f470d238\"\nuuid = \"ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2\"\nversion = \"0.9.3\"\n\n[[deps.IOCapture]]\ndeps = [\"Logging\", \"Random\"]\ngit-tree-sha1 = \"f7be53659ab06ddc986428d3a9dcc95f6fa6705a\"\nuuid = \"b5f81e59-6552-4d32-b1f0-c071b021bf89\"\nversion = \"0.2.2\"\n\n[[deps.InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[deps.InvertedIndices]]\ngit-tree-sha1 = \"bee5f1ef5bf65df56bdd2e40447590b272a5471f\"\nuuid = \"41ab1584-1d38-5bbf-9106-f11c6c58b48f\"\nversion = \"1.1.0\"\n\n[[deps.IteratorInterfaceExtensions]]\ngit-tree-sha1 = \"a3f24677c21f5bbe9d2a714f95dcd58337fb2856\"\nuuid = \"82899510-4779-5014-852e-03e436cf321d\"\nversion = \"1.0.0\"\n\n[[deps.JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"3c837543ddb02250ef42f4738347454f95079d4e\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.3\"\n\n[[deps.LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\nversion = \"0.6.3\"\n\n[[deps.LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\nversion = \"7.81.0+0\"\n\n[[deps.LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[deps.LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\nversion = \"1.10.2+0\"\n\n[[deps.Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[deps.LinearAlgebra]]\ndeps = [\"Libdl\", \"libblastrampoline_jll\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[deps.Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[deps.Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[deps.MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\nversion = \"2.28.0+0\"\n\n[[deps.Missings]]\ndeps = [\"DataAPI\"]\ngit-tree-sha1 = \"bf210ce90b6c9eed32d25dbcae1ebc565df2687f\"\nuuid = \"e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28\"\nversion = \"1.0.2\"\n\n[[deps.Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[deps.MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\nversion = \"2022.2.1\"\n\n[[deps.NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\nversion = \"1.2.0\"\n\n[[deps.OpenBLAS_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Libdl\"]\nuuid = \"4536629a-c528-5b80-bd46-f80d51c5b363\"\nversion = \"0.3.20+0\"\n\n[[deps.OrderedCollections]]\ngit-tree-sha1 = \"85f8e6578bf1f9ee0d11e7bb1b1456435479d47c\"\nuuid = \"bac558e1-5e72-5ebc-8fee-abe8a469f55d\"\nversion = \"1.4.1\"\n\n[[deps.Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"621f4f3b4977325b9128d5fae7a8b4829a0c2222\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.2.4\"\n\n[[deps.Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\nversion = \"1.8.0\"\n\n[[deps.PlutoUI]]\ndeps = [\"AbstractPlutoDingetjes\", \"Base64\", \"ColorTypes\", \"Dates\", \"Hyperscript\", \"HypertextLiteral\", \"IOCapture\", \"InteractiveUtils\", \"JSON\", \"Logging\", \"Markdown\", \"Random\", \"Reexport\", \"UUIDs\"]\ngit-tree-sha1 = \"670e559e5c8e191ded66fa9ea89c97f10376bb4c\"\nuuid = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nversion = \"0.7.38\"\n\n[[deps.PooledArrays]]\ndeps = [\"DataAPI\", \"Future\"]\ngit-tree-sha1 = \"28ef6c7ce353f0b35d0df0d5930e0d072c1f5b9b\"\nuuid = \"2dfb63ee-cc39-5dd5-95bd-886bf059d720\"\nversion = \"1.4.1\"\n\n[[deps.PrettyTables]]\ndeps = [\"Crayons\", \"Formatting\", \"Markdown\", \"Reexport\", \"Tables\"]\ngit-tree-sha1 = \"dfb54c4e414caa595a1f2ed759b160f5a3ddcba5\"\nuuid = \"08abe8d2-0d0c-5749-adfa-8a2ac140af0d\"\nversion = \"1.3.1\"\n\n[[deps.Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[deps.Profile]]\ndeps = [\"Printf\"]\nuuid = \"9abbd945-dff8-562f-b5e8-e1ebf5ef1b79\"\n\n[[deps.REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[deps.Random]]\ndeps = [\"SHA\", \"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[deps.Reexport]]\ngit-tree-sha1 = \"45e428421666073eab6f2da5c9d310d99bb12f9b\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.2.2\"\n\n[[deps.SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\nversion = \"0.7.0\"\n\n[[deps.Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[deps.SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[deps.Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[deps.SortingAlgorithms]]\ndeps = [\"DataStructures\"]\ngit-tree-sha1 = \"b3363d7460f7d098ca0912c69b082f75625d7508\"\nuuid = \"a2af1166-a08f-5f64-846c-94a0d3cef48c\"\nversion = \"1.0.1\"\n\n[[deps.SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[deps.Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[deps.TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\nversion = \"1.0.0\"\n\n[[deps.TableTraits]]\ndeps = [\"IteratorInterfaceExtensions\"]\ngit-tree-sha1 = \"c06b2f539df1c6efa794486abfb6ed2022561a39\"\nuuid = \"3783bdb8-4a98-5b6b-af9a-565f29a5fe9c\"\nversion = \"1.0.1\"\n\n[[deps.Tables]]\ndeps = [\"DataAPI\", \"DataValueInterfaces\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"OrderedCollections\", \"TableTraits\", \"Test\"]\ngit-tree-sha1 = \"5ce79ce186cc678bbb5c5681ca3379d1ddae11a1\"\nuuid = \"bd369af6-aec1-5ad0-b16a-f7cc5008161c\"\nversion = \"1.7.0\"\n\n[[deps.Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\nversion = \"1.10.0\"\n\n[[deps.Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[deps.UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[deps.Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[deps.Wordlegames]]\ndeps = [\"AbstractTrees\", \"DataFrames\", \"Random\", \"Tables\"]\ngit-tree-sha1 = \"4c463de78d2f3f9447b695e241eba43cc945f866\"\nuuid = \"1cb69566-e1cf-455f-a587-fd79a2e00f5a\"\nversion = \"0.3.0\"\n\n[[deps.Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\nversion = \"1.2.12+1\"\n\n[[deps.libblastrampoline_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"OpenBLAS_jll\"]\nuuid = \"8e850b90-86db-534c-a0d3-1478176c7d93\"\nversion = \"5.1.0+0\"\n\n[[deps.nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\nversion = \"1.41.0+1\"\n\n[[deps.p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\nversion = \"16.2.1+1\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─f9816eb0-078e-41f2-bf7c-29ed5c663fd0\n# ╟─a9678ae8-48c0-4bb9-920d-7de176105bd0\n# ╟─4eabf46e-f75c-4b15-8583-6abe17c0fd85\n# ╠═49a44e94-29c0-4004-8d0b-e37008eafc1c\n# ╟─03b41118-5756-447b-9900-15af37667529\n# ╠═73e3e38b-0935-4ef9-97b1-8a8cdfa2feb7\n# ╠═4c5e781c-fd10-425f-95d2-1fec5bf1015f\n# ╟─2046a4ca-c4d3-4804-9373-930d9cbb58fd\n# ╠═560ad4d4-945c-4d21-8947-cac68c1880a1\n# ╟─ddd7f90c-7cad-4279-a275-b1800b4ae83b\n# ╠═49500976-7ab8-43cc-9902-b25ad73ff42e\n# ╠═f6681018-f729-48de-9342-a5bcb151aca2\n# ╟─22f7e1ad-3a2b-4a88-8f81-91feada88621\n# ╠═5787eef2-7a2c-46ad-8fa0-7313c07be84b\n# ╠═8df0e0c0-cdae-450c-abc1-5cea1d520ec9\n# ╠═8580bdcf-24ce-4eb6-ac5a-4c77b729b38b\n# ╠═9ed9e8ab-3ebc-4c6e-b2c3-46ad1987561e\n# ╟─fdd6631e-8b3a-4b4f-b8a7-11135f13cc23\n# ╟─9b911b3c-17d5-42d5-b7e5-a4187ce5787c\n# ╟─4d5681f9-56a5-4f83-9b31-810bdef26d98\n# ╠═db787d98-d2a4-4d4a-8e13-8b61e80e48dd\n# ╠═9e1d6017-f79e-49b5-916e-8e3a9e49ab1d\n# ╟─e9e23c37-e4d8-4b77-ab6f-264bcba4ebec\n# ╠═b0970feb-103d-4560-b577-f611171e8da6\n# ╟─39ae1224-9cdf-4d4b-b543-985a5667a601\n# ╠═8a1cc31b-f747-49b4-9860-a2c381d98c44\n# ╟─6830dbd6-edc9-4193-8d73-becf3be3855a\n# ╠═a69f62bd-ed6d-42e7-8405-9321d13a52d1\n# ╟─e4410d39-6680-4eac-9f70-a425df352998\n# ╠═a031c3db-6630-4deb-a90d-d2b13202dec6\n# ╟─1b9261b3-c90c-4db1-9e70-51bf364072b8\n# ╠═1887c091-46a0-4e8c-9a66-2ab17968729c\n# ╠═39202f1a-e7d6-4961-9776-ec67c3fd9743\n# ╟─2b73c7f4-0203-4e2b-b634-eb310152834b\n# ╠═79f0ceab-0c9f-42f7-b3ec-a58b5ac1c083\n# ╟─b92abc9c-2a86-47ab-a6e8-127c4d7de52e\n# ╠═2f32604f-b64c-47f5-bf14-a3cbde36cc13\n# ╠═f899d69c-ee68-47e3-963f-90bc401558b2\n# ╠═643bb3f5-c8e7-446c-b7d4-ea40952c4f59\n# ╟─4742dec1-1a46-4095-bc49-467182beb163\n# ╠═225c813a-e63e-44fc-bc08-caf4cf36e21b\n# ╟─875f7d47-b71f-4f67-90ae-755b00e2b464\n# ╠═7c6e0762-de57-4041-a683-7ed6f0715057\n# ╟─178cfcd4-e198-4e44-b5bd-7da6c8b21456\n# ╠═90f09143-4046-4e2f-967e-1df115411b32\n# ╟─628fb954-e44f-4c6d-af03-c41e9e2894d5\n# ╠═c976042e-2e91-401b-acfa-88199c22326c\n# ╟─197e3fbe-6172-47b8-99c5-c8293223747c\n# ╠═de2cac98-2ca9-4d27-8b02-ff152a73df7e\n# ╟─04cbc640-70be-402b-8a7e-3e9fc8e2cb00\n# ╠═01d24948-480d-4eb5-9cc4-7c1e806f22fd\n# ╟─2c6d5aa5-7a23-4c67-8ff0-27b95ef58375\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "37828a9c0b97ca60997bc67ef45b332b36d31cd0", "size": 37383, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "tutorials/scoring.jl", "max_stars_repo_name": "dmbates/WordleTutorials", "max_stars_repo_head_hexsha": "db855a5d18b33ef65d27533ea8dafbf83c89e395", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2022-03-05T15:19:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T22:03:06.000Z", "max_issues_repo_path": "tutorials/scoring.jl", "max_issues_repo_name": "dmbates/WordleTutorials", "max_issues_repo_head_hexsha": "db855a5d18b33ef65d27533ea8dafbf83c89e395", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tutorials/scoring.jl", "max_forks_repo_name": "dmbates/WordleTutorials", "max_forks_repo_head_hexsha": "db855a5d18b33ef65d27533ea8dafbf83c89e395", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-07T18:54:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T18:54:15.000Z", "avg_line_length": 39.2678571429, "max_line_length": 297, "alphanum_fraction": 0.7228954338, "num_tokens": 13314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4416729909662417, "lm_q2_score": 0.2068940390354276, "lm_q1q2_score": 0.09137950903386367}} {"text": "## Exercise 4-2\n## Write a function called square that takes a parameter named t, which is a turtle. It should use the turtle to draw a square.\nusing ThinkJulia\n\nprintln(\"Ans: \")\n\nfunction square(turtle::Turtle, distance::Int = 100)\n @svg begin\n for i in 1:3\n forward(turtle, distance)\n turn(turtle, -90)\n end\n \n forward(turtle, distance)\n end\nend\n\nturtle = Turtle()\nsquare(turtle)\n\nprintln(\"End.\")\n", "meta": {"hexsha": "0f171eccd4cd88cb7df34d9d5b5c2f4d937f0607", "size": 455, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chapter4/ex2.jl", "max_stars_repo_name": "yashppawar/ThinkJuliaExercises.jl", "max_stars_repo_head_hexsha": "72145b969dc51ebcac413a10004175ebc63cd5c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-13T14:11:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T14:11:30.000Z", "max_issues_repo_path": "Chapter4/ex2.jl", "max_issues_repo_name": "yashppawar/ThinkJuliaExercises.jl", "max_issues_repo_head_hexsha": "72145b969dc51ebcac413a10004175ebc63cd5c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter4/ex2.jl", "max_forks_repo_name": "yashppawar/ThinkJuliaExercises.jl", "max_forks_repo_head_hexsha": "72145b969dc51ebcac413a10004175ebc63cd5c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.6818181818, "max_line_length": 127, "alphanum_fraction": 0.6285714286, "num_tokens": 116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.18952109132967757, "lm_q1q2_score": 0.08443724370030364}} {"text": "# Copyright (c) 2019 Arpit Bhatia and contributors #src\n# #src\n# Permission is hereby granted, free of charge, to any person obtaining a copy #src\n# of this software and associated documentation files (the \"Software\"), to deal #src\n# in the Software without restriction, including without limitation the rights #src\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #src\n# copies of the Software, and to permit persons to whom the Software is #src\n# furnished to do so, subject to the following conditions: #src\n# #src\n# The above copyright notice and this permission notice shall be included in all #src\n# copies or substantial portions of the Software. #src\n# #src\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #src\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #src\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #src\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #src\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #src\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #src\n# SOFTWARE. #src\n\n# # Getting started with JuMP\n\n# This tutorial is aimed at providing a quick introduction to writing JuMP code.\n\n# ## What is JuMP?\n\n# JuMP (\"Julia for Mathematical Programming\") is an open-source modeling\n# language that is embedded in Julia. It allows users to formulate various\n# classes of optimization problems (linear, mixed-integer, quadratic, conic\n# quadratic, semidefinite, and nonlinear) with easy-to-read code. These problems\n# can then be solved using state-of-the-art open-source and commercial solvers.\n\n# JuMP also makes advanced optimization techniques easily accessible from a\n# high-level language.\n\n# ## Installation\n\n# JuMP is a package for Julia. From Julia, JuMP is installed by using the\n# built-in package manager.\n\n# ```julia\n# import Pkg\n# Pkg.add(\"JuMP\")\n# ```\n\n# You also need to include a Julia package which provides an appropriate solver.\n# One such solver is `GLPK.Optimizer`, which is provided by the\n# [GLPK.jl package](https://github.com/jump-dev/GLPK.jl).\n# ```julia\n# import Pkg\n# Pkg.add(\"GLPK\")\n# ```\n# See [Installation Guide](@ref) for a list of other solvers you can use.\n\n# ## An example\n\n# Let's try to solve the following linear programming problem by using JuMP and\n# GLPK. We will first look at the complete code to solve the problem and then go\n# through it step by step.\n\n# ```math\n# \\begin{aligned}\n# & \\min & 12x + 20y \\\\\n# & \\;\\;\\text{s.t.} & 6x + 8y \\geq 100 \\\\\n# & & 7x + 12y \\geq 120 \\\\\n# & & x \\geq 0 \\\\\n# & & y \\in [0, 3] \\\\\n# \\end{aligned}\n# ```\n\nusing JuMP\nusing GLPK\nmodel = Model(GLPK.Optimizer)\n@variable(model, x >= 0)\n@variable(model, 0 <= y <= 3)\n@objective(model, Min, 12x + 20y)\n@constraint(model, c1, 6x + 8y >= 100)\n@constraint(model, c2, 7x + 12y >= 120)\nprint(model)\noptimize!(model)\n@show termination_status(model)\n@show primal_status(model)\n@show dual_status(model)\n@show objective_value(model)\n@show value(x)\n@show value(y)\n@show shadow_price(c1)\n@show shadow_price(c2)\n\n# ## Step-by-step\n\n# Once JuMP is installed, to use JuMP in your programs, we just need to write:\n\nusing JuMP\n\n# We also need to include a Julia package which provides an appropriate solver.\n# We want to use `GLPK.Optimizer` here which is provided by the `GLPK.jl`\n# package.\n\nusing GLPK\n\n# A model object is a container for variables, constraints, solver options, etc.\n# Models are created with the [`Model`](@ref) function. The model can be created\n# with an optimizer attached with default arguments by calling the constructor\n# with the optimizer type, as follows:\n\nmodel = Model(GLPK.Optimizer)\n\n# Variables are modeled using [`@variable`](@ref):\n\n@variable(model, x >= 0)\n\n# They can have lower and upper bounds.\n\n@variable(model, 0 <= y <= 30)\n\n# The objective is set using [`@objective`](@ref):\n\n@objective(model, Min, 12x + 20y)\n\n# Constraints are modeled using [`@constraint`](@ref). Here `c1` and `c2` are\n# the names of our constraint.\n\n@constraint(model, c1, 6x + 8y >= 100)\n\n#-\n\n@constraint(model, c2, 7x + 12y >= 120)\n\n#- Call `print` to display the model:\n\nprint(model)\n\n# To solve the optimization problem, call the `optimize!` function.\n\noptimize!(model)\n\n# !!! info\n# The `!` after optimize is just part of the name. It's nothing special.\n# Julia has a convention that functions which mutate their arguments should\n# end in `!`. A common example is `push!`.\n\n# Now let's see what information we can query about the solution.\n\n# [`termination_status`](@ref) tells us why the solver stopped:\n\ntermination_status(model)\n\n# In this case, the solver found an optimal solution. We should also check\n# [`primal_status`](@ref) to see if the solver found a primal feasible point:\n\nprimal_status(model)\n\n# and [`dual_status`](@ref) to see if the solver found a dual feasible point:\n\ndual_status(model)\n\n# Now we know that our solver found an optimal solution, and has a primal and a\n# dual solution to query.\n\n# Query the objective value using [`objective_value`](@ref):\n\nobjective_value(model)\n\n# The primal solution using [`value`](@ref):\n\nvalue(x)\n\n#-\n\nvalue(y)\n\n# and the dual solution using [`shadow_price`](@ref):\n\nshadow_price(c1)\n\n#-\n\nshadow_price(c2)\n\n# ## Variable basics\n\nmodel = Model()\n\n\n# ### Variable bounds\n\n# All of the variables we have created till now have had a bound. We can also\n# create a free variable.\n\n@variable(model, free_x)\n\n# While creating a variable, instead of using the <= and >= syntax, we can also\n# use the `lower_bound` and `upper_bound` keyword arguments.\n\n@variable(model, keyword_x, lower_bound = 1, upper_bound = 2)\n\n# We can query whether a variable has a bound using the `has_lower_bound` and\n# `has_upper_bound` functions. The values of the bound can be obtained using the\n# `lower_bound` and `upper_bound` functions.\n\nhas_upper_bound(keyword_x)\n\n#-\n\nupper_bound(keyword_x)\n\n# Note querying the value of a bound that does not exist will result in an error.\n\nlower_bound(free_x)\n\n# JuMP also allows us to change the bounds on variable. We will learn this in\n# the problem modification tutorial.\n\n# ### [Containers](@id tutorial_variable_container)\n\n# We have already seen how to add a single variable to a model using the\n# [`@variable`](@ref) macro. Let's now look at more ways to add variables to a\n# JuMP model.\n\n# JuMP provides data structures for adding collections of variables to a model.\n# These data structures are referred to as Containers and are of three types:\n# `Arrays`, `DenseAxisArrays`, and `SparseAxisArrays`.\n\n# #### Arrays\n\n# JuMP arrays are created in a similar syntax to Julia arrays with the addition\n# of specifying that the indices start with 1. If we do not tell JuMP that the\n# indices start at 1, it will create a `DenseAxisArray` instead.\n\n@variable(model, a[1:2, 1:2])\n\n# An n-dimensional variable $x \\in {R}^n$ having a bound $l \\preceq x \\preceq u$\n# ($l, u \\in {R}^n$) is added in the following manner.\n\nn = 10\nl = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]\nu = [10; 11; 12; 13; 14; 15; 16; 17; 18; 19]\n\n@variable(model, l[i] <= x[i = 1:n] <= u[i])\n\n# Note that while working with Containers, we can also create variable bounds\n# depending upon the indices:\n\n@variable(model, y[i = 1:2, j = 1:2] >= 2i + j)\n\n# #### DenseAxisArrays\n\n# `DenseAxisArrays` are used when the required indices are not one-based integer\n# ranges. The syntax is similar except with an arbitrary vector as an index as\n# opposed to a one-based range.\n\n# An example where the indices are integers but do not start with one.\n\n@variable(model, z[i = 2:3, j = 1:2:3] >= 0)\n\n# Another example where the indices are an arbitrary vector.\n\n@variable(model, w[1:5, [\"red\", \"blue\"]] <= 1)\n\n# #### SparseAxisArrays\n\n# `SparseAxisArrays` are created when the indices do not form a rectangular set.\n# For example, this applies when indices have a dependence upon previous indices\n# (called triangular indexing).\n\n@variable(model, u[i = 1:3, j = i:5])\n\n# We can also conditionally create variables by adding a comparison check that\n# depends upon the named indices and is separated from the indices by a\n# semi-colon (;).\n\n@variable(model, v[i = 1:9; mod(i, 3) == 0])\n\n# ### Variable types\n\n# The last argument to the `@variable` macro is usually the variable type. Here\n# we'll look at how to specify the variable type.\n\n# #### Integer variables\n\n# Integer optimization variables are constrained to the set $x \\in {Z}$\n\n@variable(model, integer_x, Int)\n\n# or\n\n@variable(model, integer_z, integer = true)\n\n# #### Binary variables\n\n# Binary optimization variables are constrained to the set $x \\in \\{0, 1\\}$.\n\n@variable(model, binary_x, Bin)\n\n# or\n\n@variable(model, binary_z, binary = true)\n\n# ## Constraint basics\n\nmodel = Model()\n@variable(model, x)\n@variable(model, y)\n@variable(model, z[1:10]);\n\n# ### Constraint references\n\n# While calling the `@constraint` macro, we can also set up a constraint\n# reference. Such a reference is useful for obtaining additional information\n# about the constraint, such as its dual solution.\n\n@constraint(model, con, x <= 4)\n\n# ### [Containers](@id tutorial_constraint_container)\n\n# Just as we had containers for variables, JuMP also provides `Arrays`,\n# `DenseAxisArrays`, and `SparseAxisArrays` for storing collections of\n# constraints. Examples for each container type are given below.\n\n# #### Arrays\n\n@constraint(model, [i = 1:3], i * x <= i + 1)\n\n# #### DenseAxisArrays\n\n@constraint(model, [i = 1:2, j = 2:3], i * x <= j + 1)\n\n# #### SparseAxisArrays\n\n@constraint(model, [i = 1:2, j = 1:2; i != j], i * x <= j + 1)\n\n# ### Constraints in a loop\n\n# We can add constraints using regular Julia loops\n\nfor i in 1:3\n @constraint(model, 6x + 4y >= 5i)\nend\n\n# or use for each loops inside the `@constraint` macro.\n\n@constraint(model, [i in 1:3], 6x + 4y >= 5i)\n\n# We can also create constraints such as $\\sum _{i = 1}^{10} z_i \\leq 1$\n\n@constraint(model, sum(z[i] for i in 1:10) <= 1)\n\n# ## Objective functions\n\n# While the recommended way to set the objective is with the [`@objective`](@ref)\n# macro, the functions [`set_objective_sense`](@ref) and [`set_objective_function`](@ref)\n# provide an equivalent lower-level interface.\n\nusing GLPK\n\nmodel = Model(GLPK.Optimizer)\n@variable(model, x >= 0)\n@variable(model, y >= 0)\nset_objective_sense(model, MOI.MIN_SENSE)\nset_objective_function(model, x + y)\n\noptimize!(model)\n\n#-\n\nobjective_value(model)\n\n# To query the objective function from a model, we use the [`objective_sense`](@ref),\n# [`objective_function`](@ref), and [`objective_function_type`](@ref) functions.\n\nobjective_sense(model)\n\n#-\n\nobjective_function(model)\n\n#-\n\nobjective_function_type(model)\n\n# ## Vectorized syntax\n\n# We can also add constraints and an objective to JuMP using vectorized linear\n# algebra. We'll illustrate this by solving an LP in standard form i.e.\n\n# ```math\n# \\begin{aligned}\n# & \\min & c^T x \\\\\n# & \\;\\;\\text{s.t.} & A x = b \\\\\n# & & x \\succeq 0 \\\\\n# & & x \\in \\mathbb{R}^n\n# \\end{aligned}\n# ```\n\nvector_model = Model(GLPK.Optimizer)\n\nA = [\n 1 1 9 5\n 3 5 0 8\n 2 0 6 13\n]\n\nb = [7; 3; 5]\n\nc = [1; 3; 5; 2]\n\n@variable(vector_model, x[1:4] >= 0)\n@constraint(vector_model, A * x .== b)\n@objective(vector_model, Min, c' * x)\n\noptimize!(vector_model)\n\n#-\n\nobjective_value(vector_model)\n\n", "meta": {"hexsha": "64ed4a2fb44726d901bf724b73a3b2de9ce88440", "size": 11793, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/getting_started_with_JuMP.jl", "max_stars_repo_name": "odow/jump-training-materials", "max_stars_repo_head_hexsha": "0ed2164c7625ce66b59881f1ea6c5b491daae013", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-08-31T05:32:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T08:33:50.000Z", "max_issues_repo_path": "src/getting_started_with_JuMP.jl", "max_issues_repo_name": "odow/jump-training-materials", "max_issues_repo_head_hexsha": "0ed2164c7625ce66b59881f1ea6c5b491daae013", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/getting_started_with_JuMP.jl", "max_forks_repo_name": "odow/jump-training-materials", "max_forks_repo_head_hexsha": "0ed2164c7625ce66b59881f1ea6c5b491daae013", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-09-08T15:45:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T05:37:06.000Z", "avg_line_length": 28.2129186603, "max_line_length": 89, "alphanum_fraction": 0.6809972017, "num_tokens": 3145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.18010666848732088, "lm_q1q2_score": 0.08373187319458142}} {"text": "### A Pluto.jl notebook ###\n# v0.12.21\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ bcaefa4e-85c6-11eb-3316-0db4881ebd30\nbegin\n\tusing PlutoUI\n\tusing NativeSVG\nend\n\n# ╔═╡ 13d62b06-85c7-11eb-00b9-0399467b1ab5\nmd\"\"\"# Dictionaries\n\nThis chapter presents another built-in type called a dictionary.\"\"\"\n\n# ╔═╡ 1f1c885e-85c7-11eb-1452-13a8943ebc90\nmd\"\"\"## A Dictionary Is a Mapping\n\nA *dictionary* is like an array, but more general. In an array, the indices have to be integers; in a dictionary they can be (almost) any type.\n\nA dictionary contains a collection of indices, which are called *keys*, and a collection of *values*. Each key is associated with a single value. The association of a key and a value is called a *key-value* pair, or sometimes an *item*.\n\nIn mathematical language, a dictionary represents a *mapping* from keys to values, so you can also say that each key “maps to” a value. As an example, we’ll build a dictionary that maps from English to Spanish words, so the keys and the values are all strings.\n\nThe function `Dict` creates a new dictionary with no items (because Dict is the name of a built-in function, you should avoid using it as a variable name):\n\n```julia\njulia> eng2sp = Dict() \nDict{Any,Any} with 0 entries\n```\n\nThe types of the keys and values in the dictionary are specified in curly braces: here, both are of type `Any`.\n\n\nThe dictionary is empty. To add items to the dictionary, you can use square brackets:\n\n```julia\njulia> eng2sp[\"one\"] = \"uno\";\n```\n\nThis line creates an item that maps from the key `\"one\"` to the value `\"uno\"`. If we print the dictionary again, we see a key-value pair with an arrow `=>` between the key and value:\n\n```julia\njulia> eng2sp \nDict{Any,Any} with 1 entry:\n \"one\" => \"uno\"\n```\n\nThis output format is also an input format. For example, you can create a new dictionary with three items as follows:\n\n```julia\njulia> eng2sp = Dict(\"one\" => \"uno\", \"two\" => \"dos\", \"three\" => \"tres\") Dict{String,String} with 3 entries:\n \"two\" => \"dos\"\n \"one\" => \"uno\"\n \"three\" => \"tres\"\n```\n\nHere all the initial keys and values are strings, so a `Dict{String,String}` is created. \n\nThe order of the items in a dictionary is unpredictable. If you type the same example\non your computer, you might get a different result.\n\nBut that’s not a problem because the elements of a dictionary are never indexed with integer indices. Instead, you use the keys to look up the corresponding values:\n\n```julia\njulia> eng2sp[\"two\"] \n\"dos\"\n```\n\nThe key `\"two\"` always maps to the value `\"dos\"`, so the order of the items doesn’t matter.\n\nIf the key isn’t in the dictionary, you get an exception:\n\n```julia\njulia> eng2sp[\"four\"]\nERROR: KeyError: key \"four\" not found\n```\n\nThe `length` function works on dictionaries; it returns the number of key-value pairs: \n\n```julia\njulia> length(eng2sp)\n3\n```\n\nThe function keys returns a collection with the keys of the dictionary: \n\n```julia\njulia> ks = keys(eng2sp);\n\njulia> print(ks) \n[\"two\", \"one\", \"three\"]\n```\n\nNow you can use the `∈` operator to see whether something appears as a key in the dictionary:\n\n```julia\njulia> \"one\" ∈ ks \ntrue\njulia> \"uno\" ∈ ks \nfalse\n```\n\nTo see whether something appears as a value in a dictionary, you can use the function `values`, which returns a collection of values, and then use the `∈` operator:\n\n```julia\njulia> vs = values(eng2sp); \n\njulia> \"uno\" ∈ vs\ntrue\n```\n\nThe `∈` operator uses different algorithms for arrays and dictionaries. For arrays, it searches the elements of the array in order, as described in “Searching”. As the array gets longer, the search time gets longer in direct proportion.\n\nFor dictionaries, Julia uses an algorithm called a *hash table* that has a remarkable property: the `∈` operator takes about the same amount of time no matter how many items are in the dictionary.\n\"\"\"\n\n# ╔═╡ 27e4cf0c-85c8-11eb-0d95-ab9ddc845387\nmd\"\"\"## Dictionaries as Collections of Counters\n\nSuppose you are given a string and you want to count how many times each letter appears. There are several ways you could do it:\n\n* You could create 26 variables, one for each letter of the alphabet. Then you could traverse the string and, for each character, increment the corresponding counter, probably using a chained conditional.\n* You could create an array with 26 elements. Then you could convert each character to a number (using the built-in function Int), use the number as an index into the array, and increment the appropriate counter.\n* You could create a dictionary with characters as keys and counters as the corresponding values. The first time you see a character, you would add an item to the dictionary. After that you would increment the value of an existing item.\n\nEach of these options performs the same computation, but each of them implements that computation in a different way.\n\nAn *implementation* is a way of performing a computation. Some implementations are better than others. For example, an advantage of the dictionary implementation is that we don’t have to know ahead of time which letters appear in the string and we only have to make room for the letters that do appear.\n\nHere is what the code might look like:\n\n```julia\nfunction histogram(s) \n\td = Dict()\n\tfor c in s\n\t\tif c ∉ keys(d)\n\t\t\td[c] = 1 \n\t\telse\n\t\t\td[c] += 1 \n\t\tend\n\tend\n\td\nend\n```\n\nThe name of the function is `histogram`, which is a statistical term for a collection of counters (or frequencies).\n\n\nThe first line of the function creates an empty dictionary. The `for` loop traverses the string. Each time through the loop, if the character `c` is not in the dictionary, we create a new item with key `c` and the initial value `1` (since we have seen this letter once). If `c` is already in the dictionary we increment `d[c]`.\n\nHere’s how it works:\n\n```julia\njulia> h = histogram(\"brontosaurus\") Dict{Any,Any} with 8 entries:\n 'n' => 1\n 's' => 2\n 'a' => 1\n 'r' => 2\n 't' => 1\n 'o' => 2\n 'u' => 2\n 'b' => 1\n```\n\nThe histogram indicates that the letters *a* and *b* appear once, *o* appears twice, and so on.\n\nDictionaries have a function called `get` that takes a key and a default value. If the key appears in the dictionary, `get` returns the corresponding value; otherwise, it returns the default value. For example:\n\n```julia\njulia> h = histogram(\"a\") \nDict{Any,Any} with 1 entry:\n 'a' => 1\njulia> get(h, 'a', 0) \n1\njulia> get(h, 'b', 0) \n0\n```\n\"\"\"\n\n# ╔═╡ c8dff15e-85c8-11eb-1230-bd39702cf460\nmd\"\"\"#### Exercise 11-1\n\nUse `get` to write `histogram` more concisely. You should be able to eliminate the `if` statement. What does the function `get!` do? Can you use it to simplify `histogram`?\n\"\"\"\n\n# ╔═╡ 0b2e93b0-85c9-11eb-0dc3-61b1cbfb022b\nmd\"\"\"## Looping and Dictionaries\n\nYou can traverse the keys of a dictionary in a for statement. For example, `printhist` prints each key and the corresponding value:\n\n```julia\nfunction printhist(h) \n\tfor c in keys(h)\n\t\tprintln(c, \" \", h[c]) \n\tend\nend\n```\n\nHere’s what the output looks like:\n\n```julia\njulia> h = histogram(\"parrot\");\n\njulia> printhist(h) \na 1\nr 2\np 1\no 1 \nt 1\n```\n\nAgain, the keys are in no particular order. To traverse the keys in sorted order, you can combine `sort` and `collect`:\n\n```julia\njulia> for c in sort(collect(keys(h))) \n\t println(c, \" \", h[c])\n end\na 1 \no 1 \np 1 \nr 2 \nt 1\n```\n\"\"\"\n\n# ╔═╡ 82a2f936-85c9-11eb-1d33-0d9dc98fdac0\nmd\"\"\"## Reverse Lookup\n\nGiven a dictionary `d` and a key `k`, it is easy to find the corresponding value `v = d[k]`. This operation is called a *lookup*.\n\nBut what if you have `v` and you want to find `k`? You have two problems. First, there might be more than one key that maps to the value `v`. Depending on the application, you might be able to pick one, or you might have to make an array that contains all of them. Second, there is no simple syntax to do a *reverse lookup*; you have to search.\n\n!!! danger\n A reverse lookup is much slower than a forward lookup; if you have to do it often, or if the dictionary gets big, the performance of your program will suffer.\n\nHere is a function that takes a value and returns the first key that maps to that value:\n\n```julia\nfunction reverselookup(d, v) \n\tfor k in keys(d)\n\t\tif d[k]==v \n\t\t\treturn k\n\t\tend \n\tend\n\terror(\"LookupError\") \nend\n```\n\nThis function is yet another example of the search pattern, but it uses a function we haven’t seen before: `error`. The `error` function is used to produce an `ErrorException` that interrupts the normal flow of control. In this case it has the message `\"LookupError\"`, indicating that a key does not exist.\n\n\nIf we get to the end of the loop, that means `v` doesn’t appear in the dictionary as a value, so we throw an exception.\n\nHere is an example of a successful reverse lookup:\n\n```julia\njulia> h = histogram(\"parrot\"); \n\njulia> key = reverselookup(h, 2)\n'r': ASCII/Unicode U+0072 (category Ll: Letter, lowercase)\n```\n\nAnd an unsuccessful one:\n\n```julia\njulia> key = reverselookup(h, 3) \nERROR: LookupError\n```\n\nThe effect when you generate an exception is the same as when Julia throws one: it prints a stacktrace and an error message.\n\n!!! tip\n Julia provides an optimized way to do a reverse lookup: findall(isequal(3), h).\n\"\"\"\n\n# ╔═╡ 6d87ad02-85ca-11eb-2a3d-999d28a7c4b7\nmd\"\"\"## Dictionaries and Arrays\n\nArrays can appear as values in a dictionary. For example, if you are given a dictionary that maps from letters to frequencies, you might want to invert it—that is, create a dictionary that maps from frequencies to letters. Since there might be several letters with the same frequency, each value in the inverted dictionary should be an array of letters.\n\nHere is a function that inverts a dictionary:\n\n```julia\nfunction invertdict(d) \n\tinverse = Dict()\n\tfor key in keys(d) \n\t\tval = d[key]\n\t\tif val ∉ keys(inverse) \n\t\t\tinverse[val] = [key]\n\t\telse\n\t\t\tpush!(inverse[val], key) \n\t\tend\n\tend\n\tinverse\nend\n```\n\nEach time through the loop, `key` gets a key from `d` and `val` gets the corresponding value. If `val` is not in `inverse`, that means we haven’t seen it before, so we create a new item and initialize it with a *singleton* (an array that contains a single element). Otherwise, we have seen this value before, so we append the corresponding key to the array.\n\nHere is an example:\n\n```julia\njulia> hist = histogram(\"parrot\");\n\njulia> inverse = invertdict(hist) Dict{Any,Any} with 2 entries:\n 2 => ['r']\n 1 => ['a', 'p', 'o', 't']\n```\n\nFigure 11-1 is a state diagram showing `hist` and `inverse`. A dictionary is represented as a box with the key-value pairs inside. If the values are integers, floats, or strings, I draw them inside the box, but I usually draw arrays outside the box, just to keep the diagram simple.\n\"\"\"\n\n# ╔═╡ 4fb90040-85cb-11eb-23dd-ad9ea62b94c3\nDrawing(width=720, height=150) do\n\tdefs() do\n marker(id=\"arrow\", markerWidth=\"10\", markerHeight=\"10\", refX=\"0\", refY=\"3\", orient=\"auto\", markerUnits=\"strokeWidth\") do\n \t\tpath(d=\"M0,0 L0,6 L9,3 z\", fill=\"black\")\n\t\tend\n\tend\n\ttext(x=105, y=80, font_family=\"JuliaMono, monospace\", text_anchor=\"end\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"hist ->\") \n\tend\n\trect(x=120, y=20, width=150, height=110, fill=\"rgb(242, 242, 242)\", stroke=\"black\")\n\ttext(x=140, y=40, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"'o'\") \n\tend\n\tline(x1=170, y1=35, x2=220, y2=35, stroke=\"black\", marker_end=\"url(#arrow)\")\n\ttext(x=240, y=40, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"1\") \n\tend\n\ttext(x=140, y=60, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"'a'\") \n\tend\n\tline(x1=170, y1=55, x2=220, y2=55, stroke=\"black\", marker_end=\"url(#arrow)\")\n\ttext(x=240, y=60, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"1\") \n\tend\n\ttext(x=140, y=80, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"'p'\") \n\tend\n\ttext(x=140, y=100, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"'t'\") \n\tend\n\ttext(x=140, y=120, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"'r'\") \n\tend\n\tline(x1=170, y1=115, x2=220, y2=115, stroke=\"black\", marker_end=\"url(#arrow)\")\n\ttext(x=240, y=120, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"2\") \n\tend\n\tline(x1=170, y1=95, x2=220, y2=95, stroke=\"black\", marker_end=\"url(#arrow)\")\n\ttext(x=240, y=100, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"1\") \n\tend\n\tline(x1=170, y1=75, x2=220, y2=75, stroke=\"black\", marker_end=\"url(#arrow)\")\n\ttext(x=240, y=80, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"1\") \n\tend\n\ttext(x=410, y=80, font_family=\"JuliaMono, monospace\", text_anchor=\"end\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"inverse ->\") \n\tend\n rect(x=520, y=10, width=150, height=90, fill=\"rgb(242, 242, 242)\", stroke=\"black\")\n\ttext(x=540, y=30, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"1\") \n\tend\n\tline(x1=560, y1=25, x2=610, y2=25, stroke=\"black\", marker_end=\"url(#arrow)\")\n\ttext(x=630, y=30, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"'o'\") \n\tend\n\ttext(x=540, y=50, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"2\") \n\tend\n\tline(x1=560, y1=45, x2=610, y2=45, stroke=\"black\", marker_end=\"url(#arrow)\")\n\ttext(x=630, y=50, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"'a'\") \n\tend\n\ttext(x=540, y=70, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"3\") \n\tend\n\tline(x1=560, y1=65, x2=610, y2=65, stroke=\"black\", marker_end=\"url(#arrow)\")\n\ttext(x=630, y=70, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"'p'\") \n\tend\n\ttext(x=540, y=90, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"4\") \n\tend\n\tline(x1=560, y1=85, x2=610, y2=85, stroke=\"black\", marker_end=\"url(#arrow)\")\n\ttext(x=630, y=90, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"'t'\") \n\tend\n\trect(x=520, y=110, width=150, height=30, fill=\"rgb(242, 242, 242)\", stroke=\"black\")\n\ttext(x=540, y=130, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"1\") \n\tend\n\tline(x1=560, y1=125, x2=610, y2=125, stroke=\"black\", marker_end=\"url(#arrow)\")\n\ttext(x=630, y=130, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"'r'\") \n\tend\n\trect(x=420, y=10, width=50, height=130, fill=\"rgb(242, 242, 242)\", stroke=\"black\")\n\ttext(x=440, y=60, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"1\") \n\tend\n\tline(x1=460, y1=55, x2=510, y2=55, stroke=\"black\", marker_end=\"url(#arrow)\")\n\ttext(x=440, y=130, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"2\") \n\tend\n\tline(x1=460, y1=125, x2=510, y2=125, stroke=\"black\", marker_end=\"url(#arrow)\")\nend\n\n# ╔═╡ 26c0d704-85cf-11eb-2a13-293b42210e70\nmd\"*Figure 11-1. State diagram.*\"\n\n# ╔═╡ 35e8ee92-85cf-11eb-215c-21912c5fc92b\nmd\"\"\"!!! note\n I mentioned earlier that a dictionary is implemented using a hash table. That means that the keys have to be *hashable*.\n \n A *hash* is a function that takes a value (of any kind) and returns an integer. Dictionaries use these integers, called hash values, to store and look up key-value pairs.\n\"\"\"\n\n# ╔═╡ 8316e7a0-85cf-11eb-2ecb-df63279cadc6\nmd\"\"\"## Memos\n\nIf you played with the `fibonacci` function from “One More Example”, you might have noticed that the bigger the argument you provide, the longer the function takes to run. Furthermore, the runtime increases quickly.\n\nTo understand why, consider Figure 11-2, which shows the *call graph* for `fibonacci` with `n = 4`.\n\"\"\"\n\n# ╔═╡ c1e519e8-85cf-11eb-2ce1-4bcd389f56bf\nDrawing(width=720, height=310) do\n\tdefs() do\n marker(id=\"arrow\", markerWidth=\"10\", markerHeight=\"10\", refX=\"0\", refY=\"3\", orient=\"auto\", markerUnits=\"strokeWidth\") do\n \t\tpath(d=\"M0,0 L0,6 L9,3 z\", fill=\"black\")\n\t\tend\n\tend\n\trect(x=310, y=10, width=100, height=50, fill=\"rgb(242, 242, 242)\", stroke=\"black\")\n\ttext(x=325, y=30, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"fibonacci\") \n\tend\n\ttext(x=325, y=50, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"n\") \n\tend\n\tline(x1=340, y1=45, x2=375, y2=45, stroke=\"black\", marker_end=\"url(#arrow)\")\n\ttext(x=390, y=50, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"4\") \n\tend\n\tline(x1=310, y1=60, x2=260, y2=85, stroke=\"black\", marker_end=\"url(#arrow)\")\n\tline(x1=410, y1=60, x2=460, y2=85, stroke=\"black\", marker_end=\"url(#arrow)\")\n\trect(x=150, y=90, width=100, height=50, fill=\"rgb(242, 242, 242)\", stroke=\"black\")\n\ttext(x=165, y=110, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"fibonacci\") \n\tend\n\ttext(x=165, y=130, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"n\") \n\tend\n\tline(x1=180, y1=125, x2=215, y2=125, stroke=\"black\", marker_end=\"url(#arrow)\")\n\ttext(x=230, y=130, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"3\") \n\tend\n\tline(x1=150, y1=140, x2=130, y2=162, stroke=\"black\", marker_end=\"url(#arrow)\")\n\trect(x=75, y=170, width=100, height=50, fill=\"rgb(242, 242, 242)\", stroke=\"black\")\n\ttext(x=90, y=190, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"fibonacci\") \n\tend\n\ttext(x=90, y=210, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"n\") \n\tend\n\tline(x1=105, y1=205, x2=140, y2=205, stroke=\"black\", marker_end=\"url(#arrow)\")\n\ttext(x=155, y=210, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"2\") \n\tend\n\tline(x1=250, y1=140, x2=270, y2=162, stroke=\"black\", marker_end=\"url(#arrow)\")\n\trect(x=225, y=170, width=100, height=50, fill=\"rgb(242, 242, 242)\", stroke=\"black\")\n\ttext(x=240, y=190, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"fibonacci\") \n\tend\n\ttext(x=240, y=210, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"n\") \n\tend\n\tline(x1=255, y1=205, x2=290, y2=205, stroke=\"black\", marker_end=\"url(#arrow)\")\n\ttext(x=305, y=210, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"1\") \n\tend\n\tline(x1=75, y1=220, x2=53, y2=242, stroke=\"black\", marker_end=\"url(#arrow)\")\n\trect(x=0, y=250, width=100, height=50, fill=\"rgb(242, 242, 242)\", stroke=\"black\")\n\ttext(x=15, y=270, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"fibonacci\") \n\tend\n\ttext(x=15, y=290, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"n\") \n\tend\n\tline(x1=30, y1=285, x2=65, y2=285, stroke=\"black\", marker_end=\"url(#arrow)\")\n\ttext(x=80, y=290, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"1\") \n\tend\n\tline(x1=175, y1=220, x2=197, y2=242, stroke=\"black\", marker_end=\"url(#arrow)\")\n\trect(x=150, y=250, width=100, height=50, fill=\"rgb(242, 242, 242)\", stroke=\"black\")\n\ttext(x=150+15, y=270, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"fibonacci\") \n\tend\n\ttext(x=150+15, y=290, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"n\") \n\tend\n\tline(x1=150+30, y1=285, x2=150+65, y2=285, stroke=\"black\", marker_end=\"url(#arrow)\")\n\ttext(x=150+80, y=290, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"0\") \n\tend\n\trect(x=470, y=90, width=100, height=50, fill=\"rgb(242, 242, 242)\", stroke=\"black\")\n\ttext(x=485, y=110, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"fibonacci\") \n\tend\n\ttext(x=485, y=130, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"n\") \n\tend\n\tline(x1=500, y1=125, x2=535, y2=125, stroke=\"black\", marker_end=\"url(#arrow)\")\n\ttext(x=550, y=130, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"2\") \n\tend\n\tline(x1=570, y1=140, x2=590, y2=162, stroke=\"black\", marker_end=\"url(#arrow)\")\n\trect(x=720-175, y=170, width=100, height=50, fill=\"rgb(242, 242, 242)\", stroke=\"black\")\n\ttext(x=720-175+15, y=190, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"fibonacci\") \n\tend\n\ttext(x=720-175+15, y=210, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"n\") \n\tend\n\tline(x1=720-175+30, y1=205, x2=720-175+65, y2=205, stroke=\"black\", marker_end=\"url(#arrow)\")\n\ttext(x=720-175+80, y=210, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"0\") \n\tend\n\tline(x1=470, y1=140, x2=450, y2=162, stroke=\"black\", marker_end=\"url(#arrow)\")\n\trect(x=720-325, y=170, width=100, height=50, fill=\"rgb(242, 242, 242)\", stroke=\"black\")\n\ttext(x=720-325+15, y=190, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"fibonacci\") \n\tend\n\ttext(x=720-325+15, y=210, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"n\") \n\tend\n\tline(x1=720-325+30, y1=205, x2=720-325+65, y2=205, stroke=\"black\", marker_end=\"url(#arrow)\")\n\ttext(x=720-325+80, y=210, font_family=\"JuliaMono, monospace\", font_size=\"0.85rem\", font_weight=600) do \n\t\tstr(\"1\") \n\tend\nend\n\n# ╔═╡ 2a7646fe-85d9-11eb-3bbe-95f975f3901f\nmd\"*Figure 11-2. Call graph.*\"\n\n# ╔═╡ 388a8d90-85d9-11eb-08f1-6b622cfb2c11\nmd\"\"\"A call graph shows a set of function frames, with lines connecting each frame to the frames of the functions it calls. At the top of the graph, `fibonacci` with `n = 4` calls `fibonacci` with `n = 3` and `n = 2`. In turn, `fibonacci` with `n = 3` calls `fibonacci` with `n = 2`and `n = 1`, and so on.\n\nCount how many times `fibonacci(0)` and `fibonacci(1)` are called. This is an inefficient solution to the problem, and it gets worse as the argument gets bigger.\n\nOne solution is to keep track of values that have already been computed by storing them in a dictionary. A previously computed value that is stored for later use is called a *memo*. Here is a “memoized” version of `fibonacci`:\n\n```julia\nconst known = Dict(0=>0, 1=>1)\n\nfunction fibonacci(n) \n\tif n ∈ keys(known)\n\t\treturn known[n] \n\tend\n res = fibonacci(n-1) + fibonacci(n-2)\n\tknown[n] = res\n\tres\nend\n```\n\n`known` is a constant dictionary that keeps track of the Fibonacci numbers we already know. It starts with two items: `0` maps to `0` and `1` maps to `1`.\n\nWhenever `fibonacci` is called, it checks `known`. If the result is already there, it can return immediately. Otherwise, it has to compute the new value, add it to the dictionary, and return it.\n\nIf you run this version of `fibonacci` and compare it with the original, you will find that it is much faster.\n\"\"\"\n\n# ╔═╡ 170c40ea-85da-11eb-2079-a912e41da021\nmd\"\"\"## Global Variables\n\nIn the previous example, `known` is created outside the function, so it belongs to the special frame called `Main`. Variables in `Main` are sometimes called *global* because they can be accessed from any function. Unlike local variables, which disappear when their function ends, global variables persist from one function call to the next.\n\nFor performance reasons, you should declare a global variable *constant* with the keyword `const`. You can no longer reassign the variable, but if it refers to a mutable value, you can modify the value.\n\n!!! danger\n Global variables can be useful, but if you have a lot of them, and you modify them frequently, they can make programs hard to debug and perform badly.\n\"\"\"\n\n# ╔═╡ 698eb48a-85da-11eb-272f-157bb3fec731\nmd\"\"\"## Debugging\n\nAs you work with bigger datasets, it can become unwieldy to debug by printing and checking the output by hand. Here are some suggestions for debugging large datasets:\n* Scale down the input.\n \n If possible, reduce the size of the dataset. For example, if the program reads a text file, start with just the first 10 lines, or with the smallest example you can find that errors. You should not edit the files themselves, but rather modify the pro‐ gram so it reads only the first n lines.\n \n If there is an error, you can reduce n to the smallest value that manifests the error, and then increase it gradually as you find and correct errors.\n\n* Check summaries and types.\n \n Instead of printing and checking the entire dataset, consider printing summaries of the data: for example, the number of items in a dictionary or the total of an array of numbers.\n \n A common cause of runtime errors is a value that is not the right type. For debugging this kind of error, it is often enough to print the type of a value.\n \n* Write self-checks.\n \n Sometimes you can write code to check for errors automatically. For example, if you are computing the average of an array of numbers, you could check that the result is not greater than the largest element in the array or less than the smallest. This is called a “sanity check.”\n \n Another kind of check compares the results of two different computations to see if they are consistent. This is called a “consistency check.”\n \n* Format the output.\n\n Formatting debugging output can make it easier to spot an error. We saw an example in “Debugging”.\n \n Again, time you spend building scaffolding can reduce the time you spend debugging.\n\"\"\"\n\n# ╔═╡ 057b7444-85db-11eb-1dc3-179e19732c1c\nmd\"\"\"## Glossary\n\n*dictionary*:\nA mapping from keys to their corresponding values.\n\n*key*:\nAn object that appears in a dictionary as the first part of a key-value pair.\n\n*value*:\nAn object that appears in a dictionary as the second part of a key-value pair. This is more specific than our previous use of the word “value.”\n\n*key-value pair*:\nThe representation of the mapping from a key to a value.\n\n*item*:\nIn a dictionary, another name for a key-value pair.\n\n*mapping*:\nA relationship in which each element of one set corresponds to an element of another set.\n\n*hash table*:\nThe algorithm used to implement Julia dictionaries.\n\n*implementation*:\nA way of performing a computation.\n\n*lookup*:\nA dictionary operation that takes a key and finds the corresponding value.\n\n*reverse lookup*:\nA dictionary operation that takes a value and finds one or more keys that map to it.\n\n*singleton*:\nAn array (or other sequence) with a single element.\n\n*hashable*:\nA type that has a hash function.\n\n*hash function*:\nA function used by a hash table to compute the location for a key.\n\n*call graph*:\nA diagram that shows every frame created during the execution of a program, with an arrow from each caller to each callee.\n\n*memo*:\nA computed value stored to avoid unnecessary future computation.\n\n*global variable*:\nA variable defined outside a function. Global variables can be accessed from any function.\n\n*constant global variable*\nA global variable that cannot be reassigned.\n\"\"\"\n\n# ╔═╡ 64397616-85db-11eb-0150-fd07faf0ee9b\nmd\"\"\"## Exercises \n\n#### Exercise 11-2\n\nWrite a function that reads the words in words.txt and stores them as keys in a dictionary. It doesn’t matter what the values are. Then you can use the `∈` operator as a fast way to check whether a string is in the dictionar.\n\nIf you did “Exercise 10-10”, you can compare the speed of this implementation with the array `∈` operator and the bisection search.\n\"\"\"\n\n# ╔═╡ 9513aed2-85db-11eb-19ee-dd547267503b\nmd\"\"\"#### Exercise 11-3\n\nRead the documentation of the dictionary function `get!` and use it to write a more concise version of `invertdict`.\n\"\"\"\n\n# ╔═╡ a5cd8176-85db-11eb-193c-75864c42871e\nmd\"\"\"#### Exercise 11-4\n\nMemoize the Ackermann function from “Exercise 6-5” and see if memoization makes it possible to evaluate the function with bigger arguments.\n\"\"\"\n\n# ╔═╡ b8989c78-85db-11eb-3a4a-c3bb2dc3a988\nmd\"\"\"#### Exercise 11-5\n\nIf you did “Exercise 10-7”, you already have a function named `hasduplicates` that takes an array as a parameter and returns true if there is any object that appears more than once in the array.\n\n\nUse a dictionary to write a faster, simpler version of `hasduplicates`.\n\"\"\"\n\n# ╔═╡ d4c39484-85db-11eb-0ed1-a3268690454e\nmd\"\"\"#### Exercise 11-6\n\nTwo words are “rotate pairs” if you can rotate one of them and get the other (see rotateword in “Exercise 8-11”).\n\nWrite a program that reads a word array and finds all the rotate pairs.\n\"\"\"\n\n# ╔═╡ e388e7f8-85db-11eb-0451-df6af9de2adc\nmd\"\"\"#### Exercise 11-7\n\nHere’s another Puzzler from Car Talk:\n\n> [A contributor] came upon a common one-syllable, five-letter word recently that has the following unique property. When you remove the first letter, the remaining letters form a homophone of the original word, that is a word that sounds exactly the same. Replace the first letter, that is, put it back and remove the second letter and the result is yet another homophone of the original word. And the question is, what’s the word?\n> \n> Now I’m going to give you an example that doesn’t work. Let’s look at the five-letter word, ‘wrack.’ W-R-A-C-K, you know like to ‘wrack with pain.’ If I remove the first letter, I am left with a four-letter word, ‘R-A-C-K.’ As in, ‘Holy cow, did you see the rack on that buck! It must have been a nine-pointer!’ It’s a perfect homophone. If you put the ‘w’ back, and remove the ‘r,’ instead, you’re left with the word, ‘wack,’ which is a real word, it’s just not a homophone of the other two words.\n> \n> But there is, however, at least one word that [I] know of, which will yield two homophones if you remove either of the first two letters to make two, new four-letter words. The question is, what’s the word?\n\nYou can use the dictionary from “Exercise 11-2” to check whether a string is in the word array.\n!!! tip\n To check whether two words are homophones, you can use the Carnegie Mellon University Pronouncing Dictionary.\n\nWrite a program that lists all the words that solve the Puzzler.\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─bcaefa4e-85c6-11eb-3316-0db4881ebd30\n# ╟─13d62b06-85c7-11eb-00b9-0399467b1ab5\n# ╟─1f1c885e-85c7-11eb-1452-13a8943ebc90\n# ╟─27e4cf0c-85c8-11eb-0d95-ab9ddc845387\n# ╟─c8dff15e-85c8-11eb-1230-bd39702cf460\n# ╟─0b2e93b0-85c9-11eb-0dc3-61b1cbfb022b\n# ╟─82a2f936-85c9-11eb-1d33-0d9dc98fdac0\n# ╟─6d87ad02-85ca-11eb-2a3d-999d28a7c4b7\n# ╟─4fb90040-85cb-11eb-23dd-ad9ea62b94c3\n# ╟─26c0d704-85cf-11eb-2a13-293b42210e70\n# ╟─35e8ee92-85cf-11eb-215c-21912c5fc92b\n# ╟─8316e7a0-85cf-11eb-2ecb-df63279cadc6\n# ╟─c1e519e8-85cf-11eb-2ce1-4bcd389f56bf\n# ╟─2a7646fe-85d9-11eb-3bbe-95f975f3901f\n# ╟─388a8d90-85d9-11eb-08f1-6b622cfb2c11\n# ╟─170c40ea-85da-11eb-2079-a912e41da021\n# ╟─698eb48a-85da-11eb-272f-157bb3fec731\n# ╟─057b7444-85db-11eb-1dc3-179e19732c1c\n# ╟─64397616-85db-11eb-0150-fd07faf0ee9b\n# ╟─9513aed2-85db-11eb-19ee-dd547267503b\n# ╟─a5cd8176-85db-11eb-193c-75864c42871e\n# ╟─b8989c78-85db-11eb-3a4a-c3bb2dc3a988\n# ╟─d4c39484-85db-11eb-0ed1-a3268690454e\n# ╟─e388e7f8-85db-11eb-0451-df6af9de2adc\n", "meta": {"hexsha": "331020eb76b3a3e8193d7543cccf495d74fcbe6c", "size": 31050, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Lectures/Lecture11.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/Lecture11.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/Lecture11.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": 41.1803713528, "max_line_length": 500, "alphanum_fraction": 0.7150402576, "num_tokens": 9936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3849121303722487, "lm_q2_score": 0.20689405370611846, "lm_q1q2_score": 0.07963603097337249}} {"text": "### A Pluto.jl notebook ###\n# v0.14.1\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 000c1c07-fd7a-4e08-9e36-3f0aa6069309\nbegin\n\tusing PlutoUI\n\t\n\tusing CSV, DataFrames, Pipe, TabularDisplay\n\tusing Plots, StatsPlots\nend\n\n# ╔═╡ 578530b0-9b50-11eb-07e1-5db7ceb1b1c7\nmd\"\"\"\n## Data wrangling in Julia\n\nBased on presentations by Tom Kwong:\n - [Data Wrangling Techniques in Julia - Part 1](https://www.youtube.com/watch?v=txme9o0EdLk) \n - [Data Wrangling Techniques in Julia - Part 2](https://www.youtube.com/watch?v=NbqQZq42gLc)\n\n\n$(html\"
© Pascal, April 2021
\")\n\"\"\"\n\n# ╔═╡ 6bcfba84-98ab-4d26-b98c-d86cb65dc277\nPlutoUI.TableOfContents(indent=true, depth=4, aside=true)\n\n# ╔═╡ f88a1737-7a84-4103-82c8-1920bae6b2e8\nmd\"\"\"\n### What is data wrangling?\n\nTake raw data (and/or unorganized data) and turn them (data as plural of datum) into something useful.\n\nA possible data wrangling is as follows:\n\n\n read | $\\Rightarrow$ | clean | $\\Rightarrow$ | Tidy \n --- | --- | --- | --- | --- \n | | $\\Uparrow$ | | $\\Downarrow$ \n | | **Visualize** | $\\Leftarrow$ | **Analyze** \n\n\n**Julia ecosystem**:\n\nRead | Clean, Tidy, Analyze | Visualize\n--- | --- | --- |\nCSV | DataFrames| Plots, StatsPlots\nParquet | DataFramesMeta | Makie, StatsMakie\nSASLib | Query| Gadfly\nReadStat | JuliaDB, JuliaDBMeta | Gaston\nJSON, JSON2/3 | | VegaLite\nLightXML, EzXML | | UnicodePlots\nXLSX, ExcelReader, Taro | | \nPDFIO | |\n\"\"\"\n\n# ╔═╡ 02ac758d-3706-4bf4-8a36-83aff4422d0e\nmd\"\"\"\n### Read\n\nUtilize automated tools to read data into memory as cleanly as possible.\n\n`CSV.jl`:\n - Skip leading/trailing rows\n - Parse missing values e.g \"NA\"\n - Parse date/time values\n - Normalize columns\n - Select/drop columns on read\n - User specified column types\n - Auto-delimiter detection\n - Automatic pooled string columns\n - Parse booleans\n - Transpose data\n\"\"\"\n\n# ╔═╡ fb1f4efc-6b89-48a6-95d5-8e3661edf53d\nmd\"\"\"\n### Clean\n\n - Delete unwanted columns\n - Delete rows with missing data\n - Rename columns\n - Fix column data type\n - ...\n\nExamples\n```julia\ndescribe(df) # take a quick peek\n\nselect!(df, 1:5) # keep \"good\" columns / delete unwanted ones \nselect!(df, Not([\"garbaggecol1\", \"garbaggecol2\"]))\n\n\nrename!(df, \"Region Name\" => :region_name)\n\ndropmissing!(df) # Remove rows with missing data\ndropmissing!(df, Between(:x3, :x5))\n```\n\n\"\"\"\n\n# ╔═╡ f22c3d88-e0e6-4d1d-92d4-c99f80aa4733\nmd\"\"\"\n### Tidy Data\n\n - Each variable forms a *column*\n - Each observation forms a *row*\n - Each type of observational unit forms a *table*\n\n\n**Tidy Recipes, examples:**\n\n```julia\n# Stack all date columns into rows\n# The column names are stored ion a new column \"Date\"\nsdf = stack(df, Not(:Region_name); variable_name=:Date)\nsdf = stack(df, Not(1); variable_name=:Date)\nsdf = stack(df, 2:5; variable_name=:Date)\n\n# Date column is a CategoricalArray type. Make it Date type\nsdf.Date = [Date(get(x)) for x ∈ sdf.Date]\n# or maybe using broadcast:\nsdf.Date .= get.(sdf.Data) .|> Date\n\n# Hoe to turn it back to a wide format?\ndf2 = unstack(sdf, :date, :value)\n\n# It may introduce Union{Missing, T} column type. Let's fix it.\ndisallowmissing!(df2, 2:5)\n```\n\"\"\"\n\n# ╔═╡ 2dc07426-ad94-46a0-8da2-68d687ad87c2\nmd\"\"\"\n### Analyze\n\nGet some insights from data. \n\n**Analuyze Recipe**:\n\n```julia\nselct(df, :region_name, 4:5) # select by column\n\nfilter(:region_name => ==(\"Abilene, TX\"), df) # note df is the 2nd arg here\nfilter(\"2020-01-31\" => >(400_000), df)\n\nsort(df, :region_name)\nsort(df, :region_name, rev=true)\n\n# Transform means adding new columns - many more ways of using Transform\ntransform(df, :region_name => ByRow(length) => :region_name_len)\n\n# Group\ngroupby(sdf, :Date)\n\n# Summarize the grouped data:\ncombine(groupby(sdf, :Date), :value => mean => :avg)\n\n# Using Pipe.jl to build a transformation pipeline\n@pipe sdf |>\n groupby(_, :Date) |>\n\tcombine(_, :value => mean => :avg)\n\ncountry = DataFrame(Name=[\"United States\"])\n\n# Joining data is easy\ninnerjoin(df, country, on=[:region_name => :name])\nleftjoin(df, country, on=[:region_name => :name])\nrightjoin(df, country, on=[:region_name => :name])\nouterjoin(df, country, on=[:region_name => :name])\n\n# Also\nsemijoin(df, country, on=[:region_name => :name])\nantijoin(df, country, on=[:region_name => :name])\n```\n\"\"\"\n\n# ╔═╡ cb11e3e6-f385-44db-b739-cf056a7f8841\nmd\"\"\"\n### Visualize\n\nGain more insight by looking at the data in a graphical form.\n\n\n**Visualize Recipes:**\n\n`Plots.jl` | `StatsPlots.jl`\n--- | ---\n`plot` | `groupedbar`\n`scatter` | `corrplot`\n`histogram` | `marginhist`\n`heatmap` | `boxplot`\n`bar` | `violin`\n... | ...\n\n\"\"\"\n\n# ╔═╡ 944f1843-1802-45b7-a505-8bb32ad09902\nmd\"\"\"\n## Let's practice\n\n### Tidying\n\"\"\"\n\n# ╔═╡ f9d0761d-a859-404a-812f-f2a424c7b191\nbegin\n\tdf = CSV.File(\"data/youth_suicide.csv\", header=true) |> DataFrame;\n\tsize(df)\nend\n\n# ╔═╡ 6790c878-d494-4247-ab1a-d5122d3d845b\nfirst(df, 5)\n\n# ╔═╡ ff4cc1c3-5967-4614-82eb-cc8771e962dc\nnames(df)\n\n# ╔═╡ 5315e6b5-344e-42e7-a9a7-b53cfaf2b5b5\nwith_terminal() do\n\tdisplaytable(names(df), index=true)\nend\n\n# ╔═╡ 8083c3d3-51f6-437e-ba12-38f8b5814e1e\ndescribe(df, :eltype, :nmissing, :first => first)\n\n# ╔═╡ e70b9da8-34f9-4193-a86e-5e7dc9ed23aa\n## turn colums 2 to 19 to row (observations)\nsdf = stack(df, 2:19; variable_name=:type_year);\n\n# ╔═╡ e783b82c-052e-49d3-87c8-70142b990d5f\nsize(sdf)\n\n# ╔═╡ e9d507d7-df67-4bd4-b80b-02385b2f9be5\nbegin\n\t## Now spread content of column `:type_year` into 2 separate columns\n\tsdf[!, :ctype] .= split.(sdf.type_year, \" \") .|> a -> getindex(a, 1)\n\tsdf[!, :year] .= split.(sdf.type_year, \" \") .|> a -> getindex(a, 2)\n\tselect!(sdf, Not(:type_year))\n\tfirst(sdf, 3)\nend\n\n# ╔═╡ 723dc0d9-96c4-43c0-81fd-611209e10106\n## Let's check if the Total type really contains the total\n## 1 - Pick a county\nsdf[sdf.County .== \"Yakima\", :]\n\n# ╔═╡ 0031eb09-8e5f-47fe-b04d-1600fad8f994\n## Remove the total row which is redundant\n\nsdf₁ = @pipe sdf |>\n\tfilter(:ctype => ≠(\"Total\"), _) |>\n\tfilter(:year => ≠(\"(2008-2012)\"), _);\n\n# ╔═╡ f8ee2398-2b69-4133-b2d6-11a2c12b9d27\nsdf₁[sdf₁.County .== \"Yakima\", :]\n\n# ╔═╡ c52c8ce7-c68b-4b7b-b507-5a813d32cf93\ndescribe(sdf₁)\n\n# ╔═╡ 4b14a6ad-6dc5-4319-95bf-007e84ae6877\nunique(sdf₁.year)\n## Now we want integer instead of string and we want to get rid of the parentheses.\n\n# ╔═╡ 54a8cfd0-5daa-40e3-8a0e-12413cc36e83\n## mutate column year from String to Int\nsdf₁[!, :year] .= replace.(sdf₁.year, r\"[\\(\\)]\" => \"\") |> a -> parse.(Int, a)\n\n# ╔═╡ 3378787b-c9cf-4d47-a119-2a35abc3b0b4\ndescribe(sdf₁, :eltype, :min, :max, :nunique, :nmissing)\n\n# ╔═╡ 53aa180c-7260-46cf-a2a3-4a49e0c30844\nbegin\n\t# Male and Female variables can be put back as columns now\n\tdf₁ = unstack(sdf₁, :ctype, :value)\n\tdf₁[df₁.County .== \"Yakima\", :]\nend\n\n# ╔═╡ 56d8dcc1-8b76-4332-bbe4-f7081e178300\nmd\"\"\"\n### Visualize\n\"\"\"\n\n# ╔═╡ 73a99bae-e8a6-44d1-af74-9778e17df7b9\n# Plot King county's yearly rate\nfilter(:County => ==(\"King\"), df₁)\n\n# ╔═╡ 5eaa88b0-95e4-4410-bd99-cb9ad40fdb79\n# bar chart\n@pipe df₁ |>\n\tfilter(:County => ==(\"King\"), _) |>\n\tbar(_.year, _.Male, \n title = \"King County Youth Suicides (Male)\",\n legend = :none,\n size = (450, 300))\n\n# ╔═╡ 5548eaac-d390-4cb1-bf49-0b8985c1f0f0\nbegin\n\t# Prepare to plot both Male and Female together\n\tdf_stacked = stack(df₁, 3:4; variable_name = \"gender\");\n\tnames(df_stacked)\nend\n\n# ╔═╡ bb947d94-62f3-45f6-a0d1-9ed596e289c8\n@pipe df_stacked |>\n\tfilter(:County => ==(\"King\"), _) |>\n\t groupedbar( # StatsPlots.jl\n\t\t_.year, # x-axis \n\t _.value; # y-axis\n group = _.gender,\n bar_position = :stack,\n bar_width = 0.7,\n title = \"King County Suicides\",\n size = (450, 300),\n legend = :topleft)\n\n# ╔═╡ 5fadd975-cbcf-4a0e-b493-0382875354ba\n@pipe df₁ |>\n groupby(_, :County)\n\n# ╔═╡ a92c1c18-39bd-4dcf-81a7-f2f62577e156\n# 5 year totals\n@pipe df₁ |>\n groupby(_, :County) |>\n combine(_, :Female => sum, :Male => sum)\n\n# ╔═╡ 2c21d894-7e57-4f92-b08d-a4d527f5c25a\n# 5 year totals with male/female combined\n@pipe df₁ |>\n groupby(_, :County) |>\n combine(_, :Female => sum, :Male => sum) |>\n select(_, :County, [:Female_sum, :Male_sum] => ByRow(+) => :Total)\n\n# ╔═╡ 72aeaa39-6529-4fc3-ba86-f2b113a5a075\nlet \n data₁ = @pipe df₁ |>\n groupby(_, :year) |>\n combine(_, :Female => sum => :Female, :Male => sum => :Male) |>\n stack(_, 2:3; variable_name = :gender, value_name = :suicides) \n\t\n plot(data₁.year, data₁.suicides; groups = data₁.gender,\n title = \"Youth Suicides Trend\",\n legend = :topleft,\n linewidth = 3,\n size = (450, 300))\nend\n\n# ╔═╡ a7802df0-6819-4650-a539-ccbb99333e92\nlet\n data₂ = @pipe df₁ |>\n select(_, :County, :year, [:Female, :Male] => ByRow(+) => :total) |>\n unstack(_, :year, :total)\n\t\n values = Matrix(data₂[:, 2:end])\n\t\n StatsPlots.heatmap(2008:2012, data₂.County, values;\n title = \"Youth Suicide Heatmap\",\n xticks = :all,\n yticks = :all,\n size = (400, 600))\nend\n\n# ╔═╡ 8018394c-a123-43c4-aaaf-3d942284e182\nhtml\"\"\"\n\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─578530b0-9b50-11eb-07e1-5db7ceb1b1c7\n# ╠═000c1c07-fd7a-4e08-9e36-3f0aa6069309\n# ╟─6bcfba84-98ab-4d26-b98c-d86cb65dc277\n# ╟─f88a1737-7a84-4103-82c8-1920bae6b2e8\n# ╟─02ac758d-3706-4bf4-8a36-83aff4422d0e\n# ╟─fb1f4efc-6b89-48a6-95d5-8e3661edf53d\n# ╟─f22c3d88-e0e6-4d1d-92d4-c99f80aa4733\n# ╟─2dc07426-ad94-46a0-8da2-68d687ad87c2\n# ╟─cb11e3e6-f385-44db-b739-cf056a7f8841\n# ╟─944f1843-1802-45b7-a505-8bb32ad09902\n# ╠═f9d0761d-a859-404a-812f-f2a424c7b191\n# ╠═6790c878-d494-4247-ab1a-d5122d3d845b\n# ╠═ff4cc1c3-5967-4614-82eb-cc8771e962dc\n# ╠═5315e6b5-344e-42e7-a9a7-b53cfaf2b5b5\n# ╠═8083c3d3-51f6-437e-ba12-38f8b5814e1e\n# ╠═e70b9da8-34f9-4193-a86e-5e7dc9ed23aa\n# ╠═e783b82c-052e-49d3-87c8-70142b990d5f\n# ╠═e9d507d7-df67-4bd4-b80b-02385b2f9be5\n# ╠═723dc0d9-96c4-43c0-81fd-611209e10106\n# ╠═0031eb09-8e5f-47fe-b04d-1600fad8f994\n# ╠═f8ee2398-2b69-4133-b2d6-11a2c12b9d27\n# ╠═c52c8ce7-c68b-4b7b-b507-5a813d32cf93\n# ╠═4b14a6ad-6dc5-4319-95bf-007e84ae6877\n# ╠═54a8cfd0-5daa-40e3-8a0e-12413cc36e83\n# ╠═3378787b-c9cf-4d47-a119-2a35abc3b0b4\n# ╠═53aa180c-7260-46cf-a2a3-4a49e0c30844\n# ╟─56d8dcc1-8b76-4332-bbe4-f7081e178300\n# ╠═73a99bae-e8a6-44d1-af74-9778e17df7b9\n# ╠═5eaa88b0-95e4-4410-bd99-cb9ad40fdb79\n# ╠═5548eaac-d390-4cb1-bf49-0b8985c1f0f0\n# ╠═bb947d94-62f3-45f6-a0d1-9ed596e289c8\n# ╠═5fadd975-cbcf-4a0e-b493-0382875354ba\n# ╠═a92c1c18-39bd-4dcf-81a7-f2f62577e156\n# ╠═2c21d894-7e57-4f92-b08d-a4d527f5c25a\n# ╠═72aeaa39-6529-4fc3-ba86-f2b113a5a075\n# ╠═a7802df0-6819-4650-a539-ccbb99333e92\n# ╟─8018394c-a123-43c4-aaaf-3d942284e182\n", "meta": {"hexsha": "8d03f9af8158aa606c21b62885711debbd32118d", "size": 10747, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Julia_Investigation/data_wrangling_with_julia.jl", "max_stars_repo_name": "pascal-p/julia-notebooks", "max_stars_repo_head_hexsha": "568c884c8b0de8ce34a84e8d1ce5fb6994cf32b8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-01T20:34:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-01T20:34:56.000Z", "max_issues_repo_path": "Julia_Investigation/data_wrangling_with_julia.jl", "max_issues_repo_name": "pascal-p/julia-notebooks", "max_issues_repo_head_hexsha": "568c884c8b0de8ce34a84e8d1ce5fb6994cf32b8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Julia_Investigation/data_wrangling_with_julia.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": 25.8341346154, "max_line_length": 102, "alphanum_fraction": 0.6655810924, "num_tokens": 4524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.403566839388498, "lm_q2_score": 0.19436782035217448, "lm_q1q2_score": 0.07844040693835844}} {"text": "### A Pluto.jl notebook ###\n# v0.12.7\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 845202ce-23d9-11eb-085e-ad2c26fd531c\nbegin\n\tusing TextAnalysis\n\tusing CSV\n\tusing DataFrames\nend\n\n# ╔═╡ cac12010-23d8-11eb-0321-3fc66858fc84\nmd\"# Authorship Analysis using TextAnalysis.jl\n\nIn this notebook we will implement an authorship analysis technique that uses n-gram frequencies for identifying authors. This technique is described in [Grieve 2018](https://research.birmingham.ac.uk/portal/files/53402456/Bixby_PREPRINT.pdf) The technique counts token and character n-grams and compares them to a reference corpus. It counts the number of overlapping n-grams in the reference corpus and identifies the author based on which reference corpus contains more of the n-grams from the text.\"\n\n# ╔═╡ f400d820-23d9-11eb-091a-898d693456ad\nmd\"First off, the necessary imports are made.\"\n\n# ╔═╡ c9d140dc-2463-11eb-06a2-2d0dcb8dbed2\nmd\"Our data will be from [Spooky Author Identification](https://www.kaggle.com/c/spooky-author-identification/overview) Kaggle contest. The data comes in the form of a CSV file which contains sentences attributed to one of three authors. The data was manualy cleaned to remove rows that were corropted as well as making sure that each author had approximately equal word counts.\n\nThe data is read into a dataframe after which we iterate over the df and turn each sentence into a StringDocument which is then accumalted into a Corpus for each author.\"\n\n# ╔═╡ 68255d02-23da-11eb-3232-613c0e1b0ee2\nreferenceData = CSV.read(\"train.csv\", DataFrame);\n\n# ╔═╡ c8b1e874-23e0-11eb-1aad-995c03f040ef\nbegin\n\tMWS = GenericDocument[]\n\tEAP = GenericDocument[]\n\tHPL = GenericDocument[]\n\t\n\tfor line in eachrow(referenceData)\n\t\tif line.author == \"MWS\"\n\t\t\tpush!(MWS, StringDocument(line.text))\n\t\telseif line.author == \"EAP\"\n\t\t\tpush!(EAP, StringDocument(line.text))\n\t\telse\n\t\t\tpush!(HPL, StringDocument(line.text))\n\t\tend\n\tend\n\t\n\tMWS_corpus = Corpus(MWS)\n\tEAP_corpus = Corpus(EAP)\n\tHPL_corpus = Corpus(HPL);\nend\n\n# ╔═╡ 60390844-2472-11eb-010b-d155abe74997\nmd\"The following code snippet allows one to retrieve the word count of a corpus. The word counts are as follows:\n- MWS_corpus: 147914\n- EAP_corpus: 147911\n- HPL_corpus: 147916\"\n\n# ╔═╡ 7b9ce77e-23e4-11eb-39d4-03e26b33cad7\nbegin\n\twordCount = 0\n\tfor doc in HPL_corpus\n\t\tglobal wordCount += length(ngrams(doc, 1))\n\tend\nend\n\n# ╔═╡ 43a58408-246f-11eb-29ab-91cc00373c2a\nwordCount\n\n# ╔═╡ 96f5d60a-248b-11eb-2795-a51a9fbf3fc0\nmd\"Now that we have our corpora it is time to extract the ngrams that are needed for the analysis. The original paper used both character ngrams and token ngrams. Due to TextAnalysis.jl's functionality I will be restricting this analysis to only using token ngrams.\"\n\n# ╔═╡ 95691ad4-2472-11eb-346e-07a9f5dc8f6c\nbegin\n\tMWS_ngrams = []\n\tHPL_ngrams = []\n\tEAP_ngrams = []\n\tfor i in 1:4\n\t\tpush!(MWS_ngrams, map(x -> ngrams(x,i), MWS_corpus))\n\t\tpush!(HPL_ngrams, map(x -> ngrams(x,i), HPL_corpus))\n\t\tpush!(EAP_ngrams, map(x -> ngrams(x,i), EAP_corpus))\n\tend\nend\n\n# ╔═╡ e207949e-2526-11eb-3ae4-0712b7082681\nmd\"We also retrieve the token ngrams from the files we want to analyze and classify.\"\n\n# ╔═╡ 62443a4c-2525-11eb-0e70-393860da7b4f\nbegin\n\t# first we load our files from memory\n\ttext1 = FileDocument(\"./MWS.txt\")\n\ttext2 = FileDocument(\"./HPL.txt\")\n\ttext3 = FileDocument(\"./EAP.txt\")\n\t\n\t# this is the same as retrieveing ngrams for the reference corpora\n\ttext1_ngrams = []\n\ttext2_ngrams = []\n\ttext3_ngrams = []\n\tfor i in 1:4\n\t\tpush!(text1_ngrams, ngrams(text1, i))\n\t\tpush!(text2_ngrams, ngrams(text2, i))\n\t\tpush!(text3_ngrams, ngrams(text3, i))\n\tend\nend\n\n# ╔═╡ 32909f1e-2527-11eb-0efd-6d81943df28e\nmd\"Finally we will a script that calculates the intersection of the ngrams from the text and the three reference corpora. To try different files edit the second for loop.\"\n\n# ╔═╡ 5d1320ee-2479-11eb-3664-c33f5ace1ba7\nbegin\n\tMWS_count = 0\n\tHPL_count = 0\n\tEAP_count = 0\n\tfor i in 1:4\n\t\tfor j in text1_ngrams[i]\n\t\t\tfor k in MWS_ngrams[i]\n\t\t\t\tif haskey(k, j[1])\n\t\t\t\t\tglobal MWS_count += 1\n\t\t\t\t\tbreak\n\t\t\t\tend\n\t\t\tend\n\t\t\tfor k in HPL_ngrams[i]\n\t\t\t\tif haskey(k, j[1])\n\t\t\t\t\tglobal HPL_count += 1\n\t\t\t\t\tbreak\n\t\t\t\tend\n\t\t\tend\n\t\t\tfor k in EAP_ngrams[i]\n\t\t\t\tif haskey(k, j[1])\n\t\t\t\t\tglobal EAP_count += 1\n\t\t\t\t\tbreak\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend\nend\n\n# ╔═╡ 16a5c100-252a-11eb-1258-b769d50904d3\nmd\"The following block will output the author as identified by this script.\nThe correct authors should be as follows:\n- text1 = MWS\n- text2 = HPL\n- text3 = EAP\"\n\n# ╔═╡ df84c6ee-247a-11eb-24f9-e92653c334bb\nbegin\n\tif MWS_count > HPL_count && MWS_count > EAP_count\n\t\t\"MWS\"\n\telseif HPL_count > MWS_count && HPL_count > EAP_count\n\t\t\"HPL\"\n\telse\n\t\t\"EAP\"\n\tend\nend\n\n# ╔═╡ 34de486c-252b-11eb-2071-f12f0f445d9f\nmd\"## Conclusion\nWhile this is a very watered down analysis of what the paper presents it is a good starting point and shows that this technique is viable as it correctly predicts the authors of our random test data. One way to improve the current analysis is to add character ngrams as the paper does.\n\nAll in all this was a fun project to learn more about Julia and its NLP cabalities. This project only scratches the surface of what Julia has to offer given that the TextAnalysis.jl package offers things such as part-of-speech(POS) tagging, tf-idf measures, a sentiment analysis model, and much more.\"\n\n# ╔═╡ Cell order:\n# ╟─cac12010-23d8-11eb-0321-3fc66858fc84\n# ╟─f400d820-23d9-11eb-091a-898d693456ad\n# ╠═845202ce-23d9-11eb-085e-ad2c26fd531c\n# ╟─c9d140dc-2463-11eb-06a2-2d0dcb8dbed2\n# ╠═68255d02-23da-11eb-3232-613c0e1b0ee2\n# ╠═c8b1e874-23e0-11eb-1aad-995c03f040ef\n# ╟─60390844-2472-11eb-010b-d155abe74997\n# ╠═7b9ce77e-23e4-11eb-39d4-03e26b33cad7\n# ╠═43a58408-246f-11eb-29ab-91cc00373c2a\n# ╟─96f5d60a-248b-11eb-2795-a51a9fbf3fc0\n# ╠═95691ad4-2472-11eb-346e-07a9f5dc8f6c\n# ╟─e207949e-2526-11eb-3ae4-0712b7082681\n# ╠═62443a4c-2525-11eb-0e70-393860da7b4f\n# ╟─32909f1e-2527-11eb-0efd-6d81943df28e\n# ╠═5d1320ee-2479-11eb-3664-c33f5ace1ba7\n# ╟─16a5c100-252a-11eb-1258-b769d50904d3\n# ╠═df84c6ee-247a-11eb-24f9-e92653c334bb\n# ╟─34de486c-252b-11eb-2071-f12f0f445d9f\n", "meta": {"hexsha": "17ee0f4c4eaed59de18824e270fed658999bcd44", "size": 6092, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Week2-TextAnalysis.jl/laurens777/notebook.jl", "max_stars_repo_name": "Humans-of-Julia/Challenges", "max_stars_repo_head_hexsha": "9efd04b90110e4c19456a6a75c3f137d613c92fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-11-15T04:08:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-15T08:01:32.000Z", "max_issues_repo_path": "Week2-TextAnalysis.jl/laurens777/notebook.jl", "max_issues_repo_name": "Humans-of-Julia/WeeklyContest", "max_issues_repo_head_hexsha": "9efd04b90110e4c19456a6a75c3f137d613c92fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Week2-TextAnalysis.jl/laurens777/notebook.jl", "max_forks_repo_name": "Humans-of-Julia/WeeklyContest", "max_forks_repo_head_hexsha": "9efd04b90110e4c19456a6a75c3f137d613c92fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-09T18:10:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-09T18:10:26.000Z", "avg_line_length": 34.0335195531, "max_line_length": 503, "alphanum_fraction": 0.7465528562, "num_tokens": 2241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.5, "lm_q2_score": 0.15203224354320868, "lm_q1q2_score": 0.07601612177160434}} {"text": "# Copyright (c) 2019 Arpit Bhatia and contributors #src\n# #src\n# Permission is hereby granted, free of charge, to any person obtaining a copy #src\n# of this software and associated documentation files (the \"Software\"), to deal #src\n# in the Software without restriction, including without limitation the rights #src\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #src\n# copies of the Software, and to permit persons to whom the Software is #src\n# furnished to do so, subject to the following conditions: #src\n# #src\n# The above copyright notice and this permission notice shall be included in all #src\n# copies or substantial portions of the Software. #src\n# #src\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #src\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #src\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #src\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #src\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #src\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #src\n# SOFTWARE. #src\n\n# # Getting started with Julia\n\n# Since JuMP is embedded in Julia, knowing some basic Julia is important\n# for learning JuMP. This tutorial is designed to provide a minimalist\n# crash course in the basics of Julia. You can find resources that provide\n# a more comprehensive introduction to Julia [here](https://julialang.org/learning/).\n\n# ## Installing Julia\n\n# To install Julia, [download the latest stable release](https://julialang.org/downloads/),\n# then follow the [platform specific install instructions](https://julialang.org/downloads/platform/).\n\n# !!! tip\n# Unless you know otherwise, you probably want the 64-bit version.\n\n# Next, you need an IDE to develop in. VS Code is a popular choice, so follow\n# [these install instructions](https://www.julia-vscode.org/docs/stable/gettingstarted/).\n\n# ## Numbers and arithmetic\n\n# Since we want to solve optimization problems, we're going to be using a lot of\n# math. Luckily, Julia is great for math, with all the usual operators:\n\n@show 1 + 1\n@show 1 - 2\n@show 2 * 2\n@show 4 / 5\n@show 3^2\nnothing #hide\n\n# !!! info\n# The `@` in front of something indicates that it is a macro, which is just\n# a special type of function. In this case, `@show` prints the expression as\n# typed (e.g., `1 - 2`), as well as the evaluation of the expression (`-1`).\n\n# Did you notice how Julia didn't print `.0` after some of the numbers? Julia is\n# a dynamic language, which means you never have to explictly declare the type\n# of a variable. However, in the background, Julia is giving each variable a\n# type. Check the type of something using the `typeof` function:\n\n@show typeof(1)\n@show typeof(1.0)\nnothing #hide\n\n# Here `1` is an `Int64`, which is an integer with 64 bits of precision, and\n# `1.0` is a `Float64`, which is a floating point number with 64-bits of\n# precision.\n\n# !!! tip\n# If you aren't familiar with floating point numbers, make sure to read\n# the [Floating point numbers](@ref) section.\n\n# We create complex numbers using `im`:\n\nx = 2 + 1im\n@show real(x)\n@show imag(x)\n@show typeof(x)\n@show x * (1 - 2im)\nnothing #hide\n\n# !!! info\n# The curly brackets surround what we call the _parameters_ of a type. You\n# can read `Complex{Int64}` as \"a complex number, where the real and\n# imaginary parts are represented by `Int64`.\" If we call\n# `typeof(1.0 + 2.0im)` it will be `Complex{Float64}`, which a complex\n# number with the parts represented by `Float64`.\n\n# There are also some cool things like an irrational representation of π.\n\nπ\n\n# !!! tip\n# To make π (and most other greek letters), type `\\pi` and then press\n# `[TAB]`.\n\ntypeof(π)\n\n# Athough if we do math with irrational numbers, they get converted to\n# `Float64`:\n\ntypeof(2π / 3)\n\n# ### Floating point numbers\n\n# !!! warning\n# If you aren't familiar with floating point numbers, make sure to read this\n# section carefully.\n\n# A `Float64` is a [floating point](https://en.wikipedia.org/wiki/Floating-point_arithmetic)\n# approximation of a real number using 64-bits of information.\n\n# Because it is an approximation, things we know hold true in mathematics don't\n# hold true in a computer! For example:\n\n0.1 * 3 == 0.3\n\n#- A more complicated example is:\n\nsin(2π / 3) == √3 / 2\n\n# !!! tip\n# Get `√` by typing `\\sqrt` then press `[TAB]`.\n\n# Let's see what the differences are:\n\n0.1 * 3 - 0.3\n\n#-\n\nsin(2π / 3) - √3 / 2\n\n# They are small, but not zero!\n\n# One way of explaining this difference is to consider how we would write\n# `1 / 3` and `2 / 3` using only four digits after the decimal point. We would\n# write `1 / 3` as `0.3333`, and `2 / 3` as `0.6667`. So, depiste the fact that\n# `2 * (1 / 3) == 2 / 3`, `2 * 0.3333 == 0.6666 != 0.6667`.\n\n# Let's try that again using ≈ (`\\approx + [TAB]`) instead of `==`:\n\n0.1 * 3 ≈ 0.3\n\n#-\n\nsin(2π / 3) ≈ √3 / 2\n\n# `≈` is just a clever way of calling the `isapprox` function:\n\nisapprox(sin(2π / 3), √3 / 2; atol = 1e-8)\n\n# !!! warning\n# Floating point is the reason solvers use tolerances when they solve\n# optimization models. A common mistake you're likely to make is checking\n# whether a binary variable is 0 using `value(z) == 0`. Always remember to\n# use something like `isapprox` when comparing floating point numbers.\n#\n# Gurobi has a [good series of articles](https://www.gurobi.com/documentation/9.0/refman/num_grb_guidelines_for_num.html)\n# on the implications of floating point in optimization if you want to read\n# more.\n\n# If you aren't careful, floating point arithmetic can throw up all manner of\n# issues. For example:\n\n1 + 1e-16 == 1\n\n# It even turns out that floating point numbers aren't associative!\n\n(1 + 1e-16) - 1e-16 == 1 + (1e-16 - 1e-16)\n\n# It's important to note that this issue isn't Julia-specific. It happens in\n# every programming language (try it out in Python).\n\n# ## Vectors, matrices and arrays\n\n# Similar to Matlab, Julia has native support for vectors, matrices and tensors;\n# all of which are represented by arrays of different dimensions. Vectors are\n# constructed by comma-separated elements surrounded by square brackets:\n\nb = [5, 6]\n\n# !!! info\n# `Array{Int64, 1}` means that this is an `Array`, with `Int64` elements,\n# and it has `1` dimension.\n\n# Matrices can by constructed with spaces separating the columns, and semicolons\n# separating the rows:\n\nA = [1.0 2.0; 3.0 4.0]\n\n# Note how this time the type is `Array{Float64, 2}`; the elements are `Float64`\n# and there are `2` dimenions.\n\n# We can do linear algebra:\n\nx = A \\ b\n\n# !!! info\n# Here is floating point at work again! `x` is approximately `[-4, 4.5]`.\n\n#-\n\nA * x\n\n#-\n\nA * x ≈ b\n\n# Note that when multiplying vectors and matrices, dimensions matter. For\n# example, you can't multiply a vector by a vector:\n\ntry #hide\nb * b\ncatch err; showerror(stderr, err); end #hide\n\n# But multiplying transposes works:\n\nb' * b\n\n#-\n\nb * b'\n\n# ## Other common types\n\n# ### Strings\n\n# Double quotes are used for strings:\n\ntypeof(\"This is Julia\")\n\n# Unicode is fine in strings:\n\ntypeof(\"π is about 3.1415\")\n\n# Use [`println`](https://docs.julialang.org/en/v1/base/io-network/#Base.println)\n# to print a string:\n\nprintln(\"Hello, World!\")\n\n# We can use `$()` to interpolate values into a string:\n\nx = 123\nprintln(\"The value of x is: $(x)\")\n\n# ### Symbols\n\n# Julia `Symbol`s provide a way to make human readable unique identifiers:\n\n:my_id\n\n#-\n\ntypeof(:my_id)\n\n# You can think of a `Symbol` as a `String` that takes up less memory, and that\n# can't be modified.\n\n# ### Tuples\n\n# Julia makes extensive use of a simple data structure called Tuples. Tuples are\n# immutable collections of values. For example:\n\nt = (\"hello\", 1.2, :foo)\n\n#-\n\ntypeof(t)\n\n# Tuples can be accessed by index, similar to arrays:\n\nt[2]\n\n# And they be \"unpacked\" like so:\n\na, b, c = t\nb\n\n# The values can also be given names, which is a convenient way of making\n# light-weight data structures.\n\nt = (word = \"hello\", num = 1.2, sym = :foo)\n\n# Values can be accessed using dot syntax:\n\nt.word\n\n# ## Dictionaries\n\n# Similar to Python, Julia has native support for dictionaries. Dictionaries\n# provide a very generic way of mapping keys to values. For example, a map of\n# integers to strings:\n\nd1 = Dict(1 => \"A\", 2 => \"B\", 4 => \"D\")\n\n# !!! info\n# Type-stuff again: `Dict{Int64,String}` is a dictionary with `Int64` keys\n# and `String` values.\n\n# Looking up a values uses the bracket syntax:\n\nd1[2]\n\n# Dictionaries support non-integer keys and can mix data types:\n\nDict(\"A\" => 1, \"B\" => 2.5, \"D\" => 2 - 3im)\n\n# !!! info\n# Julia types form a hierarchy. Here the value type of the dictionary is\n# `Number`, which is a generalization of `Int64`, `Float64`, and `Complex{Int}`.\n# In general, having variables with \"Abstract\" types like `Number` can lead\n# to slower code, so you should try to make sure every element in a\n# dictionary or vector is the same type. For example, in this case we could\n# represent every element as a `Complex{Float64}`:\n\nDict(\"A\" => 1.0 + 0.0im, \"B\" => 2.5 + 0.0im, \"D\" => 2.0 - 3.0im)\n\n# Dictionaries can be nested:\n\nd2 = Dict(\"A\" => 1, \"B\" => 2, \"D\" => Dict(:foo => 3, :bar => 4))\n\n#-\n\nd2[\"B\"]\n\n#-\n\nd2[\"D\"][:foo]\n\n# ## Loops\n\n# Julia has native support for for-each style loops with the syntax\n# `for in end`:\n\nfor i in 1:5\n println(i)\nend\n\n\n# !!! info\n# Ranges are constructed as `start:stop`, or `start:step:stop`.\n\n#-\n\nfor i in [1.2, 2.3, 3.4, 4.5, 5.6]\n println(i)\nend\n\n# This for-each loop also works with dictionaries:\n\nfor (key, value) in Dict(\"A\" => 1, \"B\" => 2.5, \"D\" => 2 - 3im)\n println(\"$(key): $(value)\")\nend\n\n# Note that in contrast to vector languages like Matlab and R, loops do not\n# result in a significant performance degradation in Julia.\n\n# ## Control Flow\n\n# Julia control flow is similar to Matlab, using the keywords\n# `if-elseif-else-end`, and the logical operators `||` and `&&` for **or** and\n# **and** respectively:\n\nfor i in 0:3:15\n if i < 5\n println(\"$(i) is less than 5\")\n elseif i < 10\n println(\"$(i) is less than 10\")\n else\n if i == 10\n println(\"the value is 10\")\n else\n println(\"$(i) is bigger than 10\")\n end\n end\nend\n\n# ## Comprehensions\n\n# Similar to languages like Haskell and Python, Julia supports the use of simple\n# loops in the construction of arrays and dictionaries, called comprehenions.\n#\n# A list of increasing integers:\n\n[i for i in 1:5]\n\n# Matrices can be built by including multiple indices:\n\n[i * j for i in 1:5, j in 5:10]\n\n# Conditional statements can be used to filter out some values:\n\n[i for i in 1:10 if i % 2 == 1]\n\n# A similar syntax can be used for building dictionaries:\n\nDict(\"$(i)\" => i for i in 1:10 if i % 2 == 1)\n\n# ## Functions\n\n# A simple function is defined as follows:\n\nfunction print_hello()\n println(\"hello\")\nend\nprint_hello()\n\n# Arguments can be added to a function:\n\nfunction print_it(x)\n println(x)\nend\nprint_it(\"hello\")\nprint_it(1.234)\nprint_it(:my_id)\n\n# Optional keyword arguments are also possible:\n\nfunction print_it(x; prefix = \"value:\")\n println(\"$(prefix) $(x)\")\nend\nprint_it(1.234)\nprint_it(1.234, prefix = \"val:\")\n\n# The keyword `return` is used to specify the return values of a function:\n\nfunction mult(x; y = 2.0)\n return x * y\nend\n\nmult(4.0)\n\n#-\n\nmult(4.0, y = 5.0)\n\n# ### Anonymous functions\n\n# The syntax `input -> output` creates an anonymous function. These are most\n# useful when passed to other functions. For example:\n\nf = x -> x^2\nf(2)\n\n#-\n\nmap(x -> x^2, 1:4)\n\n# ### Type parameters\n\n# We can constrain the inputs to a function using type parameters, which are\n# `::` followed by the type of the input we want. For example:\n\nfunction foo(x::Int)\n return x^2\nend\n\nfunction foo(x::Float64)\n return exp(x)\nend\n\nfunction foo(x::Number)\n return x + 1\nend\n\n@show foo(2)\n@show foo(2.0)\n@show foo(1 + 1im)\nnothing #hide\n\n# But what happens if we call `foo` with something we haven't defined it for?\n\ntry #hide\nfoo([1, 2, 3])\ncatch err; showerror(stdout, err) end #hide\n\n# We get a dreaded `MethodError`! A `MethodError` means that you passed a\n# function something that didn't match the type that it was expecting. In this\n# case, the error message says that it doesn't know how to handle an\n# `Array{Int64, 1}`, but it does know how to handle `Float64`, `Int64`, and\n# `Number`.\n#\n# !!! tip\n# Read the \"Closest candidates\" part of the error message carefully to get a\n# hint as to what was expected.\n\n# ### Broadcasting\n\n# In the example above, we didn't define what to do if `f` was passed an\n# `Array`. Luckily, Julia provides a convienient syntax for mapping `f`\n# element-wise over arrays! Just add a `.` between the name of the function and\n# the opening `(`. This works for _any_ function, including functions with\n# multiple arguments. For example:\n\nf.([1, 2, 3])\n\n# !!! tip\n# Get a `MethodError` when calling a function that takes an `Array`? Try\n# broadcasting it!\n\n# ## Mutable vs immutable objects\n\n# Some types in Julia are *mutable*, which means you can change the values\n# inside them. A good example is an array. You can modify the contents of an\n# array without having to make a new array.\n\n# In contrast, types like `Float64` are *immutable*. You can't modify the\n# contents of a `Float64`.\n\n# This is something to be aware of when passing types into functions. For\n# example:\n\nfunction mutability_example(mutable_type::Vector{Int}, immutable_type::Int)\n mutable_type[1] += 1\n immutable_type += 1\n return\nend\n\nmutable_type = [1, 2, 3]\nimmutable_type = 1\n\nmutability_example(mutable_type, immutable_type)\n\nprintln(\"mutable_type: $(mutable_type)\")\nprintln(\"immutable_type: $(immutable_type)\")\n\n# Because `Vector{Int}` is a mutable type, modifying the variable inside the\n# function changed the value outside of the function. In constrast, the change\n# to `immutable_type` didn't modify the value outside the function.\n\n# You can check mutability with the `isimmutable` function:\n\nisimmutable([1, 2, 3])\n\n#-\n\nisimmutable(1)\n\n# ## The package manager\n\n# ### Installing packages\n\n# No matter how wonderful Julia's base language is, at some point you will want\n# to use an extension package. Some of these are built-in, for example random\n# number generation is available in the `Random` package in the standard\n# library. These packages are loaded with the commands `using` and `import`.\n\nusing Random # The equivalent of Python's `from Random import *`\nimport Random # The equivalent of Python's `import Random`\n\nRandom.seed!(33)\n\n[rand() for i in 1:10]\n\n# The Package Manager is used to install packages that are not part of Julia's\n# standard library.\n\n# For example the following can be used to install JuMP,\n# ```julia\n# using Pkg\n# Pkg.add(\"JuMP\")\n# ```\n\n# For a complete list of registed Julia packages see the package listing at\n# [JuliaHub](https://juliahub.com).\n\n# From time to you may wish to use a Julia package that is not registered. In\n# this case a git repository URL can be used to install the package.\n# ```julia\n# using Pkg\n# Pkg.add(\"https://github.com/user-name/MyPackage.jl.git\")\n# ```\n\n# ### Package environments\n\n# By default, `Pkg.add` will add packages to Julia's global environment.\n# However, Julia also has built-in support for virtual environments.\n\n# Activate a virtual environment with:\n# ```julia\n# import Pkg; Pkg.activate(\"/path/to/environment\")\n# ```\n\n# You can see what packages are installed in the current environment with\n# `Pkg.status()`.\n\n# !!! tip\n# We _strongly_ recommend you create a Pkg environment for each project\n# that you create in Julia, and add only the packages that you need, instead\n# of adding lots of packages to the global environment. The [Pkg manager documentation](https://julialang.github.io/Pkg.jl/v1/environments/)\n# has more information on this topic.\n", "meta": {"hexsha": "7af139a58f5a649eaa7dc30aabf6341a649b5b5d", "size": 16499, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/an_introduction_to_julia.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/an_introduction_to_julia.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/an_introduction_to_julia.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8699324324, "max_line_length": 144, "alphanum_fraction": 0.672889266, "num_tokens": 4510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.16667539847889923, "lm_q1q2_score": 0.07490269642289611}} {"text": "# Uncomment to debug:\n# macro dbgutil(x); esc(:(println(_dbg($x)))); end\nmacro dbgutil(x); end\n\n### @primitive and @zerograd macros:\n\n# I would like to make these type signatures as specific as possible.\n# The following are not allowed yet, see https://github.com/JuliaLang/julia/issues/3766\n# f{T<:Number,A<:AbstractArray{T}}(x::Value{A})\n# f{T<:Number,A<:AbstractArray}(x::Value{A{T}})\n\n\"\"\"\n\n`@primitive fx g1 g2...` can be used to define a new primitive\nand (optionally) its gradients.\n\nJulia supports multiple dispatch, i.e. a single function can have\nmultiple methods with different arg types. AutoGrad supports\nmultiple dispatch for primitives and gradients. Thus fx is a\ntyped method declaration such as:\n\n* @primitive sin(x::Number)\n* @primitive hypot(x1::Array,x2::Array),dy,y\n\nThe second example specifies variable names for the output gradient\n`dy` and the output `y` after the method declaration which can be used\nin gradient expressions. Untyped, ellipsis and keyword arguments are\nok as in `f(a::Int,b,c...;d=1)`. Parametric methods such as\n`f{T<:Number}(x::T)` cannot be used.\n\nThe @primitive macro turns the first example into:\n\n local sin_r = recorder(sin)\n sin{T<:Number}(x::Value{T}) = sin_r(x)\n\nThis will cause any call to `sin` with a Value{T<:Number} argument\nto be recorded. With multiple arguments things are a bit more\ncomplicated. Here is what happens with the second example:\n\n local hypot_r = recorder(hypot)\n hypot{T<:Array,S<:Array}(x1::Value{T},x2::Value{S})=hypot_r(x1,x2)\n hypot{T<:Array,S<:Array}(x1::Value{T},x2::S)=hypot_r(x1,x2)\n hypot{T<:Array,S<:Array}(x1::T,x2::Value{S})=hypot_r(x1,x2)\n\nWe want the recorder version to be called if any one of the arguments\nis a boxed Value. There is no easy way to specify this in Julia, so\nthe macro generates all 2^N-1 boxed/unboxed argument combinations.\n\nThe method declaration can optionally be followed by gradient\nexpressions. Here are the same examples with gradients:\n\n* @primitive sin(x::Number),dy (dy*cos(x))\n* @primitive hypot(x1::Array,x2::Array),dy,y `(dy.*x1./y)` `(dy.*x2./y)`\n\nNote that the parameters, the return variable and the output gradient\nof the original function can be used in the gradient expressions.\n\nIn AutoGrad, gradients are defined using gradient methods that have\nthe following signature:\n\n f(Grad{i},dy,y,x...) => dx[i]\n\nFor the first example here is the generated gradient method:\n\n`sin{T<:Number}(::Type{Grad{1}}, dy, y, x::Value{T})=(dy*cos(x))`\n\nFor the second example a different gradient method is generated for\neach argument:\n\n`hypot{T<:Array,S<:Array}(::Type{Grad{1}},dy,y,x1::Value{T},x2::Value{S})=(dy.*x1./y)`\n`hypot{T<:Array,S<:Array}(::Type{Grad{2}},dy,y,x1::Value{T},x2::Value{S})=(dy.*x2./y)`\n\nIn fact @primitive generates four more definitions for the other\nboxed/unboxed argument combinations.\n\nNon-differentiable functions such as `sign`, and non-numeric functions\nsuch as `size` should be defined using the @zerograd macro instead.\n\n\"\"\"\nmacro primitive(f,g...)\n isa(f,Expr) || error(\"'$f' not a method signature\")\n if f.head == :tuple # Using f(x),dy,y to indicate return variable for gradients\n if length(f.args) == 3\n (f,dy,y) = f.args\n elseif length(f.args) == 2\n (f,dy) = f.args; y = gensym()\n else\n error(\"The first arg '$f' should have the format f(x),dy,y\")\n end\n else\n dy = gensym(); y = gensym()\n end\n f.head == :call || error(\"'$f' not a method signature\")\n isa(dy,Symbol) || error(\"Output gradient '$dy' not a symbol\")\n isa(y,Symbol) || error(\"Return variable '$y' not a symbol\")\n b = Expr(:block)\n r = gensym()\n push!(b.args, esc(:(local $r = recorder($(fname(f))))))\n rx = rcall(r,f)\n for fx in fsigs(f)\n push!(b.args, esc(:($fx = $rx)))\n for i=1:length(g)\n gx = gsig(fx,dy,y,i)\n push!(b.args, esc(:($gx = $(g[i]))))\n end\n end\n return b\nend\n\n\"\"\"\n`@zerograd f(args...; kwargs...)` allows f to handle its Value inputs\nby unboxing them like @primitive, but unlike @primitive it does not\nrecord its actions or return a Value result. Some functions, like\nsign(), have zero gradient. Others, like length() have discrete or\nconstant outputs. These need to handle Value inputs, but do not need\nto record anything and can return regular values. Their output can be\ntreated like a constant in the program. Use the @zerograd macro for\nthose. Note that kwargs are NOT unboxed.\n\"\"\"\nmacro zerograd(f)\n b = Expr(:block)\n f.head == :(::) && (f=f.args[1])\n for fx in fsigs(f)\n zx = zcall(fx)\n push!(b.args, esc(:($fx = $zx)))\n end\n return b\nend\n\nfunction zcall(f)\n z = copy(f)\n z1 = z.args[1]\n isa(z1,Expr) && z1.head==:curly && (z.args[1]=z1.args[1])\n for i=2:length(z.args)\n zi = z.args[i]\n if isa(zi,Symbol)\n # all done\n elseif !isa(zi,Expr)\n error(\"Unrecognized argtype '$zi'\")\n elseif zi.head==:(::)\n (v,t) = zi.args\n if t==:Value || (isa(t,Expr) && t.head==:curly && t.args[1]==:Value)\n z.args[i] = :($v.value)\n else\n z.args[i] = v\n end\n elseif zi.head==:(...) # done\n elseif zi.head==:parameters # done\n else\n error(\"Unrecognized argtype '$zi'\")\n end\n end\n return z\nend\n\n# get name out of function declaration\nfunction fname(f)\n n = f.args[1]\n isa(n,Expr) && n.head==:curly && error(\"parametric methods not currently supported\")\n if isa(n,Symbol)\n return n\n else\n error(\"$n not a symbol\")\n end\nend\n\n# create call to r using typeless argument of f\nfunction rcall(r,f)\n rx = notypes(f)\n rx.args[1]=r\n # Need to fix kwargs\n r2 = rx.args[2]\n if isa(r2,Expr) && r2.head == :parameters\n for i in 1:length(r2.args)\n k = r2.args[i]\n if !isa(k,Expr); error(\"Bad kwarg '$k'\")\n elseif k.head == :(...); continue\n elseif k.head != :kw; error(\"Bad kwarg '$k'\")\n elseif !isa(k.args[1],Symbol); error(\"Bad kwarg '$k'\")\n else; k.args[2]=k.args[1]; end\n end\n end\n return rx\nend\n\n# eliminate type declarations from a function call\nfunction notypes(ex)\n if isa(ex, Expr)\n if (ex.head == :(::) || ex.head == :curly)\n return notypes(ex.args[1])\n else\n return Expr(ex.head, map(notypes, ex.args)...)\n end\n else\n return ex\n end\nend\n\n# create type signatures for f where one or more args are Nodes.\nfunction fsigs(f)\n f1 = copy(f)\n a1 = f1.args[1] = Expr(:curly,fname(f1))\n nargs = 0\n for i=2:length(f1.args)\n ai = f1.args[i]\n if isa(ai,Symbol)\n nargs+=1\n ti = gensym()\n push!(a1.args, Expr(:<:, ti, Any))\n f1.args[i] = Expr(:(::),ai,ti)\n elseif !isa(ai,Expr)\n error(\"Neither Symbol nor Expr: $ai\")\n elseif in(ai.head, (:parameters, :(...)))\n continue\n elseif ai.head == :(::)\n nargs+=1\n ti = gensym()\n push!(a1.args, Expr(:<:,ti,ai.args[2]))\n ai.args[2] = ti\n else\n error(\"Argtype not supported: '$ai'\")\n end\n end\n flist = []\n for nodes=0:(1<, Expr(:tuple, plist...), Expr(:call, f1, alist...)))\n # if f has non-scalar output, sum it\n isbits(y) || (f2=f; f=(x...)->toscalar(f2(x...)))\n return (f,fargs...)\nend\n\nfunction randin(range, dims...; eps=EPS)\n if isa(range, UnitRange{Int64})\n rand(range, dims...)\n elseif range==(-Inf,Inf)\n randn(dims...)\n elseif range==(0,Inf)\n eps-log(rand(dims...))\n elseif range==(1,Inf)\n eps+1-log(rand(dims...))\n elseif range==(-1,Inf)\n eps-1-log(rand(dims...))\n elseif range==(-1,1)\n (1-eps)*(2rand(dims...)-1)\n elseif range==(0,1)\n eps+(1-2eps)*rand(dims...)\n elseif range==(0,2)\n eps+2*(1-eps)*rand(dims...)\n elseif range==(-Inf,-1,1,Inf)\n x = sec(randn(dims...))\n sign(x)*eps + x\n else\n error(\"Unknown range $range\")\n end\nend\n\nfunction addtest1(f,r) # unary\n addtest(f,randin(r))\n addtest(f,randin(r,2))\nend\n\nfunction addtest2(f,r1,r2=r1) # binary\n addtest(f,randin(r1),randin(r2))\n addtest(f,randin(r1),randin(r2,2))\n addtest(f,randin(r1,2),randin(r2))\n addtest(f,randin(r1,2),randin(r2,2))\nend\n\nfunction addtest3(f,r1,r2=r1) # broadcasting\n addtest2(f,r1,r2)\n addtest(f,randin(r1,2),randin(r2,2,2))\n addtest(f,randin(r1,2,2),randin(r2,2))\n addtest(f,randin(r1,1,2),randin(r2,2,2))\n addtest(f,randin(r1,2,2),randin(r2,1,2))\nend\n\n\n# EPS, RTOL, ATOL = 1e-4, 1e-4, 1e-6\nEPS, RTOL, ATOL = 1e-4, 1e-2, 1e-4\n\n# TODO: do sampling or random direction for large args\n\"\"\"\ncheck_grads(fun, args...) checks the computed gradients for fun(args)\ncomparing them with numeric approximations.\n\"\"\"\nfunction check_grads(fun, args...; eps=EPS, rtol=RTOL, atol=ATOL, fname=fun)\n @dbgutil((:check_grads,fname,:args,args...))\n isempty(args) && error(\"No args given\")\n exact = ntuple(i->grad(fun,i)(args...), length(args))\n numeric = nd(fun, args...; eps=eps)\n @dbgutil((:check_grads,fname,:exact,exact,:numeric,numeric))\n same = isequivalent(exact, numeric; rtol=rtol, atol=atol)\n same || warn((:check_grads,fname,:args,args,:exact,exact,:numeric,numeric))\n return same\nend\n\nfunction nd(f, args...; eps=EPS)\n @dbgutil((:nd,f,args..., :eps, eps))\n unary_f = x->f(x...)\n unary_nd(unary_f, args, eps)\nend\n\nunary_nd(f, x::Tuple, eps) = ntuple(i->unary_nd(indexed_function(f, x, i), x[i], eps), length(x))\nunary_nd(f, x::Associative, eps) = (a=similar(x); for(k,v) in x; a[k] = unary_nd(indexed_function(f, x, k), v, eps); end; a)\nunary_nd(f, x::AbstractArray, eps) = reshape(eltype(x)[unary_nd(indexed_function(f, x, i), v, eps) for (i,v) in enumerate(x)], size(x))\nunary_nd(f, x::Complex, eps) = ((f(x + eps/2) - f(x - eps/2)) / eps - im*(f(x + im*eps/2) - f(x - im*eps/2)) / eps)\nunary_nd(f, x::Real, eps) = ((f(x + eps/2) - f(x - eps/2)) / eps)\n\nfunction indexed_function(fun, arg, index)\n function partial_function(x)\n if isa(arg, Tuple)\n local_arg = (arg[1:index-1]..., x, arg[index+1:end]...)\n else\n local_arg = copy(arg); local_arg[index] = x\n end\n return fun(local_arg)\n end\n return partial_function\nend\n\n# isequivalent uses isapprox for Number and AbstractArray{T<:Number}\nisequivalent(x::Number,y::Number; o...)=isapprox(x,y;o...)\nisequivalent{T<:Number,S<:Number}(x::AbstractArray{T},y::AbstractArray{S}; o...)=isapprox(x,y;o...)\n\n# isequivalent extends to Tuple, Associative, and other Arrays, comparing elementwise\nisequivalent(x::Tuple, y::Tuple; o...)=(length(x)==length(y) && all(i->isequivalent(x[i],y[i];o...), 1:length(x)))\nisequivalent(x::AbstractArray, y::AbstractArray; o...)=(length(x)==length(y) && all(i->isequivalent(x[i],y[i];o...), 1:length(x)))\nisequivalent(x::Associative, y::Associative; o...)=all(k->isequivalent(get(x,k,nothing),get(y,k,nothing);o...), unique([keys(x)...,keys(y)...]))\n\n# isequivalent treats `nothing` as equivalent to zero or zero array.\nisequivalent(x::Number,z::Void; o...)=isequivalent(z,x;o...)\nisequivalent{T<:Number}(x::AbstractArray{T},z::Void; o...)=isequivalent(z,x;o...)\nisequivalent(z::Void,x::Number; o...)=isapprox(zero(x),x;o...)\nisequivalent{T<:Number}(z::Void,x::AbstractArray{T}; rtol::Real=Base.rtoldefault(T), atol::Real=0, norm::Function=vecnorm) = (norm(x) <= atol/(1-rtol)) # Modified from: linalg/generic.jl:522\n\n# The way broadcasting works in Julia:\n# y = f(x...) where f is a broadcasting operation.\n# size(y) = broadcast_shape(x...)\n# ndims(y) = max ndims(x)\n# size(y,i) = max size(x,i)\n# size(x,i) = 1 or size(y,i) for all x and i<=ndims(x)\n# if ndims(x) < ndims(y) the extra dimensions of x are treated as 1\n\nfunction unbroadcast(x, dx)\n if size(x)==size(dx)\n return dx\n elseif isa(getval(x),Number)\n return sum(dx)\n else\n d = []\n for i=1:ndims(dx)\n size(x,i) == size(dx,i) && continue\n size(x,i) != 1 && throw(DimensionMismatch())\n push!(d,i)\n end\n length(d)==1 && (d=d[1])\n return sum(dx, d)\n end\nend\n\nfunction toscalar(xv; rng=MersenneTwister())\n x = getval(xv)\n isa(x,Number) && return xv\n isa(x,OneHot) && (x = full(x))\n idx = isa(x,Tuple) ? (1:length(x)) : eachindex(x)\n s = 0\n for i in idx\n s += xv[i] * rand(rng)\n end\n return s\nend\n\n# sumvalues sums values of dictionaries, otherwise acts like sum:\n\nsumvalues(x)=sum(x)\nsumvalues(x::Associative)=sum(values(x))\n@primitive sumvalues(x::Associative),ds fillvalues(ds,x)\nfillvalues(v,x)=(y=similar(x);for k in keys(x); y[k]=v; end; y)\n@primitive fillvalues(v,x),dxv sumvalues(dxv) nothing\naddtest(sumvalues, Dict(1=>1.,2=>2.))\naddtest(fillvalues, 0., Dict(1=>1.,2=>2.,3=>3.))\n\n# This needs more work:\n# @primitive values(x),dy Dict(map((a,b)->(a=>b), keys(x), dy))\n\n# It gets tiresome to write `Type{Grad{1}}` after a while, here are\n# some convenient aliases:\n\ntypealias D1 Type{Grad{1}}\ntypealias D2 Type{Grad{2}}\nif !isdefined(:Dn)\ntypealias Dn{N} Type{Grad{N}}\nend\n\n# Pretty print for debugging:\n_dbg(x)=x # extend to define short printable representations\n_dbg(x::Tuple)=map(_dbg,x)\n_dbg(x::Node)=\"N$(id2(x))_$(id2(x.value))\"\n_dbg(x::Value)=\"V$(id2(x))_$(_dbg(x.value))\"\n_dbg(x::Tape)=\"T$(join([id2(x),map(id2,x)...],'_'))\"\n_dbg(x::AbstractArray)=\"A$(join([id2(x),size(x)...],'_'))\"\nid2(x)=Int(object_id(x)%1000)\n\nBase.show(io::IO, n::Value) = print(io, _dbg(n))\nBase.show(io::IO, n::Node) = print(io, _dbg(n))\nBase.show(io::IO, n::Tape) = print(io, _dbg(n))\n\n", "meta": {"hexsha": "0435f0b644a12776798e13cc91373690f8e95114", "size": 15794, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/util.jl", "max_stars_repo_name": "JuliaPackageMirrors/AutoGrad.jl", "max_stars_repo_head_hexsha": "3775730f69e07a37a998cd4489ee7c7bcbc3c4a5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/util.jl", "max_issues_repo_name": "JuliaPackageMirrors/AutoGrad.jl", "max_issues_repo_head_hexsha": "3775730f69e07a37a998cd4489ee7c7bcbc3c4a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/util.jl", "max_forks_repo_name": "JuliaPackageMirrors/AutoGrad.jl", "max_forks_repo_head_hexsha": "3775730f69e07a37a998cd4489ee7c7bcbc3c4a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9041666667, "max_line_length": 190, "alphanum_fraction": 0.5919336457, "num_tokens": 4864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.14608725262486594, "lm_q1q2_score": 0.07247298459155538}} {"text": "# read_samples\n\n\"\"\"\n\nRead sample output files created by StanSample.jl.\n\nThis method is added to StanRun's read_sample function.\n\n### Method\n```julia\nread_samples(model::SampleModel; start=1)\n```\n\n### Required arguments\n```julia\n* `model` : SampleModel\n```\n\n### Optional arguments\n```julia\n* `start=1` : First draw saved in MCMCHains.Chains object\n```\n\n\"\"\"\nfunction read_samples(model::SampleModel; start=1)\n\n local a3d, monitors, index, idx, indvec, ftype, noofsamples\n \n output_base = model.output_base\n name_base =\"_chain\"\n n_samples = model.method. num_samples \n n_chains = StanBase.get_n_chains(model)\n \n # Handle save_warmup\n start = model.method.save_warmup ? model.method.num_warmup+1 : start\n \n # a3d will contain the samples such that a3d[s, i, c] where\n\n # s: num_samples\n # i: variables (from cmdstan .csv file)\n # c: n_chains\n\n # Read .csv files created by each chain\n \n for i in 1:n_chains\n if isfile(output_base*name_base*\"_$(i).csv\")\n #noofsamples = 0\n instream = open(output_base*name_base*\"_$(i).csv\")\n #\n # Skip initial set of commented lines, e.g. containing cmdstan version info, etc.\n #\n skipchars(isspace, instream, linecomment='#')\n #\n # First non-comment line contains names of variables\n #\n line = Unicode.normalize(readline(instream), newline2lf=true)\n idx = split(strip(line), \",\")\n index = [idx[k] for k in 1:length(idx)] \n indvec = 1:length(index)\n \n if i == 1\n a3d = fill(0.0, n_samples, length(indvec), n_chains)\n end\n \n #println(size(a3d))\n skipchars(isspace, instream, linecomment='#')\n for j in 1:n_samples\n skipchars(isspace, instream, linecomment='#')\n line = Unicode.normalize(readline(instream), newline2lf=true)\n if eof(instream) && length(line) < 2\n close(instream)\n break\n else\n flds = parse.(Float64, split(strip(line), \",\"))\n flds = reshape(flds[indvec], 1, length(indvec))\n a3d[j,:,i] = flds\n end\n end # read in samples\n end # read in next file\n end # read in file for each chain\n \n cnames = convert.(String, idx[indvec])\n chns = convert_a3d(a3d, cnames, Val(:mcmcchains); start=start)\n\nend # end of read_samples\n\nfunction read_samples(model::StanModel; chain=1)\n read_samples(default_output_base(model)*\"_chain_$(chain).csv\")\nend\n\n\"\"\"\n\n# convert_a3d\n\nConvert the output file created by cmdstan to the shape of choice.\n\n### Method\n```julia\nconvert_a3d(a3d_array, cnames, ::Val{Symbol}; start=1)\n```\n### Required arguments\n```julia\n* `a3d_array::Array{Float64, 3},` : Read in from output files created by cmdstan \n* `cnames::Vector{AbstractString}` : Monitored variable names\n```\n\n### Optional arguments\n```julia\n* `::Val{Symbol}` : Output format\n* `::start=1` : First draw for MCMCChains.Chains\n```\nMethod called is based on the output_format defined in the stanmodel, e.g.:\n\n stanmodel = Stanmodel(`num_samples`=1200, thin=2, name=\"bernoulli\", \n model=bernoullimodel, `output_format`=:mcmcchains);\n\nCurrent formats supported are:\n\n1. :array (a3d_array format, the default for CmdStan)\n2. :namedarray (NamedArrays object)\n3. :dataframe (DataFrames object)\n4. :mambachains (Mamba.Chains object)\n5. :mcmcchains (TuringLang/MCMCChains.Chains object)\n\nOptions 3 through 5 are respectively provided by the packages StanDataFrames, \nStanMamba, StanMCMCChains and StanMCMCChains.\n```\n\n### Return values\n```julia\n* `res` : Draws converted to the specified format.\n```\n\"\"\"\nconvert_a3d(a3d_array, cnames, ::Val{:array}; start=1) = a3d_array\n\nconvert_a3d(a3d_array, cnames, ::Val{:namedarray}; start=1) = \n [NamedArray(a3d_array[:,:,i], (collect(1:size(a3d_array, 1)), Symbol.(cnames))) \n for i in 1:size(a3d_array, 3)]\n\nfunction convert_a3d(a3d_array, cnames, ::Val{:mcmcchains}; start=1)\n pi = filter(p -> length(p) > 2 && p[end-1:end] == \"__\", cnames)\n p = filter(p -> !(p in pi), cnames)\n\n MCMCChains.Chains(a3d_array,\n cnames,\n Dict(\n :parameters => p,\n :internals => pi\n );\n start=start\n )\nend\n", "meta": {"hexsha": "a980c7a09e180a4579d9fd47f0a7f5fd3a7f5e26", "size": 4259, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/stansamples/read_samples.jl", "max_stars_repo_name": "UnofficialJuliaMirror/StanSample.jl-c1514b29-d3a0-5178-b312-660c88baa699", "max_stars_repo_head_hexsha": "768894f98284a1840f01fd9c6c51c5247bae2ad5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/stansamples/read_samples.jl", "max_issues_repo_name": "UnofficialJuliaMirror/StanSample.jl-c1514b29-d3a0-5178-b312-660c88baa699", "max_issues_repo_head_hexsha": "768894f98284a1840f01fd9c6c51c5247bae2ad5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/stansamples/read_samples.jl", "max_forks_repo_name": "UnofficialJuliaMirror/StanSample.jl-c1514b29-d3a0-5178-b312-660c88baa699", "max_forks_repo_head_hexsha": "768894f98284a1840f01fd9c6c51c5247bae2ad5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8366013072, "max_line_length": 120, "alphanum_fraction": 0.6386475699, "num_tokens": 1231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4765796510636759, "lm_q2_score": 0.15203223778010538, "lm_q1q2_score": 0.07245547083167243}} {"text": "### A Pluto.jl notebook ###\n# v0.17.3\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ c730d000-5ed6-11ec-36b6-39741ccad6c7\nbegin\n\tusing Pkg; Pkg.activate(@__DIR__); Pkg.instantiate()\n\tPkg.precompile()\n\n\tusing PlutoUI\n\tusing BenchmarkTools\n\tusing DataFrames\n\tusing DelimitedFiles\n\tusing CSV\n\tusing XLSX\n\tusing Downloads\n\tusing JLD, NPZ, MAT, RData\n\tusing RCall\nend;\n\n# ╔═╡ 62c5d4f2-9776-43ae-8125-0d429d6cde42\nPlutoUI.TableOfContents(aside=true, indent=true, depth=3)\n\n# ╔═╡ 34f92fb1-6c1e-4db6-b795-8a526007ea92\nhtml\"\"\"\n

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

\n\"\"\"\n\n# ╔═╡ 13a10dac-8c7e-4e72-9fa9-d58ca8dd0202\nmd\"\"\"\n# 💾 Data\n\nBeing able to easily load and process data is a crucial task that can make any data science more pleasant. In this notebook, we will cover most common types often encountered in data science tasks, and we will be using this data throughout the rest of this tutorial.\n\n[YouTube link](https://www.youtube.com/watch?v=iG1dZBaxS-U)\n\"\"\"\n\n# ╔═╡ 5100df3f-c5d3-4346-bcd9-8afc92bc559c\nmd\"\"\"\n## Get some data\n\nIn Julia, it's pretty easy to dowload a file from the web using the `download` function. But also, you can use your favorite command line commad to download files by easily switching from Julia via the `;` key. Let's try both.\n\n**Note:** `download` depends on external tools such as curl, wget or fetch. So you must have one of these.\n\"\"\"\n\n# ╔═╡ abe62085-b630-4816-af11-b39133892849\ndata₁ = Downloads.download(\"https://raw.githubusercontent.com/nassarhuda/easy_data/master/programming_languages.csv\", \"programminglanguages.csv\")\n\n# ╔═╡ 51c909b1-1d37-458f-acd6-68f4041bc92f\nmd\"\"\"\n## Read your data from text files\n\nThe key question here is to load data from files such as `csv` files, `xlsx` files, or just raw text files. We will go over some Julia packages that will allow us to read such files very easily.\n\"\"\"\n\n# ╔═╡ 6483858c-2e58-4930-b4e9-76b47032eac4\nmd\"\"\"\n### DelimitedFiles.jl\n\nLet's start with the package `DelimitedFiles` which is in the standard library. When loaded, the file is stored as a `Matrix`.\n\n> **readdlm**(source, \n> delim::AbstractChar, \n> T::Type, \n> eol::AbstractChar; \n> header=false, \n> skipstart=0, \n> skipblanks=true, \n> use_mmap, \n> quotes=true, \n> dims, \n> comments=false, \n> comment_char='#')\n\"\"\"\n\n# ╔═╡ 89a5a316-5058-4ff2-8d71-fc832a84c58d\nbegin\n\tdata₂, header = readdlm(\"programming_languages.csv\",',';header=true)\n\theader\nend\n\n# ╔═╡ 853a4e90-ac39-4d73-9953-c7b70e8f78ef\ndata₂\n\n# ╔═╡ 3a22c018-2ca7-41df-9ee4-91dc8b64d940\nmd\"\"\"\n> **Note:** the output table is a Matrix (2D Array).\n\nWe can use the function `writedlm`, from `DelimitedFiles.jl` package, to write to a text file...\n\"\"\"\n\n# ╔═╡ b4fcdcf9-793f-4d4a-a5fb-950108cb8188\nwritedlm(\"output/programminglanguages_dlm.txt\", data₂, '-')\n\n# ╔═╡ cfa37c7c-810c-4095-8887-262dee4a9d04\nmd\"\"\"\n### CSV.jl\n\nA more powerful package to use here is the `CSV.jl` package. By default, this package imports the data to a `DataFrame`, which can have several advantages as we will see below.\n\n_In general, `CSV.jl` is the recommended way to load CSVs in Julia_. Only use `DelimitedFiles.jl` when you have a more complicated file where you want to specify several things.\n\"\"\"\n\n# ╔═╡ 4b651b5a-e562-46ef-a3b5-8ee85b5a61ed\ndf = CSV.read(\"programming_languages.csv\", DataFrame)\n\n# ╔═╡ 11471bbf-b7b4-4b6e-90cb-9e9ff47bbe4a\nmd\"\"\"\nWe can use the `typeof` function to make sure that the output is a DataFrame.\n\"\"\"\n\n# ╔═╡ 2652dc01-d80d-46d9-ae7a-9afa534e88cb\ntypeof(df)\n\n# ╔═╡ b2f35e6b-8c19-4729-87a3-292858bfbcb5\nmd\"\"\"\nWe can use the macro `@btime`, from `BenchMarkTools.jl`, to prove that `CSV.jl` is faster than `DelimitedFiles.jl`...\n\n**Note:** Check Julia REPL to see the processing time.\n\"\"\"\n\n# ╔═╡ e1210609-a216-4d54-be63-04f10c5c15bc\n@btime df₁, h₁ = readdlm(\"programming_languages.csv\",',';header=true);\n\n# ╔═╡ 008b635f-c4e5-475a-83af-4bc3fc722344\n@btime df₂ = CSV.read(\"programming_languages.csv\", DataFrame);\n\n# ╔═╡ 934c8549-c86c-45e6-a9f5-56297c73513d\nmd\"\"\"\nWe can use the function `write`, from `CSV.jl` package, to write to a text file...\n\n**Note:** if we want to write a Matrix, we could first convert it into a DataFrame (using the `DataFrame` function) and, then, write it using the `write` function.\n\"\"\"\n\n# ╔═╡ 92708ece-3620-4cf5-b09d-098002044623\nCSV.write(\"output/programminglanguages_CSV.csv\", df)\n\n# ╔═╡ cac4f1b5-f9e3-469e-9576-553a1cf1b363\nmd\"\"\"\n### Some DataFrame Operations\n\nThere are different ways to slice a DataFrame. Suppose that we want just the first 10 rows of a DataFrame...\n\"\"\"\n\n# ╔═╡ 3d378ec4-659f-4032-a5b7-6d6b6d402c2f\ndf[1:10,:]\n\n# ╔═╡ e50ae64c-ff64-4597-bf75-d7c921d23225\nmd\"\"\"\nSuppose that we want all the instances of a given feature (column)...\n\"\"\"\n\n# ╔═╡ d9ea3574-2ffb-4fdb-9ced-db1dc669ecd9\ndf[!,\"year\"]\n\n# ╔═╡ 09ff6d8b-15f2-4d8e-a775-dee357a417e4\ndf.year\n\n# ╔═╡ 843a668f-7b08-4bce-b02a-3153d0eb7d0d\ndf[!,\"year\"] == df.year\n\n# ╔═╡ 159a35f4-09fd-47bd-9935-88668a7e7f27\ntypeof(df.year)\n\n# ╔═╡ 494ebede-80d0-430e-91aa-0a9050a1bb29\nmd\"\"\"\nWe can use the `names` function to get an array of all column names...\n\"\"\"\n\n# ╔═╡ 00d12274-3057-4a52-8400-0c8c3c358e6b\nnames(df)\n\n# ╔═╡ fede3ce2-da03-4ff9-a13e-7ce55ec05bf6\nmd\"\"\"\nWe can use the `describe` function to check some data stats...\n\"\"\"\n\n# ╔═╡ 74783bbb-3c9d-4e15-bc54-b3d8e7c2d230\ndescribe(df)\n\n# ╔═╡ e4b3a444-c487-4fe8-8048-873b8a3affb7\nmd\"\"\"\nLet's create two DataFrames...\n\"\"\"\n\n# ╔═╡ 0becba29-d5ff-4595-86ab-6b0575674047\nbegin\n\tfoods = [\"Apple\",\"Cucumber\",\"Tomato\",\"Banana\"]\n\tcalories = [105,47,22,105]\n\n\tdf_cal = DataFrame(Item=foods, Calories=calories)\nend\n\n# ╔═╡ 9d522bdc-d066-40ac-84c4-47287d9e07e0\nbegin\n\tprices = [0.85,1.6,0.8,0.6]\n\n\tdf_price = DataFrame(Item=foods, Price=prices)\nend\n\n# ╔═╡ 79de9741-c913-4c00-8833-4f1b68f80ea5\nmd\"\"\"\nNow, we can use the `innerjoin` function to join both DataFrames on `Item` column...\n\"\"\"\n\n# ╔═╡ fd724d83-41bb-422c-860e-2bbeff17e0dc\ndf_comb = innerjoin(df_cal, df_price, on=:Item)\n\n# ╔═╡ 51301eeb-709a-4ea9-a1a5-d7967f8dd55d\nmd\"\"\"\n### XLSX.jl\n\nAnother type of files that we may often need to read is XLSX files. Let's try to read this type of file using the `XLSX.jl` package...\n\n> **readdata**(filepath, sheetname, cellrange)\n\"\"\"\n\n# ╔═╡ 64e7e90b-cd7d-4569-a715-4f27f1787e40\nxlsx₁ = XLSX.readdata(\"data/zillow_data_download_april2020.xlsx\",\n \t\t\t \t \"Sale_counts_city\",\n \t\t\t \t \"A1:F9\")\n\n# ╔═╡ e5f2c69b-fbd8-4048-aaed-792a64a4d66c\nmd\"\"\"\nIf you don't want to specify cell ranges, you can use the `readtable` function. However, this will take a little longer...\n\n> **readtable**(filepath, sheetname)\n\"\"\"\n\n# ╔═╡ 26047637-1b77-4203-b705-e34f74137295\nxlsx₂ = XLSX.readtable(\"data/zillow_data_download_april2020.xlsx\",\n\t\t\t\t\t \"Sale_counts_city\")\n\n# ╔═╡ 0f3d505c-a575-419f-8155-fd071f510714\ntypeof(xlsx₂)\n\n# ╔═╡ c2f1eab2-862a-4eb8-b233-71567cdc9963\nmd\"\"\"\nHere, `xlsx₂` is a tuple of two items. The first item is an vector of vectors where each vector corresponds to a column in the excel file...\n\"\"\"\n\n# ╔═╡ 3a924b3e-3dbe-49b6-9e5e-5a48b0ffd385\nxlsx₂[1]\n\n# ╔═╡ 58bad348-0586-4d0f-8d54-7c3e1a7a2c40\nmd\"\"\"\nWe can access the first column by typing...\n\"\"\"\n\n# ╔═╡ 036de982-36ad-431a-8445-517178626911\nxlsx₂[1][1]\n\n# ╔═╡ 4ead9039-f4c2-4f82-bf1e-2146718014a3\nmd\"\"\"\nWe can access the third column first 10 elements...\n\"\"\"\n\n# ╔═╡ bb04dc6c-e62e-4b2c-a247-ebe4836d8013\nxlsx₂[1][3][begin:10]\n\n# ╔═╡ d9550872-fa7c-4ebd-9a4d-828182c8e49d\nmd\"\"\"\nOn the other hand, the second is the header with the column names...\n\"\"\"\n\n# ╔═╡ e01a65ab-394a-4718-b9ae-ca2bb30e20b5\nxlsx₂[2]\n\n# ╔═╡ 1eb26b3c-8a5a-4648-bb73-f8291b656edc\nmd\"\"\"\nWe could check the names of the last 10 columns...\n\"\"\"\n\n# ╔═╡ cb027055-2cf6-4f74-b265-9d01c23c2967\nxlsx₂[2][end-9:end]\n\n# ╔═╡ 12dccfc3-e976-46e6-81b0-dc51b48309f4\nmd\"\"\"\nAnd we can easily store this data in a `DataFrame`. We can use the \"splat\" operator to unwrap these arrays and pass them to the DataFrame constructor...\n\"\"\"\n\n# ╔═╡ 403ac783-9c02-4fd1-8506-afe0af36a14b\ndf_xlsx = DataFrame(xlsx₂...)\n# df_xlsx = DataFrame(xlsx₂[1], xlsx₂[2])\n\n# ╔═╡ 36d8898e-980c-4f54-bbff-277ded2229ea\nmd\"\"\"\n**Note:** the first argument is the actual data and the second one comprises the column names.\n\nWe can also easily write data to an XLSX file (takes several amount of time)...\n\"\"\"\n\n# ╔═╡ 8d769d53-1902-4a09-8228-ce60174b22bb\n# XLSX.writetable(\"output/writefile_using_XLSX.xlsx\",xlsx₂[1],xlsx₂[2])\n\n# ╔═╡ bc29d2b5-e6c2-4b45-8b79-cbb012659be1\nmd\"\"\"\n## Importing your data\n\nOften, the data you want to import is not stored in plain text, and you might want to import different kinds of types. Here we will go over importing `jld`, `npz`, `rda`, and `mat` files. Hopefully, these four will capture the types from four common programming languages used in Data Science (Julia, Python, R and Matlab).\n\nWe will use a toy example here of a very small matrix. But the same syntax will hold for bigger files.\n\"\"\"\n\n# ╔═╡ 7c2fef9c-4e9a-4637-bc8e-6636af5f98ae\nmd\"\"\"\n### Julia Data (JLD)\n\nJLD, for which files conventionally have the extension `.jld`, is a widely-used format for data storage with the Julia programming language.\n\nJLD is a specific \"dialect\" of HDF5, a cross-platform, multi-language data storage format most frequently used for scientific data. By comparison with \"plain\" HDF5, JLD files automatically add attributes and naming conventions to preserve type information for each object.\n\"\"\"\n\n# ╔═╡ 8f51aeb5-3e75-4e5a-8c8f-ed0201eb8ce0\n# load JLD file\njld_data = JLD.load(\"data/mytempdata.jld\")\n\n# ╔═╡ 879ac394-8598-4399-957f-1280ecd99478\n# see the data\njld_data[\"tempdata\"]\n\n# ╔═╡ 0d27e3b3-79e3-424d-bc6b-94252900f7fb\n# save JLD file\nsave(\"output/mywrite.jld\", \"A\", jld_data)\n\n# ╔═╡ 13053d54-8680-41e2-b416-8a7bc50f6c92\n# JLD type\ntypeof(jld_data)\n\n# ╔═╡ e0f49c77-0c0d-4740-9227-5619d14748b6\nmd\"\"\"\n### Numpy Data (NPZ)\n\nSeveral arrays into a single file in uncompressed Numpy `.npz` format.\n\"\"\"\n\n# ╔═╡ f4ddf1bf-0cbf-47c5-bb5f-f8abf0fb8ac2\n# load NPZ file\nnpz_data = npzread(\"data/mytempdata.npz\")\n\n# ╔═╡ a979107e-f2cf-42da-aefa-5cb249bc7073\n# save NPZ file\nnpzwrite(\"output/mywrite.npz\", npz_data)\n\n# ╔═╡ edd2093e-f84a-4563-acb7-219f2bd07399\n# NPZ type\ntypeof(npz_data)\n\n# ╔═╡ be91882d-fe73-40d0-8e75-30c2e8ddd564\nmd\"\"\"\n### R Data (RDA)\n\nThe RData format (usually with extension `.rdata` or `.rda`) is a format designed for use with R, a system for statistical computation and related graphics, for storing a complete R workspace or selected \"objects\" from a workspace in a form that can be loaded back by R.\n\"\"\"\n\n# ╔═╡ 1f3092e8-3f3a-4d29-a9f5-e64ef96c13a8\n# load RDA file\nR_data = RData.load(\"data/mytempdata.rda\")\n\n# ╔═╡ cf9a1b00-79dd-4305-93ad-69f229319ce2\n# see the data\nR_data[\"tempdata\"]\n\n# ╔═╡ 1b49419d-18cd-4617-9442-15080e3ef588\nbegin\n\t# save RDA file\n\t@rput R_data\n\tR\"save(R_data, file=\\\"output/mywrite.rda\\\")\"\nend\n\n# ╔═╡ c3bce6db-d503-4a68-b83f-278c6d603f07\nmd\"\"\"\n**Note:** we must use the `RCall.jl` package to save `.rda` files.\n\"\"\"\n\n# ╔═╡ 7131ac1c-984e-4ad9-a1cd-b1d46a4f240e\n# RDA type\ntypeof(R_data)\n\n# ╔═╡ 4f70b5df-0026-43cd-b769-d4ca50145fbd\nmd\"\"\"\n### MATLAB® Data (MAT)\n\nMAT-files are binary MATLAB® `.mat` files that store workspace variables.\n\"\"\"\n\n# ╔═╡ 0c1201b9-6acb-4206-a806-e09e04c6a65e\n# load MAT file\nmatlab_data = matread(\"data/mytempdata.mat\")\n\n# ╔═╡ cc555ffc-0eea-4e35-b0d1-36d3a734f9f2\n# see the data\nmatlab_data[\"tempdata\"]\n\n# ╔═╡ 5516dd98-3a87-4801-a62e-e91a95e4923a\n# save MAT file\nmatwrite(\"output/mywrite.mat\", matlab_data)\n\n# ╔═╡ 53be8986-1f06-45a5-9303-5018a3ddf06f\n# MAT type\ntypeof(matlab_data)\n\n# ╔═╡ ecefa934-49a8-4abf-880d-d91d3f9f9d05\nmd\"\"\"\nAll files, when loaded, are `Dict`. The only exception is NPZ data, which is loaded as an `Matrix`.\n\"\"\"\n\n# ╔═╡ 01be19ba-2aaa-4746-af5d-8ce7f1cf3a55\nmd\"\"\"\n## Processing different types of data\n\nWe will mainly cover `Vector` (`Matrix` included), `DataFrame`, and `Dict`. Let's bring back our programming languages dataset `data₂` and start playing it the matrix it's stored in.\n\"\"\"\n\n# ╔═╡ 3a6f9dc0-2186-440a-9d78-5da6acabcdae\nmd\"\"\"\n### Matrix\n\"\"\"\n\n# ╔═╡ 4f9dca90-9f1a-4c0e-a510-fa640d109b0d\ndata₂\n\n# ╔═╡ 57b8265f-be5c-4f05-91c6-6c4fec4f0a6b\nmd\"\"\"\nHere are some quick questions we might want to ask about this simple data.\n\n> **Q1:** Which year was was a given language invented?\n\"\"\"\n\n# ╔═╡ 157e9e3d-2e10-418e-997e-0178c14d7b3d\nfunction year_created_mtx(data, language::String)\n loc = findfirst(data[:,2] .== language)\n !isnothing(loc) && return data[loc,1]\n\terror(\"Error: Language not found!\")\nend\n\n# ╔═╡ e7bd695e-c7d6-4b38-8520-7d915e740015\nmd\"\"\"\n**Note:** this function return the year just when `loc` local variable is not `nothing`. Otherwise, it returns an error message.\n\"\"\"\n\n# ╔═╡ c9ead4e0-aa01-43bc-8107-72d8ec4c073b\nbegin\n\tjulia_year1 = year_created_mtx(data₂, \"Julia\")\n\n\t\"Julia was created in $julia_year1.\"\nend\n\n# ╔═╡ 92b4a2d9-b271-42b3-97d1-647300a9439a\nbegin\n\tcobol_year1 = year_created_mtx(data₂, \"COBOL\")\n\n\t\"COBOL was created in $cobol_year1.\"\nend\n\n# ╔═╡ 01a73335-69b9-4297-9910-a441848fe2c5\nmd\"\"\"\n> **Q2:** How many languages were created in a given year?\n\"\"\"\n\n# ╔═╡ fbf69873-af41-428c-9bba-d63cdb20149b\nfunction langs_per_year_mtx(data, year::Int64)\n\tcount = length(findall(data[:,1] .== year))\n\n\treturn count\nend\n\n# ╔═╡ 1ea19d7e-5748-4559-b2d2-fd4f4d449516\nbegin\n\tlangs_1988₁ = langs_per_year_mtx(data₂, 1988)\n\n\t\"In 1988, $langs_1988₁ language(s) was/were created.\"\nend\n\n# ╔═╡ 2592f7cd-95ec-493c-93e1-bbedf433367f\nbegin\n\tlangs_2006₁ = langs_per_year_mtx(data₂, 2006)\n\n\t\"In 2006, $langs_2006₁ language(s) was/were created.\"\nend\n\n# ╔═╡ 12121f45-8a7b-4709-bc85-b2fde7313a21\nmd\"\"\"\n### DataFrame\n\nNow let's try to store this data in a DataFrame...\n\"\"\"\n\n# ╔═╡ d455f80e-c5b5-4b1a-9667-86fade5ee3d3\n# anonymous column names\ndata₃ = DataFrame(data₂, :auto)\n\n# ╔═╡ 42c72fde-8331-4e40-b761-c50d0e2e8486\n# specifying column names\ndata₄ = DataFrame(Year = data₂[:,1], Language = data₂[:,2])\n\n# ╔═╡ 201a8534-91ee-4ac9-a120-51b29f196c23\n# specifying both column names and data types\ndata₅ = DataFrame(Year = Int.(data₂[:,1]), Language = string.(data₂[:,2]))\n\n# ╔═╡ 0b14e9fc-62e6-4ad7-ab67-eb36e340749c\nmd\"\"\"\n> **Q1:** Which year was was a given language invented?\n\"\"\"\n\n# ╔═╡ 679b2b83-07f9-40bd-bdd1-89e7233bfade\nfunction year_created_df(df,language::String)\n loc = findfirst(df.Language .== language)\n\t!isnothing(loc) && return df.Year[loc]\n\terror(\"Error: Language not found!\")\nend\n\n# ╔═╡ f4738476-8b05-4dbc-a15e-6b3d59c90c50\nmd\"\"\"\n**Note:** this function return the year just when `loc` local variable is not `nothing`. Otherwise, it returns an error message.\n\"\"\"\n\n# ╔═╡ c6b170be-6576-480e-b2ba-65d3b853871a\nbegin\n\tjulia_year2 = year_created_df(data₅, \"Julia\")\n\n\t\"Julia was created in $julia_year2.\"\nend\n\n# ╔═╡ 9977fdaa-db30-43a5-bd58-14087c2163e4\nbegin\n\tcobol_year2 = year_created_df(data₅, \"COBOL\")\n\n\t\"COBOL was created in $cobol_year2.\"\nend\n\n# ╔═╡ a137ebd7-9db4-4c29-a694-b1acad5214a3\nmd\"\"\"\n> **Q2:** How many languages were created in a given year?\n\"\"\"\n\n# ╔═╡ 2cc2938b-58d5-4c27-bdab-dddf22231bc8\nfunction langs_per_year_df(df, year::Int64)\n count = length(findall(df.Year.==year))\n return count\nend\n\n# ╔═╡ ae7a1714-2245-4d5a-89bb-10b3adff787a\nbegin\n\tlangs_1988₂ = langs_per_year_mtx(data₅, 1988)\n\n\t\"In 1988, $langs_1988₂ language(s) was/were created.\"\nend\n\n# ╔═╡ ce4ac86d-5e06-4c3e-93d6-ebdee46439bd\nbegin\n\tlangs_2006₂ = langs_per_year_mtx(data₅, 2006)\n\n\t\"In 2006, $langs_2006₂ language(s) was/were created.\"\nend\n\n# ╔═╡ 515b7479-97d8-464b-8245-1034f3cd8bdc\nmd\"\"\"\n### Dictionary\n\nNext, we'll use dictionaries. A quick way to create a dictionary is with the `Dict()` command. But this creates a dictionary without types. Here, we will specify the types of this dictionary.\n\"\"\"\n\n# ╔═╡ 3b08a2c8-546b-4a6c-8ae0-2a1e64578af8\n# dict from a list of tuples\nDict([(\"A\", 1), (\"B\", 2)])\n\n# ╔═╡ 21551a38-57fc-42c2-81a2-b314bb06250b\nmd\"\"\"\n**Note:** the key type is `String`, while the value type is `Int64`.\n\"\"\"\n\n# ╔═╡ 6da1f5a7-56a2-4a7a-abfc-25ec3f44f892\n# dictionary from a list of tuples\nDict([(\"A\", 1), (\"B\", 2), (\"C\", [1,2,3])])\n\n# ╔═╡ 43ad8297-d94c-45a0-941f-ab0d5bfd2ddb\nmd\"\"\"\n**Note:** the key type is `String`, while the value type is `Any`, since we have integers and arrays as values.\n\"\"\"\n\n# ╔═╡ 9390d98f-94eb-48bb-ba9c-e6b3f67f762f\n# empty dict\nDict()\n\n# ╔═╡ 30718df7-5085-4d0d-8a86-7b4a08ff20b2\n# empty dict, specifying that keys are Integers and values are Vectors of Strings\ndict₁ = Dict{Integer, Vector{String}}()\n\n# ╔═╡ f77a5189-19b4-4f99-b394-72190253912f\n# appending a key-value pair to dict\ndict₁[2012] = [\"Julia\", \"Programming\", \"Language\"]\n\n# ╔═╡ 50ba8f3b-5104-4d4f-85ea-831d4afe9164\n# updated dict\ndict₁\n\n# ╔═╡ bb814af7-62e3-4744-955f-31b557540057\nmd\"\"\"\nNow, let's populate the dictionary with years as keys and vectors that hold all the programming languages created in each year as their values. Even though this looks like more work, we often need to do it just once.\n\"\"\"\n\n# ╔═╡ 9193df28-7ed1-4853-a97b-aa5a1232e07b\nbegin\n\tlang_dict = Dict{Integer, Vector{String}}()\n\n\tfor i in 1:size(data₂,1)\n\t\tyear, lang = data₂[i,:]\n\t\tif year ∈ keys(lang_dict)\n\t\t\tlang_dict[year] = push!(lang_dict[year], lang)\n\t\telse\n\t\t\tlang_dict[year] = [lang]\n\t\tend\n\tend\nend\n\n# ╔═╡ c5aca233-9a26-4800-9b8d-7f0f03852626\nlang_dict\n\n# ╔═╡ 7b2d5919-9629-4ca9-8195-f26183734044\nmd\"\"\"\n> **Note:** there is an `enumerate()` method in Julia which is useful when you need not only the values `x` over which you are iterating, but also the number of iterations (index) so far.\n**Syntax:**\n```julia\nfor (index, value) in enumerate(df.column)\n```\n\"\"\"\n\n# ╔═╡ d8054919-1554-4c73-a4a2-09383ee09224\nmd\"\"\"\nWe can check the size of the dictionary...\n\"\"\"\n\n# ╔═╡ 7d57f6cc-ab44-4658-a73e-92c873111155\nlength(keys(lang_dict))\n\n# ╔═╡ a322a0e7-3984-4c00-95a5-7b23fc6ec06f\nmd\"\"\"\nOr we can check the size of the vector made up by unique `Year` values...\n\"\"\"\n\n# ╔═╡ e0a28251-a7d6-4c17-b49e-84ffc91c60b6\nlength(unique(data₂[:,1]))\n\n# ╔═╡ 9073e71f-b922-44a4-a470-5cb081588fcd\nmd\"\"\"\n> **Q1:** Which year was was a given language invented?\n\"\"\"\n\n# ╔═╡ f9325e7b-8df8-448a-98b2-9ea8add93da6\nfunction year_created_dict(dict,language::String)\n keys_vec = collect(keys(dict))\n lookup = map(keyid -> findfirst(dict[keyid] .== language), keys_vec)\n \n return keys_vec[findfirst((!isnothing).(lookup))]\nend\n\n# ╔═╡ c33df74d-dd81-4efa-81d6-a5deb4685f1d\nbegin\n\tjulia_year3 = year_created_dict(lang_dict, \"Julia\")\n\n\t\"Julia was created in $julia_year3.\"\nend\n\n# ╔═╡ a08ad2fd-5d3c-4e76-a059-0608de3e36aa\nmd\"\"\"\n> **Q2:** How many languages were created in a given year?\n\"\"\"\n\n# ╔═╡ fb6df54d-0765-4493-b889-17707ff0cf14\nlangs_per_year_dict(dict, year::Int64) = length(dict[year])\n\n# ╔═╡ d5e60574-5afd-498c-aedd-1f5ffc4c6bd7\nbegin\n\tlangs_1988₃ = langs_per_year_dict(lang_dict, 1988)\n\n\t\"In 1988, $langs_1988₃ language(s) was/were created.\"\nend\n\n# ╔═╡ ee8bcf97-9efa-47f0-a82e-cfaa2efd68e6\nmd\"\"\"\n## Missing data\n\nLet's remove the first year value from our data (Matrix) and, after that, create a DataFrame...\n\"\"\"\n\n# ╔═╡ b3927e97-7516-4a80-bcc1-49614cf67166\nbegin\n\tdata₂[1,1] = missing\n\n\tdata₆ = DataFrame(Year=data₂[:,1], Language=data₂[:,2])\nend\n\n# ╔═╡ dc7ed277-b044-464e-8ad3-998a83b00d1b\nmd\"\"\"\nWe can now use the `dropmissing!` function to remove (inplace) the line with missing value...\n\"\"\"\n\n# ╔═╡ e2b6b920-2e05-4168-af16-07e9611d895d\ndropmissing!(data₆)\n\n# ╔═╡ Cell order:\n# ╟─c730d000-5ed6-11ec-36b6-39741ccad6c7\n# ╟─62c5d4f2-9776-43ae-8125-0d429d6cde42\n# ╟─34f92fb1-6c1e-4db6-b795-8a526007ea92\n# ╟─13a10dac-8c7e-4e72-9fa9-d58ca8dd0202\n# ╟─5100df3f-c5d3-4346-bcd9-8afc92bc559c\n# ╠═abe62085-b630-4816-af11-b39133892849\n# ╟─51c909b1-1d37-458f-acd6-68f4041bc92f\n# ╟─6483858c-2e58-4930-b4e9-76b47032eac4\n# ╠═89a5a316-5058-4ff2-8d71-fc832a84c58d\n# ╠═853a4e90-ac39-4d73-9953-c7b70e8f78ef\n# ╟─3a22c018-2ca7-41df-9ee4-91dc8b64d940\n# ╠═b4fcdcf9-793f-4d4a-a5fb-950108cb8188\n# ╟─cfa37c7c-810c-4095-8887-262dee4a9d04\n# ╠═4b651b5a-e562-46ef-a3b5-8ee85b5a61ed\n# ╟─11471bbf-b7b4-4b6e-90cb-9e9ff47bbe4a\n# ╠═2652dc01-d80d-46d9-ae7a-9afa534e88cb\n# ╟─b2f35e6b-8c19-4729-87a3-292858bfbcb5\n# ╠═e1210609-a216-4d54-be63-04f10c5c15bc\n# ╠═008b635f-c4e5-475a-83af-4bc3fc722344\n# ╟─934c8549-c86c-45e6-a9f5-56297c73513d\n# ╠═92708ece-3620-4cf5-b09d-098002044623\n# ╟─cac4f1b5-f9e3-469e-9576-553a1cf1b363\n# ╠═3d378ec4-659f-4032-a5b7-6d6b6d402c2f\n# ╟─e50ae64c-ff64-4597-bf75-d7c921d23225\n# ╠═d9ea3574-2ffb-4fdb-9ced-db1dc669ecd9\n# ╠═09ff6d8b-15f2-4d8e-a775-dee357a417e4\n# ╠═843a668f-7b08-4bce-b02a-3153d0eb7d0d\n# ╠═159a35f4-09fd-47bd-9935-88668a7e7f27\n# ╟─494ebede-80d0-430e-91aa-0a9050a1bb29\n# ╠═00d12274-3057-4a52-8400-0c8c3c358e6b\n# ╟─fede3ce2-da03-4ff9-a13e-7ce55ec05bf6\n# ╠═74783bbb-3c9d-4e15-bc54-b3d8e7c2d230\n# ╟─e4b3a444-c487-4fe8-8048-873b8a3affb7\n# ╠═0becba29-d5ff-4595-86ab-6b0575674047\n# ╠═9d522bdc-d066-40ac-84c4-47287d9e07e0\n# ╟─79de9741-c913-4c00-8833-4f1b68f80ea5\n# ╠═fd724d83-41bb-422c-860e-2bbeff17e0dc\n# ╟─51301eeb-709a-4ea9-a1a5-d7967f8dd55d\n# ╠═64e7e90b-cd7d-4569-a715-4f27f1787e40\n# ╟─e5f2c69b-fbd8-4048-aaed-792a64a4d66c\n# ╠═26047637-1b77-4203-b705-e34f74137295\n# ╠═0f3d505c-a575-419f-8155-fd071f510714\n# ╟─c2f1eab2-862a-4eb8-b233-71567cdc9963\n# ╠═3a924b3e-3dbe-49b6-9e5e-5a48b0ffd385\n# ╟─58bad348-0586-4d0f-8d54-7c3e1a7a2c40\n# ╠═036de982-36ad-431a-8445-517178626911\n# ╟─4ead9039-f4c2-4f82-bf1e-2146718014a3\n# ╠═bb04dc6c-e62e-4b2c-a247-ebe4836d8013\n# ╟─d9550872-fa7c-4ebd-9a4d-828182c8e49d\n# ╠═e01a65ab-394a-4718-b9ae-ca2bb30e20b5\n# ╟─1eb26b3c-8a5a-4648-bb73-f8291b656edc\n# ╠═cb027055-2cf6-4f74-b265-9d01c23c2967\n# ╟─12dccfc3-e976-46e6-81b0-dc51b48309f4\n# ╠═403ac783-9c02-4fd1-8506-afe0af36a14b\n# ╟─36d8898e-980c-4f54-bbff-277ded2229ea\n# ╠═8d769d53-1902-4a09-8228-ce60174b22bb\n# ╟─bc29d2b5-e6c2-4b45-8b79-cbb012659be1\n# ╟─7c2fef9c-4e9a-4637-bc8e-6636af5f98ae\n# ╠═8f51aeb5-3e75-4e5a-8c8f-ed0201eb8ce0\n# ╠═879ac394-8598-4399-957f-1280ecd99478\n# ╠═0d27e3b3-79e3-424d-bc6b-94252900f7fb\n# ╠═13053d54-8680-41e2-b416-8a7bc50f6c92\n# ╟─e0f49c77-0c0d-4740-9227-5619d14748b6\n# ╠═f4ddf1bf-0cbf-47c5-bb5f-f8abf0fb8ac2\n# ╠═a979107e-f2cf-42da-aefa-5cb249bc7073\n# ╠═edd2093e-f84a-4563-acb7-219f2bd07399\n# ╟─be91882d-fe73-40d0-8e75-30c2e8ddd564\n# ╠═1f3092e8-3f3a-4d29-a9f5-e64ef96c13a8\n# ╠═cf9a1b00-79dd-4305-93ad-69f229319ce2\n# ╠═1b49419d-18cd-4617-9442-15080e3ef588\n# ╟─c3bce6db-d503-4a68-b83f-278c6d603f07\n# ╠═7131ac1c-984e-4ad9-a1cd-b1d46a4f240e\n# ╟─4f70b5df-0026-43cd-b769-d4ca50145fbd\n# ╠═0c1201b9-6acb-4206-a806-e09e04c6a65e\n# ╠═cc555ffc-0eea-4e35-b0d1-36d3a734f9f2\n# ╠═5516dd98-3a87-4801-a62e-e91a95e4923a\n# ╠═53be8986-1f06-45a5-9303-5018a3ddf06f\n# ╟─ecefa934-49a8-4abf-880d-d91d3f9f9d05\n# ╟─01be19ba-2aaa-4746-af5d-8ce7f1cf3a55\n# ╟─3a6f9dc0-2186-440a-9d78-5da6acabcdae\n# ╠═4f9dca90-9f1a-4c0e-a510-fa640d109b0d\n# ╟─57b8265f-be5c-4f05-91c6-6c4fec4f0a6b\n# ╠═157e9e3d-2e10-418e-997e-0178c14d7b3d\n# ╟─e7bd695e-c7d6-4b38-8520-7d915e740015\n# ╠═c9ead4e0-aa01-43bc-8107-72d8ec4c073b\n# ╠═92b4a2d9-b271-42b3-97d1-647300a9439a\n# ╟─01a73335-69b9-4297-9910-a441848fe2c5\n# ╠═fbf69873-af41-428c-9bba-d63cdb20149b\n# ╠═1ea19d7e-5748-4559-b2d2-fd4f4d449516\n# ╠═2592f7cd-95ec-493c-93e1-bbedf433367f\n# ╟─12121f45-8a7b-4709-bc85-b2fde7313a21\n# ╠═d455f80e-c5b5-4b1a-9667-86fade5ee3d3\n# ╠═42c72fde-8331-4e40-b761-c50d0e2e8486\n# ╠═201a8534-91ee-4ac9-a120-51b29f196c23\n# ╟─0b14e9fc-62e6-4ad7-ab67-eb36e340749c\n# ╠═679b2b83-07f9-40bd-bdd1-89e7233bfade\n# ╟─f4738476-8b05-4dbc-a15e-6b3d59c90c50\n# ╠═c6b170be-6576-480e-b2ba-65d3b853871a\n# ╠═9977fdaa-db30-43a5-bd58-14087c2163e4\n# ╟─a137ebd7-9db4-4c29-a694-b1acad5214a3\n# ╠═2cc2938b-58d5-4c27-bdab-dddf22231bc8\n# ╠═ae7a1714-2245-4d5a-89bb-10b3adff787a\n# ╠═ce4ac86d-5e06-4c3e-93d6-ebdee46439bd\n# ╟─515b7479-97d8-464b-8245-1034f3cd8bdc\n# ╠═3b08a2c8-546b-4a6c-8ae0-2a1e64578af8\n# ╠═21551a38-57fc-42c2-81a2-b314bb06250b\n# ╠═6da1f5a7-56a2-4a7a-abfc-25ec3f44f892\n# ╟─43ad8297-d94c-45a0-941f-ab0d5bfd2ddb\n# ╠═9390d98f-94eb-48bb-ba9c-e6b3f67f762f\n# ╠═30718df7-5085-4d0d-8a86-7b4a08ff20b2\n# ╠═f77a5189-19b4-4f99-b394-72190253912f\n# ╠═50ba8f3b-5104-4d4f-85ea-831d4afe9164\n# ╟─bb814af7-62e3-4744-955f-31b557540057\n# ╠═9193df28-7ed1-4853-a97b-aa5a1232e07b\n# ╠═c5aca233-9a26-4800-9b8d-7f0f03852626\n# ╟─7b2d5919-9629-4ca9-8195-f26183734044\n# ╟─d8054919-1554-4c73-a4a2-09383ee09224\n# ╠═7d57f6cc-ab44-4658-a73e-92c873111155\n# ╟─a322a0e7-3984-4c00-95a5-7b23fc6ec06f\n# ╠═e0a28251-a7d6-4c17-b49e-84ffc91c60b6\n# ╟─9073e71f-b922-44a4-a470-5cb081588fcd\n# ╠═f9325e7b-8df8-448a-98b2-9ea8add93da6\n# ╠═c33df74d-dd81-4efa-81d6-a5deb4685f1d\n# ╟─a08ad2fd-5d3c-4e76-a059-0608de3e36aa\n# ╠═fb6df54d-0765-4493-b889-17707ff0cf14\n# ╠═d5e60574-5afd-498c-aedd-1f5ffc4c6bd7\n# ╟─ee8bcf97-9efa-47f0-a82e-cfaa2efd68e6\n# ╠═b3927e97-7516-4a80-bcc1-49614cf67166\n# ╟─dc7ed277-b044-464e-8ad3-998a83b00d1b\n# ╠═e2b6b920-2e05-4168-af16-07e9611d895d\n", "meta": {"hexsha": "c46a5ac323833890ed7e7d1aaf24c7030bd7d04e", "size": 24674, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "01_Data.jl", "max_stars_repo_name": "fnaghetini/DataScience", "max_stars_repo_head_hexsha": "5cd1c2a9c72aacc8a67800c74e394fb0e2045f2d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "01_Data.jl", "max_issues_repo_name": "fnaghetini/DataScience", "max_issues_repo_head_hexsha": "5cd1c2a9c72aacc8a67800c74e394fb0e2045f2d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "01_Data.jl", "max_forks_repo_name": "fnaghetini/DataScience", "max_forks_repo_head_hexsha": "5cd1c2a9c72aacc8a67800c74e394fb0e2045f2d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4439140811, "max_line_length": 323, "alphanum_fraction": 0.731944557, "num_tokens": 11321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32423541204073586, "lm_q2_score": 0.22000708951749934, "lm_q1q2_score": 0.07133408932158945}} {"text": "# # Stuff I Like About The Julia Programming Language\n\n# `git_club 2020-06-19` - Hannes\n\n# [View this notebook online](https://nbviewer.jupyter.org/github/Hasnep/stuff-i-like-about-julia/blob/master/stuff-i-like-about-julia.ipynb)\n\n# > Julia's unofficial tagline is \"Looks like Python, feels like Lisp, runs like Fortran.\"\n# > I've been learning Julia for slightly less than a year now, and I'd like to share some of the things I've enjoyed about it.\n# > I'll give an overview of the language's main features with code examples and discuss whether it really is the future scientific computing.\n\n# Technically:\n# > Julia is a high level, JIT compiled, dynamic language designed with multiple dispatch, automatic differentiation and metaprogramming.\n\n# In practice:\n# > Julia finds a balance between being fast and easy to use with lots of features you'll miss when you use another language.\n\n# ## History\n\n# - Julia was started in 2009 by Jeff Bezanson, Stefan Karpinski, Viral B. Shah, and Alan Edelman\n# - Announced in 2012\n# - Version 1.0 was released in 2018\n# - Now on version 1.4, heading for 1.5 soon\n\n# ## Julia is easy to use\n\n# Let's write a function from scratch to sum an array of numbers, first in Python:\n# ```python\n# def my_sum(array):\n# \"\"\"\n# Sum a list.\n# \"\"\"\n# total = 0\n# for x in array:\n# total += x\n# return total\n# ```\n\n# Then in Julia:\n\n\"\"\"\nSum an array.\n\"\"\"\nfunction my_sum(array)\n total = 0\n for x in array\n total += x\n end\n return total\nend\n\n# This syntax will be familliar if you've used Python.\n \nmy_sum(1:10)\n\n# Benchmarks for this function in different languages:\n# - C: ~10ms\n# - Python: ~500ms\n# - Julia: ~10ms\n# > Source: [An Introduction to Julia (Beginner Level) | SciPy 2018 Tutorial | Jane Herriman, Sacha Verweij](https://www.youtube.com/watch?v=b5xvVyzUnXI)\n\n# ## It's fast\n\n# Julia was designed to solve the \"two language problem\", where researchers use a slower, high-level language for research and then have to use a slower, low-level language once they hit a bottleneck or for production.\n# Julia is both languages at the same time!\n\n# Some benchmarks (from the Julia website) of different languages relative to C.\n# ![Benchmarks of different languages relative to C](https://julialang.org/assets/benchmarks/benchmarks.svg)\n# > Source: https://julialang.org/benchmarks/\n\n# These benchmarks try to compare implementations of the same algorithm.\n# Julia is comparable to compiled languages like Rust, Go, Fortran, etc. and is sometimes faster than C.\n# Python is sometimes 100x slower than C.\n# R is a bit slower than that.\n\n# How is it so fast?\n\n# Generally languages fall into two categories:\n\n# - Compiled languages like C or Rust compile all the code before you run\n# - Interpreted languages like Python or R don't compile\n\n# Julia uses a _Just-In-Time_ (JIT) compiler which compiles a function the first time it is called.\n\n# In my opinion, speed doesn't matter all that much\n\n# - JIT compilation takes a short while\n# - My time is more valuable than the computer's time\n\n# Now, back to some code!\n\n# ## Dynamically typed\n\n# Let's write a function to calculate the $n$th Fibonacci number.\n# We want the input `n` to only allow integers and we want to specify the output should only be integers.\n\n\"\"\"\nCalculate the nth Fibonacci number.\n\"\"\"\nfunction fib(n::Integer)::Integer\n if n < 2\n return n\n else\n return fib(n - 1) + fib(n - 2)\n end\nend\n\n# If we try to run the function with a non-integer input\n\n# ```julia\n# julia> fib(0.5)\n# ```\n\n# Julia will throw an error:\n\n# ```\n# ERROR: MethodError: no method matching fib(::Float64)\n# Closest candidates are:\n# fib(::Integer)\n# ```\n\nfib(20)\n\n# There is also a one-line function notation that is useful for short functions\n\nshort_fib(n::Integer)::Integer = n < 2 ? n : short_fib(n - 1) + short_fib(n - 2)\n\nshort_fib(20)\n\n# ## It's free!\n\n# Julia is MIT licenced.\n\n# ## Broadcasting\n\n# In Python, most functions accept one element.\n# Running this code:\n# ```python\n# >>> import math\n# >>> math.sin([1, 2, 3])\n# ```\n# will give this error:\n# ```\n# TypeError: must be real number, not list\n# ```\n# Pythonistas would probably use a list comprehension:\n# ```python\n# >>> [math.sin(x) for x in [1, 2, 3]]\n# ```\n# or a map:\n# ```python\n# >>> map(math.sin, [1, 2, 3])\n# ```\n# ```\n# [0.8414709848078965, 0.9092974268256817, 0.1411200080598672]\n# ```\n\n# In R, most functions are vectorised\n# ```R\n# > sin(c(1, 2, 3))\n# ```\n# ```\n# [1] 0.8414710 0.9092974 0.1411200\n# ```\n\n# In Julia, functions are not vectorised, for example, this line:\n# ```julia\n# julia> sin([1, 2, 3])\n# ```\n# gives this error:\n# ```\n# ERROR: MethodError: no method matching sin(::Array{Int64,1})\n# ```\n\n# Using the broadcast operator, the funciton is applied elementwise!\n\nsin.([1, 2, 3])\n\n# Broadcasting even works for user functions\n \nfib.(1:10)\n\n# And for operators:\n\n## What are the first 10 square numbers?\n(1:10).^2\n\n# This is powerful, but sometimes tricky syntax.\n# For example, adding a dot makes the length function broadcast over the array:\n\nlength(split(\"How many words are in this sentence?\"))\n# +\nlength.(split(\"How many characters are each of these words?\"))\n\n# ## Useful Unicode characters\n\n# Julia lets you type lots of symbols using LaTeX-y abbreviations, e.g. type `\\alpha` and press tab for α or `\\sqrt` and tab for √.\n\nα = 37\n\n# The square root symbol is an abbreviation for the `sqrt()` function:\n\n√α\n\n# Some constants like π for pi and ℯ for Euler's constant are predefined:\n\n## Use the approximate equals sign ≈ because this calculation is not exact\nℯ^(im * π) ≈ -1\n \n# You can define your own operators using either built in functions:\n\nconst ⊂ = issubset\n[2, 5] ⊂ [1, 2, 3, 4, 5]\n\n# or user functions:\n\nconst ∑ = my_sum\n∑(1:10)\n\n# Because Julia supports almost any symbol you can type as a variable name, that includes emojis!\n\n🔥 = 10\n🐶 = 20\n🌭 = 30\n🔥 + 🐶 == 🌭\n\n# ## Julia is (mostly) written in Julia\n\n# If you can read Julia code, you can also read Julia's source code to understand what it does.\n# I looked at the most recent PR as an example:\n\ntensor(A::AbstractArray, B::AbstractArray) = [a * b for a in A, b in B]\nconst ⊗ = tensor\n#-\n[1, 2] ⊗ [3, 4, 5]\n\n# Python's numpy is fast because it's mostly written in C/C++ (51.4%), but if you want to do something that numpy can't do, you need to either use C++ or write slower Python code.\n\n# This bridges the gap between a Julia user and a Julia developer.\n# For every user of Julia, there's another possible contributer.\n\n# ## Multiple dispatch\n\n# As an example, let's build a small Julia package based on [Measurements.jl](https://github.com/JuliaPhysics/Measurements.jl/).\n\n\"\"\"\nA number with some error.\n\"\"\"\nstruct Uncertain <: Real\n val::Real\n err::Real\nend\n\n# Define the standard gravity on earth.\n\ng = Uncertain(9.8, 0.1)\n\n# Wouldn't it be nicer to show an uncertain number with the plus/minus symbol?\n# Let's write a show function that dispatches on the Uncertain type:\n\nBase.show(io::IO, x::Uncertain) = print(io, \"$(x.val) ∓ $(x.err)\")\n\ng\n\n# Let's define the plus/minus operator to create `Uncertain` numbers:\n\n∓(a::Real, b::Real) = Uncertain(a, b)\nmy_height = 190 ∓ 1\n\n# How do you add two uncertain measurements?\n\nmy_brothers_height = 175 ∓ 2\n\n# ```julia\n# julia> my_height + my_brothers_height\n# ```\n# ```\n# ERROR: + not defined for Uncertain\n# ```\n\n# $$\n# Q = a + b \\\\\n# {\\delta Q} = \\sqrt{(\\delta a)^2 + (\\delta b)^2}\n# $$\n\nBase.:+(a::Uncertain, b::Uncertain) = (a.val + b.val) ∓ sqrt(a.err^2 + b.err^2)\nmy_height + my_brothers_height\n\n# Similar for subtraction.\n\nBase.:-(a::Uncertain, b::Uncertain) = (a.val - b.val) ∓ sqrt(a.err^2 + b.err^2)\nmy_height - my_brothers_height\n\n# Slightly more complicated for multiplcation and division.\n\n\nfunction Base.:*(a::Uncertain, b::Uncertain) \n total_value = a.val * b.val\n total_error = total_value * sqrt((a.err / a.val)^2 + (b.err / b.val)^2)\n return Uncertain(total_value, total_error)\nend\n\nfunction Base.:/(a::Uncertain, b::Uncertain) \n total_value = a.val / b.val\n total_error = total_value * sqrt((a.err / a.val)^2 + (b.err / b.val)^2)\n return Uncertain(total_value, total_error)\nend\n#-\nmy_height * my_brothers_height\n#-\nmy_height / my_brothers_height\n\n# Finally powers, again the exact formula is not important.\n\nBase.:^(a::Uncertain, b::Real) = (a.val^b) ∓ (abs(b) * a.val^(b - 1) * a.err)\nmy_height^2.0\n\n# Finally, we need to tell Julia what to do if we give it an `Uncertain` number and some other number in the same operation.\n\n# ```julia\n# julia> 1 + g\n# ```\n# ```\n# ERROR: promotion of types Int64 and Uncertain failed to change any arguments\n# ```\n\n# We want to convert both numbers to our `Uncertain` type:\n\nBase.promote_rule(::Type{Uncertain}, ::Type{T}) where T <: Real = Uncertain\n\n# Coverting a real number to our Uncertain type just means we add an error of 0: \n\nBase.convert(::Type{Uncertain}, x::Real) = Uncertain(x, 0)\n\n# When Julia wants to convert an Uncertain number it doesn't need to do anything :\n\nBase.convert(::Type{Uncertain}, x::Uncertain) = x\n#-\n1 + g\n\n# Now we can solve a simple problem, how much time would it take if I dropped a ball from my height and my brother caught it at his height?\n\n# Solve for t:\n# $$\n# t = \\frac{\\sqrt{2 a s + u^2} - u}{a} = \\frac{\\sqrt{2 g (h_1 - h_2)}}{g}\n# $$\n\nt = ((2 * g * (my_height - my_brothers_height))^0.5) / g\n\n# Let's use the actual Measurements.jl package\n\nusing Measurements: Measurement, ±\n\n# Let's solve the same problem as before and make sure we get the same result:\n\ng = 9.8 ± 0.1\nmy_height = 190 ± 1\nmy_brothers_height = 175 ± 2\n\nt = (2 * g * (my_height - my_brothers_height))^0.5 / g\n\n# This next part is inspired by a JuliaCon talk called [_The Unreasonable Effectiveness of Multiple Dispatch_](https://www.youtube.com/watch?v=kc9HwsxE1OY) by one of the Julia co-founders, Stefan Karpinski.\n\n# All the \"methods\" are outside the class definition, that can include being in a completely different package.\n\n# Let's solve the same problem using differential equations!\n\n# Calculate the position of the ball between time $t = 0$ and $t = 3$\n# $$\n# v = \\frac{ds}{dt}\n# $$\n# $$\n# f(t) = -g t = - (9.8 \\pm 0.1) t\n# $$\n# With initial conditions $s_0 = 190 \\pm 1$\n\nusing DifferentialEquations\n#-\nf(s, p, t) = -g * t\ns₀ = my_height\ntime_span = (0.0, 3.0)\nproblem = ODEProblem(f, s₀, time_span)\n#-\nsolution = solve(problem, Tsit5(), saveat=0.1)\n#-\nusing Plots\n#-\nplot(\n solution.t,\n solution.u,\n title=\"Solution to the ODE\",\n xaxis=\"Time (t) in seconds\",\n yaxis=\"Displacement s(t) in metres\"\n)\n\n# ## Interoperability\n\n# We can import any python module using the PyCall package:\n\nusing PyCall\n#-\nmath = pyimport(\"math\")\n#-\nmath.sqrt(100)\n\n# We can mix Python functions and variables with Julia code:\n\nmath.sin.([π, math.pi, 2π, 2 * math.pi])\n\n# We can define Python functions that call Julia funcitons\n\npy\"\"\"\ndef pyfib(n, fun):\n if n < 2:\n return n\n else:\n return fun(n - 1, pyfib) + fun(n - 2, pyfib)\n\"\"\"\n#-\nfunction jlfib(n, fun)\n if n < 2\n return n\n else\n return fun(n - 1, jlfib) + fun(n - 2, jlfib)\n end\nend\n#-\njlfib(20, py\"pyfib\")\n\n# If you have some code written in another language (like Python), there can be a smooth transition to using Julia.\n\n# # Summary\n\n# - Julia looks a bit like Python\n# - It's fast (with some caveats)\n# - It's free!\n# - It's written in Julia\n# - It has powerful features like:\n# - Broadcasting syntax\n# - Unicode variables\n# - Multiple dispatch\n# - Good interoperability\n\n# Other stuff I haven't mentioned:\n# - Automatic differentiation (Swift also has this now)\n# - Metaprogramming\n# - Data science stuff (The first two letters of Jupyter Notebooks are named after Julia!)\n", "meta": {"hexsha": "f7192404a272cba43f68d01a4b9a00041950a72e", "size": 11755, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/stuff-i-like-about-julia.jl", "max_stars_repo_name": "Hasnep/stuff-i-like-about-julia", "max_stars_repo_head_hexsha": "47e92d4889ac9a9e18213066f66dcb84d7476b41", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/stuff-i-like-about-julia.jl", "max_issues_repo_name": "Hasnep/stuff-i-like-about-julia", "max_issues_repo_head_hexsha": "47e92d4889ac9a9e18213066f66dcb84d7476b41", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/stuff-i-like-about-julia.jl", "max_forks_repo_name": "Hasnep/stuff-i-like-about-julia", "max_forks_repo_head_hexsha": "47e92d4889ac9a9e18213066f66dcb84d7476b41", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2975391499, "max_line_length": 218, "alphanum_fraction": 0.6801361123, "num_tokens": 3432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186969238628498, "lm_q2_score": 0.1688569500503904, "lm_q1q2_score": 0.07069988555896134}} {"text": "# Copyright (c) 2019 Arpit Bhatia and contributors #src\n# #src\n# Permission is hereby granted, free of charge, to any person obtaining a copy #src\n# of this software and associated documentation files (the \"Software\"), to deal #src\n# in the Software without restriction, including without limitation the rights #src\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #src\n# copies of the Software, and to permit persons to whom the Software is #src\n# furnished to do so, subject to the following conditions: #src\n# #src\n# The above copyright notice and this permission notice shall be included in all #src\n# copies or substantial portions of the Software. #src\n# #src\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #src\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #src\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #src\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #src\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #src\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #src\n# SOFTWARE. #src\n\n# # Solvers and Solutions\n\n# **Originally Contributed by**: Arpit Bhatia\n\n# The purpose of this part of the tutorial is to introduce you to solvers and\n# how to use them with JuMP. We'll also learn what to do with a problem after\n# the solver has finished optimizing it.\n\n# ## What is a Solver?\n\n# A solver is a software package that incorporates algorithms for finding\n# solutions to one or more classes of problem. For example, GLPK, which we used\n# in the previous tutorials is a solver for linear programming (LP) and mixed\n# integer programming (MIP) problems. It incorporates algorithms such as the\n# simplex method, interior-point method etc. JuMP currently supports a number of\n# open-source and commercial solvers which can be viewed in the [Supported-solvers](@ref)\n# table.\n\n# ## What is MathOptInterface?\n\n# Each mathematical optimization solver API has its own concepts and data\n# structures for representing optimization models and obtaining results.\n# However, it is often desirable to represent an instance of an optimization\n# problem at a higher level so that it is easy to try using different solvers.\n\n# MathOptInterface (MOI) is an abstraction layer designed to provide an\n# interface to mathematical optimization solvers so that users do not need to\n# understand multiple solver-specific APIs. MOI can be used directly, or through\n# a higher-level modeling interface like JuMP.\n\n# Note that JuMP re-exports MathOptInterface and you can use the shortcut `MOI`\n# to refer to MathOptInterface in your code.\n\n# ## Constructing a model\n\n# JuMP models can be created in three different modes: `AUTOMATIC`, `MANUAL` and\n# `DIRECT`. We'll use the following LP to illustrate them.\n\n# ```math\n# \\begin{aligned}\n# & \\max_{x,y} & x + 2y \\\\\n# & \\;\\;\\text{s.t.} & x + y &\\leq 1 \\\\\n# & & 0\\leq x, y &\\leq 1 \\\\\n# \\end{aligned}\n# ```\n\nusing JuMP\nusing GLPK\n\n# ### `AUTOMATIC` Mode\n\n# #### With Optimizer\n\n# This is the easiest method to use a solver in JuMP. In order to do so, we\n# simply set the solver inside the Model constructor.\n\nmodel_auto = Model(GLPK.Optimizer)\n@variable(model_auto, 0 <= x <= 1)\n@variable(model_auto, 0 <= y <= 1)\n@constraint(model_auto, x + y <= 1)\n@objective(model_auto, Max, x + 2y)\noptimize!(model_auto)\nobjective_value(model_auto)\n\n# #### No Optimizer (at first)\n\n# It is also possible to create a JuMP model with no optimizer attached. After\n# the model object is initialized empty and all its variables, constraints and\n# objective are set, then we can attach the solver at `optimize!` time.\n\nmodel_auto_no = Model()\n@variable(model_auto_no, 0 <= x <= 1)\n@variable(model_auto_no, 0 <= y <= 1)\n@constraint(model_auto_no, x + y <= 1)\n@objective(model_auto_no, Max, x + 2y)\nset_optimizer(model_auto_no, GLPK.Optimizer)\noptimize!(model_auto_no)\nobjective_value(model_auto_no)\n\n# Note that we can also enforce the automatic mode by passing\n# `caching_mode = MOIU.AUTOMATIC` in the Model function call.\n\n# ### `MANUAL` Mode\n\n# This mode is similar to the `AUTOMATIC` mode, but there are less protections\n# from the user getting errors from the solver API. On the other side, nothing\n# happens silently, which might give the user more control. It requires\n# attaching the solver before the solve step using the `MOIU.attach_optimizer()`\n# function.\n\nmodel_manual = Model(GLPK.Optimizer, caching_mode = MOIU.MANUAL)\n@variable(model_manual, 0 <= x <= 1)\n@variable(model_manual, 0 <= y <= 1)\n@constraint(model_manual, x + y <= 1)\n@objective(model_manual, Max, x + 2y)\nMOIU.attach_optimizer(model_manual)\noptimize!(model_manual)\nobjective_value(model_manual)\n\n# ### `DIRECT` Mode\n\n# Some solvers are able to handle the problem data directly. This is common for\n# LP/MIP solver but not very common for open-source conic solvers. In this case\n# we do not set a optimizer, we set a backend which is more generic and is able\n# to hold data and not only solving a model.\n\nmodel_direct = direct_model(GLPK.Optimizer())\n@variable(model_direct, 0 <= x <= 1)\n@variable(model_direct, 0 <= y <= 1)\n@constraint(model_direct, x + y <= 1)\n@objective(model_direct, Max, x + 2y)\noptimize!(model_direct)\nobjective_value(model_direct)\n\n# ### Solver Options\n\n# Many of the solvers also allow options to be passed in. However, these options\n# are solver-specific. To find out the various options available, please check\n# out the individual solver packages. Some examples for the GLPK solver are\n# given below.\n\nusing GLPK\n\n# To turn off printing (i.e. silence the solver),\n\nmodel = Model(optimizer_with_attributes(GLPK.Optimizer, \"msg_lev\" => 0));\n\n# To increase the maximum number of simplex iterations:\n\nmodel = Model(optimizer_with_attributes(GLPK.Optimizer, \"it_lim\" => 10_000));\n\n# To set the solution timeout limit (in milliseconds):\n\nmodel = Model(optimizer_with_attributes(GLPK.Optimizer, \"tm_lim\" => 5_000));\n\n# ## How to querying the solution\n\n# So far we have seen all the elements and constructs related to writing a JuMP\n# optimization model. In this section we reach the point of what to do with a\n# solved problem. JuMP follows closely the concepts defined in MathOptInterface\n# to answer user questions about a finished call to `optimize!(model)`. The\n# three main steps in querying a solution are given below. We'll use the model\n# we created in `AUTOMATIC` mode with an optimizer attached in this section.\n\n# ### The termination status\n\n# Termination statuses are meant to explain the reason why the optimizer stopped\n# executing in the most recent call to `optimize!`.\n\ntermination_status(model_auto)\n\n# You can view the different termination status codes by referring to the docs\n# or though checking the possible types using the below command.\n\ndisplay(typeof(MOI.OPTIMAL))\n\n# ### The primal and dual status\n\n# These statuses indicate what kind of result is available to be queried from\n# the model. It's possible that no result is available to be queried. We shall\n# discuss more on the dual status and solutions in the Duality tutorial.\n\nprimal_status(model_auto)\n\n#-\n\ndual_status(model_auto)\n\n# As we saw before, the result (solution) status codes can be viewed directly\n# from Julia.\n\ndisplay(typeof(MOI.FEASIBLE_POINT))\n\n# ### Getting the primal solution\n\n# Provided the primal status is not `MOI.NO_SOLUTION`, we can inspect the\n# solution values and optimal cost.\n\nvalue(x)\n\n#-\n\nvalue(y)\n\n#-\n\nobjective_value(model_auto)\n\n# Since it is possible that no solution is available to be queried from the\n# model, calls to [`value`](@ref) may throw errors. Hence, it is recommended to\n# check for the presence of solutions.\n\nmodel_no_solution = Model(GLPK.Optimizer)\n@variable(model_no_solution, 0 <= x <= 1)\n@variable(model_no_solution, 0 <= y <= 1)\n@constraint(model_no_solution, x + y >= 3)\n@objective(model_no_solution, Max, x + 2y)\n\noptimize!(model_no_solution)\n\ntry #hide\nif termination_status(model_no_solution) == MOI.OPTIMAL\n optimal_solution = value(x)\n optimal_objective = objective_value(model_no_solution)\nelseif termination_status(model_no_solution) == MOI.TIME_LIMIT && has_values(model_no_solution)\n suboptimal_solution = value(x)\n suboptimal_objective = objective_value(model_no_solution)\nelse\n error(\"The model was not solved correctly.\")\nend\ncatch err; showerror(stderr, err); end #hide\n", "meta": {"hexsha": "0bec0f5928d0847cdf694a9ae0cdcfa3c870d383", "size": 8887, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/solvers_and_solutions.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/solvers_and_solutions.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/solvers_and_solutions.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.3060344828, "max_line_length": 95, "alphanum_fraction": 0.7168898391, "num_tokens": 2092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186969093556867, "lm_q2_score": 0.1688569500503904, "lm_q1q2_score": 0.07069988310932603}} {"text": "list_test_str = \"light red bags contain 1 bright white bag, 2 muted yellow bags.\ndark orange bags contain 3 bright white bags, 4 muted yellow bags.\nbright white bags contain 1 shiny gold bag.\nmuted yellow bags contain 2 shiny gold bags, 9 faded blue bags.\nshiny gold bags contain 1 dark olive bag, 2 vibrant plum bags.\ndark olive bags contain 3 faded blue bags, 4 dotted black bags.\nvibrant plum bags contain 5 faded blue bags, 6 dotted black bags.\nfaded blue bags contain no other bags.\ndotted black bags contain no other bags.\"\n\nlist_test = split(list_test_str, '\\n')\n\nlist = readlines(\"day7_input.txt\")\n\nbag = \"shiny gold\"\n\n#regxrule = r\"( bags contain | bag\\, | bags\\, | bag\\.| bags\\.)\"\n\nregxrule = r\"( bags contain | bags?, | bags?.)\"\n\nregxrule = r\" bags contain | bags?[,.] ?\"\n\nregxrule = r\" bags contain | bags?(, |\\.)\"\n\nfunction get_outer_bag_rules(list)\n outer = Dict()\n for line in list\n parts = split(line, regxrule, keepempty=false)\n for part in parts[2:end]\n if part ≠ \"no other\"\n num, bag = split(part, ' ', limit=2)\n if bag in keys(outer)\n push!(outer[bag], parts[1])\n else\n push!(outer, bag => Set([parts[1]]))\n end\n end\n end\n end\n return outer\nend\n\nfunction get_outer_bags(bag, outer_bag_rules, outer_set = Set())\n if bag in keys(outer_bag_rules)\n outermost_bags = outer_bag_rules[bag]\n if outermost_bags ∉ outer_set\n union!(outer_set,outermost_bags)\n for outer_bag ∈ outermost_bags\n union!(outer_set, get_outer_bags(outer_bag, outer_bag_rules, outer_set))\n end\n end\n end\n return outer_set\nend\n\nget_number_outer_bags(bag, list) = length(get_outer_bags(bag, get_outer_bag_rules(list)))\n\nprintln(\"Number of outer bags containing `$bag` bag in test list is $(get_number_outer_bags(bag, list_test))\\n\")\nprintln(\"Number of outer bags containing `$bag` bag in problem list is $(get_number_outer_bags(bag, list))\\n\")\n\n#= \n```julia\njulia> @btime get_number_outer_bags(\"shiny gold\", list)\n 5.744 ms (99019 allocations: 3.22 MiB)\n185\n\njulia> @btime get_outer_bag_rules(list);\n 1.970 ms (17606 allocations: 1.25 MiB)\n\njulia> outer_bag_rules = get_outer_bag_rules(list);\n\njulia> @btime length(get_outer_bags(bag, outer_bag_rules));\n 3.742 ms (81414 allocations: 1.97 MiB)\n```\n=#\n\n# Outra versão com mais regex, mas só um pouco mais rápida.\n\n# A versão regex_web foi testada em https://regexr.com/5hutn\nregexrule_web = r\"(.+)(?: bags contain )((\\d+) ([^,\\n]*) (bag,|bags,) )?((\\d+) ([^,\\n]*) (bag,|bags,) )?((\\d+) ([^,\\n]*) (bag,|bags,) )?((\\d+) ([^,\\n]*) (bag,|bags,))?((\\d+|no) ([^,\\n]*) ((bag\\.|bags\\.)))\\n?\"\nregexrule = r\"(.+)(?: bags contain )((\\d+) ([^,]*) (bag,|bags,) )?((\\d+) ([^,]*) (bag,|bags,) )?((\\d+) ([^,]*) (bag,|bags,) )?((\\d+) ([^,]*) (bag,|bags,))?((\\d+|no) ([^,]*) ((bag\\.|bags\\.)))\"\n#regexrule = r\"(.+)(?: bags contain )((\\d+) ([^,]*) (bag,|bags,) )?{4}((\\d+|no) ([^,]*) ((bag\\.|bags\\.)))\"\n\nfunction get_outer_bag_rules2(list)\n outer = Dict()\n for line in list\n m = match(regexrule, line)\n for j in 3:4:length(m.captures)\n if m[j] ∉ (\"\", \"no\") && !(m[j+1] === nothing)\n num = m[j]\n bag = m[j+1]\n if bag in keys(outer)\n push!(outer[bag], m[1])\n else\n push!(outer, bag => Set([m[1]]))\n end\n end\n end\n end\n return outer\nend\n\n\n# part 2\n\nlist_test2_str = \"shiny gold bags contain 2 dark red bags.\ndark red bags contain 2 dark orange bags.\ndark orange bags contain 2 dark yellow bags.\ndark yellow bags contain 2 dark green bags.\ndark green bags contain 2 dark blue bags.\ndark blue bags contain 2 dark violet bags.\ndark violet bags contain no other bags.\"\n\nlist_test2 = split(list_test2_str, '\\n')\n\nfunction get_inner_bag_rules(list)\n inner = Dict()\n for line in list\n parts = split(line, regxrule, keepempty=false)\n for part in parts[2:end]\n if part ≠ \"no other\"\n num, bag = split(part, ' ', limit=2)\n if parts[1] in keys(inner)\n push!(inner[parts[1]], (bag, parse(Int, num)))\n else\n push!(inner, parts[1] => [(bag, parse(Int, num))])\n end\n end\n end\n end\n return inner\nend\n\nfunction get_next_inner_bags(bag, inner_bag_rules)\n if bag in keys(inner_bag_rules)\n innermost_stuff = inner_bag_rules[bag]\n inner_sum = 1 # start with containing bag\n for (innermost_bag, innermost_num) in innermost_stuff\n # recursively count inner bags\n inner_sum += innermost_num * get_next_inner_bags(innermost_bag, inner_bag_rules)\n end\n return inner_sum\n else\n return 1\n end\nend\n\nget_number_inner_bags(bag, list) = get_next_inner_bags(bag, get_inner_bag_rules(list)) - 1 # discount starting bag\n\nprintln(\"Number of bags contained in `$bag` bag in test list is $(get_number_inner_bags(bag, list_test))\\n\")\nprintln(\"Number of bags contained in `$bag` bag in second test list is $(get_number_inner_bags(bag, list_test2))\\n\")\nprintln(\"Number of bags contained in `$bag` bag in problem list is $(get_number_inner_bags(bag, list))\\n\")\n\n#= \n# In this case, most of the time is taken extracting the rules.\n# We don't need to keep growing with the set of color bags, just the number\n```julia\njulia> @btime get_number_inner_bags(\"shiny gold\", list)\n 1.970 ms (17252 allocations: 1.10 MiB)\n89084\n\njulia> inner_bag_rules = get_inner_bag_rules(list);\n\njulia> @btime get_inner_bag_rules(list);\n 1.906 ms (16404 allocations: 1.07 MiB)\n\njulia> @btime get_next_inner_bags(bag, inner_bag_rules) - 1;\n 61.513 μs (848 allocations: 33.66 KiB)\n\n```\n=#\n", "meta": {"hexsha": "8eeb27ce86dbb0afb2b17292b4c51e6fcc2bbffa", "size": 5983, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "aoc2020/day07_bags.jl", "max_stars_repo_name": "rmsrosa/adventofcode2020", "max_stars_repo_head_hexsha": "7a14a4c08eb33c9d02b97b1fbe63a150c81b2ade", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "aoc2020/day07_bags.jl", "max_issues_repo_name": "rmsrosa/adventofcode2020", "max_issues_repo_head_hexsha": "7a14a4c08eb33c9d02b97b1fbe63a150c81b2ade", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aoc2020/day07_bags.jl", "max_forks_repo_name": "rmsrosa/adventofcode2020", "max_forks_repo_head_hexsha": "7a14a4c08eb33c9d02b97b1fbe63a150c81b2ade", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7848837209, "max_line_length": 208, "alphanum_fraction": 0.6052147752, "num_tokens": 1707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.1561049013715009, "lm_q1q2_score": 0.06954934412544315}} {"text": "for p in (\"Knet\",\"AutoGrad\",\"ArgParse\",\"Compat\")\n Pkg.installed(p) == nothing && Pkg.add(p)\nend\n\n\"\"\"\ncharlm.jl: Knet8 version (c) Emre Yolcu, Deniz Yuret, 2016\n\nThis example implements an LSTM network for training and testing\ncharacter-level language models inspired by [\"The Unreasonable\nEffectiveness of Recurrent Neural\nNetworks\"](http://karpathy.github.io/2015/05/21/rnn-effectiveness) from\nthe Andrej Karpathy blog. The model can be trained with different\ngenres of text, and can be used to generate original text in the same\nstyle.\n\nExample usage:\n\n* `julia charlm.jl`: trains a model using its own code.\n\n* `julia charlm.jl --data foo.txt`: uses foo.txt to train instead.\n\n* `julia charlm.jl --data foo.txt bar.txt`: uses foo.txt for training\n and bar.txt for validation. Any number of files can be specified,\n the first two will be used for training and validation, the rest for\n testing.\n\n* `julia charlm.jl --best foo.jld --save bar.jld`: saves the best\n model (according to validation set) to foo.jld, last model to\n bar.jld.\n\n* `julia charlm.jl --load foo.jld --generate 1000`: generates 1000\n characters from the model in foo.jld.\n\n* `julia charlm.jl --help`: describes all available options.\n \n\"\"\"\nmodule CharLM\n\nusing Knet,AutoGrad,ArgParse,Compat\n\nfunction main(args=ARGS)\n s = ArgParseSettings()\n s.description=\"charlm.jl (c) Emre Yolcu, Deniz Yuret, 2016. Character level language model based on http://karpathy.github.io/2015/05/21/rnn-effectiveness.\"\n s.exc_handler=ArgParse.debug_handler\n @add_arg_table s begin\n (\"--datafiles\"; nargs='+'; help=\"If provided, use first file for training, second for dev, others for test.\")\n (\"--loadfile\"; help=\"Initialize model from file\")\n (\"--savefile\"; help=\"Save final model to file\")\n (\"--bestfile\"; help=\"Save best model to file\")\n (\"--generate\"; arg_type=Int; default=0; help=\"If non-zero generate given number of characters.\")\n (\"--hidden\"; nargs='+'; arg_type=Int; default=[256]; help=\"Sizes of one or more LSTM layers.\")\n (\"--embed\"; arg_type=Int; default=256; help=\"Size of the embedding vector.\")\n (\"--epochs\"; arg_type=Int; default=3; help=\"Number of epochs for training.\")\n (\"--batchsize\"; arg_type=Int; default=128; help=\"Number of sequences to train on in parallel.\")\n (\"--seqlength\"; arg_type=Int; default=100; help=\"Number of steps to unroll the network for.\")\n (\"--decay\"; arg_type=Float64; default=0.9; help=\"Learning rate decay.\")\n (\"--lr\"; arg_type=Float64; default=4.0; help=\"Initial learning rate.\")\n (\"--gclip\"; arg_type=Float64; default=3.0; help=\"Value to clip the gradient norm at.\")\n (\"--winit\"; arg_type=Float64; default=0.3; help=\"Initial weights set to winit*randn().\")\n (\"--gcheck\"; arg_type=Int; default=0; help=\"Check N random gradients.\")\n (\"--seed\"; arg_type=Int; default=-1; help=\"Random number seed.\")\n (\"--atype\"; default=(gpu()>=0 ? \"KnetArray{Float32}\" : \"Array{Float32}\"); help=\"array type: Array for cpu, KnetArray for gpu\")\n (\"--fast\"; action=:store_true; help=\"skip loss printing for faster run\")\n #TODO (\"--dropout\"; arg_type=Float64; default=0.0; help=\"Dropout probability.\")\n end\n println(s.description)\n isa(args, AbstractString) && (args=split(args))\n o = parse_args(args, s; as_symbols=true)\n println(\"opts=\",[(k,v) for (k,v) in o]...)\n o[:seed] > 0 && srand(o[:seed])\n o[:atype] = eval(parse(o[:atype]))\n if any(f->(o[f]!=nothing), (:loadfile, :savefile, :bestfile))\n Pkg.installed(\"JLD\")==nothing && Pkg.add(\"JLD\") # error(\"Please Pkg.add(\\\"JLD\\\") to load or save files.\")\n eval(Expr(:using,:JLD))\n end\n\n # we initialize a model from loadfile, train using datafiles (both optional).\n # if the user specifies neither, train a model using the charlm.jl source code.\n isempty(o[:datafiles]) && o[:loadfile]==nothing && push!(o[:datafiles],@__FILE__) # shakespeare()\n\n # read text and report lengths\n text = map((@compat readstring), o[:datafiles])\n !isempty(text) && info(\"Chars read: $(map((f,c)->(basename(f),length(c)),o[:datafiles],text))\")\n\n # vocab (char_to_index) comes from the initial model if there is one, otherwise from the datafiles.\n # if there is an initial model make sure the data has no new vocab\n if o[:loadfile]==nothing\n vocab = Dict{Char,Int}()\n for t in text, c in t; get!(vocab, c, 1+length(vocab)); end\n model = initweights(o[:atype], o[:hidden], length(vocab), o[:embed], o[:winit])\n else\n info(\"Loading model from $(o[:loadfile])\")\n vocab = load(o[:loadfile], \"vocab\") \n for t in text, c in t; haskey(vocab, c) || error(\"Unknown char $c\"); end\n model = map(p->convert(o[:atype],p), load(o[:loadfile], \"model\"))\n end\n info(\"$(length(vocab)) unique chars.\")\n if !isempty(text)\n train!(model, text, vocab, o)\n end\n if o[:savefile] != nothing\n info(\"Saving last model to $(o[:savefile])\")\n save(o[:savefile], \"model\", model, \"vocab\", vocab)\n end\n if o[:generate] > 0\n state = initstate(o[:atype],o[:hidden],1)\n generate(model, state, vocab, o[:generate])\n end\nend\n\n\nfunction train!(model, text, vocab, o)\n s0 = initstate(o[:atype], o[:hidden], o[:batchsize])\n data = map(t->minibatch(t, vocab, o[:batchsize]), text)\n lr = o[:lr]\n if o[:fast]\n @time (for epoch=1:o[:epochs]\n train1(model, copy(s0), data[1]; slen=o[:seqlength], lr=lr, gclip=o[:gclip])\n end; gpu()>=0 && Knet.cudaDeviceSynchronize())\n return\n end\n losses = map(d->loss(model,copy(s0),d), data)\n println((:epoch,0,:loss,losses...))\n devset = ifelse(length(data) > 1, 2, 1)\n devlast = devbest = losses[devset]\n for epoch=1:o[:epochs]\n @time train1(model, copy(s0), data[1]; slen=o[:seqlength], lr=lr, gclip=o[:gclip])\n @time losses = map(d->loss(model,copy(s0),d), data)\n println((:epoch,epoch,:loss,losses...))\n if o[:gcheck] > 0\n gradcheck(loss, model, copy(s0), data[1], 1:o[:seqlength]; gcheck=o[:gcheck])\n end\n devloss = losses[devset]\n if devloss < devbest\n devbest = devloss\n if o[:bestfile] != nothing\n info(\"Saving best model to $(o[:bestfile])\")\n save(o[:bestfile], \"model\", model, \"vocab\", vocab)\n end\n end\n if devloss > devlast\n lr *= o[:decay]\n info(\"New learning rate: $lr\")\n end\n devlast = devloss\n end\nend \n\n\n# sequence[t]: input token at time t\n# state is modified in place\nfunction train1(param, state, sequence; slen=100, lr=1.0, gclip=0.0)\n for t = 1:slen:length(sequence)-slen\n range = t:t+slen-1\n gloss = lossgradient(param, state, sequence, range)\n gscale = lr\n if gclip > 0\n gnorm = sqrt(mapreduce(sumabs2, +, 0, gloss))\n if gnorm > gclip\n gscale *= gclip / gnorm\n end\n end\n for k in 1:length(param)\n # param[k] -= gscale * gloss[k]\n axpy!(-gscale, gloss[k], param[k])\n end\n isa(state,Vector{Any}) || error(\"State should not be Boxed.\")\n # The following is needed in case AutoGrad boxes state values during gradient calculation\n for i = 1:length(state)\n state[i] = AutoGrad.getval(state[i])\n end\n end\nend\n\n# param[2k-1,2k]: weight and bias for the k'th lstm layer\n# param[end-2]: embedding matrix\n# param[end-1,end]: weight and bias for final prediction\nfunction initweights(atype, hidden, vocab, embed, winit)\n param = Array(Any, 2*length(hidden)+3)\n input = embed\n for k = 1:length(hidden)\n param[2k-1] = winit*randn(input+hidden[k], 4*hidden[k])\n param[2k] = zeros(1, 4*hidden[k])\n param[2k][1:hidden[k]] = 1 # forget gate bias\n input = hidden[k]\n end\n param[end-2] = winit*randn(vocab,embed)\n param[end-1] = winit*randn(hidden[end],vocab)\n param[end] = zeros(1,vocab)\n return map(p->convert(atype,p), param)\nend\n\n# state[2k-1,2k]: hidden and cell for the k'th lstm layer\nfunction initstate(atype, hidden, batchsize)\n state = Array(Any, 2*length(hidden))\n for k = 1:length(hidden)\n state[2k-1] = zeros(batchsize,hidden[k])\n state[2k] = zeros(batchsize,hidden[k])\n end\n return map(s->convert(atype,s), state)\nend\n\nfunction lstm(weight,bias,hidden,cell,input)\n gates = hcat(input,hidden) * weight .+ bias\n hsize = size(hidden,2)\n forget = sigm(gates[:,1:hsize])\n ingate = sigm(gates[:,1+hsize:2hsize])\n outgate = sigm(gates[:,1+2hsize:3hsize])\n change = tanh(gates[:,1+3hsize:end])\n cell = cell .* forget + ingate .* change\n hidden = outgate .* tanh(cell)\n return (hidden,cell)\nend\n\n# s[2k-1,2k]: hidden and cell for the k'th lstm layer\n# w[2k-1,2k]: weight and bias for k'th lstm layer\n# w[end-2]: embedding matrix\n# w[end-1,end]: weight and bias for final prediction\n# state is modified in place\nfunction predict(w, s, x)\n x = x * w[end-2]\n for i = 1:2:length(s)\n (s[i],s[i+1]) = lstm(w[i],w[i+1],s[i],s[i+1],x)\n x = s[i]\n end\n return x * w[end-1] .+ w[end]\nend\n\n# sequence[t]: input token at time t\n# state is modified in place\nfunction loss(param,state,sequence,range=1:length(sequence)-1)\n total = 0.0; count = 0\n atype = typeof(AutoGrad.getval(param[1]))\n input = convert(atype,sequence[first(range)])\n for t in range\n ypred = predict(param,state,input)\n ynorm = logp(ypred,2) # ypred .- log(sum(exp(ypred),2))\n ygold = convert(atype,sequence[t+1])\n total += sum(ygold .* ynorm)\n count += size(ygold,1)\n input = ygold\n end\n return -total / count\nend\n\nlossgradient = grad(loss)\n\nfunction generate(param, state, vocab, nchar)\n index_to_char = Array(Char, length(vocab))\n for (k,v) in vocab; index_to_char[v] = k; end\n input = oftype(param[1], zeros(1,length(vocab)))\n index = 1\n for t in 1:nchar\n ypred = predict(param,state,input)\n input[index] = 0\n index = sample(exp(logp(ypred)))\n print(index_to_char[index])\n input[index] = 1\n end\n println()\nend\n\nfunction sample(p)\n p = convert(Array,p)\n r = rand()\n for c = 1:length(p)\n r -= p[c]\n r < 0 && return c\n end\nend\n\nfunction shakespeare()\n file = Knet.dir(\"data\",\"100.txt\")\n if !isfile(file)\n info(\"Downloading 'The Complete Works of William Shakespeare'\")\n url = \"http://www.gutenberg.org/files/100/100.txt\"\n download(url,file)\n end\n return file\nend\n\nfunction minibatch(chars, char_to_index, batch_size)\n nbatch = div(length(chars), batch_size)\n vocab_size = length(char_to_index)\n data = [ falses(batch_size, vocab_size) for i=1:nbatch ] # using BitArrays\n cidx = 0\n for c in chars # safest way to iterate over utf-8 text\n idata = 1 + cidx % nbatch\n row = 1 + div(cidx, nbatch)\n row > batch_size && break\n col = char_to_index[c]\n data[idata][row,col] = 1\n cidx += 1\n end\n return data\nend\n\n# To be able to load/save KnetArrays:\nif Pkg.installed(\"JLD\") != nothing\n import JLD: writeas, readas\n type KnetJLD; a::Array; end\n writeas(c::KnetArray) = KnetJLD(Array(c))\n readas(d::KnetJLD) = KnetArray(d.a)\nend\n\n# This allows both non-interactive (shell command) and interactive calls like:\n# $ julia charlm.jl --epochs 10\n# julia> CharLM.main(\"--epochs 10\")\n!isinteractive() && !isdefined(Core.Main,:load_only) && main(ARGS)\n\nend # module\n\n# Note: 10.txt used in the sample runs below was generated using\n# head -10000 100.txt > 10.txt\n# where 100.txt is the file downloaded by shakespeare().\n\n\n\n### SAMPLE RUN 74a2e6c+ Mon Sep 19 14:03:10 EEST 2016\n### Implemented multi-layer. Removed the keepstate option fixing it to true.\n### Note that winit default changed so I specify it below for comparison.\n### The slight difference is due to keepstate.\n\n# julia> CharLM.main(\"--data 10.txt --winit 0.3 --fast\")\n# charlm.jl (c) Emre Yolcu, Deniz Yuret, 2016. Character level language model based on http://karpathy.github.io/2015/05/21/rnn-effectiveness.\n# opts=(:lr,4.0)(:atype,\"KnetArray{Float32}\")(:winit,0.3)(:savefile,nothing)(:loadfile,nothing)(:generate,0)(:bestfile,nothing)(:gclip,3.0)(:hidden,[256])(:epochs,3)(:decay,0.9)(:gcheck,0)(:seqlength,100)(:seed,42)(:embed,256)(:batchsize,128)(:datafiles,Any[\"10.txt\"])(:fast,true)\n# INFO: Chars read: [(\"10.txt\",425808)]\n# INFO: 87 unique chars.\n# 1.406687 seconds (1.74 M allocations: 196.799 MB, 2.49% gc time)\n# (:epoch,0,:loss,6.1075509900258)\n# 4.002638 seconds (6.12 M allocations: 374.188 MB, 2.41% gc time)\n# 3.990772 seconds (6.11 M allocations: 374.129 MB, 2.44% gc time)\n# 4.006249 seconds (6.12 M allocations: 374.240 MB, 2.53% gc time)\n# 1.405878 seconds (1.75 M allocations: 197.059 MB, 2.56% gc time)\n# (:epoch,3,:loss,1.8713183968407767)\n\n\n\n### SAMPLE RUN 4ce58d1+ Fri Sep 16 12:24:00 EEST 2016\n### Transposed everything so getindex does not need to copy\n\n# charlm.jl (c) Emre Yolcu, Deniz Yuret, 2016. Character level language model based on http://karpathy.github.io/2015/05/21/rnn-effectiveness.\n# opts=(:keepstate,false)(:lr,4.0)(:atype,\"KnetArray{Float32}\")(:winit,0.3)(:savefile,nothing)(:loadfile,nothing)(:generate,0)(:bestfile,nothing)(:gclip,3.0)(:embedding,256)(:hidden,256)(:epochs,3)(:decay,0.9)(:gcheck,0)(:seqlength,100)(:seed,42)(:batchsize,128)(:datafiles,Any[\"data/10.txt\"])(:fast,true)\n# INFO: Chars read: [(\"10.txt\",425808)]\n# INFO: 87 unique chars.\n# 1.388652 seconds (1.73 M allocations: 196.686 MB, 2.04% gc time)\n# (:epoch,0,:loss,6.1075509900258)\n# 3.940298 seconds (6.06 M allocations: 373.166 MB, 2.06% gc time)\n# 3.935995 seconds (6.06 M allocations: 373.244 MB, 2.07% gc time)\n# 3.934983 seconds (6.06 M allocations: 373.245 MB, 2.08% gc time)\n# 1.390374 seconds (1.73 M allocations: 196.820 MB, 2.11% gc time)\n# (:epoch,3,:loss,1.860654126576015)\n\n\n\n### SAMPLE RUN 31136d5+ Wed Sep 14 17:51:44 EEST 2016: using vcat(x,h) and vcat(w...)\n### optimized learning parameters: winit=0.3, lr=4.0, gclip=3.0\n\n# charlm.jl (c) Emre Yolcu, Deniz Yuret, 2016. Character level language model based on http://karpathy.github.io/2015/05/21/rnn-effectiveness.\n# opts=(:keepstate,false)(:lr,4.0)(:atype,\"KnetArray{Float32}\")(:winit,0.3)(:savefile,nothing)(:loadfile,nothing)(:generate,0)(:bestfile,nothing)(:gclip,3.0)(:embedding,256)(:hidden,256)(:epochs,3)(:decay,0.9)(:gcheck,0)(:seqlength,100)(:seed,42)(:batchsize,128)(:datafiles,Any[\"10.txt\"])(:fast,true)\n# INFO: Chars read: [(\"10.txt\",425808)]\n# INFO: 87 unique chars.\n# 1.596959 seconds (1.79 M allocations: 197.432 MB, 2.56% gc time)\n# (:epoch,0,:loss,5.541976199042528)\n# 4.421566 seconds (6.23 M allocations: 375.843 MB, 2.54% gc time)\n# 4.418540 seconds (6.25 M allocations: 376.058 MB, 2.51% gc time)\n# 4.402317 seconds (6.26 M allocations: 376.297 MB, 2.66% gc time)\n# 1.594677 seconds (1.81 M allocations: 197.737 MB, 2.64% gc time)\n# (:epoch,3,:loss,1.8484550957572192)\n\n\n### SAMPLE RUN 80503e7+ Wed Sep 14 17:35:36 EEST 2016: using vcat(x,h)\n#\n# charlm.jl (c) Emre Yolcu, Deniz Yuret, 2016. Character level language model based on http://karpathy.github.io/2015/05/21/rnn-effectiveness.\n# opts=(:keepstate,false)(:lr,1.0)(:atype,\"KnetArray{Float32}\")(:savefile,nothing)(:loadfile,nothing)(:generate,0)(:bestfile,nothing)(:embedding,256)(:gclip,5.0)(:hidden,256)(:epochs,3)(:decay,0.9)(:gcheck,0)(:seqlength,100)(:seed,42)(:batchsize,128)(:datafiles,Any[\"10.txt\"])(:fast,true)\n# INFO: Chars read: [(\"10.txt\",425808)]\n# INFO: 87 unique chars.\n# 1.930180 seconds (1.95 M allocations: 213.741 MB, 1.82% gc time)\n# (:epoch,0,:loss,4.462641664662756)\n# 4.968101 seconds (7.47 M allocations: 454.259 MB, 2.24% gc time)\n# 4.963733 seconds (7.47 M allocations: 454.363 MB, 2.26% gc time)\n# 4.967413 seconds (7.45 M allocations: 454.024 MB, 2.14% gc time)\n# 1.945658 seconds (1.98 M allocations: 214.183 MB, 2.02% gc time)\n# (:epoch,3,:loss,3.2389672966290237)\n\n\n### SAMPLE RUN 65f57ff+ Wed Sep 14 10:02:30 EEST 2016: separate x, h, w, b\n#\n# charlm.jl (c) Emre Yolcu, Deniz Yuret, 2016. Character level language model based on http://karpathy.github.io/2015/05/21/rnn-effectiveness.\n# opts=(:keepstate,false)(:lr,1.0)(:atype,\"KnetArray{Float32}\")(:savefile,nothing)(:loadfile,nothing)(:generate,0)(:bestfile,nothing)(:embedding,256)(:gclip,5.0)(:hidden,256)(:epochs,3)(:decay,0.9)(:gcheck,0)(:seqlength,100)(:seed,42)(:batchsize,128)(:datafiles,Any[\"10.txt\"])(:fast,true)\n# INFO: Chars read: [(\"10.txt\",425808)]\n# INFO: 87 unique chars.\n# 2.156358 seconds (2.31 M allocations: 237.913 MB, 2.30% gc time)\n# (:epoch,0,:loss,4.465127425659868)\n# 6.287736 seconds (9.54 M allocations: 574.703 MB, 2.84% gc time)\n# 6.272144 seconds (9.54 M allocations: 574.633 MB, 2.80% gc time)\n# 6.277462 seconds (9.54 M allocations: 574.637 MB, 2.86% gc time)\n# 2.165516 seconds (2.34 M allocations: 238.323 MB, 2.56% gc time)\n# (:epoch,3,:loss,3.226540256084356)\n\n\n### SAMPLE OUTPUT (with head -10000 100.txt): first version\n# julia> CharLM.main(\"--gpu --data 10.txt\")\n# opts=(:lr,1.0)(:savefile,nothing)(:loadfile,nothing)(:dropout,0.0)(:generate,0)(:bestfile,nothing)(:embedding,256)(:gclip,5.0)(:hidden,256)(:epochs,10)(:nlayer,1)(:decay,0.9)(:gpu,true)(:seqlength,100)(:seed,42)(:batchsize,128)(:datafiles,Any[\"10.txt\"])\n# INFO: Chars read: [(\"10.txt\",425808)]\n# INFO: 87 unique chars.\n# (0,4.465127425659868)\n# 2.182693 seconds (2.36 M allocations: 240.394 MB, 1.74% gc time)\n# 7.861079 seconds (10.12 M allocations: 601.311 MB, 1.84% gc time)\n# (1,3.3244698245543285)\n# 2.159062 seconds (2.35 M allocations: 239.217 MB, 1.80% gc time)\n# 6.200085 seconds (9.55 M allocations: 575.573 MB, 2.28% gc time)\n# (2,3.24593908969621)\n# 2.352389 seconds (2.34 M allocations: 239.381 MB, 1.51% gc time)\n# 6.211946 seconds (9.55 M allocations: 575.568 MB, 2.21% gc time)\n# (3,3.226540256084356)\n\n", "meta": {"hexsha": "27c71fa1752b535324012bb0bf877522f1b15adf", "size": 18100, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/charlm.jl", "max_stars_repo_name": "enzotarta/Knet.jl", "max_stars_repo_head_hexsha": "4330f3fec812ccbbfeabbcf6aa63450ca743f9c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/charlm.jl", "max_issues_repo_name": "enzotarta/Knet.jl", "max_issues_repo_head_hexsha": "4330f3fec812ccbbfeabbcf6aa63450ca743f9c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/charlm.jl", "max_forks_repo_name": "enzotarta/Knet.jl", "max_forks_repo_head_hexsha": "4330f3fec812ccbbfeabbcf6aa63450ca743f9c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.3014354067, "max_line_length": 305, "alphanum_fraction": 0.6443093923, "num_tokens": 5976, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.13660839354130014, "lm_q1q2_score": 0.06830419677065007}} {"text": "module JuliennedArrays\n\nimport Base: axes, getindex, setindex!, size\nusing Base: promote_op, @pure, @propagate_inbounds, tail\n\nmap_unrolled(call, variables::Tuple{}) = ()\nmap_unrolled(call, variables) =\n call(first(variables)), map_unrolled(call, tail(variables))...\n\nmap_unrolled(call, variables1::Tuple{}, variables2::Tuple{}) = ()\nmap_unrolled(call, variables1, variables2) =\n call(first(variables1), first(variables2)),\n map_unrolled(call, tail(variables1), tail(variables2))...\n\nis_in(needle::Needle, straw1::Needle, straws...) where {Needle} = True()\nis_in(needle, straw1, straws...) = is_in(needle, straws...)\nis_in(needle) = False()\n\nin_unrolled(straws, needle1, needles...) =\n is_in(needle1, straws...),\n in_unrolled(straws, needles...)...\nin_unrolled(straws) = ()\n\n@pure as_vals(them::Int...) = map(Val, them)\n\nabstract type TypedBool end\n\"\"\"\n struct True\n\nTyped `true`\n\"\"\"\nstruct True <: TypedBool end\n\"\"\"\n struct False\n\nTyped `false`\n\"\"\"\nstruct False <: TypedBool end\n\n@inline untyped(::True) = true\n@inline untyped(::False) = false\n\nnot(::False) = True()\nnot(::True) = False()\n\nexport True\nexport False\n\ngetindex_unrolled(into::Tuple{}, switches::Tuple{}) = ()\nfunction getindex_unrolled(into, switches)\n next = getindex_unrolled(tail(into), tail(switches))\n if untyped(first(switches))\n (first(into), next...)\n else\n next\n end\nend\n\nsetindex_unrolled(old::Tuple{}, something, ::Tuple{}) = ()\nsetindex_unrolled(old, new, switches) =\n if untyped(first(switches))\n first(new),\n setindex_unrolled(tail(old), tail(new), tail(switches))...\n else\n first(old),\n setindex_unrolled(tail(old), new, tail(switches))...\n end\n\nstruct Slices{Item, Dimensions, Whole, Alongs} <: AbstractArray{Item, Dimensions}\n whole::Whole\n alongs::Alongs\nend\nSlices{Item, Dimensions}(whole::Whole, alongs::Alongs) where {Item, Dimensions, Whole, Alongs} =\n Slices{Item, Dimensions, Whole, Alongs}(whole, alongs)\n\naxes(slices::Slices) =\n getindex_unrolled(axes(slices.whole), map_unrolled(not, slices.alongs))\nsize(slices::Slices) = map_unrolled(length, axes(slices))\n\nslice_index(slices, indices) = setindex_unrolled(\n axes(slices.whole),\n indices,\n map_unrolled(not, slices.alongs)\n)\n@propagate_inbounds getindex(slices::Slices, indices::Int...) =\n view(slices.whole, slice_index(slices, indices)...)\n@propagate_inbounds setindex!(slices::Slices, value, indices::Int...) =\n slices.whole[slice_index(slices, indices)...] = value\n\naxis_or_1(switch, axis) =\n if untyped(switch)\n axis\n else\n 1\n end\n\"\"\"\n Slices(whole, alongs::TypedBool...)\n\nSlice `whole` into `view`s.\n\n`alongs`, made of [`True`](@ref) and [`False`](@ref) objects, shows which dimensions will be replaced with `:` when slicing.\n\n```jldoctest\njulia> using JuliennedArrays\n\njulia> whole = [1 2; 3 4];\n\njulia> slices = Slices(whole, False(), True())\n2-element Slices{SubArray{Int64,1,Array{Int64,2},Tuple{Int64,Base.OneTo{Int64}},true},1,Array{Int64,2},Tuple{False,True}}:\n [1, 2]\n [3, 4]\n\njulia> slices[1] == whole[1, :]\ntrue\n\njulia> slices[1] = [2, 1];\n\njulia> whole\n2×2 Array{Int64,2}:\n 2 1\n 3 4\n\njulia> larger = rand(5, 5, 5);\n\njulia> larger_slices = Slices(larger, True(), False(), False());\n\njulia> size(first(larger_slices))\n(5,)\n```\n\"\"\"\nSlices(whole::AbstractArray, alongs::TypedBool...) =\n Slices{\n typeof(@inbounds view(\n whole,\n map_unrolled(axis_or_1, alongs, axes(whole))...\n )),\n length(getindex_unrolled(alongs, map_unrolled(not, alongs)))\n }(whole, alongs)\n\n\"\"\"\n Slices(whole, alongs::Int...)\n\nAlternative syntax: `alongs` is which dimensions will be replaced with `:` when slicing.\n\n```jldoctest\njulia> using JuliennedArrays\n\njulia> input = reshape(1:8, 2, 2, 2)\n2×2×2 reshape(::UnitRange{Int64}, 2, 2, 2) with eltype Int64:\n[:, :, 1] =\n 1 3\n 2 4\n\n[:, :, 2] =\n 5 7\n 6 8\n\njulia> Slices(input, 1, 3)\n2-element Slices{SubArray{Int64,2,Base.ReshapedArray{Int64,3,UnitRange{Int64},Tuple{}},Tuple{Base.OneTo{Int64},Int64,Base.OneTo{Int64}},false},1,Base.ReshapedArray{Int64,3,UnitRange{Int64},Tuple{}},Tuple{True,False,True}}:\n [1 5; 2 6]\n [3 7; 4 8]\n```\n\"\"\"\nSlices(whole::AbstractArray{Item, NumberOfDimensions}, alongs::Int...) where {Item, NumberOfDimensions} =\n Slices(whole, in_unrolled(\n as_vals(alongs...),\n ntuple(Val, NumberOfDimensions)...\n )...)\nexport Slices\n\nstruct Align{Item, Dimensions, Sliced, Alongs} <: AbstractArray{Item, Dimensions}\n slices::Sliced\n alongs::Alongs\nend\nAlign{Item, Dimensions}(slices::Sliced, alongs::Alongs) where {Item, Dimensions, Sliced, Alongs} =\n Align{Item, Dimensions, Sliced, Alongs}(slices, alongs)\n\naxes(aligned::Align) = setindex_unrolled(\n setindex_unrolled(\n aligned.alongs,\n axes(aligned.slices),\n map_unrolled(not, aligned.alongs)\n ),\n axes(first(aligned.slices)),\n aligned.alongs\n)\nsize(aligned::Align) = map_unrolled(length, axes(aligned))\n\nsplit_indices(aligned, indices) =\n getindex_unrolled(indices, map_unrolled(not, aligned.alongs)),\n getindex_unrolled(indices, aligned.alongs)\n@propagate_inbounds function getindex(aligned::Align, indices::Int...)\n outer, inner = split_indices(aligned, indices)\n aligned.slices[outer...][inner...]\nend\n@propagate_inbounds function setindex!(aligned::Align, value, indices::Int...)\n outer, inner = split_indices(aligned, indices)\n aligned.slices[outer...][inner...] = value\nend\n\n\"\"\"\n Align(slices, alongs::TypedBool...)\n\n`Align` an array of arrays, all with the same size.\n\n`alongs`, made of [`True`](@ref) and [`False`](@ref) objects, shows which dimensions will be taken up by the inner arrays. Inverse of [`Slices`](@ref).\n\n```jldoctest\njulia> using JuliennedArrays\n\njulia> slices = [[1, 2], [3, 4]];\n\njulia> aligned = Align(slices, False(), True())\n2×2 Align{Int64,2,Array{Array{Int64,1},1},Tuple{False,True}}:\n 1 2\n 3 4\n\njulia> aligned[1, :] == slices[1]\ntrue\n\njulia> aligned[1, 1] = 0;\n\njulia> slices\n2-element Array{Array{Int64,1},1}:\n [0, 2]\n [3, 4]\n```\n\"\"\"\nAlign(slices::AbstractArray{<:AbstractArray{Item, InnerDimensions}, OuterDimensions}, alongs::TypedBool...) where {Item, InnerDimensions, OuterDimensions} =\n Align{Item, OuterDimensions + InnerDimensions}(slices, alongs)\nexport Align\n\n\"\"\"\n Along(slices, alongs::Int...)\n\nAlternative syntax: `alongs` is which dimensions will be taken up by the inner arrays.\n\n```jldoctest\njulia> using JuliennedArrays\n\njulia> input = reshape(1:8, 2, 2, 2)\n2×2×2 reshape(::UnitRange{Int64}, 2, 2, 2) with eltype Int64:\n[:, :, 1] =\n 1 3\n 2 4\n\n[:, :, 2] =\n 5 7\n 6 8\n\njulia> slices = collect(Slices(input, 1, 3))\n2-element Array{SubArray{Int64,2,Base.ReshapedArray{Int64,3,UnitRange{Int64},Tuple{}},Tuple{Base.OneTo{Int64},Int64,Base.OneTo{Int64}},false},1}:\n [1 5; 2 6]\n [3 7; 4 8]\n\njulia> Align(slices, 1, 3)\n2×2×2 Align{Int64,3,Array{SubArray{Int64,2,Base.ReshapedArray{Int64,3,UnitRange{Int64},Tuple{}},Tuple{Base.OneTo{Int64},Int64,Base.OneTo{Int64}},false},1},Tuple{True,False,True}}:\n[:, :, 1] =\n 1 3\n 2 4\n\n[:, :, 2] =\n 5 7\n 6 8\n```\n\"\"\"\nAlign(slices::AbstractArray{<:AbstractArray{Item, InnerDimensions}, OuterDimensions}, alongs::Int...) where {Item, InnerDimensions, OuterDimensions} =\n Align(slices, in_unrolled(\n as_vals(alongs...),\n ntuple(Val, InnerDimensions + OuterDimensions)...\n )...)\n\nend\n", "meta": {"hexsha": "3b5b7981449f889d47f078a2e26ffe119e6f3b6b", "size": 7415, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/JuliennedArrays.jl", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/JuliennedArrays.jl-5cadff95-7770-533d-a838-a1bf817ee6e0", "max_stars_repo_head_hexsha": "8dc49be38ce5d85c0adb92e31917ccd6c5ac3827", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/JuliennedArrays.jl", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/JuliennedArrays.jl-5cadff95-7770-533d-a838-a1bf817ee6e0", "max_issues_repo_head_hexsha": "8dc49be38ce5d85c0adb92e31917ccd6c5ac3827", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/JuliennedArrays.jl", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/JuliennedArrays.jl-5cadff95-7770-533d-a838-a1bf817ee6e0", "max_forks_repo_head_hexsha": "8dc49be38ce5d85c0adb92e31917ccd6c5ac3827", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0620437956, "max_line_length": 222, "alphanum_fraction": 0.6737693864, "num_tokens": 2349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.14033624949008322, "lm_q1q2_score": 0.06742857563719645}} {"text": "## Exercise 7-1\n## Rewrite the function printn from Recursion using iteration instead of recursion.\nprintln(\"Ans: \")\n\nfunction printn(s, n::Int)\n while n > 0\n println(s)\n n -= 1\n end\nend \n\nprintn(\"Hello iteration!\", 4)\n\nprintln(\"End.\")\n", "meta": {"hexsha": "d04f5565fff29320737666650a2e1e5f6dcb2ace", "size": 256, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Chapter7/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": "Chapter7/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": "Chapter7/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.0666666667, "max_line_length": 83, "alphanum_fraction": 0.6328125, "num_tokens": 71, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.22270013882530884, "lm_q2_score": 0.30074559147596, "lm_q1q2_score": 0.0669760849727959}} {"text": "### A Pluto.jl notebook ###\n# v0.19.8\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n quote\n local iv = try Base.loaded_modules[Base.PkgId(Base.UUID(\"6e696c72-6542-2067-7265-42206c756150\"), \"AbstractPlutoDingetjes\")].Bonds.initial_value catch; b -> missing; end\n local el = $(esc(element))\n global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el)\n el\n end\nend\n\n# ╔═╡ 4712d6fd-efb3-4f46-9160-c82797a3b5e4\n# ╠═╡ show_logs = false\nbegin\n\tusing Logging\n\tglobal_logger(NullLogger())\n\tdisplay(\"\")\nend\n\n# ╔═╡ f0545c67-5cfd-438f-a9ef-92c35ebaefa4\n# ╠═╡ show_logs = false\n#Set-up packages\nbegin\n\t\n\tusing DataFrames, HTTP, CSV, Dates, Plots, PlutoUI, Printf, LaTeXStrings, HypertextLiteral, ShortCodes\n\t\n\tgr();\n\tPlots.GRBackend()\n\n\n\t#Define html elements\n\tnbsp = html\" \" #non-breaking space\n\tvspace = html\"\"\"
\"\"\"\n\tbr = html\"
\"\n\n\t#Sets the width of cells, caps the cell width by 90% of screen width\n\t#(setting overwritten by cell below)\n\t# @bind screenWidth @htl(\"\"\"\n\t# \t
\n\t# \t\n\t# \t
\n\t# \"\"\")\n\n\t\n\t# cellWidth= min(1000, screenWidth*0.9)\n\t# @htl(\"\"\"\n\t# \t\n\t# \"\"\")\n\t\n\n\t#Sets the width of the cells\n\t#begin\n\t#\thtml\"\"\"\n\"\"\"\n\n# ╔═╡ 81290d1c-8ce2-11eb-3340-337957fd81b7\nhtml\"\"\"\n
\n\"\"\"\n\n# ╔═╡ 8ff1bb20-8ce2-11eb-1de6-fd84daec8930\nmd\"\"\"\n#### Create table and insert rows\n\n\"\"\"\n\n# ╔═╡ d3ee2138-8ce2-11eb-0b29-659a3be01512\nmd\"\"\"\nWe will represent our table in memory by a dictionary (not really space efficient). \n\nAlso, we will:\n - Support the primary key for our table (some table do not and will not have a primary key).\n - Allow for NULL value for any column of our table (but for the primary key).\n\"\"\"\n\n# ╔═╡ 6d759180-928b-11eb-1cc1-0593c7f3b0c2\nbegin\n\tconst Row = Dict{Symbol, Any}\n\tconst GRow = Union{Row, Vector{Pair{Symbol, Any}}, Vector{Any}} ## Generic Row\n\tconst WhereClause = Function\n\tconst HavingClause = Function\n\tconst S_N = Union{Symbol, Nothing}\n\t# const PK = Pair{S_N, DataType}\n\tconst D_SF = Dict{Symbol, Function}\n\tconst U_IN = Union{Int, Nothing}\n\tconst U_SN = Union{String, Nothing}\n\tconst UDT = Union{Union, DataType, Type};\nend\n\n# ╔═╡ 2e8684fc-2ba6-48ec-81b3-f1c31cdde43a\nmd\"\"\"\nLet us define our custom type for a relational table:\n\"\"\"\n\n# ╔═╡ 53accaea-92d4-11eb-0bc2-3d2ee10f9bfb\nmutable struct Table\n\tcolumns::Vector{Symbol}\n\ttypes::Vector{UDT}\n\tpkey::Union{Symbol, Nothing}\n\trows::Vector{Row}\n\t\n function Table(col_types::Vector{Pair{Symbol, DT}};\n pkey::Pair=(:id => Int)) where DT <: UDT\n # vector of pairs keeps implicit order\n @assert length(col_types) ≥ 1\n #\n cols = map(((k, _)=p) -> k, col_types)\n types = map(((_, v)=p) -> v, col_types)\n cols, types = check_pk(cols, types, pkey)\n new(cols, types, pkey.first, Vector{Row}[])\n end\n\n function Table(cols::Vector{Symbol}, types::Vector{DT};\n pkey::Pair=(:id => Int)) where DT <: UDT\n cols, types = check_pk(cols, types, pkey)\n new(cols, types, pkey.first, Vector{Row}[])\n end\nend\n\n# ╔═╡ 1b1b8d8c-3803-43fa-b3af-7a58d75bb13b\nmd\"\"\"\nAnd let us start developing our API and utilities:\n\"\"\"\n\n# ╔═╡ 6f9c58d4-92d1-11eb-2c09-cb1ea5afcd6d\nbegin\n\timport Base: length\n\t##\n\t## API for Table\n\t##\n\n\tid(self::Table) = self.pkey\n\n\tlength(self::Table) = length(self.rows)\n\n\tfunction gen_pkey_value(self::Table)\n\t \"\"\"\n\t Assuming pkey is instance of a numeric type\n\t \"\"\"\n\t length(self.rows) == 0 && (return 1)\n\t (map(r -> r[id(self)], self.rows) |> maximum) + 1\n\tend\n\n\t## utility\n\tfunction check_pk(cols, types, pkey)\n\t if pkey.first !== nothing\n\t\t@assert pkey[2] <: Integer \"Expecting an Integer, got: $(pkey[2])\"\n\t end\n\n\t if pkey.first !== nothing && pkey.first ∉ cols\n\t\tcols = [pkey[1], cols...]\n\t\ttypes = [pkey[2], types...]\n\t end\n\t (cols, types)\n\tend\nend\n\n# ╔═╡ 040a7354-92d2-11eb-2825-7bac34b9fdf9\nYaUsers = Table([:name => String, :num_friends => Int];\n\tpkey=(:user_id => Int32))\n\n# ╔═╡ 17d214a7-be15-4236-a614-3127b535ef66\nAltUsers = Table([:name => String, :num_friends => Int]) ## Default pkey\n\n# ╔═╡ 85211d8a-be50-454d-a6c5-cd820a20f8d4\n## Default pkey and NULL values allowed\nAltUsers₂ = Table([:name, :num_friends], [U_SN, U_IN])\n\n# ╔═╡ adf67244-92d4-11eb-3004-41e62e906e32\nbegin\n\t##\n\t## Convention: by default all tables have a primary key called :id,\n\t## unless explicitly stated otherwise, something like:\n\t## :pkey => (:user_id, Int)\n\t##\n\tUsers = Table([:name => U_SN, :num_friends => U_IN];\n\t\tpkey=(:user_id => Int))\n\t@assert length(Users) == 0\n\tUsers;\nend\n\n# ╔═╡ 650237ee-928e-11eb-0e43-17ab98a0cc11\nbegin\n\t##\n\t## API for Table (cont'ed)\n\t##\n\n\tfunction insert(self::Table, row::Vector{Pair{Symbol, DT}}) where DT <: Any\n\t \"\"\"\n\t row is something like [:name => \"FooBar\", :num_friends => 3, id(Users) => 3]\n\t \"\"\"\n\t res = filter(p -> p.first == id(self), row)\n\t has_pkey = length(res) > 0\n\t ##\n\t ## NULL values permitted\n\t #length(row) ≠ length(self.types) && has_pkey &&\n\t # throw(ArgumentError(\"Mismatch with expected number of columns\"))\n\t ##\n\t check_value_dtype(self, row)\n\t ## find the pair pkey is given by id(self)\n\t row_ids = filter(p -> p.first == id(self), row)\n\t if length(row_ids) == 0\n\t\tpk_id = gen_pkey_value(self)\n\t\trow = [row..., id(self) => pk_id]\n\t else\n\t\tid_val = row_ids[1][2] ## value assoc with this pkey\n\t\trow_already_inserted(self, id_val) && (return nothing)\n\t end\n\t push!(self.rows, Dict(row...))\n\tend\n\n\tfunction insert(self::Table, row::Vector{Any})\n\t \"\"\"\n\t row is something like: [9, \"Foo\", 2 ] - just pure values\n\t \"\"\"\n\t length(row) ≠ length(self.types) && id(self) ∈ map(p -> p[1], row) &&\n\t\tthrow(ArgumentError(\"Mismatch with expected number of columns \"))\n\t #\n\t check_value_dtype(self, row)\n\t ## row[1] is the value assoc. with pkey\n\t row_already_inserted(self, row[1]) && (return nothing)\n\t push!(self.rows, Dict(zip(self.columns, row)))\n\tend\n\n\tfunction insert(self::Table, row::Row)\n\t \"\"\"\n\t row is a Dict, like: insert(Users, Dict(:name => \"Foo\", :num_friends => 5))\n\t \"\"\"\n\t length(row) ≠ length(self.types) && haskey(row, id(self)) &&\n\t\tthrow(ArgumentError(\"Mismatch with expected number of columns\"))\n\t check_value_dtype(self, row)\n\t if haskey(row, id(self))\n\t\trow_already_inserted(self, row[id(self)]) && (return nothing)\n\t else\n\t\trow[id(self)] = gen_pkey_value(self)\n\t end\n\t push!(self.rows, row)\n\tend\n\n\tinsert(self::Table, rows::Vector{T}) where T <: GRow = insert.(Ref(self), rows)\n\n\tfunction coltype(self::Table, colname::Symbol)::UDT\n\t ix = findfirst(col -> col == colname, self.columns)\n\t ix === nothing && throw(ArgumentError(\"column $(colname) inexistent\"))\n\t self.types[ix]\n\tend\n\n\t# function Base.show(io::IO, self::Table)\n\t# \ts = \"num. records: $(length(self)):\\n\"\n\t# \tfor rd ∈ self.rows\n\t# \t\ts₁ = []\n\t# \t\tfor (k, v) ∈ rd\n\t# \t\t\tpush!(s₁, \"$(k): $(v)\")\n\t# \t\tend\n\t# \t\ts = string(s, \" <\", join(s₁, \", \"), \">\\n\")\n\t# \tend\n\t# \tprint(io, \"$(s)\")\n\t# end\n\n\n\t##\n\t## Internal checkers\n\t##\n\n\tfunction check_value_dtype(self::Table, values::Vector{DT}) where DT <: Any\n\t dtypes = self.types\n\t for (v, dt) ∈ zip(values, dtypes)\n\t\t!(typeof(v) <: dt) && v !== nothing &&\n\t\t throw(\"Expected type for <$(v)>: $(dt), got: $(typeof(v))\")\n\t end\n\tend\n\n\n\tfunction check_value_dtype(self::Table,\n\t\t\t\t\t\t\t row::Union{Row, Vector{Pair{Symbol, DT}}}) where DT <: Any\n\t (cols, types) = self.columns, self.types\n\t col_type = Dict(zip(cols, types))\n\t for (k, v) ∈ row\n\t\t(haskey(col_type, k) && typeof(v) <: col_type[k]) ||\n\t\t throw(\"Expected type/2: $(col_type[k]), got: $(typeof(v))\")\n\t end\n\tend\n\n\tfunction row_already_inserted(self::Table, id_val::Any)::Bool\n\t\tid(self) === nothing && return false ## no pkey => ignore check\n\t\t#\n\t\tres = filter(r -> r[id(self)] == id_val, self.rows)\n\t\tlength(res) > 0 ## row already inserted id > 0\n\tend\n\nend\n\n# ╔═╡ d146a8ac-92cc-11eb-29b1-bb065a468477\nmd\"\"\"\nInsert using an array/vector:\n\"\"\"\n\n# ╔═╡ 13a0940e-8ce4-11eb-231c-f331a607203c\nbegin\n\tinsert(Users, [0, \"Hero\", 0])\n\t@assert length(Users) ≥ 1\nend\n\n# ╔═╡ e3458d34-92cc-11eb-2426-79f229abd908\nmd\"\"\"\nInsert using a vector of pairs:\n\"\"\"\n\n# ╔═╡ 96c2a668-9290-11eb-074d-19ffeb68eba6\nbegin\n\tinsert(Users, [id(Users) => 1, :name => \"Dunn\", :num_friends => 2])\n\t@assert length(Users) ≥ 2\nend\n\n# ╔═╡ f1357972-92cc-11eb-1f73-43aae5a43aa5\nmd\"\"\"\nInsert using a dictionary\n\"\"\"\n\n# ╔═╡ 5a3a8fdc-929d-11eb-25e3-e309dffdb455\nbegin\n\t## Insert with a Dict\n\tinsert(Users, Dict(id(Users) => 2, :name => \"Sue\", :num_friends => 3))\n\t@assert length(Users) ≥ 3\nend\n\n# ╔═╡ 0292e48e-92cd-11eb-1882-81a2faaad136\nmd\"\"\"\nInsert using a dictionary, no primary key value specified:\n\"\"\"\n\n# ╔═╡ 8545d17c-929e-11eb-0989-ffd4749bbb25\nbegin\n\t## Insert with a Dict no pkey/1\n\tinsert(Users, Dict(:name => \"Ayumi\", :num_friends => 5))\n\t@assert length(Users) ≥ 4\nend\n\n# ╔═╡ 95d2b19e-92a4-11eb-0f91-e343c9317983\nbegin\n\t## Insert with a Dict no pkey/2\n\tinsert(Users, [:name => \"PasMas\", :num_friends => 5])\n\t@assert length(Users) ≥ 5\nend\n\n# ╔═╡ 8a945abc-012f-4ace-a67a-b7e0f520346b\nbegin\n\t## Insert with a Dict no pkey/2 + null value (encoded as nothing)\n\t# insert(Users,\n\t# \t[:name => \"Foobar\", :num_friends => nothing])\n\tinsert(Users,\n\t\t[:name => \"Foobar\", :num_friends => nothing, :user_id => 17])\nend\n\n# ╔═╡ 28ba0bf6-92cd-11eb-0669-75eadb768518\nmd\"\"\"\nInsert using a collection (vector of rows):\n\"\"\"\n\n# ╔═╡ d4562f7e-9290-11eb-2d8c-952f2e0edfed\nbegin\n\t## Insert a collection (Vector of) of Records \n\tinsert(Users, [\n\t\t[5, \"Chi\", 3],\n\t\t[6, \"Thor\", 3],\n\t\t[7, \"Clive\", 2],\n\t\t[8, \"Devin\", 2],\n\t\t[9, \"Kate\", 2],\n\t\t[10, \"Kaze\", nothing]\n\t])\n\t@assert length(Users) ≥ 10\nend\n\n# ╔═╡ f877c3e6-929c-11eb-00cd-c15568f99627\nUsers\n\n# ╔═╡ d5657a88-92c4-11eb-2a4f-c7dcaa97bcf6\nbegin\n\t@test_throws ArgumentError coltype(Users, :foobar)\n\t@test coltype(Users, :num_friends) == U_IN\n\t@test coltype(Users, :name) == U_SN\nend\n\n# ╔═╡ 80ddf0f4-8ce2-11eb-3046-331119a0dc9b\nhtml\"\"\"\n
\n\"\"\"\n\n# ╔═╡ 80a71408-8ce2-11eb-3978-75a4a2df9116\nmd\"\"\"\n#### Update\n\"\"\"\n\n# ╔═╡ d1ed1e36-8ce5-11eb-34ee-4db60fb0db8a\nmd\"\"\"\nThe key features for an update:\n - what table,\n - which fields/rows \n - what their new values will be\n\"\"\"\n\n# ╔═╡ 4ccdb1ce-92c2-11eb-18dd-c510e88474c6\n##\n## API (cont'ed)\n##\nfunction update(self::Table, updates::Row, pred::WhereClause=row -> true)\n\t## 1 - Make sure key/columns and values are consistent with column types\n\tfor (col, val) ∈ updates\n\t\tcol ∉ self.columns && throw(ArgumentError(\"invalid column $(col)\"))\n\t\tcol_type = coltype(self, col)\n\t\t!(typeof(val) <: col_type) && val !== nothing && \n\t\t\tthrow(ArgumentError(\"Expected $(col_type), got $(typeof(val))\"))\n\tend\n\n\t## 2 - OK, update\n\trows_to_update = filter(((ix, r)=t) -> pred(r), collect(enumerate(self.rows)))\n\tfor (ix, row) ∈ rows_to_update\n\t\t# self.rows[ix] = Row(row..., updates...)\n\t\tfor (k, v) ∈ updates\n\t\t\tself.rows[ix][k] = v\n\t\tend\n\tend\n\tnothing\nend\n\n# ╔═╡ 2af6dbec-92c6-11eb-1155-596ed44b04f8\nbegin\n\tupdate(Users, Dict{Symbol, Any}(:num_friends => 7),\n\t\trow -> row[:name] == \"Ayumi\")\n\tUsers\nend\n\n# ╔═╡ 2abb0114-92c6-11eb-01d5-cd34aa6426b2\nbegin\n\tupdate(Users, Dict{Symbol, Any}(:num_friends => 4), row -> row[:num_friends] == 2)\n\tUsers\nend\n\n# ╔═╡ bc1fb8d2-92ca-11eb-14e0-c9586461bc1e\nbegin\n\tupdate(Users, Dict{Symbol, Any}(:num_friends => 1))\n\tUsers\nend\n\n# ╔═╡ d2b198b6-8ce2-11eb-170e-0f17904c9f2c\nhtml\"\"\"\n
\n\"\"\"\n\n# ╔═╡ d37f37b8-8ce8-11eb-2c00-3f98ca407f41\nmd\"\"\"\n#### Delete\n\"\"\"\n\n# ╔═╡ 5bf7729e-8dfd-11eb-070f-9b7ec0746bd7\n##\n## API (cont'ed)\n##\nfunction delete(self::Table, pred::WhereClause=row -> true)|\n\tself.rows = [\n\t\trow for row ∈ self.rows if !pred(row)\n\t]\n\tnothing\nend\n\n# ╔═╡ 394093fa-8cea-11eb-0071-eff3045a012b\nbegin\n\tn = length(Users)\n\tdelete(Users, row -> row[id(Users)] == 1)\n\t@assert length(Users) == n - 1\nend\n\n# ╔═╡ 435c4444-8dfd-11eb-24e8-5543f905f199\nbegin\n\tdelete(Users)\n\t@assert length(Users) == 0\nend\n\n# ╔═╡ e95983ba-8ceb-11eb-38fd-ed92cdcf754c\nhtml\"\"\"\n
\n\"\"\"\n\n# ╔═╡ d3a749a2-8cec-11eb-1f06-b568f244b576\nmd\"\"\"\n#### Select\n\"\"\"\n\n# ╔═╡ 31d3226a-8cf4-11eb-0897-39989ba76b58\nmd\"\"\"\nWe will give our Table struct a select method that returns a new Table . The\nmethod accepts two optional arguments:\n - `keep_cols` which specifies the names of the columns we want to\nkeep in the result. if none supply, the result contains all the columns, and\n\n - `add_cols` is a dictionary whose keys are new column names and whose values are functions specifying how to compute the values of the new columns. \n\"\"\"\n\n# ╔═╡ 3ec9f5d5-6d6d-4586-b68b-84e3ee5aee27\n## Utility function\n##\nfunction create_res_table(self::Table, new_cols, new_types;\n pred::Function=_a -> true)\n ## keep pkey or not...\n pred(self) ?\n\tTable(new_cols, new_types; pkey=id(self) => coltype(self, id(self))) :\n Table(new_cols, new_types; pkey=nothing => Nothing)\nend\n\n# ╔═╡ a56253c8-92cd-11eb-31b9-51e1fd5ae026\nfunction select(self::Table;\n\t\tkeep_cols=Vector{Symbol}[], add_cols=D_SF())::Table\n\t##\n\tlength(keep_cols) == 0 && (keep_cols = self.columns)\n\n\t## New column names and types\n\tnew_cols = [keep_cols..., collect(keys(add_cols))...]\n\tkeep_types = [coltype(self, col) for col in keep_cols]\n\n\t## collect the rows for result table\n\tn_rows = Vector{Any}[]\n\tadd_types = Any[]\n\tfor (ix, row) ∈ enumerate(self.rows)\n\t\tn_row = Any[row[col] for col ∈ keep_cols]\n\t\t## as we process the first row, we can get the return type...\n\t\t## ...of each function defined in add_cols\n\t\t## What if no row to process => tag with Any\n\t\tfor (_col_name, fn) ∈ add_cols\n\t\t\tr = fn(row)\n\t\t\tix == 1 && push!(add_types, typeof(r))\n\t\t\tpush!(n_row, r)\n\t\tend\n\t\tpush!(n_rows, n_row)\n\tend\n\n\tif length(add_cols) > 0 && length(add_types) == 0\n\t\t## add as many Any as column in add_cols\n\t\tpush!(add_types, repeat(Any[Any], inner=length(add_cols)))\n\tend\n\n\t## Create result table\n\tnew_types = UDT[keep_types..., add_types...]\n\t@assert(length(new_cols) == length(new_types),\n\t\t\"length(new_cols) == length(new_types)\")\n\n\tn_table = create_res_table(self, new_cols, new_types;\n\t\tpred=s -> id(s) ∈ keep_cols)\n\n\tinsert(n_table, n_rows)\n\tn_table\nend\n\n# ╔═╡ e6348294-92cb-11eb-3bfd-09d80933b33a\nbegin\n\tdelete(Users)\n\tinsert(Users, [[0, \"Hero\", 0],\n\t\t\t[1, \"Dunn\", 2],\n\t\t\t[2, \"Sue\", 3],\n\t\t\t[3, \"Chi\", 3],\n\t\t\t[4, \"Thor\", 3],\n\t\t\t[5, \"Clive\", 2],\n\t\t\t[6, \"Hicks\", 3],\n\t\t\t[7, \"Devin\", 2],\n\t\t\t[8, \"Kate\", 2]\n\t])\n\tinsert(Users, Dict(:name => \"Ayumi\", :num_friends => 5))\n\tinsert(Users, [:name => \"PasMas\", :num_friends => 5])\nend\n\n# ╔═╡ 96386ab8-93ef-44c7-a524-1246379d7103\nTable([:user_id, :name, :num_friends], UDT[Int64, Union{Nothing, String}, Union{Nothing, Int64}])\n\n# ╔═╡ a5441766-92cd-11eb-1c8e-edcf3db0022e\nbegin\n\t## SELECT * FROM Users;\n\tn₀ = length(Users)\n\tall_users = select(Users)\n\t@assert length(all_users) == n₀\nend\n\n# ╔═╡ 3bfad78b-2ebd-4067-b306-b687f5a92a10\nbegin\n\t## SELECT id FROM Users;\n\tuser_ids = select(Users, keep_cols=[:name])\nend\n\n# ╔═╡ cfed19ac-94e2-4c84-85b4-6134765cce0b\nmd\"\"\"\n##### Limit\n\"\"\"\n\n# ╔═╡ 386a0591-92ce-4267-b1e6-73e293eb727c\n##\n## API (cont'ed)\n##\nfunction limit(self::Table, num_rows::Int=5)::Table\n\t\"\"\"\n\tOnly the first num_rows are returned\n\t\"\"\"\n\t@assert 1 ≤ num_rows ≤ length(self.rows) \"1 ≤ $(num_rows) ≤ $(length(self.rows))\"\n\n \tn_table = create_res_table(self, self.columns, self.types;\n\t\tpred=s -> id(s) !== nothing)\n\n\t## NOTE: mark vector as GRow type\n\trows = Vector{Any}[]\n\tfor row ∈ self.rows[1:num_rows]\n\t\tpush!(rows, Any[v for (_, v) ∈ row])\n\tend\n\tinsert(n_table, rows)\n\tn_table\nend\n\n# ╔═╡ 53c15148-1b04-4d85-aac6-874a6f750a00\nuser_names₁ = select(Users, keep_cols=[:name]) |> limit\n\n# ╔═╡ 1ac32ed0-6e47-4606-8b70-524159660d93\nuser_names₂ = select(Users, keep_cols=[:name]) |>\n u -> limit(u, 2)\n\n# ╔═╡ be425e03-c7b4-401d-9d29-fa2b07618ee5\nmd\"\"\"\n###### Where\n\"\"\"\n\n# ╔═╡ e99eab12-08d9-4955-ba10-2eb46f74bd85\n##\n## API (cont'ed)\n##\nfunction where(self::Table, pred::WhereClause=row -> true)::Table\n\t\"\"\"\n\tOnly the rows that satisfy pred are returned\n\t\"\"\"\n\tn_table = create_res_table(self, self.columns, self.types;\n\t\tpred=s -> id(s) !== nothing)\n\n\tn_rows = Vector{Any}[]\n\tfor row ∈ self.rows\n\t\tpred(row) && (push!(n_rows, [row[col] for col ∈ n_table.columns]))\t\n\tend\n\n\tinsert(n_table, n_rows)\n\tn_table\nend\n\n# ╔═╡ b08b9470-5d53-4420-bef6-ef1c0bb4414c\nbegin\n\tdunn_ids = where(Users, row -> row[:name] == \"Dunn\") |> \n\t\tu -> select(u, keep_cols=[id(Users)])\n\t# @assert length(dunn_ids) == 1\nend\n\n# ╔═╡ 955fe2a1-22b3-44db-b23d-d595d58bac3d\nbegin\n\tamp_ids = where(Users, row -> row[:name][1] ∈ ['A', 'P']) |> \n\t\tu -> select(u, keep_cols=[id(Users), :name])\nend\n\n# ╔═╡ 964507de-c48d-4f7c-ab05-9b7739ecd5f3\nbegin\n\tncol = length(Users.columns)\n\tfunction name_len_fn(row)::Int \n\t\tlength(row[:name])\n\tend\n\n\tname_lengths = select(Users;\n\t\tadd_cols=D_SF(:name_length => name_len_fn))\nend\n\n# ╔═╡ 13c464eb-2a59-488b-b0ab-922ecda91bbd\nbegin\n\tname_lengths₂ = select(Users;\n\t\tadd_cols=Dict{Symbol, Function}(\n\t\t\t:name_ini => row -> string(row[:name][1]),\n\t\t\t:len_name => row -> length(row)\n\t\t)\n\t)\nend\n\n# ╔═╡ 95ae9db4-f9ba-4fde-a021-0fc952550627\nmd\"\"\"\n##### Aside on introspection\n\"\"\"\n\n# ╔═╡ 17b2e439-4f70-4db6-a01f-638ae2f88b6f\nbegin\n\t## with explicit return type\n\t##\n\tstr_fn = \"\"\"\nfunction name_len_fn(row, bar, vargs...)::UInt16\n\tlength(row[:name])\nend\n\"\"\"\n\texpr = Meta.parse(str_fn)\nend\n\n# ╔═╡ a57b3859-d026-4325-a5b2-7d4e7b4db408\nbegin\n\t## w/o explicit return type\n\t##\n\tstr_fn₂ = \"\"\"\nfunction name_len_fn(row1, bar1; foo1=10)\n\tlength(row[:name])\nend\n\"\"\"\n\texpr₂ = Meta.parse(str_fn₂)\nend\n\n# ╔═╡ 8e25eb57-b6f0-4c61-b657-4d815f1eb31f\nwith_terminal() do\n\tdump(expr)\nend\n\n# ╔═╡ 8ea2ba50-ad35-40b2-ab2d-1c34c9d90bd9\nexpr.args[1], expr₂.args[1]\n\n# ╔═╡ b34d8aaa-7696-452f-9fd7-1002aa771547\n## get return type\nexpr.args[1].args, length(expr.args[1].args), expr.args[1].args[end]\n\n# ╔═╡ 4ff7e8e9-354e-4c99-b6f8-aedbf7ce1f3f\nexpr₂.args[1].args, length(expr₂.args[1].args)\n\n# ╔═╡ 3a438295-3d30-41cc-95bd-db3b93e62d12\nfunction get_fn_retype(str_fn::String)::DataType\n\t\"\"\"\n\tReturn output type of a user function if such type is available...\n\t...which is the case iff expr.args[1].args has length of 2\n\tOtherwise fallback to Any\n\t\"\"\"\n\texpr = Meta.parse(str_fn)\n\tlength(expr.args[1].args) == 2 ? eval(expr.args[1].args[end]) : Any\nend\n\n# ╔═╡ 9b24fead-ccfd-43ed-afa8-ed5ef6c4cf8f\nget_fn_retype(str_fn), get_fn_retype(str_fn₂)\n\n# ╔═╡ 6e7e7896-8cf8-11eb-062e-99492ec8cff8\nhtml\"\"\"\n
\n\"\"\"\n\n# ╔═╡ 70f707c0-8cf6-11eb-11c2-73d7b28f7a0c\nmd\"\"\"\n#### Group by\n\"\"\"\n\n# ╔═╡ 70d84470-8cf6-11eb-23b6-c7ba506d8552\nmd\"\"\"\nThis function will take a list of columns we want to group by and a dictionary of aggragation functions plus an optional predicate parameter (having clause) that can operate on multiple rows. \n\"\"\"\n\n# ╔═╡ c451451a-8cf7-11eb-183b-e358c9d618e0\n##\n## API (cont'ed)\n##\n\nfunction group_by(self::Table; group_by_cols::Vector{Symbol}, agg::D_SF,\n\thaving=HavingClause=row_gp -> true)::Table\n\tgrouped_rows = Dict{}()\n\n\t## 1 - Populate groups\n\tfor row ∈ self.rows\n\t\tkey = Tuple(row[col] for col ∈ group_by_cols)\n\t\tary = get(grouped_rows, key, Row[])\n\t\tpush!(ary, row)\n\t\tgrouped_rows[key] = ary\n\tend\n\n\t## 2 - populate rows\n\tn_rows = Vector{Any}[]\n\tagg_types = Any[]\n\tfor (ix, (key, rows)) ∈ enumerate(grouped_rows)\n\t\tagg_row = Any[]\n\t\tif having(rows)\n\t\t\tagg_row = Any[agg_row..., key...] ## Keep Any[]\n\t\t\tfor (_, agg_fn) ∈ agg\n\t\t\t\tr = agg_fn(rows)\n\t\t\t\tix == 1 && push!(agg_types, typeof(r))\n\t\t\t\tpush!(agg_row, r)\n\t\t\tend\n\t\tend\n\t\tlength(agg_row) > 0 && (push!(n_rows, agg_row))\n\tend\n\n\t## 3 - res. table consists of group_by columns and aggregates\n\tnew_cols = [group_by_cols..., collect(keys(agg))...] |> unique\n\tgp_by_types = [coltype(self, col) for col ∈ group_by_cols]\n\tnew_types = [gp_by_types..., agg_types...]\n\n\tn_table = create_res_table(self, new_cols, new_types;\n\t\tpred=s -> id(s) ∈ new_cols)\n\tinsert(n_table, n_rows)\n\tn_table\nend\n\n# ╔═╡ 30bdc788-8d01-11eb-2f8f-9fd79593ddb8\nbegin\n\t\"\"\"\n\t-- find number of users and smallest user_id for each possible name length:\n\tSELECT LENGTH(name) as name_length, MIN(user_id) AS min_user_id,\n\t\tCOUNT(*) AS num_users\n\tFROM users\n\tGROUP BY LENGTH(name);\n\t\"\"\"\n\tmin_user_id = rows -> minimum(row[id(Users)] for row ∈ rows)\n\tnum_rows = rows -> length(rows)\n\n\tstats_by_len = select(Users, add_cols=D_SF(:name_length => name_len_fn)) |>\n\t\tu -> group_by(u,\n\t\t\t\tgroup_by_cols=[:name_length],\n\t\t\t\tagg=D_SF(:min_user_id => min_user_id, :num_users => num_rows))\n\t#\nend\n\n# ╔═╡ c5bac3ae-c63b-44ba-9b10-75144410f456\nUsers\n\n# ╔═╡ e696c2dd-b250-418c-9161-9fd87bfc378e\nbegin\n\t\"\"\"\n\t-- average number of friends for users whose names start with specific letters\n\t-- but see only the results for letters whose corresponding average is greater\n\t-- than 1\n\tSELECT SUBSTR(name, 1, 1) AS first_letter,\n\t\tAVG(num_friends) AS avg_num_friends\n\tFROM users\n\tGROUP BY SUBSTR(name, 1, 1)\n\tHAVING AVG(num_friends) > 1;\n\t\"\"\"\n\tfirst_letter_fn = row -> row[:name] !== nothing ? string(row[:name][1]) : \"\"\n\n\tavg_num_friends_fn =\n\t\trows -> sum([row[:num_friends] for row in rows]) / length(rows)\n\n\tenough_friends_fn = rows -> avg_num_friends_fn(rows) > 1.\n\n\tavg_friends_by_letter =\n\t\tselect(Users, add_cols=D_SF(:first_letter => first_letter_fn)) |>\n\t\tu -> group_by(u, group_by_cols=[:first_letter],\n\t\t\t\tagg=D_SF(:avg_num_friends => avg_num_friends_fn),\n\t\t\t\thaving=enough_friends_fn)\nend\n\n# ╔═╡ 84946000-8d02-11eb-3160-571efee8fb0b\nhtml\"\"\"\n
\n\"\"\"\n\n# ╔═╡ d05f1c40-8d17-11eb-2724-4d989c4c6b92\nmd\"\"\"\n#### Order by\n\"\"\"\n\n# ╔═╡ 848fd812-8d02-11eb-01d6-75965b08bcc5\n##\n## API (cont'ed)\n##\nfunction order_by(self::Table, order::Function)::Table\n\tn_table = select(self)\n\tsort!(n_table.rows, by=order)\n\tn_table\nend\n\n# ╔═╡ 6cde1330-e1bb-419e-87f3-cf73c0e11e3d\nfriendliest_letters = avg_friends_by_letter |>\n\tu -> order_by(u, row -> -row[:avg_num_friends])\n# NOTE: -row(...) to reverse the sort\n\n# ╔═╡ 7d35f85e-8e07-11eb-228c-81d28a444b52\nfriendliest_letters₂ = avg_friends_by_letter |>\n\tu -> order_by(u, row -> -row[:avg_num_friends]) |>\n\tu -> limit(u, 3)\n# NOTE: -row(...) to reverse the sort\n\n# ╔═╡ 40d46802-8e0f-11eb-2e47-53096e24dbd8\nhtml\"\"\"\n
\n\"\"\"\n\n# ╔═╡ 80dff352-8d02-11eb-06b1-5f5e325046f5\nmd\"\"\"\n#### Join\n\"\"\"\n\n# ╔═╡ f1af4256-8e02-11eb-0238-2515d39a89cd\n##\n## API (cont'ed)\n##\nfunction join(self::Table, otable::Table; left_join=false)::Table\n\tjoin_on_cols = [c for c ∈ self.columns if c ∈ otable.columns]\n\n\tadd_cols = [c for c ∈ otable.columns if c ∉ join_on_cols && c != id(otable)]\n\tnew_cols = [self.columns..., add_cols...]\n\tnew_types = UDT[self.types..., coltype.(Ref(otable), add_cols)...]\n\n\tn_table = Table(new_cols, new_types; pkey=nothing => Nothing)\n\n\tn_rows = Vector{Any}[]\n\tfor row ∈ self.rows\n\t\tis_join = orow -> all(orow[c] == row[c] for c ∈ join_on_cols)\n\n\t\to_rows = where(otable, is_join).rows\n\t\tfor o_row ∈ o_rows\n\t\t\tpush!(n_rows, Any[[row[c] for c ∈ self.columns]...,\n\t\t\t\t\t[o_row[c] for c ∈ add_cols]...])\n\t\tend\n\n\t\tif left_join && length(o_rows) == 0\n\t\t\tpush!(n_rows, Any[[row[c] for c ∈ self.columns]...,\n\t\t\t\t\t[nothing for _ ∈ add_cols]...])\n\t\tend\n\tend\n\t@show \"join/4\", n_rows, length(n_rows)\n\tinsert(n_table, n_rows)\n\tn_table\nend\n\n# ╔═╡ 26571096-f30c-476a-ad0e-ef133ba2562f\nbegin\n\tUser_Interests = Table([:user_id => Int, :interest => String]) ## Default pkey\n\tinsert(User_Interests, [\n\t\t\t[1, 0, \"SQL\"],\n\t\t\t[2, 0, \"NoSQL\"],\n\t\t\t[3, 2, \"SQL\"],\n\t\t\t[4, 2, \"MySQL\"],\n\t\t\t[5, 7, \"PostgreSQL\"],\n\t\t\t[6, 7, \"SQL\"]\n\t])\nend\n\n# ╔═╡ a1a91e04-ffdb-49b1-a999-e1cf1a730cb4\nbegin\n\tsql_users = join(Users, User_Interests) |>\n\t\tu -> where(u, r -> r[:interest] == \"SQL\") |>\n\t\tu -> select(u, keep_cols=[:name])\nend\n\n# ╔═╡ 43a52692-8e10-11eb-2043-8f0be195f58a\nbegin\n\tsql_users₂ = join(Users, User_Interests; left_join=true) |>\n\t\tu -> where(u, r -> r[:interest] !== nothing &&\n\t\t\t\t\t\t\toccursin(r\"SQL\\z\", r[:interest])) |>\n\t\tu -> select(u, keep_cols=[:name])\n\t@test length(sql_users₂.rows) == 6\nend\n\n# ╔═╡ Cell order:\n# ╟─8c80e072-8b59-11eb-3c21-a18fe43c4536\n# ╠═de098278-8e74-11eb-13e3-49c1b6e06e7d\n# ╠═ac463e7a-8b59-11eb-229e-db560e17c5f5\n# ╟─e7373726-8b59-11eb-2a2b-b5138e4f5268\n# ╟─f5ee64b2-8b59-11eb-2751-0778efd589cd\n# ╟─81290d1c-8ce2-11eb-3340-337957fd81b7\n# ╟─8ff1bb20-8ce2-11eb-1de6-fd84daec8930\n# ╟─d3ee2138-8ce2-11eb-0b29-659a3be01512\n# ╠═6d759180-928b-11eb-1cc1-0593c7f3b0c2\n# ╟─2e8684fc-2ba6-48ec-81b3-f1c31cdde43a\n# ╠═53accaea-92d4-11eb-0bc2-3d2ee10f9bfb\n# ╟─1b1b8d8c-3803-43fa-b3af-7a58d75bb13b\n# ╠═6f9c58d4-92d1-11eb-2c09-cb1ea5afcd6d\n# ╠═040a7354-92d2-11eb-2825-7bac34b9fdf9\n# ╠═17d214a7-be15-4236-a614-3127b535ef66\n# ╠═85211d8a-be50-454d-a6c5-cd820a20f8d4\n# ╠═adf67244-92d4-11eb-3004-41e62e906e32\n# ╠═650237ee-928e-11eb-0e43-17ab98a0cc11\n# ╟─d146a8ac-92cc-11eb-29b1-bb065a468477\n# ╠═13a0940e-8ce4-11eb-231c-f331a607203c\n# ╟─e3458d34-92cc-11eb-2426-79f229abd908\n# ╠═96c2a668-9290-11eb-074d-19ffeb68eba6\n# ╟─f1357972-92cc-11eb-1f73-43aae5a43aa5\n# ╠═5a3a8fdc-929d-11eb-25e3-e309dffdb455\n# ╟─0292e48e-92cd-11eb-1882-81a2faaad136\n# ╠═8545d17c-929e-11eb-0989-ffd4749bbb25\n# ╠═95d2b19e-92a4-11eb-0f91-e343c9317983\n# ╠═8a945abc-012f-4ace-a67a-b7e0f520346b\n# ╟─28ba0bf6-92cd-11eb-0669-75eadb768518\n# ╠═d4562f7e-9290-11eb-2d8c-952f2e0edfed\n# ╠═f877c3e6-929c-11eb-00cd-c15568f99627\n# ╠═d5657a88-92c4-11eb-2a4f-c7dcaa97bcf6\n# ╟─80ddf0f4-8ce2-11eb-3046-331119a0dc9b\n# ╟─80a71408-8ce2-11eb-3978-75a4a2df9116\n# ╟─d1ed1e36-8ce5-11eb-34ee-4db60fb0db8a\n# ╠═4ccdb1ce-92c2-11eb-18dd-c510e88474c6\n# ╠═2af6dbec-92c6-11eb-1155-596ed44b04f8\n# ╠═2abb0114-92c6-11eb-01d5-cd34aa6426b2\n# ╠═bc1fb8d2-92ca-11eb-14e0-c9586461bc1e\n# ╟─d2b198b6-8ce2-11eb-170e-0f17904c9f2c\n# ╟─d37f37b8-8ce8-11eb-2c00-3f98ca407f41\n# ╠═5bf7729e-8dfd-11eb-070f-9b7ec0746bd7\n# ╠═394093fa-8cea-11eb-0071-eff3045a012b\n# ╠═435c4444-8dfd-11eb-24e8-5543f905f199\n# ╟─e95983ba-8ceb-11eb-38fd-ed92cdcf754c\n# ╟─d3a749a2-8cec-11eb-1f06-b568f244b576\n# ╟─31d3226a-8cf4-11eb-0897-39989ba76b58\n# ╠═3ec9f5d5-6d6d-4586-b68b-84e3ee5aee27\n# ╠═a56253c8-92cd-11eb-31b9-51e1fd5ae026\n# ╠═e6348294-92cb-11eb-3bfd-09d80933b33a\n# ╠═96386ab8-93ef-44c7-a524-1246379d7103\n# ╠═a5441766-92cd-11eb-1c8e-edcf3db0022e\n# ╠═3bfad78b-2ebd-4067-b306-b687f5a92a10\n# ╟─cfed19ac-94e2-4c84-85b4-6134765cce0b\n# ╠═386a0591-92ce-4267-b1e6-73e293eb727c\n# ╠═53c15148-1b04-4d85-aac6-874a6f750a00\n# ╠═1ac32ed0-6e47-4606-8b70-524159660d93\n# ╟─be425e03-c7b4-401d-9d29-fa2b07618ee5\n# ╠═e99eab12-08d9-4955-ba10-2eb46f74bd85\n# ╠═b08b9470-5d53-4420-bef6-ef1c0bb4414c\n# ╠═955fe2a1-22b3-44db-b23d-d595d58bac3d\n# ╠═964507de-c48d-4f7c-ab05-9b7739ecd5f3\n# ╠═13c464eb-2a59-488b-b0ab-922ecda91bbd\n# ╟─95ae9db4-f9ba-4fde-a021-0fc952550627\n# ╠═17b2e439-4f70-4db6-a01f-638ae2f88b6f\n# ╠═a57b3859-d026-4325-a5b2-7d4e7b4db408\n# ╠═8e25eb57-b6f0-4c61-b657-4d815f1eb31f\n# ╠═8ea2ba50-ad35-40b2-ab2d-1c34c9d90bd9\n# ╠═b34d8aaa-7696-452f-9fd7-1002aa771547\n# ╠═4ff7e8e9-354e-4c99-b6f8-aedbf7ce1f3f\n# ╠═3a438295-3d30-41cc-95bd-db3b93e62d12\n# ╠═9b24fead-ccfd-43ed-afa8-ed5ef6c4cf8f\n# ╟─6e7e7896-8cf8-11eb-062e-99492ec8cff8\n# ╟─70f707c0-8cf6-11eb-11c2-73d7b28f7a0c\n# ╟─70d84470-8cf6-11eb-23b6-c7ba506d8552\n# ╠═c451451a-8cf7-11eb-183b-e358c9d618e0\n# ╠═30bdc788-8d01-11eb-2f8f-9fd79593ddb8\n# ╠═c5bac3ae-c63b-44ba-9b10-75144410f456\n# ╠═e696c2dd-b250-418c-9161-9fd87bfc378e\n# ╟─84946000-8d02-11eb-3160-571efee8fb0b\n# ╟─d05f1c40-8d17-11eb-2724-4d989c4c6b92\n# ╠═848fd812-8d02-11eb-01d6-75965b08bcc5\n# ╠═6cde1330-e1bb-419e-87f3-cf73c0e11e3d\n# ╠═7d35f85e-8e07-11eb-228c-81d28a444b52\n# ╟─40d46802-8e0f-11eb-2e47-53096e24dbd8\n# ╟─80dff352-8d02-11eb-06b1-5f5e325046f5\n# ╠═f1af4256-8e02-11eb-0238-2515d39a89cd\n# ╠═26571096-f30c-476a-ad0e-ef133ba2562f\n# ╠═a1a91e04-ffdb-49b1-a999-e1cf1a730cb4\n# ╠═43a52692-8e10-11eb-2043-8f0be195f58a\n", "meta": {"hexsha": "e54eed33ad8f4538e8781df434a0bebfec2c2fd6", "size": 26862, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Data Science From Scratch/24_DB_SQL.jl", "max_stars_repo_name": "pascal-p/julia-notebooks", "max_stars_repo_head_hexsha": "568c884c8b0de8ce34a84e8d1ce5fb6994cf32b8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-01T20:34:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-01T20:34:56.000Z", "max_issues_repo_path": "Data Science From Scratch/24_DB_SQL.jl", "max_issues_repo_name": "pascal-p/julia-notebooks", "max_issues_repo_head_hexsha": "568c884c8b0de8ce34a84e8d1ce5fb6994cf32b8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Data Science From Scratch/24_DB_SQL.jl", "max_forks_repo_name": "pascal-p/julia-notebooks", "max_forks_repo_head_hexsha": "568c884c8b0de8ce34a84e8d1ce5fb6994cf32b8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-10T09:03:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-10T09:03:18.000Z", "avg_line_length": 26.1812865497, "max_line_length": 192, "alphanum_fraction": 0.674149356, "num_tokens": 11137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.411110869232168, "lm_q2_score": 0.14414884935602926, "lm_q1q2_score": 0.059261158757574026}} {"text": "#=\nCreated on 20/01/2021 16:45:00\nLast update: -\n\n@author: Michiel Stock\nmichielfmstock@gmail.com\n\nIllustration of the composite and parametric types:\n- composite types\n - mutable/immuatble\n- unions\n- Parametric types\n=#\n\n#=\nComposite types, sometimes call records, structs or object, can store several values in its *fields*.\n\nWhen defining a new composite type, we can choose them to be mutable or immuatble:\n- mutable types are defined using `mutable struct ... end`, they allow the fields to be changed after the object is created;\n- immuatble types are defined similarly using `mutable struct ... end`, after creating the object its fields cannot be changed.\nMutable types are a bit more flexible, though might be a somewhat less safe and are more difficult to work with. As the compiler\nknows everything in advance, it might better optimize for immutable types. Which one you choose depends on your application, though\ngenerally immuatable types are the better choice!\n\nAs an example, let us define an agent type for an ecological individual-based model (IBM). We create the abstract type `Agent` for which we\ncan then specify several children types.\n=#\n\nabstract type Agent end\n\n#=\nThe concrete types in such an IBM might represent an animal type you want to model, for example preys and predators. Making a concrete type of \na prey animal, we want each to have an unique identifier (represented by an integer) and a position. As we expect the agent to move, hence changing\nits position when our simulation runs, we choose a mutable type.\n=#\n\nmutable struct Prey <: Agent\n id::Int\n pos\nend\n# notice the type annotation for `id`, which we choose to always reprsenent by an integer.\n# the position might be represented by (x,y) coordinates, or as a location ID, or a position on a grid. We don't know, so we leave it untyped.\n\n# defining a composite type immediately a constructor available.\ndeer = Prey(1, (0.5, 1.9))\n\n# you can always check which field names are available\nfieldnames(Prey)\n\n# the fields can be accessed simply\ndeer.id, deer.pos\n\n# FYI: This is just syntactic sugar for `getfield`, e.g. `getfield(deer, :id)`\n\n# Similarly, a predator type can be defined. In addition to an id and position, which each agent has, they also have a size, determining its mobility.\n\nmutable struct Predator <: Agent\n id::Int\n pos\n size::Float64\nend\n\nwolf = Predator(2, (0.0, 0.0), 40.0) # 40 kg wolf\n\n#=\nUsing the `.` syntax for accessing the fields is not very tidy! We should define custom getter functions\nfor the user to access the relevant fields. We could define `id` and `position` methods to get the respective\nfields for the two agents. However, since these fields should be defined for every `Agent` type, we can just create\nthese for the Agent type!\n=#\n\nid(agent::Agent) = agent.id\nposition(agent::Agent) = agent.pos\n\n# Here, we could theoretically have ommited the type annotation in the function. Then the function would accept\n# objects of the non-agent type and likely yield an error because they don't have the `id` or `pos` field. Now,\n# these functions will return a `MethodError` when given a non-`Agent` input.\n\n# A slightly more interesting example is by extending `size`.\n\nBase.size(agent::Predator) = agent.size\n\n# Here, we had to import `size` because we are extending a function from the `Base` library to work with a new type (doing something vastly different\n# than its original function).\n\n# similarly, we can program behaviour between the agents\n\ninteract(agent1::Agent, agent2::Agent) = nothing\ninteract(agent1::Predator, agent2::Prey) = \"eat\"\ninteract(agent1::Prey, agent2::Predator) = \"run\"\n\n# We have chosen the default behaviour that two Agents of unspecified types do not interact at al,\n# this will now be the case when a prey meets other prey, a predator an other predator or a new third type comes into the equation.\n\n# FYI: Since in these simple examples, the `interact` methods do not use their arguments, merely perform type checking, we could have written this as `interact(::Agent,::Agent) = ...` etc.\n\n# PARAMETRIC TYPES\n\n#=\nSometimes we want more flexiblility in defining types. Think of designing a new type of matrix. Here you would like to work them for all\nnumeric datatypes, Int, Int8, Float6, Rational, in addition to new datatypes that might not even be defined yet! To this end, we use\n*parametric types*, types that depend on another type.\n\nFor example, consider a 2-dimensional coordinate:\n=#\n\nstruct Point{T}\n x::T\n y::T\nend\n\n# Here, each coordinate of the type `Point` has two attributes, `x` and `y`, of the same type. The specific type of Point can vary.\n\np = Point(1.0, 2.0)\n\nPoint(1, 2)\n\n# note that\n\np isa Point\n\n# But what will happen if you evaluate `Point(1, 2.0)`?\n\nPoint(1, 2.0)\n\n# Parametric types can be used in dispatch. For example, if we want to compute the norm of a Point, this would only make sense if Point is a number.\n\nnorm(p::Point{T} where {T<:Number}) = sqrt(p.x^2 + p.y^2)\n\nnorm(p)\n\n# Constructors\n\n## Outer constructors\n\n# Constructors are functions that create new objects. We have already seen that when creating a new `struc`, this immediately initiates the constructor (e.g., `Point(1.0, 2.0)`). These can also be made explicitly:\n\nPoint(x::T, y::T) where {T<:Real} = Point{T}(x,y)\n\n# Constructors, however, allow us to have custom behavior when initializing types. For example, we have seen that `Point(1, 2.0)` won't work, because the two inputs are of the same type.\n# In this case, we can make the rule that one of the inputs has to be promoted to a more general type.\n\n\nPoint(x::Real, y::Real) = Point(promote(x, y)...)\n\n\nPoint(1, 2.0)\n\n\n# We can write other constructors just like functions. For example, support that when we provide a single `x`, we want to create a point (x, y):\n\nPoint(x) = Point(x, x);\n\nPoint(1)\n\n## Inner constructors\n\n#The above examples show *outer constructors*. These are defined outside the structure. We can also use *inner constructors*, which are declared within the definition of the type. These make use of the keyword `new`. For example, let us define an ordered pair.\n\nstruct OrderedPair\n x\n y\n function OrderedPair(x, y)\n if x < y\n new(x, y)\n else\n new(y, x)\n end\n end\nend\n\nOrderedPair(18, 23)\n\nOrderedPair(8, 2)\n\n# FYI: for parametric types, the `new` keyword should be type annotated. So, for in the `Point` example one would use `new{T}(x,y)`.", "meta": {"hexsha": "65e18e7c2a57151dcee00c67b9062f12b520d203", "size": 6424, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/composite_types.jl", "max_stars_repo_name": "jpgmolina/DS-Julia2925", "max_stars_repo_head_hexsha": "4d96351afb72f4107fa12561a6a460dcd3c617e3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-02-03T14:07:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-18T13:27:08.000Z", "max_issues_repo_path": "examples/composite_types.jl", "max_issues_repo_name": "jpgmolina/DS-Julia2925", "max_issues_repo_head_hexsha": "4d96351afb72f4107fa12561a6a460dcd3c617e3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 74, "max_issues_repo_issues_event_min_datetime": "2020-11-23T22:50:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-27T12:49:00.000Z", "max_forks_repo_path": "examples/composite_types.jl", "max_forks_repo_name": "jpgmolina/DS-Julia2925", "max_forks_repo_head_hexsha": "4d96351afb72f4107fa12561a6a460dcd3c617e3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-01-31T14:56:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-19T07:11:30.000Z", "avg_line_length": 36.5, "max_line_length": 260, "alphanum_fraction": 0.7392590286, "num_tokens": 1639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3451052574867685, "lm_q2_score": 0.171061193791558, "lm_q1q2_score": 0.05903411732942963}} {"text": "\"\"\"\n ispangram(input)\n\nReturn `true` if `input` contains every alphabetic character (case insensitive).\n\n\"\"\"\nfunction ispangram(input)\n input_low = lowercase(input)\n lower_alpha = 'a':'z'\n\n return all(\n [(c in input_low) for c in lower_alpha]) \n\nend\n\n", "meta": {"hexsha": "fe6ac098d55b9f2426a1da1f2dfadc4a9745b65a", "size": 273, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/pangram/pangram.jl", "max_stars_repo_name": "jfcliang/jl-exercism-solutions", "max_stars_repo_head_hexsha": "8e8c2ee48dbea3175bcd0d0f2071de945014ce0f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "julia/pangram/pangram.jl", "max_issues_repo_name": "jfcliang/jl-exercism-solutions", "max_issues_repo_head_hexsha": "8e8c2ee48dbea3175bcd0d0f2071de945014ce0f", "max_issues_repo_licenses": ["MIT"], "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/pangram/pangram.jl", "max_forks_repo_name": "jfcliang/jl-exercism-solutions", "max_forks_repo_head_hexsha": "8e8c2ee48dbea3175bcd0d0f2071de945014ce0f", "max_forks_repo_licenses": ["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.0625, "max_line_length": 80, "alphanum_fraction": 0.6483516484, "num_tokens": 67, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.12252320450794524, "lm_q1q2_score": 0.05886978733217089}} {"text": "import Base.BaseDocs: @kw_str\n\n\"\"\"\n**欢迎来到 Julia $(string(VERSION)).** 完整的中文手册可以在这里找到\n\n https://docs.juliacn.com/\n\n更多中文资料和教程,也请关注 Julia 中文社区\n\n https://cn.julialang.org\n\n新手请参考中文 discourse 上的新手指引\n\n https://discourse.juliacn.com/t/topic/159\n\n输入 `?`, 然后输入你想要查看帮助文档的函数或者宏名称就可以查看它们的文档。例如 `?cos`, 或者 `?@time` 然后按回车键即可。\n\n在 REPL 中输入 `ENV[\"REPL_LOCALE\"]=\"\"` 将恢复英文模式。再次回到中文模式请输入 `ENV[\"REPL_LOCALE\"]=\"zh_CN\"`。\n\"\"\"\nkw\"help\", kw\"?\", kw\"julia\", kw\"\"\n\n\n\"\"\"\n using\n\n`using Foo` 将会加载一个名为 `Foo` 的模块(module)或者一个包,然后其 [`export`](@ref) 的名称将可以直接使用。不论是否被 `export`,名称都可以通过点来访问(例如,输入 `Foo.foo` 来访问到 `foo`)。查看[手册中关于模块的部分](@ref modules)以获取更多细节。\n\"\"\"\nkw\"using\"\n\n\"\"\"\n import\n\n`import Foo` 将会加载一个名为 `Foo` 的模块(module)或者一个包。`Foo` 模块中的名称可以通过点来访问到(例如,输入 `Foo.foo` 可以获取到 `foo`)。查看[手册中关于模块的部分](@ref modules)以获取更多细节。\n\"\"\"\nkw\"import\"\n\n\"\"\"\n export\n\n`export` 被用来在模块中告诉Julia哪些函数或者名字可以由用户使用。例如 `export foo` 将在 [`using`](@ref) 这个 module 的时候使得 `foo`可以直接被访问到。查看[手册中关于模块的部分](@ref modules)以获取更多细节。\n\"\"\"\nkw\"export\"\n\n\"\"\"\n abstract type\n\n`abstract type` 声明来一个不能实例化的类型,它将仅仅作为类型图中的一个节点存在,从而能够描述一系列相互关联的具体类型(concrete type):这些具体类型都是抽象类型的子节点。抽象类型在概念上使得 Julia 的类型系统不仅仅是一系列对象的集合。例如:\n\n```julia\nabstract type Number end\nabstract type Real <: Number end\n```\n\n[`Number`](@ref) 没有父节点(父类型), 而 [`Real`](@ref) 是 `Number` 的一个抽象子类型。\n\"\"\"\nkw\"abstract type\"\n\n\"\"\"\n module\n\n`module` 会声明一个 `Module` 类型的实例用于描述一个独立的变量名空间。在一个模块(module)里,你可以控制来自于其它模块的名字是否可见(通过载入,import),你也可以决定你的名字有哪些是可以公开的(通过暴露,export)。模块使得你在在创建上层定义时无需担心命名冲突。查看[手册中关于模块的部分](@ref modules)以获取更多细节。\n\n# 例子\n```julia\nmodule Foo\nimport Base.show\nexport MyType, foo\n\nstruct MyType\n x\nend\n\nbar(x) = 2x\nfoo(a::MyType) = bar(a.x) + 1\nshow(io::IO, a::MyType) = print(io, \"MyType \\$(a.x)\")\nend\n```\n\"\"\"\nkw\"module\"\n\n\"\"\"\n baremodule\n\n`baremodule` 将声明一个不包含 `using Base` 或者 `eval` 定义的模块。但是它将仍然载入 `Core` 模块。\n\"\"\"\nkw\"baremodule\"\n\n\"\"\"\n primitive type\n\n`primitive type` 声明了一个其数据仅仅由一系列二进制数表示的具体类型。比较常见的例子是整数类型和浮点类型。下面是一些内置的原始类型(primitive type):\n\n```julia\nprimitive type Char 32 end\nprimitive type Bool <: Integer 8 end\n```\n\n名称后面的数字表达了这个类型存储所需的比特数目。目前这个数字要求是 8 bit 的倍数。[`Bool`](@ref) 类型的声明展示了一个原始类型如何选择成为另一个类型的子类型。\n\"\"\"\nkw\"primitive type\"\n\n\n\"\"\"\n macro\n\n`macro` 定义了一种会将生成的代码包含在最终程序体中的方法,这称之为宏。一个宏将一系列输入映射到一个表达式,然后所返回的表达式将会被直接进行编译而不需要在运行时调用 `eval` 函数。宏的输入可以包括表达式、字面量和符号。例如:\n\n# 例子\n\n```jldoctest\njulia> macro sayhello(name)\n return :( println(\"Hello, \", \\$name, \"!\") )\n end\n@sayhello (macro with 1 method)\n\njulia> @sayhello \"小明\"\nHello, 小明!\n```\n\"\"\"\nkw\"macro\"\n\n\"\"\"\n local\n\n`local`将会定义一个新的局部变量。\n\n查看[手册:变量作用域](@ref scope-of-variables)以获取更详细的信息。\n\n# 例子\n```jldoctest\njulia> function foo(n)\n x = 0\n for i = 1:n\n local x # introduce a loop-local x\n x = i\n end\n x\n end\nfoo (generic function with 1 method)\n\njulia> foo(10)\n0\n```\n\"\"\"\nkw\"local\"\n\n\"\"\"\n global\n\n`global x` 将会使得当前作用域和当前作用所包含的作用域里的 `x` 指向名为 `x` 的全局变量。查看[手册:变量作用域](@ref scope-of-variables)以获取更多信息。\n\n# 例子\n```jldoctest\njulia> z = 3\n3\n\njulia> function foo()\n global z = 6 # use the z variable defined outside foo\n end\nfoo (generic function with 1 method)\n\njulia> foo()\n6\n\njulia> z\n6\n```\n\"\"\"\nkw\"global\"\n\n\"\"\"\n let\n\n`let` 会在每次被运行时声明一个新的变量绑定。这个新的变量绑定将拥有一个新的地址。这里的不同只有当变量通过闭包生存在它们的作用域外时才会显现。`let` 语法接受逗号分割的一系列赋值语句和变量名:\n\n```julia\nlet var1 = value1, var2, var3 = value3\n code\nend\n```\n\n这些赋值语句是按照顺序求值的,等号右边的表达式将会首先求值,然后才绑定给左边的变量。因此这使得 `let x = x` 这样的表达式有意义,因为这两个 `x` 变量将具有不同的地址。\n\"\"\"\nkw\"let\"\n\n\"\"\"\n quote\n\n`quote` 会将其包含的代码扩变成一个多重的表达式对象,而无需显示调用 `Expr` 的构造器。这称之为引用,比如说\n\n```julia\nex = quote\n x = 1\n y = 2\n x + y\nend\n```\n\n和其它引用方式不同的是,`:( ... )`形式的引用(被包含时)将会在表达式树里引入一个在操作表达式树时必须要考虑的 `QuoteNode` 元素。而在其它场景下,`:( ... )`和 `quote .. end` 代码块是被同等对待的。\n\"\"\"\nkw\"quote\"\n\n\n\"\"\"\n '\n\n厄米算符(共轭转置),参见 [`adjoint`](@ref)\n\n# 例子\n```jldoctest\njulia> A = [1.0 -2.0im; 4.0im 2.0]\n2×2 Array{Complex{Float64},2}:\n 1.0+0.0im -0.0-2.0im\n 0.0+4.0im 2.0+0.0im\n\njulia> A'\n2×2 Array{Complex{Float64},2}:\n 1.0-0.0im 0.0-4.0im\n -0.0+2.0im 2.0-0.0im\n```\n\"\"\"\nkw\"'\"\n\n\"\"\"\n const\n\n`const` 被用来声明常数全局变量。在大部分(尤其是性能敏感的代码)全局变量应当被声明为常数。\n\n```julia\nconst x = 5\n```\n\n可以使用单个 `const` 声明多个常数变量。\n\n```julia\nconst y, z = 7, 11\n```\n\n注意 `const` 只会作用于一个 `=` 操作,因此 `const x = y = 1` 声明了 `x` 是常数,而 `y` 不是。在另一方面,`const x = const y = 1`声明了 `x` 和 `y` 都是常数。\n\n注意「常数性质」并不会强制容器内部变成常数,所以如果 `x` 是一个数组或者字典(举例来讲)你仍然可以给它们添加或者删除元素。\n\n严格来讲,你甚至可以重新定义 `const`(常数)变量,尽管这将会让编译器产生一个警告。唯一严格的要求是这个变量的**类型**不能改变,这也是为什么常数变量会比一般的全局变量更快的原因。\n\"\"\"\nkw\"const\"\n\n\"\"\"\n function\n\n函数由 `function` 关键词定义:\n\n```julia\nfunction add(a, b)\n return a + b\nend\n```\n\n或者是更短的形式:\n\n```julia\nadd(a, b) = a + b\n```\n\n[`return`](@ref) 关键词的使用方法和其它语言完全一样,但是常常是不使用的。一个没有显示声明 `return` 的函数将返回函数体最后一个表达式。\n\"\"\"\nkw\"function\"\n\n\"\"\"\n return\n\n`return` 可以用来在函数体中立即退出并返回给定值,例如\n\n```julia\nfunction compare(a, b)\n a == b && return \"equal to\"\n a < b ? \"less than\" : \"greater than\"\nend\n```\n\n通常,你可以在函数体的任意位置放置 `return` 语句,包括在多层嵌套的循环和条件表达式中,但要注意 `do` 块。例如:\n\n```julia\nfunction test1(xs)\n for x in xs\n iseven(x) && return 2x\n end\nend\n\nfunction test2(xs)\n map(xs) do x\n iseven(x) && return 2x\n x\n end\nend\n```\n\n在第一个例子中,return 一碰到偶数就跳出包含它的函数,因此 `test1([5,6,7])` 返回 `12`。\n\n你可能希望第二个例子的行为与此相同,但实际上,这里的 `return` 只会跳出(在 `do` 块中的)*内部*函数并把值返回给 `map`。于是,`test2([5,6,7])` 返回 `[5,12,7]`。\n\"\"\"\nkw\"return\"\n\n# 仿照 https://docs.juliacn.com/latest/manual/control-flow/#man-conditional-evaluation-1\n\"\"\"\n if/elseif/else\n\n`if`/`elseif`/`else` 执行条件表达式(Conditional evaluation)可以根据布尔表达式的值,让部分代码被执行或者不被执行。下面是对 `if`-`elseif`-`else` 条件语法的分析:\n\n```julia\nif x < y\n println(\"x is less than y\")\nelseif x > y\n println(\"x is greater than y\")\nelse\n println(\"x is equal to y\")\nend\n```\n\n如果表达式 `x < y` 是 `true`,那么对应的代码块会被执行;否则判断条件表达式 `x > y`,如果它是 `true`,则执行对应的代码块;如果没有表达式是 true,则执行 `else` 代码块。`elseif` 和 `else` 代码块是可选的,并且可以使用任意多个 `elseif` 代码块。\n\"\"\"\nkw\"if\", kw\"elseif\", kw\"else\"\n\n\"\"\"\n for\n\n`for` 循环通过迭代一系列值来重复计算循环体。\n\n# 例子\n```jldoctest\njulia> for i in [1, 4, 0]\n println(i)\n end\n1\n4\n0\n```\n\"\"\"\nkw\"for\"\n\n# 仿照 https://docs.juliacn.com/latest/manual/control-flow/#man-loops-1\n\"\"\"\n while\n\n`while` 循环会重复执行条件表达式,并在该表达式为 `true` 时继续执行 while 循环的主体部分。当 while 循环第一次执行时,如果条件表达式为 false,那么主体代码就一次也不会被执行。\n\n# 例子\njldoctest\njulia> i = 1\n1\n\njulia> while i < 5\n println(i)\n global i += 1\n end\n1\n2\n3\n4\n```\n\"\"\"\nkw\"while\"\n\n\"\"\"\n end\n\n`end` 标记一个表达式块的结束,例如 [`module`](@ref)、[`struct`](@ref)、[`mutable struct`](@ref)、[`begin`](@ref)、[`let`](@ref)、[`for`](@ref) 等。`end` 在索引数组时也可以用来表示维度的最后一个索引。\n\n# 例子\n```jldoctest\njulia> A = [1 2; 3 4]\n2×2 Array{Int64,2}:\n 1 2\n 3 4\n\njulia> A[end, :]\n2-element Array{Int64,1}:\n 3\n 4\n```\n\"\"\"\nkw\"end\"\n\n# 仿照 https://docs.juliacn.com/latest/manual/control-flow/#try/catch-%E8%AF%AD%E5%8F%A5-1\n\"\"\"\n try/catch\n\n`try/catch` 语句可以用来捕获 `Exception`,并进行异常处理。例如,一个自定义的平方根函数可以通过 `Exception` 来实现自动按需调用求解实数或者复数平方根的方法:\n\n```julia\nf(x) = try\n sqrt(x)\ncatch\n sqrt(complex(x, 0))\nend\n```\n\n`try/catch` 语句允许保存 `Exception` 到一个变量中,例如 `catch y`。\n\n`try/catch` 组件的强大之处在于能够将高度嵌套的计算立刻解耦成更高层次地调用函数。\n\"\"\"\nkw\"try\", kw\"catch\"\n\n# 仿照 https://docs.juliacn.com/latest/manual/control-flow/#finally-%E5%AD%90%E5%8F%A5-1\n\"\"\"\n finally\n\n无论代码块是如何退出的,都让代码块在退出时运行某段代码。这里是一个确保一个打开的文件被关闭的例子:\n\n```julia\nf = open(\"file\")\ntry\n operate_on_file(f)\nfinally\n close(f)\nend\n```\n\n当控制流离开 `try` 代码块(例如,遇到 `return`,或者正常结束),`close(f)` 就会被执行。如果 `try` 代码块由于异常退出,这个异常会继续传递。`catch` 代码块可以和 `try` 还有 `finally` 配合使用。这时 `finally` 代码块会在 `catch` 处理错误之后才运行。\n\"\"\"\nkw\"finally\"\n\n\"\"\"\n break\n\n立即跳出当前循环。\n\n# 例子\n```jldoctest\njulia> i = 0\n0\n\njulia> while true\n global i += 1\n i > 5 && break\n println(i)\n end\n1\n2\n3\n4\n5\n```\n\"\"\"\nkw\"break\"\n\n\"\"\"\n continue\n\n跳过当前循环迭代的剩余部分。\n\n# 例子\n```jldoctest\njulia> for i = 1:6\n iseven(i) && continue\n println(i)\n end\n1\n3\n5\n```\n\"\"\"\nkw\"continue\"\n\n\"\"\"\n do\n\n创建一个匿名函数。例如:\n\n```julia\nmap(1:10) do x\n 2x\nend\n```\n\n等价于 `map(x->2x, 1:10)`。\n\n像这样便可使用多个参数:\n\n```julia\nmap(1:10, 11:20) do x, y\n x + y\nend\n```\n\"\"\"\nkw\"do\"\n\n\"\"\"\n ...\n\n「splat」运算符 `...` 表示参数序列。`...` 可以在函数定义中用来表示该函数接受任意数量的参数。`...` 也可以用来将函数作用于参数序列。\n\n# 例子\n```jldoctest\njulia> add(xs...) = reduce(+, xs)\nadd (generic function with 1 method)\n\njulia> add(1, 2, 3, 4, 5)\n15\n\njulia> add([1, 2, 3]...)\n6\n\njulia> add(7, 1:100..., 1000:1100...)\n111107\n```\n\"\"\"\nkw\"...\"\n\n\"\"\"\n ;\n\n`;` 在 Julia 中具有与许多类 C 语言相似的作用,用于分隔前一个语句的结尾。`;` 在换行中不是必要的,但可以用于在单行中分隔语句或者将多个表达式连接为单个表达式。`;` 也用于抑制 REPL 和类似界面中的输出打印。\n\n# 例子\n```julia\njulia> function foo()\n x = \"Hello, \"; x *= \"World!\"\n return x\n end\nfoo (generic function with 1 method)\n\njulia> bar() = (x = \"Hello, Mars!\"; return x)\nbar (generic function with 1 method)\n\njulia> foo();\n\njulia> bar()\n\"Hello, Mars!\"\n```\n\"\"\"\nkw\";\"\n\n\"\"\"\n x && y\n\n短路布尔 AND。\n\"\"\"\nkw\"&&\"\n\n\"\"\"\n x || y\n\n短路布尔 OR。\n\"\"\"\nkw\"||\"\n\n\"\"\"\n ccall((function_name, library), returntype, (argtype1, ...), argvalue1, ...)\n ccall(function_name, returntype, (argtype1, ...), argvalue1, ...)\n ccall(function_pointer, returntype, (argtype1, ...), argvalue1, ...)\n\n调用由 C 导出的共享库里的函数,该函数由元组 `(function_name, library)` 指定,其中的每个组件都是字符串或符号。若不指定库,还可以使用 `function_name` 的符号或字符串,它会在当前进程中解析。另外,`ccall` 也可用于调用函数指针 `function_pointer`,比如 `dlsym` 返回的函数指针。\n\n请注意参数类型元组必须是字面上的元组,而不是元组类型的变量或表达式。\n\n通过自动插入对 `unsafe_convert(argtype, cconvert(argtype, argvalue))` 的调用,每个传给 `ccall` 的 `argvalue` 将被类型转换为对应的 `argtype`。(有关的详细信息,请参阅 [`unsafe_convert`](@ref Base.unsafe_convert) 和 [`cconvert`](@ref Base.cconvert) 的文档。)在大多数情况下,这只会简单地调用 `convert(argtype, argvalue)`。\n\"\"\"\nkw\"ccall\"\n\n\"\"\"\n begin\n\n`begin...end` 表示一个代码块。\n\n```julia\nbegin\n println(\"Hello, \")\n println(\"World!\")\nend\n```\n\n通常,`begin` 不会是必需的,因为诸如 [`function`](@ref) and [`let`](@ref) 之类的关键字会隐式地开始代码块。另请参阅 [`;`](@ref)。\n\"\"\"\nkw\"begin\"\n\n\"\"\"\n struct\n\nstruct 是 Julia 中最常用的数据类型,由名称和一组字段指定。\n\n```julia\nstruct Point\n x\n y\nend\n```\n\n可对字段施加类型限制,该限制也可被参数化:\n\n```julia\n struct Point{X}\n x::X\n y::Float64\n end\n```\n\nstruct 可以通过 `<:` 语法声明一个抽象超类型:\nA struct can also declare an abstract super type via `<:` syntax:\n\n```julia\nstruct Point <: AbstractPoint\n x\n y\nend\n```\n\n`struct` 默认是不可变的;这些类型的实例在构造后不能被修改。如需修改实例,请使用 [`mutable struct`](@ref) 来声明一个可以修改其实例的类型。\n\n有关更多细节,比如怎么定义构造函数,请参阅手册的 [复合类型](@ref) 章节。\n\"\"\"\nkw\"struct\"\n\n\"\"\"\n mutable struct\n\n`mutable struct` 类似于 [`struct`](@ref),但另外允许在构造后设置类型的字段。有关详细信息,请参阅 [复合类型](@ref)。\n\"\"\"\nkw\"mutable struct\"\n\n\"\"\"\n new\n\n仅在内部构造函数中可用的特殊函数,用来创建该类型的对象。有关更多信息,请参阅手册的 [内部构造方法](@ref) 章节。\n\"\"\"\nkw\"new\"\n\n\"\"\"\n where\n\n`where` 关键字创建一个类型,该类型是其他类型在一些变量上所有值的迭代并集。例如 `Vector{T} where T<:Real` 包含所有元素类型是某种 `Real` 的 [`Vector`](@ref)。\n\n如果省略,变量上界默认为 `Any`:\n\n```julia\nVector{T} where T # short for `where T<:Any`\n```\n\n变量也可以具有下界:\n\n```julia\nVector{T} where T>:Int\nVector{T} where Int<:T<:Real\n```\n\n嵌套的 `where` 也有简洁的语法。例如,这行代码:\n\n```julia\nPair{T, S} where S<:Array{T} where T<:Number\n```\n\n可以缩写为:\n\n```julia\nPair{T, S} where {T<:Number, S<:Array{T}}\n```\n\n这种形式常见于方法签名:\n\n请注意,在这种形式中,最外层变量列在最前面。这与使用语法 `T{p1, p2, ...}` 将类型「作用」于参数值时所替换变量的次序相匹配。\n\"\"\"\nkw\"where\"\n\n\"\"\"\n ans\n\n一个引用最后一次计算结果的变量,在交互式提示符中会自动设置。\n\"\"\"\nkw\"ans\"\n\n\"\"\"\n Union{}\n\n`Union{}`,即空的类型 [`Union`](@ref),是没有值的类型。也就是说,它具有决定性性质:对于任何 `x`,`isa(x, Union{}) == false`。`Base.Bottom` 被定义为其别名,`Union{}` 的类型是 `Core.TypeofBottom`。\n\n# 例子\n```jldoctest\njulia> isa(nothing, Union{})\nfalse\n```\n\"\"\"\nkw\"Union{}\", Base.Bottom\n\n\"\"\"\n ::\n\n`::` 运算符用于类型声明,在程序中可被附加到表达式和变量后。详见手册的 [类型声明](@ref) 章节\n\n在类型声明外,`::` 用于断言程序中的表达式和变量具有给定类型。\n\n# 例子\n```jldoctest\njulia> (1+2)::AbstractFloat\nERROR: TypeError: typeassert: expected AbstractFloat, got Int64\n\njulia> (1+2)::Int\n3\n```\n\"\"\"\nkw\"::\"\n\n\"\"\"\nJulia 的基础库。\n\"\"\"\nkw\"Base\"\n", "meta": {"hexsha": "5b5abdfbfeebcba59678d56501022aa5209333d6", "size": 11505, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/basedocs.jl", "max_stars_repo_name": "UnofficialJuliaMirror/JuliaZH.jl-652e05fd-ed22-5b6c-bf99-44e63a676e5f", "max_stars_repo_head_hexsha": "78c38dadab009de38e34f12af89eff240bb9a724", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 504, "max_stars_repo_stars_event_min_datetime": "2018-07-19T03:38:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T04:55:11.000Z", "max_issues_repo_path": "src/basedocs.jl", "max_issues_repo_name": "UnofficialJuliaMirror/JuliaZH.jl-652e05fd-ed22-5b6c-bf99-44e63a676e5f", "max_issues_repo_head_hexsha": "78c38dadab009de38e34f12af89eff240bb9a724", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 78, "max_issues_repo_issues_event_min_datetime": "2018-07-18T16:21:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-04T14:44:51.000Z", "max_forks_repo_path": "src/basedocs.jl", "max_forks_repo_name": "UnofficialJuliaMirror/JuliaZH.jl-652e05fd-ed22-5b6c-bf99-44e63a676e5f", "max_forks_repo_head_hexsha": "78c38dadab009de38e34f12af89eff240bb9a724", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 114, "max_forks_repo_forks_event_min_datetime": "2018-07-18T19:24:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T08:23:42.000Z", "avg_line_length": 16.3191489362, "max_line_length": 258, "alphanum_fraction": 0.6392003477, "num_tokens": 6183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32082130082460697, "lm_q2_score": 0.18242552825126704, "lm_q1q2_score": 0.05852599527718758}} {"text": "module Example\n\nexport func\n\n\"\"\"\n func(x)\n\nReturns double the number `x` plus `1`.\n\nHere's an equation:\n\n``\\\\frac{n!}{k!(n - k)!} = \\\\binom{n}{k}``\n\n\"\"\"\nfunc(x) = 2x + 1\n\nend\n", "meta": {"hexsha": "2cba04500b4dc95f0556e1ed0de0d6e84788a6ff", "size": 178, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Example.jl", "max_stars_repo_name": "jorgepz/Julia_Docs_Testbed", "max_stars_repo_head_hexsha": "f1271de3a024e194f5161b28cb9e7e7d11fca238", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Example.jl", "max_issues_repo_name": "jorgepz/Julia_Docs_Testbed", "max_issues_repo_head_hexsha": "f1271de3a024e194f5161b28cb9e7e7d11fca238", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-06-23T14:34:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-24T20:35:58.000Z", "max_forks_repo_path": "src/Example.jl", "max_forks_repo_name": "jorgepz/Julia_Docs_Testbed", "max_forks_repo_head_hexsha": "f1271de3a024e194f5161b28cb9e7e7d11fca238", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 9.8888888889, "max_line_length": 42, "alphanum_fraction": 0.5449438202, "num_tokens": 63, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.11757213663746784, "lm_q1q2_score": 0.05832681150355962}} {"text": "#### Elementwise manipulations (scaling/clamping/type conversion) ####\n\n# This file exists primarily to handle conversions for display and\n# saving to disk. Both of these operations require UFixed-valued\n# elements, but with display we always want to convert to 8-bit\n# whereas saving can handle 16-bit.\n# We also can't trust that user images are clamped properly.\n# Finally, this supports adjustable contrast limits.\n\n# Structure of MapInfo subtype definitions:\n# - type definition\n# - constructors for scalars\n# - constructors for AbstractArrays\n# - similar (syntax: similar(mapi, ToType, FromType))\n# - implementation of map() for scalars\n# - implementation of map() for AbstractArrays\n# map(mapi::MapInfo{T}, x) should return an object of type T (for x not an array)\n# map1(mapi::MapInfo{T}, x) is designed to allow T<:Color to work on\n# scalars x::Fractional\n\n\n# Dispatch-based elementwise manipulations\n\"\"\"\n`MapInfo{T}` is an abstract type that encompasses objects designed to\nperform intensity or color transformations on pixels. For example,\nbefore displaying an image in a window, you might need to adjust the\ncontrast settings; `MapInfo` objects provide a means to describe these\ntransformations without calculating them immediately. This delayed\nexecution can be useful in many contexts. For example, if you want to\ndisplay a movie, it would be quite wasteful to have to first transform\nthe entire movie; instead, `MapInfo` objects allow one to specify a\ntransformation to be performed on-the-fly as particular frames are\ndisplayed.\n\nYou can create your own custom `MapInfo` objects. For example, given a\ngrayscale image, you could color \"saturated\" pixels red using\n\n```jl\nimmutable ColorSaturated{C<:AbstractRGB} <: MapInfo{C}\nend\n\nBase.map{C}(::ColorSaturated{C}, val::Union{Number,Gray}) = ifelse(val == 1, C(1,0,0), C(val,val,val))\n\nimgc = map(ColorSaturated{RGB{U8}}(), img)\n```\n\nFor pre-defined types see `MapNone`, `BitShift`, `ClampMinMax`, `ScaleMinMax`,\n`ScaleAutoMinMax`, and `ScaleSigned`.\n\"\"\"\nabstract MapInfo{T}\neltype{T}(mapi::MapInfo{T}) = T\n\n\n## MapNone\n\"`MapNone(T)` is a `MapInfo` object that converts `x` to have type `T`.\"\nimmutable MapNone{T} <: MapInfo{T}; end\n\n# Constructors\nMapNone{T}(::Type{T}) = MapNone{T}()\nMapNone{T}(val::T) = MapNone{T}()\nMapNone{T}(A::AbstractArray{T}) = MapNone{T}()\n\nsimilar{T}(mapi::MapNone, ::Type{T}, ::Type) = MapNone{T}()\n\n# Implementation\nmap{T}(mapi::MapNone{T}, val::Union{Number,Colorant}) = convert(T, val)\nmap1(mapi::Union{MapNone{RGB24}, MapNone{ARGB32}}, b::Bool) = ifelse(b, 0xffuf8, 0x00uf8)\nmap1(mapi::Union{MapNone{RGB24},MapNone{ARGB32}}, val::Fractional) = convert(UFixed8, val)\nmap1{CT<:Colorant}(mapi::MapNone{CT}, val::Fractional) = convert(eltype(CT), val)\n\nmap{T<:Colorant}(mapi::MapNone{T}, img::AbstractImageIndexed{T}) = convert(Image{T}, img)\nmap{C<:Colorant}(mapi::MapNone{C}, img::AbstractImageDirect{C}) = img # ambiguity resolution\nmap{T}(mapi::MapNone{T}, img::AbstractArray{T}) = img\n\n\n## BitShift\n\"\"\"\n`BitShift{T,N}` performs a \"saturating rightward bit-shift\" operation.\nIt is particularly useful in converting high bit-depth images to 8-bit\nimages for the purpose of display. For example,\n\n```\nmap(BitShift(UFixed8, 8), 0xa2d5uf16) === 0xa2uf8\n```\n\nconverts a `UFixed16` to the corresponding `UFixed8` by discarding the\nleast significant byte. However,\n\n```\nmap(BitShift(UFixed8, 7), 0xa2d5uf16) == 0xffuf8\n```\n\nbecause `0xa2d5>>7 == 0x0145 > typemax(UInt8)`.\n\nWhen applicable, the main advantage of using `BitShift` rather than\n`MapNone` or `ScaleMinMax` is speed.\n\"\"\"\nimmutable BitShift{T,N} <: MapInfo{T} end\nBitShift{T}(::Type{T}, n::Int) = BitShift{T,n}() # note that this is not type-stable\n\nsimilar{S,T,N}(mapi::BitShift{S,N}, ::Type{T}, ::Type) = BitShift{T,N}()\n\n# Implementation\nimmutable BS{N} end\n_map{T<:Unsigned,N}(::Type{T}, ::Type{BS{N}}, val::Unsigned) = (v = val>>>N; tm = oftype(val, typemax(T)); convert(T, ifelse(v > tm, tm, v)))\n_map{T<:UFixed,N}(::Type{T}, ::Type{BS{N}}, val::UFixed) = reinterpret(T, _map(FixedPointNumbers.rawtype(T), BS{N}, reinterpret(val)))\nmap{T<:Real,N}(mapi::BitShift{T,N}, val::Real) = _map(T, BS{N}, val)\nmap{T<:Real,N}(mapi::BitShift{Gray{T},N}, val::Gray) = Gray(_map(T, BS{N}, val.val))\nmap1{N}(mapi::Union{BitShift{RGB24,N},BitShift{ARGB32,N}}, val::Unsigned) = _map(UInt8, BS{N}, val)\nmap1{N}(mapi::Union{BitShift{RGB24,N},BitShift{ARGB32,N}}, val::UFixed) = _map(UFixed8, BS{N}, val)\nmap1{CT<:Colorant,N}(mapi::BitShift{CT,N}, val::UFixed) = _map(eltype(CT), BS{N}, val)\n\n\n## Clamp types\n# The Clamp types just enforce bounds, but do not scale or offset\n\n# Types and constructors\nabstract AbstractClamp{T} <: MapInfo{T}\n\"\"\"\n`ClampMin(T, minvalue)` is a `MapInfo` object that clamps pixel values\nto be greater than or equal to `minvalue` before converting to type `T`.\n\nSee also: `ClampMax`, `ClampMinMax`.\n\"\"\"\nimmutable ClampMin{T,From} <: AbstractClamp{T}\n min::From\nend\nClampMin{T,From}(::Type{T}, min::From) = ClampMin{T,From}(min)\nClampMin{T}(min::T) = ClampMin{T,T}(min)\n\"\"\"\n`ClampMax(T, maxvalue)` is a `MapInfo` object that clamps pixel values\nto be less than or equal to `maxvalue` before converting to type `T`.\n\nSee also: `ClampMin`, `ClampMinMax`.\n\"\"\"\nimmutable ClampMax{T,From} <: AbstractClamp{T}\n max::From\nend\nClampMax{T,From}(::Type{T}, max::From) = ClampMax{T,From}(max)\nClampMax{T}(max::T) = ClampMax{T,T}(max)\nimmutable ClampMinMax{T,From} <: AbstractClamp{T}\n min::From\n max::From\nend\n\"\"\"\n`ClampMinMax(T, minvalue, maxvalue)` is a `MapInfo` object that clamps\npixel values to be between `minvalue` and `maxvalue` before converting\nto type `T`.\n\nSee also: `ClampMin`, `ClampMax`, and `Clamp`.\n\"\"\"\nClampMinMax{T,From}(::Type{T}, min::From, max::From) = ClampMinMax{T,From}(min,max)\nClampMinMax{T}(min::T, max::T) = ClampMinMax{T,T}(min,max)\n\"\"\"\n`Clamp(C)` is a `MapInfo` object that clamps color values to be within\ngamut. For example,\n\n```\nmap(Clamp(RGB{U8}), RGB(1.2, -0.4, 0.6)) === RGB{U8}(1, 0, 0.6)\n```\n\"\"\"\nimmutable Clamp{T} <: AbstractClamp{T} end\nClamp{T}(::Type{T}) = Clamp{T}()\n\nsimilar{T,F}(mapi::ClampMin, ::Type{T}, ::Type{F}) = ClampMin{T,F}(convert(F, mapi.min))\nsimilar{T,F}(mapi::ClampMax, ::Type{T}, ::Type{F}) = ClampMax{T,F}(convert(F, mapi.max))\nsimilar{T,F}(mapi::ClampMinMax, ::Type{T}, ::Type{F}) = ClampMin{T,F}(convert(F, mapi.min), convert(F, mapi.max))\nsimilar{T,F}(mapi::Clamp, ::Type{T}, ::Type{F}) = Clamp{T}()\n\n# Implementation\nmap{T<:Real,F<:Real}(mapi::ClampMin{T,F}, val::F) = convert(T, max(val, mapi.min))\nmap{T<:Real,F<:Real}(mapi::ClampMax{T,F}, val::F) = convert(T, min(val, mapi.max))\nmap{T<:Real,F<:Real}(mapi::ClampMinMax{T,F}, val::F) = convert(T,min(max(val, mapi.min), mapi.max))\nmap{T<:Fractional,F<:Real}(mapi::ClampMin{Gray{T},F}, val::F) = convert(Gray{T}, max(val, mapi.min))\nmap{T<:Fractional,F<:Real}(mapi::ClampMax{Gray{T},F}, val::F) = convert(Gray{T}, min(val, mapi.max))\nmap{T<:Fractional,F<:Real}(mapi::ClampMinMax{Gray{T},F}, val::F) = convert(Gray{T},min(max(val, mapi.min), mapi.max))\nmap{T<:Fractional,F<:Fractional}(mapi::ClampMin{Gray{T},F}, val::Gray{F}) = convert(Gray{T}, max(val, mapi.min))\nmap{T<:Fractional,F<:Fractional}(mapi::ClampMax{Gray{T},F}, val::Gray{F}) = convert(Gray{T}, min(val, mapi.max))\nmap{T<:Fractional,F<:Fractional}(mapi::ClampMinMax{Gray{T},F}, val::Gray{F}) = convert(Gray{T},min(max(val, mapi.min), mapi.max))\nmap{T<:Fractional,F<:Fractional}(mapi::ClampMin{Gray{T},Gray{F}}, val::Gray{F}) = convert(Gray{T}, max(val, mapi.min))\nmap{T<:Fractional,F<:Fractional}(mapi::ClampMax{Gray{T},Gray{F}}, val::Gray{F}) = convert(Gray{T}, min(val, mapi.max))\nmap{T<:Fractional,F<:Fractional}(mapi::ClampMinMax{Gray{T},Gray{F}}, val::Gray{F}) = convert(Gray{T},min(max(val, mapi.min), mapi.max))\nmap1{T<:Union{RGB24,ARGB32},F<:Fractional}(mapi::ClampMin{T,F}, val::F) = convert(UFixed8, max(val, mapi.min))\nmap1{T<:Union{RGB24,ARGB32},F<:Fractional}(mapi::ClampMax{T,F}, val::F) = convert(UFixed8, min(val, mapi.max))\nmap1{T<:Union{RGB24,ARGB32},F<:Fractional}(mapi::ClampMinMax{T,F}, val::F) = convert(UFixed8,min(max(val, mapi.min), mapi.max))\nmap1{CT<:Colorant,F<:Fractional}(mapi::ClampMin{CT,F}, val::F) = convert(eltype(CT), max(val, mapi.min))\nmap1{CT<:Colorant,F<:Fractional}(mapi::ClampMax{CT,F}, val::F) = convert(eltype(CT), min(val, mapi.max))\nmap1{CT<:Colorant,F<:Fractional}(mapi::ClampMinMax{CT,F}, val::F) = convert(eltype(CT), min(max(val, mapi.min), mapi.max))\n\nmap{To<:Real}(::Clamp{To}, val::Real) = clamp01(To, val)\nmap{To<:Real}(::Clamp{Gray{To}}, val::AbstractGray) = Gray(clamp01(To, val.val))\nmap{To<:Real}(::Clamp{Gray{To}}, val::Real) = Gray(clamp01(To, val))\nmap1{CT<:AbstractRGB}(::Clamp{CT}, val::Real) = clamp01(eltype(CT), val)\nmap1{P<:TransparentRGB}(::Clamp{P}, val::Real) = clamp01(eltype(P), val)\n\n# Also available as a stand-alone function\nclamp01{T}(::Type{T}, x::Real) = convert(T, min(max(x, zero(x)), one(x)))\nclamp01(x::Real) = clamp01(typeof(x), x)\nclamp01(x::Colorant) = clamp01(typeof(x), x)\nclamp01{Cdest<:AbstractRGB }(::Type{Cdest}, x::AbstractRGB) = (To = eltype(Cdest);\n Cdest(clamp01(To, red(x)), clamp01(To, green(x)), clamp01(To, blue(x))))\nclamp01{Pdest<:TransparentRGB}(::Type{Pdest}, x::TransparentRGB) = (To = eltype(Pdest);\n Pdest(clamp01(To, red(x)), clamp01(To, green(x)), clamp01(To, blue(x)), clamp01(To, alpha(x))))\n\n# clamp is generic for any colorspace; this version does the right thing for any RGB type\nclamp(x::Union{AbstractRGB, TransparentRGB}) = clamp01(x)\n\n## ScaleMinMax\n\"\"\"\n`ScaleMinMax(T, min, max, [scalefactor])` is a `MapInfo` object that\nclamps the image at the specified `min`/`max` values, subtracts the\n`min` value, scales the result by multiplying by `scalefactor`, and\nfinally converts to type `T`. If `scalefactor` is not specified, it\ndefaults to scaling the interval `[min,max]` to `[0,1]`.\n\nAlternative constructors include `ScaleMinMax(T, img)` for which\n`min`, `max`, and `scalefactor` are computed from the minimum and\nmaximum values found in `img`.\n\nSee also: `ScaleMinMaxNaN`, `ScaleAutoMinMax`, `MapNone`, `BitShift`.\n\"\"\"\nimmutable ScaleMinMax{To,From,S<:AbstractFloat} <: MapInfo{To}\n min::From\n max::From\n s::S\n\n function ScaleMinMax(min, max, s)\n min >= max && error(\"min must be smaller than max\")\n new(min, max, s)\n end\nend\n\nScaleMinMax{To,From}(::Type{To}, min::From, max::From, s::AbstractFloat) = ScaleMinMax{To,From,typeof(s)}(min, max, s)\nScaleMinMax{To<:Union{Fractional,Colorant},From}(::Type{To}, mn::From, mx::From) = ScaleMinMax(To, mn, mx, 1.0f0/(convert(Float32, mx)-convert(Float32, mn)))\n\n# ScaleMinMax constructors that take AbstractArray input\nScaleMinMax{To,From<:Real}(::Type{To}, img::AbstractArray{From}, mn::Real, mx::Real) = ScaleMinMax(To, convert(From,mn), convert(From,mx), 1.0f0/(convert(Float32, convert(From, mx))-convert(Float32,convert(From, mn))))\nScaleMinMax{To,From<:Real}(::Type{To}, img::AbstractArray{Gray{From}}, mn::Real, mx::Real) = ScaleMinMax(To, convert(From,mn), convert(From,mx), 1.0f0/(convert(Float32, convert(From,mx))-convert(Float32, convert(From,mn))))\nScaleMinMax{To,From<:Real,R<:Real}(::Type{To}, img::AbstractArray{From}, mn::Gray{R}, mx::Gray{R}) = ScaleMinMax(To, convert(From,mn.val), convert(From,mx.val), 1.0f0/(convert(Float32, convert(From,mx.val))-convert(Float32, convert(From,mn.val))))\nScaleMinMax{To,From<:Real,R<:Real}(::Type{To}, img::AbstractArray{Gray{From}}, mn::Gray{R}, mx::Gray{R}) = ScaleMinMax(To, convert(From,mn.val), convert(From,mx.val), 1.0f0/(convert(Float32, convert(From,mx.val))-convert(Float32, convert(From,mn.val))))\nScaleMinMax{To}(::Type{To}, img::AbstractArray) = ScaleMinMax(To, img, minfinite(img), maxfinite(img))\nScaleMinMax{To,CV<:AbstractRGB}(::Type{To}, img::AbstractArray{CV}) = (imgr = reinterpret(eltype(CV), img); ScaleMinMax(To, minfinite(imgr), maxfinite(imgr)))\n\nsimilar{T,F,To,From,S}(mapi::ScaleMinMax{To,From,S}, ::Type{T}, ::Type{F}) = ScaleMinMax{T,F,S}(convert(F,mapi.min), convert(F.mapi.max), mapi.s)\n\n# Implementation\nfunction map{To<:Union{Real,AbstractGray},From<:Union{Real,AbstractGray}}(mapi::ScaleMinMax{To,From}, val::From)\n g = gray(val)\n t = ifelse(g < mapi.min, zero(From), ifelse(g > mapi.max, mapi.max-mapi.min, g-mapi.min))\n convert(To, mapi.s*t)\nend\nfunction map{To<:Union{Real,AbstractGray},From<:Union{Real,AbstractGray}}(mapi::ScaleMinMax{To,From}, val::Union{Real,Colorant})\n map(mapi, convert(From, val))\nend\nfunction map1{To<:Union{RGB24,ARGB32},From<:Real}(mapi::ScaleMinMax{To,From}, val::From)\n t = ifelse(val < mapi.min, zero(From), ifelse(val > mapi.max, mapi.max-mapi.min, val-mapi.min))\n convert(UFixed8, mapi.s*t)\nend\nfunction map1{To<:Colorant,From<:Real}(mapi::ScaleMinMax{To,From}, val::From)\n t = ifelse(val < mapi.min, zero(From), ifelse(val > mapi.max, mapi.max-mapi.min, val-mapi.min))\n convert(eltype(To), mapi.s*t)\nend\nfunction map1{To<:Union{RGB24,ARGB32},From<:Real}(mapi::ScaleMinMax{To,From}, val::Union{Real,Colorant})\n map1(mapi, convert(From, val))\nend\nfunction map1{To<:Colorant,From<:Real}(mapi::ScaleMinMax{To,From}, val::Union{Real,Colorant})\n map1(mapi, convert(From, val))\nend\n\n## ScaleSigned\n\"\"\"\n`ScaleSigned(T, scalefactor)` is a `MapInfo` object designed for\nvisualization of images where the pixel's sign has special meaning.\nIt multiplies the pixel value by `scalefactor`, then clamps to the\ninterval `[-1,1]`. If `T` is a floating-point type, it stays in this\nrepresentation. If `T` is an `AbstractRGB`, then it is encoded as a\nmagenta (positive)/green (negative) image, with the intensity of the\ncolor proportional to the clamped absolute value.\n\"\"\"\nimmutable ScaleSigned{T, S<:AbstractFloat} <: MapInfo{T}\n s::S\nend\nScaleSigned{T}(::Type{T}, s::AbstractFloat) = ScaleSigned{T, typeof(s)}(s)\n\nScaleSigned{T}(::Type{T}, img::AbstractArray) = ScaleSigned(T, 1.0f0/maxabsfinite(img))\nScaleSigned(img::AbstractArray) = ScaleSigned(Float32, img)\n\nsimilar{T,To,S}(mapi::ScaleSigned{To,S}, ::Type{T}, ::Type) = ScaleSigned{T,S}(mapi.s)\n\nmap{T}(mapi::ScaleSigned{T}, val::Real) = convert(T, clamppm(mapi.s*val))\nfunction map{C<:AbstractRGB}(mapi::ScaleSigned{C}, val::Real)\n x = clamppm(mapi.s*val)\n g = UFixed8(abs(x))\n ifelse(x >= 0, C(g, zero(UFixed8), g), C(zero(UFixed8), g, zero(UFixed8)))\nend\n\nclamppm(x::Real) = ifelse(x >= 0, min(x, one(x)), max(x, -one(x)))\n\n## ScaleAutoMinMax\n# Works only on whole arrays, not values\n\"\"\"\n`ScaleAutoMinMax(T)` constructs a `MapInfo` object that causes images\nto be dynamically scaled to their specific min/max values, using the\nsame algorithm for `ScaleMinMax`. When displaying a movie, the min/max\nwill be recalculated for each frame, so this can result in\ninconsistent contrast scaling.\n\"\"\"\nimmutable ScaleAutoMinMax{T} <: MapInfo{T} end\nScaleAutoMinMax{T}(::Type{T}) = ScaleAutoMinMax{T}()\nScaleAutoMinMax() = ScaleAutoMinMax{UFixed8}()\n\nsimilar{T}(mapi::ScaleAutoMinMax, ::Type{T}, ::Type) = ScaleAutoMinMax{T}()\n\n## NaN-nulling mapping\n\"\"\"\n`ScaleMinMaxNaN(smm)` constructs a `MapInfo` object from a\n`ScaleMinMax` object `smm`, with the additional property that `NaN`\nvalues map to zero.\n\nSee also: `ScaleMinMax`.\n\"\"\"\nimmutable ScaleMinMaxNaN{To,From,S} <: MapInfo{To}\n smm::ScaleMinMax{To,From,S}\nend\n\n\"\"\"\n`Clamp01NaN(T)` or `Clamp01NaN(img)` constructs a `MapInfo` object\nthat clamps grayscale or color pixels to the interval `[0,1]`, sending\n`NaN` pixels to zero.\n\"\"\"\nimmutable Clamp01NaN{T} <: MapInfo{T} end\n\nClamp01NaN{T}(A::AbstractArray{T}) = Clamp01NaN{T}()\n\n# Implementation\nsimilar{T,F,To,From,S}(mapi::ScaleMinMaxNaN{To,From,S}, ::Type{T}, ::Type{F}) = ScaleMinMaxNaN{T,F,S}(similar(mapi.smm, T, F))\nsimilar{T}(mapi::Clamp01NaN, ::Type{T}, ::Type) = Clamp01NaN{T}()\n\nBase.map{To}(smmn::ScaleMinMaxNaN{To}, g::Number) = isnan(g) ? zero(To) : map(smmn.smm, g)\nBase.map{To}(smmn::ScaleMinMaxNaN{To}, g::Gray) = isnan(g) ? zero(To) : map(smmn.smm, g)\n\nfunction Base.map{T<:RGB}(::Clamp01NaN{T}, c::AbstractRGB)\n r, g, b = red(c), green(c), blue(c)\n if isnan(r) || isnan(g) || isnan(b)\n return T(0,0,0)\n end\n T(clamp(r, 0, 1), clamp(g, 0, 1), clamp(b, 0, 1))\nend\nfunction Base.map{T<:Union{Fractional,Gray}}(::Clamp01NaN{T}, c::Union{Fractional,AbstractGray})\n g = gray(c)\n if isnan(g)\n return T(0)\n end\n T(clamp(g, 0, 1))\nend\n\n# Conversions to RGB{T}, RGBA{T}, RGB24, ARGB32,\n# for grayscale, AbstractRGB, and abstract ARGB inputs.\n# This essentially \"vectorizes\" map over a single pixel's color channels using map1\nfor SI in (MapInfo, AbstractClamp)\n for ST in subtypes(SI)\n ST.abstract && continue\n ST == ScaleSigned && continue # ScaleSigned gives an RGB from a scalar, so don't \"vectorize\" it\n @eval begin\n # Grayscale and GrayAlpha inputs\n map(mapi::$ST{RGB24}, g::Gray) = map(mapi, g.val)\n map(mapi::$ST{RGB24}, g::Real) = (x = map1(mapi, g); convert(RGB24, RGB{UFixed8}(x,x,x)))\n function map(mapi::$ST{RGB24}, g::AbstractFloat)\n if isfinite(g)\n x = map1(mapi, g)\n convert(RGB24, RGB{UFixed8}(x,x,x))\n else\n RGB24(0)\n end\n end\n map{G<:Gray}(mapi::$ST{RGB24}, g::TransparentColor{G}) = map(mapi, gray(g))\n map(mapi::$ST{ARGB32}, g::Gray) = map(mapi, g.val)\n function map(mapi::$ST{ARGB32}, g::Real)\n x = map1(mapi, g)\n convert(ARGB32, ARGB{UFixed8}(x,x,x,0xffuf8))\n end\n function map{G<:Gray}(mapi::$ST{ARGB32}, g::TransparentColor{G})\n x = map1(mapi, gray(g))\n convert(ARGB32, ARGB{UFixed8}(x,x,x,map1(mapi, g.alpha)))\n end\n end\n for O in (:RGB, :BGR)\n @eval begin\n map{T}(mapi::$ST{$O{T}}, g::Gray) = map(mapi, g.val)\n function map{T}(mapi::$ST{$O{T}}, g::Real)\n x = map1(mapi, g)\n $O{T}(x,x,x)\n end\n end\n end\n for OA in (:RGBA, :ARGB, :BGRA)\n exAlphaGray = ST == MapNone ? :nothing : quote\n function map{T,G<:Gray}(mapi::$ST{$OA{T}}, g::TransparentColor{G})\n x = map1(mapi, gray(g))\n $OA{T}(x,x,x,map1(mapi, g.alpha))\n end # avoids an ambiguity warning with MapNone definitions\n end\n @eval begin\n map{T}(mapi::$ST{$OA{T}}, g::Gray) = map(mapi, g.val)\n function map{T}(mapi::$ST{$OA{T}}, g::Real)\n x = map1(mapi, g)\n $OA{T}(x,x,x)\n end\n $exAlphaGray\n end\n end\n @eval begin\n # AbstractRGB and abstract ARGB inputs\n map(mapi::$ST{RGB24}, rgb::AbstractRGB) =\n convert(RGB24, RGB{UFixed8}(map1(mapi, red(rgb)), map1(mapi, green(rgb)), map1(mapi, blue(rgb))))\n map{C<:AbstractRGB, TC}(mapi::$ST{RGB24}, argb::TransparentColor{C,TC}) =\n convert(RGB24, RGB{UFixed8}(map1(mapi, red(argb)), map1(mapi, green(argb)),\n map1(mapi, blue(argb))))\n map{C<:AbstractRGB, TC}(mapi::$ST{ARGB32}, argb::TransparentColor{C,TC}) =\n convert(ARGB32, ARGB{UFixed8}(map1(mapi, red(argb)), map1(mapi, green(argb)),\n map1(mapi, blue(argb)), map1(mapi, alpha(argb))))\n map(mapi::$ST{ARGB32}, rgb::AbstractRGB) =\n convert(ARGB32, ARGB{UFixed8}(map1(mapi, red(rgb)), map1(mapi, green(rgb)), map1(mapi, blue(rgb))))\n end\n for O in (:RGB, :BGR)\n @eval begin\n map{T}(mapi::$ST{$O{T}}, rgb::AbstractRGB) =\n $O{T}(map1(mapi, red(rgb)), map1(mapi, green(rgb)), map1(mapi, blue(rgb)))\n map{T,C<:AbstractRGB, TC}(mapi::$ST{$O{T}}, argb::TransparentColor{C,TC}) =\n $O{T}(map1(mapi, red(argb)), map1(mapi, green(argb)), map1(mapi, blue(argb)))\n end\n end\n for OA in (:RGBA, :ARGB, :BGRA)\n @eval begin\n map{T, C<:AbstractRGB, TC}(mapi::$ST{$OA{T}}, argb::TransparentColor{C,TC}) =\n $OA{T}(map1(mapi, red(argb)), map1(mapi, green(argb)),\n map1(mapi, blue(argb)), map1(mapi, alpha(argb)))\n map{T}(mapi::$ST{$OA{T}}, argb::ARGB32) = map(mapi, convert(RGBA{UFixed8}, argb))\n map{T}(mapi::$ST{$OA{T}}, rgb::AbstractRGB) =\n $OA{T}(map1(mapi, red(rgb)), map1(mapi, green(rgb)), map1(mapi, blue(rgb)))\n map{T}(mapi::$ST{$OA{T}}, rgb::RGB24) = map(mapi, convert(RGB{UFixed8}, argb))\n end\n end\n end\nend\n\n# # Apply to any Colorant\n# map(f::Callable, x::Color) = f(x)\n# map(mapi, x::Color) = map(mapi, convert(RGB, x))\n# map{C<:Color, TC}(f::Callable, x::TransparentColor{C, TC}) = f(convert(ARGB, x))\n# map{C<:Color, TC}(mapi, x::TransparentColor{C, TC}) = map(mapi, convert(ARGB, x))\n\n## Fallback definitions of map() for array types\n\nfunction map{T}(mapi::MapInfo{T}, img::AbstractArray)\n out = similar(img, T)\n map!(mapi, out, img)\nend\n\nmap{C<:Colorant,R<:Real}(mapi::MapNone{C}, img::AbstractImageDirect{R}) = mapcd(mapi, img) # ambiguity resolution\nmap{C<:Colorant,R<:Real}(mapi::MapInfo{C}, img::AbstractImageDirect{R}) = mapcd(mapi, img)\nfunction mapcd{C<:Colorant,R<:Real}(mapi::MapInfo{C}, img::AbstractImageDirect{R})\n # For this case we have to check whether color is defined along an array axis\n cd = colordim(img)\n if cd > 0\n dims = setdiff(1:ndims(img), cd)\n out = similar(img, C, size(img)[dims])\n map!(mapi, out, img, TypeConst{cd})\n else\n out = similar(img, C)\n map!(mapi, out, img)\n end\n out # note this isn't type-stable\nend\n\nfunction map{T<:Colorant}(mapi::MapInfo{T}, img::AbstractImageIndexed)\n out = Image(Array(T, size(img)), properties(img))\n map!(mapi, out, img)\nend\n\nmap!{T,T1,T2,N}(mapi::MapInfo{T1}, out::AbstractArray{T,N}, img::AbstractArray{T2,N}) =\n _map_a!(mapi, out, img)\nfunction _map_a!{T,T1,T2,N}(mapi::MapInfo{T1}, out::AbstractArray{T,N}, img::AbstractArray{T2,N})\n mi = take(mapi, img)\n dimg = data(img)\n dout = data(out)\n size(dout) == size(dimg) || throw(DimensionMismatch())\n for I in eachindex(dout, dimg)\n @inbounds dout[I] = map(mi, dimg[I])\n end\n out\nend\n\ntake(mapi::MapInfo, img::AbstractArray) = mapi\ntake{T}(mapi::ScaleAutoMinMax{T}, img::AbstractArray) = ScaleMinMax(T, img)\n\n# Indexed images (colormaps)\nmap!{T,T1,N}(mapi::MapInfo{T}, out::AbstractArray{T,N}, img::AbstractImageIndexed{T1,N}) =\n _mapindx!(mapi, out, img)\nfunction _mapindx!{T,T1,N}(mapi::MapInfo{T}, out::AbstractArray{T,N}, img::AbstractImageIndexed{T1,N})\n dimg = data(img)\n dout = data(out)\n cmap = map(mapi, img.cmap)\n for I in eachindex(dout, dimg)\n @inbounds dout[I] = cmap[dimg[I]]\n end\n out\nend\n\n# For when color is encoded along dimension CD\n# NC is the number of color channels\n# This is a very flexible implementation: color can be stored along any dimension, and it handles conversions to\n# many different colorspace representations.\nfor (CT, NC) in ((Union{AbstractRGB,RGB24}, 3), (Union{RGBA,ARGB,ARGB32}, 4), (Union{AGray,GrayA,AGray32}, 2))\n for N = 1:4\n N1 = N+1\n @eval begin\nfunction map!{T<:$CT,T1,T2,CD}(mapi::MapInfo{T}, out::AbstractArray{T1,$N}, img::AbstractArray{T2,$N1}, ::Type{TypeConst{CD}})\n mi = take(mapi, img)\n dimg = data(img)\n dout = data(out)\n # Set up the index along the color axis\n # We really only need dimension CD, but this will suffice\n @nexprs $NC k->(@nexprs $N1 d->(j_k_d = k))\n # Loop over all the elements in the output, performing the conversion on each color component\n @nloops $N i dout d->(d(j_k_d = i_d)) : (@nexprs $NC k->(j_k_{d+1} = i_d))) begin\n @inbounds @nref($N, dout, i) = @ncall $NC T k->(map1(mi, @nref($N1, dimg, j_k)))\n end\n out\nend\n end\n end\nend\n\n\n#### MapInfo defaults\n# Each \"client\" can define its own methods. \"clients\" include UFixed,\n# RGB24/ARGB32, and ImageMagick\n\nconst bitshiftto8 = ((UFixed10, 2), (UFixed12, 4), (UFixed14, 6), (UFixed16, 8))\n\n# typealias GrayType{T<:Fractional} Union{T, Gray{T}}\ntypealias GrayArray{T<:Fractional} Union{AbstractArray{T}, AbstractArray{Gray{T}}}\n# note, though, that we need to override for AbstractImage in case the\n# \"colorspace\" property is defined differently\n\n# mapinfo{T<:Union{Real,Colorant}}(::Type{T}, img::AbstractArray{T}) = MapNone(img)\n\"\"\"\n`mapi = mapinf(T, img)` returns a `MapInfo` object that is deemed\nappropriate for converting pixels of `img` to be of type `T`. `T` can\neither be a specific type (e.g., `RGB24`), or you can specify an\nabstract type like `Clamp` and it will return one of the `Clamp`\nfamily of `MapInfo` objects.\n\nYou can define your own rules for `mapinfo`. For example, the\n`ImageMagick` package defines methods for how pixels values should be\nconverted before saving images to disk.\n\"\"\"\nmapinfo{T<:UFixed}(::Type{T}, img::AbstractArray{T}) = MapNone(img)\nmapinfo{T<:AbstractFloat}(::Type{T}, img::AbstractArray{T}) = MapNone(img)\n\n# Grayscale methods\nmapinfo(::Type{UFixed8}, img::GrayArray{UFixed8}) = MapNone{UFixed8}()\nmapinfo(::Type{Gray{UFixed8}}, img::GrayArray{UFixed8}) = MapNone{Gray{UFixed8}}()\nmapinfo(::Type{GrayA{UFixed8}}, img::AbstractArray{GrayA{UFixed8}}) = MapNone{GrayA{UFixed8}}()\nfor (T,n) in bitshiftto8\n @eval mapinfo(::Type{UFixed8}, img::GrayArray{$T}) = BitShift{UFixed8,$n}()\n @eval mapinfo(::Type{Gray{UFixed8}}, img::GrayArray{$T}) = BitShift{Gray{UFixed8},$n}()\n @eval mapinfo(::Type{GrayA{UFixed8}}, img::AbstractArray{GrayA{$T}}) = BitShift{GrayA{UFixed8},$n}()\nend\nmapinfo{T<:UFixed,F<:AbstractFloat}(::Type{T}, img::GrayArray{F}) = ClampMinMax(T, zero(F), one(F))\nmapinfo{T<:UFixed,F<:AbstractFloat}(::Type{Gray{T}}, img::GrayArray{F}) = ClampMinMax(Gray{T}, zero(F), one(F))\nmapinfo{T<:AbstractFloat, R<:Real}(::Type{T}, img::AbstractArray{R}) = MapNone(T)\n\nmapinfo(::Type{RGB24}, img::Union{AbstractArray{Bool}, BitArray}) = MapNone{RGB24}()\nmapinfo(::Type{ARGB32}, img::Union{AbstractArray{Bool}, BitArray}) = MapNone{ARGB32}()\nmapinfo{F<:Fractional}(::Type{RGB24}, img::GrayArray{F}) = ClampMinMax(RGB24, zero(F), one(F))\nmapinfo{F<:Fractional}(::Type{ARGB32}, img::AbstractArray{F}) = ClampMinMax(ARGB32, zero(F), one(F))\n\n# Color->Color methods\nmapinfo(::Type{RGB{UFixed8}}, img) = MapNone{RGB{UFixed8}}()\nmapinfo(::Type{RGBA{UFixed8}}, img) = MapNone{RGBA{UFixed8}}()\nfor (T,n) in bitshiftto8\n @eval mapinfo(::Type{RGB{UFixed8}}, img::AbstractArray{RGB{$T}}) = BitShift{RGB{UFixed8},$n}()\n @eval mapinfo(::Type{RGBA{UFixed8}}, img::AbstractArray{RGBA{$T}}) = BitShift{RGBA{UFixed8},$n}()\nend\nmapinfo{F<:Fractional}(::Type{RGB{UFixed8}}, img::AbstractArray{RGB{F}}) = Clamp(RGB{UFixed8})\nmapinfo{F<:Fractional}(::Type{RGBA{UFixed8}}, img::AbstractArray{RGBA{F}}) = Clamp(RGBA{UFixed8})\n\n\n\n# Color->RGB24/ARGB32\nmapinfo(::Type{RGB24}, img::AbstractArray{RGB24}) = MapNone{RGB24}()\nmapinfo(::Type{ARGB32}, img::AbstractArray{ARGB32}) = MapNone{ARGB32}()\nfor C in tuple(subtypes(AbstractRGB)..., Gray)\n C == RGB24 && continue\n @eval mapinfo(::Type{RGB24}, img::AbstractArray{$C{UFixed8}}) = MapNone{RGB24}()\n @eval mapinfo(::Type{ARGB32}, img::AbstractArray{$C{UFixed8}}) = MapNone{ARGB32}()\n for (T, n) in bitshiftto8\n @eval mapinfo(::Type{RGB24}, img::AbstractArray{$C{$T}}) = BitShift{RGB24, $n}()\n @eval mapinfo(::Type{ARGB32}, img::AbstractArray{$C{$T}}) = BitShift{ARGB32, $n}()\n end\n @eval mapinfo{F<:AbstractFloat}(::Type{RGB24}, img::AbstractArray{$C{F}}) = ClampMinMax(RGB24, zero(F), one(F))\n @eval mapinfo{F<:AbstractFloat}(::Type{ARGB32}, img::AbstractArray{$C{F}}) = ClampMinMax(ARGB32, zero(F), one(F))\n for AC in subtypes(TransparentColor)\n length(AC.parameters) == 2 || continue\n @eval mapinfo(::Type{ARGB32}, img::AbstractArray{$AC{$C{UFixed8},UFixed8}}) = MapNone{ARGB32}()\n @eval mapinfo(::Type{RGB24}, img::AbstractArray{$AC{$C{UFixed8},UFixed8}}) = MapNone{RGB24}()\n for (T, n) in bitshiftto8\n @eval mapinfo(::Type{ARGB32}, img::AbstractArray{$AC{$C{$T},$T}}) = BitShift{ARGB32, $n}()\n @eval mapinfo(::Type{RGB24}, img::AbstractArray{$AC{$C{$T},$T}}) = BitShift{RGB24, $n}()\n end\n @eval mapinfo{F<:AbstractFloat}(::Type{ARGB32}, img::AbstractArray{$AC{$C{F},F}}) = ClampMinMax(ARGB32, zero(F), one(F))\n @eval mapinfo{F<:AbstractFloat}(::Type{RGB24}, img::AbstractArray{$AC{$C{F},F}}) = ClampMinMax(RGB24, zero(F), one(F))\n end\nend\n\nmapinfo{CT<:Colorant}(::Type{RGB24}, img::AbstractArray{CT}) = MapNone{RGB24}()\nmapinfo{CT<:Colorant}(::Type{ARGB32}, img::AbstractArray{CT}) = MapNone{ARGB32}()\n\n\n# UInt32 conversions will use ARGB32 for images that have an alpha channel,\n# and RGB24 when not\nmapinfo{CV<:Union{Fractional,Color,AbstractGray}}(::Type{UInt32}, img::AbstractArray{CV}) = mapinfo(RGB24, img)\nmapinfo{CV<:TransparentColor}(::Type{UInt32}, img::AbstractArray{CV}) = mapinfo(ARGB32, img)\nmapinfo(::Type{UInt32}, img::Union{AbstractArray{Bool},BitArray}) = mapinfo(RGB24, img)\nmapinfo(::Type{UInt32}, img::AbstractArray{UInt32}) = MapNone{UInt32}()\n\n\n# Clamping mapinfo client. Converts to RGB and uses UFixed, clamping\n# floating-point values to [0,1].\nmapinfo{T<:UFixed}(::Type{Clamp}, img::AbstractArray{T}) = MapNone{T}()\nmapinfo{T<:AbstractFloat}(::Type{Clamp}, img::AbstractArray{T}) = ClampMinMax(UFixed8, zero(T), one(T))\nlet handled = Set()\nfor ACV in (Color, AbstractRGB)\n for CV in subtypes(ACV)\n (length(CV.parameters) == 1 && !(CV.abstract)) || continue\n CVnew = CV<:AbstractGray ? Gray : RGB\n @eval mapinfo{T<:UFixed}(::Type{Clamp}, img::AbstractArray{$CV{T}}) = MapNone{$CVnew{T}}()\n @eval mapinfo{CV<:$CV}(::Type{Clamp}, img::AbstractArray{CV}) = Clamp{$CVnew{UFixed8}}()\n CVnew = CV<:AbstractGray ? Gray : BGR\n AC, CA = alphacolor(CV), coloralpha(CV)\n if AC in handled\n continue\n end\n push!(handled, AC)\n ACnew, CAnew = alphacolor(CVnew), coloralpha(CVnew)\n @eval begin\n mapinfo{T<:UFixed}(::Type{Clamp}, img::AbstractArray{$AC{T}}) = MapNone{$ACnew{T}}()\n mapinfo{P<:$AC}(::Type{Clamp}, img::AbstractArray{P}) = Clamp{$ACnew{UFixed8}}()\n mapinfo{T<:UFixed}(::Type{Clamp}, img::AbstractArray{$CA{T}}) = MapNone{$CAnew{T}}()\n mapinfo{P<:$CA}(::Type{Clamp}, img::AbstractArray{P}) = Clamp{$CAnew{UFixed8}}()\n end\n end\nend\nend\nmapinfo(::Type{Clamp}, img::AbstractArray{RGB24}) = MapNone{RGB{UFixed8}}()\nmapinfo(::Type{Clamp}, img::AbstractArray{ARGB32}) = MapNone{BGRA{UFixed8}}()\n\n\n# Backwards-compatibility\nuint32color(img) = map(mapinfo(UInt32, img), img)\nuint32color!(buf, img::AbstractArray) = map!(mapinfo(UInt32, img), buf, img)\nuint32color!(buf, img::AbstractArray, mi::MapInfo) = map!(mi, buf, img)\nuint32color!{T,N}(buf::Array{UInt32,N}, img::AbstractImageDirect{T,N}) =\n map!(mapinfo(UInt32, img), buf, img)\nuint32color!{T,N,N1}(buf::Array{UInt32,N}, img::AbstractImageDirect{T,N1}) =\n map!(mapinfo(UInt32, img), buf, img, TypeConst{colordim(img)})\nuint32color!{T,N}(buf::Array{UInt32,N}, img::AbstractImageDirect{T,N}, mi::MapInfo) =\n map!(mi, buf, img)\nuint32color!{T,N,N1}(buf::Array{UInt32,N}, img::AbstractImageDirect{T,N1}, mi::MapInfo) =\n map!(mi, buf, img, TypeConst{colordim(img)})\n\n\"\"\"\n```\nimgsc = sc(img)\nimgsc = sc(img, min, max)\n```\n\nApplies default or specified `ScaleMinMax` mapping to the image.\n\"\"\"\nsc(img::AbstractArray) = map(ScaleMinMax(UFixed8, img), img)\nsc(img::AbstractArray, mn::Real, mx::Real) = map(ScaleMinMax(UFixed8, img, mn, mx), img)\n\nfor (fn,T) in ((:float32, Float32), (:float64, Float64), (:ufixed8, UFixed8),\n (:ufixed10, UFixed10), (:ufixed12, UFixed12), (:ufixed14, UFixed14),\n (:ufixed16, UFixed16))\n @eval begin\n function $fn{C<:Colorant}(A::AbstractArray{C})\n newC = eval(C.name.name){$T}\n convert(Array{newC}, A)\n end\n $fn{C<:Colorant}(img::AbstractImage{C}) = shareproperties(img, $fn(data(img)))\n end\nend\n\n\nufixedsc{T<:UFixed}(::Type{T}, img::AbstractImageDirect) = map(mapinfo(T, img), img)\nufixed8sc(img::AbstractImageDirect) = ufixedsc(UFixed8, img)\n", "meta": {"hexsha": "1b65412f52fb34d3e52492e151f6e6277d3b9542", "size": 32574, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/map.jl", "max_stars_repo_name": "rsrock/Images.jl", "max_stars_repo_head_hexsha": "8e4192a04c45be0f93f8b13b189249ed93f394c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/map.jl", "max_issues_repo_name": "rsrock/Images.jl", "max_issues_repo_head_hexsha": "8e4192a04c45be0f93f8b13b189249ed93f394c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/map.jl", "max_forks_repo_name": "rsrock/Images.jl", "max_forks_repo_head_hexsha": "8e4192a04c45be0f93f8b13b189249ed93f394c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.5342857143, "max_line_length": 253, "alphanum_fraction": 0.6518388899, "num_tokens": 10646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828341018881344, "lm_q2_score": 0.11920292045759122, "lm_q1q2_score": 0.058204808505498515}} {"text": "## CPItree.jl - Tipos y métodos para operar la estructura jerárquica del IPC\n\n## ----------------------------------------------------------------------------\n# Main type definitions\n# ----------------------------------------------------------------------------\n\n\"\"\"\n Item{T}(code::String, name::String, weight::T<:AbstractFloat)\n\nRepresenta un gasto básico en la estructura de nodos del IPC. Es el nivel más\nbajo de la estructura. Almacena el código del gasto básico, su nombre o\ndescripción y su ponderación en el IPC. Los datos de este nodo deben estar\ndisponibles en algún [`FullCPIBase`](@ref). \n\nPosee los campos: \n- `code`: que almacena el código del gasto básico como un `String`.\n- `name`: que almacena el nombre del gasto básico como un `String`.\n- `weight::T`: que almacena la ponderación del gasto básico como un valor\n flotante de tipo `T`.\n\nAunque este nodo será usualmente creado de manera automática por métodos como\n[`CPITree`](@ref), se pueden crear estructuras jerárquicas manualmente. Por\nejemplo, para crear un nodo del nivel inferior: \n```julia-repl\njulia> Item(\"_011101\", \"Item A\", 7.352945f0)\nItem{Float32}(\"_011101\", \"Item A\", 7.352945f0)\n```\n\nVer también: [`Group`](@ref), [`CPITree`](@ref).\n\"\"\"\nstruct Item{T}\n code::String\n name::String\n weight::T\nend\n\n\"\"\"\n Group{S,T}\n\n Group(code, name, children::Vector{S}) where S\n Group(code, name, children...) \n\nRepresenta un nodo de agrupación de cualquier nivel en la estructura de nodos\ndel IPC. Puede almacenar gastos básicos u otros grupos de mayor jerarquía.\nAlmacena el código del grupo, su nombre o descripción y su ponderación en el\nIPC. \n\nPosee los campos: \n- `code`: almacena el código del grupo como un `String`.\n- `name`: almacena el nombre del grupo como un `String`.\n- `weight::T`: almacena la ponderación del grupo como un valor flotante de tipo\n `T`.\n- `children::Vector{S}`: almacena el vector de nodos \"hijos\" de la estructura.\n Por ejemplo, este vector podría ser un vector de elementos `Item` para agrupar\n un conjunto de gastos básicos.\n\nAunque este nodo será usualmente creado de manera automática por métodos como\n[`CPITree`](@ref), se pueden crear estructuras jerárquicas manualmente. Por\nejemplo, para crear un grupo: \n```julia-repl\njulia> a = Item(\"_011201\", \"Item B\", 6.7442417f0)\nItem{Float32}(\"_011201\", \"Item B\", 6.7442417f0)\n\njulia> b = Item(\"_011202\", \"Item C\", 7.394718f0)\nItem{Float32}(\"_011202\", \"Item C\", 7.394718f0)\n\njulia> g = Group(\"_0112\", \"Subgr._0112\", a, b)\nGroup{Item{Float32}, Float32}\n_0112: Subgr._0112 [14.13896] \n├─ _011201: Item B [6.7442417]\n└─ _011202: Item C [7.394718]\n```\n\nVer también: [`Item`](@ref), [`CPITree`](@ref).\n\"\"\"\nstruct Group{S,T}\n code::String\n name::String\n weight::T\n children::Vector{S}\n\n function Group(code, name, children...)\n sum_weights = sum(child.weight for child in children)\n T = eltype(sum_weights)\n S = eltype(children)\n new{S,T}(code, name, sum_weights, S[children...])\n end\n Group(code, name, children::Vector{S}) where {S} = Group(code, name, children...)\nend\n\n# Redefine methods for getting children\nchildren(::Item) = ()\nchildren(g::Group) = g.children\n\n# Redefine how to print a node in the print_tree function \nprintnode(io::IO, g::Item) = print(io, g.code * \": \" * g.name * \" [\" * string(g.weight) * \"] \")\nprintnode(io::IO, g::Group) = print(io, g.code * \": \" * g.name * \" [\" * string(g.weight) * \"] \")\n\n# How to show a Group\nfunction Base.show(io::IO, g::Group)\n println(io, typeof(g)) \n print_tree(io, g)\nend\n\n\n## ----------------------------------------------------------------------------\n# CPI tree functions \n# ----------------------------------------------------------------------------\n\n\"\"\"\n cpi_tree_nodes(codes::Vector{<:AbstractString}; \n characters::(NTuple{N, Int} where N), depth::Int=1, chars::Int=characters[depth], prefix::AbstractString=\"\", \n base::FullCPIBase, \n group_names::Vector{<:AbstractString}, \n group_codes::Vector{<:AbstractString})\n\nConstruye y devuelve una lista de nodos a partir de la lista de códigos `codes`\no de la especificación jerárquica de caracteres en `characters`. Los nombres y\nlas ponderaciones del nivel inferior (nivel de gasto básico) son\nobtenidas de la estructura `base`. Se debe proveer el vector de códigos y\nnombres de todas las jerarquías superiores en la estructura de códigos en los\nvectores `group_names` y `group_codes`.\n\nEsta función permite crear únicamente la estructura jerárquica de nodos. Para construir de manera automática una estructura del IPC, se recomienda utilizar preferentemente [`CPITree`](@ref).\n\nVea también: [`CPITree`](@ref).\n\"\"\"\nfunction cpi_tree_nodes(codes::Vector{<:AbstractString}; \n characters::(NTuple{N, Int} where N), depth::Int=1, chars::Int=characters[depth], prefix::AbstractString=\"\", \n base::FullCPIBase, \n group_names::Vector{<:AbstractString}, \n group_codes::Vector{<:AbstractString})\n \n # Get available starting codes \n available = filter(code -> startswith(code, prefix), codes)\n \n # Base case: \n # If code length is the last available then we reached a leaf node\n if chars == last(characters)\n # With available codes construct leaf CPI nodes\n children = map(available) do code\n # Find the code index \n icode = findfirst(==(code), codes)\n Item(code, base.names[icode], base.w[icode])\n end\n return children\n end\n\n # Get possible prefixes values from the available list. Possible prefixes\n # are the ones from the beginning of the string to the number of chars,\n # which depends on the depth we are on.\n possibles = unique(getindex.(available, Ref(1:chars)))\n\n # For each available code, call the function itself with the next downward hierarchy\n groups = map(possibles) do prefixcode\n # Go get the children in the next downward level\n children = cpi_tree_nodes(codes; \n characters, depth=depth+1, prefix=prefixcode,\n base, group_names, group_codes\n )\n # Get the group name \n @debug \"Prefix code:\" prefixcode\n i = findfirst(==(prefixcode), group_codes)\n if i === nothing \n @warn \"Código de grupo para $(prefixcode) no encontrado en `group_codes`. Utilizando nombre genérico.\"\n gname = \"Group: $prefixcode\"\n else\n gname = group_names[i]\n end\n # With the children create a group \n group = Group(prefixcode, gname, children)\n group\n end\n\n # Return the group for the upward parents\n return groups\nend\n\n\"\"\"\n get_cpi_tree(; \n base::FullCPIBase, \n group_names::Vector{<:AbstractString}, \n group_codes::Vector{<:AbstractString}, \n characters::(NTuple{N, Int} where N),\n upperlevel_code = \"_0\", \n upperlevel_name = \"IPC\")\n\nFunción superior para obtener estructura jerárquica del IPC. Devuelve el nodo\nsuperior del árbol jerárquico. Utiliza la función de más bajo nivel\n`cpi_tree_nodes` para construir los nodos del nivel más alto y hacia abajo en la\nestructura jerárquica. Se debe proveer el vector de códigos y nombres de todas\nlas jerarquías superiores en la estructura de códigos en los vectores\n`group_names` y `group_codes`. \n\nEsta función permite crear únicamente la estructura jerárquica de nodos. Para construir de manera automática una estructura del IPC, se recomienda utilizar preferentemente [`CPITree`](@ref).\n\nVea también: [`CPITree`](@ref).\n\"\"\"\nfunction get_cpi_tree(; \n base::FullCPIBase, \n group_names::Vector{<:AbstractString}, \n group_codes::Vector{<:AbstractString}, \n characters::(NTuple{N, Int} where N),\n upperlevel_code = \"_0\", \n upperlevel_name = \"IPC\")\n\n length(characters) >= 2 || throw(ArgumentError(\"`characters` debe ser una tupla con al menos dos valores\"))\n for i in 2:length(characters)\n characters[i] > characters[i-1] || throw(ArgumentError(\"Valores en `characters` deben ser ascendentes hasta el largo de los códigos en base\"))\n end\n # Get the codes list from the FullCPIBase object\n codes = base.codes\n @debug \"Codes:\" codes\n\n # Call lower level tree building function\n upper_nodes = cpi_tree_nodes(codes; characters, base, group_names, group_codes)\n \n # Build upper level tree node\n tree = Group(upperlevel_code, upperlevel_name, upper_nodes)\n tree\nend\n\n\n## Build functions to find the inner tree of a given code\nfunction find_tree(code, tree::Item) \n code == tree.code && return tree \n nothing\nend\n\nfunction find_tree(code, tree::Group)\n # Most basic case: the code is the same as the tree in which to search \n code == tree.code && return tree\n\n # Search in the tree's nodes \n for child in tree.children\n # If code searched is one of the children, return the child\n code == child.code && return child\n\n # Look if the code starts the same as the child's code, i.e the code\n # contains the child's code. If so, find in the inner tree and break out\n # of this level's search\n contains(code, child.code) && return find_tree(code, child)\n end\n\n # Code not found at any level\n nothing\nend\n\n# Redefine getindex to search for specific nodes within the tree\nBase.getindex(tree::Union{Item, Group}, code::AbstractString) = find_tree(code, tree)\n\n\n\n\n## ----------------------------------------------------------------------------\n# Functions to compute any code's price index from the lower level data\n# ----------------------------------------------------------------------------\n\n# Basic case: compute index of an Item, which is stored in the `base` structure\nfunction compute_index(good::Item, base::FullCPIBase)\n i = findfirst(==(good.code), base.codes)\n # Maybe add a warning here if code not found\n base.ipc[:, i]\nend\n\n# Recursive function to compute inner price indexes for groups\nfunction compute_index(group, base::FullCPIBase)\n # Get the indexes of the children. At the lowest level the dispatch will\n # select compute_index(::Item, ::FullCPIBase) to return the Goods indices\n ipcs = mapreduce(c -> compute_index(c, base), hcat, group.children)\n\n # If there exists only one good in the group, that is the group's index\n size(ipcs, 2) == 1 && return ipcs\n \n # Get the weights\n weights = map(c -> c.weight, group.children) \n\n # Return normalized sum product \n ipcs * weights / sum(weights)\nend\n\n# Edge case called when searching for a node that doest not exist. For example,\n# if called compute_index(tree[\"_0101101\"], base) and node with code \"_0101101\"\n# does not exist, returns nothing and raises a warning\nfunction compute_index(::Nothing, ::FullCPIBase)\n @warn \"Nodo no disponible en la estructura\"\n nothing \nend\n\n\n## ----------------------------------------------------------------------------\n# In-place functions to compute any code's price index from the lower level data\n# ----------------------------------------------------------------------------\n\nfunction compute_index!(cache::Dict, good::Item, base::FullCPIBase)\n i = findfirst(==(good.code), base.codes)\n cache[good.code] = base.ipc[:, i] # save a copy in the cache\n cache[good.code]\nend\n\nfunction compute_index!(cache::Dict, group::Group, base::FullCPIBase)\n # If code is available in cache, just return it\n group.code in keys(cache) && return cache[group.code]\n\n # Else, compute the index and store it \n # Get the indexes of the children. At the lowest level the dispatch will\n # select compute_index(::Item, ::FullCPIBase) to return the Goods indices\n ipcs = mapreduce(c -> compute_index!(cache, c, base), hcat, group.children)\n\n # If there exists only one good in the group, that is the group's index\n if size(ipcs, 2) == 1 \n cache[group.code] = ipcs \n return ipcs\n end\n \n # Get the weights\n weights = map(c -> c.weight, group.children) \n\n # Store normalized sum product \n cache[group.code] = ipcs * weights / sum(weights)\n cache[group.code]\nend\n\nfunction compute_index!(::Dict, ::Nothing, ::FullCPIBase)\n @warn \"Nodo no disponible en la estructura\"\n nothing \nend\n\n\n## ----------------------------------------------------------------------------\n# CPITree: estructura contenedora del árbol jerárquico y los datos necesarios\n# para computar cualquier nodo en la estructura del IPC.\n# ----------------------------------------------------------------------------\n\n\"\"\"\n CPITree\n\n CPITree(base::FullCPIBase, tree::Union{Group, Item}, group_names::Vector{String}, group_codes::Vector{String})\n CPITree(; base::FullCPIBase, groupsdf::DataFrame, characters::(NTuple{N, Int} where N), upperlevel_code = \"_0\", upperlevel_name = \"IPC\")\n\nContenedor envolvente de un árbol jerárquico del IPC y los datos necesarios de\nlos gastos básicos para computar cualquier jerarquía dentro del árbol. Permite\nvisualizar y explorar la composición del IPC de un país, así como computar los\níndices de precios de las diferentes jerarquías de la estructura del IPC. Está\ncompuesto por: \n- Un objeto `base`, de tipo [`FullCPIBase`](@ref), el cual almacena las series\n de tiempo de los índices de los gastos básicos. \n- Un objeto `tree` que contiene la estructura de nodos del IPC.\n- El vector de nombres `group_names` de los grupos del árbol `tree`.\n- El vector de códigos `group_codes` de los grupos del árbol `tree`.\n\nEl constructor simple requiere una estructura jerárquica de nodos como la\ndevuelta por [`get_cpi_tree`](@ref). Al utilizar el constructor con `groupsdf` y\n`characters`, se construye automáticamente un `CPITree` utilizando los códigos\ncomo indicadores de la estructura jerárquica. Los códigos de los gastos básicos\ncontenidos en `base` describen cómo se agrupan las jerarquías. Por ejemplo, el\nsiguiente `FullCPIBase` contiene 10 gastos básicos: \n```julia-repl\njulia> base\nFullCPIBase{Float32, Float32}: 36 períodos × 10 gastos básicos Jan-01-Dec-03\n┌─────┬────────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┐\n│ Row │ Dates │ _011101 │ _011201 │ _011202 │ _021101 │ _022101 │ _031101 │ _041101 │ _041201 │ _041202 │ _041301 │\n│ │ │ Item A │ Item B │ Item C │ Item D │ Item E │ Item F │ Item G │ Item H │ Item I │ Item J │\n│ │ │ 11.8947 │ 2.39931 │ 7.80836 │ 1.58585 │ 20.141 │ 12.0526 │ 9.56901 │ 14.6256 │ 15.0276 │ 4.89602 │\n├─────┼────────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┤\n│ 1 │ 2001-01-01 │ 100.00 │ 100.00 │ 100.00 │ 100.00 │ 100.00 │ 101.13 │ 100.00 │ 100.00 │ 100.51 │ 100.00 │\n│ 2 │ 2001-02-01 │ 100.00 │ 100.00 │ 100.00 │ 100.00 │ 100.00 │ 102.28 │ 100.00 │ 100.00 │ 101.02 │ 100.00 │\n│ 3 │ 2001-03-01 │ 100.00 │ 100.00 │ 100.00 │ 100.00 │ 100.00 │ 103.44 │ 100.00 │ 100.00 │ 101.53 │ 100.00 │\n│ 4 │ 2001-04-01 │ 100.00 │ 100.00 │ 100.00 │ 100.00 │ 100.00 │ 104.61 │ 100.00 │ 100.00 │ 102.05 │ 100.00 │\n│ 5 │ 2001-05-01 │ 100.00 │ 100.00 │ 100.00 │ 100.00 │ 100.00 │ 105.79 │ 100.00 │ 100.00 │ 102.56 │ 100.00 │\n│ ⋮ │ ⋮ │ ⋮ │ ⋮ │ ⋮ │ ⋮ │ ⋮ │ ⋮ │ ⋮ │ ⋮ │ ⋮ │ ⋮ │\n│ 32 │ 2003-08-01 │ 100.00 │ 100.00 │ 100.00 │ 100.00 │ 100.00 │ 143.39 │ 100.00 │ 100.00 │ 117.59 │ 100.00 │\n│ 33 │ 2003-09-01 │ 100.00 │ 100.00 │ 100.00 │ 100.00 │ 100.00 │ 145.02 │ 100.00 │ 100.00 │ 118.19 │ 100.00 │\n│ 34 │ 2003-10-01 │ 100.00 │ 100.00 │ 100.00 │ 100.00 │ 100.00 │ 146.66 │ 100.00 │ 100.00 │ 118.79 │ 100.00 │\n│ 35 │ 2003-11-01 │ 100.00 │ 100.00 │ 100.00 │ 100.00 │ 100.00 │ 148.32 │ 100.00 │ 100.00 │ 119.39 │ 100.00 │\n│ 36 │ 2003-12-01 │ 100.00 │ 100.00 │ 100.00 │ 100.00 │ 100.00 │ 150.00 │ 100.00 │ 100.00 │ 120.00 │ 100.00 │\n└─────┴────────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┘\n 26 rows omitted\n```\n\nEn este ejemplo, el argumento debe especificarse como `characters = (3, 4, 5,\n7)`, pues los códigos indican las jerarquías en el IPC de manera siguiente: \n- Los primeros 3 caracteres indican la jerarquía de *división de gasto*. \n- El siguiente caracter indica la jerarquía de *agrupación de gasto*. \n- El siguiente caracter indica la jerarquía de *subgrupo de gasto*. \n- Los siguientes 2 caracteres indican el *número de gasto básico dentro de su\n grupo*. \n\nPor su parte, el DataFrame `groupsdf` debe tener la estructura mínima siguiente: \n- La primera columna debe ser de tipo `String` y contiene los códigos de los\n grupos disponibles en la estructura del IPC. \n- La segunda columna debe ser de tipo `String` y contiene las descripciones o\nnombres de los grupos disponibles en la estructura del IPC. Por ejemplo, el\nDataFrame `groupsdf` puede verse de esta forma: \n```\n17×2 DataFrame\n Row │ code description \n │ String String \n─────┼─────────────────────\n 1 │ _01 Div._01\n 2 │ _02 Div._02\n 3 │ _03 Div._03\n 4 │ _04 Div._04\n 5 │ _011 Agr._011\n 6 │ _021 Agr._021\n 7 │ _022 Agr._022\n 8 │ _031 Agr._031\n 9 │ _041 Agr._041\n 10 │ _0111 Subgr._0111\n 11 │ _0112 Subgr._0112\n 12 │ _0211 Subgr._0211\n 13 │ _0221 Subgr._0221\n 14 │ _0311 Subgr._0311\n 15 │ _0411 Subgr._0411\n 16 │ _0412 Subgr._0412\n 17 │ _0413 Subgr._0413\n```\n\nPor ejemplo, al construir un `CPITree` con la estructura de códigos indicada anteriormente y el DataFrame de ejemplo, el árbol del IPC se puede ver de esta forma: \n```julia-repl\njulia> tree = CPITree(; base, groupsdf, characters=(3,4,5,7))\nCPITree{Group{Group{Group{Group{Item{Float32}, Float32}, Float32}, Float32}, Float32}} con datos\n└─→ FullCPIBase{Float32, Float32}: 36 períodos × 10 gastos básicos Jan-01-Dec-03\n_0: IPC [100.0]\n├─ _01: Div._01 [21.491905]\n│ └─ _011: Agr._011 [21.491905]\n│ ├─ _0111: Subgr._0111 [7.352945]\n│ │ └─ _011101: Item A [7.352945]\n│ └─ _0112: Subgr._0112 [14.13896]\n│ ├─ _011201: Item B [6.7442417]\n│ └─ _011202: Item C [7.394718]\n├─ _02: Div._02 [3.0530455]\n│ ├─ _021: Agr._021 [1.1036392]\n│ │ └─ _0211: Subgr._0211 [1.1036392]\n│ │ └─ _021101: Item D [1.1036392]\n│ └─ _022: Agr._022 [1.9494063]\n│ └─ _0221: Subgr._0221 [1.9494063]\n│ └─ _022101: Item E [1.9494063]\n├─ _03: Div._03 [11.68543]\n│ └─ _031: Agr._031 [11.68543]\n│ └─ _0311: Subgr._0311 [11.68543]\n│ └─ _031101: Item F [11.68543]\n└─ _04: Div._04 [63.769615]\n └─ _041: Agr._041 [63.769615]\n ├─ _0411: Subgr._0411 [16.103952]\n │ └─ _041101: Item G [16.103952]\n ├─ _0412: Subgr._0412 [28.824577]\n │ ├─ _041201: Item H [11.367162]\n │ └─ _041202: Item I [17.457417]\n └─ _0413: Subgr._0413 [18.841085]\n └─ _041301: Item J [18.841085]\n```\n\"\"\"\nstruct CPITree{G}\n base::FullCPIBase\n tree::G\n group_names::Vector{String}\n group_codes::Vector{String}\n function CPITree(base::FullCPIBase, tree::Union{Group, Item}, group_names::Vector{String}, group_codes::Vector{String})\n G = typeof(tree)\n new{G}(base, tree, group_names, group_codes)\n end\nend\n\nfunction CPITree(; \n base::FullCPIBase, \n groupsdf::DataFrame, \n characters::(NTuple{N, Int} where N),\n upperlevel_code = \"_0\", \n upperlevel_name = \"IPC\")\n\n # Obtener códigos y nombres de los grupos en las jerarquías\n group_codes = convert.(String, groupsdf[!, 1])\n group_names = groupsdf[!, 2]\n\n tree = get_cpi_tree(;\n base, \n characters,\n group_names, \n group_codes,\n upperlevel_code, \n upperlevel_name\n )\n\n CPITree(base, tree, group_names, group_codes)\nend\n\n\nfunction Base.show(io::IO, cpitree::CPITree)\n println(io, typeof(cpitree), \" con datos\")\n println(io, \"└─→ \", sprint(summary, cpitree.base)) \n print_tree(io, cpitree.tree)\nend\n\n\"\"\"\n Base.getindex(cpitree::CPITree, code::AbstractString)\n\nEste método se utiliza para indexar el árbol jerárquico `cpitree` y obtener una\nestructura similar cuyo nodo superior sea el nodo con el código provisto `code`. Por ejemplo, si tenemos el siguiente árbol: \n```julia-repl\njulia> tree\nCPITree{Group{Group{Group{Group{Item{Float32}, Float32}, Float32}, Float32}, Float32}} con datos\n└─→ FullCPIBase{Float32, Float32}: 36 períodos × 10 gastos básicos Jan-01-Dec-03\n_0: IPC [100.0]\n├─ _01: Div._01 [21.491905]\n│ └─ _011: Agr._011 [21.491905]\n│ ├─ _0111: Subgr._0111 [7.352945]\n│ │ └─ _011101: Item A [7.352945]\n│ └─ _0112: Subgr._0112 [14.13896]\n│ ├─ _011201: Item B [6.7442417]\n│ └─ _011202: Item C [7.394718]\n├─ _02: Div._02 [3.0530455]\n│ ├─ _021: Agr._021 [1.1036392] \n│ │ └─ _0211: Subgr._0211 [1.1036392]\n│ │ └─ _021101: Item D [1.1036392]\n│ └─ _022: Agr._022 [1.9494063]\n│ └─ _0221: Subgr._0221 [1.9494063]\n│ └─ _022101: Item E [1.9494063]\n├─ _03: Div._03 [11.68543]\n│ └─ _031: Agr._031 [11.68543]\n│ └─ _0311: Subgr._0311 [11.68543]\n│ └─ _031101: Item F [11.68543]\n└─ _04: Div._04 [63.769615]\n └─ _041: Agr._041 [63.769615]\n ├─ _0411: Subgr._0411 [16.103952]\n │ └─ _041101: Item G [16.103952]\n ├─ _0412: Subgr._0412 [28.824577]\n │ ├─ _041201: Item H [11.367162]\n │ └─ _041202: Item I [17.457417]\n └─ _0413: Subgr._0413 [18.841085]\n └─ _041301: Item J [18.841085]\n```\n\nAl indexar por un código, como `_041`, obtenemos una estructura similar a partir de ese nodo:\n```julia-repl\njulia> tree[\"_041\"]\nCPITree{Group{Group{Item{Float32}, Float32}, Float32}} con datos\n└─→ FullCPIBase{Float32, Float32}: 36 períodos × 10 gastos básicos Jan-01-Dec-03\n_041: Agr._041 [63.769615]\n├─ _0411: Subgr._0411 [16.103952]\n│ └─ _041101: Item G [16.103952] \n├─ _0412: Subgr._0412 [28.824577]\n│ ├─ _041201: Item H [11.367162]\n│ └─ _041202: Item I [17.457417]\n└─ _0413: Subgr._0413 [18.841085]\n └─ _041301: Item J [18.841085]\n```\n\"\"\"\nfunction Base.getindex(cpitree::CPITree, code::AbstractString) \n node = cpitree.tree[code]\n node === nothing && return nothing\n CPITree(cpitree.base, node, cpitree.group_names, cpitree.group_codes)\nend\n\n\"\"\"\n compute_index(cpitree::CPITree [, code::AbstractString])\n\nPermite computar el índice de precios de la jerarquía provista en `code`. Si se\nomite `code`, se computa la jerarquía padre de la estructura `cpitree`. Si el\nnodo no se encuentra en el árbol, devuelve `nothing`.\n\n```julia-repl\njulia> tree\nCPITree{Group{Group{Group{Group{Item{Float32}, Float32}, Float32}, Float32}, Float32}} con datos\n└─→ FullCPIBase{Float32, Float32}: 36 períodos × 10 gastos básicos Jan-01-Dec-03\n_0: IPC [100.0]\n├─ _01: Div._01 [21.491905]\n│ └─ _011: Agr._011 [21.491905]\n│ ├─ _0111: Subgr._0111 [7.352945]\n│ │ └─ _011101: Item A [7.352945]\n│ └─ _0112: Subgr._0112 [14.13896]\n│ ├─ _011201: Item B [6.7442417]\n│ └─ _011202: Item C [7.394718]\n├─ _02: Div._02 [3.0530455]\n│ ├─ _021: Agr._021 [1.1036392]\n│ │ └─ _0211: Subgr._0211 [1.1036392]\n│ │ └─ _021101: Item D [1.1036392]\n│ └─ _022: Agr._022 [1.9494063]\n│ └─ _0221: Subgr._0221 [1.9494063]\n│ └─ _022101: Item E [1.9494063]\n├─ _03: Div._03 [11.68543]\n│ └─ _031: Agr._031 [11.68543]\n│ └─ _0311: Subgr._0311 [11.68543]\n│ └─ _031101: Item F [11.68543]\n└─ _04: Div._04 [63.769615]\n └─ _041: Agr._041 [63.769615]\n ├─ _0411: Subgr._0411 [16.103952]\n │ └─ _041101: Item G [16.103952]\n ├─ _0412: Subgr._0412 [28.824577]\n │ ├─ _041201: Item H [11.367162]\n │ └─ _041202: Item I [17.457417]\n └─ _0413: Subgr._0413 [18.841085]\n └─ _041301: Item J [18.841085]\n\njulia> compute_index(tree, \"_041\")\n36-element Vector{Float32}:\n 100.13899\n 100.2787\n 100.41912\n 100.560234\n 100.70207\n 100.84464\n 100.98792\n ⋮\n 104.65377\n 104.81638\n 104.97984\n 105.14412\n 105.309235\n 105.47519\n\njulia> compute_index(tree[\"_041\"])\n36-element Vector{Float32}:\n 100.13899\n 100.2787\n 100.41912\n 100.560234\n 100.70207\n 100.84464\n 100.98792\n ⋮\n 104.65377\n 104.81638\n 104.97984\n 105.14412\n 105.309235\n 105.47519\n\njulia> a = tree[\"_041302\"]\n\njulia> a === nothing\ntrue\n```\n\"\"\"\nfunction compute_index(cpitree::CPITree, code::AbstractString)\n node = cpitree.tree[code]\n node === nothing && return nothing \n compute_index(node, cpitree.base)\nend\n\n# When single argument, compute the top level node\nfunction compute_index(cpitree::CPITree)\n node = cpitree.tree\n compute_index(node, cpitree.base)\nend\n\n\nchildren(cpitree::CPITree) = children(cpitree.tree)\n\n", "meta": {"hexsha": "1f7a7c62d79591819a6c12faf9a4db010b1e4d0b", "size": 24677, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/tree/CPItree.jl", "max_stars_repo_name": "DIE-BG/CPIDataBase.jl", "max_stars_repo_head_hexsha": "bc541a4217d4ec30c0959238b38a494548798f39", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tree/CPItree.jl", "max_issues_repo_name": "DIE-BG/CPIDataBase.jl", "max_issues_repo_head_hexsha": "bc541a4217d4ec30c0959238b38a494548798f39", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2022-02-10T03:41:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-24T02:04:02.000Z", "max_forks_repo_path": "src/tree/CPItree.jl", "max_forks_repo_name": "DIE-BG/CPIDataBase.jl", "max_forks_repo_head_hexsha": "bc541a4217d4ec30c0959238b38a494548798f39", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9646153846, "max_line_length": 190, "alphanum_fraction": 0.6274263484, "num_tokens": 8096, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.44167300566462553, "lm_q2_score": 0.13117322546005342, "lm_q1q2_score": 0.057935672751665376}} {"text": "export AbstractPolynomial\n\nconst SymbolLike = Union{AbstractString,Char,Symbol}\n\n\"\"\"\n AbstractPolynomial{T}\n\nAn abstract container for various polynomials. \n\n# Properties\n- `coeffs` - The coefficients of the polynomial\n- `var` - The indeterminate of the polynomial\n\"\"\"\nabstract type AbstractPolynomial{T} end\n\n# We want ⟒(P{α…,T}) = P{α…}; this default\n# works for most cases\n⟒(P::Type{<:AbstractPolynomial}) = constructorof(P)\n\n# convert `as` into polynomial of type P based on instance, inheriting variable\n# (and for LaurentPolynomial the offset)\n_convert(p::P, as) where {P <: AbstractPolynomial} = ⟒(P)(as, p.var)\n\n\"\"\"\n Polynomials.@register(name)\n\nGiven a polynomial with `name`, creates some common convenience constructors and conversions to minimize code required for implementation of a new polynomial type.\n\n# Example\n```julia\nstruct MyPolynomial{T} <: AbstractPolynomial{T} end\n\nPolynomials.@register MyPolynomial\n```\n\n# Implementations\nThis will implement simple self-conversions like `convert(::Type{MyPoly}, p::MyPoly) = p` and creates two promote rules. The first allows promotion between two types (e.g. `promote(Polynomial, ChebyshevT)`) and the second allows promotion between parametrized types (e.g. `promote(Polynomial{T}, Polynomial{S})`). \n\nFor constructors, it implements the shortcut for `MyPoly(...) = MyPoly{T}(...)`, singleton constructor `MyPoly(x::Number, ...)`, conversion constructor `MyPoly{T}(n::S, ...)`, and `variable` alternative `MyPoly(var=:x)`.\n\"\"\"\nmacro register(name)\n poly = esc(name)\n quote\n Base.convert(::Type{P}, p::P) where {P<:$poly} = p\n Base.convert(P::Type{<:$poly}, p::$poly{T}) where {T} = P(coeffs(p), p.var)\n Base.promote(p::P, q::Q) where {T, P <:$poly{T}, Q <: $poly{T}} = p,q\n Base.promote_rule(::Type{<:$poly{T}}, ::Type{<:$poly{S}}) where {T,S} =\n $poly{promote_type(T, S)}\n Base.promote_rule(::Type{<:$poly{T}}, ::Type{S}) where {T,S<:Number} =\n $poly{promote_type(T, S)}\n $poly(coeffs::AbstractVector{T}, var::SymbolLike = :x) where {T} =\n $poly{T}(coeffs, Symbol(var))\n $poly{T}(x::AbstractVector{S}, var::SymbolLike = :x) where {T,S<:Number} =\n $poly(T.(x), Symbol(var))\n function $poly(coeffs::G, var::SymbolLike=:x) where {G}\n !Base.isiterable(G) && throw(ArgumentError(\"coeffs is not iterable\"))\n $poly(collect(coeffs), var)\n end\n $poly{T}(n::S, var::SymbolLike = :x) where {T, S<:Number} =\n n * one($poly{T}, Symbol(var))\n $poly(n::S, var::SymbolLike = :x) where {S <: Number} = n * one($poly{S}, Symbol(var))\n $poly{T}(var::SymbolLike=:x) where {T} = variable($poly{T}, Symbol(var))\n $poly(var::SymbolLike=:x) = variable($poly, Symbol(var))\n end\nend\n\n\nmacro registerN(name, params...)\n poly = esc(name)\n αs = tuple(esc.(params)...)\n quote\n Base.convert(::Type{P}, q::Q) where {$(αs...),T, P<:$poly{$(αs...),T}, Q <: $poly{$(αs...),T}} = q\n Base.convert(::Type{$poly{$(αs...)}}, q::Q) where {$(αs...),T, Q <: $poly{$(αs...),T}} = q \n Base.promote(p::P, q::Q) where {$(αs...),T, P <:$poly{$(αs...),T}, Q <: $poly{$(αs...),T}} = p,q\n Base.promote_rule(::Type{<:$poly{$(αs...),T}}, ::Type{<:$poly{$(αs...),S}}) where {$(αs...),T,S} =\n $poly{$(αs...),promote_type(T, S)}\n Base.promote_rule(::Type{<:$poly{$(αs...),T}}, ::Type{S}) where {$(αs...),T,S<:Number} = \n $poly{$(αs...),promote_type(T,S)}\n\n function $poly{$(αs...),T}(x::AbstractVector{S}, var::SymbolLike = :x) where {$(αs...),T,S}\n $poly{$(αs...),T}(T.(x), Symbol(var))\n end\n $poly{$(αs...)}(coeffs::AbstractVector{T}, var::SymbolLike=:x) where {$(αs...),T} =\n $poly{$(αs...),T}(coeffs, Symbol(var))\n $poly{$(αs...),T}(n::Number, var::SymbolLike = :x) where {$(αs...),T} = n*one($poly{$(αs...),T}, Symbol(var))\n $poly{$(αs...)}(n::Number, var::SymbolLike = :x) where {$(αs...)} = n*one($poly{$(αs...)}, Symbol(var))\n $poly{$(αs...),T}(var::SymbolLike=:x) where {$(αs...), T} = variable($poly{$(αs...),T}, Symbol(var))\n $poly{$(αs...)}(var::SymbolLike=:x) where {$(αs...)} = variable($poly{$(αs...)}, Symbol(var))\n end\nend\n\n\n# deprecated. If desired, replace with @registerN type parameters... macro\n# Macros to register POLY{α, T} and POLY{α, β, T}\nmacro register1(name)\n @warn \"@register1 is deprecated use @registerN\"\n poly = esc(name)\n quote\n Base.convert(::Type{P}, p::P) where {P<:$poly} = p\n Base.promote(p::P, q::Q) where {α,T, P <:$poly{α,T}, Q <: $poly{α,T}} = p,q\n Base.promote_rule(::Type{<:$poly{α,T}}, ::Type{<:$poly{α,S}}) where {α,T,S} =\n $poly{α,promote_type(T, S)}\n Base.promote_rule(::Type{<:$poly{α,T}}, ::Type{S}) where {α,T,S<:Number} = \n $poly{α,promote_type(T,S)}\n function $poly{α,T}(x::AbstractVector{S}, var::SymbolLike = :x) where {α,T,S}\n $poly{α,T}(T.(x), Symbol(var))\n end\n $poly{α}(coeffs::AbstractVector{T}, var::SymbolLike=:x) where {α,T} =\n $poly{α,T}(coeffs, Symbol(var))\n $poly{α,T}(n::Number, var::SymbolLike = :x) where {α,T} = n*one($poly{α,T}, Symbol(var))\n $poly{α}(n::Number, var::SymbolLike = :x) where {α} = n*one($poly{α}, Symbol(var))\n $poly{α,T}(var::SymbolLike=:x) where {α, T} = variable($poly{α,T}, Symbol(var))\n $poly{α}(var::SymbolLike=:x) where {α} = variable($poly{α}, Symbol(var))\n end\nend\n\n\n# Macro to register POLY{α, β, T}\nmacro register2(name)\n @warn \"@register2 is deprecated use @registerN\"\n poly = esc(name)\n quote\n Base.convert(::Type{P}, p::P) where {P<:$poly} = p\n Base.promote(p::P, q::Q) where {α,β,T, P <:$poly{α,β,T}, Q <: $poly{α,β,T}} = p,q \n Base.promote_rule(::Type{<:$poly{α,β,T}}, ::Type{<:$poly{α,β,S}}) where {α,β,T,S} =\n $poly{α,β,promote_type(T, S)}\n Base.promote_rule(::Type{<:$poly{α,β,T}}, ::Type{S}) where {α,β,T,S<:Number} =\n $poly{α,β,promote_type(T, S)}\n $poly{α,β}(coeffs::AbstractVector{T}, var::SymbolLike = :x) where {α,β,T} =\n $poly{α,β,T}(coeffs, Symbol(var))\n $poly{α,β,T}(x::AbstractVector{S}, var::SymbolLike = :x) where {α,β,T,S<:Number} = $poly{α,β,T}(T.(x), var)\n $poly{α,β,T}(n::Number, var::SymbolLike = :x) where {α,β,T} = n*one($poly{α,β,T}, Symbol(var))\n $poly{α,β}(n::Number, va::SymbolLiker = :x) where {α,β} = n*one($poly{α,β}, Symbol(var))\n $poly{α,β,T}(var::SymbolLike=:x) where {α,β, T} = variable($poly{α,β,T}, Symbol(var))\n $poly{α,β}(var::SymbolLike=:x) where {α,β} = variable($poly{α,β}, Symbol(var))\n end\nend\n\n", "meta": {"hexsha": "4bb0a1007d1f9c215d013ba81ccc25831b17c6ce", "size": 6746, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/abstract.jl", "max_stars_repo_name": "michakraus/Polynomials.jl", "max_stars_repo_head_hexsha": "8b6a3d282d8f67cfca219ec91aa4076257a16ff0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/abstract.jl", "max_issues_repo_name": "michakraus/Polynomials.jl", "max_issues_repo_head_hexsha": "8b6a3d282d8f67cfca219ec91aa4076257a16ff0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-01-09T18:43:34.000Z", "max_issues_repo_issues_event_max_datetime": "2017-01-11T11:18:49.000Z", "max_forks_repo_path": "src/abstract.jl", "max_forks_repo_name": "michakraus/Polynomials.jl", "max_forks_repo_head_hexsha": "8b6a3d282d8f67cfca219ec91aa4076257a16ff0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.5323741007, "max_line_length": 314, "alphanum_fraction": 0.5677438482, "num_tokens": 2265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3702253925955866, "lm_q2_score": 0.15610489940847916, "lm_q1q2_score": 0.05779399766959875}} {"text": "### A Pluto.jl notebook ###\n# v0.15.1\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n quote\n local el = $(esc(element))\n global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing\n el\n end\nend\n\n# ╔═╡ ac87ced2-986f-4e6c-80b2-104b25c171c2\nbegin\n\tusing CSV, JLD2, FITSIO, FileIO# , HDF5\n\tusing DataFrames #, Query\n\tusing PyCall\n\tusing PlutoUI, PlutoTeachingTools\n\teval(Meta.parse(code_for_check_type_funcs))\nend\n\n# ╔═╡ e0e60e09-3808-4d6b-a773-6ba59c02f517\nmd\"\"\"\n# Astro 528, Lab 3, Exercise 2\n# Benchmarking File I/O &\n# (and calling Python packages)\n\"\"\"\n\n# ╔═╡ 8c1d81ab-d215-4972-afeb-7e00bf6063c2\nmd\"\"\"\nFor many applications, its important that we be able to read input data from a file and/or to write our outputes to files so they can be reused later. Disk access is typically much slower than accessing system memory. Therefore, disk access can easily become the limiting factor for a project. In this set of exercises, you'll see examples of how to perform basic file I/O. In the process, you'll also see how to import Python packages, call python functions and access data computed by python functions.\n\nYou'll be provided with most of the code you need, so that you can focus on comparing how much disk space and time is required by different file formats. Near the end of the lab, you'll be asked to think about when each type of file format would be a good choice for you to use in your research projects.\n\"\"\"\n\n# ╔═╡ 1607eac9-e76f-4d1f-a9ce-981ce3be9bea\nmd\"\"\"\n### Download some data\nFirst, we're going to download some data from the web. Julia has a built in `download` function that can be handy for this. It relies on your system having some utilities already installed (e.g., `curl`, `wget` or `fetch`). If you run this on a local system and run into trouble, then you can leave the cell below, and manually download the file to the data subdirectory.\n\"\"\"\n\n# ╔═╡ f27e1e8f-15eb-4754-a94c-7f37c54b871e\nbegin \n\tpath = basename(pwd())==\"test\" ? \"../data/\" : \"data/\"\n\tif !isdir(path) mkdir(path) end # make sure there's a data directory\n\turl = \"https://exoplanetarchive.ipac.caltech.edu/data/KeplerData/Simulated/kplr_dr25_inj1_plti.txt\"\n\tfilename_ipac = joinpath(path,basename(url)) # extract the filename and prepend \"data/\"\n\ttime_to_download = NaN\n\tif !isfile(filename_ipac) # skip downloading if file already exists\n\t time_to_download = @elapsed download(url,filename_ipac)\n\tend\nend\n\n# ╔═╡ 80f02c3a-6751-48df-92ec-13f5c7d8c71e\nif !isnan(time_to_download)\n\tmd\"Downloading the file took $time_to_download seconds.\"\nend\n\n# ╔═╡ 624c9038-3008-4e78-a149-60796dacf9c0\nmd\"\"\"\nPreviously, everything you needed for an assignment was included in a GitHub repository. So why did I make you download the file?\n\nNotice the size of the file. Git is great for tracking source code, but it wasn't really designed for working with large files (especially large _binary_ files). Since we're not going to be editing it, we'll simply download it once. Besides, it's useful to know how to download a file from within a julia script and to compare the time required to download the file from the internet to the time required to read the file from disk.\n\"\"\"\n\n# ╔═╡ 2eb255d9-707d-4224-a0ce-fe90a1c69722\nmd\"\"\"\n## Calling AstroPy to read data in unusual formats\n\nHere I've picked a file containing the results of applying the pipeline for NASA's Kepler mission to [simulated data](https://exoplanetarchive.ipac.caltech.edu/docs/KeplerSimulated.html) in which the signals of simulated \"planet's\" have been injected into actual Kepler data. This data set is the basis for computing the efficiency of the Kepler pipeline at detecting real planets. This dataset has played an important role in enabling astronomers to estimate the occurrence rates of planets around other stars. \nFor documentation of its contents, you could read [its documentation](https://exoplanetarchive.ipac.caltech.edu/docs/KSCI-19110-001.pdf). However, that's not necessary for this lab. For now, we'll just do some basic manipulations of the file, and the details of its contents aren't important. That said, it is important to know the _file format_. \n\nThis data file that we downloaded is in [IPAC format](https://irsa.ipac.caltech.edu/applications/DDGEN/Doc/ipac_tbl.html). \nIt would be tedious to learn the details of every file format that is used in astronomy, let alone to write our own code to read them. Fortunately, there are packages that can read the most common file formats. Sometimes astronomers use specialized/less common file formats which aren't always implemented in native Julia. Reading such files is an example of something that [astropy](http://docs.astropy.org) is particularly good for. It provides a function [`astropy.io.ascii.read`](http://docs.astropy.org/en/stable/io/ascii/) that will read a file in IPAC for us. \nSince astropy is written in Python, we import the [`PyCall`](https://github.com/stevengj/PyCall.jl) package, so we can import python packages and call python functions from Julia. \nSince reading a file from disk is typically limited by the rate of getting data from disk, rather than compute speed, it's usually not a problem that Python isn't particularly fast, when it's comes to reading files.\n\"\"\"\n\n# ╔═╡ 8571ccaf-5fbc-4593-82db-ead073a4074f\nmd\"\"\"\nAt the bottom of this notebook, I've run `using PyCall`. Here, we'll import the required python module using `pyimport`. \n\"\"\"\n\n# ╔═╡ 442604d0-b490-404b-8b1c-7e1c01cebad7\nastropy_io_ascii = pyimport(\"astropy.io.ascii\")\n\n# ╔═╡ 70f5fe63-fea1-4afc-b03d-f113b8bd621e\nmd\"\"\"\nNow, we can review the documentation for [`astropy.io.ascii.read`](http://docs.astropy.org/en/stable/io/ascii/) and call that function load the data in our input file. Let's use `@time`, so we can compare the time required to read various formats.\n\"\"\"\n\n# ╔═╡ 8cd5a772-a3aa-4166-92e6-39436d0d2278\nwith_terminal() do \n\t@time astropy_io_ascii.read(filename_ipac, format=\"ipac\", fast_reader=false)\nend\n\n# ╔═╡ 074b00ce-dae6-4e4f-8673-49be73085327\nmd\"\"\"\nOn the plus side, the data was read in. However, what is the type of the data that astropy read for us and stored into `data_from_astropy`? Let's check.\n\"\"\"\n\n# ╔═╡ ced3ecc9-94ea-408f-bdef-d34802166663\nbegin\n\ttime_to_read_with_astropy = @elapsed data_from_astropy = astropy_io_ascii.read(filename_ipac, format=\"ipac\", fast_reader=false)\n\ttypeof(data_from_astropy)\nend\n\n# ╔═╡ c62adfb6-6ef8-45fd-992f-07bca59f82cd\nmd\"\"\"\nSince Python is a weakly-typed language, it's type is `PyObject`. That can contain most anything! \nThat flexibility can be convenient, but it is also one of the reasons that Python is not a good language for high-performance computing. To enable Julia to work efficiently with the data, we'll want Julia to know what type the data is and store a list of strictly-typed columns into a the data into a `DataFrame`.\nThe PyCall package provides an interface for For accessing data from PyObjects. Because of the weak typing issue, the syntax and details can be a bit confusing. If you're not intending to call Python for your class project, then there's no reason to worry about that these details. \n\"\"\"\n\n# ╔═╡ 03edae54-4368-4b81-8713-17f93bbb9ed9\nprotip(md\"\"\"\nThis list is just for students who are curious about accessing Python data and methods from Julia.\n\t\n - Given o::PyObject, o.attribute in Julia is equivalent to o.attribute in Python, with automatic type conversion. To get an attribute as a PyObject without type conversion, do o.\"attribute\" instead. The keys(o::PyObject) function returns an array of the available attribute symbols.\n\n - Given o::PyObject, get(o, key) is equivalent to o[key] in Python, with automatic type conversion. To get as a PyObject without type conversion, do get(o, PyObject, key), or more generally get(o, SomeType, key). You can also supply a default value to use if the key is not found by get(o, key, default) or get(o, SomeType, key, default). Similarly, set!(o, key, val) is equivalent to o[key] = val in Python, and delete!(o, key) is equivalent to del o[key] in Python. For one or more integer indices, o[i] in Julia is equivalent to o[i-1] in Python.\n\n - You can call an o::PyObject via o(args...) just like in Python (assuming that the object is callable in Python). The explicit pycall form is still useful in Julia if you want to specify the return type.\n\n - pystr(o) and pyrepr(o) are analogous to str and repr in Python, respectively.\n\n - There's more information about accessing data in PyObjects (and other types to contain Python data) in the [PyCall documentation](https://github.com/JuliaPy/PyCall.jl#types). (The above info is copied directly from there.)\n\"\"\")\n\n# ╔═╡ e0b82e6c-043c-4e66-a2a4-ae0f3e4e5404\nmd\"\"\"\nFor now, you can get a [`Dict` or \"Dictionary\"](https://docs.julialang.org/en/v1/base/collections/index.html#Dictionaries-1) by using `data_from_astropy.columns`. The dictionary consists of a set of _keys_ (in this case strings), where each key is associated with a _value_ (in this case a Vector or 1-d array). \nOften times, the data you want to work with can be represented as a table. For efficiency's sake, it's usually best to represent these as a bunch of `Vector`'s, each containing one columns of data. Using a `Dict` allows you to give the columns names (instead of just numbers, so you're less likely to access the wrong column) and allows each column to have a different type (again useful for Julia to optimize your code). \n\"\"\"\n\n# ╔═╡ aa62f1e5-6af5-43f6-be11-665ed25986c0\ndict_from_astropy = data_from_astropy.columns\n\n# ╔═╡ 540468dc-3f9f-457b-9b44-efb3ec036166\nmd\"\"\"\nMost of the columns can be automatically converted to an array with a known Julia type. For example, `data_from_astropy.columns[\"KIC_ID\"]` returns data as an `Array{Int64,1}`. However, value associated with `TCE_ID` is some `PyObject` that can't be automatically reinterpretted as a Julia array. \n\"\"\"\n\n# ╔═╡ 21e3adbb-0176-4963-bdfc-0ba2422af4bf\ntypeof(dict_from_astropy[\"KIC_ID\"])\n\n# ╔═╡ d27aef3b-bfe7-466a-9580-93fc53dcef18\ntypeof(dict_from_astropy[\"TCE_ID\"])\n\n# ╔═╡ 02f638d9-ec2f-4072-9fb3-e6fabac1b1e6\nmd\"\"\"Since many `KIC_ID`'s don't have an associated `TCE_ID`, there are many missing entries. Python is trying to store a list with lots of empty entries efficiently, but PyCall doesn't (yet?) know how to deal with this `MaskedColumn` for us. Working with the data when Julia can't know its type would be very inefficient. Therefore, we want to create an array of Strings that allows Julia to represent this data more efficiently. Technically, it will be an array where each element is either a `String` or a `missing`. It took a little tinkering, but eventually, I figured out how to extract that data into an efficient Julia object.\n\"\"\"\n\n# ╔═╡ 481c5b7a-4660-4954-84f3-29d33bd73f3d\nbegin\n\tTCE_ID_list = map(x -> x != nothing ? x : missing, data_from_astropy.columns[\"TCE_ID\"].data.tolist())\n\tTCE_ID_list_type = typeof(TCE_ID_list)\n\tTCE_ID_list\nend\n\n# ╔═╡ aba84742-a927-4ce5-9f7c-6e535db1ee47\nprotip(md\"Note that the type of `TCE_ID_list` is a $TCE_ID_list_type. Julia is able to store and compute on vectors with missing data very efficiently thanks to its rich type system.\")\n\n# ╔═╡ aa7c4dfe-a3d4-448b-a559-1bc7b338a1dc\nmd\"\"\"\nNow let's replace the value associated with TCE_ID with this list.\n\"\"\"\n\n# ╔═╡ a97f9c8e-dbd3-4613-9c6e-c471340ea2d6\ndict_from_astropy[\"TCE_ID\"] = TCE_ID_list;\n\n# ╔═╡ 7c7430a0-d16e-485b-bbd9-7f231fee853a\nmd\"\"\"\nIf we just wantted to access the data, then we could use the data stored in the columns as a dictionary. \nHowever, a dictionary doesn't guarentee anything about the relationship of the value of different keys.\nFor example, in a table, each column should have the same number of rows. Therefore, we'll switch from representing the data as a dictionary and start using a `DataFrame`, a type provided by the [DataFrames.jl package](https://github.com/JuliaData/DataFrames.jl). A `DataFrame` can be thought of as a table, where the data for each column is stored as an array. A `DataFrame` also provides some additional features to allow easy and efficient access and manipulation of the table that will come in useful later. \n\"\"\"\n\n# ╔═╡ cebe52b3-386c-4d31-8497-c19b6c742577\nbegin\n\t# First, we'll create and copy a small `DataFrame`, so the functions get compiled before we start timing things.\n\tsmall_dict = Dict(:a=>[1,2],:b=>[3.0,4.0],:c=>[\"hello\",missing])\n\tsmall_df1 = DataFrame(small_dict)\n\tsmall_df2 = DataFrame(small_dict, copycols=false)\nend;\n\n# ╔═╡ 3d09d38a-ca72-43f2-bd85-17fc0e05a645\nmd\"\"\"\nWe'll use our existing dictionary to initialize a `DataFrame`. \n\"\"\"\n\n# ╔═╡ 9257c879-d96f-4d2b-994e-d542617b0c65\nwith_terminal() do\n\tsmall_dict # makes sure already compiled code for creating small DataFrame\n\t@time df_tmp = DataFrame(dict_from_astropy)\nend\n\n# ╔═╡ 307a7a29-afa6-4c4d-88ae-4f757aeba892\nmd\"\"\"\n2a. Look at how much memory was allocated during this line of code. \nDo you think it involved allocating and copying lots of data from the dictionary?\n\n\"\"\"\n\n# ╔═╡ afdc442a-2931-4129-824e-98431e1d8be2\nresponse_2a = missing\n\n# ╔═╡ c42deea3-acf1-491a-97bd-fdc472917584\ndisplay_msg_if_fail(check_type_isa(:response_2a,response_2a,[AbstractString,Markdown.MD]))\n\n# ╔═╡ 7c1f4a27-dfd7-428a-97ef-eac1784e8d6f\nmd\"\"\"By default `DataFrames` prioritizes _safe operations_ over efficient ones. However, it also provides options for more efficient operations for times when users want to invest a little more time to get good performance. For example, we can tell it not to copy the data, using `copycols=false`).\"\"\"\n\n# ╔═╡ 97111ccc-8a16-4e7d-adf7-0dcd90524be3\nwith_terminal() do\n\t\t@time df = DataFrame(dict_from_astropy, copycols=false)\nend\n\n# ╔═╡ f45668b1-1cbd-48e6-9224-d469826e093b\nmd\"\"\"\n2b. Look at how much memory was allocated the second time. \nDid Julia make a new copy of all of the data? How did the time required compare to the first attempt?\n\"\"\"\n\n# ╔═╡ 52beb148-6214-4a03-a0cf-6c2a6da77d40\nresponse_2b = missing\n\n# ╔═╡ 1ecbd400-0157-45ce-b1b8-db764012ba5e\ndisplay_msg_if_fail(check_type_isa(:response_2b,response_2b,[AbstractString,Markdown.MD]))\n\n# ╔═╡ 191ba96e-2573-4bc1-a352-46a66e0a5c4f\nmd\"\"\"\n## Writing a CSV file\n\nThe IPAC format allows for significant metadata, but reading not-so-common file formats can be annoying. \nLet's say that we'd like to write the data to a [CSV file](https://en.wikipedia.org/wiki/Comma-separated_values), so that it's easier for other programs to read in. Using the CSV package, we can read a CSV file into a DataFrame (or several other tabular data structures) and write CSV files from a DataFrame with code like the following.\n\"\"\"\n\n# ╔═╡ 82a757ad-566d-4c1d-8b3d-366ffd980fb4\nbegin\n\t# Read & write a small test file so compilation time not included below\n\tn_small_df = 1024\n\tsmall_csv_filename = \"random_numbers.csv\"\n\tsmall_df = DataFrame(a=rand(n_small_df),b=rand(n_small_df) ) \n\tCSV.write(joinpath(path,small_csv_filename),small_df) \n\tsmall_df_from_csv = CSV.read(joinpath(path,small_csv_filename),DataFrame)\nend;\n\n# ╔═╡ 3e550b71-4750-460b-be18-911a848a8f49\nmd\"\"\"\nNow, let's write the DataFrame from our IPAC file to a CSV file. We'll investigate how the filesize and time to read files compares.\n\"\"\"\n\n# ╔═╡ b0c3875b-ef07-4e92-a0a8-55f42b266c6b\nbegin\n\tfilename_csv = replace(filename_ipac, \".txt\" => \".csv\") \n\tdf = DataFrame(dict_from_astropy, copycols=false)\n\twith_terminal() do\n\t\t@time CSV.write(filename_csv,df)\n\tend\nend\n\n# ╔═╡ 58e021c6-500f-40d8-a388-a5732bc808b3\nmd\"\"\"Next, we'll compare the filesizes for the IPAC file and the CSV file containing the same data. \n\n2c. Which do you expect will be larger? Why?\nOnce you've made a prediction, mouse over the hint box below to see the sizes of the two files. If you were suprsised, try to explain what happened.\"\"\"\n\n# ╔═╡ 36bfd224-a13b-438c-9106-382c15a6a1d2\nresponse_2c = missing\n\n# ╔═╡ 7f4c3ab8-041e-4ef0-bb2e-320f5293cdde\ndisplay_msg_if_fail(check_type_isa(:response_2c,response_2c,[AbstractString,Markdown.MD]))\n\n# ╔═╡ 195c2df4-7e1c-49f8-871f-f76b985dab6d\nbegin\n\tipac_filesize = filesize(filename_ipac) /1024^2\n\tcsv_filesize = filesize(filename_csv) /1024^2\n\thint(md\"The IPAC file size is $ipac_filesize MB versus $csv_filesize MB for the CSV.\")\nend\n\n# ╔═╡ 32124f8a-f5cf-41d1-97a9-ce1d05145fde\nmd\"\"\"\n\n## Reading CSV files\n\n2d. Think back to how long it took to read in the file in IPAC format ($time_to_read_with_astropy seconds). How long do you think it will take to read in the same data once it's been stored in CSV format?\n\"\"\"\n\n# ╔═╡ 507e1516-5433-49eb-831d-32426f30895e\nresponse_2d = missing\n\n# ╔═╡ eac67cc9-754b-4f7d-add8-93900a1b5b49\ndisplay_msg_if_fail(check_type_isa(:response_2d,response_2d,[AbstractString,Markdown.MD]))\n\n# ╔═╡ 64224c6b-c5a0-44f2-b2a0-7f77759cb848\nmd\"\"\"\nNow, try reading it in and see. \n\"\"\"\n\n# ╔═╡ 73c06bb1-be49-46bd-b7f1-c45cc56af7b4\nmd\"\"\"\nI'm ready to benchmark reading a CSV file. $(@bind ready_read_csv CheckBox()) \n$(@bind go_read_csv Button(\"Rerun the benchmarks.\"))\n\"\"\"\n\n# ╔═╡ ebfaa677-829b-4bf9-bdbb-19f3c87dd3a4\nif ready_read_csv\n\tgo_read_csv\n\ttime_read_csv = @elapsed df_csv = CSV.read(filename_csv, DataFrame)\n\tmd\"It took $time_read_csv seconds to read the CSV file.\"\nend\n\n# ╔═╡ 945f5a55-3026-4497-9ece-8af878c87788\nmd\"\"\"\n2e. How did the time required to read the data in CSV format compare to the time to read the data in IPAC format? If you were suprsised, try to explain what happened.\n\"\"\"\n\n# ╔═╡ 57397ee4-9efc-48b3-b640-d2b7a10da633\nresponse_2e = missing\n\n# ╔═╡ 8059a6a3-384a-4344-8a23-650ee0be10c2\ndisplay_msg_if_fail(check_type_isa(:response_2e,response_2e,[AbstractString,Markdown.MD]))\n\n# ╔═╡ f5b93929-2c59-4360-8c41-97a1324ba455\nmd\"2f. How do you think the sizes of the files in the two formats will compare? Once you've made your prediction, mouse over the hint box. If you were suprsised, try to explain what happened.\"\n\n# ╔═╡ 122196fa-45ca-4031-85eb-4afd4782de9e\nresponse_2f = missing\n\n# ╔═╡ e9dc1456-616b-4e4b-b209-9f6ba4c48607\ndisplay_msg_if_fail(check_type_isa(:response_2f,response_2f,[AbstractString,Markdown.MD]))\n\n# ╔═╡ f15d37a7-d962-4da0-977f-76729a3313be\nhint(md\"The IPAC file size is $ipac_filesize MB versus $csv_filesize MB for the CSV.\")\n\n# ╔═╡ 28f195c4-4f61-4873-85d6-b4e3aaa3660f\nmd\"\"\"\n## Binary formats: HDF5/JLD2\n\nThere are numerous binary file formats that one could use. Here, we'll try using JLD2 which is a subset of the [HDF5](https://www.hdfgroup.org/solutions/hdf5/) file format. This means that when [Julia's JLD2 package](https://github.com/JuliaIO/JLD2.jl) writes jld2 files, they can be read by other programs that can read HDF5 files. However, a generic HDF5 file is not a valid JLD2 file. If you want to read a HDF5 file, then you can use Julia's [HDF5.jl package](https://github.com/JuliaIO/HDF5.jl). The [FileIO.jl](https://github.com/JuliaIO/FileIO.jl) package provides a common interface for reading and writing from multiple file formats, including these and several others.\n\nAs before, we'll call each function once using a small DataFrame, just so they get compiled before we benchmark them.\n\"\"\"\n\n# ╔═╡ 3837e439-250b-4577-b0d7-93352ec19f6e\nbegin\n\tfilename_jld2_small = replace(small_csv_filename, \".csv\" => \".jld2\") \n\t@save joinpath(path,filename_jld2_small) small_df \n\tsmall_df_from_jld2 = load(joinpath(path,filename_jld2_small), \"small_df\")\nend;\n\n# ╔═╡ df9b701f-d314-4512-b2ea-1f6ae015166c\nresponse_2g = missing\n\n# ╔═╡ 377f7527-a338-4526-bb24-9766c635e719\ndisplay_msg_if_fail(check_type_isa(:response_2g,response_2g,[AbstractString,Markdown.MD]))\n\n# ╔═╡ 25f24754-16d4-4343-b54a-cf8ea1358ce9\nbegin \n\tsmall_jld2_filesize = filesize(joinpath(path,filename_jld2_small))/1024\n\tsmall_csv_filesize = filesize(joinpath(path,small_csv_filename))/1024\n\thint(md\"For the small random data set, the JLD2 file's size is $small_jld2_filesize KB versus $small_csv_filesize KB for the CSV file.\")\nend\n\n# ╔═╡ 8255b5a9-cbe6-4604-bedd-0e366f311096\nmd\"\"\"\nLet's check the filesizes for the JLD2 file to the CSV file. \nThe small CSV file we created is $small_jld2_filesize KB. \n\n2g. How large would you guess the JLD2 file will be? Once you've made your prediction, mouse over the hint box. If you were suprised, try to explain what happened.\n\"\"\"\n\n# ╔═╡ 570fd826-23fd-46ee-bdb4-58fb0c45719a\nmd\"\"\"\nNow let's time how long it takes to save the data from IPAC into a JLD2 file.\n\"\"\"\n\n# ╔═╡ 691410bb-0472-4800-a90d-29ddf947de3e\nbegin\n\tfilename_jld2 = replace(filename_ipac, \".txt\" => \".jld2\") \n\twith_terminal() do \n\t\t@time @save filename_jld2 df\n\tend\nend\n\n# ╔═╡ 8cbb1c90-bd94-44b5-80b6-81d38f3e6252\nmd\"2h. How long do you think it will take to load the data from the JLD2 file? \"\n\n# ╔═╡ c3065acf-6205-455f-ba74-ca51f3f6761b\nresponse_2h = missing\n\n# ╔═╡ 9c392be9-1505-40bc-a290-68085a1c2700\ndisplay_msg_if_fail(check_type_isa(:response_2h,response_2h,[AbstractString,Markdown.MD]))\n\n# ╔═╡ d738bdcc-5f83-4dfa-a17f-e9ea23db2986\nmd\"\"\"\nNow time how long it takes to load the data from the JLD2 file.\n\"\"\"\n\n# ╔═╡ d55ce157-099c-4c1b-94db-62918f04e5fe\nmd\"\"\"\nI'm ready to benchmark reading a JLD2 file. $(@bind ready_read_jld2 CheckBox()) \n$(@bind go_read_jld2 Button(\"Rerun the benchmarks.\"))\n\"\"\"\n\n# ╔═╡ 206f464b-55fe-46aa-85b7-8f0246a0aaad\nif ready_read_jld2\n\tgo_read_jld2\n\ttime_read_jld2 = @elapsed df_jld2_read_back_in = load(filename_jld2, \"df\")\n\tmd\"It took $time_read_jld2 seconds to read the JLD2 file.\"\nend\n\n# ╔═╡ 6f72d1b2-63f6-4301-8272-bb2d6d2d049e\nmd\"\"\"\n2i. How does the time required to read and write the JLD2 file compare to the time required to read the IPAC and CSV formatted files? If you were suprised, try to explain what happend.\n\"\"\"\n\n# ╔═╡ 01201c37-0b79-46b1-a001-e716f5b3ba67\nresponse_2i = missing\n\n# ╔═╡ e3d37bc1-a119-4add-a111-899ee0caea05\ndisplay_msg_if_fail(check_type_isa(:response_2i,response_2i,[AbstractString,Markdown.MD]))\n\n# ╔═╡ 6dff3f21-fac0-42e1-910a-f969a231374f\nmd\"\"\"\nNext, we'll compare the filesizes for the JLD2 file to the CSV file. \n\n2j. How large would you guess the JLD2 file will be? Once you've made your prediction, mouse over the hint box. If you were suprised, try to explain what happened.\n\"\"\"\n\n# ╔═╡ b26b8253-e6cd-49f4-81c5-2a3c2963a37c\nresponse_2j = missing\n\n# ╔═╡ e5dc123f-1596-4311-9398-f0cfe80a5342\ndisplay_msg_if_fail(check_type_isa(:response_2j,response_2j,[AbstractString,Markdown.MD]))\n\n# ╔═╡ 7b9d26c2-899e-45e9-b664-39d5f1adfe3f\nbegin \n\tjld2_filesize = filesize(filename_jld2) / 1024^2;\n\thint(md\"The JLD2 file size is $jld2_filesize MB versus $csv_filesize MB for the CSV.\")\nend\n\n# ╔═╡ fc01d57f-c90b-4231-96be-ddd48656d55e\nmd\"\"\"\n## Flexible Format: FITS\n\nAstronomers often use the [FITS file format](https://en.wikipedia.org/wiki/FITS). Like [HDF\n5](https://www.hdfgroup.org/solutions/hdf5/), it's a very flexible (e.g., it can store both text and binary data) and thus complicated file\n format. \nTherefore, most languages call a common [FITSIO library written in C](https://heasarc.gsfc.nasa.gov/fitsio/), rather than implementing code themselves. Indeed, that's what [Julia's FITSIO.jl package](https://github.com/JuliaAstro/FITSIO.jl) does.\n\nUnfortunately, the FITSIO package isn't as polished as the others. It expects a `Dict` rather than a `DataFrame`, and it can't handle missing values. So I've provided some helper functions at the bottom of the notebook. Also, FITS files have complicated headers, so I'll provide a function to read all the tabular data from a simple FITS file. As usual, we'll use each function once, so that Julia compiles them before we start timing.\n\"\"\"\n\n# ╔═╡ 3b232365-f2fe-4edb-a39f-3e37c8cbb666\nmd\"Now we can time how long it takes to write and read the data as FITS files.\"\n\n# ╔═╡ 568862b3-6fce-426a-a9e2-e558adf3932a\nmd\"\"\"\nI'm ready to benchmark reading a FITS file. $(@bind ready_read_fits CheckBox()) \n$(@bind go_read_fits Button(\"Rerun the benchmarks.\"))\n\"\"\"\n\n# ╔═╡ ae79ee89-d788-4612-8b1d-fc22d85c7744\nmd\"2k. How do the read/write times and file sizes for FITS compare to CSV and JLD2?\"\n\n# ╔═╡ 3745c237-ba48-4f2c-959e-441484244764\nresponse_2k = missing\n\n# ╔═╡ 6d061411-6f19-4119-aefb-cc380198b0ce\ndisplay_msg_if_fail(check_type_isa(:response_2k,response_2k,[AbstractString,Markdown.MD]))\n\n# ╔═╡ 8def87d2-f10b-4a82-b353-a6477eeead9b\nmd\"## Implications for your project\"\n\n# ╔═╡ c74b3105-f480-4688-b85f-3e7dff70da3b\nmd\"\"\"\n2l. How does the time required to read any of the above formats compare to the time required to download the files ($time_to_download seconds)? \nWill your project need to transfer large files over the internet? If so, very roughly how large do you expect they will be? \n\"\"\"\n\n# ╔═╡ 55438c09-1d94-4ff7-90c3-0cc6064a091e\nresponse_2l = missing\n\n# ╔═╡ bcc796c9-db11-4a09-a5f9-215127ac0938\ndisplay_msg_if_fail(check_type_isa(:response_2l,response_2l,[AbstractString,Markdown.MD]))\n\n# ╔═╡ 92b2ecdd-9491-4f16-8cb9-bacbcf180280\nmd\"\"\"\n2m. Will your project need to read in any input files? If so, what format are they in? \n\nI assume everyone's project code will write at least some output files? Very roughly, how large do you expect that they'll be? What format(s) would be a good choice for your project?\"\"\"\n\n# ╔═╡ 83216915-cdcf-4f0f-829f-a5ff4c4b8da0\nresponse_2m = missing\n\n# ╔═╡ 452872f9-2009-4733-b2d3-28f262ae19b7\ndisplay_msg_if_fail(check_type_isa(:response_2m,response_2m,[AbstractString,Markdown.MD]))\n\n# ╔═╡ 29415ddc-e002-4f56-a169-95f7b1c36be9\nmd\"# Helper Functions\"\n\n# ╔═╡ fb23d6c6-b812-4fe1-b224-0014bedbd43f\nChooseDisplayMode()\n\n# ╔═╡ 1e53aa10-dff6-40d5-89e2-da194ffc2052\nTableOfContents()\n\n# ╔═╡ 14cca8ce-cc61-4fae-b871-21c3fd23d0ea\n\"Convert a DataFrame to a Dict, replacing missing values with 0 or an empty string.\"\nfunction convert_dataframe_to_dict_remove_missing(df::DataFrame)\n d = Dict(map(n->\"$n\"=> # create a dictionary\n ( any(ismissing.(df[!,n])) ? # if column contains a missing\n map(x-> !ismissing(x) ? # search for missings\n x : # leave non-missing values alone\n ( (eltype(df[!,n]) <: Number) ? zero(eltype(n)) : \"\")\n , df[!,n]) # but replace missing with 0 or \"\"\n : df[!,n] ), # if nothing is missing, just use column as is\n names(df) )) \nend\n\n# ╔═╡ 28fc8de4-749b-4093-b32f-c398f8d27d3d\n\"Write a DataFrame to a FITS file, replacing missing values with 0 or an empty string.\"\nfunction write_dataframe_as_fits(filename::String, df::DataFrame)\n try \n dict = convert_dataframe_to_dict_remove_missing(df) \n fits_file = FITS(filename,\"w\")\n write(fits_file, dict )\n close(fits_file)\n catch\n @warn(\"There was a problem writing a dataframe to \" * filename * \".\")\n end\nend\n\n\n# ╔═╡ 57b422e5-0ad0-4674-bdd3-a8358bc7aaeb\n\n\"Read the columns of the first table from a FITS file into a Dict\"\nfunction read_fits_tables(filename::String)\n dict = Dict{String,Any}()\n fits_file = FITS(filename,\"r\")\n # fits_file[1] is image data, we're interested in the table\n @assert length(fits_file) >= 2\n header = read_header(fits_file[2])\n for i in 1:length(header)\n c = get_comment(header,i)\n if !occursin(\"label for field\",c)\n continue\n end\n h = header[i]\n @assert typeof(h) == String\n try \n dict[h] = read(fits_file[2],h)\n catch\n @warn \"# Problem reading table column \" * h * \".\"\n end\n end\n close(fits_file)\n return dict\nend\n\n\n# ╔═╡ e05f16d6-eb50-49a9-bf14-95d63c9da7ff\nbegin\n\tfilename_fits_small = replace(small_csv_filename, \".csv\" => \".fits\") \n\twrite_dataframe_as_fits(joinpath(path,filename_fits_small),small_df)\n\tread_fits_tables(joinpath(path,filename_fits_small))\nend;\n\n# ╔═╡ 1992595f-9976-4b18-bf9c-df8a73d30dc8\nbegin\n\tfilename_fits_small # make sure have already compiled functions\n\tfilename_fits = replace(filename_ipac, \".txt\" => \".fits\") \n\twith_terminal() do \n\t\t@time write_dataframe_as_fits(filename_fits,df)\n\tend\nend\n\n# ╔═╡ 90d5244e-17be-4601-b922-8c254f1248bf\nbegin\n\tfits_filesize = filesize(filename_fits) /1024^2\n\thint(md\"The FITS file size is $fits_filesize MB versus $jld2_filesize MB for the JLD2 and $csv_filesize MB for the CSV.\")\nend\n\n# ╔═╡ 52f9edd0-79b0-4a9a-9930-3a05d3aa2447\nif ready_read_fits\n\tgo_read_fits\n\ttime_read_fits = @elapsed read_fits_tables(filename_fits)\n\tmd\"It took $time_read_fits seconds to read the FITS file.\"\nend\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nCSV = \"336ed68f-0bac-5ca0-87d4-7b16caf5d00b\"\nDataFrames = \"a93c6f00-e57d-5684-b7b6-d8193f3e46c0\"\nFITSIO = \"525bcba6-941b-5504-bd06-fd0dc1a4d2eb\"\nFileIO = \"5789e2e9-d7fb-5bc7-8068-2c6fae9b9549\"\nJLD2 = \"033835bb-8acc-5ee8-8aae-3f567f8a3819\"\nPlutoTeachingTools = \"661c6b06-c737-4d37-b85c-46df65de6f69\"\nPlutoUI = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nPyCall = \"438e738f-606a-5dbb-bf0a-cddfbfd45ab0\"\n\n[compat]\nCSV = \"~0.8.5\"\nDataFrames = \"~1.2.2\"\nFITSIO = \"~0.16.7\"\nFileIO = \"~1.10.1\"\nJLD2 = \"~0.4.13\"\nPlutoTeachingTools = \"~0.1.3\"\nPlutoUI = \"~0.7.9\"\nPyCall = \"~1.92.3\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\n[[ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[CFITSIO]]\ndeps = [\"CFITSIO_jll\"]\ngit-tree-sha1 = \"c860f5545064216f86aa3365ec186ce7ced6a935\"\nuuid = \"3b1b4be9-1499-4b22-8d78-7db3344d1961\"\nversion = \"1.3.0\"\n\n[[CFITSIO_jll]]\ndeps = [\"Artifacts\", \"JLLWrappers\", \"LibCURL_jll\", \"Libdl\", \"Pkg\"]\ngit-tree-sha1 = \"2fabb5fc48d185d104ca7ed7444b475705993447\"\nuuid = \"b3e40c51-02ae-5482-8a39-3ace5868dcf4\"\nversion = \"3.49.1+0\"\n\n[[CSV]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"PooledArrays\", \"SentinelArrays\", \"Tables\", \"Unicode\"]\ngit-tree-sha1 = \"b83aa3f513be680454437a0eee21001607e5d983\"\nuuid = \"336ed68f-0bac-5ca0-87d4-7b16caf5d00b\"\nversion = \"0.8.5\"\n\n[[Compat]]\ndeps = [\"Base64\", \"Dates\", \"DelimitedFiles\", \"Distributed\", \"InteractiveUtils\", \"LibGit2\", \"Libdl\", \"LinearAlgebra\", \"Markdown\", \"Mmap\", \"Pkg\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"SharedArrays\", \"Sockets\", \"SparseArrays\", \"Statistics\", \"Test\", \"UUIDs\", \"Unicode\"]\ngit-tree-sha1 = \"727e463cfebd0c7b999bbf3e9e7e16f254b94193\"\nuuid = \"34da2185-b29b-5c13-b0c7-acf172513d20\"\nversion = \"3.34.0\"\n\n[[Conda]]\ndeps = [\"JSON\", \"VersionParsing\"]\ngit-tree-sha1 = \"299304989a5e6473d985212c28928899c74e9421\"\nuuid = \"8f4d0f93-b110-5947-807f-2305c1781a2d\"\nversion = \"1.5.2\"\n\n[[Crayons]]\ngit-tree-sha1 = \"3f71217b538d7aaee0b69ab47d9b7724ca8afa0d\"\nuuid = \"a8cc5b0e-0ffa-5ad4-8c14-923d3ee1735f\"\nversion = \"4.0.4\"\n\n[[DataAPI]]\ngit-tree-sha1 = \"ee400abb2298bd13bfc3df1c412ed228061a2385\"\nuuid = \"9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a\"\nversion = \"1.7.0\"\n\n[[DataFrames]]\ndeps = [\"Compat\", \"DataAPI\", \"Future\", \"InvertedIndices\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"Markdown\", \"Missings\", \"PooledArrays\", \"PrettyTables\", \"Printf\", \"REPL\", \"Reexport\", \"SortingAlgorithms\", \"Statistics\", \"TableTraits\", \"Tables\", \"Unicode\"]\ngit-tree-sha1 = \"d785f42445b63fc86caa08bb9a9351008be9b765\"\nuuid = \"a93c6f00-e57d-5684-b7b6-d8193f3e46c0\"\nversion = \"1.2.2\"\n\n[[DataStructures]]\ndeps = [\"Compat\", \"InteractiveUtils\", \"OrderedCollections\"]\ngit-tree-sha1 = \"7d9d316f04214f7efdbb6398d545446e246eff02\"\nuuid = \"864edb3b-99cc-5e75-8d2d-829cb0a9cfe8\"\nversion = \"0.18.10\"\n\n[[DataValueInterfaces]]\ngit-tree-sha1 = \"bfc1187b79289637fa0ef6d4436ebdfe6905cbd6\"\nuuid = \"e2d170a0-9d28-54be-80f0-106bbe20a464\"\nversion = \"1.0.0\"\n\n[[Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[DelimitedFiles]]\ndeps = [\"Mmap\"]\nuuid = \"8bb1440f-4735-579b-a4ab-409b98df4dab\"\n\n[[Distributed]]\ndeps = [\"Random\", \"Serialization\", \"Sockets\"]\nuuid = \"8ba89e20-285c-5b6f-9357-94700520ee1b\"\n\n[[Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[FITSIO]]\ndeps = [\"CFITSIO\", \"Printf\", \"Reexport\", \"Tables\"]\ngit-tree-sha1 = \"85b66005c9d16d3d27c9d06fd3be5e25074128da\"\nuuid = \"525bcba6-941b-5504-bd06-fd0dc1a4d2eb\"\nversion = \"0.16.7\"\n\n[[FileIO]]\ndeps = [\"Pkg\", \"Requires\", \"UUIDs\"]\ngit-tree-sha1 = \"256d8e6188f3f1ebfa1a5d17e072a0efafa8c5bf\"\nuuid = \"5789e2e9-d7fb-5bc7-8068-2c6fae9b9549\"\nversion = \"1.10.1\"\n\n[[Formatting]]\ndeps = [\"Printf\"]\ngit-tree-sha1 = \"8339d61043228fdd3eb658d86c926cb282ae72a8\"\nuuid = \"59287772-0a20-5a39-b81b-1366585eb4c0\"\nversion = \"0.4.2\"\n\n[[Future]]\ndeps = [\"Random\"]\nuuid = \"9fa8497b-333b-5362-9e8d-4d0656e87820\"\n\n[[InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[InvertedIndices]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"15732c475062348b0165684ffe28e85ea8396afc\"\nuuid = \"41ab1584-1d38-5bbf-9106-f11c6c58b48f\"\nversion = \"1.0.0\"\n\n[[IteratorInterfaceExtensions]]\ngit-tree-sha1 = \"a3f24677c21f5bbe9d2a714f95dcd58337fb2856\"\nuuid = \"82899510-4779-5014-852e-03e436cf321d\"\nversion = \"1.0.0\"\n\n[[JLD2]]\ndeps = [\"DataStructures\", \"FileIO\", \"MacroTools\", \"Mmap\", \"Pkg\", \"Printf\", \"Reexport\", \"TranscodingStreams\", \"UUIDs\"]\ngit-tree-sha1 = \"59ee430ac5dc87bc3eec833cc2a37853425750b4\"\nuuid = \"033835bb-8acc-5ee8-8aae-3f567f8a3819\"\nversion = \"0.4.13\"\n\n[[JLLWrappers]]\ndeps = [\"Preferences\"]\ngit-tree-sha1 = \"642a199af8b68253517b80bd3bfd17eb4e84df6e\"\nuuid = \"692b3bcd-3c85-4b1f-b108-f13ce0eb3210\"\nversion = \"1.3.0\"\n\n[[JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"8076680b162ada2a031f707ac7b4953e30667a37\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.2\"\n\n[[LaTeXStrings]]\ngit-tree-sha1 = \"c7f1c695e06c01b95a67f0cd1d34994f3e7db104\"\nuuid = \"b964fa9f-0449-5b57-a5c2-d3ea65f4040f\"\nversion = \"1.2.1\"\n\n[[LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[LinearAlgebra]]\ndeps = [\"Libdl\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[MacroTools]]\ndeps = [\"Markdown\", \"Random\"]\ngit-tree-sha1 = \"0fb723cd8c45858c22169b2e42269e53271a6df7\"\nuuid = \"1914dd2f-81c6-5fcd-8719-6d5c9610ff09\"\nversion = \"0.5.7\"\n\n[[Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[Missings]]\ndeps = [\"DataAPI\"]\ngit-tree-sha1 = \"2ca267b08821e86c5ef4376cffed98a46c2cb205\"\nuuid = \"e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28\"\nversion = \"1.0.1\"\n\n[[Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[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 = \"bfd7d8c7fd87f04543810d9cbd3995972236ba1b\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"1.1.2\"\n\n[[Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[PlutoTeachingTools]]\ndeps = [\"LaTeXStrings\", \"Markdown\", \"PlutoUI\", \"Random\"]\ngit-tree-sha1 = \"e2b63ee022e0b20f43fcd15cda3a9047f449e3b4\"\nuuid = \"661c6b06-c737-4d37-b85c-46df65de6f69\"\nversion = \"0.1.4\"\n\n[[PlutoUI]]\ndeps = [\"Base64\", \"Dates\", \"InteractiveUtils\", \"JSON\", \"Logging\", \"Markdown\", \"Random\", \"Reexport\", \"Suppressor\"]\ngit-tree-sha1 = \"44e225d5837e2a2345e69a1d1e01ac2443ff9fcb\"\nuuid = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nversion = \"0.7.9\"\n\n[[PooledArrays]]\ndeps = [\"DataAPI\", \"Future\"]\ngit-tree-sha1 = \"cde4ce9d6f33219465b55162811d8de8139c0414\"\nuuid = \"2dfb63ee-cc39-5dd5-95bd-886bf059d720\"\nversion = \"1.2.1\"\n\n[[Preferences]]\ndeps = [\"TOML\"]\ngit-tree-sha1 = \"00cfd92944ca9c760982747e9a1d0d5d86ab1e5a\"\nuuid = \"21216c6a-2e73-6563-6e65-726566657250\"\nversion = \"1.2.2\"\n\n[[PrettyTables]]\ndeps = [\"Crayons\", \"Formatting\", \"Markdown\", \"Reexport\", \"Tables\"]\ngit-tree-sha1 = \"0d1245a357cc61c8cd61934c07447aa569ff22e6\"\nuuid = \"08abe8d2-0d0c-5749-adfa-8a2ac140af0d\"\nversion = \"1.1.0\"\n\n[[Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[PyCall]]\ndeps = [\"Conda\", \"Dates\", \"Libdl\", \"LinearAlgebra\", \"MacroTools\", \"Serialization\", \"VersionParsing\"]\ngit-tree-sha1 = \"169bb8ea6b1b143c5cf57df6d34d022a7b60c6db\"\nuuid = \"438e738f-606a-5dbb-bf0a-cddfbfd45ab0\"\nversion = \"1.92.3\"\n\n[[REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[Random]]\ndeps = [\"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[Reexport]]\ngit-tree-sha1 = \"5f6c21241f0f655da3952fd60aa18477cf96c220\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.1.0\"\n\n[[Requires]]\ndeps = [\"UUIDs\"]\ngit-tree-sha1 = \"4036a3bd08ac7e968e27c203d45f5fff15020621\"\nuuid = \"ae029012-a4dd-5104-9daa-d747884805df\"\nversion = \"1.1.3\"\n\n[[SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[SentinelArrays]]\ndeps = [\"Dates\", \"Random\"]\ngit-tree-sha1 = \"54f37736d8934a12a200edea2f9206b03bdf3159\"\nuuid = \"91c51154-3ec4-41a3-a24f-3f23e20d615c\"\nversion = \"1.3.7\"\n\n[[Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[SharedArrays]]\ndeps = [\"Distributed\", \"Mmap\", \"Random\", \"Serialization\"]\nuuid = \"1a1011a3-84de-559e-8e89-a11a2f7dc383\"\n\n[[Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[SortingAlgorithms]]\ndeps = [\"DataStructures\"]\ngit-tree-sha1 = \"b3363d7460f7d098ca0912c69b082f75625d7508\"\nuuid = \"a2af1166-a08f-5f64-846c-94a0d3cef48c\"\nversion = \"1.0.1\"\n\n[[SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[Suppressor]]\ngit-tree-sha1 = \"a819d77f31f83e5792a76081eee1ea6342ab8787\"\nuuid = \"fd094767-a336-5f1f-9728-57cf17d0bbfb\"\nversion = \"0.2.0\"\n\n[[TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[TableTraits]]\ndeps = [\"IteratorInterfaceExtensions\"]\ngit-tree-sha1 = \"c06b2f539df1c6efa794486abfb6ed2022561a39\"\nuuid = \"3783bdb8-4a98-5b6b-af9a-565f29a5fe9c\"\nversion = \"1.0.1\"\n\n[[Tables]]\ndeps = [\"DataAPI\", \"DataValueInterfaces\", \"IteratorInterfaceExtensions\", \"LinearAlgebra\", \"TableTraits\", \"Test\"]\ngit-tree-sha1 = \"d0c690d37c73aeb5ca063056283fde5585a41710\"\nuuid = \"bd369af6-aec1-5ad0-b16a-f7cc5008161c\"\nversion = \"1.5.0\"\n\n[[Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[TranscodingStreams]]\ndeps = [\"Random\", \"Test\"]\ngit-tree-sha1 = \"216b95ea110b5972db65aa90f88d8d89dcb8851c\"\nuuid = \"3bb67fe8-82b1-5028-8e26-92a6c54297fa\"\nversion = \"0.9.6\"\n\n[[UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[VersionParsing]]\ngit-tree-sha1 = \"80229be1f670524750d905f8fc8148e5a8c4537f\"\nuuid = \"81def892-9a0e-5fdd-b105-ffc91e053289\"\nversion = \"1.2.0\"\n\n[[Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─e0e60e09-3808-4d6b-a773-6ba59c02f517\n# ╟─8c1d81ab-d215-4972-afeb-7e00bf6063c2\n# ╟─1607eac9-e76f-4d1f-a9ce-981ce3be9bea\n# ╠═f27e1e8f-15eb-4754-a94c-7f37c54b871e\n# ╠═80f02c3a-6751-48df-92ec-13f5c7d8c71e\n# ╟─624c9038-3008-4e78-a149-60796dacf9c0\n# ╟─2eb255d9-707d-4224-a0ce-fe90a1c69722\n# ╟─8571ccaf-5fbc-4593-82db-ead073a4074f\n# ╠═442604d0-b490-404b-8b1c-7e1c01cebad7\n# ╟─70f5fe63-fea1-4afc-b03d-f113b8bd621e\n# ╠═8cd5a772-a3aa-4166-92e6-39436d0d2278\n# ╟─074b00ce-dae6-4e4f-8673-49be73085327\n# ╠═ced3ecc9-94ea-408f-bdef-d34802166663\n# ╟─c62adfb6-6ef8-45fd-992f-07bca59f82cd\n# ╟─03edae54-4368-4b81-8713-17f93bbb9ed9\n# ╟─e0b82e6c-043c-4e66-a2a4-ae0f3e4e5404\n# ╠═aa62f1e5-6af5-43f6-be11-665ed25986c0\n# ╟─540468dc-3f9f-457b-9b44-efb3ec036166\n# ╠═21e3adbb-0176-4963-bdfc-0ba2422af4bf\n# ╠═d27aef3b-bfe7-466a-9580-93fc53dcef18\n# ╟─02f638d9-ec2f-4072-9fb3-e6fabac1b1e6\n# ╠═481c5b7a-4660-4954-84f3-29d33bd73f3d\n# ╟─aba84742-a927-4ce5-9f7c-6e535db1ee47\n# ╟─aa7c4dfe-a3d4-448b-a559-1bc7b338a1dc\n# ╠═a97f9c8e-dbd3-4613-9c6e-c471340ea2d6\n# ╟─7c7430a0-d16e-485b-bbd9-7f231fee853a\n# ╟─cebe52b3-386c-4d31-8497-c19b6c742577\n# ╟─3d09d38a-ca72-43f2-bd85-17fc0e05a645\n# ╠═9257c879-d96f-4d2b-994e-d542617b0c65\n# ╟─307a7a29-afa6-4c4d-88ae-4f757aeba892\n# ╠═afdc442a-2931-4129-824e-98431e1d8be2\n# ╟─c42deea3-acf1-491a-97bd-fdc472917584\n# ╟─7c1f4a27-dfd7-428a-97ef-eac1784e8d6f\n# ╠═97111ccc-8a16-4e7d-adf7-0dcd90524be3\n# ╟─f45668b1-1cbd-48e6-9224-d469826e093b\n# ╠═52beb148-6214-4a03-a0cf-6c2a6da77d40\n# ╟─1ecbd400-0157-45ce-b1b8-db764012ba5e\n# ╟─191ba96e-2573-4bc1-a352-46a66e0a5c4f\n# ╠═82a757ad-566d-4c1d-8b3d-366ffd980fb4\n# ╟─3e550b71-4750-460b-be18-911a848a8f49\n# ╠═b0c3875b-ef07-4e92-a0a8-55f42b266c6b\n# ╟─58e021c6-500f-40d8-a388-a5732bc808b3\n# ╠═36bfd224-a13b-438c-9106-382c15a6a1d2\n# ╟─7f4c3ab8-041e-4ef0-bb2e-320f5293cdde\n# ╟─195c2df4-7e1c-49f8-871f-f76b985dab6d\n# ╟─32124f8a-f5cf-41d1-97a9-ce1d05145fde\n# ╠═507e1516-5433-49eb-831d-32426f30895e\n# ╟─eac67cc9-754b-4f7d-add8-93900a1b5b49\n# ╟─64224c6b-c5a0-44f2-b2a0-7f77759cb848\n# ╟─73c06bb1-be49-46bd-b7f1-c45cc56af7b4\n# ╟─ebfaa677-829b-4bf9-bdbb-19f3c87dd3a4\n# ╟─945f5a55-3026-4497-9ece-8af878c87788\n# ╠═57397ee4-9efc-48b3-b640-d2b7a10da633\n# ╟─8059a6a3-384a-4344-8a23-650ee0be10c2\n# ╟─f5b93929-2c59-4360-8c41-97a1324ba455\n# ╠═122196fa-45ca-4031-85eb-4afd4782de9e\n# ╟─e9dc1456-616b-4e4b-b209-9f6ba4c48607\n# ╟─f15d37a7-d962-4da0-977f-76729a3313be\n# ╟─28f195c4-4f61-4873-85d6-b4e3aaa3660f\n# ╠═3837e439-250b-4577-b0d7-93352ec19f6e\n# ╟─8255b5a9-cbe6-4604-bedd-0e366f311096\n# ╠═df9b701f-d314-4512-b2ea-1f6ae015166c\n# ╟─377f7527-a338-4526-bb24-9766c635e719\n# ╟─25f24754-16d4-4343-b54a-cf8ea1358ce9\n# ╟─570fd826-23fd-46ee-bdb4-58fb0c45719a\n# ╠═691410bb-0472-4800-a90d-29ddf947de3e\n# ╟─8cbb1c90-bd94-44b5-80b6-81d38f3e6252\n# ╠═c3065acf-6205-455f-ba74-ca51f3f6761b\n# ╟─9c392be9-1505-40bc-a290-68085a1c2700\n# ╟─d738bdcc-5f83-4dfa-a17f-e9ea23db2986\n# ╟─d55ce157-099c-4c1b-94db-62918f04e5fe\n# ╟─206f464b-55fe-46aa-85b7-8f0246a0aaad\n# ╟─6f72d1b2-63f6-4301-8272-bb2d6d2d049e\n# ╠═01201c37-0b79-46b1-a001-e716f5b3ba67\n# ╟─e3d37bc1-a119-4add-a111-899ee0caea05\n# ╟─6dff3f21-fac0-42e1-910a-f969a231374f\n# ╠═b26b8253-e6cd-49f4-81c5-2a3c2963a37c\n# ╟─e5dc123f-1596-4311-9398-f0cfe80a5342\n# ╟─7b9d26c2-899e-45e9-b664-39d5f1adfe3f\n# ╟─fc01d57f-c90b-4231-96be-ddd48656d55e\n# ╠═e05f16d6-eb50-49a9-bf14-95d63c9da7ff\n# ╟─3b232365-f2fe-4edb-a39f-3e37c8cbb666\n# ╠═1992595f-9976-4b18-bf9c-df8a73d30dc8\n# ╟─568862b3-6fce-426a-a9e2-e558adf3932a\n# ╟─52f9edd0-79b0-4a9a-9930-3a05d3aa2447\n# ╟─90d5244e-17be-4601-b922-8c254f1248bf\n# ╟─ae79ee89-d788-4612-8b1d-fc22d85c7744\n# ╠═3745c237-ba48-4f2c-959e-441484244764\n# ╟─6d061411-6f19-4119-aefb-cc380198b0ce\n# ╟─8def87d2-f10b-4a82-b353-a6477eeead9b\n# ╟─c74b3105-f480-4688-b85f-3e7dff70da3b\n# ╠═55438c09-1d94-4ff7-90c3-0cc6064a091e\n# ╟─bcc796c9-db11-4a09-a5f9-215127ac0938\n# ╟─92b2ecdd-9491-4f16-8cb9-bacbcf180280\n# ╠═83216915-cdcf-4f0f-829f-a5ff4c4b8da0\n# ╟─452872f9-2009-4733-b2d3-28f262ae19b7\n# ╟─29415ddc-e002-4f56-a169-95f7b1c36be9\n# ╟─fb23d6c6-b812-4fe1-b224-0014bedbd43f\n# ╠═1e53aa10-dff6-40d5-89e2-da194ffc2052\n# ╠═ac87ced2-986f-4e6c-80b2-104b25c171c2\n# ╠═14cca8ce-cc61-4fae-b871-21c3fd23d0ea\n# ╠═28fc8de4-749b-4093-b32f-c398f8d27d3d\n# ╠═57b422e5-0ad0-4674-bdd3-a8358bc7aaeb\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "9f1deb054894d9474c6a7f29abbb30367ac1ac72", "size": 44325, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ex2.jl", "max_stars_repo_name": "PsuAstro528/lab3-start", "max_stars_repo_head_hexsha": "adc592c7a3d00a2402ebe1943ab4a09c8d8cabfa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-20T16:12:26.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-20T16:12:26.000Z", "max_issues_repo_path": "ex2.jl", "max_issues_repo_name": "PsuAstro528/lab3-start", "max_issues_repo_head_hexsha": "adc592c7a3d00a2402ebe1943ab4a09c8d8cabfa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ex2.jl", "max_forks_repo_name": "PsuAstro528/lab3-start", "max_forks_repo_head_hexsha": "adc592c7a3d00a2402ebe1943ab4a09c8d8cabfa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.5535224154, "max_line_length": 683, "alphanum_fraction": 0.7465313029, "num_tokens": 17288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34158249943831703, "lm_q2_score": 0.16885695214168317, "lm_q1q2_score": 0.05767857976009242}} {"text": "\"\"\"\natleast2d \\\\\n\nFor formatting the dimensions of the random variables to at least 2 dimensions \\\\\nArguments: random_variable \\\\\nReturns: A 2-d version of the variable \\\\\n\"\"\"\nfunction atleast2d(random_variable::Array)\n is_one_d = 1 == ndims(random_variable)\n return is_one_d ? reshape(random_variable, size(random_variable)[1], 1) : random_variable\nend\n", "meta": {"hexsha": "3a2fa21f7a0910553404554a522b64420434f93b", "size": 361, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/atleast2d.jl", "max_stars_repo_name": "thomasjdelaney/Jentropy.jl", "max_stars_repo_head_hexsha": "7d991182ea3deb1643907edda77b02782da8b933", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-05T18:19:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-05T18:19:27.000Z", "max_issues_repo_path": "src/atleast2d.jl", "max_issues_repo_name": "thomasjdelaney/Jentropy.jl", "max_issues_repo_head_hexsha": "7d991182ea3deb1643907edda77b02782da8b933", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/atleast2d.jl", "max_forks_repo_name": "thomasjdelaney/Jentropy.jl", "max_forks_repo_head_hexsha": "7d991182ea3deb1643907edda77b02782da8b933", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0833333333, "max_line_length": 91, "alphanum_fraction": 0.7479224377, "num_tokens": 89, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.11757214127540647, "lm_q1q2_score": 0.05740852433415701}} {"text": "### A Pluto.jl notebook ###\n# v0.14.4\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 1d460401-7c48-4718-914e-ba3fc9f7950a\nbegin\n import Pkg\n # activate a clean environment\n Pkg.activate(mktempdir())\n\n Pkg.add([\n Pkg.PackageSpec(name=\"PlutoUI\"),\n Pkg.PackageSpec(name=\"Unitful\"),\n # ... keep adding your packages\n ])\n\n using PlutoUI\n\tusing Unitful\n\t\n\tfunction Image(filepath::String)\n\t\t@assert !isempty(filepath)\n\t\tPlutoUI.LocalResource(joinpath(split(@__FILE__, '#')[1] * \".assets\", filepath))\n\tend\nend;\n\n# ╔═╡ baaa0f44-a9d8-11eb-0d0d-53b78cd74315\nmd\"# Physics II Final Exam Review\n\n- PHYS 1062 Section 003 (Spring 2021)\n- Instructor: Zbigniew Dziembowski\n- Temple University\"\n\n# ╔═╡ c565da05-80ca-4b72-af73-d5da2f1c2abc\nmd\"### Information about the exam\n\n- Please print out and bring to the exam two copies of the IRDEA worksheet.\n The worksheet is available for download in the *Final exam* Module.\n It includes a one sectence honesty statement which you have to sign.\n\n- The exam will have two parts:\n - A quiz consisting of 25 multiple choice questions covering **units 5 through 12**.\n The quiz setting will be such that there will be only one attempt given.\n You will see one question at a time and the questions will be locked after answering.\n The quiz will be available on Canvas.\n - 2 word problems covering **units 9-12**.\n These problems, where you are expected to show your explanations, must be solved using the IRDEA worksheet.\n The solutions must be uploaded for grading on Canvas (like the in-class problem solutions).\n\n- Final exam is worth 234 pts (125pts/quiz and 54.5 pts/problem)\n\n- Extra Credit\n - 4 pts extra credit per problem will be given, if a solution is submitted on time\n and on the IRDEA worksheet with signed the one sentence honesty statement.\n\n- Penalties\n - 4 pts penalty per problem will be applied if a solution is uploaded to Canvas less than 10 mins LATE.\n - 8 pts penalty per problem if uploaded to Canvas 10-20 mins LATE.\n - Solution is not graded if it is uploaded to Canvas more than 20 mins. LATE.\n\n- Do not wait to the last moment. Upload each solution once you completed it!\n\n- After the exam, we reserve the right to ask anyone to work out a few new problems with us to spot check the exam inconsistency.\n\"\n\n# ╔═╡ a1c99c25-e72e-4c4f-9ee9-855dad795483\nmd\"### How to review and prepare for the final exam\n\n1. Review the lecture notes for Unit 5 through 12.\n Especially, go through the quick-check questions in the posted lecture notes.\n Then take the practice quiz to be posted on Canvas by Sunday, April 25th.\n\n\n2. The contents of the two word-problem section of the exam will be limited to the contents of Units 9 through 12.\n\n To prepare for this section of the exam, redo, using a copy of the RIDEA worksheet, all exercises and problems in the DT and PSW homework for Unit 9 through 12.\n Use the wording of the assignments as in the back of Chapters 29, 30, 31 and 34, respectively.\n Check your answers against the answers to those exercises and problems as given in the file posted on Canvas (\\\"DT-PSW list for Unit XX with answers\\\") in the module **Final exam.**\"\n\n# ╔═╡ c5cf2733-8d62-4f97-9c6c-97c6bce90b02\nmd\"### Electricity and Magnetism formulas\"\n\n# ╔═╡ 7abb1db1-d637-446c-9e55-3457db3db17e\nmd\"$$\\begin{gather*}\n\\vec{E} = k \\frac{q}{r^2} \\hat{r}; \\qquad \\vec{F} = q\\vec{E} \\\\\nV_B - V_A = -\\int_A^B \\vec{E} \\cdot d\\vec{r} \\\\\nV = k \\frac{q}{r}; \\qquad U = qV = k\\frac{q_1q_2}{r} \\\\\nC \\equiv \\frac{Q}{\\Delta V_C} = \\frac{\\epsilon_0 A}{d} \\\\\nU = \\frac{1}{2} \\frac{Q^2}{C} \\\\\nI = \\frac{dQ}{dt} \\qquad J = v_d e n_e \\\\\nI = \\frac{\\Delta V}{R} \\qquad R = \\rho \\frac{L}{A} \\qquad P = I \\mathcal{E} \\\\\n\\frac{1}{C_{\\text{eq}}} = \\sum \\frac{1}{C_i} \\qquad C_{\\text{eq}} = \\sum C_i \\\\\nR_{\\text{eq}} = \\sum R_i \\qquad \\frac{1}{R_{\\text{eq}}} = \\sum \\frac{1}{R_i} \\\\\n\\vec{F} = I\\vec{L} \\times \\vec{B} \\qquad \\vec{F} = q\\vec{v} \\times \\vec{B} \\\\\nr = \\frac{mv}{qB} \\qquad f = \\frac{qB}{2\\pi m} \\\\\nF = \\frac{\\mu_0}{2\\pi} \\frac{I_1 I_2}{d} L\n\\end{gather*}$$\"\n\n# ╔═╡ be1d2a6e-8c24-4a1e-b84b-aabfad8e6135\nmd\"$$\\begin{gather*}\n\\tau = NIAB \\sin{\\theta} \\\\\nB = \\frac{\\mu_0}{2\\pi} \\frac{I}{r} \\qquad B = \\frac{\\mu_0 I a^2}{2(x^2 + a^2)^{3/2}} \\\\\n\\vec{B} = \\frac{\\mu_0}{2\\pi} \\frac{\\vec{\\mu}}{z^3} \\qquad B = \\frac{\\mu_0 IN}{L} \\\\\n\\Phi_{\\text{m}} = \\int \\vec{B} \\cdot d\\vec{A} \\qquad \\mathcal{E} = \\left|\\frac{d\\Phi_{\\text{m}}}{dt}\\right| \\\\\nE_{\\text{inside}} = \\frac{r}{2} \\left|\\frac{dB}{dt}\\right| \\qquad V_S = \\left(\\frac{N_S}{N_P}\\right) V_P \\\\\nU_L = \\frac{1}{2} LI^2 \\qquad L_{\\text{sol}} = \\frac{\\mu_0 N^2 A}{\\ell} \\\\\n\\mathcal{E} = NB \\omega A \\sin{\\omega t} \\\\\nI = \\frac{P}{A} = S_{\\text{avg}} = \\frac{1}{2c\\mu_0} {E_0}^2 = \\frac{c\\epsilon_0}{2} {E_0}^2 \\\\\nk = \\frac{2\\pi}{\\lambda} \\qquad \\omega = 2\\pi f \\qquad f\\lambda = \\frac{\\omega}{k} = v \\\\\nv = \\frac{\\omega}{k} = \\frac{1}{\\sqrt{\\epsilon_0 \\mu_0}} \\qquad E = \\frac{\\omega}{k} B = cB\n\\end{gather*}$$\"\n\n# ╔═╡ 6c9182b4-2bf5-40a8-8a7e-ecfb1f7e59f3\nmd\"#### Relevant constants and conversion factors\n\n$$\\begin{gather*}\nk \\approx 9.0 \\times 10^9 \\text{ N} \\cdot \\text{m}^2 / \\text{C}^2 \\\\\n\\mu_0 = 4\\pi \\times 10^{-7} \\text{ T} \\cdot \\text{m} / \\text{A} \\\\\n\\epsilon_0 = \\frac{1}{4\\pi k} = 8.85 \\times 10^{-12} \\text{ C}^2 / \\text{N}\\cdot\\text{m}^2 \\\\\n1 \\text{ eV} = 1.602 \\times 10^{-19} \\text{ J} \\\\\ne = 1.60 \\times 10^{-19} \\text{ C} \\qquad c = 3.00 \\times 10^8 \\text{ m/c} \\\\\nm_e = 9.11 \\times 10^{-31} \\text{ kg} \\qquad m_p = 1.67 \\times 10^{-27} \\text{ kg}\n\\end{gather*}$$\n\"\n\n# ╔═╡ b670ab02-1fe7-4204-9747-237348707d97\nbegin\n\tk = 9.0e9u\"N*m^2/C^2\"\n\tμ0 = 1.26e-6u\"T*m/A\"\n\tϵ0 = 8.85e-12u\"C^2/(N*m^2)\"\n\te = 1.60e-19u\"C\"\n\tc = 3.00e8u\"m/s\"\n\tme = 9.11e-31u\"kg\"\n\tmp = 1.67e-27u\"kg\"\n\t\n\t# Other constants\n\tB_earth = 50e-6u\"T\" # Earth's magnetic field\n\tg = 9.8u\"m/s^2\"\nend;\n\n# ╔═╡ 3240dda1-8d4c-4551-8878-8c2ddd9f12d1\nmd\"### Ray Optics\n| Medium | $n$ |\n| :--- | :--- |\n| Vacuum | 1.00 exact |\n| Air (actual) | 1.0003 |\n| Air (accepted) | 1.00 |\n| Water | 1.33 |\n| Ethyl alcohol | 1.36 |\n| Oil | 1.46 |\n| Glass (typical) | 1.50 |\n| Polystyrene plastic | 1.59 |\n| Cubic zirconia | 2.18 |\n| Diamond | 2.41 |\n| Silicon (infrared) | 3.50 |\n\n$$\\begin{gather*}\nn = \\frac{c}{v} \\qquad n_1 \\sin{\\theta_1} = n_2 \\sin_{\\theta_2} \\\\\n\\frac{1}{s} + \\frac{1}{s'} = \\frac{1}{f} \\\\\nM = \\frac{h'}{h} = -\\frac{s'}{s} \\\\\n|f| = \\frac{R}{2}\n\\end{gather*}$$\n\"\n\n# ╔═╡ 8a56ceb5-dbd9-4950-bbfe-50b56c682487\nmd\"# Notebook environment\"\n\n# ╔═╡ 98b7f219-578b-4717-8dfa-5f22f86c04b2\nmd\"# Topics covered\n\n- Unit 5: Chapters 22 and 23---Electric Charges and Forces, The Electric Field\n- Unit 6: Chapters 25 and 26---The Electric Potential, Potential and Field\n- Unit 7: Chapter 27---Current and Resistance\n- Unit 8: Chapter 28---Fundamentals of Circuits\n- Unit 9: Chapter 29---The Magnetic Field\n- Unit 10: Chapter 30---Electromagnetic Induction\n- Unit 11: Chapter 31---Electromagnetic Fields and Waves\n- Unit 12: Chapter 34---Ray Optics\"\n\n# ╔═╡ f6b01ecd-9629-422c-800e-a41512fa9933\nmd\"# QuickChecks\"\n\n# ╔═╡ 81d41ebd-9c50-49a1-b77d-1f6c600477e7\nmd\"## Unit 5 The Electric Charge, Force and Field\"\n\n# ╔═╡ 067e90ac-b370-4c53-b1d8-8ee65189b036\nmd\"### Unit 5 Part 1 QuickCheck #1\n\nWhich is the direction of the net force on the charge at the lower left?\"\n\n# ╔═╡ 179020bb-048a-4040-b517-0c081a5b68c0\nImage(\"Unit5/P1QC1.png\")\n\n# ╔═╡ 8065e0db-4aa8-447f-a130-49feedcddad7\nmd\"**Answer:** B, down to the left\"\n\n# ╔═╡ 5745f4ea-219d-4e60-b269-9e08f010836a\nmd\"### Unit 5 Part 2 QuickCheck #1\n\nWhat is the direction of the net electric field at the dot?\"\n\n# ╔═╡ 885d48fa-4a05-4468-8492-0cae4bfb7b26\nImage(\"Unit5/P2QC1.png\")\n\n# ╔═╡ 2d690e4b-3d09-4907-99de-5f0ef4662b7e\nmd\"**Answer:** D, to the right\"\n\n# ╔═╡ eae4eef0-1701-406f-966d-736a2b2381f5\nmd\"### Unit 5 Part 2 QuickCheck #2\n\nAn electron is in the plane that bisects a dipole.\nWhat is the direction of the electric force on the electron?\"\n\n# ╔═╡ 9ca8f846-5d5b-4b28-85b6-90c5f9c068b6\nImage(\"Unit5/P2QC2.png\")\n\n# ╔═╡ 04912a55-5871-4917-8c95-7f03bd4abf1d\nmd\"**Answer:** A, up because the electron goes towards the proton\"\n\n# ╔═╡ 42f03b7e-9fec-40bc-8d22-e594a22ab54e\nmd\"### Unit 5 Part 3 QuickCheck #1\n\nThree points inside a parallel-plate capacitor are marked.\nWhich is true?\n\nA. $E_1 > E_2 > E_3$\n\nB. $E_1 < E_2 < E_3$\n\nC. $E_1 = E_2 = E_3$\n\nD. $E_1 = E_3 > E_2$\n\"\n\n# ╔═╡ 34b75779-b546-4628-ac0a-1d8fedc231eb\nImage(\"Unit5/P3QC1.png\")\n\n# ╔═╡ fb93dd3c-de36-4087-9870-8365161f7d1f\nmd\"**Answer:**\nC. $E_1 = E_2 = E_3$\"\n\n# ╔═╡ ab703047-2e82-4c13-a9d9-c97ffd42af67\nmd\"## Unit 6 The Electric Potential, and Capacitors\"\n\n# ╔═╡ 253d5697-9088-424f-aa2e-c5df2c7675bf\nmd\"### Unit 6 Part 2 QuickCheck #1\n\nAt the midpoint between these two equal but opposite charges,\n\nA. $\\vec{E} = \\vec{0}; \\;V = 0$\n\nB. $\\vec{E} = \\vec{0}; \\;V > 0$\n\nC. $\\vec{E} = \\vec{0}; \\;V < 0$\n\nD. $\\vec{E}$ points right; $V = 0$\n\nE. $\\vec{E}$ points left; $V = 0$\n\"\n\n# ╔═╡ fcdb7ea5-6203-4e74-b746-4470052b5f99\nImage(\"Unit6/P2QC1.png\")\n\n# ╔═╡ 5db75338-4b19-4037-942d-979856662d6c\nmd\"**Answer:** D. $\\vec{E}$ points right; $V = 0$\n\n**Explanation:** $V = \\frac{k q_1}{r} + \\frac{k q_2}{r} = 0$\"\n\n# ╔═╡ 74378daa-7994-403e-9c41-86bae271a74d\nmd\"### Unit 6 QuickCheck #2 (Exercise 25.6)\nWhat is the electrostatic energy of the group of charges in figure below?\n\nA. positive\n\nB. negative\n\nC. zero\n\"\n\n# ╔═╡ af3ab252-16c6-4e6f-bdc6-9a01fede5a30\nImage(\"Unit6/P2QC2.png\")\n\n# ╔═╡ 64bbc192-28dd-4db4-8dab-1cde2a031bc5\nmd\"**Answer:** C. zero\n\n**Explanation:**\n\n$\\begin{gather*}\nU = \\;? \\\\\nU = k \\sum_{i 1 \\text{ W})$.\"\n\n# ╔═╡ 060fd1a0-5548-4eb4-b4c2-f2db077e0d50\nmd\"### Unit 8 Part 1 QuickCheck #2\n\nWhich bulb is brighter?\n\nA. The 60 W bulb\n\nB. The 100 W bulb\n\nC. Their brightnesses are the same.\n\nD. There's not enough information to tell.\"\n\n# ╔═╡ 8eb2caa8-5341-40a7-8ae5-aad8e44c1af1\nImage(\"Unit8/P1QC2.png\")\n\n# ╔═╡ 860bbf33-9025-44ee-aa26-7217f0bc7562\nmd\"**Answer:** A. The 60 W bulb\n\n**Explanation:**\n\n$\\begin{gather*}\nV = 120 \\text{ V} \\\\\nP_{60} = 60 \\text{ W} \\\\\nP_{100} = 100 \\text{ W} \\\\\nP_R = \\frac{V^2}{R} \\implies R = \\frac{(\\Delta V_R)^2}{P_R} \\\\\nR_{60} = \\frac{V^2}{60} \\;\\Omega \\\\\nR_{100} = \\frac{V^2}{100} \\;\\Omega \\\\\nV = IR \\\\\nR_{60} > R_{100} \\implies V_{60} > V_{100}\n\\end{gather*}$\"\n\n# ╔═╡ 28acdfbe-1020-4921-8c6c-0e38d0732d78\nmd\"### Unit 8 Part 2 QuickCheck #1\n\nThe battery current $I$ is\n\nA. 3 A\n\nB. 2 A\n\nC. 1 A\n\nD. 2/3 A\n\nE. 1/2 A\"\n\n# ╔═╡ e06efb86-5366-49c3-acb6-f9b209bf5d81\nImage(\"Unit8/P2QC1.png\")\n\n# ╔═╡ 6c9233eb-058a-4e8a-9c9b-22964e210dd1\nmd\"**Answer:** 2/3 A\n\n**Explanation:** Use Ohm's Law $V = IR$\"\n\n# ╔═╡ c83063bd-0bba-47e7-b869-e169d6e9c03e\nmd\"### Unit 8 Part 2 QuickCheck #2\n\nWhat does the (ideal) ammeter read?\n\nA. 6 A\n\nB. 3 A\n\nC. 2 A\n\nD. Some other value\n\nE. Nothing because this will fry the meter.\"\n\n# ╔═╡ c9102584-2196-4483-b79f-60089ad9e1b4\nImage(\"Unit8/P2QC2.png\")\n\n# ╔═╡ b30d503e-ab6c-4515-9a68-81327795aa6c\nmd\"**Answer:** E. Nothing because this will fry the meter.\n\n**Explanation:** Since the ammeter is ideal, its resistance $R = 0 \\implies I = \\lim_{R \\to 0} \\frac{V}{R} = \\infty$\"\n\n# ╔═╡ 85e2b232-6a09-4621-ab97-e2345b676999\nmd\"### Unit 8 Part 2 QuickCheck #3\n\nThe battery current $I$ is\n\nA. 3 A\n\nB. 2 A\n\nC. 1 A\n\nD. 2/3 A\n\nE. 1/2 A\"\n\n# ╔═╡ 69bdb37e-2f06-4c78-a5bc-c3fce3cf6be8\nImage(\"Unit8/P2QC3.png\")\n\n# ╔═╡ f9ba57aa-4113-40e0-af24-8d7066baef4c\nmd\"**Answer:** 3 A\n\n**Explanation:** The problem involves resistors in parallel and Ohm's Law.\n\n$\\begin{gather*}\nI = \\;? \\\\\nV = 12 \\text{ V} \\\\\n\\frac{1}{R} = \\frac{1}{12} + \\frac{1}{6} = \\frac{3}{12} \\implies R = 4 \\\\\nV = IR \\implies I = \\frac{V}{R} = \\frac{12}{4} = 3 \\text{ A}\n\\end{gather*}$\n\"\n\n# ╔═╡ cdc4c352-a21c-4d88-8a6e-28da5974e893\nmd\"### Unit 8 Part 2 QuickCheck #4\n\nWhat does the (ideal) voltmeter read?\n\nA. 6 V\n\nB. 3 V\n\nC. 2 V\n\nD. Some other value\n\nE. Nothing because this will fry the meter.\n\"\n\n# ╔═╡ bc7ebdc7-3614-43ad-bb1c-695f535c339b\nImage(\"Unit8/P2QC4.png\")\n\n# ╔═╡ 3badd910-d0be-435d-8b61-751d2fc46984\nmd\"**Answer:** A. 6 V\n\n**Answer:** An ideal voltmeter will have very high resistance to measure the voltage of the circuit.\"\n\n# ╔═╡ f5871103-8943-4085-8ec8-f7c19155262c\nmd\"## Unit 9 Magnetism: Force and Field\"\n\n# ╔═╡ 64256f0e-f61a-41d9-9f07-f53f12b81d9f\nmd\"### Unit 9 Part 1 QuickCheck #1\n\nA long straight wire extends into and out of the screen.\nThe current in the wire is\n\nA. Into the screen.\n\nB. Out of the screen.\n\nC. There is no current in the wire.\n\nD. Not enough info to tell the direction.\"\n\n# ╔═╡ 56988b0d-40f0-485c-bfd1-468431e2f906\nImage(\"Unit9/P1QC1.png\")\n\n# ╔═╡ baf581de-7077-4c25-a5df-b5e82490b113\nmd\"**Answer:** Out of the screen.\n\n**Explanation:** Use the right-hand rule along the direction of the magnetic field.\"\n\n# ╔═╡ 11c087b0-7823-41ac-8034-e66875bcaec1\nmd\"### Unit 9 Part 1 QuickCheck #2\n\nWhat is the direction of the magnetic field at the position of the dot?\n\nA. Into the screen\n\nB. Out of the screen\n\nC. Up\n\nD. Down\n\nE. Left\"\n\n# ╔═╡ ad23f43f-c8ac-48fd-9b21-901658710684\nImage(\"Unit9/P1QC2.png\")\n\n# ╔═╡ a59c5606-b60e-44c8-a7e3-b84cd89b322c\nmd\"**Answer:** C. Up\n\n**Explanation:** Use the right-hand rule for the cross product $\\vec{v} \\times \\hat{r}$ where $\\hat{r}$ is the distance between the two points and determine the direction of the magnetic field at the given point.\"\n\n# ╔═╡ 69065726-b456-4ab1-b8a6-22e638304388\nmd\"### Unit 9 Part 2 QuickCheck #1\n\nCompared to the magnetic field at point A, the magnetic field at point B is\n\nA. Half as strong, same direction.\n\nB. Half as strong, opposite direction.\n\nC. One-quarter as strong, same direction.\n\nD. One-quarter as strong, opposite direction.\n\nE. Can't compare without knowing $I$.\"\n\n# ╔═╡ 47e713c1-0741-4135-ad0c-8b7ad003c141\nImage(\"Unit9/P2QC1.png\")\n\n# ╔═╡ 45baa2c9-e2a9-44fc-a6a3-9e1b149d3ec6\nmd\"**Answer:** B. Half as strong, opposite direction.\n\n**Explanation:** The magnetic field of a current carrying wire is\n\n$B = \\frac{\\mu_0}{2\\pi} \\frac{I}{r}$\"\n\n# ╔═╡ a44466e8-0954-4738-9836-e7d445d41a91\nmd\"### Unit 9 Part 3 QuickCheck #1\n\nWhat is the current direction in this loop?\nAnd where is the north magnetic pole of this current loop?\n\nA. Current CW; north pole on top\n\nB. Current CW; north pole on bottom\n\nC. Current CCW; north pole on top\n\nD. Current CCW; north pole on bottom\"\n\n# ╔═╡ 13f7bece-837b-473e-bb86-df55d3f5dbdf\nImage(\"Unit9/P3QC1.png\")\n\n# ╔═╡ 6917fdb5-0538-4995-9ac5-14d7fc92b903\nmd\"**Answer:** B. Current CW; north pole on bottom\n\n**Explanation:** Use the right-hand rule.\"\n\n# ╔═╡ 018a2522-f201-44a7-8f63-d67411970a90\nmd\"### Unit 9 Part 5 QuickCheck #1\n\nThe direction of the magnetic force on the proton is\n\nA. To the right.\n\nB. To the left.\n\nC. Into the screen.\n\nD. Out of the screen.\n\nE. The magnetic force is zero.\"\n\n# ╔═╡ ebe19088-8374-441c-9c1b-c00194737814\nImage(\"Unit9/P5QC1.png\")\n\n# ╔═╡ 30625a27-4961-4eff-be88-27a351a3db12\nmd\"**Answer:** D. Out of the screen.\n\n**Explanation:** Use the right-hand rule for $\\vec{v} \\times \\vec{B}$\"\n\n# ╔═╡ 66bd1832-dd76-43fa-ab08-018c8e726885\nmd\"### Unit 9 Part 5 QuickCheck #2\n\nThe direction of the magnetic force on the electron is\n\nA. Upward.\n\nB. Downward.\n\nC. Into the screen.\n\nD. Out of the screen.\n\nE. The magnetic force is zero.\"\n\n# ╔═╡ 08c4b0d3-a431-46dd-a0ae-3bd5a59b81e3\nImage(\"Unit9/P5QC2.png\")\n\n# ╔═╡ eff73afd-3ded-49d2-9411-ec11933fb31f\nmd\"**Answer:** E. The magnetic force is zero.\n\n**Explanation:** Use the right-hand rule for $\\vec{v} \\times \\vec{B}$\"\n\n# ╔═╡ 6e2b45e2-67bd-4512-9b3c-6f25dc75824f\nmd\"### Unit 9 Part 6 QuickCheck #1\n\nThe horizontal wire can be levitated---held up against the force of gravity---if the current in the wire is\n\nA. Right to left.\n\nB. Left to right.\n\nC. It can't be done with this magnetic field.\"\n\n# ╔═╡ 9cf0faf9-ea42-45da-9788-975cfecdca37\nImage(\"Unit9/P6QC1.png\")\n\n# ╔═╡ 67aca9a5-da3f-4a2c-9159-2dfb922217f8\nmd\"**Answer:** B. Left to right\n\n**Explanation:** Use the right-hand rule for $\\vec{v} \\times \\vec{B}$\"\n\n# ╔═╡ 37aeddcf-e1cf-40a0-925e-20d600f24845\nmd\"### Unit 9 Part 6 QuickCheck #2\n\nIf released from rest, the current loop will\n\nA. Move upward.\n\nB. Move downward.\n\nC. Rotate clockwise.\n\nD. Rotate counterclockwise.\n\nE. Do something not listed here.\"\n\n# ╔═╡ 5fb3d735-8df5-4e69-aa47-ff467dee9047\nImage(\"Unit9/P6QC2.png\")\n\n# ╔═╡ c4f15be9-ba69-4b9f-9b5a-407a975c2fbe\nmd\"**Answer:** D. Rotate counterclockwise.\n\n**Explanation:** Use the right-hand rule for $\\vec{v} \\times \\vec{B}$ on both ends of the current loop to determine the direction of each end.\"\n\n# ╔═╡ 2c330d4d-8fa2-4c3f-a5b8-8a3ac19fd075\nmd\"## Unit 10 Electromagnetic Induction\"\n\n# ╔═╡ a2fbf237-3b84-4331-be33-e13c0f726838\nmd\"### Unit 10 Part 2 QuickCheck #1\n\nAn induced current flows clockwise as the metal bar is pushed to the right.\nThe original magnetic field points\n\nA. Up.\n\nB. Down.\n\nC. Into the screen.\n\nD. Out of the screen.\n\nE. To the right.\"\n\n# ╔═╡ 84cdc818-8a8c-4888-b3bd-12399e60a739\nImage(\"Unit10/P2QC1.png\")\n\n# ╔═╡ b759a10f-6110-4e66-8121-e1c8bf24efee\nmd\"**Answer:** C. Into the screen\n\n**Explanation:** Apply Lenz's Law for direction of current induced in a loop.\"\n\n# ╔═╡ 9c245886-b491-4adf-9ccd-0f8d20326949\nmd\"Unit 10 Part 2 QuickCheck #2\n\nThe current in the straight wire is decreasing.\nWhich is true?\n\nA. There is a clockwise induced current in the loop.\n\nB. There is a counterclockwise induced current in the loop.\n\nC. There is no induced current in the loop.\"\n\n# ╔═╡ c352a601-03e9-4f47-9d8e-2e7e806a7433\nImage(\"Unit10/P2QC2.png\")\n\n# ╔═╡ d085be3a-89ec-4672-a47d-f5f2c020885b\nmd\"**Answer:** A. There is a clockwise induced current in the loop.\n\n**Explanation:** Apply Lenz's law for direction of current induced in a loop for decreasing magnetic flux. To oppose the decrease (pointing out of the screen), the magnetic field of the induced current must point into the screen.\"\n\n# ╔═╡ 3d7c7ea7-24a4-4acc-8238-e71118fef4f1\nmd\"## Unit 11 EM Fields and Waves\"\n\n# ╔═╡ 27a07162-335c-4d3a-9771-2a3793490631\nmd\"### Unit 11 Part 1 QuickCheck #1\"\n\n# ╔═╡ 04beeb35-c9b8-4aca-9afa-6d9cefaacc62\nImage(\"Unit11/P1QC1.png\")\n\n# ╔═╡ 2f72f311-4bb9-4459-a1ee-3a3b5339b13f\nmd\"**Answer**: A.\"\n\n# ╔═╡ 082f1121-811b-4404-b561-6ce9ca6a05ce\nmd\"### Unit 11 Part 1 QuickCheck #2\n\nIn which direction is this electro-magnetic wave traveling?\n\nA. Up\n\nB. Down\n\nC. Into the screen\n\nD. Out of the screen\n\nE. These are not allowable fields for an electromagnetic wave\"\n\n# ╔═╡ 4584596e-c66f-45b3-ad3d-3042f13a1eca\nImage(\"Unit11/P1QC2.png\")\n\n# ╔═╡ 99a92b4f-0a27-4681-a372-e6db84db033a\nmd\"**Answer:** A. Up\n\n**Explanation:** Use the right-hand rule for $\\vec{E} \\times \\vec{B}$ to determine the direction of the electro-magnetic wave.\"\n\n# ╔═╡ 3a92f0e7-983c-433d-a83d-7c4e1a52a206\nmd\"### Unit 11 Part 2 QuickCheck #1\"\n\n# ╔═╡ ae445aa3-dcd9-4d97-87f7-7be0a2287cf3\nImage(\"Unit11/P2QC1.png\")\n\n# ╔═╡ 6c521a07-2a6b-4ce8-a772-68b511bddf50\nmd\"**Answer:** A.\n\n**Explanation:** Use the right-hand rule where $\\vec{E} \\times \\vec{B}$ determines the direction of the wave.\"\n\n# ╔═╡ 90a8d78d-cdf9-4485-ba31-1364e2c920ae\nmd\"## Unit 12 Ray Optics\"\n\n# ╔═╡ 1f9d99d8-d613-4e62-9d46-5ebc61b029d6\nmd\"### Unit 12 Part 1 QuickCheck #1\n\nA laser beam passing from medium 1 to medium 2 is refracted as shown.\nWhich is true?\n\nA. $n_1 < n_2$\n\nB. $n_1 > n_2$\n\nC. There's not enough information to compare $n_1$ and $n_2$.\"\n\n# ╔═╡ 141ea713-8276-4799-8e9c-f46f14e30c44\nImage(\"Unit12/P1QC1.png\")\n\n# ╔═╡ 59508d51-2fab-4cab-816c-6d0c88979af8\nmd\"**Answer:** B. $n_1 > n_2$\n\n**Explanation:** The light bends away from the normal.\"\n\n# ╔═╡ 685e68c4-2be2-4fc7-b22f-9dc78b231236\nmd\"### Unit 12 Part 2 QuickCheck #1\n\nIn an optical setup consisting of a single mirror and an object we measure the magnification factor $m = +3$.\nWe can conclude that the image is:\n\nA. Inverted and virtual\n\nB. Inverted and real\n\nC. Upright and virtual\n\nD. Upright and real\"\n\n# ╔═╡ f0d975f2-dc73-476a-9dec-6c7939511066\nmd\"**Answer:** Upright and virtual\n\n**Explanation:** The mirror must be concave to produce an enlarged image. The image must be upright since the magnification is positive. The image is only upright with the condition that the object's distance from the mirror is less than the focal length, i.e., $s < f$. The image will form behind the mirror so it will be virtual.\"\n\n# ╔═╡ d1a284e5-e3d9-4d9c-b350-f6a9f9d4bf23\nmd\"### Unit 12 Part 3 QuickCheck #1\n\nIn an optical setup consisting of a single lens and an object we measure the magnification factor $m = -0.5$.\nWe can conclude that object in this setup is:\n\nA. Between lens and focal point\n\nB. Between focal point and point of twice the focal length\n\nC. Exactly at point of twice the focal length\n\nD. At distance greater than twice the focal length\"\n\n# ╔═╡ a76b95fb-bf1e-4fea-ae0b-927017a78d1b\nmd\"**Answer:** D. At distance greater than twice the focal length\n\n**Explanation:** The image must be inverted, so a converging lens must be used. Use two rays to determine the height of the image: one passing through the lens bending towards the focal point and another passing through the center of the lens. Notice that the image will only get smaller for distances larger than $2f$.\"\n\n# ╔═╡ 368b2131-d30c-42ae-9550-b51073e7592b\nmd\"# Final Practice Quiz\"\n\n# ╔═╡ 0acf5486-3702-4e8a-889e-871916d2ecf3\nmd\"### Question 1\n\nWhich is the direction of the net force on the charge at the lower left?\n\n- A\n\n- D\n\n- B\n\n- C\n\n- E. None of these.\"\n\n# ╔═╡ bfef7588-5c90-4a37-967e-660eb3e5efcd\nImage(\"Unit5/P1QC1.png\")\n\n# ╔═╡ 86fa33b9-17da-4322-b195-fdc99687c518\nmd\"**Answer:** B\n\n**Explanation:** Apply the principle of superposition.\"\n\n# ╔═╡ 9fdb361f-cb53-4270-a59c-6b967da468ea\nmd\"### Question 2\n\nWhich is the direction of the net force on the charge at the top?\n\n- A\n\n- D\n\n- C\n\n- E. None of these.\n\n- B\"\n\n# ╔═╡ 4c54fa63-06a1-4519-8104-aea78a2bbfbe\nImage(\"Unit5/P2QC1.png\")\n\n# ╔═╡ a68a80e3-b74e-4dbf-93ce-2892bc6dafd5\nmd\"**Answer:** D\n\n**Explanation:** The positive charge pushes, the negative charge pulls. Their vertical forces cancel each other out.\"\n\n# ╔═╡ cda191c4-afb2-4512-a930-171f5757a094\nmd\"### Question 3\n\nA uniform electric field, with a magnitude of 500 V/m, is directed parallel to the +x axis.\nIf the potential at x = 5.0 m is 2500 V, what is the potential at x = 2.0 m?\n\n- 1000V\n\n- 2000V\n\n- 4000V\n\n- 500V\"\n\n# ╔═╡ c721d98c-3586-450c-a22f-a4ff048d12c6\nmd\"\n##### Incorrect\n**Answer:** 1000V\"\n\n# ╔═╡ b55d0b05-3713-46ea-819e-d180e662a47e\nmd\"##### Correct answer\n4000V\n\n**Explanation:**\nThe electric field's magnitude $E$ is the rate at which the potential $U$ is decreasing.\nThen the potential at 2.0 m must be greater than the potential at 5.0 m.\n\n$\\begin{gather*}\nE = 500 \\text{ V/m} \\\\\nU_1 = 2500 \\text{ V} \\\\\nx_1 = 5.0 \\text{ m} \\\\\nx_0 = 2.0 \\text{ m} \\\\\nU_2 = U_1 + E(x_1 - x_0) = 2500 + 500(3) = 4000 \\text{ V}\n\\end{gather*}$\"\n\n# ╔═╡ 16f0dd9e-f5bb-4173-a07c-7feba801837f\nlet\n\tE = 500\n\tU1 = 2500\n\tx1 = 5.0\n\tx0 = 2.0\n\tU2 = U1 + E * (x1 - x0)\nend\n\n# ╔═╡ b87d87a8-da10-4af4-94af-868947f45d02\nmd\"### Question 4\n\nA parallel-plate capacitor is connected to a battery and becomes fully charged.\nThe capacitor is then disconnected, and the separation between the plates is increased in such a way that no charge leaks off.\nThe energy stored in this capacitor has\n\n- increased.\n\n- become zero.\n\n- decreased.\n\n- not changed.\"\n\n# ╔═╡ e664b06c-2924-423c-9f1b-52174fca7cc3\nmd\"**Answer:** increased.\n\n**Explanation:** $C = \\frac{\\epsilon_0 A}{d}$\"\n\n# ╔═╡ 7ec6edf3-7b6d-4ea2-8a4f-86dd2178eb91\nmd\"### Question 5\n\nThe plates of a parallel-plate capacitor are maintained with constant voltage by a battery as they are pulled apart.\nWhat happens to the strength of the electric field during this process?\n\n- It remains constant\n\n- cannot be determined from the information given\n\n- It decreases.\n\n- It increases.\n\n- not changed.\"\n\n# ╔═╡ 6de0da98-8dfe-496d-adc8-82c5c9af499e\nmd\"**Answer:** It decreases.\n\n**Explanation:** $C = \\frac{\\epsilon_0 A}{d}$\"\n\n# ╔═╡ d518d932-52d5-45de-aaf4-d94dfaf3eb64\nmd\"### Question 6\n\nConsider two copper wires.\nOne has twice the cross-sectional area of the other.\nHow do the resistances of these two wires compare?\n\n- The thicker wire has twice the resistance of the shorter\n\n- Both wires have the same resistance\n\n- none of the given answers\n\n- The thicker wire has half the resistance of the shorter wire.\"\n\n# ╔═╡ 570a8d6f-b108-4bba-81a4-8adffe79cea5\nmd\"**Answer:** The thicker wire has half the resistance of the shorter wire.\n\n**Explanation:** $R = \\rho \\frac{L}{A}$\"\n\n# ╔═╡ e275bc47-c73c-4cf5-bbdb-bebee2fb08af\nmd\"### Question 7\n\nConsider two copper wires.\nOne has twice the length of the other.\nHow do the resistances of these two wires compare?\n\n- The longer wire has twice the resistance of the shorter wire.\n\n- The longer wire has half the resistance of the shorter wire.\n\n- Both wires have the same resistance.\n\n- none of the given answers\"\n\n# ╔═╡ 07adb0ac-6cb2-40ed-ad5f-659a6f58303b\nmd\"\n##### Incorrect\n**Answer:** Both wires have the same resistance\"\n\n# ╔═╡ 276749db-45c7-43b9-a746-e48a6bdede2e\nmd\"##### Correct answer\n\nThe longer wire has twice the resistance of the shorter wire.\n\n**Explanation:**\nRefer to the formula sheet to find that the resistance of a wire is\n\n$R = \\rho \\frac{L}{A}$\n\"\n\n# ╔═╡ 4689568d-ba6d-4954-86ba-3fcadb52f957\nmd\"### Question 8\n\nIf the voltage across a circuit of constant resistance is doubled, the power dissipated by that circuit will\n\n- decrease to one fourth.\n\n- decrease to one half.\n\n- double.\n\n- quadruple.\"\n\n# ╔═╡ 9a0b5bac-f167-4150-beaa-3c770dbc8cac\nmd\"**Answer:** quadruple.\n\n**Explanation:** $P = \\frac{V^2}{R}$\"\n\n# ╔═╡ 7094b76b-519e-4427-91fe-88d33304fef1\nmd\"### Question 9\n\nIf the resistance in a constant voltage circuit is doubled, the power dissipated by that circuit will\n\n- decrease to one-fourth its original value.\n\n- increase by a factor of four.\n\n- decrease to one-half its original value.\n\n- increase by a factor of two.\"\n\n# ╔═╡ 82836166-8d43-4c15-a2d8-ac451a1d20ab\nmd\"**Answer:** decrease to one-half its original value.\n\n**Explanation:** $P = \\frac{V^2}{R}$\"\n\n# ╔═╡ 06389e81-54a5-46df-b7a6-fd11b44c5406\nmd\"### Question 10\n\nIf the resistance in a circuit with constant current flowing is doubled, the power dissipated by that circuit will\n\n- decrease to one fourth.\n\n- quadruple\n\n- decrease to one half.\n\n- double\"\n\n# ╔═╡ 5b87298f-9b97-4f7c-aab5-b3d740f9cab0\nmd\"**Answer:** double\n\n**Explanation:** $P = I^2 R$\"\n\n# ╔═╡ 980aa663-98cd-42be-9b92-238a452f537a\nmd\"#### Question 11\n\nConsider three identical resistors, each of resistance R.\nThe maximum power each can dissipate is P.\nThree of the resistors are connected in series, and a fourth is connected in parallel with these three.\nWhat is the maximum power this network can dissipate?\n\n- 2P\n\n- 3P\n\n- 3P/2\n\n- 4P/3\"\n\n# ╔═╡ 44d12feb-10cf-48b2-929a-8e6ff39a9496\nmd\"**Answer:** 4P/3\"\n\n# ╔═╡ 9f4b96a0-2b5e-47d0-8694-1c1d2144fd01\nmd\"### Question 12\n\nA charged particle is observed traveling in a circular path in a uniform magnetic field.\nIf the particle had been traveling twice as fast, the radius of the circular path would be\n\n- four times the original radius.\n\n- twice the original radius.\n\n- one-fourth the original radius.\n\n- one-half the original radius.\"\n\n# ╔═╡ 2434b3b5-2da8-4c1b-8bf2-522fc75b5cd1\nmd\"**Answer:** one-half the original radius.\n\n**Explanation:** $2B = \\frac{\\mu_0}{2\\pi} \\frac{I}{r} \\implies r \\propto \\frac{1}{2}$\"\n\n# ╔═╡ 72bd9e28-5048-48f2-a110-f5feaa67caee\nmd\"### Question 13\n\nAt a particular instant, a proton moves eastward at speed V in a uniform magnetic field that is directed straight downward.\nThe magnetic force that acts on it is\n\n- directed to the north.\n\n- directed upward.\n\n- zero\n\n- directed to the south.\"\n\n# ╔═╡ a8dd4343-6913-4e19-bc12-23e89c9e6236\nmd\"**Answer:** directed to the north.\"\n\n# ╔═╡ 239d8478-4571-4155-90e3-95ae1deb4939\nmd\"### Question 14\n\nAn electron moving along the +x axis enters a region where there is a uniform magnetic field in the +y direction.\nWhat is the direction of the magnetic force on the electron? (+x to the right, +y up, and +z out of the page.)\n\n- -z direction\n\n- -x direction\n\n- -y direction\n\n- +z direction\"\n\n# ╔═╡ a748ef26-adc8-4fe5-ad2b-8c8b1d79b54d\nmd\"**Answer:** -z direction\"\n\n# ╔═╡ f584bd06-21b6-41c2-b729-84b77acd2e2f\nmd\"### Question 15\n\nWhat is the current direction in this loop?\nAnd where is the north magnetic pole of this current loop?\n\n- Current CW; north pole on top\n\n- Current CW; north pole on bottom\n\n- Current CCW; north pole on bottom\n\n- Current CCW; north pole on top\"\n\n# ╔═╡ 0fbb0fa0-6c8e-497f-856f-2f3f8f2ce735\nImage(\"Unit9/P3QC1.png\")\n\n# ╔═╡ 4e172839-92b8-411a-ab77-3f8238d3a5e1\nmd\"**Answer:** Current CW; north pole on bottom\"\n\n# ╔═╡ 51cf30e3-8fdc-4b62-a1a6-9252ed608dc9\nmd\"### Question 16\n\nA long, straight wire extends into and out of the screen.\nThe current in the wire is\n\n- Into the screen\n\n- Not enough info to tell the direction.\n\n- There is no current in the wire.\n\n- Out of the screen.\"\n\n# ╔═╡ 1183767b-3d27-49c0-91ba-fd65e96cf773\nImage(\"Unit9/P1QC1.png\")\n\n# ╔═╡ 9086f546-aa48-438e-b682-b0f27b2bff5c\nmd\"**Answer:** Out of the screen.\"\n\n# ╔═╡ d78a8b7b-4ea8-45ad-9d8d-331a090170a4\nmd\"### Question 17\n\nSolenoid 2 has twice the diameter, twice the length, and twice as many turns as solenoid 1.\nHow does the field B₂ at the center of solenoid 2 compare to B₁ at the center of solenoid 1?\n\n- B2 = 4B1\n\n- B2 = B1\n\n- B2 = B1/2\n\n- B2 = 2B1\n\n- B2 = B1/4\"\n\n# ╔═╡ b7181523-93b0-4865-9c91-9ee965124bfa\nImage(\"Quiz/Q17.png\")\n\n# ╔═╡ fe0fb4f9-6d8f-48e7-9809-71c55035ba75\nmd\"**Answer:** B2 = B1\"\n\n# ╔═╡ 39fe00bb-0eb1-4f31-8073-e17186da71e7\nmd\"### Question 18\n\nWhere is the north magnetic pole of this current loop?\n\n- Right side\n\n- Top side\n\n- Left side\n\n- Bottom side\"\n\n# ╔═╡ 818d7074-6ce6-4746-a15e-a101ae653ec9\nImage(\"Quiz/Q18.png\")\n\n# ╔═╡ da06ac7d-67f3-483c-aad0-98529cf44a28\nmd\"**Answer:** Bottom side\"\n\n# ╔═╡ eae1f535-37ac-48dd-8f2c-65b88852fa43\nmd\"### Question 19\n\nWhat is the induced current direction in the loop?\n\n- In at the top, out at the bottom.\n\n- Out at the top, in at the bottom.\"\n\n# ╔═╡ d0224ffa-a5ef-465c-89fe-bc293e4d46ad\nImage(\"Quiz/Q19.png\")\n\n# ╔═╡ 4ff2da18-3d84-4cc8-9588-9fcc017aa4db\nmd\"\n##### Incorrect\n**Answer:** Out at the top, in at the bottom.\"\n\n# ╔═╡ 73709c95-3e75-48b9-9465-b80684920db7\nmd\"##### Correct answer\n\nIn at the top, out at the bottom.\n\n**Explanation:**\nBecome familiar with Lenz's Law.\nThe change in magnetic flux is increasing, so the induced current's direction is switched.\n\"\n\n# ╔═╡ 6036b824-7567-444a-8bad-a0472aeb549e\nmd\"### Question 20\n\nThe bar magnet is pushed toward the center of a wire loop.\nWhich is true?\n\n- There is a clockwise induced current in the loop.\n\n- There is no induced current in the loop.\n\n- There is a counterclockwise induced current in the loop.\"\n\n# ╔═╡ 9a0f2ce9-6ac6-4c9a-a1dc-dc2e93187247\nImage(\"Quiz/Q20.png\")\n\n# ╔═╡ 3bd6fefb-1475-4044-b637-f2358469d38f\nmd\"**Answer:** There is a clockwise induced current in the loop.\"\n\n# ╔═╡ 87b9e579-9e52-4d85-8c33-8438c548184a\nmd\"### Question 21\n\nThe current in the straight wire is decreasing.\nWhich is true?\n\n- There is no induced current in the loop.\n\n- There is a counterclockwise induced current in the loop.\n\n- There is a clockwise induced current in the loop.\"\n\n# ╔═╡ 8633003f-0de3-466a-974a-9087eaea00ec\nImage(\"Unit10/P2QC2.png\")\n\n# ╔═╡ ffa99665-c461-43ee-9939-e6027e53fad8\nmd\"**Answer:** There is a clockwise induced current in the loop.\"\n\n# ╔═╡ 81deea62-431f-404e-9df4-7536baa0cabd\nmd\"### Question 22\n\nThe out of the page magnetic field in the circular region is decreasing.\nWhich is the induced electric field?\n\n- D\n\n- B\n\n- C\n\n- A\"\n\n# ╔═╡ cb6cc92b-2d9a-4ee7-9e82-a175c0d1202f\nImage(\"Quiz/Q22.png\")\n\n# ╔═╡ 16e94b95-66bd-4b73-8185-e564eb2d6789\nmd\"\n##### Incorrect\n**Answer:** A.\"\n\n# ╔═╡ 6516bc36-7df5-4522-90e1-57ddbf01bd9d\nmd\"##### Correct answer\n\nB.\n\n**Explanation:** Use the right-hand rule into the screen. The electric field is induced to oppose the direction of the increasing magnetic field.\"\n\n# ╔═╡ aab4689d-9e64-486c-8913-99972148d7f5\nmd\"### Question 23\n\nAn electromagnetic wave is traveling to the east.\nAt one instant at a given point its E vector points straight up.\nWhat is the direction of its B vector?\n\n- down\n\n- east\n\n- south\n\n- north\"\n\n# ╔═╡ b7a99f37-aeb3-4123-aa05-dadfca72f06e\nmd\"\n##### Incorrect\n**Answer:** north\"\n\n# ╔═╡ c6563fbe-7118-4ddc-a922-9e9327b46bc5\nmd\"##### Correct answer\n\nsouth\n\n**Explanation:** Apply the right-hand rule where $\\vec{E} \\times \\vec{B}$ determines the direction of the electromagnetic wave.\"\n\n# ╔═╡ 79f4dc36-9ea9-4f22-9e0a-23f7e7bc139e\nmd\"### Question 24\n\nA lens creates an image as shown.\nIn this situation, the object distance $s$ is\n\n- Larger than the focal length f\n\n- Larger than 2f\n\n- Equal to the focal length f.\n\n- Larger than the focal length f but smaller than 2f\"\n\n# ╔═╡ 80c5e3e4-61bd-46cd-aa7c-1f6b098269a6\nImage(\"Quiz/Q24.png\")\n\n# ╔═╡ cd63ab55-26fe-4015-b171-0a1073eee06d\nmd\"**Answer:** Larger than the focal length f but smaller than 2f\"\n\n# ╔═╡ f08902fd-e2b8-47bc-b6fe-ffee0c0b5267\nmd\"### Question 25\n\nA lens creates an image as shown.\nIn this situation, the image distance $s'$ is\n\n- Larger than the focal length f.\n\n- Smaller than focal length f.\n\n- Equal to the focal length f.\"\n\n# ╔═╡ ed2b1790-224a-442e-9971-dc8f5313dbcc\nImage(\"Quiz/Q24.png\")\n\n# ╔═╡ c32eba5a-fc0e-4eb3-b179-3c4ef4dbc000\nmd\"**Answer:** Larger than the focal length f.\"\n\n# ╔═╡ 574b6d09-5147-404b-a0b7-3a7f6c88e251\nmd\"### Question 26\n\nYou see an upright, magnified image of your face when you look into magnifying \\\"cosmetic mirror\\\". The image is located\n\n- Behind the mirror's surface.\n\n- In front of the mirror's surface.\n\n- Only in your mind because it's a virtual image\n\n- On the mirror's surface.\"\n\n# ╔═╡ 6a8c8c80-3833-42ef-b5e2-b36385d2a456\nmd\"**Answer:** Behind the mirror's surface\"\n\n# ╔═╡ 3d9f7f6a-f6d4-4566-80ca-61b791cde540\nmd\"### Question 27\n\nIn an optical setup consisting of a single concave mirror and an object we measure the magnification factor M=-3.\nWe can conclude that this image is:\n\n- Inverted and virtual\n\n- Upright and virtual\n\n- Upright and real\n\n- Inverted and real\"\n\n# ╔═╡ e25ab1b9-ead0-48cd-8bb4-8611cba660dc\nmd\"**Answer:** Inverted and real\"\n\n# ╔═╡ e18a7261-ef49-4a4d-a961-4d4977554e1d\nmd\"### Question 28\n\nIn an optical setup consisting of a single lens and an object we measure the magnification factor M = -1.0.\nWe can conclude that object in this setup is:\n\n- At distance greater than twice the focal length\n\n- Exactly at point of twice the focal length\n\n- Between focal point and point of twice the focal length\n\n- Between lens and focal point\"\n\n# ╔═╡ 2c9665eb-2e88-4405-8eb6-4804253a34dd\nmd\"**Answer:** Exactly at point of twice the focal length\"\n\n# ╔═╡ bb10b8d6-d5e3-415f-bda7-9f26cd52f3a6\nmd\"## Diagnostic Test 5\"\n\n# ╔═╡ ff1c72bf-e271-46df-a288-8619a9f0a2e4\nmd\"### Conceptual Question 22.14\n\nCharges **A** and **B** in the figure are equal. Each charge exerts a force on the other of magnitude $F$. Suppose the charge of **B** is increased by a factor of 4, but everything else is unchanged.\"\n\n# ╔═╡ c40cfee1-3a46-4b05-ad7e-e2a8126f56cd\nImage(\"Unit5/DTP1.png\")\n\n# ╔═╡ c24e62c5-08e4-465c-b8cb-80328a8df16f\nmd\"#### Part A\n\nIn terms of $F$, what is the magnitude of the force on **A**?\n\n**Express your answer in terms of $F$.**\"\n\n# ╔═╡ 19d8e693-2fa4-4311-8fab-40c636d19169\nmd\"**Answer:** $F_A = 4F$\"\n\n# ╔═╡ c810aee0-42df-4e43-9a0c-5b3a37e0c892\nmd\"#### Part B\n\nIn terms of $F$, what is the magnitude of the force on **B**?\n\n**Express your answer in terms of $F$.**\"\n\n# ╔═╡ 058a4e62-655b-4e86-8ac9-c14c9f303153\nmd\"**Answer:** $F_B = 4F$\"\n\n# ╔═╡ 9594aa75-3585-4a4b-8f16-0e23e999268d\nmd\"### Conceptual Question 22.15\n\nThe electric force on a charged particle in an electric field is $F$.\"\n\n# ╔═╡ 4379e2f3-d536-40c1-bff6-dbd652c496ff\nmd\"#### Part A\n\nWhat will be the force if the particle's charge is tripled and the electric field strength is halved?\n\n**Give your answer in terms of F**\"\n\n# ╔═╡ 746b5d5b-5fde-4270-9e52-129f21ac722b\nmd\"**Answer:** $F' = \\frac{3}{2}F$\n\n**Explanation:** $\\vec{F} = q\\vec{E}$\"\n\n# ╔═╡ 40616231-34a0-4308-ac97-05ef93da2c86\nmd\"### Problem 22.17 - Enhanced - with Feedback\n\nYou may want to review (Pages 613 - 616).\"\n\n# ╔═╡ f8c5aaf6-7cbb-4a87-b08c-fbea27e0658a\nImage(\"Unit5/DTP3.png\")\n\n# ╔═╡ 65c05232-36bb-4df8-8146-4e8237e11758\nmd\"#### Part A\n\nWhat is the magnitude of the net electric force on charge A in the figure (Figure 1)?\nAssume that $q_1$ = 1.2 nC and $q_2$ = 5.2 nC.\n\n**Express your answer to two significant figures and include the appropriate units.**\"\n\n# ╔═╡ ae4eb3d7-cb85-4655-9e12-fdbb1e99af1b\nmd\"**Answer:**\n\n**Explanation:** Use $F = \\frac{k q_1 q_2}{r}$\n\n$\\begin{gather*}\nq_1 = 1.2 \\text{ nC} = 1.2 \\times 10^{-9} \\text{ C} \\\\\nq_2 = 5.2 \\text{ nC} = 5.2 \\times 10^{-9} \\text{ C} \\\\\nr = 1 \\text{ cm} = 0.01 \\text{ m} \\\\\n|F| = \\left|\\frac{kq_1q_1}{r^2} - \\frac{kq_1q_2}{(2r)^2}\\right| = 1.1 \\times 10^{-5} \\text{ N}\n\\end{gather*}$\"\n\n# ╔═╡ 9319bfbb-97c1-44f4-b605-16ee995476c3\nlet\n\tq1 = 1.2e-9\n\tq2 = 5.2e-9\n\tr = 1 / 100\n\tk = 9e9\n\tF = k*q1*q1 / r^2 - k*q1*q2/(2r)^2\nend\n\n# ╔═╡ ef5e8506-4a02-42a1-950d-4a53aecd42d7\nmd\"#### Part B\n\nWhat is the direction of the net electric force on charge A?\n\n- right\n\n- left\n\n- up\n\n- down\"\n\n# ╔═╡ 9f5e3964-3c67-41c8-b194-3dcdd6d485c2\nmd\"**Answer:** left\n\n**Explanation:** Compare the two forces being exerted on charge A.\"\n\n# ╔═╡ 5fe3b6d7-2277-4c43-8e21-7cd4203433cc\nlet\n\tq1 = 1.2e-9\n\tq2 = 5.2e-9\n\tr = 1 / 100\n\tk = 9e9\n\tFB = k*q1*q1 / r^2\n\tFA = -k*q1*q2 / (2r)^2\n\tFB, FA\nend\n\n# ╔═╡ c50bcc01-6ab1-43d6-bdb0-4e9e17b524c0\nmd\"## Diagnostic Test 9 (Chapter 29)\"\n\n# ╔═╡ 4830439e-3665-44c1-88c4-2b63da020890\nmd\"### Problem 29.5\"\n\n# ╔═╡ dde0edeb-b85c-4bca-b5e9-a75255dc50af\nImage(\"Unit9/DTP1.png\")\n\n# ╔═╡ 1120ad44-3519-4a0e-b464-d3666470ca35\nmd\"#### Part A\n\nWhat is the magnetic field at the position of the dot in the figure (Figure 1)?\nGive your answer as a vector.\n\nExpress your answer in terms of the unit vectors $\\hat{i}$, $\\hat{j}$, and $\\hat{k}$. Use the 'unit vector' button to denote unit vectors in your answer.\"\n\n# ╔═╡ fefd36c1-8607-4825-b72b-4d4f0f357523\nmd\"**Answer:** \n$\\begin{gather*}\nB = \\frac{\\mu_0}{4\\pi} \\frac{qv\\sin{\\theta}}{r^2}\n\\end{gather*}$\"\n\n# ╔═╡ ffb0edda-d3b5-4154-9df0-95758f3f3f12\nlet\n\tv = 2e7u\"m/s\"\n\tθ = 45u\"°\"\n\tq = e\n\tx = (2/100)u\"m\"\n\ty = (2/100)u\"m\"\n\t\n\t# B = ?\n\t# Magnetic field of a moving charge\n\t# B = (μ0 / 4π) * (qvsin(θ) / r^2)\n\t\n\t# r = ?\n\t# Distance formula\n\tr = sqrt(x^2 + y^2)u\"m\"\n\t\n\tB = (μ0 / 4π) * (q*v*sin(θ))/(r^2)\nend\n\n# ╔═╡ c45dde4e-d60f-4543-a2ee-d061f45bc848\nmd\"### Problem 29.9\n\nAlthough the evidence is weak, there has been concern in recent years over possible health effects from the magnetic fields generated by electric transmission lines. A typical high-voltage transmission line is 20 m above the ground and carries a 200 A current at a potential of 110 kV.\"\n\n# ╔═╡ 0bcd7967-9648-4f80-8b8b-7a1459f963b7\nmd\"#### Part A\n\nWhat is the magnetic field strength on the ground directly under such a transmission line?\n\n**Express your answer with the appropriate units.**\"\n\n# ╔═╡ ee17d3a7-a845-4b0d-991f-0d1546bd89c8\nmd\"**Answer:**\n$B = \\frac{\\mu_0}{2\\pi} \\frac{I}{r}$\"\n\n# ╔═╡ 0497b136-6780-4e31-9066-5cab808fa9f3\nlet\n\tr = 20u\"m\"\n\tI = 200u\"A\"\n\t\n\t# B = ?\n\t# Magnetic field of a wire\n\tB = (μ0 / 2π) * (I / r)\nend\n\n# ╔═╡ a57d36a2-c69a-4a4b-b623-e7067527a8d6\nmd\"#### Part B\n\nWhat percentage is this of the earth's magnetic field of 50 μT?\n\n$\\frac{B_{\\text{wire}}}{B_{\\text{earth}}}$\"\n\n# ╔═╡ 42774779-7c00-46c6-af46-29e6bfa5b362\nlet\n\t(r, I) = 20u\"m\", 200u\"A\"\n\tB_wire = (μ0 / 2π) * (I / r)\n\t\n\t(B_wire / B_earth) * 100\nend\n\n# ╔═╡ 924acf6e-5ada-4a64-ad51-1ff5ce84bb5e\nmd\"# Notice\n\nFrom this point on, I will no longer write out each problem since it takes too long and my exam is coming up very soon.\"\n\n# ╔═╡ 7bb28d6d-6d18-4209-b48e-5e87eedec74b\nmd\"### Problem 29.14\"\n\n# ╔═╡ d878a54c-a6e3-4fa7-81c9-5b045781f353\nlet\n\tI = 12u\"A\"\n\tr = (2/100)u\"m\"\n\t\n\t# B = ?\n\t# Magnetic field of a wire + superposition principle\n\t# B = (μ0 / 2π) * (I / r)\n\t\n\tB1a = (μ0 / 2π) * (I / r)\n\tB2a = -(μ0 / 2π) * (I / 3r)\n\tB1b = (μ0 / 2π) * (I / r)\n\tB2b = (μ0 / 2π) * (I / r)\n\tB1c = -(μ0 / 2π) * (I / 3r)\n\tB2c = (μ0 / 2π) * (I / r)\n\t\n\tB1a + B2a, (B1a, B2a), B1b + B2b, B1c + B2c, (B1c, B2c)\nend\n\n# ╔═╡ 862df6ac-1091-48b6-93a3-6cf64aa27dde\nmd\"### Problem 29.46\"\n\n# ╔═╡ 294246d2-c696-4f46-b746-d5f40234eb59\nlet\n\tI = 4.0u\"A\"\n\tr1 = (1 / 100)u\"m\"\n\tr2 = (2.0 / 100)u\"m\"\n\ts1 = 2π * r1\n\ts2 = 2π * r2\n\t\n\t# B = ?\n\t# Magnetic field of a loop + superposition principle\n\t# B = (μ0 / 2π) * (I / r)\n\t\n\tB1 = (μ0 / 4π) * (I / r1)\n\tB2 = (μ0 / 4π) * (I / r2)\n\t\n\tB1 + B2 # Incorrect!\nend\n\n# ╔═╡ 9a3ac337-de34-41cb-96cf-7c2dd7cd47e3\nmd\"### Problem 29.44\"\n\n# ╔═╡ 5bfab755-ed80-4318-ba3e-5774c89fff9f\nmd\"$B = \\frac{\\mu_0 IR^2}{2(z^2 + R^2)^{3/2}} = \\frac{\\mu_0 I}{4R}$\n\n$(z^2 + R^2)^{3/2} = 2R^3$\n\n$z^2 + R^2 = 1.59R^2$\n\n$z^2 = 0.59R^2$\n\n$z = 0.77$\"\n\n# ╔═╡ 06f1e08c-95b3-430d-86a1-3de041fe1506\nlet\n\t# z = ?\n\t# Magnetic field of a circular loop\n\t# B = (μ0 I R^2) / (2(z^2 + R^2)^(3/2))\n\t\n\t# Compare to center of loop, z = 0\n\t# B = (μ0 I) / 2R\n\t#\n\t# Half it\n\t# B = (μ0 I) / 4R\n\t\n\tsqrt(2^(2/3) - 1)\nend\n\n# ╔═╡ 64d28e04-f67f-4b98-afd6-9c16a15f2277\nmd\"### Problem 29.29\"\n\n# ╔═╡ a502e763-da48-4811-ab9b-6d2075c94758\nlet\n\tB = 3.0000u\"T\"\n\tu = 1.6605e-27u\"kg\"\n\tmO2 = 2 * 15.995 * u\n\tmN2 = 2 * 14.003 * u\n\tmCO = 12.000 * u + 15.995 * u\n\tq = 1.6022e-19u\"C\"\n\t\n\t# f = ?\n\t# Frequency of cyclotron\n\t# f = qB / (2π * m)\n\t\n\tfO2 = q*B / (2π * mO2)\n\tfN2 = q*B / (2π * mN2)\n\tfCO = q*B / (2π * mCO)\n\tfO2, fN2, fCO # Hz\nend\n\n# ╔═╡ 634882f3-baf9-4e98-a7c2-03c08314322d\nmd\"### Problem 29.30\"\n\n# ╔═╡ 0a95a636-be2d-43cc-ac71-707c88d5f117\nlet\n\tv = (0.1c)u\"m/s\"\n\td = (42 / 100)u\"m\"\n\tr = (d / 2)u\"m\"\n\tq = e\n\tB = (mp * v) / (q * r)\nend\n\n# ╔═╡ 9fa6bc2f-f99f-4d4b-91fa-695d04f0e83b\nmd\"### Problem 29.33\"\n\n# ╔═╡ 2b72b700-5b08-4744-b29e-2714ec33580a\nlet\n\tm = (2 / 1000)u\"kg\"\n\tI = 1.6u\"A\"\n\td = (12 / 100)u\"m\"\n\tB = m*g / (I*d)\nend\n\n# ╔═╡ 998d6c8b-3af1-4549-b633-13f4977e9afe\nmd\"### Problem 29.34\"\n\n# ╔═╡ a18585ce-d13b-4581-9c49-65c54bc3436f\nlet\n\tL = 10 / 100\n\td = 5 / 1000\n\tF = 7.2e-5\n\tV = 9\n\tR1 = 2\n\tI1 = V / R1\n\tI2 = F * 2π * d / (μ0 * I1 * L)\n\tR2 = V / I2\nend\n\n# ╔═╡ d8f53b47-1267-426b-a6d6-15b397dc8d9e\nmd\"### Problem 29.38\"\n\n# ╔═╡ f6840354-2325-470c-8fd1-a3246f236550\nlet\n\ts = (5.50 / 100)u\"m\"\n\tI = (510 / 1000)u\"A\"\n\tB = 1.60u\"T\"\n\tθ = 30u\"°\"\n\tτ = I*s^2*B*sin(θ)\nend\n\n# ╔═╡ dc205f5d-0512-4429-8f26-f60e9f07115b\nmd\"## PSW 9 (Chapter 29)\"\n\n# ╔═╡ d6e4e26e-cb79-4aa1-8d97-1f2f238aeb10\nmd\"### Problem 29.15\"\n\n# ╔═╡ 9f8323d5-1480-490a-b088-be9d69bf6e00\nlet\n\td = (6.0 / 1000)u\"m\"\n\tℰ = 60u\"V\"\n\tR100 = 100u\"Ω\"\n\tR30 = 30u\"Ω\"\n\tR20 = 20u\"Ω\"\n\tR = (1/R100 + 1/(R30+R20))^-1\n\tI = ℰ / R\n\tI1 = ℰ / R100\n\tI2 = ℰ / (R30 + R20)\n\tB = (μ0 / 2π) * (I2 / d)\nend\n\n# ╔═╡ 4a0ecf24-5fc7-4586-9313-3c2fc33ea91c\nmd\"### Problem 29.37\"\n\n# ╔═╡ c494b302-bf92-44b5-abf2-59956da672d5\nlet\n\tl = 1u\"m\"\n\tm = (58 / 1000)u\"kg\"\n\tr = (4 / 100)u\"m\"\n\tθ = 60u\"°\"\n\t# 2F = mg\n\t# ⟹ 2IlB sin(θ) = mg\n\t# ⟹ μ0 * I^2 sin(θ) / πr = mg\n\t# ⟹ I = sqrt(mg * πr / (μ0 * sin(θ)))\n\tI = sqrt(m*g * π*r / (μ0 * sin(θ)))\nend\n\n# ╔═╡ c8d2f67e-33ec-4ecd-b7f4-2037c1ac91ec\nmd\"### Problem 29.50\"\n\n# ╔═╡ 6bc0b95d-be29-42ba-93ca-bb1bc910256e\nlet\n\td = (2 / 100)u\"m\"\n\tL = (8 / 100)u\"m\"\n\tB = 0.10u\"T\"\n\tI = 1.6u\"A\"\n\tN = B * L / (μ0 * I)\nend\n\n# ╔═╡ 971c6622-d701-4142-addf-55c2fb8007bd\nmd\"### Problem 29.52\"\n\n# ╔═╡ beedbeca-0477-4162-9c9e-05aa9cfd907f\nmd\"\n$B = \\frac{\\mu_0 I a^2}{2(x^2 + a^2)^{3/2}}$\"\n\n# ╔═╡ 63619364-64ad-44aa-bbc5-1a847358c892\nlet\n\td = (18 / 100)u\"m\"\n\tr = (d / 2)\n\tB = 6e-12u\"T\"\n\tx = r\n\tI = (B * 2 * (x^2 + r^2)^(3/2)) / (μ0 * r^2)\n\tI = (B * 2 * (r^2 + r^2)^(3/2)) / (μ0 * r^2)\n\tI = (B * 2 * (2r^2)^(3/2)) / (μ0 * r^2)\n\tI = (B * 2 * (sqrt(2) * r)^(3)) / (μ0 * r^2)\nend\n\n# ╔═╡ d05ed603-19ce-4c7d-b67d-78e7258378d5\nmd\"### Problem 29.73\"\n\n# ╔═╡ 21c3aacf-abb7-4f65-8681-440ee3c13341\nlet\n\tm = 4.0u\"kg\"\n\ts = 4.0u\"m\"\n\tI = 25u\"A\"\n\tθ = 25u\"°\"\n\t\n\t# Force acts on center of object\n\t# τ = Fd cos(θ)\n\t# ⟹ mg (s / 2) cos(θ) = Is^2B sin(90-θ)\n\t# ⟹ B = mg cos(θ) / (2Is sin(90-θ))\n\tB = m*g*cos(θ) / (2*I*s*sin(90u\"°\"-θ))\nend\n\n# ╔═╡ 651147e8-f7f8-4b87-9793-21e9b82a7c91\nmd\"### Problem 29.65\"\n\n# ╔═╡ f30306c0-0006-4a6f-873a-07fadcdc5d2d\nlet\n\tB = u\"T\"(29.0u\"mT\")\n\tv = 4.9e6u\"m/s\"\n\tθ = 30u\"°\"\n\tvpp = v*cos(θ)\n\tvpl = v*sin(θ)\n\tq = e\n\tr = me*(vpp) / (q*B)\n\t\n\tΔt = 2π*r / vpp\n\tp = vpl * Δt\nend\n\n# ╔═╡ bfec2cfd-b400-4e73-8a40-7b3665209a5d\nmd\"## Diagnostic Test 10 (Chapter 30)\"\n\n# ╔═╡ 1b65d5b3-ffb4-4c4c-a071-24cf1cfdd0c4\nmd\"### Problem 30.4\"\n\n# ╔═╡ 6a010c2a-f8e6-44db-84ff-8e9a9593a29e\nlet\n\ta = u\"m\"(30u\"cm\")\n\tB1 = 2.0u\"T\"\n\tB2 = 1.0u\"T\"\n\tΦ1 = a^2 * B1\n\tΦ2 = a^2 * B2\n\tΦ1 - Φ2\nend\n\n# ╔═╡ e5254b57-0930-4083-b8d5-b37ae9292052\nmd\"### Problem 30.5\"\n\n# ╔═╡ d7fd0a6d-2df6-4614-abf0-72971f07220b\nlet\n\tA = u\"m^2\"((5*10)u\"cm^2\")\n\tB = 5.50e-2u\"T\"\n\tθ = 45u\"°\"\n\tΦ1 = A*B*cos(θ)\n\tΦ2 = A*B*cos(θ)\n\tΦ1 + Φ2\nend\n\n# ╔═╡ e6375fb6-ae08-4442-b7c5-26953bd1cd95\nmd\"### Problem 30.8\"\n\n# ╔═╡ adcf50c9-8c45-46fa-aca3-10a5c660f80b\nlet\n\tds = u\"m\"(2.6u\"cm\")\n\tdl = u\"m\"(7.0u\"cm\")\n\tA = 1/4 * π * ds^2\n\tB = 0.16u\"T\"\n\tΦ1 = Φ2 = A*B\nend\n\n# ╔═╡ 549d2a7f-d307-4c96-9df5-6f936842cc59\nmd\"### Problem 30.11\"\n\n# ╔═╡ 4cd51b45-2e77-41a2-9691-2d5e1fc01d3f\nlet\n\ts = u\"m\"(20u\"cm\")\n\tB = 0.30u\"T\"\n\tθ = 60u\"°\"\n\tb = s/2\n\th = s*sin(θ)\n\tA = b*h / 2\n\tΦ = A*B\nend\n\n# ╔═╡ 3945a727-df1d-4717-b9d1-3b14f9e07adf\nmd\"### Problem 30.12\n\n- Yes, clockwise. Use Lenz's law.\"\n\n# ╔═╡ 9c8a76a8-7caa-4d0d-9608-4e98d3955677\nmd\"### Problem 30.13\"\n\n# ╔═╡ bf938d16-4f96-409a-b3e7-39f6873ca275\nlet\n\tB = 0.50u\"T\"\n\tv = 55u\"m/s\"\n\tR = 0.70u\"Ω\"\n\tl = u\"m\"(5.0u\"cm\")\n\tℰ = v*l*B\n\tI = ℰ / R\nend\n\n# ╔═╡ e4ecd474-4d48-4414-93b4-6eb029da45eb\nmd\"### Problem 30.15\"\n\n# ╔═╡ b798ffc4-bc44-4add-885f-96b88cf66960\nlet\n\tR = 0.30u\"Ω\"\n\tI = u\"A\"(150u\"mA\")\n\ts = u\"m\"(8.0u\"cm\")\n\tE = I*R\n\tA = s^2\n\t# E = dΦ/dt = A |dB/dt|\n\tdBdt = E/A\nend\n\n# ╔═╡ 1d2210ec-00a9-4960-8686-85df92dae42d\nmd\"### Problem 30.22\"\n\n# ╔═╡ d2162fdf-dc4b-4138-8cc8-6ac803d82566\nlet\n\tV1 = 13000u\"V\"\n\tf = 60u\"Hz\"\n\tV2 = 120u\"V\"\n\tN2 = 150\n\tN1 = N2*V1/V2\n\t\n\tI2 = 220u\"A\"\n\t# I1V1 = I2V2 ⟹ I1 = I2V2/V1\n\tI1 = I2*V2/V1\n\t\n\tN1, I1\nend\n\n# ╔═╡ 57086fd7-66cb-4a72-b589-dc5fa3c8c8c2\nmd\"### Problem 30.26\"\n\n# ╔═╡ a7972df8-734e-4108-86b6-c0a5d0ede63d\nlet\n\tL = (100 / 1000)u\"H\"\n\tRw = 5.0u\"Ω\"\n\tℰ = 9u\"V\"\n\tRi = 3.0u\"Ω\"\n\tR = Rw + Ri\n\tI = ℰ/R\n\tUL = 1/2 * L * I^2\nend\n\n# ╔═╡ 465bc5f9-d40c-4227-8962-da6746b1dcc4\nmd\"### Problem 30.27\"\n\n# ╔═╡ 2817d2a7-fb3f-4986-adb9-3fb36a66d1b9\nlet\n\td = u\"m\"(3.00u\"cm\")\n\tA = 1/4 * π * d^2\n\tℓ = u\"m\"(14.0u\"cm\")\n\tN = 200\n\tI = 0.750u\"A\"\n\tLsol = μ0 * N^2 * A / ℓ\n\tUL = 1/2 * Lsol * I^2\nend\n\n# ╔═╡ 6f906af6-1379-42a3-b24d-dd5d257241c9\nmd\"### Problem 30.19\"\n\n# ╔═╡ b94bf1ef-fb85-4e1a-92f8-3f47e143f9e6\nlet\n\t# F = ma = qE ⟹ a = qE/m\n\tdBdt = 0.7u\"T/s\"\n\tra = u\"m\"(1.0u\"cm\")\n\trb = u\"m\"(0.0u\"cm\")\n\trc = u\"m\"(1.0u\"cm\")\n\trd = u\"m\"(2.0u\"cm\")\n\tq = e\n\tEa = ra/2 * dBdt\n\tEb = rb/2 * dBdt\n\tEc = rc/2 * dBdt\n\tEd = rd/2 * dBdt\n\taa = q*Ea / mp # upwards\n\tab = q*Eb / mp # a = 0\n\tac = q*Ec / mp # downwards\n\tad = q*Ed / mp # downwards\n\taa,ab,ac,ad\nend\n\n# ╔═╡ 1568e950-6ae3-4eee-8c28-8db36795a929\nmd\"### Problem 30.20\"\n\n# ╔═╡ 66cb890a-45af-4faf-8ecd-02df1bcdf3e6\nlet\n\td = u\"m\"(5.0u\"cm\")\n\tB = 2.0u\"T\"\n\tdBdt = 3.40u\"T/s\"\n\tr = u\"m\"(1.60u\"cm\")\n\tE = r/2 * dBdt\nend\n\n# ╔═╡ 22fc3d80-341b-4902-89c1-c1a587c28a08\nmd\"## PSW 10 (Chapter 30)\"\n\n# ╔═╡ 63b35422-6697-4a1f-8d60-55c977a87360\nmd\"### Problem 30.39\"\n\n# ╔═╡ d410ae9c-d876-4ac2-9d7d-44154cc24325\nlet\n\tN = 100\n\tdc = u\"m\"(5.0u\"cm\")\n\tdw = u\"m\"(0.50u\"mm\")\n\trc = dc / 2\n\tI = 4.0u\"A\"\n\tρ = 1.7e-8u\"Ω\"\n\n\t# |dB/dt| = ?\n\t# Faraday's Law\n\t# E = N|dΦ/dt| = NA |dB/dt| ⟹ |dB/dt| = E/NA\n\t\n\tAw = 1/4 * π * dw^2\n\tL = dw * N\n\tR = N * ρ * (2π*rc) / Aw\n\tE = I * R\n\t\n\tA = 1/4 * π * dc^2\n\t\n\tdBdt = E/(N*A)\nend\n\n# ╔═╡ e0a50b78-31a1-45ee-be74-2c6d8b5f13b8\nmd\"### Problem 30.49\"\n\n# ╔═╡ 77c5d223-6de7-454f-b6d3-2895600e2b1a\nlet\n\td = u\"m\"(18u\"cm\")\n\tN = 120\n\tf = 60u\"Hz\"\n\tℰ = 350u\"V\"\n\t\n\t# B = ?\n\t# Electromotive force of a generator\n\t# ℰ = NBωA sinωt ⟹ B = ℰ/(NωAsin(ωt)) = ℰ/(NωA) since peak of sin = 1\n\t\n\tω = 2π * f\n\tA = 1/4 * π * d^2\n\tB = ℰ/(N*ω*A)\nend\n\n# ╔═╡ 85dee8d0-d364-4744-a5ac-5459f7c1a95c\nmd\"### Problem 30.50\"\n\n# ╔═╡ 91d1441c-8d8b-4652-b089-5d06d191d21d\nlet\n\tNc = 40\n\tdc = u\"m\"(4.0u\"cm\")\n\tR = 0.40u\"Ω\"\n\t\n\tds = u\"m\"(4.0u\"cm\")\n\tLs = u\"m\"(20u\"cm\")\n\tNs = 200\n\t\n\tf = 60u\"Hz\"\n\tI = 0.20u\"A\"\n\t\n\t# I0 = ?\n\t# Magnetic field of a solenoid\n\t# Bsol = μ0 INs / Ls = μ0 (I0 sin(2πft)) Ns / Ls\n\t\n\t# Magnetic flux through coil\n\t# Φm = Nc ABsol = Nc A (μ0 (I0 sin(2πft)) Ns / Ls)\n\t\n\t# Induced emf in coil\n\t# ℰ = -dΦ/dt = Nc A (2πf μ0 (I0 cos(2πft)) Ns / Ls)\n\t# I = ℰ/R = Nc A (2πf μ0 (I0 cos(2πft)) Ns / Ls) / R\n\t\n\t# Solve for I0\n\t# I0 = (I * Ls * R) / (Nc A 2πf μ0 Ns)\n\t\n\tA = 1/4 * π * ds^2\n\tI0 = I*Ls*R / (Nc*A*2π*f*μ0*Ns) # The correct answer is 6.0 A.\nend\n\n# ╔═╡ 2e69b5bd-0b56-4bf2-a338-b4d373dde517\nmd\"### Problem 30.65\"\n\n# ╔═╡ e65a8d69-d925-4de2-9edd-c33669b756a8\nlet\n\tA = 6.3e-2u\"m^2\"\n\tB = 5.3u\"T\"\n\tℰ = 9e-2u\"V\"\n\t\n\t# Δt = ?\n\t# Faraday's Law\n\t# ℰ = ΔΦm/Δt ⟹ Δt = ΔΦm/ℰ\n\t\n\t# ΔΦm = ?\n\t# Magnetic flux equation\n\tΔΦm = A*B\n\t\n\tΔt = ΔΦm/ℰ\nend\n\n# ╔═╡ e0d4b7ca-578b-4d25-a9e6-81baafa497b0\nmd\"### Problem 30.80\"\n\n# ╔═╡ f44da9f7-87fa-4a44-864b-11e54553b3b0\nlet\n\tR = 2.4e-2u\"Ω\"\n\tI = 15u\"A\"\n\tr = u\"m\"(2.0u\"cm\")\n\tl = u\"m\"(4.0u\"cm\")\n\tx = u\"m\"(1.0u\"cm\")\n\tv = 10u\"m/s\"\n\t\n\t# I_loop = ?\n\t# Ohm's Law\n\t# ℰ = IR ⟹ I = ℰ/R\n\t\n\t# ℰ = ?\n\t# Faraday's Law\n\t# ℰ = dΦ/dt = d/dt(AB) = d/dt(xlB) = vlB = vl(B_r - B_rx)\n\t\n\t# B_r = ?\n\t# Magnetic field of a wire\n\tB_r = (μ0 / 2π) * (I / r)\n\t\n\t# B_rx = ?\n\t# Magnetic field of a wire\n\tB_rx = (μ0 / 2π) * (I / (r+x))\n\t\n\tℰ = v*l*(B_r - B_rx)\n\t\n\tI = ℰ/R\nend\n\n# ╔═╡ ca39044c-f352-4fb9-a8be-355f4a01a17d\nmd\"### Problem 30.85\"\n\n# ╔═╡ 092aa2fc-ddc6-4729-911c-aa4e21ad7bd9\nlet\n\td = u\"m\"(2.1u\"cm\")\n\tN = 1200\n\tL = 1u\"m\"\n\tr = u\"m\"(0.60u\"cm\")\n\tℰ = 5.4e-4u\"V/m\"\n\t\n\t# dI/dt = ?\n\t# Magnetic field of a solenoid\n\t# dB/dt = (μ0 N / L) (dI/dt) ⟹ dI/dt = (dB/dt) / (μ0 N / L)\n\t\n\t# dB/dt = ?\n\t# Faraday's Law of induction\n\t# ℰ = r/2 (dB/dt) ⟹ dB/dt = 2ℰ / r\n\t\n\tdBdt = 2ℰ / r\n\t\n\tdIdt = dBdt / (μ0 * N / L)\nend\n\n# ╔═╡ 3ece80ba-1bde-48a9-93ff-d6b9778b43e2\nmd\"## Diagnostic Test 11 (Chapter 31)\"\n\n# ╔═╡ 07586a45-e8b7-466d-99b5-5b1fc20b32eb\nmd\"### Conceptual Question 31.7\"\n\n# ╔═╡ 88053dfe-70e5-498a-bfd1-cb7eb33fad96\nlet\n\t# Part A\n\t# Out of the page\n\t\n\t# Part B\n\t# Upward\nend\n\n# ╔═╡ 4c49f6cf-0f0e-408c-acde-ad77faa9903c\nmd\"### Problem 31.19\"\n\n# ╔═╡ da63cb45-9b93-4423-8fd7-0b6aae9e4a29\nlet\n\td = u\"m\"(2.0u\"mm\")\n\tP = u\"W\"(1.6u\"mW\")\n\t\n\t# E0 = ?\n\t# Intensity of electromagnetic wave\n\t# P/A = 1/2cμ0 E0^2\n\t# ⟹ E0 = sqrt((P/A) * 2cμ0)\n\t\n\t# A = ?\n\tA = 1/4 * π * d^2\n\t\n\tE0 = sqrt((P/A) * 2c*μ0)\n\t\n\t# B0 = ?\n\t# EM Field strength relationship\n\t# E0 = cB0\n\t# ⟹ B0 = E0/c\n\tB0 = E0/c\n\t\n\tE0, B0\nend\n\n# ╔═╡ 472fc923-c527-47e4-9ea2-e2a762c08f62\nmd\"### Problem 31.21\"\n\n# ╔═╡ 916addb5-4a54-422d-b9c9-5b24c3f16e3f\nlet\n\tP = u\"W\"(160u\"MW\")\n\td = u\"m\"(1.6u\"μm\")\n\t\n\t# E0 = ?\n\t# Intensity of electromagnetic wave\n\t# P/A = 1/2cμ0 E0^2\n\t# ⟹ E0 = sqrt((P/A) * 2cμ0)\n\t\n\t# A = ?\n\tA = 1/4 * π * d^2\n\t\n\tE0 = sqrt((P/A) * 2c*μ0)\n\t\n\t# Ehydrogen = ?\n\t# Electric field produced by a point charge\n\tq = e\n\tr = u\"m\"(0.053u\"nm\")\n\tEhydrogen = k*q/r^2\n\t\n\tE0, E0 / Ehydrogen\nend\n\n# ╔═╡ bfafde7f-8d61-41fb-be8c-d3bf12404fab\nmd\"### Problem 31.22\"\n\n# ╔═╡ 892661d3-046f-4df9-9269-89f26ca79b4c\nlet\n\tP = 1000u\"W\"\n\tλ = u\"m\"(10u\"μm\")\n\td = u\"m\"(3.0u\"mm\")\n\t\n\t# F = ?\n\t# Radiation force due to beam of light\n\tF = P / c\nend\n\n# ╔═╡ 04898c9a-5eca-4d1f-bd19-aec0d16f51d8\nmd\"### Conceptual Question 31.10\"\n\n# ╔═╡ 8f1b5656-c3e6-4490-ba16-fbeb3f9c574e\nlet\n\tθ = Dict(\n\t\t:a => 90u\"°\",\n\t\t:b => 45u\"°\",\n\t\t:c => 30u\"°\",\n\t\t:d => 0u\"°\",\n\t\t:e => 30u\"°\"\n\t)\n\t\n\tsort(collect(θ), by=x->(cos(x[2])^2), rev=true)\nend\n\n# ╔═╡ 705a1476-eb5d-4f76-af51-4cf3bb61d36d\nmd\"## PSW 11 (Chapter 31)\"\n\n# ╔═╡ ff9db5b4-9875-4279-8957-4cfd3245d6f7\nmd\"### Problem 31.47\"\n\n# ╔═╡ 61c3c8a1-4a00-4c1f-8c82-6594bcdfb006\nlet\n\tr = u\"m\"(4.5e9u\"km\")\n\tP = 21u\"W\"\n\t\n\t# I = ?\n\t# Intensity of point source\n\t# I = P/4πr^2\n\tI = P/(4π*r^2)\n\t\n\t# E0 = ?\n\t# Intensity of electromagnetic wave\n\t# I = 1/2cμ0 E0^2\n\t# ⟹ E0 = sqrt(2Icμ0)\n\tE0 = sqrt(2I*c*μ0)\n\t\n\tI, E0\nend\n\n# ╔═╡ 241d99b8-c672-40f3-8b9d-854413a57630\nmd\"### Problem 31.59\"\n\n# ╔═╡ d40d40e9-e141-4161-8cc7-403d30e74304\nlet\n\ts = u\"m\"(10u\"cm\")\n\tE0 = u\"V/m\"(11u\"kV/m\")\n\tΔT = 45\n\t\n\t# t = ?\n\t# 0.85P = E/t\n\t# ⟹ t = E/0.85P\n\t\n\t# P = ?\n\t# Intensity of electromagnetic wave\n\t# P/A = 1/2cμ0 E0^2\n\t# ⟹ P = A/2cμ0 E0^2\n\t\n\tbegin\n\t\t# A = ?\n\t\t# Area of one side of the cube\n\t\tA = s^2\n\n\t\tP = A/(2c*μ0) * E0^2\n\tend\n\t\n\t# E = ?\n\t# Specific heat of water\n\t# E = Q = mcΔT = ρVcΔT\n\t\n\tbegin\n\t\t# ρ = ?\n\t\t# Density of water\n\t\tρ = 1000u\"kg/m^3\"\n\n\t\t# V = ?\n\t\t# Volume of water\n\t\tV = s^3\n\n\t\t# c = ?\n\t\t# Specific heat capacity of water\n\t\tcw = 4190u\"J/(kg*K)\"\n\t\n\t\tE = Q = ρ*V*cw*ΔT\n\tend\n\t\n\tt = E/0.85P\nend\n\n# ╔═╡ df7ed866-611b-4b64-94fd-b5876ed39336\nmd\"### Problem 31.60\"\n\n# ╔═╡ c74ce47c-697f-4fa6-9d27-bef932bd2d54\nlet\n\tm = 80u\"kg\"\n\tΔx = 5.0u\"m\"\n\tP = 1000u\"W\"\n\tt0 = u\"s\"(1.0u\"hr\")\n\t\n\t# t = ?\n\t# Initial time plus extra time\n\t# t = t0 + t1\n\t\n\tbegin\n\t\t# t1 = ?\n\t\t# Change in position over time\n\t\t# v = Δx1/t1 ⟹ t = Δx1/v\n\t\t\n\t\tbegin\n\t\t\t# Δx1 = ?\n\t\t\t# Change in position after 1.0hr\n\t\t\t# Δx1 = Δx - Δx1\n\n\t\t\tbegin\n\t\t\t\t# Δx0 = ?\n\t\t\t\t# Kinematic equation\n\t\t\t\t# Δx0 = 1/2 a(t0)^2\n\t\t\t\t\n\t\t\t\tbegin\n\t\t\t\t\t# a = ?\n\t\t\t\t\t# Newton's second law\n\t\t\t\t\t# F = ma ⟹ a = F/m\n\t\t\t\t\t\n\t\t\t\t\tbegin\n\t\t\t\t\t\t# F = ?\n\t\t\t\t\t\t# Force due to beam of light\n\t\t\t\t\t\t# F = P/c\n\t\t\t\t\t\t\n\t\t\t\t\t\tF = P/c\n\t\t\t\t\tend\n\t\t\t\t\t\n\t\t\t\t\ta = F/m\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\tΔx0 = 1/2 * a * t0^2\n\t\t\tend\n\t\t\t\n\t\t\tΔx1 = Δx - Δx0\n\t\tend\n\t\t\n\t\tbegin\n\t\t\t# v = ?\n\t\t\t# Kinematic equation\n\t\t\t# v = at0\n\t\t\t\n\t\t\tv = a*t0\n\t\tend\n\t\t\n\t\tt1 = Δx1/v\n\tend\n\t\n\tt = t0 + t1\n\tu\"hr\"(t)\nend\n\n# ╔═╡ 69e73591-3bdf-4e31-9ce9-4c1f44e207a8\nmd\"### Problem 31.37\"\n\n# ╔═╡ 3388d0f4-ace3-4322-89ba-a06ba0840adf\nlet\n\tI = 5.0u\"A\"\n\td = u\"m\"(1.0u\"cm\")\n\tR = d / 2\n\tr = u\"m\"(1.8u\"mm\")\n\t\n\t# B = ?\n\t# Magnetic field of a wire\n\tB1 = (μ0 / 2π) * (I / r)\n\t\n\t# B = ?\n\t# Biot-Savart Law\n\tB2 = (μ0 / 2π) * (r / R^2) * I\n\t\n\tB1, B2\nend\n\n# ╔═╡ aa2e1f09-bb0e-452d-b277-32ed87f1d805\nmd\"## Diagnostic Test 12 (Chapter 34)\"\n\n# ╔═╡ 49522fe9-e9d9-433c-92a2-072d60e1576e\nmd\"### Problem 34.40\"\n\n# ╔═╡ e9661551-68aa-41fc-be08-e88b8444e4f6\nlet\n\ts = 30.0u\"cm\"\n\tf = -22.0u\"cm\"\n\t\n\t# s′ = ?\n\t# Mirror equation\n\t# 1/s + 1/s′ = 1/f\n\t# ⟹ s′f + sf = ss′\n\t# ⟹ s′(f - s) = -sf\n\t# ⟹ s′ = -sf/(f - s)\n\ts′ = -s*f/(f - s)\nend\n\n# ╔═╡ 8d7d25f5-f27e-4b86-a845-15e9a3dd2f72\nmd\"### Problem 34.41\"\n\n# ╔═╡ 3548c0a7-1de7-4534-a930-58d80e9efad7\nlet\n\th = 1.3u\"cm\"\n\ts = 18.0u\"cm\"\n\tf = 56.0u\"cm\"\n\t\n\t# s′ = ?\n\t# Mirror equation\n\t# 1/s + 1/s′ = 1/f\n\t# ⟹ s′f + sf = ss′\n\t# ⟹ s′(f - s) = -sf\n\t# ⟹ s′ = -sf/(f - s)\n\ts′ = -s*f/(f - s)\n\t\n\t# h′ = ?\n\t# Magnification equation\n\t# M = h′/h = -s′/s\n\t# ⟹ h′ = -s′/s h\n\th′ = -s′/s * h\n\t\n\ts′, h′\nend\n\n# ╔═╡ b550aa41-be86-4336-91cd-816565045da5\nmd\"### Problem 34.33\"\n\n# ╔═╡ 0fe25f6d-0132-4fa4-a1b8-a03963fd1ee7\nlet\n\th = 2.2u\"cm\"\n\ts = 36.0u\"cm\"\n\tf = 18.0u\"cm\"\n\t\n\t# s′ = ?\n\t# Lens equation\n\t# 1/s + 1/s′ = 1/f\n\t# ⟹ s′f + sf = ss′\n\t# ⟹ s′(f - s) = -sf\n\t# ⟹ s′ = -sf/(f - s)\n\ts′ = -s*f/(f - s)\n\t\n\t# h′ = ?\n\t# Magnification equation\n\t# M = h′/h = -s′/s\n\t# ⟹ h′ = -s′/s h\n\th′ = -s′/s * h\n\t\n\ts′, abs(h′)\nend\n\n# ╔═╡ a6e0b275-276f-4c0b-b548-4a4c283a6330\nmd\"### Problem 34.16\"\n\n# ╔═╡ f0a5c1d8-0de4-4455-b6e7-73b0426cd04c\nlet\n\t# d = ?\n\t# Transparent hemisphere\n\t# d = R / n\nend\n\n# ╔═╡ ceccbe3d-5c9a-47bf-a168-18154f30729b\nmd\"### Problem 34.11\"\n\n# ╔═╡ 6f920972-e2ab-4e62-855e-9bac912831df\nlet\n\ty = 1.0u\"cm\"\n\tθ1 = 69u\"°\"\n\tn1 = 1\n\tn2 = 1.33\n\tn3 = 1.50\n\t\n\t# θ2 = ?\n\t# Snell's Law\n\t# n1 sin(θ1) = n2 sin(θ2)\n\t# ⟹ θ2 = asin(n1 sin(θ1) / n2)\n\tθ2 = asind(n1 * sind(θ1) / n2)\n\t\n\t# θ3 = ?\n\t# Snell's Law\n\t# n2 sin(θ2) = n3 sin(θ3)\n\t# ⟹ θ3 = asin(n2 sin(θ2) / n3)\n\tθ3 = asind(n2 * sind(θ2) / n3)\nend\n\n# ╔═╡ 3be6b392-ea30-4015-a718-41f43797626e\nmd\"### Problem 34.7\"\n\n# ╔═╡ 1c600f48-8f4d-4841-bfcf-14e805e284b8\nlet\n\tb = 5.0u\"m\"\n\th = 3.0u\"m\"\n\tmid = h / 2\n\t\n\t# ϕ = ?\n\t# Trigonometry\n\t# ϕ = atan(h/x)\n\t\n\tbegin\n\t\t# x = ?\n\t\t# Trigonometry relationship\n\t\t# tan(ϕ) = h/x = mid / (b - x)\n\t\t# ⟹ (b - x) h = x mid\n\t\t# ⟹ bh - xh = x mid\n\t\t# ⟹ bh = x(mid + h)\n\t\t# ⟹ x = bh / (mid + h)\n\t\t\n\t\tx = b*h / (mid + h)\n\tend\n\t\n\tϕ = atand(h/x)\nend\n\n# ╔═╡ f4730b14-2902-457d-a5f8-7e9140926b1e\nmd\"### Problem 34.14\"\n\n# ╔═╡ 2fbca1ac-29e5-4f5b-8cac-faf6b48045eb\nlet\n\tn1 = 1.60\n\tn2 = 1.45\n\t\n\t# θc = ?\n\t# Critical angle\n\tθc = asind(n2/n1)u\"°\"\n\t\n\tθmax = 90u\"°\" - θc\nend\n\n# ╔═╡ c9cae5ed-a959-4c20-a4a6-21b6962f7fc5\nmd\"### Problem 34.37\"\n\n# ╔═╡ 53439784-13c7-4f08-949d-e60cd41d4494\nlet\n\th = 2.2u\"cm\"\n\ts = 15u\"cm\"\n\tf = -23u\"cm\"\n\t\n\t# s′ = ?\n\t# Lens equation\n\t# 1/s + 1/s′ = 1/f\n\t# ⟹ s′f + sf = ss′\n\t# ⟹ s′(f - s) = -sf\n\t# ⟹ s′ = -sf/(f - s)\n\ts′ = -s*f/(f - s)\n\t\n\t# h′ = ?\n\t# Magnification equation\n\t# M = h′/h = -s′/s\n\t# ⟹ h′ = -s′/s h\n\th′ = -s′/s * h\n\t\n\ts′, abs(h′)\nend\n\n# ╔═╡ e98b7caa-8df6-4292-93f5-f364ddeda2a3\nmd\"### Problem 34.5\"\n\n# ╔═╡ 692de57c-99d1-439c-ab59-945db21dfe47\nlet\n\t(Ax, Ay) = (10u\"cm\", 5u\"cm\")\n\t(Bx, By) = (15u\"cm\", 15u\"cm\")\n\t\n\t# d = ?\n\t# Initial displacement\n\t# d = d0 + y\n\t\n\td0 = Ay\n\t\n\tbegin\n\t\t# y = ?\n\t\t# Use trigonometry relationship\n\t\t# tan(ϕ) = (By - Ay)/y = By/((By - Ay) - y)\n\t\t# let dy = By - Ay\n\t\t# ⟹ dy (dy - y) = By * y\n\t\t# ⟹ dy^2 - dy y = By * y\n\t\t# ⟹ dy^2 = y * (By + dy)\n\t\t# ⟹ y = dy^2 / (By + dy)\n\t\t\n\t\tdy = By - Ay\n\t\ty = dy^2 / (By + dy)\n\tend\n\t\n\td = d0 + y\nend\n\n# ╔═╡ 0efd04be-af2c-45e4-9aaa-b3fe5fb9c7d0\nmd\"### Problem 34.34\"\n\n# ╔═╡ da59c2ff-871e-4dee-9ec8-467ed823f11a\nlet\n\th = 1.1u\"cm\"\n\ts = 87.0u\"cm\"\n\tf = 31.0u\"cm\"\n\t\n\t# s′ = ?\n\t# Lens equation\n\t# 1/s + 1/s′ = 1/f\n\t# ⟹ s′f + sf = ss′\n\t# ⟹ s′(f - s) = -sf\n\t# ⟹ s′ = -sf/(f - s)\n\ts′ = -s*f/(f - s)\n\t\n\t# h′ = ?\n\t# Magnification equation\n\t# M = h′/h = -s′/s\n\t# ⟹ h′ = -s′/s h\n\th′ = -s′/s * h\n\t\n\ts′, abs(h′)\nend\n\n# ╔═╡ b520e5e2-702d-4131-9d10-3b12b04bda7e\nmd\"## PSW 12 (Chapter 34)\"\n\n# ╔═╡ c843abfd-f681-4850-83c0-f80241b3b122\nmd\"### Problem 34.52\"\n\n# ╔═╡ 210917a3-6257-4723-a0ee-5bc04dd87884\nlet\n\tx1 = 2.1u\"m\"\n\ty1 = 1.0u\"m\"\n\ty2 = 3.0u\"m\"\n\tn1 = 1.00\n\tn2 = 1.33\n\t\n\t# d = ?\n\t# d = x1 + x2\n\t\n\tbegin\n\t\t# x2 = ?\n\t\t# Trigonometry\n\t\t# tan(θ2) = x2/y2 ⟹ x2 = y2 tan(θ2)\n\t\t\n\t\tbegin\n\t\t\t# θ2 = ?\n\t\t\t# Snell's Law\n\t\t\t# n1 sin(θ1) = n2 sin(θ2)\n\t\t\t# ⟹ θ2 = asin(n1 sin(θ1) / n2)\n\n\t\t\tbegin\n\t\t\t\t# θ1 = ?\n\t\t\t\t# Trigonometry\n\t\t\t\t# tan(θ1) = x1/y1 ⟹ θ1 = atan(x1/y1)\n\t\t\t\tθ1 = atand(x1/y1)\n\t\t\tend\n\t\t\t\n\t\t\tθ2 = asind(n1 * sind(θ1) / n2)\n\t\tend\n\t\t\n\t\tx2 = y2 * tand(θ2)\n\tend\n\t\n\td = x1 + x2\nend\n\n# ╔═╡ ad1e49db-25cf-425a-88dd-47422330e85a\nmd\"### Problem 34.53\"\n\n# ╔═╡ b51230db-b12f-4c92-a140-79002eb2c1e0\nlet\n\ty = 1.90u\"m\"\n\tn1 = 1.00\n\ts = u\"m\"(36.0u\"cm\")\n\ts′ = u\"m\"(46.0u\"cm\")\n\tx = s′ - s\n\t\n\t# n2 = ?\n\t# Snell's law\n\t# n1 sin(θ1) = n2 sin(θ2)\n\t# ⟹ n1 = n2 sin(θ2)\n\t# ⟹ n2 = n1 / sin(θ2)\n\t\n\tbegin\n\t\t# θ2 = ?\n\t\t# Trigonometry\n\t\t# tan(θ2) = x/y ⟹ θ2 = atan(x/y)\n\t\t\n\t\tθ2 = atand(x/y)\n\tend\n\t\n\tn2 = n1 / sind(θ2) # Incorrect!\nend\n\n# ╔═╡ 9bf8ac4d-5c33-4dd5-a2d2-5ae1b03ebcd2\nmd\"### Problem 34.63\"\n\n# ╔═╡ 8799b871-5a4c-4663-afcc-35e58ccf502e\nlet\n\tM = 1.5\n\ts = 1.8u\"cm\"\n\t\n\t# f = ?\n\t# Mirror equation\n\t# 1/s + 1/s′ = 1/f\n\t# ⟹ s′f + sf = ss′\n\t# ⟹ f = ss′ / (s′ + s)\n\n\tbegin\n\t\t# s′ = ?\n\t\t# Magnification equation\n\t\t# M = -s′/s\n\t\t# ⟹ s′ = -M * s\n\t\t\n\t\ts′ = -M * s\n\tend\n\t\n\tf = s*s′ / (s′ + s)\nend\n\n# ╔═╡ 9e90dab3-6ba7-4298-889d-047bac5b5059\nmd\"### Problem 34.76\"\n\n# ╔═╡ 9df87359-662d-46d0-8983-d45c2798a93c\nlet\n\tM = 3\n\tr = 30u\"cm\"\n\tf = r / 2\n\t\n\t# s = ?\n\t# Mirror equation\n\t# 1/s + 1/s′ = 1/f\n\t# ⟹ 1/s + 1/3s = 1/f\n\t# ⟹ 3f - f = 3s\n\t# ⟹ 2f = 3s\n\t# ⟹ s = 2f/3\n\t\n\ts = 2f/3\nend\n\n# ╔═╡ a47cc5f3-9375-4128-bac4-da8bd689b46c\nmd\"### Problem 34.69\"\n\n# ╔═╡ ed90dde8-3230-4fe9-87c2-615aab4269bb\nlet\n\tr = 2.6u\"m\"\n\tM = -2\n\t\n\t# f = ?\n\t# Mirror equation\n\t# 1/s + 1/s′ = 1/f\n\t# ⟹ s′f + sf = ss′\n\t# ⟹ f = ss′ / (s′ + s)\n\t\n\t# s = ?\n\t# Magnification equation\n\t# M = -s′/s = -(r - s)/s\n\t# ⟹ sM = s - r\n\t# ⟹ s = r / (1 - M)\n\ts = r / (1 - M)\n\t\n\t# s′ = ?\n\t# s + s′ = r\n\t# ⟹ s′ = r - s\n\ts′ = r - s\n\t\n\tf = s*s′ / (s′ + s)\n\t\n\tf, s\nend\n\n# ╔═╡ 14f633eb-43f6-44b3-8558-6871f318d908\nmd\"### Problem 34.73\"\n\n# ╔═╡ bd8ebbf4-7a57-4216-9690-f7c407fcfc58\nlet\n\ts = 13u\"cm\"\n\tM = 2\n\t\n\t# s′ = ?\n\t# Magnification equation\n\t# M = -s′/s ⟹ s′ = -M*s\n\ts′ = -M * s\nend\n\n# ╔═╡ Cell order:\n# ╟─baaa0f44-a9d8-11eb-0d0d-53b78cd74315\n# ╟─c565da05-80ca-4b72-af73-d5da2f1c2abc\n# ╟─a1c99c25-e72e-4c4f-9ee9-855dad795483\n# ╟─c5cf2733-8d62-4f97-9c6c-97c6bce90b02\n# ╟─7abb1db1-d637-446c-9e55-3457db3db17e\n# ╟─be1d2a6e-8c24-4a1e-b84b-aabfad8e6135\n# ╟─6c9182b4-2bf5-40a8-8a7e-ecfb1f7e59f3\n# ╠═b670ab02-1fe7-4204-9747-237348707d97\n# ╟─3240dda1-8d4c-4551-8878-8c2ddd9f12d1\n# ╟─8a56ceb5-dbd9-4950-bbfe-50b56c682487\n# ╠═1d460401-7c48-4718-914e-ba3fc9f7950a\n# ╟─98b7f219-578b-4717-8dfa-5f22f86c04b2\n# ╟─f6b01ecd-9629-422c-800e-a41512fa9933\n# ╟─81d41ebd-9c50-49a1-b77d-1f6c600477e7\n# ╟─067e90ac-b370-4c53-b1d8-8ee65189b036\n# ╟─179020bb-048a-4040-b517-0c081a5b68c0\n# ╟─8065e0db-4aa8-447f-a130-49feedcddad7\n# ╟─5745f4ea-219d-4e60-b269-9e08f010836a\n# ╟─885d48fa-4a05-4468-8492-0cae4bfb7b26\n# ╟─2d690e4b-3d09-4907-99de-5f0ef4662b7e\n# ╟─eae4eef0-1701-406f-966d-736a2b2381f5\n# ╟─9ca8f846-5d5b-4b28-85b6-90c5f9c068b6\n# ╟─04912a55-5871-4917-8c95-7f03bd4abf1d\n# ╟─42f03b7e-9fec-40bc-8d22-e594a22ab54e\n# ╟─34b75779-b546-4628-ac0a-1d8fedc231eb\n# ╟─fb93dd3c-de36-4087-9870-8365161f7d1f\n# ╟─ab703047-2e82-4c13-a9d9-c97ffd42af67\n# ╟─253d5697-9088-424f-aa2e-c5df2c7675bf\n# ╟─fcdb7ea5-6203-4e74-b746-4470052b5f99\n# ╟─5db75338-4b19-4037-942d-979856662d6c\n# ╟─74378daa-7994-403e-9c41-86bae271a74d\n# ╟─af3ab252-16c6-4e6f-bdc6-9a01fede5a30\n# ╟─64bbc192-28dd-4db4-8dab-1cde2a031bc5\n# ╟─185600d3-131d-491d-869d-06a865280a5c\n# ╟─5fd137c7-a14e-4a53-9c9f-39f0992b1e43\n# ╟─8a9474e5-4b73-4a3e-9573-fa0ca066f9de\n# ╟─d8c9b9e2-eaa1-40e5-9899-f60d8fb9dddb\n# ╟─f6000dca-7d5a-4bb6-93ec-3de97124fe51\n# ╟─05c12afa-6ce0-4ab6-aac9-bb6a4f7a20e8\n# ╟─f30d8566-72fd-4658-a4cb-fcd2ac33b063\n# ╟─b6605cff-3e3c-40ed-b003-547a908a89f3\n# ╟─c53a0513-5a65-453b-8833-f4be54af3e0c\n# ╟─6be1aa76-6cf2-4e57-bde4-7effcc453073\n# ╟─8acec63d-de21-4698-9e51-579c16d2e398\n# ╟─1e73fe74-4f6d-4137-b771-2cfac7cf6332\n# ╟─762087fa-ffcf-4691-8c67-6837555bbfb0\n# ╟─d6dba861-4f6e-4aad-9b8c-1e18ee2639af\n# ╟─6cf18ee6-6b70-466f-9e23-32368cb35865\n# ╟─c5ee0bee-d2db-4daa-bbcf-5ac9f30b2f12\n# ╟─24a53a41-96a8-4bab-a8cf-1f3cd6ad30ff\n# ╟─060fd1a0-5548-4eb4-b4c2-f2db077e0d50\n# ╟─8eb2caa8-5341-40a7-8ae5-aad8e44c1af1\n# ╟─860bbf33-9025-44ee-aa26-7217f0bc7562\n# ╟─28acdfbe-1020-4921-8c6c-0e38d0732d78\n# ╟─e06efb86-5366-49c3-acb6-f9b209bf5d81\n# ╟─6c9233eb-058a-4e8a-9c9b-22964e210dd1\n# ╟─c83063bd-0bba-47e7-b869-e169d6e9c03e\n# ╟─c9102584-2196-4483-b79f-60089ad9e1b4\n# ╟─b30d503e-ab6c-4515-9a68-81327795aa6c\n# ╟─85e2b232-6a09-4621-ab97-e2345b676999\n# ╟─69bdb37e-2f06-4c78-a5bc-c3fce3cf6be8\n# ╟─f9ba57aa-4113-40e0-af24-8d7066baef4c\n# ╟─cdc4c352-a21c-4d88-8a6e-28da5974e893\n# ╟─bc7ebdc7-3614-43ad-bb1c-695f535c339b\n# ╟─3badd910-d0be-435d-8b61-751d2fc46984\n# ╟─f5871103-8943-4085-8ec8-f7c19155262c\n# ╟─64256f0e-f61a-41d9-9f07-f53f12b81d9f\n# ╟─56988b0d-40f0-485c-bfd1-468431e2f906\n# ╟─baf581de-7077-4c25-a5df-b5e82490b113\n# ╟─11c087b0-7823-41ac-8034-e66875bcaec1\n# ╟─ad23f43f-c8ac-48fd-9b21-901658710684\n# ╟─a59c5606-b60e-44c8-a7e3-b84cd89b322c\n# ╟─69065726-b456-4ab1-b8a6-22e638304388\n# ╟─47e713c1-0741-4135-ad0c-8b7ad003c141\n# ╟─45baa2c9-e2a9-44fc-a6a3-9e1b149d3ec6\n# ╟─a44466e8-0954-4738-9836-e7d445d41a91\n# ╟─13f7bece-837b-473e-bb86-df55d3f5dbdf\n# ╟─6917fdb5-0538-4995-9ac5-14d7fc92b903\n# ╟─018a2522-f201-44a7-8f63-d67411970a90\n# ╟─ebe19088-8374-441c-9c1b-c00194737814\n# ╟─30625a27-4961-4eff-be88-27a351a3db12\n# ╟─66bd1832-dd76-43fa-ab08-018c8e726885\n# ╟─08c4b0d3-a431-46dd-a0ae-3bd5a59b81e3\n# ╟─eff73afd-3ded-49d2-9411-ec11933fb31f\n# ╟─6e2b45e2-67bd-4512-9b3c-6f25dc75824f\n# ╟─9cf0faf9-ea42-45da-9788-975cfecdca37\n# ╟─67aca9a5-da3f-4a2c-9159-2dfb922217f8\n# ╟─37aeddcf-e1cf-40a0-925e-20d600f24845\n# ╟─5fb3d735-8df5-4e69-aa47-ff467dee9047\n# ╟─c4f15be9-ba69-4b9f-9b5a-407a975c2fbe\n# ╟─2c330d4d-8fa2-4c3f-a5b8-8a3ac19fd075\n# ╟─a2fbf237-3b84-4331-be33-e13c0f726838\n# ╟─84cdc818-8a8c-4888-b3bd-12399e60a739\n# ╟─b759a10f-6110-4e66-8121-e1c8bf24efee\n# ╟─9c245886-b491-4adf-9ccd-0f8d20326949\n# ╟─c352a601-03e9-4f47-9d8e-2e7e806a7433\n# ╟─d085be3a-89ec-4672-a47d-f5f2c020885b\n# ╟─3d7c7ea7-24a4-4acc-8238-e71118fef4f1\n# ╟─27a07162-335c-4d3a-9771-2a3793490631\n# ╟─04beeb35-c9b8-4aca-9afa-6d9cefaacc62\n# ╟─2f72f311-4bb9-4459-a1ee-3a3b5339b13f\n# ╟─082f1121-811b-4404-b561-6ce9ca6a05ce\n# ╟─4584596e-c66f-45b3-ad3d-3042f13a1eca\n# ╟─99a92b4f-0a27-4681-a372-e6db84db033a\n# ╟─3a92f0e7-983c-433d-a83d-7c4e1a52a206\n# ╟─ae445aa3-dcd9-4d97-87f7-7be0a2287cf3\n# ╟─6c521a07-2a6b-4ce8-a772-68b511bddf50\n# ╟─90a8d78d-cdf9-4485-ba31-1364e2c920ae\n# ╟─1f9d99d8-d613-4e62-9d46-5ebc61b029d6\n# ╟─141ea713-8276-4799-8e9c-f46f14e30c44\n# ╟─59508d51-2fab-4cab-816c-6d0c88979af8\n# ╟─685e68c4-2be2-4fc7-b22f-9dc78b231236\n# ╟─f0d975f2-dc73-476a-9dec-6c7939511066\n# ╟─d1a284e5-e3d9-4d9c-b350-f6a9f9d4bf23\n# ╟─a76b95fb-bf1e-4fea-ae0b-927017a78d1b\n# ╟─368b2131-d30c-42ae-9550-b51073e7592b\n# ╟─0acf5486-3702-4e8a-889e-871916d2ecf3\n# ╟─bfef7588-5c90-4a37-967e-660eb3e5efcd\n# ╟─86fa33b9-17da-4322-b195-fdc99687c518\n# ╟─9fdb361f-cb53-4270-a59c-6b967da468ea\n# ╟─4c54fa63-06a1-4519-8104-aea78a2bbfbe\n# ╟─a68a80e3-b74e-4dbf-93ce-2892bc6dafd5\n# ╟─cda191c4-afb2-4512-a930-171f5757a094\n# ╟─c721d98c-3586-450c-a22f-a4ff048d12c6\n# ╟─b55d0b05-3713-46ea-819e-d180e662a47e\n# ╠═16f0dd9e-f5bb-4173-a07c-7feba801837f\n# ╟─b87d87a8-da10-4af4-94af-868947f45d02\n# ╟─e664b06c-2924-423c-9f1b-52174fca7cc3\n# ╟─7ec6edf3-7b6d-4ea2-8a4f-86dd2178eb91\n# ╟─6de0da98-8dfe-496d-adc8-82c5c9af499e\n# ╟─d518d932-52d5-45de-aaf4-d94dfaf3eb64\n# ╟─570a8d6f-b108-4bba-81a4-8adffe79cea5\n# ╟─e275bc47-c73c-4cf5-bbdb-bebee2fb08af\n# ╟─07adb0ac-6cb2-40ed-ad5f-659a6f58303b\n# ╟─276749db-45c7-43b9-a746-e48a6bdede2e\n# ╟─4689568d-ba6d-4954-86ba-3fcadb52f957\n# ╟─9a0b5bac-f167-4150-beaa-3c770dbc8cac\n# ╟─7094b76b-519e-4427-91fe-88d33304fef1\n# ╟─82836166-8d43-4c15-a2d8-ac451a1d20ab\n# ╟─06389e81-54a5-46df-b7a6-fd11b44c5406\n# ╟─5b87298f-9b97-4f7c-aab5-b3d740f9cab0\n# ╟─980aa663-98cd-42be-9b92-238a452f537a\n# ╟─44d12feb-10cf-48b2-929a-8e6ff39a9496\n# ╟─9f4b96a0-2b5e-47d0-8694-1c1d2144fd01\n# ╟─2434b3b5-2da8-4c1b-8bf2-522fc75b5cd1\n# ╟─72bd9e28-5048-48f2-a110-f5feaa67caee\n# ╟─a8dd4343-6913-4e19-bc12-23e89c9e6236\n# ╟─239d8478-4571-4155-90e3-95ae1deb4939\n# ╟─a748ef26-adc8-4fe5-ad2b-8c8b1d79b54d\n# ╟─f584bd06-21b6-41c2-b729-84b77acd2e2f\n# ╟─0fbb0fa0-6c8e-497f-856f-2f3f8f2ce735\n# ╟─4e172839-92b8-411a-ab77-3f8238d3a5e1\n# ╟─51cf30e3-8fdc-4b62-a1a6-9252ed608dc9\n# ╟─1183767b-3d27-49c0-91ba-fd65e96cf773\n# ╟─9086f546-aa48-438e-b682-b0f27b2bff5c\n# ╟─d78a8b7b-4ea8-45ad-9d8d-331a090170a4\n# ╟─b7181523-93b0-4865-9c91-9ee965124bfa\n# ╟─fe0fb4f9-6d8f-48e7-9809-71c55035ba75\n# ╟─39fe00bb-0eb1-4f31-8073-e17186da71e7\n# ╟─818d7074-6ce6-4746-a15e-a101ae653ec9\n# ╟─da06ac7d-67f3-483c-aad0-98529cf44a28\n# ╟─eae1f535-37ac-48dd-8f2c-65b88852fa43\n# ╟─d0224ffa-a5ef-465c-89fe-bc293e4d46ad\n# ╟─4ff2da18-3d84-4cc8-9588-9fcc017aa4db\n# ╟─73709c95-3e75-48b9-9465-b80684920db7\n# ╟─6036b824-7567-444a-8bad-a0472aeb549e\n# ╟─9a0f2ce9-6ac6-4c9a-a1dc-dc2e93187247\n# ╟─3bd6fefb-1475-4044-b637-f2358469d38f\n# ╟─87b9e579-9e52-4d85-8c33-8438c548184a\n# ╟─8633003f-0de3-466a-974a-9087eaea00ec\n# ╟─ffa99665-c461-43ee-9939-e6027e53fad8\n# ╟─81deea62-431f-404e-9df4-7536baa0cabd\n# ╟─cb6cc92b-2d9a-4ee7-9e82-a175c0d1202f\n# ╟─16e94b95-66bd-4b73-8185-e564eb2d6789\n# ╟─6516bc36-7df5-4522-90e1-57ddbf01bd9d\n# ╟─aab4689d-9e64-486c-8913-99972148d7f5\n# ╟─b7a99f37-aeb3-4123-aa05-dadfca72f06e\n# ╟─c6563fbe-7118-4ddc-a922-9e9327b46bc5\n# ╟─79f4dc36-9ea9-4f22-9e0a-23f7e7bc139e\n# ╟─80c5e3e4-61bd-46cd-aa7c-1f6b098269a6\n# ╟─cd63ab55-26fe-4015-b171-0a1073eee06d\n# ╟─f08902fd-e2b8-47bc-b6fe-ffee0c0b5267\n# ╟─ed2b1790-224a-442e-9971-dc8f5313dbcc\n# ╟─c32eba5a-fc0e-4eb3-b179-3c4ef4dbc000\n# ╟─574b6d09-5147-404b-a0b7-3a7f6c88e251\n# ╟─6a8c8c80-3833-42ef-b5e2-b36385d2a456\n# ╟─3d9f7f6a-f6d4-4566-80ca-61b791cde540\n# ╟─e25ab1b9-ead0-48cd-8bb4-8611cba660dc\n# ╟─e18a7261-ef49-4a4d-a961-4d4977554e1d\n# ╟─2c9665eb-2e88-4405-8eb6-4804253a34dd\n# ╟─bb10b8d6-d5e3-415f-bda7-9f26cd52f3a6\n# ╟─ff1c72bf-e271-46df-a288-8619a9f0a2e4\n# ╟─c40cfee1-3a46-4b05-ad7e-e2a8126f56cd\n# ╟─c24e62c5-08e4-465c-b8cb-80328a8df16f\n# ╟─19d8e693-2fa4-4311-8fab-40c636d19169\n# ╟─c810aee0-42df-4e43-9a0c-5b3a37e0c892\n# ╟─058a4e62-655b-4e86-8ac9-c14c9f303153\n# ╟─9594aa75-3585-4a4b-8f16-0e23e999268d\n# ╟─4379e2f3-d536-40c1-bff6-dbd652c496ff\n# ╟─746b5d5b-5fde-4270-9e52-129f21ac722b\n# ╟─40616231-34a0-4308-ac97-05ef93da2c86\n# ╟─f8c5aaf6-7cbb-4a87-b08c-fbea27e0658a\n# ╟─65c05232-36bb-4df8-8146-4e8237e11758\n# ╟─ae4eb3d7-cb85-4655-9e12-fdbb1e99af1b\n# ╠═9319bfbb-97c1-44f4-b605-16ee995476c3\n# ╟─ef5e8506-4a02-42a1-950d-4a53aecd42d7\n# ╟─9f5e3964-3c67-41c8-b194-3dcdd6d485c2\n# ╠═5fe3b6d7-2277-4c43-8e21-7cd4203433cc\n# ╟─c50bcc01-6ab1-43d6-bdb0-4e9e17b524c0\n# ╟─4830439e-3665-44c1-88c4-2b63da020890\n# ╟─dde0edeb-b85c-4bca-b5e9-a75255dc50af\n# ╟─1120ad44-3519-4a0e-b464-d3666470ca35\n# ╟─fefd36c1-8607-4825-b72b-4d4f0f357523\n# ╠═ffb0edda-d3b5-4154-9df0-95758f3f3f12\n# ╟─c45dde4e-d60f-4543-a2ee-d061f45bc848\n# ╟─0bcd7967-9648-4f80-8b8b-7a1459f963b7\n# ╟─ee17d3a7-a845-4b0d-991f-0d1546bd89c8\n# ╠═0497b136-6780-4e31-9066-5cab808fa9f3\n# ╟─a57d36a2-c69a-4a4b-b623-e7067527a8d6\n# ╠═42774779-7c00-46c6-af46-29e6bfa5b362\n# ╟─924acf6e-5ada-4a64-ad51-1ff5ce84bb5e\n# ╟─7bb28d6d-6d18-4209-b48e-5e87eedec74b\n# ╠═d878a54c-a6e3-4fa7-81c9-5b045781f353\n# ╟─862df6ac-1091-48b6-93a3-6cf64aa27dde\n# ╠═294246d2-c696-4f46-b746-d5f40234eb59\n# ╟─9a3ac337-de34-41cb-96cf-7c2dd7cd47e3\n# ╟─5bfab755-ed80-4318-ba3e-5774c89fff9f\n# ╠═06f1e08c-95b3-430d-86a1-3de041fe1506\n# ╟─64d28e04-f67f-4b98-afd6-9c16a15f2277\n# ╠═a502e763-da48-4811-ab9b-6d2075c94758\n# ╟─634882f3-baf9-4e98-a7c2-03c08314322d\n# ╠═0a95a636-be2d-43cc-ac71-707c88d5f117\n# ╟─9fa6bc2f-f99f-4d4b-91fa-695d04f0e83b\n# ╠═2b72b700-5b08-4744-b29e-2714ec33580a\n# ╟─998d6c8b-3af1-4549-b633-13f4977e9afe\n# ╠═a18585ce-d13b-4581-9c49-65c54bc3436f\n# ╟─d8f53b47-1267-426b-a6d6-15b397dc8d9e\n# ╠═f6840354-2325-470c-8fd1-a3246f236550\n# ╟─dc205f5d-0512-4429-8f26-f60e9f07115b\n# ╟─d6e4e26e-cb79-4aa1-8d97-1f2f238aeb10\n# ╠═9f8323d5-1480-490a-b088-be9d69bf6e00\n# ╟─4a0ecf24-5fc7-4586-9313-3c2fc33ea91c\n# ╠═c494b302-bf92-44b5-abf2-59956da672d5\n# ╟─c8d2f67e-33ec-4ecd-b7f4-2037c1ac91ec\n# ╠═6bc0b95d-be29-42ba-93ca-bb1bc910256e\n# ╟─971c6622-d701-4142-addf-55c2fb8007bd\n# ╟─beedbeca-0477-4162-9c9e-05aa9cfd907f\n# ╠═63619364-64ad-44aa-bbc5-1a847358c892\n# ╟─d05ed603-19ce-4c7d-b67d-78e7258378d5\n# ╠═21c3aacf-abb7-4f65-8681-440ee3c13341\n# ╟─651147e8-f7f8-4b87-9793-21e9b82a7c91\n# ╠═f30306c0-0006-4a6f-873a-07fadcdc5d2d\n# ╟─bfec2cfd-b400-4e73-8a40-7b3665209a5d\n# ╟─1b65d5b3-ffb4-4c4c-a071-24cf1cfdd0c4\n# ╠═6a010c2a-f8e6-44db-84ff-8e9a9593a29e\n# ╟─e5254b57-0930-4083-b8d5-b37ae9292052\n# ╠═d7fd0a6d-2df6-4614-abf0-72971f07220b\n# ╟─e6375fb6-ae08-4442-b7c5-26953bd1cd95\n# ╠═adcf50c9-8c45-46fa-aca3-10a5c660f80b\n# ╟─549d2a7f-d307-4c96-9df5-6f936842cc59\n# ╠═4cd51b45-2e77-41a2-9691-2d5e1fc01d3f\n# ╟─3945a727-df1d-4717-b9d1-3b14f9e07adf\n# ╟─9c8a76a8-7caa-4d0d-9608-4e98d3955677\n# ╠═bf938d16-4f96-409a-b3e7-39f6873ca275\n# ╟─e4ecd474-4d48-4414-93b4-6eb029da45eb\n# ╠═b798ffc4-bc44-4add-885f-96b88cf66960\n# ╟─1d2210ec-00a9-4960-8686-85df92dae42d\n# ╠═d2162fdf-dc4b-4138-8cc8-6ac803d82566\n# ╟─57086fd7-66cb-4a72-b589-dc5fa3c8c8c2\n# ╠═a7972df8-734e-4108-86b6-c0a5d0ede63d\n# ╟─465bc5f9-d40c-4227-8962-da6746b1dcc4\n# ╠═2817d2a7-fb3f-4986-adb9-3fb36a66d1b9\n# ╟─6f906af6-1379-42a3-b24d-dd5d257241c9\n# ╠═b94bf1ef-fb85-4e1a-92f8-3f47e143f9e6\n# ╟─1568e950-6ae3-4eee-8c28-8db36795a929\n# ╠═66cb890a-45af-4faf-8ecd-02df1bcdf3e6\n# ╟─22fc3d80-341b-4902-89c1-c1a587c28a08\n# ╟─63b35422-6697-4a1f-8d60-55c977a87360\n# ╠═d410ae9c-d876-4ac2-9d7d-44154cc24325\n# ╟─e0a50b78-31a1-45ee-be74-2c6d8b5f13b8\n# ╠═77c5d223-6de7-454f-b6d3-2895600e2b1a\n# ╟─85dee8d0-d364-4744-a5ac-5459f7c1a95c\n# ╠═91d1441c-8d8b-4652-b089-5d06d191d21d\n# ╟─2e69b5bd-0b56-4bf2-a338-b4d373dde517\n# ╠═e65a8d69-d925-4de2-9edd-c33669b756a8\n# ╟─e0d4b7ca-578b-4d25-a9e6-81baafa497b0\n# ╠═f44da9f7-87fa-4a44-864b-11e54553b3b0\n# ╟─ca39044c-f352-4fb9-a8be-355f4a01a17d\n# ╠═092aa2fc-ddc6-4729-911c-aa4e21ad7bd9\n# ╟─3ece80ba-1bde-48a9-93ff-d6b9778b43e2\n# ╟─07586a45-e8b7-466d-99b5-5b1fc20b32eb\n# ╠═88053dfe-70e5-498a-bfd1-cb7eb33fad96\n# ╟─4c49f6cf-0f0e-408c-acde-ad77faa9903c\n# ╠═da63cb45-9b93-4423-8fd7-0b6aae9e4a29\n# ╟─472fc923-c527-47e4-9ea2-e2a762c08f62\n# ╠═916addb5-4a54-422d-b9c9-5b24c3f16e3f\n# ╟─bfafde7f-8d61-41fb-be8c-d3bf12404fab\n# ╠═892661d3-046f-4df9-9269-89f26ca79b4c\n# ╟─04898c9a-5eca-4d1f-bd19-aec0d16f51d8\n# ╠═8f1b5656-c3e6-4490-ba16-fbeb3f9c574e\n# ╟─705a1476-eb5d-4f76-af51-4cf3bb61d36d\n# ╟─ff9db5b4-9875-4279-8957-4cfd3245d6f7\n# ╠═61c3c8a1-4a00-4c1f-8c82-6594bcdfb006\n# ╟─241d99b8-c672-40f3-8b9d-854413a57630\n# ╠═d40d40e9-e141-4161-8cc7-403d30e74304\n# ╟─df7ed866-611b-4b64-94fd-b5876ed39336\n# ╠═c74ce47c-697f-4fa6-9d27-bef932bd2d54\n# ╟─69e73591-3bdf-4e31-9ce9-4c1f44e207a8\n# ╠═3388d0f4-ace3-4322-89ba-a06ba0840adf\n# ╟─aa2e1f09-bb0e-452d-b277-32ed87f1d805\n# ╟─49522fe9-e9d9-433c-92a2-072d60e1576e\n# ╠═e9661551-68aa-41fc-be08-e88b8444e4f6\n# ╟─8d7d25f5-f27e-4b86-a845-15e9a3dd2f72\n# ╠═3548c0a7-1de7-4534-a930-58d80e9efad7\n# ╟─b550aa41-be86-4336-91cd-816565045da5\n# ╠═0fe25f6d-0132-4fa4-a1b8-a03963fd1ee7\n# ╟─a6e0b275-276f-4c0b-b548-4a4c283a6330\n# ╠═f0a5c1d8-0de4-4455-b6e7-73b0426cd04c\n# ╟─ceccbe3d-5c9a-47bf-a168-18154f30729b\n# ╠═6f920972-e2ab-4e62-855e-9bac912831df\n# ╟─3be6b392-ea30-4015-a718-41f43797626e\n# ╠═1c600f48-8f4d-4841-bfcf-14e805e284b8\n# ╟─f4730b14-2902-457d-a5f8-7e9140926b1e\n# ╠═2fbca1ac-29e5-4f5b-8cac-faf6b48045eb\n# ╟─c9cae5ed-a959-4c20-a4a6-21b6962f7fc5\n# ╠═53439784-13c7-4f08-949d-e60cd41d4494\n# ╟─e98b7caa-8df6-4292-93f5-f364ddeda2a3\n# ╠═692de57c-99d1-439c-ab59-945db21dfe47\n# ╠═0efd04be-af2c-45e4-9aaa-b3fe5fb9c7d0\n# ╠═da59c2ff-871e-4dee-9ec8-467ed823f11a\n# ╟─b520e5e2-702d-4131-9d10-3b12b04bda7e\n# ╟─c843abfd-f681-4850-83c0-f80241b3b122\n# ╠═210917a3-6257-4723-a0ee-5bc04dd87884\n# ╟─ad1e49db-25cf-425a-88dd-47422330e85a\n# ╠═b51230db-b12f-4c92-a140-79002eb2c1e0\n# ╟─9bf8ac4d-5c33-4dd5-a2d2-5ae1b03ebcd2\n# ╠═8799b871-5a4c-4663-afcc-35e58ccf502e\n# ╟─9e90dab3-6ba7-4298-889d-047bac5b5059\n# ╠═9df87359-662d-46d0-8983-d45c2798a93c\n# ╟─a47cc5f3-9375-4128-bac4-da8bd689b46c\n# ╠═ed90dde8-3230-4fe9-87c2-615aab4269bb\n# ╟─14f633eb-43f6-44b3-8558-6871f318d908\n# ╠═bd8ebbf4-7a57-4216-9690-f7c407fcfc58\n", "meta": {"hexsha": "54516ac2dc40c83c2180e67cc7c4c51641a39ce3", "size": 77041, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "PHYS1062FinalsReview.jl", "max_stars_repo_name": "airicbear/finals-review", "max_stars_repo_head_hexsha": "4c3fafe0fde2d656b28baebce516b2b22a494067", "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": "PHYS1062FinalsReview.jl", "max_issues_repo_name": "airicbear/finals-review", "max_issues_repo_head_hexsha": "4c3fafe0fde2d656b28baebce516b2b22a494067", "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": "PHYS1062FinalsReview.jl", "max_forks_repo_name": "airicbear/finals-review", "max_forks_repo_head_hexsha": "4c3fafe0fde2d656b28baebce516b2b22a494067", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3953841482, "max_line_length": 332, "alphanum_fraction": 0.660868888, "num_tokens": 38833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014736319616964, "lm_q2_score": 0.13296424535145931, "lm_q1q2_score": 0.05719421953729878}} {"text": "# Before running this, please make sure to activate and instantiate the environment\n# corresponding to [this `Project.toml`](https://raw.githubusercontent.com/alan-turing-institute/MLJTutorials/master/Project.toml) and [this `Manifest.toml`](https://raw.githubusercontent.com/alan-turing-institute/MLJTutorials/master/Manifest.toml)\n# so that you get an environment which matches the one used to generate the tutorials:\n#\n# ```julia\n# cd(\"MLJTutorials\") # cd to folder with the *.toml\n# using Pkg; Pkg.activate(\".\"); Pkg.instantiate()\n# ```\n\n# ## Machine type vs Scientific Type## ### Why make a distinction?## When analysing data, it is important to distinguish between## * *how the data is encoded* (e.g. `Int`), and# * *how the data should be interpreted* (e.g. a class label, a count, ...)## How the data is encoded will be referred to as the **machine type** whereas how the data should be interpreted will be referred to as the **scientific type** (or `scitype`).## In some cases, this may be un-ambiguous, for instance if you have a vector of floating point values, this should usually be interpreted as a continuous feature (e.g.: weights, speeds, temperatures, ...).## In many other cases however, there may be ambiguities, we list a few examples below:## * A vector of `Int` e.g. `[1, 2, ...]` which should be interpreted as categorical labels,# * A vector of `Int` e.g. `[1, 2, ...]` which should be interpreted as count data,# * A vector of `String` e.g. `[\"High\", \"Low\", \"High\", ...]` which should be interpreted as ordered categorical labels,# * A vector of `String` e.g. `[\"John\", \"Maria\", ...]` which should not interpreted as informative data,# * A vector of floating points `[1.5, 1.5, -2.3, -2.3]` which should be interpreted as categorical data (e.g. the few possible values of some setting), etc.## ### The Scientific Types## The package [ScientificTypes.jl](https://github.com/alan-turing-institute/ScientificTypes.jl) defines a barebone type hierarchy which can be used to indicate how a particular feature should be interpreted; in particular:## ```plaintext# Found# ├─ Known# │ ├─ Textual# │ ├─ Finite# │ │ ├─ Multiclass# │ │ └─ OrderedFactor# │ └─ Infinite# │ ├─ Continuous# │ └─ Count# └─ Unknown# ```## A *scientific type convention* is a specific implementation indicating how machine types can be related to scientific types. It may also provide helper functions to convert data to a given scitype.## The convention used in MLJ is implemented in [MLJScientificTypes.jl](https://github.com/alan-turing-institute/ScientificTypes.jl).# This is what we will use throughout; you never need to use ScientificTypes.jl# unless you intend to implement your own scientific type convention.## ### Inspecting the scitype## The `schema` function\nusing RDatasets, MLJScientificTypes\nboston = dataset(\"MASS\", \"Boston\")\nsch = schema(boston)\n\n# In this cases, most of the variables have a (machine) type `Float64` and# their default interpretation is `Continuous`.# There is also `:Chas`, `:Rad` and `:Tax` that have a (machine) type `Int64`# and their default interpretation is `Count`.## While the interpretation as `Continuous` is usually fine, the interpretation# as `Count` needs a bit more attention.# For instance note that:\nunique(boston.Chas)\n\n# so even though it's got a machine type of `Int64` and consequently a# default interpretation of `Count`, it would be more appropriate to interpret# it as an `OrderedFactor`.## ### Changing the scitype## In order to re-specify the scitype(s) of feature(s) in a dataset, you can# use the `coerce` function and specify pairs of variable name and scientific# type:\nboston2 = coerce(boston, :Chas => OrderedFactor);\n\n# the effect of this is to convert the `:Chas` column to an ordered categorical# vector:\neltype(boston2.Chas)\n\n# corresponding to the `OrderedFactor` scitype:\nelscitype(boston2.Chas)\n\n# You can also specify multiple pairs in one shot with `coerce`:\nboston3 = coerce(boston, :Chas => OrderedFactor, :Rad => OrderedFactor);\n\n# ### String and Unknown## If a feature in your dataset has String elements, then the default scitype# is `Textual`; you can either choose to drop such columns or to coerce them# to categorical:\nfeature = [\"AA\", \"BB\", \"AA\", \"AA\", \"BB\"]\nelscitype(feature)\n\n# which you can coerce:\nfeature2 = coerce(feature, Multiclass)\nelscitype(feature2)\n\n# ## Tips and tricks## ### Type to Type coercion## In some cases you will want to reinterpret all features currently# interpreted as some scitype `S1` into some other scitype `S2`.# An example is if some features are currently interpreted as `Count` because# their original type was `Int` but you want to consider all such as# `Continuous`:\ndata = select(boston, [:Rad, :Tax])\nschema(data)\n\n# let's coerce from `Count` to `Continuous`:\ndata2 = coerce(data, Count => Continuous)\nschema(data2)\n\n# ### Autotype## A last useful tool is `autotype` which allows you to specify *rules* to# define the interpretation of features automatically.# You can code your own rules but there are three useful ones that are pre-# coded:## * the `:few_to_finite` rule which checks how many unique entries are present# in a vector and if there are \"few\" suggests a categorical type,# * the `:discrete_to_continuous` rule converts `Integer` or `Count` to# `Continuous`# * the `:string_to_multiclass` which returns `Multiclass` for any string-like# column.## For instance:\nboston3 = coerce(boston, autotype(boston, :few_to_finite))\nschema(boston3)\n\n# You can also specify multiple rules, see [the docs](https://alan-turing-institute.github.io/MLJScientificTypes.jl/stable/#Automatic-type-conversion-for-tabular-data-1) for more information.\n# This file was generated using Literate.jl, https://github.com/fredrikekre/Literate.jl\n\n", "meta": {"hexsha": "a4446a680ba3860d051df3f1e5f238579e4f7aa9", "size": 5792, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "__site/generated/scripts/D0-scitype.jl", "max_stars_repo_name": "ven-k/MLJTutorials", "max_stars_repo_head_hexsha": "42151c8a96ad701aeaf763d53c8b7c6689eb6e8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "__site/generated/scripts/D0-scitype.jl", "max_issues_repo_name": "ven-k/MLJTutorials", "max_issues_repo_head_hexsha": "42151c8a96ad701aeaf763d53c8b7c6689eb6e8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "__site/generated/scripts/D0-scitype.jl", "max_forks_repo_name": "ven-k/MLJTutorials", "max_forks_repo_head_hexsha": "42151c8a96ad701aeaf763d53c8b7c6689eb6e8d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 109.2830188679, "max_line_length": 2245, "alphanum_fraction": 0.7353245856, "num_tokens": 1495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014733397551624, "lm_q2_score": 0.1329642333263228, "lm_q1q2_score": 0.05719421047941624}} {"text": "\"\"\"\n ArcEager()\n\nArc-Eager transition system for dependency parsing.\n\n# Transitions\n\n| Transition | Definition |\n|:----------- |:--------------------------------------------- |\n| LeftArc(l) | (σ\\\\|s, b\\\\|β, A) → (σ, b\\\\|β, A ∪ (b, l, s)) |\n| RightArc(l) | (σ\\\\|s, b\\\\|β, A) → (σ, b\\\\|β, A ∪ (b, l, s)) |\n| Reduce | (σ\\\\|s, β, A) → (σ, β, A) |\n| Shift\t | (σ, b\\\\|β, A) → (σ\\\\|b, β, A) |\n\n# Preconditions\n\n| Transition | Condition |\n|:----------- |:-------------------------------- |\n| LeftArc(l) | ¬[s = 0], ¬∃k∃l'[(k, l', i) ϵ A] |\n| RightArc(l) | ¬∃k∃l'[(k, l', j) ϵ A] |\n| Reduce | ∃k∃l[(k, l, i) ϵ A] |\n\n# References\n\n[Nivre 2003](http://stp.lingfil.uu.se/~nivre/docs/iwpt03.pdf), [Nivre 2008](https://www.aclweb.org/anthology/J08-4003.pdf).\n\"\"\"\nstruct ArcEager <: AbstractTransitionSystem end\n\ninitconfig(::ArcEager, graph::DependencyTree) =\n ArcEagerConfig(graph)\n\ntransition_space(::ArcEager, labels=[]) =\n isempty(labels) ? [LeftArc(), RightArc(), Reduce(), Shift()] :\n [LeftArc.(labels)..., RightArc.(labels)..., Reduce(), Shift()]\n\nprojective_only(::ArcEager) = true\n\nstruct ArcEagerConfig <: AbstractParserConfiguration\n stack::Vector{Int}\n buffer::Vector{Int}\n A::Vector{Token}\nend\n\nArcEagerConfig(sentence) = stack_buffer_config(ArcEagerConfig, sentence)\n\nbuffer(cfg::ArcEagerConfig) = cfg.buffer\nstack(cfg::ArcEagerConfig) = cfg.stack\ntokens(cfg::ArcEagerConfig) = cfg.A\n\nfunction apply_transition(f, cfg::ArcEagerConfig, a...; k...)\n σ, β, A = f(cfg.stack, cfg.buffer, cfg.A, a...; k...)\n return ArcEagerConfig(σ, β, A)\nend\n\nleftarc(cfg::ArcEagerConfig, args...; kwargs...) =\n apply_transition(leftarc_reduce, cfg, args...; kwargs...)\n\nrightarc(cfg::ArcEagerConfig, args...; kwargs...) =\n apply_transition(rightarc_shift, cfg, args...; kwargs...)\n\nreduce(cfg::ArcEagerConfig) = apply_transition(reduce, cfg)\n\nshift(cfg::ArcEagerConfig) = apply_transition(shift, cfg)\n\nisfinal(cfg::ArcEagerConfig) = all(has_head, cfg.A)\n\nhas_head(cfg::ArcEagerConfig, k) = has_head(token(cfg, k))\n\n\"\"\"\n static_oracle(cfg::ArcEagerConfig, gold, arc=untyped)\n\nDefault static oracle function for arc-eager dependency parsing.\n\nSee [Goldberg & Nivre 2012](https://www.aclweb.org/anthology/C12-1059.pdf).\n(Also called Arc-Eager-Reduce in [Qi & Manning 2017](https://nlp.stanford.edu/pubs/qi2017arcswift.pdf)).\n\"\"\"\nfunction static_oracle(cfg::ArcEagerConfig, gold, arc=untyped)\n if stacklength(cfg) >= 1\n (σ, s) = popstack(cfg)\n if bufferlength(cfg) >= 1\n (b, β) = shiftbuffer(cfg)\n has_arc(gold, b, s) && return LeftArc(arc(gold[s])...)\n has_arc(gold, s, b) && return RightArc(arc(gold[b])...)\n end\n if all(k -> k > 0 && has_head(cfg, k), [s ; deps(gold, s)])\n return Reduce()\n end\n end\n return Shift()\nend\n\n\"\"\"\n static_oracle_prefer_shift(cfg::ArcEagerConfig, tree, arc=untyped)\n\nStatic oracle for arc-eager dependency parsing. Similar to the\n\"regular\" static oracle, but always Shift when ambiguity is present.\n\nSee [Qi & Manning 2017](https://nlp.stanford.edu/pubs/qi2017arcswift.pdf).\n\"\"\"\nfunction static_oracle_prefer_shift(cfg::ArcEagerConfig, tree, arc=untyped)\n l = i -> arc(token(tree, i))\n gold_arc = (a, b) -> has_arc(tree, a, b)\n (σ, s), (b, β) = popstack(cfg), shiftbuffer(cfg)\n gold_arc(b, s) && return LeftArc(l(s)...)\n gold_arc(s, b) && return RightArc(l(b)...)\n must_reduce = false\n for k in stack(cfg)\n if gold_arc(k, b) || gold_arc(b, k)\n must_reduce = true\n break\n elseif has_head(token(cfg, k), -1)\n break\n end\n end\n has_right_children = any(k -> s in rightdeps(tree, k), buffer(cfg))\n if !must_reduce || s > 0 && !has_head(cfg, s) || has_right_children\n return Shift()\n else\n return Reduce()\n end\nend\n\n\"\"\"\n dynamic_oracle(cfg::ArgEagerConfig, tree, arc=untyped)\n\nDynamic oracle function for arc-eager parsing.\n\nFor details, see [Goldberg & Nivre 2012](https://aclweb.org/anthology/C12-1059).\n\"\"\"\ndynamic_oracle(cfg::ArcEagerConfig, tree, arc=untyped) =\n filter(t -> cost(t, cfg, tree) == 0, possible_transitions(cfg, tree, arc))\n\n# see figure 2 in goldberg & nivre 2012 \"a dynamic oracle...\"\npossible_transitions(cfg::ArcEagerConfig, graph::DependencyTree, arc=untyped) =\n possible_transitions(cfg, arc)\n\nfunction possible_transitions(cfg::ArcEagerConfig, arc=untyped)\n ts = TransitionOperator[]\n if is_possible(LeftArc(), cfg)\n s = last(stack(cfg))\n push!(ts, LeftArc(arc(token(cfg, s))...))\n end\n if is_possible(RightArc(), cfg)\n b = first(buffer(cfg))\n push!(ts, RightArc(arc(token(cfg, b))...))\n end\n is_possible(Reduce(), cfg) && push!(ts, Reduce())\n is_possible(Shift(), cfg) && push!(ts, Shift())\n return ts\nend\n\nfunction cost(t::LeftArc, cfg::ArcEagerConfig, gold)\n # left arc cost: num of arcs (k,l',s), (s,l',k) s.t. k ϵ β\n σ, s = popstack(cfg)\n b, β = shiftbuffer(cfg)\n if has_arc(gold, b, s)\n 0\n else\n count(k -> has_arc(gold, k, s) || has_arc(gold, s, k), β)\n end\nend\n\nfunction cost(t::RightArc, cfg::ArcEagerConfig, gold)\n # right arc cost: num of gold arcs (k,l',b), s.t. k ϵ σ or k ϵ β,\n # plus num of gold arcs (b,l',k) s.t. k ϵ σ\n σ, s = popstack(cfg)\n b, β = shiftbuffer(cfg)\n if has_arc(gold, s, b)\n 0\n else\n count(k -> has_arc(gold, k, b), [σ ; β]) + count(k -> has_arc(gold, b, k), σ)\n end\nend\n\nfunction cost(t::Reduce, cfg::ArcEagerConfig, gold)\n # num of gold arcs (s,l',k) s.t. k ϵ b|β\n σ, s = popstack(cfg)\n count(k -> has_arc(gold, s, k), buffer(cfg))\nend\n\nfunction cost(t::Shift, cfg::ArcEagerConfig, gold)\n # num of gold arcs (k,l',b), (b,l',k) s.t. k ϵ s|σ\n b, β = shiftbuffer(cfg)\n count(k -> has_arc(gold, k, b) || has_arc(gold, b, k), stack(cfg))\nend\n\nfunction is_possible(::LeftArc, cfg::ArcEagerConfig)\n if length(cfg.stack) > 0 && length(cfg.buffer) > 0\n s = last(stack(cfg))\n return s != 0 && !has_head(token(cfg, s))\n end\n return false\nend\n\nfunction is_possible(::RightArc, cfg::ArcEagerConfig)\n return length(cfg.stack) > 0 && length(cfg.buffer) > 0 && \n !has_head(token(cfg, first(buffer(cfg))))\nend\n\nis_possible(::Reduce, cfg::ArcEagerConfig) =\n stacklength(cfg) > 0 && has_head(token(cfg, last(stack(cfg))))\n\nis_possible(::Shift, cfg::ArcEagerConfig) = bufferlength(cfg) > 0\n\n==(cfg1::ArcEagerConfig, cfg2::ArcEagerConfig) =\n cfg1.stack == cfg2.stack && cfg1.buffer == cfg2.buffer && cfg1.A == cfg2.A\n\nBase.getindex(cfg::ArcEagerConfig, i) = token(cfg, i)\n", "meta": {"hexsha": "78791e5cc5d79bf5a99f92295f67d32d62526c0a", "size": 6781, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/transition_parsing/systems/arc_eager.jl", "max_stars_repo_name": "dellison/DependencyTrees.jl", "max_stars_repo_head_hexsha": "d5889ac8ce64f00b500bf3485507e7ab94375b3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-03-13T02:07:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-07T21:30:21.000Z", "max_issues_repo_path": "src/transition_parsing/systems/arc_eager.jl", "max_issues_repo_name": "dellison/DependencyTrees.jl", "max_issues_repo_head_hexsha": "d5889ac8ce64f00b500bf3485507e7ab94375b3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2018-09-09T22:43:46.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-19T17:10:31.000Z", "max_forks_repo_path": "src/transition_parsing/systems/arc_eager.jl", "max_forks_repo_name": "dellison/DependencyTrees.jl", "max_forks_repo_head_hexsha": "d5889ac8ce64f00b500bf3485507e7ab94375b3c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-07-25T04:22:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T12:25:41.000Z", "avg_line_length": 32.4449760766, "max_line_length": 123, "alphanum_fraction": 0.602860935, "num_tokens": 2098, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.1225232125181592, "lm_q1q2_score": 0.056485256826120184}} {"text": "### A Pluto.jl notebook ###\n# v0.18.0\n\nusing Markdown\nusing InteractiveUtils\n\n# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).\nmacro bind(def, element)\n quote\n local iv = try Base.loaded_modules[Base.PkgId(Base.UUID(\"6e696c72-6542-2067-7265-42206c756150\"), \"AbstractPlutoDingetjes\")].Bonds.initial_value catch; b -> missing; end\n local el = $(esc(element))\n global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el)\n el\n end\nend\n\n# ╔═╡ cab5e5da-8609-11ec-2b2c-2d98fe66bb99\nbegin\n import Pkg\n\tENV[\"JULIA_MARGO_LOAD_PYPLOT\"] = \"no thank you\"\n Pkg.activate(mktempdir())\n Pkg.add([\n Pkg.PackageSpec(name=\"Plots\", version=\"1\"),\n Pkg.PackageSpec(name=\"ClimateMARGO\", version=v\"0.3.2\"),\n Pkg.PackageSpec(name=\"PlutoUI\", version=\"0.7\"),\n Pkg.PackageSpec(name=\"HypertextLiteral\", version=\"0.9\"),\n ])\n\t\n\tusing Plots\n\tusing Plots.Colors\n\tusing ClimateMARGO\n\tusing ClimateMARGO.Models\n\tusing ClimateMARGO.Optimization\n\tusing ClimateMARGO.Diagnostics\n\tusing PlutoUI\n using HypertextLiteral\n\t\n\tPlots.default(linewidth=5)\nend;\n\n# ╔═╡ cc8614a3-dd69-42d4-9954-44885bac93eb\nmd\"## Exploring uncertainty in climate forcing, feedbacks, and ocean heat uptake.\n\n*by Henri F. Drake*\n\"\n\n# ╔═╡ 84ff8ba3-fd8a-4bc9-ab4e-7f763f98d34d\nmd\"##### Anthropogenic forcing\"\n\n# ╔═╡ 8037ac4e-5c70-4aa7-9982-7442baaa83a0\nmd\"##### The climate response\"\n\n# ╔═╡ 4575f6fd-d1ec-4fd1-bd56-268fab59a533\n\n\n# ╔═╡ 7ea69497-8b83-45f9-93d3-bbce4c3c10b2\nreveal_box = @bind reveal CheckBox(default=false);\n\n# ╔═╡ 71975b7f-e8b7-4097-b573-8e383bb83868\nif reveal\nmd\"The analytical scalings are:\n\n$\\text{TCR}\\propto \\frac{a}{\\lambda + \\kappa}, \\quad\\quad\\quad \\text{ECS} \\propto \\frac{a}{\\lambda}, \\quad\\quad\\quad \\tau = \\frac{C_{D}}{\\lambda}\\,\\frac{\\lambda + \\kappa}{\\kappa}.$\"\nelse\nmd\"Reveal solution: $(reveal_box)\"\nend\n\n# ╔═╡ 8b17a78f-f3d8-4777-becd-01de58974de3\n\n\n# ╔═╡ 56e32b2b-8830-4f2c-97ea-7bc5820dca1b\nρ_slider = @bind ρ Slider(0.:0.5:3, default=3, show_value=true);\n\n# ╔═╡ 7e63eaf5-6841-4f2d-9388-427d9905fd2e\ndo_optimize_box = @bind do_optimize CheckBox(default=false);\n\n# ╔═╡ a442349e-f6ba-4841-93a6-d7ea7235371a\nif reveal\nmd\"#### Exercise 2: policy solutions\nExplore the sensivity of ''optimal'' policy solutions. Check the box: $(do_optimize_box)\n\"\nend\n\n# ╔═╡ 053db221-7f7f-4358-915f-bcfb9f6b6783\nif do_optimize\n\tmd\"*Note the emissions reductions (and carbon dioxide removal) and corresponding warming reductions above!*\"\nend\n\n# ╔═╡ 2f4a79c4-5455-4b8d-9a85-1aac1cdad3f7\nif do_optimize\n\tmd\"#### Exercise 3: Intergenerational (in)equity\n\nYou may have guessed the ''optimal'' level of warming depends strongly on economic preferences, e.g. how much the model values the welfare of future generations.\n \nHow does the ''optimal'' policy response change as we decrease the ''discount rate'' towards intergenerational equity?\n\n $(ρ_slider) % per year\n\t\"\nend\n\n# ╔═╡ 42a58da0-bffc-4fd1-ab7b-0a90b0664e4e\nbegin\n\tif do_optimize\n\t\tlast_year = 2800\n\telse\n\t\tlast_year = 4000\n\tend\n\tend_year_slider = @bind end_year Slider(2100:50:last_year, default=2200, show_value=true);\nend;\n\n# ╔═╡ 97e66e74-7f38-4811-8d11-f69df3e5ce49\nmd\"\n#### Exercise 1: transient and equilibrium global warming\nLengthen the simulation's time horizon and graphically explore the scaling of the following emergent properties with the four key parameters above:\n\nA) the Transient Climate Response (TCR), i.e. the warming in 2150 when forcing stabilizes\n\nB) the Equilibrium Climate Sensivity (ECS), i.e. the warming when temperatures have equilibrated with\n\nC) the timescale $\\tau_{D}$ of the equilibration\n\n$(end_year_slider)\n\"\n\n# ╔═╡ 56b88523-aa8e-42d7-8637-17b0a0c6fd22\n\n\n# ╔═╡ b72a5d5f-1806-4ae0-95e1-d3b1e4b845ce\n\n\n# ╔═╡ 4fee292d-9cf1-40ec-b96d-0eacb0135cae\nmd\"# Appendix\"\n\n# ╔═╡ 1a3b7318-d0a8-424a-96db-1deb03da716b\ncmip5_std = Dict(\"a\"=>0.9*log(2.), \"λ\"=>0.31, \"κ\"=>0.18, \"Cd\"=>62.)\n\n# ╔═╡ 8742ea1c-54af-4a7d-8f41-1566a71c4d94\nblob(el, color = \"blue\") = @htl(\"\"\"
$(el)
\"\"\");\n\n# ╔═╡ 24d098eb-a548-4c80-935b-0e9bec229105\nfunction default_parameters(years)::ClimateModelParameters\n\tresult = deepcopy(ClimateMARGO.IO.included_configurations[\"default\"])\n\tresult.domain = years isa Domain ? years : Domain(step(years), first(years), last(years))\n\tresult.economics.baseline_emissions = ramp_emissions(result.domain)\n result.economics.extra_CO₂ = zeros(size(result.economics.baseline_emissions))\n\treturn result\nend;\n\n# ╔═╡ 226ae32f-36d4-4563-8af4-1aa9d16702c6\nbegin\n\t# Create default parameter values\n\tyears = 2020:6.0:end_year;\n\tdefault_params = default_parameters(years);\n\tdefault_params.physics.a = 6.9*log(2.);\n\tphys = default_params.physics\nend\n\n# ╔═╡ c834b860-866d-4f21-b51a-4fa301d17348\na_slider = @bind a Slider(\n\tround(phys.a-2*cmip5_std[\"a\"], digits=2)\n\t:round(4*cmip5_std[\"a\"]/100., digits=2)\n\t:round(phys.a+2*cmip5_std[\"a\"], digits=2),\n\tdefault=phys.a, show_value=true\n);\n\n# ╔═╡ 27c8bca8-55f9-4289-a839-cebbbf696169\nλ_slider = @bind λ Slider(\n\tround(phys.B-2*cmip5_std[\"λ\"], digits=2)\n\t:round(4*cmip5_std[\"λ\"]/100., digits=2)\n\t:round(phys.B+2*cmip5_std[\"λ\"], digits=2),\n\tdefault=phys.B, show_value=true\n);\n\n# ╔═╡ 672287f1-f1bd-4899-9d7e-29a6a5646f10\nκ_slider = @bind κ Slider(\n\tround(phys.κ-2*cmip5_std[\"κ\"], digits=2)\n\t:round(4*cmip5_std[\"κ\"]/100., digits=2)\n\t:round(phys.κ+2*cmip5_std[\"κ\"], digits=2),\n\tdefault=phys.κ, show_value=true\n);\n\n# ╔═╡ 58441503-2998-472e-b466-5d4c832f9042\nCd_slider = @bind Cd Slider(\n\tmax(Int(round(phys.Cd-2*cmip5_std[\"Cd\"], digits=0)), 20)\n\t:Int(round(4*cmip5_std[\"Cd\"]/100., digits=0))\n\t:Int(round(phys.Cd+2*cmip5_std[\"Cd\"], digits=0)),\n\tdefault=phys.Cd, show_value=true\n);\n\n# ╔═╡ 9c7d7e6c-d2d9-4754-b2e3-72c3b9e0ec06\nlet\n\tblob(\n\t\t@htl(\"\"\"\n\t

Energy Balance Model Parameters

\n\t
Defaults are CMIP5 multi-model mean; ranges are ±2σ.
\n\t\n\t\n\t\n\t\n\t\n\t\n\t\t\n\n\t\t\n\t\t\n\t\t\t\n\n\t\t\n\t\t\n\t\t\n\t\t\n\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\n\t
Value
CO2 forcing parameter, a [W m⁻²]$(a_slider)
Feedback parameter, λ [W m⁻² K⁻¹]$(λ_slider)
Heat uptake rate, κ [W m⁻² K⁻¹]$(κ_slider)
Deep ocean heat capacity, C₀ [W yr m⁻² K⁻¹]$(Cd_slider)
\n\t\t\"\"\"),\n\t\t\"#c0ecff33\"\n\t)\nend\n\n# ╔═╡ 8c1ddae9-a9dd-4556-9027-4f701a064604\nbegin\n\t# Overwrite defaults with slider values\n\tparams = deepcopy(default_params)\n\tparams.economics.ρ = ρ/100. + params.economics.γ;\n\tparams.economics.β = 0.003;\n\tparams.physics.T0 = 1.0;\n\tparams.physics.a = a;\n\tparams.physics.B = λ;\n\tparams.physics.κ = κ;\n\tparams.physics.Cd = Cd;\n\tm = ClimateModel(params);\n\tmax_deployment = Dict(\"mitigate\"=>1., \"remove\"=>0.5, \"geoeng\"=>0., \"adapt\"=>0.)\n\tif do_optimize\n\t\topt = optimize_controls!(\n\t\t\tm, obj_option=\"net_benefit\", max_deployment=max_deployment\n\t\t);\n\tend\n\tm;\nend\n\n# ╔═╡ 1285f653-a4a8-4c5c-b395-2f3ffd24811d\nbegin\n\tp_emit = plot(t(m), effective_emissions(m), color=:grey, linewidth=3, alpha=0.5, label=\"baseline fossil growth\")\n\tif do_optimize\n\t\tplot!(p_emit, t(m), effective_emissions(m, M=true, R=true), linewidth=5, color=:deepskyblue2, label=\"''optimal'' policy\")\n\tend\n\tplot!(p_emit, t(m), 0. *t(m), linestyle=:dash, color=:black, alpha=0.3, linewidth = 2.5, label=\"\")\n\tplot!(p_emit, ylim=(-5., 15.), xlim=(t(m)[1], t(m)[end]))\n\tplot!(p_emit, ylabel=\"emissions [ppm/year]\", xlabel=\"year\")\n\tplot!(p_emit, size=(700, 225), margins=2.75Plots.Measures.mm)\nend\n\n# ╔═╡ 13b0c090-ff52-4eca-98a5-1306f859c58f\nbegin\n\tp = plot(t(m), T(m), color=:grey, linewidth=3, alpha=0.5, label=\"baseline fossil growth\")\n\tif do_optimize\n\t\tplot!(t(m), T(m, M=true, R=true), linewidth=5, color=:deepskyblue2, label=\"''optimal'' policy\")\n\tend\n\tif minimum(T(m, M=true, R=true)) < 0.\n\t\tplot!(ylim=(-2, max(8, maximum(T(m, M=true, R=true)))), xlim=(t(m)[1], t(m)[end]))\n\telse\n\t\tplot!(ylim=(0, max(8, maximum(T(m, M=true, R=true)))), xlim=(t(m)[1], t(m)[end]))\n\tend\n\tplot!(ylabel=\"warming (relative to P-I)\", xlabel=\"year\")\n\tplot!(yticks=[-1., 0., 1., 1.5, 2., 2.5, 3., 4., 5., 6., 7., 8., 9, 10.])\n\tplot!(size=(700, 250), margins=2.75Plots.Measures.mm)\n\tplot!(legend=:topleft)\nend\n\n# ╔═╡ 10befe5b-9e7c-40a6-9079-1ab5a380888b\nif do_optimize\n\tp_discount = plot(\n\t\tt(m),\n\t\t(1 .- (m.economics.ρ - m.economics.γ)).^((t(m) .- t(m)[1])) * 100., label=\"\"\n\t)\n\tplot!(xlabel=\"year\", ylabel=\"discount factor [%]\", ylim = (0, 100))\nend\n\n# ╔═╡ Cell order:\n# ╟─cc8614a3-dd69-42d4-9954-44885bac93eb\n# ╟─84ff8ba3-fd8a-4bc9-ab4e-7f763f98d34d\n# ╟─1285f653-a4a8-4c5c-b395-2f3ffd24811d\n# ╟─8037ac4e-5c70-4aa7-9982-7442baaa83a0\n# ╟─13b0c090-ff52-4eca-98a5-1306f859c58f\n# ╟─9c7d7e6c-d2d9-4754-b2e3-72c3b9e0ec06\n# ╟─97e66e74-7f38-4811-8d11-f69df3e5ce49\n# ╟─4575f6fd-d1ec-4fd1-bd56-268fab59a533\n# ╟─71975b7f-e8b7-4097-b573-8e383bb83868\n# ╟─7ea69497-8b83-45f9-93d3-bbce4c3c10b2\n# ╟─a442349e-f6ba-4841-93a6-d7ea7235371a\n# ╟─053db221-7f7f-4358-915f-bcfb9f6b6783\n# ╟─8b17a78f-f3d8-4777-becd-01de58974de3\n# ╟─2f4a79c4-5455-4b8d-9a85-1aac1cdad3f7\n# ╟─10befe5b-9e7c-40a6-9079-1ab5a380888b\n# ╟─42a58da0-bffc-4fd1-ab7b-0a90b0664e4e\n# ╟─56e32b2b-8830-4f2c-97ea-7bc5820dca1b\n# ╟─7e63eaf5-6841-4f2d-9388-427d9905fd2e\n# ╟─56b88523-aa8e-42d7-8637-17b0a0c6fd22\n# ╟─b72a5d5f-1806-4ae0-95e1-d3b1e4b845ce\n# ╟─4fee292d-9cf1-40ec-b96d-0eacb0135cae\n# ╠═cab5e5da-8609-11ec-2b2c-2d98fe66bb99\n# ╠═226ae32f-36d4-4563-8af4-1aa9d16702c6\n# ╠═8c1ddae9-a9dd-4556-9027-4f701a064604\n# ╠═1a3b7318-d0a8-424a-96db-1deb03da716b\n# ╟─8742ea1c-54af-4a7d-8f41-1566a71c4d94\n# ╟─c834b860-866d-4f21-b51a-4fa301d17348\n# ╟─27c8bca8-55f9-4289-a839-cebbbf696169\n# ╟─672287f1-f1bd-4899-9d7e-29a6a5646f10\n# ╟─58441503-2998-472e-b466-5d4c832f9042\n# ╟─24d098eb-a548-4c80-935b-0e9bec229105\n", "meta": {"hexsha": "6a9cd632985e651978f614e002af0ce93fad2413", "size": 10045, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "ebm.jl", "max_stars_repo_name": "ClimateMARGO/interactive", "max_stars_repo_head_hexsha": "9351c5d33e4a17f0272bd397f7bb429ab50c1ecd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-09-24T18:15:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-07T21:21:09.000Z", "max_issues_repo_path": "ebm.jl", "max_issues_repo_name": "ClimateMARGO/interactive", "max_issues_repo_head_hexsha": "9351c5d33e4a17f0272bd397f7bb429ab50c1ecd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2022-02-03T13:31:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-11T20:47:51.000Z", "max_forks_repo_path": "ebm.jl", "max_forks_repo_name": "ClimateMARGO/interactive", "max_forks_repo_head_hexsha": "9351c5d33e4a17f0272bd397f7bb429ab50c1ecd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0748502994, "max_line_length": 195, "alphanum_fraction": 0.7014435042, "num_tokens": 4246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.1159607258918425, "lm_q1q2_score": 0.05616906618031096}} {"text": "## RESAMPLING STRATEGIES\n\nabstract type ResamplingStrategy <: MLJType end\nshow_as_constructed(::Type{<:ResamplingStrategy}) = true\n\n# resampling strategies are `==` if they have the same type and their\n# field values are `==`:\nfunction ==(s1::S, s2::S) where S <: ResamplingStrategy\n return all(getfield(s1, fld) == getfield(s2, fld) for fld in fieldnames(S))\nend\n\n# fallbacks:\ntrain_test_pairs(s::ResamplingStrategy, rows, X, y, w) =\n train_test_pairs(s, rows, X, y)\ntrain_test_pairs(s::ResamplingStrategy, rows, X, y) =\n train_test_pairs(s, rows, y)\ntrain_test_pairs(s::ResamplingStrategy, rows, y) =\n train_test_pairs(s, rows)\n\n\n# Helper to interpret rng, shuffle in case either is `nothing` or if\n# `rng` is an integer:\nfunction shuffle_and_rng(shuffle, rng)\n if rng isa Integer\n rng = MersenneTwister(rng)\n end\n\n if shuffle === nothing\n shuffle = ifelse(rng===nothing, false, true)\n end\n\n if rng === nothing\n rng = Random.GLOBAL_RNG\n end\n\n return shuffle, rng\nend\n\n\"\"\"\n holdout = Holdout(; fraction_train=0.7,\n shuffle=nothing,\n rng=nothing)\n\nHoldout resampling strategy, for use in `evaluate!`, `evaluate` and in tuning.\n\n train_test_pairs(holdout, rows)\n\nReturns the pair `[(train, test)]`, where `train` and `test` are\nvectors such that `rows=vcat(train, test)` and\n`length(train)/length(rows)` is approximatey equal to fraction_train`.\n\nPre-shuffling of `rows` is controlled by `rng` and `shuffle`. If `rng`\nis an integer, then the `Holdout` keyword constructor resets it to\n`MersenneTwister(rng)`. Otherwise some `AbstractRNG` object is\nexpected.\n\nIf `rng` is left unspecified, `rng` is reset to `Random.GLOBAL_RNG`,\nin which case rows are only pre-shuffled if `shuffle=true` is\nspecified.\n\n\"\"\"\nstruct Holdout <: ResamplingStrategy\n fraction_train::Float64\n shuffle::Bool\n rng::Union{Int,AbstractRNG}\n\n function Holdout(fraction_train, shuffle, rng)\n 0 < fraction_train < 1 ||\n error(\"`fraction_train` must be between 0 and 1.\")\n return new(fraction_train, shuffle, rng)\n end\nend\n\n# Keyword Constructor\nHoldout(; fraction_train::Float64=0.7, shuffle=nothing, rng=nothing) =\n Holdout(fraction_train, shuffle_and_rng(shuffle, rng)...)\n\nfunction train_test_pairs(holdout::Holdout, rows)\n\n train, test = partition(rows, holdout.fraction_train,\n shuffle=holdout.shuffle, rng=holdout.rng)\n return [(train, test),]\n\nend\n\n\n\"\"\"\n cv = CV(; nfolds=6, shuffle=nothing, rng=nothing)\n\nCross-validation resampling strategy, for use in `evaluate!`,\n`evaluate` and tuning.\n\n train_test_pairs(cv, rows)\n\nReturns an `nfolds`-length iterator of `(train, test)` pairs of\nvectors (row indices), where each `train` and `test` is a sub-vector\nof `rows`. The `test` vectors are mutually exclusive and exhaust\n`rows`. Each `train` vector is the complement of the corresponding\n`test` vector. With no row pre-shuffling, the order of `rows` is\npreserved, in the sense that `rows` coincides precisely with the\nconcatenation of the `test` vectors, in the order they are\ngenerated. All but the last `test` vector have equal length.\n\nPre-shuffling of `rows` is controlled by `rng` and `shuffle`. If `rng`\nis an integer, then the `CV` keyword constructor resets it to\n`MersenneTwister(rng)`. Otherwise some `AbstractRNG` object is\nexpected.\n\nIf `rng` is left unspecified, `rng` is reset to `Random.GLOBAL_RNG`,\nin which case rows are only pre-shuffled if `shuffle=true` is\nexplicitly specified.\n\n\"\"\"\nstruct CV <: ResamplingStrategy\n nfolds::Int\n shuffle::Bool\n rng::Union{Int,AbstractRNG}\n function CV(nfolds, shuffle, rng)\n nfolds > 1 || error(\"Must have nfolds > 1. \")\n return new(nfolds, shuffle, rng)\n end\nend\n\n# Constructor with keywords\nCV(; nfolds::Int=6, shuffle=nothing, rng=nothing) =\n CV(nfolds, shuffle_and_rng(shuffle, rng)...)\n\nfunction train_test_pairs(cv::CV, rows)\n\n n_observations = length(rows)\n nfolds = cv.nfolds\n\n if cv.shuffle\n rows=shuffle!(cv.rng, collect(rows))\n end\n\n # number of observations per fold\n k = floor(Int, n_observations/nfolds)\n k > 0 || error(\"Inusufficient data for $nfolds-fold cross-validation.\\n\"*\n \"Try reducing nfolds. \")\n\n # define the (trainrows, testrows) pairs:\n firsts = 1:k:((nfolds - 1)*k + 1) # itr of first `test` rows index\n seconds = k:k:(nfolds*k) # itr of last `test` rows index\n\n ret = map(1:nfolds) do k\n f = firsts[k]\n s = seconds[k]\n k < nfolds || (s = n_observations)\n return (vcat(rows[1:(f - 1)], rows[(s + 1):end]), # trainrows\n rows[f:s]) # testrows\n end\n\n return ret\nend\n\n\"\"\"\n stratified_cv = StratifiedCV(; nfolds=6,\n shuffle=false,\n rng=Random.GLOBAL_RNG)\n\nStratified cross-validation resampling strategy, for use in\n`evaluate!`, `evaluate` and in tuning. Applies only to classification\nproblems (`OrderedFactor` or `Multiclass` targets).\n\n train_test_pairs(stratified_cv, rows, y)\n\nReturns an `nfolds`-length iterator of `(train, test)` pairs of\nvectors (row indices) where each `train` and `test` is a sub-vector of\n`rows`. The `test` vectors are mutually exclusive and exhaust\n`rows`. Each `train` vector is the complement of the corresponding\n`test` vector.\n\nUnlike regular cross-validation, the distribution of the levels of the\ntarget `y` corresponding to each `train` and `test` is constrained, as\nfar as possible, to replicate that of `y[rows]` as a whole.\n\nSpecifically, the data is split into a number of groups on which `y`\nis constant, and each individual group is resampled according to the\nordinary cross-validation strategy `CV(nfolds=nfolds)`. To obtain the\nfinal `(train, test)` pairs of row indices, the per-group pairs are\ncollated in such a way that each collated `train` and `test` respects\nthe original order of `rows` (after shuffling, if `shuffle=true`).\n\nPre-shuffling of `rows` is controlled by `rng` and `shuffle`. If `rng`\nis an integer, then the `StratifedCV` keyword constructor resets it to\n`MersenneTwister(rng)`. Otherwise some `AbstractRNG` object is\nexpected.\n\nIf `rng` is left unspecified, `rng` is reset to `Random.GLOBAL_RNG`,\nin which case rows are only pre-shuffled if `shuffle=true` is\nexplicitly specified.\n\n\"\"\"\nstruct StratifiedCV <: ResamplingStrategy\n nfolds::Int\n shuffle::Bool\n rng::Union{Int,AbstractRNG}\n function StratifiedCV(nfolds, shuffle, rng)\n nfolds > 1 || error(\"Must have nfolds > 1. \")\n return new(nfolds, shuffle, rng)\n end\nend\n\n# Constructor with keywords\nStratifiedCV(; nfolds::Int=6, shuffle=nothing, rng=nothing) =\n StratifiedCV(nfolds, shuffle_and_rng(shuffle, rng)...)\n\nfunction train_test_pairs(stratified_cv::StratifiedCV, rows, X, y)\n\n n_observations = length(rows)\n nfolds = stratified_cv.nfolds\n\n if stratified_cv.shuffle\n rows=shuffle!(stratified_cv.rng, collect(rows))\n end\n\n st = scitype(y)\n st <: AbstractArray{<:Finite} ||\n error(\"Supplied target has scitpye $st but stratified \"*\n \"cross-validation applies only to classification problems. \")\n\n\n freq_given_level = countmap(y[rows])\n minimum(values(freq_given_level)) >= nfolds ||\n error(\"The number of observations for which the target takes on a \"*\n \"given class must, for each class, exceed `nfolds`. Try \"*\n \"reducing `nfolds`. \")\n\n levels_seen = keys(freq_given_level) |> collect\n\n cv = CV(nfolds=nfolds)\n\n # the target is constant on each stratum, a subset of `rows`:\n class_rows = [rows[y[rows] .== c] for c in levels_seen]\n\n # get the cv train/test pairs for each level:\n train_test_pairs_per_level = (train_test_pairs(cv, class_rows[m])\n for m in eachindex(levels_seen))\n\n # just the train rows in each level:\n trains_per_level = map(x -> first.(x),\n train_test_pairs_per_level)\n\n # just the test rows in each level:\n tests_per_level = map(x -> last.(x),\n train_test_pairs_per_level)\n\n # for each fold, concatenate the train rows over levels:\n trains_per_fold = map(x->vcat(x...), zip(trains_per_level...))\n\n # for each fold, concatenate the test rows over levels:\n tests_per_fold = map(x->vcat(x...), zip(tests_per_level...))\n\n # restore ordering specified by rows:\n trains_per_fold = map(trains_per_fold) do train\n filter(in(train), rows)\n end\n tests_per_fold = map(tests_per_fold) do test\n filter(in(test), rows)\n end\n\n # re-assemble:\n return zip(trains_per_fold, tests_per_fold) |> collect\n\nend\n\n\n## EVALUATION TYPE\n\nconst PerformanceEvaluation = NamedTuple{(:measure, :measurement,\n :per_fold, :per_observation)}\n# pretty printing:\nround3(x) = round(x, sigdigits=3)\n_short(v::Vector{<:Real}) = MLJBase.short_string(v)\n_short(v::Vector) = string(\"[\", join(_short.(v), \", \"), \"]\")\n_short(::Missing) = missing\n\nfunction Base.show(io::IO, ::MIME\"text/plain\", e::PerformanceEvaluation)\n data = hcat(e.measure, round3.(e.measurement),\n [round3.(v) for v in e.per_fold])\n header = [\"_.measure\", \"_.measurement\", \"_.per_fold\"]\n PrettyTables.pretty_table(io, data, header;\n header_crayon=Crayon(bold=false),\n alignment=:l)\n println(io, \"_.per_observation = $(_short(e.per_observation))\")\nend\n\nfunction Base.show(io::IO, e::PerformanceEvaluation)\n summary = Tuple(round3.(e.measurement))\n print(io, \"PerformanceEvaluation$summary\")\nend\n\n\n## EVALUATION METHODS\n\nfunction _check_measure(model, measure, y, operation, override)\n\n override && (return nothing)\n\n T = scitype(y)\n\n T == Unknown && (return nothing)\n target_scitype(measure) == Unknown && (return nothing)\n prediction_type(measure) == :unknown && (return nothing)\n\n avoid = \"\\nTo override measure checks, set check_measure=false. \"\n\n T <: target_scitype(measure) ||\n throw(ArgumentError(\n \"\\nscitype of target = $T but target_scitype($measure) = \"*\n \"$(target_scitype(measure)).\"*avoid))\n\n if model isa Probabilistic\n if operation == predict\n if prediction_type(measure) != :probabilistic\n suggestion = \"\"\n if target_scitype(measure) <: Finite\n suggestion = \"\\nPerhaps you want to set operation=\"*\n \"predict_mode. \"\n elseif target_scitype(measure) <: Continuous\n suggestion = \"\\nPerhaps you want to set operation=\"*\n \"predict_mean or operation=predict_median. \"\n else\n suggestion = \"\"\n end\n throw(ArgumentError(\n \"\\n$model <: Probabilistic but prediction_type($measure) = \"*\n \":$(prediction_type(measure)). \"*suggestion*avoid))\n end\n end\n end\n\n model isa Deterministic && prediction_type(measure) != :deterministic &&\n throw(ArgumentError(\"$model <: Deterministic but \"*\n \"prediction_type($measure) =\"*\n \":$(prediction_type(measure)).\"*avoid))\n\n return nothing\n\nend\n\nfunction _process_weights_measures(weights, measures, mach,\n operation, verbosity, check_measure)\n\n if measures === nothing\n candidate = default_measure(mach.model)\n candidate === nothing && error(\"You need to specify measure=... \")\n _measures = [candidate, ]\n elseif !(measures isa AbstractVector)\n _measures = [measures, ]\n else\n _measures = measures\n end\n\n y = mach.args[2]\n\n [ _check_measure(mach.model, m, y, operation, !check_measure)\n for m in _measures ]\n\n if weights != nothing\n weights isa AbstractVector{<:Real} ||\n throw(ArgumentError(\"`weights` must be a `Real` vector.\"))\n length(weights) == nrows(y) ||\n throw(DimensionMismatch(\"`weights` and target \"*\n \"have different lengths. \"))\n _weights = weights\n elseif length(mach.args) == 3\n verbosity < 1 ||\n @info \"Passing machine sample weights to any supported measures. \"\n _weights = mach.args[3]\n else\n _weights = weights\n end\n\n return _weights, _measures\n\nend\n\n\"\"\"\n evaluate!(mach,\n resampling=CV(),\n measure=nothing,\n weights=nothing,\n operation=predict,\n n = 1,\n acceleration=default_resource(),\n force=false,\n verbosity=1)\n\nEstimate the performance of a machine `mach` wrapping a supervised\nmodel in data, using the specified `resampling` strategy (defaulting\nto 6-fold cross-validation) and `measure`, which can be a single\nmeasure or vector.\n\nDo `subtypes(MLJ.ResamplingStrategy)` to obtain a list of available\nresampling strategies. If `resampling` is not an object of type\n`MLJ.ResamplingStrategy`, then a vector of pairs (of the form\n`(train_rows, test_rows)` is expected. For example, setting\n\n resampling = [(1:100), (101:200)),\n (101:200), (1:100)]\n\ngives two-fold cross-validation using the first 200 rows of data.\n\nThe resampling strategy is applied repeatedly if `repeats > 1`. For\n`resampling = CV(nfolds=5)`, for example, this generates a total of\n`5n` test folds for evaluation and subsequent aggregation.\n\nIf `resampling isa MLJ.ResamplingStrategy` then one may optionally\nrestrict the data used in evaluation by specifying `rows`.\n\nAn optional `weights` vector may be passed for measures that support\nsample weights (`MLJ.supports_weights(measure) == true`), which is\nignored by those that don't.\n\n*Important:* If `mach` already wraps sample weights `w` (as in `mach =\nmachine(model, X, y, w)`) then these weights, which are used for\n*training*, are automatically passed to the measures for\nevaluation. However, for evaluation purposes, any `weights` specified\nas a keyword argument will take precedence over `w`.\n\nUser-defined measures are supported; see the manual for details.\n\nIf no measure is specified, then `default_measure(mach.model)` is\nused, unless this default is `nothing` and an error is thrown.\n\nThe `acceleration` keyword argument is used to specify the compute resource (a\nsubtype of `ComputationalResources.AbstractResource`) that will be used to\naccelerate/parallelize the resampling operation.\n\nAlthough evaluate! is mutating, `mach.model` and `mach.args` are\nuntouched.\n\n### Return value\n\nA property-accessible object of type `PerformanceEvaluation` with\nthese properties:\n\n- `measure`: the vector of specified measures\n\n- `measurements`: the corresponding measurements, aggregated across the\n test folds using the aggregation method defined for each measure (do\n `aggregation(measure)` to inspect)\n\n- `per_fold`: a vector of vectors of individual test fold evaluations\n (one vector per measure)\n\n- `per_observation`: a vector of vectors of individual observation\n evaluations of those measures for which\n `reports_each_observation(measure)` is true, which is otherwise\n reported `missing`.\n\nSee also [`evaluate`](@ref)\n\n\"\"\"\nfunction evaluate!(mach::Machine{<:Supervised};\n resampling=CV(),\n measures=nothing, measure=measures, weights=nothing,\n operation=predict, acceleration=default_resource(),\n rows=nothing, repeats=1, force=false,\n check_measure=true, verbosity=1)\n\n # this method just checks validity of options, preprocess the\n # weights and measures, and dispatches a strategy-specific\n # `evaluate!`\n\n repeats > 0 || error(\"Need n > 0. \")\n\n if resampling isa TrainTestPairs\n if rows !== nothing\n error(\"You cannot specify `rows` unless `resampling \"*\n \"isa MLJ.ResamplingStrategy` is true. \")\n end\n if repeats != 1 && verbosity > 0\n @warn \"repeats > 1 not supported unless \"*\n \"`resampling<:ResamplingStrategy. \"\n end\n end\n\n _weights, _measures =\n _process_weights_measures(weights, measure, mach,\n operation, verbosity, check_measure)\n\n if verbosity >= 0 && weights !== nothing\n unsupported = filter(_measures) do m\n !supports_weights(m)\n end\n if !isempty(unsupported)\n unsupported_as_string = string(unsupported[1])\n unsupported_as_string *=\n reduce(*, [string(\", \", m) for m in unsupported[2:end]])\n @warn \"Sample weights ignored in evaluations of the following\"*\n \" measures, as unsupported: \\n$unsupported_as_string \"\n end\n end\n\n evaluate!(mach, resampling, _weights, rows, verbosity, repeats,\n _measures, operation, acceleration, force)\n\nend\n\n\"\"\"\n evaluate(model, X, y; measure=nothing, options...)\n evaluate(model, X, y, w; measure=nothing, options...)\n\nEvaluate the performance of a supervised model `model` on input data\n`X` and target `y`, optionally specifying sample weights `w` for\ntraining, where supported. The same weights are passed to measures\nthat support sample weights, unless this behaviour is overridden by\nexplicitly specifying the option `weights=...`.\n\nSee the machine version `evaluate!` for the complete list of options.\n\n\"\"\"\nevaluate(model::Supervised, args...; kwargs...) =\n evaluate!(machine(model, args...); kwargs...)\n\nconst AbstractRow = Union{AbstractVector{<:Integer}, Colon}\nconst TrainTestPair = Tuple{AbstractRow,AbstractRow}\nconst TrainTestPairs = AbstractVector{<:TrainTestPair}\n\nfunction _evaluate!(func::Function, res::CPU1, nfolds, verbosity)\n p = Progress(nfolds + 1, dt=0, desc=\"Evaluating over $nfolds folds: \",\n barglyphs=BarGlyphs(\"[=> ]\"), barlen=25, color=:yellow)\n verbosity > 0 && next!(p)\n return reduce(vcat, (func(k, p, verbosity) for k in 1:nfolds))\nend\nfunction _evaluate!(func::Function, res::CPUProcesses, nfolds, verbosity)\n # TODO: use pmap here ?:\n return @distributed vcat for k in 1:nfolds\n func(k)\n end\nend\n@static if VERSION >= v\"1.3.0-DEV.573\"\n function _evaluate!(func::Function, res::CPUThreads, nfolds, verbosity)\n task_vec = [Threads.@spawn func(k) for k in 1:nfolds]\n return reduce(vcat, fetch.(task_vec))\n end\nend\n\n# Evaluation when resampling is a TrainTestPairs (core evaluator):\nfunction evaluate!(mach::Machine, resampling, weights,\n rows, verbosity, repeats,\n measures, operation, acceleration, force)\n\n # Note: `rows` and `n` are ignored here\n\n resampling isa TrainTestPairs ||\n error(\"`resampling` must be an \"*\n \"`MLJ.ResamplingStrategy` or tuple of pairs \"*\n \"of the form `(train_rows, test_rows)`\")\n\n X = mach.args[1]\n y = mach.args[2]\n\n nfolds = length(resampling)\n\n nmeasures = length(measures)\n\n function get_measurements(k)\n train, test = resampling[k]\n fit!(mach; rows=train, verbosity=verbosity-1, force=force)\n Xtest = selectrows(X, test)\n ytest = selectrows(y, test)\n if weights == nothing\n wtest = nothing\n else\n wtest = weights[test]\n end\n yhat = operation(mach, Xtest)\n return [value(m, yhat, Xtest, ytest, wtest)\n for m in measures]\n end\n function get_measurements(k, p, verbosity) # p = progress meter\n ret = get_measurements(k)\n verbosity > 0 && next!(p)\n return ret\n end\n\n measurements_flat = if acceleration isa CPUProcesses\n ## TODO: progress meter for distributed case\n if verbosity > 0\n @info \"Distributing cross-validation computation \" *\n \"among $(nworkers()) workers.\"\n end\n end\n measurements_flat =\n _evaluate!(get_measurements, acceleration, nfolds, verbosity)\n\n # in the following rows=folds, columns=measures:\n measurements_matrix = permutedims(\n reshape(measurements_flat, (nmeasures, nfolds)))\n\n # measurements for each observation:\n per_observation = map(1:nmeasures) do k\n m = measures[k]\n if reports_each_observation(m)\n [measurements_matrix[:,k]...]\n else\n missing\n end\n end\n\n # measurements for each fold:\n per_fold = map(1:nmeasures) do k\n m = measures[k]\n if reports_each_observation(m)\n broadcast(MLJBase.aggregate, per_observation[k], [m,])\n else\n [measurements_matrix[:,k]...]\n end\n end\n\n # overall aggregates:\n per_measure = map(1:nmeasures) do k\n m = measures[k]\n MLJBase.aggregate(per_fold[k], m)\n end\n\n ret = (measure=measures,\n measurement=per_measure,\n per_fold=per_fold,\n per_observation=per_observation)\n\n return ret\n\nend\n\nfunction actual_rows(rows, N, verbosity)\n unspecified_rows = (rows === nothing)\n _rows = unspecified_rows ? (1:N) : rows\n unspecified_rows || @info \"Creating subsamples from a subset of all rows. \"\n return _rows\nend\n\n# Evaluation when resampling is a ResamplingStrategy:\nfunction evaluate!(mach::Machine, resampling::ResamplingStrategy,\n weights, rows, verbosity, repeats, args...)\n\n y = mach.args[2]\n _rows = actual_rows(rows, length(y), verbosity)\n\n repeated_train_test_pairs =\n vcat([train_test_pairs(resampling, _rows, mach.args...)\n for i in 1:repeats]...)\n\n return evaluate!(mach::Machine,\n repeated_train_test_pairs,\n weights, nothing, verbosity, repeats, args...)\n\nend\n\n\n## RESAMPLER - A MODEL WRAPPER WITH `evaluate` OPERATION\n\n\"\"\"\n resampler = Resampler(model=ConstantRegressor(),\n resampling=CV(),\n measure=nothing,\n weights=nothing,\n operation=predict,\n repeats = 1,\n acceleration=default_resource(),\n check_measure=true)\n\nResampling model wrapper, used internally by the `fit` method of\n`TunedModel` instances. See [`evaluate!](@ref) for options. Not\nintended for general use.\n\nGiven a machine `mach = machine(resampler, args...)` one obtains a\nperformance evaluation of the specified `model`, performed according\nto the prescribed `resampling` strategy and other parameters, using\ndata `args...`, by calling `fit!(mach)` followed by\n`evaluate(mach)`. The advantage over using `evaluate(model, X, y)` is\nthat the latter call always calls `fit` on the `model` but\n`fit!(mach)` only calls `update` after the first call.\n\nThe sample `weights` are passed to the specified performance\nmeasures that support weights for evaluation.\n\n*Important:* If `weights` are left unspecified, then any weight vector\n`w` used in constructing the resampler machine, as in\n`resampler_machine = machine(resampler, X, y, w)` (which is then used\nin *training* the model) will also be used in evaluation.\n\n\"\"\"\nmutable struct Resampler{S,M<:Supervised} <: Supervised\n model::M\n resampling::S # resampling strategy\n measure\n weights::Union{Nothing,AbstractVector{<:Real}}\n operation\n acceleration::AbstractResource\n check_measure::Bool\n repeats::Int\nend\n\nMLJBase.is_wrapper(::Type{<:Resampler}) = true\nMLJBase.supports_weights(::Type{<:Resampler{<:Any,M}}) where M =\n supports_weights(M)\nMLJBase.is_pure_julia(::Type{<:Resampler}) = true\n\nfunction MLJBase.clean!(resampler::Resampler)\n warning = \"\"\n if resampler.measure === nothing\n measure = default_measure(resampler.model)\n if measure === nothing\n error(\"No default measure known for $(resampler.model). \"*\n \"You must specify measure=... \")\n else\n warning *= \"No `measure` specified. \"*\n \"Setting `measure=$measure`. \"\n end\n end\n return warning\nend\n\nfunction Resampler(; model=ConstantRegressor(), resampling=CV(),\n measure=nothing, weights=nothing, operation=predict,\n acceleration=default_resource(), check_measure=true, repeats=1)\n\n resampler = Resampler(model, resampling, measure, weights, operation,\n acceleration, check_measure, repeats)\n message = MLJBase.clean!(resampler)\n isempty(message) || @warn message\n\n return resampler\n\nend\n\nfunction MLJBase.fit(resampler::Resampler, verbosity::Int, args...)\n\n mach = machine(resampler.model, args...)\n\n weights, measures =\n _process_weights_measures(resampler.weights, resampler.measure,\n mach, resampler.operation,\n verbosity, resampler.check_measure)\n\n fitresult = evaluate!(mach, resampler.resampling,\n weights, nothing, verbosity - 1, resampler.repeats,\n measures, resampler.operation,\n resampler.acceleration, false)\n\n cache = (mach, deepcopy(resampler.resampling))\n report = NamedTuple()\n\n return fitresult, cache, report\n\nend\n\n# in special case of holdout, we can reuse the underlying model's\n# machine, provided the training_fraction has not changed:\nfunction MLJBase.update(resampler::Resampler{Holdout},\n verbosity::Int, fitresult, cache, args...)\n\n old_mach, old_resampling = cache\n\n if old_resampling.fraction_train == resampler.resampling.fraction_train\n mach = old_mach\n else\n mach = machine(resampler.model, args...)\n cache = (mach, deepcopy(resampler.resampling))\n end\n\n weights, measures =\n _process_weights_measures(resampler.weights, resampler.measure,\n mach, resampler.operation,\n verbosity, resampler.check_measure)\n mach.model = resampler.model\n fitresult = evaluate!(mach, resampler.resampling,\n weights, nothing, verbosity - 1, resampler.repeats,\n measures, resampler.operation,\n resampler.acceleration, false)\n\n\n report = NamedTuple\n\n return fitresult, cache, report\n\nend\n\nMLJBase.input_scitype(::Type{<:Resampler{S,M}}) where {S,M} =\n MLJBase.input_scitype(M)\nMLJBase.target_scitype(::Type{<:Resampler{S,M}}) where {S,M} =\n MLJBase.target_scitype(M)\nMLJBase.package_name(::Type{<:Resampler}) = \"MLJBase\"\n\nMLJBase.load_path(::Type{<:Resampler}) = \"MLJBase.Resampler\"\n\nevaluate(resampler::Resampler, fitresult) = fitresult\n\nfunction evaluate(machine::AbstractMachine{<:Resampler})\n if isdefined(machine, :fitresult)\n return evaluate(machine.model, machine.fitresult)\n else\n throw(error(\"$machine has not been trained.\"))\n end\nend\n\n", "meta": {"hexsha": "7ee7571cf0ecb257dd4d3910d0f8a3f02e202608", "size": 27063, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/resampling.jl", "max_stars_repo_name": "darenasc/MLJBase.jl", "max_stars_repo_head_hexsha": "88d70061e2823528026998c2019d25b885dc37e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/resampling.jl", "max_issues_repo_name": "darenasc/MLJBase.jl", "max_issues_repo_head_hexsha": "88d70061e2823528026998c2019d25b885dc37e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/resampling.jl", "max_forks_repo_name": "darenasc/MLJBase.jl", "max_forks_repo_head_hexsha": "88d70061e2823528026998c2019d25b885dc37e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7443890274, "max_line_length": 80, "alphanum_fraction": 0.6503344049, "num_tokens": 6509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.11596071825396675, "lm_q1q2_score": 0.05616906248067606}} {"text": "#=\n\n Reading input\n\n=#\nfunction read_input()\n\n pass=[]\n policy=[]\n letter=[]\n open(\"./input\", \"r\") do f\n while ! eof(f)\n s::String = readline(f)\n entry = split(s,\" \")\n push!(pass,entry[3])\n push!(letter,entry[2][1])\n\n policy_split = split(entry[1],\"-\")\n policy_tuple = (parse(Int32,policy_split[1]), \n parse(Int32,policy_split[2]))\n push!(policy,policy_tuple)\n end\n end\n\n return pass, policy, letter\nend\n\ninput = read_input()\npass = input[1]\npolicy = input[2]\nletter = input[3]\n\n\n\n\n#=\n\n--- Day 2: Password Philosophy ---\n\nYour flight departs in a few days from the coastal airport; the easiest way down to \nthe coast from here is via toboggan.\n\nThe shopkeeper at the North Pole Toboggan Rental Shop is having a bad day. \"Something's \nwrong with our computers; we can't log in!\" You ask if you can take a look.\n\nTheir password database seems to be a little corrupted: some of the passwords wouldn't \nhave been allowed by the Official Toboggan Corporate Policy that was in effect when they \nwere chosen.\n\nTo try to debug the problem, they have created a list (your puzzle input) of passwords \n(according to the corrupted database) and the corporate policy when that password was set.\n\nFor example, suppose you have the following list:\n\n1-3 a: abcde\n1-3 b: cdefg\n2-9 c: ccccccccc\n\nEach line gives the password policy and then the password. The password policy indicates \nthe lowest and highest number of times a given letter must appear for the password to be \nvalid. For example, 1-3 a means that the password must contain a at least 1 time and at \nmost 3 times.\n\nIn the above example, 2 passwords are valid. The middle password, cdefg, is not; it contains \nno instances of b, but needs at least 1. The first and third passwords are valid: they contain \none a or nine c, both within the limits of their respective policies.\n\nHow many passwords are valid according to their policies?\n\n=#\n\n\nfunction is_valid(policy, letter, password)\n letter_count = count(==(letter), password)\n if letter_countpolicy[2]\n return false\n else\n return true\n end\nend\n\nfunction count_valid_passwords(policy, letter, pass)\n count_valid = 0\n for i in 1:size(pass,1)\n if is_valid(policy[i], letter[i], pass[i])\n count_valid+=1\n end\n end\n return count_valid\nend\n\nprintln(size(policy,1),\", \",size(letter,1), \", \", size(pass,1))\nprintln(\"Valid passwords found: \", count_valid_passwords(policy, letter, pass))\n\n\n#=\n--- Part Two ---\n\nWhile it appears you validated the passwords correctly, they don't seem to be \nwhat the Official Toboggan Corporate Authentication System is expecting.\n\nThe shopkeeper suddenly realizes that he just accidentally explained the password \npolicy rules from his old job at the sled rental place down the street! The Official \nToboggan Corporate Policy actually works a little differently.\n\nEach policy actually describes two positions in the password, where 1 means the \nfirst character, 2 means the second character, and so on. (Be careful; Toboggan \nCorporate Policies have no concept of \"index zero\"!) Exactly one of these positions \nmust contain the given letter. Other occurrences of the letter are irrelevant for \nthe purposes of policy enforcement.\n\nGiven the same example list from above:\n\n 1-3 a: abcde is valid: position 1 contains a and position 3 does not.\n 1-3 b: cdefg is invalid: neither position 1 nor position 3 contains b.\n 2-9 c: ccccccccc is invalid: both position 2 and position 9 contain c.\n\nHow many passwords are valid according to the new interpretation of the policies?\n=#\n\nfunction is_valid(policy, letter, password)\n in_fst_pos = (password[policy[1]] == letter)\n in_snd_pos = (password[policy[2]] == letter)\n\n if in_fst_pos\n if in_snd_pos\n return false\n else\n return true\n end\n elseif in_snd_pos\n return true\n else\n return false\n end\nend\n\nfunction count_valid_passwords(policy, letter, pass)\n count_valid = 0\n for i in 1:size(pass,1)\n if is_valid(policy[i], letter[i], pass[i])\n count_valid+=1\n end\n end\n return count_valid\nend\n\nprintln(\"Valid passwords found with second policy: \", count_valid_passwords(policy, letter, pass))", "meta": {"hexsha": "79dab5720a6ef06ce8e079d844719f8adcb50880", "size": 4432, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "Day2/password_philosophy.jl", "max_stars_repo_name": "colombelli/AoC2020-julia", "max_stars_repo_head_hexsha": "ae857741dccad0dc4f7da3636b3c7dd6fe00bd3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Day2/password_philosophy.jl", "max_issues_repo_name": "colombelli/AoC2020-julia", "max_issues_repo_head_hexsha": "ae857741dccad0dc4f7da3636b3c7dd6fe00bd3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Day2/password_philosophy.jl", "max_forks_repo_name": "colombelli/AoC2020-julia", "max_forks_repo_head_hexsha": "ae857741dccad0dc4f7da3636b3c7dd6fe00bd3d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5466666667, "max_line_length": 98, "alphanum_fraction": 0.6949458484, "num_tokens": 1065, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958346, "lm_q2_score": 0.11436851561661297, "lm_q1q2_score": 0.05584424712022446}} {"text": "### A Pluto.jl notebook ###\n# v0.18.2\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ c3530026-5a87-4447-88f5-fc744cb48ff2\nbegin\n\tusing PlutoUI \nend\n\n# ╔═╡ 2c895e14-e71a-435d-86d4-c1b101877b3c\nmd\"\"\"\n### The End of the Beginning: Whole-Cell Metabolic Engineering\n\nIn the first lecture, we introduced metabolic engineering. Today, we'll close the loop at put together all we learned. Metabolic engineering is the practice of optimizing genetic and regulatory processes within cells to increase the cell's production of a desired small molecule or protein product of interest. \n\nMetabolic engineers manipulate the biochemical networks cells use to convert raw materials into molecules necessary for the cell's survival. Metabolic engineering specifically seeks to:\n\n1. Mathematically model biochemical networks, calculate the yield (product divided by substrate) of valuable products and identify parts of the network that constrain the production of these products of interest. \n1. Use genetic engineering techniques to modify the biochemical network to relieve constraints limiting production. Metabolic engineers can then model the modified network to calculate the new product yield and identify new constraints (back to 1).\n\nIn this (the final lecture of Part I of the course), we'll:\n\n* Incorporate the costs of transcription and translation into the flux balance analysis problem\n* Introduce a workaround (often used in practice) to account for the metabolic cost of gene expression\n* Close the loop: using a metabolic model and flux balance to optimize glycan production in _E.coli_. \n\n\"\"\"\n\n# ╔═╡ ce5c8e9c-7652-4c3e-98a7-98e3567dc695\nmd\"\"\"\n### Integrating the Cost and Logic of Gene Expression With Flux Balance Analysis\n\nThe [Allen and Palsson study](https://pubmed.ncbi.nlm.nih.gov/12453446/) gave us a roadmap of integrating the cost of gene expression with the metabolic operation of the cell. Further, [Vilkhovoy et al.](https://pubmed.ncbi.nlm.nih.gov/29944340/) showed how we could do this in a cell-free system. However, how do you account for gene expression in metabolic models at the whole-genome scale?\n\n* [Thiele I, Jamshidi N, Fleming RM, Palsson BØ. Genome-scale reconstruction of Escherichia coli's transcriptional and translational machinery: a knowledge base, its mathematical formulation, and its functional characterization. PLoS Comput Biol. 2009;5(3):e1000312. doi:10.1371/journal.pcbi.1000312](https://www.ncbi.nlm.nih.gov/labs/pmc/articles/PMC2648898/?report=classic)\n* [Lerman JA, Hyduke DR, Latif H, Portnoy VA, Lewis NE, Orth JD, Schrimpe-Rutledge AC, Smith RD, Adkins JN, Zengler K, Palsson BO. In silico method for modeling metabolism and gene product expression at genome scale. Nat Commun. 2012 Jul 3;3:929. doi: 10.1038/ncomms1928. PMID: 22760628; PMCID: PMC3827721.](https://pubmed.ncbi.nlm.nih.gov/22760628/)\n\"\"\"\n\n# ╔═╡ bfd134fe-b311-4768-a53b-2c5c4c1b121a\nmd\"\"\"\n##### Aside: A question of timescales\nOne open question is whether we need to solve the gene expression and flux estimation problem simultaneously. The time scale of enzyme activity (and hence metabolic flux) is much faster than gene expression. Why? \n\n* The $k_{cat}$ for [phosphofructokinase-2 (pfk) in _E.coli_ is 9240 s$^{-1}$](https://bionumbers.hms.harvard.edu/bionumber.aspx?id=104955&ver=7&trm=kcat+pfk+in+E.+coli&org=). Thus, pfk has a characteristic time scale of $\\tau\\sim{k_{cat}}^{-1}$ or about 1$\\times$10$^{-4}$ s.\n* The $k_{cat}$ for RNAP polymerase is $k_{cat}$=$e_{x}L^{-1}$. If we assume [$e_{x}\\sim{35}$ nt/s](https://bionumbers.hms.harvard.edu/bionumber.aspx?id=111871&ver=1&trm=elongation+rate+RNAP+E.coli+&org=) and average read length [$L\\sim{924}$ nt](https://bionumbers.hms.harvard.edu/bionumber.aspx?id=111922&ver=3&trm=avarge+gene+length+in+E.+coli&org=), this gives $k_{cat}\\sim$ 0.038 s$^{-1}$ or a timescale of $\\tau\\sim$26.4 s.\n\nThus, the time scale of metabolic flux (e.g., the timescale of enzyme activity) is approximately 5-orders of magnitude faster than gene expression. Therefore, gene expression seems constant from the perspective of metabolic flux; hence, we treat these scales separately in traditional models. \n\"\"\"\n\n# ╔═╡ 8041cb6c-b80f-4e81-8d1d-5a2e9942d809\nmd\"\"\"\n##### Aside: How do you account for macromolecular synthesis without the E/ME formulation?\nThe E/ME formulation of Palsson and coworkers is detailed and requires more time investment than perhaps you're willing to give in a metabolic engineering application. How do you account for the energy and resource cost of producing enzymes (and all the other machinery) required to make a cell?\n\nThe traditional way metabolic engineers address this question is to treat cell mass formation as just another reaction, e.g., the growth reaction $\\mu$: \n\n$$\\left\\{precursors\\right\\}~\\rightarrow~cell$$\n\nwhere each cellmass precursor has some stoichiometric coefficient $\\sigma_{i,\\mu}$ which describes how much of precursor $i$ is consumed (or produced) during cellmass formation. This formulation leads to species material balances of the form (assuming cellmass specific units, in a constant volume batch culture):\n\n$$\\frac{dx_{i}}{dt} = \\sum_{j=1}^{\\mathcal{R}}\\sigma_{ij}\\hat{r}_{j} - \\left(x_{i}-\\sigma_{i,\\mu}\\right)\\mu\\qquad{i=1,2,\\dots,\\mathcal{M}}$$\n\nAt steady state, for example in a flux balance analysis problem, these balances form the species constraints:\n\n$$\\sum_{j=1}^{\\mathcal{R}}\\sigma_{ij}\\hat{r}_{j} - \\left(x_{i}-\\sigma_{i,\\mu}\\right)\\mu = 0\\qquad{i=1,2,\\dots,\\mathcal{M}}$$\n\nPalsson and coworkers gave an example cell mass reaction for _E.coli_ in:\n\n* [Orth JD, Fleming RM, Palsson BØ. Reconstruction and Use of Microbial Metabolic Networks: the Core Escherichia coli Metabolic Model as an Educational Guide. EcoSal Plus. 2010 Sep;4(1). doi: 10.1128/ecosalplus.10.2.1. PMID: 26443778.](https://pubmed.ncbi.nlm.nih.gov/26443778/)\n\nA recent paper on sampling uncertain biomass stoichiometric coefficients:\n\n* [Dinh et al. (2022) Quantifying the propagation of parametric uncertainty on flux balance analysis. Metabolic Engineering, 69:26-39; https://doi.org/10.1016/j.ymben.2021.10.012](https://www.sciencedirect.com/science/article/pii/S1096717621001634)\n\n\"\"\"\n\n# ╔═╡ 06c3eafa-10b3-4a47-9a06-39f6abd29db3\nmd\"\"\"\n### Using flux balance analysis to improve metabolic performance\nUltimately a metabolic engineer uses a model to improve the performance of a production host or cell-free system. There is a huge variety of design approaches to improve metabolic function; let's look at a recent one from Cornell:\n\n* [Wayman JA, Glasscock C, Mansell TJ, DeLisa MP, Varner JD. Improving designer glycan production in Escherichia coli through model-guided metabolic engineering. Metab Eng Commun. 2019;9:e00088. Published 2019 Mar 29. doi:10.1016/j.mec.2019.e00088](https://www.ncbi.nlm.nih.gov/labs/pmc/articles/PMC6454127/)\n\n\"\"\"\n\n# ╔═╡ b15b540b-8f13-4f21-b2da-510d34143b33\nmd\"\"\"\n### Summary and conclusions\n\nToday, we:\n\n* Incorporated the costs of transcription and translation into the flux balance analysis problem\n* Introduced a workaround (often used in practice) to account for the metabolic cost of gene expression\n* Closed the loop: using a metabolic model and flux balance to optimize glycan production in _E.coli_. \n\"\"\"\n\n# ╔═╡ a818128b-d642-49e0-8c7c-db36b37ea882\nmd\"\"\"\n### Alas, if we just had some more time, it would have been cool to talk about:\n\n##### So many interesting tools:\n\n* [Lewis NE, Nagarajan H, Palsson BO. Constraining the metabolic genotype-phenotype relationship using a phylogeny of in silico methods. Nat Rev Microbiol. 2012 Feb 27;10(4):291-305. doi: 10.1038/nrmicro2737. PMID: 22367118; PMCID: PMC3536058.](https://pubmed.ncbi.nlm.nih.gov/22367118/)\n\n##### Better constraints give better flux estimates:\n\n* [Buescher JM, Antoniewicz MR, Boros LG, et al. A roadmap for interpreting (13)C metabolite labeling patterns from cells. Curr Opin Biotechnol. 2015;34:189-201. doi:10.1016/j.copbio.2015.02.003](https://www.ncbi.nlm.nih.gov/labs/pmc/articles/PMC4552607/)\n\n##### Flux balance analysis prediction of mutant response is not correct:\n\n* [Segrè D, Vitkup D, Church GM. Analysis of optimality in natural and perturbed metabolic networks. Proc Natl Acad Sci U S A. 2002 Nov 12;99(23):15112-7. doi: 10.1073/pnas.232349399. Epub 2002 Nov 1. PMID: 12415116; PMCID: PMC137552.](https://pubmed.ncbi.nlm.nih.gov/12415116/)\n\n##### Molecular crowding plays a role in metabolism (non-representative random sample):\n\n\n* [Beg QK, Vazquez A, Ernst J, de Menezes MA, Bar-Joseph Z, Barabási AL, Oltvai ZN. Intracellular crowding defines the mode and sequence of substrate uptake by Escherichia coli and constrains its metabolic activity. Proc Natl Acad Sci U S A. 2007 Jul 31;104(31):12663-8. doi: 10.1073/pnas.0609845104. Epub 2007 Jul 24. PMID: 17652176; PMCID: PMC1937523.](https://pubmed.ncbi.nlm.nih.gov/17652176/)'\n* [Conrado RJ, Mansell TJ, Varner JD, DeLisa MP. Stochastic reaction-diffusion simulation of enzyme compartmentalization reveals improved catalytic efficiency for a synthetic metabolic pathway. Metab Eng. 2007 Jul;9(4):355-63. doi: 10.1016/j.ymben.2007.05.002. Epub 2007 May 26. PMID: 17601761.](https://pubmed.ncbi.nlm.nih.gov/17601761/)\n* [Klumpp S, Scott M, Pedersen S, Hwa T. Molecular crowding limits translation and cell growth. Proc Natl Acad Sci U S A. 2013 Oct 15;110(42):16754-9. doi: 10.1073/pnas.1310377110. Epub 2013 Sep 30. PMID: 24082144; PMCID: PMC3801028.](https://pubmed.ncbi.nlm.nih.gov/22760628/)\n\n\"\"\"\n\n# ╔═╡ 84d8a1c4-483c-4cc2-bdd0-7c88d26fd319\nTableOfContents(title=\"📚 Lecture Outline\", indent=true, depth=5, aside=true)\n\n# ╔═╡ 7988263a-a5f5-11ec-3836-150105d04264\nhtml\"\"\"\n\"\"\"\n\n# ╔═╡ dee24b55-a5c5-4a47-9e1c-88ea0cf1cd61\nhtml\"\"\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000001\nPLUTO_PROJECT_TOML_CONTENTS = \"\"\"\n[deps]\nPlutoUI = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\n\n[compat]\nPlutoUI = \"~0.7.37\"\n\"\"\"\n\n# ╔═╡ 00000000-0000-0000-0000-000000000002\nPLUTO_MANIFEST_TOML_CONTENTS = \"\"\"\n# This file is machine-generated - editing it directly is not advised\n\njulia_version = \"1.7.2\"\nmanifest_format = \"2.0\"\n\n[[deps.AbstractPlutoDingetjes]]\ndeps = [\"Pkg\"]\ngit-tree-sha1 = \"8eaf9f1b4921132a4cff3f36a1d9ba923b14a481\"\nuuid = \"6e696c72-6542-2067-7265-42206c756150\"\nversion = \"1.1.4\"\n\n[[deps.ArgTools]]\nuuid = \"0dad84c5-d112-42e6-8d28-ef12dabb789f\"\n\n[[deps.Artifacts]]\nuuid = \"56f22d72-fd6d-98f1-02f0-08ddc0907c33\"\n\n[[deps.Base64]]\nuuid = \"2a0f44e3-6c83-55bd-87e4-b1978d98bd5f\"\n\n[[deps.ColorTypes]]\ndeps = [\"FixedPointNumbers\", \"Random\"]\ngit-tree-sha1 = \"024fe24d83e4a5bf5fc80501a314ce0d1aa35597\"\nuuid = \"3da002f7-5984-5a60-b8a6-cbb66c0b333f\"\nversion = \"0.11.0\"\n\n[[deps.CompilerSupportLibraries_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"e66e0078-7015-5450-92f7-15fbd957f2ae\"\n\n[[deps.Dates]]\ndeps = [\"Printf\"]\nuuid = \"ade2ca70-3891-5945-98fb-dc099432e06a\"\n\n[[deps.Downloads]]\ndeps = [\"ArgTools\", \"LibCURL\", \"NetworkOptions\"]\nuuid = \"f43a241f-c20a-4ad4-852c-f6b1247861c6\"\n\n[[deps.FixedPointNumbers]]\ndeps = [\"Statistics\"]\ngit-tree-sha1 = \"335bfdceacc84c5cdf16aadc768aa5ddfc5383cc\"\nuuid = \"53c48c17-4a7d-5ca2-90c5-79b7896eea93\"\nversion = \"0.8.4\"\n\n[[deps.Hyperscript]]\ndeps = [\"Test\"]\ngit-tree-sha1 = \"8d511d5b81240fc8e6802386302675bdf47737b9\"\nuuid = \"47d2ed2b-36de-50cf-bf87-49c2cf4b8b91\"\nversion = \"0.0.4\"\n\n[[deps.HypertextLiteral]]\ngit-tree-sha1 = \"2b078b5a615c6c0396c77810d92ee8c6f470d238\"\nuuid = \"ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2\"\nversion = \"0.9.3\"\n\n[[deps.IOCapture]]\ndeps = [\"Logging\", \"Random\"]\ngit-tree-sha1 = \"f7be53659ab06ddc986428d3a9dcc95f6fa6705a\"\nuuid = \"b5f81e59-6552-4d32-b1f0-c071b021bf89\"\nversion = \"0.2.2\"\n\n[[deps.InteractiveUtils]]\ndeps = [\"Markdown\"]\nuuid = \"b77e0a4c-d291-57a0-90e8-8db25a27a240\"\n\n[[deps.JSON]]\ndeps = [\"Dates\", \"Mmap\", \"Parsers\", \"Unicode\"]\ngit-tree-sha1 = \"3c837543ddb02250ef42f4738347454f95079d4e\"\nuuid = \"682c06a0-de6a-54ab-a142-c8b1cf79cde6\"\nversion = \"0.21.3\"\n\n[[deps.LibCURL]]\ndeps = [\"LibCURL_jll\", \"MozillaCACerts_jll\"]\nuuid = \"b27032c2-a3e7-50c8-80cd-2d36dbcbfd21\"\n\n[[deps.LibCURL_jll]]\ndeps = [\"Artifacts\", \"LibSSH2_jll\", \"Libdl\", \"MbedTLS_jll\", \"Zlib_jll\", \"nghttp2_jll\"]\nuuid = \"deac9b47-8bc7-5906-a0fe-35ac56dc84c0\"\n\n[[deps.LibGit2]]\ndeps = [\"Base64\", \"NetworkOptions\", \"Printf\", \"SHA\"]\nuuid = \"76f85450-5226-5b5a-8eaa-529ad045b433\"\n\n[[deps.LibSSH2_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"MbedTLS_jll\"]\nuuid = \"29816b5a-b9ab-546f-933c-edad1886dfa8\"\n\n[[deps.Libdl]]\nuuid = \"8f399da3-3557-5675-b5ff-fb832c97cbdb\"\n\n[[deps.LinearAlgebra]]\ndeps = [\"Libdl\", \"libblastrampoline_jll\"]\nuuid = \"37e2e46d-f89d-539d-b4ee-838fcccc9c8e\"\n\n[[deps.Logging]]\nuuid = \"56ddb016-857b-54e1-b83d-db4d58db5568\"\n\n[[deps.Markdown]]\ndeps = [\"Base64\"]\nuuid = \"d6f4376e-aef5-505a-96c1-9c027394607a\"\n\n[[deps.MbedTLS_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"c8ffd9c3-330d-5841-b78e-0817d7145fa1\"\n\n[[deps.Mmap]]\nuuid = \"a63ad114-7e13-5084-954f-fe012c677804\"\n\n[[deps.MozillaCACerts_jll]]\nuuid = \"14a3606d-f60d-562e-9121-12d972cd8159\"\n\n[[deps.NetworkOptions]]\nuuid = \"ca575930-c2e3-43a9-ace4-1e988b2c1908\"\n\n[[deps.OpenBLAS_jll]]\ndeps = [\"Artifacts\", \"CompilerSupportLibraries_jll\", \"Libdl\"]\nuuid = \"4536629a-c528-5b80-bd46-f80d51c5b363\"\n\n[[deps.Parsers]]\ndeps = [\"Dates\"]\ngit-tree-sha1 = \"85b5da0fa43588c75bb1ff986493443f821c70b7\"\nuuid = \"69de0a69-1ddd-5017-9359-2bf0b02dc9f0\"\nversion = \"2.2.3\"\n\n[[deps.Pkg]]\ndeps = [\"Artifacts\", \"Dates\", \"Downloads\", \"LibGit2\", \"Libdl\", \"Logging\", \"Markdown\", \"Printf\", \"REPL\", \"Random\", \"SHA\", \"Serialization\", \"TOML\", \"Tar\", \"UUIDs\", \"p7zip_jll\"]\nuuid = \"44cfe95a-1eb2-52ea-b672-e2afdf69b78f\"\n\n[[deps.PlutoUI]]\ndeps = [\"AbstractPlutoDingetjes\", \"Base64\", \"ColorTypes\", \"Dates\", \"Hyperscript\", \"HypertextLiteral\", \"IOCapture\", \"InteractiveUtils\", \"JSON\", \"Logging\", \"Markdown\", \"Random\", \"Reexport\", \"UUIDs\"]\ngit-tree-sha1 = \"bf0a1121af131d9974241ba53f601211e9303a9e\"\nuuid = \"7f904dfe-b85e-4ff6-b463-dae2292396a8\"\nversion = \"0.7.37\"\n\n[[deps.Printf]]\ndeps = [\"Unicode\"]\nuuid = \"de0858da-6303-5e67-8744-51eddeeeb8d7\"\n\n[[deps.REPL]]\ndeps = [\"InteractiveUtils\", \"Markdown\", \"Sockets\", \"Unicode\"]\nuuid = \"3fa0cd96-eef1-5676-8a61-b3b8758bbffb\"\n\n[[deps.Random]]\ndeps = [\"SHA\", \"Serialization\"]\nuuid = \"9a3f8284-a2c9-5f02-9a11-845980a1fd5c\"\n\n[[deps.Reexport]]\ngit-tree-sha1 = \"45e428421666073eab6f2da5c9d310d99bb12f9b\"\nuuid = \"189a3867-3050-52da-a836-e630ba90ab69\"\nversion = \"1.2.2\"\n\n[[deps.SHA]]\nuuid = \"ea8e919c-243c-51af-8825-aaa63cd721ce\"\n\n[[deps.Serialization]]\nuuid = \"9e88b42a-f829-5b0c-bbe9-9e923198166b\"\n\n[[deps.Sockets]]\nuuid = \"6462fe0b-24de-5631-8697-dd941f90decc\"\n\n[[deps.SparseArrays]]\ndeps = [\"LinearAlgebra\", \"Random\"]\nuuid = \"2f01184e-e22b-5df5-ae63-d93ebab69eaf\"\n\n[[deps.Statistics]]\ndeps = [\"LinearAlgebra\", \"SparseArrays\"]\nuuid = \"10745b16-79ce-11e8-11f9-7d13ad32a3b2\"\n\n[[deps.TOML]]\ndeps = [\"Dates\"]\nuuid = \"fa267f1f-6049-4f14-aa54-33bafae1ed76\"\n\n[[deps.Tar]]\ndeps = [\"ArgTools\", \"SHA\"]\nuuid = \"a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e\"\n\n[[deps.Test]]\ndeps = [\"InteractiveUtils\", \"Logging\", \"Random\", \"Serialization\"]\nuuid = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[[deps.UUIDs]]\ndeps = [\"Random\", \"SHA\"]\nuuid = \"cf7118a7-6976-5b1a-9a39-7adc72f591a4\"\n\n[[deps.Unicode]]\nuuid = \"4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5\"\n\n[[deps.Zlib_jll]]\ndeps = [\"Libdl\"]\nuuid = \"83775a58-1f1d-513f-b197-d71354ab007a\"\n\n[[deps.libblastrampoline_jll]]\ndeps = [\"Artifacts\", \"Libdl\", \"OpenBLAS_jll\"]\nuuid = \"8e850b90-86db-534c-a0d3-1478176c7d93\"\n\n[[deps.nghttp2_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"8e850ede-7688-5339-a07c-302acd2aaf8d\"\n\n[[deps.p7zip_jll]]\ndeps = [\"Artifacts\", \"Libdl\"]\nuuid = \"3f19e933-33d8-53b3-aaab-bd5110c3b7a0\"\n\"\"\"\n\n# ╔═╡ Cell order:\n# ╟─2c895e14-e71a-435d-86d4-c1b101877b3c\n# ╟─ce5c8e9c-7652-4c3e-98a7-98e3567dc695\n# ╟─bfd134fe-b311-4768-a53b-2c5c4c1b121a\n# ╟─8041cb6c-b80f-4e81-8d1d-5a2e9942d809\n# ╟─06c3eafa-10b3-4a47-9a06-39f6abd29db3\n# ╟─b15b540b-8f13-4f21-b2da-510d34143b33\n# ╟─a818128b-d642-49e0-8c7c-db36b37ea882\n# ╠═84d8a1c4-483c-4cc2-bdd0-7c88d26fd319\n# ╠═c3530026-5a87-4447-88f5-fc744cb48ff2\n# ╟─7988263a-a5f5-11ec-3836-150105d04264\n# ╟─dee24b55-a5c5-4a47-9e1c-88ea0cf1cd61\n# ╟─00000000-0000-0000-0000-000000000001\n# ╟─00000000-0000-0000-0000-000000000002\n", "meta": {"hexsha": "22c3a7a3f1c4f2a529ab0b83f1db20314e2a40a9", "size": 17419, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lectures/Lecture-13-5440-7770-S2022.jl", "max_stars_repo_name": "varnerlab/CHEME-5440-7770-Cornell-Spring-2022", "max_stars_repo_head_hexsha": "f580d12cb9d08657b6e7488280e5bf8391bb8530", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-02-07T23:40:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T19:06:26.000Z", "max_issues_repo_path": "lectures/Lecture-13-5440-7770-S2022.jl", "max_issues_repo_name": "varnerlab/CHEME-5440-7770-Cornell-Spring-2022", "max_issues_repo_head_hexsha": "f580d12cb9d08657b6e7488280e5bf8391bb8530", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lectures/Lecture-13-5440-7770-S2022.jl", "max_forks_repo_name": "varnerlab/CHEME-5440-7770-Cornell-Spring-2022", "max_forks_repo_head_hexsha": "f580d12cb9d08657b6e7488280e5bf8391bb8530", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2022-02-03T15:15:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T22:46:36.000Z", "avg_line_length": 41.6722488038, "max_line_length": 429, "alphanum_fraction": 0.7331649348, "num_tokens": 6142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3522017684487511, "lm_q2_score": 0.15817435274843167, "lm_q1q2_score": 0.05570928676123421}} {"text": "\nexport numstring\n\n\"\"\"\n`numstring(x, n=2)`\n\nLeft pads a number (`x`) with zeros to a total of `n` charaters.\n\n## Example\n```julia-repl\njulia> numstring(11, 2)\n\"11\"\n\njulia> numstring(11, 3)\n\"011\"\n\njulia> numstring(11, 4)\n\"0011\"\n``` \n\"\"\"\nnumstring(x, n=2) = string(10^n + x)[2:end]\n", "meta": {"hexsha": "f83e64378f19985f3a34aaf36fe432058c3913d7", "size": 280, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/utils.jl", "max_stars_repo_name": "pjsjipt/AbstractDAQs.jl", "max_stars_repo_head_hexsha": "9fce348643324722d4824862e9889faff08673f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils.jl", "max_issues_repo_name": "pjsjipt/AbstractDAQs.jl", "max_issues_repo_head_hexsha": "9fce348643324722d4824862e9889faff08673f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils.jl", "max_forks_repo_name": "pjsjipt/AbstractDAQs.jl", "max_forks_repo_head_hexsha": "9fce348643324722d4824862e9889faff08673f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 12.7272727273, "max_line_length": 64, "alphanum_fraction": 0.6214285714, "num_tokens": 109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.1208532261576127, "lm_q1q2_score": 0.05477815662682093}} {"text": "struct KnotVector{T,P<:AbstractVector{T}} <: AbstractVector{T}\n parent::P\n front::Int\n back::Int\n\n @inline function KnotVector{T,P}(parent, front, back) where {T,P<:AbstractVector{T}}\n @boundscheck begin\n front ≥ 0 || throw(DomainError(front, \"front padding must be non-negative.\"))\n back ≥ 0 || throw(DomainError(back, \"back padding must be non-negative.\"))\n has_offset_axes(parent) && throw(ArgumentError(\"parent array must not have offset axes.\"))\n isempty(parent) && throw(ArgumentError(\"parent array must not be empty.\"))\n end\n new(parent, front, back)\n end\nend\n\n\"\"\"\n KnotVector(parent::AbstractVector, front[, back=front])\n\nCreate a view into `parent` where the first element of `parent` is appended `front` times at\nthe front and the last element `back` times at the back. (not exported)\n\n# Examples \n\n```jldoctest\njulia> BSplines.KnotVector(0:4, 2)\n9-element $(BSplines.KnotVector{Int64, UnitRange{Int64}}):\n 0\n 0\n 0\n 1\n 2\n 3\n 4\n 4\n 4\n\njulia> BSplines.KnotVector([\"first\", \"second\", \"last\"], 2, 3)\n8-element $(BSplines.KnotVector{String, Vector{String}}):\n \"first\"\n \"first\"\n \"first\"\n \"second\"\n \"last\"\n \"last\"\n \"last\"\n \"last\"\n```\n\"\"\"\n@propagate_inbounds KnotVector(parent::AbstractVector, front, back=front) =\n KnotVector{eltype(parent), typeof(parent)}(parent, front, back)\n@propagate_inbounds KnotVector(p::KnotVector, front, back=front) =\n KnotVector(parent(p), front + p.front, back + p.back)\n\n@inline @propagate_inbounds function Base.getindex(p::KnotVector, i::Int)\n @boundscheck checkbounds(p, i)\n @inbounds parent(p)[clamp(i-p.front, 1, length(parent(p)))]\nend\nBase.getindex(p::KnotVector, ::Colon) = copy(p)\n\nBase.IndexStyle(p::KnotVector) = IndexLinear()\nBase.parent(p::KnotVector) = p.parent\nBase.size(p::KnotVector) = (length(parent(p)) + p.front + p.back,)\n\nBase.copy(p::KnotVector) = @inbounds KnotVector(copy(parent(p)), p.front, p.back)\n\nBase.first(p::KnotVector) = @inbounds first(parent(p))\nBase.last(p::KnotVector) = @inbounds last(parent(p))\nBase.issorted(p::KnotVector) = issorted(parent(p))\n\nBase.allunique(p::KnotVector) = iszero(p.front) && iszero(p.back) && allunique(parent(p))\nBase.unique(p::KnotVector) = unique(parent(p))\n\nfunction intervalindex(p::KnotVector, x)\n index = intervalindex(parent(p), x)\n index === nothing && return nothing\n return index + p.front\nend\n\nfunction intervalindex(p::KnotVector, x, start::Integer)\n checkbounds(p, start)\n index = intervalindex(parent(p), x, clamp(start-p.front, 1, length(parent(p))))\n index === nothing && return nothing\n return index + p.front\nend\n\nstruct StandardBasisVector{T<:Number} <: AbstractVector{T}\n length::Int\n index::Int\n\n @inline function StandardBasisVector{T}(length, index) where T\n @boundscheck if !(1 ≤ index ≤ length)\n throw(DomainError(index, \"Index not in range 1:$length.\"))\n end\n new(length, index)\n end\nend\n\n\"\"\"\n StandardBasisVector([T=Bool,] length, i)\n\nCreate a vector of the specified `length` where the `i`-th element is equal to `1` and all\nother elements are equal to `0`. The elements are of type `T`. (not exported)\n\n# Examples\n\n```jldoctest\njulia> BSplines.StandardBasisVector(5, 3)\n5-element BSplines.StandardBasisVector{Bool}:\n 0\n 0\n 1\n 0\n 0\n\njulia> BSplines.StandardBasisVector(Float64, 6, 2)\n6-element BSplines.StandardBasisVector{Float64}:\n 0.0\n 1.0\n 0.0\n 0.0\n 0.0\n 0.0\n```\n\"\"\"\n@propagate_inbounds StandardBasisVector(length, index) = StandardBasisVector(Bool, length, index)\n@propagate_inbounds StandardBasisVector(T::Type, length, index) =\n StandardBasisVector{T}(length, index)\n\nBase.size(A::StandardBasisVector) = (A.length,)\n\nBase.copy(A::StandardBasisVector) = A\n\n@inline @propagate_inbounds function Base.getindex(A::StandardBasisVector, i::Int)\n @boundscheck checkbounds(A, i)\n convert(eltype(A), i == A.index)\nend\nBase.getindex(A::StandardBasisVector, ::Colon) = A\n\nBase.:(==)(x::StandardBasisVector, y::StandardBasisVector) =\n (x.length == y.length) & (x.index == y.index)\n", "meta": {"hexsha": "c558c9c213ff65fc32ef832c36921c92a743a724", "size": 4079, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/vectortypes.jl", "max_stars_repo_name": "sostock/BSplines.jl", "max_stars_repo_head_hexsha": "c76eb279f1ea0c309058f49c9eaec438da88ff7a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-04-13T12:31:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T07:34:39.000Z", "max_issues_repo_path": "src/vectortypes.jl", "max_issues_repo_name": "sostock/BSplines.jl", "max_issues_repo_head_hexsha": "c76eb279f1ea0c309058f49c9eaec438da88ff7a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28, "max_issues_repo_issues_event_min_datetime": "2020-04-26T15:47:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T18:52:24.000Z", "max_forks_repo_path": "src/vectortypes.jl", "max_forks_repo_name": "sostock/BSplines.jl", "max_forks_repo_head_hexsha": "c76eb279f1ea0c309058f49c9eaec438da88ff7a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-04-28T21:08:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-02T12:28:11.000Z", "avg_line_length": 28.7253521127, "max_line_length": 102, "alphanum_fraction": 0.6888943368, "num_tokens": 1203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.11436853070975538, "lm_q1q2_score": 0.05450571445832053}} {"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# ## 0104 Control Flow and Functions\n\n# ## Some stuff to set-up the environment..\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() \n## Pkg.instantiate() # run this if you didn't in Segment 01.01\nusing Random\nRandom.seed!(123)\nusing InteractiveUtils # loaded automatically when working... interactively\n\n# ## Variables scope\n\n# The scope of a variable is the region of code where the variable can be accessed directly (without using prefixes).\n# Modules, functions, `for` and other blocks (but notably not \"if\" blocks) introduce an inner scope that hinerit from the scope where the block or function is defined (but not, for function, from the caller's scope).\n# Variables that are defined outside any block or function are _global_ for the module where they are defined (the `Main` module if outside any other module, e.g. on the REPL), the others being _local_.\n# Variables defined in a `for` block that already exists as global behave differently depending if we are working interactively or not:\n\ng = 2\ng2 = 20\nfor i in 1:2\n l1 = g2 # l1: local, g2: global (read only)\n l1 += i\n g = i # REPL/INTERACTIVE: global (from Julia 1.5), FILE MODE: local by default (with a warning `g` being already defined)\n g += i \n println(\"i: $i\")\n println(\"l1: $l1\")\n println(\"g: $g\")\n for j in 1:2\n l1 += j # still the local in outer loop, not a new local one \n l2 = j\n g += j\n println(\"j: $j\")\n println(\"l1 inside inner loop: $l1\")\n println(\"l2 inside inner loop: $l2\")\n println(\"g inside inner loop: $g\")\n end\n ## println(\"l2 post: $l2\") # error: l2 not defined in this scope \n println(\"l1 post: $l1\")\n println(\"g post: $g\")\nend\n## println(\"l1 global $l1\") # error; l1 is not defined in the global scope\nprintln(\"g in global: $g\") # REPL/INTERACTIVE: \"7\", FILE MODE: \"2\"\n\nfunction foo(i)\n l1 = g2 # l1: local, g2: global (read only)\n l1 += i\n g = i # REPL/INTERACTIVE and FILE MODE: local by default (with a warning `g` being already defined)\n g += i \n println(\"i: $i\")\n println(\"l1: $l1\")\n println(\"g: $g\")\n for j in 1:2\n l1 += j # still the local in outer loop, not a new local one \n l2 = j\n g += j\n println(\"j: $j\")\n println(\"l1 inside inner loop: $l1\")\n println(\"l2 inside inner loop: $l2\")\n println(\"g inside inner loop: $g\")\n end\n ## println(\"l2 post: $l2\") # error: l2 not defined in this scope \n println(\"l1 post: $l1\")\n println(\"g post: $g\")\nend\n\nprintln(\"Calling foo..\")\nfoo(10)\nprintln(\"g in global: $g\") # REPL/INTERACTIVE: \"7\", FILE MODE: \"2\"\n\ng = 2\ninclude(\"010401-varScopeExample.jl.txt\") # gives a warning !\n\n\n# ## Repeated iterations: `for` and `while` loops, List Comprehension, Maps\n\nfor i in 1:2, j in 3:4 # j is the inner loop\n println(\"i: $i, j: $j\")\nend\na = 1\nwhile true # or condition, e.g. while a == 10\n global a += 1\n println(\"a: $a\")\n if a == 10\n break \n else \n continue\n end\n println(\"This is never printed\")\nend\n\n# ### List Comprehension\n[ i+j for i in 1:2, j in 3:4 if j >= 4]\n\n# ### Maps\n\n# Apply a (possible anonymous) function to a list of arguments:\n\nmap((name,year) -> println(\"$name is $year year old\"), [\"Marc\",\"Anna\"], [25,22])\n\n# !!! warninng\n# Don't confuse the single-line arrows used in anonymous functions (`->`) with the double-line arrow used to define a Pair (`=>`)\n\n# We can use maps to substitute values of an array based on a dictionary:\ncountries = [\"US\",\"UK\",\"IT\",\"UK\",\"UK\"]\ncountryNames = Dict(\"IT\" => \"Italy\", \"UK\" => \"United Kngdom\", \"US\"=>\"United States\")\ncountryLongNames = map(cShortName -> countryNames[cShortName], countries)\n\n# ## Conditional statements: if blocks and ternary operators\n\na = 10\n\nif a < 4 # use `!`, `&&` and `||` for \"not\", \"and\" and \"or\" conditions\n println(\"a < 4\")\nelseif a < 8\n println(\"a < 8\")\nelse \n println(\"a is big!\")\nend\n\na = 10\n\nif a < 5\n b = 100\nelse \n b = 200\nend\n\nb\n\n# Ternary operators\nb = a < 5 ? 100 : 200 # ? condition : if true : if false\n\n# Short-circuit evaluation\nb = 100\n(a < 5) || (b = 200) # replace an if: the second part is executed unless the first part is already true\nb\n(a < 50) || (b = 500) # here is never executed\nb\n\n# !!! warning \n# Don't confuse boolean operators `&&` and `||` with their analogous `&` and `|` bitwise operators\n\na = 3 \nb = 2 \nbitstring(a)\nbitstring(b)\n\n##a && b # error non boolean used in boolean context\na & b \na | b \n\n\n# ## Functions\n\nfunction foo(x) # function definition\n x+2\nend\nfoo(2) # function call\ninlineFunction(x) = x+2\nfoo2 = x -> x+2 # anonymous function (aka \"lambda function\") and assignment to the variable foo2\nfoo2(2)\n\n# A nested function:\nfunction f1(x)\n function f2(x,y)\n x+y\n end\n f2(x,2)\nend\n\nf1(2)\n\n# A recursive function:\nfunction fib(n) # This is a naive implementation. Much faster implementations of the Fibonacci numbers exist\n if n == 0 return 0\n elseif n == 1 return 1\n else\n return fib(n-1) + fib(n-2)\n end\nend\nfib(4)\n\n# ### Function arguments\n\n# #### Positional vs keyword arguments\nf(a,b=1;c=1) = a+10b+100c # `a` and `b` are positional arguments (`b` with a default provided), `c` is a keyword argument\nf(2)\nf(2,c=3)\n\nfoo(a, args...;c=1) = a + length(args) + sum(args) + c\nfoo(1,2,3,c=4)\n\n# Rules for positional and keyword arguments:\n# - keyword arguments follow a semicolon `;` in the parameters list of the function definition \n# - a positional argument without a default can not follow a positional argument with a default provided\n# - the splat operator to define variable number of arguments must be the last positional argument \n# - the function call must use positional arguments by position and keyword arguments by name\n\n\n## foo(a::String=\"aaa\",b::Int64) = \"$a \"+string(b) # error! Optional positional argument before a mandatory positional one \n\n# ### Argument types and multiple dispatch\n\n# Simple to understand the usage, complex to understand the deep implications\nfoo3(a::Int64,b::String) = a + parse(Int64,b)\nfoo3(2,\"3\")\nfoo3(a::String,b::Int64) = parse(Int64,a) + b\nfoo3(\"3\",2)\nmethods(foo3)\n\n# Multiple dispatch allows to compile a _specialised_ version JIT at run time, on the first call with the given parameters type\n# We will see it again when dealing with type inheritance\n# In general, unless we need to write specialised methods, no need to specify the type of the parameters. No influence on performances, this is automatically inferred (and the funciton compiled) based on the run-time type of the argument\n\n# !!! tip Functions performances tip\n# The most important things for performances are (1) that the function is _type stable_, that is, that conditional to a specific combination of the types of the parameters the function returns the same type. This is a condition necessary to have a working chain of type inference across function calls; (2) that no (non constant) global constants are used in the function and indeed all the required information for the functio ndoing its work is embedded in the function parameters\n\n\n# ### Function templates\nfoo3(a::T,b::String) where {T<: Number} = a + parse(T,b) # can use T in the function body\nfoo3(2,\"1\")\nfoo3(1.5,\"1.5\")\nfoo4(a::Int64,b::T where T <: Number) = a + b # ok not used in functio nbody\nfoo4(a::Int64,b::Array{T} where T <: Number) = a .+ fill(T,b,2) # wil lerror, can't use T in the function body\n## foo4(2,[1,2]) # run time error, T not defined \n\n# ### Call by reference vs. call by value \n\n# How the variable used as function argument within the function body relates to the variable used in calling the function ?\n# - **call by value**: the value of the argument is copied and the function body works on a copy of the value\n# - **call by reference**: the function works on the same object being referenced by the caller variable and the function argument\n# - **call by sharing** (Julia): the arguments are just new local variables that bind the same object. The effects of \"modifications\" on the local variable on the caller's one depends on the mutability property of the object as we saw in the _Types and objects_ segment:\n# - immutable objects: we can only have that the argument is rebinded to other objects. No effects on the original caller object\n# - mutable objects: if the argument is rebinded to an other object, no effects on the caller object. If the object is modified, the caller object (being the same object) is also modified\n\nx = 10\nfoo(y) = y = 1\nfoo(x)\nx\nfoo(x) = x[1] = 10\nx = [1,2]\nfoo(x)\nx\nfoo3(x) = x = [10,20]\nfoo3(x)\nx\n\n\n# !!! info\n# Functions that modify at least one of their arguments are named, by convention, with an exclamation mark at the end of their name and the argument(s) that is (are) modified set as the first(s) argument(s) \n\nfoo!(x) = x[1] = 10 # to follow the convention\n\n\n# ## `do` blocks\n\n# Functions that accept an other function as their first parameter can be rewritten with the function itself defined in a `do` block:\nusing Statistics\npool(f,x,poolSize=3) = [f(x[i:i+poolSize-1]) for i in 1:length(x)-poolSize+1] # a real case, used in neural networks as pooling layer\npool(mean,[1,2,3,4,5,6])\npool(maximum,[1,2,3,4,5,6])\npool([1,2,3,4,5]) do x # x is a local variable within the do block. We need as many local variables as the number of parameters of the inner function\n sum(x)/length(x)\nend\n# Using the `do` block we can call the outer function and define the inner function at the same time.\n# `do` blocks are frequently used in input/output operations\n", "meta": {"hexsha": "1e89f33d5bd7050da50c600471ce776a0b5b4b8e", "size": 11006, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lessonsSources/01_-_JULIA1_-_Basic_Julia_programming/0104_-_Control_flow_and_functions.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/01_-_JULIA1_-_Basic_Julia_programming/0104_-_Control_flow_and_functions.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/01_-_JULIA1_-_Basic_Julia_programming/0104_-_Control_flow_and_functions.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": 39.4480286738, "max_line_length": 486, "alphanum_fraction": 0.6212974741, "num_tokens": 2886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30074557894124154, "lm_q2_score": 0.1801066574851787, "lm_q1q2_score": 0.05416628097655196}} {"text": "\"\"\"\n sign_cadlag(x::N) where {N<:Real}\n\nThis function works like the sign function but is ``1`` for input ``0``.\n\n### Input\n\n- `x` -- real scalar\n\n### Output\n\n``1`` if ``x ≥ 0``, ``-1`` otherwise.\n\n### Notes\n\nThis is the sign function right-continuous at zero (see\n[càdlàg function](https://en.wikipedia.org/wiki/C%C3%A0dl%C3%A0g)).\nIt can be used with vector-valued arguments via the dot operator.\n\n### Examples\n\n```jldoctest\njulia> LazySets.sign_cadlag.([-0.6, 1.3, 0.0])\n3-element Array{Float64,1}:\n -1.0\n 1.0\n 1.0\n```\n\"\"\"\nfunction sign_cadlag(x::N) where {N<:Real}\n return x < zero(x) ? -one(x) : one(x)\nend\n\n\"\"\"\n substitute(substitution::Dict{Int, T}, x::AbstractVector{T}) where {T}\n\nApply a substitution to a given vector.\n\n### Input\n\n- `substitution` -- substitution (a mapping from an index to a new value)\n- `x` -- vector\n\n### Output\n\nA fresh vector corresponding to `x` after `substitution` was applied.\n\"\"\"\nfunction substitute(substitution::Dict{Int, T}, x::AbstractVector{T}) where {T}\n return substitute!(substitution, copy(x))\nend\n\n\"\"\"\n substitute!(substitution::Dict{Int, T}, x::AbstractVector{T}) where {T}\n\nApply a substitution to a given vector.\n\n### Input\n\n- `substitution` -- substitution (a mapping from an index to a new value)\n- `x` -- vector (modified in this function)\n\n### Output\n\nThe same (but see the Notes below) vector `x` but after `substitution` was\napplied.\n\n### Notes\n\nThe vector `x` is modified in-place if it has type `Vector` or `SparseVector`.\nOtherwise, we first create a new `Vector` from it.\n\"\"\"\nfunction substitute!(substitution::Dict{Int, T}, x::AbstractVector{T}) where {T}\n return substitute!(Vector(x), substitution)\nend\n\nfunction substitute!(substitution::Dict{Int, T},\n x::Union{Vector{T}, SparseVector{T}}) where {T}\n for (index, value) in substitution\n x[index] = value\n end\n return x\nend\n\n\"\"\"\n reseed(rng::AbstractRNG, seed::Union{Int, Nothing})\n\nReset the RNG seed if the seed argument is a number.\n\n### Input\n\n- `rng` -- random number generator\n- `seed` -- seed for reseeding\n\n### Output\n\nThe input RNG if the seed is `nothing`, and a reseeded RNG otherwise.\n\"\"\"\nfunction reseed(rng::AbstractRNG, seed::Union{Int, Nothing})\n if seed != nothing\n return Random.seed!(rng, seed)\n end\n return rng\nend\n\n\"\"\"\n StrictlyIncreasingIndices\n\nIterator over the vectors of `m` strictly increasing indices from 1 to `n`.\n\n### Fields\n\n- `n` -- size of the index domain\n- `m` -- number of indices to choose (resp. length of the vectors)\n\n### Notes\n\nThe vectors are modified in-place.\n\nThe iterator ranges over ``\\\\binom{n}{m}`` (`n` choose `m`) possible vectors.\n\nThis implementation results in a lexicographic order with the last index growing\nfirst.\n\n### Examples\n\n```jldoctest\njulia> for v in LazySets.StrictlyIncreasingIndices(4, 2)\n println(v)\n end\n[1, 2]\n[1, 3]\n[1, 4]\n[2, 3]\n[2, 4]\n[3, 4]\n```\n\"\"\"\nstruct StrictlyIncreasingIndices\n n::Int\n m::Int\n\n function StrictlyIncreasingIndices(n::Int, m::Int)\n @assert n >= m > 0 \"require n >= m > 0\"\n new(n, m)\n end\nend\n\nBase.eltype(::Type{StrictlyIncreasingIndices}) = Vector{Int}\nBase.length(sii::StrictlyIncreasingIndices) = binomial(sii.n, sii.m)\n\n# initialization\nfunction Base.iterate(sii::StrictlyIncreasingIndices)\n v = [1:sii.m;]\n return (v, v)\nend\n\n# normal iteration\nfunction Base.iterate(sii::StrictlyIncreasingIndices, state::AbstractVector{Int})\n v = state\n i = sii.m\n diff = sii.n\n if i == diff\n return nothing\n end\n while v[i] == diff\n i -= 1\n diff -= 1\n end\n # update vector\n v[i] += 1\n for j in i+1:sii.m\n v[j] = v[j-1] + 1\n end\n # detect termination: first index has maximum value\n if i == 1 && v[1] == (sii.n - sii.m + 1)\n return (v, nothing)\n end\n return (v, v)\nend\n\n# termination\nfunction Base.iterate(sii::StrictlyIncreasingIndices, state::Nothing)\n return nothing\nend\n\n\"\"\"\n subtypes(interface, concrete::Bool)\n\nReturn the concrete subtypes of a given interface.\n\n### Input\n\n- `interface` -- an abstract type, usually a set interface\n- `concrete` -- if `true`, seek further the inner abstract subtypes of the given\n interface, otherwise return only the direct subtypes of `interface`\n\n### Output\n\nA list with the subtypes of the abstract type `interface`, sorted alphabetically.\n\n### Examples\n\nConsider the `AbstractPolytope` interface. If we include the abstract subtypes\nof this interface,\n\n```jldoctest subtypes\njulia> using LazySets: subtypes\n\njulia> subtypes(AbstractPolytope, false)\n4-element Array{Any,1}:\n AbstractCentrallySymmetricPolytope\n AbstractPolygon\n HPolytope\n VPolytope\n```\n\nWe can use this function to obtain the concrete subtypes of\n`AbstractCentrallySymmetricPolytope` and `AbstractPolygon` (further until all\nconcrete types are obtained), using the `concrete` flag:\n\n```jldoctest subtypes\njulia> subtypes(AbstractPolytope, true)\n14-element Array{Type,1}:\n Ball1\n BallInf\n HPolygon\n HPolygonOpt\n HPolytope\n Hyperrectangle\n Interval\n LineSegment\n Singleton\n SymmetricIntervalHull\n VPolygon\n VPolytope\n ZeroSet\n Zonotope\n```\n\"\"\"\nfunction subtypes(interface, concrete::Bool)\n\n subtypes_to_test = subtypes(interface)\n\n # do not seek the concrete subtypes further\n if !concrete\n return sort(subtypes_to_test, by=string)\n end\n\n result = Vector{Type}()\n i = 0\n while i < length(subtypes_to_test)\n i += 1\n subtype = subtypes_to_test[i]\n new_subtypes = subtypes(subtype)\n if isempty(new_subtypes)\n # base type found\n push!(result, subtype)\n else\n # yet another interface layer\n append!(subtypes_to_test, new_subtypes)\n end\n end\n return sort(result, by=string)\nend\n\n\"\"\"\n implementing_sets(op::Function;\n signature::Tuple{Vector{Type}, Int}=(Type[], 1),\n type_args=Float64, binary::Bool=false)\n\nCompute a dictionary containing information about availability of (unary or\nbinary) concrete set operations.\n\n### Input\n\n- `op` -- set operation (respectively its `Function` object)\n- `signature` -- (optional, default: `Type[]`) the type signature of the\n function without the `LazySet` type(s) (see also the `index`\n option and the `Examples` section below)\n- `index` -- (optional, default: `1`) index of the set type in the signature\n in the unary case (see the `binary` option)\n- `type_args` -- (optional, default: `Float64`) type arguments added to the\n `LazySet`(s) when searching for available methods; valid\n inputs are a type or `nothing`, and in the unary case (see the\n `binary` option) it can also be a list of types\n- `binary` -- (optional, default: `false`) flag indicating whether `op` is a\n binary function (`true`) or a unary function (`false`)\n\n### Output\n\nA dictionary with three keys each mapping to a list:\n- `\"available\"` -- This list contains all set types such that there exists an\n implementation of `op`.\n- `\"missing\"` -- This list contains all set types such that there does not\n exist an implementation of `op`. Note that this is the\n complement of the `\"available\"` list.\n- `\"specific\"` -- This list contains all set types such that there exists a\n type-specific implementation. Note that those set types also\n occur in the `\"available\"` list.\n\nIn the unary case, the lists contain set types.\nIn the binary case, the lists contain pairs of set types.\n\n### Examples\n\n```jldoctests\njulia> using LazySets: implementing_sets\n\njulia> dict = implementing_sets(tovrep);\n\njulia> dict[\"available\"] # tovrep is only available for polyhedral set types\n6-element Array{Type,1}:\n HPolygon\n HPolygonOpt\n HPolyhedron\n HPolytope\n VPolygon\n VPolytope\n\njulia> dict = implementing_sets(σ; signature=Type[AbstractVector{Float64}], index=2);\n\njulia> dict[\"missing\"] # every set type implements function σ\n0-element Array{Type,1}\n\njulia> N = Rational{Int}; # restriction of the number type\n\njulia> dict = implementing_sets(σ; signature=Type[AbstractVector{N}], index=2, type_args=N);\n\njulia> dict[\"missing\"] # some set types are not available with number type N\n4-element Array{Type,1}:\n Ball2\n Ballp\n Bloating\n Ellipsoid\n\njulia> dict = LazySets.implementing_sets(convex_hull; binary=true); # binary case\n\njulia> (HPolytope, HPolytope) ∈ dict[\"available\"] # dict contains pairs now\ntrue\n```\n\"\"\"\nfunction implementing_sets(op::Function;\n signature::Vector{Type}=Type[],\n index::Int=1,\n type_args=Float64,\n binary::Bool=false)\n function get_unary_dict()\n return Dict{String, Vector{Type}}(\"available\" => Vector{Type}(),\n \"missing\" => Vector{Type}(),\n \"specific\" => Vector{Type}())\n end\n\n if !binary\n # unary case\n dict = get_unary_dict()\n _implementing_sets_unary!(dict, op, signature, index, type_args)\n return dict\n end\n\n # binary case by considering all set types as second argument\n binary_dict = Dict{String, Vector{Tuple{Type, Type}}}(\n \"available\" => Vector{Tuple{Type, Type}}(),\n \"missing\" => Vector{Tuple{Type, Type}}(),\n \"specific\" => Vector{Tuple{Type, Type}}())\n signature_copy = copy(signature)\n insert!(signature_copy, 1, LazySet) # insert a dummy type\n for set_type in subtypes(LazySet, true)\n augmented_set_type = set_type\n try\n if type_args isa Type\n augmented_set_type = set_type{type_args}\n else\n @assert type_args == nothing \"for binary functions, \" *\n \"`type_args` must not be a list\"\n end\n catch e\n # type combination not available\n push!(binary_dict[\"missing\"], (set_type, LazySet))\n continue\n end\n signature_copy[1] = augmented_set_type # replace dummy type\n unary_dict = get_unary_dict()\n _implementing_sets_unary!(unary_dict, op, signature_copy, 1, type_args)\n\n # create pairs\n for key in [\"available\", \"missing\", \"specific\"]\n i = 1\n for other_set_type in unary_dict[key]\n push!(binary_dict[key], (set_type, other_set_type))\n i += 1\n end\n end\n end\n return binary_dict\nend\n\nfunction _implementing_sets_unary!(dict, op, signature, index, type_args)\n function create_type_tuple(given_type)\n if isempty(signature)\n return Tuple{given_type}\n end\n # create dynamic tuple\n new_signature = copy(signature)\n insert!(new_signature, index, given_type)\n return Tuple{new_signature...}\n end\n\n for set_type in subtypes(LazySet, true)\n augmented_set_type = set_type\n try\n if type_args isa Type\n augmented_set_type = set_type{type_args}\n elseif type_args != nothing\n augmented_set_type = set_type{type_args...}\n end\n catch e\n # type combination not available\n push!(dict[\"missing\"], set_type)\n continue\n end\n tuple_set_type = create_type_tuple(augmented_set_type)\n if !hasmethod(op, tuple_set_type)\n # implementation not available\n push!(dict[\"missing\"], set_type)\n continue\n end\n # implementation available\n push!(dict[\"available\"], set_type)\n\n # check if there is a type-specific method\n super_type = supertype(augmented_set_type)\n tuple_super_type = create_type_tuple(super_type)\n if !hasmethod(op, tuple_super_type)\n continue\n end\n method_set_type = which(op, tuple_set_type)\n method_super_type = which(op, tuple_super_type)\n if method_set_type != method_super_type\n push!(dict[\"specific\"], set_type)\n end\n end\nend\n", "meta": {"hexsha": "3a2082cd2270f6f21fb56f8c7ff1cd837e4053be", "size": 12254, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/Utils/helper_functions.jl", "max_stars_repo_name": "birm/LazySets.jl", "max_stars_repo_head_hexsha": "634d9c0cbbc4acd81fb0e787757409946d6e1550", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Utils/helper_functions.jl", "max_issues_repo_name": "birm/LazySets.jl", "max_issues_repo_head_hexsha": "634d9c0cbbc4acd81fb0e787757409946d6e1550", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Utils/helper_functions.jl", "max_forks_repo_name": "birm/LazySets.jl", "max_forks_repo_head_hexsha": "634d9c0cbbc4acd81fb0e787757409946d6e1550", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6613995485, "max_line_length": 92, "alphanum_fraction": 0.6384853925, "num_tokens": 3109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681662740417, "lm_q2_score": 0.13660839881392148, "lm_q1q2_score": 0.05410623801586285}} {"text": "# This file is a part of AstroLib.jl. License is MIT \"Expat\".\n# Copyright (C) 2016 Mosè Giordano.\n\n\"\"\"\n daycnv(julian_days) -> DateTime\n\n### Purpose ###\n\nConverts Julian days number to Gregorian calendar dates.\n\n### Explanation ###\n\nTakes the number of Julian calendar days since epoch `-4713-11-24T12:00:00` and\nreturns the corresponding proleptic Gregorian Calendar date.\n\n### Argument ###\n\n* `julian_days`: Julian days number.\n\n### Output ###\n\nProleptic Gregorian Calendar date, of type `DateTime`, corresponding to the\ngiven Julian days number.\n\n### Example ###\n\n```jldoctest\njulia> using AstroLib\n\njulia> daycnv(2440000)\n1968-05-23T12:00:00\n```\n\n### Notes ###\n\n`jdcnv` is the inverse of this function.\n\"\"\"\nconst daycnv=Dates.julian2datetime\n", "meta": {"hexsha": "87efaaec0019a86fc222e69c4926cbc1e778642f", "size": 749, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/daycnv.jl", "max_stars_repo_name": "UnofficialJuliaMirror/AstroLib.jl-c7932e45-9af1-51e7-9da9-f004cd3a462b", "max_stars_repo_head_hexsha": "fb2ef587a2ac68a1c864bf251e8d9c3601ec4719", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 62, "max_stars_repo_stars_event_min_datetime": "2016-09-11T14:59:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T20:45:36.000Z", "max_issues_repo_path": "src/daycnv.jl", "max_issues_repo_name": "UnofficialJuliaMirror/AstroLib.jl-c7932e45-9af1-51e7-9da9-f004cd3a462b", "max_issues_repo_head_hexsha": "fb2ef587a2ac68a1c864bf251e8d9c3601ec4719", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 64, "max_issues_repo_issues_event_min_datetime": "2017-01-19T21:03:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T12:27:46.000Z", "max_forks_repo_path": "src/daycnv.jl", "max_forks_repo_name": "UnofficialJuliaMirror/AstroLib.jl-c7932e45-9af1-51e7-9da9-f004cd3a462b", "max_forks_repo_head_hexsha": "fb2ef587a2ac68a1c864bf251e8d9c3601ec4719", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2016-07-12T02:11:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T11:55:21.000Z", "avg_line_length": 19.2051282051, "max_line_length": 79, "alphanum_fraction": 0.7129506008, "num_tokens": 215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4339814501625211, "lm_q2_score": 0.12421301969912356, "lm_q1q2_score": 0.053906146418091445}} {"text": "\n\"\"\"\n neighbors(vec::AbstractVector)\n\nReturns an iterator over neighboring pairs.\n```julia\njulia> neighbors([1,2,3]) |> collect\n2-element Array{Tuple{Int64,Int64},1}:\n (1, 2)\n (2, 3)\n ```\n \"\"\"\nfunction neighbors(itr::AbstractVector)\n first = @view itr[1:end-1]\n second = @view itr[2:end]\n zip(first, second)\nend\n", "meta": {"hexsha": "fe86fc73dd3cab659cf9e073bcde91343a0cecbb", "size": 325, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/helpers.jl", "max_stars_repo_name": "jonalm/SparseTimeSeries.jl", "max_stars_repo_head_hexsha": "1dedc8380e6cdd00deda59664b890ebc49f3a714", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-02-04T15:41:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-27T23:03:26.000Z", "max_issues_repo_path": "src/helpers.jl", "max_issues_repo_name": "jonalm/SparseTimeSeries.jl", "max_issues_repo_head_hexsha": "1dedc8380e6cdd00deda59664b890ebc49f3a714", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-02-03T15:18:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-15T17:53:20.000Z", "max_forks_repo_path": "src/helpers.jl", "max_forks_repo_name": "jonalm/SparseTimeSeries.jl", "max_forks_repo_head_hexsha": "1dedc8380e6cdd00deda59664b890ebc49f3a714", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T10:41:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T10:41:07.000Z", "avg_line_length": 18.0555555556, "max_line_length": 43, "alphanum_fraction": 0.6461538462, "num_tokens": 101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4301473485858429, "lm_q2_score": 0.12421300511003351, "lm_q1q2_score": 0.05342989480796067}} {"text": "abstract type SaturationGoal end\n\nreached(g::EGraph, goal::Nothing) = false\nreached(g::EGraph, goal::SaturationGoal) = false\n\n\"\"\"\nThis goal is reached when the `exprs` list of expressions are in the \nsame equivalence class.\n\"\"\"\nstruct EqualityGoal <: SaturationGoal\n exprs::Vector{Any}\n ids::Vector{EClassId}\n function EqualityGoal(exprs, eclasses) \n @assert length(exprs) == length(eclasses) && length(exprs) != 0 \n new(exprs, eclasses)\n end\nend\n\nfunction reached(g::EGraph, goal::EqualityGoal)\n all(x -> in_same_class(g, goal.ids[1], x), @view goal.ids[2:end])\nend\n\n\"\"\"\nBoolean valued function as an arbitrary saturation goal.\nUser supplied function must take an [`EGraph`](@ref) as the only parameter.\n\"\"\"\nstruct FunctionGoal <: SaturationGoal\n fun::Function\nend\n\nfunction reached(g::EGraph, goal::FunctionGoal)::Bool\n fun(g) \nend\n\nmutable struct Report\n reason::Union{Symbol, Nothing}\n egraph::EGraph\n iterations::Int\n to::TimerOutput\nend\n\nReport() = Report(nothing, EGraph(), 0, TimerOutput())\nReport(g::EGraph) = Report(nothing, g, 0, TimerOutput())\n\n\n\n# string representation of timedata\nfunction Base.show(io::IO, x::Report)\n g = x.egraph\n println(io, \"Equality Saturation Report\")\n println(io, \"=================\")\n println(io, \"\\tStop Reason: $(x.reason)\")\n println(io, \"\\tIterations: $(x.iterations)\")\n # println(io, \"\\tRules applied: $(g.age)\")\n println(io, \"\\tEGraph Size: $(g.numclasses) eclasses, $(length(g.memo)) nodes\")\n print_timer(io, x.to)\nend\n\n\"\"\"\nConfigurable Parameters for the equality saturation process.\n\"\"\"\n@with_kw mutable struct SaturationParams\n timeout::Int = 8\n timelimit::Period = Second(-1)\n # default sizeout. TODO make this bytes\n # sizeout::Int = 2^14\n matchlimit::Int = 5000\n eclasslimit::Int = 5000\n enodelimit::Int = 15000\n goal::Union{Nothing, SaturationGoal} = nothing\n stopwhen::Function = ()->false\n scheduler::Type{<:AbstractScheduler} = BackoffScheduler\n schedulerparams::Tuple=()\n threaded::Bool = false\n timer::Bool = true\n printiter::Bool = false\n simterm::Function = similarterm\nend\n\nstruct Match\n rule::AbstractRule \n # the rhs pattern to instantiate \n pat_to_inst\n # the substitution\n sub::Sub \n # the id the matched the lhs \n id::EClassId\nend\n\nconst MatchesBuf = Vector{Match}\n\nfunction cached_ids(g::EGraph, p::AbstractPat)# ::Vector{Int64}\n if isground(p)\n id = lookup_pat(g, p)\n !isnothing(id) && return [id]\n else\n return collect(keys(g.classes))\n end\n return []\nend\n\nfunction cached_ids(g::EGraph, p) # p is a literal\n id = lookup(g, ENodeLiteral(p))\n !isnothing(id) && return [id]\n return []\nend\n\n# FIXME \nfunction cached_ids(g::EGraph, p::PatTerm)\n # println(\"pattern $p, $(p.head)\")\n # println(\"all ids\")\n # keys(g.classes) |> println\n # println(\"cached symbols\")\n # cached = get(g.symcache, p.head, Set{Int64}())\n # println(\"symbols where $(p.head) appears\")\n # appears = Set{Int64}() \n # for (id, class) ∈ g.classes \n # for n ∈ class \n # if n.head == p.head\n # push!(appears, id) \n # end\n # end\n # end\n # # println(appears)\n # if !(cached == appears)\n # @show cached \n # @show appears\n # end\n\n collect(keys(g.classes))\n # cached\n # get(g.symcache, p.head, [])\nend\n\n# function cached_ids(g::EGraph, p::PatLiteral)\n# get(g.symcache, p.val, [])\n# end\n\nfunction (r::SymbolicRule)(g::EGraph, id::EClassId)\n ematch(g, r.ematch_program, id) .|> sub -> Match(r, r.right, sub, id)\nend\n\nfunction (r::DynamicRule)(g::EGraph, id::EClassId)\n ematch(g, r.ematch_program, id) .|> sub -> Match(r, nothing, sub, id)\nend\n\nfunction (r::BidirRule)(g::EGraph, id::EClassId)\n vcat(ematch(g, r.ematch_program_l, id) .|> sub -> Match(r, r.right, sub, id),\n ematch(g, r.ematch_program_r, id) .|> sub -> Match(r, r.left, sub, id))\nend\n\n\n\"\"\"\nReturns an iterator of `Match`es.\n\"\"\"\nfunction eqsat_search!(egraph::EGraph, theory::Vector{<:AbstractRule},\n scheduler::AbstractScheduler, report; threaded=false)\n match_groups = Vector{Match}[]\n function pmap(f, xs) \n # const propagation should be able to optimze one of the branch away\n if threaded\n # # try to divide the work evenly between threads without adding much overhead\n # chunks = Threads.nthreads() * 10\n # basesize = max(length(xs) ÷ chunks, 1)\n # ThreadsX.mapi(f, xs; basesize=basesize) \n ThreadsX.map(f, xs)\n else\n map(f, xs)\n end\n end\n\n inequalities = filter(Base.Fix2(isa, UnequalRule), theory)\n # never skip contradiction checks\n append_time = TimerOutput()\n for rule ∈ inequalities\n @timeit report.to repr(rule) begin\n ids = cached_ids(egraph, rule.left)\n rule_matches = pmap(i -> rule(egraph, i), ids)\n @timeit append_time \"appending matches\" begin\n append!(match_groups, rule_matches)\n end\n end\n end\n\n other_rules = filter(theory) do rule \n !(rule isa UnequalRule)\n end\n for rule ∈ other_rules \n @timeit report.to repr(rule) begin\n # don't apply banned rules\n if !cansearch(scheduler, rule)\n # println(\"skipping banned rule $rule\")\n continue\n end\n ids = cached_ids(egraph, rule.left)\n rule_matches = pmap(i -> rule(egraph, i), ids)\n\n n_matches = isempty(rule_matches) ? 0 : sum(length, rule_matches)\n # @show (rule, n_matches)\n can_yield = inform!(scheduler, rule, n_matches)\n if can_yield\n @timeit append_time \"appending matches\" begin\n append!(match_groups, rule_matches)\n end\n end\n end\n end\n\n # @timeit append_time \"appending matches\" begin\n # result = reduce(vcat, match_groups) # this should be more efficient than multiple appends\n # end\n merge!(report.to, append_time, tree_point=[\"Search\"])\n\n return Iterators.flatten(match_groups)\n # return result\nend\n \n\nfunction (rule::UnequalRule)(g::EGraph, match::Match; simterm=similarterm)\n lc = match.id\n rinst = instantiate(g, match.pat_to_inst, match.sub, rule; simterm=simterm)\n rc, node = addexpr!(g, rinst)\n\n if find(g, lc) == find(g, rc)\n @log \"Contradiction!\" rule\n return :contradiction\n end\n return nothing\nend\n\nfunction (rule::SymbolicRule)(g::EGraph, match::Match; simterm=similarterm)\n rinst = instantiate(g, match.pat_to_inst, match.sub, rule; simterm=simterm)\n rc, node = addexpr!(g, rinst)\n merge!(g, match.id, rc.id)\n return nothing\nend\n\n\nfunction (rule::DynamicRule)(g::EGraph, match::Match; simterm=similarterm)\n f = rule.rhs_fun\n actual_params = [instantiate(g, PatVar(v, i, alwaystrue), match.sub, rule) for (i, v) in enumerate(rule.patvars)]\n r = f(g[match.id], match.sub, g, actual_params...)\n isnothing(r) && return nothing\n rc, node = addexpr!(g, r)\n merge!(g, match.id, rc.id)\n return nothing\nend\n\n\nfunction eqsat_apply!(g::EGraph, matches, rep::Report, params::SaturationParams)\n i = 0\n # println.(matches)\n for match ∈ matches\n i += 1\n\n # if params.eclasslimit > 0 && g.numclasses > params.eclasslimit\n # @log \"E-GRAPH SIZEOUT\"\n # rep.reason = :eclasslimit\n # return\n # end\n\n if reached(g, params.goal)\n @log \"Goal reached\"\n rep.reason = :goalreached\n return\n end\n\n\n rule = match.rule\n # println(\"applying $rule\")\n\n halt_reason = rule(g, match; simterm=params.simterm)\n if (halt_reason !== nothing)\n rep.reason = halt_reason\n return \n end \n\n # println(rule)\n # println(sub)\n # println(l); println(r)\n # display(egraph.classes); println()\n end\nend\n\nimport ..@log\n\n\n\"\"\"\nCore algorithm of the library: the equality saturation step.\n\"\"\"\nfunction eqsat_step!(g::EGraph, theory::Vector{<:AbstractRule}, curr_iter,\n scheduler::AbstractScheduler, match_hist::MatchesBuf, \n params::SaturationParams, report)\n\n instcache = Dict{AbstractRule, Dict{Sub, EClassId}}()\n\n setiter!(scheduler, curr_iter)\n\n matches = @timeit report.to \"Search\" eqsat_search!(g, theory, scheduler, report; threaded=params.threaded)\n\n # matches = setdiff!(matches, match_hist)\n\n @timeit report.to \"Apply\" eqsat_apply!(g, matches, report, params)\n \n\n # union!(match_hist, matches)\n\n if report.reason === nothing && cansaturate(scheduler) && isempty(g.dirty)\n report.reason = :saturated\n end\n @timeit report.to \"Rebuild\" rebuild!(g)\n \n return report, g\nend\n\n\"\"\"\nGiven an [`EGraph`](@ref) and a collection of rewrite rules,\nexecute the equality saturation algorithm.\n\"\"\"\nfunction saturate!(g::EGraph, theory::Vector{<:AbstractRule}, params=SaturationParams())\n curr_iter = 0\n\n sched = params.scheduler(g, theory, params.schedulerparams...)\n match_hist = MatchesBuf()\n report = Report(g)\n\n start_time = Dates.now().instant\n\n !params.timer && disable_timer!(report.to)\n timelimit = params.timelimit > Second(0)\n \n\n while true\n curr_iter+=1\n\n params.printiter && @info(\"iteration \", curr_iter)\n\n report, egraph = eqsat_step!(g, theory, curr_iter, sched, match_hist, params, report)\n\n elapsed = Dates.now().instant - start_time\n\n if timelimit && params.timelimit <= elapsed\n report.reason = :timelimit\n break\n end\n\n # report.reason == :matchlimit && break\n if !(report.reason isa Nothing)\n break\n end\n\n if curr_iter >= params.timeout \n report.reason = :timeout\n break\n end\n\n if params.eclasslimit > 0 && g.numclasses > params.eclasslimit \n # println(params.eclasslimit)\n report.reason = :eclasslimit\n break\n end\n\n if reached(g, params.goal)\n report.reason = :goalreached\n break\n end\n end\n report.iterations = curr_iter\n @log report\n\n return report\nend\n\nfunction areequal(theory::Vector, exprs...; params=SaturationParams())\n g = EGraph(exprs[1])\n areequal(g, theory, exprs...; params=params)\nend\n\nfunction areequal(g::EGraph, t::Vector{<:AbstractRule}, exprs...; params=SaturationParams())\n @log \"Checking equality for \" exprs\n if length(exprs) == 1; return true end\n # rebuild!(G)\n\n @log \"starting saturation\"\n\n n = length(exprs)\n ids = Vector{EClassId}(undef, n)\n nodes = Vector{AbstractENode}(undef, n)\n for i ∈ 1:n\n ec, node = addexpr!(g, exprs[i])\n ids[i] = ec.id\n nodes[i] = node\n end\n\n goal = EqualityGoal(collect(exprs), ids)\n \n # alleq = () -> (all(x -> in_same_set(G.uf, ids[1], x), ids[2:end]))\n\n params.goal = goal\n # params.stopwhen = alleq\n\n report = saturate!(g, t, params)\n\n # display(g.classes); println()\n if !(report.reason === :saturated) && !reached(g, goal)\n return missing # failed to prove\n end\n return reached(g, goal)\nend\n\nmacro areequal(theory, exprs...)\n esc(:(areequal($theory, $exprs...))) \nend\n\nmacro areequalg(G, theory, exprs...)\n esc(:(areequal($G, $theory, $exprs...)))\nend\n", "meta": {"hexsha": "c9964dfc585ea8de874b878067bbca649310ebf1", "size": 11469, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/EGraphs/saturation.jl", "max_stars_repo_name": "Wilkenfeld/Metatheory.jl", "max_stars_repo_head_hexsha": "40d535ebe9765eca77658f090f9151ac72788455", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 157, "max_stars_repo_stars_event_min_datetime": "2021-02-12T17:44:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-08T03:28:09.000Z", "max_issues_repo_path": "src/EGraphs/saturation.jl", "max_issues_repo_name": "Wilkenfeld/Metatheory.jl", "max_issues_repo_head_hexsha": "40d535ebe9765eca77658f090f9151ac72788455", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 62, "max_issues_repo_issues_event_min_datetime": "2021-02-12T12:39:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-11T15:47:19.000Z", "max_forks_repo_path": "src/EGraphs/saturation.jl", "max_forks_repo_name": "Wilkenfeld/Metatheory.jl", "max_forks_repo_head_hexsha": "40d535ebe9765eca77658f090f9151ac72788455", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2021-02-21T13:34:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-29T18:56:22.000Z", "avg_line_length": 27.4377990431, "max_line_length": 117, "alphanum_fraction": 0.6148748801, "num_tokens": 3103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38491215859561845, "lm_q2_score": 0.1384618030118943, "lm_q1q2_score": 0.05329563148034954}} {"text": "function isinplace_jump(p,rj)\n if p isa DiscreteProblem && p.f === DiffEqBase.DISCRETE_INPLACE_DEFAULT && rj !== nothing\n # Just a default discrete problem f, so don't use it for iip\n DiffEqBase.isinplace(rj)\n else\n DiffEqBase.isinplace(p)\n end\nend\n\n\"\"\"\n$(TYPEDEF)\n\nDefines a collection of jump processes to associate with another problem type.\n- [Documentation Page](https://diffeq.sciml.ai/stable/types/jump_types/) \n- [Tutorial\n Page](https://diffeq.sciml.ai/stable/tutorials/discrete_stochastic_example/)\n- [FAQ\n Page](https://diffeq.sciml.ai/stable/tutorials/discrete_stochastic_example/#FAQ)\n\n### Constructors\n\n`JumpProblem`s can be constructed by first building another problem type to\nwhich the jumps will be associated. For example, to simulate a collection of\njump processes for which the transition rates do not explicitly depend on time\n(called `ConstantRateJump`s or `MassActionJump`s), we must first construct a\n`DiscreteProblem`\n```julia\nprob = DiscreteProblem(u0, p, tspan)\n```\nwhere `u0` is the initial condition, `p` the parameters and `tspan` the time\nspan. If we wanted to have the jumps coupled with a system of ODEs, or have\ntransition rates with explicit time dependence, we would use an `ODEProblem`\ninstead that defines the ODE portion of the dynamics. \n\nGiven `prob` we define the jumps via\n- `JumpProblem(prob, aggregator::AbstractAggregatorAlgorithm, jumps::JumpSet ;\n kwargs...)`\n- `JumpProblem(prob, aggregator::AbstractAggregatorAlgorithm, jumps...;\n kwargs...)`\n\nHere `aggregator` specifies the underlying algorithm for calculating next jump\ntimes and types, for example `Direct`. The collection of different\n`AbstractJump` types can then be passed within a single `JumpSet` or as\nsubsequent sequential arguments. \n\n### Fields\n\n$(FIELDS)\n\n## Keyword Arguments\n- `rng`, the random number generator to use. On 1.7 and up defaults to Julia's\n builtin generator, below 1.7 uses RandomNumbers.jl's\n `Xorshifts.Xoroshiro128Star(rand(UInt64))`.\n- `save_positions=(true,true)`, specifies whether to save the system's state\n (before,after) the jump occurs. \n- `spatial_system`, for spatial problems the underlying spatial structure.\n- `hopping_constants`, for spatial problems the spatial transition rate\n coefficients.\n\nPlease see the [tutorial\npage](https://diffeq.sciml.ai/stable/tutorials/discrete_stochastic_example/) in\nthe DifferentialEquations.jl [docs](https://diffeq.sciml.ai/stable/) for usage\nexamples and commonly asked questions.\n\"\"\"\nmutable struct JumpProblem{iip,P,A,C,J<:Union{Nothing,AbstractJumpAggregator},J2,J3,J4,R} <: DiffEqBase.AbstractJumpProblem{P,J}\n \"\"\"The type of problem to couple the jumps to. For a pure jump process use `DiscreteProblem`, to couple to ODEs, `ODEProblem`, etc.\"\"\"\n prob::P\n \"\"\"The aggregator algorithm that determines the next jump times and types for `ConstantRateJump`s and `MassActionJump`s. Examples include `Direct`.\"\"\"\n aggregator::A\n \"\"\"The underlying state data associated with the chosen aggregator.\"\"\"\n discrete_jump_aggregation::J\n \"\"\"`CallBackSet` with the underlying `ConstantRate` and `VariableRate` jumps.\"\"\"\n jump_callback::C\n \"\"\"The `VariableRateJump`s.\"\"\"\n variable_jumps::J2\n \"\"\"The `RegularJump`s.\"\"\"\n regular_jump::J3\n \"\"\"The `MassActionJump`s.\"\"\"\n massaction_jump::J4\n \"\"\"The random number generator to use.\"\"\"\n rng::R\nend\nfunction JumpProblem(p::P,a::A,dj::J,jc::C,vj::J2,rj::J3,mj::J4,rng::R) where {P,A,J,C,J2,J3,J4,R}\n iip = isinplace_jump(p,rj)\n JumpProblem{iip,P,A,C,J,J2,J3,J4,R}(p,a,dj,jc,vj,rj,mj,rng)\nend\n\n# for remaking\nBase.@pure remaker_of(prob::T) where {T <: JumpProblem} = DiffEqBase.parameterless_type(T)\nfunction DiffEqBase.remake(thing::JumpProblem; kwargs...)\n T = remaker_of(thing)\n\n errmesg = \"\"\"\n JumpProblems can currently only be remade with new u0, p, tspan or prob fields. To change other fields create a new JumpProblem. Feel free to open an issue on DiffEqJump to discuss further.\n \"\"\"\n !issubset(keys(kwargs),(:u0,:p,:tspan,:prob)) && error(errmesg)\n\n if :prob ∉ keys(kwargs)\n dprob = DiffEqBase.remake(thing.prob; kwargs...)\n\n # if the parameters were changed we must remake the MassActionJump too\n if (:p ∈ keys(kwargs)) && using_params(thing.massaction_jump)\n update_parameters!(thing.massaction_jump, dprob.p; kwargs...)\n end \n else\n any(k -> k in keys(kwargs), (:u0,:p,:tspan)) && error(\"If remaking a JumpProblem you can not pass both prob and any of u0, p, or tspan.\")\n dprob = kwargs[:prob]\n\n # we can't know if p was changed, so we must remake the MassActionJump\n if using_params(thing.massaction_jump)\n update_parameters!(thing.massaction_jump, dprob.p; kwargs...)\n end \n end\n\n T(dprob, thing.aggregator, thing.discrete_jump_aggregation, thing.jump_callback,\n thing.variable_jumps, thing.regular_jump, thing.massaction_jump, thing.rng)\nend\n\nDiffEqBase.isinplace(::JumpProblem{iip}) where {iip} = iip\nJumpProblem(prob::JumpProblem) = prob\n\nJumpProblem(prob,jumps::ConstantRateJump;kwargs...) = JumpProblem(prob,JumpSet(jumps);kwargs...)\nJumpProblem(prob,jumps::VariableRateJump;kwargs...) = JumpProblem(prob,JumpSet(jumps);kwargs...)\nJumpProblem(prob,jumps::RegularJump;kwargs...) = JumpProblem(prob,JumpSet(jumps);kwargs...)\nJumpProblem(prob,jumps::MassActionJump;kwargs...) = JumpProblem(prob,JumpSet(jumps);kwargs...)\nJumpProblem(prob,jumps::AbstractJump...;kwargs...) = JumpProblem(prob,JumpSet(jumps...);kwargs...)\n\nJumpProblem(prob,aggregator::AbstractAggregatorAlgorithm,jumps::ConstantRateJump;kwargs...) = JumpProblem(prob,aggregator,JumpSet(jumps);kwargs...)\nJumpProblem(prob,aggregator::AbstractAggregatorAlgorithm,jumps::VariableRateJump;kwargs...) = JumpProblem(prob,aggregator,JumpSet(jumps);kwargs...)\nJumpProblem(prob,aggregator::AbstractAggregatorAlgorithm,jumps::RegularJump;kwargs...) = JumpProblem(prob,aggregator,JumpSet(jumps);kwargs...)\nJumpProblem(prob,aggregator::AbstractAggregatorAlgorithm,jumps::AbstractMassActionJump;kwargs...) = JumpProblem(prob,aggregator,JumpSet(jumps);kwargs...)\nJumpProblem(prob,aggregator::AbstractAggregatorAlgorithm,jumps::AbstractJump...;kwargs...) = JumpProblem(prob,aggregator,JumpSet(jumps...);kwargs...)\nJumpProblem(prob,jumps::JumpSet;kwargs...) = JumpProblem(prob,NullAggregator(),jumps;kwargs...)\n\nfunction JumpProblem(prob, aggregator::AbstractAggregatorAlgorithm, jumps::JumpSet;\n save_positions = typeof(prob) <: DiffEqBase.AbstractDiscreteProblem ? (false,true) : (true,true),\n rng = DEFAULT_RNG, scale_rates = true, useiszero = true, spatial_system=nothing, hopping_constants=nothing, kwargs...)\n\n # initialize the MassActionJump rate constants with the user parameters\n if using_params(jumps.massaction_jump) \n rates = jumps.massaction_jump.param_mapper(prob.p)\n maj = MassActionJump(rates, jumps.massaction_jump.reactant_stoch, jumps.massaction_jump.net_stoch, \n jumps.massaction_jump.param_mapper; scale_rates=scale_rates, useiszero=useiszero, \n nocopy=true)\n else\n maj = jumps.massaction_jump\n end\n\n ## Spatial jumps handling\n if spatial_system !== nothing && hopping_constants !== nothing && !is_spatial(aggregator) # check if need to flatten\n prob, maj = flatten(maj, prob, spatial_system, hopping_constants; kwargs...)\n end\n ## Constant Rate Handling\n t,end_time,u = prob.tspan[1],prob.tspan[2],prob.u0\n if (typeof(jumps.constant_jumps) <: Tuple{}) && (maj === nothing) && !is_spatial(aggregator) # check if there are no jumps\n disc = nothing\n constant_jump_callback = CallbackSet()\n else\n disc = aggregate(aggregator,u,prob.p,t,end_time,jumps.constant_jumps,maj,save_positions,rng; spatial_system = spatial_system, hopping_constants = hopping_constants, kwargs...)\n constant_jump_callback = DiscreteCallback(disc)\n end\n\n iip = isinplace_jump(prob, jumps.regular_jump)\n\n ## Variable Rate Handling\n if typeof(jumps.variable_jumps) <: Tuple{}\n new_prob = prob\n variable_jump_callback = CallbackSet()\n else\n new_prob = extend_problem(prob,jumps; rng=rng)\n variable_jump_callback = build_variable_callback(CallbackSet(),0,jumps.variable_jumps...; rng=rng)\n end\n callbacks = CallbackSet(constant_jump_callback,variable_jump_callback)\n\n JumpProblem{iip,typeof(new_prob),typeof(aggregator),typeof(callbacks),\n typeof(disc),typeof(jumps.variable_jumps),\n typeof(jumps.regular_jump),typeof(maj),typeof(rng)}(\n new_prob,aggregator,disc,\n callbacks,\n jumps.variable_jumps,\n jumps.regular_jump, maj, rng)\nend\n\nfunction extend_problem(prob::DiffEqBase.AbstractDiscreteProblem, jumps; rng=DEFAULT_RNG)\n error(\"VariableRateJumps require a continuous problem, like an ODE/SDE/DDE/DAE problem.\")\nend\n\nfunction extend_problem(prob::DiffEqBase.AbstractODEProblem,jumps; rng=DEFAULT_RNG)\n function jump_f(du::ExtendedJumpArray,u::ExtendedJumpArray,p,t)\n prob.f(du.u,u.u,p,t)\n update_jumps!(du,u,p,t,length(u.u),jumps.variable_jumps...)\n end \n ttype = eltype(prob.tspan)\n u0 = ExtendedJumpArray(prob.u0,[-randexp(rng,ttype) for i in 1:length(jumps.variable_jumps)])\n remake(prob,f=ODEFunction{true}(jump_f),u0=u0)\nend\n\nfunction extend_problem(prob::DiffEqBase.AbstractSDEProblem,jumps; rng=DEFAULT_RNG)\n function jump_f(du,u,p,t)\n prob.f(du.u,u.u,p,t)\n update_jumps!(du,u,p,t,length(u.u),jumps.variable_jumps...)\n end\n\n if prob.noise_rate_prototype === nothing\n jump_g = function (du,u,p,t)\n prob.g(du.u,u.u,p,t)\n end\n else\n jump_g = function (du,u,p,t)\n prob.g(du,u.u,p,t)\n end\n end\n\n ttype = eltype(prob.tspan)\n u0 = ExtendedJumpArray(prob.u0,[-randexp(rng,ttype) for i in 1:length(jumps.variable_jumps)])\n remake(prob,f=SDEFunction{true}(jump_f,jump_g),g=jump_g,u0=u0)\nend\n\nfunction extend_problem(prob::DiffEqBase.AbstractDDEProblem,jumps; rng=DEFAULT_RNG)\n jump_f = function (du,u,h,p,t)\n prob.f(du.u,u.u,h,p,t)\n update_jumps!(du,u,p,t,length(u.u),jumps.variable_jumps...)\n end\n ttype = eltype(prob.tspan)\n u0 = ExtendedJumpArray(prob.u0,[-randexp(rng,ttype) for i in 1:length(jumps.variable_jumps)])\n ramake(prob,f=DDEFunction{true}(jump_f),u0=u0)\nend\n\n# Not sure if the DAE one is correct: Should be a residual of sorts\nfunction extend_problem(prob::DiffEqBase.AbstractDAEProblem,jumps; rng=DEFAULT_RNG)\n jump_f = function (out,du,u,p,t)\n prob.f(out.u,du.u,u.u,t)\n update_jumps!(du,u,t,length(u.u),jumps.variable_jumps...)\n end\n ttype = eltype(prob.tspan)\n u0 = ExtendedJumpArray(prob.u0,[-randexp(rng,ttype) for i in 1:length(jumps.variable_jumps)])\n remake(prob,f=DAEFunction{true}(jump_f),u0=u0)\nend\n\nfunction build_variable_callback(cb,idx,jump,jumps...; rng=DEFAULT_RNG)\n idx += 1\n condition = function (u,t,integrator)\n u.jump_u[idx]\n end\n affect! = function (integrator)\n jump.affect!(integrator)\n integrator.u.jump_u[idx] = -randexp(rng,typeof(integrator.t)) \n end\n new_cb = ContinuousCallback(condition,affect!;\n idxs = jump.idxs,\n rootfind = jump.rootfind,\n interp_points = jump.interp_points,\n save_positions = jump.save_positions,\n abstol = jump.abstol,\n reltol = jump.reltol)\n build_variable_callback(CallbackSet(cb,new_cb),idx,jumps...; rng=DEFAULT_RNG)\nend\n\nfunction build_variable_callback(cb,idx,jump; rng=DEFAULT_RNG)\n idx += 1\n condition = function (u,t,integrator)\n u.jump_u[idx]\n end\n affect! = function (integrator)\n jump.affect!(integrator)\n integrator.u.jump_u[idx] = -randexp(rng,typeof(integrator.t))\n end\n new_cb = ContinuousCallback(condition,affect!;\n idxs = jump.idxs,\n rootfind = jump.rootfind,\n interp_points = jump.interp_points,\n save_positions = jump.save_positions,\n abstol = jump.abstol,\n reltol = jump.reltol)\n CallbackSet(cb,new_cb)\nend\n\naggregator(jp::JumpProblem{P,A,C,J,J2}) where {P,A,C,J,J2} = A\n\n@inline function extend_tstops!(tstops,jp::JumpProblem{P,A,C,J,J2}) where {P,A,C,J,J2}\n !(typeof(jp.jump_callback.discrete_callbacks) <: Tuple{}) && push!(tstops,jp.jump_callback.discrete_callbacks[1].condition.next_jump_time)\nend\n\n@inline function update_jumps!(du,u,p,t,idx,jump)\n idx += 1\n du[idx] = jump.rate(u.u,p,t)\nend\n\n@inline function update_jumps!(du,u,p,t,idx,jump,jumps...)\n idx += 1\n du[idx] = jump.rate(u.u,p,t)\n update_jumps!(du,u,p,t,idx,jumps...)\nend\n\n\n### Displays\nnum_constant_rate_jumps(aggregator::AbstractSSAJumpAggregator) = length(aggregator.rates)\n\nBase.summary(io::IO, prob::JumpProblem) = string(DiffEqBase.parameterless_type(prob),\" with problem \",DiffEqBase.parameterless_type(prob.prob),\" and aggregator \",typeof(prob.aggregator))\nfunction Base.show(io::IO, mime::MIME\"text/plain\", A::JumpProblem)\n println(io,summary(A))\n println(io,\"Number of constant rate jumps: \",A.discrete_jump_aggregation === nothing ? 0 : num_constant_rate_jumps(A.discrete_jump_aggregation))\n println(io,\"Number of variable rate jumps: \",length(A.variable_jumps))\n if A.regular_jump !== nothing\n println(io,\"Have a regular jump\")\n end\n if (A.massaction_jump !== nothing) && (get_num_majumps(A.massaction_jump) > 0)\n println(io,\"Have a mass action jump\")\n end\nend\n\nTreeViews.hastreeview(x::JumpProblem) = true\n", "meta": {"hexsha": "c34c160a10c006fd1ac7dd098fe568925a8864c1", "size": 13498, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/problem.jl", "max_stars_repo_name": "JuliaDiffEq/JumpDiffEq.jl", "max_stars_repo_head_hexsha": "d150ace322fbb16b37af9f24988013fafb45d04d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2017-02-18T18:37:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-21T18:44:34.000Z", "max_issues_repo_path": "src/problem.jl", "max_issues_repo_name": "JuliaDiffEq/DiffEqJump.jl", "max_issues_repo_head_hexsha": "d150ace322fbb16b37af9f24988013fafb45d04d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 68, "max_issues_repo_issues_event_min_datetime": "2017-02-09T06:38:26.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-24T17:51:48.000Z", "max_forks_repo_path": "src/problem.jl", "max_forks_repo_name": "JuliaDiffEq/JumpDiffEq.jl", "max_forks_repo_head_hexsha": "d150ace322fbb16b37af9f24988013fafb45d04d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16, "max_forks_repo_forks_event_min_datetime": "2017-02-08T17:11:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:36:36.000Z", "avg_line_length": 43.124600639, "max_line_length": 191, "alphanum_fraction": 0.7190694918, "num_tokens": 3573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.11757212890757046, "lm_q1q2_score": 0.05329096042374859}} {"text": "# These Symata functions (symbols) translate between Symata and Julia data and expressions\n\n### JVar\n\n@sjdoc JVar \"\"\"\n JVar(x)\n\nreturn the Julia value of the Symbol that `x` evaluates to.\n\nFor example, if `a = 1` in Julia and `b = a` in Symata, then `JVar(b)` evaluates to `1`.\n\"\"\"\n\n@sjseealso_group(Jxpr, JVar)\napprules(mx::Mxpr{:JVar}) = Core.eval(Main,symname(mx[1]))\n\n### SetJ\n\n@mkapprule SetJ nargs => 2 \"\"\"\n SetJ(x,val)\n\nsets the Julia symbol `x` to `val`.\n\nVariables and functions in Symata are separate from those in Julia, ie, their table of bindings to symbols are separate.\n\"\"\"\n\nexportj(lhs::SymString) = exportj(lhs,doeval(lhs))\n## FIXME: find out what we want on the next line and do it properly.\nexportj(lhs::SymString, rhs) = Main.eval(Expr(:(=),symname(Symbol(lhs)),rhs))\nexportj(lhs::SymString, rhs::Symbol) = exportj(lhs,QuoteNode(rhs))\n@doap SetJ(lhs::SymString,rhs) = exportj(lhs,rhs)\n\n### ExportJ\n\n@mkapprule ExportJ \"\"\"\n ExportJ(x,y,...)\n\nsets the Julia symbols `x`,`y`, etc. to the Symata-value of `x`,`y`, etc.\n`ExportJ(x)` is equivalent to `SetJ(x,x)`.\n\"\"\"\n\n@doap ExportJ(vars::SymString...) = foreach(exportj, vars)\n\n### Jxpr\n\n@sjdoc Jxpr \"\"\"\n Jxpr\n\nallows embedding Julia expressions. A Jxpr is entered like this `J( expr )`.\n\n`expr` is interpreted as a Julia expression and it is wrapped expression with head `Jxpr`, which is then evaluated when\n`Jxpr` is evaluated. You never see the head `Jxpr`. For example,\n `m = J( collect(1:10) )` creates a Julia array and binds it to the Symata symbol `m`.\n\"\"\"\n\n@sjexamp( Jxpr,\n \"This creates a Julia Array{Int,1} and \\\"binds\\\" it to the Symata symbol m.\",\n (\"m = J( collect(1:3) )\",\n \"3-element Array{Int64,1}:\\n 1\\n 2\\n 3\"))\n\n@sjexamp( Jxpr,\n \"Call a Julia function\",\n (\"tf = J( time )\",\"\"),\n (\"tf()\",\"1.424287593897437e9\"))\n\n# quote, i.e. :( expr ) is parsed as a Julia expression and is wrapped as < -- we will remove this\n# Mxpr with head Jxpr. It is evaluated here.\n@mkapprule Jxpr :nodefault => true\n\n@doap function Jxpr(args...)\n local res\n for x in args\n res = eval(x)\n end\n res\nend\n\n@sjdoc J \"\"\"\n J(expr1,expr2,...)\n\nEvaluate Julia expressions `expr1`, `expr2`, ... in Julia and return the final result.\n\"\"\"\n\n@sjseealso_group(J, Compile, SymataCall)\n\n#### Unpack\n\n@sjdoc Unpack \"\"\"\n Unpack(a)\n\nunpack a Julia typed `AbstractArray` into an Symata `List` expression.\n\nOnly `1`-d is supported. If `a` is a Julia `Dict`, then a `List` of `Lists` of\nkey,value pairs is returned.\n\"\"\"\n\n@sjexamp( Unpack,\n \"This creates a List of three random Float64's.\",\n (\"Unpack( J(rand(3)) )\", \"[0.5548766917324894,0.034964001133465095,0.9122052258982192]\"))\n\n\n@mkapprule Unpack :nargs => 1\n\n@doap Unpack(a::AbstractArray) = unpacktoList(a)\n\n\"\"\"\n unpacktoList(obj::AbstractArray{T,1})\n\nConverts a Julia array to a Symata list of type `ListT`. Only one-dimensional\narrays are supported.\n\"\"\"\nfunction unpacktoList(obj)\n mx = mxpr(:List, do_unpack(obj))\n setfixed(mx)\n setcanon(mx)\n return mx\nend\ndo_unpack(obj) = copyto!(newargs(length(obj)),obj)\n\n## We copy this and change it a bit to tolistoflists in mxpr_utils\nfunction do_unpack(dict::Dict)\n args = newargs(length(dict))\n i = 0\n for (k,v) in dict\n i += 1\n args[i] = mxpr(:List,k,v)\n end\n return args\nend\n\n#### Pack\n\n@sjdoc Pack \"\"\"\n Pack(expr)\n\npack the arguments of the Symata expression `expr` into a Julia array,\nwhose element type is the minimum required to holds the arguments of `expr`.\n\"\"\"\n\n@sjexamp( Pack,\n \"This returns a Julia array of element type Int [1,2,3].\",\n (\"ClearAll(f)\",\"\"),\n (\"Pack(f(1,2,3))\",\"3-element Array{Int64,1}: [1,2,3]\"))\n\n@sjseealso_group(Pack,Unpack)\n\n\"\"\"\n typejoin_array(a::Array)\n\nreturn the typejoin of all elements in `a`.\nI saw this in Base somewhere. Probably more efficient there.\n\"\"\"\nfunction typejoin_array(a)\n length(a) == 0 && return Any\n T = typeof(a[1])\n@inbounds for i in 2:length(a)\n T = typejoin(T, typeof(a[i]))\n end\n T\nend\n\n# 1-d unpack\nfunction apprules(mx::Mxpr{:Pack})\n a = margs(margs(mx)[1])\n T = typejoin_array(a)\n do_pack(T,a)\nend\n\ndo_pack(T,sjobj) = copyto!(Array{T}(undef, length(sjobj)), sjobj)\n\n#### Translate Symata to Julia\n\n##\n# Wrap Expr to prevent Symata from evaluating it.\n\nabstract type AbstractMtoE end\n\nmutable struct MtoECompile <: AbstractMtoE\nend\n\nmutable struct MtoEPlain <: AbstractMtoE\nend\n\nmxpr_to_expr(x, aux::AbstractMtoE) = x\n\n# Don't really want to do this with everything !\nfunction mxpr_to_expr(s::Symbol, aux::AbstractMtoE)\n s\n# Symbol(lowercase(string(s)))\nend\n\nfunction mxpr_to_expr(s::Symbol,aux::MtoEPlain)\n Symbol(lowercase(string(s))) # only lowercase some\nend\n\n\nconst MTOJSYM_COMPILE = Dict(\n :Times => :mmul,\n :Plus => :mplus,\n :Power => :mpow,\n :Abs => :mabs,\n :Exp => :Exp # Is this necessary ?\n)\n\nmtojsym_compile(s::Symbol) = get(MTOJSYM_COMPILE, s, mtojsym(s))\n\nconst MTOJSYM_PLAIN = Dict(\n :Times => :(*),\n :Plus => :(+),\n :Power => :(^),\n :Abs => :abs,\n :E => :e\n )\n\nfunction mtojsym_plain(s::Symbol)\n Symbol(lowercase(string(get(MTOJSYM_PLAIN, s, mtojsym(s)))))\nend\n\nfunction mxpr_to_expr(mx::Mxpr,aux::MtoECompile)\n head = mtojsym_compile(mhead(mx))\n mxpr_to_expr_body(head,mx,aux)\nend\n\nfunction mxpr_to_expr(mx::Mxpr{:Power}, aux::MtoECompile)\n if mx[1] == :E\n # return Expr(:call, :Exp, margs(mx)[2:end]...)\n return Expr(:call, :Exp, [mxpr_to_expr(x,aux) for x in margs(mx)[2:end]]...)\n else\n# return Expr(:call, :mpow, margs(mx)[1:end]...)\n return Expr(:call, :mpow, [mxpr_to_expr(x,aux) for x in margs(mx)]...)\n end\nend\n\n# convert List to Julia array\nfunction mxpr_to_expr(mx::Mxpr{:List},aux::MtoECompile)\n Expr(:vect, [mxpr_to_expr(x,aux) for x in margs(mx)]...)\nend\n\nfunction mxpr_to_expr(mx::Mxpr,aux::MtoEPlain)\n head = mtojsym_plain(mhead(mx))\n mxpr_to_expr_body(head,mx,aux)\nend\n\nfunction mxpr_to_expr_body(head,mx::Mxpr,aux::AbstractMtoE)\n isempty(mx) && return :( $(head)() )\n a = margs(mx)\n a1 = mxpr_to_expr(a[1],aux)\n ex = :( $(head)($(a1)) )\n length(mx) == 1 && return ex\n for i in 2:length(a)\n push!(ex.args, mxpr_to_expr(a[i],aux))\n end\n ex\nend\n\n#### Compile\n\n\n@mkapprule Compile \"\"\"\n f = Compile(expr)\n\nconvert `expr` to a compiled function.\n\n f = Compile( [x,y,...], expr)\n\ncreate an anonymous Julia function `(x,y,...) -> expr` from Symata expression `expr` and bind\nthe result to `f`.\n\n```\nsymata> f = Compile(x^2 + y^2)\nsymata> f(3,4)\n 25\n```\n\nCompile works by creating an anonymous Julia function from the Symata expression `expr`. This anonymous\nfunction is just-in-time compiled for the arguments that it is called with.\nIf no arguments are specified, then the function signature is the sorted list of free symbols found in `expr`. Free symbols are all symbols\nthat are not bound in the Julia. More precisely, in the Symata module scope. This\nexcludes `e`, for instance. Alternatively, the arguments may be specified, for example `Compile( [x,y], expr)`.\n\nBy default `expr` is not evaluated. This works for literal expressions, such as `x^2`. If the expression must be evaluated, wrap it\nin `Evaluate`. For example\n\n```\nsymata 1> expr = x^2 + y^3\nOut(1) = x^2 + y^3\n\nsymata 2> f = Compile(Evaluate(expr))\nOut(2) = (::#1) (generic function with 1 method)\n\nsymata 3> f(2,3)\nOut(3) = 31\n```\n\"\"\"\n@doap function Compile(a::Mxpr{:List}, body)\n aux = MtoECompile()\n jexpr = Expr(:function, Expr(:tuple, [mxpr_to_expr(x, aux) for x in margs(a)]...) , mxpr_to_expr(body, aux))\n Core.eval(Main, jexpr)\nend\n\n# This is not reliable. It is not worth the complexity of fixing it, I think.\n# We require an explicit list of variables, instead.\n# We could look at Attributes, Protected, etc. and just use plain variables.\n# @doap function Compile(body)\n# aux = MtoECompile()\n# jbody = mxpr_to_expr(body,aux)\n# Core.eval(Main, Expr(:function, Expr(:tuple, freesyms(jbody)...), jbody))\n# end\n\n## NOTE: freesyms is unrelated to getfreesyms and setfreesyms\n\"\"\"\n freesyms(ex::Expr)\n\nreturn a list of Symata-unbound symbols at any depth in expression `ex`, by\nwalking through the expression. This may not be useful anymore.\n\"\"\"\nfunction freesyms(x)\n syms = Dict()\n freesyms!(x, syms)\n sort(collect(keys(syms)))\nend\n\nfunction freesyms!(ex::Expr, syms::Dict)\n a = ( ex.head == :call ? view(ex.args,2:length(ex.args)) : ex.args )\n foreach(x -> freesyms!(x,syms), a)\nend\n\n# We have been using isdefined for a long time,\n# but this is incorrect. We want isbound, which\n# checks for Symata binding.\n# Neither is correct. For instance, E is not Symata bound.\n# E is bound in Julia Main. (we did it). So, the fact\n# that this was worked for several examples, is fortuitous.\nfunction freesyms!(s::Symbol, syms)\n# if ! isdefined(Symata,s)\n if ! isbound(s)\n syms[s] = 1\n end\nend\n\nfreesyms!(x, syms) = nothing\n\n#### ToJuliaExpression\n\n@mkapprule ToJuliaExpression\n\n@doap function ToJuliaExpression(x)\n mxpr(:JuliaExpression, mxpr_to_expr(x, MtoEPlain()))\nend\n\n\"\"\"\n @symExpr(expr)\n\nSymata-evaluates `expr`, translates the result to a Julia expression, and inserts it into the surrounding code. This works\njust like any Julia macro for inserting code, except that the code is generated by evaluating a Symata expression.\n\nThe following evaluates Symata code, translates the result to Julia and uses it as the body of a Julia function.\n```\njulia> f1(z) = @symExpr Together(PolyLog(-1,z) + (1-z))\n```\n\"\"\"\nmacro symExpr(expr)\n mx = symataevaluate(expr, EvaluateJuliaSyntaxSimple())\n mx = doeval(mx)\n local ex\n if isa(mx,Mxpr{:JuliaExpression})\n ex = mx[1]\n else\n ex = mxpr_to_expr(mx, MtoECompile())\n end\n :(($(esc(ex)))) ## We need to escape this so that the code is evaluated in the correct module\nend\n\n### ToJuliaString\n\n@sjdoc ToJuliaString \"\"\"\n ToJuliaString(expr)\n\ntranslate `expr` to Julia, returning a string.\nIf the option `NoSymata => False` is given, then translated code requires `using Symata`.\nCurrently, only arithemetic, trigonometric functions, and a few other things are translated.\n\"\"\"\n@mkapprule ToJuliaString :nodefault => true :options => Dict( :NoSymata => true )\n\nprotect(:NoSymata)\n\nfunction do_ToJuliaString(mx, x; NoSymata=true)\n aux = NoSymata ? MtoEPlain() : MtoECompile()\n string(mxpr_to_expr(x, aux))\nend\n\n@mkapprule SymataCall \"\"\"\n SymataCall(var, body)\n SymataCall(varlist, body)\n\nreturn a Julia function that substitues `var` or variable in `varlist` into `body` and\nsubmits the result to the Symata evaluation sequence.\n\nThe variables are localized before writing the Julia function.\n\"\"\"\n@doap SymataCall(var::Symbol, ex::Mxpr) = wrap_symata(doeval(ex),var)\n@doap SymataCall(vars::Mxpr{:List}, ex::Mxpr) = wrap_symata(doeval(ex),vars...)\n\n\"\"\"\n f = wrap_symata(expr::Mxpr,var)\n\nreturn a Julia function that Symata-evaluates an expression when called.\n\nThe function corresponds to `f(var) = expr`.\nThis wraps `expr` in a single-argument Julia function.\n\nFirst creates a lexical scope, that is a new gensym symbol `nvar` is generated and is substituted\neverywhere in `expr` for `var`. Calling `f(x)` Symata-binds `x` to `nvar` and `expr` is\nSymata-evaluated and the result is returned.\n\n`wrap_symata` is used by `NIntegrate` and `Plot`.\n\"\"\"\nfunction wrap_symata(var0,expr0::Mxpr) # Why are arguments reversed here ? Is this ever called ?\n (var,expr) = localize_variable(var0,expr0)\n# deepunsetfixed(expr)\n function (x)\n setsymval(var,x)\n # deepunsetfixed(expr)\n # this seems wasteful. When called from NIntegrate, it is not needed. Don't know why.\n # because we needed HoldAll\n doeval(expr)\n end\nend\n\nfunction wrap_symata(expr0::Mxpr,vars0...)\n vars = Array{Symbol}(undef, length(vars0))\n expr = expr0\n for i in 1:length(vars0)\n (vars[i],expr) = localize_variable(vars0[i],expr)\n end\n deepunsetfixed(expr)\n function (args...)\n for i in 1:length(args)\n setsymval(vars[i],args[i])\n end\n deepunsetfixed(expr)\n doeval(expr)\n end\nend\n\nfunction wrap_symata(expr0::SJSym,var0)\n var0 == expr0 && return (x) -> x\n sym = get_localized_symbol(var0)\n return (sym,expr0) # this does not appear to be useful\nend\n\n\n#### CodeNative\n\n# This does not yet work. Symata evaluates the symbol `f` to\n# the function object, so we lose its name. We probably need\n# a robust way to associate the symbol with the function.\n# ... Julia numbers anonymous functions and names others.\n# we can get this information somehow\n# ok, it is string(func::Function). Then we can keep a\n# hash table of Symata symbols bound to functions.\n# ... a PITA.\n# Better to define a Julia type symfunction or something\n# that stores the function and the name.\n# we can make it callable and it passes the call to its function\n# can also do this at the Symata level.\n\n# FIXME. implement functions according to the description above.\n\n# @mkapprule CodeNative\n# @doap function CodeNative(f::Symbol, arg)\n# thetypes = (margs(args)...)\n# code_native(eval(f), thetypes)\n# end\n", "meta": {"hexsha": "d8563efbc4bab7f177f3fe130836482845938da8", "size": 13414, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/symata_julia_interface.jl", "max_stars_repo_name": "jlapeyre/Symata.jl", "max_stars_repo_head_hexsha": "bfe97c96176853d80e7fbb15f35aa9a3d3a4534f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 149, "max_stars_repo_stars_event_min_datetime": "2016-10-09T07:17:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T02:18:19.000Z", "max_issues_repo_path": "src/symata_julia_interface.jl", "max_issues_repo_name": "jlapeyre/Symata.jl", "max_issues_repo_head_hexsha": "bfe97c96176853d80e7fbb15f35aa9a3d3a4534f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 183, "max_issues_repo_issues_event_min_datetime": "2016-10-14T15:49:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-01T12:20:47.000Z", "max_forks_repo_path": "src/symata_julia_interface.jl", "max_forks_repo_name": "jlapeyre/SJulia.jl", "max_forks_repo_head_hexsha": "bfe97c96176853d80e7fbb15f35aa9a3d3a4534f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 23, "max_forks_repo_forks_event_min_datetime": "2016-10-09T07:08:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-29T10:37:49.000Z", "avg_line_length": 28.2995780591, "max_line_length": 139, "alphanum_fraction": 0.6652005368, "num_tokens": 3925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30735800417608683, "lm_q2_score": 0.17328821019878957, "lm_q1q2_score": 0.05326151843394618}} {"text": "# ------------------------------------------------------------------------------------------\n# # Julia for Data Science\n# Prepared by [@nassarhuda](https://github.com/nassarhuda)! 😃\n#\n# `Last updated on 03/Jan/2020`\n#\n# In this tutorial, we will discuss why *Julia* is the tool you want to use for your data\n# science applications.\n#\n# We will cover the following:\n# * **Data**\n# * Data processing\n# * Visualization\n#\n# ### Data: Build a strong relationship with your data.\n# Every data science task has one main ingredient, the _data_! Most likely, you want to use\n# your data to learn something new. But before the _new_ part, what about the data you\n# already have? Let's make sure you can **read** it, **store** it, and **understand** it\n# before you start using it.\n#\n# Julia makes this step really easy with data structures and packages to process the data,\n# as well as, existing functions that are readily usable on your data.\n#\n# The goal of this first part is get you acquainted with some Julia's tools to manage your\n# data.\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# First, let's download a csv file from github that we can work with.\n#\n# Note: `download` depends on external tools such as curl, wget or fetch. So you must have\n# one of these.\n# ------------------------------------------------------------------------------------------\n\nP = download(\"https://raw.githubusercontent.com/nassarhuda/easy_data/master/programming_languages.csv\",\"programminglanguages.csv\")\n\n# ------------------------------------------------------------------------------------------\n# We can use shell commands like `ls` in Julia by preceding them with a semicolon.\n# ------------------------------------------------------------------------------------------\n\n;ls\n\n# ------------------------------------------------------------------------------------------\n# And there's the *.csv file we downloaded!\n#\n# Now let's load it into Julia\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# We'll use the `DelimitedFiles` standard library package and its `readdlm()` function as\n# shown\n# below.\n#\n# (Today, the [CSV.jl](https://juliadata.github.io/CSV.jl/stable/) package is the\n# recommended way to load CSVs in Julia. We can install it via `Pkg.add()`, and load .csv\n# files using `CSV.read()`. This tutorial hasn't been updated to use CSV.jl yet.)\n# ------------------------------------------------------------------------------------------\n\n# using Pkg\n# Pkg.add(\"CSV\") # for CSV.read()\n# Pkg.add(\"DelimitedFiles\") # for readdlm\n\n# using CSV\n# P = CSV.read(\"programminglanguages.csv\",header=true)\n# or\nusing DelimitedFiles # Standard library in Base\n\n# ------------------------------------------------------------------------------------------\n# By default, `readdlm` will fill an array with the data stored in the input .csv file. If\n# we set the keyword argument `header` to `true`, we'll get a second output array for just\n# the headers.\n# ------------------------------------------------------------------------------------------\n\nP,H = readdlm(\"programminglanguages.csv\", ',', header=true)\n\nP # stores the dataset\n\nH # stores the header names\n\n# ------------------------------------------------------------------------------------------\n# Here we write our first small function.
\n# Now you can answer questions such as, \"when was language X created?\"\n# ------------------------------------------------------------------------------------------\n\nfunction language_created_year(P,language::String)\n loc = findfirst(P[:,2].==language)\n return P[loc,1]\nend\n\nlanguage_created_year(P,\"Julia\")\n\nlanguage_created_year(P,\"julia\")\n\n# ------------------------------------------------------------------------------------------\n# As expected, this will not return what you want, but thankfully, string manipulation is\n# really easy in Julia!\n# ------------------------------------------------------------------------------------------\n\nfunction language_created_year_v2(P,language::String)\n loc = findfirst(lowercase.(P[:,2]).==lowercase.(language))\n return P[loc,1]\nend\nlanguage_created_year_v2(P,\"julia\")\n\n# ------------------------------------------------------------------------------------------\n# **Reading and writing to files is really easy in Julia.**
\n#\n# You can use different delimiters with the function `readdlm`, from the `DelimitedFiles`\n# package.
\n#\n# To write to files, we can use `writedlm`.
\n#\n# Let's write this same data to a file with a different delimiter.\n# ------------------------------------------------------------------------------------------\n\nwritedlm(\"programming_languages_data.txt\", P, '-')\n\n# ------------------------------------------------------------------------------------------\n# We can now check that this worked using a shell command to glance at the file,\n# ------------------------------------------------------------------------------------------\n\n;head -10 programming_languages_data.txt\n\n# ------------------------------------------------------------------------------------------\n# and also check that we can use `readdlm` to read our new text file correctly.\n# ------------------------------------------------------------------------------------------\n\nP_new_delim = readdlm(\"programming_languages_data.txt\", '-');\nP == P_new_delim\n\n# ------------------------------------------------------------------------------------------\n# ### Dictionaries\n# Let's try to store the above data in a dictionary format!\n#\n# First, let's initialize an empty dictionary\n# ------------------------------------------------------------------------------------------\n\ndict = Dict{Integer,Vector{String}}()\n\n# ------------------------------------------------------------------------------------------\n# Here we told Julia that we want `dict` to only accept integers as keys and vectors of\n# strings as values.\n#\n# However, we could have initialized an empty dictionary without providing this information\n# (depending on our application).\n# ------------------------------------------------------------------------------------------\n\ndict2 = Dict()\n\n# ------------------------------------------------------------------------------------------\n# This dictionary takes keys and values of any type!\n#\n# Now, let's populate the dictionary with years as keys and vectors that hold all the\n# programming languages created in each year as their values.\n# ------------------------------------------------------------------------------------------\n\nfor i = 1:size(P,1)\n year,lang = P[i,:]\n \n if year in keys(dict)\n dict[year] = push!(dict[year],lang)\n else\n dict[year] = [lang]\n end\nend\n\n# ------------------------------------------------------------------------------------------\n# Now you can pick whichever year you want and find what programming languages were invented\n# in that year\n# ------------------------------------------------------------------------------------------\n\ndict[2003]\n\n# ------------------------------------------------------------------------------------------\n# ### DataFrames!\n# *Shout out to R fans!*\n# One other way to play around with data in Julia is to use a DataFrame.\n#\n# This requires loading the `DataFrames` package. Thankfully, this tutorial came with a\n# Project.toml file that specifies exactly which version of DataFrames to install...\n# ------------------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------\n# #### Project.toml files\n#\n# For this tutorial (Julia for Data Science), you may have noticed that there are files in\n# this folder called [`Project.toml`](/edit/introductory-tutorials/broader-topics-and-\n# ecosystem/intro-to-julia-for-data-science/Project.toml) and\n# [`Manifest.toml`](/edit/introductory-tutorials/broader-topics-and-ecosystem/intro-to-\n# julia-for-data-science/Manifest.toml). These are files autogenerated by Julia's package\n# manager, `Pkg`, that describe the _exact set of packages_ installed for a julia project,\n# allowing you to share your work in a perfectly reproducible way.\n#\n# Jupyter was able to detect those `.toml` files, and so this notebook was automatically\n# started with _this project activated!_ Note that this means any packages you add or remove\n# inside this notebook will only affect this \"Julia for Data Science\" _project_.\n#\n# To install all of the package dependencies used in the rest of the tutorial, you only need\n# to run this next cell (commands that start with `]` are package repl commands):\n# ------------------------------------------------------------------------------------------\n\n] instantiate\n\n# ------------------------------------------------------------------------------------------\n# You can read more about package manager commands, here:\n# https://docs.julialang.org/en/v1/stdlib/Pkg/index.html\n#\n# **Now back to DataFrames!**\n# ------------------------------------------------------------------------------------------\n\nusing DataFrames\ndf = DataFrame(year = P[:,1], language = P[:,2])\n\n# ------------------------------------------------------------------------------------------\n# You can access columns by header name, or column index.\n#\n# In this case, `df[1]` is equivalent to `df.year` or `df[!, :year]`.\n#\n# Note that if we want to index columns by header name, we precede the header name with a\n# colon. In Julia, this means that the header names are treated as *symbols*.\n# ------------------------------------------------------------------------------------------\n\ndf.year\n\n# ------------------------------------------------------------------------------------------\n# **`DataFrames` provides some handy features when dealing with data**\n#\n# First, it uses julia's \"missing\" type.\n# ------------------------------------------------------------------------------------------\n\na = missing\ntypeof(a)\n\n# ------------------------------------------------------------------------------------------\n# Let's see what happens when we try to add a \"missing\" type to a number.\n# ------------------------------------------------------------------------------------------\n\na + 1\n\n# ------------------------------------------------------------------------------------------\n# `DataFrames` provides the `describe` function, which can give you quick statistics about\n# each column in your dataframe\n# ------------------------------------------------------------------------------------------\n\ndescribe(df)\n\n# ------------------------------------------------------------------------------------------\n# ### RDatasets\n#\n# We can use RDatasets to play around with pre-existing datasets\n# ------------------------------------------------------------------------------------------\n\nusing RDatasets\niris = dataset(\"datasets\", \"iris\")\n\n# ------------------------------------------------------------------------------------------\n# Note that data loaded with `dataset` is stored as a DataFrame. 😃\n# ------------------------------------------------------------------------------------------\n\ntypeof(iris) \n\n# ------------------------------------------------------------------------------------------\n# The summary we get from `describe` on `iris` gives us a lot more information than the\n# summary on `df`!\n# ------------------------------------------------------------------------------------------\n\ndescribe(iris)\n\n# ------------------------------------------------------------------------------------------\n# ### More on Missing Values\n#\n# Julia 1.0 and beyond has native support for `missing` values. (Before Julia 1.0, this was\n# done via the DataArrays.jl package.)\n# More information on using arrays with missing values can be found\n# [in the Julia documentation](https://docs.julialang.org/en/v1/manual/missing/#Arrays-With-\n# Missing-Values-1).\n# ------------------------------------------------------------------------------------------\n\nfoods = [\"apple\", \"cucumber\", \"tomato\", \"banana\"]\ncalories = [missing,47,22,105]\ntypeof(calories)\n\nusing Statistics # julia's standard library for stats\nmean(calories)\n\n# ------------------------------------------------------------------------------------------\n# Missing values ruin everything! 😑\n#\n# Luckily we can ignore them with `skipmissing`!\n# ------------------------------------------------------------------------------------------\n\nmean(skipmissing(calories))\n\n# ------------------------------------------------------------------------------------------\n# Oh WAIT! Detour. How did I get the emoji there?\n#\n# Try this out:\n#\n# ```\n# \\:expressionless: + \n# ```\n# ------------------------------------------------------------------------------------------\n\n😑 = 0 # expressionless\n😀 = 1\n😞 = -1\n\n# ------------------------------------------------------------------------------------------\n# *Back to missing values*\n# ------------------------------------------------------------------------------------------\n\nprices = [0.85,1.6,0.8,0.6,]\n\ndataframe_calories = DataFrame(item=foods,calories=calories)\n\ndataframe_prices = DataFrame(item=foods,price=prices)\n\n# ------------------------------------------------------------------------------------------\n# We can also `join` two dataframes together\n# ------------------------------------------------------------------------------------------\n\nDF = join(dataframe_calories,dataframe_prices,on=:item)\n\n# ------------------------------------------------------------------------------------------\n# ### FileIO\n# ------------------------------------------------------------------------------------------\n\nusing FileIO\njulialogo = download(\"https://avatars0.githubusercontent.com/u/743164?s=200&v=4\",\"julialogo.png\")\n\n# ------------------------------------------------------------------------------------------\n# Again, let's check that this download worked!\n# ------------------------------------------------------------------------------------------\n\n;ls\n\n# ------------------------------------------------------------------------------------------\n#\n# Next, let's load the Julia logo, stored as a .png file\n#\n# **NOTE: You may see errors below, that certain Image packages could not be found. If so:**\n# - This is because these packages are specific to your OS, so aren't installed by default.\n# - Simply run the suggested commands to install the packages, then try again.\n# ------------------------------------------------------------------------------------------\n\n# These commands may vary depending on your operating system.\n#import Pkg; Pkg.add(\"QuartzImageIO\")\n#import Pkg; Pkg.add(\"ImageMagick\")\n\nX1 = load(\"julialogo.png\")\n\n# ------------------------------------------------------------------------------------------\n# We see here that Julia stores this logo as an array of colors.\n# ------------------------------------------------------------------------------------------\n\n@show typeof(X1);\n@show size(X1);\n\n# ------------------------------------------------------------------------------------------\n# And if we load the Images package, it will display in Jupyter as an image:\n# ------------------------------------------------------------------------------------------\n\nusing Images\n\nX1\n\n# ------------------------------------------------------------------------------------------\n# ### File types\n# In Julia, many file types are supported so you do not have to transfer a file you from\n# another language to a text file before you read it.\n#\n# *Some packages that achieve this:*\n# MAT CSV NPZ JLD FASTAIO\n#\n#\n# Let's try using MAT to write a file that stores a matrix.\n# ------------------------------------------------------------------------------------------\n\nusing MAT\n\nA = rand(5,5)\nmatfile = matopen(\"densematrix.mat\", \"w\") \nwrite(matfile, \"A\", A)\nclose(matfile)\n\n# ------------------------------------------------------------------------------------------\n# Now try opening densematrix.mat with MATLAB!\n# ------------------------------------------------------------------------------------------\n\nnewfile = matopen(\"densematrix.mat\")\nread(newfile,\"A\")\n\nnames(newfile)\n\nclose(newfile)\n\n\n", "meta": {"hexsha": "b975902b08b8e488abb28783e3395cbf0ffad001", "size": 16374, "ext": "jl", "lang": "Julia", "max_stars_repo_path": ".nbexports/introductory-tutorials/broader-topics-and-ecosystem/intro-to-julia-for-data-science/1. Julia for Data Science - Data.jl", "max_stars_repo_name": "grenkoca/JuliaTutorials", "max_stars_repo_head_hexsha": "3968e0430db77856112521522e10f7da0d7610a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 535, "max_stars_repo_stars_event_min_datetime": "2020-07-15T14:56:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T12:50:32.000Z", "max_issues_repo_path": ".nbexports/introductory-tutorials/broader-topics-and-ecosystem/intro-to-julia-for-data-science/1. Julia for Data Science - Data.jl", "max_issues_repo_name": "grenkoca/JuliaTutorials", "max_issues_repo_head_hexsha": "3968e0430db77856112521522e10f7da0d7610a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 42, "max_issues_repo_issues_event_min_datetime": "2018-02-25T22:53:47.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-14T02:15:50.000Z", "max_forks_repo_path": ".nbexports/introductory-tutorials/broader-topics-and-ecosystem/intro-to-julia-for-data-science/1. Julia for Data Science - Data.jl", "max_forks_repo_name": "grenkoca/JuliaTutorials", "max_forks_repo_head_hexsha": "3968e0430db77856112521522e10f7da0d7610a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 394, "max_forks_repo_forks_event_min_datetime": "2020-07-14T23:22:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T20:12:57.000Z", "avg_line_length": 41.1407035176, "max_line_length": 130, "alphanum_fraction": 0.4212165628, "num_tokens": 2707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398147944527615, "lm_q2_score": 0.12252320771203076, "lm_q1q2_score": 0.05317280294924798}} {"text": "### A Pluto.jl notebook ###\n# v0.12.7\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ e077ab16-22e5-11eb-15ed-5f0654bf7328\nusing Pkg, DrWatson\n\n# ╔═╡ ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\nmd\"## Listing4.01\"\n\n# ╔═╡ e75a9a06-22e5-11eb-2e36-8d4f62b830ed\nbegin\n\t@quickactivate \"StatisticsWithJuliaPlutoNotebooks\"\nend\n\n# ╔═╡ fa68607e-22e5-11eb-0558-c9a4d9f77426\nbegin\n\tf(z::Int) = begin z = 0 end\n\tf(z::Array{Int}) = begin z[1] = 0 end\nend\n\n# ╔═╡ 572972b2-22e6-11eb-1ec4-2d53fc807d03\nbegin\n\tx1 = 1\n\ttypeof(x1)\nend\n\n# ╔═╡ 5729a994-22e6-11eb-00b0-e525c9e271cb\nisimmutable(x1)\n\n# ╔═╡ 572a4444-22e6-11eb-351f-65750fcd0d5e\nText(\"Before call by value: $x1\")\n\n# ╔═╡ 57305f50-22e6-11eb-1aef-61c42e0c6363\nf(x1)\n\n# ╔═╡ 573d81bc-22e6-11eb-3b89-010224cc8027\nText(\"After call by value: $x1\")\n\n# ╔═╡ 573e105a-22e6-11eb-32cb-859417a95d32\nbegin\n\tx2 = [1]\n\ttypeof(x2)\nend\n\n# ╔═╡ 574411da-22e6-11eb-2e9e-739f51ea9fc6\nisimmutable(x2)\n\n# ╔═╡ 574ff9c8-22e6-11eb-3866-817010612a7e\nText(\"Before call by reference: $x2\")\n\n# ╔═╡ 575094b4-22e6-11eb-25b6-fb702eec82a2\nf(x2)\n\n# ╔═╡ 575b02be-22e6-11eb-29ad-3f48f1b6eae6\nText(\"After call by reference: $x2\")\n\n# ╔═╡ 475ff888-22e6-11eb-2354-09f8f40a8e12\nmd\"## End of listing4.01\"\n\n# ╔═╡ Cell order:\n# ╟─ca5fbdc8-22e5-11eb-0a60-cb0a127a3ca5\n# ╠═e077ab16-22e5-11eb-15ed-5f0654bf7328\n# ╠═e75a9a06-22e5-11eb-2e36-8d4f62b830ed\n# ╠═fa68607e-22e5-11eb-0558-c9a4d9f77426\n# ╠═572972b2-22e6-11eb-1ec4-2d53fc807d03\n# ╠═5729a994-22e6-11eb-00b0-e525c9e271cb\n# ╠═572a4444-22e6-11eb-351f-65750fcd0d5e\n# ╠═57305f50-22e6-11eb-1aef-61c42e0c6363\n# ╠═573d81bc-22e6-11eb-3b89-010224cc8027\n# ╠═573e105a-22e6-11eb-32cb-859417a95d32\n# ╠═574411da-22e6-11eb-2e9e-739f51ea9fc6\n# ╠═574ff9c8-22e6-11eb-3866-817010612a7e\n# ╠═575094b4-22e6-11eb-25b6-fb702eec82a2\n# ╠═575b02be-22e6-11eb-29ad-3f48f1b6eae6\n# ╟─475ff888-22e6-11eb-2354-09f8f40a8e12\n", "meta": {"hexsha": "e66618960afa3b9b5b69b9228fd1e5b677c5a02e", "size": 1824, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebooks/04/listing4.01.jl", "max_stars_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_stars_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2020-11-08T07:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:58:01.000Z", "max_issues_repo_path": "notebooks/04/listing4.01.jl", "max_issues_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_issues_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-07T08:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T16:16:06.000Z", "max_forks_repo_path": "notebooks/04/listing4.01.jl", "max_forks_repo_name": "pitmonticone/StatisticsWithJuliaPlutoNotebooks.jl", "max_forks_repo_head_hexsha": "47a10ee915d87dd3241d2863e47b5f9630a03409", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-11-14T05:07:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T21:05:35.000Z", "avg_line_length": 23.0886075949, "max_line_length": 51, "alphanum_fraction": 0.7319078947, "num_tokens": 1083, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.37754066879814546, "lm_q2_score": 0.1403362494900832, "lm_q1q2_score": 0.05298264148910941}} {"text": "# # Example 3: Pulse Parametrization\n\n#md # !!! tip\n#md # This example is also available as a Jupyter notebook:\n#md # [`state_to_state_parametrizations.ipynb`](@__NBVIEWER_ROOT_URL__/examples/state_to_state_parametrizations.ipynb).\n\n#md # ``\\gdef\\op#1{\\hat{#1}}``\n#md # ``\\gdef\\init{\\text{init}}``\n#md # ``\\gdef\\tgt{\\text{tgt}}``\n\n#nb # $\n#nb # \\newcommand{tr}[0]{\\operatorname{tr}}\n#nb # \\newcommand{diag}[0]{\\operatorname{diag}}\n#nb # \\newcommand{abs}[0]{\\operatorname{abs}}\n#nb # \\newcommand{pop}[0]{\\operatorname{pop}}\n#nb # \\newcommand{aux}[0]{\\text{aux}}\n#nb # \\newcommand{opt}[0]{\\text{opt}}\n#nb # \\newcommand{tgt}[0]{\\text{tgt}}\n#nb # \\newcommand{init}[0]{\\text{init}}\n#nb # \\newcommand{lab}[0]{\\text{lab}}\n#nb # \\newcommand{rwa}[0]{\\text{rwa}}\n#nb # \\newcommand{bra}[1]{\\langle#1\\vert}\n#nb # \\newcommand{ket}[1]{\\vert#1\\rangle}\n#nb # \\newcommand{Bra}[1]{\\left\\langle#1\\right\\vert}\n#nb # \\newcommand{Ket}[1]{\\left\\vert#1\\right\\rangle}\n#nb # \\newcommand{Braket}[2]{\\left\\langle #1\\vphantom{#2}\\mid{#2}\\vphantom{#1}\\right\\rangle}\n#nb # \\newcommand{op}[1]{\\hat{#1}}\n#nb # \\newcommand{Op}[1]{\\hat{#1}}\n#nb # \\newcommand{dd}[0]{\\,\\text{d}}\n#nb # \\newcommand{Liouville}[0]{\\mathcal{L}}\n#nb # \\newcommand{DynMap}[0]{\\mathcal{E}}\n#nb # \\newcommand{identity}[0]{\\mathbf{1}}\n#nb # \\newcommand{Norm}[1]{\\lVert#1\\rVert}\n#nb # \\newcommand{Abs}[1]{\\left\\vert#1\\right\\vert}\n#nb # \\newcommand{avg}[1]{\\langle#1\\rangle}\n#nb # \\newcommand{Avg}[1]{\\left\\langle#1\\right\\rangle}\n#nb # \\newcommand{AbsSq}[1]{\\left\\vert#1\\right\\vert^2}\n#nb # \\newcommand{Re}[0]{\\operatorname{Re}}\n#nb # \\newcommand{Im}[0]{\\operatorname{Im}}\n#nb # $\n\n\n# This example illustrates the parametrization of control pulses as a\n# form of amplitude constraint.\n\nusing DrWatson\n@quickactivate \"KrotovTests\"\n#-\nusing QuantumControl\nusing QuantumControl.Shapes: flattop\nusing Krotov:\n SquareParametrization,\n TanhParametrization,\n TanhSqParametrization,\n LogisticParametrization,\n LogisticSqParametrization\nusing LinearAlgebra\n\n#-\n#jl using Test; println(\"\")\nusing Plots\nPlots.default(\n linewidth = 3,\n size = (550, 300),\n legend = :top,\n foreground_color_legend = nothing,\n background_color_legend = RGBA(1, 1, 1, 0.8),\n)\n#-\n\n# ## Parametrizations\n\n# ## Symmetric Bounded Controls\n\n#-\ninclude(joinpath(@__DIR__, \"plots\", \"symmetric_parametrization_comparison.jl\")) # hide\nfig = plot_symmetric_parametrization_comparison() # hide\n#jl display(fig)\n\n# ## Positive (Bounded) Controls\n\n#-\ninclude(joinpath(@__DIR__, \"plots\", \"positive_parametrization_comparison.jl\")) # hide\nfig = plot_positive_parametrization_comparison() # hide\n#jl display(fig)\n\n# ## Two-level Hamiltonian\n\n# We consider the Hamiltonian $\\op{H}_{0} = - \\frac{\\omega}{2} \\op{\\sigma}_{z}$, representing\n# a simple qubit with energy level splitting $\\omega$ in the basis\n# $\\{\\ket{0},\\ket{1}\\}$. The control field $\\epsilon(t)$ is assumed to couple via\n# the Hamiltonian $\\op{H}_{1}(t) = \\epsilon(t) \\op{\\sigma}_{x}$ to the qubit,\n# i.e., the control field effectively drives transitions between both qubit\n# states.\n#\n# We we will use\n\nϵ(t) = 0.2 * flattop(t, T=5, t_rise=0.3, func=:blackman);\n\n\n#-\n\"\"\"Two-level-system Hamiltonian.\"\"\"\nfunction hamiltonian(Ω=1.0, ϵ=ϵ)\n σ̂_z = ComplexF64[\n 1 0\n 0 -1\n ]\n σ̂_x = ComplexF64[\n 0 1\n 1 0\n ]\n Ĥ₀ = -0.5 * Ω * σ̂_z\n Ĥ₁ = σ̂_x\n return (Ĥ₀, (Ĥ₁, ϵ))\nend;\n#-\n\nH = hamiltonian();\n#jl @test length(H) == 2\n\n# The control field here switches on from zero at $t=0$ to it's maximum amplitude\n# 0.2 within the time period 0.3 (the switch-on shape is half a [Blackman pulse](https://en.wikipedia.org/wiki/Window_function#Blackman_window)).\n# It switches off again in the time period 0.3 before the\n# final time $T=5$). We use a time grid with 500 time steps between 0 and $T$:\n\ntlist = collect(range(0, 5, length=500));\n\n#-\nfunction plot_control(pulse::Vector, tlist)\n plot(tlist, pulse, xlabel=\"time\", ylabel=\"amplitude\", legend=false)\nend\n\nplot_control(ϵ::T, tlist) where {T<:Function} = plot_control([ϵ(t) for t in tlist], tlist)\n\nplot_control(H[2][2], tlist)\n\n# ## Optimization target\n\n# The `krotov` package requires the goal of the optimization to be described by a\n# list of `Objective` instances. In this example, there is only a single\n# objective: the state-to-state transfer from initial state $\\ket{\\Psi_{\\init}} =\n# \\ket{0}$ to the target state $\\ket{\\Psi_{\\tgt}} = \\ket{1}$, under the dynamics\n# of the Hamiltonian $\\op{H}(t)$:\n\nfunction ket(label)\n result = Dict(\"0\" => Vector{ComplexF64}([1, 0]), \"1\" => Vector{ComplexF64}([0, 1]),)\n return result[string(label)]\nend;\n\n#-\n#jl @test dot(ket(0), ket(1)) ≈ 0\n#-\n\nobjectives = [Objective(initial_state=ket(0), generator=H, target_state=ket(1))]\n\n#-\n#jl @test length(objectives) == 1\n#-\n\n\n# ## Square-parametrization for positive pulses\n\n\nproblem = ControlProblem(\n objectives=objectives,\n pulse_options=IdDict(\n ϵ => Dict(\n :lambda_a => 5,\n :update_shape => t -> flattop(t, T=5, t_rise=0.3, func=:blackman),\n :parametrization => SquareParametrization(),\n )\n ),\n tlist=tlist,\n iter_stop=50,\n J_T=QuantumControl.Functionals.J_T_ss,\n check_convergence=res -> begin\n ((res.J_T < 1e-3) && (res.converged = true) && (res.message = \"J_T < 10⁻³\"))\n end\n);\n#-\nopt_result_positive, file = @optimize_or_load(\n datadir(),\n problem;\n method=:krotov,\n filename=\"parametrization#opt_result_positive.jld2\"\n);\n#-\nopt_result_positive\n\n# We can plot the optimized field:\n\n#-\n#!jl plot_control(opt_result_positive.optimized_controls[1], tlist)\n#-\n\n#-\n#jl @test minimum(opt_result_positive.optimized_controls[1]) ≥ 0.0\n#jl @test minimum(opt_result_positive.optimized_controls[1]) < 1e-16\n#jl @test maximum(opt_result_positive.optimized_controls[1]) > 0.0\n#-\n\n# ## Tanh-Square-Parametrization for positive amplitude-constrained pulses\n\n\nproblem_tanhsq = ControlProblem(\n objectives=objectives,\n pulse_options=IdDict(\n ϵ => Dict(\n :lambda_a => 10,\n :update_shape => t -> flattop(t, T=5, t_rise=0.3, func=:blackman),\n :parametrization => TanhSqParametrization(3),\n )\n ),\n tlist=tlist,\n iter_stop=50,\n J_T=QuantumControl.Functionals.J_T_ss,\n check_convergence=res -> begin\n ((res.J_T < 1e-3) && (res.converged = true) && (res.message = \"J_T < 10⁻³\"))\n end\n);\n#-\nopt_result_tanhsq, file = @optimize_or_load(\n datadir(),\n problem_tanhsq;\n method=:krotov,\n filename=\"parametrization#opt_result_tanhsq.jld2\"\n);\n#-\nopt_result_tanhsq\n\n# We can plot the optimized field:\n\n#-\n#!jl plot_control(opt_result_tanhsq.optimized_controls[1], tlist)\n#-\n\n#-\n#jl @test minimum(opt_result_tanhsq.optimized_controls[1]) ≥ 0.0\n#jl @test minimum(opt_result_tanhsq.optimized_controls[1]) < 1e-16\n#jl @test maximum(opt_result_tanhsq.optimized_controls[1]) > 0.0\n#jl @test maximum(opt_result_tanhsq.optimized_controls[1]) < 3.0\n#-\n\n# ## Logistic-Square-Parametrization for positive amplitude-constrained pulses\n\nproblem_logisticsq = ControlProblem(\n objectives=objectives,\n pulse_options=IdDict(\n ϵ => Dict(\n :lambda_a => 1,\n :update_shape => t -> flattop(t, T=5, t_rise=0.3, func=:blackman),\n :parametrization => LogisticSqParametrization(3, k=1.0),\n )\n ),\n tlist=tlist,\n iter_stop=50,\n J_T=QuantumControl.Functionals.J_T_ss,\n check_convergence=res -> begin\n ((res.J_T < 1e-3) && (res.converged = true) && (res.message = \"J_T < 10⁻³\"))\n end\n);\n#-\nopt_result_logisticsq, file = @optimize_or_load(\n datadir(),\n problem_logisticsq;\n method=:krotov,\n filename=\"parametrization#opt_result_logisticsq.jld2\"\n);\n# We can plot the optimized field:\n\n#-\n#!jl plot_control(opt_result_logisticsq.optimized_controls[1], tlist)\n#-\n\n#-\n#jl @test minimum(opt_result_logisticsq.optimized_controls[1]) ≥ 0.0\n#jl @test minimum(opt_result_logisticsq.optimized_controls[1]) < 1e-16\n#jl @test maximum(opt_result_logisticsq.optimized_controls[1]) > 0.0\n#jl @test maximum(opt_result_logisticsq.optimized_controls[1]) < 3.0\n#-\n# ## Tanh-parametrization for amplitude-constrained pulses\n\nproblem_tanh = ControlProblem(\n objectives=objectives,\n pulse_options=IdDict(\n ϵ => Dict(\n :lambda_a => 1,\n :update_shape => t -> flattop(t, T=5, t_rise=0.3, func=:blackman),\n :parametrization => TanhParametrization(-0.5, 0.5),\n )\n ),\n tlist=tlist,\n iter_stop=50,\n J_T=QuantumControl.Functionals.J_T_ss,\n check_convergence=res -> begin\n ((res.J_T < 1e-3) && (res.converged = true) && (res.message = \"J_T < 10⁻³\"))\n end\n);\n#-\nopt_result_tanh, file = @optimize_or_load(\n datadir(),\n problem_tanh;\n method=:krotov,\n filename=\"parametrization#opt_result_tanh.jld2\"\n);\n#-\n#!jl plot_control(opt_result_tanh.optimized_controls[1], tlist)\n#-\n#jl @test minimum(opt_result_tanh.optimized_controls[1]) > -0.5\n#jl @test maximum(opt_result_tanh.optimized_controls[1]) < 0.5\n#-\n", "meta": {"hexsha": "34e4c88f6b1a624c89744159616694ce457cf13a", "size": 9108, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/state_to_state_parametrizations.jl", "max_stars_repo_name": "JuliaQuantumControl/Krotov.jl", "max_stars_repo_head_hexsha": "6eab22b1d2e084210ecaf7fe32fcf28a2183be83", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-11-13T03:01:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T00:52:11.000Z", "max_issues_repo_path": "examples/state_to_state_parametrizations.jl", "max_issues_repo_name": "JuliaQuantumControl/Krotov.jl", "max_issues_repo_head_hexsha": "6eab22b1d2e084210ecaf7fe32fcf28a2183be83", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2021-10-02T04:17:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T01:52:40.000Z", "max_forks_repo_path": "examples/state_to_state_parametrizations.jl", "max_forks_repo_name": "JuliaQuantumControl/Krotov.jl", "max_forks_repo_head_hexsha": "6eab22b1d2e084210ecaf7fe32fcf28a2183be83", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-10T00:52:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T00:52:12.000Z", "avg_line_length": 29.1923076923, "max_line_length": 145, "alphanum_fraction": 0.66523935, "num_tokens": 2960, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.10669059749614017, "lm_q1q2_score": 0.05292854708040067}} {"text": "### A Pluto.jl notebook ###\n# v0.12.16\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ 9dfa6a82-3b9d-11eb-2557-3bb72249910a\nusing PaddedViews\n\n# ╔═╡ 97dcb6ca-3b9b-11eb-2c96-0904d9a90046\ns=\"\"\"L.LL.LL.LL\nLLLLLLL.LL\nL.L.L..L..\nLLLL.LL.LL\nL.LL.LL.LL\nL.LLLLL.LL\n..L.L.....\nLLLLLLLLLL\nL.LLLLLL.L\nL.LLLLL.LL\"\"\"\n\n# ╔═╡ 1501f7ee-3ba3-11eb-2b57-7b10a8d1d5d4\nsbig=\"\"\"LLLLLLLLLLLLLLLLLLLLLLL.LLLLLLL.L.LLLLL.LLLL.LLLLLLLLL..LLL.LLLLLLLLLLLLLL.LLLLLLLLL.LLL.LLLLLL\nLLLLLLLLLL.L.LLLLLLL.LL.LLLLLLL.LLLLLLLL.LLLLLLLLLLLLL.LLLLLLLLLLL.LLLLLLLL.LLLLLLLLLLLL.LLLLLL\nLLLLLLLL.L.LLLLLLLLLLLL.LLLLLLL.LLLLLL.LLLLL.LLLLLLLLL.LLLLLLLLLLL.LLLLLLLLLLLLLLLL.LLLL.LLLLLL\n.LLLLLLLLLLLLLLLLL.LLLL.LLLLLLL.LLLLLL.LLLLL.LLL.LLLLLLLLLL.LLLLLL.LLLLLLLL.LLLLLL.LLLLL.LLLLLL\nLLLLLLLLLLLLLLLLLLLLLLL.LLLLLLL.LLL.LLLLL.LL.LLLLLLLLL.LLLL.LLLLLL.LLLLLLLL.LLLLLLL.LLLL.LLLLLL\nLLL.LL..L..L.LL.L.L........L.............LLL....LL...L..L.L.....L..L.L.......L..L......LLLL.L.L\nLLLLLLLLLLLLLLLLL..LLLL.LLLLLLL.LLLLLL.LLLLL.LLLLLLLLL.LLLL.LLLLLLLLLLLLLLL.LLLLLLL.LLLLL.LLLLL\nLLLLLLLLLL.LLLL.LL.LLLL.LLLLLLLLLLLLLLLLLL.L.LLLLLLLLL.LLLL.L.L.LL.LLLLLLLLLLLLL.LL.LLLLLLLLLLL\nLLLLLLLLLLLLLLLLL.LLLLL.LLLLLLL.LLLLLLLLLLLL.LLLLLLLLL.LLLL.LLLLLLLLLLLLLLL.LL.LLLLLLLLL.LLLLL.\nLLLLLLLLLLLLLLLLL..LLL.LLLLLLLLLLLLLLL.LLLLL.LLLLLLLLL.LLLL.LLLLLL.LLLLLLLL.LLLLLLLLLLLL.LLLLLL\nLLLLLLLLLL.LLLLLLLLLLLL.LLLLLLLLLLLLLLLLLLLL.LLLLLLLLLLLLLL.LLLL.LLLLLLLLLLLLL.LLLL.LLLLLLLLLLL\nLLLLLLLLLL.LLLLLLL.LLLLLLLLLLLL.LLLLLL.LLL.L..LLLLLLLL.LLLL.LLLLLL..LLLLLLLLLLLLLLL.LLLL.LLLLLL\nL.LLLLLLLL..LLLLLL.LLLL.LLLLLLLLLLLLLL.LLLLL.LLLLLLLLLLLLLL.LLLLLLLLL.LLLLL.LLLLLLL.LLLL.LLLLLL\n.LLLLLLLLL.LLLLLLLLLLLL.LLLLLLLLLLLLLLLLLLLLLLLLLLLLLL.LLLLLLLLLLLLLLLLLLLL.LLLLLLL.LLLLLLLLLLL\nLL.L..LL...LL..L..L.L.L.....L..LL...L.LLL......L.L...L.LL...L.L.L.........L.LL....L.LL.LL...LL.\nLLLLLLLLLLLLLLLLLLLLLLL.LLLLLLL.LLLLLLLLLLLLLLLLLLLLLL.LLLL.LLLLLL.L.LLLLLLLLLLLLLL.LLL..LLLLLL\nLLLLL.LLLL.LLLL.LLLLLLLLLLLLLLL.LLLLLL.L.LLL.LLLLLLLLL.LLLLLLLLLLLLLLLLLLLLLLLLLLLL.LLL.LLLLLLL\nLLL.LLLLLL.LLLLLLL.LLLL.LLL.LLL.LLLL.L.LL.LLLLLLLLLLLL.LLLL.LLL.LL.LLLLLLLLLLLLLLLLLLLLL.LL.LLL\nLLLLLLLLLL.LLL.LLLLLLLL.LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL.LLLLLL.LLLLLLLLLLLLLLLL.LLLL.LLLLLL\n...L...L..L.L...L..L......L.......L.L...L...L...L.....L...L...L....L...LL..L..L.............LL.\nLLL..LLLLL.LLLLLLLLLLLL.LLLLLLL.LLLLLL.LLLLLLLLLLL.LLL.LLLL.LLLLLL.LLLLLLLLLLLLLLLL.LLLLL.LLLLL\nLLLLLLLLLL.LLL..LLLLLLL.L.LLLLL.LLLLLLLLLLLL.LLLLLLLLL.LLLLLLLLLLL.LLL.LLLLLLLLLLLLLLLLLLLLLLLL\nLLLLLL.L.L.L.LLLLLLLLLL.LLLLLLL.LLLLLL.LLLLL.LLLLLLLLLLLLLL.LLLLLL.LLLLLLLL.LLLLLLL.LLLL.LLLLL.\nLLLLLL.LLL.LLLLLLLLLLLL.LLLLLLL.L.LLLLLLLLLL.LLLLLLLLL.LLLL.LLLLLL.LLL.LLLL.LLLLLLL.LLLL.LLLLL.\nLLLLLLLLLL.LLLLLLL.LLLL.LLLLLLL.LLLLLL.LLLLL.LLL.LLLLL.L.LL.LLLLLL.LLLLLLLL..LLLLLLLLLLL.LLLLLL\nLLLLLL.LLL.LLLLLLL.LLLL.LLLLLLL.LLLLLLLLLLLLLLLLLLLLLL.LLLLLLLLLLL.LLLLLLLL.LLLLLLL.LLLLLLLLLLL\nLLLLLLLLLL.LLLLLLL.LLLL.LLLLLLLLLLLLLLLLLLLL.LLLLLLLLL.LLLL.LLLLLL.LLLLLLL..LLLLLLLLL.LL.LLLLLL\nLLLLLLLLLLLLLLLLLLLLLL..LLLLLLL.LLLLLL.LLLLL.LL.LLLLLL.LLLLLLLLLLL.LLLLL.L.LLLLLLLLLLLLL.LLLLLL\nLLLLLLLLLL.LLLLLLLLLLLL.LLLLLLL.LLLLLLL.LLLL.LLLLLLLLLLLLLL.LLLLLLLLLLLLLLL.LL.LLLL.LLLL.LLLLLL\n.L......L..L........LL..LLL...LL.L.....L..L.L..LLL..LLL..LL.LL...LLL.......L...LL...........LLL\nLLLLLLLLLL.LL.LLLL.LLLL.LLLLLLL.LLLLL.LLLLLL.LLLLLLLLL.LLLLLLLLLLL.LLLLLLLL.LLLLLLLLLLLL.LLLLLL\nLLLLLLLLLLLLLLLLLL.LLLLLLLLLLLLLLLLLLLLLLLLL.LLLLL.LLL.LLLLLLLLLLL.LLLLLLLLLLLLLLLL.LLLL.LLLLLL\nLLLLLLLLLL.LLLLLLL.LLLL.LLLLLL..LLLLLL.LLLLLLLLLLLLLLL.LL.L.L.LLLLLLLLLLLLL.LLLLLLL.LLL..LLLLLL\nLLLLLL.LLL.LLLLLLL.LLLLLLLLL.LL.LLLLLL.LLLLLLLLLLLLLLL.LLLL.LLLLLL.LLL.LLLL.LLLLLLL.LLLL.LLLLLL\nLLLLLLLLLLLLLLLL.L.LLLL.LLLLLL..LLLLLLLLLLLL.LLLLLLL.L.LLLLLLLLLLL.LLLLLLLL.LLLLLLL.LLLL..LLLLL\nLLLLLLLLLL.LLLLLLL.LLLL.LLLLLLL.LLLLLLLLLLLL.LLLLLLLLLLLLLL.LLLLLL.LL.LLLLL.LL.L.LL.LLLLLLLLLLL\nLLLLLL.LLL.LLLLLLL.LLLLLLL.LLLL.LLLLLLLLLLLL.LLLLLLLLL.LLL.LLLLLLL.LLLLLLLLLLLLLLL..LLLL.LLLLLL\nLL.LLLLLLL.LLLLLLL.LLLLLLLLLLLL.LLLLLLLLLLLLL.LLLLLLLLLLLLLLLL.LLL.LLLLLLLL.LLLLLLLLLLLLLL.LLLL\nLLLLLLLLLL.LLLLLLL.LLLL.LLL.LLL.LLLLLL.LLLL..LLLLLLLLLLLLLL.LLLLLLLLLLLLLLL.LLLLLLL.LLLL.LLLLLL\n........LL.L..LLLL..L..LLLL..LLL.........L.L......LL.LL..L........L...L..LL..LLLL.L.L.....L.LL.\nLL.LLLLLLL.LLLLLLL.LLLL.LLLL.LL.LLLLLLLLLLLLLLLLLLLLLL.LLLL.LLLLL..LLLLLLLLLLLLLLLL.LLLLL.L..LL\nLLLLLLLLL.LLLLLLLL.LLL..LLLLLLL.LLLLLL.LLLLL.LLLLLLLLL.LLLL.LLLLLLLLLL.LLLL.LLLL.LLLLLLLLLLLLLL\nLL.LLLLLLL.LLLLLLL.LLLL.LLLLLLLLLLLLLL.LLLLLLLL.LLLLLLLLLLL.LLLLLL.LLLLLLL..LLL.LLLLLLLLLL.LLLL\nLLLLLLLLLLLLLLLLLLLLLLL.LLLLLLL.LLLLLLLLLLLL.LLLLLLLLL.LLLL.LLLLLL.LLL.LLL..LLLLLLL.LLLL.LLLLLL\nLLL.LLLLLL.LLLLLLLLLLLLLLLLLLLL.LLLLLL..LLL.LLLLLLLLLL.LLLL.LLLLLL.LLLLLLLLLLLLLLLL.LLLL.LLLL.L\nLLLLLLLLLL.LLLLLLL.LLLLLLLLLLLL.LLLLLL.LLLLLLLL.LLLLLLLLLLL.LLLLLL.LL.LLLL..LLLLLLLLLLLLLLLLLLL\n..LL..LLL.....LL......L..L.L.LLL........LL......LLL...L......L.LL..L.LL.LL.L.......LL....LL...L\n.LL.LLLLLLLLLLLLLL.L.LL.LLLLLLL.LLL.LL...L.L.LLLLLLLLL.LLLLLLLLLLLLL.LLLLLL.LLLLLLL.LLLL.LLLLLL\nL.LLLLLLLLLLLL.LLL.LLLL.LLLLLLL.LLLLLLLLLLLL.LLLLLLLLLLLL.LLLLLLLL.LLL.LLLL.LLL.LLL.LLLL.LLLLLL\nLLLLLLLLLL.LLLLLLL.LLLL.LLLLLLL.LLLLLLLLLLLL.LLLLLLLLL.LLL..L.LLLL.LLLLLLLL..LLL.LLLLLLL.LLLLLL\n.LLLLLLLLL.LLL.LLL.LLLL.LLL..LLLLLLLLLLLLLLLLLLLLLLLLLL.LLL.LLLLLL.LLLLLLLL.LLLLLLL.LLLL.LLLLLL\nL..L...LL...L.LL....L.LL.L..LL.L.........L.........LLLL..L.L..LL...L.L.L....LLL.....L..L.L...LL\n.LLLLLLLLL.LLLL.LL.LLLL.LLLLLLLLL.LLLL.LLLLL.LLL.LLLLL.LLLLLLLLLLL.LLLLLLLLLLLLLLLLLLLLL.LLLLLL\nLLLLLLLLLL.L..LLLL.LLLL.LLLLLLL..LLLLLLLLLLL.LLLLLLLLL.LLLL.LLLLLLLLLLLLLLL.LLLLLLLLLLLL.LLLLLL\nLLLLLLLLLL.LLLLLLL.LLLL.LLLLLLL.LLLLLL.LLLLLLLL.LLLLL.LLLLLLLLLLLL.LLLLLLLL.LLLLLLL.LL.LLLLL.LL\nLLLLLLLLLL.LLLLLLL.LLLL.LLLLLLL.LLLLLL.LLLLLLLLLLLLLLLLLLLLLLLLLLL.LLLLLLLL.LLLLLLL.LLLLLLLLLLL\nL.LLLLLLLL.LLLLLLLLLLLL.LLLL.LL..LLLLL.LLLL.LLLLLL.LLLLLLLL.LLL.LLLLLLLLLLLLLLLLL.L.LLLL.LLLLLL\nLLLLLLLLLL..LLLLLL.LLLLLLLLLLLL.L.LLLL.LLLLLLLLLLLLLLL.LLLL.LLLLLL..LL.LLLL.LLLLLLL.LLLL.LLLLLL\nLLL.LLLLLLLLLLLLLL.LLLLLLLLLLLL.LL.LLL.LLLLL.LLLLL.LLL.LLLL.LLLLLL.LL.LLLL..LLLLLLL.LLLLLLLLLLL\nLLLLLLLLLL.LLLLLLLLLLLL.LLLLLLL.LLLLLL.LLLLL.LLLLLLLL..LLLL.LLLLLLLLLLLLLLL.LLLLL.LLLLLL.LLLLLL\nL.L...L...L..L..L....L...L..LLL..L....L..LL...LLL.LL.L...L.L..L.LLL..L....L.L...LL..L..L.L..L.L\nLLLLLLLLLLLLLLLLLLLLLLLLLLLL.LLLLLLLLLLLLLLL.LLLLLLLLL.LLLL.LLLLLL.LLLLLLLL.LLLLLLL.LLLL.LLLLLL\nLLLLLLLLLLLLLLLLLL.LLLLLLLLLLLLLLLLLLLLLLLLL.LLLLLLLLL.LLLL.LLLLLLLLLLLLLLLLLLLLLLL.LLLLL.LLL.L\nLLLLLLLLLL.LLLLL.L.LLLL.LLLLLLL.LLLLLLLLLLLL.LLLLLLLLL.LLLL.LLLLLL.LLLLLLLLLLLLL.LLLL.LLLLLLLLL\nL..LLLLLLLLL.LLLLL.L.LLLLLL.LLL.LLLLLL.LLLLLLLLLLLLLLL.LLLL.LLLLLL.LL.LLLLLLLLLLLLL.LLLLLLLLLLL\nLLLLL.LLLL.LLLL.LL.LLLL.LLLLLLLLLLLLLLLLLLLL.LLLLLLLLL.LLLLLL.LL.L.LLL.LLLLLLLLL.LL.LLLL.LLLLLL\n....L....L..L.....L....L..LL....L.L..L..LL.LLL...L.....L.LLL.L.LL.....L....L.L........L.LLL....\nL.L.LL.LLL.LLLLL.L.LLLL.LLLLLLL.LLLLLL.LLLLL.LLLLLLLLL.LLLL.LLLLLLLL.LLLLLLLLLLL.LL.LLLL.LLLLLL\nLLLLLLLLL.LLLLLLLL.LLLL.LLLLLLL.LLLLLL.LLLLL.LL.LLLLLL.LLLL.LLLLLL.LLLLLLL.LLLLLLLL.LLLL.LLLLLL\nLLLLLLLLL.LL.LLLLLLLLLL.LLLL.LLLL.LLLLLLLLLLLLLLLLLLLL..LLL.L..LLL.LLL.L.LL.LLLLLL..LLLL.LLLLLL\nLLLLLLLLLL.LLLLLLL.LLLL.LLLLLLL.LLLLLL.LLLLLLLLLLLLLLLLLLLLLLLLLLL.LLLLLLLLLLLLLLLL.LLLLLLLLLLL\nLLLLLLLLLLLLLLLLLLLLLLL.LLLLLLL.LLLLLLLLLLLL.LLLLLLLLL.LLLL.LLLLLLLLLLLL.LL.LLLLLLL.LLLL.LLLLLL\n.....LL.LL.L.....LL.LL..L...L...LLLLL......L.L....LL...LLL...LLLLL..LL..L....L......L.......L.L\nLLLLLLLLLL.LLLL.LL.LLLL.L.LLLLL.LLLLLL.LL.LL.LLLLLLLLL.LLLL.LLLLLLLLLLLLLLL.LLLLLLLLLLLLLLLLLLL\nLLLLLLLLLL.LLLLLLL.LLLL.LLLLLLL.LLL.LL.LLLLL.LLLLLLLLLLLLLLLLLLLLL.LLLLLLLLLLLLLLLL.LLLLLLLLL.L\nLLLL.LLLLL.LLLLLLL.LLLL.LLLLLLL.LLLLLL.LLLLLLL.LLLLLLLLLLLLLLLLLLL.LLLLLLLL.LLLLLLLLLLLL.LLLLLL\nLLLLLLLLL..LLLLLLL.L.LL..LLLLLLLLLLLLL.LLLLL.LLLLLLLLLLLLLL.LLL.LL.LLLLLLLL.LLLL.LLLLLLLLLLLLLL\nLLLLLLLLLLLLL.LLLLLLLLL.LLLLLL..LLLLLL.LLLLL.LLLLLLLLLLL.LLLLLLLLLL.LLLLLLL.LLLLLLL.LLLLLLLLLLL\n..LLL..L..L...L..L..L.L.....L............L.....L..L....L.LL......L.....L..LLL..L.L..L..........\nLLL.LLLLLL.LLLLLLLLLLLL.LL.LLLLLLLLLLL.LLLLLL.LLLLLLL..LLLL.LLLL.L.L.LLLL.LLLLLLLLLLLLLLLLLLLLL\nLLLLLLLLLL.LLLLLLL.LLLL.LLLLLLL.LLLLLL.LL.LL.LLLLLLLLLL.LLL.LL.LLLLLLLLLLLL.LLLLLLLLLLLL.LLLLLL\n.LLLLLLLLL.LLLL.LLLLLLLLLLLLL...LL.L.LLLLLLL.LLLLLLLLLLLLLLLLLLLLL.LLLLLLLL.LLLLLLLLLL.L.LLLLLL\nLLLL.LLLLLLLLLLLLL.LLLL.LLLLLLLLLLLLLL.LLLLL.LLLLL.LLL.LLLL.LLLLLLLLLLLL.LLLLL.LLLLLLLLLLLLLLLL\nLLLLLLLLLL.LLLLLLL.LLLLLLLLLLLL.LLLLLL.LLLLL.LLLLLLLLL.LLLLL.LLL.L.LLLLLLLL.LLLLLL..LLLLLLLLLLL\n.LLLLLLLLL.LLLLLLL.LLLL.LLLLLL..LLLLLL.LLLLL.LLLLLLLLLLLLLLLLLLLLL.LLLLLLLL.LLLLLLL.LLLL.LLLLLL\n.L.....LL......L........L.L....LLL......L...L.LL...L...L..LL................L...L..L...........\nLLLLLLLLLL.LLLLLLL.LLLL.LLLL.LL.LLLLLL.LLLL..LLLLLLLLLLLLLLLLLLLLL.LLLLLLLL.LLLL.LL.LLL.LLLLLLL\nLLLLLL.LLL.LLLLLL..LLL..LLLLLL..LLLLLL.LLLL..LLLLLLLLLLLLLLLLLLLLL.LLLLLLLL.LLLLLLL..LLLLLLLLLL\nLLLLLL..LL.LLLLLLL.LLLL.LLLL.LL.LLL.LL.LLLLLLLLLLLLLLLLLLLL.LLLLLL.LLLLLLLLLLLLLLLL.LLLLLLLLLLL\nLLLLLLLLLL.LLLLLLL.LLLLLLLLLLLL.LLLLLL.LLLLLLLLLLLLLLL.LL.L.LLLLLL.L.LLLLLL.LLLLLLLLLLLLLLLL.LL\nLLLLLLLLLL.LLLLLL.LLLLLLL.LLLLL.LLLLL.LLLLLL.L.LLLLLLL.LL.LLLLLLLLLLL.LLLLLLLLLLLLL.LLLLLLLLLLL\nLLLLLLLLLL.LLLLLLL.LLLL.LLLLLLLLLLLLLL.LLLL..LLLLLLLLL.LLLLLLLLLLLLL.LLLLLL.LLLLLLL.LL.L.LLLLLL\nLLLLL.LLLL.LLLLLLL..LLLLLLLLLLL.LLLLLL.LLL.L.L.LLLLLLLLLLLL.LLLL.L.LLLLLLLL.LLLLLLL.LLLLLLLLLLL\n....LLL...LLL.....L.L...LL...L..L....LL...L.L.LLLLL....L......LLLL......L..LLLLL.L.LL...LL..LLL\nLLLLLLLLLLLLLLLLLLLLLLL.LLLLLLL.LL.LLL.LLLLL.LLLLLLLLL.LLLL.LLLLLL.LLLLLLLL.LLLLLLLLLLLL.LLLLLL\nLLLLLLLLLLLLLLLLLL.LLLLLLLLLLLL.LLLLLL.LLLLL.LLLLLLLLL.LLLL.LLLLLL.LLLLLLLLLLLLLLLL.LLLLLLLLLLL\n.LLLLLLLLL.L..LLLLLLLLLLLLLLLLL.LLLLLL.LLLL..LLLLLLLLL.LLLLLLLLLLL.LLLLLLLLLLLLLLLL.LLLLLLLLLLL\nLLLLLLLLLL.LLLLLLL.LLLL.L.L.LLLLLLLLLL.LLLLLLLLLLLLLLLLLLLL.LLLLLL.LLLLLLLL.LLL.LLLL.LLL.LLLLLL\nLLLLLLLLLLLLLLLLLL.LLLL.LLLLLLLLLLLLLLLLLLLLLLLLLLLLLL.LLLL.LLLLLL.LLLLLLLL..LLLLLL.LLLL.L.LLLL\"\"\"\n\n# ╔═╡ c06dfe28-3b9b-11eb-0e90-73b965f01cef\nres = collect.(split(sbig))\n\n# ╔═╡ f2078fda-3b9b-11eb-02f6-69faf6d6ce6b\nparsedict = Dict('L'=>0, '.'=>-1, '#'=>1)\n\n# ╔═╡ 74450896-3ba2-11eb-27f9-5f052f8bf906\nprintdict = Dict(-1 => '.', 0 => 'L', 1 => '#')\n\n# ╔═╡ 39aeaf84-3b9d-11eb-209a-15a19031a709\nstate = ((ch -> parsedict[ch]).(hcat(res...)))'\n\n# ╔═╡ 85e5c7d2-3b9d-11eb-2a71-9fff27469aa8\nfunction nextstate(state, countfn, occthreshold)\n\temptyseat = state .== 0\n\toccupied = state .> 0\n\toccneigh = countfn(state)\n\tupdate1 = (emptyseat) .& (occneigh .== 0) # 0 -> 1\n\tupdate2 = (occupied) .& (occneigh .>= occthreshold) # 1 -> 0\n\tanyupdate = (sum(update1) + sum(update2)) > 0\n\tstate + update1 - update2, anyupdate\nend\n\n# ╔═╡ 716c36ee-3b9d-11eb-02cd-59c13327fbb4\nfunction run(countfn, occthreshold; maxiter=100)\n\tmystate = state\n\tfor i=1:maxiter\n\t\tmystate, anyupdate = nextstate(mystate, countfn, occthreshold)\n\t\tif anyupdate\n\t\t\tprintln(\"Updated\")\n\t\telse\n\t\t\tprintln(\"No change after $i steps\")\n\t\t\tprintln(\"Sum:\", sum(mystate.==1))\n\t\t\tbreak\n\t\tend\n\t\t#printstate(mystate)\n\tend\n\tmystate\nend\n\n# ╔═╡ 837a6fae-3ba2-11eb-3dd4-a971f8334552\nfunction printstate(state)\n\tfor col = 1:size(state, 1)\n\t\tfor row = 1:size(state, 2)\n\t\t\tprint(printdict[state[col,row]])\n\t\tend\n\t\tprintln()\n\tend\n\tprintln()\nend\n\n# ╔═╡ eb8e5ce6-3ba6-11eb-34e1-c541043ea307\n\"\"\"\nPart 2: for each seat, count the occupancy of the next seats in each of the eight cardinal directions.\n\"\"\"\nfunction countoccupiedneighbours2(state)\n\taccum = zeros(Int64, size(state))\n\trow, col = size(state)\n\tfor i=1:row\n\t\tfor j=1:col\n\t\t\tif state[i, j] < 0\n\t\t\t\tcontinue\n\t\t\tend\n\t\t\tfor delta in (\n\t\t\t\t\t[0,1], [0,-1], [1,0], [-1,0],\n\t\t\t\t\t[1,1], [1,-1], [-1,1], [-1,-1])\n\t\t\t\tpos = [i,j] + delta\n\t\t\t\twhile ((1 <= pos[1] <= row)\n\t\t\t\t\t\t&& (1 <= pos[2] <= col)\n\t\t\t\t\t\t&& (state[pos...] < 0))\n\t\t\t\t\tpos += delta\n\t\t\t\tend\n\t\t\t\tif ((1 <= pos[1] <= row) && (1 <= pos[2] <= col))\n\t\t\t\t\tif state[pos...] == 1\n\t\t\t\t\t\taccum[i,j] += 1\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend\n\taccum\nend\n\n# ╔═╡ f89e53ea-3c7c-11eb-323b-576f7f77da00\nsum(run(countoccupiedneighbours2, 5) .== 1)\n\n# ╔═╡ 19ad6462-3b9f-11eb-056e-1b99dc5b3979\n\"\"\"\nShifts an array left or right and/or up or down and pads the empty row/column.\n\"\"\"\nfunction shiftpad(a, leftright, topbottom; v=0)\n\trow, col = size(a)\n\tif leftright == \"l\"\n\t\tyold = 1:col-1\n\t\tynew = 2:col\n\telseif leftright == \"r\"\n\t\tyold = 2:col\n\t\tynew = 1:col-1\n\telse\n\t\tyold = ynew = 1:col\n\tend\n\tif topbottom == \"t\"\n\t\txold = 1:row-1\n\t\txnew = 2:row\n\telseif topbottom == \"b\"\n\t\txold = 2:row\n\t\txnew = 1:row-1\n\telse\n\t\txold = xnew = 1:row\n\tend\n\t\t\n\tPaddedView(v, convert(Array{Int64,2}, a)[xold, yold], (1:row, 1:col), (xnew, ynew))\nend\n\n# ╔═╡ 6100b904-3b9f-11eb-1d2e-d5f8ed748767\n\"\"\"\nSums up the values in the eight neighbouring cells for a 2D array.\n\"\"\"\nfunction neighboursum(a)\n\taccum = zeros(Int64, size(a))\n\tfor lr in (\"\", \"l\", \"r\")\n\t\tfor tb in (\"\", \"t\", \"b\")\n\t\t\tif lr == \"\" && tb == \"\"\n\t\t\t\tcontinue\n\t\t\tend\n\t\t\taccum += shiftpad(a, lr, tb)\n\t\tend\n\tend\n\taccum\nend\n\n# ╔═╡ 222c5fc0-3c7c-11eb-3f59-095768dc679b\n\"\"\"\nPart 1: for each seat, count the occupied seats amongst the eight neighbouring spaces.\n\"\"\"\nfunction countoccupiedneighbours(state)\n\tneighboursum(state .> 0)\nend\n\n# ╔═╡ b5b08618-3c7c-11eb-1a95-25275bbf81af\nsum(run(countoccupiedneighbours, 4) .== 1)\n\n# ╔═╡ Cell order:\n# ╠═97dcb6ca-3b9b-11eb-2c96-0904d9a90046\n# ╟─1501f7ee-3ba3-11eb-2b57-7b10a8d1d5d4\n# ╠═c06dfe28-3b9b-11eb-0e90-73b965f01cef\n# ╠═f2078fda-3b9b-11eb-02f6-69faf6d6ce6b\n# ╟─74450896-3ba2-11eb-27f9-5f052f8bf906\n# ╠═39aeaf84-3b9d-11eb-209a-15a19031a709\n# ╠═85e5c7d2-3b9d-11eb-2a71-9fff27469aa8\n# ╠═716c36ee-3b9d-11eb-02cd-59c13327fbb4\n# ╠═b5b08618-3c7c-11eb-1a95-25275bbf81af\n# ╠═f89e53ea-3c7c-11eb-323b-576f7f77da00\n# ╠═837a6fae-3ba2-11eb-3dd4-a971f8334552\n# ╠═eb8e5ce6-3ba6-11eb-34e1-c541043ea307\n# ╠═222c5fc0-3c7c-11eb-3f59-095768dc679b\n# ╠═6100b904-3b9f-11eb-1d2e-d5f8ed748767\n# ╠═9dfa6a82-3b9d-11eb-2557-3bb72249910a\n# ╠═19ad6462-3b9f-11eb-056e-1b99dc5b3979\n", "meta": {"hexsha": "44423066f80d69f7e06f00ae34704464f78be93d", "size": 13816, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "2020/11.jl", "max_stars_repo_name": "st--/advent-of-code", "max_stars_repo_head_hexsha": "b01ca4502820c972015e940024dbd482f7bc69c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2020/11.jl", "max_issues_repo_name": "st--/advent-of-code", "max_issues_repo_head_hexsha": "b01ca4502820c972015e940024dbd482f7bc69c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2020/11.jl", "max_forks_repo_name": "st--/advent-of-code", "max_forks_repo_head_hexsha": "b01ca4502820c972015e940024dbd482f7bc69c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.9929078014, "max_line_length": 103, "alphanum_fraction": 0.7532570932, "num_tokens": 5530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782348444346736, "lm_q2_score": 0.12085322299118381, "lm_q1q2_score": 0.05291237919622346}} {"text": "\"\"\"\n frule([::RuleConfig,] (Δf, Δx...), f, x...)\n\nExpressing the output of `f(x...)` as `Ω`, return the tuple:\n\n (Ω, ΔΩ)\n\nThe second return value is the differential w.r.t. the output.\n\nIf no method matching `frule((Δf, Δx...), f, x...)` has been defined, then return `nothing`.\n\nExamples:\n\nunary input, unary output scalar function:\n\n```jldoctest frule\njulia> dself = NoTangent();\n\njulia> x = rand()\n0.8236475079774124\n\njulia> sinx, Δsinx = frule((dself, 1), sin, x)\n(0.7336293678134624, 0.6795498147167869)\n\njulia> sinx == sin(x)\ntrue\n\njulia> Δsinx == cos(x)\ntrue\n```\n\nUnary input, binary output scalar function:\n\n```jldoctest frule\njulia> sincosx, Δsincosx = frule((dself, 1), sincos, x);\n\njulia> sincosx == sincos(x)\ntrue\n\njulia> Δsincosx[1] == cos(x)\ntrue\n\njulia> Δsincosx[2] == -sin(x)\ntrue\n```\n\nNote that techically speaking julia does not have multiple output functions, just functions\nthat return a single output that is iterable, like a `Tuple`.\nSo this is actually a [`Tangent`](@ref):\n```jldoctest frule\njulia> Δsincosx\nTangent{Tuple{Float64, Float64}}(0.6795498147167869, -0.7336293678134624)\n```\n\nThe optional [`RuleConfig`](@ref) option allows specifying frules only for AD systems that\nsupport given features. If not needed, then it can be omitted and the `frule` without it\nwill be hit as a fallback. This is the case for most rules.\n\nSee also: [`rrule`](@ref), [`@scalar_rule`](@ref), [`RuleConfig`](@ref)\n\"\"\"\nfrule(ȧrgs, f, ::Vararg{Any}) = nothing\n\n# if no config is present then fallback to config-less rules\nfrule(::RuleConfig, args...) = frule(args...)\n\n# Manual fallback for keyword arguments. Usually this would be generated by\n#\n# frule(::Any, ::Vararg{Any}; kwargs...) = nothing\n#\n# However - the fallback method is so hot that we want to avoid any extra code\n# that would be required to have the automatically generated method package up\n# the keyword arguments (which the optimizer will throw away, but the compiler\n# still has to manually analyze). Manually declare this method with an\n# explicitly empty body to save the compiler that work.\nconst frule_kwfunc = Core.kwftype(typeof(frule)).instance\n(::typeof(frule_kwfunc))(::Any, ::typeof(frule), ȧrgs, f, ::Vararg{Any}) = nothing\nfunction (::typeof(frule_kwfunc))(kws::Any, ::typeof(frule), ::RuleConfig, args...)\n return frule_kwfunc(kws, frule, args...)\nend\n\n\"\"\"\n rrule([::RuleConfig,] f, x...)\n\nExpressing `x` as the tuple `(x₁, x₂, ...)` and the output tuple of `f(x...)`\nas `Ω`, return the tuple:\n\n (Ω, (Ω̄₁, Ω̄₂, ...) -> (s̄elf, x̄₁, x̄₂, ...))\n\nWhere the second return value is the the propagation rule or pullback.\nIt takes in differentials corresponding to the outputs (`x̄₁, x̄₂, ...`),\nand `s̄elf`, the internal values of the function itself (for closures)\n\nIf no method matching `rrule(f, xs...)` has been defined, then return `nothing`.\n\nExamples:\n\nunary input, unary output scalar function:\n\n```jldoctest\njulia> x = rand();\n\njulia> sinx, sin_pullback = rrule(sin, x);\n\njulia> sinx == sin(x)\ntrue\n\njulia> sin_pullback(1) == (NoTangent(), cos(x))\ntrue\n```\n\nbinary input, unary output scalar function:\n\n```jldoctest\njulia> x, y = rand(2);\n\njulia> hypotxy, hypot_pullback = rrule(hypot, x, y);\n\njulia> hypotxy == hypot(x, y)\ntrue\n\njulia> hypot_pullback(1) == (NoTangent(), (x / hypot(x, y)), (y / hypot(x, y)))\ntrue\n```\n\nThe optional [`RuleConfig`](@ref) option allows specifying rrules only for AD systems that\nsupport given features. If not needed, then it can be omitted and the `rrule` without it\nwill be hit as a fallback. This is the case for most rules.\n\nSee also: [`frule`](@ref), [`@scalar_rule`](@ref), [`RuleConfig`](@ref)\n\"\"\"\nrrule(::Any, ::Vararg{Any}) = nothing\n\n# if no config is present then fallback to config-less rules\nrrule(::RuleConfig, args...) = rrule(args...)\n\n# Manual fallback for keyword arguments. See above\nconst rrule_kwfunc = Core.kwftype(typeof(rrule)).instance\n(::typeof(rrule_kwfunc))(::Any, ::typeof(rrule), ::Any, ::Vararg{Any}) = nothing\nfunction (::typeof(rrule_kwfunc))(kws::Any, ::typeof(rrule), ::RuleConfig, args...)\n return rrule_kwfunc(kws, rrule, args...)\nend\n", "meta": {"hexsha": "0abc8120506e2cb9195abbb8f82f9643d52713d5", "size": 4118, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/rules.jl", "max_stars_repo_name": "pierre-haessig/ChainRulesCore.jl", "max_stars_repo_head_hexsha": "ea252f0651c11e1018c3fe79a6fe7e736eff71fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/rules.jl", "max_issues_repo_name": "pierre-haessig/ChainRulesCore.jl", "max_issues_repo_head_hexsha": "ea252f0651c11e1018c3fe79a6fe7e736eff71fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rules.jl", "max_forks_repo_name": "pierre-haessig/ChainRulesCore.jl", "max_forks_repo_head_hexsha": "ea252f0651c11e1018c3fe79a6fe7e736eff71fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0, "max_line_length": 92, "alphanum_fraction": 0.6918406994, "num_tokens": 1270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.11279540479169524, "lm_q1q2_score": 0.05243876093135655}} {"text": "\n@eval struct SiteType{T}\n (f::Type{<:SiteType})() = $(Expr(:new, :f))\nend\n\n# Note that the complicated definition of\n# SiteType above is a workaround for performance\n# issues when creating parameterized types\n# in Julia 1.4 and 1.5-beta. Ideally we\n# can just use the following in the future:\n# struct SiteType{T}\n# end\n\n\"\"\"\nSiteType is a parameterized type which allows\nmaking Index tags into Julia types. Use cases\ninclude overloading functions such as `op`,\n`siteinds`, and `state` which generate custom\noperators, Index arrays, and IndexVals associated\nwith Index objects having a certain tag.\n\nTo make a SiteType type, you can use the string\nmacro notation: `SiteType\"MyTag\"`\n\nTo make a SiteType value or object, you can use\nthe notation: `SiteType(\"MyTag\")`\n\nThere are currently a few built-in site types\nrecognized by `ITensors.jl`. The system is easily extensible\nby users. To add new operators to an existing site type,\nyou can follow the instructions [here](http://itensor.org/docs.cgi?vers=julia&page=formulas/sitetype_extending).\nTo create new site types, you can follow the instructions\n[here](https://itensor.org/docs.cgi?vers=julia&page=formulas/sitetype_basic) and \n[here](https://itensor.org/docs.cgi?vers=julia&page=formulas/sitetype_qns).\n\nThe current built-in site types are:\n\n- `SiteType\"S=1/2\"` (or `SiteType\"S=½\"`)\n- `SiteType\"S=1\"`\n- `SiteType\"Fermion\"`\n- `SiteType\"tJ\"`\n- `SiteType\"Electron\"`\n\n# Examples\n\nTags on indices get turned into SiteTypes internally, and then\nwe search for overloads of functions like `op` and `siteind`.\nFor example:\n```julia\njulia> s = siteind(\"S=1/2\")\n(dim=2|id=862|\"S=1/2,Site\")\n\njulia> @show op(\"Sz\", s);\nop(s, \"Sz\") = ITensor ord=2\nDim 1: (dim=2|id=862|\"S=1/2,Site\")'\nDim 2: (dim=2|id=862|\"S=1/2,Site\")\nNDTensors.Dense{Float64,Array{Float64,1}}\n 2×2\n 0.5 0.0\n 0.0 -0.5\n\njulia> @show op(\"Sx\", s);\nop(s, \"Sx\") = ITensor ord=2\nDim 1: (dim=2|id=862|\"S=1/2,Site\")'\nDim 2: (dim=2|id=862|\"S=1/2,Site\")\nNDTensors.Dense{Float64,Array{Float64,1}}\n 2×2\n 0.0 0.5\n 0.5 0.0\n\njulia> @show op(\"Sy\", s);\nop(s, \"Sy\") = ITensor ord=2\nDim 1: (dim=2|id=862|\"S=1/2,Site\")'\nDim 2: (dim=2|id=862|\"S=1/2,Site\")\nNDTensors.Dense{Complex{Float64},Array{Complex{Float64},1}}\n 2×2\n 0.0 + 0.0im -0.0 - 0.5im\n 0.0 + 0.5im 0.0 + 0.0im\n\njulia> s = siteind(\"Electron\")\n(dim=4|id=734|\"Electron,Site\")\n\njulia> @show op(\"Nup\", s);\nop(s, \"Nup\") = ITensor ord=2\nDim 1: (dim=4|id=734|\"Electron,Site\")'\nDim 2: (dim=4|id=734|\"Electron,Site\")\nNDTensors.Dense{Float64,Array{Float64,1}}\n 4×4\n 0.0 0.0 0.0 0.0\n 0.0 1.0 0.0 0.0\n 0.0 0.0 0.0 0.0\n 0.0 0.0 0.0 1.0\n```\n\nMany operators are available, for example:\n\n- `SiteType\"S=1/2\"`: `\"Sz\"`, `\"Sx\"`, `\"Sy\"`, `\"S+\"`, `\"S-\"`, ...\n- `SiteType\"Electron\"`: `\"Nup\"`, `\"Ndn\"`, `\"Nupdn\"`, `\"Ntot\"`, `\"Cup\"`, `\"Cdagup\"`, `\"Cdn\"`, `\"Cdagup\"`, `\"Sz\"`, `\"Sx\"`, `\"Sy\"`, `\"S+\"`, `\"S-\"`, ...\n- ...\n\nYou can view the source code for the internal SiteType definitions\nand operators that are defined [here](https://github.com/ITensor/ITensors.jl/tree/master/src/physics/site_types).\n\"\"\"\nSiteType(s::AbstractString) = SiteType{Tag(s)}()\n\nSiteType(t::Tag) = SiteType{t}()\n\ntag(::SiteType{T}) where {T} = T\n\nmacro SiteType_str(s)\n SiteType{Tag(s)}\nend\n\n# Keep TagType defined for backwards\n# compatibility; will be deprecated later\nconst TagType = SiteType\nmacro TagType_str(s)\n TagType{Tag(s)}\nend\n\n#---------------------------------------\n#\n# op system\n#\n#---------------------------------------\n\n@eval struct OpName{Name}\n (f::Type{<:OpName})() = $(Expr(:new, :f))\nend\n\n# Note that the complicated definition of\n# OpName above is a workaround for performance\n# issues when creating parameterized types\n# in Julia 1.4 and 1.5-beta. Ideally we\n# can just use the following in the future:\n# struct OpName{Name}\n# end\n\n\"\"\"\nOpName is a parameterized type which allows\nmaking strings into Julia types for the purpose\nof representing operator names.\nThe main use of OpName is overloading the \n`ITensors.op!` method which generates operators \nfor indices with certain tags such as \"S=1/2\".\n\nTo make a OpName type, you can use the string\nmacro notation: `OpName\"MyTag\"`. \n\nTo make an OpName value or object, you can use\nthe notation: `OpName(\"myop\")`\n\"\"\"\nOpName(s::AbstractString) = OpName{Symbol(s)}()\nOpName(s::Symbol) = OpName{s}()\nname(::OpName{N}) where {N} = N\n\nmacro OpName_str(s)\n OpName{Symbol(s)}\nend\n\n# Default implementations of op and op!\nop(::OpName, ::SiteType; kwargs...) = nothing\nop(::OpName, ::SiteType, ::Index...; kwargs...) = nothing\nop(::OpName, ::SiteType, ::SiteType,\n sitetypes_inds::Union{SiteType, Index}...; kwargs...) = nothing\nop!(::ITensor, ::OpName, ::SiteType, ::Index...; kwargs...) = nothing \nop!(::ITensor, ::OpName, ::SiteType, ::SiteType,\n sitetypes_inds::Union{SiteType, Index}...; kwargs...) = nothing \n\n# Deprecated version, for backwards compatibility\nop(::SiteType, ::Index, ::AbstractString; kwargs...) = nothing\n\nfunction _sitetypes(ts::TagSet)\n Ntags = length(ts)\n return SiteType[SiteType(ts[n]) for n in 1:Ntags]\nend\n\n_sitetypes(i::Index) = _sitetypes(tags(i))\n\n\"\"\"\n op(opname::String, s::Index; kwargs...)\n\nReturn an ITensor corresponding to the operator\nnamed `opname` for the Index `s`. The operator\nis constructed by calling an overload of either\nthe `op` or `op!` methods which take a `SiteType`\nargument that corresponds to one of the tags of\nthe Index `s` and an `OpName\"opname\"` argument\nthat corresponds to the input operator name.\n\nOperator names can be combined using the `\"*\"`\nsymbol, for example `\"S+*S-\"` or `\"Sz*Sz*Sz\"`. \nThe result is an ITensor made by forming each operator \nthen contracting them together in a way corresponding\nto the usual operator product or matrix multiplication.\n\nThe `op` system is used by the AutoMPO\nsystem to convert operator names into ITensors,\nand can be used directly such as for applying\noperators to MPS.\n\n# Example\n```julia\ns = Index(2, \"Site,S=1/2\")\nSz = op(\"Sz\", s)\n```\n\"\"\"\nfunction op(name::AbstractString,\n s::Index...;\n kwargs...)\n\n name = strip(name)\n\n # TODO: filter out only commons tags\n # if there are multiple indices\n commontags_s = commontags(s...)\n\n # Interpret operator names joined by *\n # as acting sequentially on the same site\n starpos = findfirst(\"*\", name)\n if !isnothing(starpos)\n op1 = name[1:starpos.start-1]\n op2 = name[starpos.start+1:end]\n return product(op(op1, s...; kwargs...),\n op(op2, s...; kwargs...))\n end\n\n common_stypes = _sitetypes(commontags_s)\n push!(common_stypes,SiteType(\"Generic\"))\n opn = OpName(name)\n\n\n #\n # Try calling a function of the form:\n # op(::OpName, ::SiteType, ::Index; kwargs...)\n #\n for st in common_stypes\n res = op(opn, st, s...; kwargs...)\n if !isnothing(res)\n return res\n end\n end\n\n # otherwise try calling a function of the form:\n # op!(::ITensor, ::OpName, ::SiteType, ::Index; kwargs...)\n #\n Op = emptyITensor(prime.(s)..., dag.(s)...)\n for st in common_stypes\n op!(Op, opn, st, s...; kwargs...)\n if !isempty(Op)\n return Op\n end\n end\n\n #\n # otherwise try calling a function of the form:\n # op(::OpName, ::SiteType; kwargs...)\n # which returns a Julia matrix\n #\n for st in common_stypes\n op_mat = op(opn, st; kwargs...)\n if !isnothing(op_mat)\n rs = reverse(s)\n return itensor(op_mat, prime.(rs)..., dag.(rs)...)\n end\n end\n\n if length(s) > 1\n # No overloads for common tags found. It might be a\n # case of making an operator with mixed site types,\n # searching for overloads like:\n # op(::OpName,\n # ::SiteType...,\n # ::Index...;\n # kwargs...)\n # op!(::ITensor, ::OpName,\n # ::SiteType...,\n # ::Index...;\n # kwargs...)\n stypes = _sitetypes.(s)\n\n for st in Iterators.product(stypes...)\n res = op(opn, st..., s...; kwargs...)\n if !isnothing(res)\n return res\n end\n end\n\n Op = emptyITensor(prime.(s)..., dag.(s)...)\n for st in Iterators.product(stypes...)\n op!(Op, opn, st..., s...; kwargs...)\n if !isempty(Op)\n return Op\n end\n end\n error(\"Older op interface does not support multiple indices with mixed site types. You may want to overload `op(::OpName, ::SiteType..., ::Index...)` or `op!(::ITensor, ::OpName, ::SiteType..., ::Index...) for the operator \\\"$name\\\" and Index tags $(tags.(s)).\")\n end\n\n #\n # otherwise try calling a function of the form:\n # op(::SiteType, ::Index, ::AbstractString)\n #\n # (Note: this version is for backwards compatibility\n # after version 0.1.10, and may be eventually\n # deprecated)\n #\n for st in common_stypes\n res = op(st, s[1], name; kwargs...)\n if !isnothing(res)\n return res\n end\n end\n\n throw(ArgumentError(\"Overload of \\\"op\\\" or \\\"op!\\\" functions not found for operator name \\\"$name\\\" and Index tags: $(commontags_s))\"))\nend\n\n# For backwards compatibility, version of `op`\n# taking the arguments in the other order:\nop(s::Index,\n opname::AbstractString;\n kwargs...) = op(opname, s; kwargs...)\n\n\n# To ease calling of other op overloads,\n# allow passing a string as the op name\nop(opname::AbstractString,t::SiteType) = op(OpName(opname),t)\n\n\"\"\"\n op(opname::String,sites::Vector{<:Index},n::Int; kwargs...)\n\nReturn an ITensor corresponding to the operator\nnamed `opname` for the n'th Index in the array \n`sites`.\n\n# Example\n\n```julia\ns = siteinds(\"S=1/2\", 4)\nSz2 = op(\"Sz\", s, 2)\n```\n\"\"\"\nop(opname::AbstractString, s::Vector{<:Index},\n ns::Vararg{Int, N}; kwargs...) where {N} =\n op(opname, ntuple(n -> s[ns[n]], Val(N))...; kwargs...)\n\nop(s::Vector{ <: Index}, opname::AbstractString,\n ns::Int...; kwargs...) =\n op(opname, s, ns...; kwargs...)\n\nop(s::Vector{ <: Index}, opname::AbstractString,\n ns::Tuple{Vararg{Int}}, kwargs::NamedTuple) =\n op(opname, s, ns...; kwargs...)\n\nop(s::Vector{ <: Index}, opname::AbstractString,\n ns::Int, kwargs::NamedTuple) =\n op(opname, s, ns; kwargs...)\n\n# This version helps with call like `op.(Ref(s), os)` where `os`\n# is a vector of tuples.\nop(s::Vector{ <: Index}, os::Tuple{String, Vararg}) =\n op(s, os...)\n\n# Here, Ref is used to not broadcast over the vector of indices\n# TODO: consider overloading broadcast for `op` with the example\n# here: https://discourse.julialang.org/t/how-to-broadcast-over-only-certain-function-arguments/19274/5\n# so that `Ref` isn't needed.\nops(s::Vector{ <: Index},\n os::AbstractArray{ <: Tuple{String, Vararg}}) =\n op.(Ref(s), os)\n\nops(os::Vector{ <: Tuple{String, Vararg}}, s::Vector{ <: Index}) =\n op.(Ref(s), os)\n\n#---------------------------------------\n#\n# state system\n#\n#---------------------------------------\n\n@eval struct StateName{Name}\n (f::Type{<:StateName})() = $(Expr(:new, :f))\nend\n\nStateName(s::AbstractString) = StateName{SmallString(s)}()\nStateName(s::SmallString) = StateName{s}()\nname(::StateName{N}) where {N} = N\n\nmacro StateName_str(s)\n StateName{SmallString(s)}\nend\n\nstate(::SiteType, ::StateName) = nothing\nstate(::SiteType, ::AbstractString) = nothing\n\nfunction state(s::Index,\n name::AbstractString)::IndexVal\n stypes = _sitetypes(s)\n sname = StateName(name)\n\n # Try calling state(::SiteType\"Tag\",::StateName\"Name\")\n for st in stypes\n res = state(st,sname)\n !isnothing(res) && return s(res)\n end\n\n # Try calling state(::SiteType\"Tag\",\"Name\")\n for st in stypes\n res = state(st,name)\n !isnothing(res) && return s(res)\n end\n\n throw(ArgumentError(\"Overload of \\\"state\\\" function not found for Index tags $(tags(s))\"))\nend\n\nstate(s::Index,n::Integer) = s[n]\n\nstate(sset::Vector{<:Index},j::Integer,st) = state(sset[j],st)\n\n#---------------------------------------\n#\n# siteind system\n#\n#---------------------------------------\n\nspace(st::SiteType; kwargs...) = nothing\n\nspace(st::SiteType, n::Int; kwargs...) =\n space(st; kwargs...)\n\nfunction space_error_message(st::SiteType)\n return \"Overload of \\\"space\\\",\\\"siteind\\\", or \\\"siteinds\\\" functions not found for Index tag: $(tag(st))\"\nend\n\nfunction siteind(st::SiteType; addtags = \"\", kwargs...) \n sp = space(st; kwargs...)\n isnothing(sp) && return nothing\n return Index(sp, \"Site, $(tag(st)), $addtags\")\nend\n\nfunction siteind(st::SiteType, n; kwargs...)\n s = siteind(st; kwargs...)\n !isnothing(s) && return addtags(s, \"n=$n\")\n sp = space(st, n; kwargs...)\n isnothing(sp) && error(space_error_message(st))\n return Index(sp, \"Site, $(tag(st)), n=$n\")\nend\n\nsiteind(tag::String; kwargs...) =\n siteind(SiteType(tag); kwargs...)\n\nsiteind(tag::String, n; kwargs...) =\n siteind(SiteType(tag), n; kwargs...)\n\n# Special case of `siteind` where integer (dim) provided\n# instead of a tag string\nsiteind(d::Integer,n::Integer; kwargs...) = Index(d,\"Site,n=$n\")\n\n#---------------------------------------\n#\n# siteinds system\n#\n#---------------------------------------\n\nsiteinds(::SiteType, N; kwargs...) = nothing\n\n\"\"\"\n siteinds(tag::String, N::Integer; kwargs...)\n\nCreate an array of `N` physical site indices of type `tag`.\nKeyword arguments can be used to specify quantum number conservation,\nsee the `space` function corresponding to the site type `tag` for\nsupported keyword arguments.\n\"\"\"\nfunction siteinds(tag::String,\n N::Integer; kwargs...)\n st = SiteType(tag)\n\n si = siteinds(st,N;kwargs...)\n if !isnothing(si)\n return si\n end\n\n return [siteind(st,j; kwargs...) for j=1:N]\nend\n\n\"\"\"\n siteinds(f::Function, N::Integer; kwargs...)\n\nCreate an array of `N` physical site indices where the site type at site `n` is given\nby `f(n)` (`f` should return a string).\n\"\"\"\nfunction siteinds(f::Function,\n N::Integer; kwargs...)\n [siteind(f(n),n; kwargs...) for n=1:N]\nend\n\n# Special case of `siteinds` where integer (dim)\n# provided instead of a tag string\nfunction siteinds(d::Integer,\n N::Integer; kwargs...)\n return [siteind(d,n; kwargs...) for n=1:N]\nend\n\n#---------------------------------------\n#\n# has_fermion_string system\n#\n#---------------------------------------\n\nhas_fermion_string(::OpName, ::SiteType) = nothing\n\nfunction has_fermion_string(opname::AbstractString,\n s::Index;\n kwargs...)::Bool\n opname = strip(opname)\n\n # Interpret operator names joined by *\n # as acting sequentially on the same site\n starpos = findfirst(\"*\", opname)\n if !isnothing(starpos)\n op1 = opname[1:starpos.start-1]\n op2 = opname[starpos.start+1:end]\n return xor(has_fermion_string(op1,s; kwargs...),\n has_fermion_string(op2,s; kwargs...))\n end\n\n Ntags = length(tags(s))\n stypes = _sitetypes(s)\n opn = OpName(opname)\n for st in stypes\n res = has_fermion_string(opn, st)\n !isnothing(res) && return res\n end\n return false\nend\n", "meta": {"hexsha": "a847b3508b56105bb024280c51bc2c146ef7f501", "size": 14738, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/physics/sitetype.jl", "max_stars_repo_name": "saolof/ITensors.jl", "max_stars_repo_head_hexsha": "ae84b80ef55271dca1aa39dfcd4db350c4e864e1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/physics/sitetype.jl", "max_issues_repo_name": "saolof/ITensors.jl", "max_issues_repo_head_hexsha": "ae84b80ef55271dca1aa39dfcd4db350c4e864e1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/physics/sitetype.jl", "max_forks_repo_name": "saolof/ITensors.jl", "max_forks_repo_head_hexsha": "ae84b80ef55271dca1aa39dfcd4db350c4e864e1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4962686567, "max_line_length": 266, "alphanum_fraction": 0.6327181436, "num_tokens": 4441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.11279539733570564, "lm_q1q2_score": 0.05243875746505526}} {"text": "# # GARTEUR SM-AG19 Testbed: Construction of the geometry\n\n# Source code: [`garteur_geometry_vis_tut.jl`](garteur_geometry_vis_tut.jl)\n\n# ## Description\n\n# This virtual test application is based on the test article \n# used by the GARTEUR Structures & Materials Action Group 19 \n# which organized a Round Robin exercise where 12 European laboratories \n# tested a single structure between 1995 and 1997. The benchmark structure \n# was a laboratory structure built to simulate the dynamic behaviour \n# of an aeroplane. The structure was initially built for a benchmark \n# study on experimental modal analysis conducted by the \n# Structures and Materials Action Group (SM-AG19) of the Group \n# for Aeronautical Research and Technology in EURope (GARTEUR). \n# The test-bed was designed and manufactured by ONERA, France.\n\n# ![](IMAC97photo.png)\n\n# ### References\n\n# - [GARTEUR] Ground Vibration Test Techniques, compiled by A Gravelle, GARTEUR\n# Structures & Materials Action Group 19 Technical report TP-115, 1999.\n# - [BW] Etienne Balmes, Jan R. Wright, GARTEUR GROUP ON GROUND VIBRATION\n# TESTING | RESULTS FROM THE TEST OF A SINGLE STRUCTURE BY 12 LABORATORIES IN\n# EUROPE, Proceedings of DETC'97, 1997 ASME Design Engineering Technical\n# Conferences, September 14-17, 1997, Sacramento, California.\n\n# ## Goals\n\n# - Show how to construct model from multiple connected beams.\n# - Demonstrate the use of massless connectors.\n# - Visualize the structure interactively.\n# \n\n##\n# ## Geometry of the testbed airplane.\n\n# The aluminum testbed was a rather simple structure which was reasonably\n# dynamically representative of a simple airplane structure [GARTEUR](@ref\n# References). It was composed of several beams simulating a fuselage with wings\n# and a tail. Wing tip drums allowed to adjust bending and torsion frequencies\n# similarly to airplane ones, with some very close modal frequencies. \n\n# ![](garteur-geom.png)\n\n# The script included below defines the geometry of the structure, the\n# cross-sectional properties, the connectivity, and the location of the nodes.\n\ninclude(\"garteur_geometry_tut.jl\")\n\n##\n# ## Basic visualization\n\n# Here we use the `PlotlyJS` plotting library, with some simple utilities for\n# generating geometry of beams.\nusing PlotlyJS\nusing FinEtoolsFlexBeams.VisUtilModule: plot_solid, plot_space_box, render, default_layout_3d, save_to_json\n\n# The colors are used to help distinguish between the individual parts of the model.\ncolors = [\n\"rgb(125, 155, 155)\", # 1 body\n\"rgb(125, 155, 155)\", # 2 wing\n\"rgb(125, 155, 155)\", # 3 drums\n\"rgb(125, 155, 155)\", # 4 vertical tail\n\"rgb(125, 155, 155)\", # 5 horizontal tail\n\"rgb(125, 155, 155)\", # 6 constraining plate\n\"rgb(15, 15, 155)\", # 7 massless connectors: wing beam to plate\n\"rgb(125, 15, 15)\", # 8 massless connectors: wing beam to drums\n\"rgb(125, 175, 15)\", # 9 massless connectors: fuselage to wing beam\n\"rgb(125, 175, 15)\", # 10 massless connectors: fuselage to tail\n\"rgb(15, 155, 155)\", # 11 massless connectors: sensors, point masses\n]\n\n# The geometry is defined in terms of \"traces\" (a trace is in the `PlotlyJS`\n# parlance a graphical object; it could be a curve, surface, and a lot of other\n# things). It is the name for a graphical object in `PlotlyJS`. The two points\n# below define a box, which is helpful when setting the extents of the graphics\n# display.\ntbox = plot_space_box([[-1.2 * L -1.2 * L -1.2 * L]; [+1.2 * L +1.2 * L +1.2 * L]])\n# For each finite element set in the array `fesa`, generate the graphics to\n# represent that object.\ntraces = let traces = tbox\n for fes in fesa\n labl = fes.label[1]\n tm = plot_solid(fens, fes; facecolor=colors[labl]);\n traces = cat(traces, tm; dims = 1)\n end\n traces\nend\n# The layout of the plot is defined with simple defaults.\nlayout = default_layout_3d(;width=900, height=900)\n# Next, the graphics is rendered, and may be interacted with by zooming,\n# panning, etc.\npl = render(traces; layout = layout)\n\n##\n# ## Visualizing the nodes\n\n# In order to be able to discern the nodes we will reduce the opacity of the\n# surfaces representing the beams, otherwise the nodes would be hidden by these\n# surfaces. Otherwise the geometries defined in the same way as above.\n\ntbox = plot_space_box([[-1.2 * L -1.2 * L -1.2 * L]; [+1.2 * L +1.2 * L +1.2 * L]])\ntraces = let traces = tbox\n for fes in fesa\n labl = fes.label[1]\n tm = plot_solid(fens, fes; facecolor=colors[labl], opacity = 0.3);\n traces = cat(traces, tm; dims = 1)\n end\n traces\nend\n# Next we add to the \"traces\" the graphics representing all the nodes in the\n# model as bright red dots.\nusing FinEtoolsFlexBeams.VisUtilModule: plot_nodes\ntraces = cat(traces, plot_nodes(fens; color = \"rgb(255, 15, 5)\"); dims = 1)\n\n# Finally, the graphics is presented.\nlayout = default_layout_3d(;width=900, height=900)\npl = render(traces; layout = layout)\n\ntrue", "meta": {"hexsha": "d245863253e02760cf7b2126cab4fc61263ce3f2", "size": 4921, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/tutorials/garteur_geometry_vis_tut.jl", "max_stars_repo_name": "PetrKryslUCSD/FinEtoolsFlexBeamsTutorials.jl", "max_stars_repo_head_hexsha": "970460483aa01ebcc86d6840070825752633ad8e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/src/tutorials/garteur_geometry_vis_tut.jl", "max_issues_repo_name": "PetrKryslUCSD/FinEtoolsFlexBeamsTutorials.jl", "max_issues_repo_head_hexsha": "970460483aa01ebcc86d6840070825752633ad8e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/src/tutorials/garteur_geometry_vis_tut.jl", "max_forks_repo_name": "PetrKryslUCSD/FinEtoolsFlexBeamsTutorials.jl", "max_forks_repo_head_hexsha": "970460483aa01ebcc86d6840070825752633ad8e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.3360655738, "max_line_length": 107, "alphanum_fraction": 0.7236334078, "num_tokens": 1394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.11436852165386972, "lm_q1q2_score": 0.05228205049726425}} {"text": "# Copyright (c) 2019 Arpit Bhatia and contributors #src\n# #src\n# Permission is hereby granted, free of charge, to any person obtaining a copy #src\n# of this software and associated documentation files (the \"Software\"), to deal #src\n# in the Software without restriction, including without limitation the rights #src\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #src\n# copies of the Software, and to permit persons to whom the Software is #src\n# furnished to do so, subject to the following conditions: #src\n# #src\n# The above copyright notice and this permission notice shall be included in all #src\n# copies or substantial portions of the Software. #src\n# #src\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #src\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #src\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #src\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #src\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #src\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #src\n# SOFTWARE. #src\n\n# # Variables, constraints, and objective functions\n\n# **Originally Contributed by**: Arpit Bhatia\n\n# While the last tutorial introduced you to basics of of JuMP code, this\n# tutorial will go in depth focusing on how to work with different parts of a\n# JuMP program.\n\nusing JuMP\nmodel = Model();\n\n# ## Variable basics\n\n# ### Variable bounds\n\n# All of the variables we have created till now have had a bound. We can also\n# create a free variable.\n\n@variable(model, free_x)\n\n# While creating a variable, instead of using the <= and >= syntax, we can also\n# use the `lower_bound` and `upper_bound` keyword arguments.\n\n@variable(model, keyword_x, lower_bound = 1, upper_bound = 2)\n\n# We can query whether a variable has a bound using the `has_lower_bound` and\n# `has_upper_bound` functions. The values of the bound can be obtained using the\n# `lower_bound` and `upper_bound` functions.\n\nhas_upper_bound(keyword_x)\n\n#-\n\nupper_bound(keyword_x)\n\n# Note querying the value of a bound that does not exist will result in an error.\n\ntry #hide\nlower_bound(free_x)\ncatch err; showerror(stderr, err); end #hide\n\n# JuMP also allows us to change the bounds on variable. We will learn this in\n# the problem modification tutorial.\n\n# ### [Containers](@id tutorial_variable_container)\n\n# We have already seen how to add a single variable to a model using the\n# [`@variable`](@ref) macro. Let's now look at more ways to add variables to a\n# JuMP model.\n\n# JuMP provides data structures for adding collections of variables to a model.\n# These data structures are referred to as Containers and are of three types:\n# `Arrays`, `DenseAxisArrays`, and `SparseAxisArrays`.\n\n# #### Arrays\n\n# JuMP arrays are created in a similar syntax to Julia arrays with the addition\n# of specifying that the indices start with 1. If we do not tell JuMP that the\n# indices start at 1, it will create a `DenseAxisArray` instead.\n\n@variable(model, a[1:2, 1:2])\n\n# An n-dimensional variable $x \\in {R}^n$ having a bound $l \\preceq x \\preceq u$\n# ($l, u \\in {R}^n$) is added in the following manner.\n\nn = 10\nl = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]\nu = [10; 11; 12; 13; 14; 15; 16; 17; 18; 19]\n\n@variable(model, l[i] <= x[i = 1:n] <= u[i])\n\n# Note that while working with Containers, we can also create variable bounds\n# depending upon the indices:\n\n@variable(model, y[i = 1:2, j = 1:2] >= 2i + j)\n\n# #### DenseAxisArrays\n\n# `DenseAxisArrays` are used when the required indices are not one-based integer\n# ranges. The syntax is similar except with an arbitrary vector as an index as\n# opposed to a one-based range.\n\n# An example where the indices are integers but do not start with one.\n\n@variable(model, z[i = 2:3, j = 1:2:3] >= 0)\n\n# Another example where the indices are an arbitrary vector.\n\n@variable(model, w[1:5,[\"red\", \"blue\"]] <= 1)\n\n# #### SparseAxisArrays\n\n# `SparseAxisArrays` are created when the indices do not form a rectangular set.\n# For example, this applies when indices have a dependence upon previous indices\n# (called triangular indexing).\n\n@variable(model, u[i = 1:3, j = i:5])\n\n# We can also conditionally create variables by adding a comparison check that\n# depends upon the named indices and is separated from the indices by a\n# semi-colon (;).\n\n@variable(model, v[i = 1:9; mod(i, 3) == 0])\n\n# ### Variable types\n\n# The last arguement to the `@variable` macro is usually the variable type. Here\n# we'll look at how to specifiy the variable type.\n\n# #### Integer variables\n\n# Integer optimization variables are constrained to the set $x \\in {Z}$\n\n@variable(model, integer_x, Int)\n\n# or\n\n@variable(model, integer_z, integer = true)\n\n# #### Binary variables\n\n# Binary optimization variables are constrained to the set $x \\in \\{0, 1\\}$.\n\n@variable(model, binary_x, Bin)\n\n# or\n\n@variable(model, binary_z, binary = true)\n\n# #### Semidefinite variables\n\n# JuMP also supports modeling with semidefinite variables. A square symmetric\n# matrix X is positive semidefinite if all eigenvalues are nonnegative.\n\n@variable(model, psd_x[1:2, 1:2], PSD)\n\n# We can also impose a weaker constraint that the square matrix is only\n# symmetric (instead of positive semidefinite) as follows:\n\n@variable(model, sym_x[1:2, 1:2], Symmetric)\n\n# ## Constraint basics\n\nmodel = Model()\n@variable(model, x)\n@variable(model, y)\n@variable(model, z[1:10]);\n\n# ### Constraint references\n\n# While calling the `@constraint` macro, we can also set up a constraint\n# reference. Such a referrence is useful for obtaining additional information\n# about the constraint, such as its dual solution.\n\n@constraint(model, con, x <= 4)\n\n# ### [Containers](@id tutorial_constraint_container)\n\n# Just as we had containers for variables, JuMP also provides `Arrays`,\n# `DenseAxisArrays`, and `SparseAxisArrays` for storing collections of\n# constraints. Examples for each container type are given below.\n\n# #### Arrays\n\n@constraint(model, [i = 1:3], i * x <= i + 1)\n\n# #### DenseAxisArrays\n\n@constraint(model, [i = 1:2, j = 2:3], i * x <= j + 1)\n\n# #### SparseAxisArrays\n\n@constraint(model, [i = 1:2, j = 1:2; i != j], i * x <= j + 1)\n\n# ### Constraints in a loop\n\n# We can add constraints using regular Julia loops\n\nfor i in 1:3\n @constraint(model, 6x + 4y >= 5i)\nend\n\n# or use for each loops inside the `@constraint` macro.\n\n@constraint(model, [i in 1:3], 6x + 4y >= 5i)\n\n# We can also create constraints such as $\\sum _{i = 1}^{10} z_i \\leq 1$\n\n@constraint(model, sum(z[i] for i in 1:10) <= 1)\n\n# ## Objective functions\n\n# While the recommended way to set the objective is with the [`@objective`](@ref)\n# macro, the functions [`set_objective_sense`](@ref) and [`set_objective_function`](@ref)\n# provide an equivalent lower-level interface.\n\nusing GLPK\n\nmodel = Model(GLPK.Optimizer)\n@variable(model, x >= 0)\n@variable(model, y >= 0)\nset_objective_sense(model, MOI.MIN_SENSE)\nset_objective_function(model, x + y)\n\noptimize!(model)\n\n#-\n\nobjective_value(model)\n\n# To query the objective function from a model, we use the [`objective_sense`](@ref),\n# [`objective_function`](@ref), and [`objective_function_type`](@ref) functions.\n\nobjective_sense(model)\n\n#-\n\nobjective_function(model)\n\n#-\n\nobjective_function_type(model)\n\n# # Vectorized syntax\n\n# We can also add constraints and an objective to JuMP using vectorized linear\n# algebra. We'll illustrate this by solving an LP in standard form i.e.\n\n# ```math\n# \\begin{aligned}\n# & \\min & c^T x \\\\\n# & \\;\\;\\text{s.t.} & A x = b \\\\\n# & & x \\succeq 0 \\\\\n# & & x \\in \\mathbb{R}^n\n# \\end{aligned}\n# ```\n\nvector_model = Model(GLPK.Optimizer)\n\nA= [ 1 1 9 5;\n 3 5 0 8;\n 2 0 6 13]\n\nb = [7; 3; 5]\n\nc = [1; 3; 5; 2]\n\n@variable(vector_model, x[1:4] >= 0)\n@constraint(vector_model, A * x .== b)\n@objective(vector_model, Min, c' * x)\n\noptimize!(vector_model)\n\n#-\n\nobjective_value(vector_model)\n", "meta": {"hexsha": "8dc74228e448e799955d495b6ac0a1761cc337ab", "size": 8400, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "lang/Julia/variables_constraints_objective.jl", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/Julia/variables_constraints_objective.jl", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/Julia/variables_constraints_objective.jl", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3249097473, "max_line_length": 89, "alphanum_fraction": 0.6747619048, "num_tokens": 2227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489886026626094, "lm_q2_score": 0.1259227631950178, "lm_q1q2_score": 0.05224521093119116}} {"text": "#' # MNIST: Knet.jl CNN\ninfo(\"MNIST: Knet.jl CNN example\") #jl-only\n\n#' In this tutorial we will adapt the\n#' [MNIST example](http://denizyuret.github.io/Knet.jl/latest/tutorial.html#Convolutional-neural-network-1)\n#' from [Knet.jl](https://github.com/denizyuret/Knet.jl)\n#' to utilize a custom augmentation pipeline.\n#' In order to showcase the effect that image augmentation can\n#' have on a neural network's ability to generalize, we will\n#' limit the training set to just the first 500 images (of the\n#' available 60,000!). For more information on the dataset see\n#' [^MNIST1998].\n\n#md #' !!! note\n#md #'\n#md #' This tutorial is also available as a\n#md #' [Juypter](https://jupyter.org/) notebook. You can\n#md #' find a link to the Juypter version of this tutorial\n#md #' in the top right corner of this page.\n\n#' ## Preparing the MNIST dataset\ninfo(\"Preparing the MNIST dataset\") #jl-only\n\n#' In order to access, prepare, and visualize the MNIST images we\n#' employ the help of three additional Julia packages. In the\n#' interest of time and space we will not go into great detail\n#' about their functionality. Feel free to click on their\n#' respective names to find out more information about the\n#' utility they can provide.\n#'\n#' - [MLDatasets.jl](https://github.com/JuliaML/MLDatasets.jl)\n#' has an MNIST submodule that offers a convenience interface\n#' to read the MNIST database.\n#'\n#' - [Images.jl](https://github.com/JuliaImages/Images.jl) will\n#' provide us with the necessary tools to process and display\n#' the image data in Julia / Juypter.\n#'\n#' - [MLDataUtils.jl](https://github.com/JuliaML/MLDataUtils.jl)\n#' implements a variety of functions to convert and partition\n#' Machine Learning datasets. This will help us prepare the\n#' MNIST data to be used with Knet.jl.\n\nusing Images, MLDatasets, MLDataUtils, Random\nRandom.seed!(42);\n#md nothing # hide\n\n#' As you may have seen previously in the\n#' [elastic distortions tutorial](@ref elastic), the function\n#' `MNIST.traintensor` returns the MNIST training images\n#' corresponding to the given indices as a multi-dimensional\n#' array. These images are stored in the native horizontal-major\n#' memory layout as a single array. Because we specify that\n#' the `eltype` of that array should be `Float32`, all the\n#' individual values are scaled to be between `0.0` and `1.0`.\n#' Also note, how the observations are laid out along the last\n#' array dimension\n\n@show summary(MNIST.traintensor(Float32, 1:500));\n#md nothing # hide\n\n#' The corresponding label of each image is stored as an integer\n#' value between `0` and `9`. That means that if the label has\n#' the value `3`, then the corresponding image is known to be a\n#' handwritten \"3\". To show a more concrete example, the\n#' following code reveals that the first training image denotes a\n#' \"5\" and the second training image a \"0\" (etc).\n\n@show summary(MNIST.trainlabels(1:500))\nprintln(\"First eight labels: \", join(MNIST.trainlabels(1:8),\", \"))\n\n#' For Knet we will require a slightly format for the images\n#' and also the labels. More specifically, we add an additional\n#' singleton dimension of length 1 to our image array. Think of\n#' this as our single color channel (because MNIST images are gray).\n#' Additionally we will convert our labels to proper 1-based indices.\n#' This is because some functions provided by Knet expect the labels\n#' to be in this format. We will do all this by creating a little\n#' utility function that we will name `prepare_mnist`.\n\n\"\"\"\n prepare_mnist(images, labels) -> (X, Y)\n\nChange the dimension layout x1×x2×N of the given array\n`images` to x1×x2×1×N and return the result as `X`.\nThe given integer vector `labels` is transformed into\nan integer vector denoting 1-based class indices.\n\"\"\"\nfunction prepare_mnist(images, labels)\n X = reshape(images, (28, 28, 1, :))\n Y = convertlabel(LabelEnc.Indices{Int8}, labels, 0:9)\n X, Y\nend\n#md nothing # hide\n\n#' With `prepare_mnist` defined, we can now use it in conjunction\n#' with the functions in the `MLDatasets.MNIST` sub-module to load\n#' and prepare our training set. Recall that for this tutorial only\n#' the first 500 images of the training set will be used.\n\ntrain_x, train_y = prepare_mnist(MNIST.traintensor(Float32, 1:500), MNIST.trainlabels(1:500))\n@show summary(train_x) summary(train_y);\n[MNIST.convert2image(train_x[:,:,1,i]) for i in 1:8]\n#md tmp = hcat(ans...) # hide\n#md save(\"mnist_knet_train.png\",repeat(tmp, inner=(4,4))) # hide\n#md nothing # hide\n\n#md #' ![training images](mnist_knet_train.png)\n\n#' Similarly, we use `MNIST.testtensor` and `MNIST.testlabels`\n#' to load the full MNIST test set. We will utilize that data to\n#' measure how well the network is able to generalize with and\n#' without augmentation.\n\ntest_x, test_y = prepare_mnist(MNIST.testtensor(Float32), MNIST.testlabels())\n@show summary(test_x) summary(test_y);\n[MNIST.convert2image(test_x[:,:,1,i]) for i in 1:8]\n#md tmp = hcat(ans...) # hide\n#md save(\"mnist_knet_test.png\",repeat(tmp, inner=(4,4))) # hide\n#md nothing # hide\n\n#md #' ![test images](mnist_knet_test.png)\n\n#' ## Defining the Network\ninfo(\"Defining the Network\") #jl-only\n\n#' With the dataset prepared, we can now define and instantiate\n#' our neural network. To keep things simple, we will use the same\n#' convolutional network as defined in the\n#' [MNIST example](http://denizyuret.github.io/Knet.jl/latest/tutorial.html#Convolutional-neural-network-1)\n#' of the Knet.jl package.\n\nusing Knet\n#md nothing # hide\n\n#' The first thing we will do is define the forward pass through\n#' the network. This will effectively outline the computation\n#' graph of the network architecture. Note how this does not\n#' define some details, such as the number of neurons per layer.\n#' We will define those later when initializing our\n#' vector of weight arrays `w`.\n\n\"\"\"\n forward(w, x) -> a\n\nCompute the forward pass for the given minibatch `x` by using the\nneural network parameters in `w`. The resulting (unnormalized)\nactivations of the last layer are returned as `a`.\n\"\"\"\nfunction forward(w, x)\n # conv1 (2x2 maxpool)\n a1 = pool(relu.(conv4(w[1], x) .+ w[2]))\n # conv2 (2x2 maxpool)\n a2 = pool(relu.(conv4(w[3], a1) .+ w[4]))\n # dense1 (relu)\n a3 = relu.(w[5] * mat(a2) .+ w[6])\n # dense2 (identity)\n a4 = w[7] * a3 .+ w[8]\n return a4\nend\n#md nothing # hide\n\n#' In order to be able to train our network we need to choose a\n#' cost function. Because this is a classification problem we will\n#' use the negative log-likelihood (provided by `Knet.nll`).\n#' With the cost function defined we can the simply use the\n#' higher-order function `grad` to create a new function `costgrad`\n#' that computes us the corresponding gradients.\n\n\"\"\"\n cost(w, x, y) -> AbstractFloat\n\nCompute the per-instance negative log-likelihood for the data\nin the minibatch `(x, y)` given the network with the current\nparameters in `w`.\n\"\"\"\ncost(w, x, y) = nll(forward(w, x), y)\ncostgrad = grad(cost)\n#md nothing # hide\n\n#' Aside from the cost function that we need for training, we\n#' would also like a more interpretable performance measurement.\n#' In this tutorial we will use \"accuracy\" for its simplicity\n#' and because we know that the class distribution for MNIST\n#' is close to uniform.\n\n\"\"\"\n acc(w, X, Y; [batchsize]) -> Float64\n\nCompute the accuracy for the data in `(X,Y)` given the network\nwith the current parameters in `w`. The resulting value is\ncomputed by iterating over the data in minibatches of size\n`batchsize`.\n\"\"\"\nfunction acc(w, X, Y; batchsize = 100)\n sum = 0; count = 0\n for (x_cpu, y) in eachbatch((X, Y), maxsize = batchsize)\n x = KnetArray{Float32}(x_cpu)\n sum += Int(accuracy(forward(w,x), y, average = false))\n count += length(y)\n end\n return sum / count\nend\n#md nothing # hide\n\n#' Before we can train or even just use our network, we need to\n#' define how we initialize `w`, which is our the vector of\n#' parameter arrays. The dimensions of these individual arrays\n#' specify the filter sizes and number of neurons.\n#' It can be helpful to compare the indices here with the indices\n#' used in our `forward` function to see which array corresponds\n#' to which computation node of our network.\n\nfunction weights(atype = KnetArray{Float32})\n w = Array{Any}(undef, 8)\n # conv1\n w[1] = xavier(5,5,1,20)\n w[2] = zeros(1,1,20,1)\n # conv2\n w[3] = xavier(5,5,20,50)\n w[4] = zeros(1,1,50,1)\n # dense1\n w[5] = xavier(500,800)\n w[6] = zeros(500,1)\n # dense2\n w[7] = xavier(10,500)\n w[8] = zeros(10,1)\n return map(a->convert(atype,a), w)\nend\n#md nothing # hide\n\n\n#' ## Training without Augmentation\ninfo(\"Training baseline network without augmentation\") #jl-only\n\n#' In order to get an intuition for how useful augmentation can\n#' be, we need a sensible baseline to compare to. To that end, we\n#' will first train the network we just defined using only the\n#' (unaltered) 500 training examples.\n\n#' The package\n#' [ValueHistories.jl](https://github.com/JuliaML/ValueHistories.jl)\n#' will help us record the accuracy during the training process.\n#' We will use those logs later to visualize the differences\n#' between having augmentation or no augmentation.\n\nusing ValueHistories\nusing ProgressMeter #jl-only\n\n#' To keep things simple, we will not overly optimize our\n#' training function. Thus, we will be content with using a\n#' closure. Because both, the baseline and the augmented version,\n#' will share this \"inefficiency\", we should still get a decent\n#' enough picture of their performance differences.\n\nfunction train_baseline(; epochs = 500, batchsize = 100, lr = .03)\n w = weights()\n log = MVHistory()\n p = Progress(epochs, desc = \"Baseline: \") #jl-only\n for epoch in 1:epochs\n for (batch_x_cpu, batch_y) in eachbatch((train_x ,train_y), batchsize)\n batch_x = KnetArray{Float32}(batch_x_cpu)\n g = costgrad(w, batch_x, batch_y)\n Knet.update!(w, g, lr = lr)\n end\n\n next!(p) #jl-only\n if (epoch % 5) == 0\n train = acc(w, train_x, train_y)\n test = acc(w, test_x, test_y)\n @trace log epoch train test\n msg = \"epoch \" * lpad(epoch,4) * \": train accuracy \" * rpad(round(train, digits=3),5,\"0\") * \", test accuracy \" * rpad(round(test,digits=3),5,\"0\")\n cancel(p, msg, :blue) #jl-only\n#md println(msg)\n#jp println(msg)\n end\n end\n finish!(p) #jl-only\n log\nend\n#md nothing # hide\n\n#' Aside from the accuracy, we will also keep an eye on the\n#' training time. In particular we would like to see if and how\n#' the addition of augmentation causes our training time to\n#' increase.\n\ntrain_baseline(epochs=1) # warm-up\nbaseline_log = @time train_baseline(epochs=200);\n#md nothing # hide\n\n#' As we can see, the accuracy on the training set is around a\n#' 100%, while the accuracy on the test set peaks around 90%. For\n#' a mere 500 training examples, this isn't actually that bad of\n#' a result.\n\n#' ## Integrating Augmentor\ninfo(\"Training network with augmentation\") #jl-only\n\n#' Now that we have a network architecture with a baseline to\n#' compare to, let us finally see what it takes to add Augmentor\n#' to our experiment. First, we need to include the package to\n#' our experiment.\n\nusing Augmentor\n\n#' The next step, and maybe the most human-hour consuming part of\n#' adding image augmentation to a prediction problem, is to\n#' design and select a sensible augmentation pipeline. Take a\n#' look at the [elastic distortions tutorial](@ref elastic) for\n#' an example of how to do just that.\n\n#' For this example, we already choose a quite complicated but\n#' promising augmentation pipeline for you. This pipeline was\n#' designed to yield a large variation of effects as well as to\n#' showcase how even deep pipelines are quite efficient in terms\n#' of performance.\n\npl = Reshape(28,28) |>\n PermuteDims(2,1) |>\n ShearX(-5:5) * ShearY(-5:5) |>\n Rotate(-15:15) |>\n CropSize(28,28) |>\n Zoom(0.9:0.1:1.2) |>\n CacheImage() |>\n ElasticDistortion(10) |>\n PermuteDims(2,1) |>\n Reshape(28,28,1)\nprintln(pl) #jl-only\n\n#' Most of the used operations are quite self explanatory, but\n#' there are some details about this pipeline worth pointing out\n#' explicitly.\n\n#' 1. We use the operation [`PermuteDims`](@ref) to convert the\n#' horizontal-major MNIST image to a julia-native\n#' vertical-major image. The vertical-major image is then\n#' processed and converted back to a horizontal-major array.\n#' We mainly do this here to showcase the option, but it is\n#' also to keep consistent with how the data is usually used\n#' in the literature. Alternatively, one could just work with\n#' the MNIST data in a vertical-major format all the way\n#' through without any issue.\n\n#' 2. As counter-intuitive as it sounds, the operation\n#' [`CacheImage`](@ref) right before\n#' [`ElasticDistortion`](@ref) is actually used to improve\n#' performance. If we were to omit it, then the whole pipeline\n#' would be applied in one single pass. In this case, applying\n#' distortions on top of affine transformations lazily is in\n#' fact less efficient than using a temporary variable.\n\n#' With the pipeline now defined, let us quickly peek at what\n#' kind of effects we can achieve with it. In particular, lets\n#' apply the pipeline multiple times to the first training image\n#' and look at what kind of results it produces.\n\n#jp [MNIST.convert2image(reshape(augment(train_x[:,:,:,1], pl), (28, 28))) for i in 1:2, j in 1:8]\n#md [MNIST.convert2image(reshape(augment(train_x[:,:,:,1], pl), (28, 28))) for i in 1:8, j in 1:2]\n#md tmp = vcat(hcat(ans[:,1]...), hcat(ans[:,2]...)) # hide\n#md save(\"mnist_knet_aug.png\",repeat(tmp, inner=(4,4))) # hide\n#md nothing # hide\n\n#md #' ![augmented samples](mnist_knet_aug.png)\n\n#' As we can see, we can achieve a wide range of effects, from\n#' more subtle to more pronounced. The important part is that all\n#' examples are still clearly representative of the true label.\n\n#' Next, we have to adapt the function `train_baseline` to make\n#' use of our augmentation pipeline. To integrate Augmentor\n#' efficiently, there are three necessary changes we have to\n#' make.\n\n#' 1. Preallocate a buffer with the same size and element type\n#' that each batch has.\n#'\n#' ```\n#' batch_x_aug = zeros(Float32, 28, 28, 1, batchsize)\n#' ```\n\n#' 2. Add a call to [`augmentbatch!`](@ref) in the inner loop of\n#' the batch iterator using our pipeline and buffer.\n#'\n#' ```\n#' augmentbatch!(batch_x_aug, batch_x_org, pl)\n#' ```\n\n#' 3. Replace `batch_x_org` with `batch_x_aug` in the constructor\n#' of `KnetArray`.\n#'\n#' ```\n#' batch_x = KnetArray{Float32}(batch_x_aug)\n#' ```\n\n\n#' Applying these changes to our `train_baseline` function\n#' will give us something similar to the following function.\n#' Note how all the other parts of the function remain exactly\n#' the same as before.\n\nfunction train_augmented(; epochs = 500, batchsize = 100, lr = .03)\n w = weights()\n log = MVHistory()\n p = Progress(epochs, desc = \"Augmented: \") #jl-only\n batch_x_aug = zeros(Float32, size(train_x,1), size(train_x,2), 1, batchsize)\n for epoch in 1:epochs\n for (batch_x_cpu, batch_y) in eachbatch((train_x ,train_y), batchsize)\n augmentbatch!(CPUThreads(), batch_x_aug, batch_x_cpu, pl)\n batch_x = KnetArray{Float32}(batch_x_aug)\n g = costgrad(w, batch_x, batch_y)\n Knet.update!(w, g, lr = lr)\n end\n\n next!(p) #jl-only\n if (epoch % 5) == 0\n train = acc(w, train_x, train_y)\n test = acc(w, test_x, test_y)\n @trace log epoch train test\n msg = \"epoch \" * lpad(epoch,4) * \": train accuracy \" * rpad(round(train, digits=3),5,\"0\") * \", test accuracy \" * rpad(round(test,digits=3),5,\"0\")\n cancel(p, msg, :blue) #jl-only\n#md println(msg)\n#jp println(msg)\n end\n end\n finish!(p) #jl-only\n log\nend\n#md nothing # hide\n\n#' You may have noticed in the code above that we also pass a\n#' `CPUThreads()` as the first argument to [`augmentbatch!`](@ref).\n#' This instructs Augmentor to process the images of the batch in\n#' parallel using multi-threading. For this to work properly you\n#' will need to set the environment variable `JULIA_NUM_THREADS`\n#' to the number of threads you wish to use. You can check how\n#' many threads are used with the function `Threads.nthreads()`\n\n@show Threads.nthreads();\n#md nothing # hide\n\n#' Now that all pieces are in place, let us train our network\n#' once more. We will use the same parameters except that now\n#' instead of the original training images we will be using\n#' randomly augmented images. This will cause every epoch to be\n#' different.\n\ntrain_augmented(epochs=1) # warm-up\naugmented_log = @time train_augmented(epochs=200);\n#md nothing # hide\n\n#' As we can see, our network reaches far better results on our\n#' testset than our baseline network did. However, we can also\n#' see that the training took quite a bit longer than before.\n#' This difference generally decreases as the complexity of the\n#' utilized neural network increases. Yet another way to improve\n#' performance (aside from simplifying the augmentation pipeline)\n#' would be to increase the number of available threads.\n\n#' ## Improving Performance\ninfo(\"Improving Performance\") #jl-only\n\n#' One of the most effective ways to make the most out of the\n#' available resources is to augment the next (couple) mini-batch\n#' while the current minibatch is being processed on the GPU.\n#' We can do this via julia's build in parallel computing\n#' capabilities\n\n#' First we need a worker process that will be responsible for\n#' augmenting our dataset each epoch. This worker also needs\n#' access to a couple of our packages\n\nusing Distributed\naddprocs(1)\n@everywhere using Augmentor, MLDataUtils\n#md nothing # hide\n\n\n#' Next, we replace the inner `eachbatch` loop with a more\n#' complicated version using a `RemoteChannel` to exchange and\n#' queue the augmented data.\n\nfunction async_train_augmented(; epochs = 500, batchsize = 100, lr = .03)\n w = weights()\n log = MVHistory()\n p = Progress(epochs, desc = \"Async Augmented: \") #jl-only\n for epoch in 1:epochs\n @sync begin\n local_ch = Channel{Tuple}(4) # prepare up to 4 minibatches in adavnce\n remote_ch = RemoteChannel(()->local_ch)\n @spawn begin\n # This block is executed on the worker process\n batch_x_aug = zeros(Float32, size(train_x,1), size(train_x,2), 1, batchsize)\n for (batch_x_cpu, batch_y) in eachbatch((train_x ,train_y), batchsize)\n # we are still using multithreading\n augmentbatch!(CPUThreads(), batch_x_aug, batch_x_cpu, pl)\n put!(remote_ch, (batch_x_aug, batch_y))\n end\n close(remote_ch)\n end\n @async begin\n # This block is executed on the main process\n for (batch_x_aug, batch_y) in local_ch\n batch_x = KnetArray{Float32}(batch_x_aug)\n g = costgrad(w, batch_x, batch_y)\n Knet.update!(w, g, lr = lr)\n end\n end\n end\n\n next!(p) #jl-only\n if (epoch % 5) == 0\n train = acc(w, train_x, train_y)\n test = acc(w, test_x, test_y)\n @trace log epoch train test\n msg = \"epoch \" * lpad(epoch,4) * \": train accuracy \" * rpad(round(train,digits=3),5,\"0\") * \", test accuracy \" * rpad(round(test,digits=3),5,\"0\")\n cancel(p, msg, :blue) #jl-only\n#md println(msg)\n#jp println(msg)\n end\n end\n finish!(p) #jl-only\n log\nend\n#md nothing # hide\n\n#' Note that for this toy example the overhead of this approach\n#' is greater than the benefit.\n\nasync_train_augmented(epochs=1) # warm-up\naugmented_log = @time async_train_augmented(epochs=200);\n#md nothing # hide\n\n#' ## Visualizing the Results\ninfo(\"Visualizing the Results\") #jl-only\n\n#' Before we end this tutorial, let us make use the\n#' [Plots.jl](https://github.com/JuliaPlots/Plots.jl) package to\n#' visualize and discuss the recorded training curves.\n#' We will plot the accuracy curves of both networks side by side\n#' in order to get a good feeling about their differences.\n\nusing Plots\n#jp gr()\n#md gr()\n#md nothing # hide\nunicodeplots() #jl-only\n\n#+\n\n#md default(bg_outside=colorant\"#FFFFFF\") # hide\nplt = plot(\n plot(baseline_log, title=\"Baseline\", ylim=(.5,1)),\n plot(augmented_log, title=\"Augmented\", ylim=(.5,1)),\n size = (900, 400),\n xlab = \"Epoch\",\n ylab = \"Accuracy\",\n markersize = 1\n)\n#jp plt\n#md png(plt, \"mnist_knet_curves.png\") # hide\n#md nothing # hide\n\n#md #' ![learning curves](mnist_knet_curves.png)\n\n#' Note how the accuracy on the (unaltered) training set\n#' increases faster for the baseline network than for the\n#' augmented one. This is to be expected, since our augmented\n#' network doesn't actually use the unaltered images for\n#' training, and thus has not actually seen them. Given this\n#' information, it is worth pointing out explicitly how the\n#' accuracy on training set is still greater than on the test set\n#' for the augmented network as well. This is also not a\n#' surprise, given that the augmented images are likely more\n#' similar to their original ones than to the test images.\n\n#' For the baseline network, the accuracy on the test set\n#' plateaus quite quickly (around 90%). For the augmented network\n#' on the other hand, it the accuracy keeps increasing for quite\n#' a while longer.\n\n#' ## References\n#'\n#' [^MNIST1998]: LeCun, Yan, Corinna Cortes, Christopher J.C. Burges. [\"The MNIST database of handwritten digits\"](http://yann.lecun.com/exdb/mnist/) Website. 1998.\n", "meta": {"hexsha": "3dcac49afc7641209e94edae3dd92a41533c599d", "size": 21980, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/mnist_knet.jl", "max_stars_repo_name": "baggepinnen/Augmentor.jl", "max_stars_repo_head_hexsha": "9652e66b5db5b431cccb9799615ae3e98d55ccfd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/mnist_knet.jl", "max_issues_repo_name": "baggepinnen/Augmentor.jl", "max_issues_repo_head_hexsha": "9652e66b5db5b431cccb9799615ae3e98d55ccfd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/mnist_knet.jl", "max_forks_repo_name": "baggepinnen/Augmentor.jl", "max_forks_repo_head_hexsha": "9652e66b5db5b431cccb9799615ae3e98d55ccfd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5726495726, "max_line_length": 164, "alphanum_fraction": 0.6873066424, "num_tokens": 5857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.11757212272365286, "lm_q1q2_score": 0.05147583816915406}} {"text": "### A Pluto.jl notebook ###\n# v0.12.18\n\nusing Markdown\nusing InteractiveUtils\n\n# ╔═╡ a4f0a914-1ec9-11eb-3c22-db87a9776aaa\nbegin\n\tusing JSON\n\tusing DataFrames\nend\n\n# ╔═╡ 5f83510e-1fc5-11eb-3c40-83a844bf2907\nusing Turing\n\n# ╔═╡ 2414104e-1d41-11eb-37cb-9b5cee78a98b\nmd\"## Creating our conjectures\"\n\n# ╔═╡ 3b7f8a1e-1d42-11eb-1ab1-c11fda416e80\nmd\"\"\"If there is one thing we can all agree on, it is that the reality in which we live is complex. The explanation for the things we usually see, and have naturalized in our daily lives, is usually quite complex and requires abstraction from what \"is simply seen\".\n\nIn order to give an explanation and gain a deeper understanding of the things we see, we tend to generate models that seek to explain them in a simple and generalized way. In this way we can reduce the noise of our observations to general rules that \"govern\" them.\n\nFor example, it is obvious to everyone that if we push a glass it will move in the same direction as we did. We also know that if we keep pushing it and it goes beyond the limits of the table, it will fall to the floor. But one thing is to have the intuition of what's going to happen, and another is to have an understanding of the laws that govern that movement. In this case, they are the Newton´s Law´s of motion:\n\n\"\"\"\n\n# ╔═╡ 4e4385b4-203b-11eb-0c5b-cbe41156401b\nmd\"$ \\vec{F}^{\\} = m*\\vec{a}^{\\} $\"\n\n# ╔═╡ 2dca2f42-203b-11eb-2cb3-0d6a3823cdcd\nmd\"\"\"In this way, and with only one formula, it is possible to gain an understanding that is generalizable to many aspects of reality. \n\n#### Observable variables vs Latent variables\n\nNow, it is worth noting that in this case all the variables that make up our model are observable. This means that they can be measured directly.\n\nIn the case of a glass, we could weigh it with a scale. Then, by pushing it, we could measure the acceleration it acquired and from these two measurements we could obtain the force we applied to it. So, every parameter of the model is fully defined.\n\nHowever, as we try to advance in our understanding of reality, we arrive at more and more complex models and many times we are not so lucky to be able to define them with simple observable variables.\n\nFor example, this is very common in the economic sciences, where models are created with variables such as \"quality of life\". Economists will try to measure this latent variable with other variables that can be observed (such as quality of life, schooling rate, number of hospitals for a certain number of inhabitants, etc), but that do not have an obvious and direct relationship as if they had newton's equations.\n\nThis type of latent variables are used in different models to gain greater abstraction and to be able to obtain information that a priori is not found at first sight in the data. For example, in the case of economics, from concrete measures of a country's economy it is possible to generalize knowledge and be able to infer an abstract variable such as quality of life.\n\n### Bayesian hierarchical models\n\nThe Bayesian framework allows us to build statistical models that can generalize the information obtained from the data and make inferences from latent variables. \n\nA nice way to think about this kind of models is that they allow us to build our \"story\" about which are the variables that generate the data we are observing. Basically, they allow us to increase the \"depth\" of our model by indicating that the parameters of our prior distributions also follow other probability distributions.\n\nThis sure is sounding very strange. Don't worry, let's move on to an example to clarify it.\n\n#### Football analysis\n\nLet's imagine for a moment that we are brilliant statisticians. We find ourselves looking for new interesting challenges to solve and we come across a sports bookmaker. They tell us that they want to expand into football betting and that they would like us to be able to build a model that allows them to analyze the strengths and weaknesses of English Premier League teams. They are interested because they want to be able to predict possible outcomes and thus be able to price the bets. \n\nThe problem is that, as they have never worked in this sector before, they only have the results of the league matches. So what can we do? \"\"\"\n\n# ╔═╡ 0c0268dc-1ed3-11eb-2f73-b3706305b298\nmd\"We have the data stored in a specific format called JSON, so the first thing to do is to parse and visualize it\"\n\n# ╔═╡ cbaaf72c-1eb4-11eb-3509-932b337f270b\nbegin\nengland_league = JSON.parsefile(\"matches_England.json\")\nmatches_df = DataFrame(home = [], away = [], score_home = [], score_away = [])\nend;\n\n# ╔═╡ ab6fcb22-1ed2-11eb-2749-3bef16911972\nbegin\n\tmatches = []\n\tfor match in england_league\n\t\tpush!(matches, split(match[\"label\"], \",\"))\nend\nend\n\n# ╔═╡ d2a81a14-1ed2-11eb-1307-bfb169aebbb4\nbegin\nfor match in matches\n\thome, away = split(match[1], \" - \")\n\tscore_home, score_away = split(match[2], \" - \")\n\t\n\tpush!(matches_df,[home, away, parse(Int,score_home), parse(Int,score_away)])\nend\nend\t\n\n# ╔═╡ dd80fc38-1ed2-11eb-0e8c-49859d27c72c\nmatches_df\n\n# ╔═╡ 7f0c72d4-1f9e-11eb-06f1-cb587d7e5436\nteams = unique(collect(matches_df[1]))\n\n# ╔═╡ 868e5c8c-1ed3-11eb-291c-fb26d512c103\nmd\"\"\"So, we have the data of the 380 matches that were played in the Premier League 2017/2018 and our challenge is to be able to analyze the characteristics of these teams. \n\nA priori it may seem that we are missing data, that with the data we have we cannot infer \"characteristics\" specific to each team. At most, it might be possible to see who the teams that scored the most goals, the averages of goals per game or how the positions were after the tournament, but to obtain characteristics of the teams? how could we face this problem?\n\n#### Creating our stories\n\nOkay, let's see what information we have from our data: \nOn one hand we have specified the names of each team and which one is local. On the other hand, we have the number of goals scored.\n\nA possible approach to this data is to realize that the goals scored by each team can be modeled with a poisson distribution. \n\nWhy? You have to remember that this distribution describes \"arrivals\" - discrete events - in a continuum. For example, it is widely used to describe customer arrivals to a location as time passes or failures in continuous industrial processes (e.g. failure in the production of a pipe). \n\nIn this particular case, we could propose that the goals scored by a team are the discrete events that occur in the time continuum that the game last:\n\n\"\"\"\n\n# ╔═╡ 04a8f16c-1ed5-11eb-3979-af35c6d9dea1\nmd\"$Score \\sim Poisson(θ)$\"\n\n# ╔═╡ 9f1e1618-1edb-11eb-02af-9fa5c8904163\nmd\"\"\"Well, we have an improvement. We've already told our model how to think about goals scored. \n\nNow we can use the flexibility of Bayesianism to indicate what the \"goal rate\" of our Poisson depends on. You can think of it literally as the number of goals a team scores per unit of time. And this is where we have to take advantage of all the information provided by the data set.\n\nAs expected, this rate has to be particular to each match the team plays and take into account the opponent. We can therefore propose that the scoring rate of each team (in each particular match) depends on the \"attacking power\" of the team on the one hand, and the \"defensive power\" of the opponent on the other:\n\n\"\"\"\n\n# ╔═╡ 42104900-1f80-11eb-019f-a7c561ca3e4b\nmd\"$θ_{team1} \\sim att_{team1} + def_{team2}$\" \n\n# ╔═╡ 9d0f3a1e-1f80-11eb-3422-fb7b4696cc13\nmd\"\"\"In this way we could be capturing, from the results of each game, the attack and defence strengths of each team. \n\nAnother latent variable that we could obtain, given the data, is if there is an effect that increases (or decreases) the goal rate related to whether the team is local or not. This would also help - in case there is indeed an effect - in not the attack and defence parameters be disrupted by having to \"contain\" that information.\"\"\"\n\n# ╔═╡ 0b1f9c68-1f83-11eb-11e7-e7614c021c05\nmd\"$θ_{home} \\sim home + att_{home} + def_{away}$\n$θ_{away} \\sim att_{away} + def_{home}$\"\n\n# ╔═╡ 043c438c-1f84-11eb-2cd7-6dd07a125910\nmd\"\"\"This leaves one attack and one defense parameter for each team, and a global league parameter that indicates the effect of being local on the scoring rate.\n\n#### Letting the information flow \n\nOkay, we are already getting much closer to the initial goal we set. As a last step, we must be able to make the information flow between the two independent poissons that we proposed to model the score of each of the two teams that are playing. We need to do that precisely because we have proposed that the poissons are independent, but we need that when making the inference of the parameters the model can access the information from both scores so it can catch the correlation between them. In other words, we have to find a way to interconnect our model.\n\nAnd that is exactly what hierarchical Bayesian models allow us to do. How? By letting us choose probability distributions for the parameters that represent the characteristics of both equipment. With the addition that these parameters will share the same prior distributions. Let's see how:\n\nThe first thing to do, as we already know, is to assign the prior distributions of our attack and defense parameters. A reasonable idea would be to propose that they follow a normal distribution since it is consistent that there are some teams that have a very good defense, so the parameter would take negative values; or there may be others that have a very bad one, taking positive values (since they would \"add up\" to the goal rate of the opposing team). The normal distribution allows us to contemplate both cases.\n\nNow, when choosing the parameters we are not going to stop and assign fixed numbers, but we will continue to deepen the model and add another layer of distributions:\n\n\"\"\"\n\n# ╔═╡ 4a31541e-1f97-11eb-038e-736446224c21\nmd\"$att_{t} \\sim Normal(μ_{att}, σ_{att})$\n$def_{t} \\sim Normal(μ_{def}, σ_{def})$\"\n\n# ╔═╡ e3a99868-1f97-11eb-1872-79c8f6abe1be\nmd\"Where the t sub-index is indicating us that there are a couple of these parameters for each team.\n\nThen, as a last step to have our model defined, we have to assign the priority distributions that follow the parameters of each normal distribution. We have to define our hyper priors.\n\n\"\n\n# ╔═╡ c3ca1cc4-1f98-11eb-3c23-33acb95fbc03\nmd\"$μ_{att}, μ_{def} \\sim Normal(0, 0.1)$\n$σ_{att}, σ_{def} \\sim Exponential(1)$\"\n\n# ╔═╡ 4106e55a-1f99-11eb-110e-b79221774f12\nmd\"We must not forget the parameter that represents the advantage of being local\"\n\n# ╔═╡ bff4fdae-1f99-11eb-2d94-aba7bf9d097f\nmd\"$home \\sim Normal(0,1)$\"\n\n# ╔═╡ 2b135202-1fa7-11eb-324d-93a5eda41e3e\nmd\"\"\"Now that our model is fully define, let's add one last restriction to the characteristics of the teams to make it easier to compare them: subtract the average of all the attack and defence powers from each one. In this way we will have the features centred on zero, with negative values for the teams that have less attacking power than the average and positive values for those that have more. As we already said, the opposite analysis applies to the defence, negative values are the ones that will indicate that a team has a strong defence as they will be \"subtracting\" from the scoring rate of the opponent. This is equivalent to introducing the restriction:\n\"\"\"\n\n# ╔═╡ ddc7b166-203a-11eb-0ac2-056c309bb590\nmd\"$\\sum att_{t} = 0$\n$\\sum def_{t} = 0$\"\n\n# ╔═╡ 8e164be0-203b-11eb-293a-6b32dba96133\nmd\"Let's translate all this into Turing code:\"\n\n# ╔═╡ 51a309bc-2033-11eb-10c0-ed17545df33d\nbegin\n\t@model function football_matches(home_teams, away_teams, score_home, score_away, teams)\n\t#hyper priors\n\tσatt ~ Exponential(1)\n\tσdeff ~ Exponential(1)\n\tμatt ~ Normal(0,0.1)\n\tμdef ~ Normal(0,0.1)\n\t\n\thome ~ Normal(0,1)\n\t\t\n\t#Team-specific effects\t\n\tatt ~ filldist(Normal(μatt, σatt), length(teams))\n\tdef ~ filldist(Normal(μatt, σdeff), length(teams))\n\t\n\tdict = Dict{String, Int64}()\n\tfor (i, team) in enumerate(teams)\n\t\tdict[team] = i\n\tend\n\t\t\n\t#Zero-sum constrains\n\toffset = mean(att) + mean(def)\n\t\n\tlog_θ_home = Vector{Real}(undef, length(home_teams))\n\tlog_θ_away = Vector{Real}(undef, length(home_teams))\n\t\t\n\t#Modeling score-rate and scores (as many as there were games in the league) \n\tfor i in 1:length(home_teams)\n\t\t#score-rate\n\t\tlog_θ_home[i] = home + att[dict[home_teams[i]]] + def[dict[away_teams[i]]] - offset\n\t\tlog_θ_away[i] = att[dict[away_teams[i]]] + def[dict[home_teams[i]]] - offset\n\t\t#scores\n\t\tscore_home[i] ~ LogPoisson(log_θ_home[i])\n\t\tscore_away[i] ~ LogPoisson(log_θ_away[i])\n\tend\n\t\n\tend\nend\n\n# ╔═╡ f3f0b6f8-2033-11eb-0f9e-d951d791001d\nmd\"\"\"As you can see, the turing code is very clear and direct. In the first block we define our hyperpriors for the distributions of the characteristics of the equipment.\n\nIn the second one, we define the priors distributions that will encapsulate the information about the attack and defense powers of the teams. With the *filldist* function we are telling Turing that we need as many of these parameters as there are teams in the league *length(teams)*\n\nThen, we calculate the average of the defense and attack parameters that we are going to use to centralize those variables, and we use the LogPoisson distribution to allow the theta to take some negative value in the inference process and give more sensitivity to the parameters that make it up.\n\nAs we said before, we will model the thetas for each game played in the league, that's why the *for* of the last block goes from 1 to *length(home_teams)*, which is the list that contains who was the local team of each game played.\n\nSo let´s run it and see if all of this effort was worth it:\n\"\"\"\n\n# ╔═╡ f3f4bfba-203f-11eb-142c-a187112744d2\nmodel = football_matches(matches_df[1], matches_df[2], matches_df[3], matches_df[4], teams)\n\n# ╔═╡ 2ce4435c-2040-11eb-1670-e39ad4cc690c\nposterior = sample(model, NUTS(),3000);\n\n# ╔═╡ 9e50e56e-5674-11eb-2919-4bde8964bc59\nrand(LogPoisson(0.2), 100)\n\n# ╔═╡ 8c1dd9de-2040-11eb-35a3-39e8196577a1\nmd\"#### Analyzing the results\nIn order to compare and corroborate that the inference of our model makes sense, it is key to have the ranking table of how the teams actually performed in the 2017/2018 Premier League.\n\"\n\n# ╔═╡ 0f9406ae-2054-11eb-3f0c-1d03ba779f18\nbegin\n\ttable_positions = \n\t[11, 5, 9, 4, 13, 14, 1, 15, 12, 6, 2, 16, 10, 17, 20, 3, 7, 8, 19, 18]\n\t\n\tgames_won = \n\t[32, 25, 23, 21, 21, 19, 14, 13, 12, 12, 11, 11, 10, 11, 9, 9, 7, 8, 7, 6]\n\t\n\tteams_ = []\n\tfor i in table_positions\n\t\tpush!(teams_, teams[i])\n\tend\n\t\n\ttable_position_df = DataFrame(Table_of_positions = teams_, Wins = games_won)\n\nend\n\n# ╔═╡ 099e4188-2054-11eb-1e7e-69bdb2b0202c\nmd\"Let's now explore a little bit the a posteriori values we obtained.\"\n\n# ╔═╡ 16572944-2045-11eb-38d0-fb20d981e3e9\nbegin\n\tpost_att = collect(get(posterior, :att)[1])\n\tpost_def = collect(get(posterior, :def)[1])\n\tpost_home = collect(get(posterior, :home)[1])\nend;\n\n# ╔═╡ 4ae7d968-206f-11eb-1925-c5b5a31e6940\nbegin\nusing Plots\nhistogram(post_home, legend=false, title=\"Posterior distribution of home parameter\")\nend\n\n# ╔═╡ 93d3bf98-5684-11eb-361e-c7b0f1a3bb0e\nget(posterior, :att)[:att]\n\n# ╔═╡ 18f36e1a-5682-11eb-2826-ab4d4c457af3\nposterior.value.data\n\n# ╔═╡ 6f096138-5682-11eb-179f-f973803b9268\ncollect(get(posterior, :att)[1])\n\n# ╔═╡ 8cec9318-206e-11eb-3caa-3bad9d788d3c\nmd\"As a first measure to analyze, it is interesting to see and quantify (if any) the effect that being local has on the score rate:\"\n\n# ╔═╡ 8b77d12c-206f-11eb-19a5-f557157ac05e\nmean(post_home)\n\n# ╔═╡ b56df7ea-206f-11eb-18b9-0544cc596ca5\nmd\"So, to include in the model the parameter home was a good idea. indeed being local provides a very big advantage. \n\nBeyond the fact that it is interesting to be able to quantify how much the location influences the scoring rate of the teams, including it in the analysis allow us to have better estimates of the defense and attack parameters of the teams. This is true because if it had not been included, this positive effect would have manifested itself in the only parameters it would have found, the attack and defense parameters, deforming the real measure of these.\n\nSo, being confident that we are on the right track, let´s find the attack and defence parameters of each team.\"\n\n# ╔═╡ 554b4ef0-2045-11eb-3218-050ec936f1aa\nbegin\n\tteams_att = []\n\tteams_def = []\n\tfor i in 1:length(post_att)\n\t\tpush!(teams_att, post_att[i])\n\t\tpush!(teams_def, post_def[i])\n\tend\nend\n\n# ╔═╡ 8a4df438-2045-11eb-2798-af592dbbffb5\nmd\"This way we obtain all the samples of the posterior distributions for each one of the parameters of each equipment. Scroll right to explore the entire array.\"\n\n# ╔═╡ 6b1a1520-2045-11eb-1302-0778b4e7a836\nteams_att\n\n# ╔═╡ da93bf52-2045-11eb-2b6f-3f31f57d8653\nmd\"For example, if we would like to se the posterior distribution of the attack parameter for Burnley:\"\n\n# ╔═╡ 1fa92570-2046-11eb-3541-e5fccf7afabd\nteams[1]\n\n# ╔═╡ 255c4d08-2046-11eb-1cf0-b32d2cd711bf\nhistogram(teams_att[1], legend=false, title=\"Posterior distribution of Burnley´s attack power\")\n\n# ╔═╡ 473e6a46-205b-11eb-2731-7b47b99d86a5\nmean(teams_att[1])\n\n# ╔═╡ 917d4550-2058-11eb-174b-65436a4e6cc8\nmd\"Comparing it to the attacking power of Manchester City, champion of the Premier league:\"\n\n# ╔═╡ c2de4714-2058-11eb-1a0d-f1bf96649844\nteams[11]\n\n# ╔═╡ 0103406e-2059-11eb-333f-7b5814f21a54\nbegin\n\thistogram(teams_att[11], legend=false, title=\"Posterior distribution of Manchester City´s attack power\")\nend\n\n# ╔═╡ 579a4d9e-205b-11eb-2352-83beca145211\nmean(teams_att[11])\n\n# ╔═╡ 6924f372-2059-11eb-2b98-6f4b65b777f4\nmd\"Okay, when comparing the league champion against a mid-table team, we can clearly see the superiority in attack. For now, it seems that the inference comes in handy. \n\nLet's try now to have an overview of the attacking powers of each team. To do this, just take the average of each and plot it next to the standard deviation \n\"\n\n# ╔═╡ ece1d052-2060-11eb-2b50-ef46663ed88f\nbegin\n\tteams_att_μ = mean.(teams_att)\n\tteams_def_μ = mean.(teams_def)\n\tteams_att_σ = std.(teams_att)\n\tteams_def_σ = std.(teams_def)\nend;\n\n# ╔═╡ 43a39b30-2061-11eb-28c5-37cbc4aed84b\nmd\"\"\"Remember that the \".\" operator is used for broadcasting. This means that it will apply the function to each component of the array\"\"\"\n\n# ╔═╡ 41ca2316-2062-11eb-3fe6-f33a789fd578\nbegin\n\tteams_att_μ\n\tsorted_att = sortperm(teams_att_μ)\n\tabbr_names = [t[1:3] for t in teams]\nend;\n\n# ╔═╡ 0ef8a16e-2063-11eb-1391-6b3b959de541\nbegin\n\tabbr_names[5] = \"Mun\"\n\tabbr_names[10] = \"Whu\"\n\tabbr_names[11] = \"Mci\"\n\tabbr_names[16] = \"Bou\"\n\tabbr_names[18] = \"Wba\"\n\tabbr_names[19] = \"Stk\"\n\tabbr_names[20] = \"Bha\"\nend;\n\n# ╔═╡ 1eb73246-2063-11eb-0f20-416e433b5144\nsorted_names = abbr_names[sorted_att]\n\n# ╔═╡ abace764-2062-11eb-2949-fd9e86b50f17\nbegin\n\tscatter(1:20, teams_att_μ[sorted_att], grid=false, legend=false, yerror=teams_att_σ[sorted_att], color=:blue, title=\"Premier league 17/18 teams attack power\")\n\tannotate!(collect(1:20), teams_att_μ[sorted_att] .+ 0.238, text.(sorted_names, :black, :center, 8))\n\tylabel!(\"Mean team attack\")\nend\n\n# ╔═╡ ebd267a4-2064-11eb-02a7-b93465de6319\nmd\"\"\"Although there is a high correlation between the attacking power of each team and its position on the table after the league ends, it is clear that this is not enough to explain the results. For example, Manchester City was the league's sub-champion, but only appeared in fifth place.\n\nLet's explore what happens to the defence power: \"\"\"\n\n# ╔═╡ f6ad5f52-2065-11eb-0be7-f159941e0d89\nbegin\n\tsorted_def = sortperm(teams_def_μ)\n\tsorted_names_def = abbr_names[sorted_def]\nend\n\n# ╔═╡ 539e68b4-2066-11eb-09c2-b337241c36bc\nbegin\n\tscatter(1:20, teams_def_μ[sorted_def], grid=false, legend=false, yerror=teams_def_σ[sorted_def], color=:blue, title=\"Premier league 17/18 teams defence power\")\n\tannotate!(collect(1:20), teams_def_μ[sorted_def] .+ 0.2, text.(sorted_names_def, :black, :center, 8))\n\tylabel!(\"Mean team defence\")\nend\n\n# ╔═╡ 69e7e54c-2067-11eb-21a1-cb72f4b423cd\nmd\"To read this graph we have to remember that the defense effect is better the more negative it is, since it is representing the scoring rate that takes away from the opponent team. As we already said:\"\n\n# ╔═╡ f59d488a-2067-11eb-1d4b-1d9dd97ea39e\nmd\"$θ_{team1} \\sim att_{team1} + def_{team2}$\"\n\n# ╔═╡ 27d5a290-2068-11eb-06f5-0b16f6ec6cc5\nmd\"As the $def_{team2}$ is adding up in the equation, if it take negative values, it is going to start substracting the scoring rate of the oponent.\n\nThings, then, begin to make a little more sense. Now we can see that Manchester United is the team with the strongest defence, so being second in the overall is not extrange.\n\nTo gain a deeper understanding of what´s going on here, let's chart both characteristics together. This is going to let us see the combined effect they have. Also i´m going to add the final position of each team to improve the interpretability.\"\n\n# ╔═╡ b8f9bae8-206a-11eb-1426-031f6fd05fd6\nbegin\n\ttable_position = \n\t[11, 5, 9, 4, 13, 14, 1, 15, 12, 6, 2, 16, 10, 17, 20, 3, 7, 8, 19, 18]\n\tposition = sortperm(table_position)\nend\n\n# ╔═╡ ee45d48e-206a-11eb-0edf-2b8b893bb583\nbegin\nscatter(teams_att_μ, teams_def_μ, legend=false)\nannotate!(teams_att_μ, teams_def_μ.+ 0.016, text.(abbr_names, :black, :center, 6))\nannotate!(teams_att_μ, teams_def_μ.- 0.016, text.(position, :left, :center, 5))\n\nxlabel!(\"Mean team attack\")\nylabel!(\"Mean team defence\")\nend\n\n# ╔═╡ c794f45e-206b-11eb-33c4-05bc429ba846\nmd\"Well, great! Now we have some interesting information to analyze the teams and the league in general. It´s easier now to perceive how the two features interact with each other, comparing between teams and being able to see how that affects the final position. \n\nFor example, looking at the cases of Liverpool and Tottenham, or Leicester City and Everton; one could say (against general common sense) that the power of defense has a greater effect on the performance of each team than the attack. But we leave you to do those analysis for the betting house.\n\nWell, we went from having a problem that seemed almost impossible to have a solid solution, with a quantitative analysis of the characteristics of each team. We even know how much the localization of the teams increases the scoring rate. We were able to achieve this thanks to the hierarchical framework that Bayesianism provides us. Using this tool allows us to create models proposing latent variables that cannot be observed, to infer them and to gain a much deeper and more generalized knowledge than we had at first. You just have to imagine a good story.\"\n\n# ╔═╡ fcb7e8d2-2071-11eb-020d-7bb1d53f8a6d\nmd\"### Bibliography \n\n- [Paper of Gianluca Baio and Marta A. Blangiardo](https://discovery.ucl.ac.uk/id/eprint/16040/1/16040.pdf)\n- [Post of Daniel Weitzenfeld](http://danielweitzenfeld.github.io/passtheroc/blog/2014/10/28/bayes-premier-league/)\n\n\"\n\n# ╔═╡ fac413ec-5684-11eb-3167-d56d967247fc\nmun_att_post = collect(get(posterior, :att)[:att])[5][:,1];\n\n# ╔═╡ cc6681a2-5688-11eb-1d8e-e1edcb80a20d\nmun_def_post = collect(get(posterior, :def)[:def])[5][:,1];\n\n# ╔═╡ f01e7438-5688-11eb-2900-8df62e9feb18\nliv_att_post = collect(get(posterior, :att)[:att])[4][:,1];\n\n# ╔═╡ fae4e938-5688-11eb-3ab8-e3a8a4a61692\nliv_def_post = collect(get(posterior, :def)[:def])[4][:,1];\n\n# ╔═╡ 84d5e7a2-56dc-11eb-0d54-b790c7c714fb\n\n\n# ╔═╡ 7704b9e6-56a0-11eb-0ade-2194a0845f61\npost_home;\n\n# ╔═╡ 03f063cc-5689-11eb-3d90-b7a5991332ba\n# This function simulates matches given the attach, defense and home parameters.\n# The first pair of parameters alwas correspond to the home team.\nfunction simulate_matches_(att₁, def₁, att₂, def₂, home, n_matches, home_team=1)\n\tif home_team == 1\n\t\tlogθ₁ = home + att₁ + def₂\n\t\tlogθ₂ = att₂ + def₁\n\t\t\t\t\n\telseif home_team == 2\n\t\tlogθ₁ = att₁ + def₂\n\t\tlogθ₂ = home + att₂ + def₁\n\telse\n\t\treturn DomainError(home_team, \"Invalid home_team value\")\n\tend\n\t\n\tscores₁ = rand(LogPoisson(logθ₁), n_matches)\n\tscores₂ = rand(LogPoisson(logθ₂), n_matches)\n\t\n\tresults = [(s₁, s₂) for (s₁, s₂) in zip(scores₁, scores₂)]\n\t\n\treturn results\nend\n\n# ╔═╡ a8a9179c-5693-11eb-1758-e7d34722c7fa\nmat = simulate_matches_(0.2, -0.1, 0.4, -0.3, 0.2, 1000, 2)\n\n# ╔═╡ 7e82f15c-5695-11eb-20f1-85763cbfa572\nmax_h = maximum(map(x -> x[1], mat))\n\n# ╔═╡ bd11306c-5697-11eb-22ed-99ae7703be59\nmax_a = maximum(map(x -> x[2], mat))\n\n# ╔═╡ d99e52fa-5697-11eb-12fe-ab4ae36ab362\nfunction simulate_matches(team1_att_post, team1_def_post, team2_att_post,\t\t\t\tteam2_def_post, home_post, n_matches)\n\t\n\tteam1_as_home_results = Tuple{Int64,Int64}[]\n\tteam2_as_home_results = Tuple{Int64,Int64}[]\n\t\n\tfor (t1_att, t1_def, t2_att, t2_def, home) in zip(team1_att_post, team1_def_post, team2_att_post, team2_def_post, home_post)\n\t\t\n\t\tteam1_as_home_results = vcat(team1_as_home_results, simulate_matches_(t1_att, t1_def, t2_att, t2_def, home, n_matches, 1))\n\t\t\n\t\tteam2_as_home_results = vcat(team2_as_home_results, simulate_matches_(t1_att, t1_def, t2_att, t2_def, home, n_matches, 2))\n\tend\n\t\n\treturn team1_as_home_results, team2_as_home_results\nend\n\n# ╔═╡ 5a3d6966-56a0-11eb-0db1-c5a06ea2dd83\nkjj, kjjj = simulate_matches(mun_att_post, mun_def_post, liv_att_post, liv_def_post, post_home, 1000)\n\n# ╔═╡ 9d1f1e7e-56a1-11eb-2539-f5da33710a32\nfunction match_heatmaps(team1_as_home_results, team2_as_home_results)\n\t\n\tmax_t1_as_home = maximum(map(x -> x[1], team1_as_home_results))\n\tmax_t2_as_away = maximum(map(x -> x[2], team1_as_home_results))\n\t\n\tmax_t1_as_away = maximum(map(x -> x[1], team2_as_home_results))\n\tmax_t2_as_home = maximum(map(x -> x[2], team2_as_home_results))\n\t\n\tmatrix_t1_as_home = zeros(Int64, (max_t1_as_home + 1, max_t2_as_away + 1))\n\tmatrix_t2_as_home = zeros(Int64, (max_t1_as_away + 1, max_t2_as_home + 1))\n\t\n\tfor match in team1_as_home_results\n\t\tmatrix_t1_as_home[match[1] + 1, match[2] + 1] += 1\n\tend\n\t\n\tfor match in team2_as_home_results\n\t\tmatrix_t2_as_home[match[1] + 1, match[2] + 1] += 1\n\tend\n\t\n\tgr()\n\t#heat_t1_home = heatmap(0:max_t1_as_home,\n\theatmap(0:max_t1_as_home,\n\t\t\t\t\t\t\t\t0:max_t2_as_away,\n\t\t\t\t\t\t\t\tmatrix_t1_as_home,\n\t\t\t\t\t\t\t\tc=cgrad([:blue, :white,:red, :yellow]),\n\t\t\t\t\t\t\t\txlabel=\"Team1 score\", ylabel=\"Team2 score\",\n\t\t\t\t\t\t\t\ttitle=\"Team1 as home\")\n\tsavefig(\"./t1_as_home\")\n\t\n\t#heat_t2_home = heatmap(0:max_t1_as_away,\n\theatmap(0:max_t1_as_away,\n\t\t\t\t\t\t\t\t0:max_t2_as_home,\n\t\t\t\t\t\t\t\tmatrix_t2_as_home,\n\t\t\t\t\t\t\t\tc=cgrad([:blue, :white,:red, :yellow]),\n\t\t\t\t\t\t\t\txlabel=\"Team1 Score\", ylabel=\"Team2 Score\",\n\t\t\t\t\t\t\t\ttitle=\"Team2 as home\")\n\tsavefig(\"./t2_as_home\")\n\t#plot(heat_t1_home, heat_t2_home, layout=(2,1), size=(900, 400))\n\t#current()\n\t\n\treturn matrix_t1_as_home, matrix_t2_as_home\nend\n\n# ╔═╡ d7bfc106-56d0-11eb-21b3-3b9036905041\nm_1_home, m_t2_home = match_heatmaps(kjj, kjjj)\n\n# ╔═╡ 9ceba0fa-56d4-11eb-2696-21f4babf699c\nbegin\n\tgr()\n\theatmap(collect(0:(size(m_t2_home, 1)-1)),\t\t\n\t\t\tcollect(0:(size(m_t2_home, 2)-1)),\t\n\t\t\tm_t2_home,\n\t\t\tc=cgrad([:blue, :white,:red, :yellow]),\n\t\t\txlabel=\"Team1 score\", ylabel=\"Team2 score\",\n\t\t\ttitle=\"Team1 as home\")\nend\n\n# ╔═╡ 0da9d3a0-56d5-11eb-08a9-c9e83106dfc3\nm_t1_home\n\n# ╔═╡ db8ed140-5735-11eb-2078-2f90d15d6325\n\"hola\"\n\n# ╔═╡ Cell order:\n# ╟─2414104e-1d41-11eb-37cb-9b5cee78a98b\n# ╟─3b7f8a1e-1d42-11eb-1ab1-c11fda416e80\n# ╟─4e4385b4-203b-11eb-0c5b-cbe41156401b\n# ╟─2dca2f42-203b-11eb-2cb3-0d6a3823cdcd\n# ╠═a4f0a914-1ec9-11eb-3c22-db87a9776aaa\n# ╠═0c0268dc-1ed3-11eb-2f73-b3706305b298\n# ╠═cbaaf72c-1eb4-11eb-3509-932b337f270b\n# ╠═ab6fcb22-1ed2-11eb-2749-3bef16911972\n# ╠═d2a81a14-1ed2-11eb-1307-bfb169aebbb4\n# ╠═dd80fc38-1ed2-11eb-0e8c-49859d27c72c\n# ╠═7f0c72d4-1f9e-11eb-06f1-cb587d7e5436\n# ╟─868e5c8c-1ed3-11eb-291c-fb26d512c103\n# ╟─04a8f16c-1ed5-11eb-3979-af35c6d9dea1\n# ╟─9f1e1618-1edb-11eb-02af-9fa5c8904163\n# ╟─42104900-1f80-11eb-019f-a7c561ca3e4b\n# ╟─9d0f3a1e-1f80-11eb-3422-fb7b4696cc13\n# ╟─0b1f9c68-1f83-11eb-11e7-e7614c021c05\n# ╟─043c438c-1f84-11eb-2cd7-6dd07a125910\n# ╟─4a31541e-1f97-11eb-038e-736446224c21\n# ╟─e3a99868-1f97-11eb-1872-79c8f6abe1be\n# ╟─c3ca1cc4-1f98-11eb-3c23-33acb95fbc03\n# ╟─4106e55a-1f99-11eb-110e-b79221774f12\n# ╟─bff4fdae-1f99-11eb-2d94-aba7bf9d097f\n# ╟─2b135202-1fa7-11eb-324d-93a5eda41e3e\n# ╟─ddc7b166-203a-11eb-0ac2-056c309bb590\n# ╟─8e164be0-203b-11eb-293a-6b32dba96133\n# ╠═5f83510e-1fc5-11eb-3c40-83a844bf2907\n# ╠═51a309bc-2033-11eb-10c0-ed17545df33d\n# ╟─f3f0b6f8-2033-11eb-0f9e-d951d791001d\n# ╠═f3f4bfba-203f-11eb-142c-a187112744d2\n# ╠═2ce4435c-2040-11eb-1670-e39ad4cc690c\n# ╠═9e50e56e-5674-11eb-2919-4bde8964bc59\n# ╟─8c1dd9de-2040-11eb-35a3-39e8196577a1\n# ╟─0f9406ae-2054-11eb-3f0c-1d03ba779f18\n# ╟─099e4188-2054-11eb-1e7e-69bdb2b0202c\n# ╠═16572944-2045-11eb-38d0-fb20d981e3e9\n# ╠═93d3bf98-5684-11eb-361e-c7b0f1a3bb0e\n# ╠═18f36e1a-5682-11eb-2826-ab4d4c457af3\n# ╠═6f096138-5682-11eb-179f-f973803b9268\n# ╟─8cec9318-206e-11eb-3caa-3bad9d788d3c\n# ╠═4ae7d968-206f-11eb-1925-c5b5a31e6940\n# ╠═8b77d12c-206f-11eb-19a5-f557157ac05e\n# ╟─b56df7ea-206f-11eb-18b9-0544cc596ca5\n# ╠═554b4ef0-2045-11eb-3218-050ec936f1aa\n# ╟─8a4df438-2045-11eb-2798-af592dbbffb5\n# ╠═6b1a1520-2045-11eb-1302-0778b4e7a836\n# ╟─da93bf52-2045-11eb-2b6f-3f31f57d8653\n# ╠═1fa92570-2046-11eb-3541-e5fccf7afabd\n# ╠═255c4d08-2046-11eb-1cf0-b32d2cd711bf\n# ╠═473e6a46-205b-11eb-2731-7b47b99d86a5\n# ╟─917d4550-2058-11eb-174b-65436a4e6cc8\n# ╠═c2de4714-2058-11eb-1a0d-f1bf96649844\n# ╠═0103406e-2059-11eb-333f-7b5814f21a54\n# ╠═579a4d9e-205b-11eb-2352-83beca145211\n# ╟─6924f372-2059-11eb-2b98-6f4b65b777f4\n# ╠═ece1d052-2060-11eb-2b50-ef46663ed88f\n# ╟─43a39b30-2061-11eb-28c5-37cbc4aed84b\n# ╠═41ca2316-2062-11eb-3fe6-f33a789fd578\n# ╟─0ef8a16e-2063-11eb-1391-6b3b959de541\n# ╠═1eb73246-2063-11eb-0f20-416e433b5144\n# ╠═abace764-2062-11eb-2949-fd9e86b50f17\n# ╟─ebd267a4-2064-11eb-02a7-b93465de6319\n# ╠═f6ad5f52-2065-11eb-0be7-f159941e0d89\n# ╠═539e68b4-2066-11eb-09c2-b337241c36bc\n# ╟─69e7e54c-2067-11eb-21a1-cb72f4b423cd\n# ╟─f59d488a-2067-11eb-1d4b-1d9dd97ea39e\n# ╟─27d5a290-2068-11eb-06f5-0b16f6ec6cc5\n# ╠═b8f9bae8-206a-11eb-1426-031f6fd05fd6\n# ╠═ee45d48e-206a-11eb-0edf-2b8b893bb583\n# ╟─c794f45e-206b-11eb-33c4-05bc429ba846\n# ╟─fcb7e8d2-2071-11eb-020d-7bb1d53f8a6d\n# ╠═fac413ec-5684-11eb-3167-d56d967247fc\n# ╠═cc6681a2-5688-11eb-1d8e-e1edcb80a20d\n# ╠═f01e7438-5688-11eb-2900-8df62e9feb18\n# ╠═fae4e938-5688-11eb-3ab8-e3a8a4a61692\n# ╠═84d5e7a2-56dc-11eb-0d54-b790c7c714fb\n# ╠═7704b9e6-56a0-11eb-0ade-2194a0845f61\n# ╠═03f063cc-5689-11eb-3d90-b7a5991332ba\n# ╠═a8a9179c-5693-11eb-1758-e7d34722c7fa\n# ╠═7e82f15c-5695-11eb-20f1-85763cbfa572\n# ╠═bd11306c-5697-11eb-22ed-99ae7703be59\n# ╠═d99e52fa-5697-11eb-12fe-ab4ae36ab362\n# ╠═5a3d6966-56a0-11eb-0db1-c5a06ea2dd83\n# ╠═9d1f1e7e-56a1-11eb-2539-f5da33710a32\n# ╠═d7bfc106-56d0-11eb-21b3-3b9036905041\n# ╠═9ceba0fa-56d4-11eb-2696-21f4babf699c\n# ╠═0da9d3a0-56d5-11eb-08a9-c9e83106dfc3\n# ╠═db8ed140-5735-11eb-2078-2f90d15d6325\n", "meta": {"hexsha": "39b66e7fd31e105849066a81e87403d74f1019b1", "size": 30672, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "football_simulation_chapter/football-analysis-chapter.jl", "max_stars_repo_name": "lambdaclass/julia_playground", "max_stars_repo_head_hexsha": "53e50d251e752d77c0f1cba4ac559db45d45bb01", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "football_simulation_chapter/football-analysis-chapter.jl", "max_issues_repo_name": "lambdaclass/julia_playground", "max_issues_repo_head_hexsha": "53e50d251e752d77c0f1cba4ac559db45d45bb01", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "football_simulation_chapter/football-analysis-chapter.jl", "max_forks_repo_name": "lambdaclass/julia_playground", "max_forks_repo_head_hexsha": "53e50d251e752d77c0f1cba4ac559db45d45bb01", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.5074183976, "max_line_length": 666, "alphanum_fraction": 0.7565858112, "num_tokens": 11142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.10521054231434403, "lm_q1q2_score": 0.05137256082216398}} {"text": "f(x) = x + 100\n\nmacro g() # According to Julia docs, ...\n :(f(x) + 5) # ... f is global, x is local, right?\nend # if so, f should refer to the f above?\n\n(function main()\n local x = 3\n f(x) = x - 100 # f in the call environment subtracts 100\n# println(@g()) # So why does this do -92?\nend)()\n", "meta": {"hexsha": "f71de03d26b7e90564930575a83df2a8503c3496", "size": 324, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "julia/eval_and_scope.jl", "max_stars_repo_name": "idrougge/ple", "max_stars_repo_head_hexsha": "fcf645e23fec68fea93a068eb3bb78a88ca8af46", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 59, "max_stars_repo_stars_event_min_datetime": "2016-10-27T03:33:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T06:10:10.000Z", "max_issues_repo_path": "julia/eval_and_scope.jl", "max_issues_repo_name": "idrougge/ple", "max_issues_repo_head_hexsha": "fcf645e23fec68fea93a068eb3bb78a88ca8af46", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2017-01-07T19:27:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-10T21:29:59.000Z", "max_forks_repo_path": "julia/eval_and_scope.jl", "max_forks_repo_name": "idrougge/ple", "max_forks_repo_head_hexsha": "fcf645e23fec68fea93a068eb3bb78a88ca8af46", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2016-09-20T16:22:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-15T09:28:06.000Z", "avg_line_length": 27.0, "max_line_length": 59, "alphanum_fraction": 0.5339506173, "num_tokens": 106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.10374862132405094, "lm_q1q2_score": 0.051063840513087405}} {"text": "\r\n\"\"\"\r\n nullgraph!(net)\r\n\r\nRemove all nodes and links from the network. \r\n\r\nThe first argument *net* is a FastNet structure that is be used in the simulation. \r\n\r\n# Examples \r\n```jldoctest\r\njulia> using Fastnet\r\n\r\njulia> net=FastNet(1000,2000,1,[])\r\nNetwork of 0 nodes and 0 links\r\n\r\njulia> randomgraph!(net)\r\nNetwork of 1000 nodes and 2000 links\r\n\r\njulia> nullgraph!(net)\r\nNetwork of 0 nodes and 0 links\r\n```\r\n\"\"\"\r\nfunction nullgraph!(net::FastNet)\r\n while countnodes_f(net)>0\r\n destroynode_f!(net,net.nid[1])\r\n end\r\n net\r\nend\r\n\r\n\"\"\"\r\n randomgraph!(net;)\r\n\r\nCreate an ER random graph in the network *net*. \r\n\r\nThe network isn't guaranteed to be a simple graph, but in large sparse \r\nnetworks it is simple with high probability. \r\n\r\nBy default all nodes and links that the network can accommodate will be used and \r\nall nodes will be set to state one. This behavior can be controlled by the following \r\nkeyword arguments:\r\n\r\n- N : The number of nodes that will be used in the creation of the random graph.\r\n All other nodes will be removed from the network. \r\n- K : The number of links that will be used in the creation of the random graph.\r\n All other links will be removed from the network. \r\n- S : The state of the nodes. All nodes will be set to this state. \r\n\r\n# Examples \r\n```jldoctest\r\njulia> using Fastnet\r\n\r\njulia> net=FastNet(1000,2000,1,[])\r\nNetwork of 0 nodes and 0 links\r\n\r\njulia> randomgraph!(net)\r\nNetwork of 1000 nodes and 2000 links\r\n\r\njulia> nullgraph!(net)\r\nNetwork of 0 nodes and 0 links\r\n\r\njulia> randomgraph!(net,N=100,K=10)\r\nNetwork of 100 nodes and 10 links\r\n```\r\n\"\"\"\r\nfunction randomgraph!(net::FastNet; N::Int=0,K::Int=0,S::Int=1)\r\n nullgraph!(net)\r\n n=N;\r\n k=K;\r\n s=S;\r\n if n===0\r\n n=net.N\r\n end \r\n if k===0\r\n k=net.K\r\n end\r\n if n<1 && k>0\r\n throw(ArgumentError(\"In order to create links the net has to have at least one node\"))\r\n end\r\n if n>net.N\r\n throw(ArgumentError(\"Trying to create more nodes than maximum allowed by the net\"))\r\n end\r\n if k>net.K\r\n throw(ArgumentError(\"Trying to create more links than maximum allowed by the net\"))\r\n end\r\n if s<1 || s>net.C-1\r\n msg=\"The net passed to randomgraph! only supports node states between 1 and $(net.C-1),\"\r\n msg*=\" but you are asking it to set nodes to state $s.\"\r\n throw(ArgumentError(msg))\r\n end\r\n makenodes!(net,n,s)\r\n for i=1:k\r\n src=randomnode_f(net,s)\r\n dst=randomnode_f(net,s)\r\n makelink_f!(net,src,dst)\r\n end\r\n net\r\nend\r\n\r\n\r\n\"\"\"\r\n configmodel!(net::FastNet,degreedist;)\r\n\r\nCreate a configuration model style network with prescribed degree distribution, *degreedist*.\r\n\r\nThe network in *net* is replaced with the new topology. The degree distribution is specified in \r\nterms of a vector of Float64 variables such that *degreedist[k]* is specifies, pk, the probability\r\nthat a randomly drawn node has degree k. If the elements of *degreedist* add up to less than 1.0 the \r\nremaining nodes will have degree zero. \r\n \r\nThe network generation is fast and unbiased but isn't guaranteed to result in a simple graph. \r\nThe algorithm will try to match the desired degree distribution as closely as possible,\r\nbut small discrepancies can appear if the degree distribution would result in an odd degree sum \r\nor non integer numbers of nodes of certain degrees. \r\n\r\nIf there FastNet is not large enough to accomodate the desired number of links or nodes an argument error \r\nwill be thrown. \r\n\r\nThe keyword arguments are \r\n- N : The number of nodes that will be used in the creation of the network\r\n- S : The state of the nodes. All nodes will be set to this state. \r\n\r\n# Examples \r\n```jldoctest\r\njulia> using Fastnet\r\n\r\njulia> net=FastNet(1000,2000,2,[])\r\nNetwork of 0 nodes and 0 links\r\n\r\njulia> configmodel!(net,[0.5,0.25,0.25],N=200)\r\nNetwork of 200 nodes and 175 links\r\n\r\njulia> degreedist(net)\r\n3-element Vector{Float64}:\r\n 0.5\r\n 0.25\r\n 0.25\r\n\r\njulia> configmodel!(net,[0.5,0.25],N=200)\r\nNetwork of 200 nodes and 100 links\r\n\r\njulia> degreedist(net)\r\n2-element Vector{Float64}:\r\n 0.5\r\n 0.25\r\n```\r\n\"\"\"\r\nfunction configmodel!(net::FastNet,degreedist;N=0,S=1)\r\n (counts,totalstubs)=_configmodelsetup!(net,degreedist,N,S)\r\n nn=sum(counts);\r\n l=length(counts)\r\n nde=Array{Int,1}(undef,totalstubs)\r\n curnode=1\r\n curstub=1\r\n for i=1:l\r\n for j=1:counts[i]\r\n for s=1:i\r\n nde[curstub]=curnode\r\n curstub+=1\r\n end\r\n curnode+=1\r\n end\r\n end\r\n cutoff=totalstubs\r\n rng=net.rng\r\n while cutoff>1\r\n stub=rand(rng,1:cutoff)\r\n src=node_f(net,nde[stub])\r\n nde[stub]=nde[cutoff]\r\n cutoff-=1\r\n stub=rand(rng,1:cutoff)\r\n dst=node_f(net,nde[stub])\r\n nde[stub]=nde[cutoff]\r\n cutoff-=1\r\n makelink_f!(net,src,dst)\r\n end\r\n net\r\nend\r\n\r\n\r\n\"\"\"\r\n regulargraph!(net::FastNet,deg;)\r\n\r\nCreate a regular graph with node degree *deg*. \r\n\r\nThe network in *net* is replaced with the new topology in which all nodes have degree *deg*\r\nand are randomly connected. If the number of nodes is not specified the function will\r\ntry to use all nodes allowed by net. \r\n \r\nThe network generation is fast and unbiased, but isn't guaranteed to result in a simple graph. \r\n\r\nNote that finite regular graphs with odd node degree and odd number of nodes do not exist. Hence \r\neither *deg* or the number of nodes must be even. \r\n\r\nIf there FastNet is not large enough to accomodate the desired number of links or nodes an argument error \r\nwill be thrown. \r\n\r\nThe keyword arguments are \r\n- N : The number of nodes that will be used in the creation of the network\r\n- S : The state of the nodes. All nodes will be set to this state. \r\n\r\n# Examples \r\n```jldoctest\r\njulia> using Fastnet\r\n\r\njulia> net=FastNet(1000,2000,2,[])\r\nNetwork of 0 nodes and 0 links\r\n\r\njulia> regulargraph!(net,4)\r\nNetwork of 1000 nodes and 2000 links\r\n\r\njulia> degreedist(net)\r\n4-element Vector{Float64}:\r\n 0.0\r\n 0.0\r\n 0.0\r\n 1.0\r\n```\r\n\"\"\"\r\nfunction regulargraph!(net::FastNet,deg;N=0,S=1)\r\n s=0\r\n n=0\r\n d=0\r\n try \r\n s=convert(Int,S)\r\n catch e\r\n throw(ArgumentError(\"regulargraph expects s to be an integer\"))\r\n end\r\n try \r\n n=convert(Int,N)\r\n catch e\r\n throw(ArgumentError(\"regulargraph expects N to be an integer\"))\r\n end\r\n try \r\n d=convert(Int,deg)\r\n catch e\r\n throw(ArgumentError(\"regulargraph expects deg to be an integer\"))\r\n end\r\n if n==0\r\n n=net.N\r\n end\r\n checknodestate(net,s,\"Trying to create regular graph\")\r\n if n<1\r\n throw(ArgumentError(\"regulargraph expects number of nodes n to be positive\"))\r\n end\r\n if d<0\r\n throw(ArgumentError(\"regulargraph expects nodedegree deg to be non-negative\"))\r\n end\r\n if n>net.N\r\n throw(ArgumentError(\"Requested size for regulargraph exceeds max node count of underlyng FastNet\"))\r\n end\r\n if (n*d)÷2>net.K\r\n throw(ArgumentError(\"Requested regulargraph exceeds max link count of underlyng FastNet\"))\r\n end\r\n if isodd(n) && isodd(d)\r\n throw(ArgumentError(\"A regular graph of odd node degree must have an even number of nodes.\"))\r\n end\r\n nullgraph!(net)\r\n makenodes!(net,n,s)\r\n totalstubs=n*d\r\n nde=Array{Int,1}(undef,totalstubs)\r\n for i=1:totalstubs\r\n nde[i]=((i-1)÷deg)+1 \r\n end\r\n cutoff=totalstubs\r\n rng=net.rng\r\n while cutoff>0\r\n srcs=rand(rng,1:cutoff) # pick the source\r\n src=node_f(net,nde[srcs])\r\n nde[srcs]=nde[cutoff]\r\n cutoff-=1\r\n dsts=rand(rng,1:cutoff) # pick the source\r\n dst=node_f(net,nde[dsts])\r\n nde[dsts]=nde[cutoff]\r\n cutoff-=1\r\n makelink_f!(net,src,dst)\r\n end\r\n net\r\nend\r\n\r\n\"\"\"\r\n rectlattice!(net::FastNet,dims, )\r\n\r\nCreate a rectangular lattice with given dimensions *dims*. \r\n\r\nThe network in *net* is replaced with the new topology, that is a lattice specified by dims. \r\n*dims* can be a number, in this case it indicates the number of nodes to be arranged into a 1D lattice. \r\nAlternatively, *dims* can be a vector of Ints. In this case the dimension of the lattice is identical to the \r\nlength of *dims* and each element of *dims* specifies the length of the lattice in one of these dimensions. \r\n\r\nIf there FastNet is not large enough to accomodate the desired number of nodes or links an argument error \r\nwill be thrown. \r\n\r\nKeyword arguments are \r\n- periodic : If this argument is true the lattice is generated with periodic boundary conditions in all dimensions. \r\n Alternatively a Vector of Bool of the same length as *dims* can be supplied. In this case the n'th argument of \r\n the vector specifies if the lattice is periodic in the n'th dimension. \r\n- S : The state of the nodes. All nodes will be set to this state. \r\n\r\n# Examples \r\n```jldoctest\r\njulia> using Fastnet\r\n\r\njulia> net=FastNet(2000,6000,2,[])\r\nNetwork of 0 nodes and 0 links\r\n\r\njulia> rectlattice!(net,[10,20,10],periodic=[true,false,true])\r\nNetwork of 2000 nodes and 5900 links\r\n\r\njulia> degreedist(net)\r\n6-element Vector{Float64}:\r\n 0.0\r\n 0.0\r\n 0.0\r\n 0.0\r\n 0.1\r\n 0.9\r\n```\r\n\"\"\"\r\nfunction rectlattice!(\r\n net ::FastNet,\r\n dims ::Union{Int,Tuple,AbstractVector};\r\n S ::Integer=1,\r\n periodic ::Union{AbstractArray,Bool,Tuple}=false\r\n )\r\n task=\"Trying to create a rectangular lattice\"\r\n d=[dims...]\r\n nd=length(d)\r\n per=[false]\r\n if isa(periodic,Bool)\r\n per=fill(periodic,nd)\r\n else\r\n per=[periodic...]\r\n end\r\n if length(per)!=length(d)\r\n throw(ArgumentError(task*\", but the number of values passed for parameter periodic does not agree with dims\"))\r\n end\r\n for x in per\r\n if !isa(x,Bool)\r\n throw(ArgumentError(task*\", but $x in periodic is not of type Bool\"))\r\n end\r\n end\r\n n=1\r\n s=checknodestate(net,S,task)\r\n for i=1:nd\r\n n*=d[i]\r\n end\r\n nullgraph!(net)\r\n makenodes!(net,n,s)\r\n linksneeded=0\r\n for i=1:nd\r\n linksneeded+=n \r\n if !per[i]\r\n linksneeded-=n÷d[i]\r\n end\r\n end \r\n for i=1:n\r\n lowmult=1\r\n for j=1:nd\r\n if ((i-1)÷lowmult)%d[j]==d[j]-1\r\n if per[j]\r\n src=node_f(net,i)\r\n dst=node_f(net,i+lowmult-d[j]*lowmult) \r\n makelink_f!(net,src,dst)\r\n end\r\n else\r\n src=node_f(net,i)\r\n dst=node_f(net,i+lowmult)\r\n makelink_f!(net,src,dst)\r\n end\r\n lowmult*=d[j]\r\n end \r\n end\r\n net\r\nend\r\n\r\n\"\"\"\r\n adjacency!(net,mat;S=1)\r\n\r\nCreate a network with given adjacency matrix.\r\n\r\nThe network in *net* is replaced with the new topology that is specified by the adjacency matrix *mat*. \r\nIf direction of links matters note that the element *mat[i,j]* corresponds to the link from j to i. \r\n\r\nSymmeric matrices will not result in parallel links, instead the link is placed in an arbitrary direction. \r\n\r\nNote that node *n* in the matrix will be the node in position *n* in *net* after creation, which is \r\nnot necessarily the node with ID *n*, if you need to find a particular node at a later time then it\r\nis best to save its id using the node(net,pos) function directly after calling adjacency!(net,mat). \r\n\r\nIf *net* is not large enough to accomodate the desired number of nodes or links an argument error \r\nwill be thrown. \r\n\r\nKeyword arguments are \r\n- S : The state of the nodes. All nodes will be set to this state. \r\n\r\n# Examples \r\n```jldoctest\r\njulia> using Fastnet\r\n\r\njulia> net=FastNet(1000,2000,2,[])\r\nNetwork of 0 nodes and 0 links\r\n\r\njulia> mat=[0 1 0; 1 0 1; 0 1 0]\r\n3×3 Matrix{Int64}:\r\n 0 1 0\r\n 1 0 1\r\n 0 1 0\r\n\r\njulia> adjacency!(net,mat)\r\nNetwork of 3 nodes and 2 links\r\n```\r\n\"\"\"\r\nfunction adjacency!(\r\n net ::FastNet,\r\n mat ::AbstractMatrix;\r\n S ::Integer=1\r\n )\r\n task=\"Trying to create topology from adjacency matrix\"\r\n x,y=size(mat)\r\n if x!=y\r\n err=task*\", but adjacency! expects a square matrix as its second argument and received a rectangular one\"\r\n throw(ArgumentError(err)) \r\n end\r\n if x>net.N \r\n throw(ArgumentError(task*\", but the matrix is larger than the maximum number of allowed nodes by the network\")) \r\n end\r\n s=checknodestate(net,S,task)\r\n count=0\r\n b1=false\r\n b2=false\r\n for i=1:x-1\r\n for j=i+1:x\r\n try \r\n b1=convert(Bool,mat[i,j])\r\n b2=convert(Bool,mat[i,j])\r\n catch e\r\n throw(ArgumentError(task*\", but was unable to convert an element of mat to Bool\"))\r\n end\r\n if b1||b2\r\n count+=1 \r\n end\r\n end\r\n end\r\n if count>net.K\r\n throw(ArgumentError(task*\", but the matrix contains more links than permitted by net\"))\r\n end\r\n nullgraph!(net)\r\n makenodes!(net,x,s)\r\n for i=1:x\r\n dst=node_f(net,i)\r\n for j=i+1:x\r\n src=node_f(net,j)\r\n linked::Bool = mat[i,j]\r\n if linked\r\n makelink_f!(net,src,dst) \r\n else \r\n linked = mat[j,i]\r\n if linked\r\n makelink_f!(net,dst,src) \r\n end\r\n end\r\n end\r\n end\r\n net\r\nend\r\n\r\n### WIP\r\nfunction configmodel_DG!(net::FastNet,degreedist,N::Int=0,S::Int=1)\r\n (counts,totalstubs)=_configmodelsetup!(net,degreedist,N,S) \r\n\r\n println(\"On track\")\r\nend\r\n\r\n\"\"\"\r\n randomgeometricgraph!(net::FastNet; N::Int,K::Int,S::Int, dim::Int, deg::Float64)\r\n\r\nCreate a random geometric graph with mean degree *deg*. \r\n\r\nThe network in *net* is replaced with the new topology in which each node has *dim* vector entries uniformly drawn\r\nfrom (0,1). A maximal connection distance is calculated from the given mean degree and nodes get connected,\r\nwhen their euclidean distance is smaller than the maximal connection distance. \r\n\r\nIf there FastNet is not large enough to accomodate the desired number of links or nodes an argument error \r\nwill be thrown.\r\n\r\nAdditionaly, if the calculated maximal connection distance results in more links being generated than supported by the net,\r\nan argument error will be thrown as well.\r\n\r\nThe keyword arguments are \r\n- N : The number of nodes that will be used in the creation of the network\r\n- S : The state of the nodes. All nodes will be set to this state.\r\n- dim : Dimensions of the random geometric graph.\r\n- deg : The graph´s mean degree which is used to calculate the maximal connection distance between nodes.\r\n\r\n# Examples \r\n```jldoctest\r\njulia> using Fastnet\r\n\r\njulia> net=FastNet(1000,2000,2,[])\r\nNetwork of 0 nodes and 0 links\r\n\r\njulia> randomgeometricgraph!(net,dim=2,meandegree=2.0)\r\nNetwork of 1000 nodes and 970 links\r\n\r\n```\r\n\"\"\"\r\nfunction randomgeometricgraph!(net::FastNet; N::Int=0,K::Int=0,S::Int=1, dim::Int=2, deg::Float64=2.0)\r\n nullgraph!(net)\r\n n=N;\r\n k=K;\r\n s=S;\r\n if n===0\r\n n=net.N\r\n end \r\n if k===0\r\n k=net.K\r\n end\r\n if n<1 && k>0\r\n throw(ArgumentError(\"In order to create links the net has to have at least one node\"))\r\n end\r\n if n>net.N\r\n throw(ArgumentError(\"Trying to create more nodes than maximum allowed by the net\"))\r\n end\r\n if k>net.K\r\n throw(ArgumentError(\"Trying to create more links than maximum allowed by the net\"))\r\n end\r\n if s<1 || s>net.C-1\r\n msg=\"The net passed to randomgeometricgraph! only supports node states between 1 and $(net.C-1),\"\r\n msg*=\" but you are asking it to set nodes to state $s.\"\r\n throw(ArgumentError(msg))\r\n end\r\n\r\n r = (1/2)*((deg/n) * double_factorial(dim) / (pi/2)^(floor(dim/2)))^(1/dim)\r\n makenodes!(net,n,s)\r\n loc = rand(n,dim)\r\n for i = 1:n\r\n for j = i+1:n\r\n dist = sqrt(sum((loc[i,:].-loc[j,:]).^2))\r\n if (dist < r)\r\n if countlinks_f(net)>=k\r\n throw(ArgumentError(\"For the given mean degree, you would create more links than allowed by the net\"))\r\n end\r\n makelink_f!(net,i,j)\r\n end\r\n end\r\n end\r\n net\r\nend\r\n\r\nfunction double_factorial(n::Int)\r\n if isodd(n)\r\n k=Int((n+1)/2)\r\n return factorial(2*k-1)/(2^(k-1)*factorial(k-1))\r\n else\r\n k=Int(n/2)\r\n return 2^k*factorial(k)\r\n end\r\nend\r\n\r\n\r\n", "meta": {"hexsha": "116df1823b1ebdee3042f6236845c962b4f3dbfd", "size": 16691, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/nettools.jl", "max_stars_repo_name": "bridgewalker/Quicknet.jl", "max_stars_repo_head_hexsha": "2dc354f0901bb336648245731bb587898b6ad208", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-09-03T08:28:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T19:32:14.000Z", "max_issues_repo_path": "src/nettools.jl", "max_issues_repo_name": "bridgewalker/Quicknet.jl", "max_issues_repo_head_hexsha": "2dc354f0901bb336648245731bb587898b6ad208", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-09-03T07:22:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-13T20:18:26.000Z", "max_forks_repo_path": "src/nettools.jl", "max_forks_repo_name": "bridgewalker/Quicknet.jl", "max_forks_repo_head_hexsha": "2dc354f0901bb336648245731bb587898b6ad208", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-09-03T11:05:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-14T11:56:35.000Z", "avg_line_length": 29.752228164, "max_line_length": 124, "alphanum_fraction": 0.6254867893, "num_tokens": 4544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.10970576660095784, "lm_q1q2_score": 0.05057619919036222}} {"text": "# This file contains SDESystem prototypes\n\nimport DifferentialEquations: LambaEM, SDEProblem\nimport UUIDs: uuid4\n\n\"\"\"\n @def_sde_system ex \n\nwhere `ex` is the expression to define to define a new AbstractSDESystem component type. The usage is as follows:\n```julia\n@def_sde_system mutable struct MySDESystem{T1,T2,T3,...,TN,OP,RH,RO,ST,IP,OP} <: AbstractSDESystem\n param1::T1 = param1_default # optional field \n param2::T2 = param2_default # optional field \n param3::T3 = param3_default # optional field\n ⋮\n paramN::TN = paramN_default # optional field \n drift::DR = drift_function # mandatory field\n diffusion::DF = diffusion_function # mandatory field\n readout::RO = readout_functtion # mandatory field\n state::ST = state_default # mandatory field\n input::IP = input_default # mandatory field\n output::OP = output_default # mandatory field\nend\n```\nHere, `MySDESystem` has `N` parameters. `MySDESystem` is represented by the `drift`, `diffusion` and `readout` function. `state`, `input` and `output` is the initial state, input port and output port of `MySDESystem`.\n\n!!! warning \n `drift` must have the signature \n ```julia\n function drift((dx, x, u, t, args...; kwargs...)\n dx .= .... # update dx\n end\n ```\n and `diffusion` must have the signature \n ```julia\n function diffusion((dx, x, u, t, args...; kwargs...)\n dx .= .... # update dx\n end\n ```\n and `readout` must have the signature \n ```julia\n function readout(x, u, t)\n y = ...\n return y\n end\n ```\n\n!!! warning \n New SDE system must be a subtype of `AbstractSDESystem` to function properly.\n\n# Example \n```julia \njulia> @def_sde_system mutable struct MySDESystem{DR, DF, RO, IP, OP} <: AbstractSDESystem\n η::Float64 = 1.\n drift::DR = (dx, x, u, t) -> (dx .= x)\n diffusion::DF = (dx, x, u, t, η=η) -> (dx .= η)\n readout::RO = (x, u, t) -> x \n state::Vector{Float64} = rand(2) \n input::IP = nothing \n output::OP = Outport(2)\n end\n\njulia> ds = MySDESystem();\n```\n\"\"\"\nmacro def_sde_system(ex) \n checksyntax(ex, :AbstractSDESystem)\n appendcommonex!(ex)\n foreach(nex -> appendex!(ex, nex), [\n :( alg::$ALG_TYPE_SYMBOL = Causal.LambaEM{true}() ), \n :( integrator::$INTEGRATOR_TYPE_SYMBOL = Causal.construct_integrator(Causal.SDEProblem, input, \n (drift, diffusion), state, t, modelargs, solverargs; alg=alg, modelkwargs=modelkwargs, solverkwargs=solverkwargs, numtaps=3) ) \n ])\n quote \n Base.@kwdef $ex \n end |> esc \nend\n\n\n##### Define SDE system library\n\n\"\"\"\n SDESystem(; drift, diffusion, readout, state, input, output) \n\nConstructs a SDE system. \n\"\"\"\n@def_sde_system mutable struct SDESystem{DR, DF, RO, ST, IP, OP} <: AbstractSDESystem \n drift::DR \n diffusion::DF \n readout::RO \n state::ST \n input::IP \n output::OP \nend\n\n@doc raw\"\"\"\n NoisyLorenzSystem() \n\nConstructs a noisy Lorenz system \n\"\"\"\n@def_sde_system mutable struct NoisyLorenzSystem{ET, DR, DF, RO, IP, OP} <: AbstractSDESystem\n σ::Float64 = 10.\n β::Float64 = 8 / 3\n ρ::Float64 = 28.\n η::ET = 1.\n γ::Float64 = 1.\n drift::DR = function lorenzdrift(dx, x, u, t, σ=σ, β=β, ρ=ρ, γ=γ)\n dx[1] = σ * (x[2] - x[1])\n dx[2] = x[1] * (ρ - x[3]) - x[2]\n dx[3] = x[1] * x[2] - β * x[3]\n dx .*= γ\n end\n diffusion::DF = (dx, x, u, t, η=η) -> (dx .= η)\n readout::RO = (x, u, t) -> x\n state::Vector{Float64} = rand(3)\n input::IP = nothing \n output::OP = Outport(3) \nend \n\n@doc raw\"\"\"\n NoisyLorenzSystem() \n\nConstructs a noisy Lorenz system \n\"\"\"\n@def_sde_system mutable struct ForcedNoisyLorenzSystem{ET, CM, DR, DF, RO, IP, OP} <: AbstractSDESystem\n σ::Float64 = 10.\n β::Float64 = 8 / 3\n ρ::Float64 = 28.\n η::ET = 1.\n cplmat::CM = I(3)\n γ::Float64 = 1.\n drift::DR = function forcedlorenzdrift(dx, x, u, t, σ=σ, β=β, ρ=ρ, γ=γ, cplmat=cplmat)\n dx[1] = σ * (x[2] - x[1])\n dx[2] = x[1] * (ρ - x[3]) - x[2]\n dx[3] = x[1] * x[2] - β * x[3]\n dx .*= γ\n dx .+= cplmat * map(ui -> ui(t), u.itp) # Couple inputs\n end\n diffusion::DF = (dx, x, u, t, η=η) -> (dx .= η)\n readout::RO = (x, u, t) -> x\n state::Vector{Float64} = rand(3)\n input::IP = Inport(3) \n output::OP = Outport(3) \nend \n\n\n##### Pretty printing \nshow(io::IO, ds::SDESystem) = print(io, \n \"SDESystem(drift:$(ds.drift), diffusion:$(ds.diffusion), readout:$(ds.readout), state:$(ds.state), t:$(ds.t), \",\n \"input:$(ds.input), output:$(ds.output))\")\nshow(io::IO, ds::NoisyLorenzSystem) = print(io, \n \"NoisyLorenzSystem(σ:$(ds.σ), β:$(ds.β), ρ:$(ds.ρ), η:$(ds.η), γ:$(ds.γ), state:$(ds.state), t:$(ds.t), \",\n \"input:$(ds.input), output:$(ds.output))\")\nshow(io::IO, ds::ForcedNoisyLorenzSystem) = print(io, \n \"ForcedNoisyLorenzSystem(σ:$(ds.σ), β:$(ds.β), ρ:$(ds.ρ), η:$(ds.η), γ:$(ds.γ), cplmat:$(ds.cplmat), \", \n \"state:$(ds.state), t:$(ds.t), input:$(ds.input), output:$(ds.output))\")\n", "meta": {"hexsha": "f6fc4810a113e466868edfb13dedaf22599ce260", "size": 5217, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/components/systems/dynamicalsystems/sdesystems.jl", "max_stars_repo_name": "gs246/Causal.jl", "max_stars_repo_head_hexsha": "a667a24638415710333af760409566cc6f5dc681", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/components/systems/dynamicalsystems/sdesystems.jl", "max_issues_repo_name": "gs246/Causal.jl", "max_issues_repo_head_hexsha": "a667a24638415710333af760409566cc6f5dc681", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/components/systems/dynamicalsystems/sdesystems.jl", "max_forks_repo_name": "gs246/Causal.jl", "max_forks_repo_head_hexsha": "a667a24638415710333af760409566cc6f5dc681", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2292993631, "max_line_length": 217, "alphanum_fraction": 0.5689093349, "num_tokens": 1771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.10230470857690284, "lm_q1q2_score": 0.05035316378992509}}