annotate COBRAxy/utils/general_utils.py @ 245:58037c24c716 draft

Uploaded
author francesco_lapi
date Wed, 15 Jan 2025 11:08:09 +0000
parents 63f5078627a9
children
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
rev   line source
240
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
1 import math
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
2 import re
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
3 import sys
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
4 import csv
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
5 import pickle
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
6 import lxml.etree as ET
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
7
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
8 from enum import Enum
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
9 from itertools import count
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
10 from typing import Any, Callable, Dict, Generic, List, Optional, TypeVar, Union
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
11
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
12 import pandas as pd
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
13 import cobra
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
14
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
15 # FILES
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
16 class FileFormat(Enum):
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
17 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
18 Encodes possible file extensions to conditionally save data in a different format.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
19 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
20 DAT = ("dat",) # this is how galaxy treats all your files!
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
21 CSV = ("csv",) # this is how most editable input data is written
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
22 TSV = ("tsv",) # this is how most editable input data is ACTUALLY written TODO:more support pls!!
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
23
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
24 SVG = ("svg",) # this is how most metabolic maps are written
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
25 PNG = ("png",) # this is a common output format for images (such as metabolic maps)
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
26 PDF = ("pdf",) # this is also a common output format for images, as it's required in publications.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
27
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
28 XML = ("xml",) # this is one main way cobra models appear in
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
29 JSON = ("json",) # this is the other
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
30
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
31 TXT = ("txt",) # this is how most output data is written
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
32
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
33 PICKLE = ("pickle", "pk", "p") # this is how all runtime data structures are saved
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
34 #TODO: we're in a pickle (ba dum tss), there's no point in supporting many extensions internally. The
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
35 # issue will never be solved for user-uploaded files and those are saved as .dat by galaxy anyway so it
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
36 # doesn't matter as long as we CAN recognize these 3 names as valid pickle extensions. We must however
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
37 # agree on an internal standard and use only that one, otherwise constructing usable paths becomes a nightmare.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
38 @classmethod
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
39 def fromExt(cls, ext :str) -> "FileFormat":
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
40 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
41 Converts a file extension string to a FileFormat instance.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
42
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
43 Args:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
44 ext : The file extension as a string.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
45
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
46 Returns:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
47 FileFormat: The FileFormat instance corresponding to the file extension.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
48 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
49 variantName = ext.upper()
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
50 if variantName in FileFormat.__members__: return FileFormat[variantName]
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
51
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
52 variantName = variantName.lower()
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
53 for member in cls:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
54 if variantName in member.value: return member
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
55
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
56 raise ValueErr("ext", "a valid FileFormat file extension", ext)
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
57
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
58 def __str__(self) -> str:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
59 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
60 (Private) converts to str representation. Good practice for usage with argparse.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
61
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
62 Returns:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
63 str : the string representation of the file extension.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
64 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
65 return self.value[-1] #TODO: fix, it's the dumb pickle thing
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
66
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
67 class FilePath():
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
68 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
69 Represents a file path. View this as an attempt to standardize file-related operations by expecting
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
70 values of this type in any process requesting a file path.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
71 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
72 def __init__(self, filePath :str, ext :FileFormat, *, prefix = "") -> None:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
73 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
74 (Private) Initializes an instance of FilePath.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
75
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
76 Args:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
77 path : the end of the path, containing the file name.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
78 ext : the file's extension.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
79 prefix : anything before path, if the last '/' isn't there it's added by the code.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
80
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
81 Returns:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
82 None : practically, a FilePath instance.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
83 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
84 self.ext = ext
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
85 self.filePath = filePath
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
86
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
87 if prefix and prefix[-1] != '/': prefix += '/'
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
88 self.prefix = prefix
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
89
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
90 @classmethod
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
91 def fromStrPath(cls, path :str) -> "FilePath":
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
92 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
93 Factory method to parse a string from which to obtain, if possible, a valid FilePath instance.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
94
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
95 Args:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
96 path : the string containing the path
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
97
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
98 Raises:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
99 PathErr : if the provided string doesn't represent a valid path.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
100
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
101 Returns:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
102 FilePath : the constructed instance.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
103 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
104 # This method is often used to construct FilePath instances from ARGS UI arguments. These arguments *should*
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
105 # always be correct paths and could be used as raw strings, however most if not all functions that work with
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
106 # file paths request the FilePath objects specifically, which is a very good thing in any case other than this.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
107 # What ends up happening is we spend time parsing a string into a FilePath so that the function accepts it, only
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
108 # to call show() immediately to bring back the string and open the file it points to.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
109 # TODO: this is an indication that the arguments SHOULD BE OF TYPE FilePath if they are filepaths, this ENSURES
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
110 # their correctness when modifying the UI and avoids the pointless back-and-forth.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
111 result = re.search(r"^(?P<prefix>.*\/)?(?P<name>.*)\.(?P<ext>[^.]*)$", path)
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
112 if not result or not result["name"] or not result["ext"]:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
113 raise PathErr(path, "cannot recognize folder structure or extension in path")
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
114
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
115 prefix = result["prefix"] if result["prefix"] else ""
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
116 return cls(result["name"], FileFormat.fromExt(result["ext"]), prefix = prefix)
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
117
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
118 def show(self) -> str:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
119 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
120 Shows the path as a string.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
121
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
122 Returns:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
123 str : the path shown as a string.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
124 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
125 return f"{self.prefix}{self.filePath}.{self.ext}"
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
126
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
127 def __str__(self) -> str: return self.show()
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
128
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
129 # ERRORS
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
130 def terminate(msg :str) -> None:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
131 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
132 Terminate the execution of the script with an error message.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
133
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
134 Args:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
135 msg (str): The error message to be displayed.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
136
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
137 Returns:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
138 None
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
139 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
140 sys.exit(f"Execution aborted: {msg}\n")
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
141
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
142 def logWarning(msg :str, loggerPath :str) -> None:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
143 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
144 Log a warning message to an output log file and print it to the console. The final period and a
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
145 newline is added by the function.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
146
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
147 Args:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
148 s (str): The warning message to be logged and printed.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
149 loggerPath : The file path of the output log file. Given as a string, parsed to a FilePath and
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
150 immediately read back (beware relative expensive operation, log with caution).
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
151
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
152 Returns:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
153 None
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
154 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
155 # building the path and then reading it immediately seems useless, but it's actually a way of
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
156 # validating that reduces repetition on the caller's side. Besides, logging a message by writing
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
157 # to a file is supposed to be computationally expensive anyway, so this is also a good deterrent from
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
158 # mindlessly logging whenever something comes up, log at the very end and tell the user everything
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
159 # that went wrong. If you don't like it: implement a persistent runtime buffer that gets dumped to
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
160 # the file only at the end of the program's execution.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
161 with open(FilePath.fromStrPath(loggerPath).show(), 'a') as log: log.write(f"{msg}.\n")
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
162
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
163 class CustomErr(Exception):
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
164 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
165 Custom error class to handle exceptions in a structured way, with a unique identifier and a message.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
166 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
167 __idGenerator = count()
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
168 errName = "Custom Error"
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
169 def __init__(self, msg :str, details = "", explicitErrCode = -1) -> None:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
170 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
171 (Private) Initializes an instance of CustomErr.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
172
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
173 Args:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
174 msg (str): Error message to be displayed.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
175 details (str): Informs the user more about the error encountered. Defaults to "".
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
176 explicitErrCode (int): Explicit error code to be used. Defaults to -1.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
177
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
178 Returns:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
179 None : practically, a CustomErr instance.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
180 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
181 self.msg = msg
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
182 self.details = details
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
183
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
184 self.id = max(explicitErrCode, next(CustomErr.__idGenerator))
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
185
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
186 def throw(self, loggerPath = "") -> None:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
187 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
188 Raises the current CustomErr instance, logging a warning message before doing so.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
189
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
190 Raises:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
191 self: The current CustomErr instance.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
192
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
193 Returns:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
194 None
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
195 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
196 if loggerPath: logWarning(str(self), loggerPath)
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
197 raise self
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
198
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
199 def abort(self) -> None:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
200 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
201 Aborts the execution of the script.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
202
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
203 Returns:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
204 None
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
205 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
206 terminate(str(self))
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
207
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
208 def __str__(self) -> str:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
209 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
210 (Private) Returns a string representing the current CustomErr instance.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
211
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
212 Returns:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
213 str: A string representing the current CustomErr instance.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
214 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
215 return f"{CustomErr.errName} #{self.id}: {self.msg}, {self.details}."
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
216
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
217 class ArgsErr(CustomErr):
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
218 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
219 CustomErr subclass for UI arguments errors.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
220 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
221 errName = "Args Error"
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
222 def __init__(self, argName :str, expected :Any, actual :Any, msg = "no further details provided") -> None:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
223 super().__init__(f"argument \"{argName}\" expected {expected} but got {actual}", msg)
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
224
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
225 class DataErr(CustomErr):
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
226 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
227 CustomErr subclass for data formatting errors.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
228 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
229 errName = "Data Format Error"
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
230 def __init__(self, fileName :str, msg = "no further details provided") -> None:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
231 super().__init__(f"file \"{fileName}\" contains malformed data", msg)
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
232
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
233 class PathErr(CustomErr):
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
234 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
235 CustomErr subclass for filepath formatting errors.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
236 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
237 errName = "Path Error"
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
238 def __init__(self, path :FilePath, msg = "no further details provided") -> None:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
239 super().__init__(f"path \"{path}\" is invalid", msg)
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
240
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
241 class ValueErr(CustomErr):
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
242 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
243 CustomErr subclass for any value error.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
244 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
245 errName = "Value Error"
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
246 def __init__(self, valueName: str, expected :Any, actual :Any, msg = "no further details provided") -> None:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
247 super().__init__("value " + f"\"{valueName}\" " * bool(valueName) + f"was supposed to be {expected}, but got {actual} instead", msg)
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
248
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
249 # RESULT
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
250 T = TypeVar('T')
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
251 E = TypeVar('E', bound = CustomErr) # should bind to Result.ResultErr but python happened!
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
252 class Result(Generic[T, E]):
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
253 class ResultErr(CustomErr):
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
254 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
255 CustomErr subclass for all Result errors.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
256 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
257 errName = "Result Error"
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
258 def __init__(self, msg = "no further details provided") -> None:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
259 super().__init__(msg)
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
260 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
261 Class to handle the result of an operation, with a value and a boolean flag to indicate
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
262 whether the operation was successful or not.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
263 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
264 def __init__(self, value :Union[T, E], isOk :bool) -> None:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
265 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
266 (Private) Initializes an instance of Result.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
267
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
268 Args:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
269 value (Union[T, E]): The value to be stored in the Result instance.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
270 isOk (bool): A boolean flag to indicate whether the operation was successful or not.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
271
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
272 Returns:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
273 None : practically, a Result instance.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
274 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
275 self.isOk = isOk
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
276 self.isErr = not isOk
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
277 self.value = value
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
278
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
279 @classmethod
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
280 def Ok(cls, value :T) -> "Result":
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
281 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
282 Constructs a new Result instance with a successful operation.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
283
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
284 Args:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
285 value (T): The value to be stored in the Result instance, set as successful.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
286
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
287 Returns:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
288 Result: A new Result instance with a successful operation.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
289 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
290 return Result(value, isOk = True)
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
291
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
292 @classmethod
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
293 def Err(cls, value :E) -> "Result":
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
294 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
295 Constructs a new Result instance with a failed operation.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
296
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
297 Args:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
298 value (E): The value to be stored in the Result instance, set as failed.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
299
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
300 Returns:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
301 Result: A new Result instance with a failed operation.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
302 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
303 return Result(value, isOk = False)
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
304
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
305 def unwrap(self) -> T:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
306 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
307 Unwraps the value of the Result instance, if the operation was successful.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
308
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
309 Raises:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
310 ResultErr: If the operation was not successful.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
311
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
312 Returns:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
313 T: The value of the Result instance, if the operation was successful.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
314 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
315 if self.isOk: return self.value
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
316 raise Result.ResultErr(f"Unwrapped Result.Err : {self.value}")
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
317
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
318 def unwrapOr(self, default :T) -> T:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
319 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
320 Unwraps the value of the Result instance, if the operation was successful, otherwise
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
321 it returns a default value.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
322
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
323 Args:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
324 default (T): The default value to be returned if the operation was not successful.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
325
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
326 Returns:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
327 T: The value of the Result instance, if the operation was successful,
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
328 otherwise the default value.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
329 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
330 return self.value if self.isOk else default
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
331
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
332 def expect(self, err :"Result.ResultErr") -> T:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
333 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
334 Expects that the value of the Result instance is successful, otherwise it raises an error.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
335
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
336 Args:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
337 err (Exception): The error to be raised if the operation was not successful.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
338
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
339 Raises:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
340 err: The error raised if the operation was not successful.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
341
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
342 Returns:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
343 T: The value of the Result instance, if the operation was successful.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
344 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
345 if self.isOk: return self.value
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
346 raise err
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
347
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
348 U = TypeVar("U")
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
349 def map(self, mapper: Callable[[T], U]) -> "Result[U, E]":
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
350 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
351 Maps the value of the current Result to whatever is returned by the mapper function.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
352 If the Result contained an unsuccessful operation to begin with it remains unchanged
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
353 (a reference to the current instance is returned).
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
354 If the mapper function panics the returned result instance will be of the error kind.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
355
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
356 Args:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
357 mapper (Callable[[T], U]): The mapper operation to be applied to the Result value.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
358
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
359 Returns:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
360 Result[U, E]: The result of the mapper operation applied to the Result value.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
361 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
362 if self.isErr: return self
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
363 try: return Result.Ok(mapper(self.value))
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
364 except Exception as e: return Result.Err(e)
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
365
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
366 D = TypeVar("D", bound = "Result.ResultErr")
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
367 def mapErr(self, mapper :Callable[[E], D]) -> "Result[T, D]":
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
368 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
369 Maps the error of the current Result to whatever is returned by the mapper function.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
370 If the Result contained a successful operation it remains unchanged
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
371 (a reference to the current instance is returned).
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
372 If the mapper function panics this method does as well.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
373
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
374 Args:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
375 mapper (Callable[[E], D]): The mapper operation to be applied to the Result error.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
376
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
377 Returns:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
378 Result[U, E]: The result of the mapper operation applied to the Result error.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
379 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
380 if self.isOk: return self
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
381 return Result.Err(mapper(self.value))
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
382
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
383 def __str__(self):
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
384 return f"Result::{'Ok' if self.isOk else 'Err'}({self.value})"
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
385
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
386 # FILES
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
387 def read_dataset(path :FilePath, datasetName = "Dataset (not actual file name!)") -> pd.DataFrame:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
388 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
389 Reads a .csv or .tsv file and returns it as a Pandas DataFrame.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
390
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
391 Args:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
392 path : the path to the dataset file.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
393 datasetName : the name of the dataset.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
394
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
395 Raises:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
396 DataErr: If anything goes wrong when trying to open the file, if pandas thinks the dataset is empty or if
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
397 it has less than 2 columns.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
398
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
399 Returns:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
400 pandas.DataFrame: The dataset loaded as a Pandas DataFrame.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
401 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
402 # I advise against the use of this function. This is an attempt at standardizing bad legacy code rather than
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
403 # removing / replacing it to avoid introducing as many bugs as possible in the tools still relying on this code.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
404 # First off, this is not the best way to distinguish between .csv and .tsv files and Galaxy itself makes it really
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
405 # hard to implement anything better. Also, this function's name advertizes it as a dataset-specific operation and
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
406 # contains dubious responsibility (how many columns..) while being a file-opening function instead. My suggestion is
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
407 # TODO: stop using dataframes ever at all in anything and find a way to have tight control over file extensions.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
408 try: dataset = pd.read_csv(path.show(), sep = '\t', header = None, engine = "python")
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
409 except:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
410 try: dataset = pd.read_csv(path.show(), sep = ',', header = 0, engine = "python")
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
411 except Exception as err: raise DataErr(datasetName, f"encountered empty or wrongly formatted data: {err}")
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
412
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
413 if len(dataset.columns) < 2: raise DataErr(datasetName, "a dataset is always meant to have at least 2 columns")
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
414 return dataset
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
415
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
416 def readPickle(path :FilePath) -> Any:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
417 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
418 Reads the contents of a .pickle file, which needs to exist at the given path.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
419
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
420 Args:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
421 path : the path to the .pickle file.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
422
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
423 Returns:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
424 Any : the data inside a pickle file, could be anything.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
425 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
426 with open(path.show(), "rb") as fd: return pickle.load(fd)
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
427
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
428 def writePickle(path :FilePath, data :Any) -> None:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
429 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
430 Saves any data in a .pickle file, created at the given path.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
431
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
432 Args:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
433 path : the path to the .pickle file.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
434 data : the data to be written to the file.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
435
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
436 Returns:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
437 None
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
438 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
439 with open(path.show(), "wb") as fd: pickle.dump(data, fd)
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
440
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
441 def readCsv(path :FilePath, delimiter = ',', *, skipHeader = True) -> List[List[str]]:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
442 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
443 Reads the contents of a .csv file, which needs to exist at the given path.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
444
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
445 Args:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
446 path : the path to the .csv file.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
447 delimiter : allows other subformats such as .tsv to be opened by the same method (\\t delimiter).
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
448 skipHeader : whether the first row of the file is a header and should be skipped.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
449
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
450 Returns:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
451 List[List[str]] : list of rows from the file, each parsed as a list of strings originally separated by commas.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
452 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
453 with open(path.show(), "r", newline = "") as fd: return list(csv.reader(fd, delimiter = delimiter))[skipHeader:]
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
454
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
455 def readSvg(path :FilePath, customErr :Optional[Exception] = None) -> ET.ElementTree:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
456 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
457 Reads the contents of a .svg file, which needs to exist at the given path.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
458
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
459 Args:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
460 path : the path to the .svg file.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
461
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
462 Raises:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
463 DataErr : if the map is malformed.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
464
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
465 Returns:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
466 Any : the data inside a svg file, could be anything.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
467 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
468 try: return ET.parse(path.show())
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
469 except (ET.XMLSyntaxError, ET.XMLSchemaParseError) as err:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
470 raise customErr if customErr else err
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
471
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
472 def writeSvg(path :FilePath, data:ET.ElementTree) -> None:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
473 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
474 Saves svg data opened with lxml.etree in a .svg file, created at the given path.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
475
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
476 Args:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
477 path : the path to the .svg file.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
478 data : the data to be written to the file.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
479
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
480 Returns:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
481 None
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
482 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
483 with open(path.show(), "wb") as fd: fd.write(ET.tostring(data))
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
484
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
485 # UI ARGUMENTS
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
486 class Bool:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
487 def __init__(self, argName :str) -> None:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
488 self.argName = argName
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
489
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
490 def __call__(self, s :str) -> bool: return self.check(s)
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
491
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
492 def check(self, s :str) -> bool:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
493 s = s.lower()
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
494 if s == "true" : return True
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
495 if s == "false": return False
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
496 raise ArgsErr(self.argName, "boolean string (true or false, not case sensitive)", f"\"{s}\"")
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
497
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
498 class Float:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
499 def __init__(self, argName = "Dataset values, not an argument") -> None:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
500 self.argName = argName
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
501
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
502 def __call__(self, s :str) -> float: return self.check(s)
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
503
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
504 def check(self, s :str) -> float:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
505 try: return float(s)
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
506 except ValueError:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
507 s = s.lower()
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
508 if s == "nan" or s == "none": return math.nan
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
509 raise ArgsErr(self.argName, "numeric string or \"None\" or \"NaN\" (not case sensitive)", f"\"{s}\"")
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
510
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
511 # MODELS
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
512 OldRule = List[Union[str, "OldRule"]]
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
513 class Model(Enum):
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
514 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
515 Represents a metabolic model, either custom or locally supported. Custom models don't point
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
516 to valid file paths.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
517 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
518
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
519 Recon = "Recon"
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
520 ENGRO2 = "ENGRO2"
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
521 ENGRO2_no_legend = "ENGRO2_no_legend"
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
522 HMRcore = "HMRcore"
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
523 HMRcore_no_legend = "HMRcore_no_legend"
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
524 Custom = "Custom" # Exists as a valid variant in the UI, but doesn't point to valid file paths.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
525
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
526 def __raiseMissingPathErr(self, path :Optional[FilePath]) -> None:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
527 if not path: raise PathErr("<<MISSING>>", "it's necessary to provide a custom path when retrieving files from a custom model")
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
528
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
529 def getRules(self, toolDir :str, customPath :Optional[FilePath] = None) -> Dict[str, Dict[str, OldRule]]:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
530 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
531 Open "rules" file for this model.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
532
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
533 Returns:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
534 Dict[str, Dict[str, OldRule]] : the rules for this model.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
535 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
536 path = customPath if self is Model.Custom else FilePath(f"{self.name}_rules", FileFormat.PICKLE, prefix = f"{toolDir}/local/pickle files/")
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
537 self.__raiseMissingPathErr(path)
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
538 return readPickle(path)
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
539
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
540 def getTranslator(self, toolDir :str, customPath :Optional[FilePath] = None) -> Dict[str, Dict[str, str]]:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
541 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
542 Open "gene translator (old: gene_in_rule)" file for this model.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
543
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
544 Returns:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
545 Dict[str, Dict[str, str]] : the translator dict for this model.
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
546 """
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
547 path = customPath if self is Model.Custom else FilePath(f"{self.name}_genes", FileFormat.PICKLE, prefix = f"{toolDir}/local/pickle files/")
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
548 self.__raiseMissingPathErr(path)
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
549 return readPickle(path)
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
550
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
551 def getMap(self, toolDir = ".", customPath :Optional[FilePath] = None) -> ET.ElementTree:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
552 path = customPath if self is Model.Custom else FilePath(f"{self.name}_map", FileFormat.SVG, prefix = f"{toolDir}/local/svg metabolic maps/")
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
553 self.__raiseMissingPathErr(path)
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
554 return readSvg(path, customErr = DataErr(path, f"custom map in wrong format"))
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
555
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
556 def getCOBRAmodel(self, toolDir = ".", customPath :Optional[FilePath] = None, customExtension :Optional[FilePath]=None)->cobra.Model:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
557 if(self is Model.Custom):
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
558 return self.load_custom_model(customPath, customExtension)
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
559 else:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
560 return cobra.io.read_sbml_model(FilePath(f"{self.name}", FileFormat.XML, prefix = f"{toolDir}/local/models/").show())
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
561
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
562 def load_custom_model(self, file_path :FilePath, ext :Optional[FileFormat] = None) -> cobra.Model:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
563 ext = ext if ext else file_path.ext
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
564 try:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
565 if ext is FileFormat.XML:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
566 return cobra.io.read_sbml_model(file_path.show())
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
567
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
568 if ext is FileFormat.JSON:
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
569 return cobra.io.load_json_model(file_path.show())
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
570
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
571 except Exception as e: raise DataErr(file_path, e.__str__())
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
572 raise DataErr(file_path,
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
573 f"Fomat \"{file_path.ext}\" is not recognized, only JSON and XML files are supported.")
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
574
63f5078627a9 Uploaded
francesco_lapi
parents:
diff changeset
575 def __str__(self) -> str: return self.value