diff --git a/README.md b/README.md index 7b7c641..8970b1b 100644 --- a/README.md +++ b/README.md @@ -1,37 +1,166 @@ # CTDConverter - Given one or more CTD files, `CTD2Converter` generates the needed wrappers to include them in workflow engines, such as Galaxy and CWL. ## Dependencies +`CTDConverter` has the following python dependencies: -`CTDConverter` relies on [CTDopts]. The dependencies of each of the converters are as follows: +- [CTDopts] +- `lxml` +- `pyyaml` -### Galaxy Converter - -- Generation of Galaxy ToolConfig files relies on `lxml` to generate nice-looking XML files. - -## Installing Dependencies -You can install the [CTDopts] and `lxml` modules via `conda`, like so: +### Installing Dependencies +The easiest way is to install [CTDopts] and all required dependencies modules via `conda`, like so: ```sh -$ conda install lxml +$ conda install lxml pyyaml $ conda install -c workflowconversion ctdopts ``` -Note that the [CTDopts] module is available on the `workflowconversion` channel. +Note that [CTDopts] is a python module available on the `workflowconversion` channel. Of course, you can just download [CTDopts] and make it available through your `PYTHONPATH` environment variable. To get more information about how to install python modules, visit: https://docs.python.org/2/install/. -Of course, you can just download [CTDopts] and make it available through your `PYTHONPATH` environment variable. To get more information about how to install python modules, visit: https://docs.python.org/2/install/. +### Issues with `libxml2` and Schema Validation +`lxml` depends on `libxml2`. When you install `lxml` you'll get the latest version of `libxml2` (2.9.4) by default. You would usually want the latest version, but there is, however, a bug in validating XML files against a schema in this version of `libxml2`. + +If you require validation of input CTDs against a schema (which we recommend), you will need to downgrade to the latest known version of `libxml2` that works, namely, 2.9.2. You can do it by executing the following command **after** you've installed all other dependencies: + +```sh +$ conda install -y libxml2=2.9.2 +``` + +You will be warned that this command will downgrade some packages, which is fine, don't worry. The `-y` flag tells `conda` to perform the installation without confirmation. + +## How to install `CTDConverter` +`CTDConverter` is not a python module, rather, a series of scripts, so installing it is as easy as downloading the source code from https://github.com/genericworkflownodes/CTDConverter. + +## Usage +The first thing that you need to tell `CTDConverter` is the output format of the converted wrappers. `CTDConverter` supports conversion of CTDs into Galaxy and CWL. Invoking it is as simple as follows: + + $ python convert.py [FORMAT] [ADDITIONAL_PARAMETERS ...] + +Here `[FORMAT]` can be any of the supported formats (i.e., `cwl`, `galaxy`). `CTDConverter` offers a series of format-specific scripts and we've designed these scripts to behave *somewhat* similarly. All converter scripts have the same core functionality, that is, read CTD files, parse them using [CTDopts], validate against a schema, etc. Of course, each converter script might add extra functionality that is not present in other engines, for instance, only the Galaxy converter script supports generation of a `tool_conf.xml` file. + +The following sections in this file describe the parameters that all converter scripts share. + +Please refer to the detailed documentation for each of the converters for more information: + +- [Generation of Galaxy ToolConfig files](galaxy/README.md) +- [Generation of CWL task files](cwl/README.md) -## How to install CTDConverter +## Converting a single CTD +In its simplest form, the converter takes an input CTD file and generates an output file. The following usage of `CTDConverter`: -1. Download the source code from https://github.com/genericworkflownodes/CTDConverter. + $ python convert.py [FORMAT] -i /data/sample_input.ctd -o /data/sample_output.xml -## Usage +will parse `/data/sample_input.ctd` and generate an appropriate converted file under `/data/sample_output.xml`. The generated file can be added to your workflow engine as usual. -Check the detailed documentation for each of the converters: +## Converting several CTDs +When converting several CTDs, the expected value for the `-o`/`--output` parameter is a folder. For example: -- [Generation of Galaxy ToolConfig files](galaxy/README.md) + $ python convert.py [FORMAT] -i /data/ctds/one.ctd /data/ctds/two.ctd -o /data/converted-files + +Will convert `/data/ctds/one.ctd` into `/data/converted-files/one.[EXT]` and `/data/ctds/two.ctd` into `/data/converted-files/two.[EXT]`. Each converter has a preferred extension, here shown as a variable (`[EXT]`). Galaxy prefers `xml`, while CWL prefers `cwl`. + +You can use wildcard expansion, as supported by most modern operating systems: + + $ python convert.py [FORMAT] -i /data/ctds/*.ctd -o /data/converted-files + +## Common Parameters +### Input File(s) +* Purpose: Provide input CTD file(s) to convert. +* Short/long version: `-i` / `--input` +* Required: yes. +* Taken values: a list of input CTD files. +Example: + +Any of the following invocations will convert `/data/input_one.ctd` and `/data/input_two.ctd`: + + $ python convert.py [FORMAT] -i /data/input_one.ctd -i /data/input_two.ctd -o /data/generated + $ python convert.py [FORMAT] -i /data/input_one.ctd /data/input_two.ctd -o /data/generated + $ python convert.py [FORMAT] --input /data/input_one.ctd /data/input_two.ctd -o /data/generated + $ python convert.py [FORMAT] --input /data/input_one.ctd --input /data/input_two.ctd -o /data/generated + +The following invocation will convert `/data/input.ctd` into `/data/output.xml`: + + $ python convert.py [FORMAT] -i /data/input.ctd -o /data/output.xml + +Of course, you can also use wildcards, which will be automatically expanded by any modern operating system. This is extremely useful if you want to convert several files at a time. Let's assume that the folder `/data/ctds` contains three files: `input_one.ctd`, `input_two.ctd` and `input_three.ctd`. The following two invocations will produce the same output in the `/data/wrappers` folder: + + $ python convert.py [FORMAT] -i /data/input_one.ctd /data/input_two.ctd /data/input_three.ctd -o /data/wrappers + $ python convert.py [FORMAT] -i /data/*.ctd -o /data/wrappers + +### Output Destination +* Purpose: Provide output destination for the converted wrapper files. +* Short/long version: `-o` / `--output-destination` +* Required: yes. +* Taken values: if a single input file is given, then a single output file is expected. If multiple input files are given, then an existent folder, in which all converted CTDs will be written, is expected. + +Examples: + +A single input is given, and the output will be generated into `/data/output.xml`: + + $ python convert.py [FORMAT] -i /data/input.ctd -o /data/output.xml + +Several inputs are given. The output is the already existent folder, `/data/wrappers`, and at the end of the operation, the files `/data/wrappers/input_one.[EXT]` and `/data/wrappers/input_two.[EXT]` will be generated: + + $ python convert.py [FORMAT] -i /data/ctds/input_one.ctd /data/ctds/input_two.ctd -o /data/stubs + +### Blacklisting Parameters +* Purpose: Some parameters present in the CTD are not to be exposed on the output files. Think of parameters such as `--help`, `--debug` that might won't make much sense to be exposed to final users in a workflow management system. +* Short/long version: `-b` / `--blacklist-parameters` +* Required: no. +* Taken values: A list of parameters to be blacklisted. + +Example: + + $ pythonconvert.py [FORMAT] ... -b h help quiet + +In this case, `CTDConverter` will not process any of the parameters named `h`, `help`, or `quiet`, that is, they will not appear in the generated output files. + +### Schema Validation +* Purpose: Provide validation of input CTDs against a schema file (i.e, a XSD file). +* Short/long version: `-V` / `--validation-schema` +* Required: no. +* Taken values: location of the schema file (e.g., CTD.xsd). + +CTDs can be validated against a schema. The master version of the schema can be found under [CTDSchema]. + +If a schema is provided, all input CTDs will be validated against it. + +**NOTE:** Please make sure to read the [section on issues with schema validation](#issues-with-libxml2-and-schema-validation) if you require validation of CTDs against a schema. + +### Hardcoding Parameters +* Purpose: Fixing the value of a parameter and hide it from the end user. +* Short/long version: `-p` / `--hardcoded-parameters` +* Required: no. +* Taken values: The path of a file containing the mapping between parameter names and hardcoded values to use. + +It is sometimes required that parameters are hidden from the end user in workflow systems and that they take a predetermined, fixed value. Allowing end users to control parameters similar to `--verbosity`, `--threads`, etc., might create more problems than solving them. For this purpose, the parameter `p`/`--hardcoded-parameters` takes the path of a file that contains up to three columns separated by whitespace that map parameter names to the hardcoded value. The first column contains the name of the parameter and the second one the hardcoded value. The first two columns are mandatory. + +If the parameter is to be hardcoded only for certain tools, a third column containing a comma separated list of tool names for which the hardcoding will apply can be added. + +Lines starting with `#` will be ignored. The following is an example of a valid file: + + # Parameter name # Value # Tool(s) + threads 8 + mode quiet + xtandem_executable xtandem XTandemAdapter + verbosity high Foo, Bar + +The parameters `threads` and `mode` will be set to `8` and `quiet`, respectively, for all parsed CTDs. However, the `xtandem_executable` parameter will be set to `xtandem` only for the `XTandemAdapter` tool. Similarly, the parameter `verbosity` will be set to `high` for the `Foo` and `Bar` tools only. + +### Providing a default executable Path +* Purpose: Help workflow engines locate tools by providing a path. +* Short/long version: `-x` / `--default-executable-path` +* Required: no. +* Taken values: The default executable path of the tools in the target workflow engine. + +CTDs can contain an `` element that will be used when executing the tool binary. If this element is missing, the value provided by this parameter will be used as a prefix when building the appropriate sections in the output files. + +The following invocation of the converter will use `/opt/suite/bin` as a prefix when providing the executable path in the output files for any input CTD that lacks the `` section: + + $ python convert.py [FORMAT] -x /opt/suite/bin ... + [CTDopts]: https://github.com/genericworkflownodes/CTDopts diff --git a/common/__init__.py b/common/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/common/exceptions.py b/common/exceptions.py new file mode 100644 index 0000000..ef398d3 --- /dev/null +++ b/common/exceptions.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python +# encoding: utf-8 + +""" +@author: delagarza +""" + +from CTDopts.CTDopts import ModelError + + +class CLIError(Exception): + # Generic exception to raise and log different fatal errors. + def __init__(self, msg): + super(CLIError).__init__(type(self)) + self.msg = "E: %s" % msg + + def __str__(self): + return self.msg + + def __unicode__(self): + return self.msg + + +class InvalidModelException(ModelError): + def __init__(self, message): + super(InvalidModelException, self).__init__() + self.message = message + + def __str__(self): + return self.message + + def __repr__(self): + return self.message + + +class ApplicationException(Exception): + def __init__(self, msg): + super(ApplicationException).__init__(type(self)) + self.msg = msg + + def __str__(self): + return self.msg + + def __unicode__(self): + return self.msg \ No newline at end of file diff --git a/common/logger.py b/common/logger.py new file mode 100644 index 0000000..4ba517a --- /dev/null +++ b/common/logger.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python +# encoding: utf-8 +import sys + +MESSAGE_INDENTATION_INCREMENT = 2 + + +def _get_indented_text(text, indentation_level): + return ("%(indentation)s%(text)s" % + {"indentation": " " * (MESSAGE_INDENTATION_INCREMENT * indentation_level), + "text": text}) + + +def warning(warning_text, indentation_level=0): + sys.stdout.write(_get_indented_text("WARNING: %s\n" % warning_text, indentation_level)) + + +def error(error_text, indentation_level=0): + sys.stderr.write(_get_indented_text("ERROR: %s\n" % error_text, indentation_level)) + + +def info(info_text, indentation_level=0): + sys.stdout.write(_get_indented_text("INFO: %s\n" % info_text, indentation_level)) diff --git a/common/utils.py b/common/utils.py new file mode 100644 index 0000000..2ba2bbd --- /dev/null +++ b/common/utils.py @@ -0,0 +1,194 @@ +#!/usr/bin/env python +# encoding: utf-8 +import ntpath +import os + +from lxml import etree +from string import strip +from logger import info, error, warning + +from common.exceptions import ApplicationException +from CTDopts.CTDopts import CTDModel + + +MESSAGE_INDENTATION_INCREMENT = 2 + + +# simple struct-class containing a tuple with input/output location and the in-memory CTDModel +class ParsedCTD: + def __init__(self, ctd_model=None, input_file=None, suggested_output_file=None): + self.ctd_model = ctd_model + self.input_file = input_file + self.suggested_output_file = suggested_output_file + + +class ParameterHardcoder: + def __init__(self): + # map whose keys are the composite names of tools and parameters in the following pattern: + # [ToolName][separator][ParameterName] -> HardcodedValue + # if the parameter applies to all tools, then the following pattern is used: + # [ParameterName] -> HardcodedValue + + # examples (assuming separator is '#'): + # threads -> 24 + # XtandemAdapter#adapter -> xtandem.exe + # adapter -> adapter.exe + self.separator = "!" + self.parameter_map = {} + + # the most specific value will be returned in case of overlap + def get_hardcoded_value(self, parameter_name, tool_name): + # look for the value that would apply for all tools + generic_value = self.parameter_map.get(parameter_name, None) + specific_value = self.parameter_map.get(self.build_key(parameter_name, tool_name), None) + if specific_value is not None: + return specific_value + + return generic_value + + def register_parameter(self, parameter_name, parameter_value, tool_name=None): + self.parameter_map[self.build_key(parameter_name, tool_name)] = parameter_value + + def build_key(self, parameter_name, tool_name): + if tool_name is None: + return parameter_name + return "%s%s%s" % (parameter_name, self.separator, tool_name) + + +def validate_path_exists(path): + if not os.path.isfile(path) or not os.path.exists(path): + raise ApplicationException("The provided path (%s) does not exist or is not a valid file path." % path) + + +def validate_argument_is_directory(args, argument_name): + file_name = getattr(args, argument_name) + if file_name is not None and os.path.isdir(file_name): + raise ApplicationException("The provided output file name (%s) points to a directory." % file_name) + + +def validate_argument_is_valid_path(args, argument_name): + paths_to_check = [] + # check if we are handling a single file or a list of files + member_value = getattr(args, argument_name) + if member_value is not None: + if isinstance(member_value, list): + for file_name in member_value: + paths_to_check.append(strip(str(file_name))) + else: + paths_to_check.append(strip(str(member_value))) + + for path_to_check in paths_to_check: + validate_path_exists(path_to_check) + + +# taken from +# http://stackoverflow.com/questions/8384737/python-extract-file-name-from-path-no-matter-what-the-os-path-format +def get_filename(path): + head, tail = ntpath.split(path) + return tail or ntpath.basename(head) + + +def get_filename_without_suffix(path): + root, ext = os.path.splitext(os.path.basename(path)) + return root + + +def parse_input_ctds(xsd_location, input_ctds, output_destination, output_file_extension): + is_converting_multiple_ctds = len(input_ctds) > 1 + parsed_ctds = [] + schema = None + if xsd_location is not None: + try: + info("Loading validation schema from %s" % xsd_location, 0) + schema = etree.XMLSchema(etree.parse(xsd_location)) + except Exception, e: + error("Could not load validation schema %s. Reason: %s" % (xsd_location, str(e)), 0) + else: + info("Validation against a schema has not been enabled.", 0) + for input_ctd in input_ctds: + try: + if schema is not None: + validate_against_schema(input_ctd, schema) + output_file = output_destination + # if multiple inputs are being converted, we need to generate a different output_file for each input + if is_converting_multiple_ctds: + output_file = os.path.join(output_file, + get_filename_without_suffix(input_ctd) + '.' + output_file_extension) + parsed_ctds.append(ParsedCTD(CTDModel(from_file=input_ctd), input_ctd, output_file)) + except Exception, e: + error(str(e), 1) + continue + return parsed_ctds + + +def flatten_list_of_lists(args, list_name): + setattr(args, list_name, [item for sub_list in getattr(args, list_name) for item in sub_list]) + + +def validate_against_schema(ctd_file, schema): + try: + parser = etree.XMLParser(schema=schema) + etree.parse(ctd_file, parser=parser) + except etree.XMLSyntaxError, e: + raise ApplicationException("Invalid CTD file %s. Reason: %s" % (ctd_file, str(e))) + + +def add_common_parameters(parser, version, last_updated): + parser.add_argument("FORMAT", default=None, help="Output format (mandatory). Can be one of: cwl, galaxy.") + parser.add_argument("-i", "--input", dest="input_files", default=[], required=True, nargs="+", action="append", + help="List of CTD files to convert.") + parser.add_argument("-o", "--output-destination", dest="output_destination", required=True, + help="If multiple input files are given, then a folder in which all converted " + "files will be generated is expected; " + "if a single input file is given, then a destination file is expected.") + parser.add_argument("-x", "--default-executable-path", dest="default_executable_path", + help="Use this executable path when is not present in the CTD", + default=None, required=False) + parser.add_argument("-b", "--blacklist-parameters", dest="blacklisted_parameters", default=[], nargs="+", + action="append", + help="List of parameters that will be ignored and won't appear on the galaxy stub", + required=False) + parser.add_argument("-p", "--hardcoded-parameters", dest="hardcoded_parameters", default=None, required=False, + help="File containing hardcoded values for the given parameters. Run with '-h' or '--help' " + "to see a brief example on the format of this file.") + parser.add_argument("-V", "--validation-schema", dest="xsd_location", default=None, required=False, + help="Location of the schema to use to validate CTDs. If not provided, no schema validation " + "will take place.") + + # TODO: add verbosity, maybe? + program_version = "v%s" % version + program_build_date = str(last_updated) + program_version_message = '%%(prog)s %s (%s)' % (program_version, program_build_date) + parser.add_argument("-v", "--version", action='version', version=program_version_message) + + +def parse_hardcoded_parameters(hardcoded_parameters_file): + parameter_hardcoder = ParameterHardcoder() + if hardcoded_parameters_file is not None: + line_number = 0 + with open(hardcoded_parameters_file) as f: + for line in f: + line_number += 1 + if line is None or not line.strip() or line.strip().startswith("#"): + pass + else: + # the third column must not be obtained as a whole, and not split + parsed_hardcoded_parameter = line.strip().split(None, 2) + # valid lines contain two or three columns + if len(parsed_hardcoded_parameter) != 2 and len(parsed_hardcoded_parameter) != 3: + warning("Invalid line at line number %d of the given hardcoded parameters file. Line will be" + "ignored:\n%s" % (line_number, line), 0) + continue + + parameter_name = parsed_hardcoded_parameter[0] + hardcoded_value = parsed_hardcoded_parameter[1] + tool_names = None + if len(parsed_hardcoded_parameter) == 3: + tool_names = parsed_hardcoded_parameter[2].split(',') + if tool_names: + for tool_name in tool_names: + parameter_hardcoder.register_parameter(parameter_name, hardcoded_value, tool_name.strip()) + else: + parameter_hardcoder.register_parameter(parameter_name, hardcoded_value) + + return parameter_hardcoder diff --git a/convert.py b/convert.py new file mode 100644 index 0000000..2ca3d38 --- /dev/null +++ b/convert.py @@ -0,0 +1,265 @@ +import os +import sys +import traceback +import common.utils as utils + +from argparse import ArgumentParser +from argparse import RawDescriptionHelpFormatter +from common.exceptions import ApplicationException, ModelError + + +__all__ = [] +__version__ = 2.0 +__date__ = '2014-09-17' +__updated__ = '2017-08-09' + +program_version = "v%s" % __version__ +program_build_date = str(__updated__) +program_version_message = '%%(prog)s %s (%s)' % (program_version, program_build_date) +program_short_description = "CTDConverter - A project from the WorkflowConversion family " \ + "(https://github.com/WorkflowConversion/CTDConverter)" +program_usage = ''' +USAGE: + + $ python convert.py [FORMAT] [ARGUMENTS ...] + +FORMAT can be either one of the supported output formats: cwl, galaxy. + +There is one converter for each supported FORMAT, each taking a different set of arguments. Please consult the detailed +documentation for each of the converters. Nevertheless, all converters have the following common parameters/options: + + +I - Parsing a single CTD file and convert it: + + $ python convert.py [FORMAT] -i [INPUT_FILE] -o [OUTPUT_FILE] + + +II - Parsing several CTD files, output converted wrappers in a given folder: + + $ python converter.py [FORMAT] -i [INPUT_FILES] -o [OUTPUT_DIRECTORY] + + +III - Hardcoding parameters + + It is possible to hardcode parameters. This makes sense if you want to set a tool in 'quiet' mode or if your tools + support multi-threading and accept the number of threads via a parameter, without giving end users the chance to + change the values for these parameters. + + In order to generate hardcoded parameters, you need to provide a simple file. Each line of this file contains + two or three columns separated by whitespace. Any line starting with a '#' will be ignored. The first column contains + the name of the parameter, the second column contains the value that will always be set for this parameter. Only the + first two columns are mandatory. + + If the parameter is to be hardcoded only for a set of tools, then a third column can be added. This column contains + a comma-separated list of tool names for which the parameter will be hardcoded. If a third column is not present, + then all processed tools containing the given parameter will get a hardcoded value for it. + + The following is an example of a valid file: + + ##################################### HARDCODED PARAMETERS example ##################################### + # Every line starting with a # will be handled as a comment and will not be parsed. + # The first column is the name of the parameter and the second column is the value that will be used. + + # Parameter name # Value # Tool(s) + threads 8 + mode quiet + xtandem_executable xtandem XTandemAdapter + verbosity high Foo, Bar + + ######################################################################################################### + + Using the above file will produce a command-line similar to: + + [TOOL] ... -threads 8 -mode quiet ... + + for all tools. For XTandemAdapter, however, the command-line will look like: + + XtandemAdapter ... -threads 8 -mode quiet -xtandem_executable xtandem ... + + And for tools Foo and Bar, the command-line will be similar to: + + Foo -threads 8 -mode quiet -verbosity high ... + + + IV - Engine-specific parameters + + i - Galaxy + + a. Providing file formats, mimetypes + + Galaxy supports the concept of file format in order to connect compatible ports, that is, input ports of a + certain data format will be able to receive data from a port from the same format. This converter allows you + to provide a personalized file in which you can relate the CTD data formats with supported Galaxy data formats. + The layout of this file consists of lines, each of either one or four columns separated by any amount of + whitespace. The content of each column is as follows: + + * 1st column: file extension + * 2nd column: data type, as listed in Galaxy + * 3rd column: full-named Galaxy data type, as it will appear on datatypes_conf.xml + * 4th column: mimetype (optional) + + The following is an example of a valid "file formats" file: + + ########################################## FILE FORMATS example ########################################## + # Every line starting with a # will be handled as a comment and will not be parsed. + # The first column is the file format as given in the CTD and second column is the Galaxy data format. The + # second, third, fourth and fifth columns can be left empty if the data type has already been registered + # in Galaxy, otherwise, all but the mimetype must be provided. + + # CTD type # Galaxy type # Long Galaxy data type # Mimetype + csv tabular galaxy.datatypes.data:Text + fasta + ini txt galaxy.datatypes.data:Text + txt + idxml txt galaxy.datatypes.xml:GenericXml application/xml + options txt galaxy.datatypes.data:Text + grid grid galaxy.datatypes.data:Grid + ########################################################################################################## + + Note that each line consists precisely of either one, three or four columns. In the case of data types already + registered in Galaxy (such as fasta and txt in the above example), only the first column is needed. In the + case of data types that haven't been yet registered in Galaxy, the first three columns are needed + (mimetype is optional). + + For information about Galaxy data types and subclasses, see the following page: + https://wiki.galaxyproject.org/Admin/Datatypes/Adding%20Datatypes + + + b. Finer control over which tools will be converted + + Sometimes only a subset of CTDs needs to be converted. It is possible to either explicitly specify which tools + will be converted or which tools will not be converted. + + The value of the -s/--skip-tools parameter is a file in which each line will be interpreted as the name of a + tool that will not be converted. Conversely, the value of the -r/--required-tools is a file in which each line + will be interpreted as a tool that is required. Only one of these parameters can be specified at a given time. + + The format of both files is exactly the same. As stated before, each line will be interpreted as the name of a + tool. Any line starting with a '#' will be ignored. + + + ii - CWL + + There are, for now, no CWL-specific parameters or options. + +''' + +program_license = '''%(short_description)s + +Copyright 2017, WorklfowConversion + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +%(usage)s +''' % {'short_description': program_short_description, 'usage': program_usage} + + +def main(argv=None): + if argv is None: + argv = sys.argv + else: + sys.argv.extend(argv) + + # check that we have, at least, one argument provided + # at this point we cannot parse the arguments, because each converter takes different arguments, meaning each + # converter will register its own parameters after we've registered the basic ones... we have to do it old school + if len(argv) < 2: + utils.error('Not enough arguments provided') + print('\nUsage: $ python convert.py [TARGET] [ARGUMENTS]\n\n' + + 'Where:\n' + + ' target: one of \'cwl\' or \'galaxy\'\n\n' + + 'Run again using the -h/--help option to print more detailed help.\n') + return 1 + + # TODO: at some point this should look like real software engineering and use a map containing converter instances + # whose keys would be the name of the converter (e.g., cwl, galaxy), but for the time being, only two formats + # are supported + target = str.lower(argv[1]) + if target == 'cwl': + from cwl import converter + elif target == 'galaxy': + from galaxy import converter + elif target == '-h' or target == '--help' or target == '--h' or target == 'help': + print(program_license) + return 0 + else: + utils.error('Unrecognized target engine. Supported targets are \'cwl\' and \'galaxy\'.') + return 1 + + try: + # Setup argument parser + parser = ArgumentParser(prog="CTDConverter", description=program_license, + formatter_class=RawDescriptionHelpFormatter, add_help=True) + utils.add_common_parameters(parser, program_version_message, program_build_date) + + # add tool-specific arguments + converter.add_specific_args(parser) + + # parse arguments and perform some basic, common validation + args = parser.parse_args() + validate_and_prepare_common_arguments(args) + + # parse the input CTD files into CTDModels + parsed_ctds = utils.parse_input_ctds(args.xsd_location, args.input_files, args.output_destination, + converter.get_preferred_file_extension()) + + # let the converter do its own thing + return converter.convert_models(args, parsed_ctds) + + except KeyboardInterrupt: + # handle keyboard interrupt + return 0 + + except ApplicationException, e: + utils.error("CTDConverter could not complete the requested operation.", 0) + utils.error("Reason: " + e.msg, 0) + return 1 + + except ModelError, e: + utils.error("There seems to be a problem with one of your input CTDs.", 0) + utils.error("Reason: " + e.msg, 0) + return 1 + + except Exception, e: + traceback.print_exc() + return 2 + + return 0 + + +def validate_and_prepare_common_arguments(args): + # flatten lists of lists to a list containing elements + lists_to_flatten = ["input_files", "blacklisted_parameters"] + for list_to_flatten in lists_to_flatten: + utils.flatten_list_of_lists(args, list_to_flatten) + + # if input is a single file, we expect output to be a file (and not a dir that already exists) + if len(args.input_files) == 1: + if os.path.isdir(args.output_destination): + raise ApplicationException("If a single input file is provided, output (%s) is expected to be a file " + "and not a folder.\n" % args.output_destination) + + # if input is a list of files, we expect output to be a folder + if len(args.input_files) > 1: + if not os.path.isdir(args.output_destination): + raise ApplicationException("If several input files are provided, output (%s) is expected to be an " + "existing directory.\n" % args.output_destination) + + # check that the provided input files, if provided, contain a valid file path + input_arguments_to_check = ["xsd_location", "input_files", "hardcoded_parameters"] + for argument_name in input_arguments_to_check: + utils.validate_argument_is_valid_path(args, argument_name) + + +if __name__ == "__main__": + sys.exit(main()) \ No newline at end of file diff --git a/galaxy/README.md b/galaxy/README.md index cd7cc67..82ec943 100644 --- a/galaxy/README.md +++ b/galaxy/README.md @@ -1,131 +1,13 @@ # Conversion of CTD Files to Galaxy ToolConfigs +## Generating a `tool_conf.xml` File +* Purpose: Galaxy uses a file `tool_conf.xml` in which other tools can be included. `CTDConverter` can also generate this file. Categories will be extracted from the provided input CTDs and for each category, a different `
` will be generated. Any input CTD lacking a category will be sorted under the provided default category. +* Short/long version: `-t` / `--tool-conf-destination` +* Required: no. +* Taken values: The destination of the file. -## How to use: most common Tasks + $ python convert.py galaxy -i /data/ctds/*.ctd -o /data/generated-galaxy-stubs -t /data/generated-galaxy-stubs/tool_conf.xml -The Galaxy ToolConfig generator takes several parameters and a varying number of inputs and outputs. The following sub-sections show how to perform the most common operations. - -Running the generator with the `-h/--help` parameter will print extended information about each of the parameters. - -### Macros - -Galaxy supports the use of macros via a `macros.xml` file (we provide a sample macros file in [macros.xml]). Instead of repeating sections, macros can be used and expanded. If you want fine control over the macros, you can use the `-m` / `--macros` parameter to provide your own macros file. - -Please note that the used macros file **must** be copied to your Galaxy installation on the same location in which you place the generated *ToolConfig* files, otherwise Galaxy will not be able to parse the generated *ToolConfig* files! - -### One input, one Output - -In its simplest form, the converter takes an input CTD file and generates an output Galaxy *ToolConfig* file. The following usage of `generator.py`: - - $ python generator.py -i /data/sample_input.ctd -o /data/sample_output.xml - -will parse `/data/sample_input.ctd` and generate a Galaxy tool wrapper under `/data/sample_output.xml`. The generated file can be added to your Galaxy instance like any other tool. - -### Converting several CTDs at once - -When converting several CTDs, the expected value for the `-o`/`--output` parameter is a folder. For example: - - $ python generator.py -i /data/ctds/one.ctd /data/ctds/two.ctd -o /data/generated-galaxy-stubs - -Will convert `/data/ctds/one.ctd` into `/data/generated-galaxy-stubs/one.xml` and `/data/ctds/two.ctd` into `/data/generated-galaxy-stubs/two.xml`. - -You can use wildcard expansion, as supported by most modern operating systems: - - $ python generator.py -i /data/ctds/*.ctd -o /data/generated-galaxy-stubs - -### Generating a tool_conf.xml File - -The generator supports generation of a `tool_conf.xml` file which you can later use in your local Galaxy installation. The parameter `-t`/`--tool-conf-destination` contains the path of a file in which a `tool_conf.xml` file will be generated. - - $ python generator.py -i /data/ctds/*.ctd -o /data/generated-galaxy-stubs -t /data/generated-galaxy-stubs/tool_conf.xml - - -## How to use: Parameters in Detail - -### A Word about Parameters taking Lists of Values - -All parameters have a short and a long option and some parameters take list of values. Using either the long or the short option of the parameter will produce the same output. The following examples show how to pass values using the `-f` / `--foo` parameter: - -The following uses of the parameter will pass the list of values containing `bar`, `blah` and `blu`: - - -f bar blah blu - --foo bar blah blu - -f bar -f blah -f blu - --foo bar --foo blah --foo blu - -f bar --foo blah blu - -The following uses of the parameter will pass a single value `bar`: - - -f bar - --foo bar - -### Schema Validation - -* Purpose: Provide validation of input CTDs against a schema file (i.e, a XSD file). -* Short/long version: `v` / `--validation-schema` -* Required: no. -* Taken values: location of the schema file (e.g., CTD.xsd). - -CTDs can be validated against a schema. The master version of the schema can be found under [CTDSchema]. - -If a schema is provided, all input CTDs will be validated against it. - -### Input File(s) - -* Purpose: Provide input CTD file(s) to convert. -* Short/long version: `-i` / `--input` -* Required: yes. -* Taken values: a list of input CTD files. - -Example: - -Any of the following invocations will convert `/data/input_one.ctd` and `/data/input_two.ctd`: - - $ python generator.py -i /data/input_one.ctd -i /data/input_two.ctd -o /data/generated - $ python generator.py -i /data/input_one.ctd /data/input_two.ctd -o /data/generated - $ python generator.py --input /data/input_one.ctd /data/input_two.ctd -o /data/generated - $ python generator.py --input /data/input_one.ctd --input /data/input_two.ctd -o /data/generated - -The following invocation will convert `/data/input.ctd` into `/data/output.xml`: - - $ python generator.py -i /data/input.ctd -o /data/output.xml -m sample_files/macros.xml - -Of course, you can also use wildcards, which will be automatically expanded by any modern operating system. This is extremely useful if you want to convert several files at a time. Imagine that the folder `/data/ctds` contains three files, `input_one.ctd`, `input_two.ctd` and `input_three.ctd`. The following two invocations will produce the same output in the `/data/galaxy`: - - $ python generator.py -i /data/input_one.ctd /data/input_two.ctd /data/input_three.ctd -o /data/galaxy - $ python generator.py -i /data/*.ctd -o /data/galaxy - -### Finer Control over the Tools to be converted - -Sometimes only a set of CTDs in a folder need to be converted. The parameter `-r`/`--required-tools` takes the path a file containing the names of tools that will be converted. - - $ python generator.py -i /data/ctds/*.ctd -o /data/generated-galaxy-stubs -r required_tools.txt - -On the other hand, if you want the generator to skip conversion of some CTDs, the parameter `-s`/`--skip-tools` will take the path of a file containing the names of tools that will not be converted. - - $ python generator.py -i /data/ctds/*.ctd -o /data/generated-galaxy-stubs -s skipped_tools.txt - -The format of these files (`required_tools.txt`, `skipped_tools.txt` in the examples above) is straightforward. Each line contains the name of a tool and any line starting with `#` will be ignored. - -### Output Destination - -* Purpose: Provide output destination for the generated Galaxy *ToolConfig* files. -* Short/long version: `-o` / `--output-destination` -* Required: yes. -* Taken values: if a single input file is given, then a single output file is expected. If multiple input files are given, then an existent folder, in which all generated Galaxy *ToolConfig* will be written, is expected. - -Example: - -A single input is given, and the output will be generated into `/data/output.xml`: - - $ python generator.py -i /data/input.ctd -o /data/output.xml - -Several inputs are given. The output is the already existent folder, `/data/stubs`, and at the end of the operation, the files `/data/stubs/input_one.ctd.xml` and `/data/stubs/input_two.ctd.xml` will be generated: - - $ python generator.py -i /data/ctds/input_one.ctd /data/ctds/input_two.ctd -o /data/stubs - - -### Adding Parameters to the Command-line - +## Adding Parameters to the Command-line * Purpose: Galaxy *ToolConfig* files include a `` element in which the command line to invoke the tool can be given. Sometimes it is needed to invoke your tools in a certain way (i.e., passing certain parameters). For instance, some tools offer the possibility to be invoked in a verbose or quiet way or even to be invoked in a headless way (i.e., without GUI). * Short/long version: `-a` / `--add-to-command-line` * Required: no. @@ -133,36 +15,14 @@ Example: - $ python generator.py ... -a "--quiet --no-gui" + $ python convert.py galaxy ... -a "--quiet --no-gui" Will generate the following `` element in the generated Galaxy *ToolConfig*: TOOL_NAME --quiet --no-gui ... - -### Blacklisting Parameters - -* Purpose: Some parameters present in the CTD are not to be exposed on Galaxy. Think of parameters such as `--help`, `--debug`, that might won't make much sense to be exposed to final users in a workflow management system such as Galaxy. -* Short/long version: `-b` / `--blacklist-parameters` -* Required: no. -* Taken values: A list of parameters to be blacklisted. - -Example: - - $ python generator.py ... -b h help quiet - -Will not process any of the parameters named `h`, `help`, or `quiet` and will not appear in the generated Galaxy *ToolConfig*. - -### Generating a tool_conf.xml file - -* Purpose: Galaxy uses a file `tool_conf.xml` in which other tools can be included. `generator.py` can also generate this file. Categories will be extracted from the provided input CTDs and for each category, a different `
` will be generated. Any input CTD lacking a category will be sorted under the provided default category. -* Short/long version: `-t` / `--tool-conf-destination` -* Required: no. -* Taken values: The destination of the file. - -### Providing a default Category - -* Purpose: Input CTDs that lack a category will be sorted under the value given to this parameter. If this parameter is not given, then the category `DEFAULT` will be used. +## Providing a default Category +* Purpose: Input CTDs that lack a category will be sorted under the value given to this parameter. If this parameter is not provided, then the category `DEFAULT` will be used. * Short/long version: `-c` / `--default-category` * Required: no. * Taken values: The value for the default category to use for input CTDs lacking a category. @@ -171,7 +31,7 @@ Suppose there is a folder containing several CTD files. Some of those CTDs don't have the optional attribute `category` and the rest belong to the `Data Processing` category. The following invocation: - $ python generator.py ... -c Other + $ python convert.py galaxy ... -c Other will generate, for each of the categories, a different section. Additionally, CTDs lacking a category will be sorted under the given category, `Other`, as shown: @@ -187,16 +47,15 @@ ...
-### Providing a Path for the Location of the ToolConfig Files - -* Purpose: The `tool_conf.xml` file contains references to files which in turn contain Galaxy *ToolConfig* files. Using this parameter, you can provide information about the location of your tools. +## Providing a Path for the Location of the *ToolConfig* Files +* Purpose: The `tool_conf.xml` file contains references to files which in turn contain Galaxy *ToolConfig* files. Using this parameter, you can provide information about the location of your wrappers on your Galaxy instance. * Short/long version: `-g` / `--galaxy-tool-path` * Required: no. * Taken values: The path relative to your `$GALAXY_ROOT/tools` folder on which your tools are located. Example: - $ python generator.py ... -g my_tools_folder + $ python convert.py galaxy ... -g my_tools_folder Will generate `` elements in the generated `tool_conf.xml` as follows: @@ -204,41 +63,7 @@ In this example, `tool_conf.xml` refers to a file located on `$GALAXY_ROOT/tools/my_tools_folder/some_tool.xml`. - -### Hardcoding Parameters - -* Purpose: Fixing the value of a parameter and hide it from the end user. -* Short/long version: `-p` / `--hardcoded-parameters` -* Required: no. -* Taken values: The path of a file containing the mapping between parameter names and hardcoded values to use in the `` section. - -It is sometimes required that parameters are hidden from the end user in workflow systems such as Galaxy and that they take a predetermined value. Allowing end users to control parameters similar to `--verbosity`, `--threads`, etc., might create more problems than solving them. For this purpose, the parameter `p`/`--hardcoded-parameters` takes the path of a file that contains up to three columns separated by whitespace that map parameter names to the hardcoded value. The first column contains the name of the parameter and the second one the hardcoded value. The first two columns are mandatory. - -If the parameter is to be hardcoded only for certain tools, a third column containing a comma separated list of tool names for which the hardcoding will apply can be added. - -Lines starting with `#` will be ignored. The following is an example of a valid file: - - # Parameter name # Value # Tool(s) - threads \${GALAXY_SLOTS:-24} - mode quiet - xtandem_executable xtandem XTandemAdapter - verbosity high Foo, Bar - -This will produce a `` section similar to the following one for all tools but `XTandemAdapter`, `Foo` and `Bar`: - - TOOL_NAME -threads \${GALAXY_SLOTS:-24} -mode quiet ... - -For `XTandemAdapter`, the `` will be similar to: - - XtandemAdapter ... -threads \${GALAXY_SLOTS:-24} -mode quiet -xtandem_executable xtandem ... - -And for tools `Foo` and `Bar`, the `` will be similar to: - - Foo ... ... -threads \${GALAXY_SLOTS:-24} -mode quiet -verbosity high ... - - -### Including additional Macros Files - +## Including additional Macros Files * Purpose: Include external macros files. * Short/long version: `-m` / `--macros` * Required: no. @@ -247,30 +72,11 @@ *ToolConfig* supports elaborate sections such as ``, ``, etc., that are identical across tools of the same suite. Macros files assist in the task of including external xml sections into *ToolConfig* files. For more information about the syntax of macros files, see: https://wiki.galaxyproject.org/Admin/Tools/ToolConfigSyntax#Reusing_Repeated_Configuration_Elements -There are some macros that are required, namely `stdio`, `requirements` and `advanced_options`. A template macro file is included in [macros.xml]. It can be edited to suit your needs and you could add extra macros or leave it as it is and include additional files. +There are some macros that are required, namely `stdio`, `requirements` and `advanced_options`. A template macro file is included in [macros.xml]. It can be edited to suit your needs and you could add extra macros or leave it as it is and include additional files. Every macro found in the provided files will be expanded. -Every macro found in the included files and in `support_files/macros.xml` will be expanded. Users are responsible for copying the given macros files in their corresponding galaxy folders. +Please note that the used macros files **must** be copied to your Galaxy installation on the same location in which you place the generated *ToolConfig* files, otherwise Galaxy will not be able to parse the generated *ToolConfig* files! -### Providing a default executable Path - -* Purpose: Help Galaxy locate tools by providing a path. -* Short/long version: `-x` / `--default-executable-path` -* Required: no. -* Taken values: The default executable path of the tools in the Galaxy installation. - -CTDs can contain an `` element that will be used when executing the tool binary. If this element is missing, the value provided by this parameter will be used as a prefix when building the `` section. Suppose that you have installed a tool suite in your local Galaxy instance under `/opt/suite/bin`. The following invocation of the converter: - - $ python generator.py -x /opt/suite/bin ... - -Will produce a `` section similar to: - - /opt/suite/bin/Foo ... - -For those CTDs in which no `` could be found. - - -### Generating a `datatypes_conf.xml` File - +## Generating a `datatypes_conf.xml` File * Purpose: Specify the destination of a generated `datatypes_conf.xml` file. * Short/long version: `-d` / `--datatypes-destination` * Required: no. @@ -278,9 +84,7 @@ It is likely that your tools use file formats or mimetypes that have not been registered in Galaxy. The generator allows you to specify a path in which an automatically generated `datatypes_conf.xml` file will be created. Consult the next section to get information about how to register file formats and mimetypes. - -### Providing Galaxy File Formats - +## Providing Galaxy File Formats * Purpose: Register new file formats and mimetypes. * Short/long version: `-f` / `--formats-file` * Required: no. @@ -308,11 +112,9 @@ For information about Galaxy data types and subclasses, consult the following page: https://wiki.galaxyproject.org/Admin/Datatypes/Adding%20Datatypes - -## Notes about some of the *OpenMS* Tools - -* Most of the tools can be generated automatically. Some of the tools need some extra work (for now). -* These adapters need to be changed, such that you provide the path to the executable: +## Remarks about some of the *OpenMS* Tools +* Most of the tools can be generated automatically. However, some of the tools need some extra work (for now). +* The following adapters need to be changed, such that you provide the path to the executable: * FidoAdapter (add `-exe fido` in the command tag, delete the `$param_exe` in the command tag, delete the parameter from the input list). * MSGFPlusAdapter (add `-executable msgfplus.jar` in the command tag, delete the `$param_executable` in the command tag, delete the parameter from the input list). * MyriMatchAdapter (add `-myrimatch_executable myrimatch` in the command tag, delete the `$param_myrimatch_executable` in the command tag, delete the parameter from the input list). @@ -321,9 +123,9 @@ * XTandemAdapter (add `-xtandem_executable xtandem` in the command tag, delete the $param_xtandem_executable in the command tag, delete the parameter from the input list). * To avoid the deletion in the inputs you can also add these parameters to the blacklist - $ python generator.py -b exe executable myrimatch_excutable omssa_executable pepnovo_executable xtandem_executable + $ python convert.py galaxy -b exe executable myrimatch_excutable omssa_executable pepnovo_executable xtandem_executable -* These tools have multiple outputs (number of inputs = number of outputs) which is not yet supported in Galaxy-stable: +* The following tools have multiple outputs (number of inputs = number of outputs) which is not yet supported in Galaxy-stable: * SeedListGenerator * SpecLibSearcher * MapAlignerIdentification diff --git a/galaxy/__init__.py b/galaxy/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/galaxy/converter.py b/galaxy/converter.py new file mode 100755 index 0000000..81b1f12 --- /dev/null +++ b/galaxy/converter.py @@ -0,0 +1,992 @@ +#!/usr/bin/env python +# encoding: utf-8 + +""" +@author: delagarza +""" + +import os +import string + +from collections import OrderedDict +from string import strip +from lxml import etree +from lxml.etree import SubElement, Element, ElementTree, ParseError, parse + +from common import utils, logger +from common.exceptions import ApplicationException, InvalidModelException +from common.utils import ParsedCTD + +from CTDopts.CTDopts import _InFile, _OutFile, ParameterGroup, _Choices, _NumericRange, _FileFormat, ModelError, _Null + + +TYPE_TO_GALAXY_TYPE = {int: 'integer', float: 'float', str: 'text', bool: 'boolean', _InFile: 'data', + _OutFile: 'data', _Choices: 'select'} +STDIO_MACRO_NAME = "stdio" +REQUIREMENTS_MACRO_NAME = "requirements" +ADVANCED_OPTIONS_MACRO_NAME = "advanced_options" + +REQUIRED_MACROS = [STDIO_MACRO_NAME, REQUIREMENTS_MACRO_NAME, ADVANCED_OPTIONS_MACRO_NAME] + + +class ExitCode: + def __init__(self, code_range="", level="", description=None): + self.range = code_range + self.level = level + self.description = description + + +class DataType: + def __init__(self, extension, galaxy_extension=None, galaxy_type=None, mimetype=None): + self.extension = extension + self.galaxy_extension = galaxy_extension + self.galaxy_type = galaxy_type + self.mimetype = mimetype + + +def add_specific_args(parser): + parser.add_argument("-f", "--formats-file", dest="formats_file", + help="File containing the supported file formats. Run with '-h' or '--help' to see a " + "brief example on the layout of this file.", default=None, required=False) + parser.add_argument("-a", "--add-to-command-line", dest="add_to_command_line", + help="Adds content to the command line", default="", required=False) + parser.add_argument("-d", "--datatypes-destination", dest="data_types_destination", + help="Specify the location of a datatypes_conf.xml to modify and add the registered " + "data types. If the provided destination does not exist, a new file will be created.", + default=None, required=False) + parser.add_argument("-c", "--default-category", dest="default_category", default="DEFAULT", required=False, + help="Default category to use for tools lacking a category when generating tool_conf.xml") + parser.add_argument("-t", "--tool-conf-destination", dest="tool_conf_destination", default=None, required=False, + help="Specify the location of an existing tool_conf.xml that will be modified to include " + "the converted tools. If the provided destination does not exist, a new file will" + "be created.") + parser.add_argument("-g", "--galaxy-tool-path", dest="galaxy_tool_path", default=None, required=False, + help="The path that will be prepended to the file names when generating tool_conf.xml") + parser.add_argument("-r", "--required-tools", dest="required_tools_file", default=None, required=False, + help="Each line of the file will be interpreted as a tool name that needs translation. " + "Run with '-h' or '--help' to see a brief example on the format of this file.") + parser.add_argument("-s", "--skip-tools", dest="skip_tools_file", default=None, required=False, + help="File containing a list of tools for which a Galaxy stub will not be generated. " + "Run with '-h' or '--help' to see a brief example on the format of this file.") + parser.add_argument("-m", "--macros", dest="macros_files", default=[], nargs="*", + action="append", required=None, help="Import the additional given file(s) as macros. " + "The macros stdio, requirements and advanced_options are required. Please see " + "macros.xml for an example of a valid macros file. Al defined macros will be imported.") + + +def convert_models(args, parsed_ctds): # IGNORE:C0111 + # validate and prepare the passed arguments + validate_and_prepare_args(args) + + # extract the names of the macros and check that we have found the ones we need + macros_to_expand = parse_macros_files(args.macros_files) + + # parse the given supported file-formats file + supported_file_formats = parse_file_formats(args.formats_file) + + # parse the hardcoded parameters fileĀ¬ + parameter_hardcoder = utils.parse_hardcoded_parameters(args.hardcoded_parameters) + + # parse the skip/required tools files + skip_tools = parse_tools_list_file(args.skip_tools_file) + required_tools = parse_tools_list_file(args.required_tools_file) + + _convert_internal(parsed_ctds, + supported_file_formats=supported_file_formats, + default_executable_path=args.default_executable_path, + add_to_command_line=args.add_to_command_line, + blacklisted_parameters=args.blacklisted_parameters, + required_tools=required_tools, + skip_tools=skip_tools, + macros_file_names=args.macros_files, + macros_to_expand=macros_to_expand, + parameter_hardcoder=parameter_hardcoder) + + # generation of galaxy stubs is ready... now, let's see if we need to generate a tool_conf.xml + if args.tool_conf_destination is not None: + generate_tool_conf(parsed_ctds, args.tool_conf_destination, + args.galaxy_tool_path, args.default_category) + + # generate datatypes_conf.xml + if args.data_types_destination is not None: + generate_data_type_conf(supported_file_formats, args.data_types_destination) + + return 0 + + +def parse_tools_list_file(tools_list_file): + tools_list = None + if tools_list_file is not None: + tools_list = [] + with open(tools_list_file) as f: + for line in f: + if line is None or not line.strip() or line.strip().startswith("#"): + continue + else: + tools_list.append(line.strip()) + + return tools_list + + +def parse_macros_files(macros_file_names): + macros_to_expand = set() + + for macros_file_name in macros_file_names: + try: + macros_file = open(macros_file_name) + logger.info("Loading macros from %s" % macros_file_name, 0) + root = parse(macros_file).getroot() + for xml_element in root.findall("xml"): + name = xml_element.attrib["name"] + if name in macros_to_expand: + logger.warning("Macro %s has already been found. Duplicate found in file %s." % + (name, macros_file_name), 0) + else: + logger.info("Macro %s found" % name, 1) + macros_to_expand.add(name) + except ParseError, e: + raise ApplicationException("The macros file " + macros_file_name + " could not be parsed. Cause: " + + str(e)) + except IOError, e: + raise ApplicationException("The macros file " + macros_file_name + " could not be opened. Cause: " + + str(e)) + + # we depend on "stdio", "requirements" and "advanced_options" to exist on all the given macros files + missing_needed_macros = [] + for required_macro in REQUIRED_MACROS: + if required_macro not in macros_to_expand: + missing_needed_macros.append(required_macro) + + if missing_needed_macros: + raise ApplicationException( + "The following required macro(s) were not found in any of the given macros files: %s, " + "see galaxy/macros.xml for an example of a valid macros file." + % ", ".join(missing_needed_macros)) + + # we do not need to "expand" the advanced_options macro + macros_to_expand.remove(ADVANCED_OPTIONS_MACRO_NAME) + return macros_to_expand + + +def parse_file_formats(formats_file): + supported_formats = {} + if formats_file is not None: + line_number = 0 + with open(formats_file) as f: + for line in f: + line_number += 1 + if line is None or not line.strip() or line.strip().startswith("#"): + # ignore (it'd be weird to have something like: + # if line is not None and not (not line.strip()) ... + pass + else: + # not an empty line, no comment + # strip the line and split by whitespace + parsed_formats = line.strip().split() + # valid lines contain either one or four columns + if not (len(parsed_formats) == 1 or len(parsed_formats) == 3 or len(parsed_formats) == 4): + logger.warning( + "Invalid line at line number %d of the given formats file. Line will be ignored:\n%s" % + (line_number, line), 0) + # ignore the line + continue + elif len(parsed_formats) == 1: + supported_formats[parsed_formats[0]] = DataType(parsed_formats[0], parsed_formats[0]) + else: + mimetype = None + # check if mimetype was provided + if len(parsed_formats) == 4: + mimetype = parsed_formats[3] + supported_formats[parsed_formats[0]] = DataType(parsed_formats[0], parsed_formats[1], + parsed_formats[2], mimetype) + return supported_formats + + +def validate_and_prepare_args(args): + # check that only one of skip_tools_file and required_tools_file has been provided + if args.skip_tools_file is not None and args.required_tools_file is not None: + raise ApplicationException( + "You have provided both a file with tools to ignore and a file with required tools.\n" + "Only one of -s/--skip-tools, -r/--required-tools can be provided.") + + # flatten macros_files to make sure that we have a list containing file names and not a list of lists + utils.flatten_list_of_lists(args, "macros_files") + + # check that the arguments point to a valid, existing path + input_variables_to_check = ["skip_tools_file", "required_tools_file", "macros_files", "formats_file"] + for variable_name in input_variables_to_check: + utils.validate_argument_is_valid_path(args, variable_name) + + # check that the provided output files, if provided, contain a valid file path (i.e., not a folder) + output_variables_to_check = ["data_types_destination", "tool_conf_destination"] + for variable_name in output_variables_to_check: + file_name = getattr(args, variable_name) + if file_name is not None and os.path.isdir(file_name): + raise ApplicationException("The provided output file name (%s) points to a directory." % file_name) + + if not args.macros_files: + # list is empty, provide the default value + logger.warning("Using default macros from galaxy/macros.xml", 0) + args.macros_files = ["galaxy/macros.xml"] + + +def get_preferred_file_extension(): + return "xml" + + +def _convert_internal(parsed_ctds, **kwargs): + # parse all input files into models using CTDopts (via utils) + # the output is a tuple containing the model, output destination, origin file + for parsed_ctd in parsed_ctds: + model = parsed_ctd.ctd_model + origin_file = parsed_ctd.input_file + output_file = parsed_ctd.suggested_output_file + + if kwargs["skip_tools"] is not None and model.name in kwargs["skip_tools"]: + logger.info("Skipping tool %s" % model.name, 0) + continue + elif kwargs["required_tools"] is not None and model.name not in kwargs["required_tools"]: + logger.info("Tool %s is not required, skipping it" % model.name, 0) + continue + else: + logger.info("Converting from %s " % origin_file, 0) + tool = create_tool(model) + write_header(tool, model) + create_description(tool, model) + expand_macros(tool, model, **kwargs) + create_command(tool, model, **kwargs) + create_inputs(tool, model, **kwargs) + create_outputs(tool, model, **kwargs) + create_help(tool, model) + + # wrap our tool element into a tree to be able to serialize it + tree = ElementTree(tool) + tree.write(open(output_file, 'w'), encoding="UTF-8", xml_declaration=True, pretty_print=True) + + +def write_header(tool, model): + tool.addprevious(etree.Comment( + "This is a configuration file for the integration of a tools into Galaxy (https://galaxyproject.org/). " + "This file was automatically generated using CTDConverter.")) + tool.addprevious(etree.Comment('Proposed Tool Section: [%s]' % model.opt_attribs.get("category", ""))) + + +def generate_tool_conf(parsed_ctds, tool_conf_destination, galaxy_tool_path, default_category): + # for each category, we keep a list of models corresponding to it + categories_to_tools = dict() + for parsed_ctd in parsed_ctds: + category = strip(parsed_ctd.ctd_model.opt_attribs.get("category", "")) + if not category.strip(): + category = default_category + if category not in categories_to_tools: + categories_to_tools[category] = [] + categories_to_tools[category].append(utils.get_filename(parsed_ctd.suggested_output_file)) + + # at this point, we should have a map for all categories->tools + toolbox_node = Element("toolbox") + + if galaxy_tool_path is not None and not galaxy_tool_path.strip().endswith("/"): + galaxy_tool_path = galaxy_tool_path.strip() + "/" + if galaxy_tool_path is None: + galaxy_tool_path = "" + + for category, file_names in categories_to_tools.iteritems(): + section_node = add_child_node(toolbox_node, "section") + section_node.attrib["id"] = "section-id-" + "".join(category.split()) + section_node.attrib["name"] = category + + for filename in file_names: + tool_node = add_child_node(section_node, "tool") + tool_node.attrib["file"] = galaxy_tool_path + filename + + toolconf_tree = ElementTree(toolbox_node) + toolconf_tree.write(open(tool_conf_destination,'w'), encoding="UTF-8", xml_declaration=True, pretty_print=True) + logger.info("Generated Galaxy tool_conf.xml in %s" % tool_conf_destination, 0) + + +def generate_data_type_conf(supported_file_formats, data_types_destination): + data_types_node = Element("datatypes") + registration_node = add_child_node(data_types_node, "registration") + registration_node.attrib["converters_path"] = "lib/galaxy/datatypes/converters" + registration_node.attrib["display_path"] = "display_applications" + + for format_name in supported_file_formats: + data_type = supported_file_formats[format_name] + # add only if it's a data type that does not exist in Galaxy + if data_type.galaxy_type is not None: + data_type_node = add_child_node(registration_node, "datatype") + # we know galaxy_extension is not None + data_type_node.attrib["extension"] = data_type.galaxy_extension + data_type_node.attrib["type"] = data_type.galaxy_type + if data_type.mimetype is not None: + data_type_node.attrib["mimetype"] = data_type.mimetype + + data_types_tree = ElementTree(data_types_node) + data_types_tree.write(open(data_types_destination,'w'), encoding="UTF-8", xml_declaration=True, pretty_print=True) + logger.info("Generated Galaxy datatypes_conf.xml in %s" % data_types_destination, 0) + + +def create_tool(model): + return Element("tool", OrderedDict([("id", model.name), ("name", model.name), ("version", model.version)])) + + +def create_description(tool, model): + if "description" in model.opt_attribs.keys() and model.opt_attribs["description"] is not None: + description = SubElement(tool,"description") + description.text = model.opt_attribs["description"] + + +def get_param_cli_name(param, model): + # we generate parameters with colons for subgroups, but not for the two topmost parents (OpenMS legacy) + if type(param.parent) == ParameterGroup: + if not hasattr(param.parent.parent, 'parent'): + return resolve_param_mapping(param, model) + elif not hasattr(param.parent.parent.parent, 'parent'): + return resolve_param_mapping(param, model) + else: + if model.cli: + logger.warning("Using nested parameter sections (NODE elements) is not compatible with ", 1) + return get_param_name(param.parent) + ":" + resolve_param_mapping(param, model) + else: + return resolve_param_mapping(param, model) + + +def get_param_name(param): + # we generate parameters with colons for subgroups, but not for the two topmost parents (OpenMS legacy) + if type(param.parent) == ParameterGroup: + if not hasattr(param.parent.parent, 'parent'): + return param.name + elif not hasattr(param.parent.parent.parent, 'parent'): + return param.name + else: + return get_param_name(param.parent) + ":" + param.name + else: + return param.name + + +# some parameters are mapped to command line options, this method helps resolve those mappings, if any +def resolve_param_mapping(param, model): + # go through all mappings and find if the given param appears as a reference name in a mapping element + param_mapping = None + for cli_element in model.cli: + for mapping_element in cli_element.mappings: + if mapping_element.reference_name == param.name: + if param_mapping is not None: + logger.warning("The parameter %s has more than one mapping in the section. " + "The first found mapping, %s, will be used." % (param.name, param_mapping), 1) + else: + param_mapping = cli_element.option_identifier + + return param_mapping if param_mapping is not None else param.name + + +def create_command(tool, model, **kwargs): + final_command = get_tool_executable_path(model, kwargs["default_executable_path"]) + '\n' + final_command += kwargs["add_to_command_line"] + '\n' + advanced_command_start = "#if $adv_opts.adv_opts_selector=='advanced':\n" + advanced_command_end = '#end if' + advanced_command = '' + parameter_hardcoder = kwargs["parameter_hardcoder"] + + found_output_parameter = False + for param in extract_parameters(model): + if param.type is _OutFile: + found_output_parameter = True + command = '' + param_name = get_param_name(param) + param_cli_name = get_param_cli_name(param, model) + if param_name == param_cli_name: + # there was no mapping, so for the cli name we will use a '-' in the prefix + param_cli_name = '-' + param_name + + if param.name in kwargs["blacklisted_parameters"]: + continue + + hardcoded_value = parameter_hardcoder.get_hardcoded_value(param_name, model.name) + if hardcoded_value: + command += '%s %s\n' % (param_cli_name, hardcoded_value) + else: + # parameter is neither blacklisted nor hardcoded... + galaxy_parameter_name = get_galaxy_parameter_name(param) + repeat_galaxy_parameter_name = get_repeat_galaxy_parameter_name(param) + + # logic for ITEMLISTs + if param.is_list: + if param.type is _InFile: + command += param_cli_name + "\n" + command += " #for token in $" + galaxy_parameter_name + ":\n" + command += " $token\n" + command += " #end for\n" + else: + command += "\n#if $" + repeat_galaxy_parameter_name + ":\n" + command += param_cli_name + "\n" + command += " #for token in $" + repeat_galaxy_parameter_name + ":\n" + command += " #if \" \" in str(token):\n" + command += " \"$token." + galaxy_parameter_name + "\"\n" + command += " #else\n" + command += " $token." + galaxy_parameter_name + "\n" + command += " #end if\n" + command += " #end for\n" + command += "#end if\n" + # logic for other ITEMs + else: + if param.advanced and param.type is not _OutFile: + actual_parameter = "$adv_opts.%s" % galaxy_parameter_name + else: + actual_parameter = "$%s" % galaxy_parameter_name + # TODO only useful for text fields, integers or floats + # not useful for choices, input fields ... + + if not is_boolean_parameter(param) and type(param.restrictions) is _Choices : + command += "#if " + actual_parameter + ":\n" + command += ' %s\n' % param_cli_name + command += " #if \" \" in str(" + actual_parameter + "):\n" + command += " \"" + actual_parameter + "\"\n" + command += " #else\n" + command += " " + actual_parameter + "\n" + command += " #end if\n" + command += "#end if\n" + elif is_boolean_parameter(param): + command += "#if " + actual_parameter + ":\n" + command += ' %s\n' % param_cli_name + command += "#end if\n" + elif TYPE_TO_GALAXY_TYPE[param.type] is 'text': + command += "#if " + actual_parameter + ":\n" + command += " %s " % param_cli_name + command += " \"" + actual_parameter + "\"\n" + command += "#end if\n" + else: + command += "#if " + actual_parameter + ":\n" + command += ' %s ' % param_cli_name + command += actual_parameter + "\n" + command += "#end if\n" + + if param.advanced and param.type is not _OutFile: + advanced_command += " %s" % command + else: + final_command += command + + if advanced_command: + final_command += "%s%s%s\n" % (advanced_command_start, advanced_command, advanced_command_end) + + if not found_output_parameter: + final_command += "> $param_stdout\n" + + command_node = add_child_node(tool, "command") + command_node.text = final_command + + +# creates the xml elements needed to import the needed macros files +# and to "expand" the macros +def expand_macros(tool, model, **kwargs): + macros_node = add_child_node(tool, "macros") + token_node = add_child_node(macros_node, "token") + token_node.attrib["name"] = "@EXECUTABLE@" + token_node.text = get_tool_executable_path(model, kwargs["default_executable_path"]) + + # add nodes + for macro_file_name in kwargs["macros_file_names"]: + macro_file = open(macro_file_name) + import_node = add_child_node(macros_node, "import") + # do not add the path of the file, rather, just its basename + import_node.text = os.path.basename(macro_file.name) + + # add nodes + for expand_macro in kwargs["macros_to_expand"]: + expand_node = add_child_node(tool, "expand") + expand_node.attrib["macro"] = expand_macro + + +def get_tool_executable_path(model, default_executable_path): + # rules to build the galaxy executable path: + # if executablePath is null, then use default_executable_path and store it in executablePath + # if executablePath is null and executableName is null, then the name of the tool will be used + # if executablePath is null and executableName is not null, then executableName will be used + # if executablePath is not null and executableName is null, + # then executablePath and the name of the tool will be used + # if executablePath is not null and executableName is not null, then both will be used + + # first, check if the model has executablePath / executableName defined + executable_path = model.opt_attribs.get("executablePath", None) + executable_name = model.opt_attribs.get("executableName", None) + + # check if we need to use the default_executable_path + if executable_path is None: + executable_path = default_executable_path + + # fix the executablePath to make sure that there is a '/' in the end + if executable_path is not None: + executable_path = executable_path.strip() + if not executable_path.endswith('/'): + executable_path += '/' + + # assume that we have all information present + command = str(executable_path) + str(executable_name) + if executable_path is None: + if executable_name is None: + command = model.name + else: + command = executable_name + else: + if executable_name is None: + command = executable_path + model.name + return command + + +def get_galaxy_parameter_name(param): + return "param_%s" % get_param_name(param).replace(':', '_').replace('-', '_') + + +def get_input_with_same_restrictions(out_param, model, supported_file_formats): + for param in extract_parameters(model): + if param.type is _InFile: + if param.restrictions is not None: + in_param_formats = get_supported_file_types(param.restrictions.formats, supported_file_formats) + out_param_formats = get_supported_file_types(out_param.restrictions.formats, supported_file_formats) + if in_param_formats == out_param_formats: + return param + + +def create_inputs(tool, model, **kwargs): + inputs_node = SubElement(tool, "inputs") + + # some suites (such as OpenMS) need some advanced options when handling inputs + expand_advanced_node = add_child_node(tool, "expand", OrderedDict([("macro", ADVANCED_OPTIONS_MACRO_NAME)])) + parameter_hardcoder = kwargs["parameter_hardcoder"] + + # treat all non output-file parameters as inputs + for param in extract_parameters(model): + # no need to show hardcoded parameters + hardcoded_value = parameter_hardcoder.get_hardcoded_value(param.name, model.name) + if param.name in kwargs["blacklisted_parameters"] or hardcoded_value: + # let's not use an extra level of indentation and use NOP + continue + if param.type is not _OutFile: + if param.advanced: + if expand_advanced_node is not None: + parent_node = expand_advanced_node + else: + # something went wrong... we are handling an advanced parameter and the + # advanced input macro was not set... inform the user about it + logger.info("The parameter %s has been set as advanced, but advanced_input_macro has " + "not been set." % param.name, 1) + # there is not much we can do, other than use the inputs_node as a parent node! + parent_node = inputs_node + else: + parent_node = inputs_node + + # for lists we need a repeat tag + if param.is_list and param.type is not _InFile: + rep_node = add_child_node(parent_node, "repeat") + create_repeat_attribute_list(rep_node, param) + parent_node = rep_node + + param_node = add_child_node(parent_node, "param") + create_param_attribute_list(param_node, param, kwargs["supported_file_formats"]) + + # advanced parameter selection should be at the end + # and only available if an advanced parameter exists + if expand_advanced_node is not None and len(expand_advanced_node) > 0: + inputs_node.append(expand_advanced_node) + + +def get_repeat_galaxy_parameter_name(param): + return "rep_" + get_galaxy_parameter_name(param) + + +def create_repeat_attribute_list(rep_node, param): + rep_node.attrib["name"] = get_repeat_galaxy_parameter_name(param) + if param.required: + rep_node.attrib["min"] = "1" + else: + rep_node.attrib["min"] = "0" + # for the ITEMLISTs which have LISTITEM children we only + # need one parameter as it is given as a string + if param.default is not None: + rep_node.attrib["max"] = "1" + rep_node.attrib["title"] = get_galaxy_parameter_name(param) + + +def create_param_attribute_list(param_node, param, supported_file_formats): + param_node.attrib["name"] = get_galaxy_parameter_name(param) + + param_type = TYPE_TO_GALAXY_TYPE[param.type] + if param_type is None: + raise ModelError("Unrecognized parameter type %(type)s for parameter %(name)s" + % {"type": param.type, "name": param.name}) + + if param.is_list: + param_type = "text" + + if is_selection_parameter(param): + param_type = "select" + if len(param.restrictions.choices) < 5: + param_node.attrib["display"] = "radio" + + if is_boolean_parameter(param): + param_type = "boolean" + + if param.type is _InFile: + # assume it's just text unless restrictions are provided + param_format = "txt" + if param.restrictions is not None: + # join all formats of the file, take mapping from supported_file if available for an entry + if type(param.restrictions) is _FileFormat: + param_format = ','.join([get_supported_file_type(i, supported_file_formats) if + get_supported_file_type(i, supported_file_formats) + else i for i in param.restrictions.formats]) + else: + raise InvalidModelException("Expected 'file type' restrictions for input file [%(name)s], " + "but instead got [%(type)s]" + % {"name": param.name, "type": type(param.restrictions)}) + + param_node.attrib["type"] = "data" + param_node.attrib["format"] = param_format + # in the case of multiple input set multiple flag + if param.is_list: + param_node.attrib["multiple"] = "true" + + else: + param_node.attrib["type"] = param_type + + # check for parameters with restricted values (which will correspond to a "select" in galaxy) + if param.restrictions is not None: + # it could be either _Choices or _NumericRange, with special case for boolean types + if param_type == "boolean": + create_boolean_parameter(param_node, param) + elif type(param.restrictions) is _Choices: + # create as many