391
|
1 import math
|
|
2 import re
|
|
3 import sys
|
|
4 import csv
|
|
5 import pickle
|
|
6 import lxml.etree as ET
|
|
7
|
|
8 from enum import Enum
|
|
9 from itertools import count
|
|
10 from typing import Any, Callable, Dict, Generic, List, Literal, Optional, TypeVar, Union
|
|
11
|
|
12 import pandas as pd
|
|
13 import cobra
|
|
14
|
|
15 import zipfile
|
|
16 import gzip
|
|
17 import bz2
|
|
18 from io import StringIO
|
|
19
|
|
20 class ValueErr(Exception):
|
|
21 def __init__(self, param_name, expected, actual):
|
|
22 super().__init__(f"Invalid value for {param_name}: expected {expected}, got {actual}")
|
|
23
|
|
24 class PathErr(Exception):
|
|
25 def __init__(self, path, message):
|
|
26 super().__init__(f"Path error for '{path}': {message}")
|
|
27
|
|
28 class FileFormat(Enum):
|
|
29 """
|
|
30 Encodes possible file extensions to conditionally save data in a different format.
|
|
31 """
|
|
32 DAT = ("dat",) # this is how galaxy treats all your files!
|
|
33 CSV = ("csv",) # this is how most editable input data is written
|
|
34 TSV = ("tsv",) # this is how most editable input data is ACTUALLY written TODO:more support pls!!
|
|
35 SVG = ("svg",) # this is how most metabolic maps are written
|
|
36 PNG = ("png",) # this is a common output format for images (such as metabolic maps)
|
|
37 PDF = ("pdf",) # this is also a common output format for images, as it's required in publications.
|
|
38
|
|
39 # Updated to include compressed variants
|
|
40 XML = ("xml", "xml.gz", "xml.zip", "xml.bz2") # SBML files are XML files, sometimes compressed
|
|
41 JSON = ("json", "json.gz", "json.zip", "json.bz2") # COBRA models can be stored as JSON files, sometimes compressed
|
|
42 MAT = ("mat", "mat.gz", "mat.zip", "mat.bz2") # COBRA models can be stored as MAT files, sometimes compressed
|
|
43 YML = ("yml", "yml.gz", "yml.zip", "yml.bz2") # COBRA models can be stored as YML files, sometimes compressed
|
|
44
|
|
45 TXT = ("txt",) # this is how most output data is written
|
|
46 PICKLE = ("pickle", "pk", "p") # this is how all runtime data structures are saved
|
|
47
|
|
48 def __init__(self, *extensions):
|
|
49 self.extensions = extensions
|
|
50 # Store original extension when set via fromExt
|
|
51 self._original_extension = None
|
|
52
|
|
53 @classmethod
|
|
54 def fromExt(cls, ext: str) -> "FileFormat":
|
|
55 """
|
|
56 Converts a file extension string to a FileFormat instance.
|
|
57 Args:
|
|
58 ext : The file extension as a string.
|
|
59 Returns:
|
|
60 FileFormat: The FileFormat instance corresponding to the file extension.
|
|
61 """
|
|
62 variantName = ext.upper()
|
|
63 if variantName in FileFormat.__members__:
|
|
64 instance = FileFormat[variantName]
|
|
65 instance._original_extension = ext
|
|
66 return instance
|
|
67
|
|
68 variantName = ext.lower()
|
|
69 for member in cls:
|
|
70 if variantName in member.value:
|
|
71 # Create a copy-like behavior by storing the original extension
|
|
72 member._original_extension = ext
|
|
73 return member
|
|
74
|
|
75 raise ValueErr("ext", "a valid FileFormat file extension", ext)
|
|
76
|
|
77 def __str__(self) -> str:
|
|
78 """
|
|
79 (Private) converts to str representation. Good practice for usage with argparse.
|
|
80 Returns:
|
|
81 str : the string representation of the file extension.
|
|
82 """
|
|
83 # If we have an original extension stored (for compressed files only), use it
|
|
84 if hasattr(self, '_original_extension') and self._original_extension:
|
|
85 return self._original_extension
|
|
86
|
|
87 # For XML, JSON, MAT and YML without original extension, use the base extension
|
|
88 if self == FileFormat.XML:
|
|
89 return "xml"
|
|
90 elif self == FileFormat.JSON:
|
|
91 return "json"
|
|
92 elif self == FileFormat.MAT:
|
|
93 return "mat"
|
|
94 elif self == FileFormat.YML:
|
|
95 return "yml"
|
|
96
|
|
97 return self.value[-1]
|
|
98
|
|
99 class FilePath():
|
|
100 """
|
|
101 Represents a file path. View this as an attempt to standardize file-related operations by expecting
|
|
102 values of this type in any process requesting a file path.
|
|
103 """
|
|
104 def __init__(self, filePath: str, ext: FileFormat, *, prefix="") -> None:
|
|
105 """
|
|
106 (Private) Initializes an instance of FilePath.
|
|
107 Args:
|
|
108 path : the end of the path, containing the file name.
|
|
109 ext : the file's extension.
|
|
110 prefix : anything before path, if the last '/' isn't there it's added by the code.
|
|
111 Returns:
|
|
112 None : practically, a FilePath instance.
|
|
113 """
|
|
114 self.ext = ext
|
|
115 self.filePath = filePath
|
|
116
|
|
117 if prefix and prefix[-1] != '/':
|
|
118 prefix += '/'
|
|
119 self.prefix = prefix
|
|
120
|
|
121 @classmethod
|
|
122 def fromStrPath(cls, path: str) -> "FilePath":
|
|
123 """
|
|
124 Factory method to parse a string from which to obtain, if possible, a valid FilePath instance.
|
|
125 It detects double extensions such as .json.gz and .xml.bz2, which are common in COBRA models.
|
|
126 These double extensions are not supported for other file types such as .csv.
|
|
127 Args:
|
|
128 path : the string containing the path
|
|
129 Raises:
|
|
130 PathErr : if the provided string doesn't represent a valid path.
|
|
131 Returns:
|
|
132 FilePath : the constructed instance.
|
|
133 """
|
|
134 result = re.search(r"^(?P<prefix>.*\/)?(?P<name>.*)\.(?P<ext>[^.]*)$", path)
|
|
135 if not result or not result["name"] or not result["ext"]:
|
|
136 raise PathErr(path, "cannot recognize folder structure or extension in path")
|
|
137
|
|
138 prefix = result["prefix"] if result["prefix"] else ""
|
|
139 name, ext = result["name"], result["ext"]
|
|
140
|
|
141 # Check for double extensions (json.gz, xml.zip, etc.)
|
|
142 parts = path.split(".")
|
|
143 if len(parts) >= 3:
|
|
144 penultimate = parts[-2]
|
|
145 last = parts[-1]
|
|
146 double_ext = f"{penultimate}.{last}"
|
|
147
|
|
148 # Try the double extension first
|
|
149 try:
|
|
150 ext_format = FileFormat.fromExt(double_ext)
|
|
151 name = ".".join(parts[:-2])
|
|
152 # Extract prefix if it exists
|
|
153 if '/' in name:
|
|
154 prefix = name[:name.rfind('/') + 1]
|
|
155 name = name[name.rfind('/') + 1:]
|
|
156 return cls(name, ext_format, prefix=prefix)
|
|
157 except ValueErr:
|
|
158 # If double extension doesn't work, fall back to single extension
|
|
159 pass
|
|
160
|
|
161 # Single extension fallback (original logic)
|
|
162 try:
|
|
163 ext_format = FileFormat.fromExt(ext)
|
|
164 return cls(name, ext_format, prefix=prefix)
|
|
165 except ValueErr:
|
|
166 raise PathErr(path, f"unsupported file extension: {ext}")
|
|
167
|
|
168 def show(self) -> str:
|
|
169 """
|
|
170 Shows the path as a string.
|
|
171 Returns:
|
|
172 str : the path shown as a string.
|
|
173 """
|
|
174 return f"{self.prefix}{self.filePath}.{self.ext}"
|
|
175
|
|
176 def __str__(self) -> str:
|
|
177 return self.show()
|
|
178
|
|
179 # ERRORS
|
|
180 def terminate(msg :str) -> None:
|
|
181 """
|
|
182 Terminate the execution of the script with an error message.
|
|
183
|
|
184 Args:
|
|
185 msg (str): The error message to be displayed.
|
|
186
|
|
187 Returns:
|
|
188 None
|
|
189 """
|
|
190 sys.exit(f"Execution aborted: {msg}\n")
|
|
191
|
|
192 def logWarning(msg :str, loggerPath :str) -> None:
|
|
193 """
|
|
194 Log a warning message to an output log file and print it to the console. The final period and a
|
|
195 newline is added by the function.
|
|
196
|
|
197 Args:
|
|
198 s (str): The warning message to be logged and printed.
|
|
199 loggerPath : The file path of the output log file. Given as a string, parsed to a FilePath and
|
|
200 immediately read back (beware relative expensive operation, log with caution).
|
|
201
|
|
202 Returns:
|
|
203 None
|
|
204 """
|
|
205 # building the path and then reading it immediately seems useless, but it's actually a way of
|
|
206 # validating that reduces repetition on the caller's side. Besides, logging a message by writing
|
|
207 # to a file is supposed to be computationally expensive anyway, so this is also a good deterrent from
|
|
208 # mindlessly logging whenever something comes up, log at the very end and tell the user everything
|
|
209 # that went wrong. If you don't like it: implement a persistent runtime buffer that gets dumped to
|
|
210 # the file only at the end of the program's execution.
|
|
211 with open(FilePath.fromStrPath(loggerPath).show(), 'a') as log: log.write(f"{msg}.\n")
|
|
212
|
|
213 class CustomErr(Exception):
|
|
214 """
|
|
215 Custom error class to handle exceptions in a structured way, with a unique identifier and a message.
|
|
216 """
|
|
217 __idGenerator = count()
|
|
218 errName = "Custom Error"
|
|
219 def __init__(self, msg :str, details = "", explicitErrCode = -1) -> None:
|
|
220 """
|
|
221 (Private) Initializes an instance of CustomErr.
|
|
222
|
|
223 Args:
|
|
224 msg (str): Error message to be displayed.
|
|
225 details (str): Informs the user more about the error encountered. Defaults to "".
|
|
226 explicitErrCode (int): Explicit error code to be used. Defaults to -1.
|
|
227
|
|
228 Returns:
|
|
229 None : practically, a CustomErr instance.
|
|
230 """
|
|
231 self.msg = msg
|
|
232 self.details = details
|
|
233
|
|
234 self.id = max(explicitErrCode, next(CustomErr.__idGenerator))
|
|
235
|
|
236 def throw(self, loggerPath = "") -> None:
|
|
237 """
|
|
238 Raises the current CustomErr instance, logging a warning message before doing so.
|
|
239
|
|
240 Raises:
|
|
241 self: The current CustomErr instance.
|
|
242
|
|
243 Returns:
|
|
244 None
|
|
245 """
|
|
246 if loggerPath: logWarning(str(self), loggerPath)
|
|
247 raise self
|
|
248
|
|
249 def abort(self) -> None:
|
|
250 """
|
|
251 Aborts the execution of the script.
|
|
252
|
|
253 Returns:
|
|
254 None
|
|
255 """
|
|
256 terminate(str(self))
|
|
257
|
|
258 def __str__(self) -> str:
|
|
259 """
|
|
260 (Private) Returns a string representing the current CustomErr instance.
|
|
261
|
|
262 Returns:
|
|
263 str: A string representing the current CustomErr instance.
|
|
264 """
|
|
265 return f"{CustomErr.errName} #{self.id}: {self.msg}, {self.details}."
|
|
266
|
|
267 class ArgsErr(CustomErr):
|
|
268 """
|
|
269 CustomErr subclass for UI arguments errors.
|
|
270 """
|
|
271 errName = "Args Error"
|
|
272 def __init__(self, argName :str, expected :Any, actual :Any, msg = "no further details provided") -> None:
|
|
273 super().__init__(f"argument \"{argName}\" expected {expected} but got {actual}", msg)
|
|
274
|
|
275 class DataErr(CustomErr):
|
|
276 """
|
|
277 CustomErr subclass for data formatting errors.
|
|
278 """
|
|
279 errName = "Data Format Error"
|
|
280 def __init__(self, fileName :str, msg = "no further details provided") -> None:
|
|
281 super().__init__(f"file \"{fileName}\" contains malformed data", msg)
|
|
282
|
|
283 class PathErr(CustomErr):
|
|
284 """
|
|
285 CustomErr subclass for filepath formatting errors.
|
|
286 """
|
|
287 errName = "Path Error"
|
|
288 def __init__(self, path :FilePath, msg = "no further details provided") -> None:
|
|
289 super().__init__(f"path \"{path}\" is invalid", msg)
|
|
290
|
|
291 class ValueErr(CustomErr):
|
|
292 """
|
|
293 CustomErr subclass for any value error.
|
|
294 """
|
|
295 errName = "Value Error"
|
|
296 def __init__(self, valueName: str, expected :Any, actual :Any, msg = "no further details provided") -> None:
|
|
297 super().__init__("value " + f"\"{valueName}\" " * bool(valueName) + f"was supposed to be {expected}, but got {actual} instead", msg)
|
|
298
|
|
299 # RESULT
|
|
300 T = TypeVar('T')
|
|
301 E = TypeVar('E', bound = CustomErr) # should bind to Result.ResultErr but python happened!
|
|
302 class Result(Generic[T, E]):
|
|
303 class ResultErr(CustomErr):
|
|
304 """
|
|
305 CustomErr subclass for all Result errors.
|
|
306 """
|
|
307 errName = "Result Error"
|
|
308 def __init__(self, msg = "no further details provided") -> None:
|
|
309 super().__init__(msg)
|
|
310 """
|
|
311 Class to handle the result of an operation, with a value and a boolean flag to indicate
|
|
312 whether the operation was successful or not.
|
|
313 """
|
|
314 def __init__(self, value :Union[T, E], isOk :bool) -> None:
|
|
315 """
|
|
316 (Private) Initializes an instance of Result.
|
|
317
|
|
318 Args:
|
|
319 value (Union[T, E]): The value to be stored in the Result instance.
|
|
320 isOk (bool): A boolean flag to indicate whether the operation was successful or not.
|
|
321
|
|
322 Returns:
|
|
323 None : practically, a Result instance.
|
|
324 """
|
|
325 self.isOk = isOk
|
|
326 self.isErr = not isOk
|
|
327 self.value = value
|
|
328
|
|
329 @classmethod
|
|
330 def Ok(cls, value :T) -> "Result":
|
|
331 """
|
|
332 Constructs a new Result instance with a successful operation.
|
|
333
|
|
334 Args:
|
|
335 value (T): The value to be stored in the Result instance, set as successful.
|
|
336
|
|
337 Returns:
|
|
338 Result: A new Result instance with a successful operation.
|
|
339 """
|
|
340 return Result(value, isOk = True)
|
|
341
|
|
342 @classmethod
|
|
343 def Err(cls, value :E) -> "Result":
|
|
344 """
|
|
345 Constructs a new Result instance with a failed operation.
|
|
346
|
|
347 Args:
|
|
348 value (E): The value to be stored in the Result instance, set as failed.
|
|
349
|
|
350 Returns:
|
|
351 Result: A new Result instance with a failed operation.
|
|
352 """
|
|
353 return Result(value, isOk = False)
|
|
354
|
|
355 def unwrap(self) -> T:
|
|
356 """
|
|
357 Unwraps the value of the Result instance, if the operation was successful.
|
|
358
|
|
359 Raises:
|
|
360 ResultErr: If the operation was not successful.
|
|
361
|
|
362 Returns:
|
|
363 T: The value of the Result instance, if the operation was successful.
|
|
364 """
|
|
365 if self.isOk: return self.value
|
|
366 raise Result.ResultErr(f"Unwrapped Result.Err : {self.value}")
|
|
367
|
|
368 def unwrapOr(self, default :T) -> T:
|
|
369 """
|
|
370 Unwraps the value of the Result instance, if the operation was successful, otherwise
|
|
371 it returns a default value.
|
|
372
|
|
373 Args:
|
|
374 default (T): The default value to be returned if the operation was not successful.
|
|
375
|
|
376 Returns:
|
|
377 T: The value of the Result instance, if the operation was successful,
|
|
378 otherwise the default value.
|
|
379 """
|
|
380 return self.value if self.isOk else default
|
|
381
|
|
382 def expect(self, err :"Result.ResultErr") -> T:
|
|
383 """
|
|
384 Expects that the value of the Result instance is successful, otherwise it raises an error.
|
|
385
|
|
386 Args:
|
|
387 err (Exception): The error to be raised if the operation was not successful.
|
|
388
|
|
389 Raises:
|
|
390 err: The error raised if the operation was not successful.
|
|
391
|
|
392 Returns:
|
|
393 T: The value of the Result instance, if the operation was successful.
|
|
394 """
|
|
395 if self.isOk: return self.value
|
|
396 raise err
|
|
397
|
|
398 U = TypeVar("U")
|
|
399 def map(self, mapper: Callable[[T], U]) -> "Result[U, E]":
|
|
400 """
|
|
401 Maps the value of the current Result to whatever is returned by the mapper function.
|
|
402 If the Result contained an unsuccessful operation to begin with it remains unchanged
|
|
403 (a reference to the current instance is returned).
|
|
404 If the mapper function panics the returned result instance will be of the error kind.
|
|
405
|
|
406 Args:
|
|
407 mapper (Callable[[T], U]): The mapper operation to be applied to the Result value.
|
|
408
|
|
409 Returns:
|
|
410 Result[U, E]: The result of the mapper operation applied to the Result value.
|
|
411 """
|
|
412 if self.isErr: return self
|
|
413 try: return Result.Ok(mapper(self.value))
|
|
414 except Exception as e: return Result.Err(e)
|
|
415
|
|
416 D = TypeVar("D", bound = "Result.ResultErr")
|
|
417 def mapErr(self, mapper :Callable[[E], D]) -> "Result[T, D]":
|
|
418 """
|
|
419 Maps the error of the current Result to whatever is returned by the mapper function.
|
|
420 If the Result contained a successful operation it remains unchanged
|
|
421 (a reference to the current instance is returned).
|
|
422 If the mapper function panics this method does as well.
|
|
423
|
|
424 Args:
|
|
425 mapper (Callable[[E], D]): The mapper operation to be applied to the Result error.
|
|
426
|
|
427 Returns:
|
|
428 Result[U, E]: The result of the mapper operation applied to the Result error.
|
|
429 """
|
|
430 if self.isOk: return self
|
|
431 return Result.Err(mapper(self.value))
|
|
432
|
|
433 def __str__(self):
|
|
434 return f"Result::{'Ok' if self.isOk else 'Err'}({self.value})"
|
|
435
|
|
436 # FILES
|
|
437 def read_dataset(path :FilePath, datasetName = "Dataset (not actual file name!)") -> pd.DataFrame:
|
|
438 """
|
|
439 Reads a .csv or .tsv file and returns it as a Pandas DataFrame.
|
|
440
|
|
441 Args:
|
|
442 path : the path to the dataset file.
|
|
443 datasetName : the name of the dataset.
|
|
444
|
|
445 Raises:
|
|
446 DataErr: If anything goes wrong when trying to open the file, if pandas thinks the dataset is empty or if
|
|
447 it has less than 2 columns.
|
|
448
|
|
449 Returns:
|
|
450 pandas.DataFrame: The dataset loaded as a Pandas DataFrame.
|
|
451 """
|
|
452 # I advise against the use of this function. This is an attempt at standardizing bad legacy code rather than
|
|
453 # removing / replacing it to avoid introducing as many bugs as possible in the tools still relying on this code.
|
|
454 # First off, this is not the best way to distinguish between .csv and .tsv files and Galaxy itself makes it really
|
|
455 # hard to implement anything better. Also, this function's name advertizes it as a dataset-specific operation and
|
|
456 # contains dubious responsibility (how many columns..) while being a file-opening function instead. My suggestion is
|
|
457 # TODO: stop using dataframes ever at all in anything and find a way to have tight control over file extensions.
|
|
458 try: dataset = pd.read_csv(path.show(), sep = '\t', header = None, engine = "python")
|
|
459 except:
|
|
460 try: dataset = pd.read_csv(path.show(), sep = ',', header = 0, engine = "python")
|
|
461 except Exception as err: raise DataErr(datasetName, f"encountered empty or wrongly formatted data: {err}")
|
|
462
|
|
463 if len(dataset.columns) < 2: raise DataErr(datasetName, "a dataset is always meant to have at least 2 columns")
|
|
464 return dataset
|
|
465
|
|
466 def readPickle(path :FilePath) -> Any:
|
|
467 """
|
|
468 Reads the contents of a .pickle file, which needs to exist at the given path.
|
|
469
|
|
470 Args:
|
|
471 path : the path to the .pickle file.
|
|
472
|
|
473 Returns:
|
|
474 Any : the data inside a pickle file, could be anything.
|
|
475 """
|
|
476 with open(path.show(), "rb") as fd: return pickle.load(fd)
|
|
477
|
|
478 def writePickle(path :FilePath, data :Any) -> None:
|
|
479 """
|
|
480 Saves any data in a .pickle file, created at the given path.
|
|
481
|
|
482 Args:
|
|
483 path : the path to the .pickle file.
|
|
484 data : the data to be written to the file.
|
|
485
|
|
486 Returns:
|
|
487 None
|
|
488 """
|
|
489 with open(path.show(), "wb") as fd: pickle.dump(data, fd)
|
|
490
|
|
491 def readCsv(path :FilePath, delimiter = ',', *, skipHeader = True) -> List[List[str]]:
|
|
492 """
|
|
493 Reads the contents of a .csv file, which needs to exist at the given path.
|
|
494
|
|
495 Args:
|
|
496 path : the path to the .csv file.
|
|
497 delimiter : allows other subformats such as .tsv to be opened by the same method (\\t delimiter).
|
|
498 skipHeader : whether the first row of the file is a header and should be skipped.
|
|
499
|
|
500 Returns:
|
|
501 List[List[str]] : list of rows from the file, each parsed as a list of strings originally separated by commas.
|
|
502 """
|
|
503 with open(path.show(), "r", newline = "") as fd: return list(csv.reader(fd, delimiter = delimiter))[skipHeader:]
|
|
504
|
|
505 def readSvg(path :FilePath, customErr :Optional[Exception] = None) -> ET.ElementTree:
|
|
506 """
|
|
507 Reads the contents of a .svg file, which needs to exist at the given path.
|
|
508
|
|
509 Args:
|
|
510 path : the path to the .svg file.
|
|
511
|
|
512 Raises:
|
|
513 DataErr : if the map is malformed.
|
|
514
|
|
515 Returns:
|
|
516 Any : the data inside a svg file, could be anything.
|
|
517 """
|
|
518 try: return ET.parse(path.show())
|
|
519 except (ET.XMLSyntaxError, ET.XMLSchemaParseError) as err:
|
|
520 raise customErr if customErr else err
|
|
521
|
|
522 def writeSvg(path :FilePath, data:ET.ElementTree) -> None:
|
|
523 """
|
|
524 Saves svg data opened with lxml.etree in a .svg file, created at the given path.
|
|
525
|
|
526 Args:
|
|
527 path : the path to the .svg file.
|
|
528 data : the data to be written to the file.
|
|
529
|
|
530 Returns:
|
|
531 None
|
|
532 """
|
|
533 with open(path.show(), "wb") as fd: fd.write(ET.tostring(data))
|
|
534
|
|
535 # UI ARGUMENTS
|
|
536 class Bool:
|
|
537 def __init__(self, argName :str) -> None:
|
|
538 self.argName = argName
|
|
539
|
|
540 def __call__(self, s :str) -> bool: return self.check(s)
|
|
541
|
|
542 def check(self, s :str) -> bool:
|
|
543 s = s.lower()
|
|
544 if s == "true" : return True
|
|
545 if s == "false": return False
|
|
546 raise ArgsErr(self.argName, "boolean string (true or false, not case sensitive)", f"\"{s}\"")
|
|
547
|
|
548 class Float:
|
|
549 def __init__(self, argName = "Dataset values, not an argument") -> None:
|
|
550 self.argName = argName
|
|
551
|
|
552 def __call__(self, s :str) -> float: return self.check(s)
|
|
553
|
|
554 def check(self, s :str) -> float:
|
|
555 try: return float(s)
|
|
556 except ValueError:
|
|
557 s = s.lower()
|
|
558 if s == "nan" or s == "none": return math.nan
|
|
559 raise ArgsErr(self.argName, "numeric string or \"None\" or \"NaN\" (not case sensitive)", f"\"{s}\"")
|
|
560
|
|
561 # MODELS
|
|
562 OldRule = List[Union[str, "OldRule"]]
|
|
563 class Model(Enum):
|
|
564 """
|
|
565 Represents a metabolic model, either custom or locally supported. Custom models don't point
|
|
566 to valid file paths.
|
|
567 """
|
|
568
|
|
569 Recon = "Recon"
|
|
570 ENGRO2 = "ENGRO2"
|
|
571 ENGRO2_no_legend = "ENGRO2_no_legend"
|
|
572 HMRcore = "HMRcore"
|
|
573 HMRcore_no_legend = "HMRcore_no_legend"
|
|
574 Custom = "Custom" # Exists as a valid variant in the UI, but doesn't point to valid file paths.
|
|
575
|
|
576 def __raiseMissingPathErr(self, path :Optional[FilePath]) -> None:
|
|
577 if not path: raise PathErr("<<MISSING>>", "it's necessary to provide a custom path when retrieving files from a custom model")
|
|
578
|
|
579 def getRules(self, toolDir :str, customPath :Optional[FilePath] = None) -> Dict[str, Dict[str, OldRule]]:
|
|
580 """
|
|
581 Open "rules" file for this model.
|
|
582
|
|
583 Returns:
|
|
584 Dict[str, Dict[str, OldRule]] : the rules for this model.
|
|
585 """
|
|
586 path = customPath if self is Model.Custom else FilePath(f"{self.name}_rules", FileFormat.PICKLE, prefix = f"{toolDir}/local/pickle files/")
|
|
587 self.__raiseMissingPathErr(path)
|
|
588 return readPickle(path)
|
|
589
|
|
590 def getTranslator(self, toolDir :str, customPath :Optional[FilePath] = None) -> Dict[str, Dict[str, str]]:
|
|
591 """
|
|
592 Open "gene translator (old: gene_in_rule)" file for this model.
|
|
593
|
|
594 Returns:
|
|
595 Dict[str, Dict[str, str]] : the translator dict for this model.
|
|
596 """
|
|
597 path = customPath if self is Model.Custom else FilePath(f"{self.name}_genes", FileFormat.PICKLE, prefix = f"{toolDir}/local/pickle files/")
|
|
598 self.__raiseMissingPathErr(path)
|
|
599 return readPickle(path)
|
|
600
|
|
601 def getMap(self, toolDir = ".", customPath :Optional[FilePath] = None) -> ET.ElementTree:
|
|
602 path = customPath if self is Model.Custom else FilePath(f"{self.name}_map", FileFormat.SVG, prefix = f"{toolDir}/local/svg metabolic maps/")
|
|
603 self.__raiseMissingPathErr(path)
|
|
604 return readSvg(path, customErr = DataErr(path, f"custom map in wrong format"))
|
|
605
|
|
606 def getCOBRAmodel(self, toolDir = ".", customPath :Optional[FilePath] = None, customExtension :Optional[FilePath]=None)->cobra.Model:
|
|
607 if(self is Model.Custom):
|
|
608 return self.load_custom_model(customPath, customExtension)
|
|
609 else:
|
|
610 return cobra.io.read_sbml_model(FilePath(f"{self.name}", FileFormat.XML, prefix = f"{toolDir}/local/models/").show())
|
|
611
|
|
612 def load_custom_model(self, file_path :FilePath, ext :Optional[FileFormat] = None) -> cobra.Model:
|
|
613 ext = ext if ext else file_path.ext
|
|
614 try:
|
|
615 if str(ext) in FileFormat.XML.value:
|
|
616 return cobra.io.read_sbml_model(file_path.show())
|
|
617
|
|
618 if str(ext) in FileFormat.JSON.value:
|
|
619 # Compressed files are not automatically handled by cobra
|
|
620 if(ext == "json"):
|
|
621 return cobra.io.load_json_model(file_path.show())
|
|
622 else:
|
|
623 return self.extract_model(file_path, ext, "json")
|
|
624
|
|
625 if str(ext) in FileFormat.MAT.value:
|
|
626 # Compressed files are not automatically handled by cobra
|
|
627 if(ext == "mat"):
|
|
628 return cobra.io.load_matlab_model(file_path.show())
|
|
629 else:
|
|
630 return self.extract_model(file_path, ext, "mat")
|
|
631
|
|
632 if str(ext) in FileFormat.YML.value:
|
|
633 # Compressed files are not automatically handled by cobra
|
|
634 if(ext == "yml"):
|
|
635 return cobra.io.load_yaml_model(file_path.show())
|
|
636 else:
|
|
637 return self.extract_model(file_path, ext, "yml")
|
|
638
|
|
639 except Exception as e: raise DataErr(file_path, e.__str__())
|
|
640 raise DataErr(file_path,
|
|
641 f"Fomat \"{file_path.ext}\" is not recognized, only JSON, XML, MAT and YAML (.yml) files are supported.")
|
|
642
|
|
643
|
|
644 def extract_model(self, file_path:FilePath, ext :FileFormat, model_encoding:Literal["json", "mat", "yml"]) -> cobra.Model:
|
|
645 """
|
|
646 Extract JSON, MAT and YAML COBRA model from a compressed file (zip, gz, bz2).
|
|
647
|
|
648 Args:
|
|
649 file_path: File path of the model
|
|
650 ext: File extensions of class FileFormat (should be .zip, .gz or .bz2)
|
|
651
|
|
652 Returns:
|
|
653 cobra.Model: COBRApy model
|
|
654
|
|
655 Raises:
|
|
656 Exception: Extraction errors
|
|
657 """
|
|
658 ext_str = str(ext)
|
|
659
|
|
660 try:
|
|
661 if '.zip' in ext_str:
|
|
662 with zipfile.ZipFile(file_path.show(), 'r') as zip_ref:
|
|
663 with zip_ref.open(zip_ref.namelist()[0]) as json_file:
|
|
664 content = json_file.read().decode('utf-8')
|
|
665 if model_encoding == "json":
|
|
666 return cobra.io.load_json_model(StringIO(content))
|
|
667 elif model_encoding == "mat":
|
|
668 return cobra.io.load_matlab_model(StringIO(content))
|
|
669 elif model_encoding == "yml":
|
|
670 return cobra.io.load_yaml_model(StringIO(content))
|
|
671 else:
|
|
672 raise ValueError(f"Unsupported model encoding: {model_encoding}. Supported: json, mat, yml")
|
|
673 elif '.gz' in ext_str:
|
|
674 with gzip.open(file_path.show(), 'rt', encoding='utf-8') as gz_ref:
|
|
675 if model_encoding == "json":
|
|
676 return cobra.io.load_json_model(gz_ref)
|
|
677 elif model_encoding == "mat":
|
|
678 return cobra.io.load_matlab_model(gz_ref)
|
|
679 elif model_encoding == "yml":
|
|
680 return cobra.io.load_yaml_model(gz_ref)
|
|
681 else:
|
|
682 raise ValueError(f"Unsupported model encoding: {model_encoding}. Supported: json, mat, yml")
|
|
683 elif '.bz2' in ext_str:
|
|
684 with bz2.open(file_path.show(), 'rt', encoding='utf-8') as bz2_ref:
|
|
685 if model_encoding == "json":
|
|
686 return cobra.io.load_json_model(bz2_ref)
|
|
687 elif model_encoding == "mat":
|
|
688 return cobra.io.load_matlab_model(bz2_ref)
|
|
689 elif model_encoding == "yml":
|
|
690 return cobra.io.load_yaml_model(bz2_ref)
|
|
691 else:
|
|
692 raise ValueError(f"Unsupported model encoding: {model_encoding}. Supported: json, mat, yml")
|
|
693 else:
|
|
694 raise ValueError(f"Compression format not supported: {ext_str}. Supported: .zip, .gz and .bz2")
|
|
695
|
|
696 except Exception as e:
|
|
697 raise Exception(f"Error during model extraction: {str(e)}")
|
|
698
|
|
699
|
|
700
|
240
|
701 def __str__(self) -> str: return self.value |