Julia Tutorial PDF Version Quick Guide Resources Job Search Discussion One of the facts about scientific programming is that it requires high performance flexible dynamic programming language. Unfortunately, to a great extent, the domain experts have moved to slower dynamic programming languages. There can be many good reasons for using such dynamic programming languages and, in fact, their use cannot be diminished as well. On the flip side, what can we expect from modern language design and compiler techniques? Some of the expectations are as follows − It should eradicate the performance trade-off. It should provide the domain experts a single environment that is productive enough for prototyping and efficient for deploying performance-intensive applications. Audience This tutorial will be useful for graduates, post-graduates, and research students who either have an interest in Julia Programming or have these subjects as a part of their curriculum. The reader can be a beginner or an advanced learner. Prerequisites The reader should have knowledge on basic computer programming languages. Print Page Previous Next Advertisements ”;
Category: julia
Integers and Floating-Point Numbers ”; Previous Next In any programming language, there are two basic building blocks of arithmetic and computation. They are integers and floating-point values. Built-in representation of the values of integers and floating-point are called numeric primitives. On the other hand, their representation as immediate values in code are called numeric literals. Following are the example of integer and floating-point literals − 100 is an integer literal 100.50 is a floating-point literal Their built-in memory representations as objects is numeric primitives. Integers Integer is one of the primitive numeric types in Julia. It is represented as follows − julia> 100 100 julia> 123456789 123456789 We can check the default type of an integer literal, which depends on whether our system is 32-bit or 64-bit architecture. julia> Sys.WORD_SIZE 64 julia> typeof(100) Int64 Integer types The table given below shows the integer types in Julia − Type Signed? Number of bits Smallest value Largest value Int8 ✓ 8 -2^7 2^7 – 1 UInt8 8 0 2^8 – 1 Int16 ✓ 16 -2^15 2^15 – 1 UInt16 16 0 2^16 – 1 Int32 ✓ 32 -2^31 2^31 – 1 UInt32 32 0 2^32 – 1 Int64 ✓ 64 -2^63 2^63 – 1 UInt64 64 0 2^64 – 1 Int128 ✓ 128 -2^127 2^127 – 1 UInt128 128 0 2^128 – 1 Bool N/A 8 false (0) true (1) Overflow behavior In Julia, if the maximum representable value of a given type exceeds, then it results in a wraparound behavior. For example − julia> A = typemax(Int64) 9223372036854775807 julia> A + 1 -9223372036854775808 julia> A + 1 == typemin(Int64) true It is recommended to explicitly check for wraparound produced by overflow especially where overflow is possible. Otherwise use BigInt type in Arbitrary Precision Arithmetic. Below is an example of overflow behavior and how we can resolve it − julia> 10^19 -8446744073709551616 julia> big(10)^19 10000000000000000000 Division errors Integer division throws a DivideError in the following two exceptional cases − Dividing by zero Dividing the lowest negative number The rem (remainder) and mod (modulus) functions will throw a DivideError whenever their second argument is zero. The example are given below − julia> mod(1, 0) ERROR: DivideError: integer division error Stacktrace: [1] div at .int.jl:260 [inlined] [2] div at .div.jl:217 [inlined] [3] div at .div.jl:262 [inlined] [4] fld at .div.jl:228 [inlined] [5] mod(::Int64, ::Int64) at .int.jl:252 [6] top-level scope at REPL[52]:1 julia> rem(1, 0) ERROR: DivideError: integer division error Stacktrace: [1] rem(::Int64, ::Int64) at .int.jl:261 [2] top-level scope at REPL[54]:1 Floating-point numbers Another primitive numeric types in Julia is floating-point numbers. It is represented (using E-notation when needed) as follows − julia> 1.0 1.0 julia> 0.5 0.5 julia> -1.256 -1.256 julia> 2e11 2.0e11 julia> 3.6e-5 3.6e-5 All the above results are Float64. If we would like to enter Float32 literal, they can be written by writing f in the place of e as follows − julia> 0.5f-5 5.0f-6 julia> typeof(ans) Float32 julia> 1.5f0 1.5f0 julia> typeof(ans) Float32 Floating-point types The table given below shows the floating-point types in Julia − Type Precision Number of bits Float16 half 16 Float32 single 32 Float64 double 64 Floating-point zeros There are two kind of floating-point zeros, one is positive zero and other is negative zero. They are same but their binary representation is different. It can be seen in the example below − julia> 0.0 == -0.0 true julia> bitstring(0.0) ”0000000000000000000000000000000000000000000000000000000000000000″ julia> bitstring(-0.0) ”1000000000000000000000000000000000000000000000000000000000000000″ Special floating-point values The table below represents three specified standard floating-point values. These floating-point values do not correspond to any point on the real number line. Float16 Float32 Float64 Name Description Inf16 Inf32 Inf positive infinity It is the value greater than all finite floating-point values -Inf16 -Inf32 -Inf negative infinity It is the value less than all finite floating-point values NaN16 NaN32 NaN not a number It is a value not == to any floating-point value (including itself) We can also apply typemin and typemax functions as follows − julia> (typemin(Float16),typemax(Float16)) (-Inf16, Inf16) julia> (typemin(Float32),typemax(Float32)) (-Inf32, Inf32) julia> (typemin(Float64),typemax(Float64)) (-Inf, Inf) Machine epsilon Machine epsilon is the distance between two adjacent representable floating-point numbers. It is important to know machine epsilon because most of the real numbers cannot be represented exactly with floating-point numbers. In Julia, we have eps() function that gives us the distance between 1.0 and the next larger representable floating-point value. The example is given below − julia> eps(Float32) 1.1920929f-7 julia> eps(Float64) 2.220446049250313e-16 Rounding modes As we know that the number should be rounded to an appropriate representable value if it does not have an exact floating-point representation. Julia uses the default mode called RoundNearest. It rounds to the nearest integer, with ties being rounded to the nearest even integer. For example, julia> BigFloat(“1.510564889″,2,RoundNearest) 1.5 Print Page Previous Next Advertisements ”;
Julia – Discussion
Discuss Julia ”; Previous Next One of the facts about scientific programming is that it requires high performance flexible dynamic programming language. Unfortunately, to a great extent, the domain experts have moved to slower dynamic programming languages. There can be many good reasons for using such dynamic programming languages and, in fact, their use cannot be diminished as well. On the flip side, what can we expect from modern language design and compiler techniques? Some of the expectations are as follows −; It should eradicate the performance trade-off. It should provide the domain experts a single environment that is productive enough for prototyping and efficient for deploying performance-intensive applications. Print Page Previous Next Advertisements ”;
Julia – Dictionaries & Sets
Julia – Dictionaries and Sets ”; Previous Next Many of the functions we have seen so far are working on arrays and tuples. Arrays are just one type of collection, but Julia has other kind of collections too. One such collection is Dictionary object which associates keys with values. That is why it is called an ‘associative collection’. To understand it better, we can compare it with simple look-up table in which many types of data are organized and provide us the single piece of information such as number, string or symbol called the key. It doesn’t provide us the corresponding data value. Creating Dictionaries The syntax for creating a simple dictionary is as follows − Dict(“key1” => value1, “key2” => value2,,…, “keyn” => valuen) In the above syntax, key1, key2…keyn are the keys and value1, value2,…valuen are the corresponding values. The operator => is the Pair() function. We can not have two keys with the same name because keys are always unique in dictionaries. Example julia> first_dict = Dict(“X” => 100, “Y” => 110, “Z” => 220) Dict{String,Int64} with 3 entries: “Y” => 110 “Z” => 220 “X” => 100 We can also create dictionaries with the help of comprehension syntax. The example is given below − Example julia> first_dict = Dict(string(x) => sind(x) for x = 0:5:360) Dict{String,Float64} with 73 entries: “320” => -0.642788 “65” => 0.906308 “155” => 0.422618 “335” => -0.422618 “75” => 0.965926 “50” => 0.766044 ⋮ => ⋮ Keys As discussed earlier, dictionaries have unique keys. It means that if we assign a value to a key that already exists, we will not be creating a new one but modifying the existing key. Following are some operations on dictionaries regarding keys − Searching for a key We can use haskey() function to check whether the dictionary contains a key or not − julia> first_dict = Dict(“X” => 100, “Y” => 110, “Z” => 220) Dict{String,Int64} with 3 entries: “Y” => 110 “Z” => 220 “X” => 100 julia> haskey(first_dict, “Z”) true julia> haskey(first_dict, “A”) false Searching for a key/value pair We can use in() function to check whether the dictionary contains a key/value pair or not − julia> in((“X” => 100), first_dict) true julia> in((“X” => 220), first_dict) false Add a new key-value We can add a new key-value in the existing dictionary as follows − julia> first_dict[“R”] = 400 400 julia> first_dict Dict{String,Int64} with 4 entries: “Y” => 110 “Z” => 220 “X” => 100 “R” => 400 Delete a key We can use delete!() function to delete a key from an existing dictionary − julia> delete!(first_dict, “R”) Dict{String,Int64} with 3 entries: “Y” => 110 “Z” => 220 “X” => 100 Getting all the keys We can use keys() function to get all the keys from an existing dictionary − julia> keys(first_dict) Base.KeySet for a Dict{String,Int64} with 3 entries. Keys: “Y” “Z” “X” Values Every key in dictionary has a corresponding value. Following are some operations on dictionaries regarding values − Retrieving all the values We can use values() function to get all the values from an existing dictionary − julia> values(first_dict) Base.ValueIterator for a Dict{String,Int64} with 3 entries. Values: 110 220 100 Dictionaries as iterable objects We can process each key/value pair to see the dictionaries are actually iterable objects − for kv in first_dict println(kv) end “Y” => 110 “Z” => 220 “X” => 100 Here the kv is a tuple that contains each key/value pair. Sorting a dictionary Dictionaries do not store the keys in any particular order hence the output of the dictionary would not be a sorted array. To obtain items in order, we can sort the dictionary − Example julia> first_dict = Dict(“R” => 100, “S” => 220, “T” => 350, “U” => 400, “V” => 575, “W” => 670) Dict{String,Int64} with 6 entries: “S” => 220 “U” => 400 “T” => 350 “W” => 670 “V” => 575 “R” => 100 julia> for key in sort(collect(keys(first_dict))) println(“$key => $(first_dict[key])”) end R => 100 S => 220 T => 350 U => 400 V => 575 W => 670 We can also use SortedDict data type from the DataStructures.ji Julia package to make sure that the dictionary remains sorted all the times. You can check the example below − Example julia> import DataStructures julia> first_dict = DataStructures.SortedDict(“S” => 220, “T” => 350, “U” => 400, “V” => 575, “W” => 670) DataStructures.SortedDict{String,Int64,Base.Order.ForwardOrdering} with 5 entries: “S” => 220 “T” => 350 “U” => 400 “V” => 575 “W” => 670 julia> first_dict[“R”] = 100 100 julia> first_dict DataStructures.SortedDict{String,Int64,Base.Order.ForwardOrdering} with 6 entries: “R” => 100 “S” => 220 “T” => 350 “U” => 400 “V” => 575 “W” => 670 Word Counting Example One of the simple applications of dictionaries is to count how many times each word appears in text. The concept behind this application is that each word is a key-value set and the value of that key is the number of times that particular word appears in that piece of text. In the following example, we will be counting the words in a file name NLP.txtb(saved on the desktop) − julia> f = open(“C://Users//Leekha//Desktop//NLP.txt”) IOStream() julia> wordlist = String[] String[] julia> for line in eachline(f) words = split(line, r”W”) map(w -> push!(wordlist, lowercase(w)), words) end julia> filter!(!isempty, wordlist) 984-element Array{String,1}: “natural” “language” “processing” “semantic” “analysis” “introduction” “to” “semantic” “analysis” “the” “purpose” …………………… …………………… julia> close(f) We can see from the above output that wordlist is now an array of 984 elements. We can create a dictionary to store the words and word count − julia> wordcounts = Dict{String,Int64}() Dict{String,Int64}() julia> for word in wordlist wordcounts[word]=get(wordcounts, word, 0) + 1 end To find out how many times the words appear, we can look up the words in the dictionary as follows − julia> wordcounts[“natural”] 1 julia> wordcounts[“processing”] 1 julia> wordcounts[“and”] 14 We can also sort the dictionary as
Julia – Useful Resources
Julia – Useful Resources ”; Previous Next The following resources contain additional information on Julia. Please use them to get more in-depth knowledge on this. Useful Links on Julia Julia − Official Website of Julia. Julia @ Wikipedia − Julia, its history and various other terms has been explained in simple language. Useful Books on Julia To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;
Julia – Networking
Julia Programming – Networking ”; Previous Next Sockets and Servers To deal with streaming I/O objects such as pipes, TCP sockets, terminals, etc., we need a rich interface which is provided by Julia. This Julia interface is provided to the programmer in synchronous manner despite the fact that it is presented asynchronously at system level. The advantage is that the programmer does not need to think about the underlying asynchronous operations. Before getting deep into this, we should know the concept of well-known ports. Well-known ports The concept of well-known ports and networked services on them was introduced in early 1980s by Berkeley development. It was first introduced to Unix. The basic idea behind this was − A particular network service should associate with a particular port number. And the network packet should be sent tagged with that port number. Some of the well-known ports are as follows − Port 21-file transfer protocol Port 22-SSH Port 25-sendmail Port 80-web servers to deliver HTTP content Port 3306-used commonly by MySQL database Port 28017-used commonly by MongoDB Server Port 6379- Stores Redis key-value Julia’s UDP and TCP sockets The internet protocol (IP) specified following two types of sockets − Unreliable The concept of unreliable socket rests in the fact that some requests which if not serviced, will be ignored, and retired. Example, requesting the network time from NNTP server. All these kinds of sockets are connectionless and operating via UDP (User Datagram Protocol). Reliable The concept of reliable sockets is opposite to unreliable sockets. They are connection full and operate via TCP (Transmission Control Protocol). Julia supports both these sockets (UDP and TCP) and the source code is provided in socket.jl and streams.jl base modules. Example In the example given below, we will be creating a simple server involving TCP sockets − julia> using Sockets julia> @async begin server = listen(ip”127.0.0.1″,2000) while true sock = accept(server) println(“This is TCP server examplen”) end end julia> connect(2000) This is TCP server example Named Pipes Named pipes or UNIX domain sockets is a FIFO(First-in, First-out) stream and an extension to the traditional pipe mechanism on Unix and OS X. It is also available on Windows and has a specific pattern for the name prefix (\.pipe). It is a communication channel which uses a special file. Example We can also create a named pipe server as given below − julia> using Sockets julia> @async begin server = listen(“\\.\pipe\testsocket”) while true sock = accept(server) println(“This is a named pipe server examplen”) end end julia> connect(2000) This is a named pipe server example A TCP web service The functionality of a web browser is different from that of an echo server (which we developed earlier in this section). One important difference is that the web server should be able to return different file formats (JPEG, PNG, GIFs, TXT, etc.) and the browser should be able to distinguish between them. Example The following example will return a random quote as plain text from a text file − julia> function web_server(sock::Integer) foo = open(“/Users/Leekha/Desktop/Hello.txt”); header = “””HTTP/1.1 200 OK Content-type: text/plain; charset=us-ascii “”” ; wb = readlines(foo); close(foo); wn = length(wb); @async begin server = listen(sock) while true wi = rand(1:wn) ws = chomp(wb[wi]) sock = accept(server) println(header*ws) end end end web_server (generic function with 1 method) julia> web_server(8080) Task (runnable) @0x0000000014bae570 julia> conn = connect(8080) HTTP/1.1 200 OK Content-type: text/plain; charset=us-ascii Hello, This is Tutorialspoint TCPSocket(Base.Libc.WindowsRawSocket(0x00000000000003f8) open, 0 bytes waiting) The Julia Web Group The web browsers are mainly built with the property to respond to the request issued for a browser. Here we will discuss how we can interact with the Web through HTTP requests (for getting as well as posting data to the web). First, we need to import the Requests.jl package as follows − Pkg.add(“Requests”) Next, import the necessary modules namely get and post as follows − import Requests: get, post Use GET request to request data from a specified web browser as follows − get(“url of the website”) If you want to request from a specified web page inside the website, use the query parameter as follows − get(“url of the website”; query = Dict(“title”=>”pagenumber/page name”)) We can also set the timeouts for the GET request as follows − get(“url of the website”; timeout = 0.2) We can use the below command to avoid getting your request repeatedly redirected to different websites − get(“url of the website”; max_redirects = 2) Using the below command prevents the site from redirecting your GET request − get(“url of tcommand he website”; allow_redirects = false) To send the post request, we have to use the below command − post(“url of the website”) Using the below command, we can send data to web browser through the POST request − post(“url of the website”, data = “Data to be sent”) Let us see how we can send data such as session cookies to web browser through the POST request − post(“url of the website”, cookies = Dict(“sessionkey”=> “key”) Files can also be sent as follows − file = “book.jl” post(“url of the website”; files = [FileParam(file), “text/julia”, ”file_name”, “file_name.jl”]) WebSockets We are familiar with the method called AJAX (Asynchronous JavaScript and XML). The example for this method can be the process where we type in the search box and the server returns a set of suggestions and they change as the search term is refined. With this, it is clear that the overhead usage of HTTP protocols is very high. Web Sockets, which combine the parts of UDP and TCP, are the way to overcome this problem. Hence, web sockets are message-based such as UDP and reliable as TCP. It uses normal HTTP/HTTPS ports,
Julia – Flow Control
Julia – Flow Control ”; Previous Next As we know that each line of a program in Julia is evaluated in turn hence it provides many of the control statements (familiar to other programming languages) to control and modify the flow of evaluation. Following are different ways to control the flow in Julia programming language − Ternary and compound expressions Boolean switching expressions If elseif else end (conditional evaluation) For end (iterative evaluation) While end (iterative conditional evaluation) Try catch error throw (exception handling) Do blocks Ternary expressions It takes the form expr ? a : b. It is called ternary because it takes three arguments. The expr is a condition and if it is true then a will be evaluated otherwise b. Example for this is given below − julia> A = 100 100 julia> A < 20 ? “Right” : “wrong” ”wrong” julia> A > 20 ? “Right” : “wrong” ”Right” Boolean Switching expressions As the name implies, the Boolean switching expression allows us to evaluate an expression if the condition is met, i.e., the condition is true. There are two operators to combine the condition and expression − The && operator (and) If this operator is used in the Boolean switching expression, the second expression will be evaluated if the first condition is true. If the first condition is false, the expression will not be evaluated and only the condition will be returned. Example julia> isodd(3) && @warn(“An odd Number!”) ┌ Warning: An odd Number! └ @ Main REPL[5]:1 julia> isodd(4) && @warn(“An odd Number!”) false The || operator (or) If this operator is used in the Boolean switching expression, the second expression will be evaluated only if the first condition is false. If the first condition is true, then there is no need to evaluate the second expression. Example julia> isodd(3) || @warn(“An odd Number!”) true julia> isodd(4) || @warn(“An odd Number!”) ┌ Warning: An odd Number! └ @ Main REPL[8]:1 If, elseif and else We can also use if, elseif, and else for conditions execution. The only condition is that all the conditional construction should finish with end. Example julia> fruit = “Apple” ”Apple” julia> if fruit == “Apple” println(“I like Apple”) elseif fruit == “Banana” println(“I like Banana.”) println(“But I prefer Apple.”) else println(“I don”t know what I like”) end I like Apple julia> fruit = “Banana” ”Banana” julia> if fruit == “Apple” println(“I like Apple”) elseif fruit == “Banana” println(“I like Banana.”) println(“But I prefer Apple.”) else println(“I don”t know what I like”) end I like Banana. But I prefer Apple. for loops Some of the common example of iteration are − working through a list or set of values or from a start value to a finish value. We can iterate through various types of objects like arrays, sets, dictionaries, and strings by using “for” loop (for…end construction). Let us understand the syntax with the following example − julia> for i in 0:5:50 println(i) end 0 5 10 15 20 25 30 35 40 45 50 In the above code, the variable ‘i’ takes the value of each element in the array and hence will step from 0 to 50 in steps of 5. Example (Iterating over an array) In case if we iterate through array, it is checked for change each time through the loop. One care should be taken while the use of ‘push!’ to make an array grow in the middle of a particular loop. julia> c = [1] julia> 1-element Array{Int64,1}: 1 julia> for i in c push!(c, i) @show c sleep(1) end c = [1,1] c = [1,1,1] c = [1,1,1,1] … Note − To exit the output, press Ctrl+c. Loop variables Loop variable is a variable that steps through each item. It exists only inside the loop. It disappears as soon as the loop finishes. Example julia> for i in 0:5:50 println(i) end 0 5 10 15 20 25 30 35 40 45 50 julia> i ERROR: UndefVarError: i not defined Example Julia provides global keyword for remembering the value of the loop variable outside the loop. julia> for i in 1:10 global hello if i % 3 == 0 hello = i end end julia> hello 9 Variables declared inside a loop Similar to Loop Variable, the variables declared inside a loop won’t exist once the loop is finished. Example julia> for x in 1:10 y = x^2 println(“$(x) squared is $(y)”) end Output 1 squared is 1 2 squared is 4 3 squared is 9 4 squared is 16 5 squared is 25 6 squared is 36 7 squared is 49 8 squared is 64 9 squared is 81 10 squared is 100 julia> y ERROR: UndefVarError: y not defined Continue Statement The Continue statement is used to skip the rest of the code inside the loop and start the loop again with the next value. It is mostly used in the case when on a particular iteration you want to skip to the next value. Example julia> for x in 1:10 if x % 4 == 0 continue end println(x) end Output 1 2 3 5 6 7 9 10 Comprehensions Generating and collecting items something like [n for n in 1:5] is called array comprehensions. It is sometimes called list comprehensions too. Example julia> [X^2 for X in 1:5] 5-element Array{Int64,1}: 1 4 9 16 25 We can also specify the types of elements we want to generate − Example julia> Complex[X^2 for X in 1:5] 5-element Array{Complex,1}: 1 + 0im 4 + 0im 9 + 0im 16 + 0im 25 + 0im Enumerated arrays Sometimes we would like to go through an array element by element while keeping track of the index number of every element of that array. Julia has enumerate() function for this task. This function gives us an iterable version of something. This function will produce the index number as well as the value at each index number. Example julia> arr
Julia – Plotting
Julia Programming – Plotting ”; Previous Next Julia has various packages for plotting and before starting making plots, we need to first download and install some of them as follows − (@v1.5) pkg> add Plots PyPlot GR UnicodePlots The package Plots is a high-level plotting package, also referred to as ‘back-ends’ interfaces with other plotting packages. To start using the Plots package, type the following command − julia> using Plots [ Info: Precompiling Plots [91a5bcdd-55d7-5caf-9e0b-520d859cae80] Plotting a function For plotting a function, we need to switch back to PyPlot back-end as follows − julia> pyplot() Plots.PyPlotBackend() Here we will be plotting the equation of Time graph which can be modeled by the following function − julia> eq(d) = -7.65 * sind(d) + 9.87 * sind(2d + 206); julia> plot(eq, 1:365) sys:1: MatplotlibDeprecationWarning: Passing the fontdict parameter of _set_ticklabels() positionally is deprecated since Matplotlib 3.3; the parameter will become keyword-only two minor releases later. sys:1: UserWarning: FixedFormatter should only be used together with FixedLocator Packages Everyone wants a package that helps them to draw quick plots by text rather than graphics. UnicodePlots Julia provides one such package called UnicodePlots which can produce the following − scatter plots line plots bar plots staircase plots histograms sparsity patterns density plots We can add it to our Julia installation by the following command − (@v1.5) pkg> add UnicodePlots Once added, we can use this to plot a graph as follows: julia> using UnicodePlots Example Following Julia example generates a line chart using UnicodePlots. julia> FirstLinePlot = lineplot([1, 2, 3, 7], [1, 2, -5, 7], title=”First Line Plot”, border=:dotted) First Line Plot Example Following Julia example generates a density chart using UnicodePlots. Julia> using UnicodePlots Julia> FirstDensityPlot = densityplot(collect(1:100), randn(100), border=:dotted) VegaLite This Julia package is a visualization grammar which allows us to create visualization in a web browser window. With this package, we can − describe data visualization in a JSON format generate interactive views using HTML5 Canvas or SVG It can produce the following − Area plots Bar plots/Histograms Line plots Scatter plots Pie/Donut charts Waterfall charts Worldclouds We can add it to our Julia installation by following command − (@v1.5) pkg> add VegaLite Once added we can use this to plot a graph as follows − julia> using VegaLite Example Following Julia example generates a Pie chart using VegaLite. julia> X = [“Monday”, “Tuesday”, “Wednesday”, “Thrusday”, “Friday”,”Saturday”,”Sunday”]; julia> Y = [11, 11, 15, 13, 12, 13, 10] 7-element Array{Int64,1}: 11 11 15 13 12 13 10 julia> P = pie(X,Y) Print Page Previous Next Advertisements ”;
Julia – Data Frames
Julia Programming – Data Frames ”; Previous Next DataFrame may be defined as a table or spreadsheet which we can be used to sort as well as explore a set of related data values. In other words, we can call it a smarter array for holding tabular data. Before we use it, we need to download and install DataFrame and CSV packages as follows − (@v1.5) pkg> add DataFrames (@v1.5) pkg> add CSV To start using the DataFrames package, type the following command − julia> using DataFrames Loading data into DataFrames There are several ways to create new DataFrames (which we will discuss later in this section) but one of the quickest ways to load data into DataFrames is to load the Anscombe dataset. For better understanding, let us see the example below − anscombe = DataFrame( [10 10 10 8 8.04 9.14 7.46 6.58; 8 8 8 8 6.95 8.14 6.77 5.76; 13 13 13 8 7.58 8.74 12.74 7.71; 9 9 9 8 8.81 8.77 7.11 8.84; 11 11 11 8 8.33 9.26 7.81 8.47; 14 14 14 8 9.96 8.1 8.84 7.04; 6 6 6 8 7.24 6.13 6.08 5.25; 4 4 4 19 4.26 3.1 5.39 12.5; 12 12 12 8 10.84 9.13 8.15 5.56; 7 7 7 8 4.82 7.26 6.42 7.91; 5 5 5 8 5.68 4.74 5.73 6.89]); julia> rename!(anscombe, [Symbol.(:N, 1:4); Symbol.(:M, 1:4)]) 11×8 DataFrame │ Row │ N1 │ N2 │ N3 │ N4 │ M1 │ M2 │ M3 │ M4 │ │ │ Float64 │ Float64 │ Float64 │ Float64 │ Float64 │ Float64 │ Float64 │ Float64 │ ├─────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┤ │ 1 │ 10.0 │ 10.0 │ 10.0 │ 8.0 │ 8.04 │ 9.14 │ 7.46 │ 6.58 │ │ 2 │ 8.0 │ 8.0 │ 8.0 │ 8.0 │ 6.95 │ 8.14 │ 6.77 │ 5.76 │ │ 3 │ 13.0 │ 13.0 │ 13.0 │ 8.0 │ 7.58 │ 8.74 │ 12.74 │ 7.71 │ │ 4 │ 9.0 │ 9.0 │ 9.0 │ 8.0 │ 8.81 │ 8.77 │ 7.11 │ 8.84 │ │ 5 │ 11.0 │ 11.0 │ 11.0 │ 8.0 │ 8.33 │ 9.26 │ 7.81 │ 8.47 │ │ 6 │ 14.0 │ 14.0 │ 14.0 │ 8.0 │ 9.96 │ 8.1 │ 8.84 │ 7.04 │ │ 7 │ 6.0 │ 6.0 │ 6.0 │ 8.0 │ 7.24 │ 6.13 │ 6.08 │ 5.25 │ │ 8 │ 4.0 │ 4.0 │ 4.0 │ 19.0 │ 4.26 │ 3.1 │ 5.39 │ 12.5 │ │ 9 │ 12.0 │ 12.0 │ 12.0 │ 8.0 │ 10.84 │ 9.13 │ 8.15 │ 5.56 │ │10 │ 7.0 │ 7.0 │ 7.0 │ 8.0 │ 4.82 │ 7.26 │ 6.42 │ 7.91 │ │11 │ 5.0 │ 5.0 │ 5.0 │ 8.0 │ 5.68 │ 4.74 │ 5.73 │ 6.89 │ We assigned the DataFrame to a variable named Anscombe, convert them to an array and then rename columns. Collected Datasets We can also use another dataset package named RDatasets package. It contains several other famous datasets including Anscombe’s. Before we start using it, we need to first download and install it as follows − (@v1.5) pkg> add RDatasets To start using this package, type the following command − julia> using DataFrames julia> anscombe = dataset(“datasets”,”anscombe”) 11×8 DataFrame │ Row │ X1 │ X2 │ X3 │ X4 │ Y1 │ Y2 │ Y3 │ Y4 │ │ │ Int64 │ Int64 │ Int64 │ Int64 │ Float64 │ Float64 │ Float64 │ Float64 │ ├─────┼───────┼───────┼───────┼───────┼─────────┼─────────┼─────────┼─────────┤ │ 1 │ 10 │ 10 │ 10 │ 8 │ 8.04 │ 9.14 │ 7.46 │ 6.58 │ │ 2 │ 8 │ 8 │ 8 │ 8 │ 6.95 │ 8.14 │ 6.77 │ 5.76 │ │ 3 │ 13 │ 13 │ 13 │ 8 │ 7.58 │ 8.74 │ 12.74│ 7.71 │ │ 4 │ 9 │ 9 │ 9 │ 8 │ 8.81 │ 8.77 │ 7.11 │ 8.84 │ │ 5 │ 11 │ 11 │ 11 │ 8 │ 8.33 │ 9.26 │ 7.81 │ 8.47 │ │ 6 │ 14 │ 14 │ 14 │ 8 │ 9.96 │ 8.1 │ 8.84 │ 7.04 │ │ 7 │ 6 │ 6 │ 6 │ 8 │ 7.24 │ 6.13 │ 6.08 │ 5.25 │ │ 8 │ 4 │ 4 │ 4 │ 19 │ 4.26 │ 3.1 │ 5.39 │ 12.5 │ │ 9 │ 12 │ 12 │ 12 │ 8 │ 10.84 │ 9.13 │ 8.15 │ 5.56 │ │ 10 │ 7 │ 7 │ 7 │ 8 │ 4.82 │ 7.26 │ 6.42 │ 7.91 │ │ 11 │ 5 │ 5 │ 5 │ 8 │ 5.68 │ 4.74 │ 5.73 │ 6.89 │ Empty DataFrames We can also create DataFrames by simply providing the information about rows, columns as we give in an array. Example julia> empty_df = DataFrame(X = 1:10, Y = 21:30) 10×2 DataFrame │ Row │ X │ Y │ │ │ Int64 │ Int64 │ ├─────┼───────┼───────┤ │ 1 │ 1 │ 21 │ │ 2 │ 2 │ 22 │ │ 3 │ 3 │ 23 │ │ 4 │ 4 │ 24 │ │ 5 │ 5 │ 25 │ │ 6 │ 6 │ 26 │ │ 7 │ 7 │ 27 │ │ 8 │ 8 │ 28 │ │ 9 │ 9 │ 29 │ │ 10 │ 10 │ 30 │ To create completely empty DataFrame, we only need to supply the Column Names and define their types as follows − julia> Complete_empty_df = DataFrame(Name=String[], W=Float64[], H=Float64[], M=Float64[], V=Float64[]) 0×5 DataFrame julia> Complete_empty_df = vcat(Complete_empty_df, DataFrame(Name=”EmptyTestDataFrame”, W=5.0, H=5.0, M=3.0, V=5.0)) 1×5 DataFrame │ Row │ Name │ W │ H │ M │ V │ │ │ String │ Float64 │ Float64 │ Float64 │ Float64 │ ├─────┼────────────────────┼─────────┼─────────┼─────────┼─────────┤ │ 1 │ EmptyTestDataFrame │ 5.0 │ 5.0 │ 3.0 │ 5.0 │ julia> Complete_empty_df = vcat(Complete_empty_df, DataFrame(Name=”EmptyTestDataFrame2″, W=6.0, H=6.0, M=5.0, V=7.0)) 2×5 DataFrame │ Row │ Name │ W │ H │ M │ V │ │ │
Julia – Modules and Packages
Julia Programming – Modules and Packages ”; Previous Next The modules in Julia programming language are used to group together the related functions and other definitions. The structure of a module is given below − module ModuleName end We can define and put functions, type definitions, and so on in between above two lines. Installing Modules Julia’s package manager can be used to download and install a particular package. To enter the package manage from REPL, type ] (right bracket). Once entering the package manager, you need to type the following command − (@v1.5) pkg> add DataFrames Updating registry at `C:UsersLeekha.juliaregistriesGeneral` Resolving package versions… Updating `C:UsersLeekha.juliaenvironmentsv1.5Project.toml` [a93c6f00] + DataFrames v0.21.7 No Changes to `C:UsersLeekha.juliaenvironmentsv1.5Manifest.toml` The above command will add DataFrames package to Julia’s environment. The (@v1.5) in the prompt tells us that we are working in the default project, “v1.5”, in ~/.julia/environments/. Using Modules Once installed, it is time to start using the functions and definitions from the installed module. For this we need to tell Julia programming language to make code available for our current session. Use using statement which will accept the names of one or more installed modules. Example julia> using DataFrames [ Info: Precompiling DataFrames [a93c6f00-e57d-5684-b7b6-d8193f3e46c0] julia> empty_df = DataFrame(X = 1:10, Y = 21:30) 10×2 DataFrame │ Row │ X │ Y │ │ │ Int64 │ Int64 │ ├─────┼───────┼───────┤ │ 1 │ 1 │ 21 │ │ 2 │ 2 │ 22 │ │ 3 │ 3 │ 23 │ │ 4 │ 4 │ 24 │ │ 5 │ 5 │ 25 │ │ 6 │ 6 │ 26 │ │ 7 │ 7 │ 27 │ │ 8 │ 8 │ 28 │ │ 9 │ 9 │ 29 │ │ 10 │ 10 │ 30 │ Import Like using, import can also be used for modules. The only difference is that import lets you decide how you would like to access the functions inside the module. In the below example, we have two different functions in a module. Let us see how we can import them − Example julia> module first_module export foo1 function foo1() println(“this is first function”) end function foo2() println(“this is second function”) end end Main.first_module Now we need to use import to import this module − julia> import first_module julia> foo1() ERROR: foo1 not defined julia> first_module.foo1() ”this is first function” You can notice that the function foo1() can only be accessed if it is used with module prefix. It is because the first_module was loaded using import command rather than using command. Include What if you want to use the code from other files that are not contained in the modules? For this you can use include() function which will evaluate the contents of the file in the context of the current module. It will search the relative path of the source file from which it is called. Packages Use status command in Julia package environment to see all the packages you have installed. (@v1.5) pkg> status Status `C:UsersLeekha.juliaenvironmentsv1.5Project.toml` [336ed68f] CSV v0.7.7 [a93c6f00] DataFrames v0.21.7 [864edb3b] DataStructures v0.18.6 [7806a523] DecisionTree v0.10.10 [38e38edf] GLM v1.3.10 [28b8d3ca] GR v0.52.0 [86223c79] Graphs v0.10.3 [7073ff75] IJulia v1.21.3 [682c06a0] JSON v0.21.1 [91a5bcdd] Plots v1.6.8 [d330b81b] PyPlot v2.9.0 [ce6b1742] RDatasets v0.6.10 [3646fa90] ScikitLearn v0.6.2 [f3b207a7] StatsPlots v0.14.13 [b8865327] UnicodePlots v1.3.0 [112f6efa] VegaLite v1.0.0 Structure of a package As we know that Julia uses git for organizing as well controlling the packages. All the packages are stored with .ji prefix. Let us see the structure of Calculus package − Calculus.jl/ src/ Calculus.jl module Calculus import Base.ctranspose export derivative, check_gradient, … include(“derivative.jl”) include(“check_derivative.jl”) include(“integrate.jl”) end derivative.jl function derivative() … end … check_derivative.jl function check_derivative(f::…) … end … integrate.jl function adaptive_simpsons_inner(f::Funct … end … symbolic.jl export processExpr, BasicVariable, … import Base.show, … type BasicVariable <: AbstractVariable … end function process(x::Expr) … end … test/ runtests.jl using Calculus using Base.Test tests = [“finite_difference”, … for t in tests include(“$(t).jl”) end … finite_difference.jl @test … … Print Page Previous Next Advertisements ”;