juliaref.txt 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121
  1. Julia Reference
  2. Julia Documentation - https://docs.julialang.org/en/v1/
  3. Julia by Examples - https://juliabyexample.helpmanual.io/
  4. The fast track to Julia - https://juliadocs.github.io/Julia-Cheat-Sheet/
  5. Julia Plots - https://docs.juliaplots.org/
  6. Julia Community (Standards) - https://julialang.org/community/standards/
  7. Julia Data Science - https://juliadatascience.io/
  8. Plotting with Makie - https://docs.makie.org/stable/
  9. Numerical Computing in Julia -
  10. https://www.matecdev.com/posts/julia-tutorial-science-engineering.html
  11. Julia interface to Gnuplot - https://gcalderone.github.io/Gnuplot.jl/
  12. Gaston Julia package for plotting - https://mbaz.github.io/Gaston.jl/stable/
  13. Introduction to Julia's Debugger -
  14. https://webpages.csus.edu/fitzgerald/julia-debugger-tutorial/
  15. Julia Mathematics - https://docs.julialang.org/en/v1/base/math/#Base.ceil
  16. A Deep Introduction to Julia for Data Science and Scientific Computing -
  17. http://ucidatascienceinitiative.github.io/IntroToJulia/
  18. Julia SOS - https://www.juliasos.com/
  19. Profile Julia code - https://opensourc.es/blog/constraint-solver-profiling/
  20. Parallel processing in Julia - https://berkeley-scf.github.io/tutorial-parallelization/parallel-julia
  21. # Julia-1.9.2 Current Stable version installation
  22. $ wget julia-1.9.2-linux-x86_64.tar.gz
  23. $ tar -xzvf julia-1.9.2-linux-x86_64.tar.gz
  24. $ mv julia-1.9.2/ ~/.julia/
  25. $ set path in ~/.bashrc [export PATH="$PATH:/home/saran/.julia/bin"]
  26. $ source .bashrc
  27. # upgrade julia-1.9.2 to julia-1.9.3 [https://julialang.org/downloads/]
  28. 1. download current stable release: v1.9.3 [Generic Linux on x86 - 64-bit (glibc)]
  29. $ wget https://julialang-s3.julialang.org/bin/linux/x64/1.9/julia-1.9.3-linux-x86_64.tar.gz
  30. 2. untar julia-1.9.3-linux-x86_64.tar.gz
  31. $ tar -xzvf julia-1.9.3-linux-x86_64.tar.gz
  32. 3. move julia-1.9.3/ to ~/.julia-1.9.3/
  33. $ mv downloads/julia-1.9.3/ .julia-1.9.3/
  34. 4. move directories compiled/ environments/ logs/ packages/ registries/ scratchspaces/
  35. $ mv ~/.julia-1.9.2/compiled/ ~/.julia-1.9.3/
  36. $ mv ~/.julia-1.9.2/environments/ ~/.julia-1.9.3/
  37. $ mv ~/.julia-1.9.2/logs/ ~/.julia-1.9.3/
  38. $ mv ~/.julia-1.9.2/packages/ ~/.julia-1.9.3/
  39. $ mv ~/.julia-1.9.2/registries/ ~/.julia-1.9.3/
  40. $ mv ~/.julia-1.9.2/scratchspaces/ ~/.julia-1.9.3/
  41. 5. remove ~/.julia-1.9.2
  42. $ rm -rf .julia/
  43. 6. rename ~/.julia-1.9.3 to ~/.julia/
  44. $ mv ~/.julia-1.9.3/ ~/.julia/
  45. 7. activate virtual environment, check status and update
  46. $ source .venv/dsci/bin/activate
  47. (@v1.9) pkg> status
  48. (@v1.9) pkg> update
  49. # install Julia
  50. Install the latest Julia version (v1.10.4 June 4, 2024) by running this in your
  51. terminal: curl -fsSL https://install.julialang.org | sh
  52. Once installed julia will be available via the command line interface.
  53. This will install the Juliaup installation manager, which will automatically install
  54. julia and help keep it up to date. The command juliaup is also installed. To install
  55. different julia versions see juliaup --help.
  56. # Types - https://docs.julialang.org/en/v1/manual/types/
  57. # Arrays - https://docs.julialang.org/en/v1/base/arrays/
  58. # Mathematical operations and Elementary functions -
  59. https://docs.julialang.org/en/v1/mathematical-operations/
  60. # concise tutorial - https://syli.gitbook.io/julia-language-a-concise-tutorial/
  61. # random num - www.juliabloggers.com/basics-of-generating-random-numbers-in-julia/
  62. $ julia
  63. > versioninfo()
  64. > using Pkg
  65. > Pkg.add("package_name")
  66. # update julia to latest stable version
  67. (@v1.8) pkg> add UpdateJulia
  68. julia> using UpdateJulia
  69. julia> update_julia()
  70. Ref: https://stackoverflow.com/questions/30555225/how-to-upgrade-julia-to-a-new-release
  71. # remove broken link if already present
  72. cd .local/bin/
  73. rm julia
  74. rm julia-1.8
  75. rm julia-1.8.2
  76. # create symbolic link
  77. ln -s /home/saran/.julia/bin/julia /home/saran/.local/bin/julia
  78. ln -s /home/saran/.julia/bin/julia /home/saran/.local/bin/julia-1.8
  79. ln -s /home/saran/.julia/bin/julia /home/saran/.local/bin/julia-1.8.2
  80. # in the Julia REPL, hit ] to enter package mode and then enter
  81. (@v1.8) pkg> help
  82. (@v1.8) pkg> status
  83. (@v1.8) pkg> status --outdated
  84. (@v1.8) pkg> update
  85. (@v1.8) pkg> add <package>
  86. (@v1.8) pkg> rm <package>
  87. # the julia internal variable Sys.WORD_SIZE indicates
  88. # whether the target system is 32-bit or 64-bit
  89. Sys.WORD_SIZE
  90. # to quit
  91. exit()
  92. # Source Installation
  93. sudo apt-get install libncurses-dev libncurses5-dev libtinfo-dev
  94. git clone git://github.com/JuliaLang/julia.git
  95. cd julia
  96. make
  97. ... go take a long nap ...
  98. git pull && make (to upgrade Julia)
  99. # virtual environment
  100. pkg> add VirtualEnv
  101. $ mkdir .venv
  102. $ venv -h # display help
  103. $ venv --prompt dsci .venv/dsci/ # creating virtual environment with prompt name (dsci)
  104. $ source .venv/dsci/bin/activate # activating virtual environment
  105. $ deactivate # deactivating environment
  106. note: if above method of creating virtual environment not work then
  107. pkg> add Comonicon
  108. pkg> add VirtualEnv
  109. $ mkdir .venv
  110. $ julia -e 'using VirtualEnv; venv("/home/user/.venv/dsci")'
  111. $ source .venv/dsci/bin/activate
  112. $ deactivate
  113. Reference: Documentataion - https://mehalter.github.io/VirtualEnv.jl/stable/
  114. # creating your own environments
  115. (@v1.8) pkg> activate fdtd
  116. Activating new environment at '~/fdtd/Project.toml'
  117. (fdtd) pkg> st
  118. Status '~/fdtd/Project.toml' (empty project)
  119. Note that the REPL prompt changes when the new project is activated. Until a
  120. package is added, there are no files in this environment and the directory to
  121. the environment might not even be created:
  122. julia> isdir("fdtd")
  123. false
  124. (fdtd) pkg> ad PyPlot
  125. julia> isdir("fdtd")
  126. true
  127. julia> readdir("fdtd")
  128. julia> print(read(joinpath("fdtd", "Project.toml"), String))
  129. julia> print(read(joinpath("fdtd", "Manifest.toml"), String))
  130. # using someone else's project
  131. Simply clone their project using e.g. git clone, cd to the project directory and
  132. call
  133. shell> git clone https://github.com/julialang/example.jl.git
  134. Cloning into 'example.jl'...
  135. ...
  136. (@v1.8) pkg> activate example.jl
  137. Activating project at '~/example.jl'
  138. (example) pkg> instantiate
  139. No Changes to '~/example.jl/Project.toml'
  140. No Changes to '~/example.jl/Manifest.toml'
  141. Reference: https://pkgdocs.julialang.org/v1/environments/
  142. # load a file into the julia console
  143. > include('program.jl')
  144. # time function
  145. @time function(x)
  146. # import benchmark library
  147. using BenchmarkTools
  148. # benchmark function
  149. @benchmark function(x)
  150. # benchmark function with time tolerance
  151. @benchmark function() seconds=1 time_tolerance=0.01
  152. @benchmark function(x) seconds=1 time_tolerance=0.01
  153. # print the minimum time and memory allocation
  154. @btime function(x)
  155. # print minimum time in seconds
  156. @belapsed function(x)
  157. # import profiling library
  158. using Profile
  159. # profile function
  160. @profile function(x)
  161. # print the results
  162. Profile.print()
  163. # clear the profile results
  164. Profile.clear()
  165. # numerical type hierarchy
  166. Number
  167. |
  168. |----- Complex
  169. |----- Real
  170. |----- AbstractFloat
  171. | |_____ BigFloat
  172. | |_____ Float16
  173. | |_____ Float32
  174. | |_____ Float64
  175. |
  176. |----- AbstractIrrational
  177. | |_____ Irrational
  178. |
  179. |----- Integer
  180. | |
  181. | |----- Bool
  182. | |
  183. | |----- Signed
  184. | | |_____ BigInt
  185. | | |_____ Int128
  186. | | |_____ Int16
  187. | | |_____ Int32
  188. | | |_____ Int64
  189. | | |_____ Int8
  190. | |
  191. | |_____ Unsigned
  192. | |_____ UInt128
  193. | |_____ UInt16
  194. | |_____ UInt32
  195. | |_____ UInt64
  196. | |_____ UInt8
  197. |
  198. |_____ Rational
  199. # arithmetic operators
  200. Expression Name Description
  201. +x unary plus the identity operation
  202. -x unary minus maps values to their additive inverses
  203. x + y binary plus performs addition
  204. x - y binary minus performs subtraction
  205. x * y times performs multiplication
  206. x / y divide performs division
  207. x \div y integer divide x / y, truncated to an integer
  208. x \ y inverse divide equivalent to y / x
  209. x ^ y power raises x to the yth power
  210. x % y remainder equivalent to rem(x, y)
  211. # boolean operators
  212. Expression Name
  213. !x negation
  214. x && y short-circuiting and
  215. x || y short-circuiting or
  216. # bitwise operators
  217. Expression Name
  218. ~x bitwise not
  219. x & y bitwise and
  220. x | y bitwise or
  221. xor(x, y) bitwise xor (exclusive or)
  222. nand(x, y) bitwise nand (not and)
  223. nor(x, y) bitwise nor (not or)
  224. x >>> y logical shift right
  225. x >> y arithmetic shift right
  226. x << y logical/arithmetic shift left
  227. # updating operators
  228. The updating versions of all the binary arithmetic and bitwise operators are:
  229. += -= *= /= \= \div= %= ^= &= |= >>>= >>= <<=
  230. # numeric comparisons
  231. Operator Name
  232. == equality
  233. != inequality
  234. < less than
  235. <= less than or equal to
  236. > greater than
  237. >= greater than or equal to
  238. Function Tests if
  239. isequal(x, y) x and y are identical
  240. isfinite(x) x is a finite number
  241. isinf(x) x is infinite
  242. isnan(x) x is not a number
  243. # rounding functions
  244. Function Description Return type
  245. round(x) round x to the nearest integer typeof(x)
  246. round(T, x) round x to the nearest integer T
  247. floor(x) round x towards -Inf typeof(x)
  248. floor(T, x) round x towards -Inf T
  249. ceil(x) round x towards +Inf typeof(x)
  250. ceil(T, x) round x towards +Inf T
  251. trunc(x) round x towards zero typeof(x)
  252. trunc(T, x) round x towards zero T
  253. # division functions
  254. Function Description
  255. div(x, y) truncated division; quotient rounded towards zero
  256. fld(x, y) floored division; quotient rounded towards -Inf
  257. cld(x, y) ceiling division; quotient rounded towards +Inf
  258. rem(x, y) remainder; satisfies x == div(x,y)*y + rem(x,y); sign matches x
  259. mod(x, y) modulus; satisfies x == fld(x,y)*y + mod(x,y); sign matches y
  260. mod1(x, y) mod with offset 1; returns x(0, y] for y>0 or x[y,0) for y<0
  261. mod2pi(x) modulus with respect to 2pi; 0 <= mod2pi(x) < 2pi
  262. divrem(x, y) returns (div(x, y), rem(x, y))
  263. fldmod(x, y) returns (fld(x, y), mod(x, y))
  264. gcd(x, y...) greatest positive common divisor of x, y, ...
  265. lcm(x, y...) least positive common multiple of x, y, ...
  266. # sign and absolute value functions
  267. Function Description
  268. abs(x) a positive value with the magnitude of x
  269. abs2(x) the squared magnitude of x
  270. sign(x) indicates the sign of x, returning -1, 0, or +1
  271. signbit(x) indicates whether the sign bit is on (true) or off(false)
  272. copysign(x, y) a value with the magnitude of x and the sign of y
  273. flipsign(x, y) a value with the magnitude of x and the sign of x*y
  274. # powers, logs and roots
  275. Function Description
  276. sqrt(x) square root of x
  277. cbrt(x) cube root of x
  278. hypot(x, y) hypotenuse of right-angled triangle with other sides of length x and y
  279. exp(x) natural exponential function at x
  280. expm1(x) accurate exp(x)-1 for x near zero
  281. ldexp(x, n) x*2^n computed efficiently for integer values of n
  282. log(x) natural logarithm of x
  283. log(b, x) base b logarithm of x
  284. log2(x) base 2 logarithm of x
  285. log10(x) base 10 logarithm of x
  286. log1p(x) accurate log(1+x) for x near zero
  287. exponent(x) binary exponent of x
  288. significand(x) binary significand (a.k.a. mantissa) of a floating-point number x
  289. # trigonometric and hyperbolic functions
  290. sin cos tan cot sec csc
  291. sinh cosh tanh coth sech csch
  292. asin acos atan acot asec acsc
  293. asinh acosh atanh acoth asech acsch
  294. sinc cosc
  295. sinpi(x) == sin(pi*x)
  296. cospi(x) == cos(pi*x)
  297. In order to compute trigonometric functions with degrees instead of radians, suffix
  298. the function with d. For example, sind(x) computes the sine of x where x is specified
  299. in degrees. The complete list of trigonometric functions with degree variants is:
  300. sind cosd tand cotd secd cscd
  301. asind acosd atand acotd asecd acscd
  302. Reference: https://docs.julialang.org/en/v1/manual/mathematical-operations/
  303. # conversion of Integer to Float
  304. Float64(2) # 2.0 (double-precision)
  305. Float32(2) # 2.0f0 (single-precision)
  306. Float16(2) # Float16(2.0) (half-precision)
  307. # conversion of Float to Integer (the float must coincide with an integer)
  308. Int64(2.0) # 2
  309. Int64(2.4) # Error!
  310. floor(Int64, 2.4) # 2
  311. ceil(Int64, 2.4) # 3
  312. round(Int64, 2.4) # 2
  313. # math constants
  314. \pi + Tab
  315. pi
  316. \euler + Tab
  317. MathConstants.e
  318. # Integer division
  319. By default, dividing two integers could return a float. If we are interested in
  320. the integer (or Euclidean) division, the div function (or \div, unicode symbol)
  321. returns the quotient, while for the remainder we have the rem function, or %.
  322. a = 1/2 # 0.5 (Float64)
  323. div(x, y) computes x/y, truncated to an integer
  324. div(10, 3) # 3
  325. \div(10, 3) # 3
  326. fld(x, y) computes x/y, truncated to an integer
  327. fld(10, 3) # 3
  328. Note: prefer fld() than div(), since div() not work for negative integer
  329. div(-3, 2) # -1 whereas the correct answer is -2
  330. fld(-3, 2) # -2
  331. rem(x, y) computes the remainder of x/y
  332. rem(10, 3) # 1
  333. 10%3 # 1
  334. # gotcha! Integer vs Float
  335. In Julia, if you input a number like
  336. a = 2
  337. you'll be getting an Int64 by default. This can lead to errors if we are not
  338. careful. For example, consider the following operation
  339. a = 1/2^64
  340. Inf
  341. Now, that's unexpected. Two things just happened. In the first place, an Int64
  342. will overflow past 2^{64}, and the default overflow value is 0.
  343. 2^64 # returns 0
  344. In the second place, in Julia 1 divided by 0 returns Inf. We just computed 1/0.
  345. We have some alternatives:
  346. 1/2.0^64 # 5.421010862427522e-20
  347. (1/2)^64 # 5.421010862427522e-20
  348. 1.0/2^64 # Inf
  349. # file system [Reference: https://docs.julialang.org/en/v1/base/file/]
  350. > pwd()
  351. "/home/user"
  352. > cd("/home/user/Directory")
  353. > pwd()
  354. "/home/user/Directory"
  355. > cd()
  356. > pwd()
  357. "/home/user"
  358. > cd(readdir, "/home/user/Directory")
  359. "file1.sh"
  360. "file2.jl"
  361. > pwd()
  362. "/home/user"
  363. # plots in Julia - https://juliaplots.github.io/
  364. # add package with specific version number
  365. (@v1.6) pkg> add FiniteDiff@1.2
  366. # display the type of a variable
  367. typeof(variable_name)
  368. # useful commands
  369. ctrl + D # exits Julia
  370. ctrl + C # interrupts computations
  371. ? # enters help mode
  372. ; # enters system shell mode
  373. ] # enters package manager mode
  374. ctrl + l # clears screen
  375. putting ; after the expression will disable showing its value in REPL # not needed in script
  376. # essential functions in the Julia REPL (they can be also invoked in scripts)
  377. @edit max(1,2) # show the definition of max function when invoked with arguments 1 and 2
  378. varinfo() # list of global variables and their types
  379. cd("/home/user") # change working directory to /home/user/
  380. pwd() # get current working directory
  381. include("file.jl") # execute source file
  382. exit(1) # exit Julia with code 1 (exit code 0 is used by default)
  383. clipboard([1,2]) # copy data to system clipboard
  384. clipboard() # load data from system clipboard as a string
  385. # configuring PyCall to use a different python version
  386. julia> ENV["PYTHON"]="/home/saran/.envn/dsci/bin/python"
  387. "/home/saran/.envn/dsci/bin/python"
  388. julia> using Pkg
  389. julia> Pkg.bulid("PyCall")
  390. Matplotlib uses matplotlibrc configuration files to customize all kinds of properties.
  391. To display where the currently active matplotlibrc file was loaded from, one can do the
  392. following:
  393. >>> import matplotlib
  394. >>> matplotlib.matplotlib_fname()
  395. '/home/user/.config/matplotlib/matplotlibrc'
  396. Ref: PyPlot.jl - https://juliapackages.com/p/pyplot
  397. # changing font style for latex rendering using PyPlot
  398. import PyPlot
  399. const plt = PyPlot
  400. plt.rc("font", family="serif", weight="normal", size=8)
  401. plt.rc("axes", labelsize=10)
  402. https://discourse.julialang.org/t/changing-font-style-for-latex-rendering-using-PyPlot/5910
  403. # numerical methods for linear algebra
  404. Ref: https://julia.quantecon.org/tools_andtechniques/iterative_methods_sparsity.html
  405. using LinearAlgebra
  406. create 2x3 matrix: A = [2 -4 8.2; -5.5 3.5 63]
  407. size of a matrix as a pair: A_rows, A_cols = size(A)
  408. size of rows of a matrix: A_rows = size(A)[1]
  409. size of columns of a matrix: A_cols = size(A)[2]
  410. condition number of a matrix A: cond(A)
  411. inverse of a matrix A: inv(A)
  412. trace of a matrix A: tr(A)
  413. determinant of a matrix A: det(A)
  414. identity matrix: I = eye(n)
  415. zeros of a matrix: A = zeros(m, n)
  416. ones of a matrix: A = ones(m, n)
  417. transpose of a matrix: A'
  418. +/- are used for matrix addition/subtraction
  419. (matrices must have the same size): [4.0 7; -10.6 89.8] + [19 -34.7; 20 1]
  420. matrix-scalar operations (+,-,*,\) apply elementwise
  421. scalar-matrix multiplication: 10 * [1 2; 3 4] = [1 2; 3 4] * 10
  422. scalar-matrix addition: [10 10; 10 10] + [1 2; 3 4] = [1 2; 3 4] + [10 10; 10 10]
  423. matrix-vector multiplication: [1 2; 3 4] * [5, 6]
  424. matrix-matrix multiplication: [2 4 3; 3 1 5] * [3 10; 4 2; 1 7]
  425. square matrix: A*A == A^2; A*A*A == A^3; A*A*A*A == A^4
  426. sum of entries of a matrix: sum(A)
  427. average of entries of a matrix: mean(A)
  428. # pretty print an array
  429. [Ref: https://stackoverflow.com/questions/62868864/julia-how-to-pretty-print-an-array]
  430. julia> A = zeros(4,4);
  431. julia> show(stdout, A)
  432. [0.0 0.0 0.0 0.0; 0.0 0.0 0.0 0.0; 0.0 0.0 0.0 0.0; 0.0 0.0 0.0 0.0]
  433. julia> show(stdout, "text/plain", A)
  434. 4x4 Array{Float64,2}:
  435. 0.0 0.0 0.0 0.0
  436. 0.0 0.0 0.0 0.0
  437. 0.0 0.0 0.0 0.0
  438. 0.0 0.0 0.0 0.0
  439. # dimensions of a matrix
  440. A = zeros(4,4)
  441. size(A)
  442. # matrix operations
  443. A = [1 2 3 4; 5 6 7 8; 9 10 11 12]
  444. typeof(A) # Matrix(Int64) (alias for Array{Int64, 2})
  445. # vector equality
  446. x = [-1.1, 0.0, 3.6, -7.2]
  447. y = copy(x)
  448. y[3] = 4.0
  449. y == x # false
  450. z = x
  451. z[3] = 4.0
  452. z == x # true
  453. # printf function in julia
  454. using Printf
  455. @printf("%d \t %d \t %f\n", time, freq, result)
  456. # format program in Julia
  457. Reference: https://domluna.github.io/JuliaFormatter.jl/dev/
  458. julia> using JuliaFormatter
  459. # recursively formats all Julia files in the current directory
  460. julia> format(".")
  461. # formats an individual file
  462. julia> format_file("program.jl")
  463. # formats a string (contents of a Julia file)
  464. julia> format_text(str)
  465. # inner product
  466. x = [1 2 3]
  467. y = [3 2 1]
  468. dot(vec(x), vec(y)) == sum(x.*y)
  469. # https://www.matecdev.com/posts/julia-numerical-integration.html
  470. # functions in Julia
  471. function f(x,y)
  472. x + y
  473. end
  474. The traditional function declaration syntax demonstrated above is equivalent to
  475. the following compact "assignment form":
  476. f(x,y) = x + y
  477. # version info
  478. julia> versioninfo()
  479. julia> using CUDA
  480. julia> CUDA.versioninfo()
  481. julia> CUDA.memory_status()
  482. julia> CUDA.reclaim()
  483. Ref: https://github.com/JuliaGPU/CUDA.jl/issues/866
  484. # to execute the program inside the julia prompt
  485. julia> include("/path/to/file.jl")
  486. # profiling
  487. https://cuda.juliagpu.org/stable/development/profiling/
  488. https://morioh.com/p/0340fd968665
  489. https://thirld.com/blog/2015/05/30/julia-profiling-cheat-sheet/
  490. https://danmackinlay.name/notebook/julia_debug.html
  491. # parallel programming with Julia using MPI
  492. http://www.claudiobellei.com/2018/09/30/julia-mpi/
  493. # ODE in Julia
  494. https://nextjournal.com/sosiris-de/ode-diffeq
  495. # iteration on each index
  496. N = [10, 20]
  497. for n in eachindex(N) for m in N
  498. println(n, m)
  499. end
  500. end
  501. Output:
  502. 110
  503. 120
  504. 210
  505. 220
  506. can be written as
  507. for n in eachindex(N), m in N
  508. println(n, m)
  509. end
  510. Output:
  511. 110
  512. 120
  513. 210
  514. 220
  515. # append in Julia
  516. str = "institute"
  517. strind = collect(eachindex(str))
  518. print(strind)
  519. [1,2,3,4,5,6,7,8,9]
  520. # enumerate in julia
  521. N = 10
  522. for (m, n) in enumerate(N)
  523. println(m, n)
  524. end
  525. # symbols
  526. julia> ex = :(a+b*c)
  527. The use of the colon (:) operator in front of (a + b*c) results in the
  528. expression being saved in ex rather than being evaluated. In fact, the
  529. expression would clearly fail unless all the variables had values. The
  530. colon (:) operator creates a symbolic representation, and this is stored
  531. in a data structure Expr and is saved in ex rather than being evaluated.
  532. julia> typeof(ex); # Expr
  533. julia> a = 1.0; b = 2.5; c = 23 + 4im;
  534. julia> eval(ex)
  535. 58.5 + 10.0im
  536. # vectorized and devectorized code
  537. # vectorized code
  538. function vecadd1(a,b,c,N)
  539. for i = 1:N
  540. c = a + b
  541. end
  542. end
  543. # devectorized code
  544. function vecadd2(a,b,c,N)
  545. for i = 1:N, j = 1:length(c)
  546. c[j] = a[j] + b[j]
  547. end
  548. end
  549. julia> A = rand(2); B = rand(2); C = zeros(2);
  550. julia> @elapsed vecadd1(A,B,C,10000000)
  551. @elapsed vecadd1(A,B,C,10000000) # 18.418755286
  552. julia> @elapsed vecadd2(A,B,C,10000000)
  553. @elapsed vecadd2(A,B,C,10000000) # 0.524002398
  554. The current situation in Julia is that devectorized code is much quicker than
  555. vectorized.
  556. # get input from the user
  557. print("Enter length of side: ")
  558. s = parse(Int64, readline())
  559. a = s*s
  560. println("\nArea of square is $a")
  561. # floating-point numbers
  562. print("Enter a number: ")
  563. num = parse(Float32, readline())
  564. dnum = parse(Float64, readline())
  565. # get text/string input from the user
  566. print("Enter institute name: ")
  567. name = readline()
  568. println("Institution name is $name")
  569. # escape sequences
  570. \n newline (line feed)
  571. \$ dollar sign
  572. \\ backslash
  573. \" double quote
  574. \' single quote
  575. \r carriage return
  576. \b backspace
  577. \t horizontal tab
  578. \f form feed (new page)
  579. # reserved words
  580. baremodule begin break catch const continue do else
  581. elseif end export false finally for function global
  582. if import let local macro module quote return
  583. struct true try using while
  584. # multi-threading: starting Julia with multiple threads
  585. By default, Julia starts up with a single thread of execution. This can be
  586. verified by using the command Threads.nthreads():
  587. julia> Threads.nthreads()
  588. 1
  589. The number of execution threads is controlled either by using the -t/--threads
  590. command line argument or by using the JULIA_NUM_THREADS environment variable.
  591. The number of threads can either be specified as an integer (--threads=4) or as
  592. auto (--threads=auto), where auto sets the number of threads to the number of
  593. local CPU threads.
  594. Lets start Julia with 4 threads:
  595. $ julia --threads 4
  596. Lets verify there are 4 threads at our disposal:
  597. julia> Threads.nthreads()
  598. 4
  599. But we are currently on the master thread. To check, we use the function
  600. julia> Threads.threadid()
  601. 1
  602. # list comprehension
  603. julia> L = ['a', 'b', 'c']
  604. julia> for n in L
  605. println(n)
  606. end
  607. julia> x = [n^2 for n in 1:10]
  608. julia> println(x)
  609. [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
  610. julia> [(x,y) for x in [1,2] for y in [3,1] if x != y]
  611. 3-element Vector{Tuple{Int32, Int32}}:
  612. (1, 3)
  613. (2, 3)
  614. (2, 1)
  615. julia> function is_even(a)
  616. return a%2 == 0
  617. end
  618. julia> is_even(3)
  619. false
  620. julia> is_even(4)
  621. true
  622. # generators
  623. julia> x = (n^3 for n in 1:10)
  624. julia> for n in x
  625. println(n)
  626. end
  627. # functional programming tools
  628. julia> items = [1,2,3,4,5]
  629. julia> function sqr(x)
  630. return x^2
  631. end
  632. julia> map(sqr, items)
  633. 5-element Vector{Int32}:
  634. 1
  635. 4
  636. 9
  637. 16
  638. 25
  639. julia> sum(items)
  640. 15
  641. julia> minimum(items)
  642. 1
  643. julia> maximum(items)
  644. 5
  645. julia> function f(x)
  646. return x%2 != 0 && x%3 != 0
  647. end
  648. julia> filter(f, 2:25)
  649. 8-element Vector{Int32}:
  650. 5
  651. 7
  652. 11
  653. 13
  654. 17
  655. 19
  656. 23
  657. 25
  658. # diagm in julia (Ref: Statistics with Julia, Page No: 434)
  659. # information of a package
  660. julia> using SpecialFunctions
  661. julia> ?
  662. help?> SpecialFunctions
  663. # functional
  664. julia> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  665. julia> typeof(a)
  666. Vector{Int32} (alias for Array{Int32, 1})
  667. julia> reduce(+, a) # 55
  668. julia> sum(a) # 55
  669. julia> reduce(*, a) # 3628800
  670. julia> prod(a) # 3628808
  671. julia> reduce(-, a) # -53
  672. julia> reduce(/, a) # 2.7557319223985894e-7
  673. # discard the fractional part
  674. julia> x = 7.3;
  675. julia> n = trunc(x)
  676. 7.0
  677. julia> typeof(n)
  678. Float64
  679. julia> n = trunc(Int32, x)
  680. 7
  681. julia> typeof(n)
  682. Int32
  683. # alternate function declaration
  684. function f(n)
  685. n == 0 && return "zero"
  686. n == 1 && return "ones"
  687. n == 2 && return "twos"
  688. return "nothing"
  689. end
  690. julia> f(0)
  691. "zero"
  692. julia> f(1)
  693. "ones"
  694. julia> f(2)
  695. "twos"
  696. julia> f(3)
  697. "nothing'
  698. julia> f(4)
  699. "nothing"
  700. # floating-point representation of 10.375
  701. bitstring(10.375)
  702. # roots and weights of Legendre polynomials
  703. Method 1:
  704. julia> import Polynomials, SpecialPolynomials
  705. julia> p = basis(Legendre, 3) # legendre polynomial (n = 3)
  706. Legendre(1.0 P_3 (x))
  707. julia> p = convert(Polynomial, p)
  708. Polynomial(-1.5*x + 2.5*x^3)
  709. julia> node_values = roots(p)
  710. 3-element Vector{Flo
  711. -0.7745966692414834
  712. 0.7745966692414834
  713. 0.0
  714. Method 2:
  715. using FastGaussQuadrature
  716. julia> Pn = gausslegendre(3)[1] # compute roots/nodes of legendre polynomial
  717. 3-element Vector{Float64}: # to compute nodes and weights:
  718. -0.7745966692414834 # x, w = gausslegendre(3)
  719. 0.0
  720. 0.7745966692414834
  721. # finding type
  722. Reference: https://discourse.julialang.org/t/annotating-types-best-practice-for-beginners/50521/4
  723. similar(x) - creates an uninitialized array with the same type and the same dimensions as x
  724. typeof(x) - returns the type of x, can be used as a constructor
  725. eltype(x) - returns the type of elements in x
  726. # constrain two arguments to be of the same type T
  727. value = add(x::T, y::T) where T = x + y
  728. Now, add(2, 3) returns 5 and add(2, 3.0) returns ERROR: MethodError: `add`
  729. has no method matching add(::Int64, ::Float64) error message.
  730. # package compilation (Precompiling project...)
  731. julia> import Pkg;
  732. julia> Pkg.precompile()
  733. # Gnuplot
  734. julia> using Gnuplot
  735. julia> gpexec("set term sixelgd size 480,360');
  736. julia> @gp hist(randn(1000))
  737. # Gaston and Gnuplot.jl: two philosophies
  738. Gnuplot.jl is another front-end for gnuplot, with comparable capabilities to
  739. Gaston. An example serves to illustrate the differences in how the two packages
  740. approach the interface problem.
  741. Gnuplot.jl:
  742. x = 1:0.1:10
  743. @gp "set grid" "set key left" "set logscale y"
  744. @gp :- "set title 'Plot title'" "set label 'X label'" "set xrange [0:*]"
  745. @gp :- x x.^0.5 "w l tit 'Pow 0.5' dt 2 lw 2 lc rgb 'red'"
  746. @gp :- x x "w l tit 'Pow 1' dt 1 lw 3 lc rgb 'blue'"
  747. @gp :- x x.^2 "w l tit 'Pow 2' dt 3 lw 2 lc rgb 'purple'"
  748. This shows that Gnuplot.jl essentially allows one to write gnuplot commands
  749. directly in Julia. The same plot in Gaston would be:
  750. x = 1:0.1:10
  751. plot(x, x.^0.5,
  752. w = "1",
  753. legend = "'Pow 0.5'",
  754. dt = 2,
  755. lw = 2,
  756. lc = :red,
  757. Axes(grid = :on,
  758. key = "left",
  759. axis = "semilogy"))
  760. plot!(x, x,
  761. w = :l,
  762. leg = :Pow_1,
  763. dt = 1,
  764. lw = 3,
  765. lc = :blue)
  766. plot!(x, x.^2,
  767. curveconf = "w l tit 'Pow 2' dt 3 lw 2 lc 'purple'")
  768. Gaston offers a function-based interface, and gnuplot commands can be specified
  769. in a few different ways, with convenient notation, such as the optional use of
  770. "legend" instead of gnuplot's "title", symbols to avoid typing quote martks(")
  771. all the time.
  772. # help prompt (type ? in julia>)
  773. help?> PyPlot.matplotlib
  774. help?> plt.matplotlib.use
  775. julia> plt.matplotlib.rcParams
  776. julia> Pyplot.matplotlib # location of matplotlib
  777. help?> plt.rc("classic")
  778. # using classic style
  779. import PyPlot
  780. const plt = PyPlot
  781. plt.matplotlib.style.use("classic")
  782. import PyPlot.matplotlib as plt
  783. plt.style.use("classic")
  784. # factorial
  785. julia> factorial(10)
  786. julia> factorial(big(10))
  787. julia> factorial(big(100))
  788. # access the last element of an list/array
  789. x = [1, 2, 3, 4]
  790. last(x) # 4
  791. x[begin] # 1
  792. x[end] # 4
  793. julia> N = 4
  794. julia> "$N$pi"
  795. julia> "$pi/2"
  796. x1 = LinRange(-pi, pi, 10000) # prefer
  797. x2 = range(-pi, pi, 10000)
  798. julia> @time 2*x1
  799. julia> @time 2*x2
  800. julia> @time x1+x1
  801. julia> @time x2+x2
  802. julia> @timev 2*x1
  803. julia> @timev 2*x2
  804. julia> @timev x1+x1
  805. julia> @timev x2+x2
  806. x = Array{Float64}(undef, 10) # is equalent to x = zeros(10)
  807. # hit Exc and X for delete notebook cell
  808. # hit Esc and A to create notebook cell above the current cell
  809. # hit Esc and L for line numbers
  810. # Help menu for keyboard shortcuts
  811. Math Teacher's code session 1: (Shift + Enter evaluates the notebook cell)
  812. > isEven(x) = x%2 == 0
  813. > next(x) = isEven(x) ? Int(x/2) : 3x+1
  814. # division always changes to Float64 even if input is Int64
  815. > x = 7
  816. > for _ in 1:20
  817. print(x, '')
  818. x = next(x)
  819. end
  820. > while x != 1
  821. print(x, '')
  822. x = next(x)
  823. end
  824. > function colletz(x)
  825. while x != 1
  826. print(x, '')
  827. x = next(x)
  828. end
  829. print(x)
  830. end
  831. > colletz(7)
  832. > colletz(32)
  833. > collectz(27)
  834. > myArray = [2, 4, 5, 62]
  835. > function colletz(x)
  836. val = [x]
  837. while x != 1
  838. x = next(x)
  839. push!(val, x)
  840. end
  841. return val
  842. end
  843. > using PyPlot
  844. > yval = colletz(27)
  845. > n = length(yval)
  846. > xval = 1:n
  847. > plot(xval, yval)
  848. > ? push! # get info of push! function
  849. # Base.Sys
  850. > using Base.Sys
  851. > names(Sys)
  852. > cpu_info()
  853. > cpu_summary()
  854. # concatenating arrays in Julia
  855. 1. Using the 'vcat' function
  856. The vcat function in Julia allows to vertically concatenate arrays. This means that the
  857. arrays will be stacked on top of each other to create a new array.
  858. > array1 = [1, 2, 3]
  859. > array2 = [4, 5, 6]
  860. > result = vcat(array1, array2)
  861. In this example, the 'vcat' function is used to concatenate 'array1' and 'array2' into
  862. a new array called 'result'. The resulting array will be '[1, 2, 3, 4, 5, 6]'.
  863. 2. Using the 'hcat' function
  864. The hcat function in Julia allows to horizontally concatenate arrays. This means that
  865. the arrays will be placed side by side to create a new array.
  866. > array1 = [1, 2, 3]
  867. > array2 = [4, 5, 6]
  868. > result = hcat(array1, array2)
  869. In this example, the 'hcat' function is used to concatenate 'array1' and 'array2' into
  870. a new array called 'result'. The resulting array will be '[1 4; 2 5; 3 6]'.
  871. 3. Using the 'append!' function
  872. The append! function in Julia allows to append one array to another. This modifies the
  873. original array in place.
  874. > array1 = [1, 2, 3]
  875. > array2 = [4, 5, 6]
  876. > append!(array1, array2)
  877. In this example, the 'append!' function is used to append 'array2' to 'array1'. After
  878. the operation, 'array1' will be '[1, 2, 3, 4, 5, 6]'.
  879. If need to create a new array, either vertically or horizontally, then using the 'vcat'
  880. or 'hcat' functions respectively would be the way to go. However, if you want to modify
  881. an existing array in place, then using the 'append!' function would be appropriate.
  882. # writing type-stable code
  883. Code is said to be type-stable if the type of every variable does not vary over time.
  884. To clarify this idea, consider the following two closely related function definitions.
  885. function summation1(n::Int)
  886. r = 0
  887. for i in 1:n
  888. r += sin(3.4)
  889. end
  890. return r
  891. end
  892. function summation2(n::Int)
  893. r = 0.0
  894. for i in 1:n
  895. r += sin(3.4)
  896. end
  897. return r
  898. end
  899. The difference between these function definitions is that summation1 initializes
  900. r to 0, whereas summation2 initializes r to 0.0
  901. julia> summation1(100_000)
  902. -25554.110202663698
  903. julia> summation2(100_000)
  904. -25554.110202663698
  905. juliaa> @time [summation1(100_000) for i in 1:1000];
  906. 0.131536 seconds (31.90 k allocations: 2.162 MiB, 27.03% compilation time)
  907. julia> @time [summation2(100_000) for i in 1:1000];
  908. 0.129389 seconds (28.65 k allocations: 1.941 MiB, 25.74% compilation time)
  909. We can confirm that the compiler produces more complex code by examining the LLVM IR
  910. for both of these functions.
  911. julia> code_llvm(summation1, (Int, ))
  912. julia> code_llvm(summation2, (Int, ))
  913. The difference in size and complexity of code between these two functions in compiled
  914. form is considerable. And this difference is entirely attributable to the compiler's
  915. need to recheck the type of r on every iteration of the main loop in summation1, which
  916. can be optimized out in summation2, where r has a stable type.
  917. Reference:
  918. https://www.johnmyleswhite.com/notebook/2013/12/06/writing-type-stable-code-in-julia/