Skip to content
Snippets Groups Projects
Commit a4e1e525 authored by Mikhail Karnevskiy's avatar Mikhail Karnevskiy
Browse files

Use template. Optimise imports.

parent efcfe680
No related branches found
No related tags found
1 merge request!68Add title page. Modify conf.py.
import argparse
from collections import OrderedDict
import copy
import glob
from jinja2 import Template
import os import os
from os.path import isfile, isdir, splitext from os.path import isfile, isdir, splitext
from time import sleep
from subprocess import check_output, check_call, CalledProcessError
from shutil import copy, move, rmtree, copytree
from queue import Queue from queue import Queue
import re from collections import OrderedDict
import shutil import glob
from subprocess import Popen, PIPE, check_output, check_call from jinja2 import Template
import textwrap import textwrap
from time import sleep import tabulate
import time from importlib.machinery import SourceFileLoader
from uuid import uuid4 from xfel_calibrate import settings
def atoi(text): def atoi(text):
''' '''
...@@ -72,7 +69,7 @@ def combine_report(run_path, calibration): ...@@ -72,7 +69,7 @@ def combine_report(run_path, calibration):
gfile.write("\n\n") gfile.write("\n\n")
if isdir("{}/{}".format(run_path, entry)): if isdir("{}/{}".format(run_path, entry)):
shutil.copytree("{}/{}".format(run_path, entry), "{}/{}".format(sphinx_path, entry)) copytree("{}/{}".format(run_path, entry), "{}/{}".format(sphinx_path, entry))
return sphinx_path return sphinx_path
...@@ -154,7 +151,7 @@ def make_timing_summary(run_path, joblist): ...@@ -154,7 +151,7 @@ def make_timing_summary(run_path, joblist):
{{ line }} {{ line }}
{%- endfor %} {%- endfor %}
''') ''')
import tabulate
with open("{}/timing_summary.rst".format(run_path), "w+") as gfile: with open("{}/timing_summary.rst".format(run_path), "w+") as gfile:
table = tabulate.tabulate(pars_vals, tablefmt='latex', table = tabulate.tabulate(pars_vals, tablefmt='latex',
...@@ -162,36 +159,48 @@ def make_timing_summary(run_path, joblist): ...@@ -162,36 +159,48 @@ def make_timing_summary(run_path, joblist):
gfile.write(textwrap.dedent(tmpl.render(table=table.split('\n')))) gfile.write(textwrap.dedent(tmpl.render(table=table.split('\n'))))
def make_report(run_path, tmp_path, out_path, project, author, version, report_to): def make_report(run_path, tmp_path, out_path, project, author, version,
report_to):
"""
Create calibration report (pdf file)
Automatically generated report document results, produced by
jupyter-notebooks.
:param run_path: Path to sphinx run directory
:param tmp_path: Run path of the slurm job
:param out_path: Output directory for report.
Overwritten if path to report is given in `report_to`
:param project: Project title
:param author: Author of the notebook
:param version: Version of the notebook
:param report_to: Name or path of the report file
"""
run_path = os.path.abspath(run_path) run_path = os.path.abspath(run_path)
report_path, report_name = os.path.split(report_to) report_path, report_name = os.path.split(report_to)
if report_path != '': if report_path != '':
out_path = report_path out_path = report_path
try: try:
import subprocess check_call(["sphinx-quickstart",
subprocess.check_call(["sphinx-quickstart", "--quiet",
"--quiet", "--project='{}'".format(project),
"--project='{}'".format(project), "--author='{}'".format(author),
"--author='{}'".format(author), "-v", str(version),
"-v", str(version), "--suffix=.rst",
"--suffix=.rst", "--master=index",
"--master=index", "--ext-intersphinx",
"--ext-intersphinx", "--ext-mathjax",
"--ext-mathjax", "--makefile",
"--makefile", "--no-batchfile", run_path])
"--no-batchfile", run_path])
except CalledProcessError:
except subprocess.CalledProcessError:
raise Exception("Failed to run sphinx-quickbuild. Is sphinx installed?" raise Exception("Failed to run sphinx-quickbuild. Is sphinx installed?"
"Generated simple index.rst instead") "Generated simple index.rst instead")
# quickbuild went well we need to edit the index.rst and conf.py files # quickbuild went well we need to edit the index.rst and conf.py files
from shutil import move
module_path = "{}".format(os.path.abspath(os.path.dirname(__file__))) module_path = "{}".format(os.path.abspath(os.path.dirname(__file__)))
from importlib.machinery import SourceFileLoader
conf = SourceFileLoader("conf", conf = SourceFileLoader("conf",
"{}/conf.py".format(run_path)).load_module() "{}/conf.py".format(run_path)).load_module()
l_var = [v for v in dir(conf) if not v.startswith('__')] l_var = [v for v in dir(conf) if not v.startswith('__')]
...@@ -200,7 +209,8 @@ def make_report(run_path, tmp_path, out_path, project, author, version, report_t ...@@ -200,7 +209,8 @@ def make_report(run_path, tmp_path, out_path, project, author, version, report_t
latex_elements = {'extraclassoptions': ',openany, oneside', latex_elements = {'extraclassoptions': ',openany, oneside',
'maketitle': r'\input{titlepage.tex.txt}'} 'maketitle': r'\input{titlepage.tex.txt}'}
mf.write("latex_elements = {}\n".format(latex_elements)) mf.write("latex_elements = {}\n".format(latex_elements))
mf.write("latex_logo = '{}/xfel.pdf'\n".format(module_path)) mf.write("latex_logo = '{}/{}'\n".format(module_path,
settings.logo_path))
mf.write("latex_additional_files = ['titlepage.tex.txt']\n") mf.write("latex_additional_files = ['titlepage.tex.txt']\n")
for var in l_var: for var in l_var:
...@@ -208,12 +218,13 @@ def make_report(run_path, tmp_path, out_path, project, author, version, report_t ...@@ -208,12 +218,13 @@ def make_report(run_path, tmp_path, out_path, project, author, version, report_t
'latex_additional_files']: 'latex_additional_files']:
continue continue
tmpl = '{} = {}\n' tmpl = '{} = {}\n'
if isinstance(getattr(conf, var, "None"), str): v = getattr(conf, var, None)
if isinstance(v, str):
print(var, v)
tmpl = '{} = "{}"\n' tmpl = '{} = "{}"\n'
mf.write(tmpl.format(var, getattr(conf, var, "None"))) mf.write(tmpl.format(var, v))
_ = os.getcwd()
os.remove("{}/conf.py".format(run_path)) os.remove("{}/conf.py".format(run_path))
move("{}/conf.py.tmp".format(run_path), "{}/conf.py".format(run_path)) move("{}/conf.py.tmp".format(run_path), "{}/conf.py".format(run_path))
...@@ -221,7 +232,7 @@ def make_report(run_path, tmp_path, out_path, project, author, version, report_t ...@@ -221,7 +232,7 @@ def make_report(run_path, tmp_path, out_path, project, author, version, report_t
files_to_handle = [] files_to_handle = []
for entry in direntries: for entry in direntries:
if isfile("{}/{}".format(run_path, entry)): if isfile("{}/{}".format(run_path, entry)):
name, ext = splitext("{}".format(entry)) name, ext = splitext("{}".format(entry))
if ext == ".rst" and "index" not in name: if ext == ".rst" and "index" not in name:
files_to_handle.append(name.strip()) files_to_handle.append(name.strip())
...@@ -242,45 +253,36 @@ def make_report(run_path, tmp_path, out_path, project, author, version, report_t ...@@ -242,45 +253,36 @@ def make_report(run_path, tmp_path, out_path, project, author, version, report_t
# finally call the make scripts # finally call the make scripts
os.chdir(run_path) os.chdir(run_path)
try: try:
import subprocess check_call(["make", "latexpdf"])
subprocess.check_call(["make", "latexpdf"])
except subprocess.CalledProcessError: except CalledProcessError:
print("Failed to make pdf documentation") print("Failed to make pdf documentation")
print("Temp files will not be deleted and "+ print("Temp files will not be deleted and " +
"can be inspected at: {}".format(run_path)) "can be inspected at: {}".format(run_path))
return return
print("Moving report to final location: {}".format(out_path)) print("Moving report to final location: {}".format(out_path))
for f in glob.glob(r'{}/_build/latex/*.pdf'.format(run_path)): for f in glob.glob(r'{}/_build/latex/*.pdf'.format(run_path)):
print(f) print(f)
shutil.copy(f, out_path) copy(f, out_path)
print("Removing temporary files at: {}".format(tmp_path)) print("Removing temporary files at: {}".format(tmp_path))
shutil.rmtree(tmp_path) rmtree(tmp_path)
def make_titlepage(sphinx_path, project, data_path): def make_titlepage(sphinx_path, project, data_path):
with open("{}/titlepage.tex.txt".format(sphinx_path), "w+") as gfile: """
gfile.write('\\begin{titlepage}\n') Create title page for report using template
gfile.write(' \\centering\n')
gfile.write(' \\vspace*{40mm}\n') :param sphinx_path: path to sphinx run directory
gfile.write(' \\textbf{\\Huge {') :param project: title of the project
gfile.write(project) :param data_path: path to input data sample used for notebook
gfile.write('}}\n') """
gfile.write(' \\vspace{0mm}\n\n') module_path = "{}".format(os.path.abspath(os.path.dirname(__file__)))
gfile.write(' \\begin{figure}[!h]\n') with open('{}/titlepage.tmpl'.format(module_path)) as file_:
gfile.write(' \\centering\n') title_tmp = Template(file_.read())
gfile.write(' \\includegraphics[scale=0.3]{xfel.pdf}\n')
gfile.write(' \\end{figure}\n\n') with open("{}/titlepage.tex.txt".format(sphinx_path), "w+") as mf:
gfile.write(' \\vspace{0mm}\n') mf.write(textwrap.dedent(title_tmp.render(project=project,
gfile.write(' \\Large \\textbf{{Detector group}}\n\n') data_path=data_path)))
gfile.write(' Based on data sample: {}\n\n'.format(data_path))
gfile.write(' Release : 0.1\n\n')
gfile.write(' \\vspace*{0mm}\n')
gfile.write(' \\today\n')
gfile.write(' \\vfill\n')
gfile.write(' \\textit{For internal use only}\n')
gfile.write('\\end{titlepage}\n')
gfile.write("\n\n")
def finalize(joblist, finaljob, run_path, out_path, project, calibration, def finalize(joblist, finaljob, run_path, out_path, project, calibration,
......
...@@ -24,6 +24,9 @@ report_path = "{}/calibration_reports/".format(os.getcwd()) ...@@ -24,6 +24,9 @@ report_path = "{}/calibration_reports/".format(os.getcwd())
# Also try to output the report to an out_folder defined by the notebook # Also try to output the report to an out_folder defined by the notebook
try_report_to_output = True try_report_to_output = True
# logo file for calibration report (located in cal_tools/cal_tools)
logo_path = "xfel.pdf"
# the command to run this concurrently. It is prepended to the actual call # the command to run this concurrently. It is prepended to the actual call
sprof = os.environ.get("XFELCALSLURM", "exfel") sprof = os.environ.get("XFELCALSLURM", "exfel")
launcher_command = "sbatch -t 24:00:00 --mem 500G --requeue --output {temp_path}/slurm-%j.out" launcher_command = "sbatch -t 24:00:00 --mem 500G --requeue --output {temp_path}/slurm-%j.out"
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment