JackyZzZzZ commited on
Commit
2ef7744
·
1 Parent(s): 6c55a4f

Removed duplicate code

Browse files
streamlit_app/pages/{2_MaxSum.py → page_MaxSum.py} RENAMED
@@ -21,32 +21,22 @@
21
  # --
22
 
23
  import streamlit as st
24
- import numpy as np
25
- import pandas as pd
26
- import json
27
  import os
 
28
 
29
- from sklearn.metrics import pairwise_distances
30
  from selector.methods.distance import MaxSum
31
 
32
- # Get the current directory path
33
  current_dir = os.path.dirname(os.path.abspath(__file__))
 
 
34
 
35
- # Construct the path to the assets directory
36
- assets_dir = os.path.join(current_dir, "..", "assets")
37
 
38
- # Set page configuration
39
- st.set_page_config(
40
- page_title="MaxSum",
41
- page_icon=os.path.join(assets_dir, "QC-Devs.png")
42
- )
43
 
44
  st.title("Brute Strength - MaxSum")
45
 
46
- st.sidebar.header("Brute Strength - MaxSum")
47
-
48
- st.sidebar.info(
49
- """
50
  Whereas the goal of the MaxMin algorithm is to maximize the minimum distance between any pair
51
  of distinct elements in the selected subset of a dataset, the MaxSum algorithm aims to maximize
52
  the sum of distances between all pairs of elements in the selected subset. When presented with
@@ -60,16 +50,17 @@ st.sidebar.info(
60
  In the current implementation, this method requires or computes the full pairwise-distance
61
  matrix, so it is not recommended for large datasets.
62
  """
63
- )
64
 
65
- st.sidebar.title("References")
66
 
67
- st.sidebar.info("[1] Borodin, Allan, Hyun Chul Lee, and Yuli Ye, Max-sum diversification, "
68
- "monotone submodular functions and dynamic updates, Proceedings of the 31st ACM "
69
- "SIGMOD-SIGACT-SIGAI symposium on Principles of Database Systems. 2012.")
 
 
70
 
71
  # File uploader for feature matrix or distance matrix (required)
72
- matrix_file = st.file_uploader("Upload a feature matrix or distance matrix (required)", type=["csv", "xlsx", "npz", "npy"], key="matrix_file")
 
73
 
74
  # Clear selected indices if a new matrix file is uploaded
75
  if matrix_file is None:
@@ -77,87 +68,15 @@ if matrix_file is None:
77
 
78
  # Load data from matrix file
79
  else:
80
- try:
81
- header_option = None
82
- if matrix_file.name.endswith(".csv") or matrix_file.name.endswith(".xlsx"):
83
- header_option = st.checkbox("Does the file have a header?", key = "header_option")
84
- st.warning("Warning: This will affect the final output if not specified correctly.")
85
-
86
- if matrix_file.name.endswith(".csv") or matrix_file.name.endswith(".xlsx"):
87
- if header_option:
88
- # Load the matrix with header
89
- matrix = pd.read_csv(matrix_file).values
90
- else:
91
- # Load the matrix without header
92
- matrix = pd.read_csv(matrix_file, header = None).values
93
- st.write("Matrix shape:", matrix.shape)
94
- st.write(matrix)
95
-
96
- elif matrix_file.name.endswith(".npz"):
97
- matrix_data = np.load(matrix_file)
98
- # Select the array in the .npz file
99
- array_names = matrix_data.files
100
- selected_array = st.selectbox("Select the array to use", array_names)
101
- matrix = matrix_data[selected_array]
102
- st.write("Matrix shape:", matrix.shape)
103
- st.write(matrix)
104
- elif matrix_file.name.endswith(".npy"):
105
- matrix = np.load(matrix_file)
106
- st.write("Matrix shape:", matrix.shape)
107
- st.write(matrix)
108
- except Exception as e:
109
- st.error(f'An error occurred while loading matrix file: {e}')
110
- matrix = None
111
-
112
-
113
- # Input for number of points to select (required)
114
- num_points = st.number_input("Number of points to select", min_value=1, step=1, key="num_points")
115
-
116
- # Input for cluster label list (optional)
117
- label_file = st.file_uploader("Upload a cluster label list (optional)", type=["csv", "xlsx"], key="label_file")
118
- labels = None
119
- if label_file is not None:
120
- try:
121
- label_header_option = None
122
- if label_file.name.endswith(".csv") or label_file.name.endswith(".xlsx"):
123
- label_header_option = st.checkbox("Does the file have a header?",
124
- key = "label_header_option")
125
- st.warning(
126
- "Warning: This will affect the final output if not specified correctly.")
127
-
128
- if label_file.name.endswith(".csv") or label_file.name.endswith(".xlsx"):
129
- if label_header_option:
130
- labels = pd.read_csv(label_file).values.flatten()
131
- else:
132
- labels = pd.read_csv(label_file, header = None).values.flatten()
133
- st.write("Cluster labels shape:", labels.shape)
134
- st.write(labels)
135
- except Exception as e:
136
- st.error(f'An error occurred while loading cluster label file: {e}')
137
- labels = None
138
-
139
 
140
  if st.button("Run MaxSum Algorithm"):
141
- try:
142
- # Check if the input matrix is a feature matrix or a distance matrix
143
- if matrix.shape[0] == matrix.shape[1]:
144
- # Distance matrix
145
- selector = MaxSum()
146
- selected_ids = selector.select(matrix, size = num_points, labels = labels)
147
- else:
148
- # Feature matrix
149
- selector = MaxSum(lambda x: pairwise_distances(x, metric = "euclidean"))
150
- selected_ids = selector.select(matrix, size = num_points, labels = labels)
151
-
152
- # Convert selected indices to a list of integers
153
- selected_ids = [int(i) for i in selected_ids]
154
-
155
- # Save selected indices to session state
156
- st.session_state['selected_ids'] = selected_ids
157
- except ValueError as ve:
158
- st.error(f"An error occurred while running the MaxMin algorithm: {ve}")
159
- except Exception as e:
160
- st.error(f"An error occurred while running the MaxMin algorithm: {e}")
161
 
162
 
163
  # Check if the selected indices are stored in the session state
@@ -165,23 +84,4 @@ if 'selected_ids' in st.session_state and matrix_file is not None:
165
  selected_ids = st.session_state['selected_ids']
166
  st.write("Selected indices:", selected_ids)
167
 
168
- # export format
169
- export_format = st.selectbox("Select export format", ["CSV", "JSON"], key="export_format")
170
-
171
- if export_format == "CSV":
172
- csv_data = pd.DataFrame(selected_ids, columns = ["Selected Indices"])
173
- csv = csv_data.to_csv(index = False).encode('utf-8')
174
- st.download_button(
175
- label = "Download as CSV",
176
- data = csv,
177
- file_name = 'selected_indices.csv',
178
- mime = 'text/csv',
179
- )
180
- else:
181
- json_data = json.dumps({"Selected Indices": selected_ids})
182
- st.download_button(
183
- label = "Download as JSON",
184
- data = json_data,
185
- file_name = 'selected_indices.json',
186
- mime = 'application/json',
187
- )
 
21
  # --
22
 
23
  import streamlit as st
 
 
 
24
  import os
25
+ import sys
26
 
 
27
  from selector.methods.distance import MaxSum
28
 
29
+ # Add the streamlit_app directory to the Python path
30
  current_dir = os.path.dirname(os.path.abspath(__file__))
31
+ parent_dir = os.path.join(current_dir, "..")
32
+ sys.path.append(parent_dir)
33
 
34
+ from utils import display_sidebar_info, load_matrix, load_labels, run_algorithm, export_results
 
35
 
 
 
 
 
 
36
 
37
  st.title("Brute Strength - MaxSum")
38
 
39
+ description = """
 
 
 
40
  Whereas the goal of the MaxMin algorithm is to maximize the minimum distance between any pair
41
  of distinct elements in the selected subset of a dataset, the MaxSum algorithm aims to maximize
42
  the sum of distances between all pairs of elements in the selected subset. When presented with
 
50
  In the current implementation, this method requires or computes the full pairwise-distance
51
  matrix, so it is not recommended for large datasets.
52
  """
 
53
 
 
54
 
55
+ references = "[1] Borodin, Allan, Hyun Chul Lee, and Yuli Ye, Max-sum diversification, "\
56
+ "monotone submodular functions and dynamic updates, Proceedings of the 31st ACM "\
57
+ "SIGMOD-SIGACT-SIGAI symposium on Principles of Database Systems. 2012."
58
+
59
+ display_sidebar_info("Brute Strength - MaxSum", description, references)
60
 
61
  # File uploader for feature matrix or distance matrix (required)
62
+ matrix_file = st.file_uploader("Upload a feature matrix or distance matrix (required)",
63
+ type=["csv", "xlsx", "npz", "npy"], key="matrix_file")
64
 
65
  # Clear selected indices if a new matrix file is uploaded
66
  if matrix_file is None:
 
68
 
69
  # Load data from matrix file
70
  else:
71
+ matrix = load_matrix(matrix_file)
72
+ num_points = st.number_input("Number of points to select", min_value = 1, step = 1,
73
+ key = "num_points")
74
+ label_file = st.file_uploader("Upload a cluster label list (optional)", type = ["csv", "xlsx"],
75
+ key = "label_file")
76
+ labels = load_labels(label_file) if label_file else None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
 
78
  if st.button("Run MaxSum Algorithm"):
79
+ selected_ids = run_algorithm(MaxSum, matrix, num_points, labels)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
 
82
  # Check if the selected indices are stored in the session state
 
84
  selected_ids = st.session_state['selected_ids']
85
  st.write("Selected indices:", selected_ids)
86
 
87
+ export_results(selected_ids)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
streamlit_app/pages/page_maxmin.py CHANGED
@@ -21,32 +21,21 @@
21
  # --
22
 
23
  import streamlit as st
24
- import numpy as np
25
- import pandas as pd
26
- import json
27
  import os
 
28
 
29
- from sklearn.metrics import pairwise_distances
30
  from selector.methods.distance import MaxMin
31
 
32
- # Get the current directory path
33
  current_dir = os.path.dirname(os.path.abspath(__file__))
 
 
34
 
35
- # Construct the path to the assets directory
36
- assets_dir = os.path.join(current_dir, "..", "assets")
37
-
38
- # Set page configuration
39
- st.set_page_config(
40
- page_title="MaxMin",
41
- page_icon=os.path.join(assets_dir, "QC-Devs.png")
42
- )
43
 
44
  st.title("Brute Strength - MaxMin")
45
 
46
- st.sidebar.header("Brute Strength - MaxMin")
47
-
48
- st.sidebar.info(
49
- """
50
  MaxMin is possibly the most widely used method for dissimilarity-based
51
  compound selection. When presented with a dataset of samples, the
52
  initial point is chosen as the dataset's medoid center. Next, the second
@@ -61,127 +50,37 @@ st.sidebar.info(
61
  In the current implementation, this method requires or computes the full pairwise-distance
62
  matrix, so it is not recommended for large datasets.
63
  """
64
- )
65
 
66
- st.sidebar.title("References")
67
 
68
- st.sidebar.info("[1] Ashton, Mark, et al., Identification of diverse database subsets using "
69
- "property‐based and fragment‐based molecular descriptions, "
70
- "Quantitative Structure‐Activity Relationships 21.6 (2002): 598-604.")
71
 
 
72
 
73
  # File uploader for feature matrix or distance matrix (required)
74
- matrix_file = st.file_uploader("Upload a feature matrix or distance matrix (required)", type=["csv", "xlsx", "npz", "npy"], key="matrix_file")
 
75
 
76
  # Clear selected indices if a new matrix file is uploaded
77
  if matrix_file is None:
78
  st.session_state.pop("selected_ids", None)
79
  # Load data from matrix file
80
  else:
81
- try:
82
- header_option = None
83
- if matrix_file.name.endswith(".csv") or matrix_file.name.endswith(".xlsx"):
84
- header_option = st.checkbox("Does the file have a header?", key = "header_option")
85
- st.warning("Warning: This will affect the final output if not specified correctly.")
86
-
87
- if matrix_file.name.endswith(".csv") or matrix_file.name.endswith(".xlsx"):
88
- if header_option:
89
- # Load the matrix with header
90
- matrix = pd.read_csv(matrix_file).values
91
- else:
92
- # Load the matrix without header
93
- matrix = pd.read_csv(matrix_file, header = None).values
94
- st.write("Matrix shape:", matrix.shape)
95
- st.write(matrix)
96
-
97
- elif matrix_file.name.endswith(".npz"):
98
- matrix_data = np.load(matrix_file)
99
- # Select the array in the .npz file
100
- array_names = matrix_data.files
101
- selected_array = st.selectbox("Select the array to use", array_names)
102
- matrix = matrix_data[selected_array]
103
- st.write("Matrix shape:", matrix.shape)
104
- st.write(matrix)
105
- elif matrix_file.name.endswith(".npy"):
106
- matrix = np.load(matrix_file)
107
- st.write("Matrix shape:", matrix.shape)
108
- st.write(matrix)
109
- except Exception as e:
110
- st.error(f'An error occurred while loading matrix file: {e}')
111
- matrix = None
112
-
113
-
114
- # Input for number of points to select (required)
115
- num_points = st.number_input("Number of points to select", min_value=1, step=1, key="num_points")
116
-
117
- # Input for cluster label list (optional)
118
- label_file = st.file_uploader("Upload a cluster label list (optional)", type=["csv", "xlsx"], key="label_file")
119
- labels = None
120
- if label_file:
121
- try:
122
- label_header_option = None
123
- if label_file.name.endswith(".csv") or label_file.name.endswith(".xlsx"):
124
- label_header_option = st.checkbox("Does the file have a header?",
125
- key = "label_header_option")
126
- st.warning(
127
- "Warning: This will affect the final output if not specified correctly.")
128
-
129
- if label_file.name.endswith(".csv") or label_file.name.endswith(".xlsx"):
130
- if label_header_option:
131
- labels = pd.read_csv(label_file).values.flatten()
132
- else:
133
- labels = pd.read_csv(label_file, header = None).values.flatten()
134
- st.write("Cluster labels shape:", labels.shape)
135
- st.write(labels)
136
- except Exception as e:
137
- st.error(f'An error occurred while loading cluster label file: {e}')
138
- labels = None
139
-
140
 
141
  if st.button("Run MaxMin Algorithm"):
142
- try:
143
- # Check if the input matrix is a feature matrix or a distance matrix
144
- if matrix.shape[0] == matrix.shape[1]:
145
- # Distance matrix
146
- selector = MaxMin()
147
- selected_ids = selector.select(matrix, size = num_points, labels = labels)
148
- else:
149
- # Feature matrix
150
- selector = MaxMin(lambda x: pairwise_distances(x, metric = "euclidean"))
151
- selected_ids = selector.select(matrix, size = num_points, labels = labels)
152
-
153
- # Convert selected indices to a list of integers
154
- selected_ids = [int(i) for i in selected_ids]
155
-
156
- # Save selected indices to session state
157
- st.session_state['selected_ids'] = selected_ids
158
- except ValueError as ve:
159
- st.error(f"An error occurred while running the MaxMin algorithm: {ve}")
160
- except Exception as e:
161
- st.error(f"An error occurred while running the MaxMin algorithm: {e}")
162
 
163
  # Check if the selected indices are stored in the session state
164
  if 'selected_ids' in st.session_state and matrix_file is not None:
165
  selected_ids = st.session_state['selected_ids']
166
  st.write("Selected indices:", selected_ids)
167
 
168
- # export format
169
- export_format = st.selectbox("Select export format", ["CSV", "JSON"], key="export_format")
170
-
171
- if export_format == "CSV":
172
- csv_data = pd.DataFrame(selected_ids, columns = ["Selected Indices"])
173
- csv = csv_data.to_csv(index = False).encode('utf-8')
174
- st.download_button(
175
- label = "Download as CSV",
176
- data = csv,
177
- file_name = 'selected_indices.csv',
178
- mime = 'text/csv',
179
- )
180
- else:
181
- json_data = json.dumps({"Selected Indices": selected_ids})
182
- st.download_button(
183
- label = "Download as JSON",
184
- data = json_data,
185
- file_name = 'selected_indices.json',
186
- mime = 'application/json',
187
- )
 
21
  # --
22
 
23
  import streamlit as st
 
 
 
24
  import os
25
+ import sys
26
 
 
27
  from selector.methods.distance import MaxMin
28
 
29
+ # Add the streamlit_app directory to the Python path
30
  current_dir = os.path.dirname(os.path.abspath(__file__))
31
+ parent_dir = os.path.join(current_dir, "..")
32
+ sys.path.append(parent_dir)
33
 
34
+ from utils import display_sidebar_info, load_matrix, load_labels, run_algorithm, export_results
 
 
 
 
 
 
 
35
 
36
  st.title("Brute Strength - MaxMin")
37
 
38
+ description = """
 
 
 
39
  MaxMin is possibly the most widely used method for dissimilarity-based
40
  compound selection. When presented with a dataset of samples, the
41
  initial point is chosen as the dataset's medoid center. Next, the second
 
50
  In the current implementation, this method requires or computes the full pairwise-distance
51
  matrix, so it is not recommended for large datasets.
52
  """
 
53
 
 
54
 
55
+ references = "[1] Ashton, Mark, et al., Identification of diverse database subsets using "\
56
+ "property‐based and fragment‐based molecular descriptions, "\
57
+ "Quantitative Structure‐Activity Relationships 21.6 (2002): 598-604."
58
 
59
+ display_sidebar_info("Brute Strength - MaxMin", description, references)
60
 
61
  # File uploader for feature matrix or distance matrix (required)
62
+ matrix_file = st.file_uploader("Upload a feature matrix or distance matrix (required)",
63
+ type=["csv", "xlsx", "npz", "npy"], key="matrix_file")
64
 
65
  # Clear selected indices if a new matrix file is uploaded
66
  if matrix_file is None:
67
  st.session_state.pop("selected_ids", None)
68
  # Load data from matrix file
69
  else:
70
+ matrix = load_matrix(matrix_file)
71
+ num_points = st.number_input("Number of points to select", min_value = 1, step = 1,
72
+ key = "num_points")
73
+ label_file = st.file_uploader("Upload a cluster label list (optional)", type = ["csv", "xlsx"],
74
+ key = "label_file")
75
+ labels = load_labels(label_file) if label_file else None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
 
77
  if st.button("Run MaxMin Algorithm"):
78
+ selected_ids = run_algorithm(MaxMin, matrix, num_points, labels)
79
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
  # Check if the selected indices are stored in the session state
82
  if 'selected_ids' in st.session_state and matrix_file is not None:
83
  selected_ids = st.session_state['selected_ids']
84
  st.write("Selected indices:", selected_ids)
85
 
86
+ export_results(selected_ids)