mirror of
https://github.com/fverdugo/XM_40017.git
synced 2025-11-08 20:14:23 +01:00
Merge branch 'main' of https://github.com/fverdugo/XM_40017
This commit is contained in:
commit
ff9158dd9b
27
docs/make.jl
27
docs/make.jl
@ -65,7 +65,7 @@ function create_md_nb_file( notebook_path )
|
||||
end
|
||||
|
||||
# Convert to html using nbconvert
|
||||
function convert_notebook_to_html(notebook_path; output_name = "index", output_dir = "./docs/src/notebook-output", theme = "dark")
|
||||
function convert_notebook_to_html(notebook_path; output_name = "index", output_dir = "./docs/src/notebook-output", theme = "light")
|
||||
command_jup = "jupyter"
|
||||
command_nbc = "nbconvert"
|
||||
output_format = "--to=html"
|
||||
@ -95,21 +95,21 @@ end
|
||||
|
||||
# Replace colors to match Documenter.jl
|
||||
function replace_colors(content)
|
||||
content = replace( content, "--jp-layout-color0: #111111;" => "--jp-layout-color0: #1f2424;")
|
||||
content = replace(content, "--md-grey-900: #212121;" => "--md-grey-900: #282f2f;")
|
||||
#content = replace( content, "--jp-layout-color0: #111111;" => "--jp-layout-color0: #1f2424;")
|
||||
#content = replace(content, "--md-grey-900: #212121;" => "--md-grey-900: #282f2f;")
|
||||
return content
|
||||
end
|
||||
|
||||
# Loop over notebooks and generate html and markdown
|
||||
notebook_files = glob("*.ipynb", "docs/src/notebooks/")
|
||||
for filepath in notebook_files
|
||||
convert_embedded_img_to_base64(filepath)
|
||||
create_md_nb_file(filepath)
|
||||
filename_with_ext = splitpath(filepath)[end]
|
||||
filename = splitext(filename_with_ext)[1]
|
||||
convert_notebook_to_html(filepath, output_name = filename)
|
||||
modify_notebook_html("docs/src/notebook-output/$(filename).html")
|
||||
end
|
||||
#for filepath in notebook_files
|
||||
# convert_embedded_img_to_base64(filepath)
|
||||
# create_md_nb_file(filepath)
|
||||
# filename_with_ext = splitpath(filepath)[end]
|
||||
# filename = splitext(filename_with_ext)[1]
|
||||
# convert_notebook_to_html(filepath, output_name = filename)
|
||||
# modify_notebook_html("docs/src/notebook-output/$(filename).html")
|
||||
#end
|
||||
|
||||
makedocs(;
|
||||
modules=[XM_40017],
|
||||
@ -121,9 +121,8 @@ makedocs(;
|
||||
prettyurls=get(ENV, "CI", "false") == "true",
|
||||
canonical="https://fverdugo.github.io/XM_40017",
|
||||
edit_link="main",),
|
||||
pages=["Home" => "index.md", "Notebooks"=>[
|
||||
"Julia Tutorial" => "julia_tutorial.md",
|
||||
"Why is Julia fast?" => "julia_intro.md",
|
||||
pages=["Home" => "index.md","Getting started"=>"getting_started_with_julia.md", "Notebooks"=>[
|
||||
"Is Julia fast?" => "julia_intro.md",
|
||||
"Julia Basics" => "julia_basics.md",
|
||||
"Julia Asynchronous" => "julia_async.md",
|
||||
"Julia Distributed" => "julia_distributed.md",
|
||||
|
||||
380
docs/src/getting_started_with_julia.md
Normal file
380
docs/src/getting_started_with_julia.md
Normal file
@ -0,0 +1,380 @@
|
||||
|
||||
# Getting started
|
||||
|
||||
|
||||
## Introduction
|
||||
|
||||
The programming of this course will be done using the [Julia programming language](https://julialang.org). Thus, we start by explaining how to get up and running with Julia. After learning this page, you will be able to:
|
||||
|
||||
- Use the Julia REPL;
|
||||
- Run serial and parallel code;
|
||||
- Install and manage Julia packages.
|
||||
|
||||
## Why Julia?
|
||||
|
||||
Courses related with high-performance computing (HPC) often use languages such as C, C++, or Fortran. We use Julia instead to make the course accessible to a wider set of students, including the ones that have no experience with
|
||||
C/C++ or Fortran, but are willing to learn parallel programming. Julia is a relatively new programming language specifically designed for scientific computing. It combines a high-level syntax close to interpreted languages like Python with the performance of compiled languages like C, C++, or Fortran. Thus, Julia will allow us to write efficient parallel algorithms with a syntax that is convenient in a teaching setting. In addition, Julia provides easy access to different programming models to write distributed algorithms, which will be useful to learn and experiment with them.
|
||||
|
||||
## Installing Julia
|
||||
|
||||
This is a tutorial-like page. Follow these steps before you continue reading the document.
|
||||
|
||||
- Download and install Julia from [julialang.org](https://julialang.org);
|
||||
- Follow the specific instructions for your operating system: [Windows](https://julialang.org/downloads/platform/#windows), [MacOS](https://julialang.org/downloads/platform/#macos), or [Linux](https://julialang.org/downloads/platform/#linux_and_freebsd)
|
||||
- Download and install [VSCode and its Julia extension](https://www.julia-vscode.org/docs/dev/gettingstarted/);
|
||||
|
||||
|
||||
## The Julia REPL
|
||||
|
||||
### Starting Julia
|
||||
|
||||
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:
|
||||
|
||||
```
|
||||
julia>
|
||||
```
|
||||
|
||||
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*.
|
||||
|
||||
### Basic usage
|
||||
|
||||
The usage of the REPL is as follows:
|
||||
- You write some input
|
||||
- press enter
|
||||
- you get the output
|
||||
|
||||
For instance, try this
|
||||
|
||||
```julia
|
||||
julia> 1 + 1
|
||||
```
|
||||
|
||||
A "Hello world" example looks like this in Julia
|
||||
|
||||
```julia
|
||||
julia> println("Hello, world!")
|
||||
```
|
||||
|
||||
Try to run it in the REPL.
|
||||
|
||||
### Help mode
|
||||
|
||||
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:
|
||||
|
||||
```julia
|
||||
julia> ?
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
```julia
|
||||
help?> println
|
||||
```
|
||||
|
||||
### Package and shell modes
|
||||
|
||||
The REPL comes with two more modes, namely *package* and *shell* modes. To enter package mode type
|
||||
|
||||
```julia
|
||||
julia> ]
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
To enter shell mode type semicolon (`;`)
|
||||
```julia
|
||||
julia> ;
|
||||
```
|
||||
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,
|
||||
|
||||
```julia
|
||||
shell> ls
|
||||
```
|
||||
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.
|
||||
|
||||
|
||||
|
||||
## Running Julia code
|
||||
|
||||
### Running more complex code
|
||||
|
||||
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
|
||||
|
||||
```julia
|
||||
julia> include("hello.jl")
|
||||
```
|
||||
|
||||
\warn{ Make sure that the file `"hello.jl"` is located in the current working directory of your Julia session. You can query the current directory with function `pwd()`. You can change to another directory with function `cd()` if needed. Also, make sure that the file extension is `.jl`.}
|
||||
|
||||
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.
|
||||
|
||||
```
|
||||
$ julia hello.jl
|
||||
```
|
||||
|
||||
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
|
||||
|
||||
```
|
||||
$ julia --version
|
||||
```
|
||||
|
||||
If this runs without error and you see a version number, you are good to go!
|
||||
|
||||
|
||||
!!! note
|
||||
In this tutorial, when a code snipped starts with `$`, it should be run in the terminal. Otherwise, the code is to be run in the Julia REPL.
|
||||
|
||||
!!! tip
|
||||
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.
|
||||
|
||||
### Running parallel code
|
||||
|
||||
|
||||
Since we are in a parallel computing course, let's run a parallel "hello world" example in Julia. Open a Julia REPL and write
|
||||
|
||||
```julia
|
||||
julia> using Distributed
|
||||
julia> @everywhere println("Hello, world! I am proc $(myid()) from $(nprocs())")
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
```julia
|
||||
julia> addprocs(3)
|
||||
```
|
||||
We have added 3 new processes, plus the old one, we have 4 processes. Run the code again.
|
||||
|
||||
```julia
|
||||
julia> @everywhere println("Hello, world! I am proc $(myid()) from $(nprocs())")
|
||||
```
|
||||
|
||||
Now, you should see output from 4 processes.
|
||||
|
||||
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
|
||||
|
||||
```
|
||||
$ julia -p 3
|
||||
```
|
||||
and then run
|
||||
|
||||
```julia
|
||||
julia> @everywhere println("Hello, world! I am proc $(myid()) from $(nprocs())")
|
||||
```
|
||||
|
||||
You should get output from 4 processes as before.
|
||||
|
||||
### Installing packages
|
||||
|
||||
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. This example uses the message passing interface (MPI). We will learn more about MPI later in the course.
|
||||
|
||||
|
||||
Copy the following block of code into a new file named `"hello_mpi.jl"`
|
||||
|
||||
```julia
|
||||
# file hello_mpi.jl
|
||||
using MPI
|
||||
MPI.Init()
|
||||
comm = MPI.COMM_WORLD
|
||||
rank = MPI.Comm_rank(comm)
|
||||
nranks = MPI.Comm_size(comm)
|
||||
println("Hello world, I am rank $rank of $nranks")
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
Now, run the file from the REPL
|
||||
```julia
|
||||
julia> incude("hello_mpi.jl")
|
||||
```
|
||||
|
||||
It provably didn't work, right? Read the error message and note that the MPI package needs to be installed to run this code.
|
||||
|
||||
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 `]`
|
||||
```julia
|
||||
julia> ]
|
||||
```
|
||||
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).
|
||||
|
||||
To install the MPI package, type
|
||||
```julia
|
||||
(@v1.8) pkg> add MPI
|
||||
```
|
||||
Congrats, you have installed MPI!
|
||||
|
||||
!!! note
|
||||
Many Julia package names end with `.jl`. This is just a way of signaling that a package is written in Julia. When using such packages, the `.jl` needs to be ommited. In this case, we have isntalled the `MPI.jl` package even though we have only typed `MPI` in the REPL.
|
||||
|
||||
!!! note
|
||||
The package you have installed it is the Julia interface to MPI, called `MPI.jl`. 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 `MPI.jl` for further details.
|
||||
|
||||
To check that the package was installed properly, exit package mode by pressing the backspace key several times, and run it again
|
||||
|
||||
```julia
|
||||
julia> incude("hello_mpi.jl")
|
||||
```
|
||||
|
||||
Now, it should work, but you provably get output from a single MPI rank only.
|
||||
|
||||
### Running MPI code
|
||||
|
||||
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
|
||||
```
|
||||
$ mpiexec -np 4 julia hello_mpi.jl
|
||||
```
|
||||
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
|
||||
|
||||
```julia
|
||||
julia> using MPI
|
||||
julia> MPI.mpiexec_path
|
||||
```
|
||||
|
||||
and then try again
|
||||
```
|
||||
$ /path/to/my/mpiexec -np 4 julia hello_mpi.jl
|
||||
```
|
||||
with your particular path.
|
||||
|
||||
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:
|
||||
```julia
|
||||
julia> using MPI
|
||||
julia> mpiexec(cmd->run(`$cmd -np 4 julia hello_mpi.jl`))
|
||||
```
|
||||
|
||||
Now, you should see output from 4 ranks.
|
||||
|
||||
## Package manager
|
||||
|
||||
### Installing packages locally
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
```julia
|
||||
(@v1.8) pkg> activate .
|
||||
```
|
||||
Previous command will activate the current working directory. Note that the dot `.` is indeed the path to the current folder.
|
||||
|
||||
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.
|
||||
|
||||
!!! tip
|
||||
You can activate a project directly when opening Julia from the terminal using the `--project` flag. The command `$ julia --project=.` will open Julia and activate a project in the current directory. You can also achieve the same effect by setting the environment variable `JULIA_PROJECT` with the path of the folder you want to activate.
|
||||
|
||||
!!! note
|
||||
The active project folder and the current working directory are two independent concepts! For instance, `(@v1.8) pkg> activate folderB` and then `julia> cd("folderA")`, will activate the project in `folderB` and change the current working directory to `folderA`.
|
||||
|
||||
At this point all package-related operations will be local to the new project. For instance, install the `DataFrames` package.
|
||||
|
||||
```julia
|
||||
(lessons) pkg> add DataFrames
|
||||
```
|
||||
Use the package to check that it is installed
|
||||
|
||||
```julia
|
||||
julia> using DataFrames
|
||||
julia> DataFrame(a=[1,2],b=[3,4])
|
||||
```
|
||||
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.
|
||||
|
||||
```julia
|
||||
(lessons) pkg> activate
|
||||
```
|
||||
The prompt is again `(@v1.8) pkg>`
|
||||
|
||||
Now, try to use `DataFrames`.
|
||||
|
||||
```julia
|
||||
julia> using DataFrames
|
||||
julia> DataFrame(a=[1,2],b=[3,4])
|
||||
```
|
||||
You should get an error or a warning unless you already had `DataFrames` installed globally.
|
||||
|
||||
### Project and Manifest files
|
||||
|
||||
The information about a project is stored in two files `Project.toml` and `Manifest.toml`.
|
||||
|
||||
- `Project.toml` contains the packages explicitly installed (the direct dependencies)
|
||||
|
||||
- `Manifest.toml` contains direct and indirect dependencies along with the concrete version of each package.
|
||||
|
||||
|
||||
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.
|
||||
|
||||
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
|
||||
|
||||
```julia
|
||||
(@v1.8) pkg> status
|
||||
```
|
||||
|
||||
The information about the `Manifest.toml` can be inspected by passing the `-m` flag.
|
||||
|
||||
```julia
|
||||
(@v1.8) pkg> status -m
|
||||
```
|
||||
|
||||
### Installing packages from a project file
|
||||
|
||||
Project files can be used to install lists of packages defined by others. E.g., to install all the dependencies of a Julia application.
|
||||
|
||||
Assume that a colleague has sent to you a `Project.toml` file with this content:
|
||||
|
||||
```
|
||||
[deps]
|
||||
BenchmarkTools = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf"
|
||||
DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0"
|
||||
MPI = "da04e1cc-30fd-572f-bb4f-1f8673147195"
|
||||
```
|
||||
|
||||
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
|
||||
|
||||
```julia
|
||||
julia> mkdir("newproject")
|
||||
```
|
||||
|
||||
To install all the packages registered in this file you need to activate the folder containing your `Project.toml` file
|
||||
```julia
|
||||
(@v1.8) pkg> activate newproject
|
||||
```
|
||||
and then *instantiating* it
|
||||
```julia
|
||||
(newproject) pkg> instantiate
|
||||
```
|
||||
|
||||
The instantiate command will download and install all listed packages and their dependencies in just one click.
|
||||
|
||||
### Getting help in package mode
|
||||
|
||||
You can get help about a particular package operator by writing `help` in front of it
|
||||
|
||||
```julia
|
||||
(@v1.8) pkg> help activate
|
||||
```
|
||||
|
||||
You can get an overview of all package commands by typing `help` alone
|
||||
```julia
|
||||
(@v1.8) pkg> help
|
||||
```
|
||||
|
||||
### Package operations in Julia code
|
||||
|
||||
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
|
||||
|
||||
```julia
|
||||
julia> using Pkg
|
||||
julia> Pkg.status()
|
||||
```
|
||||
is equivalent to call `status` in package mode.
|
||||
```julia
|
||||
(@v1.8) pkg> status
|
||||
```
|
||||
|
||||
## Conclusion
|
||||
|
||||
We have learned the basics of how to work with Julia. If you want to further dig into the topics we have covered here, you can take a look and the following links
|
||||
|
||||
- [Julia Manual](https://docs.julialang.org/en/v1/manual/getting-started/)
|
||||
- [Package manager](https://pkgdocs.julialang.org/v1/getting-started/)
|
||||
|
||||
|
||||
|
||||
@ -1,7 +1,66 @@
|
||||
```@meta
|
||||
CurrentModule = XM_40017
|
||||
```
|
||||
# XM_40017
|
||||
# Programming Large-Scale Parallel Systems (XM_40017)
|
||||
|
||||
Welcome!
|
||||
Welcome to the interactive lecture notes of the [Programming Large-Scale Parallel Systems course](https://studiegids.vu.nl/EN/courses/2023-2024/XM_40017#/) at [VU Amsterdam](https://vu.nl)!
|
||||
|
||||
## What
|
||||
|
||||
This page contains part of the course material of the Programming Large-Scale Parallel Systems course at VU Amsterdam.
|
||||
Further information about this course is found in the study guide
|
||||
([click here](https://studiegids.vu.nl/EN/courses/2023-2024/XM_40017#/)) and our Canvas page (for registered students). This material consists of several lecture notes in jupyter notebook format, which will help you to learn how to design, analyze, and program parallel algorithms on multi-node computing systems.
|
||||
|
||||
!!! note
|
||||
This page contains only part of the course material. The rest is available on Canvas. In particular, **the lecture notes in this public webpage do not fully cover all topics in the final exam**.
|
||||
|
||||
## How to use this page
|
||||
|
||||
You have two main ways of running the notebooks:
|
||||
|
||||
- Download the notebooks and run them locally on your computer (recommended)
|
||||
- Run the notebooks on the cloud via [mybinder.org](https://mybinder.org) (high startup time).
|
||||
|
||||
You also have the static version of the notebooks displayed in this webpage for quick reference. At each notebook page you will find a green box with links to download the notebook or to open in on mybinder.
|
||||
|
||||
## How to run the notebooks locally
|
||||
|
||||
To run a notebook locally follow these steps:
|
||||
|
||||
- Install Julia (if not done already). More information in [Getting started](@ref).
|
||||
- Download the notebook.
|
||||
- Launch Julia. More information in [Getting started](@ref).
|
||||
```
|
||||
_ _ _(_)_ | Documentation: https://docs.julialang.org
|
||||
(_) | (_) (_) |
|
||||
_ _ _| |_ __ _ | Type "?" for help, "]?" for Pkg help.
|
||||
| | | | | | |/ _` | |
|
||||
| | |_| | | | (_| | | Version 1.9.0 (2023-05-07)
|
||||
_/ |\__'_|_|_|\__'_| | Official https://julialang.org/ release
|
||||
|__/ |
|
||||
|
||||
julia>
|
||||
```
|
||||
- Execute these commands in the Julia command line:
|
||||
|
||||
```
|
||||
julia> using Pkg
|
||||
julia> Pkg.add("IJulia")
|
||||
julia> using IJulia
|
||||
julia> notebook()
|
||||
```
|
||||
- These commands will open a jupyter in your web browser. Navigate in jupyter to the notebook file you have downloaded and open it.
|
||||
|
||||
## Authorship
|
||||
|
||||
This material was created by [Francesc Verdugo](https://github.com/fverdugo/) with the help of Gelieza Kötterheinrich. Part of the notebooks are based on the course slides by [Henri Bal](https://www.vuhpdc.net/henri-bal/).
|
||||
|
||||
|
||||
## License
|
||||
|
||||
All material in this page that is original to this course may be used under a [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) license.
|
||||
|
||||
|
||||
## Acknowledgment
|
||||
|
||||
This page was created with the support of the Faculty of Science of [Vrije Universiteit Amsterdam](https://vu.nl) in the framework of the project "Interactive lecture notes and exercises for the Programming Large-Scale Parallel Systems course" funded by the "Innovation budget BETA 2023 Studievoorschotmiddelen (SVM) towards Activated Blended Learning".
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
260
docs/src/notebooks/tsp.ipynb
Normal file
260
docs/src/notebooks/tsp.ipynb
Normal file
@ -0,0 +1,260 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 1,
|
||||
"id": "8850d90e",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"using Distributed"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 2,
|
||||
"id": "5d4935ee",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"4-element Vector{Int64}:\n",
|
||||
" 2\n",
|
||||
" 3\n",
|
||||
" 4\n",
|
||||
" 5"
|
||||
]
|
||||
},
|
||||
"execution_count": 2,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"if procs() == workers()\n",
|
||||
" addprocs(4)\n",
|
||||
"end"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 3,
|
||||
"id": "4a2756ae",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"@everywhere function visited(city,hops,path)\n",
|
||||
" for i = 1:hops\n",
|
||||
" if path[i] == city\n",
|
||||
" return true\n",
|
||||
" end\n",
|
||||
" end\n",
|
||||
" return false\n",
|
||||
"end"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 4,
|
||||
"id": "39e9e667",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"tsp_serial_impl (generic function with 1 method)"
|
||||
]
|
||||
},
|
||||
"execution_count": 4,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"function tsp_serial_impl(connections,hops,path,current_distance,min_distance)\n",
|
||||
" num_cities = length(connections)\n",
|
||||
" if hops == num_cities\n",
|
||||
" if current_distance < min_distance\n",
|
||||
" return current_distance\n",
|
||||
" end\n",
|
||||
" else\n",
|
||||
" current_city = path[hops]\n",
|
||||
" next_hops = hops + 1\n",
|
||||
" for (next_city,distance_increment) in connections[current_city]\n",
|
||||
" if !visited(next_city,hops,path)\n",
|
||||
" path[next_hops] = next_city\n",
|
||||
" next_distance = current_distance + distance_increment\n",
|
||||
" if next_distance < min_distance\n",
|
||||
" return tsp_serial_impl(connections,next_hops,path,next_distance,min_distance)\n",
|
||||
" end\n",
|
||||
" end\n",
|
||||
" end \n",
|
||||
" end\n",
|
||||
" min_distance\n",
|
||||
"end"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 5,
|
||||
"id": "83b58881",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"tsp_serial (generic function with 1 method)"
|
||||
]
|
||||
},
|
||||
"execution_count": 5,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"function tsp_serial(connections,city)\n",
|
||||
" num_cities = length(connections)\n",
|
||||
" path=zeros(Int,num_cities)\n",
|
||||
" hops = 1\n",
|
||||
" path[hops] = city\n",
|
||||
" current_distance = 0\n",
|
||||
" min_distance = typemax(Int)\n",
|
||||
" min_distance = tsp_serial_impl(connections,hops,path,current_distance,min_distance)\n",
|
||||
" (;path=path,distance=min_distance)\n",
|
||||
"end"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 6,
|
||||
"id": "78095098",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"(path = [1, 4, 5, 2, 3, 6], distance = 222)"
|
||||
]
|
||||
},
|
||||
"execution_count": 6,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"connections = [\n",
|
||||
" [(1,0),(4,39),(5,76), (6,78),(3,94),(2,97)],\n",
|
||||
" [(2,0),(5,25),(4,58),(3,62),(1,97),(6,109)],\n",
|
||||
" [(3,0),(6,58),(2,62),(4,68),(5,70),(1,94)],\n",
|
||||
" [(4,0),(5,38),(1,39),(2,58),(3,68),(6,78)],\n",
|
||||
" [(5,0),(2,25),(4,38),(3,70),(1,76),(6,104)],\n",
|
||||
" [(6,0),(3,58),(1,78),(4,78),(5,104),(2,109)]\n",
|
||||
"]\n",
|
||||
"city = 1\n",
|
||||
"tsp_serial(connections,city)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "03f0dd8e",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"@everywhere function tsp_dist_impl(connections,hops,path,current_distance,min_distance,max_hops,jobs_chnl,ftr_result)\n",
|
||||
" num_cities = length(connections)\n",
|
||||
" if hops == num_cities\n",
|
||||
" if current_distance < min_distance\n",
|
||||
" if ftr_result !== nothing\n",
|
||||
" @spawnat 1 begin\n",
|
||||
" result = fetch(ftr_result)\n",
|
||||
" result.path .= path\n",
|
||||
" result.min_distance_ref[] = current_distance\n",
|
||||
" end |> wait\n",
|
||||
" end\n",
|
||||
" return current_distance\n",
|
||||
" end\n",
|
||||
" elseif hops <= max_hops\n",
|
||||
" current_city = path[hops]\n",
|
||||
" next_hops = hops + 1\n",
|
||||
" for (next_city,distance_increment) in connections[current_city]\n",
|
||||
" if !visited(next_city,hops,path)\n",
|
||||
" path[next_hops] = next_city\n",
|
||||
" next_distance = current_distance + distance_increment\n",
|
||||
" if next_distance < min_distance\n",
|
||||
" return tsp_dist_impl(connections,next_hops,path,next_distance,min_distance,max_hops,jobs_chnl,ftr_result)\n",
|
||||
" end\n",
|
||||
" end\n",
|
||||
" end \n",
|
||||
" else\n",
|
||||
" if jobs_channel !== nothing\n",
|
||||
" put!(jobs_chnl,(;hops,path,current_distance))\n",
|
||||
" end\n",
|
||||
" end\n",
|
||||
" min_distance\n",
|
||||
"end\n",
|
||||
"\n",
|
||||
"function tsp_dist(connections,city)\n",
|
||||
" max_hops = 2\n",
|
||||
" num_cities = length(connections)\n",
|
||||
" path=zeros(Int,num_cities)\n",
|
||||
" hops = 1\n",
|
||||
" path[hops] = city\n",
|
||||
" current_distance = 0\n",
|
||||
" min_distance = typemax(Int)\n",
|
||||
" jobs_chnl = RemoteChannel(()->Channel{Any}(10))\n",
|
||||
" ftr_result = @spawnat 1 (;path,min_distance_ref=Ref(min_distance))\n",
|
||||
" task = @async begin\n",
|
||||
" tsp_dist_impl(connections,hops,path,current_distance,min_distance,max_hops,jobs_chnl,nothing)\n",
|
||||
" for w in workers()\n",
|
||||
" put!(job_chnl,nothing)\n",
|
||||
" end\n",
|
||||
" end\n",
|
||||
" @sync for w in workers()\n",
|
||||
" @spawnat w begin\n",
|
||||
" max_hops = typemax(Int)\n",
|
||||
" jobs_channel = nothing\n",
|
||||
" while true\n",
|
||||
" job = take!(jobs_chnl)\n",
|
||||
" if job == nothing\n",
|
||||
" break\n",
|
||||
" end\n",
|
||||
" hobs = job.hobs\n",
|
||||
" path = job.path\n",
|
||||
" current_distance = job.current_distance\n",
|
||||
" tsp_dist_impl(connections,hops,path,current_distance,min_distance,max_hops,jobs_chnl,ftr_result)\n",
|
||||
" end\n",
|
||||
" end\n",
|
||||
" end \n",
|
||||
" (;path=path,distance=min_distance)\n",
|
||||
"end\n",
|
||||
"city = 1\n",
|
||||
"tsp_dist(connections,city)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "370a1205",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": []
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Julia 1.9.0",
|
||||
"language": "julia",
|
||||
"name": "julia-1.9"
|
||||
},
|
||||
"language_info": {
|
||||
"file_extension": ".jl",
|
||||
"mimetype": "application/julia",
|
||||
"name": "julia",
|
||||
"version": "1.9.0"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user