Last active
April 29, 2022 00:00
-
-
Save JayGwod/fcd480a000e49942a7f2798a927d9c67 to your computer and use it in GitHub Desktop.
[Useful packages and matplotlib preamble]Here is a full #notebook preamble with some options to make the plots more publication ready.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""This preprocessor replaces bibliography code in markdowncell | |
""" | |
#----------------------------------------------------------------------------- | |
# Copyright (c) 2015, Julius Schulz | |
# | |
# Distributed under the terms of the Modified BSD License. | |
# | |
#----------------------------------------------------------------------------- | |
from nbconvert.preprocessors import * | |
import re | |
import os | |
import sys | |
class BibTexPreprocessor(Preprocessor): | |
def create_bibentry(self, refkey, reference): | |
entry = "@article{" + refkey + ",\n" | |
entry += " author = {" | |
entry += " and ".join(map(lambda a: a["family"] + ", " + a["given"], reference["author"])) | |
entry += "}, \n" | |
if ("title" in reference): | |
entry += " title = {" + reference["title"] + "}, \n" | |
if ("issued" in reference): | |
entry += " year = {" + reference["issued"]["year"] + "}, \n" | |
if ("container-title" in reference): | |
entry += " journal = {" + reference["container-title"] + "}, \n" | |
if ("page" in reference): | |
entry += " pages = {" + re.sub("-", "--", reference["page"]) + "}, \n" | |
if ("volume" in reference): | |
entry += " volume = {" + reference["volume"] + "}, \n" | |
if ("issue" in reference): | |
entry += " issue = {" + reference["issue"] + "}, \n" | |
if ("DOI" in reference): | |
entry += " doi = {" + reference["DOI"] + "}, \n" | |
if ("URL" in reference): | |
entry += " url = {" + reference["URL"] + "}, \n" | |
entry += "}\n" | |
entry += "\n" | |
return entry | |
def create_bibfile(self, filename): | |
if not os.path.exists(os.path.dirname(filename)): | |
os.makedirs(os.path.dirname(filename)) | |
f = open(filename, "w") | |
for r in self.references: | |
if (sys.version_info > (3, 0)): | |
f.write(self.create_bibentry(r, self.references[r])) | |
else: | |
f.write(self.create_bibentry(r, self.references[r]).encode('utf-8')) | |
f.close() | |
def preprocess(self, nb, resources): | |
try: | |
self.references = nb["metadata"]["cite2c"]["citations"] | |
self.create_bibfile(resources["output_files_dir"]+"/"+resources["unique_key"]+".bib") | |
except: | |
print("Did not find cite2c") | |
for index, cell in enumerate(nb.cells): | |
nb.cells[index], resources = self.preprocess_cell(cell, resources, index) | |
return nb, resources | |
def preprocess_cell(self, cell, resources, index): | |
""" | |
Preprocess cell | |
Parameters | |
---------- | |
cell : NotebookNode cell | |
Notebook cell being processed | |
resources : dictionary | |
Additional resources used in the conversion process. Allows | |
preprocessors to pass variables into the Jinja engine. | |
cell_index : int | |
Index of the cell being processed (see base.py) | |
""" | |
if cell.cell_type == "markdown": | |
if "<div class=\"cite2c-biblio\"></div>" in cell.source: | |
replaced = re.sub("<div class=\"cite2c-biblio\"></div>", r"\\bibliography{"+resources["output_files_dir"]+"/"+resources["unique_key"]+r"} \n ", cell.source) | |
cell.source = replaced | |
return cell, resources |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
c = get_config() | |
c.Exporter.preprocessors = [ 'bibpreprocessor.BibTexPreprocessor', 'pre_pymarkdown.PyMarkdownPreprocessor' ] | |
c.Exporter.template_file = 'revtex_nocode.tplx' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"latex_metadata": { | |
"title": "Amazing Article", | |
"author": "Julius C. F. Schulz", | |
"affiliation": "Freie Universit\\\"at Berlin, Fachbereich Physik, 14195 Berlin, Germany" | |
}, | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
"""Nbconvert preprocessor for the python-markdown nbextension.""" | |
import re | |
from nbconvert.preprocessors import Preprocessor | |
class PyMarkdownPreprocessor(Preprocessor): | |
""" | |
:mod:`nbconvert` Preprocessor for the python-markdown nbextension. | |
This :class:`~nbconvert.preprocessors.Preprocessor` replaces kernel code in | |
markdown cells with the results stored in the cell metadata. | |
""" | |
def replace_variables(self, source, variables): | |
""" | |
Replace {{variablename}} with stored value | |
""" | |
try: | |
replaced = re.sub( | |
"{{(.*?)}}", lambda m: variables.get(m.group(1), ''), source) | |
except TypeError: | |
replaced = source | |
return replaced | |
def preprocess_cell(self, cell, resources, index): | |
""" | |
Preprocess cell | |
Parameters | |
---------- | |
cell : NotebookNode cell | |
Notebook cell being processed | |
resources : dictionary | |
Additional resources used in the conversion process. Allows | |
preprocessors to pass variables into the Jinja engine. | |
cell_index : int | |
Index of the cell being processed (see base.py) | |
""" | |
if cell.cell_type == "markdown": | |
if hasattr(cell['metadata'], 'variables'): | |
variables = cell['metadata']['variables'] | |
if len(variables) > 0: | |
cell.source = self.replace_variables( | |
cell.source, variables) | |
return cell, resources |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# class PrettyTable | |
class PrettyTable(list): | |
""" Overridden list class which takes a 2-dimensional list of | |
the form [[1,2,3],[4,5,6]], and renders HTML and LaTeX Table in | |
IPython Notebook. For LaTeX export two styles can be chosen.""" | |
def __init__(self, initlist=[], extra_header=None, print_latex_longtable=True): | |
self.print_latex_longtable = print_latex_longtable | |
if extra_header is not None: | |
if len(initlist[0]) != len(extra_header): | |
raise ValueError("Header list must have same length as data has columns.") | |
initlist = [extra_header]+list(initlist) | |
super(PrettyTable, self).__init__(initlist) | |
def latex_table_tabular(self): | |
latex = ["\\begin{tabular}"] | |
latex.append("{"+"|".join((["l"]*len(self[0])))+"}\n") | |
for row in self: | |
latex.append(" & ".join(map(format, row))) | |
latex.append("\\\\ \n") | |
latex.append("\\end{tabular}") | |
return ''.join(latex) | |
def latex_longtable(self): | |
latex = ["\\begin{longtable}[c]{@{}"] | |
latex.append("".join((["l"]*len(self[0])))) | |
latex.append("@{}}\n") | |
latex.append("\\toprule\\addlinespace\n") | |
first = True | |
for row in self: | |
latex.append(" & ".join(map(format, row))) | |
latex.append("\\\\\\addlinespace \n") | |
if first: | |
latex.append("\\midrule\\endhead\n") | |
first = False | |
latex.append("\\bottomrule \n \\end{longtable}") | |
return ''.join(latex) | |
def _repr_html_(self): | |
html = ["<table>"] | |
for row in self: | |
html.append("<tr>") | |
for col in row: | |
html.append("<td>{0}</td>".format(col)) | |
html.append("</tr>") | |
html.append("</table>") | |
return ''.join(html) | |
def _repr_latex_(self): | |
if self.print_latex_longtable: | |
return self.latex_longtable() | |
else: | |
return self.latex_table_tabular() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
((*- extends 'article.tplx' -*)) | |
((* block docclass *)) | |
\documentclass[reprint, floatfix, groupaddress, prb]{revtex4-1} | |
\usepackage{placeins} | |
\AtBeginDocument{ | |
\heavyrulewidth=.08em | |
\lightrulewidth=.05em | |
\cmidrulewidth=.03em | |
\belowrulesep=.65ex | |
\belowbottomsep=0pt | |
\aboverulesep=.4ex | |
\abovetopsep=0pt | |
\cmidrulesep=\doublerulesep | |
\cmidrulekern=.5em | |
\defaultaddspace=.5em | |
} | |
((* endblock docclass *)) | |
% Author and Title from metadata | |
((* block maketitle *)) | |
((*- if nb.metadata["latex_metadata"]: -*)) | |
((*- if nb.metadata["latex_metadata"]["author"]: -*)) | |
\author{((( nb.metadata["latex_metadata"]["author"] )))} | |
((*- endif *)) | |
((*- else -*)) | |
\author{Julius C. F. Schulz} | |
((*- endif *)) | |
((*- if nb.metadata["latex_metadata"]: -*)) | |
((*- if nb.metadata["latex_metadata"]["affiliation"]: -*)) | |
\affiliation{((( nb.metadata["latex_metadata"]["affiliation"] )))} | |
((*- endif *)) | |
((*- endif *)) | |
((*- if nb.metadata["latex_metadata"]: -*)) | |
((*- if nb.metadata["latex_metadata"]["title"]: -*)) | |
\title{((( nb.metadata["latex_metadata"]["title"] )))} | |
((*- endif *)) | |
((*- else -*)) | |
\title{((( resources.metadata.name )))} | |
((*- endif *)) | |
\date{\today} | |
\maketitle | |
((* endblock maketitle *)) | |
% New mechanism for rendering figures with captions | |
((*- block data_png -*)) | |
((*- if cell.metadata.widefigure: -*)) | |
((( draw_widefigure_with_caption(output.metadata.filenames['image/png'], cell.metadata.caption, cell.metadata.label) ))) | |
((*- else -*)) | |
((*- if cell.metadata.caption: -*)) | |
((*- if cell.metadata.label: -*)) | |
((( draw_figure_with_caption(output.metadata.filenames['image/png'], cell.metadata.caption, cell.metadata.label) ))) | |
((*- else -*)) | |
((( draw_figure_with_caption(output.metadata.filenames['image/png'], cell.metadata.caption, "") ))) | |
((*- endif *)) | |
((*- else -*)) | |
((( draw_figure_with_caption(output.metadata.filenames['image/png'], "") ))) | |
((*- endif *)) | |
((*- endif *)) | |
((*- endblock -*)) | |
((*- block data_jpg -*)) | |
((*- if cell.metadata.caption: -*)) | |
((*- if cell.metadata.label: -*)) | |
((( draw_figure_with_caption(output.metadata.filenames['image/jpeg'], cell.metadata.caption, cell.metadata.label) ))) | |
((*- else -*)) | |
((( draw_figure_with_caption(output.metadata.filenames['image/jpeg'], cell.metadata.caption, "") ))) | |
((*- endif *)) | |
((*- else -*)) | |
((( draw_figure_with_caption(output.metadata.filenames['image/jpeg'], "") ))) | |
((*- endif *)) | |
((*- endblock -*)) | |
((*- block data_svg -*)) | |
((*- if cell.metadata.caption: -*)) | |
((*- if cell.metadata.label: -*)) | |
((( draw_figure_with_caption(output.metadata.filenames['image/svg+xml'], cell.metadata.caption, cell.metadata.label) ))) | |
((*- else -*)) | |
((( draw_figure_with_caption(output.metadata.filenames['image/svg+xml'], cell.metadata.caption, "") ))) | |
((*- endif *)) | |
((*- else -*)) | |
((( draw_figure_with_caption(output.metadata.filenames['image/svg+xml'], "") ))) | |
((*- endif *)) | |
((*- endblock -*)) | |
((*- block data_pdf -*)) | |
((*- if cell.metadata.widefigure: -*)) | |
((( draw_widefigure_with_caption(output.metadata.filenames['application/pdf'], cell.metadata.caption, cell.metadata.label) ))) | |
((*- else -*)) | |
((*- if cell.metadata.caption: -*)) | |
((*- if cell.metadata.label: -*)) | |
((( draw_figure_with_caption(output.metadata.filenames['application/pdf'], cell.metadata.caption, cell.metadata.label) ))) | |
((*- else -*)) | |
((( draw_figure_with_caption(output.metadata.filenames['application/pdf'], cell.metadata.caption, "") ))) | |
((*- endif *)) | |
((*- else -*)) | |
((( draw_figure_with_caption(output.metadata.filenames['application/pdf'], "") ))) | |
((*- endif *)) | |
((*- endif *)) | |
((*- endblock -*)) | |
% Draw a figure using the graphicx package. | |
((* macro draw_figure_with_caption(filename, caption, label) -*)) | |
((* set filename = filename | posix_path *)) | |
((*- block figure scoped -*)) | |
\begin{figure} | |
\begin{center}\adjustimage{max size={0.9\linewidth}{0.4\paperheight}}{((( filename )))}\end{center} | |
\caption{((( caption )))} | |
\label{((( label )))} | |
\end{figure} | |
((*- endblock figure -*)) | |
((*- endmacro *)) | |
% Draw a figure using the graphicx package. | |
((* macro draw_widefigure_with_caption(filename, caption, label) -*)) | |
((* set filename = filename | posix_path *)) | |
((*- block figure_wide scoped -*)) | |
\begin{figure*} | |
\begin{center}\adjustimage{max size={0.9\linewidth}{0.4\paperheight}}{((( filename )))}\end{center} | |
\caption{((( caption )))} | |
\label{((( label )))} | |
\end{figure*} | |
((*- endblock figure_wide -*)) | |
((*- endmacro *)) | |
% Disable input cells | |
((* block input_group *)) | |
((* endblock input_group *)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# load libraries and set plot parameters | |
import numpy as np | |
import prettytable as pt | |
import matplotlib.pyplot as plt | |
%matplotlib inline | |
from IPython.display import set_matplotlib_formats | |
set_matplotlib_formats('pdf', 'png') | |
plt.rcParams['savefig.dpi'] = 75 | |
plt.rcParams['figure.autolayout'] = False | |
plt.rcParams['figure.figsize'] = 10, 6 | |
plt.rcParams['axes.labelsize'] = 18 | |
plt.rcParams['axes.titlesize'] = 20 | |
plt.rcParams['font.size'] = 16 | |
plt.rcParams['lines.linewidth'] = 2.0 | |
plt.rcParams['lines.markersize'] = 8 | |
plt.rcParams['legend.fontsize'] = 14 | |
plt.rcParams['text.usetex'] = True | |
plt.rcParams['font.family'] = "serif" | |
plt.rcParams['font.serif'] = "cm" | |
plt.rcParams['text.latex.preamble'] = r"\usepackage{subdepth}, \usepackage{type1cm}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment