generator.py 5.47 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :

'''Utilities for generating configurations for running experiments in batch'''


import collections
import itertools

import yaml
import jinja2


14 15 16 17 18 19 20 21
class _OrderedDict(collections.OrderedDict):
  """An OrderedDict class that can be compared.
  This is to avoid sort errors (in Python 3) that happen in jinja internally.
  """
  def __lt__(self, other):
    return id(self) < id(other)


22
def _ordered_load(stream, Loader=yaml.Loader,
23 24
    object_pairs_hook=_OrderedDict):
  '''Loads the contents of the YAML stream into :py:class:`collections.OrderedDict`'s
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133

  See: https://stackoverflow.com/questions/5121931/in-python-how-can-you-load-yaml-mappings-as-ordereddicts

  '''

  class OrderedLoader(Loader): pass

  def construct_mapping(loader, node):
    loader.flatten_mapping(node)
    return object_pairs_hook(loader.construct_pairs(node))

  OrderedLoader.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
      construct_mapping)

  return yaml.load(stream, OrderedLoader)


def expand(data):
  '''Generates configuration sets based on the YAML input contents

  For an introduction to the YAML mark-up, just search the net. Here is one of
  its references: https://en.wikipedia.org/wiki/YAML

  A configuration set corresponds to settings for **all** variables in the
  input template that needs replacing. For example, if your template mentions
  the variables ``name`` and ``version``, then each configuration set should
  yield values for both ``name`` and ``version``.

  For example:

  .. code-block:: yaml

     name: [john, lisa]
     version: [v1, v2]


  This should yield to the following configuration sets:

  .. code-block:: python

     [
       {'name': 'john', 'version': 'v1'},
       {'name': 'john', 'version': 'v2'},
       {'name': 'lisa', 'version': 'v1'},
       {'name': 'lisa', 'version': 'v2'},
     ]


  Each key in the input file should correspond to either an object or a YAML
  array. If the object is a list, then we'll iterate over it for every possible
  combination of elements in the lists. If the element in question is not a
  list, then it is considered unique and repeated for each yielded
  configuration set. Example

  .. code-block:: yaml

     name: [john, lisa]
     version: [v1, v2]
     text: >
        hello,
        world!

  Should yield to the following configuration sets:

  .. code-block:: python

     [
       {'name': 'john', 'version': 'v1', 'text': 'hello, world!'},
       {'name': 'john', 'version': 'v2', 'text': 'hello, world!'},
       {'name': 'lisa', 'version': 'v1', 'text': 'hello, world!'},
       {'name': 'lisa', 'version': 'v2', 'text': 'hello, world!'},
     ]

  Keys starting with one `_` (underscore) are treated as "unique" objects as
  well. Example:

  .. code-block:: yaml

     name: [john, lisa]
     version: [v1, v2]
     _unique: [i1, i2]

  Should yield to the following configuration sets:

  .. code-block:: python

     [
       {'name': 'john', 'version': 'v1', '_unique': ['i1', 'i2']},
       {'name': 'john', 'version': 'v2', '_unique': ['i1', 'i2']},
       {'name': 'lisa', 'version': 'v1', '_unique': ['i1', 'i2']},
       {'name': 'lisa', 'version': 'v2', '_unique': ['i1', 'i2']},
     ]


  Parameters:

    data (str): YAML data to be parsed


  Yields:

    dict: A dictionary of key-value pairs for building the templates

  '''

  data = _ordered_load(data, yaml.SafeLoader)

  # separates "unique" objects from the ones we have to iterate
  # pre-assemble return dictionary
134 135
  iterables = _OrderedDict()
  unique = _OrderedDict()
136 137 138 139 140 141 142 143
  for key, value in data.items():
    if isinstance(value, list) and not key.startswith('_'):
      iterables[key] = value
    else:
      unique[key] = value

  # generates all possible combinations of iterables
  for values in itertools.product(*iterables.values()):
144
    retval = _OrderedDict(unique)
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
    keys = list(iterables.keys())
    retval.update(dict(zip(keys, values)))
    yield retval


def generate(variables, template):
  '''Yields a resolved "template" for each config set and dumps on output

  This function will extrapolate the ``template`` file using the contents of
  ``variables`` and will output individual (extrapolated, expanded) files in
  the output directory ``output``.


  Parameters:

    variables (str): A string stream containing the variables to parse, in YAML
      format as explained on :py:func:`expand`.

    template (str): A string stream containing the template to extrapolate


  Yields:

    str: A generated template you can save

170 171 172 173 174

  Raises:

    jinja2.UndefinedError: if a variable used in the template is undefined

175 176
  '''

177
  env = jinja2.Environment(undefined=jinja2.StrictUndefined)
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
  for c in expand(variables):
    yield env.from_string(template).render(c)


def aggregate(variables, template):
  '''Generates a resolved "template" for **all** config sets and returns

  This function will extrapolate the ``template`` file using the contents of
  ``variables`` and will output a single (extrapolated, expanded) file.


  Parameters:

    variables (str): A string stream containing the variables to parse, in YAML
      format as explained on :py:func:`expand`.

    template (str): A string stream containing the template to extrapolate


  Returns:

    str: A generated template you can save

201 202 203 204 205

  Raises:

    jinja2.UndefinedError: if a variable used in the template is undefined

206 207
  '''

208
  env = jinja2.Environment(undefined=jinja2.StrictUndefined)
209
  d = {'cfgset': list(expand(variables))}
210
  return env.from_string(template).render(d)