annotate COBRAxy/utils/general_utils.py @ 183:e7150fbbf428 draft

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