Quick Mathematica
Posted on September 2, 2022
Tags: mathematica
1 dockerfile
# Use the Wolfram Engine container as the base image
FROM wolframresearch/wolframengine
USER root
RUN pip install jupyterlab
ARG WOLFRAM_ID
ARG WOLFRAM_PASSWORD
RUN wolframscript -activate -username "${WOLFRAM_ID}" -password "${WOLFRAM_PASSWORD}"
RUN wolframscript -activate
RUN wget --no-check-certificate --content-disposition https://github.com/WolframResearch/WolframLanguageForJupyter/archive/refs/heads/master.zip
RUN apt install unzip
RUN unzip WolframLanguageForJupyter-master.zip
RUN ./WolframLanguageForJupyter-master/configure-jupyter.wls add
# RUN wget --no-check-certificate --content-disposition https://github.com/WolframResearch/WolframLanguageForJupyter/releases/download/v0.9.3/WolframLanguageForJupyter-0.9.3.paclet
# # RUN wolframscript -code PacletInstall["WolframLanguageForJupyter-0.9.3.paclet"]
# # RUN wolframscript -code Needs["WolframLanguageForJupyter`"]
# # RUN wolframscript -code ConfigureJupyter["Add"]
RUN wget -P /opt https://github.com/Kitware/CMake/releases/download/v3.26.4/cmake-3.26.4-linux-x86_64.sh
RUN chmod +x /opt/cmake-3.26.4-linux-x86_64.sh
EXPOSE 8888
CMD ["jupyter", "lab", "--ip=0.0.0.0", "--allow-root", "--no-browser", "--NotebookApp.token=''", "--NotebookApp.password=''"]
# CMD sh -c 'while true; do date; sleep 1; done'
# Install JupyterLab and the Wolfram Kernel for Jupyter
# RUN wolframscript -e 'PacletInstall["WolframLanguageForJupyter"]'
# # Configure JupyterLab extensions
# RUN jupyter labextension install @jupyter-widgets/jupyterlab-manager \
# && jupyter labextension install @jupyterlab/debugger
docker build --build-arg WOLFRAM_ID="nsj65837@aklqo.com" --build-arg WOLFRAM_PASSWORD="yourpassword" -t jupywolf .
#docker run -p 8888:8888 jupywolf
docker run -p 8888:8888 -v $PWD:/mountedDir jupywolf
#the above maps host file current dir to /mountedDir
2 Basics
Concept | Python | Mathematica |
---|---|---|
list | [1,2,3] |
{1,2,3} |
index | a[0] |
a[[0]] |
slice | a[2:5] |
a[[2;5]] |
list-notation | [x**2 for x in range(10)] |
Table[x^2, {x, 10}] |
2.1 Solve for x
Concept | Mathematica |
---|---|
Solve for x | Solve[x+2y==5,x] |
Numerical Approx Solve | NSolve[x^5 - 2 x + 3 == 0, x] |
Derivative | D[x^2+2==0,x] |
Integrate | Integrate[E^2x,x] |
- output of
Solve
is a nested list in the form of Rules. - use pattern matching
/.
to apply the rules
sol = Solve[x+2y==5,x]
OUTPUT: {{x -> 5-2y}}
x /. sol
OUTPUT: 5-2y
2.2 Selective Expand
- Only expand
(1 - Sin[x])
term
Clear[x]
Expand[(1 - Sin[x]) (x+1)^2 + (1 - Sin[x]) (x+6)^2 , (1 - Sin[x]) ]
2.3 Collect
- Collect terms so that same variables are together
Clear[x,y]
p[x_,y_] := y*x^2 + x^2 + 3 y^2 x + x y^4 + (x+1+y)^2
p[x,y]
Collect[p[x,y],x]
2.4 Differential Equation
Concept | Mathematica |
---|---|
Analytical Solve | DSolve[x] |
Numerical Solve | NDSolve[x] |
2.5 Numbers
N
Reduce expr to numeric valueFixedPoint[x,7]
Find closest fixed point from x = 7
2.6 Map Fold Zip
Concept | Function |
---|---|
original | f[3] |
preapply | f@3 |
postapply | 3 // f |
Concept | Function |
---|---|
Map | f /@ {1,2,3} |
Fold | NestList[,,] |
Zip | Thread[{lista,listb}] |
3 Plot
3.1 2d+3d plots
^2,{x,0,30}] Plot[x
= np.linspace(0,30,999)
x = lambda x: x**2
f plt.plot(x,f(x))
1/(1+Exp[-(x1+x2)]),{x1,-Pi,Pi},{x2,-Pi,Pi}] ContourPlot[
= np.linspace(-np.pi,np.pi,999)
x1 = np.linspace(-np.pi,np.pi,999)
x2 = lambda x1,x2: 1/(1+np.exp(-(x1+x2)))
f = np.meshgrid(x1,x2)
X1,X2 plt.contourf(X1,X2,f(X1,X2))
Plot3D[1/(1+Exp[-(x1+x2)]),{x1,-10,10},{x2,-10,10}]
=lambda x1,x2: 1/(1+np.exp(-(x1+x2)))
f= np.linspace(-10, 10, 99)
x1 = np.linspace(-10, 10, 99)
x2 = np.meshgrid(x1, x2)
X1,X2 = plt.figure(figsize=(10, 6))
fig = fig.add_subplot(111, projection='3d')
ax
=2, cstride=2,cmap=cm.jet,alpha=0.7,linewidth=0.25)
ax.plot_surface(X1,X2,f(X1, X2),rstride#ax.contour3D(X1,X2,f(X1, X2),rstride=2, cstride=2,cmap=cm.jet,alpha=0.7,linewidth=0.25)
#ax.plot_wireframe(X1,X2,f(X1, X2),rstride=2, cstride=2,cmap=cm.jet,alpha=0.7,linewidth=0.25)
plt.show()
3.2 vector + plots
AArrow[{p_, q_}, label_:""] := {{Inset[Style[label,Purple],Midpoint[{p,q}]], Arrow[{p,q}]}};
vec2[q_,label_:""] := Graphics@AArrow[{{0,0},q},label];
vec2[p_,q_,label_:""] := Graphics@AArrow[{p,q},label];
vec3[q_,label_:""] := Graphics3D@AArrow[{{0,0,0},q},label];
vec3[p_,q_,label_:""] := Graphics3D@AArrow[{p,q},label];
vec[q_,label_:""] := If[Length[q] == 2,vec2[q,label],vec3[q,label]];
vec[p_,q_,label_:""] := If[Length[q] == 2,vec2[p,q,label],vec3[p,q,label]];
pnt[x_] := Graphics3D@Point[x];
- Combining vector arrow plots with equation plots
v1 = {1,2};
v2 = {2,3};
Show[vec[v1,"a"],
vec[v2,"b"],
vec[v1,v2,"b-a"],
Plot[x^2,{x,0,2}],
ImageSize->Small,
Axes->True
]
vv1 = {1,1,5};
vv2 = {4,5,5};
Show[vec[vv1,"v1"],
vec[vv2,"v2"],
Plot3D[2*x1*x2,{x1,-1,1},{x2,-1,1}, PlotStyle->Opacity[0.3]],
ImageSize->Small,
Axes->True
]
3.2.1 Annotated arrow
4 AST
Transform vec2 to vec3 functions in the Plot subsection above.
vv1 = {1,1,10};
vv2 = {4,5,10};
ooo = {0,0,0};
vec2[p_,q_] := Graphics@Arrow[{p,q}]
vec3 := (vec2[#1,#2] /. Graphics -> Graphics3D)&
Graphics[stuff] /. Graphics -> Graphics3D
allows us to pattern-replace Graphics
Head node with Graphics3D
Head node in the AST
- Head of a AST is the function or operator
SetOptions[TreeForm,ImageSize -> {150, 150}];
f[x_] := p+q^2
f[x_] // TreeForm
f[x_] // Head
ExpressionGraph[f[x_], VertexLabels -> Automatic, DirectedEdges -> True,ImageSize -> {150,150}]
4.1 print out AST
x*Tan[y + z] // TreeForm
5 Nested list
NestList[f, x, 4]
(* {f[x],f^2[x],f^3[x],f^4[x]}*)
[{f[#1], g[#1]} &, x, 3, VertexLabels -> All] NestGraph
6 functions
6.1 Module
bleh = Module[
{a = 1,
b = 4},
a + b + 8]
def blah():
= 1
a = 4
b return a + b + 8
6.2 Lambda
#1, #2
are the bound variables of the lambda&
indicates the expr is a lambda
f[x_,y_] := x*y + 2
f := (#1*#2 + 2)&
6.3 Post apply and LateX output
double backslash for post application
A ={{1,2,3},{-1,3,0}} // MatrixForm // TeXForm
A = TeXForm[MatrixForm[{{1,2,3},{-1,3,0}}]]
7 Simplify with condition
Simplify[expr,assum] : simjply with assumptions Expand[expr,patt] : expand all but pattern patt ExpandAll[expr] : expand product and exponents ExpandAll[expr,patt] : expand when matching pattern patt
Assuming[Element[n, Integers] && n > 0,
Integrate[Sin[n x]^2, {x, 0, Pi}]]
8 Solve implicit differentiation
x[t_] := Cosh[t]
y[s_] := Cos[s]
z[x_, y_] := x[t] Exp[-y[s]]
D[z[x, y], s]
9 Taylor Series
Series[E^x, {x, 0, 7}]
10 Extras
10.1 show all prob dist
StringCases[#, ___ ~~ "Distribution" ~~ ___ :> #] & /@ Names["System`*"];
DeleteCases[%, {}]
10.2 print out probability Distributions
StringCases[#, ___ ~~ "Distribution" ~~ ___ :> #] & /@
Names["System`*"];
DeleteCases[%, {}]
10.3 Importing Fred Data
y = Import["C:\\Users\\User\\Downloads\\DCOILWTICO.csv", "Dataset",
"HeaderLines" -> 1]
DateListPlot[y]
10.4 Equity Timeseries Forecast
x = FinancialData["SPX", {{2020, 1, 1}, {2021, 1, 1}}]
= TimeSeriesModelFit[x]
tsm ListLinePlot[{tsm["TemporalData"], TimeSeriesForecast[x, {10}]}]
10.6 Visualizing injectivity surjectivity
AArrow[{p_, q_}, label_:""] := {{Arrow[{p,q}], Inset[label,Midpoint[{p,q}]]}};
vec2[p_,q_,label_:""] := Graphics@AArrow[{p,q},label];
vec3[p_,q_,label_:""] := Graphics3D@AArrow[{p,q},label];
pnt[x_] := Graphics3D@Point[x];
ydst[y_] := {0,#1}& /@ y
xsrc[x_] := {#1,0}& /@ x
dset = Range[-5,5,1]
xpnt = xsrc[dset];
yset2[f_] = f /@ dset
yset = yset2[#^2&];
ypnt = ydst[yset];
srcdstlst = Thread[{xpnt,ypnt}] ;
arrowlst := vec2[#[[1]],#[[2]]]& /@ srcdstlst
Show[
arrowlst,
Plot[x^2,{x,-5,5}],
Axes->True
]
10.7 Visualize Geometric Mean
- The Red arrow is the geometric mean of the two black arrows.
- ContourPlot allows plotting of implicit equations like the circle equation
hc := ContourPlot[x^2+y^2==1,{x,-2,2},{y,-2,2}] // Graphics
a := 1.5
b := 0.5
geoMean := N[Sqrt[a*b]]
aArrow := Arrow[{{-1, 0}, {-1+a, 0}}] // Graphics
bArrow := Arrow[{{0.5,0},{0.5+b,0}}] // Graphics
geoArrow := Arrow[{{0.5,0},{0.5,geoMean}}] // Graphics[{Red,#1}]&
(* Graphics[{Red,#}]& is a lambda function, with #1 as the bound variable and & indicating a lambda expr*)
Show[aArrow,bArrow,geoArrow,hc, ImageSize -> {150, 150}]