Snakefile 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. # -*- coding: utf-8; -*-
  2. import locale
  3. import os.path
  4. import regex
  5. import urllib.parse
  6. import os.path
  7. import bibtexparser
  8. import pypandoc
  9. from collections.abc import Iterable, Mapping
  10. from distutils.spawn import find_executable
  11. from fnmatch import fnmatch
  12. from subprocess import check_output, check_call
  13. from tempfile import NamedTemporaryFile
  14. from bibtexparser.bibdatabase import BibDatabase
  15. from lxml import html
  16. from snakemake.utils import min_version
  17. min_version('3.7.1')
  18. try:
  19. from os import scandir, walk
  20. except ImportError:
  21. from scandir import scandir, walk
  22. def unnest(*args):
  23. '''Un-nest list- and tuple-like elements in arguments.
  24. "List-like" means anything with a len() and whose elments can be
  25. accessed with numeric indexing, except for string-like elements. It
  26. must also be an instance of the collections.Iterable abstract class.
  27. Dict-like elements and iterators/generators are not affected.
  28. This function always returns a list, even if it is passed a single
  29. scalar argument.
  30. '''
  31. result = []
  32. for arg in args:
  33. if isinstance(arg, str):
  34. # String
  35. result.append(arg)
  36. elif isinstance(arg, Mapping):
  37. # Dict-like
  38. result.append(arg)
  39. elif isinstance(arg, Iterable):
  40. try:
  41. # Duck-typing test for list-ness (a stricter condition
  42. # than just "iterable")
  43. for i in range(len(arg)):
  44. result.append(arg[i])
  45. except TypeError:
  46. # Iterable but not list-like
  47. result.append(arg)
  48. else:
  49. # Not iterable
  50. result.append(arg)
  51. return result
  52. def check_output_decode(*args, encoding=locale.getpreferredencoding(), **kwargs):
  53. '''Shortcut for check.output + str.decode'''
  54. return check_output(*args, **kwargs).decode(encoding)
  55. def find_mac_app(name):
  56. try:
  57. result = \
  58. check_output_decode(
  59. ['mdfind',
  60. 'kMDItemDisplayName=={name}.app&&kMDItemKind==Application'.format(name=name)]).split('\n')[0] or \
  61. check_output_decode(
  62. ['mdfind',
  63. 'kMDItemDisplayName=={name}&&kMDItemKind==Application'.format(name=name)]).split('\n')[0]
  64. if result:
  65. return result
  66. else:
  67. raise Exception("Not found")
  68. except Exception:
  69. return None
  70. def find_lyx():
  71. lyx_finders = [
  72. lambda: find_executable('lyx'),
  73. lambda: os.path.join(find_mac_app('LyX'), 'Contents/MacOS/lyx'),
  74. lambda: '/Applications/Lyx.app/Contents/MacOS/lyx',
  75. ]
  76. for finder in lyx_finders:
  77. try:
  78. lyxpath = finder()
  79. if not lyxpath:
  80. continue
  81. elif not os.access(lyxpath, os.X_OK):
  82. continue
  83. else:
  84. return lyxpath
  85. except Exception:
  86. pass
  87. else:
  88. # Fallback which will just trigger an error when run (we don't
  89. # want to trigger an error now, while building the rules)
  90. return '/bin/false'
  91. LYX_PATH = find_lyx()
  92. PDFINFO_PATH = find_executable('pdfinfo')
  93. def glob_recursive(pattern, top='.', include_hidden=False, *args, **kwargs):
  94. '''Combination of glob.glob and os.walk.
  95. Reutrns the relative path to every file or directory matching the
  96. pattern anywhere in the specified directory hierarchy. Defaults to the
  97. current working directory. Any additional arguments are passed to
  98. os.walk.'''
  99. for (path, dirs, files) in walk(top, *args, **kwargs):
  100. for f in dirs + files:
  101. if include_hidden or f.startswith('.'):
  102. continue
  103. if fnmatch(f, pattern):
  104. yield os.path.normpath(os.path.join(path, f))
  105. def rsync_list_files(*paths, extra_rsync_args=(), include_dirs=False):
  106. '''Iterate over the files in path that rsync would copy.
  107. By default, only files are listed, not directories, since doit doesn't
  108. like dependencies on directories because it can't hash them.
  109. This uses "rsync --list-only" to make rsync directly indicate which
  110. files it would copy, so any exclusion/inclusion rules are taken into
  111. account.
  112. '''
  113. rsync_list_cmd = [ 'rsync', '-r', '--list-only' ] + unnest(extra_rsync_args) + unnest(paths) + [ '.' ]
  114. rsync_out = check_output_decode(rsync_list_cmd).splitlines()
  115. for line in rsync_out:
  116. s = regex.search('^(-|d)(?:\S+\s+){4}(.*)', line)
  117. if s is not None:
  118. if include_dirs or s.group(1) == '-':
  119. yield s.group(2)
  120. def lyx_input_deps(lyxfile):
  121. '''Return an iterator over all tex files included by a Lyx file.'''
  122. try:
  123. with open(lyxfile) as f:
  124. lyx_text = f.read()
  125. for m in regex.finditer('\\\\(?:input|loadglsentries){(.*?[.]tex)}', lyx_text):
  126. yield m.group(1)
  127. except FileNotFoundError:
  128. pass
  129. def lyx_bib_deps(lyxfile):
  130. '''Return an iterator over all bib files referenced by a Lyx file.
  131. This will only return the names of existing files, so it will be
  132. unreliable in the case of an auto-generated bib file.
  133. '''
  134. try:
  135. with open(lyxfile) as f:
  136. lyx_text = f.read()
  137. bib_names = regex.search('bibfiles "(.*?)"', lyx_text).group(1).split(',')
  138. # Unfortunately LyX doesn't indicate which bib names refer to
  139. # files in the current directory and which don't. Currently that's
  140. # not a problem for me since all my refs are in bib files in the
  141. # current directory.
  142. for bn in bib_names:
  143. bib_path = bn + '.bib'
  144. yield bib_path
  145. except FileNotFoundError:
  146. pass
  147. def lyx_gfx_deps(lyxfile):
  148. '''Return an iterator over all graphics files included by a LyX file.'''
  149. try:
  150. with open(lyxfile) as f:
  151. lyx_text = f.read()
  152. for m in regex.finditer('\\\\begin_inset Graphics\\s+filename (.*?)$', lyx_text, regex.MULTILINE):
  153. yield m.group(1)
  154. except FileNotFoundError:
  155. pass
  156. def lyx_hrefs(lyxfile):
  157. '''Return an iterator over hrefs in a LyX file.'''
  158. try:
  159. pattern = '''
  160. (?xsm)
  161. ^ LatexCommand \\s+ href \\s* \\n
  162. (?: name \\b [^\\n]+ \\n )?
  163. target \\s+ "(.*?)" $
  164. '''
  165. with open(lyxfile) as f:
  166. return (urllib.parse.unquote(m.group(1)) for m in
  167. re.finditer(pattern, f.read()))
  168. except FileNotFoundError:
  169. pass
  170. def tex_gfx_extensions(tex_format = 'xetex'):
  171. '''Return the ordered list of graphics extensions.
  172. This yields the list of extensions that TeX will try for an
  173. \\includegraphics path.
  174. '''
  175. try:
  176. cmdout = check_output_decode(['texdef', '-t', tex_format, '-p', 'graphicx', 'Gin@extensions'])
  177. m = regex.search('^macro:->(.*?)$', cmdout, regex.MULTILINE)
  178. return m.group(1).split(',')
  179. except FileNotFoundError:
  180. return ()
  181. def get_mkdn_included_images(fname):
  182. '''Return list of all images references in a markdown file.'''
  183. with open(fname) as f:
  184. tree = html.fromstring(pypandoc.convert_text(f.read(), 'html', format='md'))
  185. return list(map(str, tree.xpath("//img/@src")))
  186. def get_mkdn_included_pdfs(fname):
  187. '''Return list of all images references in a markdown file.'''
  188. with open(fname) as f:
  189. tree = html.fromstring(pypandoc.convert_text(f.read(), 'html', format='md'))
  190. return list(map(str, tree.xpath("//embed/@src")))
  191. rsync_common_args = ['-rL', '--size-only', '--delete', '--exclude', '.DS_Store', '--delete-excluded',]
  192. rule build_all:
  193. input: 'thesis.pdf', 'thesis-final.pdf', 'presentation.pdf'
  194. # Note: Any rule that generates an input LyX file for this rule must
  195. # be marked as a checkpoint. See
  196. # https://snakemake.readthedocs.io/en/stable/snakefiles/rules.html#data-dependent-conditional-execution
  197. rule thesis_lyx_to_pdf:
  198. '''Produce PDF output for a LyX file.'''
  199. input: lyxfile = '{basename}.lyx',
  200. gfx_deps = lambda wildcards: lyx_gfx_deps(wildcards.basename + '.lyx'),
  201. bib_deps = lambda wildcards: lyx_bib_deps(wildcards.basename + '.lyx'),
  202. tex_deps = lambda wildcards: lyx_input_deps(wildcards.basename + '.lyx'),
  203. output: pdf='{basename,thesis.*}.pdf'
  204. run:
  205. if not LYX_PATH or LYX_PATH == '/bin/false':
  206. raise Exception('Path to LyX executable could not be found.')
  207. shell('''{LYX_PATH:q} -batch --verbose --export-to pdf4 {output.pdf:q} {input.lyxfile:q}''')
  208. if PDFINFO_PATH:
  209. shell('''{PDFINFO_PATH} {output.pdf:q}''')
  210. checkpoint lyx_add_final:
  211. '''Copy LyX file and add final option.'''
  212. input: lyxfile = '{basename}.lyx'
  213. # Ensure we can't get file-final-final-final-final.lyx
  214. output: lyxtemp = temp('{basename,(?!graphics/).*(?<!-final)}-final.lyx')
  215. run:
  216. with open(input.lyxfile, 'r') as infile, \
  217. open(output.lyxtemp, 'w') as outfile:
  218. lyx_text = infile.read()
  219. if not regex.search('\\\\options final', lyx_text):
  220. lyx_text = regex.sub('\\\\use_default_options true', '\\\\options final\n\\\\use_default_options true', lyx_text)
  221. outfile.write(lyx_text)
  222. # TODO: Remove all URLs from entries with a DOI
  223. rule process_bib:
  224. '''Preprocess bib file for LaTeX.
  225. For entries with a DOI, all URLs are stripped, since the DOI already
  226. provides a clickable link. For entries with no DOI, all but one URL is
  227. discarded, since LyX can't handle entries with multiple URLs. The
  228. shortest URL is kept.'''
  229. input: '{basename}.bib'
  230. output: '{basename,.*(?<!-PROCESSED)}-PROCESSED.bib'
  231. run:
  232. with open(input[0]) as infile:
  233. bib_db = bibtexparser.load(infile)
  234. entries = bib_db.entries
  235. for entry in entries:
  236. if 'doi' in entry:
  237. try:
  238. del entry['url']
  239. except KeyError:
  240. pass
  241. else:
  242. try:
  243. entry_urls = regex.split('\\s+', entry['url'])
  244. shortest_url = min(entry_urls, key=len)
  245. # Need to fix e.g. 'http://www.pubmedcentral.nih.gov/articlerender.fcgi?artid=55329{\\&}tool=pmcentrez{\\&}rendertype=abstract'
  246. shortest_url = re.sub('\\{\\\\(.)\\}', '\\1', shortest_url)
  247. entry['url'] = shortest_url
  248. except KeyError:
  249. pass
  250. new_db = BibDatabase()
  251. new_db.entries = entries
  252. with open(output[0], 'w') as outfile:
  253. bibtexparser.dump(new_db, outfile)
  254. rule pdf_extract_page:
  255. '''Extract a single page from a multi-page PDF.'''
  256. # Input is a PDF whose basename doesn't already have a page number
  257. input: pdf = 'graphics/{basename}.pdf'
  258. output: pdf = 'graphics/{basename}-PAGE{pagenum,[1-9][0-9]*}.pdf'
  259. run:
  260. # This could be done with a regex constraint on basename,
  261. # except that variable width lookbehind isn't supported.
  262. # Unfortunately, that makes this a runtime error instead of an
  263. # error during DAG construction.
  264. if regex.search('-PAGE[0-9]+$', wildcards.basename):
  265. raise ValueError("Can't extract page from extracted page PDF.")
  266. shell('pdfseparate -f {wildcards.pagenum:q} -l {wildcards.pagenum:q} {input:q} {output:q}')
  267. rule pdf_crop:
  268. '''Crop away empty margins from a PDF.'''
  269. input: pdf = 'graphics/{basename}.pdf'
  270. output: pdf = 'graphics/{basename,.*(?<!-CROP)}-CROP.pdf'
  271. shell: 'pdfcrop --resolution 300 {input:q} {output:q}'
  272. rule pdf_raster:
  273. '''Rasterize PDF to PNG at 600 PPI.
  274. The largest dimension is scaled '''
  275. input: pdf = 'graphics/{basename}.pdf'
  276. output: png = 'graphics/{basename}-RASTER.png'
  277. shell: 'pdftoppm -singlefile -r 600 {input:q} | convert - {output:q}'
  278. rule pdf_raster_res:
  279. '''Rasterize PDF to PNG at specific PPI.
  280. The largest dimension is scaled '''
  281. input: pdf = 'graphics/{basename}.pdf'
  282. output: png = 'graphics/{basename}-RASTER{res,[1-9][0-9]+}.png'
  283. shell: 'pdftoppm -singlefile -r {wildcards.res} {input:q} | convert - {output:q}'
  284. rule png_crop:
  285. '''Crop away empty margins from a PNG.'''
  286. input: pdf = 'graphics/{basename}.png'
  287. output: pdf = 'graphics/{basename,.*(?<!-CROP)}-CROP.png'
  288. shell: 'convert {input:q} -trim {output:q}'
  289. rule jpg_crop:
  290. '''Crop away empty margins from a JPG.'''
  291. input: pdf = 'graphics/{basename}.jpg'
  292. output: pdf = 'graphics/{basename,.*(?<!-CROP)}-CROP.jpg'
  293. shell: 'convert {input:q} -trim {output:q}'
  294. rule svg_to_pdf:
  295. input: 'graphics/{filename}.svg'
  296. output: 'graphics/{filename}-SVG.pdf'
  297. run:
  298. infile = os.path.join(os.path.abspath("."), input[0])
  299. outfile = os.path.join(os.path.abspath("."), output[0])
  300. shell('''inkscape {infile:q} --export-pdf={outfile:q} --export-dpi=300''')
  301. rule svg_raster:
  302. input: 'graphics/{filename}.svg'
  303. output: 'graphics/{filename}-SVG.png'
  304. run:
  305. infile = os.path.join(os.path.abspath("."), input[0])
  306. outfile = os.path.join(os.path.abspath("."), output[0])
  307. shell('''inkscape {infile:q} --export-png={outfile:q} --export-dpi=300''')
  308. rule R_to_html:
  309. '''Render an R script as syntax-hilighted HTML.'''
  310. input: '{dirname}/{basename}.R'
  311. output: '{dirname}/{basename,[^/]+}.R.html'
  312. shell: 'pygmentize -f html -O full -l R -o {output:q} {input:q}'
  313. rule build_presentation_beamer:
  314. input:
  315. extra_preamble='extra-preamble.latex',
  316. mkdn_file='{basename}.mkdn',
  317. images=lambda wildcards: get_mkdn_included_images('{basename}.mkdn'.format(**wildcards)),
  318. pdfs=lambda wildcards: get_mkdn_included_pdfs('{basename}.mkdn'.format(**wildcards)),
  319. output:
  320. pdf='{basename,presentation.*}.pdf'
  321. params:
  322. # http://deic.uab.es/~iblanes/beamer_gallery/index_by_theme.html
  323. theme='Boadilla',
  324. # https://pandoc.org/MANUAL.html#variables-for-beamer-slides
  325. aspectratio='169',
  326. run:
  327. shell('''
  328. pandoc \
  329. -f markdown -t beamer \
  330. --pdf-engine=xelatex \
  331. -o {output.pdf:q} \
  332. -H {input.extra_preamble:q} \
  333. {input.mkdn_file:q}
  334. ''')
  335. if PDFINFO_PATH:
  336. shell('''{PDFINFO_PATH} {output.pdf:q}''')
  337. rule build_presentation_ppt:
  338. input:
  339. extra_preamble='extra-preamble.latex',
  340. mkdn_file='{basename}.mkdn',
  341. images=lambda wildcards: get_mkdn_included_images('{basename}.mkdn'.format(**wildcards)),
  342. pdfs=lambda wildcards: get_mkdn_included_pdfs('{basename}.mkdn'.format(**wildcards)),
  343. output:
  344. pptx='{basename,presentation.*}.pptx'
  345. shell: '''
  346. pandoc \
  347. -f markdown -t pptx \
  348. -o {output.pptx:q} \
  349. {input.mkdn_file:q}
  350. '''
  351. rule build_all_presentations:
  352. input:
  353. 'presentation.pdf',
  354. 'presentation.pptx',
  355. rule make_transplant_organs_graph:
  356. input:
  357. Rscript='graphics/presentation/transplants-organ.R',
  358. data='graphics/presentation/transplants-organ.xlsx',
  359. output:
  360. pdf='graphics/presentation/transplants-organ.pdf'
  361. shell: '''
  362. Rscript 'graphics/presentation/transplants-organ.R'
  363. '''