Coverage for biobb_template/template/template.py: 75%
57 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-10-03 15:35 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2024-10-03 15:35 +0000
1#!/usr/bin/env python3
3"""Module containing the Template class and the command line interface."""
4import argparse
5import shutil
6from pathlib import PurePath
7from biobb_common.generic.biobb_object import BiobbObject
8from biobb_common.configuration import settings
9from biobb_common.tools import file_utils as fu
10from biobb_common.tools.file_utils import launchlogger
13# 1. Rename class as required
14class Template(BiobbObject):
15 """
16 | biobb_template Template
17 | Short description for the `template <http://templatedocumentation.org>`_ module in Restructured Text (reST) syntax. Mandatory.
18 | Long description for the `template <http://templatedocumentation.org>`_ module in Restructured Text (reST) syntax. Optional.
20 Args:
21 input_file_path1 (str): Description for the first input file path. File type: input. `Sample file <https://urlto.sample>`_. Accepted formats: top (edam:format_3881).
22 input_file_path2 (str) (Optional): Description for the second input file path (optional). File type: input. `Sample file <https://urlto.sample>`_. Accepted formats: dcd (edam:format_3878).
23 output_file_path (str): Description for the output file path. File type: output. `Sample file <https://urlto.sample>`_. Accepted formats: zip (edam:format_3987).
24 properties (dic):
25 * **boolean_property** (*bool*) - (True) Example of boolean property.
26 * **binary_path** (*str*) - ("zip") Example of executable binary property.
27 * **remove_tmp** (*bool*) - (True) [WF property] Remove temporal files.
28 * **restart** (*bool*) - (False) [WF property] Do not execute if output files exist.
29 * **sandbox_path** (*str*) - ("./") [WF property] Parent path to the sandbox directory.
31 Examples:
32 This is a use example of how to use the building block from Python::
34 from biobb_template.template.template import template
36 prop = {
37 'boolean_property': True
38 }
39 template(input_file_path1='/path/to/myTopology.top',
40 output_file_path='/path/to/newCompressedFile.zip',
41 input_file_path2='/path/to/mytrajectory.dcd',
42 properties=prop)
44 Info:
45 * wrapped_software:
46 * name: Zip
47 * version: >=3.0
48 * license: BSD 3-Clause
49 * ontology:
50 * name: EDAM
51 * schema: http://edamontology.org/EDAM.owl
53 """
55 # 2. Adapt input and output file paths as required. Include all files, even optional ones
56 def __init__(self, input_file_path1, output_file_path, input_file_path2=None, properties=None, **kwargs) -> None:
57 properties = properties or {}
59 # 2.0 Call parent class constructor
60 super().__init__(properties)
61 self.locals_var_dict = locals().copy()
63 # 2.1 Modify to match constructor parameters
64 # Input/Output files
65 self.io_dict = {
66 'in': {'input_file_path1': input_file_path1, 'input_file_path2': input_file_path2},
67 'out': {'output_file_path': output_file_path}
68 }
70 # 3. Include all relevant properties here as
71 # self.property_name = properties.get('property_name', property_default_value)
73 # Properties specific for BB
74 self.boolean_property = properties.get('boolean_property', True)
75 self.binary_path = properties.get('binary_path', 'zip')
76 self.properties = properties
78 # Check the properties
79 self.check_properties(properties)
80 # Check the arguments
81 self.check_arguments()
83 @launchlogger
84 def launch(self) -> int:
85 """Execute the :class:`Template <template.template.Template>` object."""
87 # 4. Setup Biobb
88 if self.check_restart():
89 return 0
90 self.stage_files()
92 # Creating temporary folder
93 self.tmp_folder = fu.create_unique_dir()
94 fu.log('Creating %s temporary folder' % self.tmp_folder, self.out_log)
96 # 5. Include here all mandatory input files
97 # Copy input_file_path1 to temporary folder
98 shutil.copy(self.io_dict['in']['input_file_path1'], self.tmp_folder)
100 # 6. Prepare the command line parameters as instructions list
101 instructions = ['-j']
102 if self.boolean_property:
103 instructions.append('-v')
104 fu.log('Appending optional boolean property', self.out_log, self.global_log)
106 # 7. Build the actual command line as a list of items (elements order will be maintained)
107 self.cmd = [self.binary_path,
108 ' '.join(instructions),
109 self.io_dict['out']['output_file_path'],
110 str(PurePath(self.tmp_folder).joinpath(PurePath(self.io_dict['in']['input_file_path1']).name))]
111 fu.log('Creating command line with instructions and required arguments', self.out_log, self.global_log)
113 # 8. Repeat for optional input files if provided
114 if self.io_dict['in']['input_file_path2']:
115 # Copy input_file_path2 to temporary folder
116 shutil.copy(self.io_dict['in']['input_file_path2'], self.tmp_folder)
117 # Append optional input_file_path2 to cmd
118 self.cmd.append(str(PurePath(self.tmp_folder).joinpath(PurePath(self.io_dict['in']['input_file_path2']).name)))
119 fu.log('Appending optional argument to command line', self.out_log, self.global_log)
121 # 9. Uncomment to check the command line
122 # print(' '.join(cmd))
124 # Run Biobb block
125 self.run_biobb()
127 # Copy files to host
128 self.copy_to_host()
130 # Remove temporary file(s)
131 self.tmp_files.extend([
132 self.stage_io_dict.get("unique_dir"),
133 self.tmp_folder
134 ])
135 self.remove_tmp_files()
137 # Check output arguments
138 self.check_arguments(output_files_created=True, raise_exception=False)
140 return self.return_code
143def template(input_file_path1: str, output_file_path: str, input_file_path2: str = None, properties: dict = None, **kwargs) -> int:
144 """Create :class:`Template <template.template.Template>` class and
145 execute the :meth:`launch() <template.template.Template.launch>` method."""
147 return Template(input_file_path1=input_file_path1,
148 output_file_path=output_file_path,
149 input_file_path2=input_file_path2,
150 properties=properties, **kwargs).launch()
153def main():
154 """Command line execution of this building block. Please check the command line documentation."""
155 parser = argparse.ArgumentParser(description='Description for the template module.', formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999))
156 parser.add_argument('--config', required=False, help='Configuration file')
158 # 10. Include specific args of each building block following the examples. They should match step 2
159 required_args = parser.add_argument_group('required arguments')
160 required_args.add_argument('--input_file_path1', required=True, help='Description for the first input file path. Accepted formats: top.')
161 parser.add_argument('--input_file_path2', required=False, help='Description for the second input file path (optional). Accepted formats: dcd.')
162 required_args.add_argument('--output_file_path', required=True, help='Description for the output file path. Accepted formats: zip.')
164 args = parser.parse_args()
165 args.config = args.config or "{}"
166 properties = settings.ConfReader(config=args.config).get_prop_dic()
168 # 11. Adapt to match Class constructor (step 2)
169 # Specific call of each building block
170 template(input_file_path1=args.input_file_path1,
171 output_file_path=args.output_file_path,
172 input_file_path2=args.input_file_path2,
173 properties=properties)
176if __name__ == '__main__':
177 main()
179# 12. Complete documentation strings