Coverage for biobb_dna / curvesplus / biobb_canal.py: 82%
72 statements
« prev ^ index » next coverage.py v7.13.0, created at 2025-12-15 18:49 +0000
« prev ^ index » next coverage.py v7.13.0, created at 2025-12-15 18:49 +0000
1#!/usr/bin/env python3
3"""Module containing the Canal class and the command line interface."""
4import os
5import zipfile
6from typing import Optional
7from pathlib import Path
9from biobb_common.generic.biobb_object import BiobbObject
10from biobb_common.tools import file_utils as fu
11from biobb_common.tools.file_utils import launchlogger
14class Canal(BiobbObject):
15 """
16 | biobb_dna Canal
17 | Wrapper for the Canal executable that is part of the Curves+ software suite.
18 | The Canal program is used to analyze the curvature of DNA structures.
20 Args:
21 input_cda_file (str): Input cda file, from Cur+ output. File type: input. `Sample file <https://raw.githubusercontent.com/bioexcel/biobb_dna/master/biobb_dna/test/data/curvesplus/curves_output.cda>`_. Accepted formats: cda (edam:format_2330).
22 input_lis_file (str) (Optional): Input lis file, from Cur+ output. File type: input. Accepted formats: lis (edam:format_2330).
23 output_zip_path (str): zip filename for output files. File type: output. `Sample file <https://raw.githubusercontent.com/bioexcel/biobb_dna/master/biobb_dna/test/reference/curvesplus/canal_output.zip>`_. Accepted formats: zip (edam:format_3987).
24 properties (dic):
25 * **bases** (*str*) - (None) sequence of bases to be searched for in the I/P data (default is blank, meaning no specified sequence).
26 * **itst** (*int*) - (0) Iteration start index.
27 * **itnd** (*int*) - (0) Iteration end index.
28 * **itdel** (*int*) - (1) Iteration delimiter.
29 * **lev1** (*int*) - (0) Lower base level limit (i.e. base pairs) used for analysis.
30 * **lev2** (*int*) - (0) Upper base level limit used for analysis. If lev1 > 0 and lev2 = 0, lev2 is set to lev1 (i.e. analyze lev1 only). If lev1=lev2=0, lev1 is set to 1 and lev2 is set to the length of the oligmer (i.e. analyze all levels).
31 * **nastr** (*str*) - ('NA') character string used to indicate missing data in .ser files.
32 * **cormin** (*float*) - (0.6) minimal absolute value for printing linear correlation coefficients between pairs of analyzed variables.
33 * **series** (*bool*) - (False) if True then output spatial or time series data. Only possible for the analysis of single structures or single trajectories.
34 * **histo** (*bool*) - (False) if True then output histogram data.
35 * **corr** (*bool*) - (False) if True than output linear correlation coefficients between all variables.
36 * **sequence** (*str*) - (Optional) sequence of the first strand of the corresponding DNA fragment, for each .cda file. If not given it will be parsed from .lis file.
37 * **binary_path** (*str*) - ('Canal') Path to Canal executable, otherwise the program wil look for Canal executable in the binaries folder.
38 * **remove_tmp** (*bool*) - (True) [WF property] Remove temporal files.
39 * **restart** (*bool*) - (False) [WF property] Do not execute if output files exist.
40 * **sandbox_path** (*str*) - ("./") [WF property] Parent path to the sandbox directory.
41 Examples:
42 This is a use example of how to use the building block from Python::
44 from biobb_dna.curvesplus.biobb_canal import biobb_canal
45 prop = {
46 'series': 'True',
47 'histo': 'True',
48 'sequence': 'CGCGAATTCGCG'
49 }
50 biobb_canal(
51 input_cda_file='/path/to/curves/output.cda',
52 output_zip_path='/path/to/output.zip',
53 properties=prop)
54 Info:
55 * wrapped_software:
56 * name: Canal
57 * version: >=2.6
58 * license: BSD 3-Clause
59 * ontology:
60 * name: EDAM
61 * schema: http://edamontology.org/EDAM.owl
62 """
64 def __init__(self, input_cda_file, input_lis_file=None,
65 output_zip_path=None, properties=None, **kwargs) -> None:
66 properties = properties or {}
68 # Call parent class constructor
69 super().__init__(properties)
70 self.locals_var_dict = locals().copy()
72 # Input/Output files
73 self.io_dict = {
74 'in': {
75 'input_cda_file': input_cda_file,
76 'input_lis_file': input_lis_file,
77 },
78 'out': {
79 'output_zip_path': output_zip_path
80 }
81 }
83 # Properties specific for BB
84 self.bases = properties.get('bases', None)
85 self.nastr = properties.get('nastr', None)
86 self.cormin = properties.get('cormin', 0.6)
87 self.lev1 = properties.get('lev1', 0)
88 self.lev2 = properties.get('lev2', 0)
89 self.itst = properties.get('itst', 0)
90 self.itnd = properties.get('itnd', 0)
91 self.itdel = properties.get('itdel', 1)
92 self.series = ".t." if properties.get('series', False) else ".f."
93 self.histo = ".t." if properties.get('histo', False) else ".f."
94 self.corr = ".t." if properties.get('corr', False) else ".f."
95 self.sequence = properties.get('sequence', None)
96 self.binary_path = properties.get('binary_path', 'Canal')
97 self.properties = properties
99 # Check the properties
100 self.check_properties(properties)
101 self.check_arguments()
103 @launchlogger
104 def launch(self) -> int:
105 """Execute the :class:`Canal <biobb_dna.curvesplus.biobb_canal.Canal>` object."""
107 # Setup Biobb
108 if self.check_restart():
109 return 0
110 self.stage_files()
112 if self.sequence is None:
113 if self.stage_io_dict['in']['input_lis_file'] is None:
114 raise RuntimeError(
115 "if no sequence is passed in the configuration, "
116 "you must at least specify `input_lis_file` "
117 "so sequence can be parsed from there")
118 lis_lines = Path(
119 self.stage_io_dict['in']['input_lis_file']).read_text().splitlines()
120 for line in lis_lines:
121 if line.strip().startswith("Strand 1"):
122 self.sequence = line.split(" ")[-1]
123 fu.log(
124 f"using sequence {self.sequence} "
125 f"from {self.stage_io_dict['in']['input_lis_file']}",
126 self.out_log)
128 # define temporary file name
129 tmp_cda_path = Path(self.stage_io_dict['in']['input_cda_file']).name
131 # change directory to temporary folder
132 original_directory = os.getcwd()
133 os.chdir(self.stage_io_dict.get("unique_dir", ""))
135 # create intructions
136 instructions = [
137 f"{self.binary_path} <<! ",
138 "&inp",
139 " lis=canal_output,"]
140 if self.bases is not None:
141 # add topology file if needed
142 fu.log('Appending sequence of bases to be searched to command',
143 self.out_log, self.global_log)
144 instructions.append(f" seq={self.bases},")
145 if self.nastr is not None:
146 # add topology file if needed
147 fu.log('Adding null values string specification to command',
148 self.out_log, self.global_log)
149 instructions.append(f" nastr={self.nastr},")
151 instructions = instructions + [
152 f" cormin={self.cormin},",
153 f" lev1={self.lev1},lev2={self.lev2},",
154 f" itst={self.itst},itnd={self.itnd},itdel={self.itdel},",
155 f" histo={self.histo},",
156 f" series={self.series},",
157 f" corr={self.corr},",
158 "&end",
159 f"{tmp_cda_path} {self.sequence}",
160 "!"]
162 self.cmd = ["\n".join(instructions)]
163 fu.log('Creating command line with instructions and required arguments',
164 self.out_log, self.global_log)
166 # Run Biobb block
167 self.run_biobb()
169 # change back to original directory
170 os.chdir(original_directory)
172 # create zipfile and write output inside
173 zf = zipfile.ZipFile(
174 Path(self.stage_io_dict["out"]["output_zip_path"]), "w")
175 for canal_outfile in Path(self.stage_io_dict.get("unique_dir", "")).glob("canal_output*"):
176 if canal_outfile.suffix not in (".zip"):
177 zf.write(
178 canal_outfile,
179 arcname=canal_outfile.name)
180 zf.close()
182 # Copy files to host
183 self.copy_to_host()
185 # Remove temporary file(s)
186 self.remove_tmp_files()
188 self.check_arguments(output_files_created=True, raise_exception=False)
190 return self.return_code
193def biobb_canal(
194 input_cda_file: str,
195 output_zip_path: str,
196 input_lis_file: Optional[str] = None,
197 properties: Optional[dict] = None,
198 **kwargs) -> int:
199 """Create :class:`Canal <biobb_dna.curvesplus.biobb_canal.Canal>` class and
200 execute the :meth:`launch() <biobb_dna.curvesplus.biobb_canal.Canal.launch>` method."""
201 return Canal(**dict(locals())).launch()
204biobb_canal.__doc__ = Canal.__doc__
205main = Canal.get_main(biobb_canal, "Execute Canal from the Curves+ software suite.")
208if __name__ == '__main__':
209 main()