utils
Functions and decorators for common tasks in Python programming.
ExternalTool
¶
A class to manage and run external tools.
This class provides a unified interface for managing external bioinformatics tools, handling path resolution, and executing commands with proper error checking.
Parameters¶
name : str The name of the external tool. default_path : Optional[str], optional The default path to the tool if not found in the system PATH, by default None.
Attributes¶
name : str The name of the external tool. default_path : Optional[str] The default path to the tool if not found in the system PATH. custom_path : Optional[str] A custom path set by the user.
Methods¶
set_custom_path(path: str) -> None Sets a custom path for the tool if it exists. get_path() -> str Retrieves the path to the tool, checking custom, system, and default paths. run(command: List[str], log_file: str, output_file_path: Optional[Union[str, List[str]]]) -> None Runs the tool with the given arguments.
Examples¶
tool = ExternalTool("samtools", "/usr/local/bin/samtools") tool.set_custom_path("/opt/samtools/bin/samtools") tool.run(["view", "-h", "input.bam"], "samtools.log", "output.sam")
Source code in credtools/utils.py
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 |
|
__init__(name, default_path=None)
¶
Initialize the ExternalTool with a name and an optional default path.
Parameters¶
name : str The name of the external tool. default_path : Optional[str], optional The default path to the tool if not found in the system PATH, by default None.
Source code in credtools/utils.py
get_path()
¶
Retrieve the path to the tool, checking custom, system, and default paths.
The function checks paths in the following order: 1. Custom path (if set via set_custom_path) 2. System PATH (using shutil.which) 3. Default path (relative to package directory)
Returns¶
str The path to the tool.
Raises¶
FileNotFoundError If the tool cannot be found in any of the paths.
Source code in credtools/utils.py
run(command, log_file, output_file_path=None, timeout=None)
¶
Execute a command line instruction, log the output, and handle errors.
This function runs the given command, captures stdout and stderr, logs them using logging.debug, and raises exceptions for command failures, timeouts, or missing output files.
Parameters¶
command : List[str] The command line instruction to be executed (without the tool name). log_file : str The file to log the output. output_file_path : Optional[Union[str, List[str]]], optional The expected output file path(s). If provided, the function will check if these files exist after command execution, by default None. timeout : Optional[float], optional Maximum runtime in seconds. If the command exceeds this limit, it will be terminated and a TimeoutError will be raised, by default None.
Raises¶
TimeoutError If the command execution exceeds the provided timeout. subprocess.CalledProcessError If the command execution fails. FileNotFoundError If the specified output file is not found after command execution.
Examples¶
tool = ExternalTool("finemap") tool.run(["--help"], "finemap.log") tool.run(["--in-files", "data.master"], "finemap.log", "output.snp")
Source code in credtools/utils.py
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 |
|
set_custom_path(path)
¶
Set a custom path for the tool if it exists.
Parameters¶
path : str The custom path to set.
Raises¶
FileNotFoundError If the custom path does not exist.
Source code in credtools/utils.py
ToolManager
¶
A class to manage multiple external tools.
This class provides a centralized registry for managing multiple external tools, allowing for easy registration, configuration, and execution of bioinformatics software.
Attributes¶
tools : Dict[str, ExternalTool] A dictionary to store registered tools by their names.
Methods¶
register_tool(name: str, default_path: Optional[str] = None) -> None Registers a new tool with an optional default path. set_tool_path(name: str, path: str) -> None Sets a custom path for a registered tool. get_tool(name: str) -> ExternalTool Retrieves a registered tool by its name. run_tool(name: str, args: List[str], log_file: str, output_file_path: Optional[Union[str, List[str]]], timeout: Optional[float] = None) -> None Runs a registered tool with the given arguments.
Examples¶
manager = ToolManager() manager.register_tool("finemap", "bin/finemap") manager.set_tool_path("finemap", "/usr/local/bin/finemap") manager.run_tool("finemap", ["--help"], "finemap.log")
Source code in credtools/utils.py
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 |
|
__init__()
¶
get_tool(name)
¶
Retrieve a registered tool by its name.
Parameters¶
name : str The name of the registered tool.
Returns¶
ExternalTool The registered tool.
Raises¶
KeyError If the tool is not registered.
Source code in credtools/utils.py
register_tool(name, default_path=None)
¶
Register a new tool with an optional default path.
Parameters¶
name : str The name of the tool to register. default_path : Optional[str], optional The default path to the tool if not found in the system PATH, by default None.
Source code in credtools/utils.py
run_tool(name, args, log_file, output_file_path=None, timeout=None)
¶
Run a registered tool with the given arguments.
Parameters¶
name : str The name of the registered tool. args : List[str] The arguments to pass to the tool. log_file : str The file to log the output. output_file_path : Optional[Union[str, List[str]]], optional The expected output file path(s). If provided, the function will check if these files exist after command execution, by default None. timeout : Optional[float], optional Maximum runtime in seconds for the tool execution, by default None.
Raises¶
KeyError If the tool is not registered. subprocess.CalledProcessError If the subprocess call fails. FileNotFoundError If expected output files are not found after execution. TimeoutError If the tool execution exceeds the provided timeout.
Source code in credtools/utils.py
set_tool_path(name, path)
¶
Set a custom path for a registered tool.
Parameters¶
name : str The name of the registered tool. path : str The custom path to set for the tool.
Raises¶
KeyError If the tool is not registered.
Source code in credtools/utils.py
create_float_format_dict(df)
¶
Create a dictionary of float formats for DataFrame columns.
Parameters¶
df : pd.DataFrame DataFrame to create format dictionary for.
Returns¶
Dict[str, str] Dictionary mapping column names to format strings.
Source code in credtools/utils.py
format_float(x, decimals=4, sci_threshold=0.0001)
¶
Format floating point numbers for output.
Parameters¶
x : Any The value to format. decimals : int, optional Number of decimal places for regular numbers, by default 4. sci_threshold : float, optional Threshold below which to use scientific notation, by default 1e-4.
Returns¶
str Formatted string representation.
Source code in credtools/utils.py
format_pvalue(p)
¶
get_float_format(col_name)
¶
Get appropriate float format for a column based on its name.
Parameters¶
col_name : str Column name.
Returns¶
Optional[str] Format string or None for default formatting.
Source code in credtools/utils.py
io_in_tempdir(dir='./tmp')
¶
Create a temporary directory for I/O operations during function execution.
This decorator creates a temporary directory before executing the decorated function and
provides the path to this directory via the temp_dir
keyword argument. After the function
execution, the temporary directory is removed based on the logging level:
- If the logging level is set to INFO
or higher, the temporary directory is deleted.
- If the logging level is lower than INFO
(e.g., DEBUG
), the directory is retained for inspection.
Parameters¶
dir : str, optional The parent directory where the temporary directory will be created, by default "./tmp".
Returns¶
Callable[[F], F] A decorator that manages a temporary directory for the decorated function.
Raises¶
OSError If the temporary directory cannot be created.
Examples¶
@io_in_tempdir(dir="./temporary")
def process_data(temp_dir: str, data: str) -> None:
# Perform I/O operations using temp_dir
with open(f"{temp_dir}/data.txt", "w") as file:
file.write(data)
process_data(data="Sample data")