1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
//! # Execute a set of optimization tasks in parallel on a single shared memory device.
//!
//! This function is used to execute a set of optimization tasks in parallel on a single
//! shared memory device. A `Task` is defined as a call to `optimize` and a set of
//! tasks is expected to be a list of at least length 1 where at least one task is
//! the unpermuted optimization and the rest are permutations which will be used to
//! calculate the empirical p-value of the unpermuted optimization.
use Clone;
use ;
use crateRankedFeatureList;
use crateOptimizationResult;
use crateoptimize;
use crateTask;
/// Executes multiple tasks for dual threshold optimization in parallel.
///
/// This function distributes tasks across a specified number of threads, leveraging
/// multithreading for efficient parallel execution of the `optimize`
/// function. Each thread processes a chunk of tasks, and the results are aggregated
/// and returned as a single vector.
///
/// # Arguments
/// - `tasks`: A vector of `Task` objects defining the parameters for each optimization.
/// - `ranked_feature_list1`: The first `RankedFeatureList` for the optimization.
/// - `ranked_feature_list2`: The second `RankedFeatureList` for the optimization.
/// - `background`: An optional `FeatureList` defining the background population. If absent,
/// the two ranked lists must have identical genes.
/// - `num_threads`: The number of threads to use for parallel processing.
///
/// # Returns
/// A `Vec<OptimizationResult>` containing the results for all tasks.
///
/// # Panics
/// - If the number of tasks is smaller than the number of threads.
/// - If a thread fails to complete execution.
///
/// # Implementation Details
/// - The `tasks` vector is divided into chunks, and each thread processes one chunk.
/// - The `ranked_feature_list1`, `ranked_feature_list2`, and `background` are cloned for each thread.
/// - Results are stored in a thread-safe `Arc<Mutex<Vec<OptimizationResult>>>` to avoid race conditions.
///
/// # Examples
/// ```rust
/// use dual_threshold_optimization::run::{run_single_node, Task};
/// use dual_threshold_optimization::collections::{FeatureList, RankedFeatureList, Feature};
/// use dual_threshold_optimization::dto::OptimizationResult;
///
/// // Define RankedFeatureLists and background
/// let ranked_feature_list1 = RankedFeatureList::from(
/// FeatureList::from(vec![Feature::from("gene1"), Feature::from("gene2"), Feature::from("gene3")]),
/// vec![1, 2, 3],
/// ).unwrap();
///
/// let ranked_feature_list2 = RankedFeatureList::from(
/// FeatureList::from(vec![Feature::from("gene1"), Feature::from("gene2"), Feature::from("gene4")]),
/// vec![1, 2, 3],
/// ).unwrap();
///
/// let population_size: usize = 4;
///
/// // Define tasks
/// let tasks: Vec<Task> = vec![
/// Task { id: 1, permute: true }, // Replace with actual task definitions
/// Task { id: 2, permute: true },
/// ];
///
/// // Run with 2 threads
/// let results = run_single_node(tasks, ranked_feature_list1, ranked_feature_list2, population_size, 2);
///
/// // Check results
/// assert_eq!(results.len(), 2);
/// for result in results {
/// match result {
/// OptimizationResult::Debug(_) => println!("Debug results returned."),
/// OptimizationResult::Best(best) => println!(
/// "Best result: Rank1 {}, Rank2 {}, p-value {}",
/// best.rank1, best.rank2, best.pvalue
/// ),
/// }
/// }
/// ```
// The following was a previous implementation of the run_single_node function
// which did not use the Arc<Mutex<Vec<OptimizationResult>>> for thread-safe
// access to the rankedlists and background. kept for comparison purposes
// pub fn run(
// tasks: Vec<Task>,
// ranked_feature_list1: RankedFeatureList,
// ranked_feature_list2: RankedFeatureList,
// background: Option<FeatureList>,
// num_threads: usize,
// ) -> Vec<OptimizationResult> {
// // Split the tasks into chunks and ensure ownership is transferred
// let task_chunks: Vec<Vec<Task>> = tasks
// .chunks(tasks.len() / num_threads)
// .map(|chunk| chunk.to_vec())
// .collect();
// let results = Arc::new(Mutex::new(Vec::new()));
// let handles: Vec<_> = task_chunks
// .into_iter()
// .map(|chunk| {
// let ranked_feature_list1 = ranked_feature_list1.clone();
// let ranked_feature_list2 = ranked_feature_list2.clone();
// let background = background.clone();
// let results = Arc::clone(&results);
// std::thread::spawn(move || {
// let mut local_results = Vec::new();
// for _ in chunk {
// let result = optimize(
// &ranked_feature_list1,
// &ranked_feature_list2,
// true,
// background.as_ref(),
// false,
// );
// local_results.push(result);
// }
// results.lock().unwrap().extend(local_results);
// })
// })
// .collect();
// for handle in handles {
// handle.join().unwrap();
// }
// Arc::try_unwrap(results).unwrap().into_inner().unwrap()
// }