public int Bin()
{
if (parameters.predefinedBinsFile == null)
{
throw new ApplicationException("Predefined bins in BED is required for fragment binning.");
}
if (!parameters.isPairedEnd) // Janus-SRS-189
{
throw new ApplicationException("Paired-end reads are required for fragment binning.");
}
Dictionary<string, List<GenomicBin>> predefinedBins = Utilities.LoadBedFile(parameters.predefinedBinsFile, gcIndex: 3);
List<string> chromosomes = GetChromosomesInBam(); // used to order chromosomes
if (!Utilities.IsSubset(predefinedBins.Keys, chromosomes))
{
throw new ApplicationException(
String.Format("Not all chromosomes in {0} are found in {1}.", parameters.predefinedBinsFile, parameters.bamFile));
}
// Count fragments by chromosome
List<ThreadStart> binningThreads = new List<ThreadStart>();
List<BinTask> tasks = new List<BinTask>();
foreach (string chrom in chromosomes)
{
if (!predefinedBins.ContainsKey(chrom)) { continue; }
BinTask task = new BinTask(parameters.referenceFile, chrom, parameters.bamFile, predefinedBins[chrom]);
tasks.Add(task);
binningThreads.Add(new ThreadStart(() => { task.DoIt(); }));
}
Console.WriteLine("Launch fragment binning jobs...");
Console.Out.WriteLine();
Parallel.ForEach(binningThreads, t => { t.Invoke(); });
Console.WriteLine("Completed fragment binning jobs.");
Console.Out.WriteLine();
long usableFragmentCount = tasks.Select(t => t.UsableFragmentCount).Sum();
if (usableFragmentCount == 0)
{
throw new ApplicationException(String.Format("No passing-filter fragments overlapping bins are found in {0}", parameters.bamFile));
}
// Aggregate bins
List<GenomicBin> finalBins = new List<GenomicBin>();
foreach (string chrom in chromosomes)
{
if (!predefinedBins.ContainsKey(chrom)) { continue; }
finalBins.AddRange(predefinedBins[chrom]);
}
// Output!
CanvasIO.WriteToTextFile(parameters.outFile, finalBins);
return 0;
}