{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "<img src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/3/39/VU_logo.png/800px-VU_logo.png?20161029201021\" width=\"350\">\n",
    "\n",
    "### Programming large-scale parallel systems\n",
    "### Lectures on Julia for HPC\n",
    "\n",
    "\n",
    "# Tutorial: Getting started with Julia\n",
    "\n",
    "by Francesc Verdugo (VU Amsterdam)\n",
    "\n",
    "Version fall 2022"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Contents\n",
    "\n",
    "- Using the Julia REPL\n",
    "- Running serial and parallel code\n",
    "- Installing and managing packages"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction\n",
    "\n",
    "Julia has its own way of running code and using packages. Many educational sources about Julia assume that you have this basic knowledge, which can be confusing to new users. In this lesson, we will learn these basic skills so that you can start learning more on Julia."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Preliminaries\n",
    "\n",
    "This is a tutorial. To follow it:\n",
    "\n",
    "- Download and install Julia from https://julialang.org/\n",
    "- Download and install VSCode and its Julia extension. How to: https://www.julia-vscode.org/docs/dev/gettingstarted/\n",
    "- Continue reading this document \n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The Julia REPL\n",
    "\n",
    "There are several ways of opening Julia depending on your operating system and your IDE, but it is usually as simple as launching the Julia app. With VSCode, open a folder (File > Open Folder). Then,  press `Ctrl`+`Shift`+`P` to open the command bar, and execute `Julia: Start REPL`. If this does not work, make sure you have the Julia extension for VSCode installed. Independently of the method you use, opening Julia results in a window with some text ending with:\n",
    "\n",
    "```\n",
    "julia> \n",
    "```\n",
    "\n",
    "You have just opened the Julia *read-evaluate-print loop*, or simply the Julia *REPL*. Congrats! You will spend most of time using the REPL, when working in Julia. The REPL is a console waiting for user input. Just as in other consoles, the string of text right before the input area (`julia>` in the case) is called the *command prompt* or simply the *prompt*.\n",
    "\n",
    "\n",
    "The usage is as follows:\n",
    "- You write some input\n",
    "- press enter\n",
    "- you get the output\n",
    "\n",
    "For instance, try this\n",
    "\n",
    "```julia\n",
    "julia> 1 + 1\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Hello world!\n",
    "\n",
    "A \"Hello world\" example looks like this in Julia\n",
    "\n",
    "```julia\n",
    "julia> println(\"Hello, world!\")\n",
    "```\n",
    "\n",
    "Try to run it in the REPL."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Help mode\n",
    "\n",
    "\n",
    "\n",
    "Curious about what function `println` does? Enter into *help* mode to look into the documentation. This is done by typing a question mark (`?`) into the inut field:\n",
    "\n",
    "```julia\n",
    "julia> ?\n",
    "```\n",
    "\n",
    "After typing `?`, the command prompt changes to `help?>`. It means we are in help mode. Now, we can type a function name to see its documentation.\n",
    "\n",
    "```julia\n",
    "help?> println\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Package and shell modes\n",
    "\n",
    "The REPL comes with two more modes, namely *package* and *shell* modes. To enter package mode type\n",
    "\n",
    "```julia\n",
    "julia> ]\n",
    "```\n",
    "\n",
    "Package mode is used to install and manage packages. We are going to discuss the package mode in greater detail later. To return back to normal mode press the backspace key several times.\n",
    "\n",
    "To enter shell mode type semicolon (`;`)\n",
    "```julia\n",
    "julia> ;\n",
    "```\n",
    "The prompt should have changed to `shell>` indicating that we are in shell mode. Now you can type commands that you would normally do on your system command line. For instance, \n",
    "\n",
    "```julia\n",
    "shell> ls\n",
    "```\n",
    "will display the contents of the current folder in Mac or Linux. Using shell mode in Windows is not straightforward, and thus not recommended for beginners.\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Running more complex code\n",
    "\n",
    "Real-world Julia programs are not typed in the REPL in practice. They are written in one or more files and *included* in the REPL. To try this, create a new file called `hello.jl`, write the code of the \"Hello world\" example above, and save it. If you are using VSCode, you can create the file using File > New File > Julia File. Once the file is saved with the name `hello.jl`, execute it as follows\n",
    "\n",
    "```julia\n",
    "julia> include(\"hello.jl\")\n",
    "```\n",
    "\n",
    "<div class=\"alert alert-block alert-warning\">\n",
    "<b>Warning:</b> Make sure that the file <code>\"hello.jl\"</code> is located in the current working directory of your Julia session. You can query the current directory with function <code>pwd()</code>. You can change to another directory with function <code>cd()</code> if needed.  Also, make sure that the file extension is <code>.jl</code>.\n",
    "</div>\n",
    "\n",
    "The recommended way of running Julia code is using the REPL as we did. But it is also possible to run code directly from the system command line. To this end, open a terminal and call Julia followed buy the path to the file containing the code you want to execute.\n",
    "\n",
    "```\n",
    "$ julia hello.jl\n",
    "```\n",
    "\n",
    "Previous line assumes that you have Julia properly installed in the system and that is usable from the terminal. In UNIX systems (Linux and Mac), the Julia binary needs to be in one of the directories listed in the `PATH` environment variable. To check that Julia is properly installed, you can use\n",
    "\n",
    "```\n",
    "$ julia --version\n",
    "```\n",
    "\n",
    "If this runs without error and you see a version number, you are good to go!\n",
    "\n",
    "\n",
    "<div class=\"alert alert-block alert-info\">\n",
    "<b>Tip:</b> In this tutorial, when a code snipped starts with <code>$</code>, it should be run in the terminal. Otherwise, the code is to be run in the Julia REPL.\n",
    "</div>\n",
    "\n",
    "<div class=\"alert alert-block alert-info\">\n",
    "<b>Tip:</b> Avoid calling Julia code from the terminal, use the Julia REPL instead! Each time you call Julia from the terminal, you start a fresh Julia session and Julia will need to compile your code from scratch. This can be time consuming for large projects. In contrast, if you execute code in the REPL, Julia will compile code incrementally, which is much faster. Running code in a cluster (like in DAS-5 for the Julia assignment) is among the few situations you need to run Julia code from the terminal.\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Running parallel code\n",
    "\n",
    "\n",
    "Since we are in a parallel computing course, let's run a parallel \"hello world\" example in Julia. Open a Julia REPL and write \n",
    "\n",
    "```julia\n",
    "julia> using Distributed\n",
    "julia> @everywhere println(\"Hello, world! I am proc $(myid()) from $(nprocs())\")\n",
    "```\n",
    "\n",
    "Here, we are using the `Distributed` package, which is part of the Julia standard library that provides distributed memory parallel support. The code prints the process id and the number of processes in the current Julia session.\n",
    "\n",
    "You will provably only see output from 1 proces. We need to add more processes to run the example in parallel. This is done with the `addprocs` function.\n",
    "\n",
    "```julia\n",
    "julia> addprocs(3)\n",
    "```\n",
    "We have added 3 new processes, plus the old one, we have 4 processes. Run the code again.\n",
    "\n",
    "```julia\n",
    "julia> @everywhere println(\"Hello, world! I am proc $(myid()) from $(nprocs())\")\n",
    "```\n",
    "\n",
    "Now, you should see output from 4 processes.\n",
    "\n",
    "It is possible to specify the number of processes when starting Julia from the terminal with the `-p` argument (useful, e.g., when running in a cluster).  If you launch Julia from the terminal as\n",
    "\n",
    "```\n",
    "$ julia -p 3\n",
    "```\n",
    "and then run \n",
    "\n",
    "```julia\n",
    "julia> @everywhere println(\"Hello, world! I am proc $(myid()) from $(nprocs())\")\n",
    "```\n",
    "\n",
    "You should get output from 4 processes as before.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Installing packages\n",
    "\n",
    "One of the most useful features of Julia is its package manager. It allows one to install Julia packages in a straightforward and platform independent way. To illustrate this, let us consider the following parallel \"Hello world\" example.\n",
    "\n",
    "\n",
    "Copy the following block of code into a new file named `\"hello_mpi.jl\"`\n",
    "\n",
    "```julia\n",
    "# file hello_mpi.jl\n",
    "using MPI\n",
    "MPI.Init()\n",
    "comm = MPI.COMM_WORLD\n",
    "rank = MPI.Comm_rank(comm)\n",
    "nranks = MPI.Comm_size(comm)\n",
    "println(\"Hello world, I am rank $rank of $nranks\")\n",
    "```\n",
    "\n",
    "As you can see from this example, one can access MPI from Julia in a clean way, without type annotations and other complexities of C/C++ code.\n",
    "\n",
    "Now, run the file from the REPL\n",
    "```julia\n",
    "julia> incude(\"hello_mpi.jl\")\n",
    "```\n",
    "\n",
    "It provably didn't work, right? Read the error message and note that the MPI package needs to be installed to run this code.\n",
    "\n",
    "To install a package, we need to enter *package* mode. Remember that we entered into help mode by typing `?`. Package mode is activated by typing `]`\n",
    "```julia\n",
    "julia> ]\n",
    "```\n",
    "At this point, the promp should have changed to `(@v1.8) pkg>` indicating that we are in package mode. The text between parenthesis indicates which is the active *project*, i.e., where packages are going to be installed. In this case, we are working with the global project associated with our Julia installation (which is Julia 1.8 in this example, but it can be another version in your case).\n",
    "\n",
    "To install the MPI package, type\n",
    "```julia\n",
    "(@v1.8) pkg> add MPI\n",
    "```\n",
    "Congrats, you have installed MPI!\n",
    "\n",
    "<div class=\"alert alert-block alert-info\">\n",
    "    <b>Tip:</b>  Many Julia package names end with <code>.jl</code>. This is just a way of signaling that a package is written in Julia. When using such packages, the <code>.jl</code> needs to be ommited. In this case, we have isntalled the <code>MPI.jl</code> package even though we have only typed <code>MPI</code> in the REPL.\n",
    "</div>\n",
    "\n",
    "<div class=\"alert alert-block alert-info\">\n",
    "    <b>Tip:</b>\n",
    "The package you have installed it is the Julia interface to MPI, called  <code>MPI.jl</code>. Note that it is not a MPI library by itself. It is just a thin wrapper between MPI and Julia. To use this interface, you need an actual MPI library installed in your system such as OpenMPI or MPICH. Julia downloads and installs a MPI library for you, but it is also possible to use a MPI library already available in your system. This is useful, e.g., when running on HPC clusters. See the documentation of <code>MPI.jl</code> for further details.\n",
    "</div>\n",
    "\n",
    "To check that the package was installed properly, exit package mode by pressing the backspace key several times, and run it again\n",
    "\n",
    "```julia\n",
    "julia> incude(\"hello_mpi.jl\")\n",
    "```\n",
    "\n",
    "Now, it should work, but you provably get output from a single MPI rank only.\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Running MPI code\n",
    "\n",
    "To run MPI applications in parallel, you need a launcher like `mpiexec`. MPI codes written in Julia are not an exception to this rule. From the system terminal, you can run\n",
    "```\n",
    "$ mpiexec -np 4 julia hello_mpi.jl\n",
    "```\n",
    "But it will provably don't work since the version of `mpiexec` needs to match with the MPI version we are using from Julia. You can find the path to the `mpiexec` binary you need to use with these commands\n",
    "\n",
    "```julia\n",
    "julia> using MPI\n",
    "julia> MPI.mpiexec_path\n",
    "```\n",
    "\n",
    "and then try again\n",
    "```\n",
    "$ /path/to/my/mpiexec -np 4 julia hello_mpi.jl\n",
    "```\n",
    "with your particular path.\n",
    "\n",
    "However, this is not very convenient. Don't worry if you could not make it work! A more elegant way to run MPI code is from the Julia REPL directly, by using these commands:\n",
    "```julia\n",
    "julia> using MPI\n",
    "julia> mpiexec(cmd->run(`$cmd -np 4 julia hello_mpi.jl`))\n",
    "```\n",
    "\n",
    "Now, you should see output from 4 ranks."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Installing packages locally\n",
    "\n",
    "We have installed the `MPI` package globally and it will be available in all Julia sessions. However, in some situations, we want to work with different versions of the same package or to install packages in an isolated way to avoid potential conflicts with other packages. This can be done by using local projects.\n",
    "\n",
    "A project is simply a folder in the hard disk. To use a particular folder as your project, you need to *activate* it. This is done by entering package mode and using the `activate` command followed by the path to the folder you want to activate.\n",
    "```julia\n",
    "(@v1.8) pkg> activate .\n",
    "```\n",
    " Previous command will activate the current working directory. Note that the dot `.` is indeed the path to the current folder.\n",
    " \n",
    "The prompt has changed to `(lessons) pkg>` indicating that we are in the project within the `lessons` folder. The particular folder name can be different in your case.\n",
    "\n",
    "<div class=\"alert alert-block alert-info\">\n",
    "    <b>Tip:</b>  You can activate a project directly when opening Julia from the terminal using the <code>--project</code> flag. The command <code>$ julia --project=.</code> will open Julia and activate a project in the current directory. You can also achieve the same effect by setting the environment variable  <code>JULIA_PROJECT</code> with the path of the folder you want to activate.\n",
    "    </div>\n",
    "    \n",
    "    \n",
    "  <div class=\"alert alert-block alert-info\">\n",
    "    <b>Tip:</b>  The active project folder and the current working directory are two independent concepts! For instance,  <code>(@v1.8) pkg> activate folderB</code> and then <code>julia> cd(\"folderA\")</code>, will activate the project in <code>folderB</code> and change the current working directory to <code>folderA</code>.\n",
    "    \n",
    "</div>\n",
    "\n",
    "At this point all package-related operations will be local to the new project. For instance, install the `DataFrames` package.\n",
    "\n",
    "```julia\n",
    "(lessons) pkg> add DataFrames\n",
    "```\n",
    "Use the package to check that it is installed\n",
    "\n",
    "```julia\n",
    "julia> using DataFrames\n",
    "julia> DataFrame(a=[1,2],b=[3,4])\n",
    "```\n",
    "Now, we can return to the global project to check that `DataFrames` has not been installed there. To return to the global environment, use `activate` without a folder name.\n",
    "\n",
    "```julia\n",
    "(lessons) pkg> activate\n",
    "```\n",
    "The prompt is again `(@v1.8) pkg>`\n",
    "\n",
    "Now, try to use `DataFrames`.\n",
    "\n",
    "```julia\n",
    "julia> using DataFrames\n",
    "julia> DataFrame(a=[1,2],b=[3,4])\n",
    "```\n",
    "You should get an error or a warning unless you already had `DataFrames` installed globally.\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Project and Manifest files\n",
    "\n",
    "The information about a project is stored in two files `Project.toml` and `Manifest.toml`.\n",
    "\n",
    "- `Project.toml` contains the packages explicitly installed (the direct dependencies)\n",
    "\n",
    "- `Manifest.toml` contains direct and indirect dependencies along with the concrete version of each package.\n",
    "\n",
    "\n",
    "In other words, `Project.toml` contains the packages relevant for the user, whereas `Manifest.toml` is the detailed snapshot of all dependencies. The `Manifest.toml` can be used to reproduce the same envinonment in another machine.\n",
    "\n",
    "You can see the path to the current `Project.toml` file by using the `status` operator (or `st` in its short form) while in package mode\n",
    "\n",
    "```julia\n",
    "(@v1.8) pkg> status\n",
    "```\n",
    "\n",
    "The information about the `Manifest.toml` can be inspected by passing the `-m` flag.\n",
    "\n",
    "```julia\n",
    "(@v1.8) pkg> status -m\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Installing packages from a project file\n",
    "\n",
    "Project files can be used to install lists of packages defined by others. E.g., to install all the dependencies of a Julia application.\n",
    "\n",
    "Assume that a colleague has sent to you a `Project.toml` file with this content:\n",
    "\n",
    "```\n",
    "[deps]\n",
    "BenchmarkTools = \"6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf\"\n",
    "DataFrames = \"a93c6f00-e57d-5684-b7b6-d8193f3e46c0\"\n",
    "MPI = \"da04e1cc-30fd-572f-bb4f-1f8673147195\"\n",
    "```\n",
    "\n",
    "Copy the contents of previous code block into a file called  `Project.toml` and place it in an empty folder named `newproject`. It is important that the file is named `Project.toml`. You can create a new folder from the REPL with \n",
    "\n",
    "```julia\n",
    "julia> mkdir(\"newproject\")\n",
    "```\n",
    "\n",
    "To install all the packages registered in this file you need to activate the folder containing your `Project.toml` file\n",
    "```julia\n",
    "(@v1.8) pkg> activate newproject\n",
    "```\n",
    "and then *instantiating* it\n",
    "```julia\n",
    "(newproject) pkg> instantiate\n",
    "```\n",
    "\n",
    "The instantiate command will download and install all listed packages and their dependencies in just one click."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Getting help in package mode\n",
    "\n",
    "You can get help about a particular package operator by writing `help` in front of it\n",
    "\n",
    "```julia\n",
    "(@v1.8) pkg> help activate\n",
    "```\n",
    "\n",
    "You can get an overview of all package commands by typing `help` alone\n",
    "```julia\n",
    "(@v1.8) pkg> help\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Package operations in Julia code\n",
    "\n",
    "In some situations it is required to use package commands in Julia code, e.g., to automatize installation and deployment of Julia applications. This can be done using the `Pkg` package. For instance\n",
    "\n",
    "```julia\n",
    "julia> using Pkg\n",
    "julia> Pkg.status()\n",
    "```\n",
    "is equivalent to call `status` in package mode.\n",
    "```julia\n",
    "(@v1.8) pkg> status\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Conclusion\n",
    "\n",
    "We have learned the basics of how to work with Julia. Now, you should be ready to start learning more on the language. If you want to further dig into the topics we have covered here, you can take a look and the following links\n",
    "\n",
    "- Julia Manual   https://docs.julialang.org/en/v1/manual/getting-started/\n",
    "- Package manager https://pkgdocs.julialang.org/v1/getting-started/\n",
    "\n",
    "If you want to interact with the Julia community on discourse, sign in at https://discourse.julialang.org/"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# License\n",
    "\n",
    "TODO: replace link to website\n",
    "\n",
    "This notebook is part of the course [Programming Large Scale Parallel Systems](http://localhost:8000/) at Vrije Universiteit Amsterdam and may be used under a [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) license."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Julia 1.8.4",
   "language": "julia",
   "name": "julia-1.8"
  },
  "language_info": {
   "file_extension": ".jl",
   "mimetype": "application/julia",
   "name": "julia",
   "version": "1.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
