Julia is a high-level, high-performance dynamic programming language for
technical computing. This site is a non ofcial series of examples of Julia, for more details see about. Below are a series of examples of common operations in Julia. They assume you already have Julia installed and working the examples are currently tested with Julia v!." - latest#. $ello %orld &imple 'unctions &trings Basics &tring( )onverting and formatting &tring *anipulations +rrays ,rror $andling *ultidimensional +rrays -ictionaries .oops and *ap Types /nput 0 1utput 2ackages and /ncluding of 'iles 2lotting Text2lots 2y2lot %inston 3ad4y -ata'rames Hello World The simplest possible script. println("hello world") %ith Julia installed and added to your path this script can be run by julia hello_world.jl, it can also be run from 5,2. by typing include("hello_world.jl"), that will evaluate all valid expressions in that 6le and return the last output. Simple Functions The example below shows two simple functions, how to call them and print the results. 'urther examples of number formatting are shown below.
# function to calculate the volume of a sphere function sphere_vol(r) # julia allows Unicode names (in UTF-8 encodin) # so either "pi" or the s!m"ol # can "e used return $%&'pi'r(& end # functions can also "e defined more succinctl! )uadratic(a* s)r_term* ") + (-" , s)r_term) % -a # calculates . for / + a'.(-,"'.,c* aruments t!pes can "e defined in function definitions function )uadratic-(a00Float1$* "00Float1$* c00Float1$) # unli2e other lanuaes -a is e)uivalent to -'a # a(- is used instead of a''- or pow(a*-) s)r_term + s)rt("(--$a'c) r3 + )uadratic(a* s)r_term* ") r- + )uadratic(a* -s)r_term* ") # multiple values can "e returned from a function usin tuples # if the return 2e!word is omitted* the last term is returned r3* r- end vol + sphere_vol(&) # 4printf allows num"er formattin "ut does not automaticall! append the 5n to statements* see "elow 4printf "volume + 6/.&f5n" vol #7 volume + 33&./89 )uad3* )uad- + )uadratic-(-./* --./* -3-./) println("result 30 "* )uad3) #7 result 30 &./ println("result -0 "* )uad-) #7 result -0 --./ Strings Basics )ollection of di7erent string examples string indexing is the same as array indexing( see below#. # strins are defined with dou"le )uotes # li2e varia"les* strins can contain an! unicode character s3 + "The )uic2 "rown fo. jumps over the la:! do ;*<*=" println(s3) #7 The )uic2 "rown fo. jumps over the la:! do ;*<*= # println adds a new line to the end of output # print can "e used if !ou dont want that0 print("this") #7 this print(" and") #7 and print(" that.5n") #7 that. # chars are defined with sinle )uotes c3 + >a> println(c3) #7 a # the ascii value of a char can "e found with int()0 println(c3* " ascii value + "* int(c3)) #7 a ascii value + 89 println("int(>;>) ++ "* int(>;>)) #7 int(>;>) ++ 8$? # so "e aware that println(int(>3>) ++ 3) #7 false # strins can "e converted to upper case or lower case0 s3_caps + uppercase(s3) s3_lower + lowercase(s3) println(s3_caps* "5n"* s3_lower) #7 T@A BUCDE FGHIJ FHK LUMNO HPAG T@A QRST UHV W*X*Y #7 the )uic2 "rown fo. jumps over the la:! do ;*<*= # su" strins can "e inde.ed li2e arra!s0 # (show prints the raw value) show(s3Z33[)\ println() #7 >"> # or su" strins can "e created0 show(s3Z303/[)\ println() #7 "The )uic2 " # end is used for the end of the arra! or strin show(s3Zend-3/0end[)\ println() #7 "do ;*<*=" # julia allows strin Cnterpolation0 a + "wolcome" " + "julia" println("]a to ]".") #7 wolcome to julia. # this can e.tend to evaluate statements0 println("3 , - + ](3 , -)") #7 3 , - + & # strins can also "e concatenated usin the ' operator # usin ' instead of , isn>t intuitive when !ou start with Lulia* # however people thin2 it ma2es more sense s- + "this" ' " and" ' " that" println(s-) #7 this and that # as well as the strin function s& + strin("this"* " and"* " that") println(s&) #7 this and that String: Converting and formatting # strins can "e converted usin float and int0 e_str3 + "-.938" e + float(e_str3) println(?e) #7 3&.?83$ num_3? + int("3?") println(&num_3?) #7 $? # num"ers can "e converted to strins and formatted usin printf 4printf "e + 6/.-f5n" e #7 -.938 # or to create another strin sprintf e_str- + 4sprintf("6/.&f"* e) # to show that the - strins are the same println("e_str3 ++ e_str-0 ](e_str3 ++ e_str-)") #7 e_str3 ++ e_str-0 true # availa"le num"er format characters are f* e* * c* s* p* d0 # (pi is a predefined constant\ however* since its t!pe is # "MathDonst" it has to "e converted to a float to "e formatted) 4printf "fi. trailin precision0 6/.&f5n" float(pi) #7 fi. trailin precision0 &.3$- 4printf "scientific form0 6/.1e5n" 3///pi #7 scientific form0 &.3$3?8&e,/& # is not implemented !et 4printf "a character0 6c5n" >;> #7 a character0 ; 4printf "a strin0 6s5n" "loo2 C>m a strin^" #7 a strin0 loo2 C>m a strin^ 4printf "riht justif! a strin0 6?/s5n" "width ?/* te.t riht justified^" #7 riht justif! a strin0 width ?/* te.t riht justified^ 4printf "a pointer0 6p5n" 3e3/ #7 a pointer0 /.///////-?$/"e$// 4printf "print a inteer0 6d5n" 3e3/ #7 print an inteer0 3////////// String Manipulations s3 + "The )uic2 "rown fo. jumps over the la:! do ;*<*=" # search returns the first inde. of a char i + search(s3* >">) println(i) #7 33 # the second arument is e)uivalent to the second arument of split* see "elow # or a rane if called with another strin r + search(s3* ""rown") println(r) #7 3303? # strin replace is done thus0 r + replace(s3* ""rown"* "red") show(r)\ println() #7 "The )uic2 red fo. jumps over the la:! do" # search and replace can also ta2e a reular e.pressions "! precedin the strin with >r> r + search(s3* r""Z5w['n") println(r) #7 3303? # aain with a reular e.pression r + replace(s3* r""Z5w['n"* "red") show(r)\ println() #7 "The )uic2 red fo. jumps over the la:! do" # there are also functions for reular e.pressions that return Gee.Match t!pes # match scans left to riht for the first match (specified startin inde. optional) r + match(r""Z5w['n"* s3) println(r) #7 Gee.Match(""rown") # Gee.Match t!pes have a propert! match that holds the matched strin show(r.match)\ println() #7 ""rown" # matchall returns a vector with Gee.Matches for each match r + matchall(r"Z5w[_$*`"* s3) println(r) #7 Ou"Otrin_UTF8Otrin`Z")uic2"*""rown"*"jumps"*"over"*"la:!"[ # eachmatch returns an iterator over all the matches r + eachmatch(r"Z5w[_$*`"* s3) for(i in r) print("5"](i.match)5" ") end println() #7 ")uic2" ""rown" "jumps" "over" "la:!" # a strin can "e repeated usin the repeat function* # or more succinctl! with the ( s!nta.0 r + "hello "(& show(r)\ println() #7 "hello hello hello " # the strip function wor2s the same as p!thon0 # e..* with one arument it strips the outer whitespace r + strip("hello ") show(r)\ println() #7 "hello" # or with a second arument of an arra! of chars it strips an! of them\ r + strip("hello "* Z>h>* > >[) show(r)\ println() #7 "ello" # (note the arra! is of chars and not strins) # similarl! split wor2s in "asicall! the same wa! as p!thon0 r + split("hello* there*"o""* >*>) show(r)\ println() #7 Z"hello"*" there"*""o""[ r + split("hello* there*"o""* "* ") show(r)\ println() #7 Z"hello"*"there*"o""[ r + split("hello* there*"o""* Z>*>* > >[* /* false) show(r)\ println() #7 Z"hello"*"there"*""o""[ # (the last two aruements are limit and include_empt!* see docs) # the opposite of split0 join is simpl! r+ join(Z303/[* "* ") println(r) #7 3* -* &* $* ?* 1* 9* 8* 8* 3/ Arrays function printsum(a) # summar! enerates a summar! of an o"ject println(summar!(a)* "0 "* repr(a)) end # arra!s can "e initialised directl!0 a3 + Z3*-*&[ printsum(a3) #7 &-element Rrra!_Cnt1$*3`0 Z3*-*&[ # or initialised empt!0 a- + Z[ printsum(a-) #7 /-element Rrra!_Jone*3`0 JoneZ[ # since this arra! has no t!pe* functions li2e push^ (see "elow) don>t wor2 # instead arra!s can "e initialised with a t!pe0 a& + Cnt1$Z[ printsum(a&) #7 /-element Rrra!_Cnt1$*3`0 Z[ # ranes are different from arra!s0 a$ + 30-/ printsum(a$) #7 -/-element UnitGane_Cnt1$`0 30-/ # however the! can "e used to create arra!s thus0 a$ + Z30-/[ printsum(a$) #7 -/-element Rrra!_Cnt1$*3`0 Z3*-*&*$*?*1*9*8*8*3/*33*3-*3&*3$*3?*31*39*38*38*-/[ # arra!s can also "e enerated from comprehensions0 a? + Z-(i for i + 303/[ printsum(a?) #7 3/-element Rrra!_Cnt1$*3`0 Z-*$*8*31*&-*1$*3-8*-?1*?3-*3/-$[ # arra!s can "e an! t!pe* so arra!s of arra!s can "e created0 a1 + (Rrra!_Cnt1$* 3`)Z[ printsum(a1) #7 /-element Rrra!_Rrra!_Cnt1$*3`*3`0 Z[ # (note this is a "jaed arra!" (i.e.* an arra! of arra!s)* not a multidimensional arra!* these are not covered here) # Lulia provided a num"er of "Ue)ueue" functions* the most common for appendin to the end of arra!s is push! # ^ at the end of a function name indicates that the first arument is updated. push^(a3* $) printsum(a3) #7 $-element Rrra!_Cnt1$*3`0 Z3*-*&*$[ # push^(a-* 3) would cause error0 push^(a&* 3) printsum(a&) #7 3-element Rrra!_Cnt1$*3`0 Z3[ #7 3-element Rrra!_Cnt1$*3`0 Z3[ push^(a1* Z3*-*&[) printsum(a1) #7 3-element Rrra!_Rrra!_Cnt1$*3`*3`0 ZZ3*-*&[[ # usin repeat() to create arra!s # !ou must use the 2e!words "inner" and "outer" # all aruments must "e arra!s (not ranes) a9 + repeat(a3*inner+Z-[*outer+Z3[) printsum(a9) #7 8-element Rrra!_Cnt1$*3`0 Z3*3*-*-*&*&*$*$[ a8 + repeat(Z$0-303[*inner+Z3[*outer+Z-[) printsum(a8) #7 8-element Rrra!_Cnt1$*3`0 Z$*&*-*3*$*&*-*3[ Error Handling a+Z[ # tr!* catch can "e used to deal with errors as with man! other lanuaes tr! push^(a*3) catch err showerror(OTUHUT* err* "ac2trace())\println() end println("Dontinuin after error") Multidimensional Arrays Julia has very good multidimensional array capabilities. )heck out the manual. # repeat can "e useful to e.pand a rid # as in G>s e.pand.rid() function0 m3 + hcat(repeat(Z30-[*inner+Z3[*outer+Z&'-[)* repeat(Z30&[*inner+Z-[*outer+Z-[)* repeat(Z30$[*inner+Z&[*outer+Z3[)) printsum(m3) #7 3-.& Rrra!_Cnt1$*-`0 Z3 3 3 #7 - 3 3 #7 3 - 3 #7 - - - #7 3 & - #7 - & - #7 3 3 & #7 - 3 & #7 3 - & #7 - - $ #7 3 & $ #7 - & $[ # for simple repetitions of arra!s* # use repmat m- + repmat(m3*3*-) # replicate a8 once into dim3 and twice into dim- println("si:e0 "* si:e(m-)) #7 si:e0 (3-*1) m& + repmat(m3*-*3) # replicate a8 twice into dim3 and once into dim- println("si:e0 "* si:e(m&)) #7 si:e0 (-$*&) # Lulia comprehensions are another wa! to easil! create # multidimensional arra!s m$ + Zi,j,2 for i+30-* j+30&* 2+30-[ # creates a -.&.- arra! of Cnt1$ m? + Z"@i Cm # ](i,-'(j-3 , &'(2-3)))" for i+30-* j+30&* 2+30-[ # e.pressions are ver! fle.i"le # !ou can specif! the t!pe of the arra! "! just # placin it in front of the e.pression m? + RODCCOtrinZ"@i Cm element # ](i,-'(j-3 , &'(2-3)))" for i+30-* j+30&* 2+30-[ printsum(m?) #7 -.&.- Rrra!_RODCCOtrin*&`0 RODCCOtrinZ"@i Cm element # 3" "@i Cm element # &" "@i Cm element # ?" #7 "@i Cm element # -" "@i Cm element # $" "@i Cm element # 1"[ #7 #7 RODCCOtrinZ"@i Cm element # 9" "@i Cm element # 8" "@i Cm element # 33" #7 "@i Cm element # 8" "@i Cm element # 3/" "@i Cm element # 3-"[ # Rrra! reductions # man! functions in Lulia have an arra! method # to "e applied to specific dimensions of an arra!0 sum(m$*&) # ta2es the sum over the third dimension sum(m$*(3*&)) # sum over first and third dim ma.imum(m$*-) # find the ma. elt alon dim - findma.(m$*&) # find the ma. elt and its inde. alon dim - (availa"le onl! in ver! recent Lulia versions) # Froadcastin # when !ou com"ine arra!s of different si:es in an operation* # an attempt is made to "spread" or ""roadcast" the smaller arra! # so that the si:es match up. "roadcast operators are preceded "! a dot0 m$ ., & # add & to all elements m$ ., Z30-[ # adds vector Z3*-[ to all elements alon first dim # slices and views m$Z0*0*3[ # holds dim & fi.ed and displa!s the resultin view m$Z0*-*0[ # that>s a -.3.- arra!. not ver! intuititive to loo2 at # et rid of dimensions with si:e 30 s)uee:e(m$Z0*-*0[*-) # that>s "etter # assin new values to a certain view m$Z0*0*3[ + rand(301*-*&) printsum(m$) #7 -.&.- Rrra!_Cnt1$*&`0 Z& ? - #7 - - -[ #7 #7 Z$ ? 1 #7 ? 1 9[ # (for more e.amples of tr!* catch see Arror @andlin a"ove) tr! # this will cause an error* !ou have to assin the correct t!pe m$Z0*0*3[ + rand(-*&) catch err println(err) end #7 Cne.actArror() tr! # this will cause an error* !ou have to assin the riht shape m$Z0*0*3[ + rand(301*&*-) catch err println(err) end #7 UimensionMismatch("tried to assin &.- arra! to -.&.3 destination") Dictionaries Julia uses -icts as associative collections. 8sage is very like python except for the rather odd +7 de6nition syntax. # dicts can "e initialised directl!0 a3 + _3+7"one"* -+7"two"` printsum(a3) #7 Uict_Rn!*Rn!`0 _-+7"two"*3+7"one"` # then added to0 a3Z&[+"three" printsum(a3) #7 Uict_Rn!*Rn!`0 _-+7"two"*&+7"three"*3+7"one"` # (note dicts cannot "e assumed to 2eep their oriinal order) # dicts ma! also "e created with the t!pe e.plicitl! set a- + Uict_Cnt1$* Otrin`() a-Z/[+":ero" # dicts* li2e arra!s* ma! also "e created from comprehensions a& + _i +7 4sprintf("6d"* i) for i + 303/` printsum(a&)#7 Uict_Rn!*Rn!`0 _?+7"?"*$+7"$"*1+7"1"*9+7"9"*-+7"-"*3/+7"3/"*8+7"8"*8+7"8"*&+7"&"*3+7"3"` # as !ou would e.pect* Lulia comes with all the normal helper functions # for dicts* e..* (has2e!) Zhttp0%%docs.julialan.or%en%latest%stdli"%"ase%#Fase.has2e![ println(has2e!(a3*3)) #7 true # which is e)uivalent to println(3 in 2e!s(a3)) #7 true # where 2e!s creates an iterator over the 2e!s of the dictionar! # similar to 2e!s* (values) Zhttp0%%docs.julialan.or%en%latest%stdli"%"ase%#Fase.values[ et iterators over the dict>s values0 printsum(values(a3)) #7 PalueCterator_Uict_Rn!*Rn!``0 PalueCterator_Uict_Rn!*Rn!``(_-+7"two"*&+7"three"*3+7"one"`) # use collect to et an arra!0 printsum(collect(values(a3)))#7 &-element Rrra!_Rn!*3`0 _"two"*"three"*"one"` Loops and Map 'or loops can be de6ned in a number of ways. for i in 30? print(i* "* ") end #7 3* -* &* $* ?* # Cn loop definitions "in" is e)uivilent to "+" (RFRCE* the two are interchana"le in this conte.t) for i + 30? print(i* "* ") end println() #7 3* -* &* $* ?* # arra!s can also "e looped over directl!0 a3 + Z3*-*&*$[ for i in a3 print(i* "* ") end println() #7 3* -* &* $* # continue and break wor2 in the same wa! as p!thon a- + Z30-/[ for i in a- if i 6 - ^+ / continue end print(i* "* ") if i 7+ 8 "rea2 end end println() #7 -* $* 1* 8* # if the arra! is "ein manipulated durin evaluation a while loop shoud "e used # pop removes the last element from an arra! while ^isempt!(a3) print(pop^(a3)* "* ") end println() #7 $* &* -* 3* d3 + _3+7"one"* -+7"two"* &+7"three"` # dicts ma! "e looped throuh usin the 2e!s function0 for 2 in sort(collect(2e!s(d3))) print(2* "0 "* d3Z2[* "* ") end println() #7 30 one* -0 two* &0 three* # li2e p!thon enumerate can "e used to et "oth the inde. and value in a loop a& + Z"one"* "two"* "three"[ for (i* v) in enumerate(a&) print(i* "0 "* v* "* ") end println() #7 30 one* -0 two* &0 three* # (note enumerate starts from 3 since Lulia arra!s are 3 inde.ed unli2e p!thon) # map wor2s as !ou miht e.pect performin the iven function on each mem"er of an arra! or iter much li2e comprehensions a$ + map((.) -7 .(-* Z3* -* &* 9[) printsum(a$) #7 $-element Rrra!_Cnt1$*3`0 Z3*$*8*$8[ ypes Types are a key way of structuring data within Julia. # T!pe Uefinitions are pro"a"l! most similar to t!epdefs in ca # a simple t!pe with no special constructor functions miht loo2 li2e this t!pe Nerson name00Otrin male00Fool ae00Float1$ children00Cnt end p + Nerson("Lulia"* false* $* /) printsum(p) #7 Nerson0 Nerson("Lulia"*false*$./*/) people + NersonZ[ push^(people* Nerson("Oteve"* true* $-* /)) push^(people* Nerson("Lade"* false* 39* &)) printsum(people) #7 --element Rrra!_Nerson*3`0 ZNerson("Oteve"*true*$-./*/)*Nerson("Lade"*false*39./*&)[ # t!pes ma! also contains arra!s and dicts # constructor functions can "e defined to easil! create o"jects t!pe Famil! name00Otrin mem"ers00Rrra!_Otrin* 3` e.tended00Fool # constructor that ta2es one arument and enerates a default # for the other two values Famil!(name00Otrin) + new(name* OtrinZ[* false) # constructor that ta2es two aruements and infers the third Famil!(name00Otrin* mem"ers) + new(name* mem"ers* lenth(mem"ers) 7 &) end fam3 + Famil!(""los") println(fam3) #7 Famil!(""los"*OtrinZ[*false) fam- + Famil!("jones"* Z"anna"* ""o""* "charlie"* "dic2"[) println(fam-) #7 Famil!("jones"*OtrinZ"anna"*""o""*"charlie"*"dic2"[*true) !nput " #utput The basic syntax for reading and writing 6les in Julia is 9uite similar to python. The simple.dat 6le used in this example is available from github. fname + "simple.dat" # usin do means the file is closed automaticall! # in the same wa! "with" does in p!thon open(fname*"r") do f for line in eachline(f) print(line) end end #7 this is a simple file containin #7 te.t and num"ers0 #7 $&.& #7 39 f + open(fname*"r") showall(readlines(f)) #7 Union(RODCCOtrin*UTF8Otrin)Z"this is a simple file containin5n"*"te.t and num"ers05n"*"$&.&5n"*"395n"[ close(f) f + open(fname*"r") fstrin + readall(f) close(f) println(summar!(fstrin)) #7 RODCCOtrin print(fstrin) #7 this is a simple file containin #7 te.t and num"ers0 #7 $&.& #7 39 outfile + "outfile.dat" # writin to files is ver! similar0 f + open(outfile* "w") # "oth print and println can "e used as usual "ut with f as their first arument println(f* "some content") print(f* "more content") print(f* " more on the same line") close(f) # we can then chec2 the content of the file written # "do" a"ove just creates an anon!mous function and passes it to open # we can use the same loic to pass readall and there"! succinctl! # open* read and close a file in one line outfile_content + open(readall* outfile* "r") println(repr(outfile_content)) #7 "some content5nmore content more on the same line" $ac%ages and !ncluding of Files 2ackages extend the functionality of Julia:s standard library. # Tou miht not want to run this file completel!* as the N2-commands can ta2e a # lon time to complete. # list all availa"le pac2aes0 N2.availa"le() # install one pac2ae (e.. Dalculus) and all its dependencies0 N2.add("Dalculus") # to list all installed pac2aes N2.installed() # to update all pac2aes to their newest version N2.update() # to use a pac2ae0 usin Dalculus # will import all functions of that pac2ae into the current namespace* so that # it is possi"le to call derivative(. -7 sin(.)* 3./) # without specifin the pac2ae it is included in. import Dalculus # will ena"le !ou to specif! which pac2ae the function is called from Dalculus.derivative(. -7 cos(.)* 3./) # Usin bimportb is especiall! useful if there are conflicts in function%t!pe- names # "etween pac2aes. # A.ample0 # Iinston as well as Vadfl! provide a plot() function (see "elow). N2.add("Iinston") N2.add("Vadfl!") # Cf !ou were to "import" "oth of the pac2aes with businb* there would "e a conflict. # That can "e prevented "! usin bimportb* as follows0 import Iinston import Vadfl! Iinston.plot(rand($)) Vadfl!.plot(.+Z303/[* !+rand(3/)) $lotting 2lotting in Julia is only possible with additional 2ackages. ,xamples of di7erent packages are given below. e&t$lots Text2lots 2ackge 2age. Text2lots is an extemely simple plotting library which generates terminal plots using Braille characters. /t is well documented and re9uires no other packages or external libraries; making it the simplest plotting option for Julia. usin Te.tNlots plot(. -7 cos(.)* -303) #7 cos(.) #7 3 <============================================================> #7 ?A=BCDDDDDDEB=AF #7 ?GBDDBHF #7 ?IJDDKLF #7 ?IJMNKLF #7 ?IJMNKLF #7 ?GOPHF #7 ?IQRLF #7 ?SOPTF #7 ?UMNVF #7 ?GMRLF #7 ?WPLF #7 ?SMNTF #7 ?ICNVF #7 ?IPVF #7 ?IPVF #7 ?UVF #7 /.?$/&/ XBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBY #7 -3 3 plot(Z. -7 cos(.)* . -7 cos(. , pi)[* /0?) #7 cos(.)* cos(. , pi) #7 3 <============================================================> #7 ?DDDB=AIGJCDDDDDEB=LF #7 ?DKLGBMNE=LF #7 ?NKTGCNKLF #7 ?NKLGCNKLF #7 ?NKIQPHF #7 ?EHUMRLIF #7 ?KLSCNVGMF #7 ?PHJMEAQF #7 ?SCKLGDVF #7 ?JMPHIQELF #7 ?GCRLUMNF #7 ?IJNVSCF #7 ?IJMEHIJMF #7 ?IJOEHIJMF #7 ?AJME=LIGBMF #7 ?AAA=BDNEKHAAAAAG=BMF #7 -3 XBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBY #7 / ? plot(Z3* &* ?* 9[* Z3&* 33* 8* 9[) #7 scatter plot #7 3& <============================================================> #7 ?MF #7 ?F #7 ?F #7 ?F #7 ?IF #7 ?F #7 ?F #7 ?F #7 ?F #7 ?LF #7 ?F #7 ?F #7 ?F #7 ?F #7 ?LF #7 ?F #7 9 XBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBY #7 3 9 $y$lot 2y2lot 2ackage 2age. 2y2lot needs 2ython and matplotlib installed matplotlib.pyplot docs. # N!Nlot0 needs N!thon and matplotli" installed # matplotli".p!plot docs import N!Nlot # plot ? random num"ers in Z/*3[* N!Nlot.plot creates a new fiure N!Nlot.plot(rand(?)) # la"elin the a.es* creatin a title0 N!Nlot..la"el(".-a.is") N!Nlot.!la"el("!-a.is") N!Nlot.title("Gandom") # creatin the leend0 l + Z"random data"[ # leend ta2es an arra! of strins* "ut since strins can "e inde.ed to et # chars (e.. lZ3[ ++ >r>) the "rac2ets are necessar! N!Nlot.leend(l) # create a new fiure0 f + N!Nlot.fiure(-) # eneratin data0 !3 + randn(3/) !- + randn(3/) . + 303/ # N!Nlot can handle ranes as well as arra!s # setup a rid for plottin0 N!Nlot.su"plot-rid((&* 3)* (/* /)* rowspan+-) # options for plottin are passed as 2e!word-aruments0 N!Nlot.plot(.* !3* c+"red"* mar2er+"."* linest!le+"Jone") # a second plot will plot in an e.istin fiure%su"plot N!Nlot.plot(.* !-) # add te.t to the plot0 N!Nlot.te.t(.Z$[,.3* !3Z$[* "value #$"* verticalalinment+"center") # N!Nlot will adjust the a.es automaticall!* "ut .lim and !lim can e.plicitl! # chane the smallest and larest value displa!ed on either a.is N!Nlot..lim(Z/* 33[) N!Nlot.leend(Z"dots"* "line"[* loc+"upper left") # chane into the other su"plot0 N!Nlot.su"plot-rid((&* 3)* (-* /)* rowspan+-) # plot some more data into the lower su"plot N!Nlot.plot(.* !3-!-) N!Nlot..lim(Z/* 33[) N!Nlot.!lim(Z-&* &[) # chane the tic2s used on the !-a.is N!Nlot.!tic2s(Z-&* /* &[) # save the current fiure N!Nlot.savefi("p!plot.pn") Winston %inston 2ackage 2age *atlab-like plotting. /nstalled via N2.add("Iinston") usin Iinston # optionall! call fiure prior to plottin to set the si:e fiure(width+1//* heiht+$//) # plot some data pl + plot(cumsum(rand(?//) .- /.?)* "r"* cumsum(rand(?//) .- /.?)* """) # displa! the plot (not done automaticall!^) displa!(pl) # "! default displa! will not wait and the plot will vanish as soon as it appears # usin readline is a "lunt wait to allow the user to choose when to continue println("Nress enter to continue0 ") readline(OTUCJ) # save the current fiure savefi("winston.sv") # .eps* .pdf* c .pn are also supported # we used sv here "ecause it respects the width and heiht specified a"ove # THUH0 needs more e.pansive e.planation 'adfly 3ad4y 2ackage 2age ggplotZ-like plotting. /nstalled via N2.add("Vadfl!") usin Vadfl! # plot some data pl + 4plot(cos(.)%.* ?* -?) # and save it to a file draw(NJV("adfl!.pn"* &//* 3//)* pl) # THUH0 needs more e.pansive e.planation DataFrames The -ata'rames.[l package provides tool for working with tabular data. The iris.csv 6le used in this example is available from github. usin UataFrames showln(.) + (show(.)\ println()) # THUH0 needs more lin2s to docs. # R UataFrame is an in-memor! data"ase df + UataFrame(R + Z3* -[* F + Ze* pi[* D + Z".."* ".!"[) showln(df) #7 -.& UataFrame #7 d-------d---d---------d------d #7 d Gow # d R d F d D d #7 d 3 d 3 d -.938-8 d ".." d #7 d - d - d &.3$3?8 d ".!" d # The columns of a UataFrame can "e inde.ed usin num"ers or names showln(dfZ3[) #7 Z3*-[ showln(dfZ0R[) #7 Z3*-[ showln(dfZ-[) #7 Z-.938-838-8$?8/$?*&.3$3?8-1?&?8898&[ showln(dfZ0F[) #7 Z-.938-838-8$?8/$?*&.3$3?8-1?&?8898&[ showln(dfZ&[) #7 RODCCOtrinZ".."*".!"[ showln(dfZ0D[) #7 RODCCOtrinZ".."*".!"[ # The rows of a UataFrame can "e inde.ed onl! "! usin num"ers showln(dfZ3* 0[) #7 3.& UataFrame #7 d-------d---d---------d------d #7 d Gow # d R d F d D d #7 d 3 d 3 d -.938-8 d ".." d showln(dfZ30-* 0[) #7 -.& UataFrame #7 d-------d---d---------d------d #7 d Gow # d R d F d D d #7 d 3 d 3 d -.938-8 d ".." d #7 d - d - d &.3$3?8 d ".!" d # UataFrames can "e loaded from DOP files usin readta"le() iris + readta"le("iris.csv") # Dhec2 the names and element t!pes of the columns of our new UataFrame showln(names(iris)) #7 Z0OepalQenth*0OepalIidth*0NetalQenth*0NetalIidth*0Opecies[ showln(elt!pes(iris)) #7 T!peZFloat1$*Float1$*Float1$*Float1$*UTF8Otrin[ # Ou"set the UataFrame to onl! include rows for one species showln(irisZirisZ0Opecies[ .++ "setosa"* 0[) #7 ?/.? UataFrame #7 d-------d-------------d------------d-------------d------------d----------d #7 d Gow # d OepalQenth d OepalIidth d NetalQenth d NetalIidth d Opecies d #7 d 3 d ?.3 d &.? d 3.$ d /.- d "setosa" d #7 d - d $.8 d &./ d 3.$ d /.- d "setosa" d #7 d & d $.9 d &.- d 3.& d /.- d "setosa" d #7 d $ d $.1 d &.3 d 3.? d /.- d "setosa" d #7 d ? d ?./ d &.1 d 3.$ d /.- d "setosa" d #7 d 1 d ?.$ d &.8 d 3.9 d /.$ d "setosa" d #7 d 9 d $.1 d &.$ d 3.$ d /.& d "setosa" d #7 d 8 d ?./ d &.$ d 3.? d /.- d "setosa" d #7 d 8 d $.$ d -.8 d 3.$ d /.- d "setosa" d #7 \ #7 d $3 d ?./ d &.? d 3.& d /.& d "setosa" d #7 d $- d $.? d -.& d 3.& d /.& d "setosa" d #7 d $& d $.$ d &.- d 3.& d /.- d "setosa" d #7 d $$ d ?./ d &.? d 3.1 d /.1 d "setosa" d #7 d $? d ?.3 d &.8 d 3.8 d /.$ d "setosa" d #7 d $1 d $.8 d &./ d 3.$ d /.& d "setosa" d #7 d $9 d ?.3 d &.8 d 3.1 d /.- d "setosa" d #7 d $8 d $.1 d &.- d 3.$ d /.- d "setosa" d #7 d $8 d ?.& d &.9 d 3.? d /.- d "setosa" d #7 d ?/ d ?./ d &.& d 3.$ d /.- d "setosa" d # Dount the num"er of rows for each species showln("!(iris* 0Opecies* df -7 si:e(df* 3))) #7 &.- UataFrame #7 d-------d--------------d----d #7 d Gow # d Opecies d .3 d #7 d 3 d "setosa" d ?/ d #7 d - d "versicolor" d ?/ d #7 d & d "virinica" d ?/ d # Uiscreti:e entire columns at a time irisZ0OepalQenth[ + iround(irisZ0OepalQenth[) irisZ0OepalIidth[ + iround(irisZ0OepalIidth[) # Ta"ulate data accordin to discreti:ed columns to see "clusters" ta"ulated + "!( iris* Z0Opecies* 0OepalQenth* 0OepalIidth[* df -7 si:e(df* 3) ) showln(ta"ulated) #7 39.$ UataFrame #7 d-------d--------------d-------------d------------d----d #7 d Gow # d Opecies d OepalQenth d OepalIidth d .3 d #7 d 3 d "setosa" d $ d & d $ d #7 d - d "setosa" d ? d - d 3 d #7 d & d "setosa" d ? d & d -& d #7 d $ d "setosa" d ? d $ d 39 d #7 d ? d "setosa" d 1 d $ d ? d #7 d 1 d "versicolor" d ? d - d & d #7 d 9 d "versicolor" d ? d & d & d #7 d 8 d "versicolor" d 1 d - d 1 d #7 d 8 d "versicolor" d 1 d & d -8 d #7 d 3/ d "versicolor" d 9 d & d 8 d #7 d 33 d "virinica" d ? d & d 3 d #7 d 3- d "virinica" d 1 d - d 3 d #7 d 3& d "virinica" d 1 d & d -- d #7 d 3$ d "virinica" d 9 d & d 38 d #7 d 3? d "virinica" d 9 d $ d 3 d #7 d 31 d "virinica" d 8 d & d $ d #7 d 39 d "virinica" d 8 d $ d - d Source Examples 9uine.[l bubblesort.[l enum.[l modint.[l 9ueens.[l preduce.[l time.[l ndgrid.[l lru]test.[l staged.[l plife.[l 9uaternion.[l wordcount.[l lru.[l typetree.[l hpl.[l Julia is a high-level, high-performance dynamic programming language for technical computing. This site is a non ofcial series of examples of Julia, for more details see about. (uine)*l This script prints a string identical to it:s own source code, see here. github.com^karbarcca^5osetta-Julia^blob^master^src^_uine.[l( /n Julia, ]. in a string literal interpolates the value of the variable into the string. ] (e.pression) evaluates the expression and interpolates the result into the string. `ormally, the string value "hi5tworld" would be inserted without 9uotation marks and with a literal tab The repr function returns a string value that contains 9uotation marks and in which the literal tab is replaced by the characters 5t. %hen the result of the repr function is interpolated, the result is what you would type into your code to create that string literal. .+"println(5".+5](repr(.))55n5].5")" println(".+](repr(.))5n].") +u++lesort)*l import Fase.Oort immuta"le Fu""leOortRl e0 Oort.Rlorithm end const Fu""leOort + Fu""leOortRl() function Fase.sort^(v00R"stractPector* lo00Cnt* hi00Cnt* 00Fu""leOortRl* o00Oort.Hrderin) while true clean + true for i + lo0hi-3 if Oort.lt(o* vZi,3[* vZi[) vZi,3[* vZi[ + vZi[* vZi,3[ clean + false end end clean cc "rea2 end return v end enum)*l &ome description here. macro enum(T*s!ms...) "l2 + )uote immuta"le ](esc(T)) n00Cnt&- ](esc(T))(n00Cnteer) + new(n) end Fase.show(io00CH* .00](esc(T))) + print(io* ]s!msZ..n,3[) Fase.show(io00CH* .00T!pe_](esc(T))`) + print(io* ](strin("enum "* T* > >* >(>* join(s!ms* "* ")* >)>))) end for (i*s!m) in enumerate(s!ms) push^("l2.ars* 0(const ](esc(s!m)) + ](esc(T))(](i-3)))) end push^("l2.ars* 0nothin) "l2.head + 0toplevel return "l2 end modint)*l module ModCnts importall Fase immuta"le ModCnt_n` e0 Cnteer 200Cnt ModCnt(2) + new(mod(2*n)) end -_n`(a00ModCnt_n`) + ModCnt_n`(-a.2) ,_n`(a00ModCnt_n`* "00ModCnt_n`) + ModCnt_n`(a.2,".2) -_n`(a00ModCnt_n`* "00ModCnt_n`) + ModCnt_n`(a.2-".2) '_n`(a00ModCnt_n`* "00ModCnt_n`) + ModCnt_n`(a.2'".2) convert_n`(00T!pe_ModCnt_n``* i00Cnt) + ModCnt_n`(i) promote_rule_n`(00T!pe_ModCnt_n``* 00T!pe_Cnt`) + ModCnt_n` show_n`(io00CH* 200ModCnt_n`) + print(io* "](2.2) mod ]n") showcompact(io00CH* 200ModCnt) + print(io* 2.2) end # module (ueens)*l ,xample of the a _ueens 2ubble. add)ueen()ueens00Rrra!_Pector_Cnt``* )ueen00Pector_Cnt`) + push^(cop!()ueens)* )ueen) hitsan!()ueen00Pector_Cnt`* )ueens00Rrra!_Pector_Cnt``) + an!(map(.-7hits()ueen* .)* )ueens)) hits(a00Rrra!_Cnt`* "00Rrra!_Cnt`) + an!(a .++ ") dd a"s(a-")Z3[ ++ a"s(a-")Z-[ function solve(.* !* n* d+Rrra!(Pector_Cnt`* /)) if n ++ / return d end for p. + 30. for p! + 30! if ^hitsan!(Zp.* p![* d) s + solve(.* !* n-3* add)ueen(d* Zp.* p![)) s ^+ nothin cc return s end end end return nothin end preduce)*l importall Fase # fiure ?.- from principles of parallel prorammin* ported to julia. # sum a vector usin a tree on top of local reductions. function sum(v00URrra!) N + procs(v) nodeval + _ GemoteGef(p) for p+N ` answer + GemoteGef() np + numel(N) for i+/0np-3 4spawnat NZi,3[ "ein stride+3 tall! + sum(localpart(v)) while stride e np if i6(-'stride) ++ / tall! + tall! , ta2e(nodevalZi,stride[) stride + -'stride else put(nodevalZi[* tall!) "rea2 end end if i++/ put(answer* tall!) end end end fetch(answer) end function reduce(f* v00URrra!) mapreduce(fetch* f* _ 4spawnat p reduce(f*localpart(v)) for p + procs(v) `) end # possi"l!-useful a"straction0 t!pe GefVroup refs00Rrra!_GemoteGef*3` GefVroup(N) + new(Z GemoteGef(p) for p+N [) end etinde.(r00GefVroup* i) + fetch(r.refsZi[) setinde.^(r00GefVroup* v* i) + put(r.refsZi[* v) time)*l module Time e.port TimeUelta import Fase.show* Fase.,* Fase.-* Fase.convert* Fase.promote_rule immuta"le TimeUelta_p` v00Cnt1$ end const NGAFCKAO + Z "!octo"* ":epto"* "atto"* "femto"* "pico"* "nano"* "micro"* "milli"* ""* "2ilo"* "mea"* "ia"* "tera"* "peta"* "e.a"* ":etta"* "!otta"* [ const SAGH_CJUAK + 8 const MRK_CJUAK + 39 function show_p`(io00CH* .00TimeUelta_p`) 2 + ma.(3*min(MRK_CJUAK*fld(p*&),SAGH_CJUAK)) r + p-&(2-SAGH_CJUAK) prefi. + NGAFCKAOZ2[ if r ++ / s + ..v ++ 3 a "" 0 "s" print(io* "](..v) ](prefi.)second]s") elseif r 7 / print(io* "](..v'3/(r) ](prefi.)seconds") else print(io* "](..v%3/(-r) ](prefi.)seconds") end end convert_p*)`(00T!pe_TimeUelta_p``* .00TimeUelta_)`) + TimeUelta_p`(p e+ ) a ..v'3/(()-p) 0 div(..v*3/((p-)))) promote_rule_p*)`(00T!pe_TimeUelta_p``* 00T!pe_TimeUelta_)``) + TimeUelta_min(p*))` -_p`(.00TimeUelta_p`) + TimeUelta_p`(-..v) ,_p`(.00TimeUelta_p`* !00TimeUelta_p`) + TimeUelta_p`(..v,!.v) -_p`(.00TimeUelta_p`* !00TimeUelta_p`) + TimeUelta_p`(..v-!.v) ,(.00TimeUelta* !00TimeUelta) + ,(promote(.*!)...) -(.00TimeUelta* !00TimeUelta) + -(promote(.*!)...) end # module ndgrid)*l ndrid(v00R"stractPector) + cop!(v) function ndrid_T`(v300R"stractPector_T`* v-00R"stractPector_T`) m* n + lenth(v3)* lenth(v-) v3 + reshape(v3* m* 3) v- + reshape(v-* 3* n) (repmat(v3* 3* n)* repmat(v-* m* 3)) end function ndrid_fill(a* v* s* sne.t) for j + 30lenth(a) aZj[ + vZdiv(rem(j-3* sne.t)* s),3[ end end function ndrid_T`(vs00R"stractPector_T`...) n + lenth(vs) s: + map(lenth* vs) out + ntuple(n* i-7Rrra!(T* s:)) s + 3 for i+30n a + outZi[00Rrra! v + vsZi[ sne.t + s'si:e(a*i) ndrid_fill(a* v* s* sne.t) s + sne.t end out end meshrid(v00R"stractPector) + meshrid(v* v) function meshrid_T`(v.00R"stractPector_T`* v!00R"stractPector_T`) m* n + lenth(v!)* lenth(v.) v. + reshape(v.* 3* n) v! + reshape(v!* m* 3) (repmat(v.* m* 3)* repmat(v!* 3* n)) end function meshrid_T`(v.00R"stractPector_T`* v!00R"stractPector_T`* v:00R"stractPector_T`) m* n* o + lenth(v!)* lenth(v.)* lenth(v:) v. + reshape(v.* 3* n* 3) v! + reshape(v!* m* 3* 3) v: + reshape(v:* 3* 3* o) om + ones(Cnt* m) on + ones(Cnt* n) oo + ones(Cnt* o) (v.Zom* 0* oo[* v!Z0* on* oo[* v:Zom* on* 0[) end lru,test)*l usin QGUA.ample TestQGU + QGUA.ample.Un"oundedQGU_RODCCOtrin* RODCCOtrin`() TestFQGU + QGUA.ample.FoundedQGU_RODCCOtrin* RODCCOtrin`(3///) et_str(i) + ascii(vcat(map(.-7Z.77$\ .c/./F[* reinterpret(Uint8* Zint&-(i)[))...)) is"ounded_Qe0QGUA.ample.QGU`(00T!pe_Q`) + an!(map(n-7n++0ma.si:e* Q.names)) is"ounded_Qe0QGUA.ample.QGU`(l00Q) + is"ounded(Q) nma. + int(lospace(-* ?* $)) function lrutest() #println("QGU consistenc! tests") for lru in (TestQGU*TestFQGU) for n in nma. empt!^(lru) #4printf(" 6s* 6d items5n"* lru* n) #print(" Oimple eviction0 ") for i in 30n str + et_str(i) lruZstr[ + str 4assert lru.)Z3[.v ++ str if is"ounded(lru) cc lenth(lru) 7+ lru.ma.si:e tailstr + et_str(i-lru.ma.si:e,3) 4assert lru.)Zend[.v ++ tailstr end end #println("pass") #print(" Qoo2up* random access0 ") for i in 30n str + et_str(rand(30n)) if has2e!(lru* str) # the "ounded QGUs can have cache misses "lah + lruZstr[ 4assert lru.)Z3[.v ++ "lah end end #println("pass") end empt!^(lru) end end lrutest() staged)*l function add_method(f* an* at* "od!) are.s + _ A.pr(s!m"ol("00")* anZi[* atZi[) for i+30lenth(an) ` def + )uote let __F__+(]f) function __F__(](are.s...)) ]"od! end end end eval(def) end macro staed(fdef) if ^isa(fdef*A.pr) dd ^is(fdef.head*0function) error("4staed0 e.pected method definition") end fname + fdef.arsZ3[.arsZ3[ arspec + fdef.arsZ3[.arsZ-0end[ arnames + map(.-7(isa(.*A.pr) a ..arsZ3[ 0 .)* arspec) )arnames + map(.-7A.pr(0)uote*.)* arnames) f"od! + fdef.arsZ-[ 4ens!m enf art!pes e.pander en"od! )uote let (]enf) lo"al (]fname) # should "e "outer" local (]e.pander) function (]e.pander)(](arnames...)) ]f"od! end (]enf)() + / # should "e initiall! empt! VF function (]fname)(](arspec...)) (]art!pes) + t!peof(tuple(](arnames...))) if ^method_e.ists(]enf* ]art!pes) (]en"od!) + appl!((]e.pander)* (]art!pes)) add_method(]enf* _]()arnames...)`* ]art!pes* ]en"od!) end return (]enf)(](arnames...)) end end end end # e.ample 4staed function nloops(dims00Tuple) names + map(.-7ens!m()* dims) e. + )uote println(Z](names...)[) end for i + 30lenth(dims) e. + )uote for ](namesZi[) in dimsZ]i[ ]e. end end end e. end plife)*l function life_rule(old) m* n + si:e(old) new + similar(old* m--* n--) for j + -0n-3 for i + -0m-3 nc + ,(oldZi-3*j-3[* oldZi-3*j[* oldZi-3*j,3[* oldZi *j-3[* oldZi *j,3[* oldZi,3*j-3[* oldZi,3*j[* oldZi,3*j,3[) newZi-3*j-3[ + (nc ++ & a 3 0 nc ++ - a oldZi*j[ 0 /) end end new end function life_step(d) URrra!(si:e(d)*procs(d)) do C # fetch neih"orhood - toroidal "oundaries top + mod(first(CZ3[)--*si:e(d*3)),3 "ot + mod( last(CZ3[) *si:e(d*3)),3 left + mod(first(CZ-[)--*si:e(d*-)),3 riht + mod( last(CZ-[) *si:e(d*-)),3 old + Rrra!(Fool* lenth(CZ3[),-* lenth(CZ-[),-) 4s!nc "ein 4as!nc oldZ3 * 3 [ + dZtop * left[ # left side 4as!nc oldZ-0end-3* 3 [ + dZCZ3[* left[ 4as!nc oldZend * 3 [ + dZ"ot * left[ 4as!nc oldZ3 * -0end-3[ + dZtop * CZ-[[ 4as!nc oldZ-0end-3* -0end-3[ + dZCZ3[* CZ-[[ # middle 4as!nc oldZend * -0end-3[ + dZ"ot * CZ-[[ 4as!nc oldZ3 * end [ + dZtop * riht[ # riht side 4as!nc oldZ-0end-3* end [ + dZCZ3[* riht[ 4as!nc oldZend * end [ + dZ"ot * riht[ end life_rule(old) end end function plife(m* n) w + Iindow("parallel life"* n* m) c + Danvas(w) pac2(c) done + false c.mouse."utton3press + (c*.*!)-7(done+true) cr + etc(c) rid + URrra!(C-7convert(Rrra!_Fool*-`*rand"ool(map(lenth*C)))* (m* n)* wor2ers()) last + time()\ f + 3 while ^done 4as!nc "ein im + convert(Rrra!_Uint&-*-`*rid) .' /.//ffffff set_source_surface(cr* DairoGVFOurface(im)* /* /) paint(cr) reveal(c) end t + time() if t-last 7 - println("](f%(t-last)) FNO") last + t\ f + / end rid + life_step(rid) f ,+ 3 sleep(/./3) end end (uaternion)*l module Buaternions import Fase0 convert* promote_rule* show* real* ima* conj* a"s* a"s-* inv* ,* -* %* ' immuta"le Buaternion_Te0Geal` e0 Jum"er )/00T )300T )-00T )&00T end Buaternion()/00Geal*)300Geal*)-00Geal*)&00Geal) + Buaternion(promote()/*)3*)-*)&)...) convert_T`(00T!pe_Buaternion_T``* .00Geal) + Buaternion(convert(T*.)* :ero(T)* :ero(T)* :ero(T)) convert_T`(00T!pe_Buaternion_T``* :00Domple.) + Buaternion(convert(T*real(:))* convert(T*ima(:))* :ero(T)* :ero(T)) convert_T`(00T!pe_Buaternion_T``* :00Buaternion) + Buaternion(convert(T*:.)/)* convert(T*:.)3)* convert(T*:.)-)* convert(T*:.)&)) promote_rule_s*O`(00T!pe_MathDonst_s``* 00T!pe_Buaternion_O``) + Buaternion_O` promote_rule_T*O`(00T!pe_Domple._T``* 00T!pe_Buaternion_O``) + Buaternion_promote_t!pe(T*O)` promote_rule_O`(00T!pe_Fool`* 00T!pe_Buaternion_O``) + Buaternion_O` promote_rule_Te0Geal*O`(00T!pe_T`* 00T!pe_Buaternion_O``) + Buaternion_promote_t!pe(T*O)` promote_rule_T*O`(00T!pe_Buaternion_T``* 00T!pe_Buaternion_O``) + Buaternion_promote_t!pe(T*O)` function show(io00CH* :00Buaternion) pm(.) + . e / a " - ](-.)" 0 " , ]." print(io* :.)/* pm(:.)3)* "i"* pm(:.)-)* "j"* pm(:.)&)* "2") end real(:00Buaternion) + :.)/ ima(:00Buaternion) + :.)3 conj(:00Buaternion) + Buaternion(:.)/* -:.)3* -:.)-* -:.)&) a"s(:00Buaternion) + s)rt(:.)/':.)/ , :.)3':.)3 , :.)-':.)- , :.)&':.)&) a"s-(:00Buaternion) + :.)/':.)/ , :.)3':.)3 , :.)-':.)- , :.)&':.)& inv(:00Buaternion) + conj(:)%a"s-(:) (-)(:00Buaternion) + Buaternion(-:.)/* -:.)3* -:.)-* -:.)&) (%)(:00Buaternion* .00Geal) + Buaternion(:.)/%.* :.)3%.* :.)-%.* :.)&%.) (,)(:00Buaternion* w00Buaternion) + Buaternion(:.)/ , w.)/* :.)3 , w.)3* :.)- , w.)-* :.)& , w.)&) (-)(:00Buaternion* w00Buaternion) + Buaternion(:.)/ - w.)/* :.)3 - w.)3* :.)- - w.)-* :.)& - w.)&) (')(:00Buaternion* w00Buaternion) + Buaternion(:.)/'w.)/ - :.)3'w.)3 - :.)-'w.)- - :.)&'w.)&* :.)/'w.)3 , :.)3'w.)/ , :.)-'w.)& - :.)&'w.)-* :.)/'w.)- - :.)3'w.)& , :.)-'w.)/ , :.)&'w.)3* :.)/'w.)& , :.)3'w.)- - :.)-'w.)3 , :.)&'w.)/) (%)(:00Buaternion* w00Buaternion) + :'inv(w) end # module -ordcount)*l # wordcount.jl # # Cmplementation of paralleli:ed "word-count" of a te.t* inspired "! the # @adoop IordDount e.ample. Uses 4spawn and fetch() to paralleli:e # the "map" tas2. Geduce is currentl! done sinle-threaded. # # To run in parallel on a strin stored in varia"le bte.tb0 # julia -p eJ7 # julia7 re)uire("ejulia_dir7%e.amples%wordcount.jl") # julia7 ...(define te.t)... # julia7 counts+parallel_wordcount(te.t) # # Hr to run on a roup of files* writin results to an output file0 # julia -p eJ7 # julia7 re)uire("ejulia_dir7%e.amples%wordcount.jl") # julia7 wordcount_files("%tmp%output.t.t"* "%tmp%input3.t.t"*"%tmp%input-.t.t"*...) # "Map" function. # Ta2es a strin. Geturns a Uict with the num"er of times each word # appears in that strin. function wordcount(te.t) words+split(te.t*Z> >*>5n>*>5t>*>->*>.>*>*>*>0>*>\>[*false) counts+Uict() for w + words countsZw[+et(counts*w*/),3 end return counts end # "Geduce" function. # Ta2es a collection of Uicts in the format returned "! wordcount() # Geturns a Uict in which words that appear in multiple inputs # have their totals added toether. function wcreduce(wcs) counts+Uict() for c in wcs* (2*v) in c countsZ2[ + et(counts*2*/),v end return counts end # Oplits input strin into nprocs() e)ual-si:ed chun2s (last one rounds up)* # and 4spawns wordcount() for each chun2 to run in parallel. Then fetch()s # results and performs wcreduce(). function parallel_wordcount(te.t) lines+split(te.t*>5n>*false) np+nprocs() unitsi:e+ceil(lenth(lines)%np) wcounts+_` rrefs+_` # spawn procs for i+30np first+unitsi:e'(i-3),3 last+unitsi:e'i if last7lenth(lines) last+lenth(lines) end su"te.t+join(linesZint(first)0int(last)[*"5n") push^(rrefs* 4spawn wordcount( su"te.t ) ) end # fetch results while lenth(rrefs)7/ push^(wcounts*fetch(pop^(rrefs))) end # reduce count+wcreduce(wcounts) return count end # Ta2es the name of a result file* and a list of input file names. # Dom"ines the contents of all files* then performs a parallel_wordcount # on the resultin strin. Irites the results to result_file. function wordcount_files(result_file*inputs...) te.t + "" for file in inputs open(file) do f te.t '+ readall(f) end end wc + parallel_wordcount(te.t) open(result_file*"w") do f for (2*v) in wc println(f* 2*"+"*v) end end end lru)*l module QGUA.ample # Rn QGU (Qeast Gecentl! Used) cache is an associative data structure which # maintains its contents in an order such that the most recentl! used item # is at the "einnin of the structure* and the least recentl! used at the end. # # This file specifies two t!pes of QGU caches* "oth with and without a si:e # limit. FoundedQGU has a limit and evicts the QGU item if a new item is added # after that "ound is reached. Un"oundedQGU does not have a ma.imum si:e* "ut # can "e used as a "asis for more comple. QGUs. # # QGUs should follow the interfaces for eneral collections* inde.a"le # collections* and associative collections. # The standard implementation of an QGU "ac2s a hash ta"le with a dou"l!-lin2ed # list for H(3) operations when reorderin on access and eviction. The Lulia # implementation instead "ac2s the ta"le with a Pector. For moderatel!-si:ed # collections* the difference in performance is small* and this implmentation # is simpler and easier to understand. import Fase.isempt!* Fase.lenth* Fase.si:eof import Fase.start* Fase.ne.t* Fase.done import Fase.has2e!* Fase.et import Fase.setinde.^* Fase.etinde.* Fase.delete^* Fase.empt!^ import Fase.show a"stract QGU_E*P` e0 Rssociative_E*P` # Uefault cache si:e const __MRKDRD@A + 3/-$ t!pe DacheCtem_E*P` 200E v00P end t!pe Un"oundedQGU_E*P` e0 QGU_E*P` ht00Uict )00Pector_DacheCtem` Un"oundedQGU() + new(Uict()* similar(Rrra!(DacheCtem*3)* /)) end Un"oundedQGU() + Un"oundedQGU_Rn!* Rn!`() t!pe FoundedQGU_E*P` e0 QGU_E*P` ht00Uict )00Pector_DacheCtem` ma.si:e00Cnt FoundedQGU(m) + new(Uict()* similar(Rrra!(DacheCtem*3)* /)* m) FoundedQGU() + FoundedQGU(__MRKDRD@A) end FoundedQGU(m) + FoundedQGU_Rn!* Rn!`(m) FoundedQGU() + FoundedQGU_Rn!* Rn!`() ## collections ## isempt!(lru00QGU) + isempt!(lru.)) lenth(lru00QGU) + lenth(lru.)) has2e!(lru00QGU* 2e!) + has2e!(lru.ht* 2e!) ## associative ## # Ohould this chec2 count as an accessa has2e!(lru00QGU* 2e!) + has2e!(lru.ht* 2e!) et(lru00QGU* 2e!* default) + has2e!(lru* 2e!) a lruZ2e![ 0 default function empt!^(lru00QGU) empt!^(lru.ht) empt!^(lru.)) end show(io00CH* lru00Un"oundedQGU) + print(io*"Un"oundedQGU()") show(io00CH* lru00FoundedQGU) + print(io*"FoundedQGU(](lru.ma.si:e))") ## inde.a"le ## # Method to do the second* slow loo2up in the list with earl! return. function locate()* .) for i + 30lenth()) if )Zi[ ++ . return i end end error("Ctem not found.") end function etinde.(lru00QGU* 2e!) item + lru.htZ2e![ id. + locate(lru.)* item) splice^(lru.)* id.) unshift^(lru.)* item) item.v end function setinde.^(lru00QGU* v* 2e!) if has2e!(lru* 2e!) item + lru.htZ2e![ id. + locate(lru.)* item) item.v + v splice^(lru.)* id.) else item + DacheCtem(2e!* v) lru.htZ2e![ + item end unshift^(lru.)* item) end # Aviction function setinde.^_P*E`(lru00FoundedQGU* v00P* 2e!00E) invo2e(setinde.^* (QGU* P* E)* lru* v* 2e!) nrm + lenth(lru) - lru.ma.si:e for i in 30nrm rm + pop^(lru.)) delete^(lru.ht* rm.2) end end ## associative ## function delete^(lru00QGU* 2e!) item + lru.htZ2e![ id. + locate(lru.)* item) delete^(lru.ht* 2e!) delete^(lru.)* id.) end end # module typetree)*l module T!peTrees ## # Venerate a te.t raphic of Lulia modules t!pe tree ## # The node t!pe holds the t!pe of the cuurent node and a dict of su"t!pes t!pe TTJode strname00Otrin t!p00T!pe su"t!pes00Uict_Otrin* TTJode` TTJode(sname00Otrin* t00T!pe) + new(sname* t* Uict_Otrin* TTJode`()) end # Rdd a node to a dict if not added function add_ttnode(su"t!pes00Uict_Otrin* TTJode`* sname00Otrin* tnode00TTJode) ret + et(su"t!pes* sname* nothin) (nothin ++ ret) cc (ret + su"t!pesZsname[ + tnode) ret end function add_ttnode(su"t!pes00Uict_Otrin* TTJode`* sname00Otrin* t00T!pe) ret + et(su"t!pes* sname* nothin) (nothin ++ ret) cc (su"t!pesZsname[ + ret + TTJode(sname* t)) ret end # Vet a strin name for the t!pe t!p_name(t00UnionT!pe) + strin(t) t!p_name(t00T!peDonstructor) + strin(t) t!p_name(t) + strin(t.name) # Otore a t!pe and its t!pe hierarch! chain # Gecurse till we reach the top level t!pe function store_t!pe(sname00Otrin* t00UnionT!pe) supt!pe + UnionT!pe tnode + TTJode(sname* t) # store unions under UnionT!pe t!pe su"t!pes + store_t!pe(t!p_name(supt!pe)* supt!pe) add_ttnode(su"t!pes* sname* tnode) # unions are also in a sense related to the t!pes of their components for supt!pe + t.t!pes su"t!pes + store_t!pe(t!p_name(supt!pe)* supt!pe) add_ttnode(su"t!pes* sname* tnode) end return tnode.su"t!pes end function store_t!pe(sname00Otrin* t00T!peDonstructor) supt!pe + t."od! su"t!pes + store_t!pe(t!p_name(supt!pe)* supt!pe) tnode + add_ttnode(su"t!pes* sname* t) return tnode.su"t!pes end function store_t!pe(sname00Otrin* t00UataT!pe) supt!pe + super(t) su"t!pes + (supt!pe ^+ t) a store_t!pe(t!p_name(supt!pe)* supt!pe) 0 t!pes_tree tnode + add_ttnode(su"t!pes* sname* t) return tnode.su"t!pes end function store_t!pe(sname00Otrin* t00Tuple) tnode + add_ttnode(t!pes_tree* sname* t) return tnode.su"t!pes end function store_t!pe(sname00Otrin* t) supt!pe + super(t) su"t!pes + (supt!pe ^+ t) a store_t!pe(t!p_name(supt!pe)* supt!pe) 0 t!pes_tree tnode + add_ttnode(su"t!pes* sname* t) return tnode.su"t!pes end # e.amine all s!m"ols in module and store those that are t!pes function store_all_from(m00Module) for e.pr + names(m*true) tr! t + eval(m*e.pr) isa(t* T!pe) cc store_t!pe(strin(e.pr)* t) #catch e. # println("Arror addin "* strin(e.pr)* m* " ("* e.* ")") end end end t!pe_props(t!p) + "" t!pe_props(t!p00UataT!pe) + strin("ee"* t!p.a"stract a " a"stract" 0 " concrete"* t!p.muta"le a " muta"le" 0 " immuta"le"* t!p.pointerfree a " pointerfree" 0 ""* " si:e0"* t!p.si:e* " 77") function print_tree(su"t!pes00Uict_Otrin* TTJode`* pf.00Otrin+"") for n in sort^(Z2e!s(su"t!pes)...[) v + su"t!pesZn[ if(n ++ strin(v.t!p)) println(pf.* ",- "* n* " "* t!pe_props(v.t!p)) else println(pf.* ",- "* n* " + "* v.t!p* " "* t!pe_props(v.t!p)) end print_tree(v.su"t!pes* pf. ' ". ") end end # THUH0 optionall! ta2e module names in command line # THUH0 sort output # THUH0 option to list su"trees of t!pe tree* or other s!m"ol t!pes const t!pes_tree + Uict_Otrin* TTJode`() for m in (Fase* Dore* Main) store_all_from(m) end # print_tree(t!pes_tree) end # module .pl)*l ## Fased on "Multi-Threadin and Hne-Oided Dommunication in Narallel QU Factori:ation" ## http0%%citeseer..ist.psu.edu%viewdoc%summar!adoi+3/.3.3.3&8.$&13cran2+9 function hpl_se)(R00Matri.* "00Pector) "loc2si:e + ? n + si:e(R*3) R + ZR "[ F_rows + linspace(/* n* div(n*"loc2si:e),3) F_rowsZend[ + n F_cols + ZF_rows* Zn,3[[ nF + lenth(F_rows) depend + :eros(Fool* nF* nF) # Cn parallel* depend needs to "e a"le to hold futures ## Omall matri. case if nF e+ 3 . + RZ30n* 30n[ 5 RZ0*n,3[ return . end ## Rdd a host row of dependencies to "oostrap the computation for j+30nF\ dependZ3*j[ + true\ end for i+30(nF-3) ## Threads for panel factori:ations C + (F_rowsZi[,3)0F_rowsZi,3[ #(dependZi,3*i[* panel_p) + spawn(panel_factor_se)* C* dependZi*i[) (dependZi,3*i[* panel_p) + panel_factor_se)(R* C* dependZi*i[) ## Threads for trailin updates for j+(i,3)0nF L + (F_colsZj[,3)0F_colsZj,3[ #dependZi,3*j[ + spawn(trailin_update_se)* C* L* panel_p* dependZi,3*i[*dependZi*j[) dependZi,3*j[ + trailin_update_se)(R* C* L* panel_p* dependZi,3*i[*dependZi*j[) end end ## Dompletion of the last diaonal "loc2 sinals termination #wait(dependZnF* nF[) ## Oolve the trianular s!stem . + triu(RZ30n*30n[) 5 RZ0*n,3[ return . end ## hpl() ### Nanel factori:ation ### function panel_factor_se)(R* C* col_dep) n + si:e (R* 3) ## Anforce dependencies #wait(col_dep) ## Factori:e a panel E + CZ3[0n panel_p + lufact^(su"(R* E* C))Z0p[ # Aconom! mode ## Nanel permutation panel_p + EZpanel_p[ return (true* panel_p) end ## panel_factor_se)() ### Trailin update ### function trailin_update_se)(R* C* L* panel_p* row_dep* col_dep) n + si:e (R* 3) ## Anforce dependencies #wait(row_dep* col_dep) ## Rppl! permutation from pivotin E + (CZend[,3)0n RZCZ3[0n* L[ + RZpanel_p* L[ ## Dompute "loc2s of U Q + tril(RZC*C[*-3) , e!e(lenth(C)) RZC* L[ + Q 5 RZC* L[ ## Trailin su"matri. update if ^isempt!(E) RZE*L[ + RZE*L[ - RZE*C['RZC*L[ end return true end ## trailin_update_se)() # This version is written for a shared memor! implementation. # The matri. R is local to the first Ior2er* which allocates wor2 to other Ior2ers # Rll updates to R are carried out "! the first Ior2er. Thus R is not distri"uted hpl_par(R00Matri.* "00Pector) + hpl_par(R* "* ma.(3* div(ma.(si:e(R))*$))* true) hpl_par(R00Matri.* "00Pector* "si:e00Cnteer) + hpl_par(R* "* "si:e* true) function hpl_par(R00Matri.* "00Pector* "loc2si:e00Cnteer* run_parallel00Fool) n + si:e(R*3) R + ZR "[ if "loc2si:e e 3 throw(RrumentArror("hpl_par0 invalid "loc2si:e0 ]"loc2si:e e 3")) end F_rows + linspace(/* n* div(n*"loc2si:e),3) F_rowsZend[ + n F_cols + ZF_rows* Zn,3[[ nF + lenth(F_rows) depend + cell(nF* nF) ## Omall matri. case if nF e+ 3 . + RZ30n* 30n[ 5 RZ0*n,3[ return . end ## Rdd a host row of dependencies to "oostrap the computation for j+30nF\ dependZ3*j[ + true\ end for i+-0nF* j+30nF\ dependZi*j[ + false\ end for i+30(nF-3) #println("R+]R") ##### ## Threads for panel factori:ations C + (F_rowsZi[,3)0F_rowsZi,3[ E + CZ3[0n (R_EC* panel_p) + panel_factor_par(RZE*C[* dependZi*i[) ## Irite the factori:ed panel "ac2 to R RZE*C[ + R_EC ## Nanel permutation panel_p + EZpanel_p[ dependZi,3*i[ + true ## Rppl! permutation from pivotin L + (F_colsZi,3[,3)0F_colsZnF,3[ RZE* L[ + RZpanel_p* L[ ## Threads for trailin updates #Q_CC + tril(RZC*C[* -3) , e!e(lenth(C)) Q_CC + tril(su"(R*C*C)* -3) , e!e(lenth(C)) E + (CZlenth(C)[,3)0n R_EC + RZE*C[ for j+(i,3)0nF L + (F_colsZj[,3)0F_colsZj,3[ ## Uo the trailin update (Dompute U* and UVAMM - all flops are here) if run_parallel R_CL + RZC*L[ #R_EC + RZE*C[ R_EL + RZE*L[ dependZi,3*j[ + 4spawn trailin_update_par(Q_CC* R_CL* R_EC* R_EL* dependZi,3*i[* dependZi*j[) else dependZi,3*j[ + trailin_update_par(Q_CC* RZC*L[* RZE*C[* RZE*L[* dependZi,3*i[* dependZi*j[) end end # Iait for all trailin updates to complete* and write "ac2 to R for j+(i,3)0nF L + (F_colsZj[,3)0F_colsZj,3[ if run_parallel (R_CL* R_EL) + fetch(dependZi,3*j[) else (R_CL* R_EL) + dependZi,3*j[ end RZC*L[ + R_CL RZE*L[ + R_EL dependZi,3*j[ + true end end ## Dompletion of the last diaonal "loc2 sinals termination 4assert dependZnF* nF[ ## Oolve the trianular s!stem . + triu(RZ30n*30n[) 5 RZ0*n,3[ return . end ## hpl() ### Nanel factori:ation ### function panel_factor_par(R_EC* col_dep) 4assert col_dep ## Factori:e a panel panel_p + lufact^(R_EC)Z0p[ # Aconom! mode return (R_EC* panel_p) end ## panel_factor_par() ### Trailin update ### function trailin_update_par(Q_CC* R_CL* R_EC* R_EL* row_dep* col_dep) 4assert row_dep 4assert col_dep ## Dompute "loc2s of U R_CL + Q_CC 5 R_CL ## Trailin su"matri. update - Rll flops are here if ^isempt!(R_EL) m* 2 + si:e(R_EC) n + si:e(R_CL*-) "las_emm(>J>*>J>*m*n*2*-3./*R_EC*m*R_CL*2*3./*R_EL*m) #R_EL + R_EL - R_EC'R_CL end return (R_CL* R_EL) end ## trailin_update_par() ### usin URrra!s ### function hpl_par-(R00Matri.* "00Pector) n + si:e(R*3) R + ZR "[ D + distri"ute(R* -) nF + lenth(D.pmap) ## case if onl! one processor if nF e+ 3 . + RZ30n* 30n[ 5 RZ0*n,3[ return . end depend + Rrra!(GemoteGef* nF* nF) #pmapZi[ is where "loc2 i>s stuff is #"loc2 i is distZi[ to distZi,3[-3 for i + 30nF #println("D+](convert(Rrra!* D))") ##### ##panel factori:ation panel_p + remotecall_fetch(D.pmapZi[* panel_factor_par-* D* i* n) ## Rppl! permutation from pivotin for j + (i,3)0nF dependZi*j[ + remotecall(D.pmapZj[* permute* D* i* j* panel_p* n* false) end ## Opecial case for last column if i ++ nF dependZnF*nF[ + remotecall(D.pmapZnF[* permute* D* i* nF,3* panel_p* n* true) end ##Trailin updates (i ++ nF) a (C + (D.distZi[)0n) 0 (C + (D.distZi[)0(D.distZi,3[-3)) D_CC + DZC*C[ Q_CC + tril(D_CC* -3) , e!e(lenth(C)) E + (CZlenth(C)[,3)0n if lenth(E) 7 / D_EC + DZE*C[ else D_EC + :eros(/) end for j+(i,3)0nF dep + dependZi*j[ dependZj*i[ + remotecall(D.pmapZj[* trailin_update_par-* D* Q_CC* D_EC* i* j* n* false* dep) end ## Opecial case for last column if i ++ nF dep + dependZnF*nF[ remotecall_fetch(D.pmapZnF[* trailin_update_par-* D* Q_CC* D_EC* i* nF,3* n* true* dep) else #enforce dependencies for nonspecial case for j+(i,3)0nF wait(dependZj*i[) end end end R + convert(Rrra!* D) . + triu(RZ30n*30n[) 5 RZ0*n,3[ end ## hpl_par-() function panel_factor_par-(D* i* n) (D.distZi,3[ ++ n,-) a (C + (D.distZi[)0n) 0 (C + (D.distZi[)0(D.distZi,3[-3)) E + CZ3[0n D_EC + DZE*C[ #(D_EC* panel_p) + lu^(D_EC) #econom! mode panel_p + lu^(D_EC)Z-[ DZE*C[ + D_EC return panel_p end ##panel_factor_par-() function permute(D* i* j* panel_p* n* fla) if fla E + (D.distZi[)0n L + (n,3)0(n,3) D_EL + DZE*L[ D_EL + D_ELZpanel_p*0[ DZE*L[ + D_EL else E + (D.distZi[)0n L + (D.distZj[)0(D.distZj,3[-3) D_EL + DZE*L[ D_EL + D_ELZpanel_p*0[ DZE*L[ + D_EL end end ##permute() function trailin_update_par-(D* Q_CC* D_EC* i* j* n* fla* dep) if isa(dep* GemoteGef)\ wait(dep)\ end if fla #(D.distZi,3[ ++ n,-) a (C + (D.distZi[)0n) 0 # (C + (D.distZi[)0(D.distZi,3[-3)) C + D.distZi[0n L + (n,3)0(n,3) E + (CZlenth(C)[,3)0n D_CL + DZC*L[ if lenth(E) 7 / D_EL + DZE*L[ else D_EL + :eros(/) end ## Dompute "loc2s of U D_CL + Q_CC 5 D_CL DZC*L[ + D_CL else #(D.distZi,3[ ++ n,-) a (C + (D.distZi[)0n) 0 # (C + (D.distZi[)0(D.distZi,3[-3)) C + (D.distZi[)0(D.distZi,3[-3) L + (D.distZj[)0(D.distZj,3[-3) E + (CZlenth(C)[,3)0n D_CL + DZC*L[ if lenth(E) 7 / D_EL + DZE*L[ else D_EL + :eros(/) end ## Dompute "loc2s of U D_CL + Q_CC 5 D_CL DZC*L[ + D_CL ## Trailin su"matri. update - Rll flops are here if ^isempt!(D_EL) cm* c2 + si:e(D_EC) cn + si:e(D_CL*-) "las_emm(>J>*>J>*cm*cn*c2*-3./*D_EC*cm*D_CL*c2*3./*D_EL*cm) #D_EL + D_EL - D_EC'D_CL DZE*L[ + D_EL end end end ## trailin_update_par-() ## Test n'n matri. on np processors ## Nrints ? num"ers that should "e close to :ero function test(n* np) R + rand(n*n)\ " + rand(n)\ K + (4elapsed . + R 5 ")\ T + (4elapsed ! + hpl_par(R*"* ma.(3*div(n*np))))\ S + (4elapsed : + hpl_par-(R*"))\ for i+30(min(?*n)) print(:Zi[-!Zi[* " ") end println() return (K*T*S) end ## test 2 times and collect averae function test(n*np*2) sum3 + /\ sum- + /\ sum& + /\ for i + 302 (K*T*S) + test(n*np) sum3 ,+ K sum- ,+ T sum& ,+ S end return (sum3%2* sum-%2* sum&%2) end