PineBioML 1.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,158 @@
1
+ from typing import Union
2
+ from pandas import read_csv, read_excel, read_table, concat, Series, DataFrame
3
+ from numpy import ones
4
+ import joblib
5
+ import os
6
+
7
+
8
+ def read_file(
9
+ file_path: str,
10
+ index_col: Union[int,
11
+ str] = None) -> Union[DataFrame, dict[str, DataFrame]]:
12
+ """
13
+ Read files, which supports common data format .csv, .tsv, .xlsx and R-table in .txt format.
14
+ Notice that while an excel file has several data sheet, this function will return a python dict with corresponding sheet name as dict keys.
15
+
16
+ Args:
17
+ file_path (str): The path of target file.
18
+ index_col (Union[int, str], optional): The column index or name to set as the index of dataframe. Set None to ignore. Defaults to None.
19
+
20
+ Returns:
21
+ Union[DataFrame, dict[str, DataFrame]]: While the target file is an excel with more than one data sheet, it will return a dict consisting of the data sheets.
22
+ """
23
+
24
+ # sparse csv, tsv or excel
25
+ file_type = file_path.split(".")[-1]
26
+ if file_type == "csv":
27
+ file = read_csv(file_path, index_col=index_col)
28
+ elif file_type == "tsv":
29
+ file_a = read_csv(file_path, sep=" ", index_col=index_col)
30
+ file_b = read_csv(file_path, sep="\t", index_col=index_col)
31
+ if file_a.isna().mean().mean() > file_b.isna().mean().mean():
32
+ file = file_b
33
+ else:
34
+ file = file_a
35
+
36
+ elif file_type in ["xls", "xlsx", "xlsm", "xlsb"]:
37
+ file = read_excel(file_path, sheet_name=None, index_col=index_col)
38
+ if len(file) == 1:
39
+ file = file[list(file.keys())[0]]
40
+
41
+ elif file_type == "txt":
42
+ file = read_table(file_path, index_col=index_col)
43
+ else:
44
+ raise NotImplementedError(
45
+ "The type of target file is not supported. Must be one of .csv, .tsv, .xls, .xlsx or R table in .txt format."
46
+ )
47
+ return file
48
+
49
+
50
+ def read_multiple_groups(
51
+ file_path_list: list[str],
52
+ transpose: bool = False,
53
+ index_col: Union[int, str] = None) -> tuple[DataFrame, Series]:
54
+ """
55
+
56
+ read_multiple_groups will do:
57
+ 1. read files in
58
+ 2. assign y according to the read-in order
59
+ 3. concatenate all datas in row
60
+ It sould be used while the data was sperated into different files by their class or some kind of property we interested in.
61
+
62
+ Args:
63
+ file_path_list (list[str]): A list of path to target files.
64
+ transpose (bool, optional): Transpose before concatenating. Defaults to False.
65
+ index_col (Union[int, str], optional): The column index or name to set as the index of dataframe. Set None to ignore. Defaults to None.
66
+
67
+ Returns:
68
+ tuple[DataFrame, Series]: A tuple (x, y) where x is the stacking of target files, and y is an array of integer which records each row's source in the order of file_path_list.
69
+ """
70
+
71
+ # 1. read files in
72
+ datas = []
73
+ group_label = []
74
+ label = 0
75
+ for path in file_path_list:
76
+ group = read_file(path, index_col)
77
+ if transpose:
78
+ group = group.T
79
+
80
+ datas.append(group)
81
+ # 2. assign y according to the read-in order
82
+ group_label.append(
83
+ Series(ones(group.shape[0]) * label, index=group.index))
84
+ label += 1
85
+
86
+ # 3. concatenate all the datas in row
87
+ x = concat(datas, axis=0)
88
+ y = concat(group_label, axis=0)
89
+
90
+ if not len(set(y.index)) == len(y.index):
91
+ # if index repeats, drop them all.
92
+ x = x.reset_index(drop=True)
93
+ y = y.reset_index(drop=True)
94
+
95
+ return x, y
96
+
97
+
98
+ def save_model(model_obj: object,
99
+ save_path: str,
100
+ save_name: str,
101
+ overide: bool = False) -> None:
102
+ """
103
+ Saving the model_obj by joblib in pickle format to the path: save_path/save_name .
104
+ If overide, then overide while any file with the same save_name has already existed in the save_path.
105
+
106
+ Args:
107
+ model_obj (object): The model or pipeline to be saved.
108
+ save_path (str): The path to to save the model_obj.
109
+ save_name (str): the saving filename.
110
+ overide (bool, optional): True for overidind any file with save_name in save_path. Defaults to False.
111
+ """
112
+ if not save_path[-1] == "/":
113
+ save_path = save_path + "/"
114
+
115
+ if not os.path.exists(save_path):
116
+ print(save_path, " does not exist yet. we will try to create it.")
117
+ os.makedirs(save_path)
118
+
119
+ if os.path.exists(save_path + save_name):
120
+ print(save_name, " has already exist in ", save_path)
121
+ if overide:
122
+ print("It will be overide.")
123
+ joblib.dump(model_obj, save_path + save_name)
124
+ else:
125
+ print(
126
+ "please choose another model save_name or set overide to True which will replace the existing one"
127
+ )
128
+ else:
129
+ joblib.dump(model_obj, save_path + save_name)
130
+
131
+
132
+ def load_model(save_path: str, save_name: str = None) -> object:
133
+ """
134
+ Load a saved model.
135
+
136
+ If save_name was provided, load_model will try to access save_path/save_name .
137
+ else save_path will be regarded as save_path/save_name (lazy mode).
138
+
139
+ For example, a model saved as "./output/model/best_model"
140
+ load_model("./output/model/", "best_model")
141
+ load_model("./output/model/best_model")
142
+ have exact the same result.
143
+
144
+ Args:
145
+ save_path (str): The path to folder where the model saved.
146
+ save_name (str, optional): The name of target model. Defaults to None.
147
+
148
+ Returns:
149
+ object: An python object that was saved in previous. DO NOT TRUST UNKNOWN SOURCE PICKLE FILES.
150
+ """
151
+ if not save_name is None:
152
+ if not save_path[-1] == "/":
153
+ save_path = save_path + "/"
154
+
155
+ return joblib.load(save_path + save_name)
156
+ else:
157
+ # lazy mode
158
+ return joblib.load(save_path)
PineBioML/__init__.py ADDED
File without changes
File without changes