Introduction to Mathematica



Shirley Pepke, CACR

What is Mathematica?

•Language

Script (dynamically typed, good for rapid prototyping, etc.)

x=2; y=3;
x+y

"Everything is an expression"

TreeForm[apples+bananas]

colors={Green,Blue,Magenta};
dt=Table[Graphics[{colors[[i]],Thick,Circle[]},ImageSize->Tiny],{i,1,3}]

TreeForm[dt]

•Symbolic and Numeric Analysis Suite

•Polynomials

Clear[x]
Factor[ (x^3)+4 (x^2)-7x-10]

•Linear Algebra

dm={{1,0},{1,-1}};
dv=Transpose[Eigenvectors[dm]];
Print["Matrix is: ",MatrixForm[dm]];
Print["Eigenvector matrix is: ",MatrixForm[dv]]
Print["(dv^(-1))dm dv = ",MatrixForm[Inverse[dv].dm.dv]];

•Calculus

∫Sin[θ]\[DifferentialD]θ

D[-Cos[θ],θ]

NIntegrate[Sin[θ],{θ,0,π}]

Clear[x]
Series[Exp[x],{x,0,5}]

•Sums and Products

•Differential Equations

Clear[x,y]
spirals=DSolve[{x'[s]==Cos[t[s]],y'[s]==Sin[t[s]],t'[s]==s,x[0]==0,y[0]==0,t[0]==0},{x,y,t},s]

•Numerical Optimization and Fitting

Clear[ls,x];
For[shift=0,shift<40,shift+=2,
	Clear[mine,shiftedplus,shiftedminus,aggregate,pdata];
SetDirectory["/Users/spepke/proj/genome/twist/fits"];
alldata = Import["oneprofile.mat","Table"];
pine:=Interpolation[alldata[[1]]];
mine:=Interpolation[alldata[[2]]];
shiftedplus[din_]:={
pine[din-shift]
}/;din >shift &&din <(Length[alldata[[1]]]+shift);
shiftedplus[din_]:=0/;(din≤shift || din ≥(Length[alldata[[1]]]+shift));

shiftedminus[din_]:={
mine[din+shift]
}/;(din>=(1-shift)&&din<(Length[alldata[[2]]]-shift)
);
shiftedminus[din_]:=0/;(din<(1-shift)||din>=(Length[alldata[[2]]]-shift));
aggregate[din_]:=shiftedplus[din]+shiftedminus[din];
pdata=Flatten[Table[aggregate[i],{i,-shift,Length[alldata[[1]]+shift]}]];
	ffsol=FindFit[pdata,model,parameters,x,Method->NMinimize];
	results =Table[model/.ffsol,{x,1,Length[pdata]}];
	res = results-pdata;
	err=res*res;
	(*Print[shift," ",Sum[err[[i]],{i,1,Length[res]}]*)
ls[shift]=N[Sum[err[[i]],{i,1,Length[res]}]];
pp=Plot[model/.ffsol,{x,1,Length[pdata]},DisplayFunction->Identity,PlotRange->All];
lp=ListPlot[pdata,PlotStyle->{PointSize[0.015]},PlotRange->All];
Print[Show[lp,pp]];
Print[shift" ",Sum[err[[i]],{i,1,Length[res]}]];
]
ls[0]
lsmin=ls[0];
smin=0;
For[shift=1,shift<40,shift+=2,
If[lsmin > ls[shift],lsmin=ls[shift]; smin=shift;]
]
lsmin
smin
lst=Table[ls[i],{i,0,40}]
ListPlot[lst]

•Visualization Tool

•2D and 3D plotting

ParametricPlot[Evaluate[{x[s],y[s]}/.spirals],{s,-10,10}]

•Vector and raster graphics

•Interactive display -- demonstrations.wolfram.com

Manipulate[Show[Graphics3D[{Specularity[GrayLevel[.3],1],RGBColor[.75,.7,.45],Sphere[{0,0,0},1],White,PointSize[.001],Point[stars]},Method->{"SpherePoints"->80}],(Graphics3D[{EdgeForm[GrayLevel[.3]],Lighter[RGBColor[.65,.6,.35],Rescale[(#[[1]]+#[[2]])/2,{1.24,2.30}]],Specularity[White,128],Ring[#[[1]],#[[2]]]}]&)/@Partition[Drop[Flatten[Nest[Flatten[({{#1[[1]],#1[[1]]+(1/3) (#1[[2]]-#1[[1]])},{#1[[2]]-(1/3) (#1[[2]]-#1[[1]]),#1[[2]]}}&)/@#1,1]&,{{1.24,2.30}},n]],1],2],ImageSize->{500,380},Background->Black,PlotRange->30,Lighting->{{"Ambient",GrayLevel[.2]},{"Directional",White,{0,-5,3}}},SphericalRegion->True,ViewVector->Dynamic[{{1.1,y,1},{1.5,0,0}},None],Boxed->False,ViewRange->{.9,30},ViewAngle->Pi/5],{{n,4,"number of iterations"},{0,1,2,3,4,5},ControlType->SetterBar},{{y,-10,"fly by"},-10,10},AutorunSequencing->{{1,4},{2,10}},Initialization:>{SeedRandom[12345];stars=20 Table[{Cos[#1]Sqrt[1-#2^2],Sin[#1]Sqrt[1-#2^2],#2}&[Random[Real,{0,2Pi}],Random[Real,{-1,1}]],{5000}];Ring[rMin_,rMax_]:=Polygon[Join[Table[rMin {Cos[a],Sin[a],0},{a,0,2 Pi,Pi/64}],Table[rMax {Cos[a],Sin[a],0},{a,0,2 Pi,Pi/64}]]]}]

•Integrated Computational Workspace

•Good for exploration
•Quick solutions or diagnostics
•Lots of options
•Extensive documentation, knowledgeable userbase
•Automatic code generation
•Can change anything!

The Structure of a Mathematica Notebook

Notebooks are interactive documents that are organized into cells.
Cells have styles: Text, Input, Output, ExpressionCell

This is a text cell.

2+2

Cells have properties : Editable,Evaluatable,...

Cells can be grouped

"I'm with this guy ↑"

Notebooks have styles, too...

Basic Syntax (Variables, Lists, Iterators)

A variable can be created simply by assigning it a value.

blackbirds=24  (* a scalar *)

(* Mathematica Keywords are capitalized*)
rainbow=List[Red,Green,Blue,Yellow,Orange] (* a list *)

amatrix= {{3,4,5},{6,7,8}} (* a list of lists *)

Lists can also be constructed iteratively.

sqrs=Table[(w^2),{w,0,5}]

Elements in a list are accessed by index.

amatrix[[2,3]] (* Starting with index 1! *)
Part[amatrix,1,1]

Mathematical operations are applied to each element of a list in turn.

amatrix*2

Operations on Lists

Joining:

Clear[a,b,c,d];
list1={a,b,c};
list2={d,e,a};
Join[list1,list2]
jl={list1,list1,list2}

Union[list1,list2]

Riffle[list1,list2]

Analyzing:

Gather[{how,much,wood,would,a,wood,chuck,chuck,if,a,wood,chuck,would,chuck,wood}]

Reformatting:

j2={jl,jl}
j3=Flatten[j2]
Flatten[j2,1]

First[j3]

Apply functions over lists:

Clear[f]
Map[f,{0,Pi/2,Pi}]

Thread[f[{0,Pi/2,Pi}]]
Thread[f[{0,Pi/2,Pi},x]]

Patterns

ReplaceAll (/.)

{x,x^2,y,z}/.x->{a,b}

x+y/.{{x->1,y->2},{x->4,y->2}}

Condition (/;)

{6,-7,3,2,-1,-2}/.x_/;x<0->w

RuleDelayed(:>)   holds right hand side unevaluated

{x,x,x}/.x->RandomReal[]

{x,x,x}/.x:>RandomReal[]

Basic Syntax (Functions)

Define a simple function of two arguments:
The arguments passed can be scalars...

distance[x_,y_]:=Sqrt[(((x-y))^2)]
distance[2,1]

Or vectors...

c1={2,1};
c2={4,4};
distance[c1,c2]

Or...

distance2d[x_,y_]:=Sqrt[Sum[(((x[[i]]-y[[i]]))^2),{i,1,Length[x]}]]
distance2d[c1,c2]

altdistance2d[x_,y_]:=Norm[x-y]
altdistance2d[c1,c2]

Slots:

Gather[Range[10],Mod[#1,3]==Mod[#2,3]&]

Solving Equations

Can generate lists of solutions

sol=Solve[{x^2+y^2==1,x+y==a},{x,y}]

x/.sol

For equations that can't be solved in closed form analytically...

Solve[x^5-2x+3==0,x]

...symbolic solvers have numeric counterparts prefaced by 'N'.

NSolve[x^5-2x+3==0,x]

NDSolve returns InterpolatingFunctions

fresult = NDSolve[{u''[t]+u[t]==0,u[0]==0,u'[0]==1},u,{t,0,Pi}];
myfun = First[u/.fresult]
myfun[2.]

Accuracy and Precision can be controlled.
Numerical instability can be diagnosed and alternative methods chosen.

Graphics and Manipulation

Use Plot for 1D functions

Plot[{Sin[x],Sin[2x],Sin[3x]},{x,0,2Pi},PlotStyle->Thick,AxesLabel->{"Radians","Sin[nx]"}]

Use the function 'Manipulate' to make it interactive

Manipulate[Plot[{Sin[a*x],Sin[a*2x],Sin[a*3x]},{x,0,2 Pi},PlotStyle->Thick],{a,0,2}]

Use ListPlot for discrete points in 1D.

Plot3D and ListPlot3D for surfaces

Manipulate[Plot3D[Sin[a*x+y^2],{x,-3,3},{y,-2,2}],{a,1,4}]

Other types of data presentation

Histogram[ProteinData[#,"MolecularWeight"]&/@{"NEDD8","SLK","GGA2","PDXP","SENP8","TRIO","TDG","E2F1","PLK1","UBE2S","ETS1","PDE6D","GPX7","SOD1","PAH","RAB21"}]

ProteinData[#,"MoleculePlot"]&/@{"NEDD8","SLK","GGA2","PAH"}

PieChart[Range[5],ChartStyle->"DarkRainbow",ChartLegends->{"A","B","C","D","E"}]

File I/O

SetDirectory["/Users/spepke"];

Import:

data =Import["signalprofiles.mat","Table"];

Length[data]

lp=ListPlot[Table[data[[j]],{j,1,100}],Joined->True,PlotStyle->Thick,PlotRange->All]

Export:

Export["profiles.jpg",lp];

Next lecture: code generation, parallelism, packages, contexts, a more complex example

Final Point

Wolfram Demonstrations Project
	Physics: 39 pages
	Biology: 6 pages  ------> What an opportunity!