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
// Copyright 2023 WHERE TRUE Technologies.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::sync::Arc;

use datafusion::{
    common::tree_node::Transformed,
    datasource::listing::PartitionedFile,
    error::Result,
    physical_optimizer::PhysicalOptimizerRule,
    physical_plan::{
        coalesce_partitions::CoalescePartitionsExec, repartition::RepartitionExec,
        with_new_children_if_necessary, ExecutionPlan, Partitioning,
    },
};

use itertools::Itertools;

use crate::datasources::{
    bam::{BAMScan, IndexedBAMScan},
    bed::BEDScan,
    fasta::FASTAScan,
    fastq::FASTQScan,
    gff::GFFScan,
    gtf::GTFScan,
    hmmdomtab::HMMDomTabScan,
    sam::SAMScan,
    vcf::{IndexedVCFScanner, VCFScan},
};

#[cfg(feature = "fcs")]
use crate::datasources::fcs::FCSScan;

#[cfg(feature = "genbank")]
use crate::datasources::genbank::GenbankScan;

#[cfg(feature = "mzml")]
use crate::datasources::mzml::MzMLScan;

type FilePartitions = Vec<Vec<PartitionedFile>>;

/// Regroup the file partition into a new set of file partitions of the target size.
pub(crate) fn regroup_files_by_size(
    file_partitions: &FilePartitions,
    target_group_size: usize,
) -> FilePartitions {
    let flattened_files = file_partitions
        .iter()
        .flatten()
        .cloned()
        .collect::<Vec<_>>()
        .into_iter()
        .sorted_by_key(|f| f.object_meta.size)
        .collect::<Vec<_>>();

    let target_partitions = std::cmp::min(target_group_size, flattened_files.len());
    let mut new_file_groups = Vec::new();

    // Add empty file groups to the new file groups equal to the number of target partitions.
    for _ in 0..target_partitions {
        new_file_groups.push(Vec::new());
    }

    // Work through the flattened files and add them to the new file groups.
    for (i, file) in flattened_files.iter().enumerate() {
        let target_partition = i % target_partitions;
        new_file_groups[target_partition].push(file.clone());
    }

    new_file_groups
}

macro_rules! transform_plan {
    ($new_scan:expr, $target_partitions:expr, $config:expr) => {{
        let partitioning = Partitioning::RoundRobinBatch($target_partitions);

        let repartition = RepartitionExec::try_new($new_scan.clone(), partitioning)?;
        let coalesce_partitions = CoalescePartitionsExec::new(Arc::new(repartition));

        Ok(Transformed::Yes(Arc::new(coalesce_partitions)))
    }};
}

fn optimize_file_partitions(
    plan: Arc<dyn ExecutionPlan>,
    target_partitions: usize,
    config: &datafusion::config::ConfigOptions,
) -> Result<Transformed<Arc<dyn ExecutionPlan>>> {
    if target_partitions == 1 {
        return Ok(Transformed::No(plan));
    }

    let new_plan = if plan.children().is_empty() {
        Transformed::No(plan) // no children, i.e. leaf
    } else {
        let children = plan
            .children()
            .iter()
            .map(|child| {
                optimize_file_partitions(child.clone(), target_partitions, config)
                    .map(Transformed::into)
            })
            .collect::<Result<_>>()?;

        with_new_children_if_necessary(plan, children)?
    };

    let (new_plan, _transformed) = new_plan.into_pair();

    if let Some(bed_scan) = new_plan.as_any().downcast_ref::<BEDScan>() {
        let new_scan = bed_scan.get_repartitioned(target_partitions);
        let coalesce_partition_exec = CoalescePartitionsExec::new(Arc::new(new_scan));

        return Ok(Transformed::Yes(Arc::new(coalesce_partition_exec)));
    }

    if let Some(scan) = new_plan.as_any().downcast_ref::<FASTAScan>() {
        match scan.repartitioned(target_partitions, config)? {
            Some(new_scan) => {
                return transform_plan!(new_scan, target_partitions, config);
            }
            None => {
                return Ok(Transformed::No(new_plan));
            }
        }
    }

    if let Some(indexed_vcf_scan) = new_plan.as_any().downcast_ref::<IndexedVCFScanner>() {
        match indexed_vcf_scan.repartitioned(target_partitions, config)? {
            Some(new_scan) => {
                return transform_plan!(new_scan, target_partitions, config);
            }
            None => {
                return Ok(Transformed::No(new_plan));
            }
        }
    }

    if let Some(fastq_scan) = new_plan.as_any().downcast_ref::<FASTQScan>() {
        let new_scan = fastq_scan.get_repartitioned(target_partitions);
        let coalesce_partition_exec = CoalescePartitionsExec::new(Arc::new(new_scan));

        return Ok(Transformed::Yes(Arc::new(coalesce_partition_exec)));
    }

    if let Some(vcf_scan) = new_plan.as_any().downcast_ref::<VCFScan>() {
        let new_scan = vcf_scan.get_repartitioned(target_partitions);
        let coalesce_partition_exec = CoalescePartitionsExec::new(Arc::new(new_scan));

        return Ok(Transformed::Yes(Arc::new(coalesce_partition_exec)));
    }

    if let Some(bam_scan) = new_plan.as_any().downcast_ref::<BAMScan>() {
        let new_scan = bam_scan.get_repartitioned(target_partitions);
        let coalesce_partition_exec = CoalescePartitionsExec::new(Arc::new(new_scan));

        return Ok(Transformed::Yes(Arc::new(coalesce_partition_exec)));
    }

    if let Some(indexed_bam_scan) = new_plan.as_any().downcast_ref::<IndexedBAMScan>() {
        let new_scan = indexed_bam_scan.get_repartitioned(target_partitions);
        let coalesce_partition_exec = CoalescePartitionsExec::new(Arc::new(new_scan));

        return Ok(Transformed::Yes(Arc::new(coalesce_partition_exec)));
    }

    if let Some(sam_scan) = new_plan.as_any().downcast_ref::<SAMScan>() {
        let new_scan = sam_scan.get_repartitioned(target_partitions);
        let coalesce_partition_exec = CoalescePartitionsExec::new(Arc::new(new_scan));

        return Ok(Transformed::Yes(Arc::new(coalesce_partition_exec)));
    }

    #[cfg(feature = "fcs")]
    if let Some(fcs_scan) = new_plan.as_any().downcast_ref::<FCSScan>() {
        let new_scan = fcs_scan.get_repartitioned(target_partitions);
        let coalesce_partition_exec = CoalescePartitionsExec::new(Arc::new(new_scan));

        return Ok(Transformed::Yes(Arc::new(coalesce_partition_exec)));
    }

    #[cfg(feature = "genbank")]
    if let Some(genbank_scan) = new_plan.as_any().downcast_ref::<GenbankScan>() {
        let new_scan = genbank_scan.get_repartitioned(target_partitions);
        let coalesce_partition_exec = CoalescePartitionsExec::new(Arc::new(new_scan));

        return Ok(Transformed::Yes(Arc::new(coalesce_partition_exec)));
    }

    if let Some(gff_scan) = new_plan.as_any().downcast_ref::<GFFScan>() {
        let new_scan = gff_scan.get_repartitioned(target_partitions);
        let coalesce_partition_exec = CoalescePartitionsExec::new(Arc::new(new_scan));

        return Ok(Transformed::Yes(Arc::new(coalesce_partition_exec)));
    }

    if let Some(gtf_scan) = new_plan.as_any().downcast_ref::<GTFScan>() {
        let new_scan = gtf_scan.get_repartitioned(target_partitions);
        let coalesce_partition_exec = CoalescePartitionsExec::new(Arc::new(new_scan));

        return Ok(Transformed::Yes(Arc::new(coalesce_partition_exec)));
    }

    if let Some(hmm_scan) = new_plan.as_any().downcast_ref::<HMMDomTabScan>() {
        let new_scan = hmm_scan.get_repartitioned(target_partitions);
        let coalesce_partition_exec = CoalescePartitionsExec::new(Arc::new(new_scan));

        return Ok(Transformed::Yes(Arc::new(coalesce_partition_exec)));
    }

    #[cfg(feature = "mzml")]
    if let Some(mzml_scan) = new_plan.as_any().downcast_ref::<MzMLScan>() {
        let new_scan = mzml_scan.get_repartitioned(target_partitions);
        let coalesce_partition_exec = CoalescePartitionsExec::new(Arc::new(new_scan));

        return Ok(Transformed::Yes(Arc::new(coalesce_partition_exec)));
    }

    Ok(Transformed::No(new_plan))
}

/// Optimizer rule that repartitions the file partitions of a plan into a new set of file partitions.
///
/// This is useful for when you have a large number of files and want to reduce the number of partitions
/// so they can be processed in parallel.
#[derive(Default)]
pub struct ExonRoundRobin {}

impl PhysicalOptimizerRule for ExonRoundRobin {
    fn optimize(
        &self,
        plan: std::sync::Arc<dyn datafusion::physical_plan::ExecutionPlan>,
        config: &datafusion::config::ConfigOptions,
    ) -> datafusion::error::Result<std::sync::Arc<dyn datafusion::physical_plan::ExecutionPlan>>
    {
        let repartition_file_scans = config.optimizer.repartition_file_scans;
        let target_partitions = config.execution.target_partitions;

        let plan = if !repartition_file_scans || target_partitions == 1 {
            Transformed::No(plan)
        } else {
            optimize_file_partitions(plan, target_partitions, config)?
        };

        let (plan, _transformed) = plan.into_pair();

        Ok(plan)
    }

    fn name(&self) -> &str {
        "exon_round_robin"
    }

    fn schema_check(&self) -> bool {
        true
    }
}