SlideShare a Scribd company logo
Useful knowledge on Mathematica®
for Physicists
Miroslav Mihaylov
UIC Physics Feb-17-2016
The notebook inrerface and the
kernel
◼ The user enters input in the notebook
◼ The input is sent to the Math Kernel via Shift+Enter or Numpad Enter
◼ The kernel performs the computation ans send the result back to the frontend for display
Frontend
Integrate[Exp[-x^2],x]
π
2
Erf[x]
Math Kernel

◼ MathLink the protocol for comunication of the frontend with the Kernel and other
2 PresnetationSlides-Feb-Apr-2016.nb
Lists {a1, a2, ..., an}
◼ Generating lists with Table[]
Table expr ,  i , i min , i max ,
Table expr ,  i , i min , i max , di , Table expr ,  i ,  i 1 , i 2 , … 
Tablei, i, 10, 20, 2
{10, 12, 14, 16, 18, 20}
Tablei, 2×i, i, 10, 20, 2
{{10, 20}, {12, 24}, {14, 28}, {16, 32}, {18, 36}, {20, 40}}
Table10i+j, i, 4, j, 3
{{11, 12, 13}, {21, 22, 23}, {31, 32, 33}, {41, 42, 43}}
◼ Generating lists with Range[]
Range i max , Range i min , i max , Range i min , i max , di 
Range[5]
{1, 2, 3, 4, 5}
Range2, 5, 0.5
{2., 2.5, 3., 3.5, 4., 4.5, 5.}
◼ Table with Random
TableRandom [], 3
{0.929755, 0.0990263, 0.960832}
RandomInteger 10, 4, 3
{{5, 1, 9}, {4, 3, 10}, {6, 9, 3}, {6, 3, 2}}
PresnetationSlides-Feb-Apr-2016.nb 3
Lists Representations
◼ Usefull for easy inspection of the elemetns of the list
Table10i+j, i, 4, j, 3 // TableForm
11 12 13
21 22 23
31 32 33
41 42 43
0, -ⅈ, ⅈ, 0 // MatrixForm

0 -ⅈ
ⅈ 0

MatrixForm [{a1, a2}]

a1
a2

4 PresnetationSlides-Feb-Apr-2016.nb
Programing in Mathematica
Say we have the list bellow and we would like to reverse the elements of each item in the list
lis= {α, 1}, β, 2, γ, 3;
With procedural programing we would write
tempLis = lis;
Fori = 1, i ≤ Lengthlis, i++,

tempLis i, 1, tempLis i, 2 = lisi, 2, lisi, 1

;
tempLis
{{1, α}, {2, β}, {3, γ}}
Slightly better approach
Table lisi, 2, lisi, 1,
i, 1, Lengthlis

{{1, α}, {2, β}, {3, γ}}
PresnetationSlides-Feb-Apr-2016.nb 5
The Mathematica Way
For each element of the list we want to reverse
MapReverse, lis
{{1, α}, {2, β}, {3, γ}}
Same as above written in an alternative syntax
Reverse/@lis
{{1, α}, {2, β}, {3, γ}}
6 PresnetationSlides-Feb-Apr-2016.nb
Map[] /@ and Apply[] @@
◼ Map applies a function to each element in a list
Mapf, a, b, c
{f[a], f[b], f[c]}
◼ Apply changes the structure of the expression
Applyf, a, b, c
f[a, b, c]
ApplyPlus, a, b, c, d
a+b+c+d
ApplyPlus, a, b, c, {α, β, γ}
{a+α, b+β, c+γ}
PresnetationSlides-Feb-Apr-2016.nb 7
Slots # with functions & and user-
defined functions
◼ #&
Unset[x];
(* Function3+#[x] *)
3+# &[x]
3+x
#^2+#^4 &[x]
x2
+x4
#1^2+#2^4 &[x, y]
x2
+y4
(* Map#^2+#^4&,{x,y,z} *)
#^2+#^4 &/@{x, y, z}
x2
+x4
, y2
+y4
, z2
+z4

◼ User-defined functions
f[x_] := Sin[πx]
f0.5
1.
8 PresnetationSlides-Feb-Apr-2016.nb
Operations On Lists
varLis= Table10i+j, i, 4, j, 3
{{11, 12, 13}, {21, 22, 23}, {31, 32, 33}, {41, 42, 43}}
SelectvarLis, #2 < 22 &
{{11, 12, 13}}
GathervarLis, Abs#1[[1]]-#2[[1]] ⩵ 20 &
{{{11, 12, 13}, {31, 32, 33}}, {{21, 22, 23}, {41, 42, 43}}}
#[[1]], #3 &/@varLis
{{11, 13}, {21, 23}, {31, 33}, {41, 43}}
No loops!
PresnetationSlides-Feb-Apr-2016.nb 9
There is a Function for that,...
◼ If you wanted to bo something in Matheatica
chances are that there exists a built in function called
DoSomething[]
Solve expr , vars , FindRoot lhs == rhs ,  x , x0 , FindPeaks data , σ ,
EstimatedBackground  data , σ  , Gather list , test , Select list , crit ,
GroupBy elem 1 , elem 2 , … , spec , red , Split list , test ,
ImageConvolve  image , ker , ListConvolve ker , list , k , ImageData  image , type ,
Convolve f , g , x , y , FourierTransform  expr , t , ω , Fold f , x , list ,
NDSolve eqns , u ,  x , xmin , xmax , NIntegrate f ,  x , xmin , xmax ,
Evaluate expr , FourierSeries expr ,  t1 , t2 , … ,  n1 , n2 , … , ListPlot y1 , y2 , … ,
ListLinePlot y1 , y2 , … , ListLogPlot y1 , y2 , … , Plot f ,  x , xmin , xmax ,
TimeSeriesModelFit data , mspec , NonlinearModelFit data ,  form , cons ,  β1 , … ,  x1 , … 
◼ Your core logic should not take more than a
single line.
10 PresnetationSlides-Feb-Apr-2016.nb
Math Input Shortcuts
Switching between input form and Standard Form for selected cell in the notebook menu select
Cell-> Convert to-> StandardForm or the shortcut Shift+Ctr+N
Input form Standard Form Keyboard Shortcut
x^2 xn
x Ctr-[6] n
Subscript[x, j] xj x Ctr+_ j
Sqrt[x] x x Ctr+[2] x
x/n x
n
x Ctr+/ x
PresnetationSlides-Feb-Apr-2016.nb 11
Shortcuts Continued
Navigating throight different placeholders of the exoressins with the Tab
To exit the Ctrl + Space
Input form Standard Form Keyboard Shortcut
Integrate[, {, , }] ∫

ⅆ Esc-dintt-Esc
Sum[x, {, , }] ∑=
  Esc-sumt-Esc
Product[, {, , }] ∏=
  Esc-prodt-Esc
You can access the input palettes from the notebook menu Palletes->Basic Math Assistant
12 PresnetationSlides-Feb-Apr-2016.nb
Special Characters Shortcuts
Standard
Form
Keyboard
Shortcut
Notes
π Esc-pp-Esc The Pi 3.1415..
ⅇ Esc-ee-Esc The natural exp
ⅈ Esc-ii-Esc The imaginaryunit
∞ Esc-inf-Esc Infinitysymbol
ϵ Esc-e-Esc Greek epsilon
η Esc-et-Esc Greek etha
Similarly for the upper case greek letters Esc-G-Esc wouth output Γ Δ Ω
PresnetationSlides-Feb-Apr-2016.nb 13
Speed Math Typing Demo
14 PresnetationSlides-Feb-Apr-2016.nb
Importing data from XLS files
SetDirectoryNotebookDirectory[];
data = Import "table3InLab1.xls"[[1]];
data // TableForm
L1 Delta L1 V1 L2 Delta L2 V2 V
589.041 0.046 23.4279 589.635 0.043 21.8779 22.6529
589.051 0.056 28.5205 589.654 0.062 31.5439 30.0322
589.05 0.055 28.0112 589.644 0.052 26.4566 27.2339
589.03 0.035 17.8259 589.629 0.037 18.8254 18.3257
589.001 0.006 3.05602 589.603 0.011 5.59699 4.3265
588.983 -0.012 -6.11223 589.58 -0.012 -6.10604 -6.10914
588.964 -0.031 -15.7904 589.56 -0.032 -16.2833 -16.0369
588.964 -0.031 -15.7904 589.562 -0.03 -15.2656 -15.528
588.976 -0.019 -9.67781 589.579 -0.013 -6.61489 -8.14635
589.005 0.01 5.09334 589.604 0.012 6.10579 5.59956
589.033 0.038 19.3538 589.63 0.038 19.3342 19.344
dataV = Tablej-1, dataj+1[[7]], j, 1, Lengthdata-1;
PresnetationSlides-Feb-Apr-2016.nb 15
Nonlinear Model Fit
F[Vcm_ , Vo_, ϕ_, T_] := Vcm +Vo×Sinϕ+
2π
T
t;
nlm = NonlinearModelFitdataV, F[Vcm , Vo, ϕ, T], {Vcm , Vo, ϕ, T}, t;
pl = PlotNormal nlm , t, 0, 11;
lp = ListPlotdataV, ImageSize → 600, Frame → True,
Axes → False, FrameTicksStyle → DirectiveThick, 20,
PlotStyle → DirectiveRed, PointSize.02;
Showlp, pl
nlm "BestFitParameters "
0 2 4 6 8 10
-10
0
10
20
30
{Vcm → 6.59807, Vo → 23.1787, ϕ → 2.35962, T → 1.1067}
16 PresnetationSlides-Feb-Apr-2016.nb
Set initial conditions for the fit
nlm = NonlinearModelFitdataV, F[Vcm , Vo, ϕ, T], Vcm , Vo, ϕ, T, 10, t;
pl = PlotNormal nlm , t, 0, 11;
lp = ListPlotdataV, ImageSize → 600, Frame → True,
Axes → False, FrameTicksStyle → DirectiveThick, 20,
PlotStyle → DirectiveRed, PointSize.02;
Showlp, pl
nlm "BestFitParameters "
Totalnlm "FitResiduals"
0 2 4 6 8 10
-10
0
10
20
30
{Vcm → 6.59807, Vo → 23.1787, ϕ → 0.781968, T → 10.372}
-9.9476×10-14
PresnetationSlides-Feb-Apr-2016.nb 17
Determining the goodness of fit
nlm "ANOVATable"
DF SS MS
Model 4 3513.73 878.433
Error 7 5.11795 0.731136
Uncorrected Total 11 3518.85
Corrected Total 10 2912.13
nlm "FitResiduals"^2 // Total
5.11795
ListPlotnlm "FitResiduals", Filling→ Axis
2 4 6 8 10
-0.5
0.5
1.0
1.5
5.91404
18 PresnetationSlides-Feb-Apr-2016.nb
Fitting a subset of parameters
◼ Somtimes we might need to impose restrinctions on
some of the parameters in our model
F[Vcm , Vo, ϕ, T] /. Vo → 23.05, ϕ → 0.81
Vcm +23.05Sin0.81+
2πt
T

◼ Fitting only the subset of parameters while keeping
the other ones fixed
nlm = NonlinearModelFitdataV,
F[Vcm , Vo, ϕ, T] /. Vo → 23.05, ϕ → 0.81, Vcm , T, 10, t;
nlm "BestFitParameters "
{Vcm → 6.68274, T → 10.4396}
◼ Getting our final model
Normal nlm  /. Vo → 23.05, ϕ → 0.81
6.68274+23.05Sin[0.81+0.601862t]
PresnetationSlides-Feb-Apr-2016.nb 19
Dynamic Interactivity, Panels,
Controllers and Something else
20 PresnetationSlides-Feb-Apr-2016.nb
Manipulate[]
Manipulate
PlotSin[x(1+ax)], x, 0, 2π
, a, 0, 2
a
1 2 3 4 5 6
-1.0
-0.5
0.5
1.0
ManipulateSolute,
Solute, "H2O", "DCE", "Hexane", "Toluene", "Dodecane"

Solute H2O DCE Hexane Toluene Dodecane
Hexane
PresnetationSlides-Feb-Apr-2016.nb 21
Manipulate with different
ControlType
ManipulateSolute,
Solute, "H2O", "DCE", "Hexane", "Toluene", "Dodecane", ControlType -> PopupMenu

Solute Toluene
Toluene
Manipulatey, y, 0, 1, ControlType → Slider2D
y
0
◼ Some of the many possible values for ControlType
Animator  u ,  umin , umax , Checkbox x ,
InputField x , RadioButtonBar x ,  val1 , val2 , … 
22 PresnetationSlides-Feb-Apr-2016.nb
Working with dynamically updated
content
◼ Dynamic[expr ]
Controlx, 0, 0, {1, 1}
Dynamic [x]
{0., 0.}
Dynamic GraphicsLocatorDynamic [x], PlotRange → 1, Dynamic [x]
 , {0., 0.}
◼ DynamicModule[{x = x0 , y = y0 , … }, expr ]
Maintains a local instance of x,y,.. and preserves their values across notebook sessions
PresnetationSlides-Feb-Apr-2016.nb 23
DynamicModule x = 0, 0, GraphicsLocatorDynamic [x], PlotRange → 1, Dynamic [x]
 , {0.0111111, 0.244444}
24 PresnetationSlides-Feb-Apr-2016.nb
Manipulate vs DynamicModule
Manipulate
a×b,
a, 6, "Label for A", FieldSize→ 6,
b, 7, "Label for A", FieldSize→ 6

Label for A 6
Label for A 7
42
DynamicModule a = 6, b = 7,
PanelColumn 
"Label A", InputFieldDynamic [a], Number , ContinuousAction→ True,
"Label B", InputFieldDynamic b, Number ,
"A×B", InputFieldDynamic a×b



Label A
6
Label B
7
A×B
42
PresnetationSlides-Feb-Apr-2016.nb 25
Example Standalone Panel
Manipulate
ModuleElDenCalc,
ElDenCalcρo_, epmo_ , molwto_  :=
ρoepmo 6.0221415×1023
molwto 1024
;
IfSolute ⩵ "DCE", ρ = 1.24889, epm = 50, molwt = 98.9592;
IfSolute ⩵ "H2O", ρ = 0.99754, epm = 10, molwt = 18.0152;
IfSolute ⩵ "Toluene", ρ = 0.839, epm = 50, molwt = 92.1402;
IfSolute ⩵ "Hexane", ρ = 0.6548, epm = 50, molwt = 86.1754;
StyleElDenCalcρ, epm , molwt , Red, Bold, FontSize→ 22
,
Solute, "H2O", "DCE", "Toluene", "Hexane", ControlType -> PopupMenu,
ρ, .997, "ρmass ", FieldSize→ 6,
epm , 10, "e-
/mol ", FieldSize→ 6, molwt , 18.0152, "mw ", FieldSize→ 6
, FrameLabel →
"", "", Tooltip"Electron Density ", Style"
ρepm NA
mw 1024
", Blue, FontSize→ 30
Electron Density
Solute DCE
ρmass 1.24889
e-
/mol 50
mw 98.9592
0.380005
26 PresnetationSlides-Feb-Apr-2016.nb
Another Example Aplication
Manipulate
Module{},
(*Display *)
Column 
Row"Sign Label:", sign, " checkbox is:", cx,
Row"Slider Valie:", SliderVar,
Row" min :", minVar , " max :", maxVar 

, (*END Module*)
(*BEGIN Manipulate Controls *)
sign, "+1", "-1",
SliderVar, 2, "Slider Label", 0, 5
, cx, 1, "Check Label", 0, 1,
minVar , 0.017, maxVar , 0.03

sign +1 -1
Slider Label
Check Label
minVar 0.017
maxVar 0.03
Sign Label:+1 checkbox is:1
Slider Valie:2
min :0.017 max :0.03
PresnetationSlides-Feb-Apr-2016.nb 27
A complete example
Fit
C 10
A 15
ϕ 0.5
T 4
0 T->4 T chk->False
Model usemodel
Fit Res res
0 2 4 6 8 10
-10
0
10
20
30
28 PresnetationSlides-Feb-Apr-2016.nb
All work no play makes Jack a dull
boy
◼ Game Controller integration
ControllerInformation []
Controller Device 1: Logitech Logitech Dual Action
Raw Product Name "Logitech Logitech Dual Action "
Device Type Linux Joystick Device
Raw Controller Type Joystick
Mathematica Controls 36 controls
X $Failed
Y $Failed
Z $Failed
X1 $Failed
Y1 $Failed
Z1 $Failed
X2 $Failed
Y2 $Failed
X3 $Failed
Y3 $Failed
X4 $Failed
Y4 $Failed
X5 $Failed
Y5 $Failed
X6 $Failed
B1 $Failed
B2 $Failed
B3 $Failed
B4 $Failed
B5 $Failed
B6 $Failed
B7 $Failed
B8 $Failed
B9 $Failed
B10 $Failed
B11 $Failed
B12 $Failed
BLB $Failed
BRB $Failed
JB $Failed
JB1 $Failed
JB2 $Failed
Select Button $Failed
Start Button $Failed
TLB $Failed
TRB $Failed
Show Dynamic Values
Raw Controls 18
PresnetationSlides-Feb-Apr-2016.nb 29
Dynamic ControllerState"XY", "B1"
30 PresnetationSlides-Feb-Apr-2016.nb
Computing without the frontend
◼ Create an ASCII file scriptname.m
#!/usr/local/bin/MathematicaScript -script
<<myPackageWmyFunctions`;
a=22;b=34;
For[i=0, i<30, i++,
For[j=0, j<30, j++,
For[k=0, k<30, k++,
(*Do the work here and print some results*)
parA=j*a;parB=k*c
SomeResult=MyFunc[parA,parB]
Print[l,” “, i,” “, j,” “, k,SomeResult];
]
]
]
◼ From the command line run
$math -run <scriptname.m
PresnetationSlides-Feb-Apr-2016.nb 31
Calling Exteranl programs
◼ Opening system program
Run"notepad"
Run"calc"
◼ Executing command line script and outputing the
result to a file
Run"awk -f AWK4math /myawkscript .awk "<>filename
" > tmplocal /fileprefix_"<>fillevar<>".dat"
◼ Open the specified targeth path with the default
program
SystemOpen "phys.uic.edu"
SystemOpen "filename .docx"
32 PresnetationSlides-Feb-Apr-2016.nb
Interacting with MySQL database
◼ Connect to the database
Needs"DatabaseLink`";
JDBCDrivers"MySQL(Connector/J)";
conn = OpenSQLConnectionJDBC"MySQL(Connector/J)", "localhost/test_db",
"Username " → "root", "Password" → ""
◼ Select from the database
SQLSelectconn, "table_name ", "MaxRows" → 4, "ShowColumnHeadings " → True // TableForm
◼ Inserting
SQLInsertconn, "table_name ", "col_a", "col_b", 3, 10.5
PresnetationSlides-Feb-Apr-2016.nb 33
And many more applictions
THANK YOU
34 PresnetationSlides-Feb-Apr-2016.nb

More Related Content

PDF
LP linear programming (summary) (5s)
PPT
Bisection and fixed point method
PPTX
Particle Swarm Optimization
PDF
PPTX
Linear dependence & independence vectors
PDF
Quadratic programming (Tool of optimization)
PPT
PSO and Its application in Engineering
LP linear programming (summary) (5s)
Bisection and fixed point method
Particle Swarm Optimization
Linear dependence & independence vectors
Quadratic programming (Tool of optimization)
PSO and Its application in Engineering

What's hot (20)

PDF
Particle Swarm Optimization: The Algorithm and Its Applications
PPTX
Introduction to genetic algorithms
PDF
Big m method
PPTX
Optimization problems and algorithms
PPTX
Role OF Robots In Medical Field
PPTX
Metric space
PPTX
Function
PPTX
Linear programming graphical method (feasibility)
PDF
Traveling Salesman Problem (TSP)
PPTX
Flowchart of GA
PPTX
Particle swarm optimization
PPTX
Operations Research - The Dual Simplex Method
PPTX
ROBOTICS AND ITS APPLICATIONS
PPTX
Matlab ploting
PDF
Introduction to Numerical Analysis
PPTX
ORTHOGONAL, ORTHONORMAL VECTOR, GRAM SCHMIDT PROCESS, ORTHOGONALLY DIAGONALI...
PPT
Graph theory presentation
PPTX
Particle swarm optimization
PPTX
Real analysis
PDF
Solution manual-of-probability-statistics-for-engineers-scientists-9th-editio...
Particle Swarm Optimization: The Algorithm and Its Applications
Introduction to genetic algorithms
Big m method
Optimization problems and algorithms
Role OF Robots In Medical Field
Metric space
Function
Linear programming graphical method (feasibility)
Traveling Salesman Problem (TSP)
Flowchart of GA
Particle swarm optimization
Operations Research - The Dual Simplex Method
ROBOTICS AND ITS APPLICATIONS
Matlab ploting
Introduction to Numerical Analysis
ORTHOGONAL, ORTHONORMAL VECTOR, GRAM SCHMIDT PROCESS, ORTHOGONALLY DIAGONALI...
Graph theory presentation
Particle swarm optimization
Real analysis
Solution manual-of-probability-statistics-for-engineers-scientists-9th-editio...
Ad

Viewers also liked (12)

PPT
Cotton gin And eli whintey
KEY
Rabies
PPT
Transportation 1800's
PDF
Hafitz_Rizki 201343500823 Komponen_GUI_pada_Java
PDF
TECOSIM-Projekt: Automatischer Schraubengenerator für Crash-Simulationen in A...
PPT
Tarea 3
PPTX
Inventions and inventors with life history
PPTX
2011 AP US PP - Transportation 1800-1850
PPT
2011 AP US PP - Transportation Developments 1800 - 1850
PPTX
Java Tutorial Lab 4
PPSX
Interface Gráfico de Usuario para Google Maps v3
PDF
Pythonで画面付きのアプリを作成する
Cotton gin And eli whintey
Rabies
Transportation 1800's
Hafitz_Rizki 201343500823 Komponen_GUI_pada_Java
TECOSIM-Projekt: Automatischer Schraubengenerator für Crash-Simulationen in A...
Tarea 3
Inventions and inventors with life history
2011 AP US PP - Transportation 1800-1850
2011 AP US PP - Transportation Developments 1800 - 1850
Java Tutorial Lab 4
Interface Gráfico de Usuario para Google Maps v3
Pythonで画面付きのアプリを作成する
Ad

Similar to Mathematica for Physicits (20)

PPTX
Chapter 2 =Introduction to Mathematica.pptx
PDF
Mathematica tutorial 3
PPTX
Lecture 2.pptxLecture 2.pptxLecture 2.pptxLecture 2.pptx
PPTX
IntroductionToMathematica.pptx
PDF
Using Mathematica for computational learning
PDF
Me 443 3 basic calculations Erdi Karaçal Mechanical Engineer University of ...
DOCX
A practical work of matlab
PDF
Anything but simple Mathematica
PPTX
making of lists,tables,matrix,vactor,sets.pptx
PPTX
NumericalAlgebraic Calculations, updated.pptx
PDF
R Cheat Sheet for Data Analysts and Statisticians.pdf
PPTX
Intro to Matlab programming
PPT
Introduction to MATLAB
PDF
ML-CheatSheet (1).pdf
PPTX
Basic MATLAB Programming PPT.pptx
PDF
An Introduction to MATLAB with Worked Examples
PPTX
PPT
Matlab Nn Intro
PDF
PDF
Matlab tutorial 4
Chapter 2 =Introduction to Mathematica.pptx
Mathematica tutorial 3
Lecture 2.pptxLecture 2.pptxLecture 2.pptxLecture 2.pptx
IntroductionToMathematica.pptx
Using Mathematica for computational learning
Me 443 3 basic calculations Erdi Karaçal Mechanical Engineer University of ...
A practical work of matlab
Anything but simple Mathematica
making of lists,tables,matrix,vactor,sets.pptx
NumericalAlgebraic Calculations, updated.pptx
R Cheat Sheet for Data Analysts and Statisticians.pdf
Intro to Matlab programming
Introduction to MATLAB
ML-CheatSheet (1).pdf
Basic MATLAB Programming PPT.pptx
An Introduction to MATLAB with Worked Examples
Matlab Nn Intro
Matlab tutorial 4

Recently uploaded (20)

PDF
Worlds Next Door: A Candidate Giant Planet Imaged in the Habitable Zone of ↵ ...
PDF
CHAPTER 3 Cell Structures and Their Functions Lecture Outline.pdf
PDF
Cosmic Outliers: Low-spin Halos Explain the Abundance, Compactness, and Redsh...
PPTX
Hypertension_Training_materials_English_2024[1] (1).pptx
PPTX
Microbes in human welfare class 12 .pptx
PPTX
BIOMOLECULES PPT........................
PPTX
Pharmacology of Autonomic nervous system
PDF
Biophysics 2.pdffffffffffffffffffffffffff
PDF
Warm, water-depleted rocky exoplanets with surfaceionic liquids: A proposed c...
PDF
BET Eukaryotic signal Transduction BET Eukaryotic signal Transduction.pdf
PPTX
ognitive-behavioral therapy, mindfulness-based approaches, coping skills trai...
PDF
lecture 2026 of Sjogren's syndrome l .pdf
PPTX
C1 cut-Methane and it's Derivatives.pptx
PDF
Unveiling a 36 billion solar mass black hole at the centre of the Cosmic Hors...
PPTX
Biomechanics of the Hip - Basic Science.pptx
PPTX
The Minerals for Earth and Life Science SHS.pptx
PPTX
Fluid dynamics vivavoce presentation of prakash
PDF
. Radiology Case Scenariosssssssssssssss
PPTX
Application of enzymes in medicine (2).pptx
PDF
An interstellar mission to test astrophysical black holes
Worlds Next Door: A Candidate Giant Planet Imaged in the Habitable Zone of ↵ ...
CHAPTER 3 Cell Structures and Their Functions Lecture Outline.pdf
Cosmic Outliers: Low-spin Halos Explain the Abundance, Compactness, and Redsh...
Hypertension_Training_materials_English_2024[1] (1).pptx
Microbes in human welfare class 12 .pptx
BIOMOLECULES PPT........................
Pharmacology of Autonomic nervous system
Biophysics 2.pdffffffffffffffffffffffffff
Warm, water-depleted rocky exoplanets with surfaceionic liquids: A proposed c...
BET Eukaryotic signal Transduction BET Eukaryotic signal Transduction.pdf
ognitive-behavioral therapy, mindfulness-based approaches, coping skills trai...
lecture 2026 of Sjogren's syndrome l .pdf
C1 cut-Methane and it's Derivatives.pptx
Unveiling a 36 billion solar mass black hole at the centre of the Cosmic Hors...
Biomechanics of the Hip - Basic Science.pptx
The Minerals for Earth and Life Science SHS.pptx
Fluid dynamics vivavoce presentation of prakash
. Radiology Case Scenariosssssssssssssss
Application of enzymes in medicine (2).pptx
An interstellar mission to test astrophysical black holes

Mathematica for Physicits

  • 1. Useful knowledge on Mathematica® for Physicists Miroslav Mihaylov UIC Physics Feb-17-2016
  • 2. The notebook inrerface and the kernel ◼ The user enters input in the notebook ◼ The input is sent to the Math Kernel via Shift+Enter or Numpad Enter ◼ The kernel performs the computation ans send the result back to the frontend for display Frontend Integrate[Exp[-x^2],x] π 2 Erf[x] Math Kernel  ◼ MathLink the protocol for comunication of the frontend with the Kernel and other 2 PresnetationSlides-Feb-Apr-2016.nb
  • 3. Lists {a1, a2, ..., an} ◼ Generating lists with Table[] Table expr ,  i , i min , i max , Table expr ,  i , i min , i max , di , Table expr ,  i ,  i 1 , i 2 , …  Tablei, i, 10, 20, 2 {10, 12, 14, 16, 18, 20} Tablei, 2×i, i, 10, 20, 2 {{10, 20}, {12, 24}, {14, 28}, {16, 32}, {18, 36}, {20, 40}} Table10i+j, i, 4, j, 3 {{11, 12, 13}, {21, 22, 23}, {31, 32, 33}, {41, 42, 43}} ◼ Generating lists with Range[] Range i max , Range i min , i max , Range i min , i max , di  Range[5] {1, 2, 3, 4, 5} Range2, 5, 0.5 {2., 2.5, 3., 3.5, 4., 4.5, 5.} ◼ Table with Random TableRandom [], 3 {0.929755, 0.0990263, 0.960832} RandomInteger 10, 4, 3 {{5, 1, 9}, {4, 3, 10}, {6, 9, 3}, {6, 3, 2}} PresnetationSlides-Feb-Apr-2016.nb 3
  • 4. Lists Representations ◼ Usefull for easy inspection of the elemetns of the list Table10i+j, i, 4, j, 3 // TableForm 11 12 13 21 22 23 31 32 33 41 42 43 0, -ⅈ, ⅈ, 0 // MatrixForm  0 -ⅈ ⅈ 0  MatrixForm [{a1, a2}]  a1 a2  4 PresnetationSlides-Feb-Apr-2016.nb
  • 5. Programing in Mathematica Say we have the list bellow and we would like to reverse the elements of each item in the list lis= {α, 1}, β, 2, γ, 3; With procedural programing we would write tempLis = lis; Fori = 1, i ≤ Lengthlis, i++,  tempLis i, 1, tempLis i, 2 = lisi, 2, lisi, 1  ; tempLis {{1, α}, {2, β}, {3, γ}} Slightly better approach Table lisi, 2, lisi, 1, i, 1, Lengthlis  {{1, α}, {2, β}, {3, γ}} PresnetationSlides-Feb-Apr-2016.nb 5
  • 6. The Mathematica Way For each element of the list we want to reverse MapReverse, lis {{1, α}, {2, β}, {3, γ}} Same as above written in an alternative syntax Reverse/@lis {{1, α}, {2, β}, {3, γ}} 6 PresnetationSlides-Feb-Apr-2016.nb
  • 7. Map[] /@ and Apply[] @@ ◼ Map applies a function to each element in a list Mapf, a, b, c {f[a], f[b], f[c]} ◼ Apply changes the structure of the expression Applyf, a, b, c f[a, b, c] ApplyPlus, a, b, c, d a+b+c+d ApplyPlus, a, b, c, {α, β, γ} {a+α, b+β, c+γ} PresnetationSlides-Feb-Apr-2016.nb 7
  • 8. Slots # with functions & and user- defined functions ◼ #& Unset[x]; (* Function3+#[x] *) 3+# &[x] 3+x #^2+#^4 &[x] x2 +x4 #1^2+#2^4 &[x, y] x2 +y4 (* Map#^2+#^4&,{x,y,z} *) #^2+#^4 &/@{x, y, z} x2 +x4 , y2 +y4 , z2 +z4  ◼ User-defined functions f[x_] := Sin[πx] f0.5 1. 8 PresnetationSlides-Feb-Apr-2016.nb
  • 9. Operations On Lists varLis= Table10i+j, i, 4, j, 3 {{11, 12, 13}, {21, 22, 23}, {31, 32, 33}, {41, 42, 43}} SelectvarLis, #2 < 22 & {{11, 12, 13}} GathervarLis, Abs#1[[1]]-#2[[1]] ⩵ 20 & {{{11, 12, 13}, {31, 32, 33}}, {{21, 22, 23}, {41, 42, 43}}} #[[1]], #3 &/@varLis {{11, 13}, {21, 23}, {31, 33}, {41, 43}} No loops! PresnetationSlides-Feb-Apr-2016.nb 9
  • 10. There is a Function for that,... ◼ If you wanted to bo something in Matheatica chances are that there exists a built in function called DoSomething[] Solve expr , vars , FindRoot lhs == rhs ,  x , x0 , FindPeaks data , σ , EstimatedBackground  data , σ  , Gather list , test , Select list , crit , GroupBy elem 1 , elem 2 , … , spec , red , Split list , test , ImageConvolve  image , ker , ListConvolve ker , list , k , ImageData  image , type , Convolve f , g , x , y , FourierTransform  expr , t , ω , Fold f , x , list , NDSolve eqns , u ,  x , xmin , xmax , NIntegrate f ,  x , xmin , xmax , Evaluate expr , FourierSeries expr ,  t1 , t2 , … ,  n1 , n2 , … , ListPlot y1 , y2 , … , ListLinePlot y1 , y2 , … , ListLogPlot y1 , y2 , … , Plot f ,  x , xmin , xmax , TimeSeriesModelFit data , mspec , NonlinearModelFit data ,  form , cons ,  β1 , … ,  x1 , …  ◼ Your core logic should not take more than a single line. 10 PresnetationSlides-Feb-Apr-2016.nb
  • 11. Math Input Shortcuts Switching between input form and Standard Form for selected cell in the notebook menu select Cell-> Convert to-> StandardForm or the shortcut Shift+Ctr+N Input form Standard Form Keyboard Shortcut x^2 xn x Ctr-[6] n Subscript[x, j] xj x Ctr+_ j Sqrt[x] x x Ctr+[2] x x/n x n x Ctr+/ x PresnetationSlides-Feb-Apr-2016.nb 11
  • 12. Shortcuts Continued Navigating throight different placeholders of the exoressins with the Tab To exit the Ctrl + Space Input form Standard Form Keyboard Shortcut Integrate[, {, , }] ∫  ⅆ Esc-dintt-Esc Sum[x, {, , }] ∑=   Esc-sumt-Esc Product[, {, , }] ∏=   Esc-prodt-Esc You can access the input palettes from the notebook menu Palletes->Basic Math Assistant 12 PresnetationSlides-Feb-Apr-2016.nb
  • 13. Special Characters Shortcuts Standard Form Keyboard Shortcut Notes π Esc-pp-Esc The Pi 3.1415.. ⅇ Esc-ee-Esc The natural exp ⅈ Esc-ii-Esc The imaginaryunit ∞ Esc-inf-Esc Infinitysymbol ϵ Esc-e-Esc Greek epsilon η Esc-et-Esc Greek etha Similarly for the upper case greek letters Esc-G-Esc wouth output Γ Δ Ω PresnetationSlides-Feb-Apr-2016.nb 13
  • 14. Speed Math Typing Demo 14 PresnetationSlides-Feb-Apr-2016.nb
  • 15. Importing data from XLS files SetDirectoryNotebookDirectory[]; data = Import "table3InLab1.xls"[[1]]; data // TableForm L1 Delta L1 V1 L2 Delta L2 V2 V 589.041 0.046 23.4279 589.635 0.043 21.8779 22.6529 589.051 0.056 28.5205 589.654 0.062 31.5439 30.0322 589.05 0.055 28.0112 589.644 0.052 26.4566 27.2339 589.03 0.035 17.8259 589.629 0.037 18.8254 18.3257 589.001 0.006 3.05602 589.603 0.011 5.59699 4.3265 588.983 -0.012 -6.11223 589.58 -0.012 -6.10604 -6.10914 588.964 -0.031 -15.7904 589.56 -0.032 -16.2833 -16.0369 588.964 -0.031 -15.7904 589.562 -0.03 -15.2656 -15.528 588.976 -0.019 -9.67781 589.579 -0.013 -6.61489 -8.14635 589.005 0.01 5.09334 589.604 0.012 6.10579 5.59956 589.033 0.038 19.3538 589.63 0.038 19.3342 19.344 dataV = Tablej-1, dataj+1[[7]], j, 1, Lengthdata-1; PresnetationSlides-Feb-Apr-2016.nb 15
  • 16. Nonlinear Model Fit F[Vcm_ , Vo_, ϕ_, T_] := Vcm +Vo×Sinϕ+ 2π T t; nlm = NonlinearModelFitdataV, F[Vcm , Vo, ϕ, T], {Vcm , Vo, ϕ, T}, t; pl = PlotNormal nlm , t, 0, 11; lp = ListPlotdataV, ImageSize → 600, Frame → True, Axes → False, FrameTicksStyle → DirectiveThick, 20, PlotStyle → DirectiveRed, PointSize.02; Showlp, pl nlm "BestFitParameters " 0 2 4 6 8 10 -10 0 10 20 30 {Vcm → 6.59807, Vo → 23.1787, ϕ → 2.35962, T → 1.1067} 16 PresnetationSlides-Feb-Apr-2016.nb
  • 17. Set initial conditions for the fit nlm = NonlinearModelFitdataV, F[Vcm , Vo, ϕ, T], Vcm , Vo, ϕ, T, 10, t; pl = PlotNormal nlm , t, 0, 11; lp = ListPlotdataV, ImageSize → 600, Frame → True, Axes → False, FrameTicksStyle → DirectiveThick, 20, PlotStyle → DirectiveRed, PointSize.02; Showlp, pl nlm "BestFitParameters " Totalnlm "FitResiduals" 0 2 4 6 8 10 -10 0 10 20 30 {Vcm → 6.59807, Vo → 23.1787, ϕ → 0.781968, T → 10.372} -9.9476×10-14 PresnetationSlides-Feb-Apr-2016.nb 17
  • 18. Determining the goodness of fit nlm "ANOVATable" DF SS MS Model 4 3513.73 878.433 Error 7 5.11795 0.731136 Uncorrected Total 11 3518.85 Corrected Total 10 2912.13 nlm "FitResiduals"^2 // Total 5.11795 ListPlotnlm "FitResiduals", Filling→ Axis 2 4 6 8 10 -0.5 0.5 1.0 1.5 5.91404 18 PresnetationSlides-Feb-Apr-2016.nb
  • 19. Fitting a subset of parameters ◼ Somtimes we might need to impose restrinctions on some of the parameters in our model F[Vcm , Vo, ϕ, T] /. Vo → 23.05, ϕ → 0.81 Vcm +23.05Sin0.81+ 2πt T  ◼ Fitting only the subset of parameters while keeping the other ones fixed nlm = NonlinearModelFitdataV, F[Vcm , Vo, ϕ, T] /. Vo → 23.05, ϕ → 0.81, Vcm , T, 10, t; nlm "BestFitParameters " {Vcm → 6.68274, T → 10.4396} ◼ Getting our final model Normal nlm  /. Vo → 23.05, ϕ → 0.81 6.68274+23.05Sin[0.81+0.601862t] PresnetationSlides-Feb-Apr-2016.nb 19
  • 20. Dynamic Interactivity, Panels, Controllers and Something else 20 PresnetationSlides-Feb-Apr-2016.nb
  • 21. Manipulate[] Manipulate PlotSin[x(1+ax)], x, 0, 2π , a, 0, 2 a 1 2 3 4 5 6 -1.0 -0.5 0.5 1.0 ManipulateSolute, Solute, "H2O", "DCE", "Hexane", "Toluene", "Dodecane"  Solute H2O DCE Hexane Toluene Dodecane Hexane PresnetationSlides-Feb-Apr-2016.nb 21
  • 22. Manipulate with different ControlType ManipulateSolute, Solute, "H2O", "DCE", "Hexane", "Toluene", "Dodecane", ControlType -> PopupMenu  Solute Toluene Toluene Manipulatey, y, 0, 1, ControlType → Slider2D y 0 ◼ Some of the many possible values for ControlType Animator  u ,  umin , umax , Checkbox x , InputField x , RadioButtonBar x ,  val1 , val2 , …  22 PresnetationSlides-Feb-Apr-2016.nb
  • 23. Working with dynamically updated content ◼ Dynamic[expr ] Controlx, 0, 0, {1, 1} Dynamic [x] {0., 0.} Dynamic GraphicsLocatorDynamic [x], PlotRange → 1, Dynamic [x]  , {0., 0.} ◼ DynamicModule[{x = x0 , y = y0 , … }, expr ] Maintains a local instance of x,y,.. and preserves their values across notebook sessions PresnetationSlides-Feb-Apr-2016.nb 23
  • 24. DynamicModule x = 0, 0, GraphicsLocatorDynamic [x], PlotRange → 1, Dynamic [x]  , {0.0111111, 0.244444} 24 PresnetationSlides-Feb-Apr-2016.nb
  • 25. Manipulate vs DynamicModule Manipulate a×b, a, 6, "Label for A", FieldSize→ 6, b, 7, "Label for A", FieldSize→ 6  Label for A 6 Label for A 7 42 DynamicModule a = 6, b = 7, PanelColumn  "Label A", InputFieldDynamic [a], Number , ContinuousAction→ True, "Label B", InputFieldDynamic b, Number , "A×B", InputFieldDynamic a×b    Label A 6 Label B 7 A×B 42 PresnetationSlides-Feb-Apr-2016.nb 25
  • 26. Example Standalone Panel Manipulate ModuleElDenCalc, ElDenCalcρo_, epmo_ , molwto_  := ρoepmo 6.0221415×1023 molwto 1024 ; IfSolute ⩵ "DCE", ρ = 1.24889, epm = 50, molwt = 98.9592; IfSolute ⩵ "H2O", ρ = 0.99754, epm = 10, molwt = 18.0152; IfSolute ⩵ "Toluene", ρ = 0.839, epm = 50, molwt = 92.1402; IfSolute ⩵ "Hexane", ρ = 0.6548, epm = 50, molwt = 86.1754; StyleElDenCalcρ, epm , molwt , Red, Bold, FontSize→ 22 , Solute, "H2O", "DCE", "Toluene", "Hexane", ControlType -> PopupMenu, ρ, .997, "ρmass ", FieldSize→ 6, epm , 10, "e- /mol ", FieldSize→ 6, molwt , 18.0152, "mw ", FieldSize→ 6 , FrameLabel → "", "", Tooltip"Electron Density ", Style" ρepm NA mw 1024 ", Blue, FontSize→ 30 Electron Density Solute DCE ρmass 1.24889 e- /mol 50 mw 98.9592 0.380005 26 PresnetationSlides-Feb-Apr-2016.nb
  • 27. Another Example Aplication Manipulate Module{}, (*Display *) Column  Row"Sign Label:", sign, " checkbox is:", cx, Row"Slider Valie:", SliderVar, Row" min :", minVar , " max :", maxVar   , (*END Module*) (*BEGIN Manipulate Controls *) sign, "+1", "-1", SliderVar, 2, "Slider Label", 0, 5 , cx, 1, "Check Label", 0, 1, minVar , 0.017, maxVar , 0.03  sign +1 -1 Slider Label Check Label minVar 0.017 maxVar 0.03 Sign Label:+1 checkbox is:1 Slider Valie:2 min :0.017 max :0.03 PresnetationSlides-Feb-Apr-2016.nb 27
  • 28. A complete example Fit C 10 A 15 ϕ 0.5 T 4 0 T->4 T chk->False Model usemodel Fit Res res 0 2 4 6 8 10 -10 0 10 20 30 28 PresnetationSlides-Feb-Apr-2016.nb
  • 29. All work no play makes Jack a dull boy ◼ Game Controller integration ControllerInformation [] Controller Device 1: Logitech Logitech Dual Action Raw Product Name "Logitech Logitech Dual Action " Device Type Linux Joystick Device Raw Controller Type Joystick Mathematica Controls 36 controls X $Failed Y $Failed Z $Failed X1 $Failed Y1 $Failed Z1 $Failed X2 $Failed Y2 $Failed X3 $Failed Y3 $Failed X4 $Failed Y4 $Failed X5 $Failed Y5 $Failed X6 $Failed B1 $Failed B2 $Failed B3 $Failed B4 $Failed B5 $Failed B6 $Failed B7 $Failed B8 $Failed B9 $Failed B10 $Failed B11 $Failed B12 $Failed BLB $Failed BRB $Failed JB $Failed JB1 $Failed JB2 $Failed Select Button $Failed Start Button $Failed TLB $Failed TRB $Failed Show Dynamic Values Raw Controls 18 PresnetationSlides-Feb-Apr-2016.nb 29
  • 30. Dynamic ControllerState"XY", "B1" 30 PresnetationSlides-Feb-Apr-2016.nb
  • 31. Computing without the frontend ◼ Create an ASCII file scriptname.m #!/usr/local/bin/MathematicaScript -script <<myPackageWmyFunctions`; a=22;b=34; For[i=0, i<30, i++, For[j=0, j<30, j++, For[k=0, k<30, k++, (*Do the work here and print some results*) parA=j*a;parB=k*c SomeResult=MyFunc[parA,parB] Print[l,” “, i,” “, j,” “, k,SomeResult]; ] ] ] ◼ From the command line run $math -run <scriptname.m PresnetationSlides-Feb-Apr-2016.nb 31
  • 32. Calling Exteranl programs ◼ Opening system program Run"notepad" Run"calc" ◼ Executing command line script and outputing the result to a file Run"awk -f AWK4math /myawkscript .awk "<>filename " > tmplocal /fileprefix_"<>fillevar<>".dat" ◼ Open the specified targeth path with the default program SystemOpen "phys.uic.edu" SystemOpen "filename .docx" 32 PresnetationSlides-Feb-Apr-2016.nb
  • 33. Interacting with MySQL database ◼ Connect to the database Needs"DatabaseLink`"; JDBCDrivers"MySQL(Connector/J)"; conn = OpenSQLConnectionJDBC"MySQL(Connector/J)", "localhost/test_db", "Username " → "root", "Password" → "" ◼ Select from the database SQLSelectconn, "table_name ", "MaxRows" → 4, "ShowColumnHeadings " → True // TableForm ◼ Inserting SQLInsertconn, "table_name ", "col_a", "col_b", 3, 10.5 PresnetationSlides-Feb-Apr-2016.nb 33
  • 34. And many more applictions THANK YOU 34 PresnetationSlides-Feb-Apr-2016.nb