Lecture 8

SetDirectory[NotebookDirectory[]]

Resource Functions

The Wolfram Function Repository is a curated cloud repository of functions set up to be instantly usable in the Wolfram Language . The Function Repository includes a growing number of functions designed for a wide range of application areas . The Wolfram Language supports creation of private resource functions, which can then be submitted for inclusion in the Wolfram Function Repository .

https://resources.wolframcloud.com/FunctionRepository

PlotGrid

ResourceFunction["PlotGrid"]

[{{Plot[x,{x,0,1},Frame->True],Plot[x^2,{x,0,1},Frame->True]}}]

ResourceFunction["PlotGrid"][{{Plot[x,{x,0,1},Frame->True],Plot[x^2,{x,0,1},Frame->True]}}]

[{{Plot[x,{x,0,1},Frame->True]},{Plot[x^2,{x,0,1},Frame->True]}},ImageSize->200]

Metropolis Hastings

ResourceFunction["MetropolisHastingsSequence"]

(* generate a MCMC sampling of a likelihood *)

mc=[Exp[-1./2.(x^2.+y^2.)],{{x,0},{y,0}},{50000,0,1}];

Histogram3D[mc]

SmoothHistogram3D[mc]

(* convert into a prob distribution *)

dist=SmoothKernelDistribution[mc]

Plot3D[PDF[dist,{x,y}],{x,-3,3},{y,-3,3},PlotRange->All,PlotPoints->50]

ContourPlot[PDF[dist,{x,y}],{x,-3,3},{y,-3,3},PlotRange->All]

Covariance[dist]//MatrixForm

(* generate a MCMC sampling of a likelihood *)

cov={{1,.5},{.5,1}};invcov=Inverse[cov];var={x,y};mc=[Exp[-1./2.*var.invcov.var],{{x,0},{y,0}},{50000,0,1}];
(* convert into a prob distribution *)
dist=SmoothKernelDistribution[mc];
ContourPlot[PDF[dist,{x,y}],{x,-3,3},{y,-3,3},PlotRange->All]
Covariance[dist]//MatrixForm

max=NMaximize[PDF[dist,{x,y}],{x,y}]
maxl=max[[1]]

(* integrate over a region high than level *)

level=0.15;r=ImplicitRegion[PDF[dist,{x,y}]>level && -2<x<2 && -2<y<2,{x,y}];
NIntegrate[PDF[dist,{x,y}],{x,y}∈r]

(* do that for several levels *)

res={};tablev=Table[level,{level,0,.95*maxl,maxl/5}];
Do[{r=ImplicitRegion[PDF[dist,{x,y}]>tablev[[i]] && -2<x<2 && -2<y<2,{x,y}];
AppendTo[res,{NIntegrate[PDF[dist,{x,y}],{x,y}∈r],tablev[[i]]}]},{i,Length[tablev]}]

hei=Interpolation[res]

ContourPlot[{PDF[dist,{x,y}]==hei[.68],PDF[dist,{x,y}]==hei[.9]},{x,-3,3},{y,-3,3},PlotRange->All]

RandomMaze

ResourceFunction["RandomMaze"][30]

Magic Squares

ms=ResourceFunction["MagicSquare"][3];ms//TableForm

ms[[All,1]]
ms[[1,All]]

Table[Total[ms[[All,i]]],{i,Length[ms]}]
Table[Total[ms[[i,All]]],{i,Length[ms]}]
Total[Diagonal[ms]]

QR code

BarcodeImage["https://www.thphys.uni-heidelberg.de/~amendola/teaching.html","QR",200]

BarcodeImage["You can store any random text in a QR code, up to 4000 characters","QR",200]

Parsing text in internet

text=Import["https://edition.cnn.com/"];

?StringCount

StringCount[text,"Biden"]
StringCount[text,"Trump"]

An association is alist in which key a is associated with value x, key b with value y, etc . :

(* associations *)

assoc=<|a->x,b->y,c->z|>

<|"a"->x,"b"->{y,z}|>[["b"]]

(* convert lists into associations*)

list2Assoc[in_]:=Which[VectorQ[in,Head[#]===Rule&],Apply[Association,Map[list2Assoc,in]],ListQ[in],Map[list2Assoc,in],Head[in]===Rule&&ListQ[in[[2]]],in[[1]]->list2Assoc[in[[2]]],True,in];

(* get a response from the inpirehep API (Application Programming Interface); the response is a list in JSON format *)

authorsn="Witten";authorn="E.";
authorsn="Einstein";authorn="A.";
url="https://inspirehep.net/api/literature?sort=mostrecent&size=500&page=1&q=find%20au%20"<>authorsn<>"%2C%20"<>authorn;

text=Import[url,"JSON"];
list=list2Assoc[text];
data=list[["hits","hits"]];
cit=Table[data[[i]][["metadata","citation_count"]],{i,Length[data]}];
Print["name: ",authorsn<>", "<>authorn," , papers: ",Length[cit],"  , citations: ",Total[cit]]

text
list

URLEncode["<"]
URLEncode[">"]
URLEncode[" "]
URLEncode[","]

(* get a response from the inpirehep API (Application Programming Interface); the response is a list in JSON format *)

authorsn="Einstein";authorn="A.";
authorsn="Witten";authorn="E.";
datein="2010";dateout="2025";
url="https://inspirehep.net/api/literature?sort=mostrecent&size=500&page=1&q=find%20au%20"<>authorsn<>"%2C%20"<>authorn<>"%20and%20date%3E"<>datein<>"%20and%20date%3C"<>dateout;
text=Import[url,"JSON"];
list=list2Assoc[text];
data=list[["hits","hits"]];
cit=Table[data[[i]][["metadata","citation_count"]],{i,Length[data]}];
Print["name: ",authorsn<>", "<>authorn," , papers: ",Length[cit],"  , citations: ",Total[cit]]

Machine Learning

?FindClusters

cov={{1,0},{0,1}};np=20;c1={0,0};c2={5,5};

points=Join[RandomVariate[MultinormalDistribution[c1,cov],np],RandomVariate[MultinormalDistribution[c2,cov],np]];
ListPlot[points,Frame->True]

cl=FindClusters[points];
ListPlot[cl,Frame->True]

cov={{1,0},{0,1}};np=20;c1={0,0};c2={5,5};c3={-5,-5};c4={2,-2};
set[c_]:=RandomVariate[MultinormalDistribution[c,cov],np];
points=Join[set[c1],set[c2],set[c3],set[c4]];
ListPlot[points,Frame->True,PlotRange->All,PlotLabel->"Original"]

(* free number of clusters *)
cl=FindClusters[points];
ListPlot[cl,Frame->True,PlotLabel->"Free number of clusters"]

(* require exactly 4 clusters *)
cl=FindClusters[points,4];
ListPlot[cl,Frame->True,PlotLabel->"Four clusters"]

ImageIdentify[]

figure=Import["galaxy.jpg"];
figure

ImageIdentify[figure]

Strange symbols: @ and &

@ : short for applying a function to an argument

Sin[Pi/4.]
Sin@(Pi/4.)

Plot[x^2,{x,0,3},PlotStyle->Thickness@.03]

Pure (or anonynous) functions

f=#^2&

f@4
#^2&@4

Clear[f];list={a,b,c};
list2={d,e,f};

Map[#^2&,list]

#^2&/@list

Apply[Plus,list]
Apply[Times,list]

Plus@@list
Times@@list
Times@@@{list,list2}

Music

?Play

Sound[{SoundNote["C",1,"Violin"],SoundNote["G",0.5,"Piano",SoundVolume->0.8]}]

p=0.25;Sound[{SoundNote["C",{0,1},"Violin"],SoundNote["G",{0,.5},"Piano"],SoundNote["C",{1,1.25},"Piano"],SoundNote["D",{1.25,1.75},"Piano"],SoundNote["A",{1.25,2},"Violin"],SoundNote["D",{1.75,2},"Piano"],
SoundNote["C",2.+p+{0,1},"Violin"],SoundNote["G",2.+p+{0,.5},"Piano"],SoundNote["C",2.+p+{1,1.25},"Piano"],SoundNote["D",2.+p+{1.25,1.75},"Piano"],SoundNote["B",2.+p+{1.25,2},"Violin"],SoundNote["D",2.+p+{1.75,2},"Piano"],SoundNote["C",2+p+{2.25,3},"Violin"]}]

p=0.25;instrument="Percussion";
instrument="Harp";Sound[{SoundNote["C",{0,1},instrument],SoundNote["G",{0,.5},instrument],SoundNote["C",{1,1.25},instrument],SoundNote["D",{1.25,1.75},instrument],SoundNote["A",{1.25,2},instrument],SoundNote["D",{1.75,2},instrument],
SoundNote["C",2.+p+{0,1},instrument],SoundNote["G",2.+p+{0,.5},instrument],SoundNote["C",2.+p+{1,1.25},instrument],SoundNote["D",2.+p+{1.25,1.75},instrument],SoundNote["B",2.+p+{1.25,2},instrument],SoundNote["D",2.+p+{1.75,2},instrument],SoundNote["C",2+p+{2.25,3},instrument]}]

?Play

Play[Sin[1500 t]+Sin[1520 t],{t,0,2}]

ResourceFunction["MathToMusicTransform"][x^2,{x,-7,7},.5]

ResourceFunction["MathToMusicTransform"][Exp[x/2]+Exp[-x/3],{x,-7,7},.3]

Random music

?RandomSample

(* create a random melody *)

instruments={"Harp","Piano","Xylophone"};
Clear[dt0];
dt={0.05,0.1,0.2};
dt={0.1,0.2,0.4};

score={};t0new=0;
nn=30;
notes={"C4","D4","E4","F4","G4","A4","B4"};

Do[{dt0=RandomSample[dt,1][[1]];t0=t0new;AppendTo[score,SoundNote[RandomSample[notes,1][[1]],{t0,t0+dt0},RandomSample[instruments,1][[1]]]],t0new=t0+dt0},{i,nn}];
tt=t0
Sound[score]

(* add a random base with lower volume *)

instruments={"Bass"};
Clear[dt0];
dt={1};
basescore={};t0new=0;
nn=Floor[tt];
notes={"C3","E3"};
Do[{dt0=RandomSample[dt,1][[1]];t0=t0new;AppendTo[basescore,SoundNote[RandomSample[notes,1][[1]],{t0,t0+dt0},RandomSample[instruments,1][[1]],SoundVolume->.8]],t0new=t0+dt0},{i,nn}];
basescore
Sound[basescore]

(* add a not-random base  *)

instruments={"Bass"};
Clear[dt0];
dt={.5};
basescore={};t0new=0;
nn=Floor[tt]/dt[[1]];
notes={"C3","E3","G3"};
j=0;
Do[{dt0=dt[[1]];t0=t0new;
note=notes[[1+Mod[i,3]]];
AppendTo[basescore,SoundNote[note,{t0,t0+dt0},RandomSample[instruments,1][[1]],SoundVolume->1.]],t0new=t0+dt0},{i,nn}];
basescore
Sound[basescore]

(* combine *)

Sound[Join[score,basescore]]

Sound[{SoundNote["C",{0,1},instrument],SoundNote["G",{0,.5},instrument],SoundNote["C",{1,1.25},instrument],SoundNote["D",{1.25,1.75},instrument],SoundNote["A",{1.25,2},instrument],SoundNote["D",{1.75,2},instrument],
SoundNote["C",2.+p+{0,1},instrument],SoundNote["G",2.+p+{0,.5},instrument],SoundNote["C",2.+p+{1,1.25},instrument],SoundNote["D",2.+p+{1.25,1.75},instrument],SoundNote["B",2.+p+{1.25,2},instrument],SoundNote["D",2.+p+{1.75,2},instrument],SoundNote["C",2+p+{2.25,3},instrument]}]