LaTeX, Python tips in master's thesis

Make a note of the small story that the author (Physical Physics M2) used to write the master's thesis as a template.

LaTeX The environment is pLaTeX, \ documentclass [a4paper, 10pt] {jsarticle}.

Figure

preamble


\usepackage[dviout]{graphicx}
\usepackage{here} %[H]When using the option

Insert figure

\begin{figure}[ht]
 %Option h:On the spot, t:Top of page, b:Bottom of page, p:Create a dedicated page
 % H:Forced output on the spot
 \centering
 \includegraphics[keepaspectratio, width=0.8\linewidth]{fig1.png}
  %Option keepaspectratio:Fixed ass ratio, width,height:Size specification
  % 0.8\Specify by ratio with paper width such as line width and length with unit such as 8 cm
 \caption{caption}
 \label{fig:1} %Cross-reference label
\end{figure}

In the past, when dealing with images with TeX, the market price was decided as eps, but now PDF is the fastest. Even in other cases, dvipdfmx will convert it to PDF, so you can use PNG or JPEG as it is. http://www.yamamo10.jp/~yamamoto/comp/latex/make_doc/insert_fig/index.php#CONTEMPORARY

If you increase the number of lines of \ includegraphics ..., they will be arranged appropriately, but if you want to control it properly and make it 2 columns etc.

\begin{figure}[ht]
 \begin{tabular}{cc}
  \begin{minipage}[t]{0.45\hsize}
   \centering
   \includegraphics[keepaspectratio, width=\linewidth]{fig2.png}
   \caption{Caption 1}
   \label{fig:2}
  \end{minipage} &
  \begin{minipage}[t]{0.45\hsize}
   \centering
   \includegraphics[keepaspectratio, width=\linewidth]{fig3.png}
   \caption{Caption 2}
   \label{fig:3}
  \end{minipage}
 \end{tabular}
\end{figure}

Use the tabular environment like this.

If you want the characters to wrap around the figure, use the wrapfigure environment. This is useful when there are page restrictions such as abstruct. Please note that if you mix it with a normal figure, the output order may be incorrect. See below for details on options. http://www.yamamo10.jp/~yamamoto/comp/latex/make_doc/insert_fig/index.php#WRAPFIG

\begin{wrapfigure}{R}{0.5\hsize}
 \centering
 \includegraphics[keepaspectratio, width=\linewidth]{fig4.png}
 \caption{Caption 3}
 \label{fig:4}
\end{wrapfigure}

table

It is a table. If you draw all the ruled lines, it will be awkward, so leave it in moderation.

\begin{table}[ht]
  \centering
  \caption{caption}
  \begin{tabular}{c|ccc}
    \hline
    X & A & B & C\\
    \hline \hline
    1 & a & b & c \\
    2 & s & t & u \\
    3 & p & q & r \\
    \hline
  \end{tabular}
  \label{tab:1}
\end{table}

{c | ccc} is the setting of the number of items, left-right center alignment (l, r, c), and vertical ruled lines. Draw a horizontal ruled line with \ hline.

Cross-reference

If you put \ label {<appropriate character string>} in the figure or formula, you can output the figure number with \ ref {<the character string>}. Use cross-references instead of sticking by hand so that you can change the order while writing. Whether the label is a figure, a table, or a mathematical formula is automatically determined from the environment, but it is good to add fig, tab, etc. to the prefix so that the user can easily identify it. In addition, since the label position and number are written out in the first typeset and referenced by ref, two or more typesets are required. The number of pages may change depending on the table of contents and numbers, so it is safe to typeset 3 times if you want to be on the safe side [^ typeset].

Make chart numbers into chapters

Chart numbers are numbered serially in jsarticle, but if you want to reset each section, do as follows.

preamble


\makeatletter
%Reset the figure counter every time the section changes
\@addtoreset{figure}{section}
%Output the figure number to "<Chapter number>.<Figure number>To
\renewcommand{\thefigure}{\thesection.\arabic{figure}}
%
\@addtoreset{table}{section}
\renewcommand{\thetable}{\thesection.\arabic{table}}
\makeatother

Reference: [LaTeX] Chart formula numbers are serial numbers/divided by chapter

References

Bibliography environment or BibTeX is generally used for reference management. When using the bibliography environment

preamble


\usepackage{cite}
\begin{thebibliography}{99}
\bibitem{label1} hogehoge.
\bibitem{label2} fugafuga.
\end{thebibliography} 

Refer to it with \ cite {<label name>} as follows. It is possible to arrange two or more like \ cite {label1, label2} or add the number of pages etc. like \ cite [pp12--34] {label1}.

Embed hyperlinks in PDF

The hyperref package creates hyperlinks to cross-references, which is convenient for generating long PDFs with a single click. You can set the color of the link character string. (The default is red or green, so it's hard to see.)

preamble


\usepackage[dvipdfmx]{hyperref}
\usepackage{pxjahyper}
\hypersetup{
 setpagesize=false,
 bookmarksnumbered=true,
 bookmarksopen=true,
 colorlinks=true,
 linkcolor=black,
 citecolor=black,
}

Reference: LaTeX document with hyperlink

Reference of self-made counter

You can also cross-reference counters you define.

Create a counter named subscript and define the behavior when called.

preamble


\newcounter{subscript}
\setcounter{subscript}{0}
\renewcommand{\thesubscript}{\arabic{subscript}}
\newcommand{\subscript}{\refstepcounter{subscript}\thesubscript}
$$ T_{\subscript\label{sub:hoge}} = hoge $$
$$ T_{\subscript\label{sub:fuga}} = fuga $$
$$ T_{\subscript\label{sub:piyo}} = piyo $$

$T_{\ref{sub:fuga}}$Is fuga.

image.png

SI unit

preamble


\usepackage{siunitx}

Use like \ si {kg.m/s ^ 2}. ° is \ si {\ degree}, ℃ is \ si {\ degreeCelsius}, etc.

Also, in $ \ rm \ LaTeX $, you can print Å with \ AA, but this is" A with top ring "[^ AA], which is supposed to be used in a text environment, so use it in \ si. Then you will get a warning like LaTeX Warning: Command \ r invalid in math mode on input line XX. If you use \ angstrom, the warning will disappear.

[^ AA]: Symbols used in Norwegian and other languages. It's like a letter with an umlaut in German. More roughly, it's like a handakuon in Japanese?

reference: SI unit (International System of Units) --siunitx package macro command \r invalid

Chemical formula

Superscripts and subscripts can only be used in a mathematical environment, but since the element symbols are Roman, they have to be done like $ \ mathrm {H} _2 \ mathrm {O} $, which is very troublesome. It's easy to use the package.

preamble


\usepackage[version=3]{mhchem}

If you use \ ce {SrTiO3}, \ ce {HSO4-}, etc., superscripts, subscripts, etc. will be applied automatically (limited to one digit. Where to separate with SO42- etc." I can't decide, so I set the superscript and subscript myself). It makes Roman type even in the mathematical environment, and superscript ^ and subscript _ are effective even in the text environment.

In a permutation system containing variables such as $ \ mathrm {FeSe} _ {1-x} \ mathrm {Te} _ {x} $ If you do something like \ ce {FeSe_ {$ 1-x $} Te_ {$ x $}}, the minus of 1-x seems to be a hyphen, so$ \ ce {FeSe} _ {1-x It is better to use something like} \ ce {Te} _x $.

Reference: Chemical typesetting by TeX --TeX Alchemist Online

Check macro contents

How does this macro work? You may be worried. You can open and search for any latex.ltx in the $ \ rm \ LaTeX $ macro, but it's also a hassle to find if it's redefined or package-defined. To check the definition contents in the current environment, use \ show <token> to output the result of expanding the macro in the log.

For example, if you try with the \ AA mentioned above

> \AA=macro:
->\r A.
l.11 \show\AA
             
? 

Is output as. You can see that it is A with the accent symbol \ r. Tokens other than macros (for example, > alignment tab character & . in&) are also acceptable. There are also various debugging commands such as \ showthe that outputs register values ​​etc. (Omitted below. Reference: What you need to know before despair when debugging a TeX program (1) --Macro tweeter )))

Other

Break the bibliography

When writing [^ paper] references without using BibTeX

\begin{thebibliography}{99}
\bibitem{Josephson} B. D. Josephson, Phys. Lett. 1, 251-253 (1962).
\end{thebibliography}

You can do it like this, but if you leave it as it is, it will be text without any particular format [1] B. D. Josephson, Phys. Lett. 1, 251-253 (1962). It is written out like this.

When trying to fit the format of my field [1] B. D. Josephson, Phys. Lett. 1, 251-253 (1962). I want to make the magazine name italic and the volume number bold like this, but of course I write BD Josephson, \ textit {Phys. Lett.} \ Textbf {1}, 251-253 (1962) . every time. , Define a macro with \ newcommand {\ paper} [4] {# 1 \ textit {# 2} \ textbf {# 3} # 4} and \ paper {BD Josephson,} {Phys. Lett.,} {1,} {251-253 (1962).} It was troublesome to write parentheses [^ kakko], so I used \ def to reduce the number of inputs a little more.

In $ \ rm \ LaTeX $, you should basically use \ newcommand, but there are some situations where it is convenient to use \ def. One of the unique functions of \ def is that pattern matching can be used.

\def\paper#1;#2;#3;#4.{#1\textit{#2}\textbf{#3}#4.}

\paper B. D. Josephson,;Phys. Lett.,;1,;251-253 (1962).

Then, BD Josephson,, Phys. Lett.,, 1,, 251-253 (1962) are stored in # 1, # 2, # 3, and # 4, respectively, and expanded. .. It's convenient.

I think you shouldn't copy it too much because you have to write $ \ rm \ TeX $ (instead of $ \ rm \ LaTeX $) just to wear it sideways.

[^ paper]: Since many things are brought from PowerPoint in the past, it is easiest to bring a character string such as BD Josephson, Phys. Lett. 1, 251-253 (1962) .. It was.

[^ kakko]: I don't like brace because it requires Shift and it's hard to type because it's on the edge of the keyboard.

Python

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

I will use it without any introduction.

Graph

The goal is a graph like this.

image.png [Source: E. Snider, et al. "Room-temperature superconductivity in a carbonaceous sulfur hydride." Nature ** 586 **, 373–377 (2020).]

Scale setting

With the default settings, the scale is outward and there is no auxiliary scale, so it will be displayed.

plt.rcParams['font.family'] ='sans-serif' #Font selection
plt.rcParams['font.size'] = 12 #Font size
plt.rcParams["xtick.minor.visible"] = True #Addition of auxiliary scale
plt.rcParams["ytick.minor.visible"] = True
plt.gca().xaxis.set_tick_params(which='both', direction='in',bottom=True, top=True)
plt.gca().yaxis.set_tick_params(which='both', direction='in',left=True, right=True)

image.pngimage.png

Other setting items. Adjustment of the appearance of graphs in memorandum Matplotlib

Make the marker white

If you set markerfacecolor to"None", the marker will be only the border. If it is " white ", the back is not transparent. If you set marker edge color, you can draw with a color different from the line. In the case of the scatter plot plt.scatter, the argument names are edgecolors and facecolor, respectively.

plt.plot([0, 1, 2], [1, 0, 1], marker="o", markersize=10)
plt.plot([0, 1, 2], [0, 1, 2], marker="s", markerfacecolor="None", markersize=10)
plt.plot([0, 1, 2], [2, 1, 0], marker="^", markeredgecolor="C3", markerfacecolor="white", markersize=10)
plt.scatter([0, 1, 2], [0, 2, 1], marker="v", edgecolors="C4", facecolor='None', s=100)

matplotlib Graphing Tips (3) White Symbols and Arrows

Display legend outside the graph

plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", ncol=2)

matplotlib legend layout notes

image.png

Overlaid plot

When writing on top of the 2nd axis. It is quite troublesome to try to change the axis color according to the plot color.

fig = plt.figure()
ax1 = fig.subplots()

plt.rcParams['font.family'] ='sans-serif'
plt.rcParams['font.size'] = 10
plt.rcParams["xtick.minor.visible"] = True
plt.rcParams["ytick.minor.visible"] = True
ax1.xaxis.set_tick_params(which='both', direction='in',bottom=True, top=True)
#1-axis scale color change
ax1.yaxis.set_tick_params(which='both', direction='in',left=True, color="C0")
#Change the scale label color
ax1.tick_params(axis="y", colors="C0")

ax2 = ax1.twinx()
#2-axis scale color change
ax2.tick_params(axis="y", which='both', direction='in', right=True, color="C1")
#Change the scale label color
ax2.tick_params(axis='y', colors="C1")

#Border color change
ax2.spines['left'].set_color("C0") #ax2 is better"Up"Change ax2 because it is in
ax2.spines['right'].set_color("C1")

ax1.plot([0, 1, 2], [1, 0, 1], marker="o", markersize=10, color="C0")
ax2.plot([0, 1, 2], [0, 1, 2], marker="s", markerfacecolor="None", markersize=10, color="C1")

plt.show()

image.png

[Python] How to draw a graph with two axes on the left and right with matplotlib

When you want to plot multiple time series data vertically, and you want to draw two of them on top of each other on two axes, it looks like this.

fig = plt.figure(figsize=(8, 6))

plt.rcParams['font.family'] ='sans-serif' #Font selection
plt.rcParams['font.size'] = 10 #Font size
plt.rcParams["xtick.minor.visible"] = True #Addition of auxiliary scale
plt.rcParams["ytick.minor.visible"] = True
#plt.gca().xaxis.set_tick_params(which='both', direction='in',bottom=True, top=True)
#plt.gca().yaxis.set_tick_params(which='both', direction='in',left=True, right=True)

#Divide the screen into 4x1
ax1 = plt.subplot2grid((4,1), (0,0)) # (0,0)Draw on the screen
ax2 = plt.subplot2grid((4,1), (1,0)) # (1,0)Draw on the screen
ax3 = plt.subplot2grid((4,1), (2,0), rowspan=2)  # (2,0)Draw on the screen with two vertical punches from
ax4 = ax3.twinx() #Draw on top of ax3

ax1.xaxis.set_tick_params(which='both', direction='in', bottom=True, top=True, labelbottom=False)
ax1.yaxis.set_tick_params(which='both', direction='in', left=True, right=True)

ax2.xaxis.set_tick_params(which='both', direction='in', bottom=True, top=True, labelbottom=False)
ax2.yaxis.set_tick_params(which='both', direction='in', left=True, right=True)

ax3.xaxis.set_tick_params(which='both', direction='in', bottom=True, top=True)
ax3.yaxis.set_tick_params(which='both', direction='in', color="C2")
ax4.spines['left'].set_color("C2")

ax4.yaxis.set_tick_params(which='both', direction='in', color="C3")
ax4.tick_params(axis='y', colors="C3")
ax4.spines['right'].set_color("C3")


ax1.plot([0, 1, 2], [1, 0, 1], marker="o", color="C0", markersize=10, label="A")
ax1.set_ylabel("A")

ax2.plot([0, 1, 2], [0, 1, 2], marker="s", color="C1", markerfacecolor="None", markersize=10, label="B")
ax2.set_ylabel("B")

ax3.plot([0, 1, 2], [2, 1, 0], marker="^", color="C2", markerfacecolor="white", markersize=10, label="C")
ax3.tick_params(axis='y', colors="C2")
ax3.set_xlabel("x")
ax3.set_ylabel("C", color="C2")

ax4.scatter([0, 1, 2], [0, 2, 1], marker="v", edgecolors="C3", facecolor='None', s=100, label="D")
ax4.set_ylabel("D", color="C3")
ax4.set_ylim(-1,3)

plt.xlim(-0.2, 2.2)
ax1.set_xlim(*plt.xlim()) #ax1,Align the x-axis of ax2
ax2.set_xlim(*plt.xlim())

plt.show()

image.png

If you want to change the 2-axis to the x-axis, change twinx () to twiny ().

Smoothing

If you want to smooth the noise with a moving average, you can use np.convolve.

def gauss(x, a=1, mu=0, sigma=1):
    return a * np.exp(-(x - mu)**2 / (2*sigma**2))

x = np.array(sorted([np.random.rand()*6-3 for _ in range(500)]))
y = np.array([gauss(i)+np.random.randn()*0.05for i in x])

width = 7

plt.plot(x,y)
plt.plot(x, np.convolve(y, np.ones(width)/width, mode='same'), color="red")

image.png

In the case of time-series data, we cannot see future data, so we will shift it.

plt.plot(x,y)
plt.plot(x[width-1:], np.convolve(y, np.ones(width)/width, mode='valid'), color="red")

image.png

This pattern can also be written with the Pandas rolling function.

plt.plot(x, y)
plt.plot(x, pd.Series(y).rolling(11).mean(), color="red")

Exponential smoothing moving average can be done as well as Pandas.

plt.plot(x, y)
plt.plot(x, pd.Series(y).ewm(span=width).mean(), color="red")

For waveform data, there are various other things such as FFT. Smoothing of time series and waveform data (smoothing)

Curved fit

The parameter fit of the curve is performed by the least squares method.

from scipy.optimize import curve_fit
def gauss(x, a=1, mu=0, sigma=1):
    return a * np.exp(-(x - mu)**2 / (2*sigma**2))

x = np.array(sorted([np.random.rand()*6-3 for _ in range(500)]))
y = np.array([gauss(i, 1, 0, 1)+np.random.randn()*0.05for i in x])

popt, pcov = curve_fit(gauss, x, y)

If you give the curve_fit function" function with x as the first argument and the rest as parameters ", x, y, the optimal parameter and covariance matrix are returned.

Since the diagonal components of the covariance matrix are the variances of each parameter, the standard deviation can be obtained by taking the square root.

plt.plot(x,y)
plt.plot(np.linspace(-3,3,1000), gauss(np.linspace(-3,3,1000), *popt))
plt.show()

perr = np.sqrt(np.diag(pcov))
for i in range(3):
    print(f"{popt[i]:.3f}±{perr[i]:.3f}")
# 1.012±0.005
# 0.004±0.006
# 0.996±0.006

image.png

If you give the initial value and range of the parameter, you can fit a complicated function as it is.

def two_gauss(x, a1, m1, s1, a2, m2, s2, e):
    return gauss(x, a1, m1, s1) + gauss(x, a2, m2, s2) + e
y2 = np.array([two_gauss(i, 1.5, -1, 0.5, 1.2, 0.5, 0.8, 0.1) + np.random.rand()*0.1 for i in x])

p,q = curve_fit(two_gauss, x, y2, [2, -1.5, 0.5, 1.5, 1, 1, 0],
                bounds=((0, -np.inf, 0, 0, -np.inf, 0, 0), (np.inf, np.inf, np.inf, np.inf, np.inf, np.inf, np.inf)) )
plt.plot(x,y2)
plt.plot(x, two_gauss(x, *p))
plt.plot(x, gauss(x, p[0], p[1], p[2])+p[6])
plt.plot(x, gauss(x, p[3], p[4], p[5])+p[6])

image.png

Interpolate with a curve

If you can express it with an appropriate function, that's fine, but if you can't do that and just want to connect with an appropriate curve, you can connect with a spline.

from scipy.interpolate import make_interp_spline, BSpline
x = [0,1,2,3,4,5]
y = [0,3,5,6,6,5]

smooth = make_interp_spline(x, y)
plt.scatter(x, y)
plt.plot(np.linspace(0,5,100), smooth(np.linspace(0,5,100)), color="black", linewidth=0.5)

make_interp_spline (x, y) creates a function that represents a B-spline curve with x and y as control points, so you can draw a curve by plotting with an appropriate x value.

image.png

There are various types of interpolation using other curves. Various interpolation methods using Scipy.interpolate

DataFrame operations

When measuring resistance while changing the temperature and plotting R-T, it is annoying because the speed is not fixed when the temperature drops. A code that trims only during the temperature rise period in such a case.

df = pd.read_csv("data.csv")
df = df.iloc[1:, :] #If there is a line in the second unit, it cannot be floated, so delete it.
df = df.astype('float64')

cond = df.index>=df["Temperature"].idxmin()
plt.plot(df[cond]["Temperature"], df[cond]["Resistance"])

Trim conditions can be connected with & and |. (Because it is an array operation of boolean values, it is not a bool operation but a bit operation)

#Variations can be taken with diff
cond = (df.index>=df["Temperature"].idxmin()) & (df["Temperature"].diff() > 0.02)

cond = (df.index>=df["Temperature"].idxmin()) | ((df["Time"] > 100) & (df["Time"]<2000))

Extraction of horizontal part

I want to get the value of y in the horizontal part.

width = 0.01
z = plt.hist(y, bins=np.arange(0, 40, width)-width/2)
plt.ylim(0,50)

threshold=300
print((z[1][:-1]+width/2)[z[0]>threshold])
# [ 2.5  5.  10.  15.  20.  25.  30.  33.  35.  35.5 36.  36.5 37.  37.5]

It will be nice to change width and threshold appropriately.

image.png

Recommended Posts

LaTeX, Python tips in master's thesis
python tips
Python Tips
Python tips
Display LaTeX notation formulas in Python, matplotlib
Tips for dealing with binaries in Python
Tips for making small tools in python
Python Conda Tips
Quadtree in Python --2
Python in optimization
CURL in python
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
SendKeys in Python
Meta-analysis in Python
Unittest in python
Python debugging tips
Epoch in Python
Discord in Python
Python click tips
Sudoku in Python
DCI in Python
quicksort in python
nCr in python
Unexpectedly (?) Python tips
N-Gram in Python
Programming in python
Plink in Python
Constant in python
Lifegame in Python.
FizzBuzz in Python
Sqlite in python
StepAIC in Python
N-gram in python
LINE-Bot [0] in Python
Csv in python
Disassemble in Python
Reflection in Python
Constant in python
nCr in Python.
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python
Quad-tree in Python
Reflection in Python
Chemistry in Python
Hashable in python
DirectLiNGAM in Python
LiNGAM in Python
Flatten in python
flatten in python
[Tips] Easy-to-read writing when connecting functions in Python
Tips for hitting the ATND API in Python
Sorted list in Python
Clustering text in Python
Daily AtCoder # 2 in Python
Implement Enigma in python
Daily AtCoder # 6 in Python