PageRenderTime 65ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 0ms

/snakemake/snakemake_dir/snakemake/utils.py

https://gitlab.com/mstolarczyk/master_thesis
Python | 372 lines | 313 code | 20 blank | 39 comment | 18 complexity | 2cdf831d7e8d3f9133a4c7a297272f06 MD5 | raw file
  1. __author__ = "Johannes Köster"
  2. __contributors__ = ["Per Unneberg"]
  3. __copyright__ = "Copyright 2015, Johannes Köster"
  4. __email__ = "koester@jimmy.harvard.edu"
  5. __license__ = "MIT"
  6. import os
  7. import json
  8. import re
  9. import inspect
  10. import textwrap
  11. from itertools import chain
  12. from collections import Mapping
  13. import multiprocessing
  14. import string
  15. import shlex
  16. import sys
  17. from snakemake.io import regex, Namedlist, Wildcards
  18. from snakemake.logging import logger
  19. from snakemake.exceptions import WorkflowError
  20. import snakemake
  21. def simplify_path(path):
  22. """Return a simplified version of the given path."""
  23. relpath = os.path.relpath(path)
  24. if relpath.startswith("../../"):
  25. return path
  26. else:
  27. return relpath
  28. def linecount(filename):
  29. """Return the number of lines of given file.
  30. Args:
  31. filename (str): the path to the file
  32. """
  33. with open(filename) as f:
  34. return sum(1 for l in f)
  35. def listfiles(pattern, restriction=None, omit_value=None):
  36. """Yield a tuple of existing filepaths for the given pattern.
  37. Wildcard values are yielded as the second tuple item.
  38. Args:
  39. pattern (str): a filepattern. Wildcards are specified in snakemake syntax, e.g. "{id}.txt"
  40. restriction (dict): restrict to wildcard values given in this dictionary
  41. omit_value (str): wildcard value to omit
  42. Yields:
  43. tuple: The next file matching the pattern, and the corresponding wildcards object
  44. """
  45. pattern = os.path.normpath(pattern)
  46. first_wildcard = re.search("{[^{]", pattern)
  47. if first_wildcard:
  48. dirname = os.path.dirname(pattern[:first_wildcard.start()])
  49. if not dirname:
  50. dirname = "."
  51. else:
  52. dirname = os.path.dirname(pattern)
  53. pattern = re.compile(regex(pattern))
  54. for dirpath, dirnames, filenames in os.walk(dirname):
  55. for f in chain(filenames, dirnames):
  56. if dirpath != ".":
  57. f = os.path.normpath(os.path.join(dirpath, f))
  58. match = re.match(pattern, f)
  59. if match:
  60. wildcards = Namedlist(fromdict=match.groupdict())
  61. if restriction is not None:
  62. invalid = any(omit_value not in v and v != wildcards[k]
  63. for k, v in restriction.items())
  64. if not invalid:
  65. yield f, wildcards
  66. else:
  67. yield f, wildcards
  68. def makedirs(dirnames):
  69. """Recursively create the given directory or directories without
  70. reporting errors if they are present.
  71. """
  72. if isinstance(dirnames, str):
  73. dirnames = [dirnames]
  74. for dirname in dirnames:
  75. os.makedirs(dirname, exist_ok=True)
  76. def report(text, path,
  77. stylesheet=os.path.join(os.path.dirname(__file__), "report.css"),
  78. defaultenc="utf8",
  79. template=None,
  80. metadata=None, **files):
  81. """Create an HTML report using python docutils.
  82. Attention: This function needs Python docutils to be installed for the
  83. python installation you use with Snakemake.
  84. All keywords not listed below are intepreted as paths to files that shall
  85. be embedded into the document. They keywords will be available as link
  86. targets in the text. E.g. append a file as keyword arg via F1=input[0]
  87. and put a download link in the text like this:
  88. .. code:: python
  89. report('''
  90. ==============
  91. Report for ...
  92. ==============
  93. Some text. A link to an embedded file: F1_.
  94. Further text.
  95. ''', outputpath, F1=input[0])
  96. Instead of specifying each file as a keyword arg, you can also expand
  97. the input of your rule if it is completely named, e.g.:
  98. report('''
  99. Some text...
  100. ''', outputpath, **input)
  101. Args:
  102. text (str): The "restructured text" as it is expected by python docutils.
  103. path (str): The path to the desired output file
  104. stylesheet (str): An optional path to a css file that defines the style of the document. This defaults to <your snakemake install>/report.css. Use the default to get a hint how to create your own.
  105. defaultenc (str): The encoding that is reported to the browser for embedded text files, defaults to utf8.
  106. template (str): An optional path to a docutils HTML template.
  107. metadata (str): E.g. an optional author name or email address.
  108. """
  109. try:
  110. import snakemake.report
  111. except ImportError:
  112. raise WorkflowError(
  113. "Python 3 package docutils needs to be installed to use the report function.")
  114. snakemake.report.report(text, path,
  115. stylesheet=stylesheet,
  116. defaultenc=defaultenc,
  117. template=template,
  118. metadata=metadata, **files)
  119. def R(code):
  120. """Execute R code
  121. This function executes the R code given as a string.
  122. The function requires rpy2 to be installed.
  123. Args:
  124. code (str): R code to be executed
  125. """
  126. try:
  127. import rpy2.robjects as robjects
  128. except ImportError:
  129. raise ValueError(
  130. "Python 3 package rpy2 needs to be installed to use the R function.")
  131. robjects.r(format(textwrap.dedent(code), stepout=2))
  132. class SequenceFormatter(string.Formatter):
  133. """string.Formatter subclass with special behavior for sequences.
  134. This class delegates formatting of individual elements to another
  135. formatter object. Non-list objects are formatted by calling the
  136. delegate formatter's "format_field" method. List-like objects
  137. (list, tuple, set, frozenset) are formatted by formatting each
  138. element of the list according to the specified format spec using
  139. the delegate formatter and then joining the resulting strings with
  140. a separator (space by default).
  141. """
  142. def __init__(self, separator=" ", element_formatter=string.Formatter(),
  143. *args, **kwargs):
  144. self.separator = separator
  145. self.element_formatter = element_formatter
  146. def format_element(self, elem, format_spec):
  147. """Format a single element
  148. For sequences, this is called once for each element in a
  149. sequence. For anything else, it is called on the entire
  150. object. It is intended to be overridden in subclases.
  151. """
  152. return self.element_formatter.format_field(elem, format_spec)
  153. def format_field(self, value, format_spec):
  154. if isinstance(value, Wildcards):
  155. return ",".join("{}={}".format(name, value.get(name)) for name in value.keys())
  156. if isinstance(value, (list, tuple, set, frozenset)):
  157. return self.separator.join(self.format_element(v, format_spec) for v in value)
  158. else:
  159. return self.format_element(value, format_spec)
  160. class QuotedFormatter(string.Formatter):
  161. """Subclass of string.Formatter that supports quoting.
  162. Using this formatter, any field can be quoted after formatting by
  163. appending "q" to its format string. By default, shell quoting is
  164. performed using "shlex.quote", but you can pass a different
  165. quote_func to the constructor. The quote_func simply has to take a
  166. string argument and return a new string representing the quoted
  167. form of the input string.
  168. Note that if an element after formatting is the empty string, it
  169. will not be quoted.
  170. """
  171. def __init__(self, quote_func=shlex.quote, *args, **kwargs):
  172. self.quote_func = quote_func
  173. super().__init__(*args, **kwargs)
  174. def format_field(self, value, format_spec):
  175. do_quote = format_spec.endswith("q")
  176. if do_quote:
  177. format_spec = format_spec[:-1]
  178. formatted = super().format_field(value, format_spec)
  179. if do_quote and formatted != '':
  180. formatted = self.quote_func(formatted)
  181. return formatted
  182. class AlwaysQuotedFormatter(QuotedFormatter):
  183. """Subclass of QuotedFormatter that always quotes.
  184. Usage is identical to QuotedFormatter, except that it *always*
  185. acts like "q" was appended to the format spec.
  186. """
  187. def format_field(self, value, format_spec):
  188. if not format_spec.endswith("q"):
  189. format_spec += "q"
  190. return super().format_field(value, format_spec)
  191. def format(_pattern, *args, stepout=1, _quote_all=False, **kwargs):
  192. """Format a pattern in Snakemake style.
  193. This means that keywords embedded in braces are replaced by any variable
  194. values that are available in the current namespace.
  195. """
  196. frame = inspect.currentframe().f_back
  197. while stepout > 1:
  198. if not frame.f_back:
  199. break
  200. frame = frame.f_back
  201. stepout -= 1
  202. variables = dict(frame.f_globals)
  203. # add local variables from calling rule/function
  204. variables.update(frame.f_locals)
  205. if "self" in variables and sys.version_info < (3, 5):
  206. # self is the first arg of fmt.format as well. Not removing it would
  207. # cause a multiple values error on Python <=3.4.2.
  208. del variables["self"]
  209. variables.update(kwargs)
  210. fmt = SequenceFormatter(separator=" ")
  211. if _quote_all:
  212. fmt.element_formatter = AlwaysQuotedFormatter()
  213. else:
  214. fmt.element_formatter = QuotedFormatter()
  215. try:
  216. return fmt.format(_pattern, *args, **variables)
  217. except KeyError as ex:
  218. raise NameError("The name {} is unknown in this context. Please "
  219. "make sure that you defined that variable. "
  220. "Also note that braces not used for variable access "
  221. "have to be escaped by repeating them, "
  222. "i.e. {{{{print $1}}}}".format(str(ex)))
  223. class Unformattable:
  224. def __init__(self, errormsg="This cannot be used for formatting"):
  225. self.errormsg = errormsg
  226. def __str__(self):
  227. raise ValueError(self.errormsg)
  228. def read_job_properties(jobscript,
  229. prefix="# properties",
  230. pattern=re.compile("# properties = (.*)")):
  231. """Read the job properties defined in a snakemake jobscript.
  232. This function is a helper for writing custom wrappers for the
  233. snakemake --cluster functionality. Applying this function to a
  234. jobscript will return a dict containing information about the job.
  235. """
  236. with open(jobscript) as jobscript:
  237. for m in map(pattern.match, jobscript):
  238. if m:
  239. return json.loads(m.group(1))
  240. def min_version(version):
  241. """Require minimum snakemake version, raise workflow error if not met."""
  242. import pkg_resources
  243. if pkg_resources.parse_version(
  244. snakemake.__version__) < pkg_resources.parse_version(version):
  245. raise WorkflowError(
  246. "Expecting Snakemake version {} or higher.".format(version))
  247. def update_config(config, overwrite_config):
  248. """Recursively update dictionary config with overwrite_config.
  249. See
  250. http://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth
  251. for details.
  252. Args:
  253. config (dict): dictionary to update
  254. overwrite_config (dict): dictionary whose items will overwrite those in config
  255. """
  256. def _update(d, u):
  257. for (key, value) in u.items():
  258. if (isinstance(value, Mapping)):
  259. d[key] = _update(d.get(key, {}), value)
  260. else:
  261. d[key] = value
  262. return d
  263. _update(config, overwrite_config)
  264. def set_temporary_output(*rules):
  265. """Set the output of rules to temporary"""
  266. for rule in rules:
  267. logger.debug(
  268. "setting output of rule '{rule}' to temporary".format(rule=rule))
  269. rule.temp_output = set(rule.output)
  270. def set_protected_output(*rules):
  271. """Set the output of rules to protected"""
  272. for rule in rules:
  273. logger.debug(
  274. "setting output of rule '{rule}' to protected".format(rule=rule))
  275. rule.protected_output = set(rule.output)
  276. def available_cpu_count():
  277. """
  278. Return the number of available virtual or physical CPUs on this system.
  279. The number of available CPUs can be smaller than the total number of CPUs
  280. when the cpuset(7) mechanism is in use, as is the case on some cluster
  281. systems.
  282. Adapted from http://stackoverflow.com/a/1006301/715090
  283. """
  284. try:
  285. with open('/proc/self/status') as f:
  286. status = f.read()
  287. m = re.search(r'(?m)^Cpus_allowed:\s*(.*)$', status)
  288. if m:
  289. res = bin(int(m.group(1).replace(',', ''), 16)).count('1')
  290. if res > 0:
  291. return min(res, multiprocessing.cpu_count())
  292. except IOError:
  293. pass
  294. return multiprocessing.cpu_count()