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