Mathematica

Mathematica的一些小技巧

[TOC]

如何更好的使用目录?

解决方案来自于Table of contents with hyperlinks

1
2
3
4
5
6
7
8
9
10
11
12
13
nbTOC[nb_] := 
Button[Mouseover[#, Style[#, "HyperlinkActive"]] &@
First@NotebookRead@#, SelectionMove[#, All, CellContents],
Appearance -> None, BaseStyle -> "Hyperlink", Alignment -> Left,
ImageSize -> 1000] & /@
Cells[CellStyle -> {"Title", "Chapter", "Section", "Subsection",
"Subsubsection"}] //
CreatePalette[
Panel[Column[#, Dividers -> Center], ImageSize -> 1000],
FrontEnd`ClosingSaveDialog -> False,
WindowTitle -> "Table of Contents", Magnification -> 1] &;
nbTOC[Optional[Automatic, Automatic]] := nbTOC@EvaluationNotebook[];
nbTOC[]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
tableOfContents[notebook_] := 
Module[{headerTypes, nb, header, headerCells,
tagHeaders},(*Cell types to include in ToC*)
headerTypes = "Subsection" | "Section";
(*Find cells of the desired type and tag with their names*)
nb = Import[notebook];
headerCells = Cases[nb, Cell[_, headerTypes, ___], Infinity];
tagHeaders = Map[Append[#, CellTags -> #[[1]]] &, headerCells];
(*Export tagged cells*)
Export[notebook,
ReplaceAll[nb,
Normal[AssociationThread[headerCells, tagHeaders]]]];
(*Generate styled hyperlinks for ToC*)
Map[If[MatchQ[#[[2]], "Section"],
Hyperlink[
Style[#[[1]], RGBColor@{211/256, 15/64, 0},
FontFamily -> "Arial", FontTracking -> "Plain",
FontSize -> 18], {notebook, #[[1]]}],
Hyperlink[
Style["\t" <> #[[1]], RGBColor@{53/64, 51/128, 1/256},
FontFamily -> "Arial", FontTracking -> "Plain",
FontSize -> 14], {notebook, #[[1]]}]] &, headerCells] //
TableForm];

如何使用”Jet”颜色函数?

解决方案来自于Custom ColorFunction/ColorData in ArrayPlot (and similar functions)

1
2
3
4
jet[u_?NumericQ] := Blend[
{{0, RGBColor[0, 0, 9/16]}, {1/9, Blue}, {23/63, Cyan}, {13/21, Yellow},
{47/63, Orange}, {55/63, Red}, {1, RGBColor[1/2, 0, 0]}},
u] /; 0 <= u <= 1

一个例子示例如何制定颜色的范围(20201127),

1
2
3
4
5
6
7
vmin = -1;
vmax = 1;
DensityPlot[Sin[x] Sin[y], {x, 0, 3 \[Pi]}, {y, 0, 3 \[Pi]},
ColorFunction -> (jet[Rescale[#1, {vmin, vmax}]] &),
ColorFunctionScaling -> False,
PlotLegends ->
BarLegend[{jet[Rescale[#1, {vmin, vmax}]] &, {vmin, vmax}}]]

如何访问矩阵的元素以及部分?

1
2
3
4
mat[[m]]
mat[[m,n]]
mat[[m1;;m2,n]]
mat[[All,n]]

如何从Mathematica运行Python?

1
2
session = StartExternalSession["Python"]
ExternalEvaluate[session,File["filepath"]]

如何生成带颜色的框?

运行如下代码,然后选择颜色即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
cell[color_, form_, style_String: "Text", 
font_String: "Comic Sans MS", size_Integer: 15] :=
NotebookWrite[EvaluationCell[],
Cell[BoxData[FormBox["", form]], style,
CellFrame -> {{0.5, 0.5}, {1.5, 0.5}}, FontSize -> size,
FontFamily -> font, FontWeight -> "Plain",
Background ->
RGBColor[
Sequence @@ (color /. ColorSetter :> List /. RGBColor :> List //
Flatten)]], All];
ccell = cell[ColorSetter[GrayLevel[1]], TraditionalForm, "Text",
"Times New Roman", 15] // Defer
csmyellowcell :=
cell[RGBColor[1., 1., 0.5019607843137255], TraditionalForm, "Text",
"Comic Sans MS", 15];
csmgreencell :=
cell[LightGreen, TraditionalForm, "Text", "Comic Sans MS", 15];

tnryellowcell :=
cell[RGBColor[1., 1., 0.5019607843137255], TraditionalForm, "Text",
"Times New Roman", 15];

tnrwhitecell :=
cell[White, TraditionalForm, "Text", "Times New Roman", 15];
tnrgreencell :=
cell[LightGreen, TraditionalForm, "Text", "Times New Roman", 15];
tnrgraycell :=
cell[RGBColor[236/255, 236/255, 236/255], TraditionalForm, "Text",
"Times New Roman", 15];

Mathematica如何更改StyleSheet里面Style的快捷键

Add keyboard shortcut to the DisplayFormula style

Mathematica通过留数定理计算积分

1
2
3
4
5
6
7
8
(*Assume the original function is fana(t)/fpole(t)*)
funcomplexint[fana_, fpole_, t_] := Module[{sol, poles, numpoles},
sol = Solve[fpole == 0, t];
numpoles = Length[Flatten[sol]];
poles = t /. sol;
Table[(fana*(t - poles[[i]])/fpole) /. {t -> poles[[i]]}, {i,
numpoles}]
];

Mathematica按Enter变成换行而不是创建新的Cell

Pressing the “enter” key in the Python External Evaluation cell becomes “run” instead of “line break”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
SetOptions[EvaluationNotebook[], FrontEnd`ReturnCreatesNewCell -> False]

SetOptions[EvaluationNotebook[],
StyleDefinitions -> Notebook@{
Cell@StyleData[StyleDefinitions -> FrontEnd`FileName[{"Article"}, "JournalArticle.nb", CharacterEncoding -> "UTF-8"]],
Cell[StyleData@"ExternalLanguage", FrontEnd`ReturnCreatesNewCell -> False]
}
]

SetOptions[EvaluationNotebook[],
StyleDefinitions -> Notebook@{
Cell@StyleData[StyleDefinitions -> FrontEnd`FileName[{"Article"}, "JournalArticle.nb", CharacterEncoding -> "UTF-8"]],
Cell[StyleData@"Notebook", FrontEnd`ReturnCreatesNewCell -> False]
}
]
```

Wolfram Client Library for Python

Mathematica 获取 python数据

in python external evaluation

1
2
from wolframclient.serializers import export
export(<object>) # <object> could be any things supported

in mathematica we have

1
efficpy=ToExpression[%]];

从 Mathematica中用默认软件打开PDF

1
2
3
4
url = "C:\\Users\\xiail\\Desktop\\PhysRevA.99.023857.pdf";

Button[Style["mathematica.pdf", "Subsection"], SystemOpen[url],
Appearance -> "Frameless"]

Launch PDF viewer from within a Mathematica Notebook

Mathematica的meshgrid函数

我们在python和MATLAB都有meshgrid函数来帮我们绘图,在Mathematica需要手动实现。解决方案来自于
Simulate MATLAB’s meshgrid function

一般MATLAB实现为

1
2
3
 [X,Y] = meshgrid(-2:.1:2, -4:.2:4);
Z = X .* exp(-X.^2 - Y.^2);
surf(X,Y,Z)

而Mathematica实现为

1
2
3
4
5
6
7
8
9
meshgrid[x_List, y_List]:={ConstantArray[x,Length[y]],Transpose@ConstantArray[y,Length[x]]}

{xx, yy} = meshgrid[Range[-2, 2, .1], Range[-4, 4, .2]];
c = xx*Exp[-xx^2 - yy^2];

pts = Flatten[{xx, yy, c}, {2, 3}];
ListPlot3D[pts, PlotRange -> All, AxesLabel -> Automatic,
ImagePadding -> 20, Mesh -> 35, InterpolationOrder -> 2,
ColorFunction -> "Rainbow", Boxed -> False]

注意原答案是有问题的,我的版本已经改过来了。

Mathematica的寻找最大值以及其位置

List manipulation: position & max value combination

1
findmax[x_]:={x[[#]],#}&@@Ordering[-x,1];

运行其他的笔记本

1
2
3
4
5
6
SetDirectory[NotebookDirectory[]];
(*nbFile="Tools_ListofFunctions.nb";*)
nbFile = FileNameJoin@{Directory[], "Tools_ListofFunctions.nb"};
FileExistsQ[nbFile];
(*NotebookEvaluate[nbFile];*)
NotebookEvaluate[nbFile]

绘图调整细节

调制一下坐标的字体以及线条

1
2
3
LabelStyle -> 
Directive[FontSize -> 20, FontFamily -> "Times", FontColor -> Black],
FrameStyle -> Directive[Black, Thickness -> 0.005]

自己设置一些矩形的图例
1
2
3
4
5
Marker1 = Table[{Graphics[{EdgeForm[Thickness[0.1]], RGBColor[{
Rational[11, 51],
Rational[42, 85],
Rational[184, 255]}], Polygon[CirclePoints[4]]}], 0.04}, {i, 1, L,
1}];

修改位置

1
2
3
4
PlotLegends -> 
Placed[LineLegend[{"1"},
LabelStyle -> {FontFamily -> "Helvetica", FontSize -> 15,
Black}, LegendLayout -> {"Column", 1}], {0.5, 0.75}]];

如何导出颜色图

1
2
3
f = ColorData["TemperatureMap"];
mat = Table[f[x], {x, 0, 1, 0.01}];
mat /. {RGBColor[x_, y_, z_] -> {x, y, z}}