pax_global_header00006660000000000000000000000064131512744630014520gustar00rootroot0000000000000052 comment=528c6906f4748c0cfeda3089d9e95a5def3ecb92 CTDopts-1.2/000077500000000000000000000000001315127446300127025ustar00rootroot00000000000000CTDopts-1.2/.gitignore000066400000000000000000000000431315127446300146670ustar00rootroot00000000000000*.pyc *.DS_Store .idea .pythoscopeCTDopts-1.2/CTDopts/000077500000000000000000000000001315127446300142225ustar00rootroot00000000000000CTDopts-1.2/CTDopts/CTDopts.py000066400000000000000000001432201315127446300161160ustar00rootroot00000000000000import argparse from collections import OrderedDict, Mapping from itertools import chain from xml.etree.ElementTree import Element, SubElement, tostring, parse from xml.dom.minidom import parseString import warnings # dummy classes for input-file and output-file CTD types. class _ASingleton(type): """ A metaclass for singletons """ _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(_ASingleton, cls).__call__(*args, **kwargs) return cls._instances[cls] class _Null(object): """ A null singleton for non-initialized fields to distinguish between initialized=None and non-initialized members """ __metaclass__ = _ASingleton class _InFile(str): """Dummy class for input-file CTD type. I think most users would want to just get the file path string but if it's required to open these files for reading or writing, one could do it in these classes in a later release. Otherwise, it's equivalent to str with the information that we're dealing with a file argument. """ pass class _OutFile(str): """Same thing, a dummy class for output-file CTD type.""" pass # module globals for some common operations (python types to CTD-types back and forth) TYPE_TO_CTDTYPE = {int: 'int', float: 'float', str: 'string', bool: 'boolean', _InFile: 'input-file', _OutFile: 'output-file'} CTDTYPE_TO_TYPE = {'int': int, 'float': float, 'double': float, 'string': str, 'boolean': bool, 'bool': bool, 'input-file': _InFile, 'output-file': _OutFile, int: int, float: float, str: str, bool: bool, _InFile: _InFile, _OutFile: _OutFile} PARAM_DEFAULTS = {'advanced': False, 'required': False, 'restrictions': None, 'description': None, 'supported_formats': None, 'tags': None, 'position': None} # unused. TODO. # a boolean type caster to circumvent bool('false')==True when we cast CTD 'value' attributes to their correct type CAST_BOOLEAN = lambda x: bool(x) if not isinstance(x, str) else (x in ('true', 'True', '1')) # instead of using None or _Null, we define non-present 'position' attribute values as -1 NO_POSITION = -1 # Module-level functions for querying and manipulating argument dictionaries. def get_nested_key(arg_dict, key_list): """Looks up a nested key in an arbitrarily nested dictionary. `key_list` should be an iterable: get_nested_key(args, ['group', 'subgroup', 'param']) returns args['group']['subgroup']['param'] """ key_list = [key_list] if isinstance(key_list, str) else key_list # just to be safe. res = arg_dict for key in key_list: res = res[key] else: return res def set_nested_key(arg_dict, key_list, value): """Inserts a value into an arbitrarily nested dictionary, creating nested sub-dictionaries on the way if needed: set_nested_key(args, ['group', 'subgroup', 'param'], value) sets args['group']['subgroup']['param'] = value """ key_list = [key_list] if isinstance(key_list, str) else key_list # just to be safe. res = arg_dict for key in key_list[:-1]: if key not in res: res[key] = {} # OrderedDict() res = res[key] else: res[key_list[-1]] = value def flatten_dict(arg_dict, as_string=False): """Creates a flattened dictionary out of a nested dictionary. New keys will be tuples, with the nesting information. Ie. arg_dict['group']['subgroup']['param1'] will be result[('group', 'subgroup', 'param1')] in the flattened dictionary. `as_string` joins the nesting levels into a single string with a semicolon, so the same entry would be under result['group:subgroup:param1'] """ result = {} def flattener(subgroup, level): # recursive closure that accesses and modifies result dict and registers nested elements # as it encounters them for key, value in subgroup.iteritems(): if isinstance(value, Mapping): # collections.Mapping instead of dict for generality flattener(value, level + [key]) else: result[tuple(level + [key])] = value flattener(arg_dict, []) if as_string: return {':'.join(keylist): value for keylist, value in result.iteritems()} else: return result def override_args(*arg_dicts): """Takes any number of (nested or flat) argument dictionaries and combines them, giving preference to the last one if more than one have the same entry. Typically would be used like: combined_args = override_args(args_from_ctd, args_from_commandline) """ overridden_args = dict(chain(*(flatten_dict(d).iteritems() for d in arg_dicts))) result = {} for keylist, value in overridden_args.iteritems(): set_nested_key(result, keylist, value) return result def _translate_ctd_to_param(attribs): """Translates a CTD or XML-node's attributes to keyword arguments that Parameter's constructor expects. One should be able to call Parameter(*result) with the output of this function. For list parameters, adding is_list=True and getting values is needed after translation, as they are not stored as XML attributes. """ # right now value is a required field, but it shouldn't be for required parameters. if 'value' in attribs: # TODO 1_6_3, this line will be deleted. attribs['default'] = attribs.pop('value') # rename 'value' to 'default' (Parameter constructor takes 'default') if 'supported_formats' in attribs: # supported_formats in CTD xml is called file_formats in CTDopts attribs['file_formats'] = attribs.pop('supported_formats') # rename that attribute too if 'restrictions' in attribs: # find out whether restrictions are choices ('this,that') or numeric range ('3:10') if ',' in attribs['restrictions']: attribs['choices'] = attribs['restrictions'].split(',') elif ':' in attribs['restrictions']: n_min, n_max = attribs['restrictions'].split(':') n_min = None if n_min == '' else n_min n_max = None if n_max == '' else n_max attribs['num_range'] = (n_min, n_max) else: # there is nothing we can split with... so we will assume that this is a restriction of one possible # value... anyway, the user should be warned about it warnings.warn("Restriction [%s] of a single value found for parameter [%s]. \n" "Restrictions should be comma separated value lists or colon separated values to " "indicate numeric ranges (e.g., 'true,false', '0:14', '1:', ':2.8')\n" "Will use a restriction with one possible value of choice." % (attribs['restrictions'], attribs['name'])) attribs['choices'] = [attribs['restrictions']] # TODO: advanced. Should it be stored as a tag, or should we extend Parameter class to have that attribute? # what we can do is keep it as a tag in the model, and change Parameter._xml_node() so that if it finds # 'advanced' among its tag-list, make it output it as a separate attribute. return attribs class ArgumentError(Exception): """Base exception class for argument related problems. """ def __init__(self, parameter): self.parameter = parameter self.param_name = ':'.join(self.parameter.get_lineage(name_only=True)) class ArgumentMissingError(ArgumentError): """Exception for missing required arguments. """ def __init__(self, parameter): super(ArgumentMissingError, self).__init__(parameter) def __str__(self): return 'Required argument %s missing' % self.param_name class ArgumentTypeError(ArgumentError): """Exception for arguments that can't be casted to the type defined in the model. """ def __init__(self, parameter, value): super(ArgumentTypeError, self).__init__(parameter) self.value = value def __str__(self): return "Argument %s is of wrong type. Expected: %s, got %s" % ( self.param_name, TYPE_TO_CTDTYPE[self.parameter.type], self.value) class ArgumentRestrictionError(ArgumentError): """Exception for arguments violating numeric, file format or controlled vocabulary restrictions. """ def __init__(self, parameter, value): super(ArgumentRestrictionError, self).__init__(parameter) self.value = value def __str__(self): return 'Argument restrictions for %s failed. Restriction: %s. Value: %s' % ( self.param_name, self.parameter.restrictions.ctd_restriction_string(), self.value) class ModelError(Exception): """Exception for errors related to CTDModel building """ def __init__(self): super(ModelError, self).__init__() class ModelParsingError(ModelError): """Exception for errors related to CTD parsing """ def __init__(self, message): super(ModelParsingError, self).__init__() self.message = message def __str__(self): return "An error occurred while parsing the CTD file: %s" % self.message def __repr__(self): return str(self) class UnsupportedTypeError(ModelError): """Exception for attempting to use unsupported types in the model """ def __init__(self, wrong_type): super(UnsupportedTypeError, self).__init__() self.wrong_type = wrong_type def __str__(self): return 'Unsupported type encountered during model construction: %s' % self.wrong_type class DefaultError(ModelError): def __init__(self, parameter): super(DefaultError, self).__init__() self.parameter = parameter def __str__(self): pass class _Restriction(object): """Superclass for restriction classes (numeric, file format, controlled vocabulary). """ def __init__(self): pass # if Python had virtual methods, this one would have a _single_check() virtual method, as all # subclasses have to implement for check() to go through. check() expects them to be present, # and validates normal and list parameters accordingly. def check(self, value): """Checks whether `value` satisfies the restriction conitions. For list parameters it checks every element individually. """ if isinstance(value, list): # check every element of list (in case of list parameters) return all((self._single_check(v) for v in value)) else: return self._single_check(value) class _NumericRange(_Restriction): """Class for numeric range restrictions. Stores valid numeric ranges, checks values against them and outputs CTD restrictions attribute strings. """ def __init__(self, n_type, n_min=None, n_max=None): super(_NumericRange, self).__init__() self.n_type = n_type self.n_min = self.n_type(n_min) if n_min is not None else None self.n_max = self.n_type(n_max) if n_max is not None else None def ctd_restriction_string(self): n_min = str(self.n_min) if self.n_min is not None else '' n_max = str(self.n_max) if self.n_max is not None else '' return '%s:%s' % (n_min, n_max) def _single_check(self, value): if self.n_min is not None and value < self.n_min: return False elif self.n_max is not None and value > self.n_max: return False else: return True def __repr__(self): return 'numeric range: %s to %s' % (self.n_min, self.n_max) class _FileFormat(_Restriction): """Class for file format restrictions. Stores valid file formats, checks filenames against them and outputs CTD supported_formats attribute strings. """ def __init__(self, formats): super(_FileFormat, self).__init__() if isinstance(formats, str): # to handle ['txt', 'csv', 'tsv'] and '*.txt,*.csv,*.tsv' formats = map(lambda x: x.replace('*.', '').strip(), formats.split(',')) self.formats = formats def ctd_restriction_string(self): return ','.join(('*.' + f for f in self.formats)) def _single_check(self, value): for f in self.formats: if value.endswith('.' + f): return True return False def __repr__(self): return 'file formats: %s' % (', '.join(self.formats)) class _Choices(_Restriction): """Class for controlled vocabulary restrictions. Stores controlled vocabulary elements, checks values against them and outputs CTD restrictions attribute strings. """ def __init__(self, choices): super(_Choices, self).__init__() if isinstance(choices, str): # If it actually has to run, a user is screwing around... choices = choices.replace(', ', ',').split(',') self.choices = choices def _single_check(self, value): return value in self.choices def ctd_restriction_string(self): return ','.join(self.choices) def __repr__(self): return 'choices: %s' % (', '.join(map(str, self.choices))) class Parameter(object): def __init__(self, name, parent, **kwargs): """Required positional arguments: `name` string and `parent` ParameterGroup object Optional keyword arguments: `type`: Python type object, or a string of a valid CTD types. For all valid values, see: CTDopts.CTDTYPE_TO_TYPE.keys() `default`: default value. Will be casted to the above type (default None) `is_list`: bool, indicating whether this is a list parameter (default False) `required`: bool, indicating whether this is a required parameter (default False) `description`: string containing parameter description (default None) `tags`: list of strings or comma separated string (default []) `num_range`: (min, max) tuple. None in either position makes it unlimited `choices`: list of allowed values (controlled vocabulary) `file_formats`: list of allowed file extensions `short_name`: string for short name annotation `position`: index (1-based) of the position on which the parameter appears on the command-line """ self.name = name self.parent = parent self.short_name = kwargs.get('short_name', _Null) try: self.type = CTDTYPE_TO_TYPE[kwargs.get('type', str)] except: raise UnsupportedTypeError(kwargs.get('type')) self.tags = kwargs.get('tags', []) if isinstance(self.tags, str): # so that tags can be passed as ['tag1', 'tag2'] or 'tag1,tag2' self.tags = filter(bool, self.tags.split(',')) # so an empty string doesn't produce [''] self.required = CAST_BOOLEAN(kwargs.get('required', False)) self.is_list = CAST_BOOLEAN(kwargs.get('is_list', False)) self.description = kwargs.get('description', None) self.advanced = CAST_BOOLEAN(kwargs.get('advanced', False)) self.position = int(kwargs.get('position', str(NO_POSITION))) default = kwargs.get('default', _Null) self._validate_numerical_defaults(default) # TODO 1_6_3: right now the CTD schema requires the 'value' attribute to be present for every parameter. # So every time we build a model from a CTD file, we find at least a default='' or default=[] # for every parameter. This should change soon, but for the time being, we have to get around this # and disregard such default attributes. The below two lines will be deleted after fixing 1_6_3. if default == '' or (self.is_list and default == []): default = _Null # enforce that default is the correct type if exists. Elementwise for lists if default is _Null: self.default = _Null elif default is None: self.default = None else: if self.is_list: self.default = map(self.type, default) else: self.default = self.type(default) # same for choices. I'm starting to think it's really unpythonic and we should trust input. TODO if self.type == bool: assert self.is_list is False, "Boolean flag can't be a list type" self.required = False # override whatever we found. Boolean flags can't be required... self.default = CAST_BOOLEAN(default) # Default value should exist IFF argument is not required. # TODO: if we can have optional list arguments they don't have to have a default? (empty list) # TODO: CTD Params 1.6.3 have a required value attrib. That's very wrong for parameters that are required. # ... until that's ironed out, we have to comment this part out. # # ACTUALLY now that I think of it, letting required fields have value attribs set too # can be useful for users who want to abuse CTD and build models from argument-storing CTDs. # I know some users will do this (who are not native CTD users just want to convert their stuff # with minimal effort) so we might as well let them. # # if self.required: # assert self.default is None, ('Required field `%s` has default value' % self.name) # else: # assert self.default is not None, ('Optional field `%s` has no default value' % self.name) self.restrictions = None if 'num_range' in kwargs: try: self.restrictions = _NumericRange(self.type, *kwargs['num_range']) except ValueError: num_range = kwargs['num_range'] raise ModelParsingError("Provided range [%s, %s] is not of type %s" % (num_range[0], num_range[1], self.type)) elif 'choices' in kwargs: self.restrictions = _Choices(map(self.type, kwargs['choices'])) elif 'file_formats' in kwargs: self.restrictions = _FileFormat(kwargs['file_formats']) # perform some basic validation on the provided default values... # an empty string IS NOT a float/int! def _validate_numerical_defaults(self, default): if default is not None and default is not _Null: if self.type is int or self.type is float: defaults_to_validate = [] errors_so_far = [] if self.is_list: # for lists, validate each provided element defaults_to_validate.extend(default) else: defaults_to_validate.append(default) for default_to_validate in defaults_to_validate: try: if self.type is int: int(default_to_validate) else: float(default_to_validate) except ValueError: errors_so_far.append(default_to_validate) if len(errors_so_far) > 0: raise ModelParsingError("Invalid default value(s) provided for parameter %(name)s of type %(type)s:" " '%(default)s'" % {"name": self.name, "type": self.type, "default": ', '.join(map(str, errors_so_far))}) def get_lineage(self, name_only=False, short_name=False): """Returns a list of zero or more ParameterGroup objects plus this Parameter object at the end, ie. the nesting lineage of the Parameter object. With `name_only` setting on, it only returns the names of said objects. For top level parameters, it's a list with a single element. """ lineage = [] i = self while i.parent is not None: # Exclude ParameterGroup here, since they do not have a short_name attribute (lzimmermann) lineage.append(i.short_name if short_name and not isinstance(i, ParameterGroup) else i.name if name_only else i) i = i.parent lineage.reverse() return lineage def __repr__(self): info = [] info.append('PARAMETER %s%s' % (self.name, ' (required)' if self.required else '')) info.append(' type: %s%s%s' % ('list of ' if self.is_list else '', TYPE_TO_CTDTYPE[self.type], 's' if self.is_list else '')) if self.default: info.append(' default: %s' % self.default) if self.tags: info.append(' tags: %s' % ', '.join(self.tags)) if self.restrictions: info.append(' restrictions on %s' % self.restrictions) if self.description: info.append(' description: %s' % self.description) return '\n'.join(info) def _xml_node(self, arg_dict=None): if arg_dict is not None: # if we call this function with an argument dict, get value from there try: value = get_nested_key(arg_dict, self.get_lineage(name_only=True)) except KeyError: value = self.default else: # otherwise take the parameter default value = self.default # XML attributes to be created (depending on whether they are needed or not): # name, value, type, description, tags, restrictions, supported_formats attribs = OrderedDict() # LXML keeps the order, ElemenTree doesn't. We use ElementTree though. attribs['name'] = self.name if not self.is_list: # we'll deal with list parameters later, now only normal: # TODO: once Param_1_6_3.xsd gets fixed, we won't have to set an empty value='' attrib. # but right now value is a required attribute. attribs['value'] = '' if value is _Null else str(value) if self.type is bool: # for booleans str(True) returns 'True' but the XS standard is lowercase attribs['value'] = 'true' if value else 'false' attribs['type'] = TYPE_TO_CTDTYPE[self.type] if self.description: attribs['description'] = self.description if self.tags: attribs['tags'] = ','.join(self.tags) # Choices and NumericRange restrictions go in the 'restrictions' attrib, FileFormat has # its own attribute 'supported_formats' for whatever historic reason. if isinstance(self.restrictions, _Choices) or isinstance(self.restrictions, _NumericRange): attribs['restrictions'] = self.restrictions.ctd_restriction_string() elif isinstance(self.restrictions, _FileFormat): attribs['supported_formats'] = self.restrictions.ctd_restriction_string() if self.is_list: # and now list parameters top = Element('ITEMLIST', attribs) # (lzimmermann) I guess _Null has to be exluded here, too if value is not None and value is not _Null: for d in value: SubElement(top, 'LISTITEM', {'value': str(d)}) return top else: return Element('ITEM', attribs) def _cli_node(self, parent_name, prefix='--'): lineage = self.get_lineage(name_only=True) top_node = Element('clielement', {"optionIdentifier": prefix+':'.join(lineage)}) SubElement(top_node, 'mapping', {"referenceName": parent_name+"."+self.name}) return top_node def is_positional(self): return self.position != NO_POSITION class ParameterGroup(object): def __init__(self, name, parent, description=None): self.name = name self.parent = parent self.description = description self.parameters = OrderedDict() def add(self, name, **kwargs): """Registers a parameter in a ParameterGroup. Required: `name` string. Optional keyword arguments: `type`: Python type object, or a string of a valid CTD types. For all valid values, see: CTDopts.CTDTYPE_TO_TYPE.keys() `default`: default value. Will be casted to the above type (default None) `is_list`: bool, indicating whether this is a list parameter (default False) `required`: bool, indicating whether this is a required parameter (default False) `description`: string containing parameter description (default None) `tags`: list of strings or comma separated string (default []) `num_range`: (min, max) tuple. None in either position makes it unlimited `choices`: list of allowed values (controlled vocabulary) `short_name`: string for short name annotation """ # TODO assertion if name already exists? It just overrides now, but I'm not sure if allowing this behavior is OK self.parameters[name] = Parameter(name, self, **kwargs) return self.parameters[name] def add_group(self, name, description=None): """Registers a child parameter group under a ParameterGroup. Required: `name` string. Optional: `description` """ # TODO assertion if name already exists? It just overrides now, but I'm not sure if allowing this behavior is OK self.parameters[name] = ParameterGroup(name, self, description) return self.parameters[name] def _get_children(self): children = [] for child in self.parameters.itervalues(): if isinstance(child, Parameter): children.append(child) elif isinstance(child, ParameterGroup): children.extend(child._get_children()) return children def _xml_node(self, arg_dict=None): xml_attribs = {'name': self.name} if self.description: xml_attribs['description'] = self.description top = Element('NODE', xml_attribs) # TODO: if a Parameter comes after an ParameterGroup, the CTD won't validate. BTW, that should be changed. # Of course this should never happen if the argument tree is built properly but it would be # nice to take care of it if a user happens to randomly define his arguments and groups. # So first we could sort self.parameters (Items first, Groups after them). for arg in self.parameters.itervalues(): top.append(arg._xml_node(arg_dict)) return top def _cli_node(self, parent_name="", prefix='--'): """ Generates a list of clielements of that group :param arg_dict: dafualt values for elements :return: list of clielements """ for arg in self.parameters.itervalues(): yield arg._cli_node(parent_name=parent_name+"."+self.name, prefix=prefix) def __repr__(self): info = [] info.append('PARAMETER GROUP %s (' % self.name) for subparam in self.parameters.itervalues(): info.append(subparam.__repr__()) info.append(')') return '\n'.join(info) class Mapping(object): def __init__(self, reference_name=None): self.reference_name = reference_name class CLIElement(object): def __init__(self, option_identifier=None, mappings=[]): self.option_identifier = option_identifier self.mappings = mappings class CLI(object): def __init__(self, cli_elements=[]): self.cli_elements = cli_elements class CTDModel(object): def __init__(self, name=None, version=None, from_file=None, **kwargs): """The parameter model of a tool. `name`: name of the tool `version`: version of the tool `from_file`: create the model from a CTD file at provided path Other (self-explanatory) keyword arguments: `docurl`, `description`, `manual`, `executableName`, `executablePath`, `category` """ if from_file is not None: self._load_from_file(from_file) else: self.name = name self.version = version # TODO: check whether optional attributes in kwargs are all allowed or just ignore the rest? self.opt_attribs = kwargs # description, manual, docurl, category (+executable stuff). self.parameters = ParameterGroup('1', None, 'Parameters of %s' % self.name) # openMS legacy, top group named "1" self.cli = [] def _load_from_file(self, filename): """Builds a CTDModel from a CTD XML file. """ root = parse(filename).getroot() assert root.tag == 'tool', "Invalid CTD file, root is not " # TODO: own exception self.opt_attribs = {} self.cli = [] for tool_required_attrib in ['name', 'version']: assert tool_required_attrib in root.attrib, "CTD tool is missing a %s attribute" % tool_required_attrib setattr(self, tool_required_attrib, root.attrib[tool_required_attrib]) for tool_opt_attrib in ['docurl', 'category']: if tool_opt_attrib in root.attrib: self.opt_attribs[tool_opt_attrib] = root.attrib[tool_opt_attrib] for tool_element in root: if tool_element.tag in ['manual', 'description', 'executableName', 'executablePath']: # ignoring: cli, logs, relocators. cli and relocators might be useful later. self.opt_attribs[tool_element.tag] = tool_element.text if tool_element.tag == 'cli': self._build_cli(tool_element.findall('clielement')) if tool_element.tag == 'PARAMETERS': # tool_element.attrib['version'] == '1.6.2' # check whether the schema matches the one CTDOpts uses? params_container_node = tool_element.find('NODE') # we have to check the case in which the parent node contains # item/itemlist elements AND node element children params_container_node_contains_items = params_container_node.find('ITEM') is not None or params_container_node.find('ITEMLIST') # assert params_container_node.attrib['name'] == self.name # check params_container_node's first ITEM child's tool version information again? (OpenMS legacy?) params = params_container_node.find('NODE') # OpenMS legacy again, NODE with name="1" on top # check for the case when we have PARAMETERS/NODE/ITEM if params is None or params_container_node_contains_items: self.parameters = self._build_param_model(params_container_node, base=None) else: # OpenMS legacy again, PARAMETERS/NODE/NODE/ITEM self.parameters = self._build_param_model(params, base=None) def _build_cli(self, xml_cli_elements): for xml_cli_element in xml_cli_elements: mappings = [] for xml_mapping in xml_cli_element.findall('mapping'): mappings.append(Mapping(xml_mapping.attrib['referenceName'] if 'referenceName' in xml_mapping.attrib else None)) self.cli.append(CLIElement(xml_cli_element.attrib['optionIdentifier'] if 'optionIdentifier' in xml_cli_element.attrib else None, mappings)) def _build_param_model(self, element, base): if element.tag == 'NODE': validate_contains_keys(element.attrib, ['name'], 'NODE') if base is None: # top level group () has to be created on its own current_group = ParameterGroup(element.attrib['name'], base, element.attrib.get('description', '')) else: # other groups can be registered as a subgroup, as they'll always have parent base nodes current_group = base.add_group(element.attrib['name'], element.attrib.get('description', '')) for child in element: self._build_param_model(child, current_group) return current_group elif element.tag == 'ITEM': setup = _translate_ctd_to_param(dict(element.attrib)) validate_contains_keys(setup, ['name'], 'ITEM') base.add(**setup) # register parameter in model elif element.tag == 'ITEMLIST': setup = _translate_ctd_to_param(dict(element.attrib)) setup['default'] = [listitem.attrib['value'] for listitem in element] setup['is_list'] = True validate_contains_keys(setup, ['name'], 'ITEMLIST') base.add(**setup) # register list parameter in model def add(self, name, **kwargs): """Registers a top level parameter to the model. Required: `name` string. Optional keyword arguments: `type`: Python type object, or a string of a valid CTD types. For all valid values, see: CTDopts.CTDTYPE_TO_TYPE.keys() `default`: default value. Will be casted to the above type (default None) `is_list`: bool, indicating whether this is a list parameter (default False) `required`: bool, indicating whether this is a required parameter (default False) `description`: string containing parameter description (default None) `tags`: list of strings or comma separated string (default []) `num_range`: (min, max) tuple. None in either position makes it unlimited `choices`: list of allowed values (controlled vocabulary) `file_formats`: list of allowed file extensions `short_name`: string for short name annotation """ return self.parameters.add(name, **kwargs) def add_group(self, name, description=None): """Registers a top level parameter group to the model. Required: `name` string. Optional: `description` """ return self.parameters.add_group(name, description) def list_parameters(self): """Returns a list of all Parameter objects registered in the model. """ # root node will list all its children (recursively, if they are nested in ParameterGroups) return self.parameters._get_children() def get_defaults(self): """Returns a nested dictionary with all parameters of the model having default values. """ params_w_default = (p for p in self.list_parameters() if p.default is not _Null) defaults = {} for param in params_w_default: set_nested_key(defaults, param.get_lineage(name_only=True), param.default) return defaults def validate_args(self, args_dict, enforce_required=0, enforce_type=0, enforce_restrictions=0): """Validates an argument dictionary against the model, and returns a type-casted argument dictionary with defaults for missing arguments. Valid values for `enforce_required`, `enforce_type` and `enforce_restrictions` are 0, 1 and 2, where the different levels are: * 0: doesn't enforce anything, * 1: raises a warning * 2: raises an exception """ # iterate over model parameters, look them up in the argument dictionary, convert to correct type, # use default if argument is not present and raise exception if required argument is missing. validated_args = {} # OrderedDict() all_params = self.list_parameters() for param in all_params: lineage = param.get_lineage(name_only=True) try: arg = get_nested_key(args_dict, lineage) # boolean values are the only ones that don't get casted correctly with, say, bool('false') typecast = param.type if param.type is not bool else CAST_BOOLEAN try: validated_value = map(typecast, arg) if param.is_list else typecast(arg) except ValueError: # type casting failed validated_value = arg # just keep it as a string (or list of strings) if enforce_type: # but raise a warning or exception depending on enforcement level if enforce_type == 1: warnings.warn('Argument %s is of wrong type. Expected %s, got: %s' % (':'.join(lineage), TYPE_TO_CTDTYPE[param.type], arg)) else: raise ArgumentTypeError(param, arg) if enforce_restrictions and param.restrictions and not param.restrictions.check(validated_value): if enforce_restrictions == 1: warnings.warn('Argument restrictions for %s violated. Restriction: %s. Value: %s' % (':'.join(lineage), param.restrictions.ctd_restriction_string(), validated_value)) else: raise ArgumentRestrictionError(param, validated_value) set_nested_key(validated_args, lineage, validated_value) except KeyError: # argument was not found, checking whether required and using defaults if not if param.required: if not enforce_required: continue # this argument will be missing from the dict as required fields have no default value elif enforce_required == 1: warnings.warn('Required argument %s missing' % ':'.join(lineage), UserWarning) else: raise ArgumentMissingError(param) else: set_nested_key(validated_args, lineage, param.default) return validated_args def parse_cl_args(self, cl_args=None, prefix='--', short_prefix="-", get_remaining=False): """Parses command line arguments `cl_args` (either a string or a list like sys.argv[1:]) assuming that parameter names are prefixed by `prefix` (default '--'). Returns a nested dictionary with found arguments. Note that parameters have to be registered in the model to be parsed and returned. Remaining (unmatchable) command line arguments can be accessed if the method is called with `get_remaining`. In this case, the method returns a tuple, whose first element is the argument dictionary, the second a list of unmatchable command line options. """ cl_parser = argparse.ArgumentParser() for param in self.list_parameters(): lineage = param.get_lineage(name_only=True) short_lineage = param.get_lineage(name_only=True, short_name=True) cl_arg_kws = {} # argument processing info passed to argparse in keyword arguments, we build them here if param.type is bool: # boolean flags are not followed by a value, only their presence is required cl_arg_kws['action'] = 'store_true' else: # we take every argument as string and cast them only later in validate_args() if # explicitly asked for. This is because we don't want to deal with type exceptions # at this stage, and prefer the multi-leveled strictness settings in validate_args() cl_arg_kws['type'] = str if param.is_list: # or '+' rather? Should we allow empty lists here? If default is a proper list with elements # that we want to clear, this would be the only way to do it so I'm inclined to use '*' cl_arg_kws['nargs'] = '*' if param.default is not _Null(): cl_arg_kws['default'] = param.default if param.required: cl_arg_kws['required'] = True # hardcoded 'group:subgroup:param1' if all(a is not _Null for a in short_lineage): cl_parser.add_argument(short_prefix+':'.join(short_lineage), prefix + ':'.join(lineage), **cl_arg_kws) else: cl_parser.add_argument(prefix + ':'.join(lineage), **cl_arg_kws) cl_arg_list = cl_args.split() if isinstance(cl_args, str) else cl_args #if no arguments are given print help if not cl_arg_list: cl_arg_list.append("-h") parsed_args, rest = cl_parser.parse_known_args(cl_arg_list) res_args = {} # OrderedDict() for param_name, value in vars(parsed_args).iteritems(): # None values are created by argparse if it didn't find the argument or default=None, we skip params # that dont have a default value if value is not None or value == self.parameters.parameters[param_name].default: set_nested_key(res_args, param_name.split(':'), value) return res_args if not get_remaining else (res_args, rest) def generate_ctd_tree(self, arg_dict=None, log=None, cli=False, prefix='--'): """Generates an XML ElementTree from the model and returns the top Element object, that can be output to a file (CTDModel.write_ctd() does everything needed if the user doesn't need access to the actual element-tree). Calling this function without any arguments generates the tool-describing CTD with default values. For parameter-storing and logging optional arguments can be passed: `arg_dict`: nested dictionary with values to be used instead of defaults. `log`: dictionary with the following optional keys: 'time_start' and 'time_finish': proper XML date strings (eg. datetime.datetime.now(pytz.utc).isoformat()) 'status': exit status 'output': standard output or whatever output the user intends to log 'warning': warning logs 'error': standard error or whatever error log the user wants to store `cli`: boolean whether or not cli elements should be generated (needed for GenericKNIMENode for example) """ tool_attribs = OrderedDict() tool_attribs['version'] = self.version tool_attribs['name'] = self.name tool_attribs['xmlns:xsi'] = "http://www.w3.org/2001/XMLSchema-instance" tool_attribs['xsi:schemaLocation'] = "https://github.com/genericworkflownodes/CTDopts/raw/master/schemas/CTD_0_3.xsd" opt_attribs = ['docurl', 'category'] for oo in opt_attribs: if oo in self.opt_attribs: tool_attribs[oo] = self.opt_attribs[oo] tool = Element('tool', tool_attribs) # CTD root opt_elements = ['manual', 'description', 'executableName', 'executablePath'] for oo in opt_elements: if oo in self.opt_attribs: SubElement(tool, oo).text = self.opt_attribs[oo] if log is not None: # log is supposed to be a dictionary, with the following keys (none of them being required): # time_start, time_finish, status, output, warning, error # generate log_node = SubElement(tool, 'log') if 'time_start' in log: # expect proper XML date string like datetime.datetime.now(pytz.utc).isoformat() log_node.attrib['executionTimeStart'] = log['time_start'] if 'time_finish' in log: log_node.attrib['executionTimeStop'] = log['time_finish'] if 'status' in log: log_node.attrib['executionStatus'] = log['status'] if 'output' in log: SubElement(log_node, 'executionMessage').text = log['output'] if 'warning' in log: SubElement(log_node, 'executionWarning').text = log['warning'] if 'error' in log: SubElement(log_node, 'executionError').text = log['error'] # XML.ETREE SYNTAX params = SubElement(tool, 'PARAMETERS', { 'version': '1.6.2', 'xmlns:xsi': "http://www.w3.org/2001/XMLSchema-instance", 'xsi:noNamespaceSchemaLocation': "https://github.com/genericworkflownodes/CTDopts/raw/master/schemas/Param_1_6_2.xsd" }) # This seems to be some OpenMS hack (defining name, description, version for the second time) # but I'll stick to it for consistency top_node = SubElement(params, 'NODE', name=self.name, description=self.opt_attribs.get('description', '')) SubElement(top_node, 'ITEM', name='version', value=self.version, type='string', description='Version of the tool that generated this parameters file.', tags='advanced') # all the above was boilerplate, now comes the actual parameter tree generation args_top_node = self.parameters._xml_node(arg_dict) top_node.append(args_top_node) if cli: cli_node = SubElement(tool, "cli") for e in self.parameters._cli_node(parent_name=self.name, prefix=prefix): cli_node.append(e) # # LXML w/ pretty print syntax # return tostring(tool, pretty_print=True, xml_declaration=True, encoding="UTF-8") # xml.etree syntax (no pretty print available, so we use xml.dom.minidom stuff) return tool def write_ctd(self, out_file, arg_dict=None, log=None, cli=False): """Generates a CTD XML from the model and writes it to `out_file`, which is either a string to a file path or a stream with a write() method. Calling this function without any arguments besides `out_file` generates the tool-describing CTD with default values. For parameter-storing and logging optional arguments can be passed: `arg_dict`: nested dictionary with values to be used instead of defaults. `log`: dictionary with the following optional keys: 'time_start' and 'time_finish': proper XML date strings (eg. datetime.datetime.now(pytz.utc).isoformat()) 'status': exit status 'output': standard output or whatever output the user intends to log 'warning': warning logs 'error': standard error or whatever error log the user wants to store `cli`: boolean whether or not cli elements should be generated (needed for GenericKNIMENode for example) """ xml_content = parseString(tostring(self.generate_ctd_tree(arg_dict, log, cli), encoding="UTF-8")).toprettyxml() if isinstance(out_file, str): # if out_file is a string, we create and write the file with open(out_file, 'w') as f: f.write(xml_content) else: # otherwise we assume it's a writable stream and write into that. out_file.write(xml_content) def args_from_file(filename): """Takes a CTD file and returns a nested dictionary with all argument values found. It's not linked to a model, so there's no type casting or validation done on the arguments. This is useful for users who just want to access arguments in CTD files without having to deal with building a CTD model. If type casting or validation is required, two things can be done to hack one's way around it: Build a model from the same file and call get_defaults() on it. This takes advantage from the fact that when building a model from a CTD, the value attributes are used as defaults. Although one shouldn't build a model from an argument storing CTD (as opposed to tool describing CTDs) there's no technical obstacle to do so. """ def get_args(element, base=None): # recursive argument lookup if encountering s if element.tag == 'NODE': current_group = {} # OrderedDict() for child in element: get_args(child, current_group) if base is not None: base[element.attrib['name']] = current_group else: # top level is the only one called with base=None. # As the argument parsing is recursive, whenever the top node finishes, we are done # with the parsing and have to return the results. return current_group elif element.tag == 'ITEM': if 'value' in element.attrib: base[element.attrib['name']] = element.attrib['value'] elif element.tag == 'ITEMLIST': if element.getchildren(): base[element.attrib['name']] = [listitem.attrib['value'] for listitem in element] root = parse(filename).getroot() param_root = root if root.tag == 'PARAMETERS' else root.find('PARAMETERS') parameters = param_root.find('NODE').find('NODE') return get_args(parameters, base=None) def parse_cl_directives(cl_args, write_tool_ctd='write_tool_ctd', write_param_ctd='write_param_ctd', input_ctd='input_ctd', prefix='--'): '''Parses command line CTD processing directives. `write_tool_ctd`, `write_param_ctd` and `input_ctd` string are customizable, and will be parsed for in command line. `prefix` should be one or two dashes, default is '--'. Returns a dictionary with keys 'write_tool_ctd': if flag set, either True or the filename provided in command line. Otherwise None. 'write_param_ctd': if flag set, either True or the filename provided in command line. Otherwise None. 'input_ctd': filename if found, otherwise None ''' parser = argparse.ArgumentParser() parser.add_argument(prefix + write_tool_ctd, nargs='*') parser.add_argument(prefix + write_param_ctd, nargs='*') parser.add_argument(prefix + input_ctd, type=str) cl_arg_list = cl_args.split() if isinstance(cl_args, str) else cl_args # string or list of args directives, rest = parser.parse_known_args(cl_arg_list) directives = vars(directives) transform = lambda x: None if x is None else True if x == [] else x[0] parsed_directives = {} parsed_directives['write_tool_ctd'] = transform(directives[write_tool_ctd]) parsed_directives['write_param_ctd'] = transform(directives[write_param_ctd]) parsed_directives['input_ctd'] = directives[input_ctd] return parsed_directives # TODO: ElementTree does not provide line information... maybe refactor using lxml or other parser that does support it? def validate_contains_keys(dictionary, keys, element_tag): for key in keys: assert key in dictionary, "Missing required attribute '%s' in %s element. Present attributes: %s" % \ (key, element_tag, ', '.join(['{0}="{1}"'.format(k, v) for k, v in dictionary.iteritems()])) CTDopts-1.2/CTDopts/__init__.py000066400000000000000000000001651315127446300163350ustar00rootroot00000000000000# Empty __init__.py. No dependencies to be checked for. Also, load the namespace explicitly. __author__ = 'andras86' CTDopts-1.2/LICENSE000066400000000000000000001045051315127446300137140ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. {one line to give the program's name and a brief idea of what it does.} Copyright (C) {year} {name of author} This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: {project} Copyright (C) {year} {fullname} This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . CTDopts-1.2/README.md000066400000000000000000000040461315127446300141650ustar00rootroot00000000000000# CTDopts `CTDopts` is a module for enabling tools with CTD reading/writing, argument parsing, validating and manipulating capabilities. Please check out [example.py](example.py) for an overview of CTDopt's features. ## Installing `CTDopts` is available in the Anaconda Cloud under the `workflowconversion` channel. You can install the latest stable release using `conda` by executing the following command: ```sh $ conda install --channel workflowconversion ctdopts ``` Or, if you want the latest, possibly unstable, version, you can clone the `CTDopts` repository from https://github.com/WorkflowConversion/CTDopts. ## Information for Developers In order to upload `CTDopts` to the Anaconda Cloud for distribution, you should familiarize yourself with the [Anaconda Cloud documentation on packages](https://docs.continuum.io/anaconda-cloud/user-guide/tasks/work-with-packages). A summary of the required steps to update `CTDopts` on the Anaconda Cloud is presented here: 1. Make sure you've installed the `anaconda-client` and `conda-build` packages using `conda`. This needs to be done once per development environment. 1. Commit your changes to the code locally. 1. Bump up the version. This is a two-fold process: 1. Update the [meta.yaml file](dist/conda/meta.yaml), in particular the `package.version` and `source.git_rev` properties. Commit your changes locally. 1. Tag the state of the repository using `git tag vX.Y`. 1. Push all changes to `CTDopts` repository. 1. Push the tag you just created (i.e., by invoking `git push origin --tags`). 1. Change your working directory to `dist/conda` and execute the following command (you will be asked for credentials to finalize the upload after the build): ```sh $ conda build . ``` **IMPORTANT:** The `conda` build process **will not** use your local repository, rather, it will use the revision and repository stated in your [meta.yaml file](dist/conda/meta.yaml) under the `source` property. This is why it is important to commit all your changes and to update the version before building/distributing. CTDopts-1.2/dist/000077500000000000000000000000001315127446300136455ustar00rootroot00000000000000CTDopts-1.2/dist/conda/000077500000000000000000000000001315127446300147315ustar00rootroot00000000000000CTDopts-1.2/dist/conda/bld.bat000066400000000000000000000000631315127446300161610ustar00rootroot00000000000000"%PYTHON%" setup.py install if errorlevel 1 exit 1 CTDopts-1.2/dist/conda/build.sh000066400000000000000000000000311315127446300163560ustar00rootroot00000000000000$PYTHON setup.py install CTDopts-1.2/dist/conda/meta.yaml000066400000000000000000000005501315127446300165430ustar00rootroot00000000000000package: name: ctdopts version: "1.2" source: git_rev: v1.2 git_url: https://github.com/WorkflowConversion/CTDopts.git build: noarch_python: True requirements: build: - python - setuptools run: - python test: imports: - CTDopts.CTDopts about: home: https://github.com/WorkflowConversion/CTDopts license_file: LICENSE CTDopts-1.2/example.py000066400000000000000000000267721315127446300147250ustar00rootroot00000000000000# or for easier access of certain commonly used module methods import datetime import pprint import pytz import CTDopts.CTDopts # once you installed it, it's just CTDopts from CTDopts.CTDopts import CTDModel, args_from_file, parse_cl_directives, flatten_dict, override_args, ArgumentRestrictionError # let's set up a PrettyPrinter so nested dictionaries are easier to follow later pp = pprint.PrettyPrinter(indent=4) pretty_print = pp.pprint # First, we'll set up a CTD model. There are two different ways to do that: # 1. Define it in Python using CTDopts.CTDModel's methods # 2. load it from a CTD file # Every CTD Model has to have at least a name and a version, plus any of the optional attributes below them. model = CTDModel( name='exampleTool', # required version='1.0', # required description='This is an example tool presenting CTDopts usage', manual='manual string', docurl='http://dummy.url/docurl.html', category='testing', executableName='exampletool', executablePath='/path/to/exec/exampletool-1.0/exampletool' ) # The parameters of the tool have to be registered the following way: model.add( 'positive_int', # parameter name type=int, # parameter type. For a list of CTD-supported types see CTDopts.CTDTYPE_TO_TYPE.keys() num_range=(0, None), # numeric range restriction: tuple with minimum and maximum values. None means unlimited default=5, tags=['advanced', 'magic'], # for certain workflow engines that make use of parameter tags description='A positive integer parameter' ) model.add( 'input_files', required=True, type='input-file', # or 'output-file' is_list=True, # for list parameters with an arbitrary number of values file_formats=['fastq', 'fastq.gz'], # filename restrictions description='A list of filenames to feed this dummy tool with' ) model.add( 'this_that', type=str, choices=['this', 'that'], # controlled vocabulary default='this', description='A controlled vocabulary parameter. Allowed values `this` or `that`.' ) # Certain tools may want to group parameters together. One can define them like this: subparams = model.add_group('subparams', 'Grouped settings') # register sub-parameters to a group: subparams.add( 'param_1', type=float, default=5.5, description='Some floating point setting.' ) subparams.add( 'param_2', is_list=True, type=float, tags=['advanced'], default=[0.0, 2.5, 5.0], description='A list of floating point settings' ) subsubparams = subparams.add_group('subsubparam', 'A group of sub-subsettings') subsubparams.add( 'param_3', type=int, default=2, description="A subsetting's subsetting" ) # Now we have a CTDModel. To write the model to a CTD (xml) file: print 'Model being written to exampleTool.ctd...\n' model.write_ctd('exampleTool.ctd') # However, if we already have a CTD model for a tool, we can spare the pain of defining it like above, we can just # load it from a file directly. Like this: print 'Model loaded from exampleTool.ctd...\n' model_2 = CTDModel(from_file='exampleTool.ctd') # We can list all the model's parameters. The below call will get a list of all Parameter objects registered in the model. # These objects store name, type, default, restriction, parent group etc. information we set above. params = model.list_parameters() print "For debugging purposes we can output a human readable representation of Parameter objects. Here's the first one:" print params[0] print # Let's print out the name attributes of these parameters. print 'The following parameters were registered in the model:' print [p.name for p in params] print # In the above model, certain parameters were registered under parameter groups. We can access their 'lineage' and see # their nesting levels. Let's display nesting levels separated by colons: print 'The same parameters with subgroup information, if they were registered under parameter groups:' print [':'.join(p.get_lineage(name_only=True)) for p in params] print # (Parameter.get_lineage() returns a list of ParameterGroups down to the leaf Parameter. `name_only` setting returns # only the names of the objects, instead of the actual Parameter objects. # Some of the parameters had default values in the model. We can get those: print 'A dictionary of parameters with default values, returned by CTDModel.get_defaults():' defaults = model_2.get_defaults() pretty_print(defaults) print print ('As you can see, parameter values are usually stored in nested dictionaries. If you want a flat dictionary, you can' 'get that using CTDopts.flatten_dict(). Flat keys can be either tuples of tree node (subgroup) names down to the parameter...') flat_defaults = flatten_dict(defaults) pretty_print(flat_defaults) print print '...or they can be strings where nesing levels are separated by colons:' flat_defaults_colon = flatten_dict(defaults, as_string=True) pretty_print(flat_defaults_colon) print print ('We can create dictionaries of arguments on our own that we want to validate against the model.' 'CTDopts can read them from argument-storing CTD files or from the command line, but we can just define them in a ' 'nested dictionary on our own as well. We start with defining them explicitly.') new_values = { 'positive_int': 111, 'input_files': ['file1.fastq', 'file2.fastq', 'file3.fastq'], 'subparams': {'param_1': '999.0'} } pretty_print(new_values) print print ("We can validate these arguments against the model, and get a dictionary with parameter types correctly casted " "and defaults set. Note that subparams:param_1 was casted from string to a floating point number because that's how it " "was defined in the model.") validated = model.validate_args(new_values) pretty_print(validated) print print ('We can write a CTD file containing these validated argument values. Just call CTDModel.write_ctd() with an extra ' 'parameter: the nested argument dictionary containing the actual values.') model.write_ctd('exampleTool_preset_params.ctd', validated) print print ('As mentioned earlier, CTDopts can load argument values from CTD files. Feel free to change some values in ' "exampleTool_preset_params.ctd you've just written, and load it back.") args_from_ctd = args_from_file('exampleTool_preset_params.ctd') pretty_print(args_from_ctd) print print ("Notice that all the argument values are strings now. This is because we didn't validate them against the model, " "just loaded some stuff from a file into a dictionary. If you want to cast them, call CTDModel.validate_args():") validated_2 = model.validate_args(args_from_ctd) pretty_print(validated_2) print print ("Now certain parameters may have restrictions that we might want to validate for as well. Let's set the parameter " "positive_int to a negative value, and try to validate it with a strictness level enforce_restrictions=1. This " "will register a warning, but still accept the value.") validated_2['positive_int'] = -5 _ = model.validate_args(validated_2, enforce_restrictions=1) print print ("Validation enforcement levels can be 0, 1 or 2 for type-casting, restriction-checking and required argument presence. " "They can be set with the keywords enforce_type, enforce_restrictions and enforce_required respectively. Let's increase " "strictness for restriction checking. CTDModel.validate_args() will now raise an exception that we'll catch:\n") try: model.validate_args(validated_2, enforce_restrictions=2) # , enforce_type=0, enforce_required=0 except ArgumentRestrictionError as ee: # other exceptions: ArgumentTypeError, ArgumentMissingError, all subclasses of Argumenterror print ee print print ("One might want to combine arguments loaded from a CTD file with arguments coming from elsewhere, like the command line." "In that case, the method CTDopts.override_args(*arg_dicts) creates a combined argument dictionary where argument values " "are always taken from the rightmost (last) dictionary that has them. Let's override a few parameters:") override = { 'this_that': 'that', 'positive_int': 777 } overridden = override_args(validated, override) pretty_print(overridden) print print ("So how to deal with command line arguments? If we have a model, we can look for its arguments. " "Call CTDModel.parse_cl_args() with either a string of the command line call or a list with the split words. " "By default, it will assume a '--' prefix before parameter names, but it can be overridden with prefix='-'." "Grouped parameters are expected in --group:subgroup:param_x format.") cl_args = model.parse_cl_args('--positive_int 44 --subparams:param_2 5.0 5.5 6.0 --input_files a.fastq b.fastq') pretty_print(cl_args) print # # you can get unmatchable command line arguments with get_remaining=True like: # cl_args, unparsed = model.parse_cl_args('--positive_int 44 --subparams:param_2 5.0 5.5 6.0 --unrelated_stuff abc', get_remaining=True) print ("Override other parameters with them, and validate it against the model:") overridden_with_cl = override_args(validated, cl_args) validated_3 = model.validate_args(overridden_with_cl) pretty_print(validated_3) print print ("One last thing: certain command line directives that are specific to CTD functionality can be parsed for, " "to help your script performing common tasks. These are CTD argument input, CTD model file writing and CTD argument " "file writing. CTDopts.parse_cl_directives() can also be customized as to what directives to look for if the defaults " "--input_ctd, --write_tool_ctd and --write_param_ctd respectively don't satisfy you.") directives_1 = parse_cl_directives('--input_ctd exampleTool_preset_params.ctd --write_param_ctd new_preset_params.ctd') pretty_print(directives_1) directives_2 = parse_cl_directives('-inctd exampleTool_preset_params_2.ctd -toolctd ', input_ctd='inctd', write_tool_ctd='toolctd', prefix='-') pretty_print(directives_2) # the returned dictionary always contains the following three keys: # 'input_ctd' # 'write_tool_ctd' # 'write_param_ctd' # and their values are either a filename (if it was passed), a boolean True, if the flag was set but no filename provided # (expecting the tool to use default values, like toolName.ctd) or None if the flag wasn't used at all. # for example, if directives['input_ctd'] is set, one would load arguments from that file with # CTDopts.args_from_file(directives['input_ctd']), validate them and run the tool. # If I found directives['write_tool_ctd'], I'd immediately output the tool's CTD model with # model.write_ctd(directives['write_tool_ctd']), etc. print ("Finally, writing CTDs with logging information, passing a dictionary with a 'log' keyword, using any or all of the " "fields shown below.") time_start = datetime.datetime.now(pytz.utc).isoformat() # do stuff output = 'Output of my program, however I generated or logged it' errors = 'Standard error output of my program, however I caught or redirected them' warnings = 'Warnings of my program' exitstatus = '1' time_finish = datetime.datetime.now(pytz.utc).isoformat() log = { 'time_start': time_start, # make sure to give it a legal XML date string if you can. 'time_finish': time_finish, # You can generate them with datetime.datetime.now(pytz.utc).isoformat() 'status': exitstatus, 'output': output, 'warning': warnings, 'error': errors } model.write_ctd('exampleTool_w_logging.ctd', validated_3, log) # Methods you might find helpful to deal with argument dictionaries (see docstrings): # CTDopts.set_nested_key(dictionary, tuple_w_levels, value) and # CTDopts.get_nested_key(dictionary, tuple_w_levels for nested dictionaries CTDopts-1.2/schemas/000077500000000000000000000000001315127446300143255ustar00rootroot00000000000000CTDopts-1.2/schemas/CTD_0_3.xsd000066400000000000000000000166521315127446300161320ustar00rootroot00000000000000 More detailed description of the tool (about 10 lines). One line description of the tool. Optionally a separate name for the executable can be specified here. Contains the path were the tool can be found using either the name element or (if set) the executableName. Defines rules to find the output of the tool and move it to the originally desired location. Name of the tool. Needs to pass following regex [[A-Z]|[a-z]][[0-9]|[A-Z]|[a-z]]+ i.e.\w URL to further documentation (WWW). The category gives information on the task the associated tool performs. It can be used to categorize different tools in a GUI. Wraps the information necessary to construct a command line call for the tool. Defines which ITEM from the parameter part is associated to cliElement. Wraps a single element of a command line call (e.g., the -v flag for verbosity) and it's associated arguments. To model a non-option argument just leave the optionIdentifier empty. The mapping defines the association between the cliElement and the PARAM part. Note: If the mapped parameter is boolean, the optionIdentifier will be added to the CLI only if the mapped value is true. A string used to prefix any associated values (e.g., "-v" for a boolean flag to turn on verbosity). A boolean attribute indicating whether or not the given cliElement can be expended to occur more then once on the command line. Defines if the cliElement is required to build the full command line, i.e., if required is set to false and the mapped parameter was not set the complete element will not be used on the final cli. Wraps the log informations from the call of the tool. ... Wraps the log informations from the call of the tool. ... ... Defines a relocation rule using a pattern to find the file and the targeted output file where the found file should be moved to. The referenced parameter which should be relocated. The location of the output file defined using following variables: %TEMP% - the temporary directory while executing %PWD% - the working directory while executing %BASENAME[PARAM]% - the base name of PARAM CTDopts-1.2/schemas/Param_1_6_2.xsd000066400000000000000000000073441315127446300170030ustar00rootroot00000000000000 Main parameters node. The type of the specified ITEM. Either input or output. Defines the possible types available in the type attribute of ITEM and ITEMLIST. CTDopts-1.2/setup.py000066400000000000000000000006201315127446300144120ustar00rootroot00000000000000from distutils.core import setup setup( name='CTDopts', version='1.1', packages=['CTDopts'], url='https://github.com/genericworkflownodes/CTDopts', license='', author='Andras Szolek', author_email='', py_modules=['CTDopts/CTDopts'], description='A module for enabling tools with CTD reading/writing, argument parsing, validating and manipulating capabilities.' )